Apple M1的AI環境搭建

老茶音畫 發佈 2024-02-28T04:49:22.492404+00:00

本文環境搭建的基礎是Python3.9, 因為M1為ARM架構,所以放棄了Anaconda,使用Miniforge3。

本文環境搭建的基礎是Python3.9, 因為M1為ARM架構,所以放棄了AnaConda,使用Miniforge3。包括Tensorflow, xgboost, Lightgbm, Numpy, Pandas, Matplotlib, NGBoost等。當然,因為是python3.9, 所以有些庫實在是無法使用。

Homebrew

作為Mac的包管理神器,首先當然要先從Homebrew開始。Homebrew已經支持了ARM架構,可以直接進行安裝,當然,如果你電腦里以前存在X86的brew支持,請先卸載乾淨。

Homebrew 卸載

/bin/bash -c "$(curl -fsSL https://cdn.jsdelivr.net/gh/ineo6/homebrew-install/uninstall.sh)"

Install ARM Homebrew

/bin/bash -c "$(curl -fsSL https://cdn.jsdelivr.net/gh/ineo6/homebrew-install/install.sh)"

執行完畢後,Homebrew安裝在/opt/homebrew路徑下;在安裝完畢後,命令行後會提示執行命令設置環境變量,當然,以防萬一,這裡也提供一下:

echo 'eval "$(/opt/homebrew/bin/brew shellenv)"' >> ~/.zprofile
eval "$(/opt/homebrew/bin/brew shellenv)"

如果是bash shell, 則:

echo 'eval "$(/opt/homebrew/bin/brew shellenv)"' >> ~/.bash_profile
eval "$(/opt/homebrew/bin/brew shellenv)"

記得source ~/.zprofile

Install X86 Homebrew

arch -x86_64 /bin/bash -c "$(curl -fsSL https://cdn.jsdelivr.net/gh/ineo6/homebrew-install/install.sh)"

X86版本的安裝執行完成後命令行未提示添加環境變量。

alias 支持多版本

在終端執行:

alias brew='arch -ARM64 /opt/homebrew/bin/brew'
alias ibrew='arch -x86_64 /usr/local/bin/brew'

這裡可以看出兩者路徑區別

設置鏡像

中科大源

# brew
git -C "$(brew --repo)" remote set-url origin https://mirrors.ustc.edu.cn/brew.git

# core
git -C "$(brew --repo homebrew/core)" remote set-url origin https://mirrors.ustc.edu.cn/homebrew-core.git

# cask
git -C "$(brew --repo homebrew/cask)" remote set-url origin https://mirrors.ustc.edu.cn/homebrew-cask.git

brew update

清華大學源

# brew
git -C "$(brew --repo)" remote set-url origin https://mirrors.tuna.tsinghua.edu.cn/git/homebrew/brew.git

# core
git -C "$(brew --repo homebrew/core)" remote set-url origin https://mirrors.tuna.tsinghua.edu.cn/git/homebrew/homebrew-core.git

# cask
git -C "$(brew --repo homebrew/cask)" remote set-url origin https://mirrors.tuna.tsinghua.edu.cn/git/homebrew/homebrew-cask.git

brew update

恢復默認源

# brew
git -C "$(brew --repo)" remote set-url origin https://GitHub.com/Homebrew/brew.git

# core
git -C "$(brew --repo homebrew/core)" remote set-url origin https://github.com/Homebrew/homebrew-core.git

# cask
git -C "$(brew --repo homebrew/cask)" remote set-url origin https://github.com/Homebrew/homebrew-cask.git

brew update

更多源

Homebrew 其他相關

設置bottles鏡像

# bottles for zsh
echo 'export HOMEBREW_BOTTLE_DOMAIN=https://mirrors.ustc.edu.cn/homebrew-bottles/bottles' >> ~/.zprofile
source ~/.zprofile

# bottles bash
echo 'export HOMEbrew_BOTTLE_DOMAIN=https://mirrors.ustc.edu.cn/homebrew-bottles/bottles' >> ~/.bash_profile
source ~/.bash_profile

cask

目前cask是從GitHub上讀取軟體源,而GitHub Api對訪問有限制,如果使用比較頻繁的話,可以申請Api Token,然後在環境變量中配置到HOMEBREW_GITHUB_API_TOKEN

echo 'export HOMEBREW_GITHUB_API_TOKEN=yourtoken' >> ~/.zprofile
source ~/.zprofile

Install Miniforge3

首先需要下載安裝包: Download

請下載arm64(Apple Silicon)版本:



下載完成後進入到文件目錄,比如我是在~/Download/內,執行:

bash Miniforge3-MacOSX-arm64.sh

整個執行過程會有大概三次填寫yes並回車確定,最後一次會詢問你是否執行conda init, 會自動在~/.zshrc內添加環境變量,如果未執行的,可以將下面語句加入文件末尾:

# >>> conda initialize >>>
# !! Contents within this block are managed by 'conda init' !!
__conda_setup="$('/Users/xx/miniforge3/bin/conda' 'shell.zsh' 'hook' 2> /dev/null)"
if [ $? -eq 0 ]; then
    eval "$__conda_setup"
else
    if [ -f "/Users/xx/miniforge3/etc/profile.d/conda.sh" ]; then
        . "/Users/xx/miniforge3/etc/profile.d/conda.sh"
    else
        export PATH="/Users/xx/miniforge3/bin:$PATH"
    fi
fi
unset __conda_setup

conda activate tf
# <<< conda initialize <<<

記得自行更改/Users/xx/內的用戶名

等待Miniforge3安裝完成,然後設置一個專供學習tensorflow的虛擬環境

conda create -n tf Python=3.9.5
conda activate tf # 將這句添加到~/.zshrc內,每次打開shell都會自動執行

關於conda切換環境的命令,建議自行Google學習一下,很有用。

Install Tensorflow

目前網上流傳的Tensorflow安裝基本是兩個版本,一個是安裝一大堆的支持和依賴,一個是使用yml文件提前準備好環境庫一鍵完成環境創建,比如environment.yml

conda env create --file=environment.yml --name=tf

其實這一步也很簡單,Apple為了大力推廣自家的ARM,已經為大家做好了這部分準備,我們只需要安裝就行了。

假設目前在tf環境內

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

好了,結束!

可以自行利用下面一段代碼測試下:

from tensorflow.keras import layers
from tensorflow.keras import models
model = models.Sequential()
model.add(layers.Conv2D(32, (3, 3), activation='relu', input_shape=(28, 28, 1)))
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, activation='softmax'))
model.summary()



from tensorflow.keras.datasets import mnist
from tensorflow.keras.utils import to_categorical
(train_images, train_labels), (test_images, test_labels) = mnist.load_data()
train_images = train_images.reshape((60000, 28, 28, 1))
train_images = train_images.astype('float32') / 255
test_images = test_images.reshape((10000, 28, 28, 1))
test_images = test_images.astype('float32') / 255
train_labels = to_categorical(train_labels)
test_labels = to_categorical(test_labels)
model.compile(optimizer='rmsprop',
              loss='categorical_crossentropy',
              metrics=['accuracy'])
model.fit(train_images, train_labels, epochs=5, batch_size=64)
test_loss, test_acc = model.evaluate(test_images, test_labels)
test_acc



執行過程中可以在資源管理器中看到GPU的占用:



其他

Lightgbm

conda install Lightgbm

一句代碼解決,完全靠譜。

xgboost

xgboost稍微有點麻煩,我測試了最穩妥的安裝方式,還是自行編譯,那這個時候我們就需要用到brew安裝並設置編譯環境了:

注意,我用的都是brew而非ibrew, 目前都是在ARM環境下完成操作。

brew install gcc
brew install cmake
brew install libomp

2023年3.17 日更新:

到這裡去下載源碼,然後執行下面代碼:

pip install xgboost-x.x.x.tar.gz
# 把版本號換成你所下載的
#比如我下載的xgboost-1.7.4.tar.gz, 則輸入
pip install xgboost-1.7.4.tar.gz

然後就OK了。

至於其他的,Numpy在安裝Tensorflow的時候就自動作為依賴安裝了,Pandas, Matplotlib, NGBoost等,執行下方:

conda install -c conda-forge pandas
conda install -c conda-forge matplotlib
conda install -c conda-forge ngboost

如果conda內實在沒有的,再試試pip安裝,再不行,就只能自行下載源碼編譯了。

目前在當前環境下解決不了的幾個庫:

  1. CatBoost
  2. Cairo -> Pycairo
  3. GraphEmbedding
  4. CV2
  5. igraph

在整個過程中,可能會遇到各種各樣的問題,大家要習慣於使用Google和查閱官方文檔;

Apple M1的AI環境搭建notes.hivan.me/#/AI_Data/Apple_M1_AI_environment_construction

參考

Tensoflow-macos

Run xgboost on Mac and Regression data

Accelerating TensorFlow Performance on Mac

The new Apple M1 chips have accelerated TensorFlow support

M1 Mac Mini Scores Higher Than My RTX 2080Ti in TensorFlow Speed Test.

GPU acceleration for Apple's M1 chip?

M1晶片Mac上Homebrew安裝教程

Mac mini M1使用簡單體驗(編程、遊戲、深度學習)

Installing TensorFlow 2.4 on MacOS 11.0 without CUDA for both Intel and M1 based Macs

在 M1 晶片 Mac 上使用 Homebrew

Apple M1終於讓MacBook變的可以煉丹了

Install XGBoost and LightGBM on Apple M1 Macs

Installing TensorFlow on the M1 Mac

Getting Started with tensorflow-metal PluggableDevice

M1晶片mac安裝xgboost和lightgbm

AI - Apple Silicon Mac M1 機器學習環境 (TensorFlow, JupyterLab, VSCode)

M1晶片安裝tensorflow

使用MacBook pro M1搭建基於ML Compute加速的TensorFlow深度學習環境

你的Mac有了專用版TensorFlow,GPU可用於訓練,速度最高提升7倍

在M1的Mac上安裝Tensorflow(避坑版)

在M1晶片Mac上搭建原生適配Python環境

Conda-forge Miniforge

M1 mac安裝PyTorch的完整步驟指南

macOS M1(AppleSilicon) 安裝TensorFlow環境

傻瓜版M1配置Tensorflow-超簡單近乎一鍵完成

environment.yml

opencv-python

MAC安裝Opencv以及Dlib碰到的一些問題

Jupiter Widgets

啟動SparkContext報錯

MacBook Pro 2020 M1晶片安裝xgboost

xgboost

Homebrew / Linuxbrew 鏡像使用幫助

鏡像助手

Apple Silicon Mac 安裝xgboost

M1晶片mac安裝xgboost和lightgbm

mac安裝lightgbm踩坑心得,親測有效!

MAC 上 使用lightgbm遇到image not found 解決辦法總結

雜記-Macbook Pro M1晶片能玩深度學習嗎?

關鍵字: