使用TensorFlow在ARM Mac上利用GPU

6

我已经按照这些说明在 M1 (ARM) Mac 上安装了 TensorFlow,一切工作正常。

但是,模型训练是在 CPU 上进行的。如何将训练转换到 GPU

In: tensorflow.config.list_physical_devices()
Out: [PhysicalDevice(name='/physical_device:CPU:0', device_type='CPU')]

Apple的TensorFlow发行版文档中,我找到了以下内容较为混淆的段落

无需更改您现有 TensorFlow 脚本即可使用 ML Compute 作为 TensorFlow 和 TensorFlow Addons 的后端。ML Compute 设备选择提供一个可选的 mlcompute.set_mlc_device(device_name='any') API。device_name 的默认值为 'any',这意味着 ML Compute 将选择系统上最佳的可用设备,包括多 GPU 配置中的多个 GPU。其他可用选项是 CPUGPU。请注意,在急切模式下,ML Compute 将使用 CPU。例如,要选择 CPU 设备,可以执行以下操作:

# Import mlcompute module to use the optional set_mlc_device API for device selection with ML Compute.
from tensorflow.python.compiler.mlcompute import mlcompute

# Select CPU device.
mlcompute.set_mlc_device(device_name='cpu') # Available options are 'cpu', 'gpu', and 'any'.

我尝试运行:

from tensorflow.python.compiler.mlcompute import mlcompute
mlcompute.set_mlc_device(device_name='gpu')

并获得:

WARNING:tensorflow: Eager mode uses the CPU. Switching to the CPU.

我现在遇到了困难,如何在我的 MacBook Air 上使用 GPU 训练 keras 模型?

TensorFlow 版本:2.4.0-rc0

2个回答

3

更新

tensorflow_macos tf 2.4 存储库已被所有者归档。对于 tf 2.5,请参阅此处


也许完全禁用急切执行并不实用,但是可以针对tf. functions进行尝试。尝试此方法并检查您的GPU使用情况,警告信息可能会误导

import tensorflow as tf
tf.config.run_functions_eagerly(False)

目前发布的Mac-optimized TensorFlow存在一些问题,尚未修复(TensorFlow 2.4rc0)。最终,急切模式是TensorFlow 2.x的默认行为,在TensorFlow-MacOS中也没有改变。但与官方版本不同,这个优化版本强制使用CPU进行急切模式。正如他们在这里所述。

... 在急切模式下,ML Compute将使用CPU

这就是为什么即使我们明确设置了device_name='gpu',它仍然会切换回CPU,因为急切模式仍然开启。

from tensorflow.python.compiler.mlcompute import mlcompute
mlcompute.set_mlc_device(device_name='gpu')

WARNING:tensorflow: Eager mode uses the CPU. Switching to the CPU.

禁用急切模式可能有助于程序利用GPU,但它不是一种普遍的行为,可能会导致在CPU/GPU上表现出令人困惑的性能。目前,最合适的方法可能是选择device_name='any',这样ML Compute将查询系统上可用的设备并选择最佳设备来训练网络。


这也可以正常工作,并将模型训练放在GPU上。现在正在测试,看它会破坏多少现有的 tf 代码... - clstaudt
1
我想了解你的输入数据管道的原因是因为你在禁用急切执行时遇到了RuntimeError(),我认为可能使用tf.function装饰器可以解决这个问题或者让代码更进一步。 - Innat
1
一个意外的行为:CPU训练似乎比GPU训练稍微快一些,即使GPU利用率>90%。 - clstaudt
1
我认为这种意外行为更与tensorflow_macosautokeras.ImageClassifier.fit有关。在我的Windows机器上,当禁用急切模型时,我在使用AutoKera时遇到了这个RuntimeError - Innat
1
现在性能问题更多地与tensorflow_macros有关。其他人也遇到了这个问题,但开发者尚未解决它(https://github.com/apple/tensorflow_macos/issues/88)。 - Innat
显示剩余2条评论

1

尝试关闭急切执行,方法如下:

import tensorflow as tf

tf.compat.v1.disable_eager_execution()

如果它起作用,请告诉我。


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