π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(feature): remove the dead flash_attn path from LightGlue (#4287)
Dmytro Mishkin6b69cc68d8ec
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 8a375db6f..6a65c3e14 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -292,6 +292,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Bug fixes+* `kornia.feature.LightGlue` no longer probes for `flash_attn`; the SDPA path it always used is now+ the only one. `kornia.feature.lightglue.Attention.enable_flash`, the attribute that combined the+ constructor argument with the probe result (and so always equalled the argument, because SDPA is+ present on every supported torch), was renamed to `Attention.allow_flash`. (#4287)+* `RandAugment`, `AutoAugment`, `TrivialAugment` and `AugMix` no longer silently upcast half-precisionbatches to `float32`. `OperationBase.forward` β the shared gate every auto-augment op routes through βmoved its `batch_prob` mask to `input.device` but not `input.dtype`, and since `batch_prob` is `float32`diff --git a/kornia/feature/lightglue.py b/kornia/feature/lightglue.pyindex f20432a8b..2abb9c4f6 100644--- a/kornia/feature/lightglue.py+++ b/kornia/feature/lightglue.py@@ -30,16 +30,6 @@ from kornia.core.download import hf_url, load_state_dict_from_urlfrom kornia.core.utils import is_exportingfrom kornia.feature.laf import laf_to_three_points, scale_laf-try:- from flash_attn.modules.mha import FlashCrossAttention-except ModuleNotFoundError:- FlashCrossAttention = None--if FlashCrossAttention or hasattr(F, "scaled_dot_product_attention"):- FLASH_AVAILABLE = True-else:- FLASH_AVAILABLE = False-def math_clamp(x, min_, max_): # type: ignore"""Clamp a value to lie within [min, max]."""@@ -146,17 +136,8 @@ class Attention(nn.Module):def __init__(self, allow_flash: bool) -> None:super().__init__()- if allow_flash and not FLASH_AVAILABLE:- warnings.warn(- "FlashAttention is not available. For optimal speed, consider installing flash-attn.",- stacklevel=2,- )- self.enable_flash = allow_flash and FLASH_AVAILABLE- self.has_sdp = hasattr(F, "scaled_dot_product_attention")- if allow_flash and FlashCrossAttention:- self.flash_ = FlashCrossAttention()- if self.has_sdp:- torch.backends.cuda.enable_flash_sdp(allow_flash)+ self.allow_flash = allow_flash+ torch.backends.cuda.enable_flash_sdp(allow_flash)def forward(self, q: torch.Tensor, k: torch.Tensor, v: torch.Tensor, mask: Optional[torch.Tensor] = None@@ -176,28 +157,15 @@ class Attention(nn.Module):Returns:Attention output with shape :math:`(B, H, N_q, D_h)`."""- if self.enable_flash and q.device.type == "cuda":+ if self.allow_flash and q.device.type == "cuda":# use torch 2.0 scaled_dot_product_attention with flash- if self.has_sdp:- args = [x.half().contiguous() for x in [q, k, v]]- v = F.scaled_dot_product_attention(*args, attn_mask=mask).to(q.dtype) # type: ignore- return v if mask is None else v.nan_to_num()- else:- KORNIA_CHECK(mask is None)- q, k, v = (x.transpose(-2, -3).contiguous() for x in [q, k, v])- m = self.flash_(q.half(), torch.stack([k, v], 2).half())- return m.transpose(-2, -3).to(q.dtype).clone()- elif self.has_sdp:+ args = [x.half().contiguous() for x in [q, k, v]]+ v = F.scaled_dot_product_attention(*args, attn_mask=mask).to(q.dtype) # type: ignore+ return v if mask is None else v.nan_to_num()+ else:args = [x.contiguous() for x in [q, k, v]]v = F.scaled_dot_product_attention(*args, attn_mask=mask) # type: ignorereturn v if mask is None else v.nan_to_num()- else:- s = q.shape[-1] ** -0.5- sim = torch.einsum("...id,...jd->...ij", q, k) * s- if mask is not None:- sim.masked_fill(~mask, -float("inf"))- attn = F.softmax(sim, -1)- return torch.einsum("...ij,...jd->...id", attn, v)class SelfBlock(nn.Module):@@ -279,7 +247,7 @@ class CrossBlock(nn.Module):nn.GELU(),nn.Linear(2 * embed_dim, embed_dim),)- if flash and FLASH_AVAILABLE:+ if flash:self.flash = Attention(True)else:self.flash = None # type: ignore@@ -954,7 +922,7 @@ class LightGlue(nn.Module):Minimum number of keypoints required for width pruning on that device.A negative value disables pruning for the device."""- if self.conf.flash and FLASH_AVAILABLE and device.type == "cuda":+ if self.conf.flash and device.type == "cuda":return self.pruning_keypoint_thresholds["flash"]else:return self.pruning_keypoint_thresholds[device.type]diff --git a/tests/feature/test_lightglue.py b/tests/feature/test_lightglue.pyindex 31c960046..e2993d4b7 100644--- a/tests/feature/test_lightglue.py+++ b/tests/feature/test_lightglue.py@@ -19,6 +19,7 @@ import pytestimport torchfrom kornia.feature.lightglue import (+ Attention,LearnableFourierPositionalEncoding,LightGlue,TokenConfidence,@@ -28,7 +29,7 @@ from kornia.feature.lightglue import (rotate_half,)-from testing.base import BaseTester+from testing.base import BaseTester, assert_close# ---------------------------------------------------------------------------# Pure function tests@@ -146,6 +147,42 @@ def test_apply_cached_rotary_emb_shape():assert out.shape == t.shape+def test_attention_allow_flash_matches_on_cpu():+ """On CPU, ``allow_flash`` never selects the CUDA-only branch, so both settings take the+ same ``scaled_dot_product_attention`` path and must produce identical outputs, with and+ without a boolean mask (exercising the ``nan_to_num`` handling of fully-masked rows).+ """+ torch.manual_seed(0)+ B, H, N, Dh = 1, 2, 5, 8+ q = torch.rand(B, H, N, Dh)+ k = torch.rand(B, H, N, Dh)+ v = torch.rand(B, H, N, Dh)++ # ``Attention.__init__`` flips the process-global ``torch.backends.cuda`` flash-SDPA switch;+ # put back whatever this test found so later tests in a CUDA run do not depend on its order.+ flash_sdp_was_enabled = torch.backends.cuda.flash_sdp_enabled()+ try:+ attn_no_flash = Attention(allow_flash=False)+ attn_flash = Attention(allow_flash=True)++ out_no_flash = attn_no_flash(q, k, v)+ out_flash = attn_flash(q, k, v)+ assert_close(out_no_flash, out_flash)++ # First query row cannot attend to anything: softmax produces NaN there, which+ # ``Attention.forward`` replaces via ``nan_to_num``.+ mask = torch.ones(B, H, N, N, dtype=torch.bool)+ mask[:, :, 0, :] = False++ out_no_flash_masked = attn_no_flash(q, k, v, mask=mask)+ out_flash_masked = attn_flash(q, k, v, mask=mask)+ assert not torch.isnan(out_no_flash_masked).any()+ assert not torch.isnan(out_flash_masked).any()+ assert_close(out_no_flash_masked, out_flash_masked)+ finally:+ torch.backends.cuda.enable_flash_sdp(flash_sdp_was_enabled)++# ---------------------------------------------------------------------------# Module tests# ---------------------------------------------------------------------------