Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(augmentation): ignore a hand-made batch_prob consistently at static p=1.0 (#5616)

Muhammad Talha61edcec32375
diff --git a/changelog.d/5616.breaking.md b/changelog.d/5616.breaking.md
new file mode 100644
index 000000000..2cbf49923
--- /dev/null
+++ b/changelog.d/5616.breaking.md
@@ -0,0 +1 @@
+With static p=1.0, p_batch=1.0, a batch_prob put into params is now ignored by every handler, in eager and compiled runs (#5585). The image and transform_matrix already ignored it, but inverse and, for augmentations such as the flips and RandomCrop, the mask, box and keypoint handlers honored it, so a sample it deselected was transformed in forward and left alone by inverse. Pass p < 1 to skip samples by hand.
diff --git a/docs/source/augmentation.base.rst b/docs/source/augmentation.base.rst
index 5edee0e78..3dd519a1c 100644
--- a/docs/source/augmentation.base.rst
+++ b/docs/source/augmentation.base.rst
@@ -212,6 +212,10 @@ to either gate: `RandomMixUpV2` gates the batch and `RandomJigsaw` individual sa
(`#4425 <https://github.com/kornia/kornia/issues/4425>`_). When ``0 < p_batch < 1``, the base draws the batch
Bernoulli before the per-sample gate; endpoints skip that draw, and ``p=1.0, p_batch=0.0`` selects no sample.
+With static ``p=1.0, p_batch=1.0`` every sample is transformed: a ``batch_prob`` put into ``params`` is not consulted
+by the image, the transformation matrix, the labels or ``inverse``, in eager and compiled runs alike
+(`#5585 <https://github.com/kornia/kornia/issues/5585>`_). Pass ``p < 1`` to skip samples by hand.
+
Random Generators
^^^^^^^^^^^^^^^^^
To get an automatically generated ``__repr__`` that lists all custom parameters, implement
diff --git a/docs/source/contrib.rst b/docs/source/contrib.rst
index 7c6375c55..25773be4c 100644
--- a/docs/source/contrib.rst
+++ b/docs/source/contrib.rst
@@ -75,9 +75,9 @@ Interpreting the report
including with ``padding`` or ``pad_if_needed`` (#4473). Manually supplied
parameters that apply a shape-changing operation to only some rows raise
``ValueError``, as the ordinary forward call does, because the skipped rows
- cannot keep their shape (#4497). With ``p=1.0``, an overridden ``batch_prob``
- still gates the labels while every image row is cropped; the round-trip error
- records that inconsistency.
+ cannot keep their shape (#4497). With ``p=1.0, p_batch=1.0``, an overridden
+ ``batch_prob`` is not consulted: every image row is cropped and the labels move
+ with it (#5585). Pass ``p < 1`` to skip rows by hand.
* Non-rigid and unknown operations are explicitly unsupported for matrix
composition. A transformation-matrix identity fallback is not treated as proof
of correspondence. Supported neighboring operations remain in the provenance.
diff --git a/kornia/augmentation/_2d/base.py b/kornia/augmentation/_2d/base.py
index 8b6f4ae1c..37d3be65d 100644
--- a/kornia/augmentation/_2d/base.py
+++ b/kornia/augmentation/_2d/base.py
@@ -99,6 +99,10 @@ class AugmentationBase2D(_AugmentationBase):
caller's dict by reference and, if ``batch_prob`` is absent, inserts an all-true gate into it. Replaying
parameters reproduces the output, except for :class:`RandomDissolving`, whose VAE latents are drawn
during application and are not stored.
+ - with static ``p=1.0, p_batch=1.0`` every sample is transformed: a ``batch_prob`` put into ``params`` is not
+ consulted by the image, the transformation matrix, the labels or ``inverse``, in eager and compiled runs
+ alike (`#5585 <https://github.com/kornia/kornia/issues/5585>`_). Pass ``p < 1`` to skip samples by hand,
+ which every one of those paths honors.
- some ``_param_generator.*`` range buffers in ``state_dict()`` do not update the samplers when loaded
(`#4428 <https://github.com/kornia/kornia/issues/4428>`_).
- an empty batch gives an empty output, except on a minority of classes that raise on ``B = 0``
diff --git a/kornia/augmentation/_2d/geometric/base.py b/kornia/augmentation/_2d/geometric/base.py
index b3fd30b6f..3029b4c8d 100644
--- a/kornia/augmentation/_2d/geometric/base.py
+++ b/kornia/augmentation/_2d/geometric/base.py
@@ -237,8 +237,7 @@ class GeometricAugmentationBase2D(RigidAffineAugmentationBase2D):
"""
in_tensor = self.transform_tensor(input)
output = in_tensor.clone()
- batch_prob = params["batch_prob"]
- to_apply = torch.atleast_1d(batch_prob > 0.5)
+ to_apply = self._gate(params)
params, flags = self._process_kwargs_to_params_and_flags(
self._params if params is None else params, flags, **kwargs
@@ -310,8 +309,7 @@ class GeometricAugmentationBase2D(RigidAffineAugmentationBase2D):
**kwargs: Any,
) -> Boxes:
output = input.clone()
- batch_prob = params["batch_prob"]
- to_apply = torch.atleast_1d(batch_prob > 0.5)
+ to_apply = self._gate(params)
if transform is None:
raise RuntimeError("`transform` has to be a torch.Tensor. Got None.")
@@ -350,8 +348,7 @@ class GeometricAugmentationBase2D(RigidAffineAugmentationBase2D):
"""
output = input.clone()
- batch_prob = params["batch_prob"]
- to_apply = torch.atleast_1d(batch_prob > 0.5)
+ to_apply = self._gate(params)
if transform is None:
raise RuntimeError("`transform` has to be a torch.Tensor. Got None.")
diff --git a/kornia/augmentation/_2d/geometric/crop.py b/kornia/augmentation/_2d/geometric/crop.py
index 93cc96ba4..5537235a1 100644
--- a/kornia/augmentation/_2d/geometric/crop.py
+++ b/kornia/augmentation/_2d/geometric/crop.py
@@ -394,7 +394,7 @@ class RandomCrop(GeometricAugmentationBase2D):
# onto forward_input_shape (the padded canvas), then removes its border below.
transform = transform.clone()
transform[:, :2, 2] += params["padding_size"][:, ::2].to(transform)
- to_apply = torch.atleast_1d(params["batch_prob"] > 0.5)
+ to_apply = self._gate(params)
if not to_apply.any():
return super().inverse_inputs(input, params, flags, transform, **kwargs)
padding_size = params["padding_size"].unique(dim=0).cpu().squeeze().tolist()
diff --git a/kornia/augmentation/_3d/base.py b/kornia/augmentation/_3d/base.py
index 56bd8a8fa..67717e557 100644
--- a/kornia/augmentation/_3d/base.py
+++ b/kornia/augmentation/_3d/base.py
@@ -115,8 +115,7 @@ class RigidAffineAugmentationBase3D(AugmentationBase3D):
self, input: torch.Tensor, params: Dict[str, torch.Tensor], flags: Dict[str, Any]
) -> torch.Tensor:
"""Generate transformation matrices with the given input and param settings."""
- batch_prob = params["batch_prob"]
- to_apply = torch.atleast_1d(batch_prob > 0.5)
+ to_apply = self._gate(params)
in_tensor = self.transform_tensor(input)
diff --git a/kornia/augmentation/base.py b/kornia/augmentation/base.py
index f37861ef9..64c50b56e 100644
--- a/kornia/augmentation/base.py
+++ b/kornia/augmentation/base.py
@@ -409,6 +409,18 @@ class _AugmentationBase(_BasicAugmentationBase):
raise _mixed_gate_shape_error(not_transformed.shape[1:], transformed.shape[1:])
return transformed if apply_any else not_transformed
+ def _gate(self, params: Dict[str, torch.Tensor]) -> torch.Tensor:
+ """Return the per-sample ``to_apply`` mask that the label and ``inverse`` handlers blend with.
+
+ With static ``p == 1`` and ``p_batch == 1`` every sample is transformed, as on the image and matrix fast
+ paths, so a ``batch_prob`` in ``params`` is not consulted (#5585). The decision is static: eager and compiled
+ runs agree, and no handler synchronizes with the device. Skip samples by hand with ``p < 1``.
+ """
+ to_apply = torch.atleast_1d(params["batch_prob"] > 0.5)
+ if self.p == 1.0 and self.p_batch == 1.0:
+ return torch.ones_like(to_apply)
+ return to_apply
+
def transform_inputs(
self,
input: torch.Tensor,
@@ -461,7 +473,7 @@ class _AugmentationBase(_BasicAugmentationBase):
)
batch_prob = params["batch_prob"]
- to_apply = torch.atleast_1d(batch_prob > 0.5)
+ to_apply = self._gate(params)
ori_shape = input.shape
shape = params["forward_input_shape"]
@@ -509,8 +521,7 @@ class _AugmentationBase(_BasicAugmentationBase):
self._params if params is None else params, flags, **kwargs
)
- batch_prob = params["batch_prob"]
- to_apply = torch.atleast_1d(batch_prob > 0.5)
+ to_apply = self._gate(params)
output_transformed = self.apply_transform_box(input, params, flags, transform=transform)
output_not_transformed = self.apply_non_transform_box(input, params, flags, transform=transform)
@@ -546,8 +557,7 @@ class _AugmentationBase(_BasicAugmentationBase):
self._params if params is None else params, flags, **kwargs
)
- batch_prob = params["batch_prob"]
- to_apply = torch.atleast_1d(batch_prob > 0.5)
+ to_apply = self._gate(params)
output_transformed = self.apply_transform_keypoint(input, params, flags, transform=transform)
output_not_transformed = self.apply_non_transform_keypoint(input, params, flags, transform=transform)
@@ -577,8 +587,7 @@ class _AugmentationBase(_BasicAugmentationBase):
self._params if params is None else params, flags, **kwargs
)
- batch_prob = params["batch_prob"]
- to_apply = torch.atleast_1d(batch_prob > 0.5)
+ to_apply = self._gate(params)
output_transformed = self.apply_transform_class(input, params, flags, transform=transform)
output_not_transformed = self.apply_non_transform_class(input, params, flags, transform=transform)
diff --git a/tests/augmentation/container/test_augmentation_sequential.py b/tests/augmentation/container/test_augmentation_sequential.py
index a275b88a2..5cb8661c2 100644
--- a/tests/augmentation/container/test_augmentation_sequential.py
+++ b/tests/augmentation/container/test_augmentation_sequential.py
@@ -1988,7 +1988,7 @@ class TestConventionAugmentationSequential(BaseTester):
labels = [0, 1, 2] if mask_dtype in (torch.bool, torch.uint8) else [257, -2049, 26001]
mask = torch.tensor(labels, device=device, dtype=mask_dtype).reshape(1, 1, 1, 3).repeat(2, 1, 2, 1)
image = torch.ones(2, 1, 2, 3, device=device, dtype=dtype)
- seq = K.AugmentationSequential(K.RandomHorizontalFlip(p=1.0), data_keys=["input", "mask"])
+ seq = K.AugmentationSequential(K.RandomHorizontalFlip(p=0.5), data_keys=["input", "mask"])
seq(image, mask)
params = seq._params
params[0].data["batch_prob"] = torch.tensor([1.0, 0.0], device=device, dtype=dtype)
diff --git a/tests/augmentation/test_augmentation_mix.py b/tests/augmentation/test_augmentation_mix.py
index 3595f5ad1..92daad770 100644
--- a/tests/augmentation/test_augmentation_mix.py
+++ b/tests/augmentation/test_augmentation_mix.py
@@ -696,7 +696,7 @@ class TestRandomMosaic(BaseTester):
image = torch.zeros(2, 1, 6, 8, device=device, dtype=dtype)
xyxy = image.new_tensor([[[1.0, 1.0, 2.0, 2.0]], [[1.0, 1.0, 2.0, 2.0]]])
boxes = Boxes.from_tensor(xyxy)
- aug = FilterBoxes(p=1.0)
+ aug = FilterBoxes(p=0.5)
params = aug.forward_parameters(image.shape)
params["batch_prob"] = image.new_tensor([0.0, 1.0])
output = aug.transform_boxes(boxes, params, aug.flags)
diff --git a/tests/augmentation/test_base.py b/tests/augmentation/test_base.py
index b041bab76..fd5525b68 100644
--- a/tests/augmentation/test_base.py
+++ b/tests/augmentation/test_base.py
@@ -1392,3 +1392,83 @@ class TestEmptyIntensityAugmentation(BaseTester):
assert output.device == device
assert output.dtype == dtype
self.assert_close(output, expected)
+
+
+class TestStaticProbabilityIgnoresHandMadeGate(BaseTester):
+ """With static ``p=1.0, p_batch=1.0`` every handler transforms every sample (#5585).
+
+ A ``batch_prob`` put into ``params`` is not consulted: the image, the matrix, the labels and ``inverse`` agree.
+ """
+
+ @pytest.mark.parametrize("augmentation_cls", [K.RandomHorizontalFlip, K.RandomVerticalFlip])
+ def test_round_trip_restores_the_batch(self, augmentation_cls, device, dtype):
+ x = torch.rand(3, 3, 8, 12, device=device, dtype=dtype)
+ aug = augmentation_cls(p=1.0)
+ params = aug.forward_parameters(x.shape)
+ params["batch_prob"] = torch.tensor([0.0, 1.0, 0.0])
+
+ out = aug(x, params=copy.deepcopy(params))
+
+ assert not torch.equal(out[0], x[0]) # the hand-made gate is not read at p=1
+ self.assert_close(aug.inverse(out, params=copy.deepcopy(params)), x)
+
+ def test_keypoints_and_matrix_follow_the_image(self, device, dtype):
+ x = torch.rand(2, 1, 8, 12, device=device, dtype=dtype)
+ points = torch.tensor([[[2.0, 3.0]], [[2.0, 3.0]]], device=device, dtype=dtype)
+ module = K.RandomHorizontalFlip(p=1.0)
+ aug = K.AugmentationSequential(module, data_keys=["input", "keypoints"])
+ params = module.forward_parameters(x.shape)
+ params["batch_prob"] = torch.tensor([0.0, 1.0])
+
+ out, out_points = aug(x, points, params=[K.container.params.ParamItem("RandomHorizontalFlip_0", params)])
+
+ self.assert_close(out, x.flip(-1))
+ self.assert_close(out_points[..., 0], 11.0 - points[..., 0])
+ self.assert_close(aug.inverse(out, out_points, params=aug._params)[1], points)
+
+ @pytest.mark.parametrize(
+ ("augmentation_cls", "kwargs", "shape"),
+ [
+ pytest.param(K.RandomAffine, {"degrees": 30.0}, (2, 1, 8, 12), id="RandomAffine"),
+ pytest.param(
+ K.RandomCrop,
+ {"size": (8, 12), "padding": (1, 2, 3, 0), "cropping_mode": "resample"},
+ (2, 1, 8, 12),
+ id="RandomCrop-resample",
+ ),
+ pytest.param(K.RandomAffine3D, {"degrees": 30.0}, (2, 1, 4, 6, 6), id="RandomAffine3D"),
+ ],
+ )
+ def test_hand_made_gate_matches_the_sampled_gate(self, augmentation_cls, kwargs, shape, device, dtype):
+ x = torch.rand(*shape, device=device, dtype=dtype)
+ aug = augmentation_cls(p=1.0, **kwargs)
+ params = aug.forward_parameters(x.shape)
+ hand_made = copy.deepcopy(params)
+ hand_made["batch_prob"] = torch.tensor([0.0, 1.0])
+
+ out = aug(x, params=copy.deepcopy(params))
+ matrix = aug.transform_matrix
+
+ self.assert_close(aug(x, params=copy.deepcopy(hand_made)), out)
+ self.assert_close(aug.transform_matrix, matrix)
+ if len(shape) == 4:
+ expected = aug.inverse(out, params=copy.deepcopy(params))
+ self.assert_close(aug.inverse(out, params=copy.deepcopy(hand_made)), expected)
+
+ def test_masks_and_boxes_follow_the_image(self, device, dtype):
+ x = torch.rand(2, 1, 8, 12, device=device, dtype=dtype)
+ mask = (torch.rand(2, 1, 8, 12, device=device) > 0.5).to(dtype)
+ boxes = torch.tensor([[[1.0, 2.0, 4.0, 5.0]], [[1.0, 2.0, 4.0, 5.0]]], device=device, dtype=dtype)
+ module = K.RandomHorizontalFlip(p=1.0)
+ aug = K.AugmentationSequential(module, data_keys=["input", "mask", "bbox_xyxy"])
+ params = module.forward_parameters(x.shape)
+ params["batch_prob"] = torch.tensor([0.0, 1.0])
+
+ out, out_mask, out_boxes = aug(
+ x, mask, boxes, params=[K.container.params.ParamItem("RandomHorizontalFlip_0", params)]
+ )
+
+ self.assert_close(out_mask, mask.flip(-1))
+ _, inv_mask, inv_boxes = aug.inverse(out, out_mask, out_boxes, params=aug._params)
+ self.assert_close(inv_mask, mask)
+ self.assert_close(inv_boxes, boxes)
diff --git a/tests/contrib/test_augmentation_audit.py b/tests/contrib/test_augmentation_audit.py
index 472231fbe..2391a5161 100644
--- a/tests/contrib/test_augmentation_audit.py
+++ b/tests/contrib/test_augmentation_audit.py
@@ -585,17 +585,16 @@ class TestAugmentationAudit(BaseTester):
)
aug = K.AugmentationSequential(module, data_keys=["input", "keypoints", "bbox"])
outputs, report = audit(aug, image, points, boxes, params=[ParamItem("RandomCrop_0", params)])
- selected = (params["batch_prob"] > 0.5).to(device=image.device)
- static = p == 1.0
+ # Static p=1 transforms every row whatever an overridden batch_prob holds (#5585).
+ selected = (params["batch_prob"] > 0.5).to(device=image.device) | (p == 1.0)
# Public matrices include padding; the dynamic gate leaves skipped rows as identity.
public_shift = image.new_tensor([pad[0] - x, pad[2] - y]).expand(2, -1)
- public_shift = torch.where((selected | static)[:, None], public_shift, 0)
+ public_shift = torch.where(selected[:, None], public_shift, 0)
self.assert_close(module.transform_matrix[:, :2, 2], public_shift)
- # An explicitly overridden batch_prob still gates labels even for static p=1.
- label_shift = torch.where(selected[:, None], public_shift, 0)
- self.assert_close(outputs[1], points + label_shift[:, None])
- self.assert_close(outputs[2].data, boxes.data + label_shift[:, None, None])
- transformed = torch.ones_like(selected) if static else selected
+ # Labels follow the same decision as the image and the matrix.
+ self.assert_close(outputs[1], points + public_shift[:, None])
+ self.assert_close(outputs[2].data, boxes.data + public_shift[:, None, None])
+ transformed = selected
padded = torch.nn.functional.pad(image, pad)
expected_images = []
image_shift = image.new_zeros((2, 2))
@@ -612,19 +611,25 @@ class TestAugmentationAudit(BaseTester):
assert report.geometry_status == "available"
diagnostic_dtype = torch.float64 if dtype == torch.float64 else torch.float32
self.assert_close(report.matrix[:, :2, 2], image_shift.to(diagnostic_dtype))
- # Measure against the observed pixel mapping. With static p=1, an overridden
- # batch_prob can still return untransformed labels beside a transformed image.
+ # Measure against the observed pixel mapping.
restored_points = outputs[1][:, 0].to(diagnostic_dtype) - image_shift.to(diagnostic_dtype)
error = torch.linalg.vector_norm(restored_points - points[:, 0].to(diagnostic_dtype), dim=-1)
self.assert_close(report.spatial[0].roundtrip_max, error)
restored_boxes = outputs[2].data.to(diagnostic_dtype) - image_shift[:, None, None, :].to(diagnostic_dtype)
box_error = torch.linalg.vector_norm(restored_boxes - boxes.data.to(diagnostic_dtype), dim=-1).amax(-1).amax(-1)
self.assert_close(report.spatial[1].roundtrip_max, box_error)
- if bool((error > report.roundtrip_tolerance).any()):
- assert "round-trip error exceeds" in report.summary()
- if batch_prob is None or bool(selected.all()) or not bool(selected.any()):
- # Whole-batch application or skip keeps labels aligned with the image (#4473).
- self.assert_close(error, torch.zeros_like(error))
+ # Whole-batch application or skip keeps labels aligned with the image (#4473).
+ self.assert_close(error, torch.zeros_like(error))
+
+ def test_roundtrip_error_warning_for_tensor_boxes_under_rotation(self, device, dtype):
+ # Tensor boxes keep only the axis-aligned envelope of a rotated box, so the round trip is lossy and the
+ # audit warns. This keeps the warning covered now that no crop gate produces an image/label mismatch.
+ image = torch.zeros(2, 1, 20, 20, device=device, dtype=dtype)
+ boxes = image.new_tensor([[[[4, 6], [14, 6], [14, 10], [4, 10]]]]).expand(2, -1, -1, -1).clone()
+ aug = K.AugmentationSequential(K.RandomRotation((45.0, 45.0), p=1.0), data_keys=["input", "bbox"])
+ _, report = audit(aug, image, boxes)
+ assert float(report.spatial[0].roundtrip_max.max()) > report.roundtrip_tolerance
+ assert "round-trip error exceeds" in report.summary()
@pytest.mark.parametrize("cropping_mode", ["slice", "resample"])
@pytest.mark.parametrize(