π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(feature): LightGlue mp=True with a float64 model on CUDA; post-merge fixes from the #6417/#6424 reviews (#6441)
Dmytro Mishkin9cbd6de869bd
diff --git a/changelog.d/6417.added.md b/changelog.d/6417.added.mdindex a259a3a3b..f118c320b 100644--- a/changelog.d/6417.added.md+++ b/changelog.d/6417.added.md@@ -1 +1 @@-`LightGlue` computes its cross-attention with `torch.nn.functional.scaled_dot_product_attention` on every device, as its self-attention already did, instead of only on CUDA with `flash=True`. The matches are the same and the scores move by rounding; on an Apple M1 a 2048-keypoint DISK pair matches 1.3-1.7x faster on CPU and 1.2-1.5x faster on MPS.+`LightGlue` computes its cross-attention with `torch.nn.functional.scaled_dot_product_attention` on every device, as its self-attention already did, instead of only on CUDA with `flash=True`. In float32 the matches are the same and the scores move by rounding; in half precision, rounding can also change a few matches. A 2048-keypoint DISK pair matches 1.3-1.7x faster on an Apple M1 CPU, 1.2-1.5x faster on MPS and 2.3-4x faster on an x86 CPU (i7-14700K). On CUDA the default `flash=True` runs as before, and `flash=False` matches 1.1-1.2x faster.diff --git a/changelog.d/6441.fixed.md b/changelog.d/6441.fixed.mdnew file mode 100644index 000000000..dd8f56afe--- /dev/null+++ b/changelog.d/6441.fixed.md@@ -0,0 +1 @@+`LightGlue(mp=True)` runs a float64 model on CUDA. It used to cast the descriptors to float16 under autocast, which does not cast float64 weights, so every float64 call raised `mat1 and mat2 must have the same dtype`. A float64 model now gives float64 scores and the matches of `mp=False`, as on CPU.diff --git a/kornia/feature/lightglue.py b/kornia/feature/lightglue.pyindex 83054ffa3..52b3da2f9 100644--- a/kornia/feature/lightglue.py+++ b/kornia/feature/lightglue.py@@ -492,7 +492,8 @@ class LightGlue(nn.Module):float64 model gives float64 scores for float64 descriptors. Float16 descriptors with any other model, andbfloat16 descriptors with a float16 model, are not supported there(`#5929 <https://github.com/kornia/kornia/issues/5929>`_). On MPS, float32, float16 and bfloat16- descriptors give float32 scores; on CUDA, float32 descriptors give float32 scores. An image without+ descriptors give float32 scores; on CUDA, float32 descriptors give float32 scores, and a float64 model gives+ float64 scores for float64 descriptors, as on CPU, because autocast does not cast float64. An image withoutdescriptors runs no layer, and its zero scores keep the descriptor dtype, also with ``mp=True``.- Each pair of a batch gives the matches and scores it gives on its own when point pruning can run, that iswith ``width_confidence > 0``, no padding to the static lengths of :meth:`compile`, and an image with more@@ -847,7 +848,8 @@ class LightGlue(nn.Module):KORNIA_CHECK(desc1.shape[-1] == self.conf.input_dim, "Descriptor dimension does not match input dim in config")device_type = desc0.device.type- if device_type != "cpu" and torch.is_autocast_enabled(device_type):+ # Autocast does not cast float64, so the float64 weights of a float64 model would meet half descriptors here.+ if device_type != "cpu" and torch.is_autocast_enabled(device_type) and desc0.dtype != torch.float64:desc0 = desc0.half()desc1 = desc1.half()diff --git a/kornia/feature/sold2/sold2_detector.py b/kornia/feature/sold2/sold2_detector.pyindex 674d584dd..80757ce4a 100644--- a/kornia/feature/sold2/sold2_detector.py+++ b/kornia/feature/sold2/sold2_detector.py@@ -73,8 +73,8 @@ class SOLD2_detector(nn.Module):def __init__(self, pretrained: bool = True, config: Optional[DetectorCfg] = None) -> None:if isinstance(config, dict):warnings.warn(- "Usage of config as a plain dictionary is deprecated in favor of"- "`kornia.features.sold2.structures.DetectorCfg`. The support of plain"+ "Usage of config as a plain dictionary is deprecated in favor of "+ "`kornia.feature.sold2.structures.DetectorCfg`. The support of plain ""dictionaries as config will be removed in a future release.",category=DeprecationWarning,stacklevel=2,diff --git a/tests/feature/test_lightglue.py b/tests/feature/test_lightglue.pyindex 8cd70e894..43d3abf9b 100644--- a/tests/feature/test_lightglue.py+++ b/tests/feature/test_lightglue.py@@ -589,6 +589,23 @@ class TestLightGlue(BaseTester):assert seen["device_type"] == data["image0"]["keypoints"].device.typeassert "matches0" in out+ def test_mp_keeps_a_float64_model_in_float64(self, device):+ """Autocast does not cast float64, so ``mp=True`` leaves a float64 model as ``mp=False`` runs it.++ On CUDA the descriptors used to be cast to float16 under autocast, which the float64 weights then met.+ """+ if device.type == "mps":+ pytest.skip("MPS does not support float64")+ torch.manual_seed(0)+ models = {mp: _make_lightglue(device, torch.float64, mp=mp) for mp in (False, True)}+ models[True].load_state_dict(models[False].state_dict())+ data = _make_data(device, torch.float64)+ with torch.no_grad():+ out = {mp: model(data) for mp, model in models.items()}+ assert out[True]["matching_scores0"].dtype == torch.float64+ assert torch.equal(out[True]["matches0"], out[False]["matches0"])+ self.assert_close(out[True]["matching_scores0"], out[False]["matching_scores0"])+@pytest.mark.slowdef test_pretrained_smoke(self, device):"""Instantiating with real feature type downloads and loads weights."""