Repository: pytorch
Issue: Different results with vmap when using torch.jit.script
Labels: oncall: jit,triaged,module: functorch

### 🐛 Describe the bug

Hi,

I am trying to compute Hessian-vector products (hvps) between individual layers of a neural net, with multiple vectors. To get hvps with multiple vectors, I am using vmap on a function that I have defined (```hessian_vector_product2```). I am then using ```@torch.jit.script``` with ```torch.jit.fork``` to split the hvps over layers of the net, i.e., to compute hvps with the block-diagonal Hessian. However, using ```@torch.jit.script``` only gives me the hvp with respect to a single vector. Funnily enough, when I comment out ```@torch.jit.script```, I get the hvps with respect to all the vectors. Is there a simple explanation for why this is occurring?

I've included the relevant code snippet below, along with the entire script.

Thanks!

```python
hv2 = vmap(hessian_vector_product2, in_dims=(None, 0, None)) # Use vmap to vectorize hvps

# Get hvps w.r.t. layers in parallel
@torch.jit.script
def hvp_parallel(params : List[torch.Tensor], vs : List[Optional[torch.Tensor]], grad_params: List[List[torch.Tensor]], detach : bool = True):
    futures: List[torch.jit.Future[List[Optional[torch.Tensor]]]] = []
    for p, v, g in zip(params, vs, grad_params):
        futures.append(torch.jit.fork(hv2, [p], v, g))

    hvps : List[List[Optional[torch.Tensor]]] = []
    for future in futures:
        hvp = torch.jit.wait(future)
        hvps.append(hvp)

    return hvps

# Get HVPs with 10 random vectors
n_v = 10
vs : List[Optional[torch.Tensor]] = []
for p in model.parameters():
    vs.append(torch.randn(n_v, *tuple(p.shape)).to(device))
hvps = hvp_parallel(list(model.parameters()), vs, grad_params)
print(hvps[0][0].shape) # Got torch.Size([20, 784]), expected torch.Size([10, 20, 784])
print(hvps[1][0].shape) # Got torch.Size([20]), expected torch.Size([10, 20])
print(hvps[2][0].shape) # Got torch.Size([10, 20]), expected torch.Size([10, 10, 20])
print(hvps[3][0].shape) # Got torch.Size([10]), expected torch.Size([10, 10])
```

```python
import torch
from torch.func import vmap
from typing import List, Optional

device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")

model = torch.nn.Sequential(
    torch.nn.Flatten(),
    torch.nn.Linear(784, 20),
    torch.nn.Sigmoid(),
    torch.nn.Linear(20, 10),
).to(device)

loss_fn = torch.nn.CrossEntropyLoss().to(device)

# hvp function
def hessian_vector_product2(params : List[torch.Tensor], v : Optional[torch.Tensor], grad_params: List[torch.Tensor]) -> List[Optional[torch.Tensor]]:
    Hv = torch.autograd.grad(grad_params, params, grad_outputs = [v,],
                              retain_graph = True)
    return Hv

def get_grad_params(f : List[torch.Tensor], params : List[torch.Tensor]) -> List[Optional[torch.Tensor]]:
    grad_params = torch.autograd.grad(f, params, create_graph = True)
    return grad_params

# Define x and y
x = torch.randn(1, 28, 28).to(device)
y = torch.randint(10, (1,)).to(device)

# Get gradients while using jit -- this works
@torch.jit.script
def grad_params_parallel(f : List[torch.Tensor], params : List[torch.Tensor]):
    assert torch.jit.isinstance(f, List[torch.Tensor])
    futures: List[torch.jit.Future[List[Optional[torch.Tensor]]]] = []
    for p in params:
        futures.append(torch.jit.fork(get_grad_params, f, [p]))
    
    grad_params : List[List[Optional[torch.Tensor]]] = []
    for future in futures:
        g : List[Optional[torch.Tensor]] = torch.jit.wait(future)
        grad_params.append(g)

    return grad_params

grad_params = grad_params_parallel([loss_fn(model(x), y),], list(model.parameters()))

hv2 = vmap(hessian_vector_product2, in_dims=(None, 0, None)) # Use vmap to vectorize hvps

# Get hvps w.r.t. layers in parallel
@torch.jit.script
def hvp_parallel(params : List[torch.Tensor], vs : List[Optional[torch.Tensor]], grad_params: List[List[torch.Tensor]], detach : bool = True):
    futures: List[torch.jit.Future[List[Optional[torch.Tensor]]]] = []
    for p, v, g in zip(params, vs, grad_params):
        futures.append(torch.jit.fork(hv2, [p], v, g))

    hvps : List[List[Optional[torch.Tensor]]] = []
    for future in futures:
        hvp = torch.jit.wait(future)
        hvps.append(hvp)

    return hvps

# Get HVPs with 10 random vectors
n_v = 10
vs : List[Optional[torch.Tensor]] = []
for p in model.parameters():
    vs.append(torch.randn(n_v, *tuple(p.shape)).to(device))
hvps = hvp_parallel(list(model.parameters()), vs, grad_params)
print(hvps[0][0].shape) # Got torch.Size([20, 784]), expected torch.Size([10, 20, 784])
print(hvps[1][0].shape) # Got torch.Size([20]), expected torch.Size([10, 20])
print(hvps[2][0].shape) # Got torch.Size([10, 20]), expected torch.Size([10, 10, 20])
print(hvps[3][0].shape) # Got torch.Size([10]), expected torch.Size([10, 10])
```

### 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: Could not collect
Libc version: glibc-2.35

Python version: 3.10.6 (main, Mar 10 2023, 10:55:28) [GCC 11.3.0] (64-bit runtime)
Python platform: Linux-5.15.0-67-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 TITAN V
GPU 1: NVIDIA TITAN V
GPU 2: NVIDIA TITAN V
GPU 3: NVIDIA TITAN V
GPU 4: NVIDIA TITAN V
GPU 5: NVIDIA TITAN V
GPU 6: NVIDIA TITAN V
GPU 7: NVIDIA TITAN V

Nvidia driver version: 520.61.05
cuDNN version: Probably one of the following:
/usr/lib/x86_64-linux-gnu/libcudnn.so.8.6.0
/usr/lib/x86_64-linux-gnu/libcudnn_adv_infer.so.8.6.0
/usr/lib/x86_64-linux-gnu/libcudnn_adv_train.so.8.6.0
/usr/lib/x86_64-linux-gnu/libcudnn_cnn_infer.so.8.6.0
/usr/lib/x86_64-linux-gnu/libcudnn_cnn_train.so.8.6.0
/usr/lib/x86_64-linux-gnu/libcudnn_ops_infer.so.8.6.0
/usr/lib/x86_64-linux-gnu/libcudnn_ops_train.so.8.6.0
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):                          64
On-line CPU(s) list:             0-63
Vendor ID:                       GenuineIntel
Model name:                      Intel(R) Xeon(R) CPU E5-2698 v3 @ 2.30GHz
CPU family:                      6
Model:                           63
Thread(s) per core:              2
Core(s) per socket:              16
Socket(s):                       2
Stepping:                        2
CPU max MHz:                     3600.0000
CPU min MHz:                     1200.0000
BogoMIPS:                        4599.86
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 dca sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm abm cpuid_fault epb invpcid_single pti intel_ppin ssbd ibrs ibpb stibp tpr_shadow vnmi flexpriority ept vpid ept_ad fsgsbase tsc_adjust bmi1 avx2 smep bmi2 erms invpcid cqm xsaveopt cqm_llc cqm_occup_llc dtherm ida arat pln pts md_clear flush_l1d
Virtualization:                  VT-x
L1d cache:                       1 MiB (32 instances)
L1i cache:                       1 MiB (32 instances)
L2 cache:                        8 MiB (32 instances)
L3 cache:                        80 MiB (2 instances)
NUMA node(s):                    2
NUMA node0 CPU(s):               0-15,32-47
NUMA node1 CPU(s):               16-31,48-63
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:   Mitigation; Clear CPU buffers; SMT vulnerable
Vulnerability Retbleed:          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; 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] functorch==2.0.0
[pip3] numpy==1.23.1
[pip3] pytorch-ranger==0.1.1
[pip3] torch==2.0.0
[pip3] torch-optimizer==0.3.0
[pip3] torchsummary==1.5.1
[pip3] torchvision==0.15.1
[pip3] triton==2.0.0
[conda] Could not collect

cc @EikanWang @jgong5 @wenzhe-nrv @sanchitintel @zou3519 @Chillee @samdow @soumith @kshitij12345 @janeyx99