Engineering Practices for Sparse Activation and Long Context Inference in Large Models

    This article explores engineering practices aimed at optimizing the inference costs of large language models. It covers sparse activation using the Mixture of Experts (MoE) architecture, KV cache management and attention compression for long contexts, and strategies for improving overall model efficiency through training and knowledge distillation.

    I. Background: Inference Cost is Becoming the Primary Constraint for Large Model Deployment

    As the capabilities of large language models improve, their parameter sizes continue to grow, leading to increased computation, memory (VRAM) consumption, and latency during the inference phase. For high-frequency invocation scenarios such as conversational services, code assistance, and AI agent tasks, the cost of a single request is amplified into the total cost of millions of daily calls. Therefore, when selecting models, engineering teams must focus not only on the upper limits of model capability but also on usability per unit cost.

    The industry commonly adopts three main strategies to address this: first, reducing the number of parameters actually participating in each forward pass; second, compressing the attention overhead and cache consumption caused by long contexts; and third, optimizing inference scheduling to reduce the waiting time for token-by-token generation. These are discussed in detail below.

    II. Sparse Activation: Basic Principles of the Mixture of Experts Architecture

    The Mixture of Experts (MoE) architecture splits the feedforward network into multiple expert sub-networks, with a router selecting a small number of experts to participate in the computation for each input token. The total parameter count of the model can be very large, but the parameters actually activated per token account for only a small fraction, thereby decoupling the unit computation volume from the total capacity.

    2.1 Routing Mechanism

    A typical top-k routing process is as follows:

    1. The router computes the score for each token across all experts;
    2. It selects the top k experts with the highest scores;
    3. It computes a weighted sum of the outputs from these k experts based on normalized weights.

    Sample code:

    1. import torch
    2. import torch.nn.functional as F
    3. def top_k_route(hidden, gate_weight, k=2):
    4. # hidden: [tokens, d_model]; gate_weight: [d_model, num_experts]
    5. logits = hidden @ gate_weight
    6. scores = F.softmax(logits, dim=-1)
    7. topk_scores, topk_idx = torch.topk(scores, k, dim=-1)
    8. topk_scores = topk_scores / topk_scores.sum(dim=-1, keepdim=True)
    9. return topk_idx, topk_scores

    This code merely illustrates the basic computational logic of routing. Real-world systems must also handle load balancing, expert capacity limits, and cross-device communication overhead.

    2.2 Relationship Between Total and Activated Parameters

    Assume a model has a total of 100 billion parameters, and each token activates 10 billion parameters, resulting in an activation ratio of 10%. On the same hardware, the computation required for a single forward pass is close to that of a 10-billion-parameter dense model, while the model’s knowledge capacity is still determined by the total 100 billion parameters. This design is well-suited for cost-sensitive scenarios to balance capacity and efficiency.

    A lower activation ratio means finer division of labor among experts, which makes the impact of routing quality on performance more significant. If routing is insufficiently trained, some experts may rarely be invoked, wasting actual capacity—a phenomenon known as expert load imbalance.

    2.3 Deployment Trade-offs

    The memory requirement for MoE models is still calculated based on total parameters, as all expert weights must reside in memory or be distributed across multiple cards via sharding. An improvement in computational efficiency does not equate to a lower deployment barrier. During evaluation, teams should separately account for weight memory usage, activation computation volume, and multi-card communication costs.

    III. Long Context Cost Bottlenecks and Attention Compression

    3.1 KV Cache Memory Estimation

    During autoregressive generation, the model needs to cache the key-value vectors of historical tokens (the KV cache). Its consumption can be roughly estimated as:

    KV Cache Bytes ≈ 2 × Number of Layers × KV Heads × Head Dimension × Sequence Length × Bytes per Element

    Example: For 32 layers, 8 KV heads, 128 head dimension, 100,000 sequence length, and 2 bytes per element (FP16 or BF16), the cache size is about 2 × 32 × 8 × 128 × 100,000 × 2 ≈ 1.3×10^10 bytes, or roughly 13GB. This does not even account for the concurrency multiplier introduced by batching. Sequence length is the primary factor determining memory pressure.

    1. def kv_cache_bytes(layers, kv_heads, head_dim, seq_len, dtype_bytes=2):
    2. return 2 * layers * kv_heads * head_dim * seq_len * dtype_bytes

    3.2 Basic Idea of Sparse Attention

    The computational complexity of standard attention grows quadratically with sequence length. Sparse attention restricts each query to attending to only a subset of keys and values. Common methods include:

    • Local window: Attending only to neighboring tokens;
    • Global anchors: Retaining a few key tokens that remain always visible;
    • Content-based selection: Dynamically selecting candidate keys and values based on relevance.

    The common goal of these methods is to reduce the number of keys and values involved in the computation. The impact of information loss on long-range dependency tasks must be verified through experiments.

    3.3 Compressed Attention

    Another approach is to compress the key-values of historical tokens along the sequence dimension, for instance, by merging the key-values of several adjacent tokens into a single summary representation. The higher the compression rate, the smaller the cache, but the greater the loss of fine-grained information. Engineering practices often adopt a hierarchical strategy: maintaining fine-grained representations for close distances and using highly compressed representations for far distances. This hybrid design is commonly seen in long-document question answering and code repository understanding tasks.

    IV. General Practices for Training and Distillation

    Model efficiency does not depend solely on architecture. The data scale, data quality, and post-training strategies during the training phase also significantly affect the performance of smaller models. Common practices include:

    • Using large-scale, multi-domain corpora during the pre-training phase, while controlling for duplicate and low-quality data;
    • Employing knowledge distillation, where a smaller student model learns the output distribution of a larger teacher model;
    • Constructing specialized data for tasks like reasoning, mathematics, and coding, followed by reinforcement learning fine-tuning.

    The core of distillation lies in having the student model mimic the teacher model’s soft labels, rather than just the hard labels. The temperature parameter is used to smooth the output distribution, enabling the student model to learn the relative relationships between different categories.

    V. Inference Acceleration: Speculative Decoding