TensorFlow在我的M1 MacBook上进行训练时没有使用GPU

9

我已安装了tensorflow-macos,训练时我的CPU使用情况如下 而GPU使用情况如下

是否可以让Tensorflow在GPU上运行呢?


这里有一个有用的线程:https://github.com/pytorch/pytorch/issues/47702#issuecomment-948858262 它并不涉及Tensorflow,而是关于PyTorch的,但仍然有助于了解在这个阶段M1的GPU在深度学习方面可以期待什么。 - tyrex
这可能会有所帮助!https://dev59.com/1G0NtIcB2Jgan1znJGIT - bikram
使用tensorflow-deps==2.5.0与tensorflow-macos进行编程。 附注:https://developer.apple.com/metal/tensorflow-plugin/ - suiwenfeng
6个回答

12

今天我正在设置我的新M1机器,并寻找像Aman Anand提供的测试。在遵循#153提供的标准说明后,使用Homebrew安装的miniforge软件包管理器和从#153指南中的YAML文件克隆的环境,在GPU上成功运行。

Process running on GPU

我还运行了较小且更简单的代码片段,只能在CPU上运行,'% GPU' == 0%:

import numpy as np
import tensorflow as tf

### Aman's code to enable the GPU
#from tensorflow.python.compiler.mlcompute import mlcompute
#tf.compat.v1.disable_eager_execution()
#mlcompute.set_mlc_device(device_name='gpu')
#print("is_apple_mlc_enabled %s" % mlcompute.is_apple_mlc_enabled())
#print("is_tf_compiled_with_apple_mlc %s" % #mlcompute.is_tf_compiled_with_apple_mlc())
#print(f"eagerly? {tf.executing_eagerly()}")
#print(tf.config.list_logical_devices())

x = np.random.random((10000, 5))
y = np.random.random((10000, 2))

x2 = np.random.random((2000, 5))
y2 = np.random.random((2000, 2))

inp = tf.keras.layers.Input(shape = (5,))
l1 = tf.keras.layers.Dense(256, activation = 'sigmoid')(inp)
l1 = tf.keras.layers.Dense(256, activation = 'sigmoid')(l1)
l1 = tf.keras.layers.Dense(256, activation = 'sigmoid')(l1)
l1 = tf.keras.layers.Dense(256, activation = 'sigmoid')(l1)
l1 = tf.keras.layers.Dense(256, activation = 'sigmoid')(l1)
o = tf.keras.layers.Dense(2, activation = 'sigmoid')(l1)

model = tf.keras.models.Model(inputs = [inp], outputs = [o])
model.compile(optimizer = "Adam", loss = "mse")

model.fit(x, y, validation_data = (x2, y2), batch_size = 500, epochs = 500)

不使用GPU进行训练

取消注释Aman代码添加的行并重新运行可以使GPU正常工作:

再次使用GPU进行训练

如果这些脚本仍然不按照活动监视器(在视图/更新频率中将更新频率设置为1秒)使用GPU,请返回第153页,从干净的状态重新开始,并仔细遵循说明,并确保忽略针对Intel/X86的说明。

我的步骤:

  1. 安装Xcode(从应用商店)
  2. 安装Homebrew(不要忘记按推荐设置PATH,在安装完成后需要重新启动终端或重新加载shell配置文件)
  3. 安装miniforge(“brew install miniforge”)
  4. 复制environment.yaml文件,并使用#153中给出的命令克隆为新的conda环境。
  5. 收益。

更新2022-01-26:

在过去的6个月中,在Apple Silicon上安装tensorflow的工作流程变得更加容易了,它仍然依赖于miniforge,但是包通过conda和pip从标准conda env分发,而不必从yaml文件创建。 这些说明非常容易遵循,并且应该在不到2分钟内进行。唯一的例外是我不得不运行一个额外的命令来通过conda安装openblas以使其正常工作。

我的测试在tensorflow 2.7中断了,因为他们改变了与m1的mlcompute位置有关的某些内容,但继续说mlcompute不再需要使用Metal插件指示使用GPU,并且通过简单地删除第5-10行中对mlcompute的引用,测试可以正常工作并在活动监视器中运行在GPU上。


1
我注意到目前只需要pip install tensorflow-macospip install tensorflow-metal就足以在M1上启用GPU。然而,学习速度并不令人印象深刻。我检查了GPU的负载,发现它肯定参与其中。 - chm

5

您可以通过以下方式检查可用的GPU设备:

import tensorflow as tf
tf.config.list_physical_devices()

然后运行您的模型

with tf.device('/device:GPU:0'):
    model.fit(x_train, y_train)

另请参阅https://www.tensorflow.org/api_docs/python/tf/device


5

这个问题已经在发布TensorFlow-macos 2.5时得到修复。在Mac M1上利用GPU运行Tensorflow的最简单方法是创建一个新的conda miniforge3 ARM64环境,并运行以下3条命令来安装TensorFlow及其依赖项:

conda install -c apple tensorflow-deps
python -m pip install tensorflow-macos
python -m pip install tensorflow-metal

更多指示在此页面上:https://developer.apple.com/metal/tensorflow-plugin/

"在您的Mac上使用TensorFlow,加速机器学习模型的训练。安装TensorFlow v2.5和tensorflow-metal PluggableDevice以在Mac GPU上加速训练."


2
您可以这样做,但目前看起来有点麻烦。一种解决方法是使用 MiniForge。如果您使用的是 conda,则需要先卸载它。
1. 安装 Xcode 和 Command Line Tools 包。 2. 安装 MiniForge 以获取 conda。 3. 在 conda 环境中从 conda-forge 安装 Apple 的 TensorFlow 分支和其他所需软件包。
我的答案基于这篇有用的指南: https://medium.com/gft-engineering/macbook-m1-tensorflow-on-jupyter-notebooks-6171e1f48060 Apple 的 GitHub 上也有更多讨论: https://github.com/apple/tensorflow_macos/issues/153

2
我已经安装了miniforge和Apple版本的TensorFlow,版本是'2.4.0-rc0'。但是TensorFlow仍然在CPU上运行 :( - hat

1
您可以尝试运行以下示例代码,打开活动监视器检查GPU是否正常工作并且Tensorflow已经完美安装。
#import os
#os.environ["TF_DISABLE_MLC"] = "1"
#os.environ["TF_MLC_LOGGING"] = "1"
import tensorflow as tf
from tensorflow.python.compiler.mlcompute import mlcompute

tf.compat.v1.disable_eager_execution()
mlcompute.set_mlc_device(device_name='gpu')
print("is_apple_mlc_enabled %s" % mlcompute.is_apple_mlc_enabled())
print("is_tf_compiled_with_apple_mlc %s" % mlcompute.is_tf_compiled_with_apple_mlc())
print(f"eagerly? {tf.executing_eagerly()}")
print(tf.config.list_logical_devices())

from tensorflow.keras import datasets, layers, models

(train_images, train_labels), (test_images, test_labels) = datasets.cifar10.load_data()
train_images, test_images = train_images / 255.0, test_images / 255.0
class_names = ['airplane', 'automobile', 'bird', 'cat', 'deer',
               'dog', 'frog', 'horse', 'ship', 'truck']
model = models.Sequential()
model.add(layers.Conv2D(32, (3, 3), activation='relu', input_shape=(32, 32, 3)))
model.add(layers.MaxPooling2D((2, 2)))
model.add(layers.Conv2D(64, (3, 3), activation='relu'))
model.add(layers.MaxPooling2D((2, 2)))
model.add(layers.Conv2D(64, (3, 3), activation='relu'))
model.add(layers.Flatten())
model.add(layers.Dense(64, activation='relu'))
model.add(layers.Dense(10))
model.compile(optimizer='adam',
              loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
              metrics=['accuracy'])
history = model.fit(train_images, train_labels, epochs=10,
                    validation_data=(test_images, test_labels))

1
我也面临同样的问题。我尝试按照此youtube链接操作。但是,我的编译器在执行make -j8时仍然失败,这让我非常沮丧。希望能够提供解决方案。
截至2021年6月16日的更新:
使用opencv2和tensorflow2.4,我成功搭建了测试环境。 按照Prabhat on medium的步骤进行操作。
注意:小心不要弄乱conda和pip环境,并更改您添加/下载opncv和tensorflow虚拟环境的默认路径。
希望这对安装有所帮助。
对于测试运行,我还使用了github tf test-code

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