00-START-HERE · 01-READING-ROUTES · 08_reading_the_machine_circuits_induction_heads_and_attribution · 10_prompt_sensitivity Purpose: Explain where prompting ends, where retrieval begins, how reasoning scaffolds change decoding, and why more calls or more passages can reduce answer quality.
TL;DR
- A Retrieval-Augmented Generation (RAG) prompt has four cumulative rungs: completion, instruction, In-Context Learning (ICL), and query-time retrieval.
- The prompt hierarchy distinguishes illustrative examples from source evidence; both can be query-dependent. Demonstrations may be fixed or query-selected; retrieved evidence is selected for the query. The distinction is illustrative role and evidence provenance, not a universal fixed-versus-dynamic boundary.
- Chain-of-Thought (CoT), self-consistency, Tree of Thoughts, and Graph of Thoughts change decoding. They do not change the weights or the retrieved passages.
- Self-consistency estimates an answer marginal by sampling paths and counting final answers. It reduces variance, but it cannot correct bias from a wrong retrieved context.
- A scaffold is a program the model must execute. An all-required-stages scenario discounts accuracy by conditional stage reliability; exploratory branches may tolerate failures.
- Raising top- can improve recall and reduce answer accuracy. More passages increase competition for the generator’s attention.
- Choose prompt rungs, scaffold depth, and top- with measured failure partitions, execution reliability, ranker margin, latency, and cost.
The story
Picture an open-book exam with four rungs on a ladder beside the student’s desk. On the first rung, the student gets only the question and continues the text from memory. This is completion, which means predicting what text comes next without special directions or external material. On the second rung, the examiner adds an instruction. The student now knows to answer instead of continuing the question. The instruction changes behavior, but it does not add a missing policy fact. On the third rung, the examiner puts worked examples on the board before seeing the new question. This is In-Context Learning (ICL), which means guiding the current answer with examples while leaving permanent training unchanged. The examples teach answer form, citation style, refusal wording, or a JavaScript Object Notation (JSON) envelope, but they cannot carry every changing fact in a large corpus. On the fourth rung, the examiner lets the student find the relevant page after reading the question. This is Retrieval-Augmented Generation (RAG), which means finding evidence after the request and giving it to the answer writer. The page can be fresh, query-specific, deletable, and citable, but the student must still find and use it correctly. Now give the student scratch paper. A single reasoning chain is one worked path, while a fan of five paths lets the student solve the problem five ways and count the final answers. A tree adds branching, scoring, pruning, and continuation, while a graph can also merge or revise partial work. Each extra move asks the same student to execute another instruction. If every move is reliable, thirty moves succeed together only of the time. Too much scaffolding, meaning added scratch-work procedure, turns the exam ladder into a maze. The same warning applies to the open book. Five pages may include the right page and few distractors, while forty pages can raise recall, meaning how often the right page is present, and bury the answer among plausible competitors. A better ranker gives the right page a larger score margin, and that margin decides how many pages the student can safely receive. The interview lesson is concrete. Do not fix a missing page by rewriting instructions, biased pages by sampling more answers, or weak ranking by buying a longer desk. Climb the right rung, add only executable scratch work, and send only as many pages as the student can reliably distinguish.
Decoder table
| Technical term or symbol | Plain-English meaning | Why it matters |
|---|---|---|
| Retrieval-Augmented Generation (RAG) | A generator answers with passages selected after the query arrives. | It binds fresh, query-specific, deletable, and citable evidence at request time. |
| Prompt | The exact structured input sent to the generator. | Treating it as one opaque string hides which part caused a failure. |
| Prompt hierarchy | Completion, instruction, in-context examples, and retrieval arranged by binding time. | It routes each defect to the layer that can actually repair it. |
| Prompt rung | One level of that hierarchy. | The rungs stack rather than replace one another. |
| Instruction slot | Query-independent directions in the served input. | It controls behavior but cannot supply a missing fact. |
| Demonstration block | Worked examples placed in context, fixed or query-selected. | They communicate task, form or mappings while consuming context and uncached input work. |
| Retrieved passage block | Evidence chosen for the current query. | Its presence, order, and use determine grounded answer quality. |
| Query | The user’s live request. | It arrives late enough to select request-specific evidence. |
| Generator parameters | The learned weights that hold behavior and parametric memory. | Training changes them, while prompting and retrieval do not. |
| Conditional probability | The model’s probability of an output given its input. | All four prompt rungs change what conditions the same prediction. |
| Completion | Base-model continuation from the query alone. | It explains why an untreated model can continue a question instead of answering it. |
| Pre-training | The original next-token learning run. | It fixes the earliest binding time for facts stored in weights. |
| Base checkpoint | A model before instruction post-training. | It can expose an undistorted token distribution but may not follow commands. |
| Parametric memory | Knowledge represented inside model weights. | It has no source pointer or timestamp and updates only through training. |
| Instruction tuning | Training on instruction-response pairs across tasks. | It makes an instruction read as a command. |
| Instruction-tuned checkpoint | A model whose weights were trained to follow instructions. | It is the normal generator foundation for production RAG. |
| Preference optimization | Post-training that favors outputs people or a reward signal prefer. | The source places it above instruction tuning in the behavior stack. |
| Zero-shot | Answering without demonstrations. | It preserves context for evidence when examples do not improve form. |
| In-Context Learning (ICL) | Guiding a frozen model with examples in the current prompt. | It is mechanically similar to RAG but binds examples before the query. |
| Few-shot | Answering with a small demonstration set. | It trades prompt space and latency for task and format cues. |
| Demonstration | One worked input-output example in the prompt. | It can fix output form but cannot cover a changing corpus. |
| Binding time | The latest moment when information can enter the system. | It separates static behavior from fresh query-specific knowledge. |
| Capacity | How much information one storage or prompt path can hold. | A million-token corpus cannot fit in an 8,192-token window. |
| Context window | The token capacity available to one model request. | Instructions, examples, passages, and the query compete inside it. |
| Compression factor | Whole-corpus tokens divided by tokens retrieved for one query. | It quantifies the capacity advantage of request-time retrieval. |
| Corpus size | Number of stored facts or documents. | It sets the full-text burden a fixed demonstration block would face. |
| Fact size | Average tokens per fact or document. | It converts corpus count into token capacity. |
| Chunk size | Tokens in one retrieved chunk. | It converts top- into prompt cost. |
| Update delay | Time from a fact change to a served update. | It measures how long stale facts remain live. |
| Change interval | Time between changes to the fact. | Comparing it with update delay gives the stale fraction. |
| Stale fraction | Share of time the served system reflects the old fact. | It exposes why a three-day training cycle fails a weekly policy. |
| Retriever | The component that selects passages for query . | Its output binds after the query and before generation. |
| Top- | The highest-ranked retrieved passages. | Raising it trades recall against prompt cost and distractor competition. |
| Vector database | One possible store and search implementation for embeddings. | It is plumbing rather than the definition of RAG. |
| JavaScript Object Notation (JSON) | A machine-readable output format. | Demonstrations can reduce parse failures when a downstream system requires it. |
| Citation | A pointer from an answer claim to a source. | Retrieval can provide one, but a pointer still needs support checking. |
| Provenance | Where a claim or passage came from. | It lets auditors trace an answer to a source. |
| Abstention | Refusing to answer when support is missing. | It is safer than inventing a claim from weak context. |
| Entailment check | A test of whether a cited span supports a claim. | It turns traceability from prompt wording into a verifiable control. |
| Unsupported-claim metric | Count or rate of answer claims without evidence. | It measures the compliance failure directly. |
| Prompt token | One model input unit. | It is the recurring currency of instructions, examples, and passages. |
| Prefill | Processing prompt tokens before generation begins. | More context increases time to first output. |
| Floating-point operation (FLOP) | One arithmetic operation used to price model work. | The chapter compares prompt and scaffold costs in FLOPs. |
| Graphics processing unit (GPU) | Accelerator hardware used for model computation. | GPU time converts FLOPs into latency and money. |
| Exact match | An evaluation score that requires the predicted answer text to match a reference. | It supports the RAG-Sequence and closed-book comparison. |
| RAG-Sequence | The cited RAG system that conditions answer generation on retrieved evidence. | It beats a much larger closed-book model in the source comparison. |
| Bidirectional and Auto-Regressive Transformers (BART) | The generator family used by RAG-Sequence. | It anchors the smaller retrieved model in that comparison. |
| Text-to-Text Transfer Transformer (T5) | The closed-book model family in the comparison. | Its 11-billion-parameter result shows that parameters alone did not buy the same accuracy. |
| Natural Questions | The question-answering benchmark used for exact match and retrieval anchors. | It grounds two quantitative comparisons in the chapter. |
| Generative Pre-trained Transformer 3 (GPT-3) | A cited model family used for ICL and calibration results. | It anchors the historical prompting evidence. |
| FLAN | The cited instruction-tuning recipe over many tasks. | It shows that instruction behavior can beat a larger zero-shot model. |
| Reasoning scaffold | A procedure that changes how outputs are sampled and combined. | It changes decoding, not weights or retrieved passages. |
| Decoding | The procedure that turns model probabilities into an output. | Chains, fans, trees, and graphs differ mainly here. |
| Chain-of-Thought (CoT) | Generating an explicit reasoning path before the answer. | It exposes one path but does not marginalize over alternatives. |
| Reasoning path | One generated sequence of intermediate steps. | Several paths can reach the same answer. |
| Answer marginal | Total probability of an answer summed across all paths that reach it. | The most probable path can end at a less probable answer. |
| Greedy decoding | Choosing the highest-probability next token at each step. | It returns one path and can discard answer mass on other paths. |
| Self-consistency | Sampling several reasoning paths and counting their final answers. | It estimates the answer marginal without a learned scorer. |
| Monte Carlo estimate | An approximation made from random samples. | Self-consistency buys lower sampling error with more model calls. |
| Sampling temperature | A control over randomness in generated samples. | Zero temperature repeats one path and defeats an ensemble. |
| Majority vote | Returning the answer produced by more than half the samples. | It reduces independent variance but cannot correct shared bias. |
| Standard error | Expected sampling variation in an estimate. | It tells whether more samples or an evaluation difference are meaningful. |
| Variance | Random spread around an underlying result. | Voting can reduce it when sample errors differ. |
| Bias | A systematic tendency toward the same wrong answer. | A wrong passage or order-sensitive judge survives repeated sampling. |
| Best-of- | Generating candidates and selecting one with a scorer. | It differs from self-consistency because it needs a quality model. |
| Reward model | A learned scorer for candidate outputs. | It adds cost and its own execution error. |
| Chain topology | One serial path from query to answer. | It gives transparency with one model call. |
| Fan topology | Independent paths followed by a counter. | Its paths can run in parallel and need no evaluator. |
| Tree of Thoughts | Branch, score, keep, and expand partial solutions. | It buys exploration only when partial states can be judged reliably. |
| Graph of Thoughts | A reasoning graph that can merge and revise partial thoughts. | Its extra edges add flexibility and more model-executed stages. |
| Topology | The allowed nodes and edges in a reasoning procedure. | It determines parallelism, reversibility, and evaluator needs. |
| Branching factor | Children generated from each kept tree state. | It controls call count at every level. |
| Tree depth | Number of serial expansion levels. | It sets latency rounds and the pruning exponent. |
| Kept width | Children retained after each tree score. | It trades exploration against irreversible pruning. |
| State evaluator | A scorer for a partial solution. | A tree is only useful when this scorer beats chance. |
| Pruning | Permanently discarding branches during search. | A mistaken prune removes the correct path irreversibly. |
| Aggregation edge | An edge that merges two partial thoughts. | Graph of Thoughts can use it while a tree cannot. |
| Refinement edge | An edge that revises an existing thought. | It enables self-correction but adds another execution boundary. |
| Serial round | A stage that must finish before the next begins. | Depth can violate latency even when token totals look affordable. |
| Multi-hop question answering | Answering a question that needs evidence from several passages. | It motivates reasoning after retrieval succeeds. |
| Prefix cache | Reuse of model states for an unchanged prompt prefix. | It can make several samples much cheaper. |
| Key-value cache (KV cache) | Stored attention states for earlier tokens. | Sharing it prevents every branch from rereading the same passages. |
| 95th-percentile latency () | Time below which of requests finish. | It limits the serial depth a production scaffold can use. |
| Grade School Math 8K (GSM8K) | A math word-problem benchmark. | It anchors the chain-of-thought and self-consistency results. |
| Game of 24 | A constraint puzzle with an exact partial-state check. | It explains why Tree of Thoughts transfers poorly to tasks without an oracle. |
| Pathways Language Model (PaLM) | The model family in the 40-sample self-consistency result. | It supplies the published arithmetic cross-check. |
| Step reliability | Success probability conditional on earlier required successes. | The chain rule gives a product for an all-required-stages success event. |
| Execution rate | Probability that the whole scaffold runs as designed. | It discounts paper-level design accuracy in deployment. |
| Design accuracy | Accuracy if the scaffold executes perfectly. | It states the proposal’s best-case value. |
| Misfire accuracy | Accuracy when the scaffold fails to execute. | It determines how damaging a failed program is. |
| Incumbent accuracy | Accuracy of the current simpler system. | It sets the break-even target for a new scaffold. |
| Break-even execution | Minimum execution rate needed to beat the incumbent. | It converts an architectural proposal into a measurable reliability bar. |
| Deterministic aggregator | Ordinary code such as a counter. | It adds no model execution probability. |
| Reversible decision | A choice that keeps discarded candidates recoverable. | Reranking degrades more safely than pruning. |
| Branch survival | Chance that the correct branch survives one pruning level. | Its power across depth determines whether the tree can recover. |
| Large language model (LLM) | A generative model used for stages, scoring, or answers. | Model-executed orchestration inherits model reliability limits. |
| LLM-Blender | A cited rank-and-fuse system over outputs from several models. | It illustrates a learned aggregator that can fix bias but adds a stage. |
| Learned comparator | A model that chooses between candidate answers. | Candidate order can bias its verdict. |
| Positional bias | Preference caused by where content appears in the prompt. | Swapping candidate order can change a judge’s decision. |
| Self-review | Asking the model to inspect and revise its own answer. | It can raise confidence without raising correctness. |
| Model collapse | Degradation caused by repeatedly learning from model-generated material. | The source links it to repeated self-confirmation. |
| McNemar statistic | A paired-test signal based on examples where two systems disagree. | It checks whether a small claimed gain is more than paired noise. |
| Recall at | Chance that the answer-bearing passage appears among the first . | It can rise even when answer accuracy falls. |
| Answer-bearing or gold passage | The passage that contains the required evidence. | Its presence and use must be measured separately. |
| Closed-book accuracy | Accuracy without retrieved passages. | It is the parametric baseline that distractors can undercut. |
| No-gold accuracy | Accuracy with distractors after removing the gold passage. | It measures how much wrong context overrides parametric memory. |
| Co-occurrence substitution | Filling an answer from a passage that mentions the right entities but the wrong fact. | It explains why retrieval misses can be worse than no retrieval. |
| Utilization | Chance that the generator uses the gold passage when it is present. | It falls as more competitors enter the prompt. |
| Ranker margin | Gold-passage score lead measured in distractor standard deviations. | It determines how many passages the generator can safely compare. |
| Distractor | A plausible passage that does not contain the answer. | Each one can outscore or override the gold evidence. |
| Standard normal cumulative distribution | Probability that a standard normal value lies below a threshold. | It maps ranker margin into one-competitor win probability. |
| Dilution penalty | Relative utilization loss from one more passage. | It stays roughly constant while marginal recall shrinks. |
| Grounding rate | Recall multiplied by utilization. | It measures both finding and using the evidence. |
| Non-monotone answer accuracy | Accuracy that rises, peaks, and then falls with passage count. | It replaces the false assumption that more context can only help. |
| Recall slope | Log-linear gain in recall as top- grows. | It quantifies the shrinking benefit of another passage. |
| Optimal passage count | Passage count where recall gain balances dilution. | It can be derived from recall slope and ranker margin. |
| Bi-encoder | A fast retriever that scores query and passage representations separately. | It supplies candidates but can leave a small gold-passage margin. |
| Cross-encoder | A slower joint query-passage scorer. | It can raise margin enough to support a larger final top-. |
| Reranker | A second-stage scorer over retrieved candidates. | It buys separation, not merely a new order. |
| Score cliff | Sharp drop between strong and weak candidate scores. | It can set a query-specific cutoff instead of fixed top-. |
| Distractor-injection sweep | Add distractors while holding gold evidence fixed. | It measures utilization decay and ranker margin. |
| Dense Passage Retrieval (DPR) | The cited dense retriever with top-20 and top-100 recall anchors. | Its measurements set the worked recall curve. |
| Independent-distractor assumption | Simplifying assumption that competitor scores are independent. | Near-duplicate correlation limits the accuracy model. |
| Positional decay | Lower evidence use caused by where a passage sits in a long prompt. | The worked utilization model omits it and therefore gives an upper bound. |
| Conditional retrieval | Retrieving only when the query needs external evidence. | It avoids replacing a reliable closed-book answer with weak context. |
| High-popularity subject | A topic the model has likely seen often during training. | Retrieval can harm these queries when parametric knowledge is already strong. |
Core mechanics
Mathematical conventions
Natural logarithms measure likelihood in nats. The -billion-parameter examples use at assumed and per GPU-hour. These are parameter-work equivalents, not measured GPU service time, end-to-end latency or p95 guarantees; attention, bandwidth, queuing, orchestration and cache management are omitted. Prefix sharing avoids repeated prefix computation but not branch-specific attention or KV residency. Probabilities below are scenario inputs unless explicitly identified as reported empirical results. Percentage-point differences are absolute, not relative gains. Preserve precision until display.
9.1 The prompt hierarchy: completion to instruction to ICL to RAG
The four-slot input
| Aspect | Explanation |
|---|---|
| What | Treat the served prompt as a structured input. |
| Why | A failure belongs to one slot or to the parameters. |
| Failure without it | Teams concatenate one opaque prompt and cannot identify which artifact caused a regression. |
| Cost and complexity | Version the instruction, demonstration block, retrieval configuration, and checkpoint separately. |
The slots are instruction, demonstrations, retrieved passages, and query.
Rung 1: completion
| Aspect | Explanation |
|---|---|
| What | A base checkpoint uses next-token prediction and receives only the query. |
| Why | This is the lowest rung and the source of parametric recall. |
| Failure without it | Without the next rung: The model continues text instead of treating the text as a command. Given hi, a calibrated continuation can be how are you?. |
| Cost and complexity | It adds no prompt tokens. Its facts are bound when the checkpoint is trained. |
Rung 2: instruction
| Aspect | Explanation |
|---|---|
| What | Post-train on instruction-response pairs across a broad task mixture. |
| Why | The instruction slot becomes a command rather than text to extend. |
| Failure without it | A base model can continue retrieved passages instead of answering from them. |
| Cost and complexity | The training cost is paid once in the parameters. The rung adds zero serving tokens through the checkpoint itself. |
Wei et al. (2022) built FLAN over 62 datasets in 12 task clusters. Their instruction-tuned 137-billion-parameter model beat zero-shot GPT-3 175 billion on 20 of 25 held-out datasets. Longpre et al. (2023) scaled the recipe to tasks from 473 datasets. Ouyang et al. (2022) added preference optimization.
Rung 3: in-context learning
| Aspect | Explanation |
|---|---|
| What | Add worked examples while keeping the model frozen. |
| Why | Demonstrations can teach mapping and output form. |
| Failure without it | The model can return correct content in an unusable citation style, refusal format, or JSON envelope. |
| Cost and complexity | Demonstrations consume context and uncached prefill work. They can be fixed, cached or selected for each live query; declare which policy is being compared. |
Brown et al. (2020) made this paradigm a headline result of GPT-3.
Rung 4: retrieval-augmented generation
| Aspect | Explanation |
|---|---|
| What | Select the top- passages after the query arrives. |
| Why | Retrieval binds facts late enough to provide current, query-specific evidence. |
| Failure without it | Instructions and fixed demonstrations cannot supply a missing or newly changed fact. |
| Cost and complexity | Retrieval consumes prompt tokens on every request and adds index, ranking, and utilization failure modes. |
Mechanically, rung 4 enters through the same context channel as rung 3. The transformer has no native slot type that distinguishes a demonstration from a passage. Query dependence is not exclusive to RAG: demonstration selection can also depend on the live input. Here demonstrations illustrate task behavior, while retrieved passages supply source evidence.
Capacity
| Aspect | Explanation |
|---|---|
| What | Compare the whole corpus with the small block selected for one query. |
| Why | This shows why fixed demonstrations cannot replace retrieval for corpus facts. |
| Failure without it | A team mistakes a capacity shortfall for a prompt-tuning problem. |
| Cost and complexity | corpus tokens divided by retrieved tokens gives a selection ratio, not lossless compression. The corpus fills complete -token windows plus tokens, requiring windows to include all tokens without overlap. |
Binding latency
| Aspect | Explanation |
|---|---|
| What | Measure the delay between a fact changing and the served system reflecting it. |
| Why | Binding time decides which rung can carry a changing fact. |
| Failure without it | A fluent stale answer looks fresh because parametric memory has no timestamp and no source. |
| Cost and complexity | For deterministic periodic fact changes spaced apart and a fixed effective update lag , the illustrative stale-time fraction is . This assumes time-uniform observation and the specified update schedule, not an arbitrary three-day periodic training cycle. At days and days it is ; at it is . With Poisson changes, fixed-lag staleness is instead . |
Why the growing system prompt loses
| Aspect | Explanation |
|---|---|
| What | Appending another instruction constrains behavior. |
| Why | It can increase refusal when evidence is missing. |
| Failure without it | Without retrieval: It cannot create a fact absent from both the prompt and the parameters. |
| Cost and complexity | A 400-token clause on an 8 billion parameter generator costs floating-point operations (FLOPs). That is about of prefill on all daily queries, even if the clause addresses only of them. |
The rungs stack
| Aspect | Explanation |
|---|---|
| What | A production RAG prompt can use all four rungs. |
| Why | Each rung owns a different binding time and failure class. |
| Failure without it | Without stacking: The phrase RAG versus fine-tuning creates a false choice. |
| Cost and complexity | Use an instruction-tuned checkpoint, a system instruction, optional demonstrations for form, and retrieved passages. |
Worked policy assistant
The system uses an 8-billion-parameter generator and serves queries per day. Its window is tokens. The corpus has policy documents averaging 250 tokens. Serving uses FLOPs per token at FLOPs per second. Graphics processing unit (GPU) time costs per hour. The question uses 40 tokens. Configuration 1 uses a 120-token instruction plus the question. It totals 160 tokens, FLOPs, and of prefill. Configuration 2 adds four demonstrations of 250 tokens each. The 1,000-token block costs FLOPs and . Configuration 3 adds eight retrieved chunks of 400 tokens each. The 3,200-token block costs FLOPs and . The complete 4,360-token prompt costs FLOPs and of prefill. At per GPU-hour, it costs per query, per thousand queries, and per day. The retrieval block alone costs per thousand queries. Lewis et al. (2020) reported exact match on Natural Questions for RAG-Sequence. It used BART-large with roughly 400 million parameters and a Wikipedia index. Closed-book T5-11B scored with a model 27 times larger. Retrieval bought ten exact-match points that billion additional parameters did not buy.
Operational decisions from the hierarchy
- Route content plus an absent supporting passage to retrieval.
- Route content plus a present supporting passage to generation or ordering.
- Route form failures to instruction or demonstrations.
- Use an instruction-tuned checkpoint for RAG generation.
- Use a base checkpoint only when the undistorted token distribution is the goal, such as likelihood ranking or infilling.
- Start with zero demonstrations.
- Add demonstrations only when measured format gains justify displacing retrieved chunks.
- Two format examples can be worthwhile if they cut a JSON failure rate to near zero.
- Put facts in retrieval and behavior in instructions or demonstrations.
- Move facts into weights only when they change slowly, apply universally, and never need citation or deletion.
- Move facts out of weights when staleness approaches the change interval, erasure is required, or an auditor needs provenance.
- For strict traceability, require cited spans, entailment checks, abstention without support, and an unsupported-claim metric. Enforce evidence for asserted claims rather than claiming that parametric knowledge is unused.
9.2 Reasoning scaffolds: CoT, self-consistency, Tree of Thoughts, and Graph of Thoughts
What a scaffold changes
| Aspect | Explanation |
|---|---|
| What | A scaffold changes the decoding procedure. |
| Why | The weights, retrieved passages, and question can stay fixed while the model explores more than one reasoning path. |
| Failure without it | A generator can receive both required passages and still fail to combine them for a multi-hop answer. |
| Cost and complexity | Price the family in model calls, generated tokens, prefix reuse, and serial rounds. |
In the motivating support assistant, the supporting passage appears in the assembled context on of the evaluation set.
The hard questions require information from more than one chunk.
A short prompt, with token count depending on the tokenizer, such as Let's think step by step competes with a thirty-call tree under an 95th-percentile latency budget.
Chain-of-thought as a marginal over paths
| Aspect | Explanation |
|---|---|
| What | Precede the answer with a reasoning path . |
| Why | One answer can be reached by several paths. |
| Failure without it | The highest-probability complete path can differ from the highest-probability answer after summing over paths. Token-greedy decoding is not generally the global maximum-probability path either. |
| Cost and complexity | One greedy chain uses one model call. |
Three complete paths can reach the answer “yes, with a cap” with joint probabilities , , and .
Their answer mass totals .
One path can reach “no” with probability .
If the path is the largest complete-path probability and all unlisted paths are smaller, maximum-probability-path decoding selects “no” while the stated answer marginal favors “yes.” The listed probabilities alone do not determine token-greedy behavior, and the remaining probability mass must be allocated consistently to complete the example.
Kojima et al. (2022) used Let's think step by step plus a second answer-extraction call.
On GSM8K, text-davinci-002 rose from to .
Self-consistency
| Aspect | Explanation |
|---|---|
| What | Sample paths at nonzero temperature, extract each final answer, and return the most frequent answer. |
| Why | Counting consistently estimates the answer distribution of the actual sampling procedure when samples are IID conditional on the prompt. Temperature or truncation changes that distribution; it is not automatically the original model marginal. |
| Failure without it | Independent decodes can share the same systematic wrong-context bias without statistical dependence conditional on the prompt. Additional sampling cannot rescue a voting target dominated by one wrong answer; true dependence requires a joint sampling mechanism or a mixed-query interpretation. |
| Cost and complexity | The standard error of a proportion decreases with the square root of sample count while the bill grows linearly with sample count. |
At and , the vote-share standard error is . At , it is . Self-consistency uses a counter, not a scorer. That separates it from best-of- against a reward model.
Majority-vote arithmetic
| Aspect | Explanation |
|---|---|
| What | For IID samples with two possible answers, odd-sized majority voting is correct when more than half of the samples are correct. Multi-answer plurality and correlated samples require different models. |
| Why | This gives a concrete break-even before spending inference compute. |
| Failure without it | Teams assume more samples always help. |
| Cost and complexity | At , majority-of-five scores . Majority-of-nine scores . The first five samples buy points over one sample. The next four buy more points. At , majority-of-nine scores , below the single-sample accuracy. |
Voting can improve accuracy when the correct answer has sufficient probability under the sampled distribution. It does not generally eliminate systematic bias; treating vote share as calibrated confidence requires validation.
Chain, fan, tree, and graph
| Aspect | Explanation |
|---|---|
| What | The four topologies allow different edge operations. |
| Why | A chain gives transparency, a fan gives repeated exploration, a tree gives branching and pruning, and a graph adds merging and revision. |
| Failure without it | Without an evaluator: A tree prunes good and bad branches at similar rates while adding serial rounds. |
| Cost and complexity | A Tree of Thoughts expands children, scores states, keeps , and repeats for levels. |
Graph of Thoughts permits aggregation and refinement edges that a tree cannot draw. Yao et al. (2023) reported GPT-4 on Game of 24 at with CoT. Self-consistency over 100 samples scored . A breadth-5 tree scored . Besta et al. (2024) reported Graph of Thoughts improving sorting quality by over Tree of Thoughts at more than lower cost. Game of 24 provides an exact arithmetic state evaluator. A half-finished policy answer does not. The 70-point gain measures the evaluator as much as the tree. Wei et al. (2022) found CoT gain to be an emergent property of scale in their setting. Below roughly 100 billion parameters, their models produced fluent but illogical chains and did not beat standard prompting. Distillation on reasoning traces moved the threshold downward. The remaining failure is unchanged. A scaffold the generator cannot execute costs tokens and buys nothing.
Worked scaffold costs
The shared prompt has instruction, evidence, and question tokens: input tokens. Each chain uses output tokens. Assume each sampled chain has correctness probability and the two-answer IID voting model; this is not automatically the accuracy of a greedy chain under another decoding policy. One greedy chain processes tokens. It costs FLOPs, of GPU time, and per query. Five uncached self-consistency samples process tokens. They cost FLOPs, , and . Accuracy is . Five samples with a shared key-value (KV) cache process tokens. They cost FLOPs, , and . They preserve the same accuracy and are times cheaper. The samples can batch, so is GPU time rather than wall-clock time. A tree with , , and generates 3, then 6, then 6 children. Fifteen generation calls plus fifteen score calls make thirty model calls. Each generation uses 120 state tokens plus 80 generated tokens. Each score uses 120 state tokens plus 5 generated tokens. The cached tree adds marginal tokens to one 3,360-token prefill. It processes tokens, FLOPs, , and . Without prefix reuse, the tree calls reread prompt tokens and add marginal tokens, totaling processed tokens. The proxy is , approximately and . This is times the cached tree and times a single-chain token-work proxy. Three levels each contain a generation stage and a dependent scoring stage; parallel siblings do not remove these dependencies. Wang et al. reported PaLM-540B on GSM8K at for greedy CoT and with sampled chains. Plugging into an IID two-answer majority model with random tie-breaking predicts approximately , not . More importantly, greedy accuracy does not establish each sampled chain's correctness probability, and real answers need not have two labels. The reported result therefore does not validate that toy majority calculation.
Operational decisions for scaffolds
- Partition failures before choosing a scaffold.
- Use scaffolds only where the supporting passage is present.
- Start with CoT plus self-consistency at and a shared prefix cache.
- Raise toward 20 when three-two splits routinely decide answers.
- Drop to one greedy chain when the task is extraction and all five samples agree on the evaluation set.
- Use sampling temperature around for an ensemble and greedy decoding for one answer.
- Deterministic greedy decoding with fixed inputs and serving state returns the same output; nondeterministic kernels or other stochastic components can still vary.
- Lower temperature when parseable output rate falls. Do not infer that raising temperature fixes a unanimously wrong system; diagnose missing evidence and systematic bias first.
- Reject a tree or graph until its evaluator beats chance.
- Exact checks, Structured Query Language (SQL) parsing, arithmetic checks, and entailment against a cited span can qualify.
- Budget a fan as one parallel round and a depth- tree as serial generate-and-score rounds.
- Log the full vote distribution. A three-two split and a five-zero split should not produce the same confidence signal.
9.3 When more scaffolding makes things worse
The execution discount
| Aspect | Explanation |
|---|---|
| What | Treat every model-executed stage as an imperfect program step. |
| Why | Downstream stages consume upstream outputs, so execution reliability multiplies. |
| Failure without it | Without this model: Teams add stages as if their gains combined additively. |
| Cost and complexity | A decomposer, per-subquestion retriever, verifier, and synthesizer create four rounds and multiple failure boundaries. |
In the source example, that pipeline scores on the full multi-hop slice. A two-line fan of five scores in one round at one sixth of the calls. For stages that are all required to succeed, let be the conditional probability that stage succeeds given previous required successes. The chain rule then gives the product below without an independence assumption. Using unconditional would need independence or another justified joint model. Requiring every exploratory call to succeed is a pessimistic scenario, not a necessity for all tree algorithms.
Realized accuracy mixes the perfectly executed design with its misfire state:
For , the equality with incumbent accuracy is . A target above is infeasible, a target at or below requires no execution improvement, and has no meaningful execution crossover. An architectural label does not identify these conditional accuracies.
Use , , and . The equality is . A thirty-call tree therefore needs per-call reliability of . At per call, the tree executes end to end only of the time. The design gain is additive, but the execution discount is geometric.
Deterministic aggregation and reversible decisions
| Aspect | Explanation |
|---|---|
| What | Prefer a counter outside the model and prefer reranking over pruning. |
| Why | A counter adds no model execution probability. Reversible stages preserve recovery paths. |
| Failure without it | A learned selector adds systematic bias, and irreversible pruning compounds errors across depth. |
| Cost and complexity | A chance scorer that keeps 2 of 3 children preserves the correct path through three levels with probability . |
Jiang et al. (2023) built the large language model (LLM) system LLM-Blender. It ranks outputs from eleven open-source models pairwise and sends top candidates to a fusion model. Peiyi Wang and colleagues (2023) found that an LLM judge can change its verdict when candidate order is swapped. Their fix scores both orders and averages, which doubles comparison calls. Self-review can reinforce the model’s own answer and raise confidence without improving correctness. The source connects this mechanism to model collapse.
Reliability audit
A five-sample fan gets all five parseable outputs with probability at per-call parseability. Exactly four parse with probability . Fewer than four parse with probability . A four-sample vote with random tie-breaking scores at . Define the parseability policy explicitly: valid samples, correctness conditional on validity, random tie-breaking for even , and fallback accuracy when . Summing over gives accuracy , or , compared with ideal five-vote accuracy . Other fallback, invalidity/correctness dependence or retry policies change the result. A thirty-call tree at execution and a perfect scorer realizes . The scenario tree uses calls versus for the fan and has three dependent generate-and-score levels. At and perfect pruning, its accuracy trails the explicitly modeled fan by percentage points; arithmetic work is not a wall-clock latency guarantee. If its evaluator keeps the correct branch of the time, full execution falls to . Realized accuracy falls to , seven points below the fan. Under this all--calls-required scenario, pruning survival per level would need , hence . No feasible pruning reliability can make this tree beat that fan while the other assumptions stay fixed. The earlier threshold was incorrect. Improve execution, design/fallback accuracy or the all-calls-required design before considering evaluator gains. Measure this on 200 labeled pruning decisions before writing orchestration. On Game of 24, a perfect finite search has and the self-consistency fallback is . Within the specified mixture with and , the observed can be represented by . This is an implied mixture coefficient, not an independently measured execution rate or proof that all remaining error is execution failure. Even a free exact evaluator leaves a large execution discount. Count model-executed steps as a reliability budget. Prefer fewer than roughly ten unless the weakest stage has a measured . Log stage validity, correct-branch survival, truncation, and dropped constraints separately from final answer accuracy. Ablate downward one stage at a time. On 500 questions at accuracy near , one arm has standard error about . A two-point change on questions is not resolved by looking at one arm's standard error alone; use the paired outcomes or an independent difference interval as appropriate. With roughly discordant pairs and a net difference near , the uncorrected signed McNemar normal statistic is approximately ; the corresponding chi-square statistic is , below for a nominal two-sided test. Exact counts, discreteness and continuity correction matter.
9.4 Retrieving more can hallucinate more
Recall is not answer accuracy
| Aspect | Explanation |
|---|---|
| What | Separate passage recall from passage utilization. |
| Why | A passage can be present and still lose to a distractor inside the generator. |
| Failure without it | Raising top- from 5 to 40 can raise recall from to and lower answer accuracy by about five points. |
| Cost and complexity | More passages increase prompt tokens and multiply selection competition. |
The naive model assumes perfect use of the gold passage and closed-book fallback otherwise.
This expression can only rise with recall. Production breaks its two assumptions. When the gold passage is absent, the model can ground in a plausible wrong passage instead of returning to parametric memory. This co-occurrence substitution gives no-gold accuracy , with .
Utilization and margin
| Aspect | Explanation |
|---|---|
| What | In a deliberately simplified generator-selection model, hold the gold score fixed at and draw distractor scores independently from . |
| Why | Gold wins only if every distractor score is below its fixed threshold. |
| Failure without it | If the gold score is itself random, conditioning on it induces a different integral, not a product of the marginal one-competitor win probabilities. |
| Cost and complexity | Here . For random gold score with density , . Neither model follows automatically from a cross-encoder's retrieval scores. |
The relative penalty per added passage is . At , . At , . At , . A reranker can change selected passages and order, but a larger retrieval-score margin does not automatically increase the generator’s effective score margin. That causal link requires a separate intervention or measurement.
The non-monotone accuracy model
is the probability of selecting the gold passage in this scenario, not measured grounding or faithfulness. The accuracy formula further assumes correctness whenever gold is selected and constant fallback accuracy in every other state, including gold present but not selected. Measuring only after deleting gold does not establish that second conditional accuracy. Recall rises with while utilization falls. Karpukhin et al. (2020) reported Dense Passage Retrieval (DPR) accuracy on Natural Questions of at top-20 and at top-100. The reported anchors bracket . Use a log-linear scenario curve there; values at are extrapolations, not interpolation or reported DPR measurements:
Marginal recall decays as . Marginal dilution stays near constant at . The optimum solves:
At , the continuous stationary point of this scenario is . Check nearby integers and feasible-domain endpoints. This remains a toy optimum, not a deployment guarantee. At , the continuous stationary point of this scenario is . Check nearby integers and feasible-domain endpoints. This is below the – anchor bracket and is an extrapolation, not a validated optimal retrieval depth. At , the continuous stationary point of this scenario is . Check nearby integers and feasible-domain endpoints. This is below the – anchor bracket and is an extrapolation, not a validated optimal retrieval depth. A stationary point below the measured range calls for a held-out depth sweep and ranker/utilization diagnosis; it does not mathematically mandate a particular repair. Half a standard deviation of margin moves the optimum by more than a factor of four. A longer context window does not change the number of competing passages. Liu et al. (2023) found that extended-context variants of the same models were no better at using their context and barely moved the accuracy curve.
Worked retrieval audit
The chunks use 512 tokens. Closed-book accuracy is . Misgrounded accuracy after deleting every gold passage is . Input costs per million tokens. Under the stated scenario at and , , , the gold-selection proxy is , and . These are derived values, not measured bi-encoder or reranker outcomes. Grounding is and answer accuracy is . The 2,560-token prompt costs per query. Under the stated scenario at and , , , the gold-selection proxy is , and . These are derived values, not measured bi-encoder or reranker outcomes. Utilization falls to . Grounding falls to and accuracy falls to . The 20,480-token prompt costs per query. The input bill rises eightfold while scenario accuracy falls by percentage points. As a separate counterfactual, increase the generator-selection parameter from to while holding the scenario recall curve fixed. A top- cross-encoder does not establish those assumptions by itself: reranking also changes the recall curve of the presented subset, and generator utilization must be measured. Under the stated scenario at and , , , the gold-selection proxy is , and . These are derived values, not measured bi-encoder or reranker outcomes. Only the toy utilization parameter changes in that calculation. If the actual passages, order and generator computation are unchanged, altering an external score alone cannot change the answer. Under the stated scenario at and , , , the gold-selection proxy is , and . These are derived values, not measured bi-encoder or reranker outcomes. It uses tokens and costs . The last points from 10 to 40 passages cost four times the input bill. The input-only difference is per million queries, before the additional prompt tokens of prefill work. The modeled accuracy gain is conditional on the same scenario recall and utilization assumptions. Under the stated scenario at and , , , the gold-selection proxy is , and . These are derived values, not measured bi-encoder or reranker outcomes. The scenario crosses the baseline at continuous ; the first integer below baseline must be checked separately. Liu et al. (2023) observed the inversion at 20 documents in multi-document question answering. Omitted positional effects can change the optimum, but do not make this stationary point a proven upper bound. Correlated distractors, multiple gold passages, answer-dependent fallback and changes in reranked recall alter the curve. Duplicate correlation can reduce the effective number of independent competitors without guaranteeing that deduplication improves answer accuracy. Gate releases on answer accuracy, not recall at top-. Measure by deleting the gold passage from every context. Measure dilution by fixing the gold position and injecting distractors. Prefer a score cliff over a fixed top- when scores are calibrated. Retrieve conditionally when closed-book answers are reliable. Retrieve unconditionally when every answer requires a citation, while accounting for the accuracy trade. Mallen et al. (2023) found the unassisted model beating retrieval augmentation on high-popularity subjects.
Diagrams
Figure 9.1
Diagram description and source
flowchart BT
C["1. completion: bound at pre-training, theta_pre, continues q, +0 tokens"]
I["2. instruction: bound at post-training, theta_IT, command, +120 tokens, 5.6 ms"]
L["3. in-context learning: bound at prompt deploy, fixed before q, +1,000 tokens, 47 ms"]
R["4. RAG: bound per request, passages selected after q, +3,200 tokens, 151 ms"]
C --> I
I --> L
L --> R
Figure : The four rungs are cumulative rather than alternative, and they differ in the one property that decides everything else - how late the information they carry can be bound, from the pre-training corpus up to the request itself - with the price of that lateness paid in prompt tokens on every query.
Figure 9.2
Diagram description and source
flowchart LR
subgraph Chain["chain - CoT: 1 call"]
q1[q] --> c1((step)) --> c2((step)) --> a1[a]
end
subgraph Fan["fan - self-consistency: m parallel calls"]
q2[q] --> f1((path 1)) --> A1[A]
q2 --> f2((path 2)) --> A2[A]
q2 --> f3((path 3)) --> B1[B]
A1 --> count[count]
A2 --> count
B1 --> count
end
subgraph Tree["tree - Tree of Thoughts: about dkb calls in d serial rounds"]
q3[q] --> t1[0.9]
q3 --> t2[0.2]
q3 --> t3[0.7]
t1 --> t11((child))
t1 --> t12((child))
t3 --> t31((child))
t3 --> t32((child))
t12 --> a3[a]
end
subgraph Graph["graph - Graph of Thoughts: merge and refine"]
q4[q] --> g1((thought 1))
q4 --> g2((thought 2))
g1 --> merge((merge))
g2 --> merge
merge --> a4[a]
merge --> refine((refine))
refine --> merge
end
Figure : The four scaffolds differ in one structural property - what an edge is allowed to do - and every cost follows from it: the fan is embarrassingly parallel and needs no scorer, while the tree buys exploration only by adding a serial round per level and a state evaluator at every node.
Figure 9.3
realized accuracy
90% | tree reaches 85%
80% | ____/
70% |---------------- fan of five: 68.3% ---* break-even q = 0.982
60% | _________/
50% | _______________/
40% |____________/
0.90 0.94 0.98 1.00
per-call execution reliability q
tree: b = 3, d = 3, 30 model calls
A = 0.45 + 0.40 q^30
Figure : The scenario curve assumes every one of calls must succeed with common conditional reliability . It crosses an ideal fan target at . At , even perfect pruning remains below the parseability-modeled fan, so no rescues the tree under the unchanged assumptions. This is a reliability illustration, not an empirical latency or accuracy frontier.
Figure 9.4
answer accuracy A(k)
90% |
80% | mu = 3.0 _________* k = 40 ______
70% | mu = 2.5 * k = 9 \_______________
60% | \_______________
50% | mu = 2.0 \__________________________
42% |----------- closed book --------------* k about 73
40% | \
5 10 20 40 100
passages sent to generator k, log scale
m = 0.31
R uses DPR top-20 recall 0.784 and top-100 recall 0.854
Figure : The curve is an explicitly conditional toy model: fixed gold score, independent Gaussian distractors, perfect correctness on gold selection and common fallback elsewhere. Only recall at and is anchored to reported DPR results. Values below , generator margins and the displayed optima are constructed, not measured. A reranker must demonstrate its own presented-set recall and utilization curve.
Whiteboard pack
What to draw
- Draw four stacked boxes labeled completion, instruction, ICL, and RAG.
- Write the binding time beside each box.
- Add the four prompt slots: instruction, demonstrations, retrieved passages, query.
- Draw a fan of five sampled chains with a counter.
- Draw a depth-3 tree with generation and score calls.
- Write under the tree.
- Draw recall rising with top-.
- Draw utilization falling with top-.
- Multiply them into a curve with an interior maximum.
Spoken script
Start with the four prompt rungs. Completion recalls from weights, instruction sets behavior, examples fix form, and retrieval binds evidence after the query. Then separate retrieval from decoding. A reasoning scaffold only changes how many paths we sample and how we combine them. A fan counts answers, while a tree needs serial scoring and reliable pruning. Its execution probability multiplies across calls, so thirty reliable calls succeed together only of the time. Finally, split retrieval quality into recall and utilization. Raising top- improves recall but adds distractors. Ranker margin decides where answer accuracy peaks.
Interview traps
1. Is RAG just in-context learning with a vector database?
Mechanically, both condition frozen generator weights on context tokens. Demonstrations can be query-selected just as evidence can; distinguish their role and provenance rather than claiming a universal binding-time difference. A vector database is one retrieval implementation, not the definition of RAG.
2. Will self-consistency turn 60% grounded question-answering accuracy into 75%?
No. Majority-of-five reaches , while majority-of-nine reaches . Voting can recover probability mass already present across independent paths, but it cannot correct a wrong or missing passage that biases every sample.
3. When does more scaffolding make results worse?
It gets worse when the scaffold adds many model-executed stages, weak evaluators, irreversible pruning, or systematic comparators. Thirty calls at per-call reliability execute together only of the time. A chance scorer that keeps 2 of 3 branches preserves the correct path through three levels only of the time.
4. When does more retrieval make results worse?
It gets worse when marginal recall from another passage is smaller than the utilization loss from another competitor. At ranker margin , moving from 5 to 40 passages raises recall from to but lowers answer accuracy from to . Measure distractor sensitivity and no-gold accuracy before raising top-.
5. Does a million-token window remove the need for ranking?
No. A larger window removes a token-capacity limit but does not remove competition among passages. Dropping the reranker lowers the gold passage’s margin while raising the number of competitors, which you can test by fixing the gold position and sweeping distractor count.
Key numbers
| Topic | Source number | Meaning |
|---|---|---|
| Policy corpus | tokens | full -token windows plus tokens; windows including the remainder |
| Retrieval block | tokens | selection ratio, not lossless compression |
| Prompt stack | tokens | and per thousand queries |
| Binding latency | 3 days versus about 5 seconds | stale versus about |
| RAG-Sequence | exact match | Ten points above closed-book T5-11B at |
| Majority voting | to with 5 samples | with 9 samples |
| Cached fan | tokens | times cheaper than the uncached fan |
| Cached tree | calls across generate-then-score levels | token-work proxy; dependencies do not establish p95 latency |
| Tree break-even | per call | yields only end-to-end execution |
| Pruning | in the full scenario | Infeasible at ; the earlier threshold was wrong |
| DPR anchors | at top-, at top- | ; below is extrapolation |
| Ranker margin | and give different toy stationary points | Generator-selection margin is not automatically a retriever score margin |
| Weak margin | Accuracy at top-100 | Below closed-book and crossing near 73 passages |
| Reranked top-40 | Scenario at | The scenario gives ; neither is a measured reranker result |
| Last points | additional input-only cost per million queries | Modeled accuracy gain depends on the stated scenario; not a measured reranker result |
00-START-HERE · 01-READING-ROUTES · 08_reading_the_machine_circuits_induction_heads_and_attribution · 10_prompt_sensitivity