Repository: pytorch
Issue: gradcheck fails when inputs are dependent on each other
Labels: module: autograd,triaged,actionable

### 🐛 Describe the bug

I was writing a custom `torch.autograd.Function`, and noticed that `gradcheck` was failing, even though the results of my backward calculation seemed correct. After some debugging, it turns out that my custom backward was correct, but it was actually the inputs to `gradcheck` that caused my failure.

Specifically, if `gradcheck` is used to test a function of `x` and `y`, and `y` depends on `x`, then gradcheck may fail. This is because the analytical result propagates gradients through the entire computation graph (including from dependent tensors into intermediate tensors), but the numerical result is unable to do that (since it only performs forward passes).

Here is a minimal example:
```py
import torch
from torch.autograd import gradcheck

x = torch.ones(1, dtype=torch.float64, requires_grad=True)
y = 3 * x
y_independent = y.clone().detach()

# passes
gradcheck(torch.dot, (x, y_independent))
# fails
gradcheck(torch.dot, (x, y))
```

This fails with the following error:
```
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/dkeyes/miniconda3/envs/vanilla/lib/python3.12/site-packages/torch/autograd/gradcheck.py", line 2070, in gradcheck
    return _gradcheck_helper(**args)
           ^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/dkeyes/miniconda3/envs/vanilla/lib/python3.12/site-packages/torch/autograd/gradcheck.py", line 2099, in _gradcheck_helper
    _gradcheck_real_imag(
  File "/home/dkeyes/miniconda3/envs/vanilla/lib/python3.12/site-packages/torch/autograd/gradcheck.py", line 1487, in _gradcheck_real_imag
    gradcheck_fn(
  File "/home/dkeyes/miniconda3/envs/vanilla/lib/python3.12/site-packages/torch/autograd/gradcheck.py", line 1628, in _slow_gradcheck
    raise GradcheckError(
torch.autograd.gradcheck.GradcheckError: Jacobian mismatch for output 0 with respect to input 0,
numerical:tensor([[3.0000]], dtype=torch.float64)
analytical:tensor([[6.]], dtype=torch.float64)
```
Note that "output 0" corresponds to `x`. Even through finite differences gives a derivative of 3 w.r.t. `x` (and 1 w.r.t `y`), the backwards pass gives a final derivative of 6 ( = 3 + 1*3) w.r.t. `x`.

As a user, I think this is surprising, since I only expected `gradcheck` to consider the function being tested, not the inputs. I think `gradcheck` should either: only execute the computation graph up to the inputs (e.g. by cloning and detaching them) OR include a note in the documentation to alert users that this may be a cause of failures.

### Versions

Collecting environment information...
PyTorch version: 2.2.1
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: Could not collect
Clang version: Could not collect
CMake version: Could not collect
Libc version: glibc-2.35

Python version: 3.12.1 | packaged by Anaconda, Inc. | (main, Jan 19 2024, 15:51:05) [GCC 11.2.0] (64-bit runtime)
Python platform: Linux-5.15.133.1-microsoft-standard-WSL2-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 RTX A5500
Nvidia driver version: 536.67
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:                      48 bits physical, 48 bits virtual
Byte Order:                         Little Endian
CPU(s):                             64
On-line CPU(s) list:                0-63
Vendor ID:                          AuthenticAMD
Model name:                         AMD Ryzen Threadripper PRO 5975WX 32-Cores
CPU family:                         25
Model:                              8
Thread(s) per core:                 2
Core(s) per socket:                 32
Socket(s):                          1
Stepping:                           2
BogoMIPS:                           7186.48
Flags:                              fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush mmx fxsr sse sse2 ht syscall nx mmxext fxsr_opt pdpe1gb rdtscp lm constant_tsc rep_good nopl tsc_reliable nonstop_tsc cpuid extd_apicid pni pclmulqdq ssse3 fma cx16 sse4_1 sse4_2 movbe popcnt aes xsave avx f16c rdrand hypervisor lahf_lm cmp_legacy cr8_legacy abm sse4a misalignsse 3dnowprefetch osvw topoext ibrs ibpb stibp vmmcall fsgsbase bmi1 avx2 smep bmi2 erms rdseed adx smap clflushopt clwb sha_ni xsaveopt xsavec xgetbv1 xsaves clzero xsaveerptr arat umip vaes vpclmulqdq rdpid fsrm
Hypervisor vendor:                  Microsoft
Virtualization type:                full
L1d cache:                          1 MiB (32 instances)
L1i cache:                          1 MiB (32 instances)
L2 cache:                           16 MiB (32 instances)
L3 cache:                           32 MiB (1 instance)
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 Retbleed:             Not affected
Vulnerability Spec rstack overflow: Mitigation; safe RET, no microcode
Vulnerability Spec store bypass:    Vulnerable
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:                Not affected
Vulnerability Tsx async abort:      Not affected

Versions of relevant libraries:
[pip3] numpy==1.26.4
[pip3] pytorch-lightning==2.1.3
[pip3] torch==2.2.1
[pip3] torchaudio==2.2.1
[pip3] torchmetrics==1.2.1
[pip3] torchvision==0.17.1
[conda] blas                      1.0                         mkl
[conda] ffmpeg                    4.3                  hf484d3e_0    pytorch
[conda] libjpeg-turbo             2.0.0                h9bf148f_0    pytorch
[conda] mkl                       2023.1.0         h213fc3f_46344
[conda] mkl-service               2.4.0           py312h5eee18b_1
[conda] mkl_fft                   1.3.8           py312h5eee18b_0
[conda] mkl_random                1.2.4           py312hdb19cb5_0
[conda] numpy                     1.26.4          py312hc5e2394_0
[conda] numpy-base                1.26.4          py312h0da6c21_0
[conda] pytorch                   2.2.1           py3.12_cuda12.1_cudnn8.9.2_0    pytorch
[conda] pytorch-cuda              12.1                 ha16c6d3_5    pytorch
[conda] pytorch-lightning         2.1.3              pyhd8ed1ab_0    conda-forge
[conda] pytorch-mutex             1.0                        cuda    pytorch
[conda] torchaudio                2.2.1               py312_cu121    pytorch
[conda] torchmetrics              1.2.1              pyhd8ed1ab_0    conda-forge
[conda] torchvision               0.17.1              py312_cu121    pytorch

cc @ezyang @albanD @zou3519 @gqchen @pearu @nikitaved @soulitzer @Lezcano @Varal7