Skip to content

autograd: add ctx.set_output_grad_dtype - #189634

Closed
sorenzzio wants to merge 5 commits into
pytorch:mainfrom
sorenzzio:feature/autograd_grad_dtype_ctx_api
Closed

sorenzzio wants to merge 5 commits into
pytorch:mainfrom
sorenzzio:feature/autograd_grad_dtype_ctx_api

Conversation

@sorenzzio

@sorenzzio sorenzzio commented Jul 12, 2026 •

Copy link
Copy Markdown
Contributor

See docstring

Add ctx.set_output_grad_dtype(output, dtype), allowing an autograd.Function to declare the gradient dtype contract for one of its outputs independently of the output's storage dtype.

Declarations are matched to Function output slots by Python object identity

  • A concrete dtype converts incoming gradients to that dtype.
  • None accepts incoming gradients without conversion.
  • An output without a declaration retains the existing behavior.~

This API may only be called from forward or setup_context. Calls from other phases are rejected.

get_input_grad_dtype has been moved to a separate follow-up PR

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

@pytorch-bot

pytorch-bot Bot commented Jul 12, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

❌ You can merge normally! (6 Unrelated Failures), 2 Unclassified Failures

As of commit bbd9976 with merge base f594cad (image):

UNCLASSIFIED FAILURES - DrCI could not classify the following jobs because the workflow did not run on the merge base. The failures may be pre-existing on trunk or introduced by this PR:

  • pull / linux-jammy-cuda13.0-cudnn9-py3.10-clang20 / build (gh) (this job did not run on the merge base, so DrCI cannot tell whether the failure is pre-existing)
    mt-l-x86iavx512-8-64

    AI verdict: AI verdict: infra issue

    The failure is a Kubernetes pod scheduling timeout ("Pod is unhealthy with phase status Pending: backoff timeout"), not a build or test failure. The commit only modifies autograd test skip lists and has no relation to CI infrastructure.

    Full reasoning on HUD →

  • pull / linux-jammy-cuda13.2-cudnn9-py3.10-clang20 / build (gh) (this job did not run on the merge base, so DrCI cannot tell whether the failure is pre-existing)
    mt-l-x86iavx512-8-64

    AI verdict: AI verdict: infra issue

    The failure is a Kubernetes pod scheduling timeout ("Pod is unhealthy with phase status Pending: backoff timeout"), not a build or test failure. The CI runner never started.

    Full reasoning on HUD →

CRCR (non-blocking) - The following CRCR downstream CI jobs failed but are non-blocking:

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

@linux-foundation-easycla

linux-foundation-easycla Bot commented Jul 12, 2026 •

Copy link
Copy Markdown

CLA Signed
The committers listed above are authorized under a signed CLA.

  • ✅ login: SongyuanZhao / name: SongyuanZhao (8e17f7b)

@sorenzzio
sorenzzio force-pushed the feature/autograd_grad_dtype_ctx_api branch from 8943d16 to 8e17f7b Compare July 12, 2026 02:39
@albanD albanD added the triaged This issue has been looked at a team member, and triaged and prioritized into an appropriate module label Jul 13, 2026
@sorenzzio
sorenzzio force-pushed the feature/autograd_grad_dtype_ctx_api branch from ad5d437 to 7380626 Compare July 15, 2026 08:54
Comment thread torch/autograd/function.py Outdated
"""
from torch.autograd.graph import _get_grad_dtype

return _get_grad_dtype(input)

@soulitzer soulitzer Jul 21, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You don't actually necessary have the input tensor alive at this point!
Instead you want to traverse the graph directly to find the next node corresponding to the right input. We will eventually have to worry about the accumulation dtype, which we don't have an API exposed to alter yet (so maybe that is fine for now).

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The other thing is that when you call get_grad_dtype matters, e.g. whether you are in the forward or backward. Because someone could've gone along and altered the dtype the input_metadata later (unless we decide to ban this).

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Would it make sense for get_input_grad_dtype to use the tensor only to identify the Function input, while reading the dtype from the corresponding next_edge captured at apply time? This would make it a Function-scoped query rather than a query on the tensor's current edge.

We intend both APIs to be graph-construction-time APIs, callable only from forward or setup_context, and can enforce that explicitly. Would this address the lifetime and timing concerns, or do you expect the getter to also work in backward?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If it were a method that takes in tensor, the user might as well query some API like tensor.grad_dtype directly since nothing that about that is specfic to the autograd.Function.

I'd agree that graph-construction time seems like the most common case, but I'm not sure I want to preclude ourselves too early from post facto grad_dtype mutations (imaginary example: after the entire forward completes someone can do some additional analysis given that they have knowledge of the full graph and realize that dtype needs to be a particular way).

If we must account for possible mutation of grad_dtype, and thus must access during bw where don't have tensor, the user can manually do ctx.next_functions[idx][0].input_metadata[ctx.next_functions[idx][1]], but maybe there value in providing a helper to do this

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That makes sense—we should consider other call sites.

The Tensor arguments were intended to make the API convenient in forward/setup_context, without requiring users to maintain a Tensor-to-index mapping. Outside graph construction, I wonder whether the same API would still be convenient (immediately after apply may be one exception, since both inputs and outputs are readily available), or whether an index- or edge-based API might be more natural for cases such as graph analysis or backward.

The implementation would also differ across these phases: the current Getter maps apply inputs to captured edges, while Setter declarations are consumed during output wrapping. Supporting post-apply calls would therefore require more than removing the guard.

Do you think these PRs should support calls outside graph construction now, or should we keep the Tensor-based APIs scoped to graph construction and discuss later access separately?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let's discuss outside of graph construction later. I think for the setter ctx.set_output_grad_dtype that you propose is the right API!

@soulitzer

Copy link
Copy Markdown
Contributor

So sorry for the delay! @SongyuanZhao This is PR is looking pretty good, but can I request to have it split into two separate ones for each of the two APIs since they should work independently of one another.

Comment thread torch/autograd/function.py Outdated
The dtype has the following meaning:

- a concrete :class:`torch.dtype`: the incoming gradient is cast to that
dtype (up or down); a hard error is raised if the cast is impossible.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do you have an example where the cast be impossible?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't have a concrete example. I think that was an overly speculative statement introduced with AI. I'll remove it later.

Comment thread torch/autograd/function.py Outdated
:func:`forward` methods, and the same ``output`` Tensor object must be
among the tensors this Function returns. It controls the dtype the
autograd engine produces for the gradient flowing back into ``output``'s
slot, without placing any state on the (non-leaf) output tensor itself.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

"without placing any state on the (non-leaf) output tensor itself"

We probably don't need to mention this haha

Comment thread torch/autograd/function.py Outdated

This should be called from either the :func:`setup_context` or
:func:`forward` methods, and the same ``output`` Tensor object must be
among the tensors this Function returns. It controls the dtype the

@soulitzer soulitzer Jul 21, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

So this knob would ALSO control accumulation dtype today!
Maybe its fine, even if we plan to add a designated knob for accum dtype later.
Accum dtype defaults to the grad_dtype when accum_dtype is not specified.

@sorenzzio sorenzzio closed this Jul 22, 2026
@sorenzzio sorenzzio reopened this Jul 22, 2026
@sorenzzio

Copy link
Copy Markdown
Contributor Author

@soulitzer Sounds good, thanks! I will keep ctx.set_output_grad_dtype in this PR and move ctx.get_input_grad_dtype to a separate follow-up PR.

@sorenzzio
sorenzzio force-pushed the feature/autograd_grad_dtype_ctx_api branch from 7380626 to fc7f992 Compare July 23, 2026 04:40
@sorenzzio sorenzzio changed the title autograd: add ctx.set_output_grad_dtype / get_input_grad_dtype autograd: add ctx.set_output_grad_dtype Jul 23, 2026
@sorenzzio

sorenzzio commented Jul 23, 2026 •

Copy link
Copy Markdown
Contributor Author

This PR now contains only ctx.set_output_grad_dtype. The API is restricted to forward and setup_context.

ctx.get_input_grad_dtype has moved to #190852, where the Tensor only identifies the Function input and the dtype is read from its captured next_edge.

The two PRs share some changes and may conflict.I will rebase and resolve them after one lands.

Please take another look when convenient. @soulitzer

@soulitzer soulitzer left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can I propose a slightly different API? I think the way of doing it in this PR is also kind of reasonable, but I think the easiest way might be to just handle it positionally (the same way backward handles gradients), where the function takes varargs:

def forward(ctx, ...):
    ...
    ctx.set_output_grad_dtype(None, None, torch.float32, t3.dtype)
    return non_tensor, t1, t2, t3
  • If the user return at position i is non-tensor must return None for that position
  • If the user wants no-cast to happen by the engine, they pass the sentinel object NO_CAST
  • If the user wants the grad a particular dtype, they return that dtype
  • If the user wants the default behavior, they should do so explicitly by querying for t's dtype, e.g. not using the API is equivalent to ctx.set_output_grad_dtype(None, t1.dtype, t2.dtype, t3.dtype)

Another benefit of this is that now you can handle the case where the same tensor is returned twice, but you want to have two distinct grad dtypes (with a tensor identity based API, the user would need to return a separate view).

EDIT:
One annoying thing of the positional-based API is that None means two things: (1) skip for non-tensors, (2) engine does not cast.

Accepting a sentinel object NO_CAST = object() would help disambiguate and guard against some positional drift

But I don't like diverging from the existing t.grad_dtype API where None means engine doesn't cast. And what's worse is that due to bc it is not really possible for us to have it return NO_CAST instead of None (existing equality checks would fail).

I feel like what might be okay is to instead to think of (1) and (2) as conceptually the same. The non-tensor case, is considered a subset of the no-cast case, because there is no gradient to cast anyway!

Comment thread torch/csrc/autograd/python_function.cpp Outdated
// Preserve an in-flight Python error while releasing the recording.
PyObject *type = nullptr, *value = nullptr, *traceback = nullptr;
PyErr_Fetch(&type, &value, &traceback);
Py_CLEAR(ctx_->output_grad_dtypes);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do we need actually need this for the error case? If we return early, the node should not get attached to the graph and its fields should be cleared via tp_clear.

Comment thread torch/csrc/autograd/python_function.cpp Outdated
// Marks the user phase in which grad-dtype ctx APIs may be called. The explicit
// end closes the phase before output wrapping; the destructor handles early
// exits.
struct GradDtypeApiGuard {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't think we need to be do defensive of calling this outside of the forward / setup_context as it doesn't really do anything if called in jvp or backward.

Comment thread torch/autograd/function.py Outdated
>>> ctx.set_output_grad_dtype(out, torch.float32)
>>> return out
"""
self._set_output_grad_dtype(output, dtype)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I wonder if we could follow the pattern from the other APIs above, where the user sets to the field via a descriptor.

@sorenzzio

Copy link
Copy Markdown
Contributor Author

Thanks, that makes sense. I’ll switch to the positional API aligned with the forward outputs, use the existing ctx field/descriptor pattern, and remove the unnecessary phase guard and defensive cleanup.

Add a ctx method that lets a Python autograd.Function declare the gradient
dtype contract for each of its output slots independently of the output's
storage dtype. The API is positional, taking one dtype-or-None declaration per
returned value, aligned with how backward receives gradients:

def forward(ctx, x):
    ...
    ctx.set_output_grad_dtype(torch.float32, None, None)
    return t1, t2, "not a tensor"

For each returned value the declaration at the same index means: a concrete
dtype casts the incoming gradient (only valid for a differentiable Tensor);
None performs no conversion, which is also the only valid choice for a
non-Tensor or non-differentiable slot (there is no gradient to cast). Not
calling the API keeps the default of converting to each output's storage
dtype; that default is requested explicitly by passing the output's own dtype.

The Python method stores the tuple through a THPFunction descriptor
(output_grad_dtypes), mirroring mark_dirty / mark_non_differentiable. Output
wrapping parses it into a positional vector, validates the declaration count
equals the number of outputs and that concrete dtypes only target
differentiable Tensor slots, then applies each to the matching input_metadata
slot by index. The recording is cleared once consumed. There is no defensive
runtime phase check, matching the other construction-time ctx APIs; the
docstring documents the intended call site (forward / setup_context) and that
a later call overwrites an earlier one.

Test Plan:

Built CPU-only and ran the setter suite on a remote x86 host:

```
USE_CUDA=0 USE_ROCM=0 USE_XPU=0 USE_NUMA=0 USE_DISTRIBUTED=0 USE_FBGEMM=0 \
  python -m pip install -e . -v --no-build-isolation
python -m pytest -v test/test_autograd.py -k ctx_output_grad_dtype
python -m pytest -q test/test_autograd.py -k "custom_function or setup_context or mark_dirty or mark_non_differentiable or materialize or output_grad_dtype or save_for_backward"
```

Results: 10 passed (setter suite), 65 passed / 3 skipped (broader
custom-Function subset).

Authored with the assistance of an AI coding assistant.
@sorenzzio
sorenzzio force-pushed the feature/autograd_grad_dtype_ctx_api branch from fc7f992 to 6987dd8 Compare July 29, 2026 13:10
Comment thread torch/autograd/function.py Outdated
r"""Declare the gradient dtype for each of this Function's outputs.

This should be called from either the :func:`setup_context` or
:func:`forward` methods. If called more than once, only the last call

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I guess last call wins is the behavior, but in docs maybe just follow mark_dirty, etc here where we tell the users that they should only call it once. I'm not sure if there's an actual consequence for calling twice, but we should be clear that its not intended usage.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actually if there is an easy way to error upon second call, maybe its better to do that hmm

Comment thread torch/csrc/autograd/python_function.cpp Resolved
Comment thread torch/autograd/function.py Outdated
returns at the same index, so the number of declarations must match the
number of returned values. This lets a Function define the dtype
contract for gradients entering its output slots independently of the
outputs' storage dtypes.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This lets a Function define the dtype
contract for gradients entering its output slots independently of the
outputs' storage dtypes

Maybe too low level / edge case to mention in the main paragraph here since it should already reflect the intuitive behavior

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge started

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

Learn more about merging in the wiki.

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

Advanced Debugging
Check the merge workflow status
here

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

The trunk run for this PR fails in TestAutogradWithCompiledAutograd with
"Unsupported: setattr() on unsupported type". The grad_dtype tests report
the dtype they observed by assigning it to an attribute on the
autograd.Function class, and dynamo cannot trace that setattr once
compiled autograd inlines the backward.

run_test.py passes -x, so each shard stops at its first failure and only
ever names one test; skipping the names that surfaced just promotes the
next one in that shard's order. The whole family is affected, so skip it
by prefix. That is consistent with eager, where every one of these tests
already carries skipIfTorchDynamo("grad_dtype not supported in compile").

skipped_tests leaves the tests running eagerly under the wrapped class
rather than dropping them, so they keep the coverage they have in
test_autograd.py. known_graph_breaks_tests was the alternative, but it
would only relax fullgraph and still exercise a path the feature does not
claim to support.

Test Plan:

Reproduced the underlying dynamo limitation directly, independent of this
PR's C++, confirming it is deterministic rather than order-dependent (a
custom Function whose backward does `Rec.seen = g.dtype`, run six times
under compiled_autograd._enable with fullgraph=True, fails every time):

```
python agent_space/setattr_ca.py
```

Confirmed the prefix skip covers the whole family and changes nothing
else in the wrapped class:

```
python -c "
import importlib.util
spec = importlib.util.spec_from_file_location('tca', 'inductor/test_compiled_autograd.py')
m = importlib.util.module_from_spec(spec); spec.loader.exec_module(m)
cls = m.TestAutogradWithCompiledAutograd
fam = [x for x in dir(cls) if 'ctx_output_grad_dtype' in x]
print(len(fam), [n for n in fam if getattr(cls, n).__code__.co_name == 'wrapped'])
print(sum(1 for x in dir(cls) if x.startswith('test_') and getattr(cls, x).__code__.co_name == 'wrapped'))
"
```

reporting 13 tests in the family, none still wrapped, and 274 other tests
still wrapped as before.

```
lintrunner --take RUFF,FLAKE8,PYFMT test/inductor/test_compiled_autograd.py
```

Authored with assistance from Claude Code.
@soulitzer
soulitzer force-pushed the feature/autograd_grad_dtype_ctx_api branch from 02f63cf to bbd9976 Compare August 5, 2026 20:23
@soulitzer

Copy link
Copy Markdown
Contributor

@pytorchbot merge

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge started

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

Learn more about merging in the wiki.

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

Advanced Debugging
Check the merge workflow status
here

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge failed

Reason: 2 mandatory check(s) failed. The first few are:

Dig deeper by viewing the failures on hud

Details for Dev Infra team Raised by workflow job

Failing merge rule: Core Maintainers

@sorenzzio

Copy link
Copy Markdown
Contributor Author

@soulitzer Thanks for helping with the compiled autograd fix! It looks like the latest merge attempt was blocked by CI infrastructure issues. When convenient, could you please help trigger the merge again? Thanks!

@soulitzer

Copy link
Copy Markdown
Contributor

@pytorchbot merge -i

1 similar comment
@soulitzer

Copy link
Copy Markdown
Contributor

@pytorchbot merge -i

@soulitzer

Copy link
Copy Markdown
Contributor

@SongyuanZhao github actions might be still down, will try to reland again tomorrow

@soulitzer

Copy link
Copy Markdown
Contributor

@pytorchbot merge -i

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge started

Your change will be merged while ignoring the following 2 checks: pull / linux-jammy-cuda13.2-cudnn9-py3.10-clang20 / build, pull / linux-jammy-cuda13.0-cudnn9-py3.10-clang20 / build

Learn more about merging in the wiki.

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

Advanced Debugging
Check the merge workflow status
here

ankitbhrdwj pushed a commit to ankitbhrdwj/pytorch that referenced this pull request Aug 12, 2026
See docstring

~Add `ctx.set_output_grad_dtype(output, dtype)`, allowing an `autograd.Function` to declare the gradient dtype contract for one of its outputs independently of the output's storage dtype.~

Declarations are matched to Function output slots by Python object identity
 - A concrete dtype converts incoming gradients to that dtype.
 - `None` accepts incoming gradients without conversion.
 - An output without a declaration retains the existing behavior.~

~This API may only be called from `forward` or `setup_context`. Calls from other phases are rejected.~

`get_input_grad_dtype` has been moved to a separate follow-up PR

Pull Request resolved: pytorch#189634
Approved by: https://github.com/soulitzer

Co-authored-by: soulitzer <[email protected]>
pianpwk added a commit that referenced this pull request Oct 8, 2026
ctx.set_output_grad_dtype (#189634) lets an autograd.Function declare the
dtype its backward receives each output gradient in, independently of the
output's dtype. Dynamo traced the forward against a Python FunctionCtx
without the backing attribute, so any compiled Function calling it failed
with "'FunctionCtx' object has no attribute 'output_grad_dtypes'".

Follow the mark_non_differentiable / mark_dirty pattern:
- AutogradFunctionContextVariable records the declared dtypes (constant
  torch.dtype or None; anything else graph breaks).
- The backward is traced with gradient placeholders in the declared dtypes,
  via a new sub_args_dtypes override for forced subgraph inputs.
- autograd_function_apply replays the declaration in setup_context, so the
  autograd engine converts incoming gradients as in eager.

Motivation: torchtitan GraphTrainer's SimpleFSDP needs this to keep fp32
gradients of bf16 all-gathered weights (matching FSDP2's unsharded
grad_dtype = reduce_dtype) under torch.compile.

Test plan:
- test_set_output_grad_dtype: an fp32 gradient flowing into a bf16 output
  declared fp32 keeps a value bf16 cannot represent, in eager and under
  aot_eager with fullgraph=True. Fails without this change.
- test/dynamo/test_autograd_function.py, test/dynamo/test_higher_order_ops.py:
  348 passed.

ghstack-source-id: 86e2267
Pull Request resolved: #200311
pianpwk added a commit that referenced this pull request Oct 12, 2026
ctx.set_output_grad_dtype (#189634) lets an autograd.Function declare the
dtype its backward receives each output gradient in, independently of the
output's dtype. Dynamo traced the forward against a Python FunctionCtx
without the backing attribute, so any compiled Function calling it failed
with "'FunctionCtx' object has no attribute 'output_grad_dtypes'".

Follow the mark_non_differentiable / mark_dirty pattern:
- AutogradFunctionContextVariable records the declared dtypes (constant
  torch.dtype or None; anything else graph breaks).
- The backward is traced with gradient placeholders in the declared dtypes,
  via a new overridden_bwd_args_dtypes override for forced subgraph inputs.
- The emitted autograd.Function returns only the traced forward's
  tensor/symint outputs (flattened, plus intermediates), so the declarations
  are remapped from the original outputs to those, by VariableTracker
  identity as in handle_saved_tensors_wiring. Outputs with no original
  counterpart declare None. A declaration/output count mismatch graph breaks,
  so eager raises its usual error.
- autograd_function_apply replays the remapped declaration in setup_context,
  so the autograd engine converts incoming gradients as in eager.

Motivation: torchtitan GraphTrainer's SimpleFSDP needs this to keep fp32
gradients of bf16 all-gathered weights (matching FSDP2's unsharded
grad_dtype = reduce_dtype) under torch.compile.

Test plan:
- test_set_output_grad_dtype: an fp32 gradient flowing into a bf16 output
  declared fp32 keeps a value bf16 cannot represent, in eager and under
  aot_eager with fullgraph=True. Fails without this change.
- test_set_output_grad_dtype_non_tensor_output: a non-tensor forward output
  is dropped from the traced outputs; the remaining declarations still apply
  to the right outputs. Fails without the remapping.
- test/dynamo/test_autograd_function.py, test/dynamo/test_higher_order_ops.py:
  349 passed.

ghstack-source-id: d673648
Pull Request resolved: #200311
pianpwk added a commit that referenced this pull request Oct 12, 2026
ctx.set_output_grad_dtype (#189634) lets an autograd.Function declare the
dtype its backward receives each output gradient in, independently of the
output's dtype. Dynamo traced the forward against a Python FunctionCtx
without the backing attribute, so any compiled Function calling it failed
with "'FunctionCtx' object has no attribute 'output_grad_dtypes'".

Follow the mark_non_differentiable / mark_dirty pattern:
- AutogradFunctionContextVariable records the declared dtypes (constant
  torch.dtype or None; anything else graph breaks).
- The backward is traced with gradient placeholders in the declared dtypes,
  via a new overridden_bwd_args_dtypes override for forced subgraph inputs.
- The emitted autograd.Function returns only the traced forward's
  tensor/symint outputs (flattened, plus intermediates), so the declarations
  are remapped from the original outputs to those, by VariableTracker
  identity as in handle_saved_tensors_wiring. Outputs with no original
  counterpart declare None. A declaration/output count mismatch graph breaks,
  so eager raises its usual error.
- autograd_function_apply replays the remapped declaration in setup_context,
  so the autograd engine converts incoming gradients as in eager.

Motivation: torchtitan GraphTrainer's SimpleFSDP needs this to keep fp32
gradients of bf16 all-gathered weights (matching FSDP2's unsharded
grad_dtype = reduce_dtype) under torch.compile.

Test plan:
- test_set_output_grad_dtype: an fp32 gradient flowing into a bf16 output
  declared fp32 stays fp32 under aot_eager with fullgraph=True: the compiled
  backward's DebugMode op log has no cast to bf16, and the gradient matches
  eager bitwise.
- test_set_output_grad_dtype_non_tensor_output: a non-tensor forward output
  is dropped from the traced outputs; the remaining declarations still apply
  to the right outputs (only the gradient declared bf16 is cast to bf16 in
  the DebugMode op log). Fails without the remapping.
- test/dynamo/test_autograd_function.py, test/dynamo/test_higher_order_ops.py:
  349 passed.

ghstack-source-id: 346b290
Pull Request resolved: #200311
pianpwk added a commit that referenced this pull request Oct 12, 2026
ctx.set_output_grad_dtype (#189634) lets an autograd.Function declare the
dtype its backward receives each output gradient in, independently of the
output's dtype. Dynamo traced the forward against a Python FunctionCtx
without the backing attribute, so any compiled Function calling it failed
with "'FunctionCtx' object has no attribute 'output_grad_dtypes'".

Follow the mark_non_differentiable / mark_dirty pattern:
- AutogradFunctionContextVariable records the declared dtypes (constant
  torch.dtype or None; anything else graph breaks).
- The backward is traced with gradient placeholders in the declared dtypes,
  via a new overridden_bwd_args_dtypes override for forced subgraph inputs.
- The emitted autograd.Function returns only the traced forward's
  tensor/symint outputs (flattened, plus intermediates), so the declarations
  are remapped from the original outputs to those, by VariableTracker
  identity as in handle_saved_tensors_wiring. Outputs with no original
  counterpart declare None.
- Invalid declarations (wrong count, or a concrete dtype for a non-tensor
  output) graph break before the backward is traced, so eager raises its
  usual error.
- autograd_function_apply replays the remapped declaration in setup_context,
  so the autograd engine converts incoming gradients as in eager.

Motivation: torchtitan GraphTrainer's SimpleFSDP needs this to keep fp32
gradients of bf16 all-gathered weights (matching FSDP2's unsharded
grad_dtype = reduce_dtype) under torch.compile.

Test plan:
- test_set_output_grad_dtype: an fp32 gradient flowing into a bf16 output
  declared fp32 stays fp32 under aot_eager with fullgraph=True: the compiled
  backward's DebugMode op log has no cast to bf16, and the gradient matches
  eager bitwise.
- test_set_output_grad_dtype_non_tensor_output: a non-tensor forward output
  is dropped from the traced outputs; the remaining declarations still apply
  to the right outputs (only the gradient declared bf16 is cast to bf16 in
  the DebugMode op log). Fails without the remapping.
- test_set_output_grad_dtype_invalid_declarations: too few, too many, and a
  concrete dtype on a non-tensor output each graph break under
  fullgraph=True and raise eager's error otherwise. Fails without this check
  (too few declarations crashed Dynamo with an IndexError).
- test/dynamo/test_autograd_function.py, test/dynamo/test_higher_order_ops.py:
  350 passed.

ghstack-source-id: 21d6d46
Pull Request resolved: #200311
pytorchmergebot pushed a commit that referenced this pull request Oct 15, 2026
)

ctx.set_output_grad_dtype (#189634) lets an autograd.Function declare the
dtype its backward receives each output gradient in, independently of the
output's dtype. Dynamo traced the forward against a Python FunctionCtx
without the backing attribute, so any compiled Function calling it failed
with "'FunctionCtx' object has no attribute 'output_grad_dtypes'".

Follow the mark_non_differentiable / mark_dirty pattern:
- AutogradFunctionContextVariable records the declared dtypes (constant
  torch.dtype or None; anything else graph breaks).
- The backward is traced with gradient placeholders in the declared dtypes,
  via a new sub_args_dtypes override for forced subgraph inputs.
- autograd_function_apply replays the declaration in setup_context, so the
  autograd engine converts incoming gradients as in eager.

Motivation: torchtitan GraphTrainer's SimpleFSDP needs this to keep fp32
gradients of bf16 all-gathered weights (matching FSDP2's unsharded
grad_dtype = reduce_dtype) under torch.compile.

Test plan:
- test_set_output_grad_dtype: an fp32 gradient flowing into a bf16 output
  declared fp32 keeps a value bf16 cannot represent, in eager and under
  aot_eager with fullgraph=True. Fails without this change.
- test/dynamo/test_autograd_function.py, test/dynamo/test_higher_order_ops.py:
  348 passed.

Pull Request resolved: #200311
Approved by: https://github.com/anijain2305
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 Merged module: inductor open source release notes: autograd release notes category topic: new features topic category triaged This issue has been looked at a team member, and triaged and prioritized into an appropriate module

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants