From 7f13552888563f6ccecdcf829c44efe6e9fa4daa Mon Sep 17 00:00:00 2001 From: Sean Bell <1844189+seanbell@users.noreply.github.com> Date: Fri, 20 Nov 2026 09:09:47 +0000 Subject: [PATCH] Do not keep parameters' AccumulateGrad nodes alive from fragment mappings 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 --- deepspeed/utils/tensor_fragment.py | 3 +- .../runtime/zero/test_zero_tensor_fragment.py | 42 +++++++++++++++++++ 2 files changed, 44 insertions(+), 1 deletion(-) diff --git a/deepspeed/utils/tensor_fragment.py b/deepspeed/utils/tensor_fragment.py index 296517ea44a2..49c15901f562 100644 --- a/deepspeed/utils/tensor_fragment.py +++ b/deepspeed/utils/tensor_fragment.py @@ -391,7 +391,8 @@ def get_hp_fragment_mapping(lp_param, lp_start, flat_hp_partition, gradient_dict hp_fragment_tensor = flat_hp_partition.narrow(0, hp_frag_address.start, hp_frag_address.numel) lp_frag_address = fragment_address(start=fragment_start - lp_start, numel=fragment_numel) - 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) return tensor_fragment(lp_fragment=lp_fragment_tensor, lp_fragment_address=lp_frag_address, diff --git a/tests/unit/runtime/zero/test_zero_tensor_fragment.py b/tests/unit/runtime/zero/test_zero_tensor_fragment.py index 83c42cdad3bf..edb8d9d46882 100644 --- a/tests/unit/runtime/zero/test_zero_tensor_fragment.py +++ b/tests/unit/runtime/zero/test_zero_tensor_fragment.py @@ -58,6 +58,48 @@ def sum_peer_fragment(tensor, *, group, _peer=peer_contribution): torch.testing.assert_close(actual, reference, rtol=0, atol=0) +def _link_first_half(param): + link_hp_params(lp_param_list=[param], + flat_hp_partition=torch.zeros(2, device=param.device), + gradient_dict={}, + offload_gradient_dict={}, + use_offload=False, + param_group_index=0, + partition_start=0, + partition_size=2, + dp_group=object()) + + +def test_fragment_mapping_does_not_keep_the_gradient_accumulator_alive(): + # Autograd runs a parameter's gradient hooks on the stream that was current when its AccumulateGrad node + # was created. A mapping that kept the node alive would pin every later backward to the stream of link time. + param = torch.nn.Parameter(torch.zeros(4)) + _link_first_half(param) + reused = [] + for _ in range(2): + loss = (param * 2).sum() + node = torch.autograd.graph.get_gradient_edge(param).node + reused.append("from_earlier_iteration" in node.metadata) + node.metadata["from_earlier_iteration"] = True + loss.backward() + del loss, node + assert reused == [False, False] + + +@pytest.mark.skipif(get_accelerator().resolves_data_dependency() or not get_accelerator().is_available(), + reason="Requires an accelerator with streams") +def test_gradient_hook_runs_on_the_backward_stream_after_linking(): + accelerator = get_accelerator() + param = torch.nn.Parameter(torch.zeros(4, device=accelerator.device_name())) + _link_first_half(param) + hook_streams = [] + param.register_post_accumulate_grad_hook(lambda _: hook_streams.append(accelerator.current_stream())) + stream = accelerator.Stream() + with accelerator.stream(stream): + (param * 2).sum().backward() + assert hook_streams == [stream] + + def validate_tensor(model, api_type, opt_states): assert api_type in ["full", "local"] for _, lp in model.named_parameters():