Large Language Model Training and Inference Performance Optimization: Algorithms and Practices

    Large language models are powerful, but production deployment exposes three coupled engineering challenges: high inference latency, large memory footprint, and low compute efficiency. This article starts from language-model fundamentals and then examines memory and compute optimizations for training and inference. It covers mixed precision, activation recomputation, distributed training, prefill/decode separation, KV-cache management, continuous batching, chunked prefill, paged caches, quantization, and speculative decoding. It also explains how to use the roofline model to identify bandwidth-bound versus compute-bound bottlenecks, how to evaluate optimizations with TTFT, TPOT, throughput, peak memory, and MFU, and how to choose practical strategies by bottleneck. The goal is to help teams move from experience-based tuning to verifiable engineering practice.

    Introduction: Three Engineering Problems in LLM Deployment

    Large language models are capable, but once they enter production, teams quickly encounter three types of problems. First, inference latency is high, and users wait too long for the first token, especially in long-context scenarios. Second, memory usage is large: a single GPU cannot hold the full parameter set, and the number of concurrent requests one GPU can serve is limited. Third, compute efficiency is low, hardware capacity is not fully utilized, and costs rise accordingly.

    These problems are interrelated. Reducing memory usage often increases compute, while improving throughput may increase per-request latency. Performance optimization therefore requires identifying the bottleneck first and then choosing the right method. This article starts from basic language-model concepts, discusses optimization techniques in training and inference, and then presents a roofline-model approach for locating bottlenecks and measuring optimization results.

    1. From Language Models to Large Models

    1.1 Basic Definition of a Language Model

    A language model estimates the probability distribution of text sequences. Given context, the model predicts the probability of the next token. A token can be a character, a word, or a subword, depending on the tokenization method. During training, a language model learns statistical patterns from large-scale text and compresses those patterns into parameters.

    When the parameter scale reaches tens of billions, such models are usually called large language models. As scale increases, the model shows stronger generalization and can perform summarization, translation, code generation, and other tasks.

    1.2 Three Mainstream Architectures

    By network structure, current mainstream models fall into three categories:

    • Decoder-only: uses an autoregressive approach and generates tokens one by one from left to right. Most current mainstream conversational models belong to this category.
    • Encoder-only: understands text through bidirectional context and is suitable for classification, retrieval, extraction, and other understanding tasks.
    • Encoder-decoder: the encoder understands the input and the decoder generates the output; commonly used for translation and generative tasks.

    All three architectures are based on the Transformer. The core of the Transformer is self-attention, which allows each token to directly attend to other positions in the sequence.

    1.3 Two Pretraining Paradigms

    The objective of the pretraining stage determines how the model is used.

    Masked language modeling: randomly masks some tokens and asks the model to reconstruct the masked content from bidirectional context. This approach is good at understanding tasks.

    Autoregressive language modeling: predicts the next token based on preceding context. This approach naturally fits text generation and is the foundation of conversational models.

    1.4 Training Pipeline for Conversational Models

    Conversational models usually go through three stages:

    1. Pretraining: learn general language ability from large-scale unlabeled text.
    2. Instruction tuning: use human-written instructions and responses so the model learns to answer according to instructions.
    3. Preference alignment: use human or model rankings of response quality so outputs better match user expectations.

    Understanding this pipeline is important because compute demand and memory pressure differ greatly across stages.

    2. Memory and Compute Optimization During Training

    2.1 Four Components of Training Memory

    Training memory mainly consists of four parts:

    • Model parameters: the space occupied by the weights themselves, related to parameter count and numerical precision.
    • Gradients: gradients saved for each parameter during backpropagation, usually the same scale as parameter memory.
    • Optimizer states: for an adaptive optimizer, each parameter also needs statistics such as momentum and variance, which often take the largest share.
    • Activations: intermediate results from the forward pass used to compute gradients during backpropagation; they grow with batch size and sequence length.

    For a rough estimate, first calculate parameters, gradients, and optimizer states, then add activations. The code below gives a simplified estimation approach; actual values are also affected by framework implementation, communication buffers, and fragmentation.

    1. def estimate_training_memory_gb(num_params_billion, bytes_per_param=2,
    2. optimizer_bytes_per_param=12, activation_gb=0.0):
    3. """Roughly estimate training memory (GB): parameters + gradients + optimizer states + activations."""
    4. params_gb = num_params_billion * bytes_per_param # billion params * bytes per param ≈ GB
    5. grads_gb = params_gb # gradients have the same scale as parameters
    6. optim_gb = num_params_billion * optimizer_bytes_per_param # optimizer states (including master weight copies, etc.)
    7. return params_gb + grads_gb + optim_gb + activation_gb

    This code only illustrates the order of magnitude. Its purpose is to help teams judge before implementation whether a single GPU can hold the model and whether sharding is needed.

    2.2 Mixed Precision Training

    Mixed precision training uses low-precision formats in forward and backward computation while retaining high-precision copies at key positions to maintain numerical stability. It reduces parameter and activation memory and uses low-precision compute units on hardware to improve throughput. It requires loss scaling to prevent small gradients from underflowing at low precision.

    2.3 Activation Recomputation

    Activation recomputation saves only part of the activations during the forward pass and recomputes discarded intermediate results during the backward pass. It trades extra compute for memory space. When memory is the bottleneck and compute resources are relatively abundant, this trade is usually worthwhile. For deeper networks, the savings are especially clear.

    2.4 Distributed Training Strategies

    When a single GPU cannot hold the model, the training job must be distributed across multiple GPUs or nodes. Common strategies include:

    • Data parallelism: each GPU holds the full model, processes different data batches, and keeps consistency through gradient synchronization. It is simple to implement, but each GPU still needs to hold the full model.
    • Tensor parallelism: splits matrix operations within a layer across multiple GPUs. It suits scenarios with heavy intra-layer computation but requires high inter-GPU communication bandwidth.
    • Pipeline parallelism: splits the model into segments by layer, with different devices processing different segments and micro-batches filling pipeline gaps.
    • Optimizer state sharding: distributes optimizer states, gradients, and parameters, with each GPU holding only a portion and communicating when needed.

    Real systems usually combine these strategies. Selection should consider model scale, inter-node bandwidth, and communication overhead.

    3. Performance Bottlenecks During Inference

    3.1 Prefill and Decode Phases

    Autoregressive inference has two phases. The prefill phase processes all input tokens at once. It has high compute demand and can utilize compute well; it determines first-token latency. The decode phase generates one token at a time. It has low compute demand but must read all model parameters and historical cache at each step; it is usually limited by memory bandwidth and determines per-token output speed.

    Looking at the two phases together can lead to incorrect conclusions. They should be measured separately during optimization.

    3.2 KV Cache and Its Memory Overhead

    To avoid repeated computation, inference caches the keys and values of historical tokens at each layer, known as the KV cache. Its memory usage can be estimated as follows:

    Bytes per token = 2 × number of layers × number of KV heads × head dimension × bytes per element

    Total usage is then multiplied by the number of concurrent sequences and average sequence length. As can be seen, when long context and high concurrency grow together, the KV cache quickly exceeds the memory occupied by model parameters. KV cache is therefore a key focus of inference memory management.

    3.3 Continuous Batching

    Static batching requires a batch of requests to start and finish together. Short requests must wait for long requests, so the GPU idles. Continuous batching schedules at iteration granularity: after each generation step, it checks whether completed requests can be removed and immediately admits new requests. This significantly improves GPU utilization and overall throughput while reducing queueing time.

    Scheduler design needs attention in two areas. First, limit the total number of tokens per batch to prevent memory overflow. Second, balance throughput and per-request latency; different priorities can be set for prefill and decode.

    3.4 Chunked Prefill

    When user input is long, one-shot prefill occupies compute resources for a long time, causing decoding requests in the same batch to stall. Chunked prefill splits long input into chunks, processes one chunk at a time, and interleaves execution with decode requests. This maintains long-input processing efficiency while reducing impact on the latency of other requests.

    3.5 Blockwise Attention and Paged Cache

    Attention computation memory reads and writes grow quadratically with sequence length. Blockwise attention splits queries, keys, and values into blocks, performs local computation in on-chip memory, and then merges results. This reduces repeated reads and writes to high-bandwidth memory and avoids generating the full attention matrix at once.

    Paged KV cache divides the cache into fixed-size blocks allocated on demand, similar to virtual memory management in an operating system. It reduces memory fragmentation, allows requests of different lengths to share the same cache pool, and improves memory utilization.

    3.6 Quantization and Speculative Decoding

    Quantization reduces memory and bandwidth demand by lowering the numerical precision of weights or KV cache. Weight quantization usually has a controllable impact on model quality, but it must be validated on the target task. KV cache quantization provides clear benefits in long-context scenarios, while attention must be paid to the effect of accuracy loss on outputs.

    Speculative decoding uses a smaller draft model to propose multiple candidate tokens first, and then the target model verifies them in parallel. Accepted tokens can be accepted at once, reducing the number of serial steps in the target model. Its benefit depends on the acceptance rate between draft and target; when the acceptance rate is low, it may not pay off.

    4. Using the Roofline Model to Locate Bottlenecks

    4.1 Core Concepts

    The roofline model describes the relationship between compute and memory access with a two-dimensional plot. The horizontal axis is arithmetic intensity, defined as compute operations (floating-point operations) divided by memory traffic (bytes read and written). The vertical axis is attainable performance. There are two ceilings: the hardware peak compute and a sloped line determined by memory bandwidth. Their intersection is called the ridge point.

    Operations with arithmetic intensity below the ridge point are bandwidth-bound, and performance grows linearly with intensity. Operations above the ridge point are compute-bound, and performance approaches peak.

    4.2 Analysis Steps

    1. Count the floating-point operations and memory traffic of the target operator or the entire inference step.
    2. Calculate arithmetic intensity and compare it with the hardware ridge point.
    3. Determine the bottleneck type: in the bandwidth-bound region, prioritize reducing memory traffic, fusing operators, and quantization; in the compute-bound region, prioritize improving compute efficiency and using more suitable low-precision compute units.
    4. Measure actual performance and compare it with the roofline ceiling to judge optimization headroom.
    1. def roofline_check(flops, bytes_moved, peak_tflops, peak_bw_gbps):
    2. """Determine whether an operator is bandwidth-bound or compute-bound."""
    3. intensity = flops / bytes_moved # arithmetic intensity, FLOP/Byte
    4. ridge = (peak_tflops * 1e12) / (peak_bw_gbps * 1e9) # ridge-point intensity
    5. bound = "bandwidth-bound" if intensity < ridge else "compute-bound"
    6. attainable = min(peak_tflops * 1e12, intensity * peak_bw_gbps * 1e9)
    7. return {"intensity": intensity, "ridge": ridge,
    8. "bound": bound, "attainable_tflops": attainable / 1e12}

    In practical inference, matrix operations in the decode phase often fall in the bandwidth-bound region, so improving memory efficiency and reducing data movement are often more effective than simply adding compute. Large matrix operations in the prefill phase are closer to compute-bound, so attention should be paid to compute-unit utilization.

    5. Evaluating Optimization Results

    5.1 Key Metrics

    • Time to first token (TTFT): time from request arrival to the first output token, mainly affected by prefill.
    • Time per output token (TPOT): average interval for generating subsequent tokens, mainly affected by decode.
    • Throughput: tokens or requests processed per unit time, measuring overall system capability.
    • Peak memory: maximum memory usage during runtime, determining the concurrency and context length that can be supported.
    • Model FLOPs utilization (MFU): ratio of actual compute achieved to hardware peak, used to measure training efficiency.

    5.2 Evaluation Principles

    Comparisons should be fair. Specific practices include fixing the distribution of input lengths and output lengths, using request arrival patterns close to production, excluding warm-up data, repeating runs and taking statistical values, and observing latency percentiles rather than only averages. Changing only one variable at a time is necessary to determine which optimization produced the effect.

    6. Practical Recommendations

    Choose strategies by bottleneck, using the following as a reference:

    • High first-token latency: check whether long input is blocking scheduling, consider chunked prefill, and evaluate compute utilization in the prefill phase.
    • Insufficient memory: first estimate KV cache usage, then consider paged cache management, KV cache quantization, or reducing the maximum context length.
    • Low throughput: enable continuous batching, adjust the per-batch token limit, and check whether request length distribution varies too much.
    • Slow training: use the roofline method to identify the bottleneck first, then decide whether to increase parallelism, enable mixed precision, or optimize communication.

    Common pitfalls are also worth noting. First, looking only at average latency and ignoring the impact of tail latency on user experience. Second, blindly stacking optimization techniques without understanding the bottleneck, which increases system complexity with limited benefit. Third, skipping correctness validation and launching quantization or speculative decoding without evaluating output quality on the target task.

    7. Summary

    The core of large-model performance optimization is accurately locating the bottleneck. On the training side, teams need to understand memory composition and distributed strategies. On the inference side, they need to distinguish prefill from decode and design scheduling and storage around the KV cache. The roofline model provides a unified framework for identifying bottleneck types. Combined with standardized evaluation metrics, teams can turn optimization from experience-based judgment into verifiable engineering practice.