Skip to content

ZeRO-3: reuse the weight partition as the master copy when it already has the master dtype - #8842

Merged
pengdurice merged 6 commits into
deepspeedai:masterfrom
pengdurice:peng-fix-zero3-master-copy-device-v1
Nov 5, 2026
Merged

pengdurice merged 6 commits into
deepspeedai:masterfrom
pengdurice:peng-fix-zero3-master-copy-device-v1

Conversation

@pengdurice

@pengdurice pengdurice commented Oct 16, 2026 •

Copy link
Copy Markdown
Contributor

ZeRO-3: reuse the weight partition as the master copy when it already has the master dtype

Summary

DeepSpeedZeroOptimizer_Stage3._create_fp32_partitions has a branch that uses a sub-group's weight partition as its
master copy when the two would be identical (same dtype, on the device). Its check compared
tensor.device == self.device, where self.device is a string such as "cuda:0"
(get_accelerator().current_device_name()). A torch.device never equals a string, so the branch never ran, and
ZeRO-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:

Run Config Device memory saved per rank
Plain fp32 no bf16, fp16 or torch_autocast section 4 bytes per parameter in the rank's partition
fp32 model under torch autocast torch_autocast enabled, no bf16 / fp16 section 4 bytes per parameter in the rank's partition
bf16 master weights "bf16": {"enabled": true, "bf16_master_weights_and_grads": true} 2 bytes per parameter in the rank's partition

Runs with "bf16": {"enabled": true} and fp32 master weights are not affected: their partitions are bf16 and the
master 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_states must not
move 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 edits stage3.py, but only the restore of fp32 masters from a checkpoint.

The change

deepspeed/runtime/zero/stage3.py:

Where What
_create_fp32_partitions Compare with torch.device(self.device). Record the sub-groups whose master is the weight partition in aliased_fp32_sub_groups.
offload_states / reload_states, hp_params Move only the masters that have their own storage (_fp32_partitions_with_own_storage). An aliased master moves with lp_params; moving it alone would split it from the weights.
offload_states / reload_states, lp_params After lp_param_buffer moves, 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_params without lp_params Log a warning once: the aliased sub-groups stay on the device, so the call frees no memory for them. The DeepSpeed logger prints only warnings by default, so an info log would not show.

docs/code-docs/source/zero3.rst: the hp_params entry says that, in these runs, the fp32 copies move only with
lp_params.

Behaviour changes

  1. Memory. As in the Summary table.
  2. offload_states with hp_params alone frees no device memory for aliased sub-groups (the warning and the docs
    say so). With lp_params in the same call, or with include=None, the weights and their masters move together.
  3. GatheredParameters edits now persist in these runs. A weight edit under
    deepspeed.zero.GatheredParameters(..., modifier_rank=...) writes into the weight partition, which is now the
    master. So the next step() updates the edited value. Before this PR, step() copied the separate master back
    over the edit, unless refresh_fp32_params() was called. This is intended: there is no second copy to restore
    from. 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.

Setup Without the fix With the fix
1 node, 2 H200, first 4 layers, AutoEP 2, 4,096 tokens 51.62 GiB allocated between steps, 62.04 GiB peak 41.50 GiB allocated, 51.91 GiB peak; the same losses at every printed step (13.4375, 13.34375, 13.229167, 13.140625)
4 nodes x 8 H200, all 60 layers (426B), AutoTP 4 x AutoEP 8, 8,192 tokens per GPU out of memory in step 2 at 125.0 GiB allocated trains: 117.9 GiB peak, 15.14 s per step (mean of steps 2-4)
the same at 16,384 tokens per GPU trains: 124.1 GiB peak, 25.17 s per step

Tests

New tests, all with 2 ranks and ZeRO-3 without optimizer offload:

