跳到正文
Hugging Face Blog·· 2024-06-12精選AI 評分79

Diffusers 支持 Stable Diffusion 3 Medium

Diffusers welcomes Stable Diffusion 3

AI 導讀

Hugging Face 宣佈 Stable Diffusion 3 Medium(2B parameters)已在 Hugging Face Hub 上提供,並可透過 Diffusers 使用。

推薦理由

文章比較 offloading、移除 T5 與 8-bit T5 的顯存和耗時,並提供 torch.compile 加速與 LoRA 微調腳本,可作為 SD3 推理部署與微調的實作參考,並呈現節省顯存方案的耗時取捨。

正文 · 繁體中文

Stable Diffusion 3(SD3)是 Stability AI 最新推出的 Stable Diffusion 系列模型,現已在 Hugging Face Hub 上開放,並可配合 🧨 Diffusers 使用。

今天發布的模型是 Stable Diffusion 3 Medium,具有 2B 個參數。

這次發布亦提供:

  1. Hub 上的模型
  2. Diffusers 整合
  3. SD3 DreamBooth 和 LoRA 訓練指令碼

目錄

SD3 有哪些新功能?

模型

SD3 是一種潛在擴散模型,由三種文字編碼器(CLIP L/14、OpenCLIP bigG/14 和 T5-v1.1-XXL)、新型多模態擴散 Transformer(MMDiT)模型,以及一個與 Stable Diffusion XL 所用模型類似的 16 通道自動編碼器組成。

SD3 會將文字輸入和像素潛在表示處理為一連串嵌入向量。位置編碼會加入潛在表示的 2x2 區塊,再將它們展平成區塊編碼序列。這個序列連同文字編碼序列會輸入 MMDiT 區塊,在其中嵌入至相同維度、串接,再通過一系列調制注意力層和 MLP。

為處理兩種模態之間的差異,MMDiT 區塊使用兩組獨立權重,把文字和影像序列嵌入至相同維度。這些序列會在注意力運算前合併,使兩種表示各自在自己的空間中運作,同時在注意力運算時考慮另一方。這種文字與影像資料之間的雙向資訊流,與以往文字生成影像的方法不同;過往方法會以固定的文字表示,透過交叉注意力把文字資訊加入潛在表示。

SD3 亦會在時間步條件設定中使用兩種 CLIP 模型的池化文字嵌入。這些嵌入會先串接並加入時間步嵌入,然後傳入每個 MMDiT 區塊。

使用 Rectified Flow Matching 訓練

除了架構上的改動,SD3 亦採用條件式流匹配目標來訓練模型。在這種方法中,前向加噪過程定義為整流流,沿直線連接資料分佈和雜訊分佈。

整流流匹配的取樣過程較簡單,即使減少取樣步數,效能依然良好。為支援 SD3 推論,我們新增了排程器(FlowMatchEulerDiscreteScheduler),採用整流流匹配公式和 Euler 方法步進。它亦透過 shift 參數,按解像度調整時間步排程。提高 shift 值有助在較高解像度下更妥善地處理雜訊縮放。2B 模型建議使用 shift=3.0。

如要快速試用 SD3,請參考以下應用程式:

使用 Diffusers 執行 SD3

使用 Diffusers 執行 SD3 前,請確保已升級至最新版本的 Diffusers。

pip install --upgrade diffusers

由於模型設有存取限制,使用 diffusers 前,請先前往 Stable Diffusion 3 Medium Hugging Face 頁面填寫表格並接受存取條款。完成後,請登入,讓系統確認你已接受相關條款。使用以下指令登入:

huggingface-cli login

以下程式碼片段會以 fp16 精度下載 2B 參數版本的 SD3。這是 Stability AI 發布的原始檢查點所用格式,也是建議用於推論的方式。

文字生成影像

import torch
from diffusers import StableDiffusion3Pipeline

pipe = StableDiffusion3Pipeline.from_pretrained(
    "stabilityai/stable-diffusion-3-medium-diffusers", torch_dtype=torch.float16
).to("cuda")

image = pipe(
    "A cat holding a sign that says hello world",
    negative_prompt="",
    num_inference_steps=28,
    guidance_scale=7.0,
).images[0]
image

hello_world_cat

影像生成影像

import torch
from diffusers import StableDiffusion3Img2ImgPipeline
from diffusers.utils import load_image

pipe = StableDiffusion3Img2ImgPipeline.from_pretrained(
    "stabilityai/stable-diffusion-3-medium-diffusers", torch_dtype=torch.float16
).to("cuda")

init_image = load_image("https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/cat.png")
prompt = "cat wizard, gandalf, lord of the rings, detailed, fantasy, cute, adorable, Pixar, Disney, 8k"
image = pipe(prompt, image=init_image).images[0]
image

wizard_cat

你可以在此查看 SD3 説明文件。

SD3 記憶體最佳化

SD3 使用三種文字編碼器,其中一種是體積非常大的 T5-XXL 模型。因此,即使使用 fp16 精度,要在 VRAM 少於 24GB 的 GPU 上執行模型仍相當困難。

為此,Diffusers 整合版提供記憶體最佳化功能,讓 SD3 可在更多不同裝置上執行。

推論時卸載模型

Diffusers 提供最基本的記憶體最佳化方法:在推論期間把模型組件卸載至 CPU,以節省記憶體,但推論延遲會稍為增加。只有在需要執行某個模型組件時,系統才會把它移至 GPU;其餘組件則繼續留在 CPU。

import torch
from diffusers import StableDiffusion3Pipeline

pipe = StableDiffusion3Pipeline.from_pretrained(
    "stabilityai/stable-diffusion-3-medium-diffusers", torch_dtype=torch.float16
)
pipe.enable_model_cpu_offload()

prompt = "smiling cartoon dog sits at a table, coffee mug on hand, as a room goes up in flames. “This is fine,” the dog assures himself."
image = pipe(prompt).images[0]

推論時移除 T5 文字編碼器

推論時移除耗用大量記憶體、具有 4.7B 個參數的 T5-XXL 文字編碼器,可大幅降低 SD3 的記憶體需求,而效能只會輕微下降。

import torch
from diffusers import StableDiffusion3Pipeline

pipe = StableDiffusion3Pipeline.from_pretrained(
    "stabilityai/stable-diffusion-3-medium-diffusers",
    text_encoder_3=None, 
    tokenizer_3=None, 
    torch_dtype=torch.float16
).to("cuda")

prompt = "smiling cartoon dog sits at a table, coffee mug on hand, as a room goes up in flames. “This is fine,” the dog assures himself."
image = pipe(prompt).images[0]

使用量化版本的 T5-XXL 模型

你可以使用 bitsandbytes 函式庫,以 8 bits 載入 T5-XXL 模型,進一步降低記憶體需求。

import torch
from diffusers import StableDiffusion3Pipeline
from transformers import T5EncoderModel, BitsAndBytesConfig

# Make sure you have `bitsandbytes` installed.
quantization_config = BitsAndBytesConfig(load_in_8bit=True)

model_id = "stabilityai/stable-diffusion-3-medium-diffusers"
text_encoder = T5EncoderModel.from_pretrained(
    model_id,
    subfolder="text_encoder_3",
    quantization_config=quantization_config,
)
pipe = StableDiffusion3Pipeline.from_pretrained(
    model_id,
    text_encoder_3=text_encoder,
    device_map="balanced",
    torch_dtype=torch.float16
)

你可以在此處找到完整程式碼片段。

記憶體最佳化摘要

所有基準測試均使用 SD3 的 2B 版本,在配備 80GB VRAM 的 A100 GPU 上執行,並採用 fp16 精度和 PyTorch 2.3。

記憶體基準測試方面,我們先執行 3 次 pipeline 呼叫作暖機,然後以 10 次 pipeline 呼叫的平均推論時間作報告。我們使用 StableDiffusion3Pipeline __call__() 方法的預設參數。

技術 推論時間(秒) 記憶體(GB)
預設 4.762 18.765
卸載 32.765 (~6.8x 🔼) 12.0645 (~1.55x 🔽)
卸載 + 不使用 T5 19.110 (~4.013x 🔼) 4.266 (~4.398x 🔽)
8bit T5 4.932 (~1.036x 🔼) 10.586 (~1.77x 🔽)

SD3 效能最佳化

為提升推論速度,我們可以使用 torch.compile(),為 vae 和 transformer 組件建立最佳化運算圖。

import torch
from diffusers import StableDiffusion3Pipeline

torch.set_float32_matmul_precision("high")

torch._inductor.config.conv_1x1_as_mm = True
torch._inductor.config.coordinate_descent_tuning = True
torch._inductor.config.epilogue_fusion = False
torch._inductor.config.coordinate_descent_check_all_directions = True

pipe = StableDiffusion3Pipeline.from_pretrained(
    "stabilityai/stable-diffusion-3-medium-diffusers",
    torch_dtype=torch.float16
).to("cuda")
pipe.set_progress_bar_config(disable=True)

pipe.transformer.to(memory_format=torch.channels_last)
pipe.vae.to(memory_format=torch.channels_last)

pipe.transformer = torch.compile(pipe.transformer, mode="max-autotune", fullgraph=True)
pipe.vae.decode = torch.compile(pipe.vae.decode, mode="max-autotune", fullgraph=True)

# Warm Up
prompt = "a photo of a cat holding a sign that says hello world",
for _ in range(3):
    _ = pipe(prompt=prompt, generator=torch.manual_seed(1))

# Run Inference
image = pipe(prompt=prompt, generator=torch.manual_seed(1)).images[0]
image.save("sd3_hello_world.png")

完整指令碼請參閲此處。

我們在單一配備 80GB 記憶體的 A100 機器上,使用 PyTorch 2.3 對 SD3 的 torch.compile() 效能進行基準測試,並採用 fp16 精度。我們使用 20 個擴散步驟,執行 10 次 pipeline 推論呼叫。結果顯示,經編譯模型的平均推論時間為 0.585 秒,比 即時執行快 4X。

DreamBooth 和 LoRA 微調

此外,我們提供一個 DreamBooth 微調指令碼,利用 LoRA 為 SD3 進行高效微調。此指令碼可用於高效微調 SD3,亦可作為實作整流流訓練流程的參考。其他常見的整流流實作包括 minRF。

如要開始使用此指令碼,請先確保環境設定正確,並準備好示範資料集(例如這個)。詳情請參閲此處。安裝 peft 和 bitsandbytes 後即可開始:

export MODEL_NAME="stabilityai/stable-diffusion-3-medium-diffusers"
export INSTANCE_DIR="dog"
export OUTPUT_DIR="dreambooth-sd3-lora"

accelerate launch train_dreambooth_lora_sd3.py \
  --pretrained_model_name_or_path=${MODEL_NAME}  \
  --instance_data_dir=${INSTANCE_DIR} \
  --output_dir=/raid/.cache/${OUTPUT_DIR} \
  --mixed_precision="fp16" \
  --instance_prompt="a photo of sks dog" \
  --resolution=1024 \
  --train_batch_size=1 \
  --gradient_accumulation_steps=4 \
  --learning_rate=1e-5 \
  --report_to="wandb" \
  --lr_scheduler="constant" \
  --lr_warmup_steps=0 \
  --max_train_steps=500 \
  --weighting_scheme="logit_normal" \
  --validation_prompt="A photo of sks dog in a bucket" \
  --validation_epochs=25 \
  --seed="0" \
  --push_to_hub

鳴謝

感謝 Stability AI 團隊開發 Stable Diffusion 3,並讓我們提早使用。亦感謝 Linoy 協助製作網誌文章縮圖。

來源:Hugging Face Blog · huggingface.co