1. Lea el documento del sitio web oficial de Pytorch C ++ , instale el sistema operativo Linux de Ubuntu16.04 en la máquina virtual para construir el entorno y use el archivo MAKE para compilar, el código es conciso y fácil de leer.
sudo apt-get update
sudo apt-get install vim make cmake gcc g++ libnss3 tree git openssh-server openssh-client
2. Descargue el archivo de la biblioteca de cpu pytorch c ++ y descomprímalo, preste atención a la ruta del directorio, las necesidades de compilación de cmake
unzip libtorch-shared-with-deps-latest.zip
pwd
3. Instale vscode, enlace de descarga: linux vscode , descomprima y comience
sudo dpkg -i code_1.32.1-1552006243_amd64.deb
code
4. Cree un proyecto, estructura de directorios:
ai@ai-virtual-machine:~/pro/tb/day01_test_env_cpu$ tree
.
├── bin # cmake 编译输出的文件目录
├── CMakeLists.txt # cmake文件
├── main.cpp # 主程序
└── makefile # make编译CMakeLists.txt,代码简洁
main.cpp, código
#include <torch/script.h>
#include <ATen/ATen.h>
#include <iostream>
using namespace std;
using namespace at;
int main(int argc, const char* argv[])
{
at::Tensor a = at::ones({2,2}, at::kInt);
std::cout << a << std::endl;
std::cout << "ok" << std::endl;
return 0;
}
CMakeLists.txt, código
cmake_minimum_required(VERSION 3.0 FATAL_ERROR)
project(demo)
find_package(Torch REQUIRED)
add_executable(${PROJECT_NAME} main.cpp)
target_link_libraries(${PROJECT_NAME} "${TORCH_LIBRARIES}")
set_property(TARGET ${PROJECT_NAME} PROPERTY CXX_STANDARD 11)
makefile, código
.PHONY:all clean
PATH_BIN=bin
pytorch_lib=/home/ai/pro/tb/libtorch
all:
@cd ./$(PATH_BIN) && cmake -DCMAKE_PREFIX_PATH=$(pytorch_lib) .. && make
clean:
rm -rf $(PATH_BIN)
mkdir $(PATH_BIN)
Compilar, hacer
运 运, ./bin/demo
Enlace de descarga de código de ingeniería: https://download.csdn.net/download/wzhrsh/13206964