🎯 Mục tiêu bài học
Stable Diffusion là open-source model mạnh nhất cho image generation. ComfyUI cung cấp giao diện node-based để build complex image workflows.
Sau bài này, bạn sẽ:
✅ Hiểu Stable Diffusion architecture (U-Net, VAE, CLIP) ✅ Sử dụng SDXL với Python và thư viện diffusers ✅ Làm quen ComfyUI và workflow-based generation ✅ Thực hiện Image-to-Image và LoRA fine-tuning
🔍 Stable Diffusion Architecture
- Latent Space: Không gian nén của image
- U-Net: Neural network để khôi phục lỗi nhiễu
- VAE: Encoder/Decoder chuyển đổi giữa pixel và latent
- CLIP: Text encoder kết nối text với image
Checkpoint
Bạn đã hiểu vai trò của U-Net, VAE và CLIP trong Stable Diffusion chưa?
💻 Stable Diffusion với Python
Basic Generation
1from diffusers import StableDiffusionXLPipeline2import torch34pipe = StableDiffusionXLPipeline.from_pretrained(5 "stabilityai/stable-diffusion-xl-base-1.0",6 torch_dtype=torch.float167)8pipe = pipe.to("cuda")910image = pipe(11 prompt="Professional headshot photo, studio lighting, clean background",12 negative_prompt="cartoon, illustration, low quality, blurry",13 num_inference_steps=30,14 guidance_scale=7.5,15 width=1024,16 height=102417).images[0]1819image.save("headshot.png")Parameters quan trọng
1# Guidance Scale: Muc do theo prompt2# Low (1-5): Creative, loose interpretation3# Medium (6-8): Balanced4# High (9-15): Strict adherence to prompt56# Steps: So buoc denoise7# 20-30: Nhanh, chat luong tot8# 30-50: Chat luong cao9# 50+: Diminishing returns1011# Scheduler: Thuat toan sampling12from diffusers import DPMSolverMultistepScheduler13pipe.scheduler = DPMSolverMultistepScheduler.from_config(14 pipe.scheduler.config15)Checkpoint
Bạn đã thử generate hình ảnh với SDXL pipeline và điều chỉnh parameters chưa?
🛠️ ComfyUI Overview
ComfyUI là node-based GUI cho Stable Diffusion:
Cài đặt ComfyUI
1# Clone repository2git clone https://github.com/comfyanonymous/ComfyUI3cd ComfyUI4 5# Install dependencies6pip install -r requirements.txt7 8# Download models vao ComfyUI/models/checkpoints/9# Run10python main.pyAPI Integration
1import requests2import json34COMFYUI_URL = "http://localhost:8188"56# Basic workflow7workflow = {8 "3": {9 "class_type": "KSampler",10 "inputs": {11 "seed": 42,12 "steps": 30,13 "cfg": 7.5,14 "sampler_name": "dpmpp_2m",15 "scheduler": "karras",16 "denoise": 1.0,17 "model": ["4", 0],18 "positive": ["6", 0],19 "negative": ["7", 0],20 "latent_image": ["5", 0]21 }22 }23}2425# Queue prompt26response = requests.post(27 f"{COMFYUI_URL}/prompt",28 json={"prompt": workflow}29)30prompt_id = response.json()["prompt_id"]Checkpoint
Bạn đã cài đặt và thử nghiệm ComfyUI với node-based workflow chưa?
🎨 Image-to-Image
1from diffusers import StableDiffusionXLImg2ImgPipeline2from PIL import Image34img2img = StableDiffusionXLImg2ImgPipeline.from_pretrained(5 "stabilityai/stable-diffusion-xl-base-1.0",6 torch_dtype=torch.float167)8img2img = img2img.to("cuda")910init_image = Image.open("sketch.png").resize((1024, 1024))1112result = img2img(13 prompt="Professional illustration, detailed, vibrant colors",14 image=init_image,15 strength=0.7, # 0=no change, 1=complete regeneration16 guidance_scale=7.5,17 num_inference_steps=3018).images[0]1920result.save("refined.png")Checkpoint
Bạn đã hiểu cách sử dụng img2img pipeline với tham số strength chưa?
📐 LoRA và Custom Models
1from diffusers import StableDiffusionXLPipeline23pipe = StableDiffusionXLPipeline.from_pretrained(4 "stabilityai/stable-diffusion-xl-base-1.0",5 torch_dtype=torch.float166)78# Load LoRA adapter9pipe.load_lora_weights("path/to/lora/model.safetensors")10pipe = pipe.to("cuda")1112# Generate with LoRA style13image = pipe(14 prompt="photo of product on white background, professional lighting",15 num_inference_steps=3016).images[0]Checkpoint
Bạn đã hiểu cách load và sử dụng LoRA adapters để tuỳ chỉnh style chưa?
🎯 Tổng kết
Best Practices
- Prompt engineering: Cụ thể, chi tiết, sử dụng style keywords
- Negative prompts: Loại bỏ những gì không muốn
- Seed: Cố định seed để reproducible results
- CFG Scale: 7-8 là sweet spot cho hầu hết use cases
- Steps: 25-30 là đủ cho SDXL
Bài tập thực hành
- Setup Stable Diffusion local hoặc dùng API
- Generate 5 images với các styles khác nhau
- Thử img2img để biến sketch thành illustration
- Khảo sát ComfyUI workflows
Bonus: Tìm và sử dụng LoRA model cho specific style
Câu hỏi tự kiểm tra
- Stable Diffusion khác gì so với DALL-E 3 về kiến trúc, chi phí và mức độ kiểm soát?
- LoRA adapter là gì và nó giúp tùy chỉnh style của image generation như thế nào?
- Các tham số guidance_scale và num_inference_steps ảnh hưởng đến chất lượng ảnh đầu ra ra sao?
- Img2img pipeline hoạt động như thế nào và khi nào nên sử dụng nó thay vì text-to-image?
🎉 Tuyệt vời! Bạn đã hoàn thành bài học Stable Diffusion va ComfyUI!
Tiếp theo: Chúng ta sẽ học các kỹ thuật prompt nâng cao để tạo hình ảnh chất lượng cao và nhất quán.
