Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(tests): probe for the kernel before running half-precision tests on old torch (#4117)

Dmytro Mishkin2009933ed1d4
diff --git a/testing/base.py b/testing/base.py
index 7db2093bc..ace21b614 100644
--- a/testing/base.py
+++ b/testing/base.py
@@ -140,17 +140,37 @@ def supports_2d_border_padding(device: torch.device) -> bool:
_UNIMPLEMENTED_KERNEL_MSG = "not implemented for"
+class _UnsupportedProbeDtype(Exception):
+ """The device cannot hold the probe dtype at all -- MPS and float64 -- so it cannot run ``op``."""
+
+
+def _probe_zeros(device_type: str, dtype: torch.dtype, *shape: int) -> Tensor:
+ """Allocate a probe tensor, reporting "this device cannot hold ``dtype``" as a distinct error.
+
+ ``torch.zeros`` raises TypeError for a device/dtype pair it cannot represent (MPS and
+ float64). That is still "unsupported" and must not escape a helper whose whole contract is to
+ return a bool -- but a TypeError raised by the *operator* is a mis-written probe, and silently
+ reading it as "unsupported" would skip the guarded test on every build forever. Translating
+ only the allocation failure keeps the two apart.
+ """
+ try:
+ return torch.zeros(shape, device=device_type, dtype=dtype)
+ except TypeError as e:
+ raise _UnsupportedProbeDtype from e
+
+
@cache
-def _supports_replicate_padding_probe(device_type: str, dtype: torch.dtype) -> bool:
+def _supports_kernel_probe(op: Callable[[str, torch.dtype], object], device_type: str, dtype: torch.dtype) -> bool:
+ """Run ``op`` on tiny tensors and report whether this build has a kernel for it.
+
+ ``op`` allocates its probe tensors through :func:`_probe_zeros` and then calls the operator.
+ Cached per (op, device type, dtype), so every probe below runs once per session and
+ auto-enables once PyTorch fills the kernel in.
+ """
try:
- # Allocated outside the `try` below: a device that cannot hold `dtype` at all (MPS and
- # float64) raises TypeError here, which is still "unsupported" and must not escape a
- # helper whose whole contract is to return a bool.
- probe = torch.zeros(1, 1, 2, 2, device=device_type, dtype=dtype)
- except TypeError:
+ op(device_type, dtype)
+ except _UnsupportedProbeDtype:
return False
- try:
- F.pad(probe, (1, 1, 1, 1), mode="replicate")
except RuntimeError as e:
if _UNIMPLEMENTED_KERNEL_MSG in str(e):
return False
@@ -158,6 +178,10 @@ def _supports_replicate_padding_probe(device_type: str, dtype: torch.dtype) -> b
return True
+def _replicate_padding_op(device_type: str, dtype: torch.dtype) -> None:
+ F.pad(_probe_zeros(device_type, dtype, 1, 1, 2, 2), (1, 1, 1, 1), mode="replicate")
+
+
def supports_replicate_padding(device: torch.device, dtype: torch.dtype) -> bool:
"""Whether this device has a 2D ``mode="replicate"`` pad kernel for ``dtype``.
@@ -167,23 +191,15 @@ def supports_replicate_padding(device: torch.device, dtype: torch.dtype) -> bool
than reading the injected dtype fails there on every job. Probed at runtime and cached per
(device type, dtype), so it auto-enables once PyTorch fills the kernel in.
"""
- return _supports_replicate_padding_probe(device.type, dtype)
+ return _supports_kernel_probe(_replicate_padding_op, device.type, dtype)
-@cache
-def _supports_grid_sample_probe(device_type: str, dtype: torch.dtype) -> bool:
- try:
- probe = torch.zeros(1, 1, 2, 2, device=device_type, dtype=dtype)
- grid = torch.zeros(1, 2, 2, 2, device=device_type, dtype=dtype)
- except TypeError:
- return False
- try:
- F.grid_sample(probe, grid, align_corners=False)
- except RuntimeError as e:
- if _UNIMPLEMENTED_KERNEL_MSG in str(e):
- return False
- raise
- return True
+def _grid_sample_op(device_type: str, dtype: torch.dtype) -> None:
+ F.grid_sample(
+ _probe_zeros(device_type, dtype, 1, 1, 2, 2),
+ _probe_zeros(device_type, dtype, 1, 2, 2, 2),
+ align_corners=False,
+ )
def supports_grid_sample(device: torch.device, dtype: torch.dtype) -> bool:
@@ -195,7 +211,58 @@ def supports_grid_sample(device: torch.device, dtype: torch.dtype) -> bool:
half dtype rather than reading the injected one fails there on every job. Probed at runtime
and cached per (device type, dtype), like :func:`supports_replicate_padding`.
"""
- return _supports_grid_sample_probe(device.type, dtype)
+ return _supports_kernel_probe(_grid_sample_op, device.type, dtype)
+
+
+def _conv2d_op(device_type: str, dtype: torch.dtype) -> None:
+ F.conv2d(_probe_zeros(device_type, dtype, 1, 1, 3, 3), _probe_zeros(device_type, dtype, 1, 1, 2, 2))
+
+
+def supports_conv2d(device: torch.device, dtype: torch.dtype) -> bool:
+ """Whether this device has a 2D convolution kernel for ``dtype``.
+
+ Every CNN descriptor -- :class:`kornia.feature.HardNet`, ``HardNet8``, ``SOSNet``, ``TFeat`` --
+ is a stack of convolutions. torch 2.1.2 has no float16 CPU ``slow_conv2d`` (bfloat16 is fine),
+ so a test that hardcodes a half dtype rather than reading the injected one fails there on every
+ job. Probed at runtime and cached per (device type, dtype), like
+ :func:`supports_replicate_padding`.
+ """
+ return _supports_kernel_probe(_conv2d_op, device.type, dtype)
+
+
+def _matmul_op(device_type: str, dtype: torch.dtype) -> None:
+ _probe_zeros(device_type, dtype, 2, 3) @ _probe_zeros(device_type, dtype, 3, 2)
+
+
+def supports_matmul(device: torch.device, dtype: torch.dtype) -> bool:
+ """Whether this device has a 2D matrix-multiply kernel for ``dtype``.
+
+ Descriptor matching multiplies: :func:`kornia.feature.match_mnn` and friends route half
+ precision around ``torch.cdist`` into a manual expand-and-multiply distance matrix, and
+ ``kornia.feature.steerers.DiscreteSteerer`` steers through ``F.linear``. Both are 2D, so this
+ probes ``mm``/``addmm``; batched ``bmm`` is a separate kernel and needs its own probe. torch
+ 2.1.2 has no
+ float16 CPU ``addmm`` (bfloat16 is fine), so a test that hardcodes a half dtype rather than
+ reading the injected one fails there on every job. Probed at runtime and cached per
+ (device type, dtype), like :func:`supports_replicate_padding`.
+ """
+ return _supports_kernel_probe(_matmul_op, device.type, dtype)
+
+
+def _topk_op(device_type: str, dtype: torch.dtype) -> None:
+ _probe_zeros(device_type, dtype, 2).topk(k=1)
+
+
+def supports_topk(device: torch.device, dtype: torch.dtype) -> bool:
+ """Whether this device has a ``topk`` kernel for ``dtype``.
+
+ Every detector ranks its candidates that way, so a response map in a narrower dtype than the
+ image -- what a learned response module under autocast produces -- reaches ``topk`` in that
+ dtype. torch 2.1.2 has no float16 CPU ``topk`` (bfloat16 is fine), so a test that hardcodes a
+ half dtype rather than reading the injected one fails there on every job. Probed at runtime and
+ cached per (device type, dtype), like :func:`supports_replicate_padding`.
+ """
+ return _supports_kernel_probe(_topk_op, device.type, dtype)
class BaseTester:
diff --git a/tests/feature/test_hardnet.py b/tests/feature/test_hardnet.py
index 321045715..50897085b 100644
--- a/tests/feature/test_hardnet.py
+++ b/tests/feature/test_hardnet.py
@@ -20,7 +20,7 @@ import torch
from kornia.feature import HardNet, HardNet8
-from testing.base import BaseTester
+from testing.base import BaseTester, supports_conv2d
class TestHardNet(BaseTester):
@@ -92,6 +92,9 @@ class TestHardNetConstantPatchIsFinite(BaseTester):
@pytest.mark.parametrize("desc_dtype", [torch.float16, torch.bfloat16, torch.float32])
@pytest.mark.parametrize("model", [HardNet, HardNet8])
def test_constant_patch(self, device, desc_dtype, model):
+ if not supports_conv2d(device, desc_dtype):
+ # The descriptor is a stack of convolutions; torch 2.1.2 has no float16 CPU kernel.
+ pytest.skip(f"no conv2d kernel for {desc_dtype} on {device.type}")
patches = torch.zeros(2, 1, 32, 32, device=device, dtype=desc_dtype)
out = model().to(device, desc_dtype)(patches)
assert torch.isfinite(out).all()
diff --git a/tests/feature/test_matching.py b/tests/feature/test_matching.py
index 29e5feadf..aa106dd05 100644
--- a/tests/feature/test_matching.py
+++ b/tests/feature/test_matching.py
@@ -34,7 +34,7 @@ from kornia.feature.matching import (
)
from kornia.feature.steerers import DiscreteSteerer
-from testing.base import BaseTester
+from testing.base import BaseTester, supports_matmul
from testing.casts import dict_to
@@ -610,6 +610,10 @@ class TestMatchSteererGlobal(BaseTester):
@pytest.mark.parametrize("desc_dtype", [torch.float16, torch.bfloat16, torch.float32])
def test_normalize_is_finite_on_a_zero_descriptor(self, device, desc_dtype):
+ if not supports_matmul(device, desc_dtype):
+ # The half-precision `_cdist` fallback multiplies the descriptors, and the steerer
+ # steers through `F.linear`; torch 2.1.2 has no float16 CPU `addmm` kernel.
+ pytest.skip(f"no matmul kernel for {desc_dtype} on {device.type}")
# `F.normalize`'s default eps underflows in float16, so a zero row -- the descriptor of a
# padded slot -- became NaN, and `cdist` then poisoned its whole row and column.
torch.manual_seed(0)
@@ -617,7 +621,9 @@ class TestMatchSteererGlobal(BaseTester):
desc2 = torch.rand(6, 8, device=device, dtype=desc_dtype)
desc1[1] = 0
desc2[4] = 0
- steerer = DiscreteSteerer(torch.eye(8, device=device, dtype=desc_dtype))
+ # torch 2.2.2 and older have no bfloat16 CPU `eye` kernel. 0 and 1 are exact in every
+ # float dtype, so building in float32 and casting gives the identical matrix.
+ steerer = DiscreteSteerer(torch.eye(8, device=device, dtype=torch.float32).to(desc_dtype))
matcher = DescriptorMatcherWithSteerer(steerer=steerer, steerer_order=2, steer_mode="global", match_mode="mnn")
dists, idxs, _ = matcher(desc1, desc2, normalize=True)
assert torch.isfinite(dists).all()
diff --git a/tests/feature/test_scale_space_detector.py b/tests/feature/test_scale_space_detector.py
index 0dff976f0..7d551a1f6 100644
--- a/tests/feature/test_scale_space_detector.py
+++ b/tests/feature/test_scale_space_detector.py
@@ -29,7 +29,7 @@ from kornia.feature.scale_space_detector import (
)
from kornia.geometry.subpix import ConvQuadInterp3d
-from testing.base import BaseTester, supports_replicate_padding
+from testing.base import BaseTester, supports_replicate_padding, supports_topk
class TestScaleSpaceDetector(BaseTester):
@@ -283,6 +283,11 @@ class TestScaleSpaceDetector(BaseTester):
# The top-K sentinel is written into the *response* tensor, so it must fit that dtype: a
# response module that emits a narrower dtype than the image -- a learned response under
# autocast -- raised "value cannot be converted to type at::Half without overflow".
+ if not supports_topk(device, torch.float16):
+ # The top-K ranks the response, which this module narrows to float16; torch 2.1.2 has
+ # no float16 CPU `topk` kernel.
+ pytest.skip(f"no topk kernel for torch.float16 on {device.type}")
+
class NarrowResponse(torch.nn.Module):
def __init__(self) -> None:
super().__init__()