Enabling DP only causes NaN
Describe the bug
When training on a single machine with 8 GPUs using only data parallelism (DP), running LLaMA-2-7B results in NaNs
Steps/Code to reproduce bug
Docker: nvcr.io/nvidia/pytorch:25.09-py3 Megatron-LM: core_v0.14.0
torchrun \ --nproc_per_node 8 \ --nnodes 1 \ --node_rank 0 \ --master_addr hostname \ --master_port 1001 pretrain_gpt.py \ --data-path /path/to/dataset \ --tokenizer-model /path/to/tokenizer.model \ --num-layers 16 \ --hidden-size 4096 \ --ffn-hidden-size 11008 \ --num-attention-heads 32 \ --attention-dropout 0 \ --hidden-dropout 0 \ --use-rotary-position-embeddings \ --untie-embeddings-and-output-weights \ --swiglu \ --normalization RMSNorm \ --disable-bias-linear \ --tokenizer-type Llama2Tokenizer \ --attention-softmax-in-fp32 \ --make-vocab-size-divisible-by 100 \ --lr 1e-6 \ --lr-decay-style cosine \ --min-lr 1e-8 \ --adam-beta1 0.9 \ --adam-beta2 0.95 \ --adam-eps 1e-8 \ --weight-decay 0.1 \ --clip-grad 1 \ --lr-warmup-iters 1 \ --split 949,50,1 \ --log-interval 1 \ --save-interval 10000 \ --eval-interval 1000 \ --no-load-optim \ --no-load-rng \ --position-embedding-type rope \ --no-position-embedding \ --use-flash-attn \ --use-distributed-optimizer \ --bf16 \ --train-iters 10 \ --eval-iters 1 \ --tensor-model-parallel-size 1 \ --pipeline-model-parallel-size 1 \ --context-parallel-size 1 \ --expert-model-parallel-size 1 \ --sequence-parallel \ --seq-length 2048 \ --max-position-embeddings 2048 \ --micro-batch-size 1 \ --global-batch-size 8 \ --transformer-impl transformer_engine \ --overlap-grad-reduce \ --overlap-param-gather
Expected behavior
training ... Overwriting rerun_state_machine.current_iteration from -1 to 0... [before the start of training step] datetime: 2025-11-18 11:41:17 WARNING:megatron.core.rerun_state_machine:Result validation enabled /usr/local/lib/python3.12/dist-packages/torch/distributed/distributed_c10d.py:4814: UserWarning: No device id is provided via init_process_grouporbarrier . Using the current device set by the user. warnings.warn( # warn only once [2025-11-18 11:41:22] iteration 1/ 10 | consumed samples: 8 | elapsed time per iteration (ms): 5335.0 | learning rate: 1.000000E-06 | global batch size: 8 | loss scale: 1.0 | grad norm: nan | number of skipped iterations: 0 | number of nan iterations: 0 | Number of parameters in transformer block in billions: 1.62 Number of parameters in embedding layers in billions: 0.26 Total number of parameters in billions: 1.88 Number of parameters in most loaded shard in billions: 1.8813 Theoretical memory footprints: weight and optimizer=32294.39 MB [Rank 0] (after 1 iterations) memory (MB) | allocated: 32951.32421875 | max allocated: 32951.328125 | reserved: 34366.0 | max reserved: 34366.0 ERROR:megatron.core.rerun_state_machine:Unexpected result nan on rank 0 at iteration #2 invokation #1 (message='found NaN in local forward loss calculation') WARNING:megatron.core.rerun_state_machine:Need to rerun step to check reproducibility of initial result WARNING:megatron.core.rerun_state_machine:First rerun: unexpected result is reproducible within the tolerance (nan = nan). Need to rerun on a different GPU to verify correctness WARNING:megatron.core.rerun_state_machine:Saving a checkpoint and exiting now. Please resume the job from the checkpoint to rerun the last iteration and establish a diagnostic
Additional context
When the use-distributed-optimizer option is disabled, NaNs do not occur.
When replace _get_param_groups (megatron/core/optimizer/init.py) by 0.12.0 version, NaNs do not occur.
After enabling use_distributed_optimizer, a parameter copy operation is performed when creating the DP module.
When DP is created using a separate CUDA stream, it is not guaranteed that the parameter initialization before it and the copy operation inside DP will execute in order. It is also not guaranteed that the copy operation and the subsequent forward pass will execute in order. Therefore, it is necessary to insert wait_stream before and after to enforce execution ordering.
dp_stream = torch.cuda.Stream()
dp_stream.wait_stream(torch.cuda.current_stream())
with torch.cuda.stream(dp_stream):
model = [
DP(
config=config,
ddp_config=ddp_config,
module=model_chunk,
# Turn off bucketing for model_chunk 2 onwards, since communication for these
# model chunks is overlapped with compute anyway.
disable_bucketing=(model_chunk_idx > 0)
or args.overlap_param_gather_with_optimizer_step,
)
for (model_chunk_idx, model_chunk) in enumerate(model)
]
torch.cuda.current_stream().wait_stream(dp_stream)
Fixed in https://github.com/NVIDIA/Megatron-LM/pull/2852