(Base → Refiner 粗生成到細化修飾流程)是一種「粗生成 → 細化修飾」的方法,使用 Stable Diffusion XL 生成潛空間影像,再由 Refiner 模型細化紋理與光影,提升影像品質與真實感。
from diffusers import DiffusionPipeline
import torch
base = DiffusionPipeline.from_pretrained("stabilityai/stable-diffusion-xl-base-1.0", torch_dtype=torch.float16, variant="fp16", use_safetensors=True)
base.to("cuda")
refiner = DiffusionPipeline.from_pretrained("stabilityai/stable-diffusion-xl-refiner-1.0", text_encoder_2=base.text_encoder_2, vae=base.vae, torch_dtype=torch.float16, use_safetensors=True, variant="fp16",)
refiner.to("cuda")
# Define how many steps and what % of steps to be run on each experts (80/20) here
n_steps = 40
high_noise_frac = 0.8
prompt = "A class of data scientists learning AI engineering in a vibrant high-energy pop-art style"
# run both experts
image = base(
prompt=prompt,
num_inference_steps=n_steps,
denoising_end=high_noise_frac,
output_type="latent",
).images
image = refiner(
prompt=prompt,
num_inference_steps=n_steps,
denoising_start=high_noise_frac,
image=image,
).images[0]
display(image)
⚙️ 關鍵參數與流程說明
1️⃣ Base 模型:兩階段擴散模型的粗生成步驟
image = base(
prompt=prompt,
num_inference_steps=n_steps,
denoising_end=high_noise_frac,
output_type="latent",
).images
這裡:
- denoising_end=high_noise_frac:表示「只做前 80% 的去噪步驟」。
- output_type=”latent”:代表輸出的是潛空間的特徵,不是可見圖像。 (也就是還沒 decode 回 RGB 圖片)
→ 目的:產生一張粗略但有整體構圖的潛在影像。
2️⃣ Refiner 模型:兩階段擴散模型的細化修飾步驟
image = refiner(
prompt=prompt,
num_inference_steps=n_steps,
denoising_start=high_noise_frac,
image=image,
).images[0]
這裡:
- denoising_start=high_noise_frac:代表從第 80% 的步驟開始接手,繼續剩下的 20% 去噪。
- image=image:把 base 的潛空間影像傳進來。
- Refiner 會使用相同 prompt,但更注重紋理、光線、質感的修飾。
→ 目的:讓影像更細膩、真實、視覺品質更高。
🧩 為什麼要分兩階段?
這樣做的理由主要有三個:
- 效能: Base model 生成潛空間影像很快,Refiner 只修最後部分,可以節省大量算力。 (比起單一模型從頭到尾跑 40 步要快)
- 品質提升: Refiner 在訓練時特別強化了「高頻細節」,能更好地修正 Base 模型的模糊區域。
- 模組化靈活性: 你可以自由替換不同的 Base 和 Refiner(或只用 Base),根據需求調整品質與速度。
🔍 總結一句話
這個架構就是 「粗生成 → 細化修飾」的兩階段擴散模型設計。 Base 負責構圖,Refiner 負責畫細節。

Stable Diffusion XL Base 模型
官方模型頁面,提供模型下載與簡介。
Hugging Face
Stable Diffusion XL Refiner 模型
官方模型頁面,介紹 Refiner 模型的功能與使用方式。
Hugging Face
Diffusers 文檔:使用 SDXL
Hugging Face 的 Diffusers 文檔,詳細說明如何使用 SDXL 進行影像生成。
Hugging Face