Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

perf(feature): make LoFTR's forward 1.3x faster with 30 % less peak GPU memory (#5879)

Dmytro Mishkin88713b40170e
diff --git a/changelog.d/5879.fixed.md b/changelog.d/5879.fixed.md
new file mode 100644
index 000000000..6c5274a88
--- /dev/null
+++ b/changelog.d/5879.fixed.md
@@ -0,0 +1,6 @@
+`LoFTR.forward` is faster and needs less peak memory: it cuts fine-level windows only at the matched cells, selects
+coarse matches from row and column maxima, runs the coarse-level linear attention as dense matrix products, and
+computes the dual softmax without PyTorch's slow `softmax(dim=1)` kernel outside float16. On 1024 px image pairs from
+the IMC 2021 PhotoTourism validation set (RTX 4090, float32), inference was about 1.3x faster with 30 % less peak GPU
+memory. Outputs change at rounding level, and coarse match selection differs only when a row of the confidence matrix
+has two exactly equal maxima.
diff --git a/kornia/feature/loftr/loftr.py b/kornia/feature/loftr/loftr.py
index b1daa8c04..5d790b230 100644
--- a/kornia/feature/loftr/loftr.py
+++ b/kornia/feature/loftr/loftr.py
@@ -200,13 +200,15 @@ class LoFTR(nn.Module):
# feat_c0 = rearrange(self.pos_encoding(feat_c0), 'n c h w -> n (h w) c')
# feat_c1 = rearrange(self.pos_encoding(feat_c1), 'n c h w -> n (h w) c')
+ # Token-major copies: the reshape of the permuted maps is a channel-strided view, and every transformer GEMM
+ # on it would run on the transposed layout.
feat_c0 = self.pos_encoding(feat_c0).permute(0, 2, 3, 1)
n, _h, _w, c = feat_c0.shape
- feat_c0 = feat_c0.reshape(n, -1, c)
+ feat_c0 = feat_c0.reshape(n, -1, c).contiguous()
feat_c1 = self.pos_encoding(feat_c1).permute(0, 2, 3, 1)
n1, _h1, _w1, c1 = feat_c1.shape
- feat_c1 = feat_c1.reshape(n1, -1, c1)
+ feat_c1 = feat_c1.reshape(n1, -1, c1).contiguous()
mask_c0 = mask_c1 = None # mask is useful in training
# a coarse cell takes the mask value of the pixel it sits on
diff --git a/kornia/feature/loftr/loftr_module/fine_preprocess.py b/kornia/feature/loftr/loftr_module/fine_preprocess.py
index bcda18c88..ee803b7f5 100644
--- a/kornia/feature/loftr/loftr_module/fine_preprocess.py
+++ b/kornia/feature/loftr/loftr_module/fine_preprocess.py
@@ -22,6 +22,23 @@ import torch.nn.functional as F
from torch import nn
+def _unfold_at(feat: torch.Tensor, b_ids: torch.Tensor, ids: torch.Tensor, window: int, stride: int) -> torch.Tensor:
+ """Windows ``ids`` of ``F.unfold(feat, window, stride=stride, padding=window // 2)``, as ``(M, window**2, C)``.
+
+ Gathers only the windows of the matched cells, with the same values and layout as unfolding the whole map and
+ indexing it; the unfolded map is ``window**2`` times larger than ``feat``.
+ """
+ pad = window // 2
+ padded = F.pad(feat, (pad, pad, pad, pad))
+ # cell ids index the unfolded grid row-major
+ w_out = (feat.shape[3] + 2 * pad - window) // stride + 1
+ offsets = torch.arange(window, device=ids.device)
+ rows = ((ids // w_out) * stride)[:, None] + offsets
+ cols = ((ids % w_out) * stride)[:, None] + offsets
+ windows = padded[b_ids[:, None, None], :, rows[:, :, None], cols[:, None, :]] # (M, window, window, C)
+ return windows.reshape(ids.shape[0], window * window, feat.shape[1])
+
+
class FinePreprocess(nn.Module):
"""Preprocess feature maps for fine-level matching in LoFTR.
@@ -83,23 +100,9 @@ class FinePreprocess(nn.Module):
feat1 = torch.empty(0, self.W**2, self.d_model_f, device=feat_f0.device)
return feat0, feat1
- # 1. unfold(crop) all local windows
- feat_f0_unfold = F.unfold(feat_f0, kernel_size=(W, W), stride=stride, padding=W // 2)
-
- # feat_f0_unfold = rearrange(feat_f0_unfold, 'n (c ww) l -> n l ww c', ww=W**2)
- n0, cww0, l0 = feat_f0_unfold.shape
- c0 = cww0 // (W * W)
- feat_f0_unfold = feat_f0_unfold.reshape(n0, c0, -1, l0).permute(0, 3, 2, 1)
-
- feat_f1_unfold = F.unfold(feat_f1, kernel_size=(W, W), stride=stride, padding=W // 2)
- # feat_f1_unfold = rearrange(feat_f1_unfold, 'n (c ww) l -> n l ww c', ww=W**2)
- n1, cww1, l1 = feat_f1_unfold.shape
- c1 = cww1 // (W * W)
- feat_f1_unfold = feat_f1_unfold.reshape(n1, c1, -1, l1).permute(0, 3, 2, 1)
-
- # 2. select only the predicted matches
- feat_f0_unfold = feat_f0_unfold[data["b_ids"], data["i_ids"]] # [n, ww, cf]
- feat_f1_unfold = feat_f1_unfold[data["b_ids"], data["j_ids"]]
+ # 1. crop the local windows of the predicted matches
+ feat_f0_unfold = _unfold_at(feat_f0, data["b_ids"], data["i_ids"], W, stride) # [n, ww, cf]
+ feat_f1_unfold = _unfold_at(feat_f1, data["b_ids"], data["j_ids"], W, stride)
# option: use coarse-level loftr feature as context: concat and linear
if self.cat_c_feat:
diff --git a/kornia/feature/loftr/loftr_module/linear_attention.py b/kornia/feature/loftr/loftr_module/linear_attention.py
index 02f99dae8..5fbab427f 100644
--- a/kornia/feature/loftr/loftr_module/linear_attention.py
+++ b/kornia/feature/loftr/loftr_module/linear_attention.py
@@ -21,7 +21,7 @@ Modified from: https://github.com/idiap/fast-
transformers/blob/master/fast_transformers/attention/linear_attention.py.
"""
-from typing import Optional
+from typing import Optional, Tuple
import torch
import torch.nn.functional as F
@@ -34,6 +34,15 @@ def elu_feature_map(x: torch.Tensor) -> torch.Tensor:
return torch.nn.functional.elu(x) + 1
+def _head_blocks(heads: int, dim: int, dim_v: int, device: torch.device) -> Tuple[torch.Tensor, torch.Tensor]:
+ """Masks of the per-head blocks: ``(H D, H V)`` block diagonal and the ``(H D, H)`` head of each channel."""
+ head_d = torch.arange(heads * dim, device=device) // dim
+ head_v = torch.arange(heads * dim_v, device=device) // dim_v
+ block = head_d[:, None] == head_v[None, :]
+ head_of = head_d[:, None] == torch.arange(heads, device=device)[None, :]
+ return block, head_of
+
+
class LinearAttention(nn.Module):
"""Implement the Linear Attention mechanism for efficient transformer processing.
@@ -81,14 +90,34 @@ 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
- denominator = torch.einsum("nlhd,nhd->nlh", Q, K.sum(dim=1)) + self.eps
+ n, length, heads, dim = Q.shape
+ dim_v = values.size(3)
+ if v_length > heads * dim:
+ # Long sequences (LoFTR's coarse level: ~10^4 tokens, 8 x 32 channels). The per-head reductions over the
+ # sequence are the diagonal blocks of dense (H D) x (H D) products, which run as single GEMMs instead of
+ # an einsum's batched GEMMs with tiny outputs; the off-diagonal blocks are zeroed, not read.
+ block, head_of = _head_blocks(heads, dim, dim_v, Q.device)
+ Q = Q.reshape(n, length, heads * dim)
+ K = K.reshape(n, v_length, heads * dim)
+ # Off-head products may overflow even when every per-head product is finite. Select their zeros:
+ # multiplying by a numeric mask would turn those unused infinities into NaNs.
+ KV = (K.transpose(1, 2) @ values.reshape(n, v_length, heads * dim_v)).masked_fill(~block, 0)
+ denominator = Q @ K.sum(dim=1)[:, :, None].masked_fill(~head_of, 0) + self.eps # (N, L, H)
+ else:
+ KV = torch.einsum("nshd,nshv->nhdv", K, values) # (S,D)' @ S,V
+ 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
+ # Normalize before restoring the sequence length: for a padded query Z=1, so Z * v_length alone can
+ # overflow float16 even though the attention output is exactly zero.
+ if v_length > heads * dim:
+ queried_values = (Q @ KV).view(n, length, heads, dim_v) * Z[..., None] * v_length
+ else:
+ # two operands: a three-operand einsum searches for a contraction path on every call
+ queried_values = torch.einsum("nlhd,nhdv->nlhv", Q, KV) * Z[..., None] * 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 90cd90460..5ae09aea9 100644
--- a/kornia/feature/loftr/utils/coarse_matching.py
+++ b/kornia/feature/loftr/utils/coarse_matching.py
@@ -75,6 +75,21 @@ def mask_border_with_padding(
m[b_idx, :, :, :, w1 - bd :] = v
+def _off_border(n: int, h: int, w: int, b: int, device: torch.device, pad_mask: Optional[torch.Tensor]) -> torch.Tensor:
+ """``(n, h * w)`` cells that :func:`mask_border` (or, with ``pad_mask``, :func:`mask_border_with_padding`) keeps."""
+ rows = torch.arange(h, device=device)[None, :, None]
+ cols = torch.arange(w, device=device)[None, None, :]
+ if pad_mask is None:
+ h_end = torch.full((n, 1, 1), h, device=device)
+ w_end = torch.full((n, 1, 1), w, device=device)
+ else:
+ # the valid extent of each sample, read from its padding mask as mask_border_with_padding does
+ h_end = pad_mask.sum(1).max(-1)[0].int().view(n, 1, 1)
+ w_end = pad_mask.sum(-1).max(-1)[0].int().view(n, 1, 1)
+ keep = (rows >= b) & (cols >= b) & (rows < h_end - b) & (cols < w_end - b) if b > 0 else rows >= 0
+ return keep.expand(n, h, w).reshape(n, h * w)
+
+
def compute_max_candidates(p_m0: torch.Tensor, p_m1: torch.Tensor) -> torch.Tensor:
"""Compute the max candidates of all pairs within a batch.
@@ -166,10 +181,27 @@ class CoarseMatching(nn.Module):
invalid = invalid_c1 if invalid is None else invalid | invalid_c1
if self.match_type == "dual_softmax":
- sim_matrix = torch.einsum("nlc,nsc->nls", feat_c0, feat_c1) / self.temperature
+ # Scale after contraction: scaling an operand can overflow float16, including when autocast converts
+ # float32 features for the einsum. In-place division avoids another similarity-sized allocation.
+ sim_matrix = torch.einsum("nlc,nsc->nls", feat_c0, feat_c1).div_(self.temperature)
if invalid is not None:
sim_matrix.masked_fill_(invalid, _masked_similarity(sim_matrix.dtype))
- conf_matrix = F.softmax(sim_matrix, 1) * F.softmax(sim_matrix, 2)
+ if sim_matrix.dtype == torch.float16:
+ # Native softmax normalizes without returning the column sum in float16, where long columns can
+ # overflow. Check the similarity dtype as autocast can produce float16 from float32 features.
+ conf_matrix = F.softmax(sim_matrix, 1) * F.softmax(sim_matrix, 2)
+ else:
+ # softmax(dim=1) as exp(sim - column max) / column sum: PyTorch's dim-1 softmax kernel is several
+ # times slower on (L, S) similarity matrices than these contiguous passes.
+ conf_matrix = F.softmax(sim_matrix, 2)
+ if sim_matrix.requires_grad:
+ col_exp = torch.exp(sim_matrix - sim_matrix.amax(dim=1, keepdim=True))
+ conf_matrix = col_exp / col_exp.sum(dim=1, keepdim=True) * conf_matrix
+ else:
+ # Without autograd, in place: two (L, S) matrices alive instead of four, which also keeps the
+ # CUDA caching allocator from re-reserving them for every new pair of image sizes.
+ col_exp = sim_matrix.sub_(sim_matrix.amax(dim=1, keepdim=True)).exp_()
+ conf_matrix.mul_(col_exp.div_(col_exp.sum(dim=1, keepdim=True)))
# Fully masked rows/columns can still receive softmax mass; masked cells are never valid matches.
if invalid is not None:
conf_matrix.masked_fill_(invalid, 0.0)
@@ -233,34 +265,28 @@ class CoarseMatching(nn.Module):
"w1c": data["hw1_c"][1],
}
_device = conf_matrix.device
- # 1. confidence thresholding. A zero confidence is never a match, even for a negative `thr`: `mconf == 0` marks
- # the training ground-truth pads below and is dropped from the keypoints, but not from `b_ids`.
- mask = conf_matrix > max(self.thr, 0.0)
+ # A cell i of image 0 and the first column j of its row maximum are a match when the confidence exceeds the
+ # threshold (a zero confidence never does, even for a negative `thr`: `mconf == 0` marks the training
+ # ground-truth pads below and is dropped from the keypoints, but not from `b_ids`), both cells are off the
+ # border, and the confidence is also the maximum of column j (mutual nearest neighbour). This is the first
+ # column satisfying all four conditions unless the row maximum is tied exactly, without materialising
+ # (N, L, S) boolean masks.
N = conf_matrix.shape[0]
- mask = mask.reshape(N, axes_lengths["h0c"], axes_lengths["w0c"], axes_lengths["h1c"], axes_lengths["w1c"])
- # mask = rearrange(mask, 'b (h0c w0c) (h1c w1c) -> b h0c w0c h1c w1c',
- # **axes_lengths)
- if "mask0" not in data:
- mask_border(mask, self.border_rm, False)
- else:
- mask_border_with_padding(mask, self.border_rm, False, data["mask0"], data["mask1"])
- mask = mask.reshape(N, axes_lengths["h0c"] * axes_lengths["w0c"], axes_lengths["h1c"] * axes_lengths["w1c"])
- # rearrange(mask, 'b h0c w0c h1c w1c -> b (h0c w0c) (h1c w1c)',
- # **axes_lengths)
-
- # 2. mutual nearest
- mask = (
- mask
- * (conf_matrix == conf_matrix.max(dim=2, keepdim=True)[0])
- * (conf_matrix == conf_matrix.max(dim=1, keepdim=True)[0])
+ mconf_rows, all_j_ids = conf_matrix.max(dim=2)
+ col_max = conf_matrix.amax(dim=1)
+ # mask_border_with_padding (both padding masks) when the data carries mask0, mask_border otherwise
+ pad0, pad1 = (data["mask0"], data["mask1"]) if "mask0" in data else (None, None)
+ border0 = _off_border(N, axes_lengths["h0c"], axes_lengths["w0c"], self.border_rm, _device, pad0)
+ border1 = _off_border(N, axes_lengths["h1c"], axes_lengths["w1c"], self.border_rm, _device, pad1)
+ mask_v = (
+ (mconf_rows > max(self.thr, 0.0))
+ & (torch.gather(col_max, 1, all_j_ids) == mconf_rows)
+ & border0
+ & torch.gather(border1, 1, all_j_ids)
)
-
- # 3. find all valid coarse matches
- # this only works when at most one `True` in each row
- mask_v, all_j_ids = mask.max(dim=2)
b_ids, i_ids = torch.where(mask_v)
j_ids = all_j_ids[b_ids, i_ids]
- mconf = conf_matrix[b_ids, i_ids, j_ids]
+ mconf = mconf_rows[b_ids, i_ids]
# 4. Random sampling of training samples for fine-level LoFTR
# (optional) F.pad samples with gt coarse-level matches
@@ -269,7 +295,7 @@ class CoarseMatching(nn.Module):
# The sampling is performed across all pairs in a batch without manually balancing
# #samples for fine-level increases w.r.t. batch_size
if "mask0" not in data:
- num_candidates_max = mask.size(0) * max(mask.size(1), mask.size(2))
+ num_candidates_max = conf_matrix.size(0) * max(conf_matrix.size(1), conf_matrix.size(2))
else:
num_candidates_max = compute_max_candidates(data["mask0"], data["mask1"])
num_matches_train = num_candidates_max * self.train_coarse_percent
diff --git a/tests/feature/test_loftr.py b/tests/feature/test_loftr.py
index 68e455846..5e305df4e 100644
--- a/tests/feature/test_loftr.py
+++ b/tests/feature/test_loftr.py
@@ -589,6 +589,161 @@ class TestCoarseMatching(BaseTester):
self.assert_close(out["mkpts1_c"], expected1, rtol=0.0, atol=0.0)
+class TestCoarseMatchingSelection(BaseTester):
+ """The row max / column max selection and the dual softmax against their reference formulations."""
+
+ CFG = {**TestCoarseMatching.CFG, "train_pad_num_gt_min": 200}
+
+ @staticmethod
+ def _reference_selection(cm, conf_matrix, data):
+ """The boolean-mask selection of get_coarse_match before the row max / column max rewrite (eval mode)."""
+ from kornia.feature.loftr.utils.coarse_matching import mask_border, mask_border_with_padding
+
+ (h0, w0), (h1, w1), n = data["hw0_c"], data["hw1_c"], conf_matrix.shape[0]
+ mask = (conf_matrix > max(cm.thr, 0.0)).reshape(n, h0, w0, h1, w1)
+ if "mask0" not in data:
+ mask_border(mask, cm.border_rm, False)
+ else:
+ mask_border_with_padding(mask, cm.border_rm, False, data["mask0"], data["mask1"])
+ mask = mask.reshape(n, h0 * w0, h1 * w1)
+ mask = (
+ mask
+ * (conf_matrix == conf_matrix.max(dim=2, keepdim=True)[0])
+ * (conf_matrix == conf_matrix.max(dim=1, keepdim=True)[0])
+ )
+ mask_v, all_j_ids = mask.max(dim=2)
+ b_ids, i_ids = torch.where(mask_v)
+ j_ids = all_j_ids[b_ids, i_ids]
+ return b_ids, i_ids, j_ids, conf_matrix[b_ids, i_ids, j_ids]
+
+ @staticmethod
+ def _features(device, dtype, n, length, size, channels=16, seed=0, scale=4.0):
+ # image-1 cells are noisy copies of image-0 cells, so most rows have a clear, untied mutual maximum
+ gen = torch.Generator().manual_seed(seed)
+ feat_c1 = torch.randn(n, size, channels, generator=gen) * scale
+ rows = torch.randint(0, size, (n, length), generator=gen)
+ feat_c0 = torch.gather(feat_c1, 1, rows[..., None].expand(-1, -1, channels))
+ feat_c0 = feat_c0 + torch.randn(n, length, channels, generator=gen) * (scale / 2)
+ return feat_c0.to(device, dtype), feat_c1.to(device, dtype)
+
+ @pytest.mark.parametrize("thr", [0.0, 0.2])
+ @pytest.mark.parametrize("border_rm", [0, 1, 2])
+ @pytest.mark.parametrize("padded", [False, True])
+ def test_selection_matches_the_boolean_mask_reference(self, device, dtype, thr, border_rm, padded):
+ cm = CoarseMatching({**self.CFG, "thr": thr, "border_rm": border_rm}).to(device).eval()
+ (h0, w0), (h1, w1) = (10, 12), (11, 9)
+ feat_c0, feat_c1 = self._features(device, dtype, 2, h0 * w0, h1 * w1)
+ data = {"hw0_c": (h0, w0), "hw1_c": (h1, w1), "stride_c": 8}
+ if padded:
+ # per-sample valid extents, as mask_border_with_padding reads them
+ mask0 = torch.zeros(2, h0, w0, device=device)
+ mask1 = torch.zeros(2, h1, w1, device=device)
+ mask0[0, :9, :10], mask0[1] = 1, 1
+ mask1[0], mask1[1, :10, :8] = 1, 1
+ data.update(mask0=mask0, mask1=mask1)
+ with torch.no_grad():
+ cm(feat_c0, feat_c1, data)
+ expected = self._reference_selection(cm, data["conf_matrix"], data)
+ assert len(expected[0]) >= 5 # border 2 on the padded samples leaves 10
+ for name, value in zip(("b_ids", "i_ids", "j_ids", "mconf"), expected):
+ self.assert_close(data[name], value, rtol=0.0, atol=0.0)
+
+ @pytest.mark.parametrize("requires_grad", [False, True])
+ @pytest.mark.parametrize("masked", [False, True])
+ def test_dual_softmax_is_the_product_of_both_softmaxes(self, device, dtype, requires_grad, masked):
+ # Without autograd the confidence is computed in place, with it out of place; both are the product of the
+ # softmaxes over either dim of the masked similarity matrix, here against that product in float64.
+ cm = CoarseMatching(self.CFG).to(device).eval()
+ feat_c0, feat_c1 = self._features(device, dtype, 2, 30, 24, scale=1.0)
+ feat_c0.requires_grad_(requires_grad)
+ mask_c0 = mask_c1 = None
+ if masked:
+ mask_c0 = torch.ones(2, 30, device=device)
+ mask_c1 = torch.ones(2, 24, device=device)
+ mask_c0[0, 25:], mask_c1[1, :4] = 0, 0
+ data = {"hw0_c": (5, 6), "hw1_c": (4, 6), "stride_c": 8}
+ # Keep the high-precision reference on CPU: MPS cannot hold float64 tensors.
+ reference_c0 = feat_c0.detach().cpu().double().requires_grad_(requires_grad)
+ with torch.set_grad_enabled(requires_grad):
+ cm(feat_c0, feat_c1, data, mask_c0=mask_c0, mask_c1=mask_c1)
+ c = feat_c0.shape[-1] ** 0.5
+ sim = torch.einsum("nlc,nsc->nls", reference_c0 / c, feat_c1.cpu().double() / c)
+ sim = sim / self.CFG["dsmax_temperature"]
+ invalid = None
+ if masked:
+ invalid = ~mask_c0.cpu().bool()[..., None] | ~mask_c1.cpu().bool()[:, None]
+ sim = sim.masked_fill(invalid, -1e9)
+ expected = F.softmax(sim, 1) * F.softmax(sim, 2)
+ if masked:
+ expected = expected.masked_fill(invalid, 0.0)
+ # confidences are in [0, 1]: absolute tolerances of the input precision
+ tol = {torch.float16: 5e-3, torch.bfloat16: 3e-2, torch.float32: 1e-5, torch.float64: 1e-10}[dtype]
+ self.assert_close(data["conf_matrix"].cpu().double(), expected, rtol=0.0, atol=tol)
+ if requires_grad:
+ (grad,) = torch.autograd.grad((data["conf_matrix"] ** 2).sum(), feat_c0)
+ (grad_expected,) = torch.autograd.grad((expected**2).sum(), reference_c0)
+ self.assert_close(grad.cpu().double(), grad_expected, rtol=0.0, atol=50 * tol)
+
+ @pytest.mark.parametrize("requires_grad", [False, True])
+ def test_temperature_scaling_keeps_finite_dot_products(self, device, dtype, requires_grad):
+ # Scaling the second feature first overflows fp16, although every similarity is finite.
+ cm = CoarseMatching({**self.CFG, "border_rm": 0}).to(device).eval()
+ feat0 = torch.zeros(1, 1, 1, device=device, dtype=dtype, requires_grad=requires_grad)
+ feat1 = torch.full((1, 1, 1), 10000.0, device=device, dtype=dtype, requires_grad=requires_grad)
+ data = {"hw0_c": (1, 1), "hw1_c": (1, 1), "stride_c": 8}
+ cm(feat0, feat1, data)
+ self.assert_close(data["conf_matrix"], torch.ones_like(data["conf_matrix"]), rtol=0.0, atol=0.0)
+ if requires_grad:
+ for grad in torch.autograd.grad(data["conf_matrix"].sum(), (feat0, feat1)):
+ self.assert_close(grad, torch.zeros_like(grad), rtol=0.0, atol=0.0)
+
+ @pytest.mark.parametrize("requires_grad", [False, True])
+ def test_long_column_softmax_stays_normalized(self, device, dtype, requires_grad):
+ # The sum of 65536 exponentials equal to one cannot be represented in fp16.
+ length = 65536
+ cm = CoarseMatching(self.CFG).to(device).eval()
+ feat0 = torch.zeros(1, length, 1, device=device, dtype=dtype, requires_grad=requires_grad)
+ feat1 = torch.ones(1, 1, 1, device=device, dtype=dtype)
+ data = {"hw0_c": (256, 256), "hw1_c": (1, 1), "stride_c": 8}
+ cm(feat0, feat1, data)
+ expected = torch.full_like(data["conf_matrix"], 1.0 / length)
+ self.assert_close(data["conf_matrix"], expected, rtol=0.0, atol=0.0)
+ if requires_grad:
+ (grad,) = torch.autograd.grad(data["conf_matrix"][0, 0, 0], feat0)
+ assert bool(torch.isfinite(grad).all())
+ # The selected probability has a positive derivative; the other logits have negative derivatives.
+ reference = torch.zeros_like(feat0, device="cpu", dtype=torch.float64, requires_grad=True)
+ prob = (reference / self.CFG["dsmax_temperature"]).softmax(1)[0, 0, 0]
+ (grad_expected,) = torch.autograd.grad(prob, reference)
+ self.assert_close(grad, grad_expected.to(device=device, dtype=dtype), rtol=1e-2, atol=1e-7)
+
+ def test_long_column_softmax_autocast(self, device):
+ if device.type not in ("cpu", "cuda"):
+ pytest.skip("float16 autocast regression runs on CPU and CUDA")
+ # Float32 features can still produce float16 similarities under autocast.
+ cm = CoarseMatching(self.CFG).to(device).eval()
+ feat0 = torch.zeros(1, 65536, 2, device=device, dtype=torch.float32)
+ feat1 = torch.zeros(1, 1, 2, device=device, dtype=torch.float32)
+ data = {"hw0_c": (256, 256), "hw1_c": (1, 1), "stride_c": 8}
+ with torch.autocast(device.type, dtype=torch.float16):
+ cm(feat0, feat1, data)
+ expected = torch.full((1, 65536, 1), 1 / 65536, device=device, dtype=torch.float16)
+ self.assert_close(data["conf_matrix"], expected, rtol=0.0, atol=0.0)
+
+ def test_temperature_scaling_autocast(self, device):
+ if device.type not in ("cpu", "cuda"):
+ pytest.skip("float16 autocast regression runs on CPU and CUDA")
+ cm = CoarseMatching(self.CFG).to(device).eval()
+ feat0 = torch.zeros(1, 1, 2, device=device, dtype=torch.float32, requires_grad=True)
+ feat1 = torch.full((1, 1, 2), 10000.0, device=device, dtype=torch.float32, requires_grad=True)
+ data = {"hw0_c": (1, 1), "hw1_c": (1, 1), "stride_c": 8}
+ with torch.autocast(device.type, dtype=torch.float16):
+ cm(feat0, feat1, data)
+ self.assert_close(data["conf_matrix"], torch.ones(1, 1, 1, device=device, dtype=torch.float16))
+ for grad in torch.autograd.grad(data["conf_matrix"].sum(), (feat0, feat1)):
+ self.assert_close(grad, torch.zeros_like(grad), rtol=0.0, atol=0.0)
+
+
class TestFineMatching(BaseTester):
@staticmethod
def _run(device, dtype, peaked):
@@ -712,6 +867,36 @@ class TestFinePreprocess(BaseTester):
# 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)
+ @pytest.mark.parametrize("fine_hw", [((50, 34), (47, 43)), ((33, 37), (29, 41))])
+ def test_gathered_windows_equal_the_unfolded_ones(self, device, dtype, fine_hw):
+ # FinePreprocess cuts only the windows of the matched cells; they must be exactly the windows of
+ # F.unfold(feat, 5, stride=4, padding=2) indexed by the cell ids, for both images of a batch of two.
+ cfg = {
+ "fine_concat_coarse_feat": False,
+ "fine_window_size": 5,
+ "coarse": {"d_model": 4},
+ "fine": {"d_model": 3},
+ }
+ gen = torch.Generator().manual_seed(0)
+ (hf0, wf0), (hf1, wf1) = fine_hw
+ feat_f0 = torch.randn(2, 3, hf0, wf0, generator=gen).to(device, dtype)
+ feat_f1 = torch.randn(2, 3, hf1, wf1, generator=gen).to(device, dtype)
+
+ def unfolded(feat):
+ out = F.unfold(feat, kernel_size=(5, 5), stride=4, padding=2)
+ return out.reshape(out.shape[0], feat.shape[1], 25, -1).permute(0, 3, 2, 1)
+
+ ref0, ref1 = unfolded(feat_f0), unfolded(feat_f1)
+ b_ids = torch.tensor([0, 1, 1, 0, 1], device=device)
+ i_ids = torch.tensor([0, 5, ref0.shape[1] - 1, 17, 30], device=device)
+ j_ids = torch.tensor([ref1.shape[1] - 1, 0, 9, 41, 2], device=device)
+ data = {"stride_c": 8, "stride_f": 2, "b_ids": b_ids, "i_ids": i_ids, "j_ids": j_ids}
+ feat_c = torch.zeros(2, 1, 4, device=device, dtype=dtype)
+ with torch.no_grad():
+ win0, win1 = FinePreprocess(cfg).to(device, dtype)(feat_f0, feat_f1, feat_c, feat_c, data)
+ self.assert_close(win0, ref0[b_ids, i_ids], rtol=0.0, atol=0.0)
+ self.assert_close(win1, ref1[b_ids, j_ids], rtol=0.0, atol=0.0)
+
class TestResNetFPN(BaseTester):
def test_fpn_upsamples_by_2_then_crops_5728(self, device, dtype):
@@ -750,13 +935,14 @@ class TestResNetFPN(BaseTester):
class TestLinearAttention(BaseTester):
@pytest.mark.parametrize("dtype", [torch.float32, torch.float16, torch.bfloat16])
- def test_padded_queries_stay_finite_5728(self, device, dtype):
+ @pytest.mark.parametrize("kv_len", [5, 40]) # 40 > heads * dim = 8: the dense block-diagonal GEMM path
+ def test_padded_queries_stay_finite_5728(self, device, dtype, kv_len):
# 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, k, v = (torch.randn(1, n, 2, 4, generator=gen) for n in (6, kv_len, kv_len))
+ q_mask, kv_mask = torch.ones(1, 6), torch.ones(1, kv_len)
q_mask[0, [1, 4]], kv_mask[0, 2] = 0, 0
def attend(dt):
@@ -775,6 +961,82 @@ class TestLinearAttention(BaseTester):
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)
+ @staticmethod
+ def _reference(queries, keys, values, q_mask=None, kv_mask=None, eps=1e-6):
+ """LinearAttention's per-head einsum formulation."""
+ Q, K = F.elu(queries) + 1, F.elu(keys) + 1
+ if q_mask is not None:
+ Q = Q * q_mask[:, :, None, None]
+ if kv_mask is not None:
+ K = K * kv_mask[:, :, None, None]
+ values = values * kv_mask[:, :, None, None]
+ KV = torch.einsum("nshd,nshv->nhdv", K, values)
+ denominator = torch.einsum("nlhd,nhd->nlh", Q, K.sum(dim=1)) + eps
+ if q_mask is not None:
+ denominator = torch.where(q_mask[:, :, None] > 0, denominator, torch.ones_like(denominator))
+ return torch.einsum("nlhd,nhdv,nlh->nlhv", Q, KV, 1 / denominator)
+
+ @pytest.mark.parametrize("kv_len", [5, 40])
+ @pytest.mark.parametrize("masked", [False, True])
+ @pytest.mark.parametrize("dim_v", [4, 3])
+ def test_matches_the_per_head_einsums(self, device, dtype, kv_len, masked, dim_v):
+ # Sequences longer than heads * dim run as dense GEMMs over the per-head blocks; both paths compute the
+ # per-head linear attention, also when the values are narrower than the queries and keys.
+ gen = torch.Generator().manual_seed(1)
+ q, k = (torch.randn(2, n, 2, 4, generator=gen).to(device, dtype) for n in (7, kv_len))
+ v = torch.randn(2, kv_len, 2, dim_v, generator=gen).to(device, dtype)
+ q_mask = kv_mask = None
+ if masked:
+ q_mask = torch.ones(2, 7, dtype=dtype, device=device)
+ kv_mask = torch.ones(2, kv_len, dtype=dtype, device=device)
+ q_mask[1, 3], kv_mask[0, 1:3] = 0, 0
+ out = LinearAttention()(q, k, v, q_mask, kv_mask)
+ q_ref, k_ref, v_ref = (x.cpu().double() for x in (q, k, v))
+ qm_ref, km_ref = (None if x is None else x.cpu().double() for x in (q_mask, kv_mask))
+ expected = self._reference(q_ref, k_ref, v_ref, qm_ref, km_ref)
+ if dtype == torch.float64:
+ self.assert_close(out, expected.to(device), rtol=1e-10, atol=1e-12)
+ else:
+ self.assert_close(out, expected.to(device=device, dtype=dtype))
+
+ def test_off_head_overflow_does_not_contaminate_attention(self, device, dtype):
+ q = torch.zeros(1, 1, 2, 1, device=device, dtype=dtype, requires_grad=True)
+ k = torch.tensor([1.0, -math.log(10.0)], device=device, dtype=dtype).view(1, 1, 2, 1)
+ k = k.repeat(1, 3, 1, 1).requires_grad_()
+ v = torch.tensor([0.0, 40000.0], device=device, dtype=dtype).view(1, 1, 2, 1)
+ v = v.repeat(1, 3, 1, 1).requires_grad_()
+ out = LinearAttention()(q, k, v)
+ refs = tuple(x.detach().cpu().double().requires_grad_() for x in (q, k, v))
+ expected = self._reference(*refs)
+ self.assert_close(out, expected.to(device=device, dtype=dtype))
+ grads = torch.autograd.grad((out / 40000).sum(), (q, k, v))
+ refs_grad = torch.autograd.grad((expected / 40000).sum(), refs)
+ for grad, ref in zip(grads, refs_grad):
+ assert bool(torch.isfinite(grad).all())
+ self.assert_close(grad, ref.to(device=device, dtype=dtype))
+
+ def test_long_padded_query_stays_zero(self, device, dtype):
+ # With Z=1 for a padded query, forming Z * length first overflows fp16.
+ q = torch.zeros(1, 1, 1, 1, device=device, dtype=dtype)
+ k = torch.zeros(1, 65536, 1, 1, device=device, dtype=dtype)
+ v = torch.zeros_like(k)
+ q_mask = torch.zeros(1, 1, device=device, dtype=torch.bool)
+ out = LinearAttention()(q, k, v, q_mask=q_mask)
+ self.assert_close(out, torch.zeros_like(out), rtol=0.0, atol=0.0)
+
+ def test_gradcheck_long_sequence(self, device):
+ gen = torch.Generator().manual_seed(2)
+ q, k, v = (torch.randn(1, n, 2, 4, generator=gen, dtype=torch.float64).to(device) for n in (6, 20, 20))
+ self.gradcheck(LinearAttention(), (q, k, v), requires_grad=(True, True, True))
+
+ @pytest.mark.parametrize("kv_len", [5, 40])
+ def test_dynamo(self, device, dtype, torch_optimizer, kv_len):
+ q, k, v = (torch.rand(1, n, 2, 4, device=device, dtype=dtype) for n in (6, kv_len, kv_len))
+ q_mask = torch.ones(1, 6, device=device, dtype=torch.bool)
+ q_mask[:, 0] = False
+ op = LinearAttention()
+ self.assert_close(torch_optimizer(op)(q, k, v, q_mask), op(q, k, v, q_mask))
+
class TestConventionsLoFTR(BaseTester):
# Per batch item: a coarse cell (row, column) of image 0 (59 x 85 pixels, 8 x 11 coarse cells), its partner in