Repository: pytorch
Issue: Compiler is 2x Faster for Input Size 1 Compared to Sizes 2 and Above, Where Forward Pass Times Remain Consistent
Labels: triaged,oncall: pt2,module: inductor,module: startup-tracing-compile

### 🐛 Describe the bug

In the model available at https://github.com/alita-moore/img-to-text, increasing the length of the input IDs beyond 1 causes the process to slow down by approximately 2x compared to when the length is 1. However, for input sizes of 2, 3, and higher, the processing speed remains constant regardless of further increases in input size. If the forward pass is not compiled, the speed remains consistent across all input sizes.

This behavior is identified in the following code which you can find in dev.py

```python
import torch._dynamo
import time
from torch.nn.attention import SDPBackend

torch._dynamo.reset()
compiled_model = get_model(config, "cuda")

compiled_model.decoder.model.setup_cache(
    1,
    config.decoder_args.max_seq_len,
    config.encoder_args.max_output_patches,
    device="cuda",
)
compiled_model.decoder.model = torch.compile(compiled_model.decoder.model, mode="max-autotune", fullgraph=True)  # type: ignore

encoder_outputs = (
    torch.randn(
        1, config.encoder_args.max_output_patches, config.encoder_args.output_dimensions
    )
    .to("cuda")
    .to(torch.bfloat16)
)
encoder_cache_pos = torch.arange(0, config.encoder_args.max_output_patches).to("cuda")


def run_test(n: int):
    print(f"===={n}====")
    for i in range(10):
        with torch.inference_mode():
            with torch.autocast("cuda", dtype=torch.bfloat16):
                with torch.nn.attention.sdpa_kernel([SDPBackend.MATH]):
                    input_ids = torch.full(
                        (encoder_outputs.shape[0], n),
                        1,
                        dtype=torch.long,
                        device=encoder_outputs.device,
                    )
                    start = time.time()
                    cache_pos = torch.arange(0, n, device="cuda")
                    compiled_model.decoder.model(
                        input_ids=input_ids,
                        cache_pos=cache_pos,
                        encoder_outputs=encoder_outputs,
                        encoder_cache_pos=encoder_cache_pos,
                        use_encoder_cache=i != 0,
                    )
                    torch.cuda.synchronize()
                    print(time.time() - start)

run_test(1)
run_test(2)
run_test(3)
run_test(4)
run_test(5)
```

```
====1====
7.119003534317017
5.200806617736816
0.5054481029510498
0.004807710647583008
0.004517316818237305
0.00446319580078125
0.004462718963623047
0.0044858455657958984
0.004460811614990234
0.004508495330810547
====2====
11.30737042427063
10.24819278717041
0.7579021453857422
0.00656437873840332
0.0062541961669921875
0.006215333938598633
0.006233930587768555
0.006225109100341797
0.006213665008544922
0.0062372684478759766
====3====
0.010666608810424805
0.008718729019165039
0.5773739814758301
0.006607532501220703
0.006293773651123047
0.006253242492675781
0.006267070770263672
0.006255626678466797
0.00626063346862793
0.006249666213989258
====4====
0.010656595230102539
0.008497953414916992
0.5782616138458252
0.006651163101196289
0.006323099136352539
0.006283283233642578
0.006294965744018555
0.006295680999755859
0.006290435791015625
0.006298065185546875
====5====
0.010953187942504883
0.008683443069458008
0.5847327709197998
0.006703376770019531
0.006349325180053711
0.0063059329986572266
0.006310224533081055
0.0063097476959228516
0.006322622299194336
0.006304502487182617
```

### Versions

PyTorch version: 2.4.0+cu124
Is debug build: False
CUDA used to build PyTorch: 12.4
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.30.2
Libc version: glibc-2.35

Python version: 3.10.12 (main, Jul 29 2024, 16:56:48) [GCC 11.4.0] (64-bit runtime)
Python platform: Linux-6.8.0-1014-aws-x86_64-with-glibc2.35
Is CUDA available: True
CUDA runtime version: 12.6.20
CUDA_MODULE_LOADING set to: LAZY
GPU models and configuration: GPU 0: NVIDIA L4
Nvidia driver version: 560.35.03
cuDNN version: Probably one of the following:
/usr/lib/x86_64-linux-gnu/libcudnn.so.9.3.0
/usr/lib/x86_64-linux-gnu/libcudnn_adv.so.9.3.0
/usr/lib/x86_64-linux-gnu/libcudnn_cnn.so.9.3.0
/usr/lib/x86_64-linux-gnu/libcudnn_engines_precompiled.so.9.3.0
/usr/lib/x86_64-linux-gnu/libcudnn_engines_runtime_compiled.so.9.3.0
/usr/lib/x86_64-linux-gnu/libcudnn_graph.so.9.3.0
/usr/lib/x86_64-linux-gnu/libcudnn_heuristic.so.9.3.0
/usr/lib/x86_64-linux-gnu/libcudnn_ops.so.9.3.0
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:                        48 bits physical, 48 bits virtual
Byte Order:                           Little Endian
CPU(s):                               8
On-line CPU(s) list:                  0-7
Vendor ID:                            AuthenticAMD
Model name:                           AMD EPYC 7R13 Processor
CPU family:                           25
Model:                                1
Thread(s) per core:                   2
Core(s) per socket:                   4
Socket(s):                            1
Stepping:                             1
BogoMIPS:                             5300.00
Flags:                                fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush mmx fxsr sse sse2 ht syscall nx mmxext fxsr_opt pdpe1gb rdtscp lm constant_tsc rep_good nopl nonstop_tsc cpuid extd_apicid aperfmperf tsc_known_freq pni pclmulqdq ssse3 fma cx16 pcid sse4_1 sse4_2 x2apic movbe popcnt aes xsave avx f16c rdrand hypervisor lahf_lm cmp_legacy cr8_legacy abm sse4a misalignsse 3dnowprefetch topoext ssbd ibrs ibpb stibp vmmcall fsgsbase bmi1 avx2 smep bmi2 invpcid rdseed adx smap clflushopt clwb sha_ni xsaveopt xsavec xgetbv1 clzero xsaveerptr rdpru wbnoinvd arat npt nrip_save vaes vpclmulqdq rdpid
Hypervisor vendor:                    KVM
Virtualization type:                  full
L1d cache:                            128 KiB (4 instances)
L1i cache:                            128 KiB (4 instances)
L2 cache:                             2 MiB (4 instances)
L3 cache:                             16 MiB (1 instance)
NUMA node(s):                         1
NUMA node0 CPU(s):                    0-7
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 Reg file data sampling: Not affected
Vulnerability Retbleed:               Not affected
Vulnerability Spec rstack overflow:   Vulnerable: Safe RET, no microcode
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; Retpolines; IBPB conditional; IBRS_FW; STIBP always-on; RSB filling; PBRSB-eIBRS Not affected; BHI Not affected
Vulnerability Srbds:                  Not affected
Vulnerability Tsx async abort:        Not affected

Versions of relevant libraries:
[pip3] numpy==2.1.0
[pip3] onnx==1.16.2
[pip3] onnxruntime==1.19.0
[pip3] onnxruntime-gpu==1.19.0
[pip3] torch==2.4.0+cu124
[pip3] torchaudio==2.4.0+cu124
[pip3] torchvision==0.19.0+cu124
[pip3] triton==3.0.0
[conda] Could not collect

cc @ezyang @chauhang @penguinwu @voznesenskym @EikanWang @jgong5 @Guobing-Chen @XiaobingSuper @zhuhaozhe @blzheng @wenzhe-nrv @jiayisunx @ipiszy @yf225 @chenyang78 @kadeng @muchulee8 @ColinPeppler @amjames @desertfire @oulgen @jamesjwu @aorenste @anijain2305 @laithsakka