Joint Training Methods for Sparse Experts and Ultra-Long Context

    Ultra-long context and sparse mixture-of-experts are often treated separately, but native vision, million-token inputs, and long-horizon tool use put numerical range, routing balance, and effective depth on the same training curve. This article explains how to bound linear-attention decay, balance experts without an auxiliary loss, share attention across blocks, stage context length, and test long-horizon post-training so those failures stay observable.

    Ultra-long context and sparse mixture-of-experts are often discussed apart: the first is about attention compute and memory, the second about whether routing collapses. Once a model must also handle native visual understanding, million-token inputs, and long-horizon tool calls, all three sit on the same training curve. Stretch the window and accumulated decay in a linear recurrence pushes low-precision floats into overflow or underflow. Pack in more experts and a few routes consume almost every token, while an auxiliary loss easily fights the main loss for gradient. Add depth and every layer recomputes attention, so communication and activation memory rise together, yet later layers may not receive a more usable representation. The sections below separate these conflicts by mechanism, not by any particular release note.

    1. Collapse the compute graph into a few checkable stages

    A practical skeleton usually looks like this: a multimodal encoder maps image or document chunks into the same embedding space as text; the backbone replaces most feed-forward layers with a sparse mixture-of-experts and activates only a small subset; attention mixes an exact but expensive quadratic term with a linear recurrence that is easier to extrapolate, and cross-layer residuals let later layers reuse context already computed earlier; training warms up by context length, then post-training separates policies with verifiable long-horizon tasks.

    Scale itself is not a guarantee of stability. Total parameters can be large, but the active path each token actually walks must stay short, the numeric range must stay controllable, and expert load must stay observable. Engineering should assume three failures at once: low-precision diagonal blocks compute incorrectly, routing entropy collapses, and gradients on a million tokens are drowned in noise. Put those three items on the design-review checklist instead of patching after the loss becomes NaN.

    2. A lower bound on decay so linear attention can stay in matrix multiplies

    Linear attention, or incremental state updates, usually keeps a state that decays with position. In a blocked implementation, blocks multiply by a cumulative decay, and the interior of a block must also handle the “diagonal block”: the relative decay between every pair of positions inside the same block. If the log decay has no lower bound—for example, only a negative softplus—the decay factor on a long block becomes tiny, and its reciprocal underflows to zero or overflows to infinity in half precision. Implementers then fall back to a per-position scalar path. Specialized matrix-multiply units stay underfilled, and both throughput and correctness get worse. The problem is sharper with no positional encoding and a bet on length extrapolation, because there is no extra position term to clamp the dynamic range.

    A more stable parameterization puts a negative lower bound on the log decay and maps the learnable quantity into that interval with a bounded function, such as a scaled sigmoid. The bound does not need to be a mysterious constant. The rule is: for the block size you chose—often from the low teens to a few dozen tokens—the reciprocal scaling inside the block must stay representable in half precision and well clear of subnormal numbers. Diagonal and off-diagonal blocks can then both be dense matrix multiplies. Branches disappear, kernels fuse more easily, and you reduce the precision split between “one kernel for training, another for inference.”

    When landing this, do four things together. First, write the rounding order of decay, state, and output into the operator contract so the training framework and the inference engine do not each reorder once. Second, align short sequences and compare block outputs with and without the lower bound; set the tolerance from half-precision relative error, not from the final loss alone. Third, at the target maximum length, spot-check that the state norm is monotonic with distance and that whole spans do not go to zero. Fourth, do not judge extrapolation by perplexity alone. Also check whether retrieval position degrades with distance, because a linear recurrence is most likely to drop a clue far away.

    3. Quantile balancing without an auxiliary loss

    When the expert count reaches the hundreds or nearly a thousand, a classic auxiliary load-balancing loss has two side effects. Its weight is hard to tune: a little too large and it hurts the language or vision main task; a little too small and routing collapses again when the learning rate changes or the data mix shifts. The auxiliary loss also assumes that global uniformity is optimal, which does not match real corpora—code, tables, and image captions should not be forced into the same experts.

    Quantile balancing works differently. Over a time window, collect the quantiles of how often each expert is chosen, or of the routing scores, and pull experts that are too high or too low back into a moving band instead of yanking them toward a fixed uniform target. The center of the band can follow the task mix of the current batch, so specialization is allowed and starvation is not. It behaves more like a controller than a second term in the total loss, so it conflicts less with the main gradient.

    Watch the window and the batch. Too short, and quantile jitter makes routing jump; an expert barely memorizes a pattern before it is reassigned. Too long, and balancing lags, so under sparsity a few experts can still monopolize tokens for thousands of steps. In practice, keep the statistics inside the data-parallel group and update them with an exponential moving average by step. That is cheaper than recomputing a global histogram every micro-batch, and less likely to be skewed by a sudden burst of one modality. Monitor at least: the fraction of experts that activate, the ratio of highest to lowest load, routing entropy, and the number of experts whose load stays below a threshold for several consecutive steps. The last signal exposes collapse earlier than average load.

    When experts are extremely sparse, the capacity factor and the drop policy must be tuned with the balancer. Balancing scores without a per-expert token cap still leaves hot experts as communication hotspots. The reverse is the same: a cap that is too tight and a balancer that is too aggressive drop tokens often, and the main task shows up as a sudden quality drop in the second half of long documents.

    4. Block attention residuals: depth should also save compute

    As the layer count grows, not every layer needs a full context aggregation from scratch. If several adjacent layers share one attention output and inject it into the current layer with a learnable residual scale, later layers can spend capacity on expert compute instead of moving the same keys and values again. Sharing by block fits a pipeline better than sharing layer by layer: the number of layers inside a block is fixed, activations can stay resident, and the next update happens across blocks, which cuts all-to-all communication under tensor parallelism.

    The risk is an oversized residual scale. Deep layers then stop producing new context features. The model looks deep, but effective depth stops in the first few blocks. Early in training, keep the residual coefficient near the identity so gradients are not amplified on the shared path; later, let blocks diverge. The check is simple: compare cosine similarity of attention outputs between neighboring blocks. If it stays near 1 the whole way, sharing is excessive. If every layer stays near 0, the residual is not saving compute; it is only an extra branch that is hard to optimize.

    On memory, sharing means the key-value cache can grow by block rather than by layer. At a million tokens, the cache often fills before the parameters do. Design cache granularity to match the block residual instead of quantizing afterward. Quantization is still useful, but apply it after the numeric range has already stabilized. Otherwise quantization error stacks with decay underflow and is hard to attribute.

    5. Do not turn on multimodality and a million tokens on day one

    Vision tokens and text tokens usually differ in length distribution and norm scale. If you start on day one with million-token mixed sequences, routing and decay adapt to both scales at once. The log only shows a swinging loss, and you cannot tell modality alignment failure from sparse instability. A curriculum is more workable: first, on a short window, train tokenization, the vision projection, and expert routing until they are interpretable; then move to tens of thousands of tokens and turn on cross-segment retrieval data; then to hundreds of thousands, and check that state remains distinguishable as it decays with distance; only then go to a million, and keep replaying short-window data so the model does not forget local syntax.

    At each stage change, change one main variable: window length, expert count or capacity, or modality mix. Change all three and you cannot ablate. For the first steps after a switch, freeze the balancer or slow its response so routing does not violently reshuffle under the new length distribution. On the data side, prefer samples where the evidence is far away and the question is near, not meaningless repeated padding. Otherwise the model learns to ignore the second half while the evaluation still looks like a very long context.

    6. Post-training should test long horizon, not just longer concatenation

    Pretraining solves “can see.” Agent post-training solves “will use it step by step.” If a million tokens only means stuffing more documents into the prompt, the model can still forget the constraint from step one by the third tool call. Post-training tasks need intermediate states that can be judged automatically: whether a retrieved span was cited, whether a plan closed within the step budget, and whether an observation was written back to working memory. If the reward looks only at the final answer, the sparse signal lets a long-chain policy decay into guesswork.

    In engineering, cut trajectories into replayable segments and align them with the context curriculum: short chains with a high success rate first, then longer observations and more branches. Split failures into “the context never contained the evidence” and “the evidence was there but the state decayed it away.” Only the second should feed back into attention numeric range and cache policy, rather than simply enlarging the reward model.

    7. A minimal checklist before serving

    Operators: on the same random input, the maximum relative error between blocked linear attention and a naive recurrence is acceptable at the target block length, with no underflow warnings. Routing: no expert stays at zero load across a continuous window, and communication time for hot experts does not worsen linearly with the total expert count. Depth: block-residual similarity sits in a middle band, and sampled layers still pass both near and far probes. Curriculum: every length stage has a regression set with a frozen configuration, not only the final million-token score. Serving: prefill and decode use the same cache layout, and image tokens in a multimodal batch do not saturate the text experts. Logs: record how often the decay lower bound is hit, the share of samples outside the quantile band, and cache hits versus recomputes. Those three forecast quality incidents better than a single average latency.

    None of these practices depends on a proprietary model name. They match the numeric-range, load, and effective-depth problems that appear when sparsity, long context, and multimodality stack together. Write the lower bound, the quantiles, and the block residual as testable contracts, then pair them with a single-variable length curriculum and judgeable long-horizon post-training. Stability then has a chance to move from a paper narrative to a training system you can operate.