torch.compile not working with gradient checkpointing
Labels: module: checkpoint, triaged, oncall: pt2

### 🐛 Describe the bug

It looks like gradient checkpointing (activation checkpointing) it is not allowed if used with `torch.compile`. For example this code:

```
import torch
import torch.utils.checkpoint
import torch._dynamo
torch._dynamo.config.verbose=True
import argparse
import torch.utils.benchmark as benchmark


class myModel(torch.nn.Module):
    def __init__(self, grad_checkpoint):
        super().__init__()
        self.conv1 = torch.nn.Conv2d(3, 128, kernel_size=3, padding=1)
        self.conv2 = torch.nn.Conv2d(128, 128, kernel_size=3, padding=1)
        self.conv3 = torch.nn.Conv2d(128, 3, kernel_size=3, padding=1)
        self.checkpoint = grad_checkpoint

    def forward(self, x):
        x = self.conv1(x)
        x = torch.nn.functional.relu(x)
        if self.checkpoint:
            x = torch.utils.checkpoint.checkpoint(self.conv2, x)
        else:
            x = self.conv2(x)
        x = torch.nn.functional.relu(x)
        x = self.conv3(x)
        return x


def run_forward(model_, x):
    out = model_(x)


def run(grad_checkpoint):
    device = "cuda" if torch.cuda.is_available() else "cpu"
    model = myModel(grad_checkpoint).to(device)
    x = torch.randn((2, 3, 640, 256), device=device)

    model_opt = torch.compile(model, mode="reduce-overhead")
    num_threads = torch.get_num_threads()
    t = benchmark.Timer(
        stmt='optim(x)',
        globals={'optim': model_opt, 'x': x}, # When 'optim': model then it works
        num_threads=num_threads,
        label="Average Run Duration",
    )
    print(t.timeit(100))

if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("--grad_checkpoint", action='store_true')
    args = parser.parse_args()
    run(args.grad_checkpoint)
```

gives the following error:

