Skip to content

[PP][2/3] DTensor-aware stage and schedule refactoring - #177728

Closed
sanketpurandare wants to merge 1 commit into
mainfrom
sanketpurandare/stack/2
Closed

sanketpurandare wants to merge 1 commit into
mainfrom
sanketpurandare/stack/2

Conversation

@sanketpurandare

@sanketpurandare sanketpurandare commented Mar 18, 2026 •

Copy link
Copy Markdown
Contributor

Stacked PRs:

Fixes #172419


[PP][2/3] DTensor-aware stage and schedule refactoring

Summary:
Refactors PipelineStage and schedule infrastructure for DTensor-aware
Pipeline Parallelism, migrating to the new metadata utilities from [1/3].

Key changes in stage.py:

  • Refactored _PipelineStageBase, _PipelineStage, PipelineStage for
    DTensor support with STATIC/DYNAMIC inference modes
  • Replaced _RootArgPlaceholder with unified _RecvInfo.is_root_arg flag
  • New _prepare_forward_infra/_prepare_backward_infra for metadata-driven
    initialization with DTensor shape/placement tracking
  • Replaced PipeliningShapeError with PipeliningMetadataError
  • Added _validate_fwd_inputs using new TensorMeta-based validation
  • _make_tensor_from_meta moved from stage.py to _utils.py

Key changes in schedules.py:

  • Added _determine_and_set_global_inference_mode() for cross-stage
    consensus on STATIC vs DYNAMIC mode
  • Refactored _initialize_stage(s) with mode-change detection
  • Updated step() callers to extract first_target from target_mbs

Key changes in _utils.py:

  • Replaced old validate_tensors_metadata (torch.Tensor signature) with
    new TensorMeta-based version
  • Removed legacy backward-compat shims: PipeliningShapeError,
    validate_tensor_metadata, old validate_tensors_metadata

Test fixes:

  • test_stage.py: PipeliningShapeError -> PipeliningMetadataError

Test Plan:
python -m pytest test/distributed/pipelining/ -x

@pytorch-bot

pytorch-bot Bot commented Mar 18, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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:

⏳ 1 Pending, 17 Unrelated Failures

As of commit 59ff000 with merge base 47cdb41 (image):

BROKEN TRUNK - The following jobs failed but were present on the merge base:

👉 Rebase onto the `viable/strict` branch to avoid these failures

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 Mar 18, 2026
@pytorch-bot

pytorch-bot Bot commented Mar 18, 2026

Copy link
Copy Markdown

This PR needs a release notes: label

If your changes are user facing and intended to be a part of release notes, please use a label starting with release notes:.

If not, please add the topic: not user facing label.

To add a label, you can comment to pytorchbot, for example
@pytorchbot label "topic: not user facing"

For more information, see
https://github.com/pytorch/pytorch/wiki/PyTorch-AutoLabel-Bot#why-categorize-for-release-notes-and-how-does-it-work.

Comment thread torch/distributed/pipelining/_utils.py Resolved
Comment thread torch/distributed/pipelining/stage.py Resolved

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

reviewed all the changes except stage.py, coming back for that later

Comment thread torch/distributed/pipelining/stage.py Resolved
Comment thread torch/distributed/pipelining/stage.py Resolved
Comment thread torch/distributed/pipelining/stage.py Resolved
Comment thread torch/distributed/pipelining/stage.py Resolved
Comment thread torch/distributed/pipelining/stage.py Resolved
Comment thread torch/distributed/pipelining/stage.py Resolved
Comment thread torch/distributed/pipelining/stage.py Resolved
@wconstab

Copy link
Copy Markdown
Contributor

@claude carefully review this PR. pay special attention to

  • p2p comms for fwd/bwd metadata inference- any errors here that could lead to a hang?
  • static vs dynamic modes- do we ensure consistency across ranks and across fwd/bwd in all methods?
  • any backward-compatibility breaking changes?

@claude

claude Bot commented Mar 19, 2026 •

Copy link
Copy Markdown

Claude finished @wconstab's task in 5m 41s —— View job


Review: [PP][2/3] DTensor-aware stage and schedule refactoring

  • Read full PR diff and all changed files
  • Analyze P2P comms for fwd/bwd metadata inference (hang potential)
  • Analyze static vs dynamic mode consistency across ranks and fwd/bwd
  • Check for backward-compatibility breaking changes
  • Post detailed review

1. P2P Comms for Fwd/Bwd Metadata Inference — Hang Potential

