A Practical Guide to LLM Training, Inference, and Performance Optimization

    This guide walks through the evolution from language models to large language models, explains why decoder-only architectures dominate generative workloads, and details the main training bottlenecks and their fixes: combining data, tensor, pipeline, and sequence parallelism, plus mixed precision, activation recomputation, optimizer state sharding, and operator fusion. It then covers inference challenges such as latency sensitivity, KV cache growth, and low arithmetic intensity, along with core techniques including continuous batching, chunked attention with paged KV caches, quantization, and speculative decoding. A Roofline-based workflow and a measure-locate-optimize-regress loop help readers pick the right optimization with data behind every change.

    1. From Language Models to LLMs: Technical Lineage and Architectural Differences

    The core task of a language model is to capture the statistical regularities of natural language, that is, to predict the probability distribution of the next token given a context. Early approaches were dominated by statistical language models, followed by the neural language model era represented by recurrent networks and attention mechanisms. Once self-attention became the mainstream architecture, model size and data size expanded together, giving rise to what we now call large language models.

    Architecturally, mainstream pretrained models fall into three categories:

    • Encoder-only: characterized by bidirectional attention, well suited to understanding tasks such as text classification and sequence labeling.
    • Decoder-only: characterized by causal masked self-attention, a natural fit for autoregressive generation, and the mainstream choice for today’s chat and generative models.
    • Encoder-decoder: combines input understanding with sequence generation, commonly used for translation, summarization, and similar tasks.

    In engineering practice, the vast majority of generative LLMs adopt the decoder-only structure. The reason is that its training objective and inference pattern are highly consistent: during training it performs next-token prediction in parallel, and during inference it generates tokens one by one autoregressively. Both share the same attention implementation and operators, which shortens the engineering path and makes optimization gains more direct.

    2. Training Bottlenecks and Optimization Methods

    The central tension on the training side is that model parameters, activations, and optimizer states compete for the same GPU memory, while compute utilization is often constrained by communication and memory access.

    2.1 Combining Distributed Parallelism Strategies

    No single parallelism strategy can satisfy both memory and throughput requirements, so they are typically combined:

    • Data parallelism: splits the batch and requires gradient synchronization, with communication volume growing linearly with parameter count.
    • Tensor parallelism: splits the weight matrices within a layer, communicates frequently, and is usually confined to high-speed intra-node interconnects.
    • Pipeline parallelism: splits the model by layer and reduces the bubble ratio through micro-batch scheduling.
    • Sequence/context parallelism: splits along the long-sequence dimension to relieve activation growth caused by long contexts.

    The configuration principle is to first use tensor parallelism to solve the memory problem when a single layer does not fit, then use pipeline parallelism to span nodes, and finally use data parallelism to scale overall throughput.

    2.2 Memory and Compute Efficiency

    • Mixed precision training: uses low precision for matrix multiplications and higher precision for master weights and gradient accumulation, balancing numerical stability with bandwidth savings.
    • Activation recomputation: trades extra compute for memory by discarding some forward activations and recomputing them during the backward pass, which suits models with many layers and large hidden dimensions.
    • Optimizer state sharding: partitions states such as momentum and variance along the data parallel dimension, significantly reducing static per-GPU usage.
    • Operator fusion: fuses element-wise operations such as normalization, activation, and residual addition to reduce kernel launches and memory round trips.

    2.3 Communication and Scheduling

    Overlapping computation with communication is key to better scaling efficiency: split gradient reduction into multiple buckets and interleave it with backward computation; use interleaved pipeline scheduling to compress the bubbles in the warmup and drain phases; and rely on gradient accumulation to maintain an equivalent global batch size when memory is constrained.

    3. Key Inference Challenges

    Inference has a completely different resource profile from training, with three main challenges:

    1. Latency sensitivity: time to first token and per-token latency directly determine the interactive experience.
    2. Large memory footprint: beyond weights, the key-value cache grows linearly with batch size and context length and often becomes the real bottleneck.
    3. Low compute efficiency: the decode phase processes only one token per step, so matrix multiplications degenerate into tall, skinny shapes with low arithmetic intensity, and performance is bound by memory bandwidth rather than compute.

    4. Core Inference Optimization Techniques

    4.1 Continuous Batching

    Traditional static batching must wait for every request in a batch to finish before releasing resources, so short requests are held back by long ones. Continuous batching inserts and evicts requests dynamically at request granularity, so idle slots are immediately filled by new requests, which substantially improves throughput and stabilizes tail latency.

    4.2 Chunked Attention and Cache Management

    Splitting attention computation along the sequence dimension and pairing it with paged key-value cache management maps logically contiguous cache to non-contiguous physical blocks, reducing fragmentation, improving memory utilization, and enabling reuse scenarios such as prefix sharing. Illustration:

    1. # Pseudocode: block mapping for a paged KV cache
    2. block_table = allocate_blocks(seq_len, block_size=16)
    3. for chunk in split_by_block(q, block_size=16):
    4. k, v = kv_cache.read(block_table, chunk)
    5. out = chunked_attention(chunk, k, v, causal=True)

    4.3 Quantization and Sparsity

    Low-bit quantization of weights and caches translates directly into throughput gains in the bandwidth-bound decode phase. Structured sparsity and speculative decoding verify multiple candidate tokens in a single forward pass, reducing the average number of decode steps. Note that quantization can cause accuracy regression, so validate with a small evaluation set.

    5. Using the Roofline Model to Locate Bottlenecks

    Roofline analysis expresses the performance ceiling as the envelope of two constraints: peak compute and peak bandwidth divided by arithmetic intensity. The practical steps are:

    1. Measure the floating-point operations and memory accesses of the target operator to obtain its arithmetic intensity.
    2. Locate that point on the chart to determine whether it sits in the bandwidth-bound or compute-bound region.
    3. If bandwidth-bound, prioritize operator fusion, quantization, and fewer memory round trips; if compute-bound, prioritize higher parallelism and efficient matrix multiplication implementations.
    4. Compare measured performance against the ceiling to quantify the optimization headroom and avoid blind parameter tuning.

    6. Implementation Recommendations

    When running LLM engineering workloads on cloud platforms such as Baidu AI Cloud, you can use a container platform to host distributed training and inference services, object storage to manage datasets and model artifacts, and monitoring, alerting, and logging services to observe throughput, latency, and memory levels, forming a “measure, locate, optimize, regress” loop. The overall principle is to first establish an observable baseline, then use Roofline to identify the bottleneck type, and finally choose parallelism, caching, quantization, or scheduling techniques according to that bottleneck, ensuring every optimization is backed by data and has a rollback path.