Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(feature): place LoFTR keypoints correctly for any image size (#5729)

Dmytro Mishkin8c102d8de95f
diff --git a/changelog.d/5729.fixed.md b/changelog.d/5729.fixed.md
new file mode 100644
index 000000000..cb3b5cdfe
--- /dev/null
+++ b/changelog.d/5729.fixed.md
@@ -0,0 +1,16 @@
+`LoFTR` misplaced its keypoints for image sizes that are not multiples of 8. It converted the coarse cells of both
+images to pixels with `H0 / ceil(H0 / 8)` instead of the 8-pixel stride of the coarse feature map, cut the
+fine-matching windows of both images on a grid of the wrong stride, and scaled the fine offsets by `H0 / ceil(H0 / 2)`;
+its FPN also upsampled each level to the size of its skip connection, which reads the coarser level at other positions
+than the trained weights expect whenever a side is not 0 or 7 mod 8. On crops of Oxford graf 361 to 366 px high and
+three known homographies, 4 % of the matches were within 1 px of the ground truth, with a median error of 3.1 px and
+errors up to 9.4 px. Coarse and fine cells are now converted with the 8- and 2-pixel strides of the feature maps for
+any image size, `mask0` / `mask1` are read at the pixels the coarse cells sit on, and the FPN upsamples by 2 and crops
+to the skip size: 99 % of the matches are within 1 px on the same crops (median 0.23 px), and on IMC PhotoTourism
+validation with images resized by 0.6 the pose mAA@10 goes from 0.49 to 0.72. Inputs whose heights and widths are all
+multiples of 8 give the same results as before.
+
+`LoFTR` with `mask0` / `mask1` now runs in float16. It raised a `RuntimeError`, because the similarity -1e9 given to
+masked pairs does not fit in float16, and padded queries overflowed the linear attention's normaliser to inf, which
+made the features nan. Masked pairs now take the lowest finite float16 value, and padded queries, whose output is 0,
+divide by 1 instead of by eps, so they no longer make the output or the gradients nan; float32 results are unchanged.
diff --git a/kornia/feature/loftr/backbone/resnet_fpn.py b/kornia/feature/loftr/backbone/resnet_fpn.py
index d831eae55..7a0c4650e 100644
--- a/kornia/feature/loftr/backbone/resnet_fpn.py
+++ b/kornia/feature/loftr/backbone/resnet_fpn.py
@@ -149,13 +149,17 @@ class ResNetFPN_8_2(nn.Module):
# FPN
x3_out = self.layer3_outconv(x3)
+ # Upsample by 2 as the reference does, then crop to the skip size: the 1/4 map is one row / column smaller
+ # than twice the 1/8 map when a side is 1-4 mod 8, the 1/2 map than twice the 1/4 map when it is 1, 2, 5 or
+ # 6 mod 8, neither for 0 or 7. Cell i of the finer map then reads the coarser map at i * (n - 1) / (2n - 1),
+ # the mapping the weights were trained with, for every image size.
x2_out = self.layer2_outconv(x2)
- x3_out_2x = F.interpolate(x3_out, size=(x2_out.shape[2:]), mode="bilinear", align_corners=True)
- x2_out = self.layer2_outconv2(x2_out + x3_out_2x)
+ x3_out_2x = F.interpolate(x3_out, scale_factor=2.0, mode="bilinear", align_corners=True)
+ x2_out = self.layer2_outconv2(x2_out + x3_out_2x[..., : x2_out.shape[2], : x2_out.shape[3]])
x1_out = self.layer1_outconv(x1)
- x2_out_2x = F.interpolate(x2_out, size=(x1_out.shape[2:]), mode="bilinear", align_corners=True)
- x1_out = self.layer1_outconv2(x1_out + x2_out_2x)
+ x2_out_2x = F.interpolate(x2_out, scale_factor=2.0, mode="bilinear", align_corners=True)
+ x1_out = self.layer1_outconv2(x1_out + x2_out_2x[..., : x1_out.shape[2], : x1_out.shape[3]])
return [x3_out, x1_out]
diff --git a/kornia/feature/loftr/loftr.py b/kornia/feature/loftr/loftr.py
index 80cfe63a7..cdfbffd33 100644
--- a/kornia/feature/loftr/loftr.py
+++ b/kornia/feature/loftr/loftr.py
@@ -24,7 +24,6 @@ import torch
from torch import nn
from kornia.core.download import hf_url, load_state_dict_from_url
-from kornia.geometry import resize
from .backbone import build_backbone
from .loftr_module import FinePreprocess, LocalFeatureTransformer
@@ -84,6 +83,14 @@ class LoFTR(nn.Module):
This is based on the original code from paper "LoFTR: Detector-Free Local
Feature Matching with Transformers". See :cite:`LoFTR2021` for more details.
+ With the default ``config``, whose ``resolution`` (8, 2) every pretrained model uses, the two images can differ in
+ size, and their heights and widths do not need to be multiples of 8 (the reference implementation expects
+ multiples of 8). ``keypoints0`` lie on the grid of the 1/8-resolution coarse feature map, at ``8 * (column, row)``
+ of a coarse cell, and ``keypoints1`` are refined to sub-pixel positions. Both are :math:`(x, y)` in the frame where
+ the centre of pixel :math:`(x, y)` is at :math:`(x + 0.5, y + 0.5)`, as in the reference implementation: subtract
+ 0.5 to get kornia's frame, in which pixel centres have integer coordinates. With ``resolution`` (16, 4) in
+ ``config``, ``keypoints0`` lie on a 16-pixel grid, and most sizes that are not multiples of 16 raise an error.
+
If the distance matrix dm is not provided, :py:func:`torch.cdist` is used.
Args:
@@ -152,11 +159,19 @@ class LoFTR(nn.Module):
- ``batch_indexes``, batch indexes for the keypoints and lafs :math:`(NC)`.
"""
+ # Pixel strides of the coarse and the fine feature map, (8, 2) by default. Every stride-2 stage of the backbone
+ # has a centred kernel, so coarse cell (x, y) sits on pixel (8x, 8y) and fine cell (x, y) on pixel (2x, 2y)
+ # for any image size. The maps have ceil(H / 8) and ceil(H / 2) rows, so H divided by a map size is not the
+ # stride.
+ stride_c, stride_f = self.config["resolution"]
+
# 1. Local Feature CNN
_data: dict[str, torch.Tensor | int | torch.Size] = {
"bs": data["image0"].size(0),
"hw0_i": data["image0"].shape[2:],
"hw1_i": data["image1"].shape[2:],
+ "stride_c": stride_c,
+ "stride_f": stride_f,
}
if _data["hw0_i"] == _data["hw1_i"]: # faster & better BN convergence
@@ -188,10 +203,11 @@ class LoFTR(nn.Module):
feat_c1 = feat_c1.reshape(n1, -1, c1)
mask_c0 = mask_c1 = None # mask is useful in training
+ # a coarse cell takes the mask value of the pixel it sits on
if "mask0" in data:
- mask_c0 = resize(data["mask0"], _data["hw0_c"], interpolation="nearest").flatten(-2)
+ mask_c0 = data["mask0"][..., ::stride_c, ::stride_c].flatten(-2)
if "mask1" in data:
- mask_c1 = resize(data["mask1"], _data["hw1_c"], interpolation="nearest").flatten(-2)
+ mask_c1 = data["mask1"][..., ::stride_c, ::stride_c].flatten(-2)
feat_c0, feat_c1 = self.loftr_coarse(feat_c0, feat_c1, mask_c0, mask_c1)
# 3. match coarse-level
diff --git a/kornia/feature/loftr/loftr_module/fine_preprocess.py b/kornia/feature/loftr/loftr_module/fine_preprocess.py
index 7af0ef76c..bcda18c88 100644
--- a/kornia/feature/loftr/loftr_module/fine_preprocess.py
+++ b/kornia/feature/loftr/loftr_module/fine_preprocess.py
@@ -67,13 +67,15 @@ class FinePreprocess(nn.Module):
:math:`(B, C_c, H_c, W_c)` or :math:`(N_c, C_c)`.
feat_c1: Coarse feature map or transformed tokens of the second image with shape
:math:`(B, C_c, H_c, W_c)` or :math:`(N_c, C_c)`.
- data: Dictionary containing coarse match metadata and indices.
+ data: Dictionary containing coarse match metadata and indices, and the pixel strides ``stride_c`` and
+ ``stride_f`` of the coarse and the fine feature maps.
Returns:
Tuple of local cropped fine feature patches ``(feat0, feat1)`` each with shape :math:`(N_m, W^2, C)`.
"""
W = self.W
- stride = data["hw0_f"][0] // data["hw0_c"][0]
+ # fine cells per coarse cell (4): the window of coarse cell i is centred on fine cell stride * i
+ stride = data["stride_c"] // data["stride_f"]
data.update({"W": W})
if data["b_ids"].shape[0] == 0:
diff --git a/kornia/feature/loftr/loftr_module/linear_attention.py b/kornia/feature/loftr/loftr_module/linear_attention.py
index e58aa6473..02f99dae8 100644
--- a/kornia/feature/loftr/loftr_module/linear_attention.py
+++ b/kornia/feature/loftr/loftr_module/linear_attention.py
@@ -82,7 +82,12 @@ class LinearAttention(nn.Module):
v_length = values.size(1)
values = values / v_length # prevent fp16 overflow
KV = torch.einsum("nshd,nshv->nhdv", K, values) # (S,D)' @ S,V
- Z = 1 / (torch.einsum("nlhd,nhd->nlh", Q, K.sum(dim=1)) + self.eps)
+ denominator = torch.einsum("nlhd,nhd->nlh", Q, K.sum(dim=1)) + self.eps
+ if q_mask is not None:
+ # A padded query has Q = 0, so it gives 0 whatever its normaliser. Its 1 / eps overflows float16, and
+ # 0 * inf would be nan in the output and in the gradient, so it divides by 1 instead.
+ denominator = torch.where(q_mask[:, :, None] > 0, denominator, torch.ones_like(denominator))
+ Z = 1 / denominator
queried_values = torch.einsum("nlhd,nhdv,nlh->nlhv", Q, KV, Z) * v_length
return queried_values.contiguous()
diff --git a/kornia/feature/loftr/utils/coarse_matching.py b/kornia/feature/loftr/utils/coarse_matching.py
index aeaac14a5..f629a69bb 100644
--- a/kornia/feature/loftr/utils/coarse_matching.py
+++ b/kornia/feature/loftr/utils/coarse_matching.py
@@ -24,6 +24,15 @@ from torch import nn
INF = 1e9
+def _masked_similarity(dtype: torch.dtype) -> float:
+ """Similarity given to masked pairs: ``-INF``, or the lowest finite value of ``dtype`` when ``INF`` overflows it.
+
+ float16 holds at most 65504. The value stays finite, so a row or column that is masked entirely still gets a
+ uniform softmax, where ``-inf`` would give ``-inf - (-inf) = nan``.
+ """
+ return -min(INF, torch.finfo(dtype).max)
+
+
def mask_border(m: torch.Tensor, b: int, v: Union[torch.Tensor, float, bool]) -> None:
"""Mask borders with value.
@@ -151,14 +160,18 @@ class CoarseMatching(nn.Module):
if self.match_type == "dual_softmax":
sim_matrix = torch.einsum("nlc,nsc->nls", feat_c0, feat_c1) / self.temperature
if mask_c0 is not None and mask_c1 is not None:
- sim_matrix.masked_fill_(~(mask_c0[..., None] * mask_c1[:, None]).bool(), -INF)
+ sim_matrix.masked_fill_(
+ ~(mask_c0[..., None] * mask_c1[:, None]).bool(), _masked_similarity(sim_matrix.dtype)
+ )
conf_matrix = F.softmax(sim_matrix, 1) * F.softmax(sim_matrix, 2)
elif self.match_type == "sinkhorn":
# sinkhorn, dustbin included
sim_matrix = torch.einsum("nlc,nsc->nls", feat_c0, feat_c1)
if mask_c0 is not None and mask_c1 is not None:
- sim_matrix[:, :L, :S].masked_fill_(~(mask_c0[..., None] * mask_c1[:, None]).bool(), -INF)
+ sim_matrix[:, :L, :S].masked_fill_(
+ ~(mask_c0[..., None] * mask_c1[:, None]).bool(), _masked_similarity(sim_matrix.dtype)
+ )
# build uniform prior & use sinkhorn
log_assign_matrix = self.log_optimal_transport(sim_matrix, self.bin_score, self.skh_iters)
@@ -186,7 +199,8 @@ class CoarseMatching(nn.Module):
Args:
conf_matrix (torch.Tensor): [N, L, S]
- data (dict): with keys ['hw0_i', 'hw1_i', 'hw0_c', 'hw1_c']
+ data (dict): with keys ['hw0_c', 'hw1_c', 'stride_c'], ``stride_c`` being the pixel stride of the coarse
+ feature maps (8 by default)
Returns:
coarse_matches (dict): {
@@ -282,8 +296,9 @@ class CoarseMatching(nn.Module):
# These matches select patches that feed into fine-level network
coarse_matches = {"b_ids": b_ids, "i_ids": i_ids, "j_ids": j_ids}
- # 4. Update with matches in original image resolution
- scale = data["hw0_i"][0] / data["hw0_c"][0]
+ # 4. Update with matches in original image resolution: coarse cell (x, y) of either image sits on pixel
+ # (stride_c * x, stride_c * y) for any image size
+ scale = data["stride_c"]
scale0 = scale * data["scale0"][b_ids] if "scale0" in data else scale
scale1 = scale * data["scale1"][b_ids] if "scale1" in data else scale
mkpts0_c = torch.stack([i_ids % data["hw0_c"][1], i_ids // data["hw0_c"][1]], dim=1) * scale0
diff --git a/kornia/feature/loftr/utils/fine_matching.py b/kornia/feature/loftr/utils/fine_matching.py
index 047681402..692c9fe55 100644
--- a/kornia/feature/loftr/utils/fine_matching.py
+++ b/kornia/feature/loftr/utils/fine_matching.py
@@ -40,7 +40,8 @@ class FineMatching(nn.Module):
Args:
feat_f0 (torch.Tensor): [M, WW, C]
feat_f1 (torch.Tensor): [M, WW, C]
- data (dict)
+ data (dict): with keys ['mkpts0_c', 'mkpts1_c', 'mconf', 'b_ids', 'stride_f'], ``stride_f`` being the
+ pixel stride of the fine feature maps (2 by default)
Update:
data (dict):{
'expec_f' (torch.Tensor): [M, 3],
@@ -50,7 +51,8 @@ class FineMatching(nn.Module):
"""
M, WW, C = feat_f0.shape
W = int(math.sqrt(WW))
- scale = data["hw0_i"][0] / data["hw0_f"][0]
+ # pixel stride of the fine feature maps (2 by default), for any image size
+ scale = data["stride_f"]
self.M, self.W, self.WW, self.C, self.scale = M, W, WW, C, scale
# corner case: if no coarse matches found
diff --git a/tests/feature/test_loftr.py b/tests/feature/test_loftr.py
index 185fba6e9..bf59d7d00 100644
--- a/tests/feature/test_loftr.py
+++ b/tests/feature/test_loftr.py
@@ -16,22 +16,37 @@
#
import copy
+import math
import sys
import pytest
import torch
+import torch.nn.functional as F
from kornia.feature import LoFTR
from kornia.feature.loftr import loftr as loftr_module
+from kornia.feature.loftr.backbone import ResNetFPN_8_2
from kornia.feature.loftr.loftr import default_cfg
+from kornia.feature.loftr.loftr_module import FinePreprocess
+from kornia.feature.loftr.loftr_module.linear_attention import LinearAttention
from kornia.feature.loftr.utils.coarse_matching import CoarseMatching
from kornia.feature.loftr.utils.fine_matching import FineMatching
-from kornia.geometry import resize
+from kornia.geometry import resize, transform_points, warp_perspective
from testing.base import BaseTester
from testing.casts import dict_to
+def _loftr_matching_every_cell(device, dtype):
+ """Randomly initialised LoFTR with no confidence threshold and no border removal: every mutual nearest cell
+ is a match, so the keypoints show the coarse grid of the whole image."""
+ cfg = copy.deepcopy(default_cfg)
+ cfg["match_coarse"]["thr"] = 0.0
+ cfg["match_coarse"]["border_rm"] = 0
+ torch.manual_seed(0)
+ return LoFTR(pretrained=None, config=cfg).to(device, dtype)
+
+
class TestLoFTR(BaseTester):
@pytest.mark.slow
def test_pretrained_outdoor_smoke(self, device, dtype):
@@ -76,8 +91,15 @@ class TestLoFTR(BaseTester):
data_dev = dict_to(data, device, dtype)
with torch.no_grad():
out = loftr(data_dev)
- self.assert_close(out["keypoints0"], data_dev["loftr_outdoor_tentatives0"])
- self.assert_close(out["keypoints1"], data_dev["loftr_outdoor_tentatives1"])
+ # image0 is 450 x 600; 450 is not a multiple of 8, and its 57 coarse rows sit 8 px apart. The stored
+ # tentatives place coarse cell (x, y) at 450 / 57 * (x, y), so they give the matched cells, not the pixels.
+ cells0 = torch.round(data_dev["loftr_outdoor_tentatives0"] * 57 / 450)
+ self.assert_close(out["keypoints0"], 8 * cells0, rtol=0.0, atol=0.0)
+ # keypoints1 follow the ground-truth homography of the pair (pixel-centre frame: subtract 0.5)
+ kpts0, kpts1 = out["keypoints0"].cpu().double() - 0.5, out["keypoints1"].cpu().double() - 0.5
+ err = (transform_points(data["H_gt"].cpu().double()[None], kpts0[None])[0] - kpts1).norm(dim=-1)
+ assert (err < 3).double().mean() > 0.85, err
+ assert err.median() < 1.5, err
@pytest.mark.slow
def test_mask(self, device):
@@ -89,6 +111,68 @@ class TestLoFTR(BaseTester):
out = loftr(sample)
assert out is not None
+ @pytest.mark.slow
+ @pytest.mark.skipif(sys.platform == "win32", reason="this test takes so much memory in the CI with Windows")
+ @pytest.mark.parametrize("data", ["loftr_homo"], indirect=True)
+ def test_pretrained_outdoor_images_of_different_sizes_5728(self, device, dtype, data):
+ # image0 is a 325 x 403 crop of the pair's first image, image1 that crop warped by a known homography (8 degree
+ # rotation and 0.9 scale about (200, 160)) into 339 x 401. No side is a multiple of 8 and the two sizes
+ # differ, so each image's FPN crops to its own skip sizes.
+ loftr = LoFTR("outdoor").to(device, dtype)
+ image0 = data["image0"][..., 60:385, 100:503].to(device, dtype)
+ c, s = 0.9 * math.cos(math.radians(8.0)), 0.9 * math.sin(math.radians(8.0))
+ shift = torch.tensor([[1.0, 0.0, -200.0], [0.0, 1.0, -160.0], [0.0, 0.0, 1.0]], dtype=torch.float64)
+ rot = torch.tensor([[c, -s, 2.0], [s, c, 1.0], [0.0, 0.0, 1.0]], dtype=torch.float64)
+ homography = torch.linalg.inv(shift) @ rot @ shift # pixel-centre frame
+ image1 = warp_perspective(image0, homography[None].to(device, dtype), (339, 401), align_corners=True)
+ with torch.no_grad():
+ out = loftr({"image0": image0, "image1": image1})
+ kpts0, kpts1 = out["keypoints0"].cpu().double() - 0.5, out["keypoints1"].cpu().double() - 0.5
+ err = (transform_points(homography[None], kpts0[None])[0] - kpts1).norm(dim=-1)
+ assert kpts0.shape[0] > 1000
+ assert (err < 1).double().mean() > 0.99, err
+ assert err.median() < 0.3, err
+
+ @pytest.mark.parametrize("hw1", [(100, 67), (93, 86)])
+ def test_keypoints0_on_the_8px_grid_for_any_size_5728(self, device, dtype, hw1):
+ # Coarse cell (x, y) sits on pixel (8x, 8y) whatever the image size: the backbone's stride-2 stages have
+ # centred kernels and the map sizes are rounded up. H0 = 100 has 13 coarse rows, so 100 / 13 = 7.69 is not
+ # the stride. hw1 = (100, 67) runs both images through the backbone together, (93, 86) one by one.
+ model = _loftr_matching_every_cell(device, dtype)
+ h0, w0 = 100, 67
+ image0 = torch.rand(1, 1, h0, w0).to(device, dtype)
+ image1 = torch.rand(1, 1, *hw1).to(device, dtype)
+ with torch.no_grad():
+ kpts0 = model({"image0": image0, "image1": image1})["keypoints0"]
+ assert kpts0.shape[0] > 10
+ self.assert_close(kpts0, 8 * torch.round(kpts0 / 8), rtol=0.0, atol=0.0)
+ # the last coarse column and row are cells 8 and 12, on pixels 64 and 96; the matches reach far into both
+ assert kpts0.min() >= 0
+ assert kpts0[:, 0].max() <= 8 * 8
+ assert kpts0[:, 1].max() <= 8 * 12
+ assert kpts0[:, 0].max() >= 8 * 5
+ assert kpts0[:, 1].max() >= 8 * 9
+
+ def test_mask_is_read_at_the_coarse_cell_pixels_5728(self, device, dtype):
+ # A coarse cell takes the mask value of the pixel it sits on, (8x, 8y). The masks are 1 only on those pixels
+ # (image0: on the ones with y < 64 and x < 40, so coarse rows 0..7 and columns 0..4), so every such cell is
+ # valid, while sampling the mask at (x, y) * size / coarse size would hit a 0 everywhere but at (0, 0).
+ model = _loftr_matching_every_cell(device, dtype)
+ h0, w0 = 100, 67
+ image0 = torch.rand(1, 1, h0, w0).to(device, dtype)
+ image1 = torch.rand(1, 1, 93, 86).to(device, dtype)
+ mask0 = torch.zeros(1, h0, w0, device=device, dtype=dtype)
+ mask0[:, :64:8, :40:8] = 1
+ mask1 = torch.zeros(1, 93, 86, device=device, dtype=dtype)
+ mask1[:, ::8, ::8] = 1
+ with torch.no_grad():
+ kpts0 = model({"image0": image0, "image1": image1, "mask0": mask0, "mask1": mask1})["keypoints0"]
+ assert kpts0.shape[0] > 5
+ self.assert_close(kpts0, 8 * torch.round(kpts0 / 8), rtol=0.0, atol=0.0)
+ assert kpts0[:, 0].max() <= 32
+ assert kpts0[:, 1].max() <= 56
+ assert kpts0[:, 1].max() >= 8 * 4
+
@pytest.mark.slow
def test_gradcheck(self, device):
patches = torch.rand(1, 1, 32, 32, device=device, dtype=torch.float64)
@@ -195,6 +279,7 @@ class TestCoarseMatching(BaseTester):
"hw1_c": (self.H1C, self.W1C),
"hw0_i": (self.H0C * 8, self.W0C * 8),
"hw1_i": (self.H1C * 8, self.W1C * 8),
+ "stride_c": 8,
"spv_b_ids": torch.zeros(self.N_GT, dtype=torch.long, device=device),
"spv_i_ids": torch.full((self.N_GT,), L - 1, dtype=torch.long, device=device),
"spv_j_ids": torch.full((self.N_GT,), S - 1, dtype=torch.long, device=device),
@@ -241,6 +326,48 @@ class TestCoarseMatching(BaseTester):
assert out["gt_mask"].sum() == 0
assert out["mconf"].numel() == out["b_ids"].shape[0] == self.N_PRED
+ @pytest.mark.parametrize("dtype", [torch.float32, torch.float16, torch.bfloat16])
+ def test_masked_dual_softmax_is_finite_5728(self, device, dtype):
+ # Masked pairs get a similarity of -1e9, which float16 cannot hold, so float16 takes its lowest finite value
+ # instead; -inf would make an entirely masked row or column nan. Cell 3 of image0 and cell 5 of image1 are
+ # masked, so row 3 and column 5 of the similarity matrix are masked entirely.
+ gen = torch.Generator().manual_seed(0)
+ feat0, feat1 = torch.randn(1, 12, 8, generator=gen), torch.randn(1, 9, 8, generator=gen)
+ mask0, mask1 = torch.ones(1, 12), torch.ones(1, 9)
+ mask0[0, 3], mask1[0, 5] = 0, 0
+ cm = CoarseMatching(self.CFG).to(device).eval()
+
+ def conf_matrix(dt):
+ data = {"hw0_c": (3, 4), "hw1_c": (3, 3), "stride_c": 8}
+ args = (t.to(device, dt) for t in (feat0, feat1, mask0, mask1))
+ f0, f1, m0, m1 = args
+ cm(f0, f1, data, mask_c0=m0, mask_c1=m1)
+ return data["conf_matrix"]
+
+ conf = conf_matrix(dtype)
+ assert conf.dtype == dtype
+ assert bool(torch.isfinite(conf).all())
+ self.assert_close(conf.float(), conf_matrix(torch.float32), rtol=0.0, atol=2e-2)
+ valid1 = torch.arange(9, device=device) != 5
+ assert conf[0, 3, valid1].float().max() < 1e-3
+
+ def test_keypoints_use_the_coarse_stride_5728(self, device, dtype):
+ # image0 100 x 67 -> 13 x 9 coarse cells, image1 93 x 86 -> 12 x 11: cell (x, y) of either image sits on
+ # pixel (8x, 8y). The ratios 100 / 13, 93 / 12, 67 / 9 and 86 / 11 all differ from 8 and from each other.
+ h0c, w0c, h1c, w1c = 13, 9, 12, 11
+ i_ids = torch.tensor([0, 10, 47, h0c * w0c - 1], device=device)
+ j_ids = torch.tensor([3, 40, 77, h1c * w1c - 1], device=device)
+ conf = torch.zeros(1, h0c * w0c, h1c * w1c, device=device, dtype=dtype)
+ conf[0, i_ids, j_ids] = 0.5
+ data = {"hw0_i": (100, 67), "hw1_i": (93, 86), "hw0_c": (h0c, w0c), "hw1_c": (h1c, w1c), "stride_c": 8}
+ cm = CoarseMatching(self.CFG).to(device).eval()
+ out = cm.get_coarse_match(conf, data)
+ assert out["i_ids"].tolist() == i_ids.tolist()
+ expected0 = torch.tensor([[0, 0], [8, 8], [16, 40], [64, 96]], device=device, dtype=dtype)
+ expected1 = torch.tensor([[24, 0], [56, 24], [0, 56], [80, 88]], device=device, dtype=dtype)
+ self.assert_close(out["mkpts0_c"], expected0, rtol=0.0, atol=0.0)
+ self.assert_close(out["mkpts1_c"], expected1, rtol=0.0, atol=0.0)
+
class TestFineMatching(BaseTester):
@staticmethod
@@ -257,6 +384,7 @@ class TestFineMatching(BaseTester):
data = {
"hw0_i": (40, 40),
"hw0_f": (20, 20),
+ "stride_f": 2,
"mkpts0_c": torch.zeros(M, 2, device=device, dtype=dtype),
"mkpts1_c": torch.zeros(M, 2, device=device, dtype=dtype),
"mconf": torch.ones(M, device=device, dtype=dtype),
@@ -289,3 +417,140 @@ class TestFineMatching(BaseTester):
self.assert_close(std, torch.full_like(std, 0.5).sqrt() * 2)
std.sum().backward()
assert bool(torch.isfinite(feat_f1.grad).all()), feat_f1.grad
+
+ def test_offset_uses_the_fine_stride_5728(self, device, dtype):
+ # The fine window of a match is 5 x 5 fine cells, 2 px apart, so a heatmap expectation at normalized
+ # (u, v) moves keypoints1 by (W // 2) * 2 * (u, v) = 4 (u, v) px, whatever the image size. image0
+ # 99 x 67 has 50 x 34 fine cells; 99 / 50 = 1.98 is not the stride.
+ M, W, C = 3, 5, 8
+ feat_f0 = torch.zeros(M, W * W, C, device=device, dtype=dtype)
+ feat_f1 = torch.zeros(M, W * W, C, device=device, dtype=dtype)
+ feat_f0[:, W * W // 2, 0] = 30.0
+ for m, cell in enumerate((4, 16, 21)): # (x, y) = (4, 0), (1, 3), (1, 4) in the window
+ feat_f1[m, cell, 0] = 30.0
+ data = {
+ "hw0_i": (99, 67),
+ "hw0_f": (50, 34),
+ "stride_f": 2,
+ "mkpts0_c": torch.tensor([[8.0, 16.0], [24.0, 0.0], [64.0, 96.0]], device=device, dtype=dtype),
+ "mkpts1_c": torch.tensor([[40.0, 8.0], [0.0, 32.0], [80.0, 88.0]], device=device, dtype=dtype),
+ "mconf": torch.ones(M, device=device, dtype=dtype),
+ "b_ids": torch.zeros(M, dtype=torch.long, device=device),
+ }
+ with torch.no_grad():
+ FineMatching()(feat_f0, feat_f1, data)
+ offset = data["mkpts1_f"] - data["mkpts1_c"]
+ self.assert_close(offset, data["expec_f"][:, :2] * 4)
+ # the peaks sit 2 fine cells right / up of the centre, 1 left / 1 down, 1 left / 2 down
+ self.assert_close(
+ offset,
+ torch.tensor([[4.0, -4.0], [-2.0, 2.0], [-2.0, 4.0]], device=device, dtype=dtype),
+ rtol=0.0,
+ atol=0.05,
+ )
+ self.assert_close(data["mkpts0_f"], data["mkpts0_c"], rtol=0.0, atol=0.0)
+
+
+class TestFinePreprocess(BaseTester):
+ def test_windows_centred_on_the_coarse_cells_5728(self, device, dtype):
+ # Coarse cell (x, y) sits on fine cell (4x, 4y) for any image size. image0 100 x 67 has 13 x 9 coarse and
+ # 50 x 34 fine cells, image1 93 x 86 has 12 x 11 and 47 x 43; 50 // 13 = 3 is not the stride. The fine
+ # maps hold their own (row, column) indices, so each window shows where it was cut.
+ cfg = {
+ "fine_concat_coarse_feat": False,
+ "fine_window_size": 5,
+ "coarse": {"d_model": 4},
+ "fine": {"d_model": 2},
+ }
+
+ def index_map(h, w):
+ rows, cols = torch.meshgrid(torch.arange(h), torch.arange(w), indexing="ij")
+ return torch.stack([rows, cols])[None].to(device, dtype)
+
+ b_ids = torch.zeros(4, dtype=torch.long, device=device)
+ i_ids = torch.tensor([0, 10, 47, 13 * 9 - 1], device=device)
+ j_ids = torch.tensor([3, 40, 77, 12 * 11 - 1], device=device)
+ data = {
+ "hw0_c": (13, 9),
+ "hw0_f": (50, 34),
+ "stride_c": 8,
+ "stride_f": 2,
+ "b_ids": b_ids,
+ "i_ids": i_ids,
+ "j_ids": j_ids,
+ }
+ feat_c = torch.zeros(1, 1, 4, device=device, dtype=dtype)
+ with torch.no_grad():
+ win0, win1 = FinePreprocess(cfg).to(device, dtype)(
+ index_map(50, 34), index_map(47, 43), feat_c, feat_c, data
+ )
+ assert win0.shape == win1.shape == (4, 25, 2)
+ centre0 = torch.stack([i_ids // 9, i_ids % 9], -1) * 4
+ centre1 = torch.stack([j_ids // 11, j_ids % 11], -1) * 4
+ self.assert_close(win0[:, 12], centre0.to(dtype), rtol=0.0, atol=0.0)
+ self.assert_close(win1[:, 12], centre1.to(dtype), rtol=0.0, atol=0.0)
+ # the window spans +-2 fine cells: its last element is two cells down and right of the centre
+ self.assert_close(win0[1:3, 24], (centre0[1:3] + 2).to(dtype), rtol=0.0, atol=0.0)
+
+
+class TestResNetFPN(BaseTester):
+ def test_fpn_upsamples_by_2_then_crops_5728(self, device, dtype):
+ # Each FPN level adds to its lateral map the coarser level upsampled by 2 (align_corners=True), cropped to
+ # the lateral size. A 65 x 74 input (1 and 2 mod 8) crops at both levels: the 1/8 map is 9 x 10 and the 1/4
+ # map 17 x 19, not 18 x 20; the 1/4 map is 17 x 19 and the 1/2 map 33 x 37, not 34 x 38. Upsampling to the
+ # lateral size instead reads the coarser map at other positions.
+ torch.manual_seed(0)
+ fpn = ResNetFPN_8_2(default_cfg["resnetfpn"]).to(device, dtype).eval()
+ seen = {}
+
+ def keep(name, output=True):
+ def hook(module, args, out=None):
+ seen[name] = out if output else args[0]
+
+ return hook
+
+ for name, module in (("x1", fpn.layer1), ("x2", fpn.layer2), ("x3_out", fpn.layer3_outconv)):
+ module.register_forward_hook(keep(name))
+ fpn.layer2_outconv2.register_forward_pre_hook(keep("sum2", output=False))
+ fpn.layer2_outconv2.register_forward_hook(keep("x2_out"))
+ fpn.layer1_outconv2.register_forward_pre_hook(keep("sum1", output=False))
+ with torch.no_grad():
+ fpn(torch.rand(1, 1, 65, 74).to(device, dtype))
+ assert seen["x3_out"].shape[2:] == (9, 10)
+ assert seen["x2"].shape[2:] == (17, 19)
+ assert seen["x1"].shape[2:] == (33, 37)
+ for coarse, lateral, total in (
+ (seen["x3_out"], fpn.layer2_outconv(seen["x2"]), seen["sum2"]),
+ (seen["x2_out"], fpn.layer1_outconv(seen["x1"]), seen["sum1"]),
+ ):
+ h, w = lateral.shape[2:]
+ up = F.interpolate(coarse, scale_factor=2.0, mode="bilinear", align_corners=True)[..., :h, :w]
+ self.assert_close(total, lateral + up)
+
+
+class TestLinearAttention(BaseTester):
+ @pytest.mark.parametrize("dtype", [torch.float32, torch.float16, torch.bfloat16])
+ def test_padded_queries_stay_finite_5728(self, device, dtype):
+ # A padded query has a zero feature map, so its normaliser 1 / eps = 1e6 would exceed float16's 65504. The
+ # padded rows must come out as 0, not as 0 * inf = nan, the gradients must stay finite as well, and the
+ # rest must not change.
+ gen = torch.Generator().manual_seed(0)
+ q, k, v = (torch.randn(1, n, 2, 4, generator=gen) for n in (6, 5, 5))
+ q_mask, kv_mask = torch.ones(1, 6), torch.ones(1, 5)
+ q_mask[0, [1, 4]], kv_mask[0, 2] = 0, 0
+
+ def attend(dt):
+ q_, k_, v_ = (t.to(device, dt).requires_grad_() for t in (q, k, v))
+ out = LinearAttention()(q_, k_, v_, q_mask.to(device, dt), kv_mask.to(device, dt))
+ out.sum().backward()
+ return out.detach(), q_.grad, k_.grad, v_.grad
+
+ out, *grads = attend(dtype)
+ out32, *grads32 = attend(torch.float32)
+ assert bool(torch.isfinite(out).all())
+ self.assert_close(out[0, [1, 4]], torch.zeros_like(out[0, [1, 4]]), rtol=0.0, atol=0.0)
+ self.assert_close(out.float(), out32, rtol=0.0, atol=5e-2)
+ for grad, grad32 in zip(grads, grads32):
+ assert bool(torch.isfinite(grad).all()), grad
+ self.assert_close(grad.float(), grad32, rtol=0.0, atol=5e-2)
+ self.assert_close(grads[0][0, [1, 4]], torch.zeros_like(grads[0][0, [1, 4]]), rtol=0.0, atol=0.0)