Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Enable Apple Silicon GPU Acceleration for d2l #2587

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 15 additions & 1 deletion d2l/tensorflow.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

import numpy as np
import tensorflow as tf
import platform

nn_Module = tf.keras.Model

Expand Down Expand Up @@ -479,11 +480,24 @@ def cpu():

Defined in :numref:`sec_use_gpu`"""
return tf.device('/CPU:0')

def is_apple_silicon():
"""Check if the code is running on Apple devices
with Apple Silicon.

Return True only if the code is running on Apple Silicon devices"""
return 'Mac' in platform.uname().node and 'arm' in platform.uname().machine

def gpu(i=0):
"""Get a GPU device.

Defined in :numref:`sec_use_gpu`"""
return tf.device(f'/GPU:{i}')
if is_apple_silicon():
if num_gpus() == 0:
raise RuntimeError('Install TensorFlow-Metal!')
return tf.device(f'/physical_device:GPU:{i}')
else:
return tf.device(f'/GPU:{i}')

def num_gpus():
"""Get the number of available GPUs.
Expand Down
17 changes: 15 additions & 2 deletions d2l/torch.py
Original file line number Diff line number Diff line change
Expand Up @@ -517,17 +517,30 @@ def cpu():
Defined in :numref:`sec_use_gpu`"""
return torch.device('cpu')

def is_apple_silicon():
"""Check if the code is running on Apple devices
with Apple Silicon.

Return True only if the code is running on Apple Silicon devices"""
return torch.backends.mps.is_available()

def gpu(i=0):
"""Get a GPU device.

Defined in :numref:`sec_use_gpu`"""
return torch.device(f'cuda:{i}')
if is_apple_silicon():
return torch.device('mps')
else:
return torch.device(f'cuda:{i}')

def num_gpus():
"""Get the number of available GPUs.

Defined in :numref:`sec_use_gpu`"""
return torch.cuda.device_count()
if is_apple_silicon():
return 1
else:
return torch.cuda.device_count()

def try_gpu(i=0):
"""Return gpu(i) if exists, otherwise return cpu().
Expand Down
Loading