Chuyển đến nội dung chính

第 5 課:穩定擴散深入探討 — 架構與管道

潛在擴散模型:為什麼在潛在空間中工作? UNet架構。使用 CLIP 進行文字調節。 VAE編碼器/解碼器。調度器:DDIM、Euler、DPM++。從提示到圖像的詳細流程。

🧠 人工智慧與機器學習 — 第 4 課 第 5 課:穩定擴散深入研究 — 螞蟻 結構及管線

生成式 AI:使用 AI 創建圖像和視頻

第 2 部分:擴散模型 — 革命性的影像創建

亞洲開發網

簡介

穩定擴散是潛在擴散模型(LDM) - 它不是在像素空間(512×512×3)中擴散,而是在小48倍的潛在空間(64×64×4)中運行。這是一項突破,允許在消費級 GPU 上運行擴散。


1.穩定的擴散架構

┌─────────────────────────────────────────────────────────┐
│              STABLE DIFFUSION PIPELINE                   │
│                                                         │
│  "a cat in space"                                       │
│        ↓                                                │
│  ┌──────────┐     ┌─────────────────────────┐          │
│  │   CLIP   │────→│    UNet + Scheduler      │          │
│  │  Text    │     │  (Denoise in latent)     │          │
│  │ Encoder  │     │  T steps: 20-50          │          │
│  └──────────┘     └───────────┬─────────────┘          │
│                               ↓                         │
│                       ┌──────────────┐                  │
│  Noise z (64x64x4) → │  VAE Decoder  │ → Image 512x512│
│                       └──────────────┘                  │
└─────────────────────────────────────────────────────────┘

組件詳細信息

from diffusers import StableDiffusionPipeline

pipe = StableDiffusionPipeline.from_pretrained("stabilityai/stable-diffusion-xl-base-1.0")

# 4 components chính:
# 1. Text Encoder (CLIP): text → embeddings
pipe.text_encoder  # CLIPTextModel

# 2. UNet: noise predictor, conditioned on text
pipe.unet  # UNet2DConditionModel

# 3. VAE: latent ↔ pixel space
pipe.vae  # AutoencoderKL

# 4. Scheduler: noise schedule algorithm
pipe.scheduler  # EulerDiscreteScheduler

2. 管道分步

import torch
from diffusers import AutoencoderKL, UNet2DConditionModel, EulerDiscreteScheduler
from transformers import CLIPTextModel, CLIPTokenizer

# Step 1: Tokenize & encode text
tokenizer = CLIPTokenizer.from_pretrained("openai/clip-vit-large-patch14")
text_encoder = CLIPTextModel.from_pretrained("openai/clip-vit-large-patch14")

prompt = "a cat wearing sunglasses, digital art"
tokens = tokenizer(prompt, return_tensors="pt", padding="max_length", max_length=77)
text_embeddings = text_encoder(tokens.input_ids)[0]  # [1, 77, 768]

# Step 2: Initialize random latent
latent = torch.randn(1, 4, 64, 64)  # latent space

# Step 3: Denoise loop
scheduler = EulerDiscreteScheduler(num_train_timesteps=1000)
scheduler.set_timesteps(30)  # 30 denoising steps

for t in scheduler.timesteps:
    # Predict noise conditioned on text
    noise_pred = unet(latent, t, encoder_hidden_states=text_embeddings).sample

    # Classifier-free guidance
    noise_uncond = unet(latent, t, encoder_hidden_states=uncond_embeddings).sample
    noise_pred = noise_uncond + guidance_scale * (noise_pred - noise_uncond)

    # Update latent
    latent = scheduler.step(noise_pred, t, latent).prev_sample

# Step 4: Decode latent → pixel image
image = vae.decode(latent / 0.18215).sample

3.無分類器指導(CFG)

$$\hat{\epsilon} = \epsilon_{uncond} + s \cdot (\epsilon_{cond} - \epsilon_{uncond})$$

# guidance_scale s controls text adherence
# s = 1: no guidance (ignore prompt)
# s = 7-8: balanced (default)
# s = 15-20: strong adherence (can be over-saturated)

guidance_scale = 7.5

# During inference: run UNet twice
noise_cond = unet(latent, t, text_embeddings)    # conditioned
noise_uncond = unet(latent, t, empty_embeddings)  # unconditioned

# Interpolate
noise_pred = noise_uncond + guidance_scale * (noise_cond - noise_uncond)

4.VAE——潛在空間壓縮

# Encode: 512x512x3 → 64x64x4 (compression ratio ~48x)
with torch.no_grad():
    latent = vae.encode(image).latent_dist.sample()
    latent = latent * 0.18215  # scaling factor

# Decode: 64x64x4 → 512x512x3
with torch.no_grad():
    image = vae.decode(latent / 0.18215).sample

為什麼是潛在空間?

  • 記憶體:512×512×3 = 786K 像素 → 64×64×4 = 16K 值
  • 速度:UNet 處理小於 48x 的張量
  • 品質:VAE 學會了智慧壓縮

5. 調度程式-去雜訊演算法

from diffusers import (
    DDPMScheduler,        # Original, 1000 steps
    DDIMScheduler,        # Deterministic, 50 steps
    EulerDiscreteScheduler,       # Fast, 20-30 steps
    DPMSolverMultistepScheduler,  # DPM++, 20 steps, high quality
    UniPCMultistepScheduler,      # 10-20 steps
)

# Đổi scheduler dễ dàng
pipe.scheduler = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config)
調度程序步驟速度品質使用案例
DDPM10001000很慢參考訓練
DDIM5050中好一般
歐拉20-3020-30快太棒了預設 SDXL
DPM++ 2M20-2520-25快優推薦
聯合電腦10-1510-15非常快好即時

6. 穩定的擴散版本

版本解析度文字編碼器發佈
標清1.5512×512剪輯 ViT-L/142022
標清2.1768×768OpenCLIP ViT-H2022
SDXL1024×1024CLIP ViT-L + OpenCLIP ViT-bigG2023
SD31024×1024三重文字編碼器(CLIP×2 + T5)2024
助焊劑1024×1024T5 特大號2024
# SDXL — recommended cho production
pipe = StableDiffusionXLPipeline.from_pretrained(
    "stabilityai/stable-diffusion-xl-base-1.0",
    torch_dtype=torch.float16,
    variant="fp16",
)
pipe.to("cuda")

image = pipe(
    prompt="a majestic lion in a forest, photorealistic",
    negative_prompt="blurry, low quality, distorted",
    num_inference_steps=30,
    guidance_scale=7.5,
    width=1024,
    height=1024,
).images[0]

7. 否定提示與參數

# Negative prompt: things to avoid
negative_prompt = "blurry, low quality, deformed, ugly, bad anatomy"

# Key parameters
image = pipe(
    prompt="...",
    negative_prompt=negative_prompt,
    num_inference_steps=30,    # More = better quality, slower
    guidance_scale=7.5,        # Text adherence (7-9 optimal)
    width=1024,
    height=1024,
    seed=42,                   # Reproducibility
).images[0]

總結

組件角色
CLIP 文字編碼器文字→嵌入(語意)
大學網以文字為條件的噪音預測器
VAE壓縮像素 ↔ 潛在空間
調度程序去雜訊步驟演算法
CFG指導尺度調整文本依從性

📌 下一篇文章: 圖像生成提示工程-有效的提示寫作技巧。