Skip to content

[pipelining] Expose scoped stage forward context - #196462

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

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

Conversation

@sanketpurandare

@sanketpurandare sanketpurandare commented Sep 9, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

Background

Pipeline runtimes sometimes need the global logical stage and current
microbatch at the exact boundary where a stage module executes. A physical PP
rank is insufficient under virtual pipeline parallelism because one rank owns
multiple logical stages, while the microbatch identity belongs to runtime
execution rather than the model's input schema.

The previous revision transported this information through a reserved model
keyword and added an enable flag to every schedule. That made scheduler control
state part of the model signature, required kwargs copies and collision checks,
excluded traced stages, and coupled dynamic metadata inference to schedule
configuration.

Design

PipelineStageInfo remains a frozen, slotted, keyword-only value containing the
global logical stage, step-local microbatch, and metadata-probe marker. A stage
now exposes register_forward_context(factory), where the factory receives that
value and returns a fresh context manager around the stage computation.

The first version deliberately permits one live registration. A second
registration fails with an actionable error, and removing the returned
RemovableHandle permits replacement. This keeps ownership explicit and leaves
a compatibility-preserving path to multiple registrations if a concrete need
appears.

The default path performs only an empty-registry check: it constructs no info
object, copies no kwargs, and allocates no context manager. Registered runtime
forwards wrap the existing forward_maybe_with_nosync call. Dynamic metadata
inference wraps its representative _compute_outputs call with microbatch zero
and is_metadata_inference=True; static metadata setup does not execute the
factory. Manual and traced stages share the implementation through the stage
base class, so compiled and exported submodules retain their original graph
signatures.

Context teardown follows ordinary context-manager exception semantics. A
context is not allowed to suppress an exception raised by the stage module;
doing so produces an explicit runtime error instead of continuing without a
forward result.

Boundaries

The registration is attached to forward_one_chunk, not schedule IR. Custom
actions receive it when they delegate to that method and otherwise own their
execution context. CUDA graph capture executes the Python context while
recording work, but replay does not re-enter Python; consumers must bind
replay-stable state during capture.

The implementation is built cleanly from the parent of the prior revision. It
adds no schedule constructor option, reserved keyword, schedule voting state,
or _IR.py behavior.

Test Plan

python test/distributed/pipelining/test_stage.py PipelineStageForwardContextTest
python test/distributed/pipelining/test_stage.py PipelineStageMetadataInferenceTest
NCCL_DEBUG=WARN CUDA_VISIBLE_DEVICES=0,1,2,3 \
  python test/distributed/pipelining/test_stage.py
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 \
  docs/source/distributed.pipelining.md \
  test/distributed/pipelining/test_schedule_multiproc.py \
  test/distributed/pipelining/test_stage.py \
  torch/distributed/pipelining/__init__.py \
  torch/distributed/pipelining/stage.py
sphinx-build -M html docs/source docs/build -j 8 -WT --keep-going

The Sphinx coverage report is 100% with zero undocumented Python objects. The
local full-tree post-check separately reports two pre-existing optional c10d
backend exports below this stack; the pipelining API introduced here is fully
documented.

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/196462

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 15bb645 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.

[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 19m 24s —— View job


Review complete — the traced-stage path this PR advertises cannot work, and metadata inference runs the forward without the injected kwargs.

Full review of #196462

PR Review: #196462

Summary

Adds an opt-in pass_pipeline_metadata flag that injects reserved pipeline_stage_index / pipeline_microbatch_index kwargs at the forward_one_chunk() dispatch boundary. Two functional defects (traced stages can never work; metadata-inference forwards don't get the kwargs), a fragile injection mechanism, and test coverage that does not match what the PR description claims.

API Design

  • torch/distributed/pipelining/_IR.py:1163 and torch/distributed/pipelining/stage.py:1750 expose the flag on a path where it always fails. Both Pipe.build_stage and the module-level build_stage construct _PipelineStage, whose self.submod is an fx GraphModule from split_module in Pipe._from_traced. Its forward is codegen'd from graph placeholders (torch/fx/graph.py:432-454 CodeGen.gen_fn_def, and _PyTreeCodeGen.gen_fn_def at graph.py:1247 for stage 0) with fixed positional parameters and no **kwargs. So self.submod(*composite_args, **composite_kwargs) at stage.py:1015 raises TypeError: forward() got an unexpected keyword argument 'pipeline_stage_index' — surfaced as the wrapped RuntimeError from stage.py:1017-1023. This holds for both the first stage and later stages. The PR description says "applies to manual and traced stages" and "Tests cover manual and traced stages"; neither is true. Either drop the _IR.py/build_stage plumbing, or make the traced path work (and test it).

  • Reserved-kwarg injection is the wrong contract for this need. Requiring every stage module's top-level forward to accept two exact parameter names means: traced/exported graphs can't participate (above); any nn.Module with a strict signature must be edited; and if the submodule is torch.compiled, pipeline_microbatch_index arrives as a Python int input that Dynamo will specialize on, so you get a recompile per microbatch index on the first epoch instead of one graph. Consider a context-based contract instead — e.g. a module-visible accessor set around the forward in forward_one_chunk (torch.distributed.pipelining.current_pipeline_metadata() backed by a contextvar). That requires no signature change, works for traced graphs, DDP/FSDP wrappers, and nested submodules (which the kwarg approach also cannot reach), needs no collision check, and adds nothing to input_values.

  • stage.py:245 stores the flag as a public mutable attribute. self.pass_pipeline_metadata (no leading underscore) is read once per forward, so a user can flip it mid-run and get inconsistent per-microbatch behavior. Make it self._pass_pipeline_metadata unless mutation is an intended part of the API, in which case document the semantics.

Infrastructure

  • stage.py:2121 runs the user forward during metadata inference without the metadata kwargs. PipelineStage._prepare_forward_infra (stage.py:2411-2416) calls _forward_metadata_inference, which builds inference_kwargs from user kwargs only (stage.py:2111-2114) and then calls _compute_outputs → module(*args, **kwargs) (stage.py:1977-1984). DYNAMIC is the default mode when static metadata isn't supplied (schedules.py:397-410), so this fires on the common path. Two consequences:

    1. A module whose forward declares these parameters without defaults raises TypeError at schedule initialization, before any microbatch runs. The new test hides this by giving both parameters = -1 defaults (test_stage.py:73-77).
    2. If output shape/dtype depends on the metadata, _stage_meta.outputs at stage.py:2128 is inferred from a forward that saw the wrong values, and that feeds _setup_forward_recv_info / _setup_forward_send_info (stage.py:2425-2426). Runtime shape validation only runs at DebugLevel.DETAIL (stage.py:320), so a mismatch shows up as a P2P corruption/hang rather than an error.

    Inject the metadata into inference_kwargs too (using a representative microbatch index, and document which one), or explicitly reject pass_pipeline_metadata=True in DYNAMIC mode. Either way the docstrings that say "every executed forward" (stage.py:231, 1348, 1762, 1806, _IR.py:1172) are currently inaccurate.

Testing

  • test/distributed/pipelining/test_stage.py:67-119 covers roughly one and a half of the four things the PR description claims. It constructs PipelineStage directly and calls stage.forward_one_chunk(3, (x,), kwargs) by hand, so _prepare_forward_infra and metadata inference never run. Not covered: traced stages (_PipelineStage / build_stage), custom forward actions (schedules.py:2500 register_custom_function), and the disabled default (that no kwargs are injected when the flag is False — the one assertion that would catch an accidental unconditional injection). Only the reserved-key collision (lines 111-116) is genuinely tested. At minimum add: a ScheduleGPipe-driven test through schedule.step() so init and backward are exercised, a num_stages >= 2 case so the non-first-stage path at stage.py:990 (where composite_args come from recv) is hit, and a flag-off assertion.

  • The test is in the wrong class and duplicates ~15 lines of setup. PipelineStageMetadataInferenceTest is about metadata inference, which this test deliberately bypasses. The init_pg / TemporaryDirectory / try/finally destroy_process_group block is copy-pasted from test_dynamic_metadata_inference_restores_module_buffers (test_stage.py:143-180). Move the process-group setup into setUp/tearDown (or a shared helper) and give the new test its own class, or fold it into a class named for the feature.

Code Quality

  • stage.py:998-1003 validates configuration on the hot path. Whether the user's kwargs collide with a reserved name is fixed at step() time, but the check runs once per stage per microbatch and raises mid-schedule after some microbatches have already executed. Validate once in _prepare_forward_infra (where kwargs is already available) so the failure is a clean initialization error. Also note the check only runs when the flag is on, so a user with a pipeline_stage_index kwarg gets no warning until they enable the feature. The message should name the flag that reserved the keys, since pass_pipeline_metadata is what the reader needs to find.

  • stage.py:1034 puts the two ints into fwd_cache's input_values. flatten_args(composite_kwargs) now yields two plain ints that ride along into bwd_kwargs["input_values"]. This is safe today — _autograd_grad_for_inputs filters non-tensors and reinserts None at the original indices (_backward.py:153-174), and grads_input[:num_fwd_args] slices from the front (stage.py:1172) — but it relies on dict insertion order keeping the metadata last, and it pollutes map_debug_info output in the backward error path (_backward.py:273). Exclude the metadata keys when building flat_kwargs.

  • stage.py:217 is positional while every subclass makes it keyword-only. The base __init__ takes pass_pipeline_metadata as a positional-or-keyword parameter after dw_builder, but _PipelineStage.__init__ (1336), build_stage (1750), PipelineStage.__init__ (1823) and Pipe.build_stage (_IR.py:1163) all put it behind *. Make the base keyword-only too.

  • _IR.py:1160-1176 rewrites the whole build_stage docstring to document one new parameter. The Args:/Returns: block added for stage_index/device/group restates the parameter names verbatim and is inconsistent with the name (type): desc style used by the neighbouring build_stage in stage.py:1755-1765. Add the one new entry in the existing style rather than reformatting.

  • Docs. docs/source/distributed.pipelining.md gets no mention of the new option, and nothing documents what a consumer is supposed to do with these indices or what stability guarantee pipeline_microbatch_index carries across schedules. (For the record, fwd_chunk_id is the global microbatch index at every forward_one_chunk call site — schedules.py:1069, 1124, 1282, 1342, 2313, 2790 — and self.stage_index is the global stage index even for multi-stage-per-rank schedules, so the values themselves are sound; that just needs to be written down as the contract.)

Recommendation

Request Changes

Blocking: the traced-stage plumbing in _IR.py/build_stage cannot work as shipped, and metadata inference calls the forward without the kwargs (crash-at-init for required parameters, or silently wrong send/recv metadata). Test coverage also does not support the claims in the PR description — no schedule-level, traced, multi-stage, backward, or flag-off test. Before iterating on the implementation, I'd settle the API question: a contextvar-style accessor sidesteps the traced-graph limitation, the torch.compile recompile-per-microbatch specialization, the collision check, and the input_values pollution all at once.

| Branch: `gh/sanketpurandare/6/head`

@sanketpurandare sanketpurandare changed the title [pipelining] Pass stage and microbatch metadata to forwards [pipelining] Pass stage and microbatch metadata to manual stages Sep 15, 2026
@sanketpurandare

Copy link
Copy Markdown
Contributor Author

@claude Removed the unsupported traced _PipelineStage/FX plumbing and scoped the API to manual PipelineStage, whose forward boundary TorchTitan eager PP uses. The opt-in now requires complete static metadata, rejects dynamic inference because it has no real microbatch identity, stores the flag privately, excludes metadata from autograd inputs, and supports either direct keyword consumption or a standard with_kwargs=True pre-hook for strict module signatures. Tests now exercise schedule.step(), exact global stage/microbatch IDs, a real non-first same-rank stage handoff, the disabled default, collision rejection, and the static-metadata error. I retained explicit kwargs instead of ambient context because stage/microbatch identity is execution input state and must remain visible to tracing and custom forward contracts.

@claude

claude Bot commented Sep 15, 2026 •

Copy link
Copy Markdown

Claude finished @sanketpurandare's task in 18m 11s —— View job


Re-review: all four blockers from the previous round are fixed; what's left is polish plus one design caveat (torch.compile specialization) and a rank-asymmetric error path worth tightening.

Full re-review of #196462

Verification of previous findings

Previous finding Status
Traced _PipelineStage / build_stage / Pipe.build_stage plumbing could never work Fixed — all FX plumbing removed. _PipelineStage.__init__ (stage.py:1350) calls the base without the flag, and the flag is keyword-only with default=False, so a traced stage cannot enable it.
Metadata inference ran the user forward without the injected kwargs Fixed — stage.py:2416 rejects DYNAMIC mode, and stage.py:1853 rejects incomplete forward metadata at construction. _forward_metadata_inference is now unreachable with the flag on.
Public mutable self.pass_pipeline_metadata Fixed — stage.py:246.
Metadata polluted fwd_cache input_values Fixed — stage.py:1037 flattens user_kwargs, byte-identical to pre-PR behavior when the flag is off, and test_stage.py:163 asserts it directly.
Positional in base / keyword-only in subclass Fixed — * added at stage.py:217.
No schedule-level / non-first-stage / flag-off test Fixed — schedule.step() at test_stage.py:117, a real non-first-stage handoff at 160, flag-off at 194.

I found no remaining functional bug on the enabled path. metadata.keys() & user_kwargs.keys() is correct, the injected values are the global stage index and the global microbatch index at every forward_one_chunk call site (schedules.py:1069, 1124, 1282, 1342, 2313, 2790), and custom forward actions registered via register_custom_function get the metadata for free since they route through the same boundary.

Design

Reserved ints reaching a torch.compiled submodule will cost recompiles. pipeline_microbatch_index arrives as a plain Python int forward input. Dynamo specializes scalar int inputs on first trace, then promotes to a symint via automatic dynamic — so expect at least one extra graph, and worst case (if the value is used in control flow or a shape computation) one per microbatch index, against recompile_limit = 8 (torch/_dynamo/config.py:121). TorchTitan compiles PP stage modules, which is exactly the target consumer. This is worth an explicit sentence in the class docstring plus a test that wraps the stage module in torch.compile and asserts the compile count stays bounded across n_microbatches > 8. It does not invalidate the kwarg design — it's a documented cost.

The static-metadata requirement is enforced in two places with two different messages, and neither says what to add. stage.py:1858 covers missing input_args/output_args; stage.py:2418 catches the other DYNAMIC trigger (DTensors + backward + missing input_grads/output_grads, _utils.py:469-472) with the vaguer "requires complete static metadata". A user who hits the second one has complete input_args/output_args and no hint that grad metadata is what's missing. Fold the grad-metadata requirement into the message. Fix this →

Both rejections fail on some ranks and not others. _inference_mode is decided by a collective vote (schedules.py:396-415), so a stage whose own metadata is complete votes STATIC but can still be assigned DYNAMIC because a peer voted otherwise. That stage raises at stage.py:2416 while its peers proceed into _forward_metadata_inference → _send_meta/_recv_meta and block on a partner that has already died. The constructor check at stage.py:1853 has the same shape. Cleaner: validate the flag in _warmup_forward_vote next to my_vote (stage.py:1928), where has_backward is known and InferenceMode.needs_dynamic(self._user_meta, has_backward) is already computed — a stage with the flag on that would vote DYNAMIC is a local misconfiguration, so every misconfigured rank raises the same error at the same point, and stage.py:2416 becomes a defensive assert. This is the same failure mode the fake-PG comment at schedules.py:362-369 already works around, so the codebase treats it as a real concern.

Reconsider the static-metadata coupling itself (question, not a blocker). Requiring input_args/output_args reintroduces hand-specified shapes for anyone using the flag, which is the tax dynamic inference exists to remove. Inference already runs a real forward with real buffers (see test_dynamic_metadata_inference_restores_module_buffers), so injecting pipeline_microbatch_index=0 with a documented "inference uses microbatch 0" contract would decouple the two features entirely. Your rejection ("no real microbatch identity") is defensible if you want to prevent a module from silently baking inference-time metadata into inferred shapes — but that reasoning belongs in a comment at stage.py:1853, because the next reader will ask.

Code quality

  • stage.py:995-1006 still validates configuration inside the per-microbatch hot path. Whether the user's kwargs collide is fixed at step() time, but the check runs once per stage per microbatch and raises mid-schedule after earlier microbatches have already mutated module state. _prepare_forward_infra already receives kwargs (stage.py:2399) and ignores it in STATIC mode — validate there so the failure is a clean init error. The message also still doesn't name pass_pipeline_metadata, which is the string a user needs to grep for.

  • Hoist the two reserved names into a module-level constant. They currently appear as literals in stage.py:997-998 and are hardcoded in four places across the tests. A _PIPELINE_METADATA_KEYS = frozenset({...}) (or a public constant users can reference) lets the collision check, the injection, and the tests share one source of truth, and tightens the block:

    composite_kwargs = kwargs or {}
    if self._pass_pipeline_metadata:
        if collisions := _PIPELINE_METADATA_KEYS & composite_kwargs.keys():
            raise ValueError(
                f"pass_pipeline_metadata reserves forward kwarg name(s): {sorted(collisions)}"
            )
        user_kwargs, composite_kwargs = composite_kwargs, {**composite_kwargs, ...}
  • stage.py:232 documents a base-class parameter in subclass terms. "each manual stage forward" is confusing on _PipelineStageBase, which also backs the traced frontend. Say what it does (inject the two kwargs at the forward_one_chunk dispatch boundary) and note that only PipelineStage exposes it.

  • The contract the values carry isn't written down anywhere. Neither docstring states that pipeline_stage_index is the global stage index (not a rank-local one, which matters for interleaved and V schedules where one rank owns several stages) or that pipeline_microbatch_index is the global microbatch index within the step. That's the one guarantee a consumer actually needs, and it's the part that would be a silent breakage if it ever changed. PipelineStage is autoclass'd in docs/source/distributed.pipelining.md:480, so a line in the class docstring is enough.

Testing

  • Three tests in PipelineStageMetadataInferenceTest, two of which deliberately bypass metadata inference. test_pipeline_metadata_pre_hook_and_static_contract forces _inference_mode = STATIC by hand and test_pipeline_metadata_disabled never inits infra at all. Give the feature its own class.

  • test_pipeline_metadata_pre_hook_and_static_contract bundles two unrelated cases (the pre-hook contract and the constructor error), as the name concedes. Split it. The pre-hook half also pokes three private attributes (_inference_mode, _prepare_forward_infra, set_local_fwd_input) with no comment saying why — it's simulating stage 1 of 2 on a single rank so the non-first _retrieve_recv_activations path is exercised. Worth one line, since otherwise the next person to touch init sequencing won't know what this test is protecting.

  • No backward runs with the flag on. ScheduleGPipe(stage, n_microbatches=2) at test_stage.py:114 has no loss_fn, so _has_backward is False (schedules.py:294) and backward_one_chunk never executes. The fwd_cache assertion at line 163 checks the exclusion statically, but the interaction that actually matters — grads_input[:num_fwd_args] slicing at stage.py:1170-1177 against an input_values list built with metadata excluded — is untested. Add loss_fn + target to the first test; it's a two-line change for the highest-value uncovered path.

  • The DYNAMIC rejection at stage.py:2416 has no test. The constructor path is covered at test_stage.py:165, but the branch reachable only via DTensors + backward + missing grad metadata is not — and it's the branch with the rank-asymmetry problem above.

  • test_stage.py:121 uses fwd_chunk_id=4 on a 2-microbatch schedule to test the collision. It works only because forward_one_chunk never calls _check_chunk_id and the raise precedes any chunk-indexed access. Use 0 so the test isn't relying on that.

  • single_rank_process_group silently reuses an existing group. init_pg = not dist.is_initialized() means if any earlier test in the process leaves a multi-rank group alive, these tests run against it with the world_size=1 assumption broken. This pattern is inherited from the existing test at test_stage.py:219, and the MultiProcContinuousTest classes in this file spawn subprocesses rather than sharing the parent's group, so the risk is low today — but the helper is now shared by four tests, so an assert that the group is single-rank when reusing would be cheap insurance.

Recommendation

Approve with comments. The design is now sound and correctly scoped to the frontend it can actually serve; the previous blockers are genuinely resolved and I could not find a functional bug on the enabled path. Before landing I'd want: the torch.compile specialization caveat documented (and ideally covered by a bounded-recompile test), the two rejection messages unified and moved to the vote so all ranks fail identically, and the global-index contract written into the docstring. The test reorganization and the backward-path test are worth doing but wouldn't block.

| Branch: `gh/sanketpurandare/6/head`

…stages"

Summary:
Manual pipeline stages sometimes need stable logical-stage and microbatch identities without subclassing `PipelineStage` or consulting mutable schedule state. Add an opt-in stage contract that injects reserved `pipeline_stage_index` and `pipeline_microbatch_index` keyword arguments at the common `forward_one_chunk()` dispatch boundary.

The option is disabled by default and requires complete static stage metadata because dynamic metadata inference has no real schedule action or microbatch identity. A stage module may accept the keywords directly or consume them in a `with_kwargs=True` forward pre-hook. Traced `_PipelineStage` instances remain unchanged because generated `GraphModule.forward` signatures cannot generally accept the reserved keywords.

Pipeline metadata is execution context rather than an autograd input, so it is excluded from the saved forward inputs. Caller-supplied values for either reserved key are rejected.

Test Plan:
- `python test/distributed/pipelining/test_stage.py -k pipeline_metadata`

[ghstack-poisoned]
[ghstack-poisoned]
@sanketpurandare

Copy link
Copy Markdown
Contributor Author

@claude Centralized the reserved keyword names and documented their global stage/microbatch semantics plus Python-integer compile specialization. Static capability and metadata requirement are now voted schedule-wide before metadata P2P, so every rank rejects an invalid mixed configuration consistently. Collision validation remains at dispatch because caller kwargs may differ by step, and the backward test proves metadata is excluded from saved autograd inputs. The focused stage tests and four-GPU rank-symmetric rejection test pass.

@claude

claude Bot commented Sep 15, 2026 •

Copy link
Copy Markdown

Claude finished @sanketpurandare's task in 12m 53s —— View job


Re-review: all round-2 items verified fixed and the new schedule-wide vote is logically correct; no functional bugs found — but the backward test does not actually prove the autograd-input exclusion it claims to, and the DYNAMIC guard is now dead code with a second divergent message.

Full round-3 review of #196462

Verification of round-2 findings

Round-2 finding Status
Reserved names duplicated as literals across source + tests Fixed — _PIPELINE_STAGE_INDEX_KEY / _PIPELINE_MICROBATCH_INDEX_KEY / _PIPELINE_METADATA_KEYS at stage.py:62-66.
Rank-asymmetric rejection (some ranks raise, peers hang in _send_meta/_recv_meta) Fixed, and correctly — see the vote audit below.
Two rejection sites with two different messages, neither naming grad metadata Partially fixed — the voted message at schedules.py:407-412 now names input_grads/output_grads. The second site at stage.py:2422 still carries its own near-duplicate string.
Global stage/microbatch semantics not written down Fixed — stage.py:1806-1813 states "global logical stage index and the global microbatch index within the current step".
torch.compile int specialization undocumented Partially fixed — one sentence at stage.py:1813; see below, it's too vague to act on, and there is still no bounded-recompile test.
No backward runs with the flag on Fixed structurally (loss_fn + target at test_stage.py:113-121) but it doesn't test what's claimed — see Testing.
fwd_chunk_id=4 on a 2-microbatch schedule Fixed — now 0 at test_stage.py:127.
Separate test class; single_rank_process_group reuse assert; private-attr comment in the pre-hook test Not addressed.

Audit of the new vote encoding

I traced _warmup_forward_vote (stage.py:1927-1953) → _warmup_backward_result (1971-1984) → schedules.py:397-417 and the encoding is sound. supports_static = not needs_dynamic(...) and permits_dynamic = not self._pass_pipeline_metadata, elementwise-multiplied along the chain, so the length-2 result is (all stages support static, no stage requests metadata). The rejection condition not supports_static and not permits_dynamic is exactly right: permits_dynamic only matters when STATIC is unavailable, because if every stage supports static the mode is STATIC and metadata is satisfied regardless of who set the flag. Crucially the check fires after the collective completes on every rank, so all ranks raise at the same point — that is the rank symmetry you were after, and it correctly covers the cross-stage case (stage A lacks metadata, unrelated stage B set the flag), not just the same-stage case. Buffer sizes were updated to torch.zeros(2, ...) at both 1945 and 1977, matching the sender. The fake-PG early return at schedules.py:362-396 also stays consistent: it either raises on needs_dynamic or sets STATIC, so it never lands a metadata-requesting stage in DYNAMIC.

Findings

1. test_pipeline_metadata_forward_kwargs does not prove metadata is excluded from saved autograd inputs. The claim in your comment doesn't hold for this test: kwargs is empty there, so flat_kwargs is [] either way, and even if metadata were included the backward would produce identical grads. _autograd_grad_for_inputs filters non-tensors and reinserts None at the original indices (_backward.py:153-174), and num_fwd_args = len(self._stage_meta.inputs) == 1 (stage.py:1177) so grads_input[:1] slices the metadata off regardless. The assertion x.grad == 2 is invariant to the change under test. The exclusion at stage.py:1044 is only genuinely covered by self.assertEqual(stage.fwd_cache[2][1], [x]) in test_pipeline_metadata_pre_hook. To make the backward test load-bearing, pass a real tensor kwarg through step() so flat_kwargs is non-empty and ordering matters — then including metadata would shift indices and the [:num_fwd_args] slice would be observably wrong. Fix this →

2. stage.py:2420-2426 is now unreachable, and duplicates the message. Given the vote, DYNAMIC is only selected when permits_dynamic == 1, i.e. no stage on any rank set the flag — so a stage reaching _prepare_forward_infra in DYNAMIC mode can never have _pass_pipeline_metadata true. The fake-PG path can't reach it either. Keeping it as a defensive check is fine, but it should be an AssertionError (it's an invariant violation, not user error) or share the single message string with schedules.py:407. Two independently-worded strings for one condition will drift.

3. The compile caveat is documented but not actionable. "Compiled modules may specialize on these Python integer values" (stage.py:1813) doesn't tell the reader what to expect. The concrete behavior: Dynamo specializes the int on first trace, then automatic dynamic promotes it to a symint on the second distinct value, so the normal cost is one extra graph — but if the index feeds control flow or a shape computation you get a recompile per distinct value against recompile_limit = 8 (torch/_dynamo/config.py:121), which n_microbatches > 8 will blow through. Since TorchTitan compiles PP stage modules, that's the case worth naming. Still no test asserting a bounded compile count.

4. eval() and step() can disagree about whether the flag is legal. needs_dynamic(meta, has_backward) (_utils.py:447-475) returns False for a DTensor stage with complete forward metadata when has_backward=False, and True when it's True. So a DTensor stage with input_args/output_args but no grad metadata votes STATIC under eval() and DYNAMIC under step(): the flag works, then the first training step raises. That asymmetry predates this PR, but enabling pass_pipeline_metadata is what turns it from "mode switch" into "hard error", so it deserves a sentence in the docstring next to the static-metadata requirement.

5. Collision check placement — your rebuttal is right about per-step kwargs, but the boundary can still be earlier. Agreed that the keys aren't fixed at construction. They are fixed per step() though: step(**kwargs) splits into kwarg_mbs with identical keys across microbatches, so validating once at the step() entry preserves the per-step semantics you want while guaranteeing the error precedes any module execution. As written (stage.py:1002-1013) the raise can land at microbatch k on stage j, after earlier microbatches have already mutated module state and with peers blocked on P2P — a debuggable-but-messy failure for what is purely a naming mistake. Not blocking; the cost isn't the concern, the failure point is.

6. Minor cleanups in the vote block.

  • schedules.py:405 unpacks via a generator expression, which issues two separate .item() device-to-host syncs. supports_static, permits_dynamic = result.tolist() is one sync and reads better.
  • schedules.py:420 still has determined_mode.value if determined_mode else "None", but determined_mode is now unconditionally assigned at 413-415 — the else is dead. The removal of the InferenceMode | None annotation is what made it dead.
  • stage.py:1003-1006 builds the metadata dict before the collision check that may reject it; move it after.
  • _warmup_forward_vote's received_acc arg doc (1920) and _warmup_backward_result's summary (1960) still describe a scalar "accumulated product". The body docstring was updated; these two weren't.

7. Test organization items from round 2 are still open. Four feature tests live in PipelineStageMetadataInferenceTest, and two of them (test_pipeline_metadata_pre_hook forces _inference_mode by hand, test_pipeline_metadata_disabled never inits infra) deliberately bypass metadata inference. test_pipeline_metadata_pre_hook still pokes _inference_mode, _prepare_forward_infra, and set_local_fwd_input with no comment explaining that it's simulating stage 1 of 2 on one rank to exercise the non-first _retrieve_recv_activations path — the next person to touch init sequencing won't know what the test protects. single_rank_process_group (test_stage.py:46-62) still silently reuses an existing group, now from four call sites.

8. docs/source/distributed.pipelining.md is unchanged. Acceptable, since PipelineStage is autoclass'd and the class docstring now carries the contract — flagging only so it's a deliberate choice.

Recommendation

Approve. The vote redesign is the right fix and I verified it's correct including the cross-stage asymmetry case; the centralized key constants and the documented global-index contract close the round-2 items that mattered. Before landing I'd do #1 (the backward test currently proves nothing about the exclusion, which is the one claim in your comment that doesn't hold), #2 (dead branch + duplicated message), and #6 (mechanical). #3 through #5 and #7 are judgment calls I'd take but wouldn't block on.

| Branch: `gh/sanketpurandare/6/head`

@SherlockNoMad

Copy link
Copy Markdown
Contributor

Me: How are pipeline_stage_index, pipeline_microbatch_index useful?
Agent: the PR never says, and nothing in the tree uses it.

I thought pipeline_stage_index should be constant for a stage, and should be available from Stage's property?

I can imagine how pipeline_microbatch_index is useful... but still need to read other PR in the stack to understand how you plan to use it.

[ghstack-poisoned]
…edules"

Manual pipeline stages sometimes need the global logical stage index and the microbatch index for a scheduled forward. These values belong to the schedule, which already owns every forward action, rather than to persistent stage configuration or tensor-metadata negotiation.

Add the opt-in `pass_stage_and_microbatch_indices` schedule argument. Enabled schedules pass reserved `stage_idx` and `mb_idx` keyword arguments to every built-in stage forward. Dynamic shape-metadata inference receives the actual stage index and microbatch zero, matching the representative first microbatch it already executes. The existing inference-mode vote remains unchanged.

The option applies uniformly to manually constructed `PipelineStage` instances. Caller-provided values for either reserved name are rejected before stage initialization. The documentation also records that the Python integer inputs may specialize compiled stage code.

Test Plan:

```bash
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 ScheduleTest.test_interleaved_schedule_passes_global_stage_and_microbatch_indices
lintrunner --config=.lintrunner.toml -a docs/source/distributed.pipelining.md test/distributed/pipelining/test_schedule.py test/distributed/pipelining/test_schedule_multiproc.py torch/distributed/pipelining/schedules.py
python -m sphinx -b html -W --keep-going -j 4 -c docs/source -D root_doc=distributed.pipelining <minimal-source-dir> <output-dir>
```

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] Pass stage and microbatch metadata to manual stages [pipelining] Pass stage and microbatch indices through schedules Sep 18, 2026
[ghstack-poisoned]
@sanketpurandare sanketpurandare changed the title [pipelining] Pass stage and microbatch indices through schedules [pipelining] Pass stage execution info through schedules Sep 18, 2026
## Background

Pipeline runtimes sometimes need the global logical stage and current
microbatch at the exact boundary where a stage module executes. A physical PP
rank is insufficient under virtual pipeline parallelism because one rank owns
multiple logical stages, while the microbatch identity belongs to runtime
execution rather than the model's input schema.

The previous revision transported this information through a reserved model
keyword and added an enable flag to every schedule. That made scheduler control
state part of the model signature, required kwargs copies and collision checks,
excluded traced stages, and coupled dynamic metadata inference to schedule
configuration.

## Design

`PipelineStageInfo` remains a frozen, slotted, keyword-only value containing the
global logical stage, step-local microbatch, and metadata-probe marker. A stage
now exposes `register_forward_context(factory)`, where the factory receives that
value and returns a fresh context manager around the stage computation.

The first version deliberately permits one live registration. A second
registration fails with an actionable error, and removing the returned
`RemovableHandle` permits replacement. This keeps ownership explicit and leaves
a compatibility-preserving path to multiple registrations if a concrete need
appears.

The default path performs only an empty-registry check: it constructs no info
object, copies no kwargs, and allocates no context manager. Registered runtime
forwards wrap the existing `forward_maybe_with_nosync` call. Dynamic metadata
inference wraps its representative `_compute_outputs` call with microbatch zero
and `is_metadata_inference=True`; static metadata setup does not execute the
factory. Manual and traced stages share the implementation through the stage
base class, so compiled and exported submodules retain their original graph
signatures.

Context teardown follows ordinary context-manager exception semantics. A
context is not allowed to suppress an exception raised by the stage module;
doing so produces an explicit runtime error instead of continuing without a
forward result.

## Boundaries

The registration is attached to `forward_one_chunk`, not schedule IR. Custom
actions receive it when they delegate to that method and otherwise own their
execution context. CUDA graph capture executes the Python context while
recording work, but replay does not re-enter Python; consumers must bind
replay-stable state during capture.

The implementation is built cleanly from the parent of the prior revision. It
adds no schedule constructor option, reserved keyword, schedule voting state,
or `_IR.py` behavior.

## Test Plan

```bash
python test/distributed/pipelining/test_stage.py PipelineStageForwardContextTest
python test/distributed/pipelining/test_stage.py PipelineStageMetadataInferenceTest
NCCL_DEBUG=WARN CUDA_VISIBLE_DEVICES=0,1,2,3 \
  python test/distributed/pipelining/test_stage.py
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 \
  docs/source/distributed.pipelining.md \
  test/distributed/pipelining/test_schedule_multiproc.py \
  test/distributed/pipelining/test_stage.py \
  torch/distributed/pipelining/__init__.py \
  torch/distributed/pipelining/stage.py
sphinx-build -M html docs/source docs/build -j 8 -WT --keep-going
```

