CS231n Lecture 14 - Generative Models 2

LECTURE 글 목록
목차

핵심 한 줄 정리

GAN은 discriminator와 generator의 adversarial game으로 data distribution을 암묵적으로 맞추고, diffusion과 rectified flow는 noise와 data 사이의 경로를 학습해 반복적인 reverse process로 sample을 생성한다.

반드시 기억할 개념

Implicit generative model

Explicit density model은 주어진 sample xx에 대해 model density pθ(x)p_\theta(x) 또는 그 lower bound를 계산한다. Autoregressive model은 exact likelihood를, VAE는 ELBO를 제공한다.

Implicit generative model은 pθ(x)p_\theta(x)의 값을 직접 계산하지 않는다. 대신 simple distribution에서 latent 또는 noise를 sampling하고, 이를 data sample로 바꾸는 절차를 학습한다.

zp(z)z \sim p(z) xpg(x)x \sim p_g(x)

p(z)p(z)는 standard Gaussian처럼 쉽게 sampling할 수 있는 distribution이고, pg(x)p_g(x)는 learned generation process가 암묵적으로 정의하는 distribution이다.

GAN은 generator forward 한 번으로 sample을 만드는 direct sampling 방식이다. Diffusion model은 여러 denoising 또는 integration step을 반복하는 iterative sampling 방식이다.

GAN의 목표

Training data는 알 수 없는 true distribution에서 sampling되었다고 가정한다.

xpdata(x)x \sim p_{\text{data}}(x)

Generative Adversarial Network, GAN은 generator GθG_\theta가 만든 distribution pgp_gpdatap_{\text{data}}와 같게 만드는 것이 목표이다.

먼저 known prior에서 latent vector를 sampling한다.

zp(z)z \sim p(z) p(z)=N(0,I)p(z) = \mathcal{N}(0,I)

Generator는 zz를 data space의 sample로 mapping한다.

x~=Gθ(z)\tilde{x} = G_\theta(z)

Generator parameter θ\theta가 정해지면 zx~z\mapsto\tilde{x} mapping이 generated distribution pg(x)p_g(x)를 암묵적으로 정의한다. pg(x)p_g(x)의 density 값은 계산하지 못하더라도 zz를 뽑아 sample을 생성할 수 있다.

Generator와 discriminator

GAN은 generator가 만든 sample과 real sample을 구분하는 discriminator DϕD_\phi를 함께 학습한다.

Dϕ(x)(0,1)D_\phi(x) \in (0,1)

Dϕ(x)D_\phi(x)는 input xx가 real data일 probability를 나타낸다.

  • D(x)=1D(x)=1에 가까우면 real이라고 판단한 것이다.
  • D(x)=0D(x)=0에 가까우면 generated sample이라고 판단한 것이다.

Discriminator는 real과 fake를 정확히 구분하려 한다. Generator는 discriminator가 generated sample을 real이라고 판단하게 만들려 한다.

Generator는 정답 image와 직접 비교하는 reconstruction loss를 받지 않는다. Generated image가 discriminator를 통과할 때 생기는 gradient가 discriminator에서 image를 거쳐 generator까지 backpropagation된다.

zGθ(z)Dϕ(Gθ(z))Lz \longrightarrow G_\theta(z) \longrightarrow D_\phi(G_\theta(z)) \longrightarrow \mathcal{L}

Discriminator는 fixed dataset만 분류하는 일반적인 classifier와 다르다. Generator가 학습하면서 fake distribution이 계속 변하므로 discriminator가 풀어야 하는 classification problem도 non-stationary하다.

%% title: GAN의 Generator·Discriminator 경쟁 구조
%% caption: Generator는 latent noise를 fake sample로 바꾸고, discriminator는 real data와 fake sample을 구분한다. 두 network는 반대 목표를 번갈아 최적화한다.
flowchart LR
    z["Latent Noise<br/>z ~ p(z)"] --> generator["Generator G"]
    generator --> fake["Fake Sample G(z)"]
    real["Real Sample<br/>x ~ p_data"] --> discriminator["Discriminator D"]
    fake --> discriminator
    discriminator --> realprob["Probability of Real"]
    realprob --> dloss["D: real ↑, fake ↓"]
    realprob --> gloss["G: fake를 real로 판단하게"]
    dloss -. "update" .-> discriminator
    gloss -. "gradient through D" .-> generator

GAN minimax objective

Original GAN objective는 다음과 같다.

minGmaxDV(D,G)\min_G \max_D V(D,G) V(D,G)=Expdata[logD(x)]+Ezp(z)[log(1D(G(z)))]V(D,G) = \mathbb{E}_{x\sim p_{\text{data}}} \left[ \log D(x) \right] + \mathbb{E}_{z\sim p(z)} \left[ \log \left( 1-D(G(z)) \right) \right]

Discriminator는 V(D,G)V(D,G)를 maximize한다.

  • Real sample에서는 D(x)1D(x)\rightarrow1을 원한다.
  • Fake sample에서는 D(G(z))0D(G(z))\rightarrow0을 원한다.

Generator는 V(D,G)V(D,G)를 minimize한다. 첫 번째 term은 GG와 관계없으므로 generator는 두 번째 term만 바꿀 수 있다. Generator가 성공하려면 D(G(z))1D(G(z))\rightarrow1이 되어야 한다.

Alternating optimization

Generator와 discriminator는 같은 parameter를 공유하지 않으며 서로 반대 목표를 가진다. 따라서 minibatch마다 두 optimization을 번갈아 수행한다.

Discriminator loss를 minimize하는 형태로 쓰면 다음과 같다.

LD=Expdata[logD(x)]Ezp(z)[log(1D(G(z)))]\mathcal{L}_D = -\mathbb{E}_{x\sim p_{\text{data}}} \left[ \log D(x) \right] - \mathbb{E}_{z\sim p(z)} \left[ \log \left( 1-D(G(z)) \right) \right]

한 iteration은 다음과 같이 볼 수 있다.

  1. Real minibatch xx와 latent minibatch zz를 sampling한다.
  2. G(z)G(z)를 만들되 discriminator update에서는 generator gradient를 막는다.
  3. LD\mathcal{L}_D로 discriminator를 update한다.
  4. 새 latent zz를 sampling해 G(z)G(z)를 만든다.
  5. Discriminator를 통과한 gradient로 generator를 update한다.

Discriminator를 여러 번 update한 뒤 generator를 한 번 update하거나, 두 network에 다른 learning rate를 사용하는 등 balance를 조정할 수 있다. 어느 한쪽이 지나치게 앞서면 상대 network가 유용한 gradient를 받지 못한다.

Saturating generator loss의 문제

Original minimax formulation에서 generator가 minimize하는 term은 다음과 같다.

LG,sat=Ezp(z)[log(1D(G(z)))]\mathcal{L}_{G,\text{sat}} = \mathbb{E}_{z\sim p(z)} \left[ \log \left( 1-D(G(z)) \right) \right]

Training 초기에 generator는 거의 random noise를 만들고 discriminator는 real과 fake를 쉽게 구분한다.

D(G(z))0D(G(z)) \approx 0

이 영역에서는 sigmoid와 log objective가 포화되어 generator가 작은 gradient를 받을 수 있다. Generator가 개선되기 전에 학습이 매우 느려지는 문제이다.

실제로는 다음 non-saturating generator loss를 많이 사용한다.

LG,NS=Ezp(z)[logD(G(z))]\mathcal{L}_{G,\text{NS}} = -\mathbb{E}_{z\sim p(z)} \left[ \log D(G(z)) \right]

두 objective는 모두 D(G(z))1D(G(z))\rightarrow1을 원하지만 non-saturating loss는 discriminator가 fake를 자신 있게 구분하는 초기 구간에서 더 큰 gradient를 제공한다.

Optimal discriminator와 distribution matching

Generator GG를 고정했을 때 pointwise optimal discriminator는 다음과 같다.

DG(x)=pdata(x)pdata(x)+pg(x)D_G^*(x) = \frac{ p_{\text{data}}(x) }{ p_{\text{data}}(x)+p_g(x) }

이를 original minimax objective에 대입하면 다음 관계를 얻는다.

V(DG,G)=log4+2DJS(pdatapg)V(D_G^*,G) = -\log4 + 2D_{\mathrm{JS}} \left( p_{\text{data}} \parallel p_g \right)

Jensen-Shannon divergence는 두 distribution이 같을 때 0이다. 따라서 infinite capacity의 GGDD, optimal discriminator, 완전한 optimization을 가정하면 global optimum은 다음 조건에서 생긴다.

pg=pdatap_g = p_{\text{data}}

하지만 이 결과는 실제 training이 그 optimum에 도달한다는 것을 보장하지 않는다. Neural network는 finite capacity이고 discriminator도 매 step 최적화되지 않으며, data도 finite sample만 관찰한다. Minimax optimization의 dynamics가 불안정한 문제는 그대로 남는다.

GAN loss를 해석하기 어려운 이유

일반적인 supervised model은 loss가 감소하면 training objective가 개선되고 있다고 해석할 수 있다. GAN에서는 generator와 discriminator가 동시에 바뀌므로 한쪽 loss의 절댓값만으로 sample quality를 판단하기 어렵다.

같은 generator loss도 discriminator가 약해서 쉽게 속는 경우와 generator가 좋아서 강한 discriminator를 속인 경우에 모두 나타날 수 있다. Discriminator loss 역시 generator distribution이 계속 변하므로 stationary benchmark가 아니다.

따라서 GAN training에서는 다음을 함께 확인해야 한다.

  • 일정한 latent seed에서 생성되는 sample의 변화
  • Sample diversity와 class coverage
  • Nearest training sample과의 차이
  • Fréchet Inception Distance, FID 같은 별도의 distribution-level metric
  • Gradient norm, activation, NaN과 infinity 발생 여부

GAN loss curve가 쓸모없다는 뜻은 아니다. Optimization failure를 찾는 신호는 될 수 있지만, loss 하나가 perceptual quality를 직접 나타내지는 않는다.

FID는 real image와 generated image를 Inception feature space로 옮긴 뒤, 두 feature distribution을 Gaussian으로 근사하여 mean과 covariance의 차이를 측정한다. 값이 낮을수록 generated distribution이 real distribution에 가깝다고 해석하지만, feature extractor와 sample 수의 영향을 받으므로 단독 기준으로 사용하면 안 된다.

Mode collapse

Mode collapse는 서로 다른 latent zz가 소수의 비슷한 output으로 mapping되는 현상이다.

z1z2z_1 \ne z_2 G(z1)G(z2)G(z_1) \approx G(z_2)

극단적으로 generator가 training sample 몇 개만 memorization하고 거의 모든 zz에서 그 sample들만 출력할 수 있다. 이 경우 일부 output은 매우 realistic해서 discriminator를 속일 수 있지만 pdatap_{\text{data}}의 다양한 mode를 덮지 못한다.

Mode collapse는 sample quality와 diversity가 다른 축이라는 점을 보여준다. 선명한 image 몇 장만 반복하는 model은 좋은 generative model이 아니다.

GAN latent space

잘 학습된 GAN에서는 두 latent vector 사이를 interpolation할 때 output도 부드럽게 변하는 경우가 많다.

z(α)=(1α)z0+αz1z(\alpha) = (1-\alpha)z_0 + \alpha z_1 0α10 \le \alpha \le 1 x(α)=G(z(α))x(\alpha) = G(z(\alpha))

StyleGAN 계열에서는 latent를 이동할 때 얼굴이나 animal의 shape, pose, texture가 연속적으로 변하는 모습을 볼 수 있다. 이는 generator가 latent space에 data structure를 어느 정도 연속적으로 배치했음을 나타낸다.

하지만 smooth latent space는 GAN objective가 보장하는 성질이 아니다. Mode collapse처럼 zz를 무시하는 solution도 가능하다.

Standard GAN에는 VAE encoder에 해당하는 xzx\rightarrow z mapping이 없다. Generator는 zxz\rightarrow x만 학습한다. 주어진 image에 대응하는 latent를 찾으려면 zz를 직접 optimization하거나 별도의 encoder를 추가해야 한다.

DCGAN과 StyleGAN

DCGAN은 convolutional generator와 discriminator, batch normalization, strided convolution 같은 architecture guideline을 사용해 image GAN의 안정성과 sample quality를 크게 높인 초기 model이다. 제시된 architecture는 대략 5-layer ConvNet으로 구성되었다.

StyleGAN 계열은 latent를 여러 layer에 주입하고 feature statistics를 조절하는 방식으로 고해상도 image와 controllable latent space를 만들었다. 복잡한 architecture와 training recipe가 필요하지만 GAN이 매우 선명한 sample을 만들 수 있음을 보여준다.

Inference에서는 discriminator를 버리고 generator만 사용한다.

zp(z)z \sim p(z) x=G(z)x = G(z)

Generator forward 한 번이면 되므로 sampling 속도가 빠르다. 반면 adversarial training의 불안정성, mode collapse, scale 확장의 어려움 때문에 image generation의 중심은 점차 diffusion 계열로 이동하였다.

Diffusion model의 핵심 직관

Diffusion model도 simple noise distribution과 complex data distribution 사이의 mapping을 학습한다. GAN이 한 번의 deterministic generator forward로 zzxx로 바꾸는 데 비해 diffusion model은 여러 intermediate noise level을 거쳐 이동한다.

Continuous image space에서는 noise와 data가 같은 shape를 갖는다.

x,zRH×W×Cx,z \in \mathbb{R}^{H\times W\times C} zN(0,I)z \sim \mathcal{N}(0,I)

Noise level tt00에서 11 사이로 두면 다음처럼 해석할 수 있다.

  • t=0t=0은 clean data이다.
  • 0<t<10<t<1은 data와 noise가 섞인 intermediate state이다.
  • t=1t=1은 pure noise이다.

Training에서는 clean sample에 known noise를 섞고, model이 noise를 제거하는 데 필요한 direction이나 target을 예측하게 한다. Sampling에서는 pure noise에서 시작해 t=1t=1에서 t=0t=0으로 반복 이동한다.

Forward corruption과 reverse generation

Diffusion 계열은 data distribution을 점차 simple noise distribution으로 바꾸는 forward process를 정의한다.

x0pdatax_0 \sim p_{\text{data}} xtqt(xtx0)x_t \sim q_t(x_t\mid x_0)

tt가 커질수록 xtx_t에서 original data information은 줄어들고 noise가 많아진다.

Forward process는 training data와 noise를 알고 있으므로 직접 sampling할 수 있다. 어려운 부분은 reverse process이다.

x1pnoisex_1 \sim p_{\text{noise}} x1x1Δtx0x_1 \rightarrow x_{1-\Delta t} \rightarrow \cdots \rightarrow x_0

Model은 각 xtx_t와 noise level tt를 보고 clean-data direction을 예측한다. 여러 작은 reverse step을 누적하면 noise sample이 generated data로 변한다.

%% title: Forward Corruption과 Reverse Generation
%% caption: Forward process는 clean data에 noise를 더해 단순한 분포로 이동하고, generation은 learned field를 따라 pure noise에서 clean sample 방향으로 여러 step 이동한다.
flowchart LR
    data["Clean Data x₀<br/>t = 0"] --> n1["Low Noise xₜ₁"]
    n1 --> n2["Medium Noise xₜ₂"]
    n2 --> noise["Pure Noise x₁<br/>t = 1"]
    noise -. "reverse step" .-> r2["Denoised State"]
    r2 -. "reverse step" .-> r1["Denoised State"]
    r1 -. "reverse step" .-> sample["Generated Sample x₀"]

Rectified flow

Rectified flow는 noise sample과 data sample을 직선으로 연결하고 그 velocity field를 학습하는 formulation이다. 엄밀한 문헌에서는 diffusion과 flow matching을 구분하기도 하지만, noise에서 data로 iterative transport를 학습한다는 공통 직관으로 함께 볼 수 있다.

Training iteration마다 다음을 sampling한다.

xpdata(x)x \sim p_{\text{data}}(x) zN(0,I)z \sim \mathcal{N}(0,I) tU(0,1)t \sim \mathcal{U}(0,1)

Data와 noise 사이의 interpolation은 다음과 같다.

xt=(1t)x+tzx_t = (1-t)x + tz

t=0t=0이면 xt=xx_t=x이고 t=1t=1이면 xt=zx_t=z이다.

Data에서 noise로 향하는 ground-truth velocity는 다음과 같다.

vgt=dxtdt=zxv_{\text{gt}} = \frac{d x_t}{dt} = z-x

Neural network vθv_\theta는 noisy sample xtx_t와 time tt를 받아 velocity를 예측한다.

v^=vθ(xt,t)\hat{v} = v_\theta(x_t,t)

Training objective는 단순한 mean squared error이다.

LRF=Ex,z,t[vθ(xt,t)(zx)22]\mathcal{L}_{\text{RF}} = \mathbb{E}_{x,z,t} \left[ \left\lVert v_\theta(x_t,t) - (z-x) \right\rVert_2^2 \right]

GAN과 달리 한 network와 direct regression loss를 사용한다. Loss가 낮아지는 과정을 관찰할 수 있고 large model과 dataset으로 scale하기도 상대적으로 쉽다.

Rectified flow sampling

Sampling은 noise에서 시작한다.

x1N(0,I)x_1 \sim \mathcal{N}(0,I)

Learned velocity는 increasing tt 방향, 즉 data에서 noise로 향한다. Sample을 만들려면 t=1t=1에서 t=0t=0으로 ODE를 backward integration한다.

dxtdt=vθ(xt,t)\frac{dx_t}{dt} = v_\theta(x_t,t)

KK개 Euler step을 사용하고 Δt=1/K\Delta t=1/K라고 하면 다음과 같이 update할 수 있다.

xtΔt=xtΔtvθ(xt,t)x_{t-\Delta t} = x_t - \Delta t\, v_\theta(x_t,t)

이를 t=1t=1부터 00까지 반복하면 final sample x0x_0을 얻는다. 시작점으로 50 step을 사용할 수 있고, model과 solver가 충분하면 약 30 step에서도 reasonable한 결과를 얻을 수 있다.

Euler method는 가장 단순한 numerical integrator이다. 더 정교한 ODE solver를 사용하면 같은 quality를 더 적은 function evaluation으로 얻거나 integration error를 줄일 수 있다.

Generalized noising과 prediction target

Rectified flow는 다음 generalized formulation의 단순한 경우로 볼 수 있다.

xt=a(t)x+b(t)zx_t = a(t)x + b(t)z

Model target도 clean data와 noise의 linear combination으로 둘 수 있다.

yt=c(t)x+d(t)zy_t = c(t)x + d(t)z L=E[fθ(xt,t)yt22]\mathcal{L} = \mathbb{E} \left[ \left\lVert f_\theta(x_t,t)-y_t \right\rVert_2^2 \right]

Method에 따라 model은 다음 중 하나를 예측할 수 있다.

  • Clean sample xx
  • Added noise zz
  • Velocity처럼 xxzz의 linear combination
  • Distribution의 score와 비례하는 quantity

