π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
perf(feature): sample ALIKED's deformable convolution with grid_sample without autograd (M1 MPS ~1.8x forward) (#6464)
Dmytro Mishkin229c113d9933
diff --git a/changelog.d/6464.added.md b/changelog.d/6464.added.mdnew file mode 100644index 000000000..265accc77--- /dev/null+++ b/changelog.d/6464.added.md@@ -0,0 +1 @@+Under `torch.no_grad()` or `torch.inference_mode()`, `ALIKED` and `kornia.feature.aliked.deform_conv2d` sample the deformable convolution with one `grid_sample` call over every offset group instead of four gathers per sample. On an Apple M1 the ALIKED-n16 forward of a 640 x 512 image is 1.8x faster on MPS, in float32 and float16, and 5 % faster on CPU; outputs change by rounding. Half-precision inputs are sampled in float32, as accurately as before. With autograd enabled the previous sampler stays: `grid_sample`'s normalized coordinates can round a sample at an integer position onto the previous pixel and give it that pixel's derivative.diff --git a/kornia/feature/aliked/deform_conv2d.py b/kornia/feature/aliked/deform_conv2d.pyindex b898a19df..59e2afa2e 100644--- a/kornia/feature/aliked/deform_conv2d.py+++ b/kornia/feature/aliked/deform_conv2d.py@@ -27,6 +27,7 @@ from __future__ import annotationsfrom typing import Optional, Tuple, Unionimport torch+import torch.nn.functional as Ffrom torch import Tensor@@ -105,8 +106,14 @@ def deform_conv2d(sample_h = base_h + kern_h + off_ysample_w = base_w + kern_w + off_x- # bilinear interpolation with zero-padding- sampled = _bilinear_sample(input, sample_h, sample_w, n_off_grps, c_per_off_grp)+ # bilinear interpolation with zero-padding. Without autograd one grid_sample samples every offset group, which+ # makes ALIKED inference about 1.7x faster on MPS. Autograd keeps the absolute-coordinate sampler: normalized+ # coordinates can round a sample at an integer position, such as any sample of a zero offset, onto the other+ # side of the pixel, which changes its one-sided derivative.+ if torch.is_grad_enabled():+ sampled = _bilinear_sample(input, sample_h, sample_w, n_off_grps, c_per_off_grp)+ else:+ sampled = _grid_sample_bilinear(input, sample_h, sample_w, n_off_grps, c_per_off_grp)# sampled: [B, n_off_grps, c_per_off_grp, K, H_out, W_out]# apply mask (DCNv2 modulation)@@ -129,6 +136,47 @@ def deform_conv2d(return out+def _grid_sample_bilinear(+ input: Tensor,+ sample_h: Tensor,+ sample_w: Tensor,+ n_off_grps: int,+ c_per_off_grp: int,+) -> Tensor:+ """Sample input at fractional (sample_h, sample_w) positions with zero-padding, using one ``grid_sample``.++ Gives the values of :func:`_bilinear_sample`. Offset groups are folded into the batch of ``grid_sample`` and+ kernel points into its output height. Half-precision inputs are sampled in float32: rounding the normalized+ coordinates to half precision would add error that the absolute-coordinate sampler does not have.++ Args:+ input: ``(B, C_in, H_in, W_in)``+ sample_h: ``(B, n_off_grps, K, H_out, W_out)``+ sample_w: ``(B, n_off_grps, K, H_out, W_out)``+ n_off_grps: number of offset groups.+ c_per_off_grp: input channels per offset group.++ Returns:+ Sampled tensor ``(B, n_off_grps, c_per_off_grp, K, H_out, W_out)``.+ """+ B, _C_in, H_in, W_in = input.shape+ _B, _G, K, H_out, W_out = sample_h.shape+ dtype = torch.promote_types(input.dtype, torch.float32)+ sample_h = sample_h.to(dtype)+ sample_w = sample_w.to(dtype)+ # Pixel p is at (2 * p + 1) / size - 1 with align_corners=False. Clamping keeps a huge finite position from+ # overflowing; +-3 lies wholly in the zero padding for any size.+ grid_x = ((2 * sample_w + 1) / W_in - 1).clamp(-3, 3)+ grid_y = ((2 * sample_h + 1) / H_in - 1).clamp(-3, 3)+ grid = torch.stack((grid_x, grid_y), dim=-1).reshape(B * n_off_grps, K * H_out, W_out, 2)+ grouped = input.to(dtype).reshape(B * n_off_grps, c_per_off_grp, H_in, W_in)+ sampled = F.grid_sample(grouped, grid, mode="bilinear", padding_mode="zeros", align_corners=False)+ sampled = sampled.reshape(B, n_off_grps, c_per_off_grp, K, H_out, W_out)+ # _bilinear_sample returns nan at a non-finite position, whereas grid_sample differs between devices there.+ nonfinite = ~(torch.isfinite(sample_h) & torch.isfinite(sample_w))+ return sampled.masked_fill(nonfinite.unsqueeze(2), float("nan")).to(input.dtype)++def _bilinear_sample(input: Tensor,sample_h: Tensor,diff --git a/tests/feature/test_aliked.py b/tests/feature/test_aliked.pyindex 93b25b0f3..d3463f6e9 100644--- a/tests/feature/test_aliked.py+++ b/tests/feature/test_aliked.py@@ -15,6 +15,8 @@# limitations under the License.#+import importlib+import pytestimport torchimport torch.nn.functional as F@@ -23,7 +25,7 @@ import korniafrom kornia.feature import laf_is_filledfrom kornia.feature.aliked import ALIKED, ALIKEDFeaturesfrom kornia.feature.aliked.aliked import SDDH, _affine_from_cov, get_patches-from kornia.feature.aliked.deform_conv2d import deform_conv2d+from kornia.feature.aliked.deform_conv2d import _bilinear_sample, _grid_sample_bilinear, deform_conv2dfrom testing.base import (BaseTester,@@ -188,44 +190,46 @@ class TestDeformConv2d(BaseTester):dtype=torch.float64,).reshape(1, 2, 4, 4)+ @pytest.mark.parametrize("grad_enabled", [True, False])@pytest.mark.parametrize("use_mask", [False, True])- def test_matches_torchvision_reference(self, device, dtype, use_mask):+ def test_matches_torchvision_reference(self, device, dtype, use_mask, grad_enabled):"""Pure-PyTorch implementation should match a hardcoded torchvision-generated literal.Replaces a live comparison against ``torchvision.ops.deform_conv2d`` (skipif-guarded ontorchvision, which no CI environment installs, so it never ran there) with a literal- generated once offline -- see the comment above ``_EXPECTED_NO_MASK``.+ generated once offline -- see the comment above ``_EXPECTED_NO_MASK``. Without autograd+ deform_conv2d samples with ``grid_sample``, so both samplers are checked."""if device.type == "mps" and dtype == torch.float64:pytest.skip("MPS does not support float64")-- x64, weight64, bias64, offset64, mask64 = self._torchvision_reference_inputs()- expected64 = self._EXPECTED_WITH_MASK if use_mask else self._EXPECTED_NO_MASK-- x = x64.to(device=device, dtype=dtype)- weight = weight64.to(device=device, dtype=dtype)- bias = bias64.to(device=device, dtype=dtype)- offset = offset64.to(device=device, dtype=dtype)- mask = mask64.to(device=device, dtype=dtype) if use_mask else None-- out = deform_conv2d(x, offset, weight, bias=bias, padding=1, stride=1, mask=mask)- expected = expected64.to(device=device, dtype=dtype)-- if dtype == torch.float64 and device.type == "cpu":- # The literal is quoted to 10 decimals (its own rounding is <= 5e-11) and kornia's float64- # CPU result lands within 5e-11 of it, so an absolute bound of 1e-9 still has 20x headroom;- # a looser bound would only hide float64 arithmetic bugs.- self.assert_close(out, expected, rtol=0, atol=1e-9)- else:- self.assert_close(out, expected)-- # Guard a float32 precision regression against the float64 reference, regardless of the- # dtype this test instance is parametrized over.- mask32 = mask64.float() if use_mask else None- out_f32 = deform_conv2d(- x64.float(), offset64.float(), weight64.float(), bias=bias64.float(), padding=1, stride=1, mask=mask32- )- assert torch.allclose(out_f32.double(), expected64, rtol=0, atol=1e-5)+ with torch.set_grad_enabled(grad_enabled):+ x64, weight64, bias64, offset64, mask64 = self._torchvision_reference_inputs()+ expected64 = self._EXPECTED_WITH_MASK if use_mask else self._EXPECTED_NO_MASK++ x = x64.to(device=device, dtype=dtype)+ weight = weight64.to(device=device, dtype=dtype)+ bias = bias64.to(device=device, dtype=dtype)+ offset = offset64.to(device=device, dtype=dtype)+ mask = mask64.to(device=device, dtype=dtype) if use_mask else None++ out = deform_conv2d(x, offset, weight, bias=bias, padding=1, stride=1, mask=mask)+ expected = expected64.to(device=device, dtype=dtype)++ if dtype == torch.float64 and device.type == "cpu":+ # The literal is quoted to 10 decimals (its own rounding is <= 5e-11) and kornia's float64+ # CPU result lands within 5e-11 of it, so an absolute bound of 1e-9 still has 20x headroom;+ # a looser bound would only hide float64 arithmetic bugs.+ self.assert_close(out, expected, rtol=0, atol=1e-9)+ else:+ self.assert_close(out, expected)++ # Guard a float32 precision regression against the float64 reference, regardless of the+ # dtype this test instance is parametrized over.+ mask32 = mask64.float() if use_mask else None+ out_f32 = deform_conv2d(+ x64.float(), offset64.float(), weight64.float(), bias=bias64.float(), padding=1, stride=1, mask=mask32+ )+ assert torch.allclose(out_f32.double(), expected64, rtol=0, atol=1e-5)def test_gradients(self, device):"""Gradients should flow through the pure-PyTorch implementation."""@@ -243,6 +247,182 @@ class TestDeformConv2d(BaseTester):assert weight.grad is not Noneassert offset.grad is not None+ @pytest.mark.parametrize(+ "shape, groups, n_off_grps, stride, dilation, use_mask",+ [+ ((2, 4, 5, 7), 2, 2, 1, 1, True), # conv groups and offset groups that differ+ ((1, 4, 6, 9), 1, 4, 2, 2, False), # stride and dilation+ ((1, 2, 1, 5), 1, 1, 1, 1, True), # a single row+ ((1, 2, 4, 1), 1, 2, 1, 1, False), # a single column+ ],+ )+ def test_inference_matches_autograd_sampler(+ self, device, dtype, shape, groups, n_off_grps, stride, dilation, use_mask+ ):+ """Without autograd the grid_sample sampler gives the values of the absolute-coordinate one."""+ if device.type == "mps" and dtype == torch.float64:+ pytest.skip("MPS does not support float64")+ B, C_in, H, W = shape+ C_out, kH, kW = 6, 3, 3+ K = kH * kW+ H_out = (H + 2 - dilation * (kH - 1) - 1) // stride + 1+ W_out = (W + 2 - dilation * (kW - 1) - 1) // stride + 1+ x = torch.linspace(-1, 1, B * C_in * H * W, dtype=torch.float64).reshape(B, C_in, H, W)+ weight = torch.linspace(-0.5, 0.5, C_out * (C_in // groups) * K, dtype=torch.float64)+ weight = weight.reshape(C_out, C_in // groups, kH, kW)+ # offsets of up to 1.5 px move samples across every image border, into the zero padding and back+ offset = 1.5 * torch.sin(torch.arange(B * 2 * n_off_grps * K * H_out * W_out, dtype=torch.float64))+ offset = offset.reshape(B, 2 * n_off_grps * K, H_out, W_out)+ mask = torch.sigmoid(torch.cos(torch.arange(B * n_off_grps * K * H_out * W_out, dtype=torch.float64)))+ mask = mask.reshape(B, n_off_grps * K, H_out, W_out) if use_mask else None+ kwargs = {"padding": 1, "stride": stride, "dilation": dilation}++ x, offset, weight, mask = (t.to(device, dtype) if t is not None else None for t in (x, offset, weight, mask))++ expected = deform_conv2d(x, offset, weight, mask=mask, **kwargs)+ with torch.no_grad():+ actual = deform_conv2d(x, offset, weight, mask=mask, **kwargs)+ # In half precision the samplers round the sampled values differently, which can move an output by two units+ # in its last place.+ tol = {torch.float16: 2e-3, torch.bfloat16: 1.6e-2}.get(dtype)+ self.assert_close(actual, expected, rtol=tol, atol=tol)++ def test_dynamo(self, device, dtype, torch_optimizer):+ """Compiled without autograd, the grid_sample sampler gives eager's values, or more accurate ones in half."""+ if device.type == "mps" and dtype == torch.float64:+ pytest.skip("MPS does not support float64")+ g = torch.Generator().manual_seed(0)+ # two offset groups and two convolution groups, a stride and a mask+ x = torch.randn(2, 8, 13, 17, generator=g, dtype=torch.float64)+ weight = torch.randn(6, 4, 3, 3, generator=g, dtype=torch.float64)+ offset = 2 * torch.randn(2, 2 * 2 * 9, 7, 9, generator=g, dtype=torch.float64)+ mask = torch.rand(2, 2 * 9, 7, 9, generator=g, dtype=torch.float64)+ x, weight, offset, mask = (t.to(device, dtype) for t in (x, weight, offset, mask))+ op = torch_optimizer(deform_conv2d, fullgraph=True)++ with torch.no_grad():+ expected = deform_conv2d(x, offset, weight, stride=2, padding=1, mask=mask)+ actual = op(x, offset, weight, stride=2, padding=1, mask=mask)++ if dtype in (torch.float16, torch.bfloat16):+ # Inductor keeps the sample positions in float32, which eager sums in half precision. Compare both with+ # float64 sampling of the same rounded inputs instead of with each other.+ with torch.no_grad():+ reference = deform_conv2d(+ *(t.cpu().double() for t in (x, offset, weight)), stride=2, padding=1, mask=mask.cpu().double()+ )+ compiled_error = (actual.cpu().double() - reference).abs().mean()+ assert compiled_error <= (expected.cpu().double() - reference).abs().mean()+ else:+ self.assert_close(actual, expected)++ def test_inference_samples_with_grid_sample(self, device, dtype, monkeypatch):+ """Without autograd deform_conv2d does not call the absolute-coordinate sampler."""+ if device.type == "mps" and dtype == torch.float64:+ pytest.skip("MPS does not support float64")++ def autograd_sampler(*args):+ raise AssertionError("the absolute-coordinate sampler ran without autograd")++ # the package attribute `deform_conv2d` is the function, which shadows its module+ module = importlib.import_module("kornia.feature.aliked.deform_conv2d")+ monkeypatch.setattr(module, "_bilinear_sample", autograd_sampler)+ x = torch.ones(1, 2, 4, 5, device=device, dtype=dtype)+ weight = torch.ones(3, 2, 3, 3, device=device, dtype=dtype)+ offset = torch.zeros(1, 18, 4, 5, device=device, dtype=dtype)+ with torch.no_grad():+ assert deform_conv2d(x, offset, weight, padding=1).shape == (1, 3, 4, 5)+ with pytest.raises(AssertionError, match="without autograd"):+ deform_conv2d(x, offset, weight, padding=1)++ def test_inference_sampler_is_accurate_in_half_precision(self, device, dtype):+ """grid_sample samples half-precision inputs in float32, at least as accurately as the autograd sampler.++ Sampled in half precision, the normalized coordinates would be several times less accurate.+ """+ if dtype not in (torch.float16, torch.bfloat16):+ pytest.skip("half precision only")+ C, H, W, K = 8, 37, 53, 9+ n = K * H * W+ x = torch.sin(0.37 * torch.arange(C * H * W, dtype=torch.float64)).reshape(1, C, H, W)+ rows = torch.arange(H, dtype=torch.float64).reshape(1, 1, 1, H, 1)+ cols = torch.arange(W, dtype=torch.float64).reshape(1, 1, 1, 1, W)+ sample_h = rows + 2.5 * torch.sin(1.3 * torch.arange(n, dtype=torch.float64)).reshape(1, 1, K, H, W)+ sample_w = cols + 2.5 * torch.cos(0.7 * torch.arange(n, dtype=torch.float64)).reshape(1, 1, K, H, W)+ x, sample_h, sample_w = (t.to(device, dtype) for t in (x, sample_h, sample_w))+ # the reference of the inputs as rounded to `dtype`+ expected = _bilinear_sample(*(t.cpu().double() for t in (x, sample_h, sample_w)), 1, C)++ inference = _grid_sample_bilinear(x, sample_h, sample_w, 1, C).cpu().double()+ autograd = _bilinear_sample(x, sample_h, sample_w, 1, C).cpu().double()+ assert (inference - expected).abs().mean() <= (autograd - expected).abs().mean()++ def test_inference_nonfinite_offsets_give_nan(self, device, dtype):+ """A nan or infinite offset gives nan in both samplers, which grid_sample alone does not do on every device."""+ if device.type == "mps" and dtype == torch.float64:+ pytest.skip("MPS does not support float64")+ x = torch.arange(15, device=device, dtype=dtype).reshape(1, 1, 3, 5)+ weight = torch.ones(1, 1, 1, 1, device=device, dtype=dtype)+ offset = torch.zeros(1, 2, 3, 5, device=device, dtype=dtype)+ offset[0, 0, 0, 0] = float("nan")+ offset[0, 1, 0, 1] = float("inf")+ offset[0, 1, 0, 2] = float("-inf")++ expected = deform_conv2d(x, offset, weight)+ with torch.no_grad():+ actual = deform_conv2d(x, offset, weight)+ nan = torch.isnan(expected)+ assert nan.sum() == 3+ assert torch.equal(torch.isnan(actual), nan)+ self.assert_close(actual[~nan], expected[~nan])++ @pytest.mark.parametrize("image_hw", [(1, 5), (4, 1), (3, 5)])+ def test_inference_huge_finite_offsets_sample_zero_padding(self, device, dtype, image_hw):+ """A finite offset too large to normalize lands in the zero padding instead of overflowing."""+ if device.type == "mps" and dtype == torch.float64:+ pytest.skip("MPS does not support float64")+ H, W = image_hw+ x = torch.arange(1, H * W + 1, device=device, dtype=dtype).reshape(1, 1, H, W)+ weight = torch.ones(1, 1, 1, 1, device=device, dtype=dtype)+ offset = torch.empty(1, 2, H, W, device=device, dtype=dtype)+ offset[:, 0].fill_(torch.finfo(dtype).max)+ offset[:, 1].fill_(-torch.finfo(dtype).max)++ with torch.no_grad():+ actual = deform_conv2d(x, offset, weight)+ self.assert_close(actual, torch.zeros_like(actual))++ @pytest.mark.parametrize("grad_enabled", [True, False])+ def test_empty_batch(self, device, dtype, grad_enabled):+ if device.type == "mps" and dtype == torch.float64:+ pytest.skip("MPS does not support float64")+ x = torch.empty(0, 4, 5, 7, device=device, dtype=dtype)+ weight = torch.empty(6, 2, 3, 3, device=device, dtype=dtype)+ offset = torch.empty(0, 18, 5, 7, device=device, dtype=dtype)+ with torch.set_grad_enabled(grad_enabled):+ output = deform_conv2d(x, offset, weight, padding=1)+ assert output.shape == (0, 6, 5, 7)++ def test_integer_offset_derivative_uses_the_next_pixel(self, device, dtype):+ """Autograd keeps the absolute-coordinate sampler, whose derivative at an integer position is one-sided.++ grid_sample's normalized coordinates round some integer positions down onto the previous pixel, which would+ give those positions the derivative from the left instead.+ """+ if device.type == "mps" and dtype == torch.float64:+ pytest.skip("MPS does not support float64")+ H, W = 7, 11+ image = (3 + torch.arange(H * W, device=device, dtype=dtype)).reshape(1, 1, H, W)+ weight = torch.ones(1, 1, 1, 1, device=device, dtype=dtype)+ offset = torch.zeros(1, 2, H, W, device=device, dtype=dtype, requires_grad=True)++ deform_conv2d(image, offset, weight).sum().backward()++ # the next pixel, or the zero padding after the last one, minus the pixel itself+ padded = F.pad(image, (0, 1, 0, 1))+ expected = torch.cat((padded[..., 1:, :-1] - image, padded[..., :-1, 1:] - image), dim=1)+ self.assert_close(offset.grad, expected)+# ---------------------------------------------------------------------------# ALIKED testsdiff --git a/tests/feature/test_xfeat.py b/tests/feature/test_xfeat.pyindex e6c697aa1..2421f196e 100644--- a/tests/feature/test_xfeat.py+++ b/tests/feature/test_xfeat.py@@ -829,7 +829,8 @@ class TestConventionsXFeat(BaseTester):# torch's CPU float16 / bfloat16 grid_sample returns wrong values, NaN and overflow on sparse grids into larger# maps (#5810), and torch 2.5.1 has no such kernel. XFeat's InterpolateSparse2d, ALIKED (DKD scores and SDDH# descriptors) and SOLD2.match call it with the half map and grid directly;- # kornia.core.utils._torch_grid_sample, which the warps use, samples CPU half in float32 instead.+ # kornia.core.utils._torch_grid_sample, which the warps use, samples CPU half in float32 instead, and so does+ # ALIKED's deformable convolution without autograd (#6464).if device.type != "cpu" or dtype not in (torch.float16, torch.bfloat16):pytest.skip("the defect is in the CPU float16 / bfloat16 path")if sampler == "ALIKED" and not supports_replicate_padding(device, dtype):@@ -863,4 +864,5 @@ class TestConventionsXFeat(BaseTester):maps = torch.rand(2, 1, 128, 24, 32, dtype=dtype)SOLD2(pretrained=False).eval().match(segments, segments + 1.0, maps[0], maps[1])assert calls- assert set(calls) == {(dtype, dtype)}+ expected = {(dtype, dtype), (torch.float32, torch.float32)} if sampler == "ALIKED" else {(dtype, dtype)}+ assert set(calls) == expected