Skip to content

[pipelining] Allocate receive buffers just in time - #196463

Closed
sanketpurandare wants to merge 14 commits into
gh/sanketpurandare/7/basefrom
gh/sanketpurandare/7/head
Closed

sanketpurandare wants to merge 14 commits into
gh/sanketpurandare/7/basefrom
gh/sanketpurandare/7/head

Conversation

@sanketpurandare

@sanketpurandare sanketpurandare commented Sep 9, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

PipelineStage previously allocated one activation and gradient receive buffer
for every microbatch during setup. Those tensors remained live for the entire
step, even though each receive destination only needs to exist from the receive
action until the corresponding stage computation takes ownership.

Allocate receive buffers immediately before posting each receive and transfer
the reference to compute when it is consumed. Keep the receive descriptor and
its ownership transitions in _recv_buffers.py; stage execution imports that
storage primitive and remains responsible for peer resolution and P2P operation
construction.

Resolve every source rank before taking ownership, and make allocation plus P2P
operation construction transactional within each receive batch. When a schedule
timestep contains multiple receive batches, a failure before P2P launch also
releases buffers acquired by earlier batches in that timestep. Same-rank
V-schedule handoffs prepare and validate a complete buffer batch before assigning
any descriptor, so an invalid later input cannot strand earlier ownership.

Missing gradients are represented by missing tensor metadata at the schedule
boundary, so allocation and consumption are total over valid buffer states and
return Tensor rather than Tensor | None.

A buffer left owned after an incomplete step may still have P2P work writing to
it. Descriptor regeneration therefore fails closed across schedule modes:
callers must destroy the process group, then reconstruct the stages and schedule
before retrying. Recreating only a schedule or switching between train and eval
does not make the storage safe to reuse.

Received DTensors are reconstructed only after communication has completed, so
transferring ownership before reconstruction remains safe if reconstruction
fails. Effective gradient requirements are applied at consumption time.
Successful sequential, interleaved, V-shaped, and None-gradient schedules drain
every descriptor.

Test Plan:

  • python test/distributed/pipelining/test_schedule.py ScheduleTest.test_stage_recv_buffer_allocation_and_consumption ScheduleTest.test_recv_info_rejects_invalid_state_transitions ScheduleTest.test_stage_recv_construction_is_transactional ScheduleTest.test_same_rank_recv_assignment_is_transactional ScheduleTest.test_timestep_recv_validation_releases_prior_batches
  • python test/distributed/pipelining/test_stage.py PipelineStageMetadataInferenceTest.test_recv_metadata_reinit_rejects_owned_buffers
  • NCCL_DEBUG=WARN CUDA_VISIBLE_DEVICES=0,1,2,3 python test/distributed/pipelining/test_schedule_multiproc.py ScheduleTest.test_v_shape_schedules_schedule_class0 ScheduleTest.test_v_shape_schedules_schedule_class1 ScheduleTest.test_NoneGrad_conditional_input_grad_ScheduleClass0_pattern_first_false_then_true ScheduleTest.test_NoneGrad_conditional_input_grad_ScheduleClass1_pattern_first_true_then_false ScheduleTest.test_NoneGrad_conditional_input_grad_ScheduleClass2_pattern_first_false_then_true ScheduleTest.test_NoneGrad_conditional_input_grad_ScheduleClass2_pattern_first_true_then_false
  • lintrunner --config=.lintrunner.toml torch/distributed/pipelining/_recv_buffers.py torch/distributed/pipelining/stage.py torch/distributed/pipelining/schedules.py test/distributed/pipelining/test_schedule.py test/distributed/pipelining/test_schedule_multiproc.py

AI assistance disclosure:

This change was authored with assistance from an AI coding tool and reviewed by the author.

[ghstack-poisoned]
@pytorch-bot

pytorch-bot Bot commented Sep 9, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

🧪 See artifacts and rendered test results at hud.pytorch.org/pr/196463

Note: Links to docs will display an error until the docs builds have been completed.

❗ 1 Active SEVs

There are 1 currently active SEVs. If your PR is affected, please view them below:

✅ No Failures

As of commit c5a80a9 with merge base 38e2a2e (image):
💚 Looks good so far! There are no failures yet. 💚

This comment was automatically generated by Dr. CI and updates every 15 minutes.

@pytorch-bot pytorch-bot Bot added the ciflow/torchtitan Run TorchTitan integration tests label Sep 9, 2026
sanketpurandare added a commit that referenced this pull request Sep 10, 2026
Summary:
Optionally preallocate and reuse a deterministic pool of pipeline receive
buffers. The finalized schedule is colored before warmup, each slot is assigned
before its receive, and the slot is released only after the consuming backward;
inference retains it until outstanding sends complete.

This provides stable CUDA-graph addresses without restoring one buffer per
microbatch. Lazy just-in-time allocation remains supported. The change adds no
polling, dynamic recoloring, or schedule mutation.

Dependencies and risks:
- Requires the receive ownership model from #196463 and slot coloring from
  #196464.
- Tests cover forward/backward shape classes, full and split backward,
  inference send lifetime, repeated steps, and storage aliasing.

Test Plan:
- `python test/distributed/pipelining/test_schedule.py -k recv_buffer`
- `python test/distributed/pipelining/test_schedule_multiproc.py`

ghstack-source-id: c410342
Pull-Request: #196465
@sanketpurandare
sanketpurandare marked this pull request as ready for review September 10, 2026 20:03
[ghstack-poisoned]
@sanketpurandare

Copy link
Copy Markdown
Contributor Author

@claude provide a critical pr review, check for bugs, soundness of design, test coverage, redundant tests, slop code, cpmpactness of code, api design and provide feedback or suggest changes on how to make it better.

@claude

claude Bot commented Sep 15, 2026 •

Copy link
Copy Markdown

Claude finished @sanketpurandare's task in 21m 25s —— View job


Reviewed the just-in-time recv-buffer change: the ownership model is sound and I could not find a double-recv or double-consume path in any schedule, but clear_runtime_states no longer resets _RecvInfo.buffer, which turns the new allocate_buffer guard into a latch that masks the original failure on a subsequent step(), and three of the six new raise sites are provably dead code.

Full review — PR #196463

PR Review: #196463

Summary

Moves pipeline-stage receive buffers from setup-time allocation to just-in-time allocation behind a three-method ownership API (allocate_buffer / set_buffer / take_buffer) on _RecvInfo. The central soundness question — whether any schedule can now post a recv twice, or consume a buffer twice, and hit the new hard errors — checks out clean (verified across ScheduleGPipe, Schedule1F1B, _ScheduleForwardOnly, PipelineScheduleMulti._step_microbatches, and all _PipelineScheduleRuntime subclasses). The problems are a robustness regression in clear_runtime_states, dead defensive code, and test coverage that misses both the new error contract and every schedule where the contract is actually hard to satisfy.


Code Quality

1. clear_runtime_states no longer resets buffers — the allocation guard becomes a latch (stage.py:751-758)

The PR deletes the loop over args_recv_info that used to run here, and replaces it with nothing:

    def clear_runtime_states(self) -> None:
        self.fwd_cache.clear()
        self.output_chunks.clear()

Pre-PR this was self-healing: buffers were persistent and irecv simply overwrote them, so a step that died between recv and compute left no trace. Now, if a step aborts after allocate_buffer but before the matching take_buffer — an exception in forward_maybe_with_nosync, a collective timeout, or a user who catches the exception from step() and retries — the stale buffer survives into the next step, and allocate_buffer raises Receive buffer for '...' is already allocated. The user sees a confusing metadata error instead of the actual failure.

I confirmed the exception does escape step() (schedules.py:2439-2455 logs and re-raises; single-stage schedules have no handler at all), so this needs the user to retry — but retry-after-catch is a normal pattern, and clear_runtime_states at schedules.py:985 / 2232 is exactly the per-iteration reset hook that should be making the state clean. Restore a reset there:

        for recv_infos in self.args_recv_info.values():
            for info in recv_infos:
                info.buffer = None
        for recv_infos in self.grad_recv_info.values():
            for info in recv_infos:
                info.buffer = None

This is also the difference between allocate_buffer (latches on failure) and take_buffer (clears before it raises, so it does not latch) — worth making the two consistent. Fix this →

2. Three of the six new raise sites are unreachable

_RecvInfo.buffer has exactly two writers (allocate_buffer at stage.py:130, set_buffer at stage.py:142), and both refuse to write when tensor_meta is None — allocate_buffer returns early, set_buffer raises. tensor_meta is written only in __init__ and _TensorMeta is frozen. So buffer is not None implies tensor_meta is not None, and these three checks can never fire:

  • stage.py:151-154 — take_buffer's if buffer is not None and self.tensor_meta is None: raise ... "is not expected".
  • stage.py:779-780 — _retrieve_recv_activations: the line above already established info.tensor_meta is not None (774-777), and take_buffer itself raises when buffer is None and tensor_meta is not None. The raise AssertionError("expected receive buffer to be not None") cannot trigger.
  • stage.py:849-852 — _retrieve_recv_grads: Grad recv '...': buffer is not None but tensor_meta is None, same invariant.

The PR is trading one clear invariant (buffer-parallels-metadata, enforced in two places) for six scattered raise sites. Deleting these three would make the remaining contract easier to read and would drop the # type: ignore-shaped narrowing dance in the callers.

3. take_buffer mutates before it validates (stage.py:144-155)

    def take_buffer(self):
        buffer = self.buffer
        self.buffer = None
        if buffer is None and self.tensor_meta is not None:
            raise PipeliningMetadataError(...)

The clear-then-check ordering happens to be benign today (on the reachable raise, self.buffer was already None), and it is what keeps this method non-latching. But it reads as an accident rather than a decision. Either validate first and clear last, or state in a one-line comment that clearing before raising is deliberate so a failed consume does not poison the next step — because the follow-up pooling PR (#196465) will make this ordering load-bearing.

4. set_local_bwd_input allocates then zeroes (stage.py:587-589)

                buffer = info.allocate_buffer(self.device)
                if buffer is not None:
                    buffer.zero_()

allocate_buffer goes through _make_tensor_from_meta, i.e. torch.empty_strided, so this is an allocate-then-memset on the V-schedule local-passing path for every None gradient. Pre-PR this zeroed a buffer that already existed, so the memset was the whole cost; now it is allocation plus memset. Minor, but it is per-microbatch on a hot path.

5. allocate_buffer's tri-state return is muddy (stage.py:123-131, 503-506)

None means "root arg" or "no metadata (None gradient)", and the caller has already continued on root args two lines earlier, so the comment at stage.py:504 (# Skip entries with no metadata (None gradients)) documents only half of what the None can mean. Dropping the is_root_arg leg from allocate_buffer (it is unreachable from the only caller) would make the return value mean exactly one thing.


Testing

6. No coverage for any of the three new error paths

allocate_buffer, set_buffer, and take_buffer introduce a new, user-visible failure contract ("is already allocated", "is already set", "has not been set"). Nothing in the PR exercises it. These raises are the entire safety mechanism the PR is putting in place for the deterministic-pooling PR that builds on it (#196465), so they deserve direct tests — three short assertRaisesRegex cases in test_schedule.py against a bare _RecvInfo, no mock stage required. Fix this →

7. The multiproc drain assertion only covers the two easiest schedules (test_schedule_multiproc.py:542-548)

The new "all buffers are drained after a step" loop is added inside test_multi_iter, which is parametrized [ScheduleGPipe, Schedule1F1B] — both single-stage, both strictly sequential. The paths where the new contract is actually hard to satisfy get no assertion at all:

  • V-schedule local passing (set_local_fwd_input / set_local_bwd_input, schedules.py:2803/2832/2854) — the only callers of set_buffer, and the only place where a buffer arrives without a recv.
  • The zero-bubble BACKWARD_INPUT → BACKWARD_WEIGHT split (schedules.py:2835-2864), where grads are consumed by one action and weights by a later one.
  • Interleaved / looped schedules, where recvs are posted well ahead of their compute.

Since the whole point of the drain invariant is that no buffer outlives its microbatch, it should run for ScheduleZBVZeroBubble, ScheduleInterleaved1F1B, and ScheduleInterleavedZeroBubble too. Factor the loop into a small module-level helper and call it from the schedule-parametrized tests rather than bolting it onto test_multi_iter, which is otherwise about numerical stability across iterations.

8. The unit test never checks that the allocated buffer is the one handed to irecv (test_schedule.py:177-190)

            patch("torch.distributed.pipelining.stage.dist.P2POp"),
        ):
            fwd_ops = stage.get_fwd_recv_ops(1)
            self.assertEqual(len(fwd_ops), 1)

With P2POp mocked out, the test asserts only that one op came back. The interesting property — that _get_recv_ops passes the newly allocated info.buffer (and not a stale or copied tensor) to dist.irecv — is exactly what the mock is in a position to verify and does not. Assert on the mock's call_args tensor being fwd_buffer.

9. The unit test hand-builds stage state and calls an unbound method across classes (test_schedule.py:150-172)

        stage = MockPipelineStage(num_stages=3, group_size=1, group_rank=0)
        stage.stage_index = 1
        stage.device = torch.device("cpu")
        ...
        PipelineStage._setup_forward_recv_info(stage, 2, has_backward=True)
        for mb_index in range(2):
            stage.grad_recv_info[mb_index] = PipelineStage._create_grad_recv_info(
                stage, stage.act_send_info
            )

Ten attributes are assigned onto a MockPipelineStage and then two PipelineStage methods are invoked unbound on an object that is not a PipelineStage. This works only because those methods happen to touch a specific attribute subset; any refactor of _setup_forward_recv_info breaks the test for reasons unrelated to buffer ownership. A real PipelineStage over a two-layer nn.Module on a single-rank gloo group, or at minimum making MockPipelineStage set these fields in __init__, would be considerably more durable.

10. raise AssertionError where assertIsNotNone exists (test_schedule.py:184-185, 195-196)

            if fwd_buffer is None:
                raise AssertionError("expected forward receive buffer to be allocated")

The same test uses self.assertIsNone four lines earlier. The repo's S101 rule is about avoiding bare assert, not about avoiding unittest assertions — use self.assertIsNotNone(fwd_buffer) for consistency with the surrounding code.


Performance

11. Buffer lifetime is bounded by recv-post time, not compute time

In _PipelineScheduleRuntime, RECV_F / RECV_B actions are ordered by pipeline_order_with_comms and can be scheduled well ahead of the matching FORWARD / BACKWARD (schedules.py:2733-2748 posts, 2784-2788 / 2815-2819 waits). So for interleaved and zero-bubble schedules the peak number of live recv buffers is the recv-prefetch depth, not one — the saving over the previous num_microbatches preallocation is real but schedule-dependent. Worth stating in the PR description, since "allocate just in time" reads as if peak drops to a single buffer, and #196465's pooling design will need the actual bound.


Recommendation

Request Changes

The ownership model is right and I found no schedule that violates it. What blocks approval is finding 1 — dropping the buffer reset from clear_runtime_states converts a previously self-healing condition into an error that masks the real failure — plus the absence of any test for the three new error paths (finding 6) that the follow-up pooling PR depends on. Findings 2, 3, and 5 are cheap deletions that would leave the API materially smaller than what is currently proposed.

· branch `gh/sanketpurandare/7/head`

@sanketpurandare

Copy link
Copy Markdown
Contributor Author

@claude Kept stale ownership fail-fast deliberately: after an interrupted distributed step, outstanding P2P work may still write the buffer, so clearing the descriptor would make unsafe reuse appear valid. The error now names the incomplete-step condition and the schedule/process-group recreation boundary. Unreachable metadata/buffer combinations were removed, None now represents only a reachable no-gradient receive, and tests prove the exact allocated tensor reaches P2POp and that successful multiprocess schedule paths drain every descriptor.

@claude

claude Bot commented Sep 15, 2026 •

Copy link
Copy Markdown

Claude finished @sanketpurandare's task in 15m 32s —— View job


Re-reviewed the update: three of the four claims verify cleanly, but the tri-state take_buffer() return is failing pyrefly lint in CI right now, the drain assertion still does not cover the V-schedules that are the only set_buffer callers, and the new error message recommends a remedy (recreate the schedule) that silently clears the guard without making reuse safe.

Follow-up review — PR #196463 (round 2)

What I verified as resolved

Checked each of the four claims against the diff rather than taking them at face value:

  • Unreachable metadata/buffer combinations removed — confirmed. take_buffer's is not expected leg, _retrieve_recv_activations's buffer is None raise, and _retrieve_recv_grads's buffer is not None but tensor_meta is None raise are all gone. One dead leg survived; see finding 3.
  • _map_tensor_from_recv_info removal — confirmed unused repo-wide (only remaining map_aggregate use is _create_grad_send_info at stage.py:438, which reads is_root_arg/source, not buffer).
  • Dropping a.buffer.grad = None from clear_runtime_states — sound, and worth stating explicitly since it is not obvious from the diff. The reset existed because persistent buffers were autograd leaves that torch.autograd.backward would accumulate into across steps. With JIT allocation each microbatch gets a fresh leaf, so inp.grad is provably None when _backward.py:258 runs, and _backward.py:450 already nulls it after the fact. No behavior change.
  • Traced-frontend requires_grad refactor (stage.py:1550-1569) — verified equivalent. The old code did buffer.requires_grad_(True) at setup when has_backward and is_floating_point(); the new code encodes the same predicate into _TensorMeta.requires_grad and lets effective_requires_grad apply it at consume time, with the added torch.is_grad_enabled() gate. Strictly better.
  • No double-consume — re-verified after the refactor. _retrieve_recv_grads is called only from backward_one_chunk; the zero-bubble BACKWARD_WEIGHT path reads self.backward_state (stage.py:1215), not the descriptor, so the B/W split cannot take twice. OVERLAP_F_B recurses into _perform_action per sub-action (schedules.py:2899-2903), so no duplication there either.

1. take_buffer()'s Tensor | None return is failing pyrefly in CI — and the fix is the same change that removes the tri-state

Lint run 34938505660 → lintrunner-pyrefly-partial fails with three errors, all from this PR's new code:

Object of class `NoneType` has no attribute `requires_grad`        stage.py:794
Argument `Tensor | None` is not assignable to parameter `local_tensor`
  with type `Tensor` in function `DTensor.from_local`               stage.py:802
Object of class `NoneType` has no attribute `requires_grad_`        stage.py:810

_retrieve_recv_activations checks info.tensor_meta is None at stage.py:778-781 and then calls take_buffer() at 782, so the human-visible invariant is fine — but the checker cannot connect the guard on info.tensor_meta to the Optional return of a method on info. Suppressing this with three # type: ignore would be the wrong fix, because the same restructuring removes the tri-state return the previous round flagged.

Make both methods total and put the metadata decision in the caller, which is where it is actually a schedule-level fact:

    def allocate_buffer(self, device: torch.device | str) -> torch.Tensor:
        if self.tensor_meta is None:
            raise PipeliningMetadataError(
                f"Receive '{self.input_name}' has no tensor metadata to allocate from"
            )
        ...
        return self.buffer

    def take_buffer(self) -> torch.Tensor:
        if self.buffer is None:
            raise PipeliningMetadataError(
                f"Receive buffer for '{self.input_name}' has not been set"
            )
        buffer = self.buffer
        self.buffer = None
        return buffer

and at the three call sites make the no-gradient case explicit:

        # _get_recv_ops, stage.py:507
            if info.tensor_meta is None:   # None gradient: nothing to receive
                continue
            buffer = info.allocate_buffer(self.device)

        # _retrieve_recv_grads, stage.py:847
            if info.tensor_meta is None:
                grads.append(None)
                continue
            buffer = info.take_buffer()

That is fewer lines than the current version, drops the if buffer is None: continue indirection, makes None unrepresentable rather than merely documented, and clears pyrefly without a suppression. Fix this →


2. The remedy in the error message is defeated by its own first clause

I traced what "recreate the schedule and process group" actually does. _stages_forward_initialized is per-schedule state set to False in __init__ (schedules.py:2004), so a fresh schedule over the same stage objects re-runs _prepare_forward_infra → _setup_forward_recv_info (stage.py:2444-2465), which overwrites args_recv_info[chunk_id] with brand-new _RecvInfo objects whose buffer is None.

So recreating the schedule alone makes the guard disappear while the in-flight NCCL write is still outstanding against the old storage — exactly the unsafe state the guard exists to prevent. Only the process-group teardown is load-bearing here; the schedule recreation is the part that clears the flag. As written, a user reading the message will do the harmless-looking half and conclude they are fine.

Reword so the ordering and the load-bearing step are unambiguous, and name the API:

f"Receive buffer for '{self.input_name}' is still owned by an incomplete "
"pipeline step: in-flight P2P work may still write to it. Tear down the "
"process group (dist.destroy_process_group) before constructing a new "
"schedule; recreating the schedule alone does not make this storage safe "
"to reuse."

The PR description makes the same elision ("callers must recreate the schedule and process group") and is worth tightening the same way, since this is the user-facing contract the rest of the stack builds on. Fix this →

While there: the 4-line message is now duplicated verbatim in allocate_buffer and set_buffer. A module-level format string keeps the two in sync.


3. One dead defensive leg survived the cleanup

set_buffer's guard at stage.py:136-139:

        if self.is_root_arg or self.tensor_meta is None:
            raise PipeliningMetadataError(
                f"Receive buffer for '{self.input_name}' is not expected"
            )

The is_root_arg half is unreachable. set_buffer has exactly two callers, and both already raise AssertionError on is_root_arg immediately before calling it — set_local_fwd_input at stage.py:548-551 (raise) then 555 (call), and set_local_bwd_input at 599-602 then 605.

The tensor_meta is None half is worth keeping (it catches a next-stage grad arriving for a receive whose metadata says None), but the merged message names neither condition. Reduce to the one live check and make it actionable:

        if self.tensor_meta is None:
            raise PipeliningMetadataError(
                f"Receive '{self.input_name}' expects no gradient (tensor_meta is None) "
                "but a gradient tensor was passed"
            )

4. The drain assertion still misses the paths where the contract is hard to satisfy

The claim is that "successful multiprocess schedule paths drain every descriptor," but assert_recv_buffers_drained is called from exactly two tests:

  • test_multi_iter (test_schedule_multiproc.py:552) — parametrized [ScheduleGPipe, Schedule1F1B], both single-stage and strictly sequential.
  • test_grad_with_manual_interleaved (:820) — ScheduleInterleaved1F1B / ScheduleLoopedBFS / ScheduleInterleavedZeroBubble. This one is a genuine improvement over the previous round: it covers the recv-prefetch-depth-greater-than-one case.

Still uncovered, and these are the interesting ones:

  • V-schedules. test_v_shape_schedules (:1061, ScheduleZBVZeroBubble / ScheduleDualPipeV) has no drain assertion. These are the only callers of set_buffer — the one path where a buffer arrives without a recv, and the one path where set_local_bwd_input allocates-and-zeroes at stage.py:591-593. If any ownership contract is going to be violated, it is here.
  • The reachable None-gradient receive. test_NoneGrad_conditional_input_grad (:1428) exercises tensor_meta is None descriptors, which is precisely the semantics the update narrowed None down to. No assertion that those descriptors end the step clean.

Adding assert_recv_buffers_drained(self, stages) to those two tests is a two-line change and closes the actual gap. Fix this →

Two smaller test notes:

  • The helper's isinstance(stages, (list, tuple)) branch at :243 exists only because one call site passes a bare stage. Both call sites are known — take a sequence and pass [stage]. The repo style guide asks for explicit state over polymorphic accommodation.
  • The drain check passes trivially on the first stage of every schedule (all descriptors are is_root_arg, so buffer is always None). Not wrong, but it means the assertion is only doing work on ranks 1..N-1; worth knowing when reading a green run.

5. The unit test is materially better, with two branches left

test_stage_recv_buffers_allocated_just_in_time (test_schedule.py:150-183) now asserts p2p.call_args.args[1] is info.buffer, which is exactly the property the previous round said the mock was in a position to verify. Confirmed the positional index is right against dist.P2POp(dist.irecv, buffer, peer_global_rank, group) at stage.py:514.

Two branches of the new contract remain untested:

  • set_buffer's rejection path (finding 3) — after that guard is reduced to the live condition, one assertRaisesRegex on a tensor_meta=None descriptor covers it.
  • take_buffer() on a tensor_meta=None descriptor returning None (or, after finding 1, the caller-side grads.append(None) path). This is the semantics the update deliberately narrowed, so it should be pinned.

6. Perf note, unchanged and acceptable

set_local_bwd_input (stage.py:591-593) allocates via torch.empty_strided and then zero_()s, per None gradient per microbatch on the V-schedule local path. Pre-PR the allocation was amortized across the step. There is no zeros_strided, so allocate-then-memset is the only spelling; flagging it only because it is the kind of cost the pooling PR (#196465) is meant to remove, and it would be good for that PR's description to name this call site.


Recommendation

Request Changes — finding 1 only (CI is red on pyrefly, and the fix is a simplification rather than a suppression). Finding 2 is a message/description correctness issue worth doing in the same push; findings 3 and 4 are small. The ownership model itself continues to hold up, and the fail-fast rationale is the right call — the guard correctly refuses a retry that would race in-flight P2P work. My remaining objection is only that the message points at a remedy whose first half quietly removes the guard.

· branch `gh/sanketpurandare/7/head`

Summary:
Pipeline stages currently retain one forward and backward receive buffer per microbatch from setup. Allocate a receive buffer immediately before posting its receive, transfer ownership to computation and autograd when consumed, and clear the descriptor reference afterward.

This supersedes #193872 on current main while preserving its implementation and authorship. It establishes explicit ownership for later static reuse, but does not add pooling, polling, schedule rewrites, or send-wait policy. A descriptor that still owns storage fails loudly: an interrupted distributed step may have in-flight P2P work, so callers must recreate the schedule and process group rather than silently reusing that storage.

The peak number of live lazy buffers is determined by the schedule's receive-prefetch depth, not necessarily one. Local V-schedule transfers follow the same ownership contract.

Test Plan:
- `python test/distributed/pipelining/test_schedule.py -k recv_buffer`
- `python test/distributed/pipelining/test_schedule_multiproc.py`

[ghstack-poisoned]

@SherlockNoMad SherlockNoMad 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.

lgtm. I suppose there is a latter PR that use the buffer from a pool

@SherlockNoMad

Copy link
Copy Markdown
Contributor

linter error is real.

[ghstack-poisoned]
@pytorch pytorch deleted a comment from claude Bot Sep 16, 2026
@sanketpurandare sanketpurandare added release notes: distributed (pipeline) release notes category module: pipelining Pipeline Parallelism labels Sep 16, 2026
@sanketpurandare

Copy link
Copy Markdown
Contributor Author

I used Codex to prepare this verification summary and reviewed it against the implementation and test results; it addresses the findings in this review: @claude Moved _RecvInfo and its ownership state machine into the focused _recv_buffers.py module. Source and peer-rank validation now completes for the whole receive batch before any descriptor acquires storage, and the existing lifecycle test proves a validation failure leaves every descriptor unowned. Documented why consumption before downstream validation is safe only after receive completion and scoped the fail-closed guarantee to one schedule and execution mode. The full 105-test schedule suite and all 67 four-GPU multiprocess cases pass.

@claude

claude Bot commented Sep 16, 2026 •

Copy link
Copy Markdown

Claude finished @sanketpurandare's task in 9m 58s —— View job


Round 4 re-review

  • Read the round-4 diff and the full PR diff vs origin/gh/sanketpurandare/7/base
  • Verify claim 1: _RecvInfo + ownership state machine moved to _recv_buffers.py
  • Verify claim 2: source/peer-rank validation completes before any allocation
  • Verify claim 3: lifecycle test proves a validation failure leaves every descriptor unowned
  • Verify claim 4: docs for consume-before-validate safety + fail-closed scoping
  • Re-check ownership soundness after the module move; confirm CI/lint status
  • Post review

All four claims verify against the diff and lintrunner-pyrefly-partial is green on the current head (f3ba7f26); the round-3 reorder is genuinely fixed, and my only substantive note is that the new all-or-nothing property holds per _get_recv_ops call rather than per batched timestep, which slightly narrows the claim.

Follow-up review — PR #196463 (round 4)

What I verified as resolved

1. _RecvInfo and its ownership state machine live in _recv_buffers.py. torch/distributed/pipelining/_recv_buffers.py:17-91 holds the class plus _INCOMPLETE_RECV_BUFFER_ERROR (:9-14); the corresponding blocks are gone from stage.py. Checked the mechanics of the move rather than just its shape:

  • No import cycle. _recv_buffers imports only _utils (_make_tensor_from_meta, PipeliningMetadataError, TensorMeta), and _utils does not import back. stage.py:53 and schedules.py:25 both import from the new module.
  • All importers updated. Swept _RecvInfo repo-wide: the only consumers are stage.py, schedules.py:2087, and test_schedule.py. schedules.py:38 correctly dropped _RecvInfo from the from .stage import line, so the re-export is gone rather than left as a compatibility shim — the right call for a private symbol.
  • Dead imports actually removed, not orphaned. cast and Argument are gone from stage.py's imports and grep 'cast(' over the file now returns nothing. map_aggregate survives because _create_grad_send_info (stage.py:370) still uses it. _make_tensor_from_meta is still imported and still used at stage.py:669 for the zero-grad path, so that is not a leftover either.

The split is the right seam: the module is 91 lines with a single responsibility, stage.py shrank by 119 lines net, and _recv_buffers.py has no dependency on stage or schedule internals, so the pooling PR (#196465) can extend it without reaching into stage.py.

2. Batch-wide validation now precedes any allocation. stage.py:429-443 is a clean two-pass:

        peer_ranks: list[int | None] = []
        for info in recv_infos:
            if info.is_root_arg or info.tensor_meta is None:
                peer_ranks.append(None)
                continue
            if info.source is None:
                raise AssertionError("expected info.source to be not None")
            peer_ranks.append(self._resolve_peer_global_rank(info.source))

        ops: list[dist.P2POp] = []
        for info, peer_global_rank in zip(recv_infos, peer_ranks, strict=True):
            if peer_global_rank is None:
                continue
            buffer = info.allocate_buffer(self.device)
            ops.append(dist.P2POp(dist.irecv, buffer, peer_global_rank, group))

This closes round-3 finding 1. Worth noting it covers more than the source is None assert I flagged: _resolve_peer_global_rank (stage.py:415-421) can also raise KeyError on stage_index_to_group_rank[stage_idx] or from dist.get_global_rank, and both now happen in the validation pass. The strict=True on the zip pins the two passes to the same length, so a future edit that filters in one pass but not the other fails loudly rather than misaligning descriptors with peers.

3. The lifecycle test does prove the ordering. test_schedule.py:188-202 constructs (valid_before_invalid, invalid_source) in that order and asserts both buffers are None after the raise. This is the right shape — a single-element test would have passed trivially under the old ordering, and putting the valid descriptor first is exactly what distinguishes the two implementations.

4. Both documentation claims land. _recv_buffers.py:77-79 states why clearing before a possible downstream failure is safe ("The schedule waits for recv completion before this transfer"), which is the asymmetry I raised in round 3 finding 2 as being correct-but-unstated. I re-verified the precondition holds for every consumer: _PipelineScheduleRuntime waits at schedules.py:2798/2829/2853 before the compute action; PipelineScheduleMulti._step_microbatches waits at :2448 at the end of each timestep, before the next timestep's forward_one_chunk; single-stage schedules wait at :1075-1077, :1130-1132, :1289. The V-schedule set_buffer path involves no comm at all. And the PR description now scopes the fail-closed guarantee to one schedule and mode, which is round-3 finding 3.

5. Drain coverage and ownership soundness re-confirmed. assert_recv_buffers_drained is called from four sites (test_schedule_multiproc.py:577, 845, 1116, 1439), covering sequential, interleaved, V-shaped, and None-gradient paths; the helper takes a plain list and test_multi_iter passes [stage]. Re-walked the ownership paths after the module move — single writer per descriptor per step in _get_recv_ops, backward_weight_one_chunk reading self.backward_state rather than the descriptor, OVERLAP_F_B recursing per sub-action — and found no double-allocate or double-consume.


1. The all-or-nothing property is per-call, not per-batched-timestep

The new guarantee is scoped to one _get_recv_ops invocation. In PipelineScheduleMulti._step_microbatches, several invocations accumulate into one ops list before the single _batch_p2p at schedules.py:2448:

                                stage = stage_index_to_stage[stage_index + 1]
                                ops.extend(stage.get_fwd_recv_ops(mb_index))   # :2406
                                ...
                                stage = stage_index_to_stage[stage_index - 1]
                                ops.extend(stage.get_bwd_recv_ops(mb_index))   # :2441

If the forward call succeeds (allocating its descriptors) and the backward call then raises during validation, the forward descriptors stay owned even though _batch_p2p never ran — so the next step() reports "in-flight P2P work may still write to it" and directs the user to tear down the process group for what is actually a deterministic metadata bug with nothing posted. Same shape as round-3 finding 1, one level up.

I would not restructure the schedule for this: a stage_index_to_group_rank or info.source fault is a configuration error that fires on the very first step, before any successful step exists to retry, so in practice the misleading message is reached only via a caught-and-retried first step. But the claim in the PR description ("Validate every source rank before taking ownership of any receive storage") reads as a per-step property when it is a per-call one. A half-sentence bounding it — validation is atomic per receive batch, and a multi-stage timestep issues several — keeps the contract honest for whoever builds on it. Fix this →

2. _get_recv_ops lost the group documentation

The old docstring explained that group is the direction-specific communicator and equals self.group unless per-direction P2P is enabled. The replacement (stage.py:428) documents the new ordering but drops that, and group is the one parameter whose meaning is not obvious from its name — get_fwd_recv_ops passes self._downstream_group and get_bwd_recv_ops passes the upstream one. Worth keeping both facts:

        """Validate all peers, then allocate and construct receive operations.

        ``group`` is the direction-specific communicator (downstream vs
        upstream); it equals ``self.group`` unless per-direction P2P is enabled.
        """

3. Two small test notes

  • test_stage_recv_buffers_allocated_just_in_time is now carrying six distinct contracts (allocate/take/set happy path, P2POp identity, three error messages, and batch validation ordering). The _RecvInfo-only assertions at :165-186 need nothing from the mock stage but torch.device("cpu"), while the identity check at :164 and the ordering check at :194-202 are really about _get_recv_ops. Splitting into a descriptor-lifecycle test and a _get_recv_ops-ordering test would localize failures; not blocking, but the test will keep growing as [pipelining] Reuse deterministic receive buffers #196465 lands.
  • The ordering test covers the info.source is None branch but not the _resolve_peer_global_rank branch, which is the more likely real-world fault (a bad stage_index_to_group_rank). Making the patched _resolve_peer_global_rank raise for a second descriptor would cover it with the same fixture — and that is the case where the pre-round-4 code would have left a buffer owned.

4. Perf note, unchanged

set_local_bwd_input (stage.py:520-521) is still torch.empty_strided + zero_() per None gradient per microbatch on the V-schedule local path. No zeros_strided exists, so that is the only spelling; still worth naming this call site in #196465's description as an allocation pooling should absorb.


CI

Lint run 35062492281 is success on the current head, with lintrunner-pyrefly-partial / lint, lintrunner-noclang-partial / lint, quick-checks, and workflow-checks all green — confirming the pyrefly failure @SherlockNoMad flagged stays fixed after the module move. BC Lint and Check mergeability of ghstack PR are green; pull and docs-build are in progress, torchtitan-test queued. I could not run the test suite here (no built torch in this checkout), so the 105-test and 67-case results are taken from your report rather than independently reproduced.

Recommendation

Approve. The module extraction is a clean seam with no cycle and no leftover re-exports, batch-wide validation is correctly atomic per call, and the ordering test is constructed so that it would actually fail against the previous implementation. Finding 1 is a description-scoping point, findings 2-4 are documentation and test-structure polish.

· branch `gh/sanketpurandare/7/head`

PipelineStage previously allocated one activation and gradient receive buffer for every microbatch during setup. Those tensors remained live for the entire step, even though each receive destination only needs to exist from the receive action until the corresponding stage computation takes ownership.

Allocate receive buffers immediately before posting each receive and transfer the reference to compute when it is consumed. Keep the receive descriptor and its ownership transitions in `_recv_buffers.py`; stage execution imports that storage primitive and remains responsible for peer resolution and P2P operation construction.

Validate every source rank before taking ownership of any receive storage, so a metadata failure cannot leave an earlier descriptor falsely marked as an in-flight receive. Missing gradients are represented by missing tensor metadata at the schedule boundary, so allocation and consumption are total over valid buffer states and return `Tensor` rather than `Tensor | None`.

A buffer left owned after an incomplete step may still have P2P work writing to it. Retrying therefore fails closed: callers must destroy the process group before constructing a replacement schedule; recreating only the schedule is not safe. This guard is scoped to one initialized schedule mode because a train/eval transition reconstructs the forward receive descriptors.

Received DTensors are reconstructed only after communication has completed, so transferring ownership before reconstruction remains safe if reconstruction fails. Effective gradient requirements are applied at consumption time. Successful sequential, interleaved, V-shaped, and None-gradient schedules drain every descriptor.

Test Plan:
- `python test/distributed/pipelining/test_schedule.py ScheduleTest.test_stage_recv_buffers_allocated_just_in_time`
- `NCCL_DEBUG=WARN CUDA_VISIBLE_DEVICES=0,1,2,3 python test/distributed/pipelining/test_schedule_multiproc.py ScheduleTest.test_v_shape_schedules_schedule_class0 ScheduleTest.test_v_shape_schedules_schedule_class1 ScheduleTest.test_NoneGrad_conditional_input_grad_ScheduleClass0_pattern_first_false_then_true ScheduleTest.test_NoneGrad_conditional_input_grad_ScheduleClass0_pattern_first_true_then_false ScheduleTest.test_NoneGrad_conditional_input_grad_ScheduleClass1_pattern_first_false_then_true ScheduleTest.test_NoneGrad_conditional_input_grad_ScheduleClass1_pattern_first_true_then_false ScheduleTest.test_NoneGrad_conditional_input_grad_ScheduleClass2_pattern_first_false_then_true ScheduleTest.test_NoneGrad_conditional_input_grad_ScheduleClass2_pattern_first_true_then_false`
- `lintrunner --config=.lintrunner.toml torch/distributed/pipelining/_recv_buffers.py torch/distributed/pipelining/stage.py torch/distributed/pipelining/schedules.py test/distributed/pipelining/test_schedule.py test/distributed/pipelining/test_schedule_multiproc.py`

AI assistance disclosure:
> This change was authored with assistance from an AI coding tool and reviewed by the author.

[ghstack-poisoned]
[ghstack-poisoned]
`PipelineStage` previously allocated one activation and gradient receive buffer
for every microbatch during setup. Those tensors remained live for the entire
step, even though each receive destination only needs to exist from the receive
action until the corresponding stage computation takes ownership.

Allocate receive buffers immediately before posting each receive and transfer
the reference to compute when it is consumed. Keep the receive descriptor and
its ownership transitions in `_recv_buffers.py`; stage execution imports that
storage primitive and remains responsible for peer resolution and P2P operation
construction.

Resolve every source rank before taking ownership, and make allocation plus P2P
operation construction transactional within each receive batch. When a schedule
timestep contains multiple receive batches, a failure before P2P launch also
releases buffers acquired by earlier batches in that timestep. Same-rank
V-schedule handoffs prepare and validate a complete buffer batch before assigning
any descriptor, so an invalid later input cannot strand earlier ownership.

Missing gradients are represented by missing tensor metadata at the schedule
boundary, so allocation and consumption are total over valid buffer states and
return `Tensor` rather than `Tensor | None`.

A buffer left owned after an incomplete step may still have P2P work writing to
it. Descriptor regeneration therefore fails closed across schedule modes:
callers must destroy the process group, then reconstruct the stages and schedule
before retrying. Recreating only a schedule or switching between train and eval
does not make the storage safe to reuse.

Received DTensors are reconstructed only after communication has completed, so
transferring ownership before reconstruction remains safe if reconstruction
fails. Effective gradient requirements are applied at consumption time.
Successful sequential, interleaved, V-shaped, and None-gradient schedules drain
every descriptor.

Test Plan:
- `python test/distributed/pipelining/test_schedule.py ScheduleTest.test_stage_recv_buffer_allocation_and_consumption ScheduleTest.test_recv_info_rejects_invalid_state_transitions ScheduleTest.test_stage_recv_construction_is_transactional ScheduleTest.test_same_rank_recv_assignment_is_transactional ScheduleTest.test_timestep_recv_validation_releases_prior_batches`
- `python test/distributed/pipelining/test_stage.py PipelineStageMetadataInferenceTest.test_recv_metadata_reinit_rejects_owned_buffers`
- `NCCL_DEBUG=WARN CUDA_VISIBLE_DEVICES=0,1,2,3 python test/distributed/pipelining/test_schedule_multiproc.py ScheduleTest.test_v_shape_schedules_schedule_class0 ScheduleTest.test_v_shape_schedules_schedule_class1 ScheduleTest.test_NoneGrad_conditional_input_grad_ScheduleClass0_pattern_first_false_then_true ScheduleTest.test_NoneGrad_conditional_input_grad_ScheduleClass1_pattern_first_true_then_false ScheduleTest.test_NoneGrad_conditional_input_grad_ScheduleClass2_pattern_first_false_then_true ScheduleTest.test_NoneGrad_conditional_input_grad_ScheduleClass2_pattern_first_true_then_false`
- `lintrunner --config=.lintrunner.toml torch/distributed/pipelining/_recv_buffers.py torch/distributed/pipelining/stage.py torch/distributed/pipelining/schedules.py test/distributed/pipelining/test_schedule.py test/distributed/pipelining/test_schedule_multiproc.py`

AI assistance disclosure:
> This change was authored with assistance from an AI coding tool and reviewed by the author.

[ghstack-poisoned]
[ghstack-poisoned]
`PipelineStage` previously allocated one activation and gradient receive buffer
for every microbatch during setup. Those tensors remained live for the entire
step, even though each receive destination only needs to exist from the receive
action until the corresponding stage computation takes ownership.

Allocate receive buffers immediately before posting each receive and transfer
the reference to compute when it is consumed. Keep the receive descriptor and
its ownership transitions in `_recv_buffers.py`; stage execution imports that
storage primitive and remains responsible for peer resolution and P2P operation
construction.

Resolve every source rank before taking ownership, and make allocation plus P2P
operation construction transactional within each receive batch. When a schedule
timestep contains multiple receive batches, a failure before P2P launch also
releases buffers acquired by earlier batches in that timestep. Same-rank
V-schedule handoffs prepare and validate a complete buffer batch before assigning
any descriptor, so an invalid later input cannot strand earlier ownership.

Missing gradients are represented by missing tensor metadata at the schedule
boundary, so allocation and consumption are total over valid buffer states and
return `Tensor` rather than `Tensor | None`.

A buffer left owned after an incomplete step may still have P2P work writing to
it. Descriptor regeneration therefore fails closed across schedule modes:
callers must destroy the process group, then reconstruct the stages and schedule
before retrying. Recreating only a schedule or switching between train and eval
does not make the storage safe to reuse.

Received DTensors are reconstructed only after communication has completed, so
transferring ownership before reconstruction remains safe if reconstruction
fails. Effective gradient requirements are applied at consumption time.
Successful sequential, interleaved, V-shaped, and None-gradient schedules drain
every descriptor.

Test Plan:
- `python test/distributed/pipelining/test_schedule.py ScheduleTest.test_stage_recv_buffer_allocation_and_consumption ScheduleTest.test_recv_info_rejects_invalid_state_transitions ScheduleTest.test_stage_recv_construction_is_transactional ScheduleTest.test_same_rank_recv_assignment_is_transactional ScheduleTest.test_timestep_recv_validation_releases_prior_batches`
- `python test/distributed/pipelining/test_stage.py PipelineStageMetadataInferenceTest.test_recv_metadata_reinit_rejects_owned_buffers`
- `NCCL_DEBUG=WARN CUDA_VISIBLE_DEVICES=0,1,2,3 python test/distributed/pipelining/test_schedule_multiproc.py ScheduleTest.test_v_shape_schedules_schedule_class0 ScheduleTest.test_v_shape_schedules_schedule_class1 ScheduleTest.test_NoneGrad_conditional_input_grad_ScheduleClass0_pattern_first_false_then_true ScheduleTest.test_NoneGrad_conditional_input_grad_ScheduleClass1_pattern_first_true_then_false ScheduleTest.test_NoneGrad_conditional_input_grad_ScheduleClass2_pattern_first_false_then_true ScheduleTest.test_NoneGrad_conditional_input_grad_ScheduleClass2_pattern_first_true_then_false`
- `lintrunner --config=.lintrunner.toml torch/distributed/pipelining/_recv_buffers.py torch/distributed/pipelining/stage.py torch/distributed/pipelining/schedules.py test/distributed/pipelining/test_schedule.py test/distributed/pipelining/test_schedule_multiproc.py`

AI assistance disclosure:
> This change was authored with assistance from an AI coding tool and reviewed by the author.

[ghstack-poisoned]
`PipelineStage` previously allocated one activation and gradient receive buffer
for every microbatch during setup. Those tensors remained live for the entire
step, even though each receive destination only needs to exist from the receive
action until the corresponding stage computation takes ownership.

Allocate receive buffers immediately before posting each receive and transfer
the reference to compute when it is consumed. Keep the receive descriptor and
its ownership transitions in `_recv_buffers.py`; stage execution imports that
storage primitive and remains responsible for peer resolution and P2P operation
construction.

Resolve every source rank before taking ownership, and make allocation plus P2P
operation construction transactional within each receive batch. When a schedule
timestep contains multiple receive batches, a failure before P2P launch also
releases buffers acquired by earlier batches in that timestep. Same-rank
V-schedule handoffs prepare and validate a complete buffer batch before assigning
any descriptor, so an invalid later input cannot strand earlier ownership.

Missing gradients are represented by missing tensor metadata at the schedule
boundary, so allocation and consumption are total over valid buffer states and
return `Tensor` rather than `Tensor | None`.

A buffer left owned after an incomplete step may still have P2P work writing to
it. Descriptor regeneration therefore fails closed across schedule modes:
callers must destroy the process group, then reconstruct the stages and schedule
before retrying. Recreating only a schedule or switching between train and eval
does not make the storage safe to reuse.

Received DTensors are reconstructed only after communication has completed, so
transferring ownership before reconstruction remains safe if reconstruction
fails. Effective gradient requirements are applied at consumption time.
Successful sequential, interleaved, V-shaped, and None-gradient schedules drain
every descriptor.

Test Plan:
- `python test/distributed/pipelining/test_schedule.py ScheduleTest.test_stage_recv_buffer_allocation_and_consumption ScheduleTest.test_recv_info_rejects_invalid_state_transitions ScheduleTest.test_stage_recv_construction_is_transactional ScheduleTest.test_same_rank_recv_assignment_is_transactional ScheduleTest.test_timestep_recv_validation_releases_prior_batches`
- `python test/distributed/pipelining/test_stage.py PipelineStageMetadataInferenceTest.test_recv_metadata_reinit_rejects_owned_buffers`
- `NCCL_DEBUG=WARN CUDA_VISIBLE_DEVICES=0,1,2,3 python test/distributed/pipelining/test_schedule_multiproc.py ScheduleTest.test_v_shape_schedules_schedule_class0 ScheduleTest.test_v_shape_schedules_schedule_class1 ScheduleTest.test_NoneGrad_conditional_input_grad_ScheduleClass0_pattern_first_false_then_true ScheduleTest.test_NoneGrad_conditional_input_grad_ScheduleClass1_pattern_first_true_then_false ScheduleTest.test_NoneGrad_conditional_input_grad_ScheduleClass2_pattern_first_false_then_true ScheduleTest.test_NoneGrad_conditional_input_grad_ScheduleClass2_pattern_first_true_then_false`
- `lintrunner --config=.lintrunner.toml torch/distributed/pipelining/_recv_buffers.py torch/distributed/pipelining/stage.py torch/distributed/pipelining/schedules.py test/distributed/pipelining/test_schedule.py test/distributed/pipelining/test_schedule_multiproc.py`

AI assistance disclosure:
> This change was authored with assistance from an AI coding tool and reviewed by the author.

[ghstack-poisoned]
`PipelineStage` previously allocated one activation and gradient receive buffer
for every microbatch during setup. Those tensors remained live for the entire
step, even though each receive destination only needs to exist from the receive
action until the corresponding stage computation takes ownership.

Allocate receive buffers immediately before posting each receive and transfer
the reference to compute when it is consumed. Keep the receive descriptor and
its ownership transitions in `_recv_buffers.py`; stage execution imports that
storage primitive and remains responsible for peer resolution and P2P operation
construction.

Resolve every source rank before taking ownership, and make allocation plus P2P
operation construction transactional within each receive batch. When a schedule
timestep contains multiple receive batches, a failure before P2P launch also
releases buffers acquired by earlier batches in that timestep. Same-rank
V-schedule handoffs prepare and validate a complete buffer batch before assigning
any descriptor, so an invalid later input cannot strand earlier ownership.

Missing gradients are represented by missing tensor metadata at the schedule
boundary, so allocation and consumption are total over valid buffer states and
return `Tensor` rather than `Tensor | None`.

A buffer left owned after an incomplete step may still have P2P work writing to
it. Descriptor regeneration therefore fails closed across schedule modes:
callers must destroy the process group, then reconstruct the stages and schedule
before retrying. Recreating only a schedule or switching between train and eval
does not make the storage safe to reuse.

Received DTensors are reconstructed only after communication has completed, so
transferring ownership before reconstruction remains safe if reconstruction
fails. Effective gradient requirements are applied at consumption time.
Successful sequential, interleaved, V-shaped, and None-gradient schedules drain
every descriptor.

Test Plan:
- `python test/distributed/pipelining/test_schedule.py ScheduleTest.test_stage_recv_buffer_allocation_and_consumption ScheduleTest.test_recv_info_rejects_invalid_state_transitions ScheduleTest.test_stage_recv_construction_is_transactional ScheduleTest.test_same_rank_recv_assignment_is_transactional ScheduleTest.test_timestep_recv_validation_releases_prior_batches`
- `python test/distributed/pipelining/test_stage.py PipelineStageMetadataInferenceTest.test_recv_metadata_reinit_rejects_owned_buffers`
- `NCCL_DEBUG=WARN CUDA_VISIBLE_DEVICES=0,1,2,3 python test/distributed/pipelining/test_schedule_multiproc.py ScheduleTest.test_v_shape_schedules_schedule_class0 ScheduleTest.test_v_shape_schedules_schedule_class1 ScheduleTest.test_NoneGrad_conditional_input_grad_ScheduleClass0_pattern_first_false_then_true ScheduleTest.test_NoneGrad_conditional_input_grad_ScheduleClass1_pattern_first_true_then_false ScheduleTest.test_NoneGrad_conditional_input_grad_ScheduleClass2_pattern_first_false_then_true ScheduleTest.test_NoneGrad_conditional_input_grad_ScheduleClass2_pattern_first_true_then_false`
- `lintrunner --config=.lintrunner.toml torch/distributed/pipelining/_recv_buffers.py torch/distributed/pipelining/stage.py torch/distributed/pipelining/schedules.py test/distributed/pipelining/test_schedule.py test/distributed/pipelining/test_schedule_multiproc.py`

AI assistance disclosure:
> This change was authored with assistance from an AI coding tool and reviewed by the author.

[ghstack-poisoned]
@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Starting merge as part of PR stack under #196706

`PipelineStage` previously allocated one activation and gradient receive buffer
for every microbatch during setup. Those tensors remained live for the entire
step, even though each receive destination only needs to exist from the receive
action until the corresponding stage computation takes ownership.

Allocate receive buffers immediately before posting each receive and transfer
the reference to compute when it is consumed. Keep the receive descriptor and
its ownership transitions in `_recv_buffers.py`; stage execution imports that
storage primitive and remains responsible for peer resolution and P2P operation
construction.

Resolve every source rank before taking ownership, and make allocation plus P2P
operation construction transactional within each receive batch. When a schedule
timestep contains multiple receive batches, a failure before P2P launch also
releases buffers acquired by earlier batches in that timestep. Same-rank
V-schedule handoffs prepare and validate a complete buffer batch before assigning
any descriptor, so an invalid later input cannot strand earlier ownership.

Missing gradients are represented by missing tensor metadata at the schedule
boundary, so allocation and consumption are total over valid buffer states and
return `Tensor` rather than `Tensor | None`.

A buffer left owned after an incomplete step may still have P2P work writing to
it. Descriptor regeneration therefore fails closed across schedule modes:
callers must destroy the process group, then reconstruct the stages and schedule
before retrying. Recreating only a schedule or switching between train and eval
does not make the storage safe to reuse.

Received DTensors are reconstructed only after communication has completed, so
transferring ownership before reconstruction remains safe if reconstruction
fails. Effective gradient requirements are applied at consumption time.
Successful sequential, interleaved, V-shaped, and None-gradient schedules drain
every descriptor.

Test Plan:
- `python test/distributed/pipelining/test_schedule.py ScheduleTest.test_stage_recv_buffer_allocation_and_consumption ScheduleTest.test_recv_info_rejects_invalid_state_transitions ScheduleTest.test_stage_recv_construction_is_transactional ScheduleTest.test_same_rank_recv_assignment_is_transactional ScheduleTest.test_timestep_recv_validation_releases_prior_batches`
- `python test/distributed/pipelining/test_stage.py PipelineStageMetadataInferenceTest.test_recv_metadata_reinit_rejects_owned_buffers`
- `NCCL_DEBUG=WARN CUDA_VISIBLE_DEVICES=0,1,2,3 python test/distributed/pipelining/test_schedule_multiproc.py ScheduleTest.test_v_shape_schedules_schedule_class0 ScheduleTest.test_v_shape_schedules_schedule_class1 ScheduleTest.test_NoneGrad_conditional_input_grad_ScheduleClass0_pattern_first_false_then_true ScheduleTest.test_NoneGrad_conditional_input_grad_ScheduleClass1_pattern_first_true_then_false ScheduleTest.test_NoneGrad_conditional_input_grad_ScheduleClass2_pattern_first_false_then_true ScheduleTest.test_NoneGrad_conditional_input_grad_ScheduleClass2_pattern_first_true_then_false`
- `lintrunner --config=.lintrunner.toml torch/distributed/pipelining/_recv_buffers.py torch/distributed/pipelining/stage.py torch/distributed/pipelining/schedules.py test/distributed/pipelining/test_schedule.py test/distributed/pipelining/test_schedule_multiproc.py`

AI assistance disclosure:
> This change was authored with assistance from an AI coding tool and reviewed by the author.

[ghstack-poisoned]
@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Starting merge as part of PR stack under #196706

pytorchmergebot pushed a commit that referenced this pull request Sep 22, 2026
…6464)

Pipeline runtimes and memory planners need a deterministic way to bound the storage retained from forward through backward. Expose a schedule analysis that derives inclusive activation lifetimes and assigns the lowest reusable logical slot without allocating storage.

A forward action starts a lifetime. Full backward releases it; for split backward, input backward leaves the activation live and weight backward releases it. The result supports independent stage/microbatch lifetimes or one conservative lifetime per microbatch across selected virtual stages. It exposes the `(stage_index, microbatch_index) -> slot_id` mapping and the effective lifetime behind each assignment.

The greedy interval coloring remains deterministic and minimal for interval graphs. Tests use an independent overlap oracle, prove the input-versus-weight-backward release boundary, cover both granularities, and exercise compound actions and the real DualPipeV schedule.

Test Plan:
- `python test/distributed/pipelining/test_schedule.py -k pipeline_activation_liveness`
- `python test/distributed/pipelining/test_schedule.py`
- `lintrunner --config=.lintrunner.toml torch/distributed/pipelining/schedules.py torch/distributed/pipelining/__init__.py test/distributed/pipelining/test_schedule.py docs/source/distributed.pipelining.md`
- Strict Sphinx build of `docs/source/distributed.pipelining.md`

AI assistance disclosure:
> This change was authored with assistance from an AI coding tool and reviewed by the author.
Pull Request resolved: #196464
Approved by: https://github.com/SherlockNoMad
ghstack dependencies: #196460, #196461, #196956, #196462, #196463
pytorchmergebot pushed a commit that referenced this pull request Sep 22, 2026
`ProcessGroup::splitGroup` cloned the rendezvous Store for every child process
group. Pipeline schedules can create hundreds of directed child communicators,
turning those clones into hundreds of TCPStore connections per rank. This also
differs from `new_group()`, whose sibling groups have long used uniquely
prefixed namespaces over one shared Store connection.

Construct each child namespace directly over the parent Store and pass that
prefixed Store through `Backend::split`. Prefixes preserve key isolation while
the backend owns connection isolation. Backends that perform blocking
rendezvous or mutate connection-global state such as the timeout must clone the
Store first.

The nccl2 and nccl-legacy split implementations retain the supplied Store
because both initialize the child communicator with `ncclCommSplit` before
returning. nccl2 deliberately does not inherit `enable_reconfigure`, whose
blocking rendezvous is incompatible with the shared connection. Legacy NCCL
merge remains the narrow backend-owned exception: it returns an uninitialized
child whose first collective may block in `broadcastUniqueNCCLID()`, so it keeps
an independent connection. Gloo likewise preserves its construction-time
clone.

The parent and NCCL split children now share live connection-global state. In
particular, changing a child Store timeout affects its parent and siblings, and
opt-in NCCL error-propagation polling shares that connection. Hybrid children
still open a connection for their Gloo leg, while nested NCCL splits add only
namespaces and no new Store connections.

Add CPU boundary coverage for the exact prefixed Store identity and clone count,
plus Gloo option preservation and a legacy NCCL regression that pins the
retained merge clone. Existing legacy NCCL and nccl2 split tests cover
successful communication.

Test Plan:
- `python test/distributed/test_c10d_common.py SplitGroupOptionsTest.test_split_group_passes_prefixed_parent_store_to_backend SplitGroupOptionsTest.test_split_group_clones_parent_options SplitGroupOptionsTest.test_split_group_opts_apply_to_default_backend_only`
- `python test/distributed/test_c10d_gloo.py CommTest.test_split_group_keeps_gloo_options`
- `python test/distributed/test_c10d_nccl.py ProcessGroupNCCLGroupTest.test_merge_group_clones_store_for_uninitialized_child ProcessGroupNCCLGroupTest.test_comm_split_group_backend_filter`
- `python test/distributed/test_c10d_nccl2.py ProcessGroupNCCL2ObservabilityTest.test_split_group_child_global_ranks`
- `lintrunner --config=.lintrunner.toml test/distributed/test_c10d_common.py test/distributed/test_c10d_gloo.py test/distributed/test_c10d_nccl.py torch/csrc/distributed/c10d/Backend.hpp torch/csrc/distributed/c10d/ProcessGroup.cpp torch/csrc/distributed/c10d/ProcessGroupNCCL.cpp torch/csrc/distributed/c10d/nccl2/ProcessGroupNCCL.cpp torch/distributed/distributed_c10d.py`

AI assistance disclosure:
> This change was authored with assistance from an AI coding tool and reviewed by the author.
Pull Request resolved: #196665
Approved by: https://github.com/d4l3k
ghstack dependencies: #196460, #196461, #196956, #196462, #196463, #196464
pytorchmergebot pushed a commit that referenced this pull request Sep 22, 2026
Pipeline schedules can issue communication for several logical stages from one
physical rank. When unrelated edges share one communicator FIFO, skew between
looped schedule ranks can create cross-edge ordering cycles. Construct the P2P
communicators only after the schedule has finalized its logical-stage placement,
then isolate every used direction of every physical edge.

| Concern | Before | After |
| --- | --- | --- |
| Communicator ownership | Pipeline traffic shared the parent communicator or groups derived before final placement. | The finalized stage-to-rank assignment determines one child per directed physical edge. |
| Direction identity | A peer or broad forward/backward direction did not uniquely identify the FIFO. | Children are keyed by `(source_group_rank, destination_group_rank)`. |
| Virtual stages | Repeated stage-level setup obscured whether every local stage used one complete map. | The schedule validates all local stages, builds once, and attaches one shared map. |
| First P2P use | A transport path could first be exercised during model execution or capture. | Every directed child is preconnected once during schedule initialization. |
| Dynamic metadata | Metadata always used the shared parent group. | Metadata follows the same directed child as the corresponding stage edge. |
| Lifecycle | P2P readiness was inferred from forward-metadata initialization. | The schedule tracks P2P initialization independently from metadata reinference. |
| Terminology | “Warmup” referred to metadata voting, communicator setup, and model warmup. | Parent initialization, child splitting, P2P preconnection, and runtime model warmup are distinct. |

| Component | Responsibility | Does not own |
| --- | --- | --- |
| Pipeline schedule | Validate the finalized assignment and orchestrate one-time setup. | Individual runtime `P2POp` construction. |
| `_p2p.py` | Validate stage placement, derive split rounds, create/cache children, and preconnect their P2P paths. | Model metadata policy. |
| Pipeline stage | Resolve a logical source/destination to its child and construct runtime operations. | Process-group creation. |
| Parent process group | Setup agreement and collective source for `split_group`. | Directed activation or gradient traffic when per-edge mode is enabled. |
| Directed child | One physical source-to-destination FIFO. | CUDA-graph or model warmup policy. |
| Outer runtime | Model warmup, CUDA-graph capture, and replay. | PP group construction or first-use transport setup. |

| Frontend and metadata mode | Agreement | P2P setup |
| --- | --- | --- |
| Manual, static | Reduce local static capability over the parent. | Create and preconnect directed children. |
| Manual, dynamic | Reduce the dynamic requirement over the parent. | Use the same children; exchange inferred metadata through them. |
| Traced | Metadata is already available from tracing. | Initialize the parent, then create and preconnect the same children. |
| Fake process group, static | Validate the local static contract. | Build only the logical edge map; perform no real communication. |
| Fake process group, dynamic | Reject with an actionable diagnostic. | A fake group cannot exchange runtime metadata. |

Derive the physical rank assigned to every logical stage, collapse repeated
logical adjacencies onto physical rank pairs, and partition those pairs into
deterministic disjoint matchings. Each matching becomes one collective
`split_group` round; the reverse direction is a separate round and communicator.
For PP4/VPP2 placement `(0, 1, 2, 3, 0, 1, 2, 3)`, eight directed children are
created in four split calls.

Initialize the stage-device backend before splitting. Homogeneous parents retain
their complete backend configuration. Mixed parents select only the stage-device
backend when that selection preserves the parent's default backend type;
otherwise the child retains every required backend. Native children inherit the
selected parent backend's timeout, while TorchComms delegates split capability
and timeout policy to `split_group`.

`ProcessGroupNCCL::split()` eagerly creates the child communicator through
`ncclCommSplit`. The subsequent one-element P2P exchange is therefore described
as preconnection: it exercises each actual directed send/receive path in a
deterministic order before execution or graph capture. It is not a second model
warmup and does not depend on TorchTitan.

The group map is cached by parent, complete stage-rank assignment, and stage
device type. All local virtual stages share the same map. Full process-group
teardown owns the lifetime of real children. Same-rank turns remain local and do
not create a child.

`pipeline_per_edge_p2p` remains disabled by default and is auto-enabled for
TorchComms. The existing shared-parent path remains unchanged when the option is
disabled. Fake groups retain assignment validation without creating real
children.

This implementation derives connectors only between successive logical stages.
Long-range skip connections remain unsupported in per-edge mode; supporting
them requires deriving connectors from finalized schedule actions rather than
silently falling back to the parent communicator.

- `python test/distributed/pipelining/test_schedule.py`
- `python test/distributed/pipelining/test_stage.py`
- `python test/distributed/pipelining/test_schedule.py P2PEdgeGroupTest`
- `CUDA_VISIBLE_DEVICES=0,1,2,3 python test/distributed/pipelining/test_schedule_multiproc.py PerEdgeScheduleTest`
- `lintrunner --config=.lintrunner.toml torch/distributed/config.py torch/distributed/pipelining/_p2p.py torch/distributed/pipelining/schedules.py torch/distributed/pipelining/stage.py test/distributed/pipelining/test_stage.py test/distributed/pipelining/test_schedule.py test/distributed/pipelining/test_schedule_multiproc.py`
- Strict Sphinx HTML and coverage builds for `distributed.pipelining`.

AI assistance disclosure:
> This change was authored with assistance from an AI coding tool and reviewed by the author.
Pull Request resolved: #196666
Approved by: https://github.com/SherlockNoMad
ghstack dependencies: #196460, #196461, #196956, #196462, #196463, #196464, #196665
pytorchmergebot pushed a commit that referenced this pull request Sep 22, 2026
Pipeline initialization previously used different protocols depending on the
stage frontend and eventual metadata mode. Manual stages used a two-pass ring
whose traffic also initialized raw pairwise P2P communicators. Traced stages
used a mixed dummy-operation batch that initialized the parent communicator.
Dynamic metadata exchange happened to initialize that parent path again, while
static metadata skipped it. Correct communicator readiness therefore depended
on incidental control flow.

Replace those protocols with one explicit setup sequence. Real cross-rank
schedules reduce the local static-metadata capability over the parent group,
which both determines the global metadata mode and initializes the parent
communicator. Directed mode then creates and preconnects its child groups.
For shared mode, the all-reduce initializes the parent communicator used by
batched P2P, then raw P2P explicitly initializes the pairwise communicators.

## Before and after

| Concern | Before | After |
| --- | --- | --- |
| Manual metadata agreement | Forward ring plus backward result propagation | One parent `all_reduce(MIN)` |
| Manual P2P setup | Hidden side effect of the vote ring | Explicit shared or directed preconnection |
| Traced P2P setup | Separate mixed dummy-operation batch | Same setup protocol as manual stages |
| Static metadata | Could skip initialization of the batched parent path | Both shared-parent paths are exercised before execution |
| Dynamic metadata | Parent readiness depended partly on metadata exchange | Metadata mode no longer controls communicator readiness |
| Eval/train transition | P2P completion inferred from forward metadata state | Explicit schedule-owned P2P initialization state |
| Local stage placement | Multiple local stages had no explicit device invariant. | Every stage owned by one PP rank must use the same device. |

## Responsibility boundaries

| Component | Responsibility |
| --- | --- |
| Schedule | Compute local metadata capability, perform one global agreement, and invoke one-time transport setup. |
| `_p2p.py` | Derive deterministic communication rounds and preconnect the selected transport. |
| Stage | Resolve peers and construct runtime operations; it no longer implements setup protocols. |
| Parent group | Carry setup agreement and shared batched P2P. |
| Pairwise raw path | Carry homogeneous shared-parent P2P on lazy native backends. |
| Directed child | Carry one isolated physical source-to-destination FIFO when per-edge mode is enabled. |

## Behavior by mode

| Frontend and mode | Metadata agreement | One-time communication setup |
| --- | --- | --- |
| Manual, static | Reduce each rank's local static capability with parent `all_reduce(MIN)`. | Initialize the parent group path, then preconnect shared raw edges or directed children. |
| Manual, dynamic | The same reduction selects dynamic mode when any stage requires inference. | Identical to static mode; later metadata transfer does not initialize communicators incidentally. |
| Traced | No metadata-mode decision is needed. | Run one parent all-reduce for readiness, then the same shared or directed preconnection. |
| FakePG, static | Validate complete metadata locally because fake collectives do not exchange values. | Build the logical directed map when requested; issue no real communication. |
| FakePG, dynamic | Reject cross-rank dynamic inference with an actionable error. | No transport setup can make fake metadata exchange real. |
| Local-only schedule | Decide manual metadata mode locally. | Require no process group and issue no P2P setup. |

## Shared-parent setup

Collapse repeated logical-stage adjacencies onto unique unordered physical-rank
pairs. Partition those pairs into deterministic disjoint matchings. For each
local pair, issue one canonical raw P2P exchange on the rank's shared stage
device; the lazy pair channel is bidirectional and carries later forward and
backward traffic. Use a parent collective to align all ranks before the next
matching. Together with the initial parent all-reduce, this covers both
communicator-selection paths without redundant batched dummy traffic or
reliance on metadata inference.

The setup is run once per schedule. Static/dynamic transitions may repeat
metadata agreement but do not repeat transport setup. Local-only schedules do
not require a process group. Cross-rank FakePG remains static-only and performs
no real preconnection.

## Removed machinery

- The manual forward vote ring and backward result propagation.
- The traced-stage neighbor dummy-operation builder.
- The `stage_backend_initialized` bookkeeping flag.
- The inference that P2P readiness is equivalent to forward-metadata readiness.
- Mode-specific reliance on metadata transfer to initialize communication.

`pipeline_per_edge_p2p` remains disabled by default. Shared-parent mode,
backends without `split_group`, FakePG, manual/traced stages, and static/dynamic
metadata retain their existing capabilities.

## Test Plan

- `python test/distributed/pipelining/test_schedule.py`
- `python test/distributed/pipelining/test_stage.py`
- `CUDA_VISIBLE_DEVICES=0,1,2,3 python test/distributed/pipelining/test_schedule_multiproc.py NCCLLazyP2PInitializationTest`
- `NCCL_DEBUG=WARN CUDA_VISIBLE_DEVICES=0,1,2,3 python test/distributed/pipelining/test_schedule_multiproc.py`
- `lintrunner --config=.lintrunner.toml torch/distributed/pipelining/_p2p.py torch/distributed/pipelining/schedules.py torch/distributed/pipelining/stage.py test/distributed/pipelining/test_schedule.py test/distributed/pipelining/test_schedule_multiproc.py`
- Strict Sphinx HTML and coverage builds for `distributed.pipelining`.

AI assistance disclosure:
> This change was authored with assistance from an AI coding tool and reviewed by the author.
Pull Request resolved: #197488
Approved by: https://github.com/SherlockNoMad
ghstack dependencies: #196460, #196461, #196956, #196462, #196463, #196464, #196665, #196666
pytorchmergebot pushed a commit that referenced this pull request Sep 22, 2026
An asynchronous FSDP unshard is not free GPU work. It includes casts or
quantization before the collective, copy-in and packing, the all-gather itself,
copy-out, and post-all-gather parameter preparation. Issuing every eligible
unshard at the start of a pipeline step can therefore place non-critical work
in front of useful forward compute. The rank-aware policy in this PR estimates
how much preparation each pipeline rank's startup bubble can absorb, while
retaining an explicit per-rank override for models whose measured balance is
different.

The following detailed design and verification summary was prepared with Codex
and reviewed by the author:

> ## Problem
>
> Pipeline schedule lowering previously used `max_active_stages` for two
> independent decisions:
>
> 1. how many local FSDP stages should remain resident; and
> 2. how far ahead asynchronous unshards should be issued.
>
> Reducing `max_active_stages` to avoid an initial burst is not equivalent to
> reducing prefetch: it also changes eviction and can introduce additional
> unshard/reshard residency episodes. This PR separates those policies.
>
> | Concern | Before | After |
> | --- | --- | --- |
> | Parameter residency | `max_active_stages` | `max_active_stages` |
> | `RESHARD` placement | Derived from the residency window | Unchanged |
> | Unshard issue distance | Also `max_active_stages` | Independent `unshard_lookahead` |
> | Compatibility | Full residency window is prefetched | `"full"` preserves that behavior |
> | Expert tuning | Required rewriting schedule actions | One value per PP rank in a tuple |
>
> ## Why asynchronous unshards still need scheduling
>
> `async_op=True` avoids a host-side wait. It does not remove the GPU work or
> resource dependencies needed to make a parameter usable:
>
> ```text
> pre-all-gather cast or quantization
>   -> copy-in and packing
>   -> NCCL all-gather
>   -> copy-out
>   -> post-all-gather quantization or layout preparation
>   -> parameter ready
> ```
>
> These operations use GPU execution, memory bandwidth, collective resources,
> temporary storage, and stream synchronization. Over-prefetching can therefore
> contend with the forward it is intended to overlap.
>
> ## Rank-aware `"auto"` rationale
>
> Let a balanced stage forward take `F`, and let the composite critical-path
> cost of preparing one stage's unsharded parameters take `U`. Ignoring PP
> transfer latency, PP rank `r` cannot begin its first useful forward before
> approximately `U + rF`: rank zero first exposes its current stage's unshard,
> and each upstream rank then contributes one forward.
>
> Approximately `floor((U + rF) / U)` unshards can complete during that startup
> interval. Issuing one additional unshard lets the next preparation overlap
> the rank's first forward. Under the simplifying balanced assumption
> `F = U = T`, this gives `r + 2`, capped by the residency window.
>
> ```text
> interval           | 0..T    | T..2T   | 2T..3T  | 3T..4T  | 4T..5T
> -------------------+---------+----------+----------+----------+---------
> rank 0 forward     | blocked | F(first) |          |          |
> rank 0 preparation | U0      | U1       |          |          |  => 2
>
> rank 1 forward     | blocked | blocked  | F(first) |          |
> rank 1 preparation | U0      | U1       | U2       |          |  => 3
>
> rank 2 forward     | blocked | blocked  | blocked  | F(first) |
> rank 2 preparation | U0      | U1       | U2       | U3       |  => 4
>
> rank 3 forward     | blocked | blocked  | blocked  | blocked  | F(first)
> rank 3 preparation | U0      | U1       | U2       | U3       |  => 4
> ```
>
> For PP4 with `max_active_stages=4`, `"auto"` therefore resolves to
> `(2, 3, 4, 4)`. Rank zero issues its current and next stage; each downstream
> rank receives one additional stage of lookahead until the residency cap.
> This applies throughout lowering, not only during warmup.
>
> `Uk` denotes preparation of the kth upcoming rank-local stage, not a global
> stage index. Vertically aligned preparation and forward cells are intended to
> overlap. The diagram is an analytical starting point, not an exact
> CUDA-stream model.
> Real stages may be unbalanced, unshard phases may overlap only partially, and
> network or memory-bandwidth contention can change the best distance. `"auto"`
> is consequently a deterministic preset, not a schedule-derived optimizer or
> a universal performance guarantee.
>
> ## Policy contract
>
> | Policy | Resolution on PP rank `r` | Use |
> | --- | --- | --- |
> | `"full"` | `max_active_stages` | PyTorch compatibility default matching the original full-window behavior. |
> | `"auto"` | `min(r + 2, max_active_stages)` | Startup-bubble estimate when recipe-level tuning is unavailable. |
> | `tuple[int, ...]` | Exact value at index `r` | Expert tuning for measured model, topology, and fabric behavior. |
>
> Tuple length must equal the PP degree, and every entry must be in
> `[1, max_active_stages]`. A custom compute-only schedule can be combined with
> a tuple before lowering. A pre-lowered `compute_comms` schedule may encode
> exact `UNSHARD` placement directly and cannot be retuned by this option.
>
> ## Lowering and correctness
>
> At each compute position, lowering scans the remaining compute actions twice:
>
> ```text
> resident = next distinct stages up to max_active_stages
> prefetch = next distinct stages up to unshard_lookahead[rank]
>
> reshard stages outside resident
> unshard stages newly entering prefetch
> emit the original compute action
> ```
>
> The correctness invariants are:
>
> - `prefetch` is a prefix of `resident`, so a prefetched stage is not
>   immediately evicted.
> - The current compute action's stages are always included, so lookahead one
>   remains correct even though its all-gather may be exposed.
> - `max_active_stages` alone determines residency episodes and `RESHARD`
>   placement.
> - Changing lookahead adds or removes no collective and does not change the
>   compute-action order.
> - Active-stage insertion order makes eviction deterministic.
> - `OVERLAP_F_B` is atomic: all stages in the compound action are prepared
>   together. Such an action may extend a scan window by up to its number of
>   stages minus one, and `ScheduleDualPipeV` rejects
>   `max_active_stages=1` because its current compound action requires two.
>
> Unshards are inserted before communication lowering. Their different issue
> positions can therefore move the absolute indices of P2P actions. Tests prove
> that the P2P multiset and dependency-valid ordering remain correct and that
> receive-buffer slot assignments remain unchanged for the covered schedules.
>
> The policy is supported by Looped BFS, Interleaved 1F1B, Interleaved Zero
> Bubble, ZBV Zero Bubble, and DualPipeV.
>
> This PR does not claim that `"auto"` is universally faster. PyTorch keeps
> `"full"` as the compatibility default, and applications should benchmark an
> explicit tuple against their model, topology, and communication stack.
>
> ## Verification
>
> - Resolver tests cover `"full"`, `"auto"`, explicit tuples, invalid types,
>   wrong lengths, and out-of-range values.
> - Lowering goldens cover steady-state placement and atomic compound actions.
> - All five schedule families preserve compute order, collective counts,
>   `RESHARD` placement, communication validity, and receive-buffer slots.
> - A live four-GPU `(dp, pp)=(2, 2)` FSDP test proves `"full"` and `(1, 1)`
>   produce matching output, loss, and nonzero local sharded gradients while
>   exercising different unshard placements.
>
> Test Plan:
>
> - `python test/distributed/pipelining/test_schedule.py`
> - `NCCL_DEBUG=WARN CUDA_VISIBLE_DEVICES=0,1,2,3 python test/distributed/pipelining/test_schedule_multiproc.py`
> - `lintrunner --config=.lintrunner.toml torch/distributed/pipelining/schedules.py test/distributed/pipelining/test_schedule.py test/distributed/pipelining/test_schedule_multiproc.py docs/source/distributed.pipelining.md`
> - Strict Sphinx HTML and coverage builds of `distributed.pipelining`.
Pull Request resolved: #196706
Approved by: https://github.com/SherlockNoMad
ghstack dependencies: #196460, #196461, #196956, #196462, #196463, #196464, #196665, #196666, #197488
akoumpa added a commit to NVIDIA-NeMo/Automodel that referenced this pull request Nov 18, 2026
PyTorch 2.15 in the 26.11 base (pytorch/pytorch#196463) allocates each
pipeline receive buffer just before its receive and hands it to the stage
computation, instead of preallocating one buffer set per microbatch. The
opt-in recv-buffer pools then have nothing to save: the ordinary 1F1B ring
aliases receive descriptors that no longer own long-lived buffers, and the
interleaved pool's owned copies only add memory. Both installers now keep
the stock buffers when torch.distributed.pipelining._recv_buffers exists.

The pool unit tests pin the probe for the fake stage layouts, skip the
real-PyTorch parity and negative-control runs under just-in-time buffers
(the negative control can no longer corrupt a reused buffer), and the
interleaved schedule harness sets the PyTorch 2.15 runtime defaults it
skips by bypassing __init__ (_unshard_lookahead, _defer_reduce_grad_wait,
_max_outstanding_sends).

Signed-off-by: Alexandros Koumparoulis <[email protected]>
akoumpa added a commit to NVIDIA-NeMo/Automodel that referenced this pull request Nov 19, 2026
* build: bump container to 26.11

Move the PyTorch base to nvcr.io/nvidia/pytorch:26.11-py3 (CUDA 13.5,
PyTorch 2.15.0a0+fd23299, cuDNN 9.28, cuBLAS 13.10, NCCL 2.32.6) and the
CUDA base to cuda-dl-base:26.11-cuda13.5-devel-ubuntu24.04.

Align the PyTorch-container overrides with the 26.11 base: platformdirs
4.12.4 -> 4.14.5 (the base registers its pytest plugin). cuDNN Frontend
stays at 1.30.0: the base's 1.32.0 requires nvidia-cutlass-dsl>=4.8 while
FA4, quack-kernels and ffpa pin 4.6.2. uv-pytorch.lock is regenerated
with uv 0.8.22; only platformdirs changes.

Signed-off-by: Alexandros Koumparoulis <[email protected]>

* build(docker): drop the NVGEMM backport now that the base includes it

The 26.11 PyTorch base already contains PyTorch #198292: the backport
patch reverse-applies cleanly to its torch/_inductor/utils.py. Remove the
patch and its apply step, as its header asked once PYTORCH_IMAGE includes
the fix, and keep the import check that the NVGEMM probe tolerates the
FA4/FFPA-compatible CuTe DSL.

Signed-off-by: Alexandros Koumparoulis <[email protected]>

* build: build Transformer Engine 2.21.0 in the container

Match the 26.11 base, which ships Transformer Engine 2.21.0. Build TE
from v2.21.0, reuse a base TE only from 2.21.0 on, and require 2.21.0 in
the PyTorch image's native-runtime check.

TE 2.21.0 keeps 2.20.2's runtime requirements (nvidia-cudnn-frontend
>=1.29.0), its FusedAdam implementation that te_patches.py caches is
unchanged, and its EP module exports the same NCCL-EP API.

Signed-off-by: Alexandros Koumparoulis <[email protected]>

* build(docker): patch fla's autotune keys for Triton 3.9

Triton 3.9 in the 26.11 base rejects a triton.autotune key that names a
value which is not a kernel argument. fla-core 0.4.2 has two such keys in
fla/ops/cp/chunk_delta_h.py ("STAGE"; "BT" and "USE_EXP2"), so importing
fla failed with "key contains names that are not kernel arguments". The
import runs from nemo_automodel._transformers.infrastructure through the
Kimi K3 model, so every recipe failed at startup in the 26.11 nightly.

Earlier Triton dropped the unknown names, so the patch removes them and
keeps the same tuning keys. The image build applies it to the installed
fla or confirms it is already applied, and rejects any other source. A
scan of all 212 autotune name lists in fla-core 0.4.2 finds no others,
and Automodel's own kernels have none.

Signed-off-by: Alexandros Koumparoulis <[email protected]>

* build: move flash-linear-attention to 0.5.2 for Triton 3.9

Triton 3.9 in the 26.11 base removed block pointers: tl.make_block_ptr
and tl.advance now raise NotImplementedError when a kernel compiles.
fla 0.4.2 uses them in 77 files, so its kernels fail at the first launch
(qwen3_5_4b, qwen3_5_35b and nemotron_flash_1b_squad in the 26.11
nightly, on H100 and VR200). fla 0.5.2 is the first release that no
longer uses them (fla-org/flash-linear-attention#1062).

- pyproject.toml: flash-linear-attention>=0.5.2,<0.6. The upper bound
  keeps the lock on the release that the container patch and the CP
  prewarm launches below were written against.
- docker/common/fla-autotune-keys.patch: retarget to fla-core 0.5.2.
  Its merge_fwd_bwd_kernel autotune key still names "BT", which is not
  a kernel argument and which Triton 3.9 rejects at import. The 0.4.2
  keys are gone.
- prewarm.py: fla 0.5.2 renamed the head arguments of the private CP
  kernels (H -> HV in merge_fwd_bwd_kernel; HV added to
  pre_process_bwd_kernel_merged) and replaced USE_EXP2 with USE_BG.
  Without this the prewarm logs a signature drift and skips.

Signed-off-by: Alexandros Koumparoulis <[email protected]>

* Update uv lock

Signed-off-by: NeMo Bot <[email protected]>

* fix(moe): skip FSDP's root callback once the backward is finalized

PyTorch 2.15 in the 26.11 base (pytorch/pytorch#196640 and its stack)
records the backward finalization mode when FSDP sees a backward start,
clears it when the root post-backward final callback ends the iteration,
and asserts in that callback that the mode is set.

The pipeline-parallel backward patch calls that private callback by hand.
The MoE path calls it once per FSDP unit, but the units of a stage share
the root's state context, so the second call failed with "Expected
manual backward finalization mode to be set" (step_3.5_flash_hellaswag_pp
in the 26.11 nightly). The same assertion fires when FSDP's own callback
already finalized a last backward under defer_fsdp_grad_sync: false.

Skip the manual callback when the mode is cleared: the iteration is
already finalized, or no backward reached the root. Earlier PyTorch has
no such field, so its behavior is unchanged.

Signed-off-by: Alexandros Koumparoulis <[email protected]>

* fix(pipelining): keep stock recv buffers when PyTorch allocates them JIT

PyTorch 2.15 in the 26.11 base (pytorch/pytorch#196463) allocates each
pipeline receive buffer just before its receive and hands it to the stage
computation, instead of preallocating one buffer set per microbatch. The
opt-in recv-buffer pools then have nothing to save: the ordinary 1F1B ring
aliases receive descriptors that no longer own long-lived buffers, and the
interleaved pool's owned copies only add memory. Both installers now keep
the stock buffers when torch.distributed.pipelining._recv_buffers exists.

The pool unit tests pin the probe for the fake stage layouts, skip the
real-PyTorch parity and negative-control runs under just-in-time buffers
(the negative control can no longer corrupt a reused buffer), and the
interleaved schedule harness sets the PyTorch 2.15 runtime defaults it
skips by bypassing __init__ (_unshard_lookahead, _defer_reduce_grad_wait,
_max_outstanding_sends).

Signed-off-by: Alexandros Koumparoulis <[email protected]>

* build(docker): backport torchao's MoE FP8 autotune key fix for Triton 3.9

torchao v0.17.0, which the image builds for its MXFP8 kernels, names
"num_elements" in the triton.autotune key of
_triton_fp8_rowwise_3d_transpose_cast_rhs_kernel, but the kernel has no
such argument. Triton 3.9 in the 26.11 base rejects that when
torchao.prototype.moe_training is imported, so the MXFP8 grouped GEMM
resolver failed (tests/unit_tests/moe/test_mxfp8.py). Apply upstream's
fix, pytorch/ao#4880, to the v0.17.0 checkout before building the wheel.
The step accepts the original or the already-patched source only.

Signed-off-by: Alexandros Koumparoulis <[email protected]>

* ci(recipes): give nemotron_nano_v3_hellaswag 50 minutes in CI

Its nightly checkpoint-robustness job finished in 39.6 of its 40 minutes
on the 26.10 image. On 26.11 it trains with the same loss trajectory but
about 3% slower (93K vs 96K tokens/s), so it hit the Slurm time limit in
the automodel_reload phase in both 26.11 nightlies.

Signed-off-by: Alexandros Koumparoulis <[email protected]>

* test(ci): list the torchao patch among the container dependency inputs

The wheel-builder stage now copies docker/common/torchao-autotune-key.patch. prepare-container-dependencies.sh already fingerprints all of docker/, so only the test's explicit input list was missing it.

Signed-off-by: Alexandros Koumparoulis <[email protected]>

* test(optim): name the leaked types when the cyclic-garbage check fails

test_backward_leaves_no_cyclic_garbage failed in the 26.11 L0 CPU job
(1423 and 1420 unreachable objects in two runs) but passes alone in the
26.11 image, with and without a GPU, with coverage, and with the whole
tests/unit_tests/optim directory in one process. Some test that shares
its xdist worker leaves state behind. Report the collected object types
in the assertion so the next failure identifies the source.

Signed-off-by: Alexandros Koumparoulis <[email protected]>

* test(pipelining): skip interleaved pool parity when receives are JIT

The functional parity test asserts that installing the interleaved recv
pool leaves fewer receive descriptors than microbatches, and the 4-GPU
negative control expects corruption once the owned input copies are
removed. With PyTorch 2.15 (26.11), which allocates receive buffers just
in time, the installer keeps the stock buffers, so neither assertion
applies (L2_Distributed on H100 and GB200). Gate the module on the same
probe the unit tests use.

Signed-off-by: Alexandros Koumparoulis <[email protected]>

* test(optim): drain earlier tests' garbage before the cyclic-garbage check

On PyTorch 2.15 (26.11), the Dynamo tracing state of an earlier
torch.compile test in the same process (test_tp_linear, test_dsv4_layers,
test_experts or test_swiglu_triton) is released in two stages: the first
gc.collect() runs a finalizer that drops the last reference to another
cycle, which only the next collection finds. The single baseline collect
left those 168 to 1420 objects (FakeTensor, SymNode and fx.Node graphs,
traceback.FrameSummary) to the measured window, so the check failed
whenever such a test ran first in the xdist worker. Collect until nothing
is left before measuring; the check still covers every cycle the sketch
backward creates.

Signed-off-by: Alexandros Koumparoulis <[email protected]>

* test(pipelining): check interleaved parity with native JIT receives

Signed-off-by: Alexandros Koumparoulis <[email protected]>

---------

Signed-off-by: Alexandros Koumparoulis <[email protected]>
Signed-off-by: NeMo Bot <[email protected]>
Co-authored-by: NeMo Bot <[email protected]>
@github-actions
github-actions Bot deleted the gh/sanketpurandare/7/head branch November 29, 2026 01:47
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/torchtitan Run TorchTitan integration tests Merged module: pipelining Pipeline Parallelism release notes: distributed (pipeline) release notes category

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants