如何在Anaconda中重新编译TensorFlow以启用CPU指令
解决TensorFlow CPU指令优化编译问题(Anaconda环境)
问题描述
运行Keras脚本时出现如下提示:
2024-02-10 14:11:47.255446: I tensorflow/core/platform/cpu_feature_guard.cc:182] This TensorFlow binary is optimized to use available CPU instructions in performance-critical operations. To enable the following instructions: SSE4.1 SSE4.2 AVX AVX2 AVX_VNNI FMA, in other operations, rebuild TensorFlow with the appropriate compiler flags.需在Anaconda环境下重新编译TensorFlow以启用这些CPU指令、消除提示并提升性能,已配置好官方指南中的依赖,但不清楚TensorFlow仓库存放位置、适配问题的编译命令,以及编译后文件的放置路径。
解决方案
一、TensorFlow仓库存放位置
- 可选择Anaconda环境所在目录下的任意位置(比如环境根目录的
src文件夹),也可放在个人工作目录,只要后续编译时能定位到路径即可。建议直接克隆到当前激活的Anaconda环境的site-packages同级目录,方便后续替换操作。 - 克隆仓库命令(未克隆过的话执行):
git clone https://github.com/tensorflow/tensorflow.git
二、适配CPU指令的编译命令
先激活目标Anaconda环境,再进入TensorFlow仓库根目录,执行以下步骤:
- 配置编译参数:
配置过程中,当询问是否启用特定CPU优化时选择./configureY,并指定要启用的指令集:SSE4.1 SSE4.2 AVX AVX2 AVX_VNNI FMA;同时确保指定Anaconda环境中的Python解释器路径。 - 执行编译命令(CPU版本示例,可按需调整):
该命令通过bazel build --config=opt --copt=-mavx --copt=-mavx2 --copt=-mfma --copt=-msse4.1 --copt=-msse4.2 //tensorflow/tools/pip_package:build_pip_package--copt参数强制启用指定的CPU指令集,确保编译后的TensorFlow支持这些性能优化。
三、编译后文件部署(自动适配Anaconda路径)
- 编译完成后生成pip安装包:
./bazel-bin/tensorflow/tools/pip_package/build_pip_package /tmp/tensorflow_pkg - 卸载Anaconda环境中原有的TensorFlow:
pip uninstall tensorflow -y - 安装编译好的自定义包(替换为实际生成的包文件名):
安装完成后,编译后的TensorFlow文件会自动放置到当前Anaconda环境的pip install /tmp/tensorflow_pkg/tensorflow-*.whlsite-packages目录,无需手动移动。
内容的提问来源于stack exchange,提问作者mkow93
相关产品推荐
相关产品推荐

