You will probably never write a GPU kernel, and this chapter does not ask you to. What it asks is that you can reason about the machine a model runs on, the way a backend engineer reasons about a database server without having written one. Why is the first token slow and the rest fast? Why does a long conversation get more expensive with every turn? Why will a model fit on one GPU and not on another? These questions decide the cost, speed and scale of every AI feature you ship, and they all have arithmetic answers.
A model is a very large pile of numbers
A model with seven billion parameters is seven billion numbers, and to run it they all have to sit in fast memory. How much memory depends on how many bytes each number takes:
| Precision | Bytes per parameter | A 7B model needs about |
|---|---|---|
| 32-bit float (fp32) | 4 | 28 GB |
| 16-bit float (fp16, bf16) | 2 | 14 GB |
| 8-bit integer | 1 | 7 GB |
| 4-bit | 0.5 | 3.5 GB |
That is the weights alone. Running the model needs more on top: working memory for each request, and the KV cache described below, which grows with every token of context. A model that "fits" with nothing to spare will fall over the moment a long prompt arrives.
CPU, GPU and TPU
Running a transformer is mostly matrix multiplication: millions of independent multiply-and-add operations that can all happen at the same time. The hardware choices are about how well they do that.
- A CPU has a few powerful cores built for complicated, branching work. It can run small models, slowly.
- A GPU has thousands of simple cores built for exactly this kind of parallel arithmetic, plus tensor cores specialised for matrix multiplication. CUDA is NVIDIA's platform for programming them, and most AI software assumes it.
- A TPU is Google's chip designed only for these workloads, available through Google Cloud.
The number that matters most is often not the GPU's arithmetic speed but its memory. VRAM is the GPU's own memory, small and very fast. System RAM is large and much slower to reach from the GPU. Weights must live in VRAM for the model to run at full speed, which is why a GPU's memory size, not its core count, usually decides which models it can serve.
Training and inference
Training is choosing the weights, by running the model forward, measuring the loss and adjusting every weight a little, billions of times. It needs far more memory than running the model (the weights, their gradients and the optimiser's state) and enormous amounts of compute. Inference is using the finished weights to answer a request. Training happens once; inference happens on every request for the life of the product. As an application engineer, inference is what you pay for and what your users wait for.
Prefill and decode: why the first token is slow
Every request runs in two phases, and they behave very differently.
Prefill reads the whole prompt. All the prompt's tokens go through the model together in one parallel pass. This keeps the GPU's cores busy, so it is limited by arithmetic, and its cost grows with the length of the prompt.
Decode writes the answer, one token at a time. Each new token needs a complete pass through the model, and each pass has to read every weight from memory to do a small amount of work. The GPU spends most of its time waiting for memory, so decode is limited by memory bandwidth.
This split gives you the two latency numbers that matter for any AI feature:
- Time to first token (TTFT): roughly the prefill time, plus queueing and network. It is what makes a chat feel responsive or sluggish.
- Tokens per second during decode (or its inverse, time per output token): how fast the answer streams once it starts.
Total latency is about TTFT plus the number of output tokens divided by tokens per second. A request with a short prompt and a long answer is dominated by decode; a request that stuffs fifty pages into the prompt and asks for one word is dominated by prefill.
Throughput is a different question: how many requests, or tokens, the whole system handles per second. Latency is what one user feels, throughput is what your hardware bill buys, and the two pull against each other.
The KV cache
During decode, each new token has to attend to every token before it, and that needs each earlier token's key and value vectors (chapter 2). Recomputing them for the whole sequence at every step would be enormously wasteful, so the server keeps them in memory: the KV cache. It turns each decode step from "reprocess everything" into "process one new token".
The cost is memory, and it grows with every token of context and every concurrent request. The formula is mechanical:
The 2 is for keys and values. For Llama 2 7B (32 layers, 32 heads of size 128, fp16):
A 4,096-token conversation therefore needs about 2 GB of KV cache, on top of 14 GB of weights, for one user. Ten users at once need 20 GB more. This is why long contexts are expensive, why serving systems limit concurrency, and why newer models share key and value heads across query heads (grouped-query attention) to shrink the cache.
what fits on a GPU
- weights
- 13.0 GB
- KV cache
- 2.0 GB
- needs
- a 24 GB GPU
Making inference cheaper
Batching
Because decode is waiting on memory anyway, a GPU can process many requests' next tokens in the same pass for almost the same cost as one: the weights are read once and used many times. That is batching, and it is the biggest lever on throughput.
Simple batching waits for a group of requests, runs them together and waits for the slowest to finish, wasting capacity on requests that finished early. Continuous batching adds and removes requests from the running batch at every decode step, so the GPU stays full. Modern serving engines all do it.
Quantization
Quantization stores weights at lower precision, for example 4 bits instead of 16. The model needs a quarter of the memory, fits on smaller GPUs, and decodes faster because there are fewer bytes to read per token. The cost is some quality, usually small at 8 bits and noticeable but often acceptable at 4 bits, depending on the model and the task. Common formats are GGUF (llama.cpp and Ollama), GPTQ and AWQ. Measure on your own task before deciding.
Caching the prompt
Many requests share a long common beginning: the same system prompt, the same tool definitions, the same document. Serving engines can keep the KV cache for that shared prefix and skip its prefill next time. Most hosted APIs expose this as prompt caching, priced well below normal input tokens. Put the stable parts of your prompt first and the parts that change last, and you get this for free. Chapter 9 returns to caching in general.
The context window, priced
A bigger context window is a capability, not a free resource. Prefill compute grows with prompt length (attention compares every token with every other, so it grows faster than linearly for long prompts), and KV cache memory grows linearly with it. Every token you add to every request is paid for in latency, memory and money. Retrieval (chapter 5) is, among other things, a way to send ten relevant passages instead of a whole library.
Serving a model
To run an open model you need a serving engine: software that loads the weights, batches requests and exposes an API.
- Ollama and llama.cpp run models on a laptop or a single machine, including on CPUs and Apple silicon. Ideal for development and experiments.
- vLLM is built for serving many users on GPUs. Its PagedAttention manages the KV cache in small blocks, like virtual memory pages, so less memory is wasted and more requests fit at once.
- NVIDIA TensorRT-LLM compiles models for NVIDIA GPUs for maximum speed, at the cost of more setup.
- Hugging Face is where most open weights are published, and its libraries load them.
Most of these engines offer an OpenAI-compatible API, so your application code barely changes between a hosted model and one you run yourself.
When a model is too big for one GPU, distributed inference splits it: tensor parallelism splits each layer's matrices across GPUs, and pipeline parallelism gives different layers to different GPUs. Both add communication overhead, and you will rarely need them unless you serve very large open models yourself.
The maths underneath
Maths note 12 gives you the rules of thumb that turn these ideas into estimates.
Weight memory is parameters times bytes per parameter, as in the table above.
Compute is about floating-point operations per token to run a model with parameters (one multiply and one add per weight), and about per token to train it.
Decode speed has a ceiling set by memory bandwidth. At batch size one, every token needs every weight read once, so:
A 7B model quantized to 4 bits is about 3.5 GB. On a GPU with 1 TB/s of bandwidth the ceiling is around 285 tokens per second; on a laptop with 100 GB/s it is around 28. Real numbers come in below the ceiling, but the estimate tells you within minutes whether a model on a given machine can ever be fast enough for your feature.
Total latency is approximately:
which is why "keep the answer short" is a real latency optimisation, not just a style preference.
Build it: a model on your own machine
- Install Ollama and pull a small model that is published in several quantizations (most model pages list tags for 4-bit, 8-bit and 16-bit versions).
- Run the same prompt against each version with
ollama run <model> --verbose, which prints the prompt evaluation rate (prefill) and the eval rate (decode) in tokens per second. - While each model is loaded, run
ollama psto see how much memory it takes and whether it is on the GPU or the CPU. - Write down, for each version: memory used, time to first token, decode tokens per second, and your own judgement of the answer's quality on five prompts.
- Make one prompt ten times longer and watch which number moves (prefill) and which does not (decode).
- Optional, with a GPU: serve the same model with vLLM and send it twenty requests at once. Compare the throughput with sending them one at a time.
Check your measurements against the bandwidth ceiling above. If they disagree wildly, find out why; that is where the understanding comes from.
Where people go wrong
- Sizing a GPU for the weights alone. Leave room for the KV cache and for concurrent requests.
- Optimising the wrong phase. A slow first token is a prefill problem (prompt too long, queueing); a slow stream is a decode problem (model too big for the bandwidth).
- Assuming quantization is free. It usually is close, sometimes it is not. Measure on your task.
- Spending weeks on GPU programming. The goal is to reason about compute, not to write it. Move on once the arithmetic in this chapter feels natural.