Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(geometry): build the meshgrid pixel ramp with arange in eager too (#4036)

Logan Chu4b2cbed26b14
diff --git a/kornia/geometry/grid.py b/kornia/geometry/grid.py
index d64fed5d2..454308acf 100644
--- a/kornia/geometry/grid.py
+++ b/kornia/geometry/grid.py
@@ -67,15 +67,23 @@ def create_meshgrid(
[1., 1.]]]])
"""
- if not torch.jit.is_scripting() and is_compiling():
- # ``linspace`` specializes symbolic ``steps`` under export; ``arange`` retains the
- # dynamic output length. Match ``linspace``'s default floating dtype when none is given.
- arange_dtype = dtype if dtype is not None else torch.get_default_dtype()
- xs = torch.arange(width, device=device, dtype=arange_dtype)
- ys = torch.arange(height, device=device, dtype=arange_dtype)
- else:
- xs = torch.linspace(0, width - 1, width, device=device, dtype=dtype)
- ys = torch.linspace(0, height - 1, height, device=device, dtype=dtype)
+ # Build the pixel ramp with ``arange`` in both eager and capture. ``linspace`` rounds its
+ # endpoint into the coordinate dtype first and fills the upper half of the ramp backwards from
+ # that rounded value, so its step is exactly 1 only while ``size - 1`` is an exactly
+ # representable integer -- ``size <= 2 ** p + 1`` for a ``p``-bit significand. Past that it
+ # lands one ulp off the correctly rounded column index. The bound is 257 in bfloat16 and 2049
+ # in float16, and 2 ** 24 + 1 / 2 ** 53 + 1 in float32/float64, so no non-half grid can move.
+ # Inductor lowers the same call to a per-index computation that rounds correctly, so eager and
+ # compiled grids disagreed by up to one ulp of the width. ``arange`` also retains the dynamic
+ # output length under export, where ``linspace`` specializes symbolic ``steps``. Match
+ # ``linspace``'s default floating dtype when none is given -- read off an empty tensor rather
+ # than via ``torch.get_default_dtype()``, for which TorchScript has no builtin. The empty
+ # tensor takes ``device`` so that the read depends on an argument: a no-input factory call is
+ # constant-folded by TorchScript's optimizing executor after the first run, which would freeze
+ # the ramp at whatever the default dtype happened to be on that call.
+ ramp_dtype = dtype if dtype is not None else torch.empty(0, device=device).dtype
+ xs = torch.arange(width, device=device, dtype=ramp_dtype)
+ ys = torch.arange(height, device=device, dtype=ramp_dtype)
# Fix TracerWarning
# Note: keeping this formula inline avoids the extra tensors and shape checks incurred by
# normalize_pixel_coordinates. The two paths use the same singleton-centre policy.
@@ -146,15 +154,13 @@ def create_meshgrid3d(
grid tensor with shape :math:`(1, D, H, W, 3)`.
"""
- if not torch.jit.is_scripting() and is_compiling():
- arange_dtype = dtype if dtype is not None else torch.get_default_dtype()
- xs = torch.arange(width, device=device, dtype=arange_dtype)
- ys = torch.arange(height, device=device, dtype=arange_dtype)
- zs = torch.arange(depth, device=device, dtype=arange_dtype)
- else:
- xs = torch.linspace(0, width - 1, width, device=device, dtype=dtype)
- ys = torch.linspace(0, height - 1, height, device=device, dtype=dtype)
- zs = torch.linspace(0, depth - 1, depth, device=device, dtype=dtype)
+ # See ``create_meshgrid``: ``arange`` keeps eager and captured pixel ramps identical at
+ # float16/bfloat16, keeps the output length dynamic under export, and reads the default dtype
+ # off a ``device``-bearing empty tensor so TorchScript cannot constant-fold the read.
+ ramp_dtype = dtype if dtype is not None else torch.empty(0, device=device).dtype
+ xs = torch.arange(width, device=device, dtype=ramp_dtype)
+ ys = torch.arange(height, device=device, dtype=ramp_dtype)
+ zs = torch.arange(depth, device=device, dtype=ramp_dtype)
# Fix TracerWarning
if normalized_coordinates:
if not torch.jit.is_scripting() and (torch.jit.is_tracing() or is_compiling()):
diff --git a/tests/geometry/test_grid.py b/tests/geometry/test_grid.py
index a560c9f6e..13bd745f8 100644
--- a/tests/geometry/test_grid.py
+++ b/tests/geometry/test_grid.py
@@ -225,6 +225,69 @@ def test_pixel_meshgrid_default_dtype_matches_compile(is_3d, default_dtype):
assert_close(actual, expected, atol=0.0, rtol=0.0)
[email protected]("is_3d", [False, True], ids=["2d", "3d"])
+def test_pixel_meshgrid_scripted_ramp_follows_the_runtime_default_dtype(is_3d):
+ """A scripted grid with no explicit dtype must track ``torch.get_default_dtype()`` per call.
+
+ The default dtype is read off an empty tensor because TorchScript has no
+ ``aten::get_default_dtype``. A factory call with no graph input is constant-folded by
+ TorchScript's optimizing executor once profiling completes, which froze the ramp at whatever
+ the default happened to be on the first call -- ``linspace(0, size - 1, size)`` never folded
+ because it consumed ``size``. Passing ``device`` restores that dependency. The first call here
+ is deliberately made under a *different* default from the assertion, since the freeze only
+ shows from the second call onwards. No "compile"/"dynamo" in the name on purpose: this is
+ plain TorchScript and must run in the ordinary test jobs, which deselect those by name.
+ """
+ op = kornia.geometry.create_meshgrid3d if is_3d else kornia.geometry.create_meshgrid
+ args = (2, 3, 4) if is_3d else (3, 4)
+ scripted = torch.jit.script(op)
+
+ previous_dtype = torch.get_default_dtype()
+ try:
+ torch.set_default_dtype(torch.float32)
+ assert scripted(*args).dtype == torch.float32
+
+ torch.set_default_dtype(torch.float64)
+ assert scripted(*args).dtype == torch.float64 == op(*args).dtype
+ assert scripted(*args).dtype == torch.float64, "the scripted ramp froze its default dtype"
+ finally:
+ torch.set_default_dtype(previous_dtype)
+
+
[email protected]("grid_dtype", [torch.float16, torch.bfloat16])
[email protected]("is_3d", [False, True], ids=["2d", "3d"])
+def test_pixel_meshgrid_half_dtype_matches_compile(is_3d, grid_dtype):
+ """A half-precision pixel ramp must not change when the grid is built under ``torch.compile``.
+
+ ``linspace`` rounds its endpoint into the coordinate dtype and fills the upper half of the ramp
+ backwards from that rounded value, so it lands one ulp off the correctly rounded column index --
+ ``linspace(0, 299, 300)`` gives 258 at index 257 where bfloat16 holds 257 as 256. Inductor lowers
+ the same call to a per-index computation that rounds correctly, so the eager and compiled grids
+ disagreed by up to one ulp of the width. The sizes here are the first at which the two diverge:
+ 258 for bfloat16 and 2050 for float16.
+ """
+
+ class MeshGrid(torch.nn.Module):
+ def forward(self, image):
+ if is_3d:
+ return kornia.geometry.create_meshgrid3d(
+ image.shape[-3], image.shape[-2], image.shape[-1], False, device=image.device, dtype=image.dtype
+ )
+ return kornia.geometry.create_meshgrid(
+ image.shape[-2], image.shape[-1], False, device=image.device, dtype=image.dtype
+ )
+
+ size = 258 if grid_dtype == torch.bfloat16 else 2050
+ shape = (1, 1, 2, 2, size) if is_3d else (1, 1, 2, size)
+ image = torch.zeros(*shape, dtype=grid_dtype)
+
+ expected = MeshGrid()(image)
+ actual = torch.compile(MeshGrid(), fullgraph=True)(image)
+
+ assert actual.dtype == expected.dtype == grid_dtype
+ assert_close(actual, expected, atol=0.0, rtol=0.0)
+
+
def test_create_meshgrid3d(device, dtype):
depth, height, width = 5, 4, 6
normalized_coordinates = False