Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

test: fix CUDA-only torch.compile test contracts (resized-crop nearest oracle, fit_line, fit_plane, Keypoints) (#6586)

Dmytro Mishkinb914d37a3926
diff --git a/tests/augmentation/test_augmentation_compile.py b/tests/augmentation/test_augmentation_compile.py
index 56f8f8d77..3bbf521ca 100644
--- a/tests/augmentation/test_augmentation_compile.py
+++ b/tests/augmentation/test_augmentation_compile.py
@@ -157,7 +157,19 @@ class TestAugmentationCompile(BaseTester):
self.assert_close(actual, expected)
weights = torch.rand_like(actual)
actual_grad = torch.autograd.grad(actual, input, weights)[0]
- if device.type == "cuda" and dtype in (torch.float16, torch.bfloat16):
+ if device.type == "cuda" and resample == "nearest":
+ # CUDA's nearest-exact interpolate backward, which the eager slice crop uses, can send a pixel's
+ # gradient to its neighbour: a crop axis of 12 pixels resized to one reads pixel 6 and sends the
+ # gradient to pixel 5. The gather of the compiled crop routes it to the pixel it read, so compare with
+ # the eager crop on the CPU, in float32 for half dtypes. This is the PyTorch bug
+ # https://github.com/pytorch/pytorch/issues/97135; drop this branch once it is fixed.
+ reference_dtype = torch.float32 if dtype in (torch.float16, torch.bfloat16) else dtype
+ reference = input.detach().to("cpu", reference_dtype).requires_grad_()
+ cpu_params = {key: value.cpu() if torch.is_tensor(value) else value for key, value in params.items()}
+ expected_grad = torch.autograd.grad(
+ aug(reference, params=cpu_params), reference, weights.to("cpu", reference_dtype)
+ )[0].to(device, dtype)
+ elif device.type == "cuda" and dtype in (torch.float16, torch.bfloat16):
# CUDA half interpolate backward rounds atomic updates. Compare with
# float32 accumulation, as in the real-backend replay tests below.
reference = input.detach().float().requires_grad_()
diff --git a/tests/geometry/test_keypoints.py b/tests/geometry/test_keypoints.py
index d3176f3e4..20edb5285 100644
--- a/tests/geometry/test_keypoints.py
+++ b/tests/geometry/test_keypoints.py
@@ -17,7 +17,7 @@
import pytest
import torch
-from torch._dynamo.exc import BackendCompilerFailed, Unsupported, UserError
+from torch._dynamo.exc import BackendCompilerFailed, InternalTorchDynamoError, Unsupported, UserError
import kornia.augmentation as K
from kornia.geometry.keypoints import Keypoints, Keypoints3D, VideoKeypoints
@@ -104,6 +104,11 @@ class TestKeypointsIndexing(BaseTester):
):
pytest.xfail("Dynamo cannot specialize a CUDA scalar tensor index, including raw tensor indexing")
raise
+ except InternalTorchDynamoError as exc:
+ if scalar_tensor and device.type == "cuda" and "PendingUnbackedSymbolNotFound" in str(exc):
+ # torch 2.14 and 2.15 raise this for raw ``x[index]`` with a 0-d CUDA index as well.
+ pytest.xfail("Dynamo cannot trace a CUDA scalar tensor index, including raw tensor indexing")
+ raise
except Unsupported as exc:
if torch.__version__.startswith("2.5.") and "UserDefinedClassVariable" in str(exc):
pytest.xfail("PyTorch 2.5 cannot compile the keypoint type(self) constructor")
diff --git a/tests/geometry/test_line.py b/tests/geometry/test_line.py
index 618429b49..2b7ef8f67 100644
--- a/tests/geometry/test_line.py
+++ b/tests/geometry/test_line.py
@@ -726,7 +726,13 @@ class TestFitLine(BaseTester):
return line.origin, line.direction
origin, direction = torch_optimizer(op)(points)
- self.assert_close(origin, torch.zeros(1, 2, device=device, dtype=dtype))
+ # The origin is 0 only up to the rounding of coordinates of 40000: CUDA Inductor turns the mean into a
+ # product with 1 / 3 and fuses it with the shift back by the first point, so float32 gives 0.0012, a quarter
+ # of an ulp of the coordinates, where eager and CPU Inductor round the mean to 40000 exactly. Half dtypes are
+ # centred in float32, so the bound follows float32's rounding: their own eps would allow an origin of 39 in
+ # float16 and 312 in bfloat16.
+ atol = 40000 * torch.finfo(torch.promote_types(dtype, torch.float32)).eps
+ self.assert_close(origin, torch.zeros(1, 2, device=device, dtype=dtype), rtol=0.0, atol=atol)
expected = torch.tensor([[2.0 / math.sqrt(5), 1.0 / math.sqrt(5)]], device=device, dtype=dtype)
self.assert_close(direction, expected)
diff --git a/tests/geometry/test_plane.py b/tests/geometry/test_plane.py
index 9b60163f6..21aa0421c 100644
--- a/tests/geometry/test_plane.py
+++ b/tests/geometry/test_plane.py
@@ -432,7 +432,7 @@ class TestHyperplane(BaseTester):
def test_dynamo_skips_degenerate_checks(self, device, dtype, torch_optimizer):
# The degeneracy checks depend on tensor values, so they are skipped under torch.compile: a compiled call
- # on collinear points returns what an eager call returns with checks disabled.
+ # on collinear points returns a normal, like an eager call with checks disabled, instead of raising.
a = torch.tensor([1.0, 1.0, 1.0], device=device, dtype=dtype)
b = torch.tensor([2.0, 3.0, 4.0], device=device, dtype=dtype)
c = 2 * b - a
@@ -449,7 +449,12 @@ class TestHyperplane(BaseTester):
if checks_were_enabled:
enable_checks()
self.assert_close(actual[0], expected[0])
- self.assert_close(actual[1], expected[1])
+ # Every unit vector orthogonal to the line fits collinear points equally well, so fit_plane's normal is
+ # whichever one the decomposition returns: on CUDA the compiled and eager calls return different ones.
+ line = (b - a) / (b - a).norm()
+ for normal in (actual[1], expected[1]):
+ self.assert_close(normal.norm(), torch.ones((), device=device, dtype=dtype))
+ self.assert_close(normal @ line, torch.zeros((), device=device, dtype=dtype))
def test_thin_valid_triangle_still_fits(self, device, dtype):
# The collinearity tolerance scales with the dtype: a sliver whose height is 64 machine epsilons of its