Mixture of Experts
MoE Features
- Combined 1F1B: Expert-Parallel All-to-All Overlap
- Multi-Token Prediction (MTP)
- Multi-Latent Attention
- Design Document: MoE Router Replay Feature
Megatron Core MoE
Megatron Core MoE is a production-ready stack for training large-scale Mixture-of-Experts models, built on the Megatron Core framework. It provides foundational architecture, performance optimizations, and best practices that guide MoE development across the industry.
Whatβs New
For the latest features and architectures, please refer to the MCore dev roadmap.
π₯ [MCore dev] (2026/01)
- π Pipeline-aware fine-grained activation offloading
- π Qwen3-Next model support
- π DeepSeek-V3.2 model support
- π Muon and Layer-wise distributed optimizer
- π CUDA Graph support with fine-grained scopes
π₯ [MCore v0.15] (2025/11)
- π Add HybridEP backend to Flex Dispatcher(GB200, B200, H100 supported)
- π Support FSDP with EP for MoE models
π₯ [MCore v0.14] (2025/09)
- π Batch-level overlapping to hide EP-A2A communication (βoverlap-moe-expert-parallel-comm βdelay-wgrad-compute)
- π FP8 support for Fine-grained Recomputations
- Router fusion kernels for MoE models (βmoe-router-fusion)
- Context Parallelism (CP) support for MTP and MLA
π₯ [MCore v0.13] (2025/07)
- Support bf16 dtype for optimizer states to use precision-aware optimizer in TransformerEngine (βuse-precision-aware-optimizer)
- Flexible Asymmetric Virtual Pipeline Parallelism with Custom Pipeline Layout (βpipeline-model-parallel-layout)
- Add Hybrid Shard Data-Parallel support for MoE models (βnum-distributed-optimizer-instances)
- Fine-grained recomputation to reduce activation memory. (βrecompute-modules with βrecompute-granularity selective)
- Memory efficient token permutation by moving the probs multiplication from unpermutation to activation function of GroupedMLP.
π₯ [MCore v0.12] (2025/05)
- Support DeepSeekβs DeepEP for efficient token dispatching (βmoe-token-dispatcher-type flex βmoe-enable-deepep)
- Support Multi-Token Prediction (MTP) (βmtp-num-layers 1)
- CUDA Graph support for dropless MoE models with attention only capture (βte-rng-track βexternal-cuda-graph βcuda-graph-scope attn)
Overview of MCore MoE Supported Features and Architectures
Model Support
- β
DeepSeek
- β DeepSeek-V2
- β DeepSeek-V3, including MTP
- β
Qwen
- β Qwen2-57B-A14B
- β Qwen3-30B-A3B
- β Qwen3-235B-A22B
- β
Mixtral
- β Mixtral-8x7B
- β Mixtral-8x22B
Core MoE Functionality
- β Token dropless MoE (dMoE) - Advanced routing without token dropping
- β Top-K Router with flexible K selection
- β Load balancing losses for expert utilization optimization
Advanced Parallelism
- β Expert Parallel (EP) with 3D parallelism integration
- β Full parallelism combo: EP + DP + TP + PP + SP support
- β Context Parallel (CP) for long sequence MoE training
- β Parallel Folding Heterogeneous Parallelism Mappings for Efficient Large-Scale MoE Model Training
- β Distributed Optimizer for MoE (ZeRO-1 equivalent)
Performance Optimizations
- β Memory Efficient token permutation
- β Fine-grained Recomputations (mla, moe, mlp, moe_act, norm)
- β MLA TP Support for Mixture of Linear Attention
- β GroupedGEMM and GA Fusion
- β DP/PP/TP Communication Overlapping
- β Overlapped Shared Expert execution
- β Router Fusion optimizations
- β Token (un)permutation Fusion kernels
- β cuDNN fused Attention integration
Hardware & Precision Support
- β DeepEP support for H100 and B200
- β GroupedGEMM including FP8/MXFP8 support
- β FP8 weights with BF16 optimizer states
- β FP8 training full support
Developer Experience
- β MoE Model Zoo with pre-training best practices
- β Distributed Checkpointing for MoE models
- β Upcycling Support for model scaling
- β MCore2HF Converter for ecosystem compatibility
- β Layer-wise logging for detailed monitoring
- β Runtime Upcycling capabilities
Quick Start Guide
Basic MoE Training in Megatron-LM
To train a top-2 MoE model with 8 experts and auxiliary loss, add the following arguments to your megatron training script:
Detailed documentation for each feature is available in the Feature Documentation section.
Use the pre-defined config to train the popular MoE models
We have provided some pre-defined config to train the popular MoE models in the Megatron-MoE-Model-Zoo repository. You can use them as a reference to configure your training script. Currently we have added the config for Mixtral 8x7B, Mixtral 8x22B, DeepSeek-V3, Qwen3-30B-A3B, Qwen3-235B-A22B.
Default backends and SequentialMLP deprecation
The default training token dispatcher is alltoall, and moe_grouped_gemm=True selects grouped
experts on the Transformer Engine backend. Existing
--moe-grouped-gemm launch arguments remain valid. To explicitly use the previous choices,
pass --moe-token-dispatcher-type allgather and --no-moe-grouped-gemm (also spelled
--disable-moe-grouped-gemm). Python callers can set moe_grouped_gemm=False.
SequentialMLP is deprecated. Constructing it emits a FutureWarning once on the primary rank.
It remains available for local-backend, checkpoint, and per-expert post-training workflows.
The local backend still selects SequentialMLP even with moe_grouped_gemm=True; migrate to
the Transformer Engine backend to use TEGroupedMLP. Grouped experts require add_bias_linear=False or
bias_dropout_fusion=False when using linear biases.
With --use-checkpoint-args, an explicitly saved moe_grouped_gemm setting is still restored;
changing the default does not convert a SequentialMLP checkpointβs weight or optimizer layout.
The dispatcher remains a runtime choice: pass --moe-token-dispatcher-type allgather explicitly
to retain it when resuming. Inference-specific dispatchers and optional GroupedTensor, fused MLP,
and single-grouped-weight settings retain their existing defaults.
General Performance Tips
Training arguments
The following flags are general performance flags that can help to achieve higher performance on almost all workloads. Check if you have enabled all of them in your training script.
Environment variables
Below are some environment variables that can be useful.
Dependencies
- Use the latest version of TransformerEngine.
- Use the latest NGC PyTorch Docker Image
Best Practices to achieve high performance on MoE training
Distributed training involves complex trade-offs between communication, memory, and computation, making it challenging to find an optimal parallelism configuration. This section provides a systematic workflow to help you identify the best parallel mapping for your model and hardware.
Step 1: Find the feasible parallel mapping under the memory capacity of the GPU
To find the best parallel mapping, we need to first know the feasible parallel mapping for the model under the memory capacity of the GPU. The consumption of memory consists of three parts:
- Activation memory
- Weight and gradient memory
- Optimizer states memory Different parallel strategies will shard these tensor memory in different ways.
We provide the argument of --fake-init-process-group to emulate distributed training on one GPU. This is useful to find the feasible parallel mapping under the memory capacity of the GPU. See https://github.com/NVIDIA/Megatron-LM/pull/2254 for detailed usage.
Step 2: Select Optimal Parallelism Strategy
The optimal parallelism configuration varies based on model architecture, sequence length, and hardware platform. Below are general guidelines to help you achieve high throughput.
Guideline 1: Minimize Model Parallelism, Maximize Data Parallelism
Guideline 2: Keep EP and TP Communication Within NVLink Domain
Note: For very large MoE models like DeepSeek-V3, the EP communication may exceed the NVLink bandwidth. In this case, consider using 1F1B A2A Overlap to overlap the EP communication.
Guideline 3: Use Pipeline Parallelism (PP) for Multi-Node Scaling
VPP Size Tuning:
- Valid values: all divisors of
num_layers / PP_size - Example:
num_layers=24, PP=4β valid VPP sizes:{1, 2, 3, 6} - Trade-off: Larger VPP = fewer bubbles but more P2P communications
- Recommendation: A middle value often gives the best balance
Guideline 4: Prefer EP over TP for Expert Layers
Example: For Mixtral 8x7B, EP8ΓTP1 outperforms EP4ΓTP2.
Guideline 5: Enable Context Parallelism (CP) for Long Sequences
Step 3: Enable Performance Features Based on Profiling Bottlenecks
After establishing a working parallel configuration, profile your training to identify bottlenecks and apply targeted optimizations.
Memory Bottleneck
Symptom: Forced to use full recomputation or excessively large parallelism degrees to avoid OOM.
Solutions:
Communication Bottleneck
Symptom: Profiling shows significant time spent in collective operations.
Solutions: Identify which communication is the bottleneck and enable corresponding overlap:
CPU Overhead Bottleneck
Symptom: Nsight Systems timeline shows gaps between GPU kernels where CPU cannot launch kernels fast enough.
Solutions:
Computation Bottleneck
Symptom: GPU utilization is low despite no communication or CPU bottlenecks.
Solutions:
Feature Documentation
Router and Load Balancing
Routers determine which expert(s) handle each token. A lightweight MLP scores every token and applies softmax or sigmoid to compute routing probabilities. The router then selects the top-K experts for each token.
Note: The router logits is better to remain in FP32 or FP64 rather than BF16 by βmoe-router-dtype fp32. At high expert counts, FP32 precision yields better accuracy because output hidden states of experts are multiplied by router scores and accumulated to get the final output.
Router Types
Load Balancing Strategies
Token Dispatching
After routing, tokens are dispatched to the GPU hosting the assigned expert. After expert computation, tokens are sent back and combined to restore the original sequence.
Virtual-expert load balancing
Enable with --moe-token-dispatcher-type flex --moe-flex-dispatcher-backend hybridep --moe-virtual-expert-load-balance. MoonEP balances overloaded experts by temporarily copying
selected experts to other EP ranks. The planner uses the algorithm from
MoonshotAI/MoonEP; the integration here combines custom
Triton kernels, a virtual-expert dispatcher, and Transformer Engineβs grouped expert computation.
- Dispatcher: Flex selects
_VirtualExpertHybridEPManagerin token_dispatcher.py, which extends the existing HybridEP manager withVirtualExpertLoadBalancer. It accepts the routerβs[tokens, topk]expert IDs and probabilities, starts planning and weight prefetch, then supplies remapped runtime expert IDs to HybridEP. HybridEP handles token dispatch and combine using a fixed receive capacity calculated to cover the balanced workload and padding. - Triton kernels: virtual_expert_triton.py implements planning, selected-weight prefetch, and replica-gradient reduction. The planner combines histogram construction, cross-rank histogram exchange, placement, and route remapping in one cooperative kernel launch. Separate transport kernels push selected weights into peer virtual slots and read replica gradients back into their ownersβ native gradients through NCCL symmetric memory. These kernels move expert weights and gradients; token movement remains with HybridEP.
- Expert buffers: virtual_expert_load_balancer.py binds
native weights and temporary virtual slots into the FC1/FC2 runtime weight lists consumed by
TEβs grouped GEMMs. Compatible layers share persistent weight and gradient arenas, reusing
replica storage across layers. Non-GTP native gradients accumulate directly into DDP buffers;
GTP natives use stable wgrad buffers acquired through TEβs
DistributedWeightinterface. - Execution and backward: Autograd hooks coordinate planning, weight prefetch, and gradient reduction on separate CUDA streams, with events establishing dependencies on expert compute. Each forward retains its placement for backward, which refreshes replica weights before the expert GEMMs. FC2 replica-gradient reduction can start as soon as its wgrad is ready, followed by FC1. At the MoE input-backward boundary, compute waits for both replica reductions before handing gradients to DDP or expert GTP.
The routerβs logical expert selections and probabilities are preserved; remapping changes where the selected experts execute. Replica gradients return to the original parameters, which retain optimizer and checkpoint ownership. Replicas have no separate optimizer state.
Requirements and limits:
- Triton 3.5 or newer is required for launch-scoped descriptor allocation.
- Use EP sizes 2β64, up to 8,192 experts evenly divided across EP ranks, top-k from 1 to min(32, number of experts), and expert tensor parallel size 1.
- All layers must share one EP topology. Local token counts must be equal across EP ranks and remain fixed after each layerβs first forward.
- Use per-expert parameters with grouped-tensor GEMM, fused gradient accumulation, FP32 router
probabilities, and BF16 or native MXFP8 weights. The op fuser is optional. MXFP8 additionally
requires
--fp8-param --fp8-param-gather --reuse-grad-buf-for-mxfp8-param-agwith themxfp8recipe ande4m3format. - Use regular DDP or the distributed optimizer with eagerly allocated expert
main_gradbuffers. Megatron-FSDP v1/v2 and lazy gradient allocation are unsupported. Expert GTP is supported. - Leave
moe_expert_rank_capacity_factorunset and disablemoe_paged_stash. MoonEP selects static-capacity HybridEP transport and calculates its own dropless budget, including padding. Token dropping and expert capacity limits are unsupported. - Use
moe_hybridep_routing_map_mode='indices'(the default) and a HybridEP build supportingtopk_idx. MoonEP routers return selected expert IDs and probabilities directly. If TE cannot emit expert IDs, routing uses the unfused implementation. - Sinkhorn routing and DeepSeek-style expert bias (
--moe-router-enable-expert-bias) are unsupported. For CUDA graphs, use the whole-layermoescope rather thanmoe_routerormoe_preprocess. Full/whole-MoE recomputation is unsupported. FC1 CPU offload currently requires a separate HybridEP/TE capacity-buffer fix; MoE activation and fused-MLP offload have test coverage.
Supported routing includes FP32 sigmoid scores, router fusion, hash routing, seq_aux_loss, and quantile
balancing with its own bias update. For micro_batch quantile balancing, set
--moe-router-load-balancing-type quantile_balancing --moe-aux-loss-coeff 0, omit
--moe-router-enable-expert-bias and --moe-router-fusion, and disable
--moe-router-force-load-balancing. Quantile balancing requires token-count Γ top-k divisible
by the expert count and does not support padding masks or group-limited routing.
Virtual-expert gradients use FP32 storage and transport by default. With --grad-reduce-in-bf16,
native and replica partial gradients are stored in BF16, added locally in FP32, then downcast once.
BF16 partial storage can lose small cancellation residuals and increase optimizer-update differences;
later FP32 addition cannot recover those residuals. To retain FP32 accumulation in subsequent
reductions, enable --ddp-reduce-scatter-with-fp32-accumulation and, with expert GTP,
--gtp-remat-reduce-scatter-with-fp32-accumulation.
MoonEPβs peer handshakes and cooperative-grid barriers time out after approximately 100 seconds
of polling, including when TRITON_DEBUG=0. A timeout aborts the kernel and surfaces as an
asynchronous CUDA launch failure; restart the affected processes. Other ranks still waiting in
these barriers time out independently. This does not cover unrelated collectives or stalled
GPU instructions.
Training parity and supported offload/recompute cases are covered in
tests/unit_tests/transformer/moe/test_virtual_experts.py. Planner correctness and CUDA graph
replay are covered in tests/unit_tests/determinism/kernels/test_moe_kernels.py; checkpoint
loading and initialization parity are covered by
test_te_grouped_linear_virtual_expert_checkpoint in the neighboring test_te_wrappers.py.
Upcycling
Use --moe-use-upcycling to enable upcycling, which loads the dense model from the --load directory, converts it to an MoE model at runtime, and starts training. The converted model is saved to the --save path before training begins. Upcycling is built on distributed checkpointing, supporting parallel modes different from existing dense checkpoints, such as arbitrary expert parallelism during upcycling.
In addition to the default upcycling strategy, we also support granular upcycling strategy which is a more state-of-the-art upcycling strategy from our recent research work. For the default upcycling strategy, we duplicate the existing MLP to multiple experts, with each expert starting from a copy of the MLP. For the granular upcycling strategy, we use --moe-upcycling-granularity to specify how many times smaller is the expert hidden size compared with the original dense FFN hidden size. For using granular upcycling strategy, please set --moe-upcycling-granularity as a positive integer. If this param is set to 1, it means using the default upcycling strategy.
Note: The MoE model structure is defined through script arguments. All MoE-related arguments (such as --num-experts) can be customized; however, other model structure arguments must be consistent with those of the dense model. For granular upcycling strategy, the moeβs FFN hidden size should be set as dense FFN hidden size divided by --moe-upcycling-granularity.
Training Optimizations
MoE training faces three fundamental performance bottlenecks: Memory Wall, Communication Wall, and Compute Efficiency Wall. The following optimizations address each of these challenges.
MoE Parallel Folding
The Problem with Traditional Approaches:
- Prior MoE frameworks constrain EP β€ DP (Expert Parallelism must be a sub-group of Data Parallelism), which severely limits scalability.
- Applying the same TP/CP to both attention and MoE is suboptimal:
- High TP benefits attention but hurts MoE (small per-expert dims make TP overhead prohibitive)
- High CP benefits long-context attention but is unnecessary for MoE (tokens processed independently)
MoE Parallel Folding is Megatron Coreβs solution that decouples attention and MoE parallelism:
Key Benefits
-
Breaks the EP β€ DP Constraint
- Traditional: TP=4, CP=2, DP=8, PP=4 β max EP=8
- With Folding: Same attention config, but MoE uses ETP=1, EP=64, EDP=1 β 8Γ more expert parallelism
-
Reduces Minimum GPU Requirements
- Traditional CP=8, EP=8 requires at least 64 GPUs
- With Folding: CP and EP are folded together, only 8 GPUs needed
-
Enables Independent Optimization
- Use high TP for attention (memory efficiency)
- Use ETP=1 for MoE (better GEMM efficiency, less communication)
-
Keeps High-Bandwidth Communication in NVLink Domain
- Both CP and EP communication can remain within NVLink domain
Memory Optimization
Memory optimization is critical for large-scale MoE training, as MoE models maintain all expert parameters even though only a subset is activated per token.
Fine-grained Recomputation
A new output-discarding checkpointing method is also supported. This method discards the output memory of certain submodules during the forward pass and recomputes them during the backward pass, which can save memory compared to standard checkpointing. This can be enabled for specific submodules using the --recompute-granularity selective --recompute-modules [submodule1, submodule2, ...] argument. The supported submodules are:
moe_act: Recompute the GroupedMLP activation function.layernorm: Recompute the input_layernorm and pre_mlp_layernorm (when they are notIdentityOp).mla_up_proj: Recompute the MLA up projection and RoPE applying parts.core_attn: Recompute the core attention submodule (uses standard checkpointing rather than output-discarding).mlp: Recompute the dense MLP submodule (uses standard checkpointing rather than output-discarding) which is useful for hybrid-models like DeepSeek-V3.moe: Recompute the MoE layer submodule (uses standard checkpointing rather than output-discarding).
Fine-grained Activation Offloading
Unlike recomputation (which trades compute for memory), offloading trades GPU-CPU bandwidth for memory: activations are transferred to CPU during forward pass and retrieved during backward pass. The key is hiding transfer latency behind computation using asynchronous D2H/H2D transfers.
Key Features:
- Module-level granularity: Target specific modules rather than entire layers
- Computation-offloading overlap: Asynchronous transfers via independent CUDA streams
- Compatible with PP/VPP: Works with pipeline parallelism and fine-grained recomputation
Usage
For more details, see docs/user-guide/features/fine_grained_activation_offloading.md
Communication Optimization
Distributed training introduces communication overhead from various parallelism strategies. Megatron Core supports overlapping communication with computation to hide latency and improve throughput.
Data Parallel (DP) Communication Overlap
With distributed optimizer, DP introduces reduce-scatter (gradients) and all-gather (parameters) communications, chunked by Transformer layer granularity.
Tensor Parallel (TP) Communication Overlap
TP with sequence parallelism introduces activation all-gather and reduce-scatter operations. Communications are overlapped in bulk (no dependency) or pipelined (with dependency) fashion.
Requirements:
tensor_model_parallel_size >= 2and--sequence-parallel
Pipeline Parallel (PP) Communication Overlap
PP introduces P2P activation sends/receives between pipeline stages. Overlap is automatic in the 1F1B pipelining phase when VPP is enabled.
Expert Parallel (EP) Communication Overlap
EP All-to-All can consume 30-40% of training time without optimization. These features hide or reduce EP communication overhead.
Requirements for EP A2A Overlap:
expert_model_parallel_size > 1, CUDA_DEVICE_MAX_CONNECTIONS > 1.
Full activation recompute with EP A2A Overlap:
--recompute-granularity fullis supported and is applied per layer segment, so--recompute-methodand--recompute-num-layerscarry exactly the same meaning as without--overlap-moe-expert-parallel-comm. Both flags are required. This overlap recompute path requires--cuda-graph-impl none; CUDA Graph execution, includingfull_iteration, is not supported.
Compute Optimization
Fine-grained MoE produces many small operations that can underutilize GPU resources. These optimizations reduce kernel launch overhead and improve GPU utilization.
FP8 Training
FP8 training provides benefits across all three performance walls:
FP8 Recipes
Recommendation: Use blockwise FP8 on Hopper for production training. It has been validated at scale on DeepSeek-V3 class models.
MoE-Specific FP8 Optimizations
Example Configuration
Note: For blockwise and MXFP8 recipes with current scaling, training loss curves show negligible difference compared to BF16 baselines.
MoE Megakernel Backends
MOK
A megakernel backend replaces the native post-router dispatch, expert-compute, and combine path. Select MOK for a SwiGLU model with the following YAML configuration:
The equivalent backend-specific CLI value is a JSON object:
MOK is an optional dependency, imported only when the backend is selected. The ARM64 development
image already installs the supported
MCore integration snapshot
through docker/common/install_mok.sh. Use that image or its installation helper to retain the
supported dependency and Blackwell build targets. The AMD64 image skips MOK because its H100
target is unsupported.
Wgrad GEMMs accumulate in FP32. The destination main_grad dtype selects the reduction-store
precision: FP32 retains FP32 contributions, while BF16 rounds each contribution before adding it
to the BF16 gradient buffer. This is independent of the BF16 shared-expert weight dtype.
The pinned MOK entrypoint requires shared and routed expert main-grad buffers to use the same dtype.
The optional shared output gate aliases the native shared-expert parameter and accumulates into
its FP32 or BF16 main_grad. It supports Qwen3.5βs gated shared-expert MoE without changing native
parameter ownership or checkpoint keys; the GDN and attention layers retain their existing paths.
With reuse_grad_buf_for_mxfp8_param_ag, MCore completes parameter all-gather, requantizes into
native TE storage, and clears the staging buffer before MOK runs. Single-grouped MXFP8 parameters
require this mode in the current MCore buffer implementation. MOK aliases the native payloads
and refreshes its converted scale buffers once per optimizer iteration. The adapter requires
both native weight layouts; TEβs post_all_gather_processing is not an MXFP8 capability check.
Per-layer whole-layer capture (empty cuda_graph_modules) is distinct from
cuda_graph_impl=full_iteration. Per-layer MOK replay goes through a Transformer Engine graph that
contains the megakernel: the moe scope, or whole-layer capture, whose graph also contains the
rest of the layer. The layer refreshes MOKβs weight views eagerly before each replay. The moe
scope was validated only without pipeline parallelism, where each microbatchβs backward runs before
the next microbatch replays the layerβs graph, so both require pipeline_model_parallel_size=1.
Pipeline schedules keep several microbatches in flight, and per-layer MOK replay has not been
validated there. Transformer Engineβs capture warm-up runs the layer on static inputs whose
all-ones hidden states route every token to the same experts. The layerβs static padding_mask
input marks every token as padding, so the warm-up routes none, and each replay copies the batchβs
mask into it. The layer reserves that input only if a padding_mask reached it during the eager
warm-up steps (cuda_graph_warmup_steps > 0). Otherwise the capture raises an error before the
warm-up, unless moe_router_force_load_balancing (benchmark-only random routing) is set, so a run
whose batches carry no padding_mask must keep the MoE layer out of the graph, for example with
cuda_graph_modules=[attn]. Graphs that end between the router and MOK are not supported: capture
the whole MoE layer, or leave it out of the graph.
The current backend requires grouped experts and fused gradient accumulation. It does not support
linear biases, applying router probabilities to expert inputs, MCore EP 1F1B overlap or delayed
wgrad, native shared-expert overlap, shared-expert-only
recompute, latent MoE, GTP weight rematerialization, shortcut MoE, inference-optimized layers,
the moe_router and moe_preprocess CUDA Graph scopes, MCore expert-input
capacity padding, FC1 GLU-interleaved weights, or checkpoint conversion between physical weight
layouts.
GLU Checkpoint Layout
--moe-mlp-glu-interleave-size 32 makes routed expert activations interpret FC1
channels as alternating blocks of 32 gate and 32 up channels. Native Megatron-LM
converts contiguous checkpoint FC1 weights and biases into that runtime layout
before loading the model and initializing FP32 master weights. Both indexed
per-expert weights and single grouped weights are supported. Shared experts use
their separate --moe-shared-expert-glu-interleave-size setting when
--use-grouped-gemm-for-shared-expert is enabled.
GLU interleaving is unsupported with FP32 model parameters and is rejected during configuration validation. BF16 and FP16 model parameters remain supported, including when the optimizer uses FP32 master weights.
GLU interleaving also requires GTP weight sharding to be disabled for the affected
FC1: routed experts require expert_gtp_weight_remat_size=1, and grouped shared
experts require gtp_weight_remat_size=1. Configuration validation rejects these
combinations even when optimizer state is not loaded. GTP on other modules and
ordinary TP/ETP remain allowed.
For torch and torch_dist checkpoints, model weights are saved in contiguous
[all gate | all up] layout. Optimizer master weights and moments retain their
runtime layout, described by the existing saved configuration. GLU conversion
does not add checkpoint fields or layout metadata. Full optimizer resume
requires the same interleave sizes and the same ETP size for routed experts
(TP size for shared experts). To change those settings, load model weights with
--finetune or --no-load-optim and initialize a new optimizer. This also applies
when enabling interleaving on a checkpoint saved with a contiguous optimizer.
Model weights are always interpreted as contiguous, regardless of the interleave
settings in the saved configuration. Legacy checkpoints with interleaved model
weights must be converted to contiguous layout before loading; their source
layout is not detected automatically. In-place FSDP loading and
torch_dcp / fsdp_dtensor formats are not supported by this conversion.
CUDA Graph
CUDA Graph functionality can be enabled through the --cuda-graph-impl option. There are three implementations:
--cuda-graph-impl=local: Captures per-layer cuda graphs using the MCore-internal cuda graph manager.--cuda-graph-impl=transformer_engine: Captures per-layer cuda graphs using the TEmake_graphed_callables()interface.--cuda-graph-impl=full_iteration: Captures the whole training/evaluation forward-backward iteration as a single cuda graph.
For inference, CUDA graph scope is controlled separately with
--inference-cuda-graph-scope=layer|block together with
--cuda-graph-impl=local.
To use --cuda-graph-impl=transformer_engine, the user should call related methods TECudaGraphHelper.create_cudagraphs() and TECudaGraphHelper.cuda_graph_set_manual_hooks() in the training script. Please refer to the usage in megatron/training/training.py.
For MoE models, certain configurations may prevent CUDA Graph capture of MoE layers. Specifically, when --moe-expert-capacity-factor and --moe-pad-expert-input-to-capacity are not set, the resulting dynamic shapes make MoE layers uncapturable. In such cases, you can still leverage CUDA Graphs for the attention layers (operations in TransformerLayer._forward_attention()) by setting --cuda-graph-modules=attn, while leaving the MoE layers (operations in TransformerLayer._forward_mlp()) unmodified. See the argument description for more usage of --cuda-graph-modules.
MoE Arguments Reference
Core Arguments
Router Arguments
Loss and Regularization
Token Dispatching
Performance Optimization
Memory and Checkpointing
Miscellaneous
Examples
</details>
Contributing
We welcome contributions! Please see CONTRIBUTING.md for guidelines.
Support
- GitHub Issues: Report bugs or request features
- Documentation: Full documentation
- Performance: Latest MoE training performance summary
Citation
If you use Megatron Core MoE in your research, please cite: