00-START-HERE · 01-READING-ROUTES · 25_routing_and_adaptive_retrieval · 27_fine_tuning_the_generator Purpose: Explain why a single retrieval call fails when the useful query appears only after reasoning begins, then compare the retrieval-augmented generation (RAG) control loops that retrieve again, critique evidence, learn search behavior, fan out across sources, and stop before extra rounds reduce value.
TL;DR
- One-shot retrieval fixes its query and context before generation. Hidden bridges may need another search; unresolved references can instead need a history-aware rewrite, and stale evidence needs a currency-aware check.
- ITER-RETGEN feeds a draft into the next retrieval query and replaces the retrieved set. With fixed chunk lengths, each generator prompt stays bounded and cumulative full-replay prompt work grows linearly with rounds.
- Recursive methods derive the next hop from partial reasoning. IRCoT accumulates passages and reasoning; Self-Ask retains short question-answer history, trading evidence detail for a smaller context.
- FLARE tests ordinary draft-token probabilities. Accept a non-triggering draft; on a trigger, mask uncertain spans, retrieve and regenerate. Confidence is not a factuality certificate.
- CRAG uses a separately trained evaluator and two thresholds. The ambiguous band can preserve useful local evidence while adding web results, but does not guarantee zero answer harm.
- Self-RAG learns reflection tokens. Ranking candidates costs candidate decoding; low reflection-token overhead does not make the branches free or their critiques independent.
- Search-R1 trains policy-generated reasoning, searches and answers while treating retrieved information as context, not authored actions. GRPO removes a learned critic but needs sampled groups; identical rewards give zero reward advantages, not necessarily zero total gradient.
- Agent fan-out can overlap source-specific work or reduce context-attention work, at the price of duplicated prompts, summaries and coordination. Stop using a validated marginal-value model, not confidence alone; keep hard resource and safety caps.
The story
Imagine a field team crossing a chain of islands with one radio call to headquarters. The first island is easy to name from the mission brief. The second is reachable only after the team reads a sign on the first. A dispatcher with one frozen query may not name the next island before seeing its sign. ITER-RETGEN lets the scout radio back a draft route; headquarters joins that draft to the original mission and sends a replacement map. A map index that already links the islands could sometimes find both at once, so the analogy is a failure mode, not an impossibility theorem. IRCoT keeps maps and reasoning in a growing field notebook. Self-Ask retains short questions and intermediate answers instead of every map. Its notes are lighter, but they still grow and may omit qualifiers or provenance needed later. FLARE sends a scout ahead and masks uncertain guesses before requesting another map. CRAG adds a separately trained inspector who filters useful maps, replaces bad ones, and supplements ambiguous ones. Separate training does not make inspector errors statistically independent of the scout’s errors. Self-RAG gives the scout compact learned signal flags, but sending a scout down every candidate trail still costs work. Search-R1 lets terminal reward shape policy actions. If every expedition receives the same reward, GRPO’s reward-advantage signal vanishes; regularization or other loss terms may still update the policy. Agentic retrieval sends separate teams to separate sources. Parallel follow-ups can help, and splitting large contexts can also help before any follow-up; summaries and coordination can erase those gains. Stop when expected evidence benefit no longer compensates for dilution and resource cost, with uncertainty and hard caps stated.
Decoder table
| Term | Decode | Operational consequence |
|---|---|---|
| One-shot retrieval | Select top- context for one generator call; retrieval may include reranking | No adaptive retrieval from a newly generated bridge unless a return edge is added |
| Answer drift | A fluent answer is supported by the supplied context but answers the wrong implied question | Groundedness can remain green |
| Unresolved reference | The surface query omits a referent stored in dialogue history | Rewrite to a self-contained query before retrieval |
| Stale-but-relevant retrieval | Topically relevant evidence is outdated or temporally contradictory | Relevance-only recall may miss it; currency-aware gold and checks can detect it |
| Bridge entity | Entity discovered at hop that helps query hop | Sequential discovery can be needed, but a missing literal name alone is not an impossibility proof |
| , , , , , , , , , , , and | Corpus, document, context, retrieval depth, corpus size, score, answer distribution, required facts, source documents, chain depth, recall and bridge | Joint evidence coverage requires conditional factors or an explicit independence assumption |
| Original user query | It anchors later query rewrites | |
| Self-contained information need reconstructed from query and history | It resolves references before ranking | |
| Passages selected at round | Replacement bounds passage volume only with fixed chunk lengths; preserve earlier support when needed | |
| Generated draft or partial answer at round | It can reveal the missing bridge entity | |
| , , , , | Query size, chunk size, rounds, first-hop recall and second-hop conditional recall | Chunk-size symbol is local; conditional recall avoids an unstated independence assumption |
| ITER-RETGEN | Alternate retrieval and generation using joined to the prior draft | Fixed-length replacement gives bounded per-round generator prompts and linear cumulative replay work |
| Iterative retrieval | Repeat retrieval with a revised version of the same information need | A draft often drives the revision |
| Recursive retrieval | Emit a new reasoning step or sub-question whose answer determines the next hop | Queries can differ semantically across hops |
| Static fan-out | Prepare subqueries before seeing their results, then retrieve concurrently | Useful when the dependency topology permits it; fixed fan-out does not need agents |
| Reciprocal Rank Fusion (RRF) | Fuse several ranked lists without needing comparable raw scores | Useful after independent parallel retrieval |
| IRCoT | Derive a reasoning-sentence query and retain passages plus reasoning | Full replay grows quadratically; caches and final-reader design change the ledger |
| Self-Ask | Derive follow-up questions and retain short intermediate Q/A history | Less raw passage text, but growing history and possible loss of qualifications or provenance |
| Conditional retrieval rate when the current subject is named | Constant along successful paths only as an explicit scenario assumption | |
| Conditional retrieval rate when that subject is not named | Can be low on bridges, but need not be zero or universal across corpora | |
| Correct bridge extraction conditional on preceding successful evidence | Compounds along a successful path; no-retry powers are not final answer accuracy | |
| , , , , , , and | Path probabilities, sentence tokens, sentence count, token time, whole retrieval-path time and ordinary token probability | These symbols are local to the recursive and FLARE sections |
| Compositionality gap | Compositional failure despite correct isolated component answers | The reported GPT-3 result does not establish a model-family-independent law |
| FLARE | Draft a sentence; accept if no trigger, otherwise retrieve and regenerate | Only fired drafts are discarded in the break-even ledger |
| Threshold for the minimum probability of the drafted tokens | A confidence heuristic, not a factuality probability | |
| Threshold defining tokens or spans masked in a retrieval query | With matching strict tests, covers all triggering tokens | |
| Implicit FLARE query | Mask uncertain spans and retrieve using the remainder | No additional query-generation call beyond the draft; retrieval and context handling still cost work |
| Explicit FLARE query | Generate one question for each uncertain span | Charge query decode/input processing; spans need not be single tokens |
| Implicit break-even rate | Requires reused non-triggering drafts and equal-length regenerations; explicit-query costs lower it | |
| CRAG | Grade the retrieved set, then filter local evidence, use web evidence, or do both | Adds an explicit correction point |
| Lower boundary on a learned evaluator score | Below it is INCORRECT; equality is assigned to AMBIGUOUS here | |
| Upper boundary on a learned evaluator score | Above it is CORRECT; equality is assigned to AMBIGUOUS here | |
| INCORRECT | Discard local results, rewrite to keywords, search the web | A false positive here can delete a correct local answer |
| AMBIGUOUS | Retain filtered local evidence and append filtered web evidence | Mitigates false discard, but does not guarantee unchanged reader accuracy |
| CORRECT | Rescore strips and recompose selected local evidence | Can cut boilerplate or accidentally delete needed qualifiers |
| Knowledge strip | A sentence or two cut from a retrieved chunk and rescored | Fine-grained evidence filtering |
| , , | Answer-accuracy change, useful-local-evidence presence and reader accuracy when evidence is useful | Multiply the presence-change expression by the reader factor under the stated model |
| Probability of detecting an unhelpful local set | Controls rescue attempts, not final answer correctness by itself | |
| Probability of falsely discarding a helpful local set | Harm depends on web recovery and whether local evidence is preserved | |
| Useful-web-evidence presence after a local miss | Multiply by conditional reader success when converting to answer accuracy | |
| Useful-web-evidence presence after false discard of a useful local hit | Reduces the lost-hit penalty under the constant-reader model | |
| Self-RAG | Add learned reflection-token groups to the generator vocabulary | Critique becomes a decoder probability |
| Retrieve | Reflection group with yes, no, and continue | Gates evidence per segment |
| IsRel | Reflection group with relevant and irrelevant | Judges a retrieved passage |
| IsSup | Reflection group with fully supported, partially supported, and no support | Judges entailment of the generated segment |
| IsUse | Reflection group with ratings 1 through 5 | Rates the completed response |
| Probability of a specified desired token normalized within its reflection group | Not automatically calibrated; ordinal groups can use an explicit expected-rating score | |
| , , , , , , and | Vocabulary, offline critic, generator, input, candidate passage, retained prefix and group weight | Likelihood length convention and reflection-score definitions must be consistent |
| Passage-conditioned candidates per segment | Multiplies decoded candidate work; latency depends on concurrency and capacity | |
| Distilled critic | Local model trained from external labels to annotate generator data offline | Removes teacher calls from serving; does not impose a universal hard teacher-performance ceiling |
| Search-R1 | Policy generates reasoning, searches and answers; the environment inserts retrieved information | The transcript includes observations that are not policy-authored actions |
| PPO | Policy optimization commonly using a learned value baseline | The critic is one unsharded bf16/AdamW scenario, not unavoidable PPO memory |
| GRPO | Compare same-question rollout rewards using group statistics | Avoids a learned critic while paying for sampled rollouts and any retained regularization |
| Number of sampled rollouts for a question | Changes constant-group probability and resource cost; correlated samples need separate analysis | |
| , , , , , , | Advantage, reward, mean, population deviation, success count, observed fraction and true sampling probability | Observed group fraction and underlying probability are not interchangeable |
| Dead group | All sampled rewards are equal, so reward variance is zero | Zero reward advantages do not imply zero KL/auxiliary gradients or optimizer updates |
| Retrieved-span mask | Keep retrieved text as context; exclude prompt and observation positions from policy-action loss and action-level KL | Prevents treating search-engine observations as actions chosen by the policy |
| , , , | Per-search utility penalty, expected terminal correctness, search count and exact match | A one-extra-search threshold is a myopic comparison, not an optimal-policy guarantee |
| Sub-agent | Policy with a private context and configured retrieval/permission scope | Charge summary or structured-evidence production; interfaces need not be exclusive |
| Controller | Policy that dispatches sub-agents and synthesizes their outputs | Owns global step and spend limits |
| Fan-out | Run source-specific work concurrently when dependencies permit | Sum-to-maximum savings require a serialized baseline and enough concurrent capacity |
| , , , , , , | Layers, width, context length, parameters, agent count, additional source rounds and round time | The equal-round crossover is a simplification; actual prefix lengths change append costs |
| Conjunctive reliability | Probability every required agent result is correct | Equals when agents have equal independent accuracy |
| scoreboards | One design with two agent metrics plus dispatch and synthesis | Useful attribution layout, not a universal minimum |
| Path-discovery probability within cap in the no-retry depth-mixture toy | Does not ensure earlier evidence remains in the final prompt or that the answer is correct | |
| Conditional evidence-use surrogate from a fixed gold score versus IID normal distractors | Not a general model of language-model attention or multi-hop utilization | |
| , , , , | Depth share, normal CDF, fixed gold score, fallback accuracy and dilution coefficient | The fixed-gold and no-retry assumptions define the illustrative curve |
| , , , and | Toy answer accuracy, partial latency components and marginal coverage/accuracy | A latency proxy is not measured p95; utility weights must have consistent units |
| Accuracy-maximizing cap among the evaluated options | Three only under the stated accumulating coverage/utilization assumptions | |
| Cap maximizing the specified quality-minus-resource objective | Two in the stated accumulating ledger, including its declared cached variant | |
| Prefix caching | Reuse valid unchanged prefix KV states in an append-only sequence | Requires matching context/model/template; changed prompts or a new reader can invalidate reuse |
| Best Match 25 (BM25) and Embeddings from Bidirectional Encoder Representations (E5) | Sparse term scoring and the dense encoder named in Search-R1 | They represent two retrieval families used in the source |
| Generative Pre-trained Transformer (GPT), Text-to-Text Transfer Transformer (T5), Incomplete Information Reading Comprehension (IIRC), and American Invitational Mathematics Examination (AIME) | Generator and evaluator families, multi-hop reading benchmark, and mathematics benchmark | They decode model names and bound two reported comparisons |
Core mechanics
Mathematical conventions
Use natural logarithms, decimal storage units and full precision until rounding: and . Probabilities and accuracy are fractions; an absolute increase of is one percentage point, not necessarily a one-percent relative increase. Products of hop probabilities below require either explicitly conditional factors or a stated independence model. Discovering a path, retaining its evidence and answering correctly are different events. Where the common -billion-parameter proxy is specified, use , weight-stream bandwidth and two bytes per weight. Thus , linear prefill time per token is , and the batch-one weight-stream component is . These are accounting components, not benchmarks: attention, KV-cache traffic, kernels, utilization, queuing, communication and tool overhead may add cost. The Self-RAG and recursive examples explicitly use different stipulated token rates. Ideal parallel latency requires sufficient concurrent capacity. Prompt positions processed, new input tokens, provider-billed input tokens and output tokens have different denominators. State whether prefixes are replayed, validly cached or billed again. Letters are local to each section: in particular context , chunk size , coverage and critic are distinct; so are the FLARE mask threshold and stopping dilution coefficient . None of the chapter-reported empirical rates or historical examples is established by the arithmetic alone.
26.1 Why one-shot retrieval breaks
What:
- One-shot retrieval selects context once for a generator call: , followed by . The selection may itself include ANN search and reranking; “one-shot” does not mean every document is scored exactly once.
- Let be a retrieval score, a required hop fact, its document, the chain depth and a bridge entity. A frozen-query system cannot use a newly generated bridge to launch another retrieval unless the control flow provides that return edge. Why the failure appears:
- A chain needs facts . Let mean that the selected context contains the evidence for fact .
- The joint evidence probability is a conditional chain product. If instead denotes marginal recall, replacing the conditional factors by requires independence:
For two independent evidence events with , joint coverage is . Correlated retrieval errors need not give this value. A missing bridge can lower recall, but absence of a literal term does not prove that dense retrieval, links or a broader first result cannot recover the second document. Failure without it:
- For an explicit information need about sulfur’s classification, suppose penicillin is only a bridge. Passages about the discovery of penicillin can support “Alexander Fleming, in 1928” while failing to answer that need. The error is responsiveness, not necessarily unsupported text; the question must distinguish the two discoveries.
- In “when did he start the company?”, stoplisting may leave “start” and “company.” Their stipulated IDF contributions, and , sum to . Relative to the self-contained example’s recomputed IDF sum, this is about of the raw IDF total, not a bound on semantic information or answer accuracy. No document frequencies are supplied to rederive those two stipulated contributions.
- A PayPal or Tesla referent already present in turn can be resolved before retrieval; it is not information that inherently arrives after retrieval.
- Topical relevance does not establish current truth. Relevance-only Recall@k can miss staleness; a currency-aware gold set and evaluation can detect it. A high recall score is not, by itself, a certificate of responsiveness or currency. Cost and complexity:
- In a corpus of chunks, use the Robertson–Sparck Jones IDF variant , without the additional inside the logarithm used by another BM25 convention. The document frequencies for penicillin, element, scientist, discovered and found are , , , and .
- Their IDFs are approximately , , , and . Sum before rounding: . Penicillin contributes approximately of this raw IDF sum, not a probability or a proven share of discriminative power.
- The other terms sum to . This is not a BM25 upper bound on a passage lacking penicillin: term-frequency factors can exceed one. For a single occurrence of each query term and , the usual positive-denominator TF factor is bounded above by , giving an other-term supremum of about in this simplified score. Actual lengths and term frequencies still determine the score.
- With and tokens per chunk, retrieved text alone has tokens, beyond an -token window. Include a -token question for tokens. Linear prefills cost approximately and respectively. A prompt with the question is tokens and costs .
- For a matched partial schedule, suppose each retrieval costs and a two-hop route generates only a -token bridge before the common final answer. Its cost is . Wide one-shot costs before the same final answer. The difference is approximately , excluding other overhead. The former / versus millisecond claims omitted or inconsistently priced these components. This is not the two-full--token-round scenario in Section . Mechanism example:
- In the illustrative chemistry chain, hop one exposes sulfur. At document frequency , under the same IDF convention.
- The second query asks who established that sulfur is an element. The reported example points to Lavoisier’s argument; this mathematical pass does not independently verify that historical account.
- Distinguish benchmark configurations: the standard ten-paragraph HotpotQA distractor setting contains two supporting paragraphs and eight distractors, not two plus ten. The full-wiki setting is different. A bridge in the first supporting paragraph motivates sequential retrieval; it does not prove that every first query must miss the other paragraph. Practice decisions:
- Resolve available dialogue references before ranking; a second search is not a substitute for reading the history. Evaluate responsiveness, support and currency separately.
- The source’s -example audit and roughly ten-percent multi-hop routing threshold are workflow heuristics, not statistical guarantees. Failure categories can overlap, and a relevance-only grader need not detect stale evidence.
- Raise only after checking the context and cost budgets. Test whether a bridge-aware rewrite or iterative call improves measured joint evidence retention and downstream answer correctness.
26.2 Iterative retrieval with ITER-RETGEN
What:
- In a toy service graph, one document maps billing-api to prod-ledger-3; another maps prod-ledger-3 to eu-central-1. The bridge is in both documents but absent from the original query and final region answer.
- Let be first-document recall and second-document recall conditional on obtaining the first. One-shot joint recall is then a chain-rule product, without an independence assumption:
- ITER-RETGEN alternates retrieval and generation:
Why:
- The original question anchors generation while the previous draft augments retrieval. Joining a draft can surface a bridge, but can also amplify a hallucinated bridge; validate the resulting evidence.
- Replacing keeps the passage count at . With query length , fixed chunk length and no growing generator history, each generator prompt has tokens. This is bounded per round, not prompt size growing linearly with ; cumulative full-replay prefill grows linearly. Failure without it:
- If the original query gives no discriminating signal for the second document and ranks are exchangeable, its mean rank among chunks is , and uniform top-five inclusion probability is . A missing lexical term alone does not justify that exchangeable-rank model.
- A fully specified query naming prod-ledger-3 cannot be constructed from the original wording if that name is genuinely unknown. A placeholder, graph traversal, prior knowledge or a later adaptive step can change the design.
- Static fan-out is useful when subqueries can be prepared before their results arrive, as in many Postgres-versus-MySQL comparisons. A dependent bridge chain may instead need sequential discovery. Evaluate the dependency topology, not merely the label “multi-hop.” Cost and complexity: For full prompt replay, fixed and , and retained generated tokens per prior round, distinguish three prompt-position ledgers. The accumulating external-token ledger excludes those retained outputs; adding them changes the total:
If , stable retrieval is a possible stopping signal, not a proof of a fixed point. Stochastic decoding, changed drafts and retrieval ties can still change later states or create cycles. An extra round still pays for retrieval and generation, and replacement can lose earlier supporting passages. Worked example:
- Fix , chunk size , question size , and a -billion-parameter fp16 generator. Embedding, ANN search and cross-encoding cost per retrieval in this stipulated ledger; the ANN stage considers candidates. Hold this retrieval cost fixed despite changed query length only as an explicit simplification.
- Let first-hop recall be and second-hop conditional recall under the original query be . Joint one-shot path recall is . Linear prefill of tokens costs ; an -token output costs under the common stream proxy. Total: .
- Wide one-shot with uses conditional factors and , giving joint path recall. Its -token prefill and -token decode total including retrieval, if the context window can hold it.
- With a correct bridge-extraction probability of , the second query contains the correct bridge with probability . Conditional retrieval probability then gives discovered-path probability , approximately times the wide baseline. These are stipulated conditional rates, not measured answer accuracy; ensure the final reader still receives both required facts.
- Two complete -token replacement rounds cost , approximately less than wide one-shot under this ledger. This replaces the inconsistent , and millisecond comparisons rather than propagating them as alternative results.
- For seven accumulating rounds, external prompt positions are . Replaying all prior -token outputs adds , for prompt positions. Linear prefill, decode and retrieval cost approximately , and , totaling , or times the small one-shot ledger. This assumes full replay, no prefix caching and no additional final reader; the former millisecond prefill and millisecond total do not follow from the stated rate. Practice decisions:
- Begin with a small cap such as two or three rounds, then measure cap hits, path retention and answer correctness. These are tuning defaults, not universal optima.
- Keep earlier source identifiers and re-fetch supporting chunks when a replacement draft is not sufficient evidence. A remembered intermediate answer is not a citation.
- On timeout, return a clearly marked partial result, abstain or hand off as appropriate; do not force a confident answer merely because the cap fired.
26.3 Recursive retrieval with IRCoT and Self-Ask
What: For a deliberately simplified -hop chain, let be conditional retrieval success when the subject is named, the conditional rate when it is not, and correct bridge extraction conditional on successful evidence. If one-shot is on-subject only for the first hop and these rates stay constant along successful paths:
A recursive loop that correctly names each next subject has the following successful-path probability under the same stationary conditional-rate model, with no retries, alternate paths or repair. It is not yet the final answer probability:
Why:
- Make the example unambiguous: “Who succeeded the U.S. president in office when the Soviet Union dissolved?” The original “who was president after it dissolved?” could mean George H. W. Bush, not necessarily Bill Clinton.
- The reported chain identifies December and Bush, then asks who succeeded Bush, leading to Clinton’s January inauguration. The mathematical pass does not independently source that chronology.
- The bridge makes a useful next query; it does not prove a knowledgeable retriever or generator could never answer in one step, nor that the November election date must be unknown beforehand. Failure without it: With , and , two-hop one-shot and recursive path probabilities are and . At three hops they are and ; at five hops recursive path success is . The powers describe this conditional toy model, not independent verification of an empirical method. IRCoT mechanism:
- In the IRCoT-style implementation, retrieve on , generate one declarative reasoning sentence using , accumulated passages and prior reasoning, and use that sentence as the next query.
- Append the newly retrieved passages. Stop on a chosen terminator such as “so the answer is” or a hard cap, then run a final reader over the collected evidence. The terminator is a model output, not a guarantee of completeness.
- Declarative sentences can resemble corpus prose and suit lexical retrieval, but their effectiveness must be measured. One sentence per step is an implementation choice, not a universal property of every recursive system. Self-Ask mechanism:
- A Self-Ask-style prompt asks whether follow-up questions are needed, generates one single-hop question, retrieves for that question and records an “Intermediate answer.”
- Raw passages can be dropped after extraction while short questions and answers remain in the history; this reduces passage volume but may lose qualifiers, contradictions and provenance. End with a final answer only after checking the retained evidence is sufficient.
- The reported compositionality-gap result concerns the evaluated GPT-3 family and task, not a theorem about every model family or retrieval architecture. Cost and complexity:
- Full-replay IRCoT passage positions grow as , before adding replayed reasoning and the final reader. Valid prefix caching changes the newly computed positions but not necessarily all attention cost.
- Self-Ask can process a fixed amount of new passage text per hop, hence linear new-document volume. Replaying its growing short question-answer history can still contribute a quadratic term; “shorter” does not mean a constant-size full prompt.
- A catalog pasted into a standard dense-attention prompt is not a B-tree: it generally remains in attention computation rather than pruning disk branches. Sparse attention, learned routing and external indices have different costs, so do not generalize the dense comparison to every architecture. Worked example:
- This separate scenario uses five -token passages, retrieval and output tokens per second. A one-shot -token answer takes in retrieval-plus-decode components only; no prefill rate is given.
- Three IRCoT rounds generating reasoning tokens each, followed by a -token final answer, generate tokens. Retrieval plus decode is , or times the one-shot components. These are not full latency measurements.
- Replayed document positions are including the final reader, excluding question, reasoning and control-token replay. Two Self-Ask follow-ups process new document tokens, a -fold reduction in this scoped document ledger; a full latency comparison also needs its generated questions, intermediate answers and history processing.
- At per million document input positions and one million queries per day, these scoped document bills are , and per day. They exclude other prompt positions, output billing, tool and serving costs.
- The conditional two-hop model predicts a -percentage-point path-coverage gain, from to . Do not equate it with the reported IRCoT gains of up to retrieval-recall points or downstream QA points across HotpotQA, 2WikiMultihopQA, MuSiQue and IIRC.
- Changing to gives one-shot path coverage and an -point gap. The source’s roughly public-benchmark prior is a planning heuristic; measure the actual corpus, queries and conditional rates. Practice decisions:
- Select recursive retrieval when next-query dependencies justify it; select static fan-out when the subqueries are available together. Preserve early support when citations or multi-sentence conditions matter.
- A cap of four retrievals and around three to five are starting heuristics. Inspect cap-hit failures, compression losses and both retrieval and answer metrics under the actual context and percentile-latency budgets.
26.4 Confidence-triggered retrieval with FLARE
What: FLARE drafts the next sentence of tokens, using ordinary model probabilities for its drafted tokens under a defined decoding distribution. These are not probabilities that the tokens are true. If no token crosses the threshold, accept the draft; otherwise retrieve and regenerate the affected sentence.
On a trigger, remove or mask uncertain guessed spans when constructing the query, retrieve passages and regenerate ; discard the fired draft, not every non-triggering draft. Dropping the retrieved passages afterward changes context and may invalidate a cached suffix. Charge that context management where it occurs. Why: A minimum-token gate is sensitive to a single uncertain entity, but rare correct names can have low probability and familiar false statements can have high probability. Longer sentences have more opportunities to trigger. Tune the gate against useful-search and error labels, not just a desired search count. Failure without it: With twenty-four token probabilities of and one of , the arithmetic mean is . It can hide one weak token; neither the mean nor the minimum is a proof of factuality.
Using natural-log token loss, the same draft has perplexity
For all twenty-five probabilities equal to , and . The relative perplexity gap is about . This demonstrates averaging dilution, not a calibrated factuality threshold; rounded exponents must not be connected by exact equality. Implicit and explicit queries:
- An implicit query masks tokens below the mask threshold , for example a draft of “Person X attended [mask] and earned [mask].” It adds no extra query-generation call beyond the already charged draft. Retrieval still costs work, and the remaining frame may be uninformative or combine distinct needs.
- An explicit query generates one question per uncertain span, not necessarily one per token. It separates needs but adds query decoding and input processing.
- The trigger threshold and mask threshold have different roles. With the same strict comparison, covers every triggering token; if , a trigger may mask nothing. Specify span expansion and threshold-boundary handling.
- This implementation needs access to the relevant token probabilities. An API without them needs a different available gate or model interface; a trained Retrieve control token is an alternative architecture, not a feature automatically present in the existing model. Cost and complexity:
- Hold answer length at twelve sentences of twenty-five tokens, with the common stream proxy . Sentence decode is and the -token output costs .
- A retrieval path has embedding, ANN and new retrieved tokens. Their linear prefill costs , so .
- Retrieve-once and retrieve-before-every-sentence components total approximately and . The latter makes twelve searches and injects raw retrieved tokens.
- Implicit FLARE with four triggers reuses the other drafts and adds four regenerated sentences: . It makes four searches and injects raw retrieved tokens.
- Six explicit twelve-token query generations add , for , before their extra input processing. These partial ledgers omit shared answer-history processing, cache changes and other serving overhead; they are not complete wall-clock latencies. Break-even criterion:
- The break-even assumes every non-triggering draft is reused, each triggered draft adds one equal-length regeneration, and all other costs match. An explicit-query cost per trigger changes it to .
- Here . Four triggers in twelve sentences are above it, so implicit FLARE is approximately slower than every-sentence retrieval in these components, while using one third of the searches and raw injected tokens.
- If the entire retrieval path is instead , . If is just web wait, add embedding and prefill before applying the formula.
- The bandwidth calculation is a weight-stream roofline, not measured token latency. Achieving to of that bandwidth would give approximately to for this component. This does not establish an actual batch-one performance range.
- With and , break-even is . With the original stream proxy and it is . Different rate assumptions must not be silently combined into one threshold. Practice decisions:
- Tune trigger and mask policies on sentence lengths, calibration and false positives; low token confidence alone is not missing-evidence detection. Mask uncertain guesses without unnecessarily erasing grounded user entities.
- A twelve-token explicit query costs approximately in this decode component, before its prefill and tool work. Charge all queries generated for multiple spans.
- A cap such as four searches is a product heuristic. Benchmark whole-answer p95, context replay and cache invalidation rather than inferring them from summed mean components.
26.5 Corrective RAG
What:
- CRAG places a separately trained retrieval evaluator between retrieval and generation. It aggregates query-document scores into a set score ; this is not a calibrated correctness probability without validation.
- Choose . Here define INCORRECT as , AMBIGUOUS as , and CORRECT as , so every boundary has a branch.
- CORRECT splits chunks into short strips, rescores and recomposes survivors. INCORRECT discards local results, rewrites the query and filters web results. AMBIGUOUS retains filtered local evidence while adding filtered web results.
- Strip filtering can remove a needed qualifier, and appended evidence can distract. These are architectural mitigations, not correctness guarantees. The reported Self-CRAG system combines this correction layer with Self-RAG. Why: For a binary gate, let be useful-local-evidence presence, detection probability given a local miss, false-discard probability given a useful local hit, and useful-web-evidence presence after those two types of escalation. Assume constant answer accuracy when useful evidence is present and zero otherwise. Then the answer-accuracy change is
- The bracket alone is a change in useful-evidence presence under this model, not answer accuracy unless . The first term is rescued misses and the second useful hits lost after false discard and failed web recovery.
- Sensitivity to relative to sensitivity to missed detection is . At , and , it is , not ; it depends on the web rates, not alone.
- An ambiguous branch that preserves all needed local support can reduce discard harm. Assuming its answer accuracy stays unchanged is an additional reader assumption: longer or conflicting context can still cause harm. Failure without it:
- Retriever similarity measures a ranking objective, not a certified answer-presence probability. It can correlate with containment, but an unanswerable query still has a nearest neighbor.
- A generator grading its own output can share its original blind spots. A separate evaluator changes the model and training objective, but does not establish independent errors or guaranteed decorrelation.
- The chapter reports a separately fine-tuned T5-large evaluator of approximately parameters fitted on PopQA. Calibrate thresholds and check transfer on the new domain; reported scores are not automatically probabilities there. Cost and worked example:
- Stipulate , answer accuracy when useful evidence is present and zero otherwise, evaluator , , and useful-web-presence rates , . A web call costs per thousand calls and of wait.
- Baseline accuracy is . Escalation probability is , not before final rounding. Binary-gate accuracy masses are retained local, rescued local misses and recovery after false discard, totaling .
- Move three quarters of evaluator false positives to AMBIGUOUS and assume their preserved support remains usable with the same . This contributes ; the remaining false-discard branch contributes . Together with retained hits and rescued misses, accuracy is , a gain of points over baseline and points over the binary gate.
- Five evaluator pairs of tokens process positions. The forward proxy is , or at . This is of the linear prefill of tokens through the -billion-parameter generator, not a full serving-overhead ratio.
- At per GPU-hour, a thousand evaluator runs cost approximately . Web cost is per thousand user queries, for total incremental cost. Divide by net additional correct answers to obtain approximately per net improvement; that denominator is not a count of gross wrong-to-right conversions.
- Mean incremental components total . If baseline latency is a common constant and the web delay is exactly two-point, the added p95 is . General p95s cannot be obtained by adding component quantiles; web latency variation and dependence require measurement.
- The reported Self-CRAG PopQA score of , roughly seven points above its own Self-RAG baseline, is a separate experimental result, not validation of this constructed scenario. Practice decisions:
- Fit and validate thresholds on local labels; to queries are the source’s starting heuristic, not a coverage guarantee. Report both false discard of useful sets and failure to escalate unhelpful ones.
- Filtering chunks above roughly tokens is another heuristic. Keep tables, code, negations and cross-sentence qualifiers intact when strip boundaries would destroy their meaning.
- Under overload, local-only serving is not inherently safe. Depending on evidence, access policy and product obligations, abstention, partial answers or handoff may be preferable.
26.6 Self-RAG
What: Self-RAG extends the generator vocabulary with learned reflection groups: Retrieve decisions, IsRel relevance, IsSup support and IsUse ordinal usefulness ratings. For a specified desired token in group , normalize its probability within that group, with a positive denominator:
For passage-conditioned candidate segments, a schematic decode-time ranking combines segment likelihood with weighted reflection scores. Specify the target reflection token or rating expectation used in each group; IsUse can be an expected ordinal score rather than an argmax token. One illustrative score is
The weights are decode-time choices. Group-normalized model scores are not automatically calibrated truth probabilities. Use a consistent sequence-likelihood or length-normalized convention across candidates; otherwise unequal segment lengths can distort the ranking. This schematic is not a claim that every Self-RAG implementation uses exactly this score. Why: Reflection tokens allow structured decisions without a second free-form critique prompt or string parser, and can place retrieval/support checks within generation. They still require decoding, supervision and validation. FLARE’s ordinary token-confidence gate and a learned support-token score are different signals, neither a factuality guarantee. Training and claim limit:
- In the reported training recipe, an expensive teacher labels a seed set, a critic is distilled from it, annotates the generator corpus offline and generator learns content plus reflection tokens with next-token training. The offline critic is not called at serving time.
- A scenario with teacher calls and local critic calls uses times fewer teacher calls than directly labeling all examples with the teacher. This does not mean a -fold reduction in total training cost.
- Noisy teacher judgments can limit the student, but there is no universal theorem that a distilled student cannot outperform its teacher on a task after other data or learning. Content and critique sharing serving weights can correlate errors; separate CRAG weights do not establish statistical independence either. Cost and worked example:
- This separate scenario stipulates output tokens per second per active stream and prefill positions per second. Use , -token passages, a -token question/instruction and four -token answer segments. Vanilla RAG processes prompt positions and output tokens: .
- Charge content plus three reflection tokens per candidate segment. All five candidates per segment give decoded tokens. This counts the specified three reflections only; any extra closing or control tokens must be added in an implementation.
- A declared cache/reseed schedule processes initial prompt positions and winner-prefix refresh positions, for positions and prefill. It keeps one winner per segment, not an exponentially growing beam. Charging every branch refresh is a conservative choice; the winning branch may reuse its valid KV state, while replaying without caches costs more.
- Only if five-way batching maintains tokens per second per stream does decode take . Total is then , or times vanilla latency. Without this extra capacity, serial decode is , totaling under the same prefill ledger. A latency premium is conditional, not a measured universal result.
- Decode work is times baseline. Of the extra tokens, are reflection and discarded candidate content; reflection is of extra decode. At , decode is tokens, or times baseline work, not necessarily latency.
- As a component-only comparison, extra decode uses billion-parameter-token units. A -billion-parameter evaluator processing input positions uses such units, a ratio of . This excludes Self-RAG’s extra prefill positions, attention, batching differences and control costs; it is not a full cost comparison. The earlier CRAG example used , not , evaluator input positions. Practice decisions: Choose and reflection weights on held-out quality, support, latency and cost measurements. A support label is a learned judgment, not proof. Tune the branch budget to available capacity, preserve citations for the selected branch and report total candidate work alongside wall time.
26.7 Search-R1, GRPO, and learned stopping
What:
- In the described Search-R1 interface, the policy generates reasoning, search requests and final answers. A search closing tag pauses the policy, E5 retrieval returns the top three Wikipedia passages inside information tags and decoding resumes.
- Retrieved information is an environment observation conditioned on by later policy actions; the policy did not author the search engine’s text. Distinguish the interleaved transcript from the action sequence.
- The source describes a baseline with exact-match terminal reward and no explicit format, process or search-count reward. That is a version-specific recipe, not a restriction on every search-trained policy. Treat retrieved text as untrusted tool data, not new instructions. Why GRPO:
- PPO commonly uses a learned value baseline; GRPO instead compares sampled rollouts for one question. Sampling groups has a cost even when the baseline is a simple mean.
- For an unsharded -billion-parameter bf16 critic under the specified AdamW accounting, weights and gradients are each, while fp32 master weights and two fp32 moments are each. Total training state is , excluding activations, caches, actor and reference models.
- This is not unavoidable PPO critic memory: critic size, shared trunks, sharding, optimizer precision and offload change it. Define the population-standard-deviation group advantage as follows, setting it to zero for an exactly constant-reward group:
- For binary rewards and successes, let be the empirical group success fraction, distinct from a true sampling probability. If , success advantage is and failure advantage is under the population variance above.
- At with one success, advantages are and four copies of . With two successes, the positive value is and the negative value is , with .
- Advantages sum to zero in a nonconstant group, but the weighted policy gradients do not generally cancel. Using sample variance, an epsilon or a different normalization changes the magnitudes. Group-relative normalization is not automatically an unbiased gradient estimator for expected exact match. Failure without safeguards: If every reward is identical, these reward advantages are zero. This eliminates the reward-advantage term, not necessarily the entire training gradient: KL regularization, entropy, auxiliary losses, weight decay or optimizer state can still cause updates. For conditionally IID binary-reward rollouts with true success probability , the probability of a constant-reward group is
- At , constant-reward probabilities are for , for and for . At , gives approximately . Correlated samples or nonbinary total rewards need a different calculation.
- An -token transcript with prompt, policy-generated and retrieved tokens has a retrieved fraction .
- Mask prompt and retrieved observation positions out of the policy-action loss and the action-level policy/reference KL penalty. Keep them in the model context so later policy actions can depend on them; masking loss does not erase context or its forward cost.
- Scoring the search engine’s observed tokens as policy actions would add an imitation/language-model objective, not the standard KL over controllable actions. Observation text being legitimate context is not a reason to penalize its token likelihood as if the policy chose it. Search cost objective:
- Exact-match reward alone does not price search. An alternative is for searches, with reward and in consistent utility units.
- Let be expected terminal correctness under a specified continuation policy. In a myopic comparison of exactly one extra search, holding other costs and continuations fixed, search is worthwhile if . This is not a theorem that RL finds the optimal stopping policy; a full Bellman comparison also accounts for future search and costs.
- For a -billion-parameter model, a -token linear prefill costs . Add retrieval for , excluding search-query decode and other overhead.
- If one accuracy percentage point is worth , one unit of accuracy fraction is worth . The corresponding component-only penalty is , not a conversion using milliseconds per unit fraction as if it were per point. Training cost:
- Use a deliberately coarse arithmetic training ledger for a -billion-parameter policy: forward FLOPs per position and forward-plus-backward FLOPs per position. The -position trace has generated and prompt/observation positions. Rollout decode costs FLOPs; rollout prefill ; reference forward over the trace ; policy forward/backward . Total is per rollout. Loss masks do not remove conditioning-context computation.
- At , this is of arithmetic time per rollout, not sequential batch-one wall time. Five rollouts cost per question in this ledger. A -question pass costs arithmetic GPU-hours, or at per GPU-hour; tool waits, attention, communication and utilization are omitted.
- With conditionally IID groups, a prompt mixture of at , at and at gives constant-reward groups. Expect nonconstant groups, or per arithmetic GPU-hour. Approximately hours of the full ledger belongs to constant-reward groups; it is not necessarily wasted regularization signal.
- Generation/prefill costs per rollout and reference/update . Only if the latter stages have no required nonzero losses and can be skipped without changing normalization, optimizer-state behavior or the target objective does the optimistic ledger save , reaching hours and . Equal reward alone does not justify “identical gradients”; an active KL term is a direct counterexample.
- An oracle that discards the entire extreme-probability prompt cohort retains balanced prompts. Its training ledger costs hours and yields expected nonconstant groups, or per hour, times the original rate. It loses of the original nonconstant groups and changes the prompt distribution.
- A real five-rollout probe does not identify that oracle cohort: it retains approximately after filtering observed constant-reward groups, not . Generating probes for all original prompts alone costs approximately arithmetic hours in this ledger unless validly reused. Reusing rollouts, drawing fresh groups and resampling prompts are different algorithms with different objectives and costs; probe compute is not free.
- A weight-only arithmetic/bandwidth balance gives batch size , hence at least in that toy comparison. It is not a guarantee that batch is optimal or fits memory; attention, KV traffic and variable lengths matter. Increasing from five to sixteen multiplies linear rollout work by , while reducing constant-group probability at as above. Measure useful learning per resource, not group count alone. Practice decisions:
- Log reward variance, constant-group rate, search count, KL, tool errors and held-out answer performance. Ten-percent or forty-percent constant-group thresholds are source heuristics dependent on group size, correlation and reward shaping, not universal signals to change an optimizer.
- Dynamic sampling changes the training distribution and can remove informative examples. Charge its probes and establish which loss terms remain on filtered groups before claiming gradient equivalence or savings.
- Keep tool permissions, timeouts and hard search caps. A cap derived from twice an observed p99 trace length is a resource heuristic, not a safety guarantee or proof that the learned stopper is optimal.
26.8 Agentic RAG and its costs
What and why:
- A sub-agent has its own context and a configured retrieval interface or permission scope; a controller dispatches work and combines summaries or structured evidence. Interfaces need not be exclusive unless that is an explicit policy.
- Let be layer count, hidden width and context length. A full-square attention prefill proxy is . For a fixed total of tokens split equally across contexts with no duplicated overhead, . Only the quadratic term shrinks in that comparison. Causal kernels can change its coefficient.
- With , and , the coefficient is . A -token monolith costs linear plus attention FLOPs, totaling , or at .
- Four agents each process retrieved tokens plus a duplicated -token prompt. Each prefill costs FLOPs, or . That is the ideal concurrent prefill time only with sufficient resources; on one shared constrained device, four requests need not finish in one request’s time.
- This attention-aware example differs from the earlier linear-only prefill ledgers. Add duplicated prompts, summaries, controller work and tool waits before comparing complete schedules. Failure and crossover:
- Each -token summary costs approximately under the stream proxy, and controller prefill of tokens costs under the attention proxy. Their is an added component, not the net fan-out tax.
- Splitting initial prefill already saves on the ideal critical path. Net non-loop overhead here is therefore only , before other scheduling differences.
- Let and denote additional adaptive follow-up durations for source under their respective context schedules. If those follow-ups serialize in the monolith but overlap across agents, the conditional crossover is
- In the further simplification of equal per-round cost and additional follow-ups per source, this becomes . Initial retrieval waits that can already run concurrently in either architecture must not be counted as saved serial follow-ups.
- The former “more than rounds” threshold follows only from separately ignoring the initial prefill advantage and taking , : the quotient is . It is not the crossover for the worked context-splitting scenario or a universal requirement for agents.
- Fixed concurrent retrieval can be implemented without agents. Agent autonomy is useful when per-source adaptive queries, state or permissions justify it; context partitioning can also help even without follow-ups. Compare the full feasible baseline, not a deliberately serial fixed-retrieval implementation. Worked example:
- Use four sources, the attention-aware -billion-parameter proxy, retrieved tokens per source, prompt tokens per initial call, -token agent summaries and a -token final answer. Input/output price proxies are / per million tokens. Initial source waits of run concurrently in both architectures and are charged once on each critical path.
- With no follow-ups, the monolith’s prefill plus answer is , or including initial wait. Four ideal concurrent agents plus controller take in compute/decode components, or including wait. Agents are slower here. Device-busy components, excluding reservation during waits, are versus device-milliseconds, a ratio.
- Non-loop token-price proxies are for input and output tokens, versus for input and output tokens across agents and controller. The premium is ; ideal parallel latency does not make aggregate work free.
- Now add one -token adaptive follow-up query at each of two sources. For new evidence block size after prefix length , declare an append-only prefill proxy : compute new queries against old/new keys rather than replaying old queries. This block proxy, the full-square initial proxy and weight-only decode remain approximations; decode attention is omitted.
- The serialized monolith follow-ups cost approximately and , including query decode, wait and a -token append after prefixes of and tokens. Each looping agent’s corresponding work is after a -token prefix, and the two agent follow-ups overlap under the capacity assumption.
- Totals including the common initial wait are for the monolith and for agents: faster, not of the full schedule. Excluding that common initial wait gives partial components of and ; label that narrower denominator if using it.
- Under a new-input-only price proxy with reused prefixes billed free, the looping monolith has new input and output tokens, costing . Agents have and , costing , a premium. Free billing of reused prefixes is an assumption, not standard API pricing.
- Under full repeated-prompt input billing with no cache discount, the same logical calls bill monolith inputs of , costing including outputs. Agents bill input tokens, costing including outputs: cheaper. Billing assumptions reverse the ordering; computational prefix reuse and provider billing are distinct.
- A reported research system’s approximately fifteen-times-chat versus four-times-chat token counts give a ratio only with a common denominator. They do not identify agent fan-out or validate this dollar ledger. Do not multiply an already-looped dollar cost by another round count to manufacture agreement with a token ratio.
- Four required agent successes at independent probability give . Correlated or conditional success needs a joint model. A suggested metrics layout with two scoreboards per agent plus dispatch and synthesis has scoreboards for four agents; it is a design choice, not an attribution minimum. Practice decisions:
- Start with shallow dispatch and bounded summaries if they fit the task; source suggestions such as depth one and two-hundred-token summaries are heuristics, not guarantees of fidelity or optimum cost.
- Benchmark against concurrent fixed retrieval and a cache-aware single controller. Record aggregate device work, token billing, latency percentiles, tool permissions, missing citations and summary losses separately.
- Put timeouts and structured evidence requirements on each agent. A partial or failed source result must remain visible in the final answer; doubling a measured p99 timeout is not proof that all required evidence will arrive.
26.9 When to stop
What: Let be a stipulated traffic fraction requiring hops. In a no-retry toy model, every required hop must succeed with constant conditional retrieval rate and bridge rate . If paths requiring more than hops cannot be discovered within cap , cumulative path-discovery coverage is
- Use the source’s illustrative depth mixture , with and . Treat this as a scenario input, not a traffic measurement independently established here.
- For , coverage is , , , and . Added coverage is , , and zero.
- Saturation after four is built into the no-retry, no-alternate-path assumptions. Real retries, recovery, accidentally retrieved later hops, or losing earlier evidence can change the curve; path discovery alone does not ensure all needed support remains in the final context. Dilution and accuracy:
- A specific ranking toy has one gold score fixed at and independent standard-normal distractor scores. Then . If the gold score is itself random, this is not the same probability; with two independent unit-variance Gaussian scores it is instead.
- For illustration only, use that fixed-gold expression as a conditional evidence-utilization surrogate for accumulating context. This is not a derivation of multi-hop reader accuracy or a measured model of attention.
- With , , , each extra round multiplies by , a relative utilization tax in this toy.
- Let be fallback correctness when the discovered evidence is not used. Assuming usable evidence yields correctness one and otherwise this fixed floor, the illustrative answer accuracy is
For , and the stated multiplicative utilization model, adding a round improves this toy accuracy exactly when
- Here . The exact relative-coverage threshold is ; the first-order approximation is . Do not interchange them as exact values.
- Relative coverage gains for rounds two, three and four are approximately , and . The first two beat the exact threshold; the fourth does not.
- Over the five enumerated options, the constructed accuracy optimum is , with . This optimum is conditional on both the coverage and utilization assumptions, not a universal retrieval cap. Latency and economic stop:
- Build one consistent full-replay ledger: query , chunks of tokens, retrieval per round, generated reasoning tokens per round and an additional -token final reader output.
- Round processes prompt positions. The final reader processes . This includes prior generated reasoning wherever it is replayed; it is not just an external-document token count.
- Here is in seconds per position, hence the explicit converts to milliseconds; is already in milliseconds. Attention, tool variability and queuing remain omitted. Full latency components for caps one through five are approximately , , , and .
- Marginal costs for rounds two through five are , , and . This replaces the conflicting source formula/table ledgers rather than mixing their rates.
- At per accuracy percentage point, define per unit accuracy fraction and compare . Round two gains points worth ; round three gains points worth , below its cost. Enumeration gives economic optimum .
- A one-step marginal test is not a general global-optimum theorem if later gains can rebound. This five-option curve has been evaluated directly. To charge money too, convert it to the same utility units with an explicit weight; a prompt bill is not automatically a latency penalty.
- Confidence or a terminator may be useful inputs to a learned cost-aware stopper. Neither alone encodes this ledger. Retain calibrated validation and hard caps rather than declaring that confidence can only ever be a tiebreak. Replacement, caching, and claim limits:
- Prefix reuse requires an append-only sequence with the same model, template and valid KV states. If the final answer simply continues that cached sequence, newly prefilled external input is ; generated reasoning already has decoded KV states. A separately prompted final reader or changed passage order cannot assume this reuse. Reusing the same curve also assumes that the cache schedule preserves effective evidence use; changed ordering or reader instructions can change accuracy. Long-prefix attention still has cost omitted by the linear proxy.
- Under that specific cache schedule, incremental round cost is . Cached accumulating costs . Round three’s value is still below its cost, so the economic optimum remains two, not three. The former millisecond marginal used an inconsistent prefill rate.
- Without cache, one accumulating round uses prompt positions, costs per million queries at per million replayed input positions, and has in modeled components. Plain one-shot is , so this loop adds before overhead.
- Three accumulating rounds use positions, cost per million queries, take and reach toy accuracy. Five use positions, cost , take and reach . The extras spend and while losing points. These are scoped prompt bills, not total operating costs.
- For a separate replacement scenario, each generation sees only the original query and latest passage tokens; earlier drafts affect retrieval only. The final reader sees those latest passages plus the latest -token draft. Then . Keeping the same path coverage and setting assumes that this compressed latest state preserves all needed facts. That is a strong sufficiency assumption, not a consequence of replacing passages.
- Conditional on sufficiency, replacing at uses positions, costs per million queries, takes and reaches . Versus accumulating at three, it is points higher, faster and lower in scoped prompt billing. At four it reaches ; the -point gain is worth only against of cost, so replacement’s enumerated economic optimum is three.
- Replacement at two takes and reaches in this toy. It already exceeds a target before omitted overhead; do not advertise the old millisecond point as meeting a p95 guarantee.
- Matching a constructed gain or turnover to a reported paper’s upper bound does not independently validate the toy parameters. Measure actual answer accuracy, compression losses, cache validity and whole-request latency distributions. Practice decisions:
- Estimate traffic depth and test answer quality at each cap. Coverage alone is insufficient; extra rounds can repair errors as well as introduce dilution, which this simple curve does not model.
- Choose replacement, accumulation or evidence-ID re-fetching according to required provenance and state sufficiency, not a universal default. Compression must retain qualifications and citations needed by the final reader.
- Verify valid prefix reuse before claiming cache savings, and budget carried passages, generated history, tool calls, token billing and percentile latency separately. Use cost-aware stopping plus hard resource and permission limits; do not assume the toy’s optima transfer.
Diagrams
Figure 26.1
Diagram description and source
flowchart LR
q["frozen query q"] --> s["retrieve and possibly rerank; select top-k"] --> g["generate from selected context"]
bridge["hidden bridge may appear only in first result"] -.-> s
reference["unresolved reference is already in dialogue history"] -.-> q
stale["topical evidence may be stale; check dates and currency-aware gold"] -.-> g
Figure : These are different failure modes, not one theorem about missing terms. A hidden bridge may need another retrieval, an available dialogue referent should be resolved before retrieval, and stale evidence needs temporal checks. The penicillin term supplies about of the example’s raw IDF sum; that is not its semantic influence or a recall guarantee.
Figure 26.2
Diagram description and source
flowchart LR
oneq["one-shot original q"] --> oner["retrieve D1; bridge may be absent from q"] --> oneg["D2 can be missed; no adaptive return edge"]
iterq["original q"] --> d1["retrieve D1"] --> y1["draft y1; verify proposed bridge e"] --> qy["retrieve with q plus y1"] --> d2["replacement D2"] --> y2["generate from q and D2; re-fetch earlier support if needed"]
Figure : A bridge-aware second query can improve the chance of retrieving ; a missing literal bridge does not make one-shot retrieval impossible. The exchangeable-rank estimate requires an uninformative-rank model. With fixed chunk lengths and a fixed generator query, replacement keeps per-round prompt size bounded; cumulative full-replay work is linear in . Discovered-path probability is not automatically retained joint evidence or answer accuracy.
Figure 26.3
Diagram description and source
flowchart LR
iq["IRCoT question"] --> ir1["retrieve passages"] --> is1["one reasoning sentence in this implementation"] --> ir2["retrieve again; retain passages and reasoning"] --> reader["final reader over accumulated support"]
saq["Self-Ask question"] --> sq1["follow-up question"] --> a1["extract short intermediate answer; save provenance if needed"] --> sq2["next question uses prior Q/A history"] --> final["answer from compressed history; check lost qualifiers"]
Figure : Both controllers can derive a dependent query from partial reasoning; “iterative” and “recursive” describe overlapping control styles rather than mutually exclusive algorithms. IRCoT retains passages and reasoning. Self-Ask can retain short question-answer history instead of raw passages, but that history still grows and may lose support needed by the final answer.
Figure 26.4
Diagram description and source
flowchart LR
ctx["context and prior accepted sentences"] --> draft["draft sentence; token probabilities are model confidence, not truth"] --> gate{"minimum probability below theta?"}
gate -->|"no"| accept["accept draft"]
gate -->|"yes"| query{"query construction"}
query --> implicit["implicit: mask uncertain spans using beta"] --> retrieve["retrieve passages"] --> regen["regenerate fired sentence; charge discarded draft"]
query --> explicit["explicit: generate question per uncertain span"] --> retrieve
Figure : Non-triggering drafts become output; only fired drafts are discarded and regenerated in this ledger. A mask threshold covers all triggering tokens under matching strict comparisons, while other policies must explicitly handle uncovered spans. Confidence is not factuality. Extra query generations, context changes and invalidated caches require their own costs.
Figure 26.5
Diagram description and source
flowchart LR
docs["local top-k"] --> eval["separately trained evaluator; score s"]
eval --> bad["INCORRECT: s below tau_lo"] --> web["discard local; rewrite and filter web evidence"] --> gen["generator checks support in recomposed evidence"]
eval --> amb["AMBIGUOUS: tau_lo through tau_hi, inclusive"] --> both["retain filtered local evidence and add filtered web"] --> gen
eval --> good["CORRECT: s above tau_hi"] --> strips["filter strips without dropping needed qualifiers"] --> gen
Figure : The ambiguous branch can mitigate false-discard harm by retaining local evidence, but extra or conflicting context may still hurt the reader. Separate evaluator weights do not imply independent errors. Under the stated constant- model, binary accuracy change is , not merely the bracketed evidence-presence change.
Figure 26.6
Diagram description and source
flowchart LR
teacher["external teacher labels seed examples"] -.-> critic["offline distilled critic C"] -.-> corpus["corpus annotated with reflection tokens"] -.-> model["generator M trained on content and reflections"]
prefix["current prefix"] --> decision{"learned Retrieve decision"}
decision -->|"retrieve"| branches["K passage-conditioned candidate segments"] --> rank["rank likelihood and specified reflection scores"] --> win["keep one winner; refresh valid branch prefixes; continue"]
decision -->|"skip"| direct["continue without retrieval branch"]
Figure : Teacher and critic supervision are offline in this recipe, not an independent verifier at serving. The worked ledger charges three reflection tokens per candidate segment, not one free critique token. Its decoded tokens are times baseline work; the latency assumes maintained five-stream throughput and the declared cache/reseed schedule.
Figure 26.7
Diagram description and source
flowchart LR
rollout["transcript: 40 prompt, 170 policy actions, 600 retrieved observations"] --> mask["condition on all context; mask prompt and observations in action loss and action KL"]
mask --> learnable["G=5, observed success fraction 0.4: two advantages +1.224745, three -0.816497"] --> signal["nonconstant reward-advantage signal"]
mask --> constant["all rewards equal: reward standard deviation zero"] --> zero["zero reward advantages; KL or other losses may still update policy"]
Figure : The critic is one unsharded bf16/AdamW training-state scenario, not every PPO implementation. GRPO replaces a learned baseline with group statistics but must pay for rollouts. Retrieved observations are of the example transcript: retain them as context, while excluding them and the prompt from both policy-action loss and action-level KL. Constant rewards remove the reward-advantage term, not necessarily all gradients or optimizer updates.
Figure 26.8
Diagram description and source
flowchart LR
mono["monolith: initial sources concurrent; two adaptive follow-ups serialize"] --> mtime["3763.552533 ms including initial 400 ms wait"]
fan["four ideal concurrent agents; two follow-ups overlap"] --> summaries["200-token summary per agent; preserve source evidence"] --> controller["1100-token controller prefill; 150-token final answer"] --> ftime["2856.876613 ms including initial wait"]
Figure : For the declared attention/cache schedule and sufficient concurrency, agents reduce full modeled latency by about . They pay summary and controller work but also save initial context-attention work; the net non-loop difference is only here. The old universal -round crossover ignored that saving. Aggregate work and billing may increase or decrease depending on the schedule and prefix-billing policy.
Figure 26.9
Diagram description and source
flowchart LR
t1["acc T1: 62.463699 percent"] --> t2["T2: 74.225204; economic optimum"] --> t3["T3: 76.674541; accuracy optimum"] --> t4["T4: 75.973727"] --> t5["T5: 74.594602"]
r1["replacement only if latest state is sufficient"] --> r3["T3: 79.610099; economic optimum"] --> r4["T4: 80.378438"] --> r5["T5: same toy accuracy"]
g2["round 2: +11.761505 points; 342.608428 ms"] --> g3["round 3: +2.449337 points; 385.020193 ms"] --> g4["round 4: -0.700815 points; 427.431958 ms"] --> g5["round 5: -1.379124 points; 469.843723 ms"]
Figure : In this constructed no-retry mixture and fixed-gold utilization surrogate, accumulating accuracy peaks at . At per accuracy point, the enumerated economic optimum is , including under the specified append-only cache schedule. Replacement’s conditional optimum is three only if the latest state preserves required support. Carrying short strings does not generally remove dilution, compression error or turnover.
Table 26.1
Table : Recomputed full-replay accumulating-loop ledger, including prior reasoning and a final reader. These are scenario probabilities and partial latency components, not measured accuracy or p95. Prompt positions are processed/billed again under the stated no-cache convention. Rounded values below come from full-precision calculations.
| Replayed prompt positions | |||||
|---|---|---|---|---|---|
Whiteboard pack
- Draw frozen-query retrieval and generation, then mark where a new bridge can trigger another search. Resolve available dialogue references before the first search.
- Loop the original query plus a verified draft into replacement retrieval; retain or re-fetch early source support.
- Contrast IRCoT’s passages and reasoning with Self-Ask’s shorter question-answer history. Label replayed positions versus newly appended input.
- Draw FLARE’s accept-draft path as well as its trigger, mask/explicit-query and regeneration path.
- Add CRAG thresholds with defined boundary cases and Self-RAG’s candidate branches. Label support scores as learned judgments, not proofs.
- In Search-R1, separate policy actions from environment observations. Keep all context but mask non-actions in both action loss and action-level KL; distinguish zero reward advantage from zero total gradient.
- Compare ideal concurrent agents with concurrent fixed retrieval and a cache-aware controller. Separate critical-path latency, aggregate work and provider billing.
- Finish with conditional coverage, utilization and marginal-value curves, then hard resource and permission caps.
Spoken script
One-shot retrieval can fail when a useful bridge emerges only after the first search. Iteration can feed a draft back into retrieval; recursion can generate a dependent hop. IRCoT retains passages and reasoning, while Self-Ask compresses them into short question-answer history. FLARE gates on model token confidence, which is not truth. CRAG adds a separately trained evidence evaluator and an ambiguous band that mitigates, but does not eliminate, discard harm. Self-RAG learns reflection tokens and pays for candidate branches. Search-R1 trains policy actions conditioned on retrieved observations; group-relative rewards do not make all other gradients disappear. Agent fan-out can overlap work or partition context, but coordination and billing matter. Stop using measured quality and resource trade-offs, not a toy optimum or confidence alone.
Interview traps
1. Is iterative retrieval the same as recursive retrieval, and when do IRCoT or Self-Ask win?
Not exactly. Iteration revises retrieval from a current draft; recursion constructs a dependent reasoning step or subquestion. These are overlapping control styles. IRCoT may be preferable when full passages and citations matter, while Self-Ask can be cheaper when short intermediate answers preserve all relevant conditions. Both can fail if their generated bridge is wrong. Static fan-out is appropriate when its queries can be formed before seeing one another’s results.
2. Does FLARE retrieve the uncertain draft, and does CRAG use retriever similarity?
No to both. FLARE’s trigger threshold and mask threshold have distinct roles; the query policy must actually cover uncertain triggering spans and must not equate confidence with truth. Retriever similarity can correlate with usefulness but is not calibrated answer containment. CRAG uses a separately trained evaluator with explicit threshold boundaries. Retaining local evidence in AMBIGUOUS can reduce false-discard harm, yet strip loss and conflicting web context still need testing.
3. Are Self-RAG reflection tokens free and independent?
The reflection-token count is small relative to discarded candidate text, but the worked schedule decodes tokens versus , or times work. Its approximately latency premium requires maintained five-stream throughput and valid prefix handling; serial execution is much slower. Offline teacher supervision does not make the generator’s own critique statistically independent or a correctness certificate.
4. What does Search-R1 learn from exact match, and what can GRPO not learn?
Exact match can reinforce policy-generated reasoning, searches and stopping, but it does not charge for search. A penalty such as needs calibrated utility units, and a one-step threshold is not a proof of an optimal learned policy. GRPO avoids a learned critic but pays for rollouts. The critic example is conditional training-state accounting. Identical rewards eliminate reward advantages, not necessarily KL, auxiliary or optimizer updates. Retrieved information remains conditioning context and is masked, along with prompt tokens, out of both policy-action loss and action-level KL.
5. When is agentic RAG worth its cost, and how should the loop stop?
Compare full feasible schedules, including attention savings, overlapping adaptive work, summaries, valid caches and actual prefix billing. There is no universal -round requirement. In the stated five-option stopping toy, accumulating accuracy peaks at three and economic value at two; the declared cached variant still favors two, and replacement favors three only under evidence-sufficiency assumptions. A learned confidence signal can inform value estimates, but hard caps, permissions, measured answer quality and whole-request latency remain necessary.
Key numbers
| Source location | Exact remaining measurements and limits |
|---|---|
| opening and figure | Reported relevance recall values and describe their own labeled sets; they do not certify responsiveness or currency. A currency-aware evaluation can detect stale evidence. |
| interview arithmetic | With both retrievals, two question-inclusive prefills and a twenty-token bridge, matched partial components are versus for wide one-shot, excluding the common final answer. Earlier / values do not reconcile. An p95 target needs whole-request measurement. |
| operational limits | The opening service-document recall is reported as , not joint answer evidence. At three rounds, replacement external positions are versus accumulating; replaying prior eighty-token drafts raises the latter to . No p50 follows without a measured distribution. |
| staff case | Five accumulating rounds have external prompt positions, or with prior eighty-token drafts. Under the Section full-replay proxy this is , about times a budget, not measured p99. Two full eighty-token replacement rounds cost , not . |
| selection boundary | The interview constraints are an -token window and p95. A four-retrieval cap is a heuristic; five-hop path coverage is only in the stated conditional model. Neither a cap nor that coverage proves the latency target. |
| long answer boundary | Eight to twelve sentences are the feature boundary. Twelve independent web waits total if serialized, before decode, embedding, passage prefill and trigger/query overhead. Charge concurrency only where feasible. |
| filtering boundary | Four-fifths boilerplate is a source example, not permission to remove all low-scoring strips: the remaining fifth can need an earlier qualifier. The suggested – labels and roughly -token filtering threshold are heuristics, with table/code boundaries preserved. |
| critique boundary | Eight self-critiques need not monotonically improve confidence or truth. The five-branch worked ledger has times decoded work; reflection is of extra decode. The small latency premium requires maintained multi-stream throughput. |
| controller setup | The reported old controller used a three-hop cap, confidence threshold and an entity-count rule fitted to development questions eighteen months earlier. An unsharded critic state exceeds a single device, but sharding, offload, size and precision change the comparison. |
| reported limits | Reported GRPO/PPO reward and stability comparisons, and a dynamic-sampling AIME result at half the steps, are experiment-specific. Step count is not total compute; charge probes, retained losses and changes in the sampled prompt distribution. |
| review-layer boundary | The opening reports p95 after six weeks and a one-quarter token-bill increase; those are not derived here. The former decode claim for six agents plus review cannot be reproduced without review/synthesis lengths and a schedule. Fourteen scoreboards are one chosen metrics design, not a minimum. |
| serving boundary | The source’s five-round release and roughly twelve-point gain are reported context. In the corrected full-replay toy, cutting five to three saves and gains accuracy points, not a measured percentile result. Two-round replacement is at conditional accuracy, already above a target before overhead. |
| routing boundary | Depth at least three has share in the scenario. If shallow requests are strictly faster than every deep request, overall p95 lies at the deep distribution’s two-thirds quantile, so improving deep requests can improve p95. Below five-percent deep share, p95 lies in the shallow portion under strict separation; general overlapping latency distributions require the mixture CDF. |
00-START-HERE · 01-READING-ROUTES · 25_routing_and_adaptive_retrieval · 27_fine_tuning_the_generator