Repository: pytorch
Issue: Autocast on cpu dramatically slow
Labels: module: cpu,triaged

### 🐛 Describe the bug

On a toy regression model with pytorch 2.1.2 on cpu, `torch.autocast` is really slow.
Without `with torch.autocast(device_type="cpu", dtype=torch.bfloat16, cache_enabled=True)` in the code below, I get

Epoch 0: Loss: 5.163879e-01 in 2.6s.
Epoch 1: Loss: 5.981598e+01 in 2.5s.
Epoch 2: Loss: 6.057042e-01 in 2.5s.
Epoch 3: Loss: 3.923391e+00 in 2.5s.
Epoch 4: Loss: 1.904698e+00 in 2.5s.
training done in 12.7s.

That's fine.

With `torch.autocast`, I get

Epoch 0: Loss: 5.164276e-01 in 230.8s.
Epoch 1: Loss: 5.980967e+01 in 231.1s.
Epoch 2: Loss: 6.053763e-01 in 233.0s.
Epoch 3: Loss: 3.924905e+00 in 232.8s.
Epoch 4: Loss: 1.904750e+00 in 232.0s.
training done in 1159.7s.

So, the code with `torch.autocast` is 2 orders of magnitude slower.

Here is the code to reproduce my results:

```
import torch
import torch.nn as nn
import numpy as np
from time import time
torch.set_num_threads(1)

input_size = 1
output_size = 1
hidden_size = 512
num_data = 100000

# seeds
seed = 1234
torch.manual_seed(seed)
torch.use_deterministic_algorithms(True)
np.random.seed(seed)

# hyper-parameters
num_epochs = 5
learning_rate = 0.01

# toy dataset
x_train = np.random.rand(num_data,input_size)
y_train = np.cos(2*np.pi*x_train) + 0.1*np.random.randn(num_data,input_size)

# regression model
model = nn.Sequential(nn.Linear(input_size, hidden_size),
                       nn.GELU(),
                       nn.Linear(hidden_size, hidden_size),
                       nn.GELU(),
                       nn.Linear(hidden_size, output_size))

# loss and optimizer
criterion = nn.MSELoss()
optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate, weight_decay = 1e-2)  

# train the model
x_train = torch.from_numpy(x_train.astype(np.float32))
y_train = torch.from_numpy(y_train.astype(np.float32))

global_start_time = time()
for epoch in range(num_epochs):
    start_time = time()
    
    # forward pass
    with torch.autocast(device_type="cpu", dtype=torch.bfloat16, cache_enabled=True):
        outputs = model(x_train)
        loss = criterion(outputs, y_train)
    
    # backward and optimize
    optimizer.zero_grad(set_to_none=True)
    loss.backward()
    optimizer.step()
    
    print(f'Epoch {epoch}: Loss: {loss.item():.6e} in {time()-start_time:.1f}s.')
print(f'training done in {time()-global_start_time:.1f}s.')
```

Surprisingly, with `torch.autocast`, if I remove a layer, i.e.

```
model = nn.Sequential(nn.Linear(input_size, hidden_size),
                       nn.GELU(),
                       nn.Linear(hidden_size, output_size))
```

an epoch only takes ~2s instead of ~200s.

### Versions

PyTorch version: 2.1.2
Is debug build: False
CUDA used to build PyTorch: Could not collect
ROCM used to build PyTorch: N/A

OS: SUSE Linux Enterprise Server 15 SP4 (x86_64)
GCC version: (SUSE Linux) 7.5.0
Clang version: Could not collect
CMake version: version 3.20.4
Libc version: glibc-2.31

Python version: 3.11.4 | packaged by conda-forge | (main, Jun 10 2023, 18:08:17) [GCC 12.2.0] (64-bit runtime)
Python platform: Linux-5.14.21-150400.24.63-default-x86_64-with-glibc2.31
Is CUDA available: False
CUDA runtime version: Could not collect
CUDA_MODULE_LOADING set to: N/A
GPU models and configuration: GPU 0: NVIDIA L4-2B
Nvidia driver version: 535.129.03
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:                   45 bits physical, 48 bits virtual
Byte Order:                      Little Endian
CPU(s):                          6
On-line CPU(s) list:             0-5
Vendor ID:                       AuthenticAMD
Model name:                      AMD EPYC 7542 32-Core Processor
CPU family:                      23
Model:                           49
Thread(s) per core:              1
Core(s) per socket:              1
Socket(s):                       6
Stepping:                        0
BogoMIPS:                        5799.99
Flags:                           fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush mmx fxsr sse sse2 syscall nx mmxext fxsr_opt pdpe1gb rdtscp lm constant_tsc rep_good nopl tsc_reliable nonstop_tsc cpuid extd_apicid tsc_known_freq pni pclmulqdq ssse3 fma cx16 sse4_1 sse4_2 x2apic movbe popcnt aes xsave avx f16c rdrand hypervisor lahf_lm extapic cr8_legacy abm sse4a misalignsse 3dnowprefetch osvw topoext ssbd ibpb vmmcall fsgsbase bmi1 avx2 smep bmi2 rdseed adx smap clflushopt clwb sha_ni xsaveopt xsavec xgetbv1 xsaves clzero wbnoinvd arat umip rdpid overflow_recov succor
Hypervisor vendor:               VMware
Virtualization type:             full
L1d cache:                       192 KiB (6 instances)
L1i cache:                       192 KiB (6 instances)
L2 cache:                        3 MiB (6 instances)
L3 cache:                        96 MiB (6 instances)
NUMA node(s):                    1
NUMA node0 CPU(s):               0-5
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:          Mitigation; untrained return thunk; SMT disabled
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; Retpolines, IBPB conditional, STIBP disabled, RSB filling, PBRSB-eIBRS Not affected
Vulnerability Srbds:             Not affected
Vulnerability Tsx async abort:   Not affected

Versions of relevant libraries:
[pip3] numpy==1.25.1
[pip3] pytorch-optimizer==2.11.0
[pip3] torch==2.1.2
[pip3] torch_geometric==2.4.0
[pip3] torchdiffeq==0.2.2
[pip3] torchmetrics==0.11.4
[conda] Could not collect

cc @jgong5 @mingfeima @XiaobingSuper @sanchitintel @ashokei @jingxu10