```
File "timing.py", line 89, in <module>
    run(args.grad_checkpoint)
  File "timing.py", line 83, in run
    print(t.timeit(100))
  File "/home/manuel/anaconda3/envs/ldm/lib/python3.8/site-packages/torch/utils/benchmark/utils/timer.py", line 266, in timeit
    self._timeit(number=max(int(number // 100), 2))
  File "/home/manuel/anaconda3/envs/ldm/lib/python3.8/site-packages/torch/utils/benchmark/utils/timer.py", line 256, in _timeit
    return max(self._timer.timeit(number), 1e-9)
  File "/home/manuel/anaconda3/envs/ldm/lib/python3.8/timeit.py", line 177, in timeit
    timing = self.inner(it, self.timer)
  File "<timeit-src>", line 6, in inner
  File "/home/manuel/anaconda3/envs/ldm/lib/python3.8/site-packages/torch/nn/modules/module.py", line 1501, in _call_impl
    return forward_call(*args, **kwargs)
  File "/home/manuel/anaconda3/envs/ldm/lib/python3.8/site-packages/torch/_dynamo/eval_frame.py", line 82, in forward
    return self.dynamo_ctx(self._orig_mod.forward)(*args, **kwargs)
  File "/home/manuel/anaconda3/envs/ldm/lib/python3.8/site-packages/torch/_dynamo/eval_frame.py", line 209, in _fn
    return fn(*args, **kwargs)
  File "timing.py", line 49, in forward
    x = torch.utils.checkpoint.checkpoint(self.conv2, x)
  File "/home/manuel/anaconda3/envs/ldm/lib/python3.8/site-packages/torch/utils/checkpoint.py", line 249, in checkpoint
    return CheckpointFunction.apply(function, preserve, *args)
  File "/home/manuel/anaconda3/envs/ldm/lib/python3.8/site-packages/torch/autograd/function.py", line 506, in apply
    return super().apply(*args, **kwargs)  # type: ignore[misc]
  File "/home/manuel/anaconda3/envs/ldm/lib/python3.8/site-packages/torch/utils/checkpoint.py", line 81, in forward
    ctx.fwd_cpu_state = torch.get_rng_state()
  File "/home/manuel/anaconda3/envs/ldm/lib/python3.8/site-packages/torch/_dynamo/eval_frame.py", line 337, in catch_errors
    return callback(frame, cache_size, hooks)
  File "/home/manuel/anaconda3/envs/ldm/lib/python3.8/site-packages/torch/_dynamo/convert_frame.py", line 404, in _convert_frame
    result = inner_convert(frame, cache_size, hooks)
  File "/home/manuel/anaconda3/envs/ldm/lib/python3.8/site-packages/torch/_dynamo/convert_frame.py", line 104, in _fn
    return fn(*args, **kwargs)
  File "/home/manuel/anaconda3/envs/ldm/lib/python3.8/site-packages/torch/_dynamo/convert_frame.py", line 262, in _convert_frame_assert
    return _compile(
  File "/home/manuel/anaconda3/envs/ldm/lib/python3.8/site-packages/torch/_dynamo/utils.py", line 163, in time_wrapper
    r = func(*args, **kwargs)
  File "/home/manuel/anaconda3/envs/ldm/lib/python3.8/site-packages/torch/_dynamo/convert_frame.py", line 324, in _compile
    out_code = transform_code_object(code, transform)
  File "/home/manuel/anaconda3/envs/ldm/lib/python3.8/site-packages/torch/_dynamo/bytecode_transformation.py", line 445, in transform_code_object
    transformations(instructions, code_options)
  File "/home/manuel/anaconda3/envs/ldm/lib/python3.8/site-packages/torch/_dynamo/convert_frame.py", line 311, in transform
    tracer.run()
  File "/home/manuel/anaconda3/envs/ldm/lib/python3.8/site-packages/torch/_dynamo/symbolic_convert.py", line 1726, in run
    super().run()
  File "/home/manuel/anaconda3/envs/ldm/lib/python3.8/site-packages/torch/_dynamo/symbolic_convert.py", line 576, in run
    and self.step()
  File "/home/manuel/anaconda3/envs/ldm/lib/python3.8/site-packages/torch/_dynamo/symbolic_convert.py", line 540, in step
    getattr(self, inst.opname)(inst)
  File "/home/manuel/anaconda3/envs/ldm/lib/python3.8/site-packages/torch/_dynamo/symbolic_convert.py", line 342, in wrapper
    return inner_fn(self, inst)
  File "/home/manuel/anaconda3/envs/ldm/lib/python3.8/site-packages/torch/_dynamo/symbolic_convert.py", line 965, in CALL_FUNCTION
    self.call_function(fn, args, {})
  File "/home/manuel/anaconda3/envs/ldm/lib/python3.8/site-packages/torch/_dynamo/symbolic_convert.py", line 474, in call_function
    self.push(fn.call_function(self, args, kwargs))
  File "/home/manuel/anaconda3/envs/ldm/lib/python3.8/site-packages/torch/_dynamo/variables/torch.py", line 368, in call_function
    return wrap_fx_proxy(
  File "/home/manuel/anaconda3/envs/ldm/lib/python3.8/site-packages/torch/_dynamo/variables/builder.py", line 754, in wrap_fx_proxy
    return wrap_fx_proxy_cls(
  File "/home/manuel/anaconda3/envs/ldm/lib/python3.8/site-packages/torch/_dynamo/variables/builder.py", line 812, in wrap_fx_proxy_cls
    assert "source" in options and options["source"] is not None
AssertionError: 

from user code:
   File "/home/manuel/anaconda3/envs/ldm/lib/python3.8/site-packages/torch/random.py", line 23, in get_rng_state
    return default_generator.get_state()


You can suppress this exception and fall back to eager by setting:
    torch._dynamo.config.suppress_errors = True
```

### Versions

```
Collecting environment information...
PyTorch version: 2.0.0+cu117
Is debug build: False
CUDA used to build PyTorch: 11.7
ROCM used to build PyTorch: N/A

OS: Ubuntu 22.04.2 LTS (x86_64)
GCC version: (Ubuntu 11.3.0-1ubuntu1~22.04) 11.3.0
Clang version: Could not collect
CMake version: version 3.26.0
Libc version: glibc-2.35

Python version: 3.8.5 (default, Sep  4 2020, 07:30:14)  [GCC 7.3.0] (64-bit runtime)
Python platform: Linux-5.19.0-35-generic-x86_64-with-glibc2.10
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 2080 Ti
Nvidia driver version: 525.85.12
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:                   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:                      Intel(R) Core(TM) i7-4790 CPU @ 3.60GHz
CPU family:                      6
Model:                           60
Thread(s) per core:              2
Core(s) per socket:              4
Socket(s):                       1
Stepping:                        3
CPU max MHz:                     4000.0000
CPU min MHz:                     800.0000
BogoMIPS:                        7195.66
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 arch_perfmon pebs bts rep_good nopl xtopology nonstop_tsc cpuid aperfmperf pni pclmulqdq dtes64 monitor ds_cpl vmx smx est tm2 ssse3 sdbg fma cx16 xtpr pdcm pcid sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm abm cpuid_fault epb invpcid_single pti ssbd ibrs ibpb stibp tpr_shadow vnmi flexpriority ept vpid ept_ad fsgsbase tsc_adjust bmi1 avx2 smep bmi2 erms invpcid xsaveopt dtherm ida arat pln pts md_clear flush_l1d
Virtualisation:                  VT-x
L1d cache:                       128 KiB (4 instances)
L1i cache:                       128 KiB (4 instances)
L2 cache:                        1 MiB (4 instances)
L3 cache:                        8 MiB (1 instance)
NUMA node(s):                    1
NUMA node0 CPU(s):               0-7
Vulnerability Itlb multihit:     KVM: Mitigation: VMX disabled
Vulnerability L1tf:              Mitigation; PTE Inversion; VMX conditional cache flushes, SMT vulnerable
Vulnerability Mds:               Mitigation; Clear CPU buffers; SMT vulnerable
Vulnerability Meltdown:          Mitigation; PTI
Vulnerability Mmio stale data:   Unknown: No mitigations
Vulnerability Retbleed:          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; Retpolines, IBPB conditional, IBRS_FW, STIBP conditional, RSB filling, PBRSB-eIBRS Not affected
Vulnerability Srbds:             Mitigation; Microcode
Vulnerability Tsx async abort:   Not affected

Versions of relevant libraries:
[pip3] numpy==1.23.4
[pip3] pytorch-lightning==1.6.3
[pip3] torch==2.0.0
[pip3] torch-fidelity==0.3.0
[pip3] torch-tb-profiler==0.4.1
[pip3] torchaudio==2.0.1
[pip3] torchmetrics==0.11.1
[pip3] torchvision==0.15.1
[pip3] triton==2.0.0
[conda] blas                      1.0                         mkl  
[conda] cudatoolkit               11.3.1               h2bc3f7f_2  
[conda] ffmpeg                    4.3                  hf484d3e_0    pytorch
[conda] mkl                       2021.4.0           h06a4308_640  
[conda] mkl-service               2.4.0            py38h7f8727e_0  
[conda] mkl_fft                   1.3.1            py38hd3c417c_0  
[conda] mkl_random                1.2.2            py38h51133e4_0  
[conda] numpy                     1.23.4                   pypi_0    pypi
[conda] pytorch-lightning         1.6.3                    pypi_0    pypi
[conda] pytorch-mutex             1.0                        cuda    pytorch
[conda] torch                     2.0.0                    pypi_0    pypi
[conda] torch-fidelity            0.3.0                    pypi_0    pypi
[conda] torch-tb-profiler         0.4.1                    pypi_0    pypi
[conda] torchaudio                2.0.1                    pypi_0    pypi
[conda] torchmetrics              0.11.1                   pypi_0    pypi
[conda] torchvision               0.15.1                   pypi_0    pypi
[conda] triton                    2.0.0                    pypi_0    pypi
```

cc @ezyang @soumith @msaroufim @wconstab @ngimel @bdhirsh