Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(augmentation): track the size of PadTo and RandomMosaic in AugmentationSequential (#6133)

Aditya Sinha8b6340e1e0c4
diff --git a/changelog.d/6133.fixed.md b/changelog.d/6133.fixed.md
new file mode 100644
index 000000000..5441eb15e
--- /dev/null
+++ b/changelog.d/6133.fixed.md
@@ -0,0 +1 @@
+`AugmentationSequential`, `ImageSequential` and `VideoSequential` now track the size that `PadTo`, and `RandomMosaic` with an `output_size`, return. Every later child used to draw its parameters for the canvas before them, so the pipeline differed from applying the children one at a time. An integer-size `Resize`, `LongestMaxSize` or `SmallestMaxSize` returned the wrong size: `PadTo((40, 40))` then `Resize(16)` gave a `(16, 26)` image instead of `(16, 16)`. A resample-mode crop, `RandomCrop`, `RandomResizedCrop`, `RandomAffine`, `RandomPerspective` and `RandomErasing` used the old size for their windows, centres and corners, `RandomElasticTransform` raised a size-mismatch `RuntimeError`, and a later `Resize`, slice-mode `CenterCrop` or `RandomHorizontalFlip` moved boxes and keypoints for the old canvas. The resample-mode crop was also wrong under `torch.export`.
diff --git a/kornia/augmentation/container/image.py b/kornia/augmentation/container/image.py
index 9599b6909..0ad2cdd49 100644
--- a/kornia/augmentation/container/image.py
+++ b/kornia/augmentation/container/image.py
@@ -503,6 +503,7 @@ def _get_new_batch_shape(param: ParamItem, batch_shape: torch.Size, module: Opti
Note:
Augmentations that change the spatial size provide `output_size` with shape (B, spatial_dims).
+ `PadTo` and `RandomMosaic(output_size=...)` provide none, so their configured size is used.
Empty crops and resizes have no sampled
output-size rows, so their configured size is used only when the image forward path
always applies the transform. Other probability branches retain the current empty-gate
@@ -538,6 +539,15 @@ def _get_new_batch_shape(param: ParamItem, batch_shape: torch.Size, module: Opti
batch_shape = _get_new_batch_shape(p, batch_shape, children.get(p.name))
return batch_shape
+ # PadTo and RandomMosaic(output_size=...) always return their configured size but emit no ``output_size``.
+ # No branch below matches them, so the final return passes the updated shape on.
+ if isinstance(module, (K.PadTo, K.RandomMosaic)):
+ size = module.flags["size" if isinstance(module, K.PadTo) else "output_size"]
+ if size is not None:
+ new_batch_shape = list(batch_shape)
+ new_batch_shape[-len(size) :] = [operator.index(dim) for dim in size]
+ batch_shape = torch.Size(new_batch_shape)
+
if (
batch_shape[0] == 0
and isinstance(module, _AugmentationBase)
diff --git a/tests/augmentation/container/test_augmentation_sequential.py b/tests/augmentation/container/test_augmentation_sequential.py
index c56708f8e..9df82f736 100644
--- a/tests/augmentation/container/test_augmentation_sequential.py
+++ b/tests/augmentation/container/test_augmentation_sequential.py
@@ -3180,3 +3180,43 @@ class TestCrop3DShapePropagation(BaseTester):
actual = _get_new_batch_shape(params, image.shape, op)
assert [type(dim) for dim in actual] == [int] * 5
assert actual == (batch, 1, 4, 5, 6)
+
+
+class TestPadToMosaicShapePropagation(BaseTester):
+ @pytest.mark.parametrize(
+ "make_first",
+ [lambda: K.PadTo((40, 48)), lambda: K.RandomMosaic(output_size=(20, 30), p=1.0)],
+ ids=["PadTo", "RandomMosaic"],
+ )
+ @pytest.mark.parametrize(
+ "make_second",
+ [lambda: K.Resize(16), lambda: K.CenterCrop(8, cropping_mode="resample")],
+ ids=["Resize-int", "CenterCrop-resample"],
+ )
+ def test_next_child_sees_the_new_canvas_6043(self, make_first, make_second, device, dtype):
+ if not supports_bilinear_2d_grid_sample(device, dtype):
+ pytest.skip("2D bilinear grid sampling is unsupported for this device/dtype.")
+ image = torch.rand(2, 3, 24, 40).to(device, dtype)
+ seq = K.AugmentationSequential(make_first(), make_second())
+ actual = seq(image)
+ canvas = seq[0](image, params=seq._params[0].data)
+ assert tuple(seq._params[1].data["forward_input_shape"].tolist()) == tuple(canvas.shape)
+ self.assert_close(actual, make_second()(canvas))
+
+ @pytest.mark.parametrize("batch", [0, 2])
+ @pytest.mark.parametrize("exporting", [False, True])
+ def test_tracked_size_6043(self, batch, exporting):
+ from kornia.augmentation.container.image import _get_new_batch_shape
+
+ shape = torch.Size((batch, 3, 24, 40))
+ # RandomMosaic resizes to ``output_size`` also when the mosaic is skipped, and keeps the size without one.
+ cases = [
+ (K.PadTo((40, 48)), (40, 48)),
+ (K.PadTo((16, 48)), (16, 48)), # a target below the input height crops it
+ (K.RandomMosaic(output_size=(20, 30), p=0.0), (20, 30)),
+ (K.RandomMosaic(p=1.0), (24, 40)),
+ ]
+ for op, size in cases:
+ params = ParamItem("op", op.forward_parameters(shape))
+ with patch("kornia.augmentation.container.image.is_exporting", return_value=exporting):
+ assert _get_new_batch_shape(params, shape, op) == (batch, 3, *size)
diff --git a/tests/augmentation/test_torch_export.py b/tests/augmentation/test_torch_export.py
index c2d934ff7..6e5c84458 100644
--- a/tests/augmentation/test_torch_export.py
+++ b/tests/augmentation/test_torch_export.py
@@ -189,6 +189,34 @@ def test_torch_export_container_int_size_resize_6024(
torch.testing.assert_close(out, eager, atol=1e-5, rtol=1e-5)
+PAD_TO_FOLLOWERS: list[Tuple[str, Callable[[], list[torch.nn.Module]]]] = [
+ ("Resize", lambda: [K.Resize(16)]),
+ ("CenterCrop-resample", lambda: [K.CenterCrop(8, cropping_mode="resample")]),
+ ("Resize,CenterCrop-resample", lambda: [K.Resize(16), K.CenterCrop(8, cropping_mode="resample")]),
+]
+
+
[email protected](not hasattr(torch, "export"), reason="torch.export requires torch>=2.1")
[email protected](not dynamo_is_available(), reason=DYNAMO_UNAVAILABLE_REASON)
[email protected](not _HAS_TORCH_EXPORT_TRACKING, reason=_TORCH_EXPORT_TRACKING_REASON)
[email protected]("name,factory", PAD_TO_FOLLOWERS, ids=[n for n, _ in PAD_TO_FOLLOWERS])
+def test_torch_export_container_pad_to_then_shape_dependent_6043(
+ name: str, factory: Callable[[], list[torch.nn.Module]]
+) -> None:
+ """A shape-dependent child after ``PadTo`` plans for the padded canvas under ``torch.export`` (#6043)."""
+ torch.manual_seed(0)
+ x = torch.randn(2, 3, 24, 40)
+ augs = [K.PadTo((40, 48)), *factory()]
+ expected = x
+ for aug in augs:
+ expected = aug(expected)
+ seq = K.AugmentationSequential(*augs, data_keys=["input"])
+ out = torch.export.export(seq, (x,)).module()(x)
+ assert out.shape == expected.shape, f"{name}: shape {out.shape} vs {expected.shape}"
+ torch.testing.assert_close(out, expected, atol=1e-5, rtol=1e-5)
+
+
def _mask_export_case(case: str) -> Tuple[torch.nn.Module, tuple, Callable[[object], torch.Tensor], torch.Tensor]:
"""Build a float64 image/mask pipeline for ``case``: the module, its arguments, a mask getter, the expected mask."""
image = torch.zeros(1, 1, 1, 2, dtype=torch.float64)