Skip to content

< all problems122 · Level 02, Search

Late Interaction: Score Every Token

medium · implement · Embeddings & Retrieval

Rank documents by late interaction: every token keeps its own vector, and a document scores by how well each query token is matched somewhere in it. Implement maxsim(query, doc), which scores one document text against a query text, and rank(query, docs). encode_query(text) and encode_doc(text) are provided: each returns a list of (token, vector) pairs straight from the stand-in encoder, the query padded with [PAD] tokens to a fixed length.

  1. Skip every token for which skipped(token) is true (padding, punctuation, stop words), in the query and in the document.
  2. Normalise every remaining vector to unit length with normalize before any dot product.
  3. MaxSim. For each query token, take its largest dot product with any document token. The score is the sum of those maxima over the query tokens. A query or a document with no tokens left scores 0.0.
  4. rank(query, docs) scores every document in the dict docs (id to text) and returns (id, score) pairs, highest score first, equal scores in ascending id order.

The catch. The order of the two reductions is the method: max over the document's tokens first, then sum over the query's. Each query token is answered by its best match, wherever it sits, and a document scores well by covering the whole query. Sum over the document's tokens instead and a document wins by repeating one word. Average all the tokens into one vector first and a document that answers with two exact words among many others loses to a vague one whose average lands near the query.