The Sphinx coverage report is 100% with zero undocumented Python objects. The
local full-tree post-check separately reports two pre-existing optional c10d
backend exports below this stack; the pipelining API introduced here is fully
documented.

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] Pass stage execution info through schedules [pipelining] Expose scoped stage forward context Sep 21, 2026
## Background

Pipeline runtimes sometimes need the global logical stage and current
microbatch at the exact boundary where a stage module executes. A physical PP
rank is insufficient under virtual pipeline parallelism because one rank owns
multiple logical stages, while the microbatch identity belongs to runtime
execution rather than the model's input schema.

The previous revision transported this information through a reserved model
keyword and added an enable flag to every schedule. That made scheduler control
state part of the model signature, required kwargs copies and collision checks,
excluded traced stages, and coupled dynamic metadata inference to schedule
configuration.

## Design

`PipelineStageInfo` remains a frozen, slotted, keyword-only value containing the
global logical stage, step-local microbatch, and metadata-probe marker. A stage
now exposes `register_forward_context(factory)`, where the factory receives that
value and returns a fresh context manager around the stage computation.

The first version deliberately permits one live registration. A second
registration fails with an actionable error, and removing the returned
`RemovableHandle` permits replacement. This keeps ownership explicit and leaves
a compatibility-preserving path to multiple registrations if a concrete need
appears.

