In this article, you will learn how LLM inference works on a GPU, and which techniques and metrics engineers use to make serving faster, cheaper, and more reliable.
Topics we will cover include:
- How prefill, decode, the roofline model, and the KV cache determine where inference time and GPU memory go.
- How batching, paged and prefix caching, chunked prefill, quantization, speculative decoding, and FlashAttention raise throughput and cut latency.
- How to choose an inference engine and parallelism strategy, measure TTFT, TPOT, and goodput, and tune a deployment against latency targets.

Introduction
Training and serving a language model put different demands on the same GPU. Training cares about how many tokens a cluster processes over several days. Serving, however, cares about how long each user waits, with many users sharing one set of hardware and one pool of memory.
If you understand the basics of how transformers generate text one token at a time, you already have the foundation for understanding LLM inference engineering. This article takes you further, exploring what happens between a prompt and a generated response, how GPUs handle that workload, and how to optimize inference for speed, throughput, and efficiency. Here’s what we’ll cover:
- Steps 1 to 3: how a request runs, where GPU memory goes, and which metrics to track
- Steps 4 and 5: the techniques that raise throughput and cut latency
- Steps 6 and 7: choosing an LLM inference engine and parallelism strategy, then tuning against latency targets and planning for production
We start with what happens to a single request.
Step 1: Understanding Prefill, Decode, and the Roofline Model
An LLM generates a response in two distinct stages: first, it processes the input prompt; then, it generates the response one token at a time. These stages are known as prefill and decode, and they place very different demands on the GPU:
- Prefill: the model processes the whole prompt in one parallel pass and produces the first output token.
- Decode: the model generates the rest of the answer one token at a time, and each step depends on every token before it.
These phases load the GPU differently, and the roofline model shows how. It is a chart of achievable speed against arithmetic intensity, the number of operations a program performs for each byte it reads from memory. Two limits meet in the shape of a roof: a sloped line on the left, where memory bandwidth caps speed, and a flat line on the right, where the GPU’s peak arithmetic rate takes over. The corner is the ridge point. A kernel to its left waits on data and is memory-bound, and a kernel to its right keeps the arithmetic units busy and is compute-bound.

Image created by author on diagrams.net (click to enlarge)
Decode sits on the left. To produce one token, the GPU streams every weight out of memory and uses each for a single multiply-add, so single-stream speed tops out at the memory bandwidth divided by the model’s size in bytes. Prefill sits on the right: the whole prompt passes through each weight as it arrives, so one read serves thousands of tokens.
Batching pushes decode toward the right. When several users decode together, one read of the weights yields a token for each of them, so the work per byte grows with the batch until the GPU becomes compute-bound. Most techniques in Steps 4 and 5 raise the work done per byte read.
To practice: find your GPU’s peak arithmetic rate and memory bandwidth on its spec sheet, and divide the arithmetic rate by the bandwidth to get its ridge point.
Step 2: Understanding the KV Cache
Decode has a second cost that grows as a conversation gets longer. At each step, attention needs the keys and values of every earlier token. Recomputing them for each new token would repeat the same work again and again, so servers use KV caching: they compute the keys and values once and reuse them at every later step. The stored collection is the KV cache, which holds one key vector and one value vector per token for every layer and every key-value head. To learn more, read KV Caching in LLMs: A Guide for Developers.
The cache grows with the number of layers, key-value heads, head size, numeric precision, and the tokens across all active sequences. It shares GPU memory with the weights, so what remains after the weights and the runtime’s working space caps how many tokens the server can hold for all users combined.
Grouped-query attention (GQA) shrinks it by letting several query heads share one key-value head: with four query heads per key-value head, the cache is a quarter of the size. Check a model’s key-value head count along with its parameter count.
To practice: read a model’s layer count, key-value head count, and head dimension from its config file, and work out how many bytes one token adds to the cache at 16-bit precision.
Step 3: Measuring With the Right Metrics
A single throughput figure can look healthy while users wait seconds for the first word, so track the following key LLM inference metrics:
| Metric | What it measures |
|---|---|
| Time to first token (TTFT) | Delay until the first token arrives, including queue time and prefill |
| Time per output token (TPOT) | Average gap between tokens after the first |
| Throughput | Tokens or requests completed per second across all users |
| Goodput | Requests per second that meet your latency targets |
For one request with \( N \) output tokens, TTFT and TPOT combine into the total wait:
\(\text{E2E latency} = \text{TTFT} + \text{TPOT} \cdot (N – 1)\)
The first token arrives after TTFT, and each of the remaining \(N – 1\) tokens takes one TPOT. Goodput builds on limits you choose, such as a TTFT limit and a TPOT limit, and counts the requests that meet every limit over a measurement window of length \(T\):
\(\text{goodput} = \frac{N_{\text{good}}}{T}\)
Report TTFT and TPOT as percentiles such as P95 and P99, since an average hides the slow requests that produce complaints. Benchmarking tools also define these metrics slightly differently, so check how your LLM inference framework does before you compare numbers.
To practice: load-test a small model and record TTFT and TPOT at several concurrency levels.
Step 4: Batching Requests and Managing Memory
With the vocabulary in place, we can now look at techniques that get more out of every weight read. Serving multiple requests efficiently on a GPU comes down to how the system manages scheduling and memory. The following techniques make this possible:
Continuous batching avoids the inefficiency of static batching, where every request must wait for the slowest one to finish. For example, if three requests need only a few dozen tokens and one needs hundreds, the shorter requests leave their slots sitting idle. With iteration-level scheduling, batch membership is reassessed at every model iteration. As soon as a request finishes, a queued request takes its place, keeping the GPU busy. To learn more about batching techniques, read Static vs. Dynamic vs. Continuous Batching in LLM Inference.
Paged KV caching eliminates the memory waste of pre-allocating space for a model’s maximum sequence length. Because output lengths are unpredictable, the cache is divided into small, fixed-size blocks allocated on demand as new tokens are generated. A block table maps each sequence to its physical blocks — just like an operating system’s page table — eliminating fragmentation and allowing larger batch sizes within the same GPU memory.
Prefix caching takes this further by allowing requests with identical prefixes to share cached blocks. For example, a long system prompt or shared document only needs to be prefilled once and can then be reused across requests that begin with the exact same tokens. This avoids repeating the same computation.
Chunked prefill prevents long prompts from occupying an entire model iteration and increasing other users’ inter-token latency. Instead, each iteration gets a fixed token budget. Ongoing decode requests are handled first, and the remaining budget is used to process a portion of the incoming prompt. This allows existing requests to keep generating tokens while longer prompts advance in smaller chunks.
Together, these techniques determine how efficiently a GPU can serve multiple users simultaneously.
To practice: serve a model using vLLM and replay a mix of short and long prompts while monitoring TTFT and TPOT.
Step 5: Reducing Memory Traffic and Speeding Up Inference
Batching shares each weight read among more requests. The techniques in this step shrink what has to be read, or produce more tokens from each read.
Quantization stores each weight in fewer bits. A scale factor maps the floating-point weights onto a small range of integers, and the scale is applied again when a weight is used, so a 4-bit weight takes roughly a quarter of the memory of a 16-bit one and decode reads proportionally fewer bytes per token. The price is rounding error, which grows as the bit width shrinks. Methods such as GPTQ and AWQ quantize a trained model while limiting the damage from that error. Evaluate the quantized model on your own task before you ship it.
Speculative decoding builds on a useful fact: checking several tokens in one step costs about the same weight read as generating one. A small draft model proposes a short run of tokens, and the large model verifies the whole run in a single pass. It accepts each drafted token with a probability based on how much the two models agree, and when it rejects one, it samples a replacement from a corrected distribution. This procedure reproduces the large model’s output distribution exactly. When the draft is right, one pass of the large model yields several tokens, and when it is wrong, little is lost, because the verification pass costs about the same as an ordinary step. The gain depends on how often the draft guesses right, so measure the acceptance rate on your own traffic.

Image created by author on diagrams.net (click to enlarge)
Memory-efficient attention applies the same logic inside the attention layer. Standard attention writes a score for every pair of tokens to main memory and reads the scores back for the softmax. FlashAttention tiles the computation: it processes the scores in blocks that fit in the GPU’s small on-chip memory, keeping a running maximum and a running sum so the softmax is exact after the last block. The full score matrix never reaches main memory.
To practice: serve the same model at two precisions and compare quality and tokens per second.
Step 6: Choosing the Inference Engine and Parallelism Strategy
Now that you know what to optimize, the next decision is where the model runs. Start with whether the weights fit. Their size is the parameter count times the bytes each parameter occupies, so a 16-bit model takes two bytes per parameter and a 4-bit model about half a byte. Add the KV cache from Step 2 and the runtime’s working space, and compare the total with the memory of one GPU.
When it does not fit — or you need higher throughput and lower latency — you scale across multiple GPUs:
| Strategy | What it does |
|---|---|
| Tensor parallelism | Divides each layer’s weights across GPUs |
| Pipeline parallelism | Puts consecutive layers on different GPUs |
| Data parallelism | Runs full model copies to add capacity |
| Prefill/decode disaggregation | Runs the two phases on separate GPU pools so each can be tuned for goodput |
Tensor parallelism synchronizes the GPUs inside every layer, so it wants a fast interconnect. Pipeline parallelism passes activations from one stage to the next, and a stage sits idle whenever the pipeline is not full, a problem that splitting each batch into more micro-batches helps reduce. Disaggregation stops prefill and decode from interfering with each other but adds the cost of moving the KV cache between pools, so measure that overhead first.
With the layout chosen, pick an inference engine that implements the batching, caching, and compression techniques you need. vLLM, SGLang, and TensorRT-LLM implement the techniques from Steps 4 and 5 with different strengths, so benchmark them on your own model, prompt mix, and hardware.
Model choice affects cost as well. A small model that handles your task costs less per token, and a mixture-of-experts model activates only a few experts per token, cutting compute and weight reads even though all experts still need to fit in memory.
To practice: work out the smallest GPU count and precision that fit your target model with room for the KV cache.
Step 7: Tuning Against Latency Targets and Planning for Production
Once the model is running, the work shifts to defining good performance and keeping the deployment there. Start by writing down your latency limits, for example a TTFT limit and a TPOT limit at the 95th percentile. A request is good when it meets every limit, and goodput counts those requests per second. Four settings do most of the tuning:
- Maximum concurrent sequences
- Maximum context length
- Chunk size for chunked prefill
- Share of GPU memory given to the KV cache
Raising concurrency increases throughput until per-user speed falls below your limits, so raise it until goodput peaks and back off from there.
To plan capacity, Little’s law helps: the average number of requests in flight equals the arrival rate multiplied by the average time each request spends in the system. If you know the request rate you want to serve and the latency you can offer, their product tells you how many sequences must run at once, and from that how much KV cache the deployment needs.
After launch, watch the TTFT and TPOT percentiles, queue depth, KV cache utilization, and goodput. KV cache utilization gives early warning: when the cache fills, new requests wait, which pushes TTFT up, and some engines evict running requests. For autoscaling, queue depth or concurrent requests track GPU load better than CPU usage does. Rerun your evals whenever you change the quantization, engine version, or model, because each of those can change output quality.
To practice: pick a latency target, load-test two configurations, and compare their goodput.
Wrapping Up
Decode spends its time reading memory, and each step of this roadmap approaches that cost from a different side. Batching, paged and prefix-cached KV memory, and chunked prefill make each read serve more users. Quantization shrinks what is read, speculative decoding gets several tokens from one read, and FlashAttention cuts memory traffic inside the attention layer. Engine, parallelism, and tuning choices determine how well these techniques combine for your model.
To put this into practice, pick an open model and serve it with vLLM. Record TTFT, TPOT, and goodput at a few concurrency levels for a baseline, then change one thing at a time: enable prefix caching, try a quantized checkpoint, adjust the chunk size. A log of each change and its effect on goodput becomes your own reference for what works on your hardware.
When you are ready to decide which of these techniques to apply first for your own workload, Choosing an LLM Inference Optimization Technique: A Decision-Tree Approach is a natural next read.






No comments yet.