🐍 Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(core): keep histc counts out of half precision; invert half 3x3 matrices in float32 (#5237)
Dmytro Mishkin668183919a3d
diff --git a/changelog.d/5237.fixed.md b/changelog.d/5237.fixed.mdnew file mode 100644index 000000000..fbda8c487--- /dev/null+++ b/changelog.d/5237.fixed.md@@ -0,0 +1,11 @@+`otsu_threshold` / `OtsuThreshold` no longer return a threshold of 0 for a `float16` image plane of+65520 pixels or more (256 x 256 and up): the histogram counts were cast back to the image dtype, so+their sum overflowed to `inf`, and `bfloat16` counts were rounded to 8 bits. The normalised histogram is+no longer summed in half precision either, so the thresholds of smaller `float16` and `bfloat16` images+now match the `float32` call (a 1024-pixel ramp of the levels k / 256 gave 0.4922 in `float16` and+0.4805 in `bfloat16` against 0.5; all three give 0.5). The counts are now kept in `float32` (`float64`+for a `float64` image). `normalize_homography`, and the `warp_perspective` and `warp_affine` calls built+on it, now invert `float16` and `bfloat16` matrices in `float32` and cast the result back: the `float16`+determinant of a large image's pixel-normalization matrix is subnormal, so a 3000 px `float16`+normalization was 7 % off and an 11600 px one was NaN, and `bfloat16` on MPS with torch 2.5.1 raised for+want of a `cross` kernel.diff --git a/docs/source/get-started/precision.rst b/docs/source/get-started/precision.rstindex 8167a20b7..3000b35e8 100644--- a/docs/source/get-started/precision.rst+++ b/docs/source/get-started/precision.rst@@ -31,9 +31,9 @@ precision, so the table says nothing about those backends.* - ``kornia.filters``- ⚠️ Partial- ⚠️ Partial- - 18 / 9- - Accuracy misses in Canny magnitudes, discrete Gaussian kernels and Otsu thresholding. On CPU,- ``fft_conv`` computes its FFTs in float32 and returns the input dtype.+ - 14 / 8+ - Accuracy misses in Canny magnitudes and discrete Gaussian kernels. On CPU, ``fft_conv`` computes its FFTs+ in float32 and returns the input dtype.* - ``kornia.enhance``- ✅ Yes- ⚠️ Partialdiff --git a/kornia/core/_small_linalg.py b/kornia/core/_small_linalg.pyindex 53fc206a7..1f4cb1212 100644--- a/kornia/core/_small_linalg.py+++ b/kornia/core/_small_linalg.py@@ -27,8 +27,9 @@ and ``linalg.det`` gives ``"lu_factor_cusolver" not implemented for 'Half'``.The contract is deliberately minimal, because the callers own the policy:-- They compute in whatever dtype the caller supplies. **No promotion** -- that belongs to- :func:`kornia.core.utils._torch_inverse_cast`.+- They compute in whatever dtype the caller supplies. **No promotion** -- that belongs to the+ dispatchers :func:`kornia.core.utils._torch_inverse_cast` and+ :func:`kornia.core.utils._inverse_3x3_closed_form`, which both invert half input in float32.- Exact shape and a real floating dtype are **caller preconditions, not runtime checks**.Behavior on anything else is unspecified: ``_adjugate_3x3`` of a 4x4 silently uses theleading 3x3 block, and of a 2x2 raises an incidental ``IndexError``. The contractual sizediff --git a/kornia/core/utils.py b/kornia/core/utils.pyindex a5e98658a..65b7ff3e4 100644--- a/kornia/core/utils.py+++ b/kornia/core/utils.py@@ -180,30 +180,41 @@ def _inverse_3x3_closed_form(input: torch.Tensor) -> torch.Tensor:The arithmetic lives in :mod:`kornia.core._small_linalg`; this function owns only thechoice between the two kernels, which is execution-mode policy and therefore stays here.+ A float16 or bfloat16 input is inverted in float32 and the result cast back, as+ :func:`_torch_inverse_cast` does. The determinant is a sum of products of three entries, so it leaves+ float16's range long before the entries do: the pixel-normalization matrix of a 3000 px image,+ with entries ``2 / 2999``, has a subnormal float16 determinant, 6 % off, and one of 11600 px a zero one.+ Running ``cross`` in float32 also avoids the missing bfloat16 ``cross`` kernel on MPS in+ torch 2.5.1.+Args:input: Tensor of shape ``(..., 3, 3)``.Returns:Tensor of shape ``(..., 3, 3)`` containing the matrix inverse for each- leading-dim slice. Numerically equivalent to ``torch.linalg.inv`` for+ leading-dim slice, in the dtype of ``input``. Numerically equivalent to ``torch.linalg.inv`` forwell-conditioned matrices; behavior on singular matrices is undefined(no explicit check, same as ``torch.linalg.inv`` itself)."""+ half = input.dtype in (torch.float16, torch.bfloat16)+ x = input.float() if half else inputif not _is_tracing_or_exporting():# Eager: three fused ``cross`` ops beat nine scalar cofactor expressions and four# stacks, because kernel launches dominate on matrices this small.- return _inverse_3x3_cross(input)-- # Under tracing/export (legacy ONNX / jit.trace / dynamo ONNX) stick to the plain scalar- # adjugate. NOTE the original rationale here -- "whereas ``cross`` may not [lower]" -- does not- # hold on the torch versions CI runs: measured, ``torch.linalg.cross`` lowers on 2.5.1 (legacy- # exporter) and 2.9.1 and 2.14.0 (both exporters). The legacy exporter emits- # ``Slice``/``Mul``/``Sub``/``Concat``; the dynamo exporter emits ``Split`` in place of ``Slice``,- # on 2.9.1 as on 2.14.0. The split is kept because it is still the safer capture path (scalar- # arithmetic needs no per-dtype kernel at all, and ``cross`` has real kernel gaps -- no bfloat16- # on MPS in torch 2.5.1), not because ``cross`` fails to export.- # Collapsing the two branches is a behavior change and belongs in its own PR.- return _inverse_3x3_scalar(input)+ out = _inverse_3x3_cross(x)+ else:+ # Under tracing/export (legacy ONNX / jit.trace / dynamo ONNX) stick to the plain scalar+ # adjugate. NOTE the original rationale here -- "whereas ``cross`` may not [lower]" -- does not+ # hold on the torch versions CI runs: measured, ``torch.linalg.cross`` lowers on 2.5.1 (legacy+ # exporter) and 2.9.1 and 2.14.0 (both exporters). The legacy exporter emits+ # ``Slice``/``Mul``/``Sub``/``Concat``; the dynamo exporter emits ``Split`` in place of ``Slice``,+ # on 2.9.1 as on 2.14.0. The split is kept because it is still the safer capture path (scalar+ # arithmetic needs no per-dtype kernel at all, and ``cross`` has real kernel gaps -- no bfloat16+ # on MPS in torch 2.5.1, which the float32 promotion above keeps half input away from), not+ # because ``cross`` fails to export.+ # Collapsing the two branches is a behavior change and belongs in its own PR.+ out = _inverse_3x3_scalar(x)+ return out.to(input.dtype) if half else outdef _is_tracing_or_exporting() -> bool:@@ -260,14 +271,22 @@ def _torch_inverse_cast(input: torch.Tensor) -> torch.Tensor:def _torch_histc_cast(input: torch.Tensor, bins: int, min: Union[float, bool], max: Union[float, bool]) -> torch.Tensor:- """Make torch.histc work with other than fp32/64.-- The function torch.histc is only implemented for fp32/64 which makes impossible to be used by fp16 or others. What- this function does, is cast input data type to fp32, apply torch.inverse, and cast back to the input dtype.+ """Apply torch.histc to any real dtype, returning the counts in float32 or float64.++ The input is cast to float32 (float64 stays float64) before binning: ``torch.histc`` has no CPU+ kernel for integer input, and on MPS in torch 2.5.1 none for anything but float32.++ The counts are returned in that compute dtype, **not** cast back to the input dtype. A count grows+ with the number of values, not with their range: float16 holds integers exactly only up to 2048 and+ rounds them to ``inf`` from 65520, bfloat16 only up to 256, and an integer dtype can wrap (uint8 past+ 255). They stay floating rather than becoming int64: ``torch.histc`` counts in the floating dtype it+ bins in, so a float32 count stops being exact past 2**24 per accumulating thread (single-threaded on+ the CPU, 2**25 + 3 equal values come back as 2**24), an int64 result would be no more exact, and a+ float64 input keeps float64 counts for float64 arithmetic downstream."""KORNIA_CHECK_IS_TENSOR(input, "Input must be torch.Tensor")dtype = _normalize_to_float32_or_float64(input.dtype)- return torch.histc(input.to(dtype), bins, min, max).to(input.dtype)+ return torch.histc(input.to(dtype), bins, min, max)def _torch_svd_cast(input: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:diff --git a/kornia/geometry/conversions.py b/kornia/geometry/conversions.pyindex 45fd240d0..e8a089b20 100644--- a/kornia/geometry/conversions.py+++ b/kornia/geometry/conversions.py@@ -1805,8 +1805,12 @@ def normalize_homography(per sample; an unbatched input is returned as ``(1, 3, 3)``, and anyother shape raises ``ValueError``- in eager mode ``inv(N_src)`` is a closed-form adjugate built from- ``torch.linalg.cross``, so no ``cusolver`` is needed, but a backend- without a ``cross`` kernel for the dtype raises here+ ``torch.linalg.cross``, so no ``cusolver`` is needed. A ``float16`` or+ ``bfloat16`` matrix is inverted in ``float32`` and the result cast back:+ the ``float16`` determinant of a large image's normalization matrix is+ subnormal or zero, and some backends lack a ``bfloat16`` ``cross`` kernel+ (MPS on torch 2.5.1). For any other dtype, a backend without a ``cross``+ kernel for it raises here.. warning::An integer matrix is not rejected: the normalization matrices are castdiff --git a/testing/half_precision_xfails/cpu_float16.txt b/testing/half_precision_xfails/cpu_float16.txtindex d984360bb..f394b199a 100644--- a/testing/half_precision_xfails/cpu_float16.txt+++ b/testing/half_precision_xfails/cpu_float16.txt@@ -193,8 +193,6 @@ call builtins.AssertionError tests/filters/test_gaussian.py::test_get_gaussian_dcall builtins.AssertionError tests/filters/test_gaussian.py::test_get_gaussian_discrete_kernel1d_tensor[cpu-float16-sigma0-5]call builtins.AssertionError tests/filters/test_gaussian.py::test_get_gaussian_discrete_kernel1d_tensor[cpu-float16-sigma1-11]call builtins.AssertionError tests/filters/test_gaussian.py::test_get_gaussian_discrete_kernel1d_tensor[cpu-float16-sigma1-5]-call builtins.AssertionError tests/filters/test_otsu_thresholding.py::TestOtsuThreshold::test_gradual_threshold[cpu-float16]-call builtins.AssertionError tests/filters/test_otsu_thresholding.py::test_mask[cpu-float16]call kornia.core.exceptions.BaseError tests/geometry/calibration/test_pnp.py::TestSolvePnpDlt::test_pred_world_to_cam[cpu-float16-20]call kornia.core.exceptions.BaseError tests/geometry/calibration/test_pnp.py::TestSolvePnpDlt::test_pred_world_to_cam[cpu-float16-6]call kornia.core.exceptions.BaseError tests/geometry/calibration/test_pnp.py::TestSolvePnpDlt::test_pred_world_to_cam_weighted[cpu-float16-16]diff --git a/tests/augmentation/test_conventions_geometric_crop.py b/tests/augmentation/test_conventions_geometric_crop.pyindex af362711d..aee1cd275 100644--- a/tests/augmentation/test_conventions_geometric_crop.py+++ b/tests/augmentation/test_conventions_geometric_crop.py@@ -246,8 +246,14 @@ class TestGeometricCropConventions(BaseTester):],}expected = image.new_tensor(expected_rows[mode]).reshape(1, 1, 6, 4)- # float16 resampling also rounds its grid, so this is a bound; the matrix is pinned exactly above.- tolerance = {"rtol": 0.0, "atol": 3e-3} if dtype == torch.float16 and mode == "resample" else {}+ # Half-precision resampling rounds its matrix and grid, so this is a bound in units of the dtype's eps (3e-3 in+ # float16); the matrix is pinned exactly above. The dominant term is the forward matrix, which+ # normalize_homography already builds in the half dtype: in bfloat16 its x scale 16/15 rounds to 1.0703125+ # and its translation is several ulps off, which alone leaves the right column, next to the canvas edge, about+ # 1.6 eps off with an exact inverse and a float64 grid. Measured 1.54 eps in bfloat16; a first-order worst+ # case is about 3.4 eps.+ half = dtype in (torch.float16, torch.bfloat16)+ tolerance = {"rtol": 0.0, "atol": 3 * torch.finfo(dtype).eps} if half and mode == "resample" else {}self.assert_close(output, expected, **tolerance)self.assert_close(output[0, 0, 0], image.new_tensor([0, 0, 0, 0]))assert output.shape == (1, 1, 6, 4)diff --git a/tests/core/test_helpers.py b/tests/core/test_helpers.pyindex 9cef21eb3..e276e6423 100644--- a/tests/core/test_helpers.py+++ b/tests/core/test_helpers.py@@ -22,6 +22,7 @@ from kornia.core.exceptions import DeviceError, TypeCheckErrorfrom kornia.core.utils import (_adjugate_closed_form,_extract_device_dtype,+ _inverse_3x3_closed_form,_torch_histc_cast,_torch_inverse_cast,_torch_linalg_svdvals,@@ -254,14 +255,79 @@ class TestExportHelpers:assert_close(v.grad, torch.full_like(v, 2.0))-class TestHistcCast:+class TestHistcCast(BaseTester):def test_smoke(self, device, dtype):+ # The counts come back in the dtype they are computed in -- float32, or float64 for a float64 input -- and+ # not in the input's dtype: a count is not an image value and half precision cannot hold it (#5196).x = torch.tensor([1.0, 2.0, 1.0], device=device, dtype=dtype)- y_expected = torch.tensor([0.0, 2.0, 1.0, 0.0], device=device, dtype=dtype)+ count_dtype = torch.float64 if dtype == torch.float64 else torch.float32+ y_expected = torch.tensor([0.0, 2.0, 1.0, 0.0], device=device, dtype=count_dtype)y = _torch_histc_cast(x, bins=4, min=0, max=3)- assert_close(y, y_expected)+ self.assert_close(y, y_expected)++ def test_counts_above_the_half_precision_integer_range_are_exact(self, device, dtype):+ # #5196: float16 holds integers exactly only up to 2048 and rounds them to inf from 65520, bfloat16 only up+ # to 256. With the counts cast back to the input dtype, 70000 equal values came back as inf in float16 and as+ # 70144 in bfloat16.+ x = torch.zeros(70001, device=device, dtype=dtype)+ x[0] = 1.0++ y = _torch_histc_cast(x, bins=2, min=0, max=1)++ assert y.tolist() == [70000.0, 1.0]+ assert y.dtype == (torch.float64 if dtype == torch.float64 else torch.float32)+++class TestInverse3x3ClosedForm(BaseTester):+ @pytest.mark.parametrize("capture", [False, True], ids=["eager", "capture"])+ def test_half_input_is_inverted_in_float32(self, device, dtype, capture, monkeypatch):+ # #5197: inverted in float32 and rounded once to the half dtype, the result is within half an ulp-ish of the+ # float64 inverse of the rounded matrix (0.47 eps measured on 256 matrices, float16 and bfloat16); the+ # adjugate computed in the half dtype is 1.9 to 2.5 eps off. Pins the bfloat16 promotion as well, which no+ # other CI leg exercises (the cross kernel it avoids is missing only on MPS with torch 2.5.1).+ if dtype not in (torch.float16, torch.bfloat16):+ pytest.skip("the float32 promotion applies to half dtypes only")+ if capture:+ monkeypatch.setattr("kornia.core.utils._is_tracing_or_exporting", lambda: True)+ generator = torch.Generator().manual_seed(0)+ eye = torch.eye(3, dtype=torch.float64)+ matrix = torch.randn(256, 3, 3, generator=generator, dtype=torch.float64) + 3 * eye+ matrix = matrix.to(device=device, dtype=dtype)+ expected = torch.linalg.inv(matrix.cpu().double())++ inverse = _inverse_3x3_closed_form(matrix)++ assert inverse.dtype == dtype+ error = (inverse.cpu().double() - expected).abs() / expected.abs().amax((-2, -1), keepdim=True)+ assert error.max() <= torch.finfo(dtype).eps++ @pytest.mark.parametrize("capture", [False, True], ids=["eager", "capture"])+ @pytest.mark.parametrize("side", [3000, 11600])+ def test_pixel_normalization_matrix_of_a_large_image(self, device, dtype, side, capture, monkeypatch):+ # #5197: the pixel-normalization matrix of a `side`-pixel image, [[s, 0, -1], [0, s, -1], [0, 0, 1]] with+ # s = 2 / (side - 1), has determinant s**2: 4.4e-7 at 3000 px, which float16 holds only as a subnormal+ # (4.2e-7, 6 % off), and 3.0e-8 at 11600 px, which rounds to zero in float16 (half its smallest subnormal).+ # Inverted in float16 it lost digits and then turned inf/NaN; a half input is inverted in float32 and cast+ # back, as _torch_inverse_cast does.+ # Oracle: the exact inverse of the dtype-rounded matrix, [[r, 0, r], [0, r, r], [0, 0, 1]] with r = 1 / s, in+ # float64 (not torch.linalg.inv, whose float64 result on torch 2.5.1 is 2e-13 off at an exact zero). The+ # result is off it by the final rounding to `dtype` (half an ulp) plus the few roundings of the adjugate+ # formula. `capture` takes the scalar kernel that tracing and export use, which promotes the same way.+ if capture:+ monkeypatch.setattr("kornia.core.utils._is_tracing_or_exporting", lambda: True)+ s = 2.0 / (side - 1)+ matrix = torch.tensor([[[s, 0.0, -1.0], [0.0, s, -1.0], [0.0, 0.0, 1.0]]], dtype=torch.float64)+ matrix = matrix.to(device=device, dtype=dtype)++ inverse = _inverse_3x3_closed_form(matrix)++ assert inverse.dtype == dtype+ r = 1.0 / matrix[0, 0, 0].item()+ expected = torch.tensor([[[r, 0.0, r], [0.0, r, r], [0.0, 0.0, 1.0]]], dtype=torch.float64)+ eps = torch.finfo(dtype).eps+ self.assert_close(inverse.cpu().double(), expected, rtol=4 * eps, atol=0.0)class TestSvdCast:diff --git a/tests/filters/test_otsu_thresholding.py b/tests/filters/test_otsu_thresholding.pyindex a5641efd0..f1e43de27 100644--- a/tests/filters/test_otsu_thresholding.py+++ b/tests/filters/test_otsu_thresholding.py@@ -136,6 +136,23 @@ class TestOtsuThreshold(BaseTester):thresh_result, _thresh_value = op(input)self.assert_close(thresh_result, expected)+ def test_large_image_threshold_matches_float32(self, device, dtype):+ # #5196: the histogram counts of a 300 x 300 image (90000 pixels) came back in the input dtype, so in float16+ # their sum overflowed to inf, the normalised histogram was all zeros and the threshold was 0; bfloat16 counts+ # were rounded to 8 bits. The pixel levels k / 256 are exact in every dtype, so the float32 call sees the same+ # pixels. For float16, bfloat16 and float32 the histogram arithmetic is then the same float32 computation, and+ # the two thresholds agree up to rounding the float32 one to `dtype`. float64 bins and sums in float64, and+ # the two best splits of this image differ by only about 50 float32 eps, so it is allowed one bin (1 / 256).+ levels = torch.randint(0, 256, (1, 1, 300, 300), generator=torch.Generator().manual_seed(0))+ img = (levels / 256).to(device=device, dtype=dtype)++ _, threshold = otsu_threshold(img)+ _, expected = otsu_threshold(img.float())++ assert 0.25 < expected.item() < 0.75+ atol = 1 / 256 if dtype == torch.float64 else 0.0+ self.assert_close(threshold, expected.to(dtype), rtol=0.0, atol=atol)+def test_mask(device, dtype):input = torch.tensor([[10, 20, 30], [40, 50, 60], [70, 80, 90]], device=device, dtype=dtype)diff --git a/tests/geometry/test_conversions.py b/tests/geometry/test_conversions.pyindex ce965e0ac..ee815442a 100644--- a/tests/geometry/test_conversions.py+++ b/tests/geometry/test_conversions.py@@ -90,9 +90,8 @@ def _issue_msg(text: str):def _innermost_frame(err: BaseException) -> TracebackType | None:- # The frame an exception actually died in: the last link of its traceback chain. Two helpers- # below read that frame for different questions -- which routine failed, and which bytecode- # instruction raised -- so the walk itself is written once and cannot drift between them.+ # The frame an exception actually died in: the last link of its traceback chain, read by the+ # guard classifier below for the bytecode instruction that raised.frame = err.__traceback__while frame is not None and frame.tb_next is not None:frame = frame.tb_next@@ -101,13 +100,10 @@ def _innermost_frame(err: BaseException) -> TracebackType | None:@cachedef _dtype_allocation_error(device: torch.device, dtype: torch.dtype) -> str | None:- # "Can this backend hold this dtype at all?", as ONE probe with ONE exception set, shared by- # _skip_if_dtype_unavailable and _cross_is_unavailable below. Two copies of it with different- # exception tuples would mean a backend that starts rejecting an allocation with a new- # exception type makes one of them skip while the other errors, for the same fact. Cached- # because the answer is a property of the build, not of the caller, and the pins below ask it- # once per test; the message is returned rather than the exception so no traceback is kept- # alive between tests.+ # "Can this backend hold this dtype at all?", as ONE probe with ONE exception set, for+ # _skip_if_dtype_unavailable below. Cached because the answer is a property of the build, not+ # of the caller, and the pins below ask it once per test; the message is returned rather than+ # the exception so no traceback is kept alive between tests.try:torch.zeros(1, device=device, dtype=dtype)except (TypeError, RuntimeError, NotImplementedError) as err:@@ -139,151 +135,6 @@ def _matmul_input_eps(device: torch.device, dtype: torch.dtype) -> float:return torch.finfo(dtype).eps-_healthy_closed_form_inverse_routes: set[tuple[torch.device, torch.dtype]] = set()---def _skip_if_closed_form_inverse_unavailable(device: torch.device, dtype: torch.dtype) -> None:- # Visible skip for the pins that route through normalize_homography, one layer deeper than- # _skip_if_dtype_unavailable: a backend can REPRESENT a dtype and still have no kernel for an- # operation the route needs. kornia's cusolver-free 3x3 inverse dispatches to- # _inverse_3x3_cross (kornia/core/_small_linalg.py), which is three torch.linalg.cross calls, and- # MPS lacks a bfloat16 `cross` kernel in SOME builds -- executed: torch 2.5.1 raises- # `RuntimeError: Failed to create function state object for: cross_bfloat` there while torch- # 2.9.1 runs it, and torch.zeros in that dtype succeeds on both, so the allocation probe alone- # lets the pin fail with a message about torch's kernel coverage rather than about kornia's- # convention. Probed rather than version-gated: two builds are two data points, not a history.- # What is attempted is the PUBLIC operation, on a throwaway input, and a failure becomes a skip- # only when BOTH halves of the identification hold: the call died INSIDE the closed-form- # inverse (innermost frame, matched by code object rather than by name or message, so a rename- # is a re-raise and not a silent skip) AND the primitive that routine is built from raises on- # the same device and dtype. Every other failure is re-raised, so a kornia-side regression- # still fails the pin here rather than being skipped over. The frame half is what keeps an- # UNRELATED RuntimeError from riding the skip: on a backend that genuinely lacks the kernel the- # primitive probe always fails, so on its own it would turn any new failure raised before the- # inverse -- in the guard, in normal_transform_pixel, in the chain matmul -- into a skip, and- # the regression would be invisible exactly where the skip is live. The primitive half is what- # keeps the skip from outliving the limitation: the day kornia's inverse stops needing `cross`,- # these pins must run again on backends that lack it instead of skipping forever.- # Residual, stated rather than hidden: this identifies the failing KERNEL, not the individual- # `cross` line inside it. _inverse_3x3_cross is three `cross` calls, a multiply-sum and a- # divide, so a failure at one of the latter two on a backend whose `cross` is also missing- # would still skip. Narrowing further would mean pinning line numbers in another module.- # It reads the cross KERNEL rather than the mode dispatcher that calls it: the dispatcher owns- # only the eager/export choice, so its frame is never where a missing `cross` surfaces.- # Only the HEALTHY verdict is memoized, keyed by (device, dtype): a route that works is a- # property of the build, and four pins ask this question in every test configuration, each- # paying a matmul and a 3x3 inverse for the answer. A failing route is deliberately never- # memoized -- it has to be re-raised with its own traceback every time, and it is the branch- # this helper exists for.- # Imported here rather than at module scope on purpose: this is a PRIVATE kornia helper, and a- # module-level import of it would make the WHOLE file uncollectable if it is ever renamed --- # every test in it erroring over a rename that concerns the four pins routed through here.- # Inside the probe, the same rename is an ImportError on those four and nothing else.- from kornia.core._small_linalg import _inverse_3x3_cross-- route = (device, dtype)- if route in _healthy_closed_form_inverse_routes:- return- try:- kornia.geometry.conversions.normalize_homography(torch.eye(3, device=device, dtype=dtype)[None], (2, 2), (2, 2))- except (RuntimeError, NotImplementedError) as err:- innermost = _innermost_frame(err)- died_in_the_closed_form_inverse = (- innermost is not None and innermost.tb_frame.f_code is _inverse_3x3_cross.__code__- )- if died_in_the_closed_form_inverse and _cross_is_unavailable(device, dtype):- pytest.skip(f"torch.linalg.cross has no {dtype} kernel on device {device}: {err}")- raise- _healthy_closed_form_inverse_routes.add(route)---@cache-def _cross_is_unavailable(device: torch.device, dtype: torch.dtype) -> bool:- # "Can this build run torch.linalg.cross here?", for the helper above and the pin below.- # A dtype the backend cannot even allocate (mps rejects float8 outright) counts as unavailable- # rather than propagating as an error, and that half of the question is answered by the shared- # probe rather than by a second copy of it, so both helpers classify such a backend the same- # way. Cached for the same reason the probe is: it is a property of the build.- if _dtype_allocation_error(device, dtype) is not None:- return True- try:- probe = torch.ones(1, 3, device=device, dtype=dtype)- torch.linalg.cross(probe, probe, dim=-1)- except (RuntimeError, NotImplementedError, TypeError):- return True- return False---def test_skip_probe_re_raises_everything_it_cannot_identify(monkeypatch):- # Direct pin for _skip_if_closed_form_inverse_unavailable above, for the same reason- # test_guard_classifier_reads_the_raising_instruction pins the guard classifier: four pins- # route their "does normalize_homography work here at all" question through that helper, and if- # it starts skipping too readily they go quiet instead of failing, which is the mode a skip- # helper fails in. Nothing else in this file would notice.- # Case B needs a REAL kernel gap rather than a patched `cross`: patching it with a Python- # function puts that function in the innermost frame, which is precisely what the helper reads,- # so a patch cannot reproduce the branch it is meant to exercise. torch has no `cross` kernel- # for bool or float8 on cpu (executed, torch 2.9.1: NotImplementedError, and the route dies- # inside _inverse_3x3_cross), which is the same shape as the mps bfloat16 gap on torch- # 2.5.1 that the helper exists for, reachable on the default device without that build. The- # candidate list is searched rather than asserted: mps DOES have a bool `cross`, so a build- # that grows the missing kernels must make this case skip visibly, not fail.- # Cases C and D patch normal_transform_pixel, which normalize_homography calls BEFORE the- # inverse, so the route dies without ever reaching `cross` and the patch stays out of the- # frame the helper reads. D is the one that matters: it is exactly C on a backend that also- # lacks the kernel, which a probe of the primitive alone cannot tell apart from a real gap --- # it would skip there, and a kornia-side regression would be invisible on exactly the backends- # where the skip is live.- # The helper's memo and the two cached probes are cleared first: they are performance- # shortcuts, and a pin whose whole subject is which branch the helper takes has to run the- # branches rather than a remembered verdict from an earlier test.- # The two globals that cases C and D patch go through monkeypatch rather than by hand: this is- # the one pin in the file that writes to torch and to the kornia module itself, and a leak from- # here would follow every later test in the process, so restoration belongs to pytest rather- # than to a nest of try/finally blocks that has to be read to be trusted.- cpu = torch.device("cpu")- conversions = kornia.geometry.conversions- _healthy_closed_form_inverse_routes.clear()- _cross_is_unavailable.cache_clear()- _dtype_allocation_error.cache_clear()-- _skip_if_closed_form_inverse_unavailable(cpu, torch.float32) # A: healthy route, must not skip-- # torch.float8_e4m3fn was added in torch 2.1 and kornia now declares torch>=2.5.1, so the- # getattr probe below is redundant; it is left in place with the rest of the sub-floor- # version guards rather than cleaned up piecemeal.- candidate_dtypes = (torch.bool, getattr(torch, "float8_e4m3fn", None))- unsupported = next(- (dtype for dtype in candidate_dtypes if dtype is not None and _cross_is_unavailable(cpu, dtype)),- None,- )- if unsupported is None:- pytest.skip("no dtype without a torch.linalg.cross cpu kernel on this build")- with pytest.raises(pytest.skip.Exception): # B: the gap the helper exists for- _skip_if_closed_form_inverse_unavailable(cpu, unsupported)-- def regression(*args, **kwargs):- raise RuntimeError("kornia-side regression")-- def assert_the_injected_failure_propagates(case: str) -> None:- # Requiring RuntimeError still lets pytest.skip escape, so catch that skip separately- # and fail the pin. No error, a different error, or the wrong RuntimeError also fails.- try:- with pytest.raises(RuntimeError) as excinfo:- _skip_if_closed_form_inverse_unavailable(cpu, torch.float32)- except pytest.skip.Exception as skipped:- raise AssertionError(f"{case}: an unrelated failure was skipped over: {skipped}") from skipped- assert "kornia-side regression" in str(excinfo.value), f"{case}: wrong error re-raised: {excinfo.value}"-- # Cleared again: case A memoized (cpu, float32) as healthy, and C/D have to reach the body.- _healthy_closed_form_inverse_routes.clear()- monkeypatch.setattr(conversions, "normal_transform_pixel", regression)- assert_the_injected_failure_propagates("C, cross available")-- monkeypatch.setattr(torch.linalg, "cross", regression)- assert_the_injected_failure_propagates("D, cross unavailable too")--# The four deprecated aliases of this module, as (deprecated name, replacement name, call input),# shared by the alias-forwarding pin in TestAngleAxisToQuaternion and the two module-level# kornia#3956 pins at the end of this file.@@ -3877,14 +3728,14 @@ class TestNormalizeHomography(BaseTester):# only at these sizes AND with a literal whose intermediates are exact. The invariant also# leans on the SHAPE of the normalization matrices -- upper-triangular with power-of-two# pivots -- surviving BOTH inverse routes actually in play (the functions do NOT share one):- # normalize_homography inverts through _inverse_3x3_closed_form (cofactor arithmetic --- # products and sums of dyadic values, then division by a power-of-two determinant, all- # exact), while denormalize_homography and normalize_homography3d go through- # _torch_inverse_cast (torch.linalg.inv in eager mode, rounding-free on such triangular- # matrices, with a float32 upcast for half dtypes and a closed-form 3x3 fallback under- # tracing -- each exactness-preserving on these values). A future non-triangular- # normalization (a #3904 align_corners variant, say) voids the atol=0 claim on EVERY route- # and needs a tolerance instead.+ # normalize_homography inverts through _inverse_3x3_closed_form (cofactor arithmetic, in+ # float32 for half dtypes -- products and sums of dyadic values, then division by a+ # power-of-two determinant, all exact), while denormalize_homography and+ # normalize_homography3d go through _torch_inverse_cast (torch.linalg.inv in eager mode,+ # rounding-free on such triangular matrices, with a float32 upcast for half dtypes and a+ # closed-form 3x3 fallback under tracing -- each exactness-preserving on these values). A+ # future non-triangular normalization (a #3904 align_corners variant, say) voids the atol=0+ # claim on EVERY route and needs a tolerance instead.# No pin asserts anything about kornia#3962 (no denormalize_homography3d, no# ColmapQTVecs_to_ARKitQTVecs) -- a missing symbol is a scope question, not a defect.# NOTE: kornia#3904 landed and moved none of these. normalize_homography and@@ -3938,7 +3789,6 @@ class TestNormalizeHomography(BaseTester):# src (1, 1) -> (2*1/4 - 1, 2*1/2 - 1) = (-0.5, 0.0)# dst (3, 1) -> (2*3/4 - 1, 2*1/2 - 1) = ( 0.5, 0.0)_skip_if_dtype_unavailable(device, dtype)- _skip_if_closed_form_inverse_unavailable(device, dtype)translate_two_px = torch.tensor([[[1.0, 0.0, 2.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]], device=device, dtype=dtype)@@ -3954,7 +3804,6 @@ class TestNormalizeHomography(BaseTester):# identity to within one float32 rounding step (2**-24); which sizes land on exactly 0 is a# property of the inverse-and-matmul chain and is not pinned._skip_if_dtype_unavailable(device, torch.float32)- _skip_if_closed_form_inverse_unavailable(device, torch.float32)identity = torch.eye(3, device=device, dtype=torch.float32)[None]normalized = kornia.geometry.conversions.normalize_homography(identity, (size, size), (size, size))@@ -3975,7 +3824,6 @@ class TestNormalizeHomography(BaseTester):# normalize_homography(H, (5, 9), (3, 5))# -> [[4.0, 0.5, 4.5], [-1.0, 2.0, 1.0], [0.0, 0.0, 1.0]]_skip_if_dtype_unavailable(device, dtype)- _skip_if_closed_form_inverse_unavailable(device, dtype)homography = torch.tensor(_DIRECTION_H, device=device, dtype=dtype)normalized = kornia.geometry.conversions.normalize_homography(homography, (3, 5), (5, 9))@@ -4045,7 +3893,6 @@ class TestNormalizeHomography(BaseTester):# denormalize_homography(normalize_homography(H, (3, 5), (5, 9)), (3, 5), (5, 9)) == H (bitwise)# normalize_homography(denormalize_homography(H, (3, 5), (5, 9)), (3, 5), (5, 9)) == H (bitwise)_skip_if_dtype_unavailable(device, dtype)- _skip_if_closed_form_inverse_unavailable(device, dtype)normalize_homography = kornia.geometry.conversions.normalize_homographydenormalize_homography = kornia.geometry.conversions.denormalize_homographyhomography = torch.tensor(_ROUND_TRIP_H, device=device, dtype=dtype)@@ -4069,7 +3916,6 @@ class TestNormalizeHomography(BaseTester):# on a batch of two different homographies, comparing element 1 of the batched call against# the single-element call._skip_if_dtype_unavailable(device, dtype)- _skip_if_closed_form_inverse_unavailable(device, dtype)normalize_homography = kornia.geometry.conversions.normalize_homographydenormalize_homography = kornia.geometry.conversions.denormalize_homographybatch = torch.tensor([_DIRECTION_H[0], _ROUND_TRIP_H[0]], device=device, dtype=dtype)diff --git a/tests/geometry/test_keypoints.py b/tests/geometry/test_keypoints.pyindex 4547a9f5a..a9362f5bb 100644--- a/tests/geometry/test_keypoints.py+++ b/tests/geometry/test_keypoints.py@@ -422,17 +422,6 @@ class TestKeypoints3D(BaseTester):class TestConventionsKeypoints(BaseTester):"""Pins for the coordinate, transform and aliasing conventions of :class:`Keypoints`."""- @staticmethod- def _has_cross_kernel(device, dtype):- # The affine warp inverts its 3x3 matrix with kornia's closed-form inverse, built from torch.linalg.cross;- # some torch builds have no cross kernel for a dtype (torch 2.5.1 on MPS raises for bfloat16).- try:- probe = torch.ones(1, 3, device=device, dtype=dtype)- torch.linalg.cross(probe, probe, dim=-1)- except RuntimeError:- return False- return True-@staticmethoddef _value_at(image, xy):# The image value at the pixel nearest to an (x, y) keypoint, or None when that pixel is outside the image.@@ -451,8 +440,6 @@ class TestConventionsKeypoints(BaseTester):def test_convention_keypoints_are_xy_pixel_coordinates(self, make_augmentation, device, dtype):if not supports_bilinear_2d_grid_sample(device, dtype):pytest.skip(f"this torch build has no bilinear 2D grid_sample kernel for {dtype} on {device.type}")- if not self._has_cross_kernel(device, dtype):- pytest.skip(f"this torch build has no torch.linalg.cross kernel for {dtype} on {device.type}")# A keypoint is (x, y) in pixels: x indexes the columns (W) and y the rows (H). Image-content oracle: the# single bright pixel at row 2, column 8 of a 7 x 11 image is the keypoint (8, 2), and wherever the# augmentation moves that pixel, the transformed keypoint lands on it.diff --git a/tests/geometry/transform/test_homography_warper.py b/tests/geometry/transform/test_homography_warper.pyindex fac59068a..b21e67b95 100644--- a/tests/geometry/transform/test_homography_warper.py+++ b/tests/geometry/transform/test_homography_warper.py@@ -494,6 +494,25 @@ class TestHomographyNormalizePrecision(BaseTester):expected = dst_norm @ _torch_inverse_cast(src_norm)self.assert_close(out, expected, rtol=0.0, atol=1e-15)+ @pytest.mark.parametrize("side", [3000, 11600])+ def test_normalize_homography_of_a_large_image(self, device, dtype, side):+ # #5197: normalize_homography inverts the source normalization matrix, whose determinant 4 / (side - 1)**2 is+ # subnormal in float16 above about 256 px and rounds to zero there from about 11.6k px. The inverse ran+ # in float16, so the result was 6.8 % off at 3000 px and NaN at 11600 px; it now runs in float32 for half+ # input. Oracle: the same call in float64 on the CPU, on the same dtype-rounded homography. The bound is a+ # few roundings in `dtype` at the largest entry: the normalization matrices are built in `dtype` and the+ # chain of two products is rounded there.+ homography = torch.tensor([[[1.0, 0.02, 3.0], [0.01, 0.98, -2.0], [0.0, 0.0, 1.0]]], device=device, dtype=dtype)++ out = kornia.geometry.conversions.normalize_homography(homography, (side, side), (side, side))++ assert out.dtype == dtype+ expected = kornia.geometry.conversions.normalize_homography(+ homography.cpu().double(), (side, side), (side, side)+ )+ atol = 4 * torch.finfo(dtype).eps * expected.abs().max().item()+ self.assert_close(out.cpu().double(), expected, rtol=0.0, atol=atol)+def test_dtype_device_preserved(self, device, dtype):homo_2d = torch.eye(3, device=device, dtype=dtype)[None]homo_3d = torch.eye(4, device=device, dtype=dtype)[None]