Skip to content

Fix export move_to_device_pass device rewrites - #185105

Closed
jansel wants to merge 3 commits into
gh/jansel/1044/basefrom
gh/jansel/1044/head
Closed

jansel wants to merge 3 commits into
gh/jansel/1044/basefrom
gh/jansel/1044/head

Conversation

@jansel

@jansel jansel commented May 25, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

move_to_device_pass rewrites device-bearing FX nodes and tensor metadata, but it did not recompile the affected GraphModules. Generated Python could therefore retain stale _assert_tensor_metadata device arguments and fail when the moved graph ran directly through ep.graph_module.

Recompile every GraphModule touched by the pass so its callable code matches the rewritten graph. Export also supports interpreter-only graphs whose in-memory custom objects cannot be emitted as Python, so keep that existing fallback by ignoring only the same SyntaxError raised during code generation.

An earlier version tried to preserve parameter identity with .data. Freshly exported state aliases the source module, so that moved source parameters while replacing buffers and left the source module mixed-device. It also corrupted traceable wrapper subclasses by moving only the outer TensorImpl. Retain the existing out-of-place state movement instead, with regressions covering source-module reuse and wrapper-subclass children.

I considered overriding GraphModule.to() so it rewrites graph IR, but exported graphs are device-specific and move_to_device_pass is the supported graph-casting path. Keeping the fix in that pass avoids changing general FX GraphModule.to() semantics.

Fixes #163323
Generated by my agent

Test Plan:

python test/export/test_passes.py TestPasses.test_move_device_to TestPasses.test_move_device_submod TestPasses.test_move_to_device_pass_recompiles_graph_module TestPasses.test_move_to_device_pass_does_not_mutate_source_module TestPasses.test_move_to_device_pass_wrapper_subclass_parameter TestPasses.test_move_to_device_pass_interpreter_only_graph TestPasses.test_move_to_device_pass TestPasses.test_move_device_example_inputs
python test/export/test_export.py TestOneOffModelExportResult.test_assert_tensor_metadata_device_index
lintrunner -a

[ghstack-poisoned]
@pytorch-bot

pytorch-bot Bot commented May 25, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

✅ No Failures

As of commit df67355 with merge base ef7af40 (image):
💚 Looks good so far! There are no failures yet. 💚

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

@jansel

jansel commented May 25, 2026

Copy link
Copy Markdown
Contributor Author

@claude review these changes

@claude

claude Bot commented May 25, 2026 •

Copy link
Copy Markdown

Claude finished @jansel's task in 1m 11s —— View job


Code Review: PR #185105

  • Read the PR diff and changed files
  • Analyze the implementation changes
  • Review tests for coverage
  • Post review feedback

Summary: This is a well-motivated fix addressing two real bugs in move_to_device_pass: missing recompilation after graph rewrites, and unnecessary parameter replacement that breaks optimizer references. The implementation is clean and follows established PyTorch patterns.


Findings

The recompile fix (torch/export/passes/__init__.py:118) — Correct and clearly necessary. Without it, ep.graph_module.code returns stale Python source containing old device strings, so executing the GraphModule directly could hit _assert_tensor_metadata assertions against the wrong device.

Parameter identity preservation (_move_parameter, lines 43–60) — Mirrors the logic in torch.nn.Module._apply (torch/nn/modules/module.py:937–965). One minor deviation: Module._apply also checks not isinstance(tensor_applied, FakeTensor) before using .data =. In practice this shouldn't matter for export (you wouldn't move to a device that produces FakeTensors), but worth noting for completeness.

Shared parameter deduplication (lines 63–69) — Using id(v) as the cache key is safe here because ep.state_dict holds references to all values throughout the loop, preventing GC from reusing IDs.

Grad handling (lines 52–59) — Correctly applies the same compatible-shallow-copy pattern to gradients.

Minor observations

  1. torch.__future__ flags not consulted — Module._apply also respects get_overwrite_module_params_on_conversion() and get_swap_module_params_on_conversion(). The PR always uses set_data when types are compatible, which matches the current default behavior. For the export use case this is fine since ExportedProgram parameters aren't part of a live module's _parameters dict, so swap_tensors semantics don't apply.

  2. Test coverage is solid — The three new tests cover: recompilation correctness (run the module after move), incompatible move (CPU→meta replaces the Parameter object), and compatible move (CPU→CUDA preserves identity, grad, and optimizer references). Good edge case selection.

  3. Existing tests simplified — Removing the manual recompile() calls from test_move_device_to and test_move_device_submod is correct and serves as validation that the pass now handles this internally.

Verdict

LGTM. The fix is minimal, well-tested, and correctly addresses both reported issues. The parameter-identity semantics align with how nn.Module.to() works for compatible device moves, which is the right mental model for users.


@jansel
jansel marked this pull request as ready for review May 25, 2026 23:27
@jansel
jansel requested review from choijon5, ethche and yiming0416 and removed request for angelayi, avikchaudhuri, tugsbayasgalan, ydwu4 and zhxchen17 May 25, 2026 23:27
@jansel jansel added the agentic Created by an AI agent label Jun 9, 2026
@jansel
jansel requested a review from mlazos June 10, 2026 23:19
@jansel
jansel requested a review from frgossen June 26, 2026 03:29
@eellison
eellison removed request for eellison and ethche August 19, 2026 21:40
@jansel
jansel requested a review from bobrenjc93 August 23, 2026 09:16
Comment thread torch/export/passes/__init__.py Outdated
with torch.no_grad():
param_applied = _move_tensor(param)
if torch._has_compatible_shallow_copy_type(param, param_applied):
param.data = param_applied

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.

For freshly exported programs, ep.state_dict contains the source module's actual Parameter objects. Assigning param.data therefore moves the source module's parameters, while buffers below are only replaced in the EP dictionary, leaving a retained source module mixed-device and unusable. Either detach EP state before this mutation or establish consistent, documented alias semantics for all state, with a source-module reuse test.

@jansel jansel Aug 25, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

My agent says

Addressed by removing the in-place parameter-data mutation and retaining the existing out-of-place state replacement. The new regression verifies that both parameters and buffers in the retained source module stay on CPU and remain usable after the exported program moves to CUDA.

Comment thread torch/export/passes/__init__.py Outdated
def _move_parameter(param: torch.nn.Parameter) -> torch.nn.Parameter:
with torch.no_grad():
param_applied = _move_tensor(param)
if torch._has_compatible_shallow_copy_type(param, param_applied):

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 .data path is unsafe for traceable wrapper-subclass parameters. Export supports parameters such as TwoTensor, whose child tensors live in Python attributes; .data updates only the outer TensorImpl, leaving those children on the original device. Mirror Module._apply's is_traceable_wrapper_subclass/swap_tensors path and add a subclass-parameter regression test.

@jansel jansel Aug 25, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

My agent says

Addressed by removing the unsafe in-place path. Wrapper-subclass parameters now use the existing out-of-place Tensor.to() path, which moves both the outer wrapper and its child tensors. The new TwoTensor regression verifies that the moved exported state is CUDA-valid while the retained source state remains CPU-valid.

Comment thread torch/export/passes/__init__.py Outdated
else v,
node.meta.get("val"),
)
m.recompile()

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.

ExportedProgram deliberately catches SyntaxError during GraphModule code generation and retains the graph for interpreter execution when custom objects cannot be emitted as Python. This unconditional recompile() retries that unsupported generation without a catch, so moving such a valid interpreter-only EP now raises. Preserve the fallback and test an EP containing an in-memory custom-object constant.

@jansel jansel Aug 25, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

My agent says

Addressed by catching only SyntaxError from GraphModule.recompile(), matching the existing ExportedProgram interpreter-only fallback. The new regression injects an in-memory custom object, rewrites device-bearing IR from CPU to meta, and verifies execution through torch.fx.Interpreter.

[ghstack-poisoned]
jansel added a commit that referenced this pull request Aug 25, 2026
`move_to_device_pass` rewrites device-bearing FX nodes and tensor metadata, but it did not recompile the affected GraphModules. Generated Python could therefore retain stale `_assert_tensor_metadata` device arguments and fail when the moved graph ran directly through `ep.graph_module`.

Recompile every GraphModule touched by the pass so its callable code matches the rewritten graph. Export also supports interpreter-only graphs whose in-memory custom objects cannot be emitted as Python, so keep that existing fallback by ignoring only the same `SyntaxError` raised during code generation.

An earlier version tried to preserve parameter identity with `.data`. Freshly exported state aliases the source module, so that moved source parameters while replacing buffers and left the source module mixed-device. It also corrupted traceable wrapper subclasses by moving only the outer TensorImpl. Retain the existing out-of-place state movement instead, with regressions covering source-module reuse and wrapper-subclass children.

I considered overriding `GraphModule.to()` so it rewrites graph IR, but exported graphs are device-specific and `move_to_device_pass` is the supported graph-casting path. Keeping the fix in that pass avoids changing general FX `GraphModule.to()` semantics.

Fixes #163323
Generated by my agent

Test Plan:
```bash
python test/export/test_passes.py TestPasses.test_move_device_to TestPasses.test_move_device_submod TestPasses.test_move_to_device_pass_recompiles_graph_module TestPasses.test_move_to_device_pass_does_not_mutate_source_module TestPasses.test_move_to_device_pass_wrapper_subclass_parameter TestPasses.test_move_to_device_pass_interpreter_only_graph TestPasses.test_move_to_device_pass TestPasses.test_move_device_example_inputs
```

```bash
python test/export/test_export.py TestOneOffModelExportResult.test_assert_tensor_metadata_device_index
```

```bash
lintrunner -a
```

ghstack-source-id: 5ccc2ad
Pull-Request: #185105
jansel added a commit that referenced this pull request Aug 25, 2026
`move_to_device_pass` rewrites device-bearing FX nodes and tensor metadata, but it did not recompile the affected GraphModules. Generated Python could therefore retain stale `_assert_tensor_metadata` device arguments and fail when the moved graph ran directly through `ep.graph_module`.

Recompile every GraphModule touched by the pass so its callable code matches the rewritten graph. Export also supports interpreter-only graphs whose in-memory custom objects cannot be emitted as Python, so keep that existing fallback by ignoring only the same `SyntaxError` raised during code generation.

An earlier version tried to preserve parameter identity with `.data`. Freshly exported state aliases the source module, so that moved source parameters while replacing buffers and left the source module mixed-device. It also corrupted traceable wrapper subclasses by moving only the outer TensorImpl. Retain the existing out-of-place state movement instead, with regressions covering source-module reuse and wrapper-subclass children.

I considered overriding `GraphModule.to()` so it rewrites graph IR, but exported graphs are device-specific and `move_to_device_pass` is the supported graph-casting path. Keeping the fix in that pass avoids changing general FX `GraphModule.to()` semantics.

Fixes #163323
Generated by my agent

Test Plan:
```bash
python test/export/test_passes.py TestPasses.test_move_device_to TestPasses.test_move_device_submod TestPasses.test_move_to_device_pass_recompiles_graph_module TestPasses.test_move_to_device_pass_does_not_mutate_source_module TestPasses.test_move_to_device_pass_wrapper_subclass_parameter TestPasses.test_move_to_device_pass_interpreter_only_graph TestPasses.test_move_to_device_pass TestPasses.test_move_device_example_inputs
```

```bash
python test/export/test_export.py TestOneOffModelExportResult.test_assert_tensor_metadata_device_index
```

```bash
lintrunner -a
```

ghstack-source-id: 5ccc2ad
Pull-Request: #185105
@jansel
jansel requested review from AmesingFlank and removed request for yiming0416 September 4, 2026 01:26
Comment thread torch/export/passes/__init__.py Resolved
[ghstack-poisoned]
jansel added a commit that referenced this pull request Sep 23, 2026
`move_to_device_pass` rewrites device-bearing FX nodes and tensor metadata, but it did not recompile the affected GraphModules. Generated Python could therefore retain stale `_assert_tensor_metadata` device arguments and fail when the moved graph ran directly through `ep.graph_module`.

Recompile every GraphModule touched by the pass so its callable code matches the rewritten graph. Export also supports interpreter-only graphs whose in-memory custom objects cannot be emitted as Python, so keep that existing fallback by ignoring only the same `SyntaxError` raised during code generation.

An earlier version tried to preserve parameter identity with `.data`. Freshly exported state aliases the source module, so that moved source parameters while replacing buffers and left the source module mixed-device. It also corrupted traceable wrapper subclasses by moving only the outer TensorImpl. Retain the existing out-of-place state movement instead, with regressions covering source-module reuse and wrapper-subclass children.

I considered overriding `GraphModule.to()` so it rewrites graph IR, but exported graphs are device-specific and `move_to_device_pass` is the supported graph-casting path. Keeping the fix in that pass avoids changing general FX `GraphModule.to()` semantics.

Fixes #163323
Generated by my agent

Test Plan:
```bash
python test/export/test_passes.py TestPasses.test_move_device_to TestPasses.test_move_device_submod TestPasses.test_move_to_device_pass_recompiles_graph_module TestPasses.test_move_to_device_pass_does_not_mutate_source_module TestPasses.test_move_to_device_pass_wrapper_subclass_parameter TestPasses.test_move_to_device_pass_interpreter_only_graph TestPasses.test_move_to_device_pass TestPasses.test_move_device_example_inputs
```

```bash
python test/export/test_export.py TestOneOffModelExportResult.test_assert_tensor_metadata_device_index
```

```bash
lintrunner -a
```

ghstack-source-id: 834edda
Pull-Request: #185105
@jansel

jansel commented Sep 25, 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 Sep 25, 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

SHIHAIFENG15 added a commit to SHIHAIFENG15/pytorch that referenced this pull request Oct 12, 2026
pytorch#196974 already moved these tests onto instantiate_device_type_tests for CUDA and XPU, and pytorch#185105 added the CUDA recompile regressions. Keep that code, and open the device class to other non-CPU backends with except_for="cpu" while retaining allow_xpu=True.

Test Plan:
```
python -m pytest test/export/test_passes.py --collect-only -q
# 28 tests collected on CPU. TestMoveToDevicePassDevice is not generated without an accelerator, which matches except_for="cpu".
```
pytorchmergebot pushed a commit to tszulist-hbn/pytorch that referenced this pull request Nov 13, 2026
…rators

Four move_to_device_pass tests sat in TestMoveToDevicePassCuda behind
skipIf(not TEST_CUDA) with "cuda:0" hard-coded, so XPU and other
accelerators skipped them. Nothing in them is CUDA-specific. They check
that the moved GraphModule and its nested torch.cond submodules are
recompiled, that the source module's parameters and buffers are not
mutated, and that wrapper-subclass parameters move with their inner
tensors.

Root cause: pytorch#185105 added the tests behind a TEST_CUDA gate. pytorch#196974
moved the four older move_to_device_pass tests into the device-generic
TestMoveToDevicePassDevice but left these behind, and pytorch#191079 then
tagged their class CUDA to match its gate.

Move them into TestMoveToDevicePassDevice with a device parameter, drop
the gates and replace each "cuda:0" with device. The instantiated
primary device always carries an index (cuda:N, xpu:N,
<privateuse1>:N), so the code and device-equality assertions behave as
before on CUDA. After the previous commit the CUDA class is empty, so
delete it and the now-unused TEST_CUDA import.

XPU, PrivateUse1 and HPU gain the four tests. CUDA keeps them as
TestMoveToDevicePassDeviceCUDA::<name>_cuda. On a machine without an
accelerator they are no longer collected instead of being reported as
skipped, the same trade-off pytorch#196974 made. Widening the gate to TEST_CUDA
or TEST_XPU was the alternative; it keeps the hard-coded device and
leaves PrivateUse1 out.

See intel/torch-xpu-ops#5994.

Test Plan:

The same AST comparison as the previous commit: the four methods match
the originals once device maps back to 'cuda:0' and the device parameter
and TEST_CUDA skip are dropped. The other 40 methods are unchanged.

On an Intel Data Center GPU Max 1550:

```
python test/export/test_passes.py -v -k move_device -k move_to_device
python test/export/test_passes.py
```

All 8 TestMoveToDevicePassDeviceXPU tests pass, 4 of them new. The whole
file goes from OK (skipped=4, expected failures=2) to
OK (expected failures=2) with the same 39 tests. The only ID changes are
TestMoveToDevicePassCuda::<name> ->
TestMoveToDevicePassDeviceXPU::<name>_xpu. CUDA was not run locally.

Authored with an AI assistant (Claude Code).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
pytorchmergebot pushed a commit to tszulist-hbn/pytorch that referenced this pull request Nov 16, 2026
…rators

Four move_to_device_pass tests sat in TestMoveToDevicePassCuda behind
skipIf(not TEST_CUDA) with "cuda:0" hard-coded, so XPU and other
accelerators skipped them. Nothing in them is CUDA-specific. They check
that the moved GraphModule and its nested torch.cond submodules are
recompiled, that the source module's parameters and buffers are not
mutated, and that wrapper-subclass parameters move with their inner
tensors.

Root cause: pytorch#185105 added the tests behind a TEST_CUDA gate. pytorch#196974
moved the four older move_to_device_pass tests into the device-generic
TestMoveToDevicePassDevice but left these behind, and pytorch#191079 then
tagged their class CUDA to match its gate.

Move them into TestMoveToDevicePassDevice with a device parameter, drop
the gates and replace each "cuda:0" with device. The instantiated
primary device always carries an index (cuda:N, xpu:N,
<privateuse1>:N), so the code and device-equality assertions behave as
before on CUDA. After the previous commit the CUDA class is empty, so
delete it and the now-unused TEST_CUDA import.

XPU, PrivateUse1 and HPU gain the four tests. CUDA keeps them as
TestMoveToDevicePassDeviceCUDA::<name>_cuda. On a machine without an
accelerator they are no longer collected instead of being reported as
skipped, the same trade-off pytorch#196974 made. Widening the gate to TEST_CUDA
or TEST_XPU was the alternative; it keeps the hard-coded device and
leaves PrivateUse1 out.

See intel/torch-xpu-ops#5994.

Test Plan:

The same AST comparison as the previous commit: the four methods match
the originals once device maps back to 'cuda:0' and the device parameter
and TEST_CUDA skip are dropped. The other 40 methods are unchanged.

On an Intel Data Center GPU Max 1550:

```
python test/export/test_passes.py -v -k move_device -k move_to_device
python test/export/test_passes.py
```

All 8 TestMoveToDevicePassDeviceXPU tests pass, 4 of them new. The whole
file goes from OK (skipped=4, expected failures=2) to
OK (expected failures=2) with the same 39 tests. The only ID changes are
TestMoveToDevicePassCuda::<name> ->
TestMoveToDevicePassDeviceXPU::<name>_xpu. CUDA was not run locally.

Authored with an AI assistant (Claude Code).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
pytorchmergebot pushed a commit to tszulist-hbn/pytorch that referenced this pull request Nov 18, 2026
…rators

Four move_to_device_pass tests sat in TestMoveToDevicePassCuda behind
skipIf(not TEST_CUDA) with "cuda:0" hard-coded, so XPU and other
accelerators skipped them. Nothing in them is CUDA-specific. They check
that the moved GraphModule and its nested torch.cond submodules are
recompiled, that the source module's parameters and buffers are not
mutated, and that wrapper-subclass parameters move with their inner
tensors.

Root cause: pytorch#185105 added the tests behind a TEST_CUDA gate. pytorch#196974
moved the four older move_to_device_pass tests into the device-generic
TestMoveToDevicePassDevice but left these behind, and pytorch#191079 then
tagged their class CUDA to match its gate.

Move them into TestMoveToDevicePassDevice with a device parameter, drop
the gates and replace each "cuda:0" with device. The instantiated
primary device always carries an index (cuda:N, xpu:N,
<privateuse1>:N), so the code and device-equality assertions behave as
before on CUDA. After the previous commit the CUDA class is empty, so
delete it and the now-unused TEST_CUDA import.

XPU, PrivateUse1 and HPU gain the four tests. CUDA keeps them as
TestMoveToDevicePassDeviceCUDA::<name>_cuda. On a machine without an
accelerator they are no longer collected instead of being reported as
skipped, the same trade-off pytorch#196974 made. Widening the gate to TEST_CUDA
or TEST_XPU was the alternative; it keeps the hard-coded device and
leaves PrivateUse1 out.

See intel/torch-xpu-ops#5994.

Test Plan:

The same AST comparison as the previous commit: the four methods match
the originals once device maps back to 'cuda:0' and the device parameter
and TEST_CUDA skip are dropped. The other 40 methods are unchanged.

On an Intel Data Center GPU Max 1550:

```
python test/export/test_passes.py -v -k move_device -k move_to_device
python test/export/test_passes.py
```

All 8 TestMoveToDevicePassDeviceXPU tests pass, 4 of them new. The whole
file goes from OK (skipped=4, expected failures=2) to
OK (expected failures=2) with the same 39 tests. The only ID changes are
TestMoveToDevicePassCuda::<name> ->
TestMoveToDevicePassDeviceXPU::<name>_xpu. CUDA was not run locally.

Authored with an AI assistant (Claude Code).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@github-actions
github-actions Bot deleted the gh/jansel/1044/head branch November 30, 2026 01:47
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agentic Created by an AI agent ciflow/trunk Trigger trunk jobs on your pull request Merged release notes: export

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants