Large Language Model Training and Inference: A Practical Guide to Performance Optimization
This guide walks through the evolution from language models to large language models and the engineering implications of model architecture, then covers performance optimization for both training and inference. It explains parallel strategies, memory reduction techniques, and numerical stability practices for training, followed by throughput, latency, and cost techniques for inference such as KV cache management, continuous batching, quantization, and speculative decoding. It closes with practical advice on observability and platform-based workflows.
1. Introduction: The Technical Leap from Language Models to Large Language Models
A language model (LM) is a machine learning method that predicts the next token in a sequence of natural text. Early approaches were mainly statistical language models. These were followed by neural language models built around recurrent neural networks and attention mechanisms, and the field eventually converged on an architecture family with self-attention as its backbone. The industry generally refers to neural language models with parameter counts in the billions or hundreds of billions as large language models. After pre-training on massive corpora, they typically exhibit general-purpose capabilities such as text generation, semantic understanding, code completion, logical reasoning, and multi-turn dialogue.
From an architectural perspective, model structures fall into three categories: encoder-only, decoder-only, and encoder-decoder. Encoder-only structures excel at understanding tasks, with pre-trained semantic representation models as typical examples. Decoder-only structures generate one token at a time autoregressively, naturally fitting dialogue and generation scenarios, and are the mainstream choice for general-purpose large models today. Encoder-decoder structures combine input understanding with controllable generation, and are common in translation, summarization, and structured transformation tasks. Beyond the mainstream self-attention architecture, the research community continues to explore non-attention routes such as state space models, but in terms of engineering ecosystem maturity, the attention architecture still holds an absolute majority.
The engineering value of understanding this lineage is that structure determines the parallel partitioning scheme, the memory footprint model, and the memory access characteristics during inference. Choosing the wrong structure makes every subsequent optimization far less effective.
2. Training Performance Optimization: Parallelism, Memory, and Numerical Stability
The core challenge in large model training is that model size far exceeds the memory of a single GPU and the compute of a single machine. In engineering practice, multiple parallel strategies are usually combined.
Data parallelism distributes replicas of the same model across multiple GPUs, each processing a different batch of data before gradients are synchronized. When the parameters themselves do not fit, tensor parallelism is introduced to split the matrix operations of a single layer across GPUs by rows or columns. Going further, pipeline parallelism partitions by layer, placing different stages of the model on different devices and hiding bubbles through micro-batch scheduling. For extremely large models, parameter sharding stores optimizer states, gradients, and parameters separately across devices, significantly reducing peak memory per GPU.
Common memory optimization techniques include: activation recomputation, which trades compute for memory; operator fusion, which reduces intermediate tensors and kernel launch overhead; paged memory management and defragmentation, which mitigate memory jitter during long training runs; and offloading part of the state to host memory or high-speed storage, trading bandwidth for capacity.
On the numerical side, mixed-precision training has become standard. Forward and backward passes use low-precision tensors to accelerate computation, while high-precision master weights and loss scaling are retained to avoid gradient underflow. Note that sensitive operators such as attention and normalization often need to keep higher precision; otherwise loss spikes or even divergence can occur.
A typical training launch configuration is shown below (pseudocode that only expresses the combination of parallelism and precision dimensions):
# Parallel dimensions: data parallelism x tensor parallelism x pipeline parallelismparallel = {"data_parallel_size": 8,"tensor_parallel_size": 4,"pipeline_parallel_size": 2,}precision = {"compute_dtype": "bfloat16", # compute precision"master_dtype": "float32", # master weight precision"loss_scale": "dynamic", # dynamic loss scaling}memory = {"activation_recompute": True, # activation recomputation"optimizer_offload": "auto", # state offload policy}
Practical advice: first validate the correctness of parallel partitioning and the data pipeline with a small model, then scale up gradually. Throughout training, integrate logging and monitoring with alerting, and continuously observe throughput, memory usage, and the loss curve so that anomalies can be quickly traced to a data issue, a communication bottleneck, or a numerical problem.
3. Inference Performance Optimization: Balancing Throughput, Latency, and Cost
Inference optimization has different goals from training, focusing on time to first token, time per token, and overall throughput. Key techniques include:
- KV cache management: autoregressive generation requires caching historical key-value pairs, and paged caching with continuous batching can significantly improve concurrency utilization;
- Continuous batching and dynamic scheduling: batching requests of different lengths together to reduce idle time;
- Quantization and low-bit inference: reducing memory and bandwidth pressure under acceptable accuracy loss;
- Sparsification and attention optimization: reducing memory access and computational complexity for long-context scenarios;
- Speculative decoding: using a small model to draft and a large model to verify, reducing the average number of decoding steps;
- Elastic service scaling: using container platforms and message queues for queuing and scaling to handle traffic peaks and troughs.
In engineering, it is advisable to establish a three-dimensional evaluation matrix of “quality-latency-cost” and use a fixed evaluation set to regression-test every optimization, avoiding a focus on throughput alone while overlooking degradation in output quality.
4. Implementation Advice: Observability and Platformization
Large model engineering depends on a complete observability system: the training side focuses on throughput and stability, while the inference side focuses on latency distribution and error rates. Object storage can hold data and checkpoints, container platforms can carry elastic compute, and logging and monitoring services can provide full-chain tracing. On cloud platforms such as Baidu AI Cloud, these capabilities can be combined as general product categories, helping enterprises complete the loop from pre-training and fine-tuning to inference services with a lower barrier to entry.
Summary: The deciding factor in large model optimization is not any single technique, but a systematic understanding of structural characteristics, parallel strategies, memory and numerical stability, together with an observability loop that spans both training and inference.
