libtorch踩坑记录


一、Linux CMakeLists链接版本

官网下载Linux版本libtorch的时候会发现有(Pre-cxx11 ABI)(cxx11 ABI)两个版本。

如果链接(cxx11 ABI)版本需要在CMakeLists.txt中加入

add_definitions(-D _GLIBCXX_USE_CXX11_ABI=0)

原因是旧版(c++03规范)的libstdc++.so,和新版(c++11规范)的libstdc++.so两个库同时存在,如果不加,编译过程会报类似以下错误:

undefined references to `c10::Error::Error(c10::SourceLocation, std::__cxx11::basic_string

参考链接:https://www.codeleading.com/article/29853511199/


二、多个输入和多个输出

  • 输入
    先定义一个std::vector<torch::jit::IValue>变量,然后逐个添加
// inputs
std::vector<torch::jit::IValue> inputs;

torch::jit::IValue cate = torch::ones(( 1, 1, 1 ));
std::cout << "cate: " << cate << std::endl;

torch::Tensor temp = torch::randn({ 1, 3, 11705 });
std::cout << "temp size: " << temp.sizes() << " temp 0: " << temp[0][0][0] << std::endl;
inputs.push_back(temp);
inputs.push_back(cate);
  • 输出
    先输出torch::jit::IValue结果,然后根据pytorch端的输出相应得做转变
// forward
torch::jit::IValue output = module.forward(inputs);
std::vector<torch::Tensor> outList = output.toTensorVector();   // it used to return [x1, x2, ...] from pytorch

auto tpl = output.toTuple();                                    // it used to return (x1, x2, ...) from pytorch
auto arm_loc = tpl->elements()[i].toTensor();

三、二维vector转tensor

我的数据是二维数组,可通过以下方式转换,其中torch::Tensor input_tensor = torch::from_blob(points.data(), { n, cols }).toType(torch::kDouble).clone();转出来数据不对,有大佬懂的可以指点一下。

// std::vector<std::vector<double>> to torch::jit::IValue
int cols = points[0].size();
int n = points.size();

torch::TensorOptions options = torch::TensorOptions().dtype(torch::kFloat32);
torch::Tensor input_tensor = torch::zeros({ n, cols }, options);
for (int i = 0; i < n; i++) {
    input_tensor.slice(0, i, i + 1) = torch::from_blob(points[i].data(), { cols }, options).clone();
}

注意: 一定要有clone()复制一份, 否则数组释放后相应数据也会释放,共享的是同一内存


四、mask索引转换

python C++
A[mask] torch::masked_select(A, mask)

问题
python某个算子转换过程中需要改写成C++,中间遇到有个转换是mask索引赋值相关的,python下类似A[mask] = B[mask],我在C++中改写为torch::masked_select(A, mask) = torch::masked_select(B, mask);,运行通过了,但是结果不对,排查后发现是A的值没有变化,最终采用A = torch::_s_where(mask, B, A);替换得到解决,相关代码如下:

  • failed

  • successed


五、常见切片操作

官方文档==>index

参考链接

官网API
libtorch 常用api函数示例
LibTorch对tensor的索引/切片操作:对比PyTorch
Tensor Index API

原文地址:https://www.cnblogs.com/xiaxuexiaoab/p/15567698.html