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”)
Grouped GEMM forward path using torch._grouped_mm.
Per-expert loop forward path using gather/scatter.
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.
Supports two GEMM backends via BackendConfig.experts:
- grouped_gemm.ops.gmm (experts=“gmm”, default)
- torch._grouped_mm (experts=“torch_mm”, no external dependency)
Once the experts for a particular token have been identified, this module is invoked to compute and average the output of the activated 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]
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.
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
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
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].
Returns:
Grouped GEMM output with per-expert bias applied, shape
Reduce one expert’s contiguous token gradients without atomic writes.
grad_output_ptr is a contiguous row-major [tokens, hidden] allocation. The caller ensures its row
stride is descriptor-aligned and its token offsets fit in int32. Each program exclusively owns one
[expert, hidden block] output tile, 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 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.
Returns: torch.Tensor
CUDA tensor of shape [experts, hidden] and the same dtype as grad_output.
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.
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).
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 :func: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.