Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix: take the capture path under torch.compile at the remaining is_exporting() compile sites (#5037) (#6226)

Dmytro Mishkin5b831b4069f9
diff --git a/changelog.d/6226.fixed.md b/changelog.d/6226.fixed.md
new file mode 100644
index 000000000..713ec257b
--- /dev/null
+++ b/changelog.d/6226.fixed.md
@@ -0,0 +1 @@
+`Resize`, `LongestMaxSize` and `SmallestMaxSize` with an int size, `Boxes.from_tensor`, `Boxes.to_mask`, `Boxes3D.from_tensor`, `Boxes3D.to_mask`, `validate_bbox3d` and the 3D box functions that call it (`bbox_to_mask3d`, `infer_bbox_shape3d`, `center_crop3d`, `crop_and_resize3d`), `StereoCamera`, `So2.from_matrix`, `Se2.from_matrix` and `jpeg_codec_differentiable` / `JPEGCodecDifferentiable` now compile with `torch.compile(fullgraph=True)` on torch 2.12 and later (CI checks 2.14). Their data-dependent input checks and host-side code paths now follow any graph capture, as they already did under `torch.export` and under `torch.compile` on earlier torch releases. A compiled call on torch 2.12 and later therefore no longer checks for invalid input, as on earlier releases: boxes with a non-finite coordinate (in `Boxes3D.from_tensor`, the `'xy*'` modes of `Boxes.from_tensor` and the 3D box functions that call `validate_bbox3d`) or a non-positive extent, unequal 3D box edges, a stereo rig with differing intrinsics or a zero or reversed baseline, a rotation block that is not of the form `[[a, -b], [b, a]]`, or a JPEG quality outside `[0, 100]`. `crop_by_boxes3d` skips the same 3D box checks in a compiled call, but it reads its output size from the boxes and still does not compile in one graph. Eager calls still raise. Under capture, `Boxes.to_mask` and `Boxes3D.to_mask` take their vectorized path, which fills the same mask.
diff --git a/docs/source/geometry.camera.stereo.rst b/docs/source/geometry.camera.stereo.rst
index 0fc4f8e21..5beaec57f 100644
--- a/docs/source/geometry.camera.stereo.rst
+++ b/docs/source/geometry.camera.stereo.rst
@@ -127,7 +127,7 @@ where :math:`Q` is
The :math:`Q` that :class:`StereoCamera` builds is exactly this matrix with :math:`tx = P_1[0, 3] / fx`, which the constructor requires to be strictly negative (a zero baseline or swapped cameras raise). The class's ``tx`` attribute is the positive baseline :math:`-P_1[0, 3] / fx`, so do not substitute it for :math:`tx` above.
-The :math:`Q[3, 3]` term is zero on every rig :class:`StereoCamera` accepts outside ``torch.export``: the constructor rejects differing :math:`cx_{left}` and :math:`cx_{right}` (`#4270 <https://github.com/kornia/kornia/issues/4270>`_).
+The :math:`Q[3, 3]` term is zero on every rig :class:`StereoCamera` accepts outside graph capture (``torch.compile``, ``torch.export``): the constructor rejects differing :math:`cx_{left}` and :math:`cx_{right}` (`#4270 <https://github.com/kornia/kornia/issues/4270>`_).
Assuming :math:`fx = fy` you can further reduce this to:
diff --git a/kornia/augmentation/_2d/geometric/resize.py b/kornia/augmentation/_2d/geometric/resize.py
index 543668dd6..a870436f3 100644
--- a/kornia/augmentation/_2d/geometric/resize.py
+++ b/kornia/augmentation/_2d/geometric/resize.py
@@ -23,7 +23,7 @@ from kornia.augmentation import random_generator as rg
from kornia.augmentation._2d.base import _input_metadata_only
from kornia.augmentation._2d.geometric.base import GeometricAugmentationBase2D
from kornia.constants import Resample
-from kornia.core.utils import _to_device_nonblocking, is_exporting
+from kornia.core.utils import _to_device_nonblocking, is_compiling
from kornia.geometry.transform import crop_by_transform_mat, get_perspective_transform, resize
from kornia.geometry.transform._crop import _half_pixel_resize_transform
from kornia.geometry.transform.affwarp import _side_to_image_size
@@ -118,8 +118,9 @@ class Resize(GeometricAugmentationBase2D):
# data-dependent `output_size` param).
if isinstance(flags["size"], (tuple, list)):
out_size: Tuple[int, int] = (int(flags["size"][0]), int(flags["size"][1]))
- elif is_exporting() or input.shape[0] == 0:
- # `output_size` is a function of the (static) input shape; recompute it rather than read the tensor.
+ elif is_compiling() or input.shape[0] == 0:
+ # `output_size` is a function of the (static) input shape; recompute it rather than read the tensor,
+ # which graph capture (torch.compile, torch.export) cannot do.
# An empty batch has no row to read it from, and the generator returns no `output_size` for it (#4429).
h, w = input.shape[-2:]
out_size = _side_to_image_size(int(flags["size"]), w / h, flags["side"])
diff --git a/kornia/core/utils.py b/kornia/core/utils.py
index a89822dd4..eb20deb20 100644
--- a/kornia/core/utils.py
+++ b/kornia/core/utils.py
@@ -773,16 +773,19 @@ def is_exporting() -> bool:
``torch.export`` rejects, without changing the captured output. Always ``False`` inside
TorchScript, so the guard is safe to call from scripted functions.
- The flag is meant to be export-specific, not capture-specific, but whether it is also true inside
- a ``torch.compile`` trace depends on the Torch release, so a compiled call can take different
- paths across versions (#5037). It is false under ``torch.jit.trace`` and the legacy ONNX
- exporter. Where the intent is "inside any Dynamo capture" - skipping a data-dependent check that
- breaks ``fullgraph`` - use :func:`is_compiling`, which covers ``torch.compile`` and
- ``torch.export`` alike on every supported release. Keep this predicate for what only an export
- needs: :func:`crop_by_indices` routing to its dedicated export implementation, where letting a
- compiled call take that route changes the sampling the eager and compiled paths agree on, and
- skipping per-call state on ``self`` that ``torch.export`` rejects but a compiled call records and
- a caller reads back afterwards, such as the ``transform_matrix`` of an augmentation.
+ The flag is export-specific, not capture-specific: that is what Torch reports from 2.12 on (CI
+ checks 2.14), and it is the meaning kornia relies on. Releases before 2.12 also report it inside a
+ ``torch.compile`` trace (2.9.1, and 2.5.1 through the fallback above), so a compiled call can take
+ different paths across versions (#5037). The call sites that keep this predicate run their eager
+ checks and routes inside ``torch.compile`` from 2.12 on, so some inputs of those operators do not
+ compile with ``fullgraph=True`` there. It is false under ``torch.jit.trace`` and the legacy ONNX exporter. Where
+ the intent is "inside any Dynamo capture" - skipping a data-dependent check that breaks
+ ``fullgraph`` - use :func:`is_compiling`, which covers ``torch.compile`` and ``torch.export`` alike
+ on every supported release. Keep this predicate for what only an export needs:
+ :func:`crop_by_indices` routing to its dedicated export implementation, where letting a compiled
+ call take that route changes the sampling the eager and compiled paths agree on, and skipping
+ per-call state on ``self`` that ``torch.export`` rejects but a compiled call records and a caller
+ reads back afterwards, such as the ``transform_matrix`` of an augmentation.
"""
if torch.jit.is_scripting():
return False
diff --git a/kornia/enhance/jpeg.py b/kornia/enhance/jpeg.py
index 4bfb47034..c31e9339c 100644
--- a/kornia/enhance/jpeg.py
+++ b/kornia/enhance/jpeg.py
@@ -27,7 +27,7 @@ from torch import nn
from kornia.color import rgb_to_ycbcr, ycbcr_to_rgb
from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SAME_SIZE, KORNIA_CHECK_SHAPE
from kornia.core.ops import _device_literal
-from kornia.core.utils import _autocast_disabled, _to_device_nonblocking, is_compiling, is_exporting
+from kornia.core.utils import _autocast_disabled, _to_device_nonblocking, is_compiling
from kornia.enhance.adjust import _check_floating_image
from kornia.geometry.transform.affwarp import rescale
from kornia.image.utils import perform_keep_shape_image
@@ -641,8 +641,9 @@ def jpeg_codec_differentiable(
# Check resulting shape of quantization tables
KORNIA_CHECK_SHAPE(quantization_table_y, ["B", "8", "8"])
KORNIA_CHECK_SHAPE(quantization_table_c, ["B", "8", "8"])
- # Check value range of JPEG quality. The check reads the data, which graph capture cannot do; skip under export.
- if not is_exporting():
+ # Check value range of JPEG quality. The check reads the data, which graph capture cannot do; skip it under any
+ # capture (torch.compile, torch.export).
+ if not is_compiling():
KORNIA_CHECK(
(jpeg_quality.amin().item() >= 0.0) and (jpeg_quality.amax().item() <= 100.0),
lambda: (
diff --git a/kornia/geometry/bbox.py b/kornia/geometry/bbox.py
index dbc96f178..6ca99d32f 100644
--- a/kornia/geometry/bbox.py
+++ b/kornia/geometry/bbox.py
@@ -23,7 +23,7 @@ from typing import Optional
import torch
from kornia.core.check import KORNIA_CHECK_SHAPE
-from kornia.core.utils import is_exporting
+from kornia.core.utils import is_compiling
from .linalg import transform_points
@@ -120,8 +120,9 @@ def validate_bbox3d(boxes: torch.Tensor) -> bool:
if len(boxes.shape) == 4:
boxes = boxes.reshape(-1, 8, 3)
- # The value checks below read the data, which graph capture cannot do; skip them under export.
- if is_exporting():
+ # The value checks below read the data, which graph capture cannot do; skip them under any capture
+ # (torch.compile, torch.export). TorchScript cannot call is_compiling(), and a scripted call keeps the checks.
+ if not torch.jit.is_scripting() and is_compiling():
return True
# Non-finite coordinates are rejected as a predicate result rather than through the ``allclose``
diff --git a/kornia/geometry/boxes.py b/kornia/geometry/boxes.py
index 184ae27c6..d9c22520a 100644
--- a/kornia/geometry/boxes.py
+++ b/kornia/geometry/boxes.py
@@ -23,7 +23,7 @@ import torch
from torch import Size
from kornia.core.ops import eye_like
-from kornia.core.utils import is_exporting
+from kornia.core.utils import is_compiling, is_exporting
from kornia.geometry.linalg import transform_points
__all__ = ["Boxes", "Boxes3D", "VideoBoxes"]
@@ -173,8 +173,9 @@ def _boxes_to_quadrilaterals(boxes: torch.Tensor, mode: str = "xyxy", validate_b
else:
raise ValueError(f"Unknown mode {mode}")
- # Value validation reads the data, which graph capture cannot do; skip it under export.
- if validate_boxes and not is_exporting():
+ # Value validation reads the data, which graph capture cannot do; skip it under any capture (torch.compile,
+ # torch.export).
+ if validate_boxes and not is_compiling():
_validate_box_values(boxes, width, height)
xmin, ymin = boxes[..., 0], boxes[..., 1]
@@ -699,6 +700,8 @@ class Boxes:
validate_boxes: Reject a non-finite coordinate in every mode: ``ValueError`` for the ``'xy*'`` modes,
which also reject non-positive extents in each mode's convention, and ``RuntimeError`` from
``torch._assert_async`` for the vertex modes (skipped on MPS), which take no extent or shape check.
+ The ``'xy*'`` checks read the data, so graph capture (``torch.compile``, ``torch.export``) skips
+ them.
Returns:
:class:`Boxes` containing the converted inclusive vertex representation.
@@ -882,10 +885,11 @@ class Boxes:
# -----------------
# CPU Hotpath (loop)
# -----------------
- # The loop slices with data-dependent bounds, which graph capture cannot do; export takes the vectorized path.
- # So does the legacy ONNX exporter, which traces outside ``is_exporting()``: it loses the loop's in-place
- # writes into the mask and exports a constant all-zero mask with no graph input.
- if device.type != "cuda" and not is_exporting() and not torch.jit.is_tracing():
+ # The loop slices with data-dependent bounds, which graph capture cannot do; any capture (torch.compile,
+ # torch.export) takes the vectorized path, which fills the same mask. So does the legacy ONNX exporter, which
+ # traces outside ``is_compiling()``: it loses the loop's in-place writes into the mask and exports a constant
+ # all-zero mask with no graph input.
+ if device.type != "cuda" and not is_compiling() and not torch.jit.is_tracing():
if self._is_batched: # (B, N, 4, 2)
mask = torch.zeros(
(self._data.shape[0], self._data.shape[1], height, width), dtype=self.dtype, device=self.device
@@ -1332,7 +1336,8 @@ class Boxes3D:
validate_boxes: reject boxes with a non-finite coordinate, and boxes whose width, height or depth
is not positive when measured in the given mode's convention, so ``xmax == xmin`` is rejected in
- ``'xyzxyz'`` and accepted in ``'xyzxyz_plus'``.
+ ``'xyzxyz'`` and accepted in ``'xyzxyz_plus'``. The checks read the data, so graph capture
+ (``torch.compile``, ``torch.export``) skips them.
Returns:
:class:`Boxes3D` containing the converted inclusive vertex representation, labelled with ``mode``.
@@ -1382,8 +1387,9 @@ class Boxes3D:
else:
raise ValueError(f"Unknown mode {mode}")
- # Value validation reads the data, which graph capture cannot do; skip it under export.
- if validate_boxes and not is_exporting():
+ # Value validation reads the data, which graph capture cannot do; skip it under any capture (torch.compile,
+ # torch.export).
+ if validate_boxes and not is_compiling():
if not torch.isfinite(boxes).all():
raise ValueError("Some boxes have non-finite coordinates.")
if (width <= 0).any():
@@ -1563,10 +1569,11 @@ class Boxes3D:
# Cast boxes coordinates to be integer to use them as bounds. Use round to handle decimal values.
xyzxyz = clipped_boxes_xyzxyz.view(-1, 6).round().long()
- if is_exporting() or torch.jit.is_tracing():
- # The loop below slices with data-dependent bounds, which graph capture cannot do; compare a
- # coordinate grid against the bounds instead. The legacy ONNX exporter traces outside
- # ``is_exporting()`` and loses the loop's in-place writes, exporting a constant all-zero mask.
+ if is_compiling() or torch.jit.is_tracing():
+ # The loop below slices with data-dependent bounds, which graph capture (torch.compile, torch.export)
+ # cannot do; compare a coordinate grid against the bounds instead, which fills the same mask. The legacy
+ # ONNX exporter traces outside ``is_compiling()`` and loses the loop's in-place writes, exporting a
+ # constant all-zero mask.
device = self._data.device
zs = torch.arange(depth, device=device)
ys = torch.arange(height, device=device)
diff --git a/kornia/geometry/camera/stereo.py b/kornia/geometry/camera/stereo.py
index a04bb6f1c..f7ce58efb 100644
--- a/kornia/geometry/camera/stereo.py
+++ b/kornia/geometry/camera/stereo.py
@@ -19,7 +19,7 @@ from typing import Any, Literal, overload
import torch
-from kornia.core.utils import is_exporting
+from kornia.core.utils import is_compiling
from kornia.geometry.conversions import convert_points_from_homogeneous, convert_points_to_homogeneous
from kornia.geometry.grid import create_meshgrid
@@ -59,7 +59,7 @@ class StereoCamera:
- the baseline is read back as the attribute :attr:`tx` ``= -P_right[0, 3] / fx``, which must be
strictly **positive** for every rig in the batch: a zero baseline and swapped cameras both raise. A
non-finite ``P_right[0, 3]`` is not screened, and these checks and the equal-intrinsics check are
- skipped under ``torch.export``.
+ skipped under graph capture (``torch.compile``, ``torch.export``).
The :doc:`/geometry.camera.stereo` page's symbol ``tx`` is the negation of this attribute; :attr:`Q`
is the page's matrix evaluated at the page's ``tx``.
- ``Q[0, 0]`` carries ``fy`` and ``Q[1, 1]`` carries ``fx``; with the divide by ``W = -fy * disparity``
@@ -72,7 +72,7 @@ class StereoCamera:
.. warning::
A differing ``cx`` is **rejected**, although ``Q[3, 3] = fy * (cx_left - cx_right)`` exists for that
- case, so it is zero on every rig the constructor accepts outside ``torch.export``:
+ case, so it is zero on every rig the constructor accepts outside graph capture:
`#4270 <https://github.com/kornia/kornia/issues/4270>`_. A zero disparity (a point at infinity) makes
``W = 0``; the divide is then skipped and a finite placeholder, behind the camera on a real rig, is
returned. Request ``return_mask=True`` from :meth:`reproject_disparity_to_3D` to identify numerical
@@ -158,8 +158,9 @@ class StereoCamera:
)
# Ensure all intrinsics parameters (fx, fy, cx, cy) are the same in both cameras.
- # The check reads the data, which graph capture cannot do; skip it under export.
- if not is_exporting() and not torch.all(
+ # The check reads the data, which graph capture cannot do; skip it under any capture (torch.compile,
+ # torch.export).
+ if not is_compiling() and not torch.all(
torch.eq(rectified_left_camera[..., :, :3], rectified_right_camera[..., :, :3])
):
raise StereoException(
@@ -174,9 +175,10 @@ class StereoCamera:
# ``any``, so one bad rig cannot hide behind good ones, and an empty batch stays vacuously valid. Neither
# comparison screens non-finite input: ``nan`` fails both of them and ``-inf`` is negative, so both are
# still accepted, exactly as they were before these checks were tightened.
- # The check reads the data, which graph capture cannot do; skip it under export.
+ # The check reads the data, which graph capture cannot do; skip it under any capture (torch.compile,
+ # torch.export).
tx_fx = rectified_right_camera[..., 0, 3]
- if not is_exporting():
+ if not is_compiling():
if torch.any(tx_fx == 0):
raise StereoException(
"Expected a non-zero stereo baseline, but :math:`T_x * f_x` is 0 for at least one camera pair, "
diff --git a/kornia/geometry/liegroup/se2.py b/kornia/geometry/liegroup/se2.py
index 168ca121d..2fc3dce43 100644
--- a/kornia/geometry/liegroup/se2.py
+++ b/kornia/geometry/liegroup/se2.py
@@ -95,8 +95,8 @@ class Se2(nn.Module):
``adjoint()`` is :math:`[[R, (t_y, -t_x)^\top], [0, 1]]`.
- ``from_matrix`` ignores the bottom row. In eager execution, it checks approximately that the rotation block
has the form :math:`[[a, -b], [b, a]]`, a rotation scaled by :math:`\sqrt{a^2 + b^2}`, and keeps the scale
- as a non-unit ``z`` that ``log`` drops; it rejects a reflection. Graph export omits the value check and
- interprets the block as ``z = m00 + i m10``.
+ as a non-unit ``z`` that ``log`` drops; it rejects a reflection. Graph capture (``torch.compile``,
+ ``torch.export``) omits the value check and interprets the block as ``z = m00 + i m10``.
- ``t`` is always a tensor registered as module state, whichever constructor built the pose; a ``Vector2``
passed to the constructor is unwrapped. ``g * p`` returns a ``Vector2`` only when ``p`` is one.
- ``hat`` returns the se(2) generator :math:`[[0, -\theta, v_x], [\theta, 0, v_y], [0, 0, 0]]` and ``vee``
diff --git a/kornia/geometry/liegroup/so2.py b/kornia/geometry/liegroup/so2.py
index 8813e8e59..fc08ffc60 100644
--- a/kornia/geometry/liegroup/so2.py
+++ b/kornia/geometry/liegroup/so2.py
@@ -28,7 +28,7 @@ from torch import nn
from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SHAPE
from kornia.core.exceptions import TypeCheckError
from kornia.core.tensor_wrapper import _unwrap
-from kornia.core.utils import is_exporting, register_module_state
+from kornia.core.utils import is_compiling, register_module_state
from kornia.geometry.vector import Vector2
@@ -327,8 +327,9 @@ class So2(nn.Module):
KORNIA_CHECK_IS_TENSOR(matrix)
if len(matrix.shape) < 2 or matrix.shape[-2:] != (2, 2):
raise ValueError(f"Input size must be (*, 2, 2). Got {matrix.shape}")
- # Value validation reads the data, which graph capture cannot do; skip it under export.
- if not is_exporting():
+ # Value validation reads the data, which graph capture cannot do; skip it under any capture (torch.compile,
+ # torch.export).
+ if not is_compiling():
mask_diag = torch.allclose(matrix[..., 0, 0], matrix[..., 1, 1])
mask_off_diag = torch.allclose(matrix[..., 0, 1], -matrix[..., 1, 0])
if not (mask_diag and mask_off_diag):
diff --git a/testing/known_failure_xfails/compile_conformance_torch2.14.txt b/testing/known_failure_xfails/compile_conformance_torch2.14.txt
index 7f8274cae..f3474ad01 100644
--- a/testing/known_failure_xfails/compile_conformance_torch2.14.txt
+++ b/testing/known_failure_xfails/compile_conformance_torch2.14.txt
@@ -6,31 +6,6 @@
# 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>. The type names the kind of failure (testing.conformance
# STATUS_EXCEPTIONS): AssertionError a wrong result, RuntimeError a failed compile, ValueError a failed eager run.
-# #5037: a data-dependent check or a host-side route guarded by is_exporting(), which is False under torch.compile
-# on torch 2.14 (True on 2.9.1), so Dynamo traces it and fullgraph fails; the call sites want is_compiling().
-RuntimeError tests/test_inductor_conformance.py::test_inductor_matches_eager[LongestMaxSize]
-RuntimeError tests/test_inductor_conformance.py::test_inductor_matches_eager[SmallestMaxSize]
-RuntimeError tests/test_inductor_conformance.py::test_inductor_matches_eager[LongestMaxSize[const-size]]
-RuntimeError tests/test_inductor_conformance.py::test_inductor_matches_eager[SmallestMaxSize[const-size]]
-RuntimeError tests/test_inductor_conformance.py::test_inductor_matches_eager[transform.center_crop3d]
-RuntimeError tests/test_inductor_conformance.py::test_inductor_matches_eager[transform.crop_and_resize3d]
-RuntimeError tests/test_inductor_conformance.py::test_inductor_matches_eager[bbox.bbox_to_mask3d]
-RuntimeError tests/test_inductor_conformance.py::test_inductor_matches_eager[bbox.infer_bbox_shape3d]
-RuntimeError tests/test_inductor_conformance.py::test_inductor_matches_eager[boxes.Boxes.from_tensor[xyxy]]
-RuntimeError tests/test_inductor_conformance.py::test_inductor_matches_eager[boxes.Boxes.from_tensor[xywh]]
-RuntimeError tests/test_inductor_conformance.py::test_inductor_matches_eager[boxes.Boxes.from_tensor[xyxy_plus]]
-RuntimeError tests/test_inductor_conformance.py::test_inductor_matches_eager[boxes.Boxes.to_mask]
-RuntimeError tests/test_inductor_conformance.py::test_inductor_matches_eager[boxes.Boxes3D.from_tensor[xyzxyz]]
-RuntimeError tests/test_inductor_conformance.py::test_inductor_matches_eager[boxes.Boxes3D.from_tensor[xyzwhd]]
-RuntimeError tests/test_inductor_conformance.py::test_inductor_matches_eager[boxes.Boxes3D.to_mask]
-RuntimeError tests/test_inductor_conformance.py::test_inductor_matches_eager[geometry.camera.StereoCamera.reproject_disparity_to_3D]
-RuntimeError tests/test_inductor_conformance.py::test_inductor_matches_eager[geometry.camera.StereoCamera.Q]
-RuntimeError tests/test_inductor_conformance.py::test_inductor_matches_eager[geometry.liegroup.So2.from_matrix]
-RuntimeError tests/test_inductor_conformance.py::test_inductor_matches_eager[geometry.liegroup.Se2.from_matrix]
-RuntimeError tests/test_inductor_conformance.py::test_inductor_matches_eager[geometry.camera.StereoCamera.reproject_disparity_to_3D[baked-cams]]
-RuntimeError tests/test_inductor_conformance.py::test_inductor_matches_eager[enhance.JPEGCodecDifferentiable]
-RuntimeError tests/test_inductor_conformance.py::test_inductor_matches_eager[enhance.JPEGCodecDifferentiable[batch]]
-RuntimeError tests/test_inductor_conformance.py::test_inductor_matches_eager[enhance.JPEGCodecDifferentiable[custom_qt]]
# #6194: the survey recorded these as compiling without a graph break, but Dynamo cannot
# capture them in one graph on any measured torch (a loop over a data-dependent count, a host read of tensor values).
RuntimeError tests/test_inductor_conformance.py::test_inductor_matches_eager[bbox.nms]
diff --git a/tests/augmentation/test_augmentation.py b/tests/augmentation/test_augmentation.py
index 4b6d5b3f7..f8c84f145 100644
--- a/tests/augmentation/test_augmentation.py
+++ b/tests/augmentation/test_augmentation.py
@@ -88,7 +88,7 @@ from kornia.core.utils import _torch_inverse_cast
from kornia.geometry import create_meshgrid, transform_points
from testing.augmentation.datasets import DummyMPDataset
-from testing.base import BaseTester
+from testing.base import DYNAMO_UNAVAILABLE_REASON, BaseTester, dynamo_is_available
from testing.overwrite import default_with_one_parameter_changed
@@ -5561,6 +5561,25 @@ class TestResize:
compiled = torch.compile(aug, fullgraph=True)
torch.testing.assert_close(aug(img), compiled(img), rtol=1e-4, atol=1e-4)
+ @pytest.mark.skipif(not dynamo_is_available(), reason=DYNAMO_UNAVAILABLE_REASON)
+ @pytest.mark.parametrize(
+ "make",
+ [lambda: Resize(8), lambda: LongestMaxSize(8), lambda: SmallestMaxSize(8)],
+ ids=["Resize", "LongestMaxSize", "SmallestMaxSize"],
+ )
+ def test_int_size_traces_in_one_graph_like_eager_5037(self, make, device, dtype):
+ # An int size takes its output size from the input shape under any capture, not only under export (#5037):
+ # the sampled ``output_size`` tensor is a host read, which a fullgraph trace cannot make.
+ from torch._dynamo.testing import CompileCounter
+
+ img = torch.rand(2, 3, 10, 16, generator=torch.Generator().manual_seed(0)).to(device, dtype)
+ aug = make()
+ counter = CompileCounter()
+ torch._dynamo.reset()
+ traced = torch.compile(aug, backend=counter, fullgraph=True)
+ torch.testing.assert_close(traced(img), aug(img), rtol=0, atol=0)
+ assert counter.frame_count == 1
+
class TestSmallestMaxSize:
def test_smoke(self, device, dtype):
diff --git a/tests/enhance/test_jpeg.py b/tests/enhance/test_jpeg.py
index ab7f1030c..6af3bd89f 100644
--- a/tests/enhance/test_jpeg.py
+++ b/tests/enhance/test_jpeg.py
@@ -22,7 +22,7 @@ import torch
import kornia
-from testing.base import BaseTester
+from testing.base import DYNAMO_UNAVAILABLE_REASON, BaseTester, dynamo_is_available
class TestDiffJPEG(BaseTester):
@@ -1248,6 +1248,27 @@ class TestDiffJPEG(BaseTester):
assert img_jpeg is not None
assert img_jpeg.shape == img.shape
+ @pytest.mark.skipif(not dynamo_is_available(), reason=DYNAMO_UNAVAILABLE_REASON)
+ def test_quality_check_skipped_under_any_capture_5037(self, device, dtype) -> None:
+ # The [0, 100] check reads the quality on the host, which a fullgraph trace cannot do, so any capture skips
+ # it, not only export (#5037). Eager still raises on an out-of-range quality; a traced call does not.
+ from torch._dynamo.testing import CompileCounter
+
+ from kornia.core.exceptions import BaseError
+
+ codec = kornia.enhance.JPEGCodecDifferentiable()
+ img = torch.rand(2, 3, 16, 16, generator=torch.Generator().manual_seed(0)).to(device, dtype)
+ quality = torch.tensor([30.0, 90.0], device=device, dtype=dtype)
+ counter = CompileCounter()
+ torch._dynamo.reset()
+ traced = torch.compile(codec, backend=counter, fullgraph=True)
+ self.assert_close(traced(img, quality), codec(img, quality), atol=0.0, rtol=0.0)
+ assert counter.frame_count == 1
+ out_of_range = torch.tensor([30.0, 150.0], device=device, dtype=dtype)
+ with pytest.raises(BaseError, match="JPEG quality is out of range"):
+ codec(img, out_of_range)
+ assert traced(img, out_of_range).shape == img.shape
+
def test_module_float64_tables_on_cpu(self, device, dtype) -> None:
# The tables may stay float64 on the CPU while the image lives on a device without float64 (MPS): the codec
# converts them to the image device and its compute dtype in one step.
diff --git a/tests/geometry/camera/test_stereo.py b/tests/geometry/camera/test_stereo.py
index cfbd9557f..37c2d8eb7 100644
--- a/tests/geometry/camera/test_stereo.py
+++ b/tests/geometry/camera/test_stereo.py
@@ -21,7 +21,7 @@ import torch
from kornia.geometry.camera import StereoCamera
from kornia.geometry.camera.stereo import StereoException, reproject_disparity_to_3D
-from testing.base import BaseTester
+from testing.base import DYNAMO_UNAVAILABLE_REASON, BaseTester, dynamo_is_available
@pytest.fixture(params=[1, 2, 4])
@@ -524,6 +524,33 @@ class TestStereoCamera(BaseTester):
disparity = torch.full((1, 3, 5, 1), 10.0, device=device, dtype=dtype)
assert self._asymmetric_stereo(device, dtype).reproject_disparity_to_3D(disparity).abs().max().item() > 0.1
+ @pytest.mark.skipif(not dynamo_is_available(), reason=DYNAMO_UNAVAILABLE_REASON)
+ @pytest.mark.parametrize("entrypoint", ["Q", "reproject_disparity_to_3D"])
+ def test_rig_checks_skipped_under_any_capture_5037(self, entrypoint, device, dtype):
+ # The constructor checks the intrinsics and the baseline on the host, which a fullgraph trace cannot do, so
+ # any capture skips the checks, not only export (#5037). Eager still raises on a zero baseline; a traced call
+ # does not.
+ from torch._dynamo.testing import CompileCounter
+
+ rig = self._asymmetric_stereo(device, dtype)
+ left, right = rig.rectified_left_camera, rig.rectified_right_camera
+ disparity = torch.full((1, 3, 5, 1), 10.0, device=device, dtype=dtype)
+
+ def op(left: torch.Tensor, right: torch.Tensor) -> torch.Tensor:
+ cam = StereoCamera(left, right)
+ return cam.Q if entrypoint == "Q" else cam.reproject_disparity_to_3D(disparity)
+
+ counter = CompileCounter()
+ torch._dynamo.reset()
+ traced = torch.compile(op, backend=counter, fullgraph=True)
+ self.assert_close(traced(left, right), op(left, right), atol=0.0, rtol=0.0)
+ assert counter.frame_count == 1
+ no_baseline = right.clone()
+ no_baseline[..., 0, 3] = 0.0
+ with pytest.raises(StereoException, match="non-zero stereo baseline"):
+ op(left, no_baseline)
+ assert traced(left, no_baseline).shape == op(left, right).shape
+
def test_convention_stereo_rejects_a_four_by_four_pair_4270(self, device, dtype):
cam = self._asymmetric_stereo(device, dtype)
bottom = torch.tensor([[[0.0, 0.0, 0.0, 1.0]]], device=device, dtype=dtype)
diff --git a/tests/geometry/liegroup/test_se2.py b/tests/geometry/liegroup/test_se2.py
index 610cf498d..66dd12cc1 100644
--- a/tests/geometry/liegroup/test_se2.py
+++ b/tests/geometry/liegroup/test_se2.py
@@ -833,6 +833,29 @@ class TestSe2(BaseTester):
exported = torch.export.export(FromMatrix(), (matrix,)).module()
self.assert_close(exported(matrix), expected)
+ @pytest.mark.skipif(not dynamo_is_available(), reason=DYNAMO_UNAVAILABLE_REASON)
+ def test_convention_se2_from_matrix_omits_rotation_value_validation_under_any_capture_5037(self, device, dtype):
+ if dtype == torch.bfloat16:
+ pytest.skip("torch has no complex bfloat16 dtype, which So2 stores its rotation in")
+ # As under export, a fullgraph trace cannot read the rotation values, so any capture omits the check (#5037)
+ # and keeps m00 + i m10; a valid pose traces in one graph and matches eager.
+ from torch._dynamo.testing import CompileCounter
+
+ def from_matrix(matrix: torch.Tensor) -> torch.Tensor:
+ return Se2.from_matrix(matrix).matrix()
+
+ pose = Se2.exp(torch.tensor([[1.0, 2.0, 0.3]], device=device, dtype=dtype)).matrix().detach()
+ reflection = torch.eye(3, device=device, dtype=dtype)
+ reflection[1, 1] = -1.0
+ counter = CompileCounter()
+ torch._dynamo.reset()
+ traced = torch.compile(from_matrix, backend=counter, fullgraph=True)
+ self.assert_close(traced(pose), from_matrix(pose), atol=0.0, rtol=0.0)
+ assert counter.frame_count == 1
+ with pytest.raises(ValueError, match="Invalid SO2 rotation matrix"):
+ from_matrix(reflection[None])
+ self.assert_close(traced(reflection[None]), torch.eye(3, device=device, dtype=dtype)[None], atol=0.0, rtol=0.0)
+
def test_se2_translation_is_a_tensor_for_every_constructor_4931(self, device, dtype):
if dtype == torch.bfloat16:
pytest.skip("torch has no complex bfloat16 dtype, which So2 stores its rotation in")
diff --git a/tests/geometry/liegroup/test_so2.py b/tests/geometry/liegroup/test_so2.py
index bff54e1b1..e44464aa3 100644
--- a/tests/geometry/liegroup/test_so2.py
+++ b/tests/geometry/liegroup/test_so2.py
@@ -433,6 +433,29 @@ class TestSo2(BaseTester):
rotation = So2.exp(torch.tensor(0.3, device=device, dtype=dtype)).matrix().detach()
self.assert_close(So2.from_matrix(rotation).log(), torch.tensor(0.3, device=device, dtype=dtype))
+ @pytest.mark.skipif(not dynamo_is_available(), reason=DYNAMO_UNAVAILABLE_REASON)
+ def test_from_matrix_check_skipped_under_any_capture_5037(self, device, dtype):
+ if dtype == torch.bfloat16:
+ pytest.skip("torch has no complex bfloat16 dtype, which So2 stores its rotation in")
+ # from_matrix checks the rotation block on the host, which a fullgraph trace cannot do, so any capture skips
+ # the check, not only export (#5037), and reads the block as z = m00 + i m10. Eager still raises on a
+ # reflection; a traced call does not.
+ from torch._dynamo.testing import CompileCounter
+
+ def log(matrix: torch.Tensor) -> torch.Tensor:
+ return So2.from_matrix(matrix).log()
+
+ rotation = So2.exp(torch.tensor([0.3, -1.2], device=device, dtype=dtype)).matrix().detach()
+ reflection = torch.tensor([[1.0, 0.0], [0.0, -1.0]], device=device, dtype=dtype).expand(2, 2, 2)
+ counter = CompileCounter()
+ torch._dynamo.reset()
+ traced = torch.compile(log, backend=counter, fullgraph=True)
+ self.assert_close(traced(rotation), log(rotation), atol=0.0, rtol=0.0)
+ assert counter.frame_count == 1
+ with pytest.raises(ValueError, match="Invalid SO2 rotation matrix"):
+ log(reflection)
+ self.assert_close(traced(reflection), torch.zeros(2, device=device, dtype=dtype), atol=0.0, rtol=0.0)
+
def test_so2_column_angle_is_squeezed_4932(self, device, dtype):
if dtype == torch.bfloat16:
pytest.skip("torch has no complex bfloat16 dtype, which So2 stores its rotation in")
diff --git a/tests/geometry/test_bbox.py b/tests/geometry/test_bbox.py
index f5e76f5af..34394a1d5 100644
--- a/tests/geometry/test_bbox.py
+++ b/tests/geometry/test_bbox.py
@@ -40,7 +40,7 @@ from kornia.geometry.bbox import (
from kornia.geometry.boxes import Boxes3D
from kornia.geometry.transform.crop3d import crop_and_resize3d, crop_by_boxes3d
-from testing.base import BaseTester
+from testing.base import DYNAMO_UNAVAILABLE_REASON, BaseTester, dynamo_is_available
class TestBbox2D(BaseTester):
@@ -718,11 +718,44 @@ class TestBbox3D(BaseTester):
validate_bbox3d(unequal)
with pytest.raises(AssertionError, match="shape"):
validate_bbox3d(cuboid[0])
- monkeypatch.setattr(bbox_module, "is_exporting", lambda: True)
+ monkeypatch.setattr(bbox_module, "is_compiling", lambda: True)
assert validate_bbox3d(unequal) is True
with pytest.raises(AssertionError, match="shape"):
validate_bbox3d(cuboid[0])
+ @pytest.mark.skipif(not dynamo_is_available(), reason=DYNAMO_UNAVAILABLE_REASON)
+ @pytest.mark.parametrize(
+ "op",
+ [lambda boxes: torch.stack(infer_bbox_shape3d(boxes)), lambda boxes: bbox_to_mask3d(boxes, (4, 5, 6))],
+ ids=["infer_bbox_shape3d", "bbox_to_mask3d"],
+ )
+ def test_value_checks_skipped_under_any_capture_5037(self, op, device, dtype):
+ # validate_bbox3d checks the edge extents on the host, which a fullgraph trace cannot do, so any capture skips
+ # the check, not only export (#5037). Eager still raises on unequal edges; a traced call does not.
+ from torch._dynamo.testing import CompileCounter
+
+ cuboid = self._unit_cuboid(device, dtype)
+ unequal = cuboid.clone()
+ unequal[0, 1, 0] = 5.0
+ counter = CompileCounter()
+ torch._dynamo.reset()
+ traced = torch.compile(op, backend=counter, fullgraph=True)
+ self.assert_close(traced(cuboid), op(cuboid), atol=0.0, rtol=0.0)
+ assert counter.frame_count == 1
+ with pytest.raises(AssertionError, match="widths"):
+ op(unequal)
+ assert traced(unequal).shape == op(cuboid).shape
+
+ def test_validate_bbox3d_scripted_keeps_the_value_checks_5037(self, device, dtype):
+ # TorchScript cannot call is_compiling(); a scripted validate_bbox3d keeps the value checks, as eager does.
+ cuboid = self._unit_cuboid(device, dtype)
+ unequal = cuboid.clone()
+ unequal[0, 1, 0] = 5.0
+ scripted = torch.jit.script(validate_bbox3d)
+ assert scripted(cuboid) is True
+ with pytest.raises(torch.jit.Error, match="widths"):
+ scripted(unequal)
+
def test_convention_infer_bbox_shape3d_returns_depth_height_width_inclusive_3934(self, device, dtype):
# Convention pin (kornia#3934 tracks the inclusive arithmetic): the tuple order is
# (depths, heights, widths) and each extent is one larger than its coordinate span.
diff --git a/tests/geometry/test_boxes.py b/tests/geometry/test_boxes.py
index 801f724c6..32ef4fef2 100644
--- a/tests/geometry/test_boxes.py
+++ b/tests/geometry/test_boxes.py
@@ -27,7 +27,7 @@ from kornia.geometry import boxes as boxes_module
from kornia.geometry.bbox import bbox_to_mask, bbox_to_mask3d, infer_bbox_shape, infer_bbox_shape3d
from kornia.geometry.boxes import Boxes, Boxes3D, VideoBoxes
-from testing.base import BaseTester
+from testing.base import DYNAMO_UNAVAILABLE_REASON, BaseTester, dynamo_is_available
def _legacy_onnx_to_mask_pairs(
@@ -107,6 +107,47 @@ class TestBoxes2D(BaseTester):
self.assert_close(torch_optimizer(import_boxes, fullgraph=True)(vertices), import_boxes(vertices))
+ @pytest.mark.skipif(not dynamo_is_available(), reason=DYNAMO_UNAVAILABLE_REASON)
+ @pytest.mark.parametrize("mode", ["xyxy", "xyxy_plus", "xywh"])
+ def test_coordinate_import_checks_skipped_under_any_capture_5037(self, mode, device, dtype):
+ # The coordinate modes check finiteness and extents on the host, which a fullgraph trace cannot do, so any
+ # capture skips the check, not only export (#5037). Eager still raises on a non-finite coordinate; a traced
+ # call does not.
+ from torch._dynamo.testing import CompileCounter
+
+ def import_boxes(data: torch.Tensor) -> torch.Tensor:
+ return Boxes.from_tensor(data, mode=mode).data
+
+ valid = torch.tensor([[[1.0, 2.0, 6.0, 7.0], [0.0, 0.0, 3.0, 4.0]]], device=device, dtype=dtype)
+ invalid = valid.clone()
+ invalid[0, 1, 0] = float("nan")
+ counter = CompileCounter()
+ torch._dynamo.reset()
+ traced = torch.compile(import_boxes, backend=counter, fullgraph=True)
+ self.assert_close(traced(valid), import_boxes(valid), atol=0.0, rtol=0.0)
+ assert counter.frame_count == 1
+ with pytest.raises(ValueError, match="non-finite coordinates"):
+ import_boxes(invalid)
+ assert torch.isnan(traced(invalid)).any()
+
+ @pytest.mark.skipif(not dynamo_is_available(), reason=DYNAMO_UNAVAILABLE_REASON)
+ def test_to_mask_traces_the_vectorized_path_5037(self, device, dtype):
+ # The CPU loop slices with bounds read from the boxes, host reads that inductor cannot lower in a fullgraph
+ # trace; any capture takes the vectorized path, not only export (#5037), and it fills the same mask.
+ from torch._dynamo.testing import EagerAndRecordGraphs
+
+ def to_mask(data: torch.Tensor) -> torch.Tensor:
+ return Boxes(data, mode="vertices_plus").to_mask(9, 11)
+
+ xyxy = [[[1.0, 2.0, 6.0, 7.0], [-2.0, -1.0, 4.0, 3.0], [1.4, 1.6, 5.5, 4.4]]]
+ data = Boxes.from_tensor(torch.tensor(xyxy, device=device, dtype=dtype), mode="xyxy_plus").data
+ backend = EagerAndRecordGraphs()
+ torch._dynamo.reset()
+ traced = torch.compile(to_mask, backend=backend, fullgraph=True)
+ self.assert_close(traced(data), to_mask(data), atol=0.0, rtol=0.0)
+ assert len(backend.graphs) == 1
+ assert ".item()" not in backend.graphs[0].code
+
@pytest.mark.parametrize("container", ["Boxes", "Boxes3D"])
def test_convention_from_tensor_opt_out_preserves_non_finite_input_4238(self, container, device, dtype):
# kornia#4238 (2D) and kornia#4258 (3D): validate_boxes=False keeps a non-finite coordinate.
@@ -985,7 +1026,7 @@ class TestBoxes2D(BaseTester):
expected_mask = before.to_mask(6, 6)
expected_mask[invalid] = 0
self.assert_close(filtered.to_mask(6, 6), expected_mask, atol=0.0, rtol=0.0)
- monkeypatch.setattr(boxes_module, "is_exporting", lambda: True)
+ monkeypatch.setattr(boxes_module, "is_compiling", lambda: True)
self.assert_close(filtered.to_mask(6, 6), expected_mask, atol=0.0, rtol=0.0)
if not inplace:
self.assert_close(boxes.to_tensor("xyxy"), xyxy, atol=0.0, rtol=0.0)
@@ -1251,7 +1292,7 @@ class TestBoxes2D(BaseTester):
boxes = boxes.transform_boxes(transform.expand(3, -1, -1))
original_data = boxes.data.clone()
if export_path:
- monkeypatch.setattr(boxes_module, "is_exporting", lambda: True)
+ monkeypatch.setattr(boxes_module, "is_compiling", lambda: True)
mask = boxes.to_mask(6, 6)
expected = torch.zeros(3, 2, 6, 6, device=device, dtype=dtype)
expected[1:, 0, offset, offset] = 1.0
@@ -1262,8 +1303,8 @@ class TestBoxes2D(BaseTester):
@pytest.mark.parametrize("case", ["fractional", "outside", "negative", "rotated", "batched"])
def test_convention_to_mask_export_path_matches_loop_path(self, case, device, dtype, monkeypatch):
# Convention pin: the CPU/MPS loop path and the vectorized path taken on CUDA and under
- # export produce the same mask. The vectorized branch is selected by patching the module's
- # is_exporting predicate; on CUDA both calls already take it.
+ # graph capture produce the same mask. The vectorized branch is selected by patching the module's
+ # is_compiling predicate; on CUDA both calls already take it.
fractional = torch.tensor([[[1.4, 1.4], [3.6, 1.4], [3.6, 2.6], [1.4, 2.6]]], device=device, dtype=dtype)
data = {
"fractional": fractional,
@@ -1273,7 +1314,7 @@ class TestBoxes2D(BaseTester):
"batched": fractional.expand(2, 3, 4, 2).contiguous(),
}[case]
loop = Boxes(data).to_mask(5, 6)
- monkeypatch.setattr(boxes_module, "is_exporting", lambda: True)
+ monkeypatch.setattr(boxes_module, "is_compiling", lambda: True)
vectorized = Boxes(data).to_mask(5, 6)
assert loop.shape == vectorized.shape
self.assert_close(loop, vectorized, atol=0.0, rtol=0.0)
@@ -1287,14 +1328,14 @@ class TestBoxes2D(BaseTester):
if batched:
data = data.expand(2, 3, 4, 2).contiguous()
loop = Boxes(data).to_mask(*size)
- monkeypatch.setattr(boxes_module, "is_exporting", lambda: True)
+ monkeypatch.setattr(boxes_module, "is_compiling", lambda: True)
vectorized = Boxes(data).to_mask(*size)
assert loop.shape == vectorized.shape == (*data.shape[:-2], *size)
assert loop.dtype == vectorized.dtype == dtype
@pytest.mark.device_agnostic
def test_to_mask_legacy_onnx_export_reads_its_input_6164(self):
- # The legacy exporter traces outside is_exporting(). It used to trace the CPU loop and lose its in-place
+ # The legacy exporter traces outside is_compiling(). It used to trace the CPU loop and lose its in-place
# writes: a graph with no input that returned zeros for every box (#6164). The graph must read the boxes, so
# boxes other than the traced ones (overlapping, fractional, partly or wholly outside the image) give their
# own masks.
@@ -1433,6 +1474,31 @@ class TestBbox3D(BaseTester):
with pytest.raises(ValueError, match="non-finite coordinates"):
Boxes3D.from_tensor(invalid_source, mode=mode, validate_boxes=True)
+ @pytest.mark.skipif(not dynamo_is_available(), reason=DYNAMO_UNAVAILABLE_REASON)
+ @pytest.mark.parametrize("mode", ["xyzxyz", "xyzxyz_plus", "xyzwhd"])
+ def test_import_checks_skipped_under_any_capture_5037(self, mode, device, dtype):
+ # The import checks finiteness and extents on the host, which a fullgraph trace cannot do, so any capture
+ # skips the check, not only export (#5037). Eager still raises on a non-finite coordinate; a traced call
+ # does not.
+ from torch._dynamo.testing import CompileCounter
+
+ def import_boxes(data: torch.Tensor) -> torch.Tensor:
+ return Boxes3D.from_tensor(data, mode=mode).data
+
+ valid = torch.tensor(
+ [[[1.0, 2.0, 1.0, 5.0, 7.0, 4.0], [0.0, 0.0, 0.0, 3.0, 4.0, 2.0]]], device=device, dtype=dtype
+ )
+ invalid = valid.clone()
+ invalid[0, 1, 0] = float("nan")
+ counter = CompileCounter()
+ torch._dynamo.reset()
+ traced = torch.compile(import_boxes, backend=counter, fullgraph=True)
+ self.assert_close(traced(valid), import_boxes(valid), atol=0.0, rtol=0.0)
+ assert counter.frame_count == 1
+ with pytest.raises(ValueError, match="non-finite coordinates"):
+ import_boxes(invalid)
+ assert torch.isnan(traced(invalid)).any()
+
def test_smoke(self, device, dtype):
def _create_tensor_box():
# Sample two points of the 3d rect
@@ -2030,8 +2096,8 @@ class TestBbox3D(BaseTester):
@pytest.mark.parametrize("case", ["fractional", "outside", "negative", "batched"])
def test_convention_to_mask_export_path_matches_loop_path(self, case, device, dtype, monkeypatch):
- # Convention pin: the loop path and the grid-comparison path taken under export produce
- # the same mask. The export branch is selected by patching the module's is_exporting predicate.
+ # Convention pin: the loop path and the grid-comparison path taken under graph capture produce
+ # the same mask. The capture branch is selected by patching the module's is_compiling predicate.
fractional = self._fractional_cuboid(device, dtype)
data = {
"fractional": fractional,
@@ -2040,7 +2106,7 @@ class TestBbox3D(BaseTester):
"batched": fractional.expand(2, 2, 8, 3).contiguous(),
}[case]
loop = Boxes3D(data).to_mask(5, 5, 6)
- monkeypatch.setattr(boxes_module, "is_exporting", lambda: True)
+ monkeypatch.setattr(boxes_module, "is_compiling", lambda: True)
vectorized = Boxes3D(data).to_mask(5, 5, 6)
assert loop.shape == vectorized.shape
self.assert_close(loop, vectorized, atol=0.0, rtol=0.0)
@@ -2054,11 +2120,29 @@ class TestBbox3D(BaseTester):
if batched:
data = data.expand(2, 2, 8, 3).contiguous()
loop = Boxes3D(data).to_mask(*size)
- monkeypatch.setattr(boxes_module, "is_exporting", lambda: True)
+ monkeypatch.setattr(boxes_module, "is_compiling", lambda: True)
vectorized = Boxes3D(data).to_mask(*size)
assert loop.shape == vectorized.shape == (*data.shape[:-2], *size)
assert loop.dtype == vectorized.dtype == dtype
+ @pytest.mark.skipif(not dynamo_is_available(), reason=DYNAMO_UNAVAILABLE_REASON)
+ def test_to_mask_traces_the_grid_comparison_path_5037(self, device, dtype):
+ # The loop slices with bounds read from the boxes, host reads that inductor cannot lower in a fullgraph trace;
+ # any capture compares a coordinate grid against the bounds instead, not only export (#5037), and it fills the
+ # same mask.
+ from torch._dynamo.testing import EagerAndRecordGraphs
+
+ def to_mask(data: torch.Tensor) -> torch.Tensor:
+ return Boxes3D(data, mode="xyzxyz_plus").to_mask(5, 5, 6)
+
+ data = torch.cat([self._fractional_cuboid(device, dtype), self._fractional_cuboid(device, dtype) - 1.0])
+ backend = EagerAndRecordGraphs()
+ torch._dynamo.reset()
+ traced = torch.compile(to_mask, backend=backend, fullgraph=True)
+ self.assert_close(traced(data), to_mask(data), atol=0.0, rtol=0.0)
+ assert len(backend.graphs) == 1
+ assert ".item()" not in backend.graphs[0].code
+
@pytest.mark.device_agnostic
def test_to_mask_legacy_onnx_export_reads_its_input_6164(self):
# As for Boxes.to_mask: the legacy exporter traced the loop and exported a constant all-zero mask (#6164).