Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(geometry): unify and speed up the non-maxima suppression general path (#4242)

Dmytro Mishkin601b5a4ad619
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 04eacaf3c..7cfc3cbc6 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -112,6 +112,21 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Breaking changes
+* Non-maxima suppression applies one border rule at every window size. `NonMaximaSuppression2d` /
+ `nms2d` with a window larger than `(7, 7)`, and `NonMaximaSuppression3d` / `nms3d`, no longer report
+ maxima inside the `(k - 1) // 2` border strip. Previously the general path replicate-padded its input,
+ so a position whose window ran off an edge was judged against duplicated copies of the edge values,
+ which both fabricated plateaus that suppressed genuine maxima and hid genuine neighbours that should
+ have suppressed spurious ones; the `(3, 3)`, `(5, 5)` and `(7, 7)` paths meanwhile rejected the strip
+ outright, so the two disagreed about the same pixel. The explicit paths' rule is now the rule
+ everywhere. Every kornia detector already rejects that strip -- ALIKED by hand after calling `nms2d`,
+ DISK and XFeat by using `k = 5`, `MultiResolutionDetector` by zeroing 15 px before the call -- so no
+ detector output changes. (#4239, #4242)
+
+* `nms2d(x, (1, 1))` and `nms3d(x, (1, 1, 1))` return `x` unchanged. A unit window has no neighbours,
+ so nothing can be suppressed; the old 2-D result was an artifact of the zeroed centre tap of the
+ convolution kernel summing to `0.0`, while the old 3-D path raised because of #4241. (#4242)
+
* Kornia's minimum supported PyTorch version rises to 2.5.1. Previously the declared floor was
2.0.0; PR-time CI has only ever exercised 2.5.1 and newer, and this same change retires the
scheduled-CI legs that tested anything older.
@@ -249,6 +264,24 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Bug fixes
+* Non-maxima suppression with a window larger than `(7, 7)` no longer builds a `(k*k, 1, k, k)` one-hot
+ convolution to gather each neighbour into its own channel. On CPU in half precision that convolution
+ has no vectorized kernel and falls back to `_slow_conv2d_forward`, where it accounted for 99% of a
+ `MultiResolutionDetector.detect` call. The window minus its centre is now covered by rectangular
+ `max_pool2d` regions whose full-width slabs share one column pass, costing `O(ky + kx)` taps per
+ position rather than `ky * kx - 1`, with the centre excluded by construction so the suppression stays
+ strict. `detect` on a 240x240 image drops from 5757 ms to 27 ms in float16 and from 73.8 ms to 13.8 ms
+ in float32; a 353x353 `k = 15` suppression drops from 3150 ms to 10.5 ms in float16 and from 42.6 ms to
+ 8.7 ms in float32, and from 12.1 ms to 0.15 ms for 1024x1024 `k = 21` on CUDA. (#4242)
+
+* `nms2d` accepts a non-square `kernel_size`. It used to raise `RuntimeError: shape '[1, 1, -1, H, W]' is
+ invalid for input of size ...`, because the neighbourhood kernel was built with its two extents swapped
+ and the padding was applied to the wrong pair of edges. (#4240, #4242)
+
+* `nms3d` accepts any `kernel_size`. Every size other than `(3, 3, 3)`, the one served by a hand-written
+ branch, used to raise: `_compute_zero_padding3d` defined a `(k - 1) // 2` helper and then returned the
+ full kernel sizes, so the padded volume did not match the kernel it was convolved with. (#4241, #4242)
+
* `HyNet` and `SOSNet` now run in half precision, on CPU and on GPU, and no longer return NaN for a
degenerate patch (closes #4224). Two defects sat on the same line. On CPU both raised
`NotImplementedError: "avg_pool3d_out_frame" not implemented for 'Half'` (and the `'BFloat16'` spelling):
diff --git a/kornia/geometry/subpix/nms.py b/kornia/geometry/subpix/nms.py
index fb16e7c91..1d70cd323 100644
--- a/kornia/geometry/subpix/nms.py
+++ b/kornia/geometry/subpix/nms.py
@@ -17,27 +17,87 @@
from __future__ import annotations
+from typing import Any, List, Tuple
+
import torch
import torch.nn.functional as F
from torch import nn
-def _get_nms_kernel2d(kx: int, ky: int) -> torch.Tensor:
- """Return neigh2channels conv kernel."""
- numel: int = ky * kx
- center: int = numel // 2
- weight = torch.eye(numel)
- weight[center, center] = 0
- return weight.view(numel, 1, ky, kx)
+def _split_window(k: int) -> Tuple[int, int]:
+ """Return the neighbour extents of a length-``k`` window either side of its centre."""
+ before = (k - 1) // 2
+ return before, k - before - 1
+
+
+def _reduce_max(parts: List[torch.Tensor]) -> torch.Tensor:
+ """Reduce the maxima from the non-empty neighbourhood regions."""
+ out = parts[0]
+ for i in range(1, len(parts)):
+ out = torch.maximum(out, parts[i])
+ return out
-def _get_nms_kernel3d(kd: int, ky: int, kx: int) -> torch.Tensor:
- """Return neigh2channels conv kernel."""
- numel: int = kd * ky * kx
- center: int = numel // 2
- weight = torch.eye(numel)
- weight[center, center] = 0
- return weight.view(numel, 1, kd, ky, kx)
+def _neighbourhood_max2d(x: torch.Tensor, ky: int, kx: int) -> torch.Tensor:
+ """Max over each ``ky x kx`` window with its own centre excluded.
+
+ The window minus its centre is partitioned into four rectangles -- the rows above the centre
+ row, the rows below it, and the centre row either side of the centre -- and each is reduced with
+ ``max_pool2d``. The two full-width slabs share a single ``(1, kx)`` column pass, so the cost is
+ ``O(ky + kx)`` taps per position rather than the ``ky * kx - 1`` a literal neighbourhood costs.
+
+ Only positions whose full window lies inside the image are computed, so the result has shape
+ :math:`(B, C, H - k_y + 1, W - k_x + 1)`; entry ``(i, j)`` belongs to the centre
+ ``x[..., i + (k_y - 1) // 2, j + (k_x - 1) // 2]``.
+ """
+ cy, by = _split_window(ky)
+ cx, bx = _split_window(kx)
+ H, W = x.shape[-2], x.shape[-1]
+ parts: List[torch.Tensor] = []
+ if cy > 0 or by > 0:
+ row_max = F.max_pool2d(x, (1, kx), stride=1)
+ if cy > 0:
+ parts.append(F.max_pool2d(row_max[..., : H - by - 1, :], (cy, 1), stride=1))
+ if by > 0:
+ parts.append(F.max_pool2d(row_max[..., cy + 1 :, :], (by, 1), stride=1))
+ centre_row = x[..., cy : H - by, :]
+ if cx > 0:
+ parts.append(F.max_pool2d(centre_row[..., : W - bx - 1], (1, cx), stride=1))
+ if bx > 0:
+ parts.append(F.max_pool2d(centre_row[..., cx + 1 :], (1, bx), stride=1))
+ return _reduce_max(parts)
+
+
+def _neighbourhood_max3d(x: torch.Tensor, kd: int, ky: int, kx: int) -> torch.Tensor:
+ """Max over each ``kd x ky x kx`` window with its own centre excluded.
+
+ The 3-D analogue of :func:`_neighbourhood_max2d`: six boxes -- the depth slabs either side of
+ the centre depth, then the row slabs either side of the centre row within it, then the centre
+ row either side of the centre -- sharing the column and row passes they have in common.
+ """
+ cd, bd = _split_window(kd)
+ cy, by = _split_window(ky)
+ cx, bx = _split_window(kx)
+ D, H, W = x.shape[-3], x.shape[-2], x.shape[-1]
+ parts: List[torch.Tensor] = []
+ col_max = F.max_pool3d(x, (1, 1, kx), stride=1) if (cd > 0 or bd > 0 or cy > 0 or by > 0) else x
+ if cd > 0 or bd > 0:
+ plane_max = F.max_pool3d(col_max, (1, ky, 1), stride=1)
+ if cd > 0:
+ parts.append(F.max_pool3d(plane_max[..., : D - bd - 1, :, :], (cd, 1, 1), stride=1))
+ if bd > 0:
+ parts.append(F.max_pool3d(plane_max[..., cd + 1 :, :, :], (bd, 1, 1), stride=1))
+ centre_plane = col_max[..., cd : D - bd, :, :]
+ if cy > 0:
+ parts.append(F.max_pool3d(centre_plane[..., : H - by - 1, :], (1, cy, 1), stride=1))
+ if by > 0:
+ parts.append(F.max_pool3d(centre_plane[..., cy + 1 :, :], (1, by, 1), stride=1))
+ centre_row = x[..., cd : D - bd, cy : H - by, :]
+ if cx > 0:
+ parts.append(F.max_pool3d(centre_row[..., : W - bx - 1], (1, 1, cx), stride=1))
+ if bx > 0:
+ parts.append(F.max_pool3d(centre_row[..., cx + 1 :], (1, 1, bx), stride=1))
+ return _reduce_max(parts)
class NonMaximaSuppression2d(nn.Module):
@@ -46,27 +106,31 @@ class NonMaximaSuppression2d(nn.Module):
Flag `minima_are_also_good` is useful, when you want to detect both maxima and minima, e.g. for DoG
"""
- kernel: torch.Tensor
-
def __init__(self, kernel_size: tuple[int, int]) -> None:
super().__init__()
- self.kernel_size: tuple[int, int] = kernel_size
- self.padding: tuple[int, int, int, int] = self._compute_zero_padding2d(kernel_size)
- self.register_buffer("kernel", _get_nms_kernel2d(*kernel_size))
-
- @staticmethod
- def _compute_zero_padding2d(kernel_size: tuple[int, int]) -> tuple[int, int, int, int]:
- # TODO: This method is duplicated with some utility function on kornia.filters
if not isinstance(kernel_size, tuple):
raise AssertionError(type(kernel_size))
if len(kernel_size) != 2:
raise AssertionError(kernel_size)
+ self.kernel_size: tuple[int, int] = kernel_size
- def pad(x: int) -> int:
- return (x - 1) // 2 # zero padding function
-
- ky, kx = kernel_size # we assume a cubic kernel
- return (pad(ky), pad(kx), pad(ky), pad(kx))
+ def _load_from_state_dict(
+ self,
+ state_dict: dict[str, torch.Tensor],
+ prefix: str,
+ local_metadata: dict[str, Any],
+ strict: bool,
+ missing_keys: list[str],
+ unexpected_keys: list[str],
+ error_msgs: list[str],
+ ) -> None:
+ # The convolution implementation registered this derived tensor as a persistent buffer.
+ # It is unused by the pooled implementation, but accepting it preserves strict loading of
+ # checkpoints saved by older Kornia releases, including when NMS is nested in another module.
+ state_dict.pop(prefix + "kernel", None)
+ super()._load_from_state_dict(
+ state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs
+ )
def forward(self, x: torch.Tensor, mask_only: bool = False) -> torch.Tensor:
"""Keep only strict local maxima in a 2D response map.
@@ -76,6 +140,9 @@ class NonMaximaSuppression2d(nn.Module):
neighbors are suppressed. This is commonly used to turn dense corner or
keypoint response maps into sparse candidate locations.
+ A location within ``(k - 1) // 2`` of an edge is never a maximum: its window does not fit
+ inside the input, so the comparisons that would decide it cannot be made.
+
Args:
x: Response tensor with shape :math:`(B, C, H, W)`, where
:math:`B` is the batch size, :math:`C` is the number of
@@ -92,7 +159,9 @@ class NonMaximaSuppression2d(nn.Module):
raise AssertionError(x.shape)
B, CH, H, W = x.size()
- if self.kernel_size == (3, 3):
+ if self.kernel_size == (1, 1):
+ mask = torch.ones(B, CH, H, W, device=x.device, dtype=torch.bool)
+ elif self.kernel_size == (3, 3):
# 8-comparison explicit path: no extra memory for conv kernel.
left = slice(0, -2)
center = slice(1, -1)
@@ -206,14 +275,17 @@ class NonMaximaSuppression2d(nn.Module):
& (ct > x[..., p3, p3])
)
else:
- # General path: conv2d maps every neighbour into its own channel.
- x_padded = F.pad(x, list(self.padding)[::-1], mode="replicate")
- B, CH, HP, WP = x_padded.size()
- neighborhood = F.conv2d(x_padded.view(B * CH, 1, HP, WP), self.kernel.to(x.device, x.dtype), stride=1).view(
- B, CH, -1, H, W
- )
- max_non_center = neighborhood.max(dim=2)[0]
- mask = x > max_non_center
+ # General path: the same rule as the explicit paths above, for any window size. A
+ # position whose full window does not fit inside the image is not a maximum -- it has
+ # not been compared against the neighbours that would decide it -- so the border strip
+ # stays False and only the interior is computed (#4239).
+ ky, kx = self.kernel_size
+ cy, by = _split_window(ky)
+ cx, bx = _split_window(kx)
+ mask = torch.zeros(B, CH, H, W, device=x.device, dtype=torch.bool)
+ if H >= ky and W >= kx:
+ centre = x[..., cy : H - by, cx : W - bx]
+ mask[..., cy : H - by, cx : W - bx] = centre > _neighbourhood_max2d(x, ky, kx)
if mask_only:
return mask
@@ -225,23 +297,11 @@ class NonMaximaSuppression3d(nn.Module):
def __init__(self, kernel_size: tuple[int, int, int]) -> None:
super().__init__()
- self.kernel_size: tuple[int, int, int] = kernel_size
- self.padding: tuple[int, int, int, int, int, int] = self._compute_zero_padding3d(kernel_size)
- self.kernel = _get_nms_kernel3d(*kernel_size)
-
- @staticmethod
- def _compute_zero_padding3d(kernel_size: tuple[int, int, int]) -> tuple[int, int, int, int, int, int]:
- # TODO: This method is duplicated with some utility function on kornia.filters
if not isinstance(kernel_size, tuple):
raise AssertionError(type(kernel_size))
if len(kernel_size) != 3:
raise AssertionError(kernel_size)
-
- def pad(x: int) -> int:
- return (x - 1) // 2 # zero padding function
-
- kd, ky, kx = kernel_size # we assume a cubic kernel
- return (kd, kd, ky, ky, kx, kx)
+ self.kernel_size: tuple[int, int, int] = kernel_size
def forward(self, x: torch.Tensor, mask_only: bool = False) -> torch.Tensor:
"""Keep only strict local maxima in a 3D response volume.
@@ -250,6 +310,9 @@ class NonMaximaSuppression3d(nn.Module):
width. This is used by scale-space detectors to keep responses that are
locally maximal both in image position and in scale/depth.
+ As in :meth:`NonMaximaSuppression2d.forward`, a voxel within ``(k - 1) // 2`` of a boundary
+ in any axis is never a maximum: its window does not fit inside the input.
+
Args:
x: Response tensor with shape :math:`(B, C, D, H, W)`, where
:math:`B` is batch size, :math:`C` is channel count,
@@ -267,7 +330,9 @@ class NonMaximaSuppression3d(nn.Module):
raise AssertionError(x.shape)
# find local maximum values
B, CH, D, H, W = x.size()
- if self.kernel_size == (3, 3, 3):
+ if self.kernel_size == (1, 1, 1):
+ mask = torch.ones(B, CH, D, H, W, device=x.device, dtype=torch.bool)
+ elif self.kernel_size == (3, 3, 3):
# 26-comparison explicit path: strict local maximum, works on CPU and CUDA.
# Using integer slice literals (not slice objects) makes this torch.jit.script-friendly,
# which fuses the ops and runs ~13x faster on CUDA than the eager path.
@@ -302,17 +367,18 @@ class NonMaximaSuppression3d(nn.Module):
& (ct > x[..., 2:, 2:, 2:])
)
else:
- max_non_center = (
- F.conv3d(
- F.pad(x, list(self.padding)[::-1], mode="replicate"),
- self.kernel.repeat(CH, 1, 1, 1, 1).to(x.device, x.dtype),
- stride=1,
- groups=CH,
- )
- .view(B, CH, -1, D, H, W)
- .max(dim=2, keepdim=False)[0]
- )
- mask = x > max_non_center
+ # General path: the same rule as the explicit path above, for any window size. See
+ # `NonMaximaSuppression2d.forward` for the border convention (#4239). The old path
+ # padded by the full kernel size rather than half of it and raised for every kernel
+ # other than (3, 3, 3) (#4241); nothing pads here.
+ kd, ky, kx = self.kernel_size
+ cd, bd = _split_window(kd)
+ cy, by = _split_window(ky)
+ cx, bx = _split_window(kx)
+ mask = torch.zeros(B, CH, D, H, W, device=x.device, dtype=torch.bool)
+ if D >= kd and H >= ky and W >= kx:
+ centre = x[..., cd : D - bd, cy : H - by, cx : W - bx]
+ mask[..., cd : D - bd, cy : H - by, cx : W - bx] = centre > _neighbourhood_max3d(x, kd, ky, kx)
if mask_only:
return mask
return x * (mask.to(x.dtype))
diff --git a/tests/geometry/subpix/test_nms.py b/tests/geometry/subpix/test_nms.py
index a67869961..6e12c6e39 100644
--- a/tests/geometry/subpix/test_nms.py
+++ b/tests/geometry/subpix/test_nms.py
@@ -15,6 +15,8 @@
# limitations under the License.
#
+import itertools
+
import pytest
import torch
@@ -23,6 +25,35 @@ import kornia
from testing.base import BaseTester
+def _reference_nms_mask(x: torch.Tensor, kernel_size: tuple[int, ...]) -> torch.Tensor:
+ """Strict local maxima, written out from the definition rather than from the implementation.
+
+ A position is a maximum when its whole window lies inside the input and its value is strictly
+ greater than every *other* value in that window. A position whose window would run off an edge is
+ not a maximum: the comparisons that would decide it have not been made. This is the rule the
+ ``(3, 3)``/``(5, 5)``/``(7, 7)`` fast paths have always applied, and since #4239 the general path
+ applies it too.
+
+ Built by shifting whole views and reducing with :func:`torch.maximum`, so it shares no structure
+ with the pooled implementation it checks.
+ """
+ ndim = len(kernel_size)
+ sizes = x.shape[-ndim:]
+ before = [(k - 1) // 2 for k in kernel_size]
+ after = [k - b - 1 for k, b in zip(kernel_size, before)]
+ centre_at = tuple(slice(b, s - a) for b, a, s in zip(before, after, sizes))
+ centre = x[(..., *centre_at)]
+ neighbours = torch.full_like(centre, float("-inf"))
+ for offset in itertools.product(*(range(k) for k in kernel_size)):
+ if list(offset) == before:
+ continue # the centre itself is not one of its own neighbours
+ shifted = tuple(slice(o, o + s - k + 1) for o, s, k in zip(offset, sizes, kernel_size))
+ neighbours = torch.maximum(neighbours, x[(..., *shifted)])
+ mask = torch.zeros_like(x, dtype=torch.bool)
+ mask[(..., *centre_at)] = centre > neighbours
+ return mask
+
+
class TestNMS2d(BaseTester):
def test_shape(self, device):
inp = torch.ones(1, 3, 4, 4, device=device)
@@ -161,6 +192,91 @@ class TestNMS2d(BaseTester):
img = torch.rand(batch_size, channels, height, width, device=device, dtype=torch.float64)
self.gradcheck(kornia.geometry.subpix.nms2d, (img, (3, 3)), nondet_tol=1e-4)
+ # ------------------------------------------------------------------ #4239, #4240
+ @pytest.mark.parametrize("kernel_size", [(3, 3), (5, 5), (7, 7), (9, 9), (15, 15), (4, 4)])
+ def test_matches_the_reference_rule(self, device, dtype, kernel_size):
+ # The three hand-written fast paths and the general path have to answer the same question.
+ # Parametrizing one reference over both is the pin: (3, 3), (5, 5) and (7, 7) take the
+ # explicit branches, the rest take the general one.
+ torch.manual_seed(0)
+ inp = (torch.rand(2, 3, 23, 27, device=device) * 4).to(dtype)
+ self.assert_close(
+ kornia.geometry.subpix.nms2d(inp, kernel_size, mask_only=True).to(dtype),
+ _reference_nms_mask(inp, kernel_size).to(dtype),
+ )
+
+ @pytest.mark.parametrize("kernel_size", [(5, 5), (9, 9)])
+ def test_a_plateau_holds_no_strict_maximum(self, device, dtype, kernel_size):
+ # The suppression is strict: tied neighbours kill each other. A max-pool written as
+ # `x == max_pool(x)` would keep the whole plateau instead.
+ inp = torch.zeros(1, 1, 31, 31, device=device, dtype=dtype)
+ inp[0, 0, 10:13, 10:13] = 1.0 # nine equal, mutually adjacent maxima
+ inp[0, 0, 22, 22] = 0.5 # one strictly larger than everything around it
+ mask = kornia.geometry.subpix.nms2d(inp, kernel_size, mask_only=True)
+ assert not bool(mask[0, 0, 10:13, 10:13].any())
+ assert bool(mask[0, 0, 22, 22])
+ assert int(mask.sum()) == 1
+
+ @pytest.mark.parametrize("kernel_size", [(3, 3), (5, 5), (9, 9), (15, 15)])
+ def test_the_border_strip_is_never_a_maximum(self, device, dtype, kernel_size):
+ # A peak whose window does not fit inside the image has not been compared against the
+ # neighbours that would decide it, so it is not reported (#4239). The strip is
+ # `(k - 1) // 2` wide, the same one the explicit paths have always rejected.
+ radius = (kernel_size[0] - 1) // 2
+ inside = torch.zeros(1, 1, 41, 41, device=device, dtype=dtype)
+ inside[0, 0, radius, radius] = 1.0
+ assert bool(kornia.geometry.subpix.nms2d(inside, kernel_size, mask_only=True)[0, 0, radius, radius])
+ outside = torch.zeros(1, 1, 41, 41, device=device, dtype=dtype)
+ outside[0, 0, radius - 1, radius] = 1.0
+ assert not bool(kornia.geometry.subpix.nms2d(outside, kernel_size, mask_only=True).any())
+
+ @pytest.mark.parametrize("kernel_size", [(11, 5), (5, 11), (13, 9)])
+ def test_non_square_kernel_size(self, device, dtype, kernel_size):
+ # A non-square window used to raise out of an internal `view`, because the conv kernel was
+ # built with its two extents swapped and the padding was applied to the wrong pair of
+ # edges (#4240).
+ torch.manual_seed(0)
+ inp = (torch.rand(1, 2, 29, 31, device=device) * 4).to(dtype)
+ self.assert_close(
+ kornia.geometry.subpix.nms2d(inp, kernel_size, mask_only=True).to(dtype),
+ _reference_nms_mask(inp, kernel_size).to(dtype),
+ )
+
+ def test_unit_window_suppresses_nothing(self, device, dtype):
+ # A 1x1 window has no neighbours, so every position is vacuously a strict maximum and the
+ # input comes back untouched. It used to come back thresholded at zero, an artifact of the
+ # zeroed centre tap summing to 0.0 rather than anything NMS means.
+ inp = torch.tensor([[[[float("-inf"), 0.0, 2.0], [0.5, -0.5, 0.0]]]], device=device, dtype=dtype)
+ assert bool(kornia.geometry.subpix.nms2d(inp, (1, 1), mask_only=True).all())
+ self.assert_close(kornia.geometry.subpix.nms2d(inp, (1, 1)), inp)
+
+ def test_unit_window_suppresses_nothing_integer(self, device):
+ inp = torch.tensor([[[[torch.iinfo(torch.int64).min, 0, 2]]]], device=device, dtype=torch.int64)
+ assert bool(kornia.geometry.subpix.nms2d(inp, (1, 1), mask_only=True).all())
+ self.assert_close(kornia.geometry.subpix.nms2d(inp, (1, 1)), inp)
+
+ def test_window_larger_than_the_input_finds_no_maxima(self, device, dtype):
+ inp = torch.rand(1, 1, 5, 5, device=device, dtype=dtype)
+ assert int(kornia.geometry.subpix.nms2d(inp, (9, 9), mask_only=True).sum()) == 0
+
+ def test_module_and_functional_agree(self, device, dtype):
+ torch.manual_seed(0)
+ inp = (torch.rand(1, 2, 21, 23, device=device) * 4).to(dtype)
+ module = kornia.geometry.subpix.NonMaximaSuppression2d((9, 9)).to(device)
+ self.assert_close(module(inp), kornia.geometry.subpix.nms2d(inp, (9, 9)))
+
+ @pytest.mark.parametrize("prefix", ["", "0."])
+ def test_loads_legacy_kernel_state_dict_strictly(self, prefix):
+ nms = kornia.geometry.subpix.NonMaximaSuppression2d((9, 9))
+ module = nms if prefix == "" else torch.nn.Sequential(nms)
+ incompatible = module.load_state_dict({f"{prefix}kernel": torch.empty(81, 1, 9, 9)})
+ assert incompatible.missing_keys == []
+ assert incompatible.unexpected_keys == []
+
+ def test_gradcheck_general_path(self, device):
+ img = torch.rand(1, 2, 13, 13, device=device, dtype=torch.float64)
+ self.gradcheck(kornia.geometry.subpix.nms2d, (img, (9, 9)), nondet_tol=1e-4)
+
class TestNMS3d(BaseTester):
def test_shape(self, device):
@@ -242,6 +358,51 @@ class TestNMS3d(BaseTester):
img = torch.rand(batch_size, channels, depth, height, width, device=device, dtype=torch.float64)
self.gradcheck(kornia.geometry.subpix.nms3d, (img, (3, 3, 3)), nondet_tol=1e-4)
+ # ------------------------------------------------------------------------------- #4241
+ @pytest.mark.parametrize("kernel_size", [(3, 3, 3), (5, 5, 5), (3, 5, 7), (5, 3, 3)])
+ def test_matches_the_reference_rule(self, device, dtype, kernel_size):
+ # Every kernel size other than (3, 3, 3) used to raise: `_compute_zero_padding3d` defined a
+ # `(k - 1) // 2` helper and then returned the full kernel sizes instead, so the padded
+ # volume did not match the kernel and the `view` after the convolution failed (#4241).
+ torch.manual_seed(0)
+ inp = (torch.rand(2, 2, 11, 13, 12, device=device) * 4).to(dtype)
+ self.assert_close(
+ kornia.geometry.subpix.nms3d(inp, kernel_size, mask_only=True).to(dtype),
+ _reference_nms_mask(inp, kernel_size).to(dtype),
+ )
+
+ @pytest.mark.parametrize("kernel_size", [(5, 5, 5), (3, 5, 7)])
+ def test_shape_general_kernel(self, device, kernel_size):
+ inp = torch.ones(1, 2, 9, 12, 12, device=device)
+ nms = kornia.geometry.subpix.NonMaximaSuppression3d(kernel_size).to(device)
+ assert nms(inp).shape == inp.shape
+
+ def test_a_plateau_holds_no_strict_maximum(self, device, dtype):
+ inp = torch.zeros(1, 1, 11, 21, 21, device=device, dtype=dtype)
+ inp[0, 0, 4:6, 8:10, 8:10] = 1.0
+ inp[0, 0, 5, 15, 15] = 0.5
+ mask = kornia.geometry.subpix.nms3d(inp, (5, 5, 5), mask_only=True)
+ assert not bool(mask[0, 0, 4:6, 8:10, 8:10].any())
+ assert int(mask.sum()) == 1
+
+ def test_window_larger_than_the_input_finds_no_maxima(self, device, dtype):
+ inp = torch.rand(1, 1, 2, 4, 4, device=device, dtype=dtype)
+ assert int(kornia.geometry.subpix.nms3d(inp, (5, 5, 5), mask_only=True).sum()) == 0
+
+ def test_unit_window_suppresses_nothing(self, device, dtype):
+ inp = torch.tensor([[[[[float("-inf"), 0.0, 2.0]]]]], device=device, dtype=dtype)
+ assert bool(kornia.geometry.subpix.nms3d(inp, (1, 1, 1), mask_only=True).all())
+ self.assert_close(kornia.geometry.subpix.nms3d(inp, (1, 1, 1)), inp)
+
+ def test_unit_window_suppresses_nothing_integer(self, device):
+ inp = torch.tensor([[[[[torch.iinfo(torch.int64).min, 0, 2]]]]], device=device, dtype=torch.int64)
+ assert bool(kornia.geometry.subpix.nms3d(inp, (1, 1, 1), mask_only=True).all())
+ self.assert_close(kornia.geometry.subpix.nms3d(inp, (1, 1, 1)), inp)
+
+ def test_gradcheck_general_path(self, device):
+ img = torch.rand(1, 1, 7, 9, 9, device=device, dtype=torch.float64)
+ self.gradcheck(kornia.geometry.subpix.nms3d, (img, (5, 5, 5)), nondet_tol=1e-4)
+
class TestNMS3dMinMax(BaseTester):
def test_shapes(self, device):