π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(augmentation): make Resize torch.compile fullgraph-safe (#3800)
Edgar Riba5e5d02913f58
diff --git a/kornia/augmentation/_2d/geometric/resize.py b/kornia/augmentation/_2d/geometric/resize.pyindex 6634a868e..250825726 100644--- a/kornia/augmentation/_2d/geometric/resize.py+++ b/kornia/augmentation/_2d/geometric/resize.py@@ -80,25 +80,24 @@ class Resize(GeometricAugmentationBase2D):flags: Dict[str, Any],transform: Optional[torch.Tensor] = None,) -> torch.Tensor:- B, C, _, _ = input.shape- out_size = tuple(params["output_size"][0].tolist())- out = torch.empty(B, C, *out_size, device=input.device, dtype=input.dtype)-- for i in range(B):- x1 = int(params["src"][i, 0, 0])- x2 = int(params["src"][i, 1, 0]) + 1- y1 = int(params["src"][i, 0, 1])- y2 = int(params["src"][i, 3, 1]) + 1- out[i] = resize(- input[i : i + 1, :, y1:y2, x1:x2],- out_size,- interpolation=flags["resample"].name.lower(),- align_corners=(- flags["align_corners"] if flags["resample"] in [Resample.BILINEAR, Resample.BICUBIC] else None- ),- antialias=flags["antialias"],- )- return out+ # The generator always sets `src` to the full input box, so the per-sample crop is a+ # no-op and this reduces to a single batched resize of the whole input to `output_size`.+ # Using the static `flags["size"]` for a tuple size keeps this torch.compile+ # fullgraph-safe (an int side depends on the input aspect ratio, so it falls back to the+ # data-dependent `output_size` param).+ if isinstance(flags["size"], (tuple, list)):+ out_size: Tuple[int, int] = (int(flags["size"][0]), int(flags["size"][1]))+ else:+ out_size = tuple(params["output_size"][0].tolist())+ return resize(+ input,+ out_size,+ interpolation=flags["resample"].name.lower(),+ align_corners=(+ flags["align_corners"] if flags["resample"] in [Resample.BILINEAR, Resample.BICUBIC] else None+ ),+ antialias=flags["antialias"],+ )def inverse_transform(self,diff --git a/kornia/augmentation/base.py b/kornia/augmentation/base.pyindex 00a388ecb..67bcc41dd 100644--- a/kornia/augmentation/base.py+++ b/kornia/augmentation/base.py@@ -323,19 +323,26 @@ class _AugmentationBase(_BasicAugmentationBase):self.validate_tensor(in_tensor)output_transformed = self.apply_transform(in_tensor, params, flags, transform=transform)- output_not_transformed = self.apply_non_transform(in_tensor, params, flags, transform=transform)- if (- output_transformed.shape == output_not_transformed.shape- and output_transformed.shape[0] == to_apply.shape[0]- ):- to_apply_expanded = to_apply.view(-1, *([1] * (len(output_transformed.shape) - 1)))- output = torch.where(to_apply_expanded, output_transformed, output_not_transformed)+ if self.p == 1.0 and self.p_batch == 1.0:+ # Always applied (static probabilities): the output is unconditionally the+ # transformed one. Skip the non-transform branch and the blend entirely β this+ # also makes shape-changing augmentations (e.g. Resize) fullgraph-compilable,+ # since the data-dependent shape comparison / `to_apply.any()` fallback is avoided.+ output = output_transformedelse:- # Shape-changing augmentations (e.g. RandomCrop, Resize) cannot be where-blended- # because the two outputs differ in spatial size. We fall back to a Python branch- # on to_apply.any(); this is non-onnx-exportable.- output = output_transformed if bool(to_apply.any()) else output_not_transformed+ output_not_transformed = self.apply_non_transform(in_tensor, params, flags, transform=transform)+ if (+ output_transformed.shape == output_not_transformed.shape+ and output_transformed.shape[0] == to_apply.shape[0]+ ):+ to_apply_expanded = to_apply.view(-1, *([1] * (len(output_transformed.shape) - 1)))+ output = torch.where(to_apply_expanded, output_transformed, output_not_transformed)+ else:+ # Shape-changing augmentations (e.g. RandomCrop, Resize) cannot be where-blended+ # because the two outputs differ in spatial size. We fall back to a Python branch+ # on to_apply.any(); this is non-onnx-exportable.+ output = output_transformed if bool(to_apply.any()) else output_not_transformedif is_autocast_enabled():output = output.type(input.dtype)diff --git a/tests/augmentation/test_augmentation.py b/tests/augmentation/test_augmentation.pyindex 287cab955..703cc29e7 100644--- a/tests/augmentation/test_augmentation.py+++ b/tests/augmentation/test_augmentation.py@@ -4650,6 +4650,15 @@ class TestResize:assert out.shape == (1, 1, 4, 5)assert aug.inverse(out).shape == (1, 1, 4, 6)+ def test_dynamo(self, device, dtype):+ # A tuple output size resizes the whole batch in one call (no per-sample crop loop),+ # so Resize is torch.compile fullgraph-safe and matches eager.+ img = torch.rand(3, 3, 20, 24, device=device, dtype=dtype)+ aug = Resize(size=(16, 16))+ torch._dynamo.reset()+ compiled = torch.compile(aug, fullgraph=True)+ torch.testing.assert_close(aug(img), compiled(img), rtol=1e-4, atol=1e-4)+class TestSmallestMaxSize:def test_smoke(self, device, dtype):