macOS M1安装运行TensorFlow及速度测试

macOS安装运行Tensorflow分两种平台,一是Intel机型,二是Apple Silicon机型,前者只能使用CPU进行模型训练,而后者则可以使用GPU。

平台不同,安装过程也不同。

Intel机型

前提你的Mac上已经安装配置了Python3,可以直接使用pip3命令安装Tensorflow。

pip3 install tensorflow

Apple Silicon机型

Apple Silicon机型目前有M1系列和M2。这个步骤相对多一些,主要参考官网教程

1. 安装 Miniforge3

下载安装脚本,地址:https://github.com/conda-forge/miniforge/releases/latest/download/Miniforge3-MacOSX-arm64.sh

安装Miniforge3

bash Miniforge3-MacOSX-arm64.sh

根据提示操作即可,最后一步选择yes,会将变量自动加到.zshrc中。

使Miniforge3生效

source ~/.zshrc

2. 创建conda环境

最新的是TensorFlow 2.6,支持Python 3.9

conda create -n py39 python=3.9
conda activate py39

3. 安装Tensorflow和Metal支持

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

测试

写个脚本测试下,命名为tf.py

import tensorflow as tf
import time

mnist = tf.keras.datasets.mnist

(x_train, y_train),(x_test, y_test) = mnist.load_data()
x_train, x_test = x_train / 255.0, x_test / 255.0

model = tf.keras.models.Sequential([
  tf.keras.layers.Flatten(input_shape=(28, 28)),
  tf.keras.layers.Dense(128, activation='relu'),
  tf.keras.layers.Dropout(0.2),
  tf.keras.layers.Dense(10, activation='softmax')
])

model.compile(optimizer='adam',
              loss='sparse_categorical_crossentropy',
              metrics=['accuracy'])

start = time.time()

model.fit(x_train, y_train, epochs=5)

end = time.time()

model.evaluate(x_test, y_test)
print(end - start)

执行

python3 tf.py

测试结果

操作系统同为macOS 12 Montery。

  1. 实测在Mac mini 2018(CPU训练)上,执行时间为8秒;
  2. 在Mac mini M1 2020(CPU训练)上,执行时间为5.5秒;
  3. 在Mac mini M1 2020(GPU训练)上,执行时间为36秒。

M1的CPU速度比Intel的快了不少,但为啥GPU比CPU还慢,我也不知道。

如果想回退到使用CPU来训练,有两种方式。

  1. 卸载tensorflow-metal
python -m pip uninstall tensorflow-metal
  1. 修改代码,显式地使用CPU

全局性的:

tf.config.experimental.set_visible_devices([], 'GPU')

局部性的:

with tf.device('/cpu:0'):
    # tf代码

Leave a Comment

豫ICP备19001387号-1