π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(augmentation): make OperationBase soft blend independent of wrapped p (#5460)
NiteeshGowda7228cbdd8b6fc0
diff --git a/changelog.d/5460.fixed.md b/changelog.d/5460.fixed.mdnew file mode 100644index 000000000..e6e7a14ea--- /dev/null+++ b/changelog.d/5460.fixed.md@@ -0,0 +1 @@+`OperationBase` now applies soft `batch_prob` blending independently of the wrapped augmentation's `p` or `p_batch`, so replayed fractional probabilities produce consistent results (#4809).diff --git a/kornia/augmentation/auto/operations/base.py b/kornia/augmentation/auto/operations/base.pyindex 8ea9a6069..e009d2628 100644--- a/kornia/augmentation/auto/operations/base.py+++ b/kornia/augmentation/auto/operations/base.py@@ -45,10 +45,10 @@ class OperationBase(nn.Module):``p`` and ``p_batch`` as a hard ``0`` or ``1``. ``magnitude``, where the operation has one, is clamped tothe wrapped generator's range and receives a gradient where the wrapped augmentation is differentiablein it; ``forward_parameters`` substitutes it into the wrapped augmentation's draw.- - ``forward`` linearly blends the wrapped output with the input using ``batch_prob``. Unless the wrapped- ``p`` and ``p_batch`` are both ``1``, the wrapped augmentation first keeps rows whose gate is at most- ``0.5`` unchanged, so the same supplied fractional gates replay differently depending on ``p``- (`#4809 <https://github.com/kornia/kornia/issues/4809>`_).+ - ``forward`` linearly blends the wrapped output with the input using ``batch_prob``. The wrapped+ augmentation transforms every row whose gate is above ``0``, so the same supplied fractional+ ``batch_prob`` produces the same soft blend whatever the wrapped ``p`` or ``p_batch``. Below ``p = 1`` the+ wrapped augmentation skips a row with gate ``0``, so that row's matrix stays the identity.- a symmetric magnitude applies the magnitude mapping first and then a random sign per row, so a mappingthat quantizes to zero stays zero (``Posterize`` maps ``0.5`` to ``0`` bits with ``magnitude_range=(0, 8)``).- the concrete classes in ``kornia.augmentation.auto.operations.ops`` wrap public 2D augmentations and@@ -164,7 +164,7 @@ class OperationBase(nn.Module):return paramsdef forward(self, input: torch.Tensor, params: Optional[Dict[str, torch.Tensor]] = None) -> torch.Tensor:- """Apply the operation with probabilistic gating.+ """Apply the operation with soft probabilistic blending.Args:input: Input tensor.@@ -173,8 +173,7 @@ class OperationBase(nn.Module):Returns:Tensor blended with the wrapped augmentation's output according to- ``batch_prob``. The wrapped augmentation's own gate runs before this- blend, as described in the class's Convention block.+ ``batch_prob``."""if params is None:params = self.forward_parameters(input.shape)@@ -183,7 +182,13 @@ class OperationBase(nn.Module):device=input.device, dtype=input.dtype)- return batch_prob * self.op(input, params=params) + (1 - batch_prob) * input+ # The wrapped augmentation transforms every row the blend gives a weight, so a fractional gate is not+ # gated again by its ``p``. A row of weight 0 stays untouched, so its matrix, annotations and cost do not+ # change for the hard 0/1 gates that sampling draws.+ wrapped_params = params.copy()+ wrapped_params["batch_prob"] = (params["batch_prob"] > 0).to(params["batch_prob"].dtype)++ return batch_prob * self.op(input, params=wrapped_params) + (1 - batch_prob) * input@propertydef transform_matrix(self) -> Optional[torch.Tensor]:diff --git a/tests/augmentation/test_conventions_auto.py b/tests/augmentation/test_conventions_auto.pyindex 9d246217d..177e1ba81 100644--- a/tests/augmentation/test_conventions_auto.py+++ b/tests/augmentation/test_conventions_auto.py@@ -20,6 +20,7 @@ from __future__ import annotationsimport pytestimport torch+import kornia.augmentation as Kfrom kornia.augmentation.auto.autoaugment import AutoAugmentfrom kornia.augmentation.auto.operations import PolicySequential, opsfrom kornia.augmentation.auto.rand_augment import RandAugment@@ -286,18 +287,52 @@ class TestAutoAugmentConventions(BaseTester):operation._probability.data.fill_(-1.0)self.assert_close(operation.probability, torch.full_like(operation.probability, 1e-7), rtol=0, atol=0)- @pytest.mark.parametrize(- "probability,expected",- [(1.0, [0.375, 0.5, 0.375, 0.25]), (0.5, [0.25, 0.25, 0.375, 0.25])],- )- def test_wart_operation_soft_blend_depends_on_the_wrapped_p_4809(self, probability, expected, device, dtype):- # #4809: the wrapped p=1 path transforms every row; at p<1 it first keeps gates <=0.5 unchanged, so the- # outer blend cannot mix those rows. One of the two cases flips when the blend stops depending on p.+ @pytest.mark.parametrize("probability", [1.0, 0.99])+ def test_convention_operation_soft_blend_ignores_the_wrapped_p_4809(self, probability, device, dtype):+ # #4809: the soft blend must not depend on the wrapped augmentation's p. The wrapped operation transforms+ # every row with a nonzero gate, while OperationBase applies the supplied fractional batch_prob.invert = ops.Invert(initial_probability=probability)image = torch.tensor([0.25, 0.25, 0.75, 0.75], device=device, dtype=dtype).view(4, 1, 1, 1)params = invert.op.forward_parameters(image.shape)params["batch_prob"] = torch.tensor([0.25, 0.5, 0.75, 1.0])- self.assert_close(invert(image, params=params).flatten(), image.new_tensor(expected))+ self.assert_close(+ invert(image, params=params).flatten(),+ image.new_tensor([0.375, 0.5, 0.375, 0.25]),+ )++ def test_convention_operation_leaves_zero_gate_rows_untransformed_4809(self, device, dtype):+ # #4809: only the rows the blend gives a weight reach a wrapped augmentation with p < 1, so a row with gate 0+ # keeps an identity matrix, as on the image. Passing an all-true gate instead would record the shear for+ # rows 1 and 3 while their pixels stay unchanged.+ operation = ops.ShearX(initial_magnitude=0.3, initial_probability=0.5)+ image = torch.rand(4, 1, 6, 6, device=device, dtype=dtype)+ params = operation.forward_parameters(image.shape)+ params["batch_prob"] = torch.tensor([1.0, 0.0, 0.3, 0.0])+ out = operation(image, params=params)+ self.assert_close(out[1::2], image[1::2], rtol=0, atol=0)+ eye = torch.eye(3, device=device, dtype=operation.transform_matrix.dtype).expand(2, 3, 3)+ self.assert_close(operation.transform_matrix[1::2], eye, rtol=0, atol=0)+ assert not torch.equal(operation.transform_matrix[2], eye[0])++ def test_convention_policy_keypoints_follow_the_gated_image_4809(self, device, dtype):+ # #4809: inside AugmentationSequential the keypoint handler reads the wrapped op's matrix; a row whose image+ # a gate of 0 left unchanged must keep its keypoints too.+ policy = PolicySequential(+ ops.ShearX(initial_magnitude=0.3, initial_probability=0.5),+ ops.TranslateX(initial_magnitude=0.3, initial_probability=0.5),+ )+ aug = K.AugmentationSequential(policy, data_keys=["input", "keypoints"])+ image = torch.linspace(0, 1, 4 * 3 * 8 * 8, device=device, dtype=dtype).view(4, 3, 8, 8)+ keypoints = torch.tensor([[[2.0, 3.0], [5.0, 6.0]]], device=device, dtype=dtype).expand(4, -1, -1)+ untouched_rows = 0+ with torch.random.fork_rng(devices=[device] if device.type == "cuda" else []):+ for seed in range(8):+ torch.manual_seed(seed)+ out_image, out_keypoints = aug(image, keypoints)+ untouched = [i for i in range(4) if torch.equal(out_image[i], image[i])]+ untouched_rows += len(untouched)+ self.assert_close(out_keypoints[untouched], keypoints[untouched])+ assert untouched_rows > 0, "the seeds must leave some row ungated"@pytest.mark.device_agnosticdef test_convention_policy_sequential_samples_through_the_operation_wrapper_4441(self):