Repository navigation
[Test] Refactor test/functorch/test_eager_transforms.py and enable on XPU - #192806
tszulist-hbn wants to merge 5 commits into
Conversation
PR Status: Approved 🚀Please fix all CI failures and trigger merge by commenting "@pytorchbot merge". ✅ AUTOMATED REVIEW - Ready for human review:
Findings (2): Reviewed commit: 🔗 Helpful Links🧪 See artifacts and rendered test results at hud.pytorch.org/pr/192806
Note: Links to docs will display an error until the docs builds have been completed. ✅ No FailuresAs of commit b44e063 with merge base 731ded9 ( This comment was automatically generated by Dr. CI and updates every 15 minutes. |
bcd80a0 to
2a33380
Compare
Review feedback on pytorch#192806, part of pytorch#142029. The 15 classes in test/functorch/test_eager_transforms.py instantiated via instantiate_device_type_tests now carry a Device suffix, matching TestTypePromotionDevice (pytorch#190990). The three classes that are not device-instantiated keep their names, so the suffix marks exactly the device-instantiated set. This also renames 52 markers in test/dynamo_expected_failures, whose filenames are looked up as f"{class_name}.{test_name}" (common_utils.py:3838). TestJacCPU becomes TestJacDeviceCPU, so without the moves those tests stop being wrapped and turn red in the dynamo shard, which does not run by default. Test Plan: python -m pytest test/functorch/test_eager_transforms.py PYTORCH_TEST_WITH_DYNAMO=1 python -m pytest test/functorch/test_eager_transforms.py \ -k "(TestJacDeviceCPU and test_inplace_cpu) or (TestFunctionalizeDeviceCPU and test_simple_view_cpu)" lintrunner test/functorch/test_eager_transforms.py 723 collected, 719 passed / 2 skipped / 2 xfailed, unchanged from before the rename. The Dynamo run reports both tests skipped, which only happens when the key resolves to a marker file. This PR was authored with the assistance of Claude Code. Co-Authored-By: Claude Opus 5 <[email protected]>
2a33380 to
307465d
Compare
Review feedback on pytorch#192806, part of pytorch#142029. The 15 classes in test/functorch/test_eager_transforms.py instantiated via instantiate_device_type_tests now carry a Device suffix, matching TestTypePromotionDevice (pytorch#190990). The three classes that are not device-instantiated keep their names, so the suffix marks exactly the device-instantiated set. Renaming a test class changes every lookup key of the form f"{class_name}.{test_name}", so three name-keyed mechanisms have to move with it: test/dynamo_expected_failures (52 markers, common_utils.py:3838). TestJacCPU becomes TestJacDeviceCPU; without the moves those tests stop being wrapped and turn red in the dynamo shard, which does not run by default. test/compiled_autograd_skips (2 markers, common_utils.py:3985). Missed in the first version of this commit, which turned three dynamo_wrapped shards red on TestExamplesCorrectnessDeviceCPU.test_maml_omniglot_mechanism_- functional_call_cpu. With the marker orphaned, compiled autograd stayed enabled for the test and it failed with "TypeError: add(): argument 'other' (position 2) must be Tensor, not NoneType" inside compiled_autograd.runtime_wrapper. The test-infra disabled-tests list, which lives outside this repo and so cannot be renamed here. It disables test_jacfwd_different_levels_cpu under TestHessianCPU (pytorch#192284, dynamo only), and the orphaned key un-disabled the test on Python 3.14. Rather than depend on an out-of-repo retitle that reviewers cannot see, the existing skipIf on that test now covers dynamo unconditionally and names pytorch#192284. The alternative, retitling the issue, was rejected because it silently breaks for anyone on an older commit and leaves the same landmine for the next class rename. This over-skips slightly on Python 3.14+, where the pre-existing failure is a real dynamo bug tracked by that issue, not a regression from this change. Test Plan: python -m pytest test/functorch/test_eager_transforms.py PYTORCH_TESTING_DEVICE_ONLY_FOR=cpu PYTORCH_TEST_WITH_DYNAMO=1 \ python -m pytest test/functorch/test_eager_transforms.py -q -p no:xdist lintrunner test/functorch/test_eager_transforms.py 723 collected, 719 passed / 2 skipped / 2 xfailed, unchanged from before the rename. The dynamo run is 334 passed / 43 skipped / 1 xfailed with no failures; before the compiled_autograd_skips move it failed on test_maml_omniglot_mechanism_functional_call_cpu. All five marker directories were swept for the 15 renamed classes against the base commit: dynamo_expected_failures 52/52 moved, compiled_autograd_skips 2/2 moved, and dynamo_skips, inductor_expected_- failures and inductor_skips hold no entries for these classes. This PR was authored with the assistance of Claude Code. Co-Authored-By: Claude Opus 5 <[email protected]>
307465d to
ba48b16
Compare
|
@pytorchbot rebase |
|
@pytorchbot started a rebase job onto refs/remotes/origin/viable/strict. Check the current status here |
…device-generic Two tests in test/functorch/test_eager_transforms.py carried device decorators that reflected how the tests were written rather than a real hardware dependency. Both are pure transform-semantics tests that hold on any device. Fixing them is a prerequisite for enabling XPU on this file (pytorch#142029), since both fail once a second accelerator is instantiated. test_unrelated_hessian allocated W on `device` but built x with a bare torch.randn(M), so x was always CPU. On CPU the mismatch is invisible and the test passes; on any accelerator the W @ x inside the jacrev composition raises "Expected all tensors to be on the same device". The @onlyCPU decorator (and its stale TODO pointing at functorch/issues/12) was masking this latent bug rather than recording a CPU requirement. Passing device= to x fixes the root cause and lets the decorator go. test_linearize_errors checks four argument-validation errors raised by the linearize jvp function; only the last needs two devices, to trigger the device-mismatch branch. It took no `device` parameter, hardcoded CPU primals, and reached for torch.device("cuda") directly, so @onlyCUDA was the only thing keeping it honest. It now takes the injected device and uses it as the move target, with @onlyAccelerator in place of @onlyCUDA so it runs on whichever accelerator is present. The primals stay on CPU deliberately, which a comment now records, since the test needs the two devices to differ. This does change device coverage, so it is not a no-op refactor: test_unrelated_hessian gains accelerator coverage it never had, and test_linearize_errors trades CUDA-only for any-accelerator. CPU coverage is unchanged in both cases -- test_linearize_errors never ran on CPU, as @onlyCUDA skipped it there and @onlyAccelerator still does. Test Plan: Full file on a CPU-only path, matching the pre-change baseline exactly (378 tests, 3 skipped, 1 expected failure): ``` python test/functorch/test_eager_transforms.py ``` The two tests specifically: ``` python test/functorch/test_eager_transforms.py -v \ TestGradTransformCPU.test_unrelated_hessian_cpu \ TestLinearizeCPU.test_linearize_errors_cpu ``` test_linearize_errors_cpu reports skipped ("onlyAccelerator: doesn't run on CPU or meta devices"), which is the same outcome @onlyCUDA produced. Accelerator coverage was verified on a single-XPU host by instantiating this file with only_for=("cpu", "xpu") and allow_xpu=True in a scratch copy; both tests pass on xpu. Enabling XPU in-tree is left to a follow-up. This PR was authored with the assistance of Claude Code. Co-Authored-By: Claude Opus 5 <[email protected]>
…ad alias key
construct_sum_pyop() in test/functorch/test_eager_transforms.py builds a
HigherOrderOperator used by all of TestHigherOrderOperatorInteraction. Its
autograd fallthrough was registered twice, once on AutogradCPU and once on
AutogradCUDA, with identical bodies. Because those are per-backend keys,
dispatching the operator on any third backend finds no kernel and raises:
NotImplementedError: could not find kernel for HigherOrderOperator mysum
at dispatch key DispatchKey.AutogradXPU
That is what all 9 tests in the class hit once the file is instantiated for
XPU, which is the goal of pytorch#142029.
Registering on the Autograd alias key instead covers every backend from one
kernel, so the operator stops being the reason a device is unsupported. The
alternative was to add a third copy on AutogradXPU, which is what the
out-of-tree fork of this file in torch-xpu-ops does; that keeps the same
gap for every other backend, including out-of-tree PrivateUse1 ones, so the
alias key is preferable and is also two fewer lines.
The two bodies were already identical, so collapsing them cannot change
behavior on CPU or CUDA.
Test Plan:
```
python test/functorch/test_eager_transforms.py -k HigherOrderOperatorInteraction
python test/functorch/test_eager_transforms.py
```
9 and 378 tests respectively, both passing, the latter matching the
pre-change baseline (3 skipped, 1 expected failure).
Verified on a single-XPU host that this is sufficient to fix all 9 tests
there, by instantiating a scratch copy of the file with
only_for=("cpu", "xpu") and allow_xpu=True: 18 CPU+XPU tests pass, where
before the 9 XPU ones errored with the NotImplementedError above. Enabling
XPU in-tree is left to a follow-up.
This PR was authored with the assistance of Claude Code.
Co-Authored-By: Claude Opus 5 <[email protected]>
Adds "xpu" to only_for and allow_xpu=True to the instantiation calls in test/functorch/test_eager_transforms.py, so the device-generic test classes run on Intel GPU. Part of pytorch#142029. Both are required today: allow_xpu gates whether XPUTestBase is even a candidate base, and only_for then filters the candidates, so listing "xpu" without allow_xpu instantiates nothing. Keeping allow_xpu is deliberate friction -- it documents that XPU support here is intended rather than inherited -- and is dropped only per the TODO at common_device_type.py:1098. The two prerequisite fixes landed separately: the device-pinned test_unrelated_hessian / test_linearize_errors, and the mysum HigherOrderOperator's per-backend autograd registration. With those in, nothing in this file needs an XPU skip, so no @skipIfXpu and no torch-xpu-ops issues are filed. TestGradTrackingTensorToList is intentionally left off. It is instantiated device-generically, but none of its four tests take a `device` parameter -- they build CPU tensors unconditionally -- so XPU variants would re-run the CPU tests under a different name. A comment records why. It arguably should not be device-instantiated at all, but changing that is unrelated to enabling XPU and would drop its existing CPU test names, so it is left as-is. Note that this file is currently forked wholesale into torch-xpu-ops as test/xpu/functorch/test_eager_transforms_xpu.py, registered in skip_list_common.py with no skips. That fork becomes redundant once this lands and can be deleted separately. Test Plan: Full file on a single-XPU host: ``` python test/functorch/test_eager_transforms.py python test/functorch/test_eager_transforms.py -k _cpu python test/functorch/test_eager_transforms.py -k _xpu ``` 719 tests pass (2 skipped, 2 expected failures), split 349 CPU + 345 XPU + 29 non-device-parameterized. The CPU subset is the same outcome as before this stack (347 passed, 1 skipped, 1 expected failure), so CPU coverage is unaffected. The 349/345 gap is exactly the four TestGradTrackingTensorToList tests held at CPU. test_resnet18_per_sample_grads was the numerics case worth checking, being the only test in the file carrying @with_tf32_off. With torchvision installed both XPU variants pass, and XPU is in fact tighter than CPU: max absolute error 4.23e-06 against the test's atol=1e-3, versus 9.30e-06 on CPU. No tolerance change is needed, and @with_tf32_off is a no-op on XPU since it gates on torch.cuda.is_tf32_supported(). Not covered by local runs: nothing multi-device was exercised, as this host has a single XPU. This PR was authored with the assistance of Claude Code. Co-Authored-By: Claude Opus 5 <[email protected]>
Adds hw_classification to all 18 test classes in test/functorch/test_eager_transforms.py. Part of pytorch#142029. The classification follows the agreed rule: ACCELERATOR when a class is instantiated via instantiate_device_type_tests, GENERIC when it is not. ACCELERATOR covers behavior that must hold consistently across every device including CPU, so a class that mixes CPU and accelerators belongs there -- see TestTorchAutocastDevice in test/test_autocast.py, which is ACCELERATOR and instantiated with no device restriction. That makes the 16 device-instantiated classes here ACCELERATOR, and leaves TestSliceArgnums and TestMakeFunctional as GENERIC since they use instantiate_parametrized_tests or no instantiation at all. There is no class in this file that only makes sense on an accelerator, so unlike other files in this effort there is nothing to split out and no class to rename. The attribute is set on the generic classes and inherited by the per-device classes that instantiate_device_type_tests generates, so it does not need to be applied to the generated names. Test Plan: ``` python -m pytest test/functorch/test_eager_transforms.py python -m pytest test/functorch/test_eager_transforms.py --hw-classification ACCELERATOR python -m pytest test/functorch/test_eager_transforms.py --hw-classification GENERIC python -m pytest test/functorch/test_eager_transforms.py --hw-classification GENERIC ACCELERATOR ``` The unfiltered run is 719 passed, 2 skipped, 2 xfailed. The two selectors partition the file exactly: ``` HW classification mode active (['ACCELERATOR']): total=723, passed=694, unclassified=0, mismatched=29 HW classification mode active (['GENERIC']): total=723, passed=29, unclassified=0, mismatched=694 HW classification mode active (['GENERIC', 'ACCELERATOR']): total=723, passed=723, unclassified=0, mismatched=0 ``` 694 + 29 = 723 with unclassified=0, so every test is tagged exactly once: the 694 device-instantiated tests (CPU and XPU variants both) are ACCELERATOR and the 29 non-parameterized tests are GENERIC. This PR was authored with the assistance of Claude Code. Co-Authored-By: Claude Opus 5 <[email protected]>
Review feedback on pytorch#192806, part of pytorch#142029. The 15 classes in test/functorch/test_eager_transforms.py instantiated via instantiate_device_type_tests now carry a Device suffix, matching TestTypePromotionDevice (pytorch#190990). The three classes that are not device-instantiated keep their names, so the suffix marks exactly the device-instantiated set. Renaming a test class changes every lookup key of the form f"{class_name}.{test_name}", so three name-keyed mechanisms have to move with it: test/dynamo_expected_failures (52 markers, common_utils.py:3838). TestJacCPU becomes TestJacDeviceCPU; without the moves those tests stop being wrapped and turn red in the dynamo shard, which does not run by default. test/compiled_autograd_skips (2 markers, common_utils.py:3985). Missed in the first version of this commit, which turned three dynamo_wrapped shards red on TestExamplesCorrectnessDeviceCPU.test_maml_omniglot_mechanism_- functional_call_cpu. With the marker orphaned, compiled autograd stayed enabled for the test and it failed with "TypeError: add(): argument 'other' (position 2) must be Tensor, not NoneType" inside compiled_autograd.runtime_wrapper. The test-infra disabled-tests list, which lives outside this repo and so cannot be renamed here. It disables test_jacfwd_different_levels_cpu under TestHessianCPU (pytorch#192284, dynamo only), and the orphaned key un-disabled the test on Python 3.14. Rather than depend on an out-of-repo retitle that reviewers cannot see, the existing skipIf on that test now covers dynamo unconditionally and names pytorch#192284. The alternative, retitling the issue, was rejected because it silently breaks for anyone on an older commit and leaves the same landmine for the next class rename. This over-skips slightly on Python 3.14+, where the pre-existing failure is a real dynamo bug tracked by that issue, not a regression from this change. Test Plan: python -m pytest test/functorch/test_eager_transforms.py PYTORCH_TESTING_DEVICE_ONLY_FOR=cpu PYTORCH_TEST_WITH_DYNAMO=1 \ python -m pytest test/functorch/test_eager_transforms.py -q -p no:xdist lintrunner test/functorch/test_eager_transforms.py 723 collected, 719 passed / 2 skipped / 2 xfailed, unchanged from before the rename. The dynamo run is 334 passed / 43 skipped / 1 xfailed with no failures; before the compiled_autograd_skips move it failed on test_maml_omniglot_mechanism_functional_call_cpu. All five marker directories were swept for the 15 renamed classes against the base commit: dynamo_expected_failures 52/52 moved, compiled_autograd_skips 2/2 moved, and dynamo_skips, inductor_expected_- failures and inductor_skips hold no entries for these classes. This PR was authored with the assistance of Claude Code. Co-Authored-By: Claude Opus 5 <[email protected]>
|
Successfully rebased |
ba48b16 to
b44e063
Compare
|
|
There was a problem hiding this comment.
Automated review of b44e063: nothing blocking; ready for human review.
This PR makes the device-generic functorch eager-transform tests run on XPU. It adds hw_classification, renames the classes with a Device suffix, swaps onlyCUDA for onlyAccelerator and moves the HOP autograd kernel onto the Autograd alias key. It also renames the matching dynamo/compiled-autograd skip files. Sub-agent checks found no stale skip/xfail files and no test logic that breaks; the only issues are minor follow-ups.
⚪ 2 non-blocking findings
pytorch/test/functorch/test_eager_transforms.py
Line 5750 in b44e063
Renaming every device class (e.g. TestJacCPU -> TestJacDeviceCPU) means GitHub DISABLED-test issues keyed on the old names stop matching, so those tests silently re-enable. Only # 192284 is handled (line 2726). Check the disabled-tests list for this file's old class names and update the issues.
pytorch/test/functorch/test_eager_transforms.py
Line 2726 in b44e063
The unconditional dynamo skip makes the renamed xfail file dynamo_expected_failures/TestHessianDeviceCUDA.test_jacfwd_different_levels_cuda dead; delete it instead of renaming it. The reason string also cites only # 192284, which is wrong for Python <3.14, and an xfail is preferred over a skip unless the test crashes or hangs.
This review is AI-generated and advisory. Each new automated review replaces the previous one.
|
@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 |
… XPU (pytorch#192806) Part of pytorch#142029. Makes `test/functorch/test_eager_transforms.py` run on Intel GPU (XPU) and classifies its test classes. The file was already almost device-agnostic; two tests were pinned to a device for historical reasons, and one test-local `HigherOrderOperator` registered autograd per-backend rather than on the alias key. With those fixed, nothing in the file needs an XPU skip -- no `@skipIfXpu`, no tracked issues. Hence a stack rather than a one-line change to `only_for`: - **Device-pinned tests made generic.** `test_unrelated_hessian` built `W` on `device` but `x` on CPU unconditionally, which `@onlyCPU` hid. `test_linearize_errors` hardcoded `torch.device("cuda")`; it now takes the injected device with `@onlyAccelerator`, keeping primals on CPU so the two devices still differ. - **`mysum` registered on the `Autograd` alias key** instead of duplicating identical bodies on `AutogradCPU`/`AutogradCUDA`. The per-backend form made all 9 `TestHigherOrderOperatorInteraction` tests raise `NotImplementedError ... DispatchKey.AutogradXPU`; the alias key covers every backend, including out-of-tree `PrivateUse1`. - **XPU enabled** via `"xpu"` in `only_for` plus `allow_xpu=True` on 15 instantiation calls. Both are required: `allow_xpu` gates whether `XPUTestBase` is a candidate, `only_for` then filters. - **`TestGradTrackingTensorToList` is not device-instantiated** -- none of its four tests take a `device` parameter, so per review it has no `instantiate_device_type_tests` call and is GENERIC. - **Device-instantiated classes carry a `Device` suffix**, matching `TestTypePromotionDevice` (pytorch#190990), so the name states whether a class is device-generic. - **`hw_classification` on all 18 classes** -- 15 ACCELERATOR, 3 GENERIC (`TestSliceArgnums`, `TestMakeFunctional`, `TestGradTrackingTensorToList`). ## Name-keyed lookups moved with the rename Renaming a class invalidates every lookup keyed on `f"{class_name}.{test_name}"`. Three mechanisms use that key; the first version of this stack only handled the first, turning three `dynamo_wrapped` shards red: - `test/dynamo_expected_failures` -- 52 markers moved. - `test/compiled_autograd_skips` -- 2 markers moved. Orphaning them left compiled autograd enabled for `test_maml_omniglot_mechanism_functional_call_cpu`, which then failed with `TypeError: add(): argument 'other' (position 2) must be Tensor, not NoneType`. - The test-infra disabled-tests list, which cannot be renamed from this repo. It disables `test_jacfwd_different_levels_cpu (__main__.TestHessianCPU)` for dynamo via pytorch#192284; the orphaned key un-disabled it, failing on Python 3.14. That test's existing `skipIf` now covers dynamo unconditionally and names pytorch#192284, rather than relying on an out-of-repo retitle that reviewers cannot see. Swept all five marker directories for the 15 renamed classes: `dynamo_skips`, `inductor_expected_failures` and `inductor_skips` hold no entries for them. ## Coverage delta Full file on a single-XPU host, before vs. after the stack: | | before | after | |---|---|---| | collected | 378 | 723 | | passed | 376 | 719 | | skipped | 1 | 2 | | xfailed | 1 | 2 | After: 345 CPU + 345 XPU + 33 non-device-parameterized. The non-XPU subset (378 tests) runs 376 passed, 1 skipped, 1 xfailed -- identical to the whole file before the stack, so CPU coverage is preserved exactly. The new skip is `test_linearize_errors_cpu`, which `@onlyAccelerator` skips on CPU exactly as `@onlyCUDA` did before; the new xfail is the XPU variant of an existing CPU xfail. The widened `skipIf` on `test_jacfwd_different_levels` does not affect these numbers -- it only fires under `TEST_WITH_TORCHDYNAMO`. The two selectors partition the file exactly, so every test is tagged once: ``` --hw-classification ACCELERATOR -> total=723, passed=690, unclassified=0, mismatched=33 --hw-classification GENERIC -> total=723, passed=33, unclassified=0, mismatched=690 --hw-classification GENERIC ACCELERATOR -> total=723, passed=723, unclassified=0, mismatched=0 ``` Pull Request resolved: pytorch#192806 Approved by: https://github.com/pbielak, https://github.com/etaf, https://github.com/jansel Co-authored-by: Claude Opus 5 <[email protected]>
) Next PR for synchronizing upstream generalization with local files: 1) **functorch/test_eager_transforms.py** Upstream PR: pytorch/pytorch#192806 Before: 682 passed, 7 skipped, 2 xfailed After: 721 passed, 6 skipped, 2 xfailed Changes: - 11 new test cases: `TestGradTransform::test_inference_mode_*` - 4 new test cases: `TestCompileTransforms::test_compile_dynamic_grad_*` - 2 new test cases: `TestGradTransform::test_pop_dynamic_layer_stack_to_depth_*` - 2 new test cases: `TestFunctionalize::test_multioutput_view_*` - new test case: `TestGradTransform::test_linear_nd_inplace_activation` - new test case: `TestAutogradFunction::test_unwrap_dead_wrappers` - 1 less skipped: `test_unrelated_hessian` now passes on XPU - `TestGradTrackingTensorToList` is no longer device-parametrized: the local copy ran its 4 device-agnostic test cases twice (CPU and XPU), upstream marks the class `GENERIC` and runs them once - the 15 device-parametrized classes are renamed to `Test*Device` 2) **functorch/test_leaf_function.py** Upstream PR: pytorch/pytorch#193950 Before: not run After: 102 passed, 1 skipped 3) **export/test_passes.py** Upstream PR: pytorch/pytorch#196974 Before: 25 passed, 2 xfailed After: 26 passed, 4 skipped, 2 xfailed Changes: - 5 new test cases: `TestMoveToDevicePassCuda`, 4 require CUDA and are skipped, `test_move_to_device_pass_interpreter_only_graph` passes - move `test_move_device_example_inputs`, `test_move_device_submod`, `test_move_device_to` and `test_move_to_device_pass` from `TestPasses` to the new device-parametrized `TestMoveToDevicePassDevice` 4) **export/test_converter.py** Upstream PR: pytorch/pytorch#197113 Before: 46 passed, 2 skipped After: 46 passed, 2 skipped Changes: - move `test_prim_device` from `TestConverter` to the new device-parametrized `TestConverterDevice`, which runs it on both CPU and XPU. The local copy carried it as `test_prim_device_cuda` with a hardcoded `device="xpu:0"`, so a single misnamed test case becomes two properly parametrized ones
…rward AD
AutogradFunctionVariable.call_apply gated all autograd customization behind
`requires_grad and torch.is_grad_enabled()`. Forward-mode duals carry
requires_grad=False, so under torch.func.jvp or a bare forward_ad.dual_level()
that gate is falsy and tracing fell through to the plain-inline branch, which
traces forward() as ordinary Python and discards the custom jvp. The functorch
interpreter then differentiated the inlined primitives with their default
forward-AD rules, so the compiled function returned a different tangent than
eager with no error, no warning and no graph break, even under fullgraph=True.
The existing "Unsupported custom jvp" graph break was nested inside that same
gate, so it was unreachable from forward mode. This hoists the check above the
gate and fires it whenever a forward-AD level is live, detected by scanning the
functorch interpreter stack for a Jvp layer and by checking
forward_ad._current_level for the bare dual_level case. The whole stack is
scanned rather than just its top so that a Jvp layer nested under another
transform, as in vmap(jvp(f)), is still seen. The check matches
TransformType.Jvp specifically rather than _are_functorch_transforms_active()
so that a custom jvp does not start breaking under grad or vmap, where jvp is
never consulted.
The alternative considered was routing apply() through the custom_function_call
HOP whenever functorch transforms are active, mirroring what eager
Function.apply does in C++, which would capture the custom jvp rather than
break on it and would close the same hole for custom vmap rules. That is the
better end state but a substantially larger change; a graph break was chosen
here because it restores exact eager semantics through fallback and is
straightforward to reason about.
One behavioral note for reviewers: a Function defining both a custom vjp and a
custom jvp with grad-requiring inputs now reports the jvp break rather than the
vjp break, since jvp is now checked first. Both are graph breaks with identical
consequences.
This also deletes sixteen entries from test/dynamo_expected_failures/ for
TestAutogradFunctionDevice{CPU,CUDA}.test_function_returns_input (the class was
TestAutogradFunction{CPU,CUDA} before pytorch#192806). Those entries were a recorded
symptom of this very bug rather than an unrelated gap: the test asserts that
jvp(fn, (a,), (a_t,)) raises eager's "An input that has been returned as-is"
error, and under PYTORCH_TEST_WITH_DYNAMO=1 the dropped custom jvp meant nothing
was raised, so all eight parametrizations failed at that one assertion. With the
graph break the call falls back to eager and raises, so they pass and their
entries have to go or the harness reports "Unexpected success". The eight CUDA
entries are the same parametrizations and go for the same reason: neither the
test body nor the break decision depends on the device. No dynamo_wrapped CI
config runs on a GPU runner, so only the CPU half is exercised in CI, and only
the CPU half was run locally.
Fixes pytorch#192985
Test Plan:
```
TORCHINDUCTOR_WINDOWS_TESTS=1 python test/dynamo/test_autograd_function.py
TORCHINDUCTOR_WINDOWS_TESTS=1 python test/dynamo/test_higher_order_ops.py
PYTORCH_TEST_WITH_DYNAMO=1 python test/functorch/test_eager_transforms.py -k test_function_returns_input
PYTORCH_TEST_WITH_DYNAMO=1 python test/test_autograd.py -k test_custom_function_forward_mode -k test_custom_function_save_for_forward
```
test_autograd_function.py: 82 tests, 4 skipped, rest passing.
test_higher_order_ops.py: 224 tests, 8 skipped, 1 expected failure, and one
error in test_vmap_multiply_scalar. That error is a local environment gap
(InvalidCxxCompiler: Compiler: cl is not found), not a regression; it
reproduces with this change reverted.
test_function_returns_input: all 24 parametrizations pass; before the fix
exactly the 8 listed in dynamo_expected_failures fail, each at the same
jvp assertion.
test_autograd.py: 17 tests, all pass, with
test_custom_function_forward_mode_{view,inplace}_checks still failing as
expected, so their entries stay.
The dynamo_expected_failures harness short-circuits on win32
(dynamo_test_failures.find_test_dir returns None), so the runs that confirm the
"Unexpected success" behavior were done with that short-circuit lifted locally
to match Linux CI.
Six tests were added to AutogradFunctionFunctorchTests: the issue repro across
the eager and aot_eager backends, the fullgraph=True raise, the bare
dual_level() variant, and three guards against over-breaking (no forward AD
active, under torch.func.grad, and reverse mode still using the custom
backward).
This change was authored with the assistance of an AI coding agent.
…rward AD
AutogradFunctionVariable.call_apply gated all autograd customization behind
`requires_grad and torch.is_grad_enabled()`. Forward-mode duals carry
requires_grad=False, so under torch.func.jvp or a bare forward_ad.dual_level()
that gate is falsy and tracing fell through to the plain-inline branch, which
traces forward() as ordinary Python and discards the custom jvp. The functorch
interpreter then differentiated the inlined primitives with their default
forward-AD rules, so the compiled function returned a different tangent than
eager with no error, no warning and no graph break, even under fullgraph=True.
The existing "Unsupported custom jvp" graph break was nested inside that same
gate, so it was unreachable from forward mode. This hoists the check above the
gate and fires it whenever a forward-AD level is live, detected by scanning the
functorch interpreter stack for a Jvp layer and by checking
forward_ad._current_level for the bare dual_level case. The whole stack is
scanned rather than just its top so that a Jvp layer nested under another
transform, as in vmap(jvp(f)), is still seen. The check matches
TransformType.Jvp specifically rather than _are_functorch_transforms_active()
so that a custom jvp does not start breaking under grad or vmap, where jvp is
never consulted.
The alternative considered was routing apply() through the custom_function_call
HOP whenever functorch transforms are active, mirroring what eager
Function.apply does in C++, which would capture the custom jvp rather than
break on it and would close the same hole for custom vmap rules. That is the
better end state but a substantially larger change; a graph break was chosen
here because it restores exact eager semantics through fallback and is
straightforward to reason about.
One behavioral note for reviewers: a Function defining both a custom vjp and a
custom jvp with grad-requiring inputs now reports the jvp break rather than the
vjp break, since jvp is now checked first. Both are graph breaks with identical
consequences.
This also deletes sixteen entries from test/dynamo_expected_failures/ for
TestAutogradFunctionDevice{CPU,CUDA}.test_function_returns_input (the class was
TestAutogradFunction{CPU,CUDA} before pytorch#192806). Those entries were a recorded
symptom of this very bug rather than an unrelated gap: the test asserts that
jvp(fn, (a,), (a_t,)) raises eager's "An input that has been returned as-is"
error, and under PYTORCH_TEST_WITH_DYNAMO=1 the dropped custom jvp meant nothing
was raised, so all eight parametrizations failed at that one assertion. With the
graph break the call falls back to eager and raises, so they pass and their
entries have to go or the harness reports "Unexpected success". The eight CUDA
entries are the same parametrizations and go for the same reason: neither the
test body nor the break decision depends on the device. No dynamo_wrapped CI
config runs on a GPU runner, so only the CPU half is exercised in CI, and only
the CPU half was run locally.
Fixes pytorch#192985
Test Plan:
```
TORCHINDUCTOR_WINDOWS_TESTS=1 python test/dynamo/test_autograd_function.py
TORCHINDUCTOR_WINDOWS_TESTS=1 python test/dynamo/test_higher_order_ops.py
PYTORCH_TEST_WITH_DYNAMO=1 python test/functorch/test_eager_transforms.py -k test_function_returns_input
PYTORCH_TEST_WITH_DYNAMO=1 python test/test_autograd.py -k test_custom_function_forward_mode -k test_custom_function_save_for_forward
```
test_autograd_function.py: 82 tests, 4 skipped, rest passing.
test_higher_order_ops.py: 224 tests, 8 skipped, 1 expected failure, and one
error in test_vmap_multiply_scalar. That error is a local environment gap
(InvalidCxxCompiler: Compiler: cl is not found), not a regression; it
reproduces with this change reverted.
test_function_returns_input: all 24 parametrizations pass; before the fix
exactly the 8 listed in dynamo_expected_failures fail, each at the same
jvp assertion.
test_autograd.py: 17 tests, all pass, with
test_custom_function_forward_mode_{view,inplace}_checks still failing as
expected, so their entries stay.
The dynamo_expected_failures harness short-circuits on win32
(dynamo_test_failures.find_test_dir returns None), so the runs that confirm the
"Unexpected success" behavior were done with that short-circuit lifted locally
to match Linux CI.
Six tests were added to AutogradFunctionFunctorchTests: the issue repro across
the eager and aot_eager backends, the fullgraph=True raise, the bare
dual_level() variant, and three guards against over-breaking (no forward AD
active, under torch.func.grad, and reverse mode still using the custom
backward).
This change was authored with the assistance of an AI coding agent.
…tel#5693) Next PR for synchronizing upstream generalization with local files: 1) **functorch/test_eager_transforms.py** Upstream PR: pytorch/pytorch#192806 Before: 682 passed, 7 skipped, 2 xfailed After: 721 passed, 6 skipped, 2 xfailed Changes: - 11 new test cases: `TestGradTransform::test_inference_mode_*` - 4 new test cases: `TestCompileTransforms::test_compile_dynamic_grad_*` - 2 new test cases: `TestGradTransform::test_pop_dynamic_layer_stack_to_depth_*` - 2 new test cases: `TestFunctionalize::test_multioutput_view_*` - new test case: `TestGradTransform::test_linear_nd_inplace_activation` - new test case: `TestAutogradFunction::test_unwrap_dead_wrappers` - 1 less skipped: `test_unrelated_hessian` now passes on XPU - `TestGradTrackingTensorToList` is no longer device-parametrized: the local copy ran its 4 device-agnostic test cases twice (CPU and XPU), upstream marks the class `GENERIC` and runs them once - the 15 device-parametrized classes are renamed to `Test*Device` 2) **functorch/test_leaf_function.py** Upstream PR: pytorch/pytorch#193950 Before: not run After: 102 passed, 1 skipped 3) **export/test_passes.py** Upstream PR: pytorch/pytorch#196974 Before: 25 passed, 2 xfailed After: 26 passed, 4 skipped, 2 xfailed Changes: - 5 new test cases: `TestMoveToDevicePassCuda`, 4 require CUDA and are skipped, `test_move_to_device_pass_interpreter_only_graph` passes - move `test_move_device_example_inputs`, `test_move_device_submod`, `test_move_device_to` and `test_move_to_device_pass` from `TestPasses` to the new device-parametrized `TestMoveToDevicePassDevice` 4) **export/test_converter.py** Upstream PR: pytorch/pytorch#197113 Before: 46 passed, 2 skipped After: 46 passed, 2 skipped Changes: - move `test_prim_device` from `TestConverter` to the new device-parametrized `TestConverterDevice`, which runs it on both CPU and XPU. The local copy carried it as `test_prim_device_cuda` with a hardcoded `device="xpu:0"`, so a single misnamed test case becomes two properly parametrized ones
…rward AD
AutogradFunctionVariable.call_apply gated all autograd customization behind
`requires_grad and torch.is_grad_enabled()`. Forward-mode duals carry
requires_grad=False, so under torch.func.jvp or a bare forward_ad.dual_level()
that gate is falsy and tracing fell through to the plain-inline branch, which
traces forward() as ordinary Python and discards the custom jvp. The functorch
interpreter then differentiated the inlined primitives with their default
forward-AD rules, so the compiled function returned a different tangent than
eager with no error, no warning and no graph break, even under fullgraph=True.
The existing "Unsupported custom jvp" graph break was nested inside that same
gate, so it was unreachable from forward mode. This hoists the check above the
gate and fires it whenever a forward-AD level is live, detected by scanning the
functorch interpreter stack for a Jvp layer and by checking
forward_ad._current_level for the bare dual_level case. The whole stack is
scanned rather than just its top so that a Jvp layer nested under another
transform, as in vmap(jvp(f)), is still seen. The check matches
TransformType.Jvp specifically rather than _are_functorch_transforms_active()
so that a custom jvp does not start breaking under grad or vmap, where jvp is
never consulted.
The alternative considered was routing apply() through the custom_function_call
HOP whenever functorch transforms are active, mirroring what eager
Function.apply does in C++, which would capture the custom jvp rather than
break on it and would close the same hole for custom vmap rules. That is the
better end state but a substantially larger change; a graph break was chosen
here because it restores exact eager semantics through fallback and is
straightforward to reason about.
One behavioral note for reviewers: a Function defining both a custom vjp and a
custom jvp with grad-requiring inputs now reports the jvp break rather than the
vjp break, since jvp is now checked first. Both are graph breaks with identical
consequences.
This also deletes sixteen entries from test/dynamo_expected_failures/ for
TestAutogradFunctionDevice{CPU,CUDA}.test_function_returns_input (the class was
TestAutogradFunction{CPU,CUDA} before pytorch#192806). Those entries were a recorded
symptom of this very bug rather than an unrelated gap: the test asserts that
jvp(fn, (a,), (a_t,)) raises eager's "An input that has been returned as-is"
error, and under PYTORCH_TEST_WITH_DYNAMO=1 the dropped custom jvp meant nothing
was raised, so all eight parametrizations failed at that one assertion. With the
graph break the call falls back to eager and raises, so they pass and their
entries have to go or the harness reports "Unexpected success". The eight CUDA
entries are the same parametrizations and go for the same reason: neither the
test body nor the break decision depends on the device. No dynamo_wrapped CI
config runs on a GPU runner, so only the CPU half is exercised in CI, and only
the CPU half was run locally.
Fixes pytorch#192985
Test Plan:
```
TORCHINDUCTOR_WINDOWS_TESTS=1 python test/dynamo/test_autograd_function.py
TORCHINDUCTOR_WINDOWS_TESTS=1 python test/dynamo/test_higher_order_ops.py
PYTORCH_TEST_WITH_DYNAMO=1 python test/functorch/test_eager_transforms.py -k test_function_returns_input
PYTORCH_TEST_WITH_DYNAMO=1 python test/test_autograd.py -k test_custom_function_forward_mode -k test_custom_function_save_for_forward
```
test_autograd_function.py: 82 tests, 4 skipped, rest passing.
test_higher_order_ops.py: 224 tests, 8 skipped, 1 expected failure, and one
error in test_vmap_multiply_scalar. That error is a local environment gap
(InvalidCxxCompiler: Compiler: cl is not found), not a regression; it
reproduces with this change reverted.
test_function_returns_input: all 24 parametrizations pass; before the fix
exactly the 8 listed in dynamo_expected_failures fail, each at the same
jvp assertion.
test_autograd.py: 17 tests, all pass, with
test_custom_function_forward_mode_{view,inplace}_checks still failing as
expected, so their entries stay.
The dynamo_expected_failures harness short-circuits on win32
(dynamo_test_failures.find_test_dir returns None), so the runs that confirm the
"Unexpected success" behavior were done with that short-circuit lifted locally
to match Linux CI.
Six tests were added to AutogradFunctionFunctorchTests: the issue repro across
the eager and aot_eager backends, the fullgraph=True raise, the bare
dual_level() variant, and three guards against over-breaking (no forward AD
active, under torch.func.grad, and reverse mode still using the custom
backward).
This change was authored with the assistance of an AI coding agent.
Part of #142029.
Makes
test/functorch/test_eager_transforms.pyrun on Intel GPU (XPU) and classifies its test classes.The file was already almost device-agnostic; two tests were pinned to a device for historical reasons, and one test-local
HigherOrderOperatorregistered autograd per-backend rather than on the alias key. With those fixed, nothing in the file needs an XPU skip -- no@skipIfXpu, no tracked issues. Hence a stack rather than a one-line change toonly_for:test_unrelated_hessianbuiltWondevicebutxon CPU unconditionally, which@onlyCPUhid.test_linearize_errorshardcodedtorch.device("cuda"); it now takes the injected device with@onlyAccelerator, keeping primals on CPU so the two devices still differ.mysumregistered on theAutogradalias key instead of duplicating identical bodies onAutogradCPU/AutogradCUDA. The per-backend form made all 9TestHigherOrderOperatorInteractiontests raiseNotImplementedError ... DispatchKey.AutogradXPU; the alias key covers every backend, including out-of-treePrivateUse1."xpu"inonly_forplusallow_xpu=Trueon 15 instantiation calls. Both are required:allow_xpugates whetherXPUTestBaseis a candidate,only_forthen filters.TestGradTrackingTensorToListis not device-instantiated -- none of its four tests take adeviceparameter, so per review it has noinstantiate_device_type_testscall and is GENERIC.Devicesuffix, matchingTestTypePromotionDevice([Test] Change names of test class in test_type_promotion.py #190990), so the name states whether a class is device-generic.hw_classificationon all 18 classes -- 15 ACCELERATOR, 3 GENERIC (TestSliceArgnums,TestMakeFunctional,TestGradTrackingTensorToList).Name-keyed lookups moved with the rename
Renaming a class invalidates every lookup keyed on
f"{class_name}.{test_name}". Three mechanisms use that key; the first version of this stack only handled the first, turning threedynamo_wrappedshards red:test/dynamo_expected_failures-- 52 markers moved.test/compiled_autograd_skips-- 2 markers moved. Orphaning them left compiled autograd enabled fortest_maml_omniglot_mechanism_functional_call_cpu, which then failed withTypeError: add(): argument 'other' (position 2) must be Tensor, not NoneType.test_jacfwd_different_levels_cpu (__main__.TestHessianCPU)for dynamo via DISABLED test_jacfwd_different_levels_cpu (__main__.TestHessianCPU) #192284; the orphaned key un-disabled it, failing on Python 3.14. That test's existingskipIfnow covers dynamo unconditionally and names DISABLED test_jacfwd_different_levels_cpu (__main__.TestHessianCPU) #192284, rather than relying on an out-of-repo retitle that reviewers cannot see.Swept all five marker directories for the 15 renamed classes:
dynamo_skips,inductor_expected_failuresandinductor_skipshold no entries for them.Coverage delta
Full file on a single-XPU host, before vs. after the stack:
After: 345 CPU + 345 XPU + 33 non-device-parameterized. The non-XPU subset (378 tests) runs 376 passed, 1 skipped, 1 xfailed -- identical to the whole file before the stack, so CPU coverage is preserved exactly.
The new skip is
test_linearize_errors_cpu, which@onlyAcceleratorskips on CPU exactly as@onlyCUDAdid before; the new xfail is the XPU variant of an existing CPU xfail. The widenedskipIfontest_jacfwd_different_levelsdoes not affect these numbers -- it only fires underTEST_WITH_TORCHDYNAMO.The two selectors partition the file exactly, so every test is tagged once: