Diffusers 文件
Metal Performance Shaders (MPS)
並獲得增強的文件體驗
開始使用
Metal Performance Shaders (MPS)
帶有 徽章的 Pipeline 表示該模型可以利用 Apple 晶片裝置上的 MPS 後端進行更快的推理。歡迎提交 Pull Request 為缺少此徽章的 Pipeline 新增它。
🤗 Diffusers 相容 Apple 晶片(M1/M2 晶片),使用 PyTorch mps
裝置,該裝置使用 Metal 框架來利用 MacOS 裝置上的 GPU。您需要具備:
- 配備 Apple 晶片 (M1/M2) 硬體的 macOS 電腦
- macOS 12.6 或更高版本(推薦 13.0 或更高版本)
- Python 的 arm64 版本
- PyTorch 2.0(推薦)或 1.13(
mps
支援的最低版本)
mps
後端使用 PyTorch 的 .to()
介面將 Stable Diffusion Pipeline 移動到您的 M1 或 M2 裝置上。
from diffusers import DiffusionPipeline
pipe = DiffusionPipeline.from_pretrained("stable-diffusion-v1-5/stable-diffusion-v1-5")
pipe = pipe.to("mps")
# Recommended if your computer has < 64 GB of RAM
pipe.enable_attention_slicing()
prompt = "a photo of an astronaut riding a horse on mars"
image = pipe(prompt).images[0]
image
如果您使用 **PyTorch 1.13**,您需要透過一次額外的一次性傳遞來“預熱”Pipeline。這是針對首次推理傳遞與後續傳遞結果略有不同的問題的臨時解決方案。您只需進行一次此傳遞,並且只需一個推理步驟後即可丟棄結果。
from diffusers import DiffusionPipeline
pipe = DiffusionPipeline.from_pretrained("stable-diffusion-v1-5/stable-diffusion-v1-5").to("mps")
pipe.enable_attention_slicing()
prompt = "a photo of an astronaut riding a horse on mars"
# First-time "warmup" pass if PyTorch version is 1.13
+ _ = pipe(prompt, num_inference_steps=1)
# Results match those from the CPU device after the warmup pass.
image = pipe(prompt).images[0]
故障排除
本節列出了使用 mps
後端時的一些常見問題及其解決方案。
注意力切片 (Attention slicing)
M1/M2 的效能對記憶體壓力非常敏感。當出現這種情況時,系統會自動進行交換,從而顯著降低效能。
為了防止這種情況發生,我們建議使用*注意力切片*來減少推理過程中的記憶體壓力並防止交換。如果您的電腦系統記憶體少於 64GB,或者您生成大於 512×512 畫素的非標準解析度影像,這一點尤其重要。在您的 Pipeline 上呼叫 enable_attention_slicing() 函式
from diffusers import DiffusionPipeline
import torch
pipeline = DiffusionPipeline.from_pretrained("stable-diffusion-v1-5/stable-diffusion-v1-5", torch_dtype=torch.float16, variant="fp16", use_safetensors=True).to("mps")
pipeline.enable_attention_slicing()
注意力切片將昂貴的注意力操作分多步執行,而不是一次性執行。它通常可以將沒有通用記憶體的電腦的效能提高約 20%,但我們觀察到,除非您的 Apple 晶片電腦有 64GB 或更多 RAM,否則它在大多數 Apple 晶片電腦中表現*更好*。
批次推理
批次生成多個提示可能會導致崩潰或無法可靠工作。如果是這種情況,請嘗試迭代而不是批次處理。
< > 在 GitHub 上更新