Repository navigation
[pipelining] Analyze pipeline activation liveness from schedules - #196464
sanketpurandare wants to merge 15 commits into
Conversation
[ghstack-poisoned]
🔗 Helpful Links🧪 See artifacts and rendered test results at hud.pytorch.org/pr/196464
Note: Links to docs will display an error until the docs builds have been completed. ❗ 1 Active SEVsThere are 1 currently active SEVs. If your PR is affected, please view them below: ✅ No FailuresAs of commit ceb72e0 with merge base 38e2a2e ( This comment was automatically generated by Dr. CI and updates every 15 minutes. |
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
[ghstack-poisoned]
|
@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 finished @sanketpurandare's task in 29m 27s —— View job This PR lands 343 lines of resource-liveness analysis with zero in-tree consumers, and the two new entry points have inconsistent APIs, inconsistent
|
[ghstack-poisoned]
|
@claude Reduced the change to one deterministic inclusive-interval coloring helper and one compact stage/microbatch liveness result used by the stacked receive-pool PR and the external Dist-MoE activation planner. Removed duplicate slot fields, |
|
Claude finished @sanketpurandare's task in 25m 9s —— View job The rewrite is a real improvement — every item from the last round is genuinely addressed and the greedy coloring is provably minimal and deterministic — but two of the claimed new assertions (cross-rank, minimum coloring) aren't actually in the diff, the
|
| Claim | Status |
|---|---|
| One coloring helper | ✅ _assign_pipeline_resource_slots (schedules.py:224), single caller |
| One compact result type | ✅ _PipelineResourceLiveness (:203), 6 fields |
peak_live_count removed |
✅ |
| Linear lookup removed | ✅ slot_for is a dict hit (:217) |
| Recv-specific policy removed | ✅ _assign_pipeline_recv_buffer_slots / _PipelineRecvBufferSlots deleted entirely |
| Sparse-result assumptions removed | ✅ assignments is dense over expected (:4087-4094) |
| Duplicate slot fields removed | ✅ no _PipelineResourceLifetime, no start_position/release_position/local_compute_actions |
OVERLAP_F_B handled |
✅ recursed into (:3998-4001) instead of rejected |
Also silently fixed and worth noting: getattr(schedule, "pipeline_order_with_comms", None) → isinstance(schedule, _PipelineScheduleRuntime) (:3985), the dead next_slot coupling collapsed (:237-241), sorted(..., key=str) dropped, physical_rank → rank, and MappingProxyType for real immutability. Net −20 lines with strictly more coverage. Good pass.
I hand-traced all three fixtures against the allocator and every asserted number is correct ([0,1,0]; [0,1,2,0] with num_slots=3; num_slots=1 for the overlap case). The algorithm is sound: greedy-by-left-endpoint on an interval graph uses exactly max-clique colors, and the strict active[0][0] < start guard correctly implements closed-interval overlap, so a slot released at position p is never reused at p. The min-heap on free_slots makes the choice deterministic.
Claims not backed by the diff
-
"cross-rank analysis ... now [has] independent assertions" — there is no such test. All three new tests pass
rank=0. Therank not in pipeline_orderraise (:3989) is uncovered, andrankis still never validated againstschedule.rank(:2047), so a caller can hand in another rank's index and get a plan for actions that aren't local. That may be intentional (the docstring says "Pipeline rank whose local actions should be analyzed", which reads as local-only), but it's neither enforced nor tested. A 2-rank fixture asserting the two ranks get different plans would cover this and is ~10 lines. Fix this → -
"minimum coloring ... [has an] independent assertion" —
num_slotsis only compared to a hardcoded literal.assertEqual(plan.num_slots, 2)/(stage_plan.num_slots, 3)restate what the allocator produced; nothing independently computes max-overlap. The previous round's complaint aboutpeak_live_countwas that it couldn't disagree withnum_slots— the same gap now lives in the test. An independent check is ~4 lines and is the assertion that would actually catch a regression in the allocator:events = sorted([(s, 1) for _, s, _ in intervals] + [(r + 1, -1) for _, _, r in intervals])
i.e. sweep the closed intervals and assert
maxrunning count== num_slots. Worth adding as a helper used by both granularity cases. -
"exact reuse" and "split I/W release" — genuinely covered.
test_pipeline_resource_liveness_reuses_completed_slots(test_schedule.py:187) asserts the exact reuse pattern[0, 1, 0], and itsI/Wfixture does pin the release-at-Wpolicy. These two claims hold.
Correctness
-
The W-without-I check is order-dependent inside an
OVERLAP_F_Bcontainer, and the one test that exercises containers relies on that order.process(:3997) populatesinput_backwardsas it walks, so the check at:4029-4034requiresIto be visited beforeW. In the flat action list that's guaranteed by time order, but sub-actions in a container are concurrent — the tuple order is an artifact of how the schedule generator built it. The test fixture attest_schedule.py:266-271hardcodes(I0, W0); flip it to(W0, I0)— semantically identical for an overlapped action — and the analyzer raises. Collectinput_backwardsin a first pass over all actions, then validate releases in a second pass, and the check becomes order-free. Fix this → -
releases[key] <= starts[key]raises "ends before its forward", but==means at the same position.:4060-4062. The==case is reachable in principle (anOVERLAP_F_Bwhose sub-actions are theFand the release for the same(stage, mb)), and the message misdescribes it. One-word fix; mention "at or before". -
The
isinstance(schedule, _PipelineScheduleRuntime)branch deserves a one-line comment for why. For every in-tree runtime schedule both lists exist and the comms lowering passes only insert comm actions (_add_unshard_reshard,_add_reduce_grad,_add_send_recv,_defer_recv_ops) without reordering compute, so both lists yield identical slots. The branch is only load-bearing for_load_csv(format="compute_comms"), which populatespipeline_order_with_commsand leavespipeline_orderempty (:2665-2671). Without that note a future reader will reasonably delete the branch. -
@dataclass(frozen=True)+ aMappingProxyTypefield makes the generated__hash__raise.frozen=Truewith defaulteq=Truegenerates__hash__from the field tuple, andmappingproxyis unhashable, sohash(plan)is aTypeError. Eithereq=Falseorunsafe_hash-free explicit__hash__, or just accept it — but it's a trap for anyone caching plans in aset/dict key. -
stage_indicesisn't checked for locality, so a non-local stage surfaces as a confusing error. Passing a stage that lives on another rank produces "Forward actions do not match tracked lifetimes; missing=[...]" rather than "stage X is not on rank R".schedule.stage_index_to_group_rank(:2049) is right there. Better still: defaultstage_indicesto the rank's local stages and make the arg optional — that removes a required argument, removes this error class, and matches what both stated consumers actually want.
API / compactness
-
_PipelineResourceKey = int | tuple[int, int]exists only because the helper carries keys it never inspects._assign_pipeline_resource_slots(:224) useskeypurely as a dict label. Drop it: takeSequence[tuple[int, int]]of(start, release)and return(list[int], int)where sloticorresponds to input intervali. That deletes the union alias, and the awkward conditional dict comprehension at:4087-4094:assignments = { (stage_index, microbatch_index): resource_assignments[ microbatch_index if granularity == "microbatch" else (stage_index, microbatch_index) ] ... }
collapses into each branch building its own
assignmentsdirectly. Net simpler and removes the last place where the two granularities are entangled. -
The double sort hides the determinism guarantee.
:4083sorts by(starts[item], item), then the helper re-sorts by(start, release)(:233). The outer sort is what makes ties deterministic when two lifetimes share both endpoints — reachable viaOVERLAP_F_Bposition collapsing. Either fold the tie-break into the helper's key ((start, release, index)) and drop the outer sort, or comment that the outer sort is load-bearing. As written it reads redundant and someone will remove it. -
Two gratuitous line splits at
:4017-4020and:4023-4026— both fit on one line under 88 cols.CLAUDE.mdexplicitly asks to undo ruff's splits where possible. -
granularityis stored on the result but never read by it. Fine as consumer metadata, but note thatrank,granularity,stage_indices, andnum_microbatchesare all pure passthrough — onlyassignmentsandnum_slotscarry computed information. -
Placement. The dataclass + helper are at
:199-245, the analyzer at:3948— ~3700 lines apart in a 4460-line file, with the top-of-file pair sandwiched between_Actionand_get_profiler_function_name. Colocating all three (or moving them to_resource_liveness.py) would help; the code has no dependency on the schedule classes beyond two attribute reads and oneisinstance.
Testing
-
Nothing tests this against a real schedule. All three fixtures hand-write
pipeline_order.test_schedule.py:936already shows the pattern for building a realScheduleDualPipeVfromMockPipelineStage; one such test would simultaneously cover the actualOVERLAP_F_Bshape ((F stage_a mb_i ; FULL_BACKWARD stage_b mb_j)fromadd_overlap_f_bat:3822-3826— note it is not the(I, W)shape the current test fabricates), thepipeline_order_with_commsbranch, theNone-bubble path at:4038, and the split I/W releases from steps 6-8. It would also catch drift if a schedule generator changes. This is the single highest-value test to add. Fix this → -
test_pipeline_resource_liveness_granularity_and_overlapis three tests in one method (test_schedule.py:215-281): stage granularity, microbatch granularity, and a from-scratch overlap schedule.CLAUDE.mdpoints at@parametrize; at minimum split the overlap case out so a failure names which scenario broke. The overlap sub-case also reusesstages[0](built withnum_stages=3) in a 1-stagePipelineScheduleMulti, which is internally inconsistent even if harmless here. -
Microbatch granularity has no reuse coverage. The fixture yields
{mb0: 0, mb1: 1}withnum_slots == 2 == n_microbatches— the identity map. So themin(starts)/max(releases)merge (:4066-4079) is exercised, but the reuse path at that granularity never is. Extend to 3+ microbatches so at least one slot is recycled, mirroring what the stage-granularity test does. -
11 of 12
raisesites remain uncovered: invalidgranularity(:3975), emptystage_indices(:3979), duplicatestage_indices(:3981), rank absent (:3989), missing microbatch index (:4005), out-of-range microbatch (:4008), duplicate forward (:4014), duplicate input backward (:4019), duplicate release (:4025), W-without-I (:4032), release-at-or-before-forward (:4062), andslot_for'sValueError(:219). Only the missing-release path is tested. The three encoding real design decisions — W-without-I, release-before-forward, andslot_foron an untracked stage — are the ones to add; a single@parametrized table over(pipeline_order, expected_regex)covers most of the rest cheaply.
Still open from round 1
No in-tree consumer. Grep across the repo confirms only test_schedule.py references any of this. You've stated #196465 (stacked receive-pool) and an external Dist-MoE planner consume it — but if #196465 only uses "stage_microbatch", the "microbatch" granularity, the min/max merge, and the granularity field all land with no in-tree user, which is the "design for hypothetical future requirements" case CLAUDE.md warns about. Landing this together with #196465 would let you keep only the granularity that has a consumer. Your call, but worth an explicit decision rather than defaulting.
Recommendation
Approve with comments — the design is now sound and the surface is defensible. Before merge I'd want: the two-pass fix for the order-dependent W-without-I check, the independent max-overlap assertion (it's the one that makes "minimum coloring" a real claim), a test against a real ScheduleDualPipeV, and either a rank == schedule.rank check or a docstring line saying cross-rank is supported. The _PipelineResourceKey removal and the stage_indices default are optional but would meaningfully compact this.
…dules" Summary: Add a compact schedule-liveness utility that deterministically assigns reusable resource slots to microbatches or stage/microbatch pairs. The analyzer consumes the finalized schedule when available, treats each lifetime as inclusive from forward through full or weight backward, and handles compound `OVERLAP_F_B` actions. The API exposes only the metadata consumers need: rank, granularity, tracked stages, microbatch count, direct slot assignments, and slot count. It also provides the shared inclusive-interval coloring primitive used by the stacked static receive-buffer pool. The stage/microbatch plan is consumed externally by Dist-MoE activation arenas. Test Plan: - `python test/distributed/pipelining/test_schedule.py -k pipeline_resource_liveness` [ghstack-poisoned]
[ghstack-poisoned]
|
@claude Made compound-action validation order-independent, reduced the allocator to ordered intervals with deterministic lowest-slot coloring, and documented cross-rank analysis. Tests now independently compute closed-interval peak overlap, exercise distinct plans on different ranks, reverse compound sub-action order, validate exact reuse, and run against a real |
|
Claude finished @sanketpurandare's task in 17m 37s —— View job Round 3 is clean: all six claims hold, the greedy coloring is now checked against a genuinely independent closed-interval sweep, and the compound-action ordering bug is fixed by construction — the only real gaps left are that the microbatch granularity's
|
| Claim | Status |
|---|---|
| Compound-action validation order-independent | ✅ process (schedules.py:4009) now only collects into input_backwards/weight_backwards; the W-without-I check runs after the full walk (:4066). Order-free by construction, not by test. |
| Allocator reduced to ordered intervals | ✅ _assign_pipeline_resource_slots(intervals) -> (list[int], int) (:3930). _PipelineResourceKey union alias gone; the conditional dict comprehension is gone. |
| Cross-rank analysis documented | ✅ :3968-3970 — "may differ from the rank constructing the schedule because every rank owns the complete finalized order." |
| Independent closed-interval peak overlap | ✅ _max_live_closed_intervals (test_schedule.py:149). Correct: (release + 1, -1) makes -1 sort before a +1 at the same key, which is exactly the closed-interval semantics the allocator's strict active[0][0] < start guard implements. |
| Distinct plans on different ranks | ✅ The loop at test_schedule.py:337 actually runs rank=1 against a schedule whose self.rank is 0 and validates it against an independent sweep of rank 1's actions. That is real cross-rank coverage. The rank not present raise is now covered too (:376). |
| Reversed compound sub-action order | ✅ test_pipeline_resource_liveness_overlap_is_order_independent (:317) loops both (I, W) and (W, I). |
Real ScheduleDualPipeV incl. comms lowering |
✅ :355, reading pipeline_order_with_comms. |
Also picked up from round 2 without being claimed: the three pieces are now colocated (:3906-4106) instead of 3700 lines apart, eq=False fixes the unhashable-mappingproxy trap, the isinstance branch has its why comment (:3993), and the release-at-W docstring now gives the correct dw_builder-closure reason instead of the wrong "later weight-backward consumes state" one.
I hand-traced all three hand-written fixtures plus the coloring: [(0,3),(1,6),(4,8)] → [0,1,0], num_slots=2; [(0,4),(1,3),(2,7),(5,6)] → [0,1,2,0], num_slots=3; microbatch merge mb0=(0,4), mb1=(2,7), num_slots=2; overlap case (0,1), num_slots=1. Every asserted number is right.
Round 2's position-provenance concern is now moot — start_position/release_position no longer escape the analyzer, so it doesn't matter which list the indices came from. And worth noting for the isinstance branch: the lowering passes (_add_unshard_reshard, _add_reduce_grad, _add_send_recv, _defer_recv_ops) only insert comm actions and never reorder compute, so the interval ordering is order-isomorphic between the two lists and the slots come out identical. The branch is behavior-neutral outside the _load_csv(format="compute_comms") path.
Testing
-
The microbatch granularity's
num_slotsis still only compared to a literal.test_schedule.py:322assertsmicrobatch_plan.num_slots == 2, but_max_live_closed_intervalsis only applied to the stage-granularity intervals (:307) and the DualPipeV plan (:370). The mergedmin(starts)/max(releases)intervals (schedules.py:4076-4088) are exactly the part a regression would silently break, and they're the one place the sweep isn't used. Two lines:_max_live_closed_intervals([(0, 4), (2, 7)]). Better still, derive the merged intervals from_resource_intervalsoutput so the oracle doesn't hardcode the merge either. Fix this → -
assertNotEqual(plans[0].assignments, plans[1].assignments)(test_schedule.py:371) is trivially true. Rank 0 owns stages(0, 3)and rank 1 owns(1, 2)under the V mapping, so the two mappings have entirely disjoint key sets — they could not compare equal regardless of what the allocator did. It reads like the headline cross-rank assertion but carries no information. The load-bearing cross-rank coverage is already the per-rank sweep inside the loop; either drop this line or replace it with something that can fail (e.g. assert each plan's key set equals that rank'sstage_indices× microbatches, or thatplans[1]is identical to what a rank-1-constructed schedule produces). -
_resource_intervals(test_schedule.py:161) re-implements the analyzer's release policy, not just its traversal: samesub_actionsrecursion, same F-starts /(B, W)-releases rule. That makes it a valid oracle for the allocator but not for the policy — if release-at-Wwere changed to release-at-Iin both places the tests would still pass. That's the right design for an independent check, but a one-line comment saying "mirrors the release policy deliberately; validates the coloring, not the policy" would stop a reader from over-trusting it. -
8
raisesites remain uncovered: invalidgranularity(:3986), emptystage_indices(:3990), duplicatestage_indices(:3992), missing microbatch index (:4017), out-of-range microbatch (:4018), duplicate forward (:4026), duplicate input backward (:4030), duplicate release (:4036), release-at-or-before-forward (:4072), W-without-I (:4067), andslot_for'sValueError(:3925). Down from 11 —rank not presentand the missing-release path are now covered. The two encoding real design decisions are W-without-I andslot_foron an untracked pair; the rest are cheap in one@parametrized(pipeline_order, expected_regex)table if you want them. -
overlap_scheduleintest_pipeline_resource_liveness_rejects_incomplete_backward(:385) contains no overlap — leftover name from an earlier revision.
Compactness
-
The outer sort reduces to
sorted(expected).schedules.py:4095:keys = sorted(expected, key=lambda item: (starts[item], releases[item], item))
The helper already sorts
enumerate(intervals)by(start, release, index)(:3939-3941), so the only thing the outer sort contributes is the tie-break-by-key, andindexinherits that fromkeys' order. Sortingexpectedlexicographically gives the identicalassignments— for any two keys with equal(start, release), both orderings put the lexicographically smaller key first. Sokeys = sorted(expected)is provably equivalent and drops the lambda plus the double-sort confusion round 2 flagged. -
assignmentsinsertion order differs between the two branches. Thestage_microbatchbranch builds it from sortedkeys(:4098); themicrobatchbranch iteratesexpected, aset(:4092), so its iteration order comes from tuple hashing. A consumer that allocates buffers by walkingplan.assignments.items()gets a stable-but-arbitrary order in one granularity and a sorted order in the other.for stage_index, microbatch_index in sorted(expected)makes both branches agree, for free.
Minor / soundness
-
releases[key] <= starts[key]rejects a legitimate point interval.schedules.py:4072. A lifetime whose start and release land at the same position — reachable in principle via anOVERLAP_F_Bcollapsing both onto one index — is perfectly colorable: it's the closed interval[p, p], and both the allocator and the sweep handle it correctly. It's unreachable in-tree (add_overlap_f_bat:3780-3783always pairs different stages, and in the V layout a rank's two stages are never equal), so this is a policy choice rather than a guard against a real state. If the intent is "a resource must survive at least one action boundary", say that; otherwise<is the more defensible comparison. -
stage_indicesis still not checked for locality, so passing a stage that lives on another rank surfaces asForward actions do not match tracked lifetimes; missing=[...]rather than naming the real problem.schedule.stage_index_to_group_rankis right there. The stronger version of this — defaultingstage_indicesto the rank's local stages — would remove a required argument and this whole error class, and is what both stated consumers appear to want (the DualPipeV test derives exactly that value by hand attest_schedule.py:340-344). Note this only makes sense if you keep the local-analysis framing; it's in tension with the cross-rank support you just documented, so pick deliberately. -
eq=Falsemakes plan equality identity-based.schedules.py:3909. Correct choice —frozen=Truewitheq=Truewould generate a__hash__over the field tuple andhash(plan)wouldTypeErroron themappingproxy. But it means two structurally identical plans compare unequal, which is surprising for a frozen value type. One trailing comment on the decorator saying "eq=False keeps the plan hashable despite the mappingproxy field" would save the next reader the derivation. -
granularityandnum_microbatchesare pure passthrough — the result computes onlyassignmentsandnum_slots. Fine as consumer metadata, just noting the surface is 4 echoed fields to 2 computed ones.
Still open from rounds 1–2
No in-tree consumer. Grep confirms only test_schedule.py references any of this. You've named #196465 (stacked receive-pool) and an external Dist-MoE planner. If #196465 only consumes "stage_microbatch", then the "microbatch" granularity, the min/max merge, and the granularity field all land with no in-tree user — the case CLAUDE.md warns about. Landing the two together would let you keep only what's consumed. Your call; I'd just make it an explicit decision rather than a default.
Recommendation
Approve. The design is sound, the allocator is provably minimal and deterministic for interval graphs, and the validation is now order-free by construction. Nothing here is blocking. If you're doing one more pass, the two worth taking are the microbatch-granularity sweep assertion (it's the half of "minimum coloring" that isn't yet independently checked) and dropping the tautological assertNotEqual — plus keys = sorted(expected) and the shared sorted(expected) in both branches, which are net-negative-line cleanups.
| rank: Pipeline rank whose actions should be analyzed. This may differ | ||
| from the rank constructing the schedule because every rank owns the | ||
| complete finalized order. | ||
| stage_indices: Global logical stages that use the planned resource. |
There was a problem hiding this comment.
usually, these the vpp stages sharing the same physical rank
There was a problem hiding this comment.
yes but depending on the schedule, a pp rank might have different stages on the rank
…dules" Pipeline-integrated runtimes need deterministic bounded storage for resources whose lifetime spans forward to backward. Derive inclusive lifetimes from a finalized schedule and assign the lowest available slot with interval coloring. The result supports either one lifetime per microbatch or independent stage/microbatch lifetimes, including cross-rank analysis of the globally known schedule. Atomic schedule actions are collected before validation, so concurrent I/W subactions are independent of tuple order. The compact coloring helper operates only on ordered intervals; resource identity remains in the liveness analyzer, which keeps the allocation policy generic without a union-typed key abstraction. The greedy coloring is deterministic and minimal for interval graphs. Tests validate its slot count against an independent closed-interval sweep, cover both granularities and exact reuse, analyze multiple ranks, and exercise the real DualPipeV schedule including its atomic actions and communication lowering. Test Plan: - `python test/distributed/pipelining/test_schedule.py -k pipeline_resource_liveness` - `lintrunner --config=.lintrunner.toml torch/distributed/pipelining/schedules.py test/distributed/pipelining/test_schedule.py` AI assistance disclosure: > This change was authored with assistance from an AI coding tool and reviewed by the author. [ghstack-poisoned]
[ghstack-poisoned]
…edules" 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. [ghstack-poisoned]
[ghstack-poisoned]
…edules"
## Background
Pipeline schedules determine when a forward activation becomes live and when
backward has consumed it, but memory planners previously had to rediscover that
information from schedule internals. Counting microbatches is insufficient for
interleaved schedules: one physical PP rank can own several virtual stages, and
their activation lifetimes overlap differently according to the finalized
action order.
This PR exposes an allocation-free analysis that converts a finalized
multi-stage schedule into deterministic logical activation slots. The result is
useful for memory-capacity analysis and for consumers that map stable slot IDs
to their own tensors, arenas, or device/host storage policy.
## Before and after
| Concern | Before | After |
| --- | --- | --- |
| Activation lifetime | Consumers inferred it independently from schedule actions. | One public utility derives an inclusive forward-to-release interval. |
| VPP stages | Microbatch count did not express overlapping local stages. | Callers select the global logical stages hosted by the PP rank. |
| Slot count | Memory planners implemented their own reuse/coloring logic. | Deterministic interval coloring returns the minimum logical slot count. |
| Storage ownership | Analysis and allocation could become coupled. | The result owns no tensor or storage; callers map slot IDs to memory. |
| Split backward | Input backward could be mistaken for activation release. | Weight backward is the release point because dW may still need forward state. |
## Public API
```python
plan = analyze_pipeline_activation_liveness(
schedule,
pp_rank=pp_rank,
stage_indices=local_stage_indices,
granularity="stage_microbatch",
)
```
The function returns an immutable `PipelineActivationLiveness` plan:
| Field or method | Meaning |
| --- | --- |
| `pp_rank` | Rank in the pipeline process group whose finalized action sequence was analyzed. |
| `stage_indices` | Global logical stages selected on that rank, commonly its VPP stages. |
| `num_microbatches` | Number of microbatches represented by the schedule. |
| `granularity` | Whether storage is planned per stage/microbatch or conservatively per microbatch. |
| `slot_by_stage_and_microbatch` | Immutable `(stage_idx, mb_idx) -> slot_id` mapping. |
| `num_slots` | Number of logical slots required by the assignment. |
| `slot_for(stage_idx, mb_idx)` | Checked lookup of the assigned slot. |
| `get_activation_lifetime(stage_idx, mb_idx)` | Checked lookup of the inclusive schedule interval. |
The plan does not allocate or own slot instances. A consumer decides the
storage type, address, size, alignment, and reuse policy. If activations mapped
to one slot have different sizes, that consumer must size the slot for every
assigned activation or group only compatible activations.
## Activation lifetime semantics
| Schedule action | Effect on activation state |
| --- | --- |
| Forward `F` | Starts the activation lifetime. |
| Full backward `B` | Releases the activation after the action completes. |
| Input backward `I` | Does not release it; a later dW may still consume forward state. |
| Weight backward `W` | Releases the activation for split I/W schedules. |
| Compound action | All sub-actions share one inclusive schedule position, so an interval ending there cannot share with one starting there. |
The analyzer validates exactly one forward and one valid release action for
every selected `(stage, microbatch)` pair. It rejects missing/duplicate actions,
out-of-range microbatches, release-before-forward, and a weight backward without
its corresponding input backward.
## Granularity
| Granularity | Lifetime and slot contract | Intended use |
| --- | --- | --- |
| `stage_microbatch` | Each selected `(stage, microbatch)` keeps its own interval and may reuse independently. | Fine-grained arenas where individual stage state can be recycled. |
| `microbatch` | All selected stages for one microbatch share the convex hull from the earliest forward to the latest release and receive one slot ID. | Consumers that allocate or retire all local VPP-stage state as one unit. |
For this simplified order:
```text
position: 0 1 2 3 4 5 6 7
action: F0,0 F1,0 F0,1 B1,0 B0,0 F1,1 B1,1 B0,1
```
`stage_microbatch` produces lifetimes `(0,4)`, `(1,3)`, `(2,7)`, and
`(5,6)`, allowing the last activation to reuse the earliest freed slot.
`microbatch` instead produces conservative lifetimes `(0,4)` and `(2,7)` for
microbatches 0 and 1.
## Algorithm and determinism
1. Select the finalized action sequence for `pp_rank`; runtime schedules use
their compute-and-communication order.
2. Recursively inspect compound actions while retaining their shared position.
3. Record forward and release positions for every selected activation.
4. Optionally merge selected stage intervals into a per-microbatch convex hull.
5. Sort intervals by start, release, and stable input order.
6. Reuse the lowest numbered slot whose previous inclusive interval ended
strictly before the next begins; otherwise allocate the next logical ID.
This is deterministic greedy coloring for an interval graph and yields its
minimum slot count. No tensor allocation, allocator call, device operation, or
runtime schedule mutation occurs.
## Verification
- An independent closed-interval sweep checks the minimum slot count rather
than repeating the production allocator.
- Tests cover both granularities, exact slot reuse, point intervals, invalid
schedules, W-without-I rejection, compound `OVERLAP_F_B` actions in both
sub-action orders, and checked lookup failures.
- A real `ScheduleDualPipeV` validates the analysis against a finalized VPP
schedule and its communication-lowered action order.
## Test Plan
```bash
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 HTML and coverage builds of `distributed.pipelining` are also
required.
AI assistance disclosure:
> This change was authored with assistance from an AI coding tool and reviewed by the author.
[ghstack-poisoned]
…edules" 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. [ghstack-poisoned]
…edules" 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. [ghstack-poisoned]
…edules" 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. [ghstack-poisoned]
|
Starting merge as part of PR stack under #196706 |
…edules" 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. [ghstack-poisoned]
|
Starting merge as part of PR stack under #196706 |
`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
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
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
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
Stack from ghstack (oldest at bottom):
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_idmapping 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_livenesspython test/distributed/pipelining/test_schedule.pylintrunner --config=.lintrunner.toml torch/distributed/pipelining/schedules.py torch/distributed/pipelining/__init__.py test/distributed/pipelining/test_schedule.py docs/source/distributed.pipelining.mddocs/source/distributed.pipelining.mdAI assistance disclosure: