我需要将一行一个张量 (in c++ API)复制到另一个张量的某个部分中,开始和结束索引可用的形式。在 C++ 中,我们可以使用类似的东西:
int myints[] = {10, 20, 30, 40, 50, 60, 70};
std::vector<int> myvector(18);
std::copy(myints, myints + 3, myvector.begin() + 4);
Run Code Online (Sandbox Code Playgroud)
从第四个索引开始将三个值复制myints到 into 中myvector。我想知道libtorch(即 C++)中是否有类似的 API ?
按照官方 PyTorch教程,我用 Python 创建了模型,通过跟踪将其转换为 Torch 脚本,并将脚本模块保存到文件中.pt。加载模型和 CMakeLists 的 C++ 代码与教程中的代码相同。
我下载了LibTorch 1.3(稳定版,Windows,无CUDA,发布版)并解压,所以我的目录结构是:
\n\n\n\xe2\x94\x82\n\xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80artifact\n\xe2\x94\x82 Traced_resnet_model.pt\n\xe2\ x94\x82\n\xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80cmakeapp\n\xe2\x94\x82\xe2\x94\x82 CMakeLists.txt\n\xe2 \x94\x82 \xe2\x94\x82 示例-app.cpp\n\xe2\x94\x82 \xe2\x94\x82 \n\xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80\ xe2\x94\x80libtorch\n\xe2\x94\x82 \xe2\x94\x82 构建哈希 \n\xe2\x94\x82 \xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80\xe2 \x94\x80bin\n\xe2\x94\x82 \xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80cmake\n\xe2\x94\x82 \xe2\x94\x9c \xe2\x94\x80\xe2\x94\x80\xe2\x94\x80include\n\xe2\x94\x82 \xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80lib \n\xe2\x94\x82 \xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80share\n\xe2\x94\x82 \xe2\x94\x94\xe2\x94 \x80\xe2\x94\x80\xe2\x94\x80test\n\n\n\n
我安装了 Visual Studio 2019,并将 CMake 作为组件安装,因此我运行了 VS2019 的开发人员命令提示符并cd运行到项目目录 (cmakeapp)。
根据指南,我运行了以下命令来构建应用程序:
\n\nmkdir build\ncd build\ncmake -DCMAKE_PREFIX_PATH=..\\libtorch ..\nmake\nRun Code Online (Sandbox Code Playgroud)\n\nCMake 似乎成功了,除了一些警告:
\n\nCMake Warning (dev) at D:/dox/projects/AI/torchscript/libtorch/share/cmake/Caffe\n2/public/utils.cmake:57 (if):\n Policy CMP0054 is not set: Only interpret if() arguments …Run Code Online (Sandbox Code Playgroud) 我在Libtorch(Pytorch C++ 前端)中找不到与我的 Python Pytorch代码等效的 C++ 调用。
根据我的搜索(Pytorch Discuss),我的代码尚不存在文档。我想知道是否有人可以指导我以下几部分(如下)。
我对 Libtorch C++ 发生较多崩溃(错误使用)的地方进行了删减。
import torch as th
th.set_grad_enabled(False)
...
X = th.zeros((nobs, 3+p), device=dev, dtype=th.float32)
y = th.tensor(indata, device=dev, dtype=th.float32)
diffilter = th.tensor([-1., 1.], device=dev, dtype=th.float32).view(1, 1, 2)
dy = th.conv1d(y.view(1, 1, -1), diffilter).view(-1)
z = dy[p:].clone()
...
# X matrix
X[:, 0] = 1
X[:, 1] = th.arange(p+1, n)
X[:, 2] = y[p:-1]
...
# master X
Xm = th.zeros((nobsadf, 3+p), device=th.device('cpu'), dtype=th.float32) …Run Code Online (Sandbox Code Playgroud) 这是非常基本的:我通常使用 Eigen3 进行数学运算,但需要使用 libtorch 进行网络前向传递。现在我想用torch::tensor我的 Eigen3 (或纯 C++ )中的数据填充array,但没有for循环。我怎样才能做到这一点?
这是带有循环的解决方案:
Eigen::Matrix<double, N, 1> inputEigen; // previously initialized
torch::Tensor inputTorch = torch::ones({1, N}); // my torch tensor for the forward pass
for (int i = 0; i < N; i++) {
inputTorch[0][i] = inputEigen[i]; // batch size == 1
}
std::vector<torch::jit::IValue> inputs;
inputs.push_back(inputTorch);
at::Tensor output = net.forward(inputs).toTensor();
Run Code Online (Sandbox Code Playgroud)
目前效果很好,但N可能会变得非常大,我只是在寻找一种方法来直接torch::tensor使用以前使用过的 C++设置我的底层数据array
我使用 LibTorch (PyTorch C++ API) 用 C++ 进行编码。在这里,我传递了 Predicted_value 和 target_value,它们都是大小为 {1, 1} 的 torch::Tensor。
torch::Tensor loss = torch::nll_loss(predicted_value, target_value);
Run Code Online (Sandbox Code Playgroud)
当我尝试评估上述内容时,出现以下错误:
0.4997 [ Variable[CPUFloatType]{1,1} ] # printout of predicted_value
-0.5392 [ Variable[CPUFloatType]{1,1} ] # printout of target_value
terminate called after throwing an instance of 'c10::Error'
what(): Expected object of scalar type Long but got scalar type Float for argument #2 'target' in call to _thnn_nll_loss_forward (checked_dense_tensor_unwrap at ../../aten/src/ATen/Utils.h:84)
Run Code Online (Sandbox Code Playgroud)
我尝试搜索如何将 float 类型张量转换为 long 类型张量,但只能找到 Python 的文档。非常感谢解决这个问题的建议!
我正在尝试在 Raspberry PI 上使用 libtorch 构建 C++ 程序。该程序在 Ubuntu 上运行,但在 Raspberry 上构建时出现以下错误:
\nerror: use of deleted function \xc3\xa2\xe2\x82\xac\xcb\x9cvoid torch::jit::script::Module::operator=(const torch::jit::script::Module&)\xc3\xa2\xe2\x82\xac\xe2\x84\xa2\nIn file included from /usr/include/torch/csrc/jit/ir.h:18,\n from /usr/include/torch/csrc/jit/tracer.h:9,\n from /usr/include/torch/csrc/autograd/generated/variable_factories.h:8,\n from /usr/include/torch/csrc/api/include/torch/types.h:7,\n from /usr/include/torch/script.h:3,\n from /tmp/tmp.k6618dczxt/src/../include/suvoNet.h:26,\n from /tmp/tmp.k6618dczxt/src/../include/classifier.h:17,\n from /tmp/tmp.k6618dczxt/src/classifier.cpp:11:\n/usr/include/torch/csrc/jit/script/module.h:319:3: note: declared here\n TH_DISALLOW_COPY_AND_ASSIGN(Module);\nRun Code Online (Sandbox Code Playgroud)\n这是崩溃的代码:
\nMyClass::MyClass() {\n try {\n // Deserialize the ScriptModule from a file using torch::jit::load().\n network = torch::jit::load(MODEL_FILE);\n }\n catch (const c10::Error& e) {\n std::cerr << "Error loading the model\\n";\n exit(-1);\n }\n}\n\nRun Code Online (Sandbox Code Playgroud)\n已network声明为私有 …
我正在使用 PyTorch 的 C++ API 开发机器学习系统 ( libtorch)。
我最近一直在做的一件事是研究libtorch. 通过我的研究,我了解到 Torch 在 CPU 上使用两种并行化方式:
inter-op并行化intra-op并行化我的主要问题是:
inter-op并行性我知道我可以使用该函数指定用于并行性的线程数intra-op(根据我的理解,这是使用openmp后端执行的)torch::set_num_threads(),当我监视模型的性能时,我可以清楚地看到它使用了我指定的线程数使用这个函数,我可以通过改变intra-op线程数看到明显的性能差异。
还有另一个函数torch::set_num_interop_threads(),但似乎无论我指定多少个互操作线程,我都看不到性能有任何差异。
现在我已经阅读了这篇 PyTorch 文档文章,但我仍然不清楚如何利用互操作线程池。
文档说:
PyTorch 使用单个线程池来实现操作间并行性,该线程池由应用程序进程中分叉的所有推理任务共享。
我对这部分有两个问题:
interop线程,或者 torch 是否在内部以某种方式为我完成它?interop?在python示例中,他们使用模块fork中的函数torch.jit,但我在 C++ API 中找不到类似的东西。
我正在为 pytorch 编写一个 C++ 扩展,其中我需要通过索引访问张量的元素,并且还需要将元素转换为标准 C++ 类型。这是一个简短的例子。假设我有一个二维张量a,我需要访问a[i][j]它并将其转换为浮点数。
#include <torch/extension.h>\n\nfloat get(torch::Tensor a, int i, int j) {\n return a[i][j];\n}\nRun Code Online (Sandbox Code Playgroud)\n上面的内容被放入一个名为tensortest.cpp. 在另一个文件中setup.py我写
from setuptools import setup, Extension\nfrom torch.utils import cpp_extension\n\nsetup(name=\'tensortest\',\n ext_modules=[cpp_extension.CppExtension(\'tensortest_cpp\', [\'tensortest.cpp\'])],\n cmdclass={\'build_ext\': cpp_extension.BuildExtension})\nRun Code Online (Sandbox Code Playgroud)\n当我运行python setup.py install编译器时报告以下错误
running install\nrunning bdist_egg\nrunning egg_info\ncreating tensortest.egg-info\nwriting tensortest.egg-info/PKG-INFO\nwriting dependency_links to tensortest.egg-info/dependency_links.txt\nwriting top-level names to tensortest.egg-info/top_level.txt\nwriting manifest file \'tensortest.egg-info/SOURCES.txt\'\n/home/trisst/.local/lib/python3.8/site-packages/torch/utils/cpp_extension.py:335: UserWarning: Attempted to use ninja as the BuildExtension backend but we could not find …Run Code Online (Sandbox Code Playgroud) 我正在调试这个错误:
Unhandled exception at 0x00007FFA0B7D3E49 in AudioPluginHost.exe: Microsoft C++ exception: c10::Error at memory location 0x00000044B4DABDB0.
Run Code Online (Sandbox Code Playgroud)
我正在尝试训练一个神经网络,主要基于这个例子。
这就是我正在做的:
torch::Tensor TrainingSample::getRatingTensor()
{
c10::DeviceType deviceType;
if (torch::cuda::is_available()) {
deviceType = torch::kCUDA;
}
else {
deviceType = torch::kCPU;
}
float ratingArray[1][3] = { {0} };
ratingArray[0][(int)waveform.rating] = 1;
ostringstream os0;
for (int i = 0;i<(sizeof(ratingArray[0])/sizeof(ratingArray[0][0]));i++) {
os0 << ratingArray[0][i];
os0 << ",";
}
DBG("ratingArray: \n" + os0.str());
auto options = torch::TensorOptions().dtype(torch::kFloat32).device(deviceType);
torch::Tensor ratingTensor = torch::from_blob(ratingArray, { 1, 3 }, options);
ostringstream os1; …Run Code Online (Sandbox Code Playgroud) 在带有 PyTorch 的 Python 中,如果你有一个数组:
torch.linspace(0, 10, 10)
你可以只使用前三个元素,例如
reduced_tensor = torch.linspace(0, 10, 10)[:4]。
C++/libtorch 中是否有类似于数组切片的模拟[:]?如果没有,我怎样才能轻松实现这一目标?
下面是我想要做的伪代码。我已经知道如何将张量移动到 GPU ( .cuda())...
但不知道如何使用 GPU 指针来创建新的张量。有什么方法我错过了吗?
我不想复制devPtr回主机端,而只是用指针制作 GPU 张量。
int main(void) {
float* devPtr;
cudaMalloc((void**)&devPtr, sizeof(float)*HOSTDATA_SIZE);
cudaMemcpy(devPtr, hostData, sizeof(float)*HOSTDATA_SIZE, cudaMemcpyHostToDevice);
torch::Tensor inA = /* make Tensor with devPtr which is already in GPU */;
torch::Tensor inB = torch::randn({1, 10, 512, 512}).cuda();
torch::Tensor out = torch::matmul(inA, inB);
std::cout << out << std::endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud) 我正在尝试在项目中使用 libtorch、qt 小部件、点云库(pcl)和 opencv。对于这个项目,我使用 cmake 列表。问题是,当我一起使用所有四个库时,libtorch 会抛出错误。如果我使用 libtorch、opencv 和 qt,一切都工作正常,如果我使用 pcl qt 和 opencv,一切也工作正常。我收到的错误如下所列:
\n/libtorch/include/torch/csrc/jit/api/object.h: In member function \xe2\x80\x98size_t torch::jit::Object::num_slots() const\xe2\x80\x99:\n/libtorch/include/torch/csrc/jit/api/object.h:173:28: error: expected unqualified-id before \xe2\x80\x98(\xe2\x80\x99 token 173 return _ivalue()->slots().size();\n/libtorch/include/ATen/core/ivalue_inl.h: In member function \xe2\x80\x98c10::intrusive_ptr c10::IValue::toCustomClass() const &\xe2\x80\x99:\n/libtorch/include/ATen/core/ivalue_inl.h:1642:3: error: expected unqualified-id before \xe2\x80\x98(\xe2\x80\x99 token\n1642 | TORCH_CHECK(\n/libtorch/include/ATen/core/ivalue_inl.h: In member function \xe2\x80\x98c10::intrusive_ptr c10::IValue::toCustomClass() &&\xe2\x80\x99:\n/libtorch/include/ATen/core/ivalue_inl.h:1624:3: error: expected unqualified-id before \xe2\x80\x98(\xe2\x80\x99 token\n1624 | TORCH_CHECK(\n| ^~~~~~~~~~~\n/libtorch/include/ATen/core/ivalue_inl.h:1419:36: error: expected unqualified-id before \xe2\x80\x98)\xe2\x80\x99 token\n1419 | const std::vector& slots() const {\nRun Code Online (Sandbox Code Playgroud)\n有谁知道为什么 libtorch 会抛出这些错误?
\n我正在尝试从我制作的库中创建一个测试可执行文件。我们将它们命名为 lib1 和 lib2。lib1 的构建和测试都很好。lib2 的构建也没有任何问题。但是,每当我尝试将 lib2 与其测试可执行文件(即使用 lib2 的示例程序)链接时,我都会收到以下错误:
usr/bin/ld: CMakeFiles/Lib2_Test.dir/Lib2_Test.cpp.o: in function `main':
Lib2_Test.cpp:(.text+0xf3): undefined reference to `Lib2::Lib2(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, int, int)'
/usr/bin/ld: Lib2_Test.cpp:(.text+0x3f5): undefined reference to `Lib2::Evaluate(bool&, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >&, float&, cv::Mat&, cv::Mat&, bool)'
collect2: error: ld returned 1 exit status
make[2]: *** [CMakeFiles/Lib2_Test.dir/build.make:130: Lib2_Test] Error 1
make[1]: *** [CMakeFiles/Makefile2:76: CMakeFiles/Lib2_Test.dir/all] Error 2
make: *** [Makefile:130: all] Error 2
Run Code Online (Sandbox Code Playgroud)
readelf -d我尝试使用命令查看标题ldd,这两个库似乎都有所有必要的引用。但是 lib1 没有任何问题,而 lib2 在链接到使用它的可执行文件时会生成未引用的相关错误。
下面是我为它们制作的 cmakeList,后来我还包含了readelf …