Pytorch Environment on Apple Silicon
Anaconda
CLICK HERE to install anaconda.
Update anaconda to the latest version via
conda update anaconda
.
conda -V
to show your anaconda version. My version is
conda 4.13.0
.
Pytorch
create new environment
conda create -n <environment name> python=3.9
change environment
conda activate <environment name>
install pytorch
conda install -c pytorch pytorch
PyTorch 1.12 supports GPU acceleration on Apple Silicon now.
Test pytorch
show pytorch version
1
2
3
4
5
6
7python
Python 3.9.12 (main, Jun 1 2022, 06:36:29)
[Clang 12.0.0 ] :: Anaconda, Inc. on darwin
Type "help", "copyright", "credits" or "license" for more information.
>> import torch
>> torch.__version__
'1.12.0'test code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46import torch
import torch.nn as nn
import torch.nn.functional as F
import time
from tqdm import tqdm
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.conv1 = nn.Conv2d(3, 64, 3)
self.conv2 = nn.Conv2d(64, 128, 3)
self.conv3 = nn.Conv2d(128, 256, 3)
self.fc1 = nn.Linear(256, 128)
self.fc2 = nn.Linear(128, 56)
self.fc3 = nn.Linear(56, 10)
self.pool = nn.MaxPool2d(2, 2, 1)
self.global_pool = nn.AdaptiveAvgPool2d(1)
self.act = nn.ReLU()
def forward(self, x):
x = self.conv1(x); x = self.act(x); x = self.pool(x)
x = self.conv2(x); x = self.act(x); x = self.pool(x)
x = self.conv3(x); x = self.act(x); x = self.pool(x)
x = self.global_pool(x)
x = x.view(x.size(0), -1)
x = self.fc1(x); x = self.act(x)
x = self.fc2(x); x = self.act(x)
x = self.fc3(x)
x = torch.softmax(x, dim=1)
return x
def main():
net = Net()
x = torch.randn(8, 3, 128, 128)
# uncomment below to use M1 GPU
# net = net.to('mps')
# x = x.to('mps')
t0 = time.time()
for i in tqdm(range(1000)):
y = net(x)
t1 = time.time()
print(t1 - t0)
if __name__ == "__main__":
main()Use
Activity Monitor
to see the GPU consumption.