Skip to content

Fix AutoEP global L2 clipping for sharded expert ownership - #8470

Closed
gss10282023 wants to merge 1 commit into
deepspeedai:masterfrom
gss10282023:fix-autoep-ownership-aware-clipping
Closed

gss10282023 wants to merge 1 commit into
deepspeedai:masterfrom
gss10282023:fix-autoep-ownership-aware-clipping

Conversation

@gss10282023

Copy link
Copy Markdown

Summary

Record AutoEP's expert-parallel size on expert parameters and use each parameter's replica count when summing squared gradients. Reduce those sums across the data-parallel group before taking the square root, so clipping counts each logical parameter once.

The ownership check runs before filtering absent gradients, keeping ranks on the same collective path when an expert is unused.

Fixes #8469. The change is limited to the AutoEP FP32 L2 path with mpu=None; the integration checks use ZeRO-0.

Validation

  • Eight clipping/update cases passed through DeepSpeedEngine on two CPU/Gloo processes, using an Intel Xeon Cascadelake host and PyTorch 2.13.0+cpu. They cover replicated and sharded experts, mixed dense/expert gradients, and an unused expert on one rank.
  • The same test body fails with unmodified 0166cc87: an owner-sharded gradient is clipped to roughly twice the reference value.
  • The AutoEP parameter-metadata test passes. All pre-commit checks applicable to the four changed files pass.

The standard distributed pytest harness skips the two-process test on this single-socket CPU host. The test body was run directly with two Gloo processes using the command below. CUDA validation of this branch is still pending; the pinned-version CUDA results are in the issue.

CPU validation command

From the repository root in an environment with DeepSpeed and its test dependencies:

cat > /tmp/autoep_clip_check.py <<'PY'
import deepspeed
import deepspeed.comm as dist
from unit.v1.moe.test_autoep_grad_parity import TestAutoEPFP32Clipping

deepspeed.init_distributed(dist_backend="gloo", auto_mpi_discovery=False)
try:
    TestAutoEPFP32Clipping().test_clipping_counts_each_unique_parameter_once()
finally:
    dist.destroy_process_group()
PY
DS_ACCELERATOR=cpu PYTHONPATH="$PWD:$PWD/tests" \
python -m torch.distributed.run --standalone --nproc-per-node=2 /tmp/autoep_clip_check.py

Signed-off-by: shanshan <sgao5239@uni.sydney.edu.au>
@gss10282023
gss10282023 force-pushed the fix-autoep-ownership-aware-clipping branch from 9cd0f10 to 8288645 Compare September 10, 2026 05:58
banxingmjj pushed a commit to openanolis/DeepSpeed that referenced this pull request Nov 5, 2026
…i#8478)

Fixes deepspeedai#8475.

(Originally opened against deepspeedai#8469, which @gss10282023 withdrew and
resubmitted as deepspeedai#8475 while this was being written. The discussion about
how this and deepspeedai#8476 relate is on deepspeedai#8469 and continues on deepspeedai#8475.)

## The measurement

`clip_grad_norm_` ends by averaging the per-rank norms over the data
parallel group:

```python
pg = groups._get_data_parallel_group()
scaled_norm = total_norm * 1.0 / float(dist.get_world_size(group=pg))
dist.all_reduce(scaled_norm_tensor, group=pg)
```

That reconstructs a global norm only while every rank holds the same
parameters. Expert parameters are not replicated, so each rank's norm
describes a different set of experts. Four expert gradients across two
ranks, measured on 2×H20:

| layout | global norm |
| --- | ---: |
| reference — each expert counted once | **10.954452** (`sqrt(120)`) |
| replicated on both ranks | 10.954452 |
| one half per rank | **7.236068** |

`sqrt(20)` and `sqrt(100)` averaged to 7.236 instead of `sqrt(20 +
100)`. The same gradients, 34% apart, decided only by where the experts
happen to live. `clip_coef` is `max_norm / total_norm`, so wherever
clipping is active this changes the update.

@gss10282023 reported this (deepspeedai#8475) and measured a 0.2 shift in the
clipping coefficient on their setup; the numbers above are an
independent reproduction from a different direction.

## Why the fix is the repo's own

`get_norm_with_moe_layers` already does it correctly — it takes the
non-expert norm plus the expert gradients keyed by group, reduces each
expert group over its own `moe_ep_group`, and combines as `(Σ norm_i **
p) ** (1/p)`. **Both the bf16 and the fp16 optimizer already call it.**

The fp32 path instead inlines the approximation. That approximation also
exists under its own name, `get_norm_with_moe_layers_fast`, carrying
this comment:

> This implementation standardizes the grad_norm across ranks. A more
precise implementation can be found in 'get_norm_with_moe_layers'.

and that named copy has **no callers at all** — so the warning never
reaches the one place still doing it. This PR keeps expert gradients out
of the replicated norm and folds them in through the precise helper,
leaving fp32 the same shape as the other two optimizers.

## Scope

**Unchanged when no expert parameter is present** — that branch is the
original code, not touched. Every non-MoE fp32 run behaves exactly as
before, which the existing suite confirms (below).

Two guards worth naming:

- An expert parameter carrying no `group_name` has no expert parallel
group to reduce over. `TestClipGradNorm::test_gather` builds one by hand
exactly like that, so such a call stays on the original path rather than
guessing a group.
- `get_norm_with_moe_layers` reports a non-finite norm as `-1`. Used
as-is that would make `clip_coef` negative and flip the sign of every
gradient, so it is mapped to `inf` — which keeps what the averaging path
already did, scale to zero.

## Testing

`tests/unit/runtime/test_runtime_utils.py`, 2 GPUs (H20): 16 passed.

The cases that call `clip_grad_norm_` directly assert the **norm
value**, not that a code path was reached, and cover experts spread over
ranks, a rank whose experts got no tokens, a rank owning no expert, a
rank with no gradient at all, the expert-only inf norm, and the order
the expert groups are visited in.

`TestClipFp32GradientsThroughEngine` goes through
`deepspeed.initialize`, `backward` and `step` in an fp32 run without
ZeRO, with one expert on each of two ranks and a dense layer in front.
The engine drops the norm `clip_grad_norm_` returns, so the test reads
it from its effect: with plain SGD the update is `lr * clip_coef *
grad`, so it computes the global norm independently from the gradients
(each dense gradient once, each rank's expert once) and checks every
parameter after `step()` against `start - lr * clip_coef * grad`. It
also checks that the clip is active and that the average of the ranks'
own norms, the old answer, differs from the true one by more than 5%, so
it cannot pass by accident. On this setup the true norm is 0.624 and the
average is 0.542.

```
this branch                         16 passed
branch's test file on the code      TestClipFp32GradientsThroughEngine fails:
before this PR                          AssertionError: Tensor-likes are not close!
                                        Greatest absolute difference: 3.2e-05 (up to 1e-06 allowed)
```

It uses the plain `MoE` layer, not AutoEP: the code under test reads
`is_moe_param` and `group_name` and reduces over the expert parallel
group, which both paths share.

Earlier, on the first revision, `test_runtime_utils.py` +
`tests/unit/v1/moe/test_moe.py` compared by failure set on the same box:

```
master   7 failed, 29 passed, 14 skipped
branch   6 failed, 30 passed, 14 skipped

only failing on branch (regressions) -> none
only failing on master               -> test_sharded_experts_count_once   (the new one)
failing on both                      -> 6
```

The 6 were pre-existing there, `ImportError: libcudart.so.13`, unrelated
to this change. I have not rerun `test_moe.py` since the later commits.

## Note

deepspeedai#8470 proposed a fix for the same issue and was closed by its author
without discussion. This takes a different route: rather than repairing
the averaging, it routes the fp32 path through the combiner the other
two optimizers already use, so there is one implementation of the
correct thing instead of two.


## Environment

NVIDIA H20-3e, driver 580.105.08, Python 3.11.15, torch 2.9.1+cu128; the
runs above used 2 GPUs.

---------

Signed-off-by: alanhuangyoo <alanhuangyoo@gmail.com>
Co-authored-by: pengdurice <pengduhit@gmail.com>
@auto-pr-labeler-with-jev auto-pr-labeler-with-jev Bot added the skip-gpu-test Requires positive evidence that every changed behavior can be validated without a GPU. label Nov 14, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

skip-gpu-test Requires positive evidence that every changed behavior can be validated without a GPU.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug] AutoEP FP32 gradient clipping averages norms across ranks with different expert ownership

1 participant