Repository: pytorch
Issue: Multi-threading with AOT inductor
Labels: oncall: pt2,oncall: export,module: aotinductor

### 🐛 Describe the bug

Execute multiple-theading forward with one AOT runner https://pytorch.org/docs/main/torch.compiler_aot_inductor.html shows very pool performance.

I generated a tiny model.so with

```
import torch
from torch._inductor import config as inductor_config
inductor_config.cpp_wrapper = True
inductor_config.freezing = True
class Model(torch.nn.Module):
    def __init__(self):
        super().__init__()
        self.linear1 = torch.nn.Linear(512, 512).bfloat16()

    def forward(self, x):
        return self.linear1(x)

model = Model().eval()
inputs = torch.randn(128, 512)
with torch.no_grad(), torch.amp.autocast("cpu", enabled=True, dtype=torch.bfloat16):
    so_path = torch._export.aot_compile(
         model, (inputs, ),
         options={"aot_inductor.output_path":os.path.join(os.getcwd(), "model.so")}
    )
```

After that, I take https://pytorch.org/docs/main/torch.compiler_aot_inductor.html as a reference to create a runner on `model.so`, and invoke `runner.run` within different threads. The performance is very pool and CPU usage is only **~3%**.
![image](https://github.com/user-attachments/assets/863992cc-bb4b-4684-8a44-389f5cba0ebe)


Is there any `mutex` here? The `JIT` path should not have any mutex and can reach 100% CPU usage in similar multi-threading cases.

My `inference.cpp`
```
#include <iostream>
#include <vector>

#include <torch/torch.h>
#include <torch/csrc/inductor/aoti_runner/model_container_runner_cpu.h>

int main() {
    c10::InferenceMode mode;

    torch::inductor::AOTIModelContainerRunnerCpu runner("/localdisk/haozhe/aoti_example/model1.so");
    std::vector<torch::Tensor> inputs = {torch::randn({128, 512})};
    std::vector<torch::Tensor> outputs = runner.run(inputs);
    std::cout << "Result from the first inference:"<< std::endl;
    std::cout << outputs[0] << std::endl;

    std::vector<std::vector<torch::Tensor>> minputs;
    for (int i = 0; i < 40; i++) minputs.push_back(inputs);
    // std::vector<torch::inductor::AOTIModelContainerRunnerCpu> runners;
    // for (int i = 0; i < 40; i++) runners.push_back(torch::inductor::AOTIModelContainerRunnerCpu("/localdisk/haozhe/aoti_example/model1.so"));
    std::vector<std::thread> callers;
    for (const auto thread_id : c10::irange(40)) {
        callers.emplace_back([&, thread_id]() {
            int iter = 0;
            while (iter < 100000) {
                iter += 1;
                // std::vector<torch::Tensor> outputs = runners[thread_id].run(minputs[thread_id]);
                std::vector<torch::Tensor> outputs = runner.run(minputs[thread_id]);
            }
        });
    }
    for (auto& t : callers) {
        t.join();
    }
    return 0;
}

```



### Versions

```
PyTorch version: 2.5.0a0+gitde3a641
Is debug build: False
CUDA used to build PyTorch: None
ROCM used to build PyTorch: N/A

OS: CentOS Stream 9 (x86_64)
GCC version: (GCC) 11.4.1 20231218 (Red Hat 11.4.1-3)
Clang version: Could not collect
CMake version: version 3.30.2
Libc version: glibc-2.34

Python version: 3.9.19 | packaged by conda-forge | (main, Mar 20 2024, 12:50:21)  [GCC 12.3.0] (64-bit runtime)
Python platform: Linux-6.6.0-gnr.bkc.6.6.20.7.30.x86_64-x86_64-with-glibc2.34
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
Address sizes:                      52 bits physical, 57 bits virtual
Byte Order:                         Little Endian
CPU(s):                             480
On-line CPU(s) list:                0-479
Vendor ID:                          GenuineIntel
Model name:                         GENUINE INTEL(R) XEON(R)
CPU family:                         6
Model:                              173
Thread(s) per core:                 2
Core(s) per socket:                 120
Socket(s):                          2
Stepping:                           0
CPU max MHz:                        2500.0000
CPU min MHz:                        800.0000
BogoMIPS:                           4000.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 dca sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm abm 3dnowprefetch cpuid_fault epb cat_l3 cat_l2 cdp_l3 cdp_l2 ssbd mba ibrs ibpb stibp ibrs_enhanced tpr_shadow flexpriority ept vpid ept_ad fsgsbase tsc_adjust bmi1 hle avx2 smep bmi2 erms invpcid rtm cqm rdt_a avx512f avx512dq rdseed adx smap avx512ifma clflushopt clwb intel_pt avx512cd sha_ni avx512bw avx512vl xsaveopt xsavec xgetbv1 xsaves cqm_llc cqm_occup_llc cqm_mbm_total cqm_mbm_local split_lock_detect user_shstk avx_vnni avx512_bf16 wbnoinvd dtherm ida arat pln pts hwp hwp_act_window hwp_epp hwp_pkg_req hfi vnmi avx512vbmi umip pku ospke waitpkg avx512_vbmi2 gfni vaes vpclmulqdq avx512_vnni avx512_bitalg tme avx512_vpopcntdq la57 rdpid bus_lock_detect cldemote movdiri movdir64b enqcmd fsrm md_clear serialize tsxldtrk pconfig arch_lbr ibt amx_bf16 avx512_fp16 amx_tile amx_int8 flush_l1d arch_capabilities
Virtualization:                     VT-x
L1d cache:                          11.3 MiB (240 instances)
L1i cache:                          15 MiB (240 instances)
L2 cache:                           480 MiB (240 instances)
L3 cache:                           1008 MiB (2 instances)
NUMA node(s):                       6
NUMA node0 CPU(s):                  0-39,240-279
NUMA node1 CPU(s):                  40-79,280-319
NUMA node2 CPU(s):                  80-119,320-359
NUMA node3 CPU(s):                  120-159,360-399
NUMA node4 CPU(s):                  160-199,400-439
NUMA node5 CPU(s):                  200-239,440-479
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:      Unknown: No mitigations
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] bert_pytorch==0.0.1a4
[pip3] functorch==1.14.0a0+b71aa0b
[pip3] intel_extension_for_pytorch==2.5.0+gitf86e93e
[pip3] mypy==1.11.1
[pip3] mypy-extensions==1.0.0
[pip3] numpy==1.21.2
[pip3] onnx==1.16.2
[pip3] optree==0.12.1
[pip3] pytorch-labs-segment-anything-fast==0.2
[pip3] torch==2.5.0a0+gitde3a641
[pip3] torch_geometric==2.4.0
[pip3] torchao==0.3.1
[pip3] torchaudio==2.4.0a0+b3f6f51
[pip3] torchdata==0.7.0a0+11bb5b8
[pip3] torchmetrics==0.11.0
[pip3] torchmultimodal==0.1.0b0
[pip3] torchrec==0.3.2
[pip3] torchsnapshot==0.1.0
[pip3] torchtext==0.17.0a0+09e2690
[conda] bert-pytorch              0.0.1a4                   dev_0    <develop>
[conda] functorch                 1.14.0a0+b71aa0b          pypi_0    pypi
[conda] intel-extension-for-pytorch 2.5.0+gitf86e93e           dev_0    <develop>
[conda] mkl-include               2024.2.0                 pypi_0    pypi
[conda] mkl-static                2024.2.0                 pypi_0    pypi
[conda] numpy                     1.21.2                   pypi_0    pypi
[conda] optree                    0.12.1                   pypi_0    pypi
[conda] pytorch-labs-segment-anything-fast 0.2                      pypi_0    pypi
[conda] torch                     2.5.0a0+gitde3a641           dev_0    <develop>
[conda] torch-geometric           2.4.0                    pypi_0    pypi
[conda] torchao                   0.3.1                    pypi_0    pypi
[conda] torchaudio                2.4.0a0+b3f6f51           dev_0    <develop>
[conda] torchdata                 0.7.0a0+11bb5b8           dev_0    <develop>
[conda] torchmetrics              0.11.0                   pypi_0    pypi
[conda] torchmultimodal           0.1.0b0                  pypi_0    pypi
[conda] torchrec                  0.3.2                    pypi_0    pypi
[conda] torchsnapshot             0.1.0                    pypi_0    pypi
[conda] torchtext                 0.17.0a0+09e2690           dev_0    <develop>
```

cc @ezyang @gchanan @zou3519 @kadeng @msaroufim @chauhang @penguinwu @avikchaudhuri @gmagogsfm @zhxchen17 @tugsbayasgalan @angelayi @suo @ydwu4 @desertfire @chenyang78