Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

perf(feature): DeDoDe-G DINOv2 attention via SDPA; fix the half-precision DeDoDe scoremap (#6430)

Dmytro Mishkinf04c0c9e245c
diff --git a/changelog.d/6430.added.md b/changelog.d/6430.added.md
new file mode 100644
index 000000000..e79c0ec64
--- /dev/null
+++ b/changelog.d/6430.added.md
@@ -0,0 +1 @@
+The DINOv2 attention of the `DeDoDe` `G` descriptor uses `torch.nn.functional.scaled_dot_product_attention` instead of materialising the attention weights of every head; only training mode with a non-zero `attn_drop`, which no kornia builder sets, still materialises them. On an Apple M1 the attention layer is about 2x faster on the CPU, and the whole 24-block ViT-L backbone 1.3x faster on the CPU at 476 x 644 and 1.1 to 1.2x faster on MPS at 476 x 644 and 784 x 784. The extra CPU memory of one attention layer at 784 x 784 falls from 1.3 GB to 73 MB, and the outputs agree with the previous ones to float32 rounding.
diff --git a/changelog.d/6430.fixed.md b/changelog.d/6430.fixed.md
new file mode 100644
index 000000000..24f4d33dd
--- /dev/null
+++ b/changelog.d/6430.fixed.md
@@ -0,0 +1 @@
+`DeDoDe.detect` and `DeDoDe.forward` take the scoremap softmax and the keypoint sampling in float32 for a float16 or bfloat16 model, and the detector logits are no longer rounded to the half dtype, so the scores of a half-precision model are float32 like its keypoints. They used to run in the model dtype: in float16 the probabilities of an image above 128 x 128 fall below the smallest normal number, and on a peaky synthetic map 97 % of the top-10000 scores were 0 and only 15 % of the float32 keypoints were kept; bfloat16 kept 99.5 % of them, in another order. Float32 models are unchanged on CPU and MPS; on CUDA, where `amp_dtype` autocast is on by default, the first upsampling of the logits now also runs in float32, as in the reference. Float64 models keep every logit term in float64 instead of rounding the later ones to float32.
diff --git a/kornia/feature/dedode/dedode.py b/kornia/feature/dedode/dedode.py
index 7895ebc2a..f78dc0d39 100644
--- a/kornia/feature/dedode/dedode.py
+++ b/kornia/feature/dedode/dedode.py
@@ -92,10 +92,17 @@ class DeDoDe(nn.Module):
(``align_corners=False``), the form :meth:`describe` takes; ``(k + 1) * (W, H) / 2 - 0.5`` converts such a
``k`` to kornia's frame. A description is read at the centre of pixel ``i``.
- Each image gives its ``n`` best keypoints by score, in descending order: :math:`N = \min(n, H W)`, with no
- threshold and no padding. Keypoints, and the descriptions of
- :meth:`forward` and of ``describe(images, keypoints)``, are float32; descriptions are not normalized. The
- dense map of ``describe(images)`` follows the network dtype: ``amp_dtype`` on CUDA, the dtype of the model
- on CPU and MPS.
+ threshold and no padding. Keypoints, and the descriptions of :meth:`forward` and of
+ ``describe(images, keypoints)``, are float32; descriptions are not normalized. The scoremap softmax and the
+ keypoint sampling run in at least float32, so the scores are float32 for a half-precision model and float64
+ for a float64 one. The dense map of ``describe(images)`` follows the network dtype: ``amp_dtype`` on CUDA,
+ the dtype of the model on CPU and MPS.
+ - kornia detects and describes at the size of the input. The authors resize every image to 784 x 784, without
+ keeping its aspect ratio, in ``detect_from_path`` and ``describe_keypoints_from_path``, and train the
+ detector and the ``B`` descriptor at 512 x 512 (``G`` at 560 x 560). The 51-pixel coverage window of the
+ keypoint sampling and the 14-pixel patches of ``G`` do not scale with the image. After resizing to
+ 784 x 784, the normalized keypoints of :meth:`detect` hold for the original image unchanged; multiply those
+ of :meth:`forward` by ``(W / 784, H / 784)``.
- ``amp_dtype`` is CUDA mixed precision in every component: on CUDA tensors the networks run under
``torch.autocast`` in ``amp_dtype`` (and the DINOv2 backbone of the ``G`` descriptor is cast to it). On CPU
and MPS it has no effect, so the default argument runs there with float32 weights and images.
@@ -228,6 +235,9 @@ class DeDoDe(nn.Module):
if crop_h is not None and crop_w is not None:
logits = logits[..., :crop_h, :crop_w]
H, W = crop_h, crop_w
+ # at least float32: the probabilities are about 1 / (H W), below the smallest normal float16 for images above
+ # 128 x 128, and bfloat16 keeps 8 significant bits of them
+ logits = logits.to(torch.promote_types(logits.dtype, torch.float32))
scoremap = logits.reshape(B, H * W).softmax(dim=-1).reshape(B, H, W)
keypoints, confidence = sample_keypoints(scoremap, num_samples=n)
return keypoints, confidence
diff --git a/kornia/feature/dedode/detector.py b/kornia/feature/dedode/detector.py
index ee92eb440..e5a511b11 100644
--- a/kornia/feature/dedode/detector.py
+++ b/kornia/feature/dedode/detector.py
@@ -43,7 +43,8 @@ class DeDoDeDetector(nn.Module):
images: Input image batch with shape ``(B, C, H, W)``.
Returns:
- Keypoint detection logits with shape ``(B, 1, H, W)``.
+ Keypoint detection logits with shape ``(B, 1, H, W)``, in at least float32: float32 for half-precision
+ ``images``, float64 for float64 ones.
"""
dtype = images.dtype
features, sizes = self.encoder(images)
@@ -52,10 +53,12 @@ class DeDoDeDetector(nn.Module):
scales = ["8", "4", "2", "1"]
for idx, (feature_map, scale) in enumerate(zip(reversed(features), scales)):
delta_logits, context = self.decoder(feature_map, context=context, scale=scale)
- # ensure float (need bf16 doesn't have f.interpolate)
- logits = delta_logits if logits is None else logits + delta_logits.float()
+ # The logits are accumulated and returned in at least float32: rounding them to a half dtype would reorder
+ # the top-k that `DeDoDe.detect` takes from their softmax.
+ delta_logits = delta_logits.to(torch.promote_types(delta_logits.dtype, torch.float32))
+ logits = delta_logits if logits is None else logits + delta_logits
if idx < len(scales) - 1:
size = sizes[-(idx + 2)]
logits = F.interpolate(logits, size=size, mode="bicubic", align_corners=False)
context = F.interpolate(context.float(), size=size, mode="bilinear", align_corners=False).to(dtype)
- return logits.to(dtype)
+ return logits
diff --git a/kornia/feature/dedode/transformer/layers/attention.py b/kornia/feature/dedode/transformer/layers/attention.py
index 6836bd29f..6237c63ba 100644
--- a/kornia/feature/dedode/transformer/layers/attention.py
+++ b/kornia/feature/dedode/transformer/layers/attention.py
@@ -25,6 +25,7 @@
# https://github.com/facebookresearch/dino/blob/master/vision_transformer.py
# https://github.com/rwightman/pytorch-image-models/tree/master/timm/models/vision_transformer.py
+import torch.nn.functional as F
from torch import Tensor, nn
@@ -36,7 +37,8 @@ class Attention(nn.Module):
num_heads: Number of attention heads.
qkv_bias: If True, add a bias term to the query, key, and value projections.
proj_bias: If True, add a bias term to the output projection.
- attn_drop: Dropout probability applied to the attention weights.
+ attn_drop: Dropout probability applied to the attention weights. A non-zero value makes the training-mode
+ forward materialise the ``(B, num_heads, N, N)`` weights.
proj_drop: Dropout probability applied to the output projection.
"""
@@ -72,13 +74,16 @@ class Attention(nn.Module):
B, N, C = x.shape
qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4)
- q, k, v = qkv[0] * self.scale, qkv[1], qkv[2]
- attn = q @ k.transpose(-2, -1)
-
- attn = attn.softmax(dim=-1)
- attn = self.attn_drop(attn)
-
- x = (attn @ v).transpose(1, 2).reshape(B, N, C)
+ q, k, v = qkv[0], qkv[1], qkv[2]
+ if self.training and self.attn_drop.p > 0.0:
+ # The dropout of ``attn_drop`` acts on the weights, so they are materialised here:
+ # ``scaled_dot_product_attention`` has no dropout on MPS.
+ attn = self.attn_drop(((q * self.scale) @ k.transpose(-2, -1)).softmax(dim=-1))
+ x = attn @ v
+ else:
+ # softmax(q k^T * scale) v; the fused kernels do not materialise the N x N weights of every head.
+ x = F.scaled_dot_product_attention(q, k, v, scale=self.scale)
+ x = x.transpose(1, 2).reshape(B, N, C)
x = self.proj(x)
return self.proj_drop(x)
diff --git a/tests/feature/test_dedode.py b/tests/feature/test_dedode.py
index 904e788c8..735aaebef 100644
--- a/tests/feature/test_dedode.py
+++ b/tests/feature/test_dedode.py
@@ -23,8 +23,10 @@ import torch
from kornia.enhance.normalize import Normalize
from kornia.feature.dedode import DeDoDe
from kornia.feature.dedode.decoder import ConvRefiner
+from kornia.feature.dedode.dedode_models import get_detector
from kornia.feature.dedode.transformer.dinov2 import DinoVisionTransformer
from kornia.feature.dedode.transformer.layers import MemEffAttention, NestedTensorBlock
+from kornia.feature.dedode.transformer.layers.attention import Attention
from kornia.feature.dedode.transformer.layers.patch_embed import PatchEmbed
from kornia.feature.dedode.utils import dedode_denormalize_pixel_coordinates
@@ -56,6 +58,27 @@ class TestConvRefiner(BaseTester):
class TestMemEffAttention(BaseTester):
+ @pytest.mark.parametrize("attention_class", [Attention, MemEffAttention])
+ def test_matches_the_materialised_softmax(self, device, dtype, attention_class):
+ # The fused kernel computes softmax(q k^T * scale) v without materialising the N x N weights; the dropout of
+ # attn_drop is off in eval mode.
+ attention = attention_class(dim=16, num_heads=4, qkv_bias=True, attn_drop=0.5).to(device, dtype).eval()
+ x = torch.rand(2, 7, 16, device=device, dtype=dtype)
+ with torch.no_grad():
+ q, k, v = attention.qkv(x).reshape(2, 7, 3, 4, 4).permute(2, 0, 3, 1, 4)
+ weights = (q * attention.scale @ k.transpose(-2, -1)).softmax(dim=-1)
+ expected = attention.proj((weights @ v).transpose(1, 2).reshape(2, 7, 16))
+ self.assert_close(attention(x), expected)
+
+ def test_attn_drop_applies_in_training_mode_only(self, device, dtype):
+ attention = Attention(dim=16, num_heads=4, attn_drop=0.5).to(device, dtype)
+ x = torch.rand(2, 7, 16, device=device, dtype=dtype)
+ with torch.no_grad():
+ expected = attention.eval()(x)
+ assert not torch.allclose(attention.train()(x), expected)
+ attention.attn_drop.p = 0.0
+ self.assert_close(attention(x), expected)
+
def test_attn_bias_raises(self, device, dtype):
attention = MemEffAttention(dim=8, num_heads=2).to(device, dtype).eval()
x = torch.rand(1, 5, 8, device=device, dtype=dtype)
@@ -223,6 +246,39 @@ class TestDeDoDeHalfPrecision(BaseTester):
assert scores.shape == (1, 10)
assert torch.isfinite(scores).all()
+ def test_detector_returns_at_least_float32_logits(self, device, dtype):
+ # The networks run in the model dtype; the logits are accumulated in at least float32, as Parskatt/DeDoDe
+ # 6d15618 (detectors/dedode_detector.py) does in float32, and are not rounded to a half dtype afterwards.
+ detector = get_detector("L", amp_dtype=dtype).to(device, dtype).eval()
+ with torch.no_grad():
+ logits = detector(torch.rand(1, 3, 56, 84, device=device, dtype=dtype))
+ assert logits.shape == (1, 1, 56, 84)
+ assert logits.dtype == torch.promote_types(dtype, torch.float32)
+ assert torch.isfinite(logits).all()
+
+ def test_half_scoremap_keeps_the_float32_top_k(self, device, dtype, monkeypatch):
+ # A peaky map of integer logits, exact in every dtype. Over 252 x 336 pixels most of its softmax
+ # probabilities are below 1e-8: float16 flushes them to 0 and bfloat16 keeps 8 significant bits, so a
+ # softmax in the model dtype loses the top-k. The softmax and the keypoint sampling run in at least float32,
+ # so a half-precision model returns the float32 keypoints and scores.
+ if dtype not in (torch.float16, torch.bfloat16):
+ pytest.skip("a regression for the half dtypes")
+ h, w = 252, 336
+ logits = (torch.randn(1, 1, h, w, generator=torch.Generator().manual_seed(0)) * 8).round().to(device)
+
+ def detector(images):
+ return logits.to(images.dtype).expand(images.shape[0], -1, -1, -1)
+
+ monkeypatch.setattr("kornia.feature.dedode.dedode.get_detector", lambda *a, **k: _FixedMap(detector))
+ monkeypatch.setattr("kornia.feature.dedode.dedode.get_descriptor", lambda *a, **k: _FixedMap(lambda x: x))
+ image = torch.rand(1, 3, h, w, device=device)
+ expected_keypoints, expected_scores = DeDoDe().to(device).detect(image)
+ keypoints, scores = DeDoDe().to(device, dtype).detect(image.to(dtype))
+ assert keypoints.shape == (1, 10_000, 2)
+ self.assert_close(keypoints, expected_keypoints, rtol=0.0, atol=0.0)
+ assert keypoints.dtype == scores.dtype == torch.float32
+ self.assert_close(scores, expected_scores, rtol=0.0, atol=0.0)
+
def _tiny_dinov2(monkeypatch):
"""Replace the 24-block ViT-L/14 and its download by a one-block ViT with the same 1024-wide patch tokens."""