Algorithm Search⌘K

Algorithmresearch

SuperGlue

Also called graph neural network feature matching.

Match two sets of keypoints with attention between and within the sets, then solve a partial assignment with a dustbin by Sinkhorn iterations.

Time
O(T M N) worst · average · best
Space
O(M N) extra
Where
M = the number of keypoints in image A; N = the number of keypoints in image B; T = the number of Sinkhorn iterations
Properties
deterministiclearnednetwork cost excludedpartial assignmentsymmetric
Origin
Paul Edouard Sarlin, Daniel DeTone, Tomasz Malisiewicz, Andrew Rabinovich, 2020

SuperGlue is a learned matcher for two sets of keypoints. A graph neural network takes the positions, scores and descriptors of the keypoints of both images, mixes them with attention inside each image and across the two images, and gives a score SijS_{ij} for each pair. An optimal matching layer then adds a "dustbin" row and column for points without a partner, and turns the scores into a soft partial assignment with Sinkhorn iterations. Pairs that are mutual best choices with a high enough value are the matches. This page covers the optimal matching layer, with its proof and code; the network and its training are outside the page, and the quality of its scores is a measured result.

In plain words

Each image has its own keypoints. A network looks at all of them together and gives each pair, one point from each image, a score that says how well they fit. Some points have no partner, because they are hidden or out of view in the other image. So we add an extra "nobody" slot on each side with a fixed score. Then we spread one unit of match per point over the partners and the "nobody" slot, and adjust the spread again and again until each point gives out exactly one unit and each slot takes exactly what it should. A pair is a match when each point puts most of its unit on the other, and the amount is above a threshold.

The problem

The input is the output of the network:

  • a score matrix SS with MM rows, the keypoints of image A, and NN columns, the keypoints of image B;
  • the dustbin score zz, a single learned number;
  • the number of iterations TT and a match threshold θ\theta.

The output is a soft assignment PP of size (M+1)×(N+1)(M + 1) \times (N + 1) and a list of matches (i,j)(i, j) with i<Mi < M and j<Nj < N, where each ii and each jj appears at most once.

The soft assignment solves an entropic optimal transport problem. Row i<Mi < M of PP must sum to 1 (keypoint ii is matched once, maybe to the dustbin), and the dustbin row must sum to NN (it can take all points of B); the same holds for columns with the dustbin column summing to MM. Among these plans, PP maximizes ⟨Sˉ,P⟩+H(P)\langle \bar S, P \rangle + H(P), where Sˉ\bar S is SS with the dustbin row and column added and HH is an entropy term.

The algorithm

  1. SUPERGLUE-MATCHING-LAYER(S, z, T, θ)
  2. 1S̄ ← S with a column and then a row of value z added at the end ▷ (M + 1) × (N + 1)
  3. 2a ← (1, …, 1, N) of length M + 1; b ← (1, …, 1, M) of length N + 1
  4. 3u ← 0; v ← 0
  5. 4repeat T times
  6. 5for each row i: u_i ← log a_i - log Σ_j exp(S̄_ij + v_j)
  7. 6for each column j: v_j ← log b_j - log Σ_i exp(S̄_ij + u_i)
  8. 7P_ij ← exp(S̄_ij + u_i + v_j) for all i, j
  9. 8for each real row i, c(i) ← the real column with the largest P_ij; for each real column j, r(j) ← the real row with the largest P_ij
  10. 9return P and the pairs (i, c(i)) with r(c(i)) = i and P_{i c(i)} > θ

Lines L5 and L6 are the Sinkhorn iterations in the log domain. Each line scales the rows or the columns of exp⁡(Sˉ)\exp(\bar S) so that their sums are right; the log-sum-exp form (see the log-sum-exp trick) keeps large scores from overflowing. Line L8 looks only at the real block, not at the dustbins, as the released code does. Ties go to the smaller index.

The network before this layer, from Section 3.1 of the paper: a keypoint encoder adds an embedding of the position and detection score of each point to its descriptor. Then LL layers alternate self-attention, between the points of one image, and cross-attention, between the points of the two images. The final vectors fiAf^A_i and fjBf^B_j give Sij=⟨fiA,fjB⟩S_{ij} = \langle f^A_i, f^B_j \rangle. The dustbin score zz is a learned parameter. Training minimizes the negative log of PP at the ground-truth matches and at the dustbin entries of the unmatched points (Section 3.3), so the network learns the scale of its own scores.

Example

Take M=N=2M = N = 2, S=(3000.2)S = \begin{pmatrix} 3 & 0 \\ 0 & 0.2 \end{pmatrix} and z=1z = 1. Line L1 gives

