π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(augmentation): remove stale operation probability sampler (#4678)
NiteeshGowda72237011b726c4
diff --git a/changelog.d/4678.fixed.md b/changelog.d/4678.fixed.mdnew file mode 100644index 000000000..9984f1cd2--- /dev/null+++ b/changelog.d/4678.fixed.md@@ -0,0 +1 @@+`OperationBase` can now be deep-copied after augmentation operations have been used without retaining stale probability sampler state.diff --git a/kornia/augmentation/auto/operations/base.py b/kornia/augmentation/auto/operations/base.pyindex 4b705ddfe..d09452355 100644--- a/kornia/augmentation/auto/operations/base.py+++ b/kornia/augmentation/auto/operations/base.py@@ -15,11 +15,10 @@# limitations under the License.#-from typing import Callable, Dict, List, Optional, Self, Tuple, TypeVar+from typing import Callable, Dict, List, Optional, Tuple, TypeVarimport torchfrom torch import nn-from torch.distributions import Bernoulli, RelaxedBernoullifrom kornia.augmentation.base import _AugmentationBase@@ -35,7 +34,7 @@ class OperationBase(nn.Module):The magnitude parameter name shall align with the attribute inside the random_generatorin each augmentation. If None, the augmentation will be randomly applied according tothe augmentation sampling range.- temperature: temperature for RelaxedBernoulli distribution used during training.+ temperature: retained for API compatibility.is_batch_operation: determine if to obtain the probability from `p` or `p_batch`.Set to True for most non-shape-persistent operations (e.g. cropping).@@ -87,7 +86,7 @@ class OperationBase(nn.Module):self._init_magnitude(initial_magnitude)- # Avoid skipping the sampling in `__batch_prob_generator__`+ # Keep the legacy probability state for API and checkpoint compatibility.self.probability_range = (1e-7, 1 - 1e-7)self._is_batch_operation = is_batch_operationif is_batch_operation:@@ -147,37 +146,6 @@ class OperationBase(nn.Module):if initial_magnitude[0][1] is not None:self._magnitude = nn.Parameter(torch.empty(1).fill_(initial_magnitude[0][1]))- def _update_probability_gen(self, relaxation: bool) -> None:- if relaxation:- if self._is_batch_operation:- self.op._p_batch_gen = RelaxedBernoulli(self.temperature, self.probability)- else:- self.op._p_gen = RelaxedBernoulli(self.temperature, self.probability)- elif self._is_batch_operation:- self.op._p_batch_gen = Bernoulli(self.probability)- else:- self.op._p_gen = Bernoulli(self.probability)-- def train(self, mode: bool = True) -> Self:- """Switch training mode and refresh probability samplers.-- Args:- mode: ``True`` for training mode, ``False`` for evaluation mode.-- Returns:- This module.- """- self._update_probability_gen(relaxation=mode)- return super().train(mode=mode)-- def eval(self) -> Self:- """Switch to evaluation mode.-- Returns:- This module.- """- return self.train(False)-def forward_parameters(self, batch_shape: torch.Size, mag: Optional[torch.Tensor] = None) -> Dict[str, torch.Tensor]:@@ -194,7 +162,6 @@ class OperationBase(nn.Module):if mag is None:mag = self.magnitude- self._update_probability_gen(relaxation=True)params = self.op.forward_parameters(batch_shape)if mag is not None:diff --git a/kornia/augmentation/auto/operations/ops.py b/kornia/augmentation/auto/operations/ops.pyindex ddcd16f3c..8f49e31a7 100644--- a/kornia/augmentation/auto/operations/ops.py+++ b/kornia/augmentation/auto/operations/ops.py@@ -51,7 +51,7 @@ class AutoContrast(OperationBase):Args:initial_probability: the initial probability. If None, the augmentation will be randomlyapplied according to he augmentation sampling range.- temperature: temperature for RelaxedBernoulli distribution used during training.+ temperature: retained for API compatibility.symmetric_megnitude: if to randomly assign the magnitude as negative or not."""@@ -75,7 +75,7 @@ class Brightness(OperationBase):applied according to he augmentation sampling range.initial_magnitude: the initial magnitude.magnitude_range: the sampling range for random sampling and clamping the optimized magnitude.- temperature: temperature for RelaxedBernoulli distribution used during training.+ temperature: retained for API compatibility.symmetric_megnitude: if to randomly assign the magnitude as negative or not."""@@ -104,7 +104,7 @@ class Contrast(OperationBase):applied according to he augmentation sampling range.initial_magnitude: the initial magnitude.magnitude_range: the sampling range for random sampling and clamping the optimized magnitude.- temperature: temperature for RelaxedBernoulli distribution used during training.+ temperature: retained for API compatibility.symmetric_megnitude: if to randomly assign the magnitude as negative or not."""@@ -133,7 +133,7 @@ class Hue(OperationBase):applied according to he augmentation sampling range.initial_magnitude: the initial magnitude.magnitude_range: the sampling range for random sampling and clamping the optimized magnitude.- temperature: temperature for RelaxedBernoulli distribution used during training.+ temperature: retained for API compatibility.symmetric_megnitude: if to randomly assign the magnitude as negative or not."""@@ -162,7 +162,7 @@ class Saturate(OperationBase):applied according to he augmentation sampling range.initial_magnitude: the initial magnitude.magnitude_range: the sampling range for random sampling and clamping the optimized magnitude.- temperature: temperature for RelaxedBernoulli distribution used during training.+ temperature: retained for API compatibility.symmetric_megnitude: if to randomly assign the magnitude as negative or not."""@@ -190,7 +190,7 @@ class Equalize(OperationBase):Args:initial_probability: the initial probability. If None, the augmentation will be randomlyapplied according to he augmentation sampling range.- temperature: temperature for RelaxedBernoulli distribution used during training.+ temperature: retained for API compatibility.Note:Equalize cannot update probabilities yet.@@ -212,7 +212,7 @@ class Gray(OperationBase):Args:initial_probability: the initial probability. If None, the augmentation will be randomlyapplied according to he augmentation sampling range.- temperature: temperature for RelaxedBernoulli distribution used during training.+ temperature: retained for API compatibility."""@@ -231,7 +231,7 @@ class Invert(OperationBase):Args:initial_probability: the initial probability. If None, the augmentation will be randomlyapplied according to he augmentation sampling range.- temperature: temperature for RelaxedBernoulli distribution used during training.+ temperature: retained for API compatibility."""@@ -252,7 +252,7 @@ class Posterize(OperationBase):initial_probability: the initial probability. If None, the augmentation will be randomlyapplied according to he augmentation sampling range.magnitude_range: the sampling range for random sampling and clamping the optimized magnitude.- temperature: temperature for RelaxedBernoulli distribution used during training.+ temperature: retained for API compatibility.symmetric_megnitude: if to randomly assign the magnitude as negative or not."""@@ -287,7 +287,7 @@ class Solarize(OperationBase):applied according to he augmentation sampling range.magnitude_range: the sampling range for random sampling and clamping the optimizedsymmetric_megnitude: if to randomly assign the magnitude as negative or not.magnitude.- temperature: temperature for RelaxedBernoulli distribution used during training.+ temperature: retained for API compatibility."""@@ -315,7 +315,7 @@ class SolarizeAdd(OperationBase):initial_probability: the initial probability. If None, the augmentation will be randomlyapplied according to he augmentation sampling range.magnitude_range: the sampling range for random sampling and clamping the optimized magnitude.- temperature: temperature for RelaxedBernoulli distribution used during training.+ temperature: retained for API compatibility.symmetric_megnitude: if to randomly assign the magnitude as negative or not."""@@ -344,7 +344,7 @@ class Sharpness(OperationBase):initial_probability: the initial probability. If None, the augmentation will be randomlyapplied according to he augmentation sampling range.magnitude_range: the sampling range for random sampling and clamping the optimized magnitude.- temperature: temperature for RelaxedBernoulli distribution used during training.+ temperature: retained for API compatibility.symmetric_megnitude: if to randomly assign the magnitude as negative or not."""@@ -371,7 +371,7 @@ class HorizontalFlip(OperationBase):Args:initial_probability: the initial probability. If None, the augmentation will be randomlyapplied according to he augmentation sampling range.- temperature: temperature for RelaxedBernoulli distribution used during training.+ temperature: retained for API compatibility."""@@ -389,7 +389,7 @@ class VerticalFlip(OperationBase):Args:initial_magnitude: the initial magnitude.- temperature: temperature for RelaxedBernoulli distribution used during training.+ temperature: retained for API compatibility."""@@ -410,7 +410,7 @@ class Rotate(OperationBase):initial_probability: the initial probability. If None, the augmentation will be randomlyapplied according to he augmentation sampling range.magnitude_range: the sampling range for random sampling and clamping the optimized magnitude.- temperature: temperature for RelaxedBernoulli distribution used during training.+ temperature: retained for API compatibility.symmetric_megnitude: if to randomly assign the magnitude as negative or not."""@@ -444,7 +444,7 @@ class ShearX(OperationBase):initial_probability: the initial probability. If None, the augmentation will be randomlyapplied according to he augmentation sampling range.magnitude_range: the sampling range for random sampling and clamping the optimized magnitude.- temperature: temperature for RelaxedBernoulli distribution used during training.+ temperature: retained for API compatibility.symmetric_megnitude: if to randomly assign the magnitude as negative or not."""@@ -484,7 +484,7 @@ class ShearY(OperationBase):initial_probability: the initial probability. If None, the augmentation will be randomlyapplied according to he augmentation sampling range.magnitude_range: the sampling range for random sampling and clamping the optimized magnitude.- temperature: temperature for RelaxedBernoulli distribution used during training.+ temperature: retained for API compatibility.symmetric_megnitude: if to randomly assign the magnitude as negative or not."""@@ -529,7 +529,7 @@ class TranslateX(OperationBase):initial_probability: the initial probability. If None, the augmentation will be randomlyapplied according to he augmentation sampling range.magnitude_range: the sampling range for random sampling and clamping the optimized magnitude.- temperature: temperature for RelaxedBernoulli distribution used during training.+ temperature: retained for API compatibility.symmetric_megnitude: if to randomly assign the magnitude as negative or not."""@@ -563,7 +563,7 @@ class TranslateY(OperationBase):initial_probability: the initial probability. If None, the augmentation will be randomlyapplied according to he augmentation sampling range.magnitude_range: the sampling range for random sampling and clamping the optimized magnitude.- temperature: temperature for RelaxedBernoulli distribution used during training.+ temperature: retained for API compatibility.symmetric_megnitude: if to randomly assign the magnitude as negative or not."""diff --git a/tests/augmentation/test_auto_operation.py b/tests/augmentation/test_auto_operation.pyindex 2c8b83ea5..c085796c8 100644--- a/tests/augmentation/test_auto_operation.py+++ b/tests/augmentation/test_auto_operation.py@@ -403,3 +403,41 @@ def test_inverse_without_a_forward_pass_still_reports_missing_params(device, dtyx = torch.rand(2, 3, 8, 6, device=device, dtype=dtype)with pytest.raises(ValueError, match="No parameters available"):RandAugment(n=1, m=5).inverse(x)+++def test_operation_base_deepcopy_after_use() -> None:+ operation = ops.Brightness()+ state_dict = operation.state_dict()++ assert isinstance(operation._probability, torch.nn.Parameter)+ assert isinstance(operation.probability, torch.Tensor)+ assert operation.probability.item() == operation.op.p+ assert hasattr(operation, "temperature")+ assert "_probability" in state_dict+ assert "temperature" in state_dict++ restored = ops.Brightness()+ restored.load_state_dict(state_dict, strict=True)++ assert restored.probability.item() == operation.probability.item()+ assert torch.equal(restored.temperature, operation.temperature)++ x = torch.rand(2, 3, 32, 32)++ cases = [+ (RandAugment(n=2, m=15), "forward"),+ (AutoAugment(), "train"),+ (AutoAugment(), "eval"),+ (TrivialAugment(), "train"),+ (AugmentationSequential(RandAugment(n=2, m=15)), "forward"),+ ]++ for aug, action in cases:+ if action == "forward":+ aug(x)+ elif action == "train":+ aug.train()+ else:+ aug.eval()++ copy.deepcopy(aug)