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.
#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): 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.
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 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.
#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 , 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.
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 operations per token and grow linearly with prompt length; attention scores grow with . 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.
#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 . 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.
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.
#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: 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 the naive step also redoes all attention scores when only the newest row of is new, so per-step cost grows quadratically and generation keeps slowing down.
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.