Skip to content

ZeRO-1/2: fix offload_states() keeping the optimizer state on the device - #9016

Merged
xylian86 merged 4 commits into
deepspeedai:masterfrom
xylian86:xinyu/zero12-offload-states-optim-fragments
Nov 19, 2026
Merged

xylian86 merged 4 commits into
deepspeedai:masterfrom
xylian86:xinyu/zero12-offload-states-optim-fragments

Conversation

@xylian86

@xylian86 xylian86 commented Nov 4, 2026

Copy link
Copy Markdown
Collaborator

Summary

ZeRO-1/2 links each parameter's optimizer-state fragment (_hp_mapping.optim_fragment, which safe_get_full_optimizer_state() and safe_set_full_optimizer_state() use) once, after the first step, as narrow() views of the optimizer state. offload_states() and reload_states() replace the state tensors but never link them again:

  1. offload_states(include=[optim_states]) frees none of the device copy of the state, because the views keep it alive. reload_states() then adds a second device copy, and the fragments keep pointing at the old one, so the getters return values from before the offload.
  2. Reloading hp_params or lp_params, also with the default include=None, rebuilds the fragments through _link_all_hp_params() without the optimizer state, so from then on the getters raise TypeError: argument of type 'NoneType' is not iterable.

This PR drops the fragments' views before the state is offloaded and links the state into the fragments again at the end of reload_states(). Before the first step there is no state yet, and step() links it as before.

Fixes

Before → after, 2 GH200, ZeRO-1 and ZeRO-2, bf16, FusedAdam, 33.6M parameters (128 MiB of Adam state per rank), base a38957c17:

  1. offload_states(include=[optim_states]): 0 → 128 MiB freed; device memory after reload_states() 448.1 → 320.1 MiB (as before the offload); one step later the fragments were up to 2.5e-4 off the optimizer state → equal.
  2. include=[hp_params], [lp_params] or all states: TypeError from the getters after reload_states() → they return the current state.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 4, 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-11-04T22:38:34.086477Z 0e8dbff 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.

Copilot AI 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.

🟡 Changes recommended

With elastic checkpointing, calling state_dict() before the first step can cause an offload/reload cycle to mark empty optimizer-state fragments as linked, leaving Adam moments unlinked and causing subsequent safe_get_full_optimizer_state() calls to raise ValueError.

1 open issue
What changed in this PR

This PR fixes ZeRO-1/2 optimizer-state fragment references across offload/reload cycles, allowing device memory to be released and state accessors to read current optimizer values.

Changes:

  • Clear optimizer-state fragment views before offloading.
  • Relink fragments after reloading optimizer states or parameter buffers.
  • Add two-rank regression tests for memory release and fragment correctness across ZeRO stages 1 and 2.
File Description
tests/​unit/​v1/​zero/​test_offload_states.py Adds offload/reload tests comparing optimizer fragments with a reference run.
deepspeed/​runtime/​zero/​stage_1_and_2.py Clears stale fragment views and restores optimizer-state links after reload.

Review effort: Balanced

Comment thread deepspeed/runtime/zero/stage_1_and_2.py Resolved
@xylian86
xylian86 force-pushed the xinyu/zero12-offload-states-optim-fragments branch 2 times, most recently from b6b3149 to b174689 Compare November 5, 2026 19:49
@xylian86
xylian86 enabled auto-merge November 7, 2026 08:11
@tohtana tohtana added needs-gpu-test GPU testing is recommended to validate the changes in this PR. and removed needs-gpu-test GPU testing is recommended to validate the changes in this PR. labels Nov 10, 2026
@pengdurice

Copy link
Copy Markdown
Contributor

@xylian86 please sign off to fix the DCO.

xylian86 and others added 3 commits November 19, 2026 19:16
…on reload

Each parameter's optimizer-state fragment holds narrow() views of the
optimizer state, linked once after the first step. offload_states() with
optim_states therefore freed none of the device copy of the state (the views
kept it alive), reload_states() added a second device copy, and the fragments
kept pointing at the old tensors, so the optimizer-state getters returned
values from before the offload. Reloading hp_params or lp_params rebuilds the
fragments without the optimizer state, after which the getters raised
TypeError.

offload_states() now drops the fragments' views before it moves the state,
and reload_states() links the state into the fragments again. Before the
first step there is no state yet, and step() links it as before.

Signed-off-by: Xinyu Lian <lian7@illinois.edu>
…ntil optimizer state is initialized'

Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
Signed-off-by: Xinyu Lian <lian7@illinois.edu>
With elastic checkpointing, state_dict() before the first step adds an
empty optimizer state per group. reload_states() linked that empty
state, so the first step did not link the Adam moments and
get_optim_state_fragment() raised ValueError; 5bceb1c links
the state only when it is not empty. Test this case and update the
docstring.

Signed-off-by: Xinyu Lian <lian7@illinois.edu>
@xylian86
xylian86 force-pushed the xinyu/zero12-offload-states-optim-fragments branch from 44f64d3 to e27f82b Compare November 19, 2026 19:16
@xylian86
xylian86 added this pull request to the merge queue Nov 19, 2026
Merged via the queue into deepspeedai:master with commit 40a9f40 Nov 19, 2026
19 checks passed
@xylian86
xylian86 deleted the xinyu/zero12-offload-states-optim-fragments branch November 19, 2026 20:39
banxingmjj pushed a commit to openanolis/DeepSpeed that referenced this pull request Nov 23, 2026
…eepspeedai#9148)

Fixes deepspeedai#9140 (nightly regression, modal-torch-latest full suite at
7681845).

## Root cause

PR deepspeedai#9016 (40a9f40) added a `_relink_hp_params_optimizer_state()` call
to the end of `DeepSpeedZeroOptimizer.reload_states()`, which now runs
whenever any of hp params / lp params / optim states is offloaded.
`tests/unit/v1/pin_memory/test_offload_route.py::test_reload_states_holds_pin_buffers_until_sync`
borrowed the **real** `reload_states` for a minimal fake optimizer that
only stubbed `_link_all_hp_params`, so reloading hp params raised:

```
AttributeError: '_FakeZeroOptimizer' object has no attribute '_relink_hp_params_optimizer_state'
```

and the nightly full suite failed on this file.

## Change

Test-only. Instead of adding another private-method stub to the fake
(which would break again on the next internal refactor of
`reload_states`), the test now exercises the contract on a real engine
through the public API:

- `_FakeZeroOptimizer` is removed; the test is now
`TestReloadStatesHoldsPinBuffers(DistributedTest)` (world size 1) on a
`SimpleModel` with ZeRO-2 and a client `torch.optim.Adam` (no FusedAdam
JIT dependency).
- With `DS_PIN_MEMORY_BACKEND=native`,
`engine.offload_states(include=[hp_params], pin_memory=True)` creates
pinned host buffers registered with the native pin manager.
- `engine.reload_states(non_blocking=True)` is run while recording, at
each `accelerator.synchronize()`, that those buffers are still
registered; after the call and `gc.collect()` the ranges must be
released.
- Skips when the native pin manager is unavailable or the accelerator is
CPU.

The pinned-buffer hold-until-sync contract under test is unchanged.

## Validation (on-device)

- Original fix-up (fake + stub), 8x NVIDIA H20, torch 2.9.1+cu129:
unpatched nightly commit -> 1 failed (the AttributeError above), 5
passed; patched -> 6 passed, `tests/unit/v1/pin_memory/` 50 passed, 1
skipped.
- Real-engine rewrite, NVIDIA L20 (1 GPU used):
  - `-k TestReloadStatesHoldsPinBuffers` -> 1 passed.
- Negative check: with
`pending_host_buffers.append(self.hp_params_pin_buffers)` removed from
`reload_states`, the test fails as expected.
- Note: the L20 GPUs are in `Exclusive_Process` compute mode, so running
the whole file there makes this `DistributedTest` subprocess hit "device
busy" after the module-level tests have initialized CUDA in the pytest
parent; the other 5 tests pass. This is a local-environment limitation,
not related to the change (CI uses default compute mode).
- pre-commit clean on the modified file.

AI assistance: GitHub Copilot was used to diagnose the regression and
prepare the change; the change was reviewed line-by-line and
re-validated on device as above.

---------

Signed-off-by: Jin, Youzhi <youzhi.jin@intel.com>
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.

5 participants