Installing PyTorch on MacBook Metal M1

After I brought my M1 MacBook Pro, PyTorch no longer supported GPU. Recently I saw that the Night build for PyTorch started supporting metal GPU. Since seeing that, I intended to install it and again start working on that platform. Finally yesterday I was able to install it. In the next few weeks I also intend to test performance for this build.

Pre-requisites

PyTorch needs at least Mac version 21.3 Monterey to install. You can check the version of Mac using the following command.

% system_profiler SPSoftwareDataType

Software:

    System Software Overview:

      System Version: macOS 13.0 (22A380)
      Kernel Version: Darwin 22.1.0
      Boot Volume: Macintosh HD
      Boot Mode: Normal
      Computer Name: Suvendra's xxxx
      User Name: xxxx
      Secure Virtual Memory: Enabled
      System Integrity Protection: Enabled
      Time since boot: 1 hour, 40 minutes

Next we need to ensure that Xcode is installed.

% xcode-select -p
/Library/Developer/CommandLineTools

### INSTALL if Needed ###
% xcode-select --install

Installation

For this we will create a virtual environment and then install. Installation command line can be found from PyTorch website.

Now that we have the command line, let’s start the install. I normally just install wheel as lot of these libraries support wheel build.

(torch) % pip install -U pip
(torch) % pip install wheel
(torch) % pip install --pre torch torchvision torchaudio --extra-index-url https://download.pytorch.org/whl/nightly/cpu

This should install quite a few libraries as follows.

Successfully installed certifi-2022.9.24 charset-normalizer-2.1.1 idna-3.4 mpmath-1.2.1 networkx-3.0b1 numpy-1.23.4 pillow-9.2.0 requests-2.28.1 sympy-1.11.1 torch-1.14.0.dev20221026 torchaudio-0.14.0.dev20221025 torchvision-0.15.0.dev20221026 typing-extensions-4.4.0 urllib3-1.26.12 

Testing GPU support

Now that the installation is done, let’s see if the support for GPU is available.

(torch) % python
>>> import torch;
>>> torch.__version__
'1.14.0.dev20221026'
>>> print(torch.backends.mps.is_available())
True
>>> print(torch.backends.mps.is_built())
True

If the commands on line 5 and line 7 return True, PyTorch is capable of using GPU on this machine.

Conclusion

That completes the installation of PyTorch. Overall the entire process did not take too much time. I will next try to build a model for PyTorch in a different blog to test this out. Ciao for now!