Sˉ=(30100.21111),a=b=(1,1,2).\bar S = \begin{pmatrix} 3 & 0 & 1 \\ 0 & 0.2 & 1 \\ 1 & 1 & 1 \end{pmatrix}, \quad a = b = (1, 1, 2).

After one pass of lines L5 and L6, the column sums of PP are exactly (1,1,2)(1, 1, 2), but the row sums are (0.7081,1.2036,2.0882)(0.7081, 1.2036, 2.0882). After T=100T = 100 passes both are right to 4 digits:

P=(0.63160.07550.29290.07550.22130.70320.29290.70321.0039).P = \begin{pmatrix} 0.6316 & 0.0755 & 0.2929 \\ 0.0755 & 0.2213 & 0.7032 \\ 0.2929 & 0.7032 & 1.0039 \end{pmatrix}.

Row 0 picks column 0 and row 1 picks column 1, and each is picked back. With θ=0.2\theta = 0.2 both pairs are matches, (0,0)(0, 0) with 0.6316 and (1,1)(1, 1) with 0.2213.

Now multiply SS and zz by 4. The plan becomes sharper: P00=0.9814P_{00} = 0.9814, P11=0.0371P_{11} = 0.0371 and P1,dustbin=0.9626P_{1,\text{dustbin}} = 0.9626. Only (0,0)(0, 0) is a match. This is the answer of the limit problem: the weights Sij−zS_{ij} - z are 22, −1-1, −1-1 and −0.8-0.8, and the best partial matching keeps only the pair of positive weight. Pair (1,1)(1, 1) is a mutual best pair, so mutual nearest neighbor matching would keep it; the dustbin is what rejects it.

Correctness

The layer has a proof; the network does not. The proof in proofs/correctness.md shows:

  • Exact columns. After each pass the column sums of PP equal bb exactly. The row sums tend to aa as the iterations converge; convergence for a positive matrix is Sinkhorn's theorem, which we cite.
  • The fixed point is the entropic optimum. A converged PP is the unique maximizer of ⟨Sˉ,P⟩+H(P)\langle \bar S, P \rangle + H(P) over the plans with marginals aa and bb, with H(P)=−∑Pij(log⁡Pij−1)H(P) = -\sum P_{ij}(\log P_{ij} - 1).
  • The limit is a partial matching. For every plan, ⟨Sˉ,P⟩=∑(Sij−z)Qij+z(M+N)\langle \bar S, P \rangle = \sum (S_{ij} - z) Q_{ij} + z (M + N), where QQ is the real block, and the real blocks are exactly the doubly substochastic matrices. So the linear problem is a maximum weight partial matching with weights Sij−zS_{ij} - z. With scores scaled by β\beta, the value of the entropic plan is within O(1/β)O(1/\beta) of it.
  • The output is a matching. Each keypoint is in at most one listed pair.

What this does not show is that the scores are good. The paper measures it: it reports pose accuracy on indoor image pairs from ScanNet and on outdoor pairs from YFCC100M, and homography accuracy on synthetic warps (2020), with SuperPoint and SIFT features, against nearest neighbor matching with the ratio test or mutual checks and against learned outlier filters. These are benchmark results with the protocol of the paper.

Proof: Correctness of the SuperGlue optimal matching layerfull

This proof covers the optimal matching layer only: lines L1 to L9 of the main page, on a given score matrix S∈RM×NS \in \mathbb{R}^{M \times N}, with M,N≥1M, N \ge 1, and a given dustbin score zz. Nothing here says that the network gives good scores; that is a measured property.

Line L1 builds Sˉ\bar S of size (M+1)×(N+1)(M + 1) \times (N + 1): Sˉij=Sij\bar S_{ij} = S_{ij} for i<Mi < M and j<Nj < N, and Sˉij=z\bar S_{ij} = z in the last row and the last column. Line L2 sets a=(1,…,1,N)a = (1, \dots, 1, N) of length M+1M + 1 and b=(1,…,1,M)b = (1, \dots, 1, M) of length N+1N + 1. Write 1\mathbf{1} for a vector of ones, and

U(a,b)={P∈R≥0(M+1)×(N+1):P1=a,  PT1=b}.U(a, b) = \{ P \in \mathbb{R}_{\ge 0}^{(M+1) \times (N+1)} : P \mathbf{1} = a, \; P^T \mathbf{1} = b \}.

For P≥0P \ge 0 let H(P)=−∑ijPij(log⁡Pij−1)H(P) = -\sum_{ij} P_{ij} (\log P_{ij} - 1), with 0log⁡0=00 \log 0 = 0, and F(P)=⟨Sˉ,P⟩+H(P)F(P) = \langle \bar S, P \rangle + H(P), where ⟨X,Y⟩=∑ijXijYij\langle X, Y \rangle = \sum_{ij} X_{ij} Y_{ij}.

Lemma 1 (exact columns). After each pass of lines L5 and L6, the matrix Pij=exp⁡(Sˉij+ui+vj)P_{ij} = \exp(\bar S_{ij} + u_i + v_j) has column sums exactly bb.

Proof. Line L6 sets vj=log⁡bj−log⁡∑iexp⁡(Sˉij+ui)v_j = \log b_j - \log \sum_i \exp(\bar S_{ij} + u_i). Then ∑iPij=evj∑iexp⁡(Sˉij+ui)=bj\sum_i P_{ij} = e^{v_j} \sum_i \exp(\bar S_{ij} + u_i) = b_j. The log-sum-exp of the code subtracts the maximum before the exponentials, which changes no value in exact arithmetic. □\square

Lemma 2 (the target is feasible). ∑iai=∑jbj=M+N\sum_i a_i = \sum_j b_j = M + N, and U(a,b)U(a, b) is a non-empty compact set.

Proof. ∑iai=M⋅1+N\sum_i a_i = M \cdot 1 + N and ∑jbj=N⋅1+M\sum_j b_j = N \cdot 1 + M. The matrix Pij=aibj/(M+N)P_{ij} = a_i b_j / (M + N) is in U(a,b)U(a, b). The set is closed and each entry is at most M+NM + N, so it is compact. □\square

Lemma 3 (a fixed point is the entropic optimum). Suppose Pij=exp⁡(Sˉij+ui+vj)P_{ij} = \exp(\bar S_{ij} + u_i + v_j) for some vectors u,vu, v, and P∈U(a,b)P \in U(a, b). Then PP is the unique maximizer of FF over U(a,b)U(a, b).

Proof. Each term sp−plog⁡p+ps p - p \log p + p is concave in p≥0p \ge 0 and strictly concave, so FF is strictly concave on the non-negative orthant. All entries of PP are positive, so FF is differentiable at PP, with

∂F∂Pij=Sˉij−log⁡Pij=−ui−vj.\frac{\partial F}{\partial P_{ij}} = \bar S_{ij} - \log P_{ij} = -u_i - v_j.

Take Q∈U(a,b)Q \in U(a, b). The function t↦F(P+t(Q−P))t \mapsto F(P + t (Q - P)) is concave on [0,1][0, 1] and differentiable at 00, so

F(Q)≤F(P)+∑ij(−ui−vj)(Qij−Pij)=F(P)−∑iui(ai−ai)−∑jvj(bj−bj)=F(P).F(Q) \le F(P) + \sum_{ij} (-u_i - v_j)(Q_{ij} - P_{ij}) = F(P) - \sum_i u_i (a_i - a_i) - \sum_j v_j (b_j - b_j) = F(P).

If F(Q)=F(P)F(Q) = F(P) with Q≠PQ \ne P, strict concavity gives F((P+Q)/2)>F(P)F((P + Q)/2) > F(P), and (P+Q)/2(P + Q)/2 is in the convex set U(a,b)U(a, b), which contradicts the first part. □\square

For a matrix exp⁡(Sˉ)\exp(\bar S) with positive entries and positive marginals of equal sum, the alternating scaling of lines L5 and L6 converges to a matrix of the form in Lemma 3. This is Sinkhorn's theorem on matrix scaling, which Sinkhorn and Knopp proved for doubly stochastic targets; we use it and do not prove it here. Lemma 1 holds after every pass, and the row sums tend to aa.

Lemma 4 (temperature). Let β>0\beta > 0 and let PβP_\beta be the maximizer of ⟨βSˉ,P⟩+H(P)\langle \beta \bar S, P \rangle + H(P) over U(a,b)U(a, b), which is the limit of the algorithm on the input βS\beta S and βz\beta z. Then for every Q∈U(a,b)Q \in U(a, b),

⟨Sˉ,Q⟩−⟨Sˉ,Pβ⟩≤H(Pβ)−H(Q)β,\langle \bar S, Q \rangle - \langle \bar S, P_\beta \rangle \le \frac{H(P_\beta) - H(Q)}{\beta},

and the right side tends to 0 as β→∞\beta \to \infty.

