Large Model Training and Inference Performance Optimization: Architecture-Aware Practices

    This article presents a practical, architecture-aware framework for optimizing large model training and inference. It maps major architecture families to their optimization boundaries, then covers distributed training parallelism, memory reduction, communication overlap, KV-cache management, continuous batching, quantization, speculative decoding, and performance evaluation. The goal is to help teams build a measurement–localization–optimization–regression loop and balance quality, latency, throughput, and cost without optimizing the wrong bottleneck.

    Deploying large models in production is usually constrained by compute, memory, communication bandwidth, and online request scheduling at the same time. A single algorithmic optimization often improves only a local metric. Reusable practice starts with understanding the model architecture family, then builds a measurement–localization–optimization–regression loop across both training and inference. This article starts from architecture classification, summarizes common methods for training parallelism, memory optimization, communication overlap, inference caching, quantization, batch scheduling, and performance evaluation, and outlines an actionable practice path.

    1. Understand Optimization Boundaries Through Architecture Families

    The industry often uses an evolutionary-tree view to organize the development of language models: different branches correspond to different base structures, while openness and release timelines help observe ecosystem evolution. For engineering optimization, the more important issue is how architecture differences change training objectives, attention patterns, and inference paths.

    Mainstream structures fall into roughly three categories. The first is decoder-only, which generates tokens autoregressively and usually trains on next-token prediction. Its inference stage must maintain a KV cache, making it highly sensitive to memory capacity, cache management, and batch scheduling. The second is encoder-only, which is good at bidirectional context modeling and is often used for understanding tasks. Inference usually completes representation in one forward pass, so cache pressure is lower, but long-sequence attention and intra-batch padding efficiency remain sensitive. The third is encoder–decoder, where the encoder processes input and the decoder outputs autoregressively. Training and inference combine understanding and generation characteristics, so optimization must consider encoder throughput and decoder latency separately.

    Non-attention architecture branches also exist, but most current optimization methods center on attention computation, matrix multiplication, communication, and memory management. Architecture classification is not an academic label; it defines optimization boundaries. Decoder-only models should prioritize KV-cache governance and continuous batching. Encoder-only models should prioritize long-sequence attention and padding waste. Encoder–decoder models need their two ends’ bottlenecks separated. Only after clarifying architecture and business goals can parallelism, quantization, and scheduling avoid optimizing the wrong target.

    2. Training Optimization: Co-Design Parallelism, Memory, and Communication

    The core tension in training optimization is the mismatch among model scale, batch size, and per-GPU memory. Common methods include data parallelism, tensor parallelism, pipeline parallelism, sequence parallelism, and expert parallelism. Data parallelism replicates the model and splits data, which is suitable for scaling throughput but introduces gradient synchronization communication. Tensor parallelism splits matrix computation, reducing per-GPU memory but introducing high-frequency communication. Pipeline parallelism splits by layer and can scale across nodes, but it must handle bubbles and micro-batch scheduling. Sequence parallelism fits long-sequence scenarios by splitting the sequence dimension to reduce activation footprint. Expert parallelism targets sparse expert structures and must address load balancing and routing jitter.

    Memory optimization is usually combined with parallelism strategies. Mixed precision can reduce weight and activation footprint, but it requires loss scaling and numerical-stability checks. Optimizer-state sharding can reduce redundant storage. Activation recomputation trades compute for memory, which suits deep networks but increases training time. Parameter and optimizer-state offloading can relieve memory pressure but introduces host-memory and device-transfer overhead. In practice, use profiling tools first to confirm whether the bottleneck is memory, compute, or communication, then decide on the combination.

    Communication optimization is critical for distributed training. Gradient accumulation can increase the effective batch size and reduce synchronization frequency. Overlapping communication with backward computation can hide part of the waiting time. Topology-aware parallel-group partitioning can reduce cross-node traffic. Gradient compression or bucketing can reduce small-packet communication. Pipeline parallelism also requires sensible micro-batch counts and scheduling order to reduce bubbles. Training stability matters as well: data mixture, learning-rate warmup, gradient clipping, checkpointing, and fault recovery should all be part of the plan.

    The following neutral training-configuration pseudocode expresses the combination of parallelism dimensions and memory strategies:

    1. training_plan = {
    2. "global_batch": 1024,
    3. "data_parallel": 16,
    4. "tensor_parallel": 8,
    5. "pipeline_parallel": 2,
    6. "sequence_parallel": true,
    7. "micro_batch": 1,
    8. "gradient_accumulation": 4,
    9. "activation_recompute": "selective",
    10. "precision": "bf16",
    11. "optimizer_state_shard": true
    12. }

    This configuration is not a fixed answer. It shows that tuning should jointly search batch size, parallelism degree, micro-batch size, recomputation, and precision as a group of parameters. After every change, record throughput, peak memory, communication share, and convergence curves to avoid pursuing single-step speed at the expense of convergence.

    3. Inference Optimization: Caching, Batch Scheduling, and Decoding Strategies

    Inference is usually divided into prefill and decode phases. Prefill processes the input sequence in parallel and is compute-intensive; decode generates tokens one by one and is memory-access-intensive. The bottleneck of decoder-only structures often centers on the KV cache: longer sequences and higher concurrency increase cache footprint. Engineering practice can use paged cache management to reduce fragmentation, prefix caching to reuse identical system prompts or common context, cache eviction and capacity limits, and monitoring of cache hit rate and memory watermark.

    Batch scheduling directly affects throughput and latency. Static batching is simple but tends to waste padding when long and short requests are mixed. Continuous batching can dynamically insert new requests as requests complete, improving device utilization. The scheduler should consider maximum batch tokens, maximum concurrency, priority, and timeout policies at the same time to prevent long requests from blocking short ones. For online services, set separate targets for time to first token, time per output token, and tail latency.

    Decoding optimization includes quantization, speculative sampling, operator fusion, and graph optimization. Quantization can reduce weight and cache footprint, but accuracy loss and calibration-data distribution must be evaluated. Speculative sampling uses a small model or lightweight draft stage to propose candidate tokens, which the main model then verifies; this can reduce main-model decoding steps while preserving output quality. Operator fusion and graph optimization can reduce kernel launches and intermediate tensor reads and writes. Tensor parallelism and parallel decoding can reduce single-request latency but increase communication and scheduling complexity.

    The following inference-serving pseudocode is illustrative:

    1. serving_loop(request_queue):
    2. while true:
    3. batch = scheduler.pack(request_queue,
    4. max_tokens=...,
    5. max_batch=...,
    6. priority=...)
    7. cache = kv_manager.allocate(batch, paged=true)
    8. for step in range(max_decode_steps):
    9. logits = model.forward(batch, cache)
    10. next_tokens = sampler.select(logits, temperature=...)
    11. cache.append(next_tokens)
    12. finished = batch.update(next_tokens)
    13. metrics.record(throughput, ttft, tpot, p99)
    14. if finished.all_done():
    15. break

    In practice, ensure correctness and stability first, then enable quantization, cache reuse, and speculative decoding one item at a time. Every optimization should be regressed on the real request distribution to prevent average latency from falling while tail latency worsens.

    4. Performance Evaluation and Engineering Rollout

    Performance evaluation should cover throughput, time to first token, time per output token, P99 latency, peak memory, device utilization, communication share, and cost per request. On the training side, focus on samples per second, scaling efficiency, and convergence stability. On the inference side, focus on latency distributions across input lengths, concurrency levels, and batch sizes. Profiling should be layered: start with end-to-end metrics, then examine stage-level time, and finally locate operators, communication, or memory allocation.

    A recommended tuning process is: establish a reproducible baseline; fix data, configuration, and evaluation sets; change only a small number of variables at a time; record metrics and versions; run correctness and quality regressions on optimization results; and reserve peak headroom in capacity planning. On Baidu AI Cloud, teams can use general-purpose container platforms, object storage, logging services, and monitoring/alerting to build training and inference pipelines, linking model versions, data versions, configurations, metrics, and alerts. Specific resource specifications and scheduling policies should be determined by business SLAs and cost targets.

    Common pitfalls include looking only at single-operator performance while ignoring end-to-end gains; blindly increasing batch size and worsening tail latency; failing to run business evaluations after quantization; mismatching parallelism configuration with network topology; and lacking fault recovery and checkpoint strategies. A reliable approach treats training and inference as one engineering system: training must be reproducible and recoverable, inference must be observable and rollback-capable, and the final result should strike an explainable balance among quality, latency, throughput, and cost.