LLM Inference Performance Optimization: A Practical Guide
This guide explains how to optimize large language model inference by first identifying bottlenecks and understanding the distinct Prefill and Decode phases. It covers two main optimization paths—reducing the data that must be moved through quantization, sparsity, KV cache compression, and speculative decoding, and improving data movement efficiency through operator fusion, batching, parallelism, and cache reuse—along with a recommended rollout order and the key metrics to track.
1. Find the Bottleneck First: Don’t Optimize Blindly
The first step in performance optimization is always measurement, not applying techniques. Training workloads are dominated by large-scale matrix multiplications and gradient computation, so compute utilization is usually the main metric to watch. Inference has a completely different load profile. If you tune parameters without accounting for these stage-specific characteristics, you can easily end up improving a metric without improving perceived latency.
1.1 The Two Phases of Inference
Prefill phase: The entire input prompt is fed into the model at once, computing the hidden states for all input positions in parallel and generating the initial key-value (KV) cache. Because all positions are computed simultaneously, the matrices are large and highly parallel, making this a compute-intensive workload that easily saturates compute utilization.
Decode phase: Output tokens are generated one at a time. Each new token requires attention computation against all existing context. Only one position is processed per step, so the matrix degenerates into a tall, skinny vector-matrix form, making this a memory-bandwidth-intensive workload.
The two phases also affect latency metrics differently: Prefill determines time to first token, while Decode determines the smoothness of subsequent output. They are often lumped into a single monitoring view, which makes problem diagnosis difficult. It is better to instrument and measure them separately.
1.2 The Counterintuitive Fact: Time Is Spent Moving Data
Take a mainstream data-center-grade accelerator as an example. Half-precision compute can reach the order of hundreds of trillions of floating-point operations per second, while memory bandwidth is typically on the order of several TB/s—a gap of two to three orders of magnitude. A 7-billion-parameter model occupies roughly 14GB of memory in half precision. In theory, every generated token requires reading all parameters once: at 2TB/s bandwidth, a single read takes about 7 milliseconds, corresponding to a ceiling of roughly 140 tokens per second.
This ceiling is unrelated to compute; even infinitely fast compute units cannot break through it. Once you add KV cache reads, kernel launch overhead, sampling, and scheduling costs, measured throughput is even lower. This leads to the core tension in inference optimization: the accelerator spends most of its time waiting for data, not computing on it.
A useful self-check metric is arithmetic intensity (the number of floating-point operations per byte of data). Decode has very low arithmetic intensity and is bandwidth-bound; only when the batch is large enough to amortize the parameter-reading cost across many requests can it become compute-bound. This criterion drives all the trade-offs in the technology choices that follow.
2. Optimization Path One: Reduce the Data That Needs to Be Moved
2.1 Quantization
Lowering the bit width of weights and activations from half precision directly cuts the read volume proportionally, while also reducing memory footprint and increasing the batch size you can fit. In practice, quantizing only the weights usually yields stable gains; activation quantization requires calibration and outlier handling. For precision-sensitive scenarios, a mixed-precision strategy can keep certain layers at higher precision. The key to adoption is to quantize on an offline evaluation set first, then validate end-to-end results, rather than looking only at single-operator speed.
2.2 Sparsity and Pruning
Structured pruning genuinely reduces parameter count and delivers real speedup, whereas unstructured sparsity depends on hardware and kernel support and otherwise fails to translate into gains. When choosing an approach, confirm whether the target hardware has native support for sparse computation; otherwise the theoretical compression ratio cannot be realized as throughput improvement.
2.3 KV Cache Compression
The longer the context, the more prominent the KV cache read cost becomes, to the point where it can exceed weight reads. Common approaches include: limiting the cache window, evicting historical positions by attention importance, sharing keys and values across layers, and offloading cold data to host memory or external media such as object storage. Compression sacrifices some long-range memory capability, so regression testing with long-text tasks is needed.
2.4 Speculative Decoding and Parallel Sampling
A small draft model guesses several tokens in a row, then the large model verifies them all at once; if accepted, it advances multiple steps at once. This does not reduce total computation, but it merges multiple bandwidth-bound serial reads into one, bypassing the bandwidth wall. The draft hit rate determines the payoff, so monitor the accepted length and dynamically adjust the draft length.
3. Optimization Path Two: Improve Movement Efficiency and Overlap Computation
3.1 Operator Fusion
Element-wise operations such as attention, normalization, and activation each read and write memory separately, producing large amounts of intermediate-result round trips. After fusion, intermediate results stay in on-chip cache, reducing both memory access and the number of kernel launches. This is the most reliable foundational optimization.
3.2 Batching and Scheduling
Continuous batching lets new requests join at any point during generation and leave as soon as they finish, avoiding waiting for the longest request in the whole batch and significantly improving device utilization. Combined with chunked prefill, which splits a long prompt into small chunks interleaved with decode steps, it can alleviate the tail latency caused by long inputs blocking short requests.
3.3 Parallelism Strategies
When a single card cannot hold the model, tensor parallelism splits a single layer’s computation, pipeline parallelism splits by layer, and expert parallelism splits by parameters; they are usually combined. Parallelism introduces communication overhead, so communication should overlap with computation, and the partitioning scheme should match interconnect bandwidth to avoid frequent cross-node transfers.
3.4 Cache Reuse
Reusing the already-computed KV cache for identical prefixes (system prompts, few-shot examples, long documents) skips repeated prefill and is one of the highest-payoff techniques for scenarios with long, fixed prefixes. The hit rate depends on the request routing strategy, so session-affinity scheduling based on prefix consistency is needed.
4. Rollout Order and Measurement
Proceed in the order of “measure—low-risk, high-reward—structural changes”: first measure Prefill and Decode time separately, memory and bandwidth usage, batch size, and cache hit rate; then try operator fusion, continuous batching, prefix caching, and quantization in turn; finally evaluate larger changes such as parallel partitioning and cache compression. At each step, compare four metrics against a fixed evaluation set—time to first token, single-request latency, overall throughput, and output quality—to avoid a single-point improvement masking an overall regression.
When implementing in the cloud, you can use a container platform to host inference services, monitoring and alerting to track latency and utilization, a logging service to retain per-phase timing, and object storage to accumulate model and cache data, turning the optimization process into a sustainable engineering loop of continuous iteration.
