🐍 Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
Make use of composition for augmentation multiprocessing friendliness (#2637)
João Gustavo A. Amorimb0dda96beef6
diff --git a/kornia/augmentation/random_generator/base.py b/kornia/augmentation/random_generator/base.pyindex ab8c44716..3cffbd77e 100644--- a/kornia/augmentation/random_generator/base.py+++ b/kornia/augmentation/random_generator/base.py@@ -1,8 +1,9 @@-from typing import Any, Callable, Dict, Optional, Tuple, Type, TypeVar, Union+from typing import Any, Callable, Dict, Optional, Tuple, Type, TypeVarimport torchfrom torch.distributions import Distribution, Uniform+from kornia.augmentation.utils.helpers import MultiprocessWrapperfrom kornia.core import Device, Module, TensorT = TypeVar('T')@@ -109,15 +110,5 @@ class DistributionWithMapper(Distribution):return getattr(self.dist, attr)-class UniformDistribution(Uniform):+class UniformDistribution(MultiprocessWrapper, Uniform):"""Wrapper around torch Uniform distribution which makes it work with the 'spawn' multiprocessing context."""-- def __init__(self, low: Union[Tensor, float], high: Union[Tensor, float], validate_args: Optional[bool] = None):- if isinstance(low, torch.Tensor):- low = low.clone()- if isinstance(high, torch.Tensor):- high = high.clone()- # we could clone self.low and self.high after the init but given the- # tensors are broadcast in the init this would mean copying more data- # which would be slower- super().__init__(low, high, validate_args)diff --git a/kornia/augmentation/utils/helpers.py b/kornia/augmentation/utils/helpers.pyindex 79fe6151d..136cc532e 100644--- a/kornia/augmentation/utils/helpers.py+++ b/kornia/augmentation/utils/helpers.py@@ -380,3 +380,14 @@ def preprocess_classes(input: Tensor) -> Tensor:"""Preprocess input class tags."""# TODO: We may allow list here.return input+++class MultiprocessWrapper:+ """Utility class which when used as a base class, makes the class work with the 'spawn' multiprocessing+ context."""++ def __init__(self, *args: Any, **kwargs: Any) -> None:+ args = tuple(arg.clone() if isinstance(arg, torch.Tensor) else arg for arg in args)+ kwargs = {key: val.clone() if isinstance(val, torch.Tensor) else val for key, val in kwargs.items()}++ super().__init__(*args, **kwargs)