Skip to content

Restore fp32 masters for ZeRO-3 and the ZeRO-1 BF16 optimizer - #8892

Merged
sfc-gh-truwase merged 11 commits into
deepspeedai:masterfrom
sfc-gh-truwase:load-fp32-masters-stage3-bf16
Nov 6, 2026
Merged

sfc-gh-truwase merged 11 commits into
deepspeedai:masterfrom
sfc-gh-truwase:load-fp32-masters-stage3-bf16

Conversation

@sfc-gh-truwase

@sfc-gh-truwase sfc-gh-truwase commented Oct 22, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

  • Follow-up to Keep fp32 masters on ZeRO-1 and ZeRO-2 when a resume skips optimizer state #8891 (merged as 2dd22dc). The delta against master is ZeRO-3 and the dedicated ZeRO-1 BF16 optimizer, plus the review fixes listed below.
  • load_checkpoint still always restores saved fp32 masters. load_optimizer_states=False keeps those masters and starts Adam with fresh moments. load_module_only=True rebuilds the dedicated BF16 optimizer from the loaded bf16 weights. ZeRO-3 still reads its fp32 partition on a module-only load, because the model checkpoint does not hold the partitioned weights.
  • ZeRO-3 and BF16_Optimizer.load_state_dict(..., load_from_fp32_weights=False) now rebuild the masters from the bit16 weights, matching ZeRO stage 1 and 2. DeepSpeedEngine.load_checkpoint passes true, so a normal resume keeps the saved masters. zero_optimization.load_from_fp32_weights stays deprecated and ignored.
  • Review fixes: a pipeline-serialized load now checks that ZeRO shards exist before waiting on the previous rank, so a missing shard raises instead of leaving ranks blocked in dist.recv. A universal load that skips optimizer state keeps optim_fragment, so safe_get_full_optimizer_state and safe_set_full_optimizer_state still work. A leftover debug print in BF16_Optimizer is removed.

AI assistance was used to implement and test this change. This does not duplicate an open DeepSpeed PR.

Test plan

  • CPU, torch 2.9.1+cu130, Python 3.12.12, Intel Xeon Platinum 8488C, gloo, world size 1, tests/unit/checkpoint/test_fp32_master_only.py and tests/unit/checkpoint/test_fp32_master_stage3_bf16.py: 10 passed. Both files ran on the tree that became a22f0cc4.
    • The dedicated BF16 optimizer keeps the saved masters when optimizer state is skipped and rebuilds them for load_module_only=True. ZeRO-3 keeps the saved masters for both of those loads. Adam moments stay fresh.
    • A direct load_state_dict(..., load_from_fp32_weights=False) after a module-only load rebuilds the masters from the bit16 weights, for both BF16 and ZeRO-3.
    • Optimizer globals (clip_grad, overflow, dynamic_loss_scale) are not restored on a masters-only load.
    • A universal masters-only load into a stepped engine keeps safe_get_full_optimizer_state and safe_set_full_optimizer_state working.
    • A pipeline-serialized load with missing shards raises before dist.recv. The NVMe masters-only copy restores only the fp32 swap file.
  • 4×H200, torch 2.9.1+cu130, Python 3.12.12, same two files on tree a22f0cc4: 10 passed in 52s. This includes the three data-parallel change tests (universal, legacy, elastic), which spawn 2 ranks on cuda:0/cuda:1. The Keep fp32 masters on ZeRO-1 and ZeRO-2 when a resume skips optimizer state #8891 suite there does not cover these two optimizers.

Validated cells: dedicated ZeRO-1 BF16 optimizer and ZeRO-3, same data-parallel size, legacy checkpoint, bf16, no offload. ZeRO-1/2 universal masters-only load covered by the fragment test. Open cells: fp16, MoE, real NVMe offload (the NVMe test uses a stub swapper), and a data-parallel size change.

sfc-gh-truwase and others added 2 commits October 22, 2026 21:29
…state.

load_optimizer_states=False skipped the ZeRO shard, so a fresh optimizer rebuilt the fp32 masters from bf16/fp16. Stage 1 and 2 now restore the saved masters without Adam moments. ZeRO-3 and the dedicated ZeRO-1 BF16 optimizer stay on the previous path.

