Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(geometry): deprecate and ignore strict_maxima_bonus in the 3D subpixel refiners (#5045)

Dmytro Mishkin9ba1c7e5f304
diff --git a/benchmarks/feature/scale_space_detector.py b/benchmarks/feature/scale_space_detector.py
index 4dd857316..ce79e7f23 100644
--- a/benchmarks/feature/scale_space_detector.py
+++ b/benchmarks/feature/scale_space_detector.py
@@ -139,9 +139,9 @@ RESP_REGISTRY: dict[str, tuple] = {
}
SUBPIX_REGISTRY: dict[str, Callable] = {
- "adaptive": lambda: AdaptiveQuadInterp3d(strict_maxima_bonus=0.0, allow_scale_steps=True),
- "conv": lambda: ConvQuadInterp3d(strict_maxima_bonus=0.0),
- "iterative": lambda: IterativeQuadInterp3d(strict_maxima_bonus=0.0),
+ "adaptive": lambda: AdaptiveQuadInterp3d(allow_scale_steps=True),
+ "conv": ConvQuadInterp3d,
+ "iterative": IterativeQuadInterp3d,
"soft": lambda: ConvSoftArgmax3d((3, 3, 3), (1, 1, 1), (1, 1, 1), normalized_coordinates=False, output_value=True),
}
diff --git a/changelog.d/5045.breaking.md b/changelog.d/5045.breaking.md
new file mode 100644
index 000000000..fc01f21c6
--- /dev/null
+++ b/changelog.d/5045.breaking.md
@@ -0,0 +1 @@
+`strict_maxima_bonus` is deprecated and ignored in `conv_soft_argmax3d`, `ConvSoftArgmax3d`, `conv_quad_interp3d`, `ConvQuadInterp3d`, `iterative_quad_interp3d`, `IterativeQuadInterp3d` and `AdaptiveQuadInterp3d`. Previously the quad-interp functions and modules added `strict_maxima_bonus=10.0` by default to the returned value at every converged NMS maximum, and `conv_soft_argmax3d` scaled its values when given a positive bonus, incorrectly (#5018). Now no bonus is added: the returned values are the refined responses. The argument is still accepted, by keyword or in its 0.8.3 position, but it emits a `DeprecationWarning` and will be removed in a future release. The default refiners of `ScaleSpaceDetector` and `SIFTFeatureScaleSpace` already passed `strict_maxima_bonus=0.0`, so their detections are unchanged. Code that ranked the dense value map returned by these functions with `topk` and relied on the bonus to put strict maxima first should select candidates with a `nms3d(x, (3, 3, 3), mask_only=True)` mask instead.
diff --git a/docs/export_support/cases_geomA.py b/docs/export_support/cases_geomA.py
index 5ceb6c607..c0c254f09 100644
--- a/docs/export_support/cases_geomA.py
+++ b/docs/export_support/cases_geomA.py
@@ -937,11 +937,11 @@ CASES += [
),
case("subpix.conv_soft_argmax3d", G, conv_soft_argmax3d, [heat3d], tags=("3d",)),
case(
- "subpix.conv_soft_argmax3d[normalized,bonus]",
+ "subpix.conv_soft_argmax3d[normalized]",
G,
conv_soft_argmax3d,
[heat3d],
- {"normalized_coordinates": True, "strict_maxima_bonus": 10.0},
+ {"normalized_coordinates": True},
tags=("3d",),
),
case("subpix.conv_quad_interp3d", G, conv_quad_interp3d, [heat3d], tags=("3d",)),
diff --git a/docs/source/_data/export_support.json b/docs/source/_data/export_support.json
index 372f06b5e..f4f81ec81 100644
--- a/docs/source/_data/export_support.json
+++ b/docs/source/_data/export_support.json
@@ -7622,7 +7622,7 @@
"export": "ok",
"export_detail": "",
"graph_breaks": 0,
- "name": "subpix.conv_soft_argmax3d[normalized,bonus]",
+ "name": "subpix.conv_soft_argmax3d[normalized]",
"note": "",
"onnx": "ok",
"onnx_detail": "",
@@ -7630,7 +7630,7 @@
"package": "kornia.geometry",
"ref": "kornia.geometry.subpix.conv_soft_argmax3d",
"section": "subpix",
- "variant": "normalized,bonus",
+ "variant": "normalized",
"where": ""
},
{
diff --git a/docs/source/geometry.subpix.rst b/docs/source/geometry.subpix.rst
index a22b98321..59cc1d8a4 100644
--- a/docs/source/geometry.subpix.rst
+++ b/docs/source/geometry.subpix.rst
@@ -40,7 +40,7 @@ Convolutional
num_features=2000,
resp_module=BlobDoG(),
# default β€” auto-selects conv on CUDA, patch on CPU:
- subpix_module=AdaptiveQuadInterp3d(strict_maxima_bonus=0.0),
+ subpix_module=AdaptiveQuadInterp3d(),
scale_pyr_module=ScalePyramid(3, 1.6, 32, double_image=True),
scale_space_response=True,
minima_are_also_good=True,
diff --git a/kornia/feature/integrated.py b/kornia/feature/integrated.py
index df04b6304..85e8602c9 100644
--- a/kornia/feature/integrated.py
+++ b/kornia/feature/integrated.py
@@ -332,7 +332,7 @@ class SIFTFeatureScaleSpace(LocalFeature):
detector = ScaleSpaceDetector(
num_features,
resp_module=BlobDoG(),
- subpix_module=ConvQuadInterp3d(strict_maxima_bonus=0.0),
+ subpix_module=ConvQuadInterp3d(),
scale_pyr_module=ScalePyramid(3, 1.6, 32, double_image=True),
ori_module=PassLAF() if upright or descriptor_backend == "pyramid" else LAFOrienter(19),
scale_space_response=True,
diff --git a/kornia/feature/scale_space_detector.py b/kornia/feature/scale_space_detector.py
index e3ad31753..83251d33a 100644
--- a/kornia/feature/scale_space_detector.py
+++ b/kornia/feature/scale_space_detector.py
@@ -286,7 +286,7 @@ class ScaleSpaceDetector(nn.Module):
resp_module = BlobHessian()
self.resp = _maybe_compile(resp_module, "resp")
if subpix_module is None:
- subpix_module = AdaptiveQuadInterp3d(strict_maxima_bonus=0.0, allow_scale_steps=True)
+ subpix_module = AdaptiveQuadInterp3d(allow_scale_steps=True)
self.subpix = _maybe_compile(subpix_module, "subpix")
if ori_module is None:
ori_module = PassLAF()
diff --git a/kornia/geometry/subpix/spatial_soft_argmax.py b/kornia/geometry/subpix/spatial_soft_argmax.py
index 9ef4ffb86..3aa1c7e34 100644
--- a/kornia/geometry/subpix/spatial_soft_argmax.py
+++ b/kornia/geometry/subpix/spatial_soft_argmax.py
@@ -17,6 +17,7 @@
from __future__ import annotations
+import warnings
from typing import Optional
import torch
@@ -47,6 +48,17 @@ _PATCH_DW = torch.tensor(
)
+def _warn_strict_maxima_bonus() -> None:
+ # stacklevel 3 names the caller of the public function or module constructor that received the argument.
+ warnings.warn(
+ "`strict_maxima_bonus` is deprecated since kornia 0.9.0 and is ignored: no bonus is added to the returned "
+ "values. The argument will be removed in a future release. To keep only strict maxima, select them with a "
+ "`kornia.geometry.subpix.nms3d` mask.",
+ DeprecationWarning,
+ stacklevel=3,
+ )
+
+
def _get_window_grid_kernel2d(h: int, w: int, device: Optional[torch.device] = None) -> torch.Tensor:
r"""Generate a kernel to with window coordinates, residual to window center.
@@ -246,9 +258,11 @@ class ConvSoftArgmax3d(nn.Module):
normalized_coordinates: bool = False,
eps: float = 1e-8,
output_value: bool = True,
- strict_maxima_bonus: float = 0.0,
+ strict_maxima_bonus: Optional[float] = None,
) -> None:
super().__init__()
+ if strict_maxima_bonus is not None:
+ _warn_strict_maxima_bonus()
self.kernel_size = kernel_size
self.stride = stride
self.padding = padding
@@ -256,7 +270,6 @@ class ConvSoftArgmax3d(nn.Module):
self.normalized_coordinates = normalized_coordinates
self.eps = eps
self.output_value = output_value
- self.strict_maxima_bonus = strict_maxima_bonus
def __repr__(self) -> str:
return (
@@ -267,7 +280,6 @@ class ConvSoftArgmax3d(nn.Module):
f"temperature={self.temperature}, "
f"normalized_coordinates={self.normalized_coordinates}, "
f"eps={self.eps}, "
- f"strict_maxima_bonus={self.strict_maxima_bonus}, "
f"output_value={self.output_value})"
)
@@ -294,7 +306,6 @@ class ConvSoftArgmax3d(nn.Module):
self.normalized_coordinates,
self.eps,
self.output_value,
- self.strict_maxima_bonus,
)
@@ -421,7 +432,7 @@ def conv_soft_argmax3d(
normalized_coordinates: bool = False,
eps: float = 1e-8,
output_value: bool = True,
- strict_maxima_bonus: float = 0.0,
+ strict_maxima_bonus: Optional[float] = None,
) -> torch.Tensor | tuple[torch.Tensor, torch.Tensor]:
r"""Compute the convolutional spatial Soft-Argmax 3D over the windows of a given heatmap.
@@ -444,8 +455,8 @@ def conv_soft_argmax3d(
Otherwise, it will return the coordinates in the range of the input shape.
eps: small value to avoid zero division.
output_value: if True, val is output, if False, only ij.
- strict_maxima_bonus: pixels, which are strict maxima will score (1 + strict_maxima_bonus) * value.
- This is needed for mimic behavior of strict NMS in classic local features
+ strict_maxima_bonus: deprecated since kornia 0.9.0 and ignored; passing it emits a
+ :class:`DeprecationWarning`. Select strict maxima with :func:`~kornia.geometry.subpix.nms3d` instead.
Returns:
Function has two outputs - argmax coordinates and the softmaxpooled heatmap values themselves.
@@ -471,6 +482,9 @@ def conv_soft_argmax3d(
>>> nms_coords, nms_val = conv_soft_argmax3d(input, (3, 3, 3), (1, 2, 2), (0, 1, 1))
"""
+ if strict_maxima_bonus is not None:
+ _warn_strict_maxima_bonus()
+
if not torch.is_tensor(input):
raise TypeError(f"Input type is not a torch.Tensor. Got {type(input)}")
@@ -530,13 +544,6 @@ def conv_soft_argmax3d(
x_softmaxpool = (
pool_coef * F.avg_pool3d(x_exp.view(input.size()) * input, kernel_size, stride=stride, padding=padding) / den
)
- if strict_maxima_bonus > 0:
- in_levels: int = input.size(2)
- out_levels: int = x_softmaxpool.size(2)
- skip_levels: int = (in_levels - out_levels) // 2
- strict_maxima: torch.Tensor = F.avg_pool3d(nms3d(input, kernel_size), 1, stride, 0)
- strict_maxima = strict_maxima[:, :, skip_levels : out_levels - skip_levels]
- x_softmaxpool *= 1.0 + strict_maxima_bonus * strict_maxima
x_softmaxpool = x_softmaxpool.view(b, c, x_softmaxpool.size(2), x_softmaxpool.size(3), x_softmaxpool.size(4))
return coords_max, x_softmaxpool
@@ -740,7 +747,7 @@ def _solve_cramer_sym3x3(
def conv_quad_interp3d(
input: torch.Tensor,
n_iters: int = 5,
- strict_maxima_bonus: float = 10.0,
+ strict_maxima_bonus: Optional[float] = None,
max_subpixel_shift: float = 0.6,
precomputed_nms_mask: Optional[torch.Tensor] = None,
dilation_radius: int = 1,
@@ -772,8 +779,9 @@ def conv_quad_interp3d(
Args:
input: response pyramid with shape :math:`(B, C, D, H, W)`.
n_iters: maximum number of localization iterations per keypoint.
- strict_maxima_bonus: value added to ``y_max`` at NMS-maximum positions
- so that strict maxima are preferred during top-K selection.
+ strict_maxima_bonus: deprecated since kornia 0.9.0 and ignored; passing it emits a
+ :class:`DeprecationWarning`. Select strict maxima with ``precomputed_nms_mask`` or
+ :func:`~kornia.geometry.subpix.nms3d` instead.
max_subpixel_shift: threshold above which the integer centre is
moved one step and another iteration is run.
precomputed_nms_mask: optional bool tensor of shape
@@ -793,7 +801,7 @@ def conv_quad_interp3d(
``[scale, x(width), y(height)]`` coordinates for each NMS maximum;
non-maximum positions keep their grid coordinates.
* ``y_max`` β€” shape :math:`(B, C, D, H, W)`, quadratically corrected
- response with optional strict-maxima bonus.
+ response at each NMS maximum; other positions keep the input value.
Example:
>>> input = torch.randn(2, 3, 5, 64, 64)
@@ -804,6 +812,8 @@ def conv_quad_interp3d(
torch.Size([2, 3, 5, 64, 64])
"""
+ if strict_maxima_bonus is not None:
+ _warn_strict_maxima_bonus()
if not torch.is_tensor(input):
raise TypeError(f"Input type is not a torch.Tensor. Got {type(input)}")
if input.ndim != 5:
@@ -994,8 +1004,6 @@ def conv_quad_interp3d(
# Use the final recentered position for val_center (h_cur/w_cur may have moved during iteration)
val_center = input.view(BC, D, H, W)[bc_idx, d_cur, h_cur, w_cur]
y_max[b_idx, c_idx, d_idx, h_idx, w_idx] = val_center + val_correction
- if strict_maxima_bonus > 0:
- y_max[b_idx, c_idx, d_idx, h_idx, w_idx] += strict_maxima_bonus * valid.to(dtype)
return coords_max, y_max
@@ -1011,21 +1019,23 @@ class ConvQuadInterp3d(nn.Module):
Args:
n_iters: maximum localization iterations per keypoint.
- strict_maxima_bonus: score bonus at NMS-maximum positions.
+ strict_maxima_bonus: deprecated since kornia 0.9.0 and ignored; passing it emits a
+ :class:`DeprecationWarning`.
max_subpixel_shift: shift threshold that triggers integer centre move.
"""
def __init__(
self,
n_iters: int = 5,
- strict_maxima_bonus: float = 10.0,
+ strict_maxima_bonus: Optional[float] = None,
max_subpixel_shift: float = 0.6,
dilation_radius: int = 1,
allow_scale_steps: bool = True,
) -> None:
super().__init__()
+ if strict_maxima_bonus is not None:
+ _warn_strict_maxima_bonus()
self.n_iters = n_iters
- self.strict_maxima_bonus = strict_maxima_bonus
self.max_subpixel_shift = max_subpixel_shift
self.dilation_radius = dilation_radius
self.allow_scale_steps = allow_scale_steps
@@ -1034,7 +1044,6 @@ class ConvQuadInterp3d(nn.Module):
return (
f"{self.__class__.__name__}("
f"n_iters={self.n_iters}, "
- f"strict_maxima_bonus={self.strict_maxima_bonus}, "
f"max_subpixel_shift={self.max_subpixel_shift}, "
f"dilation_radius={self.dilation_radius}, "
f"allow_scale_steps={self.allow_scale_steps})"
@@ -1063,18 +1072,17 @@ class ConvQuadInterp3d(nn.Module):
return conv_quad_interp3d(
x,
self.n_iters,
- self.strict_maxima_bonus,
- self.max_subpixel_shift,
- precomputed_nms_mask,
- self.dilation_radius,
- self.allow_scale_steps,
+ max_subpixel_shift=self.max_subpixel_shift,
+ precomputed_nms_mask=precomputed_nms_mask,
+ dilation_radius=self.dilation_radius,
+ allow_scale_steps=self.allow_scale_steps,
)
def iterative_quad_interp3d(
input: torch.Tensor,
n_iters: int = 5,
- strict_maxima_bonus: float = 10.0,
+ strict_maxima_bonus: Optional[float] = None,
max_subpixel_shift: float = 0.6,
allow_scale_steps: bool = True,
precomputed_nms_mask: Optional[torch.Tensor] = None,
@@ -1093,8 +1101,9 @@ def iterative_quad_interp3d(
Args:
input: response pyramid with shape :math:`(B, C, D, H, W)`.
n_iters: maximum number of localization iterations per keypoint.
- strict_maxima_bonus: value added to ``y_max`` at NMS-maximum positions so
- that strict maxima are preferred when selecting the top-K keypoints.
+ strict_maxima_bonus: deprecated since kornia 0.9.0 and ignored; passing it emits a
+ :class:`DeprecationWarning`. Select strict maxima with ``precomputed_nms_mask`` or
+ :func:`~kornia.geometry.subpix.nms3d` instead.
max_subpixel_shift: if the estimated shift along any axis is larger than this
threshold the integer center is displaced and another iteration is run.
allow_scale_steps: if ``True`` (default), the iterative shift is also
@@ -1119,7 +1128,7 @@ def iterative_quad_interp3d(
coordinates ``[scale, x, y]`` for every position in the input.
Non-NMS positions keep their original grid coordinates.
* ``y_max`` has shape :math:`(B, C, D, H, W)` and stores the quadratically
- corrected response values (with the optional strict-maxima bonus added).
+ corrected response values.
Example:
>>> input = torch.randn(2, 3, 3, 8, 8)
@@ -1130,6 +1139,8 @@ def iterative_quad_interp3d(
torch.Size([2, 3, 3, 8, 8])
"""
+ if strict_maxima_bonus is not None:
+ _warn_strict_maxima_bonus()
if not torch.is_tensor(input):
raise TypeError(f"Input type is not a torch.Tensor. Got {type(input)}")
if input.ndim != 5:
@@ -1297,9 +1308,6 @@ def iterative_quad_interp3d(
val_center = inp[bc_idx, d_cur, h_cur, w_cur]
y_max[b_idx, c_idx, d_idx, h_idx, w_idx] = val_center + val_correction
- if strict_maxima_bonus > 0:
- y_max[b_idx, c_idx, d_idx, h_idx, w_idx] += strict_maxima_bonus * valid.to(dtype)
-
return coords_max, y_max
@@ -1312,14 +1320,15 @@ class IterativeQuadInterp3d(nn.Module):
def __init__(
self,
n_iters: int = 5,
- strict_maxima_bonus: float = 10.0,
+ strict_maxima_bonus: Optional[float] = None,
max_subpixel_shift: float = 0.6,
allow_scale_steps: bool = True,
max_candidates: Optional[int] = None,
) -> None:
super().__init__()
+ if strict_maxima_bonus is not None:
+ _warn_strict_maxima_bonus()
self.n_iters = n_iters
- self.strict_maxima_bonus = strict_maxima_bonus
self.max_subpixel_shift = max_subpixel_shift
self.allow_scale_steps = allow_scale_steps
self.max_candidates = max_candidates
@@ -1328,7 +1337,6 @@ class IterativeQuadInterp3d(nn.Module):
return (
f"{self.__class__.__name__}("
f"n_iters={self.n_iters}, "
- f"strict_maxima_bonus={self.strict_maxima_bonus}, "
f"max_subpixel_shift={self.max_subpixel_shift}, "
f"allow_scale_steps={self.allow_scale_steps}, "
f"max_candidates={self.max_candidates})"
@@ -1354,9 +1362,8 @@ class IterativeQuadInterp3d(nn.Module):
return iterative_quad_interp3d(
x,
self.n_iters,
- self.strict_maxima_bonus,
- self.max_subpixel_shift,
- self.allow_scale_steps,
+ max_subpixel_shift=self.max_subpixel_shift,
+ allow_scale_steps=self.allow_scale_steps,
precomputed_nms_mask=precomputed_nms_mask,
max_candidates=self.max_candidates,
)
@@ -1385,7 +1392,8 @@ class AdaptiveQuadInterp3d(nn.Module):
``"patch"`` otherwise.
n_iters: maximum localization iterations per keypoint.
- strict_maxima_bonus: score bonus added at NMS-maximum positions.
+ strict_maxima_bonus: deprecated since kornia 0.9.0 and ignored; passing it emits a
+ :class:`DeprecationWarning`.
max_subpixel_shift: integer-centre move threshold.
dilation_radius: L\ :math:`\infty` precompute radius for ``"conv"`` mode
(ignored in ``"patch"`` mode).
@@ -1411,18 +1419,19 @@ class AdaptiveQuadInterp3d(nn.Module):
self,
mode: str = "auto",
n_iters: int = 5,
- strict_maxima_bonus: float = 10.0,
+ strict_maxima_bonus: Optional[float] = None,
max_subpixel_shift: float = 0.6,
dilation_radius: int = 1,
allow_scale_steps: bool = True,
max_candidates: Optional[int] = None,
) -> None:
super().__init__()
+ if strict_maxima_bonus is not None:
+ _warn_strict_maxima_bonus()
if mode not in self.MODES:
raise ValueError(f"mode must be one of {self.MODES}, got '{mode}'")
self.mode = mode
self.n_iters = n_iters
- self.strict_maxima_bonus = strict_maxima_bonus
self.max_subpixel_shift = max_subpixel_shift
self.dilation_radius = dilation_radius
self.allow_scale_steps = allow_scale_steps
@@ -1433,7 +1442,6 @@ class AdaptiveQuadInterp3d(nn.Module):
f"{self.__class__.__name__}("
f"mode='{self.mode}', "
f"n_iters={self.n_iters}, "
- f"strict_maxima_bonus={self.strict_maxima_bonus}, "
f"max_subpixel_shift={self.max_subpixel_shift}, "
f"dilation_radius={self.dilation_radius}, "
f"allow_scale_steps={self.allow_scale_steps}, "
@@ -1465,18 +1473,16 @@ class AdaptiveQuadInterp3d(nn.Module):
return conv_quad_interp3d(
x,
self.n_iters,
- self.strict_maxima_bonus,
- self.max_subpixel_shift,
- precomputed_nms_mask,
- self.dilation_radius,
- self.allow_scale_steps,
+ max_subpixel_shift=self.max_subpixel_shift,
+ precomputed_nms_mask=precomputed_nms_mask,
+ dilation_radius=self.dilation_radius,
+ allow_scale_steps=self.allow_scale_steps,
)
return iterative_quad_interp3d(
x,
self.n_iters,
- self.strict_maxima_bonus,
- self.max_subpixel_shift,
- self.allow_scale_steps,
+ max_subpixel_shift=self.max_subpixel_shift,
+ allow_scale_steps=self.allow_scale_steps,
precomputed_nms_mask=precomputed_nms_mask,
max_candidates=self.max_candidates,
)
diff --git a/tests/feature/test_scale_space_detector.py b/tests/feature/test_scale_space_detector.py
index 8af677706..125a93af8 100644
--- a/tests/feature/test_scale_space_detector.py
+++ b/tests/feature/test_scale_space_detector.py
@@ -80,9 +80,8 @@ def _canonical_order(lafs: torch.Tensor, responses: torch.Tensor) -> tuple[torch
class TestScaleSpaceDetector(BaseTester):
@pytest.mark.parametrize("subpix_type", [AdaptiveQuadInterp3d, ConvQuadInterp3d, IterativeQuadInterp3d])
@pytest.mark.parametrize("batch", [1, 2])
- @pytest.mark.parametrize("bonus", [0.0, 10.0])
@pytest.mark.parametrize("max_candidates", [None, 3])
- def test_joint_extrema_matches_separate_refinement(self, device, dtype, subpix_type, batch, bonus, max_candidates):
+ def test_joint_extrema_matches_separate_refinement(self, device, dtype, subpix_type, batch, max_candidates):
# A subclass remains on the general extension path, which refines each sign
# independently. Pin the batched built-in path to that reference, including
# signed/weighted responses and gradients through the selected features. The value
@@ -120,7 +119,7 @@ class TestScaleSpaceDetector(BaseTester):
module.forward = counted
return calls
- kwargs = {"strict_maxima_bonus": bonus}
+ kwargs = {}
if subpix_type is not ConvQuadInterp3d:
kwargs["max_candidates"] = max_candidates
joint, separate = subpix_type(**kwargs), SeparateSubpix(**kwargs)
diff --git a/tests/geometry/subpix/test_iterative_quad_interp_pyhesaff.py b/tests/geometry/subpix/test_iterative_quad_interp_pyhesaff.py
index fc1127a17..52eb3ed4d 100644
--- a/tests/geometry/subpix/test_iterative_quad_interp_pyhesaff.py
+++ b/tests/geometry/subpix/test_iterative_quad_interp_pyhesaff.py
@@ -106,7 +106,7 @@ class TestIterativeQuadInterp3dVsRefFormula:
assert nms3d(resp_t, (3, 3, 3), True).sum().item() >= 1, "no NMS peak found"
# Our function β€” one iteration keeps the initial integer position
- coords, _ = conv_quad_interp3d(resp_t, n_iters=1, strict_maxima_bonus=0)
+ coords, _ = conv_quad_interp3d(resp_t, n_iters=1)
# Reference: apply the C++ formula to the numpy arrays
resp_np = resp_t.cpu().float().numpy()[0, 0] # (3, H, W)
@@ -143,7 +143,7 @@ class TestIterativeQuadInterp3dAccuracy:
nms_mask = nms3d(resp_t, (3, 3, 3), True)
assert nms_mask.sum().item() >= 1, "no NMS peak"
- coords, _ = conv_quad_interp3d(resp_t, strict_maxima_bonus=0)
+ coords, _ = conv_quad_interp3d(resp_t)
d_peak = 1
h_peak, w_peak = round(cy), round(cx)
ours_x = coords[0, 0, 1, d_peak, h_peak, w_peak].item()
@@ -165,7 +165,7 @@ class TestIterativeQuadInterp3dAccuracy:
"""Blob at an integer position β€” recovered coords should be very close to integer."""
cx, cy, cs = 9.0, 9.0, 1.0
resp_t = _make_3d_gauss_response(19, 19, cx, cy, cs)
- coords, _ = conv_quad_interp3d(resp_t, strict_maxima_bonus=0)
+ coords, _ = conv_quad_interp3d(resp_t)
d_peak = 1
h_peak, w_peak = round(cy), round(cx)
ours_x = coords[0, 0, 1, d_peak, h_peak, w_peak].item()
@@ -186,7 +186,7 @@ class TestIterativeQuadInterp3dAccuracy:
resp_np[d] += np.exp(-((xx - bx) ** 2 + (yy - by) ** 2) / (2 * 1.5**2) - (d - bs) ** 2 / (2 * 1.0**2))
resp_t = torch.from_numpy(resp_np).unsqueeze(0).unsqueeze(0)
- coords, _ = conv_quad_interp3d(resp_t, strict_maxima_bonus=0)
+ coords, _ = conv_quad_interp3d(resp_t)
d_peak = 1
for bx, by, _ in blobs:
h_int, w_int = round(by), round(bx)
diff --git a/tests/geometry/subpix/test_spatial_softargmax.py b/tests/geometry/subpix/test_spatial_softargmax.py
index a3c303b32..abb426b1a 100644
--- a/tests/geometry/subpix/test_spatial_softargmax.py
+++ b/tests/geometry/subpix/test_spatial_softargmax.py
@@ -15,6 +15,8 @@
# limitations under the License.
#
+import warnings
+
import pytest
import torch
from torch.nn.functional import mse_loss
@@ -523,7 +525,7 @@ class TestConvQuadInterp3dModule(BaseTester):
def test_gradcheck(self, device):
sample = torch.rand(1, 1, 3, 5, 5, device=device, dtype=torch.float64)
sample[0, 0, 1, 2, 2] += 20.0
- self.gradcheck(kornia.geometry.ConvQuadInterp3d(strict_maxima_bonus=0), (sample), atol=1e-3, rtol=1e-3)
+ self.gradcheck(kornia.geometry.ConvQuadInterp3d(), (sample), atol=1e-3, rtol=1e-3)
def test_diag(self, device, dtype):
sample = torch.tensor(
@@ -571,7 +573,7 @@ class TestConvQuadInterp3dModule(BaseTester):
[
[2.2504e-04, 2.3146e-02, 1.6808e-01, 2.3188e-02, 2.3628e-04],
[2.3146e-02, 1.8118e-01, 7.4338e-01, 1.8955e-01, 2.5413e-02],
- [1.6807e-01, 7.4227e-01, 1.1086e01, 8.0414e-01, 1.8482e-01],
+ [1.6807e-01, 7.4227e-01, 1.0865e00, 8.0414e-01, 1.8482e-01],
[2.3146e-02, 1.8118e-01, 7.4338e-01, 1.8955e-01, 2.5413e-02],
[2.2504e-04, 2.3146e-02, 1.6808e-01, 2.3188e-02, 2.3628e-04],
],
@@ -675,7 +677,7 @@ class TestConvQuadInterp3dModule(BaseTester):
class TestConvQuadInterp3d(BaseTester):
def test_smoke(self, device, dtype):
sample = torch.randn(2, 3, 3, 4, 4, device=device, dtype=dtype)
- op = kornia.geometry.subpix.ConvQuadInterp3d(n_iters=3, strict_maxima_bonus=1)
+ op = kornia.geometry.subpix.ConvQuadInterp3d(n_iters=3)
coord, val = op(sample)
assert coord.shape == (2, 3, 3, 3, 4, 4)
assert val.shape == (2, 3, 3, 4, 4)
@@ -697,7 +699,7 @@ class TestConvQuadInterp3d(BaseTester):
sample = torch.rand(1, 1, 3, 5, 5, device=device, dtype=torch.float64)
sample[0, 0, 1, 2, 2] += 20.0
self.gradcheck(
- kornia.geometry.subpix.ConvQuadInterp3d(strict_maxima_bonus=0, n_iters=1),
+ kornia.geometry.subpix.ConvQuadInterp3d(n_iters=1),
(sample,),
atol=1e-3,
rtol=1e-3,
@@ -706,7 +708,7 @@ class TestConvQuadInterp3d(BaseTester):
def test_dynamo(self, device, dtype, torch_optimizer):
sample = torch.rand(1, 1, 3, 5, 5, device=device, dtype=dtype)
sample[0, 0, 1, 2, 2] += 20.0
- op = kornia.geometry.subpix.ConvQuadInterp3d(strict_maxima_bonus=0, n_iters=1)
+ op = kornia.geometry.subpix.ConvQuadInterp3d(n_iters=1)
op_opt = torch_optimizer(op)
self.assert_close(op(sample)[0], op_opt(sample)[0])
self.assert_close(op(sample)[1], op_opt(sample)[1])
@@ -719,7 +721,7 @@ class TestConvQuadInterp3d(BaseTester):
# Pinned in float16 specifically: bfloat16 keeps float32's exponent range.
torch.manual_seed(0)
sample = torch.rand(1, 1, 5, 40, 40, device=device, dtype=torch.float16, requires_grad=True)
- coords, vals = kornia.geometry.subpix.ConvQuadInterp3d(strict_maxima_bonus=0.0)(sample)
+ coords, vals = kornia.geometry.subpix.ConvQuadInterp3d()(sample)
grad = torch.autograd.grad(coords.sum() + vals.sum(), sample)[0]
assert torch.isfinite(grad).all()
@@ -727,7 +729,7 @@ class TestConvQuadInterp3d(BaseTester):
# A clear peak at scale=1, h=2, w=2 should return coords close to (1, 2, 2).
sample = torch.zeros(1, 1, 3, 5, 5, device=device, dtype=dtype)
sample[0, 0, 1, 2, 2] = 10.0
- coord, _val = conv_quad_interp3d(sample, strict_maxima_bonus=0)
+ coord, _val = conv_quad_interp3d(sample)
# coords_max layout: dim2 = [scale, x(width), y(height)]
assert coord[0, 0, 0, 1, 2, 2].item() == pytest.approx(1.0, abs=1e-3) # scale
assert coord[0, 0, 1, 1, 2, 2].item() == pytest.approx(2.0, abs=1e-3) # x
@@ -743,7 +745,7 @@ class TestConvQuadInterp3d(BaseTester):
for dw in range(-1, 2):
dist2 = (dd - 0.2) ** 2 + (dh - 0.1) ** 2 + (dw + 0.15) ** 2
sample[0, 0, 2 + dd, 3 + dh, 3 + dw] += float(torch.exp(torch.tensor(-dist2 * 4)))
- coord, _ = conv_quad_interp3d(sample, strict_maxima_bonus=0)
+ coord, _ = conv_quad_interp3d(sample)
# The refined x (width) coord at the integer peak (d=2, h=3, w=3) should shift toward -0.15.
x_coord = coord[0, 0, 1, 2, 3, 3].item()
assert x_coord < 3.0 # shift in negative x direction
@@ -751,7 +753,7 @@ class TestConvQuadInterp3d(BaseTester):
def test_no_keypoints(self, device, dtype):
# Flat input β€” no NMS maxima, output should equal input coords/values.
sample = torch.ones(1, 1, 3, 4, 4, device=device, dtype=dtype)
- coord, val = conv_quad_interp3d(sample, strict_maxima_bonus=0)
+ coord, val = conv_quad_interp3d(sample)
assert coord.shape == (1, 1, 3, 3, 4, 4)
assert val.shape == (1, 1, 3, 4, 4)
@@ -759,8 +761,8 @@ class TestConvQuadInterp3d(BaseTester):
# With a clear symmetric peak a single iteration should converge.
sample = torch.zeros(1, 1, 3, 5, 5, device=device, dtype=dtype)
sample[0, 0, 1, 2, 2] = 5.0
- coord1, _ = conv_quad_interp3d(sample, n_iters=1, strict_maxima_bonus=0)
- coord5, _ = conv_quad_interp3d(sample, n_iters=5, strict_maxima_bonus=0)
+ coord1, _ = conv_quad_interp3d(sample, n_iters=1)
+ coord5, _ = conv_quad_interp3d(sample, n_iters=5)
self.assert_close(coord1, coord5, atol=1e-5, rtol=1e-5)
@@ -780,8 +782,8 @@ class TestAdaptiveQuadInterp3d(BaseTester):
"""patch and conv backends must produce numerically identical results."""
torch.manual_seed(7)
x = torch.randn(1, 1, 5, 16, 16, device=device, dtype=dtype)
- coords_p, vals_p = kornia.geometry.subpix.AdaptiveQuadInterp3d(mode="patch", strict_maxima_bonus=0)(x)
- coords_c, vals_c = kornia.geometry.subpix.AdaptiveQuadInterp3d(mode="conv", strict_maxima_bonus=0)(x)
+ coords_p, vals_p = kornia.geometry.subpix.AdaptiveQuadInterp3d(mode="patch")(x)
+ coords_c, vals_c = kornia.geometry.subpix.AdaptiveQuadInterp3d(mode="conv")(x)
from kornia.geometry.subpix import nms3d
mask = nms3d(x, (3, 3, 3), True)
@@ -792,9 +794,9 @@ class TestAdaptiveQuadInterp3d(BaseTester):
def test_auto_dispatches(self, device, dtype):
"""auto mode must use conv on CUDA, patch on CPU (verified via result equality)."""
x = torch.randn(1, 1, 3, 8, 8, device=device, dtype=dtype)
- auto = kornia.geometry.subpix.AdaptiveQuadInterp3d(mode="auto", strict_maxima_bonus=0)
+ auto = kornia.geometry.subpix.AdaptiveQuadInterp3d(mode="auto")
expected_mode = "conv" if x.is_cuda else "patch"
- ref = kornia.geometry.subpix.AdaptiveQuadInterp3d(mode=expected_mode, strict_maxima_bonus=0)
+ ref = kornia.geometry.subpix.AdaptiveQuadInterp3d(mode=expected_mode)
self.assert_close(auto(x)[0], ref(x)[0], atol=1e-5, rtol=1e-5)
self.assert_close(auto(x)[1], ref(x)[1], atol=1e-5, rtol=1e-5)
@@ -802,7 +804,7 @@ class TestAdaptiveQuadInterp3d(BaseTester):
x = torch.zeros(1, 1, 3, 5, 5, device=device, dtype=torch.float64)
x[0, 0, 1, 2, 2] = 5.0
self.gradcheck(
- kornia.geometry.subpix.AdaptiveQuadInterp3d(mode="patch", strict_maxima_bonus=0),
+ kornia.geometry.subpix.AdaptiveQuadInterp3d(mode="patch"),
(x,),
atol=1e-3,
rtol=1e-3,
@@ -811,7 +813,7 @@ class TestAdaptiveQuadInterp3d(BaseTester):
def test_dynamo(self, device, dtype, torch_optimizer):
x = torch.rand(1, 1, 3, 5, 5, device=device, dtype=dtype)
x[0, 0, 1, 2, 2] += 20.0
- op = kornia.geometry.subpix.AdaptiveQuadInterp3d(mode="patch", strict_maxima_bonus=0)
+ op = kornia.geometry.subpix.AdaptiveQuadInterp3d(mode="patch")
op_opt = torch_optimizer(op)
self.assert_close(op(x)[0], op_opt(x)[0])
@@ -844,10 +846,8 @@ class TestAdaptiveQuadInterp3d(BaseTester):
)
max_mask, _ = nms3d_minmax(x)
- coord_conv, _ = conv_quad_interp3d(
- x, n_iters=5, strict_maxima_bonus=0.0, precomputed_nms_mask=max_mask, dilation_radius=3
- )
- coord_iter, _ = iterative_quad_interp3d(x, n_iters=5, strict_maxima_bonus=0.0)
+ coord_conv, _ = conv_quad_interp3d(x, n_iters=5, precomputed_nms_mask=max_mask, dilation_radius=3)
+ coord_iter, _ = iterative_quad_interp3d(x, n_iters=5)
d_idx, h_idx, w_idx = torch.where(max_mask.view(D, H, W))
assert len(d_idx) > 0, "No NMS maxima found β€” check the synthetic input"
@@ -938,7 +938,7 @@ class TestPackedQuadraticFit(BaseTester):
op = getattr(subpix, op_name)
sample = torch.rand(2, 2, 5, 9, 8, dtype=dtype).requires_grad_()
cuda_sample = sample.detach().to(device).requires_grad_()
- kwargs = {"n_iters": n_iters, "allow_scale_steps": allow_scale_steps, "strict_maxima_bonus": 0.0}
+ kwargs = {"n_iters": n_iters, "allow_scale_steps": allow_scale_steps}
expected = op(sample, **kwargs)
actual = op(cuda_sample, **kwargs)
for got, want in zip(actual, expected):
@@ -946,3 +946,93 @@ class TestPackedQuadraticFit(BaseTester):
grad = torch.autograd.grad(sum(t.square().mean() for t in actual), cuda_sample)[0]
grad_ref = torch.autograd.grad(sum(t.square().mean() for t in expected), sample)[0]
self.assert_close(grad.cpu(), grad_ref)
+
+
+def _bump3d(device, dtype):
+ # One smooth off-grid peak, built without the RNG: a strict NMS maximum at (1, 3, 3) whose
+ # refined value differs from its grid value, so a bonus at that maximum shows in the output.
+ d = torch.arange(3, device=device, dtype=dtype).view(3, 1, 1)
+ h = torch.arange(7, device=device, dtype=dtype).view(1, 7, 1)
+ w = torch.arange(7, device=device, dtype=dtype).view(1, 1, 7)
+ return torch.exp(-((d - 1.1) ** 2 + (h - 3.2) ** 2 + (w - 2.8) ** 2) / 2)[None, None]
+
+
+class TestStrictMaximaBonusDeprecated(BaseTester):
+ # `strict_maxima_bonus` is deprecated since kornia 0.9.0. It is still accepted wherever 0.8.3 accepted it,
+ # by keyword or in its positional slot, but it warns and is ignored: a call that passes it returns what the
+ # call without it returns, and test_default_adds_no_bonus pins that the latter carries no bonus. The argument
+ # handling does not depend on the dtype, so these run in float32 only: conv_soft_argmax3d has no CPU
+ # float16/bfloat16 kernel (avg_pool3d).
+ _SOFT = kornia.geometry.subpix.conv_soft_argmax3d
+ _CONV = kornia.geometry.subpix.conv_quad_interp3d
+ _ITER = kornia.geometry.subpix.iterative_quad_interp3d
+
+ @pytest.mark.parametrize(
+ "fn, args, kwargs",
+ [
+ (_SOFT, (), {"strict_maxima_bonus": 10.0}),
+ (_SOFT, ((3, 3, 3), (1, 1, 1), (1, 1, 1), 1.0, False, 1e-8, True, 10.0), {}),
+ (_CONV, (), {"strict_maxima_bonus": 10.0}),
+ (_CONV, (5, 10.0, 0.6), {}),
+ (_ITER, (), {"strict_maxima_bonus": 10.0}),
+ (_ITER, (5, 10.0, 0.6), {}),
+ ],
+ ids=["soft-keyword", "soft-positional", "conv-keyword", "conv-positional", "iter-keyword", "iter-positional"],
+ )
+ def test_function_warns_and_ignores(self, device, fn, args, kwargs):
+ x = _bump3d(device, torch.float32)
+ with pytest.warns(DeprecationWarning, match="strict_maxima_bonus") as record:
+ actual = fn(x, *args, **kwargs)
+ assert len(record) == 1
+ assert record[0].filename == __file__
+ with warnings.catch_warnings():
+ warnings.simplefilter("error")
+ expected = fn(x)
+ for got, want in zip(actual, expected):
+ self.assert_close(got, want, atol=0, rtol=0)
+
+ @pytest.mark.parametrize(
+ "cls, kwargs",
+ [
+ (kornia.geometry.subpix.ConvSoftArgmax3d, {}),
+ (kornia.geometry.subpix.ConvQuadInterp3d, {}),
+ (kornia.geometry.subpix.IterativeQuadInterp3d, {}),
+ (kornia.geometry.subpix.AdaptiveQuadInterp3d, {"mode": "conv"}),
+ (kornia.geometry.subpix.AdaptiveQuadInterp3d, {"mode": "patch"}),
+ ],
+ ids=["ConvSoftArgmax3d", "ConvQuadInterp3d", "IterativeQuadInterp3d", "Adaptive-conv", "Adaptive-patch"],
+ )
+ def test_module_warns_once_and_ignores(self, device, cls, kwargs):
+ x = _bump3d(device, torch.float32)
+ with pytest.warns(DeprecationWarning, match="strict_maxima_bonus") as record:
+ module = cls(strict_maxima_bonus=10.0, **kwargs)
+ assert len(record) == 1
+ assert record[0].filename == __file__
+ with warnings.catch_warnings():
+ warnings.simplefilter("error")
+ actual = module(x)
+ expected = cls(**kwargs)(x)
+ assert "strict_maxima_bonus" not in repr(module)
+ for got, want in zip(actual, expected):
+ self.assert_close(got, want, atol=0, rtol=0)
+
+ def test_default_adds_no_bonus(self, device):
+ # The refined value at the maximum is the quadratic fit's peak, which lies just above the grid value.
+ x = _bump3d(device, torch.float32)
+ for fn in (kornia.geometry.subpix.conv_quad_interp3d, kornia.geometry.subpix.iterative_quad_interp3d):
+ with warnings.catch_warnings():
+ warnings.simplefilter("error")
+ _, vals = fn(x)
+ peak = vals[0, 0, 1, 3, 3]
+ assert x[0, 0, 1, 3, 3] < peak < 1.0
+
+ def test_scale_space_detector_083_idiom(self, device):
+ # The 0.8.3 documented detector setup keeps working and gives the same detections.
+ img = torch.arange(64 * 64, device=device, dtype=torch.float32).view(1, 1, 64, 64)
+ img = torch.sin(img * 0.37) * torch.cos(img * 0.011)
+ with pytest.warns(DeprecationWarning, match="strict_maxima_bonus"):
+ subpix = kornia.geometry.subpix.AdaptiveQuadInterp3d(strict_maxima_bonus=0.0, allow_scale_steps=True)
+ old = kornia.feature.ScaleSpaceDetector(16, subpix_module=subpix).to(device)
+ new = kornia.feature.ScaleSpaceDetector(16).to(device)
+ for got, want in zip(old(img), new(img)):
+ self.assert_close(got, want, atol=0, rtol=0)