跳到正文
Hugging Face Blog·· 2024-10-22精選AI 評分73

Stable Diffusion 3.5 Large 登上 Hugging Face Hub,Diffusers 介紹推理與訓練方法

Diffusers welcomes Stable Diffusion 3.5 Large

AI 導讀

Stable Diffusion 3.5 Large(8B)及其 timestep 蒸餾版(8B)已在 Hugging Face Hub 提供,並可透過 Diffusers 進行推理與訓練。

推薦理由

文章把 Diffusers 中的量化推理與 LoRA 微調落到具體步驟,並提供在 24GB VRAM 消費級 GPU 上微調 SD3.5 Large 的參考路徑。

正文 · 繁體中文

Stable Diffusion 3.5 是前代版本 Stable Diffusion 3的改良版。 由今天起,這些模型已在 Hugging Face Hub 上提供,並可透過 🧨 Diffusers 使用。

此版本包含兩個檢查點:

  • 大型模型(8B)
  • 大型(8B)時間步蒸餾模型,支援少步數推論

本文會介紹如何使用 Diffusers 執行 Stable Diffusion 3.5(SD3.5),涵蓋推論和訓練。

目錄

架構改動

SD3.5(large)的 Transformer 架構與 SD3(medium)非常相似,主要改動如下:

  • QK 正規化:訓練大型 Transformer 模型時,QK 正規化現已成為標準做法,SD3.5 Large 亦不例外。
  • 雙重注意力層:SD3.5 在 MMDiT 區塊中不再為每個模態串流使用單一注意力層,而是改用雙重注意力層。

文字編碼器、VAE 和噪音排程器等其餘細節,與 SD3 Medium 完全相同。如欲深入瞭解 SD3,建議閲讀原始論文。

使用 Diffusers 執行 SD3.5

請先安裝最新版 diffusers:

pip install -U diffusers

由於模型設有存取閘門,使用 diffusers 前,你需要先前往Stable Diffusion 3.5 Large 的 Hugging Face 頁面,填寫表格並同意存取條款。 取得權限後,請登入,讓系統確認你已同意條款。使用以下指令登入:

huggingface-cli login

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

import torch
from diffusers import StableDiffusion3Pipeline

pipe = StableDiffusion3Pipeline.from_pretrained(
    "stabilityai/stable-diffusion-3.5-large", torch_dtype=torch.bfloat16
).to("cuda")

image = pipe(
    prompt="a photo of a cat holding a sign that says hello world",
    negative_prompt="",
    num_inference_steps=40,
    height=1024,
    width=1024,
    guidance_scale=4.5,
).images[0]

image.save("sd3_hello_world.png")

hello_world_cat

此版本亦包含「時間步蒸餾」模型,可移除無分類器引導,並以較少步數生成圖像(通常為 4-8 步)。

import torch
from diffusers import StableDiffusion3Pipeline

pipe = StableDiffusion3Pipeline.from_pretrained(
    "stabilityai/stable-diffusion-3.5-large-turbo", torch_dtype=torch.bfloat16
).to("cuda")

image = pipe(
    prompt="a photo of a cat holding a sign that says hello world",
    num_inference_steps=4,
    height=1024,
    width=1024,
    guidance_scale=1.0,
).images[0]

image.save("sd3_hello_world.png")

hello_world_cat_2

我們在SD3 網誌文章和Diffusers 官方文件展示的範例,應該都能直接用於 SD3.5。 這兩份資源尤其深入介紹如何最佳化推論所需的記憶體。 由於 SD3.5 Large 明顯大於 SD3 Medium,記憶體最佳化對在一般用戶設備上進行推論尤其重要。

使用量化執行推論

Diffusers 原生支援 bitsandbytes量化,可進一步最佳化記憶體使用。

首先,請確保已安裝所有必要程式庫:

pip install -Uq git+https://github.com/huggingface/transformers@main
pip install -Uq bitsandbytes

然後以「NF4」精度載入 Transformer:

from diffusers import BitsAndBytesConfig, SD3Transformer2DModel
import torch

model_id = "stabilityai/stable-diffusion-3.5-large"
nf4_config = BitsAndBytesConfig(
    load_in_4bit=True,
    bnb_4bit_quant_type="nf4",
    bnb_4bit_compute_dtype=torch.bfloat16
)
model_nf4 = SD3Transformer2DModel.from_pretrained(
    model_id,
    subfolder="transformer",
    quantization_config=nf4_config,
    torch_dtype=torch.bfloat16
)

現在就可以執行推論:

from diffusers import StableDiffusion3Pipeline

pipeline = StableDiffusion3Pipeline.from_pretrained(
    model_id, 
    transformer=model_nf4,
    torch_dtype=torch.bfloat16
)
pipeline.enable_model_cpu_offload()

prompt = "A whimsical and creative image depicting a hybrid creature that is a mix of a waffle and a hippopotamus, basking in a river of melted butter amidst a breakfast-themed landscape. It features the distinctive, bulky body shape of a hippo. However, instead of the usual grey skin, the creature's body resembles a golden-brown, crispy waffle fresh off the griddle. The skin is textured with the familiar grid pattern of a waffle, each square filled with a glistening sheen of syrup. The environment combines the natural habitat of a hippo with elements of a breakfast table setting, a river of warm, melted butter, with oversized utensils or plates peeking out from the lush, pancake-like foliage in the background, a towering pepper mill standing in for a tree.  As the sun rises in this fantastical world, it casts a warm, buttery glow over the scene. The creature, content in its butter river, lets out a yawn. Nearby, a flock of birds take flight"
image = pipeline(
    prompt=prompt,
    negative_prompt="",
    num_inference_steps=28,
    guidance_scale=4.5,
    max_sequence_length=512,
).images[0]
image.save("whimsical.png")

happy_hippo

你可以在 BitsAndBytesConfig中調整其他參數。詳情請參閲文件。

亦可直接載入使用上述相同 nf4_config量化的模型。 這對 RAM 較少的電腦尤其有幫助。完整範例請參閲這個 Colab Notebook。

使用量化訓練 SD3.5 Large 的 LoRA

有了 bitsandbytes和 peft等程式庫,現在可在配備 24GB VRAM 的一般 GPU 顯示卡上微調 SD3.5 Large 等大型模型。你現時可使用我們原有的SD3 訓練指令碼訓練 LoRA。 以下訓練指令已可直接使用:

accelerate launch train_dreambooth_lora_sd3.py \
  --pretrained_model_name_or_path="stabilityai/stable-diffusion-3.5-large"  \
  --dataset_name="Norod78/Yarn-art-style" \
  --output_dir="yart_art_sd3-5_lora" \
  --mixed_precision="bf16" \
  --instance_prompt="Frog, yarn art style" \
  --caption_column="text"\
  --resolution=768 \
  --train_batch_size=1 \
  --gradient_accumulation_steps=1 \
  --learning_rate=4e-4 \
  --report_to="wandb" \
  --lr_scheduler="constant" \
  --lr_warmup_steps=0 \
  --max_train_steps=700 \
  --rank=16 \
  --seed="0" \
  --push_to_hub

不過,要配合量化使用,就需要調整幾個參數。以下説明如何操作:

  • 我們會為 transformer初始化量化設定,或直接載入已量化的檢查點。
  • 接着使用 prepare_model_for_kbit_training()函式(來自 peft)準備模型。
  • 由於 peft對 bitsandbytes有完善支援,其餘流程維持不變!

如需更完整範例,請參閲這份示範指令碼。

使用單檔載入 Stable Diffusion 3.5 Transformer

你可以使用 from_single_file方法,搭配 Stability AI 發布的原始檢查點檔案載入 Stable Diffusion 3.5 Transformer 模型:

import torch
from diffusers import SD3Transformer2DModel, StableDiffusion3Pipeline

transformer = SD3Transformer2DModel.from_single_file(
    "https://huggingface.co/stabilityai/stable-diffusion-3.5-large-turbo/blob/main/sd3.5_large.safetensors",
    torch_dtype=torch.bfloat16,
)
pipe = StableDiffusion3Pipeline.from_pretrained(
    "stabilityai/stable-diffusion-3.5-large",
    transformer=transformer,
    torch_dtype=torch.bfloat16,
)
pipe.enable_model_cpu_offload()
image = pipe("a cat holding a sign that says hello world").images[0]
image.save("sd35.png") 

重要連結

鳴謝:感謝 Daniel Frank提供本文網誌縮圖所用的背景照片。亦感謝 Pedro Cuenca和 Tom Aarsen審閲文章草稿。

來源:Hugging Face Blog · huggingface.co