AI Wiki中文/EN

Retrieval-augmented generation: who supplies the answer?

检索增强生成

Train a finite generator and compare sequence-level and token-level document marginalization.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

An open-book answer still needs a reader

An invented museum has two exhibits: Orion opens Tuesday at noon; Lyra opens Friday at dusk. The system must first find the right notice, then produce an answer. Returning the Lyra notice with a confident Orion answer is a retrieval problem. Finding the Orion notice and answering “Monday” is a generation problem. These failures call for different repairs.

Retrieval-augmented generation, or RAG, conditions generation on retrieved information. The 2020 RAG paper combines a trainable retriever with a sequence generator, treating the selected document as a latent variable. It distinguishes parametric memory in generator weights from nonparametric memory in an indexed collection. DPR supplies the dense passage retrieval component. RAG, sections 2.1–2.4 DPR

Many systems called RAG retrieve several passages, concatenate them into a prompt and generate once. That is a useful broader architecture, but it does not by itself implement the original paper’s probability marginalization. Begin with a retrieval-only result page or an exact structured lookup when those already meet the user’s need; generation adds flexibility and another source of error.

Equal document priors expose the difference between whole-answer and per-token marginalization.
Equal document priors expose the difference between whole-answer and per-token marginalization.

One document per answer, or one per token?

Let x be the question, z a candidate document and y a token sequence. With query and document encoders, our finite-candidate notation uses a normalized retrieval distribution:

rz=pη(z∣x)=exp⁡(q(x)⊤d(z))∑z′∈Cexp⁡(q(x)⊤d(z′)).r_z=p_\eta(z\mid x)=\frac{\exp(q(x)^\top d(z))}{\sum_{z'\in C}\exp(q(x)^\top d(z'))}.

C denotes retained candidates. The original method approximates retrieval over a much larger index with top-k documents. Renormalizing over a finite C, as we do here, models a conditional candidate set; it does not recover probability mass lost by retrieving the wrong candidates.

RAG-Sequence keeps the same latent document for the entire answer, then sums its possible contributions:

pseq(y∣x)=∑z∈Crz∏i=1Lpθ(yi∣x,z,y<i).p_{\mathrm{seq}}(y\mid x)=\sum_{z\in C}r_z\prod_{i=1}^{L}p_\theta(y_i\mid x,z,y_{<i}).

RAG-Token instead marginalizes a document separately at each output position:

ptok(y∣x)=∏i=1L∑z∈Crzpθ(yi∣x,z,y<i).p_{\mathrm{tok}}(y\mid x)=\prod_{i=1}^{L}\sum_{z\in C}r_zp_\theta(y_i\mid x,z,y_{<i}).

Moving the sum inside the product matters. A sequence model can preserve correlations induced by a shared document. A token model can combine evidence across documents, but combining pieces does not guarantee that the resulting statement is supported. For a one-token answer the expressions coincide. RAG, physical PDF 3

Training minimizes the negative log probability of the target answer:

L=−log⁡p(y∣x).\mathcal L=-\log p(y\mid x).

The original paper fine-tunes the query encoder and generator while keeping the document encoder and index fixed in the described setup. Our demonstration fixes the retrieval probabilities too, and trains only a small generator. For sequence marginalization, a candidate’s posterior responsibility is:

γz=rz∏ipθ(yi∣x,z,y<i)∑z′rz′∏ipθ(yi∣x,z′,y<i).\gamma_z=\frac{r_z\prod_i p_\theta(y_i\mid x,z,y_{<i})}{\sum_{z'}r_{z'}\prod_i p_\theta(y_i\mid x,z',y_{<i})}.

In our generator, each document and position has its own softmax logits w; positions are conditionally independent given the document. Its gradient is particularly transparent:

∂L∂wziv=γz(pθ(v∣z,i)−1[v=yi]).\frac{\partial\mathcal L}{\partial w_{ziv}}=\gamma_z\bigl(p_\theta(v\mid z,i)-\mathbf1[v=y_i]\bigr).

The document posterior weights the familiar softmax error. The code evaluates likelihood in log space and checks this derivative by finite differences.

Train a generator whose whole distribution fits on a page

Run with Python 3.12 and NumPy 1.26.4. There are two document IDs and two output positions. The first position chooses Tuesday or Friday; the second chooses noon or dusk. The authored training pairs are Orion→00 and Lyra→11, with fixed retrieval probabilities (0.9,0.1) and (0.1,0.9). We initialize all logits to zero and take 300 gradient steps at learning rate 0.8.

"""Trained finite two-token conditional generator, not BART or an LLM."""
import itertools
import json
import numpy as np


def softmax(x):
    x = np.asarray(x, float)
    e = np.exp(x-x.max(axis=-1, keepdims=True))
    return e/e.sum(axis=-1, keepdims=True)


def objective(logits, prior, target):
    # logits[z, position, vocabulary]; independence across positions is deliberate.
    w = np.asarray(logits, float); r = np.asarray(prior, float); y = np.asarray(target, int)
    if w.ndim != 3 or r.shape != (w.shape[0],) or y.shape != (w.shape[1],) or not np.isfinite(w).all() or not np.isfinite(r).all() or (r <= 0).any() or not np.isclose(r.sum(), 1) or (y < 0).any() or (y >= w.shape[2]).any():
        raise ValueError('invalid finite generator inputs')
    logp = w-w.max(axis=-1, keepdims=True)
    logp -= np.log(np.exp(logp).sum(axis=-1, keepdims=True))
    joint = np.log(r)+logp[:,np.arange(len(y)),y].sum(axis=1)
    maximum = joint.max(); log_likelihood = maximum+np.log(np.exp(joint-maximum).sum())
    posterior = np.exp(joint-log_likelihood)
    gradient = softmax(w)
    gradient[:,np.arange(len(y)),y] -= 1
    gradient *= posterior[:,None,None]
    return -float(log_likelihood), gradient, posterior


def sequence_distribution(logits, prior, mode='sequence'):
    if mode not in ['sequence', 'token']:
        raise ValueError('unknown marginalization')
    p = softmax(logits); r = np.asarray(prior, float)
    if r.shape != (p.shape[0],) or not np.isfinite(r).all() or (r < 0).any() or not np.isclose(r.sum(), 1):
        raise ValueError('normalized prior required')
    result = {}
    for y in itertools.product(range(p.shape[-1]), repeat=p.shape[1]):
        selected = p[:,np.arange(len(y)),y]
        value = r@selected.prod(axis=1) if mode=='sequence' else (r@selected).prod()
        result[''.join(map(str,y))] = float(value)
    return result


def train(steps=300, rate=.8):
    if not isinstance(steps,int) or steps < 0 or not np.isfinite(rate) or rate <= 0:
        raise ValueError('invalid training controls')
    # Two authored queries: Orion -> Tuesday/noon (00), Lyra -> Friday/dusk (11).
    priors = [[.9,.1],[.1,.9]]; targets = [[0,0],[1,1]]
    w = np.zeros((2,2,2)); history = []
    for step in range(steps+1):
        rows = [objective(w,r,y) for r,y in zip(priors,targets)]
        history.append(sum(row[0] for row in rows)/2)
        if step < steps:
            w -= rate*sum(row[1] for row in rows)/2
    return w, history


def demo():
    w, history = train()
    seq = sequence_distribution(w,[.5,.5]); token = sequence_distribution(w,[.5,.5],'token')
    orion = sequence_distribution(w,[.9,.1]); swapped = sequence_distribution(w,[.1,.9])
    return dict(loss=[history[0],history[-1]], token_probabilities=softmax(w).tolist(),
                ambiguous_sequence=seq, ambiguous_token=token, orion=orion, swapped=swapped,
                generated=max(orion,key=orion.get), vocabulary=[['Tuesday','Friday'],['noon','dusk']])


if __name__ == '__main__':
    print(json.dumps(demo(), allow_nan=False))

The average loss falls from 1.386294 to about 0.113799. For Orion, sequence probabilities are approximately 0.892438 for 00 and 0.099175 for 11. Enumerating the four possible answers selects “Tuesday noon.” Swapping the retrieval probabilities instead selects “Friday dusk.” The generator is trained and genuinely defines an output distribution, but the fixture does not embed or search text: its retrieval probabilities are supplied explicitly.

With an ambiguous retrieval prior (0.5,0.5), RAG-Sequence assigns about 0.495807 each to 00 and 11, and 0.004193 each to the mixed answers 01 and 10. RAG-Token assigns 0.25 to every answer here. Its separate document sums lose the shared-document correlation in this deliberately position-independent generator. This is not a general claim that every RAG-Token model generates incoherent answers; a full autoregressive generator also conditions on previous tokens.

One training example costs O(KLV) for K candidates, L positions and vocabulary size V in this table model. Enumerating every answer costs O(V to the power L times KL), so our exact decoder is practical only for tiny fixed outputs. The original paper uses beam-based decoding approximations instead. RAG, section 2.5

Retrieval is not a truth certificate

The example has no text encoder, real corpus search, autoregressive state, end token, retriever training or pretrained language knowledge. A document ID selects a parameter table; editing a notice’s text would not automatically change the table. This limitation is precisely why it must not be presented as a deployable knowledge-updating RAG service.

In a real pipeline, record source versions, chunk offsets, retrieval scores, context selection and citations. Evaluate no-context, retrieved-context and oracle-context conditions to distinguish missing evidence from failure to use available evidence. Costs include embedding and index maintenance, search, reranking and generator input/output tokens. The toy loss measures none of those operational costs.

Retrieved content can be outdated, conflicting or malicious. Treat it as data rather than instructions, and allow a supported “not enough evidence” response. Citations must identify the passages that actually support a claim; appending a document title after generation is not verification.

Follow the probability mass

  1. Explain. Does putting retrieved passages in a prompt implement RAG-Sequence? Answer: Not necessarily. RAG-Sequence sums complete-answer probabilities across latent document choices. A single prompt containing all passages can define a different conditional model.
  2. Calculate. Two documents have equal prior weight. Each assigns probability 0.9 to its own token and 0.1 to the other at both positions. What is the probability of 01? Answer: Sequence marginalization gives 0.5×0.9×0.1+0.5×0.1×0.9=0.09. Token marginalization gives 0.5×0.5=0.25.
  3. Modify. Swap the Orion retrieval prior after training. What changes? Answer: The most probable output changes from 00 to 11 while generator parameters remain fixed. This isolates the influence of retrieval probabilities in the finite model.
  4. Investigate. How would you diagnose a wrong real-world answer? Answer: Check whether relevant current evidence was retrieved, whether context packing retained it, whether the answer follows it and whether the cited passage supports the exact claim. Compare to an oracle-context run rather than assigning every error to the generator.

A family name and a specific model

The original RAG paper provides the two latent-document objectives; DPR explains the dense retrieval component. Contemporary retrieval-plus-generation designs may choose different objectives, indexes and context assemblers. Continue with chunking, RAG evaluation and GraphRAG to examine those separate choices. The museum calculation is original and does not reproduce the papers’ benchmark results.

Make a prediction, then check

Are RAG-Sequence and RAG-Token necessarily different for a one-token answer?

Choose one answer

Learning objectives

  • Derive the two original RAG objectives and test a generator under changed retrieval evidence.
  • Run the original example, explain its counterexample and identify the untested deployment assumptions.

Prerequisites & connections

Explore related knowledge →

References

  1. Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks — arXiv v1
    Patrick Lewis; Ethan Perez; Aleksandra Piktus; Fabio Petroni; Vladimir Karpukhin; Naman Goyal; Heinrich Küttler; Mike Lewis; Wen-tau Yih; Tim Rocktäschel; Sebastian Riedel; Douwe Kiela · 2020
  2. Dense Passage Retrieval for Open-Domain Question Answering — arXiv v1
    Vladimir Karpukhin; Barlas Oğuz; Sewon Min; Ledell Wu; Sergey Edunov; Danqi Chen; Wen-tau Yih · 2020

Version1 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Codex · 2026-09-20 · Single AI author. Recorded source scopes (some exact source objects reused from earlier checks): Read PDF 1 identity, 2 methods opening, 3 methods and 4 training/decoding; viewed PDF 3 equations. No BART/DPR training or benchmark reproduction. Viewed physical PDF3–4: independent encoders, dot product, loss and negatives. Read PDF5 hybrid-score paragraph; v1 author list differs from final proceedings. 6 paired equations and four explained exercises. Trained a finite document-conditioned generator; checked finite-difference gradient, normalization, one-token equivalence, hand marginalization and swapped retrieval priors. No text encoder, autoregression or retriever training.

  • Trained a finite document-conditioned generator; checked finite-difference gradient, normalization, one-token equivalence, hand marginalization and swapped retrieval priors. No text encoder, autoregression or retriever training.
  • Four computed SVG variants per topic;12 numeric/geometry tests and42 responsive cases passed. Fourteen selected final captures directly viewed. Full article acceptance recorded separately.

Source locations checked:

Related topics

No matches. Try a synonym or acronym.

0 results shown

Wrap the whole query in double quotes for a phrase match.