4

I am new to AVX512 instruction set and I write the following code as demo.

#include <iostream>
#include <array>
#include <chrono>
#include <vector>
#include <cstring>
#include <omp.h>
#include <immintrin.h>
#include <cstdlib>

int main() {

  unsigned long m, n, k;
  m = n = k = 1 << 30;
  auto *a = static_cast<double*>(aligned_alloc(512, m*sizeof(double)));
  auto *b = static_cast<double*>(aligned_alloc(512, n*sizeof(double)));
  auto *c = static_cast<double*>(aligned_alloc(512, k*sizeof(double)));

  memset(a, 1, m * sizeof(double));
  memset(b, 1, n * sizeof(double));
  memset(c, 1, k * sizeof(double));

  std::chrono::time_point<std::chrono::system_clock> start, end;

  start = std::chrono::system_clock::now();
  for (int iter = 0; iter < 30; iter++) {
    for (unsigned long i = 0; i < n; i+=4) {
      // __m512d x1 = _mm512_load_pd(&a[i]);
      // __m512d x2 = _mm512_load_pd(&b[i]);
      // __m512d result = _mm512_add_pd(x1, x2);
      // _mm512_store_pd(&c[i], result);
      __m256d x1 = _mm256_load_pd(&a[i]);
      __m256d x2 = _mm256_load_pd(&b[i]);
      __m256d result = _mm256_add_pd(x1, x2);
      _mm256_store_pd(&c[i], result);
    }
  }
  end = std::chrono::system_clock::now();

  std::chrono::duration<double> elapsed_seconds = end - start;
  std::cout << "elapsed time: " << elapsed_seconds.count() << std::endl;

  return 0;
}

I allocate the aligned memory and use the AVX instruction set to improve the computation performance. However, after I compile and execute it as the following.

szhangcj@gpu3:~/HPC$ g++ -O2 -msse -msse2 -mavx512f -fopenmp main_avx.cpp -o avx
szhangcj@gpu3:~/HPC$ ./avx 
elapsed time: 77.8923
szhangcj@gpu3:~/HPC$ g++ -O2 main.cpp -o single
szhangcj@gpu3:~/HPC$ ./single
elapsed time: 70.0907

My single thread version just replaces the for loop part as the following.

  for (int iter = 0; iter < 30; iter++) {
    for (unsigned long i = 0; i < n; i++) {
      c[i] = a[i] + b[i];
    }
  }

I expect that the computation performance should be improved a lot. But it seems that there is no improvement at all. What is wrong with that? I also want to combine the OpenMP with AVX instruction set to further improve it.

The following information is about my server. gcc version 7.4.0 (Ubuntu 7.4.0-1ubuntu1~18.04.1)

Architecture:        x86_64
CPU op-mode(s):      32-bit, 64-bit
Byte Order:          Little Endian
CPU(s):              44
On-line CPU(s) list: 0-43
Thread(s) per core:  1
Core(s) per socket:  22
Socket(s):           2
NUMA node(s):        2
Vendor ID:           GenuineIntel
CPU family:          6
Model:               85
Model name:          Intel(R) Xeon(R) Gold 6152 CPU @ 2.10GHz
Stepping:            4
CPU MHz:             1000.019
CPU max MHz:         2101.0000
CPU min MHz:         1000.0000
BogoMIPS:            4200.00
Virtualization:      VT-x
L1d cache:           32K
L1i cache:           32K
L2 cache:            1024K
L3 cache:            30976K
NUMA node0 CPU(s):   0-21
NUMA node1 CPU(s):   22-43
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 pti intel_ppin ssbd mba ibrs ibpb stibp tpr_shadow vnmi flexpriority ept vpid fsgsbase tsc_adjust bmi1 hle avx2 smep bmi2 erms invpcid rtm 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 pku ospke md_clear flush_l1d
Peter Cordes
  • 328,167
  • 45
  • 605
  • 847
Sean
  • 901
  • 2
  • 11
  • 30
  • Do you increment `i` by 4 or 8 when compiling with AVX-512? –  Feb 29 '20 at 15:53
  • @StaceyGirl Of course, you can see that in my code. – Sean Feb 29 '20 at 16:15
  • 3
    Likely memory access time limited. Parallel ops can work great when memory accessed is within cache sizes. This is a similar issue with multithreading. One technique is to increase the computational complexity in smaller memory segments. You should try increasing the complexity within L1 cache size groups. – doug Feb 29 '20 at 17:06
  • 3
    Does this answer your question? [Why vectorizing the loop does not have performance improvement](https://stackoverflow.com/questions/18159455/why-vectorizing-the-loop-does-not-have-performance-improvement) – Daniel McLaury Feb 29 '20 at 17:16
  • What hardware / microarchitecture, and compiler version? Using "just" 256-bit AVX like you're doing in the question shouldn't lower the clock speed very much; the bigger penalty is with AVX512 which you enabled at compile-time but didn't un-comment. (Memory bandwidth may depend on uncore clock speed. I think modern Intel keeps uncore clock speed fixed even if none of the cores happen to be running at max turbo, though.) I'd recommend compiling with `-O2 -march=native` to enable *and tune for* everything your CPU has. – Peter Cordes Feb 29 '20 at 23:41
  • 1
    @StaceyGirl: GCC compiles `_mm512_store_pd` to `vmovapd` or `ps` which would fault on unaligned; we can rule out unaligned loads/store that overlap and do every element twice. But yeah, I wondered the same thing at first. Compiling with MSVC or ICC would use `vmovupd` even for alignment-required intrinsics, letting you silently make that mistake. – Peter Cordes Feb 29 '20 at 23:43
  • For the record: a `double` with bit-pattern `0x101010101010101` (produced by `memset(1)`) represents a value of ~7.75E-304 (https://www.binaryconvert.com/result_double.html?hexadecimal=0101010101010101). This is tiny but *not* subnormal: it has a non-zero exponent. So there won't be any subnormal inputs or outputs to the `vaddpd` / `addsd`. I'm surprised that scalar `-O2` is *faster* than 256-bit vectorized; it should be at best equal, or more likely worse with out-of-order exec not seeing as far ahead to trigger TLB misses earlier and so on. – Peter Cordes Feb 29 '20 at 23:54
  • Amusingly, `g++-9.2 -O3` does loop-inversion: repeats each add 30 times before moving on. (Or do a 30-iteration empty loop if you don't use the `c[]` result) inside an outer loop that increments pointers). https://godbolt.org/z/YmGDjs. So you can only use `-O2` unless you take extra steps to avoid `-O3` full optimization defeating your benchmark. – Peter Cordes Mar 01 '20 at 00:01
  • @PeterCordes Yes, I only use the `-O2` optimization. – Sean Mar 01 '20 at 02:17
  • I know you do, I was just saying that you *can't* use `-O3` to see if it helps the compiler make better or different asm (e.g. pointer increments instead of indexed addressing modes). – Peter Cordes Mar 01 '20 at 02:32
  • @PeterCordes I have attached my cpu information above. I also use the random number to fill in my array and perform the add operation. The AVX version is slower than the original version. – Sean Mar 01 '20 at 02:34
  • Does the performance ratio match the CPU frequency ratio between runs? (Lower max turbo with AVX than scalar?) But yeah, Skylake Xeon has quite low single-core memory bandwidth (worse even than previous generations of many-core Xeons) so it's no surprise that a single thread can pretty much saturate it with 2 read + 1 write stream of 8-byte loads/stores, even without GCC doing loop unrolling. Do you *really* want to get to the bottom of why AVX slowed it down the fully memory-bound case, or do you just want to look at a more passes over smaller arrays where AVX gives a big speed? – Peter Cordes Mar 01 '20 at 02:58
  • And BTW, you generally don't need to manually vectorize loops this simple. Just use `-O3 -march=native` to get good code (for the non-benchmark case where there's no repeat loop to worry about). The default `-mprefer-vector-width=256` is often good, but also try 512. – Peter Cordes Mar 01 '20 at 02:59
  • @PeterCordes Actually, at first I just want to see the big performance from AVX. But now, I also want to know why AVX slowed it down. Thanks – Sean Mar 01 '20 at 03:00
  • *at first I just want to see the big performance from AVX* As Mysticial explains in the Q&A Daniel linked above, you can't do that with arrays this big. A speedup could only come from using multiple cores to use more total memory bandwidth. It's interesting and unexpected that AVX causes an actual slowdown, though. Can you consistently reproduce that? What gcc *version* (`gcc -v`)? Can you use `perf stat` on your runs to record average CPU frequency during each run? – Peter Cordes Mar 01 '20 at 03:03
  • 1
    @PeterCordes The g++ version is `gcc version 7.4.0 (Ubuntu 7.4.0-1ubuntu1~18.04.1) `. But I am sorry that we do not install the `linux-tools-common` on server and so far I do not have the permission to install it. – Sean Mar 01 '20 at 03:09
  • [edit] that into the question. For CPU frequency, `grep MHz /proc/cpuinfo` while the test is running. For anything more in-depth to test any other hypothesis, you're going to need `perf`. You can probably just extract the `perf` binary from the relevant Ubuntu `linux-tools-x.y....deb` and run it from your `~/bin`, I think without even even needing a library + LD_LIBRARY_PATH. You should be able to profile user-space code without ever needing root or modifying any sysctl settings. (The default for `kernel.perf_event_paranoid` doesn't allow profiling kernel code but that's fine for this) – Peter Cordes Mar 01 '20 at 03:16
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/208785/discussion-between-sean-and-peter-cordes). – Sean Mar 01 '20 at 03:32
  • It would remove some room for error / doubt if you combined your versions into one [mcve] with `#ifdef USE_SCALAR` / `#else`, so you could show compiling it + timing it both ways. (You could have a 3rd branch of #if with the AVX512 version, too.) I'm also curious whether a `__m128d` version is any faster than scalar. (Agner Fog's VCL is handy for testing changing vector width by changing one template type, without every func name changing. The `.size()` member function makes it easy to handle the loop bound) – Peter Cordes Mar 01 '20 at 03:32
  • you didn't check the result of `aligned_alloc`. Are you sure that the allocation of 3GB of memory succeeded? – phuclv Mar 01 '20 at 04:19
  • @phuclv: It's a dual-socket Xeon Gold server, presumably boatloads of RAM. It didn't segfault so I'd assume it's fine. (Note that it's actually 3x sizeof(double) * `1<<30` = 24 GiB.) – Peter Cordes Mar 01 '20 at 18:01

0 Answers0