π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix: support augmentation fullgraph compilation (#5183)
NiteeshGowda7224791d6fab58
diff --git a/changelog.d/5183.fixed.md b/changelog.d/5183.fixed.mdnew file mode 100644index 000000000..5960d8e1d--- /dev/null+++ b/changelog.d/5183.fixed.md@@ -0,0 +1 @@+`torch.compile(fullgraph=True)` now traces `RandomCrop` at `p=1`, `crop_by_indices` with `size` and bilinear, bicubic or nearest resampling, and the `ImageModule`, `ImageSequential` and `AugmentationSequential` call paths, including a fixed-order `ColorJiggle`. The containers no longer go through `functools.wraps` inside the traced call. Part of #5137.diff --git a/kornia/augmentation/_2d/geometric/crop.py b/kornia/augmentation/_2d/geometric/crop.pyindex 652ede5f4..c5d834554 100644--- a/kornia/augmentation/_2d/geometric/crop.py+++ b/kornia/augmentation/_2d/geometric/crop.py@@ -23,13 +23,13 @@ import torchfrom 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_tensor, _pad_with_fillfrom kornia.constants import Resamplefrom 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+from kornia.geometry.transform._crop import _compiled_slice_resizefrom kornia.geometry.transform.crop2d import _crop_translation@@ -283,7 +283,7 @@ class RandomCrop(GeometricAugmentationBase2D):transform: Optional[torch.Tensor] = None,) -> torch.Tensor:padding_size: Optional[List[int]] = None- if is_exporting():+ if is_exporting() or is_compiling():# ``padding_size`` is a function of the input shape (see ``forward_parameters``), so let# ``precrop_padding`` recompute it from the static shape instead of reading the tensor back.padding_size = Nonediff --git a/kornia/augmentation/_2d/geometric/resize.py b/kornia/augmentation/_2d/geometric/resize.pyindex 81b47668e..716b887d4 100644--- a/kornia/augmentation/_2d/geometric/resize.py+++ b/kornia/augmentation/_2d/geometric/resize.py@@ -22,10 +22,10 @@ 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 _half_pixel_resize_transformfrom kornia.constants import Resamplefrom kornia.core.utils import is_exportingfrom kornia.geometry.transform import crop_by_transform_mat, get_perspective_transform, resize+from kornia.geometry.transform._crop import _half_pixel_resize_transformfrom kornia.geometry.transform.affwarp import _side_to_image_sizediff --git a/kornia/augmentation/_2d/geometric/resized_crop.py b/kornia/augmentation/_2d/geometric/resized_crop.pyindex eef9decc6..28b1ec054 100644--- a/kornia/augmentation/_2d/geometric/resized_crop.py+++ b/kornia/augmentation/_2d/geometric/resized_crop.py@@ -24,10 +24,10 @@ 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_resize, _half_pixel_resize_transformfrom kornia.constants import Resamplefrom kornia.core.utils import is_compilingfrom kornia.geometry.transform import crop_by_indices, crop_by_transform_mat, get_perspective_transform+from kornia.geometry.transform._crop import _compiled_slice_resize, _half_pixel_resize_transformclass RandomResizedCrop(GeometricAugmentationBase2D):diff --git a/kornia/augmentation/container/augment.py b/kornia/augmentation/container/augment.pyindex 058afbac7..bdbe1b70e 100644--- a/kornia/augmentation/container/augment.py+++ b/kornia/augmentation/container/augment.py@@ -15,6 +15,7 @@# limitations under the License.#+import sysimport warningsfrom typing import Any, Dict, List, Literal, Optional, Sequence, Tuple, Union, cast@@ -26,7 +27,6 @@ from kornia.augmentation._3d.base import AugmentationBase3D, RigidAffineAugmentafrom kornia.augmentation.base import _AugmentationBasefrom kornia.augmentation.utils.helpers import _boxes_to_padded_tensorfrom kornia.constants import DataKey, Resample-from kornia.core.external import numpy as npfrom kornia.core.ops import eye_likefrom kornia.core.utils import is_autocast_enabled, is_exportingfrom kornia.geometry.boxes import Boxes, VideoBoxes@@ -53,6 +53,13 @@ _CLS_OPTIONS = (DataKey.CLASS, DataKey.LABEL)MaskDataType = Union[torch.Tensor, List[torch.Tensor]]+def _is_numpy_array(arg: Any) -> bool:+ # Look NumPy up instead of importing it through the lazy loader: an array can exist only once NumPy is+ # imported, and an import inside a compiled ``forward`` is a graph break (``importlib.import_module``).+ numpy_module = sys.modules.get("numpy")+ return numpy_module is not None and isinstance(arg, numpy_module.ndarray)++class AugmentationSequential(TransformMatrixMinIn, ImageSequential):r"""AugmentationSequential for handling multiple input types like inputs, masks, keypoints at once.@@ -652,7 +659,7 @@ class AugmentationSequential(TransformMatrixMinIn, ImageSequential):keys, data_keys, args, _ = self._preproc_dict_data(inputs[0])converted_dict = dict(inputs[0])for key, arg, data_key in zip(keys, args, data_keys):- if isinstance(arg, np.ndarray):+ if _is_numpy_array(arg):if data_key in _IMG_OPTIONS:converted_dict[key] = self.to_tensor(arg)else:@@ -669,10 +676,9 @@ class AugmentationSequential(TransformMatrixMinIn, ImageSequential):self._check_output_type(output_type)# run the forward pass in tensor mode and convert the output to ``output_type`` only after the image# has been cached, so ``.show()`` / ``.save()`` never receive a NumPy array or PIL images- decorated_forward = self.convert_input_output(input_names_to_handle=input_names_to_handle)(- super(ImageSequential, self).__call__+ tensor_output = self._call_converted(+ super(ImageSequential, self).__call__, converted_inputs, kwargs, input_names_to_handle, "pt")- tensor_output = decorated_forward(*converted_inputs, **kwargs)in_data_keys: Optional[List[DataKey]]original_keys: Optional[Tuple[str, ...]] = None@@ -694,7 +700,7 @@ class AugmentationSequential(TransformMatrixMinIn, ImageSequential):@staticmethoddef _convert_numpy_non_image(arg: Any, data_key: DataKey) -> Any:- if not isinstance(arg, np.ndarray) or data_key in _IMG_OPTIONS:+ if not _is_numpy_array(arg) or data_key in _IMG_OPTIONS:return argif data_key in _MSK_OPTIONS:return image_to_tensor(arg)diff --git a/kornia/augmentation/container/image.py b/kornia/augmentation/container/image.pyindex e42875a90..f24a033c2 100644--- a/kornia/augmentation/container/image.py+++ b/kornia/augmentation/container/image.py@@ -442,9 +442,8 @@ class ImageSequential(ImageSequentialBase, ImageModuleForSequentialMixIn):self._check_output_type(output_type)# run the forward pass in tensor mode, cache that tensor for ``.show()`` / ``.save()``, and convert the# output to ``output_type`` only afterwards, so the helpers never receive a NumPy array or PIL images- decorated_forward = self.convert_input_output(input_names_to_handle=input_names_to_handle)(super().__call__)- tensor_output = decorated_forward(*inputs, **kwargs)- self._store_output_image(tensor_output, "pt")+ tensor_output = self._call_converted(super().__call__, inputs, kwargs, input_names_to_handle, "pt")+ self._store_output_image(self._convert_output(tensor_output, "pt"), "pt")_output_image = self._convert_output(tensor_output, output_type)else:_output_image = super().__call__(*inputs, **kwargs)diff --git a/kornia/core/mixin/image_module.py b/kornia/core/mixin/image_module.pyindex be0a586d0..e7423b129 100644--- a/kornia/core/mixin/image_module.py+++ b/kornia/core/mixin/image_module.py@@ -119,29 +119,7 @@ class ImageModuleMixIn:def decorator(func: Callable[[Any], Any]) -> Callable[[Any], Any]:@wraps(func)def wrapper(*args: Any, **kwargs: Any) -> Union[Any, List[Any]]:- if input_names_to_handle is None:- # Convert image-like arguments while treating only the first positional string as an image path.- args = tuple(- self.to_tensor(arg) if (i == 0 or not isinstance(arg, str)) and self._is_valid_arg(arg) else arg- for i, arg in enumerate(args)- )- kwargs = {- k: self.to_tensor(v) if not isinstance(v, str) and self._is_valid_arg(v) else v- for k, v in kwargs.items()- }- else:- # Convert specified args to tensors- args = list(args) # type:ignore- for i, (arg, name) in enumerate(zip(args, func.__code__.co_varnames)): # ty: ignore[unresolved-attribute]- if name in input_names_to_handle:- args[i] = self.to_tensor(arg) # type:ignore- # Convert specified kwargs to tensors- for name, value in kwargs.items():- if name in input_names_to_handle:- kwargs[name] = self.to_tensor(value)-- # Call the actual forward method and convert its outputs to the desired type- tensor_outputs = func(*args, **kwargs)+ tensor_outputs = self._call_converted(func, args, kwargs, input_names_to_handle, "pt")if cache_output:self._store_output_image(self._convert_output(tensor_outputs, "pt"), "pt")return self._convert_output(tensor_outputs, output_type)@@ -150,6 +128,34 @@ class ImageModuleMixIn:return decorator+ def _call_converted(+ self,+ func: Callable[[Any], Any],+ args: Tuple[Any, ...],+ kwargs: dict[str, Any],+ input_names_to_handle: Optional[List[Any]],+ output_type: Literal["pt", "numpy", "pil"],+ ) -> Union[Any, List[Any]]:+ if input_names_to_handle is None:+ args = tuple(+ self.to_tensor(arg) if (i == 0 or not isinstance(arg, str)) and self._is_valid_arg(arg) else arg+ for i, arg in enumerate(args)+ )+ kwargs = {+ k: self.to_tensor(v) if not isinstance(v, str) and self._is_valid_arg(v) else v+ for k, v in kwargs.items()+ }+ else:+ args = list(args)+ for i, (arg, name) in enumerate(zip(args, func.__code__.co_varnames)): # ty: ignore[unresolved-attribute]+ if name in input_names_to_handle:+ args[i] = self.to_tensor(arg) # type:ignore+ for name, value in kwargs.items():+ if name in input_names_to_handle:+ kwargs[name] = self.to_tensor(value)++ return func(*args, **kwargs)+@staticmethoddef _check_output_type(output_type: str) -> None:if output_type not in ("pt", "numpy", "pil"):diff --git a/kornia/core/module.py b/kornia/core/module.pyindex 5398b4db9..d8ccc9cbe 100644--- a/kornia/core/module.py+++ b/kornia/core/module.py@@ -89,12 +89,12 @@ class ImageModule(nn.Module, ImageModuleMixIn, ONNXExportMixin):Callable: Decorated function with converted input and output types."""- # Wrap the forward method with the decorator+ # Convert inputs and outputs around the forward callif not self._disable_features:- decorated_forward = self.convert_input_output(- input_names_to_handle=input_names_to_handle, output_type=output_type, cache_output=True- )(super().__call__)- _output_image = decorated_forward(*inputs, **kwargs)+ tensor_output = self._call_converted(super().__call__, inputs, kwargs, input_names_to_handle, "pt")+ self._store_output_image(self._convert_output(tensor_output, "pt"), "pt")+ _output_image = self._convert_output(tensor_output, output_type)+else:_output_image = super().__call__(*inputs, **kwargs)return _output_image@@ -164,12 +164,12 @@ class ImageSequential(nn.Sequential, ImageModuleMixIn, ONNXExportMixin):Callable: Decorated function with converted input and output types."""- # Wrap the forward method with the decorator+ # Convert inputs and outputs around the forward callif not self._disable_features:- decorated_forward = self.convert_input_output(- input_names_to_handle=input_names_to_handle, output_type=output_type, cache_output=True- )(super().__call__)- _output_image = decorated_forward(*inputs, **kwargs)+ tensor_output = self._call_converted(super().__call__, inputs, kwargs, input_names_to_handle, "pt")+ self._store_output_image(self._convert_output(tensor_output, "pt"), "pt")+ _output_image = self._convert_output(tensor_output, output_type)+else:_output_image = super().__call__(*inputs, **kwargs)return _output_imagediff --git a/kornia/augmentation/utils/_crop.py b/kornia/geometry/transform/_crop.pysimilarity index 100%rename from kornia/augmentation/utils/_crop.pyrename to kornia/geometry/transform/_crop.pydiff --git a/kornia/geometry/transform/crop2d.py b/kornia/geometry/transform/crop2d.pyindex f0d45fa24..652739a94 100644--- a/kornia/geometry/transform/crop2d.py+++ b/kornia/geometry/transform/crop2d.py@@ -23,8 +23,9 @@ from torch import nnfrom kornia.constants import Resamplefrom kornia.core.check import KORNIA_CHECK_SHAPE-from kornia.core.utils import is_exporting+from kornia.core.utils import is_compiling, is_exportingfrom kornia.geometry.bbox import infer_bbox_shape+from kornia.geometry.transform._crop import _compiled_slice_resizefrom .affwarp import resizefrom .imgwarp import get_perspective_transform, warp_affine, warp_perspective@@ -437,8 +438,15 @@ def crop_by_indices(``antialias=False`` option- ``shape_compensation`` (``'resize'`` by default) applies whenever the croppedslice does not match ``size``, whether or not ``src_box`` is identical across- the batch β each row's output depends only on its own box. Graph export is the- exception: it always resamples (see the note below)+ the batch β each row's output depends only on its own box.++ .. note::+ Under :func:`torch.compile` a non-empty batch with ``size`` given, ``'bilinear'``,+ ``'bicubic'`` or ``'nearest'`` interpolation, ``antialias=False`` and+ ``shape_compensation='resize'`` is cropped by a gather that keeps the box coordinates+ on the device, so it traces with ``fullgraph=True`` and matches the eager result up to+ float rounding. Every other call keeps the eager path, which reads the box coordinates+ back to Python and breaks the graph. Graph export is described in the note below.Args:input_tensor: the 2D image torch.Tensor with shape (B, C, H, W).@@ -486,6 +494,17 @@ def crop_by_indices(if size is not None and is_exporting():return _crop_by_indices_export(input_tensor, src_box, size, interpolation)+ if (+ size is not None+ and is_compiling()+ and B > 0+ and (interpolation in ("bilinear", "bicubic") or (interpolation == "nearest" and align_corners is None))+ and not antialias+ and shape_compensation == "resize"+ ):+ # ``_compiled_slice_resize`` implements only these three modes (any other one would be resampled as+ # 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)# 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(...)`` insidediff --git a/tests/augmentation/test_augmentation.py b/tests/augmentation/test_augmentation.pyindex 333782e3b..80eb8be8e 100644--- a/tests/augmentation/test_augmentation.py+++ b/tests/augmentation/test_augmentation.py@@ -3621,6 +3621,18 @@ class TestRandomCrop(BaseTester):with pytest.raises(ValueError, match="one value per channel"):RandomCrop((4, 4), padding=1, fill=(1.0, 0.0), p=1.0).precrop_padding(image)+ def test_dynamo(self, device, dtype, torch_optimizer):+ torch.manual_seed(0)+ input = torch.rand(4, 3, 64, 64, device=device, dtype=dtype)+ op = RandomCrop((32, 32), p=1.0)+ params = op.forward_parameters(input.shape)+ expected = op(input, params=params)+ compiled = torch_optimizer(op, fullgraph=True)+ self.assert_close(compiled(input, params=params), expected)+ # Also compile the full forward so parameter generation is captured too.+ torch._dynamo.reset()+ assert torch_optimizer(RandomCrop((32, 32), p=1.0), fullgraph=True)(input).shape == input.shape[:2] + (32, 32)+# TODO: improve and implement more meaningful smoke tests e.g check for a consistent# return values such a Tensor variable.@pytest.mark.xfail(reason="might fail under windows OS due to printing preicision.")diff --git a/tests/augmentation/test_augmentation_compile.py b/tests/augmentation/test_augmentation_compile.pyindex 81b977df4..f8b655ad3 100644--- a/tests/augmentation/test_augmentation_compile.py+++ b/tests/augmentation/test_augmentation_compile.py@@ -30,6 +30,36 @@ from testing.base import BaseTesterclass TestAugmentationCompile(BaseTester):+ def test_dynamo_color_jiggle(self, device, dtype, torch_optimizer):+ input = torch.rand(4, 3, 64, 64, device=device, dtype=dtype)+ aug = K.AugmentationSequential(+ K.RandomHorizontalFlip(p=1.0),+ K.ColorJiggle(+ brightness=0.2,+ contrast=0.2,+ saturation=0.2,+ hue=0.1,+ order=(0, 1, 2, 3),+ p=1.0,+ ),+ )++ compiled = torch_optimizer(aug, fullgraph=True)+ output = compiled(input)++ assert output.shape == input.shape+ assert torch.isfinite(output).all()++ def test_dynamo_sequential_does_not_import_numpy(self, device, dtype, torch_optimizer, monkeypatch):+ # The container's NumPy-input check must not load NumPy through the lazy loader: Dynamo cannot trace+ # ``importlib.import_module``, so the first compiled call in a fresh process broke the graph.+ from kornia.core.external import numpy as lazy_numpy++ monkeypatch.setattr(lazy_numpy, "module", None)+ input = torch.rand(2, 3, 8, 8, device=device, dtype=dtype)+ aug = K.AugmentationSequential(K.RandomHorizontalFlip(p=1.0))+ self.assert_close(torch_optimizer(aug, fullgraph=True)(input), input.flip(-1))+def test_compile_distinct_classes(self, device, dtype, torch_optimizer):# More classes than Dynamo's default per-code-object cache limit (#4658).augmentations = [diff --git a/tests/augmentation/test_parameter_constants.py b/tests/augmentation/test_parameter_constants.pyindex 5a99be5e8..7d7dcef05 100644--- a/tests/augmentation/test_parameter_constants.py+++ b/tests/augmentation/test_parameter_constants.py@@ -131,9 +131,8 @@ class TestAugmentationConstantTransfer(BaseTester):params = aug.forward_parameters(input.shape)return aug(input, params=params), params- # RandomCrop reads replayable padding from tensors; Crop3D validates crop sizes.- # These pre-existing graph breaks are separate from constant transfer safety.- compiled = torch_optimizer(apply, fullgraph=not isinstance(aug, (K.RandomCrop, K.RandomCrop3D)))+ # Crop3D validates crop sizes and still has a separate graph break.+ compiled = torch_optimizer(apply, fullgraph=not isinstance(aug, K.RandomCrop3D))for _ in range(2):actual, params = compiled(input)if device.type == "cuda":diff --git a/tests/core/test_module.py b/tests/core/test_module.pyindex 9b4151e6c..d525bf290 100644--- a/tests/core/test_module.py+++ b/tests/core/test_module.py@@ -96,6 +96,27 @@ class TestImageModuleMixIn:output = dummy_func(sample_image)assert isinstance(output, (np.ndarray,))+ def test_convert_input_output_preserves_function_metadata(self, img_module):+ def dummy_func(tensor):+ """Test function docstring."""+ return tensor++ decorated = img_module.convert_input_output()(dummy_func)++ assert decorated.__name__ == dummy_func.__name__+ assert decorated.__doc__ == dummy_func.__doc__+ assert decorated.__wrapped__ is dummy_func++ def test_convert_input_output_caches_single_output_tuple_as_tensor(self, img_module, sample_tensor):+ # A one-element tuple is returned as its element; the cache must hold the same tensor for ``show()``.+ decorated = img_module.convert_input_output(cache_output=True)(lambda tensor: (tensor,))++ output = decorated(sample_tensor)++ assert isinstance(output, torch.Tensor)+ assert isinstance(img_module._output_image, torch.Tensor)+ assert torch.equal(img_module._output_image, sample_tensor)+def test_show(self, img_module, sample_tensor):img_module._output_image = sample_tensorpil_image = img_module.show(display=False)diff --git a/tests/geometry/transform/test_crop2d.py b/tests/geometry/transform/test_crop2d.pyindex 7cd985328..0400a2f54 100644--- a/tests/geometry/transform/test_crop2d.py+++ b/tests/geometry/transform/test_crop2d.py@@ -558,16 +558,93 @@ class TestCropByIndices(BaseTester):self.assert_close(kornia.geometry.transform.crop_by_indices(inp, indices), expected)def test_dynamo(self, device, dtype, torch_optimizer):- # Define scriptop = kornia.geometry.transform.crop_by_indicesop_script = torch_optimizer(op)- # Define inputimg = torch.ones(1, 2, 5, 4, device=device, dtype=dtype)+ src_box = torch.tensor([[[0, 0], [1, 0], [1, 1], [0, 1]]], device=device, dtype=torch.int64)++ actual = op_script(img, src_box)+ expected = op(img, src_box)++ self.assert_close(actual, expected, rtol=1e-4, atol=1e-4)++ @pytest.mark.parametrize(+ "size, interpolation, align_corners, src_box",+ [+ (+ (8, 8),+ "bilinear",+ None,+ [[[1, 1], [4, 1], [4, 4], [1, 4]]],+ ),+ (+ (2, 2),+ "bilinear",+ True,+ [[[0, 0], [7, 0], [7, 7], [0, 7]]],+ ),+ (+ (8, 8),+ "nearest",+ None,+ [[[0, 0], [3, 0], [3, 3], [0, 3]]],+ ),+ (+ (8, 8),+ "bicubic",+ None,+ [[[0, 0], [3, 0], [3, 3], [0, 3]]],+ ),+ ],+ )+ def test_dynamo_resized(self, size, interpolation, align_corners, src_box, device, dtype, torch_optimizer):+ op = kornia.geometry.transform.crop_by_indices+ img = torch.randn(1, 3, 8, 8, device=device, dtype=dtype)+ src_box = torch.tensor(src_box, device=device, dtype=torch.int64)++ expected = op(+ img,+ src_box,+ size=size,+ interpolation=interpolation,+ align_corners=align_corners,+ )+ actual = torch_optimizer(op, fullgraph=True)(+ img,+ src_box,+ size=size,+ interpolation=interpolation,+ align_corners=align_corners,+ )- actual = op_script(img, torch.tensor([[[0, 0], [1, 0], [1, 1], [0, 1]]]))- expected = op(img, torch.tensor([[[0, 0], [1, 0], [1, 1], [0, 1]]]))self.assert_close(actual, expected, rtol=1e-4, atol=1e-4)+ @pytest.mark.parametrize(+ ("batch", "interpolation"),+ [(1, "area"), (1, "nearest-exact"), (0, "bilinear")],+ )+ def test_dynamo_resized_keeps_eager_path(self, batch, interpolation, device, dtype, torch_optimizer):+ # The compiled gather implements bilinear, bicubic and nearest only, and needs a box to gather from:+ # other modes and an empty batch must keep the eager path instead of being resampled as bicubic.+ op = kornia.geometry.transform.crop_by_indices+ img = torch.arange(64, device=device, dtype=dtype).reshape(1, 1, 8, 8).repeat(batch, 1, 1, 1)+ src_box = torch.tensor([[[1, 1], [4, 1], [4, 4], [1, 4]]] * batch, device=device, dtype=torch.int64)+ src_box = src_box.reshape(batch, 4, 2)++ expected = op(img, src_box, size=(6, 6), interpolation=interpolation)+ actual = torch_optimizer(op)(img, src_box, size=(6, 6), interpolation=interpolation)++ assert actual.shape == (batch, 1, 6, 6)+ self.assert_close(actual, expected)++ def test_dynamo_resized_nearest_rejects_align_corners(self, device, dtype, torch_optimizer):+ # ``interpolate`` rejects ``align_corners`` for nearest; the compiled crop must not accept it silently.+ img = torch.rand(1, 1, 8, 8, device=device, dtype=dtype)+ src_box = torch.tensor([[[1, 1], [4, 1], [4, 4], [1, 4]]], device=device, dtype=torch.int64)+ op = torch_optimizer(kornia.geometry.transform.crop_by_indices)+ with pytest.raises((ValueError, RuntimeError), match="align_corners option can only be set"):+ op(img, src_box, size=(6, 6), interpolation="nearest", align_corners=True)+@pytest.mark.parametrize("size", [(2, 3), None])def test_crop_by_indices_empty_batch(self, size, device, dtype):# Empty in, empty out (#4429): the uniform-box fast path read the first box of an empty batch