Proof. PβP_\beta also maximizes ⟨Sˉ,P⟩+H(P)/β\langle \bar S, P \rangle + H(P)/\beta, so ⟨Sˉ,Pβ⟩+H(Pβ)/β≥⟨Sˉ,Q⟩+H(Q)/β\langle \bar S, P_\beta \rangle + H(P_\beta)/\beta \ge \langle \bar S, Q \rangle + H(Q)/\beta. Rearrange. HH is continuous on the compact set U(a,b)U(a, b) of Lemma 2, so H(Pβ)−H(Q)H(P_\beta) - H(Q) is bounded by max⁡UH−min⁡UH\max_U H - \min_U H. □\square

Lemma 5 (the limit problem is a partial matching). For P∈U(a,b)P \in U(a, b) let QQ be its real block, Qij=PijQ_{ij} = P_{ij} for i<Mi < M and j<Nj < N. Then

⟨Sˉ,P⟩=∑i<M,j<N(Sij−z)Qij+z(M+N),\langle \bar S, P \rangle = \sum_{i < M, j < N} (S_{ij} - z) Q_{ij} + z (M + N),

QQ is doubly substochastic (non-negative, with row and column sums at most 1), and each doubly substochastic M×NM \times N matrix is the real block of exactly one P∈U(a,b)P \in U(a, b). So max⁡U(a,b)⟨Sˉ,P⟩−z(M+N)\max_{U(a,b)} \langle \bar S, P \rangle - z(M + N) is the maximum weight of a partial matching between rows and columns with edge weights Sij−zS_{ij} - z.

Proof. Let σ=∑ijQij\sigma = \sum_{ij} Q_{ij}. For i<Mi < M, row ii of PP sums to 1, so PiN=1−∑jQij≥0P_{iN} = 1 - \sum_j Q_{ij} \ge 0. For j<Nj < N, column jj sums to 1, so PMj=1−∑iQij≥0P_{Mj} = 1 - \sum_i Q_{ij} \ge 0. Row MM sums to NN, so PMN=N−∑j<NPMj=N−(N−σ)=σP_{MN} = N - \sum_{j < N} P_{Mj} = N - (N - \sigma) = \sigma; column NN then sums to (M−σ)+σ=M(M - \sigma) + \sigma = M, as needed. So PP is determined by QQ, any doubly substochastic QQ gives a P≥0P \ge 0 in U(a,b)U(a, b), and

⟨Sˉ,P⟩=∑SijQij+z(M−σ)+z(N−σ)+zσ=∑(Sij−z)Qij+z(M+N).\langle \bar S, P \rangle = \sum S_{ij} Q_{ij} + z (M - \sigma) + z (N - \sigma) + z \sigma = \sum (S_{ij} - z) Q_{ij} + z (M + N).

The doubly substochastic matrices form the bipartite matching polytope, whose constraint matrix is totally unimodular, so its vertices are the 0-1 matrices of partial matchings. A linear function on a polytope reaches its maximum at a vertex. □\square

So as the scale β\beta grows, the plan approaches the optimum of the linear program of Lemma 5: a pair can be matched only when Sij>zS_{ij} > z, and the best partial matching of the weights Sij−zS_{ij} - z is chosen. When this matching is unique, the plan converges to it.

Lemma 6 (the output is a partial matching). The list of line L9 has each row index and each column index at most once, and each listed PijP_{ij} is above the threshold θ\theta.

Proof. Line L8 gives one best column per row and one best row per column, with ties to the smaller index. A row ii is listed only with its own best column, so at most once. If two rows i≠i′i \ne i' were listed with the same column jj, both would equal the best row of jj, which is one index. The threshold test is in line L9. □\square

Theorem. For any T≥1T \ge 1, the plan of line L7 has exact column sums bb, and the output is a partial matching of pairs with Pij>θP_{ij} > \theta. When the iterations converge, the plan is the unique maximizer of ⟨Sˉ,P⟩+H(P)\langle \bar S, P \rangle + H(P) over U(a,b)U(a, b), and with scores scaled by β\beta its value is within (max⁡UH−min⁡UH)/β(\max_U H - \min_U H)/\beta of the best partial matching with weights Sij−zS_{ij} - z, shifted by z(M+N)z(M + N).

Proof. Lemmas 1 and 6 give the first sentence. Lemmas 2 and 3 give the second, and Lemmas 4 and 5 the third. ■\blacksquare

Complexity

The model is the real RAM, and the cost of the network is outside the page. Lines L1 and L2 take O(MN)O(M N). Each pass of lines L5 and L6 computes M+1M + 1 and N+1N + 1 log-sum-exp values of length N+1N + 1 and M+1M + 1, which is O(MN)O(M N). Lines L7 to L9 take O(MN)O(M N). The total is O(TMN)O(T M N) time and O(MN)O(M N) space.

