TensorFlow如何充分使用所有CPU核数,提高TensorFlow的CPU使用率,以及Intel的MKL加速
转载链接:http://nooverfit.com/wp/tensorflow%E5%A6%82%E4%BD%95%E5%85%85%E5%88%86%E4%BD%BF%E7%94%A8%E6%89%80%E6%9C%89cpu%E6%A0%B8%E6%95%B0%EF%BC%8C%E6%8F%90%E9%AB%98tensorflow%E7%9A%84cpu%E4%BD%BF%E7%94%A8%E7%8E%87%EF%BC%8C%E4%BB%A5/
TensorFlow如何充分使用所有CPU核数,提高TensorFlow的CPU使用率,以及Intel的MKL加速
许多朋友使用服务器时,碰巧服务器没有安装GPU或者GPU都被占满了。可是,服务器有很多CPU都是空闲的,其实,把这些CPU都充分利用起来,也可以有不错的训练效果。
但是,如果你是用CPU版的TF,有时TensorFlow并不能把所有CPU核数使用到,这时有个小技巧David 9要告诉大家:
- with tf.Session(config=tf.ConfigProto(
- device_count={"CPU":12},
- inter_op_parallelism_threads=1,
- intra_op_parallelism_threads=1,
- gpu_options=gpu_options,
- )) as sess:
在Session定义时,ConfigProto中可以尝试指定下面三个参数:
- device_count, 告诉tf Session使用CPU数量上限,如果你的CPU数量较多,可以适当加大这个值
- inter_op_parallelism_threads和intra_op_parallelism_threads告诉session操作的线程并行程度,如果值越小,线程的复用就越少,越可能使用较多的CPU核数。如果值为0,TF会自动选择一个合适的值。
David 9亲自试验,训练似乎有1倍速度的提高。
另外,有的朋友的服务器上正好都是Intel的CPU,很可能需要把Intel的MKL包编译进TensorFlow中,以增加训练效率。这里David 9把MKL编译进TF的关键点也指出一下。
- Run “./configure” from the TensorFlow source directory, and it will download latest Intel MKL for machine learning automatically in tensorflow/third_party/mkl/mklml if you select the options to use Intel MKL
- Execute the following commands to create a pip package that can be used to install the optimized TensorFlow build.
- PATH can be changed to point to a specific version of GCC compiler:
export PATH=/PATH/gcc/bin:$PATH - LD_LIBRARY_PATH can also be changed to point to new GLIBC :
- export LD_LIBRARY_PATH=/PATH/gcc/lib64:$LD_LIBRARY_PATH.
- Build for best performance on Intel Xeon and Intel Xeon Phi processors:
- bazel build --config=mkl --copt="-DEIGEN_USE_VML" -c opt //tensorflow/tools/pip_package:
- build_pip_package
- PATH can be changed to point to a specific version of GCC compiler:
3. Install the optimized TensorFlow wheel
- bazel-bin/tensorflow/tools/pip_package/build_pip_package ~/path_to_save_wheel
- pip install --upgrade --user ~/path_to_save_wheel /wheel_name.whl
与官网编译TF的大致流程类似,就是先./configure,再用bazel编译TensorFlow。
最后用编译好的bazel工具生成whl的包,用来安装pip TensorFlow。
唯一的不同要注意用–config=mkl的选项编译TensorFlow:
bazel build –config=mkl –copt=”-DEIGEN_USE_VML” -c opt //tensorflow/tools/pip_package: build_pip_package
这样,用pip安装完成TF后,mkl就集成在TF中了。