首页 > 解决方案 > 让 TensorFlow 在 ARM Mac 上使用 GPU

问题描述

我已根据这些说明TensorFlow在 M1 ( ARM ) Mac 上安装。一切正常。

但是,模型训练正在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 的后端。有一个mlcompute.set_mlc_device(device_name='any')用于 ML Compute 设备选择的可选 API。device_name 的默认值为“any”,这意味着 ML Compute 将选择您系统上的最佳可用设备,包括多 GPU 配置上的多个 GPU。其他可用选项是CPUGPU。请注意,在 Eager 模式下,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.

在这一点上,我被困住了。如何keras将 GPU 上的模型训练到我的 MacBook Air?

TensorFlow 版本:2.4.0-rc0

标签: pythonmacostensorflowdeep-learningarm

解决方案


更新

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


完全禁用急切执行可能没有用,但tf. functions. 试试这个并检查你的 GPU 使用情况,警告信息可能会产生误导

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

当前版本的Mac 优化 TensorFlow有几个尚未修复的问题 ( TensorFlow 2.4rc0)。最终,eager 模式是 TensorFlow-MacOS 中的默认行为,这在TensorFlow-MacOSTensorFlow 2.x中也没有改变。但与官方不同的是,这个优化版本强制使用CPU进行 Eager 模式。正如他们在这里所说。

...在渴望模式下,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将查询系统上的可用设备并选择最佳设备来训练网络。


推荐阅读