前言
因为众所周知的原因,TensorFlow 和 PyTorch 等深度学习架构,只能在NVIDIA 的 GPU 下运行,对于 Mac 上的 AMD 的 GPU 并不支持。本来不关心这个问题,但是在机缘巧合执行问了下chatGPT,手上正好有个过时的MacBook Pro,就此尝试。
以下是chatGPT原文:
在深度学习过程中,显卡的性能对模型的训练速度和效果有重大影响。由于您用的是AMD显卡的Mac电脑,因此与NVIDIA显卡相比,您可能需要额外安装AMD显卡适配的深度学习库来支持GPU加速训练。
具体来说,您可以使用Keras或PyTorch这样的深度学习库,并选择适合您的显卡类型的版本。例如,Keras有支持AMD显卡的版本,您可以安装AMD版本的Keras,以充分利用您的Mac电脑上AMD显卡的计算性能。在使用GPU进行深度学习训练时,使用较新的AMD显卡会比老旧的显卡更快、更稳定。
此外,您可能还需要了解一些基本的GPU加速训练的技巧,例如,将数据靠近计算设备,减少数据读取时间、缓存数据、使用更高效的算法等等,可以进一步提高深度学习训练的效率和效果。
安装
pip install plaidml-keras
完成安装后,还需要让代码适配本机的 GPU 。
plaidml-setup
上代码
import plaidml.keras
plaidml.keras.install_backend()
import os
import keras
from keras.datasets import mnist
from keras.models import Sequential
from keras.layers import Dense, Dropout, Flatten
from keras.layers import Conv2D, MaxPooling2D
from keras import backend as K
os.environ["KERAS_BACKEND"] = "plaidml.keras.backend"
def test_speed_of_device(use_tensorflow=False):
'''Trains a simple convnet on the MNIST dataset.
Gets to 99.25% test accuracy after 12 epochs
(there is still a lot of margin for parameter tuning).
16 seconds per epoch on a GRID K520 GPU.
'''
batch_size = 128
num_classes = 10
epochs = 12
# input image dimensions
img_rows, img_cols = 28, 28
# the data, split between train and test sets
(x_train, y_train), (x_test, y_test) = mnist.load_data()
if K.image_data_format() == 'channels_first':
x_train = x_train.reshape(x_train.shape[0], 1, img_rows, img_cols)
x_test = x_test.reshape(x_test.shape[0], 1, img_rows, img_cols)
input_shape = (1, img_rows, img_cols)
else:
x_train = x_train.reshape(x_train.shape[0], img_rows, img_cols, 1)
x_test = x_test.reshape(x_test.shape[0], img_rows, img_cols, 1)
input_shape = (img_rows, img_cols, 1)
x_train = x_train.astype('float32')
x_test = x_test.astype('float32')
x_train /= 255
x_test /= 255
print('x_train shape:', x_train.shape)
print(x_train.shape[0], 'train samples')
print(x_test.shape[0], 'test samples')
# convert class vectors to binary class matrices
y_train = keras.utils.to_categorical(y_train, num_classes)
y_test = keras.utils.to_categorical(y_test, num_classes)
model = Sequential()
model.add(Conv2D(32, kernel_size=(3, 3),
activation='relu',
input_shape=input_shape))
model.add(Conv2D(64, (3, 3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))
model.add(Flatten())
model.add(Dense(128, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(num_classes, activation='softmax'))
model.compile(loss=keras.losses.categorical_crossentropy,
optimizer=keras.optimizers.Adadelta(),
metrics=['accuracy'])
model.fit(x_train, y_train,
batch_size=batch_size,
epochs=epochs,
verbose=1,
validation_data=(x_test, y_test))
score = model.evaluate(x_test, y_test, verbose=0)
print('Test loss:', score[0])
print('Test accuracy:', score[1])
if __name__ == '__main__':
os.environ["PLAIDML_DEVICE_IDS"] = "metal_amd_radeon_pro_5600m.0"
test_speed_of_device()
效果
结语
环境搭建好了,可以继续调教chatGPT帮我写代码了。
Q.E.D.