Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix: make the CUDA float32 test suite pass (scripted empty-batch dtype, xterm print, test contracts) (#6269)

Dmytro Mishkin4ad4ce887798
diff --git a/changelog.d/6269.fixed.md b/changelog.d/6269.fixed.md
new file mode 100644
index 000000000..26d9db43d
--- /dev/null
+++ b/changelog.d/6269.fixed.md
@@ -0,0 +1,13 @@
+`unproject_points_z1` and `compute_correspond_epilines`, compiled with `torch.jit.script` and run on CUDA, returned
+an empty `int32` tensor for an empty batch (no points) once the scripted function had run on non-empty inputs:
+TorchScript's CUDA fuser miscompiles a concatenation of a fused product when every input is empty. Both now avoid
+that group: `unproject_points_z1` concatenates the depth expanded to the product's shape, and
+`compute_correspond_epilines` scales `F x` directly instead of concatenating the scaled components. Eager results are
+bitwise unchanged. `unproject_points_z1` also accepts a depth whose leading dimensions broadcast against the points,
+where it used to raise from `torch.cat`, and raises `ShapeError` for a depth whose trailing size is not 1, where a
+`(..., 2)` depth used to return a meaningless `(..., 4)` result.
+
+`kornia.image.image_to_string` and `print_image` match an integer image's pixels at their exact 0–255 values on every
+device, as documented. The image was divided by 255 and multiplied back, which is exact on CPU but moved 126 of the 256
+`uint8` levels off their integer on CUDA, where a division by a scalar is a multiplication by its reciprocal. A CUDA
+image could therefore print some pixels in a different colour than its CPU copy. CPU output is unchanged.
diff --git a/kornia/geometry/camera/projection_z1.py b/kornia/geometry/camera/projection_z1.py
index 7e22ca977..837df61bb 100644
--- a/kornia/geometry/camera/projection_z1.py
+++ b/kornia/geometry/camera/projection_z1.py
@@ -82,12 +82,14 @@ def unproject_points_z1(
- ``extension`` is the camera-frame ``z`` of the unprojected point: the canonical point is multiplied
by it and it becomes the third component.
:meth:`~kornia.sensors.camera.projection_model.Z1Projection.unproject` names the same argument
- ``depth``. Both ``(...,)`` and ``(..., 1)`` extensions are accepted.
+ ``depth``. Both ``(...,)`` and ``(..., 1)`` extensions are accepted, and their leading dimensions
+ broadcast against the points'. One depth scales both coordinates: any other trailing size raises
+ ``ShapeError``.
Args:
points_in_cam_canonical: torch.Tensor representing the points to unproject with shape (..., 2).
extension: torch.Tensor representing the extension (depth) of the points to unproject with shape
- (..., 1) or (...), matching the points' leading dimensions. Defaults to unit depth.
+ (..., 1) or (...), broadcastable against the points' leading dimensions. Defaults to unit depth.
Returns:
torch.Tensor representing the unprojected points with shape (..., 3).
@@ -102,15 +104,16 @@ def unproject_points_z1(
KORNIA_CHECK_SHAPE(points_in_cam_canonical, ["*", "2"])
if extension is None:
- extension = torch.ones(
- points_in_cam_canonical.shape[:-1] + (1,),
- device=points_in_cam_canonical.device,
- dtype=points_in_cam_canonical.dtype,
- ) # (..., 1)
- elif extension.ndim == points_in_cam_canonical.ndim - 1:
+ # a ones column, not ``F.pad(..., value=1.0)``: see ``convert_points_to_homogeneous`` for MPS
+ return torch.cat([points_in_cam_canonical, torch.ones_like(points_in_cam_canonical[..., :1])], dim=-1)
+ if extension.ndim == points_in_cam_canonical.ndim - 1:
extension = extension[..., None] # (..., 1)
-
- return torch.cat([points_in_cam_canonical * extension, extension], dim=-1)
+ KORNIA_CHECK_SHAPE(extension, ["*", "1"])
+ xy = points_in_cam_canonical * extension
+ # The depth is expanded to the product's leading shape, so a broadcast depth concatenates. That also keeps
+ # TorchScript's CUDA fuser from compiling ``cat([points * w, w])`` into a group that returns an int32 tensor for
+ # an empty batch once it has specialized on non-empty calls.
+ return torch.cat([xy, extension.expand(xy[..., :1].shape)], dim=-1)
def dx_project_points_z1(points_in_camera: torch.Tensor) -> torch.Tensor:
diff --git a/kornia/geometry/epipolar/fundamental.py b/kornia/geometry/epipolar/fundamental.py
index 2b8ba13e7..18becc538 100644
--- a/kornia/geometry/epipolar/fundamental.py
+++ b/kornia/geometry/epipolar/fundamental.py
@@ -660,13 +660,16 @@ def compute_correspond_epilines(points: torch.Tensor, F_mat: torch.Tensor) -> to
KORNIA_CHECK_SHAPE(F_mat, ["*", "3", "3"])
# project points and retrieve lines components
points_h = torch.transpose(points_h, dim0=-2, dim1=-1)
- a, b, c = torch.chunk(F_mat @ points_h, dim=-2, chunks=3)
+ lines = F_mat @ points_h # *x3xN
+ a, b, _ = torch.chunk(lines, dim=-2, chunks=3)
# compute normal and compose equation line
nu: torch.Tensor = a * a + b * b
nu = torch.where(nu > 0.0, 1.0 / torch.sqrt(nu), torch.ones_like(nu))
- line = torch.cat([a * nu, b * nu, c * nu], dim=-2) # *x3xN
+ # The same values as concatenating ``a * nu``, ``b * nu`` and ``c * nu``, without the concatenation that
+ # TorchScript's CUDA fuser compiles into a group returning an int32 tensor for N = 0 after non-empty calls.
+ line = lines * nu # *x3xN
return torch.transpose(line, dim0=-2, dim1=-1) # *xNx3
diff --git a/kornia/image/image_print.py b/kornia/image/image_print.py
index 5aea67099..7d3373d6b 100644
--- a/kornia/image/image_print.py
+++ b/kornia/image/image_print.py
@@ -398,15 +398,21 @@ def image_to_string(image: torch.Tensor, max_width: int = 256) -> str:
KORNIA_CHECK_IS_IMAGE(image, None, raises=True)
KORNIA_CHECK_SHAPE(image, ["C", "H", "W"])
- if image.dtype not in [torch.bfloat16, float16, float32, float64]:
- image = image / 255.0
+ # An integer image is already on the 0-255 scale and converts to float32 exactly. Dividing it by 255 and
+ # multiplying back is not exact everywhere: CUDA divides by a scalar as a multiplication by its reciprocal, which
+ # moved 126 of the 256 uint8 values off their integer and could flip a pixel's nearest colour.
+ integer = image.dtype not in [torch.bfloat16, float16, float32, float64]
+ if integer:
+ image = image.to(float32)
if image.shape[-1] > max_width:
new_h = max(1, image.size(-2) * max_width // image.size(-1))
image = kornia.geometry.resize(image, (new_h, max_width))
# the 0-255 value, unrounded: a float pixel is matched at its own value (an integer input stays exact)
- image = (image * 255).clamp(0, 255)
+ if not integer:
+ image = image * 255
+ image = image.clamp(0, 255)
if image.shape[0] == 1:
# a grey value is the same colour in each of the three terminal components
diff --git a/testing/base.py b/testing/base.py
index ffbc92227..3b5c67e50 100644
--- a/testing/base.py
+++ b/testing/base.py
@@ -19,6 +19,7 @@ from __future__ import annotations
import math
import sys
+import types
from contextlib import contextmanager
from functools import cache
from typing import Any, Callable, Iterator, Optional, Sequence, Union
@@ -77,6 +78,22 @@ def dynamic_export_is_available() -> bool:
return dynamo_is_available() and hasattr(getattr(torch, "export", None), "Dim")
+def script_uncached(fn: Callable[..., Any]) -> torch.jit.ScriptFunction:
+ """``torch.jit.script`` a fresh copy of ``fn``, with no profiling history from earlier calls.
+
+ ``torch.jit.script`` caches one compiled function per Python function, and the profiling executor specializes
+ and fuses it on the shapes of the calls it has seen, so a test that scripts a shared function inherits whatever
+ other tests ran before it. A copy with the same code object, globals and annotations compiles to the same
+ graph but starts its own history, which makes a test of a call sequence deterministic.
+ """
+ copy = types.FunctionType(fn.__code__, fn.__globals__, fn.__name__, fn.__defaults__, fn.__closure__)
+ copy.__annotations__ = dict(fn.__annotations__)
+ copy.__kwdefaults__ = fn.__kwdefaults__
+ copy.__module__ = fn.__module__
+ copy.__qualname__ = fn.__qualname__
+ return torch.jit.script(copy)
+
+
# {dtype: (rtol, atol)}
_DTYPE_PRECISIONS = {
torch.bfloat16: (7.8e-3, 7.8e-3),
diff --git a/tests/feature/test_loftr.py b/tests/feature/test_loftr.py
index 57411f257..3df59caa0 100644
--- a/tests/feature/test_loftr.py
+++ b/tests/feature/test_loftr.py
@@ -715,6 +715,16 @@ class TestCoarseMatching(BaseTester):
assert torch.equal(out["mkpts0_c"], expected) # products of small integers and 1.3671875: exact in float32
+def _autocast_softmax_dtype(device: torch.device) -> torch.dtype:
+ """The dtype ``F.softmax`` returns for a float16 input under float16 autocast on ``device``.
+
+ The coarse confidence is a product of softmaxes, so its dtype follows the device's autocast policy: CPU autocast
+ keeps float16, while CUDA autocast runs softmax in float32 (it is on CUDA's float32 list) and returns float32.
+ """
+ with torch.autocast(device.type, dtype=torch.float16):
+ return F.softmax(torch.zeros(1, device=device, dtype=torch.float16), 0).dtype
+
+
class TestCoarseMatchingSelection(BaseTester):
"""The row max / column max selection and the dual softmax against their reference formulations."""
@@ -853,7 +863,7 @@ class TestCoarseMatchingSelection(BaseTester):
data = {"hw0_c": (256, 256), "hw1_c": (1, 1), "stride_c": 8}
with torch.autocast(device.type, dtype=torch.float16):
cm(feat0, feat1, data)
- expected = torch.full((1, 65536, 1), 1 / 65536, device=device, dtype=torch.float16)
+ expected = torch.full((1, 65536, 1), 1 / 65536, device=device, dtype=_autocast_softmax_dtype(device))
self.assert_close(data["conf_matrix"], expected, rtol=0.0, atol=0.0)
def test_temperature_scaling_autocast(self, device):
@@ -865,7 +875,8 @@ class TestCoarseMatchingSelection(BaseTester):
data = {"hw0_c": (1, 1), "hw1_c": (1, 1), "stride_c": 8}
with torch.autocast(device.type, dtype=torch.float16):
cm(feat0, feat1, data)
- self.assert_close(data["conf_matrix"], torch.ones(1, 1, 1, device=device, dtype=torch.float16))
+ expected = torch.ones(1, 1, 1, device=device, dtype=_autocast_softmax_dtype(device))
+ self.assert_close(data["conf_matrix"], expected)
for grad in torch.autograd.grad(data["conf_matrix"].sum(), (feat0, feat1)):
self.assert_close(grad, torch.zeros_like(grad), rtol=0.0, atol=0.0)
diff --git a/tests/feature/test_sift_pyramid.py b/tests/feature/test_sift_pyramid.py
index c29cc1026..b7d8fd071 100644
--- a/tests/feature/test_sift_pyramid.py
+++ b/tests/feature/test_sift_pyramid.py
@@ -288,7 +288,14 @@ class TestSIFTDescriptorFromPyramid(BaseTester):
image = torch.rand(1, 1, 8, 8, device=device, dtype=torch.float64)
lafs = torch.tensor([[[[2.0, 0.0, 3.0], [0.0, 2.0, 3.0]]]], device=device, dtype=torch.float64)
feature = SIFTDescriptorFromPyramid(spatial_bin_size=3).to(device, torch.float64)
- self.gradcheck(lambda image: feature.orient_and_describe(image, lafs, upright=upright)[1], (image,))
+ # On CUDA the image gradient of the patch sampling comes from grid_sampler_2d_backward_cuda, which
+ # accumulates with atomicAdd (no deterministic implementation; a gather-based sampler would backpropagate
+ # through an equally atomic scatter_add). Repeated backward passes differ by at most ~1.3e-15 here, a few
+ # float64 ulps, so the reentrancy check allows 1e-12; the CPU backward is deterministic and stays exact.
+ nondet_tol = 1e-12 if device.type == "cuda" else 0.0
+ self.gradcheck(
+ lambda image: feature.orient_and_describe(image, lafs, upright=upright)[1], (image,), nondet_tol=nondet_tol
+ )
@pytest.mark.parametrize("inference", [False, True])
def test_dynamo(self, device, dtype, torch_optimizer, inference):
diff --git a/tests/filters/test_otsu_thresholding.py b/tests/filters/test_otsu_thresholding.py
index 22e8f2100..433740b60 100644
--- a/tests/filters/test_otsu_thresholding.py
+++ b/tests/filters/test_otsu_thresholding.py
@@ -635,12 +635,15 @@ class TestOtsuThresholdDifferentiable(BaseTester):
# Compare against the independent documented formula on the same quantized pixels in ordinary units.
# The derivative of s * f(x / s) is f'(x / s), so a finite scale must leave this gradient unchanged.
work_dtype = torch.float64 if dtype == torch.float64 else torch.float32
- normalized = (x.detach().to(work_dtype) / scale).requires_grad_(True)
+ # Divide by a tensor: CUDA divides a tensor by a Python scalar as a multiplication by its reciprocal, and the
+ # reciprocal of a subnormal scale overflows to inf, which turns the reference into inf and NaN (0 * inf).
+ work_scale = torch.tensor(scale, device=device, dtype=work_dtype)
+ normalized = (x.detach().to(work_dtype) / work_scale).requires_grad_(True)
(expected_grad,) = torch.autograd.grad(_documented_soft_threshold(normalized, 256), normalized)
self.assert_close(grad, expected_grad.to(dtype))
expected = otsu_threshold(normalized.detach(), slow_and_differentiable=True)[1]
self.assert_close(
- threshold.detach().to(work_dtype) / scale,
+ threshold.detach().to(work_dtype) / work_scale,
expected,
rtol=max(8 * limits.eps, 1e-11),
# Subnormal thresholds round in units of the smallest subnormal, rather than relative to their value.
diff --git a/tests/geometry/camera/test_projections.py b/tests/geometry/camera/test_projections.py
index 21eadebe3..30257bf1d 100644
--- a/tests/geometry/camera/test_projections.py
+++ b/tests/geometry/camera/test_projections.py
@@ -26,7 +26,7 @@ from kornia.geometry.camera.projection_orthographic import (
)
from kornia.geometry.camera.projection_z1 import dx_project_points_z1, project_points_z1, unproject_points_z1
-from testing.base import BaseTester
+from testing.base import BaseTester, script_uncached
class TestProjectionZ1(BaseTester):
@@ -113,6 +113,31 @@ class TestProjectionZ1(BaseTester):
self.assert_close(project_points_z1(actual), points)
self.assert_close(torch.jit.script(unproject_points_z1)(points, depth), expected)
+ @pytest.mark.parametrize("depth_shape", [(3,), (2, 3, 3)])
+ def test_unproject_rejects_a_depth_per_component(self, device, dtype, depth_shape):
+ from kornia.core.exceptions import ShapeError
+
+ # a depth whose trailing dimension is 3 would broadcast against (u, v, 1) and scale each component separately
+ points = torch.ones(2, 3, 2, device=device, dtype=dtype)
+ depth = torch.full(depth_shape, 2.0, device=device, dtype=dtype)
+ with pytest.raises(ShapeError):
+ unproject_points_z1(points, depth)
+
+ @pytest.mark.parametrize("depth_form", ["none", "flat", "column"])
+ def test_unproject_scripted_empty_after_nonempty_keeps_dtype(self, device, dtype, depth_form):
+ # TorchScript's CUDA fuser used to compile ``cat([points * depth, depth])`` into a group that, once it had
+ # specialized on non-empty calls, returned an int32 tensor for an empty batch.
+ scripted = script_uncached(unproject_points_z1)
+ for batch in (2, 2, 2, 0, 3, 0, 1, 0):
+ points = torch.rand(batch, 2, device=device, dtype=dtype)
+ depth = None
+ if depth_form != "none":
+ depth = torch.rand((batch, 1) if depth_form == "column" else (batch,), device=device, dtype=dtype)
+ actual = scripted(points, depth)
+ assert actual.dtype == dtype
+ assert actual.shape == (batch, 3)
+ self.assert_close(actual, unproject_points_z1(points, depth))
+
@pytest.mark.parametrize("column_depth", [False, True])
def test_unproject_batched_depth_gradcheck(self, device, column_depth):
points = torch.tensor([[1.0, 2.0], [3.0, 4.0]], device=device, dtype=torch.float64)
diff --git a/tests/geometry/epipolar/test_fundamental.py b/tests/geometry/epipolar/test_fundamental.py
index b995a76d6..45ff99517 100644
--- a/tests/geometry/epipolar/test_fundamental.py
+++ b/tests/geometry/epipolar/test_fundamental.py
@@ -34,7 +34,7 @@ from kornia.geometry.epipolar.fundamental import (
)
from kornia.geometry.solvers.homogeneous import _null_space_lu
-from testing.base import DYNAMO_UNAVAILABLE_REASON, BaseTester, dynamo_is_available
+from testing.base import DYNAMO_UNAVAILABLE_REASON, BaseTester, dynamo_is_available, script_uncached
from testing.geometry.create import create_random_fundamental_matrix, generate_two_view_random_scene
from testing.two_view import two_view_scene
@@ -428,6 +428,20 @@ class TestFundamentalAutocast(BaseTester):
class TestComputeCorrespondEpilines(BaseTester):
+ def test_scripted_empty_after_nonempty_keeps_dtype(self, device, dtype):
+ # TorchScript's CUDA fuser used to compile ``cat([a * nu, b * nu, c * nu])`` into a group that, once it had
+ # specialized on non-empty calls, returned an int32 tensor for N = 0.
+ if device.type == "cuda" and dtype == torch.bfloat16:
+ pytest.skip("TorchScript's CUDA fuser fails to compile the bfloat16 group for a * a + b * b (NVRTC)")
+ scripted = script_uncached(epi.compute_correspond_epilines)
+ F_mat = torch.rand(2, 3, 3, device=device, dtype=dtype)
+ for num_points in (5, 5, 5, 0, 5, 0, 7, 0):
+ points = torch.rand(2, num_points, 2, device=device, dtype=dtype)
+ lines = scripted(points, F_mat)
+ assert lines.dtype == dtype
+ assert lines.shape == (2, num_points, 3)
+ self.assert_close(lines, epi.compute_correspond_epilines(points, F_mat))
+
def test_smoke(self, device, dtype):
point = torch.rand(1, 1, 2, device=device, dtype=dtype)
F_mat = torch.rand(1, 3, 3, device=device, dtype=dtype)
diff --git a/tests/geometry/transform/test_crop2d.py b/tests/geometry/transform/test_crop2d.py
index 4ea687019..4a2b179f8 100644
--- a/tests/geometry/transform/test_crop2d.py
+++ b/tests/geometry/transform/test_crop2d.py
@@ -21,7 +21,7 @@ from torch.utils._python_dispatch import TorchDispatchMode
import kornia
-from testing.base import BaseTester, supports_bilinear_2d_grid_sample
+from testing.base import BaseTester, deterministic_algorithms_on_cuda, supports_bilinear_2d_grid_sample
class TestCropAndResize(BaseTester):
@@ -623,8 +623,6 @@ class TestCropByIndices(BaseTester):
dtype=torch.int64,
)
crop = kornia.geometry.transform.crop_by_indices
- out = crop(img, src_box, size=size, shape_compensation=shape_compensation)
- weights = torch.arange(1, out.numel() + 1, device=device, dtype=dtype).reshape(out.shape)
full_output_copies = []
class OutputCopies(TorchDispatchMode):
@@ -634,17 +632,25 @@ class TestCropByIndices(BaseTester):
full_output_copies.append(func)
return result
- # Writing each row into a preallocated output made backward copy the whole output gradient once per row.
- with OutputCopies():
- (gradient,) = torch.autograd.grad(out, img, weights)
- assert not full_output_copies
- # A single image takes the batch-slicing path, so each row is checked against it.
- for i in range(batch):
- row = img[i : i + 1].detach().requires_grad_()
- row_out = crop(row, src_box[i : i + 1], size=size, shape_compensation=shape_compensation)
- (row_gradient,) = torch.autograd.grad(row_out, row, weights[i : i + 1])
- self.assert_close(out[i : i + 1], row_out, rtol=0, atol=0)
- self.assert_close(gradient[i : i + 1], row_gradient, rtol=0, atol=0)
+ # On CUDA the bilinear resize's backward (``upsample_bilinear2d_backward``) accumulates with atomics in no
+ # fixed order: the batched gradient took 4-6 distinct values over 200 identical backward passes, differing
+ # from a row's in the last bit. Deterministic algorithms give every pass one order, and the batched and
+ # per-row results then agree bit for bit on CUDA, as they do on CPU. The mode also selects the forward
+ # kernel, so both sides are computed inside it.
+ with deterministic_algorithms_on_cuda(device):
+ out = crop(img, src_box, size=size, shape_compensation=shape_compensation)
+ weights = torch.arange(1, out.numel() + 1, device=device, dtype=dtype).reshape(out.shape)
+ # Writing each row into a preallocated output made backward copy the whole output gradient once per row.
+ with OutputCopies():
+ (gradient,) = torch.autograd.grad(out, img, weights)
+ assert not full_output_copies
+ # A single image takes the batch-slicing path, so each row is checked against it.
+ for i in range(batch):
+ row = img[i : i + 1].detach().requires_grad_()
+ row_out = crop(row, src_box[i : i + 1], size=size, shape_compensation=shape_compensation)
+ (row_gradient,) = torch.autograd.grad(row_out, row, weights[i : i + 1])
+ self.assert_close(out[i : i + 1], row_out, rtol=0, atol=0)
+ self.assert_close(gradient[i : i + 1], row_gradient, rtol=0, atol=0)
def test_crop_by_indices_no_resizing(self, device, dtype):
inp = torch.tensor([[[[1.0, 2.0, 3.0], [4.0, 5.0, 6.0], [7, 8, 9]]]], device=device, dtype=dtype) # 1x3x3
diff --git a/tests/image/test_print.py b/tests/image/test_print.py
index 2ae35376f..2b448a7cc 100644
--- a/tests/image/test_print.py
+++ b/tests/image/test_print.py
@@ -143,6 +143,16 @@ class TestNearestXterm:
assert out == image_to_string(image)
assert out.count("48;5;16m") < 20 # not every pixel black
+ def test_every_uint8_level_prints_like_its_cpu_copy(self, device):
+ # An integer image is matched at its exact 0-255 value on every device. Dividing by 255 and multiplying back
+ # moved 126 of the 256 levels off their integer on CUDA (a scalar division is a reciprocal multiplication
+ # there), so pixels at a colour boundary printed differently from the CPU copy.
+ levels = torch.arange(256, dtype=torch.uint8).reshape(16, 16)
+ image = torch.stack([levels, levels.flip(0), levels.t()])
+ assert image_to_string(image.to(device)) == image_to_string(image)
+ gray = levels[None]
+ assert image_to_string(gray.to(device)) == image_to_string(gray)
+
def test_distances_are_computed_in_bounded_chunks(self, monkeypatch):
# no (pixels, 240) distance matrix has more rows than _PIXELS_PER_CHUNK, whatever the image size
sizes = []