Long-Sequence Linear Attention: Numerical Stability and Architecture Practices
Stable long-context models require more than efficient attention formulas. This article examines three complementary engineering changes: bounded decay gates for half-precision blockwise linear attention, quantile-based calibration for mixture-of-experts routing, and block-level residual connections for deep networks. It explains their numerical and systems motivations, implementation boundaries, and validation criteria without relying on unverified speedup claims.
Long-context modeling is moving beyond “making it run” toward stable execution, scalable training, and high throughput on existing matrix hardware. Linear attention replaces position-by-position interactions with recurrent or blockwise state updates, reducing the theoretical dependence on sequence length from quadratic to approximately linear. Mixture-of-experts (MoE) architectures use conditional computation to increase parameter capacity.
When these techniques are combined in deep networks, the bottleneck is often not the elegance of the formulas. It is the numerical range of half precision, persistent load imbalance, and whether activations and gradients can still propagate effectively through many layers.
Three reusable changes address these constraints at different levels: bounded decay parameterization, quantile-based routing calibration, and block-level residual connections. Each has a specific purpose—and implementation boundaries that matter as much as the high-level idea.
1. The Real Bottleneck in Blockwise Linear Attention
Standard attention explicitly constructs pairwise similarities between queries and keys. As sequences grow, the intermediate matrices and communication requirements become difficult to manage.
Linear attention uses kernel mappings or incremental state updates to compress historical information into a fixed-width state. Decoding and long-prefix processing can then advance block by block. A typical implementation divides the sequence into fixed-length blocks, carries recurrent state between them, and computes local contributions within each block using dense matrix multiplication.
The goal is to process both diagonal and off-diagonal blocks through the same matrix-multiplication path. This allows the implementation to use general-purpose tensor compute units rather than falling back to elementwise loops over position pairs.
Why decay causes numerical problems
Decay is one of the most sensitive coefficients in a linear recurrence. Many gated or incremental formulations maintain a per-channel log-decay value and convert it into multiplicative factors inside each block.
The computation may also require reciprocals or ratios of those factors. These align information accumulated from the block’s starting position with contributions viewed from other positions inside the block.
Without a lower bound on log decay, cumulative scaling can push multiplicative factors toward zero and their reciprocals toward infinity in half precision. Once this happens, a diagonal block can no longer be treated as an ordinary matrix multiplication. Implementers may need a separate position-pair path to handle underflow, overflow, and special masks.
That branch has three direct consequences:
- Lower tensor-core utilization. Position-pair processing resembles scalar or small-vector computation more than dense matrix multiplication.
- Inconsistent numerical paths. Diagonal and off-diagonal blocks follow different arithmetic paths, increasing the risk of discontinuities at block boundaries in long sequences.
- Poorer long-context extrapolation. Models without positional encoding may rely on decay to distinguish nearby from distant tokens. At extreme lengths, numerical defects can become attention collapse or state explosion.
The central issue is therefore not just whether the recurrence is mathematically valid. It is whether every scaling operation used by the blockwise implementation remains numerically safe.
2. Replace Unbounded Negative Softplus with Bounded Decay Gates
A common parameterization applies softplus to a raw gate and negates the result. The resulting log decay is nonpositive, but it has no finite lower bound.
This allows the model to learn arbitrarily steep decay. Even a block containing only a little over a dozen tokens can accumulate a product whose dynamic range exceeds what half precision can reliably represent.
The remedy is not to add more conditional branches to the kernel. It is to constrain the parameterization itself.
A bounded parameterization
Log decay can be expressed as a fixed negative lower bound multiplied by a bounded function whose output lies in the open interval (0, 1). A practical choice is a scaled sigmoid:
- Apply a linear transformation to the channel-wise gates.
- Pass the result through a sigmoid.
- Multiply by a predetermined negative lower bound.
The lower bound should be chosen so that the resulting cumulative exponentials and reciprocals remain comfortably representable in the target half-precision format. A negative constant with a magnitude of a few units may be appropriate in some settings, but its suitability depends on the block length and numerical format. It should not be treated as a universally safe choice.
For a fixed block length, this parameterization bounds both decay ratios between positions and inverse scaling within the block. Those bounds can be checked in advance.
Diagonal and off-diagonal blocks can then share the same dense blockwise matrix-multiplication path. Decay becomes a row- or column-scaling vector applied through broadcasting before matrix multiplication, removing the need for a special position-pair path on the diagonal.
Why this change is reusable
Most of the change is confined to parameterization and scaling before the operator, rather than a rewrite of the entire block scheduler.
The performance opportunity comes primarily from converging control flow: causal blocks use the same matrix-multiplication path, making it easier for compiled and handwritten kernels to maintain occupancy and coalesced memory access.
Numerically, the state update no longer depends on training dynamics that happen to avoid underflow. During direct extrapolation to longer sequences, decay can still represent relative distance without corrupting the inverse scaling used inside a block.
Boundaries to preserve
The decay bound involves a trade-off:
- Too permissive: it effectively restores the unsafe behavior of unbounded decay.
- Too restrictive: it can weaken the model’s ability to distinguish nearby and distant tokens.
Choose the bound jointly with block length, half-precision characteristics, and state width. Test the blockwise dynamic range using random gates rather than relying only on training loss.
Models without positional encoding can use decay as their primary relative-distance signal. If explicit positional terms are also present, ensure that the two mechanisms do not apply overlapping distance-dependent scaling at block boundaries.
The following code illustrates the data flow, not a specific implementation interface:
log_decay = gmin * sigmoid(linear(h))scale = exp(cumsum(log_decay))inv_scale = 1 / scale
Here, gmin is a negative constant. Before blockwise matrix multiplication, use scale and inv_scale for row and column scaling. Diagonal and off-diagonal blocks then share the subsequent multiply-accumulate path.
For validation, fix the block length and scan extreme gate quantiles. Check that the minimum and maximum values of scale, along with their reciprocals, remain within the normal-number range of the target half-precision format.
3. Why Auxiliary Losses Can Slow MoE Training
MoE routing assigns each token to a small subset of experts. Computation grows with the number of activated experts rather than the total expert count.
At larger scales, routing can collapse onto a few experts. Popular experts become overloaded, rarely selected experts receive little training, and effective capacity falls far below the nominal parameter count.
A common response is to add an auxiliary load-balancing loss that penalizes deviations from a uniform expert-frequency distribution. This can improve aggregate balance, but it introduces several costs.
First, the auxiliary weight needs tuning. A large weight can hurt the main task; a small one may fail to control imbalance.
Second, at trillion-parameter scale with very large expert counts, the reductions and synchronization required for auxiliary statistics can themselves be expensive.
Third, an attractive global frequency distribution is not the same as balanced execution time in the current step. Dynamic batches, variable-length sequences, and expert parallelism can cause frequency constraints to diverge from actual compute load.
The objective may therefore look balanced while some experts still determine step latency.
4. Use Quantiles for Dynamic Routing Calibration
Quantile-based balancing moves the balancing mechanism from the training objective into statistical calibration of routing decisions.
Each expert, or group of routing logits, maintains recent score quantiles—for example, a median and a high quantile. Current routing scores are shifted or rescaled using those statistics before Top-k selection, bringing expert thresholds onto a more comparable scale.
The intuition is straightforward:
- An expert that remains popular tends to have a higher score distribution. Quantile calibration raises its effective admission threshold.
- An expert that remains underused receives a relatively lower threshold.
Balancing happens before route selection rather than through a penalty afterward. It therefore does not require an auxiliary objective that competes with the language-modeling gradient.
Maintaining the statistics
This approach is suited to training with many experts and rapidly changing step-to-step loads.
Quantiles can be approximated using reservoir sampling, histograms, or exponentially updated estimators. Updates can be local with approximately constant overhead, avoiding a full-token auxiliary-loss reduction at every step.
However, several details determine whether the method works in practice.
- Handle cold starts. Early quantile estimates are unreliable. Uniform noise or capacity limits can provide a fallback during the first steps and reduce the risk of early routing lock-in.
- Choose an appropriate estimation window. A short window can cause oscillation; a long one can lag behind changes in the data distribution. The window should reflect the timescale of gradient accumulation and changes in the data mixture.
- Preserve sparse routing. Calibration should retain Top-k selection and the capacity-based token-dropping policy. Otherwise, the method can undermine sparse computation.
- Measure more than token counts. Track per-expert token counts, execution time, and main-task loss. Balanced token counts can conceal unequal compute costs.
- Define synchronization scope. The implementation must specify update frequency and which devices share quantile statistics. Otherwise, parallel partitions may develop separate thresholds and achieve only local balance.
Compared with an auxiliary loss, quantile calibration removes the auxiliary-loss weight as a tuning dimension and leaves the main-task gradient cleaner. Its drawback is estimation bias: the quality and consistency of the statistics become part of the routing system’s correctness.
5. Why Representations Can Stall in Deep Networks
Simply adding layers does not guarantee better long-range representations.
After repeated residual additions through attention and feed-forward layers, deep hidden states may remain highly similar to shallow ones. New contributions are overwhelmed by the existing representation. Meanwhile, saving activations for backpropagation causes memory use and cross-device activation traffic to grow with depth.
Per-layer residual connections provide a direct gradient path, but they do not require each layer to produce a clearly distinguishable update. Optimization can settle on deep-layer increments that are close to zero.
Move the main residual connection to the block level
Block-level attention residuals move the main residual connection from individual layers to a block containing several attention and feed-forward sublayers.
Sublayers within the block can share intermediate representations more closely, while the main residual addition occurs between blocks.
This changes both optimization and systems behavior.
For optimization, the block becomes the unit of representation change. A group of sublayers works together to produce a distinguishable state update, reducing the tendency for every layer to make only a negligible change.
For memory and communication, checkpoints can be organized by block rather than by sublayer. Coarser checkpoint and recomputation boundaries can reduce stored activations and communication events.
Selective recomputation can preserve the gradients needed within each block: discard sublayer activations during the forward pass and recompute the current block during backpropagation. Compared with saving every layer’s activations, this trades controlled extra computation for lower memory use and collective communication.
Avoid oversized and undersized blocks
Two extremes are problematic:
- Blocks that are too large: without internal residual paths, gradients must traverse a long chain of sublayers, which can destabilize early training.
- Blocks that are too small: the design approaches ordinary per-layer residuals and offers limited memory savings.
A common design groups a fixed number of attention–feed-forward pairs into each block. A learnable scale on the inter-block residual update is initialized to a small value, allowing the network to rely initially on the identity path and gradually increase the block’s contribution.
Normalization should follow a consistent placement strategy: normalize at the block entrance or at the block exit, rather than introducing competing scaling operations inside and outside the block.
For long-sequence models, architectural residual blocks must also be coordinated with the attention recurrence. When recurrent state crosses a block boundary, residual scaling should affect the hidden representation only. Applying the same residual coefficient to historical attention state can break the recurrence’s invariants.
6. Combine the Changes in Data-Flow Order
These three changes operate at different levels and can be introduced in data-flow order.
- Bound the decay parameters in linear attention. Establish a safe, consistent numerical path for half-precision blockwise matrix multiplication.
- Calibrate expert routing with quantiles. Replace the auxiliary balancing loss while making sparse-compute load trackable across steps.
- Organize depth with block-level residuals. Control activation storage and communication while encouraging meaningful representation updates.
This order reflects the dependencies between the mechanisms. If decay can still overflow, improved parallel scheduling will not eliminate the diagonal-block fallback. If routing remains persistently skewed, queues at popular experts can offset the benefits of reduced activation storage.
Validation should focus on whether each mechanism works, not on speedup factors unsupported by reproduced experiments.
| Change | Acceptance criteria |
|---|---|
| Bounded decay parameterization | At a fixed block length, scaling factors and their reciprocals remain within the normal-number range of the target half-precision format. Diagonal and off-diagonal blocks use one shared kernel path. |
| Quantile-based balancing | After removing the auxiliary loss, dispersion in expert token shares decreases over training or remains within capacity limits. Main-task loss shows no sustained increase. |
| Block-level residuals | Differences between adjacent block representations are clearly larger than small fluctuations among sublayers within a block. Activation checkpoint counts decrease with coarser block granularity, without degrading long-sequence loss. |
7. Common Implementation Mistakes
Bounding decay only during training
If the training forward pass uses bounded decay but inference still uses the old unbounded negative-softplus formulation, the two numerical paths diverge. Long-context extrapolation can expose the mismatch immediately.
The parameterization must remain consistent across training and inference.
Synchronizing quantiles for every token
A global all-reduce for every token can make the balancing module more expensive than the auxiliary loss it replaces.
Maintain quantile statistics by expert group and update them per step or per microbatch rather than synchronizing every token globally.
Initializing residual scales to one
Initializing the block-update scale to 1 makes deep-block contributions comparable to the identity path from the start of training. The resulting loss spikes may be misdiagnosed as attention-kernel failures.
A small initial scale lets the network begin closer to the identity path.
Continuing quantile updates during inference
Updating quantiles during serving to make routing appear balanced allows the same input to take different routes as server-side statistics change.
Separate training-time calibration from inference-time execution with frozen thresholds.
Applying decay twice at block boundaries
Repeated scaling at a block boundary scales the recurrent state twice. A characteristic symptom is a periodic drop in state energy at each block interval.
Boundary logic should make clear which scaling has already been applied.
8. Conclusion
Whether long-sequence linear attention can fully use matrix hardware depends on keeping within-block decay reciprocals numerically safe. Whether a very large MoE model turns parameter count into effective capacity depends on controlling routing imbalance without an auxiliary objective that competes with the main task. Whether deeper networks continue to improve representations depends on meaningful residual updates rather than repeated near-identity layers.
Bounded decay gates, quantile-based routing calibration, and block-level attention residuals address these three constraints respectively.
Their shared advantage is locality: each has a clear interface and can be introduced incrementally into operators or training frameworks rather than requiring an entirely new model paradigm.
Engineering acceptance should focus on numerical range, convergence to a shared kernel path, load dispersion, and activation traffic—not unverified acceleration claims.