1a. STATIC mode skips P2P metadata entirely — hang risk if ranks disagree on mode

In STATIC mode, _prepare_forward_infra (stage.py:2237-2239) copies from _user_meta and never calls _send_meta/_recv_meta. In DYNAMIC mode, _forward_metadata_inference (stage.py:1877) calls _recv_meta/_send_meta as P2P. If one rank is STATIC while another is DYNAMIC, the DYNAMIC rank will block on _recv_meta forever.

The _determine_and_set_global_inference_mode allreduce (schedules.py:33-66) is designed to prevent this — good. But:

Concern: The all_reduce uses stages[0].group (the PP group). This is correct for the standard case where the PP group spans all pipeline ranks. However, I wanted to flag that the allreduce assumes all PP ranks participate in this group. If stages[0].group is None (defaulting to the world group), and there's e.g. TP parallelism on the same world group, extra ranks will participate in the allreduce, which is harmless but wasteful. Just worth noting — not a bug.

1b. Forward metadata P2P ordering: looks correct, no hang

Forward inference runs stage 0 → N (_forward_metadata_inference):

  • Stage 0: no recv, computes, sends to stage 1 (if cross-rank) or returns _StageForwardMeta (if same-rank)
  • Stage i: recv from i-1 (or receives via arg), computes, sends to i+1

The P2P pattern is send_object_list on the sender and recv_object_list on the receiver, both with use_batch=True. The ordering is sequential (0→1→2→...) which avoids deadlocks since each stage waits only for its predecessor.

However, there's a subtle concern: _send_meta and _recv_meta (stage.py:1699-1729) use dist.recv_object_list / dist.send_object_list directly (not batched P2P). These are blocking operations. In the Multi-schedule case (_initialize_stages, schedules.py:1628-1642), stages on the same rank are processed sequentially in a loop. This works for the V-schedule pattern because same-rank stages pass metadata via return values, and cross-rank stages use P2P with matching send/recv pairs.

Potential issue: In the V-schedule multi-stage case, the loop iterates stages on a single rank. If stage i on rank R needs to send metadata to stage i+1 on a different rank, it sends immediately. Stage i+1's rank should be running its own _prepare_forward_infra which calls _recv_meta. But this depends on both ranks entering the _initialize_stages loop at roughly the same time. Since both ranks call _determine_and_set_global_inference_mode (a collective) first, they do synchronize before entering the loop. This looks safe.

1c. Backward metadata P2P ordering: looks correct, but tighter coupling

Backward inference runs stage N → 0 (_backward_metadata_inference, stage.py:1979):

  • Last stage: computes loss + input_grads, sends to N-1
  • Stage i: recv from i+1, computes input_grads, sends to i-1

In the Multi-schedule path (schedules.py:1648), stages are iterated in reverse order. Same-rank stages pass metadata via received_grad_meta return value; cross-rank stages use P2P. This is a clean mirror of forward and should not hang.

One concern: _backward_metadata_inference requires _fwd_outputs_for_bwd_meta to be populated from forward inference. If for some reason forward inference didn't run (or _fwd_outputs_for_bwd_meta was cleared), you'll get a PipeliningMetadataError rather than a hang. Good defensive coding.

1d. _recv_meta/_send_meta error handling

Both _recv_meta and _send_meta (stage.py:1699-1729) use dist.recv_object_list/send_object_list without a timeout. If there's any mismatched P2P (e.g., a send without a matching recv), the process will hang indefinitely. This is inherent to P2P communication and not unique to this PR, but worth noting that the new metadata inference adds more P2P opportunities for mismatches. A timeout-based watchdog or NCCL_TIMEOUT would be the safety net here.


2. Static vs Dynamic Mode Consistency

2a. Mode determination — correct but fragile edge case

_determine_and_set_global_inference_mode (schedules.py:33-66) uses MAX allreduce: if any rank votes DYNAMIC, all go DYNAMIC. This is the correct design.

InferenceMode.needs_dynamic (_utils.py:422-451) checks:

  1. Forward metadata incomplete → DYNAMIC
  2. No DTensors → STATIC (grad metadata derivable from fwd shapes)
  3. No backward → STATIC
  4. DTensors + backward + missing grad metadata → DYNAMIC
  5. DTensors + complete grad → STATIC

This logic is sound. The key insight is that for plain tensors, grad shapes always match fwd shapes, so no inference is needed. For DTensors, grad placements can differ (e.g., Replicate → Partial), so you need either user-provided metadata or inference.

Edge case: If _determine_and_set_global_inference_mode is only called when isinstance(self._stage, PipelineStage) (schedules.py:622), what happens if some stages are PipelineStage and others are _PipelineStage? The guard is if isinstance(self._stage, PipelineStage) (single schedule) and if all(isinstance(stage, PipelineStage) for stage in self._stages) (multi). If a mix exists, no mode is set, and PipelineStage._prepare_forward_infra will raise "inference mode not set" at stage.py:2220-2223. Mixing _PipelineStage and PipelineStage would be an unusual configuration, but the error message could be clearer about why mode isn't set.

2b. Mode consistency across fwd/bwd

The mode is set once per _initialize_stage/_initialize_stages call and applies to both forward and backward. Forward uses it in _prepare_forward_infra (stage.py:2228), backward in _prepare_backward_infra (stage.py:2128). The same self._inference_mode is checked in both paths. Consistent.

2c. Mode-change detection (eval↔train)

The mode-change detection logic at schedules.py:608-613 and schedules.py:1607-1612:

p2p_done = self._stage_forward_initialized
if self._stage_forward_initialized and (
    self._has_backward != self._stage_backward_initialized
):
    self._stage_forward_initialized = False
    self._stage_backward_initialized = False

Bug/Concern: self._stage_backward_initialized is a bool (initialized to False). self._has_backward is also a bool. The comparison self._has_backward != self._stage_backward_initialized is comparing two bools, but _stage_backward_initialized represents "has backward infra been setup?", NOT "was the last run a backward run".

Consider this scenario:

  1. First call: _has_backward=True. Forward inits (_stage_forward_initialized = True). Backward inits (_stage_backward_initialized = True).
  2. Second call: _has_backward=False (eval mode). Check: True and (False != True) → True. Resets both. Re-runs forward init + allreduce. Good.
  3. Third call: _has_backward=True (back to train). Check: True and (True != False) → True. Resets both. Re-runs forward init + allreduce. Good.

Actually, wait — after step 2, _stage_backward_initialized stays False because _has_backward=False skips the backward block. So in step 3, _stage_forward_initialized = True, _stage_backward_initialized = False, _has_backward = True. Check: True and (True != False) → resets both → re-inits. Correct behavior, but the allreduce runs again. This means every train→eval→train cycle triggers 2 allreduces and 2 sets of P2P metadata exchanges. Not a correctness issue, but could be optimized.

More importantly: When mode changes and the allreduce is re-run, ALL ranks must re-enter _initialize_stage simultaneously. If one rank switches to eval while another stays in train, they must still synchronize on the allreduce. Since eval() calls step() which calls _initialize_stage, and _has_backward is per-schedule-instance, all ranks must call eval() or step() at the same time. This is already an implicit requirement of pipeline parallelism, so it should be fine.


3. Backward-Compatibility Breaking Changes

3a. PipeliningShapeError → PipeliningMetadataError — BREAKING

PipeliningShapeError is removed from _utils.py and replaced with PipeliningMetadataError. The test changes confirm this (test_stage.py). Any user code that catches PipeliningShapeError will break. Since PipeliningShapeError was in _utils.py (not __init__.py), it might be semi-internal, but it was public enough to be imported in tests.

3b. _RootArgPlaceholder removed — BREAKING for subclasses

_RootArgPlaceholder is removed and replaced with _RecvInfo(is_root_arg=True). Any code that isinstance-checks against _RootArgPlaceholder or creates instances will break. The InputInfo = _RecvInfo | _RootArgPlaceholder type alias is also gone. This is an internal type, so the impact should be limited.

3c. _prepare_forward_infra signature change — BREAKING for subclasses

Old signature: _prepare_forward_infra(self, num_microbatches, args, kwargs=None)
New signature: _prepare_forward_infra(self, num_microbatches, args, kwargs=None, has_backward=False) -> _StageForwardMeta | None

The has_backward parameter is new and the return type is changed from tuple[Any, ...] to _StageForwardMeta | None. Any custom subclass of _PipelineStageBase that overrides _prepare_forward_infra will break.

3d. _prepare_backward_infra signature change — BREAKING for subclasses

Old signature: _prepare_backward_infra(self, num_microbatches)
New signature: _prepare_backward_infra(self, num_microbatches, loss_fn=None, target=None, received_grad_meta=None) -> _StageBackwardMeta | None

Same concern as above.

3e. PipelineStage.__init__ new parameters — NOT breaking (additive)

New optional parameters: output_grads, input_grads, get_mesh. Since they default to None, existing code will work unchanged. Good.

3f. validate_tensors_metadata signature change — BREAKING

Old: validate_tensors_metadata(desc, expected_tensors: list[torch.Tensor], actual_tensors: list[torch.Tensor])
New: validate_tensors_metadata(desc, expected_metas: tuple[TensorMeta | None, ...], actuals: tuple[torch.Tensor | TensorMeta | None, ...], *, skip_none_actuals=False, warn_on_mismatch=False)

The function now expects TensorMeta objects instead of raw tensors. Any external code calling validate_tensors_metadata with tensors will break.

3g. PipelineStage no longer auto-infers shapes at init when output_args is missing

The old code had a deprecation path where passing only input_args would run submodule(*inputs_meta) at init time with a deprecation warning. This path is removed. Users who relied on init-time inference with only input_args will now silently get DYNAMIC mode instead of the old eager-inference behavior. This is a behavior change but arguably an improvement since the old behavior was already deprecated.


4. Additional Issues

4a. _compute_input_grads for backward metadata inference (stage.py:1751-1787)

This uses torch.autograd.grad to compute input gradients during metadata inference on the meta device. wconstab flagged this in review comments (stage.py:1778). This is a separate autograd.grad call from the ones in _backward.py, which means gradient computation logic is duplicated. If the behavior diverges (e.g., different allow_unused settings), metadata inference could produce incorrect metadata. Consider documenting why this separate call is needed.

4b. Missing grad_placements in DTensor.from_local calls

As wconstab noted (stage.py:680), the DTensor.from_local call in _retrieve_recv_activations doesn't set grad_placements. For activations where grad placements differ from the forward placements (e.g., Shard → Partial), this could lead to incorrect gradient shapes. The backward path in _retrieve_recv_grads (stage.py:732) uses separate placement metadata from output_grads, which is correct. But the forward DTensor reconstruction at line 673-680 should potentially set grad_placements when the metadata is available.

4c. self.get_mesh assigned as instance attribute, not method (stage.py:211, 1664)

As wconstab noted, self.get_mesh = get_mesh stores a callable as an instance attribute rather than binding it as a method. If someone calls self.get_mesh(...), self won't be passed as the first argument (which is correct behavior for a stored callable, but confusing). Consider using a private name like _get_mesh_fn to avoid confusion with method call syntax.

4d. assert statements without raise AssertionError

Several places use assert statements (stage.py:656, 399, 400, 657, 723, 726, 910, 1021). Per PyTorch conventions, these should use raise AssertionError to avoid being stripped by -O. wconstab flagged stage.py:656 specifically.

4e. _determine_and_set_global_inference_mode runs the collective even for re-initialization

On mode change (eval↔train), both forward and backward infra are reset, and the allreduce runs again. This is correct for consistency but adds latency on mode transitions. Not a bug, but a perf consideration.

4f. _backwards_metadata_inference stores and then clears temporary state

_fwd_outputs_for_bwd_meta, _fwd_inputs_for_bwd_meta, _fwd_kwargs_tensors_for_bwd_meta are set during forward inference and consumed/cleared during backward inference (stage.py:2091-2094). This means backward inference must run exactly once after forward inference. If someone calls _prepare_forward_infra twice without calling _prepare_backward_infra, the old state is silently overwritten (no error). And if _prepare_backward_infra is called twice, the second call will raise PipeliningMetadataError because the fields are cleared. This seems fine given the current call patterns, but is somewhat fragile.


Summary

The overall design is sound. The allreduce-based mode consensus and sequential P2P metadata passing should prevent hangs under normal operation. The main risks are:

  1. Hang risk is low but present: if any rank fails to enter _initialize_stage (e.g., exception before the allreduce), other ranks will hang on the collective. Standard distributed computing concern.
  2. Mode consistency is correctly enforced via the allreduce, assuming all ranks call initialization synchronously (which is inherent to PP).
  3. Several backward-compatibility breaks exist, primarily around PipeliningShapeError removal, signature changes to _prepare_forward_infra/_prepare_backward_infra/validate_tensors_metadata, and _RootArgPlaceholder removal. These should be documented in release notes.
  4. Missing grad_placements on DTensor.from_local for forward activations could be a correctness issue for DTensor pipelines where grad placements differ from forward placements.

@sanketpurandare
sanketpurandare changed the base branch from sanketpurandare/stack/1 to main March 20, 2026 23:25
sanketpurandare added a commit that referenced this pull request Mar 20, 2026
Summary:
Refactors PipelineStage and schedule infrastructure for DTensor-aware
Pipeline Parallelism.