The default path performs only an empty-registry check: it constructs no info
object, copies no kwargs, and allocates no context manager. Registered runtime
forwards wrap the existing `forward_maybe_with_nosync` call. Dynamic metadata
inference wraps its representative `_compute_outputs` call with microbatch zero
and `is_metadata_inference=True`; static metadata setup does not execute the
factory. Manual and traced stages share the implementation through the stage
base class, so compiled and exported submodules retain their original graph
signatures.

Context teardown follows ordinary context-manager exception semantics. A
context is not allowed to suppress an exception raised by the stage module;
doing so produces an explicit runtime error instead of continuing without a
forward result.

## Boundaries

The registration is attached to `forward_one_chunk`, not schedule IR. Custom
actions receive it when they delegate to that method and otherwise own their
execution context. CUDA graph capture executes the Python context while
recording work, but replay does not re-enter Python; consumers must bind
replay-stable state during capture.

The implementation is built cleanly from the parent of the prior revision. It
adds no schedule constructor option, reserved keyword, schedule voting state,
or `_IR.py` behavior.

## Test Plan

```bash
python test/distributed/pipelining/test_stage.py PipelineStageForwardContextTest
python test/distributed/pipelining/test_stage.py PipelineStageMetadataInferenceTest
NCCL_DEBUG=WARN CUDA_VISIBLE_DEVICES=0,1,2,3 \
  python test/distributed/pipelining/test_stage.py
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 \
  docs/source/distributed.pipelining.md \
  test/distributed/pipelining/test_schedule_multiproc.py \
  test/distributed/pipelining/test_stage.py \
  torch/distributed/pipelining/__init__.py \
  torch/distributed/pipelining/stage.py
sphinx-build -M html docs/source docs/build -j 8 -WT --keep-going
```

