Inference & Deployment
How LLMs Generate Text: Decoding, Temperature, KV Cache and Quantisation
Intermediate 20 min For: Beginners / Developers / Researchers
Key takeaways
- ▸Inference has two phases: prefill (process the whole prompt in parallel) and decode (generate one token at a time).
- ▸Temperature and top-p control how the next token is sampled from the model's probabilities — creativity versus consistency.
- ▸The KV cache stores past keys and values so each new token does not recompute the whole prompt; it is also what eats memory on long contexts.
- ▸Token generation is usually limited by memory bandwidth, so smaller weights (quantisation) and batching are the main levers for speed and cost.
Two phases: prefill and decode
When you send a prompt, the inference engine does two different kinds of work:
- Prefill – the whole prompt goes through the model in one parallel pass. This is compute-heavy but fast per token, and determines the time to first token.
- Decode – the model produces the answer one token at a time: run the network, get probabilities for the next token, choose one, append it, repeat (see What Is an LLM?). This determines tokens per second.
sequenceDiagram
participant U as User
participant E as Inference engine
participant M as Model weights
U->>E: prompt (1,000 tokens)
E->>M: Prefill: all prompt tokens in parallel
M-->>E: keys/values for every layer → KV cache
loop each new token
E->>M: Decode: 1 new token + KV cache
M-->>E: probabilities for next token
E->>E: sample token, append K/V to cache
end
E-->>U: streamed answerChoosing the next token: sampling
The model outputs a probability for every token in its vocabulary. How you pick from it matters:
- Greedy – always take the most likely token. Deterministic, but prone to repetition.
- Temperature – divide the scores (logits) by a temperature T before softmax. T < 1 sharpens the distribution (safer), *T* > 1 flattens it (more diverse).
- Top-k / top-p – sample only from the k most likely tokens, or from the smallest set whose probabilities add up to p (nucleus sampling, Holtzman et al., 2019). This cuts off the long tail of nonsense tokens.
For code, extraction and agents, low temperature is usual; for brainstorming and fiction, higher. Even at temperature 0, outputs from hosted APIs are not always bit-for-bit identical, because batching and floating-point ordering vary.
The KV cache
In attention, each new token needs the keys and values of all previous tokens (Transformers and Attention). Recomputing them every step would make generation quadratically slow, so engines keep them in a KV cache and only compute K and V for the new token.
The cache costs memory: 2 × layers × KV-heads × head-size × bytes × tokens. For Llama 3 8B (32 layers, 8 KV heads of size 128, 16-bit) that is about 128 KB per token — roughly 1 GB for an 8,000-token context, per conversation. Techniques such as grouped-query attention (Ainslie et al., 2023), which shares K/V across heads, exist largely to shrink this cache.
Why generation is memory-bound
To produce one token, the hardware must read all the weights from memory. An 8B model at 16-bit is 16 GB; at, say, 400 GB/s of memory bandwidth, that caps a single stream at around 25 tokens per second regardless of how many FLOPs the chip has. Hence the main speed levers:
| Lever | What it does |
|---|---|
| Quantisation | Store weights in 8, 4 or fewer bits → fewer bytes to read per token |
| Batching | Serve many users per weight read; continuous batching adds/removes requests every step (Orca) |
| PagedAttention | Manage the KV cache in pages like virtual memory, so more requests fit (vLLM) |
| Speculative decoding | A small draft model proposes several tokens; the big model verifies them in one pass (Leviathan et al., 2022) |
Quantisation: big models, small machines
Training usually uses 16- or 32-bit numbers. Quantisation stores weights with fewer bits after training — e.g. LLM.int8() (Dettmers et al., 2022) and GPTQ (Frantar et al., 2022). The llama.cpp project popularised the GGUF file format with many quantisation types (names like Q4_K_M, Q8_0).
Rule-of-thumb weight sizes (excluding KV cache and runtime overhead):
| Model size | 16-bit | 8-bit | ~4-bit |
|---|---|---|---|
| 8B | ~16 GB | ~8 GB | ~4.5–5 GB |
| 32B | ~64 GB | ~32 GB | ~18–20 GB |
| 70B | ~140 GB | ~70 GB | ~40 GB |
Quality loss at 8-bit is usually negligible; good 4-bit quantisation is the common sweet spot for local use; below that, quality degrades faster.
Run it yourself
- Ollama and LM Studio download quantised models and show tokens per second.
- llama.cpp exposes every knob: quantisation type, context size, KV-cache type, batch size and speculative decoding.
- On Apple silicon, MLX LM runs and quantises models using unified memory.
Next steps: Inference Engines and Running LLMs on Your Own Computer (in progress), and GPUs, Memory and FLOPs for the hardware side.
Algorithm cards
| Algorithm | In one line | Original paper |
|---|---|---|
| Temperature & nucleus (top-p) sampling | Controls randomness by sampling only from the top-p probability mass | Holtzman et al., 2019 |
| KV cache | Stores past keys and values so each step doesn't recompute them | No single origin paper; see the Transformers docs |
| Attention sinks (StreamingLLM) | Keeping a few initial sink tokens enables endless streaming generation | Xiao et al., 2023 |
| Grouped-query attention (GQA) | Heads in a group share one K/V, shrinking the KV cache | Ainslie et al., 2023 |
Must-read papers
- The Curious Case of Neural Text Degeneration (2019) — why greedy decoding repeats itself, and the proposal of top-p (nucleus) sampling. arXiv:1904.09751
- Efficient Streaming Language Models with Attention Sinks (2023) — when the KV cache cannot grow forever, keeping "sink" tokens keeps streaming generation stable. arXiv:2309.17453
Hands-on project (about 6 hours)
Add a KV cache to a small GPT you trained (e.g. nanoGPT from the previous lesson), time 1,000 generated tokens with and without it, and compute the speed-up; then use the formula in self-check question 1 to estimate the KV cache of a 7B model at 32K context. Pair it with Lilian Weng's Large Transformer Model Inference Optimization; for sampling parameters see the Hugging Face generation strategies guide, and for how a production engine manages the KV cache read the vLLM docs.
Self-check
1. What is the KV cache size proportional to?
Layers × KV heads × head dimension × sequence length × batch size × 2 (one for K, one for V), times bytes per number.
2. What does top-p = 0.9 mean?
Sort candidate tokens by probability and sample only from the smallest set whose cumulative probability reaches 90%.
3. Why is GPU compute under-used during decoding?
Each step computes a single new token, so most time goes into reading weights and the KV cache from memory — it is bandwidth-bound, not compute-bound; batching spreads each weight read across many requests.
FAQ
What does temperature do in an LLM?
It rescales the model's probabilities before sampling. Low temperature (e.g. 0–0.3) makes the most likely tokens dominate, giving focused, repeatable output; higher values (0.8–1.2) flatten the distribution and give more varied output — and more mistakes.
How much memory do I need to run a 7B or 8B model?
The weights take about parameters × bytes per parameter: an 8B model needs roughly 16 GB at 16-bit and about 4–5 GB at 4-bit quantisation, plus extra for the KV cache and runtime. On a Mac the memory is shared with the system.
Does quantisation make a model worse?
Somewhat, depending on the method and bit width. 8-bit is usually close to lossless; good 4-bit methods keep most quality for chat use; below 4 bits quality drops faster, especially for small models.