🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

RAG: Retrieval-Augmented Generation

Natural Language ProcessingRAG: Retrieval-Augmented GenerationđŸŸĸ Free Lesson

RAG: Retrieval-Augmented Generation

What You'll Learn

  • 1Derive the bi-encoder similarity and the in-batch contrastive loss behind DPR
  • 2Estimate dense index memory and pick a compression level
  • 3Explain marginalization over retrieved documents in RAG
  • 4Evaluate a retrieval pipeline with recall and grounded answer accuracy

A language model stores facts implicitly in weights that go stale the moment training stops, while a retriever can read a fresh index at serving time. This lesson derives dense passage retrieval and its contrastive training loss, the memory arithmetic of a vector index, the marginalization that joins retrieval with generation, and the hybrid scoring and evaluation rules that decide whether a pipeline is actually trustworthy.

Dense Passage Retrieval

BM25 (Robertson and Zaragoza, 2009) scores a query term by term using term frequency and inverse document frequency with two damping constants:

It cannot match paraphrase, so DPR (Karpukhin et al., 2020) embeds the question and each passage independently with a bi-encoder and compares them by cosine similarity:

The encoder is trained with a contrastive loss over one positive and every other passage in the batch as a negative:

Trained on 120,000 question and passage pairs, this raised recall at 100 on Natural Questions from roughly 59 for BM25 to 78, and the same two towers can be cached so the corpus is encoded once rather than at query time.

Indexing and Compression

Vectors must fit in memory and answer within a latency budget, so the arithmetic drives the design:

where is the number of passages, the embedding width, and the bytes per value. A DPR style index over Wikipedia holds on the order of 21 million passages, which is GB in float32. Product quantization to 64 bytes per vector cuts that to 1.34 GB at the cost of a few recall points, and hierarchical navigable small world graphs trade a rebuild step for millisecond nearest neighbor search over millions of vectors.

MethodSignalIndex size at 21M passagesRecall at 100 on Natural Questions
BM25lexical overlap12 GB, inverted listsabout 59
DPR bi-encodercosine on 768d vectors64 GB float32about 78
ColBERT late interactiontoken level MaxSim210 GB float32about 84
Hybrid with reciprocal rank fusionboth rankings merged76 GBabout 86

Combining Retrieval and Generation

Lewis et al. (2020) trained the retriever and generator together by marginalizing over the top passages rather than committing to one:

and the document weights themselves come from a softmax over the similarity scores:

Two practical variants exist. A frozen retriever plus a frozen generator combines them at inference only, which is cheap to update because reindexing is the only refresh. A trained marginalization lets gradients reach the passage encoder, which improves recall but requires the generator and retriever to move together.

Reciprocal rank fusion blends a lexical and a dense ranking when neither alone is strong enough:

Worked Examples

Worked Code

python
import numpy as np

def embed(texts, dim=256):
    rng = np.random.default_rng(0)
    table = {}
    for text in texts:
        vec = np.zeros(dim)
        for token in text.lower().split():
            vec[hash(token) % dim] += 1.0
        table[text] = vec / (np.linalg.norm(vec) + 1e-9)
    return table

def cosine(a, b):
    return float(a @ b)

def retrieve(query, table, k=3):
    qv = table[query]
    scored = [(text, cosine(vec, qv)) for text, vec in table.items()
              if text != query]
    scored.sort(key=lambda pair: pair[1], reverse=True)
    return scored[:k]

def doc_weights(scored):
    scores = np.array([s for _, s in scored])
    exp = np.exp(scores - scores.max())
    return exp / exp.sum()

corpus = [
    "dense passage retrieval encodes questions and passages with two towers",
    "bm25 scores terms with term frequency and inverse document frequency",
    "the model answers from the retrieved context and cites the passage",
]
table = embed(corpus + ["what is dense passage retrieval?"])
hits = retrieve("what is dense passage retrieval?", table, k=3)
for (text, score), weight in zip(hits, doc_weights(hits)):
    print(round(score, 3), round(float(weight), 3), text[:48])