The Sphinx coverage report is 100% with zero undocumented Python objects. The
local full-tree post-check separately reports two pre-existing optional c10d
backend exports below this stack; the pipelining API introduced here is fully
documented.

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

[ghstack-poisoned]
Whereas, `ScheduleInterleaved1F1B`, `ScheduleLoopedBFS`, `ScheduleInterleavedZeroBubble`, and `ScheduleZBVZeroBubble`
are subclasses of `PipelineScheduleMulti`.

### Accessing Stage Forward Information

@SherlockNoMad SherlockNoMad Sep 21, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

I didn't find example of how to access the current PipelineStageInfo from within the stage computation.

I suppose it's in your DistMoE impl, but it's missing from the current PR.

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.

You don't access it from stage computation, you set it outside via the registered context. DistMoE context or runtime does is not owned by a stage, module or layer. It is owned by the trainer runtime. So this extension allows the trainer to register a context manager that will be called around the stage forward providing it the stage id and microbatch id to chose the correct activation slot before the stage executes its forward

## Background

Pipeline runtimes sometimes need the global logical stage and current
microbatch at the exact boundary where a stage module executes. A physical PP
rank is insufficient under virtual pipeline parallelism because one rank owns
multiple logical stages, while the microbatch identity belongs to runtime
execution rather than the model's input schema.

The previous revision transported this information through a reserved model
keyword and added an enable flag to every schedule. That made scheduler control
state part of the model signature, required kwargs copies and collision checks,
excluded traced stages, and coupled dynamic metadata inference to schedule
configuration.

## Design

`PipelineStageInfo` remains a frozen, slotted, keyword-only value containing the
global logical stage, step-local microbatch, and metadata-probe marker. A stage
now exposes `register_forward_context(factory)`, where the factory receives that
value and returns a fresh context manager around the stage computation.

The first version deliberately permits one live registration. A second
registration fails with an actionable error, and removing the returned
`RemovableHandle` permits replacement. This keeps ownership explicit and leaves
a compatibility-preserving path to multiple registrations if a concrete need
appears.

The default path performs only an empty-registry check: it constructs no info
object, copies no kwargs, and allocates no context manager. Registered runtime
forwards wrap the existing `forward_maybe_with_nosync` call. Dynamic metadata
inference wraps its representative `_compute_outputs` call with microbatch zero
and `is_metadata_inference=True`; static metadata setup does not execute the
factory. Manual and traced stages share the implementation through the stage
base class, so compiled and exported submodules retain their original graph
signatures.

