A Practical Guide to Performance Optimization for LLM Training and Inference
This article provides a practical guide to optimizing the training and inference performance of Large Language Models (LLMs). It emphasizes the importance of identifying system bottlenecks before applying specific algorithms. Key topics include training optimizations such as mixed precision, gradient accumulation, and distributed parallelism, alongside inference optimizations like quantization, key-value cache management, and continuous batching. The guide concludes with a systematic workflow for conducting repeatable optimization experiments to balance model quality, latency, and cost.
1. From Language Models to LLMs: Understanding Computational Goals
The core task of a language model is to learn the probabilistic patterns of text sequences. After tokenization, text is converted into a discrete sequence of tokens. By predicting target tokens based on context, the model gains capabilities in language understanding, information organization, and text generation. Tokens do not necessarily correspond to complete words; they can represent characters, subwords, or other text fragments.
For autoregressive language models, a sequence of length T can be decomposed as:
P(x₁, …, xₜ) = ∏ P(xᵢ | x₁, …, xᵢ₋₁)
Training typically uses negative log-likelihood loss to increase the model’s prediction probability for true subsequent tokens. During inference, the model generates new tokens step-by-step based on existing context until a stopping condition is met.
Another category of language models reconstructs masked content from context, making them more suitable for learning bidirectional semantic representations. Different training objectives correspond to different computational paths, so performance optimization strategies cannot be universally applied to all language models. This article focuses primarily on the training and generative inference of autoregressive LLMs.
There is no unified parameter threshold to define a “Large Language Model.” While parameter scale is important, the quality of training data, model architecture, training compute, context length, and subsequent adaptation methods equally influence actual capabilities. Engineering optimization should not focus solely on parameter count but should simultaneously observe model quality, resource utilization, and business service objectives.
2. Establishing a Performance Model: Identifying Bottlenecks Over Choosing Algorithms
Running large models involves computation, memory access, device communication, and task scheduling. When one component is optimized, the bottleneck may shift to another. Therefore, it is essential to measure first and then decide the optimization sequence.
2.1 Primary Costs in the Training Phase
Training memory is typically composed of:
- Model parameters;
- Parameter gradients;
- Optimizer states;
- Intermediate activations;
- Temporary computation buffers and communication buffers.
This can be described with a simplified relationship:
Training Memory ≈ Parameter Memory + Gradient Memory + Optimizer State Memory + Activation Memory + Temporary Overhead
Different precisions, optimizers, and sharding strategies change the proportion of each component. Sequence length, micro-batch size, and network depth significantly affect activation memory.
Training performance is also influenced by data reading and preprocessing. If accelerators frequently wait for input, optimizing matrix computations alone will not improve end-to-end throughput. Data preparation, computation execution, gradient synchronization, and parameter updates should be measured separately.
2.2 Two Typical Workloads in the Inference Phase
Generative inference is generally divided into two phases: context processing and token-by-token generation.
The context processing phase computes representations of the input sequence and builds the cache used for subsequent generation. Longer inputs often bring larger matrix computation workloads, making this phase more compute-bound under certain configurations.
The token-by-token generation phase processes only a few new tokens at a time but requires accessing model weights and historical caches. Especially at low batch sizes, performance is often constrained by memory bandwidth and kernel launch overhead.
This difference means that methods improving context processing throughput may not effectively reduce token-by-token generation latency.
2.3 Clarifying Metric Definitions
It is recommended to record at least:
- Effective tokens processed per second during training;
- Inference Time-To-First-Token (TTFT) latency;
- Inter-token latency;
- Request end-to-end latency;
- Service throughput under latency constraints;
- Peak memory and cache usage;
- Accelerator utilization and communication wait time;
- Model quality and task success rate.
Throughput tests must specify input length, output length, concurrency, and statistical methods. Numbers measured under different workloads cannot be directly used to compare optimization effects.
3. Training Optimization: From Numerical Precision to Distributed Parallelism
3.1 Mixed Precision: Reducing Data Movement and Storage Pressure
Mixed precision training reduces memory usage and improves computational throughput by using lower-precision data formats at appropriate stages, while retaining higher precision for numerically sensitive operations.
In practice, attention should be paid to:
- Input and accumulation precision of matrix multiplication;
- Stability of normalization and reduction operations;
- Whether gradient overflow or underflow occurs;
- If loss scaling is required;
- Precision used for optimizer states and parameter updates.
Low precision is not an unconditional substitute for high precision. Some numerical formats have a large dynamic range but limited effective precision, while others are more prone to overflow. Small-scale experiments should compare loss curves, gradient distributions, and validation results before gradually scaling up training.
3.2 Gradient Accumulation: Expanding Effective Batch Size Under Memory Constraints
Gradient accumulation allows multiple micro-batches to execute forward and backward passes sequentially before updating parameters uniformly. In standard data parallel scenarios, it can be approximated as:
Effective Batch Size = Single-Device Micro-Batch × Accumulation Steps × Number of Data Parallel Devices
It alleviates memory pressure for a single computation pass but does not automatically shorten the time required to reach the same training goal. Excessive accumulation steps may affect update frequency and alter the actual behavior of the optimizer and learning rate schedule.
Batch size should be judged based on effective token counts, not just sample counts. For texts with significant length variations, the computational workload represented by a single sample can differ greatly.
3.3 Activation Recomputation: Trading Computation for Memory Space
Activation recomputation does not save all intermediate results but re-executes parts of the forward pass during backpropagation.
The benefit is reduced activation memory; the cost is increased computation time. Suitable scenarios include long-sequence training, deep networks, and cases where insufficient memory forces micro-batches to be too small.
The scope of recomputation must be chosen based on actual bottlenecks. If training is already noticeably compute-bound, excessive recomputation may reduce throughput. If saving memory allows for a more reasonable micro-batch size, overall throughput may still improve. Evaluation should compare end-to-end training speed, not just the magnitude of memory reduction.
3.4 Parallel Training: Matching Model Scale with Device Interconnects
Common parallel approaches have different focuses:
Data Parallelism: Each device processes different data and then synchronizes gradients. The implementation is relatively straightforward, but the full model and training states must fit into device memory, or be combined with state sharding.
Tensor Parallelism: Splits large tensor computations across multiple devices. Suitable for models that cannot fit on a single device, but involves frequent intra-layer communication and is sensitive to interconnect bandwidth and latency.
Pipeline Parallelism: Places different network layers on different device groups. It distributes model storage but requires handling pipeline idle time, stage load imbalance, and micro-batch scheduling.
Training State Sharding: Distributes parameters, gradients, or optimizer states across devices to reduce redundant storage, while adding necessary data gathering and synchronization operations.
Higher parallelism is not always better. A balance should be found considering device topology, model size, and communication ratio to avoid computation time being offset by communication waits.
3.5 Data Engineering: Ensuring Continuous Effective Input for Training Devices
Data deduplication, quality filtering, length bucketing, and sample packing affect both training quality and computational efficiency.
Placing samples of similar lengths into the same batch reduces padding computation; packing multiple short samples into fixed-length sequences increases the proportion of effective tokens. However, attention boundaries and loss masks must be set correctly to prevent the model from incorrectly treating unrelated samples as continuous context.
Data reading should overlap with device computation as much as possible, and tokenization, decoding, and storage reading should be checked for bottlenecks in advance. Preprocessed data should also retain traceable versions for experiment reproducibility.
4. Attention and Model Architecture Optimization: Distinguishing Equivalent Implementations from Structural Changes
4.1 Chunked Attention: Reducing Memory Access for Intermediate Matrices
Standard dense attention incurs significant intermediate computation and storage overhead as sequence length increases. Chunked computation combined with online normalization avoids storing the complete attention score matrix, reducing memory read/write pressure.
These methods primarily optimize data movement and execution patterns and usually do not imply changing the theoretical computational complexity of dense attention from quadratic to linear. Actual gains depend on sequence length, hardware characteristics, data precision, and specific implementations.
4.2 Reducing KV Heads: Lowering Generation Cache Scale
Multiple query heads sharing fewer key and value heads can reduce KV cache usage and partial memory access pressure.
However, this is a model architecture design and cannot simply be treated as a lossless switch on existing models. Changing the KV head layout typically requires corresponding training or adaptation, and its impact on quality must be verified.
4.3 Sparse Attention and Sliding Windows
Limiting the context range each token can access reduces some computation and cache requirements for long sequences. However, this change may weaken long-range information interaction.
Such strategies can only be adopted when the model architecture, training process, and target tasks permit. It is crucial to verify cross-segment reference, long-text QA, multi-turn dialogue, and long-range dependency tasks. Usability cannot be judged solely based on effects on short inputs.
4.4 Sparse Expert Architecture
Sparse expert models typically select a subset of experts for computation for each token, decoupling the growth of total parameters from the activated computation per step.
Engineering challenges include routing overhead, expert load imbalance, cross-device data exchange, and expert weight storage. A lower number of activated parameters does not necessarily translate to lower end-to-end latency; measurement must incorporate expert distribution, batch size, and network communication.
5. Inference Optimization: Collaborative Design of Weights, Cache, and Scheduling
5.1 Model Quantization: Controlling Error, Not Just Reducing Bit-width
Quantization maps some high-precision values to lower-bit representations and can be applied to weights, activations, or the KV cache.
Common choices include per-tensor, per-channel, and grouped quantization. Finer granularity may improve error but increases scaling parameters and execution complexity. Weight quantization reduces weight storage but may not bring speedups on all hardware and kernel implementations.
Quantization validation should cover target tasks and focus on error-sensitive scenarios such as long inputs, rare words, numerical computations, and structured outputs. Calibration data should closely match the production request distribution.
If cache quantization causes error accumulation, the impact may expand as generation length increases. Therefore, both short and long outputs must be tested.
5.2 KV Cache: Avoiding Redundant Computation and Managing Lifecycle
Autoregressive generation typically caches the keys and values of historical tokens to avoid recomputing the entire context at each step.
Cache usage can be roughly estimated as:
Cache Bytes ≈ 2 × Number of Layers × Cached Tokens × Number of KV Heads × Head Dimension × Bytes Per Element
Here, the factor 2 corresponds to keys and values. Concurrent requests, different layer cache layouts, memory alignment, and management metadata introduce additional overhead.
Cache management should allocate on demand, release promptly, and reduce fragmentation. If fixed blocks are used to organize the cache, it can more flexibly support requests of varying lengths, but block size and scheduling methods still need adjustment based on the workload.
5.3 Prefix Reuse: Prioritizing Correctness and Isolation
When multiple requests share an identical input prefix, the associated cache can be reused under certain conditions to reduce redundant context computation.
Before reuse, it must be confirmed that the model version, tokenization results, position processing, adaptation configurations, and other conditions affecting the computation result are identical. Incomplete cache key design can introduce hard-to-detect errors.
In multi-tenant environments, access isolation, capacity limits, and expiration policies must be set to prevent sensitive content from being exposed across requests and to prevent low-value caches from occupying resources long-term.
5.4 Continuous Batching: Reducing Waits for the Longest Request
In static batching, where requests have varying lengths, computation slots from completed short requests cannot be immediately assigned to new requests. Continuous batching allows dynamic insertion and removal of requests during generation, improving resource utilization.
Scheduling should not be decided solely by request count; it should also consider pending token counts, cache capacity, maximum sequence length, and latency budget. Long-input requests may squeeze the TTFT of short requests. Tail latency needs to be controlled through chunked context processing, request prioritization, or queue isolation.
5.5 Speculative Decoding: Returns Depend on Acceptance Rate and Verification Cost
Speculative decoding uses a lower-cost candidate generation process to propose multiple tokens, which are then verified by the target model. If candidates are largely accepted, it can reduce the number of sequential generation rounds for the target model.
Methods conforming to appropriate acceptance and resampling rules can maintain the target generation distribution; if simplified heuristic acceptance strategies are used, the resulting distribution cannot be claimed as strictly equivalent.
Actual returns are jointly affected by candidate cost, acceptance rate, verification method, and batch size. Total resource consumption and end-to-end latency must be measured, not just the number of tokens accepted per round.
6. Practical Workflow: Turning Optimization into Repeatable Experiments
Step 1: Fix the Baseline
Record model and data versions, device configuration, runtime environment, precision, parallel strategy, and request distribution. The baseline must be reproducible; otherwise, subsequent results cannot be accurately attributed.
The inference baseline should cover both single-request and multi-concurrency scenarios, distinguishing between short-input, long-input, short-output, and long-output cases.
Step 2: Identify the Primary Bottleneck
Break down training time into data preparation, forward computation, backward computation, communication, and updates. Break down inference time into queuing, context processing, token-by-token generation, and output transmission.
If memory is insufficient, prioritize analyzing training states or cache usage. If communication waits are too long, prioritize adjusting the parallel layout. If device utilization is low, check data supply, batching, and scheduling.
Step 3: Change One Major Variable at a Time
Independently verify mixed precision, recomputation, quantization, cache management, or scheduling strategies before evaluating combined effects. Modifying multiple technologies simultaneously increases the difficulty of pinpointing quality degradation and performance fluctuations.
Each experiment should record at least three sets of results: performance, memory, and quality, while retaining configurations and logs.
Step 4: Evaluate Returns Under Business Constraints
A unified acceptance principle can be adopted:
- Model quality degradation does not exceed a pre-set tolerance range;
- TTFT and tail latency meet service objectives;
- Effective throughput increases under a fixed resource budget;
- The service can rate-limit or degrade gracefully under abnormal loads;
- The optimization solution is monitorable, reproducible, and rollback-able.
“Effective throughput” should refer to the capacity to process requests that meet quality and latency requirements, not an unconstrained peak generation speed.
Step 5: Canary Deployment and Continuous Regression
Post-deployment, monitor input length distribution, cache hit rate, queuing time, resource usage, and failure rate. Changes in real traffic may invalidate previously optimal configurations.
When memory pressure or request backlogs occur, bounded protective measures should be taken, such as limiting single-request length, constraining generation budgets, reducing intake rates, or adjusting queues. Any automatic degradation must clearly define its impact on user experience and output quality.
7. Conclusion: Establishing the Balance Among Quality, Latency, and Cost
LLM optimization is a systems engineering effort spanning model architecture, training algorithms, numerical computation, memory management, and service scheduling.
In the training phase, the focus is on increasing the proportion of effective computation and balancing memory and communication overhead. In the inference phase, the focus is on distinguishing between context processing and token-by-token generation, collaboratively optimizing weight access, cache capacity, and request scheduling.
The reliable practical path is: define business objectives first, then establish a reproducible baseline; identify bottlenecks first, then select technologies; verify quality first, then evaluate speed and cost. Only by continuously meeting these conditions under real workloads can performance optimization yield stable, maintainable engineering benefits.
