Split View: Diffusion Models Deep Dive — DDPM, Latent Diffusion, Classifier-Free Guidance, DDIM, Stable Diffusion 완전 정복 (2025)
Diffusion Models Deep Dive — DDPM, Latent Diffusion, Classifier-Free Guidance, DDIM, Stable Diffusion 완전 정복 (2025)
TL;DR
- Diffusion Model은 "점진적 노이즈 제거를 학습"하는 생성 모델. Forward process가 이미지에 노이즈를 점차 추가하고, Reverse process(신경망)가 이를 되돌린다.
- DDPM (2020, Ho et al.): 현대 diffusion의 출발. Variational lower bound를 노이즈 예측 loss 하나로 단순화.
- Score Matching: 같은 아이디어를 다른 언어로. Reverse diffusion = score function 추정.
- U-Net: Diffusion의 표준 백본. Encoder-decoder with skip connection. 입력과 같은 크기의 노이즈 출력.
- Latent Diffusion Model (LDM, 2021): VAE로 이미지를 잠재 공간(latent)으로 압축 후 그 안에서 diffusion. 48배 계산 절약 → 소비자 GPU에서 가능.
- Stable Diffusion = LDM + CLIP text encoder + 오픈소스 릴리스 (2022 Stability AI).
- Classifier-Free Guidance: 조건부/무조건부 모델을 결합해 프롬프트 충실도 조절. Text-to-image 품질의 비밀.
- DDIM: 결정론적 샘플링. 1000 step → 20 step으로 가속.
- Consistency Model: 1-4 step으로 생성. 실시간 수준.
- Conditional Generation: ControlNet, LoRA, InstructPix2Pix 등으로 제어 가능.
- Video & 3D: Sora, Stable Video Diffusion, DreamFusion. Diffusion이 이미지 너머로 확장.
1. 생성 모델의 진화
1.1 GAN의 시대 (2014-2020)
2014년 Ian Goodfellow의 GAN (Generative Adversarial Network). Generator가 이미지를 만들고, Discriminator가 "진짜 vs 가짜"를 판별. 두 네트워크가 경쟁하며 훈련.
장점:
- 한 번에 샘플 생성 (빠름).
- 고품질 이미지.
단점:
- Mode collapse: 일부 모드만 생성.
- Training instability: 하이퍼파라미터 매우 민감.
- 스케일링 어려움: 더 많은 데이터로 확장 시 불안정.
StyleGAN(2019)까지 발전했지만 복잡한 장면(텍스트 포함)에 한계.
1.2 VAE의 한계
VAE (Variational Autoencoder)는 안정적이지만 결과가 흐릿하다. Encoder가 latent code 분포를 학습하고 Decoder가 복원. 생성은 가능하지만 품질이 GAN에 밀렸다.
1.3 Autoregressive의 한계
PixelRNN, PixelCNN, iGPT: 픽셀을 순차적으로 생성. 품질 좋지만 매우 느림 (픽셀 하나하나 예측). 1024×1024 이미지 생성 = 100만 번 forward pass.
1.4 Diffusion의 등장 (2020)
2020년 DDPM (Ho, Jain, Abbeel). "기이할 정도로 단순한" 방법:
- 이미지에 노이즈를 점진적으로 추가 (forward).
- 신경망에게 노이즈를 예측하도록 훈련.
- 생성 시 랜덤 노이즈에서 시작해 반복적으로 노이즈 제거.
결과: GAN보다 품질 좋고, 안정적이고, 다양한 샘플. 커뮤니티가 흥분했다.
1.5 스케일링의 성공
2021: Dhariwal & Nichol이 "Diffusion Beats GANs" 발표. 이미지 품질 SOTA.
2021 GLIDE: OpenAI가 text-to-image diffusion. 하지만 너무 느리고 무거웠다.
2021 LDM: Rombach et al.의 Latent Diffusion. 판도 변화. 픽셀 공간이 아닌 잠재 공간에서 diffusion → 50배 빠름.
2022 DALL-E 2: OpenAI의 강력한 text-to-image.
2022 Stable Diffusion: Stability AI가 LDM을 오픈소스. 로컬 GPU로 실행 가능. 생성 AI의 대중화.
2022 Imagen: Google. 텍스트 인코더의 중요성 증명.
2024 Sora: OpenAI의 비디오 diffusion. 분 단위 고품질 비디오.
1.6 왜 Diffusion이 성공했는가
핵심: 훈련이 단순하고 안정적. GAN의 min-max 게임이 아니라 단순 MSE loss. 스케일에 따라 일관되게 개선. 더 많은 데이터 + 큰 모델 = 더 나은 결과. "단순한 것이 확장된다".
2. Forward Process — 노이즈 추가
2.1 아이디어
이미지 에 노이즈를 점진적으로 추가:
x_0 (원본) → x_1 → x_2 → ... → x_T (거의 순수 노이즈)
각 step에서 약간의 가우시안 노이즈. T = 1000 (DDPM).
2.2 수식
각 step의 transition:
의미:
- 는 을 평균으로, 를 분산으로 하는 가우시안에서 샘플.
- 는 noise schedule — step마다 얼마나 노이즈를 더할지.
- 처음엔 작은 (이미지 유지), 끝에 큰 (노이즈 지배).
2.3 Noise Schedule
Linear (DDPM 원본):
β_1 = 0.0001
β_T = 0.02
β_t = linear interpolation
Cosine (Nichol & Dhariwal, 2021):
α_t = cos²(π/2 × (t/T + s) / (1 + s))
β_t = 1 - α_t/α_{t-1}
Cosine이 초반에 더 천천히 노이즈를 더해 낮은 해상도에 유리. 대부분 현대 모델은 cosine 또는 변형.
2.4 Closed Form
연쇄 적용 시 편리한 특성: 임의의 t에 대한 를 직접 계산 가능.
정의:
그러면:
혹은 samplable form:
Forward process는 학습 없이 수학으로 계산. 원본 과 랜덤 노이즈 만 있으면 어떤 시점의 든 즉시 생성.
2.5 끝 상태
가 충분히 크면 이고 . 원본과 무관한 순수 가우시안 노이즈.
이것이 핵심: 어떤 이미지로 시작해도 끝 상태는 같다. Reverse process는 순수 노이즈에서 시작해도 이미지로 도달 가능.
3. Reverse Process — 학습해야 하는 부분
3.1 목표
Forward process를 "되돌리고" 싶다:
진짜 역과정은 Bayes로 표현 가능하지만 다루기 어려움. 신경망이 근사한다.
3.2 파라미터화
두 가지 방법:
1. 평균 예측:
2. 노이즈 예측:
Ho et al.이 보였다 — 노이즈를 직접 예측하는 것이 훨씬 잘 작동한다. 평균은 다음 공식으로 유도:
3.3 Loss 단순화
Variational Lower Bound를 유도하면 복잡하지만, Ho et al.의 통찰: 단순 MSE loss가 거의 같은 효과:
즉:
- 랜덤 원본 이미지 .
- 랜덤 시점 .
- 랜덤 노이즈 .
- Forward로 계산.
- 신경망에게 를 주고 을 예측하게.
- MSE로 학습.
놀랄 만큼 단순. GAN의 min-max 없다. 순수 supervised learning.
3.4 Sampling (Inference)
훈련 완료 후 생성:
def sample(model, T=1000):
# 시작: 순수 노이즈
x_t = torch.randn(shape)
for t in reversed(range(T)):
# 노이즈 예측
epsilon = model(x_t, t)
# 평균 계산
alpha_t = alphas[t]
alpha_bar_t = alpha_bars[t]
beta_t = betas[t]
mu = (1 / sqrt(alpha_t)) * (x_t - beta_t / sqrt(1 - alpha_bar_t) * epsilon)
# 다음 step 샘플
if t > 0:
z = torch.randn_like(x_t)
sigma = sqrt(beta_t)
x_t = mu + sigma * z
else:
x_t = mu
return x_t # 생성된 이미지
각 step에서 모델 한 번 호출 → 다음 step. 1000 step = 1000 forward pass. 매우 느리다.
3.5 왜 작동하는가
직관: 깨끗한 이미지에서 노이즈가 많은 이미지로의 변환은 확률적. 반대도 확률적. 충분히 작은 step이면 가우시안으로 근사 가능. 모델은 "현재 노이즈 수준에서 한 걸음 깨끗하게 만드는 방향"만 학습하면 된다.
수학적으로는 diffusion SDE의 이산화. 연속 SDE 형식:
Reverse SDE (Anderson 1982):
가 score function — 이것이 다음 섹션.
4. Score-Based 관점
4.1 Score Function
분포 의 score는:
"이 점에서 확률이 증가하는 방향". 높은 확률 지역으로 향하는 gradient.
4.2 Score Matching = Diffusion
놀라운 동등성: DDPM의 노이즈 예측 = score 추정.
증명 스케치: 일 때,
즉 score는 노이즈에 비례. 노이즈 예측과 score 추정은 같은 문제의 다른 표현.
4.3 Song & Ermon의 관점
Yang Song의 연구 (2019-2020)는 score-based generative model을 먼저 제시. DDPM과 독립적이었지만 수학적으로 동등.
장점: 연속 SDE 프레임워크가 더 깔끔. ODE 형식(probability flow ODE)으로도 표현 가능.
4.4 통합 프레임워크
Song et al. 2021 "Score-Based Generative Modeling through SDEs": DDPM, NCSN 등이 모두 같은 SDE 프레임워크의 특수한 경우.
현대 diffusion 연구는 SDE 관점과 DDPM 관점을 자유롭게 오간다. 실용적으로는 DDPM 표기가 직관적, 이론적으로는 SDE가 우아.
5. U-Net 아키텍처
Diffusion 모델의 백본은 대부분 U-Net.
5.1 왜 U-Net인가
Diffusion 모델의 요구:
- 입력과 출력이 같은 공간 크기 (이미지 → 노이즈).
- 멀티스케일 특징 필요 (globally coherent + locally detailed).
- 위치 정보 보존.
U-Net (원래 의료 이미지 세그멘테이션용, 2015):
- Encoder: 해상도 ↓, 채널 ↑.
- Decoder: 해상도 ↑, 채널 ↓.
- Skip connection: encoder와 decoder의 같은 레벨을 직접 연결.
완벽한 매칭.
5.2 구조
Input (예: 64×64×3)
│
▼
Conv → ResBlock → Attention
│ ↓
│ Downsample (→ 32×32)
│ ↓
│ ResBlock → Attention
│ ↓
│ Downsample (→ 16×16)
│ ↓
│ ResBlock → Attention ← Bottleneck
│ ↓
│ Upsample (→ 32×32)
│ ↑ (skip from encoder)
│ ResBlock → Attention
│ ↑
│ Upsample (→ 64×64)
│ ↑ (skip)
▼
Output (64×64×3) — 예측된 노이즈
5.3 Timestep Embedding
U-Net은 현재 시점 를 알아야 한다. 같은 이미지라도 "초반 diffusion (조금 노이즈)" vs "후반 (많은 노이즈)"의 denoising이 달라야.
Sinusoidal position embedding:
그다음 MLP → ResBlock에 bias로 더함.
5.4 Attention Layer
Diffusion U-Net에는 self-attention 포함. 장거리 의존성 (먼 픽셀끼리 상관) 캡처. 특히 bottleneck 근처.
5.5 Conditioning
텍스트 조건부 생성 시 cross-attention 추가:
Image features → Query
Text features (CLIP) → Key, Value
U-Net이 텍스트와 이미지 사이를 학습. 이것이 "프롬프트 따라가는" 핵심.
5.6 2025: Diffusion Transformer (DiT)
2023년 William Peebles et al.이 Diffusion Transformer(DiT) 제안. U-Net 대신 순수 Transformer.
- 패치 단위 입력 (ViT처럼).
- 스케일링 특성 우수.
- Sora의 기반.
DiT는 대규모에서 U-Net을 능가 → 2024-2025 추세가 DiT로 이동 중.
6. DDIM — 빠른 Sampling
6.1 DDPM의 느림
DDPM은 1000 step 샘플링. 초고품질이지만 너무 느리다. 1분 이상.
6.2 DDIM의 통찰
Song et al. 2021: DDPM의 reverse process를 결정론적으로 만들고 step을 건너뛸 수 있다.
핵심 수식 (간단화):
여기서:
는 "현재의 최선 예측" — "만약 지금 바로 깨끗한 이미지를 뽑아낸다면 이거야".
6.3 빠른 Sampling
DDPM은 1000 step 필요. DDIM은 아무 sub-sequence를 쓸 수 있다:
timesteps = [0, 50, 100, 150, 200, ..., 950] # 20 steps
50배 빠름. 품질 약간 감소하지만 거의 동일.
6.4 다양한 Sampler
DDIM 이후 많은 variant:
- Euler: ODE 관점으로 Euler integrator.
- Heun: 2차 Runge-Kutta.
- DPM-Solver: diffusion을 위한 특수 ODE solver. 10-25 step.
- DPM-Solver++: 더 개선. 현재 Stable Diffusion 기본.
- UniPC: unified predictor-corrector.
모두 같은 아이디어: 샘플링을 ODE 문제로 보고 효율적 solver 적용.
7. Classifier-Free Guidance
Text-to-image의 가장 중요한 트릭.
7.1 문제
단순 조건부 생성:
x_t → model(x_t, text) → noise
문제: 모델이 텍스트를 무시할 수 있다. 훈련 중 텍스트가 약한 신호.
7.2 Classifier Guidance (구)
원래 Dhariwal & Nichol이 제안. 별도 classifier를 훈련해서:
가 classifier gradient. 문제: 별도 classifier 훈련 필요, 복잡.
7.3 Classifier-Free Guidance (신)
Ho & Salimans 2022: classifier 없이 같은 효과.
훈련 시점:
- 10-20% 확률로 text를 null(빈 조건)으로 치환.
- 같은 모델이 조건부와 무조건부를 모두 학습.
추론 시점:
noise_cond = model(x_t, text) # 조건부 예측
noise_uncond = model(x_t, null) # 무조건부 예측
# Extrapolation!
guided_noise = noise_uncond + scale * (noise_cond - noise_uncond)
scale = 1이면 단순 조건부. scale > 1이면 조건부 방향으로 강화. 일반적 값: 5-12.
7.4 왜 작동하는가
직관: "조건부에서 무조건부를 빼면 조건의 효과만 남는다". 이를 확대 → 조건을 강조. 마치 "텍스트에 더 충실하라"고 강요.
실용적으로 text-to-image의 프롬프트 충실도를 결정. 이게 없으면 무시당하는 프롬프트.
7.5 Trade-off
scale 올리면:
- ✅ 프롬프트 더 정확.
- ❌ 이미지 다양성 감소.
- ❌ Artifact 증가 (과도한 scale).
보통 7-12가 sweet spot.
8. Latent Diffusion Model
8.1 픽셀 공간의 문제
원본 DDPM은 픽셀 공간에서 diffusion. 512×512×3 = 786,432 차원. 각 step마다 이 모든 차원 처리 → 매우 비싼 계산.
8.2 LDM의 아이디어 (Rombach et al. 2021)
"픽셀 공간에 낭비가 많다. 대부분 픽셀은 주변과 비슷하고, 의미 있는 정보는 훨씬 적은 차원에 있다. VAE로 압축하고 그 공간에서 diffusion하자."
구조:
Image (512×512×3)
↓
VAE Encoder
↓
Latent (64×64×4) ← 여기서 diffusion
↓
VAE Decoder
↓
Image (512×512×3)
Latent 공간은 64×64×4 = 16,384 차원. 원본의 1/48. 계산 48배 절감.
8.3 VAE 훈련
LDM은 사전 훈련된 VAE를 사용. VAE는 별도로 훈련:
- Encoder: 이미지 → latent.
- Decoder: latent → 이미지.
- Loss: reconstruction + KL + perceptual (LPIPS) + adversarial (discriminator).
한 번 훈련하면 모든 diffusion에 재사용.
8.4 Diffusion in Latent Space
VAE는 고정. 그 위에서 표준 DDPM:
latent = vae.encode(image) # 이미지 → latent
noisy_latent = forward_diffusion(latent, t)
predicted_noise = unet(noisy_latent, t, text)
# Loss: MSE between predicted_noise and actual noise
생성 시:
noise = torch.randn(1, 4, 64, 64) # latent 크기
for t in reversed(timesteps):
noise = denoise_step(unet, noise, t, text)
image = vae.decode(noise)
8.5 장점 정리
- 계산: 48배 빠름.
- 메모리: 역시 48배 적음.
- 고해상도 가능: 1024×1024도 합리적.
- Semantic abstraction: Latent 공간이 의미 있는 표현 학습 → 더 나은 일반화.
8.6 한계
- VAE 손실: 작은 디테일 정보 손실 (텍스트, 얼굴 등).
- VAE artifact: 약간의 블러 또는 미묘한 왜곡.
- 그래도 압도적으로 가치 있음.
9. Stable Diffusion
9.1 구성
Stable Diffusion (2022 Stability AI) = LDM + CLIP + 오픈소스.
컴포넌트:
- VAE: 이미지 ↔ 8× 압축된 latent.
- CLIP text encoder: 텍스트 → 768차원 벡터.
- U-Net: 잠재 공간의 diffusion. Cross-attention으로 텍스트 조건.
- Scheduler: DDIM, DPM-Solver 등.
9.2 CLIP Text Encoder
OpenAI CLIP (Contrastive Language-Image Pre-training, 2021). 대규모 이미지-텍스트 쌍으로 훈련된 텍스트/이미지 인코더.
역할:
- 프롬프트 → 고차원 임베딩.
- U-Net의 cross-attention이 이 임베딩을 참조.
CLIP이 좋을수록 프롬프트 이해 좋음. Stable Diffusion은 CLIP ViT-L/14 사용.
9.3 훈련 데이터
LAION-5B: 웹에서 크롤링한 50억 개 이미지-텍스트 쌍. Open 이라 재현 가능. 저작권 논란도 여기서.
9.4 버전 진화
SD 1.x (2022): 첫 릴리스. 512×512. OpenAI CLIP.
SD 2.x (2022): 더 나은 aesthetics. OpenCLIP 사용.
SDXL (2023): 더 큰 모델, refiner. 1024×1024 네이티브. 훨씬 나은 품질.
SD 3 (2024): Rectified flow 채택. Diffusion Transformer 기반.
Flux (2024 Black Forest Labs): SD3 뒤를 잇는 강자. 오픈소스 SOTA.
9.5 오픈소스 vs 클로즈드
Stable Diffusion: 오픈소스. 로컬 실행, 파인튜닝, 수정 가능.
DALL-E 3, Midjourney: API만. 품질 더 좋을 수 있지만 블랙박스.
연구/커스터마이징은 SD가 주류. 상용 품질은 클로즈드.
10. Conditional Generation 기법
10.1 Text-to-Image (기본)
위에서 설명. 텍스트 프롬프트 → 이미지.
10.2 Image-to-Image (img2img)
초기 latent를 랜덤 노이즈가 아니라 기존 이미지의 latent에서 시작.
input_latent = vae.encode(input_image)
noisy = forward_diffuse(input_latent, strength) # partial noise
output = denoise(noisy, text)
strength가 0.3이면 약간만 바뀜, 0.9면 거의 다시 생성. "이 그림을 이렇게 바꿔줘" 패턴.
10.3 Inpainting
마스크 안쪽만 재생성. Mask된 부분은 노이즈, 나머지는 원본 유지.
mask = user_drawn_mask
latent = vae.encode(image)
for t in reversed(timesteps):
# 노이즈 예측
noise = unet(noisy, t, text)
# Mask 밖은 원본으로 교체 (매 step마다)
noisy = noisy * mask + forward_diffuse(latent, t) * (1 - mask)
특정 영역만 수정. Photoshop의 "generative fill"이 이것.
10.4 ControlNet
Lvmin Zhang et al. 2023. 추가 조건으로 구조를 제어.
아이디어: U-Net을 복사한 "control" 네트워크를 훈련. Control 네트워크가 edge, pose, depth 같은 힌트 이미지를 받아서 U-Net에 영향.
Input image (pose skeleton)
↓
ControlNet copy of U-Net
↓
Influence on main U-Net
↓
Output: 프롬프트에 맞지만 pose는 따라감
ControlNet 변형:
- Canny: edge 기반.
- Depth: depth map 기반.
- OpenPose: 사람 pose 기반.
- Scribble: 손 스케치.
- Segmentation: semantic mask.
"특정 구도 + 자유로운 스타일" 패턴. 매우 유용.
10.5 LoRA (Low-Rank Adaptation)
사전 훈련 모델을 작은 파라미터로 특화.
아이디어: 각 layer의 weight 에 low-rank 업데이트 추가.
, , .
만 훈련. 원본 는 고정. 결과:
- 훨씬 적은 파라미터: 수백 MB → 수 MB.
- 빠른 훈련: 수천 이미지로 특정 스타일/캐릭터 학습.
- 교체 가능: 여러 LoRA를 on/off.
Civitai 같은 사이트에 수만 개 LoRA. "이 애니메이션 캐릭터 스타일", "이 아티스트 스타일" 등.
10.6 DreamBooth
특정 피사체(내 강아지, 특정 사람) 훈련. 5-10 장의 사진만으로.
입력: 강아지 사진 몇 장
훈련: "sks dog" 같은 고유 토큰을 이 강아지에 연결
출력: "sks dog on the beach" → 내 강아지가 바닷가에
LoRA와 결합해 경량 DreamBooth가 주류.
10.7 Textual Inversion
새 단어를 학습. 단어의 embedding만 훈련하고 모델은 고정.
"<new_concept>" 라는 토큰을 훈련
이 토큰의 embedding이 특정 스타일/피사체 표현
더 가볍지만 제한적.
10.8 InstructPix2Pix
자연어 명령으로 편집.
입력: 이미지 + "remove the person"
출력: 사람이 제거된 이미지
ChatGPT 스타일 편집 인터페이스.
11. Consistency Models — 실시간 생성
11.1 문제
DDIM으로도 20-50 step 필요. 실시간 (100ms 미만)엔 부족.
11.2 Consistency Model (Song et al. 2023)
"Diffusion은 ODE 궤도를 따라간다. 그 궤도의 어느 지점에서든 바로 로 점프할 수 있게 훈련하자."
훈련 후 1-4 step으로 고품질 생성 가능.
11.3 Latent Consistency Model
LCM (2023): LDM + Consistency Distillation. Stable Diffusion을 2-4 step으로 가속.
기존 SDXL: 25 step × 150ms = 3.75s
LCM SDXL: 4 step × 150ms = 600ms
실시간 인터랙티브 생성 가능. 사용자가 프롬프트 타이핑하면 결과 실시간 업데이트.
11.4 SDXL Turbo
Stability AI의 2023 릴리스. SDXL을 1 step으로 생성. 품질 약간 감소하지만 거의 즉시.
11.5 Progressive Distillation
원래 모델(teacher)의 여러 step을 한 step으로 학습하는 기법. 반복적으로 step 수를 반으로.
1000 → 500 → 250 → ... → 1 step.
각 단계에서 student 모델이 teacher의 n step을 1 step으로 근사.
12. 비디오 Diffusion
12.1 Naive 접근
각 프레임을 독립적으로 diffusion → 프레임 간 일관성 없음. 깜빡거림, 캐릭터가 바뀜.
12.2 Temporal Attention
U-Net에 temporal attention layer 추가. 시간 축을 따라 attention을 걸어 일관성 유지.
Spatial Attention (이미지 내 위치)
Temporal Attention (프레임 간)
12.3 Video Diffusion Models
Stable Video Diffusion (2023): 이미지 → 짧은 비디오 (2-4초).
Sora (2024 OpenAI): 분 단위 고품질. Diffusion Transformer 기반. Patch 단위로 공간×시간 통합 처리.
Sora의 비밀:
- DiT 아키텍처 (U-Net 아님).
- Spacetime patches: 3D volumetric 처리.
- 거대한 스케일 (모델 + 데이터).
- 고품질 캡션 (GPT-4로 비디오 설명 생성).
13. 3D Diffusion
13.1 DreamFusion
2D diffusion model을 사용해 3D 객체 생성.
아이디어: SDS (Score Distillation Sampling). 3D 객체 파라미터(NeRF)를 최적화. 2D diffusion이 "이 뷰가 이 프롬프트에 충실한가"를 평가.
결과: 수 시간 훈련 후 "텍스트 → 3D mesh".
13.2 Gaussian Splatting + Diffusion
2023+ Gaussian Splatting이 3D 표현 기본. Diffusion이 Gaussian 파라미터를 생성.
13.3 한계
2D에 비해 훨씬 어렵다. 훈련 데이터 부족, 품질 한계. 현재 활발한 연구 영역.
14. 구현 실전
14.1 Hugging Face Diffusers
파이썬 라이브러리. Stable Diffusion 등을 3줄로:
from diffusers import StableDiffusionPipeline
import torch
pipe = StableDiffusionPipeline.from_pretrained(
"runwayml/stable-diffusion-v1-5",
torch_dtype=torch.float16
).to("cuda")
image = pipe("a photograph of an astronaut riding a horse").images[0]
image.save("astronaut.png")
14.2 Scheduler 교체
from diffusers import DPMSolverMultistepScheduler
pipe.scheduler = DPMSolverMultistepScheduler.from_config(
pipe.scheduler.config
)
# 이제 20 step으로 고품질
image = pipe(prompt, num_inference_steps=20).images[0]
14.3 LoRA 로드
pipe.load_lora_weights("path/to/lora", weight_name="my_style.safetensors")
pipe.fuse_lora(lora_scale=0.7)
image = pipe("a cat in my_style style").images[0]
14.4 ControlNet
from diffusers import StableDiffusionControlNetPipeline, ControlNetModel
controlnet = ControlNetModel.from_pretrained(
"lllyasviel/sd-controlnet-canny"
)
pipe = StableDiffusionControlNetPipeline.from_pretrained(
"runwayml/stable-diffusion-v1-5",
controlnet=controlnet
)
from PIL import Image
edge_image = Image.open("canny_edges.png")
image = pipe(prompt="a modern house", image=edge_image).images[0]
14.5 Inference 최적화
- FP16:
torch_dtype=torch.float16. 메모리 절반, 속도 개선. - Memory-efficient attention:
pipe.enable_xformers_memory_efficient_attention()또는 PyTorch 2+의scaled_dot_product_attention. - VAE tiling: 큰 이미지 생성 시 메모리 초과 방지.
- TensorRT / OpenVINO: 컴파일 최적화. 2-3배 가속.
15. 윤리와 법적 이슈
15.1 저작권
LAION-5B에는 저작권 이미지 포함. 훈련의 합법성 논쟁.
- Getty Images: Stability AI 상대 소송 (2023).
- Andersen v. Stability AI: 아티스트 집단소송.
2025년 현재 판결 진행 중. 결과가 AI 산업 전체에 영향.
15.2 Deepfakes
Face swap, 음란 합성. Diffusion이 품질 올리면서 악용 증가.
대응:
- Content credentials (C2PA): 이미지에 메타데이터로 AI 생성 표시.
- Watermarking: Stable Signature 같은 invisible watermark.
- Detection: AI-generated 감지 모델.
15.3 편향
훈련 데이터의 편향이 출력에 반영. 특정 직업 = 남성, 특정 외모 = 우월. 연구 및 완화 활발.
15.4 일자리
일러스트레이터, 디자이너의 우려. "AI가 그림 그리면 나는?" 새 도구로 적응 vs 규제 논쟁.
16. 미래 방향
16.1 고품질 + 빠른 생성
Consistency model의 추가 발전. 1 step 고품질 생성.
16.2 컨트롤
단순 텍스트 넘어 정확한 제어 — pose, 구도, 색조, 스타일.
16.3 일관성
여러 이미지/프레임 간 일관성. 캐릭터 동일성 유지.
16.4 Multimodal
텍스트 + 이미지 + 오디오 + 비디오 통합 생성.
16.5 작은 모델
LCM, Turbo 같은 가속 + 모델 축소. 모바일/엣지에서 실행.
16.6 Physical Simulation
Sora가 보여준 가능성: diffusion이 물리 법칙을 "암묵적으로" 학습. "world model"로의 확장.
17. 학습 리소스
논문:
- DDPM (Ho et al. 2020) — 필수.
- Latent Diffusion (Rombach et al. 2021).
- Classifier-Free Guidance (Ho & Salimans 2022).
- DDIM (Song et al. 2020).
- Stable Diffusion (2022 Stability AI).
- DiT (Peebles & Xie 2023).
- Consistency Model (Song et al. 2023).
책/가이드:
- "Hands-On Machine Learning" — Aurélien Géron (확장판에 diffusion 추가).
- Lilian Weng의 블로그: "What are Diffusion Models?".
- Jay Alammar의 시각화 블로그.
코드:
- Hugging Face Diffusers 라이브러리 (Python).
- Stability AI 공식 리포 (stability-ai/generative-models).
- AUTOMATIC1111 Stable Diffusion Web UI.
강의:
- Yang Song의 MIT 강의 (score-based models).
- Andrew Ng의 생성 AI 코스.
18. 요약 — 한 장 정리
┌─────────────────────────────────────────────────────┐
│ Diffusion Models Cheat Sheet │
├─────────────────────────────────────────────────────┤
│ 핵심 아이디어: │
│ 노이즈 추가 → 신경망이 노이즈 예측 → 되돌림 │
│ │
│ Forward Process: │
│ x_t = √α̅_t · x_0 + √(1-α̅_t) · ε │
│ 학습 없이 계산 가능 │
│ Noise schedule: linear, cosine │
│ │
│ Reverse Process: │
│ 신경망 ε_θ(x_t, t) 학습 │
│ Loss: MSE(ε, ε_θ) │
│ Simple, stable, scalable │
│ │
│ 수학적 관점: │
│ DDPM: variational bound │
│ Score matching: ∇log p(x) │
│ SDE: dx = f dt + g dW │
│ ODE: probability flow │
│ │
│ U-Net 아키텍처: │
│ Encoder-decoder + skip │
│ Timestep embedding (sinusoidal) │
│ Self-attention + Cross-attention (text) │
│ 2024+: Diffusion Transformer (DiT) │
│ │
│ Sampling: │
│ DDPM: 1000 step, 느림 │
│ DDIM: 결정론적, 20-50 step │
│ DPM-Solver++: 10-25 step │
│ Consistency Model: 1-4 step │
│ │
│ Latent Diffusion (LDM): │
│ VAE encoder: image → latent │
│ Latent에서 diffusion (48x 절감) │
│ VAE decoder: latent → image │
│ Stable Diffusion의 기반 │
│ │
│ Classifier-Free Guidance: │
│ 훈련: 10% null condition │
│ 추론: uncond + scale*(cond - uncond) │
│ scale 7-12 = prompt 충실 │
│ │
│ 조건부 제어: │
│ Text: CLIP + cross-attention │
│ Image: img2img │
│ Structure: ControlNet (canny, pose, depth) │
│ Style: LoRA │
│ Subject: DreamBooth │
│ Edit: InstructPix2Pix, inpainting │
│ │
│ Production: │
│ Stable Diffusion (오픈) │
│ DALL-E 3, Midjourney (클로즈드) │
│ Flux (2024+, SOTA 오픈) │
│ │
│ 확장: │
│ Video: Sora, Stable Video Diffusion │
│ 3D: DreamFusion │
│ Audio: AudioLDM │
└─────────────────────────────────────────────────────┘
19. 퀴즈
Q1. DDPM의 훈련 loss가 단순 MSE인 이유는?
A. Ho et al. (2020)의 핵심 통찰 — variational lower bound를 수학적으로 단순화하면 각 step마다 "실제 노이즈와 예측 노이즈의 MSE"로 귀결된다. 원래는 복잡한 KL divergence 항이 있지만 reparameterization과 영리한 유도 후 대부분이 제거되고 노이즈 예측 error만 남는다. 이것이 Diffusion 훈련을 GAN처럼 불안정한 min-max 게임이 아니라 단순 supervised learning으로 만든 핵심 이유. 손실이 단순하기 때문에 스케일에 따라 일관되게 개선되고, 하이퍼파라미터에 덜 민감하다. "단순한 것이 확장된다"는 원칙의 전형.
Q2. Latent Diffusion이 계산을 48배 줄인 방법은?
A. VAE로 이미지를 압축한 후 잠재 공간에서 diffusion. 원본 512×512×3 = 786,432 차원의 픽셀 공간 대신 64×64×4 = 16,384 차원의 VAE 잠재 공간에서 denoising 수행. 각 step이 48배 작은 tensor를 처리 → 계산과 메모리 모두 48배 절감. VAE는 사전 훈련되고 diffusion 훈련 중엔 고정. 손실은 미미(VAE의 재구성 품질이 좋아서). 이 단순한 변경으로 "데이터센터 필요"에서 "소비자 GPU로 실행 가능"으로 바뀌었고, 이것이 Stable Diffusion이 오픈소스로 대중화될 수 있었던 배경. 작은 구조적 변경이 사회적 영향을 만든 사례.
Q3. Classifier-Free Guidance는 어떻게 작동하는가?
A. 훈련 시점에는 10-20% 확률로 text 조건을 null(빈 조건)로 치환해서 같은 모델이 조건부와 무조건부 생성을 모두 학습. 추론 시점에는 두 예측을 계산: noise_cond = model(x, text)와 noise_uncond = model(x, null). 그 다음 extrapolation: guided = uncond + scale * (cond - uncond). scale > 1이면 "조건 방향으로 과장" → 텍스트 프롬프트에 더 충실. 직관적으로 "조건부에서 무조건부를 빼면 조건의 순수 효과가 남는다"를 확대한 것. scale 7-12가 sweet spot. 이 단순한 트릭이 text-to-image의 실용 품질을 결정한다 — 이게 없으면 프롬프트가 무시된다.
Q4. Score-based 관점과 DDPM 관점의 관계는?
A. 수학적으로 동등. Yang Song의 score-based generative model (2019)과 Ho의 DDPM (2020)은 독립적으로 개발됐지만 같은 것의 다른 표현이다. Score function 를 추정하는 것과 "노이즈 을 예측하는 것"이 상수 배수로 관련된다: . Song et al. 2021이 둘을 통합 SDE 프레임워크로 증명. 실용적으로는 DDPM 표기가 직관적이고 코드가 단순, 이론적으로는 SDE/score가 우아하고 연속 극한을 다루기 편하다. 두 관점을 자유롭게 오갈 수 있으면 논문 읽기가 훨씬 쉬워진다.
Q5. DDIM이 DDPM보다 50배 빠른 이유는?
A. 결정론적 sampling을 가능하게 해서 step을 건너뛸 수 있게 한다. DDPM의 reverse process는 확률적(매 step마다 랜덤 노이즈 추가)이라 반드시 1000 step을 순차로 밟아야 한다. DDIM은 같은 훈련된 모델을 다르게 해석해서 결정론적 ODE 궤도로 본다 — "현재 에서 로 가는 방향"이 수학적으로 정해짐. 결정론이므로 sub-sequence(예: [0, 50, 100, ..., 950] 20 step)로 점프해도 수학적으로 합리적. 품질은 조금 감소하지만 거의 동일. 이후 DPM-Solver, DPM-Solver++ 등이 더 효율적인 ODE solver로 10-25 step까지 줄임. 모두 "DDIM의 결정론적 경로" 아이디어를 기반.
Q6. ControlNet이 기존 조건부 생성과 다른 점은?
A. 구조적 제어를 위해 U-Net의 복사본을 추가 훈련한다. 기존 cross-attention text 조건은 "스타일/내용"을 제어하지만 "정확한 구도/pose"는 조절하기 어렵다. ControlNet은 U-Net encoder의 복사본을 만들고, 새 입력(canny edge, pose skeleton, depth map 등)을 받아서 원본 U-Net의 각 layer에 영향을 준다. 원본 U-Net은 고정, ControlNet 부분만 훈련 → 작은 데이터로도 가능. 결과: "이 스케치의 구도 + 프롬프트의 내용"이 정확히 결합. 실사 사진의 pose를 만화 스타일로 전환하거나, 건물 배치도로 렌더링 생성 등. 정밀 제어가 필요한 실무에 필수적. 2023년 이후 SD의 표준 기능.
Q7. Consistency Model이 1-4 step으로 생성할 수 있는 이유는?
A. 궤도의 어느 지점에서든 바로 로 점프하도록 모델을 훈련한다. 일반 diffusion은 "현재 step에서 한 걸음 깨끗하게" 학습하는데, Consistency Model은 "현재 step에서 완전히 깨끗한 이미지로 바로"를 학습. 이것이 가능한 이유는 diffusion의 probability flow ODE 궤도가 결정론적이기 때문 — 같은 궤도 위의 모든 점이 같은 로 수렴해야 한다는 consistency 조건을 loss에 추가. 훈련 후에는 1 step으로 꽤 괜찮은 결과, 2-4 step으로 고품질. Latent Consistency Model(LCM)은 이를 LDM에 적용해 SDXL을 4 step에 돌린다. 실시간 인터랙티브 생성(사용자 타이핑에 맞춰 실시간 업데이트)을 가능하게 한 기술.
이 글이 도움이 됐다면 다음 포스트도 확인해 보세요:
- "Transformer Architecture Deep Dive" — DiT의 기반.
- "LLVM Compiler Infrastructure" — MLIR이 AI 컴파일러의 기반이 된 배경.
- "RDMA & NCCL" — 대규모 diffusion 모델 훈련의 네트워크 기반.
- "CUDA & GPU Kernels" — diffusion inference 가속.
Diffusion Models Deep Dive — DDPM, Latent Diffusion, Classifier-Free Guidance, DDIM, Stable Diffusion Complete Guide (2025)
TL;DR
- A Diffusion Model is a generative model that "learns gradual noise removal." A forward process progressively adds noise to images, and a reverse process (neural network) undoes it.
- DDPM (2020, Ho et al.): the starting point of modern diffusion. Simplified the variational lower bound into a single noise prediction loss.
- Score Matching: the same idea in different language. Reverse diffusion = score function estimation.
- U-Net: the standard backbone for diffusion. Encoder-decoder with skip connections. Outputs noise at the same size as input.
- Latent Diffusion Model (LDM, 2021): compress images into a latent space with a VAE, then diffuse inside it. 48x compute savings → feasible on consumer GPUs.
- Stable Diffusion = LDM + CLIP text encoder + open-source release (2022, Stability AI).
- Classifier-Free Guidance: combine conditional and unconditional models to tune prompt adherence. The secret behind text-to-image quality.
- DDIM: deterministic sampling. Accelerates 1000 steps to 20 steps.
- Consistency Model: generation in 1-4 steps. Real-time level.
- Conditional Generation: controllable via ControlNet, LoRA, InstructPix2Pix, and more.
- Video and 3D: Sora, Stable Video Diffusion, DreamFusion. Diffusion extends beyond images.
1. Evolution of Generative Models
1.1 The GAN Era (2014-2020)
Ian Goodfellow's GAN (Generative Adversarial Network) in 2014. A Generator produces images, a Discriminator judges "real vs fake." The two networks train by competing.
Advantages:
- One-shot sample generation (fast).
- High-quality images.
Disadvantages:
- Mode collapse: generates only a subset of modes.
- Training instability: highly hyperparameter-sensitive.
- Hard to scale: unstable when extended with more data.
Development continued through StyleGAN (2019), but complex scenes (including text) remained a limit.
1.2 Limits of VAE
VAE (Variational Autoencoder) is stable but produces blurry results. The encoder learns a distribution over latent codes and the decoder reconstructs. Generation is possible but quality lagged behind GANs.
1.3 Limits of Autoregressive Models
PixelRNN, PixelCNN, iGPT: generate pixels sequentially. Good quality but extremely slow (predicting one pixel at a time). Generating a 1024x1024 image = 1 million forward passes.
1.4 Diffusion Arrives (2020)
In 2020, DDPM (Ho, Jain, Abbeel). A "strangely simple" method:
- Gradually add noise to images (forward).
- Train a neural network to predict the noise.
- For generation, start from random noise and iteratively denoise.
Result: samples that are higher quality, more stable, and more diverse than GANs. The community got excited.
1.5 Scaling Success
2021: Dhariwal & Nichol published "Diffusion Beats GANs." SOTA image quality.
2021 GLIDE: OpenAI's text-to-image diffusion. Too slow and heavy though.
2021 LDM: Rombach et al.'s Latent Diffusion. A game changer. Diffusion in latent space rather than pixel space → 50x faster.
2022 DALL-E 2: OpenAI's powerful text-to-image model.
2022 Stable Diffusion: Stability AI open-sourced LDM. Runs on a local GPU. Democratization of generative AI.
2022 Imagen: Google. Proved the importance of the text encoder.
2024 Sora: OpenAI's video diffusion. Minute-long high-quality video.
1.6 Why Did Diffusion Succeed?
Core reason: training is simple and stable. Not a GAN-style min-max game — just plain MSE loss. Improves consistently with scale. More data + bigger model = better results. "Simple things scale."
2. Forward Process — Adding Noise
2.1 The Idea
Gradually add noise to an image x_0:
x_0 (original) → x_1 → x_2 → ... → x_T (nearly pure noise)
A small amount of Gaussian noise per step. T = 1000 (DDPM).
2.2 Equations
Transition at each step:
Meaning:
x_tis sampled from a Gaussian with meansqrt(1 - beta_t) * x_{t-1}and variancebeta_t.beta_tis the noise schedule — how much noise to add at each step.- Small
betaearly (preserve image), largerbetalater (noise dominates).
2.3 Noise Schedule
Linear (original DDPM):
beta_1 = 0.0001
beta_T = 0.02
beta_t = linear interpolation
Cosine (Nichol & Dhariwal, 2021):
alpha_t = cos^2(pi/2 * (t/T + s) / (1 + s))
beta_t = 1 - alpha_t / alpha_{t-1}
Cosine adds noise more slowly early on, which is beneficial at lower resolutions. Most modern models use cosine or variants.
2.4 Closed Form
A convenient property when applied in sequence: you can directly compute x_t for any t.
Define:
Then:
Or in samplable form:
The forward process is computed mathematically without any learning. Given the original x_0 and random noise epsilon, you can instantly produce x_t at any timestep.
2.5 Terminal State
If T is large enough, alpha_bar_T approaches 0 and x_T approaches N(0, I). Pure Gaussian noise independent of the original.
This is key: whatever image you start from, the terminal state is the same. The reverse process can start from pure noise and reach an image.
3. Reverse Process — What Must Be Learned
3.1 Goal
We want to "reverse" the forward process:
The true reverse can be written via Bayes but is intractable. A neural network approximates it.
3.2 Parameterization
Two approaches:
1. Predict the mean mu_theta(x_t, t):
2. Predict the noise epsilon_theta(x_t, t):
Ho et al. showed that directly predicting noise works much better. The mean is then derived via:
3.3 Simplifying the Loss
Deriving the Variational Lower Bound is complex, but Ho et al.'s insight: a plain MSE loss gives nearly the same effect:
In other words:
- Random original image
x_0. - Random timestep t.
- Random noise
epsilon. - Compute
x_tvia forward process. - Give
x_tto the network and let it predictepsilon. - Train with MSE.
Astonishingly simple. No GAN min-max. Pure supervised learning.
3.4 Sampling (Inference)
After training, to generate:
def sample(model, T=1000):
# start: pure noise
x_t = torch.randn(shape)
for t in reversed(range(T)):
# predict noise
epsilon = model(x_t, t)
# compute mean
alpha_t = alphas[t]
alpha_bar_t = alpha_bars[t]
beta_t = betas[t]
mu = (1 / sqrt(alpha_t)) * (x_t - beta_t / sqrt(1 - alpha_bar_t) * epsilon)
# sample next step
if t > 0:
z = torch.randn_like(x_t)
sigma = sqrt(beta_t)
x_t = mu + sigma * z
else:
x_t = mu
return x_t # generated image
Each step calls the model once → next step. 1000 steps = 1000 forward passes. Very slow.
3.5 Why It Works
Intuition: transforming a clean image into a noisy one is stochastic; the reverse is too. With sufficiently small steps, each transition can be approximated as Gaussian. The model only needs to learn "which direction makes things slightly cleaner at the current noise level."
Mathematically this is the discretization of a diffusion SDE. The continuous SDE form:
Reverse SDE (Anderson 1982):
grad_x log p_t(x) is the score function — covered in the next section.
4. Score-Based Perspective
4.1 Score Function
The score of a distribution p(x) is:
"The direction in which probability increases at this point." The gradient pointing toward high-probability regions.
4.2 Score Matching = Diffusion
A surprising equivalence: DDPM noise prediction = score estimation.
Sketch: when x_t ~ N(sqrt(alpha_bar_t) x_0, (1 - alpha_bar_t) I),
So score is proportional to noise. Noise prediction and score estimation are two expressions of the same problem.
4.3 Song and Ermon's Perspective
Yang Song's research (2019-2020) proposed the score-based generative model first. Independent of DDPM but mathematically equivalent.
Advantage: the continuous SDE framework is cleaner. It can also be expressed as an ODE (probability flow ODE).
4.4 Unified Framework
Song et al. 2021 "Score-Based Generative Modeling through SDEs": DDPM, NCSN, and so on are all special cases of the same SDE framework.
Modern diffusion research moves fluidly between SDE and DDPM viewpoints. Practically, DDPM notation is intuitive; theoretically, SDE is more elegant.
5. U-Net Architecture
The backbone of diffusion models is mostly the U-Net.
5.1 Why U-Net?
Requirements of diffusion models:
- Input and output at the same spatial size (image → noise).
- Multi-scale features (globally coherent and locally detailed).
- Preserve spatial information.
U-Net (originally for medical image segmentation, 2015):
- Encoder: resolution down, channels up.
- Decoder: resolution up, channels down.
- Skip connections: directly connect the same level of encoder and decoder.
A perfect match.
5.2 Structure
Input (e.g., 64x64x3)
|
v
Conv -> ResBlock -> Attention
| |
| Downsample (-> 32x32)
| |
| ResBlock -> Attention
| |
| Downsample (-> 16x16)
| |
| ResBlock -> Attention <- Bottleneck
| |
| Upsample (-> 32x32)
| ^ (skip from encoder)
| ResBlock -> Attention
| ^
| Upsample (-> 64x64)
| ^ (skip)
v
Output (64x64x3) — predicted noise
5.3 Timestep Embedding
The U-Net must know the current timestep t. Even for the same image, denoising in "early diffusion (slightly noisy)" vs "late (very noisy)" should differ.
Sinusoidal positional embedding:
Then an MLP — added as a bias into ResBlocks.
5.4 Attention Layers
Diffusion U-Nets include self-attention. Captures long-range dependencies (correlations between distant pixels). Especially near the bottleneck.
5.5 Conditioning
For text-conditioned generation, cross-attention is added:
Image features -> Query
Text features (CLIP) -> Key, Value
The U-Net learns to bridge text and image. This is the core of "following the prompt."
5.6 2025: Diffusion Transformer (DiT)
In 2023, William Peebles et al. proposed the Diffusion Transformer (DiT). A pure Transformer instead of a U-Net.
- Patch-wise input (like ViT).
- Excellent scaling properties.
- The foundation of Sora.
DiT surpasses U-Net at large scale → the trend in 2024-2025 is shifting toward DiT.
6. DDIM — Faster Sampling
6.1 DDPM Is Slow
DDPM samples 1000 steps. Top quality, but too slow. Over a minute.
6.2 The DDIM Insight
Song et al. 2021: the reverse process of DDPM can be made deterministic, letting you skip steps.
Core equation (simplified):
Where:
x_hat_0 is the "current best estimate" — "if I had to produce a clean image right now, this is it."
6.3 Fast Sampling
DDPM needs 1000 steps. DDIM can use any sub-sequence:
timesteps = [0, 50, 100, 150, 200, ..., 950] # 20 steps
50x faster. Quality drops slightly but is nearly identical.
6.4 Various Samplers
Many variants after DDIM:
- Euler: Euler integrator from the ODE viewpoint.
- Heun: 2nd-order Runge-Kutta.
- DPM-Solver: specialized ODE solver for diffusion. 10-25 steps.
- DPM-Solver++: further improved. Current default for Stable Diffusion.
- UniPC: unified predictor-corrector.
All share the same idea: treat sampling as an ODE problem and apply efficient solvers.
7. Classifier-Free Guidance
The most important trick in text-to-image.
7.1 The Problem
Naive conditional generation:
x_t -> model(x_t, text) -> noise
Problem: the model can ignore the text. Text is a weak signal during training.
7.2 Classifier Guidance (old)
Originally proposed by Dhariwal & Nichol. Train a separate classifier:
grad_x log p(y|x) is the classifier gradient. Problem: requires a separate classifier, and it's complex.
7.3 Classifier-Free Guidance (new)
Ho & Salimans 2022: achieve the same effect without a classifier.
At training:
- With 10-20% probability, replace the text with null (empty condition).
- The same model learns both conditional and unconditional generation.
At inference:
noise_cond = model(x_t, text) # conditional prediction
noise_uncond = model(x_t, null) # unconditional prediction
# Extrapolation!
guided_noise = noise_uncond + scale * (noise_cond - noise_uncond)
scale = 1 is plain conditional. scale > 1 amplifies the conditional direction. Typical values: 5-12.
7.4 Why It Works
Intuition: "subtracting unconditional from conditional leaves only the effect of the condition." Amplify that → emphasize the condition. As if saying "be more faithful to the text."
In practice, this determines prompt adherence in text-to-image. Without it, prompts get ignored.
7.5 Trade-off
Raising scale:
- Pros: more accurate prompt following.
- Cons: reduced image diversity.
- Cons: more artifacts (at excessive scale).
Typically 7-12 is the sweet spot.
8. Latent Diffusion Model
8.1 The Problem with Pixel Space
The original DDPM diffuses in pixel space. 512x512x3 = 786,432 dimensions. Each step processes all these dimensions → very expensive.
8.2 The LDM Idea (Rombach et al. 2021)
"There's a lot of waste in pixel space. Most pixels look like their neighbors, and meaningful information lives in far fewer dimensions. Compress with a VAE and diffuse in that space."
Structure:
Image (512x512x3)
|
VAE Encoder
|
Latent (64x64x4) <- diffusion happens here
|
VAE Decoder
|
Image (512x512x3)
The latent space is 64x64x4 = 16,384 dimensions. 1/48 the original. 48x compute savings.
8.3 Training the VAE
LDM uses a pre-trained VAE. The VAE is trained separately:
- Encoder: image → latent.
- Decoder: latent → image.
- Loss: reconstruction + KL + perceptual (LPIPS) + adversarial (discriminator).
Once trained, it's reused across diffusion models.
8.4 Diffusion in Latent Space
VAE is fixed. Standard DDPM runs on top:
latent = vae.encode(image) # image -> latent
noisy_latent = forward_diffusion(latent, t)
predicted_noise = unet(noisy_latent, t, text)
# Loss: MSE between predicted_noise and actual noise
At generation:
noise = torch.randn(1, 4, 64, 64) # latent size
for t in reversed(timesteps):
noise = denoise_step(unet, noise, t, text)
image = vae.decode(noise)
8.5 Benefits Summary
- Compute: 48x faster.
- Memory: also 48x less.
- High resolution possible: 1024x1024 is reasonable.
- Semantic abstraction: latent space learns meaningful representations → better generalization.
8.6 Limitations
- VAE loss: small-detail information loss (text, faces, etc.).
- VAE artifacts: slight blurring or subtle distortion.
- Still overwhelmingly worthwhile.
9. Stable Diffusion
9.1 Composition
Stable Diffusion (2022 Stability AI) = LDM + CLIP + open source.
Components:
- VAE: image ↔ 8x compressed latent.
- CLIP text encoder: text → 768-dim vector.
- U-Net: diffusion in latent space. Text conditioning via cross-attention.
- Scheduler: DDIM, DPM-Solver, etc.
9.2 CLIP Text Encoder
OpenAI CLIP (Contrastive Language-Image Pre-training, 2021). A text/image encoder trained on massive image-text pairs.
Role:
- Prompt → high-dimensional embedding.
- The U-Net's cross-attention references this embedding.
Better CLIP = better prompt understanding. Stable Diffusion uses CLIP ViT-L/14.
9.3 Training Data
LAION-5B: 5 billion image-text pairs crawled from the web. Open, hence reproducible. Also the source of copyright controversy.
9.4 Version Evolution
SD 1.x (2022): first release. 512x512. OpenAI CLIP.
SD 2.x (2022): improved aesthetics. Uses OpenCLIP.
SDXL (2023): larger model, refiner. 1024x1024 native. Significantly better quality.
SD 3 (2024): adopts rectified flow. Built on the Diffusion Transformer.
Flux (2024 Black Forest Labs): a strong successor to SD3. Open-source SOTA.
9.5 Open vs Closed
Stable Diffusion: open-source. Local execution, fine-tuning, and modifications possible.
DALL-E 3, Midjourney: API only. Possibly higher quality, but black boxes.
For research and customization, SD is mainstream. For commercial quality, closed options.
10. Conditional Generation Techniques
10.1 Text-to-Image (basic)
Covered above. Text prompt → image.
10.2 Image-to-Image (img2img)
Start the initial latent not from random noise but from the latent of an existing image.
input_latent = vae.encode(input_image)
noisy = forward_diffuse(input_latent, strength) # partial noise
output = denoise(noisy, text)
At strength = 0.3 it changes slightly; at 0.9 it nearly regenerates. The "edit this image this way" pattern.
10.3 Inpainting
Regenerate only inside the mask. Noise the masked region, keep the rest original.
mask = user_drawn_mask
latent = vae.encode(image)
for t in reversed(timesteps):
# predict noise
noise = unet(noisy, t, text)
# replace outside-mask with original (every step)
noisy = noisy * mask + forward_diffuse(latent, t) * (1 - mask)
Edit specific regions. Photoshop's "generative fill" is this.
10.4 ControlNet
Lvmin Zhang et al. 2023. Control structure via additional conditioning.
Idea: train a "control" network that copies the U-Net. The control network accepts a hint image (edges, poses, depth) and influences the U-Net.
Input image (pose skeleton)
|
ControlNet copy of U-Net
|
Influence on main U-Net
|
Output: matches the prompt but follows the pose
ControlNet variants:
- Canny: edge-based.
- Depth: depth-map-based.
- OpenPose: human-pose-based.
- Scribble: hand sketch.
- Segmentation: semantic mask.
The "specific composition + free style" pattern. Very useful.
10.5 LoRA (Low-Rank Adaptation)
Specialize a pretrained model with a small number of parameters.
Idea: add a low-rank update to each layer's weight W.
B in R^{d x r}, A in R^{r x k}, r << min(d, k).
Train only A and B. Keep original W frozen. Result:
- Far fewer parameters: hundreds of MB → few MB.
- Fast training: learn a specific style/character from thousands of images.
- Swappable: enable or disable multiple LoRAs.
Sites like Civitai have tens of thousands of LoRAs. "This anime character style," "this artist style," and so on.
10.6 DreamBooth
Train on a specific subject (my dog, a specific person). With just 5-10 photos.
Input: a few photos of the dog
Training: bind a unique token like "sks dog" to this dog
Output: "sks dog on the beach" -> your dog at the beach
Combined with LoRA, lightweight DreamBooth is now mainstream.
10.7 Textual Inversion
Learn a new word. Train only the word's embedding while the model stays frozen.
Train a token "<new_concept>"
Its embedding captures a specific style/subject
Lighter but more limited.
10.8 InstructPix2Pix
Edit via natural-language instructions.
Input: image + "remove the person"
Output: image with the person removed
A ChatGPT-style editing interface.
11. Consistency Models — Real-Time Generation
11.1 The Problem
Even DDIM needs 20-50 steps. For real-time (under 100ms), that's not enough.
11.2 Consistency Model (Song et al. 2023)
"Diffusion follows an ODE trajectory. Let's train the model to jump straight to x_0 from any point on that trajectory."
After training, high-quality generation in 1-4 steps.
11.3 Latent Consistency Model
LCM (2023): LDM + Consistency Distillation. Accelerates Stable Diffusion to 2-4 steps.
Existing SDXL: 25 steps x 150ms = 3.75s
LCM SDXL: 4 steps x 150ms = 600ms
Real-time interactive generation becomes possible. As a user types a prompt, results update live.
11.4 SDXL Turbo
Stability AI's 2023 release. Generates SDXL in 1 step. Quality drops slightly but is nearly instant.
11.5 Progressive Distillation
A technique that learns to compress many steps of the original (teacher) model into a single step. Repeatedly halve the step count.
1000 → 500 → 250 → ... → 1 step.
At each stage a student model approximates n teacher steps with 1 step.
12. Video Diffusion
12.1 Naive Approach
Diffuse each frame independently → no temporal consistency. Flicker and character drift.
12.2 Temporal Attention
Add temporal attention layers to the U-Net. Apply attention along the time axis to maintain consistency.
Spatial Attention (positions within an image)
Temporal Attention (across frames)
12.3 Video Diffusion Models
Stable Video Diffusion (2023): image → short video (2-4 seconds).
Sora (2024 OpenAI): minute-long high quality. Built on the Diffusion Transformer. Unified space-time processing in patches.
Sora's secrets:
- DiT architecture (not U-Net).
- Spacetime patches: 3D volumetric processing.
- Massive scale (model + data).
- High-quality captions (GPT-4 generates video descriptions).
13. 3D Diffusion
13.1 DreamFusion
Generate 3D objects using a 2D diffusion model.
Idea: SDS (Score Distillation Sampling). Optimize 3D object parameters (NeRF). The 2D diffusion model evaluates "is this view faithful to the prompt?"
Result: after hours of training, "text → 3D mesh."
13.2 Gaussian Splatting + Diffusion
From 2023+, Gaussian Splatting became the standard 3D representation. Diffusion generates Gaussian parameters.
13.3 Limitations
Much harder than 2D. Data scarcity, quality limits. Currently an active research area.
14. Implementation in Practice
14.1 Hugging Face Diffusers
A Python library. Stable Diffusion in 3 lines:
from diffusers import StableDiffusionPipeline
import torch
pipe = StableDiffusionPipeline.from_pretrained(
"runwayml/stable-diffusion-v1-5",
torch_dtype=torch.float16
).to("cuda")
image = pipe("a photograph of an astronaut riding a horse").images[0]
image.save("astronaut.png")
14.2 Swapping the Scheduler
from diffusers import DPMSolverMultistepScheduler
pipe.scheduler = DPMSolverMultistepScheduler.from_config(
pipe.scheduler.config
)
# now high quality in 20 steps
image = pipe(prompt, num_inference_steps=20).images[0]
14.3 Loading a LoRA
pipe.load_lora_weights("path/to/lora", weight_name="my_style.safetensors")
pipe.fuse_lora(lora_scale=0.7)
image = pipe("a cat in my_style style").images[0]
14.4 ControlNet
from diffusers import StableDiffusionControlNetPipeline, ControlNetModel
controlnet = ControlNetModel.from_pretrained(
"lllyasviel/sd-controlnet-canny"
)
pipe = StableDiffusionControlNetPipeline.from_pretrained(
"runwayml/stable-diffusion-v1-5",
controlnet=controlnet
)
from PIL import Image
edge_image = Image.open("canny_edges.png")
image = pipe(prompt="a modern house", image=edge_image).images[0]
14.5 Inference Optimization
- FP16:
torch_dtype=torch.float16. Half the memory, speed up. - Memory-efficient attention:
pipe.enable_xformers_memory_efficient_attention()or PyTorch 2+'sscaled_dot_product_attention. - VAE tiling: prevents OOM during large-image generation.
- TensorRT / OpenVINO: compiler optimizations. 2-3x speedup.
15. Ethics and Legal Issues
15.1 Copyright
LAION-5B contains copyrighted images. The legality of training is contested.
- Getty Images: lawsuit against Stability AI (2023).
- Andersen v. Stability AI: an artists' class action.
As of 2025, rulings are in progress. Outcomes will affect the entire AI industry.
15.2 Deepfakes
Face swaps, non-consensual imagery. As diffusion quality rises, abuse grows.
Countermeasures:
- Content credentials (C2PA): metadata marking images as AI-generated.
- Watermarking: invisible watermarks like Stable Signature.
- Detection: AI-generated detection models.
15.3 Bias
Training-data bias reflects in outputs. Certain jobs = male, certain appearances = superior. Research and mitigation are active.
15.4 Jobs
Concerns from illustrators and designers. "If AI draws, what do I do?" Debate between "adapt with new tools" and "regulate."
16. Future Directions
16.1 High Quality + Fast Generation
Further progress for consistency models. 1-step high-quality generation.
16.2 Control
Beyond simple text — precise control over pose, composition, color, style.
16.3 Consistency
Consistency across multiple images/frames. Maintaining character identity.
16.4 Multimodal
Unified generation across text + image + audio + video.
16.5 Smaller Models
Acceleration like LCM and Turbo, plus shrinking models. Running on mobile and edge.
16.6 Physical Simulation
A possibility shown by Sora: diffusion "implicitly" learns physical laws. Extension into a "world model."
17. Learning Resources
Papers:
- DDPM (Ho et al. 2020) — essential.
- Latent Diffusion (Rombach et al. 2021).
- Classifier-Free Guidance (Ho & Salimans 2022).
- DDIM (Song et al. 2020).
- Stable Diffusion (2022 Stability AI).
- DiT (Peebles & Xie 2023).
- Consistency Model (Song et al. 2023).
Books/Guides:
- "Hands-On Machine Learning" — Aurelien Geron (extended edition adds diffusion).
- Lilian Weng's blog: "What are Diffusion Models?"
- Jay Alammar's visualization blog.
Code:
- Hugging Face Diffusers library (Python).
- Stability AI's official repo (stability-ai/generative-models).
- AUTOMATIC1111 Stable Diffusion Web UI.
Lectures:
- Yang Song's MIT lecture (score-based models).
- Andrew Ng's generative AI course.
18. Summary — One-Page Cheat Sheet
+-----------------------------------------------------+
| Diffusion Models Cheat Sheet |
+-----------------------------------------------------+
| Core idea: |
| add noise -> network predicts noise -> reverse |
| |
| Forward Process: |
| x_t = sqrt(alpha_bar_t) * x_0 + sqrt(1-abar) * eps |
| computable without learning |
| Noise schedule: linear, cosine |
| |
| Reverse Process: |
| learn network eps_theta(x_t, t) |
| Loss: MSE(eps, eps_theta) |
| Simple, stable, scalable |
| |
| Mathematical view: |
| DDPM: variational bound |
| Score matching: grad log p(x) |
| SDE: dx = f dt + g dW |
| ODE: probability flow |
| |
| U-Net architecture: |
| Encoder-decoder + skip |
| Timestep embedding (sinusoidal) |
| Self-attention + Cross-attention (text) |
| 2024+: Diffusion Transformer (DiT) |
| |
| Sampling: |
| DDPM: 1000 steps, slow |
| DDIM: deterministic, 20-50 steps |
| DPM-Solver++: 10-25 steps |
| Consistency Model: 1-4 steps |
| |
| Latent Diffusion (LDM): |
| VAE encoder: image -> latent |
| diffuse in latent (48x savings) |
| VAE decoder: latent -> image |
| foundation of Stable Diffusion |
| |
| Classifier-Free Guidance: |
| Train: 10% null condition |
| Infer: uncond + scale*(cond - uncond) |
| scale 7-12 = prompt faithful |
| |
| Conditional control: |
| Text: CLIP + cross-attention |
| Image: img2img |
| Structure: ControlNet (canny, pose, depth) |
| Style: LoRA |
| Subject: DreamBooth |
| Edit: InstructPix2Pix, inpainting |
| |
| Production: |
| Stable Diffusion (open) |
| DALL-E 3, Midjourney (closed) |
| Flux (2024+, SOTA open) |
| |
| Extensions: |
| Video: Sora, Stable Video Diffusion |
| 3D: DreamFusion |
| Audio: AudioLDM |
+-----------------------------------------------------+
19. Quiz
Q1. Why is the DDPM training loss just MSE?
A. Ho et al. (2020)'s key insight — after simplifying the variational lower bound mathematically, each step boils down to the "MSE between real noise and predicted noise". Originally there are complex KL-divergence terms, but after reparameterization and clever derivation, most terms vanish and only the noise-prediction error remains. This is why diffusion training is plain supervised learning rather than a GAN-style unstable min-max game. Because the loss is simple, it improves consistently with scale and is less sensitive to hyperparameters. A classic example of "simple things scale."
Q2. How does Latent Diffusion cut compute by 48x?
A. Compress the image with a VAE and diffuse in the latent space. Instead of the original 512x512x3 = 786,432-dim pixel space, denoising runs in the 64x64x4 = 16,384-dim VAE latent space. Each step processes a tensor 48x smaller → both compute and memory drop by 48x. The VAE is pre-trained and frozen during diffusion training. Loss is minor (because VAE reconstruction is high quality). This simple change shifted things from "needs a datacenter" to "runs on a consumer GPU," which is the backdrop that let Stable Diffusion democratize via open source. A case where a small structural change produces social impact.
Q3. How does Classifier-Free Guidance work?
A. At training, with 10-20% probability the text condition is replaced with null (empty condition), so the same model learns both conditional and unconditional generation. At inference, compute two predictions: noise_cond = model(x, text) and noise_uncond = model(x, null). Then extrapolate: guided = uncond + scale * (cond - uncond). scale > 1 means "exaggerate in the conditional direction" → more prompt-faithful. Intuitively, it amplifies "subtracting unconditional from conditional leaves the pure effect of the condition." Scale 7-12 is the sweet spot. This simple trick determines the practical quality of text-to-image — without it, prompts get ignored.
Q4. What's the relationship between the score-based view and the DDPM view?
A. Mathematically equivalent. Yang Song's score-based generative models (2019) and Ho's DDPM (2020) were developed independently but are two expressions of the same thing. Estimating the score function grad_x log p(x) and "predicting noise epsilon" are related by a constant factor: grad_{x_t} log p(x_t) = -epsilon / sqrt(1 - alpha_bar_t). Song et al. 2021 unified both in the SDE framework. In practice, DDPM notation is intuitive and code is simpler; theoretically, SDE/score is elegant and handy for continuous limits. Moving fluently between the two makes papers much easier to read.
Q5. Why is DDIM 50x faster than DDPM?
A. It makes sampling deterministic so you can skip steps. DDPM's reverse process is stochastic (adds random noise every step), so you must step through 1000 steps sequentially. DDIM reinterprets the same trained model as a deterministic ODE trajectory — the "direction from current x_t to x_{t-1}" is mathematically fixed. Because it's deterministic, jumping on a sub-sequence (e.g., [0, 50, 100, ..., 950] 20 steps) is mathematically sensible. Quality drops slightly but is nearly identical. Later DPM-Solver and DPM-Solver++ cut it further to 10-25 steps with more efficient ODE solvers. All build on the "DDIM deterministic path" idea.
Q6. How is ControlNet different from existing conditional generation?
A. Trains an additional copy of the U-Net for structural control. Existing cross-attention text conditioning controls "style/content" but is poor at "exact composition/pose." ControlNet makes a copy of the U-Net encoder, takes new inputs (canny edges, pose skeleton, depth map, etc.), and influences each layer of the original U-Net. The original U-Net stays frozen, and only the ControlNet portion trains → possible with small data. Result: "composition from this sketch + content from the prompt" combined precisely. Turn a photo's pose into manga style, or render from a building layout, etc. Essential when fine control is needed in practice. Standard SD feature since 2023.
Q7. Why can Consistency Models generate in 1-4 steps?
A. The model is trained to jump directly to x_0 from any point on the trajectory. Vanilla diffusion learns "a step cleaner at the current step," whereas the Consistency Model learns "from the current step, go all the way clean." This is possible because diffusion's probability-flow ODE trajectory is deterministic — a consistency condition is added to the loss requiring all points on the same trajectory to converge to the same x_0. After training, 1 step gives a decent result and 2-4 steps give high quality. Latent Consistency Model (LCM) applies this to LDM and runs SDXL in 4 steps. The technology that enables real-time interactive generation (results update live as the user types).
If you found this helpful, check out these related posts:
- "Transformer Architecture Deep Dive" — the foundation for DiT.
- "LLVM Compiler Infrastructure" — background on how MLIR became the foundation for AI compilers.
- "RDMA and NCCL" — the networking foundation for training large diffusion models.
- "CUDA and GPU Kernels" — accelerating diffusion inference.