Long Context and Sparse Experts: How to Implement Three Key Techniques
This article breaks down three reusable engineering problems behind long-context and sparse-expert models: how to chunk linear attention while keeping numerical stability, how to balance MoE expert loads without auxiliary losses, and how deep networks can selectively read historical layer information under bounded memory and communication costs. It covers bounded log-decay design, precision range calculations, quantile-based bias balancing, block attention residuals, and a practical verification checklist.
The conclusion first: three technical paths solve three problems. First, how to keep numerical stability when chunking linear attention so that intra-chunk computation can run on dense matrix multiplications. Second, how to balance expert loads in MoE without adding auxiliary losses. Third, how deep networks can selectively read information from earlier layers while controlling memory and communication overhead.
1. Background and Reading Guide
Model capability improves mainly through two paths: scaling parameters and extending the context length. Agent applications need to retrieve, reason, and plan over inputs of hundreds of thousands or even millions of tokens. Directly scaling dense models inflates training and inference costs in lockstep, so sparse Mixture-of-Experts (MoE) and efficient attention have become mainstream engineering choices.
This article does not evaluate any specific product. It breaks down three reusable problems:
- How to chunk long-context linear attention and keep it numerically stable
- How to balance MoE expert loads without auxiliary losses
- How deep-layer residuals can reduce memory and communication overhead while preserving cross-layer information
2. How to Chunk Long-Context Linear Attention
Start by comparing three attention schemes.
| Scheme | Compute complexity (sequence length L) | Memory | Hardware fit | Applicable boundary |
|---|---|---|---|---|
| Standard softmax attention | Proportional to L² | Grows quickly with L | Mature, well-supported kernels | Short sequences, or when exact global attention is required |
| Linear attention (step-by-step recurrence) | Approximately linear in L | Fixed state size | Serial recurrence, hard to saturate matrix units | Very long sequences, but theoretical speed may not materialize |
| Chunked linear attention | Approximately linear, coefficient tied to chunk size B | Tied to chunk size B | Dense matrix multiply within chunks, good fit | Requires handling numerical stability and chunk boundaries |
The common chunked approach is: use parallel matrix multiplication within a chunk, and pass information across chunks through a recurrent state. Intra-chunk computation typically requires the reciprocal of cumulative decay factors. When the decay is unbounded, these reciprocals can become extremely large and overflow or lose precision in low-precision formats. Implementers are then forced to write a separate element-wise path for the small diagonal blocks. These branches cannot use dense matrix units, and throughput drops.
One approach is to set a lower bound on the log decay:
def bounded_log_decay(x, g_min=-5.0):# x: raw real values from the linear projection of the current token, shape [batch, heads, seq], unbounded# g_min: lower bound of the per-step log decay, must be negative# the returned g lies in (g_min, 0), so the per-step decay factor exp(g) lies in (exp(g_min), 1)return g_min * sigmoid(x)
With this, every chunk can use the same dense matrix multiplication kernel. The code is more uniform and easier to optimize with GPU operator libraries. In some designs, the decay term also carries part of the positional information. This role needs separate validation when extrapolating to longer sequences and cannot be assumed to hold.
How to Compute the Numerical Range
The upper bound of the absolute value of the cumulative log decay within a chunk is B × |g_min|. With chunk size B = 16 and g_min = -5, the bound is 80. The corresponding scaling factor exp(80) is about 5.5×10^34. Whether this value can be represented depends on the precision format:
- FP32 can represent it without overflow.
- BF16 has a maximum of about 3.4×10^38, so it can represent it.
- FP16 has a maximum of 65504, so exp(80) overflows. Under FP16, you need exp(B·|g_min|) < 65504, i.e., B·|g_min| < roughly 11.09. With g_min = -5, the chunk size must be no larger than 2.
Therefore, the “cumulative absolute upper bound of 80” only holds for the combination B = 16 and g_min = -5. Any change to chunk size or precision requires recomputing the range.
g_min determines the strongest per-step forgetting ability. The closer it is to 0, the slower the forgetting; the more negative it is, the larger the numerical range. When choosing it, check two things together: whether the numerical range fits the target precision, and whether the model retains sufficiently distant information on the validation set. Both must be determined through ablation experiments; there is no universal optimum.
3. How to Balance MoE Loads Without Auxiliary Losses
In an MoE layer, the router selects the top-k experts with the highest scores for each token. Without constraints, a few experts receive most tokens while others remain undertrained, and the compute load across devices becomes unbalanced.
The traditional approach adds an auxiliary balancing loss to the objective. It works, but it injects extra gradient interference into the main task. If the coefficient is too large, model quality suffers; if too small, balancing is insufficient. As the expert count grows into the hundreds, this trade-off becomes harder to tune.
An alternative is quantile-based bias balancing. The two methods compare as follows:
| Dimension | Auxiliary balancing loss | Quantile-based bias balancing |
|---|---|---|
| Impact on main-task gradients | Extra gradients added to the main loss; large coefficients hurt quality | Bias does not participate in backpropagation; main-loss gradients are undisturbed |
| Hyperparameter sensitivity | Loss coefficient requires repeated tuning, harder as expert count grows | Learning rate lr, quantile q, bias clipping range b_clip |
| Risk under extreme sparsity | Small coefficients lead to insufficient balancing | Too-short statistics windows cause jitter; too-long windows respond slowly |
| Main debugging items | Share of auxiliary loss, variance of per-expert load | Whether the bias sticks near the clipping bounds, statistics window length |
The pseudo-code for the bias update:
def quantile_bias_update(load_ema, bias, lr=1e-3, q=0.5, b_clip=1.0):# load_ema: exponential moving average of the token share received by each expert, length equals expert count# update rule: load_ema = decay * load_ema + (1 - decay) * batch_load# the effective window is about 1 / (1 - decay) stepsthreshold = quantile(load_ema, q)bias = bias - lr * sign(load_ema - threshold)bias = clamp(bias, -b_clip, b_clip)return bias
The update rule has four steps:
- At each step, update the received share of each expert with an exponential moving average (EMA); the decay coefficient determines the statistics window.
- Take quantile q as the reference line. Experts above the line (about 1 - q of them) receive a negative bias; the rest receive a positive bias.
- Clip the bias to [-b_clip, b_clip] to prevent any expert from being suppressed indefinitely.
- The bias only participates in expert selection, not gradient computation. It is a buffer, not a learnable parameter, so it stays outside the computation graph.
At routing time:
scores = logits + bias.detach() # the bias is only used to select expertstopk_idx = topk(scores, k) # the selected set may change because of the biasgates = softmax(gather(logits, topk_idx), dim=-1) # gate weights are still normalized over the raw logits
The bias only changes the top-k selection; gate weights are still normalized over the raw logits. Once the selected set changes, the output changes as well, so numerical stability must be monitored.
Under extremely sparse settings, each expert sees very few samples, and the numerical stability of the gating structure also matters. A common practice is to use gated linear unit (GLU)-style structures and constrain the output range of the gating branch, for example by clipping or normalization, to avoid gradient spikes caused by small sample counts.
4. How to Build Block Attention Residuals in Deep Networks
A standard residual can be written as h_{l+1} = h_l + f_l(h_l). Layer outputs accumulate one by one, so information from early layers gets diluted and the magnitude of later-layer representations keeps growing. This fixed additive scheme prevents deep networks from actively selecting the historical representations they need.
Block attention residuals work as follows:
- Divide an N-layer network into blocks of S layers each.
- Accumulate as usual within a block; at the end of the block, store the sum of its outputs as a block summary.
- Before entering a new layer, the current layer generates a query vector from its own input and performs attention-weighted aggregation over all completed block summaries plus the current block’s partial sum, producing the residual base for this layer.
- Each layer only reads block summaries, so there is no need to store every layer’s output.
The core computation is shown below. Projection matrices are omitted to highlight the structure; keys and values are the summaries themselves:
def block_attn_residual(blocks, partial, query):# blocks: list of completed block summaries, each of shape [d]# partial: partial sum accumulated so far in the current block, shape [d]# query: query vector generated from the current layer's input, shape [d]candidates = stack(blocks + [partial]) # [n + 1, d]scores = candidates @ query / sqrt(d) # [n + 1]weights = softmax(scores, dim=0)return weights @ candidates # [d], used as the residual base for this layer
The block size S determines two extremes of the structure:
- When S = 1, each layer is its own block, equivalent to attending over all historical layers; memory grows linearly with depth.
- When S = N, there is only one block, which degenerates to plain residual addition with no selection ability.
For intermediate values, the number of stored summaries is N / S, and memory is proportional to the number of blocks.
Memory and Communication Overhead
For memory, the structure stores N / S summary vectors instead of N layer outputs. In pipeline parallelism, what crosses stage boundaries is also the block summaries. Communication volume grows with the number of blocks, but since every layer reads all summaries when selecting, the read and compute overhead grows with N / S as well.
Use consistent measurement methodology:
- Memory: fix batch size and sequence length, record peak memory (e.g.,
torch.cuda.max_memory_allocated), and compare the difference with and without the structure. - Communication: record bytes transferred per step at stage boundaries; do not rely on average bandwidth alone.
- Performance: results depend on hardware, model width, and parallelism strategy. Measure in the target environment instead of reusing numbers from other setups.
If memory is still tight, consider alternatives. Gradient checkpointing trades recomputation for memory and suits scenarios with spare compute. Cross-layer parameter sharing reduces parameter count but adds no cross-layer selection ability. These methods can be used alone or combined with block attention residuals.
5. Verification Checklist
Check the following items in order, and keep a record for each.
- Decay bound: record the maximum absolute value of the cumulative log decay per chunk and confirm it does not exceed B × |g_min|.
- Precision comparison: under the target precision (FP16, BF16, or FP32), compare chunk outputs against an FP32 reference implementation. If the relative error exceeds the team’s threshold, stop and investigate.
- Overflow check: count occurrences of inf and NaN, and inspect the numerical range before and after exp computations.
- Quantile and bias: measure the share of experts receiving negative bias each step; it should be close to 1 - q. Also check whether biases sit near ±b_clip for long periods.
- Expert load: record the ratio of maximum to average per-expert share, as well as the variance, and observe whether they converge during training.
- Statistics window: compare load curves under different EMA windows. Too short a window causes jitter; too long a window responds slowly.
- Residual overhead: count bytes communicated per step at stage boundaries and correlate them with changes in block size S.
- Ablation: fix the random seed, compare validation loss with and without block attention residuals, and compare results across different values of S.
