MoE-Stream · Extended Report · July 2026

Sparse Mixture-of-Experts with
Gradient-Aware Expert Lifecycle

Augmenting Stream with dynamic MoE layers and gradient-based expert value scoring
← Back to Stream Main Report

1. Overview

MoE-Stream augments the Stream SSM backbone with sparse Mixture-of-Experts feed-forward layers and gradient-aware expert lifecycle management. Unlike Stream's minimalist design (which has no MLP at all), MoE-Stream adds specialized capacity through expert networks while maintaining Stream's clean single-loss training and O(n) SSM recurrence.

Stream Backbone
SSM + MoE
Each block: SSM recurrence → MoE FFN → residual + LN
Gradient-Aware Lifecycle
Impact / Freq
Expert value = loss-reduction impact ÷ usage frequency
Safe Replacement
Clone + Noise
Dead experts replaced via best-expert cloning with exploration bias
byte_embed → [ SSMBlock → MoEFFN → LN ] × n_layer → LN_f → MultiByteHead

2. Architecture

2.1 MoE-Stream Block

Each block stacks an SSMBlock (identical to Stream's core recurrence) followed by a sparse MoE FFN, with layer-normalized residual connection:

h = SSMBlock(x) moe_out, balance = MoEFFN(h) out = LayerNorm(h + moe_out)

2.2 MoE Feed-Forward Network

The MoEFFN replaces Stream's absent MLP with a top-k sparse mixture of expert sub-networks. Each expert is a 2-layer MLP with GELU activation:

Expert_i(x) = W_2 · GELU(W_1 · x + b_1) + b_2

Routing is performed by a learned linear gate followed by top-2 selection with normalized weights.

2.3 Config

ParameterDefaultDescription
n_experts8Number of expert sub-networks per layer
top_k2Number of active experts per token
expert_hidden_mult4Hidden dimension multiplier relative to n_embd
importance_momentum0.999EMA decay for frequency and impact tracking
replacement_threshold0.05Global floor for expert value score
expert_min_tokens5000Minimum tokens seen before eligibility for replacement
moe_balance_coeff0.01Weight for load balancing auxiliary loss

3. Gradient-Aware Expert Lifecycle Management

The core innovation in MoE-Stream is the expert lifecycle system, which distinguishes rare but valuable experts from truly useless ones using gradient-based impact measurements. This section details each component.

3.1 Expert Value Scoring

Each expert $i$ maintains two exponential moving averages updated every forward pass:

freq_ema[i] ← ρ · freq_ema[i] + (1-ρ) · n_tokens[i] impact_ema[i] ← ρ · impact_ema[i] + (1-ρ) · mean(-∇_y L · y)

The frequency EMA tracks how often the expert is selected. The impact EMA uses backward hooks on each expert's output layer to compute per-token loss reduction: $-(\partial \mathcal{L} / \partial y) \cdot y$, which is a first-order approximation of how much the expert's output contributes to reducing the loss. The combined value score is:

value[i] = impact_ema[i] / (freq_ema[i] + ε)
High-Frequency, High-Impact
Core Experts
Essential specialists — high value, should be preserved
High-Frequency, Low-Impact
Bloated Experts
Frequently selected but low per-token impact — wasteful but not dangerous
Low-Frequency, High-Impact
Rare Specialists
Infrequently selected but valuable when used — must be preserved
Low-Frequency, Low-Impact
Dead Experts
Neither selected often nor impactful — replacement candidates

3.2 Impact Hooks

Gradient-based impact is captured via PyTorch backward hooks registered on the last Linear layer of each expert:

# Pseudocode for impact hook registration for each expert i: last_linear = expert[-1] # output projection register_backward_hook on last_linear: saved = _saved_outputs[i] # y from forward grad = grad_output[0].detach() # ∂L/∂y impact = -(grad * saved).sum(dim=-1) # per-token impact append to _pending_grad_impacts[i] # Called after loss.backward(): flush_grad_impacts: for each expert i: norm = _grad_norm_ema # running scale estimate mean_impact = mean(pending_impacts / norm) _impact_ema[i] = ρ * _impact_ema[i] + (1-ρ) * mean_impact

3.3 Birth-Age Survival Boost

Recently replaced experts receive a temporary value score bonus to prevent immediate re-death before they have a chance to learn:

age = total_tokens[i] / min_tokens (0 = newborn, 1+ = mature) bonus = clamp(2.0 - age, min=0.0) / 2.0 × 0.35

This provides a score boost of up to 0.35 at birth, decaying linearly to 0 once the expert has seen 2× the minimum token threshold.

3.4 Dead Expert Detection

The `find_dead_experts` method identifies candidates for replacement using an adaptive per-layer threshold:

adaptive_th = max(global_threshold, max(value_scores) × 0.05)

Safety constraints:

3.5 Expert Replacement

When an expert is identified for replacement, the system clones the best-performing expert's weights with small Gaussian noise rather than random initialization:

# Best expert cloning (preferred path) best_idx = argmax(value_scores) noise_std = 0.01 for each layer in target_expert: layer.weight = source_layer.weight + randn() * noise_std if bias exists: layer.bias = source_layer.bias + randn() * noise_std # Fallback (all experts dead) for each layer: nn.init.normal_(layer.weight, std=0.005) nn.init.zeros_(layer.bias) # Reset tracking _freq_ema[idx] = 0.0 _impact_ema[idx] = 0.0 _total_tokens[idx] = 0 _n_replacements[idx] += 1 _exploration_bias[idx] = 0.2 # boost router probability

3.6 Exploration Bias

After replacement, an exploration bias is injected into the router logits to encourage the new expert to receive tokens during early training. This bias decays exponentially (factor 0.99 per training step), allowing the router to naturally integrate the new expert over time.

4. Training

4.1 Loss Function

MoE-Stream maintains Stream's clean single-loss approach with one additional term for load balancing:

L = L_pred + α · L_balance L_pred = (1/n_predict) · Σ_k CE(logits_{t,k}, target_{t+k}) L_balance = n_experts · Σ_i (f_i · P_i)

where $f_i$ is the batch-local fraction of tokens routed to expert $i$, and $P_i$ is the average router probability. The load balancing loss uses batch-local counts (not cumulative history) to ensure responsiveness to recent routing patterns.

4.2 Post-Backward Lifecycle Update

After each backward pass, `flush_grad_impacts()` is called via a hook registered on the loss tensor, ensuring that gradient-based impact EMAs are updated immediately after gradients are computed but before the next forward pass.

4.3 Training Config (stream_light equivalent)

ParameterValueNotes
n_embd128Embedding dimension
n_layer4Number of MoE-Stream blocks
n_experts4Experts per layer (8 for full config)
top_k2Active experts per token
learning_rate6e-4Peak LR with cosine decay
max_iters1000Training iterations
replace_interval400Check for dead experts every 400 iters
block_size256Max sequence length in bytes

5. Test Report

The following sections document smoke tests, utilization logging, and simulation results for the MoE-Stream expert lifecycle system.

5.1 Expert Utilization Log Format

During training, expert utilization statistics are logged at evaluation intervals. The `log_expert_utilization()` method produces per-layer, per-expert reports:

Layer 0:
Expert 0: score=0.823, freq=0.452, impact=0.00342, tokens= 2345, bias=0.000, replaced=0x
Expert 1: score=0.015, freq=0.031, impact=0.00005, tokens= 5001, bias=0.000, replaced=1x
Expert 2: score=0.012, freq=0.028, impact=0.00003, tokens= 5120, bias=0.000, replaced=1x
Expert 3: score=0.912, freq=0.489, impact=0.00389, tokens= 2534, bias=0.000, replaced=0x
Layer 1:
Expert 0: score=0.756, freq=0.401, impact=0.00291, tokens= 2104, bias=0.000, replaced=0x
Expert 1: score=0.890, freq=0.421, impact=0.00322, tokens= 2198, bias=0.000, replaced=0x
Expert 2: score=0.021, freq=0.042, impact=0.00008, tokens= 5023, bias=0.120, replaced=1x
Expert 3: score=0.333, freq=0.136, impact=0.00045, tokens= 3175, bias=0.000, replaced=0x

5.2 Value Score Distribution

The value score distribution across experts in a 4-expert, 4-layer configuration typically shows a bimodal pattern: 2-3 high-value core experts (score > 0.5) and 1-2 low-value candidates for replacement (score < threshold). The gradient-based metric naturally captures the distinction between frequency and impact.

Observation

The impact/frequency ratio is critical because it prevents high-frequency but low-impact experts from being wrongly classified as "valuable." A frequently selected expert that provides minimal loss reduction per token (e.g., outputting near-zero values) will have low value despite high frequency.

5.3 Replacement Safety Validation

The replacement system includes multiple safeguards verified through simulation:

SafeguardMechanismStatus
Best expert protectionBest score expert excluded from candidate listVERIFIED
Replacement capMax floor(n_experts / 2) per checkVERIFIED
Probation periodmin_tokens threshold before eligibilityVERIFIED
Adaptive thresholdmax(global, max_score × 0.05)VERIFIED
Birth-age boostScore bonus decaying over token countVERIFIED
Exploration bias decayRouter bias decays 0.99 per stepVERIFIED
Clone + noise initGaussian noise std=0.01 on best expert cloneVERIFIED
Fallback random initScaled init when all experts are deadVERIFIED

5.4 Load Balancing Validation

The load balancing loss uses batch-local token fractions:

f_i = batch_counts[i] / S P_i = weights.sum(0) / S balance_loss = n_experts · Σ_i (f_i · P_i)

This design avoids the hysteresis of cumulative count-based balancing, ensuring the router can rapidly adapt to changing expert quality after replacements. The coefficient $\alpha = 0.01$ provides gentle balancing pressure without overwhelming the prediction loss.

6. Architecture Comparison

FeatureStreamVECTORMoE-Stream
BackboneSSM onlySSM + Attn + MoESSM + MoE
Token-FreeYESYESYES
Position-FreeYESYESYES
Multi-Byte HeadYESNoYES
Gate / PruningNoneSaliencyGateNone
MoENoneTop-2Top-2
Expert LifecycleN/ANoneGradient-Aware
Loss Terms1 (CE)5 (Dual)2 (CE + Balance)
ComplexityO(n)O(n) var.O(n)
AttentionNoneGQANone

7. Implementation Details

7.1 Code Structure

MoE-Stream is implemented as a standalone module in moe_stream.py with no dependencies on Stream's model.py or VECTOR's model_vector.py. The SSMBlock is duplicated for independence, ensuring each variant can evolve independently.

7.2 Key Components

ClassFileLinesPurpose
SSMBlockmoe_stream.py53-105Selective SSM recurrence (Mamba-style)
MoEFFNmoe_stream.py111-389MoE with lifecycle tracking, hooks, replacement
MoEStreamBlockmoe_stream.py395-413SSM + MoE block with residual LN
MoEStreammoe_stream.py419-597Full model with multi-byte head

7.3 Configuration

The MoEStreamConfig dataclass provides all hyperparameters with sensible defaults (8 experts, top-2, min 5000 tokens before replacement). Training is orchestrated through train.py with model_type='moe_stream' and CLI overrides via configurator.py.

8. Pending Work & Known Issues

Known limitations
  • No streaming test yet: The lifecycle system has been validated through simulation and unit testing but not through a full training run with dynamic replacements
  • Gradient impact normalization: The gradient norm EMA for impact normalization assumes stable gradient scales; verification needed under varying learning rates and batch sizes
  • Birth-death cycles: Under some configurations, experts may enter rapid birth-death cycles where they are replaced immediately before they can learn — the birth-age boost mitigates this but may need tuning
  • Load balance vs replacement interaction: When many experts are replaced simultaneously, the load balancing loss may briefly spike as the router adapts to new experts
Next steps
  • Full training run on bytes dataset (1000 iterations) with expert replacement enabled
  • Ablation: compare clone+noise replacement vs random init vs no replacement
  • Ablation: compare gradient-based impact vs router-weight-based expert scoring
  • Sweep replacement_threshold and exploration_decay hyperparameters