python
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer

def build_prompt(question, passages, max_docs=3):
    context = "\n".join(f"[{i + 1}] {p}"
                        for i, p in enumerate(passages[:max_docs]))
    return ("Answer using only the provided context.\n\n"
            f"Context:\n{context}\n\nQuestion: {question}\nAnswer:")

def rag_generate(model_name, question, passages):
    tokenizer = AutoTokenizer.from_pretrained(model_name)
    model = AutoModelForCausalLM.from_pretrained(model_name)
    model.eval()
    inputs = tokenizer(build_prompt(question, passages), return_tensors="pt")
    with torch.no_grad():
        output = model.generate(**inputs, max_new_tokens=64, do_sample=False)
    return tokenizer.decode(output[0][inputs["input_ids"].shape[1]:],
                            skip_special_tokens=True)

docs = ["DPR uses two encoders and a contrastive loss over in-batch negatives.",
        "Retrieval quality is measured with recall at k before generation."]
print(rag_generate("gpt2", "How is DPR trained?", docs))

Real-World Applications

  • Enterprise question answering: policies and tickets live in a vector index, so answers cite the retrieved document instead of a memorized fact.
  • Legal and medical search: hybrid scoring keeps rare exact strings via BM25 while paraphrase queries reach the dense index.
  • Freshness: reindexing nightly is cheaper than retraining, which is the core operational reason RAG replaced fine-tuning for factual updates.

💡Measure retrieval before blaming the generator

When an answer is wrong, log recall at 10 first: if the correct passage never reached the prompt, no decoding setting can fix it, and most RAG failures traced to retrieval come from chunking and embedding choices rather than the model.

Common Mistakes

Chunking passages without overlap

Fix: Split on structure and overlap chunks so an answer split across a boundary still lands in one vector.

Evaluating only final answer accuracy

Fix: Track recall at 10 and faithfulness separately, otherwise retrieval regressions hide behind a fluent generator.

Using one retriever for every query type

Fix: Route exact identifiers to BM25 and paraphrase questions to dense retrieval, then fuse the rankings.

Best Practices

  • Log recall at 10 and mean reciprocal rank alongside answer accuracy on every index rebuild
  • Rerank the top 50 with a cross encoder before truncating to the top 3 for the prompt
  • Store passage ids with every generation so citations can be verified automatically

Key Takeaways

  • DPR trains a bi-encoder with a contrastive loss over one positive and in-batch negatives
  • Index memory equals passages times width times bytes per value, 64.5 GB in float32 at 21 million by 768
  • RAG marginalizes generator output over the retrieved set instead of committing to one passage
  • Reciprocal rank fusion with constant 60 merges lexical and dense rankings without score calibration

Frequently Asked Questions

How many passages should the prompt contain?

Three to five passages of roughly 100 to 200 words usually saturate quality, because extra context dilutes attention and raises cost while recall at 10 rarely improves past the first few documents.

Why rerank if the vector search already ranked?

A cross encoder reads the query and passage jointly, which scores relevance far more accurately than two independent embeddings, and running it only on the top 50 keeps the cost linear in that small set.

When is fine-tuning better than retrieval?

When the knowledge must change the model behavior itself, such as a house style or a new output format, fine-tuning wins. When facts change daily or must be cited, retrieval wins because the index can be rebuilt in minutes.

Interview Questions

Q1: Why is DPR a bi-encoder instead of a cross encoder?

Each passage can be encoded and cached once, so query time is one encode plus a nearest neighbor search, while a cross encoder would need to score every query and passage pair.

Q2: What does the in-batch negative loss assume?

That other questions in the same batch have unrelated passages, so those passages act as negatives for this question, which makes batch size directly increase training signal.

CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-07

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert NLP Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement