Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

perf(feature): compute MKD's explicit spatial encoding as one matmul (#4598)

Dipak Chaudharid3a94d0b47c1
diff --git a/changelog.d/4598.fixed.md b/changelog.d/4598.fixed.md
new file mode 100644
index 000000000..e7639e44f
--- /dev/null
+++ b/changelog.d/4598.fixed.md
@@ -0,0 +1 @@
+`MKDDescriptor`'s `ExplicitSpacialEncoding` computes the spatial encoding with one matrix multiply instead of building a `(B, in_dims * d_emb, H, W)` product and summing it over the spatial dimensions. Descriptor values are unchanged and existing state dicts still load. `ExplicitSpacialEncoding` now raises `ValueError` for an input whose channel count differs from `in_dims`, as documented; its shape check could never fire.
diff --git a/kornia/feature/mkd.py b/kornia/feature/mkd.py
index d3df585e9..60e7a301c 100644
--- a/kornia/feature/mkd.py
+++ b/kornia/feature/mkd.py
@@ -385,12 +385,17 @@ class ExplicitSpacialEncoding(nn.Module):
"""
if not isinstance(x, torch.Tensor):
raise TypeError(f"Input type is not a torch.Tensor. Got {type(x)}")
- if not ((len(x.shape) == 4) | (x.shape[1] == self.in_dims)):
+ if not ((len(x.shape) == 4) and (x.shape[1] == self.in_dims)):
raise ValueError(f"Invalid input shape, we expect Bx{self.in_dims}xHxW. Got: {x.shape}")
- idx1 = torch.jit.annotate(torch.Tensor, self.idx1)
- emb1 = torch.index_select(x, 1, idx1)
- output = emb1 * self.emb2
- output = output.sum(dim=(2, 3))
+ # output[b, c * d_emb + e] = sum_hw x[b, c, h, w] * emb[e, h, w]: every (c, e)
+ # pair in the row-major order of get_kron_order, which `emb2` / `idx1` spell as a
+ # gather. One matmul computes the same contraction without materialising the
+ # (B, in_dims * d_emb, H, W) product of that gather. The two buffers are kept so
+ # existing state dicts still load.
+ emb = torch.jit.annotate(torch.Tensor, self.emb)
+ dtype = torch.promote_types(x.dtype, emb.dtype)
+ output = torch.matmul(x.flatten(2).to(dtype), emb.flatten(2).transpose(1, 2).to(dtype))
+ output = output.flatten(1)
if self.do_l2:
output = _l2_normalize(output, dim=1)
return output
diff --git a/tests/feature/test_mkd.py b/tests/feature/test_mkd.py
index 589810fa5..43bed8c80 100644
--- a/tests/feature/test_mkd.py
+++ b/tests/feature/test_mkd.py
@@ -293,6 +293,15 @@ class TestExplicitSpacialEncoding(BaseTester):
ese = ExplicitSpacialEncoding(kernel_type=kernel_type, fmap_size=15, in_dims=7).to(device)
ese.__repr__()
+ @pytest.mark.parametrize("kernel_type", ["cart", "polar"])
+ def test_exception(self, kernel_type, device):
+ ese = ExplicitSpacialEncoding(kernel_type=kernel_type, fmap_size=15, in_dims=7).to(device)
+ # a wrong channel count must raise rather than return a descriptor of the wrong width
+ with pytest.raises(ValueError, match="we expect Bx7xHxW"):
+ ese(torch.ones(2, 5, 15, 15, device=device))
+ with pytest.raises(ValueError, match="we expect Bx7xHxW"):
+ ese(torch.ones(7, 15, 15, device=device))
+
def test_toy(self, device):
inp = torch.ones(1, 2, 6, 6).to(device).float()
inp[0, 0, :, :] = 0