Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

perf(geometry): copy crop_by_indices rows with one cat when every slice matches size (#4987)

Aditya Malkarcd24be6d4da8
diff --git a/changelog.d/4987.fixed.md b/changelog.d/4987.fixed.md
new file mode 100644
index 000000000..1c86da873
--- /dev/null
+++ b/changelog.d/4987.fixed.md
@@ -0,0 +1 @@
+`crop_by_indices` joins the per-row crops with one `torch.cat` when every row's slice already matches `size`, instead of a `copy_` per row (#4531): one copy kernel per batch instead of one per sample, with the same values and the same default memory format. `RandomCrop` in slice mode always takes this path; rows that need `shape_compensation` still go through the per-row loop, and MPS keeps the per-row copies, which are faster there. A list `size`, as `RandomCrop([h, w])` passes it, no longer resizes every row to its own size.
diff --git a/kornia/geometry/transform/crop2d.py b/kornia/geometry/transform/crop2d.py
index 9bea16011..33fb133da 100644
--- a/kornia/geometry/transform/crop2d.py
+++ b/kornia/geometry/transform/crop2d.py
@@ -506,6 +506,11 @@ def crop_by_indices(
# bicubic) and cannot gather from an empty batch; ``interpolate`` rejects ``align_corners`` for nearest.
return _compiled_slice_resize(input_tensor, src_box, size, interpolation, align_corners)
+ # ``RandomCrop`` passes its ``size`` through as given, and a list never compares equal to a ``torch.Size``:
+ # every slice would look mismatched and be resized to its own size.
+ if size is not None:
+ size = (size[0], size[1])
+
# Move the four coordinate columns to Python in a single device sync (one ``tolist`` over a
# stacked tensor) instead of a ``unique`` per column plus a device-to-host ``int(...)`` inside
# every loop iteration β€” the coordinates index Python-level slicing, so they must be host ints.
@@ -545,13 +550,22 @@ def crop_by_indices(
# path the rows are also joined with one ``cat``: writing them into ``out`` row by row would make the
# backward clone the gradient of the whole output once per row.
rows = input_tensor.unbind(0) if B > 1 and input_tensor.requires_grad and torch.is_grad_enabled() else None
+ slices = [
+ input_tensor[i : i + 1, :, y1l[i] : y2l[i], x1l[i] : x2l[i]]
+ if rows is None
+ else rows[i][None, :, y1l[i] : y2l[i], x1l[i] : x2l[i]]
+ for i in range(B)
+ ]
+ # When every row's slice already has the requested size (always the case for RandomCrop), join the
+ # views with one ``cat``: one copy kernel for the batch instead of a ``copy_`` per row (#4531).
+ # ``contiguous`` keeps the result in the default memory format, as the ``torch.empty`` below does,
+ # when the input is channels-last. MPS keeps the per-row copies: on an M1 the ``cat`` of strided
+ # views ran at 0.75-0.96x their speed without gradients (B = 4-64, 256Β² -> 128Β², #4987).
+ if B > 0 and input_tensor.device.type != "mps" and all(crop.shape[-2:] == size for crop in slices):
+ return torch.cat(slices).contiguous()
out = torch.empty(B, C, *size, device=input_tensor.device, dtype=input_tensor.dtype) if rows is None else None
crops: list[torch.Tensor] = []
- for i in range(B):
- if rows is None:
- _out = input_tensor[i : i + 1, :, y1l[i] : y2l[i], x1l[i] : x2l[i]]
- else:
- _out = rows[i][None, :, y1l[i] : y2l[i], x1l[i] : x2l[i]]
+ for i, _out in enumerate(slices):
if _out.shape[-2:] != size:
if shape_compensation == "resize":
_out = resize(
diff --git a/tests/geometry/transform/test_crop2d.py b/tests/geometry/transform/test_crop2d.py
index a559166ea..d2bb84f16 100644
--- a/tests/geometry/transform/test_crop2d.py
+++ b/tests/geometry/transform/test_crop2d.py
@@ -836,6 +836,80 @@ class TestCropByIndices(BaseTester):
# the plain-copy path, and 'pad'/'resize' agree there too.
self.assert_close(out_resize[1], out_pad[1])
+ @staticmethod
+ def _per_row_boxes_4531(device):
+ # Four 3x4 (h x w) boxes at different positions in a 6x7 image, as RandomCrop produces:
+ # the image's top-left and bottom-right corners, and two interior positions.
+ corners = [(0, 0), (3, 3), (1, 2), (2, 0)] # (x1, y1)
+ boxes = [[[x, y], [x + 3, y], [x + 3, y + 2], [x, y + 2]] for x, y in corners]
+ return torch.tensor(boxes, device=device, dtype=torch.int64), corners
+
+ def test_crop_by_indices_per_row_boxes_of_the_requested_size_4531(self, device, dtype):
+ # Rows whose slices all match `size` are joined with one `cat` instead of a copy per row
+ # (#4531). Each row must still be its own box's exact slice.
+ inp = torch.rand(4, 2, 6, 7, device=device, dtype=dtype)
+ src_box, corners = self._per_row_boxes_4531(device)
+
+ out = kornia.geometry.transform.crop_by_indices(inp, src_box, size=(3, 4))
+
+ expected = torch.stack([inp[i, :, y : y + 3, x : x + 4] for i, (x, y) in enumerate(corners)])
+ self.assert_close(out, expected, atol=0.0, rtol=0.0)
+ assert out.is_contiguous()
+
+ def test_crop_by_indices_channels_last_input_gives_a_contiguous_output_4531(self, device, dtype):
+ # `torch.cat` of channels-last views is channels-last; the per-row loop wrote into a
+ # default-format `torch.empty`, so the output format must not depend on the input's.
+ inp = torch.rand(4, 3, 6, 7, device=device, dtype=dtype)
+ src_box, _ = self._per_row_boxes_4531(device)
+
+ out = kornia.geometry.transform.crop_by_indices(
+ inp.contiguous(memory_format=torch.channels_last), src_box, size=(3, 4)
+ )
+
+ assert out.is_contiguous()
+ self.assert_close(out, kornia.geometry.transform.crop_by_indices(inp, src_box, size=(3, 4)), atol=0.0, rtol=0.0)
+
+ @pytest.mark.parametrize("size", [(3, 4), [3, 4]])
+ def test_crop_by_indices_copies_once_per_batch_4531(self, size, device, dtype):
+ # The per-row loop issued one `copy_` per row, so its kernel launches grew with the batch;
+ # rows that already match `size` are now copied by a single `cat`, except on MPS, where the
+ # row copies are faster. A list `size`, as RandomCrop passes it, must match the slices too:
+ # compared as a list it never equals a `torch.Size`, and every row was resized to its own size.
+ import collections
+
+ from torch.utils._python_dispatch import TorchDispatchMode
+
+ class _CountOps(TorchDispatchMode):
+ def __init__(self):
+ super().__init__()
+ self.calls = collections.Counter()
+
+ def __torch_dispatch__(self, func, types, args=(), kwargs=None):
+ self.calls[func.overloadpacket.__name__] += 1
+ return func(*args, **(kwargs or {}))
+
+ inp = torch.rand(4, 2, 6, 7, device=device, dtype=dtype)
+ src_box, _ = self._per_row_boxes_4531(device)
+ counter = _CountOps()
+ with counter:
+ out = kornia.geometry.transform.crop_by_indices(inp, src_box, size=size)
+
+ assert out.shape == (4, 2, 3, 4)
+ if device.type == "mps":
+ assert counter.calls["cat"] == 0
+ assert counter.calls["copy_"] == 4
+ else:
+ assert counter.calls["cat"] == 1
+ assert counter.calls["copy_"] == 0
+ assert not any(name.startswith("upsample") for name in counter.calls)
+
+ def test_gradcheck_per_row_boxes_4531(self, device):
+ inp = torch.rand(4, 1, 6, 7, device=device, dtype=torch.float64)
+ src_box, _ = self._per_row_boxes_4531(device)
+ self.gradcheck(
+ kornia.geometry.transform.crop_by_indices, (inp, src_box, (3, 4)), requires_grad=(True, False, False)
+ )
+
class TestCropSizeValidation:
"""Tests that crop functions properly reject invalid size arguments."""