Repository: pytorch
Issue: Missing torch import in _contextlib.py when using torch.jit._recursive
Labels: needs reproduction,oncall: jit

### 🐛 Describe the bug

When attempting to use `torch.jit.script()`, we see the following `ImportError`.

```
10:47:31      modest/modest/serialize/serialize.py:275: in serialize_vocoder
10:47:31           vocoder = torch.jit.script(vocoder)
10:47:31       env/lib/python3.10/site-packages/torch/jit/_script.py:1284: in script
10:47:31           return torch.jit._recursive.create_script_module(
10:47:31       env/lib/python3.10/site-packages/torch/jit/_recursive.py:480: in create_script_module
10:47:31           return create_script_module_impl(nn_module, concrete_type, stubs_fn)
10:47:31       env/lib/python3.10/site-packages/torch/jit/_recursive.py:542: in create_script_module_impl
10:47:31           script_module = torch.jit.RecursiveScriptModule._construct(cpp_module, init_fn)
10:47:31       env/lib/python3.10/site-packages/torch/jit/_script.py:614: in _construct
10:47:31           init_fn(script_module)
10:47:31       env/lib/python3.10/site-packages/torch/jit/_recursive.py:520: in init_fn
10:47:31           scripted = create_script_module_impl(orig_value, sub_concrete_type, stubs_fn)
10:47:31       env/lib/python3.10/site-packages/torch/jit/_recursive.py:546: in create_script_module_impl
10:47:31           create_methods_and_properties_from_stubs(concrete_type, method_stubs, property_stubs)
10:47:31       _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
10:47:31       
10:47:31       concrete_type = <torch.ConcreteModuleType object at 0x7ff8ec4d5cb0>
10:47:31       method_stubs = [ScriptMethodStub(resolution_callback=<function createResolutionCallbackFromEnv.<locals>.<lambda> at 0x7ff8e6b3a680>, ...
10:47:31         (last_conv): Sequential(
10:47:31           (0): ReLU()
10:47:31           (1): Conv1d(2, 1, kernel_size=(3,), stride=(1,), padding=(1,))
10:47:31         )
10:47:31       )>)]
10:47:31       property_stubs = []
10:47:31       
10:47:31           def create_methods_and_properties_from_stubs(concrete_type, method_stubs, property_stubs):
10:47:31               method_defs = [m.def_ for m in method_stubs]
10:47:31               method_rcbs = [m.resolution_callback for m in method_stubs]
10:47:31               method_defaults = [get_default_args(m.original_method) for m in method_stubs]
10:47:31       
10:47:31               property_defs = [p.def_ for p in property_stubs]
10:47:31               property_rcbs = [p.resolution_callback for p in property_stubs]
10:47:31       
10:47:31       >       concrete_type._create_methods_and_properties(property_defs, property_rcbs, method_defs, method_rcbs, method_defaults)
10:47:31       E       RuntimeError:
10:47:31       E       undefined value torch:
10:47:31       E         File "/code/env/lib/python3.10/site-packages/torch/utils/_contextlib.py", line 56
10:47:31       E                   self.n_frames_per_step - (features.shape[2] % self.n_frames_per_step)
10:47:31       E               ) % self.n_frames_per_step
10:47:31       E               features = torch.nn.functional.pad(features, (0, padding))
10:47:31       E                          ~~~~~ <--- HERE
10:47:31       E
10:47:31       E               # Start with all zeros as conditioning
10:47:31       
10:47:31       env/lib/python3.10/site-packages/torch/jit/_recursive.py:397: RuntimeError
```

No idea what's going on, sadly. However, adding `import torch` to the `/code/env/lib/python3.10/site-packages/torch/utils/_contextlib.py` file makes the error go away.

### Versions

```
Collecting environment information...
PyTorch version: 2.0.0
Is debug build: False
CUDA used to build PyTorch: 11.8
ROCM used to build PyTorch: N/A

OS: Ubuntu 20.04.5 LTS (x86_64)
GCC version: (Ubuntu 9.4.0-1ubuntu1~20.04.1) 9.4.0
Clang version: Could not collect
CMake version: version 3.22.1
Libc version: glibc-2.31

Python version: 3.10.10 (main, Mar 21 2023, 18:45:11) [GCC 11.2.0] (64-bit runtime)
Python platform: Linux-5.15.0-1020-aws-x86_64-with-glibc2.31
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
Byte Order:                      Little Endian
Address sizes:                   46 bits physical, 48 bits virtual
CPU(s):                          96
On-line CPU(s) list:             0-95
Thread(s) per core:              2
Core(s) per socket:              24
Socket(s):                       2
NUMA node(s):                    2
Vendor ID:                       GenuineIntel
CPU family:                      6
Model:                           85
Model name:                      Intel(R) Xeon(R) Platinum 8275CL CPU @ 3.00GHz
Stepping:                        7
CPU MHz:                         3461.119
BogoMIPS:                        5999.99
Hypervisor vendor:               KVM
Virtualization type:             full
L1d cache:                       1.5 MiB
L1i cache:                       1.5 MiB
L2 cache:                        48 MiB
L3 cache:                        71.5 MiB
NUMA node0 CPU(s):               0-23,48-71
NUMA node1 CPU(s):               24-47,72-95
Vulnerability Itlb multihit:     KVM: Mitigation: VMX unsupported
Vulnerability L1tf:              Mitigation; PTE Inversion
Vulnerability Mds:               Vulnerable: Clear CPU buffers attempted, no microcode; SMT Host state unknown
Vulnerability Meltdown:          Mitigation; PTI
Vulnerability Mmio stale data:   Vulnerable: Clear CPU buffers attempted, no microcode; SMT Host state unknown
Vulnerability Retbleed:          Vulnerable
Vulnerability Spec store bypass: Vulnerable
Vulnerability Spectre v1:        Mitigation; usercopy/swapgs barriers and __user pointer sanitization
Vulnerability Spectre v2:        Mitigation; Retpolines, STIBP disabled, RSB filling
Vulnerability Srbds:             Not affected
Vulnerability Tsx async abort:   Not affected
Flags:                           fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush mmx fxsr sse sse2 ss ht syscall nx pdpe1gb rdtscp lm constant_tsc arch_perfmon rep_good nopl xtopology nonstop_tsc cpuid aperfmperf tsc_known_freq pni pclmulqdq monitor ssse3 fma cx16 pcid sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand hypervisor lahf_lm abm 3dnowprefetch invpcid_single pti fsgsbase tsc_adjust bmi1 avx2 smep bmi2 erms invpcid mpx avx512f avx512dq rdseed adx smap clflushopt clwb avx512cd avx512bw avx512vl xsaveopt xsavec xgetbv1 xsaves ida arat pku ospke

Versions of relevant libraries:
[pip3] fft-conv-pytorch==1.1.3
[pip3] flake8==3.9.2
[pip3] k2==1.23.4.dev20230324+cuda11.8.torch2.0.0
[pip3] mypy-extensions==1.0.0
[pip3] numpy==1.22.3
[pip3] torch==2.0.0
[pip3] torchaudio==2.0.0
[pip3] torchvision==0.15.0
[pip3] triton==2.0.0
[pip3] tritonclient==2.19.0
[conda] blas                      1.0                         mkl
[conda] ffmpeg                    4.3                  hf484d3e_0    pytorch
[conda] fft-conv-pytorch          1.1.3                    pypi_0    pypi
[conda] k2                        1.23.4.dev20230324+cuda11.8.torch2.0.0          pypi_0    pypi
[conda] mkl                       2021.4.0           h06a4308_640
[conda] mkl-service               2.4.0           py310h7f8727e_0
[conda] mkl_fft                   1.3.1           py310hd6ae3a3_0
[conda] mkl_random                1.2.2           py310h00e6091_0
[conda] numpy                     1.22.3          py310hfa59a62_0
[conda] numpy-base                1.22.3          py310h9585f30_0
[conda] pytorch                   2.0.0           py3.10_cuda11.8_cudnn8.7.0_0    pytorch
[conda] pytorch-cuda              11.8                 h7e8668a_3    pytorch
[conda] pytorch-mutex             1.0                        cuda    pytorch
[conda] torchaudio                2.0.0               py310_cu118    pytorch
[conda] torchtriton               2.0.0                     py310    pytorch
[conda] torchvision               0.15.0              py310_cu118    pytorch
[conda] tritonclient              2.19.0                   pypi_0    pypi
```

cc @EikanWang @jgong5 @wenzhe-nrv @sanchitintel