[bug] MoE + expert parallel + `gradient_checkpoint full` fails at step 0: CheckpointError from HybridEP dispatch token-count drift
Problem
Any MoE model trained with --fsdp.ep_size > 1 and the hybridep dispatcher
fails on the first backward pass with:
torch.utils.checkpoint.CheckpointError: torch.utils.checkpoint: Recomputed values
for the following tensors have different metadata than during the forward pass.
The mismatched dimension is the permuted token count after expert dispatch — forward and recompute disagree by a few tokens, so the grouped-GEMM activations change shape between the two passes.
This is the default configuration of every shipped flagship MoE recipe, so those recipes cannot run as written:
| recipe | ep_size | AC |
|---|---|---|
examples/scripts/slurm/sft_qwen3_6_35b.sh:57,116 |
8 | full |
examples/scripts/quick_start/sft_qwen3_6_35b.sh:43,78 |
8 | full |
examples/scripts/slurm/sft_omni3_30b.sh:62,76 |
8 | full |
examples/scripts/slurm/rl_qwen3_6_35b.sh:42,47 |
8 | full |
examples/scripts/slurm/rl_glm5_2_753b.sh:42,45 |
256 | full |
The existing mitigation does not prevent it
molt/trainer/fsdp/strategy.py:242-262 sets ignore_router_for_ac=True
specifically to avoid this error, on the theory that recomputing the router
re-routes near-tie tokens and shifts per-expert counts.
Instrumentation shows that mitigation works as designed and is still not sufficient:
- The router matcher fires.
_is_router_projectioninnemo_automodel/components/moe/parallelizer.py:459-477does match the router projection, which is therefore markedMUST_SAVE:[DBG-AC] want hidden=256 experts=8 | aten.mm.default args=((56, 256), (256, 8)) MATCHED=True - Routing is byte-identical across forward and recompute. Probing right after
weights, indices, aux_loss = self.gate(...)innemo_automodel/components/moe/layers.py, the same layer object (id=) yields identical token counts, index sums, masks, and per-expert bincounts:forward id=...157750 ntok=58 isum=309 mask=57 counts=[0,55,0,1,49,11,0,0] recompute id=...157750 ntok=58 isum=309 mask=57 counts=[0,55,0,1,49,11,0,0] forward id=...1566d0 ntok=58 isum=388 mask=57 counts=[48,0,6,0,0,0,58,4] recompute id=...1566d0 ntok=58 isum=388 mask=57 counts=[48,0,6,0,0,0,58,4]
So the routing decision is preserved, yet the post-dispatch token count still drifts. The divergence originates below the router, in the HybridEP dispatch/all-to-all layer.
Suspected cause
_HybridEPManager in
nemo_automodel/components/moe/megatron/token_dispatcher.py:340-445 carries
mutable per-instance state across the dispatch call — self.num_permuted_tokens,
self.pad_multiple, self.routing_map, self.token_probs, self.handle.
Under non-reentrant activation checkpointing the same manager instance is
re-entered during recompute, so stale state from the forward pass is visible.
Only one of those fields has been guarded, and its comment names this exact
mechanism (token_dispatcher.py:408-410):
# Reset num_permuted_tokens to None to avoid reusing cached state from a prior dispatch.
# This can happen in non-reentrant activation checkpointing mode.
The remaining fields appear to need the same treatment.
Minimal repro
# 4x H20 (sm_90). Any MoE checkpoint; smallest observed repro is a 4-layer /
# 8-expert config, so no large download is needed to reproduce.
torchrun --standalone --nproc_per_node=4 -m molt.cli.train_sft \
--model.model_name_or_path /path/to/Qwen3.6-35B-A3B \
--data.dataset sft.jsonl --data.input_key prompt --data.output_key response \
--data.max_len 256 --data.max_samples 128 \
--model.lora.rank 16 --model.lora.alpha 32 \
--model.lora.target_modules '*_proj' '*experts' \
--train.max_epochs 2 --train.batch_size 16 --train.micro_batch_size 1 \
--fsdp.param_dtype bf16 --fsdp.attn_implementation sdpa \
--fsdp.ep_size 4 \
--model.gradient_checkpoint full \
--model.aux_loss_coef 0.001 --adam.lr 2e-4
# Fails at "Train step of epoch 0: 0%| | 0/32" on all ranks, rc=1.
# Workaround: --model.gradient_checkpoint none -> 2 epochs complete cleanly.
Reproduced across four models, two architectures, with and without LoRA
| model | architecture | LoRA | drift |
|---|---|---|---|
| 4-layer / 8-expert MoE | Qwen3MoeForCausalLM |
no (full FT) | 151 → 150 |
| Qwen3-30B-A3B-Base | Qwen3MoeForCausalLM |
yes | 271 → 268 |
| Qwen3.5-35B-A3B | Qwen3_5MoeForConditionalGeneration |
yes | 218 → 220 |
| Qwen3.6-35B-A3B | Qwen3_5MoeForConditionalGeneration |
yes | 246 → 248 |
The drift is not one-directional (both shrink and grow occur), is independent of
LoRA, model scale, and architecture, and reproduces at ep_size 2 and 4.
MOLT_MOE_DISPATCHER=torch does not hit this — the DTensor all-gather path
produces fixed shapes. The failure is specific to the ragged permuted buffer used
by hybridep (and, by inspection of the shared code path, deepep).
Expected behavior
gradient_checkpoint full composes with ep_size > 1, as the shipped recipes
assume. Recompute should observe the same permuted token count as the forward
pass, so backward succeeds.
Failing that, molt should reject the combination up front with an actionable
message instead of surfacing a raw CheckpointError at step 0.
Environment
Branch / commit: main @ 64b6e44
Container: not the project image; local venv matching dockerfile/Dockerfile
pins (torch 2.11.0+cu130, DeepEP 42144303 incl. DeepEP #638,
AutoModel a3aa09bcc == requirements.txt pin). Python 3.11
vs the image's 3.12.
GPU / machine: 4x NVIDIA H20 (sm_90, 78 SMs, 97871 MiB), full-mesh NV18 NVLink
Python / CUDA / torch: 3.11 / 13.0 / 2.11.0+cu130
Dispatcher: hybridep (default), GroupedExpertsDeepEPLoRA on all 40 layers
Note on H20: HybridEP's preprocessing kernel defaults to a grid of 108 blocks, which exceeds this GPU's 78 SMs. Since the kernel does a grid-wide scan requiring all blocks to be co-resident, it deadlocks before reaching the bug above; the grid must be clamped to the device SM count first. That is a separate issue.
Logs
[LoRA] rank=16 alpha=32 dropout=0.0: trainable 934.1M / 36041.2M params (2.59%)
Train step of epoch 0: 0%| | 0/32
[rank2]: Traceback (most recent call last):
[rank2]: raise CheckpointError(
[rank2]: torch.utils.checkpoint.CheckpointError: torch.utils.checkpoint: Recomputed
[rank2]: values for the following tensors have different metadata than during the
[rank2]: forward pass.
[rank2]: tensor at position 91:
[rank2]: saved metadata: {'shape': torch.Size([246, 2048]), 'dtype': torch.bfloat16, ...}
[rank2]: recomputed metadata: {'shape': torch.Size([248, 2048]), 'dtype': torch.bfloat16, ...}
[rank2]: tensor at position 94:
[rank2]: saved metadata: {'shape': torch.Size([246, 16]), 'dtype': torch.bfloat16, ...}
[rank2]: recomputed metadata: {'shape': torch.Size([248, 16]), 'dtype': torch.bfloat16, ...}
[rank2]: tensor at position 95:
[rank2]: saved metadata: {'shape': torch.Size([246, 1024]), 'dtype': torch.bfloat16, ...}
[rank2]: recomputed metadata: {'shape': torch.Size([248, 1024]), 'dtype': torch.bfloat16, ...}
rc=1
The three shapes are the same tensor at three widths: hidden (2048), the LoRA rank-16 intermediate, and the fused gate/up projection (2 x moe_intermediate 512). Positions 91/94/95 are identical across models; only the token count differs.
Downstream tracking issue for the recipe-level impact: NVIDIA-NeMo/labs-molt#60
Hi,@HuiyingLi, automodel version is 0.5.0+a3aa09bcc
https://github.com/NVIDIA-NeMo/Automodel/pull/3140 could you please take a look if this fixes it?
I'd recommend trying a more recent commit. This should have been fixed already :) Please let us know if it's still there on main TOT.
I'd recommend trying a more recent commit. This should have been fixed already :) Please let us know if it's still there on main TOT.
Thank you! I'll try it again.
Confirmed: on main TOT (0.5.0+61da36805) the CheckpointError is gone — #3140 fixes it. Thanks!
Same repro now hits a different error in the forward pass at step 0, on the linear-attention in_proj_qkv: activation is bf16 but the weight is fp32, and nothing casts between them.
File ".../qwen3_5_moe/model.py", line 211, in forward
attn_out = self.linear_attn(...)
File ".../qwen3_5_moe/cp_linear_attn.py", line 357, in forward
return self._forward_no_cp(...)
File ".../qwen3_5_moe/cp_linear_attn.py", line 195, in _forward_no_cp
mixed_qkv = self.in_proj_qkv(hidden_states)
File ".../torch/nn/modules/linear.py", line 134, in forward
return F.linear(input, self.weight, self.bias)
RuntimeError: expected mat1 and mat2 to have the same dtype, but got: c10::BFloat16 != float
Fires on all ranks at Train step of epoch 0: 0%. This looks related to #3255, which sets cast_forward_inputs=False for fp32 param groups on the assumption that fp32 compute modules cast their own inputs — but in_proj_qkv receives the bf16 activation uncast. Happy to open a separate issue if you'd prefer to track it on its own.
Repro: Qwen3.6-35B-A3B (Qwen3_5MoeForConditionalGeneration), LoRA, --fsdp.ep_size 4 --model.gradient_checkpoint full, hybridep dispatcher.
Environment:
automodel : 0.5.0+61da36805 (main TOT)
python : 3.11.13
torch : 2.11.0+cu130 (CUDA 13.0)
GPU : 4x NVIDIA H20 (sm_90)
If you're open to it, I can open a PR to fix this bug.
Also reproduces on a standard MoE (qwen3_moe), not just the SSM-hybrid qwen3_5_moe
Hit the same CheckpointError at step 0 with Qwen3-30B-A3B (Qwen3MoeForCausalLM / qwen3_moe) — plain grouped-expert MoE, regular attention, no shared_expert_gate and none of the fp32-master / linear-attention machinery that qwen3_5_moe has. So this is not specific to the Qwen3.5/3.6 architecture; it's the generic MoE + expert parallel + gradient_checkpoint full path.
Config: ep_size=4, gradient_checkpoint=full, param_dtype=bf16, hybridep dispatcher, 4×H20, main @ 61da36805, torch 2.11.0+cu130.
The drifting tensors are the permuted MoE dispatch tensors (hidden [N, 2048], router [N, 16], expert-in [N, 1536] / [N, 768], scale [N, 1] fp32) — only the token dimension N differs between the saved forward and the recompute:
[rank1]: torch.utils.checkpoint.CheckpointError: torch.utils.checkpoint: Recomputed values for the following tensors have different metadata than during the forward pass.
[rank1]: tensor at position 61:
[rank1]: saved metadata: {'shape': torch.Size([162, 2048]), 'dtype': torch.bfloat16, 'device': device(type='cuda', index=1)}
[rank1]: recomputed metadata: {'shape': torch.Size([161, 2048]), 'dtype': torch.bfloat16, 'device': device(type='cuda', index=1)}
[rank1]: tensor at position 64:
[rank1]: saved metadata: {'shape': torch.Size([162, 16]), 'dtype': torch.bfloat16, 'device': device(type='cuda', index=1)}
[rank1]: recomputed metadata: {'shape': torch.Size([161, 16]), 'dtype': torch.bfloat16, 'device': device(type='cuda', index=1)}
[rank1]: tensor at position 65:
[rank1]: saved metadata: {'shape': torch.Size([162, 1536]), 'dtype': torch.bfloat16, 'device': device(type='cuda', index=1)}
[rank1]: recomputed metadata: {'shape': torch.Size([161, 1536]), 'dtype': torch.bfloat16, 'device': device(type='cuda', index=1)}
[rank1]: tensor at position 66:
[rank1]: saved metadata: {'shape': torch.Size([162, 1]), 'dtype': torch.float32, 'device': device(type='cuda', index=1)}
[rank1]: recomputed metadata: {'shape': torch.Size([161, 1]), 'dtype': torch.float32, 'device': device(type='cuda', index=1)}
[rank1]: tensor at position 71:
[rank1]: saved metadata: {'shape': torch.Size([162, 768]), 'dtype': torch.bfloat16, 'device': device(type='cuda', index=1)}
[rank1]: recomputed metadata: {'shape': torch.Size([161, 768]), 'dtype': torch.bfloat16, 'device': device(type='cuda', index=1)}
[rank1]: tensor at position 74:
[rank1]: saved metadata: {'shape': torch.Size([162, 16]), 'dtype': torch.bfloat16, 'device': device(type='cuda', index=1)}
[rank1]: recomputed metadata: {'shape': torch.Size([161, 16]), 'dtype': torch.bfloat16, 'device': device(type='cuda', index=1)}
[rank1]: .
Per-rank token counts, forward vs recompute:
| rank | forward | recompute | Δ |
|---|---|---|---|
| 0 | 277 | 275 | −2 |
| 1 | 162 | 161 | −1 |
| 2 | 204 | 203 | −1 |
| 3 | 253 | 257 | +4 |
The total is conserved (896 both times) but the per-rank split changes on recompute — tokens are redistributed across the EP group, not dropped. This points at the dispatch/permutation across the expert-parallel all-to-all being non-deterministic between the original forward and the checkpoint recompute, rather than a token being lost. (For comparison, the original qwen3_5_moe report drifts by −1 on rank1: [171, 2048] → [170, 2048].)
Thanks closing this issue since the new error is tracked/fixed in a separate issue.
Reopening because the original CheckpointError is still reproducible. The closure appears to refer to the separate Qwen3.5 dtype error, but the later standard-Qwen3 reproduction on 61da36805 still hits the original HybridEP checkpoint-recompute failure.
Important reproduction detail: fixed-length/padded inputs pass. The failure requires variable sequence lengths across the EP ranks.
My reproduction uses:
Qwen/Qwen3-30B-A3B, LoRA rank 16 / alpha 32, bf16- 4 GPUs, FSDP2,
ep_size=4, TP/PP/CP=1 - SDPA attention, GMM experts, HybridEP dispatcher
- full activation checkpointing
- SQuAD, max length 256, local batch size 1
padding: false, so each rank receives its sample's natural sequence length
Results on both torch 2.11/CUDA 13.1 and the canonical 26.06 container with torch 2.12/CUDA 13.2:
| Revision/config | Result |
|---|---|
61da36805, padding: max_length |
passes |
61da36805, padding: false |
CheckpointError on first backward |
PR #3330 head, padding: max_length |
passes |
PR #3330 head, padding: false |
same CheckpointError |
61da36805, padding: false, activation checkpointing disabled |
passes |
During the failing recompute, per-rank permuted-token counts change while the global total remains conserved. This matches the issue's original HybridEP dispatch-token drift, rather than the separate dtype error.
I investigated a bit more. This issue matches upstream deepseek-ai/DeepEP#604. DeepEP currently does not officially support different token dimensions across GPUs and recommends padding as the workaround.
For now, please use fixed-length padding, such as padding: max_length, so every GPU uses the same configured sequence length. Padded tokens are ignored by attention, MoE routing, and the training loss, although the additional padding may increase memory usage and reduce throughput.
A minimal AutoModel improvement could detect this unsupported HybridEP configuration early, produce a clear error, and document the fixed-length requirement. A fuller solution could make the GPUs agree on a common length for each batch, add only the padding HybridEP needs, and remove it afterward. This would need careful correctness testing and performance measurements.
I investigated a bit more. This issue matches upstream deepseek-ai/DeepEP#604. DeepEP currently does not officially support different token dimensions across GPUs and recommends padding as the workaround.
For now, please use fixed-length padding, such as
padding: max_length, so every GPU uses the same configured sequence length. Padded tokens are ignored by attention, MoE routing, and the training loss, although the additional padding may increase memory usage and reduce throughput.A minimal AutoModel improvement could detect this unsupported HybridEP configuration early, produce a clear error, and document the fixed-length requirement. A fuller solution could make the GPUs agree on a common length for each batch, add only the padding HybridEP needs, and remove it afterward. This would need careful correctness testing and performance measurements.
Thank you for reply!
Another data point, on DeepSeek-V4-Pro with the hybridep dispatcher in nvcr.io/nvidia/nemo-automodel:26.08 (r0.6.0, 922e83e4), 16 × 8 H100-80GB, PP1 × EP64 (ep_shard 2), LoRA, activation_checkpointing: true, default defer_fsdp_grad_sync: true:
-
Fixed-length padding does not prevent it. Every sample was pre-tokenised and right-padded to exactly 2048 tokens (
local_batch_size 1,pad_seq_len_divisible 64, so all 128 ranks dispatch the same 2048 tokens every micro-batch). The run was clean for 29 steps and then, in the step-30 backward, one rank (50 of 128) raisedtorch.utils.checkpoint.CheckpointError: Recomputed values for the following tensors have different metadata than during the forward pass. tensor at position 111: saved {'shape': torch.Size([3197, 6144]), 'dtype': torch.bfloat16} recomputed {'shape': torch.Size([3325, 6144]), ...} tensor at position 112: saved {'shape': torch.Size([3197, 1]), 'dtype': torch.float32} recomputed {'shape': torch.Size([3325, 1]), ...}i.e. the permuted token count after the HybridEP dispatch changed by 128 tokens between forward and recompute on that rank only. The other 127 ranks then sat in the next collective until the job was cancelled.
-
The same recipe at 1024 tokens (otherwise identical) ran 200 steps + 4 validation passes without a mismatch, so the drift is intermittent and more likely with more tokens per dispatch.
-
This is the
CheckpointErrorshape-mismatch variant; theaten.split … not found in storagevariant (#3958, fixed by #3961) did not appear in either run.
Since the token counts are already uniform here, this looks like the forward/recompute non-determinism of the dispatch itself rather than a ragged-batch problem. Full logs are kept; happy to attach the rank-50 traceback and the config dump if useful.