Repository: pytorch
Issue: [JIT] Deserialized `RecursiveScriptFunction` forgets default values for arguments.
Labels: oncall: jit

### 🐛 Describe the bug

Apologies if this is a known issue, I couldn't find anything in the issue tracker. When serializing and deserializing a `torch.jit.ScriptFunction` it seems that it forgets default values for arguments.



```python
loaded_foo = jit.load(...)  # function with signature (x:Tensor, y: Tensor? = None) -> Tensor
loaded_foo(x)
```

results in:

```python
RuntimeError: forward() is missing value for argument 'y'.
    Declaration: forward(__torch__.PlaceholderModule self, Tensor x, Tensor? y) -> Tensor
```

The same **does not happen** if we instead wrap the function in a module. 


<details> <summary> Full MWE with unit tests </summary>

```python
from tempfile import TemporaryDirectory
from typing import Optional

import torch
from torch import Tensor, jit, nn

def foo(x: Tensor, y: Optional[Tensor] = None) -> Tensor:
    if y is None:
        return x
    return x + y

class Foo(nn.Module):
    def forward(self, x: Tensor, y: Optional[Tensor] = None) -> Tensor:
        if y is None:
            return x
        return x + y

def test_function_typing():
    x = torch.randn(3, 4)
    y = torch.randn(3, 4)
    z = x + y

    assert torch.equal(foo(x), x)
    assert torch.equal(foo(x, y), z)

    # test with scripted
    scripted_foo = jit.script(foo)
    assert isinstance(scripted_foo, torch.jit.ScriptFunction)
    assert torch.equal(scripted_foo(x), x)
    assert torch.equal(scripted_foo(x, y), z)

    # serialize and deserialize
    with TemporaryDirectory() as folder:
        fname = f"{folder}/foo.pt"
        jit.save(scripted_foo, fname)
        foo_loaded = jit.load(fname)

    # assert isinstance(foo_loaded, torch.jit.ScriptFunction)  # ScriptModule!
    assert torch.equal(foo_loaded(x), x)
    assert torch.equal(foo_loaded(x, y), z)

def test_module_typing():
    x = torch.randn(3, 4)
    y = torch.randn(3, 4)
    z = x + y

    module = Foo()

    assert torch.equal(module(x), x)
    assert torch.equal(module(x, y), z)

    # test with scripted
    scripted_foo = jit.script(module)
    assert isinstance(scripted_foo, torch.jit.ScriptModule)
    assert torch.equal(scripted_foo(x), x)
    assert torch.equal(scripted_foo(x, y), z)

    # serialize and deserialize
    with TemporaryDirectory() as folder:
        fname = f"{folder}/foo.pt"
        jit.save(scripted_foo, fname)
        foo_loaded = jit.load(fname)

    assert isinstance(foo_loaded, torch.jit.ScriptModule)
    assert torch.equal(foo_loaded(x), x)
    assert torch.equal(foo_loaded(x, y), z)
```

</details>

### Versions

<details><summary> Collecting environment information... </summary>

```
PyTorch version: 2.2.0+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: (Ubuntu 11.4.0-1ubuntu1~22.04) 11.4.0
Clang version: 14.0.0-1ubuntu1.1
CMake version: version 3.28.1
Libc version: glibc-2.35

Python version: 3.11.7 (main, Feb  5 2024, 11:39:05) [GCC 11.4.0] (64-bit runtime)
Python platform: Linux-6.5.0-15-generic-x86_64-with-glibc2.35
Is CUDA available: False
CUDA runtime version: 12.3.107
CUDA_MODULE_LOADING set to: N/A
GPU models and configuration: Could not collect
Nvidia driver version: Could not collect
cuDNN version: Probably one of the following:
/usr/lib/x86_64-linux-gnu/libcudnn.so.8.9.7
/usr/lib/x86_64-linux-gnu/libcudnn_adv_infer.so.8.9.7
/usr/lib/x86_64-linux-gnu/libcudnn_adv_train.so.8.9.7
/usr/lib/x86_64-linux-gnu/libcudnn_cnn_infer.so.8.9.7
/usr/lib/x86_64-linux-gnu/libcudnn_cnn_train.so.8.9.7
/usr/lib/x86_64-linux-gnu/libcudnn_ops_infer.so.8.9.7
/usr/lib/x86_64-linux-gnu/libcudnn_ops_train.so.8.9.7
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):                             8
On-line CPU(s) list:                0-7
Vendor ID:                          GenuineIntel
Model name:                         11th Gen Intel(R) Core(TM) i7-11850H @ 2.50GHz
CPU family:                         6
Model:                              141
Thread(s) per core:                 1
Core(s) per socket:                 8
Socket(s):                          1
Stepping:                           1
CPU max MHz:                        4800,0000
CPU min MHz:                        800,0000
BogoMIPS:                           4992.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 tsc_known_freq 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 cat_l2 invpcid_single cdp_l2 ssbd ibrs ibpb stibp ibrs_enhanced tpr_shadow flexpriority ept vpid ept_ad fsgsbase tsc_adjust bmi1 avx2 smep bmi2 erms invpcid rdt_a avx512f avx512dq rdseed adx smap avx512ifma clflushopt clwb intel_pt avx512cd sha_ni avx512bw avx512vl xsaveopt xsavec xgetbv1 xsaves split_lock_detect dtherm ida arat pln pts hwp hwp_notify hwp_act_window hwp_epp hwp_pkg_req vnmi avx512vbmi umip pku ospke avx512_vbmi2 gfni vaes vpclmulqdq avx512_vnni avx512_bitalg tme avx512_vpopcntdq rdpid movdiri movdir64b fsrm avx512_vp2intersect md_clear ibt flush_l1d arch_capabilities
Virtualization:                     VT-x
L1d cache:                          384 KiB (8 instances)
L1i cache:                          256 KiB (8 instances)
L2 cache:                           10 MiB (8 instances)
L3 cache:                           24 MiB (1 instance)
NUMA node(s):                       1
NUMA node0 CPU(s):                  0-7
Vulnerability Gather data sampling: Mitigation; Microcode
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: Not affected
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; Enhanced / Automatic IBRS, IBPB conditional, RSB filling, PBRSB-eIBRS SW sequence
Vulnerability Srbds:                Not affected
Vulnerability Tsx async abort:      Not affected

Versions of relevant libraries:
[pip3] mypy==1.8.0
[pip3] mypy-extensions==1.0.0
[pip3] numpy==1.26.3
[pip3] torch==2.2.0
[pip3] torchinfo==1.8.0
[pip3] triton==2.2.0
[conda] Could not collect
```

</details>


cc @EikanWang @jgong5 @wenzhe-nrv @sanchitintel