interviewpath
  • 0day streak
  • 10total XP
  • Level 1
0/6

Unit 7 · ML & applied AI · Lesson 9 of 13

Retrieval, embeddings and retrieval-augmented generation

How to find the right context for a model: lexical (BM25), dense and hybrid retrieval, chunking, reranking with cross-encoders, and grounding answers with citations. The core engineering habit is evaluating retrieval separately from generation, so you know which half failed.
About 4 h 30 minFocus mode

Step 1: Learn the ideas

  • Inverted indexes, tf-idf and BM25
  • Dense embeddings: bi-encoders, contrastive training, similarity search
  • Approximate nearest-neighbor indexes (awareness)
  • Hybrid retrieval and reciprocal rank fusion
  • Reranking with cross-encoders
  • Chunking strategies, overlap and metadata
  • Query rewriting and multi-step retrieval (awareness)
  • Provenance, citations and abstention
  • Retrieval evaluation versus generation evaluation
  • Access control in retrieval

Why it matters

Most LLM applications over private knowledge are retrieval systems with a generator on top, and many of their failures are retrieval failures: the passage that answers the question never reached the top k. A RAG design question tests more than architecture: the revealing part is explaining how you would evaluate and debug the system.

Core ideas

Lexical retrieval. An inverted index maps terms to the documents containing them. BM25 scores a document by summing, over query terms, an inverse-document-frequency weight times a saturating function of term frequency, with a correction for document length relative to the average; the parameters k1 and b control saturation and length normalization. BM25 is strong on exact identifiers, names, error codes, rare terms and unfamiliar domains, needs no training, and is a demanding baseline.

Dense retrieval. A bi-encoder embeds queries and passages independently, and relevance is cosine or dot-product similarity. Passage vectors are precomputed, so search is a nearest-neighbor lookup, usually approximate: graph-based or quantized indexes give up a little recall for large speedups. Dense retrieval captures paraphrase and topical similarity, but can miss exact strings, handles negation and numbers poorly, and degrades outside its training domain. Retrievers are trained contrastively, pulling queries towards relevant passages and away from negatives; hard negatives, passages that look relevant but are not, matter a great deal.

Hybrid retrieval and fusion. Run both retrievers and merge the lists. Raw scores live on different scales, so normalize them or use reciprocal rank fusion, score(d) = sum over retrievers of 1 / (k + rank(d)), with k commonly set to 60. Hybrid is a sensible default when queries mix keywords and natural language.

Reranking. A cross-encoder reads query and passage together and outputs a relevance score. Because tokens attend across query and passage it is much more accurate than a bi-encoder, but it needs one forward pass per candidate, so it only reranks the top tens of candidates from the first stage.

Chunking. Chunks should be small enough to be specific and to fit several into the context, and large enough to carry meaning. Split along document structure (sections, paragraphs, functions) rather than fixed character counts where possible, use modest overlap, and attach metadata: title, section path, source, date and permissions. Chunks that depend on surrounding text ("the policy above") are hard to retrieve; prepending document or section context before indexing can help.

Grounding and provenance. Pass passages with identifiers and require citations to them; check that cited passages exist and actually support each claim (string overlap or an entailment check). Let the system say it cannot answer when the context is insufficient, and evaluate that behavior. Long context windows do not remove the need to retrieve well: studies have found that models use information in the middle of long inputs less reliably than at the beginning or end, and cost grows with every token.

Permissions. Enforce access control in the retrieval query itself (tenant and document ACL filters), not by instructing the model to ignore documents. Anything retrieved can appear in the answer.

Evaluate the halves separately. Build a set of real queries with labeled relevant passages; 30 to 100 is enough to start. Retrieval metrics: recall@k (is an answer-bearing passage among the k the generator sees?), MRR and NDCG. Generation metrics given gold context: faithfulness (claims supported by the context), answer correctness and citation accuracy. Then measure end to end. When the end-to-end score drops, the split tells you whether to fix chunking, the retriever, the reranker or the prompt.

Common misconceptions

  • "Embeddings make keyword search obsolete." Lexical search wins on identifiers, rare terms and new domains; hybrid often beats either alone.
  • "A large context window removes the need for retrieval." Cost, latency and uneven use of long contexts still favor a focused set of passages.
  • "Similarity scores are relevance probabilities." They are model-specific, uncalibrated and not comparable across models or queries; set thresholds empirically.
  • "Reading a few answers is enough evaluation." Without labeled retrieval and faithfulness checks you can neither locate failures nor catch regressions.
  • "The model will respect permissions if instructed." Filter before retrieval; a prompt is not an access-control layer.
  • "A citation proves grounding." Models can cite passages that do not support the claim; verify support.

