Why does a model that answers a prompt in half a second grind to a crawl when a hundred users arrive at once? It is rarely the model’s raw intelligence. More often, it is how the serving system handles memory, batching, and the two very different phases of generation. Understanding those mechanics is the fastest route to real speedups.
Why inference optimization matters more than training
Training gets the headlines, but inference pays the bills. Every request a production system serves costs compute, memory bandwidth, and electricity. A model that is 30 percent cheaper to run at scale can save more money over a year than a slightly better model costs to train.
The economics also shape user experience. Time to first token (how long before the first word appears) and inter-token latency (how fast the rest streams) decide whether an assistant feels instant or sluggish. Optimizing inference is therefore two jobs at once: cutting cost and cutting wait time. The two goals sometimes pull in opposite directions, which is why tuning requires measurement rather than guesswork.
The two phases of generation, and why they behave differently

Every autoregressive model does two things. First comes prefill: the model reads the whole prompt in one parallel pass. This phase is compute-bound and scales with prompt length. Then comes decode: the model emits one token at a time, each step depending on the last. Decode is memory-bandwidth-bound and stubbornly sequential.
That split matters because a single optimization rarely helps both phases. A trick that accelerates prefill may do nothing for decode. Systems such as Sarathi-Serve exploit the difference by chunking prefill work so it does not stall ongoing decode steps. Practical tip: when profiling, always report prefill and decode numbers separately. Blended averages hide the bottleneck.
The KV cache is usually the real constraint
During decode, the model stores keys and values for every token it has already processed. This KV cache grows linearly with context length and batch size. On long-context workloads it can dwarf the model weights themselves, which is why memory capacity, not raw compute, often caps how many users you can serve.
The PagedAttention approach, introduced with vLLM, manages this cache in fixed-size blocks the way an operating system manages virtual memory. The PagedAttention paper on KV cache block management explains the design and reports 2 to 4 times higher throughput than prior systems on some workloads. Treat those numbers as workload-specific upper bounds, not guarantees. If you are planning capacity, it helps to understand why memory capacity matters for inference planning before you buy hardware.
Continuous batching: the single biggest scheduling win
Older servers batched requests at the request level: a batch formed, ran to completion, then a new batch started. Short requests waited behind long ones, wasting slots. Continuous batching, introduced by Orca, schedules at the iteration level instead. New requests join the running batch at the next decode step, and finished ones leave immediately.
The Orca paper on iteration-level scheduling describes the technique in detail. It is now standard in nearly every serious serving stack, and for good reason: it improves GPU utilization without touching model quality at all. If a team does only one thing from this article, continuous batching should be it.
Speculative decoding: draft cheaply, verify exactly
Speculative decoding uses a small draft model to propose several tokens, then has the large model verify them all in a single forward pass. Under rejection sampling, the output distribution stays identical to the target model, so quality does not change. The speculative decoding paper by Leviathan and colleagues lays out the draft-and-verify method.
The catch is the acceptance rate. If the draft model guesses poorly, verification rejects most proposals and you pay overhead for nothing. In practice, speculative decoding works best when the draft model closely matches the target’s style and the task is predictable, such as code completion or structured extraction. It works poorly on open-ended creative writing where token choices are unpredictable.
Kernel-level tricks: FlashAttention and friends
FlashAttention reorganized the attention computation to reduce memory traffic between GPU memory tiers, using tiling rather than changing the underlying math. The FlashAttention paper on IO-aware tiled attention explains why memory movement, not arithmetic, was the bottleneck. The second version pushed further on parallelism.
These kernel improvements are complementary to batching and caching. They lower the cost of each step; scheduling decides how many steps you run concurrently. Teams often chase kernel gains while ignoring scheduling, which is like tuning an engine while the parking brake is on.
Quantization: cheaper weights, careful quality checks
Quantization stores weights in 8-bit or 4-bit precision instead of 16-bit, cutting memory use and often raising throughput. Post-training methods such as GPTQ and AWQ make this practical without retraining. The GPTQ paper on post-training 4-bit weight quantization describes one widely used approach.
The honest caveat: quality loss is task-dependent. A model that scores well on a benchmark after 4-bit quantization can still degrade on niche reasoning, long documents, or unusual languages. A common mistake is quantizing, running one benchmark, and shipping. Better practice is to build a small evaluation set from real production traffic and compare quantized and full-precision outputs side by side before committing.
Mixture-of-experts and smaller models
Mixture-of-experts (MoE) architectures activate only a subset of parameters per token, lowering compute per token while raising memory requirements. Switch Transformer was an early large-scale demonstration. The trade is real: MoE models can be faster per token but need more VRAM, so they suit high-throughput deployments more than tight single-GPU setups.
Model-level alternatives include distillation, where a smaller student model learns from a larger teacher. DistilBERT showed the pattern for encoders; decoder equivalents now power many cost-sensitive products. Distillation changes the model rather than the serving system, so it is worth considering when latency targets are strict and some quality loss is acceptable.
Serving frameworks and the benchmarking trap
vLLM, TensorRT-LLM, and Text Generation Inference all package these techniques. Their documentation is genuinely useful, but their benchmarks are vendor-published and should be read as marketing-adjacent. The bigger problem is methodological: latency, throughput, and time-to-first-token are often reported under different batch sizes and hardware, so cross-paper comparisons are unreliable.
A practical habit that separates experienced teams from novices: fix the workload before comparing systems. Pin prompt length distribution, output length, concurrency, and hardware. Then measure. A useful discipline is to measure inference latency end to end rather than trusting single-number claims, because queueing and network time often dominate.
A practical optimization sequence
Teams that get results tend to follow a sequence rather than chasing every technique at once.
- Instrument first. Separate prefill and decode timings, log queue wait, and record token counts per request.
- Turn on continuous batching and paged KV cache. These are usually free wins with no quality cost.
- Right-size the batch and context limits. Cap maximum context where the product allows it; long contexts are expensive.
- Evaluate quantization against a real-traffic eval set, not a public benchmark alone.
- Add speculative decoding only where acceptance rates prove high in your logs.
- Revisit architecture choices such as MoE or distillation when serving-level gains plateau.
This ordering matters because later steps depend on earlier measurements. Speculative decoding tuned on a system without continuous batching will mislead you.
Batch versus real-time: pick the right mode
Not every workload should be served the same way. Offline summarization, embedding generation, and nightly classification can run as batch jobs at high utilization. Chat assistants and agents need interactive latency. Mixing the two on the same cluster usually hurts both. The trade-offs are covered well in this guide to choosing between batch and real-time inference.
If you are designing the overall system, a broader look at AI inference architecture for enterprises helps connect serving choices to cost, reliability, and scaling decisions.
Common mistakes that quietly erase gains
A few patterns show up again and again. Teams benchmark with batch size one and then deploy at concurrency fifty, where memory pressure changes everything. Others enable quantization and skip regression testing on edge cases. Some forget that time to first token includes queueing, so a fast model behind a slow scheduler still feels slow.
Another frequent error is ignoring the tail. Average latency can look fine while the 95th percentile is terrible, usually because long requests block short ones. Continuous batching helps, but admission control and per-request token limits do more. Finally, many teams never revisit their choices. Hardware, model versions, and traffic patterns shift; an optimization that was right six months ago may now be wrong.
Conclusion
LLM inference optimization is less about finding one magic trick and more about understanding where time and memory actually go. The KV cache, batching scheduler, and the prefill-decode split explain most performance differences between systems. Kernel work like FlashAttention and model-level moves like quantization or distillation add further gains, but only when measured against real traffic. Start with instrumentation, adopt continuous batching and paged caching, then layer on the rest as your data justifies it. The teams that win are the ones that measure honestly and tune for their own workload rather than someone else’s benchmark.
FAQ
What is LLM inference optimization?
It is the practice of making a trained language model cheaper and faster to run. It covers scheduling requests efficiently, managing the KV cache, reducing weight precision, and choosing the right hardware and serving framework. The goal is lower cost and latency without unacceptable quality loss.
Does speculative decoding change the model’s output?
No, not when implemented with proper rejection sampling. The large model verifies every proposed token, so the final distribution matches the target model exactly. Speedups vary with the draft model’s acceptance rate, which is why results differ so much between tasks. (Large language model)
Is 4-bit quantization safe for production?
It can be, but only with testing. Quality loss depends on the model, the quantization method, and the task. Teams should compare quantized outputs against full precision on a set of real production prompts before shipping, especially for reasoning-heavy or long-document work.
Why is the KV cache such a big deal?
Because it grows with both context length and batch size, and it competes with model weights for the same memory. On long-context workloads it often becomes the limiting factor for how many users a GPU can serve. Block-based management, as in PagedAttention, reduces waste and fragmentation.
What is the difference between prefill and decode?
Prefill processes the entire prompt in parallel and is compute-bound. Decode generates one token at a time and is memory-bandwidth-bound. Because they stress different resources, they need separate profiling and sometimes separate optimization strategies.
Do I need a specialized serving framework?
For most production workloads, yes. Frameworks such as vLLM, TensorRT-LLM, and Text Generation Inference bundle continuous batching, paged caching, and optimized kernels that are hard to replicate in-house. Just validate their published benchmarks against your own traffic before relying on the numbers.
A final note on evaluation: track goodput, the number of requests that meet your latency target per second, rather than raw throughput alone. A configuration that maximizes tokens per second can still violate tail latency if long requests crowd the batch. Goodput captures the trade-off honestly and keeps optimization aligned with user experience.
Also watch memory headroom. Pushing batch size or context limits to the edge leaves no room for traffic spikes, and a single oversized request can trigger preemption or out-of-memory errors that erase the gains you measured. Leaving ten to twenty percent headroom is usually cheaper than handling incidents.
None of these techniques is exotic anymore. The gap between average and excellent serving comes from disciplined measurement, a sensible ordering of changes, and the willingness to re-test assumptions as models and traffic evolve. Treat every optimization as a hypothesis, validate it against real prompts, and keep the ones that survive. That habit, more than any single trick, is what keeps inference costs under control.







