Repository: pytorch
Issue: torch.nn.functional.interpolate completely broken with torch.jit.script and torch.fx
Labels: oncall: jit

### 🐛 Describe the bug

The funcion `torch.nn.functional.interpolate` can't be used at the same time with `torch.jit.script` and `torchvision.models.feature_extraction.create_feature_extractor` (that uses `torch.fx`) if the destination size is an input.

First try:
If H and W are tensors, `jit` doesn't work but `fx` does.

Code:

```python
import math

import torch
from torchvision.models.feature_extraction import create_feature_extractor


class Cursed(torch.nn.Module):
    def forward(
        self, x: torch.Tensor, h: torch.Tensor, w: torch.Tensor
    ) -> torch.Tensor:
        y = torch.nn.functional.interpolate(x, size=(h, w))
        return y


model = Cursed()
try:
    model_script = torch.jit.script(model)
    print("JIT SCRIPT OK")
except Exception as e:
    print("JIT SCRIPT ERROR")
    print(e)

try:
    fe = create_feature_extractor(model, [])
    print("FEATURE EXTRACTOR OK")
except Exception as e:
    print("FEATURE EXTRACTOR ERROR")
    print(e)

```

Output:

```
JIT SCRIPT ERROR

Arguments for call are not valid.
The following variants are available:
  
  interpolate(Tensor input, int? size=None, float[]? scale_factor=None, str mode="nearest", bool? align_corners=None, bool? recompute_scale_factor=None, bool antialias=False) -> Tensor:
  Expected a value of type 'Optional[int]' for argument 'size' but instead found type 'Tuple[Tensor, Tensor]'.
  
  interpolate(Tensor input, int[]? size=None, float[]? scale_factor=None, str mode="nearest", bool? align_corners=None, bool? recompute_scale_factor=None, bool antialias=False) -> Tensor:
  Expected a value of type 'Optional[List[int]]' for argument 'size' but instead found type 'Tuple[Tensor, Tensor]'.
  
  interpolate(Tensor input, int? size=None, float? scale_factor=None, str mode="nearest", bool? align_corners=None, bool? recompute_scale_factor=None, bool antialias=False) -> Tensor:
  Expected a value of type 'Optional[int]' for argument 'size' but instead found type 'Tuple[Tensor, Tensor]'.
  
  interpolate(Tensor input, int[]? size=None, float? scale_factor=None, str mode="nearest", bool? align_corners=None, bool? recompute_scale_factor=None, bool antialias=False) -> Tensor:
  Expected a value of type 'Optional[List[int]]' for argument 'size' but instead found type 'Tuple[Tensor, Tensor]'.

The original call is:
  File "/home/federico/test.py", line 11
        self, x: torch.Tensor, h: torch.Tensor, w: torch.Tensor
    ) -> torch.Tensor:
        y = torch.nn.functional.interpolate(x, size=(h, w))
            ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ <--- HERE
        return y

/home/federico/venvs/myenv/lib/python3.10/site-packages/torch/overrides.py:110: UserWarning: 'has_cuda' is deprecated, please use 'torch.backends.cuda.is_built()'
  torch.has_cuda,
/home/federico/venvs/myenv/lib/python3.10/site-packages/torch/overrides.py:111: UserWarning: 'has_cudnn' is deprecated, please use 'torch.backends.cudnn.is_available()'
  torch.has_cudnn,
/home/federico/venvs/myenv/lib/python3.10/site-packages/torch/overrides.py:117: UserWarning: 'has_mps' is deprecated, please use 'torch.backends.mps.is_built()'
  torch.has_mps,
/home/federico/venvs/myenv/lib/python3.10/site-packages/torch/overrides.py:118: UserWarning: 'has_mkldnn' is deprecated, please use 'torch.backends.mkldnn.is_available()'
  torch.has_mkldnn,
FEATURE EXTRACTOR OK
```

Second try:
Converting tensors to numbers doesn't change the result (only the error changes).

Code:

```python
import math

import torch
from torchvision.models.feature_extraction import create_feature_extractor


class Cursed(torch.nn.Module):
    def forward(
        self, x: torch.Tensor, h: torch.Tensor, w: torch.Tensor
    ) -> torch.Tensor:
        h_ = h.item()
        w_ = w.item()
        y = torch.nn.functional.interpolate(x, size=(h_, w_))
        return y


model = Cursed()
try:
    model_script = torch.jit.script(model)
    print("JIT SCRIPT OK")
except Exception as e:
    print("JIT SCRIPT ERROR")
    print(e)

try:
    fe = create_feature_extractor(model, [])
    print("FEATURE EXTRACTOR OK")
except Exception as e:
    print("FEATURE EXTRACTOR ERROR")
    print(e)

```

Output:

```
JIT SCRIPT ERROR

Arguments for call are not valid.
The following variants are available:
  
  interpolate(Tensor input, int? size=None, float[]? scale_factor=None, str mode="nearest", bool? align_corners=None, bool? recompute_scale_factor=None, bool antialias=False) -> Tensor:
  Expected a value of type 'Optional[int]' for argument 'size' but instead found type 'Tuple[number, number]'.
  
  interpolate(Tensor input, int[]? size=None, float[]? scale_factor=None, str mode="nearest", bool? align_corners=None, bool? recompute_scale_factor=None, bool antialias=False) -> Tensor:
  Expected a value of type 'Optional[List[int]]' for argument 'size' but instead found type 'Tuple[number, number]'.
  
  interpolate(Tensor input, int? size=None, float? scale_factor=None, str mode="nearest", bool? align_corners=None, bool? recompute_scale_factor=None, bool antialias=False) -> Tensor:
  Expected a value of type 'Optional[int]' for argument 'size' but instead found type 'Tuple[number, number]'.
  
  interpolate(Tensor input, int[]? size=None, float? scale_factor=None, str mode="nearest", bool? align_corners=None, bool? recompute_scale_factor=None, bool antialias=False) -> Tensor:
  Expected a value of type 'Optional[List[int]]' for argument 'size' but instead found type 'Tuple[number, number]'.

The original call is:
  File "/home/federico/test.py", line 13
        h_ = h.item()
        w_ = w.item()
        y = torch.nn.functional.interpolate(x, size=(h_, w_))
            ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ <--- HERE
        return y

/home/federico/venvs/myenv/lib/python3.10/site-packages/torch/overrides.py:110: UserWarning: 'has_cuda' is deprecated, please use 'torch.backends.cuda.is_built()'
  torch.has_cuda,
/home/federico/venvs/myenv/lib/python3.10/site-packages/torch/overrides.py:111: UserWarning: 'has_cudnn' is deprecated, please use 'torch.backends.cudnn.is_available()'
  torch.has_cudnn,
/home/federico/venvs/myenv/lib/python3.10/site-packages/torch/overrides.py:117: UserWarning: 'has_mps' is deprecated, please use 'torch.backends.mps.is_built()'
  torch.has_mps,
/home/federico/venvs/myenv/lib/python3.10/site-packages/torch/overrides.py:118: UserWarning: 'has_mkldnn' is deprecated, please use 'torch.backends.mkldnn.is_available()'
  torch.has_mkldnn,
FEATURE EXTRACTOR OK
```

Third try:
With an explicit cast `jit` works but `fx` doesn't.

Code:
```python
import math

import torch
from torchvision.models.feature_extraction import create_feature_extractor


class Cursed(torch.nn.Module):
    def forward(
        self, x: torch.Tensor, h: torch.Tensor, w: torch.Tensor
    ) -> torch.Tensor:
        h_ = int(h.item())
        w_ = int(w.item())
        y = torch.nn.functional.interpolate(x, size=(h_, w_))
        return y


model = Cursed()
try:
    model_script = torch.jit.script(model)
    print("JIT SCRIPT OK")
except Exception as e:
    print("JIT SCRIPT ERROR")
    print(e)

try:
    fe = create_feature_extractor(model, [])
    print("FEATURE EXTRACTOR OK")
except Exception as e:
    print("FEATURE EXTRACTOR ERROR")
    print(e)
```

Output:

```
JIT SCRIPT OK
FEATURE EXTRACTOR ERROR
int() argument must be a string, a bytes-like object or a real number, not 'Proxy'
```

Fourth try:
With a trick to cast without an explicit cast `jit` doesn't work but `fx` does. It seems like that `interpolate` doesn`t understand that the variables are integers ([math.floor](https://docs.python.org/3/library/math.html#math.floor) returns an integer)

Code:
```python
import math

import torch
from torchvision.models.feature_extraction import create_feature_extractor


class Cursed(torch.nn.Module):
    def forward(
        self, x: torch.Tensor, h: torch.Tensor, w: torch.Tensor
    ) -> torch.Tensor:
        h_ = math.floor(h.item())
        w_ = math.floor(w.item())
        y = torch.nn.functional.interpolate(x, size=(h_, w_))
        return y


model = Cursed()
try:
    model_script = torch.jit.script(model)
    print("JIT SCRIPT OK")
except Exception as e:
    print("JIT SCRIPT ERROR")
    print(e)

try:
    fe = create_feature_extractor(model, [])
    print("FEATURE EXTRACTOR OK")
except Exception as e:
    print("FEATURE EXTRACTOR ERROR")
    print(e)

```

Output:

```
JIT SCRIPT ERROR

Arguments for call are not valid.
The following variants are available:
  
  interpolate(Tensor input, int? size=None, float[]? scale_factor=None, str mode="nearest", bool? align_corners=None, bool? recompute_scale_factor=None, bool antialias=False) -> Tensor:
  Expected a value of type 'Optional[int]' for argument 'size' but instead found type 'Tuple[number, number]'.
  
  interpolate(Tensor input, int[]? size=None, float[]? scale_factor=None, str mode="nearest", bool? align_corners=None, bool? recompute_scale_factor=None, bool antialias=False) -> Tensor:
  Expected a value of type 'Optional[List[int]]' for argument 'size' but instead found type 'Tuple[number, number]'.
  
  interpolate(Tensor input, int? size=None, float? scale_factor=None, str mode="nearest", bool? align_corners=None, bool? recompute_scale_factor=None, bool antialias=False) -> Tensor:
  Expected a value of type 'Optional[int]' for argument 'size' but instead found type 'Tuple[number, number]'.
  
  interpolate(Tensor input, int[]? size=None, float? scale_factor=None, str mode="nearest", bool? align_corners=None, bool? recompute_scale_factor=None, bool antialias=False) -> Tensor:
  Expected a value of type 'Optional[List[int]]' for argument 'size' but instead found type 'Tuple[number, number]'.

The original call is:
  File "/home/federico/test.py", line 13
        h_ = math.floor(h.item())
        w_ = math.floor(w.item())
        y = torch.nn.functional.interpolate(x, size=(h_, w_))
            ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ <--- HERE
        return y

/home/federico/venvs/myenv/lib/python3.10/site-packages/torch/overrides.py:110: UserWarning: 'has_cuda' is deprecated, please use 'torch.backends.cuda.is_built()'
  torch.has_cuda,
/home/federico/venvs/myenv/lib/python3.10/site-packages/torch/overrides.py:111: UserWarning: 'has_cudnn' is deprecated, please use 'torch.backends.cudnn.is_available()'
  torch.has_cudnn,
/home/federico/venvs/myenv/lib/python3.10/site-packages/torch/overrides.py:117: UserWarning: 'has_mps' is deprecated, please use 'torch.backends.mps.is_built()'
  torch.has_mps,
/home/federico/venvs/myenv/lib/python3.10/site-packages/torch/overrides.py:118: UserWarning: 'has_mkldnn' is deprecated, please use 'torch.backends.mkldnn.is_available()'
  torch.has_mkldnn,
FEATURE EXTRACTOR OK
```

Is there a way to use the example with both `jit` and `fx`?

### Versions

Collecting environment information...
PyTorch version: 2.1.0+cu118
Is debug build: False
CUDA used to build PyTorch: 11.8
ROCM used to build PyTorch: N/A

OS: Ubuntu 22.04.4 LTS (x86_64)
GCC version: (Ubuntu 11.4.0-1ubuntu1~22.04) 11.4.0
Clang version: Could not collect
CMake version: version 3.27.0
Libc version: glibc-2.35

Python version: 3.10.12 (main, Nov 20 2023, 15:14:05) [GCC 11.4.0] (64-bit runtime)
Python platform: Linux-6.5.0-41-generic-x86_64-with-glibc2.35
Is CUDA available: True
CUDA runtime version: 11.8.89
CUDA_MODULE_LOADING set to: LAZY
GPU models and configuration: GPU 0: NVIDIA GeForce RTX 2080 Ti
Nvidia driver version: 535.171.04
cuDNN version: Probably one of the following:
/usr/local/cuda-11.8/targets/x86_64-linux/lib/libcudnn.so.8.9.2
/usr/local/cuda-11.8/targets/x86_64-linux/lib/libcudnn_adv_infer.so.8.9.2
/usr/local/cuda-11.8/targets/x86_64-linux/lib/libcudnn_adv_train.so.8.9.2
/usr/local/cuda-11.8/targets/x86_64-linux/lib/libcudnn_cnn_infer.so.8.9.2
/usr/local/cuda-11.8/targets/x86_64-linux/lib/libcudnn_cnn_train.so.8.9.2
/usr/local/cuda-11.8/targets/x86_64-linux/lib/libcudnn_ops_infer.so.8.9.2
/usr/local/cuda-11.8/targets/x86_64-linux/lib/libcudnn_ops_train.so.8.9.2
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) i7-10700 CPU @ 2.90GHz
CPU family:                         6
Model:                              165
Thread(s) per core:                 2
Core(s) per socket:                 8
Socket(s):                          1
Stepping:                           5
CPU max MHz:                        4800,0000
CPU min MHz:                        800,0000
BogoMIPS:                           5799.77
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 ibrs_enhanced tpr_shadow flexpriority ept vpid ept_ad fsgsbase tsc_adjust 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 vnmi pku ospke 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 Gather data sampling: Mitigation; Microcode
Vulnerability Itlb multihit:        KVM: Mitigation: VMX disabled
Vulnerability L1tf:                 Not affected
Vulnerability Mds:                  Not affected
Vulnerability Meltdown:             Not affected
Vulnerability Mmio stale data:      Mitigation; Clear CPU buffers; SMT vulnerable
Vulnerability Retbleed:             Mitigation; Enhanced IBRS
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; BHI Syscall hardening, KVM SW loop
Vulnerability Srbds:                Mitigation; Microcode
Vulnerability Tsx async abort:      Not affected

Versions of relevant libraries:
[pip3] mypy-extensions==1.0.0
[pip3] numpy==1.26.4
[pip3] onnx==1.12.0
[pip3] onnxruntime==1.17.0
[pip3] pytorch-lightning==2.3.3
[pip3] pytorch3d==0.7.5+pyt210cu118
[pip3] torch==2.1.0+cu118
[pip3] torchmetrics==1.4.0.post0
[pip3] torchvision==0.16.0+cu118
[pip3] triton==2.1.0
[conda] Could not collect

cc @EikanWang @jgong5 @wenzhe-nrv @sanchitintel