PyTorch on Apple Silicon Mac — Easiest Steps with Code Snippets

YASH GUPTA
2 min readJul 19, 2023

--

Introduction:

Are you an owner of an Apple Silicon Mac (M1, M2, M1 Pro, M1 Max, M1 Ultra) and eager to dive into the world of data science and machine learning using PyTorch? Look no further! In this blog, we’ll guide you through the easiest steps to set up your machine for PyTorch with code snippets to make the process a breeze. Let’s get started! (Github)

https://twitter.com/YASHGUPTATECH/status/1680301712064610304

Step 1: Install Homebrew and Miniforge3

First, let’s install Homebrew, the package manager that sets up essential tools on your Mac. Open the Terminal and run the following command:

/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"

Next, download and install Miniforge3 (Conda installer) for macOS arm64 chips (M1, M2, M1 Pro, M1 Max, M1 Ultra) from GitHub. Run the following commands:

chmod +x ~/Downloads/Miniforge3-MacOSX-arm64.sh
sh ~/Downloads/Miniforge3-MacOSX-arm64.sh

Step 2: Create and Activate a PyTorch Environment

Let’s create a dedicated environment for PyTorch. In the Terminal, execute the following commands:

mkdir pytorch-test
cd pytorch-test
conda create --prefix ./env python=3.8
conda activate ./env

Step 3: Install PyTorch and Required Packages

With the environment set, it’s time to install PyTorch 1.12.0+ with GPU acceleration and other data science packages. Run these commands:

pip3 install torch torchvision torchaudio
conda install jupyter pandas numpy matplotlib scikit-learn tqdm

Step 4: Verify Your Setup

Let’s test if everything is working as expected. Start a Jupyter Notebook with:

jupyter notebook

In a new notebook cell, run the following Python code:

import torch
import numpy as np
import pandas as pd
import sklearn
import matplotlib.pyplot as plt

print(f"PyTorch version: {torch.__version__}")
device = "mps" if torch.backends.mps.is_available() else "cpu"
print(f"Using device: {device}")
If everything goes successfully expected output would be like this
If everything was successful, then expected output would be like this

Step 5: Embrace the Power of Apple Silicon GPU

To take advantage of your Apple Silicon GPU, you can use the PyTorch device name `”mps”` with `.to(“mps”)`. For example:

import torch

# Set the device
device = "mps" if torch.backends.mps.is_available() else "cpu"

# Create data and send it to the device
x = torch.rand(size=(3, 4)).to(device)
x

Conclusion:

Congratulations! You’ve successfully set up PyTorch on your Apple Silicon Mac, ready to embark on exciting data science and machine learning projects. Armed with the power of your Apple Silicon GPU, you’re all set to explore the world of AI. Happy coding! 🚀🍏 #PyTorch #AppleSilicon #DataScience #MachineLearning

--

--

YASH GUPTA
YASH GUPTA

Responses (1)