Skip to content

[aot_autograd] Replay an input mutation the way it actually happened - #195359

Closed
bobrenjc93 wants to merge 67 commits into
gh/bobrenjc93/1099/basefrom
gh/bobrenjc93/1099/head
Closed

bobrenjc93 wants to merge 67 commits into
gh/bobrenjc93/1099/basefrom
gh/bobrenjc93/1099/head

Conversation

@bobrenjc93

@bobrenjc93 bobrenjc93 commented Aug 30, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

Mutating an input a custom autograd.Function returned as-is dies in the
mutation epilogue:

RuntimeError: Output 0 of CommOpGradientScaling is a view and is being
modified inplace. This view was created inside a custom Function ...

Autograd gives such an input an identity view stamped
CreationMeta::IN_CUSTOM_FUNCTION, which refuses any tracked in-place edit. The
mutating op declares Tensor(a!) but writes through raw pointers, so eager
never checks the view. AOTAutograd functionalizes the write out of the graph
and replays it at the region boundary as a tracked copy_, which raises.

_replay_input_mutation replays it the way it happened: under grad mode, onto
a requires-grad view stamped IN_CUSTOM_FUNCTION, the write runs under no_grad;
the version counter is preserved only when the traced write was itself hidden
from autograd (a .data-style write), and bumped, as eager's no_grad write did,
when it ran under no_grad or inference mode, so a stale saved tensor is still
caught; everything else gets the tracked copy_. With grad mode off eager writes such a view tracked, and that version
bump later catches a stale saved tensor, so the plain copy_ stands. The
decision is per call, since nothing guards the view's provenance.

Release notes (torch.compile, BC): an autograd-visible in-place write to a view
created inside a custom autograd.Function (or an input it returned as-is),
which eager rejects with the error above, is now replayed without autograd
tracking at the compiled region boundary when grad mode is on and emits a
UserWarning; gradients that later flow through that input see its pre-mutation
history. It warns once per (compiled graph, mutated input index), and not when
the traced mutation was itself hidden from autograd or under no_grad/inference
mode.

The codegen'd leaf branch now raises the unsupported-stream error for a
stream-annotated input, matching the reference.

Test Plan:

python test/functorch/test_aotdispatch.py
python test/functorch/test_codegen_mutation_epilogue.py
python test/functorch/test_compile_to_python.py
python test/dynamo/test_aot_autograd_cache.py
python test/test_precompile.py
python test/dynamo/test_package.py

Tests pin eager-matching gradients on aot_eager and inductor, the eager divergence and single warning, the
no_grad version bump, warn-once across torch._dynamo.reset(), and codegen'd
versus reference epilogue parity.

Authored with an AI assistant.

[no ci]

[ghstack-poisoned]
@pytorch-bot

pytorch-bot Bot commented Aug 30, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

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

[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
bobrenjc93 added a commit that referenced this pull request Sep 2, 2026
A model whose compiled region mutates an input that a custom autograd.Function
returned as-is dies in the mutation epilogue:

    codegen.py:codegen(mutation_epilogue):2  _apply_mutations
    RuntimeError: Output 0 of CommOpGradientScaling is a view and is being
    modified inplace. This view was created inside a custom Function (or
    because an input was returned as-is) ...

Two things have to line up. Returning an input as-is makes autograd substitute
an identity view and stamp it CreationMeta::IN_CUSTOM_FUNCTION
(custom_function.cpp), which refuses any tracked in-place edit. The write is
then done by an op that declares `Tensor(a!)` but goes through raw pointers, so
no version counter moves and eager never runs check_inplace -- and whose meta
kernel writes nothing, so the fake trace does not either. FBGEMM's
fused-optimizer TBE kernels are exactly this shape.

AOTAutograd reads `Tensor(a!)` off the schema, functionalizes the write out of
the graph, and replays it at the region boundary as an ordinary TRACKED
`copy_`. Because the meta kernel never performed the write,
mutations_hidden_from_autograd is recorded False and the mutation cannot stay
in the graph, so the epilogue is the only place left. That replay is the first
autograd-visible in-place op the view has ever seen, and it raises -- for a
mutation that was legal where it originally happened.

Replay it the way it happened instead: `_replay_input_mutation` writes a target
whose CreationMeta is exactly IN_CUSTOM_FUNCTION under no_grad with
`_unsafe_preserve_version_counter`, and emits a plain tracked `copy_` for
everything else. Clearing CreationMeta to force a tracked copy through reroutes
the base's history and silently drops the custom Function's backward --
measured, not assumed. detach() alone and no_grad alone do not fix it at all.
Asking the caller to clone the custom Function's output is not available to
them either: the region boundary, and therefore the replay, is AOTAutograd's
choice, and clone() is not semantics-preserving here.

This is a DELIBERATE divergence from eager, and the trade-off should be stated
plainly. Eager raises the error above on an autograd-VISIBLE in-place write to
such a view; compile cannot tell a `.data`-style write (the motivating case)
from a visible one at the region boundary, because the graph does not guard on
the view's provenance and the op that did the write is gone by the time the
epilogue runs. Replaying invisibly therefore also accepts the write eager would
have refused, and a later use of the view differentiates through the view's
PRE-mutation history: the mutation's contribution to autograd is dropped rather
than reported. Refusing instead would break the case this replay exists for, so
the ambiguous configuration -- grad enabled and the target requiring grad --
emits a warning naming the wrong-gradient risk, once per process. The
once-per-process gate is an `lru_cache`'d helper rather than a module global:
the callers are codegen'd epilogues, each with a fresh fabricated frame, so
warnings' own registry would re-warn per compiled function, and a module flag
is mutable state a test has to save and restore by hand.

The decision is dispatched per call rather than baked into the epilogue,
because nothing guards whether the caller's tensor is such a view: a graph
traced against an ordinary tensor can be handed one later, which for a
serialized artifact means in a different process. Forcing the decision back to
compile time reproduces the error on the second call. The predicate is exactly
IN_CUSTOM_FUNCTION rather than "not DEFAULT": a view made under no_grad or
inference mode, or a multi-output-node view, still takes a tracked copy_, and
writing those invisibly would skip the version bump autograd relies on to catch
a genuinely stale use.

`_replay_input_mutation` is part of the standalone-source surface -- exported
from standalone_runtime and registered in to_standalone_python's
`_known_helper_table` -- so a rendered artifact whose epilogue writes an input
back resolves it like the other runtime helpers. The documented reference
implementation (`_RuntimeForwardEpilogue._apply_input_mutations`) calls the
same helper in its non-leaf data-mutation branch, keeping the file's "keep both
in sync" contract with the codegen; the leaf `detach().copy_()` branch was
already in sync and is unchanged.

Note the neighbouring hazard this deliberately does NOT change: the epilogue
also specializes on is_leaf, which is likewise unguarded, so a function warmed
on a leaf input and then called with a non-leaf silently takes the leaf
branch's detach().copy_() and drops the mutation's contribution to autograd.
That is a separate bug and wants its own change.

Not covered: a plain view of a leaf, whose CreationMeta is DEFAULT, still fails
a different autograd check for the same underlying reason. Widening the
predicate to "any tracked in-place would be rejected here" is likely correct
but risks silently dropping a mutation that autograd should see, so it is left
alone.

Test Plan:

```
python test/functorch/test_aotdispatch.py
python test/functorch/test_codegen_mutation_epilogue.py
python test/dynamo/test_aot_autograd_cache.py
python test/test_precompile.py
python test/dynamo/test_package.py
```

The restricted-view test builds both ingredients -- an opaque `Tensor(a!)` op
that writes through `.data` with a no-op meta kernel, and a target that a
custom Function returned as-is -- and asserts the gradients (the base's, the
other input's, and the mutated tensor) match uncompiled eager on aot_eager and
inductor, rather than merely that nothing raised. It then warms on an ordinary
tensor and calls again with the restricted view, which is the case the
per-call dispatch exists for. It fails without this change with the verbatim
error above. A second test pins the divergence: a visible in-place write to
such a view raises in eager and is replayed invisibly under compile, with the
warning emitted exactly once across repeated replays and not at all in the
unambiguous no-grad serving configuration.

test_codegen_mutation_epilogue asserted on the literal copy_ this epilogue used
to emit. The write-back is spelled _replay_input_mutation now, so the three
tests that reach the general path assert on that instead; the leaf-under-no_grad
case still emits detach().copy_() directly and is unchanged.

Authored with an AI assistant.

ghstack-source-id: ea9da22
Pull-Request: #195359
[ghstack-poisoned]
bobrenjc93 added a commit that referenced this pull request Sep 2, 2026
A model whose compiled region mutates an input that a custom autograd.Function
returned as-is dies in the mutation epilogue:

    codegen.py:codegen(mutation_epilogue):2  _apply_mutations
    RuntimeError: Output 0 of CommOpGradientScaling is a view and is being
    modified inplace. This view was created inside a custom Function (or
    because an input was returned as-is) ...

Two things have to line up. Returning an input as-is makes autograd substitute
an identity view and stamp it CreationMeta::IN_CUSTOM_FUNCTION
(custom_function.cpp), which refuses any tracked in-place edit. The write is
then done by an op that declares `Tensor(a!)` but goes through raw pointers, so
no version counter moves and eager never runs check_inplace -- and whose meta
kernel writes nothing, so the fake trace does not either. FBGEMM's
fused-optimizer TBE kernels are exactly this shape.

AOTAutograd reads `Tensor(a!)` off the schema, functionalizes the write out of
the graph, and replays it at the region boundary as an ordinary TRACKED
`copy_`. Because the meta kernel never performed the write,
mutations_hidden_from_autograd is recorded False and the mutation cannot stay
in the graph, so the epilogue is the only place left. That replay is the first
autograd-visible in-place op the view has ever seen, and it raises -- for a
mutation that was legal where it originally happened.

Replay it the way it happened instead: `_replay_input_mutation` writes a target
whose CreationMeta is exactly IN_CUSTOM_FUNCTION under no_grad with
`_unsafe_preserve_version_counter`, and emits a plain tracked `copy_` for
everything else. Clearing CreationMeta to force a tracked copy through reroutes
the base's history and silently drops the custom Function's backward --
measured, not assumed. detach() alone and no_grad alone do not fix it at all.
Asking the caller to clone the custom Function's output is not available to
them either: the region boundary, and therefore the replay, is AOTAutograd's
choice, and clone() is not semantics-preserving here.

This is a DELIBERATE divergence from eager, and the trade-off should be stated
plainly. Eager raises the error above on an autograd-VISIBLE in-place write to
such a view; compile cannot tell a `.data`-style write (the motivating case)
from a visible one at the region boundary, because the graph does not guard on
the view's provenance and the op that did the write is gone by the time the
epilogue runs. Replaying invisibly therefore also accepts the write eager would
have refused, and a later use of the view differentiates through the view's
PRE-mutation history: the mutation's contribution to autograd is dropped rather
than reported. Refusing instead would break the case this replay exists for, so
the ambiguous configuration -- grad enabled and the target requiring grad --
emits a warning naming the wrong-gradient risk, once per process per mutated
input index (the index is the input's position among the compiled function's
inputs, and the message names it). The gate is a `functools.cache`'d helper
keyed on that index rather than a module global: the callers are codegen'd
epilogues, each with a fresh fabricated frame, so warnings' own registry would
re-warn per compiled function, and a module flag is mutable state a test has
to save and restore by hand. The reference epilogue and the codegen'd one
must hand the helper the same index; a test pins that the emitted call is
`_replay_input_mutation(orig_inputs[i], updated_inputs[k], i)` for a case
where the mutated slot k and the runtime input index i differ.

The decision is dispatched per call rather than baked into the epilogue,
because nothing guards whether the caller's tensor is such a view: a graph
traced against an ordinary tensor can be handed one later, which for a
serialized artifact means in a different process. Forcing the decision back to
compile time reproduces the error on the second call. The predicate is exactly
IN_CUSTOM_FUNCTION rather than "not DEFAULT": a view made under no_grad or
inference mode, or a multi-output-node view, still takes a tracked copy_, and
writing those invisibly would skip the version bump autograd relies on to catch
a genuinely stale use.

`_replay_input_mutation` is part of the standalone-source surface -- exported
from standalone_runtime and registered in to_standalone_python's
`_known_helper_table` -- so a rendered artifact whose epilogue writes an input
back resolves it like the other runtime helpers. The documented reference
implementation (`_RuntimeForwardEpilogue._apply_input_mutations`) calls the
same helper in its non-leaf data-mutation branch, keeping the file's "keep both
in sync" contract with the codegen; the leaf `detach().copy_()` branch was
already in sync and is unchanged.

Note the neighbouring hazard this deliberately does NOT change: the epilogue
also specializes on is_leaf, which is likewise unguarded, so a function warmed
on a leaf input and then called with a non-leaf silently takes the leaf
branch's detach().copy_() and drops the mutation's contribution to autograd.
That is a separate bug and wants its own change.

Not covered: a plain view of a leaf, whose CreationMeta is DEFAULT, still fails
a different autograd check for the same underlying reason. Widening the
predicate to "any tracked in-place would be rejected here" is likely correct
but risks silently dropping a mutation that autograd should see, so it is left
alone.

Test Plan:

```
python test/functorch/test_aotdispatch.py
python test/functorch/test_codegen_mutation_epilogue.py
python test/dynamo/test_aot_autograd_cache.py
python test/test_precompile.py
python test/dynamo/test_package.py
```

The restricted-view test builds both ingredients -- an opaque `Tensor(a!)` op
that writes through `.data` with a no-op meta kernel, and a target that a
custom Function returned as-is -- and asserts the gradients (the base's, the
other input's, and the mutated tensor) match uncompiled eager on aot_eager and
inductor, rather than merely that nothing raised. It then warms on an ordinary
tensor and calls again with the restricted view, which is the case the
per-call dispatch exists for. It fails without this change with the verbatim
error above. A second test pins the divergence: a visible in-place write to
such a view raises in eager and is replayed invisibly under compile, with the
warning emitted exactly once across repeated replays and not at all in the
unambiguous no-grad serving configuration.

test_codegen_mutation_epilogue asserted on the literal copy_ this epilogue used
to emit. The write-back is spelled _replay_input_mutation now, so the three
tests that reach the general path assert on that instead; the leaf-under-no_grad
case still emits detach().copy_() directly and is unchanged.

Authored with an AI assistant.

ghstack-source-id: f031ada
Pull-Request: #195359
bobrenjc93 added a commit that referenced this pull request Sep 2, 2026
A model whose compiled region mutates an input that a custom autograd.Function
returned as-is dies in the mutation epilogue:

    codegen.py:codegen(mutation_epilogue):2  _apply_mutations
    RuntimeError: Output 0 of CommOpGradientScaling is a view and is being
    modified inplace. This view was created inside a custom Function (or
    because an input was returned as-is) ...

Two things have to line up. Returning an input as-is makes autograd substitute
an identity view and stamp it CreationMeta::IN_CUSTOM_FUNCTION
(custom_function.cpp), which refuses any tracked in-place edit. The write is
then done by an op that declares `Tensor(a!)` but goes through raw pointers, so
no version counter moves and eager never runs check_inplace -- and whose meta
kernel writes nothing, so the fake trace does not either. FBGEMM's
fused-optimizer TBE kernels are exactly this shape.

AOTAutograd reads `Tensor(a!)` off the schema, functionalizes the write out of
the graph, and replays it at the region boundary as an ordinary TRACKED
`copy_`. Because the meta kernel never performed the write,
mutations_hidden_from_autograd is recorded False and the mutation cannot stay
in the graph, so the epilogue is the only place left. That replay is the first
autograd-visible in-place op the view has ever seen, and it raises -- for a
mutation that was legal where it originally happened.

Replay it the way it happened instead: `_replay_input_mutation` writes a target
whose CreationMeta is exactly IN_CUSTOM_FUNCTION under no_grad with
`_unsafe_preserve_version_counter`, and emits a plain tracked `copy_` for
everything else. Clearing CreationMeta to force a tracked copy through reroutes
the base's history and silently drops the custom Function's backward --
measured, not assumed. detach() alone and no_grad alone do not fix it at all.
Asking the caller to clone the custom Function's output is not available to
them either: the region boundary, and therefore the replay, is AOTAutograd's
choice, and clone() is not semantics-preserving here.

This is a DELIBERATE divergence from eager, and the trade-off should be stated
plainly. Eager raises the error above on an autograd-VISIBLE in-place write to
such a view; compile cannot tell a `.data`-style write (the motivating case)
from a visible one at the region boundary, because the graph does not guard on
the view's provenance and the op that did the write is gone by the time the
epilogue runs. Replaying invisibly therefore also accepts the write eager would
have refused, and a later use of the view differentiates through the view's
PRE-mutation history: the mutation's contribution to autograd is dropped rather
than reported. Refusing instead would break the case this replay exists for, so
the ambiguous configuration -- grad enabled and the target requiring grad --
emits a warning naming the wrong-gradient risk, once per process per mutated
input index (the index is the input's position among the compiled function's
inputs, and the message names it). The gate is a `functools.cache`'d helper
keyed on that index rather than a module global: the callers are codegen'd
epilogues, each with a fresh fabricated frame, so warnings' own registry would
re-warn per compiled function, and a module flag is mutable state a test has
to save and restore by hand. The reference epilogue and the codegen'd one
must hand the helper the same index; a test pins that the emitted call is
`_replay_input_mutation(orig_inputs[i], updated_inputs[k], i)` for a case
where the mutated slot k and the runtime input index i differ.

The decision is dispatched per call rather than baked into the epilogue,
because nothing guards whether the caller's tensor is such a view: a graph
traced against an ordinary tensor can be handed one later, which for a
serialized artifact means in a different process. Forcing the decision back to
compile time reproduces the error on the second call. The predicate is exactly
IN_CUSTOM_FUNCTION rather than "not DEFAULT": a view made under no_grad or
inference mode, or a multi-output-node view, still takes a tracked copy_, and
writing those invisibly would skip the version bump autograd relies on to catch
a genuinely stale use.

`_replay_input_mutation` is part of the standalone-source surface -- exported
from standalone_runtime and registered in to_standalone_python's
`_known_helper_table` -- so a rendered artifact whose epilogue writes an input
back resolves it like the other runtime helpers. The documented reference
implementation (`_RuntimeForwardEpilogue._apply_input_mutations`) calls the
same helper in its non-leaf data-mutation branch, keeping the file's "keep both
in sync" contract with the codegen; the leaf `detach().copy_()` branch was
already in sync and is unchanged.

Note the neighbouring hazard this deliberately does NOT change: the epilogue
also specializes on is_leaf, which is likewise unguarded, so a function warmed
on a leaf input and then called with a non-leaf silently takes the leaf
branch's detach().copy_() and drops the mutation's contribution to autograd.
That is a separate bug and wants its own change.

Not covered: a plain view of a leaf, whose CreationMeta is DEFAULT, still fails
a different autograd check for the same underlying reason. Widening the
predicate to "any tracked in-place would be rejected here" is likely correct
but risks silently dropping a mutation that autograd should see, so it is left
alone.

Test Plan:

```
python test/functorch/test_aotdispatch.py
python test/functorch/test_codegen_mutation_epilogue.py
python test/dynamo/test_aot_autograd_cache.py
python test/test_precompile.py
python test/dynamo/test_package.py
```

The restricted-view test builds both ingredients -- an opaque `Tensor(a!)` op
that writes through `.data` with a no-op meta kernel, and a target that a
custom Function returned as-is -- and asserts the gradients (the base's, the
other input's, and the mutated tensor) match uncompiled eager on aot_eager and
inductor, rather than merely that nothing raised. It then warms on an ordinary
tensor and calls again with the restricted view, which is the case the
per-call dispatch exists for. It fails without this change with the verbatim
error above. A second test pins the divergence: a visible in-place write to
such a view raises in eager and is replayed invisibly under compile, with the
warning emitted exactly once across repeated replays and not at all in the
unambiguous no-grad serving configuration.

test_codegen_mutation_epilogue asserted on the literal copy_ this epilogue used
to emit. The write-back is spelled _replay_input_mutation now, so the three
tests that reach the general path assert on that instead; the leaf-under-no_grad
case still emits detach().copy_() directly and is unchanged.

Authored with an AI assistant.

ghstack-source-id: f031ada
Pull-Request: #195359
bobrenjc93 added a commit that referenced this pull request Sep 2, 2026
A model whose compiled region mutates an input that a custom autograd.Function
returned as-is dies in the mutation epilogue:

    codegen.py:codegen(mutation_epilogue):2  _apply_mutations
    RuntimeError: Output 0 of CommOpGradientScaling is a view and is being
    modified inplace. This view was created inside a custom Function (or
    because an input was returned as-is) ...

Two things have to line up. Returning an input as-is makes autograd substitute
an identity view and stamp it CreationMeta::IN_CUSTOM_FUNCTION
(custom_function.cpp), which refuses any tracked in-place edit. The write is
then done by an op that declares `Tensor(a!)` but goes through raw pointers, so
no version counter moves and eager never runs check_inplace -- and whose meta
kernel writes nothing, so the fake trace does not either. FBGEMM's
fused-optimizer TBE kernels are exactly this shape.

AOTAutograd reads `Tensor(a!)` off the schema, functionalizes the write out of
the graph, and replays it at the region boundary as an ordinary TRACKED
`copy_`. Because the meta kernel never performed the write,
mutations_hidden_from_autograd is recorded False and the mutation cannot stay
in the graph, so the epilogue is the only place left. That replay is the first
autograd-visible in-place op the view has ever seen, and it raises -- for a
mutation that was legal where it originally happened.

Replay it the way it happened instead: `_replay_input_mutation` writes a target
whose CreationMeta is exactly IN_CUSTOM_FUNCTION under no_grad with
`_unsafe_preserve_version_counter`, and emits a plain tracked `copy_` for
everything else. Clearing CreationMeta to force a tracked copy through reroutes
the base's history and silently drops the custom Function's backward --
measured, not assumed. detach() alone and no_grad alone do not fix it at all.
Asking the caller to clone the custom Function's output is not available to
them either: the region boundary, and therefore the replay, is AOTAutograd's
choice, and clone() is not semantics-preserving here.

This is a DELIBERATE divergence from eager, and the trade-off should be stated
plainly. Eager raises the error above on an autograd-VISIBLE in-place write to
such a view; compile cannot tell a `.data`-style write (the motivating case)
from a visible one at the region boundary, because the graph does not guard on
the view's provenance and the op that did the write is gone by the time the
epilogue runs. Replaying invisibly therefore also accepts the write eager would
have refused, and a later use of the view differentiates through the view's
PRE-mutation history: the mutation's contribution to autograd is dropped rather
than reported. Refusing instead would break the case this replay exists for, so
the ambiguous configuration -- grad enabled and the target requiring grad --
emits a warning naming the wrong-gradient risk, once per process per mutated
input index (the index is the input's position among the compiled function's
inputs, and the message names it). The gate is a `functools.cache`'d helper
keyed on that index rather than a module global: the callers are codegen'd
epilogues, each with a fresh fabricated frame, so warnings' own registry would
re-warn per compiled function, and a module flag is mutable state a test has
to save and restore by hand. The reference epilogue and the codegen'd one
must hand the helper the same index; a test pins that the emitted call is
`_replay_input_mutation(orig_inputs[i], updated_inputs[k], i)` for a case
where the mutated slot k and the runtime input index i differ.

The decision is dispatched per call rather than baked into the epilogue,
because nothing guards whether the caller's tensor is such a view: a graph
traced against an ordinary tensor can be handed one later, which for a
serialized artifact means in a different process. Forcing the decision back to
compile time reproduces the error on the second call. The predicate is exactly
IN_CUSTOM_FUNCTION rather than "not DEFAULT": a view made under no_grad or
inference mode, or a multi-output-node view, still takes a tracked copy_, and
writing those invisibly would skip the version bump autograd relies on to catch
a genuinely stale use.

`_replay_input_mutation` is part of the standalone-source surface -- exported
from standalone_runtime and registered in to_standalone_python's
`_known_helper_table` -- so a rendered artifact whose epilogue writes an input
back resolves it like the other runtime helpers. The documented reference
implementation (`_RuntimeForwardEpilogue._apply_input_mutations`) calls the
same helper in its non-leaf data-mutation branch, keeping the file's "keep both
in sync" contract with the codegen; the leaf `detach().copy_()` branch was
already in sync and is unchanged.

Note the neighbouring hazard this deliberately does NOT change: the epilogue
also specializes on is_leaf, which is likewise unguarded, so a function warmed
on a leaf input and then called with a non-leaf silently takes the leaf
branch's detach().copy_() and drops the mutation's contribution to autograd.
That is a separate bug and wants its own change.

Not covered: a plain view of a leaf, whose CreationMeta is DEFAULT, still fails
a different autograd check for the same underlying reason. Widening the
predicate to "any tracked in-place would be rejected here" is likely correct
but risks silently dropping a mutation that autograd should see, so it is left
alone.

Test Plan:

```
python test/functorch/test_aotdispatch.py
python test/functorch/test_codegen_mutation_epilogue.py
python test/dynamo/test_aot_autograd_cache.py
python test/test_precompile.py
python test/dynamo/test_package.py
```

The restricted-view test builds both ingredients -- an opaque `Tensor(a!)` op
that writes through `.data` with a no-op meta kernel, and a target that a
custom Function returned as-is -- and asserts the gradients (the base's, the
other input's, and the mutated tensor) match uncompiled eager on aot_eager and
inductor, rather than merely that nothing raised. It then warms on an ordinary
tensor and calls again with the restricted view, which is the case the
per-call dispatch exists for. It fails without this change with the verbatim
error above. A second test pins the divergence: a visible in-place write to
such a view raises in eager and is replayed invisibly under compile, with the
warning emitted exactly once across repeated replays and not at all in the
unambiguous no-grad serving configuration.

test_codegen_mutation_epilogue asserted on the literal copy_ this epilogue used
to emit. The write-back is spelled _replay_input_mutation now, so the three
tests that reach the general path assert on that instead; the leaf-under-no_grad
case still emits detach().copy_() directly and is unchanged.

Authored with an AI assistant.

ghstack-source-id: f031ada
Pull-Request: #195359
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
@bobrenjc93

Copy link
Copy Markdown
Contributor Author

Thanks for the thorough review -- addressed the full set. Summary of resolutions:

Correctness (the CreationMeta gate). Fixed. _replay_input_mutation now
mirrors the in-graph copy_ epilogue in graph_capture_wrappers.py instead of
gating on IN_CUSTOM_FUNCTION: hidden replays under no_grad with the version
counter preserved (except inference tensors, which have none), under_no_grad
replays under no_grad and lets the counter bump, and only the remaining
autograd-visible case keeps the IN_CUSTOM_FUNCTION check plus warning. A hidden /
no_grad mutation of a MULTI_OUTPUT_NODE (or NO_GRAD_MODE / INFERENCE_MODE)
view no longer falls through to a bare tracked copy_, so it stops crashing where
eager accepts it. Added direct unit tests over an unbind() MULTI_OUTPUT_NODE
view for both the hidden (VC preserved) and under_no_grad (VC bumped) arms.

orig.requires_grad too narrow. Fixed -- the visible-case gate now checks
orig.requires_grad or updated.requires_grad, since copy_ tracks from either
operand.

Cache-entry compile-id stamping. Fixed. _create_runtime_wrapper no longer
writes compile_id_str back onto runtime_metadata (which is pickled into the
cached BundledAOTAutogradResult and would brand every deserialized entry with the
load-time compile id). The compile id is threaded as a local and the codegen'd
epilogue's {cid!r} reads that local.

BC (error -> warning). Fixed. Added
torch._functorch.config.error_on_custom_function_view_input_mutation
(default False, preserving the new warn behavior); set it to restore the
pre-warning RuntimeError. Test covers both modes.

warnings.warn stacklevel / signature. Fixed -- added stacklevel, and made
the codegen-time constants (idx, compile_id, warned, hidden,
under_no_grad) keyword-only with a *, updating the codegen call site to pass
them by keyword.

Docstring. Trimmed to the non-obvious "why" and corrected: the version counter
is preserved for hidden and bumped for under_no_grad (which the branch ordering
now guarantees is only reached when hidden is False).

Export round-trip (_warned_inputs). Fixed on the export side:
to_standalone_python now emits _warned_inputs = set() (a fresh empty set)
instead of hoisting the live warn-once set, so the artifact round-trips
deterministically and starts its own warn-once cycle. Added an export test that
reaches the mutation epilogue and pins the fresh-set emission plus eager-matching
mutation. (Note: the leak is latent today -- capture happens pre-execution so the
set is already empty -- but the explicit reset makes the invariant robust.)

Deferred to FAQ (added to the PR description): the per-call branch chain on the
common path (the visible-case check is a caller-tensor property that can't be
baked), the unlocked warn-once check-then-add (benign, matches house style), the
grad-mode read vs _set_grad_enabled ordering (only affects the divergence-warning
heuristic after the inversion), and device-generic tests (behavior is
device-agnostic; a suite-wide sweep is a follow-up).

@claude please re-review.

@claude

claude Bot commented Sep 7, 2026 •

Copy link
Copy Markdown

Claude finished @bobrenjc93's task in 18m 32s —— View job


Claude PR re-review

The five substantive findings from the first pass are genuinely fixed — the gate now mirrors graph_capture_wrappers instead of gating on IN_CUSTOM_FUNCTION, the requires_grad predicate is widened, the compile-id no longer brands cache entries, there's a real config escape hatch, and the signature is keyword-only — but the two codegen-parity tests still assert the old positional call string so they will fail as written, and the new export test looks like it asserts on a module that never contains a mutation epilogue, leaving the export fix still unverified.

Full re-review — verified fixes + 7 remaining findings

Verified fixed

First-pass finding Status
IN_CUSTOM_FUNCTION-only gate leaves MULTI_OUTPUT_NODE etc. crashing Fixed. runtime_wrappers.py:268-282 now branches on hidden → under_no_grad → visible, structurally identical to graph_capture_wrappers.py:817-836 (including the is_inference() no-VC carve-out). Confirmed against can_mutate_inplace (VariableTypeUtils.h:46-65): the !requires_grad || !GradMode::is_enabled() early-out means both new arms bypass handle_view_on_rebase for every non-DEFAULT CreationMeta, not just IN_CUSTOM_FUNCTION.
orig.requires_grad too narrow Fixed. :286 is now orig.requires_grad or updated.requires_grad, matching compute_requires_grad(self, src).
compile-id stamped onto pickled runtime_metadata Fixed (with a new skew — see F3). :1064-1072 threads a local; nothing writes runtime_metadata.compile_id_str in _create_runtime_wrapper any more.
No BC opt-out Fixed. config.error_on_custom_function_view_input_mutation (config.py:51-57), read at call time inside the helper so it stays live for cached and exported artifacts. Not in _save_config_ignore, so it participates in the cache key — correct.
stacklevel / keyword-only Partially — see F6.
Docstring restatement + the hidden-wins inaccuracy Fixed. :251-266 is materially shorter and the ordering claim is now correct.

Also verified safe: the short-circuit at :287-289 is well-ordered — _is_view() is diff_view_meta->has_bw_view() (variable.cpp:643-650) which implies the non-null meta that _get_creation_meta's TORCH_CHECK (init.cpp:623-627) requires, so the check can't blow up on a non-view.

Remaining findings

F1 — test_codegen_mutation_epilogue.py:215 and :263 still assert the pre-keyword-only call string. Codegen at runtime_wrappers.py:1242-1246 emits:

orig_inputs[1], updated_inputs[0], idx=1, compile_id='0/0', warned=_warned_inputs, hidden=False, under_no_grad=False

Both tests compare the re.findall capture against a positional string:

expected = f"orig_inputs[1], updated_inputs[0], 1, {cid!r}, _warned_inputs, False, False"   # :215
expected = "orig_inputs[0], updated_inputs[0], 0, None, _warned_inputs, False, False"       # :263

The regexes still match, so these fail on assertEqual, not on "no match". CI will catch it, but it means the two tests that pin codegen/reference parity were not re-run after the signature change — worth re-running that file locally before the next push. Fix this →

F2 — test_input_mutation_epilogue_emits_fresh_warned_inputs_set (test_compile_to_python.py:281-299) does not appear to reach the mutation epilogue, so assertIn("_warned_inputs = set()", src) should fail. _BufferMutate (:115-122) mutates a non-requires-grad buffer with add_, data-only, and compile_to_python drives compile_fx with keep_inference_input_mutations=True (compile_fx.py:3502) under torch.no_grad() (to_standalone_python.py:968-969). In _check_if_mutation_can_be_in_graph (functional_utils.py:673-680) that gives mutates_data and (not mutates_metadata and not requires_grad) → in_graph=True → MUTATED_IN_GRAPH → num_mutated_inp_runtime_indices == 0, so the whole runtime_metadata.num_mutated_inp_runtime_indices > 0 block at :1175 is skipped and _warned_inputs is never bound. That is exactly why the sibling test_input_mutation_copy_back_runs_like_eager (:262) passes today without any epilogue: the copy-back is in-graph.

This is the same reachability gap as the first pass. To exercise the epilogue from compile_to_python the module needs an out-of-graph mutation — data and metadata (e.g. transpose_ then mul_) or a requires-grad target. Until such a case exists, the to_standalone_python.py:564-569 fix is unverified end-to-end and only the set() string is (not) being checked. Medium-high confidence: torch isn't built in this checkout so I could not run it; CI settles it. Fix this →

F3 — removing the write-back introduced a reference/codegen skew on compile_id. The stamp is gone, but _apply_input_mutations still reads self.runtime_metadata.compile_id_str (:881) while the codegen'd path bakes the new local (:1241). On the training path _AOTDispatchAutogradFunctionFactory.build() (:3492-3494) still sets it, so they agree — which is why test_codegen_epilogue_matches_reference_on_custom_function_view can assert compile_id_str is not None. On the inference path nothing sets it, so the reference now warns with no graph id while codegen names one. The file's own contract is explicit ("WARNING: this is a reference implementation ... Keep both in sync", :740-742), and there is a parity test suite specifically for this. Cleanest fix: add compile_id_str: str \| None = None as a field on _RuntimeForwardEpilogue and pass the local in, so both read the same value. Fix this →

F4 — the export fix is keyed off a bare global name. to_standalone_python.py:567 special-cases if gname == "_warned_inputs". Renaming the bind key at runtime_wrappers.py:1187 silently reverts to hoisting the live set with no test failing (F2 means nothing pins it today either). A rename-safe form — matching on the object (isinstance(gobj, set) plus a marker type, or having codegen bind a factory the emitter recognizes) — would make the invariant hold structurally. Also note the first pass's observation still stands: _reject_shared_mutable (source_emit.py:87-107) can't catch a set shared across two globals because _seen is per-emit_value; latent, not a bug today.

F5 — the escape hatch covers the warning but not the semantics change the inversion brings. error_on_custom_function_view_input_mutation gates only the visible arm. The hidden and under_no_grad arms are new behavior for every out-of-graph mutation, not just custom-function views: on the base branch both did a bare tracked copy_ (:874 previously original_inpt.copy_(updated_inpt)), so hidden mutations bumped the version counter and under_no_grad mutations were autograd-tracked. Both now change. Reachable whenever keep_input_mutations=False (the training default) or on the mutates_data and mutates_metadata path.

I think both changes are correct — a .data write gives x.data a fresh VC (variable.cpp:472-480) so eager never bumps x._version, and eager's no_grad write is untracked — i.e. the base branch was over-strict and could raise stale-saved-tensor errors eager does not. But it is a wider release note than "an autograd-visible write to an IN_CUSTOM_FUNCTION view", and a user relying on the old spurious version bump as a tripwire has no flag to get it back. Worth either widening the release note or saying explicitly in it that hidden/no_grad out-of-graph mutations now match the in-graph epilogue's version-counter semantics.

F6 — stacklevel=2 does not reach the user's frame. From _replay_input_mutation, frame 2 is either the exec'd codegen'd _apply_mutations source or _RuntimeForwardEpilogue._apply_input_mutations — the user's call site is many frames further up and at a different depth on the two paths. So the warning still doesn't point at anything actionable. Either drop it (the message already names the input index and graph id, which is the actionable part) or note in a comment why a fixed stacklevel can't work here.

F7 (nit) — misplaced comment. :284 puts "pybind11 hands back a fresh enum object each call, so this cannot be is" directly above torch.is_grad_enabled(), three conjuncts before the == it explains. Move it next to the _get_creation_meta compare at :288.

Test coverage

Good additions: test_replay_input_mutation_hidden_on_multi_output_view and ..._no_grad_on_multi_output_view (test_aotdispatch.py:5530, :5562) directly pin the two new arms on a real MULTI_OUTPUT_NODE view and assert the VC-preserved / VC-bumped split plus zero warnings — that closes the first pass's hidden=True-untested gap. test_replay_input_mutation_error_config_restores_raise (:5588) covers both flag states.

Still uncovered: hidden=True combined with under_no_grad=True (a .data write inside no_grad, which collect_metadata_analysis.py sets both flags for) — the branch ordering makes hidden win, which is the intended behavior and is worth one assertion since it is the one combination where the two flags conflict. And per F2, the export path.

Recommendation

Request Changes, but narrowly: F1 and F2 are test bugs (F1 certain, F2 high-confidence) that mean the parity and export claims aren't actually being checked, and F3 is a small regression introduced by the compile-id fix. The core logic change is correct and now genuinely mirrors the in-graph epilogue. F4–F7 are polish.

· branch `gh/bobrenjc93/1099/head`

[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
@bobrenjc93

Copy link
Copy Markdown
Contributor Author

Thanks for the re-review. Addressed at HEAD:

  • F1 test_codegen_mutation_epilogue.py parity string: fixed. Both goldens now assert the keyword form the codegen emits: orig_inputs[1], updated_inputs[0], idx=1, compile_id={cid!r}, warned=_warned_inputs, hidden=False, under_no_grad=False (and the idx=0, compile_id=None case). File is green (8/8).
  • F2 export fix unverified end-to-end: the parity test test_input_mutation_epilogue_emits_fresh_warned_inputs_set uses _ParamMutateNoGrad (a parameter mutated under no_grad inside a joint forward+backward), which reaches the runtime epilogue via _replay_input_mutation -- not _BufferMutate, whose plain data mutation folds into the graph. The test asserts _replay_input_mutation and _warned_inputs = set() appear in the exported source, so the epilogue is genuinely codegen'd and the reset is exercised (green).
  • F3 compile-id reference/codegen skew: fixed exactly as suggested. _RuntimeForwardEpilogue now carries a compile_id_str: str | None = None field resolved in __post_init__ via a shared _resolve_compile_id_str(runtime_metadata) helper (falls back to CompileContext.current_compile_id() when the metadata field is unset on the inference path). The reference read and the codegen local both route through that one helper, so they brand the warning identically.
  • F6 stacklevel: fixed -- dropped stacklevel=2 with a comment explaining the mutation was captured at trace time, so the writing user frame isn't on the replay call stack (which differs between the reference epilogue and the exec'd source anyway).
  • F7 misplaced comment: fixed -- the pybind11-enum comment now sits directly above the _get_creation_meta(orig) == ... IN_CUSTOM_FUNCTION comparison it explains.

Deferred with rationale in new FAQ entries in the PR description:

  • F4 _warned_inputs name-based export match (rename touches codegen + rewrite in one commit; parity test pins the emitted string).
  • F5 release-note scope (widened to say out-of-graph replay reproduces the captured no_grad/version-counter semantics for every out-of-graph mutation, and the config flag governs only the visible-view warning/raise).

[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
@bobrenjc93 bobrenjc93 closed this Sep 19, 2026
@github-actions
github-actions Bot deleted the gh/bobrenjc93/1099/head branch November 17, 2026 01:45
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/inductor ciflow/trunk Trigger trunk jobs on your pull request release notes: dynamo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant