Repository: pytorch
Issue: Calling jacrev with LSTM and functional_call  gives error
Labels: triaged,module: functorch

### 🐛 Describe the bug

I wanted to calculate some jacobian from the output of an LSTM, so I use funcitonal_call and feed the parameter of LSTM as input. 
```python
import torch
from torch.func import functional_call, jacrev, jacfwd
device = 'cuda'

lstm = torch.nn.LSTM(
    input_size=32,
    hidden_size=32,
    num_layers=1,
    batch_first=True,
).to(device)
dict_params = dict(lstm.named_parameters())

input_batch = torch.randn(11, 10, 32).to(device)

def func_call(params, input_batch):
    output, _ = functional_call(lstm, params, input_batch)
    return output.mean()

jac = jacrev(
    lambda params: func_call(params=params, input_batch=input_batch),
    argnums=0
)(dict_params)
```
However, it gives me error like this
```error
---------------------------------------------------------------------------
RuntimeError                              Traceback (most recent call last)
Cell In[9], line 1
----> 1 jac = jacfwd(
      2     lambda params: func_call(params=params, input_batch=input_batch),
      3     argnums=0
      4 )(dict_params)

File [~/.conda/envs/forl-proj/lib/python3.10/site-packages/torch/_functorch/eager_transforms.py:1128](https://vscode-remote+ssh-002dremote-002bquanta-002etitan.vscode-resource.vscode-cdn.net/home/quanta/Projects/FoRL-project/test_code/~/.conda/envs/forl-proj/lib/python3.10/site-packages/torch/_functorch/eager_transforms.py:1128), in jacfwd..wrapper_fn(*args)
   1125     _, jvp_out = output
   1126     return jvp_out
-> 1128 results = vmap(push_jvp, randomness=randomness)(basis)
   1129 if has_aux:
   1130     results, aux = results

File [~/.conda/envs/forl-proj/lib/python3.10/site-packages/torch/_functorch/vmap.py:434](https://vscode-remote+ssh-002dremote-002bquanta-002etitan.vscode-resource.vscode-cdn.net/home/quanta/Projects/FoRL-project/test_code/~/.conda/envs/forl-proj/lib/python3.10/site-packages/torch/_functorch/vmap.py:434), in vmap..wrapped(*args, **kwargs)
    430     return _chunked_vmap(func, flat_in_dims, chunks_flat_args,
    431                          args_spec, out_dims, randomness, **kwargs)
    433 # If chunk_size is not specified.
--> 434 return _flat_vmap(
    435     func, batch_size, flat_in_dims, flat_args, args_spec, out_dims, randomness, **kwargs
    436 )

File [~/.conda/envs/forl-proj/lib/python3.10/site-packages/torch/_functorch/vmap.py:39](https://vscode-remote+ssh-002dremote-002bquanta-002etitan.vscode-resource.vscode-cdn.net/home/quanta/Projects/FoRL-project/test_code/~/.conda/envs/forl-proj/lib/python3.10/site-packages/torch/_functorch/vmap.py:39), in doesnt_support_saved_tensors_hooks..fn(*args, **kwargs)
     36 @functools.wraps(f)
     37 def fn(*args, **kwargs):
     38     with torch.autograd.graph.disable_saved_tensors_hooks(message):
---> 39         return f(*args, **kwargs)

File [~/.conda/envs/forl-proj/lib/python3.10/site-packages/torch/_functorch/vmap.py:619](https://vscode-remote+ssh-002dremote-002bquanta-002etitan.vscode-resource.vscode-cdn.net/home/quanta/Projects/FoRL-project/test_code/~/.conda/envs/forl-proj/lib/python3.10/site-packages/torch/_functorch/vmap.py:619), in _flat_vmap(func, batch_size, flat_in_dims, flat_args, args_spec, out_dims, randomness, **kwargs)
    617 try:
    618     batched_inputs = _create_batched_inputs(flat_in_dims, flat_args, vmap_level, args_spec)
--> 619     batched_outputs = func(*batched_inputs, **kwargs)
    620     return _unwrap_batched(batched_outputs, out_dims, vmap_level, batch_size, func)
    621 finally:

File [~/.conda/envs/forl-proj/lib/python3.10/site-packages/torch/_functorch/eager_transforms.py:1119](https://vscode-remote+ssh-002dremote-002bquanta-002etitan.vscode-resource.vscode-cdn.net/home/quanta/Projects/FoRL-project/test_code/~/.conda/envs/forl-proj/lib/python3.10/site-packages/torch/_functorch/eager_transforms.py:1119), in jacfwd..wrapper_fn..push_jvp(basis)
   1118 def push_jvp(basis):
-> 1119     output = _jvp_with_argnums(func, args, basis, argnums=argnums, has_aux=has_aux)
   1120     # output[0] is the output of `func(*args)`
   1121     error_if_complex("jacfwd", output[0], is_input=False)

File [~/.conda/envs/forl-proj/lib/python3.10/site-packages/torch/_functorch/vmap.py:39](https://vscode-remote+ssh-002dremote-002bquanta-002etitan.vscode-resource.vscode-cdn.net/home/quanta/Projects/FoRL-project/test_code/~/.conda/envs/forl-proj/lib/python3.10/site-packages/torch/_functorch/vmap.py:39), in doesnt_support_saved_tensors_hooks..fn(*args, **kwargs)
     36 @functools.wraps(f)
     37 def fn(*args, **kwargs):
     38     with torch.autograd.graph.disable_saved_tensors_hooks(message):
---> 39         return f(*args, **kwargs)

File [~/.conda/envs/forl-proj/lib/python3.10/site-packages/torch/_functorch/eager_transforms.py:965](https://vscode-remote+ssh-002dremote-002bquanta-002etitan.vscode-resource.vscode-cdn.net/home/quanta/Projects/FoRL-project/test_code/~/.conda/envs/forl-proj/lib/python3.10/site-packages/torch/_functorch/eager_transforms.py:965), in _jvp_with_argnums(func, primals, tangents, argnums, strict, has_aux)
    963     primals = _wrap_all_tensors(primals, level)
    964     duals = _replace_args(primals, duals, argnums)
--> 965 result_duals = func(*duals)
    966 if has_aux:
    967     if not (isinstance(result_duals, tuple) and len(result_duals) == 2):

Cell In[9], line 2, in (params)
      1 jac = jacfwd(
----> 2     lambda params: func_call(params=params, input_batch=input_batch),
      3     argnums=0
      4 )(dict_params)

Cell In[7], line 2, in func_call(params, input_batch)
      1 def func_call(params, input_batch):
----> 2     output, _ = functional_call(lstm, params, input_batch)
      3     return output.mean()

File [~/.conda/envs/forl-proj/lib/python3.10/site-packages/torch/_functorch/functional_call.py:143](https://vscode-remote+ssh-002dremote-002bquanta-002etitan.vscode-resource.vscode-cdn.net/home/quanta/Projects/FoRL-project/test_code/~/.conda/envs/forl-proj/lib/python3.10/site-packages/torch/_functorch/functional_call.py:143), in functional_call(module, parameter_and_buffer_dicts, args, kwargs, tie_weights, strict)
    137 else:
    138     raise ValueError(
    139         f"Expected parameter_and_buffer_dicts to be a dict, or a list[/tuple](https://vscode-remote+ssh-002dremote-002bquanta-002etitan.vscode-resource.vscode-cdn.net/tuple) of dicts, "
    140         f"but got {type(parameter_and_buffer_dicts)}"
    141     )
--> 143 return nn.utils.stateless._functional_call(
    144     module,
    145     parameters_and_buffers,
    146     args,
    147     kwargs,
    148     tie_weights=tie_weights,
    149     strict=strict,
    150 )

File [~/.conda/envs/forl-proj/lib/python3.10/site-packages/torch/nn/utils/stateless.py:262](https://vscode-remote+ssh-002dremote-002bquanta-002etitan.vscode-resource.vscode-cdn.net/home/quanta/Projects/FoRL-project/test_code/~/.conda/envs/forl-proj/lib/python3.10/site-packages/torch/nn/utils/stateless.py:262), in _functional_call(module, parameters_and_buffers, args, kwargs, tie_weights, strict)
    258     args = (args,)
    259 with _reparametrize_module(
    260     module, parameters_and_buffers, tie_weights=tie_weights, strict=strict
    261 ):
--> 262     return module(*args, **kwargs)

File [~/.conda/envs/forl-proj/lib/python3.10/site-packages/torch/nn/modules/module.py:1501](https://vscode-remote+ssh-002dremote-002bquanta-002etitan.vscode-resource.vscode-cdn.net/home/quanta/Projects/FoRL-project/test_code/~/.conda/envs/forl-proj/lib/python3.10/site-packages/torch/nn/modules/module.py:1501), in Module._call_impl(self, *args, **kwargs)
   1496 # If we don't have any hooks, we want to skip the rest of the logic in
   1497 # this function, and just call forward.
   1498 if not (self._backward_hooks or self._backward_pre_hooks or self._forward_hooks or self._forward_pre_hooks
   1499         or _global_backward_pre_hooks or _global_backward_hooks
   1500         or _global_forward_hooks or _global_forward_pre_hooks):
-> 1501     return forward_call(*args, **kwargs)
   1502 # Do not call functions when jit is used
   1503 full_backward_hooks, non_full_backward_hooks = [], []

File [~/.conda/envs/forl-proj/lib/python3.10/site-packages/torch/nn/modules/rnn.py:762](https://vscode-remote+ssh-002dremote-002bquanta-002etitan.vscode-resource.vscode-cdn.net/home/quanta/Projects/FoRL-project/test_code/~/.conda/envs/forl-proj/lib/python3.10/site-packages/torch/nn/modules/rnn.py:762), in LSTM.forward(self, input, hx)
    760 if not torch.jit.is_scripting():
    761     if self._weights_have_changed():
--> 762         self._init_flat_weights()
    764 orig_input = input
    765 # xxx: isinstance check needs to be in conditional for TorchScript to compile

File [~/.conda/envs/forl-proj/lib/python3.10/site-packages/torch/nn/modules/rnn.py:139](https://vscode-remote+ssh-002dremote-002bquanta-002etitan.vscode-resource.vscode-cdn.net/home/quanta/Projects/FoRL-project/test_code/~/.conda/envs/forl-proj/lib/python3.10/site-packages/torch/nn/modules/rnn.py:139), in RNNBase._init_flat_weights(self)
    135 self._flat_weights = [getattr(self, wn) if hasattr(self, wn) else None
    136                       for wn in self._flat_weights_names]
    137 self._flat_weight_refs = [weakref.ref(w) if w is not None else None
    138                           for w in self._flat_weights]
--> 139 self.flatten_parameters()

File [~/.conda/envs/forl-proj/lib/python3.10/site-packages/torch/nn/modules/rnn.py:176](https://vscode-remote+ssh-002dremote-002bquanta-002etitan.vscode-resource.vscode-cdn.net/home/quanta/Projects/FoRL-project/test_code/~/.conda/envs/forl-proj/lib/python3.10/site-packages/torch/nn/modules/rnn.py:176), in RNNBase.flatten_parameters(self)
    170         return
    172 # If any parameters alias, we fall back to the slower, copying code path. This is
    173 # a sufficient check, because overlapping parameter buffers that don't completely
    174 # alias would break the assumptions of the uniqueness check in
    175 # Module.named_parameters().
--> 176 unique_data_ptrs = {p.data_ptr() for p in self._flat_weights}
    177 if len(unique_data_ptrs) != len(self._flat_weights):
    178     return

File [~/.conda/envs/forl-proj/lib/python3.10/site-packages/torch/nn/modules/rnn.py:176](https://vscode-remote+ssh-002dremote-002bquanta-002etitan.vscode-resource.vscode-cdn.net/home/quanta/Projects/FoRL-project/test_code/~/.conda/envs/forl-proj/lib/python3.10/site-packages/torch/nn/modules/rnn.py:176), in (.0)
    170         return
    172 # If any parameters alias, we fall back to the slower, copying code path. This is
    173 # a sufficient check, because overlapping parameter buffers that don't completely
    174 # alias would break the assumptions of the uniqueness check in
    175 # Module.named_parameters().
--> 176 unique_data_ptrs = {p.data_ptr() for p in self._flat_weights}
    177 if len(unique_data_ptrs) != len(self._flat_weights):
    178     return

RuntimeError: Cannot access data pointer of Tensor that doesn't have storage
```
It says something like `self._flat_weights` 's matrix does not have storage when calling `Tensor.data_ptr()` method. I also tried to print self._flat_weights when calling this funciton, it is 
```python
[GradTrackingTensor(lvl=1, value=
    Parameter containing:
    tensor([[ 0.0152, -0.0061,  0.0816,  ..., -0.0025, -0.0326,  0.0344],
            [-0.0327, -0.0508, -0.1517,  ..., -0.0478,  0.1520,  0.0825],
            [ 0.0265, -0.0549, -0.1710,  ...,  0.0329, -0.0428,  0.0193],
            ...,
            [-0.1371,  0.0196, -0.0076,  ..., -0.1137, -0.1058,  0.0396],
            [ 0.0370, -0.0681,  0.0193,  ..., -0.0464,  0.0921, -0.1209],
            [-0.1082, -0.1462,  0.0414,  ..., -0.0778, -0.0856,  0.0774]],
           device='cuda:0', requires_grad=True)
), GradTrackingTensor(lvl=1, value=
    Parameter containing:
    tensor([[-0.1160, -0.0630,  0.1476,  ..., -0.0603, -0.1395, -0.1528],
            [ 0.1590, -0.1527,  0.1602,  ...,  0.0061,  0.0968,  0.0363],
            [-0.1380,  0.0860, -0.1754,  ..., -0.0117, -0.0765, -0.0704],
            ...,
            [ 0.1244, -0.1528, -0.1146,  ...,  0.0456,  0.1050,  0.0627],
            [ 0.1305,  0.1589, -0.1673,  ...,  0.0688,  0.0474, -0.0307],
            [ 0.0105, -0.0980, -0.0172,  ..., -0.1360,  0.1762, -0.1558]],
           device='cuda:0', requires_grad=True)
), GradTrackingTensor(lvl=1, value=
    Parameter containing:
    tensor([ 0.0698,  0.1423, -0.0210, -0.0220,  0.1001,  0.1764, -0.1697,  0.0057,
             0.1385, -0.1068, -0.1130, -0.0255, -0.1064,  0.1258,  0.1567, -0.0853,
             0.0319,  0.0120,  0.0847, -0.1106,  0.0755,  0.0322,  0.0279, -0.1470,
            -0.1333,  0.0607,  0.0515, -0.1195, -0.1491,  0.0726, -0.1084,  0.1267,
            -0.1031,  0.0062,  0.1640, -0.0104, -0.0157, -0.1091,  0.0904,  0.1325,
            -0.1592, -0.0774,  0.0814,  0.0034,  0.0211,  0.1304,  0.1630,  0.0069,
            -0.1333,  0.1403,  0.1562,  0.0679, -0.1202,  0.0201,  0.1482, -0.1630,
             0.1039, -0.1758,  0.1112,  0.0051, -0.0909,  0.1661,  0.0383, -0.1568,
            -0.0799, -0.0284, -0.1319,  0.1042,  0.0036, -0.0238, -0.0283,  0.0488,
             0.0003,  0.1377,  0.1479, -0.1500, -0.0282, -0.0816,  0.0874,  0.0337,
             0.0751,  0.1523,  0.0758, -0.1458, -0.0024, -0.0427, -0.0908, -0.1383,
            -0.1672, -0.0800,  0.0409, -0.1399, -0.0732,  0.0321, -0.0251,  0.1068,
            -0.0486,  0.0953, -0.0917, -0.0501,  0.1601,  0.0244, -0.1500, -0.0720,
            -0.1479, -0.0894, -0.1014,  0.0321, -0.0648,  0.1300, -0.0359,  0.1623,
            -0.0691, -0.1325,  0.1291,  0.0251, -0.0148, -0.0885, -0.1415, -0.0860,
            -0.0983, -0.1115, -0.1256,  0.1620,  0.0293,  0.0540, -0.1512, -0.0097],
           device='cuda:0', requires_grad=True)
), GradTrackingTensor(lvl=1, value=
    Parameter containing:
    tensor([ 0.0405, -0.0769, -0.1045, -0.0878,  0.1220, -0.1439, -0.1761,  0.0604,
             0.0725,  0.0428,  0.1289,  0.1255, -0.0375,  0.1240, -0.0087, -0.0632,
             0.0611, -0.0453, -0.1217, -0.1690, -0.0899,  0.0293, -0.0544, -0.1171,
            -0.0123,  0.1762, -0.0029, -0.0878,  0.0648, -0.1616,  0.0643,  0.0523,
            -0.0807,  0.0242,  0.0982,  0.1478, -0.0666,  0.0869,  0.0363, -0.0100,
            -0.0016,  0.1506,  0.1727,  0.0422,  0.1144, -0.0533, -0.1611,  0.1124,
             0.0476, -0.0143,  0.1005,  0.0768, -0.0520,  0.0885, -0.0570, -0.0359,
             0.0745, -0.0665, -0.1128, -0.1228,  0.1578, -0.0029,  0.0960,  0.0956,
             0.1746,  0.0738, -0.1099,  0.1381, -0.1351,  0.0500, -0.0044,  0.1273,
            -0.1468, -0.0626, -0.0234,  0.1047,  0.1232,  0.0216,  0.1043,  0.0513,
             0.1348, -0.0211,  0.1674,  0.1112,  0.1559,  0.0566,  0.0557, -0.1758,
            -0.1657,  0.0520, -0.0968, -0.1095,  0.1301, -0.0020, -0.1110,  0.1186,
             0.0253,  0.1311,  0.0609,  0.0973, -0.0177, -0.0587,  0.1651,  0.1012,
             0.1693, -0.1229,  0.0474, -0.0748,  0.1236,  0.0510, -0.0586,  0.1208,
            -0.1384, -0.0365, -0.0905,  0.0042,  0.1580, -0.0101, -0.1153, -0.1726,
            -0.1128, -0.1615, -0.0982, -0.1030, -0.1070,  0.1587, -0.1468, -0.1594],
           device='cuda:0', requires_grad=True)
)]
```

### Versions

Collecting environment information...
PyTorch version: 2.0.0+cu118
Is debug build: False
CUDA used to build PyTorch: 11.8
ROCM used to build PyTorch: N/A

OS: Arch Linux (x86_64)
GCC version: (GCC) 13.1.1 20230429
Clang version: Could not collect
CMake version: version 3.26.3
Libc version: glibc-2.37

Python version: 3.10.11 (main, Apr 20 2023, 19:02:41) [GCC 11.2.0] (64-bit runtime)
Python platform: Linux-6.3.6-arch1-1-x86_64-with-glibc2.37
Is CUDA available: True
CUDA runtime version: 12.1.105
CUDA_MODULE_LOADING set to: LAZY
GPU models and configuration: GPU 0: NVIDIA GeForce RTX 2080 Ti
Nvidia driver version: 530.41.03
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):                          16
On-line CPU(s) list:             0-15
Vendor ID:                       GenuineIntel
Model name:                      Intel(R) Core(TM) i9-9900K CPU @ 3.60GHz
CPU family:                      6
Model:                           158
Thread(s) per core:              2
Core(s) per socket:              8
Socket(s):                       1
Stepping:                        12
CPU(s) scaling MHz:              84%
CPU max MHz:                     5000.0000
CPU min MHz:                     800.0000
BogoMIPS:                        7202.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 constant_tsc art 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 3dnowprefetch cpuid_fault epb invpcid_single ssbd ibrs ibpb stibp tpr_shadow vnmi flexpriority ept vpid ept_ad fsgsbase tsc_adjust sgx bmi1 avx2 smep bmi2 erms invpcid mpx rdseed adx smap clflushopt intel_pt xsaveopt xsavec xgetbv1 xsaves dtherm ida arat pln pts hwp hwp_notify hwp_act_window hwp_epp sgx_lc md_clear flush_l1d arch_capabilities
Virtualization:                  VT-x
L1d cache:                       256 KiB (8 instances)
L1i cache:                       256 KiB (8 instances)
L2 cache:                        2 MiB (8 instances)
L3 cache:                        16 MiB (1 instance)
NUMA node(s):                    1
NUMA node0 CPU(s):               0-15
Vulnerability Itlb multihit:     KVM: Mitigation: VMX disabled
Vulnerability L1tf:              Not affected
Vulnerability Mds:               Mitigation; Clear CPU buffers; SMT vulnerable
Vulnerability Meltdown:          Not affected
Vulnerability Mmio stale data:   Mitigation; Clear CPU buffers; SMT vulnerable
Vulnerability Retbleed:          Mitigation; IBRS
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; IBRS, IBPB conditional, STIBP conditional, RSB filling, PBRSB-eIBRS Not affected
Vulnerability Srbds:             Mitigation; Microcode
Vulnerability Tsx async abort:   Mitigation; TSX disabled

Versions of relevant libraries:
[pip3] numpy==1.23.5
[pip3] torch==2.0.0+cu118
[pip3] triton==2.0.0
[conda] numpy                     1.23.5                   pypi_0    pypi
[conda] torch                     2.0.0+cu118              pypi_0    pypi
[conda] triton                    2.0.0                    pypi_0    pypi
python collect_env.py  4.94s user 0.91s system 123% cpu 4.747 total

cc @zou3519 @Chillee @samdow @kshitij12345 @janeyx99
```[tasklist]
### Tasks
```