Repository navigation
[aot_autograd] Don't let a non-differentiable output mark its aliases - #195357
bobrenjc93 wants to merge 68 commits into
Conversation
[ghstack-poisoned]
🔗 Helpful Links🧪 See artifacts and rendered test results at hud.pytorch.org/pr/195357
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]
torch.compile(backend="inductor") silently returns no gradient for
def f(x):
y = torch.sin(x)
return y[0:4], y[4:8], y.detach()
Eager gives grad_fn [True, True, False] and a populated x.grad; inductor gives
[False, False, False] and x.grad is None. Adding a fourth, independently
differentiable output turns the silent wrong answer into a crash in the
compiled backward -- "TypeError: expected Tensor() for op: input" out of
inductor's assert_size_stride_grouped, or "Expected tensors only, but got
NoneType" out of copy_misaligned_inputs when the backward has no kernels for
the asserts to attach to.
ctx.mark_non_differentiable is keyed on TensorImpl, so marking one returned
slot marks EVERY returned slot holding that same object, and the forward
epilogue pairs it with ctx._materialize_non_diff_grads = False, which makes a
marked slot's grad arrive as None rather than zeros. Backends are free to
return one object in two slots: inductor lowers aten.detach to a no-op, and
h * 1 / h + 0 fold away. So
* `return y[:2], y[2:], y.detach()` marks y's intermediate base -- a slot
_codegen_backward_prologue keeps unconditionally -- and the base's tangent
arrives None, which process_runtime_tangent forwards verbatim; and
* `return h * 1, h.detach()` marks the sibling output, which is the only
differentiable thing in the model.
The metadata is not at fault: the backward's predicate,
requires_grad_for_backward, is a strict subset of the forward's requires_grad
(collect_metadata_analysis.py), so no slot is dropped by one and kept by the
other. Only the runtime identity collision is.
Give each slot about to be marked its own TensorImpl instead
(`_dealias_marked_returns`). That is sound precisely because we are about to
declare the slot non-differentiable, so an alias of it is as good as the
original; slots that stay differentiable keep their identity. The rejected
alternative was to skip marking any slot that aliases a surviving one, which
spares the base but also spares the detach output -- it comes back with
requires_grad=True and a grad_fn, and backward flows through a detached tensor.
Fixing this in inductor instead would be the wrong layer twice over: detach is
not the culprit (h * 1 reproduces it with no detach anywhere), and AOTAutograd
is the component making the identity-keyed call.
The codegen emits the dealias and the per-slot Tensor checks it feeds in one
block, and the helper is part of the standalone-source surface: it is exported
from standalone_runtime and registered in to_standalone_python's
`_known_helper_table`, so an artifact rendered from a graph with a
non-differentiable output resolves it through that surface like the other
runtime helpers rather than through a bare runtime_wrappers import.
The dedup indexes the marked slots, usually one or two, and probes the rest
against them, so it costs ~0.8us per forward of a compiled autograd function
that has any non-differentiable output -- about 0.3% of a small MLP forward
and below the noise floor of an end-to-end measurement. A follow-up worth
having is an index-based mark_non_differentiable, which would make this free
and also cover the same hazard in mark_dirty.
Test Plan:
```
python test/functorch/test_aotdispatch.py
python test/test_precompile.py
python test/dynamo/test_package.py
python test/dynamo/test_aot_autograd_cache.py
```
Two new tests, one per collision shape: an output aliasing an intermediate
base (parametrized over aot_eager and inductor), and an output aliasing a
sibling output. Each asserts requires_grad, grad_fn and the gradient itself
against eager, and the first also asserts the detach output stays a leaf so
the rejected fix above cannot pass. Both fail without this change -- the
intermediate-base one errors, the sibling one returns the wrong gradient.
Authored with an AI assistant.
ghstack-source-id: 85ddf1d
Pull-Request: #195357
[ghstack-poisoned]
torch.compile(backend="inductor") silently returns no gradient for
def f(x):
y = torch.sin(x)
return y[0:4], y[4:8], y.detach()
Eager gives grad_fn [True, True, False] and a populated x.grad; inductor gives
[False, False, False] and x.grad is None. Adding a fourth, independently
differentiable output turns the silent wrong answer into a crash in the
compiled backward -- "TypeError: expected Tensor() for op: input" out of
inductor's assert_size_stride_grouped, or "Expected tensors only, but got
NoneType" out of copy_misaligned_inputs when the backward has no kernels for
the asserts to attach to.
ctx.mark_non_differentiable is keyed on TensorImpl, so marking one returned
slot marks EVERY returned slot holding that same object, and the forward
epilogue pairs it with ctx._materialize_non_diff_grads = False, which makes a
marked slot's grad arrive as None rather than zeros. Backends are free to
return one object in two slots: inductor lowers aten.detach to a no-op, and
h * 1 / h + 0 fold away. So
* `return y[:2], y[2:], y.detach()` marks y's intermediate base -- a slot
_codegen_backward_prologue keeps unconditionally -- and the base's tangent
arrives None, which process_runtime_tangent forwards verbatim; and
* `return h * 1, h.detach()` marks the sibling output, which is the only
differentiable thing in the model.
The metadata is not at fault: the backward's predicate,
requires_grad_for_backward, is a strict subset of the forward's requires_grad
(collect_metadata_analysis.py), so no slot is dropped by one and kept by the
other. Only the runtime identity collision is.
Give each slot about to be marked its own TensorImpl instead
(`_dealias_marked_returns`). That is sound precisely because we are about to
declare the slot non-differentiable, so an alias of it is as good as the
original; slots that stay differentiable keep their identity. The rejected
alternative was to skip marking any slot that aliases a surviving one, which
spares the base but also spares the detach output -- it comes back with
requires_grad=True and a grad_fn, and backward flows through a detached tensor.
Fixing this in inductor instead would be the wrong layer twice over: detach is
not the culprit (h * 1 reproduces it with no detach anywhere), and AOTAutograd
is the component making the identity-keyed call.
The codegen emits the dealias and the per-slot Tensor checks it feeds in one
block, and the helper is part of the standalone-source surface: it is exported
from standalone_runtime and registered in to_standalone_python's
`_known_helper_table`, so an artifact rendered from a graph with a
non-differentiable output resolves it through that surface like the other
runtime helpers rather than through a bare runtime_wrappers import.
The dedup indexes the marked slots, usually one or two, and probes the rest
against them, so it costs ~0.8us per forward of a compiled autograd function
that has any non-differentiable output -- about 0.3% of a small MLP forward
and below the noise floor of an end-to-end measurement. A follow-up worth
having is an index-based mark_non_differentiable, which would make this free
and also cover the same hazard in mark_dirty.
Test Plan:
```
python test/functorch/test_aotdispatch.py
python test/test_precompile.py
python test/dynamo/test_package.py
python test/dynamo/test_aot_autograd_cache.py
```
Two new tests, one per collision shape: an output aliasing an intermediate
base (parametrized over aot_eager and inductor), and an output aliasing a
sibling output. Each asserts requires_grad, grad_fn and the gradient itself
against eager, and the first also asserts the detach output stays a leaf so
the rejected fix above cannot pass. Both fail without this change -- the
intermediate-base one errors, the sibling one returns the wrong gradient.
Authored with an AI assistant.
ghstack-source-id: 94c3fae
Pull-Request: #195357
torch.compile(backend="inductor") silently returns no gradient for
def f(x):
y = torch.sin(x)
return y[0:4], y[4:8], y.detach()
Eager gives grad_fn [True, True, False] and a populated x.grad; inductor gives
[False, False, False] and x.grad is None. Adding a fourth, independently
differentiable output turns the silent wrong answer into a crash in the
compiled backward -- "TypeError: expected Tensor() for op: input" out of
inductor's assert_size_stride_grouped, or "Expected tensors only, but got
NoneType" out of copy_misaligned_inputs when the backward has no kernels for
the asserts to attach to.
ctx.mark_non_differentiable is keyed on TensorImpl, so marking one returned
slot marks EVERY returned slot holding that same object, and the forward
epilogue pairs it with ctx._materialize_non_diff_grads = False, which makes a
marked slot's grad arrive as None rather than zeros. Backends are free to
return one object in two slots: inductor lowers aten.detach to a no-op, and
h * 1 / h + 0 fold away. So
* `return y[:2], y[2:], y.detach()` marks y's intermediate base -- a slot
_codegen_backward_prologue keeps unconditionally -- and the base's tangent
arrives None, which process_runtime_tangent forwards verbatim; and
* `return h * 1, h.detach()` marks the sibling output, which is the only
differentiable thing in the model.
The metadata is not at fault: the backward's predicate,
requires_grad_for_backward, is a strict subset of the forward's requires_grad
(collect_metadata_analysis.py), so no slot is dropped by one and kept by the
other. Only the runtime identity collision is.
Give each slot about to be marked its own TensorImpl instead
(`_dealias_marked_returns`). That is sound precisely because we are about to
declare the slot non-differentiable, so an alias of it is as good as the
original; slots that stay differentiable keep their identity. The rejected
alternative was to skip marking any slot that aliases a surviving one, which
spares the base but also spares the detach output -- it comes back with
requires_grad=True and a grad_fn, and backward flows through a detached tensor.
Fixing this in inductor instead would be the wrong layer twice over: detach is
not the culprit (h * 1 reproduces it with no detach anywhere), and AOTAutograd
is the component making the identity-keyed call.
The codegen emits the dealias and the per-slot Tensor checks it feeds in one
block, and the helper is part of the standalone-source surface: it is exported
from standalone_runtime and registered in to_standalone_python's
`_known_helper_table`, so an artifact rendered from a graph with a
non-differentiable output resolves it through that surface like the other
runtime helpers rather than through a bare runtime_wrappers import.
The dedup indexes the marked slots, usually one or two, and probes the rest
against them, so it costs ~0.8us per forward of a compiled autograd function
that has any non-differentiable output -- about 0.3% of a small MLP forward
and below the noise floor of an end-to-end measurement. A follow-up worth
having is an index-based mark_non_differentiable, which would make this free
and also cover the same hazard in mark_dirty.
Test Plan:
```
python test/functorch/test_aotdispatch.py
python test/test_precompile.py
python test/dynamo/test_package.py
python test/dynamo/test_aot_autograd_cache.py
```
Two new tests, one per collision shape: an output aliasing an intermediate
base (parametrized over aot_eager and inductor), and an output aliasing a
sibling output. Each asserts requires_grad, grad_fn and the gradient itself
against eager, and the first also asserts the detach output stays a leaf so
the rejected fix above cannot pass. Both fail without this change -- the
intermediate-base one errors, the sibling one returns the wrong gradient.
Authored with an AI assistant.
ghstack-source-id: 94c3fae
Pull-Request: #195357
torch.compile(backend="inductor") silently returns no gradient for
def f(x):
y = torch.sin(x)
return y[0:4], y[4:8], y.detach()
Eager gives grad_fn [True, True, False] and a populated x.grad; inductor gives
[False, False, False] and x.grad is None. Adding a fourth, independently
differentiable output turns the silent wrong answer into a crash in the
compiled backward -- "TypeError: expected Tensor() for op: input" out of
inductor's assert_size_stride_grouped, or "Expected tensors only, but got
NoneType" out of copy_misaligned_inputs when the backward has no kernels for
the asserts to attach to.
ctx.mark_non_differentiable is keyed on TensorImpl, so marking one returned
slot marks EVERY returned slot holding that same object, and the forward
epilogue pairs it with ctx._materialize_non_diff_grads = False, which makes a
marked slot's grad arrive as None rather than zeros. Backends are free to
return one object in two slots: inductor lowers aten.detach to a no-op, and
h * 1 / h + 0 fold away. So
* `return y[:2], y[2:], y.detach()` marks y's intermediate base -- a slot
_codegen_backward_prologue keeps unconditionally -- and the base's tangent
arrives None, which process_runtime_tangent forwards verbatim; and
* `return h * 1, h.detach()` marks the sibling output, which is the only
differentiable thing in the model.
The metadata is not at fault: the backward's predicate,
requires_grad_for_backward, is a strict subset of the forward's requires_grad
(collect_metadata_analysis.py), so no slot is dropped by one and kept by the
other. Only the runtime identity collision is.
Give each slot about to be marked its own TensorImpl instead
(`_dealias_marked_returns`). That is sound precisely because we are about to
declare the slot non-differentiable, so an alias of it is as good as the
original; slots that stay differentiable keep their identity. The rejected
alternative was to skip marking any slot that aliases a surviving one, which
spares the base but also spares the detach output -- it comes back with
requires_grad=True and a grad_fn, and backward flows through a detached tensor.
Fixing this in inductor instead would be the wrong layer twice over: detach is
not the culprit (h * 1 reproduces it with no detach anywhere), and AOTAutograd
is the component making the identity-keyed call.
The codegen emits the dealias and the per-slot Tensor checks it feeds in one
block, and the helper is part of the standalone-source surface: it is exported
from standalone_runtime and registered in to_standalone_python's
`_known_helper_table`, so an artifact rendered from a graph with a
non-differentiable output resolves it through that surface like the other
runtime helpers rather than through a bare runtime_wrappers import.
The dedup indexes the marked slots, usually one or two, and probes the rest
against them, so it costs ~0.8us per forward of a compiled autograd function
that has any non-differentiable output -- about 0.3% of a small MLP forward
and below the noise floor of an end-to-end measurement. A follow-up worth
having is an index-based mark_non_differentiable, which would make this free
and also cover the same hazard in mark_dirty.
Test Plan:
```
python test/functorch/test_aotdispatch.py
python test/test_precompile.py
python test/dynamo/test_package.py
python test/dynamo/test_aot_autograd_cache.py
```
Two new tests, one per collision shape: an output aliasing an intermediate
base (parametrized over aot_eager and inductor), and an output aliasing a
sibling output. Each asserts requires_grad, grad_fn and the gradient itself
against eager, and the first also asserts the detach output stays a leaf so
the rejected fix above cannot pass. Both fail without this change -- the
intermediate-base one errors, the sibling one returns the wrong gradient.
Authored with an AI assistant.
ghstack-source-id: 94c3fae
Pull-Request: #195357
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
|
@claude please review |
|
Claude finished @bobrenjc93's task in 33m 31s —— View job Reviewed: no confirmed correctness bug, but the fix lands per-call Python work in a path explicitly designed to hoist everything to compile time, duplicates the logic into a branch that is dead code, and relies on an undocumented Full review of #195357PR Review: #195357SummaryAdds Performance
Code Quality
Testing
RecommendationNeeds Discussion The diagnosis and the dealias-rather-than-skip choice are correct and the end-to-end tests do pin the user-visible behavior against eager. What needs resolving before merge is the per-call cost in a path whose stated purpose is to resolve everything at compile time, the duplicated edit into an unreachable branch, and the two undocumented invariants ( |
[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]
[ghstack-poisoned]
Stack from ghstack (oldest at bottom):
torch.compile(backend="inductor") silently returns no gradient for
Eager gives grad_fn [True, True, False] and a populated x.grad; inductor gives
[False, False, False] and x.grad is None. A fourth, independently
differentiable output turns that into a crash in the compiled backward
("TypeError: expected Tensor() for op: input" from
assert_size_stride_grouped).
ctx.mark_non_differentiableis keyed on TensorImpl, so marking one returnedslot marks every returned slot holding the same object, and the forward
epilogue sets
ctx._materialize_non_diff_grads = False, so a marked slot'sgrad arrives as None. Backends may return one object in two slots: inductor
lowers aten.detach to a no-op, and
h * 1folds away. Soy.detach()marksy's intermediate base, whose None tangent
process_runtime_tangentforwardsverbatim, and
h.detach()marks the sibling outputh * 1. The metadata isright (requires_grad_for_backward is a subset of the forward's requires_grad);
only the runtime identity collision is wrong.
_dealias_marked_returnsgives each slot about to be marked its own TensorImplvia
detach()when it collides with an unmarked slot; slots that staydifferentiable keep their identity. Skipping the mark instead would leave the
detach output with requires_grad=True and a grad_fn. The codegen'd
compiled_fn_wrapperemits the dealias ahead of the per-slot Tensor checks,and the helper is exported from standalone_runtime and registered in
to_standalone_python's
_known_helper_tableso a rendered artifact resolves itlike the other runtime helpers once training artifacts exist (a later commit).
Test Plan:
Two end-to-end tests, one per collision shape (intermediate base, parametrized
over aot_eager and inductor -- eager detach allocates a new TensorImpl, so the
aot_eager variant is parity only; sibling output, pinned to
joint_graph_constant_folding), assert requires_grad, grad_fn and the gradient
against eager, that the detach output stays a leaf, and via data_ptr that the
inductor slots really shared storage. A third
drives
_dealias_marked_returnsdirectly: only marked slots colliding with anunmarked slot are rebound.
Authored with an AI assistant.
[no ci]