Skip to content

ZeRO-1/2, BF16 optimizer: do not keep parameters' AccumulateGrad nodes alive from fragment mappings - #9135

Draft
seanbell wants to merge 1 commit into
deepspeedai:masterfrom
seanbell:fragment-view-no-autograd
Draft

seanbell wants to merge 1 commit into
deepspeedai:masterfrom
seanbell:fragment-view-no-autograd

Conversation

@seanbell

@seanbell seanbell commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor

Build the low-precision fragment view in get_hp_fragment_mapping from lp_param.detach(), so the mapping keeps the
parameter's storage but not its autograd history. Today the view holds the parameter's AccumulateGrad node alive for
as long as the mapping lives, which pins the gradient hooks of every parameter a rank holds a fragment of to the CUDA
stream that was current when the mapping was built. One changed line and one comment line.

Draft. This change, its tests and this description were written with an AI agent (Claude). No human has yet
reviewed every changed line, so the commit carries no Signed-off-by: that attestation belongs to the person who
reviews the change and takes it over. The accelerator test below is written and has not run (no accelerator was
available). The PR stays a draft until a reviewer has read every line and run that test on a device. Maintainers are
welcome to push to this branch or to take the change over.

Problem

Line numbers are for master adcabcf9.

get_hp_fragment_mapping (deepspeed/utils/tensor_fragment.py:394) builds

lp_fragment_tensor = lp_param.flatten().narrow(0, lp_frag_address.start, lp_frag_address.numel)

with grad mode on. Because lp_param requires grad, the view has a grad_fn whose next edge is the parameter's
AccumulateGrad node, and the mapping (lp_param._hp_mapping) keeps that node alive. ZeRO-1/2 (stage_1_and_2.py:855)
and the BF16 optimizer (bf16_optimizer.py:348) build these mappings at initialization and rebuild them whenever
_link_all_hp_params runs again (checkpoint loads and state reloads, stage_1_and_2.py:3920, :4094, :4114), so the
node lives for the whole run.

PyTorch records the current stream when it creates an AccumulateGrad node and runs that node, and the parameter's
post-accumulate-grad hooks, on that stream in every backward that reuses the node. A node that is released at the end
of each iteration is recreated in the next forward on whatever stream is current then. A node that is kept alive is
not. So if the current stream at deepspeed.initialize (or at a checkpoint load) differs from the stream later
forwards and backwards run on, the hooks of the parameters this rank holds a fragment of keep running on the old
stream while all other hooks run on the new one, and PyTorch warns:

The AccumulateGrad node's stream does not match the stream of the node that produced the incoming gradient. ...
This mismatch is caused by an AccumulateGrad node created prior to the current iteration being kept alive.

In ZeRO-1/2 those two groups of hooks fill and flush one shared gradient bucket, so the split puts bucket accesses on
two streams; the extra cross-stream wait PyTorch inserts for every kept-alive node is a cost even where nothing races.
Any library or user code that changes the thread's current stream after deepspeed.initialize (or after a load)
triggers this.

Change

-    lp_fragment_tensor = lp_param.flatten().narrow(0, lp_frag_address.start, lp_frag_address.numel)
+    # Detached: autograd history here would keep the parameter's AccumulateGrad node, and its stream, alive.
+    lp_fragment_tensor = lp_param.detach().flatten().narrow(0, lp_frag_address.start, lp_frag_address.numel)

Nothing needs the view's autograd history: the mapping reads and writes lp_fragment only through .data
(update_hp, update_lp, tensor_fragment.py:30-34), and every other reader uses lp_fragment_address. The detached
view shares the parameter's storage, so update_lp still writes the parameter. Hooks registered with
register_post_accumulate_grad_hook (what register_grad_hook uses on torch >= 2.1) are stored on the tensor and
read by whichever AccumulateGrad node runs, so recreating the node each iteration does not lose them.

Not changed:

  • The fp32 master view (hp_fragment) also has autograd history, but its leaf (single_partition_of_fp32_groups,
    fp32_groups_flat_partition) receives its gradient by assignment and is never reached by a backward, so the node it
    retains never runs. Detaching it would change zero_optimizer_storage_shard(param).requires_grad for no behavior.
  • On torch < 2.1, register_grad_hook registers on an AccumulateGrad node obtained through expand_as. ZeRO-1/2
    registers its hooks (stage_1_and_2.py:724) before it links the fragments (:752), and the mapping did not keep that
    earlier node alive either, so this path is unaffected (by reading; torch 2.0 not run).
  • ZeRO-3 does not use these mappings.

This removes one way gradient hooks reach two streams. It does not order the gradient bucket when hooks run on
several streams for other reasons (for example #8061); that is #9133.

Tests

In tests/unit/runtime/zero/test_zero_tensor_fragment.py:

  • test_fragment_mapping_does_not_keep_the_gradient_accumulator_alive (CPU). After link_hp_params, two
    iterations each tag the AccumulateGrad node they use (torch.autograd.graph.get_gradient_edge(param).node). The test
    fails if the second iteration reuses the first one's node. On master: assert [False, True] == [False, False] (the
    node created at link time is reused). Passes with this change.
  • test_gradient_hook_runs_on_the_backward_stream_after_linking (accelerators with streams; skipped where
    resolves_data_dependency() is true, including CPU). Link on the default stream, then run a backward under another
    stream; the test checks that the post-accumulate-grad hook ran on that stream. Written, not executed. Expected on
    master: the hook runs on the default stream.

Validation

Hardware: CPU only (x86_64, Intel Xeon Platinum 8375C; no accelerator). Python 3.12, torch 2.15.0+cpu, pytest 8.4.2,
pytest-forked 1.7.5, DeepSpeed's requirements/requirements.txt installed.

pytest --forked tests/unit/runtime/zero/test_zero_tensor_fragment.py -k "accumulator_alive or backward_stream_after_linking or owned_fragment"
  this branch:                    3 passed, 1 skipped (the accelerator test)
  master (adcabcf9), new tests:   1 failed (test_fragment_mapping_does_not_keep_the_gradient_accumulator_alive), 2 passed, 1 skipped
pytest --forked tests/unit/v1/zero/test_zero2_gradient_safety.py
  this branch:                    56 passed, 2 skipped (includes the two-rank CPU training test)
pytest --forked tests/unit/runtime/zero/test_zero_tensor_fragment.py -k "(none-1- or none-2- or cpu-2-) and not local or bf16_optimizer or Fp32GradAccum"
  this branch:                    36 passed, 17 skipped (ZeRO-1/2 get/set/update and fp32 accumulation on 2 CPU ranks;
                                  the BF16 optimizer cases skip on the CPU accelerator)
pre-commit run --files deepspeed/utils/tensor_fragment.py tests/unit/runtime/zero/test_zero_tensor_fragment.py
  all hooks passed

Re-run on the same head with DS_ACCELERATOR=cpu, torch 2.15.0+cpu and pytest 9.2.0 (without --forked): the same
counts for all three commands. The new CPU test fails the same way on master f1d37eb2, and the branch merges that
master without conflict; the first command gives the same result on the merge.

Not measured: throughput and memory on a device. The change adds no work; it removes the cross-stream wait described
above. CI: the CPU test runs in the CPU workflow; the accelerator test is outside tests/unit/v1, which the PR-level GPU
test selection covers, so on a GPU it runs only in the nightly full run after merge or when run by hand.

Compatibility matrix:

axis cell status
optimizer ZeRO-1/2 (link_hp_params from stage_1_and_2.py) CPU tests; the two-rank CPU training test in test_zero2_gradient_safety.py passes
optimizer BF16 optimizer (bf16_optimizer.py) same factory; not separately run
optimizer ZeRO-3 not touched
checkpoint relink at load (_link_all_hp_params) same factory; no checkpoint format change
torch >= 2.1 (register_post_accumulate_grad_hook) CPU test
torch 2.0 (node hook fallback) unaffected by reading; not run
accelerators CUDA and others with streams accelerator test written, not run

No config key, public API or checkpoint content changes.

Related work and duplicate check

Searched open and closed issues and PRs for "AccumulateGrad", "AccumulateGrad stream", "kept alive", "stream
mismatch", "lp_fragment detach", "tensor_fragment detach" and "hp_mapping autograd": nothing reports or changes this.
#9133 orders the ZeRO-1/2 gradient bucket across streams whatever splits the hooks; the two changes are independent
and either can land first.

AI assistance (Claude) was used to write this change, its tests and this description.

🤖 Generated with Claude Code

…ings

get_hp_fragment_mapping builds lp_fragment as lp_param.flatten().narrow(...)
with grad mode on, so the view's autograd history holds the parameter's
AccumulateGrad node for as long as the mapping lives: the whole run for
ZeRO-1/2 and the BF16 optimizer, renewed at every checkpoint load that
relinks. PyTorch records the current stream when it creates that node and
runs the parameter's gradient hooks on that stream in every later backward.
When the current stream at initialize (or at a load) differs from the one
later backwards run on, the hooks of the parameters this rank holds a
fragment of run on the old stream and all other hooks on the new one, and
PyTorch warns that an AccumulateGrad node created prior to the current
iteration is being kept alive. In ZeRO-1/2 those hooks share one gradient
bucket.

The mapping only reads and writes lp_fragment.data (update_hp, update_lp);
every other reader uses lp_fragment_address. Build the view from
lp_param.detach(): the same storage, no autograd history. Hooks registered
with register_post_accumulate_grad_hook are stored on the tensor and read
by whichever AccumulateGrad node runs, so they are unaffected.

The fp32 master view (hp_fragment) is left as it is: its leaf receives its
gradient by assignment and is never reached by a backward, so the node it
retains never runs.

Tests:
- CPU: after link_hp_params, the next iteration does not reuse the
  AccumulateGrad node of the previous one (fails before this change: the
  node created at link time is reused).
- Accelerators with streams: a backward run under another stream after
  linking runs the gradient hook on that stream (expected to fail before
  this change; written, not run).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

This branch has not been deployed

No deployments
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.

1 participant