π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(augmentation): containers export mask, box and keypoint replays on torch 2.9.1's dynamo exporter again (#6196)
Dmytro Mishkin649b3f86d9c1
diff --git a/changelog.d/6196.fixed.md b/changelog.d/6196.fixed.mdnew file mode 100644index 000000000..30b70f14b--- /dev/null+++ b/changelog.d/6196.fixed.md@@ -0,0 +1,6 @@+`AugmentationSequential` with `mask`, box or `keypoints` data keys, and the `ManyToManyAugmentationDispather` and+`ManyToOneAugmentationDispather` built from it, export again with torch 2.9's dynamo ONNX exporter when replayed with+constant `params` and a `RandomAffine` child. Since #5416 the annotation handlers recompute the child's matrix from the+caller's params under export, and `RandomAffine` copies `center` from them as-is, which that exporter turns into a+renamed graph constant and rejects. The handlers now compute from a copy of the params, as the image call does.+Eager outputs are unchanged. Fixes #6166.diff --git a/kornia/augmentation/container/ops.py b/kornia/augmentation/container/ops.pyindex 251527c1c..3fea94f75 100644--- a/kornia/augmentation/container/ops.py+++ b/kornia/augmentation/container/ops.py@@ -23,6 +23,7 @@ from torch import nnimport kornia.augmentation as Kfrom kornia.augmentation.base import _AugmentationBase+from kornia.augmentation.utils.helpers import deepcopy_dictfrom kornia.constants import DataKeyfrom kornia.core.utils import is_exportingfrom kornia.geometry.boxes import Boxes@@ -95,7 +96,10 @@ class SequentialOpsInterface(Generic[T], metaclass=ABCMeta):left, right, top, bottom = padding_size[0].tolist()input_shape = (*input_shape[:-2], input_shape[-2] - top - bottom, input_shape[-1] - left - right)matrix_input = torch.empty((), device=device, dtype=dtype).expand(input_shape)- return module.generate_transformation_matrix(matrix_input, params, module.flags)+ # Compute from a copy of the params, as the image call does (its ``data_keys`` override copies the dict). Under+ # export the caller's tensors can be graph constants, and a child that copies one as-is into its matrix, as+ # ``RandomAffine`` does with ``center``, makes torch 2.9's dynamo ONNX exporter rename that constant and fail.+ return module.generate_transformation_matrix(matrix_input, deepcopy_dict(params), module.flags)@classmethoddef get_sequential_module_param(cls, param: ParamItem) -> List[ParamItem]:diff --git a/testing/known_failure_xfails/onnx_conformance_torch2.9.txt b/testing/known_failure_xfails/onnx_conformance_torch2.9.txtindex 4c81f814b..119d80bcf 100644--- a/testing/known_failure_xfails/onnx_conformance_torch2.9.txt+++ b/testing/known_failure_xfails/onnx_conformance_torch2.9.txt@@ -5,6 +5,15 @@# regression to fix; add it only with a comment naming its own tracking issue.# Entries of packages a run does not select are not checked; every node ID must name a promised case.# Format: <exact exception type>\t<pytest node ID>+# #6164: the legacy exporter traces the CPU loop of Boxes.to_mask / Boxes3D.to_mask and writes a+# constant all-zero mask with no graph input.+AssertionError tests/onnx/test_conformance.py::test_legacy_export_is_not_wrong[boxes.Boxes.to_mask]+AssertionError tests/onnx/test_conformance.py::test_legacy_export_is_not_wrong[boxes.Boxes3D.to_mask]+# #6165: the legacy exporter gives torch.log10 of a 0-d tensor the shape (1,), so the PSNR graphs+# return (1,) instead of a scalar.+AssertionError tests/onnx/test_conformance.py::test_legacy_export_is_not_wrong[losses.PSNRLoss]+AssertionError tests/onnx/test_conformance.py::test_legacy_export_is_not_wrong[losses.psnr_loss]+AssertionError tests/onnx/test_conformance.py::test_legacy_export_is_not_wrong[metrics.psnr]# #6166: since #5416 the annotation handlers of a container recompute the child's# matrix from the replayed params under export, and torch 2.9.1's exporter rejects the graph ("Key '..._lifted_tensor_N'# does not match the name of the value 'copy_M'"); torch 2.14 exports them.diff --git a/tests/augmentation/test_torch_export.py b/tests/augmentation/test_torch_export.pyindex 8d364e5de..253f1a4b9 100644--- a/tests/augmentation/test_torch_export.py+++ b/tests/augmentation/test_torch_export.py@@ -38,6 +38,7 @@ from typing import Callable, Tupleimport pytestimport torch+from torch.export.graph_signature import InputKindimport kornia.augmentation as K@@ -282,3 +283,56 @@ def test_torch_export_integer_mask_labels_4478(image_dtype: torch.dtype) -> Nonefor invalid in (label, torch.iinfo(torch.int64).max):with pytest.raises(RuntimeError, match="Integer mask labels"):exported(image, torch.full_like(mask, invalid))+++class _ReplayWithConstantParams(torch.nn.Module):+ """Call ``seq`` with the params of its last eager call held constant, as an exported replay does."""++ def __init__(self, seq: torch.nn.Module, params: list) -> None:+ super().__init__()+ self.seq = seq+ self.params = params++ def forward(self, *args: torch.Tensor) -> object:+ return self.seq(*args, params=self.params)++[email protected](not hasattr(torch, "export"), reason="torch.export requires torch>=2.1")[email protected](not dynamo_is_available(), reason=DYNAMO_UNAVAILABLE_REASON)[email protected](not _HAS_TORCH_EXPORT_TRACKING, reason=_TORCH_EXPORT_TRACKING_REASON)[email protected]("data_key", ["mask", "keypoints", "bbox_xyxy"])[email protected]_agnostic+def test_torch_export_annotation_replay_copies_no_constant_6166(data_key: str) -> None:+ """The annotation handlers recompute a child's matrix from copies of constant params under export (#6166).++ Params held constant are graph constants in the exported program. ``RandomAffine`` writes ``center`` as-is into+ its matrix, and torch 2.9's dynamo ONNX exporter drops the same-dtype cast it lowers that ``copy`` to, renames the+ constant after the copy and then rejects it, so the export failed. The decomposed graph that exporter lowers must+ hold no ``copy`` of a constant on any torch, and the exported annotations must match eager.+ """+ torch.manual_seed(0)+ image = torch.rand(2, 3, 16, 20)+ extra = {+ "mask": (torch.rand(2, 1, 16, 20) > 0.5).float(),+ "keypoints": torch.tensor([[[3.0, 4.0], [12.0, 9.0]]]).repeat(2, 1, 1),+ "bbox_xyxy": torch.tensor([[[2.0, 3.0, 10.0, 12.0]]]).repeat(2, 1, 1),+ }[data_key]+ seq = K.AugmentationSequential(K.RandomAffine(15.0, p=1.0), data_keys=["input", data_key])+ seq(image, extra)+ model = _ReplayWithConstantParams(seq, seq._params)+ eager = model(image, extra)++ program = torch.export.export(model, (image, extra), strict=False)+ graph = program.run_decompositions()+ constants = {spec.arg.name for spec in graph.graph_signature.input_specs if spec.kind == InputKind.CONSTANT_TENSOR}+ copies_of_constants = [+ node.name+ for node in graph.graph.nodes+ if node.target == torch.ops.aten.copy.default and getattr(node.args[1], "name", None) in constants+ ]+ assert not copies_of_constants, f"{data_key}: {copies_of_constants} copy a graph constant as-is"++ out = program.module()(image, extra)+ assert len(out) == len(eager) == 2+ for got, expected in zip(out, eager, strict=True):+ torch.testing.assert_close(got, expected, atol=1e-5, rtol=1e-5)