Skip to content

[checkpoint] Preserve registered effects in SAC - #196956

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

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

Conversation

@sanketpurandare

@sanketpurandare sanketpurandare commented Sep 14, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

Selective activation checkpointing can replay an ordered-effect operation when an eager policy recomputes it. That policy takes precedence over the generic AOT partitioner safeguard, so the side effect may execute once in forward and again during backward.

Cache non-aliasing ordered effects that are valid SAC cache boundaries whenever the eager policy does not explicitly require recomputation. This includes CPU-offload policies: eager CPU offload remains unimplemented, but those policies promise to save rather than replay. Explicit MUST_RECOMPUTE remains authoritative in eager mode.

AOTAutograd cannot safely move a forward effect into backward after functionalization has established the two effect-token chains. Reject compiled MUST_RECOMPUTE effects at partition time with an actionable error instead of producing a saved None token and failing in the autograd runtime wrapper.

Keep actual save policies on the cheap path. For policies that would otherwise replay an operation, the registry lookup precedes the schema alias walk. Raw c10d launches remain excluded because they mutate inputs and return asynchronous Work handles, so their return value is not a valid cache boundary; functional collectives remain the supported graph boundary.

Test Plan:

  • python test/test_autograd.py TestSelectiveActivationCheckpoint -v
  • python test/dynamo/test_activation_checkpointing.py -k selective_checkpoint_preserves_registered_effect -v
  • python test/functorch/test_aotdispatch.py -k force_save_effectful_ops -v
  • lintrunner --config=.lintrunner.toml torch/_higher_order_ops/effects.py torch/utils/checkpoint.py torch/_functorch/partitioners.py test/test_autograd.py test/dynamo/test_activation_checkpointing.py

AI assistance disclosure:

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

cc @ezyang @gchanan @voznesenskym @penguinwu @EikanWang @jgong5 @Guobing-Chen @XiaobingSuper @zhuhaozhe @blzheng @wenzhe-nrv @jiayisunx @kadeng @chauhang @amjames @jataylo @azahed98

[ghstack-poisoned]
@pytorch-bot

pytorch-bot Bot commented Sep 14, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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:

✅ You can merge normally! (2 Unrelated Failures)

As of commit 1a333d3 with merge base 38e2a2e (image):

UNSTABLE - The following jobs are marked as unstable, possibly due to flakiness on trunk:

This comment was automatically generated by Dr. CI and updates every 15 minutes.

@pytorch-bot pytorch-bot Bot added ciflow/inductor ciflow/torchtitan Run TorchTitan integration tests module: dynamo labels Sep 14, 2026
@pytorch-bot

pytorch-bot Bot commented Sep 14, 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.

[ghstack-poisoned]
sanketpurandare added a commit that referenced this pull request Sep 14, 2026
Selective activation checkpointing must not replay operators with registered ordered effects, even when the user policy requests recomputation. Override the policy for cacheable effectful operators so eager and compiled SAC retain the original output.

Raw c10d launches remain outside this rule because they return asynchronous Work handles and mutate separately allocated outputs. Their enclosing functional collective is the valid cache boundary.

Test Plan:
- `python test/test_autograd.py TestSelectiveActivationCheckpoint`
- `python test/dynamo/test_activation_checkpointing.py -k test_compile_selective_checkpoint_preserves_registered_effect`
- `lintrunner --config=.lintrunner.toml torch/utils/checkpoint.py test/test_autograd.py test/dynamo/test_activation_checkpointing.py`


ghstack-source-id: 207d817
Pull-Request: #196956
[ghstack-poisoned]
sanketpurandare added a commit that referenced this pull request Sep 14, 2026
Selective activation checkpointing must not replay operators with registered ordered effects, even when the user policy requests recomputation. Override the policy for cacheable effectful operators so eager and compiled SAC retain the original output.

Raw c10d launches remain outside this rule because they return asynchronous Work handles and mutate separately allocated outputs. Their enclosing functional collective is the valid cache boundary.

Test Plan:
- `python test/test_autograd.py TestSelectiveActivationCheckpoint`
- `python test/dynamo/test_activation_checkpointing.py -k test_compile_selective_checkpoint_preserves_registered_effect`
- `lintrunner --config=.lintrunner.toml torch/utils/checkpoint.py test/test_autograd.py test/dynamo/test_activation_checkpointing.py`

ghstack-source-id: 540618e
Pull Request resolved: #196956
[ghstack-poisoned]
sanketpurandare added a commit that referenced this pull request Sep 14, 2026
Selective activation checkpointing must not replay operators with registered ordered effects, even when the user policy requests recomputation. Override the policy for cacheable effectful operators so eager and compiled SAC retain the original output.

Raw c10d launches remain outside this rule because they return asynchronous Work handles and mutate separately allocated outputs. Their enclosing functional collective is the valid cache boundary.

Test Plan:
- `python test/test_autograd.py TestSelectiveActivationCheckpoint`
- `python test/dynamo/test_activation_checkpointing.py -k test_compile_selective_checkpoint_preserves_registered_effect`
- `lintrunner --config=.lintrunner.toml torch/utils/checkpoint.py test/test_autograd.py test/dynamo/test_activation_checkpointing.py`

ghstack-source-id: 7d2a621
Pull Request resolved: #196956
@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 12m 21s —— View job


The core fix is right and fills a real gap, but the c10d carve-out is a name-based hack whose stated rationale isn't what the code actually implements, the override is broader than it needs to be (it also swallows MUST_CPU_OFFLOAD and runs a schema-walking lookup on every dispatched op), and the test for the carve-out is tautological while the default PREFER_RECOMPUTE path — the one most users hit — is untested.

Full review
  • Read PR diff and surrounding context in torch/utils/checkpoint.py
  • Trace has_effects / EffectHolder semantics to see which ops are actually covered
  • Cross-check against force_save_effectful_ops in the partitioner
  • Assess test coverage / redundancy / slop
  • Post review

Summary of the change

_CachingTorchDispatchMode.__torch_dispatch__ now overrides the user policy to MUST_SAVE for any op where has_effects(op) and op.namespace != "c10d". That is the correct shape: _CachedTorchDispatchMode will then return the cached value instead of replaying, and it composes correctly with the partitioner, since force_save_effectful_ops (torch/_functorch/partitioners.py:2388) is gated on not must_recompute(node) and therefore defers to a SAC-supplied MUST_RECOMPUTE. Before this PR a user policy of MUST_RECOMPUTE would suppress the partitioner's protection and the effect would be replayed. So the compile-side change is not redundant with the partitioner — worth stating in the commit message, since it's the non-obvious part.


1. The docstring describes behavior the code does not implement

Raw c10d launches return an asynchronous Work handle and mutate separately
allocated outputs. Their enclosing functional collective is the valid cache
boundary.

_c10d_functional::* ops have no ScriptObject arguments, so EffectHolder._set_default_effect (torch/_library/effects.py:56-62) never marks them effectful, and has_effects is False for them. Nothing in this file saves the enclosing functional collective. The second sentence reads as a claim about what the code does; it is actually a claim about what the partitioner does for _c10d_functional (partitioners.py:2358-2364), via a completely different mechanism. Please either drop it or say explicitly "handled separately by mark_leaf_tensor_outputs in the partitioner; not covered here."

2. The carve-out is silently inconsistent between eager and compile

force_save_effectful_ops has no c10d exclusion. So for a raw c10d::allreduce_ under compile with a save-ish policy, the partitioner force-saves the with_effects outputs; under eager, this PR's helper declines to. The two now encode "effectful ops must be saved" with different exception lists. If the c10d exclusion is genuinely load-bearing it belongs in a shared predicate (e.g. exported from torch/_higher_order_ops/effects.py) that both sites consult, not duplicated-with-a-difference.

3. Overriding every policy is broader than needed, and costs a lookup per op

if _is_cacheable_effect(func):
    policy = CheckpointPolicy.MUST_SAVE

Two problems:

  • It clobbers MUST_CPU_OFFLOAD / PREFER_CPU_OFFLOAD. Offloading is entirely compatible with "do not replay" — it isn't recomputation. Silently downgrading it to MUST_SAVE is a policy decision nobody asked for.
  • has_effects → _get_effect → simple_registry.singleton.find(qualname) constructs a SimpleOperatorEntry on miss, and EffectHolder.__init__ calls _get_operation_overload, _get_schema, and walks every schema argument. That is memoized in _data after first sight, but _get_op_qualname + dict lookup still runs for every op dispatched inside every SAC region, in the overwhelmingly common case where the op has no effects and the policy was already a save policy.

Gate on the only case that matters:

if policy in (CheckpointPolicy.MUST_RECOMPUTE, CheckpointPolicy.PREFER_RECOMPUTE) and _is_cacheable_effect(func):
    policy = CheckpointPolicy.MUST_SAVE

Cheap enum check first, expensive registry walk only when it can change the answer, and offload policies are left alone.

Fix this →

4. Dead defensiveness in the predicate

has_effects already returns False unless op is an OpOverload or HigherOrderOperator, and both types have a .namespace attribute. The getattr(op, "namespace", None) default can never be taken; write op.namespace != "c10d".

5. A silent policy override with no user-visible trace

A user writes MUST_RECOMPUTE and gets a save, with no warning and no documentation. CheckpointPolicy.MUST_RECOMPUTE's docstring (checkpoint.py:1509) and the create_selective_checkpoint_contexts docstring both still promise unconditional recomputation. At minimum add a sentence to the CheckpointPolicy docstring: ops with registered ordered effects are always saved regardless of policy. Users debugging "why is my SAC memory higher than my policy implies" have no way to discover this today.

6. Undiscussed coverage gap: mutating effectful ops are not protected

has_effects requires not has_aliasing(op). A custom op declared with mutates_args=(...) gets (a!) annotations in its schema, so has_aliasing is True and has_effects is False — meaning an effectful op that mutates its input still gets replayed, double-applying the side effect. That is arguably the worse failure mode than the one this PR fixes. It's fine to leave out of scope, but the PR description asserts a general rule ("must not replay operators with registered ordered effects") that the implementation does not deliver. Say so.

Relatedly: raw c10d::allreduce_ slips past has_aliasing only because its schema doesn't declare the in-place mutation. So the explicit c10d exclusion and the implicit aliasing exclusion are covering the same conceptual case through two unrelated accidents.

7. Possible retain_graph regression — worth a test

_RECOMPUTE storage entries are re-runnable across multiple backwards; a saved entry is set to _CONSUMED (checkpoint.py:1741) and a second backward raises "Trying to backward an extra time." A region that was previously entirely recompute-policy and therefore survived retain_graph=True will now error the moment it contains one effectful op. I couldn't run this to confirm, but if it reproduces it's a user-visible BC break that deserves either a test pinning the behavior or a note.

8. Test feedback

test_raw_c10d_launch_is_not_a_cacheable_effect is tautological and fragile. It asserts _is_cacheable_effect(c10d.alltoall_.default) is False, which restates namespace != "c10d" in different words. It would still pass if has_effects stopped returning True for c10d ops, at which point it silently stops testing the carve-out. Pin both halves:

self.assertTrue(has_effects(torch.ops.c10d.alltoall_.default))
self.assertFalse(_is_cacheable_effect(torch.ops.c10d.alltoall_.default))

It also touches torch.ops.c10d with no distributed guard — on a USE_DISTRIBUTED=0 build that namespace doesn't exist. It's in TestSelectiveActivationCheckpoint, which otherwise has no distributed dependency.

Missing the case users actually hit. Both behavioral tests use MUST_RECOMPUTE. The default SAC policy is PREFER_RECOMPUTE, and _policy_from_bool(False) produces it — that's the path most real policy functions land on, and it's untested here.

Also untested: an effectful op with no tensor output (the aten::_print / _linalg_check_errors shape, where tree_map(wrap, None) wraps a None leaf), and an effectful op with multiple outputs.

The two behavioral tests are near-identical ~35-line copies. The eager/compile split is legitimate, but the op definition, autograd registration, effect registration, and assertions could come from one helper; only the library name, register_fake, and the torch.compile wrapper genuinely differ.

Slop:

  • call_count = [0] — use a local int plus nonlocal in the closure.
  • lambda _ctx, _op, *args, **kwargs: (CheckpointPolicy.MUST_RECOMPUTE) — redundant parens.
  • early_stop=False appears in both tests with no explanation. If it's load-bearing, a one-line comment saying why; if it isn't, drop it and test the default (True), which is what users run.
  • The eager test defines recompute_all as a named function while the compile test inlines a lambda for the same thing — pick one.

9. Import placement

from torch._higher_order_ops.effects import has_effects at module top of checkpoint.py pulls in _higher_order_ops.print, torchbind, schema, and fx.experimental.proxy_tensor at checkpoint import time. Neighboring code in this file (_sac_storage_key, checkpoint.py:1571) deliberately uses function-local imports for exactly this kind of dependency. Moving it inside _is_cacheable_effect would match the local convention and sidestep cycle risk.

10. Housekeeping

The bot is still asking for a release notes: label. Given item 5 (a documented policy silently overridden), this is arguably user-facing rather than topic: not user facing.


Suggested minimal diff

def _is_cacheable_effect(op) -> bool:
    """Whether SAC can cache an effectful op's output instead of replaying it.

    Raw c10d launches are excluded: they return an asynchronous Work handle and
    mutate separately allocated outputs, so the cached value is meaningless.
    (The _c10d_functional wrappers are not effectful and are handled by the
    partitioner's mark_leaf_tensor_outputs.)
    """
    from torch._higher_order_ops.effects import has_effects
    return has_effects(op) and op.namespace != "c10d"
if policy in (CheckpointPolicy.MUST_RECOMPUTE, CheckpointPolicy.PREFER_RECOMPUTE) and _is_cacheable_effect(func):
    policy = CheckpointPolicy.MUST_SAVE

Not verified

I did not build or run the test suite in this environment, so items 7 (retain_graph) and the None-output pytree behavior in item 8 are reasoned from the source rather than observed.

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

sanketpurandare added a commit that referenced this pull request Sep 15, 2026
Selective activation checkpointing can replay a custom operator even when the
operator has a registered ordered effect. A user policy requesting recompute
takes precedence over the generic AOT partitioner's effect safeguard, so the
side effect may execute once in forward and again during backward.

For non-aliasing registered effects that are valid SAC cache boundaries,
override only recompute policies at the SAC dispatch boundary and cache the
forward result. Save and CPU-offload policies remain unchanged, and their common
path avoids the effects-registry lookup. Raw c10d launches remain excluded
because they mutate separately allocated outputs and return asynchronous Work
handles; functional collectives remain the valid graph-level cache boundary.

Mutating or aliasing custom operators remain outside the existing with-effects
contract.

Test Plan:

```bash
python test/test_autograd.py TestSelectiveActivationCheckpoint
python test/dynamo/test_activation_checkpointing.py ActivationCheckpointingViaTagsTestsCUDA.test_selective_checkpoint_preserves_registered_effect_cuda
```

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

ghstack-source-id: f11acad
Pull Request resolved: #196956
@sanketpurandare

Copy link
Copy Markdown
Contributor Author

@claude Narrowed the override to MUST_RECOMPUTE and PREFER_RECOMPUTE, so save and CPU-offload policies bypass both the override and effect lookup. The effects import is local, and the public contract now covers registered non-aliasing effects that are valid cache boundaries. Raw c10d launches remain excluded for the concrete reason that they mutate separate storage and return asynchronous Work; the test first proves they are registered as effectful and then proves they are not cacheable at this boundary. One shared behavioral helper covers eager and compiled execution under default preferred and mandatory recomputation, with correct gradients and exactly one effect execution. The full 17-test SAC class and compiled CUDA test pass.

@sanketpurandare
sanketpurandare marked this pull request as ready for review September 15, 2026 06:49
@claude

claude Bot commented Sep 15, 2026 •

Copy link
Copy Markdown

Claude finished @sanketpurandare's task in 22m 2s —— View job


Most of my previous points are addressed, but the narrowing to only MUST_RECOMPUTE/PREFER_RECOMPUTE opens a real hole: eager SAC does not implement CPU offload — checkpoint.py:1623 sends offload policies down the _RECOMPUTE branch — so an effectful op under MUST_CPU_OFFLOAD is still replayed in backward, and the new test_effect_lookup_only_for_recompute_policies pins that as intended. My earlier suggestion was wrong on this point; keying the override off "not a save policy" gets the cheap-check-first property without the hole.

Full review
  • Re-read diff against origin/gh/sanketpurandare/15/base
  • Verify the narrowed condition against the actual save-vs-replay branch in _CachingTorchDispatchMode
  • Re-check the c10d test and docstring claims
  • Check test placement / where the new tests actually run
  • Post review

What is now correct

  • The effects import is function-local in _is_cacheable_effect (checkpoint.py:1531), so checkpoint import time is unchanged. Good.
  • getattr(op, "namespace", None) is gone; op.namespace is used directly. Good.
  • The CheckpointPolicy note (checkpoint.py:1505-1508) now documents the override and scopes it to non-aliasing registered effects, which matches what has_effects actually gates on. Good.
  • _is_cacheable_effect's docstring no longer claims this file handles functional collectives, and correctly attributes that to the partitioner. Good.
  • test_raw_c10d_launch_is_not_a_cacheable_effect now pins both halves (has_effects true, _is_cacheable_effect false) and is guarded on torch.distributed.is_available(). That fixes the tautology. Good.
  • The compile-side interaction still holds: policy is written into node.meta["recompute"], must_recompute (partitioners.py:176-180) only matches the two recompute values, so force_save_effectful_ops no longer skips the node.

1. The narrowing reintroduces the bug for CPU-offload policies (eager only)

This is the one thing I'd block on, and it's my fault for suggesting the narrow gate without checking what eager actually does with offload.

CheckpointPolicy's docstring promises {MUST,PREFER}_CPU_OFFLOAD means "saved during the forward pass, offloaded to CPU". But eager SAC never implements that. The only branch that decides save-vs-replay is:

# checkpoint.py:1623
if policy in (CheckpointPolicy.MUST_SAVE, CheckpointPolicy.PREFER_SAVE) or is_compiling:
    ...
    self.storage[key][idx] = tree_map(wrap, out)
else:
    self.storage[key][idx] = _RECOMPUTE

CPU_OFFLOAD is not in that tuple, so in eager it lands on _RECOMPUTE, and _CachedTorchDispatchMode re-invokes func in backward (checkpoint.py:1717-1719). CPU_OFFLOAD appears nowhere else in the file — grep for it hits only the enum and its docstring. So today, eager + MUST_CPU_OFFLOAD + effectful op = the exact double-execution this PR exists to prevent. Before this revision the broad override caught it; now it doesn't.

Under torch.compile this is fine (is_compiling short-circuits, and the partitioner's must_recompute doesn't match offload), which is why an eager/compile divergence hides here rather than showing up as a test failure.

The fix keeps the cheap-enum-check-first property you wanted and keys the override off the same predicate that actually decides replay:

_SAVE_POLICIES = (CheckpointPolicy.MUST_SAVE, CheckpointPolicy.PREFER_SAVE)
...
if policy not in _SAVE_POLICIES and _is_cacheable_effect(func):
    policy = CheckpointPolicy.MUST_SAVE

Save policies (the common case) still never pay the registry lookup, _SAVE_POLICIES can be reused at line 1623 so the two checks can't drift, and it collapses the awkward multi-line if into one line. It also makes the new CheckpointPolicy note ("always saves ... even when the policy requests recomputation") true unconditionally rather than true-except-for-offload.

Fix this →

2. test_effect_lookup_only_for_recompute_policies locks in the hole and tests an implementation detail

with unittest.mock.patch(
    "torch.utils.checkpoint._is_cacheable_effect",
    side_effect=AssertionError("unexpected effect lookup"),
):

Two problems beyond item 1:

  • It asserts the absence of a function call, not a behavior. Any refactor that computes the predicate before the enum check fails this test while behavior is identical. That's a brittle pin on a micro-optimization.
  • Because it includes the two offload policies, it converts item 1 from an oversight into an asserted invariant. If you take the _SAVE_POLICIES fix, this test must shrink to MUST_SAVE/PREFER_SAVE.

If the goal is "the common path doesn't pay for the lookup", MUST_SAVE/PREFER_SAVE is the whole claim; the offload rows add nothing but the wrong guarantee.

3. All behavioral coverage for this fix now runs only on GPU CI

ActivationCheckpointingViaTagsTests is fed to instantiate_device_type_tests(..., except_for="cpu", allow_xpu=True) (test_activation_checkpointing.py:3592), which deletes the generic class from module scope and deletes the generic methods, leaving only ...TestsCUDA / ...TestsXPU variants. test_selective_checkpoint_preserves_registered_effect takes no device parameter and runs entirely on CPU tensors (torch.randn(3)), so it is a CPU test that will never be collected on a CPU-only run — consistent with your test plan naming ...TestsCUDA...test_..._cuda.

Combined with dropping the eager behavioral test from test_autograd.py, the net effect of this revision is that TestSelectiveActivationCheckpoint retains only two whitebox tests (a mock-based call-count assertion and a predicate assertion), and the only test that actually exercises "effect runs once, gradient is right" needs a GPU.

Suggest splitting rather than sharing: keep the eager case in TestSelectiveActivationCheckpoint (device-agnostic, runs in every CPU CI job) and keep only the torch.compile case in the dynamo file. The duplication is ~10 lines of op definition; the coverage difference is that the eager path gets tested at all on CPU shards. If you'd rather keep one helper, it needs to live somewhere that isn't device-instantiated.

4. Still unaddressed from the last round: retain_graph

An SAC region that was previously all-recompute survives multiple backwards, because _RECOMPUTE entries are re-runnable. A force-saved entry becomes _CONSUMED (checkpoint.py:1721) and the second backward raises "Trying to backward an extra time". So adding one effectful op to an otherwise recompute-only region now turns a working retain_graph=True flow into an error. That's probably the only defensible semantics (you cannot replay the effect either), but it is a user-visible behavior change with no test and no mention in the CheckpointPolicy note. One sentence in the note, or a test pinning the error, would settle it.

5. Minor

  • import itertools was added to the dynamo test file just for one itertools.product over 2x2. Nested for loops read the same and avoid touching the import block.
  • (False, CheckpointPolicy.MUST_RECOMPUTE) conflates two things: False exercises both the _policy_from_bool BC path and PREFER_RECOMPUTE. Fine as-is, but if the intent is "test the default policy", CheckpointPolicy.PREFER_RECOMPUTE says it directly and the bool path is a separate, already-covered concern.
  • The multi-line if policy in (...) and _is_cacheable_effect(func): with and trailing the closing paren is the kind of linter-driven split CLAUDE.md asks you to undo. The _SAVE_POLICIES constant from item 1 fixes this incidentally.
  • Release-notes label is still outstanding, and given the documented policy override I'd lean user-facing rather than topic: not user facing.

Not verified

No build available in this environment, so items 1, 3, and 4 are read from the source rather than executed. Item 1 in particular is worth a 10-line local repro (MUST_CPU_OFFLOAD policy + effectful op + eager backward, assert call count) before you decide whether to take the change.

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

Comment thread torch/utils/checkpoint.py Outdated
may be registered explicitly through
``torch.library._register_effectful_op`` or inferred from TorchBind
arguments. Raw c10d launches are not valid cache boundaries and remain
unsupported in recomputed SAC regions.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Can we reword this section slightly differently? Would prefer something like:

Selective checkpointing overrides ``PREFER_RECOMPUTE`` to save the outputs of
  non-aliasing operators with an ordered effect. An operator may be explicitly
  registered with an ordered effect through ``torch.library`` or inferred to have
  one from non-whitelisted TorchBind arguments. This override does not apply to
  ``MUST_RECOMPUTE`` or operators in the ``c10d`` namespace.

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.

Reworded the CheckpointPolicy section using this structure while keeping the CPU-offload fallback explicit. In eager SAC, CPU offload is not implemented and these policies otherwise record _RECOMPUTE, so the final text states that the effect-specific fallback saves the output, excludes MUST_RECOMPUTE and c10d, and explains AOTAutograd's mandatory-recompute limitation.

