在 Apple Silicon 上透過 Core ML 使用 Stable Diffusion
Using Stable Diffusion with Core ML on Apple Silicon
Hugging Face Blog 介紹如何在 Apple Silicon 上透過 Core ML 運行 Stable Diffusion,並提供自行轉換後上載至 Hugging Face Hub 的模型權重。
文章交代 Python 與 Swift 所需的模型封裝、attention 變體及運算單元差異,能幫助開發者按硬件和使用方式選擇 Core ML 推理配置。
感謝 Apple 工程師,現在你可以透過 Core ML 在 Apple Silicon 上執行 Stable Diffusion!
這個 Apple 儲存庫提供轉換指令碼和以 🧨 Diffusers 為基礎的推論程式碼,我們非常喜歡!為了讓你盡可能輕鬆上手,我們自行轉換了模型權重,並將 Core ML 版本放到 Hugging Face Hub。
更新:本文撰寫數星期後,我們建立了一款原生 Swift 應用程式,讓你可以在自己的硬件上輕鬆執行 Stable Diffusion。我們在 Mac App Store 推出應用程式,並發布原始碼,讓其他項目也能使用。
本文其餘部分會説明如何在自己的程式碼中使用已轉換的權重,或自行轉換其他權重。
可用檢查點
Stable Diffusion 的官方檢查點已完成轉換,可供使用:
- Stable Diffusion v1.4:已轉換版本 原始版本
- Stable Diffusion v1.5:已轉換版本 原始版本
- Stable Diffusion v2 base:已轉換版本 原始版本
- Stable Diffusion v2.1 base:已轉換版本 原始版本
Core ML 支援裝置上的所有運算單元:CPU、GPU 和 Apple Neural Engine(NE)。Core ML 亦可以在不同裝置上執行模型的不同部分,以提升效能。
每款模型都有多種變體,效能可能因應所用硬件而異。我們建議你逐一試用,並選擇在系統上表現最佳的版本。下文會詳述各項差異。
效能説明
每款模型都有多種變體:
- 「Original」attention 與「split_einsum」。兩者是關鍵 attention 區塊的兩種替代實作。
split_einsum由 Apple早前推出,它與所有運算單元(CPU、GPU 和 Apple Neural Engine)相容。另一方面,original只支援 CPU 和 GPU。不過,original在部分裝置上可能比split_einsum更快,值得親自試試! - 「ML Packages」與「Compiled」模型。前者適合用 Python 進行推論,而
compiled版本則是 Swift 程式碼所需。Hub 上的compiled模型會把大型 UNet 模型權重分拆成多個檔案,以兼容 iOS 和 iPadOS 裝置。這對應到--chunk-unet轉換選項。
本文撰寫時,我在 MacBook Pro(M1 Max、32 個 GPU 核心、64 GB)上採用以下組合,效果最佳:
originalattention。all運算單元(詳見下一節)。- macOS Ventura 13.1 Beta 4 (22C5059b)。
使用這些設定,以 Stable Diffusion v1.4 的 Core ML 版本生成一張圖片需時 18s 🤯。
⚠️ 注意
macOS Ventura 13.1 引入了多項 Core ML 改進,Apple 的實作需要這些改進。若使用較舊版本的 macOS,生成的圖片可能會全黑,速度也會慢得多。
每個模型儲存庫均以樹狀結構整理,提供以下不同變體:
coreml-stable-diffusion-v1-4
├── README.md
├── original
│ ├── compiled
│ └── packages
└── split_einsum
├── compiled
└── packages
你可以按以下方式下載和使用所需變體。
在 Python 中使用 Core ML 推論
先決條件
pip install huggingface_hub
pip install git+https://github.com/apple/ml-stable-diffusion
下載模型檢查點
若要在 Python 中執行推論,必須使用 packages 資料夾中的版本,因為編譯版本只與 Swift 相容。你可以選擇使用 original 或 split_einsum attention 模式。
以下示範如何從 Hub 下載 original attention 變體:
from huggingface_hub import snapshot_download
from pathlib import Path
repo_id = "apple/coreml-stable-diffusion-v1-4"
variant = "original/packages"
model_path = Path("./models") / (repo_id.split("/")[-1] + "_" + variant.replace("/", "_"))
snapshot_download(repo_id, allow_patterns=f"{variant}/*", local_dir=model_path, local_dir_use_symlinks=False)
print(f"Model downloaded at {model_path}")
上述程式碼會將下載的模型快照放入名為 models 的目錄。
推論
下載模型快照後,最簡單的推論方法是使用 Apple 的 Python 指令碼。
python -m python_coreml_stable_diffusion.pipeline --prompt "a photo of an astronaut riding a horse on mars" -i models/coreml-stable-diffusion-v1-4_original_packages -o </path/to/output/image> --compute-unit ALL --seed 93
<output-mlpackages-directory> 應指向你在上一步下載的檢查點,而 --compute-unit 用來指定允許執行推論的硬件。它必須是以下其中一個選項:ALL、CPU_AND_GPU、CPU_ONLY、CPU_AND_NE。你亦可選擇指定輸出路徑和隨機種子,以確保結果可重現。
推論指令碼預設使用 Hub 上的 Stable Diffusion 模型原始版本 CompVis/stable-diffusion-v1-4。若使用其他模型,你必須在推論命令列中以 --model-version 選項指定其 Hub ID。這適用於已支援模型,也適用於你自行訓練或微調的自訂模型。
Stable Diffusion 1.5(Hub ID:runwayml/stable-diffusion-v1-5):
python -m python_coreml_stable_diffusion.pipeline --prompt "a photo of an astronaut riding a horse on mars" --compute-unit ALL -o output --seed 93 -i models/coreml-stable-diffusion-v1-5_original_packages --model-version runwayml/stable-diffusion-v1-5
Stable Diffusion 2 base(Hub ID:stabilityai/stable-diffusion-2-base):
python -m python_coreml_stable_diffusion.pipeline --prompt "a photo of an astronaut riding a horse on mars" --compute-unit ALL -o output --seed 93 -i models/coreml-stable-diffusion-2-base_original_packages --model-version stabilityai/stable-diffusion-2-base
在 Swift 中使用 Core ML 推論
在 Swift 中執行推論比 Python 稍快,因為模型已預先編譯成 mlmodelc 格式。模型載入時,你會在應用程式啟動期間感受到速度差異;但若之後連續生成多次,差異就不會太明顯。
下載
若要在 Mac 上使用 Swift 執行推論,你需要其中一個 compiled 檢查點版本。我們建議你以類似上文的 Python 程式碼在本機下載,但要選用其中一個 compiled 變體:
from huggingface_hub import snapshot_download
from pathlib import Path
repo_id = "apple/coreml-stable-diffusion-v1-4"
variant = "original/compiled"
model_path = Path("./models") / (repo_id.split("/")[-1] + "_" + variant.replace("/", "_"))
snapshot_download(repo_id, allow_patterns=f"{variant}/*", local_dir=model_path, local_dir_use_symlinks=False)
print(f"Model downloaded at {model_path}")
推論
若要執行推論,請先複製 Apple 的儲存庫:
git clone https://github.com/apple/ml-stable-diffusion
cd ml-stable-diffusion
然後使用 Apple 的命令列工具,並透過 Swift Package Manager 執行:
swift run StableDiffusionSample --resource-path models/coreml-stable-diffusion-v1-4_original_compiled --compute-units all "a photo of an astronaut riding a horse on mars"
你必須在 --resource-path 指定上一步下載的其中一個檢查點,因此請確保該路徑包含副檔名為 .mlmodelc 的已編譯 Core ML 套件。--compute-units 必須是以下其中一個值:all、cpuOnly、cpuAndGPU、cpuAndNeuralEngine。
詳情請參閲 Apple 儲存庫中的使用説明。
使用自己的模型
若你已建立與 Stable Diffusion 相容的自訂模型(例如使用 Dreambooth、Textual Inversion 或微調建立的模型),便需要自行轉換模型。幸好 Apple 提供了轉換指令碼,讓你可以完成這項工作。
進行這項工作時,我們建議你按照這些説明操作。
後續步驟
這項技術帶來許多令人振奮的可能性,我們很期待看看社羣接下來能創作出甚麼。以下是一些構想:
- 為 Mac、iPhone 和 iPad 開發原生、高質素的應用程式。
- 將更多排程器帶到 Swift,以進一步加快推論。
- 新增其他流程和任務。
- 探索量化技術及更多最佳化方法。
期待看到你創作的成果!
來源:Hugging Face Blog · huggingface.co