Repository: pytorch
Issue: TorchDispatchMode fails on jit.trace
Labels: oncall: jit

### 🐛 Describe the bug

Failed on trace model with under TorchDispatchMode.

```python
import torch
from torch import nn
from torch.utils._python_dispatch import TorchDispatchMode


class DispatchMode(TorchDispatchMode):
    def __torch_dispatch__(self, func, types, args=(), kwargs=None):
        print(
            f"__torch_dispatch__: {func.__name__=} , tracing_state = {torch._C._get_tracing_state() is not None}",
        )
        return func(*args, **kwargs)


class SimpleModel(nn.Module):
    def __init__(self) -> None:
        super().__init__()
        self.conv1 = nn.Conv2d(1, 1, 1)
        self.b = nn.Parameter(torch.tensor(2.0))

    def forward(self, x):
        x = self.conv1(x)
        x = torch.relu(x)
        return x + self.b


model = SimpleModel().eval()
example_input = torch.ones(1, 1, 3, 3)
with DispatchMode():
    torch.jit.trace(model, example_input, check_trace=False)
```

output: 

```

__torch_dispatch__: func.__name__='convolution.default' , tracing_state = True
__torch_dispatch__: func.__name__='_to_copy.default' , tracing_state = False
__torch_dispatch__: func.__name__='select.int' , tracing_state = False
__torch_dispatch__: func.__name__='select.int' , tracing_state = False
__torch_dispatch__: func.__name__='select.int' , tracing_state = False
__torch_dispatch__: func.__name__='select.int' , tracing_state = False
__torch_dispatch__: func.__name__='select.int' , tracing_state = False
Traceback (most recent call last):
  File "reproducer.py", line 26, in <module>
    torch.jit.trace(model, example_input, check_trace=False)
  File "site-packages/torch/jit/_trace.py", line 820, in trace
    return trace_module(
  File "site-packages/torch/jit/_trace.py", line 1088, in trace_module
    module._c._create_method_from_trace(
  File "site-packages/torch/nn/modules/module.py", line 1532, in _wrapped_call_impl
    return self._call_impl(*args, **kwargs)
  File "site-packages/torch/nn/modules/module.py", line 1541, in _call_impl
    return forward_call(*args, **kwargs)
  File "site-packages/torch/nn/modules/module.py", line 1522, in _slow_forward
    result = self.forward(*input, **kwargs)
  File "reproducer.py", line 19, in forward
    x = torch.relu(x)
RuntimeError: Cannot insert a Tensor that requires grad as a constant. Consider making it a parameter or input, or detaching the gradient
Tensor:
(1,1,.,.) = 
 -0.3101 -0.3101 -0.3101
 -0.3101 -0.3101 -0.3101
 -0.3101 -0.3101 -0.3101
[ torch.FloatTensor{1,1,3,3} ]
```


If run with torch.no_grad() no error, but still looks like relu and add function runs without tracing context.

```
__torch_dispatch__: func.__name__='convolution.default' , tracing_state = True
__torch_dispatch__: func.__name__='relu.default' , tracing_state = False
__torch_dispatch__: func.__name__='add.Tensor' , tracing_state = False
```

So it's affect on export if try export model with run under TorchDispatchMode, for onnx export 
```
with torch.no_grad():
    with DispatchMode():
        torch.onnx.export(model, example_input, "1.onnx")
```
In result onnx model is empty. 

As i have question about modification of tensor in `__torch_dispatch__` function. 
Can modification of tensors in the `__torch__dispatch__` function be saved in the tractable model?
Now it looks strange, if modify tensor for `relu` output of traced model do not match inference with TorchDispatchMode, but if modify tensors for `convolution`  that output match.
Possible is result that `__torch_dispatch__` function for `relu` runs without tracing_state. 

Example to modify tensor for `relu` function:
```python
class DispatchMode(TorchDispatchMode):
    def __torch_dispatch__(self, func, types, args=(), kwargs=None):
        if func.__name__ == "relu.default":
            return func(*(args[0] + args[0],), **kwargs)
        return func(*args, **kwargs)

model = SimpleModel().eval()
example_input = torch.ones(1, 1, 3, 3)
ret0 = model(example_input)
print("ret0:", ret0)
with torch.no_grad():
    with DispatchMode():
        ret1 = model(example_input)
        print("ret1:", ret1)
        traced = torch.jit.trace(model, example_input, check_trace=False)
ret2 = traced(example_input)
print("ret2:", ret2)
```

Output 
```
ret0: tensor([[[[2.2282, 2.2282, 2.2282],
          [2.2282, 2.2282, 2.2282],
          [2.2282, 2.2282, 2.2282]]]], grad_fn=<AddBackward0>)

ret1: tensor([[[[2.4563, 2.4563, 2.4563],
          [2.4563, 2.4563, 2.4563],
          [2.4563, 2.4563, 2.4563]]]])

# Outputs of traced model is matches output of inference model without TorchDispatchMode
ret2: tensor([[[[2.2282, 2.2282, 2.2282],
          [2.2282, 2.2282, 2.2282],
          [2.2282, 2.2282, 2.2282]]]], grad_fn=<AddBackward0>)
```

Example to modify tensor for `convolution` function:
```python
class DispatchMode(TorchDispatchMode):
    def __torch_dispatch__(self, func, types, args=(), kwargs=None):
        if func.__name__ == "convolution.default":
            args = list(args)
            args[0] = args[0] + args[0]
            return func(*tuple(args), **kwargs)
        return func(*args, **kwargs)

model = SimpleModel().eval()
example_input = torch.ones(1, 1, 3, 3)
ret0 = model(example_input)
print("ret0:", ret0)
with torch.no_grad():
    with DispatchMode():
        ret1 = model(example_input)
        print("ret1:", ret1)
        traced = torch.jit.trace(model, example_input, check_trace=False)
ret2 = traced(example_input)
print("ret2:", ret2)
```

```
ret0: tensor([[[[2.2960, 2.2960, 2.2960],
          [2.2960, 2.2960, 2.2960],
          [2.2960, 2.2960, 2.2960]]]], grad_fn=<AddBackward0>)

ret1: tensor([[[[3.1684, 3.1684, 3.1684],
          [3.1684, 3.1684, 3.1684],
          [3.1684, 3.1684, 3.1684]]]])

# Outputs of traced model matches output of inference model with TorchDispatchMode
ret2: tensor([[[[3.1684, 3.1684, 3.1684],
          [3.1684, 3.1684, 3.1684],
          [3.1684, 3.1684, 3.1684]]]], grad_fn=<AddBackward0>
```




### Versions

```
Collecting environment information...
PyTorch version: 2.3.1+cu121
Is debug build: False
CUDA used to build PyTorch: 12.1
ROCM used to build PyTorch: N/A

OS: Ubuntu 22.04.4 LTS (x86_64)
GCC version: (Ubuntu 11.4.0-1ubuntu1~22.04) 11.4.0
Clang version: Could not collect
CMake version: version 3.22.1
Libc version: glibc-2.35

Python version: 3.8.19 (default, Apr  6 2024, 17:58:10)  [GCC 11.4.0] (64-bit runtime)
Python platform: Linux-6.5.0-35-generic-x86_64-with-glibc2.35
Is CUDA available: True
CUDA runtime version: 12.5.40
CUDA_MODULE_LOADING set to: LAZY
GPU models and configuration: 
GPU 0: NVIDIA GeForce RTX 3090
GPU 1: NVIDIA GeForce RTX 3090
GPU 2: NVIDIA GeForce RTX 3090

Nvidia driver version: 555.42.02
cuDNN version: Could not collect
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:                      46 bits physical, 48 bits virtual
Byte Order:                         Little Endian
CPU(s):                             36
On-line CPU(s) list:                0-35
Vendor ID:                          GenuineIntel
Model name:                         Intel(R) Core(TM) i9-10980XE CPU @ 3.00GHz
CPU family:                         6
Model:                              85
Thread(s) per core:                 2
Core(s) per socket:                 18
Socket(s):                          1
Stepping:                           7
CPU max MHz:                        4800.0000
CPU min MHz:                        1200.0000
BogoMIPS:                           6000.00
Flags:                              fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx pdpe1gb rdtscp lm constant_tsc art arch_perfmon pebs bts rep_good nopl xtopology nonstop_tsc cpuid aperfmperf pni pclmulqdq dtes64 monitor ds_cpl vmx est tm2 ssse3 sdbg fma cx16 xtpr pdcm pcid dca sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm abm 3dnowprefetch cpuid_fault epb cat_l3 cdp_l3 invpcid_single ssbd mba ibrs ibpb stibp ibrs_enhanced tpr_shadow flexpriority ept vpid ept_ad fsgsbase tsc_adjust bmi1 avx2 smep bmi2 erms invpcid cqm mpx rdt_a avx512f avx512dq rdseed adx smap clflushopt clwb intel_pt avx512cd avx512bw avx512vl xsaveopt xsavec xgetbv1 xsaves cqm_llc cqm_occup_llc cqm_mbm_total cqm_mbm_local dtherm ida arat pln pts hwp hwp_act_window hwp_epp hwp_pkg_req vnmi avx512_vnni md_clear flush_l1d arch_capabilities
Virtualization:                     VT-x
L1d cache:                          576 KiB (18 instances)
L1i cache:                          576 KiB (18 instances)
L2 cache:                           18 MiB (18 instances)
L3 cache:                           24.8 MiB (1 instance)
NUMA node(s):                       1
NUMA node0 CPU(s):                  0-35
Vulnerability Gather data sampling: Mitigation; Microcode
Vulnerability Itlb multihit:        KVM: Mitigation: VMX disabled
Vulnerability L1tf:                 Not affected
Vulnerability Mds:                  Not affected
Vulnerability Meltdown:             Not affected
Vulnerability Mmio stale data:      Mitigation; Clear CPU buffers; SMT vulnerable
Vulnerability Retbleed:             Mitigation; Enhanced IBRS
Vulnerability Spec rstack overflow: Not affected
Vulnerability Spec store bypass:    Mitigation; Speculative Store Bypass disabled via prctl
Vulnerability Spectre v1:           Mitigation; usercopy/swapgs barriers and __user pointer sanitization
Vulnerability Spectre v2:           Mitigation; Enhanced / Automatic IBRS; IBPB conditional; RSB filling; PBRSB-eIBRS SW sequence; BHI Syscall hardening, KVM SW loop
Vulnerability Srbds:                Not affected
Vulnerability Tsx async abort:      Mitigation; TSX disabled

Versions of relevant libraries:
[pip3] torch==2.3.1
[pip3] triton==2.3.1
[conda] Could not collect
```

cc @EikanWang @jgong5 @wenzhe-nrv @sanchitintel