Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

Fix strided heatmaps and masks in subpixel refinement (#5673)

A Aswanth Raj0fcfc5c52117
diff --git a/changelog.d/5673.fixed.md b/changelog.d/5673.fixed.md
new file mode 100644
index 000000000..5b7d8e873
--- /dev/null
+++ b/changelog.d/5673.fixed.md
@@ -0,0 +1 @@
+Accept channels-last and other strided heatmaps in convolutional soft-argmax and quadratic subpixel refinement, including strided precomputed NMS masks. Coordinates and responses match contiguous copies.
diff --git a/kornia/geometry/subpix/spatial_soft_argmax.py b/kornia/geometry/subpix/spatial_soft_argmax.py
index 7c9df4bfd..ff84ca6bb 100644
--- a/kornia/geometry/subpix/spatial_soft_argmax.py
+++ b/kornia/geometry/subpix/spatial_soft_argmax.py
@@ -400,7 +400,7 @@ def conv_soft_argmax2d(
py, px = (padding, padding) if isinstance(padding, int) else padding
device: torch.device = input.device
dtype: torch.dtype = input.dtype
- input = input.view(b * c, 1, h, w)
+ input = input.reshape(b * c, 1, h, w)
center_kernel: torch.Tensor = _get_center_kernel2d(ky, kx, device).to(dtype)
window_kernel: torch.Tensor = _get_window_grid_kernel2d(ky, kx, device).to(dtype)
@@ -536,7 +536,7 @@ def conv_soft_argmax3d(
pz, py, px = (padding, padding, padding) if isinstance(padding, int) else padding
device: torch.device = input.device
dtype: torch.dtype = input.dtype
- input = input.view(b * c, 1, d, h, w)
+ input = input.reshape(b * c, 1, d, h, w)
center_kernel: torch.Tensor = _get_center_kernel3d(kz, ky, kx, device).to(dtype)
window_kernel: torch.Tensor = _get_window_grid_kernel3d(kz, ky, kx, device).to(dtype)
@@ -903,7 +903,7 @@ def conv_quad_interp3d(
# ── Step 1: NMS maxima ────────────────────────────────────────────────────
nms_mask = precomputed_nms_mask if precomputed_nms_mask is not None else nms3d(input, (3, 3, 3), True)
- bc_idx, d_idx, h_idx, w_idx = torch.where(nms_mask.view(BC, D, H, W))
+ bc_idx, d_idx, h_idx, w_idx = torch.where(nms_mask.reshape(BC, D, H, W))
N = bc_idx.shape[0]
# Note: no early-return for N==0 β€” empty tensors flow through all ops as no-ops.
@@ -942,7 +942,7 @@ def conv_quad_interp3d(
# quadratic system), so last-write-wins in the LUT is correct.
# ── Step 3: gather 3x3x3 neighbourhood for all kept dilated positions ────
- inp_flat = input.view(-1)
+ inp_flat = input.reshape(-1)
patch_offsets = _PATCH_DD.to(device) * HW + _PATCH_DH.to(device) * W + _PATCH_DW.to(device) # (27,)
center_flat = bc_u * DHW + d_u * HW + h_u * W + w_u
patch = inp_flat[center_flat.unsqueeze(1) + patch_offsets.unsqueeze(0)] # (NU, 27)
@@ -1077,7 +1077,7 @@ def conv_quad_interp3d(
d_cur = torch.where(valid, d_cur, d_idx)
h_cur = torch.where(valid, h_cur, h_idx)
w_cur = torch.where(valid, w_cur, w_idx)
- val_center = input.view(BC, D, H, W)[bc_idx, d_cur, h_cur, w_cur]
+ val_center = inp_flat.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
return coords_max, y_max
@@ -1247,7 +1247,7 @@ def iterative_quad_interp3d(
DHW = D * H * W
HW = H * W
- nms_flat = (precomputed_nms_mask if precomputed_nms_mask is not None else nms3d(input, (3, 3, 3), True)).view(
+ nms_flat = (precomputed_nms_mask if precomputed_nms_mask is not None else nms3d(input, (3, 3, 3), True)).reshape(
B * C, D, H, W
)
diff --git a/tests/geometry/subpix/test_spatial_softargmax.py b/tests/geometry/subpix/test_spatial_softargmax.py
index 0bace3727..04ec44349 100644
--- a/tests/geometry/subpix/test_spatial_softargmax.py
+++ b/tests/geometry/subpix/test_spatial_softargmax.py
@@ -16,6 +16,7 @@
#
import itertools
+import math
import warnings
import pytest
@@ -32,6 +33,74 @@ from kornia.geometry.subpix.spatial_soft_argmax import (
from testing.base import BaseTester
+class TestStridedSubpixel(BaseTester):
+ @pytest.mark.parametrize(
+ "operation", ["conv_soft_argmax2d", "conv_soft_argmax3d", "conv_quad_interp3d", "iterative_quad_interp3d"]
+ )
+ @pytest.mark.parametrize("layout", ["channels_last", "batch_channel_transpose", "spatial_transpose", "slice"])
+ def test_heatmap_layout(self, device, dtype, operation, layout):
+ shape = (2, 3, 5, 7) if operation.endswith("2d") else (2, 3, 5, 6, 7)
+ sample = torch.arange(math.prod(shape), device=device, dtype=torch.float32)
+ sample = sample.sin().reshape(shape).to(dtype)
+ if layout == "channels_last":
+ memory_format = torch.channels_last if len(shape) == 4 else torch.channels_last_3d
+ sample = sample.to(memory_format=memory_format)
+ elif layout == "batch_channel_transpose":
+ sample = sample.transpose(0, 1)
+ elif layout == "spatial_transpose":
+ sample = sample.transpose(-1, -2)
+ else:
+ sample = sample[..., ::2]
+ assert not sample.is_contiguous()
+ function = getattr(kornia.geometry.subpix, operation)
+ kwargs = {"output_value": True} if "soft_argmax" in operation else {}
+
+ expected = function(sample.contiguous(), **kwargs)
+ actual = function(sample, **kwargs)
+
+ for result, reference in zip(actual, expected):
+ self.assert_close(result, reference, atol=0, rtol=0)
+
+ @pytest.mark.parametrize("operation", ["conv_soft_argmax2d", "conv_soft_argmax3d"])
+ def test_channels_last_gradient(self, device, operation):
+ if device.type == "mps":
+ pytest.skip("MPS does not support float64")
+ shape = (2, 3, 5, 7) if operation.endswith("2d") else (2, 3, 5, 6, 7)
+ sample = torch.arange(math.prod(shape), device=device, dtype=torch.float64).sin().reshape(shape)
+ reference = sample.clone().requires_grad_()
+ memory_format = torch.channels_last if len(shape) == 4 else torch.channels_last_3d
+ strided = sample.to(memory_format=memory_format).requires_grad_()
+ function = getattr(kornia.geometry.subpix, operation)
+
+ expected = function(reference, output_value=True)
+ actual = function(strided, output_value=True)
+ expected_grad = torch.autograd.grad(sum(value.sum() for value in expected), reference)[0]
+ actual_grad = torch.autograd.grad(sum(value.sum() for value in actual), strided)[0]
+
+ self.assert_close(actual_grad, expected_grad)
+
+ @pytest.mark.parametrize("operation", ["conv_quad_interp3d", "iterative_quad_interp3d"])
+ @pytest.mark.parametrize("layout", ["channels_last", "batch_channel_transpose", "spatial_transpose"])
+ def test_precomputed_mask_layout(self, device, dtype, operation, layout):
+ sample = torch.arange(2 * 3 * 5 * 6 * 7, device=device, dtype=torch.float32).sin()
+ sample = sample.reshape(2, 3, 5, 6, 7).to(dtype)
+ mask = kornia.geometry.subpix.nms3d(sample, (3, 3, 3), True)
+ if layout == "channels_last":
+ mask = mask.to(memory_format=torch.channels_last_3d)
+ elif layout == "batch_channel_transpose":
+ mask, sample = mask.transpose(0, 1), sample.transpose(0, 1).contiguous()
+ else:
+ mask, sample = mask.transpose(-1, -2), sample.transpose(-1, -2).contiguous()
+ assert not mask.is_contiguous()
+ function = getattr(kornia.geometry.subpix, operation)
+
+ expected = function(sample, precomputed_nms_mask=mask.contiguous())
+ actual = function(sample, precomputed_nms_mask=mask)
+
+ for result, reference in zip(actual, expected):
+ self.assert_close(result, reference, atol=0, rtol=0)
+
+
class TestCenterKernel2d(BaseTester):
def test_smoke(self, device, dtype):
kernel = _get_center_kernel2d(3, 4, device=device).to(dtype=dtype)