kempnerforge.model.router¶
MoE router implementations for KempnerForge models.
Classes
Mark the recompute of an activation-checkpointed block, which routers leave no trace of. |
|
DeepSeek-V3 style sigmoid router with auxiliary-loss-free balancing. |
|
Mixtral-style softmax top-k router with auxiliary load-balancing loss. |
- class kempnerforge.model.router.Recomputing[source]¶
Bases:
objectMark the recompute of an activation-checkpointed block, which routers leave no trace of.
The backward of a checkpointed block runs its forward again to rebuild the activations it did not keep. In this context a router computes what it computed in the forward, so that the rebuilt activations match, but sets no attribute and counts no token: its
aux_loss,z_lossandexpert_countsstay those of the forward, whose loss the backward differentiates, and the sigmoid router’spending_countscount each token once.inneris entered inside it, as the selective-checkpoint context that hands the recompute the forward’s top-k routing. It can be entered more than once.- __init__(inner=None)[source]¶
- Parameters:
inner (AbstractContextManager[Any] | None)
- Return type:
None
- class kempnerforge.model.router.SoftmaxTopKRouter[source]¶
Bases:
ModuleMixtral-style softmax top-k router with auxiliary load-balancing loss.
Each token independently selects top_k experts. Routing weights are softmax-normalized, then renormalized over the selected top_k.
Stores
aux_lossandexpert_countsas side effects of each forward call for collection by the training loop and metrics, except in the recompute of an activation-checkpointed block (seeRecomputing).- forward(x)[source]¶
Route tokens to experts.
- Parameters:
x (torch.Tensor) – (num_tokens, dim) — flattened token representations.
- Returns:
(num_tokens, top_k) — renormalized routing weights. expert_indices: (num_tokens, top_k) — selected expert indices.
- Return type:
weights
- class kempnerforge.model.router.SigmoidTopKRouter[source]¶
Bases:
ModuleDeepSeek-V3 style sigmoid router with auxiliary-loss-free balancing.
Uses per-expert sigmoid scoring (each expert scored independently) instead of softmax. Load balancing is maintained by
expert_bias, which the optimizer never trains:balancemoves it once per optimizer step from a running EMA of expert utilization, so no auxiliary loss term is added to the training loss by default.The bias adjustment nudges under-utilized experts up and over-utilized experts down, achieving balance without interfering with the main loss gradient signal. A training forward adds its expert counts to
pending_counts, whichbalanceconsumes; the recompute of an activation-checkpointed block does not (seeRecomputing).derived_buffersnames the buffers a load derives from the other state when a checkpoint lacks them.always_frozennames the parameters thatfreeze_paramsnever unfreezes.Optional enhancements (all disabled by default for backward compatibility):
Sequence-level auxiliary loss: lightweight variance-based balance penalty (10-100x smaller than Switch Transformer’s aux loss) that complements bias balancing to prevent degenerate routing in long runs.
Adaptive bias schedule: decays or warms up the bias update rate over training to stabilize routing after initial exploration.
- always_frozen = ('expert_bias',)¶
- derived_buffers = ('fp32_ema_bits', 'fp32_bias_bits')¶
- expert_ema: torch.Tensor¶
- pending_counts: torch.Tensor¶
- fp32_ema_bits: torch.Tensor¶
- fp32_bias_bits: torch.Tensor¶
- __init__(dim, num_experts, top_k, bias_update_rate=0.001, ema_decay=0.99, sequence_aux_loss_weight=0.0, bias_schedule='constant')[source]¶
- reset_parameters()[source]¶
Restore this router’s construction-time state.
to_empty()on a meta build leaves both holding whatever the allocator returns, andinit_weightscovers neither:expert_biasis one-dimensional andexpert_emais a buffer.- Return type:
None
- balance(counts)[source]¶
Move
expert_biastoward balance after an optimizer step, and clear the counts.countsare the step’s expert counts, summed over its micro-batches and every rank: utilization is each expert’s share of them, so ranks holding the same tokens, as under tensor parallelism, cancel out. The EMA of utilization moves toward this step’s by1 - ema_decay, and each expert’s bias by the effective rate times its shortfall from1 / num_experts. The arithmetic runs on the FP32 masters (see_masters), so that low-precision storage does not round the small moves away, andexpert_emaandexpert_biasare rounded from them; under FSDP2 the bias is updated in place on this rank’s shard.- Parameters:
counts (torch.Tensor)
- Return type:
None
- derive_buffers(names)[source]¶
Start the named FP32 masters from
expert_emaandexpert_biasas loaded.For a load from a checkpoint that lacks them; a master not named keeps its loaded value. Deriving the bias master gathers a bias that FSDP2 shards, so every rank calls it.
- Parameters:
names (Collection[str])
- Return type:
None
- forward(x)[source]¶
Route tokens to experts using sigmoid scoring.
- Parameters:
x (torch.Tensor) – (num_tokens, dim) — flattened token representations.
- Returns:
(num_tokens, top_k) — routing weights (sigmoid scores). expert_indices: (num_tokens, top_k) — selected expert indices.
- Return type:
weights