00-START-HERE · 01-READING-ROUTES · 05_data_privacy_and_the_legal_surface · 07_in_context_learning_the_mechanism_rag_rides_on This chapter explains how to allocate training, serving, memory, and retrieval budgets for a Retrieval-Augmented Generation (RAG) system.
TL;DR
- Training compute is approximately floating-point operations (FLOPs), while generation costs FLOPs per token.
- Kaplan allocation drives the token-to-parameter ratio down with budget, while Chinchilla keeps it near at its scale.
- Chinchilla minimizes training compute, not lifetime cost. Serving overtakes training at .
- Memory has three bills: weights, optimizer state, and the key-value (KV) cache. Retrieval controls the variable cache bill through context length.
- At fixed non-embedding parameter count, architecture shape changes loss only a few percent. Shape still changes cache size and decode latency.
- Test-time search can help when proposals contain better candidates and selection is reliable; lifetime cost comparisons require both serving slopes and training costs.
- Retrieval can replace parameters that store facts. It cannot replace the competence needed to read and use retrieved evidence. Datastore growth can worsen the rank distribution. Measured deep candidate retrieval plus successful reranking can keep generator presentation depth fixed; mean rank alone does not guarantee recall.
The story
Think of the system as a library with a skilled clerk. Model parameters pay for the clerk’s reading and reasoning skill, while the datastore pays for shelves that can be updated cheaply. A larger clerk may remember more books, but every answer then costs more to serve. A smaller clerk can consult the shelves, but only if the clerk can read the right passage and the catalog can surface it. The economic choice is therefore not simply big model versus small model. It is how much permanent skill to buy, how much factual content to store externally, and how much search and verification to purchase per query. As the library grows, a reranker prevents the clerk from receiving an ever larger pile of passages.
Decoder table
| Term | Meaning in this chapter | Decision it controls |
|---|---|---|
| Parameter count under the explicitly stated model or scaling-fit convention | Compute proxies use the applicable dense body/output work; hardware sizing uses all stored parameters. | |
| Number of processed training tokens | Training allocation and repeated-data cost | |
| Training compute in FLOPs | Budget constraint | |
| Test cross-entropy in nats per token | Scaling-law outcome | |
| Parameter scaling exponent, about under Kaplan | Loss reduction from more parameters | |
| Data scaling exponent, about under Kaplan | Loss reduction from more tokens | |
| Batch size in Kaplan’s allocation result | Part of the token-count scaling | |
| Training steps in Kaplan’s allocation result | Part of the token-count scaling | |
| Training-token volume in the lifetime bill | One-time training cost | |
| Processed inference tokens under the parameter-work proxy | Include input prefill and output decode; it is not automatically output tokens alone. | |
| Bytes used to store one number | Weight and cache memory | |
| Transformer layer count | Attention work and KV cache | |
| Model width | Attention work, body size, and cache | |
| Context length in tokens | Attention work and per-request cache | |
| Number of key and value heads | KV-cache width | |
| Head dimension | KV-cache width | |
| Transformer-body parameter count | Compute-relevant model size | |
| Vocabulary size | Embedding-table memory and tokenization | |
| Model depth | Body size, cache, and sequential decode | |
| Input tokens for one query | Prefill cost | |
| Output tokens for one query | Decode cost | |
| Lifetime query count | Amortization of pre-training | |
| Per-query compute multiplier of a test-time method | Breakeven against larger pre-training | |
| Positive intersection of two complete lifetime-cost functions, when one exists | Requires both training intercepts and per-query slopes. | |
| Model parameters | Parametric storage path | |
| Mean normalized number of chunks outranking gold | A scenario trend for mean rank, not a recall guarantee or fixed universal retriever constant. | |
| Mean rank of the gold chunk | Empirical input to | |
| corpus size | Number of datastore chunks | Retrieval depth and index memory |
| Chunks passed toward the generator | Recall, context, and answer-bearing fraction | |
| Deep retrieval count before reranking | Corpus-growth cost | |
| Maximum chunks that fit the context window | Retrieval ceiling | |
| Token-count reduction from a better tokenizer | Prefill, cache, and context savings | |
| Floating-point operation (FLOP) | One numerical operation in the chapter’s compute estimates | Prices training, serving, embedding, and reranking |
| Cosine learning-rate schedule | A schedule that decays the training rate over a run’s actual length | Explains the methodological correction behind Chinchilla |
| Numeric precision | -bit floating point (fp32), bfloat16 (bf16), -bit floating point (fp8), -bit integer (int8), or -bit integer (int4) storage | Determines weight memory and card boundaries |
| Concurrency | Requests served at the same time | Multiplies the per-request KV-cache bill |
| Gold chunk | The labeled passage containing the evidence needed for an answer | Supports reading tests, rank measurement, and reranking decisions |
| Kaplan allocation | grows as and grows as | Favors parameters increasingly at larger budgets |
| Chinchilla allocation | and each grow as | Holds the token-to-parameter ratio constant |
| Post-Chinchilla allocation | Smaller models trained on far more tokens | Trades a small loss penalty for lower serving cost |
| Iso-FLOP curve | Loss across model and token allocations at fixed compute | Finds an allocation minimum |
| Compute-optimal | Minimum training compute for a target loss | Correct only for a training-only objective |
| Over-trained | More tokens per parameter than Chinchilla | Reduces parameter count and serving cost |
| Weight memory | bytes | Fixed serving cost |
| Training state | Weights, gradients, master weights, and Adam moments | Full fine-tuning feasibility |
| KV cache | Keys and values retained for every token and request | Serving concurrency |
| Attention correction | Parameter-free attention work omitted by | Long-context compute accuracy |
| Low-rank adaptation (LoRA) | Small trainable matrices added to frozen weights | Fine-tuning state reduction |
| Activation checkpointing | Recompute selected forward activations during backward | A full extra-forward proxy adds , but actual policies differ. |
| Mixture-of-experts (MoE) | Store many parameters but activate only some per token | Splits memory sizing from compute sizing |
| Shape independence | Loss changes only a few percent across a wide shape range at fixed | Moves shape choice to serving constraints |
| Embedding table | Vocabulary lookup parameters, plus a separate output projection when untied | Input lookup and output-vocabulary scoring have different compute costs. |
| Convergence | Validation loss plateau for one model-data pair | Not a compute-budget allocation rule |
| Repeated-data ceiling | A study-specific regime of near-fresh returns through roughly four epochs | A heuristic to validate, not a hard universal ceiling. |
| Proposer | Produces candidate answers | Uses test-time compute to explore |
| Verifier | Scores passages or answer chains. Pass-at- checks whether any of proposals is correct. | Converts exploration into accuracy |
| Best-of- | Generate complete answers and select the top score | Default search at larger budgets |
| Beam search | Prune partial solutions using verifier scores | Stronger at small budgets on easier tasks |
| Lookahead search | Add Monte Carlo rollouts to beam search | Loses at matched budget in the cited result |
| Process reward model (PRM) | Scores reasoning steps | Stronger signal than final-answer-only scoring |
| Outcome reward model | Scores only the final answer | Weaker verifier signal in the cited comparison |
| Competence parameters | Support syntax, instructions, attention, and copying | Cannot be outsourced to retrieval |
| Content parameters | Support closed-book factual production | Can be partly substituted by a datastore |
| Write path | Cost to add or update one fact | Main economic advantage of retrieval |
| Reranker | Cheap discriminator over retrieved candidates | Holds generator context flat |
| Product quantization | Compresses stored vectors | Makes large index memory practical |
Core mechanics
Mathematical conventions
Storage units are decimal except explicit binary units: , . Here context lengths mean tokens. Parameter counts and token counts are distinct quantities; the letter means billion only in an explicitly labeled model/count abbreviation, not in byte expressions. Use the stated forward and training proxies at assumed and per GPU-hour. These are compute-equivalent estimates, not measured latency or invoices, and omit material bandwidth, communication, retrieval and serving overhead. State the relevant parameter-count convention for each model; scaling-fit conventions and full checkpoint size need not match. Keep full precision through the calculation, then use for rounded results.
6.1 Kaplan, Chinchilla, and post-Chinchilla token-to-parameter ratios
What the scaling laws say
The basic compute relation is:
Kaplan et al. fit separate power laws for parameters and data. The straight-line log-log fits span seven orders of magnitude:
Their allocation rule is:
Kaplan also reports batch size proportional to and steps proportional to . Those exponents combine to give . The token-to-parameter ratio therefore obeys:
The ratio falls as the compute budget grows. GPT-3 uses parameters and tokens, or tokens per parameter. Gopher uses parameters and tokens, or tokens per parameter.
Why Chinchilla changed the answer
Hoffmann et al. matched the cosine learning-rate schedule to each run’s actual length. Kaplan had used one schedule across runs of different lengths. That choice undervalued longer training because some runs were evaluated before the schedule finished decaying. Hoffmann et al. also counted embedding parameters. Three estimation routes agreed on exponents near one half:
Thus:
The ratio is constant. At Chinchilla’s scale, its level is about tokens per parameter. The statement that model size and tokens scale one-to-one refers to exponents. It does not mean one token per parameter. Reading it that way creates a times error. Chinchilla uses parameters and tokens. Its ratio is . Gopher uses parameters and tokens. Its ratio is . The matched-budget check is:
Under this parameter-work proxy, Chinchilla's budget is larger than Gopher's, using Gopher as the denominator. Their parameter counts differ by four. The cited MMLU scores are and , a -percentage-point difference, not a relative gain. At the stated sustained throughput and hourly price, the unrounded Gopher proxy corresponds to approximately compute-equivalent GPU-seconds, GPU-hours and million. This is not the measured cost of the reported run, and parallel wall time requires a separate scaling assumption.
Why the training-only optimum fails after deployment
Chinchilla's reported optimum concerns a training-compute/loss objective within its fitted regime. A parameter-forward serving proxy scales with and processed inference tokens; it has no explicit training-token term, but actual serving cost also depends on attention, bandwidth, precision, batching and hardware. The lifetime bill is:
Training and serving are equal when:
Therefore:
With the same and token-work conventions and , cancels and the two proxy work totals are equal at . Here counts processed input and output tokens under the proxy, not only generated tokens unless input work is negligible. For the stated Chinchilla training volume, the equality is processed inference tokens. Different utilization or dollar rates can shift a monetary crossover. Once expected inference volume enters the objective, the optimum moves toward a smaller model trained on more tokens. The shift grows with serving demand. Llama 1 at saw tokens, or per parameter. Llama 2 at saw tokens, or per parameter. Llama 3 at saw over tokens, or per parameter. The last ratio is times Chinchilla’s ratio.
Worked budget comparison
Use FLOPs. For Chinchilla, impose :
This scenario is approximately B parameters on T processed tokens. Bf16 parameter payload is approximately , excluding caches and serving overhead, so it cannot fit on one card. For the post-Chinchilla ratio, impose :
This is parameters on tokens. The bf16 weights use . The parameter-forward work is approximately for the B allocation and for the B allocation. Their ratio is approximately under identical token accounting. At processed inference tokens, serving work is approximately versus . Adding the shared training budget gives approximately versus , a ratio of approximately . These are work totals, not full ownership cost or a proof of equal task quality. The source expects a quality trade-off between these allocations, but the two ratios alone do not prove which has lower loss on a new workload. Iso-FLOP minima can be flat nearby; verify quality, data repetition and hardware constraints on the actual task before interpreting the serving-work saving. The B, T cross-check gives . Relative to the rounded reported , the difference is approximately . Agreement with a rounded work estimate is a consistency check, not an independent validation of measured training efficiency.
Practical decision
Ask for expected lifetime processed-token volume before choosing . A ratio near is a reported training-only reference at one regime, not a universal floor for every served model. Smaller models trained on more data can lower serving work when quality holds up, but token availability, repetition, training budget and required competence also bind. Use iso-FLOP experiments rather than maximizing a token/parameter ratio without constraints.
6.2 FLOPs, attention, and memory arithmetic
What contains
For a dense linear layer, forward matrix multiplication is approximately two FLOPs per weight per token, counting multiplication and addition; backward input and weight gradients each add a similar matrix-multiply cost. Biases, nonlinearities, norms, embeddings and attention are separate. This approximation motivates the parameter-work constants below, not exact operation counts for every architecture. Backward computes a gradient for the inputs and a gradient for the weights. Each costs . Backward is therefore .
Across training tokens:
Generation has no backward pass. Its parameter term is per token.
What omits
For a causal prefill of length , triangular query-key scores and value aggregation together contribute approximately forward FLOPs, or averaged per prompt token. A standard dense body with roughly parameters has forward parameter work approximately per token. This particular comparison is a forward-prefill approximation. Training needs the attention backward work too; decode at current context length uses a different per-step attention count. The omitted-to-parameter ratio is:
For the body approximation, attention-to-parameter forward work is . The condition says only that this ratio is below one, not that it is negligible. At , equality occurs at ; at the ratio is , and at it is . Using an actual B parameter proxy rather than the body estimate changes those ratios, as in the worked prefill below.
The three memory tiers
Weight payload is bytes, with nominal for fp32, for bf16, for int8 and for packed int4. Quantized formats also need scales, zero points, packing and sometimes higher-precision tensors; nominal bits alone do not give complete checkpoint or serving memory. A model uses at fp32. It uses at bf16. It uses at int8. The fp32 weights already overflow one card. Full Adam fine-tuning uses bytes per parameter before activations. The source counts bytes of bf16 weights, of gradients, of fp32 master weights, of momentum, and of variance. Pure fp32 also totals bytes through four -byte states. An model needs . A model needs . The KV cache uses:
bytes per token. For Llama 8B, use layers, key-value heads, head dimension , and bf16.
Cache payload multiplies by resident sequence length and concurrent sequences. After parameter payload on an card, the residual is only an upper budget before workspaces, allocator reserve, activations and other serving state. At , and tokens per resident sequence, cache-only ceilings are respectively , and requests. Reserving output growth or overhead lowers them; they are not measured throughput figures. Pricing deployment by parameter count alone fails because context length changes concurrency. It also fails for MoE models. Mixtral 8x7B stores parameters but activates per token. Its memory resembles a model. Its compute resembles a model.
Fine-tuning choices
Serving the at fp32 fails at . Serving it at bf16 uses and leaves . That cuts free cache memory from to , or by times. A deeper and wider model also caches more per token. With the stated training-state layout, B and B use and . Two and six cards are aggregate state-capacity lower bounds before activations and communication; fit still depends on sharding and the actual optimizer/precision layout. A rank- LoRA matrix trains values. Rank- LoRA on the query and output projections of all layers in the model trains:
parameters. The corresponding full matrices contain values. The factor count is exactly as large, with reduction for these square matrices. At a specified -byte trainable-state layout, adapter state is above the frozen bf16 base, excluding activations. This is not the ratio of total training memory or total backward compute. If activation checkpointing recomputes one full extra forward pass, parameter work rises from approximately to , an increase of . Selective checkpoint policies, frozen weights and attention recomputation change the actual overhead; “exactly ” would be false precision.
RAG prefill check
An prompt on has a parameter prefill term of:
FLOPs. Attention adds:
FLOPs. The combined forward proxy is approximately , corresponding to compute-equivalent seconds at the assumed throughput, before other first-token work. Attention is approximately of this example's parameter term, not of an actual B model. Cache payload is exactly per -token sequence; the cache-only concurrency ceiling is . At tokens, cache payload is , leaving a cache-only ceiling of requests in the nominal residual budget. Parameter work is and causal forward attention approximately , for total approximately . The compute-equivalent time is approximately , or times the -token estimate for four times the prompt length. Actual latency and concurrency need a serving benchmark. The bf16 weight rule also predicts for Llama 405B. An eight-card node with per card holds . The model therefore cannot fit on one such node at bf16. The source notes a -bit floating-point (fp8) variant and a multi-node path for bf16.
Practical decision
Answer fit questions with weights, training state, and KV cache. Use LoRA by default above about on single-node hardware. Buy concurrency first by shortening and reranking context. Add attention and checkpointing corrections to . Use active parameters for MoE compute and stored parameters for memory. Use bf16 serving weights unless a card boundary forces int8 or int4. The source calls quantization the cheapest to times memory reduction in the stack. Use -bit frozen base weights for quantized LoRA when fine-tuning memory is the binding constraint.
6.3 Three observations that change decisions: shape, embeddings, convergence
Shape is nearly free in loss
At fixed , changing feed-forward ratio, aspect ratio, and head dimension moves loss only a few percent across the measured range. Doubling changes loss by:
That is a reduction. A ten-fold increase gives:
That is a reduction. A shape sweep can cost more compute than its loss gain. The loss result does not make shape irrelevant. It moves shape selection to serving. Under ordinary multi-head attention, cache payload is bytes per token. It depends explicitly on depth and width, which also affect ; saying it is independent of parameter count would be misleading. Grouped-query attention instead uses KV width. More sequential layers can increase decode latency, but layer count alone is not a throughput law. The result only holds within a wide practical range for dense decoder-only transformers. One layer remains bad at any width. A head dimension of remains bad. MoE breaks a single- comparison because stored and active parameters differ.
Embeddings distort parameter comparisons
A standard transformer body is approximately:
The embedding table is:
The body grows quadratically with width. The table grows linearly. Counting both bends the scaling fit because the embedding share changes with model size. GPT-2 small uses layers, width , and vocabulary . Its body is parameters. Token and positional lookup tables total . The lookup share is . Llama 3 70B uses width and vocabulary with untied embeddings. Its embedding count is against total. The share is . Using the stated body approximation, GPT-2's token-plus-position tables add over its body, and are approximately of the resulting total. Llama's untied input-plus-output parameters are approximately of the stated B total and add approximately over the remainder. The difference in log inflation is approximately decades. Shares of total and additions over the body are different denominators. XLM-R base and BERT-base have comparable transformer bodies near the M approximation. At vocabularies and and width , the input-table difference is parameters, not that many vocabulary rows. Bf16 payload difference is approximately . Input embedding lookup does not multiply by every vocabulary row, so a body-only encoder-forward proxy is near for both; masked-LM or generation heads that score the whole vocabulary add work. Advertised total sizes are not directly body-compute ratios. A larger vocabulary can still help by emitting fewer tokens. If it reduces token count by a factor , prefill and cache fall by . A fixed context can also hold times as much evidence. Choose vocabulary for tokenization efficiency on the actual corpus. Do not treat lookup rows as reasoning capacity.
Convergence misallocates a fixed budget
At fixed compute, a larger model stopped before convergence can outperform a smaller converged model. Reused tokens may have lower marginal value than fresh ones. The cited study finds a roughly four-epoch near-fresh regime in its experiments; this is not a hard rule that all later epochs have zero value or that every domain should stop at four. The failed rule is to train the biggest model that converges on the available corpus. That lets the validation plateau choose . The plateau has no direct relationship to the approved compute budget.
Worked budget comparison
The corpus contains tokens. The budget is FLOPs. At FLOP/s and USD per accelerator-hour, that is accelerator-hours and about USD . A model converging after passes processes tokens.
The small scenario spends of the approved work budget and leaves unspent, approximately GPU-hours or at the proxy rate. Its first four of twenty passes account for of spent work, hence of the approved budget. Calling only those passes “productive” is a heuristic illustration: later passes need not have zero value. Cap repeats at four epochs. Then .
The larger allocation gets processed tokens per parameter and spends the full proxy budget. Its parameter count is times larger. Applying the parameter-only fit gives , or a predicted reduction in that asymptotic component. The two runs also differ in data exposure and convergence, so this is not a controlled prediction of their actual final loss. For a shape illustration, body estimates are approximately B for layers at width and B for layers at width ; these are close, not identical total models. Ordinary MHA cache payloads are and , or approximately and at tokens. With an independently rounded weight budget and no other overhead, cache-only ceilings are and . The gain is concurrency headroom, not demonstrated throughput: per-token work and scheduling still matter. For GPT-2 small, the body estimate is . Token embeddings are . Positional embeddings are . The sum is against a published . Agreement is .
Practical decision
Use parameter conventions appropriate to the question: body parameters can help compare encoder work or scaling fits, whereas all stored tensors matter for memory and output-vocabulary scoring adds compute. Select shape using measured cache, latency and quality constraints. Validate repetition policies on the corpus rather than treating four epochs as a universal ceiling. Size both model and token budget explicitly; convergence alone is not a compute-allocation objective.
6.4 Test-time compute versus pre-training compute
Lifetime breakeven
Pre-training is a fixed cost:
A RAG query costs:
Compare complete policies, not an added training bill with an unrelated added serving bill. Let be their training costs in the same units and their per-query work or cost. Then has a positive intersection only when the intercept and slope differences have compatible signs. If and , the crossover is:
The specialized expression applies only if one policy's query cost is and the more-pretrained policy's query cost is exactly . A larger model usually changes that baseline. Quality must also be matched before cost amortization decides the better policy.
Search needs a verifier
The proposer generates candidate answers. The verifier scores them and selects one. Sampling without a verifier has the same expected accuracy as drawing one answer and choosing at random. The cited reasoning experiments compare best-of-, beam search, lookahead and process/outcome reward models in particular budget and difficulty regimes. They are useful candidate policies, not a universal ordering for every RAG task. Selection quality depends on whether proposals contain correct answers and whether the verifier can identify them. The source boundary is conditional. Extra test-time compute is the better purchase for easy and moderate problems under modest inference load. Extra pre-training compute wins for genuinely hard problems under large inference load. Batch-one decode can be memory-bandwidth limited, while parallel proposals can reuse a prompt and batch their token steps. Sequential revisions depend on earlier outputs and cannot batch across those dependent steps. This can change utilization and latency at equal FLOPs, but does not guarantee that every sequential implementation costs more dollars without a serving benchmark. Shared-prefix KV storage, branch output caches and verifier memory also grow with sampling. A model run times uses FLOPs per output token. One pass uses . The smaller model uses times more compute. Its bf16 weights use instead of . That is times less weight memory.
Worked RAG query
The assistant serves queries per day. Each query retrieves chunks of tokens. Question and instructions add tokens. The answer adds . . . The total is tokens. For the -token prompt and assumed layers of width , causal forward attention is approximately , about of the parameter-prefill term. The following comparison deliberately uses parameter-only proxies. Attention does not generally cancel: proposal branches, reward models, prompt lengths and the B architecture can differ. An greedy pass costs:
FLOPs. That is seconds of accelerator time. It costs USD per thousand queries. Best-of- assumes one reusable -token proposer prefill costing , sixteen -token decode branches costing , and a separate B reward model scoring sixteen chains at an assumed processed tokens each, costing . Total parameter work is , or times the B baseline and approximately per thousand queries under the common-rate proxy. If the reward model also reads the full question/evidence for each chain, those tokens must be added; sharing the proposer prefill does not automatically share a different verifier's computation. A greedy pass costs FLOPs. That is times baseline and USD per thousand queries. Its of bf16 weights also forces a second card. Pre-training the at tokens per parameter costs FLOPs. The comparison costs . The difference is . A numerical added-work equivalence, not a complete-policy crossover, can still be calculated:
queries. This added-work equivalence is approximately years at queries per day or days at million per day. It is not the intersection of B-greedy and B-best-of- lifetime costs: the B policy has both more training work and more per-query work ( versus ). Under these proxies there is no positive cost crossover between those two policies. They may deliver different quality, which is the unresolved decision variable. One extra -token branch costs parameter FLOPs if it reuses the prompt. Three hundred additional input tokens have the same parameter term, but different attention/cache effects. Five extra -token chunks add parameter FLOPs, equivalent to such decode branches before verifier and serving overhead. These arithmetic ratios alone do not identify which purchase improves accuracy. A M cross-encoder over pairs of total tokens uses , or times the baseline query proxy. If is document length only, add the query tokens to every pair. Passage relevance scoring is not the same task as verifying the truth of a generated chain, so this is not proof that reranking is a substitute for every verifier. The deployment consumes inference tokens per year. The pre-training run uses . The ratio is . It lies two orders of magnitude below one.
Practical decision
Compare quality-matched complete lifetime policies and check whether a positive crossover actually exists. Try retrieval/reranking repairs for evidence failures and proposal/verifier changes for reasoning failures; neither an extra sample nor an extra chunk is always the better purchase. Benchmark search policies on the failing workload rather than importing a universal winner. Pass-at- measures proposal coverage, not the accuracy of the selected answer; a verifier cannot select an answer that the finite proposal set does not contain.
6.5 The small-model-plus-datastore argument and its limit
What retrieval can replace
Parameters perform two jobs. Competence supports syntax, instruction following, attending to context, and copying. Content supports closed-book recall. Retrieval can substitute for content. It cannot substitute for the competence required to read the retrieved passage. The cited controlled experiments estimate factual storage near two bits per parameter in their studied regime. Treat this as an empirical estimate, not a universal stable ceiling or a guarantee that arbitrary text is stored losslessly. Applying that coefficient to a B model gives:
bits. The arithmetic is bits, or of estimated factual information, not physical weights. A comparison with Wikipedia and textbooks requires a compatible compressed-information measure and a defined corpus; raw corpus bytes do not prove that all its useful facts fit and can be recovered. The following write-path comparison instead prices two explicit update scenarios. Embedding one -token chunk with a bi-encoder costs:
FLOPs. The vector payload is . Embedding work alone costs approximately under the proxy; index insertion, metadata, source retention, padding, batching and fixed service costs are excluded. Calling this the full price of a datastore write would understate its scope. Continued pre-training of a model on replay tokens costs:
FLOPs. The replay proxy is approximately GPU-hours or . Relative to one chunk's embedding arithmetic, the work ratio is . This compares a specified billion-token replay scenario with a single embedding pass; it is not a lower bound on every possible model edit or a measured end-to-end update speedup. A keyed datastore offers a local update operation whose scope is explicit. One fact may occupy multiple chunks or sources, and model-editing procedures need not always replay a billion tokens. The comparison shows why retained provenance and selectable rows are operationally useful, not a theorem that every factual change has exactly these two costs. Kandpal et al. report that factual question-answering accuracy is log-linear in relevant pre-training documents per question, then extrapolate scale-only long-tail coverage to about parameters. RETRO at matches GPT-3 at and Jurassic-1 at on the Pile with times fewer parameters and a -trillion-token database. Atlas at exceeds on Natural Questions from examples. It is three points above a model with times fewer parameters. A -nearest-neighbor language model trained on tokens with a datastore from beats the same architecture trained on all . The source also reports a roughly phrase-prediction system that uses retrieval to distinguish a poor-quality sense from an inexpensive sense. Local retrieval is personalization rather than federated learning because no gradient or model update crosses the device boundary.
The datastore growth limit
Define from mean gold rank:
For a particular query, let be the actual gold-chunk rank under a fixed scorer and tie policy. The number of chunks outranking gold is . Averaging over queries gives by definition. Mean rank does not guarantee that every query, or a specified recall fraction, survives a top- cutoff. The correct condition is:
Assuming stays constant as a datastore grows produces the scenario trend . Distribution shift, new distractors and retriever changes can alter . To meet a recall target, measure the rank distribution or its required quantile; rounding the mean up to an integer does not yield a guaranteed sufficient depth. With context tokens and reserved for question and answer, at most full -token chunks fit. If exactly one retrieved chunk is answer-bearing, its token share is for equal-size chunks. This fraction is a composition measure, not an accuracy law. Retrieve to a depth chosen from the observed recall curve, rerank the candidates, and pass a fixed small number of chunks to the generator. This can hold generator context constant while reranker work grows with candidate depth, but search, index memory and update costs also grow. Reranking cannot recover a gold passage absent from the candidate set.
Worked support assistant
The index holds chunks of tokens. That is corpus tokens. Queries add input tokens and emit output tokens. A closed-book query over tokens costs FLOPs. It costs USD per thousand queries. Its bf16 weights occupy and require two accelerators. Training that model over the corpus tokens costs FLOPs. That is accelerator-hours and USD per refresh. The corpus is of the model’s Chinchilla-optimal training tokens. An model with retrieved chunks processes tokens. It costs FLOPs and USD per thousand queries. That is times the closed-book query. Retrieval does not save per-query compute in this comparison. It saves weight memory and update cost. The weights occupy on one card. A daily refresh of changed chunks costs FLOPs. That is USD instead of USD . The full-precision index costs:
bytes. Fp32 vector payload is ; -byte PQ codes use before codebooks, identifiers, coarse centroids, lists and source text. Compression is needed only if the chosen machine or cost budget cannot accommodate the full representation; it is not intrinsically required by this corpus size. If the corpus grows to chunks, use the original mean rank of :
If the mean-rank trend transfers to chunks, the mean becomes . A depth is an illustrative choice at that mean, not an exact minimum or a guarantee of any target recall. Its retrieved content is tokens, exceeding the stated context budget. With exactly one answer-bearing equal-size chunk, its share is , compared with at five chunks. Stuffing those chunks, plus input and output tokens, totals processed tokens and parameter FLOPs. This is a hypothetical work comparison outside the stated -token context window; it is not an executable configuration on that window. Reranking query-document pairs of tokens with a M cross-encoder uses . Passing five chunks to the B generator gives total processed input/output tokens and parameter FLOPs. Combined work is , so the hypothetical stuffing ratio is approximately , not , once repeated query tokens are included in reranking. If a pair's total length were explicitly only tokens, the alternative ratio would be approximately . Neither ratio guarantees that the mean-depth candidate set contains gold or that the reranker puts it in the final five. The worked generator-size ratio is . The cited RETRO and Atlas comparisons use different tasks, data and evaluation setups; their reported roughly -fold and -fold parameter substitutions do not quantitatively validate this scenario's quality or make its assumptions provably conservative.
Practical decision
Choose the smallest generator that passes a representative gold-evidence reading evaluation, including difficult compositional cases. Keep changing factual sources addressable in the datastore. Measure retrieval rank distributions, recall targets, reranker success and serving costs before promising scale; mean rank alone is insufficient. Quantization and model size should be chosen against actual memory and quality budgets, not a universal ordering.
Diagrams
Figure 6.1
Panel a: allocation policies and observed models
| Policy or model | Parameters | Training tokens | Tokens per parameter | Figure marker or rule |
|---|---|---|---|---|
| Kaplan rule | grows with | grows with | falls with | |
| GPT-3 | open square | |||
| Gopher | open square | |||
| Chinchilla rule | grows with | grows with | at this scale | |
| Chinchilla | filled circle | |||
| Llama 1 | filled diamond | |||
| Llama 2 | filled diamond | |||
| Llama 3 | in the worked comparison | filled diamond |
Panel b: lifetime compute under the same training budget
| Configuration | Training compute | Serving compute for tokens | Lifetime total |
|---|---|---|---|
| Training-ratio reference, approximately B on T | Approximately | Approximately | |
| Over-trained, on | FLOPs | FLOPs | FLOPs |
Figure : The table contrasts reported model/token allocations, not every post-Chinchilla release. The equal-training-budget scenario gives approximately times as much lifetime parameter work for the B allocation at processed inference tokens. Equal training work does not establish equal task quality or complete ownership cost.
Figure 6.2
Panel a: fixed memory steps
| Operation | Arithmetic | Memory |
|---|---|---|
| Serve at bf16 | ||
| Serve at bf16 | ||
| Serve at fp32 | ||
| Fine-tune with Adam | ||
| Fine-tune with Adam | ||
| One-card boundary |
Panel b: variable KV-cache slopes
| Context | Cache per request | Requests at free |
|---|---|---|
| about | ||
Figure : The weight and stated optimizer layouts establish tensor-payload budgets. Cache-only ceilings of at tokens use the nominal after weights, with no workspaces or output-growth reserve. These are not measured concurrency, throughput or complete training-fit guarantees.
Figure 6.3
Panel a: loss sensitivity
| Change | Loss reduction |
|---|---|
| Shape at fixed | a few percent |
| Double | |
| Increase ten times |
Panel b: lookup-table share
| Model | Lookup-table share |
|---|---|
| XLM-R base, vocabulary | |
| GPT-2 small | |
| BERT-base, vocabulary | |
| Llama 3 8B | |
| Llama 3 70B |
Panel c: allocation of the FLOP budget
| Configuration | Productive four-epoch share | Other outcome |
|---|---|---|
| to convergence over epochs | spent in the first four passes | Later-pass value is study-dependent; of the approved budget remains unspent. |
| at four epochs | allocated to four passes | A budgeted scenario, not a universal fresh-data-equivalent guarantee. |
Figure : The parameter-only fit predicts approximately and reductions for doubling and tenfold scaling within its regime. Vocabulary shares use model-specific counting conventions; input lookup differs from full output scoring. The four-epoch budget comparison is a repetition-policy illustration, not a proof that all later epochs are unproductive. Cache-only concurrency gains do not automatically equal throughput gains.
Figure 6.4
Panel a: proposer and verifier in a RAG stack
Diagram description and source
flowchart TD
A["query"] --> B["retrieve chunks"]
B --> C["cross-encoder rerank"]
C --> D["sample drafts"]
D --> E["process reward model"]
E --> F["selected answer"]
E -.-> G["sequential revision"]
G -.-> D
B -.-> H["extra context cost"]
C -.-> I["passage verifier cost"]
D -.-> J["extra draft cost"]
E -.-> K["chain verifier cost"]
| Diagram label | Value or notation |
|---|---|
| Query | |
| Retrieve chunks | chunks |
| Sample drafts | drafts |
| Extra context cost | per chunks |
| Passage verifier cost | at candidates |
| Extra draft cost | per draft |
| Chain verifier cost | at |
Panel b: cost against one generation pass
| Knob | Relative per-query FLOPs |
|---|---|
| One extra sample | |
| Rerank candidates with | |
| Five extra chunks | |
| Baseline , , one sample | |
| Process reward model over chains | |
| Best-of- plus process reward model | |
| , one sample |
Figure : The work ratios use one shared proposer prefill and the stated reward-input budget. Additional prompt tokens for the reward model, attention, branching caches and hardware efficiency are excluded. Reranking relevance and checking a chain's truth are different jobs. The actual B-greedy and B-best-of- policies have no positive FLOP-cost crossover under the stated training and serving costs; quality remains to be compared.
Figure 6.5
Panel a: two write paths for one fact
Diagram description and source
flowchart TD
A["one new fact"]
A -->|"into model parameters"| B["continued pre-training"]
A -->|"into datastore"| C["embed once plus index insert"]
B --> D["training compute and cost"]
C --> E["embedding compute and cost"]
D -.-> F["write-path cost ratio"]
F -.-> E
| Diagram label | Compute, cost, or size |
|---|---|
| One new fact | A -token chunk |
| Continued pre-training | replay tokens, model |
| Embed once plus index insert | encoder plus index insert |
| Training compute and cost | FLOPs and USD |
| Embedding compute and cost | FLOPs and USD |
| Write-path cost ratio | times |
Panel b: retrieval depth against datastore size
| Datastore chunks | at | Rounded mean-rank illustration, not a recall guarantee | Generator chunks after reranking |
|---|---|---|---|
| , illustrative | if enough candidates exist and reranking succeeds | ||
| , illustrative | if enough candidates exist and reranking succeeds | ||
| , illustrative | if enough candidates exist and reranking succeeds | ||
| , illustrative | if enough candidates exist and reranking succeeds | ||
| , illustrative | if enough candidates exist and reranking succeeds |
Under this assumed mean-rank trend, at chunks. That is a mean crossing, not the corpus size at which a specified recall target becomes impossible. The -chunk context bound is separate from the measured rank quantile needed for recall. Figure : The two update scenarios compare a billion-token replay with one chunk's embedding arithmetic, a ratio approximately before index and serving overhead. The growth table shows an assumed mean-rank trend, not an exact sufficient retrieval depth. Reranking can hold presentation depth at five only when candidate recall and reranker quality support it; retrieval and index costs do not disappear. There are no source tables in this chapter.
Whiteboard pack
Numbered drawing order
- Write training compute as .
- Add generation cost as per token.
- Draw the lifetime bill with training and serving terms.
- Mark as the crossover.
- Split memory into weights, Adam state, and KV cache.
- Draw the proposer and verifier path for test-time search.
- Split model parameters into competence and factual content.
- Draw datastore growth, deep retrieval, reranking, and a fixed five-chunk generator input.
90-100 word script
Start with the lifetime bill: training costs , and generation costs per token. Ask for expected query volume before choosing model size. Chinchilla fixes the training-only ratio near tokens per parameter, but a shipped system often favors a smaller model trained longer because serving scales with . Next price weights, Adam state, and the KV cache separately. For retrieval, test whether the small model can answer when given the gold chunk. If it can, keep facts in the datastore. As the corpus grows, retrieve deeply, rerank cheaply, and keep the generator context flat.
Interview traps
1. Is tokens per parameter the final scaling rule?
No, it is the Chinchilla level for a training-compute objective at that scale. Serving crosses training at , so a heavily served system can justify a smaller model trained on far more tokens. The trade is a small loss penalty against lower memory and lower cost for every generated token.
2. Does a model fit on one card?
Precision and workload decide. Weights use at fp32 or at bf16, while full Adam state uses before activations. The KV cache then scales with context and concurrency, so the trade is quality against card count, interconnect traffic, and request capacity.
3. Should multi-step failures trigger an to upgrade?
First measure proposal coverage, verifier selection accuracy and complete serving costs. Under the chapter's scoped parameter proxies, best-of- plus the assumed reward input uses times an B greedy pass, while B greedy uses times. The training and serving totals do not produce a positive cost crossover between those actual alternatives; the task-quality comparison cannot be assumed.
4. Does RAG always reduce per-query compute?
No. The worked with chunks costs times the closed-book query, so its wins are rather than of weights and a USD rather than USD refresh bill. Use the smallest model that answers with the gold chunk, then retrieve deeply and rerank as the corpus grows because stuffing candidates costs FLOPs while rerank-then-read costs .
5. Should a fixed training budget fund a shape sweep or a small model trained to convergence?
Choose the experiment from the quality, token and hardware constraints rather than a universal preference for a shape sweep or convergence. The M scenario leaves of its approved work budget unspent; four-pass B uses it fully. The parameter-only fit's approximately component reduction does not predict the full final-loss difference because data exposure also changes. Four epochs is a study-informed starting point to validate, not a universal optimum.
Key numbers
Allocation and lifetime
| Scope | Values and committed relationship |
|---|---|
| Kaplan allocation | Kaplan uses , , , batch proportional to , steps proportional to , , and . GPT-3 is on at . Gopher is on at . |
| Chinchilla allocation | Approximately half/half fitted exponents give a scale-specific ratio near . Gopher and Chinchilla proxy work is versus , a increase over Gopher. Reported MMLU scores differ by percentage points. |
| Cost and crossover | At assumed and per GPU-hour, the Gopher work proxy is approximately GPU-hours and million. Training and inference parameter work cross at only under the same token/rate conventions; inference includes input and output tokens. |
| Post-Chinchilla comparison | At , ratio gives approximately B on T with bf16 payload; ratio gives B on T with . Serving parameter-work ratio is approximately ; lifetime work at inference tokens differs by approximately . Quality and complete ownership costs are separate. The B check gives , approximately below the rounded reported work. |
Compute and memory
| Scope | Values and committed relationship |
|---|---|
| Compute relation | Parameter proxies are forward and training FLOPs per processed token. Causal forward-prefill attention averages approximately per token. Relative to the body estimate the ratio is ; a ratio below one need not be negligible. Training backward and per-step decode attention require their own counts. |
| Precision and training state | Storage is bytes for fp32, for bf16, for int8, and for int4. Quantization is the cheapest stated route to a reduction. A uses , , and at the first three precisions. Adam uses bytes per parameter, or for and for . Moving to bf16 cuts free memory from to , a loss. |
| Cache and mixture of experts | Llama 8B uses layers, key-value heads, and head dimension . Its cache is bytes or per token. With free, concurrency is at , at , and at . Mixtral stores but activates . |
| LoRA and long context | Rank- factors on two square projections in layers store values versus , exactly . A specified -byte trainable-state layout adds before activations. At tokens the forward proxy is approximately and ; at , approximately and . The time ratio is approximately . One full recomputed forward raises to , or ; actual checkpoint policies differ. |
Shape, embeddings, and convergence
| Scope | Values and committed relationship |
|---|---|
| Shape sensitivity | Shape changes loss a few percent. Doubling gives or lower loss. Ten times gives or lower loss. Figure lookup shares are , , , , and . |
| Embedding shares | GPT-2's modeled body is parameters and token-plus-position tables total : approximately of total or added over body. Llama's untied input-plus-output count is , approximately of the stated B total and added over the remainder. Differential log inflation is approximately decades. |
| Encoder vocabularies | At width , vocabulary difference rows gives additional input-table parameters, approximately at bf16. Input lookup does not multiply by all rows; a full output-vocabulary head does add work. |
| Repeat and shape budget | The B-token, -FLOP scenario permits B at four passes; four passes are a study-informed heuristic, not a hard productive boundary. The parameter-only loss factor does not control all data-exposure differences. Shape examples give cache-only concurrency ceilings versus , a increase in headroom, not a measured throughput gain. |
Test-time compute
| Scope | Values and committed relationship |
|---|---|
| Small repeated model | A run times uses FLOPs per output token, one pass at . Weight memory is versus , or less. |
| Baseline query | At daily queries, input plus output tokens gives parameter FLOPs, approximately per thousand at the proxy rate. Prompt attention adds approximately to parameter prefill in the specified B shape; it does not generally cancel between alternatives. |
| Best-of- and | Shared proposer prefill plus branches plus assumed reward input totals , or times baseline. The B greedy proxy is , or times. Full reward context, memory and hardware effects require separate costing. |
| Breakeven and marginal FLOPs | Training intercept difference is . Dividing it by added B search work gives an added-work equivalence , not the intersection of the actual B and best-of- lifetime costs. The former has both higher training and higher query work. One cached-prefix -token branch is FLOPs; five -token chunks add parameter FLOPs. Reranking pairs of total tokens is times baseline, but relevance scoring is not complete answer verification. |
Retrieval versus parameters
| Scope | Values and committed relationship |
|---|---|
| Capacity and write paths | The two-bit coefficient is a controlled empirical estimate, not a universal capacity guarantee; B gives bits or estimated factual information. One chunk's embedding arithmetic costs approximately versus for the specified billion-token replay. The approximately ratio excludes local-index and serving costs and is not a lower bound on every possible model edit. |
| Published substitutions | Scale-only long-tail recall extrapolates to about parameters. RETRO at uses a -token database and matches and models with fewer parameters. Atlas at exceeds from examples, beats by points, and uses fewer parameters. The nearest-neighbor result compares training tokens with a -token datastore. The phrase system is roughly . |
| Context limit and large-model refresh | A -token window with reserved fits at most full chunks of tokens. One gold chunk's token share is , not an accuracy law. A B query over tokens uses parameter FLOPs; its bf16 payload is . A B-token refresh uses FLOPs, approximately at the common proxy rate, not a guaranteed successful update. |
| Retrieved small model and corpus growth | The B ten-chunk query uses parameter FLOPs, times the B closed-book example. Fifty million raw vectors use ; PQ codes alone use . Fixed implies mean rank at five billion chunks, not a sufficient minimum depth. The illustrative -candidate reranker includes repeated query tokens and uses FLOPs; five-chunk generation uses , totaling . The out-of-window stuffing proxy is approximately times larger, conditional on candidate/reranker success. |
00-START-HERE · 01-READING-ROUTES · 05_data_privacy_and_the_legal_surface · 07_in_context_learning_the_mechanism_rag_rides_on