The number of passes needed for a given accuracy grows when the scores have a large range, because the scaled matrix is then close to having zero entries. The paper uses T=100T = 100. The paper reports about 12 million parameters for the network with D=256D = 256, L=9L = 9 layers and 4 attention heads, and about 69 ms for one pair on a GTX 1080 GPU; these are measurements of 2020 and include the network.

Properties

  • Partial assignment. The dustbin lets a point stay unmatched. Without it, the plan would force every point onto some partner.
  • Symmetric. Swapping the images transposes SS, and at convergence PP is transposed too. The output pairs are the same up to the swap.
  • Soft output. PijP_{ij} is a number in (0,1)(0, 1) for real pairs and can serve as a match confidence, for example to weight RANSAC samples.
  • Differentiable. Each line is smooth in SS and zz, so the network can be trained through the layer with ordinary backpropagation. This is the reason for Sinkhorn iterations instead of the exact Hungarian algorithm.
  • Learned. The behavior of the full matcher depends on the training data, for example indoor or outdoor images.

Variants and improvements

  • Exact assignment. On fixed scores, the Hungarian algorithm on the weights Sij−zS_{ij} - z gives the limit matching of the proof directly, in O((M+N)3)O((M + N)^3) time, but it is not differentiable.
  • Classical filters. Mutual nearest neighbor matching and the ratio test work on raw descriptor distances without training. SuperGlue replaces them.
  • LightGlue (2023). Lindenberger, Sarlin and Pollefeys replaced the Sinkhorn layer with a cheaper double softmax and a matchability score, and stop early on easy pairs.
  • Dense matchers. LoFTR drops the detector and matches coarse feature maps with a related double softmax or with the same optimal transport layer.

When to use it

Use SuperGlue when you match keypoints across large changes of viewpoint or light, for example for visual localization or relative pose, and a GPU and trained weights for the type of images are available. Use the optimal matching layer alone on any score matrix when you need a soft partial assignment that is differentiable. Use nearest neighbors with the ratio test when there is no GPU, when the image type is far from the training data, or when you need a method with no learned parts.

Pitfalls

  • Iterations are not convergence. After TT passes only the columns are exact. With a large score range the rows can still be far off; check the row error if you depend on it.
  • Overflow. In the plain domain, exp⁡(Sˉ)\exp(\bar S) overflows for scores of a few hundred. Use the log domain, as lines L5 and L6 do.
  • The dustbin marginals. The dustbin row must sum to NN and the column to MM. With 1 instead, the total masses differ for M≠NM \ne N, and no plan has those marginals.
  • Normalization in the released code. The released code divides the scores by D\sqrt{D} and divides the marginals by M+NM + N so that PP sums to 1, then multiplies back. Mixed conventions shift the threshold.
  • Argmax over the dustbin. Line L8 takes the best real column, even when the dustbin entry of the row is larger; the threshold then removes weak pairs. Taking the argmax over the dustbin too is a different rule.
  • The threshold is tuned. θ=0.2\theta = 0.2 in the paper is a design choice.

Implementations

The network is outside this page. The Python code in impl/python/superglue.py implements only the optimal matching layer of lines L1 to L9 on a given score matrix and dustbin score: the augmentation, the log-domain Sinkhorn iterations, the plan and the mutual best pairs above a threshold. The tests check that the columns are exact after each pass, that the rows converge, that the log-domain result equals a plain-domain Sinkhorn, that large scores do not overflow, that marginal-preserving changes of the converged plan do not raise the entropic objective, that at a high scale the matches equal a brute-force best partial matching and the gap bound of the proof holds, and that a weak row goes to the dustbin.

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

superglue.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/superglue/. The authors are listed in prov/QBGQCK.jsonl.

"""The optimal matching layer of SuperGlue (Sarlin, DeTone, Malisiewicz and Rabinovich 2020).

The graph neural network is not part of this file. Its output is given: a
score matrix S of M rows (the keypoints of image A) and N columns (the
keypoints of image B), and the dustbin score z, which is a learned scalar.

The layer adds a dustbin row and a dustbin column of value z, so that a
keypoint can stay unmatched. It then scales the (M + 1) x (N + 1) matrix
exp(S_bar) to the marginals a = (1, ..., 1, N) and b = (1, ..., 1, M) with
Sinkhorn iterations, in the log domain so that large scores do not overflow.
The result P is the entropic optimal transport plan. A pair (i, j) of real
keypoints is a match when j is the best column of row i, i is the best row of
column j (both inside the real block) and P[i][j] is above a threshold.
"""

