Skip to content

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

Open
gss10282023 wants to merge 3 commits into
deepspeedai:masterfrom
gss10282023:fix-autoep-ownership-aware-clipping
Open

gss10282023 wants to merge 3 commits into
deepspeedai:masterfrom
gss10282023:fix-autoep-ownership-aware-clipping

Conversation

@gss10282023

@gss10282023 gss10282023 commented Sep 10, 2026 •

Copy link
Copy Markdown

Summary

AutoEP FP32 gradient clipping should count each logical parameter once, even when experts are sharded across ranks. Sum ownership-weighted squared gradients before taking the square root, instead of averaging rank-local norms.

For the mpu=None path, reduce over both data-parallel and sequence-parallel ranks. A mesh DP group can contain only replicas of one expert shard; it does not necessarily cover all experts. Using that smaller group can reject a valid EP size or over-clip gradients. Including all ranks in this path also ensures that the norm contains the other expert shards.

Fixes #8475. The change is limited to AutoEP FP32 L2 clipping with mpu=None; the integration tests use ZeRO-0.

Changes

  • Record the EP size on expert parameters and use the reduction group's size to account for replicas.
  • Detect AutoEP ownership before filtering missing gradients, keeping every rank on the same collective path when an expert is unused.
  • Extend the native clipping/update regression to ordinary and mesh-SP layouts on two and four ranks. Both layouts use the same independent full-gradient reference.

Validation

Tested on an Intel Xeon Cascadelake CPU with Python 3.11.15 and PyTorch 2.13.0+cpu.

  • 32 native engine clipping/update cases passed on CPU/Gloo: 8 ordinary and 8 mesh-SP cases at each of two and four ranks. They cover EP sizes 1 and 2, mixed dense/expert gradients, and an unused expert.
  • Before the mesh-SP correction, the two-rank case raised an invalid-ownership-metadata error. The four-rank case clipped nonzero expert gradients to about 70.7% of the reference value. The ordinary-layout controls passed.
  • The parameter-metadata test and existing p-norm clipping tests pass: 4 passed, 2 skipped. The two distributed test methods are skipped by the standard CPU harness because it sees one accelerator; their bodies were run directly at both world sizes above.
  • All pre-commit checks applicable to the changed files passed. CUDA/NCCL tests have not been run locally for this update.
CPU/Gloo regression commands

From the repository root in an environment with DeepSpeed's test dependencies:

cat > /tmp/autoep_clip_check.py <<'PYTEST'
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:
    test = TestAutoEPFP32Clipping()
    test.test_clipping_counts_each_unique_parameter_once()
    test.test_clipping_includes_expert_shards_across_mesh_sp_ranks()
finally:
    dist.destroy_process_group()
PYTEST

DS_ACCELERATOR=cpu PYTHONPATH=".:tests" OMP_NUM_THREADS=1 \
python -m torch.distributed.run --standalone --nproc-per-node=2 /tmp/autoep_clip_check.py
DS_ACCELERATOR=cpu PYTHONPATH=".:tests" OMP_NUM_THREADS=1 \
python -m torch.distributed.run --standalone --nproc-per-node=4 /tmp/autoep_clip_check.py

AI assistance was used for the implementation, tests and this description.

@gss10282023
gss10282023 marked this pull request as ready for review September 10, 2026 16:54

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: e05fa3fa14

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread deepspeed/runtime/utils.py Outdated
Comment on lines +406 to +408
if not isinstance(ep_size, int) or ep_size <= 0 or dp_world_size % ep_size != 0:
raise RuntimeError("AutoEP expert parameter has invalid EP ownership metadata")
weight = ep_size / dp_world_size

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Base expert weighting on the actual reduction group

With mesh-based sequence parallelism, mpu remains None but pg is only the mesh data-parallel group; AutoEP arranges this group as the expert-data-parallel replicas, so every rank in pg owns the same expert shard. Multiplying each shard by ep_size / dp_world_size therefore overstates its squared-norm contribution by ep_size (or raises here when ep_size does not divide the mesh DP size), causing overly aggressive clipping for supported FP32 ZeRO-0 AutoEP+SP runs. The weight must be derived from the shard's replica count within pg, rather than assuming that pg also contains the EP dimension.

Useful? React with 👍 / 👎.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-09-10T16:59:14.542081Z e05fa3f Draft marked ready
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

Assisted-by: OpenAI Codex
Signed-off-by: shanshan <[email protected]>
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 <[email protected]>
Co-authored-by: pengdurice <[email protected]>
banxingmjj pushed a commit to openanolis/DeepSpeed that referenced this pull request Nov 7, 2026
…speedai#8823)

AutoEP + AutoTP folding gives TP peers different routed experts.
ZeRO-1/2 currently filters non-TP expert parameters to TP rank zero when
computing the clipping norm, then applies the ordinary expert-norm
averaging path. This can omit expert owners and produce an incorrect
clipping coefficient even when reconstructed logical gradients are
correct.

Compute folded expert norms over the actual expert-DP partition group
and EP owner group, without another TP sum or expert-norm average. Only
groups tagged with the AutoEP expert placement family use this path.
Dense groups and native MoE groups retain their existing reductions and
native expert-norm averaging, including when native ETP and AutoEP
groups coexist. ZeRO-3 is unchanged and is checked as a sibling
reference. The existing folding contract rejects optimizer/parameter
offload.

Refs deepspeedai#8672 and deepspeedai#8670. The live duplicate check found no open PR fixing
this ZeRO-1/2 folding path. deepspeedai#8476, deepspeedai#8478 and deepspeedai#8691 address FP32/ZeRO-0
clipping in `runtime/utils.py`; they do not change the partitioned
optimizer reductions fixed here. deepspeedai#8739 implements DeepEP weight-gradient
overlap and does not change these norm reductions.

### Final change

This PR contains three files:

- `deepspeed/runtime/zero/stage_1_and_2.py`: correct the folded expert
clipping reductions.
- `tests/unit/v1/moe/test_autoep_autotp_sharded_attention.py`:
reconstruct full logical gradients and FP32 master parameters, then
compare an actual SGD update against an unsharded ZeRO-0 reference
across all 45 parameter families. Thresholds of 0.5 and 2.0 times the
reference norm cover active clipping and an inactive control. Snapshots
are cloned before in-place updates; distributed diagnostics finish
before assertions.
- `docs/code-docs/source/autoep.rst`: document expert ownership and the
reduction contract.

The sharded-attention regression supports 4- and 8-rank TP2/EP4
configurations, ZeRO-1/2/3 and ZeRO-3 `zero.Init`. An additional
two-rank analytic SGD regression covers native ETP alone and mixed
native ETP/folded AutoEP groups at ZeRO-1/2.

### Incremental review

[Incremental review report and
validation](deepspeedai#8823 (comment))
· [diff from the reviewed
head](deepspeedai/DeepSpeed@352ee55...fb5d0e5).

The correction preserves native ETP reductions alongside folded AutoEP.
**On the correction commit, 8 positive cases passed on 2 H100 GPUs, and
2 published-head negative controls failed as expected.** ZeRO-1/2
optimizer cases validate native norm 5, mixed norm 13 and the actual
clipped-SGD updates; TP2/EP2 tiny GLM4-MoE active/inactive clipping
cases validate all 45 parameter families against an unsharded reference.
The old mixed cases produce partial norms 12.369317 / 12.649111 instead
of 13. These runs used FP32, TF32 disabled, Torch 2.12.1+cu130 / CUDA
13.0, Transformers 5.15.1 and driver 595.91.07. Changed-file pre-commit
checks and independent archive/report readback passed; owned workers and
locks closed. The report records the exact execution method and CPU
diagnostic separately. The 8/16-GPU results below belong to the original
submitted head.

### Original submitted-head validation

The original submitted three-file diff at
`352ee55cd14f77f30e5170939c7e60c4d4bd7754` was tested on source based on
`1c862f7df93f0345b977c67f5408d967b94bf4ae`. The extended finite workload
used **16 NVIDIA H100 GPUs across four nodes**, random tiny GLM4-MoE,
FP32 with TF32 disabled, Torch 2.12.1+cu130, CUDA 13.0 and Transformers
5.15.1. The original receipt did not capture the NVML driver package
version.

| Coverage | Final result |
|---|---|
| Clipping and initialization | TP2/EP4 and TP2/EP8, ZeRO-1/2/3,
active/inactive clipping and ZeRO-3 `zero.Init` passed. An unfixed
ZeRO-2 control failed the norm/update oracle. |
| Routing and topology | Rotating hotspots, idle expert owners, GAS4,
and TP4/EP16 with 16 experts and ZeRO-3 `zero.Init` passed. |
| Communication | Overlap off/on and small-bucket configurations with
actual repeated/oversize flushes passed. |
| Save and resume | Continuous four-update training matched save after
two updates, process exit and new-process resume through four updates,
including parameters, momentum 0.9, losses and WarmupLR state. |
| Sustained training | 200 actual updates across four 50-update routing
stages passed the reference loss, gradient and update checks. Late live
allocated-memory spread stayed below 64 MiB for this tiny model. |
| Independent readback | All 28 cases, 448 rank packets and 247,635 raw
arrays from the 16-GPU workloads passed separate NumPy arithmetic and
complete archive checksum verification. |
| Source checks | All applicable changed-files pre-commit hooks passed,
including yapf, flake8, codespell, license and accelerator/distributed
import checks. `git diff --check` and a clean three-way merge check
against current upstream master passed. |

The extended distributed drivers used the same contributed reference
helpers. An additional 8-H100 clipping matrix passed 16 cases and 28,800
raw arrays. All owned GPU workers and contexts closed, the original GPU
locks were released, and complete outputs were archived.

Idle-owner checks exclude alignment padding using the frozen permutation
formula `ceil((n_tokens + E_local*8)/8)*8`; equality to `E_local*8`
proves zero actual received rows. The original finalizer's incorrect
padding assertion and failed scheduler status are preserved in the
private evidence. The separate corrected reader passed against the same
completed workload and unchanged numerical tolerances.

These results establish tiny-model correctness, optimizer-state
continuity and bounded-run stability. They do not establish
pretrained-model convergence, a speedup, BF16/FP16 or Muon behavior,
offload, PP/SP, DeepEP overlap, or completion of every Q4 roadmap item.

Reproduce the contributed regression and source checks:

```sh
pytest --forked -q tests/unit/v1/moe/test_autoep_autotp_sharded_attention.py \
  -k TestShardedAttentionClippedUpdate
pre-commit run --files deepspeed/runtime/zero/stage_1_and_2.py \
  tests/unit/v1/moe/test_autoep_autotp_sharded_attention.py \
  docs/code-docs/source/autoep.rst
```

AI assistance was used for implementation, test preparation and
incremental review. The human submitter reviewed the original
submission, confirmed its test results, and authorized this follow-up
correction and DCO sign-off.

---------

Signed-off-by: 0z5a <[email protected]>
Co-authored-by: pengdurice <[email protected]>
@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

This branch has not been deployed

No deployments
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