FDE Academy

Module 3 · Inference engineering · Chapter 23 · Free

How an LLM generates text: prefill, decode and the KV cache

17 min1 pipeline diagram1 generation animation3 checks
The problem A customer's compliance team will not let documents leave their network, so they want to run a model on their own GPUs. Their pilot users report two odd things: pasting a 30-page contract makes the first word take ages to appear, and asking for a long summary then trickles out slowly. Their infrastructure lead asks why "the same model" is fast at one thing and slow at another, and why memory keeps running out when more people connect. To answer you need a clear mental model of what the GPU actually does for each word.

One token at a time

A language model does not write a reply in one go. It works on tokens, which are chunks of text a little shorter than a word (Chapter 7). Given all the tokens so far, it produces a score for every possible next token, one token is picked from those scores, and that token is added to the end. Then the whole thing repeats with the longer sequence. A 300-token answer means 300 trips through the model.

This loop is called autoregressive generation: each output depends on everything before it, including the model's own earlier output. That one fact explains most of the performance behaviour in this module.

One step of text generation Tokens go through an embedding step and the transformer layers. The layers read and write a KV cache. A sampling step picks the next token, which is appended and fed back as input for the next step. Tokens inprompt + so far Embedids to vectors Transformer layersattention + feed-forward Pick tokenscores, sample New tokenstreamed out KV cachekept in GPU memory
  1. Text is split into token ids. On the first pass these are all the prompt tokens. On later passes the newest token is added.
  2. Each id is looked up in a table and becomes a list of numbers (a vector) that the layers can compute with.
  3. Dozens of identical-shaped layers run in sequence. Each has an attention step, where a token looks at earlier tokens, and a feed-forward step that transforms each token on its own.
  4. To look back at earlier tokens, a layer needs two saved summaries of each one, called its key and value. Instead of recomputing them every step, they are stored in the KV cache and only the new token's pair is added.
  5. The last layer gives a score for every token in the vocabulary. A sampling rule (greedy, or random with a temperature) picks one.
  6. The new token is sent to the user and also appended to the input. The loop runs again until a stop token or a length limit.
TokensEmbeddingModel computeSampling

Why a cache exists

In attention, every token compares itself with all earlier tokens to decide what to pay attention to. For that comparison each earlier token provides a key (used to decide how relevant it is) and a value (the content it contributes). These depend only on the tokens before them, and earlier tokens never change. So there is no reason to recompute them for every new token.

The KV cache is simply that saved set of keys and values, for every layer and every token seen so far. Each decode step computes a new key and value for one token, appends them, and reuses everything else. Without the cache, a 2,000-token reply would redo the work for the entire history 2,000 times. With it, each step does a small amount of new work, but must read the whole cache. Remember that last part. It matters in Chapter 24.

Prefill and decode

Generation has two distinct phases with very different behaviour.

Try it below. Step through a short example, then drag the slider to pretend the prompt is much longer and see which times change.

Generation animation (all times illustrative)

The eight boxes below stand in for the prompt. The slider changes only the timing model, not the boxes.

Ready

Prompt tokens, then generated tokens

KV cache (one block per token held)

Time per step (illustrative milliseconds)

What to notice The prompt is taken in with one big step: all eight cache blocks fill together. After that, exactly one block is added per step, and the bars for decode steps are all about the same size. Slide the prompt length up: the prefill bar grows a lot (that is time to first token), while each decode step grows only a little (it reads a bigger cache). The model used for the timing is a simplified shape, chosen to show the trend, not to predict a real GPU.

Why long prompts delay the first word, and long answers take long

Time to first token (TTFT) is roughly the queue wait plus the prefill. A long prompt means more tokens to process in the prefill pass, so the user stares at a blank screen for longer. Parallelism helps the GPU, but it does not make the work free: ten times the prompt is still about ten times the computation.

After that, total time is roughly the number of output tokens times the time for one decode step. Each step is bounded by how fast the GPU can read its memory, and steps cannot overlap within one request. A 1,000-token answer needs 1,000 sequential steps. This is why streaming helps perceived speed (Chapter 17) but does not shorten the total, and why asking for "a brief answer" is a real performance lever.

The cache grows, and it eats memory

Each token adds a fixed amount of cache for every layer. For a decoder with grouped-query attention (a design where several attention heads share one set of keys and values), the size per token is:

2 (keys and values) x layers x KV heads x head dimension x bytes per number

With an illustrative model of 32 layers, 8 KV heads, a head dimension of 128 and 2-byte numbers, that is 2 x 32 x 8 x 128 x 2 = 131,072 bytes, or 128 KiB per token. An 8,000-token conversation then holds about 1 GiB of cache. Serve 32 such conversations at once and the cache alone is about 32 GiB, on top of the model weights. The cache grows with sequence length and with the number of simultaneous requests (batch size). That is usually what runs a server out of memory before it runs out of compute. Chapter 25 turns this into a calculator.

Mixture of experts, briefly

Some models replace each feed-forward block with many smaller ones called experts, plus a small router that picks a few experts for each token. Only the chosen experts do work for that token, so the compute per token can be much lower than the total parameter count suggests. The catch, which people often miss, is that different tokens pick different experts, so in general all the experts' weights must still be available in memory. The model is cheaper to compute but not proportionally smaller to hold. Attention and the KV cache work the same way as in a dense model.

Check your understanding

Recap

In the field A composite example: a team sizes a self-hosted model by checking that the weights fit on one GPU, then launches. It works in testing with a few users. In the first week of real use, requests start failing under load, and nobody changed the model. The weights fit fine. The cache for many long conversations did not. The fix started with a conversation that sounds obvious in hindsight: how long are real prompts, how long are real answers, and how many requests are active at once? Ask for those three numbers before you quote any hardware.
Go deeper This chapter follows the topic order of the book Inference Engineering by Philip Kiely (Baseten Books): sections 2.1 Neural Networks and 2.2 LLM Inference Mechanics (2.2.1 to 2.2.4). The book is at baseten.co/inference-engineering. This course is independent material, not endorsed by the author or Baseten, and all explanations and numbers here are our own. For the engine view, see the vLLM documentation and its design notes on paged attention.

Chapter quiz

Four questions. Score 70% or more to mark this chapter complete.

Review