Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

Fix RandomCrop3D padding when transformation is skipped (#4667)

Junyi Zhengf6ed836298c9
diff --git a/changelog.d/4667.fixed.md b/changelog.d/4667.fixed.md
new file mode 100644
index 000000000..23bc4a447
--- /dev/null
+++ b/changelog.d/4667.fixed.md
@@ -0,0 +1 @@
+`RandomCrop3D` now preserves the input when the transformation is skipped, including when `padding` or `pad_if_needed` is enabled.
diff --git a/kornia/augmentation/_3d/geometric/crop.py b/kornia/augmentation/_3d/geometric/crop.py
index e40ac2284..9d275cff9 100644
--- a/kornia/augmentation/_3d/geometric/crop.py
+++ b/kornia/augmentation/_3d/geometric/crop.py
@@ -15,7 +15,9 @@
# limitations under the License.
#
-from typing import Any, Dict, Optional, Tuple, Union
+from __future__ import annotations
+
+from typing import Any, Dict, List, Optional, Tuple, Union
import torch
import torch.nn.functional as F
@@ -33,6 +35,7 @@ class RandomCrop3D(GeometricAugmentationBase3D):
Args:
p: probability of applying the transformation for the whole batch.
+ When skipped, the input is returned without padding or cropping.
size: Desired output size (out_d, out_h, out_w) of the crop.
Must be Tuple[int, int, int], then out_d = size[0], out_h = size[1], out_w = size[2].
padding: Optional padding on each border of the image.
@@ -108,8 +111,10 @@ class RandomCrop3D(GeometricAugmentationBase3D):
}
self._param_generator = rg.CropGenerator3D(size, None)
- def precrop_padding(self, input: torch.Tensor, flags: Optional[Dict[str, Any]] = None) -> torch.Tensor:
- flags = self.flags if flags is None else flags
+ def _compute_padding(self, shape: Tuple[int, ...], flags: Dict[str, Any]) -> List[List[int]]:
+ """Compute successive padding steps without modifying the input volume."""
+ padding_steps: List[List[int]] = []
+ depth, height, width = shape[-3:]
padding = flags["padding"]
if padding is not None:
if isinstance(padding, int):
@@ -120,18 +125,26 @@ class RandomCrop3D(GeometricAugmentationBase3D):
padding = [padding[0], padding[1], padding[2], padding[3], padding[4], padding[5]]
else:
raise ValueError(f"`padding` must be an integer, 3-element-list or 6-element-list. Got {padding}.")
- input = F.pad(input, padding, value=flags["fill"], mode=flags["padding_mode"])
+ padding_steps.append(padding)
+ depth += padding[4] + padding[5]
+ height += padding[2] + padding[3]
+ width += padding[0] + padding[1]
- if flags["pad_if_needed"] and input.shape[-3] < flags["size"][0]:
- padding = [0, 0, 0, 0, flags["size"][0] - input.shape[-3], flags["size"][0] - input.shape[-3]]
- input = F.pad(input, padding, value=flags["fill"], mode=flags["padding_mode"])
+ if flags["pad_if_needed"] and depth < flags["size"][0]:
+ padding_steps.append([0, 0, 0, 0, flags["size"][0] - depth, flags["size"][0] - depth])
- if flags["pad_if_needed"] and input.shape[-2] < flags["size"][1]:
- padding = [0, 0, (flags["size"][1] - input.shape[-2]), flags["size"][1] - input.shape[-2], 0, 0]
- input = F.pad(input, padding, value=flags["fill"], mode=flags["padding_mode"])
+ if flags["pad_if_needed"] and height < flags["size"][1]:
+ padding_steps.append([0, 0, flags["size"][1] - height, flags["size"][1] - height, 0, 0])
- if flags["pad_if_needed"] and input.shape[-1] < flags["size"][2]:
- padding = [flags["size"][2] - input.shape[-1], flags["size"][2] - input.shape[-1], 0, 0, 0, 0]
+ if flags["pad_if_needed"] and width < flags["size"][2]:
+ padding_steps.append([flags["size"][2] - width, flags["size"][2] - width, 0, 0, 0, 0])
+
+ return padding_steps
+
+ def precrop_padding(self, input: torch.Tensor, flags: Optional[Dict[str, Any]] = None) -> torch.Tensor:
+ flags = self.flags if flags is None else flags
+ # Keep fixed and automatic padding separate to preserve non-constant boundary values.
+ for padding in self._compute_padding(tuple(input.shape), flags):
input = F.pad(input, padding, value=flags["fill"], mode=flags["padding_mode"])
return input
@@ -153,13 +166,16 @@ class RandomCrop3D(GeometricAugmentationBase3D):
if not isinstance(transform, torch.Tensor):
raise TypeError(f"Expected the transform to be a torch.Tensor. Gotcha {type(transform)}")
+ input = self.precrop_padding(input, flags)
return crop_by_transform_mat3d(
input, transform, flags["size"], mode=flags["resample"].name.lower(), align_corners=flags["align_corners"]
)
- def forward(
- self, input: torch.Tensor, params: Optional[Dict[str, torch.Tensor]] = None, **kwargs: Any
- ) -> torch.Tensor:
- # TODO: need to align 2D implementations
- input = self.precrop_padding(input)
- return super().forward(input, params)
+ def forward_parameters(self, batch_shape: Tuple[int, ...]) -> Dict[str, torch.Tensor]:
+ # Sample crop coordinates on the padded canvas, while keeping the skip path unpadded.
+ padded_shape = list(batch_shape)
+ for padding in self._compute_padding(batch_shape, self.flags):
+ padded_shape[-3] += padding[4] + padding[5]
+ padded_shape[-2] += padding[2] + padding[3]
+ padded_shape[-1] += padding[0] + padding[1]
+ return super().forward_parameters(tuple(padded_shape))
diff --git a/tests/augmentation/_3d/test_random_crop_3d.py b/tests/augmentation/_3d/test_random_crop_3d.py
index 9b20d30c8..7ded05a4c 100644
--- a/tests/augmentation/_3d/test_random_crop_3d.py
+++ b/tests/augmentation/_3d/test_random_crop_3d.py
@@ -25,6 +25,71 @@ from testing.base import BaseTester
class TestRandomCrop3D(BaseTester):
+ @pytest.mark.parametrize("batch_size", [1, 2])
+ @pytest.mark.parametrize(
+ "padding,pad_if_needed,size",
+ [
+ (None, False, (2, 3, 4)),
+ (2, False, (2, 3, 4)),
+ ((1, 2, 3), False, (2, 3, 4)),
+ ((1, 2, 3, 4, 1, 2), False, (2, 3, 4)),
+ (None, True, (6, 7, 9)),
+ (1, True, (8, 9, 10)),
+ ],
+ )
+ def test_skipped_padding(self, batch_size, padding, pad_if_needed, size, device, dtype):
+ input_tensor = torch.arange(120, device=device, dtype=dtype).reshape(1, 1, 4, 5, 6)
+ input_tensor = input_tensor.repeat(batch_size, 1, 1, 1, 1).requires_grad_()
+ aug = RandomCrop3D(size, padding=padding, pad_if_needed=pad_if_needed, p=0.0)
+
+ output = aug(input_tensor)
+
+ self.assert_close(output, input_tensor, rtol=0, atol=0)
+ self.assert_close(aug.transform_matrix, torch.eye(4, device=device, dtype=dtype).expand(batch_size, 4, 4))
+ self.assert_close(aug(input_tensor, params=aug._params), input_tensor, rtol=0, atol=0)
+ output.sum().backward()
+ self.assert_close(input_tensor.grad, torch.ones_like(input_tensor), rtol=0, atol=0)
+
+ @pytest.mark.parametrize("shape", [(4, 5, 6), (2, 4, 5, 6), (2, 1, 4, 5, 6)])
+ @pytest.mark.parametrize("keepdim", [True, False])
+ def test_skipped_padding_keepdim(self, shape, keepdim, device, dtype):
+ input_tensor = torch.ones(shape, device=device, dtype=dtype)
+ aug = RandomCrop3D((6, 7, 9), padding=1, pad_if_needed=True, p=0.0, keepdim=keepdim)
+ expected = input_tensor if keepdim else input_tensor.reshape((1,) * (5 - len(shape)) + shape)
+
+ self.assert_close(aug(input_tensor), expected, rtol=0, atol=0)
+
+ def test_skipped_padding_params(self, device, dtype):
+ input_tensor = torch.arange(120, device=device, dtype=dtype).reshape(1, 1, 4, 5, 6)
+ aug = RandomCrop3D((2, 3, 4), padding=2, p=0.5)
+ # Use explicit decisions so the test does not depend on random draws.
+ params = aug.forward_parameters(input_tensor.shape)
+ params["batch_prob"] = torch.ones_like(params["batch_prob"])
+ assert aug(input_tensor, params=params).shape == (1, 1, 2, 3, 4)
+ params = {**params, "batch_prob": torch.zeros_like(params["batch_prob"])}
+
+ self.assert_close(aug(input_tensor, params=params), input_tensor, rtol=0, atol=0)
+ self.assert_close(aug.transform_matrix, torch.eye(4, device=device, dtype=dtype).unsqueeze(0))
+
+ @pytest.mark.parametrize("padding_mode", ["constant", "replicate", "reflect"])
+ @pytest.mark.parametrize("padding", [None, 1, (1, 2, 1), (1, 2, 1, 2, 1, 2)])
+ def test_padding_replay(self, padding, padding_mode, device, dtype):
+ torch.manual_seed(42)
+ input_tensor = torch.arange(120, device=device, dtype=dtype).reshape(1, 1, 4, 5, 6).repeat(2, 1, 1, 1, 1)
+ input_tensor = input_tensor / 120
+ # Nearest sampling makes integer-coordinate crops match slicing, even in half precision.
+ aug = RandomCrop3D(
+ (7, 8, 9), padding=padding, pad_if_needed=True, padding_mode=padding_mode, resample="nearest", p=1.0
+ )
+ padded = aug.precrop_padding(input_tensor)
+ output = aug(input_tensor)
+
+ assert output.shape == (2, 1, 7, 8, 9)
+ for index, box in enumerate(aug._params["src"]):
+ x, y, z = box[0].long().tolist()
+ self.assert_close(output[index], padded[index, :, z : z + 7, y : y + 8, x : x + 9], rtol=0, atol=0)
+ self.assert_close(aug(input_tensor, params=aug._params), output, rtol=0, atol=0)
+
# TODO: improve and implement more meaningful smoke tests e.g check for a consistent
# return values such a torch.Tensor variable.
@pytest.mark.xfail(reason="might fail under windows OS due to printing preicision.")