Inference Optimization is a pattern that reduces LLM serving costs and latency through techniques like quantization, batching, speculative decoding, and KV-cache management. These optimizations work at the infrastructure level without changing prompts or model weights.
At a Glance
- Problem: A naively served model handles one request at a time, takes seconds per response, and leaves GPUs mostly idle because decoding is bound by memory bandwidth. GPU utilization hovers near 30%, so you pay for hardware that mostly waits.
- Forces: Throughput versus per-request latency, since larger batches make each request wait longer; performance versus a simple stack that is easy to debug; parallelism across GPUs versus the communication overhead between them.
- Solution: Optimize below the application layer. Use continuous batching to keep the GPU saturated, paged KV cache management to fit more concurrent requests, tensor or pipeline parallelism for models that span GPUs, and Flash Attention to keep attention in SRAM.
- Consequences: Gains: higher throughput and better GPU utilization on the same hardware. Costs: more failure points, memory pressure that needs backpressure, tuning specific to your hardware, and ongoing maintenance as models and frameworks change.
What problem does Inference Optimization solve?
You have deployed a language model and it works, but it serves one request at a time, each response takes two to four seconds, and your GPU utilization hovers around 30%. You are paying for expensive hardware that spends most of its time waiting, while the request queue grows and users complain about latency.
Naive LLM inference wastes much of the hardware. During the autoregressive decoding phase, the model generates one token at a time. Each token requires a full forward pass through billions of parameters, but only produces a single output. The GPU's parallel units sit mostly idle because memory bandwidth, rather than compute, limits the work. You have a machine built to run thousands of operations at once, and you are feeding it one small task at a time.
Adding GPUs solves the throughput problem and ruins the unit economics. If each request already costs more than your revenue per query, doubling your hardware just doubles your losses. Get more out of the hardware you have before you buy more of it.
How does Inference Optimization work?
Inference optimization is a collection of techniques that make running a language model faster and cheaper. They work below the application layer: how tokens are processed, how memory is managed, and how the hardware is kept busy.
Continuous batching does more for throughput than any other optimization here. Traditional batching waits until it has collected N requests, processes them together, and returns all results. LLM requests vary widely in length, though. A short request finishes quickly but has to wait for the longest request in the batch before its slot is freed. Continuous batching (also called iteration-level batching) solves this by managing the batch at the token level rather than the request level. When a short request finishes, the next waiting request takes its slot immediately, so the GPU stays saturated and no slot sits idle waiting for a long generation to complete. This alone can improve throughput by 5-10x compared to naive sequential processing.
KV cache optimization goes after the memory bottleneck. During generation, the model stores key-value states for every token it has processed. These states are reused when generating subsequent tokens so the model does not have to recompute attention over the entire sequence for each new token. These caches grow linearly with sequence length and batch size, and they consume GPU memory that could otherwise be used for larger batches. PagedAttention, the technique behind vLLM, manages KV cache memory like an operating system manages virtual memory. It allocates cache in non-contiguous pages, cutting the fragmentation and over-reservation that leave 60-80% of KV cache memory unused in earlier serving systems. You can then fit more concurrent requests in the same GPU memory.
Model parallelism distributes the model across multiple GPUs when it does not fit in one. Tensor parallelism splits individual layers across GPUs, allowing each forward pass to use all available devices. Pipeline parallelism assigns different layers to different GPUs, creating a pipeline where multiple requests are processed at different stages simultaneously. Which one you pick depends on your hardware topology and latency requirements: tensor parallelism reduces per-request latency, while pipeline parallelism maximizes aggregate throughput.
Flash Attention reimplements the attention computation to be aware of the GPU memory hierarchy. Standard attention computation creates large intermediate matrices that spill out of fast on-chip SRAM into slower GPU HBM. Flash Attention tiles the computation so that intermediate results stay in SRAM, reducing memory reads and writes. Attention runs faster and uses less memory, so generation speeds up and the model can handle longer sequences.
When should you use Inference Optimization?
These optimizations matter when you are running models at scale and either cost or latency is a pressing concern. If you are making a handful of API calls per day to a hosted provider, none of this applies, because the provider already does this work.
Inference optimization matters once you self-host models. When you pay for GPU time directly, every percentage point of utilization saves money. It also matters when you are hitting latency targets. If your application needs sub-second responses and the model takes two seconds, no amount of prompt engineering will fix that. You need the inference itself to be faster.
Continuous batching should be your first optimization. It gives the largest improvement for the least effort, because mature frameworks like vLLM, TGI (Text Generation Inference), and TensorRT-LLM implement it out of the box. Deploying your model through one of these frameworks instead of a naive serving script is often the only optimization you need.
When not to use it: If you call a hosted provider's API, the provider already handles serving, so your levers are Prompt Caching, Model Router, and smaller models from Small Language Models. At modest self-hosted volume, a mature framework with continuous batching is usually enough, and hand-tuned parallelism or custom cache management adds failure points without a matching payoff. On hardware with slow links between GPUs, skip model parallelism and use a quantized or smaller model that fits on one GPU.
Worked Example: Cost and Latency
A self-hosted model serves 100,000 requests a day, each producing 200 output tokens, on GPUs at an assumed $2.50 per GPU-hour.
| Setup | Aggregate throughput | Per-request speed | GPU-hours per 1,000 requests | Cost per 1,000 requests | Latency per request |
|---|---|---|---|---|---|
| Naive serving, one request at a time | 80 tokens/s | 80 tokens/s | 0.69 | $1.74 | 3.0 s, plus queueing |
| Continuous batching, 16 concurrent streams | 640 tokens/s | 40 tokens/s | 0.09 | $0.22 | 5.5 s |
One thousand requests produce 200,000 output tokens. At an assumed single-stream speed of 80 tokens per second that is 2,500 s, or 0.69 GPU-hours, so $1.74; with 0.5 s to first token each request takes 3.0 s. Continuous batching at 8x (inside the 5 to 10x range above) gives 640 tokens per second: 312.5 s, 0.087 GPU-hours, $0.22. One naive GPU serves about 34,560 requests a day, so 100,000 a day needs three GPUs ($180 a day); one batched GPU serves about 276,000, so a single GPU ($60 a day) covers the load. Each batched stream runs at 40 tokens per second, so a single request takes 0.5 s + 200 / 40 s = 5.5 s.
Batching cuts the cost per request by 8x when every GPU is fully loaded, but whole-GPU billing makes the saving 3x at this page's 100,000 requests a day ($180 against $60); at low volume the GPU sits idle either way and the saving does not materialize, and if per-request latency is the hard limit, smaller batches give back some throughput for speed.
What are the common pitfalls?
Optimizing inference is systems engineering, with the usual failure modes. Aggressive batching increases memory pressure. If your batch size exceeds available GPU memory, requests start failing. You need monitoring and backpressure mechanisms to prevent over-subscription.
KV cache memory management adds complexity. PagedAttention is well-tested in frameworks like vLLM, but custom implementations or edge cases (very long sequences, unusual model architectures) can trigger bugs that produce incorrect outputs silently. Always validate outputs after changing your inference stack.
Model parallelism adds communication overhead between GPUs. The speed of the interconnect (NVLink, PCIe, InfiniBand) starts to dominate. On hardware with slow inter-GPU communication, the overhead of parallelism can exceed its benefits, making a single larger GPU a better choice than multiple smaller ones.
The optimization frameworks themselves move fast. Breaking changes, version incompatibilities with specific model architectures, and subtle differences in numerical behavior between frameworks are common. Treat your inference stack as production infrastructure that needs testing, monitoring, and version management.
What are the trade-offs?
Complexity increases with each optimization layer. A model served through a basic Python script is easy to debug. A model served through vLLM with tensor parallelism, PagedAttention, and CUDA graph optimization has many more potential failure points. You are trading simplicity for performance.
These optimizations are hardware-specific. A configuration that works well on A100 GPUs may perform differently on H100s or on AMD hardware. Benchmark on the hardware you will deploy on. Published benchmark numbers from other setups are directional at best.
Some optimizations trade latency for throughput or vice versa. Larger batch sizes improve throughput but increase the time any individual request waits. Model parallelism strategies have different latency and throughput profiles. Pick based on which metric matters more for your application.
The effort to maintain an optimized inference stack is ongoing. New model architectures may not work with existing optimizations. Framework updates need testing and hardware upgrades need re-tuning, so plan for the work to continue after the initial setup.
Goes Well With
Small Language Models reduce the baseline resource requirements, making all inference optimizations more effective. Optimizing a 7B model's inference is easier and cheaper than optimizing a 70B model. The smaller memory footprint leaves more room for larger batches and longer sequences.
Prompt Caching at the server level (prefix caching) is itself an inference optimization, and it compounds with the techniques described here. Reusing KV cache states across requests that share a prefix means less computation and less memory pressure per request.
Model Router determines which requests need a more capable model and which a lightweight one can handle. Inference optimization makes whichever model handles a request run efficiently. The router cuts how many requests reach the expensive model, and inference optimization cuts the cost of each one that does.