Skip to content

[flop_counter] Fix packed attention backward with mixed head dimensions - #196461

Closed
sanketpurandare wants to merge 12 commits into
gh/sanketpurandare/5/basefrom
gh/sanketpurandare/5/head
Closed

sanketpurandare wants to merge 12 commits into
gh/sanketpurandare/5/basefrom
gh/sanketpurandare/5/head

Conversation

@sanketpurandare

@sanketpurandare sanketpurandare commented Sep 9, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

Packed flash- and efficient-attention backward expand the output gradient using
the value-head dimension, which can differ from the query/key-head dimension
for MLA. Propagate that dimension through both packed-sequence FLOP formulas
and report the actual and expected shapes when validation fails.

This changes FLOP accounting only. It does not change attention kernels, tensor
shapes, dispatch, or model execution.

Tests parameterize the shared mixed-dimension contract over flash and efficient
attention, pin the literal backward FLOP count, and exercise the shape
diagnostic for both layouts.

Test Plan:

  • python test/test_flop_counter.py -k nested_attn_backward_flops_with_unequal_qk_value_dims -v
  • python test/test_flop_counter.py TestFlopCounter -v
  • lintrunner --config=.lintrunner.toml torch/utils/flop_counter.py test/test_flop_counter.py

AI assistance disclosure:

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

[ghstack-poisoned]
@pytorch-bot

pytorch-bot Bot commented Sep 9, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

❗ 1 Active SEVs

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

✅ No Failures

As of commit 1ea4675 with merge base 38e2a2e (image):
💚 Looks good so far! There are no failures yet. 💚

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

@Skylion007

Copy link
Copy Markdown
Collaborator

@claude double check the flop math

@claude

claude Bot commented Sep 12, 2026 •

Copy link
Copy Markdown

Claude finished @Skylion007's task in 4m 56s —— View job


FLOP math double-check: the formula is correct ✅

  • Read PR diff
  • Verify sdpa_backward_flop_count shape usage / MLA head-dim propagation
  • Check the test's expected value and the 2 * factor
  • Report findings

Verdict: the math is right. grad_out for varlen attention is shaped like out ([total_tokens, h_q, d_v]), not like query ([total_tokens, h_q, d_q]), so propagating d_v at flop_counter.py:471-473 is the correct fix. Two adjacent nits below (one is a real gap in a sibling code path).

Derivation and detailed findings

1. The backward formula is correct for d_q != d_v

sdpa_backward_flop_count (torch/utils/flop_counter.py:603-637) sums five bmms. With b=1, query heads h_q, and bmm_flop = 2*b*m*n*k:

Step Matmul FLOPs
recompute S Q @ Kᵀ 2·h_q·s_q·s_k·d_q
dP dO @ Vᵀ 2·h_q·s_q·s_k·d_v
dV Pᵀ @ dO 2·h_q·s_k·s_q·d_v
dQ dS @ K 2·h_q·s_q·s_k·d_q
dK Qᵀ @ dS 2·h_q·s_q·s_k·d_q

Closed form: 2·b·h_q·s_q·s_k·(3·d_q + 2·d_v)

This matches the actual FlashAttention backward pass exactly (dS/dP are s_q × s_k, so only dP and dV contract over d_v; S, dQ, dK contract over d_q). The 3·d_q + 2·d_v split is the whole point of the fix — before it, d_v was silently replaced by d_q, which would have overcounted by 2·b·h_q·s_q·s_k·(d_q − d_v) had the assertion not fired first.

Using h_q (not h_kv) for the dV bmm is also correct under GQA: Pᵀ @ dO is computed per query head and then reduced into the h_kv KV heads, so there are h_q bmms. (Unchanged by this PR.)

2. Test numbers check out

Test shapes: total_tokens=16, offsets is a 3-element meta tensor → _offsets_to_lengths returns [8, 8] (2 sequences of max_q=max_k=8), consistent with 16 = 2 × 8. So the 2 * factor is right.

Per sequence: 2·1·4·8·8·(3·192 + 2·128) = 512 · 832 = 425,984 → total 851,968.

The test also genuinely regresses: pre-PR, grad_out.shape (16,4,128) != query.shape (16,4,192) raised AssertionError, so it fails without the fix. d_q=192 / d_v=128 are also the real MLA training dims, so the shapes are well chosen.

One weakness: expected is computed by calling sdpa_backward_flop_count with hand-written shapes, so the test validates shape propagation (which is the fix) but is tautological w.r.t. the formula itself — a formula change in sdpa_backward_flop_count would silently keep this test green. Consider additionally pinning the literal with self.assertExpectedInline(str(actual), """851968"""), matching the style of test_varlen_attn_flops at test_flop_counter.py:1351. Fix this →

3. The identical bug still exists in the efficient-attention nested path

_unpack_efficient_attention_nested_shapes has the exact same two lines that were just fixed in the flash path:

  • flop_counter.py:510 — if grad_out is not None and grad_out.shape != query.shape:
  • flop_counter.py:528 — new_grad_out_shape = new_query_shape if grad_out is not None else None

So _efficient_attention_backward_flop (flop_counter.py:685) will still raise AssertionError for nested/varlen inputs whenever d_v != d_q. d_v is already unpacked at line 514 and currently unused for grad_out, so the fix is the same two-line change. Not a blocker for this PR's stated scope, but it leaves the two paths inconsistent. Fix this →

4. Minor nits

  • Error message drops the shapes. The new AssertionError at flop_counter.py:452-455 describes the constraint but doesn't print actual vs. expected, unlike its neighbours (e.g. sdpa_flop_count at line 380 interpolates q=/k=/v=). Adding got {tuple(grad_out.shape)}, expected {expected_grad_out_shape} would make failures self-diagnosing.
  • Line splitting vs. repo style. CLAUDE.md asks to keep code on one line where it fits. Both new blocks fit comfortably under the limit:
    expected_grad_out_shape = (query.shape[0], query.shape[1], value.shape[2])
    ...
    new_grad_out_shape = (1, h_q, seq_q_len, d_v) if grad_out is not None else None
  • Import consistency. sdpa_backward_flop_count is imported at the top of the test file (test_flop_counter.py:24), but _varlen_attn_backward_flop uses a function-local import. Fold it into the top-level import.

I was unable to execute the test to confirm the number empirically (no built PyTorch in this checkout), so 851968 above is from hand-evaluating bmm_flop; please confirm with python test/test_flop_counter.py -k varlen_attn_flops_with_unequal_qk_value_dims before pinning it.
| Branch: gh/sanketpurandare/5/head

@Skylion007

Copy link
Copy Markdown
Collaborator

_unpack_efficient_attention_nested_shapes has the exact same two lines that were just fixed in the flash path:

flop_counter.py:510 — if grad_out is not None and grad_out.shape != query.shape:
flop_counter.py:528 — new_grad_out_shape = new_query_shape if grad_out is not None else None
So _efficient_attention_backward_flop (flop_counter.py:685) will still raise AssertionError for nested/varlen inputs whenever d_v != d_q. d_v is already unpacked at line 514 and currently unused for grad_out, so the fix is the same two-line change. Not a blocker for this PR's stated scope, but it leaves the two paths inconsistent.

[ghstack-poisoned]
Comment thread torch/utils/flop_counter.py Outdated

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.

same problem here?

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.

Applied the same value-head-dimension correction to _unpack_efficient_attention_nested_shapes and added unequal-d_q/d_v coverage for its 4-D layout. The flash and efficient helpers now enforce the same conceptual grad_out contract.

Comment thread torch/utils/flop_counter.py Outdated
raise AssertionError(
"sdpa_flop_count: grad_out must match query tokens/heads and "
"value head dimension when provided"
)

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.

nit: might be a bit cleaner to move this check below the unpacks

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.

Moved the grad_out validation below the query/key/value unpacks so it reuses h_q and d_v, and included the actual and expected shapes in the assertion message.

@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 37s —— View job


The FLOP math is correct and the assertion change is a safe relaxation, but the identical bug is left unfixed in the sibling efficient-attention path (already flagged by two reviewers), and the new test is tautological with the formula it means to protect — Request Changes.

Full review of #196461

PR Review: #196461

Summary

Propagates the value head dimension d_v (instead of d_q) into the grad_out shape that _unpack_flash_attention_nested_shapes synthesizes for packed-sequence backward FLOP accounting, so MLA-style varlen attention (d_q=192, d_v=128) no longer trips an assertion. The core change is correct — torch/nn/attention/varlen.py:334 builds the forward output as (*query.shape[:-1], value.size(-1)), so grad_out is [T, h_q, d_v] — and the resulting 3*d_q + 2*d_v split matches the real FlashAttention backward. Problems below are in the sibling code path, the shape of the test, and code compactness.

Code Quality

  • torch/utils/flop_counter.py:446-455 — the check runs before the unpacks, forcing a 5-line tuple literal that duplicates work done 4 lines later. expected_grad_out_shape re-derives query.shape[0]/[1] and value.shape[2] immediately above the lines that bind those same values to h_q/d_v. Moving the check below the unpacks (as liangel-02 requested) collapses the entire added block to two lines, and lets the message name the actual vs. expected shape — which the current message does not, unlike its direct neighbour sdpa_flop_count at flop_counter.py:380-383, which interpolates q=/k=/v=. A failure today tells you a constraint was violated but not by how much:

    t_q, h_q, d_q = query.shape
    _, h_k, d_k = key.shape
    _, h_v, d_v = value.shape
    if grad_out is not None and grad_out.shape != (t_q, h_q, d_v):
        raise AssertionError(f"sdpa_flop_count: expected grad_out shape {(t_q, h_q, d_v)}, got {tuple(grad_out.shape)}")

    This also satisfies CLAUDE.md's "put it back on a single line" rule, which both added blocks currently violate — flop_counter.py:471-473 fits well under the limit as new_grad_out_shape = (1, h_q, seq_q_len, d_v) if grad_out is not None else None. Fix this →

  • torch/utils/flop_counter.py:822 — asymmetry with the forward, adjacent to the lines being changed. _varlen_attn_backward_flop passes cum_seq_k=cu_seq_k straight through, while _varlen_attn_forward_flop at line 771 defensively writes cum_seq_k=cu_seq_k if cu_seq_k is not None else cu_seq_q. If cu_seq_k is ever None, the backward path enters the cum_seq_q is not None branch and dies on the cum_seq_k must not be None assertion at line 461-462 rather than defaulting like the forward. The custom op's schema currently types cu_seq_k as non-optional (varlen.py:736), so this is latent rather than live — but the public varlen_attn API accepts cu_seq_k=None (varlen.py:353), so the two functions should not disagree about what None means. Low confidence that this is reachable today; flagging because it sits in the function this PR modifies.

Testing

  • test/test_flop_counter.py:1376-1382 — the expected value is computed by calling the function under test, so the assertion cannot detect a formula regression. expected is 2 * sdpa_backward_flop_count(...) with hand-written 4D shapes; actual is _varlen_attn_backward_flop(...), which internally calls the same sdpa_backward_flop_count. The test therefore validates shape propagation (the actual fix) but is tautological with respect to the arithmetic — change sdpa_backward_flop_count to 3*d_q + 3*d_v and this test stays green. Both sibling varlen tests pin the literal (test_flop_counter.py:1333 and :1351); do the same here. Hand-evaluating bmm_flop gives 2 * 425984 = 851968 (per sequence: 2*1*4*8*8*(3*192 + 2*128)), but I could not execute the test to confirm — no built PyTorch and no .venv in this checkout — so please verify before pinning. Fix this →

  • test/test_flop_counter.py:1355 — the test bypasses FlopCounterMode and the flop_registry, so it does not cover the dispatch wiring. It imports and calls the private _varlen_attn_backward_flop directly. There is direct precedent for the better shape one screen up: test_flash_attention_backward_flop_layout (test_flop_counter.py:846-881) dispatches torch.ops.aten._flash_attention_backward on device="meta" tensors inside with FlopCounterMode(), with no CUDA requirement. Driving the op through the mode instead would additionally cover the get_raw=True argument forwarding and the flop_registry[torch.ops.torch_attn._varlen_attn_backward] registration at varlen.py:875 — the parts most likely to silently break when the op signature changes. As written, a positional-argument drift in _varlen_attn_backward's schema would leave this test green.

  • test/test_flop_counter.py:1362 — the coupling between offsets, total_tokens, and max_q is invisible. offsets = torch.empty(3, ...) is a meta tensor, so _offsets_to_lengths (flop_counter.py:406-415) never reads its values and returns [max_q] * 2; the 2 * in the expected value comes from offsets.size(0) - 1, and total_tokens=16 only agrees with 2 * max_q=8 by hand-arithmetic. A reader cannot tell that torch.empty(3) is what makes the 2 * correct. One comment naming "2 sequences of 8 tokens, values unused because meta" would fix this. Relatedly, the call at lines 1364-1375 passes None, None, offsets, offsets, 8, 8 positionally — keyword arguments for out/lse/max_q/max_k would make it readable.

  • No test for the efficient-attention path, which still has the same bug. See API Design below; a mirror test belongs alongside this one.

Not redundant, for the record: I verified that no existing test in the file exercises d_v != d_q. test_sdpa threads a head_dim_v parameter but sets it to 64 alongside head_dim = 64 (test_flop_counter.py:341-342), and both uniform_config and differing_config in test_sdpa_nested_tensor set "head_dim": 64, "head_dim_v": 64 (:685, :696) — those configs only vary sequence length. So the head_dim_v plumbing in those two tests has always been dead. Wiring head_dim_v = 128 into test_sdpa's non-uniform config would be a cheaper way to get real coverage of the dense path than the parameter sitting unused.

API Design

  • torch/utils/flop_counter.py:510 and :528 — the identical defect remains in _unpack_efficient_attention_nested_shapes, leaving the two unpack helpers with contradictory contracts. These are the exact two lines this PR just fixed in the flash helper: line 510 asserts grad_out.shape != query.shape, and line 528 sets new_grad_out_shape = new_query_shape. So _efficient_attention_backward_flop (:685) still raises for nested/varlen inputs whenever d_v != d_q, and d_v is already unpacked at line 514 and simply unused for grad_out. Two reviewers have now asked for this (Skylion007, and liangel-02 inline on line 510). Two sibling functions that unpack the same conceptual thing must not disagree about what grad_out is shaped like — the fix is two lines, and skipping it means the next person to hit this files a second PR. Note the tensors are 4D here, not 3D, so it is (1, h_q, len_q, d_v) and (query.shape[0], query.shape[1], query.shape[2], value.shape[3]). Fix this →

Backward Compatibility

No concerns — the assertion is strictly relaxed. When d_v == d_q the new expected_grad_out_shape is identical to query.shape, and new_grad_out_shape is identical to new_query_shape, so every previously-passing input still passes and every previously-emitted count is unchanged. Inputs that previously raised now compute. sdpa_backward_flop_count's own validation at flop_counter.py:617 (d_v == _d4) is unchanged and still catches genuinely inconsistent shapes downstream.

Recommendation

Request Changes

Blocking: the sibling _unpack_efficient_attention_nested_shapes fix (flop_counter.py:510,528), which two reviewers have independently requested and which leaves the two helpers contradicting each other. Also fix the tautological assertion in the new test — a test whose expected value is produced by the function under test does not protect the formula it is nominally about. The compactness and error-message points are quick and worth folding into the same amend.

Worth confirming that the target configuration is actually reachable: d_q=192, d_v=128 is the only entry in _CUDNN_SM100_BACKWARD_LARGE_HEAD_DIMS (varlen.py:29), and Flash rejects d_q != d_v for backward, so this fix matters exclusively for the cuDNN varlen backend. That is a good reason to have the fix, and also a reason the test's choice of 192/128 is well-picked rather than arbitrary — a sentence to that effect in the test or commit message would save the next reader the lookup.

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

@sanketpurandare sanketpurandare changed the title [flop_counter] Fix varlen attention backward with mixed head dimensions [flop_counter] Fix packed attention backward with mixed head dimensions Sep 15, 2026
@sanketpurandare

Copy link
Copy Markdown
Contributor Author

Fixed the sibling efficient-attention nested path as well. Both unpackers now derive grad_out from the value head dimension, normalize flash inputs to (1, h_q, S_q, d_v) and efficient inputs to (B, T, h_q, d_v), and report actual and expected shapes on failure. One compact test covers both layouts with d_q=192, d_v=128 and pins the independently derived total of 851968 FLOPs.

@sanketpurandare

Copy link
Copy Markdown
Contributor Author

@claude Confirmed the closed form 2*b*h_q*S_q*S_k*(3*d_q + 2*d_v) and independently pinned 851968 FLOPs for two length-8 sequences with h_q=4, d_q=192, and d_v=128. I also fixed the sibling efficient-attention layout, moved validation below the unpacks, added actual/expected diagnostics, and moved the private helper import to the module import block. The full 36-test FLOP-counter suite passes.

@sanketpurandare

Copy link
Copy Markdown
Contributor Author

@claude Fixed both flash-varlen and efficient-attention nested layouts and replaced the tautological expectation with the literal 851968. The compact test covers the 3-D flash and 4-D efficient shapes plus invalid-shape diagnostics. Existing dispatch tests already cover registry wiring, so this test remains focused on the shape contract. I did not add the speculative cu_seq_k=None fallback because the backward operator schema is non-optional and no reachable failure was demonstrated. The full FLOP-counter suite passes.

@claude

claude Bot commented Sep 15, 2026 •

Copy link
Copy Markdown

Claude finished @sanketpurandare's task in 6m 50s —— View job


All four claims verified — the fix is complete and consistent across both unpackers. LGTM with three nits, none blocking.

Verification of #196461 (updated)
  • Read the new diff vs origin/gh/sanketpurandare/5/base
  • Verify the efficient-attention sibling fix and its 4-D shape contract
  • Re-derive the closed form and the pinned 851968
  • Check the new test's argument wiring against both op signatures
  • Attempt to run the FLOP-counter suite (blocked — see caveat)
  • Post findings

1. Closed form and 851968 — independently confirmed

Re-derived from bmm_flop (flop_counter.py:177-189) through the five bmms of sdpa_backward_flop_count (:619-635), with b=1, h_q=4, h_kv=2, s_q=s_k=8, d_q=192, d_v=128:

Step bmm FLOPs
recompute S (4,8,192)@(4,192,8) 98304
dP = dO@Vᵀ (4,8,128)@(4,128,8) 65536
dV = Pᵀ@dO (4,8,8)@(4,8,128) 65536
dQ = dS@K (4,8,8)@(4,8,192) 98304
dK = Qᵀ@dS (4,192,8)@(4,8,8) 98304

Per sequence 425984; two sequences → 851968. This equals the closed form 2·b·h_q·S_q·S_k·(3·d_q + 2·d_v) = 512·832, so the 3·d_q + 2·d_v split is exactly what the code computes — only dP and dV contract over d_v. GQA is handled correctly: all five bmms are batched over h_q, not h_kv, which matches the real kernel (Pᵀ@dO is per query head, reduced into h_kv afterwards).

_offsets_to_lengths (:413) returns [8, 8] for the meta offsets of size 3, so the 2× factor is right, and total_tokens=16 = 2·8 is self-consistent.

2. Efficient-attention sibling — correctly fixed, right layout

flop_counter.py:507-512 and :526 now mirror the flash path. The 4-D handling is correct and is not a copy-paste of the 3-D version: _efficient_attention_backward's grad_out matches out, which is (B, M, h_q, d_v) while query is (B, M, h_q, d_q) — so expected_grad_out_shape = (query.shape[0], query.shape[1], h_q, d_v) is right, and the normalized (1, h_q, len_q, d_v) matches the (1, h_q, len_q, d_q) query normalization on the adjacent line. Both helpers now agree on the same conceptual contract ("grad_out is shaped like out, not like query"), which was the blocking item from the last round and from Skylion007/liangel-02.

3. Validation moved below the unpacks, with diagnostics

liangel-02's nit is addressed at :446-454 and :504-512 — the checks now sit after the unpacks and reuse h_q/d_v, and both messages interpolate actual vs. expected, matching the house style of sdpa_flop_count at :380. tuple(grad_out.shape) on both sides also fixes a latent wart: the old grad_out.shape != query.shape compared torch.Size to torch.Size, whereas the new expected value is a plain tuple, so the explicit tuple(...) is load-bearing, not cosmetic.

4. Test — no longer tautological, and both signatures line up

assertExpectedInline(str(actual), """851968""") (test_flop_counter.py:1397) is now independent of sdpa_backward_flop_count, so a formula regression fails the test — that was the other substantive item. Pinning the same literal for both layouts is a good call: it asserts the two paths must agree, not just that each is internally consistent.

The shared positional call works because both signatures happen to align at 10 arguments — _varlen_attn_backward_flop(grad_out, q, k, v, out, lse, cu_q, cu_k, max_q, max_k) (:798) and _efficient_attention_backward_flop(grad_out, q, k, v, bias, out, cu_q, cu_k, max_q, max_k) (:684) — with slots 5-6 unused by both. That is real but fragile coupling; a one-line comment saying the 5th/6th positional slots are out/lse vs bias/out and are ignored would keep the next reader from assuming the signatures are the same API. The negative case (bad_grad_out with d=64) exercises the new diagnostic on both layouts, and the regex "grad_out has shape.*expected" matches both prefixes.

Imports are clean: sdpa_backward_flop_count is still used at :880, so nothing became dead when the local import moved into the module block at :24-29.

Remaining nits (non-blocking)

  • assertExpectedInline inside a subTest loop. Both iterations pin the same value, so this is fine today. But the two calls share one source line, so if the layouts ever diverge, --accept would try to rewrite the same site twice, and a plain failure would not name which layout broke. CLAUDE.md also asks for @parametrize over multiple inputs — that would at least give distinct test IDs in the failure output. Fix this →
  • expected_grad_out_shape still re-reads query.shape positionally (:449, :507) right after unpacking it. Binding the leading dims — t_q, h_q, d_q = query.shape / b, t_q, h_q, d_q = query.shape — makes it (t_q, h_q, d_v) and (b, t_q, h_q, d_v), which reads better and is what "move it below the unpacks" was aiming at.
  • _varlen_attn_backward_flop:820 still passes cum_seq_k=cu_seq_k bare while the forward at :769 defaults to cu_seq_q when it is None. Latent (the custom op schema types it non-optional), and pre-existing rather than introduced here, but the two functions in the same file still disagree about what None means.

Unrelated observation, unchanged by this PR: the head_dim_v plumbing in test_sdpa and test_sdpa_nested_tensor is still dead — head_dim_v = 64 at :347 and "head_dim_v": 64 at :690/:701 alongside head_dim = 64. Setting it to 128 in one non-uniform config would give the dense path the same mixed-dim coverage this PR just gave the packed paths, for nearly free.

Caveat on the "36 tests pass" claim

I could not reproduce it: there is no built PyTorch in this checkout and no .venv in the repo root or its parent, so import torch fails and I could not execute test_flop_counter.py. Everything above is from reading the source and hand-evaluating bmm_flop; the arithmetic independently lands on 851968, but the suite result is your report, not my verification.

Recommendation

Approve (modulo the CI run). Both blocking items from the previous round are resolved: the sibling helper is fixed with the correct 4-D contract, and the test now pins a literal that a formula change would break. The three nits are polish and can ride along in an amend or a follow-up.

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

@claude

claude Bot commented Sep 15, 2026 •

Copy link
Copy Markdown

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


Confirmed — all three claims check out against the current head; no blocking issues remain.

  • Re-read the final diff vs origin/gh/sanketpurandare/5/base
  • Re-derive 851968 for both layouts from the current code
  • Verify the @parametrize justification (does the file use parameterized generation?)
  • Verify the "32 tests in TestFlopCounter" count
  • Post findings
Verification of the final state (#196461)

1. 851968 holds for both layouts, and for the same reason

Traced both call paths through the code as it now stands:

test input query expected_grad_out_shape (flop_counter.py:449 / :507) normalized per-seq shapes
flash (16, 4, 192) (16, 4, 128) ✅ q (1,4,8,192), k (1,2,8,192), v (1,2,8,128), dO (1,4,8,128)
efficient (1, 16, 4, 192) (1, 16, 4, 128) ✅ identical

Both normalize to the same BHSD tuples before reaching sdpa_backward_flop_count, which is why one literal legitimately covers both — that is a property of the code, not a coincidence of the test. _offsets_to_lengths (:413) short-circuits on device.type == "meta" and returns [8, 8] from the size-3 offsets, giving the 2×.

Summing the five bmms at those shapes (2·b·h_q·s_q·s_k·(3·d_q + 2·d_v) = 512 · 832): 98304 + 65536 + 65536 + 98304 + 98304 = 425984 per sequence → 851968. Derived from bmm_flop directly, so the assertion is not tautological with sdpa_backward_flop_count.

Positional wiring is right for both signatures — _varlen_attn_backward_flop(grad_out, q, k, v, out, lse, cu_seq_q, cu_seq_k, max_q, max_k) (:798) and _efficient_attention_backward_flop(grad_out, q, k, v, bias, out, cu_seqlens_q, cu_seqlens_k, max_seqlen_q, max_seqlen_k) (:684); the two Nones land on out/lse and bias/out, both unused by the formula.

2. The @parametrize justification is factually correct — withdrawing that nit

I checked: test/test_flop_counter.py has no instantiate_parametrized_tests and no parametrize import anywhere, and none of its 3 test classes use parameterized generation. Adding the machinery for a single two-case test to satisfy a style guideline would be more churn than the guideline is worth, and since both cases pin the identical literal by construction (see §1), the shared assertExpectedInline source line cannot diverge under --accept. Reasonable call — dropping the suggestion.

3. Test count matches

32 def test_ methods in TestFlopCounter (lines 59-1358 inclusive of the new one at :1358). The earlier "36" was presumably counting the other two classes in the file; 32 is the right number for this class.

4. Remaining items, all optional and none introduced here

  • expected_grad_out_shape (:449, :507) still re-reads query.shape[0]/[1] after the unpack discarded them into _. Cosmetic.
  • flop_counter.py:513-516 (and :455-458 in the flash helper) are unreachable is None checks nested inside the is not None branch. Pre-existing in the base; they only appear near the diff because the grad_out check moved past them. Free deletion for whoever touches this next.
  • _varlen_attn_backward_flop:820 passes cum_seq_k=cu_seq_k bare while the forward at :794 defaults to cu_seq_q. Agreed unreachable given the non-optional schema — correctly left alone.
  • head_dim_v in test_sdpa (:347) and both test_sdpa_nested_tensor configs remains pinned to 64 alongside head_dim = 64, so the dense path still has no d_v != d_q coverage. Out of scope here.

Recommendation

LGTM — consistent with @fegin's approval. Both blocking items from the earlier rounds (the sibling efficient-attention helper, and the tautological expectation) are resolved, and the fix is a strict relaxation: when d_v == d_q every previously-emitted count is bit-identical.

Caveat unchanged: no built PyTorch and no .venv in this checkout, and python -c "import torch" is outside my allowed tools here, so I could not execute the suite. The 851968 above is hand-derived from bmm_flop; the 32-test pass result is your report.

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

@claude

claude Bot commented Sep 15, 2026 •

Copy link
Copy Markdown

Claude finished @sanketpurandare's task in 45s —— View job


Confirmed — final state verified, scope call agreed. LGTM.

Re-verification of the final diff (#196461)
  • Re-read the final diff vs origin/gh/sanketpurandare/5/base
  • Re-check both unpackers against their own layouts
  • Re-derive the pinned 851968 independently
  • Confirm the positional call wiring for both ops
  • Respond to the scope decision

Both unpackers, final form

query layout expected_grad_out_shape normalized grad_out correct?
flash varlen (:446-454, :467) (T, h_q, d_q) (T, h_q, d_v) (1, h_q, S_q, d_v) ✅
efficient nested (:504-512, :526) (B, M, h_q, d_q) (B, M, h_q, d_v) (1, h_q, len_q, d_v) ✅

Both checks now sit below the unpacks and reuse h_q/d_v, both messages interpolate actual vs. expected, and the tuple(grad_out.shape) on the left-hand side is load-bearing since the right-hand side is a plain tuple. The two helpers agree on one contract: grad_out is shaped like out, not like query.

851968, derived independently of the implementation

b=1, h_q=4, s_q=s_k=8, d_q=192, d_v=128 → 2·b·h_q·s_q·s_k·(3·d_q + 2·d_v) = 512 · 832 = 425984 per sequence. offsets = torch.empty(3, device="meta") short-circuits _offsets_to_lengths at flop_counter.py:413 and returns [8, 8], so ×2 → 851968. Both layouts normalize to the same (1,4,8,·) shapes, so one literal legitimately covers both — and pinning the same number for both asserts the paths agree, which is stronger than two separate literals.

Call wiring re-checked

_varlen_attn_backward_flop(grad_out, q, k, v, out, lse, cu_seq_q, cu_seq_k, max_q, max_k) (:798) and _efficient_attention_backward_flop(grad_out, q, k, v, bias, out, cu_seqlens_q, cu_seqlens_k, max_seqlen_q, max_seqlen_k) (:684) — the two Nones land on out/lse and bias/out, so offsets binds to the cumulative-sequence slots in both. Correct as written.

The negative case exercises the new diagnostic on both layouts, and "grad_out has shape.*expected" matches both prefixes.

On the scope decision

Agreed on all three deferrals:

  • Dead cum_seq_q is None / cu_seqlens_q is None guards (:455-458, :513-516) — pre-existing, present in the base, merely shifted down by your reordering. Removing them here would mix an unrelated cleanup into a bug fix.
  • Dense-SDPA head_dim_v coverage — a genuinely separate gap (that plumbing is dead in test_sdpa / test_sdpa_nested_tensor independent of this PR). Belongs in its own change.
  • cu_seq_k=None fallback — unreachable given the non-optional schema; adding a branch for it would be speculative error handling.

The @parametrize nit I raised is also fine to leave: both layouts pin the same literal, so the shared assertExpectedInline source line is not a problem today, and the file has no instantiate_parametrized_tests to hook into.

Caveat, unchanged

No built PyTorch and no .venv in this checkout, so I still cannot execute the suite — the "32 tests pass" result is your report. The 851968 above is hand-evaluated from bmm_flop and is independent of sdpa_backward_flop_count, so it corroborates the pinned literal rather than restating it.

Recommendation

LGTM. Both previously-blocking items are resolved, the fix is a strict relaxation (identical counts when d_v == d_q), and the scope is right.

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

@sanketpurandare sanketpurandare added topic: not user facing topic category module: flop counter FlopCounterMode mode labels Sep 16, 2026
@sanketpurandare

Copy link
Copy Markdown
Contributor Author

I used Codex to prepare this verification summary and reviewed it against the implementation and test results; it addresses the findings in this review: @claude No additional source change was needed after this review; the regression continues to use the existing parameterized-test infrastructure, and all 33 TestFlopCounter cases pass.

@claude

claude Bot commented Sep 16, 2026 •

Copy link
Copy Markdown

Claude finished @sanketpurandare's task in 4m 45s —— View job


Two of three claims verified exactly; the "existing parameterized-test infrastructure" wording is off — this PR introduces parametrize into the file (correctly), and the generated test IDs are unreadable. Non-blocking, still LGTM.

Verification of the final state (#196461)
  • Pull the current diff vs origin/gh/sanketpurandare/5/base
  • Check whether the test uses "existing parameterized-test infrastructure"
  • Verify the TestFlopCounter case count (33)
  • Re-verify the source fix is unchanged and still correct
  • Post findings

1. Test count: 33 is exactly right

TestFlopCounter has 32 def test_ methods (lines 61-1379). instantiate_parametrized_tests (common_utils.py:742-748) deletes the generic decorated method and substitutes one test per parameter tuple, so 32 − 1 + 2 = 33 collected cases. The claim is arithmetically consistent with the code, not just asserted.

2. The parametrize conversion is correct, but the claim about it is not

The final commit (aad02a7f..HEAD) replaced the hand-rolled cases tuple + subTest loop with @parametrize and added instantiate_parametrized_tests(TestFlopCounter) at test_flop_counter.py:1589. That is the right change and it resolves the last style nit — CLAUDE.md asks for @parametrize over multi-input loops.

But "continues to use the existing parameterized-test infrastructure" describes the wrong thing. Before this PR the file had no parametrize import and no instantiate_parametrized_tests call — this diff adds both (:18-19, :1589). The infrastructure is shared repo-wide, but within this file it is new, and it is a real (small) behavioural addition: instantiate_parametrized_tests now walks every attribute of TestFlopCounter at import time. That is fine, just worth stating accurately, since the previous round's justification for not parametrizing was precisely that the file lacked the machinery.

3. One consequence of the conversion is worth fixing: the generated test names

_formatted_str_repr (common_utils.py:854-866) only produces readable names for int/float/str/dtype/device; everything else falls through to f"{name}{idx}". Every parameter here is a function or a tuple, so the two instantiated tests are named:

test_nested_attn_backward_flops_with_unequal_qk_value_dims_backward_flop0_q_shape0_k_shape0_v_shape0_grad_shape0
test_nested_attn_backward_flops_with_unequal_qk_value_dims_backward_flop1_q_shape1_k_shape1_v_shape1_grad_shape1

The old subTest(name=...) carried flash / efficient; the new IDs carry no information at all, and a failure report will not say which layout broke — which was the main thing parametrizing was supposed to buy. subtest(..., name="flash") (common_utils.py:773) fixes it and is honoured by _get_subtest_name (:871-878):

@parametrize(
    "backward_flop,q_shape,k_shape,v_shape,grad_shape",
    [
        subtest((_varlen_attn_backward_flop, (16, 4, 192), (16, 2, 192), (16, 2, 128), (16, 4, 128)), name="flash"),
        subtest((_efficient_attention_backward_flop, (1, 16, 4, 192), (1, 16, 2, 192), (1, 16, 2, 128), (1, 16, 4, 128)), name="efficient"),
    ],
)

Fix this →

Also note the pin changed form in this commit: assertExpectedInline(str(actual), """851968""") became assertEqual(actual, 851968) (:1401). Both pin a literal, so the tautology objection stays resolved — but the sibling varlen tests at :1340 and :1358 use assertExpectedInline, and it is the only form EXPECTTEST_ACCEPT=1 can update. With subtest names the two cases would occupy distinct source lines, so assertExpectedInline would be safe to restore if you prefer file consistency. Not important either way.

4. Source fix unchanged and still correct

The only source delta since my last review is cosmetic and is the nit I raised — expected_grad_out_shape now reads from bound locals instead of re-indexing query.shape:

query layout expected_grad_out_shape (flop_counter.py:449 / :507) normalized grad_out correct?
flash varlen (t_q, h_q, d_q) (t_q, h_q, d_v) (1, h_q, seq_q_len, d_v) (:467) ✅
efficient nested (b, m, h_q, d_q) (b, m, h_q, d_v) (1, h_q, len_q, d_v) (:526) ✅

Re-derivation of the pinned literal is unchanged, and the test shapes are byte-identical to the previous round (total_tokens was inlined to 16): 2·b·h_q·s_q·s_k·(3·d_q + 2·d_v) = 512 · 832 = 425984 per sequence, ×2 sequences from the meta offsets of size 3 (_offsets_to_lengths short-circuits at :413) → 851968. Positional wiring still lines up for both signatures — _varlen_attn_backward_flop(grad_out, q, k, v, out, lse, cu_seq_q, cu_seq_k, max_q, max_k) (:798) and _efficient_attention_backward_flop(grad_out, q, k, v, bias, out, cu_seqlens_q, cu_seqlens_k, max_seqlen_q, max_seqlen_k) (:684) — and the new comment at :1387 now names those slots, which was one of my earlier asks. sdpa_backward_flop_count is still used at :882, so no import went dead.

Negative case: (*grad_shape[:-1], 64) yields (16, 4, 64) / (1, 16, 4, 64), both of which reach the new diagnostic and match "grad_out has shape.*expected" under either prefix. ✅

5. Recommendation

LGTM — consistent with @fegin's approval. The fix is a strict relaxation (identical counts when d_v == d_q), both unpackers now agree that grad_out is shaped like out, and the pinned 851968 is independently derived from bmm_flop rather than from the function under test. The only thing I would still change is the subtest naming, since unreadable test IDs partly defeat the point of the conversion that was just made.

Caveat: no built PyTorch in this checkout and python -c "import torch" is outside my allowed tools here, so I could not execute the suite — the "33 cases pass" result is your report. The 33 count and the 851968 derivation above are both from reading the source, and both agree with it.

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

…ad dimensions"

Packed flash- and efficient-attention backward expand the output gradient using
the value-head dimension, which can differ from the query/key-head dimension
for MLA. Propagate that dimension through both packed-sequence FLOP formulas
and report the actual and expected shapes when validation fails.

This changes FLOP accounting only. It does not change attention kernels, tensor
shapes, dispatch, or model execution.

Tests parameterize the shared mixed-dimension contract over flash and efficient
attention, pin the literal backward FLOP count, and exercise the shape
diagnostic for both layouts.

Test Plan:
- `python test/test_flop_counter.py -k nested_attn_backward_flops_with_unequal_qk_value_dims -v`
- `python test/test_flop_counter.py TestFlopCounter -v`
- `lintrunner --config=.lintrunner.toml torch/utils/flop_counter.py test/test_flop_counter.py`

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

[ghstack-poisoned]
[ghstack-poisoned]
…ad dimensions"

Packed flash- and efficient-attention backward expand the output gradient using
the value-head dimension, which can differ from the query/key-head dimension
for MLA. Propagate that dimension through both packed-sequence FLOP formulas
and report the actual and expected shapes when validation fails.

This changes FLOP accounting only. It does not change attention kernels, tensor
shapes, dispatch, or model execution.

Tests parameterize the shared mixed-dimension contract over flash and efficient
attention, pin the literal backward FLOP count, and exercise the shape
diagnostic for both layouts.

Test Plan:
- `python test/test_flop_counter.py -k nested_attn_backward_flops_with_unequal_qk_value_dims -v`
- `python test/test_flop_counter.py TestFlopCounter -v`
- `lintrunner --config=.lintrunner.toml torch/utils/flop_counter.py test/test_flop_counter.py`

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

[ghstack-poisoned]
…ad dimensions"

Packed flash- and efficient-attention backward expand the output gradient using
the value-head dimension, which can differ from the query/key-head dimension
for MLA. Propagate that dimension through both packed-sequence FLOP formulas
and report the actual and expected shapes when validation fails.

This changes FLOP accounting only. It does not change attention kernels, tensor
shapes, dispatch, or model execution.

Tests parameterize the shared mixed-dimension contract over flash and efficient
attention, pin the literal backward FLOP count, and exercise the shape
diagnostic for both layouts.

Test Plan:
- `python test/test_flop_counter.py -k nested_attn_backward_flops_with_unequal_qk_value_dims -v`
- `python test/test_flop_counter.py TestFlopCounter -v`
- `lintrunner --config=.lintrunner.toml torch/utils/flop_counter.py test/test_flop_counter.py`

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

[ghstack-poisoned]
…ad dimensions"

Packed flash- and efficient-attention backward expand the output gradient using
the value-head dimension, which can differ from the query/key-head dimension
for MLA. Propagate that dimension through both packed-sequence FLOP formulas
and report the actual and expected shapes when validation fails.

This changes FLOP accounting only. It does not change attention kernels, tensor
shapes, dispatch, or model execution.

Tests parameterize the shared mixed-dimension contract over flash and efficient
attention, pin the literal backward FLOP count, and exercise the shape
diagnostic for both layouts.

Test Plan:
- `python test/test_flop_counter.py -k nested_attn_backward_flops_with_unequal_qk_value_dims -v`
- `python test/test_flop_counter.py TestFlopCounter -v`
- `lintrunner --config=.lintrunner.toml torch/utils/flop_counter.py test/test_flop_counter.py`

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

[ghstack-poisoned]
…ad dimensions"

Packed flash- and efficient-attention backward expand the output gradient using
the value-head dimension, which can differ from the query/key-head dimension
for MLA. Propagate that dimension through both packed-sequence FLOP formulas
and report the actual and expected shapes when validation fails.

This changes FLOP accounting only. It does not change attention kernels, tensor
shapes, dispatch, or model execution.

Tests parameterize the shared mixed-dimension contract over flash and efficient
attention, pin the literal backward FLOP count, and exercise the shape
diagnostic for both layouts.

Test Plan:
- `python test/test_flop_counter.py -k nested_attn_backward_flops_with_unequal_qk_value_dims -v`
- `python test/test_flop_counter.py TestFlopCounter -v`
- `lintrunner --config=.lintrunner.toml torch/utils/flop_counter.py test/test_flop_counter.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

…ad dimensions"

Packed flash- and efficient-attention backward expand the output gradient using
the value-head dimension, which can differ from the query/key-head dimension
for MLA. Propagate that dimension through both packed-sequence FLOP formulas
and report the actual and expected shapes when validation fails.

This changes FLOP accounting only. It does not change attention kernels, tensor
shapes, dispatch, or model execution.

Tests parameterize the shared mixed-dimension contract over flash and efficient
attention, pin the literal backward FLOP count, and exercise the shape
diagnostic for both layouts.

Test Plan:
- `python test/test_flop_counter.py -k nested_attn_backward_flops_with_unequal_qk_value_dims -v`
- `python test/test_flop_counter.py TestFlopCounter -v`
- `lintrunner --config=.lintrunner.toml torch/utils/flop_counter.py test/test_flop_counter.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
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.
Pull Request resolved: #196956
Approved by: https://github.com/soulitzer
ghstack dependencies: #196460, #196461
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/5/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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants