π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(augmentation): make CenterCrop (slice mode) torch.compile fullgraph-safe (#3809)
Edgar Riba4a153ad47879
diff --git a/kornia/augmentation/_2d/geometric/center_crop.py b/kornia/augmentation/_2d/geometric/center_crop.pyindex 30165fc7b..3062f66be 100644--- a/kornia/augmentation/_2d/geometric/center_crop.py+++ b/kornia/augmentation/_2d/geometric/center_crop.py@@ -22,7 +22,7 @@ import torchfrom kornia.augmentation import random_generator as rgfrom kornia.augmentation._2d.geometric.base import GeometricAugmentationBase2Dfrom kornia.constants import Resample-from kornia.geometry.transform import crop_by_indices, crop_by_transform_mat, get_perspective_transform+from kornia.geometry.transform import crop_by_transform_mat, get_perspective_transformclass CenterCrop(GeometricAugmentationBase2D):@@ -138,7 +138,17 @@ class CenterCrop(GeometricAugmentationBase2D):flags["align_corners"],)if flags["cropping_mode"] == "slice": # uses advanced slicing to crop- return crop_by_indices(input, params["src"], flags["size"])+ # A centered crop of a static size is deterministic: the crop box is uniform across+ # the batch and depends only on the (symbolic) input shape, so slice directly instead+ # of routing through `crop_by_indices`, whose `x.unique()` uniformity probe and+ # `int(coord_tensor[i])` indexing break torch.compile fullgraph. The offsets match+ # `center_crop_generator` (`int(dim/2 - size/2)` == `(dim - size) // 2` for size <=+ # dim, which the generator guarantees) and the slice equals the requested size, so+ # this is byte-identical.+ crop_h, crop_w = int(flags["size"][0]), int(flags["size"][1])+ top = (input.shape[-2] - crop_h) // 2+ left = (input.shape[-1] - crop_w) // 2+ return input[..., top : top + crop_h, left : left + crop_w]raise NotImplementedError(f"Not supported type: {flags['cropping_mode']}.")def inverse_transform(diff --git a/tests/augmentation/test_augmentation.py b/tests/augmentation/test_augmentation.pyindex 6a7572c6d..c40610831 100644--- a/tests/augmentation/test_augmentation.py+++ b/tests/augmentation/test_augmentation.py@@ -2975,6 +2975,15 @@ class TestRandomGrayscale(BaseTester):class TestCenterCrop(BaseTester):+ def test_dynamo(self, device, dtype, torch_optimizer):+ # slice cropping mode: a static-size centered crop is fullgraph-safe and matches eager.+ input = torch.rand(2, 3, 20, 24, device=device, dtype=dtype)+ op = CenterCrop((16, 10))+ params = op.forward_parameters(input.shape)+ expected = op(input, params=params)+ compiled = torch.compile(op, fullgraph=True)+ self.assert_close(compiled(input, params=params), expected)+def test_no_transform(self, device, dtype):inp = torch.rand(1, 2, 4, 4, device=device, dtype=dtype)out = CenterCrop(2)(inp)