Key changes in stage.py:
- Refactored _PipelineStageBase, _PipelineStage, PipelineStage for
  DTensor support with STATIC/DYNAMIC inference modes
- Replaced _RootArgPlaceholder with unified _RecvInfo.is_root_arg flag
- New _prepare_forward_infra/_prepare_backward_infra for metadata-driven
  initialization with DTensor shape/placement tracking
- Replaced PipeliningShapeError with PipeliningMetadataError
- Added _validate_fwd_inputs using new TensorMeta-based validation
- _make_tensor_from_meta moved from stage.py to _utils.py

Key changes in schedules.py:
- Added _determine_and_set_global_inference_mode() for cross-stage
  consensus on STATIC vs DYNAMIC mode
- Refactored _initialize_stage(s) with mode-change detection
- Updated step() callers to extract first_target from target_mbs

Key changes in _utils.py:
- Replaced old validate_tensor_metadata/validate_tensors_metadata
  (torch.Tensor signatures) with new TensorMeta-based validation
- Removed legacy PipeliningShapeError class

Test fixes:
- test_stage.py: PipeliningShapeError -> PipeliningMetadataError
- test_schedule_multiproc.py: grad context and detach fixes

Test Plan:
python -m pytest test/distributed/pipelining/ -x

stack-info: PR: #177728, branch: sanketpurandare/stack/2
@sanketpurandare
sanketpurandare force-pushed the sanketpurandare/stack/2 branch from d653abe to cb7d43d Compare March 20, 2026 23:25
@sanketpurandare
sanketpurandare changed the base branch from main to sanketpurandare/stack/1 March 20, 2026 23:28
@sanketpurandare
sanketpurandare changed the base branch from sanketpurandare/stack/1 to main March 20, 2026 23:33
pytorch-bot Bot pushed a commit that referenced this pull request Mar 20, 2026
Summary:
Refactors PipelineStage and schedule infrastructure for DTensor-aware
Pipeline Parallelism.

Key changes in stage.py:
- Refactored _PipelineStageBase, _PipelineStage, PipelineStage for
  DTensor support with STATIC/DYNAMIC inference modes
- Replaced _RootArgPlaceholder with unified _RecvInfo.is_root_arg flag
- New _prepare_forward_infra/_prepare_backward_infra for metadata-driven
  initialization with DTensor shape/placement tracking
- Replaced PipeliningShapeError with PipeliningMetadataError
- Added _validate_fwd_inputs using new TensorMeta-based validation
- _make_tensor_from_meta moved from stage.py to _utils.py

Key changes in schedules.py:
- Added _determine_and_set_global_inference_mode() for cross-stage
  consensus on STATIC vs DYNAMIC mode
- Refactored _initialize_stage(s) with mode-change detection
- Updated step() callers to extract first_target from target_mbs

Key changes in _utils.py:
- Replaced old validate_tensor_metadata/validate_tensors_metadata
  (torch.Tensor signatures) with new TensorMeta-based validation
- Removed legacy PipeliningShapeError class

Test fixes:
- test_stage.py: PipeliningShapeError -> PipeliningMetadataError
- test_schedule_multiproc.py: grad context and detach fixes

Test Plan:
python -m pytest test/distributed/pipelining/ -x

stack-info: PR: #177728, branch: sanketpurandare/stack/2
@sanketpurandare
sanketpurandare changed the base branch from main to sanketpurandare/stack/1 March 20, 2026 23:34
@tianyu-l
tianyu-l requested a review from acisseJZhong March 22, 2026 20:46
@sanketpurandare
sanketpurandare force-pushed the sanketpurandare/stack/2 branch from 99b4a45 to 1fd24af Compare April 9, 2026 11:16
@sanketpurandare
sanketpurandare changed the base branch from main to sanketpurandare/stack/1 April 9, 2026 11:16
pytorchmergebot pushed a commit that referenced this pull request Apr 9, 2026
Stacked PRs:
 * #177729
 * #177728
 * __->__#177727

--- --- ---

### [PP][1/3] DTensor metadata foundation for Pipeline Parallelism

Summary:
Introduces core DTensor metadata types, helper infrastructure, and
utility additions for DTensor-aware Pipeline Parallelism (PP).

This commit adds:
- Foundational metadata dataclasses: _TensorMeta, _DTensorMeta,
  _StageMeta, _StageForwardMeta, _StageBackwardMeta
- InferenceMode enum (STATIC/DYNAMIC)
- _MeshCache for DeviceMesh caching with get_mesh() API and
  GetMeshCallback protocol
- to_tensor(device) / to_dtensor(device, mesh) methods on metadata classes
- Refactored flatten_args with optional detach parameter
- DTensor-aware microbatch splitting/merging in microbatch.py
- Metadata extraction helpers: extract_tensor_meta, extract_tensor_metas,
  to_local_if_dtensor, validate_and_normalize_to_tuple
- TensorMeta-based validation: validate_metadata,
  validate_static_arg_grad_correspondence
- _derive_grad_metas for gradient metadata derivation
- _autograd_grad_for_inputs and refactored stage_backward_input in _backward.py
- Grad context and detach fixes in test_schedule_multiproc.py

Legacy functions (PipeliningShapeError, validate_tensor_metadata,
old validate_tensors_metadata) are kept for backward compatibility
— removed in the next commit.

Test Plan:
python -m pytest test/distributed/pipelining/ -x

Pull Request resolved: #177727
Approved by: https://github.com/wconstab, https://github.com/acisseJZhong
@sanketpurandare
sanketpurandare changed the base branch from sanketpurandare/stack/1 to main April 9, 2026 13:29
@sanketpurandare
sanketpurandare force-pushed the sanketpurandare/stack/2 branch from 1fd24af to d363328 Compare April 9, 2026 13:29
Summary:
Refactors PipelineStage and schedule infrastructure for DTensor-aware
Pipeline Parallelism, migrating to the new metadata utilities from [1/3].

Key changes in stage.py:
- Refactored _PipelineStageBase, _PipelineStage, PipelineStage for
  DTensor support with STATIC/DYNAMIC inference modes
- Replaced _RootArgPlaceholder with unified _RecvInfo.is_root_arg flag
- New _prepare_forward_infra/_prepare_backward_infra for metadata-driven
  initialization with DTensor shape/placement tracking
- Replaced PipeliningShapeError with PipeliningMetadataError
- Added _validate_fwd_inputs using new TensorMeta-based validation
- _make_tensor_from_meta moved from stage.py to _utils.py

Key changes in schedules.py:
- Added _determine_and_set_global_inference_mode() for cross-stage
  consensus on STATIC vs DYNAMIC mode
- Refactored _initialize_stage(s) with mode-change detection
- Updated step() callers to extract first_target from target_mbs

Key changes in _utils.py:
- Replaced old validate_tensors_metadata (torch.Tensor signature) with
  new TensorMeta-based version
- Removed legacy backward-compat shims: PipeliningShapeError,
  validate_tensor_metadata, old validate_tensors_metadata

Test fixes:
- test_stage.py: PipeliningShapeError -> PipeliningMetadataError

Test Plan:
python -m pytest test/distributed/pipelining/ -x

stack-info: PR: #177728, branch: sanketpurandare/stack/2
@sanketpurandare
sanketpurandare force-pushed the sanketpurandare/stack/2 branch from d363328 to 59ff000 Compare April 9, 2026 19:51
@pytorch pytorch deleted a comment from pytorch-bot Bot Apr 9, 2026
@sanketpurandare

Copy link
Copy Markdown
Contributor Author

@pytorchbot merge -i

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge started

Your change will be merged while ignoring the following 0 checks:

Learn more about merging in the wiki.

Questions? Feedback? Please reach out to the PyTorch DevX Team

Advanced Debugging
Check the merge workflow status
here

@sanketpurandare

Copy link
Copy Markdown
Contributor Author

@pytorchbot merge -f "Unrelated failures due to broken trunk"

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge started

Your change will be merged immediately since you used the force (-f) flag, bypassing any CI checks (ETA: 1-5 minutes). Please use -f as last resort and instead consider -i/--ignore-current to continue the merge ignoring current failures. This will allow currently pending tests to finish and report signal before the merge.

Learn more about merging in the wiki.

Questions? Feedback? Please reach out to the PyTorch DevX Team

Advanced Debugging
Check the merge workflow status
here

@github-actions
github-actions Bot deleted the sanketpurandare/stack/2 branch May 10, 2026 02:27
pytorchmergebot pushed a commit that referenced this pull request Jun 3, 2026
Fixes a bug for non-CUDA devices introduced by #177728 due to a misused call to fork_rng

* Since the call to fork_rng should specify the device type, I specify this in `schedules.py`
* The design of fork_rng seems outdated since the adoption of non-CUDA devices. I change the signature so the device_type default argument is `None`, and is inferred from the passed devices. If it can't be inferred from the device list (because it's a list of ints, for example) we still fallback to the previous value of "cuda".

Pull Request resolved: #180512
Approved by: https://github.com/guangyey, https://github.com/albanD

Co-authored-by: Yu, Guangye <[email protected]>
gplutop7 pushed a commit to gplutop7/pytorch that referenced this pull request Jul 15, 2026
…ch#177727)

Stacked PRs:
 * pytorch#177729
 * pytorch#177728
 * __->__#177727

--- --- ---

### [PP][1/3] DTensor metadata foundation for Pipeline Parallelism

Summary:
Introduces core DTensor metadata types, helper infrastructure, and
utility additions for DTensor-aware Pipeline Parallelism (PP).

This commit adds:
- Foundational metadata dataclasses: _TensorMeta, _DTensorMeta,
  _StageMeta, _StageForwardMeta, _StageBackwardMeta
- InferenceMode enum (STATIC/DYNAMIC)
- _MeshCache for DeviceMesh caching with get_mesh() API and
  GetMeshCallback protocol
- to_tensor(device) / to_dtensor(device, mesh) methods on metadata classes
- Refactored flatten_args with optional detach parameter
- DTensor-aware microbatch splitting/merging in microbatch.py
- Metadata extraction helpers: extract_tensor_meta, extract_tensor_metas,
  to_local_if_dtensor, validate_and_normalize_to_tuple
- TensorMeta-based validation: validate_metadata,
  validate_static_arg_grad_correspondence
- _derive_grad_metas for gradient metadata derivation
- _autograd_grad_for_inputs and refactored stage_backward_input in _backward.py
- Grad context and detach fixes in test_schedule_multiproc.py

Legacy functions (PipeliningShapeError, validate_tensor_metadata,
old validate_tensors_metadata) are kept for backward compatibility
— removed in the next commit.

Test Plan:
python -m pytest test/distributed/pipelining/ -x

Pull Request resolved: pytorch#177727
Approved by: https://github.com/wconstab, https://github.com/acisseJZhong
gplutop7 pushed a commit to gplutop7/pytorch that referenced this pull request Jul 15, 2026
Stacked PRs:
 * pytorch#177729
 * __->__#177728

Fixes pytorch#172419
--- --- ---

### [PP][2/3] DTensor-aware stage and schedule refactoring

Summary:
Refactors PipelineStage and schedule infrastructure for DTensor-aware
Pipeline Parallelism, migrating to the new metadata utilities from [1/3].

Key changes in stage.py:
- Refactored _PipelineStageBase, _PipelineStage, PipelineStage for
  DTensor support with STATIC/DYNAMIC inference modes
- Replaced _RootArgPlaceholder with unified _RecvInfo.is_root_arg flag
- New _prepare_forward_infra/_prepare_backward_infra for metadata-driven
  initialization with DTensor shape/placement tracking
- Replaced PipeliningShapeError with PipeliningMetadataError
- Added _validate_fwd_inputs using new TensorMeta-based validation
- _make_tensor_from_meta moved from stage.py to _utils.py

Key changes in schedules.py:
- Added _determine_and_set_global_inference_mode() for cross-stage
  consensus on STATIC vs DYNAMIC mode
- Refactored _initialize_stage(s) with mode-change detection
- Updated step() callers to extract first_target from target_mbs

Key changes in _utils.py:
- Replaced old validate_tensors_metadata (torch.Tensor signature) with
  new TensorMeta-based version
- Removed legacy backward-compat shims: PipeliningShapeError,
  validate_tensor_metadata, old validate_tensors_metadata

Test fixes:
- test_stage.py: PipeliningShapeError -> PipeliningMetadataError

Test Plan:
python -m pytest test/distributed/pipelining/ -x

Pull Request resolved: pytorch#177728
Approved by: https://github.com/wconstab
gplutop7 pushed a commit to gplutop7/pytorch that referenced this pull request Jul 15, 2026
Fixes a bug for non-CUDA devices introduced by pytorch#177728 due to a misused call to fork_rng

* Since the call to fork_rng should specify the device type, I specify this in `schedules.py`
* The design of fork_rng seems outdated since the adoption of non-CUDA devices. I change the signature so the device_type default argument is `None`, and is inferred from the passed devices. If it can't be inferred from the device list (because it's a list of ints, for example) we still fallback to the previous value of "cuda".

Pull Request resolved: pytorch#180512
Approved by: https://github.com/guangyey, https://github.com/albanD

Co-authored-by: Yu, Guangye <[email protected]>
aws-kingrj pushed a commit to amazon-contributing/upstream-to-pytorch that referenced this pull request Jul 29, 2026
…ch#177727)

Stacked PRs:
 * pytorch#177729
 * pytorch#177728
 * __->__#177727

--- --- ---

### [PP][1/3] DTensor metadata foundation for Pipeline Parallelism

Summary:
Introduces core DTensor metadata types, helper infrastructure, and
utility additions for DTensor-aware Pipeline Parallelism (PP).

This commit adds:
- Foundational metadata dataclasses: _TensorMeta, _DTensorMeta,
  _StageMeta, _StageForwardMeta, _StageBackwardMeta
- InferenceMode enum (STATIC/DYNAMIC)
- _MeshCache for DeviceMesh caching with get_mesh() API and
  GetMeshCallback protocol
- to_tensor(device) / to_dtensor(device, mesh) methods on metadata classes
- Refactored flatten_args with optional detach parameter
- DTensor-aware microbatch splitting/merging in microbatch.py
- Metadata extraction helpers: extract_tensor_meta, extract_tensor_metas,
  to_local_if_dtensor, validate_and_normalize_to_tuple
- TensorMeta-based validation: validate_metadata,
  validate_static_arg_grad_correspondence
- _derive_grad_metas for gradient metadata derivation
- _autograd_grad_for_inputs and refactored stage_backward_input in _backward.py
- Grad context and detach fixes in test_schedule_multiproc.py

Legacy functions (PipeliningShapeError, validate_tensor_metadata,
old validate_tensors_metadata) are kept for backward compatibility
— removed in the next commit.

Test Plan:
python -m pytest test/distributed/pipelining/ -x

Pull Request resolved: pytorch#177727
Approved by: https://github.com/wconstab, https://github.com/acisseJZhong
aws-kingrj pushed a commit to amazon-contributing/upstream-to-pytorch that referenced this pull request Jul 29, 2026
Stacked PRs:
 * pytorch#177729
 * __->__#177728

Fixes pytorch#172419
--- --- ---

### [PP][2/3] DTensor-aware stage and schedule refactoring

Summary:
Refactors PipelineStage and schedule infrastructure for DTensor-aware
Pipeline Parallelism, migrating to the new metadata utilities from [1/3].

Key changes in stage.py:
- Refactored _PipelineStageBase, _PipelineStage, PipelineStage for
  DTensor support with STATIC/DYNAMIC inference modes
- Replaced _RootArgPlaceholder with unified _RecvInfo.is_root_arg flag
- New _prepare_forward_infra/_prepare_backward_infra for metadata-driven
  initialization with DTensor shape/placement tracking
- Replaced PipeliningShapeError with PipeliningMetadataError
- Added _validate_fwd_inputs using new TensorMeta-based validation
- _make_tensor_from_meta moved from stage.py to _utils.py

Key changes in schedules.py:
- Added _determine_and_set_global_inference_mode() for cross-stage
  consensus on STATIC vs DYNAMIC mode
- Refactored _initialize_stage(s) with mode-change detection
- Updated step() callers to extract first_target from target_mbs

Key changes in _utils.py:
- Replaced old validate_tensors_metadata (torch.Tensor signature) with
  new TensorMeta-based version
- Removed legacy backward-compat shims: PipeliningShapeError,
  validate_tensor_metadata, old validate_tensors_metadata

Test fixes:
- test_stage.py: PipeliningShapeError -> PipeliningMetadataError

Test Plan:
python -m pytest test/distributed/pipelining/ -x

Pull Request resolved: pytorch#177728
Approved by: https://github.com/wconstab
aws-kingrj pushed a commit to amazon-contributing/upstream-to-pytorch that referenced this pull request Jul 29, 2026
Fixes a bug for non-CUDA devices introduced by pytorch#177728 due to a misused call to fork_rng

* Since the call to fork_rng should specify the device type, I specify this in `schedules.py`
* The design of fork_rng seems outdated since the adoption of non-CUDA devices. I change the signature so the device_type default argument is `None`, and is inferred from the passed devices. If it can't be inferred from the device list (because it's a list of ints, for example) we still fallback to the previous value of "cuda".

Pull Request resolved: pytorch#180512
Approved by: https://github.com/guangyey, https://github.com/albanD

Co-authored-by: Yu, Guangye <[email protected]>
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 ciflow/trunk Trigger trunk jobs on your pull request 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.

RFC: DTensor Support for Pipeline Parallelism Stages

5 participants