Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(augmentation)!: raise in RandomCrop for a size larger than the input without pad_if_needed (#6303)

Saksham Sharma0951420379ed
diff --git a/changelog.d/6303.breaking.md b/changelog.d/6303.breaking.md
new file mode 100644
index 000000000..4fbedba93
--- /dev/null
+++ b/changelog.d/6303.breaking.md
@@ -0,0 +1 @@
+`RandomCrop` with `pad_if_needed=False` now raises `ValueError` when `size` is larger than the input, after any explicit `padding`, on either axis. Previously it returned an interpolated upscale of the input under the crop's name: slice mode resized the available slice, and resample mode warped with a mis-scaled matrix that could blend in zero padding. It raises whether or not the batch is selected, so `p < 1` does not hide it. Pass `pad_if_needed=True` to pad the input up to the crop size, or crop to a size that fits. Replaying recorded `params` is unchanged.
diff --git a/kornia/augmentation/_2d/geometric/crop.py b/kornia/augmentation/_2d/geometric/crop.py
index b9051826c..a762e79ba 100644
--- a/kornia/augmentation/_2d/geometric/crop.py
+++ b/kornia/augmentation/_2d/geometric/crop.py
@@ -107,12 +107,13 @@ class RandomCrop(GeometricAugmentationBase2D):
and the mask is padded with zero unless ``extra_args[DataKey.MASK]`` sets its ``fill``; a scalar ``fill``
applies to both.
- With ``pad_if_needed=False``, an oversized request does not raise: slice mode resizes the available slice,
- and resample mode uses a mis-scaled warp that rescales both matrix axes and can blend in zero padding
- (`#4414 <https://github.com/kornia/kornia/issues/4414>`_). Slice mode scales only the matrix axes along
- which the request exceeds the canvas, as its resize does, and on the resize's half-pixel grid:
- ``x' = (x + 0.5) * W_out / W_in - 0.5`` along a stretched axis (likewise for ``y``). The scale is computed
- against the padded canvas, so a crop that fits after explicit padding gets no scale correction.
+ With ``pad_if_needed=False``, a ``size`` larger than the canvas after explicit ``padding`` raises
+ ``ValueError`` on either axis, whether or not the batch is selected; it used to return an upscale of the
+ input. A crop that fits once padded is unaffected. Replayed ``params`` whose ``src`` box exceeds the canvas
+ are not checked: slice mode resizes the available slice and scales only the matrix axes along which the box
+ exceeds the canvas, on the resize's half-pixel grid, ``x' = (x + 0.5) * W_out / W_in - 0.5`` along a
+ stretched axis (likewise for ``y``), and resample mode uses a warp that rescales both matrix axes and can
+ blend in zero padding.
Slice mode uses :func:`~kornia.geometry.transform.crop_by_indices` with its own defaults and ignores this
class's ``resample`` and ``align_corners``. Resample mode uses the configured interpolation and
@@ -450,6 +451,23 @@ class RandomCrop(GeometricAugmentationBase2D):
batch_shape[3] + input_pad[0] + input_pad[1], # original width + left + right padding
)
)
+ size = self.flags["size"]
+ # A malformed ``size`` is left to the crop generator, whose message names the argument. With
+ # ``pad_if_needed=True``, negative explicit padding can still leave the canvas short of ``size``; that case
+ # keeps its resize, as before.
+ if (
+ not self.flags["pad_if_needed"]
+ and isinstance(size, (tuple, list))
+ and len(size) == 2
+ and (size[0] > batch_shape_new[2] or size[1] > batch_shape_new[3])
+ ):
+ # A crop box past the canvas would be resampled into an upscale of the whole input.
+ raise ValueError(
+ f"RandomCrop size {tuple(size)} is larger than the input "
+ f"{tuple(batch_shape[2:4])} (padded canvas {tuple(batch_shape_new[2:4])}) with "
+ "pad_if_needed=False. Pass pad_if_needed=True to pad the input up to the crop size, "
+ "or crop to a smaller size."
+ )
padding_size = _constant_tensor(tuple(input_pad), dtype=torch.long).expand(batch_shape[0], -1)
# An empty batch has no padding rows and no pixels to pad. Keep its original canvas for inverse replay.
_params = super().forward_parameters(batch_shape if batch_shape[0] == 0 else batch_shape_new)
diff --git a/testing/augmentation/utils.py b/testing/augmentation/utils.py
index e9e64170c..90324b499 100644
--- a/testing/augmentation/utils.py
+++ b/testing/augmentation/utils.py
@@ -15,11 +15,34 @@
# limitations under the License.
#
+import copy
+
import torch
from testing.base import assert_close
+def oversized_random_crop_params(crop, batch_shape):
+ """Return the parameters ``crop.forward_parameters(batch_shape)`` gave before #4414 for an oversized crop.
+
+ ``RandomCrop`` now rejects a ``size`` larger than its padded canvas when ``pad_if_needed=False``, but a replay of
+ such parameters still reaches its oversized-crop matrix scaling. A twin whose extra bottom and right padding makes
+ its canvas exactly the crop size on an oversized axis draws the same crop box, because the generator places a box
+ at offset 0 on an axis it spans, either way, from the same random draws. The twin's padding fields are then
+ replaced by the crop's own.
+ """
+ padding = crop.compute_padding(batch_shape) # left, right, top, bottom
+ canvas = (batch_shape[-2] + padding[2] + padding[3], batch_shape[-1] + padding[0] + padding[1])
+ extra_h, extra_w = (max(s - c, 0) for s, c in zip(crop.flags["size"], canvas))
+ twin = copy.deepcopy(crop)
+ twin.flags["padding"] = (padding[0], padding[2], padding[1] + extra_w, padding[3] + extra_h)
+ params = twin.forward_parameters(batch_shape)
+ params["padding_size"] = params["padding_size"].new_tensor(padding).expand(batch_shape[0], -1)
+ params["forward_input_shape"] = params["forward_input_shape"].new_tensor((*batch_shape[:-2], *canvas))
+ params["input_size"] = params["input_size"].new_tensor(canvas).expand(batch_shape[0], -1)
+ return params
+
+
def reproducibility_test(input, seq):
"""Any tests failed here indicate the output cannot be reproduced by the same params."""
if isinstance(input, (tuple, list)):
diff --git a/tests/augmentation/container/test_augmentation_sequential.py b/tests/augmentation/container/test_augmentation_sequential.py
index 2eccd823e..9b4c93936 100644
--- a/tests/augmentation/container/test_augmentation_sequential.py
+++ b/tests/augmentation/container/test_augmentation_sequential.py
@@ -31,7 +31,7 @@ from kornia.geometry.bbox import bbox_to_mask
from kornia.geometry.boxes import Boxes
from kornia.geometry.transform import resize
-from testing.augmentation.utils import reproducibility_test
+from testing.augmentation.utils import oversized_random_crop_params, reproducibility_test
from testing.base import BaseTester, assert_close, supports_bilinear_2d_grid_sample
@@ -961,7 +961,8 @@ class TestAugmentationSequential:
],
)
@pytest.mark.parametrize(
- "augmentation", [K.RandomCrop((30, 30), padding=1, cropping_mode="resample", fill=0), K.Resize((30, 30))]
+ "augmentation",
+ [K.RandomCrop((30, 30), padding=1, pad_if_needed=True, cropping_mode="resample", fill=0), K.Resize((30, 30))],
)
def test_bbox(self, bbox, augmentation, device, dtype):
img = torch.rand((3, 3, 10, 10), device=device, dtype=dtype)
@@ -3085,9 +3086,17 @@ class TestAugmentationSequentialReplay:
image = torch.rand(2, 1, 16, 16, device=device, dtype=dtype)
keypoints = torch.tensor([[[3.0, 5.0], [9.0, 12.0]]], device=device, dtype=dtype).expand(2, -1, -1)
aug = K.AugmentationSequential(K.RandomCrop((20, 22), padding=1, p=1.0), data_keys=["input", "keypoints"])
- _, expected = aug(image, keypoints)
- params = aug._params
- aug(torch.rand(3, 1, 15, 17, device=device, dtype=dtype), keypoints[:1].expand(3, -1, -1))
+
+ # A forward call rejects the oversized crop (#4414), so draw its parameters for replay.
+ def oversized_params(shape):
+ return [
+ ParamItem(name, oversized_random_crop_params(crop, shape)) for name, crop in aug.named_children()
+ ]
+
+ params = oversized_params(image.shape)
+ _, expected = aug(image, keypoints, params=params)
+ other = torch.rand(3, 1, 15, 17, device=device, dtype=dtype)
+ aug(other, keypoints[:1].expand(3, -1, -1), params=oversized_params(other.shape))
replayed = aug(keypoints, params=params, data_keys=["keypoints"])
assert_close(replayed, expected)
diff --git a/tests/augmentation/container/test_random_crop.py b/tests/augmentation/container/test_random_crop.py
index 8b9a5257d..dfb8ce27a 100644
--- a/tests/augmentation/container/test_random_crop.py
+++ b/tests/augmentation/container/test_random_crop.py
@@ -23,10 +23,12 @@ import pytest
import torch
import kornia.augmentation as K
+from kornia.augmentation.container.params import ParamItem
from kornia.constants import DataKey
from kornia.geometry.boxes import Boxes
from kornia.geometry.keypoints import Keypoints
+from testing.augmentation.utils import oversized_random_crop_params
from testing.base import DYNAMO_UNAVAILABLE_REASON, BaseTester, dynamo_is_available
@@ -38,8 +40,10 @@ class TestRandomCropAnnotations(BaseTester):
seq = K.AugmentationSequential(
K.RandomCrop((size, size), p=1.0, cropping_mode="slice"), data_keys=["input", "bbox_xyxy"]
)
+ # A forward call rejects the oversized crop (#4414); its replay still stretches the oversized axis.
+ params = [ParamItem(name, oversized_random_crop_params(crop, x.shape)) for name, crop in seq.named_children()]
- out, out_boxes = seq(x, boxes)
+ out, out_boxes = seq(x, boxes, params=params)
x_offset = out[0, 0, 0, 0]
self.assert_close(out_boxes[0, 0, [0, 2]], boxes[0, 0, [0, 2]] - x_offset)
@@ -65,7 +69,10 @@ class TestRandomCropAnnotations(BaseTester):
# An oversized axis starts at 0 and is stretched; an axis that fits is cropped, here from 1.
x0, y0 = float(w < width), float(h < height)
x1, y1 = x0 + min(w, width) - 1, y0 + min(h, height) - 1
- params = seq.forward_parameters(ramp.shape)
+ # A forward call rejects the oversized crop (#4414); its replay still stretches the oversized axis.
+ params = [
+ ParamItem(name, oversized_random_crop_params(crop, ramp.shape)) for name, crop in seq.named_children()
+ ]
params[0].data["src"] = ramp.new_tensor(
[[[x0, y0], [x0 + w - 1, y0], [x0 + w - 1, y0 + h - 1], [x0, y0 + h - 1]]]
)
diff --git a/tests/augmentation/test_augmentation.py b/tests/augmentation/test_augmentation.py
index 8d49e9019..21a00aee2 100644
--- a/tests/augmentation/test_augmentation.py
+++ b/tests/augmentation/test_augmentation.py
@@ -89,6 +89,7 @@ from kornia.core.utils import _torch_inverse_cast
from kornia.geometry import create_meshgrid, transform_points
from testing.augmentation.datasets import DummyMPDataset
+from testing.augmentation.utils import oversized_random_crop_params
from testing.base import DYNAMO_UNAVAILABLE_REASON, BaseTester, dynamo_is_available
from testing.overwrite import default_with_one_parameter_changed
@@ -3642,7 +3643,8 @@ class TestRandomCrop(BaseTester):
image = torch.zeros(1, 1, *input_size, device=device, dtype=dtype)
aug = RandomCrop(size, cropping_mode="slice", p=1.0)
- params = aug.forward_parameters(image.shape)
+ # A forward call rejects an oversized crop (#4414); its replayed parameters still reach the scaling.
+ params = oversized_random_crop_params(aug, image.shape)
monkeypatch.setattr(crop_module, "is_exporting", lambda: exporting)
transform = aug.compute_transformation(image, params, aug.flags)
@@ -3670,7 +3672,8 @@ class TestRandomCrop(BaseTester):
image = torch.zeros(1, 1, *input_size, device=device, dtype=dtype)
aug = RandomCrop(size, cropping_mode="slice", p=1.0)
- params = aug.forward_parameters(image.shape)
+ # A forward call rejects an oversized crop (#4414); its replayed parameters still reach the scaling.
+ params = oversized_random_crop_params(aug, image.shape)
monkeypatch.setattr(crop_module, "is_exporting", lambda: exporting)
transform = aug.compute_transformation(image, params, aug.flags)
diff --git a/tests/augmentation/test_augmentation_compile.py b/tests/augmentation/test_augmentation_compile.py
index b06743747..56f8f8d77 100644
--- a/tests/augmentation/test_augmentation_compile.py
+++ b/tests/augmentation/test_augmentation_compile.py
@@ -26,6 +26,7 @@ from torch._dynamo.testing import CompileCounter, CompileCounterWithBackend
import kornia.augmentation as K
+from testing.augmentation.utils import oversized_random_crop_params
from testing.base import BaseTester, dynamo_is_available
@@ -389,7 +390,9 @@ class TestRandomCropCompile(BaseTester):
input = torch.rand(2, 3, 12, 15, device=device, dtype=dtype, requires_grad=True)
fn = torch_optimizer(aug)
for _ in range(3):
- params = aug.forward_parameters(input.shape)
+ # (19, 23) without pad_if_needed exceeds the 14 x 17 padded canvas, which a forward call rejects (#4414);
+ # its replayed parameters still reach the oversized-crop scaling.
+ params = oversized_random_crop_params(aug, input.shape)
expected = aug(input, params=params)
actual = fn(input, params=params)
self.assert_close(actual, expected)
diff --git a/tests/augmentation/test_conventions_geometric_crop.py b/tests/augmentation/test_conventions_geometric_crop.py
index 93c2a1742..5e81173d1 100644
--- a/tests/augmentation/test_conventions_geometric_crop.py
+++ b/tests/augmentation/test_conventions_geometric_crop.py
@@ -21,8 +21,10 @@ import pytest
import torch
import kornia.augmentation as K
+from kornia.augmentation.container.params import ParamItem
from kornia.constants import DataKey, Resample
+from testing.augmentation.utils import oversized_random_crop_params
from testing.base import BaseTester, supports_2d_border_padding, supports_bilinear_2d_grid_sample
@@ -222,7 +224,10 @@ class TestGeometricCropConventions(BaseTester):
boxes = image.new_tensor([[[[1, 1], [2, 1], [2, 2], [1, 2]]]])
crop = K.RandomCrop((6, 4), padding=1, cropping_mode=mode, p=1.0)
seq = K.AugmentationSequential(crop, data_keys=["input", "keypoints", "bbox"])
- params = seq.forward_parameters(image.shape)
+ # A forward call rejects the oversized crop (#4414); its replay still scales against the padded canvas.
+ params = [
+ ParamItem(name, oversized_random_crop_params(child, image.shape)) for name, child in seq.named_children()
+ ]
params[0].data["src"] = image.new_tensor([[[0, 0], [3, 0], [3, 5], [0, 5]]])
params[0].data["dst"] = image.new_tensor([[[0, 0], [3, 0], [3, 5], [0, 5]]])
output, out_points, out_boxes = seq(image, points, boxes, params=params)
@@ -272,14 +277,48 @@ class TestGeometricCropConventions(BaseTester):
self.assert_close(output[0, 0, 0], image.new_tensor([0, 0, 0, 0]))
assert output.shape == (1, 1, 6, 4)
+ @pytest.mark.parametrize("p", [1.0, 0.0])
@pytest.mark.parametrize("mode", ["slice", "resample"])
@pytest.mark.parametrize("size", [(10, 10), (10, 4), (4, 10)])
- def test_wart_random_crop_oversized_rescales_matrix_axes_4414(self, device, dtype, mode, size):
- """Resample mode rescales both matrix axes (#4414); slice mode only the oversized one, as its resize (#5463),
- on the resize's half-pixel grid (#5481)."""
+ def test_convention_random_crop_oversized_size_raises_4414(self, device, dtype, mode, size, p):
+ # #4414: a crop larger than the input without pad_if_needed returned an upscale of the input. It raises
+ # whether or not the batch is selected, so a p < 1 pipeline does not fail only on some calls.
+ image = torch.rand(2, 1, 6, 8, device=device, dtype=dtype)
+ crop = K.RandomCrop(size, cropping_mode=mode, p=p)
+ with pytest.raises(
+ ValueError, match=r"size \(\d+, \d+\) is larger than the input \(6, 8\).*pad_if_needed=True"
+ ):
+ crop(image)
+ with pytest.raises(ValueError, match="pad_if_needed"):
+ crop.forward_parameters(image.shape)
+ with pytest.raises(ValueError, match="pad_if_needed"):
+ K.AugmentationSequential(crop, data_keys=["input", "keypoints"])(image, image.new_zeros(2, 1, 2))
+
+ @pytest.mark.parametrize("mode", ["slice", "resample"])
+ def test_convention_random_crop_size_is_checked_against_the_padded_canvas_4414(self, device, dtype, mode):
+ image = torch.rand(1, 1, 6, 8, device=device, dtype=dtype)
+ # One pixel of padding per side leaves an 8 x 10 canvas: too small for 10 x 10, enough for 8 x 10.
+ with pytest.raises(ValueError, match=r"padded canvas \(8, 10\)"):
+ K.RandomCrop((10, 10), padding=1, cropping_mode=mode, p=1.0)(image)
+ assert K.RandomCrop((8, 10), padding=1, cropping_mode=mode, p=1.0)(image).shape == (1, 1, 8, 10)
+ # (1, 2) pads each side of the width by one and of the height by two, a 10 x 10 canvas.
+ assert K.RandomCrop((10, 10), padding=(1, 2), cropping_mode=mode, p=1.0)(image).shape == (1, 1, 10, 10)
+ assert K.RandomCrop((10, 10), pad_if_needed=True, cropping_mode=mode, p=1.0)(image).shape == (1, 1, 10, 10)
+ assert K.RandomCrop((6, 8), cropping_mode=mode, p=1.0)(image).shape == (1, 1, 6, 8)
+ # pad_if_needed only pads an input smaller than size, so negative explicit padding can leave a 6 x 7 canvas;
+ # with pad_if_needed=True that is not rejected, and the crop keeps its resize.
+ for padding in [(-1, 0, 0, 0), -1]:
+ crop = K.RandomCrop((6, 8), padding=padding, pad_if_needed=True, cropping_mode=mode, p=1.0)
+ assert crop(image).shape == (1, 1, 6, 8)
+
+ @pytest.mark.parametrize("mode", ["slice", "resample"])
+ @pytest.mark.parametrize("size", [(10, 10), (10, 4), (4, 10)])
+ def test_convention_random_crop_oversized_replay_rescales_matrix_axes_4414(self, device, dtype, mode, size):
+ """Replayed oversized params are not checked (#4414): resample mode rescales both matrix axes; slice mode only
+ the oversized one, as its resize (#5463), on the resize's half-pixel grid (#5481)."""
image = torch.arange(48, device=device, dtype=dtype).reshape(1, 1, 6, 8) / 48
crop = K.RandomCrop(size, cropping_mode=mode, p=1.0)
- params = crop.forward_parameters(image.shape)
+ params = oversized_random_crop_params(crop, image.shape)
h, w = size
left, top = (2, 0) if size == (10, 4) else ((0, 1) if size == (4, 10) else (0, 0))
params["src"] = image.new_tensor(
@@ -358,7 +397,8 @@ class TestGeometricCropConventions(BaseTester):
ys, xs = torch.meshgrid(torch.arange(5), torch.arange(5), indexing="ij")
ramp = ((xs + 2 * ys) / 15)[None, None].to(device, dtype)
crop = K.RandomCrop((10, 10), p=1.0, cropping_mode=mode)
- restored = crop.inverse(crop(ramp))
+ # A forward call rejects the oversized crop (#4414); the inverse of its replay still undoes the scale.
+ restored = crop.inverse(crop(ramp, params=oversized_random_crop_params(crop, ramp.shape)))
# Slice mode upsamples on the half-pixel grid, which clamps at the border.
self.assert_close(restored[..., 1:-1, 1:-1], ramp[..., 1:-1, 1:-1], low_tolerance=True)
@@ -477,7 +517,11 @@ class TestGeometricCropConventions(BaseTester):
)
ramp = ramp.expand(2, -1, -1, -1).contiguous()
crop = make_crop(align_corners)
- restored = crop.inverse(crop(ramp))
+ if isinstance(crop, K.RandomCrop):
+ # A forward call rejects an oversized crop (#4414); its replay still records the stretched matrix.
+ restored = crop.inverse(crop(ramp, params=oversized_random_crop_params(crop, ramp.shape)))
+ else:
+ restored = crop.inverse(crop(ramp))
assert restored.shape == ramp.shape
# Canvas pixels that map at least one pixel inside the crop output.
# Mapped on the CPU in float64 (MPS has no float64).