Skip to content

[dynamo] Support ctx.set_output_grad_dtype in autograd.Function - #200311

Closed
pianpwk wants to merge 5 commits into
gh/pianpwk/158/basefrom
gh/pianpwk/158/head
Closed

pianpwk wants to merge 5 commits into
gh/pianpwk/158/basefrom
gh/pianpwk/158/head

Conversation

@pianpwk

@pianpwk pianpwk commented Oct 8, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

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

Follow the mark_non_differentiable / mark_dirty pattern:

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

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

Test plan:

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

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

Copy link
Copy Markdown

🔗 Helpful Links

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

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 eb68c6e with merge base f8c63a1 (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/inductor ciflow/torchtitan Run TorchTitan integration tests module: dynamo labels Oct 8, 2026
pianpwk added a commit that referenced this pull request Oct 8, 2026
ctx.set_output_grad_dtype (#189634) lets an autograd.Function declare the
dtype its backward receives each output gradient in, independently of the
output's dtype. Dynamo traced the forward against a Python FunctionCtx
without the backing attribute, so any compiled Function calling it failed
with "'FunctionCtx' object has no attribute 'output_grad_dtypes'".

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

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

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

ghstack-source-id: 86e2267
Pull Request resolved: #200311
@pianpwk
pianpwk marked this pull request as ready for review October 9, 2026 19:55
tracer: Optional["SubgraphTracer"] = None,
# Dtype overrides for forced tensor inputs; see
# validate_args_and_maybe_create_graph_inputs.
sub_args_dtypes: Sequence[torch.dtype | None] | None = None,

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 this be called overridden_bwd_args_dtypes>

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Maybe also specify in the comment that this is used only by autograd.Function set_output_grad_dtypes (because the shared helper here is used by others as well)

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

This might be incomplete. Dynamo transforms the autograd.Function into a new autograd.Function where the ordering of the transformed forward outputs might be different from the original forward outputs.

This PR just sets the output grad dtypes assuming that Dynamo-traced autograd.Function will have the same ordering. Ask the agent to look into the details of how forward and backward are traced and how the mapping of inputs, outputs, grad_outs and grad_ins is done. There should be enough info there to then reconstuct the transformed output grad dtypes.

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

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

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

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

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

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

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

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

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

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

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

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

ghstack-source-id: 21d6d46
Pull Request resolved: #200311
@pianpwk

pianpwk commented Oct 12, 2026

Copy link
Copy Markdown
Contributor Author

@pytorchbot merge

@pytorch-bot pytorch-bot Bot added the ciflow/trunk Trigger trunk jobs on your pull request label Oct 12, 2026
@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge started

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

Learn more about merging in the wiki.

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

Advanced Debugging
Check the merge workflow status
here

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge failed

Reason: 1 jobs have failed, first few of them are: trunk / macos-py3-arm64 / test (default, 2, 3, macos-m1-stable)

Details for Dev Infra team Raised by workflow job

pianpwk added a commit to pytorch/torchtitan that referenced this pull request Oct 13, 2026
… does (#5171)

Stack from [ghstack](https://github.com/ezyang/ghstack/tree/0.12.0)
(oldest at bottom):
* __->__ #5171

This fixes a numerics mismatch between eager FSDP2 and SimpleFSDP
(GraphTrainer).

pytorch/pytorch#194434 ("[FSDP2] Separate sharded and unsharded gradient
dtypes", 38d3f6fd0d6e, in the 2026-10-02 nightly) changes the dtype of
FSDP2's unsharded-parameter gradients when `grad_dtype` is not
specified: they now default to `reduce_dtype` instead of `param_dtype`.
With torchtitan's mixed-precision policy, that is fp32 instead of bf16.

This changes the backward all-reduce of TP-replicated parameters (typed
R on TP, e.g. sequence-parallel norm weights and the MoE router gate):
eager FSDP2 now sums the per-TP-rank partial gradients in fp32 and
reduce-scatters the fp32 sum. SimpleFSDP also sums them in fp32, but the
sum is rounded back down to bf16 to match the dtype of SimpleFSDP's
unsharded weight, a bf16 autograd intermediate, before the
reduce-scatter. The router gate's `grad_weight`, which `HiMidLoLinear`
computes in fp32, is rounded the same way. As a result the dense
Llama3/Qwen3 and the Qwen3 MoE numerics tests diverge from eager at step
2, and are xfailed in #5110 and #5133.

This PR adds a custom autograd Function that runs SimpleFSDP's gradient
reductions the way FSDP2 does. All of those tests match eager bitwise
again, and their xfails are removed.

## Backward, before and after

Both sides use torchtitan's default mixed-precision settings:

| Field | Value | Source |
|---|---|---|
| master (sharded) param dtype | fp32 | |
| `param_dtype` | bf16 | `training.mixed_precision_param` |
| `reduce_dtype` | fp32 | `training.mixed_precision_reduce` |
| `grad_dtype` on the param | unset | |

### Issue 1: R-on-TP parameters (e.g. sequence-parallel norm weights)

Each TP rank computes a partial gradient (over its tokens), which must
be summed over TP before the FSDP reduce-scatter.

```
Eager FSDP2
  compute -> wgrad bf16
  -> LEAF .grad: unsharded param, grad_dtype = reduce_dtype       -> fp32
     ---- autograd ends; FSDP2 post-backward ----
  -> TP all-reduce (fp32) -> reduce-scatter (fp32)

SimpleFSDP on main
  compute -> wgrad bf16
  -> spmd.convert(I -> R) bwd: cast fp32, TP all-reduce (fp32)
  -> autograd casts to the bf16 all-gathered weight's dtype       <- rounds the TP sum
  -> redistribute bwd: cast fp32, reduce-scatter (fp32)

SimpleFSDP, this PR
  compute -> wgrad bf16
  -> output grad dtype declared fp32                              -> cast up (exact)
  -> _UnshardAndReduceGradFunction bwd: TP all-reduce (fp32), reduce-scatter (fp32)
```

### Issue 2: MoE router gate (HiMidLoLinear, also R on TP)

`HiMidLoLinear`'s backward computes `grad_weight` in fp32 by design.

```
Eager FSDP2
  HiMidLo bwd -> grad_weight fp32
  -> LEAF .grad: grad_dtype = reduce_dtype                        -> kept fp32
     ---- autograd ends; FSDP2 post-backward ----
  -> TP all-reduce (fp32) -> reduce-scatter (fp32)

SimpleFSDP on main
  HiMidLo bwd -> grad_weight fp32
  -> autograd casts to convert output's dtype (bf16)              <- issue 2
  -> convert bwd: cast fp32, TP all-reduce (fp32)
  -> autograd casts to the bf16 all-gathered weight's dtype       <- issue 1
  -> redistribute bwd: cast fp32, reduce-scatter (fp32)

SimpleFSDP, this PR
  HiMidLo bwd -> grad_weight fp32
  -> output grad dtype declared fp32                              -> kept fp32
  -> _UnshardAndReduceGradFunction bwd: TP all-reduce (fp32), reduce-scatter (fp32)
```

For every other parameter, the bf16 wgrad reaches the reduce-scatter
with no reduction in between, and the bf16 -> fp32 cast is exact
wherever it happens, so those gradients already matched eager.

## Fix

`_UnshardAndReduceGradFunction` covers one parameter's unshard and
gradient reduction:

- **Forward:** wrap the TP/EP-local shard as a DTensor on the DP mesh,
cast to `param_dtype`, all-gather (no-op for DDP), and return the
unsharded weight. Same ops as before.
- **Output gradient dtype:** `ctx.set_output_grad_dtype(reduce_dtype)`,
the same value FSDP2 gives its unsharded parameter's `grad_dtype`. An
fp32 gradient flowing in is kept, and a bf16 one is cast up exactly.
- **Backward:** all-reduce (P -> I) over the non-DP axes where the
parameter is R, then Partial -> the DP placements (reduce-scatter for
FSDP, all-reduce for DDP, both for HSDP), all in `reduce_dtype`, in one
node with no bf16 intermediate.

Both branches of `ReplicateComputation.replicate_compute` (with and
without TP/EP axes) use it, replacing the `redistribute -> to_local ->
spmd.convert` chain.

Dynamo cannot trace `ctx.set_output_grad_dtype` yet, so the call is
skipped under `torch.compile`. GraphTrainer traces with `make_fx` and is
unaffected; only the SimpleFSDP unit tests that use
`torch.compile(backend="aot_eager")` take this path, and none uses mixed
precision. The guard can go once the Dynamo support (pytorch PR,
pytorch/pytorch#200311) is in the nightly.

**Compared to #5106**, which all-gathers R parameters in fp32 so the TP
sum stays fp32:
- the all-gather stays in bf16, so there are no extra fp32 all-gather
buckets (#5106: 15 -> 28 in the Llama3 debug model);
- it also fixes issue 2, which #5106 cannot reach because the router's
rounding happens before the TP sum.

## Results

8x H100, torch 2.16.0a0+gitbe3a22f (includes pytorch#194434), 20 steps,
eager vs GraphTrainer:

| Test | main | this PR |
|---|---|---|
| `test_dense_llama3_aot_fx_trace_vs_eager` | diverges at step 2 (xfail)
| bitwise |
| `test_dense_qwen3_aot_fx_trace_vs_eager` | diverges (xfail) | bitwise
|
| `test_moe_qwen3_aot_fx_trace_vs_eager` | diverges from step 2 (xfail)
| bitwise (loss and grad_norm) |
| `test_dense_llama3_hsdp_gradient_accumulation_aot_fx_trace_vs_eager` |
| bitwise |
| `test_dense_llama3_hsdp_graph_pp_vs_eager` | | bitwise |

## Test plan

- `test_numerics.py`: the five tests above pass. The strict xfails from
#5110 and #5133 are removed, and the MoE test now uses the bitwise
`run_loss_compare` instead of `run_loss_compare_close`.
- New `TestSimpleFSDP` tests, both failing on main by exactly the
rounded-off amount:
- `test_tp_reduced_grad_stays_in_reduce_dtype`: per-TP-rank grads 1 and
2**-9 (exact in bf16, but their sum is not) must reach the
reduce-scatter as 1 + 2**-9.
- `test_wide_grad_reaches_reduce_scatter`: an fp32 wgrad with a sub-bf16
term must keep it.
- `TestSimpleFSDP` + `test_simple_fsdp.py`: pass (uneven/transposed
shards, DDP/HSDP + TP, EP + TP, compiled variants).
- `test_bitwise_deterministic.py` and `test_passes.py` +
`test_graph_pp_passes.py` passed before rebasing onto #4859.
- ufmt, flake8, codespell and pyrefly pass on the changed files.
[ghstack-poisoned]
@pianpwk

pianpwk commented Oct 14, 2026

Copy link
Copy Markdown
Contributor Author

@pytorchbot merge

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge started

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

Learn more about merging in the wiki.

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

Advanced Debugging
Check the merge workflow status
here

pytorchmergebot pushed a commit that referenced this pull request Oct 16, 2026
…e tests (#201096)

Summary:
Forward fix for D125399978 (#200311). fbcode sets `guess_tangent_strides_as_outputs = not is_fbcode()`, so in fbcode the backward copies the gradient with `aten::clone` instead of `empty_strided` + `copy_`, and the inline expected `DebugMode` traces in `test_set_output_grad_dtype` and `test_set_output_grad_dtype_non_tensor_output` don't match.

Pin `torch._functorch.config.patch(guess_tangent_strides_as_outputs=True)` on both tests, matching existing tests in `test_backward_higher_order_ops.py`, `test_modes.py` and `test_debug_mode.py`.

Test Plan:
```
buck test fbcode//caffe2/test/dynamo:test_dynamo -- --regex 'test_autograd_function.*test_set_output_grad_dtype'
```

Differential Revision: D125489641

Pull Request resolved: #201096
Approved by: https://github.com/pytorchgreenlight
majing921201 pushed a commit to majing921201/pytorch that referenced this pull request Nov 16, 2026
…e tests (pytorch#201096)

Summary:
Forward fix for D125399978 (pytorch#200311). fbcode sets `guess_tangent_strides_as_outputs = not is_fbcode()`, so in fbcode the backward copies the gradient with `aten::clone` instead of `empty_strided` + `copy_`, and the inline expected `DebugMode` traces in `test_set_output_grad_dtype` and `test_set_output_grad_dtype_non_tensor_output` don't match.

Pin `torch._functorch.config.patch(guess_tangent_strides_as_outputs=True)` on both tests, matching existing tests in `test_backward_higher_order_ops.py`, `test_modes.py` and `test_debug_mode.py`.

Test Plan:
```
buck test fbcode//caffe2/test/dynamo:test_dynamo -- --regex 'test_autograd_function.*test_set_output_grad_dtype'
```

Differential Revision: D125489641

Pull Request resolved: pytorch#201096
Approved by: https://github.com/pytorchgreenlight
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/inductor ciflow/torchtitan Run TorchTitan integration tests ciflow/trunk Trigger trunk jobs on your pull request Merged module: dynamo release notes: dynamo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants