Algorithmresearch
ColBERT late interaction
Also called ColBERT.
Keeps one embedding per token and scores a document by summing, over query tokens, the maximum similarity to any document token.
- Solves
- Learning to rank
- Time
- O(n t e) stage_oneO(c L n e + c log c) stage_two
- Space
- O(t e) extra
- Where
- L = the largest number of tokens in a document; c = the number of candidate documents; e = the vector dimension; n = the number of query vectors; t = the number of token vectors in the collection
- Model
- Word RAM
- Properties
- deterministicexactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Omar Khattab, Matei Zaharia, 2020
ColBERT scores a query against a document by late interaction. Each side is encoded separately into one vector per token, for the query and for document , and the score is
the sum over query tokens of their best match in the document. A dual encoder compresses each side into one vector and scores by one inner product; ColBERT keeps all token vectors, which makes the score more expressive and the index much larger. A cross-encoder lets the query and document tokens attend to each other and cannot precompute anything; ColBERT precomputes all document vectors. This page gives the score, the two-stage retrieval with a token index and exact reranking, when the two stages give the exhaustive answer, a certificate for it, and the training gradient. Search inside the token index is the topic of maximum inner product search. The BERT encoders and the quality of their vectors are outside the code here.
In plain words
We break the question and each document into words and give every word a list of numbers that describes its meaning in context. To score a document, we take each word of the question and find the word of the document that matches it best. We add up these best matches. A document that matches every part of the question well gets a high score. Because the documents are processed once, ahead of time, a search only needs to process the question. To search a large collection, we first find, for each question word, the stored document words that match it best, collect their documents, and then score only those documents exactly.
The problem
The input is a query, given as unit vectors , and a collection of documents, each a list of unit vectors, with token vectors in all. The output is the documents with the largest , highest first, ties to the smaller document id. In the paper, the vectors come from BERT with a linear layer to a smaller dimension and normalization, the query is padded with [mask] tokens to a fixed length , and the inner product of unit vectors is the cosine similarity. Exhaustive scoring of all documents costs , which is too slow for millions of documents, so retrieval uses two stages.
The algorithm
COLBERT-RETRIEVE(q_1..q_n, docs, k', k)- 1
index ← every document token vector, with its document id and position - 2
C ← ∅ - 3
for each query vector q_i: - 4
add to C the documents of the k' token vectors with the largest q_i · e - 5
for each d ∈ C: S(q, d) ← Σ_i max_j q_i · e_{d,j} - 6
return the k documents of C with the largest S, ties to the smaller id
Line L1 is offline. Line L4 is a top- inner product search for each query vector; the code does it exactly, and the paper uses an approximate faiss index over the token vectors. Lines L5 and L6 score the candidates exactly. The paper also uses the same score alone to rerank the top 1000 documents of BM25, which is lines L5 and L6 with a given .
Example
The query has and . Document 0 has the tokens and , document 1 has , and document 2 has .
| document | best match for | best match for | |
|---|---|---|---|
| 0 | 0.8 | 0.8 | 1.6 |
| 1 | 1.0 | 0.0 | 1.0 |
| 2 | 0.0 | 1.0 | 1.0 |
The exhaustive top 1 is document 0. With , line L4 keeps the token of document 1 for and the token of document 2 for , so and line L6 returns document 1: stage 1 misses the best document, because it is good for both query vectors and best for neither. With , every document is a candidate and the result is document 0. For , the certificate of the proof file is , and the returned score 1.0 is below it, so the result is correctly not certified. In training, the pairwise loss of document 0 as the positive and document 1 as the negative is .
Correctness
The proof in proofs/correctness.md shows:
- Score. The code computes , and for unit vectors. The tests compare it with a plain double loop.
- A superset is enough. If the candidate set contains the exhaustive top , lines L5 and L6 return it in the exhaustive order. In particular, when is at least the number of tokens, is the whole collection and end-to-end retrieval equals exhaustive late interaction. The tests check both on random collections.
- Stage 1 can miss. For smaller this fails in general, as in the example.
- A certificate. With the -th largest over all tokens, every document outside has . So if the -th returned score exceeds , the result is exactly the exhaustive top .
- Training gradient. For the pairwise softmax loss, the gradient in flows only to the winning token of each document, , where the maxima are unique. The tests check it by finite differences.
These are statements about the given vectors and an exact stage 1. The quality of the ranking is measured: Khattab and Zaharia (2020) report MRR@10 on the MS MARCO passage development set of 34.9 when reranking the BM25 top 1000 and 36.0 for end-to-end retrieval, against 16.7 for BM25, and much lower latency than reranking with a BERT cross-encoder. These are measurements.
Proof: Reranking a candidate set that holds the true top k gives the exhaustive result, and a missed document scores at most the sum of the k'-th token scoresfull
A query is a list of unit vectors and document is a list of unit vectors , with . They are the outputs of the encoders, which this proof treats as given. The late interaction score is
the sum of MaxSim of Khattab and Zaharia (2020), Equation (3), with the cosine similarity. A ranking of documents sorts by , highest first, then by the smaller document id.
Lemma 1. The code computes , and . A document that holds every query vector gets .
Proof. maxsim_score takes, for each , the largest inner product over the tokens of , and sums them. Each inner product of unit vectors is in by the Cauchy-Schwarz inequality, and equals 1 for .
Stage 1 (lines L1 to L4) takes, for each , the document tokens of largest over the whole collection, with ties to the smaller document id and token position, and lets be the set of the documents that own one of these tokens. Stage 2 (lines L5 and L6) scores each document of exactly and returns the top of . Let be the exhaustive top over all documents.
Lemma 2 (a superset is enough). If , stage 2 returns , in the exhaustive order.
Proof. Every document has the distinct key . is the set of the smallest keys of the collection. Since , these are also the smallest keys of , and both rankings list them in increasing key order.
Corollary. If is at least the number of tokens in the collection, is every document, and end-to-end retrieval returns the exhaustive top .
Proof. Each then keeps every token, and every document has at least one token, so is the whole collection. Apply Lemma 2.
Lemma 3 (stage 1 can miss the best document). For $k' < $ the number of tokens, Lemma 2 does not hold in general.
Proof. Take and , document 0 with the tokens and , document 1 with the token and document 2 with the token . The scores are , so . With , the best token for is the one of document 1 and the best for is the one of document 2, so and stage 2 returns document 1.
Document 0 is good for both query vectors and best for neither, and stage 1 looks at each query vector alone.
Lemma 4 (a certificate). Let be the -th largest value of over all document tokens. Every document has . So if the -th score that stage 2 returns is larger than , the result equals the exhaustive top .
Proof. If , no token of is among the kept for any , so each of its tokens has , and . Sum over . If the -th returned score exceeds this bound, every document outside has a smaller score than each returned document, so the returned set holds the best documents of the collection and, by Lemma 2 applied to it, comes in the exhaustive order.
In the example of Lemma 3, , the bound is 2, and the returned score 1.0 does not certify the result, as it must not.
Lemma 5 (training gradient). For the pairwise loss with , at a point where each max has a unique argmax ,
Proof. Near such a point each max is the single term , so . Also and .
The gradient is taken in the given vectors, not through the normalization, and only the winning token of each document gets a gradient for each query vector. Where two tokens tie, is not differentiable and any convex combination of their gradients is a subgradient of the max.
What is outside the proof. The encoders and the quality of the ranking they give are outside the code, and the effectiveness and latency figures of the paper are measurements. The paper's stage 1 uses an approximate index, so even the certificate of Lemma 4 is about the exact search used here.
The tests in impl/python/test_colbert.py check Lemma 1 against a double loop, the corollary and Lemma 2 on random collections, the counterexample of Lemma 3, Lemma 4 on random collections, Lemma 5 by central finite differences away from ties, the tie rule, and the worked example of the page.
Complexity
Line L1 stores vectors of dimension , space, which is the main cost of the method: one vector per token rather than one per document. Stage 1 with an exact scan costs , plus the selection of the top for each query vector; an approximate index makes it sublinear in . Stage 2 scores documents of at most tokens each, , and sorts them in . A cross-encoder over the same documents needs full transformer passes over the joined text, which is much more expensive per document than inner products.
Properties
- Decomposable. The score is a sum over query tokens, so one strong match cannot make up for a missing query term, and each query token adds at most 1.
- Precomputable. Document vectors do not depend on the query; adding a document needs one encoder pass and an index update.
- Order-free inside the document. The maximum ignores where in the document the match is, except through the contextual vectors.
- Exact given the candidates. Stage 2 is exact, so all error of end-to-end retrieval comes from stage 1 and from the encoders.
- Sparse gradient. Each query vector trains only the winning token of each document in the pair.
Variants and improvements
- Compressed token vectors. Later versions store each token vector as a centroid id plus a quantized residual, which cuts the index size several times; see product quantization.
- Centroid-based candidate generation. Group token vectors by cluster, as in an inverted file index, and gather candidates by the clusters nearest each query vector.
- Distillation. Train the late interaction scores to match a cross-encoder.
- Single-vector reduction. Mean pooling of the token vectors gives a plain dual encoder, with the cost and expressiveness of one inner product.
- Learned sparse alternative. SPLADE keeps one sparse vector per document and runs on an inverted index.
When to use it
Use ColBERT when a single vector per document loses too much, for example for long or multi-aspect queries, and the index can afford one vector per token. It sits between a dual encoder and a cross-encoder in both cost and expressiveness, and it can be the first stage or a reranker. When storage is tight, a single-vector dual encoder or a sparse model is cheaper. Whether its accuracy gain is worth the index size on a given collection is a matter of measurement.
Pitfalls
- Too small . Line L4 with a small misses documents that are good for every query vector and best for none, as in the example. Use the certificate, or a larger , to detect it.
- Unnormalized vectors. The bounds and the cosine reading need unit vectors. Long, unnormalized token vectors in line L1 let a single token dominate the maximum.
- Ties in the maximum. At a tie between two document tokens, the gradient of line L5 is not unique. Fix a rule, such as the first token, so that training is reproducible.
- Mixing exact and approximate. Line L4 with an approximate index can miss tokens even for large ; the superset argument then does not hold. Compare against exact search when testing.
- Punctuation and padding. The paper filters punctuation from documents and pads queries with [mask] tokens. Changing either changes the set of vectors in lines L1 and L3 and the scores.
Implementations
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.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/colbert/. The authors are listed in prov/26Y1DV.jsonl.
"""ColBERT late interaction on given token embeddings.
The encoders are outside this file. A query is a list of token vectors
q_1..q_n and a document is a list of token vectors d_1..d_m, all scaled to
unit length. The score is the sum of MaxSim:
S(q, d) = sum over i of max over j of q_i . d_j.
End-to-end retrieval has two stages. Stage 1 runs, for each query vector,
an exact top-k' search over all document token vectors and keeps the
documents that own a hit. Stage 2 scores these candidates exactly and
returns the top k, with ties broken by the smaller document id. The real
system uses an approximate index in stage 1; this file uses an exact one.
"""
import math
def dot(a, b):
return sum(p * q for p, q in zip(a, b))
def normalize(v):
n = math.sqrt(dot(v, v))
return [x / n for x in v] if n > 0 else list(v)
def maxsim_score(q, d):
return sum(max(dot(qi, dj) for dj in d) for qi in q)
def by_score(scored):
return [doc for _, doc in sorted(scored, key=lambda t: (-t[0], t[1]))]
def exhaustive_top_k(q, docs, k):
return by_score([(maxsim_score(q, d), i) for i, d in enumerate(docs)])[:k]
def token_index(docs):
"""(document id, token position, vector) for every token of every document."""
return [(i, j, v) for i, d in enumerate(docs) for j, v in enumerate(d)] # @line L1
def candidates(q, docs, k_prime):
"""The ids of the documents that own one of the top-k' tokens of some q_i."""
index = token_index(docs)
found = set() # @line L2
for qi in q: # @line L3
hits = sorted(index, key=lambda t: (-dot(qi, t[2]), t[0], t[1]))[:k_prime]
found.update(doc for doc, _, _ in hits) # @line L4
return sorted(found)
def missed_bound(q, docs, k_prime):
"""sum over i of the k'-th largest q_i . e over all document tokens.
A document that stage 1 does not find scores at most this value.
"""
total = 0.0
for qi in q:
vals = sorted((dot(qi, v) for _, _, v in token_index(docs)), reverse=True)
total += vals[min(k_prime, len(vals)) - 1]
return total
def end_to_end(q, docs, k_prime, k):
cand = candidates(q, docs, k_prime)
scored = [(maxsim_score(q, docs[i]), i) for i in cand] # @line L5
return by_score(scored)[:k] # @line L6
def pairwise_loss(q, pos, neg):
"""-log softmax over the two scores S(q, d+) and S(q, d-), for d+."""
a, b = maxsim_score(q, pos), maxsim_score(q, neg)
m = max(a, b)
return -(a - m) + math.log(math.exp(a - m) + math.exp(b - m))
def argmax_token(qi, d):
best = 0
for j in range(1, len(d)):
if dot(qi, d[j]) > dot(qi, d[best]):
best = j
return best
def pairwise_loss_gradient(q, pos, neg):
"""dL/dq_i, valid where each max has a unique argmax.
The gradient is taken in the given vectors, not through normalize().
"""
a, b = maxsim_score(q, pos), maxsim_score(q, neg)
m = max(a, b)
p_pos = math.exp(a - m) / (math.exp(a - m) + math.exp(b - m))
out = []
for qi in q:
dp = pos[argmax_token(qi, pos)]
dn = neg[argmax_token(qi, neg)]
out.append([(p_pos - 1.0) * x + (1.0 - p_pos) * y for x, y in zip(dp, dn)])
return out
test_colbert.py 149 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/colbert/. The authors are listed in prov/26Y1DV.jsonl.
import math
import random
from colbert import (
candidates,
dot,
end_to_end,
exhaustive_top_k,
maxsim_score,
missed_bound,
normalize,
pairwise_loss,
pairwise_loss_gradient,
)
Q = [[1.0, 0.0], [0.0, 1.0]]
DOCS = [[[0.8, 0.6], [0.6, 0.8]], [[1.0, 0.0]], [[0.0, 1.0]]]
def random_unit(rng, d):
return normalize([rng.gauss(0, 1) for _ in range(d)])
def random_case(rng, n_docs=6, d=4):
q = [random_unit(rng, d) for _ in range(rng.randint(1, 4))]
docs = [[random_unit(rng, d) for _ in range(rng.randint(1, 5))] for _ in range(n_docs)]
return q, docs
def test_page_example():
assert [round(maxsim_score(Q, d), 12) for d in DOCS] == [1.6, 1.0, 1.0]
assert exhaustive_top_k(Q, DOCS, 1) == [0]
# With k' = 1 each query vector finds a one-token document first, and
# document 0, the true best, is never a candidate.
assert candidates(Q, DOCS, 1) == [1, 2]
assert end_to_end(Q, DOCS, 1, 1) == [1]
assert candidates(Q, DOCS, 2) == [0, 1, 2]
assert end_to_end(Q, DOCS, 2, 1) == [0]
def test_maxsim_against_double_loop():
rng = random.Random(1)
for _ in range(200):
q, docs = random_case(rng)
for d in docs:
total = 0.0
for qi in q:
best = -math.inf
for dj in d:
s = 0.0
for a, b in zip(qi, dj):
s += a * b
if s > best:
best = s
total += best
assert abs(maxsim_score(q, d) - total) < 1e-12
def test_full_candidate_set_gives_exhaustive_result():
rng = random.Random(2)
for _ in range(200):
q, docs = random_case(rng)
n_tokens = sum(len(d) for d in docs)
assert candidates(q, docs, n_tokens) == list(range(len(docs)))
for k in (1, 3, len(docs)):
assert end_to_end(q, docs, n_tokens, k) == exhaustive_top_k(q, docs, k)
def test_superset_of_true_top_k_is_enough():
rng = random.Random(3)
hits = 0
for _ in range(300):
q, docs = random_case(rng)
k = 2
truth = exhaustive_top_k(q, docs, k)
for k_prime in (1, 2, 3):
if set(truth) <= set(candidates(q, docs, k_prime)):
hits += 1
assert end_to_end(q, docs, k_prime, k) == truth
assert hits > 0
def test_missed_bound_certifies_the_result():
assert abs(missed_bound(Q, DOCS, 1) - 2.0) < 1e-12
rng = random.Random(6)
certified = 0
for _ in range(300):
q, docs = random_case(rng)
exact = {i: maxsim_score(q, d) for i, d in enumerate(docs)}
for k_prime in (1, 2, 4):
cand = candidates(q, docs, k_prime)
b = missed_bound(q, docs, k_prime)
assert all(exact[i] <= b + 1e-12 for i in range(len(docs)) if i not in cand)
k = 2
got = end_to_end(q, docs, k_prime, k)
if len(got) == k and exact[got[-1]] > b:
certified += 1
assert got == exhaustive_top_k(q, docs, k)
assert certified > 0
def test_ties_by_document_id():
q = [[1.0, 0.0]]
docs = [[[0.0, 1.0]], [[1.0, 0.0]], [[1.0, 0.0]]]
assert exhaustive_top_k(q, docs, 2) == [1, 2]
assert end_to_end(q, docs, 3, 2) == [1, 2]
def test_pairwise_loss_gradient_by_finite_differences():
rng = random.Random(4)
h = 1e-6
checked = 0
for _ in range(50):
q, docs = random_case(rng, n_docs=2)
pos, neg = docs
# Skip cases where some max is close to a tie, so the argmax is unique.
gaps = []
for qi in q:
for d in (pos, neg):
vals = sorted((dot(qi, dj) for dj in d), reverse=True)
if len(vals) > 1:
gaps.append(vals[0] - vals[1])
if gaps and min(gaps) < 1e-3:
continue
g = pairwise_loss_gradient(q, pos, neg)
for i in range(len(q)):
for c in range(len(q[i])):
old = q[i][c]
q[i][c] = old + h
up = pairwise_loss(q, pos, neg)
q[i][c] = old - h
down = pairwise_loss(q, pos, neg)
q[i][c] = old
assert abs((up - down) / (2 * h) - g[i][c]) < 1e-6
checked += 1
assert checked > 20
def test_score_bounds_for_unit_vectors():
rng = random.Random(5)
for _ in range(100):
q, docs = random_case(rng)
for d in docs:
assert -len(q) - 1e-12 <= maxsim_score(q, d) <= len(q) + 1e-12
# A document that contains every query vector gets the top score n.
assert abs(maxsim_score(q, q) - len(q)) < 1e-12
History
Khattab and Zaharia (2020) introduced ColBERT to close the gap between fast dual encoders and accurate but slow BERT rerankers. They kept the independence of the two encoders, so that documents can be encoded offline, and moved the interaction to a cheap sum of maxima over token vectors, with a faiss index for end-to-end retrieval. Later work compressed the token vectors and replaced the candidate stage with centroid search, which made late interaction practical on larger collections.
References
- Omar Khattab and Matei Zaharia, ColBERT, efficient and effective passage search via contextualized late interaction over BERT, Proceedings of the 43rd ACM SIGIR Conference, 2020, pp. 39-48; Section 3 and Equation (3) (the sum of maximum similarities, the encoders with [mask] padding of queries and the [Q] and [D] markers, and training with a pairwise softmax loss), Sections 3.6 and 4.1.2 (end-to-end retrieval with a faiss index over token vectors and exact reranking of the candidates), and the experimental evaluation (measured effectiveness and latency)
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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag 26Y1DV Edit this page History Report an error Markdown