Skip to content

Prevent saving mutated grad inputs in AOT min-cut - #185876

Closed
jansel wants to merge 7 commits into
gh/jansel/1250/basefrom
gh/jansel/1250/head
Closed

jansel wants to merge 7 commits into
gh/jansel/1250/basefrom
gh/jansel/1250/head

Conversation

@jansel

@jansel jansel commented Jun 2, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

AOTAutograd clones data-mutated grad inputs in the joint trace so the
backward graph can read their pre-mutation values. For mutations replayed by
the runtime epilogue, the original primal placeholder is not a valid saved
activation: it aliases the user's input and is mutated after the AOT forward
returns, so backward can observe a bumped version counter.

Mark only grad-requiring primal inputs whose data mutation is
MUTATED_OUT_GRAPH, and make min-cut treat those placeholders as unsaveable.
Mutations kept inside the graph, including conservative hidden mutations from
custom Triton kernels, remain valid saved inputs. This distinction fixes the
original failure without making such graphs produce an infeasible min-cut.
The zero-budget input-only fast path remains in place unless an out-of-graph
mutation needs a safe cut.

Subclass components do not carry the outer tensor's requires_grad, so the
tagging uses the outer input metadata expanded onto the inner inputs, the same
expansion the mutated-input bookkeeping already performed; a mutated TwoTensor
input otherwise still saved the stale primal and produced a wrong gradient for
the other operand.

Inductor's joint-graph no-op cleanup could erase the fresh input clone before
partitioning. If backward needs a cloned pre-mutation value through an alias,
that either makes the cut infeasible or reconnects backward to mutated storage.
Keep the clone through joint partitioning. Forward-only cleanup still removes
it when min-cut does not select it, avoiding an unnecessary runtime copy.

Catching NetworkXUnbounded or suppressing its visualization would only mask
an incorrect constraint, so the fix preserves a valid cut at its source.

Fixes #185497
Generated by my agent

Test Plan:

python test/inductor/test_cpu_repro.py -k mutated_input_clone_saved_for_backward

Ran 2 tests, OK.

python test/inductor/test_cpu_repro.py -k interpolate_mutated_input_backward

Ran 3 tests, OK.

python test/inductor/test_cpu_repro.py -k mutated

Ran 9 tests, OK (includes in_graph_mutated_grad_input_backward and
mutated_subclass_input_saved_for_backward for memory budgets 0 and 1).

python test/functorch/test_aotdispatch.py -k subclass
python test/dynamo/test_subclasses.py -k "TwoTensor or SubclassTests"

Ran 65 and 114 tests, OK.

python test/inductor/test_torchinductor.py -k test_remove_noop_clone

Ran 2 tests, OK.

python test/dynamo/test_aot_autograd.py -k donated_buffer

Ran 10 tests, OK.

python test/inductor/test_distributed_patterns.py -k test_unsafe_preserve_version_counter2

Ran 1 test, OK.

Standalone CPU and CUDA eager comparisons for the clone/alias corner case
passed with activation memory budgets 0 and 1.

lintrunner -a

No lint issues.

cc @voznesenskym @penguinwu @EikanWang @jgong5 @Guobing-Chen @XiaobingSuper @zhuhaozhe @blzheng @wenzhe-nrv @jiayisunx @ipiszy @kadeng @muchulee8 @amjames @chauhang @aakhundov @coconutruben @jataylo

[ghstack-poisoned]
@pytorch-bot

pytorch-bot Bot commented Jun 2, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

✅ You can merge normally! (2 Unrelated Failures)

As of commit 8237e9d with merge base 2a20f3e (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.

@jansel

jansel commented Jun 2, 2026

Copy link
Copy Markdown
Contributor Author

@claude review these changes

@claude

claude Bot commented Jun 2, 2026 •

Copy link
Copy Markdown

Claude finished @jansel's task in 2m 24s —— View job


Code Review: Prevent saving mutated grad inputs in AOT min-cut

  • Read the diff and changed files
  • Understand the fix logic in graph_compile.py
  • Review the partitioner change in partitioners.py
  • Review the test additions in test_cpu_repro.py
  • Post review feedback

Overall: This is a clean, well-scoped fix. The problem is clearly diagnosed—the min-cut partitioner can select a primal input placeholder as a saved activation, but that placeholder aliases the user's mutated input, so backward sees a bumped version counter. The fix correctly marks those nodes as unsaveable so the partitioner is forced to pick a pre-mutation clone or recompute.

torch/_functorch/_aot_autograd/graph_compile.py — marking logic

The loop at lines 1933–1944 walks primal placeholders, skips forward effect tokens, and marks nodes where input_info[primal_idx].requires_grad and input_info[primal_idx].mutates_data.

One concern: The loop relies on _is_primal() to identify primals and then uses desc metadata to skip forward tokens. _is_primal is defined as a name-based heuristic ("tangents" not in str(node.target) and not a seed/offset node). This means it matches all non-tangent, non-rng placeholders—including forward effect tokens. The code then uses isinstance(node.meta.get("desc"), ForwardTokenAOTInput) to skip those tokens before bumping primal_idx.

This is correct as written because:

  1. The desc metadata is assigned in graph_capture.py:177 before this code runs.
  2. run_joint_graph_passes_on_hops and joint_custom_pass shouldn't drop desc from existing placeholder nodes since they operate on the graph in-place.

However, this creates a subtle coupling—if a future pass were to rebuild placeholders without carrying desc forward, the token-skip logic would break silently and primal_idx would go out of sync. A defensive assert primal_idx == len(inner_meta.input_info) after the loop would catch this. Not a blocker, just a suggestion.

torch/_functorch/partitioners.py — weight function

Lines 2260–2261:

if node.meta.get("aot_mutated_input_requires_grad", False):
    return math.inf, "mutated input requiring grad"

This is placed at the very top of get_node_weight, before the static_lifetime_input_nodes check. That's the right priority order—a mutated-data input should never be saveable regardless of whether it's also marked as static-lifetime. Clean and minimal.

Tests in test/inductor/test_cpu_repro.py

Both tests are well-designed:

  • test_interpolate_mutated_input_backward — direct reproducer matching the issue pattern.
  • test_interpolate_mutated_input_backward_with_effect_token — exercises the forward-token-skip path, which is the tricky part of the marking loop.

The helper _check_interpolate_mutated_input_backward correctly compares eager vs. compiled behavior for both forward outputs and gradients.

Minor nit: base_arg is created but only its .grad is checked—the variable x_arg = (base_arg * 1.0).squeeze(0) ensures base_arg is the leaf whose grad flows through the mutation. This is correct but a brief comment on why base_arg is included (to test gradient flow through the mutated path) might help future readers. Up to you whether that's worth adding per your style preferences.

Summary

LGTM. The fix is narrow, well-tested, and addresses the root cause without overreaching. The only suggestion is an optional post-loop assertion in graph_compile.py to guard against future desc-metadata drift.


[ghstack-poisoned]
jansel added a commit that referenced this pull request Jun 6, 2026
AOTAutograd clones data-mutated grad inputs in the joint trace so the
backward graph can read their pre-mutation values. The Inductor min-cut
partitioner could still choose the original primal input placeholder as a
saved activation. At runtime that placeholder aliases the user's input,
which is mutated by the AOT forward epilogue after the forward returns, so
autograd later sees a bumped version counter and fails during backward.

Mark primal placeholders that correspond to data-mutated inputs requiring
grad, skipping forward effect-token placeholders when mapping joint graph
inputs back to input metadata. The min-cut partitioner now treats those
marked placeholders as unsaveable, forcing the cut to keep a pre-mutation
clone or another valid downstream activation instead of saving the runtime
input. This keeps the fix local to the activation-saving decision rather
than changing mutation replay or disabling recomputation more broadly.

Fixes #185497
Generated by my agent

Test Plan:
- Original issue-style CPU/CUDA reproducer: eager and compiled pass after the fix
- `python test/inductor/test_cpu_repro.py -k test_interpolate_mutated_input_backward` failed during local test module import because local torchvision was built against a different CUDA major version than this PyTorch checkout
- `PYTHONPATH=test python - <<'PY' ...` inline unittest runner with torchvision import disabled for `CPUReproTests.test_interpolate_mutated_input_backward` and `CPUReproTests.test_interpolate_mutated_input_backward_with_effect_token`: `Ran 2 tests in 8.839s`, `OK`
- `python test/dynamo/test_aot_autograd.py -k donated_buffer`: `Ran 10 tests in 23.810s`, `OK`
- `lintrunner -a`: `ok No lint issues. Successfully applied all patches.`

Benchmark Results:
- Pre-fix: the original reproducer fails backward with the version-counter `RuntimeError`, so there is no successful runtime baseline for this graph.
- Post-fix inline CPU timing after compile, 20 forward+backward runs of the small regression case: median 0.295 ms, mean 0.329 ms.

ghstack-source-id: e51ce62
Pull-Request: #185876
@jansel

jansel commented Jun 6, 2026

Copy link
Copy Markdown
Contributor Author

My agent says I rebased the PR onto current main, fixed the lintrunner formatting failure, reran lintrunner and the targeted interpolate/mutated-input regression tests locally, and added the release notes: inductor label. The docs failures were in the docs upload step with aws not found, not in this code path.

@jansel jansel added the agentic Created by an AI agent label Jun 9, 2026
@jansel
jansel marked this pull request as ready for review June 11, 2026 11:43
@jansel
jansel requested review from bobrenjc93 and eellison June 11, 2026 11:43
@jansel
jansel requested review from aorenste and bdhirsh as code owners June 11, 2026 11:43
@jansel
jansel requested review from BoyuanFeng, ethche and zou3519 June 15, 2026 21:18
@jansel
jansel requested a review from choijon5 June 23, 2026 16:03
@jansel
jansel requested review from anijain2305 and laithsakka July 1, 2026 09:31
@jansel
jansel requested review from angelayi, karthickai and oulgen July 8, 2026 11:05
@claude

claude Bot commented Sep 29, 2026 •

Copy link
Copy Markdown

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


Not fully. The failure that caused the revert and the clone-erasure case I raised last time are both fixed, and CI is green. Two review comments from @mlazos (2026-09-13) have no reply yet, and nobody has confirmed the fix on the internal signal that caused the revert. I'd sort out both before relanding.

Details
  • Read the current diff against gh/jansel/1250/base
  • Check each outstanding item
  • Check CI
  • Run tests: I couldn't, because this checkout has no built PyTorch (no .venv or build/)

Resolved

  • Infeasible min-cut behind the revert (MUTATED_IN_GRAPH). The marker is now set only for MUTATED_OUT_GRAPH inputs (graph_compile.py:2000-2006). That matches exactly the inputs that maybe_to_fresh_input (utils.py:258-263) clones before mutation. test_in_graph_mutated_grad_input_zero_memory_budget checks that the zero-budget fast path is kept.
  • remove_noop_ops erasing the pre-mutation clone. In the joint graph, clones of marked primals are now skipped (post_grad.py:1471-1478). In the forward graph, is_joint_graph is False, so the clone is removed unless min-cut saved it. If it was saved, it is a forward output, and the existing output-storage guard at :1495-1500 keeps it. test_mutated_input_clone_saved_for_backward (x.T.clone() * y; x.add_(1)) covers this at budgets 0 and 1.
  • Silent index desync (@aorenste). Replaced by zip over the matching lists. This module rebinds zip to strict_zip, so a length mismatch now raises instead of marking the wrong node.
  • CI. The latest head passes. The only inductor failures are the two unstable inductor_aoti_fallback shards. The cancelled pull, docs-build, Lint and BC Lint runs are duplicates of runs that succeeded.

Still open

  1. Subclass inputs are still not covered (@mlazos, graph_compile.py:2000). The comment is correct. The note in subclass_utils.py:731-742 says the inner parts of a grad-requiring subclass usually have requires_grad=False. Because of that, info.requires_grad is False for those parts in inner_meta.input_info. Two things follow:

    • Those inner primals are never marked, so min-cut can still save them.
    • The remove_noop_ops exemption never applies to them either.

    So the original version-counter bug can still happen for wrapper subclasses such as DTensor. This isn't a regression, since behaviour is unchanged from before this PR. It does mean the fix is incomplete, and the comment has no reply. compute_inner_mutated_inp_indices_from_subclass_meta already maps outer input metadata to inner indices, and the same mapping would work here. Either apply it, or reply that subclasses will be a follow-up.

  2. The test mocks solve_min_cut (@mlazos, test_cpu_repro.py:245), and this has no reply. The test does check the property that broke. It's a guard against the reverted version, not a test that would have failed before this PR. If mocking isn't acceptable, you could check the partition result directly: the saved values should equal the inputs. Either way, please reply to the comment.

  3. Internal validation. The idea that the internal gdpa_dcpp break was only the MUTATED_IN_GRAPH case comes from this thread; I can't see D117152835. Import the diff and run that target before landing. This is the only check that actually confirms that idea.

Minor (not blocking)

  • The exemption catches every clone of a marked primal, not just the one AOTAutograd inserted. A user's own x.clone() of the same input would also be kept in the joint graph. That can cost a little memory but doesn't affect correctness.
  • Default-budget partitioning changes too. At the default memory_budget=1, any compile with a grad-requiring input mutated outside the graph now saves the clone instead of the primal. That's one extra saved tensor per such input. It is the correct behaviour, but it will show up as higher memory in internal benchmarks.
  • is_joint_graph is inferred from partitioner_tag. Backward graphs that contain recomputed forward nodes can also look like joint graphs. That's harmless today, because marked primals can't be saved into backward. Still, it's a guess rather than an explicit signal. An explicit argument from joint_graph_passes (joint_graph.py:823) would be safer.
· branch `gh/jansel/1250/head`

[ghstack-poisoned]
jansel added a commit that referenced this pull request Sep 30, 2026
AOTAutograd clones data-mutated grad inputs in the joint trace so the
backward graph can read their pre-mutation values. For mutations replayed by
the runtime epilogue, the original primal placeholder is not a valid saved
activation: it aliases the user's input and is mutated after the AOT forward
returns, so backward can observe a bumped version counter.

Mark only grad-requiring primal inputs whose data mutation is
MUTATED_OUT_GRAPH, and make min-cut treat those placeholders as unsaveable.
Mutations kept inside the graph, including conservative hidden mutations from
custom Triton kernels, remain valid saved inputs. This distinction fixes the
original failure without making such graphs produce an infeasible min-cut.
The zero-budget input-only fast path remains in place unless an out-of-graph
mutation needs a safe cut.

Subclass components do not carry the outer tensor's requires_grad, so the
tagging uses the outer input metadata expanded onto the inner inputs, the same
expansion the mutated-input bookkeeping already performed; a mutated TwoTensor
input otherwise still saved the stale primal and produced a wrong gradient for
the other operand.

Inductor's joint-graph no-op cleanup could erase the fresh input clone before
partitioning. If backward needs a cloned pre-mutation value through an alias,
that either makes the cut infeasible or reconnects backward to mutated storage.
Keep the clone through joint partitioning. Forward-only cleanup still removes
it when min-cut does not select it, avoiding an unnecessary runtime copy.

Catching NetworkXUnbounded or suppressing its visualization would only mask
an incorrect constraint, so the fix preserves a valid cut at its source.

Fixes #185497
Generated by my agent

Test Plan:

```
python test/inductor/test_cpu_repro.py -k mutated_input_clone_saved_for_backward
```
Ran 2 tests, OK.

```
python test/inductor/test_cpu_repro.py -k interpolate_mutated_input_backward
```
Ran 3 tests, OK.

```
python test/inductor/test_cpu_repro.py -k mutated
```
Ran 9 tests, OK (includes in_graph_mutated_grad_input_backward and
mutated_subclass_input_saved_for_backward for memory budgets 0 and 1).

```
python test/functorch/test_aotdispatch.py -k subclass
python test/dynamo/test_subclasses.py -k "TwoTensor or SubclassTests"
```
Ran 65 and 114 tests, OK.

```
python test/inductor/test_torchinductor.py -k test_remove_noop_clone
```
Ran 2 tests, OK.

```
python test/dynamo/test_aot_autograd.py -k donated_buffer
```
Ran 10 tests, OK.

```
python test/inductor/test_distributed_patterns.py -k test_unsafe_preserve_version_counter2
```
Ran 1 test, OK.

Standalone CPU and CUDA eager comparisons for the clone/alias corner case
passed with activation memory budgets 0 and 1.

```
lintrunner -a
```
No lint issues.

ghstack-source-id: 2ae7e21
Pull-Request: #185876
@jansel

jansel commented Sep 30, 2026

Copy link
Copy Markdown
Contributor Author

@claude is this safe to reland? Have all the outstanding issues been resolved?

@claude

claude Bot commented Sep 30, 2026 •

Copy link
Copy Markdown

Claude finished @jansel's task in 1m 14s —— View job


Mostly yes. Every open code-review item has now been fixed in the code, and Dr. CI reports the head as mergeable. The unstable inductor_aoti_fallback shards are its only failures. One thing is still not done: nobody has confirmed the fix on the internal target that caused the revert (D117152835 / gdpa_dcpp). I'd do that before relanding.

Details
  • Read the current diff against origin/gh/jansel/1250/base
  • Re-check each item left open from the last review
  • Check CI (Dr. CI: 2 unrelated unstable failures)
  • Run tests: not possible, because this checkout has no built PyTorch

Resolved since the last review

  1. Subclass inputs (@mlazos). The new helper compute_inner_input_info_from_subclass_meta (subclass_utils.py:743) applies the outer input_info to each inner component. graph_compile.py:2005-2014 now marks inputs using that expanded info. compute_inner_mutated_inp_indices_from_subclass_meta is now built on the same helper, so the two stay consistent:
    • The strict zip length check still holds, because the helper asserts that its output has the same length as inner_meta.input_info (:809).
    • The synthetic-base path, which has no subclass_inp_meta, falls back to inner_metadata.input_info, the same as before.
    • The TwoTensor clone is inserted at the outer level by maybe_to_fresh_input inside fn_prepped_for_autograd (graph_capture_wrappers.py:177). After the subclass is unwrapped, that becomes one clone per component. Each marked inner primal therefore still has a clone that min-cut can save, so this change should not reintroduce an infeasible cut.
    • test_mutated_subclass_input_saved_for_backward covers budgets 0 and 1.
  2. Mocked solve_min_cut (@mlazos). The mock is gone. test_in_graph_mutated_grad_input_backward now checks only observable results (output, mutated input, grad) at budgets 0 and 1. The trade-off: nothing now asserts that in-graph mutations keep the zero-budget fast path. The code path is unchanged, though: only MUTATED_OUT_GRAPH inputs are marked, so the any(...) check at partitioners.py:3531 is false for them.
  3. Both review comments now have replies (2026-09-30).

The earlier fixes are still in place: inputs are marked only when their mutation is MUTATED_OUT_GRAPH, the AOT clone is kept in the joint graph (post_grad.py:1524-1531), and primals are paired with metadata through strict_zip.

Still open before reland

  • Internal validation. The reland assumes the internal break was only the in-graph (MUTATED_IN_GRAPH) hidden-Triton-mutation case. That diagnosis is second-hand and can't be checked from OSS. Import the diff and run the failing internal target. This is the one check that confirms the fix.

Minor, not blocking

  • is_joint_graph (post_grad.py:1494) is guessed from partitioner_tag, not passed in from joint_graph_passes. It's harmless today, but an explicit flag would be more robust.
  • The exemption keeps any aten.clone of a marked primal in the joint graph, including a clone the user wrote. At worst this costs extra memory; correctness isn't affected.
  • At the default budget of 1, each grad-requiring input that is mutated outside the graph now saves its clone instead of the primal. That is one extra saved tensor per such input, and it may show up in internal memory benchmarks.
· branch `gh/jansel/1250/head`

@jansel

jansel commented Sep 30, 2026

Copy link
Copy Markdown
Contributor Author

@pytorchbot merge

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge started

Your change will be merged once all checks pass (ETA 0-4 Hours).

Learn more about merging in the wiki.

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

Advanced Debugging
Check the merge workflow status
here

pytorchmergebot pushed a commit that referenced this pull request Oct 5, 2026
#199663)

The three test_interpolate_mutated_input_backward tests added in #185876 fail
consistently in the periodic nogpu_NO_AVX2 config:

```
AssertionError: Tensor-likes are not close!
Mismatched elements: 1 / 3 (33.3%)
Greatest absolute difference: 0.0005950927734375 at index (0, 0, 0) (up to 1e-05 allowed)
Greatest relative difference: 3.6538310723699396e-06 at index (0, 0, 0) (up to 1.3e-06 allowed)
```

This is float32 summation error, not a correctness bug. The mismatching tensor
is mean.grad, where each element is a sum of 256 float32 values (about 313 in
magnitude). Eager computes it with ATen's cascade_sum and is accurate to about
2e-8 relative. nogpu_NO_AVX2 sets ATEN_CPU_CAPABILITY=default, which Inductor
also uses to pick its vector ISA, so the compiled kernel is scalar. Inductor's
scalar reductions are a single running sum (its CascadeSumHelper is only used by
vectorized kernels, in 4096-element chunks), which is about 2e-6 relative off
here, just over assertEqual's default float32 rtol of 1.3e-6. Vectorized builds
keep one accumulator per lane and pass.

The fix compares with atol=1e-4 and rtol=1e-4, as the neighboring gradient tests
in this file do. The alternative, giving Inductor's scalar CPU reductions
cascade summation, would be a codegen change with performance cost and is out of
scope for a test failure.

Test Plan:

```
ATEN_CPU_CAPABILITY=default python -m pytest test/inductor/test_cpu_repro.py -k test_interpolate_mutated_input_backward
python -m pytest test/inductor/test_cpu_repro.py -k test_interpolate_mutated_input_backward
```

All three pass in both configurations; before the change they failed with
ATEN_CPU_CAPABILITY=default with the same numbers as CI. With #185876's
torch/ changes reverted, all three still fail with "one of the variables needed
for gradient computation has been modified by an inplace operation", so the
looser tolerance doesn't hide the bug the tests guard against.

This PR was authored with the help of an AI assistant.

Pull Request resolved: #199663
Approved by: https://github.com/jansel
qchip added a commit to qchip/pytorch that referenced this pull request Oct 9, 2026
Summary:
The AOT min-cut partitioner may recompute a value in the backward rather than save it. That is equivalent only when re-execution is value-preserving, which fails for a read of an input the forward mutates: recompute defers the read past the mutation, so the backward observes post-update contents. The symptom is silently wrong gradients, or a version-counter error when the input reaches the backward through `SavedVariable`. Reads of these inputs are pinned `MUST_SAVE`, walking through aliasing ops to the first op that materializes data -- pinning a view pins an alias, not a snapshot. The comment on `force_save_fw_mutated_input_readers` walks through an example of the wrong and the correct partition.

Who hits this: default `torch.compile` (Inductor), whenever min-cut recomputes a read of an input the forward mutates in place, e.g. a registered buffer read by a pointwise op and then updated with `add_`. With the pin disabled, the buffer model below gets wrong gradients at the default budget (1.0) as well as at 0 and 0.05; the gather model in `test_min_cut_no_recompute_through_mutated_input` is wrong at 0 and 0.05 but matches eager at 1.0. `aot_eager` shows the same pattern. To compare pin on and off under Inductor, disable caches: the pin is not part of the AOTAutogradCache key, so the second compile can reuse the first one's graphs.
```
class C2(torch.nn.Module):
    def __init__(self):
        super().__init__()
        self.register_buffer("buf", torch.randn(16))

    def forward(self, x):
        y = (x * (self.buf * 2)).sum()  # eager grad_x = 2 * buf before add_
        self.buf.add_(1.0)
        return y
```

## Details

Aliasing is decided by storage, not op schema, since the `getitem`s of split/chunk/unbind have no schema. A tuple-producing op cannot be saved as a tensor, so its `getitem`s are pinned; the op itself is pinned too, since min-cut never bans recomputing a `getitem`.

Mutated inputs are found from metadata AOTAutograd already attaches to the joint graph, so no new metadata is added: forward outputs described by `InputMutationAOTOutput` for mutations the runtime epilogue applies (translated through `SubclassGetAttrAOTOutput` to the inner placeholders' descriptors), and `copy_` nodes tagged `must_be_in_forward` for mutations kept in the graph. This also covers metadata-only mutations such as `t_()`, which hit the same version-counter error today.

Behaviour changes, limited to the pinned reads:
- Activation checkpointing's `PREFER_RECOMPUTE` on such a read is overridden. An explicit `MUST_RECOMPUTE` from a user policy is honored, because the pin is conservative (it also hits reads that do not depend on the mutated data, such as BatchNorm's running-stat updates after decomposition); a one-time warning (`warning_once`) says gradients may be wrong, and the nodes are logged at debug level.
- `default_partition` runs the same pass. Under activation checkpointing it recomputed such reads: with a buffer read inside the checkpointed region and mutated after it, base raises the version-counter error with `keep_inference_input_mutations=False` and gives `2 * (buf + 1)` with `True`; this gives `2 * buf`, matching the function without checkpointing. Eager checkpointing itself recomputes after the mutation and also gives `2 * (buf + 1)`, so the compiled result now matches the un-checkpointed function rather than eager checkpointing.
- `memory_budget == 0` saved only the inputs. It now also saves the pinned reads, including a `getitem` of a forward op that only the backward reads, such as BatchNorm's `save_mean`. Other `MUST_SAVE` marks are still recomputed at budget 0, as before.

Behavior change for BatchNorm: on backends that keep BatchNorm as a single op (eager-style backends such as `aot_eager`), training BatchNorm's outputs are now saved rather than recomputed. This is conservative: the partitioner only sees that `_native_batch_norm_legit_functional` reads the mutated running stats, not that `out`, `save_mean`, and `save_rstd` depend only on batch stats. It costs memory, not correctness; for conv -> BN -> ReLU at budget 0, the full (2, 4, 8, 8) BN output and four (4,) vectors are saved where trunk saves only the inputs, and gradients match eager in both. Under Inductor it is not an issue, because Inductor decomposes BN before partitioning: on the same model, the saved-for-backward set is identical with and without the pin at the default budget and at budgets 0 and 0.05, and the pin lands only on the small running-stat update ops, which feed `copy_` rather than the backward. A follow-up that snapshots each mutated input (clone before the mutation, ban recomputing the clone) and lets min-cut choose between saving the snapshot and saving the reads would remove this over-save.

Relation to pytorch#185876 (`aot_runtime_epilogue_input_mutation`): that stops min-cut from saving the placeholder of an input that requires grad and is mutated by the runtime epilogue. This covers inputs that do not require grad, such as buffers, mutations kept in the graph, and metadata-only mutations. Where both apply the results agree.
Buffers mutated by a different compiled region or by eager code are invisible to this graph; an opt-in fix follows in a separate PR.

This PR was authored with an AI assistant.

Test Plan:
```
buck2 test fbcode//mode/opt fbcode//caffe2/test/functorch:test_aotdispatch -- -r 'TestPartitioning'
buck2 test fbcode//mode/opt fbcode//caffe2/test/functorch:test_aotdispatch -- -r 'partition|Partition|mutation|Mutation|checkpoint'
```
`TestPartitioning` covers reads through a view, a tuple-producing view, a tuple-producing op read by the backward (budgets 0, 0.05, 0.5), the updated value, a metadata-only mutation (`t_()`), BatchNorm's saved statistics, several gathers at budget 0.05, flat and subclass inputs with `keep_inference_input_mutations` on and off, `default_partition` under activation checkpointing, and an honored `MUST_RECOMPUTE` (warning logged); reads of unmutated inputs are still recomputed. With the base `partitioners.py` swapped in, every new mutating case fails (wrong gradients or `modified by an inplace operation`; for BatchNorm only its structural `assertNotIn` check fails, its gradients match eager either way).
Results: `TestPartitioning` 142 pass, 0 fail; the broader filter 313 pass, 0 fail.
Descriptor discovery check, with a temporary uncommitted test that wraps `min_cut_rematerialization_partition` and compares the descriptor-derived mutated placeholders with the earlier `input_info.mutates_data`-based names, for a buffer, a `TwoTensor` buffer, a nested `TwoTensor` buffer, no-grad and requires-grad inputs, data plus metadata, and metadata-only mutations, each with `keep_inference_input_mutations` on and off: identical everywhere except metadata-only, which only the descriptors catch; with it pinned, gradients match eager.
Inductor BatchNorm check, with a temporary uncommitted test in `TestPartitioning` that compiles training-mode Conv2d(3, 4) -> BatchNorm2d(4) -> ReLU on a (2, 3, 8, 8) CPU input with `torch.compile(backend="inductor")` (caches disabled), wraps `min_cut_rematerialization_partition` in `torch._inductor.compile_fx` to record the backward graph's non-tangent placeholders, and runs with the pin on and with `force_save_fw_mutated_input_readers` patched to a no-op:
```
buck2 test fbcode//mode/opt fbcode//caffe2/test/functorch:test_aotdispatch -- --regex 'test_zz_tmp_inductor_bn_saved' --print-passing-details
```
The joint graph has no `batch_norm` op (already decomposed) and three `copy_` into the BN buffers (`running_mean`, `running_var`, `num_batches_tracked`). The pin tags `add`, `mul_2`, and `mul_5` (the buffer updates) and nothing the backward reads. Saved sets, identical with and without the pin; gradients and running stats match eager:
- default budget: `primals_1` (4, 3, 3, 3), `primals_3` (2, 3, 8, 8), `primals_7` (4,), `convolution` (2, 4, 8, 8), `squeeze_1` (4,), `le` (2, 4, 8, 8), `unsqueeze_6` (1, 4, 1, 1)
- budget 0: inputs only, `primals_1` (4, 3, 3, 3), `primals_2` (4,), `primals_3` (2, 3, 8, 8), `primals_7` (4,), `primals_8` (4,)
- budget 0.05: the same five inputs plus `getitem_1` (1, 4, 1, 1) and `rsqrt` (1, 4, 1, 1)

Who-hits-this check, with a temporary uncommitted test `test_zzprobe_default_budget` in `TestPartitioning` that compiles `C2` above and the model from `test_min_cut_no_recompute_through_mutated_input` with `torch.compile(backend="inductor")` and `backend="aot_eager"` at the default budget (`activation_memory_budget = 1.0` in `torch/_functorch/config.py`, left unpatched), 0, and 0.05, with the pin on and with `force_save_fw_mutated_input_readers` patched to a no-op. Caches are disabled (`torch.compiler.config.patch(force_disable_caches=True)`, `torch._functorch.config.patch(enable_autograd_cache=False)`), `torch._dynamo.reset()` runs before each compile, and `x.grad` and the buffer are compared against eager on a deepcopy of the module:
```
buck2 test fbcode//mode/opt fbcode//caffe2/test/functorch:test_aotdispatch -- --regex test_zzprobe --print-passing-details
```
- pin off, default budget: `C2` grads wrong (16/16) under both backends; gather model grads match eager under both.
- pin off, budgets 0 and 0.05: both models wrong under both backends (`C2` 16/16, gather model 256/256).
- pin on: every case matches eager. The updated buffer matches eager in every case.

Differential Revision: D118411035
qchip added a commit to qchip/pytorch that referenced this pull request Oct 9, 2026
…h#197039)

Summary:

The AOT min-cut partitioner may recompute a value in the backward rather than save it. That is equivalent only when re-execution is value-preserving, which fails for a read of an input the forward mutates: recompute defers the read past the mutation, so the backward observes post-update contents. The symptom is silently wrong gradients, or a version-counter error when the input reaches the backward through `SavedVariable`. Reads of these inputs are pinned `MUST_SAVE`, walking through aliasing ops to the first op that materializes data -- pinning a view pins an alias, not a snapshot. The comment on `force_save_fw_mutated_input_readers` walks through an example of the wrong and the correct partition.

Who hits this: default `torch.compile` (Inductor), whenever min-cut recomputes a read of an input the forward mutates in place, e.g. a registered buffer read by a pointwise op and then updated with `add_`. With the pin disabled, the buffer model below gets wrong gradients at the default budget (1.0) as well as at 0 and 0.05; the gather model in `test_min_cut_no_recompute_through_mutated_input` is wrong at 0 and 0.05 but matches eager at 1.0. `aot_eager` shows the same pattern. To compare pin on and off under Inductor, disable caches: the pin is not part of the AOTAutogradCache key, so the second compile can reuse the first one's graphs.
```
class C2(torch.nn.Module):
    def __init__(self):
        super().__init__()
        self.register_buffer("buf", torch.randn(16))

    def forward(self, x):
        y = (x * (self.buf * 2)).sum()  # eager grad_x = 2 * buf before add_
        self.buf.add_(1.0)
        return y
```

## Details

Aliasing is decided by storage, not op schema, since the `getitem`s of split/chunk/unbind have no schema. A tuple-producing op cannot be saved as a tensor, so its `getitem`s are pinned; the op itself is pinned too, since min-cut never bans recomputing a `getitem`.

Mutated inputs are found from metadata AOTAutograd already attaches to the joint graph, so no new metadata is added: forward outputs described by `InputMutationAOTOutput` for mutations the runtime epilogue applies (translated through `SubclassGetAttrAOTOutput` to the inner placeholders' descriptors), and `copy_` nodes tagged `must_be_in_forward` for mutations kept in the graph. This also covers metadata-only mutations such as `t_()`, which hit the same version-counter error today.

Behaviour changes, limited to the pinned reads:
- Activation checkpointing's `PREFER_RECOMPUTE` on such a read is overridden. An explicit `MUST_RECOMPUTE` from a user policy is honored, because the pin is conservative (it also hits reads that do not depend on the mutated data, such as BatchNorm's running-stat updates after decomposition); a one-time warning (`warning_once`) says gradients may be wrong, and the nodes are logged at debug level.
- `default_partition` runs the same pass. Under activation checkpointing it recomputed such reads: with a buffer read inside the checkpointed region and mutated after it, base raises the version-counter error with `keep_inference_input_mutations=False` and gives `2 * (buf + 1)` with `True`; this gives `2 * buf`, matching the function without checkpointing. Eager checkpointing itself recomputes after the mutation and also gives `2 * (buf + 1)`, so the compiled result now matches the un-checkpointed function rather than eager checkpointing.
- `memory_budget == 0` saved only the inputs. It now also saves the pinned reads, including a `getitem` of a forward op that only the backward reads, such as BatchNorm's `save_mean`. Other `MUST_SAVE` marks are still recomputed at budget 0, as before.

Behavior change for BatchNorm: on backends that keep BatchNorm as a single op (eager-style backends such as `aot_eager`), training BatchNorm's outputs are now saved rather than recomputed. This is conservative: the partitioner only sees that `_native_batch_norm_legit_functional` reads the mutated running stats, not that `out`, `save_mean`, and `save_rstd` depend only on batch stats. It costs memory, not correctness; for conv -> BN -> ReLU at budget 0, the full (2, 4, 8, 8) BN output and four (4,) vectors are saved where trunk saves only the inputs, and gradients match eager in both. Under Inductor it is not an issue, because Inductor decomposes BN before partitioning: on the same model, the saved-for-backward set is identical with and without the pin at the default budget and at budgets 0 and 0.05, and the pin lands only on the small running-stat update ops, which feed `copy_` rather than the backward. A follow-up that snapshots each mutated input (clone before the mutation, ban recomputing the clone) and lets min-cut choose between saving the snapshot and saving the reads would remove this over-save.

Relation to pytorch#185876 (`aot_runtime_epilogue_input_mutation`): that stops min-cut from saving the placeholder of an input that requires grad and is mutated by the runtime epilogue. This covers inputs that do not require grad, such as buffers, mutations kept in the graph, and metadata-only mutations. Where both apply the results agree.
Buffers mutated by a different compiled region or by eager code are invisible to this graph; an opt-in fix follows in a separate PR.

This PR was authored with an AI assistant.

Test Plan:
```
buck2 test fbcode//mode/opt fbcode//caffe2/test/functorch:test_aotdispatch -- -r 'TestPartitioning'
buck2 test fbcode//mode/opt fbcode//caffe2/test/functorch:test_aotdispatch -- -r 'partition|Partition|mutation|Mutation|checkpoint'
```
`TestPartitioning` covers reads through a view, a tuple-producing view, a tuple-producing op read by the backward (budgets 0, 0.05, 0.5), the updated value, a metadata-only mutation (`t_()`), BatchNorm's saved statistics, several gathers at budget 0.05, flat and subclass inputs with `keep_inference_input_mutations` on and off, `default_partition` under activation checkpointing, and an honored `MUST_RECOMPUTE` (warning logged); reads of unmutated inputs are still recomputed. With the base `partitioners.py` swapped in, every new mutating case fails (wrong gradients or `modified by an inplace operation`; for BatchNorm only its structural `assertNotIn` check fails, its gradients match eager either way).
Results: `TestPartitioning` 142 pass, 0 fail; the broader filter 313 pass, 0 fail.
Descriptor discovery check, with a temporary uncommitted test that wraps `min_cut_rematerialization_partition` and compares the descriptor-derived mutated placeholders with the earlier `input_info.mutates_data`-based names, for a buffer, a `TwoTensor` buffer, a nested `TwoTensor` buffer, no-grad and requires-grad inputs, data plus metadata, and metadata-only mutations, each with `keep_inference_input_mutations` on and off: identical everywhere except metadata-only, which only the descriptors catch; with it pinned, gradients match eager.
Inductor BatchNorm check, with a temporary uncommitted test in `TestPartitioning` that compiles training-mode Conv2d(3, 4) -> BatchNorm2d(4) -> ReLU on a (2, 3, 8, 8) CPU input with `torch.compile(backend="inductor")` (caches disabled), wraps `min_cut_rematerialization_partition` in `torch._inductor.compile_fx` to record the backward graph's non-tangent placeholders, and runs with the pin on and with `force_save_fw_mutated_input_readers` patched to a no-op:
```
buck2 test fbcode//mode/opt fbcode//caffe2/test/functorch:test_aotdispatch -- --regex 'test_zz_tmp_inductor_bn_saved' --print-passing-details
```
The joint graph has no `batch_norm` op (already decomposed) and three `copy_` into the BN buffers (`running_mean`, `running_var`, `num_batches_tracked`). The pin tags `add`, `mul_2`, and `mul_5` (the buffer updates) and nothing the backward reads. Saved sets, identical with and without the pin; gradients and running stats match eager:
- default budget: `primals_1` (4, 3, 3, 3), `primals_3` (2, 3, 8, 8), `primals_7` (4,), `convolution` (2, 4, 8, 8), `squeeze_1` (4,), `le` (2, 4, 8, 8), `unsqueeze_6` (1, 4, 1, 1)
- budget 0: inputs only, `primals_1` (4, 3, 3, 3), `primals_2` (4,), `primals_3` (2, 3, 8, 8), `primals_7` (4,), `primals_8` (4,)
- budget 0.05: the same five inputs plus `getitem_1` (1, 4, 1, 1) and `rsqrt` (1, 4, 1, 1)

Who-hits-this check, with a temporary uncommitted test `test_zzprobe_default_budget` in `TestPartitioning` that compiles `C2` above and the model from `test_min_cut_no_recompute_through_mutated_input` with `torch.compile(backend="inductor")` and `backend="aot_eager"` at the default budget (`activation_memory_budget = 1.0` in `torch/_functorch/config.py`, left unpatched), 0, and 0.05, with the pin on and with `force_save_fw_mutated_input_readers` patched to a no-op. Caches are disabled (`torch.compiler.config.patch(force_disable_caches=True)`, `torch._functorch.config.patch(enable_autograd_cache=False)`), `torch._dynamo.reset()` runs before each compile, and `x.grad` and the buffer are compared against eager on a deepcopy of the module:
```
buck2 test fbcode//mode/opt fbcode//caffe2/test/functorch:test_aotdispatch -- --regex test_zzprobe --print-passing-details
```
- pin off, default budget: `C2` grads wrong (16/16) under both backends; gather model grads match eager under both.
- pin off, budgets 0 and 0.05: both models wrong under both backends (`C2` 16/16, gather model 256/256).
- pin on: every case matches eager. The updated buffer matches eager in every case.

Differential Revision: D118411035
qchip added a commit to qchip/pytorch that referenced this pull request Oct 9, 2026
…h#197039)

Summary:

The AOT min-cut partitioner may recompute a value in the backward rather than save it. That is equivalent only when re-execution is value-preserving, which fails for a read of an input the forward mutates: recompute defers the read past the mutation, so the backward observes post-update contents. The symptom is silently wrong gradients, or a version-counter error when the input reaches the backward through `SavedVariable`. Reads of these inputs are pinned `MUST_SAVE`, walking through aliasing ops to the first op that materializes data -- pinning a view pins an alias, not a snapshot. The comment on `force_save_fw_mutated_input_readers` walks through an example of the wrong and the correct partition.

Who hits this: default `torch.compile` (Inductor), whenever min-cut recomputes a read of an input the forward mutates in place, e.g. a registered buffer read by a pointwise op and then updated with `add_`. With the pin disabled, the buffer model below gets wrong gradients at the default budget (1.0) as well as at 0 and 0.05; the gather model in `test_min_cut_no_recompute_through_mutated_input` is wrong at 0 and 0.05 but matches eager at 1.0. `aot_eager` shows the same pattern. To compare pin on and off under Inductor, disable caches: the pin is not part of the AOTAutogradCache key, so the second compile can reuse the first one's graphs.
```
class C2(torch.nn.Module):
    def __init__(self):
        super().__init__()
        self.register_buffer("buf", torch.randn(16))

    def forward(self, x):
        y = (x * (self.buf * 2)).sum()  # eager grad_x = 2 * buf before add_
        self.buf.add_(1.0)
        return y
```

## Details

Aliasing is decided by storage, not op schema, since the `getitem`s of split/chunk/unbind have no schema. A tuple-producing op cannot be saved as a tensor, so its `getitem`s are pinned; the op itself is pinned too, since min-cut never bans recomputing a `getitem`.

Mutated inputs are found from metadata AOTAutograd already attaches to the joint graph, so no new metadata is added: forward outputs described by `InputMutationAOTOutput` for mutations the runtime epilogue applies (translated through `SubclassGetAttrAOTOutput` to the inner placeholders' descriptors), and `copy_` nodes tagged `must_be_in_forward` for mutations kept in the graph. This also covers metadata-only mutations such as `t_()`, which hit the same version-counter error today.

Behaviour changes, limited to the pinned reads:
- Activation checkpointing's `PREFER_RECOMPUTE` on such a read is overridden. An explicit `MUST_RECOMPUTE` from a user policy is honored, because the pin is conservative (it also hits reads that do not depend on the mutated data, such as BatchNorm's running-stat updates after decomposition); a one-time warning (`warning_once`) says gradients may be wrong, and the nodes are logged at debug level.
- `default_partition` runs the same pass. Under activation checkpointing it recomputed such reads: with a buffer read inside the checkpointed region and mutated after it, base raises the version-counter error with `keep_inference_input_mutations=False` and gives `2 * (buf + 1)` with `True`; this gives `2 * buf`, matching the function without checkpointing. Eager checkpointing itself recomputes after the mutation and also gives `2 * (buf + 1)`, so the compiled result now matches the un-checkpointed function rather than eager checkpointing.
- `memory_budget == 0` saved only the inputs. It now also saves the pinned reads, including a `getitem` of a forward op that only the backward reads, such as BatchNorm's `save_mean`. Other `MUST_SAVE` marks are still recomputed at budget 0, as before.

Behavior change for BatchNorm: on backends that keep BatchNorm as a single op (eager-style backends such as `aot_eager`), training BatchNorm's outputs are now saved rather than recomputed. This is conservative: the partitioner only sees that `_native_batch_norm_legit_functional` reads the mutated running stats, not that `out`, `save_mean`, and `save_rstd` depend only on batch stats. It costs memory, not correctness; for conv -> BN -> ReLU at budget 0, the full (2, 4, 8, 8) BN output and four (4,) vectors are saved where trunk saves only the inputs, and gradients match eager in both. Under Inductor it is not an issue, because Inductor decomposes BN before partitioning: on the same model, the saved-for-backward set is identical with and without the pin at the default budget and at budgets 0 and 0.05, and the pin lands only on the small running-stat update ops, which feed `copy_` rather than the backward. A follow-up that snapshots each mutated input (clone before the mutation, ban recomputing the clone) and lets min-cut choose between saving the snapshot and saving the reads would remove this over-save.

Relation to pytorch#185876 (`aot_runtime_epilogue_input_mutation`): that stops min-cut from saving the placeholder of an input that requires grad and is mutated by the runtime epilogue. This covers inputs that do not require grad, such as buffers, mutations kept in the graph, and metadata-only mutations. Where both apply the results agree.
Buffers mutated by a different compiled region or by eager code are invisible to this graph; an opt-in fix follows in a separate PR.

This PR was authored with an AI assistant.

Test Plan:
```
buck2 test fbcode//mode/opt fbcode//caffe2/test/functorch:test_aotdispatch -- -r 'TestPartitioning'
buck2 test fbcode//mode/opt fbcode//caffe2/test/functorch:test_aotdispatch -- -r 'partition|Partition|mutation|Mutation|checkpoint'
```
`TestPartitioning` covers reads through a view, a tuple-producing view, a tuple-producing op read by the backward (budgets 0, 0.05, 0.5), the updated value, a metadata-only mutation (`t_()`), BatchNorm's saved statistics, several gathers at budget 0.05, flat and subclass inputs with `keep_inference_input_mutations` on and off, `default_partition` under activation checkpointing, and an honored `MUST_RECOMPUTE` (warning logged); reads of unmutated inputs are still recomputed. With the base `partitioners.py` swapped in, every new mutating case fails (wrong gradients or `modified by an inplace operation`; for BatchNorm only its structural `assertNotIn` check fails, its gradients match eager either way).
Results: `TestPartitioning` 142 pass, 0 fail; the broader filter 313 pass, 0 fail.
Descriptor discovery check, with a temporary uncommitted test that wraps `min_cut_rematerialization_partition` and compares the descriptor-derived mutated placeholders with the earlier `input_info.mutates_data`-based names, for a buffer, a `TwoTensor` buffer, a nested `TwoTensor` buffer, no-grad and requires-grad inputs, data plus metadata, and metadata-only mutations, each with `keep_inference_input_mutations` on and off: identical everywhere except metadata-only, which only the descriptors catch; with it pinned, gradients match eager.
Inductor BatchNorm check, with a temporary uncommitted test in `TestPartitioning` that compiles training-mode Conv2d(3, 4) -> BatchNorm2d(4) -> ReLU on a (2, 3, 8, 8) CPU input with `torch.compile(backend="inductor")` (caches disabled), wraps `min_cut_rematerialization_partition` in `torch._inductor.compile_fx` to record the backward graph's non-tangent placeholders, and runs with the pin on and with `force_save_fw_mutated_input_readers` patched to a no-op:
```
buck2 test fbcode//mode/opt fbcode//caffe2/test/functorch:test_aotdispatch -- --regex 'test_zz_tmp_inductor_bn_saved' --print-passing-details
```
The joint graph has no `batch_norm` op (already decomposed) and three `copy_` into the BN buffers (`running_mean`, `running_var`, `num_batches_tracked`). The pin tags `add`, `mul_2`, and `mul_5` (the buffer updates) and nothing the backward reads. Saved sets, identical with and without the pin; gradients and running stats match eager:
- default budget: `primals_1` (4, 3, 3, 3), `primals_3` (2, 3, 8, 8), `primals_7` (4,), `convolution` (2, 4, 8, 8), `squeeze_1` (4,), `le` (2, 4, 8, 8), `unsqueeze_6` (1, 4, 1, 1)
- budget 0: inputs only, `primals_1` (4, 3, 3, 3), `primals_2` (4,), `primals_3` (2, 3, 8, 8), `primals_7` (4,), `primals_8` (4,)
- budget 0.05: the same five inputs plus `getitem_1` (1, 4, 1, 1) and `rsqrt` (1, 4, 1, 1)

Who-hits-this check, with a temporary uncommitted test `test_zzprobe_default_budget` in `TestPartitioning` that compiles `C2` above and the model from `test_min_cut_no_recompute_through_mutated_input` with `torch.compile(backend="inductor")` and `backend="aot_eager"` at the default budget (`activation_memory_budget = 1.0` in `torch/_functorch/config.py`, left unpatched), 0, and 0.05, with the pin on and with `force_save_fw_mutated_input_readers` patched to a no-op. Caches are disabled (`torch.compiler.config.patch(force_disable_caches=True)`, `torch._functorch.config.patch(enable_autograd_cache=False)`), `torch._dynamo.reset()` runs before each compile, and `x.grad` and the buffer are compared against eager on a deepcopy of the module:
```
buck2 test fbcode//mode/opt fbcode//caffe2/test/functorch:test_aotdispatch -- --regex test_zzprobe --print-passing-details
```
- pin off, default budget: `C2` grads wrong (16/16) under both backends; gather model grads match eager under both.
- pin off, budgets 0 and 0.05: both models wrong under both backends (`C2` 16/16, gather model 256/256).
- pin on: every case matches eager. The updated buffer matches eager in every case.

Differential Revision: D118411035
qchip added a commit to qchip/pytorch that referenced this pull request Oct 9, 2026
…h#197039)

Summary:
Pull Request resolved: pytorch#197039

The AOT min-cut partitioner may recompute a value in the backward rather than save it. That is equivalent only when re-execution is value-preserving, which fails for a read of an input the forward mutates: recompute defers the read past the mutation, so the backward observes post-update contents. The symptom is silently wrong gradients, or a version-counter error when the input reaches the backward through `SavedVariable`. Reads of these inputs are pinned `MUST_SAVE`, walking through aliasing ops to the first op that materializes data -- pinning a view pins an alias, not a snapshot. The comment on `force_save_fw_mutated_input_readers` walks through an example of the wrong and the correct partition.

Who hits this: default `torch.compile` (Inductor), whenever min-cut recomputes a read of an input the forward mutates in place, e.g. a registered buffer read by a pointwise op and then updated with `add_`. With the pin disabled, the buffer model below gets wrong gradients at the default budget (1.0) as well as at 0 and 0.05; the gather model in `test_min_cut_no_recompute_through_mutated_input` is wrong at 0 and 0.05 but matches eager at 1.0. `aot_eager` shows the same pattern. To compare pin on and off under Inductor, disable caches: the pin is not part of the AOTAutogradCache key, so the second compile can reuse the first one's graphs.
```
class C2(torch.nn.Module):
    def __init__(self):
        super().__init__()
        self.register_buffer("buf", torch.randn(16))

    def forward(self, x):
        y = (x * (self.buf * 2)).sum()  # eager grad_x = 2 * buf before add_
        self.buf.add_(1.0)
        return y
```

## Details

Aliasing is decided by storage, not op schema, since the `getitem`s of split/chunk/unbind have no schema. A tuple-producing op cannot be saved as a tensor, so its `getitem`s are pinned; the op itself is pinned too, since min-cut never bans recomputing a `getitem`.

Mutated inputs are found from metadata AOTAutograd already attaches to the joint graph, so no new metadata is added: forward outputs described by `InputMutationAOTOutput` for mutations the runtime epilogue applies (translated through `SubclassGetAttrAOTOutput` to the inner placeholders' descriptors), and `copy_` nodes tagged `must_be_in_forward` for mutations kept in the graph. This also covers metadata-only mutations such as `t_()`, which hit the same version-counter error today.

Behaviour changes, limited to the pinned reads:
- Activation checkpointing's `PREFER_RECOMPUTE` on such a read is overridden. An explicit `MUST_RECOMPUTE` from a user policy is honored, because the pin is conservative (it also hits reads that do not depend on the mutated data, such as BatchNorm's running-stat updates after decomposition); a one-time warning (`warning_once`) says gradients may be wrong, and the nodes are logged at debug level.
- `default_partition` runs the same pass. Under activation checkpointing it recomputed such reads: with a buffer read inside the checkpointed region and mutated after it, base raises the version-counter error with `keep_inference_input_mutations=False` and gives `2 * (buf + 1)` with `True`; this gives `2 * buf`, matching the function without checkpointing. Eager checkpointing itself recomputes after the mutation and also gives `2 * (buf + 1)`, so the compiled result now matches the un-checkpointed function rather than eager checkpointing.
- `memory_budget == 0` saved only the inputs. It now also saves the pinned reads, including a `getitem` of a forward op that only the backward reads, such as BatchNorm's `save_mean`. Other `MUST_SAVE` marks are still recomputed at budget 0, as before.

Behavior change for BatchNorm: on backends that keep BatchNorm as a single op (eager-style backends such as `aot_eager`), training BatchNorm's outputs are now saved rather than recomputed. This is conservative: the partitioner only sees that `_native_batch_norm_legit_functional` reads the mutated running stats, not that `out`, `save_mean`, and `save_rstd` depend only on batch stats. It costs memory, not correctness; for conv -> BN -> ReLU at budget 0, the full (2, 4, 8, 8) BN output and four (4,) vectors are saved where trunk saves only the inputs, and gradients match eager in both. Under Inductor it is not an issue, because Inductor decomposes BN before partitioning: on the same model, the saved-for-backward set is identical with and without the pin at the default budget and at budgets 0 and 0.05, and the pin lands only on the small running-stat update ops, which feed `copy_` rather than the backward. A follow-up that snapshots each mutated input (clone before the mutation, ban recomputing the clone) and lets min-cut choose between saving the snapshot and saving the reads would remove this over-save.

Relation to pytorch#185876 (`aot_runtime_epilogue_input_mutation`): that stops min-cut from saving the placeholder of an input that requires grad and is mutated by the runtime epilogue. This covers inputs that do not require grad, such as buffers, mutations kept in the graph, and metadata-only mutations. Where both apply the results agree.
Buffers mutated by a different compiled region or by eager code are invisible to this graph; an opt-in fix follows in a separate PR.

This PR was authored with an AI assistant.

Test Plan:
```
buck2 test fbcode//mode/opt fbcode//caffe2/test/functorch:test_aotdispatch -- -r 'TestPartitioning'
buck2 test fbcode//mode/opt fbcode//caffe2/test/functorch:test_aotdispatch -- -r 'partition|Partition|mutation|Mutation|checkpoint'
```
`TestPartitioning` covers reads through a view, a tuple-producing view, a tuple-producing op read by the backward (budgets 0, 0.05, 0.5), the updated value, a metadata-only mutation (`t_()`), BatchNorm's saved statistics, several gathers at budget 0.05, flat and subclass inputs with `keep_inference_input_mutations` on and off, `default_partition` under activation checkpointing, and an honored `MUST_RECOMPUTE` (warning logged); reads of unmutated inputs are still recomputed. With the base `partitioners.py` swapped in, every new mutating case fails (wrong gradients or `modified by an inplace operation`; for BatchNorm only its structural `assertNotIn` check fails, its gradients match eager either way).
Results: `TestPartitioning` 142 pass, 0 fail; the broader filter 313 pass, 0 fail.
Descriptor discovery check, with a temporary uncommitted test that wraps `min_cut_rematerialization_partition` and compares the descriptor-derived mutated placeholders with the earlier `input_info.mutates_data`-based names, for a buffer, a `TwoTensor` buffer, a nested `TwoTensor` buffer, no-grad and requires-grad inputs, data plus metadata, and metadata-only mutations, each with `keep_inference_input_mutations` on and off: identical everywhere except metadata-only, which only the descriptors catch; with it pinned, gradients match eager.
Inductor BatchNorm check, with a temporary uncommitted test in `TestPartitioning` that compiles training-mode Conv2d(3, 4) -> BatchNorm2d(4) -> ReLU on a (2, 3, 8, 8) CPU input with `torch.compile(backend="inductor")` (caches disabled), wraps `min_cut_rematerialization_partition` in `torch._inductor.compile_fx` to record the backward graph's non-tangent placeholders, and runs with the pin on and with `force_save_fw_mutated_input_readers` patched to a no-op:
```
buck2 test fbcode//mode/opt fbcode//caffe2/test/functorch:test_aotdispatch -- --regex 'test_zz_tmp_inductor_bn_saved' --print-passing-details
```
The joint graph has no `batch_norm` op (already decomposed) and three `copy_` into the BN buffers (`running_mean`, `running_var`, `num_batches_tracked`). The pin tags `add`, `mul_2`, and `mul_5` (the buffer updates) and nothing the backward reads. Saved sets, identical with and without the pin; gradients and running stats match eager:
- default budget: `primals_1` (4, 3, 3, 3), `primals_3` (2, 3, 8, 8), `primals_7` (4,), `convolution` (2, 4, 8, 8), `squeeze_1` (4,), `le` (2, 4, 8, 8), `unsqueeze_6` (1, 4, 1, 1)
- budget 0: inputs only, `primals_1` (4, 3, 3, 3), `primals_2` (4,), `primals_3` (2, 3, 8, 8), `primals_7` (4,), `primals_8` (4,)
- budget 0.05: the same five inputs plus `getitem_1` (1, 4, 1, 1) and `rsqrt` (1, 4, 1, 1)

Who-hits-this check, with a temporary uncommitted test `test_zzprobe_default_budget` in `TestPartitioning` that compiles `C2` above and the model from `test_min_cut_no_recompute_through_mutated_input` with `torch.compile(backend="inductor")` and `backend="aot_eager"` at the default budget (`activation_memory_budget = 1.0` in `torch/_functorch/config.py`, left unpatched), 0, and 0.05, with the pin on and with `force_save_fw_mutated_input_readers` patched to a no-op. Caches are disabled (`torch.compiler.config.patch(force_disable_caches=True)`, `torch._functorch.config.patch(enable_autograd_cache=False)`), `torch._dynamo.reset()` runs before each compile, and `x.grad` and the buffer are compared against eager on a deepcopy of the module:
```
buck2 test fbcode//mode/opt fbcode//caffe2/test/functorch:test_aotdispatch -- --regex test_zzprobe --print-passing-details
```
- pin off, default budget: `C2` grads wrong (16/16) under both backends; gather model grads match eager under both.
- pin off, budgets 0 and 0.05: both models wrong under both backends (`C2` 16/16, gather model 256/256).
- pin on: every case matches eager. The updated buffer matches eager in every case.

Differential Revision: D118411035
cyyever pushed a commit to BakeLab/pytorch that referenced this pull request Oct 11, 2026
pytorch#199663)

The three test_interpolate_mutated_input_backward tests added in pytorch#185876 fail
consistently in the periodic nogpu_NO_AVX2 config:

```
AssertionError: Tensor-likes are not close!
Mismatched elements: 1 / 3 (33.3%)
Greatest absolute difference: 0.0005950927734375 at index (0, 0, 0) (up to 1e-05 allowed)
Greatest relative difference: 3.6538310723699396e-06 at index (0, 0, 0) (up to 1.3e-06 allowed)
```

This is float32 summation error, not a correctness bug. The mismatching tensor
is mean.grad, where each element is a sum of 256 float32 values (about 313 in
magnitude). Eager computes it with ATen's cascade_sum and is accurate to about
2e-8 relative. nogpu_NO_AVX2 sets ATEN_CPU_CAPABILITY=default, which Inductor
also uses to pick its vector ISA, so the compiled kernel is scalar. Inductor's
scalar reductions are a single running sum (its CascadeSumHelper is only used by
vectorized kernels, in 4096-element chunks), which is about 2e-6 relative off
here, just over assertEqual's default float32 rtol of 1.3e-6. Vectorized builds
keep one accumulator per lane and pass.

The fix compares with atol=1e-4 and rtol=1e-4, as the neighboring gradient tests
in this file do. The alternative, giving Inductor's scalar CPU reductions
cascade summation, would be a codegen change with performance cost and is out of
scope for a test failure.

Test Plan:

```
ATEN_CPU_CAPABILITY=default python -m pytest test/inductor/test_cpu_repro.py -k test_interpolate_mutated_input_backward
python -m pytest test/inductor/test_cpu_repro.py -k test_interpolate_mutated_input_backward
```

All three pass in both configurations; before the change they failed with
ATEN_CPU_CAPABILITY=default with the same numbers as CI. With pytorch#185876's
torch/ changes reverted, all three still fail with "one of the variables needed
for gradient computation has been modified by an inplace operation", so the
looser tolerance doesn't hide the bug the tests guard against.

This PR was authored with the help of an AI assistant.

Pull Request resolved: pytorch#199663
Approved by: https://github.com/jansel
qchip added a commit to qchip/pytorch that referenced this pull request Oct 30, 2026
…h#197039)

Summary:

The AOT min-cut partitioner may recompute a value in the backward rather than save it. That is equivalent only when re-execution is value-preserving, which fails for a read of an input the forward mutates: recompute defers the read past the mutation, so the backward observes post-update contents. The symptom is silently wrong gradients, or a version-counter error when the input reaches the backward through `SavedVariable`. Reads of these inputs are pinned `MUST_SAVE`, walking through aliasing ops to the first op that materializes data -- pinning a view pins an alias, not a snapshot. The comment on `force_save_fw_mutated_input_readers` walks through an example of the wrong and the correct partition.

Who hits this: default `torch.compile` (Inductor), whenever min-cut recomputes a read of an input the forward mutates in place, e.g. a registered buffer read by a pointwise op and then updated with `add_`. With the pin disabled, the buffer model below gets wrong gradients at the default budget (1.0) as well as at 0 and 0.05; the gather model in `test_min_cut_no_recompute_through_mutated_input` is wrong at 0 and 0.05 but matches eager at 1.0. `aot_eager` shows the same pattern. To compare pin on and off under Inductor, disable caches: the pin is not part of the AOTAutogradCache key, so the second compile can reuse the first one's graphs.
```
class C2(torch.nn.Module):
    def __init__(self):
        super().__init__()
        self.register_buffer("buf", torch.randn(16))

    def forward(self, x):
        y = (x * (self.buf * 2)).sum()  # eager grad_x = 2 * buf before add_
        self.buf.add_(1.0)
        return y
```

## Details

Aliasing is decided by storage, not op schema, since the `getitem`s of split/chunk/unbind have no schema. A tuple-producing op cannot be saved as a tensor, so every `getitem` below it is pinned, including the nested levels of a `Tensor[]` output; the op itself is pinned too, since min-cut never bans recomputing a `getitem`. `force_save_collectives` and `force_save_effectful_ops` now share this walker (`_leaf_results`) instead of their own recursive copies, with no behavior change.

Mutated inputs are found from metadata AOTAutograd already attaches to the joint graph, so no new metadata is added: forward outputs described by `InputMutationAOTOutput` for mutations the runtime epilogue applies (translated through `SubclassGetAttrAOTOutput` to the inner placeholders' descriptors), and write-backs tagged `must_be_in_forward` (`copy_`, `set_`, `resize_storage_bytes_`) for mutations kept in the graph, so a buffer swapped with `set_` under `no_grad` is found too. This also covers metadata-only mutations such as `t_()`, which hit the same version-counter error today.

Behaviour changes, limited to the pinned reads:
- Activation checkpointing's `PREFER_RECOMPUTE` on such a read is overridden. An explicit `MUST_RECOMPUTE` from a user policy is honored, because the pin is conservative (it also hits reads that do not depend on the mutated data, such as BatchNorm's running-stat updates after decomposition); a one-time warning (`warning_once`) says gradients may be wrong, and the nodes are logged at debug level.
- `default_partition` runs the same pass. Under activation checkpointing it recomputed such reads: with a buffer read inside the checkpointed region and mutated after it, base raises the version-counter error with `keep_inference_input_mutations=False` and gives `2 * (buf + 1)` with `True`; this gives `2 * buf`, matching the function without checkpointing. Eager checkpointing itself recomputes after the mutation and also gives `2 * (buf + 1)`, so the compiled result now matches the un-checkpointed function rather than eager checkpointing.
- `memory_budget == 0` saved only the inputs. It now also saves the pinned reads, including a `getitem` of a forward op that only the backward reads, such as BatchNorm's `save_mean`. Other `MUST_SAVE` marks are still recomputed at budget 0, as before.

Behavior change for BatchNorm: on backends that keep BatchNorm as a single op (eager-style backends such as `aot_eager`), training BatchNorm's outputs are now saved rather than recomputed. This is conservative: the partitioner only sees that `_native_batch_norm_legit_functional` reads the mutated running stats, not that `out`, `save_mean`, and `save_rstd` depend only on batch stats. It costs memory, not correctness; for conv -> BN -> ReLU at budget 0, the full (2, 4, 8, 8) BN output and four (4,) vectors are saved where trunk saves only the inputs, and gradients match eager in both. Under Inductor it is not an issue, because Inductor decomposes BN before partitioning: on the same model, the saved-for-backward set is identical with and without the pin at the default budget and at budgets 0 and 0.05, and the pin lands only on the small running-stat update ops, which feed `copy_` rather than the backward. A follow-up that snapshots each mutated input (clone before the mutation, ban recomputing the clone) and lets min-cut choose between saving the snapshot and saving the reads would remove this over-save.

Relation to pytorch#185876 (`aot_runtime_epilogue_input_mutation`): that stops min-cut from saving the placeholder of an input that requires grad and is mutated by the runtime epilogue. This covers inputs that do not require grad, such as buffers, mutations kept in the graph, and metadata-only mutations. Where both apply the results agree.
Buffers mutated by a different compiled region or by eager code are invisible to this graph; an opt-in fix follows in a separate PR.

This PR was authored with an AI assistant.

Test Plan:
```
buck2 test fbcode//mode/opt fbcode//caffe2/test/functorch:test_aotdispatch -- -r 'TestPartitioning'
buck2 test fbcode//mode/opt fbcode//caffe2/test/functorch:test_aotdispatch -- -r 'partition|Partition|mutation|Mutation|checkpoint'
buck2 test fbcode//mode/opt fbcode//caffe2/test/functorch:test_aotdispatch -- --regex 'force_save_effectful|effect_tokens|with_effects'
buck2 test fbcode//mode/opt fbcode//caffe2/test/distributed/tensor:dtensor_compile
```
`TestPartitioning` covers reads through a view, a tuple-producing view, a tuple-producing op read by the backward (budgets 0, 0.05, 0.5), a `(Tensor, Tensor[])` reader under activation checkpointing (budgets 0 and 1.0), an input swapped with `set_` under `no_grad` (`keep_inference_input_mutations=True`, budgets 0 and 1.0), the buffer model above at the default budget, the updated value, a metadata-only mutation (`t_()`), BatchNorm's saved statistics, several gathers at budget 0.05, flat and subclass inputs with `keep_inference_input_mutations` on and off, `default_partition` under activation checkpointing, and an honored `MUST_RECOMPUTE` (warning logged); reads of unmutated inputs are still recomputed. With the base `partitioners.py` swapped in, every new mutating case fails (wrong gradients or `modified by an inplace operation`; for BatchNorm only its structural `assertNotIn` check fails, its gradients match eager either way).
Results: `TestPartitioning` 147 pass, 0 fail; the broader filter 318 pass, 3 fail, all `test_saved_tensors_hooks_mutations_raise`, which hardcodes `device="cuda"` and fails in `torch.ones` with `CUDA error: invalid argument` on this host before compiling; the effectful-op tests 14 pass, 0 fail (they cover the shared walker); `dtensor_compile` 72 pass, 0 fail, 22 skipped.
Descriptor discovery check, with a temporary uncommitted test that wraps `min_cut_rematerialization_partition` and compares the descriptor-derived mutated placeholders with the earlier `input_info.mutates_data`-based names, for a buffer, a `TwoTensor` buffer, a nested `TwoTensor` buffer, no-grad and requires-grad inputs, data plus metadata, and metadata-only mutations, each with `keep_inference_input_mutations` on and off: identical everywhere except metadata-only, which only the descriptors catch; with it pinned, gradients match eager.
Inductor BatchNorm check, with a temporary uncommitted test in `TestPartitioning` that compiles training-mode Conv2d(3, 4) -> BatchNorm2d(4) -> ReLU on a (2, 3, 8, 8) CPU input with `torch.compile(backend="inductor")` (caches disabled), wraps `min_cut_rematerialization_partition` in `torch._inductor.compile_fx` to record the backward graph's non-tangent placeholders, and runs with the pin on and with `force_save_fw_mutated_input_readers` patched to a no-op:
```
buck2 test fbcode//mode/opt fbcode//caffe2/test/functorch:test_aotdispatch -- --regex 'test_zz_tmp_inductor_bn_saved' --print-passing-details
```
The joint graph has no `batch_norm` op (already decomposed) and three `copy_` into the BN buffers (`running_mean`, `running_var`, `num_batches_tracked`). The pin tags `add`, `mul_2`, and `mul_5` (the buffer updates) and nothing the backward reads. Saved sets, identical with and without the pin; gradients and running stats match eager:
- default budget: `primals_1` (4, 3, 3, 3), `primals_3` (2, 3, 8, 8), `primals_7` (4,), `convolution` (2, 4, 8, 8), `squeeze_1` (4,), `le` (2, 4, 8, 8), `unsqueeze_6` (1, 4, 1, 1)
- budget 0: inputs only, `primals_1` (4, 3, 3, 3), `primals_2` (4,), `primals_3` (2, 3, 8, 8), `primals_7` (4,), `primals_8` (4,)
- budget 0.05: the same five inputs plus `getitem_1` (1, 4, 1, 1) and `rsqrt` (1, 4, 1, 1)

Who-hits-this check, with a temporary uncommitted test `test_zzprobe_default_budget` in `TestPartitioning` that compiles `C2` above and the model from `test_min_cut_no_recompute_through_mutated_input` with `torch.compile(backend="inductor")` and `backend="aot_eager"` at the default budget (`activation_memory_budget = 1.0` in `torch/_functorch/config.py`, left unpatched), 0, and 0.05, with the pin on and with `force_save_fw_mutated_input_readers` patched to a no-op. Caches are disabled (`torch.compiler.config.patch(force_disable_caches=True)`, `torch._functorch.config.patch(enable_autograd_cache=False)`), `torch._dynamo.reset()` runs before each compile, and `x.grad` and the buffer are compared against eager on a deepcopy of the module:
```
buck2 test fbcode//mode/opt fbcode//caffe2/test/functorch:test_aotdispatch -- --regex test_zzprobe --print-passing-details
```
- pin off, default budget: `C2` grads wrong (16/16) under both backends; gather model grads match eager under both.
- pin off, budgets 0 and 0.05: both models wrong under both backends (`C2` 16/16, gather model 256/256).
- pin on: every case matches eager. The updated buffer matches eager in every case.

Differential Revision: D118411035
qchip added a commit to qchip/pytorch that referenced this pull request Nov 2, 2026
…h#197039)

Summary:

The AOT min-cut partitioner may recompute a value in the backward rather than save it. That is equivalent only when re-execution is value-preserving, which fails for a read of an input the forward mutates: recompute defers the read past the mutation, so the backward observes post-update contents. The symptom is silently wrong gradients, or a version-counter error when the input reaches the backward through `SavedVariable`. Reads of these inputs are pinned `MUST_SAVE`, walking through aliasing ops to the first op that materializes data -- pinning a view pins an alias, not a snapshot. The comment on `force_save_fw_mutated_input_readers` walks through an example of the wrong and the correct partition.

Who hits this: default `torch.compile` (Inductor), whenever min-cut recomputes a read of an input the forward mutates in place, e.g. a registered buffer read by a pointwise op and then updated with `add_`. With the pin disabled, the buffer model below gets wrong gradients at the default budget (1.0) as well as at 0 and 0.05; the gather model in `test_min_cut_no_recompute_through_mutated_input` is wrong at 0 and 0.05 but matches eager at 1.0. `aot_eager` shows the same pattern. To compare pin on and off under Inductor, disable caches: the pin is not part of the AOTAutogradCache key, so the second compile can reuse the first one's graphs.
```
class C2(torch.nn.Module):
    def __init__(self):
        super().__init__()
        self.register_buffer("buf", torch.randn(16))

    def forward(self, x):
        y = (x * (self.buf * 2)).sum()  # eager grad_x = 2 * buf before add_
        self.buf.add_(1.0)
        return y
```

## Details

Aliasing is decided by storage, not op schema, since the `getitem`s of split/chunk/unbind have no schema. A tuple-producing op cannot be saved as a tensor, so every `getitem` below it is pinned, including the nested levels of a `Tensor[]` output; the op itself is pinned too, since min-cut never bans recomputing a `getitem`. `force_save_collectives` and `force_save_effectful_ops` now share this walker (`_leaf_results`) instead of their own recursive copies, with no behavior change.

Mutated inputs are found from metadata AOTAutograd already attaches to the joint graph, so no new metadata is added: forward outputs described by `InputMutationAOTOutput` for mutations the runtime epilogue applies (translated through `SubclassGetAttrAOTOutput` to the inner placeholders' descriptors), and write-backs tagged `must_be_in_forward` (`copy_`, `set_`, `resize_storage_bytes_`) for mutations kept in the graph, so a buffer swapped with `set_` under `no_grad` is found too. This also covers metadata-only mutations such as `t_()`, which hit the same version-counter error today.

Behaviour changes, limited to the pinned reads:
- Activation checkpointing's `PREFER_RECOMPUTE` on such a read is overridden. An explicit `MUST_RECOMPUTE` from a user policy is honored, because the pin is conservative (it also hits reads that do not depend on the mutated data, such as BatchNorm's running-stat updates after decomposition); a one-time warning (`warning_once`) says gradients may be wrong, and the nodes are logged at debug level.
- `default_partition` runs the same pass. Under activation checkpointing it recomputed such reads: with a buffer read inside the checkpointed region and mutated after it, base raises the version-counter error with `keep_inference_input_mutations=False` and gives `2 * (buf + 1)` with `True`; this gives `2 * buf`, matching the function without checkpointing. Eager checkpointing itself recomputes after the mutation and also gives `2 * (buf + 1)`, so the compiled result now matches the un-checkpointed function rather than eager checkpointing.
- `memory_budget == 0` saved only the inputs. It now also saves the pinned reads, including a `getitem` of a forward op that only the backward reads, such as BatchNorm's `save_mean`. Other `MUST_SAVE` marks are still recomputed at budget 0, as before.

Behavior change for BatchNorm: on backends that keep BatchNorm as a single op (eager-style backends such as `aot_eager`), training BatchNorm's outputs are now saved rather than recomputed. This is conservative: the partitioner only sees that `_native_batch_norm_legit_functional` reads the mutated running stats, not that `out`, `save_mean`, and `save_rstd` depend only on batch stats. It costs memory, not correctness; for conv -> BN -> ReLU at budget 0, the full (2, 4, 8, 8) BN output and four (4,) vectors are saved where trunk saves only the inputs, and gradients match eager in both. Under Inductor it is not an issue, because Inductor decomposes BN before partitioning: on the same model, the saved-for-backward set is identical with and without the pin at the default budget and at budgets 0 and 0.05, and the pin lands only on the small running-stat update ops, which feed `copy_` rather than the backward. A follow-up that snapshots each mutated input (clone before the mutation, ban recomputing the clone) and lets min-cut choose between saving the snapshot and saving the reads would remove this over-save.

Relation to pytorch#185876 (`aot_runtime_epilogue_input_mutation`): that stops min-cut from saving the placeholder of an input that requires grad and is mutated by the runtime epilogue. This covers inputs that do not require grad, such as buffers, mutations kept in the graph, and metadata-only mutations. Where both apply the results agree.
Buffers mutated by a different compiled region or by eager code are invisible to this graph; an opt-in fix follows in a separate PR.

This PR was authored with an AI assistant.

Test Plan:
```
buck2 test fbcode//mode/opt fbcode//caffe2/test/functorch:test_aotdispatch -- -r 'TestPartitioning'
buck2 test fbcode//mode/opt fbcode//caffe2/test/functorch:test_aotdispatch -- -r 'partition|Partition|mutation|Mutation|checkpoint'
buck2 test fbcode//mode/opt fbcode//caffe2/test/functorch:test_aotdispatch -- --regex 'force_save_effectful|effect_tokens|with_effects'
buck2 test fbcode//mode/opt fbcode//caffe2/test/distributed/tensor:dtensor_compile
```
`TestPartitioning` covers reads through a view, a tuple-producing view, a tuple-producing op read by the backward (budgets 0, 0.05, 0.5), a `(Tensor, Tensor[])` reader under activation checkpointing (budgets 0 and 1.0), an input swapped with `set_` under `no_grad` (`keep_inference_input_mutations=True`, budgets 0 and 1.0), the buffer model above at the default budget, the updated value, a metadata-only mutation (`t_()`), BatchNorm's saved statistics, several gathers at budget 0.05, flat and subclass inputs with `keep_inference_input_mutations` on and off, `default_partition` under activation checkpointing, and an honored `MUST_RECOMPUTE` (warning logged); reads of unmutated inputs are still recomputed. With the base `partitioners.py` swapped in, every new mutating case fails (wrong gradients or `modified by an inplace operation`; for BatchNorm only its structural `assertNotIn` check fails, its gradients match eager either way).
Results: `TestPartitioning` 147 pass, 0 fail; the broader filter 318 pass, 3 fail, all `test_saved_tensors_hooks_mutations_raise`, which hardcodes `device="cuda"` and fails in `torch.ones` with `CUDA error: invalid argument` on this host before compiling; the effectful-op tests 14 pass, 0 fail (they cover the shared walker); `dtensor_compile` 72 pass, 0 fail, 22 skipped.
Descriptor discovery check, with a temporary uncommitted test that wraps `min_cut_rematerialization_partition` and compares the descriptor-derived mutated placeholders with the earlier `input_info.mutates_data`-based names, for a buffer, a `TwoTensor` buffer, a nested `TwoTensor` buffer, no-grad and requires-grad inputs, data plus metadata, and metadata-only mutations, each with `keep_inference_input_mutations` on and off: identical everywhere except metadata-only, which only the descriptors catch; with it pinned, gradients match eager.
Inductor BatchNorm check, with a temporary uncommitted test in `TestPartitioning` that compiles training-mode Conv2d(3, 4) -> BatchNorm2d(4) -> ReLU on a (2, 3, 8, 8) CPU input with `torch.compile(backend="inductor")` (caches disabled), wraps `min_cut_rematerialization_partition` in `torch._inductor.compile_fx` to record the backward graph's non-tangent placeholders, and runs with the pin on and with `force_save_fw_mutated_input_readers` patched to a no-op:
```
buck2 test fbcode//mode/opt fbcode//caffe2/test/functorch:test_aotdispatch -- --regex 'test_zz_tmp_inductor_bn_saved' --print-passing-details
```
The joint graph has no `batch_norm` op (already decomposed) and three `copy_` into the BN buffers (`running_mean`, `running_var`, `num_batches_tracked`). The pin tags `add`, `mul_2`, and `mul_5` (the buffer updates) and nothing the backward reads. Saved sets, identical with and without the pin; gradients and running stats match eager:
- default budget: `primals_1` (4, 3, 3, 3), `primals_3` (2, 3, 8, 8), `primals_7` (4,), `convolution` (2, 4, 8, 8), `squeeze_1` (4,), `le` (2, 4, 8, 8), `unsqueeze_6` (1, 4, 1, 1)
- budget 0: inputs only, `primals_1` (4, 3, 3, 3), `primals_2` (4,), `primals_3` (2, 3, 8, 8), `primals_7` (4,), `primals_8` (4,)
- budget 0.05: the same five inputs plus `getitem_1` (1, 4, 1, 1) and `rsqrt` (1, 4, 1, 1)

Who-hits-this check, with a temporary uncommitted test `test_zzprobe_default_budget` in `TestPartitioning` that compiles `C2` above and the model from `test_min_cut_no_recompute_through_mutated_input` with `torch.compile(backend="inductor")` and `backend="aot_eager"` at the default budget (`activation_memory_budget = 1.0` in `torch/_functorch/config.py`, left unpatched), 0, and 0.05, with the pin on and with `force_save_fw_mutated_input_readers` patched to a no-op. Caches are disabled (`torch.compiler.config.patch(force_disable_caches=True)`, `torch._functorch.config.patch(enable_autograd_cache=False)`), `torch._dynamo.reset()` runs before each compile, and `x.grad` and the buffer are compared against eager on a deepcopy of the module:
```
buck2 test fbcode//mode/opt fbcode//caffe2/test/functorch:test_aotdispatch -- --regex test_zzprobe --print-passing-details
```
- pin off, default budget: `C2` grads wrong (16/16) under both backends; gather model grads match eager under both.
- pin off, budgets 0 and 0.05: both models wrong under both backends (`C2` 16/16, gather model 256/256).
- pin on: every case matches eager. The updated buffer matches eager in every case.

Differential Revision: D118411035
qchip added a commit to qchip/pytorch that referenced this pull request Nov 3, 2026
…h#197039)

Summary:

The AOT min-cut partitioner may recompute a value in the backward rather than save it. That is equivalent only when re-execution is value-preserving, which fails for a read of an input the forward mutates: recompute defers the read past the mutation, so the backward observes post-update contents. The symptom is silently wrong gradients, or a version-counter error when the input reaches the backward through `SavedVariable`. Reads of these inputs are pinned `MUST_SAVE`, walking through aliasing ops to the first op that materializes data -- pinning a view pins an alias, not a snapshot. The comment on `force_save_fw_mutated_input_readers` walks through an example of the wrong and the correct partition.

Who hits this: default `torch.compile` (Inductor), whenever min-cut recomputes a read of an input the forward mutates in place, e.g. a registered buffer read by a pointwise op and then updated with `add_`. With the pin disabled, the buffer model below gets wrong gradients at the default budget (1.0) as well as at 0 and 0.05; the gather model in `test_min_cut_no_recompute_through_mutated_input` is wrong at 0 and 0.05 but matches eager at 1.0. `aot_eager` shows the same pattern. To compare pin on and off under Inductor, disable caches: the pin is not part of the AOTAutogradCache key, so the second compile can reuse the first one's graphs.
```
class C2(torch.nn.Module):
    def __init__(self):
        super().__init__()
        self.register_buffer("buf", torch.randn(16))

    def forward(self, x):
        y = (x * (self.buf * 2)).sum()  # eager grad_x = 2 * buf before add_
        self.buf.add_(1.0)
        return y
```

## Details

Aliasing is decided by storage, not op schema, since the `getitem`s of split/chunk/unbind have no schema. A tuple-producing op cannot be saved as a tensor, so every `getitem` below it is pinned, including the nested levels of a `Tensor[]` output; the op itself is pinned too, since min-cut never bans recomputing a `getitem`. `force_save_collectives` and `force_save_effectful_ops` now share this walker (`_leaf_results`) instead of their own recursive copies, with no behavior change.

Mutated inputs are found from metadata AOTAutograd already attaches to the joint graph, so no new metadata is added: forward outputs described by `InputMutationAOTOutput` for mutations the runtime epilogue applies (translated through `SubclassGetAttrAOTOutput` to the inner placeholders' descriptors), and write-backs tagged `must_be_in_forward` (`copy_`, `set_`, `resize_storage_bytes_`) for mutations kept in the graph, so a buffer swapped with `set_` under `no_grad` is found too. This also covers metadata-only mutations such as `t_()`, which hit the same version-counter error today.

Behaviour changes, limited to the pinned reads:
- Activation checkpointing's `PREFER_RECOMPUTE` on such a read is overridden. An explicit `MUST_RECOMPUTE` from a user policy is honored, because the pin is conservative (it also hits reads that do not depend on the mutated data, such as BatchNorm's running-stat updates after decomposition); a one-time warning (`warning_once`) says gradients may be wrong, and the nodes are logged at debug level.
- `default_partition` runs the same pass. Under activation checkpointing it recomputed such reads: with a buffer read inside the checkpointed region and mutated after it, base raises the version-counter error with `keep_inference_input_mutations=False` and gives `2 * (buf + 1)` with `True`; this gives `2 * buf`, matching the function without checkpointing. Eager checkpointing itself recomputes after the mutation and also gives `2 * (buf + 1)`, so the compiled result now matches the un-checkpointed function rather than eager checkpointing.
- `memory_budget == 0` saved only the inputs. It now also saves the pinned reads, including a `getitem` of a forward op that only the backward reads, such as BatchNorm's `save_mean`. Other `MUST_SAVE` marks are still recomputed at budget 0, as before.

Behavior change for BatchNorm: on backends that keep BatchNorm as a single op (eager-style backends such as `aot_eager`), training BatchNorm's outputs are now saved rather than recomputed. This is conservative: the partitioner only sees that `_native_batch_norm_legit_functional` reads the mutated running stats, not that `out`, `save_mean`, and `save_rstd` depend only on batch stats. It costs memory, not correctness; for conv -> BN -> ReLU at budget 0, the full (2, 4, 8, 8) BN output and four (4,) vectors are saved where trunk saves only the inputs, and gradients match eager in both. Under Inductor it is not an issue, because Inductor decomposes BN before partitioning: on the same model, the saved-for-backward set is identical with and without the pin at the default budget and at budgets 0 and 0.05, and the pin lands only on the small running-stat update ops, which feed `copy_` rather than the backward. A follow-up that snapshots each mutated input (clone before the mutation, ban recomputing the clone) and lets min-cut choose between saving the snapshot and saving the reads would remove this over-save.

Relation to pytorch#185876 (`aot_runtime_epilogue_input_mutation`): that stops min-cut from saving the placeholder of an input that requires grad and is mutated by the runtime epilogue. This covers inputs that do not require grad, such as buffers, mutations kept in the graph, and metadata-only mutations. Where both apply the results agree.
Buffers mutated by a different compiled region or by eager code are invisible to this graph; an opt-in fix follows in a separate PR.

This PR was authored with an AI assistant.

Test Plan:
```
buck2 test fbcode//mode/opt fbcode//caffe2/test/functorch:test_aotdispatch -- -r 'TestPartitioning'
buck2 test fbcode//mode/opt fbcode//caffe2/test/functorch:test_aotdispatch -- -r 'partition|Partition|mutation|Mutation|checkpoint'
buck2 test fbcode//mode/opt fbcode//caffe2/test/functorch:test_aotdispatch -- --regex 'force_save_effectful|effect_tokens|with_effects'
buck2 test fbcode//mode/opt fbcode//caffe2/test/distributed/tensor:dtensor_compile
```
`TestPartitioning` covers reads through a view, a tuple-producing view, a tuple-producing op read by the backward (budgets 0, 0.05, 0.5), a `(Tensor, Tensor[])` reader under activation checkpointing (budgets 0 and 1.0), an input swapped with `set_` under `no_grad` (`keep_inference_input_mutations=True`, budgets 0 and 1.0), the buffer model above at the default budget, the updated value, a metadata-only mutation (`t_()`), BatchNorm's saved statistics, several gathers at budget 0.05, flat and subclass inputs with `keep_inference_input_mutations` on and off, `default_partition` under activation checkpointing, and an honored `MUST_RECOMPUTE` (warning logged); reads of unmutated inputs are still recomputed. With the base `partitioners.py` swapped in, every new mutating case fails (wrong gradients or `modified by an inplace operation`; for BatchNorm only its structural `assertNotIn` check fails, its gradients match eager either way).
Results: `TestPartitioning` 147 pass, 0 fail; the broader filter 318 pass, 3 fail, all `test_saved_tensors_hooks_mutations_raise`, which hardcodes `device="cuda"` and fails in `torch.ones` with `CUDA error: invalid argument` on this host before compiling; the effectful-op tests 14 pass, 0 fail (they cover the shared walker); `dtensor_compile` 72 pass, 0 fail, 22 skipped.
Descriptor discovery check, with a temporary uncommitted test that wraps `min_cut_rematerialization_partition` and compares the descriptor-derived mutated placeholders with the earlier `input_info.mutates_data`-based names, for a buffer, a `TwoTensor` buffer, a nested `TwoTensor` buffer, no-grad and requires-grad inputs, data plus metadata, and metadata-only mutations, each with `keep_inference_input_mutations` on and off: identical everywhere except metadata-only, which only the descriptors catch; with it pinned, gradients match eager.
Inductor BatchNorm check, with a temporary uncommitted test in `TestPartitioning` that compiles training-mode Conv2d(3, 4) -> BatchNorm2d(4) -> ReLU on a (2, 3, 8, 8) CPU input with `torch.compile(backend="inductor")` (caches disabled), wraps `min_cut_rematerialization_partition` in `torch._inductor.compile_fx` to record the backward graph's non-tangent placeholders, and runs with the pin on and with `force_save_fw_mutated_input_readers` patched to a no-op:
```
buck2 test fbcode//mode/opt fbcode//caffe2/test/functorch:test_aotdispatch -- --regex 'test_zz_tmp_inductor_bn_saved' --print-passing-details
```
The joint graph has no `batch_norm` op (already decomposed) and three `copy_` into the BN buffers (`running_mean`, `running_var`, `num_batches_tracked`). The pin tags `add`, `mul_2`, and `mul_5` (the buffer updates) and nothing the backward reads. Saved sets, identical with and without the pin; gradients and running stats match eager:
- default budget: `primals_1` (4, 3, 3, 3), `primals_3` (2, 3, 8, 8), `primals_7` (4,), `convolution` (2, 4, 8, 8), `squeeze_1` (4,), `le` (2, 4, 8, 8), `unsqueeze_6` (1, 4, 1, 1)
- budget 0: inputs only, `primals_1` (4, 3, 3, 3), `primals_2` (4,), `primals_3` (2, 3, 8, 8), `primals_7` (4,), `primals_8` (4,)
- budget 0.05: the same five inputs plus `getitem_1` (1, 4, 1, 1) and `rsqrt` (1, 4, 1, 1)

Who-hits-this check, with a temporary uncommitted test `test_zzprobe_default_budget` in `TestPartitioning` that compiles `C2` above and the model from `test_min_cut_no_recompute_through_mutated_input` with `torch.compile(backend="inductor")` and `backend="aot_eager"` at the default budget (`activation_memory_budget = 1.0` in `torch/_functorch/config.py`, left unpatched), 0, and 0.05, with the pin on and with `force_save_fw_mutated_input_readers` patched to a no-op. Caches are disabled (`torch.compiler.config.patch(force_disable_caches=True)`, `torch._functorch.config.patch(enable_autograd_cache=False)`), `torch._dynamo.reset()` runs before each compile, and `x.grad` and the buffer are compared against eager on a deepcopy of the module:
```
buck2 test fbcode//mode/opt fbcode//caffe2/test/functorch:test_aotdispatch -- --regex test_zzprobe --print-passing-details
```
- pin off, default budget: `C2` grads wrong (16/16) under both backends; gather model grads match eager under both.
- pin off, budgets 0 and 0.05: both models wrong under both backends (`C2` 16/16, gather model 256/256).
- pin on: every case matches eager. The updated buffer matches eager in every case.

Differential Revision: D118411035
qchip added a commit to qchip/pytorch that referenced this pull request Nov 3, 2026
…h#197039)

Summary:

The AOT min-cut partitioner may recompute a value in the backward rather than save it. That is equivalent only when re-execution is value-preserving, which fails for a read of an input the forward mutates: recompute defers the read past the mutation, so the backward observes post-update contents. The symptom is silently wrong gradients, or a version-counter error when the input reaches the backward through `SavedVariable`. Reads of these inputs are pinned `MUST_SAVE`, walking through aliasing ops to the first op that materializes data -- pinning a view pins an alias, not a snapshot. The comment on `force_save_fw_mutated_input_readers` walks through an example of the wrong and the correct partition.

Who hits this: default `torch.compile` (Inductor), whenever min-cut recomputes a read of an input the forward mutates in place, e.g. a registered buffer read by a pointwise op and then updated with `add_`. With the pin disabled, the buffer model below gets wrong gradients at the default budget (1.0) as well as at 0 and 0.05; the gather model in `test_min_cut_no_recompute_through_mutated_input` is wrong at 0 and 0.05 but matches eager at 1.0. `aot_eager` shows the same pattern. To compare pin on and off under Inductor, disable caches: the pin is not part of the AOTAutogradCache key, so the second compile can reuse the first one's graphs.
```
class C2(torch.nn.Module):
    def __init__(self):
        super().__init__()
        self.register_buffer("buf", torch.randn(16))

    def forward(self, x):
        y = (x * (self.buf * 2)).sum()  # eager grad_x = 2 * buf before add_
        self.buf.add_(1.0)
        return y
```

## Details

Aliasing is decided by storage, not op schema, since the `getitem`s of split/chunk/unbind have no schema. A tuple-producing op cannot be saved as a tensor, so every `getitem` below it is pinned, including the nested levels of a `Tensor[]` output; the op itself is pinned too, since min-cut never bans recomputing a `getitem`. `force_save_collectives` and `force_save_effectful_ops` now share this walker (`_leaf_results`) instead of their own recursive copies, with no behavior change.

Mutated inputs are found from metadata AOTAutograd already attaches to the joint graph, so no new metadata is added: forward outputs described by `InputMutationAOTOutput` for mutations the runtime epilogue applies (translated through `SubclassGetAttrAOTOutput` to the inner placeholders' descriptors), and write-backs tagged `must_be_in_forward` (`copy_`, `set_`, `resize_storage_bytes_`) for mutations kept in the graph, so a buffer swapped with `set_` under `no_grad` is found too. This also covers metadata-only mutations such as `t_()`, which hit the same version-counter error today.

Behaviour changes, limited to the pinned reads:
- Activation checkpointing's `PREFER_RECOMPUTE` on such a read is overridden. An explicit `MUST_RECOMPUTE` from a user policy is honored, because the pin is conservative (it also hits reads that do not depend on the mutated data, such as BatchNorm's running-stat updates after decomposition); a one-time warning (`warning_once`) says gradients may be wrong, and the nodes are logged at debug level.
- `default_partition` runs the same pass. Under activation checkpointing it recomputed such reads: with a buffer read inside the checkpointed region and mutated after it, base raises the version-counter error with `keep_inference_input_mutations=False` and gives `2 * (buf + 1)` with `True`; this gives `2 * buf`, matching the function without checkpointing. Eager checkpointing itself recomputes after the mutation and also gives `2 * (buf + 1)`, so the compiled result now matches the un-checkpointed function rather than eager checkpointing.
- `memory_budget == 0` saved only the inputs. It now also saves the pinned reads, including a `getitem` of a forward op that only the backward reads, such as BatchNorm's `save_mean`. Other `MUST_SAVE` marks are still recomputed at budget 0, as before.

Behavior change for BatchNorm: on backends that keep BatchNorm as a single op (eager-style backends such as `aot_eager`), training BatchNorm's outputs are now saved rather than recomputed. This is conservative: the partitioner only sees that `_native_batch_norm_legit_functional` reads the mutated running stats, not that `out`, `save_mean`, and `save_rstd` depend only on batch stats. It costs memory, not correctness; for conv -> BN -> ReLU at budget 0, the full (2, 4, 8, 8) BN output and four (4,) vectors are saved where trunk saves only the inputs, and gradients match eager in both. Under Inductor it is not an issue, because Inductor decomposes BN before partitioning: on the same model, the saved-for-backward set is identical with and without the pin at the default budget and at budgets 0 and 0.05, and the pin lands only on the small running-stat update ops, which feed `copy_` rather than the backward. A follow-up that snapshots each mutated input (clone before the mutation, ban recomputing the clone) and lets min-cut choose between saving the snapshot and saving the reads would remove this over-save.

Relation to pytorch#185876 (`aot_runtime_epilogue_input_mutation`): that stops min-cut from saving the placeholder of an input that requires grad and is mutated by the runtime epilogue. This covers inputs that do not require grad, such as buffers, mutations kept in the graph, and metadata-only mutations. Where both apply the results agree.
Buffers mutated by a different compiled region or by eager code are invisible to this graph; an opt-in fix follows in a separate PR.

This PR was authored with an AI assistant.

Test Plan:
```
buck2 test fbcode//mode/opt fbcode//caffe2/test/functorch:test_aotdispatch -- -r 'TestPartitioning'
buck2 test fbcode//mode/opt fbcode//caffe2/test/functorch:test_aotdispatch -- -r 'partition|Partition|mutation|Mutation|checkpoint'
buck2 test fbcode//mode/opt fbcode//caffe2/test/functorch:test_aotdispatch -- --regex 'force_save_effectful|effect_tokens|with_effects'
buck2 test fbcode//mode/opt fbcode//caffe2/test/distributed/tensor:dtensor_compile
```
`TestPartitioning` covers reads through a view, a tuple-producing view, a tuple-producing op read by the backward (budgets 0, 0.05, 0.5), a `(Tensor, Tensor[])` reader under activation checkpointing (budgets 0 and 1.0), an input swapped with `set_` under `no_grad` (`keep_inference_input_mutations=True`, budgets 0 and 1.0), the buffer model above at the default budget, the updated value, a metadata-only mutation (`t_()`), BatchNorm's saved statistics, several gathers at budget 0.05, flat and subclass inputs with `keep_inference_input_mutations` on and off, `default_partition` under activation checkpointing, and an honored `MUST_RECOMPUTE` (warning logged); reads of unmutated inputs are still recomputed. With the base `partitioners.py` swapped in, every new mutating case fails (wrong gradients or `modified by an inplace operation`; for BatchNorm only its structural `assertNotIn` check fails, its gradients match eager either way).
Results: `TestPartitioning` 147 pass, 0 fail; the broader filter 318 pass, 3 fail, all `test_saved_tensors_hooks_mutations_raise`, which hardcodes `device="cuda"` and fails in `torch.ones` with `CUDA error: invalid argument` on this host before compiling; the effectful-op tests 14 pass, 0 fail (they cover the shared walker); `dtensor_compile` 72 pass, 0 fail, 22 skipped.
Descriptor discovery check, with a temporary uncommitted test that wraps `min_cut_rematerialization_partition` and compares the descriptor-derived mutated placeholders with the earlier `input_info.mutates_data`-based names, for a buffer, a `TwoTensor` buffer, a nested `TwoTensor` buffer, no-grad and requires-grad inputs, data plus metadata, and metadata-only mutations, each with `keep_inference_input_mutations` on and off: identical everywhere except metadata-only, which only the descriptors catch; with it pinned, gradients match eager.
Inductor BatchNorm check, with a temporary uncommitted test in `TestPartitioning` that compiles training-mode Conv2d(3, 4) -> BatchNorm2d(4) -> ReLU on a (2, 3, 8, 8) CPU input with `torch.compile(backend="inductor")` (caches disabled), wraps `min_cut_rematerialization_partition` in `torch._inductor.compile_fx` to record the backward graph's non-tangent placeholders, and runs with the pin on and with `force_save_fw_mutated_input_readers` patched to a no-op:
```
buck2 test fbcode//mode/opt fbcode//caffe2/test/functorch:test_aotdispatch -- --regex 'test_zz_tmp_inductor_bn_saved' --print-passing-details
```
The joint graph has no `batch_norm` op (already decomposed) and three `copy_` into the BN buffers (`running_mean`, `running_var`, `num_batches_tracked`). The pin tags `add`, `mul_2`, and `mul_5` (the buffer updates) and nothing the backward reads. Saved sets, identical with and without the pin; gradients and running stats match eager:
- default budget: `primals_1` (4, 3, 3, 3), `primals_3` (2, 3, 8, 8), `primals_7` (4,), `convolution` (2, 4, 8, 8), `squeeze_1` (4,), `le` (2, 4, 8, 8), `unsqueeze_6` (1, 4, 1, 1)
- budget 0: inputs only, `primals_1` (4, 3, 3, 3), `primals_2` (4,), `primals_3` (2, 3, 8, 8), `primals_7` (4,), `primals_8` (4,)
- budget 0.05: the same five inputs plus `getitem_1` (1, 4, 1, 1) and `rsqrt` (1, 4, 1, 1)

Who-hits-this check, with a temporary uncommitted test `test_zzprobe_default_budget` in `TestPartitioning` that compiles `C2` above and the model from `test_min_cut_no_recompute_through_mutated_input` with `torch.compile(backend="inductor")` and `backend="aot_eager"` at the default budget (`activation_memory_budget = 1.0` in `torch/_functorch/config.py`, left unpatched), 0, and 0.05, with the pin on and with `force_save_fw_mutated_input_readers` patched to a no-op. Caches are disabled (`torch.compiler.config.patch(force_disable_caches=True)`, `torch._functorch.config.patch(enable_autograd_cache=False)`), `torch._dynamo.reset()` runs before each compile, and `x.grad` and the buffer are compared against eager on a deepcopy of the module:
```
buck2 test fbcode//mode/opt fbcode//caffe2/test/functorch:test_aotdispatch -- --regex test_zzprobe --print-passing-details
```
- pin off, default budget: `C2` grads wrong (16/16) under both backends; gather model grads match eager under both.
- pin off, budgets 0 and 0.05: both models wrong under both backends (`C2` 16/16, gather model 256/256).
- pin on: every case matches eager. The updated buffer matches eager in every case.

Differential Revision: D118411035
qchip added a commit to qchip/pytorch that referenced this pull request Nov 6, 2026
…h#197039)

Summary:

The AOT min-cut partitioner may recompute a value in the backward rather than save it. That is equivalent only when re-execution is value-preserving, which fails for a read of an input the forward mutates: recompute defers the read past the mutation, so the backward observes post-update contents. The symptom is silently wrong gradients, or a version-counter error when the input reaches the backward through `SavedVariable`. Reads of these inputs are pinned `MUST_SAVE`, walking through aliasing ops to the first op that materializes data -- pinning a view pins an alias, not a snapshot. The comment on `force_save_fw_mutated_input_readers` walks through an example of the wrong and the correct partition.

Who hits this: default `torch.compile` (Inductor), whenever min-cut recomputes a read of an input the forward mutates in place, e.g. a registered buffer read by a pointwise op and then updated with `add_`. With the pin disabled, the buffer model below gets wrong gradients at the default budget (1.0) as well as at 0 and 0.05; the gather model in `test_min_cut_no_recompute_through_mutated_input` is wrong at 0 and 0.05 but matches eager at 1.0. `aot_eager` shows the same pattern. To compare pin on and off under Inductor, disable caches: the pin is not part of the AOTAutogradCache key, so the second compile can reuse the first one's graphs.
```
class C2(torch.nn.Module):
    def __init__(self):
        super().__init__()
        self.register_buffer("buf", torch.randn(16))

    def forward(self, x):
        y = (x * (self.buf * 2)).sum()  # eager grad_x = 2 * buf before add_
        self.buf.add_(1.0)
        return y
```

## Details

Aliasing is decided by storage, not op schema, since the `getitem`s of split/chunk/unbind have no schema. A tuple-producing op cannot be saved as a tensor, so every `getitem` below it is pinned, including the nested levels of a `Tensor[]` output; the op itself is pinned too, since min-cut never bans recomputing a `getitem`. `force_save_collectives` and `force_save_effectful_ops` now share this walker (`_leaf_results`) instead of their own recursive copies, with no behavior change.

Mutated inputs are found from metadata AOTAutograd already attaches to the joint graph, so no new metadata is added: forward outputs described by `InputMutationAOTOutput` for mutations the runtime epilogue applies (translated through `SubclassGetAttrAOTOutput` to the inner placeholders' descriptors), and write-backs tagged `must_be_in_forward` (`copy_`, `set_`, `resize_storage_bytes_`) for mutations kept in the graph, so a buffer swapped with `set_` under `no_grad` is found too. This also covers metadata-only mutations such as `t_()`, which hit the same version-counter error today.

Behaviour changes, limited to the pinned reads:
- Activation checkpointing's `PREFER_RECOMPUTE` on such a read is overridden. An explicit `MUST_RECOMPUTE` from a user policy is honored, because the pin is conservative (it also hits reads that do not depend on the mutated data, such as BatchNorm's running-stat updates after decomposition); a one-time warning (`warning_once`) says gradients may be wrong, and the nodes are logged at debug level.
- `default_partition` runs the same pass. Under activation checkpointing it recomputed such reads: with a buffer read inside the checkpointed region and mutated after it, base raises the version-counter error with `keep_inference_input_mutations=False` and gives `2 * (buf + 1)` with `True`; this gives `2 * buf`, matching the function without checkpointing. Eager checkpointing itself recomputes after the mutation and also gives `2 * (buf + 1)`, so the compiled result now matches the un-checkpointed function rather than eager checkpointing.
- `memory_budget == 0` saved only the inputs. It now also saves the pinned reads, including a `getitem` of a forward op that only the backward reads, such as BatchNorm's `save_mean`. Other `MUST_SAVE` marks are still recomputed at budget 0, as before.

Behavior change for BatchNorm: on backends that keep BatchNorm as a single op (eager-style backends such as `aot_eager`), training BatchNorm's outputs are now saved rather than recomputed. This is conservative: the partitioner only sees that `_native_batch_norm_legit_functional` reads the mutated running stats, not that `out`, `save_mean`, and `save_rstd` depend only on batch stats. It costs memory, not correctness; for conv -> BN -> ReLU at budget 0, the full (2, 4, 8, 8) BN output and four (4,) vectors are saved where trunk saves only the inputs, and gradients match eager in both. Under Inductor it is not an issue, because Inductor decomposes BN before partitioning: on the same model, the saved-for-backward set is identical with and without the pin at the default budget and at budgets 0 and 0.05, and the pin lands only on the small running-stat update ops, which feed `copy_` rather than the backward. A follow-up that snapshots each mutated input (clone before the mutation, ban recomputing the clone) and lets min-cut choose between saving the snapshot and saving the reads would remove this over-save.

Relation to pytorch#185876 (`aot_runtime_epilogue_input_mutation`): that stops min-cut from saving the placeholder of an input that requires grad and is mutated by the runtime epilogue. This covers inputs that do not require grad, such as buffers, mutations kept in the graph, and metadata-only mutations. Where both apply the results agree.
Buffers mutated by a different compiled region or by eager code are invisible to this graph; an opt-in fix follows in a separate PR.

This PR was authored with an AI assistant.

Test Plan:
```
buck2 test fbcode//mode/opt fbcode//caffe2/test/functorch:test_aotdispatch -- -r 'TestPartitioning'
buck2 test fbcode//mode/opt fbcode//caffe2/test/functorch:test_aotdispatch -- -r 'partition|Partition|mutation|Mutation|checkpoint'
buck2 test fbcode//mode/opt fbcode//caffe2/test/functorch:test_aotdispatch -- --regex 'force_save_effectful|effect_tokens|with_effects'
buck2 test fbcode//mode/opt fbcode//caffe2/test/distributed/tensor:dtensor_compile
```
`TestPartitioning` covers reads through a view, a tuple-producing view, a tuple-producing op read by the backward (budgets 0, 0.05, 0.5), a `(Tensor, Tensor[])` reader under activation checkpointing (budgets 0 and 1.0), an input swapped with `set_` under `no_grad` (`keep_inference_input_mutations=True`, budgets 0 and 1.0), the buffer model above at the default budget, the updated value, a metadata-only mutation (`t_()`), BatchNorm's saved statistics, several gathers at budget 0.05, flat and subclass inputs with `keep_inference_input_mutations` on and off, `default_partition` under activation checkpointing, and an honored `MUST_RECOMPUTE` (warning logged); reads of unmutated inputs are still recomputed. With the base `partitioners.py` swapped in, every new mutating case fails (wrong gradients or `modified by an inplace operation`; for BatchNorm only its structural `assertNotIn` check fails, its gradients match eager either way).
Results: `TestPartitioning` 147 pass, 0 fail; the broader filter 318 pass, 3 fail, all `test_saved_tensors_hooks_mutations_raise`, which hardcodes `device="cuda"` and fails in `torch.ones` with `CUDA error: invalid argument` on this host before compiling; the effectful-op tests 14 pass, 0 fail (they cover the shared walker); `dtensor_compile` 72 pass, 0 fail, 22 skipped.
Descriptor discovery check, with a temporary uncommitted test that wraps `min_cut_rematerialization_partition` and compares the descriptor-derived mutated placeholders with the earlier `input_info.mutates_data`-based names, for a buffer, a `TwoTensor` buffer, a nested `TwoTensor` buffer, no-grad and requires-grad inputs, data plus metadata, and metadata-only mutations, each with `keep_inference_input_mutations` on and off: identical everywhere except metadata-only, which only the descriptors catch; with it pinned, gradients match eager.
Inductor BatchNorm check, with a temporary uncommitted test in `TestPartitioning` that compiles training-mode Conv2d(3, 4) -> BatchNorm2d(4) -> ReLU on a (2, 3, 8, 8) CPU input with `torch.compile(backend="inductor")` (caches disabled), wraps `min_cut_rematerialization_partition` in `torch._inductor.compile_fx` to record the backward graph's non-tangent placeholders, and runs with the pin on and with `force_save_fw_mutated_input_readers` patched to a no-op:
```
buck2 test fbcode//mode/opt fbcode//caffe2/test/functorch:test_aotdispatch -- --regex 'test_zz_tmp_inductor_bn_saved' --print-passing-details
```
The joint graph has no `batch_norm` op (already decomposed) and three `copy_` into the BN buffers (`running_mean`, `running_var`, `num_batches_tracked`). The pin tags `add`, `mul_2`, and `mul_5` (the buffer updates) and nothing the backward reads. Saved sets, identical with and without the pin; gradients and running stats match eager:
- default budget: `primals_1` (4, 3, 3, 3), `primals_3` (2, 3, 8, 8), `primals_7` (4,), `convolution` (2, 4, 8, 8), `squeeze_1` (4,), `le` (2, 4, 8, 8), `unsqueeze_6` (1, 4, 1, 1)
- budget 0: inputs only, `primals_1` (4, 3, 3, 3), `primals_2` (4,), `primals_3` (2, 3, 8, 8), `primals_7` (4,), `primals_8` (4,)
- budget 0.05: the same five inputs plus `getitem_1` (1, 4, 1, 1) and `rsqrt` (1, 4, 1, 1)

Who-hits-this check, with a temporary uncommitted test `test_zzprobe_default_budget` in `TestPartitioning` that compiles `C2` above and the model from `test_min_cut_no_recompute_through_mutated_input` with `torch.compile(backend="inductor")` and `backend="aot_eager"` at the default budget (`activation_memory_budget = 1.0` in `torch/_functorch/config.py`, left unpatched), 0, and 0.05, with the pin on and with `force_save_fw_mutated_input_readers` patched to a no-op. Caches are disabled (`torch.compiler.config.patch(force_disable_caches=True)`, `torch._functorch.config.patch(enable_autograd_cache=False)`), `torch._dynamo.reset()` runs before each compile, and `x.grad` and the buffer are compared against eager on a deepcopy of the module:
```
buck2 test fbcode//mode/opt fbcode//caffe2/test/functorch:test_aotdispatch -- --regex test_zzprobe --print-passing-details
```
- pin off, default budget: `C2` grads wrong (16/16) under both backends; gather model grads match eager under both.
- pin off, budgets 0 and 0.05: both models wrong under both backends (`C2` 16/16, gather model 256/256).
- pin on: every case matches eager. The updated buffer matches eager in every case.

Differential Revision: D118411035
qchip added a commit to qchip/pytorch that referenced this pull request Nov 6, 2026
…h#197039)

Summary:

The AOT min-cut partitioner may recompute a value in the backward rather than save it. That is equivalent only when re-execution is value-preserving, which fails for a read of an input the forward mutates: recompute defers the read past the mutation, so the backward observes post-update contents. The symptom is silently wrong gradients, or a version-counter error when the input reaches the backward through `SavedVariable`. Reads of these inputs are pinned `MUST_SAVE`, walking through aliasing ops to the first op that materializes data -- pinning a view pins an alias, not a snapshot. The comment on `force_save_fw_mutated_input_readers` walks through an example of the wrong and the correct partition.

Who hits this: default `torch.compile` (Inductor), whenever min-cut recomputes a read of an input the forward mutates in place, e.g. a registered buffer read by a pointwise op and then updated with `add_`. With the pin disabled, the buffer model below gets wrong gradients at the default budget (1.0) as well as at 0 and 0.05; the gather model in `test_min_cut_no_recompute_through_mutated_input` is wrong at 0 and 0.05 but matches eager at 1.0. `aot_eager` shows the same pattern. To compare pin on and off under Inductor, disable caches: the pin is not part of the AOTAutogradCache key, so the second compile can reuse the first one's graphs.
```
class C2(torch.nn.Module):
    def __init__(self):
        super().__init__()
        self.register_buffer("buf", torch.randn(16))

    def forward(self, x):
        y = (x * (self.buf * 2)).sum()  # eager grad_x = 2 * buf before add_
        self.buf.add_(1.0)
        return y
```

## Details

Aliasing is decided by storage, not op schema, since the `getitem`s of split/chunk/unbind have no schema. A tuple-producing op cannot be saved as a tensor, so every `getitem` below it is pinned, including the nested levels of a `Tensor[]` output; the op itself is pinned too, since min-cut never bans recomputing a `getitem`. `force_save_collectives` and `force_save_effectful_ops` now share this walker (`_leaf_results`) instead of their own recursive copies, with no behavior change.

Mutated inputs are found from metadata AOTAutograd already attaches to the joint graph, so no new metadata is added: forward outputs described by `InputMutationAOTOutput` for mutations the runtime epilogue applies (translated through `SubclassGetAttrAOTOutput` to the inner placeholders' descriptors), and write-backs tagged `must_be_in_forward` (`copy_`, `set_`, `resize_storage_bytes_`) for mutations kept in the graph, so a buffer swapped with `set_` under `no_grad` is found too. This also covers metadata-only mutations such as `t_()`, which hit the same version-counter error today.

Behaviour changes, limited to the pinned reads:
- Activation checkpointing's `PREFER_RECOMPUTE` on such a read is overridden. An explicit `MUST_RECOMPUTE` from a user policy is honored, because the pin is conservative (it also hits reads that do not depend on the mutated data, such as BatchNorm's running-stat updates after decomposition); a one-time warning (`warning_once`) says gradients may be wrong, and the nodes are logged at debug level.
- `default_partition` runs the same pass. Under activation checkpointing it recomputed such reads: with a buffer read inside the checkpointed region and mutated after it, base raises the version-counter error with `keep_inference_input_mutations=False` and gives `2 * (buf + 1)` with `True`; this gives `2 * buf`, matching the function without checkpointing. Eager checkpointing itself recomputes after the mutation and also gives `2 * (buf + 1)`, so the compiled result now matches the un-checkpointed function rather than eager checkpointing.
- `memory_budget == 0` saved only the inputs. It now also saves the pinned reads, including a `getitem` of a forward op that only the backward reads, such as BatchNorm's `save_mean`. Other `MUST_SAVE` marks are still recomputed at budget 0, as before.

Behavior change for BatchNorm: on backends that keep BatchNorm as a single op (eager-style backends such as `aot_eager`), training BatchNorm's outputs are now saved rather than recomputed. This is conservative: the partitioner only sees that `_native_batch_norm_legit_functional` reads the mutated running stats, not that `out`, `save_mean`, and `save_rstd` depend only on batch stats. It costs memory, not correctness; for conv -> BN -> ReLU at budget 0, the full (2, 4, 8, 8) BN output and four (4,) vectors are saved where trunk saves only the inputs, and gradients match eager in both. Under Inductor it is not an issue, because Inductor decomposes BN before partitioning: on the same model, the saved-for-backward set is identical with and without the pin at the default budget and at budgets 0 and 0.05, and the pin lands only on the small running-stat update ops, which feed `copy_` rather than the backward. A follow-up that snapshots each mutated input (clone before the mutation, ban recomputing the clone) and lets min-cut choose between saving the snapshot and saving the reads would remove this over-save.

Relation to pytorch#185876 (`aot_runtime_epilogue_input_mutation`): that stops min-cut from saving the placeholder of an input that requires grad and is mutated by the runtime epilogue. This covers inputs that do not require grad, such as buffers, mutations kept in the graph, and metadata-only mutations. Where both apply the results agree.
Buffers mutated by a different compiled region or by eager code are invisible to this graph; an opt-in fix follows in a separate PR.

This PR was authored with an AI assistant.

Test Plan:
```
buck2 test fbcode//mode/opt fbcode//caffe2/test/functorch:test_aotdispatch -- -r 'TestPartitioning'
buck2 test fbcode//mode/opt fbcode//caffe2/test/functorch:test_aotdispatch -- -r 'partition|Partition|mutation|Mutation|checkpoint'
buck2 test fbcode//mode/opt fbcode//caffe2/test/functorch:test_aotdispatch -- --regex 'force_save_effectful|effect_tokens|with_effects'
buck2 test fbcode//mode/opt fbcode//caffe2/test/distributed/tensor:dtensor_compile
```
`TestPartitioning` covers reads through a view, a tuple-producing view, a tuple-producing op read by the backward (budgets 0, 0.05, 0.5), a `(Tensor, Tensor[])` reader under activation checkpointing (budgets 0 and 1.0), an input swapped with `set_` under `no_grad` (`keep_inference_input_mutations=True`, budgets 0 and 1.0), the buffer model above at the default budget, the updated value, a metadata-only mutation (`t_()`), BatchNorm's saved statistics, several gathers at budget 0.05, flat and subclass inputs with `keep_inference_input_mutations` on and off, `default_partition` under activation checkpointing, and an honored `MUST_RECOMPUTE` (warning logged); reads of unmutated inputs are still recomputed. With the base `partitioners.py` swapped in, every new mutating case fails (wrong gradients or `modified by an inplace operation`; for BatchNorm only its structural `assertNotIn` check fails, its gradients match eager either way).
Results: `TestPartitioning` 147 pass, 0 fail; the broader filter 318 pass, 3 fail, all `test_saved_tensors_hooks_mutations_raise`, which hardcodes `device="cuda"` and fails in `torch.ones` with `CUDA error: invalid argument` on this host before compiling; the effectful-op tests 14 pass, 0 fail (they cover the shared walker); `dtensor_compile` 72 pass, 0 fail, 22 skipped.
Descriptor discovery check, with a temporary uncommitted test that wraps `min_cut_rematerialization_partition` and compares the descriptor-derived mutated placeholders with the earlier `input_info.mutates_data`-based names, for a buffer, a `TwoTensor` buffer, a nested `TwoTensor` buffer, no-grad and requires-grad inputs, data plus metadata, and metadata-only mutations, each with `keep_inference_input_mutations` on and off: identical everywhere except metadata-only, which only the descriptors catch; with it pinned, gradients match eager.
Inductor BatchNorm check, with a temporary uncommitted test in `TestPartitioning` that compiles training-mode Conv2d(3, 4) -> BatchNorm2d(4) -> ReLU on a (2, 3, 8, 8) CPU input with `torch.compile(backend="inductor")` (caches disabled), wraps `min_cut_rematerialization_partition` in `torch._inductor.compile_fx` to record the backward graph's non-tangent placeholders, and runs with the pin on and with `force_save_fw_mutated_input_readers` patched to a no-op:
```
buck2 test fbcode//mode/opt fbcode//caffe2/test/functorch:test_aotdispatch -- --regex 'test_zz_tmp_inductor_bn_saved' --print-passing-details
```
The joint graph has no `batch_norm` op (already decomposed) and three `copy_` into the BN buffers (`running_mean`, `running_var`, `num_batches_tracked`). The pin tags `add`, `mul_2`, and `mul_5` (the buffer updates) and nothing the backward reads. Saved sets, identical with and without the pin; gradients and running stats match eager:
- default budget: `primals_1` (4, 3, 3, 3), `primals_3` (2, 3, 8, 8), `primals_7` (4,), `convolution` (2, 4, 8, 8), `squeeze_1` (4,), `le` (2, 4, 8, 8), `unsqueeze_6` (1, 4, 1, 1)
- budget 0: inputs only, `primals_1` (4, 3, 3, 3), `primals_2` (4,), `primals_3` (2, 3, 8, 8), `primals_7` (4,), `primals_8` (4,)
- budget 0.05: the same five inputs plus `getitem_1` (1, 4, 1, 1) and `rsqrt` (1, 4, 1, 1)

Who-hits-this check, with a temporary uncommitted test `test_zzprobe_default_budget` in `TestPartitioning` that compiles `C2` above and the model from `test_min_cut_no_recompute_through_mutated_input` with `torch.compile(backend="inductor")` and `backend="aot_eager"` at the default budget (`activation_memory_budget = 1.0` in `torch/_functorch/config.py`, left unpatched), 0, and 0.05, with the pin on and with `force_save_fw_mutated_input_readers` patched to a no-op. Caches are disabled (`torch.compiler.config.patch(force_disable_caches=True)`, `torch._functorch.config.patch(enable_autograd_cache=False)`), `torch._dynamo.reset()` runs before each compile, and `x.grad` and the buffer are compared against eager on a deepcopy of the module:
```
buck2 test fbcode//mode/opt fbcode//caffe2/test/functorch:test_aotdispatch -- --regex test_zzprobe --print-passing-details
```
- pin off, default budget: `C2` grads wrong (16/16) under both backends; gather model grads match eager under both.
- pin off, budgets 0 and 0.05: both models wrong under both backends (`C2` 16/16, gather model 256/256).
- pin on: every case matches eager. The updated buffer matches eager in every case.

Differential Revision: D118411035
qchip added a commit to qchip/pytorch that referenced this pull request Nov 6, 2026
…h#197039)

Summary:
Pull Request resolved: pytorch#197039

The AOT min-cut partitioner may recompute a value in the backward rather than save it. That is equivalent only when re-execution is value-preserving, which fails for a read of an input the forward mutates: recompute defers the read past the mutation, so the backward observes post-update contents. The symptom is silently wrong gradients, or a version-counter error when the input reaches the backward through `SavedVariable`. Reads of these inputs are pinned `MUST_SAVE`, walking through aliasing ops to the first op that materializes data -- pinning a view pins an alias, not a snapshot. The comment on `force_save_fw_mutated_input_readers` walks through an example of the wrong and the correct partition.

Who hits this: default `torch.compile` (Inductor), whenever min-cut recomputes a read of an input the forward mutates in place, e.g. a registered buffer read by a pointwise op and then updated with `add_`. With the pin disabled, the buffer model below gets wrong gradients at the default budget (1.0) as well as at 0 and 0.05; the gather model in `test_min_cut_no_recompute_through_mutated_input` is wrong at 0 and 0.05 but matches eager at 1.0. `aot_eager` shows the same pattern. To compare pin on and off under Inductor, disable caches: the pin is not part of the AOTAutogradCache key, so the second compile can reuse the first one's graphs.
```
class C2(torch.nn.Module):
    def __init__(self):
        super().__init__()
        self.register_buffer("buf", torch.randn(16))

    def forward(self, x):
        y = (x * (self.buf * 2)).sum()  # eager grad_x = 2 * buf before add_
        self.buf.add_(1.0)
        return y
```

## Details

Aliasing is decided by storage, not op schema, since the `getitem`s of split/chunk/unbind have no schema. A tuple-producing op cannot be saved as a tensor, so every `getitem` below it is pinned, including the nested levels of a `Tensor[]` output; the op itself is pinned too, since min-cut never bans recomputing a `getitem`. `force_save_collectives` and `force_save_effectful_ops` now share this walker (`_leaf_results`) instead of their own recursive copies, with no behavior change.

Mutated inputs are found from metadata AOTAutograd already attaches to the joint graph, so no new metadata is added: forward outputs described by `InputMutationAOTOutput` for mutations the runtime epilogue applies (translated through `SubclassGetAttrAOTOutput` to the inner placeholders' descriptors), and write-backs tagged `must_be_in_forward` (`copy_`, `set_`, `resize_storage_bytes_`) for mutations kept in the graph, so a buffer swapped with `set_` under `no_grad` is found too. This also covers metadata-only mutations such as `t_()`, which hit the same version-counter error today.

Behaviour changes, limited to the pinned reads:
- Activation checkpointing's `PREFER_RECOMPUTE` on such a read is overridden. An explicit `MUST_RECOMPUTE` from a user policy is honored, because the pin is conservative (it also hits reads that do not depend on the mutated data, such as BatchNorm's running-stat updates after decomposition); a one-time warning (`warning_once`) says gradients may be wrong, and the nodes are logged at debug level.
- `default_partition` runs the same pass. Under activation checkpointing it recomputed such reads: with a buffer read inside the checkpointed region and mutated after it, base raises the version-counter error with `keep_inference_input_mutations=False` and gives `2 * (buf + 1)` with `True`; this gives `2 * buf`, matching the function without checkpointing. Eager checkpointing itself recomputes after the mutation and also gives `2 * (buf + 1)`, so the compiled result now matches the un-checkpointed function rather than eager checkpointing.
- `memory_budget == 0` saved only the inputs. It now also saves the pinned reads, including a `getitem` of a forward op that only the backward reads, such as BatchNorm's `save_mean`. Other `MUST_SAVE` marks are still recomputed at budget 0, as before.

Behavior change for BatchNorm: on backends that keep BatchNorm as a single op (eager-style backends such as `aot_eager`), training BatchNorm's outputs are now saved rather than recomputed. This is conservative: the partitioner only sees that `_native_batch_norm_legit_functional` reads the mutated running stats, not that `out`, `save_mean`, and `save_rstd` depend only on batch stats. It costs memory, not correctness; for conv -> BN -> ReLU at budget 0, the full (2, 4, 8, 8) BN output and four (4,) vectors are saved where trunk saves only the inputs, and gradients match eager in both. Under Inductor it is not an issue, because Inductor decomposes BN before partitioning: on the same model, the saved-for-backward set is identical with and without the pin at the default budget and at budgets 0 and 0.05, and the pin lands only on the small running-stat update ops, which feed `copy_` rather than the backward. A follow-up that snapshots each mutated input (clone before the mutation, ban recomputing the clone) and lets min-cut choose between saving the snapshot and saving the reads would remove this over-save.

Relation to pytorch#185876 (`aot_runtime_epilogue_input_mutation`): that stops min-cut from saving the placeholder of an input that requires grad and is mutated by the runtime epilogue. This covers inputs that do not require grad, such as buffers, mutations kept in the graph, and metadata-only mutations. Where both apply the results agree.
Buffers mutated by a different compiled region or by eager code are invisible to this graph; an opt-in fix follows in a separate PR.

This PR was authored with an AI assistant.

Test Plan:
```
buck2 test fbcode//mode/opt fbcode//caffe2/test/functorch:test_aotdispatch -- -r 'TestPartitioning'
buck2 test fbcode//mode/opt fbcode//caffe2/test/functorch:test_aotdispatch -- -r 'partition|Partition|mutation|Mutation|checkpoint'
buck2 test fbcode//mode/opt fbcode//caffe2/test/functorch:test_aotdispatch -- --regex 'force_save_effectful|effect_tokens|with_effects'
buck2 test fbcode//mode/opt fbcode//caffe2/test/distributed/tensor:dtensor_compile
```
`TestPartitioning` covers reads through a view, a tuple-producing view, a tuple-producing op read by the backward (budgets 0, 0.05, 0.5), a `(Tensor, Tensor[])` reader under activation checkpointing (budgets 0 and 1.0), an input swapped with `set_` under `no_grad` (`keep_inference_input_mutations=True`, budgets 0 and 1.0), the buffer model above at the default budget, the updated value, a metadata-only mutation (`t_()`), BatchNorm's saved statistics, several gathers at budget 0.05, flat and subclass inputs with `keep_inference_input_mutations` on and off, `default_partition` under activation checkpointing, and an honored `MUST_RECOMPUTE` (warning logged); reads of unmutated inputs are still recomputed. With the base `partitioners.py` swapped in, every new mutating case fails (wrong gradients or `modified by an inplace operation`; for BatchNorm only its structural `assertNotIn` check fails, its gradients match eager either way).
Results: `TestPartitioning` 147 pass, 0 fail; the broader filter 318 pass, 3 fail, all `test_saved_tensors_hooks_mutations_raise`, which hardcodes `device="cuda"` and fails in `torch.ones` with `CUDA error: invalid argument` on this host before compiling; the effectful-op tests 14 pass, 0 fail (they cover the shared walker); `dtensor_compile` 72 pass, 0 fail, 22 skipped.
Descriptor discovery check, with a temporary uncommitted test that wraps `min_cut_rematerialization_partition` and compares the descriptor-derived mutated placeholders with the earlier `input_info.mutates_data`-based names, for a buffer, a `TwoTensor` buffer, a nested `TwoTensor` buffer, no-grad and requires-grad inputs, data plus metadata, and metadata-only mutations, each with `keep_inference_input_mutations` on and off: identical everywhere except metadata-only, which only the descriptors catch; with it pinned, gradients match eager.
Inductor BatchNorm check, with a temporary uncommitted test in `TestPartitioning` that compiles training-mode Conv2d(3, 4) -> BatchNorm2d(4) -> ReLU on a (2, 3, 8, 8) CPU input with `torch.compile(backend="inductor")` (caches disabled), wraps `min_cut_rematerialization_partition` in `torch._inductor.compile_fx` to record the backward graph's non-tangent placeholders, and runs with the pin on and with `force_save_fw_mutated_input_readers` patched to a no-op:
```
buck2 test fbcode//mode/opt fbcode//caffe2/test/functorch:test_aotdispatch -- --regex 'test_zz_tmp_inductor_bn_saved' --print-passing-details
```
The joint graph has no `batch_norm` op (already decomposed) and three `copy_` into the BN buffers (`running_mean`, `running_var`, `num_batches_tracked`). The pin tags `add`, `mul_2`, and `mul_5` (the buffer updates) and nothing the backward reads. Saved sets, identical with and without the pin; gradients and running stats match eager:
- default budget: `primals_1` (4, 3, 3, 3), `primals_3` (2, 3, 8, 8), `primals_7` (4,), `convolution` (2, 4, 8, 8), `squeeze_1` (4,), `le` (2, 4, 8, 8), `unsqueeze_6` (1, 4, 1, 1)
- budget 0: inputs only, `primals_1` (4, 3, 3, 3), `primals_2` (4,), `primals_3` (2, 3, 8, 8), `primals_7` (4,), `primals_8` (4,)
- budget 0.05: the same five inputs plus `getitem_1` (1, 4, 1, 1) and `rsqrt` (1, 4, 1, 1)

Who-hits-this check, with a temporary uncommitted test `test_zzprobe_default_budget` in `TestPartitioning` that compiles `C2` above and the model from `test_min_cut_no_recompute_through_mutated_input` with `torch.compile(backend="inductor")` and `backend="aot_eager"` at the default budget (`activation_memory_budget = 1.0` in `torch/_functorch/config.py`, left unpatched), 0, and 0.05, with the pin on and with `force_save_fw_mutated_input_readers` patched to a no-op. Caches are disabled (`torch.compiler.config.patch(force_disable_caches=True)`, `torch._functorch.config.patch(enable_autograd_cache=False)`), `torch._dynamo.reset()` runs before each compile, and `x.grad` and the buffer are compared against eager on a deepcopy of the module:
```
buck2 test fbcode//mode/opt fbcode//caffe2/test/functorch:test_aotdispatch -- --regex test_zzprobe --print-passing-details
```
- pin off, default budget: `C2` grads wrong (16/16) under both backends; gather model grads match eager under both.
- pin off, budgets 0 and 0.05: both models wrong under both backends (`C2` 16/16, gather model 256/256).
- pin on: every case matches eager. The updated buffer matches eager in every case.

Differential Revision: D118411035
qchip added a commit to qchip/pytorch that referenced this pull request Nov 12, 2026
…h#197039)

Summary:

The AOT min-cut partitioner may recompute a value in the backward rather than save it. That is equivalent only when re-execution is value-preserving, which fails for a read of an input the forward mutates: recompute defers the read past the mutation, so the backward observes post-update contents. The symptom is silently wrong gradients, or a version-counter error when the input reaches the backward through `SavedVariable`. Reads of these inputs are pinned `MUST_SAVE`, walking through aliasing ops to the first op that materializes data -- pinning a view pins an alias, not a snapshot. The comment on `force_save_fw_mutated_input_readers` walks through an example of the wrong and the correct partition.

Who hits this: default `torch.compile` (Inductor), whenever min-cut recomputes a read of an input the forward mutates in place, e.g. a registered buffer read by a pointwise op and then updated with `add_`. With the pin disabled, the buffer model below gets wrong gradients at the default budget (1.0) as well as at 0 and 0.05; the gather model in `test_min_cut_no_recompute_through_mutated_input` is wrong at 0 and 0.05 but matches eager at 1.0. `aot_eager` shows the same pattern. To compare pin on and off under Inductor, disable caches: the pin is not part of the AOTAutogradCache key, so the second compile can reuse the first one's graphs.
```
class C2(torch.nn.Module):
    def __init__(self):
        super().__init__()
        self.register_buffer("buf", torch.randn(16))

    def forward(self, x):
        y = (x * (self.buf * 2)).sum()  # eager grad_x = 2 * buf before add_
        self.buf.add_(1.0)
        return y
```

## Details

Aliasing is decided by storage, not op schema, since the `getitem`s of split/chunk/unbind have no schema. A tuple-producing op cannot be saved as a tensor, so every `getitem` below it is pinned, including the nested levels of a `Tensor[]` output; the op itself is pinned too, since min-cut never bans recomputing a `getitem`. `force_save_collectives` and `force_save_effectful_ops` now share this walker (`_leaf_results`) instead of their own recursive copies, with no behavior change.

Mutated inputs are found from metadata AOTAutograd already attaches to the joint graph, so no new metadata is added: forward outputs described by `InputMutationAOTOutput` for mutations the runtime epilogue applies (translated through `SubclassGetAttrAOTOutput` to the inner placeholders' descriptors), and write-backs tagged `must_be_in_forward` (`copy_`, `set_`, `resize_storage_bytes_`) for mutations kept in the graph, so a buffer swapped with `set_` under `no_grad` is found too. This also covers metadata-only mutations such as `t_()`, which hit the same version-counter error today.

Behaviour changes, limited to the pinned reads:
- Activation checkpointing's `PREFER_RECOMPUTE` on such a read is overridden. An explicit `MUST_RECOMPUTE` from a user policy is honored, because the pin is conservative (it also hits reads that do not depend on the mutated data, such as BatchNorm's running-stat updates after decomposition); a one-time warning (`warning_once`) says gradients may be wrong, and the nodes are logged at debug level.
- `default_partition` runs the same pass. Under activation checkpointing it recomputed such reads: with a buffer read inside the checkpointed region and mutated after it, base raises the version-counter error with `keep_inference_input_mutations=False` and gives `2 * (buf + 1)` with `True`; this gives `2 * buf`, matching the function without checkpointing. Eager checkpointing itself recomputes after the mutation and also gives `2 * (buf + 1)`, so the compiled result now matches the un-checkpointed function rather than eager checkpointing.
- `memory_budget == 0` saved only the inputs. It now also saves the pinned reads, including a `getitem` of a forward op that only the backward reads, such as BatchNorm's `save_mean`. Other `MUST_SAVE` marks are still recomputed at budget 0, as before.

Behavior change for BatchNorm: on backends that keep BatchNorm as a single op (eager-style backends such as `aot_eager`), training BatchNorm's outputs are now saved rather than recomputed. This is conservative: the partitioner only sees that `_native_batch_norm_legit_functional` reads the mutated running stats, not that `out`, `save_mean`, and `save_rstd` depend only on batch stats. It costs memory, not correctness; for conv -> BN -> ReLU at budget 0, the full (2, 4, 8, 8) BN output and four (4,) vectors are saved where trunk saves only the inputs, and gradients match eager in both. Under Inductor it is not an issue, because Inductor decomposes BN before partitioning: on the same model, the saved-for-backward set is identical with and without the pin at the default budget and at budgets 0 and 0.05, and the pin lands only on the small running-stat update ops, which feed `copy_` rather than the backward. A follow-up that snapshots each mutated input (clone before the mutation, ban recomputing the clone) and lets min-cut choose between saving the snapshot and saving the reads would remove this over-save.

Relation to pytorch#185876 (`aot_runtime_epilogue_input_mutation`): that stops min-cut from saving the placeholder of an input that requires grad and is mutated by the runtime epilogue. This covers inputs that do not require grad, such as buffers, mutations kept in the graph, and metadata-only mutations. Where both apply the results agree.
Buffers mutated by a different compiled region or by eager code are invisible to this graph; an opt-in fix follows in a separate PR.

This PR was authored with an AI assistant.

Test Plan:
```
buck2 test fbcode//mode/opt fbcode//caffe2/test/functorch:test_aotdispatch -- -r 'TestPartitioning'
buck2 test fbcode//mode/opt fbcode//caffe2/test/functorch:test_aotdispatch -- -r 'partition|Partition|mutation|Mutation|checkpoint'
buck2 test fbcode//mode/opt fbcode//caffe2/test/functorch:test_aotdispatch -- --regex 'force_save_effectful|effect_tokens|with_effects'
buck2 test fbcode//mode/opt fbcode//caffe2/test/distributed/tensor:dtensor_compile
```
`TestPartitioning` covers reads through a view, a tuple-producing view, a tuple-producing op read by the backward (budgets 0, 0.05, 0.5), a `(Tensor, Tensor[])` reader under activation checkpointing (budgets 0 and 1.0), an input swapped with `set_` under `no_grad` (`keep_inference_input_mutations=True`, budgets 0 and 1.0), the buffer model above at the default budget, the updated value, a metadata-only mutation (`t_()`), BatchNorm's saved statistics, several gathers at budget 0.05, flat and subclass inputs with `keep_inference_input_mutations` on and off, `default_partition` under activation checkpointing, and an honored `MUST_RECOMPUTE` (warning logged); reads of unmutated inputs are still recomputed. With the base `partitioners.py` swapped in, every new mutating case fails (wrong gradients or `modified by an inplace operation`; for BatchNorm only its structural `assertNotIn` check fails, its gradients match eager either way).
Results: `TestPartitioning` 147 pass, 0 fail; the broader filter 318 pass, 3 fail, all `test_saved_tensors_hooks_mutations_raise`, which hardcodes `device="cuda"` and fails in `torch.ones` with `CUDA error: invalid argument` on this host before compiling; the effectful-op tests 14 pass, 0 fail (they cover the shared walker); `dtensor_compile` 72 pass, 0 fail, 22 skipped.
Descriptor discovery check, with a temporary uncommitted test that wraps `min_cut_rematerialization_partition` and compares the descriptor-derived mutated placeholders with the earlier `input_info.mutates_data`-based names, for a buffer, a `TwoTensor` buffer, a nested `TwoTensor` buffer, no-grad and requires-grad inputs, data plus metadata, and metadata-only mutations, each with `keep_inference_input_mutations` on and off: identical everywhere except metadata-only, which only the descriptors catch; with it pinned, gradients match eager.
Inductor BatchNorm check, with a temporary uncommitted test in `TestPartitioning` that compiles training-mode Conv2d(3, 4) -> BatchNorm2d(4) -> ReLU on a (2, 3, 8, 8) CPU input with `torch.compile(backend="inductor")` (caches disabled), wraps `min_cut_rematerialization_partition` in `torch._inductor.compile_fx` to record the backward graph's non-tangent placeholders, and runs with the pin on and with `force_save_fw_mutated_input_readers` patched to a no-op:
```
buck2 test fbcode//mode/opt fbcode//caffe2/test/functorch:test_aotdispatch -- --regex 'test_zz_tmp_inductor_bn_saved' --print-passing-details
```
The joint graph has no `batch_norm` op (already decomposed) and three `copy_` into the BN buffers (`running_mean`, `running_var`, `num_batches_tracked`). The pin tags `add`, `mul_2`, and `mul_5` (the buffer updates) and nothing the backward reads. Saved sets, identical with and without the pin; gradients and running stats match eager:
- default budget: `primals_1` (4, 3, 3, 3), `primals_3` (2, 3, 8, 8), `primals_7` (4,), `convolution` (2, 4, 8, 8), `squeeze_1` (4,), `le` (2, 4, 8, 8), `unsqueeze_6` (1, 4, 1, 1)
- budget 0: inputs only, `primals_1` (4, 3, 3, 3), `primals_2` (4,), `primals_3` (2, 3, 8, 8), `primals_7` (4,), `primals_8` (4,)
- budget 0.05: the same five inputs plus `getitem_1` (1, 4, 1, 1) and `rsqrt` (1, 4, 1, 1)

Who-hits-this check, with a temporary uncommitted test `test_zzprobe_default_budget` in `TestPartitioning` that compiles `C2` above and the model from `test_min_cut_no_recompute_through_mutated_input` with `torch.compile(backend="inductor")` and `backend="aot_eager"` at the default budget (`activation_memory_budget = 1.0` in `torch/_functorch/config.py`, left unpatched), 0, and 0.05, with the pin on and with `force_save_fw_mutated_input_readers` patched to a no-op. Caches are disabled (`torch.compiler.config.patch(force_disable_caches=True)`, `torch._functorch.config.patch(enable_autograd_cache=False)`), `torch._dynamo.reset()` runs before each compile, and `x.grad` and the buffer are compared against eager on a deepcopy of the module:
```
buck2 test fbcode//mode/opt fbcode//caffe2/test/functorch:test_aotdispatch -- --regex test_zzprobe --print-passing-details
```
- pin off, default budget: `C2` grads wrong (16/16) under both backends; gather model grads match eager under both.
- pin off, budgets 0 and 0.05: both models wrong under both backends (`C2` 16/16, gather model 256/256).
- pin on: every case matches eager. The updated buffer matches eager in every case.

Differential Revision: D118411035
pytorchmergebot pushed a commit that referenced this pull request Nov 13, 2026
… (#197039)

Summary:

The AOT min-cut partitioner may recompute a value in the backward rather than save it. That is equivalent only when re-execution is value-preserving, which fails for a read of an input the forward mutates: recompute defers the read past the mutation, so the backward observes post-update contents. The symptom is silently wrong gradients, or a version-counter error when the input reaches the backward through `SavedVariable`. Reads of these inputs are pinned `MUST_SAVE`, walking through aliasing ops to the first op that materializes data -- pinning a view pins an alias, not a snapshot. The comment on `force_save_fw_mutated_input_readers` walks through an example of the wrong and the correct partition.

Who hits this: default `torch.compile` (Inductor), whenever min-cut recomputes a read of an input the forward mutates in place, e.g. a registered buffer read by a pointwise op and then updated with `add_`. With the pin disabled, the buffer model below gets wrong gradients at the default budget (1.0) as well as at 0 and 0.05; the gather model in `test_min_cut_no_recompute_through_mutated_input` is wrong at 0 and 0.05 but matches eager at 1.0. `aot_eager` shows the same pattern. To compare pin on and off under Inductor, disable caches: the pin is not part of the AOTAutogradCache key, so the second compile can reuse the first one's graphs.
```
class C2(torch.nn.Module):
    def __init__(self):
        super().__init__()
        self.register_buffer("buf", torch.randn(16))

    def forward(self, x):
        y = (x * (self.buf * 2)).sum()  # eager grad_x = 2 * buf before add_
        self.buf.add_(1.0)
        return y
```

## Details

Aliasing is decided by storage, not op schema, since the `getitem`s of split/chunk/unbind have no schema. A tuple-producing op cannot be saved as a tensor, so every `getitem` below it is pinned, including the nested levels of a `Tensor[]` output; the op itself is pinned too, since min-cut never bans recomputing a `getitem`. `force_save_collectives` and `force_save_effectful_ops` now share this walker (`_leaf_results`) instead of their own recursive copies, with no behavior change.

Mutated inputs are found from metadata AOTAutograd already attaches to the joint graph, so no new metadata is added: forward outputs described by `InputMutationAOTOutput` for mutations the runtime epilogue applies (translated through `SubclassGetAttrAOTOutput` to the inner placeholders' descriptors), and write-backs tagged `must_be_in_forward` (`copy_`, `set_`, `resize_storage_bytes_`) for mutations kept in the graph, so a buffer swapped with `set_` under `no_grad` is found too. This also covers metadata-only mutations such as `t_()`, which hit the same version-counter error today.

Behaviour changes, limited to the pinned reads:
- Activation checkpointing's `PREFER_RECOMPUTE` on such a read is overridden. An explicit `MUST_RECOMPUTE` from a user policy is honored, because the pin is conservative (it also hits reads that do not depend on the mutated data, such as BatchNorm's running-stat updates after decomposition); a one-time warning (`warning_once`) says gradients may be wrong, and the nodes are logged at debug level.
- `default_partition` runs the same pass. Under activation checkpointing it recomputed such reads: with a buffer read inside the checkpointed region and mutated after it, base raises the version-counter error with `keep_inference_input_mutations=False` and gives `2 * (buf + 1)` with `True`; this gives `2 * buf`, matching the function without checkpointing. Eager checkpointing itself recomputes after the mutation and also gives `2 * (buf + 1)`, so the compiled result now matches the un-checkpointed function rather than eager checkpointing.
- `memory_budget == 0` saved only the inputs. It now also saves the pinned reads, including a `getitem` of a forward op that only the backward reads, such as BatchNorm's `save_mean`. Other `MUST_SAVE` marks are still recomputed at budget 0, as before.

Behavior change for BatchNorm: on backends that keep BatchNorm as a single op (eager-style backends such as `aot_eager`), training BatchNorm's outputs are now saved rather than recomputed. This is conservative: the partitioner only sees that `_native_batch_norm_legit_functional` reads the mutated running stats, not that `out`, `save_mean`, and `save_rstd` depend only on batch stats. It costs memory, not correctness; for conv -> BN -> ReLU at budget 0, the full (2, 4, 8, 8) BN output and four (4,) vectors are saved where trunk saves only the inputs, and gradients match eager in both. Under Inductor it is not an issue, because Inductor decomposes BN before partitioning: on the same model, the saved-for-backward set is identical with and without the pin at the default budget and at budgets 0 and 0.05, and the pin lands only on the small running-stat update ops, which feed `copy_` rather than the backward. A follow-up that snapshots each mutated input (clone before the mutation, ban recomputing the clone) and lets min-cut choose between saving the snapshot and saving the reads would remove this over-save.

Relation to #185876 (`aot_runtime_epilogue_input_mutation`): that stops min-cut from saving the placeholder of an input that requires grad and is mutated by the runtime epilogue. This covers inputs that do not require grad, such as buffers, mutations kept in the graph, and metadata-only mutations. Where both apply the results agree.
Buffers mutated by a different compiled region or by eager code are invisible to this graph; an opt-in fix follows in a separate PR.

This PR was authored with an AI assistant.

Test Plan:
```
buck2 test fbcode//mode/opt fbcode//caffe2/test/functorch:test_aotdispatch -- -r 'TestPartitioning'
buck2 test fbcode//mode/opt fbcode//caffe2/test/functorch:test_aotdispatch -- -r 'partition|Partition|mutation|Mutation|checkpoint'
buck2 test fbcode//mode/opt fbcode//caffe2/test/functorch:test_aotdispatch -- --regex 'force_save_effectful|effect_tokens|with_effects'
buck2 test fbcode//mode/opt fbcode//caffe2/test/distributed/tensor:dtensor_compile
```
`TestPartitioning` covers reads through a view, a tuple-producing view, a tuple-producing op read by the backward (budgets 0, 0.05, 0.5), a `(Tensor, Tensor[])` reader under activation checkpointing (budgets 0 and 1.0), an input swapped with `set_` under `no_grad` (`keep_inference_input_mutations=True`, budgets 0 and 1.0), the buffer model above at the default budget, the updated value, a metadata-only mutation (`t_()`), BatchNorm's saved statistics, several gathers at budget 0.05, flat and subclass inputs with `keep_inference_input_mutations` on and off, `default_partition` under activation checkpointing, and an honored `MUST_RECOMPUTE` (warning logged); reads of unmutated inputs are still recomputed. With the base `partitioners.py` swapped in, every new mutating case fails (wrong gradients or `modified by an inplace operation`; for BatchNorm only its structural `assertNotIn` check fails, its gradients match eager either way).
Results: `TestPartitioning` 147 pass, 0 fail; the broader filter 318 pass, 3 fail, all `test_saved_tensors_hooks_mutations_raise`, which hardcodes `device="cuda"` and fails in `torch.ones` with `CUDA error: invalid argument` on this host before compiling; the effectful-op tests 14 pass, 0 fail (they cover the shared walker); `dtensor_compile` 72 pass, 0 fail, 22 skipped.
Descriptor discovery check, with a temporary uncommitted test that wraps `min_cut_rematerialization_partition` and compares the descriptor-derived mutated placeholders with the earlier `input_info.mutates_data`-based names, for a buffer, a `TwoTensor` buffer, a nested `TwoTensor` buffer, no-grad and requires-grad inputs, data plus metadata, and metadata-only mutations, each with `keep_inference_input_mutations` on and off: identical everywhere except metadata-only, which only the descriptors catch; with it pinned, gradients match eager.
Inductor BatchNorm check, with a temporary uncommitted test in `TestPartitioning` that compiles training-mode Conv2d(3, 4) -> BatchNorm2d(4) -> ReLU on a (2, 3, 8, 8) CPU input with `torch.compile(backend="inductor")` (caches disabled), wraps `min_cut_rematerialization_partition` in `torch._inductor.compile_fx` to record the backward graph's non-tangent placeholders, and runs with the pin on and with `force_save_fw_mutated_input_readers` patched to a no-op:
```
buck2 test fbcode//mode/opt fbcode//caffe2/test/functorch:test_aotdispatch -- --regex 'test_zz_tmp_inductor_bn_saved' --print-passing-details
```
The joint graph has no `batch_norm` op (already decomposed) and three `copy_` into the BN buffers (`running_mean`, `running_var`, `num_batches_tracked`). The pin tags `add`, `mul_2`, and `mul_5` (the buffer updates) and nothing the backward reads. Saved sets, identical with and without the pin; gradients and running stats match eager:
- default budget: `primals_1` (4, 3, 3, 3), `primals_3` (2, 3, 8, 8), `primals_7` (4,), `convolution` (2, 4, 8, 8), `squeeze_1` (4,), `le` (2, 4, 8, 8), `unsqueeze_6` (1, 4, 1, 1)
- budget 0: inputs only, `primals_1` (4, 3, 3, 3), `primals_2` (4,), `primals_3` (2, 3, 8, 8), `primals_7` (4,), `primals_8` (4,)
- budget 0.05: the same five inputs plus `getitem_1` (1, 4, 1, 1) and `rsqrt` (1, 4, 1, 1)

Who-hits-this check, with a temporary uncommitted test `test_zzprobe_default_budget` in `TestPartitioning` that compiles `C2` above and the model from `test_min_cut_no_recompute_through_mutated_input` with `torch.compile(backend="inductor")` and `backend="aot_eager"` at the default budget (`activation_memory_budget = 1.0` in `torch/_functorch/config.py`, left unpatched), 0, and 0.05, with the pin on and with `force_save_fw_mutated_input_readers` patched to a no-op. Caches are disabled (`torch.compiler.config.patch(force_disable_caches=True)`, `torch._functorch.config.patch(enable_autograd_cache=False)`), `torch._dynamo.reset()` runs before each compile, and `x.grad` and the buffer are compared against eager on a deepcopy of the module:
```
buck2 test fbcode//mode/opt fbcode//caffe2/test/functorch:test_aotdispatch -- --regex test_zzprobe --print-passing-details
```
- pin off, default budget: `C2` grads wrong (16/16) under both backends; gather model grads match eager under both.
- pin off, budgets 0 and 0.05: both models wrong under both backends (`C2` 16/16, gather model 256/256).
- pin on: every case matches eager. The updated buffer matches eager in every case.

Differential Revision: D118411035

Pull Request resolved: #197039
Approved by: https://github.com/aorenste
taras-janea pushed a commit to taras-janea/pytorch that referenced this pull request Nov 13, 2026
…h#197039) (pytorch#197039)

Summary:

The AOT min-cut partitioner may recompute a value in the backward rather than save it. That is equivalent only when re-execution is value-preserving, which fails for a read of an input the forward mutates: recompute defers the read past the mutation, so the backward observes post-update contents. The symptom is silently wrong gradients, or a version-counter error when the input reaches the backward through `SavedVariable`. Reads of these inputs are pinned `MUST_SAVE`, walking through aliasing ops to the first op that materializes data -- pinning a view pins an alias, not a snapshot. The comment on `force_save_fw_mutated_input_readers` walks through an example of the wrong and the correct partition.

Who hits this: default `torch.compile` (Inductor), whenever min-cut recomputes a read of an input the forward mutates in place, e.g. a registered buffer read by a pointwise op and then updated with `add_`. With the pin disabled, the buffer model below gets wrong gradients at the default budget (1.0) as well as at 0 and 0.05; the gather model in `test_min_cut_no_recompute_through_mutated_input` is wrong at 0 and 0.05 but matches eager at 1.0. `aot_eager` shows the same pattern. To compare pin on and off under Inductor, disable caches: the pin is not part of the AOTAutogradCache key, so the second compile can reuse the first one's graphs.
```
class C2(torch.nn.Module):
    def __init__(self):
        super().__init__()
        self.register_buffer("buf", torch.randn(16))

    def forward(self, x):
        y = (x * (self.buf * 2)).sum()  # eager grad_x = 2 * buf before add_
        self.buf.add_(1.0)
        return y
```

## Details

Aliasing is decided by storage, not op schema, since the `getitem`s of split/chunk/unbind have no schema. A tuple-producing op cannot be saved as a tensor, so every `getitem` below it is pinned, including the nested levels of a `Tensor[]` output; the op itself is pinned too, since min-cut never bans recomputing a `getitem`. `force_save_collectives` and `force_save_effectful_ops` now share this walker (`_leaf_results`) instead of their own recursive copies, with no behavior change.

Mutated inputs are found from metadata AOTAutograd already attaches to the joint graph, so no new metadata is added: forward outputs described by `InputMutationAOTOutput` for mutations the runtime epilogue applies (translated through `SubclassGetAttrAOTOutput` to the inner placeholders' descriptors), and write-backs tagged `must_be_in_forward` (`copy_`, `set_`, `resize_storage_bytes_`) for mutations kept in the graph, so a buffer swapped with `set_` under `no_grad` is found too. This also covers metadata-only mutations such as `t_()`, which hit the same version-counter error today.

Behaviour changes, limited to the pinned reads:
- Activation checkpointing's `PREFER_RECOMPUTE` on such a read is overridden. An explicit `MUST_RECOMPUTE` from a user policy is honored, because the pin is conservative (it also hits reads that do not depend on the mutated data, such as BatchNorm's running-stat updates after decomposition); a one-time warning (`warning_once`) says gradients may be wrong, and the nodes are logged at debug level.
- `default_partition` runs the same pass. Under activation checkpointing it recomputed such reads: with a buffer read inside the checkpointed region and mutated after it, base raises the version-counter error with `keep_inference_input_mutations=False` and gives `2 * (buf + 1)` with `True`; this gives `2 * buf`, matching the function without checkpointing. Eager checkpointing itself recomputes after the mutation and also gives `2 * (buf + 1)`, so the compiled result now matches the un-checkpointed function rather than eager checkpointing.
- `memory_budget == 0` saved only the inputs. It now also saves the pinned reads, including a `getitem` of a forward op that only the backward reads, such as BatchNorm's `save_mean`. Other `MUST_SAVE` marks are still recomputed at budget 0, as before.

Behavior change for BatchNorm: on backends that keep BatchNorm as a single op (eager-style backends such as `aot_eager`), training BatchNorm's outputs are now saved rather than recomputed. This is conservative: the partitioner only sees that `_native_batch_norm_legit_functional` reads the mutated running stats, not that `out`, `save_mean`, and `save_rstd` depend only on batch stats. It costs memory, not correctness; for conv -> BN -> ReLU at budget 0, the full (2, 4, 8, 8) BN output and four (4,) vectors are saved where trunk saves only the inputs, and gradients match eager in both. Under Inductor it is not an issue, because Inductor decomposes BN before partitioning: on the same model, the saved-for-backward set is identical with and without the pin at the default budget and at budgets 0 and 0.05, and the pin lands only on the small running-stat update ops, which feed `copy_` rather than the backward. A follow-up that snapshots each mutated input (clone before the mutation, ban recomputing the clone) and lets min-cut choose between saving the snapshot and saving the reads would remove this over-save.

Relation to pytorch#185876 (`aot_runtime_epilogue_input_mutation`): that stops min-cut from saving the placeholder of an input that requires grad and is mutated by the runtime epilogue. This covers inputs that do not require grad, such as buffers, mutations kept in the graph, and metadata-only mutations. Where both apply the results agree.
Buffers mutated by a different compiled region or by eager code are invisible to this graph; an opt-in fix follows in a separate PR.

This PR was authored with an AI assistant.

Test Plan:
```
buck2 test fbcode//mode/opt fbcode//caffe2/test/functorch:test_aotdispatch -- -r 'TestPartitioning'
buck2 test fbcode//mode/opt fbcode//caffe2/test/functorch:test_aotdispatch -- -r 'partition|Partition|mutation|Mutation|checkpoint'
buck2 test fbcode//mode/opt fbcode//caffe2/test/functorch:test_aotdispatch -- --regex 'force_save_effectful|effect_tokens|with_effects'
buck2 test fbcode//mode/opt fbcode//caffe2/test/distributed/tensor:dtensor_compile
```
`TestPartitioning` covers reads through a view, a tuple-producing view, a tuple-producing op read by the backward (budgets 0, 0.05, 0.5), a `(Tensor, Tensor[])` reader under activation checkpointing (budgets 0 and 1.0), an input swapped with `set_` under `no_grad` (`keep_inference_input_mutations=True`, budgets 0 and 1.0), the buffer model above at the default budget, the updated value, a metadata-only mutation (`t_()`), BatchNorm's saved statistics, several gathers at budget 0.05, flat and subclass inputs with `keep_inference_input_mutations` on and off, `default_partition` under activation checkpointing, and an honored `MUST_RECOMPUTE` (warning logged); reads of unmutated inputs are still recomputed. With the base `partitioners.py` swapped in, every new mutating case fails (wrong gradients or `modified by an inplace operation`; for BatchNorm only its structural `assertNotIn` check fails, its gradients match eager either way).
Results: `TestPartitioning` 147 pass, 0 fail; the broader filter 318 pass, 3 fail, all `test_saved_tensors_hooks_mutations_raise`, which hardcodes `device="cuda"` and fails in `torch.ones` with `CUDA error: invalid argument` on this host before compiling; the effectful-op tests 14 pass, 0 fail (they cover the shared walker); `dtensor_compile` 72 pass, 0 fail, 22 skipped.
Descriptor discovery check, with a temporary uncommitted test that wraps `min_cut_rematerialization_partition` and compares the descriptor-derived mutated placeholders with the earlier `input_info.mutates_data`-based names, for a buffer, a `TwoTensor` buffer, a nested `TwoTensor` buffer, no-grad and requires-grad inputs, data plus metadata, and metadata-only mutations, each with `keep_inference_input_mutations` on and off: identical everywhere except metadata-only, which only the descriptors catch; with it pinned, gradients match eager.
Inductor BatchNorm check, with a temporary uncommitted test in `TestPartitioning` that compiles training-mode Conv2d(3, 4) -> BatchNorm2d(4) -> ReLU on a (2, 3, 8, 8) CPU input with `torch.compile(backend="inductor")` (caches disabled), wraps `min_cut_rematerialization_partition` in `torch._inductor.compile_fx` to record the backward graph's non-tangent placeholders, and runs with the pin on and with `force_save_fw_mutated_input_readers` patched to a no-op:
```
buck2 test fbcode//mode/opt fbcode//caffe2/test/functorch:test_aotdispatch -- --regex 'test_zz_tmp_inductor_bn_saved' --print-passing-details
```
The joint graph has no `batch_norm` op (already decomposed) and three `copy_` into the BN buffers (`running_mean`, `running_var`, `num_batches_tracked`). The pin tags `add`, `mul_2`, and `mul_5` (the buffer updates) and nothing the backward reads. Saved sets, identical with and without the pin; gradients and running stats match eager:
- default budget: `primals_1` (4, 3, 3, 3), `primals_3` (2, 3, 8, 8), `primals_7` (4,), `convolution` (2, 4, 8, 8), `squeeze_1` (4,), `le` (2, 4, 8, 8), `unsqueeze_6` (1, 4, 1, 1)
- budget 0: inputs only, `primals_1` (4, 3, 3, 3), `primals_2` (4,), `primals_3` (2, 3, 8, 8), `primals_7` (4,), `primals_8` (4,)
- budget 0.05: the same five inputs plus `getitem_1` (1, 4, 1, 1) and `rsqrt` (1, 4, 1, 1)

Who-hits-this check, with a temporary uncommitted test `test_zzprobe_default_budget` in `TestPartitioning` that compiles `C2` above and the model from `test_min_cut_no_recompute_through_mutated_input` with `torch.compile(backend="inductor")` and `backend="aot_eager"` at the default budget (`activation_memory_budget = 1.0` in `torch/_functorch/config.py`, left unpatched), 0, and 0.05, with the pin on and with `force_save_fw_mutated_input_readers` patched to a no-op. Caches are disabled (`torch.compiler.config.patch(force_disable_caches=True)`, `torch._functorch.config.patch(enable_autograd_cache=False)`), `torch._dynamo.reset()` runs before each compile, and `x.grad` and the buffer are compared against eager on a deepcopy of the module:
```
buck2 test fbcode//mode/opt fbcode//caffe2/test/functorch:test_aotdispatch -- --regex test_zzprobe --print-passing-details
```
- pin off, default budget: `C2` grads wrong (16/16) under both backends; gather model grads match eager under both.
- pin off, budgets 0 and 0.05: both models wrong under both backends (`C2` 16/16, gather model 256/256).
- pin on: every case matches eager. The updated buffer matches eager in every case.

Differential Revision: D118411035

Pull Request resolved: pytorch#197039
Approved by: https://github.com/aorenste
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agentic Created by an AI agent ci-no-td Do not run TD on this PR ciflow/inductor ciflow/torchtitan Run TorchTitan integration tests ciflow/trunk Trigger trunk jobs on your pull request Merged module: inductor release notes: inductor Reverted

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants