Repository: pytorch
Issue: torch.compile with mode = "max-autotune" breaks when starting from inference_mode
Labels: triaged,module: cuda graphs,inference mode,oncall: pt2

### 🐛 Describe the bug

Hi, it looks like compiling model in `inference_mode` can break subsequent compilations of the same model in training mode.

Here is an example:

```python
import torch

layer = torch.nn.Linear(32, 64).bfloat16().cuda()

ex = torch.randn(8, 32).bfloat16().cuda()
layer = torch.compile(layer, mode="max-autotune")

with torch.inference_mode():
    for _ in range(3):
        res = layer(ex)
        print("value:", res.mean().item())

for _ in range(3):
    res = layer(ex)
    res.mean().backward()
    print("value:", res.mean().item())
```

when I run this code, I get the following error:

```
value: 0.072265625
value: 0.072265625
value: 0.072265625
value: 0.072265625
Traceback (most recent call last):
  File "test_compile.py", line 14, in <module>
    res = layer(ex)
  File "/home/lib/python3.8/site-packages/torch/nn/modules/module.py", line 1553, in _wrapped_call_impl
    return self._call_impl(*args, **kwargs)
  File "/home/lib/python3.8/site-packages/torch/nn/modules/module.py", line 1562, in _call_impl
    return forward_call(*args, **kwargs)
  File "/home/lib/python3.8/site-packages/torch/_dynamo/eval_frame.py", line 433, in _fn
    return fn(*args, **kwargs)
  File "/home/lib/python3.8/site-packages/torch/_dynamo/external_utils.py", line 36, in inner
    @functools.wraps(fn)
  File "/home/lib/python3.8/site-packages/torch/_dynamo/eval_frame.py", line 600, in _fn
    return fn(*args, **kwargs)
  File "/home/lib/python3.8/site-packages/torch/_functorch/aot_autograd.py", line 987, in forward
    return compiled_fn(full_args)
  File "/home/lib/python3.8/site-packages/torch/_functorch/_aot_autograd/runtime_wrappers.py", line 204, in runtime_wrapper
    all_outs = call_func_at_runtime_with_args(
  File "/home/lib/python3.8/site-packages/torch/_functorch/_aot_autograd/utils.py", line 120, in call_func_at_runtime_with_args
    out = normalize_as_list(f(args))
  File "/home/lib/python3.8/site-packages/torch/_functorch/_aot_autograd/utils.py", line 94, in g
    return f(*args)
  File "/home/lib/python3.8/site-packages/torch/autograd/function.py", line 574, in apply
    return super().apply(*args, **kwargs)  # type: ignore[misc]
  File "/home/lib/python3.8/site-packages/torch/_functorch/_aot_autograd/runtime_wrappers.py", line 1451, in forward
    fw_outs = call_func_at_runtime_with_args(
  File "/home/lib/python3.8/site-packages/torch/_functorch/_aot_autograd/utils.py", line 120, in call_func_at_runtime_with_args
    out = normalize_as_list(f(args))
  File "/home/lib/python3.8/site-packages/torch/_functorch/_aot_autograd/runtime_wrappers.py", line 451, in wrapper
    return compiled_fn(runtime_args)
  File "/home/lib/python3.8/site-packages/torch/_inductor/codecache.py", line 1131, in __call__
    return self.current_callable(inputs)
  File "/home/lib/python3.8/site-packages/torch/_inductor/compile_fx.py", line 993, in run
    return compiled_fn(new_inputs)
  File "/home/lib/python3.8/site-packages/torch/_inductor/cudagraph_trees.py", line 360, in deferred_cudagraphify
    return fn(inputs)
  File "/home/lib/python3.8/site-packages/torch/_inductor/compile_fx.py", line 944, in run
    return model(new_inputs)
  File "/home/lib/python3.8/site-packages/torch/_inductor/cudagraph_trees.py", line 1841, in run
    out = self._run(new_inputs, function_id)
  File "/home/lib/python3.8/site-packages/torch/_inductor/cudagraph_trees.py", line 1972, in _run
    return self.record_function(new_inputs, function_id)
  File "/home/lib/python3.8/site-packages/torch/_inductor/cudagraph_trees.py", line 2003, in record_function
    node = CUDAGraphNode(
  File "/home/lib/python3.8/site-packages/torch/_inductor/cudagraph_trees.py", line 927, in __init__
    ] = self._record(wrapped_function.model, recording_inputs)
  File "/home/lib/python3.8/site-packages/torch/_inductor/cudagraph_trees.py", line 1155, in _record
    with preserve_rng_state(), torch.cuda.device(
  File "/home/lib/python3.8/site-packages/torch/cuda/graphs.py", line 180, in __enter__
    self.cuda_graph.capture_begin(
  File "/home/lib/python3.8/site-packages/torch/cuda/graphs.py", line 72, in capture_begin
    super().capture_begin(pool=pool, capture_error_mode=capture_error_mode)
RuntimeError: Inplace update to inference tensor outside InferenceMode is not allowed.You can make a clone to get a normal tensor before doing inplace update.See https://github.com/pytorch/rfcs/pull/17 for more details.
```

switching from `torch.inference_mode()` to `torch.no_grad()` seems to fix this issue. 

It also looks like this matters only during first compilation - i.e. I can run successfully when the model starts in `no_grad` and then interleaves between training and inference modes.

I tried digging in deeper but the error occurs after the first training step once cudagraph starts being executed, which makes it challenging to debug...


### Versions

Collecting environment information...
PyTorch version: 2.4.1+cu121
Is debug build: False
CUDA used to build PyTorch: 12.1
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.8.20 (default, Sep  9 2024, 22:12:42)  [Clang 18.1.8 ] (64-bit runtime)
Python platform: Linux-6.8.0-40-generic-x86_64-with-glibc2.2.5
Is CUDA available: True
CUDA runtime version: Could not collect
CUDA_MODULE_LOADING set to: LAZY
GPU models and configuration: GPU 0: NVIDIA GeForce RTX 3090
Nvidia driver version: 535.183.01
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):                               24
On-line CPU(s) list:                  0-23
Vendor ID:                            GenuineIntel
Model name:                           12th Gen Intel(R) Core(TM) i9-12900K
CPU family:                           6
Model:                                151
Thread(s) per core:                   2
Core(s) per socket:                   16
Socket(s):                            1
Stepping:                             2
CPU max MHz:                          5200.0000
CPU min MHz:                          800.0000
BogoMIPS:                             6374.40
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 tsc_known_freq pni pclmulqdq dtes64 monitor ds_cpl vmx smx est tm2 ssse3 sdbg fma cx16 xtpr pdcm sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm abm 3dnowprefetch cpuid_fault epb cat_l2 cdp_l2 ssbd ibrs ibpb stibp ibrs_enhanced tpr_shadow flexpriority ept vpid ept_ad fsgsbase tsc_adjust bmi1 avx2 smep bmi2 erms invpcid rdt_a rdseed adx smap clflushopt clwb intel_pt sha_ni xsaveopt xsavec xgetbv1 xsaves split_lock_detect user_shstk avx_vnni dtherm ida arat pln pts hwp hwp_notify hwp_act_window hwp_epp hwp_pkg_req hfi vnmi umip pku ospke waitpkg gfni vaes vpclmulqdq tme rdpid movdiri movdir64b fsrm md_clear serialize pconfig arch_lbr ibt flush_l1d arch_capabilities
Virtualization:                       VT-x
L1d cache:                            640 KiB (16 instances)
L1i cache:                            768 KiB (16 instances)
L2 cache:                             14 MiB (10 instances)
L3 cache:                             30 MiB (1 instance)
NUMA node(s):                         1
NUMA node0 CPU(s):                    0-23
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:   Not affected
Vulnerability Spec store bypass:      Not affected
Vulnerability Spectre v1:             Not affected
Vulnerability Spectre v2:             Not affected
Vulnerability Srbds:                  Not affected
Vulnerability Tsx async abort:        Not affected

Versions of relevant libraries:
[pip3] numpy==1.24.4
[pip3] torch==2.4.1
[pip3] torchmetrics==1.4.1
[pip3] torchvision==0.19.1
[pip3] triton==3.0.0
[conda] Could not collect

cc @mcarilli @ezyang @eellison @penguinwu @chauhang