Comment thread torch/utils/checkpoint.py Outdated
_SAVE_POLICIES = (CheckpointPolicy.MUST_SAVE, CheckpointPolicy.PREFER_SAVE)
_EFFECT_OVERRIDE_POLICIES = (
CheckpointPolicy.PREFER_RECOMPUTE,
CheckpointPolicy.PREFER_CPU_OFFLOAD,

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.

No need to override offloading since it won't replay the effectful op again

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.

I kept the CPU-offload override because eager SAC currently does replay without it. _SAVE_POLICIES contains only MUST_SAVE and PREFER_SAVE; bypassing _is_cacheable_effect produced two executions for both PREFER_CPU_OFFLOAD and MUST_CPU_OFFLOAD, versus one with the override. The focused eager test pins one execution for both policies and two for MUST_RECOMPUTE.

isinstance(op, (torch._ops.HigherOrderOperator, torch._ops.OpOverload))
and not has_aliasing(op)
and _get_effect(op) is not None
and not has_aliasing(op)

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.

Why is the ordering for this swapped?

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.

The ordering is intentional: _is_cacheable_effect runs for replay policies on the eager hot path, and most operators have no effect. Looking up the effect first lets ordinary operators short-circuit before walking every schema argument and return for alias metadata. The diagnostic observed zero alias checks for aten.sin and one for the registered-effect operator, so I kept the ordering.

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 see, that makes sense

Selective activation checkpointing can replay an ordered-effect operation when
a preferred eager policy recomputes it. That policy takes precedence over the
generic AOT partitioner's safeguard, so the side effect may execute once in
forward and again during backward.

Cache non-aliasing ordered effects that are valid SAC cache boundaries when a
preferred recompute policy would otherwise replay them. This covers effects
registered explicitly and effects inferred from TorchBind arguments. It also
covers `PREFER_CPU_OFFLOAD`, which eager SAC currently implements as
recomputation. Mandatory policies remain authoritative, matching their public
contract that other subsystems do not override them.

Actual save policies retain the cheap path. For preferred replay policies, the
registry lookup precedes the more expensive schema alias walk. Raw c10d
launches remain excluded because they mutate inputs and return asynchronous
Work handles, so their return value is not a valid cache boundary. They may
therefore relaunch under eager recomputation; functional collectives remain the
supported graph-level boundary and are preserved by the AOT partitioner.
Mutating or aliasing custom operators remain outside the existing with-effects
contract.

Test Plan:
- `python test/test_autograd.py TestSelectiveActivationCheckpoint -v`
- `python test/dynamo/test_activation_checkpointing.py ActivationCheckpointingViaTagsTestsCUDA.test_selective_checkpoint_preserves_registered_effect_cuda -v`
- `lintrunner --config=.lintrunner.toml torch/_higher_order_ops/effects.py torch/utils/checkpoint.py test/test_autograd.py test/dynamo/test_activation_checkpointing.py`

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

[ghstack-poisoned]
@aorenste
aorenste removed their request for review September 17, 2026 15:03
Comment thread torch/utils/checkpoint.py Outdated
save additional tensors not limited to ones that are actually needed for
gradient computation.

Eager selective checkpointing overrides policies that would replay an

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.

Let's name PREFER_RECOMPUTE explicitly as an example

Comment thread torch/utils/checkpoint.py Outdated
effect. An operator may be explicitly registered with an ordered effect
through ``torch.library`` or inferred to have one from non-whitelisted
TorchBind arguments. This override does not apply to ``MUST_RECOMPUTE`` or
operators in the ``c10d`` namespace. CPU-offload policies use this fallback

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.

Don't really want to mention cpu-offload in the docs since its not actually implemented in eager. I think thats fine since the first sentence already implies this.

Comment thread torch/utils/checkpoint.py Outdated
TorchBind arguments. This override does not apply to ``MUST_RECOMPUTE`` or
operators in the ``c10d`` namespace. CPU-offload policies use this fallback
because eager SAC does not yet implement CPU offload and would otherwise
replay the operator. AOTAutograd rejects ``MUST_RECOMPUTE`` for an ordered

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.

Let's remove this last sentence on AOTAutograd as well since that's a thing internal to compile.

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

Thanks for the updates, added a few more nits on the docs. Mainly I think we want to avoid mentions of things that are not public API in the docs.

[ghstack-poisoned]
Selective activation checkpointing can replay an ordered-effect operation when an eager policy recomputes it. That policy takes precedence over the generic AOT partitioner safeguard, so the side effect may execute once in forward and again during backward.

Cache non-aliasing ordered effects that are valid SAC cache boundaries whenever the eager policy does not explicitly require recomputation. This includes CPU-offload policies: eager CPU offload remains unimplemented, but those policies promise to save rather than replay. Explicit MUST_RECOMPUTE remains authoritative in eager mode.

AOTAutograd cannot safely move a forward effect into backward after functionalization has established the two effect-token chains. Reject compiled MUST_RECOMPUTE effects at partition time with an actionable error instead of producing a saved None token and failing in the autograd runtime wrapper.

Keep actual save policies on the cheap path. For policies that would otherwise replay an operation, the registry lookup precedes the schema alias walk. Raw c10d launches remain excluded because they mutate inputs and return asynchronous Work handles, so their return value is not a valid cache boundary; functional collectives remain the supported graph boundary.

Test Plan:
- python test/test_autograd.py TestSelectiveActivationCheckpoint -v
- python test/dynamo/test_activation_checkpointing.py -k selective_checkpoint_preserves_registered_effect -v
- python test/functorch/test_aotdispatch.py -k force_save_effectful_ops -v
- lintrunner --config=.lintrunner.toml torch/_higher_order_ops/effects.py torch/utils/checkpoint.py torch/_functorch/partitioners.py test/test_autograd.py test/dynamo/test_activation_checkpointing.py

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

[ghstack-poisoned]
Selective activation checkpointing can replay an ordered-effect operation when an eager policy recomputes it. That policy takes precedence over the generic AOT partitioner safeguard, so the side effect may execute once in forward and again during backward.

Cache non-aliasing ordered effects that are valid SAC cache boundaries whenever the eager policy does not explicitly require recomputation. This includes CPU-offload policies: eager CPU offload remains unimplemented, but those policies promise to save rather than replay. Explicit MUST_RECOMPUTE remains authoritative in eager mode.

AOTAutograd cannot safely move a forward effect into backward after functionalization has established the two effect-token chains. Reject compiled MUST_RECOMPUTE effects at partition time with an actionable error instead of producing a saved None token and failing in the autograd runtime wrapper.

Keep actual save policies on the cheap path. For policies that would otherwise replay an operation, the registry lookup precedes the schema alias walk. Raw c10d launches remain excluded because they mutate inputs and return asynchronous Work handles, so their return value is not a valid cache boundary; functional collectives remain the supported graph boundary.

Test Plan:
- python test/test_autograd.py TestSelectiveActivationCheckpoint -v
- python test/dynamo/test_activation_checkpointing.py -k selective_checkpoint_preserves_registered_effect -v
- python test/functorch/test_aotdispatch.py -k force_save_effectful_ops -v
- lintrunner --config=.lintrunner.toml torch/_higher_order_ops/effects.py torch/utils/checkpoint.py torch/_functorch/partitioners.py test/test_autograd.py test/dynamo/test_activation_checkpointing.py

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

[ghstack-poisoned]
Selective activation checkpointing can replay an ordered-effect operation when an eager policy recomputes it. That policy takes precedence over the generic AOT partitioner safeguard, so the side effect may execute once in forward and again during backward.

Cache non-aliasing ordered effects that are valid SAC cache boundaries whenever the eager policy does not explicitly require recomputation. This includes CPU-offload policies: eager CPU offload remains unimplemented, but those policies promise to save rather than replay. Explicit MUST_RECOMPUTE remains authoritative in eager mode.

AOTAutograd cannot safely move a forward effect into backward after functionalization has established the two effect-token chains. Reject compiled MUST_RECOMPUTE effects at partition time with an actionable error instead of producing a saved None token and failing in the autograd runtime wrapper.

Keep actual save policies on the cheap path. For policies that would otherwise replay an operation, the registry lookup precedes the schema alias walk. Raw c10d launches remain excluded because they mutate inputs and return asynchronous Work handles, so their return value is not a valid cache boundary; functional collectives remain the supported graph boundary.

Test Plan:
- python test/test_autograd.py TestSelectiveActivationCheckpoint -v
- python test/dynamo/test_activation_checkpointing.py -k selective_checkpoint_preserves_registered_effect -v
- python test/functorch/test_aotdispatch.py -k force_save_effectful_ops -v
- lintrunner --config=.lintrunner.toml torch/_higher_order_ops/effects.py torch/utils/checkpoint.py torch/_functorch/partitioners.py test/test_autograd.py test/dynamo/test_activation_checkpointing.py

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

[ghstack-poisoned]
Selective activation checkpointing can replay an ordered-effect operation when an eager policy recomputes it. That policy takes precedence over the generic AOT partitioner safeguard, so the side effect may execute once in forward and again during backward.

Cache non-aliasing ordered effects that are valid SAC cache boundaries whenever the eager policy does not explicitly require recomputation. This includes CPU-offload policies: eager CPU offload remains unimplemented, but those policies promise to save rather than replay. Explicit MUST_RECOMPUTE remains authoritative in eager mode.

AOTAutograd cannot safely move a forward effect into backward after functionalization has established the two effect-token chains. Reject compiled MUST_RECOMPUTE effects at partition time with an actionable error instead of producing a saved None token and failing in the autograd runtime wrapper.

Keep actual save policies on the cheap path. For policies that would otherwise replay an operation, the registry lookup precedes the schema alias walk. Raw c10d launches remain excluded because they mutate inputs and return asynchronous Work handles, so their return value is not a valid cache boundary; functional collectives remain the supported graph boundary.

Test Plan:
- python test/test_autograd.py TestSelectiveActivationCheckpoint -v
- python test/dynamo/test_activation_checkpointing.py -k selective_checkpoint_preserves_registered_effect -v
- python test/functorch/test_aotdispatch.py -k force_save_effectful_ops -v
- lintrunner --config=.lintrunner.toml torch/_higher_order_ops/effects.py torch/utils/checkpoint.py torch/_functorch/partitioners.py test/test_autograd.py test/dynamo/test_activation_checkpointing.py

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

Selective activation checkpointing can replay an ordered-effect operation when an eager policy recomputes it. That policy takes precedence over the generic AOT partitioner safeguard, so the side effect may execute once in forward and again during backward.

Cache non-aliasing ordered effects that are valid SAC cache boundaries whenever the eager policy does not explicitly require recomputation. This includes CPU-offload policies: eager CPU offload remains unimplemented, but those policies promise to save rather than replay. Explicit MUST_RECOMPUTE remains authoritative in eager mode.

AOTAutograd cannot safely move a forward effect into backward after functionalization has established the two effect-token chains. Reject compiled MUST_RECOMPUTE effects at partition time with an actionable error instead of producing a saved None token and failing in the autograd runtime wrapper.

Keep actual save policies on the cheap path. For policies that would otherwise replay an operation, the registry lookup precedes the schema alias walk. Raw c10d launches remain excluded because they mutate inputs and return asynchronous Work handles, so their return value is not a valid cache boundary; functional collectives remain the supported graph boundary.

Test Plan:
- python test/test_autograd.py TestSelectiveActivationCheckpoint -v
- python test/dynamo/test_activation_checkpointing.py -k selective_checkpoint_preserves_registered_effect -v
- python test/functorch/test_aotdispatch.py -k force_save_effectful_ops -v
- lintrunner --config=.lintrunner.toml torch/_higher_order_ops/effects.py torch/utils/checkpoint.py torch/_functorch/partitioners.py test/test_autograd.py test/dynamo/test_activation_checkpointing.py

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
## 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.
Pull Request resolved: #196462
Approved by: https://github.com/SherlockNoMad
ghstack dependencies: #196460, #196461, #196956
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/15/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/inductor ciflow/torchtitan Run TorchTitan integration tests Merged module: bc-breaking Related to a BC-breaking change module: dynamo topic: bc breaking topic category

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants