Skip to content

[aot_autograd] Preserve leaf grad_dtype through the compiled backward - #199856

Open
anijain2305 wants to merge 6 commits into
gh/anijain2305/1348/basefrom
gh/anijain2305/1348/head
Open

anijain2305 wants to merge 6 commits into
gh/anijain2305/1348/basefrom
gh/anijain2305/1348/head

Conversation

@anijain2305

@anijain2305 anijain2305 commented Oct 6, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

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 [Dynamo] Preserve leaf gradient dtype through compiled backward #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.

cc @voznesenskym @penguinwu @EikanWang @jgong5 @Guobing-Chen @XiaobingSuper @zhuhaozhe @blzheng @wenzhe-nrv @jiayisunx @kadeng @chauhang @amjames @jataylo @azahed98

[ghstack-poisoned]
@pytorch-bot

pytorch-bot Bot commented Oct 6, 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 makes torch.compile honor a leaf's grad_dtype across guards,
fake/functional tensor conversion, AOTAutograd tracing/runtime, and the AOT
cache key; the core logic and most tests look sound. However, soulitzer's inline
comment on meta_utils (preserving the 'follows dtype' vs 'explicitly pinned'
distinction via _has_grad_dtype_override) has neither a code change nor an
author reply, and the builder.py graph-break relaxation has no test.

Findings (3):

[major] torch/_subclasses/meta_utils.py:434
Unaddressed: soulitzer noted this loses the 'follows tensor dtype' vs
'explicitly pinned' distinction and suggested _has_grad_dtype_override. HEAD
still records the effective dtype, and line 2265 sets r.grad_dtype
unconditionally, so every fake requires-grad leaf gets pinned (the C++ setter
always records an override), unlike the real tensor. Either guard on
t._has_grad_dtype_override (or grad_dtype != dtype, as copy_grad_dtype_override
does) or reply explaining why it doesn't matter.

[minor] torch/_dynamo/variables/builder.py:3163
Untested behavior change: a bf16 leaf with an existing fp32 .grad and
grad_dtype=fp32/None no longer graph-breaks. No test calls a compiled fn twice
on the same param (with .grad populated) under fullgraph=True.

[minor] torch/_functorch/_aot_autograd/autograd_cache.py:895
Only the DTensor _stable_hash_for_caching path of the cache-key change is
tested; this plain-tensor path and the subclass fallback without
_stable_hash_for_caching (line 807) have no test showing grad_dtype changes the
key.

Reviewed commit: 502a5a4

Review run

🔗 Helpful Links

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

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 502a5a4 with merge base b273e98 (image):

BROKEN TRUNK - The following job failed but were present on the merge base:

👉 Rebase onto the `viable/strict` branch to avoid these failures

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

@pytorch-bot pytorch-bot Bot added ciflow/dtensor Run DTensor specific tests ciflow/inductor ciflow/torchtitan Run TorchTitan integration tests module: dynamo labels Oct 6, 2026
@pytorch-bot

pytorch-bot Bot commented Oct 6, 2026

Copy link
Copy Markdown

This PR needs a release notes: label

If your changes are user facing and intended to be a part of release notes, please use a label starting with release notes:.

If not, please add the topic: not user facing label.

To add a label, you can comment to pytorchbot, for example
@pytorchbot label "topic: not user facing"

For more information, see
https://github.com/pytorch/pytorch/wiki/PyTorch-AutoLabel-Bot#why-categorize-for-release-notes-and-how-does-it-work.

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
[ghstack-poisoned]
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
anijain2305 marked this pull request as ready for review October 6, 2026 00:16
@anijain2305
anijain2305 marked this pull request as draft October 6, 2026 00:16
[ghstack-poisoned]
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
anijain2305 marked this pull request as ready for review October 6, 2026 03:20
is_inference=False if is_inference_mode_disabled else t.is_inference(),
is_leaf=is_leaf,
requires_grad=t.requires_grad,
grad_dtype=t.grad_dtype if t.requires_grad and is_leaf else t.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.

We can lose the distinction between "follows tensors dtype" and "explicitly pinned to dtype" here. We can probably use _has_grad_dtype_override to preserve that, but I'm not sure if this matters since I'm not sure how the dtype of a tensor can change in-place (in compile).


def weight_grad(fn):
weight = torch.nn.Parameter(torch.ones(1, 1, dtype=torch.bfloat16))
weight.grad_dtype = grad_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.

Should we explicitly ban the case where the grad_dtype is being set inside the compiled forward? (or if we care about supporting it, let's add a test for it)

@soulitzer soulitzer Oct 6, 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.

Oh dynamo rejects the case where its inside the compiled forward, but it could happen after forward but before backward

@soulitzer

soulitzer commented Oct 6, 2026 •

Copy link
Copy Markdown
Contributor

From sol:

The new `grad_dtype` check lives in `TENSOR_MATCH`, but `VariableBuilder.wrap_tensor`
deliberately skips the outer `TENSOR_MATCH` when `is_dtensor` is true. The DTensor-specific
path only guards its type, `_spec`, and `requires_grad`, then recursively guards
`_local_tensor`; neither the flattening context nor those guards include the outer leaf
`grad_dtype`. Because the outer DTensor and `_local_tensor` have separate autograd metadata,
changing the outer policy can reuse a compiled backward specialized for the prior casting
behavior. Could we add an explicit outer `grad_dtype` guard next to the existing
`requires_grad` guard and a two-call regression using the same compiled callable with
different policies?

@soulitzer

Copy link
Copy Markdown
Contributor

You might also want to double check whether AOTAutograd cache key computation is handling the subclass case properly

[ghstack-poisoned]
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

anijain2305 commented Oct 6, 2026 •

Copy link
Copy Markdown
Contributor Author

Update - The following comment under the dashes is no longer valid. We found that with allow_in_Graph and custom ops, setting the grad_dtype to None during aot autograd tracing could be wrong. So we are going back to the old case.


Thanks @soulitzer

I have redesigned it after your comments. The main direction is

  • Compile traces the graph with grad_dtype=None
  • The casts happen in "eager" autograd engine outside the CompileFunction of compile

We can wait for the CI to review, but let me know if this direction is ok.

[ghstack-poisoned]
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
@ezyang
ezyang removed their request for review October 7, 2026 14:43
@ezyang

ezyang commented Oct 7, 2026

Copy link
Copy Markdown
Contributor

deferring to @soulitzer

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
weifengpy added a commit that referenced this pull request Oct 7, 2026
> Authored with Claude Code.
>
> #198668 defers gradient upcasts by setting each deferring unsharded parameter's grad_dtype to None in pre_backward, and post_backward restores the unsharded gradient dtype. torch.compile traces a region's backward during its forward, when the parameter still has the restored dtype. With #199856, the compiled backward follows the leaf's grad_dtype as of that trace, so it casts every gradient to FP32 and compiled regions lose the deferral. #199856 also has to decide which grad_dtype changes between a compiled forward and its backward are safe: it checks only parameters whose gradient the traced backward narrowed, found by matching cast nodes in the graph.
>
> This change sets grad_dtype=None once, when the unsharded parameter is created, for parameters that defer, and never changes it. FSDPParam.defers_grad_upcast holds the predicate that _fsdp_params_with_wider_grad_dtype used. pre_backward no longer sets grad_dtype, and post_backward and reset_iter_state() no longer restore it. post_backward still widens a deferred gradient that the backward doesn't reduce, now in _upcast_unreduced_grads, so accumulation across backwards without gradient sync stays in FP32. grad_dtype then can't change between a forward and its backward, including when one microbatch's backward runs after another's post_backward, as in a pipeline schedule's cooldown, where restoring in post_backward would change it. #199856 can then require that grad_dtype not change between a compiled forward and its backward, and compiled regions keep the deferral.
>
> Differences from #198668: a parameter's first gradient in a backward without gradient sync, which #198668 has autograd cast, is now cast in post_backward. BF16 to FP32 is exact, so parameters used once per backward get bit-identical gradients. A parameter used more than once in that backward now sums its contributions in BF16 before post_backward widens the total, as #198668 already does in every other backward. Whether to defer no longer depends on reduce_grads or on an existing gradient at pre_backward, so disabling gradient sync between forward and backward needs no special handling. Parameters whose gradient may be reduced outside DP, e.g. the TP all-reduce of a SequenceParallel norm weight's Partial gradient, keep their FP32 grad_dtype, so that reduction stays in FP32. Compiled autograd, which captures gradient metadata before pre_backward and so kept the FP32 cast, now defers too. Between backwards, the unsharded parameter's grad_dtype reads None instead of the unsharded gradient dtype.
>
> Test Plan
>
> test_grad_dtype_accumulation_skips_upcast now expects BF16 for all three gradients AccumulateGrad receives over two backwards without gradient sync and one that reduces, with grad_dtype None after each, and still checks that 256 + 1 - 256 accumulates to 1. test_grad_dtype_upcasts_unreduced_grad, renamed from test_grad_dtype_restored_after_deferred_upcast, checks that a gradient deferred in a backward that disables gradient sync partway ends up FP32 with grad_dtype None, and that grad_dtype stays None through an aborted backward and reset_iter_state(). The new test_grad_dtype_fixed_across_interleaved_microbatches runs two forwards and then their backwards, the first without gradient sync, and checks that grad_dtype is None during both backwards and that the gradient is correct.
>
> On B200s, with this revision's Python on a PyTorch build from a few days earlier, test_fully_shard_mixed_precision.py passes on two GPUs (27 tests in 29 s) and on four (80 s), as do the training (59 passed, 5 skipped), dtensor, memory and spmd_types files. test_fully_shard_comm.py passes except test_fully_shard_alloc_from_pg, which also fails on the base. Against the base's sources, the three changed tests fail. Lint passes.
>
> ```bash
> PY=/home/weif/.conda/envs/code-review/bin/python
> T=test/distributed/_composable/fsdp
> for f in mixed_precision training comm dtensor; do CUDA_VISIBLE_DEVICES=0,1 $PY -m pytest $T/test_fully_shard_$f.py -q -rfs; done
> for f in mixed_precision memory spmd_types; do CUDA_VISIBLE_DEVICES=4,5,6,7 $PY -m pytest $T/test_fully_shard_$f.py -q -rfs; done
> PATH=/home/weif/.conda/envs/code-review/bin:$PATH lintrunner -a $(git diff HEAD~1 --name-only --diff-filter=d)
> git diff HEAD~1 --check
> ```

ghstack-source-id: a5a3242
Pull-Request: #200196
weifengpy added a commit that referenced this pull request Oct 7, 2026
> Authored with Claude Code.
>
> #198668 defers gradient upcasts by setting each deferring unsharded parameter's grad_dtype to None in pre_backward, and post_backward restores the unsharded gradient dtype. torch.compile traces a region's backward during its forward, when the parameter still has the restored dtype. With #199856, the compiled backward follows the leaf's grad_dtype as of that trace, so it casts every gradient to FP32 and compiled regions lose the deferral. #199856 also has to decide which grad_dtype changes between a compiled forward and its backward are safe: it checks only parameters whose gradient the traced backward narrowed, found by matching cast nodes in the graph.
>
> This change sets grad_dtype=None once, when the unsharded parameter is created, for parameters that defer, and never changes it. FSDPParam.defers_grad_upcast holds the predicate that _fsdp_params_with_wider_grad_dtype used. pre_backward no longer sets grad_dtype, and post_backward and reset_iter_state() no longer restore it. post_backward still widens a deferred gradient that the backward doesn't reduce, now in _upcast_unreduced_grads, so accumulation across backwards without gradient sync stays in FP32. grad_dtype then can't change between a forward and its backward, including when one microbatch's backward runs after another's post_backward, as in a pipeline schedule's cooldown, where restoring in post_backward would change it. #199856 can then require that grad_dtype not change between a compiled forward and its backward, and compiled regions keep the deferral.
>
> Differences from #198668: a parameter's first gradient in a backward without gradient sync, which #198668 has autograd cast, is now cast in post_backward. BF16 to FP32 is exact, so parameters used once per backward get bit-identical gradients. A parameter used more than once in that backward now sums its contributions in BF16 before post_backward widens the total, as #198668 already does in every other backward. Whether to defer no longer depends on reduce_grads or on an existing gradient at pre_backward, so disabling gradient sync between forward and backward needs no special handling. Parameters whose gradient may be reduced outside DP, e.g. the TP all-reduce of a SequenceParallel norm weight's Partial gradient, keep their FP32 grad_dtype, so that reduction stays in FP32. Compiled autograd, which captures gradient metadata before pre_backward and so kept the FP32 cast, now defers too. Between backwards, the unsharded parameter's grad_dtype reads None instead of the unsharded gradient dtype.
>
> Test Plan
>
> test_grad_dtype_accumulation_skips_upcast now expects BF16 for all three gradients AccumulateGrad receives over two backwards without gradient sync and one that reduces, with grad_dtype None after each, and still checks that 256 + 1 - 256 accumulates to 1. test_grad_dtype_upcasts_unreduced_grad, renamed from test_grad_dtype_restored_after_deferred_upcast, checks that a gradient deferred in a backward that disables gradient sync partway ends up FP32 with grad_dtype None, and that grad_dtype stays None through an aborted backward and reset_iter_state(). The new test_grad_dtype_fixed_across_interleaved_microbatches runs two forwards and then their backwards, the first without gradient sync, and checks that grad_dtype is None during both backwards and that the gradient is correct.
>
> On B200s, with PyTorch built at this change's base (2eb7361), test_fully_shard_mixed_precision.py passes on two GPUs (27 tests in 37 s) and on four (65 s), as do the training (59 passed, 5 skipped), dtensor, memory and spmd_types files. test_fully_shard_comm.py passes except test_fully_shard_alloc_from_pg, which also fails on the base. Against the base's sources, the three changed tests fail. Lint passes.
>
> ```bash
> PY=/home/weif/.conda/envs/code-review/bin/python
> T=test/distributed/_composable/fsdp
> for f in mixed_precision training comm dtensor; do CUDA_VISIBLE_DEVICES=0,1 $PY -m pytest $T/test_fully_shard_$f.py -q -rfs; done
> for f in mixed_precision memory spmd_types; do CUDA_VISIBLE_DEVICES=4,5,6,7 $PY -m pytest $T/test_fully_shard_$f.py -q -rfs; done
> PATH=/home/weif/.conda/envs/code-review/bin:$PATH lintrunner -a $(git diff HEAD~1 --name-only --diff-filter=d)
> git diff HEAD~1 --check
> ```

ghstack-source-id: a5a3242
Pull-Request: #200196
weifengpy added a commit that referenced this pull request Oct 7, 2026
> Authored with Claude Code.
>
> #198668 defers gradient upcasts by setting each deferring unsharded parameter's grad_dtype to None in pre_backward, and post_backward restores the unsharded gradient dtype. torch.compile traces a region's backward during its forward, when the parameter still has the restored dtype. With #199856, the compiled backward follows the leaf's grad_dtype as of that trace, so it casts every gradient to FP32 and compiled regions lose the deferral. #199856 also has to decide which grad_dtype changes between a compiled forward and its backward are safe: it checks only parameters whose gradient the traced backward narrowed, found by matching cast nodes in the graph.
>
> This change sets grad_dtype=None once, when the unsharded parameter is created, for parameters that defer, and never changes it. FSDPParam.defers_grad_upcast holds the predicate that _fsdp_params_with_wider_grad_dtype used. pre_backward no longer sets grad_dtype, and post_backward and reset_iter_state() no longer restore it. post_backward still widens a deferred gradient that the backward doesn't reduce, now in _upcast_unreduced_grads, so accumulation across backwards without gradient sync stays in FP32. grad_dtype then can't change between a forward and its backward, including when one microbatch's backward runs after another's post_backward, as in a pipeline schedule's cooldown, where restoring in post_backward would change it. #199856 can then require that grad_dtype not change between a compiled forward and its backward, and compiled regions keep the deferral.
>
> Differences from #198668: a parameter's first gradient in a backward without gradient sync, which #198668 has autograd cast, is now cast in post_backward. BF16 to FP32 is exact, so parameters used once per backward get bit-identical gradients. A parameter used more than once in that backward now sums its contributions in BF16 before post_backward widens the total, as #198668 already does in every other backward. Whether to defer no longer depends on reduce_grads or on an existing gradient at pre_backward, so disabling gradient sync between forward and backward needs no special handling. Parameters whose gradient may be reduced outside DP, e.g. the TP all-reduce of a SequenceParallel norm weight's Partial gradient, keep their FP32 grad_dtype, so that reduction stays in FP32. Compiled autograd, which captures gradient metadata before pre_backward and so kept the FP32 cast, now defers too. Between backwards, the unsharded parameter's grad_dtype reads None instead of the unsharded gradient dtype.
>
> Test Plan
>
> test_grad_dtype_accumulation_skips_upcast now expects BF16 for all three gradients AccumulateGrad receives over two backwards without gradient sync and one that reduces, with grad_dtype None after each, and still checks that 256 + 1 - 256 accumulates to 1. test_grad_dtype_upcasts_unreduced_grad, renamed from test_grad_dtype_restored_after_deferred_upcast, checks that a gradient deferred in a backward that disables gradient sync partway ends up FP32 with grad_dtype None, and that grad_dtype stays None through an aborted backward and reset_iter_state(). The new test_grad_dtype_fixed_across_interleaved_microbatches runs two forwards and then their backwards, the first without gradient sync, and checks that grad_dtype is None during both backwards and that the gradient is correct.
>
> On B200s, with PyTorch built at this change's base (2eb7361), test_fully_shard_mixed_precision.py passes on two GPUs (27 tests in 37 s) and on four (65 s), as do the training (59 passed, 5 skipped), dtensor, memory and spmd_types files. test_fully_shard_comm.py passes except test_fully_shard_alloc_from_pg, which also fails on the base. Against the base's sources, the three changed tests fail. Lint passes.
>
> ```bash
> PY=/home/weif/.conda/envs/code-review/bin/python
> T=test/distributed/_composable/fsdp
> for f in mixed_precision training comm dtensor; do CUDA_VISIBLE_DEVICES=0,1 $PY -m pytest $T/test_fully_shard_$f.py -q -rfs; done
> for f in mixed_precision memory spmd_types; do CUDA_VISIBLE_DEVICES=4,5,6,7 $PY -m pytest $T/test_fully_shard_$f.py -q -rfs; done
> PATH=/home/weif/.conda/envs/code-review/bin:$PATH lintrunner -a $(git diff HEAD~1 --name-only --diff-filter=d)
> git diff HEAD~1 --check
> ```

ghstack-source-id: a5a3242
Pull-Request: #200196
weifengpy added a commit that referenced this pull request Oct 7, 2026
> Authored with Claude Code.
>
> #198668 defers gradient upcasts by setting each deferring unsharded parameter's grad_dtype to None in pre_backward, and post_backward restores the unsharded gradient dtype. torch.compile traces a region's backward during its forward, when the parameter still has the restored dtype. With #199856, the compiled backward follows the leaf's grad_dtype as of that trace, so it casts every gradient to FP32 and compiled regions lose the deferral. #199856 also has to decide which grad_dtype changes between a compiled forward and its backward are safe: it checks only parameters whose gradient the traced backward narrowed, found by matching cast nodes in the graph.
>
> This change sets grad_dtype=None once, when the unsharded parameter is created, for parameters that defer, and never changes it. FSDPParam.defers_grad_upcast holds the predicate that _fsdp_params_with_wider_grad_dtype used. pre_backward no longer sets grad_dtype, and post_backward and reset_iter_state() no longer restore it. post_backward still widens a deferred gradient that the backward doesn't reduce, now in _upcast_unreduced_grads, so accumulation across backwards without gradient sync stays in FP32. grad_dtype then can't change between a forward and its backward, including when one microbatch's backward runs after another's post_backward, as in a pipeline schedule's cooldown, where restoring in post_backward would change it. #199856 can then require that grad_dtype not change between a compiled forward and its backward, and compiled regions keep the deferral.
>
> Differences from #198668: a parameter's first gradient in a backward without gradient sync, which #198668 has autograd cast, is now cast in post_backward. BF16 to FP32 is exact, so parameters used once per backward get bit-identical gradients. A parameter used more than once in that backward now sums its contributions in BF16 before post_backward widens the total, as #198668 already does in every other backward. Whether to defer no longer depends on reduce_grads or on an existing gradient at pre_backward, so disabling gradient sync between forward and backward needs no special handling. Parameters whose gradient may be reduced outside DP, e.g. the TP all-reduce of a SequenceParallel norm weight's Partial gradient, keep their FP32 grad_dtype, so that reduction stays in FP32. Compiled autograd, which captures gradient metadata before pre_backward and so kept the FP32 cast, now defers too. Between backwards, the unsharded parameter's grad_dtype reads None instead of the unsharded gradient dtype.
>
> Test Plan
>
> test_grad_dtype_accumulation_skips_upcast now expects BF16 for all three gradients AccumulateGrad receives over two backwards without gradient sync and one that reduces, with grad_dtype None after each, and still checks that 256 + 1 - 256 accumulates to 1. test_grad_dtype_upcasts_unreduced_grad, renamed from test_grad_dtype_restored_after_deferred_upcast, checks that a gradient deferred in a backward that disables gradient sync partway ends up FP32 with grad_dtype None, and that grad_dtype stays None through an aborted backward and reset_iter_state(). The new test_grad_dtype_fixed_across_interleaved_microbatches runs two forwards and then their backwards, the first without gradient sync, and checks that grad_dtype is None during both backwards and that the gradient is correct.
>
> On B200s, with PyTorch built at this change's base (2eb7361), test_fully_shard_mixed_precision.py passes on two GPUs (27 tests in 37 s) and on four (65 s), as do the training (59 passed, 5 skipped), dtensor, memory and spmd_types files. test_fully_shard_comm.py passes except test_fully_shard_alloc_from_pg, which also fails on the base. Against the base's sources, the three changed tests fail. Lint passes.
>
> Benchmarks ran on two B200s with one build of the base, the base's runs loading its _fsdp_param.py and _fsdp_param_group.py, with FP32 parameters, param_dtype=torch.bfloat16 and reduce_dtype=torch.float32. Each step runs two backwards without gradient sync, then one that reduces; times are the wall time of loss.backward(), the median of 30 steps after 5 warmup steps. For 3000 parameters from 1500 Linear(256, 256) in 30 groups, the first backward, where the upcast moves from autograd to post_backward, takes 6.7 ms less than in the base (median over six alternating runs; per-run differences from +1.1 to -19.7 ms, out of about 160-195 ms). The second and the final backward, which defer in both, differ by -2.8 and +0.8 ms, within the runs' noise of about 15 ms. For 8 Linear(2048, 2048) layers in one group, the two backwards without gradient sync take 1.07-1.16 ms versus 1.32-1.51 ms in the base, over two runs each, and the one that reduces 3.19-3.20 ms versus 3.18 ms. Peak memory above each backward's start is unchanged, except in the first backward for the 3000 parameters: 385.1 MiB versus 391.2 MiB, since fresh gradients stay BF16 until post_backward.
>
> ```bash
> PY=/home/weif/.conda/envs/code-review/bin/python
> T=test/distributed/_composable/fsdp
> for f in mixed_precision training comm dtensor; do CUDA_VISIBLE_DEVICES=0,1 $PY -m pytest $T/test_fully_shard_$f.py -q -rfs; done
> for f in mixed_precision memory spmd_types; do CUDA_VISIBLE_DEVICES=4,5,6,7 $PY -m pytest $T/test_fully_shard_$f.py -q -rfs; done
> PATH=/home/weif/.conda/envs/code-review/bin:$PATH lintrunner -a $(git diff HEAD~1 --name-only --diff-filter=d)
> git diff HEAD~1 --check
> ```

ghstack-source-id: a5a3242
Pull-Request: #200196
weifengpy added a commit that referenced this pull request Oct 8, 2026
sets grad_dtype=None once, when the unsharded parameter is created
* accumulation across backwards without gradient sync stays in FP32
* TP grad reduction stays in FP32

the numeric change is multi-use param in autograd are accumualted in bf16, which trunk already does for 1D with reduce-scatter

this simplifies #199856

ghstack-source-id: e22d589
Pull-Request: #200196
weifengpy added a commit that referenced this pull request Oct 8, 2026
sets grad_dtype=None once, when the unsharded parameter is created
* accumulation across backwards without gradient sync stays in FP32
* TP grad reduction stays in FP32

the numeric change is multi-use param in autograd are accumualted in bf16, which trunk already does for 1D with reduce-scatter

this simplifies #199856

ghstack-source-id: b7be99a
Pull-Request: #200196
weifengpy added a commit that referenced this pull request Oct 8, 2026
* accumulation across backwards without gradient sync stays in FP32
* TP grad reduction stays in FP32

> Authored with Claude Code.
>
> #198668 defers gradient upcasts by setting an unsharded parameter's grad_dtype to None when the backward reduces or the parameter already holds a gradient, so autograd doesn't cast every BF16 gradient to FP32. It chooses in pre_backward, so a forward sees FP32 while its backward runs with None. On trunk a compiled backward doesn't depend on grad_dtype: it casts leaf gradients to the parameter's dtype, and the autograd engine then applies the grad_dtype set when the backward runs. #199856 makes the compiled backward cast to the grad_dtype seen while tracing the forward, and guards on it. With the pre_backward choice, every compiled backward would then cast its BF16 weight gradients to FP32 inside the graph (the fourth row of #199856's table), undoing #198668 under compile. This PR is the FSDP-side prerequisite for #199856.
>
> The choice moves to pre_forward, after the unshard, and holds until post_backward, so a forward and its backward see the same grad_dtype. The rule is unchanged: None if the group reduces gradients or the parameter already holds a gradient, else the unsharded gradient dtype. It is now set either way rather than only to None, so a choice from an earlier forward can't carry over. post_backward and reset_iter_state() restore the unsharded gradient dtype and widen a deferred gradient that wasn't reduced, as on trunk; after a backward that reduces, this restore is what returns grad_dtype to FP32. No-grad forwards skip the choice, since no backward would restore it, and so does recomputation under activation checkpointing, so a backward keeps its forward's choice. The predicate moves to FSDPParam.defers_grad_upcast, and the group's list is renamed after it.
>
> Outside a forward and its backward, grad_dtype is the unsharded gradient dtype, as on trunk, so gradients deposited without FSDP's hooks still accumulate in FP32. That covers a zero-bubble schedule's weight passes, which run after their input pass's post_backward and assign or add dW themselves in stage_backward_weight, and gradients computed from unsharded parameters without calling their module. The previous revision of this PR set grad_dtype=None for the parameter's lifetime instead, and consecutive weight passes, e.g. on ScheduleInterleavedZeroBubble's last rank, then accumulated in BF16. A fixed FP32 grad_dtype would also keep forward and backward consistent, but gives up the deferral.
>
> Differences from trunk: in a backward whose forward chose None, a parameter used more than once sums its contributions in BF16 before the copy-in or AccumulateGrad widens the total. Trunk already does this in a backward that reduces, and parameters used once per backward get bit-identical gradients. It now also happens for pipeline microbatches forwarded before the step's first backward disables gradient sync, and in the synced backward of a group like fully_shard([norm, head]) used for a chunked loss, whose pre_backward trunk ran only after the per-chunk contributions had been cast. Code that reads grad_dtype during forward, such as torchtitan's MXFP8 linear, sees None in a forward that defers and produces BF16 weight gradients there instead of FP32. Once #199856 lands, a compiled module whose forward runs both with FP32 (a first microbatch without gradient sync) and with None will compile once for each, since #199856 guards on grad_dtype. FSDP only sets None or the wider dtype, so #199856's narrowing check can't fire, even when a later post_backward restores FP32 before an earlier-traced backward runs.
>
> The choice is the same loop over the group's parameters that trunk ran in pre_backward. For 3000 four-element parameters in one group on CPU, it takes 0.6 ms with gradient sync and 0.9 ms without, versus 0.9 and 0.7 ms for trunk's loop; the post_backward restore is unchanged at 0.9 ms. On a B200, the 3000 BF16-to-FP32 cast kernels the deferral avoids take 17.6 ms.
>
> Test Plan
>
> test_grad_dtype_chosen_in_forward checks that a backward sees its forward's grad_dtype when gradient sync changes in between, and that grad_dtype and the gradient are FP32 afterwards. test_grad_dtype_zero_bubble_weight_passes runs four input passes and then four weight passes over residual blocks, as on a zero-bubble schedule's last stage, and checks that the gradient is FP32 after each weight pass and equals FP32 accumulation. test_grad_dtype_outside_forward_and_backward checks that after a no-grad forward, gradients from the unsharded weight accumulate 256 + 1 to 257. All three fail on the previous revision of this PR; the zero-bubble test fails at its dtype check after the first weight pass (bfloat16 != float32). test_grad_dtype_accumulation_skips_upcast and test_grad_dtype_restored_after_deferred_upcast keep trunk's expectations.
>
> On B200 GPUs, the mixed precision file (29 tests), the training and compile selections (3 and 7) and the pipeline-with-FSDP mixed precision cases, including the zero-bubble schedules (8), pass on the previous local revision, which differs from this one only in the list's name and two comments. At this revision lint passes, and a single-rank CPU (gloo) run of the zero-bubble, chunked-loss, interleaved-microbatch and multi-use scenarios gives the results described above.
>
> ```bash
> PY=/home/weif/.conda/envs/code-review/bin/python
> $PY test/distributed/_composable/fsdp/test_fully_shard_mixed_precision.py
> $PY -m pytest -q -p no:cacheprovider test/distributed/_composable/fsdp/test_fully_shard_training.py -k "grad_dtype or mixed_precision"
> $PY -m pytest -q -p no:cacheprovider test/distributed/_composable/fsdp/test_fully_shard_compile.py -k "mixed_precision or mp"
> $PY -m pytest -q -p no:cacheprovider test/distributed/test_composability.py -k "test_pp_fsdp and FSDP_MP"
> PATH=/home/weif/.conda/envs/code-review/bin:$PATH lintrunner -a $(git diff HEAD~1 --name-only --diff-filter=d)
> ```

ghstack-source-id: 231c3e8
Pull-Request: #200196
weifengpy added a commit that referenced this pull request Oct 8, 2026
* accumulation across backwards without gradient sync stays in FP32
* TP grad reduction stays in FP32

> Authored with Claude Code.
>
> #198668 defers gradient upcasts by setting an unsharded parameter's grad_dtype to None when the backward reduces or the parameter already holds a gradient, so autograd doesn't cast every BF16 gradient to FP32. It chooses in pre_backward, so a forward sees FP32 while its backward runs with None. On trunk a compiled backward doesn't depend on grad_dtype: it casts leaf gradients to the parameter's dtype, and the autograd engine then applies the grad_dtype set when the backward runs. #199856 makes the compiled backward cast to the grad_dtype seen while tracing the forward, and guards on it. With the pre_backward choice, every compiled backward would then cast its BF16 weight gradients to FP32 inside the graph (the fourth row of #199856's table), undoing #198668 under compile. This PR is the FSDP-side prerequisite for #199856.
>
> The choice moves to pre_forward, after the unshard, and holds until post_backward, so a forward and its backward see the same grad_dtype. The rule is unchanged: None if the group reduces gradients or the parameter already holds a gradient, else the unsharded gradient dtype. It is now set either way rather than only to None, so a choice from an earlier forward can't carry over. post_backward and reset_iter_state() restore the unsharded gradient dtype and widen a deferred gradient that wasn't reduced, as on trunk; after a backward that reduces, this restore is what returns grad_dtype to FP32. No-grad forwards skip the choice, since no backward would restore it, and so does recomputation under activation checkpointing, so a backward keeps its forward's choice. The predicate moves to FSDPParam.defers_grad_upcast, and the group's list is renamed after it. Parameters whose sharded tensor implements FSDP's all-gather extension (fsdp_pre_all_gather) never defer: an extension runs its own compute, which may read grad_dtype to pick the dtype its backward produces, so grad_dtype stays the unsharded gradient dtype for them. torchtitan's MXFP8 linear reads it in forward and writes its weight gradient in that dtype; under the pre_forward choice alone it would see None and write BF16.
>
> Outside a forward and its backward, grad_dtype is the unsharded gradient dtype, as on trunk, so gradients deposited without FSDP's hooks still accumulate in FP32. That covers a zero-bubble schedule's weight passes, which run after their input pass's post_backward and assign or add dW themselves in stage_backward_weight, and gradients computed from unsharded parameters without calling their module. The previous revision of this PR set grad_dtype=None for the parameter's lifetime instead, and consecutive weight passes, e.g. on ScheduleInterleavedZeroBubble's last rank, then accumulated in BF16. A fixed FP32 grad_dtype would also keep forward and backward consistent, but gives up the deferral.
>
> Differences from trunk: in a backward whose forward chose None, a parameter used more than once sums its contributions in BF16 before the copy-in or AccumulateGrad widens the total. Trunk already does this in a backward that reduces, and parameters used once per backward get bit-identical gradients. It now also happens for pipeline microbatches forwarded before the step's first backward disables gradient sync, and in the synced backward of a group like fully_shard([norm, head]) used for a chunked loss, whose pre_backward trunk ran only after the per-chunk contributions had been cast. Extension-backed parameters no longer defer. For one whose backward writes grad_dtype, such as torchtitan's MXFP8 linear, nothing changes. One that hard-codes a BF16 weight gradient, such as torchtitan's NVFP4 linear, now gets autograd's per-parameter cast to FP32 and holds the FP32 gradient until the copy-in; pytorch/torchtitan#5180 makes NVFP4 write its weight gradient in grad_dtype, which removes the cast. Other code that reads grad_dtype during forward sees None in a forward that defers. Once #199856 lands, a compiled module whose forward runs both with FP32 (a first microbatch without gradient sync) and with None will compile once for each, since #199856 guards on grad_dtype. Extension-backed parameters keep a fixed grad_dtype, so they add no recompiles. FSDP only sets None or the wider dtype, so #199856's narrowing check can't fire, even when a later post_backward restores FP32 before an earlier-traced backward runs.
>
> The choice is the same loop over the group's parameters that trunk ran in pre_backward. For 3000 four-element parameters in one group on CPU, it takes 0.6 ms with gradient sync and 0.9 ms without, versus 0.9 and 0.7 ms for trunk's loop; the post_backward restore is unchanged at 0.9 ms. On a B200, the 3000 BF16-to-FP32 cast kernels the deferral avoids take 17.6 ms.
>
> Test Plan
>
> test_grad_dtype_chosen_in_forward checks that a backward sees its forward's grad_dtype when gradient sync changes in between, and that grad_dtype and the gradient are FP32 afterwards. test_grad_dtype_zero_bubble_weight_passes runs four input passes and then four weight passes over residual blocks, as on a zero-bubble schedule's last stage, and checks that the gradient is FP32 after each weight pass and equals FP32 accumulation. test_grad_dtype_outside_forward_and_backward checks that after a no-grad forward, gradients from the unsharded weight accumulate 256 + 1 to 257. All three fail on the previous revision of this PR; the zero-bubble test fails at its dtype check after the first weight pass (bfloat16 != float32). test_grad_dtype_accumulation_skips_upcast and test_grad_dtype_restored_after_deferred_upcast keep trunk's expectations. test_grad_dtype_fixed_for_all_gather_extensions attaches a plain all-gather extension and checks that the forward sees FP32 in two microbatches without gradient sync and a synced one, that autograd delivers FP32 gradients each time, and that 256 + 1 - 256 accumulates to 1. test_grad_dtype_seen_by_all_gather_extension_compute uses a custom autograd Function that, like torchtitan's MXFP8 linear, picks its weight gradient's dtype in forward; it sees FP32, and the reduced gradient keeps (1 + 2^-7)^2 exactly. Both fail without the extension rule, where the forward sees None.
>
> At this revision on B200 GPUs, the mixed precision file (31 tests), the all-gather extensions file (7), and the training and pipeline-with-FSDP mixed precision selections (3 and 8, including the zero-bubble schedules) pass, and lint passes. The compile selection (7) passed on the previous revision; the extension rule doesn't change those tests. The zero-bubble, chunked-loss, interleaved-microbatch and multi-use claims above come from a single-rank CPU (gloo) script, run before the extension rule, which doesn't affect those scenarios.
>
> ```bash
> PY=/home/weif/.conda/envs/code-review/bin/python
> $PY test/distributed/_composable/fsdp/test_fully_shard_mixed_precision.py
> $PY test/distributed/_composable/fsdp/test_fully_shard_extensions.py
> $PY -m pytest -q -p no:cacheprovider test/distributed/_composable/fsdp/test_fully_shard_training.py -k "grad_dtype or mixed_precision"
> $PY -m pytest -q -p no:cacheprovider test/distributed/_composable/fsdp/test_fully_shard_compile.py -k "mixed_precision or mp"
> $PY -m pytest -q -p no:cacheprovider test/distributed/test_composability.py -k "test_pp_fsdp and FSDP_MP"
> PATH=/home/weif/.conda/envs/code-review/bin:$PATH lintrunner -a $(git diff HEAD~1 --name-only --diff-filter=d)
> ```

ghstack-source-id: 28eaeed
Pull-Request: #200196
pytorchmergebot pushed a commit that referenced this pull request Oct 9, 2026
…rd (#200196)

----

* accumulation across backwards without gradient sync stays in FP32
* TP grad reduction stays in FP32

> Authored with Claude Code.
>
> #198668 defers gradient upcasts by setting an unsharded parameter's grad_dtype to None when the backward reduces or the parameter already holds a gradient, so autograd doesn't cast every BF16 gradient to FP32. It chooses in pre_backward, so a forward sees FP32 while its backward runs with None. On trunk a compiled backward doesn't depend on grad_dtype: it casts leaf gradients to the parameter's dtype, and the autograd engine then applies the grad_dtype set when the backward runs. #199856 makes the compiled backward cast to the grad_dtype seen while tracing the forward, and guards on it. With the pre_backward choice, every compiled backward would then cast its BF16 weight gradients to FP32 inside the graph (the fourth row of #199856's table), undoing #198668 under compile. This PR is the FSDP-side prerequisite for #199856.
>
> The choice moves to pre_forward, after the unshard, and holds until post_backward, so a forward and its backward see the same grad_dtype. The rule is unchanged: None if the group reduces gradients or the parameter already holds a gradient, else the unsharded gradient dtype. It is now set either way rather than only to None, so a choice from an earlier forward can't carry over. post_backward and reset_iter_state() restore the unsharded gradient dtype and widen a deferred gradient that wasn't reduced, as on trunk; after a backward that reduces, this restore is what returns grad_dtype to FP32. No-grad forwards skip the choice, since no backward would restore it, and so does recomputation under activation checkpointing, so a backward keeps its forward's choice. The predicate moves to FSDPParam.defers_grad_upcast, and the group's list is renamed after it. Parameters whose sharded tensor implements FSDP's all-gather extension (fsdp_pre_all_gather) never defer: an extension runs its own compute, which may read grad_dtype to pick the dtype its backward produces, so grad_dtype stays the unsharded gradient dtype for them. torchtitan's MXFP8 linear reads it in forward and writes its weight gradient in that dtype; under the pre_forward choice alone it would see None and write BF16.
>
> Outside a forward and its backward, grad_dtype is the unsharded gradient dtype, as on trunk, so gradients deposited without FSDP's hooks still accumulate in FP32. That covers a zero-bubble schedule's weight passes, which run after their input pass's post_backward and assign or add dW themselves in stage_backward_weight, and gradients computed from unsharded parameters without calling their module. The previous revision of this PR set grad_dtype=None for the parameter's lifetime instead, and consecutive weight passes, e.g. on ScheduleInterleavedZeroBubble's last rank, then accumulated in BF16. A fixed FP32 grad_dtype would also keep forward and backward consistent, but gives up the deferral.
>
> Differences from trunk: in a backward whose forward chose None, a parameter used more than once sums its contributions in BF16 before the copy-in or AccumulateGrad widens the total. Trunk already does this in a backward that reduces, and parameters used once per backward get bit-identical gradients. It now also happens for pipeline microbatches forwarded before the step's first backward disables gradient sync, and in the synced backward of a group like fully_shard([norm, head]) used for a chunked loss, whose pre_backward trunk ran only after the per-chunk contributions had been cast. Extension-backed parameters no longer defer. For one whose backward writes grad_dtype, such as torchtitan's MXFP8 linear, nothing changes. One that hard-codes a BF16 weight gradient, such as torchtitan's NVFP4 linear, now gets autograd's per-parameter cast to FP32 and holds the FP32 gradient until the copy-in; pytorch/torchtitan#5180 makes NVFP4 write its weight gradient in grad_dtype, which removes the cast. Other code that reads grad_dtype during forward sees None in a forward that defers. Once #199856 lands, a compiled module whose forward runs both with FP32 (a first microbatch without gradient sync) and with None will compile once for each, since #199856 guards on grad_dtype. Extension-backed parameters keep a fixed grad_dtype, so they add no recompiles. FSDP only sets None or the wider dtype, so #199856's narrowing check can't fire, even when a later post_backward restores FP32 before an earlier-traced backward runs.
>
> The choice is the same loop over the group's parameters that trunk ran in pre_backward. For 3000 four-element parameters in one group on CPU, it takes 0.6 ms with gradient sync and 0.9 ms without, versus 0.9 and 0.7 ms for trunk's loop; the post_backward restore is unchanged at 0.9 ms. On a B200, the 3000 BF16-to-FP32 cast kernels the deferral avoids take 17.6 ms.
>
> Test Plan
>
> test_grad_dtype_chosen_in_forward checks that a backward sees its forward's grad_dtype when gradient sync changes in between, and that grad_dtype and the gradient are FP32 afterwards. test_grad_dtype_zero_bubble_weight_passes runs four input passes and then four weight passes over residual blocks, as on a zero-bubble schedule's last stage, and checks that the gradient is FP32 after each weight pass and equals FP32 accumulation. test_grad_dtype_outside_forward_and_backward checks that after a no-grad forward, gradients from the unsharded weight accumulate 256 + 1 to 257. All three fail on the previous revision of this PR; the zero-bubble test fails at its dtype check after the first weight pass (bfloat16 != float32). test_grad_dtype_accumulation_skips_upcast and test_grad_dtype_restored_after_deferred_upcast keep trunk's expectations. test_grad_dtype_fixed_for_all_gather_extensions attaches a plain all-gather extension and checks that the forward sees FP32 in two microbatches without gradient sync and a synced one, that autograd delivers FP32 gradients each time, and that 256 + 1 - 256 accumulates to 1. test_grad_dtype_seen_by_all_gather_extension_compute uses a custom autograd Function that, like torchtitan's MXFP8 linear, picks its weight gradient's dtype in forward; it sees FP32, and the reduced gradient keeps (1 + 2^-7)^2 exactly. Both fail without the extension rule, where the forward sees None.
>
> At this revision on B200 GPUs, the mixed precision file (31 tests), the all-gather extensions file (7), and the training and pipeline-with-FSDP mixed precision selections (3 and 8, including the zero-bubble schedules) pass, and lint passes. The compile selection (7) passed on the previous revision; the extension rule doesn't change those tests. The zero-bubble, chunked-loss, interleaved-microbatch and multi-use claims above come from a single-rank CPU (gloo) script, run before the extension rule, which doesn't affect those scenarios.
>
> ```bash
> PY=/home/weif/.conda/envs/code-review/bin/python
> $PY test/distributed/_composable/fsdp/test_fully_shard_mixed_precision.py
> $PY test/distributed/_composable/fsdp/test_fully_shard_extensions.py
> $PY -m pytest -q -p no:cacheprovider test/distributed/_composable/fsdp/test_fully_shard_training.py -k "grad_dtype or mixed_precision"
> $PY -m pytest -q -p no:cacheprovider test/distributed/_composable/fsdp/test_fully_shard_compile.py -k "mixed_precision or mp"
> $PY -m pytest -q -p no:cacheprovider test/distributed/test_composability.py -k "test_pp_fsdp and FSDP_MP"
> PATH=/home/weif/.conda/envs/code-review/bin:$PATH lintrunner -a $(git diff HEAD~1 --name-only --diff-filter=d)
> ```
Pull Request resolved: #200196
Approved by: https://github.com/anshul-si, https://github.com/anijain2305
[ghstack-poisoned]
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
cyyever pushed a commit to BakeLab/pytorch that referenced this pull request Oct 11, 2026
…rd (pytorch#200196)

----

* accumulation across backwards without gradient sync stays in FP32
* TP grad reduction stays in FP32

> Authored with Claude Code.
>
> pytorch#198668 defers gradient upcasts by setting an unsharded parameter's grad_dtype to None when the backward reduces or the parameter already holds a gradient, so autograd doesn't cast every BF16 gradient to FP32. It chooses in pre_backward, so a forward sees FP32 while its backward runs with None. On trunk a compiled backward doesn't depend on grad_dtype: it casts leaf gradients to the parameter's dtype, and the autograd engine then applies the grad_dtype set when the backward runs. pytorch#199856 makes the compiled backward cast to the grad_dtype seen while tracing the forward, and guards on it. With the pre_backward choice, every compiled backward would then cast its BF16 weight gradients to FP32 inside the graph (the fourth row of pytorch#199856's table), undoing pytorch#198668 under compile. This PR is the FSDP-side prerequisite for pytorch#199856.
>
> The choice moves to pre_forward, after the unshard, and holds until post_backward, so a forward and its backward see the same grad_dtype. The rule is unchanged: None if the group reduces gradients or the parameter already holds a gradient, else the unsharded gradient dtype. It is now set either way rather than only to None, so a choice from an earlier forward can't carry over. post_backward and reset_iter_state() restore the unsharded gradient dtype and widen a deferred gradient that wasn't reduced, as on trunk; after a backward that reduces, this restore is what returns grad_dtype to FP32. No-grad forwards skip the choice, since no backward would restore it, and so does recomputation under activation checkpointing, so a backward keeps its forward's choice. The predicate moves to FSDPParam.defers_grad_upcast, and the group's list is renamed after it. Parameters whose sharded tensor implements FSDP's all-gather extension (fsdp_pre_all_gather) never defer: an extension runs its own compute, which may read grad_dtype to pick the dtype its backward produces, so grad_dtype stays the unsharded gradient dtype for them. torchtitan's MXFP8 linear reads it in forward and writes its weight gradient in that dtype; under the pre_forward choice alone it would see None and write BF16.
>
> Outside a forward and its backward, grad_dtype is the unsharded gradient dtype, as on trunk, so gradients deposited without FSDP's hooks still accumulate in FP32. That covers a zero-bubble schedule's weight passes, which run after their input pass's post_backward and assign or add dW themselves in stage_backward_weight, and gradients computed from unsharded parameters without calling their module. The previous revision of this PR set grad_dtype=None for the parameter's lifetime instead, and consecutive weight passes, e.g. on ScheduleInterleavedZeroBubble's last rank, then accumulated in BF16. A fixed FP32 grad_dtype would also keep forward and backward consistent, but gives up the deferral.
>
> Differences from trunk: in a backward whose forward chose None, a parameter used more than once sums its contributions in BF16 before the copy-in or AccumulateGrad widens the total. Trunk already does this in a backward that reduces, and parameters used once per backward get bit-identical gradients. It now also happens for pipeline microbatches forwarded before the step's first backward disables gradient sync, and in the synced backward of a group like fully_shard([norm, head]) used for a chunked loss, whose pre_backward trunk ran only after the per-chunk contributions had been cast. Extension-backed parameters no longer defer. For one whose backward writes grad_dtype, such as torchtitan's MXFP8 linear, nothing changes. One that hard-codes a BF16 weight gradient, such as torchtitan's NVFP4 linear, now gets autograd's per-parameter cast to FP32 and holds the FP32 gradient until the copy-in; pytorch/torchtitan#5180 makes NVFP4 write its weight gradient in grad_dtype, which removes the cast. Other code that reads grad_dtype during forward sees None in a forward that defers. Once pytorch#199856 lands, a compiled module whose forward runs both with FP32 (a first microbatch without gradient sync) and with None will compile once for each, since pytorch#199856 guards on grad_dtype. Extension-backed parameters keep a fixed grad_dtype, so they add no recompiles. FSDP only sets None or the wider dtype, so pytorch#199856's narrowing check can't fire, even when a later post_backward restores FP32 before an earlier-traced backward runs.
>
> The choice is the same loop over the group's parameters that trunk ran in pre_backward. For 3000 four-element parameters in one group on CPU, it takes 0.6 ms with gradient sync and 0.9 ms without, versus 0.9 and 0.7 ms for trunk's loop; the post_backward restore is unchanged at 0.9 ms. On a B200, the 3000 BF16-to-FP32 cast kernels the deferral avoids take 17.6 ms.
>
> Test Plan
>
> test_grad_dtype_chosen_in_forward checks that a backward sees its forward's grad_dtype when gradient sync changes in between, and that grad_dtype and the gradient are FP32 afterwards. test_grad_dtype_zero_bubble_weight_passes runs four input passes and then four weight passes over residual blocks, as on a zero-bubble schedule's last stage, and checks that the gradient is FP32 after each weight pass and equals FP32 accumulation. test_grad_dtype_outside_forward_and_backward checks that after a no-grad forward, gradients from the unsharded weight accumulate 256 + 1 to 257. All three fail on the previous revision of this PR; the zero-bubble test fails at its dtype check after the first weight pass (bfloat16 != float32). test_grad_dtype_accumulation_skips_upcast and test_grad_dtype_restored_after_deferred_upcast keep trunk's expectations. test_grad_dtype_fixed_for_all_gather_extensions attaches a plain all-gather extension and checks that the forward sees FP32 in two microbatches without gradient sync and a synced one, that autograd delivers FP32 gradients each time, and that 256 + 1 - 256 accumulates to 1. test_grad_dtype_seen_by_all_gather_extension_compute uses a custom autograd Function that, like torchtitan's MXFP8 linear, picks its weight gradient's dtype in forward; it sees FP32, and the reduced gradient keeps (1 + 2^-7)^2 exactly. Both fail without the extension rule, where the forward sees None.
>
> At this revision on B200 GPUs, the mixed precision file (31 tests), the all-gather extensions file (7), and the training and pipeline-with-FSDP mixed precision selections (3 and 8, including the zero-bubble schedules) pass, and lint passes. The compile selection (7) passed on the previous revision; the extension rule doesn't change those tests. The zero-bubble, chunked-loss, interleaved-microbatch and multi-use claims above come from a single-rank CPU (gloo) script, run before the extension rule, which doesn't affect those scenarios.
>
> ```bash
> PY=/home/weif/.conda/envs/code-review/bin/python
> $PY test/distributed/_composable/fsdp/test_fully_shard_mixed_precision.py
> $PY test/distributed/_composable/fsdp/test_fully_shard_extensions.py
> $PY -m pytest -q -p no:cacheprovider test/distributed/_composable/fsdp/test_fully_shard_training.py -k "grad_dtype or mixed_precision"
> $PY -m pytest -q -p no:cacheprovider test/distributed/_composable/fsdp/test_fully_shard_compile.py -k "mixed_precision or mp"
> $PY -m pytest -q -p no:cacheprovider test/distributed/test_composability.py -k "test_pp_fsdp and FSDP_MP"
> PATH=/home/weif/.conda/envs/code-review/bin:$PATH lintrunner -a $(git diff HEAD~1 --name-only --diff-filter=d)
> ```
Pull Request resolved: pytorch#200196
Approved by: https://github.com/anshul-si, https://github.com/anijain2305
@pytorchbot pytorchbot added the in progress PR is being worked on by the author, until the automated review accepts it label Oct 16, 2026

@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 502a5a4: changes requested before human review.

The PR makes torch.compile honor a leaf's grad_dtype across guards, fake/functional tensor conversion, AOTAutograd tracing/runtime, and the AOT cache key; the core logic and most tests look sound. However, soulitzer's inline comment on meta_utils (preserving the 'follows dtype' vs 'explicitly pinned' distinction via _has_grad_dtype_override) has neither a code change nor an author reply, and the builder.py graph-break relaxation has no test.

🔴 1 blocking finding is attached to the code below.

⚪ 2 non-blocking findings

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

Untested behavior change: a bf16 leaf with an existing fp32 .grad and grad_dtype=fp32/None no longer graph-breaks. No test calls a compiled fn twice on the same param (with .grad populated) under fullgraph=True.


grad_dtype = t.grad_dtype if t.requires_grad else t.dtype

Only the DTensor _stable_hash_for_caching path of the cache-key change is tested; this plain-tensor path and the subclass fallback without _stable_hash_for_caching (line 807) have no test showing grad_dtype changes the key.

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

This review is AI-generated and advisory. Each new automated review replaces the previous one.

is_inference=False if is_inference_mode_disabled else t.is_inference(),
is_leaf=is_leaf,
requires_grad=t.requires_grad,
grad_dtype=t.grad_dtype if t.requires_grad and is_leaf else t.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.

🔴 Unaddressed: soulitzer noted this loses the 'follows tensor dtype' vs 'explicitly pinned' distinction and suggested _has_grad_dtype_override. HEAD still records the effective dtype, and line 2265 sets r.grad_dtype unconditionally, so every fake requires-grad leaf gets pinned (the C++ setter always records an override), unlike the real tensor. Either guard on t._has_grad_dtype_override (or grad_dtype != dtype, as copy_grad_dtype_override does) or reply explaining why it doesn't matter.

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants