Skip to content

[pipelining] Analyze pipeline activation liveness from schedules - #196464

Closed
sanketpurandare wants to merge 15 commits into
gh/sanketpurandare/8/basefrom
gh/sanketpurandare/8/head
Closed

sanketpurandare wants to merge 15 commits into
gh/sanketpurandare/8/basefrom
gh/sanketpurandare/8/head

Conversation

@sanketpurandare

@sanketpurandare sanketpurandare commented Sep 9, 2026 •

Copy link
Copy Markdown
Contributor

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_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]
@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/196464

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

❗ 1 Active SEVs

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

✅ No Failures

As of commit ceb72e0 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 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 OVERLAP_F_B handling, a tautological peak_live_count, a sparse return dict that will KeyError on single-stage pipelines, and several tautological test assertions — details below.

PR Review: #196464 — Derive deterministic resource slots from schedules

Summary

Adds _analyze_pipeline_resource_liveness (schedule → deterministic slot plan for F..B-spanning resources) and _assign_pipeline_recv_buffer_slots (local action list → recv-buffer slot maps), both built on a shared greedy interval-coloring helper. The core coloring algorithm is correct, but the surrounding API surface, validation asymmetry, and test assertions have substantive problems.

API Design

  • The two new public-ish entry points have gratuitously different shapes. _analyze_pipeline_resource_liveness (schedules.py:4074) takes a PipelineScheduleMulti object, keyword-only args, validates exhaustively, and returns a rich frozen _PipelineResourceLiveness. _assign_pipeline_recv_buffer_slots (schedules.py:292) takes a raw Sequence[_Action] plus a has_backward: bool the caller must keep in sync with schedule._has_backward, validates almost nothing, and returns bare nested dicts with no num_slots. Callers must do max(slots.forward.values()) + 1 to learn how many buffers to allocate. Pick one contract — both should return something carrying its own slot count, and both should either take a schedule or take an action list.

  • _PipelineRecvBufferSlots's return dict is sparse over stages, which will KeyError. schedules.py:365-371 only emits keys for stages that appear in mutable_slots, i.e. stages that actually had a RECV_F or RECV_B. A single-stage-per-rank pipeline (stage is both first and last) produces no entry for that stage, so slots[stage_index].forward raises KeyError rather than returning {}. Return an entry for every stage present in actions, or document the sparsity in the docstring (currently a single line that says nothing about it). Fix this →

  • peak_live_count is a tautology presented as analysis. schedules.py:224-228 returns self.num_slots. Greedy coloring sorted by start endpoint provably uses exactly max-overlap colors, so the property can never disagree with num_slots and cannot detect a suboptimal coloring. It's a second name for one field, and the test at test_schedule.py:283-284 asserts both equal 5, which asserts nothing. Either delete the property or compute peak liveness independently (sweep the interval endpoints) so it actually cross-checks the allocator.

  • slot_for(stage_index, ...) silently ignores stage_index at "microbatch" granularity. At schedules.py:249 the lookup key becomes None for that granularity, so the parameter is used only for a membership check. The test at test_schedule.py:299-302 encodes this by asserting slot_for(stage_index, mb) == slot_for(0, mb). One dataclass covering two granularities forces a nullable stage_index field, a sometimes-meaningless parameter, and the isinstance(key, tuple) unpacking at schedules.py:4219-4220. Two types, or a uniform tuple[int | None, int] key, removes all three.

  • physical_rank invents a term the codebase doesn't use, and is never checked against schedule.rank. Everywhere else in this file the concept is rank/self.rank (schedules.py:2173). Worse, the resulting field is named local_compute_actions (schedules.py:221) but nothing prevents passing a different rank's index, producing a plan whose "local" actions are another rank's. Either rename to rank and validate rank == schedule.rank, or document that cross-rank analysis is intentional.

  • slot_for is an O(len(lifetimes)) linear scan (schedules.py:251-255). For a consumer that looks up a slot per stage per microbatch in a hot path, that's quadratic. Build a dict index in __post_init__ or expose the assignment map directly.

Code Quality

  • OVERLAP_F_B is handled two incompatible ways by two functions in the same PR. _analyze_pipeline_resource_liveness rejects any container action whose sub-actions touch a tracked stage (schedules.py:4127-4136), while _assign_pipeline_recv_buffer_slots recurses into sub_actions and attributes them to the container position (schedules.py:302-305). The rejection means ScheduleDualPipeV — the only schedule that emits OVERLAP_F_B (schedules.py:3952) — is unsupported by the liveness analysis, which the PR description does not mention. Pick one policy and state the limitation in the docstring.

  • The docstring's lifetime semantics don't match the recorded numbers. schedules.py:4082-4084 says the resource is "acquired immediately before forward and released after the corresponding full backward". But start_position is the index of the forward action and release_position the index of the release action, and _assign_pipeline_resource_slots reuses a slot only when active[0][0] < start (strict, schedules.py:281) — i.e. inclusive [F, B], so a slot freed at position p is not reusable by an interval starting at p. Say "inclusive of the forward and release action positions" rather than "immediately before"/"after".

  • The next_slot coupling in the allocator is dead weight. schedules.py:283-285:

    slot = heapq.heappop(free_slots) if free_slots else next_slot
    if slot == next_slot:
        next_slot += 1

    Every slot ever pushed onto free_slots was allocated when it was < next_slot, so slot == next_slot can only hold in the else branch. Collapse to a plain if free_slots: slot = heappop(...) else: slot = next_slot; next_slot += 1.

  • sorted(..., key=str) at schedules.py:339 is unnecessary and produces wrong ordering. _ComputationType subclasses str (schedules.py:56), so the (int, _ComputationType, int) tuples are directly comparable. key=str makes microbatch 10 sort before microbatch 2 in the error message. Drop it.

  • getattr(schedule, "pipeline_order_with_comms", None) (schedules.py:4109) is a string-keyed reach for a known attribute of a known subclass. Use isinstance(schedule, _PipelineScheduleRuntime). The silent fallback is also a correctness hazard for consumers: comms lowering inserts actions, so start_position/release_position/local_compute_actions indices are relative to whichever list happened to exist, and the plan doesn't record which. If a consumer uses these positions to index back into an action list, it will index the wrong list. Record the source list (or the list itself) on _PipelineResourceLiveness.

  • if action is None: continue at schedules.py:4125-4126 is dead on the pipeline_order_with_comms path — every lowering pass (_add_reduce_grad at schedules.py:1659-1660, _add_send_recv, _defer_recv_ops) filters None out, and the annotation at schedules.py:2728 is dict[int, list[_Action]]. It is live only on the pipeline_order fallback; a comment saying so would prevent a future reader from deleting it.

  • _PipelineRecvBufferSlots is frozen=True but holds mutable dicts (schedules.py:262-267), so the "immutable" framing in the PR description doesn't hold for it, unlike _PipelineResourceLiveness which correctly uses tuples. Either convert to MappingProxyType/tuples or drop the immutability claim.

  • File placement. Two sibling functions sharing _assign_pipeline_resource_slots are ~3800 lines apart (schedules.py:292 and :4074) in a file already at 4457 lines. This is self-contained analysis with no dependency on the schedule classes beyond two attribute reads — a separate _resource_liveness.py would be a better home, and would at minimum keep the siblings adjacent.

  • No in-tree consumer. Nothing outside the new tests calls any of this (verified by grep across torch/). local_compute_actions, peak_live_count, _PipelineResourceLifetime.slot, and the "microbatch" granularity are all speculative surface. CLAUDE.md asks for no half-finished implementations and no design for hypothetical requirements; if [pipelining] Reuse deterministic receive buffers #196465 is the only consumer, the strong version of this review is to land them together and drop the fields it doesn't use.

Testing

  • Several assertions in test_pipeline_resource_liveness_uses_finalized_schedule are tautological and should be deleted:

    • test_schedule.py:286-292 asserts local_compute_actions positions are strictly increasing. They come from enumerate(...) and are appended in loop order (schedules.py:4124, :4146), so this cannot fail.
    • test_schedule.py:293-298 asserts 0 <= slot_for(...) < num_slots. Guaranteed by the allocator's construction.
    • test_schedule.py:299-302 asserts slot_for(s, mb) == slot_for(0, mb) at "microbatch" granularity. Guaranteed by schedules.py:249 keying on None.
    • test_schedule.py:283-284 asserts num_slots == peak_live_count == 5. Same field.

    What's not asserted is the interesting property: that the microbatch-granularity plan's num_slots (4) is the true max-overlap of the merged intervals, and that stage-granularity slot reuse actually happens (which slots are shared, not just that they're in range).

  • Only one of ~9 raise sites is covered. test_pipeline_resource_liveness_rejects_incomplete_backward covers the missing-release path. Uncovered: invalid granularity (:4103), empty/duplicate stage_indices (:4106-4108), rank not in schedule (:4112), OVERLAP_F_B rejection (:4132), compute action with no microbatch index (:4141), out-of-range microbatch (:4143), duplicate forward (:4150), W-without-I (:4166), release-before-forward (:4200), and slot_for's two ValueErrors (:4234, :4237). For _assign_pipeline_recv_buffer_slots: duplicate-recv (:316), double-release (:327), and missing-release (:341) are all untested. The OVERLAP_F_B and W-without-I paths are the two worth adding first — they encode real design decisions.

  • test_recv_buffer_slots_follow_schedule_lifetimes uses an internally inconsistent schedule as its golden fixture. test_schedule.py:206-220 has B0/B2/B3 but only RECV_B1 and RECV_B0 — microbatches 2 and 3 do a full backward without ever receiving an output gradient. The function accepts this silently because it only checks starts-without-releases, never backwards-without-recvs. If that asymmetry is intentional, the test should say so; if not, the fixture is masking a missing validation. Relatedly, [1] on line 222 is a stage-index dict lookup that reads like tuple indexing — bind it to a named variable.

  • Two separate scenarios are crammed into one test method. test_schedule.py:222-235 tests the training case and then an unrelated inference case in the same method. CLAUDE.md points at @parametrize for multi-input tests; at minimum split the inference case out so a failure names which case broke.

Performance

  • The inference path yields zero slot reuse, defeating the stated "minimum number of slots" goal. schedules.py:333-337 sets every recv buffer's release to len(actions), so num_slots == n_microbatches and the mapping is the identity (which test_schedule.py:234 locks in as {0: 0, 1: 1}). The justifying comment — "Keep each input alive until the runtime has waited for every send at step completion" — is a claim about runtime behavior in _step_microbatches that isn't referenced or verified here. If the real constraint is per-microbatch ("until this microbatch's SEND_F completes"), the release should be that SEND_F's position and reuse becomes possible; if it genuinely is step-global, the comment should cite the specific wait site (schedules.py:3099) so a future reader can re-derive it.

  • Releasing RECV_B at W rather than I costs a slot for every non-first stage. The docstring rationale at schedules.py:4082-4084 ("a later weight-backward may still consume state") is only true for stage_index == 0, where backward_weight_one_chunk takes the full path and does pass output_grads/input_values (stage.py:1225-1238). For every other stage the W path uses only stage_output and param_groups (stage.py:1217-1224), so neither received buffer is read after I. The conservatism is defensible for the dw_builder path, where the closure can capture anything (stage.py:1141) — but say that, since the reason as written is wrong for the common case and hides available slot savings.

Recommendation

Request Changes

Blocking: the sparse-_PipelineRecvBufferSlots KeyError, the divergent OVERLAP_F_B policy between the two new functions (with ScheduleDualPipeV silently unsupported), the API asymmetry between the two entry points, and the tautological test assertions plus 9 uncovered raise paths.

Worth resolving before merge: whether this should land at all without #196465. Four of the exposed fields have no consumer, and landing them together would let you drop the ones the consumer doesn't need instead of freezing speculative surface into a 4457-line file.

· branch `gh/sanketpurandare/8/head`

@sanketpurandare

Copy link
Copy Markdown
Contributor Author

@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, peak_live_count, linear lookup, receive-specific policy, and sparse-result assumptions. Compound OVERLAP_F_B, split I/W release, cross-rank analysis, incomplete lifetimes, exact reuse, and minimum coloring now have independent assertions.

@claude

claude Bot commented Sep 15, 2026 •

Copy link
Copy Markdown

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 OVERLAP_F_B test uses a container shape no in-tree schedule emits (making the W-without-I check's order dependence untested), and nothing exercises this against a real pipeline_order.

PR Review (round 2): #196464 — Derive deterministic resource slots from schedules

Verification of the claimed changes

I checked each claim against git diff origin/gh/sanketpurandare/8/base...HEAD. All the structural ones hold:

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. The rank not in pipeline_order raise (:3989) is uncovered, and rank is still never validated against schedule.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_slots is 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 about peak_live_count was that it couldn't disagree with num_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 max running 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 its I/W fixture does pin the release-at-W policy. These two claims hold.

Correctness

  • The W-without-I check is order-dependent inside an OVERLAP_F_B container, and the one test that exercises containers relies on that order. process (:3997) populates input_backwards as it walks, so the check at :4029-4034 requires I to be visited before W. 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 at test_schedule.py:266-271 hardcodes (I0, W0); flip it to (W0, I0) — semantically identical for an overlapped action — and the analyzer raises. Collect input_backwards in 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 (an OVERLAP_F_B whose sub-actions are the F and 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 populates pipeline_order_with_comms and leaves pipeline_order empty (:2665-2671). Without that note a future reader will reasonably delete the branch.

  • @dataclass(frozen=True) + a MappingProxyType field makes the generated __hash__ raise. frozen=True with default eq=True generates __hash__ from the field tuple, and mappingproxy is unhashable, so hash(plan) is a TypeError. Either eq=False or unsafe_hash-free explicit __hash__, or just accept it — but it's a trap for anyone caching plans in a set/dict key.

  • stage_indices isn'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: default stage_indices to 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) uses key purely as a dict label. Drop it: take Sequence[tuple[int, int]] of (start, release) and return (list[int], int) where slot i corresponds to input interval i. 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 assignments directly. Net simpler and removes the last place where the two granularities are entangled.

  • The double sort hides the determinism guarantee. :4083 sorts 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 via OVERLAP_F_B position 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-4020 and :4023-4026 — both fit on one line under 88 cols. CLAUDE.md explicitly asks to undo ruff's splits where possible.

  • granularity is stored on the result but never read by it. Fine as consumer metadata, but note that rank, granularity, stage_indices, and num_microbatches are all pure passthrough — only assignments and num_slots carry 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 _Action and _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 one isinstance.

Testing

  • Nothing tests this against a real schedule. All three fixtures hand-write pipeline_order. test_schedule.py:936 already shows the pattern for building a real ScheduleDualPipeV from MockPipelineStage; one such test would simultaneously cover the actual OVERLAP_F_B shape ((F stage_a mb_i ; FULL_BACKWARD stage_b mb_j) from add_overlap_f_b at :3822-3826 — note it is not the (I, W) shape the current test fabricates), the pipeline_order_with_comms branch, the None-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_overlap is three tests in one method (test_schedule.py:215-281): stage granularity, microbatch granularity, and a from-scratch overlap schedule. CLAUDE.md points at @parametrize; at minimum split the overlap case out so a failure names which scenario broke. The overlap sub-case also reuses stages[0] (built with num_stages=3) in a 1-stage PipelineScheduleMulti, which is internally inconsistent even if harmless here.

  • Microbatch granularity has no reuse coverage. The fixture yields {mb0: 0, mb1: 1} with num_slots == 2 == n_microbatches — the identity map. So the min(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 raise sites remain uncovered: invalid granularity (:3975), empty stage_indices (:3979), duplicate stage_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), and slot_for's ValueError (:219). Only the missing-release path is tested. The three encoding real design decisions — W-without-I, release-before-forward, and slot_for on 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.

· branch `gh/sanketpurandare/8/head`

…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]
@sanketpurandare

Copy link
Copy Markdown
Contributor Author

@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 ScheduleDualPipeV including communication lowering. The focused liveness tests and full schedule suite pass.

@claude

claude Bot commented Sep 15, 2026 •

Copy link
Copy Markdown

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 num_slots is still only compared to a literal (not the sweep) and the cross-rank test's headline assertion is trivially true because the two ranks own disjoint stages.

PR Review (round 3): #196464 — Derive deterministic resource slots from schedules

Verification of the claimed changes

Checked each claim against git diff origin/gh/sanketpurandare/8/base...HEAD. All six hold:

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_slots is still only compared to a literal. test_schedule.py:322 asserts microbatch_plan.num_slots == 2, but _max_live_closed_intervals is only applied to the stage-granularity intervals (:307) and the DualPipeV plan (:370). The merged min(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_intervals output 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's stage_indices × microbatches, or that plans[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: same sub_actions recursion, same F-starts / (B, W)-releases rule. That makes it a valid oracle for the allocator but not for the policy — if release-at-W were changed to release-at-I in 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 raise sites remain uncovered: invalid granularity (:3986), empty stage_indices (:3990), duplicate stage_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), and slot_for's ValueError (:3925). Down from 11 — rank not present and the missing-release path are now covered. The two encoding real design decisions are W-without-I and slot_for on an untracked pair; the rest are cheap in one @parametrized (pipeline_order, expected_regex) table if you want them.

  • overlap_schedule in test_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, and index inherits that from keys' order. Sorting expected lexicographically gives the identical assignments — for any two keys with equal (start, release), both orderings put the lexicographically smaller key first. So keys = sorted(expected) is provably equivalent and drops the lambda plus the double-sort confusion round 2 flagged.

  • assignments insertion order differs between the two branches. The stage_microbatch branch builds it from sorted keys (:4098); the microbatch branch iterates expected, a set (:4092), so its iteration order comes from tuple hashing. A consumer that allocates buffers by walking plan.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 an OVERLAP_F_B collapsing 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_b at :3780-3783 always 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_indices is still not checked for locality, so passing a stage that lives on another rank surfaces as Forward actions do not match tracked lifetimes; missing=[...] rather than naming the real problem. schedule.stage_index_to_group_rank is right there. The stronger version of this — defaulting stage_indices to 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 at test_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=False makes plan equality identity-based. schedules.py:3909. Correct choice — frozen=True with eq=True would generate a __hash__ over the field tuple and hash(plan) would TypeError on the mappingproxy. 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.

  • granularity and num_microbatches are pure passthrough — the result computes only assignments and num_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.

· branch `gh/sanketpurandare/8/head`

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.

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.

usually, these the vpp stages sharing the same physical rank

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 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]
@sanketpurandare sanketpurandare changed the title [pipelining] Derive deterministic resource slots from schedules [pipelining] Analyze pipeline activation liveness from schedules Sep 17, 2026
[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]

@SherlockNoMad SherlockNoMad left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

LGTM

…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]
@sanketpurandare sanketpurandare added release notes: distributed (pipeline) release notes category module: pipelining Pipeline Parallelism and removed topic: not user facing topic category labels Sep 22, 2026
@pytorchmergebot

Copy link
Copy Markdown
Collaborator

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]
@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Starting merge as part of PR stack under #196706

pytorchmergebot pushed a commit that referenced this pull request Sep 22, 2026
`ProcessGroup::splitGroup` cloned the rendezvous Store for every child process
group. Pipeline schedules can create hundreds of directed child communicators,
turning those clones into hundreds of TCPStore connections per rank. This also
differs from `new_group()`, whose sibling groups have long used uniquely
prefixed namespaces over one shared Store connection.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

## Before and after

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

## Responsibility boundaries

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

## Behavior by mode

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

## Shared-parent setup

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

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

## Removed machinery

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

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

## Test Plan

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

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

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

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

Labels

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants