c++ - 使用 bazel 构建 TensorFlow C++ 调用模型时,.so 文件不起作用
问题描述
我想使用 TensorFlow C++ api 来调用模型并预测答案。首先,我克隆了 tensorflow 存储库
git clone --recursive https://github.com/tensorflow/tensorflow
然后我编写如下 C++ 代码:
一个代码是一个调用TensorFlow api的类,头文件是这样的:
#ifndef _DEEPMODEL_H_
#define _DEEPMODEL_H_
#include <iostream>
#include <string>
#include <vector>
#include "tensorflow/core/public/session.h"
#include "tensorflow/core/protobuf/meta_graph.pb.h"
#include "tensorflow/cc/client/client_session.h"
#include "tensorflow/cc/ops/standard_ops.h"
#include "tensorflow/core/framework/tensor.h"
using namespace std;
using namespace tensorflow;
class DeepModel{
public:
DeepModel(const string graph_path, const string checkpoint_path);
virtual ~DeepModel();
bool onInit();
void unInit();
vector<float> predict(vector<vector<float>>& x, string input_name, string output_name);
private:
string graph_path;
string checkpoint_path;
MetaGraphDef graph_def;
Session* my_sess;
};
#endif
在此之后,我编写了一个简单的封装代码。我想编译一个.so,将来使用没有tensorflow源代码的.so。我的封装代码如下:
#ifndef _MODEL_HELPER_H_
#define _MODEL_HELPER_H_
#include <vector>
#include <string>
using namespace std;
class ModelHelper{
public:
ModelHelper(const string graph_path, const string checkpoint_path);
virtual ~ModelHelper();
vector<float> predict(vector<vector<float> >& x, string input_name, string output_name);
private:
string graph_path;
string checkpoint_path;
};
#endif
我已经编写代码来测试上面的代码,它运行良好。然后我想用 bazel 编译 .so。
我的 BUILD 文件如下所示:
load("//tensorflow:tensorflow.bzl", "tf_cc_binary")
tf_cc_binary(
name = "my_helper.so",
srcs = ["model_helper.cc", "model_helper.h", "deepmodel.cc", "deepmodel.h"],
linkshared = 1,
deps = [
"//tensorflow/cc:cc_ops",
"//tensorflow/cc:client_session",
"//tensorflow/core:tensorflow"
],
)
然后我将model_helper.so重命名为libmodel_helper.so,并编写cpp代码来测试.so文件。我想编译代码,命令是这样的
g++ -std=c++11 test_so.cpp -L./ -lmy_helper -I./ -o my_helper
然后我遇到了错误:
.//libmy_helper.so: undefined reference to `stream_executor::cuda::ScopedActivateExecutorContext::~ScopedActivateExecutorContext()'
.//libmy_helper.so: undefined reference to `stream_executor::cuda::ScopedActivateExecutorContext::ScopedActivateExecutorContext(stream_executor::StreamExecutor*)'
.//libmy_helper.so: undefined reference to `tensorflow::DeviceName<Eigen::GpuDevice>::value[abi:cxx11]'
collect2: error: ld returned 1 exit status
我真的不知道为什么。我不能单独使用 .so 吗?
解决方案
您应该在 makefile 中引用 libtensorflow_frameowork.so。就像下面的代码:
g++ -std=c++11 test_so.cpp -L./ -lmy_helper -ltensorflow_framework -I./ -o my_helper
我猜 bazel 在编译我的代码时错过了 tensorflow 中的一些源代码到 .so 中。
推荐阅读
- symfony - Symfony 4 模态形式
- javascript - 按距离给定的升序对点数组进行排序
- c# - CheckPasswordASync 总是返回 false
- python - 在等待方法tkinter中等待一秒钟
- c++ - 如何在 C++ 中修复“没有匹配的函数来调用...”?
- python - 用于匹配 Python 列表中的特定模式的正则表达式
- amazon-web-services - S3 向用户授予对象访问权限
- laravel - Vanilo 的自定义产品属性放在哪里?
- sass - 使用设计系统作为源在各自的项目目录中编译 sass 文件
- android - 如何将视图相对于非同级视图居中?