When someone says "the model is slow" or "the GPU bill blew up", the problem is almost never the model itself. It's how the model is being served. The same model, on the same GPU, can serve one user at a time or dozens at once, depending on how memory and requests are organized.
This article explains, from scratch, what happens between you hitting Enter and the first word showing up on screen, where the bottleneck is, and what each well-known technique does. No formulas too early: first the analogy, then the mechanism, then the numbers.
An Analogy to Start
Picture a restaurant kitchen.
- The cook reads the whole order before starting: appetizer, main course, allergies, how the steak should be done. He reads it all at once, fast, because he can see the whole ticket. That's prefill.
- Then he builds the plate one item at a time, and each item depends on the one before. You can't add the sauce before the meat. That's decode: one token at a time, each one looking at all the previous ones.
- So he doesn't have to reread the ticket for every item, he leaves notes on the counter: what's done, what's left. Those notes take up space. With many tables at once, the counter fills up. That's the KV cache.
Almost every inference optimization is one of these ideas: a shorter ticket, a better organized counter, more plates going out together, or a helper running ahead so the chef only has to check.

What Happens When You Send a Prompt
A language modelAI model trained on large amounts of text to predict the next word, which lets it chat, summarize, translate and write code. generates text one token at a time (if the term is new to you, the article on what tokens are explains it). To generate the next one, it has to consider all the previous tokens. That creates two phases that behave very differently.
| Phase | What it does | Bound by | Metric it affects |
|---|---|---|---|
| Prefill | Processes all prompt tokens in parallel | Compute (the GPU stays busy) | Time to first token |
| Decode | Generates one token at a time, in sequence | Memory (reading weights and KV cache for every token) | Time between tokens |
Databricks' inference engineering post sums it up: generating the first token is usually compute-bound, and the decoding that follows is memory-bound. The practical consequence is big: during decode, the GPU spends a good part of its time waiting for data to arrive from memory, not computing. That's why so many optimizations target memory.
The Metrics That Matter
Before optimizing, you need to know what to measure. There are four numbers:
- TTFT (time to first token): how long until the first word shows up. It's what the user feels as "slow to start".
- TPOT or ITL (time per output token): the gap between one token and the next. It sets the "typing speed". Databricks gives a reference: 100 ms per token is 10 tokens per second, faster than most people read.
- Total latency: TTFT plus TPOT times the number of generated tokens. A 500-token answer with a 0.5 s TTFT and a 30 ms TPOT takes about 0.5 + 0.03 × 500 = 15.5 seconds.
- Throughput: how many tokens per second the server generates across all users. It's what sets the cost per request.
Latency and throughput pull against each other. Putting more users in the same batch raises throughput (the GPU gets more done), but each user may wait a bit longer. Optimizing means picking the right point in that trade-off for your product: a chat wants low TTFT; an overnight document job wants high throughput.
The KV Cache: The Counter That Fills Up
During decode, the model has to "look at" all the previous tokens. Recomputing everything for every token would be far too slow, so it stores two vectors per token in each layer, the keys (K) and the values (V). That's the KV cache.
The math is simple: 2 (K and V) × number of layers × KV heads × head dimension × bytes per number. For Llama 3.1 8B, using the values from the model's config file (32 layers, 8 KV heads, dimension 128, 2 bytes in bf16):
2 × 32 × 8 × 128 × 2 = 131,072 bytes, about 128 KiB per token.
It looks small until you multiply: 8K tokens of context come to 1 GiB, per user. Twenty users with long conversations at the same time take up more memory than the model weights themselves (about 16 GB in 16 bits). On Llama 3.3 70B, the same math gives about 320 KiB per token, or roughly 40 GiB for a single 128K-token context.
These models already use an architecture trick for this: GQA (grouped-query attention), where several attention heads share the same keys and values. Llama 3.1 8B has 8 KV heads for 32 query heads; without GQA, the cache would be 4 times bigger. The GQA paper shows quality close to full attention, with speed close to the leaner version.
The Techniques, One by One
Quantization: Smaller Weights
A model's weights are usually stored at 16 bits per number. Quantizing means storing them in 8 or 4 bits. The model gets smaller, fits on a cheaper GPU and, since decode is memory-bound, it also gets faster: fewer bytes to read for every token.
- LLM.int8() (2022) showed you can cut memory in half while keeping quality, by handling the few extreme values (outliers) separately in 16 bits.
- GPTQ (2022) quantizes a 175 billion parameter model to 3 or 4 bits in about four GPU hours, with negligible accuracy loss according to the authors, and sped up inference by about 3.25 times on an A100.
- AWQ (2023, best paper award at MLSys 2024) starts from one observation: protecting just the 1% most important weights already cuts the error a lot.
- FP8 is supported in hardware starting with NVIDIA's Hopper generation (H100), which, according to NVIDIA, computes in FP8 at four times the A100's rate per multiprocessor.
The catch: quantization is a trade-off. At 8 bits the loss is usually small; at 4 bits it depends on the method and the task. Measure it on your own evaluation, don't rely only on the vendor's benchmark.
PagedAttention: The Organized Counter
Older servers reserved, for each request, a contiguous block of memory sized for the longest answer it could produce. If the answer came out short, the reserved space sat empty. The vLLM launch post estimated that systems at the time wasted 60% to 80% of KV cache memory to fragmentation and over-reservation.
PagedAttention, the core idea behind vLLM (2023), copies what the operating system does with RAM: it splits the KV cache into small fixed-size blocks and allocates them on demand, without needing contiguous space. Waste dropped to under 4%.
Spare memory turns into a bigger batch: the vLLM paper measured 2 to 4 times more throughput at the same latency, compared to the best systems of the time.
Continuous Batching: More Plates Going Out Together
Grouping several requests into a batch makes the GPU get more done, because it reads the weights once and uses them for everyone. The problem with the traditional batch: it only finishes when the longest answer finishes. Whoever asked for a short sentence waits for the neighbor who asked for a long text, and the slot sits idle.
Continuous batching (also called iteration-level scheduling, from the Orca paper, 2022) swaps the batch on every token: when one answer finishes, another request takes the slot right away. Orca measured 36.9 times more throughput on GPT-3 175B, at the same latency, against FasterTransformer. Anyscale reached up to 23 times by combining continuous batching with vLLM's memory optimizations.
Prefix Caching: Don't Reread the Same Ticket
Many requests start the same way: the same long system prompt, the same instructions, the same reference document. Without a cache, prefill reprocesses that beginning on every question.
Prefix caching stores the KV cache for that prefix and reuses it when a new request starts the same way. vLLM's docs call it "almost a free lunch": it doesn't change the model's output, it just avoids repeated work. SGLang has its own version, RadixAttention, which organizes prefixes in a tree.
If you use an APIContract that defines how one program asks another for data or actions: which endpoints to call, what to send and what comes back. On the web, usually HTTP with JSON., it's the same idea as the prompt caching that OpenAI, Anthropic and Google offer: the repeated part of the prompt gets cheaper and faster, as long as it stays at the beginning and is identical across calls.
FlashAttention: Fewer Round Trips to Memory
Attention is the part of the model that compares each token with the others. The naive implementation writes and reads intermediate matrices to the GPU's main memory several times. FlashAttention (2022) reorganizes the computation into blocks that fit in the chip's fast memory, computing the exact same result with far fewer reads and writes.
The series kept going: FlashAttention-2 doubled the speed of the first one, and FlashAttention-3 (2024) was built for the H100, reaching 75% of the card's theoretical peak in FP16. You rarely use this directly: inference engines already ship it by default.
Speculative Decoding: The Helper Runs Ahead, the Chef Checks
During decode, the GPU spends its time waiting on memory, with compute to spare. Speculative decoding uses that slack: a small, fast model (the draft) guesses several tokens ahead, and the big model checks them all at once, in a single pass. The right tokens are accepted; at the first wrong one, the big model corrects it and the cycle starts over.
The detail that makes the technique so popular: the output is the same. The Leviathan et al. paper (2022) showed a 2 to 3 times speedup on T5-XXL with identical outputs, without retraining anything. Variants like Medusa and EAGLE replace the draft model with extra heads on the model itself; EAGLE reports 2.7 to 3.5 times on Llama 2 Chat 70B, keeping the output distribution.
The gain depends on the draft's hit rate: on predictable text (code, fixed formats) it pays off a lot; on creative text, less.

Parallelism and Splitting the Phases
When the model doesn't fit on one GPU, it gets split. Tensor parallelism divides each layer across several GPUs in the same server; it's the option vLLM's docs point to first for this case.
A more recent idea is running prefill and decode on different GPUs, since the two phases have opposite bottlenecks and get in each other's way when they share a card. DistServe (2024) measured up to 7.4 times more requests served within TTFT and TPOT targets.
The Map: Which Technique Targets What
| Technique | Improves | Cost or risk |
|---|---|---|
| Quantization | Memory, decode, GPU cost | Can lose quality, especially at 4 bits |
| PagedAttention | Users per GPU (throughput) | None for the user: it comes with the engine |
| Continuous batching | Throughput, GPU utilization | Individual latency can rise with a full batch |
| Prefix caching | TTFT and cost on repeated prompts | Only helps if the start of the prompt is identical |
| FlashAttention | Attention speed, long contexts | None for the user: it comes with the engine |
| Speculative decoding | Time per token (TPOT) | Needs a good draft; gain drops on unpredictable text |
| GQA | KV cache size | It's an architecture choice: it comes with the model |
| Tensor parallel and phase splitting | Large models, latency targets | More GPUs and more operational complexity |
Inference Engines in 2026
Nobody needs to implement PagedAttention by hand. The work is picking the right engine and configuring it well.
| Engine | What it's for | Version (11/21/2026) |
|---|---|---|
| vLLM | Production GPU serving, the de facto standard in the open ecosystem | 0.34.0 |
| SGLang | Production GPU serving, strong at reusing prefixes (RadixAttention) | 0.5.23 |
| TensorRT-LLM | Maximum performance on NVIDIA GPUs, with more configuration work | 1.3.0 |
| llama.cpp | CPU, Mac and modest GPUs, with quantized models (GGUF) | 1.0.0 |
| Ollama | Running models locally with one command, great for development | 0.40.17 |
A heads-up if you're following an old tutorial: TGI (Text Generation Inference, from Hugging Face) is in maintenance mode and its repository is archived. The README itself recommends moving to vLLM, SGLang, llama.cpp or MLX.
Where to Start
- Measure first. TTFT, TPOT and throughput with traffic close to the real thing. Without a baseline, you can't tell whether anything improved.
- Use a modern engine. Swapping a homemade server for vLLM or SGLang gets you PagedAttention, continuous batching and FlashAttention in one go.
- Turn on prefix caching and always put the fixed part of the prompt at the beginning.
- Test a quantized version (8 bits first, then 4 bits) and compare it on your quality evaluation.
- Keep context size in check. Every extra token in the prompt costs prefill and KV cache; summarizing history and cutting what doesn't help is worth as much as any GPU trick.
- Speculative decoding and parallelism last, once the earlier steps are in place.
If you use an API (OpenAI, Anthropic, Google) and don't serve your own model, half the list still applies: prompt cachingModel provider feature that stores the repeated start of an already processed prompt, charging less and answering faster on later calls., a lean context, streaming so the user sees the answer as it's written, and a smaller model for simple tasks. In an agent, which calls the model several times per task, that care multiplies, as I showed in the guide to AI agents from scratch.
Quick check
Frequently Asked Questions
What's the difference between training and inference?
In training, the model adjusts its weights from examples (including in fine-tuning). In inference, the weights are fixed and the model only generates answers. Training happens now and then; inference happens on every question, which is why it dominates day-to-day cost.
Does quantizing always make the model worse?
It always changes something, but at 8 bits the difference is usually small and, at 4 bits, methods like GPTQ and AWQ keep much of the quality. The right answer comes from your evaluation, with your cases.
Do I need a GPU to run a model locally?
For small, quantized models, not necessarily: llama.cpp and Ollama run on CPU and on Mac. To serve many users with low latency, a GPU is still the way to go.
vLLM or SGLang?
Both ship the main techniques. SGLang stands out when many requests share prefixes (agents, chained calls). The smart choice is to test both with your traffic.
What are tokens per second, and how much is good?
It can be per user (how fast the answer appears on screen) or summed across the server (throughput). For human reading, 10 tokens per second per user already keeps up with reading; for batch processing, what counts is the total.
References
- Efficient Memory Management for LLM Serving with PagedAttention, Kwon et al., SOSP 2023
- vLLM: Easy, Fast, and Cheap LLM Serving with PagedAttention, vLLM blog, 2023
- Orca: A Distributed Serving System for Transformer-Based Generative Models, OSDI 2022
- How continuous batching enables 23x throughput in LLM inference, Anyscale, 2023
- FlashAttention, Dao et al., 2022
- FlashAttention-2, Dao, 2023
- FlashAttention-3, Shah et al., 2024
- Fast Inference from Transformers via Speculative Decoding, Leviathan et al., 2022
- Accelerating Large Language Model Decoding with Speculative Sampling, Chen et al., 2023
- Medusa, Cai et al., 2024
- EAGLE, Li et al., 2024
- GPTQ, Frantar et al., 2022
- AWQ, Lin et al., MLSys 2024
- LLM.int8(), Dettmers et al., 2022
- GQA: Training Generalized Multi-Query Transformer Models, Ainslie et al., 2023
- DistServe, Zhong et al., OSDI 2024
- SGLang, Zheng et al., 2023
- LLM Inference Performance Engineering: Best Practices, Databricks, 2023
- Mastering LLM Techniques: Inference Optimization, NVIDIA, 2023
- LLM benchmark metrics, NVIDIA NIM
- NVIDIA Hopper Architecture In-Depth, NVIDIA
- Automatic Prefix Caching, vLLM docs
- Text Generation Inference, archived repository