Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

Refactor LightGlue as in LG upstream, also add LightGlue for KeyNetAffNetHardNet (#2706)

Dmytro Mishkin0f9886f43bd2
diff --git a/kornia/core/__init__.py b/kornia/core/__init__.py
index 928623e19..4546fc40f 100644
--- a/kornia/core/__init__.py
+++ b/kornia/core/__init__.py
@@ -10,6 +10,7 @@ from ._backend import (
complex,
concatenate,
cos,
+ deg2rad,
diag,
einsum,
eye,
@@ -19,6 +20,7 @@ from ._backend import (
ones,
ones_like,
pad,
+ rad2deg,
rand,
sin,
softmax,
@@ -47,6 +49,8 @@ __all__ = [
"softmax",
"as_tensor",
"rand",
+ "deg2rad",
+ "rad2deg",
"cos",
"sin",
"tan",
diff --git a/kornia/core/_backend.py b/kornia/core/_backend.py
index e7712b7d2..04e9ca5d2 100644
--- a/kornia/core/_backend.py
+++ b/kornia/core/_backend.py
@@ -33,6 +33,8 @@ map_coordinates = torch.nn.functional.grid_sample
cos = torch.cos
sin = torch.sin
tan = torch.tan
+deg2rad = torch.deg2rad
+rad2deg = torch.rad2deg
# constructors
as_tensor = torch.as_tensor
diff --git a/kornia/feature/integrated.py b/kornia/feature/integrated.py
index 4371967c3..dead996b1 100644
--- a/kornia/feature/integrated.py
+++ b/kornia/feature/integrated.py
@@ -4,7 +4,8 @@ from typing import ClassVar, Dict, List, Optional, Tuple
import torch
from kornia.color import rgb_to_grayscale
-from kornia.core import Device, Module, Tensor, concatenate
+from kornia.constants import pi
+from kornia.core import Device, Module, Tensor, concatenate, deg2rad
from kornia.core.check import KORNIA_CHECK_LAF
from kornia.geometry.subpix import ConvQuadInterp3d
from kornia.geometry.transform import ScalePyramid
@@ -12,7 +13,7 @@ from kornia.geometry.transform import ScalePyramid
from .affine_shape import LAFAffNetShapeEstimator
from .hardnet import HardNet
from .keynet import KeyNetDetector
-from .laf import extract_patches_from_pyramid, get_laf_center, scale_laf
+from .laf import extract_patches_from_pyramid, get_laf_center, get_laf_orientation, get_laf_scale, scale_laf
from .lightglue import LightGlue
from .matching import GeometryAwareDescriptorMatcher, _no_match
from .orientation import LAFOrienter, OriNet, PassLAF
@@ -408,7 +409,14 @@ class LightGlueMatcher(GeometryAwareDescriptorMatcher):
params: LightGlue params.
"""
- known_modes: ClassVar[List[str]] = ["superpoint", "disk"]
+ known_modes: ClassVar[List[str]] = [
+ "superpoint",
+ "disk",
+ "aliked",
+ "keynet_affnet_hardnet",
+ "dog_affnet_hardnet",
+ "sift",
+ ]
def __init__(self, feature_name: str = "disk", params: Dict = {}) -> None: # type: ignore
feature_name_: str = feature_name.lower()
@@ -442,7 +450,10 @@ class LightGlueMatcher(GeometryAwareDescriptorMatcher):
return _no_match(desc1)
keypoints1 = get_laf_center(lafs1)
keypoints2 = get_laf_center(lafs2)
-
+ if len(desc1.shape) == 2:
+ desc1 = desc1.unsqueeze(0)
+ if len(desc2.shape) == 2:
+ desc2 = desc2.unsqueeze(0)
dev = lafs1.device
if hw1 is None:
hw1_ = keypoints1.max(dim=1)[0].squeeze().flip(0)
@@ -452,15 +463,25 @@ class LightGlueMatcher(GeometryAwareDescriptorMatcher):
hw2_ = keypoints2.max(dim=1)[0].squeeze().flip(0)
else:
hw2_ = torch.tensor(hw2, device=dev)
+ ori0 = deg2rad(get_laf_orientation(lafs1).reshape(1, -1))
+ ori0[ori0 < 0] += 2.0 * pi
+ ori1 = deg2rad(get_laf_orientation(lafs2).reshape(1, -1))
+ ori1[ori1 < 0] += 2.0 * pi
input_dict = {
"image0": {
"keypoints": keypoints1,
- "descriptors": desc1[None],
+ "scales": get_laf_scale(lafs1).reshape(1, -1),
+ "oris": ori0,
+ "lafs": lafs1,
+ "descriptors": desc1,
"image_size": hw1_.flip(0).reshape(-1, 2).to(dev),
},
"image1": {
"keypoints": keypoints2,
- "descriptors": desc2[None],
+ "lafs": lafs2,
+ "scales": get_laf_scale(lafs2).reshape(1, -1),
+ "oris": ori1,
+ "descriptors": desc2,
"image_size": hw2_.flip(0).reshape(-1, 2).to(dev),
},
}
diff --git a/kornia/feature/lightglue.py b/kornia/feature/lightglue.py
index 546a17c98..5eebafeb5 100644
--- a/kornia/feature/lightglue.py
+++ b/kornia/feature/lightglue.py
@@ -16,15 +16,15 @@ from kornia.core import (
concatenate,
cos,
einsum,
+ ones,
ones_like,
sin,
- softmax,
stack,
where,
zeros,
)
from kornia.core.check import KORNIA_CHECK
-from kornia.utils._compat import torch_meshgrid
+from kornia.feature.laf import laf_to_three_points, scale_laf
try:
from flash_attn.modules.mha import FlashCrossAttention
@@ -51,6 +51,16 @@ def normalize_keypoints(kpts: Tensor, size: Tensor) -> Tensor:
return kpts
+def pad_to_length(x: Tensor, length: int) -> Tuple[Tensor, Tensor]:
+ if length <= x.shape[-2]:
+ return x, ones_like(x[..., :1], dtype=torch.bool)
+ pad = ones(*x.shape[:-2], length - x.shape[-2], x.shape[-1], device=x.device, dtype=x.dtype)
+ y = concatenate([x, pad], dim=-2)
+ mask = zeros(*y.shape[:-1], 1, dtype=torch.bool, device=x.device)
+ mask[..., : x.shape[-2], :] = True
+ return y, mask
+
+
def rotate_half(x: Tensor) -> Tensor:
x = x.unflatten(-1, (-1, 2))
x1, x2 = x.unbind(dim=-1)
@@ -97,33 +107,43 @@ class Attention(Module):
super().__init__()
if allow_flash and not FLASH_AVAILABLE:
warnings.warn(
- "FlashAttention is not available. For optimal speed, consider installing torch >= 2.0 or flash-attn.",
+ "FlashAttention is not available. For optimal speed, "
+ "consider installing torch >= 2.0 or 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)
- def forward(self, q: Tensor, k: Tensor, v: Tensor) -> Tensor:
+ def forward(self, q: Tensor, k: Tensor, v: Tensor, mask: Optional[Tensor] = None) -> Tensor:
if self.enable_flash and q.device.type == "cuda":
- if FlashCrossAttention:
- q, k, v = (x.transpose(-2, -3) for x in [q, k, v])
+ # 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(), stack([k, v], 2).half())
- return m.transpose(-2, -3).to(q.dtype)
- else: # use torch 2.0 scaled_dot_product_attention with flash
- with torch.backends.cuda.sdp_kernel(enable_flash=True):
- return F.scaled_dot_product_attention(
- q.half().contiguous(), k.half().contiguous(), v.half().contiguous()
- ).to(q.dtype)
- elif hasattr(F, "scaled_dot_product_attention"):
- return F.scaled_dot_product_attention(q.contiguous(), k.contiguous(), v.contiguous()).to(q.dtype)
+ return m.transpose(-2, -3).to(q.dtype).clone()
+ elif self.has_sdp:
+ args = [x.contiguous() for x in [q, k, v]]
+ v = F.scaled_dot_product_attention(*args, attn_mask=mask) # type: ignore
+ return v if mask is None else v.nan_to_num()
else:
s = q.shape[-1] ** -0.5
- attn = softmax(einsum("...id,...jd->...ij", q, k) * s, -1)
+ sim = einsum("...id,...jd->...ij", q, k) * s
+ if mask is not None:
+ sim.masked_fill(~mask, -float("inf"))
+ attn = F.softmax(sim, -1)
return einsum("...ij,...jd->...id", attn, v)
-class Transformer(Module):
+class SelfBlock(Module):
def __init__(self, embed_dim: int, num_heads: int, flash: bool = False, bias: bool = True) -> None:
super().__init__()
self.embed_dim = embed_dim
@@ -140,24 +160,23 @@ class Transformer(Module):
nn.Linear(2 * embed_dim, embed_dim),
)
- def _forward(self, x: Tensor, encoding: Optional[Tensor] = None) -> Tensor:
+ def forward(
+ self,
+ x: Tensor,
+ encoding: Tensor,
+ mask: Optional[Tensor] = None,
+ ) -> Tensor:
qkv = self.Wqkv(x)
qkv = qkv.unflatten(-1, (self.num_heads, -1, 3)).transpose(1, 2)
q, k, v = qkv[..., 0], qkv[..., 1], qkv[..., 2]
- if encoding is not None:
- q = apply_cached_rotary_emb(encoding, q)
- k = apply_cached_rotary_emb(encoding, k)
- context = self.inner_attn(q, k, v)
+ q = apply_cached_rotary_emb(encoding, q)
+ k = apply_cached_rotary_emb(encoding, k)
+ context = self.inner_attn(q, k, v, mask=mask)
message = self.out_proj(context.transpose(1, 2).flatten(start_dim=-2))
return x + self.ffn(concatenate([x, message], -1))
- def forward(
- self, x0: Tensor, x1: Tensor, encoding0: Optional[Tensor] = None, encoding1: Optional[Tensor] = None
- ) -> Tuple[Tensor, Tensor]:
- return self._forward(x0, encoding0), self._forward(x1, encoding1)
-
-class CrossTransformer(Module):
+class CrossBlock(Module):
def __init__(self, embed_dim: int, num_heads: int, flash: bool = False, bias: bool = True) -> None:
super().__init__()
self.heads = num_heads
@@ -173,7 +192,6 @@ class CrossTransformer(Module):
nn.GELU(),
nn.Linear(2 * embed_dim, embed_dim),
)
-
if flash and FLASH_AVAILABLE:
self.flash = Attention(True)
else:
@@ -182,20 +200,27 @@ class CrossTransformer(Module):
def map_(self, func: Callable, x0: Tensor, x1: Tensor) -> Tuple[Tensor, Tensor]: # type: ignore
return func(x0), func(x1)
- def forward(self, x0: Tensor, x1: Tensor) -> Tuple[Tensor, Tensor]:
+ def forward(self, x0: Tensor, x1: Tensor, mask: Optional[Tensor] = None) -> Tuple[Tensor, Tensor]:
qk0, qk1 = self.map_(self.to_qk, x0, x1)
v0, v1 = self.map_(self.to_v, x0, x1)
- qk0, qk1, v0, v1 = (t.unflatten(-1, (self.heads, -1)).transpose(1, 2) for t in (qk0, qk1, v0, v1))
- if self.flash is not None:
- m0 = self.flash(qk0, qk1, v1)
- m1 = self.flash(qk1, qk0, v0)
+ qk0, qk1, v0, v1 = map(
+ lambda t: t.unflatten(-1, (self.heads, -1)).transpose(1, 2),
+ (qk0, qk1, v0, v1),
+ )
+ if self.flash is not None and qk0.device.type == "cuda":
+ m0 = self.flash(qk0, qk1, v1, mask)
+ m1 = self.flash(qk1, qk0, v0, mask.transpose(-1, -2) if mask is not None else None)
else:
qk0, qk1 = qk0 * self.scale**0.5, qk1 * self.scale**0.5
- sim = einsum("b h i d, b h j d -> b h i j", qk0, qk1)
- attn01 = softmax(sim, dim=-1)
- attn10 = softmax(sim.transpose(-2, -1).contiguous(), dim=-1)
+ sim = einsum("bhid, bhjd -> bhij", qk0, qk1)
+ if mask is not None:
+ sim = sim.masked_fill(~mask, -float("inf"))
+ attn01 = F.softmax(sim, dim=-1)
+ attn10 = F.softmax(sim.transpose(-2, -1).contiguous(), dim=-1)
m0 = einsum("bhij, bhjd -> bhid", attn01, v1)
m1 = einsum("bhji, bhjd -> bhid", attn10.transpose(-2, -1), v0)
+ if mask is not None:
+ m0, m1 = m0.nan_to_num(), m1.nan_to_num()
m0, m1 = self.map_(lambda t: t.transpose(1, 2).flatten(start_dim=-2), m0, m1)
m0, m1 = self.map_(self.to_out, m0, m1)
x0 = x0 + self.ffn(concatenate([x0, m0], -1))
@@ -203,6 +228,40 @@ class CrossTransformer(Module):
return x0, x1
+class TransformerLayer(Module):
+ def __init__(self, *args, **kwargs): # type: ignore
+ super().__init__()
+ self.self_attn = SelfBlock(*args, **kwargs)
+ self.cross_attn = CrossBlock(*args, **kwargs)
+
+ def forward(
+ self,
+ desc0: Tensor,
+ desc1: Tensor,
+ encoding0: Tensor,
+ encoding1: Tensor,
+ mask0: Optional[Tensor] = None,
+ mask1: Optional[Tensor] = None,
+ ) -> Tensor:
+ if mask0 is not None and mask1 is not None:
+ return self.masked_forward(desc0, desc1, encoding0, encoding1, mask0, mask1)
+ else:
+ desc0 = self.self_attn(desc0, encoding0)
+ desc1 = self.self_attn(desc1, encoding1)
+ return self.cross_attn(desc0, desc1)
+
+ # This part is compiled and allows padding inputs
+ def masked_forward(
+ self, desc0: Tensor, desc1: Tensor, encoding0: Tensor, encoding1: Tensor, mask0: Tensor, mask1: Tensor
+ ) -> Tensor:
+ mask = mask0 & mask1.transpose(-1, -2)
+ mask0 = mask0 & mask0.transpose(-1, -2)
+ mask1 = mask1 & mask1.transpose(-1, -2)
+ desc0 = self.self_attn(desc0, encoding0, mask0)
+ desc1 = self.self_attn(desc1, encoding1, mask1)
+ return self.cross_attn(desc0, desc1, mask)
+
+
def sigmoid_log_double_softmax(sim: Tensor, z0: Tensor, z1: Tensor) -> Tensor:
"""Create the log assignment matrix from logits and similarity."""
b, m, n = sim.shape
@@ -234,29 +293,26 @@ class MatchAssignment(Module):
scores = sigmoid_log_double_softmax(sim, z0, z1)
return scores, sim
- def scores(self, desc0: Tensor, desc1: Tensor) -> Tuple[Tensor, Tensor]:
- m0 = torch.sigmoid(self.matchability(desc0)).squeeze(-1)
- m1 = torch.sigmoid(self.matchability(desc1)).squeeze(-1)
- return m0, m1
+ def get_matchability(self, desc: Tensor) -> Tensor:
+ return torch.sigmoid(self.matchability(desc)).squeeze(-1)
def filter_matches(scores: Tensor, th: float) -> Tuple[Tensor, Tensor, Tensor, Tensor]:
- """Obtain matches from a log assignment matrix [Bx M+1 x N+1]"""
+ """Obtain matches from a log assignment matrix [Bx M+1 x N+1]."""
max0, max1 = scores[:, :-1, :-1].max(2), scores[:, :-1, :-1].max(1)
m0, m1 = max0.indices, max1.indices
- mutual0 = arange(m0.shape[1]).to(m0)[None] == m1.gather(1, m0)
- mutual1 = arange(m1.shape[1]).to(m1)[None] == m0.gather(1, m1)
+ indices0 = arange(m0.shape[1], device=m0.device)[None]
+ indices1 = arange(m1.shape[1], device=m1.device)[None]
+ mutual0 = indices0 == m1.gather(1, m0)
+ mutual1 = indices1 == m0.gather(1, m1)
max0_exp = max0.values.exp()
zero = max0_exp.new_tensor(0)
mscores0 = where(mutual0, max0_exp, zero)
mscores1 = where(mutual1, mscores0.gather(1, m1), zero)
- if th is not None:
- valid0 = mutual0 & (mscores0 > th)
- else:
- valid0 = mutual0
+ valid0 = mutual0 & (mscores0 > th)
valid1 = mutual1 & valid0.gather(1, m1)
- m0 = where(valid0, m0, m0.new_tensor(-1))
- m1 = where(valid1, m1, m1.new_tensor(-1))
+ m0 = where(valid0, m0, -1)
+ m1 = where(valid1, m1, -1)
return m0, m1, mscores0, mscores1
@@ -265,6 +321,9 @@ class LightGlue(Module):
"name": "lightglue", # just for interfacing
"input_dim": 256, # input descriptor dimension (autoselected from weights)
"descriptor_dim": 256,
+ "add_scale_ori": False,
+ "add_laf": False, # for KeyNetAffNetHardNet
+ "scale_coef": 1.0, # to compensate for the SIFT scale bigger than KeyNet
"n_layers": 9,
"num_heads": 4,
"flash": True, # enable FlashAttention if available.
@@ -275,48 +334,125 @@ class LightGlue(Module):
"weights": None,
}
+ # Point pruning involves an overhead (gather).
+ # Therefore, we only activate it if there are enough keypoints.
+ pruning_keypoint_thresholds: ClassVar[Dict[str, Any]] = {
+ "cpu": -1,
+ "mps": -1,
+ "cuda": 1024,
+ "flash": 1536,
+ }
required_data_keys: ClassVar[List[str]] = ["image0", "image1"]
version: ClassVar[str] = "v0.1_arxiv"
url: ClassVar[str] = "https://github.com/cvg/LightGlue/releases/download/{}/{}_lightglue.pth"
- features: ClassVar[Dict[str, Any]] = {"superpoint": ("superpoint_lightglue", 256), "disk": ("disk_lightglue", 128)}
+ features: ClassVar[Dict[str, Any]] = {
+ "superpoint": {
+ "weights": "superpoint_lightglue",
+ "input_dim": 256,
+ },
+ "disk": {
+ "weights": "disk_lightglue",
+ "input_dim": 128,
+ },
+ "aliked": {
+ "weights": "aliked_lightglue",
+ "input_dim": 128,
+ },
+ "sift": {
+ "weights": "sift_lightglue",
+ "input_dim": 128,
+ "add_scale_ori": True,
+ },
+ "dog_affnet_hardnet": {
+ "weights": "keynet_affnet_hardnet_lightglue",
+ "input_dim": 128,
+ "width_confidence": -1,
+ "depth_confidence": -1,
+ "add_laf": True,
+ "scale_coef": 0.1,
+ },
+ "keynet_affnet_hardnet": {
+ "weights": "keynet_affnet_hardnet_lightglue",
+ "input_dim": 128,
+ "width_confidence": -1,
+ "depth_confidence": -1,
+ "add_laf": True,
+ },
+ }
- def __init__(self, features: str = "superpoint", **conf) -> None: # type: ignore
+ def __init__(self, features: str = "superpoint", **conf_) -> None: # type: ignore
super().__init__()
- temp_conf = {**self.default_conf, **conf}
+ self.conf = conf = SimpleNamespace(**{**self.default_conf, **conf_})
if features is not None:
KORNIA_CHECK(features in list(self.features.keys()), "Features keys are wrong")
- temp_conf["weights"], temp_conf["input_dim"] = self.features[features]
- self.conf = conf_ = SimpleNamespace(**temp_conf)
+ for k, v in self.features[features].items():
+ setattr(conf, k, v)
+ KORNIA_CHECK(not (self.conf.add_scale_ori and self.conf.add_laf)) # we use either scale ori, or LAF
- if conf_.input_dim != conf_.descriptor_dim:
- self.input_proj = nn.Linear(conf_.input_dim, conf_.descriptor_dim, bias=True)
+ if conf.input_dim != conf.descriptor_dim:
+ self.input_proj = nn.Linear(conf.input_dim, conf.descriptor_dim, bias=True)
else:
self.input_proj = nn.Identity() # type: ignore
- head_dim = conf_.descriptor_dim // conf_.num_heads
- self.posenc = LearnableFourierPositionalEncoding(2, head_dim, head_dim)
+ head_dim = conf.descriptor_dim // conf.num_heads
+ self.posenc = LearnableFourierPositionalEncoding(
+ 2 + 2 * conf.add_scale_ori + 4 * conf.add_laf,
+ head_dim,
+ head_dim,
+ )
- h, n, d = conf_.num_heads, conf_.n_layers, conf_.descriptor_dim
- self.self_attn = ModuleList([Transformer(d, h, conf_.flash) for _ in range(n)])
- self.cross_attn = ModuleList([CrossTransformer(d, h, conf_.flash) for _ in range(n)])
+ h, n, d = conf.num_heads, conf.n_layers, conf.descriptor_dim
+ self.transformers = ModuleList([TransformerLayer(d, h, conf.flash) for _ in range(n)])
self.log_assignment = ModuleList([MatchAssignment(d) for _ in range(n)])
self.token_confidence = ModuleList([TokenConfidence(d) for _ in range(n - 1)])
-
+ self.register_buffer(
+ "confidence_thresholds",
+ Tensor([self.confidence_threshold(i) for i in range(self.conf.n_layers)]),
+ )
+ state_dict = None
if features is not None:
- fname = f"{conf_.weights}_{self.version}.pth".replace(".", "-")
- state_dict = torch.hub.load_state_dict_from_url(self.url.format(self.version, features), file_name=fname)
- self.load_state_dict(state_dict, strict=False)
- elif conf_.weights is not None:
+ fname = f"{conf.weights}_{self.version}.pth".replace(".", "-")
+ if features in ["keynet_affnet_hardnet", "dog_affnet_hardnet"]:
+ fname = "keynet_affnet_hardnet_lightlue.pth"
+ url = "http://cmp.felk.cvut.cz/~mishkdmy/models/keynet_affnet_hardnet_lightlue.pth"
+ else:
+ url = self.url.format(self.version, features)
+ state_dict = torch.hub.load_state_dict_from_url(url, file_name=fname)
+ elif conf.weights is not None:
path = Path(__file__).parent
path = path / f"weights/{self.conf.weights}.pth"
state_dict = torch.load(str(path), map_location="cpu")
+ if state_dict:
+ # rename old state dict entries
+ for i in range(self.conf.n_layers):
+ pattern = f"self_attn.{i}", f"transformers.{i}.self_attn"
+ state_dict = {k.replace(*pattern): v for k, v in state_dict.items()}
+ pattern = f"cross_attn.{i}", f"transformers.{i}.cross_attn"
+ state_dict = {k.replace(*pattern): v for k, v in state_dict.items()}
self.load_state_dict(state_dict, strict=False)
-
print("Loaded LightGlue model")
+ # static lengths LightGlue is compiled for (only used with torch.compile)
+ self.static_lengths = None
+
+ def compile(
+ self, mode: str = "reduce-overhead", static_lengths: List[int] = [256, 512, 768, 1024, 1280, 1536]
+ ) -> None:
+ if self.conf.width_confidence != -1:
+ warnings.warn(
+ "Point pruning is partially disabled for compiled forward.",
+ stacklevel=2,
+ )
- def forward(self, data: Dict) -> Dict: # type: ignore
+ for i in range(self.conf.n_layers):
+ self.transformers[i].masked_forward = torch.compile(
+ self.transformers[i].masked_forward, mode=mode, fullgraph=True
+ )
+
+ self.static_lengths = static_lengths # type: ignore
+
+ def forward(self, data: dict) -> dict: # type: ignore
"""Match keypoints and descriptors between two images.
Input (dict):
@@ -336,34 +472,53 @@ class LightGlue(Module):
matching_scores1: [B x N]
matches: List[[Si x 2]], scores: List[[Si]]
"""
- with torch.cuda.amp.autocast(enabled=self.conf.mp):
+ with torch.autocast(enabled=self.conf.mp, device_type="cuda"):
return self._forward(data)
- def _forward(self, data: Dict[str, Dict[str, Tensor]]) -> Dict[str, Any]:
+ def _forward(self, data: dict) -> dict: # type: ignore
for key in self.required_data_keys:
KORNIA_CHECK(key in data, f"Missing key {key} in data")
data0, data1 = data["image0"], data["image1"]
- kpts0_, kpts1_ = data0["keypoints"], data1["keypoints"]
-
- # torch 1.9.0 compatibility
- if hasattr(torch, "inf"):
- inf = torch.inf
- else:
- inf = math.inf
-
- b, m, _ = kpts0_.shape
- b, n, _ = kpts1_.shape
+ kpts0, kpts1 = data0["keypoints"], data1["keypoints"]
+ b, m, _ = kpts0.shape
+ b, n, _ = kpts1.shape
+ device = kpts0.device
size0, size1 = data0.get("image_size"), data1.get("image_size")
- size0 = size0 if size0 is not None else data0["image"].shape[-2:][::-1] # type: ignore
- size1 = size1 if size1 is not None else data1["image"].shape[-2:][::-1] # type: ignore
- kpts0 = normalize_keypoints(kpts0_, size=size0)
- kpts1 = normalize_keypoints(kpts1_, size=size1)
+ size0 = size0 if size0 is not None else data0["image"].shape[-2:][::-1]
+ size1 = size1 if size1 is not None else data1["image"].shape[-2:][::-1]
+ kpts0 = normalize_keypoints(kpts0, size0).clone()
+ kpts1 = normalize_keypoints(kpts1, size1).clone()
KORNIA_CHECK(torch.all(kpts0 >= -1).item() and torch.all(kpts0 <= 1).item(), "") # type: ignore
KORNIA_CHECK(torch.all(kpts1 >= -1).item() and torch.all(kpts1 <= 1).item(), "") # type: ignore
+ if self.conf.add_scale_ori:
+ kpts0 = concatenate([kpts0] + [data0[k].unsqueeze(-1) for k in ("scales", "oris")], -1)
+ kpts1 = concatenate([kpts1] + [data1[k].unsqueeze(-1) for k in ("scales", "oris")], -1)
+ elif self.conf.add_laf:
+ laf0 = scale_laf(data0["lafs"], self.conf.scale_coef)
+ laf1 = scale_laf(data1["lafs"], self.conf.scale_coef)
+ laf0 = laf_to_three_points(laf0)
+ laf1 = laf_to_three_points(laf1)
+ kpts0 = concatenate(
+ [
+ kpts0,
+ normalize_keypoints(laf0[..., 0], size0).clone().to(kpts0.dtype),
+ normalize_keypoints(laf0[..., 1], size0).clone().to(kpts0.dtype),
+ ],
+ -1,
+ )
+ kpts1 = concatenate(
+ [
+ kpts1,
+ normalize_keypoints(laf1[..., 0], size1).clone().to(kpts1.dtype),
+ normalize_keypoints(laf1[..., 1], size1).clone().to(kpts1.dtype),
+ ],
+ -1,
+ )
+
+ desc0 = data0["descriptors"].detach().contiguous()
+ desc1 = data1["descriptors"].detach().contiguous()
- desc0 = data0["descriptors"].detach()
- desc1 = data1["descriptors"].detach()
KORNIA_CHECK(desc0.shape[-1] == self.conf.input_dim, "Descriptor dimension does not match input dim in config")
KORNIA_CHECK(desc1.shape[-1] == self.conf.input_dim, "Descriptor dimension does not match input dim in config")
@@ -371,93 +526,128 @@ class LightGlue(Module):
desc0 = desc0.half()
desc1 = desc1.half()
+ mask0, mask1 = None, None
+ c = max(m, n)
+ do_compile = self.static_lengths and c <= max(self.static_lengths)
+ if do_compile:
+ kn = min([k for k in self.static_lengths if k >= c])
+ desc0, mask0 = pad_to_length(desc0, kn)
+ desc1, mask1 = pad_to_length(desc1, kn)
+ kpts0, _ = pad_to_length(kpts0, kn)
+ kpts1, _ = pad_to_length(kpts1, kn)
desc0 = self.input_proj(desc0)
desc1 = self.input_proj(desc1)
-
# cache positional embeddings
encoding0 = self.posenc(kpts0)
encoding1 = self.posenc(kpts1)
# GNN + final_proj + assignment
- ind0 = arange(0, m).to(device=kpts0.device)[None]
- ind1 = arange(0, n).to(device=kpts0.device)[None]
- prune0 = ones_like(ind0) # store layer where pruning is detected
- prune1 = ones_like(ind1)
- dec, wic = self.conf.depth_confidence, self.conf.width_confidence
+ do_early_stop = self.conf.depth_confidence > 0
+ do_point_pruning = self.conf.width_confidence > 0 and not do_compile
+ pruning_th = self.pruning_min_kpts(device)
+ if do_point_pruning:
+ ind0 = arange(0, m, device=device)[None]
+ ind1 = arange(0, n, device=device)[None]
+ # We store the index of the layer at which pruning is detected.
+ prune0 = ones_like(ind0)
+ prune1 = ones_like(ind1)
token0, token1 = None, None
for i in range(self.conf.n_layers):
- # self+cross attention
- desc0, desc1 = self.self_attn[i](desc0, desc1, encoding0, encoding1)
- desc0, desc1 = self.cross_attn[i](desc0, desc1)
+ desc0, desc1 = self.transformers[i](desc0, desc1, encoding0, encoding1, mask0=mask0, mask1=mask1)
if i == self.conf.n_layers - 1:
continue # no early stopping or adaptive width at last layer
- if dec > 0: # early stopping
+
+ if do_early_stop:
token0, token1 = self.token_confidence[i](desc0, desc1)
- if self.stop(token0, token1, self.conf_th(i), dec, m + n):
- break
- if wic > 0: # point pruning
- match0, match1 = self.log_assignment[i].scores(desc0, desc1)
- mask0 = self.get_mask(token0, match0, self.conf_th(i), 1 - wic) # type: ignore
- mask1 = self.get_mask(token1, match1, self.conf_th(i), 1 - wic) # type: ignore
- ind0, ind1 = ind0[mask0][None], ind1[mask1][None]
- desc0, desc1 = desc0[mask0][None], desc1[mask1][None]
- if desc0.shape[-2] == 0 or desc1.shape[-2] == 0:
+ if self.check_if_stop(token0[..., :m, :], token1[..., :n, :], i, m + n):
break
- encoding0 = encoding0[:, :, mask0][:, None]
- encoding1 = encoding1[:, :, mask1][:, None]
- prune0[:, ind0] += 1
- prune1[:, ind1] += 1
-
- if wic > 0: # scatter with indices after pruning
- scores_, _ = self.log_assignment[i](desc0, desc1)
- dt, dev = scores_.dtype, scores_.device
- scores = zeros(b, m + 1, n + 1, dtype=dt, device=dev)
- scores[:, :-1, :-1] = -inf
- scores[:, ind0[0], -1] = scores_[:, :-1, -1]
- scores[:, -1, ind1[0]] = scores_[:, -1, :-1]
- x, y = torch_meshgrid([ind0[0], ind1[0]], "ij")
- scores[:, x, y] = scores_[:, :-1, :-1]
- else:
- scores, _ = self.log_assignment[i](desc0, desc1)
-
+ if do_point_pruning and desc0.shape[-2] > pruning_th:
+ scores0 = self.log_assignment[i].get_matchability(desc0)
+ prunemask0 = self.get_pruning_mask(token0, scores0, i) # type: ignore
+ keep0 = where(prunemask0)[1]
+ ind0 = ind0.index_select(1, keep0)
+ desc0 = desc0.index_select(1, keep0)
+ encoding0 = encoding0.index_select(-2, keep0)
+ prune0[:, ind0] += 1
+ if do_point_pruning and desc1.shape[-2] > pruning_th:
+ scores1 = self.log_assignment[i].get_matchability(desc1)
+ prunemask1 = self.get_pruning_mask(token1, scores1, i) # type: ignore
+ keep1 = where(prunemask1)[1]
+ ind1 = ind1.index_select(1, keep1)
+ desc1 = desc1.index_select(1, keep1)
+ encoding1 = encoding1.index_select(-2, keep1)
+ prune1[:, ind1] += 1
+
+ desc0, desc1 = desc0[..., :m, :], desc1[..., :n, :]
+ scores, _ = self.log_assignment[i](desc0, desc1)
m0, m1, mscores0, mscores1 = filter_matches(scores, self.conf.filter_threshold)
-
matches, mscores = [], []
for k in range(b):
valid = m0[k] > -1
- matches.append(stack([where(valid)[0], m0[k][valid]], -1))
+ m_indices_0 = where(valid)[0]
+ m_indices_1 = m0[k][valid]
+ if do_point_pruning:
+ m_indices_0 = ind0[k, m_indices_0]
+ m_indices_1 = ind1[k, m_indices_1]
+ matches.append(stack([m_indices_0, m_indices_1], -1))
mscores.append(mscores0[k][valid])
- return {
- "log_assignment": scores,
+ # TODO: Remove when hloc switches to the compact format.
+ if do_point_pruning:
+ m0_ = torch.full((b, m), -1, device=m0.device, dtype=m0.dtype)
+ m1_ = torch.full((b, n), -1, device=m1.device, dtype=m1.dtype)
+ m0_[:, ind0] = where(m0 == -1, -1, ind1.gather(1, m0.clamp(min=0)))
+ m1_[:, ind1] = where(m1 == -1, -1, ind0.gather(1, m1.clamp(min=0)))
+ mscores0_ = zeros((b, m), device=mscores0.device)
+ mscores1_ = zeros((b, n), device=mscores1.device)
+ mscores0_[:, ind0] = mscores0
+ mscores1_[:, ind1] = mscores1
+ m0, m1, mscores0, mscores1 = m0_, m1_, mscores0_, mscores1_
+ else:
+ prune0 = ones_like(mscores0) * self.conf.n_layers
+ prune1 = ones_like(mscores1) * self.conf.n_layers
+
+ pred = {
"matches0": m0,
"matches1": m1,
"matching_scores0": mscores0,
"matching_scores1": mscores1,
"stop": i + 1,
- "prune0": prune0,
- "prune1": prune1,
"matches": matches,
"scores": mscores,
+ "prune0": prune0,
+ "prune1": prune1,
}
- def conf_th(self, i: int) -> float:
+ return pred
+
+ def confidence_threshold(self, layer_index: int) -> float:
"""Scaled confidence threshold."""
- return math_clamp(0.8 + 0.1 * math.exp(-4.0 * float(i) / self.conf.n_layers), 0.0, 1.0)
+ threshold = 0.8 + 0.1 * math.exp(-4.0 * layer_index / self.conf.n_layers)
+ return min(max(threshold, 1), 0)
- def get_mask(self, confidence: Tensor, match: Tensor, conf_th: float, match_th: float) -> Tensor:
+ def get_pruning_mask(self, confidences: Tensor, scores: Tensor, layer_index: int) -> Tensor:
"""Mask points which should be removed."""
- if conf_th and confidence is not None:
- mask = where(confidence > conf_th, match, match.new_tensor(1.0)) > match_th
- else:
- mask = match > match_th
- return mask
-
- def stop(self, token0: Tensor, token1: Tensor, conf_th: float, inl_th: float, seql: int) -> Tensor:
+ keep = scores > (1 - self.conf.width_confidence)
+ if confidences is not None: # Low-confidence points are never pruned.
+ keep |= confidences <= self.confidence_thresholds[layer_index]
+ return keep
+
+ def check_if_stop(
+ self,
+ confidences0: Tensor,
+ confidences1: Tensor,
+ layer_index: int,
+ num_points: int,
+ ) -> Tensor:
"""Evaluate stopping condition."""
- tokens = concatenate([token0, token1], -1)
- if conf_th:
- pos = 1.0 - (tokens < conf_th).float().sum() / seql
- return pos > inl_th
+ confidences = concatenate([confidences0, confidences1], -1)
+ threshold = self.confidence_thresholds[layer_index]
+ ratio_confident = 1.0 - (confidences < threshold).float().sum() / num_points
+ return ratio_confident > self.conf.depth_confidence
+
+ def pruning_min_kpts(self, device: torch.device) -> int:
+ if self.conf.flash and FLASH_AVAILABLE and device.type == "cuda":
+ return self.pruning_keypoint_thresholds["flash"]
else:
- return tokens.mean() > inl_th
+ return self.pruning_keypoint_thresholds[device.type]