Variance-preserving schedule은 data와 noise가 unit variance이고 independent일 때 xtx_t의 variance를 일정하게 유지하도록 a(t)a(t)b(t)b(t)를 고른다. Variance-exploding schedule은 data에 점점 큰 noise scale을 더한다.

Notation과 target은 달라도 noisy input과 time을 받아 known target을 regression한다는 공통 구조가 있다.

Noise-level sampling

Rectified flow의 기본 예에서는 tU(0,1)t\sim\mathcal{U}(0,1)을 사용한다. 이는 모든 noise level에 같은 sampling probability를 준다.

하지만 양 끝은 상대적으로 쉬울 수 있다. Pure noise에 가까우면 average data direction을 예측하는 문제가 되고, clean data에 가까우면 noise distribution의 mean 방향을 예측하는 문제가 된다. 중간 noise level에서는 같은 xtx_t를 만들 수 있는 data-noise pair가 여러 개이므로 conditional expectation을 추론하기 더 어렵다.

Logit-normal schedule은 tt의 양 끝보다 중간 구간에 더 많은 weight를 줄 수 있다. Shifted schedule은 resolution과 data correlation에 맞춰 특정 noise 영역을 강조한다.

High-resolution image는 neighboring pixel의 correlation이 강하다. 같은 noise schedule을 resolution만 바꾸어 그대로 사용하면 information destruction 정도가 달라질 수 있으므로 noise-level distribution과 schedule도 함께 조정해야 한다.

Conditional rectified flow

Condition yy가 있는 data pair를 사용하면 model input에 yy를 추가하면 된다.

(x,y)pdata(x,y)(x,y) \sim p_{\text{data}}(x,y) v^=vθ(xt,t,y)\hat{v} = v_\theta(x_t,t,y) Lcond=E[vθ(xt,t,y)(zx)22]\mathcal{L}_{\text{cond}} = \mathbb{E} \left[ \left\lVert v_\theta(x_t,t,y) - (z-x) \right\rVert_2^2 \right]

yy는 class label, text embedding, reference image, segmentation map 등이 될 수 있다. Sampling의 모든 reverse step에 같은 condition을 주면 condition에 맞는 data distribution 쪽으로 이동한다.

Classifier-free guidance

Conditional model은 condition을 무시하거나 약하게 반영할 수 있다. Classifier-free guidance, CFG는 한 network가 conditional prediction과 unconditional prediction을 모두 학습하게 한다.

Training 중 일정 probability로 condition yy를 null token으로 바꾼다.