Context teardown follows ordinary context-manager exception semantics. A
context is not allowed to suppress an exception raised by the stage module;
doing so produces an explicit runtime error instead of continuing without a
forward result.

## Boundaries

The registration is attached to `forward_one_chunk`, not schedule IR. Custom
actions receive it when they delegate to that method and otherwise own their
execution context. CUDA graph capture executes the Python context while
recording work, but replay does not re-enter Python; consumers must bind
replay-stable state during capture.

The implementation is built cleanly from the parent of the prior revision. It
adds no schedule constructor option, reserved keyword, schedule voting state,
or `_IR.py` behavior.

## Test Plan

```bash
python test/distributed/pipelining/test_stage.py PipelineStageForwardContextTest
python test/distributed/pipelining/test_stage.py PipelineStageMetadataInferenceTest
NCCL_DEBUG=WARN CUDA_VISIBLE_DEVICES=0,1,2,3 \
  python test/distributed/pipelining/test_stage.py
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 \
  docs/source/distributed.pipelining.md \
  test/distributed/pipelining/test_schedule_multiproc.py \
  test/distributed/pipelining/test_stage.py \
  torch/distributed/pipelining/__init__.py \
  torch/distributed/pipelining/stage.py
sphinx-build -M html docs/source docs/build -j 8 -WT --keep-going
```

The Sphinx coverage report is 100% with zero undocumented Python objects. The
local full-tree post-check separately reports two pre-existing optional c10d
backend exports below this stack; the pipelining API introduced here is fully
documented.

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

@sanketpurandare

Copy link
Copy Markdown
Contributor Author

Me: How are pipeline_stage_index, pipeline_microbatch_index useful? Agent: the PR never says, and nothing in the tree uses it.

I thought pipeline_stage_index should be constant for a stage, and should be available from Stage's property?

I can imagine how pipeline_microbatch_index is useful... but still need to read other PR in the stack to understand how you plan to use it.

Reworked the API around the concrete Dist-MoE use case. A physical PP rank may own several logical stages, while activation-memory and other runtime resources are selected for each (stage_index, microbatch_index) invocation. PipelineStageInfo gives a context factory one immutable, self-contained identity, which also lets one factory be registered across several stage objects. The stage index remains available on the stage itself; carrying it in the invocation value avoids coupling a shared consumer back to a particular stage instance. The public documentation now includes this use case and the API no longer changes the wrapped module's forward signature.

## Background

Pipeline runtimes sometimes need the global logical stage and current
microbatch at the exact boundary where a stage module executes. A physical PP
rank is insufficient under virtual pipeline parallelism because one rank owns
multiple logical stages, while the microbatch identity belongs to runtime
execution rather than the model's input schema.

The previous revision transported this information through a reserved model
keyword and added an enable flag to every schedule. That made scheduler control
state part of the model signature, required kwargs copies and collision checks,
excluded traced stages, and coupled dynamic metadata inference to schedule
configuration.

## Design

`PipelineStageInfo` remains a frozen, slotted, keyword-only value containing the
global logical stage, step-local microbatch, and metadata-probe marker. A stage
now exposes `register_forward_context(factory)`, where the factory receives that
value and returns a fresh context manager around the stage computation.

The first version deliberately permits one live registration. A second
registration fails with an actionable error, and removing the returned
`RemovableHandle` permits replacement. This keeps ownership explicit and leaves
a compatibility-preserving path to multiple registrations if a concrete need
appears.

The default path performs only an empty-registry check: it constructs no info
object, copies no kwargs, and allocates no context manager. Registered runtime
forwards wrap the existing `forward_maybe_with_nosync` call. Dynamic metadata
inference wraps its representative `_compute_outputs` call with microbatch zero
and `is_metadata_inference=True`; static metadata setup does not execute the
factory. Manual and traced stages share the implementation through the stage
base class, so compiled and exported submodules retain their original graph
signatures.

Context teardown follows ordinary context-manager exception semantics. A
context is not allowed to suppress an exception raised by the stage module;
doing so produces an explicit runtime error instead of continuing without a
forward result.

## Boundaries

The registration is attached to `forward_one_chunk`, not schedule IR. Custom
actions receive it when they delegate to that method and otherwise own their
execution context. CUDA graph capture executes the Python context while
recording work, but replay does not re-enter Python; consumers must bind
replay-stable state during capture.

The implementation is built cleanly from the parent of the prior revision. It
adds no schedule constructor option, reserved keyword, schedule voting state,
or `_IR.py` behavior.

## Test Plan

```bash
python test/distributed/pipelining/test_stage.py PipelineStageForwardContextTest
python test/distributed/pipelining/test_stage.py PipelineStageMetadataInferenceTest
NCCL_DEBUG=WARN CUDA_VISIBLE_DEVICES=0,1,2,3 \
  python test/distributed/pipelining/test_stage.py
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 \
  docs/source/distributed.pipelining.md \
  test/distributed/pipelining/test_schedule_multiproc.py \
  test/distributed/pipelining/test_stage.py \
  torch/distributed/pipelining/__init__.py \
  torch/distributed/pipelining/stage.py
sphinx-build -M html docs/source docs/build -j 8 -WT --keep-going
```

The Sphinx coverage report is 100% with zero undocumented Python objects. The
local full-tree post-check separately reports two pre-existing optional c10d
backend exports below this stack; the pipelining API introduced here is fully
documented.

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

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

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

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

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

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

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

AI assistance disclosure:
> This change was authored with assistance from an AI coding tool and reviewed by the author.
Pull Request resolved: #196463
Approved by: https://github.com/SherlockNoMad
ghstack dependencies: #196460, #196461, #196956, #196462
pytorchmergebot pushed a commit that referenced this pull request Sep 22, 2026
…6464)

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

## Before and after

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

## Responsibility boundaries

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

## Behavior by mode

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

## Shared-parent setup

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

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

## Removed machinery

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

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

## Test Plan

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

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

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

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