kempnerforge.model.router

MoE router implementations for KempnerForge models.

Classes

Recomputing

Mark the recompute of an activation-checkpointed block, which routers leave no trace of.

SigmoidTopKRouter

DeepSeek-V3 style sigmoid router with auxiliary-loss-free balancing.

SoftmaxTopKRouter

Mixtral-style softmax top-k router with auxiliary load-balancing loss.

class kempnerforge.model.router.Recomputing[source]

Bases: object

Mark 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_loss and expert_counts stay those of the forward, whose loss the backward differentiates, and the sigmoid router’s pending_counts count each token once. inner is 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: Module

Mixtral-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_loss and expert_counts as side effects of each forward call for collection by the training loop and metrics, except in the recompute of an activation-checkpointed block (see Recomputing).

__init__(dim, num_experts, top_k)[source]
Parameters:
Return type:

None

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: Module

DeepSeek-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: balance moves 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, which balance consumes; the recompute of an activation-checkpointed block does not (see Recomputing). derived_buffers names the buffers a load derives from the other state when a checkpoint lacks them.

always_frozen names the parameters that freeze_params never 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]
Parameters:
  • dim (int)

  • num_experts (int)

  • top_k (int)

  • bias_update_rate (float)

  • ema_decay (float)

  • sequence_aux_loss_weight (float)

  • bias_schedule (str)

Return type:

None

reset_parameters()[source]

Restore this router’s construction-time state.

to_empty() on a meta build leaves both holding whatever the allocator returns, and init_weights covers neither: expert_bias is one-dimensional and expert_ema is a buffer.

Return type:

None

set_step(step, max_steps)[source]

Set current training step for adaptive bias scheduling.

Parameters:
Return type:

None

balance(counts)[source]

Move expert_bias toward balance after an optimizer step, and clear the counts.

counts are 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 by 1 - ema_decay, and each expert’s bias by the effective rate times its shortfall from 1 / num_experts. The arithmetic runs on the FP32 masters (see _masters), so that low-precision storage does not round the small moves away, and expert_ema and expert_bias are 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_ema and expert_bias as 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