Code Lab / Challenge 17

Hybrid Search: BM25, Reciprocal Rank Fusion, MMR

MediumBM25, reciprocal rank fusion, MMR diversity re-ranking

The problem, as an interviewer would set it

Dense retrieval tends to miss exact identifiers (error codes, SKUs, function
names). Lexical retrieval misses paraphrases. Hybrid search runs both and
fuses the results. Implement the three pieces.

1. bm25_scores(query_tokens, corpus_tokens, k1=1.5, b=0.75) -> np.ndarray
   Okapi BM25 over pre-tokenized documents, one score per document:
       score(d) = sum_t idf(t) * tf(t,d) * (k1 + 1)
                  / (tf(t,d) + k1 * (1 - b + b * len(d) / avgdl))
       idf(t) = ln(1 + (N - df(t) + 0.5) / (df(t) + 0.5))   non-negative form
   Unseen terms contribute nothing, a term repeated in the query counts once,
   b controls length normalization, k1 sets how fast tf saturates.

2. reciprocal_rank_fusion(rankings, k=60) -> list[int]
   Fuse ranked id lists from independent retrievers, ranks counting from 1:
       rrf(d) = sum over lists of 1 / (k + rank(d))
   A document missing from a list contributes nothing from that list. Return
   doc ids best first, ties broken by id so the output is deterministic.

3. mmr(query_vec, doc_vecs, candidate_ids, lambda_=0.5, k=5) -> list[int]
   Maximal Marginal Relevance re-ranking. Greedily pick the candidate that
   maximises, until k are chosen:
       lambda_ * sim(q, d) - (1 - lambda_) * max sim(d, s) over selected s
   Rows of doc_vecs are L2-normalized, so sim is a dot product. The first pick
   has an empty selected set and falls back to pure query similarity.

The dense side reuses the hashed n-gram embedder from the semantic search
challenge, so the whole thing runs on numpy alone.
What interviewers look for

Where lexical beats dense and vice versa, why RRF fuses ranks rather than scores

A strong solution demonstrates:
- Why the "+ 1" idf variant matters: the classic Robertson idf goes negative
  once a term is in more than half the corpus, so containing it can rank a
  document below one that does not.
- What the knobs do. b=0 switches length normalization off, and tf saturates at
  idf * (k1 + 1) however often a term repeats, unlike cosine over raw counts.
- That RRF fuses ranks, not scores: a BM25 score of 3.0 and a cosine of 0.4 are
  not comparable, and any weighted sum re-scores the corpus the moment either
  scorer is recalibrated. k damps each list's head, so a small k lets one
  rank-1 vote dominate while k=60 (the value from Cormack et al., 2009)
  rewards consensus. RRF is the zero-tuning default, not the ceiling: with
  labelled queries, a tuned convex combination of normalised scores can beat
  it, at the cost of re-tuning whenever a scorer changes.
- That MMR is greedy, trades relevance against redundancy, and collapses to
  plain top-k at lambda_=1.0, which is the cheapest way to test it.
Common mistakes: idf that can go negative; forgetting avgdl so long documents
win; recomputing document frequency per document instead of once per term; RRF
summing similarities instead of reciprocal ranks; MMR measuring redundancy
against the mean of the selected set rather than the max, which lets a cluster
in by attrition. Follow-ups: weighted RRF when one retriever is stronger; a
cross-encoder second stage over the fused top-50, and its latency budget;
per-field BM25 weights (BM25F); learned sparse retrieval such as SPLADE as the
lexical leg; whether MMR runs before or after the reranker, and which
relevance score it should then use.

Write your own version first. The reference solution and its tests are one click away when you are ready.

Next challenge