Scaling Up Large Language Models: Sparse Experts, Attention Compression, and Long-Context Techniques

    This article explains the core architectural techniques behind today's large language models: sparse mixture-of-experts layers, attention cache compression, long-context support, and token-efficient training. It covers how each technique works, what engineering trade-offs it involves, and how developers can evaluate and select a model for their deployment needs.

    1. Background: Why Mainstream Architectures Are Converging

    Over the past two years, leading large language models from Chinese and international teams have increasingly converged on a common architecture. Most use a Transformer-based decoder, add mixture-of-experts (MoE) layers to the feed-forward network, compress the key-value cache in the attention layers, and extend positional encoding to support long text. The differences between models now lie mostly in data mixtures, training procedures, and engineering optimizations.

    This convergence has clear causes. The compute and memory costs of a Transformer grow with parameter count and context length. With limited compute, teams can only choose approaches that have been validated and then make trade-offs in the details. Understanding these shared foundations helps developers avoid being misled by marketing terms and focus on what each technique solves and what it costs.

    2. Sparse Mixture of Experts: Trading Parameter Count for Compute Efficiency

    In a dense model, every parameter takes part in computing each generated token. An MoE model splits the feed-forward layer into multiple expert networks. A router selects a small number of experts for each token. The total parameter count can be very large, but each token activates only a small subset of parameters. As a result, the inference cost per token is lower than that of a dense model of the same size.

    Routing usually uses a top-k strategy. The router first scores every expert, then keeps the k highest-scoring experts and normalizes their weights. The following is a simplified example:

    1. import torch
    2. import torch.nn.functional as F
    3. def moe_forward(x, gate_weight, experts, top_k=2):
    4. # x: [num_tokens, hidden]
    5. logits = x @ gate_weight # [num_tokens, num_experts]
    6. probs = F.softmax(logits, dim=-1)
    7. topk_p, topk_idx = probs.topk(top_k, dim=-1)
    8. topk_p = topk_p / topk_p.sum(dim=-1, keepdim=True)
    9. out = torch.zeros_like(x)
    10. for e, expert in enumerate(experts):
    11. mask = (topk_idx == e)
    12. rows = mask.any(dim=-1).nonzero(as_tuple=True)[0]
    13. if rows.numel() == 0:
    14. continue
    15. weight = (topk_p * mask).sum(dim=-1)[rows]
    16. out[rows] += weight.unsqueeze(-1) * expert(x[rows])
    17. return out

    This code omits distributed communication and capacity limits, but it shows the core logic. Each token enters only a few experts, and the outputs are merged using their routing weights.

    MoE has three main engineering challenges. First, load imbalance: some experts are selected frequently while others sit almost idle. Common remedies include an auxiliary loss and capacity factor constraints. Second, cross-device communication: when experts sit on different accelerators, distributing tokens and gathering results adds significant latency. Third, training instability: small changes in the router can cause sudden shifts in how experts specialize.

    There is a trade-off between the number of experts and sparsity. More experts increase model capacity, but routing complexity and communication overhead also rise. In practice, teams usually set the expert count based on their inference hardware topology and target latency, rather than maximizing total parameter count.

    3. Attention Compression: Reducing Inference Memory and Compute

    During autoregressive inference, the model must cache the keys and values of previous tokens (the KV cache). The cache size grows with the number of layers, the number of heads, the head dimension, and the context length. In long-context workloads, the KV cache often exhausts GPU memory faster than the model weights, and it becomes the bottleneck for concurrency.

    Three common directions for compression are:

    1. Reducing heads or sharing key-value heads: Grouped-query attention lets multiple query heads share one set of key-value heads. This significantly reduces cache size and usually has a small effect on quality.
    2. Low-rank latent representations: Keys and values are projected into a lower-dimensional latent space before caching, then reconstructed when needed. This approach balances memory use and compute, but it requires extra projection computation.
    3. Reducing the total number of attention heads: Fewer heads lower the compute cost, but each head has less expressive power. To maintain overall capability, this approach must be paired with a larger hidden dimension or more experts.

    The right option depends on the target scenario. ForServing with high concurrency, cache compression should come first. When per-request compute latency is the main constraint, the efficiency of the attention kernel and the degree of operator fusion matter more.

    4. Long-Context Capability: From Positional Encoding to Engineering

    Long-context capability has two parts. The model must keep position awareness beyond its training length, and the system must handle long inputs within acceptable memory and latency limits.

    Positional encoding is the first hurdle. Rotary positional encoding (RoPE) performs stably within the training length. Beyond that length, common methods interpolate or scale the frequencies, then continue training on a small amount of long-text data. These changes must be checked to confirm that performance on short texts has not noticeably degraded.

    At the engineering level, long inputs bring quadratic costs in attention computation. Common optimizations include chunked attention, combining sliding windows with global tokens, and splitting long documents into segments for retrieval. For tasks that require close reading, retrieval augmentation and segment-level summarization are often more reliable than simply enlarging the context window.

    When evaluating long-context capability, do not rely only on the advertised window length. At least three metrics are worth tracking: needle-in-a-haystack retrieval accuracy (placing key information at different positions in a long text and checking whether the model recalls it), consistency in long-document question answering, and how time to first token and throughput change as input length increases.

    5. Training Optimization: Optimizers and Token Efficiency

    The core training question is how to obtain better capabilities from a limited supply of high-quality data. As high-quality human-written text is increasingly used up, token efficiency is becoming a key variable when scaling models. Token efficiency refers to the capability gained per training token.

    For optimizers, mainstream methods are still adaptive optimizers, adjusted with learning rate schedules, gradient clipping, and weight decay. In recent years, new optimizers based on approaches such as orthogonalized matrix updates have also appeared. Their goal is to improve the quality of updates and the convergence speed for large matrix parameters. When evaluating these methods, developers should look at convergence curves under the same compute budget and at sensitivity to hyperparameters.

    Improving token efficiency usually relies on three steps: data cleaning and deduplication, balancing data by domain and difficulty, and adjusting the data distribution across training stages (curriculum-style training). These steps often yield larger gains than simply adding more data.

    6. Engineering Deployment and Selection Guidelines

    When using a large model in a business setting, its architectural properties must match the deployment conditions. The following table lists common selection dimensions:

    Dimension Focus Typical Impact
    Inference cost Activated parameters per token, batching capability Determines the cost per request
    Context length Effective window, long-text retrieval performance Affects document processing and knowledge Q&A
    Latency Time to first token, generation speed Affects real-time interaction experience
    Deployment method Private deployment, containerization, managed service Affects data security and operations effort
    Customizability Fine-tuning interfaces, degree of open weights Affects room for further development

    At the infrastructure level, model services usually need object storage for data and checkpoints, a container platform for elastic scaling, and logging and monitoring with alerting to detect performance fluctuations. These general-purpose capabilities determine whether a model runs stably, and they matter as much as the model architecture itself.

    7. Evaluation Methods and Common Pitfalls

    Public leaderboards offer a useful reference, but business performance must be measured with your own evaluations. We recommend the following steps:

    • Sample representative cases from real business workloads, covering common requests and edge cases;
    • Define quantifiable metrics for each task type, such as accuracy, factual consistency, and format compliance rate;
    • Record latency, throughput, and cost under the same hardware and concurrency conditions;
    • Run regression tests regularly to track behavior changes across model version updates.

    Common pitfalls include judging capability by total parameter count alone, treating the advertised context length as the effective length, and ignoring inference cost and concurrency capacity. A sound approach is to weigh architectural properties, training data, engineering conditions, and business metrics together.

    8. Summary

    Leading large language models have moved toward similar approaches in sparse experts, attention compression, long-context support, and training efficiency. The differences lie mainly in implementation details and engineering trade-offs. Developers should understand the principles and costs of each technique, choose based on the latency, cost, and data conditions of their own use case, and validate results with their own evaluations.