Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save ludwig/e814b9c72183b313a4bbe5c13ffd43f5 to your computer and use it in GitHub Desktop.
Save ludwig/e814b9c72183b313a4bbe5c13ffd43f5 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-2021.11-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 py39_torch python=3.9 # you can choose the name of the environment and the python version
  • Activate the environment
conda activate py39_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 ninja 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-cuda90 # or [magma-cuda92 | magma-cuda100 ] 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/py39_torch/lib/python3.9/site-packages/torch" ..
make
  • Run the example
./main

Thats it! Hope it helped you.

cmake_minimum_required(VERSION 3.10 FATAL_ERROR)
project(example)
find_package(Torch REQUIRED)
add_executable(main main.cpp)
target_link_libraries(main ${TORCH_LIBRARIES})
set_property(TARGET main PROPERTY CXX_STANDARD 14)
#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