Question on performance under limited cpu usage
Hi, dear developers, thank you for your great work on mkl-dnn.
I run inference of a conv-lstm-dnn network on a cpu-only machine, with tensorflow with and without mkldnn integrated. I found the mkldnn version tensorflow is slower than the other when I use only one cpu core (by setting OMP_THREADS_NUM=1, intra_op_parallelism_threads=1, inter_op_parallelism_threads=1)
After profiling, I have two questions
_MklConv2DWithBiasseems much slower than tensorflow'sConv2Don my machine, is there anything wrong of my setting? is there any way to accelerate?- I'm not sure, but
MatMulseems not be replaced with mkldnn version of matmul, is there anything wrong?
Environment
Intel MKL-DNN includes hardware-specific optimizations and may behave differently on depending on the compiler and build environment. Include the following information to help reproduce the issue:
- CPU make and model (try
lscpu):
Architecture: x86_64
CPU op-mode(s): 32-bit, 64-bit
Byte Order: Little Endian
CPU(s): 32
On-line CPU(s) list: 0-31
Thread(s) per core: 2
Core(s) per socket: 8
Socket(s): 2
NUMA node(s): 2
Vendor ID: GenuineIntel
CPU family: 6
Model: 45
Model name: Intel(R) Xeon(R) CPU E5-2670 0 @ 2.60GHz
Stepping: 6
CPU MHz: 1219.867
CPU max MHz: 3300.0000
CPU min MHz: 1200.0000
BogoMIPS: 5200.07
Virtualization: VT-x
L1d cache: 32K
L1i cache: 32K
L2 cache: 256K
L3 cache: 20480K
NUMA node0 CPU(s): 0-7,16-23
NUMA node1 CPU(s): 8-15,24-31
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 arch_perfmon pebs bts rep_good nopl xtopology nonstop_tsc aperfmperf eagerfpu pni pclmulqdq dtes64 monitor ds_cpl vmx smx est tm2 ssse3 cx16 xtpr pdcm pcid dca sse4_1 sse4_2 x2apic popcnt tsc_deadline_timer aes xsave avx lahf_lm epb tpr_shadow vnmi flexpriority ept vpid xsaveopt dtherm ida arat pln pts
- OS version (
uname -a)
Linux localhost.localdomain 3.10.0-693.el7.x86_64 #1 SMP Tue Aug 22 21:09:27 UTC 2017 x86_64 x86_64 x86_64 GNU/Linux
- Compiler version (
gcc --version)
Using built-in specs.
COLLECT_GCC=gcc
COLLECT_LTO_WRAPPER=/usr/libexec/gcc/x86_64-redhat-linux/4.8.5/lto-wrapper
Target: x86_64-redhat-linux
Configured with: ../configure --prefix=/usr --mandir=/usr/share/man --infodir=/usr/share/info --with-bugurl=http://bugzilla.redhat.com/bugzilla --enable-bootstrap --enable-shared --enable-threads=posix --enable-checking=release --with-system-zlib --enable-__cxa_atexit --disable-libunwind-exceptions --enable-gnu-unique-object --enable-linker-build-id --with-linker-hash-style=gnu --enable-languages=c,c++,objc,obj-c++,java,fortran,ada,go,lto --enable-plugin --enable-initfini-array --disable-libgcj --with-isl=/builddir/build/BUILD/gcc-4.8.5-20150702/obj-x86_64-redhat-linux/isl-install --with-cloog=/builddir/build/BUILD/gcc-4.8.5-20150702/obj-x86_64-redhat-linux/cloog-install --enable-gnu-indirect-function --with-tune=generic --with-arch_32=x86-64 --build=x86_64-redhat-linux
Thread model: posix
gcc version 4.8.5 20150623 (Red Hat 4.8.5-28) (GCC)
- MKLROOT value (
echo MKLROOT=$MKLROOT)
MKLROOT=
- CMake version (
cmake --version): 3.11.2 - CMake output log
Steps to reproduce
I run inference of a network use the code below, under both case (with or without mkldnn), and generate json file of timeline for profiling.
The code was run with these envvar:
KMP_BLOCKTIME=0
KMP_AFFINITY=granularity=fine,verbose,compact,1,0
OMP_NUM_THREADS=1
KMP_SETTINGS=1
The profiling jsons are attached as attachment. timeline.json.zip
from __future__ import print_function, division
import numpy as np
import tensorflow as tf
import time
import sys
import random
BATCH_SIZE=1
def get_cld_model(feat, scope):
'''
config["n_lstm_layer", "n_lstm_unit", "n_dnn_layer", "n_dnn_unit", "n_output_dim"]
:param feature: float32, [batch_size, n_steps, n_tot_dim] (n_tot_dim = n_input * (2 * n_context + 1) )
:param is_training: bool, []
:return: float32, [batch_size, n_steps, n_output] logits
'''
#PH_STATE = tf.placeholder_with_default()
padded_len = tf.shape(feat)[1]
with tf.variable_scope('CNN') as scope:
reshaped_feature = tf.reshape(feat, shape=[-1, 11, 30, 1])
conv1 = tf.layers.conv2d(reshaped_feature, 96, [11, 7], activation=None)
conv1 = tf.layers.batch_normalization(conv1, training=False)
conv1 = tf.nn.relu(conv1)
conv1 = tf.reshape(conv1, shape=[BATCH_SIZE, -1, 2304]) # 2304 ?
lstm_list = []
zero_states = []
state_placeholders = []
with tf.variable_scope('LSTM') as scope:
for i_layer in range(2):
lstm = tf.contrib.rnn.LSTMCell(
576,
use_peepholes=True,
forget_bias=1.0,
state_is_tuple=True)
zero_states.append(lstm.zero_state(batch_size=BATCH_SIZE, dtype=tf.float32))
state_placeholders.append(tf.placeholder_with_default(lstm.zero_state(batch_size=BATCH_SIZE, dtype=tf.float32), [2, 1, 576], name='S{}'.format(i_layer)))
lstm_list.append(lstm)
stacked_lstm = tf.contrib.rnn.MultiRNNCell(
lstm_list, state_is_tuple=True)
state_tensor = tuple([tf.contrib.rnn.LSTMStateTuple(ph_layer[0,:,:], ph_layer[1,:,:]) for ph_layer in state_placeholders])
outputs, final_states = tf.nn.dynamic_rnn(
cell=stacked_lstm,
inputs=conv1,
initial_state=state_tensor,
sequence_length=None,
dtype=tf.float32,
time_major=False,
scope=scope
)
final_states = [tf.identity(final_states[i], name="FS{}".format(i)) for i in range(len(final_states))]
with tf.variable_scope('DNN') as scope:
for i_layer in range(1, 1):
outputs = tf.contrib.layers.fully_connected(
inputs=outputs,
num_outputs=1728,
activation_fn=None,
biases_initializer=tf.random_normal_initializer(stddev=0.04687),
scope=scope
)
outputs = tf.layers.batch_normalization(outputs, training=False)
outputs = tf.nn.relu(outputs)
outputs = tf.contrib.layers.fully_connected(
inputs=outputs,
num_outputs=8970,
activation_fn=None,
scope=scope
)
#outputs = tf.nn.log_softmax(outputs, name='LOGIT')
outputs = tf.nn.softmax(outputs, name='LOGIT')
return outputs, final_states, state_placeholders
def benchmark_unilstm(n_input, n_output, n_layer, n_hidden, n_iter_warmup, n_iter, n_frame):
ph_x = tf.placeholder(shape=[None, n_input], dtype=tf.float32)
var_y, var_states, _ = get_cld_model(ph_x, None)
conf = tf.ConfigProto()
conf.inter_op_parallelism_threads = 1
conf.intra_op_parallelism_threads = 1
sess = tf.Session(config=conf)
sess.run(tf.global_variables_initializer())
print("Warming up...", file=sys.stderr)
tstart = time.time()
for i in range(n_iter_warmup):
n_frame_noise = random.choice([-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5])
tstart_inner = time.time()
y, states = sess.run([var_y, var_states], feed_dict={ph_x: np.random.random([n_frame + n_frame_noise, n_input])})
tend_inner = time.time()
lapse_inner = tend_inner - tstart_inner
print(" - %d-th iter of warming up took %f seconds. NFRAME=%d, RTF=%f" % (i, lapse_inner, y.shape[1], 100 * lapse_inner / float(y.shape[1])), file=sys.stderr)
tend = time.time()
lapse = tend - tstart
rtf_warmup = 100 * lapse / float(n_frame * n_iter_warmup)
print("Warming up %d iterations in %f seconds. RTF=%f" % (n_iter_warmup, lapse, rtf_warmup), file=sys.stderr)
# profiling
print("Profiling...", file=sys.stderr)
run_metadata = tf.RunMetadata()
y, states = sess.run([var_y, var_states], feed_dict={ph_x: np.random.random([n_frame, n_input])}, options=tf.RunOptions(trace_level=tf.RunOptions.FULL_TRACE), run_metadata=run_metadata)
from tensorflow.python.client import timeline
trace = timeline.Timeline(step_stats=run_metadata.step_stats)
with open('timeline-fw.json', 'w') as trace_file:
trace_file.write(trace.generate_chrome_trace_format())
print("Profiling Done ...", file=sys.stderr)
print("Running...", file=sys.stderr)
tstart = time.time()
for i in range(n_iter):
n_frame_noise = random.choice([-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5])
tstart_inner = time.time()
y, states = sess.run([var_y, var_states], feed_dict={ph_x: np.random.random([n_frame + n_frame_noise, n_input])})
tend_inner = time.time()
lapse_inner = tend_inner - tstart_inner
print(" - %d-th iter took %f seconds. NFRAME=%d, RTF=%f" % (i, lapse_inner, y.shape[1], 100 * lapse_inner / float(y.shape[1])), file=sys.stderr)
tend = time.time()
lapse = tend - tstart
rtf = 100 * lapse / float(n_frame * n_iter)
print("%d iterations in %f seconds. RTF=%f" % (n_iter, lapse, rtf), file=sys.stderr)
print("%d, %d, %d, %d, %d, %d, %d, %.4f, %.4f" % (n_input, n_output, n_layer, n_hidden, n_iter_warmup, n_iter, n_frame, rtf_warmup, rtf))
if __name__ == "__main__":
n_input, n_output, n_layer, n_hidden, n_iter_warmup, n_iter, n_frame = [330, 8970, 2, 576, 100, 500, 48] #[int(item) for item in sys.argv[1:]]
benchmark_unilstm(n_input, n_output, n_layer, n_hidden, n_iter_warmup, n_iter, n_frame)
Actual behavior
Describe the behavior you see.
Expected behavior
Describe the behavior you expect.
Thanks very much.
Summon @jbobba on TF side. Meanwhile, @t13m, could you please run you benchmark with MKLDNN_VERBOSE=1 (when Intel MKL-DNN is used) and share the verbose dump here?
(Update) Could you please also share the timings of the convolution in TF w/o Intel MKL-DNN?
One note is that your system is SandyBridge. As of now Intel MKL-DNN uses SSE4.2 optimizations instead of AVX in this case. Alas, this would not give more than 50% of efficiency. Our colleagues have plans to create a PR with AVX optimizations, that should improve the situation though I don't have any ETA on this PR.
Another quick note is that before Haswell Intel MKL-DNN has optimizations for inference only. Backward passes would work, but would use gemm-based fallback for the convolutions which is inefficient.
Which version of tensorflow are you using?
We recently pushed some improvements to Tensorflow to reduce overhead of MKLDNN primitive creation (https://github.com/tensorflow/tensorflow/pull/19754) that might be slowing down _mklconv2dwithbias. MKLDNN_VERBOSE=2 should give a better idea of the breakdown between primitive creation vs actual mkldnn execution for this op.
The Matmul op calls into MKL's sgemm APIs without needing to rewrite.
Hi, Thank you so much for your quickly reply.
The version of tensorflow I use is 1.9.0, built from source.
Part of the output when using MKLDNN_VERBOSE=1:
mkldnn_verbose.txt
Part of the output when using MKLDNN_VERBOSE=2:
mkldnn_verbose_2.txt
Hi @emfomenk @jbobba , I attached the verbose output above. The duration of _MklConv2DWithBias is 565.738ms; the duration of TF's Conv2D(without MKL-DNN) is 1.825ms. Both timelines are attached below (the json file of timeline are already posted):

Another question is about thread setting of mkl. I want to use tensorflow with mkl-dnn as a server that responses to random requests, I hope that one request is handled with no more than one cpu core, so that multiple request can be handled simultaneously without harm to performance. I set OMP_THREADS_NUM=1 for this purpose, is that a good way?
The key line here is: mkldnn_verbose,exec,convolution,ref:any,forward_training,fsrc:nchw fwei:oihw fbia:x fdst:nchw,alg:convolution_direct,mb43_g1ic1oc96_ih11oh1kh11sh1dh0ph0_iw30ow24kw7sw1dw0pw0,660.891
MKLDNN needs to use gemm-based convolution and not ref:any. @emfomenk should be able to comment more on why its ending up there.
With regards to using single cpu core, inter_op_parallelism_threads=1 and OMP_NUM_THREADS=1 should be sufficient.
@jbobba, isn't it because Intel MKL-DNN integration in TF happens w/o Intel MKL BLAS support? Since the host is below AVX2 we can't use jitted gemm and rely on Intel MKL.
Interesting. By default, we build MKL-DNN with MKL BLAS. https://github.com/tensorflow/tensorflow/blob/master/third_party/mkl_dnn/mkldnn.BUILD#L25
Unless @t13m changed the TF build to use an open-source only MKLDNN, you should be able to use MKL inside convolution?
Agree, really weird... Might it be that TF version is old?
I ran benchdnn for the mentioned problem and gemm worked fine for me.
$ tests/benchdnn/benchdnn --conv -v10 mb43_g1ic1oc96_ih11oh1kh11sh1dh0ph0_iw30ow24kw7sw1dw0pw0
run: mb43ic1ih11iw30oc96oh1ow24kh11kw7n"wip"
mkldnn implementation: gemm:blas # <=== gemm is used
@@@ [DST] final: diff: l0(``-0``) l1:(2.91813e+08,2.91813e+08,0,``0``) l2:(1.20527e+06,1.20527e+06,0,``0``) l8:(9116,9116,-0,``-0``)
@@@ [DST] final: trust range:1.00 nz:1.00 (level range:0.30 nz:0.30). in:99072 (ok:99072) below:0 (ok:0) above:0 (ok:0) nz:99055 total:99072
0:PASSED __REPRO: mb43ic1ih11iw30oc96oh1ow24kh11kw7n"wip"
tests:1 passed:1 skipped:0 mistrusted:0 unimplemented:0 failed:0
Hi, @jbobba @emfomenk , thank you. I checked the mkldnn.BUILD file, and found the line you mentioned does not exist until https://github.com/tensorflow/tensorflow/commit/64117da0c36f0697467ce6d56a7be6837da24d2f , which means in the version I used, v1.9.0, MKL BLAS maybe not used? I guess I'll just pull the latest tensorflow and give it another try, and then report the result here.
Thank you so much :P
Sounds good, thanks @t13m!
I tried latest version TF, and it works!
The verbose output is like this:
mkldnn_verbose,exec,convolution,gemm:blas,forward_training,fsrc:nchw fwei:oihw fbia:x fdst:nchw,alg:convolution_direct,mb44_g1ic1oc96_ih11oh1kh11sh1dh0ph0_iw30ow24kw7sw1dw0pw0,0.746094
mkldnn_verbose,create,batch_normalization,ncsp_bnorm:any,forward_inference,fdata:nchw fdiff:undef,flags:3,mb44ic96ih1iw24,0.00415039
mkldnn_verbose,exec,batch_normalization,ncsp_bnorm:any,forward_inference,fdata:nchw fdiff:undef,flags:3,mb44ic96ih1iw24,0.352783
mkldnn_verbose,create,eltwise,jit:sse42,forward_training,fdata:nchw fdiff:undef,alg:eltwise_relu,mb44ic96ih1iw24,0.0490723
mkldnn_verbose,exec,eltwise,jit:sse42,forward_training,fdata:nchw fdiff:undef,alg:eltwise_relu,mb44ic96ih1iw24,0.0378418
mkldnn_verbose,exec,reorder,jit:uni,undef,in:f32_nchw out:f32_nhwc,num:1,44x96x1x24,0.0461426
mkldnn_verbose,exec,sum,simple:any,undef,in:f32_blocked out:f32_blocked,num:2,1x576,0.0109863
mkldnn_verbose,exec,sum,simple:any,undef,in:f32_blocked out:f32_blocked,num:2,1x576,0.0109863
<repeat for several times>
mkldnn_verbose,exec,sum,simple:any,undef,in:f32_blocked out:f32_blocked,num:2,1x576,0.00415039
mkldnn_verbose,exec,sum,simple:any,undef,in:f32_blocked out:f32_blocked,num:2,1x576,0.00317383
mkldnn_verbose,exec,sum,simple:any,undef,in:f32_blocked out:f32_blocked,num:2,1x576,0.00292969
mkldnn_verbose,create,softmax,ref:any,forward_inference,fdata:nc fdiff:undef,,mb44ic8970ih-1180846529iw32655,0.00292969
mkldnn_verbose,exec,softmax,ref:any,forward_inference,fdata:nc fdiff:undef,,mb44ic8970ih-1180846529iw32655,1.31421
mkldnn_verbose,exec,reorder,jit:uni,undef,in:f32_nhwc out:f32_nchw,num:1,50x1x11x30,0.0249023
mkldnn_verbose,exec,reorder,jit:uni,undef,in:f32_hwio out:f32_oihw,num:1,96x1x11x7,0.0100098
mkldnn_verbose,exec,convolution,gemm:blas,forward_training,fsrc:nchw fwei:oihw fbia:x fdst:nchw,alg:convolution_direct,mb50_g1ic1oc96_ih11oh1kh11sh1dh0ph0_iw30ow24kw7sw1dw0pw0,0.858887
mkldnn_verbose,create,batch_normalization,ncsp_bnorm:any,forward_inference,fdata:nchw fdiff:undef,flags:3,mb50ic96ih1iw24,0.00317383
mkldnn_verbose,exec,batch_normalization,ncsp_bnorm:any,forward_inference,fdata:nchw fdiff:undef,flags:3,mb50ic96ih1iw24,0.393066
mkldnn_verbose,create,eltwise,jit:sse42,forward_training,fdata:nchw fdiff:undef,alg:eltwise_relu,mb50ic96ih1iw24,0.0461426
mkldnn_verbose,exec,eltwise,jit:sse42,forward_training,fdata:nchw fdiff:undef,alg:eltwise_relu,mb50ic96ih1iw24,0.0441895
mkldnn_verbose,exec,reorder,jit:uni,undef,in:f32_nchw out:f32_nhwc,num:1,50x96x1x24,0.052002
mkldnn_verbose,exec,sum,simple:any,undef,in:f32_blocked out:f32_blocked,num:2,1x576,0.0119629
mkldnn_verbose,exec,sum,simple:any,undef,in:f32_blocked out:f32_blocked,num:2,1x576,0.0109863
mkldnn_verbose,exec,sum,simple:any,undef,in:f32_blocked out:f32_blocked,num:2,1x576,0.0109863
mkldnn_verbose,exec,sum,simple:any,undef,in:f32_blocked out:f32_blocked,num:2,1x576,0.0109863
mkldnn_verbose,exec,sum,simple:any,undef,in:f32_blocked out:f32_blocked,num:2,1x576,0.0349121
mkldnn_verbose,exec,sum,simple:any,undef,in:f32_blocked out:f32_blocked,num:2,1x576,0.0100098
mkldnn_verbose,exec,sum,simple:any,undef,in:f32_blocked out:f32_blocked,num:2,1x576,0.0100098
mkldnn_verbose,exec,sum,simple:any,undef,in:f32_blocked out:f32_blocked,num:2,1x576,0.0100098
mkldnn_verbose,exec,sum,simple:any,undef,in:f32_blocked out:f32_blocked,num:2,1x576,0.0090332
<repeat for several times>
mkldnn_verbose,exec,sum,simple:any,undef,in:f32_blocked out:f32_blocked,num:2,1x576,0.00317383
mkldnn_verbose,create,softmax,ref:any,forward_inference,fdata:nc fdiff:undef,,mb50ic8970ih-1180846529iw32655,0.00292969
mkldnn_verbose,exec,softmax,ref:any,forward_inference,fdata:nc fdiff:undef,,mb50ic8970ih-1180846529iw32655,1.76904
mkldnn_verbose,exec,reorder,jit:uni,undef,in:f32_nhwc out:f32_nchw,num:1,45x1x11x30,0.0219727
mkldnn_verbose,exec,reorder,jit:uni,undef,in:f32_hwio out:f32_oihw,num:1,96x1x11x7,0.019043
I think the issue solved! The conv, matmul and softmax are faster than TF's. Thanks! Besides, the overhead tensorflow's implementation of rnn kernels (lstm, gru ...) seems big. Is there any plan to support any optimization on rnn in MKL-DNN? It would be exciting if you do.
I found the LSTMBlockCell and GRUBlockCell in tensorflow are using eigen-based gemm. I tried to replace it with gemm of MKLBLAS, the speed of GRUBlockCell is improved by about 3% under my setting (XEON E5-2670 0, sandybridge, single thread, cell size = 576).
Glad to hear @t13m. Feel free to submit a PR to tensorflow to use MKL inside LSTMBlockCell and GRUBlockCell. Will be happy to receive contributions. We are also investigating using MKLDNN's new RNN APIs but dont have anything to report at the moment.
Great! Looking forward to your integration of MKLDNN's RNN. Thanks so much.
Thanks! And thanks @jbobba for the inputs!