环境:
win10 x64
python3.6
tensorflow r1.14
bazel 0.25.0
vs2015
msys2 x64
脱离环境谈都是耍流氓,何况在相同环境都可能出各种问题。
以下步骤使用bazel编译
1.根据官网安装以上软件软件。
2.下载tensorflow r1.14。
3.进入tensorflow代码目录,执行python configure.py。
4.因为是cpu版本,哪些xlt cuda都是No,针对cxx性能优化的选择yes。
5.开始编译dll,lib。
生成cxx版本dll:
bazel build //tensorflow:tensorflow_cc
生成lib文件:
bazel build //tensorflow:tensorflow_cc.lib
生成头文件(千万不要自己去找头文件,dll生成后不会自动生成头文件,tensorflow/BUILD有说明。网上很多都是写的自己拼凑,会疯的):
bazel build //tensorflow:install_headers
6.由于windows dll 64K符号的限制,tensorflow默认只给出了一部分符号,没有包含的符号要自己加入,可以根据编译时的编译器的提示,将提示Link失败的符号写入tensorflow/tensorflow/tools/def_file_filter/def_file_filter.py.tpl中,位置为:
if args.target:
def_fp.write("LIBRARY " + args.target + "\n")
def_fp.write("EXPORTS\n")
def_fp.write("\t ??1OpDef@tensorflow@@UEAA@XZ\n")
此段后面,然后重新生成lib即可。
坑:tensorflow不同的版本对bazel,python版本有要求,注意匹配。
其他版本不一定可行。
测试代码:输出19 -3
#include "tensorflow/cc/client/client_session.h"
#include "tensorflow/cc/ops/standard_ops.h"
#include "tensorflow/core/framework/tensor.h"
#pragma comment(lib, "tensorflow_cc.lib")
int main() {
using namespace tensorflow;
using namespace tensorflow::ops;
Scope root = Scope::NewRootScope();
// Matrix A = [3 2; -1 0]
auto A = Const(root, { {3.f, 2.f}, {-1.f, 0.f} });
// Vector b = [3 5]
auto b = Const(root, { {3.f, 5.f} });
// v = Ab^T
auto v = MatMul(root.WithOpName("v"), A, b, MatMul::TransposeB(true));
std::vector<Tensor> outputs;
ClientSession session(root);
// Run and fetch v
TF_CHECK_OK(session.Run({ v }, &outputs));
// Expect outputs[0] == [19; -3]
LOG(INFO) << outputs[0].matrix<float>();
system("pause");
return 0;
}