Megatron-LM icon indicating copy to clipboard operation
Megatron-LM copied to clipboard

[BUG] `StorageResizeBasedBucketAllocator.free` resizes gather storage to zero without `record_stream` (use-after-free race)

Open yuhezhang-ai opened this issue 4 months ago • 17 comments

Describe the bug

Package: megatron-fsdp (PyPI). Affected version: 0.5.0 (latest published release at time of writing). Upstream source: NVIDIA/Megatron-LM, megatron/core/distributed/fsdp/src/megatron_fsdp/param_and_grad_buffer.py. Symbol: StorageResizeBasedBucketAllocator.free. Location: param_and_grad_buffer.py, in the temporary-bucket release path.

There is intermittent, hard-to-reproduce numerical corruption and/or CUDA memory errors under overlapped parameter gather. It is nondeterministic: it depends on stream timing and CUDA caching-allocator reuse, so it manifests as occasional wrong results or sporadic illegal-memory-access rather than a clean, repeatable failure.

When a temporary all-gather bucket is released, its storage is resized to zero without first recording the current compute stream on the tensor:

if bucket_id in self.buckets:
    _free_storage(self.buckets[bucket_id].data)

Megatron-FSDP allocates these buckets on a dedicated parameter-gather stream, but they are consumed by TP/FSDP compute kernels on the compute stream. Freeing the storage (returning it to the CUDA caching allocator) without a record_stream(torch.cuda.current_stream()) on the consuming stream lets the allocator recycle the block for a new allocation while a still-in-flight compute kernel is reading a parameter view backed by it — a classic cross-stream use-after-free.

Steps/Code to reproduce bug

This is a timing race and is difficult to trigger deterministically. A practical approach:

  • Run Megatron-FSDP with overlap_param_gather enabled and a multi-stream parameter-gather path so buckets are allocated on the gather stream and consumed on the compute stream.
  • Add allocator pressure (many allocations/frees, or PYTORCH_NO_CUDA_MEMORY_CACHING=0 with tight memory) so freed blocks are quickly recycled, and run under compute-sanitizer to surface the cross-stream use-after-free.
  • With the record_stream fix in place the sanitizer reports clean and the intermittent corruption disappears.

Expected behavior

The caching allocator should defer reuse of the bucket storage until the consuming kernels have completed, so no cross-stream use-after-free occurs. The fix is to record the current compute stream on the bucket tensor before freeing its storage:

if bucket_id in self.buckets:
    self.buckets[bucket_id].data.record_stream(torch.cuda.current_stream())
    _free_storage(self.buckets[bucket_id].data)

Additional context

Affected version: 0.5.0 (latest published release at time of writing).

yuhezhang-ai avatar Jul 13 '26 20:07 yuhezhang-ai

Given that record_stream locks memory allocations until all tasks assigned to a stream are complete, we can't use that as a catch-all solution or else any free call will not be effective until the entire compute stream is clear of tasks.

Not sure if we have tried event-based waits during the post-forward hook. It merits double-checking for sure.

cspades avatar Jul 14 '26 15:07 cspades

Not sure if we have tried event-based waits during the post-forward hook. It merits double-checking for sure.

Agreed. For the reference, MFSDP v2 avoids using record_stream in favor of event-based waits: https://github.com/NVIDIA/Megatron-LM/pull/5719/changes#diff-f21cfe22709b6d177ca822856ab5fd4461737aa5edd6b4c00a8551c678665849R275-R280

wujingyue avatar Jul 14 '26 18:07 wujingyue

Thanks @yuhezhang-ai , @cspades — the event-based direction makes sense, and I agree that a broad record_stream() workaround would retain allocations for too much of the compute stream.

Since this issue is already assigned, I do not want to duplicate ongoing implementation work. I have 4×A100 available and would be happy to help with a narrowly scoped V1 reproduction and validation effort if useful:

  1. Build a deterministic single-GPU two-stream lifetime harness with a delayed consumer and forced allocator reuse.
  2. Exercise the real Megatron-FSDP overlap_param_gather path with DP=2.
  3. Run a TP=2 / DP=2 four-GPU regression to cover TP compute consuming FSDP-gathered parameter storage.
  4. Compare the ordering with the MFSDP v2 event-based approach referenced in #5719, ensuring that the wait is scoped to the bucket’s consumer completion rather than the entire compute stream.
  5. Validate under allocator pressure and compute-sanitizer, and check that the fix does not introduce a device-wide synchronization or eliminate overlap.

Would it be useful for me to take this scoped reproduction/test work and post the evidence before proposing any production-code change, or are you already implementing the corresponding V1 fix? I’ll wait for confirmation before opening a PR.

chengcuiping avatar Jul 19 '26 03:07 chengcuiping

are you already implementing the corresponding V1 fix?

No, we are not fixing this issue in V1 at this moment.

the event-based direction makes sense

Depending on the size of the PR, we can either take it into V1 or give up this issue and defer to V2. I suspect fixing it in V1 is going to be a big change.

wujingyue avatar Jul 20 '26 06:07 wujingyue

Thanks, that clarifies things. I agree that we should first find out whether V1 has a genuinely small fix, rather than assuming the V2 mechanism can be carried over cleanly.

I’m happy to take the investigation side: reproduce the V1 lifetime race, trace the exact gather → compute → free ordering, and try the narrowest bucket-scoped event handoff I can find. I’ll also check whether it introduces broader synchronization or reduces overlap. I’ll post the results here first, before opening any production-code PR. If the smallest safe V1 fix still turns out to be invasive, the evidence should at least help us make a clear call to defer this to V2.

@cspades, does that scope sound okay to you? I don’t want to duplicate anything you may already be investigating, so please let me know if you’d prefer a different split.

chengcuiping avatar Jul 20 '26 07:07 chengcuiping

SGTM

wujingyue avatar Jul 20 '26 15:07 wujingyue

To add a bit more detail to this issue before I hop off:

This is a timing race and is difficult to trigger deterministically.

There are many race conditions that I see all the time when they disagree with FSDP scheduling. They ideally should be fixed at the source. This is why integrations exist, like with TransformerEngine's wgrad accumulate fusion.

@yuhezhang-ai Could you update the issue description with at least a reproduction of the non-deterministic issues with freeing storage too early or too late? Otherwise, there has been much talk of "fixing" a bug that may not even exist in FSDP (and thus, should not be "fixed").

cspades avatar Jul 25 '26 01:07 cspades

Hi, I'd like to work on this fix if it's still available.

The root cause is clear — _free_storage is called without record_stream on the consuming stream, allowing the CUDA caching allocator to recycle the buffer while a compute kernel on the compute stream is still reading parameter views backed by it.

The fix is one line before the free:

if bucket_id in self.buckets:
    self.buckets[bucket_id].data.record_stream(torch.cuda.current_stream())
    _free_storage(self.buckets[bucket_id].data)

I've been working with CUDA cross-stream memory patterns (recently contributed a fused silu+mul + dynamic per-token FP8 quantization kernel to vLLM, PR vllm-project/vllm#49828), so I'm comfortable with the record_stream / caching-allocator interaction and can add a targeted test to verify the fix under compute-sanitizer.

Could I be assigned to this? Happy to submit a PR promptly.

priyanka25aug avatar Jul 26 '26 19:07 priyanka25aug

@cspades @wujingyue — apologies, I should have read the full thread before my previous comment. You've already covered exactly why a broad record_stream is wrong here (it holds the allocation until the entire compute stream clears, not just until the consuming kernel finishes), and @wujingyue's pointer to the MFSDP v2 event-based approach in #5719 is the right direction.

