ColossalAI icon indicating copy to clipboard operation
ColossalAI copied to clipboard

[zero] Gradient norm (and clipping) is wrong and differs across ranks with expert parallelism

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 + ZeRO and EP > 1, the gradient norm used for clipping (and returned by get_grad_norm()) is wrong, and each EP rank computes a different value.

The correct norm is sqrt(D² + E₀² + … + E_{ep-1}²), where D² is the squared norm of all dense gradients and E_i² that of the experts held by EP rank i. ZeRO keeps dense and expert parameters in two gradient stores (dense on the full dp group, experts on the moe_dp group). Two things go wrong when the norm is computed:

  1. Per-store norms are added after the square root. LowLevelZeroOptimizer.step() (colossalai/zero/low_level/low_level_optim.py, norm_group += self._compute_grad_norm(...)) adds the norms of the two stores, each already square-rooted, giving D + E instead of sqrt(D² + E²). This over-estimates.
  2. The expert part is not reduced over the EP group. _compute_grad_norm (the override in HybridParallelZeroOptimizer, colossalai/booster/plugin/hybrid_parallel_plugin.py, which MoeHybridParallelZeroOptimizer inherits, and likewise the base implementation) all-reduces the squared sum only over the store's process group, which for experts is the moe_dp group. The experts held by other EP ranks are never added, so EP rank i sees only E_i. This under-estimates, and makes the value differ across EP ranks.

So EP rank i ends up with D + E_i. In a real MoE model the experts carry most of the gradient, and error 2 dominates: the norm is under-estimated by roughly 1 / sqrt(ep), so clipping fails to trigger when it should. Because the clipping coefficient is computed from each rank's own norm and applied to its own ZeRO shard, different shards of the same parameter are also scaled by different factors.

Neither issue shows up without EP: there is only one gradient store, and its group covers all parameters.

While reading the same code: the inf-norm branch of HybridParallelZeroOptimizer._compute_grad_norm calls super()._compute_grad_norm(gradients, norm_type), but the parent signature is (dp_pg, gradients, norm_type), so the arguments are shifted. We have not run this path.

Minimal reproduction

# torchrun --nproc_per_node=4 repro_grad_norm.py
# ep=4 (moe_dp=1), ZeRO-1, bf16. Only the MoE blocks (experts + router) are trained, so that experts carry most of
# the gradient norm as in a real MoE model.
from copy import deepcopy

import torch
import torch.distributed as dist
from torch.nn.parallel import DistributedDataParallel as DDP
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, world = dist.get_rank(), dist.get_world_size()
torch.cuda.set_device(rank)
H = 8

plugin = MoeHybridParallelPlugin(pp_size=1, tp_size=1, ep_size=world, zero_stage=1, precision="bf16", max_norm=1e9)
booster = Booster(plugin=plugin)
torch.manual_seed(0)
config = MixtralConfig(hidden_size=H, intermediate_size=64 * H, num_hidden_layers=1, num_attention_heads=2,
                       num_key_value_heads=2, num_local_experts=8, num_experts_per_tok=2)
model = MixtralModel(config).to(torch.bfloat16).cuda()
for n, p in model.named_parameters():  # in this tiny model the dense grads would otherwise dominate the norm
    p.requires_grad_("block_sparse_moe" in n)
zero_model = deepcopy(model)
zero_model, zero_opt, *_ = booster.boost(zero_model, torch.optim.SGD(zero_model.parameters(), lr=0.0))
ddp_model = DDP(model, process_group=plugin.dp_group, find_unused_parameters=True)

torch.manual_seed(1 + rank)
x = torch.rand(8, 16, H).cuda().to(torch.bfloat16)
zero_opt.backward(zero_model(inputs_embeds=x).last_hidden_state.mean())
ddp_model(inputs_embeds=x).last_hidden_state.mean().backward()
zero_opt.step()  # lr=0: nothing moves, but this computes the norm used for clipping

grads = [p.grad.double() for p in ddp_model.parameters() if p.grad is not None]
correct = sum(g.pow(2).sum() for g in grads).sqrt().item()
expert_sq = sum(p.grad.double().pow(2).sum() for n, p in ddp_model.module.named_parameters()
                if p.grad is not None and ".experts." in n).item()
norms = [None] * world
dist.all_gather_object(norms, zero_opt.get_grad_norm())
if rank == 0:
    print(f"correct norm (DDP): {correct:.6f}  (experts carry {expert_sq / correct**2:.0%} of the squared norm)")
    for r, n in enumerate(norms):
        print(f"  rank {r}: ZeRO norm {n:.6f}  ZeRO / correct = {n / correct:.3f}")

Output

correct norm (DDP): 0.004769  (experts carry 100% of the squared norm)
  rank 0: ZeRO norm 0.001843  ZeRO / correct = 0.386
  rank 1: ZeRO norm 0.002060  ZeRO / correct = 0.432
  rank 2: ZeRO norm 0.003924  ZeRO / correct = 0.823
  rank 3: ZeRO norm 0.000590  ZeRO / correct = 0.124

Expected: every rank reports the same value, equal to the correct norm. A separate 8-GPU run (ep=4, moe_dp=2, all parameters trained) confirmed the formula: each rank's ZeRO norm equals dense_norm + norm(local experts) to four decimal places, and only ranks with the same EP rank agree.

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=4, moe_dp=1, tp=1, pp=1, sp=1, ZeRO stage 1, bf16

Additional context

Proposed fix, following Megatron-Core (megatron/core/optimizer/clip_grads.py::get_grad_norm_fp32 and ChainedOptimizer.get_grad_norm): every rank sums the squares of the gradient elements it owns across both stores, the sum is all-reduced once over all ranks, and the square root is taken once. Duplicates are excluded by ownership (e.g. parameters not split by TP are counted on TP rank 0 only) instead of the current divide-by-tp_size / divide-by-shared-stages corrections. This also removes the separate inf code path that has the argument bug above.

With all_to_all sequence parallelism, expert gradients are currently replicated (and not synchronized) across the sp axis (#6466); once that is fixed, expert gradients are sharded over (moe_dp, sp) and no SP-specific rule is needed here.

JazyJiang avatar Oct 15 '26 09:10 JazyJiang