Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(augmentation): make RandomResizedCrop's candidate test and fallback follow torchvision (#4823)

Aditya Malkarcfe2b58203f4
diff --git a/changelog.d/4791.fixed.md b/changelog.d/4791.fixed.md
index 4b049da59..e5f65ad97 100644
--- a/changelog.d/4791.fixed.md
+++ b/changelog.d/4791.fixed.md
@@ -1 +1 @@
-The `kornia.augmentation` Convention blocks outside the 2D intensity classes are shorter and state each rule once. `RandomEqualize3D` now documents its out-of-range check as raising on every backend; the old text said MPS skipped it. Each known defect is stated with its tracking issue, including the new #4775, #4776, #4777, #4787, #4801, #4802, #4804, #4805, #4809, #4814 and #4815.
+The `kornia.augmentation` Convention blocks outside the 2D intensity classes are shorter and state each rule once. `RandomEqualize3D` now documents its out-of-range check as raising on every backend; the old text said MPS skipped it. Each known defect is stated with its tracking issue, including the new #4775, #4776, #4777, #4787, #4801, #4802, #4804, #4805, #4809 and #4815.
diff --git a/changelog.d/4823.breaking.md b/changelog.d/4823.breaking.md
new file mode 100644
index 000000000..9b122d893
--- /dev/null
+++ b/changelog.d/4823.breaking.md
@@ -0,0 +1,12 @@
+`RandomResizedCrop` now follows torchvision's `get_params` in two places. A candidate crop may equal the input's
+width or height; it used to have to be strictly smaller on both axes. When none of the ten candidates fits, the
+fallback compares the input's width/height with both `min(ratio)` and `max(ratio)`: an input already in range is
+kept whole, a narrower one keeps its full width and a wider one its full height. It used to compare height/width with
+`min(ratio)` only, which could return a crop outside both `scale` and `ratio`. `scale=(1.0, 1.0)` therefore keeps an
+input whose width/height is within `ratio` whole; with the default `ratio` it used to crop every square or portrait
+input and most landscape ones (an 8x6 input gave a 4x6 crop, a 7x8 input a 6x8 crop). Like torchvision, it also
+accepts a candidate rounded a pixel short on the longer side: an 8x6 input gives 7x6 in about 18% of draws, and a
+6x8 input, which used to be kept whole every time, gives 6x7 as often. Seeded crops change for configurations that
+reach the fallback (a `scale` close to `(1.0, 1.0)`), and for draws where a candidate exactly matches the input width
+or height: about 1% of draws with the default `scale` and `ratio` on 224x224 or 256x192 inputs, more on small images
+(7% on 32x32). The fallback crop is still placed at a random position, where torchvision centres it. Fixes #4814.
diff --git a/kornia/augmentation/_2d/geometric/resized_crop.py b/kornia/augmentation/_2d/geometric/resized_crop.py
index 23b3f66f1..c72bab999 100644
--- a/kornia/augmentation/_2d/geometric/resized_crop.py
+++ b/kornia/augmentation/_2d/geometric/resized_crop.py
@@ -66,10 +66,12 @@ class RandomResizedCrop(GeometricAugmentationBase2D):
(`#4417 <https://github.com/kornia/kornia/issues/4417>`_). ``p`` selects or skips the whole batch together.
Within a selected batch, the generator tries ten candidate crops per image, sampling area fractions from
``scale`` and width/height ratios from ``ratio`` (shared with ``same_on_batch=True``), and resizes the first
- that fits to the requested output size. A candidate must be strictly smaller than the input on both axes,
- and the fallback compares height/width, not width/height, with ``min(ratio)``, so ``scale=(1.0, 1.0)``
- never keeps a square or portrait image and can leave both ranges: an 8x6 input gives a 4x6 crop where
- torchvision keeps 8x6 (`#4814 <https://github.com/kornia/kornia/issues/4814>`_).
+ that fits to the requested output size. As in torchvision's ``get_params``, a candidate may equal the input,
+ and when none fits the fallback keeps an input whose width/height is within ``ratio`` whole, or else its full
+ width (input narrower than ``min(ratio)``) or its full height (wider than ``max(ratio)``). So
+ ``scale=(1.0, 1.0)`` keeps an input within ``ratio`` whole, except that a candidate rounded a pixel or two
+ short on the longer side also fits (8x6 gives 7x6 in about 18% of draws, as in torchvision). Unlike
+ torchvision, which centres the fallback crop, it is placed at a random position like any other crop.
Both cropping modes use the configured interpolation and ``align_corners``, so slice mode raises for
``resample="nearest"`` unless ``align_corners=None``
@@ -91,13 +93,13 @@ class RandomResizedCrop(GeometricAugmentationBase2D):
>>> aug = RandomResizedCrop(size=(3, 3), scale=(3., 3.), ratio=(2., 2.), p=1., cropping_mode="resample")
>>> out = aug(inputs)
>>> out
- tensor([[[[1.0000, 1.5000, 2.0000],
- [4.0000, 4.5000, 5.0000],
- [7.0000, 7.5000, 8.0000]]]])
+ tensor([[[[3.0000, 4.0000, 5.0000],
+ [4.5000, 5.5000, 6.5000],
+ [6.0000, 7.0000, 8.0000]]]])
>>> aug.inverse(out, padding_mode="border")
- tensor([[[[1., 1., 2.],
- [4., 4., 5.],
- [7., 7., 8.]]]])
+ tensor([[[[3., 4., 5.],
+ [3., 4., 5.],
+ [6., 7., 8.]]]])
To apply the exact augmenation again, you may take the advantage of the previous parameter state:
>>> input = torch.randn(1, 3, 32, 32)
diff --git a/kornia/augmentation/random_generator/_2d/crop.py b/kornia/augmentation/random_generator/_2d/crop.py
index de4675273..bb87eb232 100644
--- a/kornia/augmentation/random_generator/_2d/crop.py
+++ b/kornia/augmentation/random_generator/_2d/crop.py
@@ -264,8 +264,8 @@ class ResizedCropGenerator(CropGenerator):
w = torch.sqrt(area * aspect_ratio).round().floor()
h = torch.sqrt(area / aspect_ratio).round().floor()
- # Element-wise w, h condition
- cond = ((0 < w) * (w < size[1]) * (0 < h) * (h < size[0])).int()
+ # Element-wise w, h condition. A candidate may equal the input size, as in torchvision's get_params.
+ cond = ((0 < w) * (w <= size[1]) * (0 < h) * (h <= size[0])).int()
# torch.argmax is not reproducible across devices: https://github.com/pytorch/pytorch/issues/17738
# Here, we will select the first occurrence of the duplicated elements.
@@ -275,19 +275,22 @@ class ResizedCropGenerator(CropGenerator):
h_out = h[torch.arange(0, batch_size, device=_device, dtype=torch.long), argmax_dim1]
w_out = w[torch.arange(0, batch_size, device=_device, dtype=torch.long), argmax_dim1]
- # Center-crop fallback for samples where no candidate crop fit (``cond_bool`` False). The
+ # Fallback crop size for samples where no candidate crop fit (``cond_bool`` False). The
# fallback size is a compile-time constant (from ``size`` and ``self.ratio``), so compute it
# unconditionally and select branchlessly with ``torch.where`` β€” dropping the
# ``if not cond_bool.all()`` device sync keeps the generator torch.compile fullgraph. When
# every candidate fit, ``where`` returns ``h_out``/``w_out`` unchanged (byte-identical).
- in_ratio = float(size[0]) / float(size[1])
+ # As in torchvision's get_params: ``ratio`` is width / height, so an input narrower than min(ratio) keeps
+ # its full width, one wider than max(ratio) keeps its full height, and one in range is kept whole.
+ in_ratio = float(size[1]) / float(size[0])
_min = float(self.ratio.min()) if isinstance(self.ratio, torch.Tensor) else min(self.ratio)
+ _max = float(self.ratio.max()) if isinstance(self.ratio, torch.Tensor) else max(self.ratio)
if in_ratio < _min:
- h_ct = torch.full((), size[0], device=_device, dtype=_dtype)
- w_ct = torch.round(h_ct / _min)
- elif in_ratio > _min:
w_ct = torch.full((), size[1], device=_device, dtype=_dtype)
- h_ct = torch.round(w_ct * _min)
+ h_ct = torch.round(w_ct / _min)
+ elif in_ratio > _max:
+ h_ct = torch.full((), size[0], device=_device, dtype=_dtype)
+ w_ct = torch.round(h_ct * _max)
else: # whole image
h_ct = torch.full((), size[0], device=_device, dtype=_dtype)
w_ct = torch.full((), size[1], device=_device, dtype=_dtype)
diff --git a/tests/augmentation/test_augmentation.py b/tests/augmentation/test_augmentation.py
index b92bd14c1..7d3545d43 100644
--- a/tests/augmentation/test_augmentation.py
+++ b/tests/augmentation/test_augmentation.py
@@ -3984,9 +3984,9 @@ class TestRandomResizedCrop(BaseTester):
[
[
[
- [1.0000, 1.5000, 2.0000],
- [4.0000, 4.5000, 5.0000],
- [7.0000, 7.5000, 8.0000],
+ [3.0000, 4.0000, 5.0000],
+ [4.5000, 5.5000, 6.5000],
+ [6.0000, 7.0000, 8.0000],
]
]
],
@@ -3994,13 +3994,14 @@ class TestRandomResizedCrop(BaseTester):
dtype=dtype,
)
rrc = RandomResizedCrop(size=(3, 3), scale=(3.0, 3.0), ratio=(2.0, 2.0))
- # It will crop a size of (3, 3) from the aspect ratio implementation of torch
+ # No candidate fits (area 3x the image), so the fallback applies: with width / height = 2 it keeps the
+ # full width, a 2 x 3 crop, as torchvision's get_params does (#4814).
out = rrc(inp)
self.assert_close(out, expected)
torch.manual_seed(0)
inversed = torch.tensor(
- [[[[0.0, 1.0, 2.0], [0.0, 4.0, 5.0], [0.0, 7.0, 8.0]]]],
+ [[[[0.0, 0.0, 0.0], [3.0, 4.0, 5.0], [6.0, 7.0, 8.0]]]],
device=device,
dtype=dtype,
)
@@ -4022,10 +4023,10 @@ class TestRandomResizedCrop(BaseTester):
[
[
[
- [1.0000, 1.3333, 1.6667, 2.0000],
- [3.0000, 3.3333, 3.6667, 4.0000],
- [5.0000, 5.3333, 5.6667, 6.0000],
- [7.0000, 7.3333, 7.6667, 8.0000],
+ [3.0000, 3.6667, 4.3333, 5.0000],
+ [4.0000, 4.6667, 5.3333, 6.0000],
+ [5.0000, 5.6667, 6.3333, 7.0000],
+ [6.0000, 6.6667, 7.3333, 8.0000],
]
]
],
@@ -4034,14 +4035,15 @@ class TestRandomResizedCrop(BaseTester):
)
rrc = RandomResizedCrop(size=(4, 4), scale=(3.0, 3.0), ratio=(2.0, 2.0))
- # It will crop a size of (3, 3) from the aspect ratio implementation of torch
+ # No candidate fits (area 3x the image), so the fallback applies: with width / height = 2 it keeps the
+ # full width, a 2 x 3 crop, as torchvision's get_params does (#4814).
out = rrc(inp)
assert out.shape == torch.Size([1, 1, 4, 4])
self.assert_close(out, exp, low_tolerance=True)
torch.manual_seed(0)
inversed = torch.tensor(
- [[[[0.0, 1.0, 2.0], [0.0, 4.0, 5.0], [0.0, 7.0, 8.0]]]],
+ [[[[0.0, 0.0, 0.0], [3.0, 4.0, 5.0], [6.0, 7.0, 8.0]]]],
device=device,
dtype=dtype,
)
@@ -4063,16 +4065,16 @@ class TestRandomResizedCrop(BaseTester):
[
[
[
- [1.0000, 1.5000, 2.0000],
- [4.0000, 4.5000, 5.0000],
- [7.0000, 7.5000, 8.0000],
+ [3.0000, 4.0000, 5.0000],
+ [4.5000, 5.5000, 6.5000],
+ [6.0000, 7.0000, 8.0000],
]
],
[
[
- [0.0000, 0.5000, 1.0000],
- [3.0000, 3.5000, 4.0000],
- [6.0000, 6.5000, 7.0000],
+ [0.0000, 1.0000, 2.0000],
+ [1.5000, 2.5000, 3.5000],
+ [3.0000, 4.0000, 5.0000],
]
],
],
@@ -4080,15 +4082,16 @@ class TestRandomResizedCrop(BaseTester):
dtype=dtype,
)
rrc = RandomResizedCrop(size=(3, 3), scale=(3.0, 3.0), ratio=(2.0, 2.0))
- # It will crop a size of (2, 2) from the aspect ratio implementation of torch
+ # No candidate fits (area 3x the image), so the fallback applies: with width / height = 2 it keeps the
+ # full width, a 2 x 3 crop, as torchvision's get_params does (#4814).
out = rrc(inp)
self.assert_close(out, expected)
torch.manual_seed(0)
inversed = torch.tensor(
[
- [[[0.0, 1.0, 2.0], [0.0, 4.0, 5.0], [0.0, 7.0, 8.0]]],
- [[[0.0, 1.0, 0.0], [3.0, 4.0, 0.0], [6.0, 7.0, 0.0]]],
+ [[[0.0, 0.0, 0.0], [3.0, 4.0, 5.0], [6.0, 7.0, 8.0]]],
+ [[[0.0, 1.0, 2.0], [3.0, 4.0, 5.0], [0.0, 0.0, 0.0]]],
],
device=device,
dtype=dtype,
diff --git a/tests/augmentation/test_conventions_geometric_crop.py b/tests/augmentation/test_conventions_geometric_crop.py
index 0ffd69e1f..151236342 100644
--- a/tests/augmentation/test_conventions_geometric_crop.py
+++ b/tests/augmentation/test_conventions_geometric_crop.py
@@ -299,13 +299,45 @@ class TestGeometricCropConventions(BaseTester):
self.assert_close(nearest(x, params=params), x)
@pytest.mark.device_agnostic
- def test_wart_random_resized_crop_fallback_leaves_scale_and_ratio_4814(self):
- # #4814: no candidate may equal the input and the fallback compares H / W with min(ratio), so scale=(1, 1)
- # crops a portrait or square image; torchvision's get_params keeps 8 x 6 and 8 x 8. Flips on either fix.
+ @pytest.mark.parametrize(
+ "shape,crops",
+ [
+ ((8, 8), {(8, 8)}),
+ ((8, 6), {(8, 6), (7, 6)}),
+ ((6, 8), {(6, 8), (6, 7)}),
+ ((7, 8), {(7, 8), (7, 7)}),
+ ],
+ ids=["square", "portrait", "landscape_at_max_ratio", "landscape"],
+ )
+ def test_convention_random_resized_crop_full_scale_keeps_the_whole_image_4814(self, shape, crops):
+ # #4814: a candidate used to have to be strictly smaller than the input, and the fallback compared
+ # H / W with min(ratio), so scale=(1, 1) cropped square, portrait and most landscape inputs
+ # (8 x 6 -> 4 x 6, 7 x 8 -> 6 x 8). As in torchvision's get_params, a candidate may equal the input, and
+ # one that rounds a pixel short on the longer side (7 x 6 for 8 x 6, in 18% of draws) also fits.
+ torch.manual_seed(0)
+ src = K.RandomResizedCrop((4, 4), scale=(1.0, 1.0), p=1.0).forward_parameters((256, 1, *shape))["src"]
+ heights = (src[:, 2, 1] - src[:, 1, 1] + 1).long().tolist()
+ widths = (src[:, 1, 0] - src[:, 0, 0] + 1).long().tolist()
+ assert set(zip(heights, widths)) == crops
+
+ @pytest.mark.device_agnostic
+ @pytest.mark.parametrize(
+ "shape,ratio,crop",
+ [
+ ((224, 224), (1.5, 2.0), (149, 224)),
+ ((100, 60), (3.0 / 4.0, 4.0 / 3.0), (80, 60)),
+ ((60, 100), (0.5, 0.75), (60, 45)),
+ ((60, 100), torch.tensor([0.5, 0.75]), (60, 45)),
+ ],
+ ids=["narrower_than_min_ratio", "portrait_narrower_than_min_ratio", "wider_than_max_ratio", "tensor_ratio"],
+ )
+ def test_convention_random_resized_crop_fallback_follows_torchvision_4814(self, shape, ratio, crop):
+ # #4814: when no candidate fits, the crop size matches torchvision's get_params. ``ratio`` is width / height:
+ # an input narrower than min(ratio) keeps its width, one wider than max(ratio) keeps its height.
torch.manual_seed(0)
- for shape, crop in (((8, 6), (4, 6)), ((8, 8), (6, 8))):
- src = K.RandomResizedCrop((4, 4), scale=(1.0, 1.0), p=1.0).forward_parameters((1, 1, *shape))["src"]
- assert ((src[0, 2, 1] - src[0, 1, 1]).item() + 1, (src[0, 1, 0] - src[0, 0, 0]).item() + 1) == crop
+ aug = K.RandomResizedCrop((4, 4), scale=(1.0, 1.0), ratio=ratio, p=1.0)
+ src = aug.forward_parameters((1, 1, *shape))["src"]
+ assert ((src[0, 2, 1] - src[0, 1, 1]).item() + 1, (src[0, 1, 0] - src[0, 0, 0]).item() + 1) == crop
@pytest.mark.device_agnostic
def test_wart_crop_siblings_disagree_on_integer_size_4417(self):