LibTorch


LibTorch源码编译

Build from source

Step 1 Download pytorch

git clone --recursive https://github.com/pytorch/pytorch
cd pytorch
git submodule update --init --recursive

Step 2 Installing dependencies

  • CMake version > 3.18
  • Python version > 3.8
  • C++ 17
conda create -n libtorch python=3.9
conda activate libtorch
conda install astunparse numpy ninja pyyaml mkl mkl-include setuptools cmake cffi typing_extensions future six requests dataclasses

Step 3 Starting compiling

mkdir pytorch-build
cd pytorch-build
cmake -DBUILD_SHARED_LIBS:BOOL=ON -DCMAKE_BUILD_TYPE:STRING=Release -DPYTHON_EXECUTABLE:PATH=`which python3` -DCMAKE_INSTALL_PREFIX:PATH=../pytorch-install ../
cmake --build . -j8 --target install

Step 4 Examples

  • 文件结构
$ tree ../example-app/ -L 1
../example-app/
├── build
├── CMakeLists.txt
└── example-app.cpp

1 directory, 2 files
  • example-app.cpp
#include <torch/torch.h>
#include <iostream>

int main() {
          torch::Tensor tensor = torch::rand({2, 3}); //生成大小为2*3的随机数矩阵
          std::cout << tensor << std::endl;           //标准输出流打印至屏幕
}
  • CMakeLists.txt
    • 注意 需要c++ 17 set_property(TARGET example-app PROPERTY CXX_STANDARD 17)
cmake_minimum_required(VERSION 3.0 FATAL_ERROR)
project(example-app)

find_package(Torch REQUIRED)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${TORCH_CXX_FLAGS}")

add_executable(example-app example-app.cpp)
target_link_libraries(example-app "${TORCH_LIBRARIES}")
set_property(TARGET example-app PROPERTY CXX_STANDARD 17)
  • 命令行
    • /path/to/pytorch-install 为libtorch编译成功后的位置
cd example-app
mkdir build && cd build
cmake -DCMAKE_PREFIX_PATH=/path/to/pytorch-install ..
make 
  • 输出结果
$ ./example-app 

 0.4473  0.6516  0.0226
 0.3360  0.1509  0.0269
[ CPUFloatType{2,3} ]

Script

  • libtorch_compile.sh
# step 1
git clone --recursive https://github.com/pytorch/pytorch
cd pytorch
git submodule update --init --recursive

# step 2
conda create -n libtorch python=3.9
conda activate libtorch
conda install astunparse numpy ninja pyyaml mkl mkl-include setuptools cmake cffi typing_extensions future six requests dataclasses

# step 3
mkdir pytorch-build
cd pytorch-build
cmake -DBUILD_SHARED_LIBS:BOOL=ON -DCMAKE_BUILD_TYPE:STRING=Release -DPYTHON_EXECUTABLE:PATH=`which python3` -DCMAKE_INSTALL_PREFIX:PATH=../pytorch-install ../
cmake --build . -j8 --target install

Reference


文章作者: Lee Jet
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 Lee Jet !
评论
  目录