如何在 windows 配置 libtorch c++ 前端库?

如何在 windows 配置 libtorch c++ 前端库?

下载 pytorch 已经编译好的库:
此库不带 gpu,主要方便演示。支持 win7 win10 系统。
下载地址:https://download.pytorch.org/libtorch/cpu/libtorch-win-shared-with-deps-latest.zip


1. cmake 配置

1.1 新建 CMakeLists.txt 并添加以下内容:
# 设置 cmake 版本限制
cmake_minimum_required(VERSION 3.0 FATAL_ERROR)

# 项目名称
project(libtorch-app)

# 设置 libtorch-win-shared-with-deps-latest 目录,主要让 find_package 可以找到 Torch 的 TorchConfig.cmake 配置文件以及其他相关 Config.cmake 配置文件

set(CMAKE_PREFIX_PATH "./libtorch-win-shared-with-deps-latest")

find_package(Torch REQUIRED)

add_executable(libtorch-app main.cpp)
target_link_libraries(libtorch-app "${TORCH_LIBRARIES}")
set_property(TARGET libtorch-app PROPERTY CXX_STANDARD 11)
1.2 在 CMakeLists.txt 同级目录新建一个 main.cpp 文件,添加以下内容:
#include <torch/torch.h>
#include <iostream>
int main()
{
    torch::Tensor tensor = torch::rand({ 9,9 });
    std::cout << tensor << std::endl;
    return 0;
}
1.3 然后在 CMakeLists.txt 同级目录下打开一个命令行(按住 Shift + 鼠标右键即可)输入以下命令:

cmake -DCMAKE_BUILD_TYPE=Release -G "Visual Studio 14 Win64"

执行完以上命令后生成 libtorch-app.sln 解决方案文件,打开编译即可。


2. 手动配置(仅适用于CPU,GPU需要自行另外添加相关依赖)

新建一个属性页并添加当当前配置文件中

2.1. 在 C/C++->常规->附加包含目录里面添加以下内容并开启多处理器编译:
$(SolutionDir)3rdparty\libtorch-win-shared-with-deps-latest\include\torch\csrc\api\include
$(SolutionDir)3rdparty\libtorch-win-shared-with-deps-latest\include
2.2. 在 连接器->输入->附加依赖项里面添加以下内容:
$(SolutionDir)3rdparty\libtorch-win-shared-with-deps-latest\lib\torch.lib
$(SolutionDir)3rdparty\libtorch-win-shared-with-deps-latest\lib\caffe2.lib
$(SolutionDir)3rdparty\libtorch-win-shared-with-deps-latest\lib\c10.lib
2.3. 在 调试->环境 里面添加环境变量

path=%path%;$(SolutionDir)3rdparty\libtorch-win-shared-with-deps-latest\lib

2.4 新建一个 main.cpp 文件,添加以下内容并使用 x64 模式编译即可:
#include <torch/torch.h>
#include <iostream>
int main()
{
    torch::Tensor tensor = torch::rand({ 9,9 });
    std::cout << tensor << std::endl;
    return 0;
}

输出一个随机数值9x9矩阵:
`0.2407 0.9294 0.5167 0.3774 0.9841 0.6530 0.9825 0.5814 0.4903 0.8882 0.5111 0.7414 0.7563 0.1666 0.2542 0.2624 0.0668 0.4328 0.0481 0.4880 0.6299 0.5140 0.0379 0.9187 0.3033 0.1510 0.6705 0.1983 0.6113 0.2893 0.0700 0.8585 0.3588 0.3891 0.0551 0.0458 0.7738 0.0797 0.0611 0.1781 0.3898 0.0238 0.0361 0.3905 0.2005 0.5774 0.5769 0.6275 0.3511 0.9609 0.3415 0.7188 0.5650 0.5670 0.0828 0.2139 0.5793 0.4089 0.5725 0.3938 0.8250 0.2695 0.6470 0.4106 0.3609 0.9982 0.8789 0.0134 0.8454 0.3880 0.0937 0.9598 0.1523 0.9423 0.2989 0.6404 0.0997 0.2817 0.0706 0.1867 0.1980 Variable[CPUFloatType]{9,9} ]

转载于:https://www.cnblogs.com/cheungxiongwei/p/10689483.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值