Repository navigation
ZeRO-1/2, BF16 optimizer: do not keep parameters' AccumulateGrad nodes alive from fragment mappings - #9135
Draft
seanbell wants to merge 1 commit into
Draft
ZeRO-1/2, BF16 optimizer: do not keep parameters' AccumulateGrad nodes alive from fragment mappings#9135seanbell wants to merge 1 commit into
seanbell wants to merge 1 commit into
Conversation
…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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Build the low-precision fragment view in
get_hp_fragment_mappingfromlp_param.detach(), so the mapping keeps theparameter'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.
Problem
Line numbers are for
masteradcabcf9.get_hp_fragment_mapping(deepspeed/utils/tensor_fragment.py:394) buildswith grad mode on. Because
lp_paramrequires grad, the view has agrad_fnwhose next edge is the parameter'sAccumulateGrad 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_paramsruns again (checkpoint loads and state reloads,stage_1_and_2.py:3920,:4094,:4114), so thenode 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 laterforwards 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:
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
Nothing needs the view's autograd history: the mapping reads and writes
lp_fragmentonly through.data(
update_hp,update_lp,tensor_fragment.py:30-34), and every other reader useslp_fragment_address. The detachedview shares the parameter's storage, so
update_lpstill writes the parameter. Hooks registered withregister_post_accumulate_grad_hook(whatregister_grad_hookuses on torch >= 2.1) are stored on the tensor andread by whichever AccumulateGrad node runs, so recreating the node each iteration does not lose them.
Not changed:
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 itretains never runs. Detaching it would change
zero_optimizer_storage_shard(param).requires_gradfor no behavior.register_grad_hookregisters on an AccumulateGrad node obtained throughexpand_as. ZeRO-1/2registers its hooks (
stage_1_and_2.py:724) before it links the fragments (:752), and the mapping did not keep thatearlier node alive either, so this path is unaffected (by reading; torch 2.0 not run).
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). Afterlink_hp_params, twoiterations each tag the AccumulateGrad node they use (
torch.autograd.graph.get_gradient_edge(param).node). The testfails if the second iteration reuses the first one's node. On
master:assert [False, True] == [False, False](thenode created at link time is reused). Passes with this change.
test_gradient_hook_runs_on_the_backward_stream_after_linking(accelerators with streams; skipped whereresolves_data_dependency()is true, including CPU). Link on the default stream, then run a backward under anotherstream; 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.txtinstalled.Compatibility matrix:
link_hp_paramsfromstage_1_and_2.py)test_zero2_gradient_safety.pypassesbf16_optimizer.py)_link_all_hp_params)register_post_accumulate_grad_hook)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