LLM Inference Performance Optimization: A Complete Guide
This guide explains how to optimize large language model inference by first measuring bottlenecks, then addressing the distinct resource profiles of the prefill and decode stages. It covers reducing data movement through quantization, KV cache compression, pruning and sparse attention, improving execution efficiency with operator fusion, parallelism and continuous batching, and a recommended implementation order with quality and performance regression gates. Readers will gain a practical map for diagnosing and resolving common production inference performance issues.
1. Locate the Bottleneck First: No Guesswork Optimization
The most common failure mode in inference optimization is blindly tuning parameters without quantifying where the bottleneck actually lies. Training and inference have very different resource profiles: training is constrained by floating-point compute and gradient communication, while the limiting factor in inference shifts dramatically with the stage, batch size, and sequence length. So the first step is always to measure, not to swap out operators.
Start by establishing three categories of baseline metrics: throughput (tokens/s or requests/s), latency distribution (P50/P95 of time-to-first-token and per-token latency), and resource utilization (compute utilization and memory bandwidth utilization). Only when latency stays nearly flat as batch size grows while bandwidth utilization remains close to the ceiling can you conclude the workload is bandwidth-bound. If increasing the batch size yields a near-linear throughput gain, compute still has headroom, and you should prioritize batching and concurrency scheduling.
2. Resource Characteristics of the Two Stages: Prefill and Decode
LLM inference can be split into two stages with fundamentally different characteristics.
The prefill stage processes the entire input prompt at once. All input tokens can be computed in parallel, the matrices are large, and the stage is typically compute-bound. Its metric is time-to-first-token, which directly determines the “responsiveness” users perceive.
The decode stage generates tokens autoregressively, one at a time. Each step must read the key-value cache for all historical context and pass through the model parameters again, so the matrices degenerate into tall, skinny shapes and the stage is typically memory-bandwidth-bound. Its metric is per-token latency, which determines the “output speed.”
A counterintuitive but critical conclusion is that in autoregressive generation, the dominant cost is often not floating-point computation but data movement. Take a common high-performance accelerator as an example: its half-precision compute can reach the hundreds of TFLOPS range, while its memory bandwidth is only on the order of a few TB/s. A 7B-parameter model in half precision occupies roughly 14GB of memory, and generating each token requires reading that entire set of parameters once. At a bandwidth of a few TB/s, parameter reading alone adds several milliseconds of overhead, corresponding to a theoretical ceiling of hundreds of tokens per second. Add KV cache reads, sampling, and scheduling overhead, and the measured result will be lower.
This is the core tension of inference optimization: compute units spend much of their time waiting for data. As a result, nearly all optimization techniques fall into two categories—reducing the amount of data that must be moved, and improving movement efficiency while overlapping computation with data transfer.
3. Reducing Data Movement: Compression and Sparsification
Quantization offers the most direct gains. Lowering weights and activations from half precision to 8-bit or below can proportionally compress parameter reads in theory. Schemes that quantize only the weights while keeping activations at higher precision are simple to implement and low-risk, making them a good first step. It is important to note that quantization introduces accuracy loss, so it must be judged against business-acceptable quality evaluations rather than compression ratio alone.
KV cache compression targets the dynamic growth during the decode stage. Cache size is proportional to batch size, sequence length, number of layers, and number of attention heads, and in long-context scenarios it often becomes a dual source of memory and bandwidth pressure. Common approaches include sharing or reusing key-values across adjacent queries to compress the head dimension, evicting or merging historical entries by importance, and offloading inactive cache to host memory or a slower storage tier and swapping it back when needed.
Pruning and sparse attention are more aggressive directions. Structured pruning genuinely reduces parameter count and memory access, while unstructured pruning depends on hardware support for sparse patterns and yields unstable gains. Sparse or local-window attention can reduce the attention cost of long sequences but affects the modeling of long-range dependencies, so it must be validated per task.
4. Improving Movement and Execution Efficiency: Fusion, Parallelism, and Scheduling
Operator fusion merges adjacent element-wise operations, normalization, activations, and matrix multiplications, reducing round-trip reads and writes of intermediate tensors and the number of kernel launches. It is a low-risk, reliable gain.
Parallelism strategy determines multi-GPU scaling efficiency. Tensor parallelism splits a single layer’s parameters across GPUs, reducing per-GPU parameter reads but introducing high-frequency communication. Pipeline parallelism splits by layer, with less communication but pipeline bubbles. Context parallelism splits the attention computation for extremely long sequences. In practice these are usually combined, with communication overlapped with computation as much as possible.
Batching and scheduling are key to improving throughput. Static batching wastes capacity due to differences in sub-request lengths, while continuous batching dynamically swaps requests in and out at the token level, significantly improving utilization. Combined with paged cache management to reduce fragmentation and prefix reuse so that an identical system prompt is computed only once, this can often deliver multiplicative throughput gains without changing the model.
The core loop of continuous batching can be expressed with the following illustrative pseudocode:
while not finished:batch = scheduler.pop_ready_requests(max_tokens=BUDGET)logits = model.forward(batch) # Mixed scheduling of prefill and decodefor req, token in zip(batch, sample(logits)):kv_cache.append(req, token) # Paged writes to reduce fragmentationif token.is_eos: finished.add(req)else: scheduler.push_back(req)if kv_cache.usage() > WATERMARK:scheduler.evict_or_offload() # Evict cold cache, keep hot cache
5. Implementation Order and General Cloud Capabilities
The recommended implementation order is: first measure and determine the bottleneck type, then adopt continuous batching and cache reuse to gain throughput, then introduce weight quantization to compress memory access, then apply operator fusion and parallel partitioning, and finally add cache compression and offloading strategies for long context. Each step should have dual gates for quality regression and performance regression.
When deploying on the cloud, you can build a closed loop using general-purpose capabilities: use a container platform to host inference services and elastic scaling, use object storage to save models and cache snapshots, use monitoring and alerting to track latency percentiles and bandwidth utilization, and use a logging service to accumulate slow-request samples for later review. Baidu AI Cloud provides standardized infrastructure support for these general capabilities, but specific choices should still be based on measured data.
In summary, the methodology of inference optimization is not mysterious: first quantify the bottleneck, then determine the constrained resource, and then verify item by item along two main lines—“move less data” and “move faster and overlap movement with computation.” Once you have drawn this map clearly, most production performance problems can be matched to a concrete lever.
