「简记」2022年macos下tensorflow2.0 gpu环境配置

前言

tensorflow 2.0已经支持arm架构的M1芯片,且支持GPU加速

macos下配置非常便捷

这里仅简单记录一下

参考官方文档

安装miniforge

方式1

通过brew

1
brew install miniforge  

方式2

官方推荐

conda-forge仓库下载安装脚本

image-20220424163900522

打开终端,赋予执行权限

1
chmod +x ~/Downloads/Miniforge3-MacOSX-arm64.sh

执行脚本

1
2
cd ~/Downloads
./Miniforge3-MacOSX-arm64.sh

激活

1
source ~/miniforge3/bin/activate

创建一个新的python环境

1
conda create -n tf_mac python=3.9.5

激活环境

1
conda activate tf_mac

修改zshrc配置,每次启动终端默认激活该环境

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# >>> conda initialize >>>
# !! Contents within this block are managed by 'conda init' !!
__conda_setup="$('/Users/lhy/miniforge3/bin/conda' 'shell.zsh' 'hook' 2> /dev/null)"
if [ $? -eq 0 ]; then
eval "$__conda_setup"
else
if [ -f "/Users/lhy/miniforge3/etc/profile.d/conda.sh" ]; then
. "/Users/lhy/miniforge3/etc/profile.d/conda.sh"
else
export PATH="/Users/lhy/miniforge3/bin:$PATH"
fi
fi
unset __conda_setup
conda activate tf_mac
# <<< conda initialize <<<

配置TF 2.0

安装tf依赖

1
2
3
# 一定要确保切换到对应环境
conda activate tf_mac
conda install -c apple tensorflow-deps

安装tf

1
python -m pip install tensorflow-macos

安装Metal Plugin

开启GPU加速

参见PluggableDevice: Device Plugins for TensorFlow

1
python -m pip install tensorflow-metal

安装jupyter lab

非必需,看个人需求

1
conda install -y jupyterlab

升级

如果需要进行版本升级

先卸载已有的tensorflow-macostensorflow-metal

1
2
python -m pip uninstall tensorflow-macos
python -m pip uninstall tensorflow-metal

升级tf依赖

1
conda install -c apple tensorflow-deps -n tf_mac --force-reinstall

安装tf

1
2
python -m pip install tensorflow-macos
python -m pip install tensorflow-metal

验证安装

image-20220424170731877

完毕