torch.autocast() hangs on CPUs
Labels: triage review, module: cpu, module: amp (automated mixed precision)

### 🐛 Describe the bug

Hi PyTorch Team, 

First and foremost, thank you for your invaluable contributions to the ML community! I recently encountered a performance issue when using torch.autocast() on CPUs. In the FP32 mode, everything is fine. When turning on the AMP with BF16, the code seems to be stuck and never finishes. Here is a quick repo:
```python3
import time
import torch
from transformers import RobertaForSequenceClassification, RobertaTokenizer

SEQUENCE_LENGTH = 512


def generate_random_batch(tokenizer, batch_size, sequence_length=SEQUENCE_LENGTH):
    """Generate a batch of random sequences for testing."""
    return tokenizer(
        [" ".join(["I am a test string."] * sequence_length) for _ in range(batch_size)],
        padding="max_length",
        truncation=True,
        max_length=SEQUENCE_LENGTH,
        return_tensors="pt",
    )


def benchmark_throughput(model, tokenizer, mixed_precision=False, batch_size=32, num_iterations=3):
    """Test and print the throughput of the model."""
    input_data = generate_random_batch(tokenizer, batch_size).to(device)
    # Warm up
    for _ in range(3):
        with torch.no_grad():
            # PyTorch only supports bfloat16 mixed precision on CPUs.
            with torch.autocast(device_type="cpu", dtype=torch.bfloat16, enabled=mixed_precision):
                _ = model(**input_data)

    start_time = time.time()
    for _ in range(num_iterations):
        with torch.no_grad():
            with torch.autocast(device_type="cpu", dtype=torch.bfloat16, enabled=mixed_precision):
                _ = model(**input_data)
    end_time = time.time()

    elapsed_time = end_time - start_time
    sequences_per_second = (batch_size * num_iterations) / elapsed_time
    latency = 1000 / sequences_per_second * batch_size

    return sequences_per_second, latency


if __name__ == "__main__":
    device = torch.device("cpu")
    tokenizer = RobertaTokenizer.from_pretrained("roberta-base")
    model = RobertaForSequenceClassification.from_pretrained("roberta-base").to(device).eval()

    model = torch.compile(model)

    throughput, latency = benchmark_throughput(model, tokenizer, mixed_precision=False)
    print(f"FP32 Throughput: {throughput:.2f} sequences/second, Latency: {latency:.2f} ms")

    throughput, latency = benchmark_throughput(model, tokenizer, mixed_precision=True)
    print(f"Mixed Precision Throughput: {throughput:.2f} sequences/second, Latency: {latency:.2f} ms")
```
On my Intel i7-13700K, FP 32 throughput is 4.98 sequences/second. Enabling AMP with autocast seems to hang the code, as 1 core spikes to 100% and the script would not finish after waiting for 30 minutes. Would appreciate a further look into this issue - thanks in advance!

### Versions

Collecting environment information...
PyTorch version: 2.1.0+cu121
Is debug build: False
CUDA used to build PyTorch: 12.1
ROCM used to build PyTorch: N/A

OS: Ubuntu 22.04.3 LTS (x86_64)
GCC version: (Ubuntu 11.4.0-1ubuntu1~22.04) 11.4.0
Clang version: Could not collect
CMake version: version 3.27.6
Libc version: glibc-2.35

Python version: 3.10.12 (main, Jun 11 2023, 05:26:28) [GCC 11.4.0] (64-bit runtime)
Python platform: Linux-6.2.0-34-generic-x86_64-with-glibc2.35
Is CUDA available: True
CUDA runtime version: 11.5.119
CUDA_MODULE_LOADING set to: LAZY
GPU models and configuration: GPU 0: NVIDIA GeForce RTX 4090
Nvidia driver version: 535.113.01
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:                      46 bits physical, 48 bits virtual
Byte Order:                         Little Endian
CPU(s):                             24
On-line CPU(s) list:                0-23
Vendor ID:                          GenuineIntel
Model name:                         13th Gen Intel(R) Core(TM) i7-13700K
CPU family:                         6
Model:                              183
Thread(s) per core:                 2
Core(s) per socket:                 16
Socket(s):                          1
Stepping:                           1
CPU max MHz:                        5400.0000
CPU min MHz:                        800.0000
BogoMIPS:                           6835.20
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 sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm abm 3dnowprefetch cpuid_fault ssbd ibrs ibpb stibp ibrs_enhanced tpr_shadow vnmi flexpriority ept vpid ept_ad fsgsbase tsc_adjust bmi1 avx2 smep bmi2 erms invpcid rdseed adx smap clflushopt clwb intel_pt sha_ni xsaveopt xsavec xgetbv1 xsaves split_lock_detect avx_vnni dtherm ida arat pln pts hwp hwp_notify hwp_act_window hwp_epp hwp_pkg_req hfi umip pku ospke waitpkg gfni vaes vpclmulqdq tme rdpid movdiri movdir64b fsrm md_clear serialize pconfig arch_lbr ibt flush_l1d arch_capabilities
Virtualization:                     VT-x
L1d cache:                          640 KiB (16 instances)
L1i cache:                          768 KiB (16 instances)
L2 cache:                           24 MiB (10 instances)
L3 cache:                           30 MiB (1 instance)
NUMA node(s):                       1
NUMA node0 CPU(s):                  0-23
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 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 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.1
[pip3] pytorch-lightning==2.1.0
[pip3] torch==2.1.0
[pip3] torchaudio==2.1.0
[pip3] torchmetrics==1.2.0
[pip3] torchvision==0.16.0
[pip3] triton==2.1.0
[conda] Could not collect

cc @jgong5 @mingfeima @XiaobingSuper @sanchitintel @ashokei @jingxu10 @mcarilli @ptrblck @leslie-fang-intel