Signed-off-by: Olatunji Ruwase <[email protected]>
Co-authored-by: Cursor <[email protected]>
Extends the stage 1/2 resume path so these optimizers also keep saved fp32 masters when optimizer state is skipped. A non-MoE data-parallel change still rebuilds the masters; ZeRO-3 MoE still loads its shard.

Signed-off-by: Olatunji Ruwase <[email protected]>
Co-authored-by: Cursor <[email protected]>
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 22, 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-22T21:48:10.727488Z bb31f40 PR opened
ℹ️ 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: bb31f4039f

ℹ️ 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".

Comment thread deepspeed/runtime/engine.py Outdated
"cannot be restored and are being rebuilt from the bit16 weights, losing precision. "
"Convert the checkpoint with ds_to_universal.py and load it with "
"checkpoint.load_universal=true to keep them.")
return False

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 Notify serialized ranks before falling back

When pipeline_loading_checkpoint is enabled and a legacy non-MoE ZeRO-3 checkpoint is loaded at a different DP world size with load_optimizer_states=False and the default FP32-master setting, every nonzero local rank is already blocked in the earlier dist.recv while local rank 0 returns here. The only matching send is reached after the Stage-3 shard load, so this hangs instead of taking the advertised bit16 fallback; decide the fallback before entering serialized loading or release the waiting ranks.

AGENTS.md reference: AGENTS.md:L38-L38

Useful? React with 👍 / 👎.

Comment thread deepspeed/runtime/engine.py Outdated
autoep_zero3_partition_native_load = self.has_moe_layers and self.zero_optimization_partition_weights()
if ((load_optimizer_states and not load_module_only) or self.load_universal_checkpoint()
load_zero_optimizer_states = load_optimizer_states and not load_module_only
if (load_zero_optimizer_states or load_saved_fp32_masters or self.load_universal_checkpoint()

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 Keep optimizer globals out of master-only loads

When load_optimizer_states=False and FP32 masters are requested (the new default path), this operand now sends a normal legacy load through _load_zero_checkpoint. The Stage 1/2 loader then always calls _load_global_state, Stage 3 always assigns loss-scaler/dynamic-scale/overflow, and BF16 always assigns clip_grad before their optimizer-state guards, so a fresh-optimizer warm start silently inherits optimizer controls and can even raise when checkpoint clipping conflicts with compute_grad_norm=False; gate those global assignments while loading only masters.

AGENTS.md reference: AGENTS.md:L19-L19

Useful? React with 👍 / 👎.

Comment thread deepspeed/runtime/engine.py Outdated
# load_module_only restores the model and rebuilds the masters from it.
if load_fp32_weights is None:
load_fp32_weights = self.zero_load_from_fp32_weights()
load_saved_fp32_masters = load_fp32_weights and not load_module_only

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 Honor the FP32 override with NVMe optimizer offload

When ZeRO-3 optimizer offload uses NVMe (swap_optimizer=True), the following branch skips _load_zero_checkpoint, while the later NVMe block unconditionally copies all saved swap files and reset_swap_buffers() swaps the saved FP32 parameters back into the bit16 partitions. Thus the newly documented load_fp32_weights=False override (and its forced-false module-only case) is ignored and can also restore saved moments despite load_optimizer_states=False; handle/filter the NVMe copy or explicitly reject this combination.

AGENTS.md reference: AGENTS.md:L38-L38

Useful? React with 👍 / 👎.

Comment on lines +247 to +248
if not load_optimizer_states:
hp_keys = [key for key in hp_keys if key == FP32_WEIGHT_KEY]

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 Preserve optimizer fragments on FP32-only loads

When a universal checkpoint is loaded with load_optimizer_states=False into a ZeRO-1/2 or BF16 engine that has already stepped, load_hp_checkpoint_state first replaces every optim_fragment with {}, this new filter prevents repopulating it, and the base loader skips relinking while _hp_optimizer_states_linked remains true. The underlying optimizer state remains present, but safe_get_full_optimizer_state and safe_set_full_optimizer_state then raise <key> not found; preserve the old mappings for an FP32-only load or relink the untouched state.

AGENTS.md reference: AGENTS.md:L19-L19

Useful? React with 👍 / 👎.

sfc-gh-truwase and others added 3 commits October 22, 2026 21:48
A full load no longer rebuilds masters from bf16, ZeRO-3 no longer gathers the whole model, and elastic ZeRO-1/2 checkpoints can repartition those masters across a new DP size when optimizer state is not loaded.

Signed-off-by: Olatunji Ruwase <[email protected]>
Co-authored-by: Cursor <[email protected]>
sfc-gh-truwase and others added 2 commits October 24, 2026 13:47
A ZeRO-1/2 load used to skip a missing fp32.pt and then copy the initialized master over the loaded weights. ZeRO-3 raised FileNotFoundError for the same gap.

Signed-off-by: Olatunji Ruwase <[email protected]>
Co-authored-by: Cursor <[email protected]>
sfc-gh-truwase and others added 2 commits October 26, 2026 23:23
…-up.

load_checkpoint still always restores saved fp32 masters. ZeRO-3 and the dedicated ZeRO-1 BF16 optimizer now rebuild those masters when load_from_fp32_weights is false, matching stage 1 and 2.

Signed-off-by: Olatunji Ruwase <[email protected]>
Co-authored-by: Cursor <[email protected]>
banxingmjj pushed a commit to openanolis/DeepSpeed that referenced this pull request Oct 27, 2026
…state (deepspeedai#8891)

## Summary
- `load_optimizer_states=False` used to skip the ZeRO shard, so a fresh
optimizer rebuilt the fp32 master weights from the bf16/fp16 parameters
and dropped the precision saved in `SINGLE_PARTITION_OF_FP32_GROUPS` or
universal `fp32.pt`.
- `DeepSpeedEngine.load_checkpoint` no longer accepts
`load_fp32_weights`. `zero_optimization.load_from_fp32_weights` is
deprecated and ignored. A full ZeRO load always restores the saved fp32
masters. `load_optimizer_states=False` with `load_module_only=False`
restores those masters and starts Adam with fresh moments.
`load_module_only=True` rebuilds ZeRO-1 and ZeRO-2 masters from the
loaded model weights. Universal module-only loads read those model
weights from `fp32.pt` first. ZeRO-3 still reads its fp32 partition,
because the model checkpoint does not hold the partitioned weights.
- A data-parallel size change that requests optimizer state, and a rigid
ZeRO-1/2 checkpoint, raise `ZeRORuntimeException`. An elastic ZeRO-1/2
checkpoint can repartition fp32 masters when optimizer state is not
loaded. Universal checkpoints keep the masters across a DP size change.
ZeRO-3 still rejects a DP size change.
- A legacy checkpoint with no `*_optim_states.pt` files, and a universal
folder with no `fp32.pt`, raise `ZeRORuntimeException` on any load that
needs the masters. ZeRO-1/2 `load_module_only=True` still succeeds
without the shard. A `parameter_alignment` mismatch raises on a full
load and on a masters-only load. Module-only remains the warm start for
that mismatch.
- Pytest 8 registers each `DistributedFixture` subclass, so a test skips
when the machine has fewer GPUs than the fixture world size.
- Further ZeRO-3 and dedicated ZeRO-1 BF16 work is in deepspeedai#8892, stacked on
this branch. Follow-ups that do not fail the current unit tests,
including ZeRO-3 NVMe `load_module_only=True`, are tracked in deepspeedai#8890.

## Load decision tree

`zero_optimization.load_from_fp32_weights` is ignored. When a universal
load has `load_optimizer_states=False`,
`load_hp_checkpoint_state_from_checkpoint_dir` reads `fp32.pt` and
returns. It does not open `optimizer_state.pt`, and it does not fill
Adam steps or moments.

```mermaid
flowchart TD
  start["ZeRO checkpoint was found"] --> module{"load_module_only"}
  module -->|"True, legacy ZeRO-1 or ZeRO-2"| rebuild["Skip the shard. Rebuild masters from the loaded model weights. Moments stay fresh."]
  module -->|"True, universal or ZeRO-3"| open["Open the shard"]
  module -->|False| open
  open --> shards{"Legacy shard files present, or the checkpoint is universal"}
  shards -->|"Legacy files missing"| raiseMissing["ZeRORuntimeException: saved fp32 weights are required"]
  shards -->|present| form{"Which checkpoint"}
  form -->|"Legacy ZeRO-1 or ZeRO-2"| legacy12["Restore the saved fp32 masters. Load Adam moments only when requested."]
  form -->|"Universal ZeRO-1, ZeRO-2, or BF16"| uniMoments{"load_optimizer_states"}
  uniMoments -->|yes| uniFull["Read fp32.pt, the moments, and optimizer_state.pt. A missing fp32.pt raises."]
  uniMoments -->|no| readFp32["Read fp32.pt and return. A missing fp32.pt raises."]
  readFp32 --> round{"load_module_only"}
  round -->|no| keep["Copy the masters onto the model weights. The masters keep the saved precision. Moments stay fresh."]
  round -->|yes| rounded["Copy the masters onto the model weights, then rebuild the masters from those weights. Moments stay fresh."]
  form -->|"Legacy ZeRO-3"| z3["Copy the saved fp32 partition into the masters and then into fp16. Load moments only when requested."]
  form -->|"Universal ZeRO-3"| z3Moments{"load_optimizer_states"}
  z3Moments -->|no| z3Masters["Read fp32.pt. A missing file raises."]
  z3Moments -->|yes| z3Full["Read fp32.pt, exp_avg.pt, and exp_avg_sq.pt. A missing file raises."]
```

A `parameter_alignment` mismatch raises on every legacy ZeRO-1/2 shard
load. Module-only never opens that shard, so it remains the warm start.

AI assistance was used to implement and test this change. This does not
duplicate an open DeepSpeed PR.

## Test plan
- [x] `tests/unit/checkpoint/test_fp32_master_only.py`,
`tests/unit/checkpoint/test_zero_optimizer.py`, and
`TestStage12ParamAlignment` on 4× NVIDIA H200 (driver 580.159.03), torch
2.9.1+cu130, Python 3.12.12, pytest 8.4.1, commit `894a2b72`: 99 passed.
Legacy and universal loads keep the saved masters and drop moments.
Module-only rebuilds ZeRO-2 masters from bf16. A missing legacy shard
raises `ZeRORuntimeException`, and module-only still loads. A legacy DP
change from 2 to 1 raises. A universal DP change keeps the masters. An
elastic DP change repartitions the masters and drops moments. A
parameter-alignment mismatch raises for a masters-only load and a full
load, and the module-only warm start matches the saved parameters. The
world-size-4 elastic DP cases and both ZeRO++ loads passed.
- [x] `TestUnevenVocabCrossTpResume::test_resume_from_tp2` on the same
machine: 2 passed.
- [x] The eight elastic DP cases and both ZeRO++ cases skip when one
device is visible: `4 required, 1 available`.
- [ ] Still open: fp16, MoE, and NVMe offload, including ZeRO-3
`load_module_only=True` with NVMe optimizer offload. See deepspeedai#8890.

Validated cells: ZeRO stages 1, 2, and the ZeRO-3 paths in
`test_zero_optimizer.py`; same DP and DP 2 to 1; legacy, elastic, and
universal checkpoints; bf16; no offload. Open cells: fp16, MoE, NVMe
offload.

---------

Signed-off-by: Olatunji Ruwase <[email protected]>
Co-authored-by: Cursor <[email protected]>

@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.

Read at b190a3f7. #8891 has landed, so against current master the change is the two load_from_fp32_weights=False branches (BF16_Optimizer._load_legacy_checkpoint and ZeRO-3's _rigid_load_state_dict / universal load) plus the new test. Merging master would shrink the diff to those three files. It merges cleanly with master.

The branches look right to me, but the new test doesn't reach them. DeepSpeedEngine.load_checkpoint always passes load_from_fp32_weights=True, and the test only loads through the engine. I ran a copy of test_fp32_master_stage3_bf16.py on CPU (gloo) with a client torch.optim.Adam, since DeepSpeed's fused Adam can't build on my machine. It passes on this branch and also on master without it.

Calling the optimizer directly does show the change. After a module-only load, I nudged the masters and then called engine.optimizer.load_state_dict(sd_list, load_optimizer_states=False, load_from_fp32_weights=False):

  • On this branch, both the BF16 optimizer and ZeRO-3 end with the saved masters rounded to bf16, i.e. rebuilt from the bit16 weights.
  • On master, the BF16 optimizer keeps the stale nudged masters, and ZeRO-3 keeps the unrounded saved masters.

A test along those lines would pin the new behaviour.

Minor: ZeRO-3's universal load honours False only with optimizer states. Without them, it calls load_module_checkpoint_state_from_checkpoint_dir_stage3(checkpoint_folder, True). The BF16 and ZeRO-1/2 universal loads ignore the flag. That path isn't reachable from the engine today, so it may not matter.

Comment thread deepspeed/runtime/bf16_optimizer.py Resolved
sfc-gh-truwase added a commit to sfc-gh-truwase/DeepSpeed that referenced this pull request Nov 5, 2026
…universal fragments

- Check that ZeRO shards exist before a pipeline-serialized load waits on
  the previous rank, so a missing-shard error cannot leave other ranks
  blocked in dist.recv.
- Keep optim_fragment when a universal load skips optimizer state, so
  safe_get/set_full_optimizer_state still work after a masters-only load.
- Cover that optimizer globals (clip_grad, overflow, dynamic loss scale)
  are not restored on a masters-only load, for ZeRO-3 and BF16.
- Cover the NVMe masters-only copy: only the fp32 swap file is restored.
- Exercise the BF16/ZeRO load_from_fp32_weights=False rebuild path through
  a direct load_state_dict after a module-only load.
- Remove a leftover debug print in BF16_Optimizer legacy load.

Co-authored-by: Cursor <[email protected]>
@sfc-gh-truwase
sfc-gh-truwase requested a review from stas00 November 5, 2026 21:40
…universal fragments

- Check that ZeRO shards exist before a pipeline-serialized load waits on
  the previous rank, so a missing-shard error cannot leave other ranks
  blocked in dist.recv.
- Keep optim_fragment when a universal load skips optimizer state, so
  safe_get/set_full_optimizer_state still work after a masters-only load.
- Cover that optimizer globals (clip_grad, overflow, dynamic loss scale)
  are not restored on a masters-only load, for ZeRO-3 and BF16.
- Cover the NVMe masters-only copy: only the fp32 swap file is restored.
- Exercise the BF16/ZeRO load_from_fp32_weights=False rebuild path through
  a direct load_state_dict after a module-only load.
- Remove a leftover debug print in BF16_Optimizer legacy load.

Co-authored-by: Cursor <[email protected]>
Signed-off-by: Olatunji Ruwase <[email protected]>
@sfc-gh-truwase
sfc-gh-truwase force-pushed the load-fp32-masters-stage3-bf16 branch from 2b5e291 to a22f0cc Compare November 5, 2026 21:41
banxingmjj pushed a commit to openanolis/DeepSpeed that referenced this pull request Nov 5, 2026
… has the master dtype (deepspeedai#8842)

# 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`. deepspeedai#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 c6291b7 + 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 c6291b7:
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).

---------

Signed-off-by: pengdurice <[email protected]>
@sfc-gh-truwase

Copy link
Copy Markdown
Collaborator Author

@0z5a, I have noticed your feedback on a number of PRs. While your interest is appreciated, these comments can be confusing to contributors who spend efforts addressing non-maintainer feedback. If you would like to become a maintainer please consult the PyTorch Foundation Governance for the process. Thanks.

@sfc-gh-truwase
sfc-gh-truwase added this pull request to the merge queue Nov 6, 2026
Merged via the queue into deepspeedai:master with commit 8af59b2 Nov 6, 2026
15 checks passed
@sfc-gh-truwase
sfc-gh-truwase deleted the load-fp32-masters-stage3-bf16 branch November 6, 2026 12:10
@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
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.

2 participants