Late interaction: keep token vectors until the match
延迟交互检索
Compute MaxSim, expose pooling collisions and mask padding correctly.
late-interactionDo not average away the two things being requested
A query asks about both a bicycle and a brake. Imagine that these needs are represented by the unit vectors [1,0] and [0,1]. One document has a token matching each need; another has just one token pointing halfway between them. Their mean vectors point in the same direction, so pooled cosine cannot separate them. Keeping the individual vectors allows a different comparison.
Late interaction independently encodes the query and document, but postpones some matching until their token representations meet. ColBERT uses contextual token embeddings and a sum of maximum similarities, called MaxSim. “Late” refers to interaction between the two texts, not to a lack of context within each text. Its BERT encoder can already use neighboring tokens before matching. ColBERT, sections 3.1–3.3
This lies between a single-vector bi-encoder and a cross-encoder that jointly processes the pair. SBERT illustrates reusable sentence embeddings and pooling; ColBERT retains multiple vectors per document instead of reducing all evidence to one vector. The tradeoff is additional storage and matching work. SBERT, section 3
A maximum for each query token, then a sum
Let f_i(q) and g_j(d) be nonzero projected token vectors. Normalize each to unit length so that their inner product equals cosine similarity:
For each query position i, choose the best document-token match. Sum these best similarities across query positions:
The maximum is taken over document positions; the sum is over query positions. One document token may win for several query tokens. There is no one-to-one matching constraint and no trainable parameter inside this final operator. The encoders that produce its inputs are learned; the original ColBERT trains them with a pairwise ranking loss. ColBERT, section 3.3
For comparison, a pooled baseline first averages each text’s normalized token vectors and then takes cosine, provided both means are nonzero:
In the opening example, both document means point along [1,1], so both pooled cosines are approximately 1. MaxSim instead gives 2 for the two exact matches and √2 for the single diagonal token. This constructed distinction does not prove that MaxSim always makes the better semantic decision.
For fixed vectors, duplicating a document vector adds no new maximum; duplicating a query vector adds another summand:
Here ∥ means append a row. The added summand can be negative. Repeating actual text can change contextual embeddings, so these are operator properties, not invariances of the full text encoder. The operator is also generally asymmetric: two orthogonal query vectors against one diagonal document vector score √2; reversing the roles scores 1/√2.
Unit-vector similarities lie between −1 and 1. Adding a document vector cannot reduce a maximum when all existing vectors stay fixed:
This monotonicity can reward extra matching opportunities even when the added text is unhelpful. The model and evaluation must decide whether those opportunities improve relevance.
The padding trap has a negative score
Run the self-contained Python 3.12 / NumPy 1.26 program. All vectors are authored; it neither trains nor loads ColBERT. Its three documents contain two exact matches, one diagonal vector, or only the first exact match. Real token vectors must be nonzero. A document mask excludes inactive positions before the maximum; an entirely masked document is rejected.
"""Original late-interaction operator with authored token vectors; no ColBERT training."""
import json
import numpy as np
def normalize(rows):
x=np.asarray(rows,dtype=float)
if x.ndim!=2 or not 1<=x.shape[1]<=64 or len(x)>128 or not np.isfinite(x).all():
raise ValueError('finite token matrix: at most128 rows, dimension1..64')
scale=np.max(np.abs(x),axis=1,keepdims=True)
y=np.divide(x,scale,out=np.zeros_like(x),where=scale>0)
norm=np.sqrt((y*y).sum(axis=1,keepdims=True))
if np.any(norm==0):raise ValueError('real token vectors must be nonzero')
return y/norm
def maxsim(query,document,mask=None):
q=normalize(query);d=normalize(document)
if not len(q) or not len(d) or q.shape[1]!=d.shape[1]:raise ValueError('nonempty matching token matrices required')
keep=np.ones(len(d),dtype=bool) if mask is None else np.asarray(mask,dtype=bool)
if keep.shape!=(len(d),) or not keep.any():raise ValueError('at least one unmasked document token required')
similarity=q@d.T
similarity[:,~keep]=-np.inf
winners=np.argmax(similarity,axis=1)
values=similarity[np.arange(len(q)),winners]
return dict(score=float(values.sum()),per_token=values.tolist(),winners=winners.tolist())
def pooled(query,document):
q=normalize(query).mean(axis=0);d=normalize(document).mean(axis=0)
# A mean can cancel to zero even when all token vectors are nonzero.
if np.linalg.norm(q)==0 or np.linalg.norm(d)==0:return 0.
return float((q/np.linalg.norm(q))@(d/np.linalg.norm(d)))
def demo():
q=np.eye(2);docs=[np.eye(2),np.array([[1.,1.]]),np.array([[1.,0.]])]
scores=[maxsim(q,d)['score'] for d in docs]
mask_case=maxsim([[1.,0.]],[[-1.,0.],[1.,0.]],[True,False])
return dict(maxsim=scores,pooled_cosine=[pooled(q,d) for d in docs],
query_duplicate=maxsim([[1,0],[0,1],[1,0]],docs[0])['score'],
document_duplicate=maxsim(q,[[1,0],[0,1],[1,0]])['score'],
negative_masked=mask_case['score'],unsafe_zero_padding=max(-1.,0.),
forward=maxsim(q,docs[1])['score'],reverse=maxsim(docs[1],q)['score'],
negative_extension_before=maxsim([[1,0]],[[-1,0]])['score'],
negative_extension_after=maxsim([[1,0]],[[-1,0],[0,1]])['score'],
scope='Authored normalized token vectors; real padding masked out before max, no contextual encoder trained.')
if __name__=='__main__':print(json.dumps(demo(),sort_keys=True,allow_nan=False))
MaxSim scores are [2,√2,1]. Copying the first query token raises the first document’s score from 2 to 3; copying a document token leaves it at 2. Another example has one legitimate similarity of −1. An inactive zero-padding score would incorrectly raise the maximum to 0. Correct masking preserves −1 by excluding the inactive position rather than treating it as a neutral contender.
ColBERT’s query augmentation uses learned representations at special MASK positions. Those are intentional query features, not ordinary inactive batch padding. Do not remove them merely because this toy example masks inactive document positions. The original paper also filters document punctuation according to a predefined list; this example does not implement its tokenizer, punctuation rules or query augmentation. ColBERT, section 3.2
For h-dimensional embeddings, direct pairwise matching and raw document storage require:
The storage expression assumes b bytes per scalar and excludes identifiers, offsets and index overhead. Our code materializes the similarity matrix; chunking could reduce temporary storage. The cost expression excludes the text encoders.
Caching is possible, compression is still a choice
Document token vectors can be prepared offline because their encoder does not depend on the current query. This does not make them small: a document with many retained positions has many vectors. Moving those vectors between CPU and GPU memory can matter as much as arithmetic. ColBERT separately describes offline storage, reranking a retrieved pool and end-to-end retrieval; a small exhaustive MaxSim routine is not the complete retrieval system. ColBERT, sections 3.4–3.6
Evaluate against lexical and single-vector baselines using the same candidate pool when studying reranking. When studying full retrieval, additionally measure candidate recall, index size, transfer cost and latency. Token truncation, masks, duplicate evidence and irrelevant long documents are useful failure tests. Swapping the encoders or projection requires compatible document embeddings and an updated index.
Which side is being reduced?
- Why do the first two documents tie under pooled cosine but not MaxSim?
Answer: Both means point diagonally, losing whether the two query directions were matched separately. MaxSim retains each query token’s best match: 1+1=2 versus 1/√2+1/√2=√2.
- A query token has document similarities [−0.8,−0.3]. An inactive padded position has value 0. What should the maximum be?
Answer: −0.3. Padding must be excluded before reduction. Leaving its zero in the competition incorrectly returns 0 and creates evidence that no real token supplied.
- Does appending a duplicate query row always increase the score?
Answer: No. It adds that row’s best similarity, which may be negative, zero or positive. Appending a duplicate document row leaves the fixed-vector maximum unchanged.
- Design a test of whether extra document tokens help meaning rather than merely create more matching opportunities.
Answer: Add controlled irrelevant text to judged documents, keep queries and relevance labels fixed, and compare scores and rankings before and after. Record truncation and contextual-encoder changes separately from the fixed-vector operator effect. Evaluate on held-out needs rather than only these constructed vectors.
Independent encoding, richer matching
Read ColBERT’s normalization and MaxSim together with its offline storage section. Compare SBERT’s pooling to see which representation is cached and which matching computation remains at query time. The fixed repository README now describes ColBERT v2; this article’s method claims use the cited 2020 first-version paper, not a silent mixture of later implementations.
Make a prediction, then check
With fixed token vectors, does copying a document token increase MaxSim?
Learning objectives
- Separate contextual token encoding from the final parameter-free matching operator.
- Run the original example and diagnose its approximation error.
Prerequisites & connections
Explore related knowledge →References
- ColBERT: Efficient and Effective Passage Search via Contextualized Late Interaction over BERT — arXiv v1
Omar Khattab; Matei Zaharia · 2020 - Sentence-BERT: Sentence Embeddings using Siamese BERT-Networks — arXiv v1
Nils Reimers; Iryna Gurevych · 2019
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-20 · Single AI author. Viewed physical PDF4–5, sections3.1–3.5 and opening3.6: token encoders, query augmentation, normalization, MaxSim and offline storage. No model or benchmark reproduction. Viewed physical PDF2–3: joint BERT comparison, tied encoders, pooling and three objectives; did not reproduce benchmarks. 6 paired equations and four explained exercises. Checked MaxSim against explicit nested sums, pooling collision, query/document duplication, asymmetry, real masks and extreme normalization; authored vectors only.
- Checked MaxSim against explicit nested sums, pooling collision, query/document duplication, asymmetry, real masks and extreme normalization; authored vectors only.
- Four computed SVG variants per topic;9 numeric/geometry tests and24 responsive cases passed. Eight selected final captures directly viewed. Full article acceptance recorded separately.
Source locations checked:
- ColBERT: Efficient and Effective Passage Search via Contextualized Late Interaction over BERT — arXiv v1 · Viewed physical PDF4–5, sections3.1–3.5 and opening3.6: token encoders, query augmentation, normalization, MaxSim and offline storage. No model or benchmark reproduction.
- Sentence-BERT: Sentence Embeddings using Siamese BERT-Networks — arXiv v1 · Viewed physical PDF2–3: joint BERT comparison, tied encoders, pooling and three objectives; did not reproduce benchmarks.
Related topics