import math
from typing import List, Sequence, Tuple

Matrix = List[List[float]]


def log_sum_exp(xs: Sequence[float]) -> float:
    m = max(xs)
    if m == -math.inf:
        return -math.inf
    return m + math.log(sum(math.exp(x - m) for x in xs))


def augment(S: Sequence[Sequence[float]], z: float) -> Matrix:
    """Add a dustbin column and a dustbin row of value z to S."""
    n = len(S[0])
    rows = [list(r) + [z] for r in S]
    rows.append([z] * (n + 1))
    return rows


def log_sinkhorn(Sbar: Sequence[Sequence[float]], log_a: Sequence[float], log_b: Sequence[float],
                 iters: int) -> Tuple[List[float], List[float]]:
    """Return log scalings (u, v) such that P_ij = exp(Sbar_ij + u_i + v_j)."""
    rows, cols = len(Sbar), len(Sbar[0])
    u = [0.0] * rows
    v = [0.0] * cols  # @line L3
    for _ in range(iters):  # @line L4
        u = [log_a[i] - log_sum_exp([Sbar[i][j] + v[j] for j in range(cols)])  # @line L5
             for i in range(rows)]
        v = [log_b[j] - log_sum_exp([Sbar[i][j] + u[i] for i in range(rows)])  # @line L6
             for j in range(cols)]
    return u, v


def transport_plan(S: Sequence[Sequence[float]], z: float, iters: int = 100) -> Matrix:
    """Return the (M + 1) x (N + 1) plan P after iters Sinkhorn iterations."""
    m, n = len(S), len(S[0])
    Sbar = augment(S, z)  # @line L1
    log_a = [0.0] * m + [math.log(n)]  # @line L2
    log_b = [0.0] * n + [math.log(m)]
    u, v = log_sinkhorn(Sbar, log_a, log_b, iters)
    return [[math.exp(Sbar[i][j] + u[i] + v[j]) for j in range(n + 1)]  # @line L7
            for i in range(m + 1)]


def mutual_matches(P: Sequence[Sequence[float]], threshold: float) -> List[Tuple[int, int, float]]:
    """Mutual best pairs of the real block with P above the threshold.

    Ties go to the smaller index.
    """
    m, n = len(P) - 1, len(P[0]) - 1
    row_best = [max(range(n), key=lambda j: (P[i][j], -j)) for i in range(m)]  # @line L8
    col_best = [max(range(m), key=lambda i: (P[i][j], -i)) for j in range(n)]
    return [(i, j, P[i][j]) for i, j in enumerate(row_best)  # @line L9
            if col_best[j] == i and P[i][j] > threshold]


def superglue_assign(S: Sequence[Sequence[float]], z: float, iters: int = 100,
                     threshold: float = 0.2) -> Tuple[Matrix, List[Tuple[int, int, float]]]:
    """Return (P, matches) for the score matrix S and the dustbin score z."""
    if len(S) == 0 or len(S[0]) == 0:
        return [], []
    P = transport_plan(S, z, iters)
    return P, mutual_matches(P, threshold)
test_superglue.py 197 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/superglue/. The authors are listed in prov/QBGQCK.jsonl.

import math
import random

from superglue import augment, mutual_matches, superglue_assign, transport_plan


def random_scores(rng, m, n, lo=-3.0, hi=3.0):
    return [[rng.uniform(lo, hi) for _ in range(n)] for _ in range(m)]


def sums(P):
    return [sum(r) for r in P], [sum(c) for c in zip(*P)]


def plain_sinkhorn(S, z, iters):
    """Sinkhorn in the plain domain: scale K = exp(S_bar) by row and column factors."""
    m, n = len(S), len(S[0])
    K = [[math.exp(x) for x in r] for r in augment(S, z)]
    a = [1.0] * m + [float(n)]
    b = [1.0] * n + [float(m)]
    y = [1.0] * (n + 1)
    x = [1.0] * (m + 1)
    for _ in range(iters):
        x = [a[i] / sum(K[i][j] * y[j] for j in range(n + 1)) for i in range(m + 1)]
        y = [b[j] / sum(K[i][j] * x[i] for i in range(m + 1)) for j in range(n + 1)]
    return [[x[i] * K[i][j] * y[j] for j in range(n + 1)] for i in range(m + 1)]


def partial_matchings(m, n):
    """All partial matchings of rows 0..m-1 into columns 0..n-1, as lists of pairs."""
    def rec(i, used):
        if i == m:
            yield []
            return
        for rest in rec(i + 1, used):
            yield rest
        for j in range(n):
            if j not in used:
                for rest in rec(i + 1, used | {j}):
                    yield [(i, j)] + rest
    yield from rec(0, frozenset())


