Repository: pytorch
Issue: forward_ad ignores checkpoints
Labels: module: bc-breaking,module: checkpoint,module: autograd,triaged,actionable,module: forward ad

### 🐛 Describe the bug

For usual backward engine, intermediate tensors can be removed within checkpoints.
For forward autograd, intermediate tensors can be always removed if not directly available to user. 

However, fwAD + checkpointing behaves differently, consider this lengthy script:

```python
import gc
from contextlib import ExitStack

import torch
import psutil
from torch.utils.checkpoint import checkpoint
import torch.autograd.forward_ad as fwAD

def print_memory():
    gc.collect()
    mem_mb = psutil.Process().memory_info().rss/1024**2
    print(f'{mem_mb} MB')
    
class DumbModule(torch.nn.Module):
    def __init__(self):
        super().__init__()
        self.mult = torch.nn.Parameter(torch.ones([]))
        
    def forward(self, x: torch.Tensor):
        for _ in range(10):
            x = x * self.mult
        return x
    

x = torch.zeros(64 * 1024, 1024)
mod = DumbModule()
print_memory()

for fwad in [False, True]:
    for checkpointed in [True, False]:
        with ExitStack() as stack:
            y = x
            if fwad:
                stack.enter_context(fwAD.dual_level())
                y = fwAD.make_dual(x, x)
                
            for i in range(10):
                if checkpointed:
                    y = checkpoint(mod.forward, x=y, use_reentrant=False)
                else:
                    y = mod.forward(y)
            print(f'{fwad=}  {checkpointed=}')
            print_memory()
            del y
```


output on linux setup with torch '2.3.0+cu121' (similar results for '2.3.1+cu121')
```
709.0546875 MB
fwad=False  checkpointed=True
3267.73046875 MB
fwad=False  checkpointed=False
26312.8515625 MB
fwad=True  checkpointed=True
28868.328125 MB                          # this should be much smaller
fwad=True  checkpointed=False
51912.05859375 MB
```


output on mac setup with torch 2.3.1 is totally different (and I'm not sure it is correct):
```
2780.328125 MB
fwad=False  checkpointed=True
2787.875 MB
fwad=False  checkpointed=False
3068.21875 MB
fwad=True  checkpointed=True
3334.15625 MB
fwad=True  checkpointed=False
3485.984375 MB
```

This example above is for CPU, but I started from observing problem on CUDA, so I guess it is backend-agnostic problem.


### 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: Could not collect
Libc version: glibc-2.35

Python version: 3.11.9 (main, Apr  6 2024, 17:59:24) [GCC 11.4.0] (64-bit runtime)
Python platform: Linux-5.15.0-94-generic-x86_64-with-glibc2.35
Is CUDA available: True
CUDA runtime version: Could not collect
CUDA_MODULE_LOADING set to: LAZY
GPU models and configuration: GPU 0: NVIDIA A100-SXM4-80GB
Nvidia driver version: 535.154.05
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, 57 bits virtual
Byte Order:                         Little Endian
CPU(s):                             96
On-line CPU(s) list:                0-95
Vendor ID:                          GenuineIntel
Model name:                         Intel(R) Xeon(R) Gold 6338 CPU @ 2.00GHz
CPU family:                         6
Model:                              106
Thread(s) per core:                 2
Core(s) per socket:                 24
Socket(s):                          2
Stepping:                           6
BogoMIPS:                           4000.00
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 cpuid tsc_known_freq 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 cpuid_fault invpcid_single ssbd ibrs ibpb stibp ibrs_enhanced tpr_shadow vnmi flexpriority 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 wbnoinvd arat avx512vbmi umip pku ospke avx512_vbmi2 gfni vaes vpclmulqdq avx512_vnni avx512_bitalg avx512_vpopcntdq la57 rdpid fsrm md_clear arch_capabilities
Virtualization:                     VT-x
Hypervisor vendor:                  KVM
Virtualization type:                full
L1d cache:                          3 MiB (96 instances)
L1i cache:                          3 MiB (96 instances)
L2 cache:                           192 MiB (48 instances)
L3 cache:                           32 MiB (2 instances)
NUMA node(s):                       2
NUMA node0 CPU(s):                  0-47
NUMA node1 CPU(s):                  48-95
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:      Vulnerable: Clear CPU buffers attempted, no microcode; SMT Host state unknown
Vulnerability Retbleed:             Not affected
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:      Mitigation; TSX disabled

Versions of relevant libraries:
[pip3] mypy==1.9.0
[pip3] mypy-extensions==1.0.0
[pip3] numpy==1.26.4
[pip3] pytorch-lightning==2.2.1
[pip3] torch==2.3.1
[pip3] torchmetrics==1.3.2
[pip3] triton==2.3.1
[conda] Could not collect
```

cc @ezyang @gchanan @soulitzer @albanD @gqchen @pearu @nikitaved @Varal7