在Mac上使用AMD GPU与Keras工作的方法?

14

我有一台带AMD处理器的MacBook Pro,想在这个GPU上运行使用Tensorflow后端的Keras。我了解到Keras只能与NVIDIA GPU配合使用。是否有解决方法(如果可能的话)?

2个回答

26
你可以使用OpenCL库来解决这个问题。我已经测试过了,对我来说很好用。
注意:我有python3.7版本,并且将使用pip3进行软件包安装。
步骤:
1. 使用以下命令安装OpenCL软件包
pip3 install pyopencl
2. 使用以下命令安装PlaidML
pip3 install plaidml-keras
3. 运行PlaidML的设置。在设置过程中,您可能会收到提示选择GPU。如果设置正确,最后您将得到一个成功消息。
plaidml-setup 4. 安装plaidbench以在GPU上测试plaidml。
pip3 install plaidbench
5. 测试它。如果一切顺利,您将获得基准分数。
plaidbench keras mobilenet
6. 现在我们必须设置环境路径。将此放在您的代码顶部。
import os
os.environ["KERAS_BACKEND"] = "plaidml.keras.backend"

os.environ["RUNFILES_DIR"] = "/Library/Frameworks/Python.framework/Versions/3.7/share/plaidml"
# plaidml might exist in different location. Look for "/usr/local/share/plaidml" and replace in above path

os.environ["PLAIDML_NATIVE_PATH"] = "/Library/Frameworks/Python.framework/Versions/3.7/lib/libplaidml.dylib"
# libplaidml.dylib might exist in different location. Look for "/usr/local/lib/libplaidml.dylib" and replace in above path
  • 在实际代码中进行测试。在您的代码中使用keras而不是tensorflow.keras,并运行以下命令。(在GPU上运行第2步已安装了keras)
  • import os
    
    # IMPORTANT: PATH MIGHT BE DIFFERENT. SEE STEP 6
    os.environ["KERAS_BACKEND"] = "plaidml.keras.backend"
    os.environ["RUNFILES_DIR"] = "/Library/Frameworks/Python.framework/Versions/3.7/share/plaidml"
    os.environ["PLAIDML_NATIVE_PATH"] = "/Library/Frameworks/Python.framework/Versions/3.7/lib/libplaidml.dylib"
    
    # Don't use tensorflow.keras anywhere, instead use keras
    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
    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])
    

    运行此命令后,你将得到

    Using plaidml.keras.backend backend.
    INFO:plaidml:Opening device "metal_intel(r)_iris(tm)_graphics_6100.0"
    # or whatever GPU you selected in step 3
    

    这证实了你正在GPU上运行它。

    参考: https://towardsdatascience.com/gpu-accelerated-machine-learning-on-macos-48d53ef1b545


    1
    @bikram,感谢你的回答!在进行了自己的实验之后,我得出了相同的结论。因此,在macOS+AMD GPU上无法使用TF2.0。我不确定这是否有什么不好或限制性的方面。基本上,TF2.0朝着Keras API的轻松和简单的方向发展。此外,采用只使用Keras API的TF2.0代码也不是太难。 - sashaegorov
    @sashaegorov 没错。 - bikram
    2
    PlaidML 可以在 MacBook 上使用 Metal 运行(在我的情况下比 OpenCL 更好),因此步骤 1 是可选的。此外,步骤 6 可以在没有设置 RUNFILES_DIR 和 PLAIDML_NATIVE_PATH 路径的情况下运行,并且唯一需要的环境变量是 KERAS_BACKEND。 - fdermishin
    运行这段代码需要多长时间?我看到我的代码正在GPU上运行,但每个epoch大约需要79秒。 - ozgur
    PlaidML似乎与Tensorflow.keras不是一对一的。这听起来正确吗?我有一个使用Huber损失函数的现有代码/模型作为示例。但是在PlaidML中不存在tf.keras.losses.Huber这个类。因此,需要进行代码移植。您是否也理解,在此处使用GPU意味着它的功能不是一对一的? - Heems

    0
    事实上,Keras并不仅支持NVIDIA GPU。您可以选择Keras使用的后端,并且如果此后端支持AMD GPU,则Keras在这种情况下也应该可以工作。
    但是,在MacOS上工作的唯一后端是PlaidML。还有ROCm适用于AMD处理器,但截至2020年10月,它在MacOS上不受支持(请参见this discussion)。

    网页内容由stack overflow 提供, 点击上面的
    可以查看英文原文,
    原文链接