LLM Inference Performance Optimization: A Practical Guide

    This guide explains how to optimize large language model inference by first understanding its two distinct phases—prefill and decode—and their different resource profiles. It covers why memory bandwidth, not compute, is usually the bottleneck, then walks through three optimization paths: reducing weight movement, compressing the KV cache, and increasing parallelism. It closes with a recommended rollout order and measurement methodology for achieving stable, reproducible latency and throughput gains.

    1. Understand the Workload First: Prefill and Decode Have Completely Different Resource Profiles

    LLM inference is not a single, uniform forward pass. It is a sequence of two phases with very different resource characteristics. Understanding this is the prerequisite for all optimization work.

    Prefill phase: The entire user prompt is fed into the model at once, computing the hidden states for all input tokens in parallel and producing the key-value cache that later steps reuse. Because there are no generation-order dependencies among input tokens, the matrix multiplications are large and arithmetic intensity is high. This phase is typically compute-bound.

    Decode phase: Tokens are generated autoregressively, one at a time. For each new token, its query vector must attend to the keys and values of all previous tokens, and pass through all network weights. Each step processes only one (or very few) tokens, so the matrices become tall and skinny, arithmetic intensity is extremely low, and this phase is typically memory-bandwidth-bound.

    A common engineering mistake is to measure service performance with a single average metric such as overall tokens/s. In reality, time-to-first-token is determined mainly by prefill, while inter-token latency is determined mainly by decode. The two have almost no overlap in optimization techniques and must be measured and tuned separately.

    2. The Core Conflict: GPUs Spend Most of Their Time Waiting for Data

    A counterintuitive but critical fact: most inference time is spent moving data, not computing.

    Consider a typical single-card spec as a rough order-of-magnitude estimate. A certain class of data-center accelerator delivers hundreds of TFLOPS in half precision, while memory bandwidth is only on the order of a few TB/s—a gap of two to three orders of magnitude. A 7-billion-parameter model occupies about 14GB of memory in half precision. During decode, generating each token theoretically requires reading all 14GB of weights. At 2TB/s bandwidth, weight reading alone takes about 7ms, capping throughput at roughly 140 tokens/s—and this ceiling cannot be exceeded even with infinite compute. Add KV cache reads, kernel launch overhead, and memory allocation, and measured throughput is lower still.

    The Roofline model describes this more rigorously: the x-axis is arithmetic intensity (floating-point operations per byte moved), and the y-axis is achievable performance. Decode sits on the left of the slope, where performance is determined solely by bandwidth; prefill sits on the right of the plateau, where performance is capped by compute. The first step of optimization is always to determine which region the workload falls into, rather than blindly applying techniques.

    1. # First-order estimate: check whether decode is bandwidth-locked
    2. def decode_upper_bound(params_bytes, kv_bytes, bw_bytes_s, flops_per_token, peak_flops):
    3. traffic = params_bytes + kv_bytes # bytes that must be moved each step
    4. t_mem = traffic / bw_bytes_s # lower bound set by bandwidth
    5. t_flops = flops_per_token / peak_flops # lower bound set by compute
    6. return max(t_mem, t_flops) # Roofline: take the larger of the two

    The value of this sketch code is this: if t_mem is much larger than t_flops, then any “optimization” that does not reduce the amount of data moved will yield no benefit.

    3. Optimization Path 1: Reduce Weight Movement

    Quantization offers the most direct gains. Lowering weights from half precision to 8-bit or below linearly reduces the amount of data moved in theory. In practice, dequantization overhead and accuracy loss must be considered, so a common approach is to quantize only the weights to low bit-widths while keeping activations at higher precision, and to control quantization granularity at the channel or group level to suppress the impact of outliers.

    Pruning and sparsification reduce the parameter count through structured trimming, so the number of bytes to move genuinely decreases. Unstructured sparsity offers high theoretical compression but is hard to translate into real speedup on general-purpose hardware, so structured approaches are generally preferred in engineering to obtain real throughput.

    Low-rank decomposition and weight sharing compress size from another angle: approximating a large matrix with two smaller ones, or sharing parameters across layers, reducing resident data with near-lossless approximation.

    4. Optimization Path 2: Compress the KV Cache

    As context grows longer, the KV cache expands rapidly and can even exceed the weights themselves, becoming a dual source of pressure on bandwidth and memory. Common mitigation techniques include:

    • Multi-query / grouped-query attention: letting multiple query heads share the same set of key-value heads, directly reducing cache size;
    • Windowed and streaming attention: keeping full keys and values only for recent tokens, while summarizing or evicting distant ones;
    • Cache quantization and paged management: storing the cache at low bit-width and using a paged memory pool to reduce fragmentation and reserved waste;
    • Prefix reuse: computing common prefixes such as system prompts and long documents only once and sharing them across requests.

    Prefix reuse is often an underestimated optimization: when many requests share the same long instruction, it reduces both time-to-first-token and repeated computation cost.

    5. Optimization Path 3: Increase Parallelism to Amortize Bandwidth

    Since the per-step data movement is hard to avoid, make a single move serve more requests. Continuous batching allows new requests to join at any decode step and completed requests to exit immediately, avoiding the idle waiting of static batching. Combined with chunked prefill, which splits long prompts into chunks and schedules them together with decode requests, latency spikes can be significantly flattened.

    When single-machine resources are insufficient, introduce parallelism strategies: tensor parallelism splits the weights of a single layer to reduce per-card movement, pipeline parallelism splits by layer to reduce per-card residency, and expert parallelism applies to sparse expert structures. Increasing parallelism introduces communication overhead and must match the network topology—avoid parallelizing for its own sake.

    6. Rollout Order and Measurement Methodology

    Proceed in the order “measure first, characterize second, act third”:

    1. Separately collect time-to-first-token, inter-token latency, throughput, memory usage, and cache hit rate;
    2. Use Roofline estimation to determine whether the bottleneck is compute or bandwidth;
    3. Prioritize optimizations that do not change numerical semantics (batch scheduling, paged cache, prefix reuse);
    4. Then introduce optimizations that change numerical results (quantization, pruning), with accuracy regression evaluation;
    5. Finally, adjust the parallelism topology and deployment specs.

    In cloud practice, you can rely on container platforms to host inference services, object storage to distribute model weights, and monitoring, alerting, and logging services to observe latency percentiles and memory levels. General-purpose capabilities from cloud providers such as Baidu AI Cloud can also be combined along these lines.

    7. Conclusion

    The essence of LLM inference optimization is subtraction and multiplication around the “data movement” bottleneck: quantization, pruning, and cache compression do subtraction, while batching and parallelism do multiplication. First locate the phase and bottleneck, then choose the corresponding technique—only then can you avoid ineffective tuning and achieve stable, reproducible throughput and latency gains.