How to approach it

Build a small end-to-end pipeline on documents you know, with BM25, a bi-encoder, fusion and a cross-encoder, plus a hand-labeled query set, and measure each stage. Read the IR book's BM25 and evaluation sections and the DPR paper for dense retrieval. In design interviews, walk through ingestion, indexing, retrieval, reranking, generation with citations, access control and evaluation, naming a metric for each stage.

Suggested order

  1. 1Read Introduction to Information Retrieval Ch. 6 on tf-idf weighting and the BM25 section of Ch. 11; compute a BM25 score by hand for a two-term query.
  2. 2Read the method section of the DPR paper (dual encoder, in-batch and hard negatives) and how it reports retrieval accuracy separately from question-answering accuracy.
  3. 3Read the Sentence Transformers "Retrieve & Re-Rank" guide and run its example with a bi-encoder and a cross-encoder.
  4. 4Read the RAG paper for the original retrieve-then-generate framing, noting how it differs from prompt-based RAG systems today.
  5. 5Read "Introducing Contextual Retrieval" for chunk context, hybrid BM25 plus embeddings and reranking; treat its numbers as the vendor’s own measurements.
  6. 6Read "Evaluation of ranked retrieval results" in the IR book, then build the 30-query retrieval evaluation in the practice guidance.

Step 2: Check off what you can do

Tap each one you can genuinely do or explain. Each earns 10 XP.

Step 3: Go deeper

  • Introduction to Information RetrievalStart here

    Cambridge University Press (free online edition hosted by the Stanford NLP Group)

    Section: Okapi BM25: a non-binary model (Ch. 11)

    BM25 term-frequency saturation and length normalization; Ch. 6 and Ch. 8 cover tf-idf and ranked evaluation.

    Open(opens in a new tab)Link responded, 5 Oct 2026
  • Sentence Transformers documentationStart here

    Sentence Transformers documentation (sbert.net)

    Section: Retrieve & Re-Rank

    Working bi-encoder retrieval plus cross-encoder reranking that you can run and measure.

    Open(opens in a new tab)Link responded, 5 Oct 2026
  • Dense Passage Retrieval for Open-Domain Question Answering

    arXiv

    How dual-encoder dense retrievers are trained with in-batch and hard negatives and evaluated by top-k retrieval accuracy.

    Open(opens in a new tab)Link responded, 5 Oct 2026
  • Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks

    arXiv

    The original retrieval-augmented generation formulation; read for framing and evaluation, not as a production recipe.

    Open(opens in a new tab)Link responded, 5 Oct 2026
  • Introducing Contextual Retrieval

    Anthropic Engineering

    Practitioner treatment of chunk context loss, hybrid lexical and dense retrieval, and reranking.

    Open(opens in a new tab)Link responded, 5 Oct 2026

Step 4: Practice

Build a tiny retrieval eval: take 50 to 200 documents you understand (course notes or documentation pages), chunk them, and write 30 realistic queries labeled with the IDs of the passages that answer them. Implement BM25 (a library is fine), a Sentence Transformers bi-encoder, reciprocal rank fusion and a cross-encoder reranker over the top 20. Report recall@5, recall@20 and MRR for each configuration, with bootstrap intervals over queries. Then generate cited answers for 10 queries and check by hand whether each cited passage supports its claim. For every failure, write down which stage caused it.

No external problems are linked; follow the guidance above.

Record attempts on each problem’s page (+15 XP, +10 more when solved on your own).

Step 5: Test yourself

Answer each one out loud or on paper before you finish the lesson.

  1. Question 1Why do bi-encoders scale to millions of passages while cross-encoders do not?
  2. Question 2What is reciprocal rank fusion, and why use it instead of adding raw scores?
  3. Question 3Answers are wrong but recall@5 is high. Where do you look next?
  4. Question 4Which queries does BM25 handle better than embeddings, and why?
  5. Question 5How would you chunk API reference pages differently from long policy documents?
  6. Question 6Where must tenant permissions be enforced in a RAG pipeline?
  7. Question 7How do you verify that a citation actually supports a claim?

You’re done when you can

  • Sketch a RAG architecture with ingestion, hybrid retrieval, reranking, citations, permissions and evaluation in under ten minutes.
  • Explain the components of BM25 and when lexical search beats dense retrieval, with examples.
  • Build and report a labeled retrieval evaluation with recall@k and MRR for at least two retriever configurations.
  • Explain why retrieval and generation are evaluated separately, with a concrete failure example for each.

Finish the lesson

How confident do you feel?

Lesson complete!

+50 XP

Reviews will come up on the Practice tab so it sticks.

Unlocks next: AI workflows, agents and tool contracts

Your notes and study time

Log study time