Skip to content

[pipelining] Reuse deterministic receive buffers - #196465

Draft
sanketpurandare wants to merge 14 commits into
gh/sanketpurandare/9/basefrom
gh/sanketpurandare/9/head
Draft

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

Conversation

@sanketpurandare

@sanketpurandare sanketpurandare commented Sep 9, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

Add an opt-in static receive-buffer pool whose slots are colored from the
finalized pipeline schedule. The pool retains stable tensor addresses across
successful steps while preserving the just-in-time descriptor ownership
contract. Every public multi-stage schedule exposes and documents the
reuse_recv_buffers option after the existing max_active_stages argument, so
positional callers retain their prior meaning.

Keep receive descriptors and storage ownership in _recv_buffers.py. Stage
execution imports those primitives, while schedule-IR lifetime analysis remains
in schedules.py; this preserves a one-way dependency without coupling buffer
allocation to schedule action types.

The pool retains ordinary, autograd-neutral base tensors allocated independently
of ambient inference mode. Each acquisition gives the receive descriptor a fresh
detached alias. Hooks, gradients, and requires_grad state therefore cannot
cross lease boundaries, while the underlying address remains stable for CUDA
graph capture and inference-to-training transitions.

Forward and backward pools are independent, use explicit assignment maps and
allocation counts, validate uniform receive metadata before allocation, and
resolve every peer before acquiring storage. Invalid routing metadata therefore
cannot leave lazy descriptors or pooled slots falsely owned. Compatible pools
grow without replacing existing storage, so train/eval transitions retain at
most the larger mode footprint while preserving captured addresses. Training
slots are released after their full or weight-backward lifetime. Inference
retains received inputs until all outstanding sends complete because the runtime
does not yet expose per-send wait actions.

Tensors that escape through network sends, same-rank stage handoffs, or final
outputs are materialized only when they alias a receive pool. Ordinary
non-aliasing values remain zero-copy. Native alias detection handles dense views
and non-strided tensors such as sparse wrappers without dereferencing unsupported
storage. Buffer acquisition and P2POp construction are transactional, so a
failure before launch restores both descriptor and pool ownership. Custom
receive handlers must preserve the stage receive acquire/populate contract.
Incomplete distributed steps remain fail-fast because outstanding P2P work may
still own the buffers; reconstructing the stages, schedule, and process group is
the safe retry boundary.

Test Plan:

  • python test/distributed/pipelining/test_schedule.py -v
  • CUDA_VISIBLE_DEVICES=0,1,2,3 python test/distributed/pipelining/test_schedule_multiproc.py
  • CUDA_VISIBLE_DEVICES=0,1,2,3 python test/distributed/pipelining/test_dtensor_pp_integration.py TestDTensorPPModes.test_static_mode_interleaved1f1b_replicate_with_recv_buffer_reuse
  • 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 test/distributed/pipelining/test_dtensor_pp_integration.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/196465

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

✅ No Failures

As of commit 1a9c52c 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 46m 33s —— View job


Reviewed the pool lifecycle against the runtime loop and the P2P stream semantics: the reuse itself is safe (thanks to syncStream in pointToPoint, not the allocator), but there is a hard bug where any exception inside step() permanently bricks the schedule, inference gets no slot reuse at all while retaining more memory than the lazy path, and the "storage aliasing" test coverage claimed in the description does not exist.

Full review — #196465 [pipelining] Reuse deterministic receive buffers

PR Review: #196465

Summary

Adds an opt-in (reuse_recv_buffers) pool of deterministically-colored receive buffers so PP recv destinations have stable addresses. The core lifecycle is sound and the reuse is stream-safe, but there is one hard robustness bug (unrecoverable pool state after any mid-step exception), a design gap that makes the feature counterproductive for inference and for step()/eval() alternation, an unverified send/recv aliasing window on the backward slot, several pieces of dead or unexplained validation, and testing that trades away default-path coverage while never asserting the memory reuse the PR claims to test.

Code Quality

1. Any exception during step() permanently bricks the schedule. _RecvBufferPool.prepare raises "Cannot resize active ... receive buffer pool" whenever _owners is non-empty (stage.py:188-191), and that check runs before the no-op early-return at stage.py:196-197. Nothing ever clears _owners on the failure path: _release_recv_buffers is inside the try (schedules.py:3122), _release_all_recv_buffers is past the raise e (schedules.py:3140), and clear_runtime_states (stage.py:929-936) only touches fwd_cache/output_chunks. So if step N raises after a RECV_F acquires a slot but before its backward — an OOM, a NaN guard, a collective timeout, anything a user would normally catch and retry — step N+1 fails with a confusing "cannot resize" error even though the schedule and metadata are identical. There is a second landmine on the same path: the stale _RecvInfo.buffer makes set_buffer raise "already set" (stage.py:140-143).

Fix: reset pool ownership in clear_runtime_states (which already runs per-step at schedules.py:2408), or move the release-all into a finally. The prepare guard should also come after the early-return, so an unchanged re-prepare is never an error. This needs a regression test — raise from inside a schedule action and assert the next step() succeeds. Fix this →

2. Backward slot is released before its SEND_B is issued. _add_send_recv appends SEND_B after the backward action (schedules.py:1890-1901), but _release_recv_buffers fires within the FULL_BACKWARD time step (schedules.py:3122), and the isend is only waited at end-of-step (schedules.py:3138-3139). If grads_input ever shares storage with the received grad buffer — plausible for a passthrough input, since AccumulateGrad stores new_grad.detach() when .grad is unset — a later RECV_B re-acquiring that slot can irecv over an in-flight isend. You already reasoned about exactly this hazard in the forward/inference direction (schedules.py:333-337, "An inference output may alias its received input") but not here. Either extend the backward release to also wait for the corresponding SEND_B, or add a comment justifying why the aliasing cannot occur. Flagging as moderate confidence — please confirm rather than take my word.

3. Dead metadata validation with a misleading error. acquire raises "Receive metadata changed for '...' in the ... buffer pool" (stage.py:234-238), but metadata is uniform across microbatches by construction: PipelineStage._setup_forward_recv_info builds every chunk's tuple from the same _stage_meta.inputs objects (stage.py:2619-2637), _create_act_recv_info takes no chunk argument (stage.py:1610), and _TensorMeta is a frozen dataclass. This branch can never fire, and the message describes a condition that cannot arise. Drop it, or restate it as the invariant assertion it actually is.

4. requires_grad_(False) on release is unexplained. stage.py:249-262 resets requires_grad with no comment. I checked the plausible justification — the DTensor guard at stage.py:967-975 — and it does not apply, because that branch applies requires_grad_ to the DTensor wrapper and never to buffer, so stale pool state cannot trip it. The non-DTensor path unconditionally overwrites at stage.py:986. If this is defensive hygiene, say so in one line; if it is load-bearing for a path I missed, document which. (buffer.grad = None on the adjacent line is load-bearing — stage_backward_input writes inp.grad = dinput at _backward.py:256-261 and never clears it — so a one-line comment distinguishing the two would help.)

5. Slot count is derived twice. _assign_pipeline_resource_slots already returns the count as next_slot (schedules.py:289), the caller discards it (schedules.py:359), and stage.py:636/:642 re-derive it as max(slots.values(), default=-1) + 1. Equivalent (numbering is dense), but carry the count on _PipelineRecvBufferSlots instead — that also removes the awkward default=-1 idiom.

6. _init_recv_buffer_pools exists only to serve a test that skips super().__init__. MockPipelineStage (test_schedule.py:80-87) hand-sets four attributes instead of calling super().__init__(), so the diff adds a manual self._init_recv_buffer_pools() call at test_schedule.py:87. That makes every future base-class field a mock-maintenance burden and adds a helper method to production code for test reasons. Fix the mock to call super().__init__() and inline the four assignments into _PipelineStageBase.__init__.

7. Shared mutable sentinel across stages. empty = _PipelineRecvBufferSlots({}, {}) (schedules.py:2861) is handed to every stage lacking slots, and _prepare_recv_buffer_pools stores those dicts by reference (stage.py:632-633), so multiple stages alias the same two dicts. Benign today since nothing mutates them, but construct per-stage or pass {}, {} directly.

API Design

8. reuse_recv_buffers is the third boolean threaded identically through five subclasses. Each of ScheduleLoopedBFS, ScheduleInterleaved1F1B, ScheduleInterleavedZeroBubble, ScheduleZBVZeroBubble, ScheduleDualPipeV gains two more lines, joining defer_pp_recv and max_active_stages in the same pattern. None of the three is documented in any class docstring — a user has no way to discover what reuse_recv_buffers does, when it helps, or that it interacts badly with inference (see Performance). At minimum document it on _PipelineScheduleRuntime; better, group these runtime knobs into one options object so the next flag costs zero subclass edits.

9. Name collision. _PipelineScheduleRuntime._prepare_recv_buffer_pools() (no args, schedules.py:2849) and _PipelineStageBase._prepare_recv_buffer_pools(fwd_slots, bwd_slots) (stage.py:622) are different operations at different layers. Rename the schedule-level one (e.g. _assign_recv_buffer_slots).

10. _recv_buffer_slots_by_mode: dict[bool, ...] (schedules.py:2673) keys a dict by a boolean. Two named fields, or keying on the mode explicitly, reads better.

Performance

11. Inference gets zero slot reuse and more retained memory than the lazy path. With has_backward=False, schedules.py:333-337 sets every RECV_F release to len(actions), so all intervals mutually overlap and _assign_pipeline_resource_slots hands each a distinct slot (schedules.py:279-287): num_slots == num_microbatches. Those buffers then stay pinned in _buffers for the stage's lifetime, whereas the lazy path drops each reference in take_buffer (stage.py:146-149). Net effect for an eval-only workload with reuse_recv_buffers=True: peak memory unchanged, steady-state retained memory strictly higher, and the only remaining benefit is address stability across steps. Note test_eval_inference_mode is one of the two tests you flipped to reuse_recv_buffers=True. Either narrow the inference release window (release per-microbatch once its sends complete, rather than deferring everything to end-of-step) or document that the flag is for training.

12. Alternating step() and eval() reallocates the whole pool at every transition — defeating the stated goal. _recv_buffer_slots_by_mode caches the coloring per mode, but each stage has a single _fwd_recv_pool/_bwd_recv_pool (stage.py:468-469). eval() sets _has_backward = False and calls step (schedules.py:797-812), producing a different num_slots (per #11), so prepare's early-return len(self._buffers) == num_slots fails and _buffers is rebuilt with fresh _make_tensor_from_meta allocations at new addresses; the backward pool is additionally torn down to () and reallocated on the next training step. Train-then-validate loops are the common case, and CUDA-graph address stability — the PR's headline motivation — does not survive it. Pool per mode.

13. Note on the CUDA-graph motivation. The reuse is stream-safe, but for a subtler reason than the allocator: P2P always runs on the internal NCCL stream (ProcessGroupNCCL.cpp:4258-4263) and pointToPoint calls syncStream at :4265, which records an event on the current compute stream and blocks the NCCL stream on it — a full compute→NCCL barrier at irecv-issue time. That is what orders mb0's backward reads before mb2's irecv writes; recordStream (:4355) only guards allocator free-and-reuse and is inert for a pooled buffer. Worth a comment in _RecvBufferPool, because the safety argument is non-obvious and the barrier means recv is serialized behind all pending compute. It also means the guarantee is conditional on the irecv being issued from the same stream the consumer ran on — under actual CUDA-graph capture or a user side-stream around step(), nothing in the pool checks that.

Testing

14. Two multiproc tests trade default-path coverage for new-path coverage. test_eval_inference_mode (test_schedule_multiproc.py:410-416) and test_grad_with_manual_interleaved (:783-789) hardcode reuse_recv_buffers=True rather than parametrizing. The second is the only test combining check_leaked_tensors() with interleaved schedules × pre_split × 2 steps, so the default-path leak check for interleaved schedules is now gone. Parametrize [False, True] as test_v_shape_schedules already does (:1063).

15. The claimed "storage aliasing" coverage does not exist. There is no data_ptr, untyped_storage, or memory_allocated assertion anywhere in test/distributed/pipelining/. The only reuse evidence is Python object identity in a mocked CPU unit test (test_schedule.py:291, :302). Nothing proves the feature actually bounds allocation end-to-end, nor that addresses are stable across two step() calls — the range(2) loops at :795/:1093 assert numerics only. Given the whole point is stable addresses, an e2e assertion that recv data_ptrs are identical across steps is the test that matters.

16. make_tensor.assert_not_called() (test_schedule.py:305) is weaker than it looks. The pool's real allocation happens in _prepare_recv_buffer_pools at :262, outside the patch opened at :271, so inside the patch the only reachable caller is the JIT fallback at stage.py:659-660. It proves "no microbatch fell through to per-microbatch allocation" — fine, but it is also partly redundant with the assertIs checks, since a fall-through would hand back a MagicMock and fail them anyway.

17. Error paths are almost entirely untested. Only "still owned by microbatch 0" is covered (:286). Untested: "Cannot resize active ... pool" (which is finding #1 — untested precisely because the recovery bug was not considered), slot-out-of-range, "is not active", owner mismatch, and the new "has not been set" raise at stage.py:614. _release_all_recv_buffers has no unit test and is only reached implicitly by test_eval_inference_mode with no buffer-state assertion.

18. Untested combinations: reuse_recv_buffers=True with defer_pp_recv=True, and with DTensor activations/grads (the _DTensorMeta branches in _retrieve_recv_activations/_retrieve_recv_grads are where a pooled buffer's requires_grad state actually gets inspected — see #4). Also no test for the inference input/output aliasing hazard that motivates the deferred release at schedules.py:334-337.

19. The new unit test is fragile. test_stage_recv_buffer_pool_reuses_deterministic_slots hand-wires eight attributes onto a MockPipelineStage and then calls unbound PipelineStage._setup_forward_recv_info(stage, ...) / PipelineStage._create_grad_recv_info(stage, ...) on an instance of a different class (test_schedule.py:257-264). That will silently rot the moment either method touches state the mock does not have. It also asserts on an error-message substring (:286), coupling the test to wording.

Recommendation

Request Changes

Finding #1 is a real robustness bug that turns any recoverable mid-step failure into an unrecoverable one, and it needs a regression test. Findings #11/#12 mean the flag is a pessimization for inference and does not deliver stable addresses across train/eval alternation — the stated goal. #2 needs confirmation before landing. The rest (#3-#10, #13-#19) are cleanups and coverage that should ride along.

· branch `gh/sanketpurandare/9/head`

@sanketpurandare

Copy link
Copy Markdown
Contributor Author

@claude Preserved fail-fast recovery after an incomplete distributed step because outstanding communication makes silent owner reset unsafe. The pool now uses explicit forward/backward assignment maps and counts, validates uniform metadata once, reuses stable addresses across successful steps, and materializes a send only when it aliases either receive pool. Inference intentionally retains one slot per live microbatch until all pending sends complete; the PR no longer claims an inference memory reduction over lazy allocation. Existing multiprocess coverage exercises lazy/static modes, repeated pointers, aliasing, split backward, V/local transfer, DTensor metadata, deferred receives, and train/eval reuse.

Summary:
Add an opt-in static receive-buffer pool whose slots are colored from the finalized pipeline schedule. The pool retains stable tensor addresses across successful steps while preserving the just-in-time descriptor ownership contract.

Forward and backward pools are independent, use explicit assignment maps and allocation counts, and validate uniform receive metadata once before allocation. Training slots are released after their full or weight backward lifetime. Inference retains received inputs until all outstanding sends complete because the runtime does not yet expose per-send completion actions. A single pool per direction avoids retaining separate train and eval allocations; changing execution mode may resize it.

A backward send that aliases either receive pool is materialized before the slot can be reused. Ordinary non-aliasing sends avoid the copy. Incomplete distributed steps remain fail-fast because outstanding P2P work may still own the buffers; recreating the schedule and process group is the safe retry boundary.

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

[ghstack-poisoned]
[ghstack-poisoned]
@claude

claude Bot commented Sep 16, 2026 •

Copy link
Copy Markdown

Claude finished @sanketpurandare's task in 39m 41s —— View job


Most of the previous round landed cleanly — the slot-count duplication, the test-only _init_recv_buffer_pools hook, the name collision, the shared mutable sentinel, the requires_grad_ comment, the dict-keyed-by-bool, and the missing data_ptr stability assertion are all fixed, and the new unit tests now exercise the real _RecvBufferPool / _assign_pipeline_recv_buffer_slots instead of hand-wired mocks. I accept the fail-fast rationale. Two things I'd still resolve before landing: get_fwd_send_ops has no _ensure_owned_send guard even though get_bwd_send_ops does, and the train/eval pool resize is now documented but still untested while it tears the backward pool down to () on every transition.

Full re-review — #196465 [pipelining] Reuse deterministic receive buffers

Re-review: #196465

Verified against git diff origin/gh/sanketpurandare/9/base...HEAD. I re-derived the coloring in the new unit test by hand and it is correct, and I traced the release points against the I/W-split schedules. Organized as: what your rationale resolves, what I think is still open, and where I think your coverage claims overstate what exists.


Accepting your rationale

Fail-fast on incomplete steps. You're right and I was wrong to call this a bug. Outstanding irecv work genuinely owns the storage, and there is no way for the pool to observe completion — _wait_batch_p2p results are dropped, so _owners is the only signal that a slot may still be a live NCCL destination. Silently resetting it would turn a caught-and-retried OOM into a silent data race, which is strictly worse than a loud error. The improved message (destroy_process_group(), then reconstruct the stages and schedule) now describes a recovery that actually works.

One follow-on, since the guard's meaning changed: because the documented recovery discards the stage objects (and therefore the pool), the guard in _RecvBufferPool.prepare (stage.py:189-194) can never be satisfied by anything except a fresh stage. It is a diagnostic for "you reused a stage after a failed step", not a resize precondition. That reads better hoisted to the top of _assign_recv_buffer_slots (schedules.py:2687) as one whole-schedule check: today it fires per-stage in iteration order, after some stages have already been re-prepared, so the error names an arbitrary direction on an arbitrary stage rather than the schedule-level condition it actually describes.

Metadata validated once. _validate_uniform_recv_metadata (stage.py:664-685) is the right shape — a cheap one-time invariant check before allocation, rather than the per-acquire branch I flagged. The message is thin though: "Receive metadata must be uniform across pooled microbatches" names neither the microbatch nor the tensor index that diverged. If this ever fires it will be on a custom stage implementation, which is exactly the case that needs the detail. Include microbatch_index and the first differing index.

Inference retention. Accepted, and the docstring change is the right call. One wording sharpen: "keeps each received input alive until all sends complete" describes a step-scoped lifetime, but _buffers is never freed — with has_backward=False the pool holds num_microbatches tensors for the stage's lifetime, which is more retained memory than the lazy path's take_buffer drop. Saying so plainly ("holds one buffer per microbatch for the schedule's lifetime") is more useful to someone deciding whether to enable the flag for an eval-only job than the current phrasing.

Slot counts, sentinel, naming, DTensor-guard comment, test-only hook. All resolved. num_forward_slots/num_backward_slots carried on _PipelineRecvBufferSlots removes the max(..., default=-1) + 1 idiom; the default _PipelineRecvBufferSlots({}, 0, {}, 0) is now constructed per stage so no two stages alias one dict; MappingProxyType on the assignment maps is a nice touch; MockPipelineStage no longer needs a production helper. The buffer.grad = None / requires_grad_(False) comment now explains the invariant.

Zero cost when disabled. Worth stating explicitly since it's load-bearing for the default path: with reuse_recv_buffers=False, _buffers stays (), so aliases() is an any() over an empty generator and _ensure_owned_send is a single False or False. No default-path regression.


Still open

1. get_fwd_send_ops is not guarded, but get_bwd_send_ops is. stage.py:947 routes the backward grad through _ensure_owned_send; stage.py:862 sends to_local_if_dtensor(out, detach=True) raw. A forward output aliases its forward recv slot whenever the submodule is a passthrough or ends in a view/reshape/slice of its input — _retrieve_recv_activations hands the pooled buffer in as the leaf (stage.py:1030), so any view-producing tail keeps that storage.

The window is: SEND_F(mb0) reads slot S and is appended to send_ops, waited only at end of step (schedules.py:2987-2988); FULL_BACKWARD(mb0) releases S; a later RECV_F(mbN) re-acquires S and irecvs into it. So an in-flight isend can be overwritten.

I'll grant this is a much looser race than the backward one you closed — SEND_B(mb) is issued in the same time step as its release, whereas SEND_F has had an entire backward pass to drain — so the prioritization is defensible. But the guard costs one call on a path that is already free when the pool is empty, and the asymmetry is currently unexplained. Either apply _ensure_owned_send at stage.py:862 or add a line saying why the forward direction is exempt. Moderate confidence on reachability; please confirm rather than take my word. Fix this →

2. Mode switching frees and reallocates the backward pool, and nothing tests it. _recv_buffer_slots stores a single (has_backward, slots) pair (schedules.py:2511-2513), and each stage has one _fwd_recv_pool/_bwd_recv_pool. On eval(), _assign_pipeline_recv_buffer_slots skips RECV_B entirely (schedules.py:4054-4055), so num_bwd_slots == 0 and prepare(0, (), device) rebuilds _buffers as () — the whole backward pool is dropped, then reallocated at new addresses on the next step(). The forward pool resizes too, since inference wants num_microbatches slots and training wants fewer.

The docstring now warns that switching "may resize the single pool", which is honest. But train-then-validate is the common loop, and this is the case where address stability — the feature's headline benefit — is guaranteed not to hold, plus you get allocator churn proportional to the backward pool at every transition. A pool per mode (or per (direction, has_backward)) removes both, at the cost of retaining both allocations.

Either way this path has no test: test_eval_inference_mode only ever calls eval(), never alternates, so the resize/teardown code has never executed in CI. A step(); eval(); step() loop asserting the training pointers match across the two step() calls is the test that would have caught it — and it's the one that decides whether the current behavior is acceptable or needs the per-mode pool. Fix this →

3. Release condition reads stage.has_backward, coloring reads self._has_backward. _release_recv_buffers gates on stage.has_backward (schedules.py:2929) while _assign_recv_buffer_slots colors with self._has_backward (schedules.py:2697). These agree only because PipelineScheduleMulti.step syncs them (schedules.py:2236-2237) — _step_microbatches itself does not. Any caller reaching _step_microbatches without going through step() gets acquire/release asymmetry, which surfaces as a confusing "is not active" or as silently leaked owners that brick the next step. Use self._has_backward in _release_recv_buffers so the release condition is derived from the same value the coloring used. Not a live bug today; it's a one-word change that makes it not become one.

4. The clone in _ensure_owned_send is silent. When it fires, the user pays an extra allocation plus copy per aliasing grad per microbatch, forever, with no indication. A logger.debug naming the input would let someone diagnose "why is reuse_recv_buffers slower than lazy for my model".

5. Interaction with custom action overrides is unstated. _release_recv_buffers runs after self._comp_type_to_function_map[...] dispatch (schedules.py:2961-2971), so a user-registered RECV_F handler that does not call get_fwd_recv_ops will skip the acquire but still hit the release, raising "is not active". One line in the _PipelineScheduleRuntime docstring saying the flag requires the built-in recv handlers would save someone a confusing debug session.


Coverage claims

Two of the claims in your comment don't match what's in the tree:

DTensor metadata is not covered with this flag. grep -rn reuse_recv_buffers test/ returns hits only in test_schedule.py and test_schedule_multiproc.py; nothing in test_dtensor_pp_integration.py or test_dtensor_pp_unit_tests.py, and the three parametrized multiproc tests all build plain MultiMLP via setup_models_and_data. The _DTensorMeta branches in _retrieve_recv_activations (stage.py:1011-1028) and _retrieve_recv_grads (stage.py:1071-1081) are where a pooled buffer's requires_grad state is actually inspected rather than overwritten — stage.py:1014 raises if the buffer requires grad before from_local. That is the one place the requires_grad_(False) reset in release is load-bearing rather than hygiene, and it is untested. This is the coverage gap I'd add next after the mode-switch test.

Train/eval reuse is not covered. As above — test_eval_inference_mode never alternates, so no test observes a pool being resized.

The rest of the claims check out: lazy vs static via the False/True parametrizations, repeated pointers via the new data_ptr comparison at test_schedule_multiproc.py:858-869, aliasing via _ensure_owned_send in the unit test, split backward via ScheduleInterleavedZeroBubble, V/local transfer via test_v_shape_schedules (which now covers both ScheduleZBVZeroBubble and ScheduleDualPipeV, so the I-without-matching-W case that would trip missing_releases is exercised), and deferred receives via the (ScheduleInterleaved1F1B, True, True) combo.

Remaining test notes:

  • CI cost. test_grad_with_manual_interleaved goes 6 → 14 runs, test_eval_inference_mode 5 → 8, test_v_shape_schedules 2 → 4: +13 four-GPU runs. The reuse dimension is largely schedule-independent — it's the coloring plus the pool, and the coloring is already unit-tested on CPU. One representative schedule per family (1F1B-interleaved, zero-bubble, V) would keep the signal at roughly half the cost. Worth weighing given how contended the distributed CI queue is.
  • test_eval_inference_mode with reuse_recv_buffers=True asserts nothing about the pool — only that grads are absent and losses exist. Since inference is the mode with the unusual lifetime (all slots live to end of step, then _release_all_recv_buffers), asserting _owners is empty after the step, and that num_forward_slots == num_microbatches, is what would pin the documented behavior.
  • test_recv_buffer_pool_reuses_slots_and_detects_aliases mixes RuntimeError and PipeliningMetadataError in adjacent assertRaisesRegex calls (test_schedule.py:246, :248-250). PipeliningMetadataError subclasses RuntimeError so both pass, but use the specific type for both. The test also covers pool mechanics, the prepare guard, and _ensure_owned_send for two pools in one body — splitting the _ensure_owned_send half out would localize failures, though I'd not block on it.
  • Schedule-validation errors are cheap to cover. "appears more than once" and "Receive-buffer lifetimes have no release action" (schedules.py:4051, :4080-4083) are pure functions of an action list — two three-line additions to test_recv_buffer_slots_follow_schedule_lifetimes (a duplicated RECV_F, and a RECV_F with no B/W). Non-uniform metadata is similarly a two-_RecvInfo unit test.

Recommendation

Approve with comments — this is close. I'd resolve #1 (guard SEND_F or justify the asymmetry) and #3 (one-word has_backward source change) before landing, and I'd want #2's test in the same PR since it decides whether the single-pool design stands. #4-#5 and the DTensor coverage gap can be follow-ups. I could not run the tests in this environment (no built torch), so the coloring verification above is by hand, not execution.

· branch `gh/sanketpurandare/9/head`

@pytorch pytorch deleted a comment from claude Bot Sep 16, 2026
@sanketpurandare sanketpurandare added the module: pipelining Pipeline Parallelism label Sep 16, 2026
"""

def __init__(self, direction: str) -> None:
self._direction = direction

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.

do we need 2 pools?

A slot indexed by payload size would address the issue of different buffer size.

In the naive pipeline case, forward activation and backward gradient of the activation usually share the same size.

I wonder having the same pool would enable more buffer reuse?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A stage can send one or more tensors to the next stage, I think for this option of using a single static recv buffer pool we need to enforce some conditions like your forward and backward payload tensors should be same. There is no guarantee that they would be same, for instance, i can send some tensors to a stage that doesn't require grads, then the backward would be None. Or in case of DTensors they might have different sizes due to some padding stuff. During init we know the exact metadata for send/recv of all the stages, so we can error out or fallback to lazy recv with a warning.

def __init__(self, *args, **kwargs):
self._defer_pp_recv: bool = kwargs.pop("defer_pp_recv", False)
self._max_active_stages: int = kwargs.pop("max_active_stages", 3)
self._reuse_recv_buffers: bool = kwargs.pop("reuse_recv_buffers", False)

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.

do you see problems with always reuse the recv buffer? maybe don't need a new flag

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Comment on lines +283 to +284
self._fwd_recv_pool = _RecvBufferPool("forward")
self._bwd_recv_pool = _RecvBufferPool("backward")

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.

These 2 pools seems to be owned by per stage.

I thought they should be global?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There is no guarantee that fwd/bwd send/recv metadata across stages is identical. Maybe for static recv buffer pool this also needs to be enforced as a constraint and we fallback to lazy recv buffers in case of non-satisfaction

for info, buffer in zip(recv_infos, buffers, strict=True):
if buffer is not None:
info.set_buffer(buffer)
self._owners[slot] = microbatch_index

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.

I am confused by the semantics of _owners?

I expect a slot to be jointly owned by a (stage, microbatch_index) pair.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yes if we are sharing the slots across stages

None if info.is_root_arg else info.tensor_meta for info in recv_infos
)
allocation_signature = tuple(
None if meta is None else (meta.shape, meta.stride, meta.dtype)

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.

stride can be skipped?

recv tensor must be contiguous.

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.

more generally, I would expect buffer to be just blob of bytes, signatured by byte_size.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This should be handled by stage metadata runtime checks when the env variable is set for debug/runtime checks is set.

Comment thread torch/distributed/pipelining/stage.py Outdated
Comment on lines +562 to +569
def _ensure_owned_send(self, tensor: torch.Tensor) -> torch.Tensor:
"""Materialize sends that alias storage managed by either recv pool."""
if self._fwd_recv_pool.aliases(tensor) or self._bwd_recv_pool.aliases(tensor):
logger.debug(
"%s Materializing a send that aliases a recv pool", self.log_prefix
)
return tensor.clone()
return tensor

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.

interesting that you are handling such case.

did you run into a concrete case where it's sending the received tensor?
I suppose this could be common case for model with AttnRes, where stages are just forwarding the recv buffer.

Such clone could need further optimization.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yes this is when recv buffer is directly forwarded, no I don't have a concrete usecase other than skip connections be served by passing tensors across stages. It is a valid case but needs to be handled with more care since if a recv buffer is used by the current stage plus the next stage then it requires accumulating the grads.

num_fwd_slots: int,
bwd_slots: Mapping[int, int],
num_bwd_slots: int,
) -> None:

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.

can you infer number of slots from the slots?

@SherlockNoMad

Copy link
Copy Markdown
Contributor

Pool granularity: per-(stage, direction) leaves ~40% on the table

I measured three pooling granularities against the schedule this PR actually
lowers, to see what the per-(stage, direction) choice costs. Methodology: build
pipeline_order_with_comms for ScheduleInterleaved1F1B pp=4, vpp=4, extract
recv lifetimes exactly as _assign_pipeline_recv_buffer_slots does, then regroup
the intervals and re-run this PR's own _assign_pipeline_resource_slots on each
grouping. Unit is one buffer slot; assumes uniform buffer size, which holds for a
homogeneous stack. Training steps only.

  • A = one pool per (stage, direction) — what this PR implements
  • B = one pool per direction, shared by the 4 local vpp stages
  • C = one pool for everything on the rank
rank A fwd A bwd A B fwd B bwd B C
0 16 6 22 12 2 14 14
1 24 6 30 18 2 20 20
2 24 4 28 16 1 17 17
3 20 12 32 14 4 18 16
sum 112 69 (-38%) 67 (-40%)

Invariant across n_microbatches in {8, 16, 32} — warmup depth bounds the live
set, as expected for 1F1B.

B captures essentially all of it

C beats B by 2 slots out of 112, and only on one rank. Merging forward with
backward buys almost nothing here, because 1F1B is designed to keep a forward
and a backward in flight simultaneously — their peaks coincide rather than
stagger, so there is nothing to reclaim. That seems worth knowing before
considering a single variable-size arena: the packing problem gets materially
harder (interval coloring is optimal only when slots are interchangeable;
mixed-size offsets in one arena is dynamic storage allocation) for a 2-slot win.

The win is cross-stage, and it is mostly backward

Aggregated over ranks: forward 84 -> 60 (1.4x), backward 28 -> 9 (3.1x).

Backward collapses hardest because a RECV_B buffer is consumed almost
immediately -- released at the B/W for the same microbatch -- so few are
concurrently live rank-wide. But per-stage pooling still forces each of the 4 vpp
stages to independently hold its own peak. Rank 0 is the clearest case: 6 slots
summed across stages, 2 actually live at any instant.

Forward gains less but from a bigger base. Rank 3's per-stage forward peaks form
a warmup staircase -- stage3=8, stage7=6, stage11=4, stage15=2 -- which sum to 20
but overlap enough that only 14 are ever co-live.

Suggestion

Worth considering one pool per direction shared across a rank's local stages.
Slots stay interchangeable within a pool, so _assign_pipeline_resource_slots
stays optimal and unchanged; the only change is the grouping key at the
intervals[(stage_index, direction)] construction and moving pool ownership from
the stage to something rank-scoped.

@SherlockNoMad

Copy link
Copy Markdown
Contributor

Pool granularity, part 2: V-shape schedules invert the result

Follow-up to my comment on pool granularity, which measured loop topology only.
The V schedules behave in the opposite way, and it changes which grouping is the
right one.

Same methodology: build pipeline_order_with_comms, extract recv lifetimes as
_assign_pipeline_recv_buffer_slots does, regroup the intervals, re-run this
PR's _assign_pipeline_resource_slots on each grouping. pp=4, 2 stages/rank,
training steps only, uniform buffer size. Invariant across n_microbatches in
{8, 16}.

  • A = one pool per (stage, direction) — what this PR implements
  • B = one pool per direction, shared by a rank's local stages
  • C = one pool for everything on the rank

ScheduleZBVZeroBubble

rank A fwd A bwd A B fwd B bwd B C
0 2 3 5 2 3 5 3
1 10 4 14 10 4 14 11
2 10 6 16 10 6 16 12
3 5 3 8 5 3 8 7
sum 43 43 (0%) 33 (-23%)

ScheduleDualPipeV

rank A fwd A bwd A B fwd B bwd B C
0 2 2 4 2 2 4 3
1 10 4 14 10 3 13 12
2 10 4 14 10 4 14 12
3 5 2 7 5 2 7 6
sum 39 38 (-3%) 33 (-15%)

Worst-rank figures, which are what actually decide whether a job fits: ZBV 16 ->
12, DualPipeV 14 -> 12.

Why B does nothing here

Two separate reasons, and neither has an analogue in the loop topology.

At the V endpoints, a rank has exactly one stage per direction, so there is
nothing for a per-direction pool to merge:

  rank0:  0/RECV_B=3   7/RECV_F=2     (stage 0 is first, stage 7 is last)
  rank3:  3/RECV_F=5   4/RECV_B=3     (V turn-around, local hand-off both ways)

On the middle ranks both stages do use both directions, but their peaks coincide
exactly, so merging within a direction still recovers nothing:

  rank1:  1/RECV_F=7  6/RECV_F=3  ->  merged 10   (= 7+3)
          1/RECV_B=3  6/RECV_B=1  ->  merged  4   (= 3+1)
          all four groups merged   ->        11   (vs 14 summed)

The two local stages in a V sit on opposite legs and are co-active by
construction. There is no warmup staircase to collapse -- which is exactly where
interleaved vpp gets its win (rank 3 forward peaks of 8/6/4/2). What V schedules
have instead is forward/backward phase separation, and only a fully shared pool
can exploit that.

Cross-topology summary

schedule A B C
Interleaved1F1B vpp=4 112 69 (-38%) 67 (-40%)
Interleaved1F1B vpp=2 46 35 (-24%) 33 (-28%)
ScheduleZBVZeroBubble 43 43 (0%) 33 (-23%)
ScheduleDualPipeV 39 38 (-3%) 33 (-15%)

This supersedes the suggestion in my earlier comment. B is the better grouping
for loop topology and worthless for V; C is within 2 slots of B on loop topology
and 5-10 slots better on V. If only one granularity is going to be implemented,
a rank-global pool is the one that holds up across the schedules this PR enables
the flag for.

Incidentally, C lands on 33 total slots for all three pp=4 / 2-stages-per-rank
schedules despite quite different per-rank distributions (interleaved 5/11/9/8,
ZBV 3/11/12/7), so a rank-global pool also gives a roughly schedule-independent
footprint. One parameter point, so treat that as an observation rather than a
claim.

The cost of C is that variable-size slots in a single arena is bin-packing
rather than interval coloring. For a homogeneous stack there is likely only one
buffer size, in which case bucketing by size and running the existing colorer
per bucket makes C no harder to implement than B.

Add an opt-in static receive-buffer pool whose slots are colored from the finalized pipeline schedule. The pool retains stable tensor addresses across successful steps while preserving the just-in-time descriptor ownership contract. The new public option follows the existing `max_active_stages` argument so positional callers retain their prior meaning.

Keep receive descriptors and storage ownership in `_recv_buffers.py`. Stage execution imports those primitives, while schedule-IR lifetime analysis remains in `schedules.py`; this preserves a one-way dependency without coupling buffer allocation to schedule action types.

Forward and backward pools are independent, use explicit assignment maps and allocation counts, validate uniform receive metadata before allocation, and resolve every peer before acquiring storage. Invalid routing metadata therefore cannot leave lazy descriptors or pooled slots falsely owned. Compatible pools grow without replacing existing storage, so train/eval transitions retain at most the larger mode footprint while preserving captured addresses. Training slots are released after their full or weight-backward lifetime. Inference retains received inputs until all outstanding sends complete because the runtime does not yet expose per-send wait actions.

Forward and backward sends that alias either receive pool are materialized before a slot can be reused. Ordinary non-aliasing sends avoid the copy. Custom receive handlers must preserve the stage receive acquire/populate contract. Incomplete distributed steps remain fail-fast because outstanding P2P work may still own the buffers; recreating the stages, schedule, and process group is the safe retry boundary.

Test Plan:
- `python test/distributed/pipelining/test_schedule.py -v`
- `CUDA_VISIBLE_DEVICES=0,1,2,3 python test/distributed/pipelining/test_schedule_multiproc.py`
- `CUDA_VISIBLE_DEVICES=0,1,2,3 python test/distributed/pipelining/test_dtensor_pp_integration.py TestDTensorPPModes.test_static_mode_interleaved1f1b_replicate_with_recv_buffer_reuse`
- `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 test/distributed/pipelining/test_dtensor_pp_integration.py`

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

[ghstack-poisoned]
sanketpurandare added a commit that referenced this pull request Sep 17, 2026
Add an opt-in static receive-buffer pool whose slots are colored from the
finalized pipeline schedule. The pool retains stable tensor addresses across
successful steps while preserving the just-in-time descriptor ownership
contract. Every public multi-stage schedule exposes and documents the
`reuse_recv_buffers` option after the existing `max_active_stages` argument, so
positional callers retain their prior meaning.

Keep receive descriptors and storage ownership in `_recv_buffers.py`. Stage
execution imports those primitives, while schedule-IR lifetime analysis remains
in `schedules.py`; this preserves a one-way dependency without coupling buffer
allocation to schedule action types.

The pool retains ordinary, autograd-neutral base tensors allocated independently
of ambient inference mode. Each acquisition gives the receive descriptor a fresh
detached alias. Hooks, gradients, and `requires_grad` state therefore cannot
cross lease boundaries, while the underlying address remains stable for CUDA
graph capture and inference-to-training transitions.

Forward and backward pools are independent, use explicit assignment maps and
allocation counts, validate uniform receive metadata before allocation, and
resolve every peer before acquiring storage. Invalid routing metadata therefore
cannot leave lazy descriptors or pooled slots falsely owned. Compatible pools
grow without replacing existing storage, so train/eval transitions retain at
most the larger mode footprint while preserving captured addresses. Training
slots are released after their full or weight-backward lifetime. Inference
retains received inputs until all outstanding sends complete because the runtime
does not yet expose per-send wait actions.

Tensors that escape through network sends, same-rank stage handoffs, or final
outputs are materialized only when they alias a receive pool. Ordinary
non-aliasing values remain zero-copy. Native alias detection handles dense views
and non-strided tensors such as sparse wrappers without dereferencing unsupported
storage. Buffer acquisition and `P2POp` construction are transactional, so a
failure before launch restores both descriptor and pool ownership. Custom
receive handlers must preserve the stage receive acquire/populate contract.
Incomplete distributed steps remain fail-fast because outstanding P2P work may
still own the buffers; reconstructing the stages, schedule, and process group is
the safe retry boundary.

Test Plan:
- `python test/distributed/pipelining/test_schedule.py -v`
- `CUDA_VISIBLE_DEVICES=0,1,2,3 python test/distributed/pipelining/test_schedule_multiproc.py`
- `CUDA_VISIBLE_DEVICES=0,1,2,3 python test/distributed/pipelining/test_dtensor_pp_integration.py TestDTensorPPModes.test_static_mode_interleaved1f1b_replicate_with_recv_buffer_reuse`
- `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 test/distributed/pipelining/test_dtensor_pp_integration.py`

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

ghstack-source-id: 0c2144f
Pull Request resolved: #196465
@sanketpurandare
sanketpurandare marked this pull request as draft September 17, 2026 08:51
[ghstack-poisoned]
sanketpurandare added a commit that referenced this pull request Sep 17, 2026
Add an opt-in static receive-buffer pool whose slots are colored from the
finalized pipeline schedule. The pool retains stable tensor addresses across
successful steps while preserving the just-in-time descriptor ownership
contract. Every public multi-stage schedule exposes and documents the
`reuse_recv_buffers` option after the existing `max_active_stages` argument, so
positional callers retain their prior meaning.

Keep receive descriptors and storage ownership in `_recv_buffers.py`. Stage
execution imports those primitives, while schedule-IR lifetime analysis remains
in `schedules.py`; this preserves a one-way dependency without coupling buffer
allocation to schedule action types.

The pool retains ordinary, autograd-neutral base tensors allocated independently
of ambient inference mode. Each acquisition gives the receive descriptor a fresh
detached alias. Hooks, gradients, and `requires_grad` state therefore cannot
cross lease boundaries, while the underlying address remains stable for CUDA
graph capture and inference-to-training transitions.

Forward and backward pools are independent, use explicit assignment maps and
allocation counts, validate uniform receive metadata before allocation, and
resolve every peer before acquiring storage. Invalid routing metadata therefore
cannot leave lazy descriptors or pooled slots falsely owned. Compatible pools
grow without replacing existing storage, so train/eval transitions retain at
most the larger mode footprint while preserving captured addresses. Training
slots are released after their full or weight-backward lifetime. Inference
retains received inputs until all outstanding sends complete because the runtime
does not yet expose per-send wait actions.

Tensors that escape through network sends, same-rank stage handoffs, or final
outputs are materialized only when they alias a receive pool. Ordinary
non-aliasing values remain zero-copy. Native alias detection handles dense views
and non-strided tensors such as sparse wrappers without dereferencing unsupported
storage. Buffer acquisition and `P2POp` construction are transactional, so a
failure before launch restores both descriptor and pool ownership. Custom
receive handlers must preserve the stage receive acquire/populate contract.
Incomplete distributed steps remain fail-fast because outstanding P2P work may
still own the buffers; reconstructing the stages, schedule, and process group is
the safe retry boundary.

Test Plan:
- `python test/distributed/pipelining/test_schedule.py -v`
- `CUDA_VISIBLE_DEVICES=0,1,2,3 python test/distributed/pipelining/test_schedule_multiproc.py`
- `CUDA_VISIBLE_DEVICES=0,1,2,3 python test/distributed/pipelining/test_dtensor_pp_integration.py TestDTensorPPModes.test_static_mode_interleaved1f1b_replicate_with_recv_buffer_reuse`
- `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 test/distributed/pipelining/test_dtensor_pp_integration.py`

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

ghstack-source-id: d2bcf3c
Pull Request resolved: #196465
Add an opt-in static receive-buffer pool whose slots are colored from the
finalized pipeline schedule. The pool retains stable tensor addresses across
successful steps while preserving the just-in-time descriptor ownership
contract. Every public multi-stage schedule exposes and documents the
`reuse_recv_buffers` option after the existing `max_active_stages` argument, so
positional callers retain their prior meaning.

Keep receive descriptors and storage ownership in `_recv_buffers.py`. Stage
execution imports those primitives, while schedule-IR lifetime analysis remains
in `schedules.py`; this preserves a one-way dependency without coupling buffer
allocation to schedule action types.

The pool retains ordinary, autograd-neutral base tensors allocated independently
of ambient inference mode. Each acquisition gives the receive descriptor a fresh
detached alias. Hooks, gradients, and `requires_grad` state therefore cannot
cross lease boundaries, while the underlying address remains stable for CUDA
graph capture and inference-to-training transitions.

Forward and backward pools are independent, use explicit assignment maps and
allocation counts, validate uniform receive metadata before allocation, and
resolve every peer before acquiring storage. Invalid routing metadata therefore
cannot leave lazy descriptors or pooled slots falsely owned. Compatible pools
grow without replacing existing storage, so train/eval transitions retain at
most the larger mode footprint while preserving captured addresses. Training
slots are released after their full or weight-backward lifetime. Inference
retains received inputs until all outstanding sends complete because the runtime
does not yet expose per-send wait actions.

Tensors that escape through network sends, same-rank stage handoffs, or final
outputs are materialized only when they alias a receive pool. Ordinary
non-aliasing values remain zero-copy. Native alias detection handles dense views
and non-strided tensors such as sparse wrappers without dereferencing unsupported
storage. Buffer acquisition and `P2POp` construction are transactional, so a
failure before launch restores both descriptor and pool ownership. Custom
receive handlers must preserve the stage receive acquire/populate contract.
Incomplete distributed steps remain fail-fast because outstanding P2P work may
still own the buffers; reconstructing the stages, schedule, and process group is
the safe retry boundary.

Test Plan:
- `python test/distributed/pipelining/test_schedule.py -v`
- `CUDA_VISIBLE_DEVICES=0,1,2,3 python test/distributed/pipelining/test_schedule_multiproc.py`
- `CUDA_VISIBLE_DEVICES=0,1,2,3 python test/distributed/pipelining/test_dtensor_pp_integration.py TestDTensorPPModes.test_static_mode_interleaved1f1b_replicate_with_recv_buffer_reuse`
- `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 test/distributed/pipelining/test_dtensor_pp_integration.py`

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

[ghstack-poisoned]
sanketpurandare added a commit that referenced this pull request Sep 18, 2026
Add an opt-in static receive-buffer pool whose slots are colored from the
finalized pipeline schedule. The pool retains stable tensor addresses across
successful steps while preserving the just-in-time descriptor ownership
contract. Every public multi-stage schedule exposes and documents the
`reuse_recv_buffers` option after the existing `max_active_stages` argument, so
positional callers retain their prior meaning.

Keep receive descriptors and storage ownership in `_recv_buffers.py`. Stage
execution imports those primitives, while schedule-IR lifetime analysis remains
in `schedules.py`; this preserves a one-way dependency without coupling buffer
allocation to schedule action types.

The pool retains ordinary, autograd-neutral base tensors allocated independently
of ambient inference mode. Each acquisition gives the receive descriptor a fresh
detached alias. Hooks, gradients, and `requires_grad` state therefore cannot
cross lease boundaries, while the underlying address remains stable for CUDA
graph capture and inference-to-training transitions.

Forward and backward pools are independent, use explicit assignment maps and
allocation counts, validate uniform receive metadata before allocation, and
resolve every peer before acquiring storage. Invalid routing metadata therefore
cannot leave lazy descriptors or pooled slots falsely owned. Compatible pools
grow without replacing existing storage, so train/eval transitions retain at
most the larger mode footprint while preserving captured addresses. Training
slots are released after their full or weight-backward lifetime. Inference
retains received inputs until all outstanding sends complete because the runtime
does not yet expose per-send wait actions.

Tensors that escape through network sends, same-rank stage handoffs, or final
outputs are materialized only when they alias a receive pool. Ordinary
non-aliasing values remain zero-copy. Native alias detection handles dense views
and non-strided tensors such as sparse wrappers without dereferencing unsupported
storage. Buffer acquisition and `P2POp` construction are transactional, so a
failure before launch restores both descriptor and pool ownership. Custom
receive handlers must preserve the stage receive acquire/populate contract.
Incomplete distributed steps remain fail-fast because outstanding P2P work may
still own the buffers; reconstructing the stages, schedule, and process group is
the safe retry boundary.

Test Plan:
- `python test/distributed/pipelining/test_schedule.py -v`
- `CUDA_VISIBLE_DEVICES=0,1,2,3 python test/distributed/pipelining/test_schedule_multiproc.py`
- `CUDA_VISIBLE_DEVICES=0,1,2,3 python test/distributed/pipelining/test_dtensor_pp_integration.py TestDTensorPPModes.test_static_mode_interleaved1f1b_replicate_with_recv_buffer_reuse`
- `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 test/distributed/pipelining/test_dtensor_pp_integration.py`

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

ghstack-source-id: bdea003
Pull Request resolved: #196465
[ghstack-poisoned]
sanketpurandare added a commit that referenced this pull request Sep 18, 2026
Add an opt-in static receive-buffer pool whose slots are colored from the
finalized pipeline schedule. The pool retains stable tensor addresses across
successful steps while preserving the just-in-time descriptor ownership
contract. Every public multi-stage schedule exposes and documents the
`reuse_recv_buffers` option after the existing `max_active_stages` argument, so
positional callers retain their prior meaning.

Keep receive descriptors and storage ownership in `_recv_buffers.py`. Stage
execution imports those primitives, while schedule-IR lifetime analysis remains
in `schedules.py`; this preserves a one-way dependency without coupling buffer
allocation to schedule action types.

The pool retains ordinary, autograd-neutral base tensors allocated independently
of ambient inference mode. Each acquisition gives the receive descriptor a fresh
detached alias. Hooks, gradients, and `requires_grad` state therefore cannot
cross lease boundaries, while the underlying address remains stable for CUDA
graph capture and inference-to-training transitions.

Forward and backward pools are independent, use explicit assignment maps and
allocation counts, validate uniform receive metadata before allocation, and
resolve every peer before acquiring storage. Invalid routing metadata therefore
cannot leave lazy descriptors or pooled slots falsely owned. Compatible pools
grow without replacing existing storage, so train/eval transitions retain at
most the larger mode footprint while preserving captured addresses. Training
slots are released after their full or weight-backward lifetime. Inference
retains received inputs until all outstanding sends complete because the runtime
does not yet expose per-send wait actions.

Tensors that escape through network sends, same-rank stage handoffs, or final
outputs are materialized only when they alias a receive pool. Ordinary
non-aliasing values remain zero-copy. Native alias detection handles dense views
and non-strided tensors such as sparse wrappers without dereferencing unsupported
storage. Buffer acquisition and `P2POp` construction are transactional, so a
failure before launch restores both descriptor and pool ownership. Custom
receive handlers must preserve the stage receive acquire/populate contract.
Incomplete distributed steps remain fail-fast because outstanding P2P work may
still own the buffers; reconstructing the stages, schedule, and process group is
the safe retry boundary.

Test Plan:
- `python test/distributed/pipelining/test_schedule.py -v`
- `CUDA_VISIBLE_DEVICES=0,1,2,3 python test/distributed/pipelining/test_schedule_multiproc.py`
- `CUDA_VISIBLE_DEVICES=0,1,2,3 python test/distributed/pipelining/test_dtensor_pp_integration.py TestDTensorPPModes.test_static_mode_interleaved1f1b_replicate_with_recv_buffer_reuse`
- `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 test/distributed/pipelining/test_dtensor_pp_integration.py`

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

ghstack-source-id: bf77499
Pull Request resolved: #196465
[ghstack-poisoned]
sanketpurandare added a commit that referenced this pull request Sep 18, 2026
Add an opt-in static receive-buffer pool whose slots are colored from the
finalized pipeline schedule. The pool retains stable tensor addresses across
successful steps while preserving the just-in-time descriptor ownership
contract. Every public multi-stage schedule exposes and documents the
`reuse_recv_buffers` option after the existing `max_active_stages` argument, so
positional callers retain their prior meaning.

Keep receive descriptors and storage ownership in `_recv_buffers.py`. Stage
execution imports those primitives, while schedule-IR lifetime analysis remains
in `schedules.py`; this preserves a one-way dependency without coupling buffer
allocation to schedule action types.

The pool retains ordinary, autograd-neutral base tensors allocated independently
of ambient inference mode. Each acquisition gives the receive descriptor a fresh
detached alias. Hooks, gradients, and `requires_grad` state therefore cannot
cross lease boundaries, while the underlying address remains stable for CUDA
graph capture and inference-to-training transitions.

Forward and backward pools are independent, use explicit assignment maps and
allocation counts, validate uniform receive metadata before allocation, and
resolve every peer before acquiring storage. Invalid routing metadata therefore
cannot leave lazy descriptors or pooled slots falsely owned. Compatible pools
grow without replacing existing storage, so train/eval transitions retain at
most the larger mode footprint while preserving captured addresses. Training
slots are released after their full or weight-backward lifetime. Inference
retains received inputs until all outstanding sends complete because the runtime
does not yet expose per-send wait actions.

Tensors that escape through network sends, same-rank stage handoffs, or final
outputs are materialized only when they alias a receive pool. Ordinary
non-aliasing values remain zero-copy. Native alias detection handles dense views
and non-strided tensors such as sparse wrappers without dereferencing unsupported
storage. Buffer acquisition and `P2POp` construction are transactional, so a
failure before launch restores both descriptor and pool ownership. Custom
receive handlers must preserve the stage receive acquire/populate contract.
Incomplete distributed steps remain fail-fast because outstanding P2P work may
still own the buffers; reconstructing the stages, schedule, and process group is
the safe retry boundary.

Test Plan:
- `python test/distributed/pipelining/test_schedule.py -v`
- `CUDA_VISIBLE_DEVICES=0,1,2,3 python test/distributed/pipelining/test_schedule_multiproc.py`
- `CUDA_VISIBLE_DEVICES=0,1,2,3 python test/distributed/pipelining/test_dtensor_pp_integration.py TestDTensorPPModes.test_static_mode_interleaved1f1b_replicate_with_recv_buffer_reuse`
- `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 test/distributed/pipelining/test_dtensor_pp_integration.py`

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

ghstack-source-id: 9f8e99d
Pull Request resolved: #196465
[ghstack-poisoned]
sanketpurandare added a commit that referenced this pull request Sep 18, 2026
Add an opt-in static receive-buffer pool whose slots are colored from the
finalized pipeline schedule. The pool retains stable tensor addresses across
successful steps while preserving the just-in-time descriptor ownership
contract. Every public multi-stage schedule exposes and documents the
`reuse_recv_buffers` option after the existing `max_active_stages` argument, so
positional callers retain their prior meaning.

Keep receive descriptors and storage ownership in `_recv_buffers.py`. Stage
execution imports those primitives, while schedule-IR lifetime analysis remains
in `schedules.py`; this preserves a one-way dependency without coupling buffer
allocation to schedule action types.

The pool retains ordinary, autograd-neutral base tensors allocated independently
of ambient inference mode. Each acquisition gives the receive descriptor a fresh
detached alias. Hooks, gradients, and `requires_grad` state therefore cannot
cross lease boundaries, while the underlying address remains stable for CUDA
graph capture and inference-to-training transitions.

Forward and backward pools are independent, use explicit assignment maps and
allocation counts, validate uniform receive metadata before allocation, and
resolve every peer before acquiring storage. Invalid routing metadata therefore
cannot leave lazy descriptors or pooled slots falsely owned. Compatible pools
grow without replacing existing storage, so train/eval transitions retain at
most the larger mode footprint while preserving captured addresses. Training
slots are released after their full or weight-backward lifetime. Inference
retains received inputs until all outstanding sends complete because the runtime
does not yet expose per-send wait actions.

Tensors that escape through network sends, same-rank stage handoffs, or final
outputs are materialized only when they alias a receive pool. Ordinary
non-aliasing values remain zero-copy. Native alias detection handles dense views
and non-strided tensors such as sparse wrappers without dereferencing unsupported
storage. Buffer acquisition and `P2POp` construction are transactional, so a
failure before launch restores both descriptor and pool ownership. Custom
receive handlers must preserve the stage receive acquire/populate contract.
Incomplete distributed steps remain fail-fast because outstanding P2P work may
still own the buffers; reconstructing the stages, schedule, and process group is
the safe retry boundary.

Test Plan:
- `python test/distributed/pipelining/test_schedule.py -v`
- `CUDA_VISIBLE_DEVICES=0,1,2,3 python test/distributed/pipelining/test_schedule_multiproc.py`
- `CUDA_VISIBLE_DEVICES=0,1,2,3 python test/distributed/pipelining/test_dtensor_pp_integration.py TestDTensorPPModes.test_static_mode_interleaved1f1b_replicate_with_recv_buffer_reuse`
- `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 test/distributed/pipelining/test_dtensor_pp_integration.py`

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

ghstack-source-id: 3bd2447
Pull Request resolved: #196465
Add an opt-in static receive-buffer pool whose slots are colored from the
finalized pipeline schedule. The pool retains stable tensor addresses across
successful steps while preserving the just-in-time descriptor ownership
contract. Every public multi-stage schedule exposes and documents the
`reuse_recv_buffers` option after the existing `max_active_stages` argument, so
positional callers retain their prior meaning.

Keep receive descriptors and storage ownership in `_recv_buffers.py`. Stage
execution imports those primitives, while schedule-IR lifetime analysis remains
in `schedules.py`; this preserves a one-way dependency without coupling buffer
allocation to schedule action types.

The pool retains ordinary, autograd-neutral base tensors allocated independently
of ambient inference mode. Each acquisition gives the receive descriptor a fresh
detached alias. Hooks, gradients, and `requires_grad` state therefore cannot
cross lease boundaries, while the underlying address remains stable for CUDA
graph capture and inference-to-training transitions.

Forward and backward pools are independent, use explicit assignment maps and
allocation counts, validate uniform receive metadata before allocation, and
resolve every peer before acquiring storage. Invalid routing metadata therefore
cannot leave lazy descriptors or pooled slots falsely owned. Compatible pools
grow without replacing existing storage, so train/eval transitions retain at
most the larger mode footprint while preserving captured addresses. Training
slots are released after their full or weight-backward lifetime. Inference
retains received inputs until all outstanding sends complete because the runtime
does not yet expose per-send wait actions.

Tensors that escape through network sends, same-rank stage handoffs, or final
outputs are materialized only when they alias a receive pool. Ordinary
non-aliasing values remain zero-copy. Native alias detection handles dense views
and non-strided tensors such as sparse wrappers without dereferencing unsupported
storage. Buffer acquisition and `P2POp` construction are transactional, so a
failure before launch restores both descriptor and pool ownership. Custom
receive handlers must preserve the stage receive acquire/populate contract.
Incomplete distributed steps remain fail-fast because outstanding P2P work may
still own the buffers; reconstructing the stages, schedule, and process group is
the safe retry boundary.

Test Plan:
- `python test/distributed/pipelining/test_schedule.py -v`
- `CUDA_VISIBLE_DEVICES=0,1,2,3 python test/distributed/pipelining/test_schedule_multiproc.py`
- `CUDA_VISIBLE_DEVICES=0,1,2,3 python test/distributed/pipelining/test_dtensor_pp_integration.py TestDTensorPPModes.test_static_mode_interleaved1f1b_replicate_with_recv_buffer_reuse`
- `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 test/distributed/pipelining/test_dtensor_pp_integration.py`

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

[ghstack-poisoned]
sanketpurandare added a commit that referenced this pull request Sep 18, 2026
Add an opt-in static receive-buffer pool whose slots are colored from the
finalized pipeline schedule. The pool retains stable tensor addresses across
successful steps while preserving the just-in-time descriptor ownership
contract. Every public multi-stage schedule exposes and documents the
`reuse_recv_buffers` option after the existing `max_active_stages` argument, so
positional callers retain their prior meaning.

Keep receive descriptors and storage ownership in `_recv_buffers.py`. Stage
execution imports those primitives, while schedule-IR lifetime analysis remains
in `schedules.py`; this preserves a one-way dependency without coupling buffer
allocation to schedule action types.

The pool retains ordinary, autograd-neutral base tensors allocated independently
of ambient inference mode. Each acquisition gives the receive descriptor a fresh
detached alias. Hooks, gradients, and `requires_grad` state therefore cannot
cross lease boundaries, while the underlying address remains stable for CUDA
graph capture and inference-to-training transitions.

Forward and backward pools are independent, use explicit assignment maps and
allocation counts, validate uniform receive metadata before allocation, and
resolve every peer before acquiring storage. Invalid routing metadata therefore
cannot leave lazy descriptors or pooled slots falsely owned. Compatible pools
grow without replacing existing storage, so train/eval transitions retain at
most the larger mode footprint while preserving captured addresses. Training
slots are released after their full or weight-backward lifetime. Inference
retains received inputs until all outstanding sends complete because the runtime
does not yet expose per-send wait actions.

Tensors that escape through network sends, same-rank stage handoffs, or final
outputs are materialized only when they alias a receive pool. Ordinary
non-aliasing values remain zero-copy. Native alias detection handles dense views
and non-strided tensors such as sparse wrappers without dereferencing unsupported
storage. Buffer acquisition and `P2POp` construction are transactional, so a
failure before launch restores both descriptor and pool ownership. Custom
receive handlers must preserve the stage receive acquire/populate contract.
Incomplete distributed steps remain fail-fast because outstanding P2P work may
still own the buffers; reconstructing the stages, schedule, and process group is
the safe retry boundary.

Test Plan:
- `python test/distributed/pipelining/test_schedule.py -v`
- `CUDA_VISIBLE_DEVICES=0,1,2,3 python test/distributed/pipelining/test_schedule_multiproc.py`
- `CUDA_VISIBLE_DEVICES=0,1,2,3 python test/distributed/pipelining/test_dtensor_pp_integration.py TestDTensorPPModes.test_static_mode_interleaved1f1b_replicate_with_recv_buffer_reuse`
- `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 test/distributed/pipelining/test_dtensor_pp_integration.py`

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

ghstack-source-id: 04608a3
Pull Request resolved: #196465
Add an opt-in static receive-buffer pool whose slots are colored from the
finalized pipeline schedule. The pool retains stable tensor addresses across
successful steps while preserving the just-in-time descriptor ownership
contract. Every public multi-stage schedule exposes and documents the
`reuse_recv_buffers` option after the existing `max_active_stages` argument, so
positional callers retain their prior meaning.

Keep receive descriptors and storage ownership in `_recv_buffers.py`. Stage
execution imports those primitives, while schedule-IR lifetime analysis remains
in `schedules.py`; this preserves a one-way dependency without coupling buffer
allocation to schedule action types.

The pool retains ordinary, autograd-neutral base tensors allocated independently
of ambient inference mode. Each acquisition gives the receive descriptor a fresh
detached alias. Hooks, gradients, and `requires_grad` state therefore cannot
cross lease boundaries, while the underlying address remains stable for CUDA
graph capture and inference-to-training transitions.

Forward and backward pools are independent, use explicit assignment maps and
allocation counts, validate uniform receive metadata before allocation, and
resolve every peer before acquiring storage. Invalid routing metadata therefore
cannot leave lazy descriptors or pooled slots falsely owned. Compatible pools
grow without replacing existing storage, so train/eval transitions retain at
most the larger mode footprint while preserving captured addresses. Training
slots are released after their full or weight-backward lifetime. Inference
retains received inputs until all outstanding sends complete because the runtime
does not yet expose per-send wait actions.

Tensors that escape through network sends, same-rank stage handoffs, or final
outputs are materialized only when they alias a receive pool. Ordinary
non-aliasing values remain zero-copy. Native alias detection handles dense views
and non-strided tensors such as sparse wrappers without dereferencing unsupported
storage. Buffer acquisition and `P2POp` construction are transactional, so a
failure before launch restores both descriptor and pool ownership. Custom
receive handlers must preserve the stage receive acquire/populate contract.
Incomplete distributed steps remain fail-fast because outstanding P2P work may
still own the buffers; reconstructing the stages, schedule, and process group is
the safe retry boundary.

Test Plan:
- `python test/distributed/pipelining/test_schedule.py -v`
- `CUDA_VISIBLE_DEVICES=0,1,2,3 python test/distributed/pipelining/test_schedule_multiproc.py`
- `CUDA_VISIBLE_DEVICES=0,1,2,3 python test/distributed/pipelining/test_dtensor_pp_integration.py TestDTensorPPModes.test_static_mode_interleaved1f1b_replicate_with_recv_buffer_reuse`
- `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 test/distributed/pipelining/test_dtensor_pp_integration.py`

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

[ghstack-poisoned]
sanketpurandare added a commit that referenced this pull request Sep 21, 2026
Add an opt-in static receive-buffer pool whose slots are colored from the
finalized pipeline schedule. The pool retains stable tensor addresses across
successful steps while preserving the just-in-time descriptor ownership
contract. Every public multi-stage schedule exposes and documents the
`reuse_recv_buffers` option after the existing `max_active_stages` argument, so
positional callers retain their prior meaning.

Keep receive descriptors and storage ownership in `_recv_buffers.py`. Stage
execution imports those primitives, while schedule-IR lifetime analysis remains
in `schedules.py`; this preserves a one-way dependency without coupling buffer
allocation to schedule action types.

The pool retains ordinary, autograd-neutral base tensors allocated independently
of ambient inference mode. Each acquisition gives the receive descriptor a fresh
detached alias. Hooks, gradients, and `requires_grad` state therefore cannot
cross lease boundaries, while the underlying address remains stable for CUDA
graph capture and inference-to-training transitions.

Forward and backward pools are independent, use explicit assignment maps and
allocation counts, validate uniform receive metadata before allocation, and
resolve every peer before acquiring storage. Invalid routing metadata therefore
cannot leave lazy descriptors or pooled slots falsely owned. Compatible pools
grow without replacing existing storage, so train/eval transitions retain at
most the larger mode footprint while preserving captured addresses. Training
slots are released after their full or weight-backward lifetime. Inference
retains received inputs until all outstanding sends complete because the runtime
does not yet expose per-send wait actions.

Tensors that escape through network sends, same-rank stage handoffs, or final
outputs are materialized only when they alias a receive pool. Ordinary
non-aliasing values remain zero-copy. Native alias detection handles dense views
and non-strided tensors such as sparse wrappers without dereferencing unsupported
storage. Buffer acquisition and `P2POp` construction are transactional, so a
failure before launch restores both descriptor and pool ownership. Custom
receive handlers must preserve the stage receive acquire/populate contract.
Incomplete distributed steps remain fail-fast because outstanding P2P work may
still own the buffers; reconstructing the stages, schedule, and process group is
the safe retry boundary.

Test Plan:
- `python test/distributed/pipelining/test_schedule.py -v`
- `CUDA_VISIBLE_DEVICES=0,1,2,3 python test/distributed/pipelining/test_schedule_multiproc.py`
- `CUDA_VISIBLE_DEVICES=0,1,2,3 python test/distributed/pipelining/test_dtensor_pp_integration.py TestDTensorPPModes.test_static_mode_interleaved1f1b_replicate_with_recv_buffer_reuse`
- `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 test/distributed/pipelining/test_dtensor_pp_integration.py`

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

ghstack-source-id: 73e4976
Pull Request resolved: #196465
@github-actions

Copy link
Copy Markdown
Contributor

Looks like this PR hasn't been updated in a while so we're going to go ahead and mark this as Stale.
Feel free to remove the Stale label if you feel this was a mistake.
If you are unable to remove the Stale label please contact a maintainer in order to do so.
If you want the bot to never mark this PR stale again, add the no-stale label.
Stale pull requests will automatically be closed after 30 days of inactivity.

@github-actions github-actions Bot added the Stale label Nov 20, 2026

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants