Repository: pytorch
Issue: The performance of `torch.index_select` and regular indexing differs dramatically based on the size of the tensor it is indexing
Labels: module: performance,module: autograd,module: cpu,triaged,module: advanced indexing,needs research

### 🐛 Describe the bug

As the picture below shows, `torch.index_select` outperforms regular indexing when the tensor size is small, but is outperformed when the size is large. Is this expected behavior? If I have to do indexing many times, am I expected to choose the indexing method based on the size of the tensor I need to index? Also, [backward pass](https://github.com/dmlc/dgl/issues/3729) implies that during backward pass index_select is faster, especially if indices are repeated.. Which should I choose then?  

(please ignore the "log scale" in the colorbar (it's not actually log scale)

![image](https://github.com/pytorch/pytorch/assets/34816251/f49428f7-eb26-4542-9859-6231c064cb2a)



Below was the code that was run 
```
import time
import torch
import matplotlib.pyplot as plt
import matplotlib.colors as colors
import matplotlib.patheffects as pe

batch_sizes = [8, 16, 32, 64, 128, 256, 512, 1024, 2048]
feature_sizes = [8, 16, 32, 64, 128, 256, 512, 1024, 2048]

index_select_times = []
indexing_times = []

for batch_size in batch_sizes:
    for feature_size in feature_sizes:
        x = torch.arange(batch_size * feature_size).reshape(batch_size, feature_size) + 0.1
        indx = torch.randperm(feature_size)

        start = time.time()
        for _ in range(10000):
            x = torch.index_select(x, -1, indx)
        end = time.time()
        index_select_times.append(end - start)

        start = time.time()
        for _ in range(10000):
            x = x[:, indx]
        end = time.time()
        indexing_times.append(end - start)

# Convert batch_sizes and feature_sizes to tensors
batch_sizes_tensor = torch.tensor(batch_sizes)
feature_sizes_tensor = torch.tensor(feature_sizes)

# Create a 2D grid of batch sizes and feature sizes
X, Y = torch.meshgrid(batch_sizes_tensor, feature_sizes_tensor)

# Convert the index_select_times and indexing_times lists to a 2D array
index_select_times = torch.tensor(index_select_times).reshape(len(batch_sizes), len(feature_sizes))
indexing_times = torch.tensor(indexing_times).reshape(len(batch_sizes), len(feature_sizes))

# Plotting the performance results
plt.figure(figsize=(10, 6))
plt.imshow(index_select_times / indexing_times, cmap='hot', origin='lower')
plt.colorbar(label='Relative Time (log scale)', format='%.2f')  # Add format to display numbers
plt.xticks(range(len(feature_sizes)), feature_sizes)
plt.yticks(range(len(batch_sizes)), batch_sizes)
plt.xlabel('Feature Size')
plt.ylabel('Batch Size')
plt.title('Performance Comparison (torch.index_select/index)')

# Display the actual z values
for i in range(len(batch_sizes)):
    for j in range(len(feature_sizes)):
        plt.text(j, i, f'{index_select_times[i][j]/indexing_times[i][j]:.2f}', ha='center', va='center', color='white', path_effects=[pe.withStroke(linewidth=3, foreground="blue")])

plt.show()

print(index_select_times)
print(indexing_times)
```

### Versions

Collecting environment information...
PyTorch version: 2.0.1+cu117
Is debug build: False
CUDA used to build PyTorch: 11.7
ROCM used to build PyTorch: N/A

OS: Ubuntu 20.04.4 LTS (x86_64)
GCC version: (Ubuntu 9.4.0-1ubuntu1~20.04.2) 9.4.0
Clang version: Could not collect
CMake version: version 3.27.5
Libc version: glibc-2.31

Python version: 3.10.12 | packaged by conda-forge | (main, Jun 23 2023, 22:40:32) [GCC 12.3.0] (64-bit runtime)
Python platform: Linux-5.4.0-167-generic-x86_64-with-glibc2.31
Is CUDA available: True
CUDA runtime version: 11.7.64
CUDA_MODULE_LOADING set to: LAZY
GPU models and configuration: 
GPU 0: NVIDIA GeForce RTX 3090
GPU 1: NVIDIA GeForce RTX 3090
GPU 2: NVIDIA GeForce RTX 3090
GPU 3: NVIDIA GeForce RTX 3090
GPU 4: NVIDIA GeForce RTX 3090
GPU 5: NVIDIA GeForce RTX 3090
GPU 6: NVIDIA GeForce RTX 3090
GPU 7: NVIDIA GeForce RTX 3090

Nvidia driver version: 525.147.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
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) Gold 6240R CPU @ 2.40GHz
Stepping:                           7
CPU MHz:                            3218.731
CPU max MHz:                        4000.0000
CPU min MHz:                        1000.0000
BogoMIPS:                           4800.00
Virtualization:                     VT-x
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 Gather data sampling: Mitigation; Microcode
Vulnerability Itlb multihit:        KVM: Mitigation: Split huge pages
Vulnerability L1tf:                 Not affected
Vulnerability Mds:                  Not affected
Vulnerability Meltdown:             Not affected
Vulnerability Mmio stale data:      Mitigation; Clear CPU buffers; SMT vulnerable
Vulnerability Retbleed:             Mitigation; Enhanced IBRS
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:      Mitigation; TSX disabled
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 cdp_l3 invpcid_single intel_ppin 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 mpx rdt_a avx512f avx512dq rdseed adx smap clflushopt clwb intel_pt avx512cd avx512bw avx512vl xsaveopt xsavec xgetbv1 xsaves cqm_llc cqm_occup_llc cqm_mbm_total cqm_mbm_local dtherm ida arat pln pts hwp hwp_act_window hwp_epp hwp_pkg_req pku ospke avx512_vnni md_clear flush_l1d arch_capabilities

Versions of relevant libraries:
[pip3] numpy==1.26.0
[pip3] torch==2.0.1
[pip3] torchaudio==2.0.2+cu118
[pip3] torchinfo==1.8.0
[pip3] torchvision==0.15.2
[pip3] triton==2.0.0
[conda] numpy                     1.26.0                   pypi_0    pypi
[conda] torch                     2.0.1                    pypi_0    pypi
[conda] torchaudio                2.0.2+cu118              pypi_0    pypi
[conda] torchinfo                 1.8.0                    pypi_0    pypi
[conda] torchvision               0.15.2                   pypi_0    pypi
[conda] triton                    2.0.0                    pypi_0    pypi

cc @ezyang @albanD @zou3519 @gqchen @pearu @nikitaved @soulitzer @Lezcano @Varal7 @jgong5 @mingfeima @XiaobingSuper @sanchitintel @ashokei @jingxu10