Highlights

Contents

Part I
01

Prefill and Decode

A prompt is known before generation begins. Its continuation is chosen sequentially. Separate prefill from decode to understand why they reuse data differently and respond to different optimizations.

YOU ARE HEREmessageschat templatetokenizertoken IDsconfig.jsonmodel.safetensorsint8 / int4 weightsOUR DECODER, REBUILT FROM THE CONFIGprefilldecodeattention kernelKV cacheparity checkvs referenceLM head → logitssamplingdetokenizereply textnext token

#Section 1Training vs Inference

In training, the model never waits for itself. A 2,048-token sequence arrives complete, the targets are the same tokens shifted by one, and the causal mask lets every position predict its next token in one forward pass. Chapter 1 called this “one pass, seven lessons” (Section 44): TT predictions for the price of one pass.

At inference the next input is the model's own previous output, which does not exist until the previous step finishes. This is autoregressive generation: predict a token, append it, predict again (Section 1). Each step is the same forward pass as in training, but the steps form a chain: the 200th token cannot be computed before the 199th is chosen.

SAME FORWARD PASS, TWO SCHEDULEStraining: one pass, every positionThecatsatonthematdecoder (causal mask)catsatonthemat.all 6 targets known, 6 predictions at onceinference: one token per stepThecatsat1Thecatsaton2Thecatsatonthe3each step waits for the last
Figure 4.1Training sees the whole sequence at once and predicts every position in one pass. Inference generates left to right, each new token waiting for the one before it.

Why inference does less work per token

Inference needs no backward pass or saved gradient graph. A cache also avoids recomputing earlier positions. Weights, cached history, and temporary buffers still occupy memory.

Two jobs: reading the prompt and writing the reply

A chat request is two jobs. Prompt processing reads the input: every prompt token is known, so all go through the model in one parallel pass, as in training. Token generation writes the reply, one token per step, each step a full trip through every layer for one position. The industry names are prefill and decode.

Latency versus throughput

Two kinds of speed pull against each other. Latency is how long one user waits, split into time to first token (TTFT), mostly prefill, and inter-token latency (ITL), the time per decode step. With TTFT 40 ms and ITL 5 ms, a 200-token reply takes 40+199×5=1,03540 + 199 \times 5 = 1{,}035 ms. Throughput is tokens per second across all users.

Batching reuses weight reads across users, raising total throughput while potentially slowing each stream. Measure both views of performance.

ONE REQUEST ON A TIMELINE (ILLUSTRATIVE: TTFT 40 MS, ITL 5 MS)timequeue +tokenizeprefill the promptt1t2t3t4t5t6t7t8t9t10t11t12t13t14…requesttime to first token (TTFT)ITLdecode: one token per step, streamed to the user200 tokens: 40 + 199 × 5 = 1,035 ms
Figure 4.2One request on a timeline. Prefill ends at the first token; each decode step then adds one. TTFT is the wait before anything appears, ITL the streaming speed.
PICTURE THIS: READ THE BRIEF, THEN ANSWER WORD BY WORDprefill: the whole stack at once40 pages, skimmed in paralleldecode: one word, then the nextThecapitalis…each word chosen, said, heard, then the nextfaster reader: shorter silence. faster speaker: faster stream.
Figure 4.3The stenographer of the analogy. Reading the brief is one parallel pass over many pages; answering is a chain of single words, each waiting for the last.

#Section 2Prefill

A user pastes a 2,048-token document and asks about it. Before the first word of the answer, the model must run all 2,048 tokens through all 32 layers of Llama 3 8B.

Prefill does that in one forward pass over input of shape (B,T,d)(B, T, d), every position in parallel under the causal mask, as in training. Two things are special. Each layer writes its prompt keys and values into the KV cache, so prefill builds the initial cache: one key and value row per position, layer, and KV head. And only the last position's output is needed, because only it predicts the next token.

PREFILL: THE WHOLE PROMPT GOES UP TOGETHER, THE CACHE FILLS ON THE WAYYouareahelpful?layer 1K, Vlayer 2K, Vlayer 28K, V⋮⋮outputs not neededLM head, last rowKV cache, one row per prompt tokenbuilt once, reused forever
Figure 4.4Prefill: all prompt positions pass through every layer together. Each layer leaves its keys and values in the cache; only the final position goes on to the LM head.

For generation, only the last prompt position needs vocabulary logits. Slice before the head, for example with h[:, -1:, :], to avoid projecting unused positions.

Why prefill is parallel, and fast per token

Prefill reuses each weight across many known positions through matrix multiplication. This often makes it compute-bound, unlike small-batch decode.

Time to first token

Time to first token covers tokenization and template (microseconds to a millisecond), queueing, prefill, and the LM head and sampling for the last position. On an idle server with a long prompt, prefill dominates, so TTFT tracks prompt length.

Prefill cost for long prompts

Projections and MLP cost 2N2N operations per token and grow linearly with prompt length; attention scores grow with T2T^2. The linear part dominates short prompts, and the quadratic part catches up on long ones.

Popular identical prefixes can reuse their computed KV states, reducing repeated prefill work. Hardware-peak calculations alone do not establish actual latency.

LLAMA 3 8B PREFILL, H100 PEAK, LOWER BOUND (LOG TIME SCALE)1 ms10 ms100 ms1000 msattention share128 tok1.9 ms0.2%2,048 tok32.2 ms3.5%8,192 tok142.1 ms12.5%32,768 tok781.6 ms36.4%linear work (projections, MLP) grows with T; attention grows with T², so its share climbs
Figure 4.5Prefill lower bound for Llama 3 8B on an H100 by prompt length, attention share in orange. Four times the tokens costs a little over four times the time at short lengths and more at long ones.

#Section 3Decode

After prefill the model has logits for the first new token. Sampling picks one (greedy, temperature, top-k and top-p are covered in Unit III), and the second phase begins.

Decode generates one token per step from input of shape (B,1,d)(B, 1, d). In every layer the new token computes its query, key, and value, appends the key and value to the cache, attends over the whole cache, and passes one row through the MLP. The LM head yields one row of logits, sampling picks the next token, and the step repeats, reusing everything about earlier tokens.

ONE DECODE STEP: ONE ROW UP, EVERYTHING READ ONCEParislayer 1layer 2layer 28⋮LM headnext tokenweights(read every one)15.0 GB forLlama 3 8BKV cache(read every row)+ append onenew K, V rowlots of reading, little math
Figure 4.6One decode step: one new row goes up through the layers, reading every weight once and the whole cache once, and comes out as one token.

Decode latency and tokens per second

Inter-token latency is time between emitted tokens; tokens per second describes stream speed. Reading weights and cached history limits small-batch decode.

Why decode is memory-bandwidth heavy

Arithmetic intensity is work per byte moved. Small-batch decode reuses each weight little, so it can be memory-bandwidth bound even when the GPU has spare arithmetic capacity.

Smaller caches and quantized weights target memory traffic. Batching increases weight reuse. Each helps only to the extent that the workload is limited by the resource it changes.

H100 ROOFLINE: 3.35 TB/S, 989.4 TFLOPS BF16 (LOG SCALE, BOTH AXES)operations per byteTFLOPS attainableridge ≈ 2950.11101001000100001101001000decode, batch 1decode, batch 64prefill, 2,048 tokensmemory-boundcompute-boundbatching slides decode up the slope
Figure 4.7A roofline for the H100. Below 295 operations per byte, speed is capped by bandwidth; above it, by arithmetic. Batch-1 decode sits far down the slope; long-prompt prefill sits on the flat roof.

#Section 4Why Naive Autoregressive Inference Is Wasteful

Chapter 1's cache-free generation (Section 58) reruns the whole sequence to produce each token and keeps only the last row of logits. It works and repeats almost all its work.

Reprocessing the entire context. With a 1,000-token prompt and a 500-token reply, the naive loop processes 1,000, then 1,001, up to 1,499 tokens: 500×1,000+(0+1+⋯+499)=624,750500 \times 1{,}000 + (0 + 1 + \dots + 499) = 624{,}750 positions. A cached loop processes the prompt once and then one token per step, 1,499 positions. The naive loop does about 417 times the work, all of it reproducing existing numbers.

Recomputing old K and V. A past position depends only on its causal prefix. Repeating that computation after every appended token wastes work without adding information.

Growing context length and increasing attention cost. At length tt the naive step also redoes all t(t+1)/2t(t+1)/2 attention scores when only the newest row of tt is new, so per-step cost grows quadratically and generation keeps slowing down.

PROMPT OF 4, THEN 5 NEW TOKENS: CELLS = TOKEN POSITIONS PUSHED THROUGH THE MODELwithout a cacheprefillstep 1step 2step 3step 4step 539 cellswith a cacheprefillstep 1step 2step 3step 4step 59 cells1,000-token prompt, 500 new: 624,750 vs 1,499
Figure 4.8The work of the naive loop. Each step reprocesses the whole prefix (grey); only the newest row (orange) is new. The cached loop computes only the orange cells.

Motivation for caching. The repeated numbers are keys and values of old positions, which never change. Store them once and each step needs only the new row. Part II puts that into practice.