nemo_automodel.components.moe.layers
nemo_automodel.components.moe.layers
Module Contents
Classes
Functions
Data
API
Bases: Module
Load balanced gate implementation, spreads tokens uniformly across all experts. The rationale for this class is to do performance experiments to understand how the load imbalance with real data is impacting end-to-end performance.
When noise > 0, random perturbation is added to mimic realistic routing
imbalance. A noise value of 0.0 gives perfectly balanced assignment, while
1.0 gives fully random expert selection and non-uniform weights.
Forward pass for the gating mechanism.
Parameters:
Input tensor.
Boolean mask indicating valid tokens.
Device mesh for context parallel computation.
Returns: torch.Tensor
Routing weights for the selected experts.
Bases: Module
Gating mechanism for routing inputs in a mixture-of-experts (MoE) model.
Optional bias term for the gate.
Dimensionality of input features.
Number of groups for routing.
Scaling factor for routing weights.
Scoring function (‘softmax’, ‘sigmoid’, ‘sigmoid_with_bias’, ‘softmax_with_bias’, or ‘sqrtsoftplus’).
Number of top experts activated for each input.
Number of groups to route inputs to.
Learnable weights for the gate.
Computes the auxiliary loss for load balancing.
Warning: Assumes batch size = 1, if batch size > 1, the aux_loss will be computed across multiple sequences.
Parameters:
Original scores from the gating mechanism. Shape is [num_tokens, num_experts].
Load of each expert (number of tokens routed to each expert). Shape is [num_experts].
Boolean mask indicating valid tokens. Shape is [num_tokens].
Device mesh for context parallel computation.
Returns: torch.Tensor
torch.Tensor: Auxiliary loss for load balancing. Shape is [].
Computes the load of each expert based on the selected indices. Args: indices (torch.Tensor): Indices of the selected experts. Shape is [num_tokens, num_activated_experts]. token_mask (torch.Tensor): Boolean mask indicating valid tokens. Shape is [num_tokens].
Returns: torch.Tensor
torch.Tensor: Load of each expert (number of tokens routed to each expert). Shape is [num_local_experts].
Load gate state while preserving the routing-bias DTensor layout.
Parameters:
State mapping whose correction bias is either a full tensor
of shape [experts] or an already distributed tensor.
Prefix applied to this module’s state-dict keys.
Metadata saved for this module.
Whether state-dict keys must match exactly.
Missing state-dict keys collected during loading.
Unexpected state-dict keys collected during loading.
State-dict loading errors collected during loading.
Raises:
RuntimeError: If a full correction-bias tensor targets an incompatible shape or a DTensor that is not replicated on every mesh dimension.
Return the local tensor used to adjust this rank’s routing scores.
Returns: torch.Tensor | None
Tensor of shape [experts] replicated across the gate’s DP/CP mesh, or
Apply fixed-shape expert selection and probability math to router logits.
Parameters:
Tensor of shape [tokens, experts] containing local router logits.
Returns: torch.Tensor
Tuple containing routing weights of shape [tokens, activated_experts],
Forward pass for the gating mechanism.
Parameters:
Input tensor.
Boolean mask indicating valid tokens.
Device mesh for context parallel computation.
Returns: torch.Tensor
Routing weights for the selected experts.
Updates the correction bias used in the gate based on the popularity of experts. This function is a NoOp if the gate is not trained.
To avoid routing collapse, and to promote better load balance of experts, DeepSeek-V3 uses a correction mechanism to adjust the scores of experts using a learned bias parameter. The bias parameter is updated based on the popularity of experts, i.e., the number of tokens routed to each expert. If an expert is more popular than the average, its bias term is decreased, and vice versa. This encourages the model to route tokens to less popular experts, promoting better load balance.
Bases: Module
Multi-Layer Perceptron (MLP) used as a feed-forward layer.
Supports both gated activations (SwiGLU) and simple activations (ReLU²).
Linear layer for hidden-to-output transformation.
Linear layer for gate in gated activations (or up_proj for simple).
Additional linear layer for gated activations (None for simple).
Forward pass for the MLP layer.
Parameters:
Input tensor.
Returns: torch.Tensor
torch.Tensor: Output tensor after MLP computation.
Bases: Module
Mixture-of-Experts (MoE) module.
Dimensionality of input features.
List of expert modules.
Gating mechanism to route inputs to experts.
Number of experts activated for each input.
Number of experts handled locally in distributed systems.
Total number of experts in the model.
Shared experts applied to all inputs.
Make the current stream wait for the side-stream shared-expert output z.
Shared-expert output for x, gated by shared_expert_gate when the model has one.
Run the shared experts for x on the per-device side stream.
Returns the shared-expert output and the stream it was computed on; the caller runs the routed
path on the current stream and then joins with _join_shared_experts. Subclasses with their
own forward (Kimi K3) reuse both helpers so the stream choreography lives in one place.
Route tokens through shared and routed experts.
Parameters:
Input tensor of shape [..., hidden].
Boolean tensor matching x.shape[:-1] where true
entries are padding.
Optional context-parallel mesh used by the router.
Returns: torch.Tensor
Tensor with the same shape and dtype as x.
Bases: Module
Parameterless, fixed-shape portion of a learned MoE router.
The gate projection remains eager so FSDP can unshard its DTensor parameters. The owning gate is passed as a non-tensor control so this child remains an independent, parameterless CUDA graph boundary and survives model copies.
Select experts and compute routing probabilities from projected scores.
fp32 clamped SwiGLU on separate gate / up projections, cast back to the input dtype.
Same arithmetic as the eager branch of MLP.forward (the DeepSeek-V4 reference Expert.forward); inductor
fuses it into one kernel per direction. Dynamo’s default shape policy: the first token count compiles a static
graph, the second recompiles once with a symbolic row count and every later shape reuses it — dynamic=False
with fullgraph=True would instead raise FailOnRecompileLimitHit after recompile_limit distinct
token counts (variable-length batches). CPU inputs keep the eager chain.
Return the per-device side stream used for shared-expert overlap (created lazily, one per process).