Skip to content

autograd: make Tensor.grad_dtype readable on non-leaf tensors - #190852

Closed
sorenzzio wants to merge 4 commits into
pytorch:mainfrom
sorenzzio:feature/grad-dtype-getter
Closed

sorenzzio wants to merge 4 commits into
pytorch:mainfrom
sorenzzio:feature/grad-dtype-getter

Conversation

@sorenzzio

@sorenzzio sorenzzio commented Jul 23, 2026 •

Copy link
Copy Markdown
Contributor

Summary

This PR makes Tensor.grad_dtype readable on non-leaf tensors.

For a non-leaf tensor, the getter reads the gradient dtype from the producing autograd node's output metadata:

t.grad_fn()->input_metadata(t.output_nr()).grad_dtype()

The existing behavior for leaf tensors is unchanged. Setting Tensor.grad_dtype also remains restricted to leaf tensors.

Motivation

The gradient dtype declared for a custom autograd Function output is stored in the producing node's InputMetadata by ctx.set_output_grad_dtype(...). Simply removing the leaf-only check while continuing to read the Tensor's AutogradMeta would therefore not expose that declaration on a non-leaf output.

Reading the metadata associated with the tensor's current gradient edge allows a downstream Function to observe the gradient dtype contract declared by its producer.

One motivating example is the DTensor path:

param (DTensor) -> redistribute -> to_local

Here, redistribute can declare its output gradient dtype with ctx.set_output_grad_dtype(...), and to_local can read that declaration from its non-leaf input through Tensor.grad_dtype during forward.

Testing

Added coverage for:

  • reading the default gradient dtype from a non-leaf tensor;
  • reading gradient dtypes declared by ctx.set_output_grad_dtype(...) both inside a downstream Function's forward() and outside the Function;
  • explicit dtype declarations, None, and the unset/default behavior;
  • selecting the correct metadata entry for each tensor returned by a multi-output Function;
  • keeping the setter restricted to leaf tensors.

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 23, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

✅ You can merge normally! (1 Unrelated Failure)

As of commit 74feb0d with merge base 83296c3 (image):

CRCR (non-blocking) - The following CRCR downstream CI job failed but is non-blocking:

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

@albanD albanD added the triaged This issue has been looked at a team member, and triaged and prioritized into an appropriate module label Jul 24, 2026
@sorenzzio
sorenzzio force-pushed the feature/grad-dtype-getter branch from 34c0d05 to fc80536 Compare August 8, 2026 00:42
@pytorch-bot

pytorch-bot Bot commented Aug 8, 2026 •

Copy link
Copy Markdown

Workflows were awaiting approval. CI has now been triggered for the ciflow labels on this PR.

@sorenzzio

Copy link
Copy Markdown
Contributor Author

Hi @soulitzer , based on our previous discussion around the setter API, I’ve reworked the getter API to return a tuple. This keeps its interface consistent with set_output_grad_dtype while also simplifying the implementation. When you have a chance, could you please take another look? Thanks!

@jansel

jansel commented Aug 9, 2026

Copy link
Copy Markdown
Contributor

@claude review these changes

@claude

claude Bot commented Aug 9, 2026 •

Copy link
Copy Markdown

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


Reviewed — the main finding is that the getter silently returns all-None when the Function runs under torch.no_grad() (or when no input requires grad), because next_edges is deliberately left empty for non-executable nodes; that path is undocumented and untested.

Full review of #190852

PR Review: #190852

Summary

Adds ctx.get_input_grad_dtype(), returning a positional tuple of per-input expected gradient dtypes read out of the autograd graph's next_edges() input metadata. One correctness/contract gap around non-executable nodes, a missing null-cdata guard for consistency with sibling methods, missing docs registration, and tests that don't exercise the motivating end-to-end use case.

Code Quality

torch/csrc/autograd/python_function.cpp:1708 — missing check_legacy_fn_attr_access guard. Every other THPFunction method that dereferences self->cdata guards first: THPFunction_name (:1367), THPFunction_sequence_nr (:1375), THPFunction_set_sequence_nr (:1383), THPFunction_input_metadata (:1392). The new function does self->cdata->next_edges() at :1711 with no guard. Since the guard exists specifically because cdata can be null on legacy-access instances of _C._FunctionBase, this is a raw null deref rather than a TORCH_CHECK. Add the guard.

Fix this →

torch/csrc/autograd/python_function.cpp:1722 — the bounds check hides an invariant instead of asserting it. if (variable_index < next_edges.size()) silently produces None when the two containers disagree. There are exactly two cases: the node is executable, in which case next_edges.size() equals the number of true entries in is_variable_input and the check can never fail; or it is non-executable, in which case next_edges is empty and every entry silently becomes None (see next section). A TORCH_INTERNAL_ASSERT on the executable path plus explicit handling of the empty case would express what's actually going on.

torch/autograd/function.py:300 — the .pyi stub doesn't silence anything at this call site. FunctionCtx (function.py:38) does not inherit _C._FunctionBase; BackwardCFunction (:364) does. So adding _input_grad_dtype to _FunctionBase in torch/_C/__init__.pyi.in:280 types the other class, and the # pyrefly: ignore[missing-attribute] is still required. Prefer a class-level declaration on FunctionCtx, matching how the sibling PR handled the same problem for output_grad_dtypes at function.py:39. Also note the new stub is inserted directly beneath the comment "skip adding type hints for the fields that have wrappers defined in torch/autograd/function.py" — which describes exactly this method.

API Design

Non-executable nodes return all-None, silently. In unpack_input (python_function.cpp:1119-1122), next_edges is only populated when is_executable (GradMode::is_enabled() && any_requires_grad) is true; otherwise set_next_edges at :1867 stores an empty list, and nothing repopulates it. So a Function invoked under torch.no_grad(), in inference, or with no input requiring grad gets (None, None, ...) from forward, even for float inputs with a concrete grad_dtype.

The docstring promises "None means that any dtype is accepted", so a user branching on the result in forward (which the docstring explicitly sanctions and the motivation section describes) gets different forward behavior under no_grad than under grad mode, with no signal that anything changed. Pick one and commit to it: raise when the node is non-executable, or fall back to the input tensor's own grad_dtype, or document the behavior explicitly. Whichever you choose, it needs a test — see Testing below.

Fix this →

torch/autograd/function.py:279 — "This method may be called from any Function method" is not true under torch.compile. AutogradFunctionContextVariable.call_method (torch/_dynamo/variables/misc.py) models only __setattr__, mark_non_differentiable, mark_dirty, and save_for_backward; anything else raises Unsupported, which becomes a hard error rather than a graph break inside the speculated autograd.Function subgraph. That is why every test here is @skipIfTorchDynamo. The docstring should say so, rather than leaving the constraint only in a test skip reason.

Naming. The method returns N dtypes but is named singular, and the PR body itself calls the result input_grad_dtypes. set_output_grad_dtype takes varargs so the singular reads naturally there; a getter returning a tuple does not. Worth settling now, since renaming after landing is a BC break.

None overloading. None currently means: non-Tensor input, Tensor not requiring grad, grad_dtype explicitly set to None, and (per the issue above) non-executable node. The first two are recoverable from ctx.needs_input_grad, but "any dtype accepted" and "no gradient expected" are not distinguishable, and those are precisely the two cases a backward implementation would want to branch on differently. If that's intentional, the docstring should state that needs_input_grad is the way to disambiguate.

Testing

No test for the non-executable path. No test calls the Function under torch.no_grad() or with a non-requires_grad input, which is exactly where the all-None behavior above bites.

test/test_autograd.py:4526-4529 is vacuous. Setting x.grad_dtype = None and asserting (None, None, None, None) passes even if the getter is completely broken and always returns all-None — including under the no_grad bug. Mix a concrete dtype into the same call so the assertion can distinguish "read None correctly" from "read nothing".

Nothing tests the motivating use case. The stated motivation is constructing backward gradients in the reported dtype, but no test returns a gradient built from the getter's result and confirms the engine's validate_outputs dtype check (engine.cpp:997-1006) accepts it. test_ctx_input_grad_dtype_from_output_declaration sets up the interesting cross-Function case and then never calls .backward(), so the reported dtype is never validated against what the engine actually demands. Add an end-to-end case: read the dtype in backward, return a grad in it, assert no error and that x.grad.dtype is as expected.

test/test_autograd.py:4506, 4520-4521 — stashing ctx on the class and querying it after backward returns. QueryInput.ctx = ctx keeps the ctx (and its graph edges) alive on the class for the rest of the process, and the two QueryInput.ctx.get_input_grad_dtype() assertions test access from outside any Function method — behavior the docstring does not cover. If post-hoc access is intended to be supported, document it; if not, drop those two assertions rather than pinning behavior you may want to change. Separately, this setattr-on-the-Function-class pattern is what the comment at test/inductor/test_compiled_autograd.py:5702-5707 identifies as untraceable, so it's also what forces the skip.

test/test_autograd.py:4622-4626 — the unexplained float16 → float32 transition needs a comment. After entering fwAD.dual_level() and applying to a dual tensor, setup_seen flips from (torch.float16,) to (torch.float32,). Why the forward-AD wrapper drops the leaf's grad_dtype is not locally inferrable, and this is precisely the kind of non-obvious global context CLAUDE.md says a comment should carry. If it's incidental rather than intended, it shouldn't be asserted at all.

Documentation

get_input_grad_dtype is not added to the Context method mixins autosummary in docs/source/autograd.md:229-237, so the new public ctx method won't render in the docs. set_output_grad_dtype was also missed by the sibling PR — add both while you're here.

Fix this →

Thread Safety

Reading metadata.grad_dtype() from backward runs on an autograd worker thread, while Tensor.grad_dtype = ... writes the same field through mutable_input_metadata(0).set_grad_dtype (variable.cpp:966-969) with no lock. The race pre-exists (the engine reads the same field at engine.cpp:997), but this getter makes it reachable from user code on a user-chosen thread, and test_ctx_input_grad_dtype_live_read documents mid-forward mutation as a supported pattern. At minimum the docstring shouldn't advertise live mutation as intended without noting there's no synchronization.

Recommendation

Request Changes

The non-executable/no_grad behavior is the blocker: it's a silent, undocumented, untested divergence in a value users are meant to branch on. The missing cdata guard and the missing docs entry are small and mechanical. The test additions are broad but never exercise the end-to-end scenario the PR exists to enable, which should be the bar before landing a new public ctx method.

· branch [`feature/grad-dtype-getter`](https://github.com/pytorch/pytorch/tree/feature/grad-dtype-getter)

@soulitzer

Copy link
Copy Markdown
Contributor

Should we just make reading t.grad_dtype work on non-leafs too? 🤔

@sorenzzio

sorenzzio commented Aug 11, 2026 •

Copy link
Copy Markdown
Contributor Author

Thanks! I think there are two possible interpretations of making t.grad_dtype readable on non-leaf tensors:

  1. Only remove the leaf-only check from the current getter. I don't think this would be sufficient: Tensor.grad_dtype currently reads from the Tensor's AutogradMeta, while ctx.set_output_grad_dtype(...) writes to the producing Function node's InputMetadata. A non-leaf read would therefore not necessarily see the gradient dtype declared by the producer.

  2. For a non-leaf tensor, make t.grad_dtype read from t.grad_fn->input_metadata(t.output_nr). This would retrieve the gradient dtype contract for the producing node's corresponding output slot, so it should satisfy the use case.

Did you mean the second approach, or simply lifting the current leaf-only restriction?

For our target DTensor propagation path between Redistribute and to_local, either ctx.get_input_grad_dtype() together with ctx.set_output_grad_dtype(...), or the edge-aware non-leaf t.grad_dtype described in (2), should satisfy the requirement. The main difference seems to be the API perspective: the ctx API is organized around a Function's input and output slots, while t.grad_dtype is organized around the Tensor's current gradient edge. I'd appreciate your thoughts on which abstraction would be more appropriate here. @soulitzer

@soulitzer

Copy link
Copy Markdown
Contributor

@SongyuanZhao Yep, checking the input_metadata here for reading t.grad_dtype sounds good!

@sorenzzio
sorenzzio force-pushed the feature/grad-dtype-getter branch from 9388e63 to 0957da0 Compare August 14, 2026 04:26
@sorenzzio sorenzzio changed the title autograd: add ctx.get_input_grad_dtype autograd: make Tensor.grad_dtype readable on non-leaf tensors Aug 14, 2026
@sorenzzio

Copy link
Copy Markdown
Contributor Author

@soulitzer Thanks for the suggestion! I've reworked the PR accordingly. Could you please take another look when you have a chance?

@soulitzer

Copy link
Copy Markdown
Contributor

Thanks for the update! I think one thing we need to validate here is whether setting .grad on non-leaf is also consistent with the non-leaf grad-dtype

Non-leaf grad_dtype is stored in the output edge metadata, but assigning .grad only consulted the tensor AutogradMeta. This made the public grad_dtype value disagree with the dtype accepted by the .grad setter.

Use one effective grad dtype lookup for both the getter and setter, and cover successful and rejected assignments. Keeping the lookup shared avoids duplicating the non-leaf edge handling.

Test Plan:

Remote CPU-only build:

```
/home/hadoop-scale-llm/ptbuild/bin/python -m pip install -e . -v --no-build-isolation
```

Targeted remote test (14 passed):

```
env -u LD_PRELOAD -u PYTHONPATH /home/hadoop-scale-llm/ptbuild/bin/python /home/hadoop-scale-llm/codex-build/pytorch-pr190852/test/test_autograd.py -v -k grad_dtype
```

Lint attempted locally:

```
.venv/bin/lintrunner -a
```

Lint could not complete because the local build directory is absent; the all-files Pyrefly checks also reported pre-existing missing torch attributes from the unbuilt checkout.

Authored with assistance from Codex, an AI coding assistant.
@sorenzzio
sorenzzio force-pushed the feature/grad-dtype-getter branch from 0957da0 to 5fe7d6f Compare August 15, 2026 02:03
@sorenzzio

Copy link
Copy Markdown
Contributor Author

Thanks for pointing this out! This was indeed a gap: assigning .grad on a non-leaf tensor was not validated against its effective grad_dtype. I’ve fixed the inconsistency and added tests.

@jansel jansel added the topic: not user facing topic category label Aug 16, 2026
Comment thread torch/_tensor_docs.py Outdated
``t.grad_dtype == t.dtype``. When not None, the autograd engine casts
incoming gradients to this dtype. This attribute is only accessible and
settable for leaf tensors.
incoming gradients to this dtype. This attribute is readable for all tensors,

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.

minor nit: "this attribute is readable for both leaf and non-leaf tensors, but can only be set for leaf tensors"

Suggesting this wording as "all tensors" might too broad and could imply other properties like whether a tensor is differnetiable. Although it is possible to access grad_dtype for tensors of non-differentiable dtype it is not useful to do so.

@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.

Looks great, thanks for the update! Minor comment on wording of doc

Replace "all tensors" with "both leaf and non-leaf tensors" to describe the supported tensor categories precisely.

Test Plan:

Documentation-only wording change.

Authored with assistance from Codex, an AI coding assistant.
Bind the producing node shared pointer by const reference when reading the effective gradient dtype.

Test Plan:

```
spin quicklint -- --take CLANGFORMAT
```

Authored with assistance from Codex, an AI coding assistant.
@sorenzzio

Copy link
Copy Markdown
Contributor Author

@soulitzer Thanks! I’ve updated the wording as suggested~

@soulitzer

Copy link
Copy Markdown
Contributor

@pytorchbot merge

@pytorch-bot pytorch-bot Bot added the ciflow/trunk Trigger trunk jobs on your pull request label Aug 19, 2026
@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

orrangetabby17 pushed a commit to orrangetabby17/pytorch that referenced this pull request Sep 2, 2026
…h#190852)

## Summary

This PR makes `Tensor.grad_dtype` readable on non-leaf tensors.

For a non-leaf tensor, the getter reads the gradient dtype from the producing autograd node's output metadata:

```cpp
t.grad_fn()->input_metadata(t.output_nr()).grad_dtype()
```

The existing behavior for leaf tensors is unchanged. Setting `Tensor.grad_dtype` also remains restricted to leaf tensors.

## Motivation

The gradient dtype declared for a custom autograd Function output is stored in the producing node's `InputMetadata` by `ctx.set_output_grad_dtype(...)`. Simply removing the leaf-only check while continuing to read the Tensor's `AutogradMeta` would therefore not expose that declaration on a non-leaf output.

Reading the metadata associated with the tensor's current gradient edge allows a downstream Function to observe the gradient dtype contract declared by its producer.

One motivating example is the DTensor path:

```text
param (DTensor) -> redistribute -> to_local
```

Here, `redistribute` can declare its output gradient dtype with `ctx.set_output_grad_dtype(...)`, and `to_local` can read that declaration from its non-leaf input through `Tensor.grad_dtype` during forward.

## Testing

Added coverage for:

- reading the default gradient dtype from a non-leaf tensor;
- reading gradient dtypes declared by `ctx.set_output_grad_dtype(...)` both inside a downstream Function's `forward()` and outside the Function;
- explicit dtype declarations, `None`, and the unset/default behavior;
- selecting the correct metadata entry for each tensor returned by a multi-output Function;
- keeping the setter restricted to leaf tensors.

Pull Request resolved: pytorch#190852
Approved by: https://github.com/soulitzer
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 topic: not user facing 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.

6 participants