Repository navigation
ZeRO-3: reuse the weight partition as the master copy when it already has the master dtype - #8842
Conversation
… has the master dtype Signed-off-by: pengdurice <[email protected]>
ghost
left a comment
There was a problem hiding this comment.
The fix itself is right: torch.device == str was always False, so the alias branch was dead. But that dead branch was also what kept hp and lp storage separate everywhere, and offload_states / reload_states rely on that. Turning it on breaks the offload round trip, and it now also fires for plain fp32 ZeRO-3, not only autocast / bf16-master runs.
1. [blocking] offload_states / reload_states desync the weights once the partitions alias — stage3.py:1162, stage3.py:3881, stage3.py:3948
Once fp32_partitioned_groups_flat[i] is fp16_partitioned_groups_flat[i], offloading hp_params rebinds .data of the shared tensor while the ds_tensors still point into lp_param_buffer. After the next step() they get repointed to the new storage, lp_param_buffer goes stale, and a later lp_params offload/reload restores stale weights.
Repro on the CPU accelerator (1 rank, plain fp32 nn.Sequential, Adam, ZeRO-3, no optimizer offload): step → offload/reload [hp_params] → step → offload/reload [lp_params]. On this branch the module weights change by up to 1e-2 across the lp_params round trip and no longer share storage with lp_param_buffer; on the merge base the same sequence is exact.
Also, while aliased, offloading lp_params can't free device memory (the master still references the old storage), and after a reload the two lists are separate tensors again, so the saving silently disappears. TestDynamicOffloadStatesZero3 only runs bf16, where nothing aliases, so it doesn't catch this. Suggest moving hp and lp together for aliased groups (and re-aliasing after reload), plus an fp32 / autocast parametrization of that test.
2. [should-fix] This now applies to every plain fp32 ZeRO-3 run — stage3.py:1162
The branch also fires without any bf16 / fp16 / autocast section, but the summary lists only autocast with an fp32 model and bf16 master weights, so reviewers may read plain fp32 runs as untouched. Please call that out, and add a numerical parity test (aliased vs. a forced copy over a few steps) in addition to the identity check in TestZero3AutocastSharesMasterWeights.
3. [question] GatheredParameters edits now persist in fp32 runs
With the alias, weight edits under GatheredParameters(..., modifier_rank=0) now go straight into the master copy in fp32 runs. On master the next step() overwrote them unless refresh_fp32_params() was called (in my check the weight mean is -0.011 on master vs. 0.500 kept here); bf16 runs keep the old behaviour. Is that intended? If so it deserves a note. Related: with #8843 the fp32 sub-groups from keep_in_fp32_modules will alias too, and #8843 still allows hp_params offload for mixed dtypes, which is the half that breaks the alias.
…ates With the master partition reused as the weight partition (same dtype, on the device), offload_states and reload_states moved the two apart: an hp_params round trip rebound the shared tensor to new storage while lp_param_buffer kept the old one, so after the next step a weight round trip restored stale weights, and an lp_params offload freed no device memory because the master still held it. Sub-groups whose master partition is the weight partition are now recorded. hp_params offload and reload leave them alone; they move with lp_params, and after lp_param_buffer moves each of them is pointed at its slice again, keeping the tensor the optimizer holds. Tests: offload round trips for fp32 and torch autocast models (weights unchanged, still one copy, the weights' memory freed, training identical to a run without offloading), and fp32 ZeRO-3 training against torch.optim.Adam. Signed-off-by: pengdurice <[email protected]>
|
@0z5a , thank you for the review. fixed accordingly. |
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: bd89a532d5
ℹ️ About Codex in GitHub
Codex has been enabled to automatically 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 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| }, | ||
| } | ||
| if precision == "autocast": | ||
| config_dict["torch_autocast"] = {"enabled": True, "dtype": "bfloat16"} |
There was a problem hiding this comment.
Skip autocast cases without BF16 support
When this parametrization runs on a device for which get_accelerator().is_bf16_supported() is false (for example, an NVIDIA V100), the autocast case still forces bfloat16; CUDA autocast rejects that dtype at forward time, so this test fails before exercising the offload behavior. Add the same capability guard already used by TestZero3AutocastSharesMasterWeights in tests/unit/v1/zero/test_zero.py so unsupported jobs skip only this case.
Useful? React with 👍 / 👎.
ghost
left a comment
There was a problem hiding this comment.
Re-checked at bd89a532 (the fix is 8045140f).
My blocking point from the earlier round is fixed. I reran the same sequence on the CPU accelerator: step → offload/reload [hp_params] → step → offload/reload [lp_params].
- On
1409708dthe weights still move by about 1e-2 across thelp_paramsround trip, and the master partition ends up outsidelp_param_buffer. - On this head the round trip is exact. The master is still the weight partition itself, inside
lp_param_buffer. - That holds for plain fp32 and for autocast, on 1 rank and on 2 ranks with
sub_group_size: 64, which gives two aliased sub-groups. So the offset walk in_point_aliased_fp32_partitions_at_lp_bufferlines up with the buffer. - For that run I had to relax the FusedAdam-only class check in
offload_states. Thehp_params/lp_paramspaths don't use FusedAdam itself. - I couldn't run the two new test classes here, because they need the fused_adam op.
A few things are left from the earlier round:
- The description. It still says the change is one line, and it lists only autocast and bf16 master weights. Please add two things: plain fp32 ZeRO-3 runs now share the master too, and
offload_states/reload_statesmove aliased sub-groups withlp_params. Reviewers will look for both. The fp32 parity test againsttorch.optim.Adamcovers the numerics part, thanks. GatheredParametersedits. Edits undermodifier_ranknow persist into the master in fp32 runs, where master used to overwrite them at the next step unlessrefresh_fp32_params()was called. Is that intended? A sentence in the description would settle it.- The Codex note on the autocast parametrization. It asks for that case to skip on devices without bf16 support. It's still open, and it looks right to me.
- The merge conflict with master in
tests/unit/v1/zero/test_zero.py.
| ] | ||
|
|
||
| for src_tensor, dest_buf in zip(self.fp32_partitioned_groups_flat, self.hp_params_pin_buffers): | ||
| for src_tensor, dest_buf in zip(self._fp32_partitions_with_own_storage(), self.hp_params_pin_buffers): |
There was a problem hiding this comment.
With only hp_params in include, an aliased sub-group is now left in place, since it moves with lp_params. So that call frees no memory for it. That's the right behaviour, but a caller offloading hp_params to make room gets nothing back without being told. Maybe a one-time info log, or a line in the offload_states docstring.
Signed-off-by: pengdurice <[email protected]>
…he device Document it on the hp_params entry in zero3.rst, and skip the autocast case of TestOffloadStatesZero3AliasedMaster on accelerators without bf16. Signed-off-by: pengdurice <[email protected]>
tohtana
left a comment
There was a problem hiding this comment.
Thank you for the improvement! Looks good to me.
…deepspeedai#9020) ## CI: drop the abandoned deepspeed-kernels from the dev requirements ### Problem When Modal has no GPU within 600 s, `modal-torch-latest` falls back to AWS. Since deepspeedai#8950 (merged 2026-11-04) that fallback has failed 6 times out of 6 with `AwsControllerError: AWS prepare failed with exit code 1`, and no tests ran. Five were merge-queue entries whose PRs were not at fault (deepspeedai#8985 twice, deepspeedai#8728, deepspeedai#8612, deepspeedai#8842); one was the scheduled run on master. Examples: - https://github.com/deepspeedai/DeepSpeed/actions/runs/41940811586/job/126960989358 - https://github.com/deepspeedai/DeepSpeed/actions/runs/42061411246/job/127364012408 ### Cause deepspeedai#8950 added `python -m pip check` after "install candidate DeepSpeed" in `build_remote_commands`. On the AWS environment (uv venv, CPython 3.12.14) it exits 1 with: ``` deepspeed-kernels 0.0.1.dev1698255861 is not supported on this platform ``` `deepspeed-kernels` comes from `requirements/requirements-dev.txt`. Its only file on PyPI (last release 2023-10-25) is named `deepspeed_kernels-0.0.1.dev1698255861-py3-none-manylinux1_x86_64.whl`, but the `WHEEL` file inside it says `Tag: cp38-cp38-linux_x86_64`. pip installs by the file name (any Python 3) and `pip check` checks the internal tag (Python 3.8 only). To see the tag: ``` pip download deepspeed-kernels==0.0.1.dev1698255861 --no-deps -d /tmp/dk && unzip -p /tmp/dk/*.whl '*.dist-info/WHEEL' ``` The job logs never show this line: the prepare output is cut at 24,000 characters of stdout (`SSM_INLINE_STDOUT_CHARS`), and the complete output is fetched only when the test phase fails. I found it by running the same prepare commands outside CI. (The Modal sandbox runs the same `pip check` and prints `No broken requirements found.` with the same package; I could not find out why it passes there.) ### Change | Where | What | |---|---| | `requirements/requirements-dev.txt` | Remove `deepspeed-kernels`, which is no longer maintained. | | `ci/torch_latest.py`: `_emit_ssm_output` | Fetch the complete output tail for a failed `prepare` phase too, not only `test`, so the next prepare failure shows its error in the job log. | | `ci/test_torch_latest.py` | One test for the prepare tail; the fake AWS CLI returns the prepare output for prepare-phase S3 keys. | `pip check` itself is unchanged (as deepspeedai#8950 wrote it). The first version of this PR exempted the `deepspeed-kernels` line instead; following review, the package is removed rather than exempted. No active CI job uses `deepspeed-kernels`: - the inference-v2 kernel tests are deselected by `tests/pytest.ini` (`not inference_v2_ops`); the only workflow that selected them (`nv-a6000.yml`) is disabled; - `nv-pre-compile-ops` builds with `DS_BUILD_CUTLASS_OPS=0 DS_BUILD_RAGGED_DEVICE_OPS=0`; - it was the only reason `cmake` was installed, and nothing else in `ci/`, `tests/` or the workflows uses `cmake`. Not removed: `op_builder/ragged_ops.py` and `op_builder/inference_cutlass_builder.py` link prebuilt libraries from the package (`-lblockedflash`, `-ldeepspeedft`) to build the inference-v2 ragged kernels and CUTLASS MoE / mixed GEMM. Inference v2 is not deprecated (deepspeedai#8489), and DeepSpeed-MII (0.3.3) still installs `deepspeed-kernels` as a dependency, so those builders keep working for its users. The AWS prepare installs the requirements of the candidate commit, so this change also applies to its own merge-queue run. ### Duplicate check Searched open PRs and issues on 2026-11-05 for "deepspeed-kernels", "pip check", "AWS prepare failed" and "capacity fallback": none addresses this. deepspeedai#8950 added the check; deepspeedai#8921 moved the AWS fallback to Python 3.12. ### Tests Hardware: CPU only (CI controller code and requirements; no GPU path changed). Intel Xeon Platinum 8375C, Ubuntu 22.04.5, CPython 3.12.14, pip 26.3, pytest 8.3.5. | Command | Result | |---|---| | `python ci/test_torch_latest.py` | 50/50 passed (49 existing + 1 new) | | `python ci/test_tests_fetcher.py` | 27/27 passed | | `pre-commit run --files ci/torch_latest.py ci/test_torch_latest.py requirements/requirements-dev.txt` | all hooks pass | | the new test against the master version of `ci/` | fails (the prepare log ends at "AWS prepare failed with exit code 1" without the late line) | | the AWS prepare commands rerun from scratch outside CI with this `requirements-dev.txt` (uv 0.12.7, CPython 3.12.14, the three requirements files, torch 2.10.0 cu128 pin, Transformers `main`, DeepSpeed master) | RERUN_RESULT | `test_aws_prepare_failure_emits_bounded_s3_tail`: a failed prepare whose output exceeds the inline limit prints the tail, including the last line, read from the prepare-phase S3 key. Not run: the real AWS fallback (needs the CI's AWS credentials) and the Modal sandbox. No workflow runs `ci/test_torch_latest.py`; I ran it by hand. ### Compatibility CI and development requirements only. No DeepSpeed runtime code changes, so no ZeRO stage, offload, precision or parallelism cell is affected. Users who build the inference-v2 ragged or CUTLASS ops from a source checkout now install `deepspeed-kernels` themselves (DeepSpeed-MII does this). ### AI assistance This change, its tests and this description were prepared with AI assistance (Claude), which also ran the tests above. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Signed-off-by: pengdurice <[email protected]> Co-authored-by: Claude Opus 5.5 <[email protected]>
ZeRO-3: reuse the weight partition as the master copy when it already has the master dtype
Summary
DeepSpeedZeroOptimizer_Stage3._create_fp32_partitionshas a branch that uses a sub-group's weight partition as itsmaster copy when the two would be identical (same dtype, on the device). Its check compared
tensor.device == self.device, whereself.deviceis a string such as"cuda:0"(
get_accelerator().current_device_name()). Atorch.devicenever equals a string, so the branch never ran, andZeRO-3 kept a second copy of every partition. This PR compares with
torch.device(self.device).The branch now runs in these ZeRO-3 runs without optimizer offload:
bf16,fp16ortorch_autocastsectiontorch_autocastenabled, nobf16/fp16section"bf16": {"enabled": true, "bf16_master_weights_and_grads": true}Runs with
"bf16": {"enabled": true}and fp32 master weights are not affected: their partitions are bf16 and themaster copy is fp32, so the branch does not apply with or without this PR. Runs with optimizer offload or NVMe are not
affected either: those branches come first.
In these runs the master and the weight partition are the same tensor, so
offload_states/reload_statesmust notmove them apart. This PR makes those sub-groups move with
lp_params(details below).Duplicate check
Searched open pull requests on 2026-11-01 ("master copy stage3", "fp32_partitioned_groups_flat",
"torch.device self.device", "offload_states alias", "master weights autocast zero3"). None changes this comparison or
offload_states. #8892 also editsstage3.py, but only the restore of fp32 masters from a checkpoint.The change
deepspeed/runtime/zero/stage3.py:_create_fp32_partitionstorch.device(self.device). Record the sub-groups whose master is the weight partition inaliased_fp32_sub_groups.offload_states/reload_states,hp_params_fp32_partitions_with_own_storage). An aliased master moves withlp_params; moving it alone would split it from the weights.offload_states/reload_states,lp_paramslp_param_buffermoves, point each aliased master at its slice of the moved buffer again (_point_aliased_fp32_partitions_at_lp_buffer). The master stays the tensor the optimizer holds.offload_states,hp_paramswithoutlp_paramsdocs/code-docs/source/zero3.rst: thehp_paramsentry says that, in these runs, the fp32 copies move only withlp_params.Behaviour changes
offload_stateswithhp_paramsalone frees no device memory for aliased sub-groups (the warning and the docssay so). With
lp_paramsin the same call, or withinclude=None, the weights and their masters move together.GatheredParametersedits now persist in these runs. A weight edit underdeepspeed.zero.GatheredParameters(..., modifier_rank=...)writes into the weight partition, which is now themaster. So the next
step()updates the edited value. Before this PR,step()copied the separate master backover the edit, unless
refresh_fp32_params()was called. This is intended: there is no second copy to restorefrom. Runs with bf16 / fp16 weights and fp32 masters keep the old behaviour.
refresh_fp32_params()still works;for an aliased sub-group it copies the partition onto itself.
Measured
MiniMax-M3 built from its config (random weights), ZeRO-3, bf16 weights with bf16 master weights and Adam states, no
CPU offload. The fix was tested in a DeepSpeed study tree before this branch existed.
Tests
New tests, all with 2 ranks and ZeRO-3 without optimizer offload:
TestZero3AutocastSharesMasterWeights(test_zero.py)TestZero3Fp32SharesMasterWeights(test_zero.py)torch.optim.Adamon an unsharded copy (losses and final weights, rtol 1e-5, atol 1e-6, gradient clipping off).TestOffloadStatesZero3AliasedMaster(test_offload_states.py; fp32 and autocast,pin_memoryFalse / True)[lp_params],[hp_params],[lp_params],[hp_params, lp_params], then all states, with a step before each. After each round trip the weights are bitwise unchanged and each master is still the weight partition insidelp_param_buffer; offloadinglp_paramsfrees at least the weights' bytes. At the end the weights equal those of a run without offloading, bitwise. The autocast case skips on accelerators without bf16.On master the first two fail at
assert master is model_partition, and the third fails at its first check that themaster is the weight partition.
Hardware: 1 node of 8 H200, torch 2.8.0+cu126, Python 3.10.12, pytest 9.1.1. The driver version was not recorded
in this run; the earlier runs on these nodes used 580.126.09.
The
hp_params-only round trip inTestOffloadStatesZero3AliasedMasterprints the new warning once per process.pre-commit run --filespasses on the changed files.Compatibility
torch.optim.Adamand the offload round trips)aliased_fp32_sub_groupsstays empty andoffload_statesbehaves as beforetorch.device(name)accepts every accelerator's device name; not runAI assistance
This change, its tests and this description were prepared with AI assistance (Claude).