使用 bazel 构建 TensorFlow C++调用模型时,.so 文件不起作用

When using bazel to build TensorFlow C++ call model, .so file doesn't work

本文关键字:so 文件 不起作用 模型 调用 bazel 构建 TensorFlow C++ 使用      更新时间:2023-10-16

我想使用TensorFlow C++api来调用模型并预测答案。首先,我克隆了张量流存储库

git clone --递归 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,并在将来使用没有张量流源代码的 .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。

我的构建文件如下所示:

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?

你应该在生成文件中引用libtensorflow_frameowork.so。就像下面的代码一样:

g++ -std=c++11 test_so.cpp -L./ -lmy_helper -ltensorflow_framework -I./ -o my_helper

我猜 bazel 在编译我的代码时错过了 .so 中的一些 tensorflow 中的源代码。