LLM Training and Inference Performance Optimization: A Practical Guide
This article breaks down practical performance optimization for large language models across the training and inference lifecycle. It maps mainstream architectures and their impact on optimization choices, then examines training bottlenecks in memory, compute throughput, and communication, along with inference techniques such as KV caching, continuous batching, quantization, and serving architecture. It closes with a three-layer evaluation and tuning loop covering accuracy, performance, and cost. Readers will find actionable methods and configuration patterns for building measurable, traceable performance governance.
1. Introduction: From Model Lineages to Engineering Practice
Large model technology has moved from research prototypes to production systems over the past few years. To understand the boundaries of engineering optimization, it helps first to see how model architectures have evolved. The industry often draws mainstream language models as an “evolution tree”: the vertical axis represents release time, while the horizontal axis branches out by base architecture. Most branches are built on the self-attention architecture, with only a few early branches using recurrent or convolutional structures.
By information flow, mainstream architectures fall into three categories:
- Encoder-only: characterized by bidirectional attention, strong at classification, extraction, retrieval, and other understanding tasks, usually with smaller parameter counts and lower inference cost.
- Decoder-only: autoregressive modeling with causal masking, now the de facto standard for generative large models and backed by the most mature training and inference engineering ecosystem.
- Encoder-decoder: combines input encoding with sequence generation, and still holds advantages in conditional generation tasks such as translation and summarization.
Solid and hollow markers in the diagram distinguish open-source from closed-source forms, and the statistics strip in the corner reflects the distribution of model counts across organizations. The direct takeaway for engineering practice is that architecture choice determines the feasible region for all downstream optimization. Decoder-only structures are highly optimizable at inference time thanks to mechanisms such as weight tying and KV caching, which is the core reason enterprises prioritize this route for deployment.
2. Training-Stage Performance Optimization: Three Bottlenecks and Their Remedies
Performance problems in training almost always trace back to three resource constraints: memory capacity, compute throughput, and communication bandwidth. The three are coupled, and optimizing any single point can shift the bottleneck elsewhere.
2.1 Memory Optimization: From Redundancy to Sharding
Training memory consists of model states (weights, gradients, optimizer states), activations, and temporary buffers. Under mixed-precision training, optimizer states are often the largest memory consumer. Common techniques include:
- Optimizer state sharding: partition optimizer states along the data-parallel dimension so each rank holds and updates only its own portion, with memory usage dropping roughly linearly as parallelism increases.
- Activation recomputation: skip saving all intermediate activations in the forward pass and recompute the needed segments during backpropagation, trading about 20%–30% extra compute for a significant memory reduction.
- Tensor/pipeline parallel partitioning: split single-layer operator matrices across GPUs by row or column, combined with micro-batch pipeline scheduling to hide bubbles.
Illustrative configuration logic (pseudocode):
# Parallelism strategy: data parallel + optimizer state sharding + activation recomputationparallel = ParallelConfig(tensor_parallel_size=8, # split single-layer operators across 8 GPUspipeline_parallel_size=2, # inter-layer pipeline partitioningdata_parallel_size=16, # replication along the data dimensionshard_optimizer_state=True, # shard optimizer statesrecompute_granularity="block",)
2.2 Compute Throughput: Mixed Precision and Operator Fusion
Numerical precision is the highest-leverage knob. BF16/FP16 delivers several times the throughput of FP32 on the same hardware, but it needs loss scaling or a high-precision master weight copy to avoid gradient underflow. Further techniques include:
- Operator fusion: fuse element-wise operators such as normalization, activation, and residual addition into adjacent matrix multiplications to cut memory reads and writes. In most decoder architectures, memory bandwidth rather than compute is the real bottleneck.
- Attention kernel optimization: use tiled computation and online normalization to avoid explicitly materializing the n×n attention matrix, reducing memory complexity from quadratic to linear.
- Communication-computation overlap: overlap gradient reduction with backward computation bucket by bucket so communication time is hidden behind computation.
2.3 Stability: An Unavoidable Concern in Large-Scale Training
Once parameter counts reach the hundreds of billions, training stability itself becomes an engineering problem. In practice, watch for cross-rank consistency checks on gradient norms, locating and rolling back loss spikes, asynchronous checkpoint persistence, and automatic isolation of faulty nodes with elastic rescheduling. It is advisable to route monitoring metrics (throughput, memory watermark, communication share, loss curves) into a unified logging and alerting system to build a traceable evidence chain for tuning.
3. Inference-Stage Performance Optimization: Rebalancing Latency and Throughput
Inference and training have different objective functions: training pursues tokens processed per unit time, while inference must constrain time to first token, per-token latency, and overall throughput at the same time.
3.1 KV Caching: The Core Memory-Latency Trade-off
Autoregressive generation requires caching historical key-value pairs, and its memory footprint grows linearly with sequence length and concurrency, often becoming the primary bottleneck for long-context serving. Common optimization directions:
- Multi-query/grouped-query attention: multiple query heads share one set of key-value heads, directly compressing cache size.
- Cache quantization: store the cache at lower precision, trading controllable accuracy loss for several times the capacity.
- Paged cache management: allocate on demand in fixed-size blocks to reduce fragmentation and reserved waste, improving concurrency capacity.
3.2 Batch Scheduling: From Static to Continuous
Static batching requires requests in the same batch to be equal in length, forcing short requests to wait for long ones and leaving GPUs underutilized. Continuous batching dynamically swaps requests in and out after each decoding step, fully interleaving requests of different lengths, with typically substantial throughput gains. Combined with disaggregated deployment of the prefill and decode stages, resources can be configured separately for their compute-intensive and bandwidth-intensive characteristics.
3.3 Quantization and Compression
Weight quantization (such as 8-bit/4-bit group quantization) mainly relieves bandwidth pressure from weight loading and pays off clearly in the decode stage; activation quantization requires careful handling of outliers. Structured pruning and low-rank decomposition can further reduce weight size, but their effects must be revalidated on the target task set to avoid losing usability in pursuit of speed.
3.4 Serving Architecture
In production, it is recommended to run model serving on a container platform with elastic scaling to handle traffic peaks and troughs; put a message queue at the request entry point for peak shaving and priority scheduling; store model files and checkpoints in object storage and use a cache layer to reduce cold-start overhead; and wire full-link metrics into monitoring and alerting to inform capacity planning.
4. The Evaluation and Tuning Loop
Any optimization must rest on trustworthy evaluation. A three-layer evaluation is recommended:
- Accuracy layer: compare output consistency before and after optimization on a fixed task set, with an acceptable deviation threshold.
- Performance layer: measure prefill throughput, decode throughput, time to first token, and tail latency (P99) separately, rather than looking only at averages.
- Cost layer: convert to resource cost per million tokens as the final basis for architecture selection.
Tuning should follow the order “locate first, then isolate single changes, then combine”: first use sampling and flame graphs to confirm whether the bottleneck is compute, bandwidth, or communication, then validate the benefit of each technique individually, and finally combine them and run regression tests. Avoid enabling multiple optimizations at once, which invalidates attribution.
5. Conclusion
The essence of large model engineering optimization is finding the optimal solution in a four-dimensional space formed by memory, compute, bandwidth, and cost. Architecture evolution determines the feasible region for optimization; the training stage centers on sharding and precision; the inference stage centers on cache management and scheduling; and running through it all is a quantifiable, traceable evaluation loop. The general methodology accumulated in Baidu AI Cloud’s related engineering practice shows that abstracting resources into standard categories such as compute, storage, network, and monitoring, and making data-driven decisions, is the path to sustainable performance governance.
