LLM Inference Performance Optimization: Core Logic Explained
This article breaks down why large language model inference stays slow even when compute capacity is not the bottleneck. It separates inference into the compute-bound prefill stage and the memory-bound decode stage, derives a bandwidth-based lower bound on token generation speed, and organizes common optimization techniques into two main lines: moving data more efficiently and overlapping data movement with computation. Readers will also find a staged tuning workflow and a list of frequent pitfalls.
1. The Starting Point: Slow Inference Is Usually Not a Compute Shortage
Many teams hit the same wall when deploying large language models: GPU compute headroom is still available, yet throughput refuses to climb, and adding capacity barely improves latency. Explaining this requires splitting inference into two stages with fundamentally different characteristics.
1.1 Prefill: The Whole Prompt Processed in One Parallel Pass
The prefill stage feeds the user’s entire prompt into the model at once, computes the hidden states for all input tokens, and writes each layer’s Key/Value into the cache along the way. Because tokens inside the input sequence already have known relationships with one another, this step expands into large-scale matrix multiplications and additions with a high degree of parallelism. It is a classic compute-intensive workload. Compute utilization is typically high here, and the bottleneck sits closer to floating-point throughput.
1.2 Decode: One Token per Step
Decode works the opposite way, generating a single new token per step. The new token must attend to all preceding history tokens, but the reusable portion already lives in the cache, so the vectors that actually need fresh computation are tiny. Matrix multiplications degenerate into matrix-vector form, arithmetic intensity drops sharply, and the workload shifts from compute-intensive to memory-intensive.
1.3 A Quantitative Intuition: Bandwidth Sets the Speed Ceiling
Take a model of roughly 7 billion parameters. At half precision, the weights occupy about 14GB. Every generated token theoretically requires reading that entire set of weights. With memory bandwidth on the order of 2TB/s, moving the weights alone takes about 7 milliseconds, which corresponds to a ceiling of roughly 140 tokens per second. This estimate deliberately ignores other overheads, so it is an optimistic figure. A real system must additionally read the ever-growing key-value cache, run sampling and post-processing, and absorb kernel launch and synchronization costs, so measured speed is necessarily lower.
The conclusion is clear: even with unlimited compute, the memory path is a hard constraint. The central tension in inference optimization is that the hardware spends most of its time waiting for data rather than computing on data.
2. A Unified Optimization Framework: Two Main Lines
Following that tension, nearly every inference optimization technique falls into one of two categories.
- Line one: move data more efficiently. Reduce the number of bytes that must be moved and increase how effectively bytes are moved per unit time. Techniques include quantization and low-bit representations, rearranging the layout of weights and caches, cache compression and sparsification, and more compact batch organization.
- Line two: overlap computation with data movement. Use concurrency to hide memory latency. Techniques include continuous batching and request scheduling, operator fusion to avoid materializing intermediate tensors, pipeline parallelism with computation-communication overlap, and multi-stream concurrency with graph-level execution optimization.
To judge whether an optimization is worth the investment, just ask which line it falls on and which portion of the bytes it removes.
3. Line One: Reduce and Accelerate Data Movement
3.1 Low-Bit Quantization
Dropping weights from half precision to 8 bits or lower compresses the movement volume proportionally, and is the most direct source of gains. In practice, low-bit representation is usually applied to weights only, while activations stay at higher precision to control accuracy loss. Keeping high precision for sensitive modules such as attention and normalization is a common compromise. Note that if the kernel implementation is poor after quantization, dequantization overhead can eat the gains, so end-to-end measurement is mandatory.
3.2 Key-Value Cache Compression and Reuse
Cache size grows linearly with sequence length and concurrency, and in long-context scenarios it can even exceed the weights themselves. Viable directions include: letting adjacent requests share cached results for an identical prefix to avoid repeated prefill; storing historical cache at low bit width or evicting it by importance; and reducing the number of cache heads under multi-query or grouped-query attention. Prefix reuse pays off especially well for workloads with a fixed system prompt or long-document question answering.
3.3 Memory Access Coalescing and Layout Optimization
Whether memory accesses are contiguous and coalesced directly determines whether bandwidth can be saturated. Rearranging weights into the block sizes the kernel requires, cutting repeated reads and writes of intermediate tensors, and avoiding unnecessary type conversions and copies are all gains available without touching the algorithm.
The decision logic can be sketched as pseudocode:
# Estimate the memory-movement lower bound for a single tokenweight_bytes = params * bytes_per_param # bytes moved for weightscache_bytes = 2 * layers * kv_heads * head_dim \* seq_len * batch * bytes_per_kv # bytes moved for KV cachelower_bound_ms = (weight_bytes + cache_bytes) / bandwidthprint("Theoretical ceiling tokens/s ≈", 1000 / lower_bound_ms)
Writing the cache term explicitly into the estimate explains why speed degrades faster than expected under long context and high concurrency.
4. Line Two: Overlap Data Movement with Computation
4.1 Continuous Batching and Scheduling
Static batching requires all requests in a batch to start and finish together, so short requests must wait for long ones and resources are wasted heavily. Continuous batching swaps requests in and out dynamically at token or iteration granularity, letting a single weight movement serve multiple requests under high concurrency and amortizing the per-request memory cost. This is one of the most significant levers for throughput, but it introduces queuing and fairness scheduling problems, so length limits and priority policies are needed.
4.2 Operator Fusion
Fusion merges multiple small operators into a single execution, avoiding repeated trips of intermediate results to and from memory. Element-wise operations such as normalization, activation, and residual addition are especially suited to fusion. Inside attention implementations, combining scoring, masking, softmax, and the weighted sum also cuts read and write counts substantially.
4.3 Parallelism and Communication Overlap
When the model or workload exceeds what a single GPU can handle, partitioning schemes such as tensor parallelism and pipeline parallelism come in. Here the communication volume is itself data movement, so it must overlap with computation and stay within the high-speed interconnect domain as much as possible; otherwise the added synchronization wait cancels out the parallel gains.
4.4 Graph-Level Execution and Static Shapes Within a Batch
Turning dynamic control flow into a static graph, fixing shapes, and reusing execution plans reduces kernel launch and scheduling overhead. In short-output, low-latency scenarios, this fixed cost is often larger than people assume.
5. A Practical Tuning Order by Stage
- Measure before optimizing: separately track prefill time, per-token decode time, cache hit rate, and memory usage to locate the real bottleneck instead of tuning parameters on intuition.
- Address prefill bottlenecks: prioritize prefix cache reuse, then chunked prefill to smooth time-to-first-token, and retrieval-style trimming for extremely long inputs when necessary.
- Address decode bottlenecks: adopt continuous batching and low-bit weights first, then evaluate cache compression; when single-request latency is sensitive, reduce in-batch concurrency in exchange for stable latency.
- Address capacity and cost: plan memory based on the context-length distribution and concurrency peaks, wire logs, monitoring, and alerting into a unified system, and make scaling decisions from long-term metrics rather than a single load test.
- Establish a regression baseline: run a fixed workload and a fixed accuracy evaluation on every change so throughput gains do not come at the price of quality.
6. Common Pitfalls
- Watching compute utilization only, while ignoring bandwidth and cache hit rate, which sends optimization in the wrong direction.
- Extrapolating real throughput from theoretical peak, ignoring sampling, post-processing, and scheduling overhead.
- Optimizing single-request latency only, and missing tail-latency degradation caused by queuing under high concurrency.
- Skipping end-to-end evaluation after quantization and mistaking kernel dequantization cost for net gain.
7. Conclusion
The essence of LLM inference optimization is fighting for the efficiency of every byte and the reuse of every movement within a memory-bound reality. Work out the two-stage characteristics and the bandwidth lower bound first, then verify item by item along the two lines of reducing movement and overlapping movement, backed by solid monitoring and baseline regression. That is how you find the balance point between latency, throughput, and cost that fits your own workload. For cloud deployments, general capabilities such as container platforms, object storage, log services, and monitoring and alerting can support elastic scaling and full-chain observability, keeping optimization results sustainable and measurable.
