[export] Bug Report: module.to(device) on exported programs causes assertion failures (device-agnostic export broken since 2.8)
- Dominant language
- Python
- Stars
- 103k
- Forks
- 29.5k
- PR merge metrics
- PR metrics pending
Description
### 🐛 Describe the bug
When casting an ExportedProgram to a different device (a common strategy for device-agnostic export), the IR contains a hardcoded assertion introduced in [PR #149235](https://github.com/pytorch/pytorch/pull/149235) (cc @chauhang @penguinwu @avikchaudhuri @gmagogsfm @zhxchen17 @tugsbayasgalan @angelayi @suo @ydwu4 @pianpwk )
```
_assert_tensor_metadata_default = torch.ops.aten._assert_tensor_metadata.default(idx, dtype = torch.int64, device = 'cuda:0', layout = torch.strided);
```
This assertion is not updated when calling module.to(device), leading to runtime failures, even though tensors have been correctly moved.
### Why This Is a Problem
We are developing a device-agnostic export strategy, where exported modules can be seamlessly recast to different devices in production. The new IR behavior breaks this assumption by hardcoding device in the assert statement at export time.
The issue is particularly confusing because it only manifests at runtime, not during export. As a result, models that export successfully in PyTorch 2.8 may fail unexpectedly in production—even though the same workflow worked without issue in 2.7.
```python
# Minimal Repro
import torch, torch.nn as nn
from torch import export
import traceback
class M(nn.Module):
def forward(self, x):
return x.long().sum()
m = M()
ep = export.export(m, (torch.zeros(4, dtype=torch.float32),))
gm = ep.module()
gm_cuda = gm.to("cuda:0")
gm_cuda(torch.ones(4, dtype=torch.float32, device="cuda:0"))
```
Error Trace
```
Traceback (most recent call last):
File "/home/jobuser/torch_test.py", line 14, in
gm_cuda(torch.ones(4, dtype=torch.float32, device="cuda:0"))
File "/home/jobuser/.local/lib/python3.10/site-packages/torch/fx/graph_module.py", line 905, in call_wrapped
return self._wrapped_call(self, *args, **kwargs)
File "/home/jobuser/.local/lib/python3.10/site-packages/torch/fx/graph_module.py", line 425, in __call__
raise e
File "/home/jobuser/.local/lib/python3.10/site-packages/torch/fx/graph_module.py", line 412, in __call__
return super(self.cls, obj).__call__(*args, **kwargs) # type: ignore[misc]
File "/home/jobuser/.local/lib/python3.10/site-packages/torch/nn/modules/module.py", line 1774, in _wrapped_call_impl
return self._call_impl(*args, **kwargs)
File "/home/jobuser/.local/lib/python3.10/site-packages/torch/nn/modules/module.py", line 1880, in _call_impl
return inner()
File "/home/jobuser/.local/lib/python3.10/site-packages/torch/nn/modules/module.py", line 1828, in inner
result = forward_call(*args, **kwargs)
File ".8", line 6, in forward
File "/home/jobuser/.local/lib/python3.10/site-packages/torch/_ops.py", line 829, in __call__
return self._op(*args, **kwargs)
RuntimeError: Tensor device mismatch! Expected: cpu, Got: cuda:0
```
### Workarounds (discussed with @supercharleszhu)
#### 1. Disable aten.to metadata assertions
```
from torch._export.utils import _disable_aten_to_metadata_assertions
with _disable_aten_to_metadata_assertions():
ep = export.export(m, (torch.zeros(4, dtype=torch.long),), strict=True)
```
Drawback: Disables optimizations like operator fusion that depend on metadata assertions.
#### 2. Use passes.move_to_device_pass
Drawback: Creates a new parameter group, requiring relinking optimizer states if used for training.
### Proposed Fix
Add a GraphModule.to() override that updates IR metadata alongside parameters/buffers:
```
class GraphModule(torch.nn.Module):
...
def to(self, *args, **kwargs):
# 1. Move buffers/params
result = super(GraphModule, self).to(*args, **kwargs)
# 2. Parse device
device, dtype, non_blocking, memory_format = torch._C._nn._parse_to(*args, **kwargs)
if device is None:
return result
new_device = torch.device(device)
# 3. Update IR metadata
for node in self.graph.nodes:
if "device" in node.kwargs:
node.kwargs = {**node.kwargs, "device": new_device}
if node.op == "call_function" and node.target == torch.ops.aten.to.device:
args = list(node.args)
args[1] = new_device
node.args = tuple(args)
if "val" in node.meta:
node.meta["val"] = torch.utils._pytree.tree_map(
lambda v: v.to(new_device) if isinstance(v, torch.Tensor) else v,
node.meta["val"],
)
self.recompile()
return result
```
### Versions
Collecting environment information...
PyTorch version: 2.8.0.0+cu128
Is debug build: False
CUDA used to build PyTorch: 12.8
ROCM used to build PyTorch: N/A
OS: CBL-Mariner/Linux (x86_64)
GCC version: (GCC) 11.2.0
Clang version: Could not collect
CMake version: version 3.21.4
Libc version: glibc-2.35
Python version: 3.10.14 (main, Jul 14 2024, 22:24:12) [GCC 11.2.0] (64-bit runtime)
Python platform: Linux-5.15.180.1-1.cm2-x86_64-with-glibc2.35
Is CUDA available: True
CUDA runtime version: 12.8.93
CUDA_MODULE_LOADING set to: LAZY
GPU models and configuration:
GPU 0: NVIDIA H100 80GB HBM3
GPU 1: NVIDIA H100 80GB HBM3
Nvidia driver version: 550.163.01
cuDNN version: Probably one of the following:
/usr/lib/libcudnn.so.9.3.0
/usr/lib/libcudnn_adv.so.9.3.0
/usr/lib/libcudnn_cnn.so.9.3.0
/usr/lib/libcudnn_engines_precompiled.so.9.3.0
/usr/lib/libcudnn_engines_runtime_compiled.so.9.3.0
/usr/lib/libcudnn_graph.so.9.3.0
/usr/lib/libcudnn_heuristic.so.9.3.0
/usr/lib/libcudnn_ops.so.9.3.0
Is XPU available: False
HIP runtime version: N/A
MIOpen runtime version: N/A
Is XNNPACK available: True
CPU:
Architecture: x86_64
CPU op-mode(s): 32-bit, 64-bit
Address sizes: 52 bits physical, 57 bits virtual
Byte Order: Little Endian
CPU(s): 256
On-line CPU(s) list: 0-255
Vendor ID: AuthenticAMD
Model name: AMD EPYC 9554 64-Core Processor
CPU family: 25
Model: 17
Thread(s) per core: 2
Core(s) per socket: 64
Socket(s): 2
Stepping: 1
Frequency boost: enabled
CPU max MHz: 3100.0000
CPU min MHz: 1500.0000
BogoMIPS: 6199.90
Flags: fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush mmx fxsr sse sse2 ht syscall nx mmxext fxsr_opt pdpe1gb rdtscp lm constant_tsc rep_good nopl nonstop_tsc cpuid extd_apicid aperfmperf rapl pni pclmulqdq monitor ssse3 fma cx16 pcid sse4_1 sse4_2 x2apic movbe popcnt aes xsave avx f16c rdrand lahf_lm cmp_legacy svm extapic cr8_legacy abm sse4a misalignsse 3dnowprefetch osvw ibs skinit wdt tce topoext perfctr_core perfctr_nb bpext perfctr_llc mwaitx cpb cat_l3 cdp_l3 invpcid_single hw_pstate ssbd mba ibrs ibpb stibp ibrs_enhanced vmmcall fsgsbase bmi1 avx2 smep bmi2 erms invpcid cqm rdt_a avx512f avx512dq rdseed adx smap avx512ifma clflushopt clwb avx512cd sha_ni avx512bw avx512vl xsaveopt xsavec xgetbv1 xsaves cqm_llc cqm_occup_llc cqm_mbm_total cqm_mbm_local avx512_bf16 clzero irperf xsaveerptr rdpru wbnoinvd amd_ppin arat npt lbrv svm_lock nrip_save tsc_scale vmcb_clean flushbyasid decodeassists pausefilter pfthreshold avic v_vmsave_vmload vgif v_spec_ctrl avx512vbmi umip pku ospke avx512_vbmi2 gfni vaes vpclmulqdq avx512_vnni avx512_bitalg avx512_vpopcntdq rdpid overflow_recov succor smca fsrm flush_l1d
Virtualization: AMD-V
L1d cache: 4 MiB (128 instances)
L1i cache: 4 MiB (128 instances)
L2 cache: 128 MiB (128 instances)
L3 cache: 512 MiB (16 instances)
NUMA node(s): 2
NUMA node0 CPU(s): 0-63,128-191
NUMA node1 CPU(s): 64-127,192-255
Vulnerability Gather data sampling: Not affected
Vulnerability Itlb multihit: Not affected
Vulnerability L1tf: Not affected
Vulnerability Mds: Not affected
Vulnerability Meltdown: Not affected
Vulnerability Mmio stale data: Not affected
Vulnerability Reg file data sampling: Not affected
Vulnerability Retbleed: Not affected
Vulnerability Spec rstack overflow: Mitigation; safe RET
Vulnerability Spec store bypass: Mitigation; Speculative Store Bypass disabled via prctl and seccomp
Vulnerability Spectre v1: Mitigation; usercopy/swapgs barriers and __user pointer sanitization
Vulnerability Spectre v2: Mitigation; Retpolines; IBPB conditional; IBRS_FW; STIBP always-on; RSB filling; PBRSB-eIBRS Not affected; BHI Not affected
Vulnerability Srbds: Not affected
Vulnerability Tsx async abort: Not affected
Versions of relevant libraries:
[pip3] mypy-extensions==1.0.0
[pip3] numpy==1.26.4
[pip3] optree==0.14.0
[pip3] torch==2.8.0.0+cu128
[pip3] torchmetrics==1.8.2
[pip3] torchvision==0.22.0.1+cu128
[pip3] triton==3.0.0
[conda] Could not collect
Contributor guide
Assessment
This issue has not been assessed yet.