Repository navigation
AutoEP + AutoTP folding under ZeRO-3 - #8670
sfc-gh-truwase merged 6 commits into
Conversation
…input gradient over TP Remove the ZeRO-3 rejections for AutoEP + AutoTP folding, apply the per-family folding gradient correction in ZeRO-3, count the ZeRO-3 gradient norm once per distinct partition, and let AutoTP shard models built under deepspeed.zero.Init. Fix wrong gradients below every folded MoE layer when a layer below it is tensor-parallel (all ZeRO stages): the MoE input gradient is now averaged over the TP group. Signed-off-by: pengdurice <pengduhit@gmail.com>
66143d4 to
6b0a4d6
Compare
test_zero3_compatibility_gate_rejects_active_autotp expected the ZeRO-3 AutoTP rejection this PR removes; it now checks that the check accepts AutoTP. test_zero3_cpu_offload_grad_norm_reduces_autoep_expert_parallel_group builds the optimizer without __init__, so it now sets model_parallel_group the way __init__ does without an mpu. Signed-off-by: pengdurice <pengduhit@gmail.com>
…ro.Init save_checkpoint crashed at ZeRO-3 with AutoEP + AutoTP folding: the folding metadata assumed ZeRO-1/2 partition groups. ZeRO-3 records and checks its own partitions, so the ZeRO-1/2 record is skipped there. Universal conversion of such a checkpoint now says it is not supported yet. Under zero.Init, AutoTP's gather replaced a tied output head's weight but not the embedding's, which broke the tie and let a row-parallel spec shard the head; every holder of the weight now gets the replacement. Signed-off-by: pengdurice <pengduhit@gmail.com>
tohtana
left a comment
There was a problem hiding this comment.
Hi @pengdurice,
Thank you for the great PR! I'm so glad that you made the combination work.
I also appreciate the gradient bug fix.
That said, I found one issue with initialization:
Models created under deepspeed.zero.Init store their weights in ZeRO partitions and leave empty tensors in their place. AutoTP must gather the full weights before splitting them for tensor parallelism.
This PR adds that step for linear layers split according to partition_config. However, it is still missing when
- AutoTP splits embeddings
- Splits an output head that shares its weight with an embedding using
vocab_parallel_lm_head - Or automatically chooses how to split layers without a usable partition plan
These cases therefore try to split weights that have not been gathered and fail during initialization, before training starts.
Can you confirm and address the issue?
Signed-off-by: pengdurice <pengduhit@gmail.com>
Hi @tohtana , thank you for your comments, fixed them! This similar to other PRs also motivates a better handling of model initialization under |
tohtana
left a comment
There was a problem hiding this comment.
Thank you for the update! My concern has now been addressed.
## Problem Since deepspeedai#8680 landed, `modal-torch-latest / DeepSpeedAI CI` has failed for every merge-queue entry that runs this test on Modal's L40S runners (deepspeedai#8794, deepspeedai#8701, deepspeedai#8670). Example: [run 38009529440](https://github.com/deepspeedai/DeepSpeed/actions/runs/38009529440/job/114086150257). ``` FAILED tests/unit/v1/autotp/test_autotp_training.py::TestTiedRowParallelOutputHeadTraining::test_training_matches_unsharded_reference[35-3-False-0] FAILED tests/unit/v1/autotp/test_autotp_training.py::TestTiedRowParallelOutputHeadTraining::test_training_matches_unsharded_reference[35-3-True-0] Mismatched elements: 1 / 670 (0.1%) Greatest absolute difference: 1.1173542588949203e-06 at index (1, 1, 45) (up to 1e-06 allowed) ``` deepspeedai#8680's own merge-queue run and the next nightly run both used the AWS fallback, where the test passes, so the failure wasn't caught there. ## Root cause The row-parallel head (`LinearAllreduceWithReplicatedInput`) slices the hidden vector, computes a partial matmul on each rank, and all-reduces the partial logits. The reference is one unsharded fp32 matmul, and the two summation orders round differently. The tied head uses the embedding's N(0,1) weights, so logits reach about 14, where one fp32 ulp is about 1e-6. Logits that are near zero through cancellation can therefore differ by more than `atol=1e-6`. Even the fp32 reference differs from a float64 ground truth by up to 2.2e-6. ## Fix Use torch.testing's default fp32 tolerance (`atol=1e-5`, `rtol=1.3e-6`) for every fp32 `assert_close` in `test_autotp_training.py`. That covers 17 checks, including both row-parallel logits checks, and matches the 19 fp32 checks in the file that already use the default. The half-precision tolerances in `run_tp_layer_fwd_bwd` are unchanged. The default is enough for what these tests check: - The sharding bugs they target (wrong shard offset, missing all-reduce, dropped tied-gradient contribution, tied weights drifting apart) move values by 0.1 to 10. - A simulated precision regression (all-reduce inputs rounded to bf16) still fails every check it failed under the old tolerances. The one exception is the SGD-update check, which can't detect it under either tolerance. - The custom values were tighter than the default only for values below about 1, and looser for larger ones such as the losses. ## Evidence (2x H200) - In a sweep of 40 init seeds, every parametrization of the tied test has seeds that fail the old logits check (worst ratio to the allowed tolerance: 1.19). Under the default, the worst case uses under 30% of the limit. - Changing only the seed to 8199 reproduces the CI failure: `[35-3-False-0]` and `[35-3-True-0]` fail with `1 / 670` mismatched and `1.25e-06 (up to 1e-06 allowed)`. - Every other changed check stays under 3% of the default limit, recorded per call across the 4 affected test classes. ## Testing Hardware: 2x NVIDIA H200, torch 2.12.0+cu130, Python 3.12. - `pytest tests/unit/v1/autotp/test_autotp_training.py -k "TestRowParallelOutputHeadTraining or TestTiedRowParallelOutputHeadTraining"`: 8 passed. - `pytest tests/unit/v1/autotp/test_autotp_training.py -m sequential -k "TestTiedEmbeddingAliasesAndFallback or TestTiedVocabParallelLMHead"`: 30 passed. - Seed-8199 reproduction, which fails before this change: passes with the default logits tolerance. - `pre-commit run --files tests/unit/v1/autotp/test_autotp_training.py`: passed. No L40S is available locally. This PR's merge-queue run selects this test file, so it will check the fix on Modal's L40S runners unless the run falls back to AWS. --------- Signed-off-by: Hongwei Chen <hongweichen@microsoft.com> Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
deepspeedai#8855) ## Summary Fixes a stale test expectation. `TestTiedOutputHead::test_row_parallel_tied_head_is_refused[False/True]` in `tests/unit/v1/moe/test_autoep_autotp_sharded_attention.py` fails on master: ``` AssertionError: AutoTP sharded an output head whose weight is tied to the input embedding ``` The test (added in deepspeedai#8670) expects AutoTP to refuse a row-parallel output head whose weight is tied to the input embedding. Since 3c6a5ca ("[AutoTP] Support tied embeddings for row-parallel…"), AutoTP supports this case: it replaces the embedding with a `HiddenParallelEmbedding` that shares the head's sharded weight. The two changes landed a day apart, so the expectation was already stale when deepspeedai#8670 merged. Change (test only, no runtime code modified): - Rename the test to `test_row_parallel_tied_head_keeps_the_tie`. - With and without `zero.Init`, check after `deepspeed.initialize` that the embedding is a `HiddenParallelEmbedding` and `lm_head.weight is embed_tokens.weight`. - Run it in the CPU multi-rank nightly (`cpu-torch-multi-latest`). Before, it skipped on CPU and needed 4 GPUs, so no nightly ran it: the GPU nightly (`ci/torch_latest.py`) has exactly 2 GPUs. The check only builds the engine, so it needs no accelerator: drop the CPU skip and mark it `sequential`, because that nightly selects tests under `unit/v1` only through its sequential phase. It keeps 4 ranks, which that nightly admits (`LOCAL_SIZE=4`). The original concern of the test still holds: under `zero.Init` AutoTP gathers the partitioned head weight into a new parameter, and if the embedding kept the old one the two would train as separate copies. The identity check catches that. Numerical training parity of a tied row-parallel head is already covered by `TestTiedRowParallelOutputHeadTraining` in `tests/unit/v1/autotp/test_autotp_training.py`. ## Related work No open PR fixes this test. deepspeedai#8829 and deepspeedai#8848 both list these two failures as pre-existing and leave them unchanged. I searched open PRs touching `TestTiedOutputHead` and tied/vocab-parallel output heads. ## Tests ``` cd tests # CPU, as in cpu-torch-multi-latest DS_ACCELERATOR=cpu LOCAL_SIZE=4 DS_DISABLE_REUSE_DIST_ENV=1 pytest -p no:randomly --forked -m sequential "unit/v1/moe/test_autoep_autotp_sharded_attention.py::TestTiedOutputHead" # XPU CUDA_VISIBLE_DEVICES=4,5,6,7 pytest -p no:randomly -m sequential "unit/v1/moe/test_autoep_autotp_sharded_attention.py::TestTiedOutputHead" ``` | Test | master `cc7b5125d` | This PR | |---|---|---| | `TestTiedOutputHead[zero_init=False]` | failed on XPU (`AssertionError` above) | passed on CPU (4 gloo ranks) and XPU (4 ranks) | | `TestTiedOutputHead[zero_init=True]` | failed on XPU (`AssertionError` above) | passed on CPU (4 gloo ranks) and XPU (4 ranks) | `pre-commit run --files` on the changed file passes. Hardware and software: - CPU: Intel Xeon Platinum 8457C, 4 ranks over gloo - XPU: 4× Intel Arc Pro B70 - Level Zero driver 1.15.39122 (compute runtime 26.27.39122.11) - torch 2.14.0.dev20260804+xpu, transformers 5.17.0 ## Compatibility matrix Test-only change; no numerics, performance or memory impact. | | Validated | Not validated | |---|---|---| | ZeRO | Stage 3, with and without `zero.Init` (as in the test) | Other stages (not exercised by this test) | | Precision | fp32 | | | Offload | | Not exercised | | Parallelism | AutoTP 2 × AutoEP 2 folding, world size 4 | | | Accelerator | CPU, XPU | CUDA (not run locally; the GPU nightly does not select `sequential` tests) | ## AI assistance This PR was developed with AI assistance (GitHub Copilot CLI). I reviewed every changed line and ran the tests above. cc @pengdurice @0z5a @delock --------- Signed-off-by: Jin, Youzhi <youzhi.jin@intel.com> Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Co-authored-by: Ma, Guokai <guokai.ma@gmail.com>
…epspeedai#8829) ### Summary deepspeedai#8670 left optimizer and parameter offload rejected for AutoEP + AutoTP folding ("not validated yet ... run a follow-up proof for per-family replica groups"). This PR provides that proof for ZeRO-3 with the optimizer offloaded to the CPU, and accepts that configuration: ```json { "zero_optimization": {"stage": 3, "offload_optimizer": {"device": "cpu"}}, "tensor_parallel": {"autotp_size": 2}, "expert_parallel": {"enabled": true, "autoep_size": 2} } ``` Everything else stays rejected, now with a message that names the unsupported part: optimizer offload with ZeRO stages 1 and 2, NVMe optimizer offload, parameter offload, and Muon with optimizer offload. An explicit `"device": "none"` is treated as no offload (it was rejected before). ### Why ZeRO-3 + CPU optimizer offload is already correct - ZeRO-3 applies the folded per-family gradient correction (`_apply_autoep_folding_tp_correction`: AVERAGE for TP-replicated parameters, `/tp_size` for routed experts, SKIP for TP-sharded ones) in `reduce_independent_p_g_buckets_and_remove_grads`, before every reduce-scatter. That path is the same with and without offload; offload only changes where the reduced partitions are stored. - The offloaded norm (`complete_grad_norm_calculation_for_cpu_offload`) uses the same folding-aware counting as the device norm (`_grad_norm_counts_every_rank` plus the expert-parallel all-reduce), from per-partition norms recorded at the accumulation boundary. The test below checks the claim end to end instead of relying on this reading. ### Changes - `validate_folding_global` / `validate_autoep_config`: take the offload **devices** instead of "offload configured" booleans (`offload_optimizer_device`, `offload_param_device`); accept stage 3 + `"cpu"`; reject the rest as above. Internal helpers; the two in-repo callers are updated. - `DeepSpeedEngine`: passes the configured devices. - ZeRO-3: rejects Muon with optimizer offload under folding. The offloaded Muon update gathers full gradients on its own path, which this PR does not validate (and which overlaps ongoing Muon offload work). - Docs: the AutoEP folding constraint in `autoep.rst`. ### Tests - `test_autoep_autotp_folding_config.py`: accepted and rejected offload combinations (replaces the blanket-rejection test; the duplicate in `test_autoep_autotp_grad_parity.py` is removed). - `test_autoep_autotp_sharded_attention.py`, new `TestFoldedZero3ClippedUpdate`: reuses deepspeedai#8670's per-gradient comparison against an unfolded ZeRO-0 reference and adds one clipped SGD step. For each of 4 folding shapes (world 4; TP x EP = 2x2, 2x4, 4x2, 4x4), `zero.Init` on/off, and offload on/off, it compares losses, every gradient, the global norm, and every parameter's update. Clipping (clip 1e-2, lr 1/clip) makes the update depend on the norm the optimizer computed, so a wrong offloaded norm fails the test; the comparison allows one fp32 ulp of the parameter for recovering an update as `after - before`, and asserts that a 0.1% error in the update is still detected. #### Results (on-device) Hardware: 1 node, 4x NVIDIA H100 (64 GB, NVLink NV6 between all pairs), driver 595.91.07 (CUDA 13.2), torch 2.12.1+cu130, NCCL 2.29.7, transformers 5.15.1, Python 3.12.1 (MareNostrum 5 ACC). | Command (from `tests/`) | This PR | Unpatched base `1c862f7df` | | --- | --- | --- | | `pytest unit/v1/moe/test_autoep_autotp_sharded_attention.py -k TestFoldedZero3ClippedUpdate` | 16 passed | offload off: 8 passed; offload on: 8 fail with the old "not validated yet" ValueError (the restriction this PR lifts) | | `pytest unit/v1/moe/test_autoep_autotp_sharded_attention.py -k "not TestFoldedZero3ClippedUpdate"` | 18 passed, 15 skipped, 2 failed | 18 passed, 15 skipped, 2 failed | | `pytest unit/v1/moe/test_autoep_autotp_{bf16_folding_parity,checkpoint,deepcompile_reject,dispatch,folding_config,folding_groups,grad_parity,runtime,zero1_overlap_folding}.py` | 81 passed, 9 skipped | 75 passed, 9 skipped | | `pytest unit/v1/moe/test_autoep_autotp_folding_config.py` (CPU) | 33 passed | — | The 2 failures are `TestTiedOutputHead::test_row_parallel_tied_head_is_refused[False/True]` ("AutoTP sharded an output head whose weight is tied to the input embedding"). They fail identically on the unpatched base in the same job, so they are pre-existing and unrelated to this change (likely AutoTP tied-head detection with transformers 5.15.1); not addressed here. The global norms match the reference exactly, for example folded 2.380656 vs reference 2.380656 (TP 2) and 3.552228 vs 3.552228 (TP 4). 8-rank shapes skip on the 4-GPU node. The GPU runs used base `1c862f7df`; the branch is rebased onto `5f266e26d` without conflicts (the 4 commits in between touch DeepEP slicing, XPU op builders, ZeRO-2 partition storage and a test footprint, none of the paths changed here). `pre-commit run --files` on the changed files passes (yapf, flake8, codespell, check-torchdist, check-license, check-torchcuda). ### Compatibility matrix Validated: ZeRO-3 x optimizer offload {none, cpu} x `zero.Init` {off, on} x fp32 x folding TP {2, 4} x EP {2, 4} (world 4), torch SGD on the offloaded CPU fp32 partitions. Not validated (and either rejected or left unchanged): DeepSpeedCPUAdam's offloaded step (the tests run torch SGD on the CPU fp32 partitions with `zero_force_ds_cpu_optimizer: false`; DeepSpeedCPUAdam steps the same partitions but through its own kernel), bf16/fp16 with offload, 8-rank shapes, NVMe offload (rejected), parameter offload (rejected), ZeRO-1/2 optimizer offload (rejected; its offloaded norm path is being changed by deepspeedai#8823), Muon with offload (rejected). ### Not a duplicate No open or merged PR enables offload with AutoEP + AutoTP folding (searched "folding offload", "AutoEP offload", "AutoTP offload"). deepspeedai#8823 fixes ZeRO-1/2 routed-expert clipping under folding and does not touch ZeRO-3 or offload; ZeRO-1/2 offload is left rejected so the two do not interact. Tracked in the Q4 roadmap deepspeedai#8672 (AutoEP + AutoTP folding milestone). Signed-off-by: 0z5a <dezhen.lu@student.uni-tuebingen.de> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: pengdurice <pengduhit@gmail.com>
…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 <dezhen.lu@student.uni-tuebingen.de> Co-authored-by: pengdurice <pengduhit@gmail.com>
AutoEP + AutoTP folding under ZeRO-3, and correct gradients for tensor-parallel layers under folding
Summary
its partition specification names (the tests shard attention only), AutoEP distributes the routed experts, and
expert_tensor_parallel_sizestays 1. This also works for models built underdeepspeed.zero.Init.tensor-parallel, that layer and every parameter below it get wrong gradients. On unmodified
masterat ZeRO-2,36 of the 45 gradients of a small GLM-4.5-Air-shaped model differ from plain data parallelism by 1.0 % to 5.5 %.
The existing folding tests shard nothing ("skip" for every weight), so they could not see it.
ZeRO-3, on 4 and 8 ranks, with and without
zero.Init. On GLM-4.5-Air with 23 of its 46 layers (53.0Bparameters) on 8 H200s, the folded ZeRO-3 run gives the same losses and gradient norms as the unfolded run on the
same samples (largest norm difference 0.1 %).
Problem 1: ZeRO-3 was rejected
Two checks rejected AutoEP + AutoTP under ZeRO-3:
validate_folding_global(deepspeed/module_inject/auto_ep_folding.py): "AutoEP+AutoTP with ZeRO stage 3 isreserved for the separate ZeRO-3 composition lane".
DeepSpeedEngine._validate_zero3_moe_compatibility: "AutoEP with ZeRO Stage 3 does not support AutoTP yet".Removing them is not enough. ZeRO-3 did not apply the per-family gradient corrections folding needs, counted the
gradient norm wrongly, and AutoTP could not shard a model built under
zero.Init(see "The change").Problem 2: wrong gradients below every folded MoE layer (all ZeRO stages)
In the folded MoE layer each TP peer dispatches only its share of the (token, expert) assignments, and
restore_combinedall-gathers the results back into the full output. The backward of that all-gather(
_AllGatherVariableRows) all-reduces the replicated output gradient, so each peer getstp_sizetimes thegradient of the assignments it kept. The gradient the layer returns for its input is therefore, on peer
p:No peer holds the true gradient; only their average is right.
dx, and the folding reduction averagesthem over the TP group, which gives the gradient of the averaged
dx. This is why the existing folding testspass: every weight there is replicated.
o_proj) computes its shard's weight gradient from itsown
dx_p, and its gradient is not reduced over the TP group. A column-parallel layer (q_proj,k_proj,v_proj) sums the peers' partial input gradients, each computed from a differentdx_p. Both are wrong, andevery parameter below them inherits the error.
Measured with the new test on unmodified
masterat ZeRO-2 (4 ranks, TP 2 x EP 2): 36 of 45 gradients differ,relative errors 1.0 % to 5.5 %, scale 0.995 to 1.021 (wrong direction, not a scale factor). The 9 correct gradients
are exactly those that do not pass back through a tensor-parallel layer after leaving an MoE layer:
lm_head, thefinal norm, the last layer's MoE block, and the norm that feeds it.
Fix:
average_gradient_over_tp(deepspeed/moe/ep_tp_dispatch.py) is an identity in forward and averages thegradient over the TP group in backward. The folded MoE layer applies it to its input, so every peer returns the true
input gradient. The cost is one all-reduce of
[tokens, hidden]over the TP group per MoE layer in backward, thesame size as the one a column-parallel layer already does. The router still needs the AVERAGE reduction and the
routed experts the division by
tp_size, because those corrections are about gradients computed inside the layer.The change
deepspeed/moe/ep_tp_dispatch.pyaverage_gradient_over_tp: identity forward, TP average in backwarddeepspeed/module_inject/auto_ep_layer.pydeepspeed/module_inject/auto_ep_folding.pyexpert_tensor_parallel_size > 1still aredeepspeed/runtime/zero/stage3.pydeepspeed/runtime/engine.py_validate_zero3_moe_compatibility; ZeRO-3 partition groups resolved whenever AutoTP runs; caller's optimizer remapped after AutoTP; the engine's fallback correction skips ZeRO-3deepspeed/module_inject/auto_tp.pyzero.Initbefore sharding themautoep.rst,config-json.md)Details:
Gradient correction in ZeRO-3.
DeepSpeedZeroOptimizer_Stage3getsconfigure_autoep_folding_tp_gradient_reduction,which the engine already calls on any optimizer that has it. Each micro-batch gradient is corrected with the
existing
apply_folding_correction_to_grad_bufferbefore it is reduce-scattered: AVERAGE over TP for the routerand other replicated parameters, a division by
tp_sizefor routed experts, nothing for TP-sharded parameters.The engine's own after-backward correction now skips ZeRO-3: a gradient still waiting in the reduce bucket has been
corrected already, and a second pass would divide expert gradients by
tp_sizetwice.Gradient norm in ZeRO-3. ZeRO-3 counts a parameter that is not tensor-parallel only on model-parallel rank 0,
then sums over the partition group and the model-parallel group. That assumes each TP rank holds its own copy
partitioned over the data-parallel group. Two cases break it, and
_grad_norm_counts_every_rankdetects them:expert-parallel already covers every rank. Counting only on TP rank 0 and then summing over TP misses half the
experts and doubles the rest (8 ranks, TP 2 x EP 4: the result is
2 * (norms on ranks 0, 2, 4, 6));zero.Initpartitions every parameter overall ranks before AutoTP creates the data-parallel group.
In both cases every rank counts its partition and the model-parallel all-reduce is skipped.
AutoTP with
zero.Init. A weight partitioned byzero.Initholds an empty 1-D placeholder, so AutoTP bothskipped the layer (its "is this a 2-D linear weight" check saw 1 dimension) and would have sliced the
placeholder. AutoTP now reads
ds_shapefor that check, gathers the weight once, and gives the layer an ordinaryparameter holding the full value to slice. ZeRO-3 partitions the new shard over the data-parallel group
(
_resolve_zero3_param_placementnow also runs when AutoTP is on). The replaced parameters are returned as aReplacementSourceMap, and the engine re-points a caller-built optimizer or parameter list with the existingAutoEP remap functions. The
use_muonandmuon_num_headstags are carried over.A hang avoided.
deepspeed.comm.get_all_ranks_from_groupstops only whenget_global_rankraises, and torchnever raises for the world group, so it never returns for that group. The norm code enumerates ranks bounded by
the group size instead.
get_all_ranks_from_groupitself is unchanged here.Tests
tests/unit/v1/moe/test_autoep_autotp_sharded_attention.py(new). The model is a small transformersglm4_moe(the GLM-4.5-Air architecture): attention with biases, one dense MLP layer, two MoE layers with a sigmoid router and
a shared expert. AutoTP shards only
q_proj,k_proj,v_proj(column) ando_proj(row); AutoEP replaces the MoEblocks. The reference is the same model, float32, plain data parallelism at ZeRO-0, reading the same micro-batches
(2 per rank, gradient accumulation 2). The test checks:
over the expert-parallel group), to 1e-4 relative;
approximate norm for MoE parameter groups with or without folding (
_average_expert_grad_normsaverages theexpert groups' norms over the expert-data-parallel group), so its norm is printed but not asserted.
Folding only needs TP and EP to divide the world size (dense layers use TP x world/TP, experts EP x world/EP),
so the test covers TP x EP smaller than, equal to and larger than the world size:
zero.Init27 passed in 741 s on one node of 8 H200.
The earlier two-shape version of this file (4 ranks TP 2 x EP 2, 8 ranks TP 2 x EP 4) on unmodified
master, ZeRO-2cases only (
masterrejects ZeRO-3): both fail, 36 of 45 gradients differ.test_autoep_autotp_folding_config.py: the rule test that asserted the ZeRO-3 rejection now asserts that ZeRO-3 isaccepted. The duplicate rejection test in
test_autoep_autotp_grad_parity.pyis removed.Existing tests, rerun on this branch:
test_autoep_autotp_grad_parity.py,test_autoep_autotp_folding_config.py,test_autoep_autotp_runtime.py,test_autoep_autotp_dispatch.py,test_autoep_autotp_checkpoint.py,test_autoep_grad_parity.py,unit/v1/autotp/test_autotp_training.py: 123 passed, 0 failed (17 skipped and 29deselected by their own conditions).
Hardware: one node of 8 H200, torch 2.8.0+cu126, transformers 5.15.1.
pre-commit run --filespasses on everychanged file.
GLM-4.5-Air, 1 node of 8 H200
Config-only GLM-4.5-Air (random weights) built under
zero.Init. Sequence 4,096, micro-batch 1, bf16 with bf16optimizer states, AdamW at learning rate 1e-5, activation checkpointing, ZeRO-3 with
leaf_moduleon the AutoEPlayer, AutoEP preset
deepseek_v3, AutoTP on the attention projections only. Both runs of a pair read the same 4sequences per step: the folded run's 4 dense data-parallel ranks and the unfolded run's 4 ranks take the same
samples. The loss is the running mean of the per-step losses since step 1, as the benchmark prints it.
size of bf16 rounding.
EP 16 on 16 GPUs, attention, dense MLP and shared expert sharded) had a step-1 gradient norm of 3.2311 against
2.9245 for the unfolded run, 10.5 % higher.
8 layers (0.727 against 0.541 s per step) and 4 % faster at 23 layers. The unfolded 23-layer run reserves 134.9
of 139.8 GiB per GPU, the folded one 76.9 GiB.