Macalinao StudioLearnAll lessons ↗

TAKE THE LONGER ROUTE

Open the complete college lesson →

Worked explanations, full local narration, and connected Signal Room, Workbench and Field Notes.

SIGNAL ROOM

RAG + PromptingUnderstand the moving parts.

Semantic search, hybrid retrieval, GraphRAG.

Suggested preparation: 05

WORKBENCH / CHANGE ONE THING

Choose how much evidence to retrieve

Increase top-k over a labeled toy ranking and compare precision with recall.

Computed teaching example · fixed assumptions shown below

LISTEN & FOLLOW / GUIDED RECAP

Audio starts only when you choose.

FIELD NOTES / THE COMPLETE READING

Take the longer way.

The full lesson narrative, equations and code. Switch views without losing your place.

A slower starting point

Find relevant pages first, then answer with evidence from those pages.

Where this deserves more time

Chunk boundaries; retriever evaluation; discrete top-k; citations and prompt injection.

Open the complete high-school reading

Moment 01 / 09

Overview of Retrieval-Augmented Generation (RAG)

Today we begin with Retrieval-Augmented Generation, or RAG, a framework that conditions language model outputs on externally retrieved knowledge at inference time. This directly addresses the core limitations of frozen, parametric-only large language models.

First, consider those limitations. A frozen model's knowledge is fixed at the training checkpoint; it cannot update or verify facts post-training, so it hallucinates—producing fluent but factually incorrect completions with high confidence.

RAG reframes generation as an open-book examination. A retriever queries an external corpus, and the generator conditions on the returned passages, grounding its logits in retrieved evidence and measurably reducing hallucination rates.

A vital component is data ingestion. Documents are segmented into chunks—typically a few hundred tokens with overlap—and encoded by an embedding model into dense vectors, enabling retrieval of semantically related passages at query time.

Dense vector databases store these high-dimensional embeddings and serve approximate nearest-neighbor search—HNSW or inverted-file indexes—delivering sublinear retrieval latency over millions of passages.

Lastly, semantic search and hybrid retrieval combine dense embedding similarity with sparse lexical methods like BM25, fusing both signals to improve recall and precision of the passages passed to the generator.

In summary, RAG couples retrieval with generation: chunked document embeddings in a vector index let the model access knowledge beyond its parameters, decoupling memory from the weights themselves.

Equations, code and original cards

Overview of Retrieval-Augmented Generation (RAG)

Limitations of Frozen LLMs

• Knowledge fixed at training cutoff

• Hallucination: confident, false completions

RAG as "Open-Book Test"

• Conditions generation on retrieved passages

• Grounds outputs in external corpora

Data Ingestion Essentials

• Chunking: ~200–500 tokens, with overlap

• Dense embeddings encode semantics

Dense Vector Databases

• Store high-dimensional embeddings

• Approximate nearest-neighbor search (HNSW, IVF)

Semantic Search & Hybrid Retrieval

• Dense similarity beyond keyword match

• Fuse sparse BM25 with dense retrieval

Moment 02 / 09

Mathematical Foundations of RAG

Welcome. Today we develop the mathematical foundations of Retrieval-Augmented Generation, RAG, the framework that couples parametric language models with non-parametric retrieval. We will formalize the embedding geometry, the contrastive objectives, and the gradient flow that make these systems trainable end to end.

Begin with embedding generation. Input tokens form a matrix X in n-by-d real space; a learned projection, E equals X W plus b, maps them into a dense semantic space. The inductive bias here is that cosine proximity in that space should track semantic relatedness.

Next, the contrastive loss, essentially the InfoNCE objective. It is a softmax over similarities: the negative log of the positive pair's exponentiated similarity, temperature-scaled, over the sum across all candidates. Minimizing it pulls positive pairs together and repels in-batch negatives.

We then derive gradients for both modules. For the retrieval projection, the gradient of the loss with respect to W is X transpose times the residual, predictions minus targets. The generator receives gradients through the decoder; joint optimization keeps the full pipeline differentiable.

These foundations support the extensions ahead: augmenting the context window with retrieved passages, and hybrid retrieval that interpolates sparse lexical scores, such as BM25, with dense embedding similarity for stronger recall.

To summarize: embeddings define the geometry, the contrastive loss shapes that geometry, while discrete top-k selection is not generally differentiable; retriever and generator training must specify how each receives a learning signal.

Equations, code and original cards

Mathematical Foundations of Retrieval-Augmented Generation (RAG)

1. Embedding Generation

• Input matrix: \(X \in \mathbb{R}^{n \times d}\)

• Embeddings: \(E = XW + b\), with
\(W \in \mathbb{R}^{d \times k}, b \in \mathbb{R}^k\)

• Inductive bias: cosine proximity \(\approx\) semantic relatedness

2. Contrastive Loss (InfoNCE)

• Softmax over similarities:
\(\mathcal{L} = -\log\frac{\exp(\text{sim}(q, p^+) / \tau)}{\sum_{p\in P} \exp(\text{sim}(q, p)/\tau)}\)

• \(q\): query embedding, \(p^+\): positive doc embedding

• \(\tau\): softmax temperature; in-batch negatives \(P\)

3. Gradient Derivations for Retrieval & Generation• Retrieval module gradient:
\(\nabla_W \mathcal{L} = X^T (\hat{y} - y)\)• Generator: backpropagation through the decoder• Joint optimization keeps the pipeline end-to-end differentiable# PyTorch example snippet
loss.backward()  # Computes gradients automatically

Moment 03 / 09

RAG Pipeline: Step-by-Step Diagram and Explanation

Walk the RAG pipeline left to right. Ingestion first: documents are segmented into chunks, typically a few hundred tokens with overlap so semantic units are not split at boundaries.

Next, the embedding node. A bi-encoder maps each chunk to a dense vector in, say, 768 or 1536 dimensions, trained so that cosine proximity tracks semantic similarity.

At query time we embed the question with the same encoder and run approximate nearest neighbor search, inner product or cosine, over the index to fetch the top-k chunks.

Retrieved chunks are then concatenated into the prompt as context, subject to the context window budget. This is the augmentation step; the model's weights never change.

Finally, generation: the language model conditions on the augmented prompt, so its output distribution is grounded in retrieved evidence rather than parametric memory alone.

Equations, code and original cards

Moment 04 / 09

Implementation Details: Python and PyTorch

Here we make retrieval augmented generation concrete in Python and PyTorch: fixed token chunks with overlap, a bi encoder embedding model, an approximate vector index, and a generator conditioned on the retrieved evidence.

The chunking code is not cosmetic: token windows with overlap control recall, boundary effects, and index size. The encoder maps each chunk to a dense vector, trained contrastively so relevant passages cluster near their queries.

Querying is a nearest neighbor problem under cosine similarity, equivalent to inner product after ell two normalization. At corpus scale we use approximate indexes such as HNSW or IVF rather than exhaustive scan.

The module skeleton is simple, but do not assume gradients flow through top k retrieval; that operation is discrete. RAG marginalizes over retrieved documents, while encoders are usually trained with a contrastive objective.

Prompt augmentation then serializes evidence with citations, delimiters, and instructions, so the generator can attribute claims instead of hallucinating from parametric memory.

For throughput, batch encoding, cache embeddings, shard the index, and tune recall against latency; measure end to end quality, not nearest neighbor recall alone.

The implementation pattern is therefore: chunk, embed, index, retrieve, augment, generate, then evaluate faithfulness and answer accuracy under ablation.

Equations, code and original cards

Implementation Details: Python and PyTorch

• Token windows + overlap
• Bi-encoder embeddings
chunks = split_tokens(text, size=512, stride=64)
emb = encoder.encode(chunks, normalize=True)
• Approximate kNN query
• Cosine = normalized inner product
results = index.search(q_vec, k=5,
 metric='cosine', ef=64)
import torch.nn as nn
class RAGModule(nn.Module):
    def __init__(self, retriever, generator):
        super().__init__()
        self.retriever = retriever  # discrete top-k
        self.generator = generator

    def forward(self, input_ids):
        docs, scores = self.retriever(input_ids)
        logits = self.generator(docs, input_ids)
        return marginalize(logits, scores)

Moment 05 / 09

State-of-the-Art Optimizations (2024-2026)

We turn now to state-of-the-art optimizations in retrieval-augmented generation spanning 2024 through 2026, where the research frontier has shifted from simply retrieving documents to jointly optimizing retrieval quality, memory footprint, and grounding fidelity.

First, scalable retrieval and memory optimization. Modern systems index billions of passages using approximate nearest neighbor search over compressed embeddings, trading a small recall penalty for orders-of-magnitude reductions in latency and storage.

This expression formalizes the memory-versus-recall tradeoff: product quantization and residual coding compress each embedding vector into compact codes, so index size scales sublinearly in corpus size while retrieval accuracy degrades gracefully.

Next, this PyTorch snippet illustrates a hybrid retrieval pipeline: a projection layer reduces embedding dimensionality, a sparse inverted index captures exact lexical matches, and dense retrieval supplies semantic recall, with the two signals fused at ranking time.

Beyond retrieval, alignment techniques constrain the generator to ground its outputs in retrieved evidence, reducing hallucination. Hybrid sparse-dense indexing proves especially effective for multimodal corpora and streaming data, where lexical and semantic signals are complementary.

To summarize: compressed indexing, hybrid retrieval, and grounding-aware alignment collectively define the current frontier. These are the mechanisms that make retrieval-augmented systems scalable, factually reliable, and adaptive to real-time workloads.

Equations, code and original cards

State-of-the-Art Optimizations (2024-2026)

• Scalable retrieval: ANN search over compressed embeddings

• Grounding alignment to suppress hallucination

• Hybrid sparse-dense indexing: lexical + semantic recall

• Embedding compression via product quantization

• Extending RAG to multimodal and streaming data

\text{Memory Optimization: }\\ \quad \underbrace{\text{Index Size Reduction}}_{\text{Sparse}} + \underbrace{\text{Embedding Compression}}_{\text{Dense}} \\ \quad = \text{Hybrid Sparse-Dense Index Structure}
import torchembedding_model = torch.nn.Linear(768, 256)  # Dimensionality reductionsparse_index = build_sparse_index(documents)dense_embedding = embedding_model(query)hybrid_search_results = hybrid_retrieve(dense_embedding, sparse_index)

Moment 06 / 09

GraphRAG: From Local to Global Summarization Visualization

Explore the GraphRAG visualization: it operationalizes query-focused summarization by lifting retrieval from isolated chunks to an entity-relation graph, as in Edge et al. 2024.

Each node embeds an extracted entity, each edge a claimed relation; community detection partitions the graph into hierarchical clusters for summarization.

Zoom from a local neighborhood to a community summary and ask which evidence survives aggregation; the global answer is only as faithful as those intermediate summaries.

Equations, code and original cards

Moment 07 / 09

Advanced Variations and Open Research Questions

Let's push past baseline retrieval augmented generation into the open problems: multi-hop evidence composition, multimodal indexes, long-context latency, and alignment, where Lewis and colleagues twenty twenty still frames the tradeoffs.

Multi-hop systems chain retrieval and generation, so each hop rewrites the query using the residual evidence already gathered; multimodal variants embed text, images, and audio into one index, which improves coverage but makes relevance scoring and provenance much harder.

Retrieval can serve as in-context learning: frozen models condition on freshly retrieved passages as exemplars or evidence, gaining domain adaptation without touching weights, though prompt position and citation faithfulness become variables.

Long-context scaling is not free: dense retrieval over millions of chunks needs approximate nearest neighbor indexes, while long-window attention raises latency; Liu and colleagues twenty twenty three showed information is lost in the middle.

