π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
Fix augmentation compile caches and crop/CLAHE recompilation (#4659)
Dmytro Mishkin1eb0697447bf
diff --git a/changelog.d/4659.fixed.md b/changelog.d/4659.fixed.mdnew file mode 100644index 000000000..721064a13--- /dev/null+++ b/changelog.d/4659.fixed.md@@ -0,0 +1,11 @@+Augmentation classes no longer exhaust a shared `torch.compile` cache. Compiled+`RandomResizedCrop` and `RandomCrop` slice modes keep sampled crop coordinates in+tensors, avoiding recompilation as crop boxes change while preserving interpolation+and input gradients. Nearest-neighbor upsampling accumulates half-precision+input gradients in float32 to avoid saturation. Compiled `RandomClahe` also keeps per-image clip limits in+tensors so varying sampled limits reuse the graph.++`RandomClahe` batches clip limits in eager execution as well. Compiled crop+interpolation matches eager to floating-point tolerance rather than bitwise.+Avoiding recompilation does not guarantee faster steady-state execution: compiled+CPU `RandomCrop` can remain slower than eager or the previous post-fallback path.diff --git a/kornia/augmentation/_2d/geometric/crop.py b/kornia/augmentation/_2d/geometric/crop.pyindex 891932231..b7931baed 100644--- a/kornia/augmentation/_2d/geometric/crop.py+++ b/kornia/augmentation/_2d/geometric/crop.py@@ -15,6 +15,8 @@# limitations under the License.#+from __future__ import annotations+from typing import Any, Dict, List, Optional, Tuple, Unionimport torch@@ -22,9 +24,10 @@ import torch.nn.functional as Ffrom kornia.augmentation import random_generator as rgfrom kornia.augmentation._2d.geometric.base import GeometricAugmentationBase2D+from kornia.augmentation.utils._crop import _compiled_slice_resizefrom kornia.augmentation.utils.helpers import _constant_tensorfrom kornia.constants import Resample-from kornia.core.utils import is_exporting+from kornia.core.utils import is_compiling, is_exportingfrom kornia.geometry.boxes import Boxesfrom kornia.geometry.keypoints import Keypointsfrom kornia.geometry.transform import crop_by_indices, crop_by_transform_mat, get_perspective_transform@@ -97,12 +100,19 @@ class RandomCrop(GeometricAugmentationBase2D):Slice mode calls ``crop_by_indices`` with thatfunction's bilinear/``align_corners=None`` defaults, ignoring this class's ``resample`` and- ``align_corners`` flags. Resample mode uses ``crop_by_transform_mat`` with the configured interpolation and+ ``align_corners`` flags. Under ``torch.compile``, tensor indexing and interpolation keep newly sampled+ crop coordinates from triggering recompilation. Resample mode uses ``crop_by_transform_mat`` with the configured+ interpolation and``align_corners``; it maps constant, replicate, and reflect pre-padding to zero, border, and reflectionsampler padding respectively. Onlyresample mode supports :meth:`inverse`; inverse removes pre-crop padding but cannot restore cropped orinterpolated content.+ Note:+ Compiled slice-mode interpolation matches eager execution to floating-point tolerance,+ not bitwise. Eager execution retains native slicing and resizing for performance;+ the tensorized compiled path avoids recompilation as crop coordinates change.+Examples:>>> import torch>>> _ = torch.manual_seed(0)@@ -302,6 +312,8 @@ class RandomCrop(GeometricAugmentationBase2D):align_corners=flags["align_corners"],)if flags["cropping_mode"] == "slice": # uses advanced slicing to crop+ if is_compiling():+ return _compiled_slice_resize(input, params["src"], flags["size"], "bilinear", None)return crop_by_indices(input, params["src"], flags["size"])raise NotImplementedError(f"Not supported type: {flags['cropping_mode']}.")diff --git a/kornia/augmentation/_2d/geometric/resized_crop.py b/kornia/augmentation/_2d/geometric/resized_crop.pyindex 11f254565..74a8839e2 100644--- a/kornia/augmentation/_2d/geometric/resized_crop.py+++ b/kornia/augmentation/_2d/geometric/resized_crop.py@@ -15,6 +15,8 @@# limitations under the License.#+from __future__ import annotations+from typing import Any, Dict, Optional, Tuple, Unionimport torch@@ -22,7 +24,9 @@ import torchfrom kornia.augmentation import random_generator as rgfrom kornia.augmentation._2d.base import _input_metadata_onlyfrom kornia.augmentation._2d.geometric.base import GeometricAugmentationBase2D+from kornia.augmentation.utils._crop import _compiled_slice_resizefrom kornia.constants import Resample+from kornia.core.utils import is_compilingfrom kornia.geometry.transform import crop_by_indices, crop_by_transform_mat, get_perspective_transform@@ -73,9 +77,16 @@ class RandomResizedCrop(GeometricAugmentationBase2D):Slice mode calls index cropping with the configured interpolation and ``align_corners``; resample modecalls ``crop_by_transform_mat`` with zero padding. Both default to bilinear sampling and- ``align_corners=True``. Only resample mode supports :meth:`inverse`; its inverse+ ``align_corners=True``. Under ``torch.compile``, slice mode uses tensor indexing and+ interpolation so newly sampled crop coordinates do not trigger recompilation.+ Only resample mode supports :meth:`inverse`; its inverseresamples onto the original canvas and cannot recover information discarded by cropping or interpolation.+ Note:+ Compiled slice-mode interpolation matches eager execution to floating-point tolerance,+ not bitwise. Eager execution retains native slicing and resizing for performance;+ the tensorized compiled path avoids recompilation as crop coordinates change.+Example:>>> rng = torch.manual_seed(0)>>> inputs = torch.tensor([[[0., 1., 2.],@@ -158,6 +169,10 @@ class RandomResizedCrop(GeometricAugmentationBase2D):align_corners=flags["align_corners"],)if flags["cropping_mode"] == "slice": # uses advanced slicing to crop+ if is_compiling():+ return _compiled_slice_resize(+ input, params["src"], flags["size"], flags["resample"].name.lower(), flags["align_corners"]+ )return crop_by_indices(input,params["src"],diff --git a/kornia/augmentation/_2d/intensity/clahe.py b/kornia/augmentation/_2d/intensity/clahe.pyindex ceb2b1c2e..3d1ddd5ae 100644--- a/kornia/augmentation/_2d/intensity/clahe.py+++ b/kornia/augmentation/_2d/intensity/clahe.py@@ -23,7 +23,7 @@ import torchfrom kornia.augmentation import random_generator as rgfrom kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D-from kornia.enhance import equalize_clahe+from kornia.enhance.equalization import _equalize_claheclass RandomClahe(IntensityAugmentationBase2D):@@ -63,10 +63,12 @@ class RandomClahe(IntensityAugmentationBase2D):leaves the gather unchecked and returns an in-range image as if the input had been valid.Convention:- - ``clip_limit`` is drawn per sample and each image is equalized with its own draw. When every- draw is equal -- which ``same_on_batch=True`` guarantees, and an unlucky batch can produce on- its own -- the batch takes a single :func:`kornia.enhance.equalize_clahe` call instead of one- per image; the result is the same either way.+ - ``clip_limit`` is drawn per sample and each image is equalized with its own draw. Both eager and+ compiled execution batch the per-image limits as tensors, so newly sampled limits reuse the same+ graph without converting draws to Python scalars. Batched differentiable histogram arithmetic+ can differ from separate per-image calls by floating-point rounding.+ On MPS, clip limits stored on the device are copied to CPU for float64 threshold arithmetic,+ then thresholds are copied back; this preserves scalar rounding but adds transfer overhead... warning::``grid_size`` is unvalidated past its positivity check. Its two@@ -125,13 +127,4 @@ class RandomClahe(IntensityAugmentationBase2D):flags: dict[str, Any],transform: Optional[torch.Tensor] = None,) -> torch.Tensor:- clip_limits = params["clip_limit_factor"]- if bool(torch.all(clip_limits == clip_limits[0])):- return equalize_clahe(input, float(clip_limits[0]), flags["grid_size"], flags["slow_and_differentiable"])-- return torch.stack(- [- equalize_clahe(image, float(clip_limit), flags["grid_size"], flags["slow_and_differentiable"])- for image, clip_limit in zip(input, clip_limits)- ]- )+ return _equalize_clahe(input, params["clip_limit_factor"], flags["grid_size"], flags["slow_and_differentiable"])diff --git a/kornia/augmentation/base.py b/kornia/augmentation/base.pyindex 890a90c73..dba778b1f 100644--- a/kornia/augmentation/base.py+++ b/kornia/augmentation/base.py@@ -16,6 +16,9 @@#from enum import Enum+from functools import update_wrapper+from inspect import getattr_static+from types import FunctionTypefrom typing import Any, Callable, Dict, Optional, Tuple, Unionimport torch@@ -82,6 +85,26 @@ class _BasicAugmentationBase(nn.Module):# subset in ``tests/augmentation/test_onnx_export.py``.ONNX_EXPORTABLE = True+ def __init_subclass__(cls, **kwargs: Any) -> None:+ super().__init_subclass__(**kwargs)+ # Dynamo caches by code object. Sharing an inherited forward across all augmentation+ # classes exhausts its recompilation limit after only a few distinct augmentations.+ # Copy the implementation (not a wrapper that re-enters the shared frame), once per+ # class. Keep overrides and the original globals/closure, including zero-argument super.+ # This isolates the entry frame only: graph-break resumptions inside shared helpers+ # can still share caches (for example RandomCrop padding in a mixed pipeline).+ forward = getattr_static(cls, "forward")+ if "forward" not in cls.__dict__ and isinstance(forward, FunctionType):+ code = forward.__code__.replace(+ co_name=f"{cls.__name__}.forward", co_qualname=f"{cls.__qualname__}.forward"+ )+ clone = FunctionType(code, forward.__globals__, "forward", forward.__defaults__, forward.__closure__)+ update_wrapper(clone, forward)+ clone.__kwdefaults__ = forward.__kwdefaults__+ clone.__qualname__ = f"{cls.__qualname__}.forward"+ clone.__module__ = cls.__module__+ cls.forward = clone+@propertydef exportable(self) -> bool:"""Whether this augmentation supports ONNX export via the legacy tracer at opset 20.diff --git a/kornia/augmentation/utils/_crop.py b/kornia/augmentation/utils/_crop.pynew file mode 100644index 000000000..5e5797db0--- /dev/null+++ b/kornia/augmentation/utils/_crop.py@@ -0,0 +1,152 @@+# LICENSE HEADER MANAGED BY add-license-header+#+# Copyright 2018 Kornia Team+#+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.+#++from __future__ import annotations++from typing import Optional, Tuple++import torch+++def _resize_coordinates(+ start: torch.Tensor,+ end: torch.Tensor,+ input_size: int,+ output_size: int,+ mode: str,+ align_corners: Optional[bool],+) -> torch.Tensor:+ length = end - start+ positions = torch.arange(output_size, device=start.device, dtype=start.dtype)+ if mode == "nearest":+ # ATen computes the scale on the host (usually float32; see the CPU-double path). CUDA/Inductor+ # tensor float32 division can change pixels at integer boundaries (e.g. 26 -> 22).+ # Build scales in CPU float64 before casting, like host scalar arithmetic. Tensor+ # arange keeps input_size symbolic under dynamic=True; a Python range specializes it.+ # No float64 GPU/MPS ops or device-to-host copies of sampled coordinates are needed.+ scales = (torch.arange(input_size + 1, device="cpu", dtype=torch.float64) / output_size).to(start)+ return (positions * scales[length.long()]).float().floor()+ if align_corners:+ coordinates = positions * ((length - 1) / (output_size - 1) if output_size > 1 else length * 0.0)+ else:+ coordinates = (positions + 0.5) * (length / output_size) - 0.5+ # Reciprocal multiplication can round an identity scale below one (e.g. 41/41).+ # Keep exact integer indices for unchanged axes, including the no-resize center tap.+ return torch.where(length == output_size, positions, coordinates)+++def _cubic_weights(fraction: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:+ # PyTorch interpolate's cubic convolution, A=-0.75 (ATen/native/UpSample.h).+ def inner(x: torch.Tensor) -> torch.Tensor:+ return ((1.25 * x - 2.25) * x) * x + 1.0++ def outer(x: torch.Tensor) -> torch.Tensor:+ return ((-0.75 * x + 3.75) * x - 6.0) * x + 3.0++ return outer(fraction + 1), inner(fraction), inner(1 - fraction), outer(2 - fraction)+++def _compiled_slice_resize(+ input: torch.Tensor, src: torch.Tensor, size: Tuple[int, int], mode: str, align_corners: Optional[bool]+) -> torch.Tensor:+ """Slice and resize without ragged intermediate tensors or Python crop coordinates.++ Match ``interpolate`` pixel locations and clamp each interpolation tap to the *crop*+ boundary, including bicubic's outer taps. A warp of the entire image would read outside+ that boundary. Integer box conversion matches ``crop_by_indices`` and stops box gradients.+ """+ batch, channels, height, width = input.shape+ # Nearest normally uses float32 index arithmetic; handle ATen's CPU-double exception below.+ coordinate_dtype = torch.float64 if input.dtype == torch.float64 and mode != "nearest" else torch.float32+ src = src.to(device=input.device, dtype=torch.long)+ # Match Python slicing for negative and out-of-bounds replay coordinates.+ x0, x1 = src[:, 0, 0:1], src[:, 1, 0:1] + 1+ y0, y1 = src[:, 0, 1:2], src[:, 3, 1:2] + 1+ x0 = torch.where(x0 < 0, x0 + width, x0).clamp(0, width).to(coordinate_dtype)+ x1 = torch.where(x1 < 0, x1 + width, x1).clamp(0, width).to(coordinate_dtype)+ y0 = torch.where(y0 < 0, y0 + height, y0).clamp(0, height).to(coordinate_dtype)+ y1 = torch.where(y1 < 0, y1 + height, y1).clamp(0, height).to(coordinate_dtype)+ x = _resize_coordinates(x0, x1, width, size[1], mode, align_corners)+ y = _resize_coordinates(y0, y1, height, size[0], mode, align_corners)+ if mode == "nearest" and input.device.type == "cpu" and input.dtype == torch.float64 and sum(size) > 128:+ # ATen's generic CPU nearest kernel uses double scales for double images,+ # then floorf; its channels-last kernel uses float scales. Match the layout+ # of the actual slices (including crop_by_indices' identical-box batch path).+ # _use_vectorized_kernel_cond_2d selects float scales for Hout + Wout <= 128+ # or channels-last slices with C > 3; otherwise HelperInterpNearest uses doubles.+ # The threshold is an ATen benchmark heuristic, present in both supported endpoints:+ # https://github.com/pytorch/pytorch/blob/v2.5.1/aten/src/ATen/native/cpu/UpSampleKernel.cpp#L1539-L1574+ # https://github.com/pytorch/pytorch/blob/v2.14.0/aten/src/ATen/native/cpu/UpSampleKernel.cpp+ # Keep test_compile_nearest_large_output across torch versions: a rounding change+ # selects a different pixel, so this cannot be covered by a looser value tolerance.+ xd = _resize_coordinates(x0.double(), x1.double(), width, size[1], mode, align_corners)+ yd = _resize_coordinates(y0.double(), y1.double(), height, size[0], mode, align_corners)+ if channels > 3:+ h, w = y1 - y0, x1 - x0+ sn, sc, sh, sw = input.stride()+ channels_last = (sc == 1) & ((w == 1) | (sw == channels)) & ((h == 1) | (sh == channels * w))+ if batch > 1:+ corners = src[:, [0, 1, 0, 3], [0, 0, 1, 1]]+ identical = (corners == corners[:1]).all()+ channels_last = channels_last & (~identical | (sn == channels * h * w))+ x, y = torch.where(channels_last, x, xd), torch.where(channels_last, y, yd)+ else:+ x, y = xd, yd+ # Accumulate gradients in opmath precision before casting to half/bfloat16.+ # Nearest upsampling also needs this: many outputs can gather the same pixel,+ # and half atomic additions can saturate even with a single gather operation.+ work = input.float() if input.dtype in (torch.float16, torch.bfloat16) else input+ if mode != "nearest":+ work = work.to(coordinate_dtype)+ flat = work.reshape(batch, channels, height * width)++ def gather(x_index: torch.Tensor, y_index: torch.Tensor) -> torch.Tensor:+ x_index = (x0 + x_index.clamp(min=0)).minimum(x1 - 1).long()+ y_index = (y0 + y_index.clamp(min=0)).minimum(y1 - 1).long()+ indices = (y_index.unsqueeze(-1) * width + x_index.unsqueeze(-2)).reshape(batch, 1, -1)+ return flat.gather(2, indices.expand(-1, channels, -1)).reshape(batch, channels, *size)++ if mode == "nearest":+ return gather(x, y).to(input.dtype)++ def preserve_slice(result: torch.Tensor, slice_values: torch.Tensor) -> torch.Tensor:+ # crop_by_indices skips interpolate entirely when the slice already has the+ # requested size. Avoid spreading NaNs/Infs through zero-weight neighbors.+ unchanged = ((x1 - x0 == size[1]) & (y1 - y0 == size[0]))[:, :, None, None]+ # The central tap already equals the exact slice when both dimensions match.+ return torch.where(unchanged, slice_values, result).to(input.dtype)++ if mode == "bilinear":+ x, y = x.clamp(min=0), y.clamp(min=0)+ ix, iy = x.floor(), y.floor()+ fx, fy = x - ix, y - iy+ center = gather(ix, iy)+ if mode == "bilinear":+ wx, wy = fx[:, None, None, :], fy[:, None, :, None]+ top = center * (1 - wx) + gather(ix + 1, iy) * wx+ bottom = gather(ix, iy + 1) * (1 - wx) + gather(ix + 1, iy + 1) * wx+ return preserve_slice(top * (1 - wy) + bottom * wy, center)++ wxs, wys = _cubic_weights(fx), _cubic_weights(fy)+ result = input.new_zeros((batch, channels, *size), dtype=coordinate_dtype)+ for j in range(4):+ row = input.new_zeros((batch, channels, *size), dtype=coordinate_dtype)+ for i in range(4):+ tap = center if i == 1 and j == 1 else gather(ix + i - 1, iy + j - 1)+ row = row + tap * wxs[i][:, None, None, :]+ result = result + row * wys[j][:, None, :, None]+ return preserve_slice(result, center)diff --git a/kornia/enhance/equalization.py b/kornia/enhance/equalization.pyindex 520f0b96a..72d4afa26 100644--- a/kornia/enhance/equalization.py+++ b/kornia/enhance/equalization.py@@ -18,7 +18,7 @@"""In this module several equalization methods are exposed: he, ahe, clahe."""import math-from typing import Tuple+from typing import Tuple, Unionimport torchimport torch.nn.functional as F@@ -166,7 +166,7 @@ def _tiles_histc(tiles: torch.Tensor, bins: int) -> torch.Tensor:def _compute_luts(- tiles_x_im: torch.Tensor, num_bins: int = 256, clip: float = 40.0, diff: bool = False+ tiles_x_im: torch.Tensor, num_bins: int = 256, clip: Union[float, torch.Tensor] = 40.0, diff: bool = False) -> torch.Tensor:r"""Compute luts for a batched set of tiles.@@ -196,7 +196,21 @@ def _compute_luts(histos = histogram(tiles, bins, torch.tensor(0.001))histos *= pixels- if clip > 0.0:+ if isinstance(clip, torch.Tensor):+ # Match Python scalar arithmetic before rounding each image's threshold, then broadcast+ # over its tiles and channels. Keeping the limits in tensors avoids compile guards on draws.+ # MPS cannot store doubles; compute its thresholds on CPU before copying them with the LUTs.+ limits = clip.to(device="cpu", dtype=torch.float64) if clip.device.type == "mps" else clip.double()+ max_vals = (limits * pixels).div(num_bins, rounding_mode="floor").clamp(min=1)+ max_vals = max_vals.to(histos).view(b, 1).expand(b, gh * gw * c).reshape(-1, 1)+ limited = histos.clamp(max=max_vals)+ clipped_tensor = torch.relu(histos - max_vals).sum(1) if diff else pixels - limited.sum(1)+ residual_tensor = torch.remainder(clipped_tensor, num_bins)+ limited = limited + ((clipped_tensor - residual_tensor) / num_bins).unsqueeze(1)+ limited = limited + (torch.arange(num_bins, device=histos.device) < residual_tensor.unsqueeze(1))+ enabled = (clip > 0).to(device=histos.device).view(b, 1).expand(b, gh * gw * c).reshape(-1, 1)+ histos = torch.where(enabled, limited, histos)+ elif clip > 0.0:max_val: float = max(clip * pixels // num_bins, 1)if diff:clipped: torch.Tensor = torch.relu(histos - max_val).sum(1)@@ -399,6 +413,16 @@ def equalize_clahe(if not isinstance(clip_limit, float):raise TypeError(f"Input clip_limit type is not float. Got {type(clip_limit)}")+ return _equalize_clahe(input, clip_limit, grid_size, slow_and_differentiable)+++def _equalize_clahe(+ input: torch.Tensor,+ clip_limit: Union[float, torch.Tensor],+ grid_size: Tuple[int, int],+ slow_and_differentiable: bool,+) -> torch.Tensor:+ """Equalize a BCHW tensor using a scalar or one tensor clip limit per image."""if not isinstance(grid_size, tuple):raise TypeError(f"Input grid_size type is not Tuple. Got {type(grid_size)}")diff --git a/tests/augmentation/test_augmentation.py b/tests/augmentation/test_augmentation.pyindex 0fa219af8..a25c1e2a3 100644--- a/tests/augmentation/test_augmentation.py+++ b/tests/augmentation/test_augmentation.py@@ -4238,10 +4238,12 @@ class TestRandomClahe(BaseTester):@pytest.mark.parametrize("batch_prob", [(True, True), (False, True), (False, False)])@pytest.mark.parametrize("slow_and_differentiable", [False, True])- def test_per_sample_clip_limit_replay(self, batch_prob, slow_and_differentiable, device, dtype):+ @pytest.mark.parametrize("limits", [(0.5, 40.0), (7.0, 7.0), (0.0, -1.0)])+ def test_per_sample_clip_limit_replay(self, batch_prob, slow_and_differentiable, limits, device, dtype):torch.manual_seed(0)input_data = torch.rand(2, 1, 32, 32).pow(3).to(device=device, dtype=dtype)- clip_limits = torch.tensor([0.5, 40.0])+ input_data.requires_grad_(slow_and_differentiable)+ clip_limits = torch.tensor(limits)aug = RandomClahe(clip_limit=(0.5, 40.0),grid_size=(2, 2),@@ -4262,7 +4264,14 @@ class TestRandomClahe(BaseTester):)expected = torch.where(torch.tensor(batch_prob, device=device).view(-1, 1, 1, 1), transformed, input_data)- self.assert_close(aug(input_data, params=params), expected)+ actual = aug(input_data, params=params)+ self.assert_close(actual, expected)+ if slow_and_differentiable:+ weights = torch.rand_like(actual)+ self.assert_close(+ torch.autograd.grad(actual, input_data, weights)[0],+ torch.autograd.grad(expected, input_data, weights)[0],+ )def test_same_on_batch(self, device, dtype):torch.manual_seed(0)diff --git a/tests/augmentation/test_augmentation_compile.py b/tests/augmentation/test_augmentation_compile.pynew file mode 100644index 000000000..81b977df4--- /dev/null+++ b/tests/augmentation/test_augmentation_compile.py@@ -0,0 +1,353 @@+# LICENSE HEADER MANAGED BY add-license-header+#+# Copyright 2018 Kornia Team+#+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.+#++from __future__ import annotations++import copy+import pickle++import pytest+import torch+from torch._dynamo.testing import CompileCounter, CompileCounterWithBackend++import kornia.augmentation as K++from testing.base import BaseTester+++class TestAugmentationCompile(BaseTester):+ def test_compile_distinct_classes(self, device, dtype, torch_optimizer):+ # More classes than Dynamo's default per-code-object cache limit (#4658).+ augmentations = [+ K.RandomHorizontalFlip(p=1),+ K.RandomVerticalFlip(p=1),+ K.RandomInvert(p=1),+ K.RandomGrayscale(p=1),+ K.RandomBrightness(p=1),+ K.RandomContrast(p=1),+ K.RandomGamma(p=1),+ K.RandomSharpness(p=1),+ K.RandomSolarize(p=1),+ ]+ input = torch.rand(2, 3, 8, 8, device=device, dtype=dtype)+ compiled = []+ for aug in augmentations:+ # Isolate shared entry-frame caching here. Crop and CLAHE random-path+ # tests separately trace parameter sampling and check graph reuse.+ params = aug.forward_parameters(input.shape)+ counter = CompileCounter()+ fn = torch_optimizer(aug, backend=counter, fullgraph=True)+ self.assert_close(fn(input, params=params), aug(input, params=params))+ assert counter.frame_count > 0+ compiled.append((aug, fn, params, counter, counter.frame_count))+ for aug, fn, params, counter, frames in compiled:+ self.assert_close(fn(input, params=params), aug(input, params=params))+ assert counter.frame_count == frames++ @pytest.mark.parametrize(+ "resample,align_corners",+ [("bilinear", True), ("bilinear", False), ("bicubic", True), ("bicubic", False), ("nearest", None)],+ )+ @pytest.mark.parametrize("size", [(5, 7), (1, 1)])+ def test_compile_resized_crop_replay(self, device, dtype, torch_optimizer, resample, align_corners, size):+ aug = K.RandomResizedCrop(size, resample=resample, align_corners=align_corners)+ input = torch.rand(2, 3, 12, 15, device=device, dtype=dtype, requires_grad=True)+ counter = CompileCounter()+ fn = torch_optimizer(aug, backend=counter, fullgraph=True)+ # Include singleton crops, up/downsampling, borders and different boxes within a batch.+ boxes = [+ ((0, 0, 15, 12), (2, 3, 7, 6)),+ ((4, 2, 1, 1), (1, 0, 11, 10)),+ ((2, 5, 10, 4), (7, 1, 4, 9)),+ ((0, 0, 5, 7), (3, 2, 7, 5)),+ ]+ for batch_boxes in boxes:+ params = aug.forward_parameters(input.shape)+ params["src"] = torch.tensor(+ [[[x, y], [x + w - 1, y], [x + w - 1, y + h - 1], [x, y + h - 1]] for x, y, w, h in batch_boxes],+ device=device,+ dtype=dtype,+ )+ expected = aug(input, params=params)+ actual = fn(input, params=params)+ self.assert_close(actual, expected)+ weights = torch.rand_like(actual)+ actual_grad = torch.autograd.grad(actual, input, weights)[0]+ if device.type == "cuda" and dtype in (torch.float16, torch.bfloat16):+ # CUDA half interpolate backward rounds atomic updates. Compare with+ # float32 accumulation, as in the real-backend replay tests below.+ reference = input.detach().float().requires_grad_()+ expected_grad = torch.autograd.grad(aug(reference, params=params), reference, weights.float())[0].to(+ dtype+ )+ else:+ expected_grad = torch.autograd.grad(expected, input, weights)[0]+ self.assert_close(actual_grad, expected_grad)+ assert counter.frame_count == 1++ @pytest.mark.parametrize("same_on_batch", [False, True])+ def test_compile_resized_crop_random(self, device, dtype, torch_optimizer, same_on_batch):+ aug = K.RandomResizedCrop((8, 8), same_on_batch=same_on_batch)+ input = torch.rand(2, 3, 16, 16, device=device, dtype=dtype)+ counter = CompileCounter()+ fn = torch_optimizer(aug, backend=counter, fullgraph=True)+ outputs = [fn(input) for _ in range(20)]+ assert all(output.shape == (2, 3, 8, 8) for output in outputs)+ assert any(not torch.equal(outputs[0], output) for output in outputs[1:])+ assert counter.frame_count == 1++ def test_forward_code_qualname(self):+ for cls in (K.RandomHorizontalFlip, K.RandomVerticalFlip):+ assert cls.forward.__code__.co_qualname == f"{cls.__qualname__}.forward"++ @pytest.mark.parametrize("backend", ["eager", "inductor"])+ def test_compile_nearest_dynamic_shape(self, device, dtype, torch_optimizer, backend):+ aug = K.RandomResizedCrop((46, 22), resample="nearest", align_corners=None)+ counter = CompileCounter() if backend == "eager" else CompileCounterWithBackend(backend)+ fn = torch_optimizer(aug, backend=counter, fullgraph=True, dynamic=True)+ frames = None+ for height, width in [(14, 26), (18, 30), (22, 34)]:+ input = torch.rand(2, 3, height, width, device=device, dtype=dtype)+ params = aug.forward_parameters(input.shape)+ params["src"] = (+ torch.tensor(+ [[[0, 0], [width - 1, 0], [width - 1, height - 1], [0, height - 1]]],+ device=device,+ dtype=dtype,+ )+ .expand(2, -1, -1)+ .clone()+ )+ self.assert_close(fn(input, params=params), aug(input, params=params), atol=0, rtol=0)+ if frames is None:+ # Cold Inductor can invoke the backend twice during initial dynamic+ # compilation. Changing spatial sizes must reuse the resulting graph.+ frames = counter.frame_count+ assert frames > 0+ assert counter.frame_count == frames++ def test_forward_copy_and_pickle(self, device, dtype):+ aug = K.RandomHorizontalFlip(p=1)+ input = torch.rand(2, 3, 8, 8, device=device, dtype=dtype)+ for clone in (copy.deepcopy(aug), pickle.loads(pickle.dumps(aug))): # noqa: S301+ self.assert_close(clone(input), input.flip(-1))++ @pytest.mark.parametrize(+ "resample,align_corners",+ [("bilinear", True), ("bilinear", False), ("bicubic", True), ("bicubic", False), ("nearest", None)],+ )+ def test_compile_resized_crop_backend(self, device, dtype, torch_optimizer, resample, align_corners):+ aug = K.RandomResizedCrop((9, 11), resample=resample, align_corners=align_corners)+ input = torch.rand(2, 3, 16, 17, device=device, dtype=dtype, requires_grad=True)+ params = aug.forward_parameters(input.shape)+ expected = aug(input, params=params)+ actual = torch_optimizer(aug, fullgraph=True)(input, params=params)+ self.assert_close(actual, expected)+ weights = torch.rand_like(actual)+ actual_grad = torch.autograd.grad(actual, input, weights)[0]+ if device.type == "cuda" and dtype in (torch.float16, torch.bfloat16):+ # CUDA interpolate accumulates half gradients with reduced precision. Use+ # its float32 result as the oracle for our float32 tap accumulation.+ reference = input.detach().float().requires_grad_()+ expected_grad = torch.autograd.grad(aug(reference, params=params), reference, weights.float())[0].to(dtype)+ else:+ expected_grad = torch.autograd.grad(expected, input, weights)[0]+ self.assert_close(actual_grad, expected_grad)+ # Exercise sampling and resizing in one graph, not just parameter replay.+ fresh = K.RandomResizedCrop((9, 11), resample=resample, align_corners=align_corners)+ fn = torch_optimizer(fresh, fullgraph=True)+ assert fn(input).shape == fn(input).shape == (2, 3, 9, 11)++ @pytest.mark.parametrize("backend", ["eager", "inductor"])+ def test_compile_nearest_upsample_gradient(self, device, dtype, torch_optimizer, backend):+ torch.manual_seed(17)+ aug = K.RandomResizedCrop((32, 32), resample="nearest", align_corners=None)+ input = torch.rand(1, 1, 2, 2, device=device, dtype=dtype, requires_grad=True)+ params = aug.forward_parameters(input.shape)+ params["src"] = torch.zeros(1, 4, 2, device=device, dtype=dtype)+ actual = torch_optimizer(aug, backend=backend, fullgraph=True)(input, params=params)+ self.assert_close(actual, aug(input, params=params), atol=0, rtol=0)+ weights = torch.rand_like(actual)+ # All 1024 output gradients accumulate into one pixel. Half atomics can+ # saturate here; use float32 accumulation for both half dtypes as the oracle.+ reference = input.detach().to(torch.float32 if dtype in (torch.float16, torch.bfloat16) else dtype)+ reference.requires_grad_()+ expected_grad = torch.autograd.grad(aug(reference, params=params), reference, weights.to(reference))[0]+ self.assert_close(torch.autograd.grad(actual, input, weights)[0], expected_grad.to(dtype))++ def test_compile_nearest_rounding(self, device, dtype, torch_optimizer):+ aug = K.RandomResizedCrop((46, 22), resample="nearest", align_corners=None)+ input = torch.arange(14 * 26, device=device, dtype=dtype).reshape(1, 1, 14, 26)+ params = aug.forward_parameters(input.shape)+ params["src"] = torch.tensor([[[0, 0], [25, 0], [25, 13], [0, 13]]], device=device, dtype=dtype)+ self.assert_close(+ torch_optimizer(aug, fullgraph=True)(input, params=params), aug(input, params=params), atol=0, rtol=0+ )++ def test_compile_nearest_without_resize(self, device, dtype, torch_optimizer):+ aug = K.RandomResizedCrop((4, 4), scale=(1, 1), ratio=(1, 1), resample="nearest")+ input = torch.rand(1, 1, 4, 4, device=device, dtype=dtype)+ self.assert_close(torch_optimizer(aug, fullgraph=True)(input), aug(input))++ def test_compile_inherited_override(self, device, dtype, torch_optimizer):+ class CustomFlip(K.RandomHorizontalFlip):+ def forward(self, input, params=None, *, offset=2):+ return super().forward(input, params=params) + offset++ class InheritedFlip(CustomFlip):+ pass++ input = torch.rand(2, 3, 8, 8, device=device, dtype=dtype)+ aug = InheritedFlip(p=1)+ self.assert_close(torch_optimizer(aug, fullgraph=True)(input, offset=3), input.flip(-1) + 3)+ self.assert_close(copy.deepcopy(aug)(input), input.flip(-1) + 2)++ @pytest.mark.parametrize("channels,channels_last", [(1, False), (4, False), (4, True)])+ def test_compile_nearest_large_output(self, device, dtype, torch_optimizer, channels, channels_last):+ aug = K.RandomResizedCrop((1, 210), resample="nearest", align_corners=None)+ input = torch.rand(2, channels, 2, 465, device=device, dtype=dtype)+ if channels_last:+ input = input.contiguous(memory_format=torch.channels_last)+ fn = torch_optimizer(aug, fullgraph=True)+ # Large float64 CPU outputs use a different ATen nearest kernel. Full-width+ # cropped rows can change between channels-last and strided batch layouts.+ for boxes in [+ ((0, 0, 465, 2), (0, 0, 465, 2)),+ ((0, 0, 465, 1), (0, 0, 465, 1)),+ ((0, 0, 465, 1), (0, 1, 465, 1)),+ ((1, 0, 463, 2), (0, 0, 465, 2)),+ ]:+ params = aug.forward_parameters(input.shape)+ params["src"] = torch.tensor(+ [[[x, y], [x + w - 1, y], [x + w - 1, y + h - 1], [x, y + h - 1]] for x, y, w, h in boxes],+ device=device,+ dtype=dtype,+ )+ self.assert_close(fn(input, params=params), aug(input, params=params), atol=0, rtol=0)++ def test_inherited_static_forward(self, device, dtype):+ class StaticFlip(K.RandomHorizontalFlip):+ @staticmethod+ def forward(input):+ return input + 1++ class InheritedFlip(StaticFlip):+ pass++ input = torch.rand(1, 1, 2, 2, device=device, dtype=dtype)+ self.assert_close(InheritedFlip()(input), input + 1)+++class TestRandomCropCompile(BaseTester):+ @pytest.mark.parametrize("padding_mode", ["constant", "reflect", "replicate"])+ def test_compile_crop_replay(self, device, dtype, torch_optimizer, padding_mode):+ aug = K.RandomCrop((5, 7), padding=(2, 1, 3, 2), padding_mode=padding_mode)+ input = torch.rand(2, 3, 12, 15, device=device, dtype=dtype, requires_grad=True)+ counter = CompileCounter()+ fn = torch_optimizer(aug, backend=counter)+ for offset in range(10):+ params = aug.forward_parameters(input.shape)+ params["src"] = torch.tensor(+ [+ [[offset, 0], [offset + 6, 0], [offset + 6, 4], [offset, 4]],+ [[1, 2], [3, 2], [3, 5], [1, 5]],+ ],+ device=device,+ dtype=dtype,+ )+ expected = aug(input, params=params)+ actual = fn(input, params=params)+ self.assert_close(actual, expected)+ weights = torch.rand_like(actual)+ actual_grad = torch.autograd.grad(actual, input, weights)[0]+ if device.type == "cuda" and dtype in (torch.float16, torch.bfloat16):+ # CUDA half interpolate backward rounds atomic updates. Compare with+ # float32 accumulation, as in the real-backend replay tests below.+ reference = input.detach().float().requires_grad_()+ expected_grad = torch.autograd.grad(aug(reference, params=params), reference, weights.float())[0].to(+ dtype+ )+ else:+ expected_grad = torch.autograd.grad(expected, input, weights)[0]+ self.assert_close(actual_grad, expected_grad)+ if offset == 1:+ frames = counter.frame_count+ assert counter.frame_count == frames++ @pytest.mark.parametrize("same_on_batch", [False, True])+ def test_compile_crop_random(self, device, dtype, torch_optimizer, same_on_batch):+ aug = K.RandomCrop((32, 32), same_on_batch=same_on_batch)+ input = torch.rand(32, 3, 64, 64, device=device, dtype=dtype)+ counter = CompileCounter()+ fn = torch_optimizer(aug, backend=counter)+ outputs = []+ for i in range(40):+ outputs.append(fn(input))+ if i == 1:+ frames = counter.frame_count+ assert all(output.shape == (32, 3, 32, 32) for output in outputs)+ assert any(not torch.equal(outputs[0], output) for output in outputs[1:])+ assert counter.frame_count == frames++ @pytest.mark.parametrize("size,pad_if_needed", [((7, 9), False), ((19, 23), False), ((19, 23), True)])+ def test_compile_crop_backend(self, device, dtype, torch_optimizer, size, pad_if_needed):+ aug = K.RandomCrop(size, pad_if_needed=pad_if_needed, padding=1)+ input = torch.rand(2, 3, 12, 15, device=device, dtype=dtype, requires_grad=True)+ fn = torch_optimizer(aug)+ for _ in range(3):+ params = aug.forward_parameters(input.shape)+ expected = aug(input, params=params)+ actual = fn(input, params=params)+ self.assert_close(actual, expected)+ weights = torch.rand_like(actual)+ actual_grad = torch.autograd.grad(actual, input, weights)[0]+ if device.type == "cuda" and dtype in (torch.float16, torch.bfloat16):+ # Compare against opmath accumulation, as for compiled resized crops above.+ reference = input.detach().float().requires_grad_()+ expected_grad = torch.autograd.grad(aug(reference, params=params), reference, weights.float())[0].to(+ dtype+ )+ else:+ expected_grad = torch.autograd.grad(expected, input, weights)[0]+ self.assert_close(actual_grad, expected_grad)++ @pytest.mark.parametrize("augmentation", [K.RandomCrop, K.RandomResizedCrop])+ @pytest.mark.parametrize("nonfinite", [float("nan"), float("inf")])+ @pytest.mark.parametrize("resample", ["bilinear", "bicubic"])+ def test_compile_crop_without_resize_nonfinite(+ self, device, dtype, torch_optimizer, augmentation, nonfinite, resample+ ):+ aug = augmentation((3, 3), resample=resample)+ input = torch.arange(16, device=device, dtype=dtype).reshape(1, 1, 4, 4)+ input[..., 1, 1] = nonfinite+ params = aug.forward_parameters(input.shape)+ params["src"] = torch.tensor([[[0, 0], [2, 0], [2, 2], [0, 2]]], device=device, dtype=dtype)+ actual = torch_optimizer(aug)(input, params=params)+ expected = aug(input, params=params)+ self.assert_close(actual.isnan(), expected.isnan())+ self.assert_close(actual.isinf(), expected.isinf())+ self.assert_close(actual.nan_to_num(), expected.nan_to_num(), atol=0, rtol=0)++ @pytest.mark.parametrize("size,align_corners", [(41, False), (42, True)])+ def test_compile_identity_resize_coordinates(self, device, dtype, torch_optimizer, size, align_corners):+ aug = K.RandomResizedCrop((size, size), align_corners=align_corners)+ input = torch.rand(1, 1, size, size, device=device, dtype=dtype)+ params = aug.forward_parameters(input.shape)+ params["src"] = torch.tensor(+ [[[0, 0], [size - 1, 0], [size - 1, size - 1], [0, size - 1]]], device=device, dtype=dtype+ )+ self.assert_close(torch_optimizer(aug, fullgraph=True)(input, params=params), input, atol=0, rtol=0)diff --git a/tests/augmentation/test_clahe_compile.py b/tests/augmentation/test_clahe_compile.pynew file mode 100644index 000000000..5ecf2b00a--- /dev/null+++ b/tests/augmentation/test_clahe_compile.py@@ -0,0 +1,93 @@+# LICENSE HEADER MANAGED BY add-license-header+#+# Copyright 2018 Kornia Team+#+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.+#++from __future__ import annotations++import pytest+import torch+from torch._dynamo.testing import CompileCounter, CompileCounterWithBackend++from kornia.augmentation import RandomClahe++from testing.base import BaseTester+++class TestClaheCompile(BaseTester):+ @pytest.mark.parametrize("differentiable", [False, True])+ @pytest.mark.parametrize("backend", ["eager", "inductor"])+ def test_compile_replay(self, device, dtype, torch_optimizer, differentiable, backend):+ if backend == "inductor" and dtype in (torch.float16, torch.bfloat16):+ pytest.skip("Inductor changes half-precision lookup rounding in scalar CLAHE as well")+ if differentiable and backend == "inductor" and device.type == "cpu" and torch.__version__.startswith("2.5.1"):+ pytest.skip(+ "PyTorch 2.5.1 CPU Inductor emits invalid VecMask code for differentiable CLAHE, including scalar CLAHE"+ )+ aug = RandomClahe(grid_size=(2, 3), slow_and_differentiable=differentiable, p=1)+ input = torch.rand(2, 2, 12, 18, device=device, dtype=dtype, requires_grad=differentiable)+ params = aug.forward_parameters(input.shape)+ counter = CompileCounter() if backend == "eager" else CompileCounterWithBackend(backend)+ fn = torch_optimizer(aug, backend=counter, fullgraph=True)+ for limits in [(2.0, 40.0), (0.0, 3.0), (-1.0, 0.0), (7.0, 7.0), (40.0, 2.0), (256 / 36, 512 / 36)]:+ params["clip_limit_factor"] = torch.tensor(limits, device=device, dtype=dtype)+ expected = aug(input, params=params)+ actual = fn(input, params=params)+ self.assert_close(actual, expected)+ if differentiable:+ weights = torch.rand_like(actual)+ actual_grad = torch.autograd.grad(actual, input, weights)[0]+ expected_grad = torch.autograd.grad(expected, input, weights)[0]+ if backend == "eager":+ self.assert_close(actual_grad, expected_grad)+ else:+ # Inductor also changes the scalar API's Gaussian-histogram gradients+ # slightly; the counter backend above isolates per-image clipping parity.+ assert torch.isfinite(actual_grad).all()+ assert counter.frame_count == 1++ @pytest.mark.parametrize("same_on_batch", [False, True])+ def test_compile_random_backend(self, device, dtype, torch_optimizer, same_on_batch):+ aug = RandomClahe(clip_limit=(2.0, 40.0), grid_size=(2, 2), same_on_batch=same_on_batch, p=1)+ # A concentrated histogram responds to every clipping threshold; uniform noise can+ # remain unchanged across many draws because its bins never reach the sampled limits.+ input = torch.zeros(2, 1, 16, 16, device=device, dtype=dtype)+ counter = CompileCounterWithBackend("inductor")+ fn = torch_optimizer(aug, backend=counter, fullgraph=True)+ outputs = [fn(input) for _ in range(12)]+ assert all(output.shape == input.shape and output.dtype == input.dtype for output in outputs)+ assert all(torch.isfinite(output).all() for output in outputs)+ assert any(not torch.equal(outputs[0], output) for output in outputs[1:])+ assert counter.frame_count == 1++ def test_compile_backend_gradients(self, device, dtype, torch_optimizer):+ if device.type == "cpu" and torch.__version__.startswith("2.5.1"):+ pytest.skip(+ "PyTorch 2.5.1 CPU Inductor emits invalid VecMask code for differentiable CLAHE, including scalar CLAHE"+ )+ # At the first bin, linspace rounding does not amplify differences through the narrow+ # Gaussian kernel, so the real backend's gradients can be compared at normal tolerances.+ aug = RandomClahe(grid_size=(2, 3), slow_and_differentiable=True, p=1)+ input = torch.zeros(2, 2, 12, 18, device=device, dtype=dtype, requires_grad=True)+ params = aug.forward_parameters(input.shape)+ params["clip_limit_factor"] = torch.tensor([0.0, 40.0], device=device, dtype=dtype)+ actual = torch_optimizer(aug, fullgraph=True)(input, params=params)+ expected = aug(input, params=params)+ self.assert_close(actual, expected)+ weights = torch.rand_like(actual)+ actual_grad = torch.autograd.grad(actual, input, weights)[0]+ expected_grad = torch.autograd.grad(expected, input, weights)[0]+ assert expected_grad.abs().max() > 0+ self.assert_close(actual_grad, expected_grad)