Test What it checks
TestZero3AutocastSharesMasterWeights (test_zero.py) torch autocast (bf16), fp32 weights: every master partition is the weight partition itself; 2 training steps run.
TestZero3Fp32SharesMasterWeights (test_zero.py) Plain fp32: every master partition is the weight partition; 3 steps match torch.optim.Adam on 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_memory False / True) Offload and reload [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 inside lp_param_buffer; offloading lp_params frees 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 the
master 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.

# master c6291b7e1 + only this PR's two test files:
pytest unit/v1/zero/test_zero.py unit/v1/zero/test_offload_states.py \
    -k "SharesMasterWeights or AliasedMaster"                             # 6 failed (2 + 4, as above)
# this branch, merged with master c6291b7e1:
pytest unit/v1/zero/test_zero.py unit/v1/zero/test_offload_states.py \
    -k "SharesMasterWeights or OffloadPinnedCopyBack or AliasedMaster"     # 8 passed
pytest unit/v1/zero/test_offload_states.py                                # 132 passed
pytest unit/v1/zero/test_zero.py                                          # 110 passed, 1 skipped (TestZero3ParamPartitioningBaseBF16, marked "not working")
pytest unit/v1/zero/test_zero_autocast.py                                 # 24 passed

The hp_params-only round trip in TestOffloadStatesZero3AliasedMaster prints the new warning once per process.

pre-commit run --files passes on the changed files.

Compatibility

Cell Validated
ZeRO-3, no offload, plain fp32 yes (tests, including parity with torch.optim.Adam and the offload round trips)
ZeRO-3, no offload, fp32 model under torch autocast yes (tests)
ZeRO-3, bf16 master weights (AutoTP + AutoEP) yes (1 node and 4 nodes, see Measured; before this branch existed)
ZeRO-3 with optimizer offload, NVMe, or parameter offload branch not reached; aliased_fp32_sub_groups stays empty and offload_states behaves as before
ZeRO-1 / ZeRO-2 not touched
Accelerators other than CUDA torch.device(name) accepts every accelerator's device name; not run
Multi-node not run for the new tests

AI assistance

This change, its tests and this description were prepared with AI assistance (Claude).

@ghost ghost left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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]>
@pengdurice

Copy link
Copy Markdown
Contributor Author

@0z5a , thank you for the review. fixed accordingly.

@pengdurice
pengdurice marked this pull request as ready for review October 25, 2026 17:32
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 25, 2026 •

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-10-25T17:40:33.678713Z bd89a53 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.

@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: 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"}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge 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 ghost left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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 1409708d the weights still move by about 1e-2 across the lp_params round trip, and the master partition ends up outside lp_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_buffer lines up with the buffer.
  • For that run I had to relax the FusedAdam-only class check in offload_states. The hp_params/lp_params paths 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_states move aliased sub-groups with lp_params. Reviewers will look for both. The fp32 parity test against torch.optim.Adam covers the numerics part, thanks.
  • GatheredParameters edits. Edits under modifier_rank now persist into the master in fp32 runs, where master used to overwrite them at the next step unless refresh_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):

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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.

…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 tohtana left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Thank you for the improvement! Looks good to me.

@tohtana
tohtana added this pull request to the merge queue Nov 5, 2026
@github-merge-queue
github-merge-queue Bot removed this pull request from the merge queue due to failed status checks Nov 5, 2026
@pengdurice
pengdurice added this pull request to the merge queue Nov 5, 2026
@github-merge-queue
github-merge-queue Bot removed this pull request from the merge queue due to failed status checks Nov 5, 2026
@pengdurice
pengdurice added this pull request to the merge queue Nov 5, 2026
Merged via the queue into deepspeedai:master with commit ed82739 Nov 5, 2026
15 checks passed
@pengdurice
pengdurice deleted the peng-fix-zero3-master-copy-device-v1 branch November 5, 2026 22:35
xylian86 pushed a commit to xylian86/DeepSpeed that referenced this pull request Nov 7, 2026
…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]>
@tohtana tohtana added the needs-gpu-test GPU testing is recommended to validate the changes in this PR. label Nov 10, 2026
@tohtana tohtana removed the needs-gpu-test GPU testing is recommended to validate the changes in this PR. label Nov 14, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants