Repository: pytorch
Issue: Loaded torch.jit traced module treats dtypes incorrectly in autograd
Labels: oncall: jit

### 🐛 Describe the bug

The following minimal example shows the issue I encountered.

- I have a model that relies on implicit type conversion when multiplying a float with a double.
- Conditions
    - using torch.autograd.grad on the output of a torch.jit traced model
    - after saving the model to a file and loading it
    - and doing this for the _second time_.
- This fails with the message:
```
Traceback of TorchScript (most recent call last):
  File "<string>", line 75, in <backward op>

                weight_size = weight.size()
                grad_input = torch.matmul(grad_output, weight)
                             ~~~~~~~~~~~~ <--- HERE
                grad_weight = torch.matmul(grad_output.reshape(-1, weight_size[0]).t(), input.reshape(-1, weight_size[1]))
                # Note: calling unchecked_unwrap_optional is only safe, when we
RuntimeError: expected scalar type Double but found Float
```

Example:

```python
import torch


class WLS(torch.nn.Module):
    def __init__(self):
        super().__init__()
        self.model = torch.nn.Linear(2, 1)

    def forward(self, x, weights):
        return torch.sum(self.model(x) * weights)
        # return torch.sum(self.model(x).to(weights.dtype) * weights)   <-- this fixes the bug.


wls = WLS()

for _ in range(2):
    x = torch.randn(10, 2, requires_grad=True)
    weights = torch.randn(10, 1, dtype=torch.float64)
    out = wls(x, weights)
    torch.autograd.grad(out, x, torch.ones_like(out))

traced_wls = torch.jit.trace_module(wls, {"forward": [x, weights]})

for _ in range(2):
    x = torch.randn(10, 2, requires_grad=True)
    weights = torch.randn(10, 1, dtype=torch.float64)
    out = traced_wls(x, weights)
    torch.autograd.grad(out, x, torch.ones_like(out))

traced_wls.save("saved.pt")
loaded_wls = torch.jit.load("saved.pt")

for _ in range(2):
    x = torch.randn(10, 2, requires_grad=True)
    weights = torch.randn(10, 1, dtype=torch.float64)
    out = loaded_wls(x, weights)
    torch.autograd.grad(out, x, torch.ones_like(out))  # Fails the second time.
```



### Versions

PyTorch version: 2.0.1
Is debug build: False
CUDA used to build PyTorch: 11.7
ROCM used to build PyTorch: N/A

OS: Ubuntu 22.04.3 LTS (x86_64)
GCC version: (Ubuntu 11.4.0-1ubuntu1~22.04) 11.4.0
Clang version: Could not collect
CMake version: Could not collect
Libc version: glibc-2.35

Python version: 3.10.13 | packaged by conda-forge | (main, Oct 26 2023, 18:07:37) [GCC 12.3.0] (64-bit runtime)
Python platform: Linux-5.15.133.1-microsoft-standard-WSL2-x86_64-with-glibc2.35
Is CUDA available: False
CUDA runtime version: No CUDA
CUDA_MODULE_LOADING set to: N/A
GPU models and configuration: No CUDA
Nvidia driver version: No CUDA
cuDNN version: No CUDA
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:                      39 bits physical, 48 bits virtual
Byte Order:                         Little Endian
CPU(s):                             8
On-line CPU(s) list:                0-7
Vendor ID:                          GenuineIntel
Model name:                         11th Gen Intel(R) Core(TM) i7-11370H @ 3.30GHz
CPU family:                         6
Model:                              140
Thread(s) per core:                 2
Core(s) per socket:                 4
Socket(s):                          1
Stepping:                           1
BogoMIPS:                           6604.79
Flags:                              fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush mmx fxsr sse sse2 ss ht syscall nx pdpe1gb rdtscp lm constant_tsc arch_perfmon rep_good nopl xtopology tsc_reliable nonstop_tsc cpuid pni pclmulqdq vmx ssse3 fma cx16 pdcm pcid sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand hypervisor lahf_lm abm 3dnowprefetch invpcid_single ssbd ibrs ibpb stibp ibrs_enhanced tpr_shadow vnmi ept vpid ept_ad fsgsbase tsc_adjust bmi1 avx2 smep bmi2 erms invpcid avx512f avx512dq rdseed adx smap avx512ifma clflushopt clwb avx512cd sha_ni avx512bw avx512vl xsaveopt xsavec xgetbv1 xsaves avx512vbmi umip avx512_vbmi2 gfni vaes vpclmulqdq avx512_vnni avx512_bitalg avx512_vpopcntdq rdpid movdiri movdir64b fsrm avx512_vp2intersect flush_l1d arch_capabilities
Virtualization:                     VT-x
Hypervisor vendor:                  Microsoft
Virtualization type:                full
L1d cache:                          192 KiB (4 instances)
L1i cache:                          128 KiB (4 instances)
L2 cache:                           5 MiB (4 instances)
L3 cache:                           12 MiB (1 instance)
Vulnerability Gather data sampling: Unknown: Dependent on hypervisor status
Vulnerability Itlb multihit:        Not affected
Vulnerability L1tf:                 Not affected
Vulnerability Mds:                  Not affected
Vulnerability Meltdown:             Not affected
Vulnerability Mmio stale data:      Not affected
Vulnerability Retbleed:             Mitigation; Enhanced IBRS
Vulnerability Spec rstack overflow: Not affected
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; Enhanced IBRS, IBPB conditional, RSB filling, PBRSB-eIBRS SW sequence
Vulnerability Srbds:                Not affected
Vulnerability Tsx async abort:      Not affected

Versions of relevant libraries:
[pip3] mypy==1.7.1
[pip3] mypy-extensions==1.0.0
[pip3] numpy==1.23.5
[pip3] pytorch-lightning==2.0.0
[pip3] torch==2.0.1
[pip3] torch-cluster==1.6.3
[pip3] torch-scatter==2.1.2
[pip3] torchmetrics==1.2.0
[pip3] torchvision==0.15.2
[pip3] triton==2.0.0
[conda] numpy                     1.26.2          py310hb13e2d6_0    conda-forge

cc @EikanWang @jgong5 @wenzhe-nrv @sanchitintel