nemo_automodel.components.moe.experts
nemo_automodel.components.moe.experts
Module Contents
Classes
Functions
Data
API
Bases: Module
Sparse MoE implementation using all-gather/reduce-scatter primitives.
Supports two compute backends:
- Per-expert loop with gather/scatter (default)
- torch._grouped_mm with argsort-based permutation (backend.experts=“torch_mm”; “gmm” remains a deprecated compatibility alias)
Linear layer for hidden-to-output transformation.
Linear layer for gate+up (gated) or just up (non-gated).
Total number of experts in the model.
Grouped GEMM forward path using torch._grouped_mm.
Per-expert loop forward path using gather/scatter.
Gather unequal token shards across the expert-parallel group.
Parameters:
Tensor of shape [local_tokens, hidden], containing local activations.
Tensor of shape [local_tokens], marking valid tokens.
Tensor of shape [local_tokens, topk], containing routing probabilities.
Tensor of shape [local_tokens, topk], containing global expert IDs.
Expert-parallel process group.
Number of ranks in ep_group.
Returns: torch.Tensor
Activations [gathered_tokens, hidden], routing weights [gathered_tokens, topk],
Forward pass for the grouped experts.
Parameters:
Input tensor. Shape is [num_tokens, model_dim].
Boolean mask indicating valid tokens. Shape is [num_tokens].
Routing weights for the selected experts. Shape is [num_tokens, num_activated_experts].
Indices of the selected experts. Shape is [num_tokens, num_activated_experts].
Returns: torch.Tensor
torch.Tensor: Output tensor after expert computation. Shape is [num_tokens, model_dim]
Bases: Module
Sparse MoE implementation using grouped GEMM with DeepEP token dispatch.
Uses torch._grouped_mm for the canonical experts="torch_mm" backend.
experts="gmm" remains a deprecated compatibility alias.
Once the experts for a particular token have been identified, this module is invoked to compute and average the output of the activated experts.
Linear layer for hidden-to-output transformation.
Linear layer for gate+up (gated) or just up (non-gated).
Total number of experts in the model.
Dispatch valid tokens and stabilize empty probabilities for recomputation.
Parameters:
Tensor of shape [local_tokens, hidden], containing local activations.
Tensor of shape [local_tokens], marking valid tokens.
Tensor of shape [local_tokens, topk], containing routing probabilities.
Tensor of shape [local_tokens, topk], containing global expert IDs.
Returns: torch.Tensor
Expert-sorted activations [dispatched_tokens, hidden], counts [local_experts],
Initialize DeepEP communication buffers before activation checkpointing.
Forward pass for the grouped experts.
Parameters:
Input tensor. Shape is [num_tokens, model_dim].
Boolean mask indicating valid tokens. Shape is [num_tokens].
Routing weights for the selected experts. Shape is [num_tokens, num_activated_experts].
Indices of the selected experts. Shape is [num_tokens, num_activated_experts].
Returns: torch.Tensor
torch.Tensor: Output tensor after expert computation. Shape is [num_tokens, model_dim]
Return dispatcher-owned resources that must be ready before a PP step.
Returns: tuple[HybridEPPipelineRuntimeInitializer, ...]
HybridEP runtime initializers supplied by this expert module’s token dispatcher.
Bases: Module
MoE experts using TE’s GroupedLinear module directly.
Uses TE’s native GroupedLinear for computation, providing:
- Optimized grouped GEMM kernels from TE
For expert parallelism, each rank creates GroupedLinear with num_local_experts = n_routed_experts / ep_size.
Down projection.
Combined gate and up projection.
Total number of experts in the model.
Load state dict with stacked tensors in DeepEP format.
Converts stacked format to TE GroupedLinear’s weight{i} parameters:
- gate_and_up_projs: [num_local_experts, dim, moe_inter_dim * 2]
- down_projs: [num_local_experts, moe_inter_dim, dim]
Forward pass using TE’s GroupedLinear with native FP8 support.
Parameters:
[num_tokens, model_dim] input tensor
[num_tokens] boolean mask for valid tokens
[num_tokens, num_activated_experts] routing weights
[num_tokens, num_activated_experts] expert indices
Returns: torch.Tensor
[num_tokens, model_dim] output tensor
Return dispatcher-owned resources that must be ready before a PP step.
Returns: tuple[HybridEPPipelineRuntimeInitializer, ...]
HybridEP runtime initializers supplied by this expert module’s token dispatcher.
Initialize the token dispatcher for expert parallelism.
Called by the parallelizer after model initialization.
Parameters:
Device mesh for expert parallelism.
Initialize weights using reset_parameters()
Return state dict with stacked tensors in DeepEP format.
Converts TE GroupedLinear’s weight{i} parameters to stacked format:
- gate_and_up_projs: [num_local_experts, dim, moe_inter_dim * 2]
- down_projs: [num_local_experts, moe_inter_dim, dim]
When EP is enabled, returns DTensors sharded on dimension 0.
Bases: Function
All-gather with variable local lengths and autograd-safe backward.
Backward uses all-reduce + local narrow instead of reduce-scatter to avoid monitoredBarrier deadlocks observed with mixed FSDP/EP backward collective ordering.
Bases: Function
Add expert bias without materializing a full-size expanded bias.
Compute value, bias, and probability gradients in bounded memory.
Parameters:
Autograd context containing bias, token counts, and optional probabilities.
Upstream gradient of shape [tokens, hidden].
Returns:
Gradients for value, bias, and probs; token counts are non-differentiable.
Add optionally weighted expert bias with bounded temporary memory.
Parameters:
Autograd context used to retain the compact inputs.
Grouped expert output of shape [tokens, hidden].
Per-expert bias of shape [experts, hidden].
Tensor of shape [experts] containing nonnegative token counts.
Optional FP32 routing probabilities of shape [tokens, 1].
Whether the caller transfers ownership of value so its storage can hold the result.
Returns:
Tensor of shape [tokens, hidden] and the same dtype as value.
Bases: Function
Expand expert biases while reducing their gradients deterministically.
Reduce expanded bias gradients with one deterministic segmented reduction.
Parameters:
Autograd context containing the forward token counts.
Tensor of shape [tokens, hidden].
Returns:
Tuple containing the bias gradient of shape [experts, hidden] and no gradients for token counts or size.
Expand each expert bias over its contiguous token group.
Parameters:
Autograd context used to retain the token counts for backward.
Tensor of shape [experts, hidden].
Tensor of shape [experts] containing nonnegative token counts.
Total number of grouped tokens.
Returns:
Tensor of shape [tokens, hidden], with each expert row repeated for its tokens.
Allocate device workspace required by Triton tensor descriptors.
Parameters:
Workspace size in bytes.
Required byte alignment. CUDA allocations already provide at least 256-byte alignment.
CUDA stream pointer requesting the allocation, or None outside a stream.
Returns: torch.Tensor
One-dimensional CUDA byte tensor with size elements.
Apply per-expert bias to grouped GEMM output.
NOTE: torch._grouped_mm accepts a bias kwarg in its schema but raises
“RuntimeError: Bias not supported yet” as of PyTorch 2.9.0.
Additionally, down projection bias needs weighting by routing probs
(bias * permuted_probs) which native bias support wouldn’t handle.
Parameters:
Output from grouped GEMM, shape [total_tokens, features].
Per-expert bias, shape [num_experts, features].
Token counts, shape [num_experts].
Optional routing probabilities broadcastable to [total_tokens, features], typically [total_tokens, 1].
Reuse value storage for the result when the bounded-memory path supports it. The caller
must not read value afterward or pass storage retained by a selective-checkpoint cache.
Returns:
Grouped GEMM output with per-expert bias applied, shape
Run a grouped expert MLP in bounded row chunks.
Each chunk is independently checkpointed, so backward recomputes its two
grouped GEMMs instead of retaining full [tokens, 2 * inter_dim] and
[tokens, inter_dim] activations. The final [tokens, hidden] tensor
is allocated once and populated by slice assignment; no concatenation or
stateful scratch buffer is used.
The checkpoint callback captures the input dtype rather than the routed tensor so an enclosing activation checkpoint can release that tensor.
This helper is for the plain torch._grouped_mm path. MXFP8 uses a
different quantization contract and remains on its existing whole-dispatch
implementation.
Parameters:
Tensor of shape [tokens, hidden], with rows grouped contiguously by expert.
Tensor of shape [experts, hidden, gate_up], where gate_up stores the fused gate and
up projections in the ordering required by activation_fn.
Tensor of shape [experts, intermediate, hidden].
Optional tensor of shape [experts, gate_up].
Optional tensor of shape [experts, hidden].
Tensor of shape [experts] containing the number of contiguous rows for each expert.
Tensor of shape [tokens, 1] containing each routed token’s probability.
Callable mapping tensors of shape [chunk_tokens, gate_up] and [chunk_tokens, 1] to a tensor of shape [chunk_tokens, intermediate].
Whether to apply permuted_probs after the down projection instead of in
activation_fn.
Returns: torch.Tensor
Tensor of shape [tokens, hidden] in hidden_states.dtype with independent storage.
Reduce one expert’s contiguous token gradients without atomic writes.
grad_output_ptr is a contiguous row-major [tokens, hidden] allocation and probs_ptr is a
contiguous FP32 [tokens, 1] allocation when USE_PROBS is true. The caller ensures the gradient row
stride is descriptor-aligned and token offsets fit in int32. Each program exclusively owns one contiguous
FP32 [expert, hidden block] tile in grad_bias_ptr, so the reduction order is deterministic.
Permute tokens by expert assignment and compute offs for torch._grouped_mm.
Takes the raw router outputs and produces sorted token IDs, routing weights, tokens_per_expert counts, and cumulative offsets ready for grouped GEMM.
Returns:
Token indices sorted by expert assignment.
Reduce bias gradients without full-size intermediates.
Parameters:
Tensor of shape [tokens, hidden], grouped contiguously by expert.
Tensor of shape [experts] containing each contiguous segment length.
Optional routing probabilities of shape [tokens, 1].
Result dtype.
Returns: torch.Tensor
Tensor of shape [experts, hidden] with one weighted gradient sum per expert.
Reduce grouped token gradients without requiring Triton.
Parameters:
Tensor of shape [tokens, hidden], grouped contiguously by expert.
Tensor of shape [experts] containing each contiguous segment length.
Returns: torch.Tensor
Tensor of shape [experts, hidden] with one gradient sum per expert.
Reduce grouped CUDA token gradients with deterministic compensated FP32 sums.
Parameters:
Contiguous CUDA tensor of shape [tokens, hidden], grouped by expert. Supported dtypes are FP16, BF16, and FP32.
Contiguous CUDA tensor of shape [experts] containing each segment length.
Optional FP32 routing probabilities of shape [tokens, 1].
Result dtype. Defaults to grad_output.dtype.
Returns: torch.Tensor
CUDA tensor of shape [experts, hidden] and output_dtype when provided,
Resolve the per-expert split sizes for TE’s grouped GEMM.
Parameters:
Per-local-expert token counts of shape [num_local_experts] (CUDA tensor from the flex dispatcher, or an already-materialized sequence).
Benchmark-only static-routing mode (see
BackendConfig.benchmark_static_routing) under which the counts are
constant for every microbatch.
The first microbatch’s split list, or None before it is known.
Returns: list
The split sizes as a Python list. Under static routing with a warm cache the
Reduce contiguous expert segments into an accumulation-dtype tensor.
Parameters:
Tensor of shape [tokens, hidden], grouped contiguously by expert.
Tensor of shape [experts] containing each contiguous segment length.
Dtype used by the segmented sums.
Returns: torch.Tensor
Tensor of shape [experts, hidden] in accumulation_dtype.
Keep empty expert probabilities stable across checkpoint recomputation.
DeepEP may return an empty probability tensor in either the router dtype or the activation dtype. With non-reentrant activation checkpointing, a later recomputation can choose the other representation, and PyTorch checkpointing rejects the resulting saved-tensor metadata change even though both tensors contain zero elements. Empty probabilities have no numerical contribution, so canonicalize only that case to the dispatched activation dtype. Non-empty probabilities retain their original (normally FP32) router precision.
Clamped SwiGLU (DeepSeek V4 style) for DeepEP.
Gate is clamped at max=limit and up at (-limit, +limit) in FP32
before silu(gate) * up; the result is multiplied by the permuted
routing probs and cast back. Matches the official V4 Expert.forward::
gate = self.w1(x).float() up = self.w3(x).float() if self.swiglu_limit > 0: up = torch.clamp(up, min=-swiglu_limit, max=swiglu_limit) gate = torch.clamp(gate, max=swiglu_limit) y = F.silu(gate) * up
x has shape [..., 2 * inter_dim] with gate in the first half
and up in the second half (same layout as weighted_bias_swiglu_impl).
Add weighted expert bias without expanded bias or FP32 activation buffers.
Parameters:
Tensor of shape [tokens, hidden] containing grouped expert outputs.
Tensor of shape [experts, hidden] containing per-expert biases.
Contiguous integer tensor of shape [tokens] mapping each row to its expert.
FP32 tensor of shape [tokens, 1] containing routing weights.
Tensor of shape [tokens, hidden], optionally aliasing value_ptr exactly.
Number of output elements.
Feature count.
Value row stride.
Value feature stride.
Bias expert stride.
Bias feature stride.
Probability row stride.
Output row stride.
Output feature stride.
Number of elements processed by each program.
Reduce each row’s bias-weighted gradient without expanded bias buffers.
Parameters:
Upstream gradient of shape [tokens, hidden].
Per-expert bias of shape [experts, hidden].
Contiguous integer tensor of shape [tokens] mapping each row to its expert.
FP32 probability gradient of shape [tokens, 1].
Feature count.
Upstream-gradient row stride.
Upstream-gradient feature stride.
Bias expert stride.
Bias feature stride.
Probability-gradient row stride.
Power-of-two feature extent processed by each program.
Return the DeepEP expert activation function selected by the MoE config.
Check if activation requires gating (gate_proj + up_proj).
Gated activations (SwiGLU, Quick-GEGLU) use both gate_proj and up_proj, requiring gate_and_up_projs tensor with shape [n_experts, dim, 2*inter_dim].
Non-gated activations (ReLU²) only use up_proj, requiring up_projs tensor with shape [n_experts, dim, inter_dim] - 50% memory savings.
Apply DeepEP Quick-GEGLU activation and routing probabilities.
ReLU² activation for DeepEP: relu(x)^2
For DeepEP with ReLU², x is the output of the up projection (already computed). x already has shape […, inter_dim] from efficient up_proj.
Clamped SwiGLU (DeepSeek V4 style) for DeepEP: Triton kernels on CUDA, the compiled function elsewhere.
See nemo_automodel.components.moe.swiglu_triton for the kernels and the layout guard.
SwiGLU-OAI (GPT-OSS / MiniMax-M3) activation for grouped experts.
Computes gate * sigmoid(alpha * gate) * (up + 1) in fp32 with gate
clamped max=limit and up clamped +/-limit (when limit > 0).
Unlike quick_geglu_deepep (which expects an interleaved gate/up
layout, x[..., ::2] / x[..., 1::2]), this reads the concatenated
[gate | up] layout produced by MoESplitExpertsStateDictMixin
(torch.cat([gate_t, up_t], dim=-1)), matching sglang’s
swiglu_no_interleaved_with_alpha_and_limit.