Skip to content

[Dynamo] Preserve leaf gradient dtype through compiled backward - #197381

Open
xiuhu17 wants to merge 2 commits into
pytorch:mainfrom
xiuhu17:xiuhu17/fsdp-compile-grad-dtype
Open

xiuhu17 wants to merge 2 commits into
pytorch:mainfrom
xiuhu17:xiuhu17/fsdp-compile-grad-dtype

Conversation

@xiuhu17

@xiuhu17 xiuhu17 commented Sep 17, 2026 •

Copy link
Copy Markdown
Contributor

Agent details (AI-generated)

A BF16 leaf with grad_dtype=torch.float32 keeps a custom backward's FP32
gradient in eager, but compiled backward rounded it to BF16: functional and
fake tensors lost the leaf's grad_dtype, so AOTAutograd traced a cast to the
tensor dtype.

  • _mirror_autograd_meta_to copies the grad_dtype override before
    set_history, which covers FunctionalTensor and subclass (DTensor) inputs.
    MetaConverter sets it on fakes before attaching an existing .grad.
  • The receiving grad_dtype is part of C++ TensorCheck (TENSOR_MATCH and the
    dict-tag fast path); DTensor, which skips TENSOR_MATCH, gets an
    EQUALS_MATCH. A default leaf and a non-leaf share a graph.
  • The AOT cache key and guard serialization include it.
  • Dynamo no longer graph-breaks on an existing .grad whose dtype the leaf's
    grad_dtype allows (FSDP2 FP32 grads on BF16 params).

Relation to the FSDP2 stack (#194434, #198668, #200196): on main FSDP2 sets
the unsharded param's grad_dtype to FP32 or None per microbatch, so a
compiled region has at most two graphs. Overlaps with #199856.

Validation (CPU aarch64 source build; no CUDA run): see commit message
Test Plan.

Follow-ups not in scope

  • compiled autograd's accumulate_grad placeholder ignores grad_dtype
    (raises under compiled_autograd=True, also on main)
  • export-mode tensor guards ([Note - On Export Tensor Guards]) do not
    check grad_dtype

🤖 Generated with Claude Code

@pytorch-bot

pytorch-bot Bot commented Sep 17, 2026 •

Copy link
Copy Markdown

PR Status: in progress

A maintainer requested changes. Please address their feedback before the PR returns to maintainer review.

To become ready for review, the change must pass automated review and every maintainer comment must be addressed, either with a code change or a reply explaining why no change is needed. Any running CI must finish and every failure must be classified as unrelated to your PR (see status below in this comment).

To minimize iteration time, feel free to run the pr-review skill from the repo locally. If an automated review comment is irrelevant, react with 👎 on that specific comment to reject it, and leave a short reply explaining why. To trigger a fresh automated review, make a new push or comment @pytorchbot review. To bypass automated review, please add the “no automated review” label.

🟡 AUTOMATED REVIEW - Changes requested:

The PR keeps a leaf's `grad_dtype` on FakeTensor and FunctionalTensor inputs so
compiled backward no longer rounds an FP32 custom-backward gradient to BF16. It
adds `grad_dtype` to `TensorCheck` and the AOT cache key, and stops
graph-breaking on a `.grad` whose dtype the leaf's `grad_dtype` allows.
Recommendation: Request Changes. The new DTensor test should fail under the
compiled-autograd wrapper, and removing the graph break exposes a `clone_input`
crash.

Findings (10):

[major] test/distributed/tensor/test_dtensor_compile.py:1294
The new DTensor test should fail under compiled autograd.
`test/inductor/test_compiled_autograd.py:5809-5813` wraps every
`TestDTensorCompile` test when `HAS_GPU_AND_TRITON`, so this test also runs as
`TestDTensorCompileWithCompiledAutograd.test_dtensor_grad_dtype_recompile`, and
`ciflow/inductor` is on the PR. Under compiled autograd the fake DTensor now
carries `grad_dtype=float32` (`meta_utils.py:2275-2278`). `accumulate_grad`
assigns an `empty_like` BF16 dummy to `variable.grad`
(`compiled_autograd.py:911-913`), and the `.grad` setter rejects it. The PR body
confirms compiled autograd raises here, and the author validated on CPU only.
Existing `grad_dtype` tests are already xfailed or skipped there (lines 5681,
5786-5792). Fix: add the new test to `xfail_by_backend` or `skipped_tests` in
`test_compiled_autograd.py`.

[major] torch/_dynamo/variables/builder.py:3488
Removing the graph break exposes a `clone_input` crash. A BF16 leaf with
`grad_dtype` FP32 or `None` and an FP32 `.grad` used to graph-break before
becoming a graph input; now it is traced. `clone_input`
(`torch/_dynamo/utils.py:2687-2772`) clones the tensor without its `grad_dtype`
override, then sets `result.grad = clone_input(x.grad)` (line 2765), and the
`.grad` setter (`python_variable.cpp:2829-2838`) raises. The `except
RuntimeError` fallback to `torch_clone` assigns `.grad` again at line 2708
outside any `try`, so the error escapes. Reached when Dynamo clones real inputs:
`config.verify_correctness` (`WrapperBackend` calls `clone_inputs` at
`output_graph.py:405-406`; used to fall back to eager, now crashes), the
minifier/accuracy repro (`clone_inputs_retaining_gradness` in
`debug_utils.py:592`, `repro/after_dynamo.py`, `repro/after_aot.py:1446-1522`),
and export's `cache_real_value_when_export`. Fix: copy the `grad_dtype` override
in `clone_input` and `clone_tensor` before assigning `.grad`, and add a test.

[minor] torch/_dynamo/variables/builder.py:3628
The DTensor guard follows a different rule than the rest of the PR. The
`grad_dtype` EQUALS_MATCH is gated only on `value.requires_grad`. For a non-leaf
DTensor the Python getter returns the dtype declared in `grad_fn`'s input
metadata (`python_variable.cpp:2796-2803`), while `TensorCheck`
(`receiving_grad_dtype`, `guards.cpp:216`) and `_receiving_grad_dtype`
(`autograd_cache.py:916`) use the tensor's own dtype. The getter goes through
`grad_fn()`, which `guards.cpp:214-215` says raises for a multi-output view
modified in place (`variable.cpp:857-888`). At runtime the accessor clears that
error and counts a guard failure, but EQUALS_MATCH reads the value when the
guard is built (`guards.py:3162`), so compiling such a DTensor fails outright.
Fix: gate the guard on `safe_is_leaf(value)`, or compare the same leaf-or-dtype
value `TensorCheck` uses.

[minor] torch/_dynamo/variables/builder.py:3488
builder.py:3488 uses raw `value.is_leaf`. The other new Python sites
(`guards.py:5236`, `meta_utils.py:310`, `autograd_cache.py:919`) use
`safe_is_leaf`, which catches the `RuntimeError` from `grad_fn()`. Here a raise
turns the old graph break into a hard error. Import `safe_is_leaf` alongside
`safe_grad` at line 83 and use it.

(6 more not shown, see the review run)

Reviewed commit: e787fbf

Review run

🐛 Report a bad review

🔗 Helpful Links

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

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

❌ 2 Cancelled Jobs, 1 Unrelated Failure

As of commit e787fbf with merge base 113a303 (image):

NEW FAILURES SUPPRESSED BY AI (non-blocking) - The following job failed, but the AI CI Advisor judged the failure not to be evidence against this change:

CANCELLED JOBS - The following jobs were cancelled. Please retry:

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

@pytorch-bot

pytorch-bot Bot commented Sep 17, 2026 •

Copy link
Copy Markdown

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

@pytorch-bot

pytorch-bot Bot commented Sep 17, 2026

Copy link
Copy Markdown

The following ciflow label(s) have been added but CI has not been triggered yet because the workflows are awaiting approval:

  • ciflow/inductor
  • ciflow/torchtitan

Once a maintainer approves the workflows (scroll to the bottom of the PR page), the corresponding CI jobs will be triggered automatically. Please ping one of the reviewers if you do not have access to approve and run workflows.

@xiuhu17
xiuhu17 marked this pull request as ready for review September 17, 2026 05:22
@liangel-02 liangel-02 added the triaged This issue has been looked at a team member, and triaged and prioritized into an appropriate module label Sep 17, 2026
felipemello1 pushed a commit to felipemello1/torchtitan that referenced this pull request Oct 2, 2026
pytorch/pytorch#194434 landed: FSDP2 keeps an fp32 grad on a bf16 unsharded param
under fp32 reduce, so casting grad_weight to the weight's dtype only dropped bits.
This replaces the "keep grad_weight in bf16" TODO from the previous commit.
- All paths return grad_weight in fp32; the LM-head layout uses mm(out_dtype=fp32).
  grad_input is still rounded once to the input's dtype.
- Without FSDP's fp32 grads, autograd rounds it to bf16 as before (bitwise the same
  as the previous commit). Compiled, AOTAutograd rounds it too (pytorch/pytorch#197381).
- Free the split pieces before the fp32 grad_weight GEMM (peak memory).
- FSDP eager, 2026-10-02 nightly: grad_weight error vs fp64 is 2.7e-7 (LM head)
  and 2.4e-7 (router), down from the 1.7e-3 bf16 floor.
- Tests: fp32 grad_weight with an fp32 grad_dtype (both layouts, fallback, both
  split modes), a 2-GPU FSDP test (compiled is a strict xfail), zero tokens,
  converter idempotence.
anijain2305 added a commit that referenced this pull request Oct 6, 2026
Please open this PR as a draft and mark it ready for review once the description and code are ready to be looked at.

Before submitting, please review:
- [PR lifecycle](https://github.com/pytorch/pytorch/blob/main/CONTRIBUTING.md#pr-lifecycle) in the contributing guide
- [AI-Assisted Development](https://github.com/pytorch/pytorch/blob/main/AI_POLICY.md) policy

Go through the following checklist
- [x] Passes lint (`spin fixlint`)
- [x] Added/updated tests
- [ ] Updated documentation (if applicable)
- [ ] Included benchmark results (for PRs impacting perf)

---

Summary (human written only)
---------------------------

grad_dtype is a recent PyTorch feature. This PR adds plumbing for compile.

There was a parallel effort in #197381. Some parts in this PR are borrowed from that PR, but that PR does more than necessary.

BC-breaking?
--------------

No. Dynamo now also guards on `grad_dtype` of grad-requiring inputs, so changing `grad_dtype` between calls recompiles.

Agent details (if applicable)
-----------------------------
Claude (AI assistant) wrote the following analysis and test summary:

> **Bug:** a bf16 leaf with `grad_dtype=torch.float32` (set by FSDP2 for `reduce_dtype=torch.float32`) keeps a custom backward's fp32 gradient in eager. Under torch.compile the gradient is rounded to bf16: `.grad` is still fp32, but the low bits are gone.
>
> **Root cause:** the autograd engine casts each gradient to the receiving node's `InputMetadata.grad_dtype`, which defaults to the tensor's own dtype. When AOTAutograd traces the joint graph it wraps inputs (FunctionalTensor, and for subclasses a rebuilt subclass plus its functional wrapper) and calls `_mirror_autograd_meta_to`, which copies `requires_grad` but not `grad_dtype`. The wrapper's dummy grad_fn records bf16, so the engine bakes a `_to_copy(..., bfloat16)` into the traced backward.
>
> **Fix:** `copy_grad_dtype_override` copies the effective `grad_dtype` onto each wrapper before it gets a grad_fn, at all three wrapping sites: `FunctionalTensor.to_functional`, the subclass branch of `to_fun`, and `SubclassCreationMeta.creation_fn`. For non-leaves the `grad_dtype` getter returns the grad_fn's input metadata, so the same check works when the source is an already-mirrored wrapper. This is what makes DTensor inputs work.
>
> Because the backward graph now depends on `grad_dtype`:
> - Dynamo guards on `grad_dtype` of every grad-requiring input. Changing it (e.g. FSDP2 toggling `None`/fp32), or going from a non-leaf to a leaf with an override, recompiles.
> - The AOTAutograd cache key includes `grad_dtype`.
> - An existing `.grad` whose dtype differs from the param's no longer graph-breaks when the leaf's `grad_dtype` permits it. Meta conversion sets `grad_dtype` on the fake leaf before attaching the fake `.grad` (gradient-accumulation case).
>
> The guard, cache-key, graph-break and meta_utils pieces are adapted from #197381, with a single `grad_dtype` guard instead of separate `is_leaf` and `grad_dtype` guards, and no `is_leaf` special case in the cache key. #197381 only handles `to_functional`, so DTensor inputs were still rounded there.
>
> **Test Plan:** the new tests fail before the fix and pass after:
>
> ```
> python -m pytest -q test/functorch/test_aotdispatch.py test/distributed/tensor/test_dtensor_compile.py -k test_custom_autograd_grad_dtype
> ```
>
> The Dynamo tests from #197381 (`test/dynamo/test_grad_dtype.py`, not included here) cover the grad_dtype-change recompile, non-leaf to leaf, an existing fp32 `.grad`, and the cache key. All 26 pass.
>
> Single-GPU checks against eager on aot_eager and inductor: a plain bf16 param; a DTensor param (Replicate and Shard(0)) passed straight into the compiled function; and FSDP2 `fully_shard(param_dtype=bf16, reduce_dtype=fp32)` with `torch.compile(module)`. All were rounded before the fix and match eager after.
>
> Regression suites:
>
> ```
> python -m pytest -q test/functorch/test_aotdispatch.py -k "not TestEagerFusion"
> python -m pytest -q test/distributed/tensor/test_dtensor_compile.py
> python -m pytest -q test/dynamo/test_subclasses.py
> python -m pytest -q test/test_autograd.py test/test_fake_tensor.py test/functorch/test_leaf_function.py -k grad_dtype
> python -m pytest -q test/dynamo/test_recompiles.py test/dynamo/test_guard_manager.py test/dynamo/test_modules.py test/dynamo/test_misc.py
> ```
>
> All pass, except `test_aotdispatch.py::TestPartitioning::test_disable_functionalization_ignores_effect_token_metadata`, which also fails without this change (the local build lacks LAPACK).


ghstack-source-id: 45a4f17
Pull-Request: #199856
anijain2305 added a commit that referenced this pull request Oct 6, 2026
Summary (human written only)
----------------------------

grad_dtype is a recent PyTorch feature. This PR adds plumbing for compile.

There was a parallel effort in #197381. Some parts in this PR are borrowed from that PR, but that PR does more than necessary.

BC-breaking?
------------

No. Dynamo now also guards on `grad_dtype` of grad-requiring inputs, so changing `grad_dtype` between calls recompiles.

Agent details (if applicable)
-----------------------------
Claude (AI assistant) wrote the following analysis and test summary:

> **Bug:** a bf16 leaf with `grad_dtype=torch.float32` (set by FSDP2 for `reduce_dtype=torch.float32`) keeps a custom backward's fp32 gradient in eager. Under torch.compile the gradient is rounded to bf16: `.grad` is still fp32, but the low bits are gone.
>
> **Root cause:** the autograd engine casts each gradient to the receiving node's `InputMetadata.grad_dtype`, which defaults to the tensor's own dtype. When AOTAutograd traces the joint graph it wraps inputs (FunctionalTensor, and for subclasses a rebuilt subclass plus its functional wrapper) and calls `_mirror_autograd_meta_to`, which copies `requires_grad` but not `grad_dtype`. The wrapper's dummy grad_fn records bf16, so the engine bakes a `_to_copy(..., bfloat16)` into the traced backward.
>
> **Fix:** `copy_grad_dtype_override` copies the effective `grad_dtype` onto each wrapper before it gets a grad_fn, at all three wrapping sites: `FunctionalTensor.to_functional`, the subclass branch of `to_fun`, and `SubclassCreationMeta.creation_fn`. For non-leaves the `grad_dtype` getter returns the grad_fn's input metadata, so the same check works when the source is an already-mirrored wrapper. This is what makes DTensor inputs work.
>
> Because the backward graph now depends on `grad_dtype`:
> - Dynamo guards on `grad_dtype` of every grad-requiring input. Changing it (e.g. FSDP2 toggling `None`/fp32), or going from a non-leaf to a leaf with an override, recompiles.
> - The AOTAutograd cache key includes `grad_dtype`.
> - An existing `.grad` whose dtype differs from the param's no longer graph-breaks when the leaf's `grad_dtype` permits it. Meta conversion sets `grad_dtype` on the fake leaf before attaching the fake `.grad` (gradient-accumulation case).
>
> The guard, cache-key, graph-break and meta_utils pieces are adapted from #197381, with a single `grad_dtype` guard instead of separate `is_leaf` and `grad_dtype` guards, and no `is_leaf` special case in the cache key. #197381 only handles `to_functional`, so DTensor inputs were still rounded there.
>
> **Test Plan:** the new tests fail before the fix and pass after:
>
> ```
> python -m pytest -q test/functorch/test_aotdispatch.py test/distributed/tensor/test_dtensor_compile.py -k test_custom_autograd_grad_dtype
> ```
>
> The Dynamo tests from #197381 (`test/dynamo/test_grad_dtype.py`, not included here) cover the grad_dtype-change recompile, non-leaf to leaf, an existing fp32 `.grad`, and the cache key. All 26 pass.
>
> Single-GPU checks against eager on aot_eager and inductor: a plain bf16 param; a DTensor param (Replicate and Shard(0)) passed straight into the compiled function; and FSDP2 `fully_shard(param_dtype=bf16, reduce_dtype=fp32)` with `torch.compile(module)`. All were rounded before the fix and match eager after.
>
> Regression suites:
>
> ```
> python -m pytest -q test/functorch/test_aotdispatch.py -k "not TestEagerFusion"
> python -m pytest -q test/distributed/tensor/test_dtensor_compile.py
> python -m pytest -q test/dynamo/test_subclasses.py
> python -m pytest -q test/test_autograd.py test/test_fake_tensor.py test/functorch/test_leaf_function.py -k grad_dtype
> python -m pytest -q test/dynamo/test_recompiles.py test/dynamo/test_guard_manager.py test/dynamo/test_modules.py test/dynamo/test_misc.py
> ```
>
> All pass, except `test_aotdispatch.py::TestPartitioning::test_disable_functionalization_ignores_effect_token_metadata`, which also fails without this change (the local build lacks LAPACK).

ghstack-source-id: 4652e68
Pull-Request: #199856
anijain2305 added a commit that referenced this pull request Oct 6, 2026
Summary (human written only)
----------------------------

grad_dtype is a recent PyTorch feature. This PR adds plumbing for compile.

There was a parallel effort in #197381. Some parts in this PR are borrowed from that PR, but that PR does more than necessary.

BC-breaking?
------------

No. Dynamo now also guards on `grad_dtype` of grad-requiring inputs, so changing `grad_dtype` between calls recompiles.

Agent details (if applicable)
-----------------------------
Claude (AI assistant) wrote the following analysis and test summary:

> **Bug:** a bf16 leaf with `grad_dtype=torch.float32` (set by FSDP2 for `reduce_dtype=torch.float32`) keeps a custom backward's fp32 gradient in eager. Under torch.compile the gradient is rounded to bf16: `.grad` is still fp32, but the low bits are gone.
>
> **Root cause:** the autograd engine casts each gradient to the receiving node's `InputMetadata.grad_dtype`, which defaults to the tensor's own dtype. When AOTAutograd traces the joint graph it wraps inputs (FunctionalTensor, and for subclasses a rebuilt subclass plus its functional wrapper) and calls `_mirror_autograd_meta_to`, which copies `requires_grad` but not `grad_dtype`. The wrapper's dummy grad_fn records bf16, so the engine bakes a `_to_copy(..., bfloat16)` into the traced backward.
>
> **Fix:** `copy_grad_dtype_override` copies the effective `grad_dtype` onto each wrapper before it gets a grad_fn, at all three wrapping sites: `FunctionalTensor.to_functional`, the subclass branch of `to_fun`, and `SubclassCreationMeta.creation_fn`. For non-leaves the `grad_dtype` getter returns the grad_fn's input metadata, so the same check works when the source is an already-mirrored wrapper. This is what makes DTensor inputs work.
>
> Because the backward graph now depends on `grad_dtype`:
> - `TENSOR_MATCH` (C++ `TensorCheck`) also checks `grad_dtype` for tensors that require grad. Changing it (e.g. FSDP2 toggling `None`/fp32), or going from a non-leaf to a leaf with an override, recompiles with a `grad_dtype mismatch` reason.
> - The AOTAutograd cache key includes `grad_dtype`.
> - An existing `.grad` whose dtype differs from the param's no longer graph-breaks when the leaf's `grad_dtype` permits it. Meta conversion sets `grad_dtype` on the fake leaf before attaching the fake `.grad` (gradient-accumulation case).
>
> The cache-key, graph-break and meta_utils pieces are adapted from #197381. That PR adds separate Python `is_leaf` and `grad_dtype` guards; here the check lives in `TensorCheck`, and the cache key has no `is_leaf` special case. #197381 only handles `to_functional`, so DTensor inputs were still rounded there.
>
> **Test Plan:** the new tests fail before the fix and pass after:
>
> ```
> python -m pytest -q test/functorch/test_aotdispatch.py test/distributed/tensor/test_dtensor_compile.py -k test_custom_autograd_grad_dtype
> ```
>
> The Dynamo tests from #197381 (`test/dynamo/test_grad_dtype.py`, not included here) cover the grad_dtype-change recompile, non-leaf to leaf, an existing fp32 `.grad`, and the cache key. All 26 pass.
>
> Single-GPU checks against eager on aot_eager and inductor: a plain bf16 param; a DTensor param (Replicate and Shard(0)) passed straight into the compiled function; and FSDP2 `fully_shard(param_dtype=bf16, reduce_dtype=fp32)` with `torch.compile(module)`. All were rounded before the fix and match eager after.
>
> Regression suites:
>
> ```
> python -m pytest -q test/functorch/test_aotdispatch.py -k "not TestEagerFusion"
> python -m pytest -q test/distributed/tensor/test_dtensor_compile.py
> python -m pytest -q test/dynamo/test_subclasses.py
> python -m pytest -q test/test_autograd.py test/test_fake_tensor.py test/functorch/test_leaf_function.py -k grad_dtype
> python -m pytest -q test/dynamo/test_recompiles.py test/dynamo/test_guard_manager.py test/dynamo/test_modules.py test/dynamo/test_misc.py
> ```
>
> All pass, except `test_aotdispatch.py::TestPartitioning::test_disable_functionalization_ignores_effect_token_metadata`, which also fails without this change (the local build lacks LAPACK).

ghstack-source-id: 30a10f5
Pull-Request: #199856
anijain2305 added a commit that referenced this pull request Oct 6, 2026
Summary (human written only)
----------------------------

grad_dtype is a recent PyTorch feature. This PR adds plumbing for compile.

There was a parallel effort in #197381. Some parts in this PR are borrowed from that PR, but that PR does more than necessary.

BC-breaking?
------------

No.

Agent details (if applicable)
-----------------------------
Claude (AI assistant) wrote the following analysis and test summary:

> **Bug:** a bf16 leaf with `grad_dtype=torch.float32` (set by FSDP2 for `reduce_dtype=torch.float32`) keeps a custom backward's fp32 gradient in eager. Under torch.compile the gradient is rounded to bf16: `.grad` is still fp32, but the low bits are gone.
>
> **Root cause:** the autograd engine casts each gradient to the receiving node's `InputMetadata.grad_dtype`, which defaults to the tensor's own dtype. When AOTAutograd traces the joint graph it wraps inputs (FunctionalTensor, and for subclasses a rebuilt subclass plus its functional wrapper) and calls `_mirror_autograd_meta_to`, which copies `requires_grad` but not `grad_dtype`. The wrapper's dummy grad_fn records bf16, so the engine bakes a `_to_copy(..., bfloat16)` into the traced backward.
>
> **Fix:** let the eager autograd engine do this cast, as in eager. The engine casts a gradient to `grad_dtype` on the edge into the leaf's `AccumulateGrad`, reading the live metadata at backward time. `AccumulateGrad` stays outside the compiled region, so it already does that cast for the compiled backward's outputs; the trace-time cast inside the graph was a second, frozen copy. While tracing the joint graph, `defer_input_grad_casts` marks each input wrapper as accepting any grad dtype (`grad_dtype=None`) before it gets a grad_fn, at all three wrapping sites: `FunctionalTensor.to_functional`, the subclass branch of `to_fun`, and `SubclassCreationMeta.creation_fn`. The backward graph then returns input grads in the dtype their formula produced and does not depend on any input's `grad_dtype`. So no guard or cache-key change is needed. Changing `grad_dtype` between calls, or between forward and backward, matches eager, and DTensor inputs need no special handling.
>
> Exported joint graphs (`aot_config.is_export`) run without the engine, so they keep the cast and instead copy the input's `grad_dtype` onto the wrappers.
>
> An existing `.grad` whose dtype differs from the param's (the gradient-accumulation case) no longer graph-breaks when the leaf's `grad_dtype` permits it, and meta conversion sets `grad_dtype` on the fake leaf before attaching the fake `.grad`, which the `.grad` setter would otherwise reject. These two pieces are adapted from #197381.
>
> **Alternative considered:** copying the input's `grad_dtype` onto the wrappers everywhere, plus a Dynamo guard and an AOTAutograd cache-key entry for it. That froze the cast at trace time, so widening `grad_dtype` after the forward still rounded. It also needed per-input-kind plumbing: DTensor skips the outer `TENSOR_MATCH`, and subclass cache hashes omit `grad_dtype`.
>
> **Test Plan:** the new tests fail before the fix and pass after:
>
> ```
> python -m pytest -q test/functorch/test_aotdispatch.py test/distributed/tensor/test_dtensor_compile.py -k test_custom_autograd_grad_dtype
> ```
>
> Checked against eager on aot_eager and inductor: the custom fp32-grad backward with `grad_dtype` fp32 and None; `grad_dtype` changed between forward and backward in both directions; the same compiled callable called with a DTensor param under bf16 and then fp32 `grad_dtype` (no recompile needed); and plain linear/matmul with gradient accumulation.

ghstack-source-id: 9261e36
Pull-Request: #199856
anijain2305 added a commit that referenced this pull request Oct 6, 2026
Summary (human written only)
----------------------------

grad_dtype is a recent PyTorch feature. This PR adds plumbing for compile.

There was a parallel effort in #197381. Some parts in this PR are borrowed from that PR, but that PR does more than necessary.

Claude (AI assistant) wrote this explanation of when changing `grad_dtype` between the compiled forward and backward is safe:

> Under compile, a leaf's grad goes through two casts, while eager applies only one:
>
> ```
> compiled:  formula -> [A: in the graph, to the trace-time grad_dtype] -> [B: autograd engine, to the live grad_dtype] -> .grad
> eager:     formula ----------------------------------------------------> [B: autograd engine, to the live grad_dtype] -> .grad
> ```
>
> Cast A is baked into the traced backward (skipped when the formula already produces the trace-time grad_dtype). Cast B is the engine's normal cast into AccumulateGrad, using the grad_dtype set when backward runs. Compiled matches eager whenever A followed by B gives the same result as B alone, which holds unless A discarded bits that B would have kept. Only a narrowing cast discards bits:
>
> | Formula | Trace-time grad_dtype (cast A) | Live grad_dtype (cast B) | Compiled vs eager |
> |---|---|---|---|
> | fp32 (custom) | fp32 (none) | bf16 (narrow) | same |
> | fp32 (custom) | fp32 (none) | None (none) | same |
> | bf16 (normal mm) | bf16 (none) | fp32 (widen) | same |
> | bf16 (normal mm) | fp32 (widen) | None (none) | same values; fp32 instead of bf16 |
> | fp32 (custom) | bf16 (narrow) | fp32 or None | compiled is bf16-rounded |
>
> Only the last row loses precision: A narrowed fp32 to bf16 in the graph, and B can't restore the bits. So the runtime records the inputs whose traced backward narrows their grad and raises if their grad_dtype differs at backward time.

BC-breaking?
------------

No.

Agent details (if applicable)
-----------------------------
Claude (AI assistant) wrote the following analysis and test summary:

> **Bug:** a bf16 leaf with `grad_dtype=torch.float32` (set by FSDP2 for `reduce_dtype=torch.float32`) keeps a custom backward's fp32 gradient in eager. Under torch.compile the gradient is rounded to bf16: `.grad` is still fp32, but the low bits are gone.
>
> **Root cause:** the autograd engine casts each gradient to the receiving node's `InputMetadata.grad_dtype`, which defaults to the tensor's own dtype. When AOTAutograd traces the joint graph it wraps inputs (FunctionalTensor, and for subclasses a rebuilt subclass plus its functional wrapper) and calls `_mirror_autograd_meta_to`, which copies `requires_grad` but not `grad_dtype`. The wrapper's dummy grad_fn records bf16, so the engine bakes a `_to_copy(..., bfloat16)` into the traced backward.
>
> **Fix:** `copy_grad_dtype_override` copies the effective `grad_dtype` onto each wrapper before it gets a grad_fn, at all three wrapping sites: `FunctionalTensor.to_functional`, the subclass branch of `to_fun`, and `SubclassCreationMeta.creation_fn`. For non-leaves the `grad_dtype` getter returns the grad_fn's input metadata, so the same check works when the source is an already-mirrored wrapper. Copying the real value (rather than tracing with "accept any dtype") also keeps code that reads `grad_dtype` while AOTAutograd traces it correct, e.g. a custom op's `setup_context` choosing its GEMM output dtype.
>
> Because the backward graph depends on `grad_dtype`:
> - `TENSOR_MATCH` (C++ `TensorCheck`) checks `grad_dtype` for tensors that require grad. DTensor skips the outer `TENSOR_MATCH`, so it gets an explicit `grad_dtype` guard next to its `requires_grad` guard.
> - The AOTAutograd cache key includes `grad_dtype`, for plain tensors and for subclasses (whose stable hashes don't cover it).
> - Changing `grad_dtype` between forward and backward is checked at runtime as described in the Summary.
> - An existing `.grad` whose dtype differs from the param's no longer graph-breaks when the leaf's `grad_dtype` permits it, and meta conversion sets `grad_dtype` on the fake leaf before attaching the fake `.grad` (the gradient-accumulation case). These two pieces are adapted from #197381.
>
> **Alternative considered:** tracing the joint graph with `grad_dtype=None` on the input wrappers and letting the engine do the only cast at runtime. That matches eager for late `grad_dtype` changes and needs no guards, but code that reads `grad_dtype` during the AOTAutograd trace (custom-op `setup_context`, `allow_in_graph` Functions) then sees `None` and silently picks the narrower dtype.
>
> **Test Plan:**
>
> ```
> python -m pytest -q test/functorch/test_aotdispatch.py -k test_custom_autograd_grad_dtype
> python -m pytest -q test/distributed/tensor/test_dtensor_compile.py -k "test_custom_autograd_grad_dtype or test_aot_cache_key_grad_dtype"
> ```
>
> The DTensor tests call the same compiled callable with bf16 and then fp32 `grad_dtype` (it must recompile and match eager), and check that the DTensor cache key differs per `grad_dtype`. Both fail without the DTensor guard and cache-key fixes. The aotdispatch tests cover the original rounding and the forward/backward `grad_dtype` change.

ghstack-source-id: 4158ae1
Pull-Request: #199856
anijain2305 added a commit that referenced this pull request Oct 6, 2026
Summary (human written only)
----------------------------

grad_dtype is a recent PyTorch feature. This PR adds plumbing for compile.

There was a parallel effort in #197381. Some parts in this PR are borrowed from that PR, but that PR does more than necessary.

This PR raises exception when the `grad_dtype` changes between the compiled forward and backward but only when its narrowing

Under compile, a leaf's grad goes through two casts, while eager applies only one:
>
> ```
> compiled:  formula -> [A: in the graph, to the trace-time grad_dtype] -> [B: autograd engine, to the live grad_dtype] -> .grad
> eager:     formula ----------------------------------------------------> [B: autograd engine, to the live grad_dtype] -> .grad
> ```
>
> Cast A is baked into the traced backward (skipped when the formula already produces the trace-time grad_dtype). Cast B is the engine's normal cast into AccumulateGrad, using the grad_dtype set when backward runs. Compiled matches eager whenever A followed by B gives the same result as B alone, which holds unless A discarded bits that B would have kept. Only a narrowing cast discards bits:
>
> | Formula | Trace-time grad_dtype (cast A) | Live grad_dtype (cast B) | Compiled vs eager |
> |---|---|---|---|
> | fp32 (custom) | fp32 (none) | bf16 (narrow) | same |
> | fp32 (custom) | fp32 (none) | None (none) | same |
> | bf16 (normal mm) | bf16 (none) | fp32 (widen) | same |
> | bf16 (normal mm) | fp32 (widen) | None (none) | same values; fp32 instead of bf16 |
> | fp32 (custom) | bf16 (narrow) | fp32 or None | compiled is bf16-rounded |
>
> Only the last row loses precision: A narrowed fp32 to bf16 in the graph, and B can't restore the bits. So the runtime records the inputs whose traced backward narrows their grad and raises if their grad_dtype differs at backward time.

BC-breaking?
------------

No.

Agent details (if applicable)
-----------------------------
Claude (AI assistant) wrote the following analysis and test summary:

> **Bug:** a bf16 leaf with `grad_dtype=torch.float32` (set by FSDP2 for `reduce_dtype=torch.float32`) keeps a custom backward's fp32 gradient in eager. Under torch.compile the gradient is rounded to bf16: `.grad` is still fp32, but the low bits are gone.
>
> **Root cause:** the autograd engine casts each gradient to the receiving node's `InputMetadata.grad_dtype`, which defaults to the tensor's own dtype. When AOTAutograd traces the joint graph it wraps inputs (FunctionalTensor, and for subclasses a rebuilt subclass plus its functional wrapper) and calls `_mirror_autograd_meta_to`, which copies `requires_grad` but not `grad_dtype`. The wrapper's dummy grad_fn records bf16, so the engine bakes a `_to_copy(..., bfloat16)` into the traced backward.
>
> **Fix:** `copy_grad_dtype_override` copies the effective `grad_dtype` onto each wrapper before it gets a grad_fn, at all three wrapping sites: `FunctionalTensor.to_functional`, the subclass branch of `to_fun`, and `SubclassCreationMeta.creation_fn`. For non-leaves the `grad_dtype` getter returns the grad_fn's input metadata, so the same check works when the source is an already-mirrored wrapper. Copying the real value (rather than tracing with "accept any dtype") also keeps code that reads `grad_dtype` while AOTAutograd traces it correct, e.g. a custom op's `setup_context` choosing its GEMM output dtype.
>
> Because the backward graph depends on `grad_dtype`:
> - `TENSOR_MATCH` (C++ `TensorCheck`) checks `grad_dtype` for tensors that require grad. DTensor skips the outer `TENSOR_MATCH`, so it gets an explicit `grad_dtype` guard next to its `requires_grad` guard.
> - The AOTAutograd cache key includes `grad_dtype`, for plain tensors and for subclasses (whose stable hashes don't cover it).
> - Changing `grad_dtype` between forward and backward is checked at runtime as described in the Summary.
> - An existing `.grad` whose dtype differs from the param's no longer graph-breaks when the leaf's `grad_dtype` permits it, and meta conversion sets `grad_dtype` on the fake leaf before attaching the fake `.grad` (the gradient-accumulation case). These two pieces are adapted from #197381.
>
> **Alternative considered:** tracing the joint graph with `grad_dtype=None` on the input wrappers and letting the engine do the only cast at runtime. That matches eager for late `grad_dtype` changes and needs no guards, but code that reads `grad_dtype` during the AOTAutograd trace (custom-op `setup_context`, `allow_in_graph` Functions) then sees `None` and silently picks the narrower dtype.
>
> **Test Plan:**
>
> ```
> python -m pytest -q test/functorch/test_aotdispatch.py -k test_custom_autograd_grad_dtype
> python -m pytest -q test/distributed/tensor/test_dtensor_compile.py -k "test_custom_autograd_grad_dtype or test_aot_cache_key_grad_dtype"
> ```
>
> The DTensor tests call the same compiled callable with bf16 and then fp32 `grad_dtype` (it must recompile and match eager), and check that the DTensor cache key differs per `grad_dtype`. Both fail without the DTensor guard and cache-key fixes. The aotdispatch tests cover the original rounding and the forward/backward `grad_dtype` change.

ghstack-source-id: 4158ae1
Pull-Request: #199856
anijain2305 added a commit that referenced this pull request Oct 7, 2026
Summary (human written only)
----------------------------

grad_dtype is a recent PyTorch feature. This PR adds plumbing for compile.

There was a parallel effort in #197381. Some parts in this PR are borrowed from that PR, but that PR does more than necessary.

This PR raises exception when the `grad_dtype` changes between the compiled forward and backward but only when its narrowing

Under compile, a leaf's grad goes through two casts, while eager applies only one:
>
> ```
> compiled:  formula -> [A: in the graph, to the trace-time grad_dtype] -> [B: autograd engine, to the live grad_dtype] -> .grad
> eager:     formula ----------------------------------------------------> [B: autograd engine, to the live grad_dtype] -> .grad
> ```
>
> Cast A is baked into the traced backward (skipped when the formula already produces the trace-time grad_dtype). Cast B is the engine's normal cast into AccumulateGrad, using the grad_dtype set when backward runs. Compiled matches eager whenever A followed by B gives the same result as B alone, which holds unless A discarded bits that B would have kept. Only a narrowing cast discards bits:
>
> | Formula | Trace-time grad_dtype (cast A) | Live grad_dtype (cast B) | Compiled vs eager |
> |---|---|---|---|
> | fp32 (custom) | fp32 (none) | bf16 (narrow) | same |
> | fp32 (custom) | fp32 (none) | None (none) | same |
> | bf16 (normal mm) | bf16 (none) | fp32 (widen) | same |
> | bf16 (normal mm) | fp32 (widen) | None (none) | same values; fp32 instead of bf16 |
> | fp32 (custom) | bf16 (narrow) | fp32 or None | compiled is bf16-rounded |
>
> Only the last row loses precision: A narrowed fp32 to bf16 in the graph, and B can't restore the bits. So the runtime records the inputs whose traced backward narrows their grad and raises if their grad_dtype differs at backward time.

BC-breaking?
------------

No.

Agent details (if applicable)
-----------------------------
Claude (AI assistant) wrote the following analysis and test summary:

> **Bug:** a bf16 leaf with `grad_dtype=torch.float32` (set by FSDP2 for `reduce_dtype=torch.float32`) keeps a custom backward's fp32 gradient in eager. Under torch.compile the gradient is rounded to bf16: `.grad` is still fp32, but the low bits are gone.
>
> **Root cause:** the autograd engine casts each gradient to the receiving node's `InputMetadata.grad_dtype`, which defaults to the tensor's own dtype. When AOTAutograd traces the joint graph it wraps inputs (FunctionalTensor, and for subclasses a rebuilt subclass plus its functional wrapper) and calls `_mirror_autograd_meta_to`, which copies `requires_grad` but not `grad_dtype`. The wrapper's dummy grad_fn records bf16, so the engine bakes a `_to_copy(..., bfloat16)` into the traced backward.
>
> **Fix:** `copy_grad_dtype_override` copies the effective `grad_dtype` onto each wrapper before it gets a grad_fn, at all three wrapping sites: `FunctionalTensor.to_functional`, the subclass branch of `to_fun`, and `SubclassCreationMeta.creation_fn`. For non-leaves the `grad_dtype` getter returns the grad_fn's input metadata, so the same check works when the source is an already-mirrored wrapper. Copying the real value (rather than tracing with "accept any dtype") also keeps code that reads `grad_dtype` while AOTAutograd traces it correct, e.g. a custom op's `setup_context` choosing its GEMM output dtype.
>
> Because the backward graph depends on `grad_dtype`:
> - `TENSOR_MATCH` (C++ `TensorCheck`) checks `grad_dtype` for tensors that require grad. DTensor skips the outer `TENSOR_MATCH`, so it gets an explicit `grad_dtype` guard next to its `requires_grad` guard.
> - The AOTAutograd cache key includes `grad_dtype`, for plain tensors and for subclasses (whose stable hashes don't cover it).
> - Changing `grad_dtype` between forward and backward is checked at runtime as described in the Summary.
> - An existing `.grad` whose dtype differs from the param's no longer graph-breaks when the leaf's `grad_dtype` permits it, and meta conversion sets `grad_dtype` on the fake leaf before attaching the fake `.grad` (the gradient-accumulation case). These two pieces are adapted from #197381.
>
> **Alternative considered:** tracing the joint graph with `grad_dtype=None` on the input wrappers and letting the engine do the only cast at runtime. That matches eager for late `grad_dtype` changes and needs no guards, but code that reads `grad_dtype` during the AOTAutograd trace (custom-op `setup_context`, `allow_in_graph` Functions) then sees `None` and silently picks the narrower dtype.
>
> **Test Plan:**
>
> ```
> python -m pytest -q test/functorch/test_aotdispatch.py -k test_custom_autograd_grad_dtype
> python -m pytest -q test/distributed/tensor/test_dtensor_compile.py -k "test_custom_autograd_grad_dtype or test_aot_cache_key_grad_dtype"
> ```
>
> The DTensor tests call the same compiled callable with bf16 and then fp32 `grad_dtype` (it must recompile and match eager), and check that the DTensor cache key differs per `grad_dtype`. Both fail without the DTensor guard and cache-key fixes. The aotdispatch tests cover the original rounding and the forward/backward `grad_dtype` change.

ghstack-source-id: 4158ae1
Pull-Request: #199856
anijain2305 added a commit that referenced this pull request Oct 9, 2026
Summary (human written only)
----------------------------

grad_dtype is a recent PyTorch feature. This PR adds plumbing for compile.

There was a parallel effort in #197381. Some parts in this PR are borrowed from that PR, but that PR does more than necessary.

This PR raises exception when the `grad_dtype` changes between the compiled forward and backward but only when its narrowing

Under compile, a leaf's grad goes through two casts, while eager applies only one:
>
> ```
> compiled:  formula -> [A: in the graph, to the trace-time grad_dtype] -> [B: autograd engine, to the live grad_dtype] -> .grad
> eager:     formula ----------------------------------------------------> [B: autograd engine, to the live grad_dtype] -> .grad
> ```
>
> Cast A is baked into the traced backward (skipped when the formula already produces the trace-time grad_dtype). Cast B is the engine's normal cast into AccumulateGrad, using the grad_dtype set when backward runs. Compiled matches eager whenever A followed by B gives the same result as B alone, which holds unless A discarded bits that B would have kept. Only a narrowing cast discards bits:
>
> | Formula | Trace-time grad_dtype (cast A) | Live grad_dtype (cast B) | Compiled vs eager |
> |---|---|---|---|
> | fp32 (custom) | fp32 (none) | bf16 (narrow) | same |
> | fp32 (custom) | fp32 (none) | None (none) | same |
> | bf16 (normal mm) | bf16 (none) | fp32 (widen) | same |
> | bf16 (normal mm) | fp32 (widen) | None (none) | same values; fp32 instead of bf16 |
> | fp32 (custom) | bf16 (narrow) | fp32 or None | compiled is bf16-rounded |
>
> Only the last row loses precision through the cast: A narrowed fp32 to bf16 in the graph, and B can't restore the bits. A custom backward that reads grad_dtype (e.g. to pick its kernel) also bakes in the trace-time value. So the runtime records the trace-time grad_dtype of each grad-requiring leaf input and raises if it changes before backward. Inputs traced with None are not checked: their grads leave the graph uncast, and the engine applies the grad_dtype set at backward time, as in eager. FSDP2 (#200196) relies on this when an earlier microbatch's post_backward restores grad_dtype under a forward that chose None.

BC-breaking?
------------

No.

Agent details (if applicable)
-----------------------------
Claude (AI assistant) wrote the following analysis and test summary:

> **Bug:** a bf16 leaf with `grad_dtype=torch.float32` (set by FSDP2 for `reduce_dtype=torch.float32`) keeps a custom backward's fp32 gradient in eager. Under torch.compile the gradient is rounded to bf16: `.grad` is still fp32, but the low bits are gone.
>
> **Root cause:** the autograd engine casts each gradient to the receiving node's `InputMetadata.grad_dtype`, which defaults to the tensor's own dtype. When AOTAutograd traces the joint graph it wraps inputs (FunctionalTensor, and for subclasses a rebuilt subclass plus its functional wrapper) and calls `_mirror_autograd_meta_to`, which copies `requires_grad` but not `grad_dtype`. The wrapper's dummy grad_fn records bf16, so the engine bakes a `_to_copy(..., bfloat16)` into the traced backward.
>
> **Fix:** `copy_grad_dtype_override` copies the effective `grad_dtype` onto each wrapper before it gets a grad_fn, at all three wrapping sites: `FunctionalTensor.to_functional`, the subclass branch of `to_fun`, and `SubclassCreationMeta.creation_fn`. For non-leaves the `grad_dtype` getter returns the grad_fn's input metadata, so the same check works when the source is an already-mirrored wrapper. Copying the real value (rather than tracing with "accept any dtype") also keeps code that reads `grad_dtype` while AOTAutograd traces it correct, e.g. a custom op's `setup_context` choosing its GEMM output dtype.
>
> Because the backward graph depends on `grad_dtype`:
> - `TENSOR_MATCH` (C++ `TensorCheck`) checks `grad_dtype` for tensors that require grad. DTensor skips the outer `TENSOR_MATCH`, so it gets an explicit `grad_dtype` guard next to its `requires_grad` guard.
> - The AOTAutograd cache key includes `grad_dtype`, for plain tensors and for subclasses (whose stable hashes don't cover it).
> - Changing `grad_dtype` between forward and backward is checked at runtime as described in the Summary.
> - An existing `.grad` whose dtype differs from the param's no longer graph-breaks when the leaf's `grad_dtype` permits it, and meta conversion sets `grad_dtype` on the fake leaf before attaching the fake `.grad` (the gradient-accumulation case). These two pieces are adapted from #197381.
>
> **Alternative considered:** tracing the joint graph with `grad_dtype=None` on the input wrappers and letting the engine do the only cast at runtime. That matches eager for late `grad_dtype` changes and needs no guards, but code that reads `grad_dtype` during the AOTAutograd trace (custom-op `setup_context`, `allow_in_graph` Functions) then sees `None` and silently picks the narrower dtype.
>
> **Test Plan:**
>
> ```
> python -m pytest -q test/functorch/test_aotdispatch.py -k test_custom_autograd_grad_dtype
> python -m pytest -q test/distributed/tensor/test_dtensor_compile.py -k "test_custom_autograd_grad_dtype or test_aot_cache_key_grad_dtype"
> ```
>
> The DTensor tests call the same compiled callable with bf16 and then fp32 `grad_dtype` (it must recompile and match eager), and check that the DTensor cache key differs per `grad_dtype`. Both fail without the DTensor guard and cache-key fixes. The aotdispatch tests cover the original rounding, `grad_dtype` changes between forward and backward (raising when traced with a concrete dtype, matching eager when traced with None), and a custom backward that picks its kernel by reading `grad_dtype`.

ghstack-source-id: f45d7a1
Pull-Request: #199856

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

Since #197368 was not merged it seems like this needs to be at least rebased?

@xiuhu17

xiuhu17 commented Oct 27, 2026

Copy link
Copy Markdown
Contributor Author

Since #197368 was not merged it seems like this needs to be at least rebased?

Thanks for the reminder! Let me rebase.

@felipemello1

Copy link
Copy Markdown
Contributor

Hi @xiuhu17 , do you plan on still landing this? It would unblock one of my prs in TorchTitan. Thanks for working on it!

A BF16 leaf with grad_dtype=torch.float32 can retain a custom backward's FP32
result in eager execution, but AOTAutograd loses the receiver dtype while
constructing functional tensors and traces a BF16 cast after the FP32 backward
result.

Preserve the leaf's gradient dtype in functional and meta tensor
reconstruction, installing it before attaching existing gradients. Dynamo
accepts existing gradients permitted by the receiver, guards leafness for every
gradient-requiring input, and guards the receiving dtype for leaves; the AOT
cache key also includes the receiver dtype.
@xiuhu17
xiuhu17 force-pushed the xiuhu17/fsdp-compile-grad-dtype branch from 4892d49 to e8619b1 Compare November 3, 2026 21:35
@xiuhu17 xiuhu17 changed the title [Dynamo][stacked] Preserve leaf gradient dtype through compiled backward [Dynamo] Preserve leaf gradient dtype through compiled backward Nov 3, 2026
@xiuhu17

xiuhu17 commented Nov 3, 2026

Copy link
Copy Markdown
Contributor Author

Hi @xiuhu17 , do you plan on still landing this? It would unblock one of my prs in TorchTitan. Thanks for working on it!

Hi, @felipemello1 @aorenste I just rebased!

@weifengpy

Copy link
Copy Markdown
Contributor

@anijain2305 is this PR still related to our previous discussion ? eg letting fsdp2 consistent .grad_dtype to make tracing easier

@aorenste
aorenste dismissed their stale review November 4, 2026 20:44

issues addressed

@pytorch-bot pytorch-bot Bot added the in progress PR is being worked on by the author, until the automated review accepts it label Nov 4, 2026
github-actions[bot]

This comment was marked as outdated.

…grad-meta mirror

The previous revision guarded is_leaf and grad_dtype with per-input Python
CONSTANT_MATCH guards. Those read grad_fn() through the Python getters, which
raises for multi-output views modified in place and replays FunctionalTensor
views outside a mode; they also crashed for ConstantSource tensors, recompiled
a default leaf vs a non-leaf, and gave every requires_grad tensor a GetAttr
accessor, which turns off dict-tag guard skipping for modules with parameters.

The receiving grad_dtype (the leaf's policy, or dtype for a non-leaf) is now a
field of the C++ TensorCheck, read from autograd meta without grad_fn(), so
TENSOR_MATCH and the dict-tag fast path both compare it. DTensor skips
TENSOR_MATCH, so it gets an EQUALS_MATCH on grad_dtype next to its
requires_grad guard. Guard serialization carries a leaf's grad_dtype override
so loaded guards rebuild the same TensorCheck.

grad_dtype is copied in _mirror_autograd_meta_to, before set_history snapshots
it into the Error node. That covers FunctionalTensor and every subclass hop
(e.g. DTensor), so the FunctionalTensor.to_functional change is reverted and the
fake_tensor.py block, which duplicated meta_utils for plain leaves and never ran
for FunctionalTensor inputs, is removed. MetaTensorDesc records only an
assigned override (has_grad_dtype_override, grad_dtype, both defaulted), so
describe_tensor output is unchanged for other tensors. The AOT cache key
includes the receiving grad_dtype for subclass inputs too.

Alternative considered: a single Python grad_dtype guard per input. It still
raises for multi-output views and still disables dict-tag skipping.

The tests move into existing files: test/dynamo/test_grad_dtype.py failed
TEST_LINTER and, using common_utils.run_tests, also ran under dynamo_wrapped,
where compiled autograd's accumulate_grad placeholder ignores grad_dtype (also
the case on main; not addressed here).

Test Plan:
CPU-only aarch64 source build (USE_CUDA=0), Python 3.12:

    python -m pytest test/dynamo/test_autograd_function.py -k grad_dtype
    python -m pytest test/test_fake_tensor.py -k grad_dtype
    python -m pytest test/dynamo/test_aot_autograd_cache.py -k grad_dtype
    python -m pytest test/distributed/tensor/test_dtensor_compile.py -k "grad_dtype or requires_grad_recompile"
    python -m pytest test/dynamo/test_repros.py -k "many_overlapping_inputs or trace_functional_tensor_with"
    python -m pytest test/dynamo/test_dynamic_shapes.py -k "trace_functional_tensor_with or export_with_builtin_op_on_assume_constant or many_overlapping_inputs"
    python -m pytest test/dynamo/test_export.py -k export_with_builtin_op_on_assume_constant
    python -m pytest test/dynamo/test_modules.py -k test_inline_inbuilt_nn_modules
    python -m pytest test/dynamo/test_nested_graph_breaks_wrapped.py -k many_overlapping_inputs

Full files (pytest -n 24): test_autograd_function, test_aot_autograd_cache,
test_fake_tensor, test_structured_trace (with tlparse), test_recompile_ux,
test_guard_manager, test_guard_serialization, test_aot_autograd,
test_subclasses, test_repros, test_modules, test_export,
distributed/tensor/test_dtensor_compile, test_autograd -k grad_dtype,
test_functionalization, functorch/test_aotdispatch: all pass except
test_aotdispatch.py::TestPartitioning::test_disable_functionalization_ignores_effect_token_metadata,
which needs LAPACK (absent in this build).

Lint: `spin quicklint` is clean except CLANGTIDY, which needs a local build
directory and was not run.

Not executed: CUDA tests (test_grad_dtype_fp32_weight_grad_from_mm_out_dtype
is @requires_gpu).

This change was authored with an AI assistant (Claude Code).
@pytorch-bot pytorch-bot Bot added the ciflow/dtensor Run DTensor specific tests label Nov 5, 2026
@xiuhu17

xiuhu17 commented Nov 5, 2026

Copy link
Copy Markdown
Contributor Author

@weifengpy yes, it is related. On main fsdp2 switches the unsharded param grad_dtype between fp32 and None per microbatch, so each compiled region has at most 2 graphs.

Pushed e787fbf for the automated review, now the check is in the C++ TensorCheck and grad_dtype is copied in _mirror_autograd_meta_to, so DTensor and other subclass leaves are covered too (DTensor gets an EQUALS_MATCH).

@anijain2305 #199856 overlaps with this one, would you like to combine them into one pr? I can land this with your runtime check, or port these parts and the tests into #199856, whichever you prefer. Thanks!

@github-actions github-actions Bot 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.

Automated review of e787fbf: changes requested before human review.

The PR keeps a leaf's grad_dtype on FakeTensor and FunctionalTensor inputs so compiled backward no longer rounds an FP32 custom-backward gradient to BF16. It adds grad_dtype to TensorCheck and the AOT cache key, and stops graph-breaking on a .grad whose dtype the leaf's grad_dtype allows. Recommendation: Request Changes. The new DTensor test should fail under the compiled-autograd wrapper, and removing the graph break exposes a clone_input crash.

🔴 2 blocking findings are attached to the code below.

⚪ 8 non-blocking findings

if value.requires_grad:

The DTensor guard follows a different rule than the rest of the PR. The grad_dtype EQUALS_MATCH is gated only on value.requires_grad. For a non-leaf DTensor the Python getter returns the dtype declared in grad_fn's input metadata (python_variable.cpp:2796-2803), while TensorCheck (receiving_grad_dtype, guards.cpp:216) and _receiving_grad_dtype (autograd_cache.py:916) use the tensor's own dtype. The getter goes through grad_fn(), which guards.cpp:214-215 says raises for a multi-output view modified in place (variable.cpp:857-888). At runtime the accessor clears that error and counts a guard failure, but EQUALS_MATCH reads the value when the guard is built (guards.py:3162), so compiling such a DTensor fails outright. Fix: gate the guard on safe_is_leaf(value), or compare the same leaf-or-dtype value TensorCheck uses.


and not (value.is_leaf and value.grad_dtype in (None, grad_value.dtype))

builder.py:3488 uses raw value.is_leaf. The other new Python sites (guards.py:5236, meta_utils.py:310, autograd_cache.py:919) use safe_is_leaf, which catches the RuntimeError from grad_fn(). Here a raise turns the old graph break into a hard error. Import safe_is_leaf alongside safe_grad at line 83 and use it.


// Only a leaf carries a grad_dtype policy; a non-leaf receives its own dtype.

"Only a leaf carries a grad_dtype policy" is false (here and torch/_functorch/_aot_autograd/autograd_cache.py:917-918). ctx.set_output_grad_dtype (autograd/function.py:322, python_function.cpp:891-897) gives a non-leaf output a declared grad dtype, which the engine casts to (engine.cpp:1050-1053). Such a non-leaf passed into a compiled region with an FP32 backward still gets the BF16 cast in the traced backward; the guard and cache key cannot tell it apart from a plain BF16 non-leaf. This predates the PR and is not a regression, but the comments present it as intended and the PR body's follow-up list omits it. Correct the comments and add it to the follow-ups.


ret.grad_dtype = grad_dtype_override[0]

A comment now sits apart from its code. The new if grad_dtype_override: block is inserted between the comment about the pruned .grad/_Missing sentinel and the ret.grad = ... line that comment explains. Move the grad_dtype lines above the comment, and add a short note that grad_dtype must be set before .grad.


The last step of test_grad_dtype_leaf_and_nonleaf cannot fail (lines 2291-2294). If the non-leaf base * 1 wrongly reused the FP32-leaf graph, the engine would cast its FP32 result back to BF16 for MulBackward0; 1 + 2**-8 rounds to 1 in BF16, so base.grad would still equal ones. frame_count stays 2 either way, because the default graph is there to fall back on. The same holds for the base.grad check at line 188. Fix: record guard-failure reasons and assert the FP32 entry rejected the non-leaf, or compile the FP32 leaf first, call with the non-leaf, and assert frame_count == 2.


def test_grad_dtype_override_survives_pickle(self):

The guard-serialization test never checks that a reloaded guard rejects anything (lines 1822-1837). It only reads attributes off the unpickled tensor and never runs a reloaded TENSOR_MATCH against an input with a different grad_dtype; _test_serialization/_test_check_fn, as used by test_tensor_match at line 3464, would cover that. The new subclass branch (guards.py:4884-4885) has no test at all.


def test_different_grad_dtype(self):

No DTensor cache-key coverage. The _stable_hash_for_caching branch (autograd_cache.py:815-826) is only run by existing tests whose DTensors do not require grad, so the new grad_dtype part of the key is never exercised for DTensor. Add a requires-grad DTensor case.


if value.requires_grad:

weifengpy's question to anijain2305 (whether FSDP2 should keep .grad_dtype consistent) has no answer yet. It decides whether FSDP2 runs with gradient accumulation should accept a second graph per compiled region, so it should be settled before landing.

Please address the findings and push; a new commit normally gets a fresh automated review.

Disagree with a finding? Reply with your reasoning, then comment @pytorchbot review to request a re-review. This review is AI-generated and advisory. Each new automated review replaces the previous one. Report a bad review


self.assertEqual(cnt.frame_count, 2)

def test_dtensor_grad_dtype_recompile(self):

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 new DTensor test should fail under compiled autograd. test/inductor/test_compiled_autograd.py:5809-5813 wraps every TestDTensorCompile test when HAS_GPU_AND_TRITON, so this test also runs as TestDTensorCompileWithCompiledAutograd.test_dtensor_grad_dtype_recompile, and ciflow/inductor is on the PR. Under compiled autograd the fake DTensor now carries grad_dtype=float32 (meta_utils.py:2275-2278). accumulate_grad assigns an empty_like BF16 dummy to variable.grad (compiled_autograd.py:911-913), and the .grad setter rejects it. The PR body confirms compiled autograd raises here, and the author validated on CPU only. Existing grad_dtype tests are already xfailed or skipped there (lines 5681, 5786-5792). Fix: add the new test to xfail_by_backend or skipped_tests in test_compiled_autograd.py.

Report this finding

and (grad_value := safe_grad(value)) is not None
and value.dtype != grad_value.dtype
# a leaf's grad_dtype may allow the mismatch (FSDP2 fp32 grads)
and not (value.is_leaf and value.grad_dtype in (None, grad_value.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.

🔴 Removing the graph break exposes a clone_input crash. A BF16 leaf with grad_dtype FP32 or None and an FP32 .grad used to graph-break before becoming a graph input; now it is traced. clone_input (torch/_dynamo/utils.py:2687-2772) clones the tensor without its grad_dtype override, then sets result.grad = clone_input(x.grad) (line 2765), and the .grad setter (python_variable.cpp:2829-2838) raises. The except RuntimeError fallback to torch_clone assigns .grad again at line 2708 outside any try, so the error escapes. Reached when Dynamo clones real inputs: config.verify_correctness (WrapperBackend calls clone_inputs at output_graph.py:405-406; used to fall back to eager, now crashes), the minifier/accuracy repro (clone_inputs_retaining_gradness in debug_utils.py:592, repro/after_dynamo.py, repro/after_aot.py:1446-1522), and export's cache_real_value_when_export. Fix: copy the grad_dtype override in clone_input and clone_tensor before assigning .grad, and add a test.

Report this finding

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/dtensor Run DTensor specific tests ciflow/inductor ciflow/torchtitan Run TorchTitan integration tests in progress PR is being worked on by the author, until the automated review accepts it module: dynamo open source release notes: distributed (fsdp) release notes 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