Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(augmentation): support BHW masks with torch.compile (#5602)

NiteeshGowda7241207c955b06
diff --git a/changelog.d/5602.fixed.md b/changelog.d/5602.fixed.md
new file mode 100644
index 000000000..c0e0d2839
--- /dev/null
+++ b/changelog.d/5602.fixed.md
@@ -0,0 +1 @@
+`AugmentationSequential` with a `(B, H, W)` mask now compiles with `torch.compile(..., fullgraph=True)`, with and without `keepdim=True`: the mask's batch size comes from the per-sample gate instead of the `forward_input_shape` tensor. A `(B, T, H, W)` mask under `VideoSequential(same_on_frame=True)` no longer raises.
diff --git a/kornia/augmentation/base.py b/kornia/augmentation/base.py
index 68771a27f..ed56c1d59 100644
--- a/kornia/augmentation/base.py
+++ b/kornia/augmentation/base.py
@@ -465,6 +465,15 @@ class _AugmentationBase(_BasicAugmentationBase):
ori_shape = input.shape
shape = params["forward_input_shape"]
+
+ # A batched call has one gate per sample, so ``batch_prob`` gives the batch size as a Python int. The shape
+ # helpers read it from the ``forward_input_shape`` tensor, a data-dependent branch that breaks
+ # ``torch.compile(fullgraph=True)`` for a ``(B, H, W)`` mask (#5598). A list entry (0-d gate) keeps them.
+ channel_dim: Optional[int] = None
+ if input.dim() == 3 and batch_prob.dim() == 1:
+ channel_dim = 1 if input.shape[0] == batch_prob.shape[0] else 0
+ input = input.unsqueeze(channel_dim)
+
in_tensor = self.transform_tensor(input, shape=shape, match_channel=False)
self.validate_tensor(in_tensor)
@@ -474,7 +483,11 @@ class _AugmentationBase(_BasicAugmentationBase):
output = self._blend_by_prob(output_transformed, output_not_transformed, to_apply)
- return _transform_output_shape(output, ori_shape, reference_shape=shape) if self.keepdim else output
+ if not self.keepdim:
+ return output
+ if channel_dim is not None:
+ return output.squeeze(channel_dim)
+ return _transform_output_shape(output, ori_shape, reference_shape=shape)
def transform_boxes(
self,
diff --git a/tests/augmentation/test_augmentation_compile.py b/tests/augmentation/test_augmentation_compile.py
index ffc19c102..bd90ee08c 100644
--- a/tests/augmentation/test_augmentation_compile.py
+++ b/tests/augmentation/test_augmentation_compile.py
@@ -72,6 +72,21 @@ class TestAugmentationCompile(BaseTester):
self.assert_close(out_input, input.flip(-1))
self.assert_close(out_mask, mask.flip(-1))
+ @pytest.mark.parametrize("keepdim", [None, True])
+ def test_dynamo_sequential_bhw_mask_5598(self, device, dtype, torch_optimizer, keepdim):
+ # A (B, H, W) mask takes its batch size from ``batch_prob``; reading it from the ``forward_input_shape``
+ # tensor was a data-dependent branch, on the way in and, under keepdim, on the way out.
+ input = torch.rand(2, 3, 8, 8, device=device, dtype=dtype)
+ mask = torch.rand(2, 8, 8, device=device, dtype=dtype)
+ aug = K.AugmentationSequential(
+ K.RandomHorizontalFlip(p=1.0),
+ data_keys=["input", "mask"],
+ keepdim=keepdim,
+ )
+ out_input, out_mask = torch_optimizer(aug, fullgraph=True)(input, mask)
+ self.assert_close(out_input, input.flip(-1))
+ self.assert_close(out_mask, mask.flip(-1) if keepdim else mask.flip(-1).unsqueeze(1))
+
def test_dynamo_sequential_bbox(self, device, dtype, torch_optimizer):
# The 'bbox' key imports through Boxes.from_tensor('vertices_plus'), whose finiteness check is
# asynchronous, so the box path compiles with fullgraph=True (#4177).
diff --git a/tests/augmentation/test_base.py b/tests/augmentation/test_base.py
index 521c02859..9b9165cbe 100644
--- a/tests/augmentation/test_base.py
+++ b/tests/augmentation/test_base.py
@@ -757,6 +757,40 @@ class TestConventionAugmentationBase2D(BaseTester):
with pytest.raises(NotImplementedError):
K.AugmentationSequential(aug, data_keys=["input", key])(image, data)
+ def test_convention_bhw_mask_list_entry_follows_the_image_5598(self, device, dtype):
+ # A batched (B, H, W) mask takes its batch size from ``batch_prob`` (#5598). A list entry has a 0-d gate and
+ # still reads a first dimension equal to the image batch as that batch, so each row gets its own crop window.
+ # The meaning of a mask list is tracked in #4477.
+ image = torch.arange(2 * 64, device=device).to(dtype).reshape(2, 1, 8, 8)
+ sequence = K.AugmentationSequential(K.RandomCrop((4, 4), p=1.0), data_keys=["input", "mask"])
+ output_image, output_masks = sequence(image, [image[:, 0]])
+ assert output_masks[0].shape == (2, 1, 4, 4)
+ self.assert_close(output_masks[0], output_image, rtol=0, atol=0)
+
+ @pytest.mark.parametrize("first_dim", [2, 3])
+ def test_convention_3d_mask_keepdim_returns_its_rank_5598(self, device, dtype, first_dim):
+ # Under keepdim a 3-D mask whose first dimension is the image batch stays (B, H, W); otherwise it is a
+ # single (C, H, W) mask that is broadcast across the image batch.
+ image = torch.zeros(2, 1, 8, 8, device=device, dtype=dtype)
+ mask = torch.arange(first_dim * 64, device=device).to(dtype).reshape(first_dim, 8, 8)
+ sequence = K.AugmentationSequential(K.RandomHorizontalFlip(p=1.0), data_keys=["input", "mask"], keepdim=True)
+ _, output_mask = sequence(image, mask)
+ expected = (
+ mask.flip(-1)
+ if first_dim == image.shape[0]
+ else mask.flip(-1).unsqueeze(0).expand(image.shape[0], -1, -1, -1)
+ )
+ self.assert_close(output_mask, expected, rtol=0, atol=0)
+
+ def test_convention_video_bthw_mask_follows_the_clip_5598(self, device, dtype):
+ # VideoSequential flattens a (B, T, H, W) mask to (B * T, H, W). With same_on_frame=True the child draws for B
+ # and its gates are broadcast to B * T, which is the batch the mask has; the drawn shape says B (#5598).
+ clip = torch.arange(2 * 3 * 64, device=device).to(dtype).reshape(2, 3, 1, 8, 8)
+ video = K.VideoSequential(K.RandomHorizontalFlip(p=1.0))
+ sequence = K.AugmentationSequential(video, data_keys=["input", "mask"])
+ output_clip, output_mask = sequence(clip, clip[:, :, 0])
+ self.assert_close(output_mask, output_clip, rtol=0, atol=0)
+
def test_convention_direct_geometric_mask_handler_rejects_bool(self, device, dtype):
# The container casts bool masks around geometric dispatch. Calling the geometric handler directly
# instead takes the image dtype guard, so float masks work while bool masks raise TypeError.