Repository: pytorch
Issue: jacrev and jacfwd yield different results if one uses torch.no_grad blocks in module
Labels: module: docs,module: autograd,triaged,actionable,module: functorch

### 🐛 Describe the bug

When running a model through `torch.func.functional_call` that contains a `with torch.no_grad` block, you get different results when computing the jacobian with forward/reverse mode:

````python
class Model(nn.Module):
    def __init__(self,):
        super().__init__()
        self.l1 = nn.Linear(8,34)
        self.l2 = nn.Linear(8,34)
    def forward(self,x):
        with torch.no_grad():
            y=self.l1(x)
        return self.l2(x) + y
m = Model()
n=torch.func.jacrev(lambda x: torch.func.functional_call(m, dict(m.named_parameters()),x))(torch.ones(1,8))
k=torch.func.jacfwd(lambda x: torch.func.functional_call(m, dict(m.named_parameters()),x))(torch.ones(1,8))
n-k
# not close to zero
````
The errors are not within numerical tolerances (i.e. 0.1 or 0.2).

It does work as intended if you manually detach `y`
````python
class Model(nn.Module):
    def __init__(self,):
        super().__init__()
        self.l1 = nn.Linear(8,34)
        self.l2 = nn.Linear(8,34)
    def forward(self,x):
        with torch.no_grad():
            y=self.l1(x).detach()
        return self.l2(x) + y
m = Model()
n=torch.func.jacrev(lambda x: torch.func.functional_call(m, dict(m.named_parameters()),x))(torch.ones(1,8))
k=torch.func.jacfwd(lambda x: torch.func.functional_call(m, dict(m.named_parameters()),x))(torch.ones(1,8))
n-k
````
gives zero error.
In general `torch.Tensor.detach` has the expected behaviour (as far as I can test it)

The same thing holds if you compute the jacobian wrt parameters and for vjp.
````
k=torch.func.jvp(lambda x: torch.func.functional_call(m, dict(m.named_parameters()),x),(torch.ones(1,8),),(torch.ones(1,8),))
n=torch.func.jacrev(lambda x: torch.func.functional_call(m, dict(m.named_parameters()),x))(torch.ones(1,8))@torch.ones(8)
k[1]-n.squeeze(-1)
# not close to zero
```` 
Once again, the manual detach trick works.

I would imagine this to work as documented [here](https://pytorch.org/docs/stable/generated/torch.func.vjp.html#torch.func.vjp).



### Versions

````
Collecting environment information...
PyTorch version: 2.2.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: (conda-forge gcc 12.3.0-5) 12.3.0
Clang version: Could not collect
CMake version: Could not collect
Libc version: glibc-2.35

Python version: 3.10.13 | packaged by conda-forge | (main, Dec 23 2023, 15:36:39) [GCC 12.3.0] (64-bit runtime)
Python platform: Linux-4.4.0-19041-Microsoft-x86_64-with-glibc2.35
Is CUDA available: False
CUDA runtime version: No CUDA
CUDA_MODULE_LOADING set to: N/A
GPU models and configuration: No CUDA
Nvidia driver version: No CUDA
cuDNN version: No CUDA
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:       36 bits physical, 48 bits virtual
Byte Order:          Little Endian
CPU(s):              12
On-line CPU(s) list: 0-11
Vendor ID:           GenuineIntel
Model name:          12th Gen Intel(R) Core(TM) i7-1265U
CPU family:          6
Model:               154
Thread(s) per core:  2
Core(s) per socket:  10
Socket(s):           1
Stepping:            4
CPU max MHz:         1800.0000
CPU min MHz:         0.0000
BogoMIPS:            3600.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 pni pclmulqdq dtes64 monitor ds_cpl vmx smx est tm2 ssse3 fma cx16 xtpr pdcm pcid sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave osxsave avx f16c rdrand lahf_lm abm 3dnowprefetch fsgsbase tsc_adjust bmi1 avx2 smep bmi2 erms invpcid rdseed adx smap clflushopt clwb intel_pt sha_ni umip pku gfni vaes vpclmulqdq rdpid pconfig ibrs ibpb stibp ssbd
Virtualization:      VT-x
Hypervisor vendor:   Windows Subsystem for Linux
Virtualization type: container

Versions of relevant libraries:
[pip3] numpy==1.26.4
[pip3] torch==2.2.0
[pip3] torch_geometric==2.4.0
[pip3] torchaudio==2.1.2
[pip3] torchrl==0.3.1
[pip3] torchvision==0.16.2
[pip3] triton==2.2.0
[conda] blas                      1.0                         mkl    conda-forge
[conda] cpuonly                   2.0                           0    pytorch
[conda] ffmpeg                    4.3                  hf484d3e_0    pytorch
[conda] libblas                   3.9.0            16_linux64_mkl    conda-forge
[conda] libcblas                  3.9.0            16_linux64_mkl    conda-forge
[conda] liblapack                 3.9.0            16_linux64_mkl    conda-forge
[conda] mkl                       2022.2.1         h84fe81f_16997    conda-forge
[conda] numpy                     1.26.4                   pypi_0    pypi
[conda] pytorch-mutex             1.0                         cpu    pytorch
[conda] torch                     2.2.0                    pypi_0    pypi
[conda] torch-geometric           2.4.0                    pypi_0    pypi
[conda] torchaudio                2.1.2                    pypi_0    pypi
[conda] torchrl                   0.3.1                    pypi_0    pypi
[conda] torchvision               0.16.2                   pypi_0    pypi
[conda] triton                    2.2.0                    pypi_0    pypi
```` 

This test is under WSL (since that is what I currently have access to), but I also tested this under bare-metal linux and it has the same behaviour there. Behaviour stays the same on cuda as well.


cc @svekars @brycebortree @ezyang @albanD @gqchen @pearu @nikitaved @soulitzer @Lezcano @Varal7 @zou3519 @Chillee @samdow @kshitij12345 @janeyx99