[BUG] Expert RNG seed depends on pp_rank + ep_rank only, so experts in different pipeline stages get identical initial weights
Describe the bug
The expert-parallel RNG seed depends on the pipeline rank and the expert-parallel rank only through their sum:
# megatron/training/initialize.py:466 (_set_random_seed)
seed = seed_ + (100 * pp_rank)
# megatron/core/tensor_parallel/random.py:525 (model_parallel_cuda_manual_seed)
expert_parallel_seed = seed + 1024 + 100 * ep_rank + etp_rankSo the expert seed is seed_ + 1024 + 100 * (pp_rank + ep_rank) + etp_rank, and the rank at (pp_rank=a, ep_rank=b) gets the same expert-parallel-rng seed as the rank at (pp_rank=a+1, ep_rank=b-1). With PP stages and EP ranks there are PP + EP - 1 distinct expert seeds instead of PP x EP.
Expert weights are initialized under this tracker (_initialize_affine_weight_gpu(..., is_expert=True); the TE path forks the same tracker via rng_tracker_name). When stages hold the same number of MoE layers with the same expert shapes, local expert j of MoE layer i on stage s starts bitwise identical to local expert j of MoE layer i on stage s+1 on the neighbouring EP rank. There is no warning: CudaRNGStatesTracker.add rejects a duplicate seed only within one process.
This affects every run that initializes from scratch with PP >= 2 and EP >= 2. For example, the layout in examples/mixtral/train_mixtral_8x7b_distributed.sh (pp 4, ep 8), started without a checkpoint, has 32 expert shards and 11 distinct expert seeds. Runs that load a checkpoint are not affected.
Steps/Code to reproduce bug
Single process; no GPU needed (on a GPU machine nothing is patched). It calls the real _set_random_seed with explicit stand-in groups and the real _initialize_affine_weight_gpu.
PYTHONPATH=/path/to/Megatron-LM python upstream_repro.py"""Minimal repro: Megatron-LM gives two expert-parallel ranks in different pipeline stages
the same expert RNG seed, so their experts start from bitwise-identical weights.
Seed arithmetic (Megatron-LM main @ e998be07):
megatron/training/initialize.py seed = seed_ + 100 * pp_rank
megatron/core/tensor_parallel/random.py expert_parallel_seed = seed + 1024 + 100 * ep_rank + etp_rank
so the expert seed depends on (pp_rank, ep_rank) only through pp_rank + ep_rank.
Runs the real _set_random_seed and _initialize_affine_weight_gpu(is_expert=True) for two
simulated ranks, (pp=0, ep=1) and (pp=1, ep=0). Ranks are passed through the explicit
group arguments of _set_random_seed; no parallel_state mocking. No GPU needed: on a
CPU-only box the CUDA generator calls are aliased to the CPU generator (on a GPU box
nothing is patched). Usage: PYTHONPATH=/path/to/Megatron-LM python upstream_repro.py
"""
import importlib.util
import inspect
import sys
import types
import torch
import torch.distributed as dist
class _Stub(types.ModuleType):
def __getattr__(self, n):
if n.startswith("__"):
raise AttributeError(n)
return lambda *a, **k: None
if importlib.util.find_spec("triton") is None:
# macOS / CPU-only: a few megatron.core modules import triton at top level; none is on
# the seed or init path. Stub only those.
for m in (
"megatron.core.ssm.ops.mamba2.ssd_chunk_state", "megatron.core.ssm.ops.mamba2.ssd_combined",
"megatron.core.ssm.ops.mamba2.ssd_chunk_scan", "megatron.core.ssm.ops.mamba2.ssd_state_passing",
"megatron.core.ssm.ops.mamba2.ssd_bmm", "megatron.core.ssm.ops.mamba2.batch_invariant_decode",
"megatron.core.ssm.ops.common.causal_conv1d_varlen", "megatron.core.fusions.fused_gated_norm",
"megatron.core.fusions.fused_pre_gated_delta_rule", "megatron.core.transformer.moe.ops.paged_stash",
):
sys.modules[m] = _Stub(m)
import megatron.core.tensor_parallel.random as mrandom # noqa: E402
from megatron.core.tensor_parallel.layers import _initialize_affine_weight_gpu # noqa: E402
from megatron.core.utils import init_method_normal # noqa: E402
from megatron.training.initialize import _set_random_seed # noqa: E402
if not torch.cuda.is_available():
torch.cuda.device_count = lambda: 1
torch.cuda.manual_seed = torch.manual_seed
torch.cuda.get_rng_state = lambda *a, **k: torch.get_rng_state()
mrandom._get_cuda_rng_state = lambda *a, **k: torch.get_rng_state()
mrandom._set_cuda_rng_state = lambda s, *a, **k: torch.set_rng_state(s)
_seeds = {}
_orig_add = mrandom.CudaRNGStatesTracker.add
def _add(self, name, seed): # record the seed Megatron computes; body unchanged
_seeds[name] = seed
return _orig_add(self, name, seed)
mrandom.CudaRNGStatesTracker.add = _add
# get_pg_rank() returns group.rank() only when torch.distributed is initialised.
dist.init_process_group("gloo", init_method="tcp://127.0.0.1:29517", rank=0, world_size=1)
class G: # stand-in process group: rank()/size() are all _set_random_seed reads
def __init__(self, rank, size):
self._r, self._s = rank, size
def rank(self):
return self._r
def size(self):
return self._s
def expert_weights(pp_rank, ep_rank, seed=1234, n_local_experts=2):
groups = dict(
pp_group=G(pp_rank, 2), dp_group=G(0, 1), tp_group=G(0, 1), ep_group=G(ep_rank, 2),
etp_group=G(0, 1), gtp_remat_group=G(0, 1), egtp_remat_group=G(0, 1),
)
accepted = inspect.signature(_set_random_seed).parameters # older branches lack gtp_*
_set_random_seed(seed, **{k: v for k, v in groups.items() if k in accepted})
seeds = dict(_seeds)
ws = []
for _ in range(n_local_experts):
w = torch.empty(256, 64, device="cuda" if torch.cuda.is_available() else "cpu")
_initialize_affine_weight_gpu(w, init_method_normal(0.02), partition_dim=0, is_expert=True)
ws.append(w.cpu())
return ws, seeds
a, sa = expert_weights(pp_rank=0, ep_rank=1)
b, sb = expert_weights(pp_rank=1, ep_rank=0)
c, sc = expert_weights(pp_rank=0, ep_rank=0)
print("seeds (pp=0,ep=1):", sa)
print("seeds (pp=1,ep=0):", sb)
print("seeds (pp=0,ep=0):", sc)
print("identical expert init, (pp=0,ep=1) vs (pp=1,ep=0):", all(torch.equal(x, y) for x, y in zip(a, b)))
print("identical expert init, (pp=0,ep=1) vs (pp=0,ep=0):", any(torch.equal(x, y) for x, y in zip(a, c)))
dist.destroy_process_group()Output on main @ e998be07 (2026-09-30), torch 2.14.0, CPU:
seeds (pp=0,ep=1): {'data-parallel-rng': 1234, 'model-parallel-rng': 3952, 'expert-parallel-rng': 2358}
seeds (pp=1,ep=0): {'data-parallel-rng': 1334, 'model-parallel-rng': 4052, 'expert-parallel-rng': 2358}
seeds (pp=0,ep=0): {'data-parallel-rng': 1234, 'model-parallel-rng': 3952, 'expert-parallel-rng': 2258}
identical expert init, (pp=0,ep=1) vs (pp=1,ep=0): True
identical expert init, (pp=0,ep=1) vs (pp=0,ep=0): FalseExpected behavior
Expert shards with different (pp_rank, ep_rank, etp_rank) get different expert seeds; equal expert seeds only across expert-data-parallel replicas, as the model_parallel_cuda_manual_seed docstring describes.
Additional context
- Possible fix: give the pipeline rank its own non-overlapping slot in the seed layout, or derive each stream's seed from a hash of (seed, stream name, rank coordinates). A one-time startup check that all-gathers each rank's tracker seeds and asserts uniqueness outside the intended replica groups would catch this class of problem.
- #4828 changes the EP stride to 1024 but leaves the
100 * pp_rankoffset in_set_random_seed. With that layout the first expert/expert collision needs pp >= 42 (with ep, etp >= 5) or pp >= 257 (with ep >= 26), so it would mostly remove this as a side effect. - Lower priority, same cause: with
--data-parallel-random-init,seed_ + 100 * pp_rank + 10 * dp_rankgives (pp=1, dp=0) and (pp=0, dp=10) the same default and TP seeds. - Not measured: whether identical initial experts across layers change loss or expert specialization. Layers see different inputs, so they may diverge quickly.
- Disclosure: the repro, the seed scan and this report were prepared with an AI coding assistant (Claude). The output above is from running the script on the stated commit.
Source: NVIDIA/Megatron-LM