To clarify my earlier comment: I'm not proposing a simple record_stream drop-in. What I'd like to explore (if it's still useful) is the narrower investigation @chengcuiping outlined — reproducing the V1 lifetime race with a deterministic harness and checking whether the bucket-scoped event handoff from #5719 can be carried into V1 cleanly without introducing a device-wide sync or collapsing overlap.

If @chengcuiping is already running that, I'm happy to step back or help with validation on a different GPU configuration. Let me know what's most useful.

priyanka25aug avatar Jul 26 '26 19:07 priyanka25aug

Thanks @priyanka25aug — yes, I’m continuing the scoped V1 investigation, and I’d like to take primary ownership of the reproduction and attribution work through to a minimal PR if the evidence supports an FSDP-side fix.

I currently have a synthetic lifetime oracle and preliminary validation of the bucket-scoped event-handoff direction, but I do not consider either sufficient to establish that the reported failure originates in Megatron-FSDP itself. The next step is a real DP=2 V1-path comparison with runtime-only instrumentation: unmodified scheduling under allocator pressure, controlled consumer delay, and the scoped event handoff. I’ll report the frozen commit, exact commands, per-rank logs, failure rates, observed gather → compute → free/reuse ordering, and whether the handoff introduces broader synchronization or reduces overlap.

If the failure reproduces and attribution points to FSDP, I’d like to follow up with the smallest V1 PR after maintainer review. If it instead points to an integration-level scheduling violation, I’ll report that result rather than forcing an allocator fix.

Validation on a different GPU/software configuration would be very useful once the harness and protocol are frozen. I’d be happy to tag you at that point so we can compare results without duplicating the initial investigation.

chengcuiping avatar Jul 27 '26 01:07 chengcuiping

Thanks for the detailed update @chengcuiping — the scoped event-handoff direction sounds right to me given the ordering violation.

Happy to hold off on parallel reproduction until your harness and protocol are frozen so we're not duplicating work. Cross-validation on a different GPU/software config makes sense as the next step.

A few things I can confirm on my end when you're ready to tag me:

  • I can run the DP=2 V1-path comparison with your exact frozen commit and commands
    • I have a different hardware config (different CUDA/PyTorch version stack) which should make the cross-validation meaningful
      • I can capture per-rank logs in the same format you're using One question while you're doing the initial investigation — are you planning to instrument the record_stream path before or after the gather→compute→free/reuse ordering is confirmed? Asking because if the handoff fix requires a record_stream call on the gather tensor, it'd be worth checking whether that interacts with the existing _free_storage path in the allocator under ZeRO-3.

Will wait for your tag.

priyanka25aug avatar Jul 27 '26 01:07 priyanka25aug

Thanks @priyanka25aug — that cross-validation setup will be very useful, particularly the different CUDA/PyTorch stack and the ability to capture matching per-rank logs. I’ll tag you once the commit, harness, arm definitions, and output schema are frozen.

One clarification on the current evidence: the synthetic lifetime oracle demonstrates that the hypothesized early-reuse ordering is sufficient to corrupt a delayed consumer, and static analysis of the V1 call graph has not found an explicit consumer → release edge. Neither result establishes that the real DP=2 V1 path violates the lifetime contract, so that remains the primary attribution question in the protocol.

I plan to establish the ordering on the unmodified real path first. The baseline instrumentation is observation-only around bucket readiness, consumer launch and completion, the _free_storage resize-to-zero operation, and subsequent data-pointer/allocation reuse. It will not add record_stream, a stream wait, or a synchronization edge to the measured path. I also will not assume that torch.cuda.current_stream() is necessarily the only consumer: if an integration-owned auxiliary stream is involved, I’ll record that separately as part of the attribution result.

If the real-path violation is confirmed, the main candidate arm will be a bucket-scoped event handoff modeled on #5719: record completion on the identified consumer stream, make the bucket’s allocation/release stream wait on that event, and execute _free_storage with that stream current. This should queue reuse behind the relevant consumer without introducing a host wait or device-wide synchronization. A broad record_stream arm may be included afterward as a diagnostic control, but not as the proposed V1 fix. So, to answer your question directly, the record_stream arm will come after the unmodified ordering run, not before it.

I agree that the ZeRO-3 interaction needs explicit coverage. I’ll track the owning bucket tensor and its parameter views, storage size and data pointer, reuse timing, and allocated/reserved memory around _free_storage. I do not want to assume that record_stream combined with manual storage resize has the same lifetime behavior as ordinary tensor deallocation. If the event-handoff implementation still requires recording the gather tensor on the broader compute stream, I would treat that as evidence that the proposed bucket-scoped design has failed rather than quietly including it in a patch.

I’ll share the frozen protocol and exact commands before asking you to run the independent cross-validation.

chengcuiping avatar Jul 27 '26 01:07 chengcuiping

Thanks @chengcuiping , Agreed on all points — establishing the ordering on the unmodified path first is the right sequence, and treating a required broad-stream record as evidence against the bucket-scoped design (rather than folding it into a patch) is the correct standard. Standing by for the frozen protocol.

priyanka25aug avatar Jul 27 '26 02:07 priyanka25aug

Hey @yuhezhang-ai, I'm assign this back to you as per https://github.com/NVIDIA/Megatron-LM/issues/5788#issuecomment-5076076596

I agree with Cory that we need a reproduction of the non-deterministic issues. Especially, given that V1 is in maintenance mode and V2 is designed to avoid this issue altogether, we'd like to make sure we're investing our time where it has the most impact.

wujingyue avatar Jul 27 '26 15:07 wujingyue

@wujingyue @cspades — you're both right, and I owe you an apology. I dug into this properly and the bug as I filed it does not exist. I'd like to retract it — please close as invalid.

What I got wrong: I found this by static inspection during a source audit of 0.5.0, looking at the free() site in isolation. I never observed a failure. The original description asserted "intermittent numerical corruption / CUDA memory errors" and that "with the record_stream fix in place the sanitizer reports clean and the intermittent corruption disappears" as though they were observations. They were not. That was careless of me, and I'm sorry for the time it cost you and @chengcuiping and @priyanka25aug.

What I missed: the ordering that record_stream would provide is already supplied one frame up, in AllGatherPipeline.all_gather_params:

all_gather_stream.wait_stream(torch.cuda.current_stream())   # param_and_grad_buffer.py:4141
with torch.cuda.stream(all_gather_stream):
    with _coalescing_manager(dp_group, async_ops=async_param_gather) as coalescing_event:
        for bucket_id in buckets:
            self.async_bucket_gather(bucket_id, bwd)   # -> fetch_bucket -> allocator.allocate

Bucket storage is only ever allocated with all_gather_stream current, and the caching allocator only recycles a block for allocations on that same stream — so any reuse-write is necessarily enqueued after that wait_stream, which covers the compute-stream kernels enqueued before the free. Consumption is ordered the other way by param_gather_event.wait() in wait_bucket_ready, and ProcessGroupNCCL already records the bucket on the NCCL stream. The gradient sibling is stronger still — its free sits behind grad_reduce_event.wait().

The clincher: RotaryBucketAllocator.free and FixedPoolAllocator.free don't touch the CUDA allocator at all — they push the buffer straight back to the idle pool, handing the same memory to the next bucket immediately. record_stream would be a no-op for those. They can only be correct if stream-ordering is the intended contract — which it is. So this is deliberate design, not an oversight, and my suggested patch would have traded a real memory regression for nothing.

Agreed on the priority framing too: with V1 in maintenance mode and V2 event-based by design, there's nothing here worth investing in. @chengcuiping @priyanka25aug — thank you both, sincerely, and sorry for sending you after a phantom; please don't spend further GPU time on it.

yuhezhang-ai avatar Jul 27 '26 15:07 yuhezhang-ai

Thanks for the careful follow-up and for tracing the ordering through the complete allocation path.

That resolves the attribution question I was investigating. My synthetic oracle only established that an artificially introduced early-reuse ordering could corrupt a delayed consumer; it did not demonstrate that the real Megatron-FSDP V1 path permits that ordering. Given the existing stream-ordering contract you identified, I’ll stop the DP=2 instrumentation and GPU validation work and will not pursue a V1 patch for #5788.

@priyanka25aug, no cross-validation run is needed for this issue. Thanks again for offering the independent configuration.

chengcuiping avatar Jul 27 '26 15:07 chengcuiping

Closed as per https://github.com/NVIDIA/Megatron-LM/issues/5788#issuecomment-5093130870

wujingyue avatar Jul 27 '26 16:07 wujingyue