Preference optimization can align the pipeline end to end: reward grounded, cited answers and penalize unsupported claims, as in InstructGPT style reinforcement learning, while DPO gives a cheaper offline surrogate.

The hard problems are evaluation and causality: hallucinations persist when retrieval is irrelevant, attention maps rarely explain provenance, and web corpora import selection bias, stale facts, and near duplicates.

The frontier is systems-level: retriever, index, context compressor, and generator must be trained and audited together, because small retrieval errors compound into confident, well-phrased mistakes at scale.

Equations, code and original cards

Advanced Variations and Open Research Questions

From Lewis et al. 2020 to RETRO: open problems in retrieval augmentation

1. Multi-hop & Multi-modal RAG

• Iterative query reformulation over evidence chains

• Shared embeddings for text, image, and audio indexes

2. Retrieval Combined with In-Context Learning

• Retrieved passages as exemplars and evidence, not parameters

• Frozen weights; behavior shifts via prompt context

• Risk: position bias and unfaithful citations

3. Challenges in Long-Context Scaling & Latency

• Approximate nearest neighbor indexes under million-scale corpora

• Long windows: latency, cost, and lost-in-the-middle effects

4. RL and Preference Optimization for Alignment

• Reward grounded, cited answers; penalize unsupported claims

• InstructGPT-style RLHF; DPO as offline surrogate

5. Open Issues in RAG Research

• Hallucination under irrelevant retrieval • Interpretability of provenance • Bias, staleness, and duplication in web corpora

Moment 08 / 09

Challenging Quiz on RAG Concepts and Computations

Now we probe whether the retrieval-augmented generation mechanics actually landed: grounding versus parametric recall, the dense retriever's inner-product search, and where hallucination enters when retrieval fails. Work each problem before submitting.

After you submit, we will walk the solutions together, and I will flag the failure modes that most often trip students on RAG systems.

Equations, code and original cards

Moment 09 / 09

Summary and Key Takeaways

We close by rebuilding the RAG pipeline end to end: query encoder, dense index, retriever, generator, all trained against cross entropy. The inductive bias is explicit: ground generation in retrieved evidence, not parametric memory alone.

The probabilistic core is a latent document variable: the retriever scores candidates, the generator conditions on the evidence, and training marginalizes or uses the top k as a tractable approximation.

In words: the probability of an answer given the query equals the sum over retrieved documents of the document posterior times the answer likelihood given query and document. This is the Lewis and colleagues twenty twenty marginalization; exact summation is intractable, so we truncate to top k.

The PyTorch skeleton mirrors that factorization: encode the query, retrieve nearest passages by inner product, concatenate evidence, then decode. Production swaps this toy loop for batching, mixed precision, approximate nearest neighbor search, and cached embeddings.

Frontier work pushes graph-structured retrieval, better rerankers, faithfulness metrics, and index refresh under drifting corpora. The open problems are attribution, hallucination control, latency at billion-scale, and evaluation that rewards evidence use rather than fluent guessing.

Equations, code and original cards

RAG: Summary and Key Takeaways

• Retriever–generator factorization and pipeline invariants
• Latent-document marginalization; top k truncation
• Dual-encoder scoring, cross-entropy, and ablations
• Graph-structured retrieval, reranking, faithfulness
• Open problems: attribution, latency, drifting indexes

Latent-Document Marginalization

p(\mathbf{a}|\mathbf{q}) = \sum_{r \in R} p(\mathbf{a}|r,\mathbf{q}) p(r|\mathbf{q})

Minimal RAG Inference

import torchdef rag_inference(query, retriever, generator):  docs, scores = retriever.topk(query, k=5)  logits = generator(query, docs)  return generator.decode(logits, scores)

MAKE IT YOURS

Explain the change.

References, scope & corrections

Research snapshots in the source material are not a claim of current state of the art. The reference review corrects identified errors; it is not exhaustive certification of every historical statement. Source code snippets are examples, not a tested production training system.

1 correction entries · expansion notes

Reset this lesson?

This removes only this lesson’s saved notes, experiments and progress.