Installing PyTorch

Tim Stuart 2020-04-05 2 minute read

See the PyTorch website: https://pytorch.org/tutorials/

1. Install miniconda

I find minoconda3 is the easiest way to get everything installed and working for pytorch. Install the python 3.7 64 bit linux version from here:

https://docs.conda.io/en/latest/miniconda.html

2. Create a conda environment

It’s a good idea to use a separate environment for different projects. Create a new conda environment for deep learning stuff:

conda create --name cnn

3. Activate the conda environment

conda activate cnn

4. Install python packages in conda environment

Install pytorch and its dependencies

conda install pytorch torchvision -c pytorch

Install jupyterlab:

conda install -c conda-forge jupyterlab

5. Setting up CUDA

Using a GPU with pytorch requires an NVIDIA GPU and the CUDA toolkit installed. Follow instructions here to get the CUDA toolkit installed: CUDA Toolkit 10.2 Download | NVIDIA Developer

6. Configuring Jupyter

We need to link the jupyter kernelspec to the conda environment we created. The configuration for available jupyter kernels is stored in ~/.local/share/jupyter/kernels. To create a new kernel for jupyter, create a directory within the kernels directory called cnn: ~/.local/share/jupyter/kernels/cnn. Within this directory create a file called kernel.json containing the following (change path for your user account):

{
 "argv": [
  "/home/stuartt/miniconda3/envs/cnn/bin/python",
  "-m",
  "ipykernel_launcher",
  "-f",
  "{connection_file}"
 ],
 "display_name": "CNN",
 "language": "python"
}

This will allow you to select the python installation created by your conda environment as a drop-down in the new notebook menu in jupyter.

7. Running jupyter lab remotely

You will need to launch jupyter on the remote server and set up ssh tunnelling on your local computer. It’s a good idea to start jupyter in a GNU screen so that you can close your ssh session and keep the notebook active.

On the remote server:

# start a screen
screen -S torch
# activate environment
conda activate cnn
# can cd to wherever you want to start the notebook from
# start jupyter
jupyter lab --no-browser --port=8889

On your local machine:

ssh -f <remote-address> -L 8889:localhost:8889 -N

8. Verify that everything works

Navigate to http://localhost:8889/lab and you should see jupyterlab. Open a new ipython notebook using the conda env and run the following code:

import torch
torch.cuda.is_available()

Should see True.