Repository navigation
Fix ZeRO parameter alignment for grouped_mm - #8277
Conversation
|
Codex usage limits have been reached for code reviews. Please check with the admins of this repo to increase the limits by adding credits. |
Signed-off-by: Cao Yuhang <[email protected]>
6e3f912 to
29044f6
Compare
There was a problem hiding this comment.
Pull request overview
Fixes ZeRO stage 1/2 parameter rebinding so model parameters exposed to alignment-sensitive kernels (e.g., torch._grouped_mm) remain 16-byte aligned even when their corresponding flat-buffer views are not.
Changes:
- Update ZeRO stage 1/2
_update_model_bit16_weights()to keep zero-copy views when aligned, otherwise preserve/allocate an aligned tensor and copy updated values into it. - Add a ZeRO-1 BF16 regression test that constructs a deliberately misaligned flat-buffer view and asserts the model’s parameter pointer remains 16-byte aligned across an optimizer step.
Reviewed changes
Copilot reviewed 2 out of 2 changed files in this pull request and generated 3 comments.
| File | Description |
|---|---|
deepspeed/runtime/zero/stage_1_and_2.py |
Adds alignment-aware logic when rebinding model params from flat buffers to avoid misaligned parameter pointers. |
tests/unit/v1/zero/test_stage2_flatten_on_gpu.py |
Adds a regression test model + test case that validates alignment is preserved for a misaligned flat view under ZeRO-1 BF16. |
💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.
Signed-off-by: Cao Yuhang <[email protected]>
There was a problem hiding this comment.
Hi @fwerkor, thank you for submitting this PR!
This is useful, but I think this approach has two challenges:
- This has too much impact about the performance and memory usage. All misaligned parameters will be duplicated.
- This can easily cause a bug about synchronization. Actually the current code leaves the flat buffer stale when a checkpoint is loaded, so the first optimizer step silently overwrites loaded misaligned parameters. (I reproduced this on ZeRO-1/2 with both
load_module_only=Trueandload_optimizer_states=False)
It might be okay to accept this as an opt-in, but I still feel the performance impact is too big. I think a long term solution is to pad parameters in the flat buffer. It will need more changes, but the performance/memory impact will be small.
Can you share your thoughts?
Signed-off-by: Cao Yuhang <[email protected]>
Signed-off-by: Cao Yuhang <[email protected]>
Signed-off-by: Cao Yuhang <[email protected]>
Thanks, agreed. I switched to padding the ZeRO flat buffer and synced with current master. The previous GPU CI was killed by the 1-hour timeout (exit 137) at ~76%, with no failures before that. |
tohtana
left a comment
There was a problem hiding this comment.
Thank you for switching to padding the flat buffer and adding the checkpoint reload regression tests! This addresses my original concerns.
I found two additional correctness issues in the updated implementation, detailed inline below.
This PR can have a significant impact on broad usage of DeepSpeed. Can we validate the correctness by running a simple training loop?
Signed-off-by: Cao Yuhang <[email protected]>
…mm-alignment Signed-off-by: Cao Yuhang <[email protected]> # Conflicts: # deepspeed/utils/mixed_precision_linkage.py
|
Thanks, addressed both issues.
I also added regression tests for the CPU flatten fallback with a short training loop, and for The existing alignment/checkpoint regression still passes as well. |
tohtana
left a comment
There was a problem hiding this comment.
Thank you for addressing my previous comments! The changes look good to me.
I left a few more comments (two of them already existed before your recent update).
b68b61a to
b6b8226
Compare
Signed-off-by: Cao Yuhang <[email protected]>
b6b8226 to
0460068
Compare
|
Thanks, addressed all three comments. I fixed the offload gradient indexing, preserved |
Signed-off-by: Masahiro Tanaka <[email protected]>
tohtana
left a comment
There was a problem hiding this comment.
Thanks for the fixes! They look good to me.
I left one comment about a similar issue to the previous one.
As we are not super confident in the correctness of all the features, can we make this opt-in?
I opened a PR to this PR branch. If you think it useful, please review and merge it. It would also be good if you could implement it separately.
|
Thanks — I merged your opt-in PR into this branch and also addressed the elastic |
080eb6b
deepspeedai#8277 rewrote ZeRO-1/2's _update_model_bit16_weights to bind each parameter with narrow(...).view(meta.shape), which keeps a zero-element parameter's shape, so stage_1_and_2.py takes master's version and no longer needs bind_flat_views. Co-Authored-By: Claude Opus 5 <[email protected]> Signed-off-by: alanhuangyoo <[email protected]>
deepspeedai#8277 rewrote ZeRO-1/2's _update_model_bit16_weights to bind each parameter with narrow(...).view(meta.shape), which keeps a zero-element parameter's shape, so stage_1_and_2.py takes master's version and no longer needs bind_flat_views. Signed-off-by: alanhuangyoo <[email protected]>
Follow-up to #9114 (stacked on its branch; proposal in #9113): lets `deferred_dw_flush_period` run with ZeRO stage 3. This PR was written with AI assistance (Claude Code). I have reviewed the code line by line, wrote part of it and signed off the commit. It depends on #8981, which is now merged; the branch is rebased onto it and the results below were measured on the`c76a7ea55`, which has the same tree as the then signed-off head `b708bbfc8`. The branch has since been rebased onto #9114's review fixes and a review fix added (head `e27a91cc9`); the results on that head are listed first below. ## How we support ZeRO-3, and what each part does: 1. **Gradient hook with no gradient** (this PR, `zero/stage3.py`, core, 4 lines). On a backward that stages, the expert weights are in the graph but get no gradient, and the per-parameter hook still fires. `reduce_independent_p_g_buckets_and_remove_grads` now returns early for a `None` gradient, as #9114 does for ZeRO-2. 2. **Stale accumulation buffer** (not in this PR; fixed by #8981, merged). `partition_grads` overwrote a parameter's gradient partition only in micro step 0 and added afterwards. A staged expert weight gets its first gradient of a window in a later micro step, so it was added onto the previous window's gradient. #8981 makes a parameter's first gradient after `step()` overwrite its partition, which is what staging needs. I did not duplicate that fix here. 3. **Unaligned weights** (this PR, `moe/ep_experts.py`). ZeRO-3 hands a module its weights as slices of a gathered buffer that need not start on the 16-byte boundary the CUDA `torch._grouped_mm` requires (`RuntimeError: expected data_ptr to be aligned to 16 bytes`). On this machine that failed for `use_grouped_mm=true` with ZeRO-3 with or without staging. `_grouped_mm_weight` clones a weight only when it is unaligned; the plain, fused gate+up and deferred paths use it. The deferred function saves the parameters and derives the aligned weights again in the backward, for which ZeRO-3 gathers them, so the gathered weights are not kept allocated between a layer's forward and its backward (e27a91c; with `gate_up_impl="fused"` the packed gate+up copy is still kept, see Review fixes). The ZeRO-stage rejection in `auto_ep_config.py` is removed and the docs updated. ## Open design question #8277 solved the same alignment failure for ZeRO-1/2 by padding the flat buffer (`zero_optimization.parameter_alignment`), explicitly without copying misaligned parameters. Item 3 here takes the other route for ZeRO-3: a weight-sized copy per forward, only when a gathered weight is unaligned. Extending the padding to ZeRO-3's gathered buffers would avoid the copy but is a larger change to `partition_parameters.py`. Maintainers should choose; item 3 can be dropped from this PR if padding is preferred. ## Duplicate-work check Searched open and closed issues/PRs for "deferred dw", "tgmm", "expected data_ptr to be aligned", "grouped_mm data_ptr aligned 16 bytes", "partition_grads micro_step_id stale gradient". Found #8981 (covers item 2; not duplicated, since merged) and #8276/#8277 (alignment for ZeRO-1/2 only; see above). Sibling paths: the ZeRO-2 hook guard is in #9114; ZeRO-1/2 passed the same two-window parity test without further changes. ## Tests run Hardware: 3x NVIDIA H200 (143 GiB), driver 595.112.07, PyTorch 2.8.0+cu129, Python 3.12, `DS_SKIP_CUDA_CHECK=1` (system CUDA toolkit 13.2). On `e27a91cc9` (rebased onto #9114 at `6ee0cbb9a`, which returns staged gradients in the same backward on every rank, plus the weight-retention fix): ``` pytest unit/v1/moe/test_autoep_grad_parity.py -k TestAutoEPDeferredDwParity -> 8 passed (2 GPUs, comm backend, accumulation 4, flush period 3, two optimizer steps) expert parallel 2, ZeRO 0/1/2/3: staged vs. unstaged parity expert parallel 1 (both ranks replicate every expert, different data), ZeRO 1/2/3, 12 rows per expert: ranks flush early in different backwards and still reduce together plus the step() guard pytest unit/v1/moe/test_autoep_expert_activation.py -k "TestDeferredDwStaging or slot or overlap" -> 48 passed (1 GPU, bf16) pytest unit/v1/zero/test_zero3_unused_param_grads.py -> 21 passed, 7 skipped (2 GPUs) pytest unit/v1/moe/test_autoep_expert_activation.py unit/module_inject/test_auto_ep_comm.py unit/v1/moe/test_autoep_unit.py -> 387 passed, 50 skipped (CPU, PyTorch 2.10.0+cpu) pre-commit run --files <changed files> -> passed ``` The rebase conflicted in `docs/_pages/config-json.md` and `test_autoep_grad_parity.py`; beyond resolving them, this PR now runs #9114's replicated-expert test under ZeRO-3 as well, since ZeRO-3 also reduces a gradient in the backward that returns it. The results below were not repeated on this head. Rerun on `c76a7ea55` (rebased onto master with #8981): ``` pytest unit/v1/moe/test_autoep_grad_parity.py -k DeferredDw -> 5 passed: staged vs unstaged gradients for ZeRO 0/1/2/3, plus the step() guard (2 GPUs, expert parallel 2, accumulation 4, flush period 3, two optimizer steps) pytest unit/v1/moe/test_autoep_expert_activation.py -k DeferredDwStaging -> 39 passed (1 GPU; includes the new unaligned-weights test) pytest unit/v1/zero/test_zero3_unused_param_grads.py -> 21 passed, 7 skipped (the tests added by #8981) pytest unit/module_inject/test_auto_ep_comm.py -> 65 passed, 3 skipped, 6 failed; the same 6 fail on unmodified master here (this torch build has no CPU `torch._grouped_mm`) ``` A single-GPU ZeRO-3 script over optimizer steps with flush periods 2/3/4 gave staged gradients within 0.8% of the largest unstaged gradient element (bf16 rounding). Before #8981 the same script gave 198%, and the ZeRO-3 case of the parity test failed at the second window. Run before the rebase and not repeated on this head: `unit/v1/moe/test_autoep_integration.py` (7 passed, 3 skipped), a `unit/v1/zero/test_zero.py` ZeRO-3 subset (40 passed, 1 skipped), and `pre-commit run --files <changed files>` (passed; the rebase did not change this PR's diff). Known gaps: the same pre-existing hang as in #9114 (zero-row groups in `torch._grouped_mm` on this machine) keeps the rest of `test_autoep_expert_activation.py` from running here; the full unit suite was not run. Commit ids: the branch was rebased onto #9114 at `6ee0cbb9a` (itself rebased onto master `b9896d054`, a README-only change) after these runs. The results labelled e27a91c were measured on the patch-identical commit c381ff0, whose tree differs only in that README line, and were not repeated. ## Review fixes - Codex P1 ([thread](#9115 (comment))): staged gradients returned on only some ranks of a ZeRO-3 partition group. Fixed in #9114 (`6ee0cbb9a`); reproduced here as a ZeRO-3 hang with that change reverted, and covered by the replicated-expert test for ZeRO 3. - Codex P2 (e27a91c): the detached weight aliases kept gathered expert weights allocated until the backward. In a probe emulating ZeRO-3's release (8 experts, 96 MiB of bf16 weights, one H200), the staged path kept 98 MiB after the release before the fix and 2 MiB after it with separate gate/up. With `gate_up_impl="fused"` it keeps 66 MiB, because the packed gate+up copy is still saved: packing it again in the backward made the fused staged forward+backward 30% slower at 8 rows per expert (2.16 -> 2.82 ms per microbatch; 128 experts, hidden 2048, intermediate 768). With the copy kept, timings were unchanged for both variants. The plain `torch._grouped_mm` path keeps its weights through the views autograd saves and is not changed. ## Compatibility matrix | Cell | Status | | --- | --- | | ZeRO 3, bf16, expert parallel 1 and 2, `comm` backend | validated (parity test above; expert parallel 1 by the 2-rank replicated-expert test and the single-GPU script) | | ZeRO 0 / 1 / 2 | re-validated by the same parity test | | ZeRO-3 optimizer / parameter offload, NVMe, hpZeRO, quantized gradients with staging | not validated | | DeepEP backend, sequence parallel, multi-node | not validated | No end-to-end throughput, peak-memory or convergence measurements were made for this PR; the module-level numbers under Review fixes are the only ones. Item 3 adds a `data_ptr()` check per weight per forward on the grouped-GEMM paths and, under ZeRO-3 with an unaligned gathered weight, a weight-sized copy per forward; its cost was not measured. --------- Signed-off-by: Zhipeng Wang <[email protected]> Co-authored-by: Claude Fable 5.2 <[email protected]>
Summary
ZeRO stage 1/2 stores model parameters as views into flattened fp16/bf16 buffers. Individual parameter views can start at non-16-byte offsets even when the flat buffer itself is aligned, which breaks alignment-sensitive kernels such as
torch._grouped_mm.Pad parameter boundaries inside the ZeRO flat buffer so model parameter views remain 16-byte aligned without duplicating misaligned parameters. The padded layout is propagated through partition/gradient offsets, LP↔HP linkage, DeepCompile gradient buffers, checkpoint restore, and
zero_to_fp32reconstruction.Older checkpoints without parameter-alignment padding remain loadable; their compact layout is converted when restored.
Tests
load_module_only=Trueandload_optimizer_states=False.master, including the ZeRO-1/2 DeepCompile file rename.Fixes #8276