Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(subpix): make iterative_quad_interp3d's max_candidates cap per image (closes #4256) (#4350)

Dipak Chaudharif80f5478de8f
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 3581fce35..11d596fa8 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -385,6 +385,14 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
`eps=1e-8` is below float16 resolution, so half-precision callers must pass a representable `eps`.
(#4280, #4348)
+* `iterative_quad_interp3d`'s `max_candidates` cap is now a per-image budget rather than one shared
+ across the batch. The `topk` ranked the flattened `(B*C)` candidate list, so an image's refined
+ keypoints depended on which other images shared its batch: a quiet image next to a high-contrast
+ one got none. This also reaches `IterativeQuadInterp3d` and `AdaptiveQuadInterp3d` in `patch` mode.
+ The docstring already read as a per-image budget. A negative `max_candidates` now raises
+ `ValueError`; it previously raised a `topk` `RuntimeError`, and under the per-image ranking it
+ would otherwise have silently disabled refinement instead. (#4256, #4350)
+
* `RenderingDeFMO` (used by `DeFMO`) no longer crashes on a half-precision forward pass. Its rendering
time-steps (`times`) were a plain Python attribute, not a registered buffer, so `nn.Module.to()` never
moved it; `forward` re-derived `times`'s device from the input on every call but never its dtype, so
diff --git a/kornia/geometry/subpix/spatial_soft_argmax.py b/kornia/geometry/subpix/spatial_soft_argmax.py
index 884d78ab1..d65e8a259 100644
--- a/kornia/geometry/subpix/spatial_soft_argmax.py
+++ b/kornia/geometry/subpix/spatial_soft_argmax.py
@@ -1051,7 +1051,7 @@ def iterative_quad_interp3d(
making the per-candidate gather+solve loop the dominant CPU cost. Setting
``max_candidates = num_features * 5`` (say) dramatically reduces that work
at the cost of occasionally missing a feature whose response rank would have
- improved after refinement.
+ improved after refinement. Must be non-negative; ``0`` refines nothing.
Returns:
A tuple ``(coords_max, y_max)`` where
@@ -1075,6 +1075,8 @@ def iterative_quad_interp3d(
raise TypeError(f"Input type is not a torch.Tensor. Got {type(input)}")
if input.ndim != 5:
raise ValueError(f"Invalid input shape, expected BxCxDxHxW. Got: {input.shape}")
+ if max_candidates is not None and max_candidates < 0:
+ raise ValueError(f"max_candidates must be non-negative. Got: {max_candidates}")
B, C, D, H, W = input.shape
device = input.device
@@ -1108,14 +1110,26 @@ def iterative_quad_interp3d(
# few hundred features are ultimately needed. The per-candidate patch gather
# (random memory access into a multi-MB volume) is cache-miss dominated on CPU;
# reducing N here gives a proportional speedup of the iteration loop below.
+ # The cap is per image, not over the flattened batch: a global topk would make
+ # one image's refined keypoints depend on which other images share its batch,
+ # so a quiet image next to a high-contrast one would get none. N <= the cap is
+ # the fast path, because then no row can be over it either.
if max_candidates is not None and N > max_candidates:
cand_vals = inp[bc_idx, d_idx, h_idx, w_idx] # (N,) pre-refinement responses
- _, keep = torch.topk(cand_vals, k=max_candidates)
+ # Sort by response, then stably by row: within each row the candidates
+ # stay in descending-response order, so a positional rank inside the row
+ # is the same ranking the global topk used, taken one image at a time.
+ by_value = torch.argsort(cand_vals, descending=True, stable=True)
+ grouped = by_value[torch.argsort(bc_idx[by_value], stable=True)]
+ counts = torch.bincount(bc_idx, minlength=B * C)
+ row_start = torch.cumsum(counts, 0) - counts
+ rank = torch.arange(N, device=device) - row_start[bc_idx[grouped]]
+ keep = grouped[rank < max_candidates]
bc_idx = bc_idx[keep]
d_idx = d_idx[keep]
h_idx = h_idx[keep]
w_idx = w_idx[keep]
- N = max_candidates
+ N = int(keep.shape[0])
patch_offsets = _PATCH_DD.to(device) * HW + _PATCH_DH.to(device) * W + _PATCH_DW.to(device)
diff --git a/tests/geometry/subpix/test_iterative_quad_interp_pyhesaff.py b/tests/geometry/subpix/test_iterative_quad_interp_pyhesaff.py
index 1d4aee9e3..fc1127a17 100644
--- a/tests/geometry/subpix/test_iterative_quad_interp_pyhesaff.py
+++ b/tests/geometry/subpix/test_iterative_quad_interp_pyhesaff.py
@@ -33,7 +33,7 @@ import pytest
import torch
from kornia.geometry.subpix.nms import nms3d
-from kornia.geometry.subpix.spatial_soft_argmax import conv_quad_interp3d
+from kornia.geometry.subpix.spatial_soft_argmax import conv_quad_interp3d, iterative_quad_interp3d
# ---------------------------------------------------------------------------
# Helpers
@@ -194,3 +194,54 @@ class TestIterativeQuadInterp3dAccuracy:
ours_y = coords[0, 0, 2, d_peak, h_int, w_int].item()
assert abs(ours_x - bx) < 0.1, f"blob ({bx},{by}): x ours={ours_x:.3f}"
assert abs(ours_y - by) < 0.1, f"blob ({bx},{by}): y ours={ours_y:.3f}"
+
+
+class TestIterativeQuadInterp3dMaxCandidates:
+ """The candidate cap is a per-image budget, not a budget over the batch."""
+
+ def test_cap_is_per_image_not_per_batch(self) -> None:
+ """One image's refinement must not depend on its batch-mates.
+
+ The cap used to rank the flattened (B*C) candidate list, so a quiet
+ image next to a high-contrast one lost its whole budget to the other
+ image and came back unrefined.
+ """
+ torch.manual_seed(0)
+ x = torch.rand(2, 1, 5, 40, 40)
+ x[1] *= 10 # every candidate here outranks every candidate in image 0
+
+ coords_batched, vals_batched = iterative_quad_interp3d(x, max_candidates=50)
+ coords_0, vals_0 = iterative_quad_interp3d(x[:1], max_candidates=50)
+ coords_1, vals_1 = iterative_quad_interp3d(x[1:], max_candidates=50)
+
+ assert torch.equal(coords_batched[:1], coords_0)
+ assert torch.equal(vals_batched[:1], vals_0)
+ assert torch.equal(coords_batched[1:], coords_1)
+ assert torch.equal(vals_batched[1:], vals_1)
+
+ def test_cap_still_bounds_the_work_per_image(self) -> None:
+ """A per-image cap must still cap: refine at most K positions per image."""
+ torch.manual_seed(0)
+ x = torch.rand(2, 1, 5, 40, 40)
+ cap = 10
+
+ coords, _ = iterative_quad_interp3d(x, max_candidates=cap)
+ unrefined, _ = iterative_quad_interp3d(x, max_candidates=0)
+ # A position is refined when its coordinates moved off the integer grid
+ # that max_candidates=0 leaves everywhere.
+ moved = (coords != unrefined).any(dim=2).flatten(1).sum(dim=1)
+ assert (moved <= cap).all(), f"refined {moved.tolist()} positions with cap {cap}"
+
+ @pytest.mark.parametrize("cap", [-1, -50])
+ def test_negative_cap_is_rejected(self, cap: int) -> None:
+ """A negative budget is an error, not a silent no-op.
+
+ Ranking per image compares a positional rank against the cap, so a
+ negative cap would select nothing and return every candidate
+ unrefined -- quietly disabling refinement. Before the per-image
+ ranking, ``torch.topk`` rejected it with a ``RuntimeError``; keep it
+ an error, with a message that names the argument.
+ """
+ x = torch.rand(1, 1, 5, 10, 10)
+ with pytest.raises(ValueError, match="max_candidates must be non-negative"):
+ iterative_quad_interp3d(x, max_candidates=cap)