Repository navigation
Conversation
🔗 Helpful Links🧪 See artifacts and rendered test results at hud.pytorch.org/pr/189634
Note: Links to docs will display an error until the docs builds have been completed. ❌ You can merge normally! (6 Unrelated Failures), 2 Unclassified FailuresAs of commit bbd9976 with merge base f594cad ( UNCLASSIFIED FAILURES - DrCI could not classify the following jobs because the workflow did not run on the merge base. The failures may be pre-existing on trunk or introduced by this PR:
CRCR (non-blocking) - The following CRCR downstream CI jobs failed but are non-blocking:
This comment was automatically generated by Dr. CI and updates every 15 minutes. |
|
|
8943d16 to
8e17f7b
Compare
ad5d437 to
7380626
Compare
| """ | ||
| from torch.autograd.graph import _get_grad_dtype | ||
|
|
||
| return _get_grad_dtype(input) |
There was a problem hiding this comment.
You don't actually necessary have the input tensor alive at this point!
Instead you want to traverse the graph directly to find the next node corresponding to the right input. We will eventually have to worry about the accumulation dtype, which we don't have an API exposed to alter yet (so maybe that is fine for now).
There was a problem hiding this comment.
The other thing is that when you call get_grad_dtype matters, e.g. whether you are in the forward or backward. Because someone could've gone along and altered the dtype the input_metadata later (unless we decide to ban this).
There was a problem hiding this comment.
Would it make sense for get_input_grad_dtype to use the tensor only to identify the Function input, while reading the dtype from the corresponding next_edge captured at apply time? This would make it a Function-scoped query rather than a query on the tensor's current edge.
We intend both APIs to be graph-construction-time APIs, callable only from forward or setup_context, and can enforce that explicitly. Would this address the lifetime and timing concerns, or do you expect the getter to also work in backward?
There was a problem hiding this comment.
If it were a method that takes in tensor, the user might as well query some API like tensor.grad_dtype directly since nothing that about that is specfic to the autograd.Function.
I'd agree that graph-construction time seems like the most common case, but I'm not sure I want to preclude ourselves too early from post facto grad_dtype mutations (imaginary example: after the entire forward completes someone can do some additional analysis given that they have knowledge of the full graph and realize that dtype needs to be a particular way).
If we must account for possible mutation of grad_dtype, and thus must access during bw where don't have tensor, the user can manually do ctx.next_functions[idx][0].input_metadata[ctx.next_functions[idx][1]], but maybe there value in providing a helper to do this
There was a problem hiding this comment.
That makes sense—we should consider other call sites.
The Tensor arguments were intended to make the API convenient in forward/setup_context, without requiring users to maintain a Tensor-to-index mapping. Outside graph construction, I wonder whether the same API would still be convenient (immediately after apply may be one exception, since both inputs and outputs are readily available), or whether an index- or edge-based API might be more natural for cases such as graph analysis or backward.
The implementation would also differ across these phases: the current Getter maps apply inputs to captured edges, while Setter declarations are consumed during output wrapping. Supporting post-apply calls would therefore require more than removing the guard.
Do you think these PRs should support calls outside graph construction now, or should we keep the Tensor-based APIs scoped to graph construction and discuss later access separately?
There was a problem hiding this comment.
Let's discuss outside of graph construction later. I think for the setter ctx.set_output_grad_dtype that you propose is the right API!
|
So sorry for the delay! @SongyuanZhao This is PR is looking pretty good, but can I request to have it split into two separate ones for each of the two APIs since they should work independently of one another. |
| The dtype has the following meaning: | ||
|
|
||
| - a concrete :class:`torch.dtype`: the incoming gradient is cast to that | ||
| dtype (up or down); a hard error is raised if the cast is impossible. |
There was a problem hiding this comment.
Do you have an example where the cast be impossible?
There was a problem hiding this comment.
I don't have a concrete example. I think that was an overly speculative statement introduced with AI. I'll remove it later.
| :func:`forward` methods, and the same ``output`` Tensor object must be | ||
| among the tensors this Function returns. It controls the dtype the | ||
| autograd engine produces for the gradient flowing back into ``output``'s | ||
| slot, without placing any state on the (non-leaf) output tensor itself. |
There was a problem hiding this comment.
"without placing any state on the (non-leaf) output tensor itself"
We probably don't need to mention this haha
|
|
||
| This should be called from either the :func:`setup_context` or | ||
| :func:`forward` methods, and the same ``output`` Tensor object must be | ||
| among the tensors this Function returns. It controls the dtype the |
There was a problem hiding this comment.
So this knob would ALSO control accumulation dtype today!
Maybe its fine, even if we plan to add a designated knob for accum dtype later.
Accum dtype defaults to the grad_dtype when accum_dtype is not specified.
|
@soulitzer Sounds good, thanks! I will keep |
7380626 to
fc7f992
Compare
|
This PR now contains only
The two PRs share some changes and may conflict.I will rebase and resolve them after one lands. Please take another look when convenient. @soulitzer |
There was a problem hiding this comment.
Can I propose a slightly different API? I think the way of doing it in this PR is also kind of reasonable, but I think the easiest way might be to just handle it positionally (the same way backward handles gradients), where the function takes varargs:
def forward(ctx, ...):
...
ctx.set_output_grad_dtype(None, None, torch.float32, t3.dtype)
return non_tensor, t1, t2, t3- If the user return at position i is non-tensor must return None for that position
If the user wants no-cast to happen by the engine, they pass the sentinel object NO_CAST- If the user wants the grad a particular dtype, they return that dtype
- If the user wants the default behavior, they should do so explicitly by querying for t's dtype, e.g. not using the API is equivalent to
ctx.set_output_grad_dtype(None, t1.dtype, t2.dtype, t3.dtype)
Another benefit of this is that now you can handle the case where the same tensor is returned twice, but you want to have two distinct grad dtypes (with a tensor identity based API, the user would need to return a separate view).
EDIT:
One annoying thing of the positional-based API is that None means two things: (1) skip for non-tensors, (2) engine does not cast.
Accepting a sentinel object NO_CAST = object() would help disambiguate and guard against some positional drift
But I don't like diverging from the existing t.grad_dtype API where None means engine doesn't cast. And what's worse is that due to bc it is not really possible for us to have it return NO_CAST instead of None (existing equality checks would fail).
I feel like what might be okay is to instead to think of (1) and (2) as conceptually the same. The non-tensor case, is considered a subset of the no-cast case, because there is no gradient to cast anyway!
| // Preserve an in-flight Python error while releasing the recording. | ||
| PyObject *type = nullptr, *value = nullptr, *traceback = nullptr; | ||
| PyErr_Fetch(&type, &value, &traceback); | ||
| Py_CLEAR(ctx_->output_grad_dtypes); |
There was a problem hiding this comment.
Do we need actually need this for the error case? If we return early, the node should not get attached to the graph and its fields should be cleared via tp_clear.
| // Marks the user phase in which grad-dtype ctx APIs may be called. The explicit | ||
| // end closes the phase before output wrapping; the destructor handles early | ||
| // exits. | ||
| struct GradDtypeApiGuard { |
There was a problem hiding this comment.
I don't think we need to be do defensive of calling this outside of the forward / setup_context as it doesn't really do anything if called in jvp or backward.
| >>> ctx.set_output_grad_dtype(out, torch.float32) | ||
| >>> return out | ||
| """ | ||
| self._set_output_grad_dtype(output, dtype) |
There was a problem hiding this comment.
I wonder if we could follow the pattern from the other APIs above, where the user sets to the field via a descriptor.
|
Thanks, that makes sense. I’ll switch to the positional API aligned with the forward outputs, use the existing ctx field/descriptor pattern, and remove the unnecessary phase guard and defensive cleanup. |
Add a ctx method that lets a Python autograd.Function declare the gradient
dtype contract for each of its output slots independently of the output's
storage dtype. The API is positional, taking one dtype-or-None declaration per
returned value, aligned with how backward receives gradients:
def forward(ctx, x):
...
ctx.set_output_grad_dtype(torch.float32, None, None)
return t1, t2, "not a tensor"
For each returned value the declaration at the same index means: a concrete
dtype casts the incoming gradient (only valid for a differentiable Tensor);
None performs no conversion, which is also the only valid choice for a
non-Tensor or non-differentiable slot (there is no gradient to cast). Not
calling the API keeps the default of converting to each output's storage
dtype; that default is requested explicitly by passing the output's own dtype.
The Python method stores the tuple through a THPFunction descriptor
(output_grad_dtypes), mirroring mark_dirty / mark_non_differentiable. Output
wrapping parses it into a positional vector, validates the declaration count
equals the number of outputs and that concrete dtypes only target
differentiable Tensor slots, then applies each to the matching input_metadata
slot by index. The recording is cleared once consumed. There is no defensive
runtime phase check, matching the other construction-time ctx APIs; the
docstring documents the intended call site (forward / setup_context) and that
a later call overwrites an earlier one.
Test Plan:
Built CPU-only and ran the setter suite on a remote x86 host:
```
USE_CUDA=0 USE_ROCM=0 USE_XPU=0 USE_NUMA=0 USE_DISTRIBUTED=0 USE_FBGEMM=0 \
python -m pip install -e . -v --no-build-isolation
python -m pytest -v test/test_autograd.py -k ctx_output_grad_dtype
python -m pytest -q test/test_autograd.py -k "custom_function or setup_context or mark_dirty or mark_non_differentiable or materialize or output_grad_dtype or save_for_backward"
```
Results: 10 passed (setter suite), 65 passed / 3 skipped (broader
custom-Function subset).
Authored with the assistance of an AI coding assistant.
fc7f992 to
6987dd8
Compare
| r"""Declare the gradient dtype for each of this Function's outputs. | ||
|
|
||
| This should be called from either the :func:`setup_context` or | ||
| :func:`forward` methods. If called more than once, only the last call |
There was a problem hiding this comment.
I guess last call wins is the behavior, but in docs maybe just follow mark_dirty, etc here where we tell the users that they should only call it once. I'm not sure if there's an actual consequence for calling twice, but we should be clear that its not intended usage.
There was a problem hiding this comment.
Actually if there is an easy way to error upon second call, maybe its better to do that hmm
| returns at the same index, so the number of declarations must match the | ||
| number of returned values. This lets a Function define the dtype | ||
| contract for gradients entering its output slots independently of the | ||
| outputs' storage dtypes. |
There was a problem hiding this comment.
This lets a Function define the dtype
contract for gradients entering its output slots independently of the
outputs' storage dtypes
Maybe too low level / edge case to mention in the main paragraph here since it should already reflect the intuitive behavior
Merge startedYour 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 |
Merge failedReason: 3 jobs have failed, first few of them are: trunk / linux-jammy-cuda13.0-py3.10-gcc11 / test (default, 7, 14, mt-l-x86aavx2-29-113-l4), trunk / linux-jammy-cuda13.0-py3.10-gcc11 / test (default, 6, 14, mt-l-x86aavx2-29-113-l4), trunk / linux-jammy-rocm-py3.10-mi350 / test (default, 2, 8, linux.rocm.gpu.gfx950.1) Details for Dev Infra teamRaised by workflow job |
The trunk run for this PR fails in TestAutogradWithCompiledAutograd with
"Unsupported: setattr() on unsupported type". The grad_dtype tests report
the dtype they observed by assigning it to an attribute on the
autograd.Function class, and dynamo cannot trace that setattr once
compiled autograd inlines the backward.
run_test.py passes -x, so each shard stops at its first failure and only
ever names one test; skipping the names that surfaced just promotes the
next one in that shard's order. The whole family is affected, so skip it
by prefix. That is consistent with eager, where every one of these tests
already carries skipIfTorchDynamo("grad_dtype not supported in compile").
skipped_tests leaves the tests running eagerly under the wrapped class
rather than dropping them, so they keep the coverage they have in
test_autograd.py. known_graph_breaks_tests was the alternative, but it
would only relax fullgraph and still exercise a path the feature does not
claim to support.
Test Plan:
Reproduced the underlying dynamo limitation directly, independent of this
PR's C++, confirming it is deterministic rather than order-dependent (a
custom Function whose backward does `Rec.seen = g.dtype`, run six times
under compiled_autograd._enable with fullgraph=True, fails every time):
```
python agent_space/setattr_ca.py
```
Confirmed the prefix skip covers the whole family and changes nothing
else in the wrapped class:
```
python -c "
import importlib.util
spec = importlib.util.spec_from_file_location('tca', 'inductor/test_compiled_autograd.py')
m = importlib.util.module_from_spec(spec); spec.loader.exec_module(m)
cls = m.TestAutogradWithCompiledAutograd
fam = [x for x in dir(cls) if 'ctx_output_grad_dtype' in x]
print(len(fam), [n for n in fam if getattr(cls, n).__code__.co_name == 'wrapped'])
print(sum(1 for x in dir(cls) if x.startswith('test_') and getattr(cls, x).__code__.co_name == 'wrapped'))
"
```
reporting 13 tests in the family, none still wrapped, and 274 other tests
still wrapped as before.
```
lintrunner --take RUFF,FLAKE8,PYFMT test/inductor/test_compiled_autograd.py
```
Authored with assistance from Claude Code.
02f63cf to
bbd9976
Compare
|
@pytorchbot merge |
Merge startedYour 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 |
Merge failedReason: 2 mandatory check(s) failed. The first few are:
Dig deeper by viewing the failures on hud |
|
@soulitzer Thanks for helping with the compiled autograd fix! It looks like the latest merge attempt was blocked by CI infrastructure issues. When convenient, could you please help trigger the merge again? Thanks! |
|
@pytorchbot merge -i |
1 similar comment
|
@pytorchbot merge -i |
|
@SongyuanZhao github actions might be still down, will try to reland again tomorrow |
|
@pytorchbot merge -i |
Merge startedYour change will be merged while ignoring the following 2 checks: pull / linux-jammy-cuda13.2-cudnn9-py3.10-clang20 / build, pull / linux-jammy-cuda13.0-cudnn9-py3.10-clang20 / build Learn more about merging in the wiki. Questions? Feedback? Please reach out to the PyTorch DevX Team |
See docstring ~Add `ctx.set_output_grad_dtype(output, dtype)`, allowing an `autograd.Function` to declare the gradient dtype contract for one of its outputs independently of the output's storage dtype.~ Declarations are matched to Function output slots by Python object identity - A concrete dtype converts incoming gradients to that dtype. - `None` accepts incoming gradients without conversion. - An output without a declaration retains the existing behavior.~ ~This API may only be called from `forward` or `setup_context`. Calls from other phases are rejected.~ `get_input_grad_dtype` has been moved to a separate follow-up PR Pull Request resolved: pytorch#189634 Approved by: https://github.com/soulitzer Co-authored-by: soulitzer <[email protected]>
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
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
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
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
) ctx.set_output_grad_dtype (#189634) lets an autograd.Function declare the dtype its backward receives each output gradient in, independently of the output's dtype. Dynamo traced the forward against a Python FunctionCtx without the backing attribute, so any compiled Function calling it failed with "'FunctionCtx' object has no attribute 'output_grad_dtypes'". Follow the mark_non_differentiable / mark_dirty pattern: - AutogradFunctionContextVariable records the declared dtypes (constant torch.dtype or None; anything else graph breaks). - The backward is traced with gradient placeholders in the declared dtypes, via a new sub_args_dtypes override for forced subgraph inputs. - autograd_function_apply replays the declaration in setup_context, so the autograd engine converts incoming gradients as in eager. Motivation: torchtitan GraphTrainer's SimpleFSDP needs this to keep fp32 gradients of bf16 all-gathered weights (matching FSDP2's unsharded grad_dtype = reduce_dtype) under torch.compile. Test plan: - test_set_output_grad_dtype: an fp32 gradient flowing into a bf16 output declared fp32 keeps a value bf16 cannot represent, in eager and under aot_eager with fullgraph=True. Fails without this change. - test/dynamo/test_autograd_function.py, test/dynamo/test_higher_order_ops.py: 348 passed. Pull Request resolved: #200311 Approved by: https://github.com/anijain2305
See docstring
Addctx.set_output_grad_dtype(output, dtype), allowing anautograd.Functionto declare the gradient dtype contract for one of its outputs independently of the output's storage dtype.Declarations are matched to Function output slots by Python object identity
Noneaccepts incoming gradients without conversion.This API may only be called fromforwardorsetup_context. Calls from other phases are rejected.get_input_grad_dtypehas been moved to a separate follow-up PRcc @voznesenskym @penguinwu @EikanWang @jgong5 @Guobing-Chen @XiaobingSuper @zhuhaozhe @blzheng @wenzhe-nrv @jiayisunx @ipiszy @kadeng @muchulee8 @amjames @chauhang @aakhundov @coconutruben @jataylo