Skip to main content

PyTorch for Apple Silicon

PyTorch 1.12 includes GPU acceleration on Apple Silicon.

We will install it and verify it is using GPU acceleration. This blog post also serve as a documentation to reproduce a runtime environment for machine learning.

The test laptop:

  • MacBook Pro (14-inch, 2021).
    • Apple M1 Pro
    • 16 GB memory
  • macOS Monterey 12.6.

Steps #

  1. Install pyenv and pyenv-virtualenv.

  2. Install python 3.9.13 in a virtual environment.

pyenv install 3.9.13
pyenv virtualenv 3.9.13 pytorch1.12.1-apple
  1. Install PyTorch 1.12.1
pyenv activate pytorch1.12.1-apple
pip install torch torchvision torchaudio
  1. Verify the PyTorch install per its documentation.
import torch
x = torch.rand(5, 3)
print(x)

The output should be something like:

tensor([[0.5031, 0.1897, 0.0958],
        [0.2736, 0.8608, 0.6307],
        [0.7279, 0.7578, 0.9858],
        [0.3378, 0.8042, 0.6693],
        [0.2946, 0.8163, 0.2774]])
  1. Verify that PyTorch can access the GPU.
import torch
import math
# this ensures that the current MacOS version is at least 12.3+
print(torch.backends.mps.is_available())
# this ensures that the current current PyTorch installation was built with MPS activated.
print(torch.backends.mps.is_built())

Reference: https://towardsdatascience.com/installing-pytorch-on-apple-m1-chip-with-gpu-acceleration-3351dc44d67c

  1. Install an opinated MLops stack.
pip install \
      jupyterlab \
      matplotlib \
      nltk \
      opencv-python-headless \
      pandas \
      pytorch-lightning \
      scikit-learn \
      scikit-image \
      seaborn \
      tensorboard