Scaling Sparse MoE Models and Million-Token Context: A System-Level Rework

    This article explains how to move from headline parameter counts to a system-level design for ultra-large sparse Mixture-of-Experts (MoE) models with million-token context windows. It separates total parameters, sparse activation size, and context length; outlines why long context is a structural requirement; and walks through the three core rework areas—attention, MoE routing and expert parallelism, and kernels plus memory—along with evaluation practices and a deployment checklist.

    Scaling Sparse MoE and Million-Token Context: From Paper Parameters to System-Level Rework

    1. Read the Paper Parameters Correctly: Total Parameters, Sparse Activation, and Context Length

    When discussing ultra-large sparse models, the most common mistake is conflating three numbers: total parameter count, sparse activation per token, and context window length. They determine training cost, inference compute, and memory/bandwidth pressure respectively, and none can substitute for another.

    A typical two-tier setup can be understood as follows:

    Tier Total parameters Sparse activation Context window
    Large ~1.6T ~49B Million-level by default
    Small ~284B ~13B Million-level by default

    Two points need clarification:

    • The small tier is not a distilled version of the large one. Both tiers are independently pre-trained MoE models. The difference lies in the number of experts, routing sparsity, and training budget—not in “compression from the same source.” Distillation is only one path for model compression and is a separate matter from “same family, different scale.”
    • Long context is not a toggle. Both tiers support million-level context by default, and the serving side no longer maintains two separate routes for “long-text models” and “short-text models.” This means capacity planning must be done for the worst case (a full window), not for the average request length.

    What really determines feasibility is the second number: the 49B and 13B activation sizes determine the floating-point operations per token, while the total parameter count determines memory footprint and expert sharding strategy. The two differ by an order of magnitude, and their cost structures are completely different.

    2. Why Ultra-Long Context Is Needed

    Long context is not decoration for a parameter race; it is a structural requirement for several real scenarios:

    1. Repository-level code understanding. Cross-file references, type definitions, build scripts, tests, and documentation all need to be in view at once; retrieval-based chunking breaks the integrity of the call chain.
    2. Long-document and multi-document reasoning. Contracts, financial reports, logs, and papers require global comparison; local summaries lose the mutual constraints across sections.
    3. Agent trajectory accumulation. Observations, errors, and intermediate artifacts from multiple rounds of tool calls keep piling up; context is the Agent’s “working memory.”
    4. Few-shot and long instructions. Providing the specification, examples, and boundary conditions all at once is more stable than repeated clarification.

    The cost is equally clear: attention overhead grows superlinearly with sequence length, and the KV cache expands linearly with length. Without system-level rework, a million-token context is not usable in engineering terms.

    3. System-Level Rework One: The Attention Mechanism

    The first bottleneck for long context is attention. Common directions in the industry include:

    • Sparse and block attention: restrict global attention to a local window plus a small number of global tokens, reducing complexity from quadratic to near-linear.
    • Multi-query/grouped-query attention (MQA/GQA): compress the number of KV heads to directly reduce cache size and bandwidth pressure.
    • Low-rank KV compression: project keys and values into a low-dimensional latent space, trading a small cache for an approximation of the full effect.
    • Linear attention and hybrid layers: some layers use linear/gated structures for long-range modeling, while a few layers retain full attention for precise retrieval.

    An illustrative complexity comparison (showing only order-of-magnitude relationships):

    1. Full attention: O(L^2 * d)
    2. Window + global sparse: O(L * w * d) + O(L * g * d) # w is window, g is number of global tokens
    3. Linear attention: O(L * d^2)

    The engineering caveat: sparsification changes the degree of parallelism, and block size must be tuned together with the kernels and memory hierarchy. Otherwise, theoretical complexity drops but measured throughput does not improve.

    4. System-Level Rework Two: MoE Routing and Expert Parallelism

    Sparse activation decouples compute from capacity but introduces new engineering problems:

    • Load imbalance. A few popular experts get overloaded while the rest sit idle. The common approach is a capacity factor plus an auxiliary load-balancing loss, with random routing noise added when necessary.
    • Communication amplification. After experts are sharded, each token needs all-to-all dispatch and collection across devices, and communication becomes the main contributor to end-to-end latency.
    • Group-limited routing. Restricting which expert groups a single token can hit reduces cross-node traffic, at the cost of slightly lower expressiveness.
    • Shared experts. Keeping a small number of always-active experts to carry general knowledge lets the routed experts focus on differentiated features.

    Pseudocode for the routing and dispatch in one forward pass:

    1. logits = gate(x) # [tokens, num_experts]
    2. scores, idx = topk(logits, k) # sparse selection
    3. weights = softmax(scores) * capacity_mask(idx)
    4. y = zeros_like(x)
    5. for e in unique(idx): # group by expert to reduce communication rounds
    6. tokens_e = gather(x, idx == e)
    7. y_e = experts[e](tokens_e)
    8. y = scatter_add(y, tokens_e, y_e * weights_e)

    5. System-Level Rework Three: Kernels and Memory

    Turning paper parameters into usable throughput ultimately comes down to kernels and memory:

    • Kernel fusion: fuse normalization, projection, activation, and routing scores to reduce HBM round trips; in memory-bound scenarios, fusion often yields more than compute optimization.
    • Quantization and low precision: store weights and activations at lower precision and quantize the KV cache, trading precision for capacity; this requires calibration and outlier handling.
    • Paged cache management: manage KV blocks using the paging idea from operating systems to reduce fragmentation and support prefix sharing.
    • Combining parallelism strategies: tensor parallelism splits a single layer, pipeline parallelism splits layers, expert parallelism splits experts, and context parallelism splits the sequence; the four must be jointly searched according to the topology.
    • Scheduling and batching: continuous batching plus chunked prefill prevents long requests from blocking short ones; chunked prefill for ultra-long inputs reduces jitter in time-to-first-token.

    6. Evaluating Results: What It Means to Be in the Top Tier on Four Dimensions at Once

    Being in the top tier simultaneously on coding, math, Agent, and long-text dimensions indicates balanced capability rather than a single strong point. Evaluation should avoid looking only at aggregate scores:

    • Break it down by dimension: for code, look at cross-file completion and repository-level Q&A; for math, look at multi-step derivation and self-checking; for Agent, look at the success rate of long-range tool calls; for long text, look at global retrieval and cross-section constraints.
    • Look at the long tail: average scores hide long-tail failures, so the distribution of failure types needs to be measured.
    • Look at cost: evaluate on three dimensions—cost per million tokens, time-to-first-token, and throughput—rather than a single accuracy metric.
    • Look at stability: the variance across multiple samples of the same prompt directly affects production usability.

    7. Deployment Checklist

    1. Do capacity planning for a full window first, then optimize for average length.
    2. Load-test with replayed real business traffic, covering mixed scenarios of ultra-long inputs and concurrency.
    3. Prioritize cache hit rate over peak compute: prefix sharing and system-prompt reuse deliver significant gains.
    4. Build a segmented evaluation set to prevent “lost in the middle” in long context from being masked by average scores.
    5. On the inference side, combine general cloud capabilities: a container platform for elastic scaling, object storage for models and corpora, a message queue for request peak shaving, and logging plus monitoring and alerting for full-link observability.
    6. Put cost governance first: set context budgets and truncation policies, and distinguish “can be filled” from “worth filling.”

    8. Conclusion

    The competitiveness of ultra-large sparse models does not come from one impressive number but from the coordinated rework of attention, routing, kernels, memory, and scheduling. Understanding the difference between total parameters and activation size, and treating long context as a capacity problem rather than a toggle, is the prerequisite for making the right architecture decisions. The general engineering practices at Baidu AI Cloud in related areas can also serve as a reference for capacity planning and building an observability system.