π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
perf(geometry): Avoid full-batch gradients per crop (#5447)
A Aswanth Rajbc9bd62bf4ac
diff --git a/changelog.d/5447.fixed.md b/changelog.d/5447.fixed.mdnew file mode 100644index 000000000..bdc546c3a--- /dev/null+++ b/changelog.d/5447.fixed.md@@ -0,0 +1 @@+`crop_by_indices` no longer allocates a full-batch input gradient and a copy of the whole output gradient for each image crop when gradients flow to a batch of images, so the backward of slice-mode crops (`RandomCrop`, `RandomResizedCrop`, `CenterCrop2D`) grows linearly with the batch size instead of quadratically.diff --git a/kornia/geometry/transform/crop2d.py b/kornia/geometry/transform/crop2d.pyindex 652739a94..9bea16011 100644--- a/kornia/geometry/transform/crop2d.py+++ b/kornia/geometry/transform/crop2d.py@@ -541,13 +541,20 @@ def crop_by_indices("Please pass `size` explicitly when box dimensions vary across the batch.")size = (int(h[0].item()), int(w[0].item())) if B > 0 else (0, 0)- out = torch.empty(B, C, *size, device=input_tensor.device, dtype=input_tensor.dtype)- # Find out the cropped shapes that need to be resized.+ # Unbind only when batch-slice gradients would allocate a full input buffer for every crop. On that+ # 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+ 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):- _out = input_tensor[i : i + 1, :, y1l[i] : y2l[i], x1l[i] : x2l[i]]+ 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]]if _out.shape[-2:] != size:if shape_compensation == "resize":- out[i] = resize(+ _out = resize(_out,size,interpolation=interpolation,@@ -556,9 +563,13 @@ def crop_by_indices(antialias=antialias,)else:- out[i] = F.pad(_out, [0, size[1] - _out.shape[-1], 0, size[0] - _out.shape[-2]])+ _out = F.pad(_out, [0, size[1] - _out.shape[-1], 0, size[0] - _out.shape[-2]])+ if out is None:+ crops.append(_out)else:out[i] = _out+ if out is None:+ return torch.cat(crops).contiguous()return outdiff --git a/tests/geometry/transform/test_crop2d.py b/tests/geometry/transform/test_crop2d.pyindex 0400a2f54..d6b95232c 100644--- a/tests/geometry/transform/test_crop2d.py+++ b/tests/geometry/transform/test_crop2d.py@@ -17,6 +17,7 @@import pytestimport torch+from torch.utils._python_dispatch import TorchDispatchModeimport kornia@@ -548,6 +549,99 @@ class TestCropByTransform(BaseTester):class TestCropByIndices(BaseTester):+ @pytest.mark.parametrize("batch", [1, 2, 5])+ @pytest.mark.parametrize("requires_grad", [False, True])+ @pytest.mark.parametrize("grad_enabled", [False, True])+ def test_backward_avoids_full_batch_slices_5004(self, batch, requires_grad, grad_enabled, device, dtype):+ img = torch.rand(batch, 2, 8, 9, device=device, dtype=dtype, requires_grad=requires_grad)+ src_box = torch.tensor(+ [[[i, i], [i + 2, i], [i + 2, i + 2], [i, i + 2]] for i in range(batch)],+ device=device,+ dtype=torch.int64,+ )+ full_batch_slices = []+ unbinds = []++ class SliceShapes(TorchDispatchMode):+ def __torch_dispatch__(self, func, types, args=(), kwargs=None):+ if func == torch.ops.aten.slice_backward.default and args[2] == 0 and tuple(args[1]) == img.shape:+ full_batch_slices.append(args[1])+ if func == torch.ops.aten.unbind.int:+ unbinds.append(func)+ return func(*args, **(kwargs or {}))++ # Each batch slice previously allocated a full input-sized gradient buffer (#5004).+ with torch.set_grad_enabled(grad_enabled), SliceShapes():+ out = kornia.geometry.transform.crop_by_indices(img, src_box, size=(3, 3))+ if out.requires_grad:+ out.sum().backward()+ assert not full_batch_slices+ assert len(unbinds) == int(batch > 1 and requires_grad and grad_enabled)++ @pytest.mark.parametrize("batch", [1, 4])+ @pytest.mark.parametrize("layout", ["contiguous", "channels_last", "transposed", "expanded"])+ @pytest.mark.parametrize("size", [None, (3, 3), [3, 3]])+ def test_per_row_values_and_gradients_5004(self, batch, layout, size, device, dtype):+ img = torch.rand(batch, 2, 8, 9, device=device, dtype=dtype)+ if layout == "channels_last":+ img = img.to(memory_format=torch.channels_last)+ elif layout == "transposed":+ img = img.transpose(-2, -1)+ elif layout == "expanded":+ img = img[:1].expand(batch, -1, -1, -1)+ img.requires_grad_()+ src_box = torch.tensor(+ [[[i, i], [i + 2, i], [i + 2, i + 2], [i, i + 2]] for i in range(batch)],+ device=device,+ dtype=torch.int64,+ )+ out = kornia.geometry.transform.crop_by_indices(img, src_box, size=size)+ expected = torch.stack([img[i, :, i : i + 3, i : i + 3] for i in range(batch)])+ weights = torch.arange(1, batch + 1, device=device, dtype=dtype).view(batch, 1, 1, 1).expand_as(out)+ gradient = torch.autograd.grad(out, img, weights)[0]+ expected_gradient = torch.zeros_like(img)+ for i in range(batch):+ expected_gradient[i, :, i : i + 3, i : i + 3] = i + 1++ self.assert_close(out, expected, rtol=0, atol=0)+ self.assert_close(gradient, expected_gradient, rtol=0, atol=0)+ # A batch is gathered into a new contiguous tensor; one image can take the uniform-box shortcut.+ assert batch == 1 or out.is_contiguous()+ assert out.untyped_storage().data_ptr() != img.untyped_storage().data_ptr()++ @pytest.mark.parametrize("batch", [2, 5])+ @pytest.mark.parametrize("size, shape_compensation", [((3, 3), "resize"), ((4, 5), "resize"), ((4, 5), "pad")])+ def test_backward_avoids_full_output_copies_5004(self, batch, size, shape_compensation, device, dtype):+ img = torch.rand(batch, 2, 8, 9, device=device, dtype=dtype, requires_grad=True)+ src_box = torch.tensor(+ [[[i, i], [i + 2, i], [i + 2, i + 2], [i, i + 2]] for i in range(batch)],+ device=device,+ dtype=torch.int64,+ )+ crop = kornia.geometry.transform.crop_by_indices+ out = crop(img, src_box, size=size, shape_compensation=shape_compensation)+ weights = torch.arange(1, out.numel() + 1, device=device, dtype=dtype).reshape(out.shape)+ full_output_copies = []++ class OutputCopies(TorchDispatchMode):+ def __torch_dispatch__(self, func, types, args=(), kwargs=None):+ result = func(*args, **(kwargs or {}))+ if func == torch.ops.aten.copy_.default and tuple(result.shape) == tuple(out.shape):+ full_output_copies.append(func)+ return result++ # Writing each row into a preallocated output made backward copy the whole output gradient once per row.+ with OutputCopies():+ (gradient,) = torch.autograd.grad(out, img, weights)+ assert not full_output_copies+ # A single image takes the batch-slicing path, so each row is checked against it.+ for i in range(batch):+ row = img[i : i + 1].detach().requires_grad_()+ row_out = crop(row, src_box[i : i + 1], size=size, shape_compensation=shape_compensation)+ (row_gradient,) = torch.autograd.grad(row_out, row, weights[i : i + 1])+ self.assert_close(out[i : i + 1], row_out, rtol=0, atol=0)+ self.assert_close(gradient[i : i + 1], row_gradient, rtol=0, atol=0)+def test_crop_by_indices_no_resizing(self, device, dtype):inp = torch.tensor([[[[1.0, 2.0, 3.0], [4.0, 5.0, 6.0], [7, 8, 9]]]], device=device, dtype=dtype) # 1x3x3