π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(feature): DeDoDe default amp_dtype runs describe/forward on CPU and MPS (#5939)
Dmytro Mishkin8764833525b3
diff --git a/changelog.d/5939.fixed.md b/changelog.d/5939.fixed.mdnew file mode 100644index 000000000..8d4c2c335--- /dev/null+++ b/changelog.d/5939.fixed.md@@ -0,0 +1 @@+`DeDoDe()` with the default `amp_dtype=torch.float16` now runs `describe` and `forward` on CPU and MPS with float32 weights and images instead of raising `Input type (c10::Half) and bias type (float) should be the same`. `amp_dtype` is CUDA mixed precision in every component: the `G` descriptor's DINOv2 backbone is cast to it only for CUDA inputs, and on other devices follows the dtype of the input (a float32 backbone stays float32, a `.half()` model gets a half one), so a `.half()` or `.bfloat16()` model with a different `amp_dtype` also runs there now. The CUDA path casts on the host and then moves the backbone, as before; the one difference is that the cast happens at the first CUDA call instead of at construction, so about 0.6 GB more host memory is held in between.diff --git a/kornia/feature/dedode/dedode.py b/kornia/feature/dedode/dedode.pyindex 59fef5319..b545a7b78 100644--- a/kornia/feature/dedode/dedode.py+++ b/kornia/feature/dedode/dedode.py@@ -92,12 +92,18 @@ 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 descriptions are float32, and descriptions are not normalized.+ 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.+ - ``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.Args:detector_model: The detector model kind. Available options are: `L`.descriptor_model: The descriptor model kind. Available options are: `G` or `B`- amp_dtype: The automatic mixed precision desired.+ amp_dtype: The dtype of the automatic mixed precision used on CUDA; it has no effect on other devices.Example:>>> dedode = DeDoDe.from_pretrained(detector_weights="L-C4-v2", descriptor_weights="B-upright")@@ -299,8 +305,10 @@ class DeDoDe(nn.Module):One of 'B-upright','G-upright' (original paper, https://arxiv.org/abs/2308.08479),'B-C4', 'B-SO2', 'G-C4', 'G-SO2' (from steerers, better for rotations, https://arxiv.org/abs/2312.02152).Default is 'G-upright'.- amp_dtype: the dtype to use for the model. One of torch.float16 or torch.float32.- Default is torch.float16, suitable for CUDA. Use torch.float32 for CPU or MPS+ amp_dtype: the dtype of the automatic mixed precision used on CUDA, one of torch.float16 or+ torch.float32. It has no effect on CPU or MPS, where every component runs in the dtype of the+ input and the model.+ Default is torch.float16.Returns:The pretrained model.diff --git a/kornia/feature/dedode/encoder.py b/kornia/feature/dedode/encoder.pyindex 1bd44b6ab..55f6f1f8d 100644--- a/kornia/feature/dedode/encoder.py+++ b/kornia/feature/dedode/encoder.py@@ -91,25 +91,37 @@ class FrozenDINOv2(nn.Module):dinov2_vitl14.load_state_dict(dinov2_weights)self.amp = ampself.amp_dtype = amp_dtype- if self.amp:- dinov2_vitl14 = dinov2_vitl14.to(self.amp_dtype)+ # The backbone keeps the dtype of the checkpoint; `forward` casts it to ``amp_dtype`` once it runs on CUDA.self.dinov2_vitl14 = [dinov2_vitl14] # ugly hack to not show parameters to DDPdef forward(self, x: torch.Tensor): # type: ignore[no-untyped-def]"""Run this DeDoDe module forward.+ ``amp_dtype`` is CUDA mixed precision, as in the other DeDoDe components: on a CUDA input with ``amp=True``+ the backbone and the image are cast to ``amp_dtype``. On other devices (CPU, MPS), or with ``amp=False``, the+ backbone is cast to the dtype and device of ``x``, so the features come back in the dtype of ``x``.+Args:- x: Input image tensor with shape :math:`(B, 3, H, W)`. Converted to ``amp_dtype`` internally.+ x: Input image tensor with shape :math:`(B, 3, H, W)`.Returns:Tuple of ``([features_16], [(H//14, W//14)])`` where ``features_16`` has shape:math:`(B, 1024, H/14, W/14)`."""B, _C, H, W = x.shape- if self.dinov2_vitl14[0].device != x.device:- self.dinov2_vitl14[0] = self.dinov2_vitl14[0].to(x.device).to(self.amp_dtype)+ use_amp = self.amp and x.is_cuda+ backbone = self.dinov2_vitl14[0]+ if use_amp:+ if backbone.device != x.device or backbone.cls_token.dtype != self.amp_dtype:+ # Cast on the host, then move: the half copy is what travels to the device.+ self.dinov2_vitl14[0] = backbone.to(self.amp_dtype).to(x.device)+ backbone_input = x.to(self.amp_dtype)+ else:+ if backbone.device != x.device or backbone.cls_token.dtype != x.dtype:+ self.dinov2_vitl14[0] = backbone.to(x.device, x.dtype)+ backbone_input = xwith torch.inference_mode():- dinov2_features_16 = self.dinov2_vitl14[0].forward_features(x.to(self.amp_dtype))+ dinov2_features_16 = self.dinov2_vitl14[0].forward_features(backbone_input)features_16 = dinov2_features_16["x_norm_patchtokens"].permute(0, 2, 1).reshape(B, 1024, H // 14, W // 14)return [features_16.clone()], [(H // 14, W // 14)] # clone from inference mode to use in autograddiff --git a/tests/feature/test_dedode.py b/tests/feature/test_dedode.pyindex 2fa486027..d938637cc 100644--- a/tests/feature/test_dedode.py+++ b/tests/feature/test_dedode.py@@ -203,6 +203,113 @@ class TestDeDoDeHalfPrecision(BaseTester):assert torch.isfinite(scores).all()+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."""+ from functools import partial++ import kornia.feature.dedode.encoder as encoder_module+ import kornia.feature.dedode.transformer as transformer_module++ def vit_large(patch_size=16, **kwargs):+ return DinoVisionTransformer(+ patch_size=patch_size,+ embed_dim=1024,+ depth=1,+ num_heads=16,+ mlp_ratio=4,+ block_fn=partial(NestedTensorBlock, attn_class=MemEffAttention),+ **kwargs,+ )++ torch.manual_seed(0)+ state = vit_large(img_size=518, patch_size=14, init_values=1.0, ffn_layer="mlp", block_chunks=0).state_dict()+ monkeypatch.setattr(transformer_module, "vit_large", vit_large)+ monkeypatch.setattr(encoder_module, "load_state_dict_from_url", lambda *args, **kwargs: state)+++class TestDeDoDeDefaultAmpDtype5934(BaseTester):+ """`amp_dtype` is CUDA mixed precision in every component, so the default argument runs off CUDA."""++ @staticmethod+ def _image(device):+ return torch.rand(1, 3, 56, 84, generator=torch.Generator().manual_seed(7)).to(device)++ @pytest.mark.parametrize("entry", ["detect", "describe", "forward"])+ def test_default_runs_with_float32(self, device, monkeypatch, entry):+ if device.type == "cuda":+ pytest.skip("CUDA runs the float16 mixed-precision path, which this test does not cover")+ _tiny_dinov2(monkeypatch)+ model = DeDoDe().to(device).eval()+ x = self._image(device)+ if entry == "detect":+ kpts, scores = model.detect(x, n=8)+ outs = (kpts, scores)+ elif entry == "describe":+ outs = (model.describe(x),)+ assert outs[0].shape == (1, 256, 56, 84)+ else:+ kpts, scores, descs = model(x, n=8)+ assert descs.shape == (1, 8, 256)+ outs = (kpts, scores, descs)+ for out in outs:+ assert out.dtype == torch.float32+ assert torch.isfinite(out).all()++ def test_forward_is_detect_then_describe(self, device, monkeypatch):+ if device.type == "cuda":+ pytest.skip("CUDA runs the float16 mixed-precision path, which this test does not cover")+ _tiny_dinov2(monkeypatch)+ model = DeDoDe().to(device).eval()+ x = self._image(device)+ kpts, scores, descs = model(x, n=8)+ kpts_d, scores_d = model.detect(x, n=8)+ self.assert_close(kpts, dedode_denormalize_pixel_coordinates(kpts_d, 56, 84))+ self.assert_close(scores, scores_d)+ self.assert_close(descs, model.describe(x, kpts_d))++ def test_dinov2_is_not_cast_off_cuda(self, device, monkeypatch):+ if device.type == "cuda":+ pytest.skip("CUDA casts the DINOv2 backbone to amp_dtype by design")+ _tiny_dinov2(monkeypatch)+ model = DeDoDe().to(device).eval()+ backbone = model.descriptor.encoder.frozen_dinov2.dinov2_vitl14+ assert backbone[0].cls_token.dtype == torch.float32+ model.describe(self._image(device))+ assert backbone[0].cls_token.dtype == torch.float32+ assert backbone[0].cls_token.device.type == device.type++ @pytest.mark.parametrize("entry", ["describe", "forward"])+ def test_descriptor_g_follows_the_model_dtype(self, device, dtype, monkeypatch, entry):+ if device.type == "cuda":+ pytest.skip("CUDA runs the mixed-precision path, see test_cuda_casts_the_backbone_to_amp_dtype")+ _tiny_dinov2(monkeypatch)+ model = DeDoDe(amp_dtype=dtype).to(device, dtype).eval()+ x = self._image(device).to(dtype)+ out = model.describe(x) if entry == "describe" else model(x, n=8)[2]+ assert out.dtype == (dtype if entry == "describe" else torch.float32)+ assert torch.isfinite(out).all()+ backbone = model.descriptor.encoder.frozen_dinov2.dinov2_vitl14[0]+ assert backbone.cls_token.dtype == dtype++ def test_cuda_casts_the_backbone_to_amp_dtype(self, device, monkeypatch):+ if device.type != "cuda":+ pytest.skip("requires CUDA")+ _tiny_dinov2(monkeypatch)+ amp_dtype = torch.float16+ model = DeDoDe(amp_dtype=amp_dtype).to(device).eval()+ image = self._image(device)+ keypoints = torch.zeros(1, 4, 2, device=device)+ # The sparse path casts the map to float32 for `grid_sample`; the dense map comes out of the decoders'+ # float16 autocast and nothing casts it back.+ sparse = model.describe(image, keypoints)+ assert sparse.dtype == torch.float32+ assert torch.isfinite(sparse).all()+ dense = model.describe(image)+ assert dense.dtype == amp_dtype+ assert torch.isfinite(dense).all()+ assert model.descriptor.encoder.frozen_dinov2.dinov2_vitl14[0].cls_token.dtype == amp_dtype++class TestDeDoDeNoGrad(BaseTester):@staticmethoddef _model(device, dtype):