848. ColBERT late interaction MaxSim score
Why it matters Late interaction (ColBERT, ColPali) is a strong retrieval baseline and a common RAG interview topic: why it beats single-vector search and what it costs.
Paper: "ColBERT: Efficient and Effective Passage Search via Contextualized Late Interaction over BERT", Khattab and Zaharia, 2020, arXiv 2004.12832.
ColBERT keeps one embedding per token. The score between a query and a document is the sum, over query tokens, of the maximum cosine similarity to any document token: S(q, d) = sum_i max_j E_q[i] . E_d[j], with every token vector L2-normalised first.
Write colbert_scores(query, docs).
Inputs:
- query: a list or ndarray of shape (n_q, dim).
- docs: a list of documents, each a list or ndarray of shape (n_j, dim). Documents can have different lengths.
- Normalise each token vector by its L2 norm. A zero vector stays zero (divide by max(norm, 1e-12)).
Return an ndarray of floats with shape (len(docs),), one score per document in input order. No rounding.
def colbert_scores(query, docs)Example 1
Input: colbert_scores([[1.0, 0.0], [0.0, 1.0]], [[[1.0, 0.0]], [[3.0, 0.0], [0.0, 2.0]]])
Output: [1.0, 2.0]
Example 2
Input: query = [[1.0, 1.0]], docs = [[[1.0, 0.0], [0.0, 1.0]], [[-1.0, -1.0]]]
Output: [0.707107, -1]
Example 3
Input: query = [[2.0, 0.0, 0.0], [0.0, 0.0, 5.0]], docs = [[[1.0, 1.0, 0.0], [0.0, 1.0, 1.0], [1.0, 0.0, 1.0]]]
Output: [1.414214]
Constraints
- Python 3 with NumPy. Code runs in your browser.
- Your code must pass all 4 tests to be accepted.
Hint 1
Normalise rows with np.linalg.norm(m, axis=1, keepdims=True).
Hint 2
For each doc, sim = q @ d.T has shape (n_q, n_j).
Hint 3
Take max over axis 1 (document tokens), then sum.
Common mistakes
- Max over the query axis instead of the document axis.
- Skipping normalisation, which rewards long vectors.
- Averaging instead of summing over query tokens.
Understand the idea
A single-vector retriever squashes the whole passage into one point. ColBERT keeps every token and lets each query token find its best match, then adds the matches. For query tokens [1, 0] and [0, 1] and a document with tokens [3, 0] and [0, 2], each query token finds a perfect match, so the score is 2.0. A one-token document [1, 0] only scores 1.0.
Shapes and data flow
query: (n_q, dim). each doc: (n_j, dim). similarity matrix per doc: (n_q, n_j).