개발로 하는 개발

Using PyTorch GPU acceleration on Mac Silicon M1 pro 본문

Tips

Using PyTorch GPU acceleration on Mac Silicon M1 pro

jiwon152 2024. 1. 8. 23:36

Make a venv with the local python > 3.8

python -m venv torchaccel

 

Activate the venv

source torchaccel/bin/activate

 

Get the installation code from here

Get this image

Run it on the (venv) shell. I used Pip.

 

# MPS acceleration is available on MacOS 12.3+
pip3 install torch torchvision torchaudio

 

To check if torch is installed, in python, run

import torch
x = torch.rand(5, 3)
print(x)

 

 you may check it from the official website too.

 

You must modify the main code like this to use 'mps' as a torch device.

# in the main python code,
# Declaration of device must be like this
device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')
# Change it to this
device = torch.device('cuda:0' if torch.cuda.is_available() else ('mps' if torch.backends.mps.is_available() else 'cpu'))

 

You are good to go!

If you want to check if it is installed and torch can find 'mps', 

In the venv, write "python"

# In the shell, write "python" to activate python. 
# Then, write down this code. It would print 'mps'
import torch
device = torch.device('cuda:0' if torch.cuda.is_available() else ('mps' if torch.backends.mps.is_available() else 'cpu'))
print(device)