Slow convolutions on CPU with autocast

Aknw_Fen: <p><strong>Context</strong></p>
<p>After observing slower training (by logging.) using <em>autocast</em>, a profiling was run to check for expensive operations.</p>
<p>This shows CPU results, but using T4s (GPU) in Colab, <strong>bfloat16</strong> takes very long (just like float16 does in the CPU below.). However, <strong>float16</strong> does run faster than <strong>float32</strong>. (Apparently the reason for this is that <a href="https://github.com/vllm-project/vllm/issues/1400" rel="noopener nofollow ugc">T4s do not support</a> bfloat16. I’m unsure if this is correct, but seems the case in Colab.)</p>
<p>But the issue here is mainly for CPUs.</p>
<ul>
<li>Hardware: CPU - 11th Gen Intel(R) Core™ i7-1165G7 @ 2.80GHz (aka Intel CORE i7 11th)</li>
</ul>
<hr>
<p><strong>Results</strong></p>
<p>Running a profiler on inference (on training mode) using an autoencoder, with a snippet like:</p>
<pre data-code-wrap="python"><code class="lang-python">    with (
      profile(
        activities=[
          ProfilerActivity.CPU,
        ],
        record_shapes=True,
        profile_memory=True,
      ) as prof,
      torch.autocast(get_device_name(), torch.float16),
      record_function("model_inference"),
    ):
      model(img)
    print(prof.key_averages().table(sort_by="cpu_time_total", row_limit=3))
</code></pre>
<ul>
<li>Using 500 images on a network of 10Mb weights</li>
</ul>
<p>It outputs, for each case, sorted by total cpu time:</p>
<p><strong>float16</strong></p>
<pre data-code-wrap="python"><code class="lang-python">DEBUG:root:Device cpu 
INFO:root:--------------------------------  ------------  ------------  ------------  ------------  ------------  ------------  ------------  ------------  
                            Name    Self CPU %      Self CPU   CPU total %     CPU total  CPU time avg       CPU Mem  Self CPU Mem    # of Calls  
--------------------------------  ------------  ------------  ------------  ------------  ------------  ------------  ------------  ------------  
                    aten::linear         0.00%      49.990us       159.06%        2.392s     597.946ms      46.11 Mb           0 b             4  
                 model_inference         0.16%       2.472ms       100.00%        1.504s        1.504s       7.44 Mb    -250.91 Mb             1  
                     aten::addmm        79.36%        1.193s        79.49%        1.195s     597.630ms      19.34 Mb      19.34 Mb             2  
--------------------------------  ------------  ------------  ------------  ------------  ------------  ------------  ------------  ------------  
Self CPU time total: 1.504s

</code></pre>
<p><strong>float 32</strong>:</p>
<pre><code class="lang-auto">DEBUG:root:Device cpu
INFO:root:--------------------------------  ------------  ------------  ------------  ------------  ------------  ------------  ------------  ------------  
                            Name    Self CPU %      Self CPU   CPU total %     CPU total  CPU time avg       CPU Mem  Self CPU Mem    # of Calls  
--------------------------------  ------------  ------------  ------------  ------------  ------------  ------------  ------------  ------------  
                 model_inference         4.88%       8.560ms       100.00%     175.375ms     175.375ms           0 b    -495.96 Mb             1  
               aten::convolution         0.06%     107.845us        52.11%      91.393ms      15.232ms     107.55 Mb           0 b             6  
              aten::_convolution        32.91%      57.722ms        52.05%      91.285ms      15.214ms     107.55 Mb           0 b             6  
--------------------------------  ------------  ------------  ------------  ------------  ------------  ------------  ------------  ------------  
Self CPU time total: 175.375ms
</code></pre>
<p><strong>bfloat16</strong></p>
<pre><code class="lang-auto">DEBUG:root:Device cpu
INFO:root:--------------------------------  ------------  ------------  ------------  ------------  ------------  ------------  ------------  ------------  
                            Name    Self CPU %      Self CPU   CPU total %     CPU total  CPU time avg       CPU Mem  Self CPU Mem    # of Calls  
--------------------------------  ------------  ------------  ------------  ------------  ------------  ------------  ------------  ------------  
          aten::conv_transpose2d         0.02%      58.300us       119.44%     453.313ms      75.552ms      37.46 Mb           0 b             6  
                 model_inference         0.90%       3.428ms       100.00%     379.540ms     379.540ms       7.44 Mb    -250.91 Mb             1  
               aten::convolution         0.03%     123.037us        71.21%     270.288ms      45.048ms      53.78 Mb           0 b             6  
--------------------------------  ------------  ------------  ------------  ------------  ------------  ------------  ------------  ------------  
Self CPU time total: 379.540ms
</code></pre>
<p>Both conv and transposed convolution should be faster in half precision, but they are slower than float. Any ideas what it going wrong?</p>

Aknw_Fen: <p>That was run within a Docker container, but in a standard system install the results are almost the same.</p>

Aknw_Fen: <p>Just forgot that i commented in a related post and gh issue here <a href="https://discuss.pytorch.org/t/autocast-on-cpu-dramatically-slow/196203/3" class="inline-onebox">Autocast on cpu dramatically slow - #3 by Laurent1</a></p>
<p>No solution yet apparently. I’ll test what happens on T4s…</p>
<p>Also, issue not be autocast but bf16, related issue below:</p>
<aside class="onebox githubissue" data-onebox-src="https://github.com/pytorch/pytorch/issues/111456">
  <header class="source">

      <a href="https://github.com/pytorch/pytorch/issues/111456" target="_blank" rel="noopener nofollow ugc">github.com/pytorch/pytorch</a>
  </header>

  <article class="onebox-body">
    <div class="github-row">
  <div class="github-icon-container" title="Issue" data-github-private-repo="false">
	  <svg width="60" height="60" class="github-icon" viewBox="0 0 14 16" aria-hidden="true"><path fill-rule="evenodd" d="M7 2.3c3.14 0 5.7 2.56 5.7 5.7s-2.56 5.7-5.7 5.7A5.71 5.71 0 0 1 1.3 8c0-3.14 2.56-5.7 5.7-5.7zM7 1C3.14 1 0 4.14 0 8s3.14 7 7 7 7-3.14 7-7-3.14-7-7-7zm1 3H6v5h2V4zm0 6H6v2h2v-2z"></path></svg>
  </div>

  <div class="github-info-container">
    <h4>
      <a href="https://github.com/pytorch/pytorch/issues/111456" target="_blank" rel="noopener nofollow ugc">torch.autocast() hangs on CPUs</a>
    </h4>

    <div class="github-info">
      <div class="date">
        opened <span class="discourse-local-date" data-format="ll" data-date="2023-10-18" data-time="03:46:51" data-timezone="UTC">03:46AM - 18 Oct 23 UTC</span>
      </div>

        <div class="date">
          closed <span class="discourse-local-date" data-format="ll" data-date="2024-02-21" data-time="03:27:07" data-timezone="UTC">03:27AM - 21 Feb 24 UTC</span>
        </div>

      <div class="user">
        <a href="https://github.com/YunfanZhang42" target="_blank" rel="noopener nofollow ugc">
          <img alt="" src="https://avatars.githubusercontent.com/u/39713606?v=4" class="onebox-avatar-inline" width="20" height="20">
          YunfanZhang42
        </a>
      </div>
    </div>

    <div class="labels">
        <span style="display:inline-block;margin-top:2px;background-color: #B8B8B8;padding: 2px;border-radius: 4px;color: #fff;margin-left: 3px;">
          module: cpu
        </span>
        <span style="display:inline-block;margin-top:2px;background-color: #B8B8B8;padding: 2px;border-radius: 4px;color: #fff;margin-left: 3px;">
          triaged
        </span>
        <span style="display:inline-block;margin-top:2px;background-color: #B8B8B8;padding: 2px;border-radius: 4px;color: #fff;margin-left: 3px;">
          module: amp (automated mixed precision)
        </span>
    </div>
  </div>
</div>

  <div class="github-row">
    <p class="github-body-container">### 🐛 Describe the bug

Hi PyTorch Team, 

First and foremost, thank you for y<span class="show-more-container"><a href="" rel="noopener" class="show-more">…</a></span><span class="excerpt hidden">our 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</span></p>
  </div>

  </article>

  <div class="onebox-metadata">
    
    
  </div>

  <div style="clear: both"></div>
</aside>