Matmul from OneDNN is 10x slower than MKL_BLAS_Sgemm?

Rubic_ZHANG: <h1><a name="p-468306-summary-1" class="anchor" href="#p-468306-summary-1"></a>Summary</h1>
<p>I have downloaded pre-trained LLM: deepseek-R1-1.5B,  separately running on OneDNN and MKL_BLAS.<br>
And get 10x slower:</p>
<p><img src="https://github.com/user-attachments/assets/cbe23a32-36a3-4655-8b13-5b933db47950" alt="Image" width="690" height="211"></p>
<pre data-code-wrap="python"><code class="lang-python">            model, tokenizer = load_model_for_profiling(
                args.model,
                torch_dtype,
                random_weights=args.random_weights
            )
            
# Apply MKLDNN/OneDNN optimization
            if args.use_mkldnn:
                model = mkldnn_utils.to_mkldnn(model)

# Prepare batch inputs
            if args.batch_prompts:
    # Use the provided list of prompts
                prompts = args.batch_prompts
                if len(prompts) &lt; args.batch_size:
        # If there are not enough prompts, repeat the last prompt
                    prompts.extend([prompts[-1]] * (args.batch_size - len(prompts)))
                prompts = prompts[:args.batch_size]
            else:
    # Repeat the default prompt
                prompts = [args.prompt] * args.batch_size
            
            print(f"Preparing batch of {args.batch_size} prompts...")
            inputs = tokenizer(prompts, return_tensors="pt", padding=True)
            
# Calculate number of prompt tokens
            prompt_tokens = inputs["input_ids"].shape[1]
            performance_data["prompt_tokens"] = prompt_tokens
            
            inputs = {key: val.to(device) for key, val in inputs.items()}
            def inference_fn():
                with torch.no_grad():
                    for _ in range(args.iterations):
                        if args.use_mkldnn and args.mkldnn_verbose:
                            with torch.backends.mkldnn.verbose(torch.backends.mkldnn.VERBOSE_ON):
                                outputs = model(**inputs)
                        else:
                            outputs = model(**inputs)
</code></pre>
<p>I have checked the onednn_verbose log info, and realized that the cost of aten::linear is mainly about the reorder:</p>
<pre><code class="lang-auto">onednn_verbose,primitive,exec,cpu,inner_product,brgemm:avx512_core,forward_training,src_f32:a:blocked:ab::f0 wei_f32:a:blocked:AB16b64a::f0 bia_f32:a:blocked:a::f0 dst_f32:a:blocked:ab::f0,attr-scratchpad:user,,mb1ic1536oc8960,0.596924
onednn_verbose,primitive,exec,cpu,reorder,simple:any,undef,src_f32::blocked:abc::f0 dst_f32::blocked:abc::f0,attr-scratchpad:user,,1x1x8960,4.28809
onednn_verbose,primitive,exec,cpu,reorder,simple:any,undef,src_f32::blocked:abc::f0 dst_f32::blocked:abc::f0,attr-scratchpad:user,,1x1x1536,0.0109863
onednn_verbose,primitive,exec,cpu,reorder,jit:uni,undef,src_f32::blocked:ab::f0 dst_f32::blocked:AB16b64a::f0,attr-scratchpad:user,,8960x1536,4.32202
onednn_verbose,primitive,exec,cpu,inner_product,brgemm:avx512_core,forward_training,src_f32:a:blocked:ab::f0 wei_f32:a:blocked:AB16b64a::f0 bia_f32:a:blocked:a::f0 dst_f32:a:blocked:ab::f0,attr-scratchpad:user,,mb1ic1536oc8960,0.611816
onednn_verbose,primitive,exec,cpu,reorder,simple:any,undef,src_f32::blocked:abc::f0 dst_f32::blocked:abc::f0,attr-scratchpad:user,,1x1x8960,0.059082
onednn_verbose,primitive,exec,cpu,reorder,simple:any,undef,src_f32::blocked:abc::f0 dst_f32::blocked:abc::f0,attr-scratchpad:user,,1x1x8960,0.013916
onednn_verbose,primitive,exec,cpu,reorder,jit:uni,undef,src_f32::blocked:ab::f0 dst_f32::blocked:AB16b64a::f0,attr-scratchpad:user,,1536x8960,4.17603
onednn_verbose,primitive,exec,cpu,inner_product,brgemm:avx512_core,forward_training,src_f32:a:blocked:ab::f0 wei_f32:a:blocked:AB16b64a::f0 bia_f32:a:blocked:a::f0 dst_f32:a:blocked:ab::f0,attr-scratchpad:user,,mb1ic8960oc1536,0.780029
</code></pre>
<p>My question is, is there a way to directly convert a pretrained model’s weights downloaded from PyTorch into onednn format, so that future linear operations don’t need to perform reordering?</p>

Rubic_ZHANG: <p>here is my pytorch enviroment:<br>
:root@server1:/workspace# python -c “import torch; print(f’Pytorch version : {torch.<strong>version</strong>}‘); print(*torch.<strong>config</strong>.show().split(’\n’), sep=‘\n’)”<br>
Pytorch version : 2.5.1+cu124<br>
PyTorch built with:</p>
<ul>
<li>GCC 9.3</li>
<li>C++ Version: 201703</li>
<li>Intel(R) oneAPI Math Kernel Library Version 2024.2-Product Build 20240605 for Intel(R) 64 architecture applications</li>
<li>Intel(R) MKL-DNN v3.5.3 (Git Hash <a href="https://github.com/uxlfoundation/oneDNN/commit/66f0cb9eb66affd2da3bf5f8d897376f04aae6af" rel="noopener nofollow ugc">66f0cb9</a>)</li>
<li>OpenMP 201511 (a.k.a. OpenMP 4.5)</li>
<li>LAPACK is enabled (usually provided by MKL)</li>
<li>NNPACK is enabled</li>
<li>CPU capability usage: AVX512</li>
<li>Build settings: BLAS_INFO=mkl, BUILD_TYPE=Release, CUDA_VERSION=12.4, CUDNN_VERSION=9.1.0, CXX_COMPILER=/opt/rh/devtoolset-9/root/usr/bin/c++, CXX_FLAGS= -D_GLIBCXX_USE_CXX11_ABI=0 -fabi-version=11 -fvisibility-inlines-hidden -DUSE_PTHREADPOOL -DNDEBUG -DUSE_KINETO -DLIBKINETO_NOROCTRACER -DLIBKINETO_NOXPUPTI=ON -DUSE_FBGEMM -DUSE_PYTORCH_QNNPACK -DUSE_XNNPACK -DSYMBOLICATE_MOBILE_DEBUG_HANDLE -O2 -fPIC -Wall -Wextra -Werror=return-type -Werror=non-virtual-dtor -Werror=bool-operation -Wnarrowing -Wno-missing-field-initializers -Wno-type-limits -Wno-array-bounds -Wno-unknown-pragmas -Wno-unused-parameter -Wno-strict-overflow -Wno-strict-aliasing -Wno-stringop-overflow -Wsuggest-override -Wno-psabi -Wno-error=old-style-cast -Wno-missing-braces -fdiagnostics-color=always -faligned-new -Wno-unused-but-set-variable -Wno-maybe-uninitialized -fno-math-errno -fno-trapping-math -Werror=format -Wno-stringop-overflow, LAPACK_INFO=mkl, PERF_WITH_AVX=1, PERF_WITH_AVX2=1, TORCH_VERSION=2.5.1, USE_CUDA=ON, USE_CUDNN=ON, USE_CUSPARSELT=1, USE_EXCEPTION_PTR=1, USE_GFLAGS=OFF, USE_GLOG=OFF, USE_GLOO=ON, USE_MKL=ON, USE_MKLDNN=ON, USE_MPI=OFF, USE_NCCL=1, USE_NNPACK=ON, USE_OPENMP=ON, USE_ROCM=OFF, USE_ROCM_KERNEL_ASSERT=OFF,</li>
</ul>
<p>root@server1:/workspace# lscpu<br>
Architecture: x86_64<br>
CPU op-mode(s): 32-bit, 64-bit<br>
Address sizes: 46 bits physical, 48 bits virtual<br>
Byte Order: Little Endian<br>
CPU(s): 48<br>
On-line CPU(s) list: 0-47<br>
Vendor ID: GenuineIntel<br>
BIOS Vendor ID: Intel<br>
Model name: Intel(R) Xeon(R) Silver 4214 CPU @ 2.20GHz<br>
BIOS Model name: Intel(R) Xeon(R) Silver 4214 CPU @ 2.20GHz<br>
CPU family: 6<br>
Model: 85<br>
Thread(s) per core: 2<br>
Core(s) per socket: 12<br>
Socket(s): 2<br>
Stepping: 7<br>
BogoMIPS: 4400.00<br>
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 a<br>
rt arch_perfmon pebs bts rep_good nopl xtopology nonstop_tsc aperfmperf eagerfpu pni pclmulqdq dtes64 monitor ds_cpl vmx smx est tm2 ssse3 sdbg fma cx16 xtpr pdcm<br>
pcid dca sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm abm 3dnowprefetch epb cat_l3 cdp_l3 invpcid_single intel_ppin intel<br>
_pt ssbd mba ibrs ibpb stibp ibrs_enhanced tpr_shadow vnmi flexpriority ept vpid fsgsbase tsc_adjust bmi1 hle avx2 smep bmi2 erms invpcid rtm cqm mpx rdt_a avx512f<br>
avx512dq rdseed adx smap clflushopt clwb avx512cd avx512bw avx512vl xsaveopt xsavec xgetbv1 cqm_llc cqm_occup_llc cqm_mbm_total cqm_mbm_local dtherm ida arat pln<br>
pts pku ospke avx512_vnni md_clear spec_ctrl intel_stibp flush_l1d arch_capabilities<br>
Virtualization features:<br>
Virtualization: VT-x<br>
Caches (sum of all):<br>
L1d: 768 KiB (24 instances)<br>
L1i: 768 KiB (24 instances)<br>
L2: 24 MiB (24 instances)<br>
L3: 33 MiB (2 instances)<br>
NUMA:<br>
NUMA node(s): 2<br>
NUMA node0 CPU(s): 0,2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40,42,44,46<br>
NUMA node1 CPU(s): 1,3,5,7,9,11,13,15,17,19,21,23,25,27,29,31,33,35,37,39,41,43,45,47<br>
Vulnerabilities:<br>
Itlb multihit: KVM: Mitigation: Split huge pages<br>
L1tf: Not affected<br>
Mds: Not affected<br>
Meltdown: Not affected<br>
Spec store bypass: Mitigation; Speculative Store Bypass disabled via prctl and seccomp<br>
Spectre v1: Mitigation; Load fences, usercopy/swapgs barriers and __user pointer sanitization<br>
Spectre v2: Mitigation; Full retpoline, IBPB<br>
Srbds: Not affected<br>
Tsx async abort: Mitigation; Clear CPU buffers; SMT vulnerable</p>