LLM Training and Inference Performance Optimization: A Practical Guide

    This guide explains why getting a large language model to run is not the same as making it production-ready, and presents a practical framework for optimizing both training and inference. It traces the evolution from language models to decoder-only LLMs, breaks down the three main inference bottlenecks—high latency, large KV cache memory usage, and low compute efficiency—along with their corresponding techniques such as continuous batching, KV cache compression and paging, and operator fusion. It also covers training-side parallelism strategies and memory governance, shows how to use the Roofline model to locate bottlenecks, and recommends a three-layer metrics approach for building a measurable optimization feedback loop.

    1. Introduction: Why “It Runs” Is Not “It Works”

    When a large model moves from an experimental environment to production, the real barrier is often not algorithmic quality but engineering efficiency. Completing a forward and backward pass on a single machine and GPU only proves the pipeline is connected. What determines success is whether the model can reliably support high-concurrency, low-latency online serving under limited memory and bandwidth, or maintain a linear speedup at thousand-GPU scale. This article takes a general technical perspective, reviews the evolution from language models to large models, and provides an actionable performance optimization framework along two main lines: training and inference.

    2. From Language Models to Large Models

    At its core, a language model is a probability model that predicts the next token based on context. Early approaches relied on statistical language models and recurrent neural networks, limited by long-sequence modeling capability and parallelism. Attention and self-attention architectures then became mainstream, allowing any position in a sequence to interact directly and naturally fitting parallel computation based on matrix multiplication.

    By structure, there are three common pre-training architectures in the industry: encoder-only structures excel at understanding tasks, encoder-decoder structures suit sequence-to-sequence transformation, and decoder-only structures center on autoregressive generation and have become the mainstream choice for conversational large models. The mix of open and closed source, and the dense release cadence over time, both illustrate the compounding effect of foundational architecture research: most capability leaps are built on the same scalable backbone.

    The engineering implication is direct: optimization cannot be separated from architecture. Inference for decoder-only structures is autoregressive token by token, with inherent serial dependencies and memory-access-intensive characteristics. This determines the boundaries of all inference optimization techniques discussed later.

    3. Three Inference Bottlenecks and Their Solutions

    3.1 High Latency: Static Batching Is the Primary Culprit

    Traditional static batching requires all requests in a batch to enter and exit at the same time. Short requests must wait for long requests to finish generating, causing substantial idle time. Continuous batching pushes the scheduling granularity down from the “batch” to the “single decoding iteration”: after each step, slots of completed sequences are reclaimed and immediately filled with queued requests.

    1. Static batching: [req1 ████████████ done]
    2. [req2 ██ done ...... idle]
    3. Continuous batching: re-batch at each tick; completed requests exit, new requests fill in immediately

    The gains come from slot utilization and effective throughput, not single-request latency. As a result, the improvement is significant in high-concurrency online scenarios and limited in low-concurrency scenarios.

    3.2 Large Memory Usage: The KV Cache Is the Main Consumer

    Autoregressive decoding requires caching historical key-value tensors, whose size grows linearly with sequence length, number of layers, number of attention heads, and concurrency. In long-context scenarios, this easily becomes a memory bottleneck. General optimization directions include: compressing cache precision, sharing and reusing across layers or heads, paged management to reduce fragmentation, and using sparse or chunked attention to reduce the range of history that must be retained.

    The value of chunked attention is that it splits full attention into local block computation plus a small amount of global summary, reducing complexity from quadratic in sequence length to near-linear, while preserving intra-block parallelism and balancing memory and compute efficiency.

    3.3 Low Compute Efficiency: Operator and Memory-Access Mismatch

    During decoding, each step processes only one token, so matrices degenerate into thin, tall shapes with low arithmetic intensity, and performance is limited by memory bandwidth rather than peak compute. Optimization focuses on operator fusion, reducing kernel launches and intermediate tensor reads/writes, increasing the batch dimension to restore matrix shapes, and using unified memory access and efficient numerical formats to improve effective bandwidth.

    4. Training Side: Parallelism Strategies and Memory Governance

    The core tension in training optimization is memory capacity versus communication overhead. A common approach is sharding: partition optimizer states, gradients, and parameters across devices by dimension, trading communication for memory. This is combined with tensor parallelism to split single-layer computation, pipeline parallelism to split inter-layer dependencies, and data parallelism to scale throughput. When combining the three, care must be taken to overlap communication and computation in time to avoid bubbles.

    Memory governance also includes recomputation (trading compute for memory), activation chunking and offloading, and loss-scaling stability under mixed precision. There is only one criterion for judging whether a strategy is sound: whether end-to-end throughput and scaling efficiency improve under a given cluster topology, not whether single-GPU metrics look good.

    5. Using the Roofline Model to Locate Bottlenecks

    Roofline expresses achievable performance as an upper bound jointly constrained by peak compute and peak bandwidth: the x-axis is arithmetic intensity (floating-point operations per byte of memory access), and the y-axis is achievable compute. Below the ridge point, performance is bandwidth-bound; above it, compute-bound.

    Recommended practical steps:

    1. Count the floating-point operations and memory-access bytes of the target operator to compute arithmetic intensity.
    2. Compare against the hardware ridge point to determine whether it is bandwidth-bound or compute-bound.
    3. If bandwidth-bound, prioritize fusion, quantization, and cache reuse; if compute-bound, prioritize increasing parallelism and matrix size.
    4. Use monitoring and logging services to collect actual utilization, compare against the theoretical upper bound, and quantify the optimization space.

    6. Implementation Recommendations and Evaluation Loop

    Optimization must be measurable. It is recommended to establish three layers of metrics: at the business layer, time to first token and end-to-end latency; at the system layer, throughput and memory watermark; at the hardware layer, compute and bandwidth utilization. Any change should be compared before and after against a fixed load-testing baseline to avoid local optima harming the whole. If building an elastic inference service on a container platform and object storage, load testing, canary release, and monitoring alerts can be chained into a loop, turning performance optimization from one-off tuning into a continuously iterated engineering capability.