π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(lightglue): resolve AMP device_type via accelerator instead of hardcoded cuda (#4624)
li-lizhe744125e49cdb
diff --git a/changelog.d/4624.fixed.md b/changelog.d/4624.fixed.mdnew file mode 100644index 000000000..fa45bfad2--- /dev/null+++ b/changelog.d/4624.fixed.md@@ -0,0 +1 @@+Fixed the mixed-precision (`autocast`) guard in `kornia.feature.lightglue` to resolve the accelerator type from the input tensor instead of a hardcoded `"cuda"`. This makes `LightGlue`/`LighterGlue` usable under autocast on any accelerator (Ascend NPU, XPU, MPS) and on CPU-only builds where `torch.accelerator.current_accelerator()` returns `None`. (#4624)diff --git a/kornia/feature/lightglue.py b/kornia/feature/lightglue.pyindex 1954d8484..5ab196da2 100644--- a/kornia/feature/lightglue.py+++ b/kornia/feature/lightglue.py@@ -36,19 +36,19 @@ def math_clamp(x, min_, max_): # type: ignorereturn min(max(x, min_), max_)-if hasattr(torch.amp, "custom_fwd"):- AMP_CUSTOM_FWD_F32 = torch.amp.custom_fwd(cast_inputs=torch.float32, device_type="cuda")-else:- # ``torch.amp.custom_fwd`` was introduced after Kornia's minimum supported Torch;- # the CUDA-specific spelling provides the same behavior on older releases.- AMP_CUSTOM_FWD_F32 = torch.cuda.amp.custom_fwd(cast_inputs=torch.float32)---@AMP_CUSTOM_FWD_F32def normalize_keypoints(kpts: torch.Tensor, size: torch.Tensor) -> torch.Tensor:"""Normalize torch.Tensor of keypoints."""if isinstance(size, torch.Size):size = torch.tensor(size)[None]+ # Under an active autocast, cast fp16/bf16 inputs to fp32 so the normalisation+ # arithmetic runs at full precision regardless of the accelerator.+ # Deriving the autocast device from the input tensor itself is correct for any+ # backend (CUDA, NPU, XPU, MPS) and on CPU-only builds where+ # ``torch.accelerator.current_accelerator()`` would be ``None``.+ device_type = kpts.device.type+ if kpts.is_floating_point() and kpts.dtype in (torch.float16, torch.bfloat16):+ if torch.is_autocast_enabled(device_type):+ kpts = kpts.to(torch.float32)shift = size.float().to(kpts) / 2scale = size.max(1).values.float().to(kpts) / 2kpts = (kpts - shift[:, None]) / scale[:, None, None]@@ -688,7 +688,8 @@ class LightGlue(nn.Module):matching_scores1: [B x N]matches: List[[Si x 2]], scores: List[[Si]]"""- with torch.autocast(enabled=self.conf.mp, device_type="cuda"):+ device_type = data["image0"]["keypoints"].device.type+ with torch.autocast(enabled=self.conf.mp, device_type=device_type):return self._forward(data)def _forward(self, data: dict) -> dict: # type: ignorediff --git a/tests/feature/test_lightglue.py b/tests/feature/test_lightglue.pyindex e2993d4b7..38d4fcfff 100644--- a/tests/feature/test_lightglue.py+++ b/tests/feature/test_lightglue.py@@ -15,6 +15,8 @@# limitations under the License.#+import unittest.mock+import pytestimport torch@@ -112,6 +114,21 @@ def test_normalize_keypoints_range():assert out.max() <= 1.0 + 1e-3+def test_normalize_keypoints_autocast_promotes_to_f32():+ """Under CPU autocast, bf16 keypoints are promoted to fp32 for normalization.++ On the main branch (before #4624) the decorator-based ``@AMP_CUSTOM_FWD_F32``+ with ``device_type="cuda"`` did not fire under CPU autocast, so bf16 inputs+ remained bf16. This head's per-tensor inline autocast guard correctly promotes.+ """+ kpts = torch.randn(1, 5, 2, dtype=torch.bfloat16)+ size = torch.tensor([[100, 200]])+ with torch.autocast("cpu", dtype=torch.bfloat16):+ out = normalize_keypoints(kpts, size)+ assert out.dtype == torch.float32+ assert out.shape == kpts.shape++def test_pad_to_length_no_pad():x = torch.rand(1, 10, 64)y, mask = pad_to_length(x, 5)@@ -278,7 +295,7 @@ class TestTokenConfidence(BaseTester):# ----------------------------------------------------------------------------def _make_lightglue(device, dtype, input_dim=64, n_layers=2):+def _make_lightglue(device, dtype, input_dim=64, n_layers=2, mp=False):"""Instantiate a small LightGlue with random weights (features=None)."""return (LightGlue(@@ -290,6 +307,7 @@ def _make_lightglue(device, dtype, input_dim=64, n_layers=2):depth_confidence=-1,width_confidence=-1,flash=False,+ mp=mp,).to(device, dtype).eval()@@ -408,6 +426,36 @@ class TestLightGlue(BaseTester):out = lg(data)assert isinstance(out, dict)+ def test_mp_forward_uses_input_device_type(self, device, dtype):+ """With ``mp=True``, ``forward`` derives the autocast ``device_type`` from the+ keypoints device (the computation device), not from a hardcoded ``\"cuda\"`` nor+ from the first tensor encountered while scanning the input dict (regression for+ #4624).+ """+ if dtype == torch.float16:+ pytest.skip("LightGlue requires float32 or float64")+ lg = _make_lightglue(device, dtype, mp=True)+ data = _make_data(device, dtype)+ # Put a non-keypoint tensor (image_size) first so a naive "first tensor wins"+ # resolver would select it instead of the keypoints device.+ data["image0"] = {+ "image_size": data["image0"].pop("image_size"),+ **data["image0"],+ }+ seen: dict[str, str] = {}+ real_ac = torch.autocast++ def _spy(*args: object, **kwargs: object):+ seen["device_type"] = kwargs.get("device_type", "")+ return real_ac(*args, **kwargs)++ with unittest.mock.patch("kornia.feature.lightglue.torch.autocast", side_effect=_spy):+ with torch.no_grad():+ out = lg(data)++ assert seen["device_type"] == data["image0"]["keypoints"].device.type+ assert "matches0" in out+@pytest.mark.slowdef test_pretrained_smoke(self, device):"""Instantiating with real feature type downloads and loads weights."""