π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(augmentation)!: reject a mixed gate on shape-changing augmentations (#5473)
Tejas Anil Nagmote584251cd694a
diff --git a/changelog.d/5473.breaking.md b/changelog.d/5473.breaking.mdnew file mode 100644index 000000000..14f9b833b--- /dev/null+++ b/changelog.d/5473.breaking.md@@ -0,0 +1 @@+A shape-changing augmentation such as `RandomCrop` or `Resize` given a hand-made `batch_prob` that mixes applied and skipped rows now raises `ValueError`, in `forward` and in `inverse`. Before, `forward` transformed the skipped rows too, and `inverse` failed with a shape mismatch. `kornia.contrib.augmentation_audit.audit` raises the same `ValueError` for such a step; before, it returned a report for it.diff --git a/docs/source/contrib.rst b/docs/source/contrib.rstindex 91ac3798d..7c6375c55 100644--- a/docs/source/contrib.rst+++ b/docs/source/contrib.rst@@ -71,13 +71,13 @@ Interpreting the report* Crop matrices can invert coordinates even after image content has been discarded.The report records this distinction and never evaluates image reconstruction.Cropping and downsampling emit possible content-loss warnings.-* Partially applied ``RandomCrop`` mappings follow the returned image branch. A- crop skipped for the whole batch leaves images and labels unchanged, including- with ``padding`` or ``pad_if_needed`` (#4473). Manually supplied parameters that- apply the crop to only some rows can still return a transformed image with- untransformed labels on the skipped rows; the resulting round-trip error records- that inconsistency. Mixed shape-changing operations are reported as- ``unsupported`` when their cached matrices cannot certify every returned image row.+* A ``RandomCrop`` skipped for the whole batch leaves images and labels unchanged,+ 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.* Non-rigid and unknown operations are explicitly unsupported for matrixcomposition. A transformation-matrix identity fallback is not treated as proofof correspondence. Supported neighboring operations remain in the provenance.diff --git a/kornia/augmentation/_2d/geometric/base.py b/kornia/augmentation/_2d/geometric/base.pyindex 0bafc7592..0317599be 100644--- a/kornia/augmentation/_2d/geometric/base.py+++ b/kornia/augmentation/_2d/geometric/base.py@@ -20,6 +20,7 @@ from typing import Any, Dict, Optional, Tupleimport torchfrom kornia.augmentation._2d.base import RigidAffineAugmentationBase2D+from kornia.augmentation.base import _mixed_gate_shape_errorfrom kornia.constants import Resamplefrom kornia.core.utils import _torch_inverse_castfrom kornia.geometry.boxes import Boxes@@ -249,6 +250,8 @@ class GeometricAugmentationBase2D(RigidAffineAugmentationBase2D):elif to_apply.all():output = self.inverse_transform(in_tensor, flags=flags, transform=transform, size=size)else:+ if size is not None and tuple(in_tensor.shape[-2:]) != size:+ raise _mixed_gate_shape_error(in_tensor.shape[1:], (*in_tensor.shape[1:-2], *size), inverse=True)output[to_apply] = self.inverse_transform(in_tensor[to_apply],transform=transform[to_apply] if transform is not None else transform,diff --git a/kornia/augmentation/_2d/geometric/crop.py b/kornia/augmentation/_2d/geometric/crop.pyindex 2c1c2a263..5be670e39 100644--- a/kornia/augmentation/_2d/geometric/crop.py+++ b/kornia/augmentation/_2d/geometric/crop.py@@ -306,8 +306,7 @@ class RandomCrop(GeometricAugmentationBase2D):# Pixels are padded below; sample with the padded-canvas crop matrix.offset = self._padding_offset(input, params)if not (self.p == 1.0 and self.p_batch == 1.0):- # Only selected matrices include padding. Keep skipped rows as identity,- # including when a shape-changing blend returns the whole transformed image.+ # Only selected matrices include padding. Keep skipped rows as identity.applied = torch.atleast_1d(params["batch_prob"] > 0.5).to(offset)applied = applied if applied.shape[0] == transform.shape[0] else applied.any()offset = offset * applied.reshape(-1, 1)diff --git a/kornia/augmentation/base.py b/kornia/augmentation/base.pyindex 5bdaf0aaa..68771a27f 100644--- a/kornia/augmentation/base.py+++ b/kornia/augmentation/base.py@@ -34,6 +34,24 @@ from kornia.core.utils import is_autocast_enabled, is_exportingfrom kornia.geometry.boxes import Boxesfrom kornia.geometry.keypoints import Keypoints++def _mixed_gate_shape_error(+ input_shape: Tuple[int, ...], output_shape: Tuple[int, ...], inverse: bool = False+) -> ValueError:+ """Build the error for a per-row gate on an augmentation that changes the sample shape.++ A batch can only hold one sample shape, so the rows the gate skips cannot keep their own shape next to the+ rows it applies to. ``inverse`` names the inverse call, which maps the output shape back to the input shape.+ See `#4497 <https://github.com/kornia/kornia/issues/4497>`_.+ """+ subject = "the inverse of this augmentation" if inverse else "this augmentation"+ return ValueError(+ f"`batch_prob` mixes applied and skipped rows, but {subject} changes the sample shape from "+ f"{tuple(input_shape)} to {tuple(output_shape)}, so the skipped rows cannot keep their shape. "+ "Pass a `batch_prob` that is all ones or all zeros."+ )++TensorWithTransformMat = Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]# Sentinel for ``_commit_state`` fields: distinguishes "not provided" from an explicit ``None``.@@ -380,12 +398,16 @@ class _AugmentationBase(_BasicAugmentationBase):When the two branches share a shape this is a ``torch.where`` blend (onnx- andfullgraph-friendly). Shape-changing augmentations (e.g. crop/resize) whose branchesdiffer in spatial size fall back to a Python branch on ``to_apply.any()``, which is- not onnx-exportable.+ not onnx-exportable. Such a fallback cannot select rows, so a ``to_apply`` that mixes applied and skipped+ rows raises ``ValueError`` instead of transforming the skipped rows too."""if transformed.shape == not_transformed.shape and transformed.shape[0] == to_apply.shape[0]:to_apply_expanded = to_apply.view(-1, *([1] * (len(transformed.shape) - 1))).to(transformed.device)return torch.where(to_apply_expanded, transformed, not_transformed)- return transformed if bool(to_apply.any()) else not_transformed+ apply_any = bool(to_apply.any())+ if apply_any and not bool(to_apply.all()) and transformed.shape[1:] != not_transformed.shape[1:]:+ raise _mixed_gate_shape_error(not_transformed.shape[1:], transformed.shape[1:])+ return transformed if apply_any else not_transformeddef transform_inputs(self,diff --git a/kornia/contrib/augmentation_audit.py b/kornia/contrib/augmentation_audit.pyindex 18c538c57..2684e13a7 100644--- a/kornia/contrib/augmentation_audit.py+++ b/kornia/contrib/augmentation_audit.py@@ -30,7 +30,6 @@ import torchfrom torch import Tensor, nnfrom kornia.augmentation._2d.geometric.base import GeometricAugmentationBase2D-from kornia.augmentation._2d.geometric.crop import RandomCropfrom kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2Dfrom kornia.augmentation._3d.base import AugmentationBase3Dfrom kornia.augmentation.container.image import ImageSequential@@ -244,33 +243,6 @@ def _capture_warnings(sequence: AugmentationSequential, steps: list[Augmentationreturn []-def _crop_matrix(- module: RandomCrop,- matrix: Tensor,- params: dict[str, Any],- flags: dict[str, Any],- image: Tensor,- output: Tensor,-) -> tuple[Tensor | None, str | None]:- applied = params["batch_prob"] > 0.5- static = module.p == 1.0 and module.p_batch == 1.0- changed_shape = output.shape[-2:] != image.shape[-2:]- if not static and changed_shape and flags["cropping_mode"] == "slice" and not bool(applied.all()):- # The shape-changing blend returns every transformed row, but slice uses- # src indices even where the cached per-row matrix is the identity.- return None, "mixed-application slice crop has no reliable per-row image matrix after changing shape"- if static or not changed_shape:- return matrix, None- # Selected matrices already map original coordinates, including padding.- # A shape-changing resample still returns padded pixels for skipped rows whose- # public matrix is identity. Only those rows need the image-only correction.- padding = params["padding_size"].to(matrix)- translation = torch.eye(3, device=matrix.device, dtype=matrix.dtype).expand_as(matrix).clone()- translation[:, 0, 2] = padding[:, 0] * (~applied).to(matrix)- translation[:, 1, 2] = padding[:, 2] * (~applied).to(matrix)- return matrix @ translation, None--def _coordinates(value: DataType, key: DataKey) -> Tensor:if (isinstance(value, Boxes) and key not in _BOX_MODES) or (isinstance(value, Keypoints) and key != DataKey.KEYPOINTS@@ -308,22 +280,8 @@ def _capture(reason = Noneif isinstance(module, (GeometricAugmentationBase2D, IntensityAugmentationBase2D)):# Materialize lazy matrices in the caller's context so the ordinary spatial- # outputs remain identical, then adjust diagnostics outside autocast.+ # outputs remain identical.matrix = _snapshot(module.transform_matrix)- with torch.autocast(device_type=image.device.type, enabled=False):- if matrix is not None and isinstance(module, RandomCrop):- matrix, reason = _crop_matrix(module, matrix, params, flags, image, output)- elif (- matrix is not None- and output.shape[-2:] != image.shape[-2:]- and not (module.p == 1.0 and module.p_batch == 1.0)- and not bool((params["batch_prob"] > 0.5).all())- ):- # A shape-changing image blend returns the transformed branch for- # every row when any row is selected. Matrices and spatial labels- # remain blended per row, so they cannot certify the returned image.- matrix = None- reason = "mixed-application shape-changing operation has no reliable per-row image matrix"if matrix is not None and matrix.shape != (image.shape[0], 3, 3):matrix = Nonereason = "operation produced a matrix with an unsupported shape"diff --git a/tests/augmentation/container/test_random_crop.py b/tests/augmentation/container/test_random_crop.pyindex b9da7cadb..0583ed391 100644--- a/tests/augmentation/container/test_random_crop.py+++ b/tests/augmentation/container/test_random_crop.py@@ -231,11 +231,41 @@ class TestRandomCropAnnotations(BaseTester):for actual, target in zip(output, expected):self.assert_close(actual, target)- # Equal spatial sizes let the image path select rows. Mixed shape-changing crops- # and mixed inverse have separate size/unpadding issues and are not asserted here.+ # Equal spatial sizes let the image path select rows. A mixed gate on a shape-changing crop raises+ # (test_mixed_gate_with_shape_change_raises_4497); the mixed inverse is not asserted here.for actual, target in zip(output, inputs):self.assert_close(actual[1], target[1], rtol=0, atol=0)+ @pytest.mark.parametrize(+ "make_aug",+ [+ lambda: K.RandomCrop((20, 26), padding=(1, 2), p=0.5, cropping_mode="slice"),+ lambda: K.RandomCrop((20, 26), padding=(1, 2), p=0.5, cropping_mode="resample"),+ lambda: K.Resize((20, 26), p=0.5),+ ],+ ids=["crop-slice", "crop-resample", "resize"],+ )+ def test_mixed_gate_with_shape_change_raises_4497(self, make_aug, device, dtype):+ # A batch holds one sample shape, so rows skipped by the gate cannot keep their own size.+ # Before #4497 they were silently transformed too, and inverse failed with a shape mismatch.+ aug = make_aug()+ image = torch.rand(4, 1, 24, 32, device=device, dtype=dtype)+ params = aug.forward_parameters(image.shape)+ params["batch_prob"] = torch.tensor([0.0, 1.0, 0.0, 1.0])+ with pytest.raises(ValueError, match="mixes applied and skipped rows"):+ aug(image, params=deepcopy(params))+ if aug.flags.get("cropping_mode", "resample") == "resample":+ output = torch.rand(4, 1, 20, 26, device=device, dtype=dtype)+ with pytest.raises(ValueError, match="mixes applied and skipped rows"):+ aug.inverse(output, params=deepcopy(params))++ # A whole-batch gate in either direction is still accepted.+ for gate in ([1.0] * 4, [0.0] * 4):+ params["batch_prob"] = torch.tensor(gate)+ output = aug(image, params=deepcopy(params))+ expected = (20, 26) if gate[0] else (24, 32)+ assert output.shape == (4, 1, *expected)+@pytest.mark.parametrize("box_format", ["bbox", "bbox_xyxy", "bbox_xywh"])@pytest.mark.parametrize("unbatched", [False, True])@pytest.mark.parametrize("p", [0.0, 1.0])@@ -350,10 +380,15 @@ class TestRandomCropPaddingMatrix(BaseTester):params["src"] = (image.new_tensor([[[1, 1], [size[1], 1], [size[1], size[0]], [1, size[0]]]]).expand(2, -1, -1).clone())+ if size != image.shape[-2:]:+ # Skipped rows cannot keep their shape in a cropped batch (#4497).+ with pytest.raises(ValueError, match="mixes applied and skipped rows"):+ torch_optimizer(crop)(image, params=params)+ returnoutput = torch_optimizer(crop)(image, params=params)padded = torch.nn.functional.pad(image, (1, 1, 2, 2))expected = padded[..., 1 : size[0] + 1, 1 : size[1] + 1].clone()- expected[0] = image[0] if size == image.shape[-2:] else padded[0, :, : size[0], : size[1]]+ expected[0] = image[0]self.assert_close(output, expected, rtol=0, atol=0)matrix = image.new_tensor([[[1, 0, 0], [0, 1, 0], [0, 0, 1]], [[1, 0, 0], [0, 1, 1], [0, 0, 1]]])self.assert_close(crop.transform_matrix, matrix, rtol=0, atol=0)diff --git a/tests/contrib/test_augmentation_audit.py b/tests/contrib/test_augmentation_audit.pyindex 6c211e64a..907b9a83c 100644--- a/tests/contrib/test_augmentation_audit.py+++ b/tests/contrib/test_augmentation_audit.py@@ -141,20 +141,16 @@ class TestAugmentationAudit(BaseTester):assert torch.equal(actual[0], expected[0])assert torch.equal(actual[1], expected[1])- def test_shape_changing_mixed_application_is_unsupported(self, device, dtype):+ def test_shape_changing_mixed_application_raises(self, device, dtype):image = torch.zeros(2, 1, 8, 10, device=device, dtype=dtype)- image[:, 0, 2, 4] = 1points = image.new_tensor([[[4, 2]], [[4, 2]]])resize = K.Resize((4, 5), resample="nearest", p=0.5)params = resize.forward_parameters(image.shape)params["batch_prob"] = image.new_tensor([0, 1])aug = K.AugmentationSequential(resize, data_keys=["input", "keypoints"])- outputs, report = audit(aug, image, points, params=[ParamItem("Resize_0", params)])- assert outputs[0][0, 0, 1, 2].item() == 1- self.assert_close(outputs[1][0], points[0])- assert report.geometry_status == "unsupported"- assert report.matrix is None and report.inverse_matrix is None- assert "mixed-application shape-changing" in report.summary()+ # The audit matches the ordinary forward call, which rejects a mixed gate here (#4497).+ with pytest.raises(ValueError, match="mixes applied and skipped rows"):+ audit(aug, image, points, params=[ParamItem("Resize_0", params)])@pytest.mark.parametrize("cropping_mode", ["slice", "resample"])def test_crop_padding_and_content_loss(self, device, dtype, cropping_mode):@@ -544,7 +540,6 @@ class TestAugmentationAudit(BaseTester):(0.0, None),(1.0, None),(0.5, [0.0, 0.0]),- (0.5, [0.0, 1.0]),(0.5, [1.0, 1.0]),(1.0, [0.0, 1.0]),],@@ -592,47 +587,80 @@ class TestAugmentationAudit(BaseTester):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])- all_transformed = static or (size != image.shape[-2:] and bool(selected.any()))- transformed = torch.ones_like(selected) if all_transformed else selected+ transformed = torch.ones_like(selected) if static else selectedpadded = torch.nn.functional.pad(image, pad)expected_images = []image_shift = image.new_zeros((2, 2))for row in range(2):if transformed[row]:- # Slice ignores the cached matrix; resample uses its per-row identity/crop selection.- use_crop = cropping_mode == "slice" or static or bool(selected[row])- left, top = (x, y) if use_crop else (0, 0)- expected_images.append(padded[row, :, top : top + size[0], left : left + size[1]])- image_shift[row] = image.new_tensor([pad[0] - left, pad[2] - top])+ expected_images.append(padded[row, :, y : y + size[0], x : x + size[1]])+ image_shift[row] = image.new_tensor([pad[0] - x, pad[2] - y])else:expected_images.append(image[row])self.assert_close(outputs[0], torch.stack(expected_images))for row in range(2):destination = points[row, 0] + image_shift[row]assert outputs[0][row, 0, int(destination[1]), int(destination[0])].item() == 1- ambiguous_slice = cropping_mode == "slice" and all_transformed and not static and not bool(selected.all())- if ambiguous_slice:- assert report.geometry_status == "unsupported"- assert report.matrix is None and "slice" in report.summary()- else:- 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. Manually mixed rows can still- # return untransformed labels beside a transformed image.- 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))+ 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.+ 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))++ @pytest.mark.parametrize("cropping_mode", ["slice", "resample"])+ @pytest.mark.parametrize(+ "size, padding, pad_if_needed",+ [+ ((4, 8), None, False),+ ((4, 8), (1, 2), False),+ ((4, 8), (1, 2, 3, 0), False),+ ((6, 10), (1, 2, 3, 0), False),+ ((8, 12), None, True),+ ],+ )+ def test_crop_mixed_gate(self, device, dtype, cropping_mode, size, padding, pad_if_needed):+ image = torch.zeros(2, 1, 6, 10, device=device, dtype=dtype)+ image[:, 0, 1, 3] = 1+ points = image.new_tensor([[[3, 1]], [[3, 1]]])+ module = K.RandomCrop(+ size, padding=padding, pad_if_needed=pad_if_needed, p=0.5, cropping_mode=cropping_mode, resample="nearest"+ )+ params = module.forward_parameters(image.shape)+ params["batch_prob"] = image.new_tensor([0, 1])+ pad = params["padding_size"][0].tolist()+ x = min(1, image.shape[-1] + pad[0] + pad[1] - size[1])+ y = min(1, image.shape[-2] + pad[2] + pad[3] - size[0])+ params["src"] = (+ image.new_tensor([[[x, y], [x + size[1] - 1, y], [x + size[1] - 1, y + size[0] - 1], [x, y + size[0] - 1]]])+ .expand(2, -1, -1)+ .clone()+ )+ aug = K.AugmentationSequential(module, data_keys=["input", "keypoints"])+ item = [ParamItem("RandomCrop_0", params)]+ if size != image.shape[-2:]:+ # Skipped rows cannot keep their shape in a cropped batch (#4497).+ with pytest.raises(ValueError, match="mixes applied and skipped rows"):+ audit(aug, image, points, params=item)+ return+ outputs, report = audit(aug, image, points, params=item)+ padded = torch.nn.functional.pad(image, pad)+ self.assert_close(outputs[0][0], image[0])+ self.assert_close(outputs[0][1], padded[1, :, y : y + size[0], x : x + size[1]])+ assert report.geometry_status == "available"+ shift = report.matrix.new_tensor([[0, 0], [pad[0] - x, pad[2] - y]])+ self.assert_close(report.matrix[:, :2, 2], shift)+ self.assert_close(report.spatial[0].roundtrip_max, torch.zeros_like(report.spatial[0].roundtrip_max))@pytest.mark.parametrize("configured, effective", [("resample", "slice"), ("slice", "resample")])def test_crop_effective_mode_override(self, device, dtype, configured, effective):@@ -640,7 +668,8 @@ class TestAugmentationAudit(BaseTester):image[:, 0, 1, 3] = 1module = K.RandomCrop((4, 8), padding=(1, 2), p=0.5, cropping_mode=configured, resample="nearest")params = module.forward_parameters(image.shape)- params["batch_prob"] = image.new_tensor([0, 1])+ # A whole-batch gate: a mixed gate on this crop raises (#4497).+ params["batch_prob"] = image.new_tensor([1, 1])params["src"] = image.new_tensor([[[1, 1], [8, 1], [8, 4], [1, 4]]]).expand(2, -1, -1).clone()aug = K.AugmentationSequential(module, data_keys=["input", "keypoints"], extra_args={DataKey.INPUT: {"cropping_mode": effective}}@@ -650,11 +679,6 @@ class TestAugmentationAudit(BaseTester):)assert report.steps[0].flags["cropping_mode"] == effectiveassert module.flags["cropping_mode"] == configured- assert outputs[0][1, 0, 2, 3].item() == 1- if effective == "slice":- assert outputs[0][0, 0, 2, 3].item() == 1- assert report.geometry_status == "unsupported" and report.matrix is None- else:- assert outputs[0][0, 0, 3, 4].item() == 1- assert report.geometry_status == "available"- self.assert_close(report.matrix[:, :2, 2], report.matrix.new_tensor([[1, 2], [0, 1]]))+ assert outputs[0][0, 0, 2, 3].item() == 1 and outputs[0][1, 0, 2, 3].item() == 1+ assert report.geometry_status == "available"+ self.assert_close(report.matrix[:, :2, 2], report.matrix.new_tensor([[0, 1], [0, 1]]))