Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

perf(feature): closed-form 2x2 inverse in ellipse_to_laf (#4122)

Dmytro Mishkin1331a861ee38
diff --git a/CHANGELOG.md b/CHANGELOG.md
index bcafb5e2a..35087a4c4 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -76,8 +76,37 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
they are subject to its check: a mask that is not at the image's spatial size, which used to be ignored, is
rejected. A floating-point mask changes meaning in `ScaleSpaceDetector`-based pipelines too, see below.
+* `ellipse_to_laf` no longer raises on a degenerate ellipse. One whose `a` or `c` is `0` after rounding to the input
+ dtype makes the matrix being inverted singular; the batched `torch.inverse` it now replaces (see below) failed the
+ whole call with `linalg.LinAlgError`, and the closed form returns non-finite values in that LAF instead, leaving
+ the other rows of the batch usable. Callers that relied on the exception to reject bad input -- reading
+ Oxford-format `.ellipse` files, say -- should test the result with `kornia.feature.laf_is_valid`, since an invalid
+ LAF otherwise propagates silently through `get_laf_scale` and into matching. Detecting the degenerate rows up front
+ would cost a device synchronisation and the `fullgraph=True` capture, so it is left to the caller. The in-repo
+ affine estimators handle invalid candidates before nonlinear LAF operations. `PatchAffineShapeEstimator` computes
+ half-precision gradients, Gaussian weights, moments, and normalization in `float32`, preserving valid anisotropic
+ shapes that would otherwise underflow; `LAFAffineShapeEstimator` sanitizes non-positive-definite ellipse
+ coefficients before conversion; and both it and `LAFAffNetShapeEstimator` use a finite fallback with finite
+ backward. The fallback is the input LAF when `preserve_orientation=True` and its upright form otherwise; a finite
+ zero-scale input keeps its center and zero affine block.
+
### Bug fixes
+* Replace the batched `torch.inverse` in `ellipse_to_laf` with the closed-form inverse of its lower-triangular
+ 2x2 matrix. Results agree with the previous implementation to ~1.6e-7 relative in `float32` (machine epsilon in
+ `float64`). Reproducible numbers via `benchmarks/feature/ellipse_to_laf.py` (float32, N=1e3..1e5, torch 2.9.1,
+ Linux/WSL2, base `2009933e`): throughput improves ~2.4-5.3x eager / ~3-6.5x compiled on CPU (i7-14700K) and
+ ~1.4-1.7x eager / ~4.2-5.5x compiled on CUDA (RTX 4090). The largest win is MPS, where the batched inverse hit a
+ pathological `linalg` path, emitted a deprecated-resize `UserWarning` on every call, and failed to `torch.compile`
+ (~1500x once measured ad hoc at N=20000 on Apple Silicon; rerun the benchmark there for a citable number). The
+ function now compiles with `fullgraph=True` on every backend and accepts `float16`/`bfloat16` on CPU, where the
+ raw `.inverse()` call raised for low-precision dtypes (`_torch_inverse_cast` would have lifted that restriction
+ too; the closed form is for speed). The off-diagonal divides `a21 = b / (a11 + a22)` by the product of the
+ diagonal square roots, which can neither overflow nor round to zero: every ordering of the reciprocal product
+ overflows to `inf` (or flushes a representable value to `0`) on a sufficiently lopsided or subnormal diagonal,
+ and when that product is subnormal the division loses precision but never corrupts a representable result to a
+ zero, `inf`, or `nan`.
+
* Make `load_pointcloud_ply` and `load_pointcloud_ply_binary` parse the PLY header instead of skipping a fixed
number of lines. Both loaders skipped `header_size=8` lines and read everything after them as `x y z` triples, so a
minimal PLY file (seven header lines, no `comment`) lost its first point to a header line -- the binary reader
diff --git a/benchmarks/README.md b/benchmarks/README.md
index 83105e071..5718238ca 100644
--- a/benchmarks/README.md
+++ b/benchmarks/README.md
@@ -12,7 +12,7 @@ baselines. Goal: current, citable numbers with disclosed methodology β€” where k
| [`geometry/`](geometry/) | [`flagship.py`](geometry/flagship.py): core geometry ops vs OpenCV/torchvision v2. |
| [`filters/`](filters/) | [`flagship.py`](filters/flagship.py): core filters vs OpenCV/albumentations/torchvision v2/kornia-rs/PIL. |
| [`color/`](color/) | pytest-benchmark microbenchmarks for color conversions. |
-| [`feature/`](feature/) | Local-feature detector benchmarks incl. quality (matching) metrics. |
+| [`feature/`](feature/) | Local-feature detector benchmarks incl. quality (matching) metrics; [`ellipse_to_laf.py`](feature/ellipse_to_laf.py) op microbenchmark (base-revision A/B, no cross-library baseline exists). |
| [`common.py`](common.py) | Shared methodology utilities β€” use these in every new benchmark. |
## Methodology contract
diff --git a/benchmarks/feature/ellipse_to_laf.py b/benchmarks/feature/ellipse_to_laf.py
new file mode 100644
index 000000000..bd259437d
--- /dev/null
+++ b/benchmarks/feature/ellipse_to_laf.py
@@ -0,0 +1,118 @@
+# LICENSE HEADER MANAGED BY add-license-header
+#
+# Copyright 2018 Kornia Team
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+"""Microbenchmark for ``kornia.feature.ellipse_to_laf``.
+
+No other library exposes this conversion, so there is no cross-library column: the baseline is
+the same script run on another kornia revision (see AGENTS.md, "Comparing a branch against
+another revision"). Running this file directly puts its own directory on ``sys.path[0]``, not the
+worktree root, so ``cd``-ing into the worktree does not shadow the editable install by itself --
+run with ``PYTHONPATH="$PWD"`` from the worktree root instead, and check that the header's
+printed module path names the worktree you meant.
+
+Input regime: a batch of well-conditioned Oxford-format ellipses ``(1, N, 5)`` in the given
+dtype, pinned seed. Throughput counts ellipses per second. The compiled column uses
+``torch.compile(fullgraph=True)``; a warmup failure is reported as a NOTE, never silently
+skipped.
+
+Usage:
+ python benchmarks/feature/ellipse_to_laf.py --device cpu
+ python benchmarks/feature/ellipse_to_laf.py --device cuda --compile --json ellipse_cuda.json
+ python benchmarks/feature/ellipse_to_laf.py --device mps --compile --dtype float32
+"""
+
+from __future__ import annotations
+
+import argparse
+import platform
+import sys
+from pathlib import Path
+from typing import Callable, Optional
+
+import torch
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
+from common import run_batch_sweep, run_metadata, save_json, versions_line
+
+import kornia.feature as KF
+
+Backend = Optional[Callable[[], object]]
+
+
+def make_ellipses(n: int, device: torch.device, dtype: torch.dtype) -> torch.Tensor:
+ """Well-conditioned Oxford-format ellipses ``(1, N, 5)``: [x, y, a, b, c], positive definite."""
+ torch.manual_seed(0)
+ ells = torch.rand(1, n, 5, device=device, dtype=dtype)
+ ells[..., 2] = ells[..., 3] + 0.3
+ ells[..., 4] += 1.0
+ return ells
+
+
+def build_ops(
+ n: int, device: torch.device, dtype: torch.dtype, do_compile: bool
+) -> tuple[dict[str, dict[str, Backend]], dict[str, str]]:
+ ells = make_ellipses(n, device, dtype)
+ row: dict[str, Backend] = {"kornia (eager)": lambda: KF.ellipse_to_laf(ells)}
+ compile_failures: dict[str, str] = {}
+ if do_compile:
+ # Reset dynamo so every sweep size compiles a fresh static-shape graph; without this the
+ # first size is timed on a static graph and later sizes on the automatic-dynamic recompile
+ # (~1.4x one-row bias). Mirrors test_dynamo_fullgraph in tests/feature/test_laf.py.
+ torch._dynamo.reset()
+ compiled = torch.compile(KF.ellipse_to_laf, fullgraph=True)
+ try:
+ compiled(ells)
+ row["kornia (compiled)"] = lambda: compiled(ells)
+ except Exception as e:
+ compile_failures["ellipse_to_laf"] = type(e).__name__
+ return {"ellipse_to_laf": row}, compile_failures
+
+
+def main() -> None:
+ parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
+ parser.add_argument("--device", default="cpu")
+ parser.add_argument("--dtype", default="float32", choices=["float16", "bfloat16", "float32", "float64"])
+ parser.add_argument("--sizes", default="1000,20000,100000", help="comma-separated N (ellipses per call)")
+ parser.add_argument("--compile", action="store_true", help="add a torch.compile(fullgraph=True) column")
+ parser.add_argument("--json", default=None, help="write results to this path as strict JSON")
+ args = parser.parse_args()
+
+ device = torch.device(args.device)
+ dtype = getattr(torch, args.dtype)
+ sizes = [int(s) for s in args.sizes.split(",")]
+ sync = torch.mps.synchronize if device.type == "mps" else None # blocked_autorange syncs CUDA itself
+
+ meta = run_metadata(device)
+ kornia_file = sys.modules["kornia"].__file__
+ print(f"# ellipse_to_laf | commit {meta['git_commit']} | {platform.platform()} | {device} | {args.dtype}")
+ print(f"# kornia module: {kornia_file}")
+ print(versions_line(meta))
+
+ backends = ["kornia (eager)"] + (["kornia (compiled)"] if args.compile else [])
+ results = run_batch_sweep(
+ sizes,
+ lambda n: build_ops(n, device, dtype, args.compile),
+ backends,
+ row_fields=lambda n: {"n": n, "dtype": args.dtype},
+ sync=sync,
+ )
+ if args.json:
+ out = save_json(args.json, {**meta, "kornia_module": kornia_file}, results)
+ print(f"# wrote {out}")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/docs/source/feature.rst b/docs/source/feature.rst
index 6fa742cc6..d75d1fe30 100644
--- a/docs/source/feature.rst
+++ b/docs/source/feature.rst
@@ -260,6 +260,7 @@ Local Affine Frames (LAF)
.. autofunction:: set_laf_orientation
.. autofunction:: laf_from_center_scale_ori
.. autofunction:: laf_is_inside_image
+.. autofunction:: laf_is_valid
.. autofunction:: laf_to_three_points
.. autofunction:: laf_from_three_points
.. autofunction:: KORNIA_CHECK_LAF
diff --git a/kornia/feature/__init__.py b/kornia/feature/__init__.py
index 21e081f39..6a3e28ed1 100644
--- a/kornia/feature/__init__.py
+++ b/kornia/feature/__init__.py
@@ -53,6 +53,7 @@ from .laf import (
laf_from_center_scale_ori,
laf_from_three_points,
laf_is_inside_image,
+ laf_is_valid,
laf_to_boundary_points,
laf_to_three_points,
make_upright,
@@ -166,6 +167,7 @@ __all__ = [
"laf_from_center_scale_ori",
"laf_from_three_points",
"laf_is_inside_image",
+ "laf_is_valid",
"laf_to_boundary_points",
"laf_to_three_points",
"make_upright",
diff --git a/kornia/feature/affine_shape.py b/kornia/feature/affine_shape.py
index 943611d63..f0b1f4c0a 100644
--- a/kornia/feature/affine_shape.py
+++ b/kornia/feature/affine_shape.py
@@ -31,6 +31,7 @@ from .laf import (
extract_patches_from_pyramid,
get_laf_orientation,
get_laf_scale,
+ laf_is_valid,
make_upright,
scale_laf,
set_laf_orientation,
@@ -48,6 +49,10 @@ class PatchAffineShapeEstimator(nn.Module):
The method determines the affine shape of the local feature as in :cite:`baumberg2000`.
+ For float16 and bfloat16 inputs, the gradients, Gaussian weighting, moments, and normalization are computed
+ in float32.
+ The output keeps the input dtype.
+
Args:
patch_size: the input image patch size.
eps: for safe division.
@@ -81,9 +86,24 @@ class PatchAffineShapeEstimator(nn.Module):
"""
KORNIA_CHECK_SHAPE(patch, ["B", "1", "H", "W"])
- # cast into a local; rebinding `self.weighting` would make the module's dtype/device depend
- # on whichever tensor was passed last.
- weighting = self.weighting.to(patch.dtype).to(patch.device)
+ dtype = patch.dtype
+ # Squared weighted gradients and the degeneracy threshold can underflow in half precision.
+ if dtype in (torch.float16, torch.bfloat16):
+ patch = patch.float()
+ # `.to(dtype)` also quantizes buffers, so rebuild this derived kernel instead of upcasting
+ # half-precision coefficients that have already lost their float32 precision.
+ sigma = float(self.patch_size) / math.sqrt(2.0)
+ weighting = get_gaussian_kernel2d(
+ (self.patch_size, self.patch_size),
+ (sigma, sigma),
+ True,
+ device=patch.device,
+ dtype=patch.dtype,
+ )
+ else:
+ # Cast into a local; rebinding `self.weighting` would make the module's dtype/device depend
+ # on whichever tensor was passed last.
+ weighting = self.weighting.to(device=patch.device, dtype=patch.dtype)
grads: torch.Tensor = self.gradient(patch) * weighting
# unpack the edges
gx: torch.Tensor = grads[:, :, 0]
@@ -99,13 +119,51 @@ class PatchAffineShapeEstimator(nn.Module):
)
# Now lets detect degenerate cases: when 2 or 3 elements are close to zero (e.g. if patch is completely black
- bad_mask = ((ellipse_shape < self.eps).float().sum(dim=2, keepdim=True) >= 2).to(ellipse_shape.dtype)
+ bad_mask = (ellipse_shape < self.eps).sum(dim=2, keepdim=True) >= 2
# We will replace degenerate shape with circular shapes.
- circular_shape = torch.tensor([1.0, 0.0, 1.0]).to(ellipse_shape.device).to(ellipse_shape.dtype).view(1, 1, 3)
- ellipse_shape = ellipse_shape * (1.0 - bad_mask) + circular_shape * bad_mask
+ circular_shape = ellipse_shape.new_tensor([1.0, 0.0, 1.0]).view(1, 1, 3)
+ ellipse_shape = torch.where(bad_mask, circular_shape, ellipse_shape)
# normalization
ellipse_shape = ellipse_shape / ellipse_shape.max(dim=2, keepdim=True)[0]
- return ellipse_shape
+ return ellipse_shape.to(dtype)
+
+
+def _sanitize_laf(laf: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
+ invalid = ~laf_is_valid(laf)
+ unit = laf.new_tensor([[1.0, 0.0], [0.0, 1.0]]).expand(*laf.shape[:2], -1, -1)
+ center = torch.where(laf[..., 2:3].isfinite(), laf[..., 2:3], torch.zeros_like(laf[..., 2:3]))
+ replacement = torch.cat([unit, center], dim=-1)
+ return torch.where(invalid[..., None, None], replacement, laf), invalid
+
+
+def _finalize_laf(
+ laf_out: torch.Tensor,
+ laf: torch.Tensor,
+ preserve_orientation: bool,
+ bad: torch.Tensor,
+ make_candidate_upright: bool = False,
+) -> torch.Tensor:
+ safe_input, invalid_input = _sanitize_laf(laf)
+ bad = bad | invalid_input
+ safe_fallback = safe_input if preserve_orientation else make_upright(safe_input)
+ if preserve_orientation:
+ fallback = laf
+ else:
+ zero_scale_upright = torch.cat([torch.zeros_like(laf[..., :2]), laf[..., 2:3]], dim=-1)
+ fallback = torch.where(invalid_input[..., None, None], zero_scale_upright, safe_fallback)
+ # This first selection is the backward-safety boundary: scale and orientation operations must only
+ # see nonsingular LAFs. Candidate upright conversion must stay between this selection and the final one.
+ safe_laf_out = torch.where(bad[..., None, None], safe_fallback, laf_out)
+ scale_orig = get_laf_scale(safe_input)
+ if preserve_orientation:
+ ori_orig = get_laf_orientation(safe_input)
+ ellipse_scale = get_laf_scale(safe_laf_out)
+ if make_candidate_upright:
+ safe_laf_out = make_upright(safe_laf_out)
+ safe_laf_out = scale_laf(safe_laf_out, scale_orig / ellipse_scale)
+ if preserve_orientation:
+ safe_laf_out = set_laf_orientation(safe_laf_out, ori_orig)
+ return torch.where(bad[..., None, None], fallback, safe_laf_out)
class LAFAffineShapeEstimator(nn.Module):
@@ -155,18 +213,25 @@ class LAFAffineShapeEstimator(nn.Module):
KORNIA_CHECK_SHAPE(img, ["B", "1", "H", "W"])
B, N = laf.shape[:2]
PS: int = self.patch_size
- patches: torch.Tensor = extract_patches_from_pyramid(img, make_upright(laf), PS, True).view(-1, 1, PS, PS)
+ safe_input, _ = _sanitize_laf(laf)
+ patches: torch.Tensor = extract_patches_from_pyramid(img, make_upright(safe_input), PS, True).view(
+ -1, 1, PS, PS
+ )
ellipse_shape: torch.Tensor = self.affine_shape_detector(patches)
- ellipses = torch.cat([laf.view(-1, 2, 3)[..., 2].unsqueeze(1), ellipse_shape], dim=2).view(B, N, 5)
- scale_orig = get_laf_scale(laf)
- if self.preserve_orientation:
- ori_orig = get_laf_orientation(laf)
+ ellipse_det = ellipse_shape[..., 0] * ellipse_shape[..., 2] - ellipse_shape[..., 1].square()
+ bad_shape = (
+ ~ellipse_shape.isfinite().all(dim=-1)
+ | ~ellipse_det.isfinite()
+ | (ellipse_shape[..., 0] <= 0)
+ | (ellipse_shape[..., 2] <= 0)
+ | (ellipse_det <= 0)
+ )
+ circular_shape = ellipse_shape.new_tensor([1.0, 0.0, 1.0])
+ safe_ellipse_shape = torch.where(bad_shape[..., None], circular_shape, ellipse_shape)
+ ellipses = torch.cat([laf.view(-1, 2, 3)[..., 2].unsqueeze(1), safe_ellipse_shape], dim=2).view(B, N, 5)
laf_out = ellipse_to_laf(ellipses)
- ellipse_scale = get_laf_scale(laf_out)
- laf_out = scale_laf(laf_out, scale_orig / ellipse_scale)
- if self.preserve_orientation:
- laf_out = set_laf_orientation(laf_out, ori_orig)
- return laf_out
+ bad = bad_shape.view(B, N) | ~laf_is_valid(laf_out)
+ return _finalize_laf(laf_out, laf, self.preserve_orientation, bad)
class LAFAffNetShapeEstimator(nn.Module):
@@ -242,17 +307,14 @@ class LAFAffNetShapeEstimator(nn.Module):
KORNIA_CHECK_SHAPE(img, ["B", "1", "H", "W"])
B, N = laf.shape[:2]
PS: int = self.patch_size
- patches: torch.Tensor = extract_patches_from_pyramid(img, make_upright(laf), PS, True).view(-1, 1, PS, PS)
+ safe_input, _ = _sanitize_laf(laf)
+ patches: torch.Tensor = extract_patches_from_pyramid(img, make_upright(safe_input), PS, True).view(
+ -1, 1, PS, PS
+ )
xy = self.features(self._normalize_input(patches)).view(-1, 3)
a1 = torch.cat([1.0 + xy[:, 0].reshape(-1, 1, 1), 0 * xy[:, 0].reshape(-1, 1, 1)], dim=2)
a2 = torch.cat([xy[:, 1].reshape(-1, 1, 1), 1.0 + xy[:, 2].reshape(-1, 1, 1)], dim=2)
new_laf_no_center = torch.cat([a1, a2], dim=1).reshape(B, N, 2, 2)
new_laf = torch.cat([new_laf_no_center, laf[:, :, :, 2:3]], dim=3)
- scale_orig = get_laf_scale(laf)
- if self.preserve_orientation:
- ori_orig = get_laf_orientation(laf)
- ellipse_scale = get_laf_scale(new_laf)
- laf_out = scale_laf(make_upright(new_laf), scale_orig / ellipse_scale)
- if self.preserve_orientation:
- laf_out = set_laf_orientation(laf_out, ori_orig)
- return laf_out
+ bad = ~laf_is_valid(new_laf)
+ return _finalize_laf(new_laf, laf, self.preserve_orientation, bad, make_candidate_upright=True)
diff --git a/kornia/feature/laf.py b/kornia/feature/laf.py
index ee3f40af6..701224a9e 100644
--- a/kornia/feature/laf.py
+++ b/kornia/feature/laf.py
@@ -47,6 +47,26 @@ def get_laf_scale(LAF: torch.Tensor) -> torch.Tensor:
return out.abs().sqrt()
+def laf_is_valid(laf: torch.Tensor) -> torch.Tensor:
+ """Check that each LAF is finite and has a finite, nonzero determinant.
+
+ Args:
+ laf: :math:`(B, N, 2, 3)`.
+
+ Returns:
+ validity mask :math:`(B, N)`.
+
+ Example:
+ >>> laf = torch.eye(2, 3).view(1, 1, 2, 3)
+ >>> laf_is_valid(laf)
+ tensor([[True]])
+
+ """
+ KORNIA_CHECK_LAF(laf)
+ det = laf[..., 0, 0] * laf[..., 1, 1] - laf[..., 1, 0] * laf[..., 0, 1]
+ return laf.isfinite().all(dim=-1).all(dim=-1) & det.isfinite() & (det != 0)
+
+
def get_laf_center(LAF: torch.Tensor) -> torch.Tensor:
"""Return a center (keypoint) of the LAFs.
@@ -228,6 +248,17 @@ def ellipse_to_laf(ells: torch.Tensor) -> torch.Tensor:
Returns:
LAF :math:`(B, N, 2, 3)`
+ Note:
+ A degenerate ellipse -- one whose ``a`` or ``c`` is ``0`` after rounding to ``ells.dtype`` --
+ describes an unbounded strip rather than a bounded region, and makes the matrix being inverted
+ singular. Its LAF is non-finite: ``inf`` always appears on the diagonal, while ``nan`` appears
+ only in the sub-case where the off-diagonal ``b`` is exactly ``0`` (``0 * inf``) -- the generic
+ degenerate ellipse is ``inf``-only, so screen results with :func:`laf_is_valid` rather than an
+ ``isnan`` test, which misses it. :func:`get_laf_scale` of such a LAF is non-finite as
+ well. The conversion does not raise. Rounding is part of the condition: in ``float16`` an ``a``
+ below roughly ``3e-8`` (half the smallest subnormal) rounds to ``0``, and a backend that
+ flushes subnormals to zero raises that cutoff to the smallest normal, about ``6e-5``.
+
Example:
>>> input = torch.ones(1, 10, 5) # BxNx5
>>> output = ellipse_to_laf(input) # BxNx2x3
@@ -248,10 +279,22 @@ def ellipse_to_laf(ells: torch.Tensor) -> torch.Tensor:
# M = (A 0; C D)
# R = (sqrt(A) 0; C / (sqrt(A)+sqrt(D)) sqrt(D))
a11 = ells[..., 2:3].abs().sqrt()
- a12 = torch.zeros_like(a11)
a22 = ells[..., 4:5].abs().sqrt()
- a21 = ells[..., 3:4] / (a11 + a22).clamp(1e-9)
- A = torch.stack([a11, a12, a21, a22], dim=-1).view(B, N, 2, 2).inverse()
+ a21 = ells[..., 3:4] / (a11 + a22)
+ # The matrix [[a11, 0], [a21, a22]] is lower-triangular, so its inverse is the closed form
+ # [[1/a11, 0], [-a21/(a11*a22), 1/a22]] β€” no batched torch.inverse, which is orders of
+ # magnitude slower, unsupported in float16/bfloat16 on CPU, and pathological on MPS.
+ inv11 = 1.0 / a11
+ inv22 = 1.0 / a22
+ # Divide by the product of the roots instead of multiplying the reciprocals: every ordering of
+ # `-a21 * inv11 * inv22` has an input region where an intermediate overflows to inf (or a
+ # mathematically-zero off-diagonal becomes 0 * inf = nan) or flushes a representable result to
+ # zero. a11 * a22 = sqrt(a) * sqrt(c) can neither overflow nor round to zero, so the single
+ # division is correctly rounded (not exact) wherever the product is a normal number; when the
+ # product is subnormal the result loses precision but is never a corrupted zero, inf, or nan.
+ # What remains non-finite is exactly the singular ellipse, which we deliberately do not guard.
+ inv21 = -a21 / (a11 * a22)
+ A = torch.stack([inv11, torch.zeros_like(inv11), inv21, inv22], dim=-1).view(B, N, 2, 2)
out = torch.cat([A, ells[..., :2].view(B, N, 2, 1)], dim=3)
return out
diff --git a/kornia/feature/scale_space_detector.py b/kornia/feature/scale_space_detector.py
index 14188ecf3..1a36796c7 100644
--- a/kornia/feature/scale_space_detector.py
+++ b/kornia/feature/scale_space_detector.py
@@ -173,10 +173,9 @@ def _zero_unfilled(lafs: torch.Tensor, filled: torch.Tensor) -> torch.Tensor:
r"""Replace the LAFs of the slots no detection filled with the zero LAF.
``filled`` is a ``(B, N)`` boolean mask of the slots a detection actually filled. The
- affine-shape and orientation modules normalise a frame, and a zero LAF comes out of
- :class:`LAFAffineShapeEstimator` as a finite 1e-5-scale frame at the origin, so the mask is
- re-applied after them. ``where`` rather than a multiply, so a module that returns NaN for a
- zero frame cannot leak it into the padding.
+ affine-shape and orientation modules may normalise or propagate invalid padding frames
+ differently by dtype, so the mask is re-applied after them. ``where`` rather than a multiply,
+ so a module that returns NaN for a zero frame cannot leak it into the padding.
Both detectors' ``forward`` read the mask off the LAFs that ``detect`` returns: a zero LAF is
the padding contract, and it is the one signal a subclass overriding ``detect`` also honours.
diff --git a/tests/feature/test_affine_shape_estimator.py b/tests/feature/test_affine_shape_estimator.py
index 71c5ecba2..c8d97d0db 100644
--- a/tests/feature/test_affine_shape_estimator.py
+++ b/tests/feature/test_affine_shape_estimator.py
@@ -15,15 +15,74 @@
# limitations under the License.
#
+import math
+
import pytest
import torch
from kornia.feature.affine_shape import LAFAffineShapeEstimator, LAFAffNetShapeEstimator, PatchAffineShapeEstimator
+from kornia.feature.laf import make_upright
+from kornia.filters import get_gaussian_kernel2d
+
+from testing.base import BaseTester, supports_grid_sample
+
+
+class DegenerateShape(torch.nn.Module):
+ def forward(self, patches: torch.Tensor) -> torch.Tensor:
+ shape = patches.mean(dim=(-2, -1), keepdim=False).unsqueeze(-1) * 0
+ return torch.cat([shape, shape, torch.ones_like(shape)], dim=-1)
-from testing.base import BaseTester
+
+class OverflowShape(torch.nn.Module):
+ def forward(self, patches: torch.Tensor) -> torch.Tensor:
+ one = patches.mean(dim=(-2, -1), keepdim=False).unsqueeze(-1) * 0 + 1
+ tiny = one * 1e-38
+ return torch.cat([tiny, one, tiny], dim=-1)
+
+
+class SingularAffNetOutput(torch.nn.Module):
+ def forward(self, patches: torch.Tensor) -> torch.Tensor:
+ zero = patches.mean(dim=(-3, -2, -1), keepdim=True) * 0
+ return torch.cat([zero - 1, zero, zero - 1], dim=1)
class TestPatchAffineShapeEstimator(BaseTester):
+ def test_zero_patch_uses_circular_shape(self, device, dtype):
+ patch = torch.zeros(1, 1, 32, 32, device=device, dtype=dtype)
+ out = PatchAffineShapeEstimator(32).to(device, dtype)(patch)
+ expected = torch.tensor([[[1.0, 0.0, 1.0]]], device=device, dtype=dtype)
+ self.assert_close(out, expected)
+
+ def test_half_precision_retains_anisotropic_shape(self, device, dtype):
+ if dtype not in (torch.float16, torch.bfloat16):
+ pytest.skip("half-precision regression test")
+ patch = torch.zeros(1, 1, 32, 32, device=device, dtype=dtype)
+ patch[:, :, 15:17, 9:23] = 1
+ expected = PatchAffineShapeEstimator(32).to(device)(patch.float()).to(dtype)
+ patch.requires_grad_()
+
+ out = PatchAffineShapeEstimator(32).to(device, dtype)(patch)
+
+ assert out.dtype == dtype
+ self.assert_close(out, expected)
+ out.sum().backward()
+ assert patch.grad is not None
+ assert torch.isfinite(patch.grad).all()
+
+ def test_half_precision_uses_float32_weighting(self, device, dtype):
+ if dtype not in (torch.float16, torch.bfloat16):
+ pytest.skip("half-precision regression test")
+ patch = torch.zeros(1, 1, 32, 32, device=device, dtype=dtype)
+ patch[:, :, 2:4, 14:16] = 1
+ reference = PatchAffineShapeEstimator(32).to(device)
+ sigma = 32.0 / math.sqrt(2.0)
+ reference.weighting = get_gaussian_kernel2d((32, 32), (sigma, sigma), True, device=device, dtype=torch.float32)
+ expected = reference(patch.float()).to(dtype)
+
+ out = PatchAffineShapeEstimator(32).to(device, dtype)(patch)
+
+ assert torch.equal(out, expected)
+
def test_shape(self, device):
inp = torch.rand(1, 1, 32, 32, device=device)
ori = PatchAffineShapeEstimator(32).to(device)
@@ -107,7 +166,11 @@ class TestLAFAffineShapeEstimator(BaseTester):
laf = torch.tensor([[[[20.0, 0.0, 16.0], [0.0, 20.0, 16.0]]]], device=device, dtype=dtype)
new_laf = aff(laf, inp)
expected = torch.tensor([[[[35.078, 0.0, 16.0], [0.0, 11.403, 16.0]]]], device=device, dtype=dtype)
- self.assert_close(new_laf, expected, atol=1e-4, rtol=1e-4)
+ if dtype in (torch.float16, torch.bfloat16):
+ # Use the repository's dtype-specific tolerances for the newly supported half-precision path.
+ self.assert_close(new_laf, expected)
+ else:
+ self.assert_close(new_laf, expected, atol=1e-4, rtol=1e-4)
def test_toy_preserve(self, device, dtype):
aff = LAFAffineShapeEstimator(32, preserve_orientation=True).to(device, dtype)
@@ -116,7 +179,11 @@ class TestLAFAffineShapeEstimator(BaseTester):
laf = torch.tensor([[[[0.0, 20.0, 16.0], [-20.0, 0.0, 16.0]]]], device=device, dtype=dtype)
new_laf = aff(laf, inp)
expected = torch.tensor([[[[0.0, 35.078, 16.0], [-11.403, 0, 16.0]]]], device=device, dtype=dtype)
- self.assert_close(new_laf, expected, atol=1e-4, rtol=1e-4)
+ if dtype in (torch.float16, torch.bfloat16):
+ # Orientation recovery adds small absolute noise to entries whose ideal value is zero.
+ self.assert_close(new_laf, expected, atol=2e-2, rtol=1e-3 if dtype == torch.float16 else 7.8e-3)
+ else:
+ self.assert_close(new_laf, expected, atol=1e-4, rtol=1e-4)
def test_toy_not_preserve(self, device):
aff = LAFAffineShapeEstimator(32, preserve_orientation=False).to(device)
@@ -127,6 +194,86 @@ class TestLAFAffineShapeEstimator(BaseTester):
expected = torch.tensor([[[[35.078, 0, 16.0], [0, 11.403, 16.0]]]], device=device)
self.assert_close(new_laf, expected, atol=1e-4, rtol=1e-4)
+ def test_degenerate_ellipse_falls_back_to_input_laf_float16(self, device, dtype):
+ if dtype != torch.float16:
+ pytest.skip("float16 regression test")
+ # The default patch estimator now catches this nearly one-dimensional patch at the source.
+ # Keep the end-to-end assertion to pin the public finite-value and finite-gradient boundary.
+ if device.type == "mps":
+ pytest.skip("MPS autocast changes the effective dtype")
+ if not supports_grid_sample(device, dtype):
+ # Patch extraction still runs in the input dtype; the moment estimator promotes to float32.
+ pytest.skip(f"no float16 grid_sample kernel on {device.type}")
+ y = torch.linspace(0, 1, 32, device=device, dtype=dtype).view(32, 1).expand(32, 32)
+ x = torch.linspace(0, 1e-4, 32, device=device, dtype=dtype).view(1, 32).expand(32, 32)
+ img = (y + x).view(1, 1, 32, 32).clone().requires_grad_()
+ laf = torch.tensor([[[[8.0, 0.0, 16.0], [0.0, 8.0, 16.0]]]], device=device, dtype=dtype, requires_grad=True)
+ out = LAFAffineShapeEstimator(32).to(device, dtype)(laf, img)
+ assert torch.isfinite(out).all()
+ self.assert_close(out, laf)
+ out.sum().backward()
+ assert img.grad is not None
+ assert torch.isfinite(img.grad).all()
+ assert laf.grad is not None
+ assert torch.isfinite(laf.grad).all()
+
+ @pytest.mark.parametrize("preserve_orientation", [False, True])
+ def test_zero_scale_input_has_finite_fallback(self, device, dtype, preserve_orientation):
+ if dtype not in (torch.float16, torch.bfloat16):
+ pytest.skip("half-precision regression test")
+ if device.type == "mps":
+ pytest.skip("MPS autocast changes the effective dtype")
+ if not supports_grid_sample(device, dtype):
+ pytest.skip(f"no {dtype} grid_sample kernel on {device.type}")
+ img = torch.rand(1, 1, 32, 32, device=device, dtype=dtype, requires_grad=True)
+ laf = torch.tensor([[[[0.0, 0.0, 16.0], [0.0, 0.0, 16.0]]]], device=device, dtype=dtype, requires_grad=True)
+ aff = LAFAffineShapeEstimator(32, DegenerateShape(), preserve_orientation=preserve_orientation).to(
+ device, dtype
+ )
+
+ out = aff(laf, img)
+
+ assert torch.isfinite(out).all()
+ self.assert_close(out, laf)
+ out.sum().backward()
+ assert img.grad is not None
+ assert torch.isfinite(img.grad).all()
+ assert laf.grad is not None
+ assert torch.isfinite(laf.grad).all()
+
+ def test_degenerate_ellipse_boundary_has_finite_backward(self, device):
+ dtype = torch.float32
+ img = torch.rand(1, 1, 32, 32, device=device, dtype=dtype, requires_grad=True)
+ laf = torch.tensor([[[[8.0, 0.0, 16.0], [0.0, 8.0, 16.0]]]], device=device, dtype=dtype, requires_grad=True)
+ out = LAFAffineShapeEstimator(32, DegenerateShape(), preserve_orientation=True).to(device, dtype)(laf, img)
+ assert torch.isfinite(out).all()
+ self.assert_close(out, laf)
+ out.sum().backward()
+ assert img.grad is not None
+ assert torch.isfinite(img.grad).all()
+ assert laf.grad is not None
+ assert torch.isfinite(laf.grad).all()
+
+ def test_non_positive_definite_shape_falls_back_with_finite_backward(self, device):
+ dtype = torch.float32
+ img = torch.rand(1, 1, 32, 32, device=device, dtype=dtype, requires_grad=True)
+ laf = torch.tensor([[[[8.0, 0.0, 16.0], [0.0, 8.0, 16.0]]]], device=device, dtype=dtype, requires_grad=True)
+ out = LAFAffineShapeEstimator(32, OverflowShape(), preserve_orientation=True).to(device, dtype)(laf, img)
+ assert torch.isfinite(out).all()
+ self.assert_close(out, laf)
+ out.sum().backward()
+ assert img.grad is not None
+ assert torch.isfinite(img.grad).all()
+ assert laf.grad is not None
+ assert torch.isfinite(laf.grad).all()
+
+ def test_degenerate_ellipse_fallback_respects_upright_contract(self, device):
+ dtype = torch.float32
+ img = torch.rand(1, 1, 32, 32, device=device, dtype=dtype)
+ laf = torch.tensor([[[[0.0, 8.0, 16.0], [-8.0, 0.0, 16.0]]]], device=device, dtype=dtype)
+ out = LAFAffineShapeEstimator(32, DegenerateShape(), preserve_orientation=False).to(device, dtype)(laf, img)
+ self.assert_close(out, make_upright(laf))
+
def test_gradcheck(self, device):
batch_size, channels, height, width = 1, 1, 40, 40
patches = torch.rand(batch_size, channels, height, width, device=device, dtype=torch.float64)
@@ -141,6 +288,39 @@ class TestLAFAffineShapeEstimator(BaseTester):
class TestLAFAffNetShapeEstimator(BaseTester):
+ def test_singular_prediction_falls_back_upright(self, device, dtype):
+ if dtype in (torch.float16, torch.bfloat16) and not supports_grid_sample(device, dtype):
+ pytest.skip(f"no {dtype} grid_sample kernel on {device.type}")
+ img = torch.rand(1, 1, 32, 32, device=device, dtype=dtype)
+ laf = torch.tensor([[[[0.0, 8.0, 16.0], [-8.0, 0.0, 16.0]]]], device=device, dtype=dtype)
+ aff = LAFAffNetShapeEstimator(preserve_orientation=False).to(device, dtype)
+ aff.features = SingularAffNetOutput()
+ out = aff(laf, img)
+ self.assert_close(out, make_upright(laf))
+
+ @pytest.mark.parametrize("preserve_orientation", [False, True])
+ def test_zero_scale_input_has_finite_fallback(self, device, dtype, preserve_orientation):
+ if dtype not in (torch.float16, torch.bfloat16):
+ pytest.skip("half-precision regression test")
+ if device.type == "mps":
+ pytest.skip("MPS autocast changes the effective dtype")
+ if not supports_grid_sample(device, dtype):
+ pytest.skip(f"no {dtype} grid_sample kernel on {device.type}")
+ img = torch.rand(1, 1, 32, 32, device=device, dtype=dtype, requires_grad=True)
+ laf = torch.tensor([[[[0.0, 0.0, 16.0], [0.0, 0.0, 16.0]]]], device=device, dtype=dtype, requires_grad=True)
+ aff = LAFAffNetShapeEstimator(pretrained=False, preserve_orientation=preserve_orientation).to(device, dtype)
+ aff.features = SingularAffNetOutput()
+
+ out = aff(laf, img)
+
+ assert torch.isfinite(out).all()
+ self.assert_close(out, laf)
+ out.sum().backward()
+ assert img.grad is not None
+ assert torch.isfinite(img.grad).all()
+ assert laf.grad is not None
+ assert torch.isfinite(laf.grad).all()
+
def test_shape(self, device):
inp = torch.rand(1, 1, 32, 32, device=device)
laf = torch.rand(1, 1, 2, 3, device=device)
diff --git a/tests/feature/test_laf.py b/tests/feature/test_laf.py
index c0cb152ae..74549dc87 100644
--- a/tests/feature/test_laf.py
+++ b/tests/feature/test_laf.py
@@ -15,13 +15,15 @@
# limitations under the License.
#
+import math
+
import pytest
import torch
import kornia
import kornia.geometry.transform.imgwarp
-from testing.base import BaseTester
+from testing.base import DYNAMO_UNAVAILABLE_REASON, BaseTester, dynamo_is_available
from testing.geometry.create import create_random_homography
@@ -265,6 +267,105 @@ class TestELL2LAF(BaseTester):
# assure it is positive definite
self.gradcheck(kornia.feature.ellipse_to_laf, (img,))
+ def test_small_root_sum_is_not_clamped(self, device):
+ # The root sum is finite and nonzero, so clamping it changes a valid inverse by orders of magnitude.
+ tiny = torch.finfo(torch.float32).tiny
+ inp = torch.tensor([[[0.0, 0.0, tiny, tiny, tiny]]], device=device, dtype=torch.float32)
+ expected = torch.tensor(-0.5 / math.sqrt(tiny), device=device, dtype=torch.float32)
+ laf = kornia.feature.ellipse_to_laf(inp)
+ assert torch.isfinite(laf).all()
+ self.assert_close(laf[0, 0, 1, 0], expected)
+
+ def test_no_overflow_asymmetric_diag(self, device, dtype):
+ # Regression test: the closed-form inverse's off-diagonal must divide by the root product,
+ # not multiply reciprocals. `a` is the dtype's smallest normal and `c` is picked so that
+ # (sqrt(a) + sqrt(c)) * sqrt(a) == 0.5, which makes the intermediate of the fixed order
+ # `-a21 * (1 / a11) * (1 / a22)` twice b -- inf for a b above half the dtype's maximum,
+ # although the result itself is well inside range. https://github.com/kornia/kornia/pull/4122
+ finfo = torch.finfo(dtype)
+ a11 = math.sqrt(finfo.tiny)
+ a22 = 0.5 / a11
+ inp = torch.tensor([[[0.0, 0.0, finfo.tiny, finfo.max * 0.75, a22 * a22]]], device=device, dtype=dtype)
+ # Reference in float64, from the inputs as the dtype actually rounded them. Via CPU:
+ # MPS tensors cannot be converted to float64 (TESTING.md, "Writing new tests that work on MPS").
+ expected = kornia.feature.ellipse_to_laf(inp.cpu().double())[0, 0, 1, 0]
+ laf = kornia.feature.ellipse_to_laf(inp)
+ assert torch.isfinite(laf).all()
+ self.assert_close(laf[0, 0, 1, 0], expected.to(device=device, dtype=dtype))
+
+ def test_no_overflow_subnormal_diag(self, device, dtype):
+ # The mirror case: a subnormal but nondegenerate diagonal makes 1 / (a11 * a22) overflow, so
+ # forming that product first turns a mathematically-zero off-diagonal into 0 * inf = nan.
+ # Subnormal input is unavoidable here -- a11 * a22 >= finfo.tiny > 1 / finfo.max in every IEEE
+ # dtype, so no normal input reaches this regime -- hence the flush-to-zero guard below.
+ finfo = torch.finfo(dtype)
+ a = finfo.tiny / 8 # subnormal, and small enough that 1 / (a11 * a22) == 1 / a overflows
+ inp = torch.tensor([[[0.0, 0.0, a, 0.0, a]]], device=device, dtype=dtype)
+ # Guard on the arithmetic, not just the storage: a backend can store the subnormal
+ # faithfully yet flush it inside sqrt, which makes the diagonal degenerate all the same.
+ if inp[0, 0, 2].sqrt() == 0:
+ pytest.skip("backend flushes subnormals to zero, so this diagonal is degenerate here")
+ laf = kornia.feature.ellipse_to_laf(inp)
+ assert torch.isfinite(laf).all()
+ self.assert_close(laf[0, 0, 1, 0], torch.zeros_like(laf[0, 0, 1, 0]))
+
+ def test_no_underflow_asymmetric_diag(self, device, dtype):
+ # Regression test for the ordering the two tests above do not cover: multiplying by the
+ # smaller reciprocal first (f7b573a3, since replaced by the division form) passes both of
+ # them but silently flushes a representable off-diagonal to a false zero. `a` is the
+ # dtype's smallest normal and `c` its reciprocal squared, so a11 * a22 == 1 and
+ # inv22 == a11 is itself tiny; `b` is picked so a21 * inv22 -- the min/max order's first
+ # product -- underflows to zero while the true off-diagonal, a21 / (a11 * a22), stays
+ # representable. https://github.com/kornia/kornia/pull/4122
+ finfo = torch.finfo(dtype)
+ a11 = math.sqrt(finfo.tiny)
+ a22 = 1.0 / a11
+ b = finfo.eps * math.sqrt(a11)
+ inp = torch.tensor([[[0.0, 0.0, finfo.tiny, b, a22 * a22]]], device=device, dtype=dtype)
+ # Guard on the arithmetic, not just the storage: a21 is shared by every ordering, so if a
+ # backend's division already flushes it to zero, no ordering has anything left to get wrong.
+ a11_t, a22_t = inp[..., 2:3].abs().sqrt(), inp[..., 4:5].abs().sqrt()
+ a21_t = inp[..., 3:4] / (a11_t + a22_t)
+ if (a21_t == 0).any():
+ pytest.skip("backend flushes this off-diagonal's shared numerator to zero regardless of ordering")
+ expected = kornia.feature.ellipse_to_laf(inp.cpu().double())[0, 0, 1, 0]
+ laf = kornia.feature.ellipse_to_laf(inp)
+ assert torch.isfinite(laf).all()
+ # Loose relative tolerance: the point is distinguishing a false zero (100% off) from the
+ # real value, not pinning float16's reduced precision this deep into its subnormal range.
+ self.assert_close(laf[0, 0, 1, 0], expected.to(device=device, dtype=dtype), rtol=0.1, atol=0.0)
+
+ @pytest.mark.parametrize("degenerate_index", [2, 4])
+ def test_degenerate_ellipse_is_non_finite(self, device, dtype, degenerate_index):
+ # A degenerate ellipse makes the matrix singular. The batched torch.inverse this replaced
+ # raised linalg.LinAlgError; the closed form returns non-finite values and must not raise.
+ inp = torch.tensor([[[1.0, 2.0, 3.0, 0.5, 4.0]]], device=device, dtype=dtype)
+ inp[0, 0, degenerate_index] = 0.0
+ laf = kornia.feature.ellipse_to_laf(inp)
+ assert not torch.isfinite(laf[0, 0, :, :2]).all()
+ self.assert_close(laf[0, 0, :, 2], inp[0, 0, :2]) # the centre is untouched
+
+ def test_dynamo(self, device, dtype, torch_optimizer):
+ inp = self._well_conditioned_ellipses(device, dtype)
+ op = kornia.feature.ellipse_to_laf
+ self.assert_close(torch_optimizer(op)(inp), op(inp))
+
+ @pytest.mark.skipif(not dynamo_is_available(), reason=DYNAMO_UNAVAILABLE_REASON)
+ def test_dynamo_fullgraph(self, device, dtype):
+ # The batched torch.inverse this replaced graph-broke; the closed form must stay capturable.
+ inp = self._well_conditioned_ellipses(device, dtype)
+ expected = kornia.feature.ellipse_to_laf(inp)
+ torch._dynamo.reset()
+ compiled = torch.compile(kornia.feature.ellipse_to_laf, fullgraph=True)
+ self.assert_close(compiled(inp), expected)
+
+ @staticmethod
+ def _well_conditioned_ellipses(device, dtype):
+ inp = torch.rand(1, 2, 5, device=device, dtype=dtype).abs()
+ inp[..., 2] = inp[..., 3].abs() + 0.3
+ inp[..., 4] += 1.0
+ return inp
+
@pytest.mark.jit()
def test_jit(self, device, dtype):
batch_size, channels, height = 1, 2, 5
@@ -276,6 +377,30 @@ class TestELL2LAF(BaseTester):
self.assert_close(model(img), model_jit(img))
+class TestLAFIsValid(BaseTester):
+ def test_finite_nonsingular_laf_is_valid(self, device, dtype):
+ laf = torch.tensor([[[[2.0, 0.0, 1.0], [0.0, 3.0, 2.0]]]], device=device, dtype=dtype)
+ assert kornia.feature.laf_is_valid(laf).all()
+
+ def test_nonfinite_or_singular_laf_is_invalid(self, device, dtype):
+ laf = torch.tensor(
+ [[[[2.0, 0.0, 1.0], [0.0, 3.0, 2.0]], [[1.0, 2.0, 0.0], [2.0, 4.0, 0.0]]]],
+ device=device,
+ dtype=dtype,
+ )
+ laf[0, 0, 0, 0] = torch.inf
+ expected = torch.tensor([[False, False]], device=device)
+ assert torch.equal(kornia.feature.laf_is_valid(laf), expected)
+
+ @pytest.mark.skipif(not dynamo_is_available(), reason=DYNAMO_UNAVAILABLE_REASON)
+ def test_dynamo_fullgraph(self, device, dtype):
+ laf = torch.tensor([[[[2.0, 0.0, 1.0], [0.0, 3.0, 2.0]]]], device=device, dtype=dtype)
+ expected = kornia.feature.laf_is_valid(laf)
+ torch._dynamo.reset()
+ compiled = torch.compile(kornia.feature.laf_is_valid, fullgraph=True)
+ assert torch.equal(compiled(laf), expected)
+
+
class TestNormalizeLAF(BaseTester):
def test_shape(self, device):
inp = torch.rand(5, 3, 2, 3)
diff --git a/tests/feature/test_scale_space_detector.py b/tests/feature/test_scale_space_detector.py
index 7d551a1f6..6c2876b54 100644
--- a/tests/feature/test_scale_space_detector.py
+++ b/tests/feature/test_scale_space_detector.py
@@ -29,7 +29,23 @@ from kornia.feature.scale_space_detector import (
)
from kornia.geometry.subpix import ConvQuadInterp3d
-from testing.base import BaseTester, supports_replicate_padding, supports_topk
+from testing.base import BaseTester, supports_conv2d, supports_grid_sample, supports_replicate_padding, supports_topk
+
+
+def _require_affine_orientation_kernels(device: torch.device, dtype: torch.dtype) -> None:
+ if dtype not in (torch.float16, torch.bfloat16):
+ return
+ if device.type == "mps":
+ pytest.skip("MPS autocast changes the effective dtype")
+ probes = (
+ ("replicate-padding", supports_replicate_padding),
+ ("conv2d", supports_conv2d),
+ ("grid-sample", supports_grid_sample),
+ ("topk", supports_topk),
+ )
+ for name, probe in probes:
+ if not probe(device, dtype):
+ pytest.skip(f"no {name} kernel for {dtype} on {device.type}")
class TestScaleSpaceDetector(BaseTester):
@@ -360,9 +376,8 @@ class TestScaleSpaceDetector(BaseTester):
def test_padding_survives_the_affine_and_orientation_modules(self, device, dtype):
# Same contract as `MultiResolutionDetector.forward`: the shape and orientation modules
- # normalise a zero frame into a finite one, so the padding is re-applied after them.
- if dtype in (torch.float16, torch.bfloat16):
- pytest.skip("LAFAffineShapeEstimator uses linalg.inv, which has no half-precision kernel")
+ # may transform a zero frame differently by dtype, so the padding is re-applied after them.
+ _require_affine_orientation_kernels(device, dtype)
det = ScaleSpaceDetector(
10, aff_module=kornia.feature.LAFAffineShapeEstimator(19), ori_module=kornia.feature.LAFOrienter(19)
).to(device, dtype)
@@ -722,10 +737,9 @@ class TestMultiResolutionDetector(BaseTester):
assert not torch.equal(resps_bool, resps_free)
def test_padding_survives_the_affine_and_orientation_modules(self, device, dtype):
- # `forward` runs `aff` and `ori` after `detect`; `LAFAffineShapeEstimator` normalises a
- # zero frame into a finite 1e-5-scale one, so the zero-LAF contract has to be re-applied.
- if dtype in (torch.float16, torch.bfloat16):
- pytest.skip("LAFAffineShapeEstimator uses linalg.inv, which has no half-precision kernel")
+ # `forward` runs `aff` and `ori` after `detect`; they may transform a zero frame differently
+ # by dtype, so the zero-LAF contract has to be re-applied.
+ _require_affine_orientation_kernels(device, dtype)
det = MultiResolutionDetector(
kornia.feature.BlobHessian(),
num_features=10,