Repository navigation
Conversation
🔗 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 ( 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. |
|
@claude review these changes |
|
Claude finished @jansel's task in 2m 24s —— View job Code Review: Prevent saving mutated grad inputs in AOT min-cut
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.
|
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
|
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. |
|
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
Resolved
Still open
Minor (not blocking)
|
[ghstack-poisoned]
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
|
@claude is this safe to reland? Have all the outstanding issues been resolved? |
|
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 Details
Resolved since the last review
The earlier fixes are still in place: inputs are marked only when their mutation is Still open before reland
Minor, not blocking
|
|
@pytorchbot merge |
Merge startedYour 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 |
#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
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
…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
…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
…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
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
…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
…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
…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
…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
…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
…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
…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
…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
… (#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
…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
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:
Ran 2 tests, OK.
Ran 3 tests, OK.
Ran 9 tests, OK (includes in_graph_mutated_grad_input_backward and
mutated_subclass_input_saved_for_backward for memory budgets 0 and 1).
Ran 65 and 114 tests, OK.
Ran 2 tests, OK.
Ran 10 tests, OK.
Ran 1 test, OK.
Standalone CPU and CUDA eager comparisons for the clone/alias corner case
passed with activation memory budgets 0 and 1.
No lint issues.
cc @voznesenskym @penguinwu @EikanWang @jgong5 @Guobing-Chen @XiaobingSuper @zhuhaozhe @blzheng @wenzhe-nrv @jiayisunx @ipiszy @kadeng @muchulee8 @amjames @chauhang @aakhundov @coconutruben @jataylo