Repository: pytorch
Issue: [Perf]The delay between inference request impact the performance
Labels: module: performance,triaged

### 🐛 Describe the bug

The delay between inference request will impact the performance of latency.

If the delay is 0 second, the performance of bs=1 is best.
If the delay is 2s, the performance of bs=1 will reduced.

If same in following cases:
1. both CPU and CUDA
2.  eager and [torch.compile()]([url](url)) mode.
3. Jemalloc.

I draft an example code and get the following log

on CPU:

```
latency: 0.019783496856689453 sleep 0
latency: 0.01930999755859375 sleep 0
latency: 0.019414663314819336 sleep 0
latency: 0.01890277862548828 sleep 0
latency: 0.019414663314819336 sleep 0
latency: 0.018809795379638672 sleep 0
latency: 0.01901698112487793 sleep 0
latency: 0.018945693969726562 sleep 0
latency: 0.01931285858154297 sleep 0
avg latency 0.01921232541402181 sleep 0
```
```
latency: 0.023831844329833984 sleep 2
latency: 0.02048492431640625 sleep 2
latency: 0.024386167526245117 sleep 2
latency: 0.026789426803588867 sleep 2
latency: 0.026439666748046875 sleep 2
latency: 0.027832984924316406 sleep 2
latency: 0.028536081314086914 sleep 2
latency: 0.028757095336914062 sleep 2
latency: 0.0296633243560791 sleep 2
avg latency 0.02630239062839084 sleep 2
```

on CUDA V100
```
latency: 0.004566669464111328 sleep 0
latency: 0.0043337345123291016 sleep 0
latency: 0.0042057037353515625 sleep 0
latency: 0.004201173782348633 sleep 0
latency: 0.004255771636962891 sleep 0
latency: 0.004193544387817383 sleep 0
latency: 0.0042057037353515625 sleep 0
latency: 0.004158973693847656 sleep 0
latency: 0.004200458526611328 sleep 0
avg latency 0.004257970386081272 sleep 0
```

```
latency: 0.0038862228393554688 sleep 2
latency: 0.0036373138427734375 sleep 2
latency: 0.0035004615783691406 sleep 2
latency: 0.004335165023803711 sleep 2
latency: 0.005205392837524414 sleep 2
latency: 0.006509542465209961 sleep 2
latency: 0.008309125900268555 sleep 2
latency: 0.004138946533203125 sleep 2
latency: 0.009718179702758789 sleep 2
avg latency 0.005471150080362956 sleep 2
```

Reproduce:

run the attachment script:

```
python delay_perf.py 0
python delay_perf.py 2
```

delay_perf.py

for CPU
```
import torchvision.models as tv_models
import torch
import os
import time
import sys

class Infer():
    def __init__(self, inter=4, intra=4):
        self.inter=inter
        self.intra=intra

        self.model = tv_models.resnet50(pretrained=True)
        self.model.eval()
        self.model = torch.compile(self.model)

        # torch.no_grad()

        os.environ['CUDA_VISIBLE_DEVICES'] = '-1'
        os.environ["KMP_BLOCKTIME"] = "1"
        os.environ["KMP_SETTINGS"] = "0"
        os.environ["KMP_AFFINITY"] = "granularity=fine,compact,1,0"
        os.environ["OMP_NUM_THREADS"] = str(self.intra)

    def predict(self):
        input_batch = torch.rand(1,3,244,244)
        infer_time = self.infer_perf_run(input_batch)

        return infer_time

    def infer_perf_run(self, input_batch):
        bt = time.time()
        with torch.no_grad():
            output = self.model(input_batch)
        et = time.time()
        latency = (et - bt)
        #self.handle_output(output)
        #print('latency:', latency)
        return latency

if __name__=='__main__':
    inter=4
    intra=4
    infer = Infer(inter, intra)

    sleep_time = int(sys.argv[1]) if len(sys.argv)>1 else 0
    res_list = []
    for i in range(10):
        res = infer.predict()
        if i>0:
            print('latency:', res, "sleep", sleep_time)
        time.sleep(sleep_time)
        res_list.append(res)
    res_list = res_list[1:]
    print("avg latency", sum(res_list)/len(res_list), "sleep", sleep_time)
```

for CUDA

```
import torchvision.models as tv_models
import torch
import os
import time
import sys

class Infer():
    def __init__(self, inter=4, intra=4, device="cuda"):
        self.inter=inter
        self.intra=intra

        self.model = tv_models.resnet50(pretrained=True).to(device)
        self.model.eval()
        self.model = torch.compile(self.model)
        self.device = device

        # torch.no_grad()

        os.environ['CUDA_VISIBLE_DEVICES'] = '0'
        os.environ["KMP_BLOCKTIME"] = "1"
        os.environ["KMP_SETTINGS"] = "0"
        os.environ["KMP_AFFINITY"] = "granularity=fine,compact,1,0"
        os.environ["OMP_NUM_THREADS"] = str(self.intra)

    def predict(self):
        input_batch = torch.rand(1,3,244,244).to(self.device)
        infer_time = self.infer_perf_run(input_batch)

        return infer_time

    def infer_perf_run(self, input_batch):
        bt = time.time()
        with torch.no_grad():
            output = self.model(input_batch)
        et = time.time()
        latency = (et - bt)
        #self.handle_output(output)
        #print('latency:', latency)
        return latency

if __name__=='__main__':
    inter=4
    intra=4
    infer = Infer(inter, intra)

    sleep_time = int(sys.argv[1]) if len(sys.argv)>1 else 0
    res_list = []
    for i in range(10):
        res = infer.predict()
        if i>0:
            print('latency:', res, "sleep", sleep_time)
        time.sleep(sleep_time)
        res_list.append(res)
    res_list = res_list[1:]
    print("avg latency", sum(res_list)/len(res_list), "sleep", sleep_time)
```

### Versions
CUDA:
```
pytorch-triton           3.1.0+cf34004b8a
torch                    2.4.1+cu124
torchaudio               2.4.1+cu124
torchvision              0.19.1+cu124
```

CPU:
```
python collect_env.py 

Collecting environment information...
PyTorch version: 2.4.1+cpu
Is debug build: False
CUDA used to build PyTorch: None
ROCM used to build PyTorch: N/A

OS: Ubuntu 22.04.3 LTS (x86_64)
GCC version: (Ubuntu 12.3.0-1ubuntu1~22.04) 12.3.0
Clang version: 14.0.0-1ubuntu1.1
CMake version: version 3.28.4
Libc version: glibc-2.35

Python version: 3.10.14 | packaged by conda-forge | (main, Mar 20 2024, 12:45:18) [GCC 12.3.0] (64-bit runtime)
Python platform: Linux-5.15.0-94-generic-x86_64-with-glibc2.35
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):                             64
On-line CPU(s) list:                0-63
Vendor ID:                          GenuineIntel
Model name:                         Intel(R) Xeon(R) Gold 6346 CPU @ 3.10GHz
CPU family:                         6
Model:                              106
Thread(s) per core:                 2
Core(s) per socket:                 16
Socket(s):                          2
Stepping:                           6
CPU max MHz:                        3600.0000
CPU min MHz:                        800.0000
BogoMIPS:                           6200.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 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 invpcid_single ssbd mba ibrs ibpb stibp ibrs_enhanced tpr_shadow vnmi flexpriority ept vpid ept_ad fsgsbase tsc_adjust bmi1 avx2 smep bmi2 erms invpcid 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 wbnoinvd dtherm ida arat pln pts avx512vbmi umip pku ospke avx512_vbmi2 gfni vaes vpclmulqdq avx512_vnni avx512_bitalg tme avx512_vpopcntdq la57 rdpid fsrm md_clear pconfig flush_l1d arch_capabilities
Virtualization:                     VT-x
L1d cache:                          1.5 MiB (32 instances)
L1i cache:                          1 MiB (32 instances)
L2 cache:                           40 MiB (32 instances)
L3 cache:                           72 MiB (2 instances)
NUMA node(s):                       2
NUMA node0 CPU(s):                  0-15,32-47
NUMA node1 CPU(s):                  16-31,48-63
Vulnerability Gather data sampling: Vulnerable: No microcode
Vulnerability Itlb multihit:        Not affected
Vulnerability L1tf:                 Not affected
Vulnerability Mds:                  Not affected
Vulnerability Meltdown:             Not affected
Vulnerability Mmio stale data:      Vulnerable: Clear CPU buffers attempted, no microcode; SMT vulnerable
Vulnerability Retbleed:             Not affected
Vulnerability Spec rstack overflow: Not affected
Vulnerability Spec store bypass:    Mitigation; Speculative Store Bypass disabled via prctl and seccomp
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] numpy==1.26.3
[pip3] torch==2.4.1+cpu
[pip3] torchaudio==2.4.1+cpu
[pip3] torchvision==0.19.1+cpu
[conda] No relevant packages

```

cc @msaroufim