LLM Training and Inference Performance Optimization: Algorithms and Practice
This article examines performance optimization for large language model training and inference, from model evolution and inference scheduling to memory management, Roofline-based bottleneck analysis, distributed training parallelism, and system-level trade-offs. It explains how to identify memory-bound versus compute-bound workloads and how to apply practical techniques such as continuous batching, KV-cache optimization, mixed precision, and ZeRO sharding.
1. From Language Models to Large Models
A language model is fundamentally a machine learning method that predicts the next token from natural text. Its core assumption is that statistical language patterns can be learned automatically from large-scale corpora. Natural language processing has evolved through three broad phases: rule-driven methods, the rise of statistical methods, and the emergence of neural networks. Early work relied mainly on manually written grammar rules. Later, statistical modeling methods such as hidden Markov models and conditional random fields became mainstream. Neural networks then gradually replaced handcrafted features with end-to-end learning.
After the Transformer architecture was introduced, the pretraining paradigm produced three major technical branches. Encoder-only architectures are well suited to understanding tasks and learn bidirectional contextual representations through masked language modeling. Decoder-only architectures focus on generation tasks and predict tokens autoregressively one at a time. Encoder-decoder architectures combine understanding and generation and are suitable for sequence-to-sequence tasks such as translation and summarization. The large number of general-purpose open-source and closed-source models shows that “pretraining + instruction tuning + human feedback alignment” has become a widely accepted technical route. Large models generally refer to neural network language models with hundreds of millions of parameters or more. Their capability emergence is closely related to scale expansion, which is why engineering efficiency in training and inference has become critical to deployment success.
2. Inference-Side Challenges and Optimization Techniques
2.1 Continuous Batching
Traditional static batching requires all requests in a batch to finish generation before compute resources can be released. Short requests must wait for long requests, resulting in low GPU utilization. Continuous batching dynamically schedules at each decoding step: a sequence exits the batch as soon as it finishes generation, and new requests join immediately, keeping batch occupancy high. In practice, this is often combined with iteration-level scheduling and preemption strategies. It can significantly improve throughput and reduce queueing latency, and it is currently a mainstream scheduling approach for inference services.
2.2 Chunked Attention and Memory Management
The KV cache used in autoregressive generation is a major source of memory pressure. Its memory footprint can be estimated as: layers × 2 (K and V) × heads × head dimension × sequence length × bytes per data type. For a medium-scale model in a long-context scenario, the KV cache may occupy several GB or even tens of GB. Common optimization methods include:
- Paged memory management: split the KV cache into fixed-size blocks and allocate them on demand, eliminating internal fragmentation.
- Chunked/sliding-window attention: limit the visible range of attention, reducing the computation and memory of long sequences from quadratic to linear or near-linear.
- Quantization and compression: store the KV cache in low-bit formats such as FP8/INT8 to compress memory while keeping precision acceptable.
- Prefix cache sharing: compute common prefixes such as identical system prompts only once and reuse them across multiple requests.
2.3 Compute Efficiency Optimization
The decoding phase is a typical memory-bound scenario. Each step generates small matrix operations and reads weights frequently. Useful techniques include operator fusion to reduce intermediate result reads and writes; speculative decoding, which uses a small model to draft tokens and a large model to verify them in parallel, generating multiple tokens per step; kernel-level optimization; and GEMM tuning for batch dimensions. To determine whether an optimization is effective, it is necessary to use performance analysis models to locate the bottleneck.
3. Roofline Model and Bottleneck Identification
The Roofline model plots the hardware compute ceiling (peak computational throughput) and bandwidth ceiling (peak memory access) as a two-dimensional boundary. It characterizes workloads using arithmetic intensity, defined as computation divided by memory traffic. Workloads in the diagonal region are bandwidth-limited, while workloads in the plateau region are compute-limited.
In inference scenarios, if arithmetic intensity is below the arithmetic-intensity knee point (peak compute divided by peak bandwidth), the optimization direction should be to reduce memory access, such as weight quantization, batching aggregation, and cache reuse. If the workload is already close to the compute ceiling, the focus should be on optimizing computation itself, such as lower-precision numeric formats, sparse computation, or better parallel partitioning. In practice, it is advisable to first use professional performance profiling tools to collect per-stage latency and memory bandwidth utilization, then use Roofline to determine the bottleneck and avoid blindly applying optimization techniques.
4. Training-Side Performance Optimization
4.1 Distributed Parallelism Strategies
A single GPU cannot hold the full parameters, gradients, and optimizer states of a large model, so multiple parallelism techniques must be combined:
- Tensor parallelism: split the weight matrices of a single layer by column or row across GPUs; communication occurs in forward and backward reduction operations.
- Pipeline parallelism: split the model by layers and use micro-batch pipeline filling to reduce bubble rate; this requires balancing bubble time and memory usage.
- Data parallelism: synchronize gradients across GPUs. Combined with ZeRO-style sharding, optimizer states, gradients, and even parameters can be partitioned across GPUs, greatly reducing per-GPU redundancy.
- Sequence and context parallelism: for very long contexts, split the sequence dimension to reduce the memory pressure of attention computation.
4.2 Memory and Efficiency Techniques
Mixed-precision training, using FP16/BF16 with FP32 master weights, is standard. Activation recomputation trades a small amount of additional computation for a substantial reduction in activation memory. Gradient checkpointing, memory fragmentation management, and unified memory allocators can further reduce peak memory usage. The following is an illustrative description of common configuration approaches:
Training parallelism reference:- 10B-class model: data parallelism + ZeRO sharding + BF16 mixed precision- 100B-class model: tensor parallelism (intra-node) + pipeline parallelism (inter-node) + data parallelismTraining techniques: gradient accumulation to compensate for small batches, activation recomputation to balance memory and speed, gradient clipping for training stability
5. Practical Trade-offs and Conclusion
Performance optimization is never a matter of stacking individual techniques; it is a system-level trade-off. Memory efficiency, throughput, and latency often conflict. For example, increasing batch size improves throughput but may raise per-request latency. Speculative decoding reduces latency but introduces verification computation overhead. A practical process should follow “measure first, locate the bottleneck second, optimize third.” Use Roofline and profiling tools to determine whether the bottleneck is memory-bound or compute-bound, then apply optimizations at the scheduling, operator, parallelism, and numerical precision layers. For enterprise deployment, platform capabilities such as monitoring and alerting, elastic scaling, and canary releases are also needed so that algorithmic optimization gains can be reliably translated into improved online service user experience. Only by combining algorithmic understanding with systems engineering can large models run efficiently under real-world cost constraints.