def entropy(P):
    return -sum(p * (math.log(p) - 1.0) for r in P for p in r if p > 0)


def objective(Sbar, P):
    return sum(s * p for rs, rp in zip(Sbar, P) for s, p in zip(rs, rp))


def plan_of_matching(pairs, m, n):
    P = [[0.0] * (n + 1) for _ in range(m + 1)]
    for i, j in pairs:
        P[i][j] = 1.0
    for i in range(m):
        P[i][n] = 1.0 - sum(P[i][:n])
    for j in range(n):
        P[m][j] = 1.0 - sum(P[i][j] for i in range(m))
    P[m][n] = float(len(pairs))
    return P


def test_column_sums_are_exact_after_each_iteration():
    rng = random.Random(1)
    for iters in (1, 3, 10):
        m, n = rng.randint(1, 6), rng.randint(1, 6)
        P = transport_plan(random_scores(rng, m, n), rng.uniform(-1, 1), iters)
        _, cols = sums(P)
        assert all(abs(c - 1.0) < 1e-12 for c in cols[:n])
        assert abs(cols[n] - m) < 1e-12


def test_row_sums_converge_and_mass_is_m_plus_n():
    rng = random.Random(2)
    for _ in range(10):
        m, n = rng.randint(1, 6), rng.randint(1, 6)
        P = transport_plan(random_scores(rng, m, n), rng.uniform(-1, 1), 300)
        rows, _ = sums(P)
        assert all(abs(r - 1.0) < 1e-9 for r in rows[:m])
        assert abs(rows[m] - n) < 1e-9
        assert abs(sum(rows) - (m + n)) < 1e-9


def test_log_domain_equals_plain_domain():
    rng = random.Random(3)
    for _ in range(8):
        m, n = rng.randint(1, 5), rng.randint(1, 5)
        S, z = random_scores(rng, m, n), rng.uniform(-1, 1)
        P = transport_plan(S, z, 25)
        Q = plain_sinkhorn(S, z, 25)
        assert all(abs(p - q) < 1e-10 for rp, rq in zip(P, Q) for p, q in zip(rp, rq))


def test_large_scores_do_not_overflow():
    rng = random.Random(4)
    S = random_scores(rng, 4, 5, 500.0, 900.0)
    P, matches = superglue_assign(S, 700.0, iters=200)
    assert all(math.isfinite(p) for r in P for p in r)
    _, cols = sums(P)
    assert all(abs(c - 1.0) < 1e-9 for c in cols[:5])


def test_fixed_point_beats_marginal_preserving_perturbations():
    rng = random.Random(5)
    m, n = 4, 3
    S, z = random_scores(rng, m, n), 0.3
    Sbar = augment(S, z)
    P = transport_plan(S, z, 500)
    best = objective(Sbar, P) + entropy(P)
    for _ in range(200):
        i, k = rng.sample(range(m + 1), 2)
        j, l = rng.sample(range(n + 1), 2)
        d = rng.uniform(-1, 1) * 0.5 * min(P[i][j], P[k][l], P[i][l], P[k][j])
        Q = [r[:] for r in P]
        Q[i][j] += d
        Q[k][l] += d
        Q[i][l] -= d
        Q[k][j] -= d
        assert objective(Sbar, Q) + entropy(Q) <= best + 1e-12


def test_high_scale_matches_best_partial_matching():
    rng = random.Random(6)
    done = 0
    while done < 6:
        m, n = rng.randint(1, 4), rng.randint(1, 4)
        S, z = random_scores(rng, m, n), rng.uniform(-1, 1)
        values = sorted(((sum(S[i][j] - z for i, j in pm), sorted(pm))
                         for pm in partial_matchings(m, n)), reverse=True)
        if len(values) > 1 and values[0][0] - values[1][0] < 1.0:
            continue  # skip near ties
        done += 1
        beta = 5.0
        Sb = [[beta * s for s in r] for r in S]
        P, matches = superglue_assign(Sb, beta * z, iters=2000, threshold=0.5)
        assert sorted((i, j) for i, j, _ in matches) == values[0][1]
        rows, _ = sums(P)
        assert all(abs(r - 1.0) < 1e-6 for r in rows[:m])  # converged
        # the bound of Lemma 4: LP optimum minus <S_bar, P> is at most (H(P) - H(P*)) / beta
        Sbar = augment(S, z)
        star = plan_of_matching(values[0][1], m, n)
        assert abs(objective(Sbar, star) - (values[0][0] + z * (m + n))) < 1e-9
        gap = objective(Sbar, star) - objective(Sbar, P)
        assert gap <= (entropy(P) - entropy(star)) / beta + 1e-6