y~={y,condition 유지,condition 제거\tilde{y} = \begin{cases} y, & \text{condition 유지} \\ \varnothing, & \text{condition 제거} \end{cases}

제시된 설정에서는 condition을 50%50\% 확률로 제거한다. 이는 고정 규칙이 아니라 조절 가능한 hyperparameter이다.

Sampling 시 같은 (xt,t)(x_t,t)에 대해 model을 두 번 평가한다.

vcond=vθ(xt,t,y)v_{\text{cond}} = v_\theta(x_t,t,y) vuncond=vθ(xt,t,)v_{\text{uncond}} = v_\theta(x_t,t,\varnothing)

Guided velocity는 다음과 같다.

vCFG=(1+w)vcondwvuncondv_{\text{CFG}} = (1+w)v_{\text{cond}} - w v_{\text{uncond}}

같은 식을 다음 형태로 볼 수도 있다.

vCFG=vuncond+s(vcondvuncond)v_{\text{CFG}} = v_{\text{uncond}} + s \left( v_{\text{cond}}-v_{\text{uncond}} \right)

여기서 s=1+ws=1+w이다. w=0w=0이면 raw conditional prediction을 사용하고, ww를 높일수록 unconditional direction에서 conditional direction 쪽으로 더 멀리 extrapolation한다.

Guidance scale을 높이면 prompt adherence와 visual sharpness가 좋아질 수 있지만 diversity가 줄고 artifact가 생길 수 있다. 또한 naive CFG는 매 sampling step마다 network를 두 번 평가하므로 inference compute가 약 2배가 된다.

%% title: Classifier-Free Guidance의 두 Prediction
%% caption: 같은 noisy state에 conditional·unconditional prediction을 둘 다 계산하고, 두 방향의 차이를 확대해 condition을 더 강하게 따르는 update를 만든다.
flowchart LR
    state["Noisy State xₜ + Time t"] --> cond["Model with Condition y<br/>v_cond"]
    state --> uncond["Model with Null Condition ∅<br/>v_uncond"]
    cond --> guide["v_CFG = v_uncond<br/>+ s(v_cond - v_uncond)"]
    uncond --> guide
    guide --> update["Guided Reverse Update"]
    update --> next["x_t-Δt"]

Latent diffusion

Pixel-space diffusion은 high-resolution tensor 전체에서 여러 번 network를 평가해야 하므로 매우 비싸다. Latent diffusion은 먼저 autoencoder로 image를 spatially 압축하고 diffusion model은 latent space에서 학습한다.

Encoder와 decoder는 다음 mapping을 학습한다.

h=E(x)h = E(x) x^=D(h)\hat{x} = D(h)

예시 구성은 spatial dimension을 각 축에서 8배 downsampling하고 RGB 3 channel을 latent 16 channel로 바꾼다.

xRH×W×3x \in \mathbb{R}^{H\times W\times3} hRH8×W8×16h \in \mathbb{R}^{\frac{H}{8}\times\frac{W}{8}\times16}

각 spatial 축이 8배 줄어들면 token 위치 수는 pixel space의 1/641/64이 된다. Channel 수는 늘지만 expensive backbone이 처리하는 spatial sequence는 크게 짧아진다.

Training은 두 stage로 나뉜다.

  1. Autoencoder E,DE,D를 image reconstruction으로 학습한다.
  2. Encoder를 freeze하고 h=E(x)h=E(x)를 추출한다.
  3. Latent hh에 noise를 더해 diffusion 또는 flow model을 학습한다.

Diffusion training gradient를 encoder로 전파하지 않는 것이 중요하다. Latent space가 계속 변하면 diffusion model의 target distribution도 non-stationary해진다.

Sampling에서는 latent noise에서 clean latent를 만든 뒤 decoder로 image를 복원한다.

zhN(0,I)z_h \sim \mathcal{N}(0,I) zhiterative generationh0z_h \xrightarrow{\text{iterative generation}} h_0 x^=D(h0)\hat{x} = D(h_0)
%% title: Latent Diffusion의 두 단계 Pipeline
%% caption: Autoencoder가 pixel image를 작은 spatial latent로 압축하고, diffusion·flow backbone은 고비용 반복 계산을 latent space에서 수행한다. 최종 clean latent만 decoder로 image로 복원한다.
flowchart LR
    image["Training Image<br/>H × W × 3"] --> encoder["Frozen Autoencoder E"]
    encoder --> latent["Latent h<br/>H/8 × W/8 × 16"]
    latent --> noise["Add Noise at t"]
    text["Optional Condition<br/>Text / Class"] --> model["Latent Diffusion or Flow Model"]
    noise --> model
    model --> objective["Noise / Velocity Target Loss"]
    start["Latent Noise"] --> reverse["Iterative Reverse Process"]
    text --> reverse
    model -. "learned field" .-> reverse
    reverse --> clean["Clean Latent h₀"]
    clean --> decoder["Autoencoder Decoder D"]
    decoder --> output["Generated Image"]

Autoencoder에 adversarial loss를 더하는 이유

Gaussian reconstruction loss만 사용한 VAE decoder는 가능한 detail을 평균내 blurry reconstruction을 만들 수 있다. Latent diffusion의 최종 image quality는 decoder reconstruction quality보다 좋아질 수 없으므로 autoencoder 자체가 sharp한 image를 복원해야 한다.

이를 위해 reconstruction loss, perceptual loss, latent regularization에 adversarial discriminator loss를 함께 사용할 수 있다.

LAE=λrecLrec+λpercLperceptual+λadvLadv+λregLlatent\mathcal{L}_{\text{AE}} = \lambda_{\text{rec}} \mathcal{L}_{\text{rec}} + \lambda_{\text{perc}} \mathcal{L}_{\text{perceptual}} + \lambda_{\text{adv}} \mathcal{L}_{\text{adv}} + \lambda_{\text{reg}} \mathcal{L}_{\text{latent}}

따라서 modern latent diffusion pipeline은 VAE 계열의 encoder-decoder, GAN 계열의 discriminator, diffusion 또는 flow model을 결합한다. 서로 경쟁하던 generative model 계열이 실제 system에서는 역할별 component로 함께 쓰이는 셈이다.

Diffusion Transformer

Diffusion Transformer, DiT는 noisy latent를 token sequence로 바꾸고 Transformer block으로 prediction target을 계산한다. Model은 최소한 세 종류의 input을 받는다.

  • Noisy latent xtx_t
  • Noise level 또는 timestep tt
  • Text 같은 condition yy

Timestep embedding은 scale과 shift를 예측해 normalized activation을 modulation하는 방식으로 주입할 수 있다.

h=γ(t)Norm(h)+β(t)h' = \gamma(t) \odot \operatorname{Norm}(h) + \beta(t)

Text condition은 cross-attention으로 image token이 text token을 참조하게 하거나, text와 image token을 하나의 sequence로 합친 joint attention으로 처리할 수 있다.

U-Net은 multi-scale convolution과 skip connection으로 diffusion model의 표준 architecture 역할을 오랫동안 맡았다. DiT는 Transformer scaling과 distributed training infrastructure를 활용하기 쉬워 large model에서 널리 사용된다.

Text-to-image pipeline

Text-to-image latent diffusion은 다음 component로 구성할 수 있다.

  1. Frozen text encoder가 prompt를 text embedding으로 바꾼다.
  2. Latent noise와 text embedding, timestep을 DiT에 넣는다.
  3. CFG를 적용한 prediction으로 latent를 반복 update한다.
  4. Clean latent를 autoencoder decoder로 image pixel에 복원한다.

Text encoder로 T5나 CLIP 계열을 사용할 수 있다. 제시된 FLUX.1-dev 예시는 T5와 CLIP encoder, 8배 spatial downsampling encoder, 12-billion-parameter Transformer를 사용하며 추가 downsampling 뒤 1,024개의 image token을 처리한다.

Prompt 예시는 다음처럼 object, relation, location, attribute를 함께 포함한다.

A professional documentary photograph of a monkey shaking hands with a tiger in front of the Eiffel Tower. The monkey is wearing a hat made out of bananas. The tiger is standing on two legs and wearing a suit.

이처럼 복합적인 condition을 따르려면 text encoder와 diffusion backbone이 object identity뿐 아니라 relation과 attribute binding도 학습해야 한다.

Text-to-video pipeline

Video latent에는 두 spatial dimension 외에 time dimension이 추가된다.

hRT×H×W×Ch \in \mathbb{R}^{T\times H'\times W'\times C}

Spatial-temporal autoencoder는 image의 width와 height뿐 아니라 frame 축도 압축한다. Diffusion backbone은 frame마다 plausible한 image를 만드는 것과 동시에 motion과 object identity가 시간에 따라 일관되게 유지되도록 해야 한다.

Text-to-image 예시가 1,024 image token을 처리했다면 제시된 고해상도 video model 예시는 약 76,000 video token을 처리한다. Architecture가 비슷해도 time dimension 때문에 sequence length와 attention cost가 크게 증가한다.

Video generation 비용의 핵심은 다음과 같다.

  • High resolution은 frame당 spatial token 수를 늘린다.
  • 긴 duration과 높은 FPS는 temporal token 수를 늘린다.
  • Sampling step마다 긴 sequence를 large model로 다시 처리한다.
  • Audio까지 joint generation하면 추가 modality와 synchronization이 필요하다.

Diffusion sampling과 distillation

GAN은 generator forward 한 번으로 sample을 만들지만 diffusion은 보통 수십 번 network를 평가한다. Backbone이 수십억 parameter이고 sequence도 길면 inference latency와 cost가 매우 커진다.

Diffusion distillation은 많은 step을 사용하는 teacher의 generation trajectory를 더 적은 step의 student가 근사하게 한다. 일반적으로 30, 50, 100 step이 필요했던 model을 몇 step으로 줄이며, 일부 방법은 single-step sampling을 목표로 한다.

Step 수를 줄이면 speed는 빨라지지만 integration error와 sample-quality degradation이 커질 수 있다. Distillation의 핵심 trade-off는 sample quality를 최대한 유지하면서 network function evaluation 횟수를 줄이는 것이다.

Diffusion을 보는 세 관점

Diffusion 계열은 서로 다른 수학적 관점에서 유도할 수 있으며 최종 algorithm의 형태가 비슷하게 나타나기도 한다.

Latent-variable model

Clean sample x0x_0에 대응하는 noisy states x1,,xTx_1,\ldots,x_T를 latent variable로 본다. Forward corruption은 known distribution이고 reverse transition을 neural network로 학습한다. VAE와 비슷하게 data likelihood의 variational lower bound를 만들 수 있다.

Score matching

Distribution pt(x)p_t(x)의 score는 log-density를 input에 대해 미분한 vector field이다.

st(x)=xlogpt(x)s_t(x) = \nabla_x \log p_t(x)

Score는 local하게 density가 더 빠르게 증가하는 방향을 가리킨다. Diffusion model은 여러 noise level tt에 대한 score field를 학습하고, noise에서 high-density data region으로 sample을 이동시킨다.

Score는 normalized density 값 자체를 몰라도 gradient field로 sampling direction을 제공할 수 있다는 점이 중요하다.

Differential equation

Noise distribution과 data distribution 사이의 transport를 시간에 따른 differential equation으로 나타낼 수 있다.

dxt=f(xt,t)dt+g(t)dWtdx_t = f(x_t,t)\,dt + g(t)\,dW_t

dWtdW_t가 있는 stochastic differential equation, SDE와 이를 제거한 probability-flow ODE 관점을 사용할 수 있다. Sampling algorithm은 learned vector field를 따라 differential equation을 푸는 numerical integrator로 해석된다.

Rectified flow의 단순 Euler update는 ODE를 푸는 first-order method이다. Heun method나 higher-order solver는 더 적은 step에서 trajectory를 정확하게 근사할 수 있다.

Generative model이 결합되는 방식

Modern generation pipeline은 하나의 방법만 고집하지 않는다.

  • VAE 또는 autoencoder가 pixel을 compact latent로 압축한다.
  • GAN discriminator가 decoder reconstruction을 sharp하게 만든다.
  • Diffusion 또는 rectified flow가 continuous latent distribution을 생성한다.
  • Pretrained text encoder가 condition을 제공한다.
  • Autoregressive model은 discrete latent token의 distribution을 modeling할 수 있다.

다른 modern recipe는 discrete autoencoder로 image token을 만든 뒤 causal Transformer가 token을 autoregressive하게 생성하는 방식이다.

xdiscrete encoder(q1,,qT)x \xrightarrow{\text{discrete encoder}} (q_1,\ldots,q_T) p(q1,,qT)=t=1Tp(qtq<t)p(q_1,\ldots,q_T) = \prod_{t=1}^{T} p(q_t\mid q_{<t})

Pixel, latent, text 중 어느 space에서 어떤 generative objective를 사용할지는 quality, controllability, likelihood, training stability, sampling speed 사이의 trade-off로 결정한다.

GAN과 diffusion 비교

항목GANDiffusion 또는 rectified flow
DensityImplicit대개 score, flow, variational 관점으로 다룸
Training signalAdversarial classifierKnown noise target에 대한 regression
NetworkGenerator와 discriminator주된 denoiser 또는 velocity network 하나
Training stabilityMinimax game으로 불안정비교적 안정적인 regression loss
SamplingGenerator forward 한 번여러 iterative step
Sample quality잘 조정하면 매우 sharpScale이 크고 coverage가 좋은 편
대표 failureMode collapseSlow sampling, schedule와 solver error
Latent inversion기본적으로 encoder 없음Latent diffusion은 별도 encoder 사용

GAN은 inference가 빠르고 선명한 output을 만들 수 있지만 training이 어렵다. Diffusion은 training과 scaling이 상대적으로 안정적이지만 inference가 느리다. Latent diffusion과 distillation은 diffusion의 compute 문제를 줄이고, adversarial decoder는 reconstruction detail을 보완한다.

과제에서 확인할 것

GAN objective

  • Discriminator가 real sample과 detached fake sample을 모두 사용하는지 확인한다.
  • Discriminator와 generator optimizer가 서로 다른 parameter만 update하는지 확인한다.
  • Generator update에서 discriminator parameter는 고정하지만 gradient가 D(G(z))D(G(z))에서 GG까지 흐르는지 확인한다.
  • Saturating loss 대신 logD(G(z))-\log D(G(z)) 형태의 non-saturating loss를 사용하는지 확인한다.
  • Label convention에서 real이 1, fake가 0인지 loss 식과 일치하는지 확인한다.
  • Generator와 discriminator loss만으로 sample quality를 단정하지 않고 fixed latent sample과 diversity를 함께 확인한다.

Rectified flow training

  • xxzz의 shape가 같은지 확인한다.
  • tt가 sample마다 독립적으로 sampling되고 broadcasting shape가 올바른지 확인한다.
  • xt=(1t)x+tzx_t=(1-t)x+tz에서 t=0t=0이 data, t=1t=1이 noise인지 확인한다.
  • Target velocity가 vgt=zxv_{\text{gt}}=z-x인지 확인한다.
  • Model이 noisy sample뿐 아니라 timestep embedding도 받는지 확인한다.
  • Loss가 model prediction과 target velocity 사이 MSE인지 확인한다.

Rectified flow sampling

  • Initial state를 x1N(0,I)x_1\sim\mathcal{N}(0,I)에서 시작하는지 확인한다.
  • Time이 11에서 00으로 감소하므로 update sign이 training velocity의 반대 방향인지 확인한다.
  • Step size와 number of function evaluations를 함께 기록한다.
  • Sampling 중 gradient를 저장하지 않도록 inference mode를 사용하는지 확인한다.
  • Euler solver와 더 높은 차수 solver에서 quality와 runtime이 어떻게 달라지는지 확인한다.

Classifier-free guidance

  • Training 중 condition dropout이 실제 null representation으로 바뀌는지 확인한다.
  • Conditional과 unconditional prediction을 같은 (xt,t)(x_t,t)에서 계산하는지 확인한다.
  • Guidance scale w=0w=0에서 raw conditional prediction과 같아지는지 식으로 확인한다.
  • Guidance scale을 높였을 때 condition adherence, diversity, artifact가 어떻게 달라지는지 비교한다.
  • Model을 두 번 평가하므로 CFG가 sampling latency에 주는 영향을 측정한다.

Latent diffusion pipeline

  • Autoencoder를 먼저 학습하고 diffusion training 중에는 encoder를 freeze하는지 확인한다.
  • Pixel shape와 latent shape를 기록해 실제 compression ratio를 계산한다.
  • Diffusion output이 pixel이 아니라 clean latent라는 점을 확인한다.
  • Final image가 autoencoder decoder의 reconstruction quality에 의해 제한되는지 확인한다.
  • Text condition, timestep, noisy latent가 DiT block에 각각 어떤 경로로 주입되는지 확인한다.