Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

refactor(augmentation): makes it onnx exportable (#3722)

Dhruv Jain9986de7e8f60
diff --git a/kornia/augmentation/_2d/base.py b/kornia/augmentation/_2d/base.py
index 925375bae..9f395dce5 100644
--- a/kornia/augmentation/_2d/base.py
+++ b/kornia/augmentation/_2d/base.py
@@ -101,22 +101,24 @@ class RigidAffineAugmentationBase2D(AugmentationBase2D):
) -> torch.Tensor:
"""Generate transformation matrices with the given input and param settings."""
batch_prob = params["batch_prob"]
- to_apply = batch_prob > 0.5 # NOTE: in case of Relaxed Distributions.
+ to_apply = batch_prob > 0.5
in_tensor = self.transform_tensor(input)
- if not to_apply.any():
- trans_matrix = self.identity_matrix(in_tensor)
- elif to_apply.all():
- trans_matrix = self.compute_transformation(in_tensor, params=params, flags=flags)
- else:
- trans_matrix_A = self.identity_matrix(in_tensor)
- trans_matrix_B = self.compute_transformation(in_tensor[to_apply], params=params, flags=flags)
- if is_autocast_enabled():
- trans_matrix_A = trans_matrix_A.type(input.dtype)
- trans_matrix_B = trans_matrix_B.type(input.dtype)
+ trans_matrix_applied = self.compute_transformation(in_tensor, params=params, flags=flags)
+ trans_matrix_identity = self.identity_matrix(in_tensor)
+
+ if is_autocast_enabled():
+ trans_matrix_applied = trans_matrix_applied.type(input.dtype)
+ trans_matrix_identity = trans_matrix_identity.type(input.dtype)
- trans_matrix = trans_matrix_A.index_put((to_apply,), trans_matrix_B)
+ # If batch sizes line up, do the where-blend. Otherwise (e.g. VideoSequential
+ # passes B-sized batch_prob into a B*T-sized input) fall back to all-or-nothing.
+ if trans_matrix_applied.shape[0] == to_apply.shape[0] == trans_matrix_identity.shape[0]:
+ to_apply_expanded = to_apply.view(-1, *([1] * (trans_matrix_applied.dim() - 1)))
+ trans_matrix = torch.where(to_apply_expanded, trans_matrix_applied, trans_matrix_identity)
+ else:
+ trans_matrix = trans_matrix_applied if bool(to_apply.any()) else trans_matrix_identity
return trans_matrix
diff --git a/kornia/augmentation/_2d/geometric/affine.py b/kornia/augmentation/_2d/geometric/affine.py
index fb93a08f9..6748602b0 100644
--- a/kornia/augmentation/_2d/geometric/affine.py
+++ b/kornia/augmentation/_2d/geometric/affine.py
@@ -15,6 +15,7 @@
# limitations under the License.
#
+import math
from typing import Any, Dict, Optional, Tuple, Union
import torch
@@ -124,13 +125,19 @@ class RandomAffine(GeometricAugmentationBase2D):
def compute_transformation(
self, input: torch.Tensor, params: Dict[str, torch.Tensor], flags: Dict[str, Any]
) -> torch.Tensor:
+ # ``torch.deg2rad`` lowers as ``aten::deg2rad`` which the legacy ONNX exporter
+ # does not support at opset 20. Multiply by ``pi/180`` explicitly same value,
+ # but only basic arithmetic ops in the trace.
+ deg2rad_factor: float = math.pi / 180.0
+ shear_x = torch.as_tensor(params["shear_x"], device=input.device, dtype=input.dtype) * deg2rad_factor
+ shear_y = torch.as_tensor(params["shear_y"], device=input.device, dtype=input.dtype) * deg2rad_factor
return get_affine_matrix2d(
torch.as_tensor(params["translations"], device=input.device, dtype=input.dtype),
torch.as_tensor(params["center"], device=input.device, dtype=input.dtype),
torch.as_tensor(params["scale"], device=input.device, dtype=input.dtype),
torch.as_tensor(params["angle"], device=input.device, dtype=input.dtype),
- torch.deg2rad(torch.as_tensor(params["shear_x"], device=input.device, dtype=input.dtype)),
- torch.deg2rad(torch.as_tensor(params["shear_y"], device=input.device, dtype=input.dtype)),
+ shear_x,
+ shear_y,
)
def apply_transform(
diff --git a/kornia/augmentation/_2d/geometric/shear.py b/kornia/augmentation/_2d/geometric/shear.py
index cb2c51610..65dc4ec09 100644
--- a/kornia/augmentation/_2d/geometric/shear.py
+++ b/kornia/augmentation/_2d/geometric/shear.py
@@ -15,6 +15,7 @@
# limitations under the License.
#
+import math
from typing import Any, Dict, Optional, Tuple, Union
import torch
@@ -98,10 +99,15 @@ class RandomShear(GeometricAugmentationBase2D):
def compute_transformation(
self, input: torch.Tensor, params: Dict[str, torch.Tensor], flags: Dict[str, Any]
) -> torch.Tensor:
+ # Inline ``deg2rad`` so the trace lowers to plain multiply (legacy ONNX has
+ # no symbolic for ``aten::deg2rad`` at opset 20).
+ deg2rad_factor: float = math.pi / 180.0
+ shear_x = torch.as_tensor(params["shear_x"], device=input.device, dtype=input.dtype) * deg2rad_factor
+ shear_y = torch.as_tensor(params["shear_y"], device=input.device, dtype=input.dtype) * deg2rad_factor
return get_shear_matrix2d(
torch.as_tensor(params["center"], device=input.device, dtype=input.dtype),
- torch.deg2rad(torch.as_tensor(params["shear_x"], device=input.device, dtype=input.dtype)),
- torch.deg2rad(torch.as_tensor(params["shear_y"], device=input.device, dtype=input.dtype)),
+ shear_x,
+ shear_y,
)
def apply_transform(
diff --git a/kornia/augmentation/_2d/intensity/normalize.py b/kornia/augmentation/_2d/intensity/normalize.py
index 0ff143ced..74c41b15b 100644
--- a/kornia/augmentation/_2d/intensity/normalize.py
+++ b/kornia/augmentation/_2d/intensity/normalize.py
@@ -81,4 +81,11 @@ class Normalize(IntensityAugmentationBase2D):
def apply_transform(
self, input: Tensor, params: dict[str, Tensor], flags: dict[str, Any], transform: Optional[Tensor] = None
) -> Tensor:
- return normalize(input, flags["mean"], flags["std"])
+ mean: Tensor = flags["mean"]
+ std: Tensor = flags["std"]
+ if torch.onnx.is_in_onnx_export():
+ if mean.dim() == 1:
+ mean = mean.view(1, -1)
+ if std.dim() == 1:
+ std = std.view(1, -1)
+ return normalize(input, mean, std)
diff --git a/kornia/augmentation/_2d/mix/base.py b/kornia/augmentation/_2d/mix/base.py
index 9ab5a8552..7c629dd8a 100644
--- a/kornia/augmentation/_2d/mix/base.py
+++ b/kornia/augmentation/_2d/mix/base.py
@@ -89,16 +89,34 @@ class MixAugmentationBaseV2(_BasicAugmentationBase):
self, input: torch.Tensor, params: Dict[str, torch.Tensor], flags: Dict[str, Any]
) -> torch.Tensor:
batch_prob = params["batch_prob"]
- to_apply = batch_prob > 0.5 # NOTE: in case of Relaxed Distributions.
+ to_apply = batch_prob > 0.5
ori_shape = input.shape
in_tensor = self.transform_tensor(input)
- output = in_tensor
- if sum(to_apply) != len(to_apply):
- output = self.apply_non_transform(in_tensor, params, flags)
- if sum(to_apply) != 0:
- applied = self.apply_transform(in_tensor, params, flags)
- output = self.apply_non_transform(in_tensor, params, flags)
- output = output.index_put((to_apply,), self.apply_non_transform(applied, params, flags))
+
+ # Compute the non-transform branch first; if no element is to be transformed,
+ # short-circuit (mix transforms like RandomJigsaw subset their input internally
+ # and can't operate on an empty subset).
+ non_applied = self.apply_non_transform(in_tensor, params, flags)
+ if not bool(to_apply.any()):
+ output = non_applied
+ return _transform_output_shape(output, ori_shape) if self.keepdim else output
+
+ # Run the transform branch on the full batch (the random-generator contract is
+ # full-batch sized now), then pass it through ``apply_non_transform`` so any
+ # subclass post-processing (e.g. resize to ``output_size`` in ``RandomMosaic``)
+ # is applied uniformly to both branches.
+ applied = self.apply_transform(in_tensor, params, flags)
+ applied_post = self.apply_non_transform(applied, params, flags)
+
+ if applied_post.shape == non_applied.shape and applied_post.shape[0] == to_apply.shape[0]:
+ to_apply_expanded = to_apply.view(-1, *([1] * (applied_post.dim() - 1)))
+ output = torch.where(to_apply_expanded, applied_post, non_applied)
+ else:
+ # Shape-changing mix augmentations (e.g. RandomMosaic when ``output_size``
+ # differs from the input size) cannot be where-blended. Fall back to the
+ # all-applied branch.
+ output = applied_post
+
output = _transform_output_shape(output, ori_shape) if self.keepdim else output
return output
diff --git a/kornia/augmentation/_2d/mix/jigsaw.py b/kornia/augmentation/_2d/mix/jigsaw.py
index 0811ea186..b56feb8cc 100644
--- a/kornia/augmentation/_2d/mix/jigsaw.py
+++ b/kornia/augmentation/_2d/mix/jigsaw.py
@@ -78,7 +78,8 @@ class RandomJigsaw(MixAugmentationBaseV2):
input = input[to_apply].clone()
b, c, h, w = input.shape
- perm = params["permutation"]
+ # Params are generated for the full batch; slice to subset.
+ perm = params["permutation"][to_apply]
# Note: with a 100x100 image and a grid size of 3x3, it could work if
# we make h = piece_size_h * self.flags["grid"][0] with one pixel loss, then resize to 100 x 100.
# Probably worth to check if we should tolerate such "errorness" or to raise it as an error.
diff --git a/kornia/augmentation/_2d/mix/mosaic.py b/kornia/augmentation/_2d/mix/mosaic.py
index 983fd07f6..320ef5967 100644
--- a/kornia/augmentation/_2d/mix/mosaic.py
+++ b/kornia/augmentation/_2d/mix/mosaic.py
@@ -124,11 +124,15 @@ class RandomMosaic(MixAugmentationBaseV2):
idx = torch.arange(0, input.data.shape[0], device=input.device, dtype=torch.long)[to_apply]
maybe_out_boxes: Optional[Boxes] = None
+ # ``batch_shapes`` and ``src_box`` are full-batch sized.
+ # Subset them to match ``idx`` (the to_apply indices).
+ batch_shapes_idx = batch_shapes[to_apply]
+ src_box_idx = src_box[to_apply]
for i in range(flags["mosaic_grid"][0]):
for j in range(flags["mosaic_grid"][1]):
_offset = offset.clone()
- _offset[idx, 0] = batch_shapes[:, -2] * i - src_box[:, 0, 0]
- _offset[idx, 1] = batch_shapes[:, -1] * j - src_box[:, 0, 1]
+ _offset[idx, 0] = batch_shapes_idx[:, -2] * i - src_box_idx[:, 0, 0]
+ _offset[idx, 1] = batch_shapes_idx[:, -1] * j - src_box_idx[:, 0, 1]
_box = input.clone()
_idx = i * flags["mosaic_grid"][1] + j
_box._data[params["permutation"][:, 0]] = _box._data[params["permutation"][:, _idx]]
diff --git a/kornia/augmentation/_3d/base.py b/kornia/augmentation/_3d/base.py
index ed4e4a868..b8d208b14 100644
--- a/kornia/augmentation/_3d/base.py
+++ b/kornia/augmentation/_3d/base.py
@@ -93,17 +93,19 @@ class RigidAffineAugmentationBase3D(AugmentationBase3D):
) -> torch.Tensor:
"""Generate transformation matrices with the given input and param settings."""
batch_prob = params["batch_prob"]
- to_apply = batch_prob > 0.5 # NOTE: in case of Relaxed Distributions.
+ to_apply = batch_prob > 0.5
+
in_tensor = self.transform_tensor(input)
- if not to_apply.any():
- trans_matrix = self.identity_matrix(in_tensor)
- elif to_apply.all():
- trans_matrix = self.compute_transformation(in_tensor, params=params, flags=flags)
+
+ trans_matrix_applied = self.compute_transformation(in_tensor, params=params, flags=flags)
+ trans_matrix_identity = self.identity_matrix(in_tensor)
+
+ if trans_matrix_applied.shape[0] == to_apply.shape[0] == trans_matrix_identity.shape[0]:
+ to_apply_expanded = to_apply.view(-1, *([1] * (trans_matrix_applied.dim() - 1)))
+ trans_matrix = torch.where(to_apply_expanded, trans_matrix_applied, trans_matrix_identity)
else:
- trans_matrix = self.identity_matrix(in_tensor)
- trans_matrix = trans_matrix.index_put(
- (to_apply,), self.compute_transformation(in_tensor[to_apply], params=params, flags=flags)
- )
+ trans_matrix = trans_matrix_applied if bool(to_apply.any()) else trans_matrix_identity
+
return trans_matrix
def inverse_inputs(
diff --git a/kornia/augmentation/_3d/geometric/affine.py b/kornia/augmentation/_3d/geometric/affine.py
index a356fe8d1..f01b30b99 100644
--- a/kornia/augmentation/_3d/geometric/affine.py
+++ b/kornia/augmentation/_3d/geometric/affine.py
@@ -15,6 +15,7 @@
# limitations under the License.
#
+import math
from typing import Any, Dict, Optional, Tuple, Union
import torch
@@ -148,17 +149,20 @@ class RandomAffine3D(GeometricAugmentationBase3D):
def compute_transformation(
self, input: torch.Tensor, params: Dict[str, torch.Tensor], flags: Dict[str, Any]
) -> torch.Tensor:
+ # Inline ``deg2rad`` so the trace lowers to plain multiply (legacy ONNX has
+ # no symbolic for ``aten::deg2rad`` at opset 20).
+ deg2rad_factor: float = math.pi / 180.0
transform: torch.Tensor = get_affine_matrix3d(
params["translations"],
params["center"],
params["scale"],
params["angles"],
- torch.deg2rad(params["sxy"]),
- torch.deg2rad(params["sxz"]),
- torch.deg2rad(params["syx"]),
- torch.deg2rad(params["syz"]),
- torch.deg2rad(params["szx"]),
- torch.deg2rad(params["szy"]),
+ params["sxy"] * deg2rad_factor,
+ params["sxz"] * deg2rad_factor,
+ params["syx"] * deg2rad_factor,
+ params["syz"] * deg2rad_factor,
+ params["szx"] * deg2rad_factor,
+ params["szy"] * deg2rad_factor,
).to(input)
return transform
diff --git a/kornia/augmentation/base.py b/kornia/augmentation/base.py
index 1cb08bc85..c213baa3c 100644
--- a/kornia/augmentation/base.py
+++ b/kornia/augmentation/base.py
@@ -20,12 +20,9 @@ from typing import Any, Callable, Dict, Optional, Tuple, Union
import torch
from torch import nn
-from torch.distributions import Bernoulli, Distribution, RelaxedBernoulli
from kornia.augmentation.random_generator import RandomGeneratorBase
from kornia.augmentation.utils import (
- _adapted_rsampling,
- _adapted_sampling,
_transform_output_shape,
override_parameters,
)
@@ -70,9 +67,24 @@ class _BasicAugmentationBase(nn.Module):
"""
- # TODO: Hard to support. Many codes are not ONNX-friendly that contains lots of if-else blocks, etc.
- # Please contribute if anyone interested.
- ONNX_EXPORTABLE = False
+ # Flag for whether this augmentation supports ONNX export. Override to False in subclasses
+ # that use ops the legacy tracer can't lower (e.g. ``torch.histc``,
+ # ``torch.distributions.Beta``).
+ # Users can introspect via ``aug.exportable``; CI iterates the known-exportable
+ # subset in ``tests/augmentation/test_onnx_export.py``.
+ ONNX_EXPORTABLE = True
+
+ @property
+ def exportable(self) -> bool:
+ """Whether this augmentation supports ONNX export via the legacy tracer at opset 20.
+
+ Reflects the class-level ``ONNX_EXPORTABLE`` flag. Note that ``True`` here
+ means *the graph traces and exports* β€” it does not guarantee the resulting
+ ONNX runtime output is bit-equivalent to eager. See the categorisation in
+ ``tests/augmentation/test_onnx_export.py`` for the numerical-correctness
+ signal per augmentation.
+ """
+ return bool(self.ONNX_EXPORTABLE)
def __init__(
self,
@@ -87,12 +99,6 @@ class _BasicAugmentationBase(nn.Module):
self.same_on_batch = same_on_batch
self.keepdim = keepdim
self._params: Dict[str, torch.Tensor] = {}
- self._p_gen: Distribution
- self._p_batch_gen: Distribution
- if p not in {0.0, 1.0}:
- self._p_gen = Bernoulli(self.p)
- if p_batch not in {0.0, 1.0}:
- self._p_batch_gen = Bernoulli(self.p_batch)
self._param_generator: Optional[RandomGeneratorBase] = None
self.flags: Dict[str, Any] = {}
self.set_rng_device_and_dtype(torch.device("cpu"), torch.get_default_dtype())
@@ -163,28 +169,26 @@ class _BasicAugmentationBase(nn.Module):
) -> torch.Tensor:
batch_prob: torch.Tensor
if p_batch == 1:
- batch_prob = torch.zeros(1) + 1
+ batch_prob = torch.ones(1, device=self.device, dtype=self.dtype)
elif p_batch == 0:
- batch_prob = torch.zeros(1)
- elif isinstance(self._p_batch_gen, (RelaxedBernoulli,)):
- # NOTE: there is no simple way to know if the sampler has `rsample` or not
- batch_prob = _adapted_rsampling((1,), self._p_batch_gen, same_on_batch)
+ batch_prob = torch.zeros(1, device=self.device, dtype=self.dtype)
else:
- batch_prob = _adapted_sampling((1,), self._p_batch_gen, same_on_batch)
+ batch_prob = (torch.rand(1, device=self.device) < p_batch).to(self.dtype)
if batch_prob.sum() == 1:
elem_prob: torch.Tensor
if p == 1:
- elem_prob = torch.zeros(batch_shape[0]) + 1
+ elem_prob = torch.ones(batch_shape[0], device=self.device, dtype=self.dtype)
elif p == 0:
- elem_prob = torch.zeros(batch_shape[0])
- elif isinstance(self._p_gen, (RelaxedBernoulli,)):
- elem_prob = _adapted_rsampling((batch_shape[0],), self._p_gen, same_on_batch)
+ elem_prob = torch.zeros(batch_shape[0], device=self.device, dtype=self.dtype)
+ elif same_on_batch:
+ elem_prob = (torch.rand(1, device=self.device) < p).to(self.dtype).expand(batch_shape[0])
else:
- elem_prob = _adapted_sampling((batch_shape[0],), self._p_gen, same_on_batch)
+ elem_prob = (torch.rand(batch_shape[0], device=self.device) < p).to(self.dtype)
batch_prob = batch_prob * elem_prob
else:
batch_prob = batch_prob.repeat(batch_shape[0])
+
if len(batch_prob.shape) == 2:
return batch_prob[..., 0]
return batch_prob
@@ -213,8 +217,7 @@ class _BasicAugmentationBase(nn.Module):
def forward_parameters(self, batch_shape: Tuple[int, ...]) -> Dict[str, torch.Tensor]:
batch_prob = self.__batch_prob_generator__(batch_shape, self.p, self.p_batch, self.same_on_batch)
- to_apply = batch_prob > 0.5
- _params = self.generate_parameters(torch.Size((int(to_apply.sum().item()), *batch_shape[1:])))
+ _params = self.generate_parameters(batch_shape)
if _params is None:
_params = {}
_params["batch_prob"] = batch_prob
@@ -310,28 +313,29 @@ class _AugmentationBase(_BasicAugmentationBase):
)
batch_prob = params["batch_prob"]
- to_apply = batch_prob > 0.5 # NOTE: in case of Relaxed Distributions.
+ to_apply = batch_prob > 0.5
ori_shape = input.shape
in_tensor = self.transform_tensor(input)
self.validate_tensor(in_tensor)
- if to_apply.all():
- output = self.apply_transform(in_tensor, params, flags, transform=transform)
- elif not to_apply.any():
- output = self.apply_non_transform(in_tensor, params, flags, transform=transform)
- else: # If any torch.Tensor needs to be transformed.
- output = self.apply_non_transform(in_tensor, params, flags, transform=transform)
- applied = self.apply_transform(
- in_tensor[to_apply],
- params,
- flags,
- transform=transform if transform is None else transform[to_apply],
- )
-
- if is_autocast_enabled():
- output = output.type(input.dtype)
- applied = applied.type(input.dtype)
- output = output.index_put((to_apply,), applied)
+
+ 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)
+ 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_transformed
+
+ if is_autocast_enabled():
+ output = output.type(input.dtype)
output = _transform_output_shape(output, ori_shape) if self.keepdim else output
@@ -352,26 +356,29 @@ class _AugmentationBase(_BasicAugmentationBase):
)
batch_prob = params["batch_prob"]
- to_apply = batch_prob > 0.5 # NOTE: in case of Relaxed Distributions.
+ to_apply = batch_prob > 0.5
ori_shape = input.shape
shape = params["forward_input_shape"]
in_tensor = self.transform_tensor(input, shape=shape, match_channel=False)
self.validate_tensor(in_tensor)
- if to_apply.all():
- output = self.apply_transform_mask(in_tensor, params, flags, transform=transform)
- elif not to_apply.any():
- output = self.apply_non_transform_mask(in_tensor, params, flags, transform=transform)
- else: # If any torch.Tensor needs to be transformed.
- output = self.apply_non_transform_mask(in_tensor, params, flags, transform=transform)
- applied = self.apply_transform_mask(
- in_tensor[to_apply],
- params,
- flags,
- transform=transform if transform is None else transform[to_apply],
- )
- output = output.index_put((to_apply,), applied)
+
+ output_transformed = self.apply_transform_mask(in_tensor, params, flags, transform=transform)
+ output_not_transformed = self.apply_non_transform_mask(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_transformed
+
output = _transform_output_shape(output, ori_shape, reference_shape=shape) if self.keepdim else output
return output
@@ -391,25 +398,28 @@ class _AugmentationBase(_BasicAugmentationBase):
)
batch_prob = params["batch_prob"]
- to_apply = batch_prob > 0.5 # NOTE: in case of Relaxed Distributions.
- output: Boxes
- if to_apply.bool().all():
- output = self.apply_transform_box(input, params, flags, transform=transform)
- elif not to_apply.any():
- output = self.apply_non_transform_box(input, params, flags, transform=transform)
- else: # If any torch.Tensor needs to be transformed.
- output = self.apply_non_transform_box(input, params, flags, transform=transform)
- applied = self.apply_transform_box(
- input[to_apply],
- params,
- flags,
- transform=transform if transform is None else transform[to_apply],
- )
- if is_autocast_enabled():
- output = output.type(input.dtype)
- applied = applied.type(input.dtype)
-
- output = output.index_put((to_apply,), applied)
+ to_apply = batch_prob > 0.5
+
+ output_transformed = self.apply_transform_box(input, params, flags, transform=transform)
+ output_not_transformed = self.apply_non_transform_box(input, params, flags, transform=transform)
+
+ data_transformed = output_transformed.data
+ data_not_transformed = output_not_transformed.data
+
+ if is_autocast_enabled():
+ data_transformed = data_transformed.type(input.data.dtype)
+ data_not_transformed = data_not_transformed.type(input.data.dtype)
+
+ if data_transformed.shape == data_not_transformed.shape and data_transformed.shape[0] == to_apply.shape[0]:
+ to_apply_expanded = to_apply.view(-1, *([1] * (len(data_transformed.shape) - 1)))
+ blended_data = torch.where(to_apply_expanded, data_transformed, data_not_transformed)
+ else:
+ blended_data = data_transformed if bool(to_apply.any()) else data_not_transformed
+
+ # Reuse the not-transformed Boxes container (preserves mode/_N/is_batched/etc.)
+ # and swap in the blended data, same effect as the index_put on .data.
+ output = output_not_transformed.clone()
+ output._data = blended_data
return output
def transform_keypoints(
@@ -428,23 +438,26 @@ class _AugmentationBase(_BasicAugmentationBase):
)
batch_prob = params["batch_prob"]
- to_apply = batch_prob > 0.5 # NOTE: in case of Relaxed Distributions.
- if to_apply.all():
- output = self.apply_transform_keypoint(input, params, flags, transform=transform)
- elif not to_apply.any():
- output = self.apply_non_transform_keypoint(input, params, flags, transform=transform)
- else: # If any torch.Tensor needs to be transformed.
- output = self.apply_non_transform_keypoint(input, params, flags, transform=transform)
- applied = self.apply_transform_keypoint(
- input[to_apply],
- params,
- flags,
- transform=transform if transform is None else transform[to_apply],
- )
- if is_autocast_enabled():
- output = output.type(input.dtype)
- applied = applied.type(input.dtype)
- output = output.index_put((to_apply,), applied)
+ to_apply = batch_prob > 0.5
+
+ output_transformed = self.apply_transform_keypoint(input, params, flags, transform=transform)
+ output_not_transformed = self.apply_non_transform_keypoint(input, params, flags, transform=transform)
+
+ data_transformed = output_transformed.data
+ data_not_transformed = output_not_transformed.data
+
+ if is_autocast_enabled():
+ data_transformed = data_transformed.type(input.data.dtype)
+ data_not_transformed = data_not_transformed.type(input.data.dtype)
+
+ if data_transformed.shape == data_not_transformed.shape and data_transformed.shape[0] == to_apply.shape[0]:
+ to_apply_expanded = to_apply.view(-1, *([1] * (len(data_transformed.shape) - 1)))
+ blended_data = torch.where(to_apply_expanded, data_transformed, data_not_transformed)
+ else:
+ blended_data = data_transformed if bool(to_apply.any()) else data_not_transformed
+
+ output = output_not_transformed.clone()
+ output._data = blended_data
return output
def transform_classes(
@@ -460,20 +473,23 @@ class _AugmentationBase(_BasicAugmentationBase):
)
batch_prob = params["batch_prob"]
- to_apply = batch_prob > 0.5 # NOTE: in case of Relaxed Distributions.
- if to_apply.all():
- output = self.apply_transform_class(input, params, flags, transform=transform)
- elif not to_apply.any():
- output = self.apply_non_transform_class(input, params, flags, transform=transform)
- else: # If any torch.Tensor needs to be transformed.
- output = self.apply_non_transform_class(input, params, flags, transform=transform)
- applied = self.apply_transform_class(
- input[to_apply],
- params,
- flags,
- transform=transform if transform is None else transform[to_apply],
- )
- output = output.index_put((to_apply,), applied)
+ to_apply = batch_prob > 0.5
+
+ output_transformed = self.apply_transform_class(input, params, flags, transform=transform)
+ output_not_transformed = self.apply_non_transform_class(input, 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_transformed
+
return output
def apply_non_transform_mask(
diff --git a/kornia/augmentation/container/augment.py b/kornia/augmentation/container/augment.py
index c421a267b..55eb1822b 100644
--- a/kornia/augmentation/container/augment.py
+++ b/kornia/augmentation/container/augment.py
@@ -435,6 +435,13 @@ class AugmentationSequential(TransformMatrixMinIn, ImageSequential):
"""Compute multiple tensors simultaneously according to ``self.data_keys``."""
self.clear_state()
+ # Strip trailing ``None`` positional args. The legacy torch.onnx.export tracer
+ # rebinds keyword-only defaults (``params``/``data_keys``) as positional, so
+ # ``forward(x)`` arrives as ``forward(x, None, None)``. Real data inputs are
+ # always tensors / Boxes / Keypoints / dicts β€” never ``None``, so this is safe.
+ while args and args[-1] is None:
+ args = args[:-1]
+
# Unpack/handle dictionary args
original_keys = None
if len(args) == 1 and isinstance(args[0], dict):
diff --git a/kornia/augmentation/random_generator/_2d/affine.py b/kornia/augmentation/random_generator/_2d/affine.py
index 4d64bccfe..c22e88a9d 100644
--- a/kornia/augmentation/random_generator/_2d/affine.py
+++ b/kornia/augmentation/random_generator/_2d/affine.py
@@ -20,7 +20,13 @@ from typing import Dict, Optional, Tuple, Union
import torch
from kornia.augmentation.random_generator.base import RandomGeneratorBase, UniformDistribution
-from kornia.augmentation.utils import _adapted_rsampling, _common_param_check, _joint_range_check, _range_bound
+from kornia.augmentation.utils import (
+ _adapted_rsampling,
+ _check_positive_int_or_traced,
+ _common_param_check,
+ _joint_range_check,
+ _range_bound,
+)
from kornia.core.utils import _extract_device_dtype
__all__ = ["AffineGenerator"]
@@ -159,8 +165,8 @@ class AffineGenerator(RandomGeneratorBase):
_device, _dtype = _extract_device_dtype([self.degrees, self.translate, self.scale, self.shear])
_common_param_check(batch_size, same_on_batch)
- if not (isinstance(width, (int,)) and isinstance(height, (int,)) and width > 0 and height > 0):
- raise AssertionError(f"`width` and `height` must be positive integers. Got {width}, {height}.")
+ _check_positive_int_or_traced(width, "width")
+ _check_positive_int_or_traced(height, "height")
angle = _adapted_rsampling((batch_size,), self.degree_sampler, same_on_batch).to(device=_device, dtype=_dtype)
diff --git a/kornia/augmentation/random_generator/_2d/crop.py b/kornia/augmentation/random_generator/_2d/crop.py
index 5d5c2a897..5c100e96d 100644
--- a/kornia/augmentation/random_generator/_2d/crop.py
+++ b/kornia/augmentation/random_generator/_2d/crop.py
@@ -21,7 +21,12 @@ import torch
from torch.distributions import Uniform
from kornia.augmentation.random_generator.base import RandomGeneratorBase
-from kornia.augmentation.utils import _adapted_rsampling, _common_param_check, _joint_range_check
+from kornia.augmentation.utils import (
+ _adapted_rsampling,
+ _check_positive_int_or_traced,
+ _common_param_check,
+ _joint_range_check,
+)
from kornia.core.utils import _extract_device_dtype
from kornia.geometry.bbox import bbox_generator
@@ -310,9 +315,9 @@ def center_crop_generator(
_common_param_check(batch_size)
if not isinstance(size, (tuple, list)) or len(size) != 2:
raise ValueError(f"Input size must be a tuple/list of length 2. Got {size}")
- if not (isinstance(height, int) and height > 0 and isinstance(width, int) and width > 0):
- raise AssertionError(f"'height' and 'width' must be integers. Got {height}, {width}.")
- if not (height >= size[0] and width >= size[1]):
+ _check_positive_int_or_traced(height, "height")
+ _check_positive_int_or_traced(width, "width")
+ if isinstance(height, int) and isinstance(width, int) and not (height >= size[0] and width >= size[1]):
raise AssertionError(f"Crop size must be smaller than input size. Got ({height}, {width}) and {size}.")
# unpack input sizes
diff --git a/kornia/augmentation/random_generator/_2d/cutmix.py b/kornia/augmentation/random_generator/_2d/cutmix.py
index 631f5ac3f..fbcb96867 100644
--- a/kornia/augmentation/random_generator/_2d/cutmix.py
+++ b/kornia/augmentation/random_generator/_2d/cutmix.py
@@ -21,7 +21,13 @@ import torch
from torch.distributions import Bernoulli, Beta, Uniform
from kornia.augmentation.random_generator.base import RandomGeneratorBase
-from kornia.augmentation.utils import _adapted_rsampling, _adapted_sampling, _common_param_check, _joint_range_check
+from kornia.augmentation.utils import (
+ _adapted_rsampling,
+ _adapted_sampling,
+ _check_positive_int_or_traced,
+ _common_param_check,
+ _joint_range_check,
+)
from kornia.core.utils import _extract_device_dtype
from kornia.geometry.bbox import bbox_generator
@@ -101,8 +107,8 @@ class CutmixGenerator(RandomGeneratorBase):
height = batch_shape[-2]
width = batch_shape[-1]
- if not (isinstance(height, int) and height > 0 and isinstance(width, int) and width > 0):
- raise AssertionError(f"'height' and 'width' must be integers. Got {height}, {width}.")
+ _check_positive_int_or_traced(height, "height")
+ _check_positive_int_or_traced(width, "width")
_device, _dtype = _extract_device_dtype([self.beta, self.cut_size])
_common_param_check(batch_size, same_on_batch)
diff --git a/kornia/augmentation/random_generator/_2d/perspective.py b/kornia/augmentation/random_generator/_2d/perspective.py
index a99dd7771..a6cabf40b 100644
--- a/kornia/augmentation/random_generator/_2d/perspective.py
+++ b/kornia/augmentation/random_generator/_2d/perspective.py
@@ -21,7 +21,7 @@ import torch
from torch.distributions import Uniform
from kornia.augmentation.random_generator.base import RandomGeneratorBase
-from kornia.augmentation.utils import _adapted_rsampling, _common_param_check
+from kornia.augmentation.utils import _adapted_rsampling, _check_positive_int_or_traced, _common_param_check
from kornia.core.utils import _extract_device_dtype
__all__ = ["PerspectiveGenerator"]
@@ -77,8 +77,8 @@ class PerspectiveGenerator(RandomGeneratorBase):
_device, _dtype = _extract_device_dtype([self.distortion_scale])
_common_param_check(batch_size, same_on_batch)
- if not (isinstance(height, int) and height > 0 and isinstance(width, int) and width > 0):
- raise AssertionError(f"'height' and 'width' must be integers. Got {height}, {width}.")
+ _check_positive_int_or_traced(height, "height")
+ _check_positive_int_or_traced(width, "width")
start_points: torch.Tensor = torch.tensor(
[[[0.0, 0], [width - 1, 0], [width - 1, height - 1], [0, height - 1]]], device=_device, dtype=_dtype
diff --git a/kornia/augmentation/random_generator/_2d/rectangle_earase.py b/kornia/augmentation/random_generator/_2d/rectangle_earase.py
index f2f89bc49..c089e5e6e 100644
--- a/kornia/augmentation/random_generator/_2d/rectangle_earase.py
+++ b/kornia/augmentation/random_generator/_2d/rectangle_earase.py
@@ -20,7 +20,12 @@ from typing import Dict, Tuple, Union
import torch
from kornia.augmentation.random_generator.base import RandomGeneratorBase, UniformDistribution
-from kornia.augmentation.utils import _adapted_rsampling, _common_param_check, _joint_range_check
+from kornia.augmentation.utils import (
+ _adapted_rsampling,
+ _check_positive_int_or_traced,
+ _common_param_check,
+ _joint_range_check,
+)
from kornia.core.utils import _extract_device_dtype
__all__ = ["RectangleEraseGenerator"]
@@ -95,8 +100,8 @@ class RectangleEraseGenerator(RandomGeneratorBase):
batch_size = batch_shape[0]
height = batch_shape[-2]
width = batch_shape[-1]
- if not (isinstance(height, int) and height > 0 and isinstance(width, int) and width > 0):
- raise AssertionError(f"'height' and 'width' must be integers. Got {height}, {width}.")
+ _check_positive_int_or_traced(height, "height")
+ _check_positive_int_or_traced(width, "width")
_common_param_check(batch_size, same_on_batch)
_device, _dtype = _extract_device_dtype([self.ratio, self.scale])
diff --git a/kornia/augmentation/random_generator/_2d/shear.py b/kornia/augmentation/random_generator/_2d/shear.py
index d1233cb29..8a1fe5f9c 100644
--- a/kornia/augmentation/random_generator/_2d/shear.py
+++ b/kornia/augmentation/random_generator/_2d/shear.py
@@ -20,7 +20,13 @@ from typing import Dict, Tuple, Union
import torch
from kornia.augmentation.random_generator.base import RandomGeneratorBase, UniformDistribution
-from kornia.augmentation.utils import _adapted_rsampling, _common_param_check, _joint_range_check, _range_bound
+from kornia.augmentation.utils import (
+ _adapted_rsampling,
+ _check_positive_int_or_traced,
+ _common_param_check,
+ _joint_range_check,
+ _range_bound,
+)
from kornia.core.utils import _extract_device_dtype
__all__ = ["ShearGenerator"]
@@ -95,8 +101,8 @@ class ShearGenerator(RandomGeneratorBase):
_device, _dtype = _extract_device_dtype([self.shear])
_common_param_check(batch_size, same_on_batch)
- if not (isinstance(width, (int,)) and isinstance(height, (int,)) and width > 0 and height > 0):
- raise AssertionError(f"`width` and `height` must be positive integers. Got {width}, {height}.")
+ _check_positive_int_or_traced(width, "width")
+ _check_positive_int_or_traced(height, "height")
center: torch.Tensor = torch.tensor([width, height], device=_device, dtype=_dtype).view(1, 2) / 2.0 - 0.5
center = center.expand(batch_size, -1)
diff --git a/kornia/augmentation/random_generator/_2d/translate.py b/kornia/augmentation/random_generator/_2d/translate.py
index fa02e319b..1d808b9b6 100644
--- a/kornia/augmentation/random_generator/_2d/translate.py
+++ b/kornia/augmentation/random_generator/_2d/translate.py
@@ -20,7 +20,12 @@ from typing import Dict, Optional, Tuple, Union
import torch
from kornia.augmentation.random_generator.base import RandomGeneratorBase, UniformDistribution
-from kornia.augmentation.utils import _adapted_rsampling, _common_param_check, _range_bound
+from kornia.augmentation.utils import (
+ _adapted_rsampling,
+ _check_positive_int_or_traced,
+ _common_param_check,
+ _range_bound,
+)
from kornia.core.utils import _extract_device_dtype
__all__ = ["TranslateGenerator"]
@@ -88,8 +93,8 @@ class TranslateGenerator(RandomGeneratorBase):
_device, _dtype = _extract_device_dtype([self.translate_x, self.translate_y])
_common_param_check(batch_size, same_on_batch)
- if not (isinstance(width, (int,)) and isinstance(height, (int,)) and width > 0 and height > 0):
- raise AssertionError(f"`width` and `height` must be positive integers. Got {width}, {height}.")
+ _check_positive_int_or_traced(width, "width")
+ _check_positive_int_or_traced(height, "height")
if self.translate_x_sampler is not None:
translate_x = (
diff --git a/kornia/augmentation/random_generator/_3d/affine.py b/kornia/augmentation/random_generator/_3d/affine.py
index 6dd02b97a..b90c041ef 100644
--- a/kornia/augmentation/random_generator/_3d/affine.py
+++ b/kornia/augmentation/random_generator/_3d/affine.py
@@ -20,7 +20,12 @@ from typing import Dict, Optional, Tuple, Union
import torch
from kornia.augmentation.random_generator.base import RandomGeneratorBase, UniformDistribution
-from kornia.augmentation.utils import _adapted_rsampling, _singular_range_check, _tuple_range_reader
+from kornia.augmentation.utils import (
+ _adapted_rsampling,
+ _check_positive_int_or_traced,
+ _singular_range_check,
+ _tuple_range_reader,
+)
from kornia.core.utils import _extract_device_dtype
@@ -166,15 +171,9 @@ class AffineGenerator3D(RandomGeneratorBase):
height = batch_shape[-2]
width = batch_shape[-1]
- if not (
- isinstance(depth, int)
- and depth > 0
- and isinstance(height, int)
- and height > 0
- and isinstance(width, int)
- and width > 0
- ):
- raise AssertionError(f"'depth', 'height' and 'width' must be integers. Got {depth}, {height}, {width}.")
+ _check_positive_int_or_traced(depth, "depth")
+ _check_positive_int_or_traced(height, "height")
+ _check_positive_int_or_traced(width, "width")
_device, _dtype = _extract_device_dtype([self.degrees, self.translate, self.scale, self.shears])
diff --git a/kornia/augmentation/random_generator/_3d/crop.py b/kornia/augmentation/random_generator/_3d/crop.py
index cd6b0e394..0434982e9 100644
--- a/kornia/augmentation/random_generator/_3d/crop.py
+++ b/kornia/augmentation/random_generator/_3d/crop.py
@@ -21,7 +21,7 @@ import torch
from torch.distributions import Uniform
from kornia.augmentation.random_generator.base import RandomGeneratorBase
-from kornia.augmentation.utils import _adapted_rsampling, _common_param_check
+from kornia.augmentation.utils import _adapted_rsampling, _check_positive_int_or_traced, _common_param_check
from kornia.core.utils import _extract_device_dtype
from kornia.geometry.bbox import bbox_generator3d
@@ -186,16 +186,15 @@ def center_crop_generator3d(
device = torch.device("cpu")
if not isinstance(size, (tuple, list)) or len(size) != 3:
raise ValueError(f"Input size must be a tuple/list of length 3. Got {size}")
- if not (
+ _check_positive_int_or_traced(depth, "depth")
+ _check_positive_int_or_traced(height, "height")
+ _check_positive_int_or_traced(width, "width")
+ if (
isinstance(depth, int)
- and depth > 0
and isinstance(height, int)
- and height > 0
and isinstance(width, int)
- and width > 0
+ and not (depth >= size[0] and height >= size[1] and width >= size[2])
):
- raise AssertionError(f"'depth', 'height' and 'width' must be integers. Got {depth}, {height}, {width}.")
- if not (depth >= size[0] and height >= size[1] and width >= size[2]):
raise AssertionError(f"Crop size must be smaller than input size. Got ({depth}, {height}, {width}) and {size}.")
if batch_size == 0:
diff --git a/kornia/augmentation/utils/__init__.py b/kornia/augmentation/utils/__init__.py
index e7fa52bbf..23bda9f16 100644
--- a/kornia/augmentation/utils/__init__.py
+++ b/kornia/augmentation/utils/__init__.py
@@ -42,6 +42,7 @@ from kornia.augmentation.utils.helpers import (
override_parameters,
)
from kornia.augmentation.utils.param_validation import (
+ _check_positive_int_or_traced,
_common_param_check,
_joint_range_check,
_range_bound,
@@ -54,6 +55,7 @@ __all__ = [
"_adapted_rsampling",
"_adapted_sampling",
"_adapted_uniform",
+ "_check_positive_int_or_traced",
"_common_param_check",
"_infer_batch_shape",
"_infer_batch_shape3d",
diff --git a/kornia/augmentation/utils/param_validation.py b/kornia/augmentation/utils/param_validation.py
index 0e1079ec5..1c09a3ce2 100644
--- a/kornia/augmentation/utils/param_validation.py
+++ b/kornia/augmentation/utils/param_validation.py
@@ -20,8 +20,41 @@ from typing import Any, List, Optional, Tuple, Union
import torch
+def _check_positive_int_or_traced(value: Any, name: str) -> None:
+ """Assert ``value`` is a non-negative Python int, or accept it as a traced dim.
+
+ Used by random generators to validate ``height``/``width``/``depth`` derived from
+ ``tensor.shape``. Under tracing those are 0-d tensors; we accept them rather than
+ aborting export, since the surrounding ops will fail loudly if the value is
+ actually invalid.
+ """
+ if _is_traced_dim(value):
+ return
+ if not (isinstance(value, int) and value > 0):
+ raise AssertionError(f"`{name}` must be a positive integer. Got {value}.")
+
+
+def _is_traced_dim(value: Any) -> bool:
+ """Return True if ``value`` looks like a shape dim that came from tensor tracing.
+
+ Under torch.onnx.export's TorchScript tracer (and torch.fx), accessing
+ ``tensor.shape[i]`` can yield a 0-d tensor instead of a Python ``int``. The
+ runtime validators in this module are redundant during tracing, the tensor
+ constructors that follow will catch any real shape problem. Treat such
+ "traced ints" as opaque-but-valid so the trace can continue.
+ """
+ return isinstance(value, torch.Tensor) and value.numel() == 1 and value.dim() <= 1
+
+
def _common_param_check(batch_size: int, same_on_batch: Optional[bool] = None) -> None:
- """Check valid batch_size and same_on_batch params."""
+ """Check valid batch_size and same_on_batch params.
+
+ Skips the integer-type check when ``batch_size`` is a 0-d / 1-element tensor
+ (the shape of a traced tensor), since static configuration is already
+ validated at module construction time.
+ """
+ if _is_traced_dim(batch_size):
+ return
if not (isinstance(batch_size, int) and batch_size >= 0):
raise AssertionError(f"`batch_size` shall be a positive integer. Got {batch_size}.")
if same_on_batch is not None and not isinstance(same_on_batch, bool):
diff --git a/kornia/core/utils.py b/kornia/core/utils.py
index 429c77280..b75923e57 100644
--- a/kornia/core/utils.py
+++ b/kornia/core/utils.py
@@ -131,14 +131,71 @@ def _normalize_to_float32_or_float64(dtype: torch.dtype) -> torch.dtype:
return dtype if dtype in (torch.float32, torch.float64) else torch.float32
+def _inverse_3x3_closed_form(input: torch.Tensor) -> torch.Tensor:
+ """Closed-form inverse for batched 3x3 matrices.
+
+ Used as an ONNX-traceable fallback to ``torch.linalg.inv``: the legacy ONNX
+ exporter does not lower ``aten::linalg_inv`` (as of opset 17). Computed via
+ the adjugate / determinant formula, which is composed entirely of basic
+ arithmetic ops that all standard ONNX opsets support.
+
+ Args:
+ input: Tensor of shape ``(..., 3, 3)``.
+
+ Returns:
+ Tensor of shape ``(..., 3, 3)`` containing the matrix inverse for each
+ leading-dim slice. Numerically equivalent to ``torch.linalg.inv`` for
+ well-conditioned matrices; behavior on singular matrices is undefined
+ (no explicit check, same as ``torch.linalg.inv`` itself).
+ """
+ a = input[..., 0, 0]
+ b = input[..., 0, 1]
+ c = input[..., 0, 2]
+ d = input[..., 1, 0]
+ e = input[..., 1, 1]
+ f = input[..., 1, 2]
+ g = input[..., 2, 0]
+ h = input[..., 2, 1]
+ i = input[..., 2, 2]
+
+ # Cofactors (signed minors).
+ c00 = e * i - f * h
+ c01 = -(d * i - f * g)
+ c02 = d * h - e * g
+ c10 = -(b * i - c * h)
+ c11 = a * i - c * g
+ c12 = -(a * h - b * g)
+ c20 = b * f - c * e
+ c21 = -(a * f - c * d)
+ c22 = a * e - b * d
+
+ det = a * c00 + b * c01 + c * c02
+
+ # Adjugate is the transpose of the cofactor matrix.
+ row0 = torch.stack([c00, c10, c20], dim=-1)
+ row1 = torch.stack([c01, c11, c21], dim=-1)
+ row2 = torch.stack([c02, c12, c22], dim=-1)
+ adj = torch.stack([row0, row1, row2], dim=-2)
+
+ return adj / det[..., None, None]
+
+
def _torch_inverse_cast(input: torch.Tensor) -> torch.Tensor:
"""Make torch.inverse work with other than fp32/64.
The function torch.inverse is only implemented for fp32/64 which makes impossible to be used by fp16 or others. What
this function does, is cast input data type to fp32, apply torch.inverse, and cast back to the input dtype.
+
+ During tracing (``torch.jit.trace`` and legacy ``torch.onnx.export``) on 3x3
+ matrices, falls back to a closed-form inverse so the resulting graph does not
+ include ``aten::linalg_inv`` (unsupported by the legacy ONNX exporter at
+ opset 20). ``torch.jit.is_tracing()`` is JIT-script-safe (unlike
+ ``torch.onnx.is_in_onnx_export``, which contains an ``import`` statement).
"""
KORNIA_CHECK_IS_TENSOR(input, "Input must be torch.Tensor")
dtype = _normalize_to_float32_or_float64(input.dtype)
+ if torch.jit.is_tracing() and input.shape[-2:] == (3, 3):
+ return _inverse_3x3_closed_form(input.to(dtype)).to(input.dtype)
return torch.linalg.inv(input.to(dtype)).to(input.dtype)
diff --git a/kornia/feature/xfeat.py b/kornia/feature/xfeat.py
index 364898ffd..2b5b807a5 100644
--- a/kornia/feature/xfeat.py
+++ b/kornia/feature/xfeat.py
@@ -365,6 +365,12 @@ class XFeat(nn.Module):
self, feats1: torch.Tensor, feats2: torch.Tensor, min_cossim: float = 0.82
) -> Tuple[torch.Tensor, torch.Tensor]:
"""Mutual nearest-neighbour matching on L2-normalised descriptor pairs."""
+ # If either descriptor set is empty there are no possible matches; return early
+ # with empty index tensors.
+ if feats1.shape[0] == 0 or feats2.shape[0] == 0:
+ empty = torch.empty(0, dtype=torch.long, device=feats1.device)
+ return empty, empty.clone()
+
cossim = feats1 @ feats2.t()
cossim_t = feats2 @ feats1.t()
_, match12 = cossim.max(dim=1)
diff --git a/kornia/geometry/conversions.py b/kornia/geometry/conversions.py
index 1480f9017..b8f0ebf83 100644
--- a/kornia/geometry/conversions.py
+++ b/kornia/geometry/conversions.py
@@ -1116,14 +1116,19 @@ def normal_transform_pixel(
normalized transform with shape :math:`(1, 3, 3)`.
"""
- tr_mat = torch.tensor([[1.0, 0.0, -1.0], [0.0, 1.0, -1.0], [0.0, 0.0, 1.0]], device=device, dtype=dtype) # 3x3
-
# prevent divide by zero bugs
width_denom: float = eps if width == 1 else width - 1.0
height_denom: float = eps if height == 1 else height - 1.0
- tr_mat[0, 0] = tr_mat[0, 0] * 2.0 / width_denom
- tr_mat[1, 1] = tr_mat[1, 1] * 2.0 / height_denom
+ sx: float = 2.0 / width_denom
+ sy: float = 2.0 / height_denom
+
+ # Construct the matrix in one shot (no in-place mutation).
+ tr_mat = torch.tensor(
+ [[sx, 0.0, -1.0], [0.0, sy, -1.0], [0.0, 0.0, 1.0]],
+ device=device,
+ dtype=dtype,
+ ) # 3x3
return tr_mat.unsqueeze(0) # 1x3x3
diff --git a/kornia/geometry/transform/imgwarp.py b/kornia/geometry/transform/imgwarp.py
index 1bad09bcd..5faacd6cf 100644
--- a/kornia/geometry/transform/imgwarp.py
+++ b/kornia/geometry/transform/imgwarp.py
@@ -24,7 +24,7 @@ import torch.nn.functional as F
from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_SHAPE
from kornia.core.ops import eye_like
-from kornia.core.utils import _torch_inverse_cast, _torch_solve_cast
+from kornia.core.utils import _inverse_3x3_closed_form, _torch_inverse_cast, _torch_solve_cast
from kornia.geometry.conversions import (
angle_to_rotation_matrix,
axis_angle_to_rotation_matrix,
@@ -312,6 +312,67 @@ def warp_grid3d(grid: torch.Tensor, src_homo_dst: torch.Tensor) -> torch.Tensor:
# super().__init__()
+def _unit_square_to_quad(points: torch.Tensor) -> torch.Tensor:
+ """Closed-form perspective matrix mapping the unit square to a quadrilateral.
+
+ Maps the canonical unit-square corners ``[(0,0), (1,0), (1,1), (0,1)]`` to the
+ four points in ``points`` (in the same corner order). Implemented via Heckbert's
+ direct formulation (no linear solve) so it lowers cleanly to ONNX.
+
+ Args:
+ points: ``(B, 4, 2)`` tensor of quadrilateral vertices.
+
+ Returns:
+ ``(B, 3, 3)`` perspective transformation matrix.
+ """
+ x0 = points[..., 0, 0]
+ y0 = points[..., 0, 1]
+ x1 = points[..., 1, 0]
+ y1 = points[..., 1, 1]
+ x2 = points[..., 2, 0]
+ y2 = points[..., 2, 1]
+ x3 = points[..., 3, 0]
+ y3 = points[..., 3, 1]
+
+ dx1 = x1 - x2
+ dx2 = x3 - x2
+ sx = x0 - x1 + x2 - x3
+ dy1 = y1 - y2
+ dy2 = y3 - y2
+ sy = y0 - y1 + y2 - y3
+
+ denom = dx1 * dy2 - dy1 * dx2
+ a31 = (sx * dy2 - sy * dx2) / denom
+ a32 = (dx1 * sy - dy1 * sx) / denom
+ a11 = x1 - x0 + a31 * x1
+ a12 = x3 - x0 + a32 * x3
+ a13 = x0
+ a21 = y1 - y0 + a31 * y1
+ a22 = y3 - y0 + a32 * y3
+ a23 = y0
+
+ one = torch.ones_like(x0)
+
+ row0 = torch.stack([a11, a12, a13], dim=-1)
+ row1 = torch.stack([a21, a22, a23], dim=-1)
+ row2 = torch.stack([a31, a32, one], dim=-1)
+ return torch.stack([row0, row1, row2], dim=-2)
+
+
+def _get_perspective_transform_closed_form(points_src: torch.Tensor, points_dst: torch.Tensor) -> torch.Tensor:
+ """ONNX-traceable perspective transform via two unit-square decompositions.
+
+ Computes ``H = H_d @ inv(H_s)`` where ``H_s`` maps the unit square to
+ ``points_src`` and ``H_d`` maps it to ``points_dst``. Replaces the 8x8
+ ``torch.linalg.solve`` in :func:`get_perspective_transform` with two 3x3
+ Heckbert constructions and one 3x3 inverse β€” all closed-form ops that the
+ legacy ONNX exporter supports.
+ """
+ h_s = _unit_square_to_quad(points_src)
+ h_d = _unit_square_to_quad(points_dst)
+ return h_d @ _inverse_3x3_closed_form(h_s)
+
+
def get_perspective_transform(points_src: torch.Tensor, points_dst: torch.Tensor) -> torch.Tensor:
r"""Calculate a perspective transform from four pairs of the corresponding points.
@@ -363,6 +424,15 @@ def get_perspective_transform(points_src: torch.Tensor, points_dst: torch.Tensor
KORNIA_CHECK(points_src.shape == points_dst.shape, "Source data shape must match Destination data shape.")
KORNIA_CHECK(points_src.dtype == points_dst.dtype, "Source data type must match Destination data type.")
+ # Under tracing (legacy torch.onnx.export, torch.jit.trace), use the closed-form
+ # Heckbert decomposition: the legacy ONNX tracer does not lower
+ # ``aten::linalg_solve``, but the closed-form path only uses arithmetic ops
+ # + a closed-form 3x3 inverse, both fully supported. ``torch.jit.is_tracing()``
+ # is JIT-script-safe (unlike ``torch.onnx.is_in_onnx_export``, which contains
+ # an ``import`` statement that JIT script cannot compile).
+ if torch.jit.is_tracing():
+ return _get_perspective_transform_closed_form(points_src, points_dst)
+
# we build matrix A by using only 4 point correspondence. The linear
# system is solved with the least square method, so here
# we could even pass more correspondence
diff --git a/tests/augmentation/_3d/test_random_rotation_3d.py b/tests/augmentation/_3d/test_random_rotation_3d.py
index 56b661fc3..9927a4d6b 100644
--- a/tests/augmentation/_3d/test_random_rotation_3d.py
+++ b/tests/augmentation/_3d/test_random_rotation_3d.py
@@ -105,9 +105,11 @@ class TestRandomRotation3D(BaseTester):
self.assert_close(f.transform_matrix, expected_transform, rtol=rtol, atol=atol)
def test_batch_random_rotation(self, device, dtype):
- torch.manual_seed(24) # for random reproductibility
-
- f = RandomRotation3D(degrees=45.0)
+ # Verifies per-element random rotation invariants on a batch input:
+ # p=1.0 forces every element to be transformed so the assertions don't depend on
+ # how the underlying RNG happens to roll the per-element apply mask.
+ torch.manual_seed(24)
+ f = RandomRotation3D(degrees=45.0, p=1.0, same_on_batch=False)
input_tensor = torch.tensor(
[
@@ -119,85 +121,35 @@ class TestRandomRotation3D(BaseTester):
],
device=device,
dtype=dtype,
- ) # 1 x 1 x 4 x 4
+ ).repeat(2, 1, 1, 1, 1) # (2, 1, 3, 4, 4)
- expected = torch.tensor(
- [
- [
- [
- [
- [1.0000, 0.0000, 0.0000, 2.0000],
- [0.0000, 0.0000, 0.0000, 0.0000],
- [0.0000, 1.0000, 2.0000, 0.0000],
- [0.0000, 0.0000, 1.0000, 2.0000],
- ],
- [
- [1.0000, 0.0000, 0.0000, 2.0000],
- [0.0000, 0.0000, 0.0000, 0.0000],
- [0.0000, 1.0000, 2.0000, 0.0000],
- [0.0000, 0.0000, 1.0000, 2.0000],
- ],
- [
- [1.0000, 0.0000, 0.0000, 2.0000],
- [0.0000, 0.0000, 0.0000, 0.0000],
- [0.0000, 1.0000, 2.0000, 0.0000],
- [0.0000, 0.0000, 1.0000, 2.0000],
- ],
- ]
- ],
- [
- [
- [
- [0.0000, 0.0726, 0.0000, 0.0000],
- [0.1038, 1.0134, 0.5566, 0.1519],
- [0.0000, 1.0849, 1.1068, 0.0000],
- [0.1242, 1.1065, 0.9681, 0.0000],
- ],
- [
- [0.0000, 0.0047, 0.0166, 0.0000],
- [0.0579, 0.4459, 0.0000, 0.4728],
- [0.1864, 1.3349, 0.7530, 0.3251],
- [0.1431, 1.2481, 0.4471, 0.0000],
- ],
- [
- [0.0000, 0.4840, 0.2314, 0.0000],
- [0.0000, 0.0328, 0.0000, 0.1434],
- [0.1899, 0.5580, 0.0000, 0.9170],
- [0.0000, 0.2042, 0.1571, 0.0855],
- ],
- ]
- ],
- ],
- device=device,
- dtype=dtype,
- )
+ atol = 5e-3 if (device.type == "cuda" and dtype == torch.float32) else 1e-4
+ rtol = 1e-3 if (device.type == "cuda" and dtype == torch.float32) else 1e-6
- expected_transform = torch.tensor(
- [
- [
- [1.0000, 0.0000, 0.0000, 0.0000],
- [0.0000, 1.0000, 0.0000, 0.0000],
- [0.0000, 0.0000, 1.0000, 0.0000],
- [0.0000, 0.0000, 0.0000, 1.0000],
- ],
- [
- [0.7522, -0.6326, -0.1841, 1.5047],
- [0.6029, 0.5482, 0.5796, -0.8063],
- [-0.2657, -0.5470, 0.7938, 1.4252],
- [0.0000, 0.0000, 0.0000, 1.0000],
- ],
- ],
- device=device,
- dtype=dtype,
- )
+ torch.manual_seed(24)
+ out = f(input_tensor)
+ transform = f.transform_matrix
- input_tensor = input_tensor.repeat(2, 1, 1, 1, 1) # 5 x 4 x 4 x 3
+ # 1. Shape preservation
+ assert out.shape == input_tensor.shape
+ assert transform.shape == (2, 4, 4)
- out = f(input_tensor)
- atol = 5e-3 if (device.type == "cuda" and dtype == torch.float32) else 1e-4
- rtol = 1e-3 if (device.type == "cuda" and dtype == torch.float32) else 1e-6
- self.assert_close(out, expected, rtol=rtol, atol=atol)
- self.assert_close(f.transform_matrix, expected_transform, rtol=rtol, atol=atol)
+ # 2. Per-element variation: the two batch elements were rotated by *different* angles
+ assert not torch.allclose(transform[0], transform[1], atol=1e-3)
+
+ # 3. Valid rigid 3D transforms: rotation block is orthogonal, bottom row is [0,0,0,1]
+ bottom_row = torch.tensor([0.0, 0.0, 0.0, 1.0], device=device, dtype=dtype).expand(2, 4)
+ self.assert_close(transform[:, 3, :], bottom_row, rtol=rtol, atol=atol)
+ rot = transform[:, :3, :3]
+ rot_rt = rot @ rot.transpose(-1, -2)
+ eye = torch.eye(3, device=device, dtype=dtype).expand(2, 3, 3)
+ self.assert_close(rot_rt, eye, rtol=rtol, atol=atol)
+
+ # 4. Reproducibility under fixed seed
+ torch.manual_seed(24)
+ out2 = f(input_tensor)
+ self.assert_close(out, out2, rtol=rtol, atol=atol)
+ self.assert_close(transform, f.transform_matrix, rtol=rtol, atol=atol)
def test_same_on_batch(self, device, dtype):
f = RandomRotation3D(degrees=40, same_on_batch=True)
@@ -206,9 +158,19 @@ class TestRandomRotation3D(BaseTester):
self.assert_close(res[0], res[1])
def test_sequential(self, device, dtype):
- torch.manual_seed(24) # for random reproductibility
+ # Verifies AugmentationSequential composition for 3D rotations:
+ # Sequential(aug_a, aug_b)(x) == aug_b(aug_a(x))
+ # and the composed transform matrix equals aug_b.transform_matrix @ aug_a.transform_matrix.
+ # p=1.0 forces both rotations to fire so the assertion is independent of the per-element
+ # apply mask. Two distinct instances are required because nn.Module dedupes children
+ # passed by the same instance.
+ atol = 5e-3 if (device.type == "cuda" and dtype == torch.float32) else 1e-4
+ rtol = 1e-3 if (device.type == "cuda" and dtype == torch.float32) else 1e-6
+
+ aug_a = RandomRotation3D(degrees=torch.tensor([-45.0, 90.0]), p=1.0)
+ aug_b = RandomRotation3D(degrees=10.4, p=1.0)
+ f = AugmentationSequential(aug_a, aug_b)
- f = AugmentationSequential(RandomRotation3D(torch.tensor([-45.0, 90])), RandomRotation3D(10.4))
input_tensor = torch.tensor(
[
[[1.0, 0.0, 0.0, 2.0], [0.0, 0.0, 0.0, 0.0], [0.0, 1.0, 2.0, 0.0], [0.0, 0.0, 1.0, 2.0]],
@@ -219,53 +181,18 @@ class TestRandomRotation3D(BaseTester):
dtype=dtype,
) # 3 x 4 x 4
- expected = torch.tensor(
- [
- [
- [
- [
- [0.3431, 0.1239, 0.0000, 1.0348],
- [0.0000, 0.2035, 0.1139, 0.1770],
- [0.0789, 0.9057, 1.7780, 0.0000],
- [0.0000, 0.2286, 1.2498, 1.2643],
- ],
- [
- [0.5460, 0.2131, 0.0000, 1.1453],
- [0.0000, 0.0899, 0.0000, 0.4293],
- [0.0797, 1.0193, 1.6677, 0.0000],
- [0.0000, 0.2458, 1.2765, 1.0920],
- ],
- [
- [0.6322, 0.2614, 0.0000, 0.9207],
- [0.0000, 0.0037, 0.0000, 0.6551],
- [0.0689, 0.9251, 1.3442, 0.0000],
- [0.0000, 0.2449, 0.9856, 0.6862],
- ],
- ]
- ]
- ],
- device=device,
- dtype=dtype,
- )
+ torch.manual_seed(24)
+ out_seq = f(input_tensor)
+ transform_seq = f.transform_matrix
- expected_transform = torch.tensor(
- [
- [
- [0.9857, -0.1686, -0.0019, 0.2762],
- [0.1668, 0.9739, 0.1538, -0.3650],
- [-0.0241, -0.1520, 0.9881, 0.2760],
- [0.0000, 0.0000, 0.0000, 1.0000],
- ]
- ],
- device=device,
- dtype=dtype,
- )
+ torch.manual_seed(24)
+ out_a = aug_a(input_tensor)
+ transform_a = aug_a.transform_matrix
+ out_manual = aug_b(out_a)
+ transform_manual = aug_b.transform_matrix @ transform_a
- out = f(input_tensor)
- atol = 5e-3 if (device.type == "cuda" and dtype == torch.float32) else 1e-4
- rtol = 1e-3 if (device.type == "cuda" and dtype == torch.float32) else 1e-6
- self.assert_close(out, expected, rtol=rtol, atol=atol)
- self.assert_close(f.transform_matrix, expected_transform, rtol=rtol, atol=atol)
+ self.assert_close(out_seq, out_manual, rtol=rtol, atol=atol)
+ self.assert_close(transform_seq, transform_manual, rtol=rtol, atol=atol)
def test_gradcheck(self, device):
torch.manual_seed(0) # for random reproductibility
diff --git a/tests/augmentation/test_augmentation.py b/tests/augmentation/test_augmentation.py
index 8192dac44..a9ec75e22 100644
--- a/tests/augmentation/test_augmentation.py
+++ b/tests/augmentation/test_augmentation.py
@@ -184,25 +184,21 @@ class CommonTests(BaseTester):
generated_params = augmentation.forward_parameters(batch_shape)
assert isinstance(generated_params, dict)
- # compute_transformation can be called and returns the correct shaped transformation matrix
- to_apply = generated_params["batch_prob"] > 0.5
- expected_transformation_shape = torch.Size((to_apply.sum(), 3, 3))
+ # compute_transformation now operates on the full batch (ONNX-friendly contract)
+ # and returns a (B, 3, 3) transform matrix.
+ expected_transformation_shape = torch.Size((batch_shape[0], 3, 3))
test_input = torch.ones(batch_shape, device=self.device, dtype=self.dtype)
- transformation = augmentation.compute_transformation(test_input[to_apply], generated_params, augmentation.flags)
+ transformation = augmentation.compute_transformation(test_input, generated_params, augmentation.flags)
assert transformation.shape == expected_transformation_shape
- # apply_transform can be called and returns the correct batch sized output
- if to_apply.sum() != 0:
- output = augmentation.apply_transform(
- test_input[to_apply],
- generated_params,
- augmentation.flags,
- transformation,
- )
- assert output.shape[0] == to_apply.sum()
- else:
- # Re-generate parameters if 0 batch size
- self._test_smoke_implementation(params)
+ # apply_transform can be called on the full batch and returns full-batch output
+ output = augmentation.apply_transform(
+ test_input,
+ generated_params,
+ augmentation.flags,
+ transformation,
+ )
+ assert output.shape[0] == batch_shape[0]
def _test_smoke_call_implementation(self, params):
batch_shape = (4, 3, 5, 6)
@@ -262,26 +258,34 @@ class CommonTests(BaseTester):
self.assert_close(transform, expected_transformation, low_tolerance=True)
def _test_module_implementation(self, params):
- augmentation = self._create_augmentation_from_params(**params, p=0.5)
+ # Verifies the composition invariant of AugmentationSequential:
+ # Sequential(aug_a, aug_b)(x) == aug_b(aug_a(x))
+ # and the transform matrix is the product of the individual matrices.
+ #
+ # Two distinct instances are required because `AugmentationSequential(aug, aug)`
+ # registers a single child (nn.Module dedupes same-instance children).
+ # We force p=1.0 so both augmentations always fire.
+ augmentation_a = self._create_augmentation_from_params(**params, p=1.0)
+ augmentation_b = self._create_augmentation_from_params(**params, p=1.0)
- augmentation_sequence = AugmentationSequential(augmentation, augmentation)
+ augmentation_sequence = AugmentationSequential(augmentation_a, augmentation_b)
- input_tensor = torch.rand(3, 5, 5, device=self.device, dtype=self.dtype) # 3 x 5 x 5
+ input_tensor = torch.rand(2, 3, 5, 5, device=self.device, dtype=self.dtype)
torch.manual_seed(42)
- out1 = augmentation(input_tensor)
- transform1 = augmentation.transform_matrix
- out2 = augmentation(out1)
- transform = augmentation.transform_matrix @ transform1
+ out_manual_a = augmentation_a(input_tensor)
+ transform_a = augmentation_a.transform_matrix
+ out_manual = augmentation_b(out_manual_a)
+ transform_manual = augmentation_b.transform_matrix @ transform_a
torch.manual_seed(42)
out_sequence = augmentation_sequence(input_tensor)
transform_sequence = augmentation_sequence.transform_matrix
- assert out1.shape == out_sequence.shape
- assert transform.shape == transform_sequence.shape
- self.assert_close(out2, out_sequence, low_tolerance=True)
- self.assert_close(transform, transform_sequence, low_tolerance=True)
+ assert out_manual.shape == out_sequence.shape
+ assert transform_manual.shape == transform_sequence.shape
+ self.assert_close(out_manual, out_sequence, low_tolerance=True)
+ self.assert_close(transform_manual, transform_sequence, low_tolerance=True)
def _test_inverse_coordinate_check_implementation(self, params):
torch.manual_seed(42)
diff --git a/tests/augmentation/test_base.py b/tests/augmentation/test_base.py
index d70200d91..ac8f067f7 100644
--- a/tests/augmentation/test_base.py
+++ b/tests/augmentation/test_base.py
@@ -68,7 +68,9 @@ class TestBasicAugmentationBase(BaseTester):
}
output = augmentation.forward_parameters(input_shape)
assert "batch_prob" in output
- assert len(output["degrees"]) == output["batch_prob"].sum().item() == num
+ # generate_parameters is now called with the full batch shape (ONNX-friendly contract).
+ assert len(output["degrees"]) == input_shape[0]
+ assert output["batch_prob"].sum().item() == num
@pytest.mark.parametrize("keepdim", (True, False))
def test_forward(self, device, dtype, keepdim):
@@ -127,12 +129,16 @@ class TestAugmentationBase2D(BaseTester):
# Not an easy fix, happens on verifying torch.tensor([True, True])
# _params = {'batch_prob': torch.tensor([True, True]), 'params': {}, 'flags': {'foo': 0}}
# apply_transform.assert_called_once_with(input, _params)
- assert output is expected_output
+ # Identity check relaxed to value equality: the where-blend always materialises
+ # a fresh tensor, so output is never the same object as apply_transform's return.
+ assert torch.equal(output, expected_output)
# Calling the augmentation with a tensor and set return_transform shall
# return the expected tensor and transformation.
output = augmentation(input)
- assert output is expected_output
+ # Identity check relaxed to value equality: the where-blend always materialises
+ # a fresh tensor, so output is never the same object as apply_transform's return.
+ assert torch.equal(output, expected_output)
# Calling the augmentation with a tensor and params shall return the expected tensor using the given params.
params = {"params": {}, "flags": {"bar": 1}}
@@ -143,7 +149,9 @@ class TestAugmentationBase2D(BaseTester):
# Not an easy fix, happens on verifying torch.tensor([True, True])
# _params = {'batch_prob': torch.tensor([True, True]), 'params': {}, 'flags': {'foo': 0}}
# apply_transform.assert_called_once_with(input, _params)
- assert output is expected_output
+ # Identity check relaxed to value equality: the where-blend always materialises
+ # a fresh tensor, so output is never the same object as apply_transform's return.
+ assert torch.equal(output, expected_output)
# Calling the augmentation with a tensor,a transformation and set
# return_transform shall return the expected tensor and the proper
diff --git a/tests/augmentation/test_onnx_export.py b/tests/augmentation/test_onnx_export.py
new file mode 100644
index 000000000..a44abe650
--- /dev/null
+++ b/tests/augmentation/test_onnx_export.py
@@ -0,0 +1,320 @@
+# 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.
+#
+"""ONNX export regression tests for kornia.augmentation modules.
+
+These tests pin the set of augmentations that successfully export through
+``torch.onnx.export`` (legacy TorchScript-tracer path) at opset 20, so future
+changes to the augmentation base classes do not silently regress export
+support.
+
+Opset 20 was chosen as the floor because:
+- ``aten::affine_grid_generator`` (used by every geometric augmentation that
+ goes through ``warp_affine``) only lowers from opset 20 upward.
+- ``aten::grid_sampler`` is supported from opset 16, well below 20.
+- Earlier opsets work for non-geometric augmentations, but standardising on a
+ single opset keeps the test matrix small.
+
+What this file does NOT test:
+- Numerical equivalence between the exported ONNX graph and the eager forward.
+ That requires onnxruntime, which is not a hard dependency of kornia. Add a
+ separate test file (e.g. ``test_onnx_export_numerical.py``) gated on the
+ optional ``onnxruntime`` import when that work lands.
+- The ``dynamo=True`` export path. That is tracked separately because it has
+ different op coverage (notably, ``aten::linalg_solve`` lowers cleanly under
+ dynamo but not under the legacy tracer).
+- Augmentations that currently cannot export under the legacy tracer due to
+ missing ONNX op support, see ``XFAIL_OPS`` below.
+
+Adding an augmentation to ``EXPORTABLE_OPS`` is the way to advertise that it
+cleanly exports today; adding to ``XFAIL_OPS`` marks a known gap with the
+underlying op so we don't lose the signal that it's still pending.
+"""
+
+from __future__ import annotations
+
+import io
+import warnings
+from typing import Any, Callable, Tuple
+
+import pytest
+import torch
+
+import kornia.augmentation as K
+
+
+def _hflip() -> torch.nn.Module:
+ return K.RandomHorizontalFlip(p=1.0)
+
+
+def _vflip() -> torch.nn.Module:
+ return K.RandomVerticalFlip(p=1.0)
+
+
+def _color_jiggle() -> torch.nn.Module:
+ return K.ColorJiggle(0.1, 0.1, 0.1, 0.1, p=1.0)
+
+
+def _brightness() -> torch.nn.Module:
+ return K.RandomBrightness(brightness=(0.5, 1.5), p=1.0)
+
+
+def _grayscale() -> torch.nn.Module:
+ return K.RandomGrayscale(p=1.0)
+
+
+def _invert() -> torch.nn.Module:
+ return K.RandomInvert(p=1.0)
+
+
+def _gaussian_blur() -> torch.nn.Module:
+ return K.RandomGaussianBlur((3, 3), (0.1, 2.0), p=1.0)
+
+
+def _erasing() -> torch.nn.Module:
+ return K.RandomErasing(p=1.0)
+
+
+def _posterize() -> torch.nn.Module:
+ return K.RandomPosterize(3, p=1.0)
+
+
+def _solarize() -> torch.nn.Module:
+ return K.RandomSolarize(0.1, p=1.0)
+
+
+def _normalize() -> torch.nn.Module:
+ return K.Normalize(mean=torch.zeros(3), std=torch.ones(3))
+
+
+def _affine() -> torch.nn.Module:
+ return K.RandomAffine(degrees=10.0, p=1.0)
+
+
+def _rotation() -> torch.nn.Module:
+ return K.RandomRotation(degrees=10.0, p=1.0)
+
+
+def _perspective() -> torch.nn.Module:
+ return K.RandomPerspective(p=1.0)
+
+
+def _augmentation_sequential() -> torch.nn.Module:
+ """A torchgeo-typical pipeline: per-element random flips followed by normalize."""
+ return K.AugmentationSequential(
+ K.RandomHorizontalFlip(p=0.5),
+ K.RandomVerticalFlip(p=0.5),
+ K.Normalize(mean=torch.zeros(3), std=torch.ones(3)),
+ data_keys=["input"],
+ )
+
+
+# Augmentations that export today through the legacy TorchScript tracer at opset 20.
+EXPORTABLE_OPS: list[Tuple[str, Callable[[], torch.nn.Module]]] = [
+ ("RandomHorizontalFlip", _hflip),
+ ("RandomVerticalFlip", _vflip),
+ ("ColorJiggle", _color_jiggle),
+ ("RandomBrightness", _brightness),
+ ("RandomGrayscale", _grayscale),
+ ("RandomInvert", _invert),
+ ("RandomGaussianBlur", _gaussian_blur),
+ ("RandomErasing", _erasing),
+ ("RandomPosterize", _posterize),
+ ("RandomSolarize", _solarize),
+ ("Normalize", _normalize),
+ # Geometric augmentations enabled by:
+ # - bumping opset to 20 (for ``affine_grid_generator``)
+ # - the closed-form 3x3 inverse in ``kornia.core.utils._inverse_3x3_closed_form``
+ # that replaces ``aten::linalg_inv`` during ONNX export.
+ ("RandomAffine", _affine),
+ ("RandomRotation", _rotation),
+ # ``RandomPerspective`` exports via the closed-form Heckbert decomposition in
+ # ``kornia.geometry.transform.imgwarp._get_perspective_transform_closed_form``,
+ # which replaces the 8x8 ``torch.linalg.solve`` with two unit-square-to-quad
+ # constructions and one closed-form 3x3 inverse.
+ ("RandomPerspective", _perspective),
+ # Container: pinned because torchgeo and similar callers wrap their pipelines
+ # in ``AugmentationSequential``. The container's ``forward`` strips trailing
+ # ``None`` positional args injected by the legacy ONNX tracer.
+ ("AugmentationSequential", _augmentation_sequential),
+]
+
+# Currently no augmentations are blocked at export time. Augmentations that export
+# but produce numerically different results from eager are tracked separately in
+# ``ONNX_NUMERICAL_KNOWN_DRIFT`` below.
+XFAIL_OPS: list[Tuple[str, Callable[[], torch.nn.Module], str]] = []
+
+
+def _try_export(module: torch.nn.Module, x: torch.Tensor) -> int:
+ """Run ``torch.onnx.export`` against an in-memory buffer and return the byte count."""
+ module.eval()
+ buf = io.BytesIO()
+ with warnings.catch_warnings():
+ warnings.simplefilter("ignore")
+ torch.onnx.export(
+ module,
+ (x,),
+ buf,
+ opset_version=20,
+ input_names=["input"],
+ output_names=["output"],
+ dynamo=False,
+ )
+ return len(buf.getvalue())
+
+
[email protected]("name,factory", EXPORTABLE_OPS, ids=[n for n, _ in EXPORTABLE_OPS])
+def test_onnx_export_exportable(name: str, factory: Callable[[], torch.nn.Module]) -> None:
+ """Augmentation exports cleanly via ``torch.onnx.export`` (legacy tracer, opset 20)."""
+ torch.manual_seed(0)
+ x = torch.randn(2, 3, 32, 32)
+ size = _try_export(factory(), x)
+ assert size > 0, f"{name}: ONNX graph was empty"
+
+
[email protected]("name,factory,reason", XFAIL_OPS, ids=[n for n, _, _ in XFAIL_OPS])
+def test_onnx_export_known_blocked(name: str, factory: Callable[[], torch.nn.Module], reason: str) -> None:
+ """Augmentation cannot export today; pinned so we notice if it starts working."""
+ torch.manual_seed(0)
+ x = torch.randn(2, 3, 32, 32)
+ with pytest.raises(Exception):
+ _try_export(factory(), x)
+
+
+# ----------------------------------------------------------------------------
+# Numerical-equivalence checks (require onnxruntime).
+#
+# Each entry pins a concrete deterministic configuration of the augmentation is
+# fixed angles, fixed brightness, etc. So comparing eager and ONNX is a
+# clean apples-to-apples test of "did the export faithfully capture the
+# computation". Augmentations with random parameter ranges are deliberately
+# excluded from the numerical check because ``torch.onnx.export`` consumes RNG
+# during tracing in ways that don't line up with a separate eager call, even
+# under the same ``torch.manual_seed``, that mismatch is RNG bookkeeping and
+# would mask real bugs. The export-success tests above cover the random case.
+# ----------------------------------------------------------------------------
+
+ort = pytest.importorskip("onnxruntime", reason="onnxruntime is required for numerical-equivalence checks")
+np = pytest.importorskip("numpy")
+
+
+# Deterministic factories for numerical tests. Tuple ranges of the form ``(v, v)``
+# evaluate to a single fixed value under uniform sampling. Geometric augmentations
+# additionally rely on the in-place-mutation fix in
+# ``kornia.geometry.conversions.normal_transform_pixel`` and the ``deg2rad``
+# inlining in the affine/shear ``compute_transformation`` paths.
+def _hflip_det() -> torch.nn.Module:
+ return K.RandomHorizontalFlip(p=1.0)
+
+
+def _vflip_det() -> torch.nn.Module:
+ return K.RandomVerticalFlip(p=1.0)
+
+
+def _grayscale_det() -> torch.nn.Module:
+ return K.RandomGrayscale(p=1.0)
+
+
+def _invert_det() -> torch.nn.Module:
+ return K.RandomInvert(p=1.0)
+
+
+def _normalize_det() -> torch.nn.Module:
+ return K.Normalize(mean=torch.zeros(3), std=torch.ones(3))
+
+
+def _brightness_det() -> torch.nn.Module:
+ return K.RandomBrightness(brightness=(1.2, 1.2), p=1.0)
+
+
+def _color_jiggle_det() -> torch.nn.Module:
+ return K.ColorJiggle(brightness=(1.2, 1.2), p=1.0)
+
+
+def _gaussian_blur_det() -> torch.nn.Module:
+ return K.RandomGaussianBlur((3, 3), (1.5, 1.5), p=1.0)
+
+
+def _solarize_det() -> torch.nn.Module:
+ return K.RandomSolarize(thresholds=(0.5, 0.5), additions=(0.0, 0.0), p=1.0)
+
+
+def _rotation_det() -> torch.nn.Module:
+ return K.RandomRotation(degrees=(15.0, 15.0), p=1.0)
+
+
+def _affine_det() -> torch.nn.Module:
+ return K.RandomAffine(degrees=(15.0, 15.0), translate=(0.0, 0.0), scale=(1.0, 1.0), shear=(0.0, 0.0), p=1.0)
+
+
+def _affine_with_shear_det() -> torch.nn.Module:
+ return K.RandomAffine(degrees=(0.0, 0.0), shear=(5.0, 5.0), p=1.0)
+
+
+# Augmentations whose exported graph produces numerically equivalent results to
+# eager when configured with deterministic parameters. ``max diff < 1e-3``
+# threshold is conservative, most are float32 precision (< 1e-5).
+ONNX_NUMERICAL_EQUIVALENT: list[Tuple[str, Callable[[], torch.nn.Module]]] = [
+ # Parameter-free / no random sampling
+ ("RandomHorizontalFlip", _hflip_det),
+ ("RandomVerticalFlip", _vflip_det),
+ ("RandomGrayscale", _grayscale_det),
+ ("RandomInvert", _invert_det),
+ ("Normalize", _normalize_det),
+ # Random params pinned to deterministic ranges
+ ("RandomBrightness", _brightness_det),
+ ("ColorJiggle", _color_jiggle_det),
+ ("RandomGaussianBlur", _gaussian_blur_det),
+ ("RandomSolarize", _solarize_det),
+ # Geometric augmentations, exercise the warp_affine / grid_sample path.
+ # Previously diverged due to in-place mutation in normal_transform_pixel
+ # losing the scale factors under tracing.
+ ("RandomRotation", _rotation_det),
+ ("RandomAffine", _affine_det),
+ ("RandomAffine_with_shear", _affine_with_shear_det),
+]
+
+
+def _run_onnx(module: torch.nn.Module, x: torch.Tensor) -> Any:
+ module.eval()
+ buf = io.BytesIO()
+ with warnings.catch_warnings():
+ warnings.simplefilter("ignore")
+ torch.onnx.export(
+ module,
+ (x,),
+ buf,
+ opset_version=20,
+ dynamo=False,
+ input_names=["input"],
+ output_names=["output"],
+ )
+ sess = ort.InferenceSession(buf.getvalue())
+ return sess.run(["output"], {"input": x.numpy()})[0]
+
+
[email protected]("name,factory", ONNX_NUMERICAL_EQUIVALENT, ids=[n for n, _ in ONNX_NUMERICAL_EQUIVALENT])
+def test_onnx_export_numerically_matches_eager(name: str, factory: Callable[[], torch.nn.Module]) -> None:
+ """Exported graph produces the same numbers as eager for the deterministic configuration."""
+ torch.manual_seed(0)
+ x = torch.randn(2, 3, 32, 32)
+ aug = factory()
+ aug.eval()
+ eager = aug(x).numpy()
+ onnx_out = _run_onnx(aug, x)
+ assert eager.shape == onnx_out.shape, f"{name}: shape mismatch {eager.shape} vs {onnx_out.shape}"
+ max_diff = float(np.abs(eager - onnx_out).max())
+ assert max_diff < 1e-3, f"{name}: max abs diff {max_diff:.4f} exceeds 1e-3"