def test_weak_rows_go_to_the_dustbin_and_matches_are_a_matching():
    rng = random.Random(7)
    S = random_scores(rng, 5, 4)
    S[2] = [-8.0] * 4
    P, matches = superglue_assign(S, 0.0, iters=200)
    assert all(i != 2 for i, _, _ in matches)
    assert P[2][4] > 0.99
    assert len({i for i, _, _ in matches}) == len(matches) == len({j for _, j, _ in matches})
    assert all(p > 0.2 for _, _, p in matches)
    assert mutual_matches(P, 1.0) == []
    assert superglue_assign([], 0.0) == ([], [])


def brute_mutual(P, theta):
    m, n = len(P) - 1, len(P[0]) - 1
    out = []
    for i in range(m):
        for j in range(n):
            row_ok = all(P[i][j] > P[i][k] or (P[i][j] == P[i][k] and j <= k) for k in range(n))
            col_ok = all(P[i][j] > P[k][j] or (P[i][j] == P[k][j] and i <= k) for k in range(m))
            if row_ok and col_ok and P[i][j] > theta:
                out.append((i, j, P[i][j]))
    return out


def test_many_small_inputs_against_plain_sinkhorn_and_brute_mutual():
    rng = random.Random(9)
    for trial in range(600):
        m, n = rng.randint(1, 4), rng.randint(1, 4)
        S = [[float(rng.randint(-2, 2)) for _ in range(n)] for _ in range(m)]
        z = float(rng.randint(-1, 1))
        iters = rng.randint(1, 8)
        P, matches = superglue_assign(S, z, iters=iters, threshold=0.2)
        Q = plain_sinkhorn(S, z, iters)
        assert all(abs(p - q) < 1e-9 for rp, rq in zip(P, Q) for p, q in zip(rp, rq))
        assert matches == brute_mutual(P, 0.2)


def test_transpose_gives_transposed_matches():
    rng = random.Random(8)
    for _ in range(5):
        m, n = rng.randint(1, 5), rng.randint(1, 5)
        S, z = random_scores(rng, m, n), rng.uniform(-1, 1)
        T = [list(c) for c in zip(*S)]
        _, a = superglue_assign(S, z, iters=400)
        _, b = superglue_assign(T, z, iters=400)
        assert sorted((i, j) for i, j, _ in a) == sorted((j, i) for i, j, _ in b)

History

Sinkhorn studied the scaling of a positive matrix to given row and column sums in the 1960s, and Sinkhorn and Knopp (1967) proved convergence for the doubly stochastic case. Cuturi (2013) used the iterations for entropic optimal transport and made them a common tool in machine learning. Before 2020, feature matching was nearest neighbor search with hand-made filters such as the ratio test and mutual checks, sometimes followed by a learned outlier filter. Sarlin, DeTone, Malisiewicz and Rabinovich (2020) learned the matching itself with attention and put a Sinkhorn layer with a dustbin at the end. With SuperPoint features it became a common baseline, and LightGlue (2023) followed as a faster successor.

References

  1. Paul-Edouard Sarlin, Daniel DeTone, Tomasz Malisiewicz and Andrew Rabinovich, SuperGlue, learning feature matching with graph neural networks, IEEE/CVF Conference on Computer Vision and Pattern Recognition (CVPR), 2020 (arXiv 1911.11763), Section 3.1 (the keypoint encoder and the attentional graph neural network), Section 3.2 (the score matrix, the dustbin, the marginals and the Sinkhorn iterations), Section 3.3 (the loss), Section 4 (the implementation details)
  2. Richard Sinkhorn and Paul Knopp, Concerning nonnegative matrices and doubly stochastic matrices, Pacific Journal of Mathematics 21(2), 1967, pages 343-348, the convergence of alternating row and column scaling
  3. Marco Cuturi, Sinkhorn distances, lightspeed computation of optimal transport, Advances in Neural Information Processing Systems 26 (NIPS), 2013, pages 2292-2300, entropic regularization of optimal transport and its solution by Sinkhorn iterations
  4. Daniel DeTone, Tomasz Malisiewicz and Andrew Rabinovich, SuperPoint, self-supervised interest point detection and description, IEEE/CVF Conference on Computer Vision and Pattern Recognition Workshops (CVPRW), 2018, the keypoints and descriptors that SuperGlue takes as input in most of its experiments

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.average
  • a full proof of time.best
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example