无法使用Tensorflow作为依赖项的Bazel构建C ++项目

时间:2018-11-11 22:55:12

标签: c++ tensorflow bazel

我看到很多教程,它们解释了如何在Tensorflow的Bazel WORKSPACE(例如this one)内部构建项目。但是我似乎无法找到一种方法来构建自己的项目并将tensorflow作为依赖项。我查看了this Bazel文档,并且显然有一种使用外部依赖项进行构建的方法,我尝试着自己进行研究。 (因为tf也是用bazel构建的。)

这是我的目录结构:

.
├── perception
│   ├── BUILD
│   └── graph_loader.cc
├── third-party
│   └── tensorflow # I cloned tf repo into this folder
└── WORKSPACE

这是我的perception/BUILD文件中的内容:

cc_binary(
    name = "graph-loader",
    srcs = [
        "graph_loader.cc",
    ],
    deps = [
        "@tensorflow//tensorflow:libtensorflow.so",
    ]
)

这是我的WORKSPACE文件中的内容:

local_repository(
    name = "tensorflow",
    path = "path/to/my/project/third-party/tensorflow",
)

这是我的perception/graph_loader.cc文件中的内容:

#include "tensorflow/cc/client/client_session.h"
#include "tensorflow/cc/ops/standard_ops.h"
#include "tensorflow/core/framework/tensor.h"

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>();
  return 0;
}

我使用以下命令运行构建:

build //perception:graph-loader

但是此消息失败:

ERROR: path/to/my/project/perception/BUILD:1:1: error loading package '@tensorflow//tensorflow': Extension file not found. Unable to load package for '@local_config_cuda//cuda:build_defs.bzl': The repository could not be resolved and referenced by '//perception:graph-loader'
ERROR: Analysis of target '//perception:graph-loader' failed; build aborted: error loading package '@tensorflow//tensorflow': Extension file not found. Unable to load package for '@local_config_cuda//cuda:build_defs.bzl': The repository could not be resolved
INFO: Elapsed time: 0.037s
INFO: 0 processes.
FAILED: Build did NOT complete successfully (1 packages loaded, 0 targets configured)
    currently loading: @tensorflow//tensorflow

以下是问题:

  1. 我在做什么错,从而使我的构建不断失败?
  2. 甚至有可能做我在这里尝试的事情,即在我的项目内部构建tensorflow吗?

1 个答案:

答案 0 :(得分:4)

您收到此错误,因为您没有在WORKSPACE中添加必需的存储库规则。 Bazel当前没有递归工作空间,因此您需要手动将所有依赖项的存储库复制到主WORKSPACE中。

在您的WORKSPACE文件中,复制以下内容:

local_repository(
    name = "org_tensorflow",
    path = "third-party/tensorflow",
)

https://github.com/tensorflow/tensorflow/blob/master/WORKSPACE的所有内容附加到WORKSPACE文件中。删除workspace(name = "org_tensorflow")行。

最后,将//*中的所有WOKRSPACE更改为@org_tensorflow//*

请注意,尚未正式支持在子文件夹中构建Tensorflow。