LLM Architecture Selection: Technical Trade-offs in Sparse MoE, Attention Optimization, and Training Stability

    This article explores the technical trade-offs in Large Language Model (LLM) architecture selection, focusing on Sparse Mixture of Experts (MoE), attention optimization, and training stability. It explains why mainstream LLM architectures are converging and provides actionable insights on evaluating MoE models, optimizing KV cache in attention mechanisms, estimating inference costs, and maintaining training stability through proper optimizer choices and continuous monitoring.

    I. Why Mainstream LLM Architectures Are Converging

    The capabilities of Large Language Models (LLMs) are primarily constrained by parameter scale, training data volume, and compute budget. Since the stabilization of the Transformer framework, competition among teams has shifted toward three objectives: improving parameter utilization under fixed compute, reducing inference costs, and stabilizing the training process. Consequently, designs across different teams often converge on several key modules, with true differences mostly reflected in hyperparameter ratios and engineering implementations.

    Understanding this helps developers focus on the mechanisms themselves rather than specific model names. The following sections explore four main themes: computation efficiency, inference cost, training stability, and data efficiency. Each section provides principles, trade-offs, and actionable evaluation methods.

    II. Sparse Mixture of Experts: Decoupling Total Parameters from Per-Token Computation

    In dense models, every token passes through all parameters, meaning computation scales linearly with parameter count. The Mixture of Experts (MoE) architecture places multiple expert networks in the feedforward layer, where a router selects only a few experts for each token. The model’s total parameter count can be very large, while a single forward pass only activates a fraction of them.

    When evaluating MoE models, it is crucial to distinguish between two metrics:

    • Total parameters: Determines the upper limit of model capacity and the memory footprint for weight storage in VRAM or distributed storage.
    • Activated parameters: Determines the computation volume for a single token, serving as the primary source of inference latency and throughput.

    Assuming a total of E experts and k activated experts per token, the activation ratio for the feedforward layer is approximately k/E. For example, if E=256 and k=8, a single token in the feedforward layer only computes about 3% of the expert parameters. This figure is for illustrative purposes and does not represent any specific model configuration.

    2.1 Routing and Load Balancing

    The router is typically a linear layer followed by a softmax, selecting the top-k experts based on their scores. Below is a simplified routing code snippet:

    1. import torch
    2. import torch.nn.functional as F
    3. def topk_route(hidden, gate_weight, k=2):
    4. # hidden: [num_tokens, d_model]
    5. # gate_weight: [d_model, num_experts]
    6. logits = hidden @ gate_weight # [num_tokens, num_experts]
    7. probs = F.softmax(logits, dim=-1)
    8. topk_probs, topk_idx = probs.topk(k, dim=-1)
    9. # Re-normalize the selected weights so they sum to 1
    10. topk_probs = topk_probs / topk_probs.sum(dim=-1, keepdim=True)
    11. return topk_idx, topk_probs

    If routing relies solely on scores, a few experts may be selected frequently while others receive almost no training. A common industry practice is to add an auxiliary loss to encourage a uniform distribution of token counts and routing probabilities across experts. The formulation used in works like the Switch Transformer is:

    L_aux = α · E · Σᵢ fᵢ · Pᵢ

    Where fᵢ is the fraction of tokens assigned to expert i, Pᵢ is the average routing probability for expert i, and α is the coefficient. If α is too large, it suppresses the model’s ability to learn expert division of labor; if too small, the load imbalance remains unresolved. It requires tuning on a validation set.

    2.2 Trade-offs Between Expert Count and Sparsity

    Increasing the number of experts generally improves model capacity but introduces the following constraints:

    1. Increased communication overhead: In expert parallelism, tokens must be distributed to different devices via all-to-all communication and then retrieved. More experts mean higher communication volume.
    2. Fewer samples per expert: Each expert receives fewer tokens, increasing the variance in gradient estimation, which is especially noticeable during small-batch training.
    3. Capacity overflow: To prevent a single expert from overloading, a capacity factor is usually set. Tokens exceeding the capacity are dropped or bypass the layer, affecting effective computation.

    In engineering, expert parallelism is typically combined with data and pipeline parallelism. Before increasing the number of experts, one should estimate whether the communication bandwidth can handle the additional distribution costs and compare validation losses across different expert counts under the same activated parameter count.

    III. Attention Mechanism: The KV Cache Bottleneck in Inference

    During autoregressive generation, the model must cache the keys (K) and values (V) of historical tokens to avoid redundant computation. The KV cache size for a single sequence can be estimated using the following formula:

    Memory ≈ 2 × Layers × KV Heads × Head Dimension × Sequence Length × Bytes per Element

    Taking FP16 as an example, each element occupies 2 bytes. As sequence length and concurrency increase, cache consumption grows rapidly and may become the throughput bottleneck before computational capacity does.

    3.1 Common Approaches to Cache Compression

    Approach Method Benefit Cost
    Reduce attention heads Decrease the number of query or KV heads per layer Reduces attention computation and cache overhead Decreased representational diversity; requires quality loss validation
    Grouped-Query Attention Multiple query heads share the same KV head group Cache reduced by the grouping factor Potential quality degradation in specific tasks if grouping is excessive
    Low-rank latent compression Project K and V into a low-dimensional latent space for storage Significantly reduces cache size Requires additional projection and reconstruction computation; high implementation complexity

    The approach of reducing head count warrants separate clarification. In models with a large hidden dimension, halving the number of heads might increase the dimension per head, reducing the total attention computation. However, whether this adjustment impacts quality must be evaluated separately across long-context, coding, and mathematical tasks, not just by looking at perplexity.

    3.2 Estimating Inference Costs

    When estimating the cost of a single request, it is recommended to calculate the prefill and decode phases separately:

    • The prefill phase processes the entire input. Computation scales roughly linearly with input length, making it suitable for measuring via parallel throughput.
    • The decode phase generates tokens sequentially. It is limited by memory bandwidth and KV cache reads, meaning single-request latency is primarily determined by the memory access volume per step.

    Because the bottlenecks differ between the two phases, the same model will perform very differently across scenarios like Q&A, long-document analysis, and code completion.

    IV. Optimizers and Training Stability

    4.1 Choosing the Right Optimizer

    Adaptive optimizers (like AdamW) remain the default choice for LLM training. Recent research has explored structured optimizers designed for 2D weight matrices, such as orthogonalizing the momentum matrix to balance update magnitudes across different directions. The value of these methods should be evaluated by comparing loss curves against AdamW under the same token count, while observing training throughput and memory overhead, rather than just looking at the final metrics of a single experiment.

    4.2 Attention Logits Overflow

    During training, the dot-product scores between queries and keys may continuously increase. When scores become too large, the softmax saturates, gradients become unstable, and the loss may spike or even diverge. Common mitigation techniques include:

    • QK Normalization: Normalizing queries and keys before computing the dot product to limit the numerical range of the scores.
    • Score Clipping: Monitoring the maximum score per attention head and scaling the corresponding query or key projections proportionally when a threshold is exceeded to suppress growth.
    • Learning Rate and Initialization Adjustments: Using conservative learning rate warmups and weight initialization to reduce early-stage instability risks.

    A conceptual monitoring logic snippet is as follows:

    1. def monitor_attention_logits(scores, threshold=50.0):
    2. # scores: [batch, heads, q_len, k_len], unscaled QK dot product
    3. max_per_head = scores.abs().amax(dim=(0, 2, 3))
    4. overflow_heads = (max_per_head > threshold).nonzero().flatten()
    5. return max_per_head, overflow_heads

    The threshold needs to be determined based on the specific model and numerical precision; the value above is for illustrative purposes only.

    4.3 Daily Monitoring Metrics for Stability

    During training, it is recommended to track at least the following metrics:

    • The divergence between training loss and validation loss.
    • Global gradient norm; a sudden increase is usually a precursor to anomalies.
    • Maximum logit per attention layer.
    • Token distribution ratio per expert, used to detect load imbalance.
    • The number of numerical overflows or underflows, especially in low-precision training.

    When a loss spike occurs, one should first roll back to the most recent stable checkpoint, then investigate the relationship between the data batch and the learning rate, rather than directly lowering the target metrics.

    V. Token Efficiency and Data Strategy

    Under the same token count, how much a model ultimately learns depends on three factors: data quality, training methods, and architectural design. As the availability of high-quality public text continues to…