Repository: pytorch
Issue: Multi-Threaded GraphModule / torch.fx inference raises an exception
Labels: module: multiprocessing,triaged,module: fx

### 🐛 Describe the bug

When doing two or more independent inferences in separate Threads with the model in the GraphModule format(output of torch.fx tracer), getting the following error:

> 
>   File "/home/user/anaconda3/lib/python3.9/site-packages/torch/fx/_symbolic_trace.py", line 473, in call_module
>     module_qualified_name = self.path_of_module(m)
>   File "/home/user/anaconda3/lib/python3.9/site-packages/torch/fx/_symbolic_trace.py", line 428, in path_of_module
>     raise NameError("module is not installed as a submodule")
> NameError: module is not installed as a submodule

If we replace **Thread** by **Process** everything will work just fine.

Here is the minimal example to reproduce the problem. The problem applies to all PyTorch version I've tried so far, including 2.0 and 2.1.

```
import torch
import torch.fx
import time
from threading import Thread
from multiprocessing import Process

def single_worker():
    model = torch.hub.load('pytorch/vision:v0.10.0', 'mobilenet_v2', pretrained=True)
    model.eval()
    model = torch.fx.symbolic_trace(model)
    for i in range(10):
        model(torch.rand(1,3,224,224))
        time.sleep(1)

# if we replace Thread by Process it will work well
t1 = Thread(target=single_worker,args=())
t2 = Thread(target=single_worker,args=())

#
t1.start()
t2.start()

t1.join()
t2.join()
```

### Versions

PyTorch version: 2.1.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: Could not collect
CMake version: version 3.26.0
Libc version: glibc-2.35

Python version: 3.9.13 (main, Aug 25 2022, 23:26:10)  [GCC 11.2.0] (64-bit runtime)
Python platform: Linux-6.2.0-36-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 GeForce RTX 3070 Laptop GPU
Nvidia driver version: 525.85.05
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):                             20
On-line CPU(s) list:                0-19
Vendor ID:                          GenuineIntel
Model name:                         12th Gen Intel(R) Core(TM) i7-12700H
CPU family:                         6
Model:                              154
Thread(s) per core:                 2
Core(s) per socket:                 14
Socket(s):                          1
Stepping:                           3
CPU max MHz:                        4700.0000
CPU min MHz:                        400.0000
BogoMIPS:                           5376.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 sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm abm 3dnowprefetch cpuid_fault epb cat_l2 cdp_l2 ssbd ibrs ibpb stibp ibrs_enhanced tpr_shadow vnmi flexpriority ept vpid ept_ad fsgsbase tsc_adjust bmi1 avx2 smep bmi2 erms invpcid rdt_a rdseed adx smap clflushopt clwb intel_pt sha_ni xsaveopt xsavec xgetbv1 xsaves split_lock_detect avx_vnni dtherm ida arat pln pts hwp hwp_notify hwp_act_window hwp_epp hwp_pkg_req hfi umip pku ospke waitpkg gfni vaes vpclmulqdq rdpid movdiri movdir64b fsrm md_clear serialize arch_lbr ibt flush_l1d arch_capabilities
Virtualization:                     VT-x
L1d cache:                          544 KiB (14 instances)
L1i cache:                          704 KiB (14 instances)
L2 cache:                           11.5 MiB (8 instances)
L3 cache:                           24 MiB (1 instance)
NUMA node(s):                       1
NUMA node0 CPU(s):                  0-19
Vulnerability Gather data sampling: Not affected
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 IBRS, IBPB conditional, RSB filling, PBRSB-eIBRS SW sequence
Vulnerability Srbds:                Not affected
Vulnerability Tsx async abort:      Not affected

Versions of relevant libraries:
[pip3] Aimet==torch-cpu-1.26.0
[pip3] AimetCommon==torch-cpu-1.26.0
[pip3] AimetTorch==torch-cpu-1.26.0
[pip3] flake8==4.0.1
[pip3] mypy-extensions==0.4.3
[pip3] numpy==1.21.6
[pip3] numpydoc==1.4.0
[pip3] onnx==1.13.1
[pip3] onnx-pytorch==0.1.5
[pip3] onnx2pytorch==0.4.1
[pip3] onnx2torch==1.5.6
[pip3] onnxruntime==1.14.1
[pip3] torch==2.1.0
[pip3] torchaudio==2.0.2
[pip3] torchmetrics==0.11.4
[pip3] torchsummary==1.5.1
[pip3] torchvision==0.15.2
[pip3] triton==2.1.0
[conda] aimet                     torch-cpu-1.26.0          pypi_0    pypi
[conda] aimetcommon               torch-cpu-1.26.0          pypi_0    pypi
[conda] aimettorch                torch-cpu-1.26.0          pypi_0    pypi
[conda] blas                      1.0                         mkl  
[conda] mkl                       2021.4.0           h06a4308_640  
[conda] mkl-service               2.4.0            py39h7f8727e_0  
[conda] mkl_fft                   1.3.1            py39hd3c417c_0  
[conda] mkl_random                1.2.2            py39h51133e4_0  
[conda] numpy                     1.21.6                   pypi_0    pypi
[conda] numpydoc                  1.4.0            py39h06a4308_0  
[conda] onnx-pytorch              0.1.5                    pypi_0    pypi
[conda] onnx2pytorch              0.4.1                    pypi_0    pypi
[conda] onnx2torch                1.5.6                    pypi_0    pypi
[conda] torch                     2.1.0                    pypi_0    pypi
[conda] torchaudio                2.0.2                    pypi_0    pypi
[conda] torchmetrics              0.11.4                   pypi_0    pypi
[conda] torchsummary              1.5.1                    pypi_0    pypi
[conda] torchvision               0.15.2                   pypi_0    pypi
[conda] triton                    2.1.0                    pypi_0    pypi


cc @VitalyFedyunin @ezyang @SherlockNoMad @EikanWang @jgong5 @wenzhe-nrv