一 编译torch
我这是用torch==2.3.1,torchvision==0.18.1,注意torch和torchvision的版本要对应上。
1. 克隆源码
git clone --recursive https://github.com/pytorch/pytorch.git
cd pytorch
git checkout v2.3.1 #跳转到你指定的版本
git submodule sync
git submodule update --init --recursive
2. 编译安装
我这里是安装到/opt/libtorch下,没有GPU加速,编译选项按自己的需求进行修改。
cd pytorch
mkdir build && cd build
cmake -D CMAKE_BUILD_TYPE=RELEASE -D CMAKE_INSTALL_PREFIX=/opt/libtorch -DCMAKE_CXX_STANDARD=17 -D CMAKE_CXX_STANDARD_REQUIRED=ON -D USE_CUDA=OFF -D USE_CUDNN=OFF -D USE_OPENCV=ON -D BUILD_CAFFE2_MOBILE=OFF -D BUILD_PYTHON=OFF -D BUILD_CAFFE2_OPS=OFF -D BUILD_TEST=OFF -D USE_TBB=OFF ..
make -j4
sudo make install
3. 报错解决
torch的编译是需要依赖python环境的,缺啥模块就安装啥模块,下面的两个模块是我碰到需要安装的
pyyaml typing_extensions
4. 测试
4.1 测试程序,example-torch.cpp
#include <torch/torch.h>
#include <iostream>
int main() {
torch::Tensor tensor = torch::rand({2, 3})