Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(augmentation): reject 4D input for 3D sequential (#4697)

NiteeshGowda722d2e5e6aca52
diff --git a/changelog.d/4697.breaking.md b/changelog.d/4697.breaking.md
new file mode 100644
index 000000000..8d451438e
--- /dev/null
+++ b/changelog.d/4697.breaking.md
@@ -0,0 +1 @@
+`AugmentationSequential` now rejects rank-4 image input when used with a 3D augmentation. Previously, rank-4 input was promoted as ``(C, D, H, W)``; this is ambiguous with the container's ``(B, C, H, W)`` image layout. To pass a single 3D volume explicitly, use ``unsqueeze(0)`` to add the batch dimension and provide input as ``(B, C, D, H, W)``. Bare 3D augmentations retain their rank-3 and rank-4 input promotion behavior.
diff --git a/changelog.d/4697.fixed.md b/changelog.d/4697.fixed.md
new file mode 100644
index 000000000..65c546425
--- /dev/null
+++ b/changelog.d/4697.fixed.md
@@ -0,0 +1 @@
+`AugmentationSequential` now rejects 4D image batches when used with a 3D augmentation instead of silently treating the batch as a single 3D sample.
diff --git a/kornia/augmentation/_3d/base.py b/kornia/augmentation/_3d/base.py
index 3934898b1..56bd8a8fa 100644
--- a/kornia/augmentation/_3d/base.py
+++ b/kornia/augmentation/_3d/base.py
@@ -38,9 +38,11 @@ class AugmentationBase3D(_AugmentationBase):
same_on_batch: apply the same transformation across the batch.
Convention:
- - the working layout is ``(B, C, D, H, W)`` float. Inputs of rank three and four are promoted by
- prepending batch and, for rank three, channel dimensions; ``keepdim=True`` restores that original
- rank. The dtype guard accepts only ``float16``, ``bfloat16``, ``float32``, and ``float64``.
+ - the working layout is ``(B, C, D, H, W)`` float. Bare 3D augmentations accept inputs of rank three
+ and four and promote them by prepending batch and, for rank three, channel dimensions; ``keepdim=True``
+ restores that original rank. Inside ``AugmentationSequential``, rank-4 input is rejected because
+ ``(C, D, H, W)`` is ambiguous with the container's ``(B, C, H, W)`` image layout. The dtype guard
+ accepts only ``float16``, ``bfloat16``, ``float32``, and ``float64``.
:class:`~kornia.augmentation.RandomTransplantation3D` overrides ``forward`` and takes batched inputs
only.
- ``p`` gates samples and ``p_batch`` gates a whole call; ``same_on_batch=True`` shares the generated
diff --git a/kornia/augmentation/_3d/mix/transplantation.py b/kornia/augmentation/_3d/mix/transplantation.py
index bcaa8590d..7975062a8 100644
--- a/kornia/augmentation/_3d/mix/transplantation.py
+++ b/kornia/augmentation/_3d/mix/transplantation.py
@@ -34,10 +34,8 @@ class RandomTransplantation3D(RandomTransplantation, AugmentationBase3D): # typ
:class:`~kornia.augmentation.container.AugmentationSequential` dispatches it as a 3D augmentation;
called directly, it is byte-identical to the 2D class at every rank, volumes included.
- inside a container, use this class for ``(B, C, D, H, W)`` volumes and
- :class:`~kornia.augmentation.RandomTransplantation` for ``(B, C, H, W)`` images. Only one of the two
- mistakes is reported: the container refuses a 5D batch before the 2D class runs, while this class
- returns a 4D batch unchanged, because the container builds a one-element gate from a rank it padded
- (`#4692 <https://github.com/kornia/kornia/issues/4692>`_).
+ :class:`~kornia.augmentation.RandomTransplantation` for ``(B, C, H, W)`` images. The container
+ rejects ambiguous 4D input for this 3D class and rejects 5D input for the 2D class.
- it derives from both :class:`~kornia.augmentation.MixAugmentationBaseV2` and
:class:`~kornia.augmentation.AugmentationBase3D`, so it is the one 3D augmentation that carries a
mix ``inverse`` -- which raises ``RuntimeError`` -- and the one mix augmentation a container accepts
diff --git a/kornia/augmentation/container/augment.py b/kornia/augmentation/container/augment.py
index 1ff298603..7f5b44550 100644
--- a/kornia/augmentation/container/augment.py
+++ b/kornia/augmentation/container/augment.py
@@ -120,8 +120,9 @@ class AugmentationSequential(TransformMatrixMinIn, ImageSequential):
The input dictionary is not modified.
- the layouts are ``(B, C, H, W)`` for images and masks, ``(B, N, 4, 2)`` vertices for ``bbox``,
``(B, N, 4)`` for ``bbox_xyxy`` and ``bbox_xywh``, and ``(B, N, 2)`` in ``(x, y)`` for ``keypoints``.
- Feeding a coordinate layout under another coordinate key raises ``ValueError`` naming the expected shape.
- ``N = 0`` is
+ For 3D augmentations, inputs must be ``(D, H, W)`` or ``(B, C, D, H, W)``; rank-4 input is rejected
+ because ``(C, D, H, W)`` and ``(B, C, H, W)`` are ambiguous. Feeding a coordinate layout under another
+ coordinate key raises ``ValueError`` naming the expected shape. ``N = 0`` is
accepted on every one of them. A ``mask`` is the one key whose rank changes: a ``(B, H, W)`` mask is
accepted and returned as ``(B, 1, H, W)``. A wrong input *rank* raises ``RuntimeError`` here rather than
the ``ValueError`` a bare augmentation raises.
@@ -578,14 +579,24 @@ class AugmentationSequential(TransformMatrixMinIn, ImageSequential):
in_args = self._arguments_preproc(*args, data_keys=self.transform_op.data_keys) # type: ignore
+ if DataKey.INPUT in self.transform_op.data_keys:
+ inp = in_args[self.transform_op.data_keys.index(DataKey.INPUT)]
+ if not isinstance(inp, torch.Tensor):
+ raise ValueError(f"`INPUT` should be a torch.Tensor but `{type(inp)}` received.")
+ if self.contains_3d_augmentation and len(inp.shape) == 4:
+ raise RuntimeError(
+ f"3D augmentations in AugmentationSequential expect input shape "
+ f"(D, H, W) or (B, C, D, H, W), but got {inp.shape}."
+ )
+
if params is None:
# image data must exist if params is not provided.
if DataKey.INPUT in self.transform_op.data_keys:
inp = in_args[self.transform_op.data_keys.index(DataKey.INPUT)]
- if not isinstance(inp, torch.Tensor):
- raise ValueError(f"`INPUT` should be a torch.Tensor but `{type(inp)}` received.")
# A video input shall be BCDHW while an image input shall be BCHW
- if self.contains_video_sequential or self.contains_3d_augmentation:
+ if self.contains_video_sequential:
+ _, out_shape = self.autofill_dim(inp, dim_range=(3, 5))
+ elif self.contains_3d_augmentation:
_, out_shape = self.autofill_dim(inp, dim_range=(3, 5))
else:
_, out_shape = self.autofill_dim(inp, dim_range=(2, 4))
diff --git a/tests/augmentation/container/test_augmentation_sequential.py b/tests/augmentation/container/test_augmentation_sequential.py
index 34c45822b..1b55e5324 100644
--- a/tests/augmentation/container/test_augmentation_sequential.py
+++ b/tests/augmentation/container/test_augmentation_sequential.py
@@ -110,6 +110,31 @@ class TestAugmentationSequential:
out = aug_list(input)
assert out.shape == input.shape
+ def test_3d_augmentation_rejects_4d_input(self, device, dtype):
+ input = torch.randn(2, 3, 5, 6, device=device, dtype=dtype)
+ aug_list = K.AugmentationSequential(K.RandomAffine3D(360.0, p=1.0), data_keys=["input"])
+
+ with pytest.raises(
+ RuntimeError,
+ match=r"3D augmentations in AugmentationSequential expect input shape",
+ ):
+ aug_list(input)
+
+ def test_3d_augmentation_rejects_4d_input_when_replaying_params(self, device, dtype):
+ input_5d = torch.randn(1, 2, 3, 5, 6, device=device, dtype=dtype)
+ aug_list = K.AugmentationSequential(K.RandomAffine3D(360.0, p=1.0), data_keys=["input"])
+
+ aug_list(input_5d)
+ params = aug_list._params
+
+ input_4d = torch.randn(2, 3, 5, 6, device=device, dtype=dtype)
+
+ with pytest.raises(
+ RuntimeError,
+ match=r"3D augmentations in AugmentationSequential expect input shape",
+ ):
+ aug_list(input_4d, params=params)
+
def test_identity_matrix_3d(self, device, dtype):
input = torch.rand(2, 1, 3, 4, 5, device=device, dtype=dtype)
aug = K.AugmentationSequential(K.RandomDepthicalFlip3D(p=1.0))
diff --git a/tests/augmentation/test_conventions_transplantation.py b/tests/augmentation/test_conventions_transplantation.py
index 9c7ddf32e..fb82974a4 100644
--- a/tests/augmentation/test_conventions_transplantation.py
+++ b/tests/augmentation/test_conventions_transplantation.py
@@ -470,20 +470,19 @@ class TestTransplantationConventions(BaseTester):
assert torch.equal(flat_mask, volume_mask)
@pytest.mark.device_agnostic
- def test_wart_container_dispatch_reports_only_one_of_the_two_rank_mistakes_4692(self):
+ def test_convention_container_rejects_both_rank_mistakes_4692(self):
image, mask = _labelled_batch(batch=3, spatial=(4, 6))
volume, volume_mask = _labelled_batch(batch=3, spatial=(3, 4, 6))
# The 2D class on a volume raises.
with pytest.raises(RuntimeError, match="input shape expected to be in"):
K.AugmentationSequential(K.RandomTransplantation(p=1.0), data_keys=["image", "mask"])(volume, volume_mask)
- # The 3D class on a 2D batch is a silent no-op: correct shapes, nothing moved.
+ # The 3D class on a 2D batch is rejected because the 4D shape is ambiguous.
inner = K.RandomTransplantation3D(p=1.0)
- torch.manual_seed(7)
- out_image, out_mask = K.AugmentationSequential(inner, data_keys=["image", "mask"])(image, mask)
- assert out_image.shape == image.shape
- assert torch.equal(out_mask, mask)
- assert inner._params["batch_prob"].numel() == 1 # a one-element gate for a batch of 3
- assert inner._params["donor_indices"].tolist() == [0]
+ with pytest.raises(
+ RuntimeError,
+ match=r"3D augmentations in AugmentationSequential expect input shape",
+ ):
+ K.AugmentationSequential(inner, data_keys=["image", "mask"])(image, mask)
@pytest.mark.device_agnostic
def test_wart_container_runs_the_transplant_only_as_the_first_step_4707(self):