Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save ghrua/b6c7c8394fbb8bd0f17d272e1d878e3e to your computer and use it in GitHub Desktop.
Save ghrua/b6c7c8394fbb8bd0f17d272e1d878e3e to your computer and use it in GitHub Desktop.

PyTorch C++ API Ubuntu Installation Guide

The best way to get a clean installation of PyTorch, is to install the pre-compiled binaries from the Anaconda distribution. Therefore, we need to setup Anaconda first.

Step 1: Install Anaconda

  • Go to the download section and download your desired Anaconda version for Linux

  • Run the downloaded shell script and follow the install instruction, do
cd ~/Downloads
sh Anaconda3-2018.12-Linux-x86_64.sh # actual name depends on your download

Step 2: Setup an Environment

  • To keep things clean, now setup an environment for Anaconda, do
conda create --name py37_torch python=3.7 # you can choose the name of the environment and the python version
  • Activate the environment
conda activate py37_torch

Step 3: Install PyTorch

There are two different ways on how to proceed.

Install pre-compiled Binaries

  • Go to pytorch.org and choose your desired settings like so

  • Run the proposed command, and make sure your environment is activated
conda install pytorch-cpu torchvision-cpu -c pytorch

Install from Source

Sometimes you want to compile from source, due to specific dependencies for example. You can look up what to do here. The main steps are

  • Get dependencies
conda install numpy pyyaml mkl mkl-include setuptools cmake cffi typing
  • In case you want to use CUDA on a GPU, otherwise you can skip
# Add LAPACK support for the GPU if needed
conda install -c pytorch magma-cuda92 # or [magma-cuda80 | magma-cuda91] depending on your cuda version
  • Clone PyTorch from GitHub
git clone --recursive https://github.com/pytorch/pytorch
cd pytorch
  • Install PyTorch, make sure your environment is activated
export CMAKE_PREFIX_PATH=${CONDA_PREFIX:-"$(dirname $(which conda))/../"}
python setup.py install

Step 4: Link against libtorch.so

Great you came this far, now lets see if everything worked well. Here is a minimal example, on how to link against the C++ API of Pytorch.

  • Build the example, the path depends on your installation. If you followed the previous steps, it should be
mkdir build
cd build
cmake -DCMAKE_PREFIX_PATH=${HOME}/anaconda3/envs/py37_torch/lib/python3.7/site-packages/torch" ..
make
  • Run the example
./main

Thats it! Hope it helped you.

cmake_minimum_required(VERSION 3.10 FATAL_ERROR)
project(example)
set(CMAKE_CXX_STANDARD 11)
find_package(Torch REQUIRED)
add_executable(main main.cpp)
target_link_libraries(main ${TORCH_LIBRARIES})
#include <torch/torch.h>
int main()
{
torch::Tensor tensor = torch::zeros({2, 2});
std::cout << tensor << std::endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment