ColossalAI icon indicating copy to clipboard operation
ColossalAI copied to clipboard

[moe] With all_to_all sequence parallelism, expert gradients are not reduced over the sp group

Open JazyJiang opened this issue 1 month ago • 0 comments

Checklist

  • [x] I have searched the existing issues and did not find a duplicate.
  • [x] I have reproduced this on the latest main (250c903c).

Describe the bug

With MoeHybridParallelPlugin, EP > 1 and sequence_parallelism_mode="all_to_all", the gradients of expert parameters are not summed over the sp group. Each sp rank keeps the gradient computed from its own part of the sequence only, so the copies of the same expert on different sp ranks receive different updates and drift apart.

What happens. all_to_all SP splits every sequence along the sequence dimension at the model input (colossalai/shardformer/modeling/mixtral.py, split_forward_gather_backward(inputs_embeds, 1, sp_group, 1 / sp_size, ...)), and the MoE block runs on that local part. The ranks of one sp group hold the same experts but see different tokens, so, exactly like data parallelism, their expert gradients must be summed over the sp group.

  • Dense parameters are synchronized over mixed_dp_group, which spans the (moe_dp, ep, sp) axes (colossalai/booster/plugin/moe_hybrid_parallel_plugin.py), so they are correct.
  • Expert parameters are put in a ZeRO store on moe_dp_group, which spans only the moe_dp axis. The sp axis is missing. With ep=2, sp=2 on 4 GPUs, moe_dp=1 and every rank's moe_dp_group contains only itself: expert gradients are not synchronized at all.

The averaging works out once the sp axis is added: the output gather_forward_split_backward(..., grad_scale=sp_size) already multiplies each rank's contribution by sp, and ZeRO divides by the group size.

Why tests did not catch it. tests/test_shardformer/test_model/test_shard_mixtral.py and test_shard_deepseek.py include ep=2, sp=2 configs, but they only compare parameters after training with atol=4e-3, which is larger than the gradients of the tiny test models.

Impact. Wrong expert gradients for every MoE model trained with EP + all_to_all SP; the expert copies across sp ranks diverge over training; sharded checkpoints keep only the copy from sp rank 0.

Minimal reproduction

# torchrun --nproc_per_node=4 repro_sp_ep_expert_sync.py
# ep=2, sp=2 (all_to_all), moe_dp=1, ZeRO-1, bf16. Ranks in the same sp group get the same batch (sp splits its
# sequence); the two data replicas get different batches. Reference: one fp32 copy of the model run on both batches.
import os
from copy import deepcopy

import torch
import torch.distributed as dist
from transformers import MixtralConfig, MixtralModel

import colossalai
from colossalai.booster import Booster
from colossalai.booster.plugin import MoeHybridParallelPlugin

colossalai.launch_from_torch(seed=0)
rank = dist.get_rank()
torch.cuda.set_device(rank)
EP, SP = 2, 2

plugin = MoeHybridParallelPlugin(pp_size=1, tp_size=1, ep_size=EP, sp_size=SP, zero_stage=1, precision="bf16",
                                 enable_sequence_parallelism=True, sequence_parallelism_mode="all_to_all")
booster = Booster(plugin=plugin)
torch.manual_seed(0)
config = MixtralConfig(hidden_size=32, intermediate_size=64, num_hidden_layers=2, num_attention_heads=8,
                       num_key_value_heads=8, num_local_experts=4, num_experts_per_tok=2, attn_implementation="sdpa")
model = MixtralModel(config).to(torch.bfloat16).cuda()
single = deepcopy(model).float()
zero_model = deepcopy(model)
zero_model, zero_opt, *_ = booster.boost(zero_model, torch.optim.SGD(zero_model.parameters(), lr=1))


def batch(i):
    return torch.rand(2, 8, 32, generator=torch.Generator("cuda").manual_seed(i), device="cuda")


replicas = dist.get_world_size(plugin.dp_group)  # data replicas; sp peers share one
zero_opt.backward(zero_model(inputs_embeds=batch(dist.get_rank(plugin.dp_group)).bfloat16()).last_hidden_state.mean())
(sum(single(inputs_embeds=batch(i)).last_hidden_state.mean() for i in range(replicas)) / replicas).backward()

ref = dict(single.named_parameters())
for n, p in zero_model.named_parameters():
    n = n.removeprefix("module.")
    g = zero_opt.get_param_grad(p)  # collective, call on every rank
    g = torch.zeros_like(p, dtype=torch.float) if g is None else g.float()
    peers = [torch.empty_like(g) for _ in range(SP)]
    dist.all_gather(peers, g, group=plugin.sp_group)
    if rank == 0 and n.startswith("layers.0.") and (".experts.1.w2" in n or "self_attn.q_proj" in n):
        err = lambda a: ((a - ref[n].grad).norm() / ref[n].grad.norm()).item()
        print(f"{n:45s} rel. error vs reference: sp rank 0 {err(peers[0]):.3f}, sp rank 1 {err(peers[1]):.3f}, "
              f"mean of the two {err(torch.stack(peers).mean(0)):.3f}")
os._exit(0)

Output

layers.0.self_attn.q_proj.weight              rel. error vs reference: sp rank 0 0.010, sp rank 1 0.010, mean of the two 0.010
layers.0.block_sparse_moe.experts.1.w2.weight rel. error vs reference: sp rank 0 1.000, sp rank 1 0.994, mean of the two 0.007

Expected: the expert gradient on both sp ranks matches the reference within bf16 noise, like the dense one (0.010). The two expert copies are each completely off, while their mean matches the reference: what is missing is exactly the reduction over the sp group. The same check with ep=2, sp=1 (moe_dp=2) is correct (≤ 0.013 for all parameters).

Environment

  • ColossalAI: main @ 250c903c
  • PyTorch: 2.11.0+cu128 (CUDA runtime 12.8, NCCL 2.28.9)
  • Transformers: 4.51.3
  • CUDA toolkit: 12.8; driver 595.71.05
  • GPU: 8 × NVIDIA H20, 1 node (4 used)
  • OS / Python: Ubuntu 22.04.5, Python 3.10.12
  • Plugin: MoeHybridParallelPlugin
  • Parallel config: ep=2, sp=2 (all_to_all), moe_dp=1, tp=1, pp=1, ZeRO stage 1, bf16

Additional context

Proposed fix: add a process group along the (moe_dp, sp) axes when all_to_all SP is enabled (it is the existing moe_dp_group otherwise), and use it for the expert gradient store, i.e. for both the gradient reduction and the ZeRO sharding of expert parameters. MoECheckpointIO gathers expert shards over moe_dp_group and has to follow. This also shards expert optimizer states over sp, saving memory, and makes the grad-norm fix in #6465 independent of SP. A regression test should compare expert gradients against a single-GPU reference instead of the loose post-training parameter check.

JazyJiang avatar Oct 15 '26 09:10 JazyJiang