BM25, factorization, two towers, and ANN
Hybrid retrieval works because lexical, collaborative, and content representations fail in different places.
Marketplace ranking learns from biased clicks and reinforces its own mistakes.
This chapter moves from assign each source a job to version the serving path. We will make the idea concrete in a small code example before placing it back inside a production system with 80 ms ranking budget.
Publish tokenizer, towers, vector normalization, item snapshot, ANN index, and score semantics together, then audit exact-search recall.
Verify the behavior illustrated in hybrid_candidates.py, then measure decision utility, slice reliability, and system latency.
A random interaction split and click-only labels improve offline NDCG while amplifying already-prominent items. An unsafe release must degrade to a named baseline or the last known-good version.
Build the idea one layer at a time.
Candidate generators have different superpowers. BM25 matches words, factorization learns recurring user–item structure, and two-tower encoders turn users and items into vectors that can be searched at scale.
BM25 is strong for exact terms and new searchable items because it needs no interaction history. Matrix factorization learns embeddings whose dot product explains observed preference but struggles with cold-start entities. Two towers create query and item vectors from features, allowing new users or items to participate when informative metadata exists.
At serving time, item embeddings are precomputed and placed in an ANN index; the user tower runs per request. That decomposition makes retrieval fast but limits early interaction between query and item features. Hybrid retrieval preserves complementary lexical, collaborative, and fresh-item coverage for the downstream ranker.
- two-tower embeddings
- BPR
- NDCG
- cold start
Follow the reasoning before touching the code.
- 01
Assign each source a job
Use lexical retrieval for exact intent, collaborative signals for taste, content towers for cold start, and popularity or recency for safe coverage.
- 02
Train with meaningful negatives
Contrast positives against exposed or hard candidates rather than arbitrary catalog rows, and prevent future interactions from entering historical embeddings.
- 03
Version the serving path
Publish tokenizer, towers, vector normalization, item snapshot, ANN index, and score semantics together, then audit exact-search recall.
lexical = {'manual': 8.2, 'guide': 6.1}
two_tower = {'guide': 0.92, 'course': 0.88}
pool = {}
for source, results in [('bm25', lexical), ('tower', two_tower)]:
for rank, item in enumerate(results, start=1):
row = pool.setdefault(item, {'sources': [], 'rrf': 0.0})
row['sources'].append(source)
row['rrf'] += 1 / (60 + rank)
for item, evidence in sorted(pool.items(), key=lambda pair: -pair[1]['rrf']):
print(item, evidence)Combine lexical and two-tower candidates with source evidence.
What to notice
- Raw BM25 and embedding scores are not mixed directly because their scales and meanings differ.
- Reciprocal-rank fusion rewards guide for appearing in both sources while retaining source evidence for later analysis.
YOUR TURN Pause and predict before revealing the answer.
A brand-new item has rich text but no interactions. Which source can retrieve it immediately, and when can a two-tower model also do so?
Need a hint?
Separate methods that require an interaction ID embedding from those that encode content.
Check your reasoning
BM25 can retrieve it from indexed text immediately; a two-tower model can too if the item tower uses available content features rather than only a learned ID.
Lessons 1, 2 in this course.
Connect the chapter to the course’s quantitative spine.
Hybrid retrieval works because lexical, collaborative, and content representations fail in different places. The discounted cumulative gain below is the shared course-level lens that helps quantify the surrounding system. Name each symbol, check its units or shape, and use only values that were available at the production cutoff.
Discounted cumulative gain
| Symbol | Meaning / shape / unit |
|---|---|
rel_r | relevance at rank r |
r | one-indexed rank |
K | slate cutoff |
Open derivation and numerical substitution
Start from the production quantity being optimized, substitute the observed values with their declared units, then isolate the model-controlled term. Preserve shape annotations at each step so broadcasting or aggregation cannot silently change the result.
- Write the named inputs: rel_r, r, K.
- Substitute one small, hand-checkable batch before vectorizing.
- Calculate an independent reference value and compare within a declared tolerance.
# equation → code contract
inputs = validate_shapes_and_units(batch)
value = compute_c08(inputs)
assert is_finite(value)Change one assumption and make the tradeoff visible.
Use the worked chapter as your prediction, then change one input in the lab and explain why the output moves. The lab runs predefined TypeScript and never executes learner code, so the focus stays on the concept rather than setup.
Exploration feedback loop
Allocate unbiased exploration and observe learning coverage versus short-term utility.
Assumption: Simplified marketplace with position-biased clicks and fixed demand.
Open nonvisual data table
| Item | Computed state | Interpretation |
|---|---|---|
| rank 1 | 35.0% | 6.2% |
| rank 2 | 30.3% | 6.9% |
| rank 3 | 25.6% | 7.5% |
| rank 4 | 20.8% | 8.2% |
| rank 5 | 16.1% | 8.8% |
Trace the complete operating path.
Carry the chapter’s central idea into the system: Hybrid retrieval works because lexical, collaborative, and content representations fail in different places. The path below shows where that reasoning needs an artifact, a test, an owner, or a fallback.
- 01
Turn “Assign each source a job” into a written invariant and a failing test.
- 02
Promote hybrid_candidates.py from illustration to a versioned implementation with representative fixtures.
- 03
Use “Version the serving path” as the release checkpoint: Publish tokenizer, towers, vector normalization, item snapshot, ANN index, and score semantics together, then audit exact-search recall.
- 04
Serve or materialize behind explicit 80 ms ranking budget.
- 05
Join telemetry to mature outcomes and retain a rollback path.
Observability
Join service health, input quality, prediction distributions, slice behavior, and mature outcomes by exact version.
Cost
Measure storage, preprocessing, compute, queueing, and human review under a representative arrival pattern.
Failure modes
A random interaction split and click-only labels improve offline NDCG while amplifying already-prominent items. Add a detector, owner, mitigation, and stop condition for this class of failure.
Alternatives
Compare a rule, a simpler statistical baseline, and a different system boundary before adding model complexity.
Explain the contract, not just the vocabulary.
Hybrid catalog ranker
Specify BM25 plus learned retrieval, ranking, re-ranking, temporal evaluation, and a versioned online path.
- Exposure-aware data contract
- Candidate recall analysis
- Ranker and NDCG report
- Diversity/fallback/latency plan
Read primary material with a purpose.
Return to the opening failure.
Version index, ranker, features, and catalog together; log exposures and measure each stage separately.
For this lesson, the release evidence is the worked code example, a hand-checked formal result, deterministic simulation output, a ≥80% checkpoint, the production rubric, and a named fallback. The course resolves when the system can produce candidate generation, ranking metrics, debiasing, and online experiment design.