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-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, here
conda install pytorch-cpu torchvision-cpu -c pytorch

Install from Source

Sometime 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.

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})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment