16.7  GAN 너머의 적대적 손실

주택 가격 같은 단일 스칼라를 예측할 때는 평균 제곱 오차(\(L_2\) 손실)를 최소화하는 것이 표준 관행입니다. 그러나 초해상화(저해상도 썸네일 \(c\) 를 고해상도 이미지 \(x\) 로 사상)나 스케치–사진 변환(pix2pix, Isola 기타 (2017년)) 같은 조건부 이미지 생성 문제에서 픽셀별 \(L_2\) 및 \(L_1\) 회귀 손실은 흐릿한 출력을 만듭니다. 동일한 저해상도 입력에 수많은 서로 다른 고해상도 질감이 대응하는데 픽셀별 제곱 오차를 최소화하면 신경망이 그 타당한 선명한 이미지들 중 어디에도 속하지 않는 흐릿한 조건부 평균 \(\mathbb{E}[x \mid c]\) 를 출력하도록 강제되기 때문입니다. 이 회귀 손실을 출력이 조건 \(c\) 에 걸맞은 사실적 이미지인지 채점하는 판별자 \(D(x, c)\) 와 짝지으면 선명한 고주파 세부 묘사가 되살아납니다.

바로 이 메커니즘 덕분에 범용 이미지 합성에서 확산 모델과 플로 매칭 모델(17장)이 독립형 GAN을 대체한 오늘날에도 적대적 손실이 여전히 널리 쓰입니다. 다단계 확산 모델로부터 증류한 1스텝 생성자, 잠재 확산 모델이 작동하는 기반인 이미지 오토인코더(토크나이저), 스펙트로그램에서 음성 파형을 복원하는 신경망 오디오 보코더 모두 학습된 판별자로 훈련됩니다. 아래에서는 최소 이봉 회귀 문제 위에서 조건부 평균화 효과를 분석하고, 높은 잡음의 디노이징 교사 모델로부터 1스텝 증류를 수행할 때 판별자가 없으면 왜 조건부 평균으로 붕괴하는지 보인 뒤, 현대 생성 파이프라인 어디에 적대적 손실이 쓰이는지 정리합니다.

16.7.1 조건부 평균과 다봉 타깃

16.7.1.1 조건부 평균 분해

\(g(c)\) 를 조건 \(c\) 가 주어졌을 때 \(x\) 의 결정론적 예측기라 하고 \(\mu(c) = \mathbb{E}[x \mid c]\) 를 조건부 평균이라 합시다. \(\mathbb{E}[\|x - g(c)\|^2]\) 안에서 \(\mu(c)\) 를 더하고 빼면(\(c\) 가 주어졌을 때의 반복 기댓값 법칙에 의해) 교차항 \(2\,\mathbb{E}[\langle x - \mu(c), \mu(c) - g(c) \rangle] = 0\) 이 사라지고 다음 직교 분해가 남습니다:

\[ \begin{aligned} \mathbb{E}\big[(x - g(c))^2\big] &= \mathbb{E}\big[(x - \mu(c))^2\big] + \mathbb{E}\big[(\mu(c) - g(c))^2\big]. \end{aligned} \tag{16.7.1}\]

첫 번째 항은 줄일 수 없는 조건부 분산 \(\operatorname{Var}(x \mid c)\) 이고 두 번째 항은 \(g(c)\) 와 \(\mu(c)\) 사이의 제곱 거리입니다. 따라서 제곱 오차는 조건부 평균 \(g^\star(c) = \mu(c)\) 에서 유일하게 최소화됩니다. \(p(x \mid c)\) 가 단봉이고 집중되어 있을 때는 \(\mu(c)\) 가 훌륭한 대푯값이지만, \(p(x \mid c)\) 가 다봉일 때는 \(\mu(c)\) 가 모드들 사이의 저밀도 영역에 떨어집니다. \(L_2\) 를 \(L_1\) 손실 \(\mathbb{E}[|x - g(c)|]\) 로 바꾸더라도 조건부 평균이 좌표별 조건부 중앙값으로 바뀔 뿐이며(2 참조), 대칭 이봉 분포에서는 중앙값 역시 지지집합 바깥에 놓입니다.

16.7.1.2 이봉 2-띠 벤치마크

\(c \sim \textrm{Uniform}[-1, 1]\) 이고 빈 통로 하나를 사이에 둔 두 개의 평행 데이터 띠로 이루어진 1차원 조건부 분포를 생각해 봅시다:

\[ \begin{aligned} x &= c + b + 0.05\,\xi, \\ b &\in \{-1, +1\} \textrm{ with probability } \tfrac12 \textrm{ each}, \quad \xi \sim \mathcal{N}(0, 1). \end{aligned} \tag{16.7.2}\]

조건부 평균 \(\mu(c) = c\) 는 두 띠 \(x = c \pm 1\) 사이의 텅 빈 통로 한가운데를 따라 달리며 \(\mathbb{E}[(x - \mu(c))^2] = 1 + 0.05^2 = 1.0025\) 를 달성합니다. 이와 대조적으로 위쪽 띠 \(g(c) = c + 1\) 하나를 확실히 택하는 예측기는 제곱 오차가 \(\tfrac12(0) + \tfrac12(2^2) + 0.05^2 = 2.0025\) 로 두 배나 큽니다. 즉 제곱 오차는 유효한 데이터 모드를 택하는 행위에 오히려 벌점을 매깁니다.

반면 조건부 판별자 \(D(x, c)\) 는 로그 밀도비를 추정합니다(16.6절):

\[ D^\star(x, c) = \log \frac{p(x, c)}{q(x, c)}. \]

\(p(x, c) \approx 0\) 인 빈 통로에서는 \(D^\star(x, c)\) 가 강한 음수가 되므로 비포화 적대적 손실 \(-\log \sigma(D(\hat x, c))\) 를 최소화하면 예측기 \(\hat x = g(c)\) 가 고밀도 데이터 띠들 중 하나 위로 밀려 올라갑니다.

동일한 초기 가중치에서 출발하는 똑같은 구조의 은닉층 2개짜리 \(\tanh\) MLP 두 개(g_mse와 g_adv)를 훈련해 이를 시험합니다. g_mse는 제곱 오차를 최소화하고, g_adv는 16.4절 의 d2l.gan_loss_D와 d2l.gan_loss_G를 사용해 Leaky ReLU 판별자 \(D(x, c)\) 에 맞서 훈련합니다.

def make_bands(n):
    """Draw n pairs (c, x) from the two bands x = c + b + 0.05 xi."""
    c = torch.rand(n, 1) * 2 - 1
    b = torch.randint(0, 2, (n, 1)) * 2.0 - 1.0
    return c, c + b + 0.05 * torch.randn(n, 1)

torch.manual_seed(0)
g_mse = d2l.make_mlp([1, 32, 32, 1], nn.Tanh())
g_adv = d2l.make_mlp([1, 32, 32, 1], nn.Tanh())
g_adv.load_state_dict(g_mse.state_dict())  # both students start alike
D = d2l.make_mlp([2, 32, 32, 1], nn.LeakyReLU(0.2))
c_data, x_data = make_bands(200)  # a data sample for the plot
def make_bands(key, n):
    """Draw n pairs (c, x) from the two bands x = c + b + 0.05 xi."""
    k_c, k_b, k_xi = jax.random.split(key, 3)
    c = jax.random.uniform(k_c, (n, 1), minval=-1, maxval=1)
    b = jax.random.rademacher(k_b, (n, 1), dtype=jnp.float32)
    return c, c + b + 0.05 * jax.random.normal(k_xi, (n, 1))

rngs = nnx.Rngs(0)
g_mse = d2l.make_mlp([1, 32, 32, 1], nnx.tanh, rngs=rngs)
g_adv = nnx.clone(g_mse)  # both students start alike
D = d2l.make_mlp([2, 32, 32, 1], lambda h: nnx.leaky_relu(h, 0.2), rngs=rngs)
key_mse, key_adv, key_data = jax.random.split(rngs(), 3)
c_data, x_data = make_bands(key_data, 200)  # a data sample for the plot

첫 번째 학생 모델은 2,000스텝에 걸쳐 학습률이 0.01에서 0까지 코사인 곡선을 따라 감쇠하는 Adam으로 제곱 오차를 최소화합니다. 이 모델이 어디에 도달할지는 실험해 볼 필요도 없습니다. 식 16.7.1 에 의해 각 띠로부터 1단위씩 떨어진 직선 \(x = c\) 를 따라갈 것이며 두 번째 학생 모델의 대조군 역할을 합니다.

def train_mse(g, num_steps=2000, batch_size=128, lr=0.01):
    opt = torch.optim.Adam(g.parameters(), lr=lr)
    sched = torch.optim.lr_scheduler.CosineAnnealingLR(opt, num_steps)
    for _ in range(num_steps):
        c, x = make_bands(batch_size)  # a fresh batch at every step
        opt.zero_grad()
        ((g(c) - x) ** 2).mean().backward()
        opt.step()
        sched.step()

train_mse(g_mse)
@nnx.jit(static_argnums=3)
def mse_step(g, opt, key, batch_size):
    c, x = make_bands(key, batch_size)  # a fresh batch at every step
    opt.update(g, nnx.grad(lambda g_: ((g_(c) - x) ** 2).mean())(g))

def train_mse(g, key, num_steps=2000, batch_size=128, lr=0.01):
    schedule = optax.cosine_decay_schedule(lr, num_steps)
    opt = nnx.Optimizer(g, optax.adam(schedule), wrt=nnx.Param)
    for k in jax.random.split(key, num_steps):
        mse_step(g, opt, k, batch_size)

train_mse(g_mse, key_mse)

두 번째 학생 모델은 16.4절 의 손실 d2l.gan_loss_D 및 d2l.gan_loss_G로 로그 손실 게임을 치릅니다. 매 스텝 크리틱은 예측 쌍 \((\hat x, c)\) 대비 실제 쌍 \((x, c)\) 위에서 로지스틱 회귀 스텝 한 번을 밟고, 이어서 학생 모델이 갱신된 크리틱에 맞서 \(-\log \sigma\big(D(\hat x, c)\big)\) 위에서 한 스텝을 밟습니다. 두 분포가 매끄러움 정도가 아니라 질량을 어디에 두는지에서만 차이 나도록 예측값에는 새로 뽑은 \(\xi' \sim \mathcal{N}(0, 1)\) 로 데이터의 관측 잡음 \(\hat x = g(c) + 0.05\,\xi'\) 을 더해 게임에 투입합니다. 게임은 회귀보다 천천히 움직이므로 이 학생 모델에는 8,000스텝을 부여합니다(제곱 오차 학생 모델은 2,000스텝이면 이미 최적해에 도달해 스텝을 더 주어도 움직이지 않습니다).

def train_adversarial(g, D, num_steps=8000, batch_size=128):
    opt_G = torch.optim.Adam(g.parameters(), lr=1e-3)
    opt_D = torch.optim.Adam(D.parameters(), lr=2e-3)
    for _ in range(num_steps):
        c, x = make_bands(batch_size)
        x_hat = g(c) + 0.05 * torch.randn(batch_size, 1)  # the data's noise
        real, fake = torch.cat([c, x], 1), torch.cat([c, x_hat], 1)
        opt_D.zero_grad()
        d2l.gan_loss_D(D, real, fake.detach()).backward()
        opt_D.step()
        opt_G.zero_grad()
        d2l.gan_loss_G(D, real, fake).backward()
        opt_G.step()

train_adversarial(g_adv, D)
@nnx.jit(static_argnums=5)
def adversarial_step(g, D, opt_G, opt_D, key, batch_size):
    k_data, k_xi = jax.random.split(key)
    c, x = make_bands(k_data, batch_size)
    xi = jax.random.normal(k_xi, (batch_size, 1))  # the data's noise
    real = jnp.concatenate([c, x], 1)
    fake = lambda g_: jnp.concatenate([c, g_(c) + 0.05 * xi], 1)
    loss_D = lambda D_: d2l.gan_loss_D(D_, real, fake(g))
    opt_D.update(D, nnx.grad(loss_D)(D))
    loss_G = lambda g_: d2l.gan_loss_G(D, real, fake(g_))
    opt_G.update(g, nnx.grad(loss_G)(g))

def train_adversarial(g, D, key, num_steps=8000, batch_size=128):
    opt_G = nnx.Optimizer(g, optax.adam(1e-3), wrt=nnx.Param)
    opt_D = nnx.Optimizer(D, optax.adam(2e-3), wrt=nnx.Param)
    for k in jax.random.split(key, num_steps):
        adversarial_step(g, D, opt_G, opt_D, k, batch_size)

train_adversarial(g_adv, D, key_adv)

입력 격자점 201개 위에서 세 숫자가 각 학생 모델을 요약합니다. 곡선에서 더 가까운 띠까지의 평균 거리, 조건부 평균 \(x = c\) 까지의 평균 거리, 그리고 곡선이 두 띠 모두로부터 0.25 넘게 떨어진 입력 비율입니다.

cs = torch.linspace(-1, 1, 201).reshape(-1, 1)
with torch.no_grad():
    curves = {'squared error': g_mse(cs), 'adversarial': g_adv(cs)}
for name, x_hat in curves.items():
    to_band = torch.minimum((x_hat - cs - 1).abs(), (x_hat - cs + 1).abs())
    print(f'{name}: {to_band.mean():.2f} from the nearer band, '
          f'{(x_hat - cs).abs().mean():.2f} from x = c, '
          f'{(to_band > 0.25).float().mean():.0%} off the bands')
squared error: 0.98 from the nearer band, 0.02 from x = c, 100% off the bands
adversarial: 0.02 from the nearer band, 0.99 from x = c, 2% off the bands
cs = jnp.linspace(-1, 1, 201).reshape(-1, 1)
curves = {'squared error': g_mse(cs), 'adversarial': g_adv(cs)}
for name, x_hat in curves.items():
    to_band = jnp.minimum(jnp.abs(x_hat - cs - 1), jnp.abs(x_hat - cs + 1))
    print(f'{name}: {to_band.mean():.2f} from the nearer band, '
          f'{jnp.abs(x_hat - cs).mean():.2f} from x = c, '
          f'{(to_band > 0.25).mean():.0%} off the bands')
squared error: 0.98 from the nearer band, 0.02 from x = c, 100% off the bands
adversarial: 0.04 from the nearer band, 1.01 from x = c, 0% off the bands

파선으로 표시한 조건부 평균 \(x = c\) 와 함께 훈련 표본 (c_data, x_data) 위에 curves의 학습된 두 곡선을 그리면 회귀와 적대적 훈련의 차이가 한눈에 드러납니다:

d2l.plot([c_data, cs, cs, cs],
         [x_data, curves['squared error'], curves['adversarial'], cs],
         '$c$', '$x$', ['data', 'squared-error student',
                        'adversarial student', '$x = c$'],
         ylim=(-2.2, 3.6), fmts=('C0.', 'C2-', 'C1-', 'k--'),
         figsize=(5.5, 3.2))

d2l.plot([c_data, cs, cs, cs],
         [x_data, curves['squared error'], curves['adversarial'], cs],
         '$c$', '$x$', ['data', 'squared-error student',
                        'adversarial student', '$x = c$'],
         ylim=(-2.2, 3.6), fmts=('C0.', 'C2-', 'C1-', 'k--'),
         figsize=(5.5, 3.2))

예측한 대로 제곱 오차 모델 g_mse는 빈 통로 한가운데로 조건부 평균 \(\mu(c) = c\) 를 추적합니다(어느 띠에서든 약 1단위 거리, 예측의 \(100\%\) 가 띠 바깥). 반면 적대적 모델 g_adv는 유효한 데이터 띠에 안착합니다(최근접 띠로부터 평균 백분의 몇 단위 거리, 통로를 가로지르는 점은 기껏해야 \(2\%\) 이하).

근본적인 지각–왜곡 트레이드오프(perception–distortion trade-off) (Blau 와/과 Michaeli 2018년) 에 주목합시다. 이상적인 확률적 샘플러 \(\hat x \sim p(x \mid c)\) 조차 기대 제곱 오차가 \(2\,\operatorname{Var}(x \mid c)\) 로서 흐릿한 조건부 평균 \(\mu(c)\) 보다 MSE가 두 배 크고 PSNR은 \(3\text{ dB}\) 더 낮습니다(1 참조). 나아가 결정론적 함수 \(g(c)\) 는 입력 \(c\) 마다 값 하나만 출력할 수 있으므로 두 띠를 동시에 덮으려면 \(c\) 옆에 확률적 잠재 변수 \(z\) 를 함께 건네주어야 합니다: \(\hat x = g(c, z)\) (3 참조).

16.7.2 확산 증류에서의 판별자

16.7.2.1 조건부 평균으로서의 디노이저

확산 모델과 플로 매칭 모델(17장)은 잡음 섞인 입력 \(x_\tau = x_0 + \tau\xi\)(\(\xi \sim \mathcal{N}(0, I)\))로부터 깨끗한 데이터 \(x_0\) 를 예측하도록 제곱 오차로 디노이저 신경망을 훈련합니다. 식 16.7.1 에 의해 최적 디노이저는 사후 조건부 평균 \(\mathbb{E}[x_0 \mid x_\tau]\) 를 계산합니다(17.1절). 큰 잡음 수준 \(\tau\) 에서는 수많은 깨끗한 이미지가 \(x_\tau\) 와 양립하므로 \(\mathbb{E}[x_0 \mid x_\tau]\) 는 흐릿한 평균이 되며, 다단계 샘플러들은 높은 잡음에서 \(\tau \to 0\) 까지 작은 스텝을 여러 번 밟음으로써 이 흐릿한 평균을 그대로 반환하는 일을 피합니다.

다단계 확산 교사 모델을 빠른 1스텝 학생 생성자로 증류(distillation)할 때(17.8절) 흔히 쓰는 한 가지 접근법은 학생 출력 \(\hat x\) 에 잡음 \(\tau\xi\) 를 더하고 동결된 교사의 디노이징 추정치 \(\mathbb{E}[x_0 \mid \hat x + \tau\xi]\) 를 향해 \(\hat x\) 를 회귀시키는 것입니다. 그러나 높은 잡음 \(\tau\) 에서는 교사의 디노이징 타깃 자체가 조건부 평균이므로 적대적 크리틱을 함께 넣지 않으면 1스텝 학생을 다시 흐릿한 평균 쪽으로 끌어당깁니다.

16.7.2.2 2-띠 벤치마크에서의 닫힌 형태 증류

식 16.7.2 의 2-띠 벤치마크에서는 잡음 수준 \(\tau\) 의 정확한 베이즈 최적 디노이징 교사가 닫힌 형태로 주어집니다. 띠 \(b \in \{-1, +1\}\) 위의 한 점에 대한 잡음 관측 \(\tilde x = x + \tau\xi\) 가 주어지면 \(\tilde x \mid c, b \sim \mathcal{N}(c + b, \tau^2 + 0.05^2)\) 입니다. 베이즈 법칙에 의해 \(b = -1\) 대비 \(b = +1\) 의 사후 로그 오즈는 \(2(\tilde x - c)/(\tau^2 + 0.05^2)\) 이므로 사후 평균 띠 중심은 다음과 같습니다:

\[ \mathbb{E}[c + b \mid \tilde x, c] \;=\; c + \tanh\Big(\frac{\tilde x - c}{\tau^2 + 0.05^2}\Big). \tag{16.7.3}\]

이제 두 띠를 모두 덮을 용량을 갖추도록 각 학생 \(g(c, z)\) 에 1차원 가우스 잠재 변수 \(z \sim \mathcal{N}(0, 1)\) 을 장착하고 교사 잡음 수준 \(\tau = 2\) 에서 세 가지 훈련 목적 함수를 비교합니다:

  1. 회귀 단독: \(\|\hat x - \operatorname{stop\_grad}(\text{teacher}(\hat x + \tau\xi, c, \tau))\|^2\) 최소화. \(\tau = 2\) 에서 \(\tilde x\) 에 대한 식 16.7.3 의 기울기는 기껏해야 \((\tau^2 + 0.05^2)^{-1} \approx \tfrac14 < 1\) 이므로 오프셋 \(u = g(c, z) - c\) 에 대한 고정점 방정식 \(u = \mathbb{E}_\xi[\tanh((u + \sqrt{\tau^2 + 0.05^2}\,\xi)/(\tau^2 + 0.05^2))]\) 는 유일한 수축 고정점 \(u = 0\)(빈 통로)을 갖습니다.
  2. 크리틱 단독: d2l.gan_loss_D와 d2l.gan_loss_G로 조건부 판별자 \(D(x, c)\) 에 맞서 \(g(c, z)\) 훈련.
  3. 크리틱 + 회귀: 적대적 손실과 교사 회귀 손실을 동일 가중치로 합산(적대적 확산 증류, Adversarial Diffusion Distillation, ADD, Sauer 기타 (2023년) 의 방법과 동일 방식).
def teacher(x_tilde, c, tau):
    """Posterior mean of the band center c + b given x_tilde = x + tau xi."""
    return c + torch.tanh((x_tilde - c) / (tau ** 2 + 0.05 ** 2))

def train_student(g, D, lam, tau=2.0, num_steps=4000, batch_size=128):
    """Train g(c, z) on the critic's loss if D is given, plus lam times the
    squared error toward the teacher's estimate at noise level tau."""
    opt_G = torch.optim.Adam(g.parameters(), lr=1e-3)
    if D is not None:
        opt_D = torch.optim.Adam(D.parameters(), lr=2e-3)
    for _ in range(num_steps):
        c, x = make_bands(batch_size)
        z = torch.randn(batch_size, 1)  # the student's latent
        x_hat = g(torch.cat([c, z], 1)) + 0.05 * torch.randn(batch_size, 1)
        real, fake = torch.cat([c, x], 1), torch.cat([c, x_hat], 1)
        loss_G = 0
        if D is not None:
            opt_D.zero_grad()
            d2l.gan_loss_D(D, real, fake.detach()).backward()
            opt_D.step()
            loss_G = d2l.gan_loss_G(D, real, fake)
        with torch.no_grad():  # the teacher's estimate is a fixed target
            target = teacher(x_hat + tau * torch.randn(batch_size, 1), c, tau)
        loss_G = loss_G + lam * ((x_hat - target) ** 2).mean()
        opt_G.zero_grad()
        loss_G.backward()
        opt_G.step()
def teacher(x_tilde, c, tau):
    """Posterior mean of the band center c + b given x_tilde = x + tau xi."""
    return c + jnp.tanh((x_tilde - c) / (tau ** 2 + 0.05 ** 2))

@nnx.jit(static_argnums=7)
def student_step(g, D, opt_G, opt_D, key, lam, tau, batch_size):
    k_data, k_z, k_xi, k_tau = jax.random.split(key, 4)
    c, x = make_bands(k_data, batch_size)
    z = jax.random.normal(k_z, (batch_size, 1))  # the student's latent
    xi = jax.random.normal(k_xi, (batch_size, 1))  # the data's noise
    sample = lambda g_: g_(jnp.concatenate([c, z], 1)) + 0.05 * xi
    real = jnp.concatenate([c, x], 1)
    fake = lambda g_: jnp.concatenate([c, sample(g_)], 1)
    if D is not None:
        loss_D = lambda D_: d2l.gan_loss_D(D_, real, fake(g))
        opt_D.update(D, nnx.grad(loss_D)(D))
    noise = tau * jax.random.normal(k_tau, (batch_size, 1))
    def loss_G(g_):
        x_hat = sample(g_)  # the teacher's estimate is a fixed target
        target = jax.lax.stop_gradient(teacher(x_hat + noise, c, tau))
        loss = lam * ((x_hat - target) ** 2).mean()
        if D is not None:
            loss += d2l.gan_loss_G(D, real, fake(g_))
        return loss
    opt_G.update(g, nnx.grad(loss_G)(g))

def train_student(g, D, lam, key, tau=2.0, num_steps=4000, batch_size=128):
    """Train g(c, z) on the critic's loss if D is given, plus lam times the
    squared error toward the teacher's estimate at noise level tau."""
    opt_G = nnx.Optimizer(g, optax.adam(1e-3), wrt=nnx.Param)
    opt_D = (None if D is None
             else nnx.Optimizer(D, optax.adam(2e-3), wrt=nnx.Param))
    for k in jax.random.split(key, num_steps):
        student_step(g, D, opt_G, opt_D, k, lam, tau, batch_size)

이제 학생 모델은 각 \(c\) 마다 출력 분포를 이룹니다. 함수 band_shares는 첫 실험의 입력 201개와 균등 간격 잠재 분위수 64개에서 학생 모델을 평가하여 더 가까운 띠까지의 평균 거리 및 위쪽 띠와 아래쪽 띠로부터 0.25 이내에 들어오는 출력 비율을 반환합니다.

def band_shares(g, cs):
    """Mean distance of g(c, z) to the nearer band, and its shares on the
    upper and the lower band, over the inputs cs and 64 quantiles z."""
    zs = torch.special.ndtri((torch.arange(64) + 0.5) / 64)
    c, z = (v.reshape(-1, 1) for v in torch.meshgrid(
        cs.flatten(), zs, indexing='ij'))
    with torch.no_grad():
        u = g(torch.cat([c, z], 1)) - c  # offset from the corridor
    to_band = torch.minimum((u - 1).abs(), (u + 1).abs())
    return (to_band.mean(), ((u - 1).abs() < 0.25).float().mean(),
            ((u + 1).abs() < 0.25).float().mean())
def band_shares(g, cs):
    """Mean distance of g(c, z) to the nearer band, and its shares on the
    upper and the lower band, over the inputs cs and 64 quantiles z."""
    zs = jax.scipy.special.ndtri((jnp.arange(64) + 0.5) / 64)
    c, z = (v.reshape(-1, 1) for v in jnp.meshgrid(
        cs.flatten(), zs, indexing='ij'))
    u = g(jnp.concatenate([c, z], 1)) - c  # offset from the corridor
    to_band = jnp.minimum(jnp.abs(u - 1), jnp.abs(u + 1))
    return (to_band.mean(), (jnp.abs(u - 1) < 0.25).mean(),
            (jnp.abs(u + 1) < 0.25).mean())

각 학생 모델은 세 시드로 훈련하며 한 시드 안에서 세 학생 모델은 동일한 가중치에서 시작해 동일한 데이터를 봅니다.

students = {'regression': (False, 1.0), 'critic': (True, 0.0),
            'critic + regression': (True, 1.0)}
for name, (has_critic, lam) in students.items():
    for seed in range(3):
        torch.manual_seed(seed)
        g = d2l.make_mlp([2, 32, 32, 1], nn.Tanh())
        D = d2l.make_mlp([2, 32, 32, 1], nn.LeakyReLU(0.2))
        train_student(g, D if has_critic else None, lam)
        dist, upper, lower = band_shares(g, cs)
        print(f'{name}, seed {seed}: {dist:.2f} from the nearer band, '
              f'{upper:.0%} upper, {lower:.0%} lower, '
              f'{1 - upper - lower:.0%} off the bands')
regression, seed 0: 0.97 from the nearer band, 0% upper, 0% lower, 100% off the bands
regression, seed 1: 0.98 from the nearer band, 0% upper, 0% lower, 100% off the bands
regression, seed 2: 0.98 from the nearer band, 0% upper, 0% lower, 100% off the bands
critic, seed 0: 0.03 from the nearer band, 49% upper, 50% lower, 1% off the bands
critic, seed 1: 0.08 from the nearer band, 50% upper, 49% lower, 1% off the bands
critic, seed 2: 0.04 from the nearer band, 50% upper, 49% lower, 1% off the bands
critic + regression, seed 0: 0.05 from the nearer band, 48% upper, 50% lower, 2% off the bands
critic + regression, seed 1: 0.06 from the nearer band, 50% upper, 48% lower, 2% off the bands
critic + regression, seed 2: 0.04 from the nearer band, 48% upper, 51% lower, 1% off the bands
students = {'regression': (False, 1.0), 'critic': (True, 0.0),
            'critic + regression': (True, 1.0)}
for name, (has_critic, lam) in students.items():
    for seed in range(3):
        rngs = nnx.Rngs(seed)
        g = d2l.make_mlp([2, 32, 32, 1], nnx.tanh, rngs=rngs)
        D = d2l.make_mlp([2, 32, 32, 1], lambda h: nnx.leaky_relu(h, 0.2),
                         rngs=rngs)
        train_student(g, D if has_critic else None, lam, rngs())
        dist, upper, lower = band_shares(g, cs)
        print(f'{name}, seed {seed}: {dist:.2f} from the nearer band, '
              f'{upper:.0%} upper, {lower:.0%} lower, '
              f'{1 - upper - lower:.0%} off the bands')
regression, seed 0: 0.96 from the nearer band, 0% upper, 0% lower, 100% off the bands
regression, seed 1: 0.97 from the nearer band, 0% upper, 0% lower, 100% off the bands
regression, seed 2: 0.97 from the nearer band, 0% upper, 0% lower, 100% off the bands
critic, seed 0: 0.03 from the nearer band, 52% upper, 47% lower, 1% off the bands
critic, seed 1: 0.06 from the nearer band, 50% upper, 49% lower, 1% off the bands
critic, seed 2: 0.03 from the nearer band, 52% upper, 47% lower, 2% off the bands
critic + regression, seed 0: 0.04 from the nearer band, 48% upper, 50% lower, 1% off the bands
critic + regression, seed 1: 0.04 from the nearer band, 49% upper, 50% lower, 1% off the bands
critic + regression, seed 2: 0.04 from the nearer band, 49% upper, 49% lower, 1% off the bands

세 시드 실험 결과는 고정점 분석을 그대로 확인해 줍니다:

  • 고잡음 교사에 대한 회귀는 잠재 변수 \(z\) 를 무시한 채 출력의 \(100\%\) 를 빈 통로(어느 띠에서든 약 1단위 거리)로 붕괴시킵니다.
  • 크리틱 단독과 크리틱 + 회귀는 둘 다 출력의 \(98\text{--}99\%\) 를 두 데이터 띠 위에 곧장 올려놓으며(평균 거리가 백분의 몇 단위로 항상 \(0.1\) 미만), 잠재 변수 \(z\) 를 통해 위쪽 띠와 아래쪽 띠 사이에 확률 질량을 고르게(\(\sim 49\% / 49\%\)) 나눕니다. 띠의 폭이 \(\sigma = 0.05\) 로 좁기 때문에 최적 크리틱의 복원 기울기(\(\delta / 0.05^2 = 400\delta\))가 고잡음 교사의 완만한 안쪽 인력을 손쉽게 압도합니다.

16.7.2.3 대규모 증류, 오토인코더 및 보코더

회귀 또는 지각 기준점(anchor)을 적대적 판별자와 결합하는 이 패턴은 현대 생성 시스템의 세 가지 주요 부류 전반에 걸쳐 등장합니다:

  1. 적대적 확산 증류(ADD와 DMD2): ADD (Sauer 기타 2023년) 는 디노이징 교사 회귀 손실을 동결된 DINOv2 특성 위에 구축한 판별자와 결합해 1스텝 이미지 생성자를 훈련하며 위 실험과 똑같은 순서를 확인합니다(교사 회귀만으로는 흐릿한 이미지가 나오지만 판별자를 더하면 선명한 1스텝 샘플이 나옵니다). 분포 매칭 증류(DMD, Yin, Gharbi, Zhang, 기타 (2024년))는 동결된 교사 스코어 \(\nabla_x \log p_\tau\) 와 가짜 분포 확산 모델 스코어 \(\nabla_x \log q_\tau\) 의 차이를 이용해 \(D_{\textrm{KL}}(q_\tau \,\|\, p_\tau)\) 를 따라 하강합니다. 이 차이는 이미 앞에서 만난 바 있습니다. \(\nabla_x \log p_\tau - \nabla_x \log q_\tau = \nabla_x \lambda_\tau\) 는 잡음 섞인 두 분포 사이의 최적 크리틱 \(\lambda_\tau = \log(p_\tau/q_\tau)\) 입력 그레이디언트입니다. 따라서 DMD의 생성자 업데이트는 판별자 대신 두 스코어 신경망이 크리틱 기울기를 공급하는 5 의 비가중(\(w = 1\)) 역방향 KL 업데이트입니다. 두 분포 모두에 잡음이 섞여 있으므로 모든 잡음 수준 \(\tau > 0\) 에서 지지집합이 겹치는데, 이는 곧 16.1.2.3절 의 인스턴스 잡음입니다. DMD2 (Yin, Gharbi, Park, 기타 2024년) 는 여기에 실제 이미지 대비 적대적 판별자를 추가하여 1스텝 학생이 교사 품질을 뛰어넘게 해 줍니다.
  2. 잠재 이미지 오토인코더(토크나이저): 잠재 확산 모델(17.7절)은 오토인코더(예: VQGAN이나 Stable Diffusion VAE, Esser 기타 (2021년); Rombach 기타 (2022년) 참조)를 사용해 이미지를 저차원 잠재 공간으로 압축합니다. 압축된 잠재 코드만으로는 세밀한 국소 질감이 하나로 정해지지 않으므로 픽셀별 \(L_1/L_2\) 및 지각(LPIPS) 손실에 패치 수준 판별자(PatchGAN)를 보강해 디코더를 훈련함으로써 또렷한 고주파 질감을 확보합니다.
  3. 신경망 음성 보코더: 텍스트–음성 변환(TTS) 파이프라인은 보통 프레임 수준 주파수 크기만 지정하고 위상은 버리는 멜 스펙트로그램(mel-spectrogram)을 예측한 뒤 HiFi-GAN (Kong 기타 2020년) 같은 보코더로 스펙트로그램을 오디오 파형으로 역변환합니다. 미지 위상 \(\vartheta \sim \textrm{Uniform}[-a, a]\) 에 대한 정현파 \(\sin(\omega n + \vartheta)\) 의 기댓값은 진폭이 \(\sin(a)/a\) 배로 줄어들어(\(\vartheta \sim \textrm{Uniform}[-\pi, \pi]\) 일 때는 아예 0으로 소멸, 5 참조) 단순 파형 회귀는 침묵으로 붕괴합니다. HiFi-GAN은 그 대신 멜 스펙트로그램 \(L_1\) 손실과 판별자 활성화값 위의 특성 매칭 손실을 다주기(multi-period)·다중 스케일 파형 판별자들과 짝짓습니다.

16.7.3 이 장의 적대적 목적 함수 비교

표 16.7.1 에서는 이 장 전반에서 살펴본 여섯 가지 적대적 정식화를 최적 크리틱 추정 대상, 입력 채점 규칙, 크리틱 함수족 정칙화 방식의 세 가지 차원을 따라 종합합니다.

표 16.7.1: 이 장에서 분석한 적대적 목적 함수 요약.
목적 함수 최적 크리틱 추정 대상 채점 규칙 크리틱 제약 / 정칙화 서로소 지지집합 거동(최적 크리틱 기준)
로그 손실 / \(f\)-GAN (16.1절, 16.2절) \(\log(p/q)\) 또는 \(f'(p/q)\) 단일 샘플 분류 비제약 포화됨
힌지 (16.2절) \(\operatorname{sign}\log(p/q)\) 마진 분류 비제약(또는 스펙트럼 정규화) 포화됨(\(\kappa\)-립시츠 크리틱 시 \(2/\kappa\) 까지 선형)
MMD (16.2절) 커널 평활화된 \(p - q\)(증인 함수) 평균 차이 RKHS 단위 공 커널 대역폭 \(s\) 안에서 0이 아닌 그레이디언트
Wasserstein-1 (16.2절) Kantorovich 퍼텐셜 평균 차이 1-립시츠 공(예: WGAN-GP) 모든 분리 거리에서 단위 기울기
RpGAN (16.3절) \(\log(p/q) + c\) 쌍별 Bradley–Terry 순위 비제약 포화됨
R3GAN: RpGAN + \(R_1 + R_2\) (16.4절) 스케일 \(2\sqrt{\gamma}\) 아래 저역 통과 필터링된 \(\log(p/q)\) 쌍별 Bradley–Terry 순위 \(p\) 와 \(q\) 위의 영중심 입력 그레이디언트 페널티 페널티 신경망을 통한 간격 너머 매끄러운 보간

반복적인 확산 및 플로 모델(17장)과 비교할 때 적대적 생성자는 단일 패스 추론과 불량 설정(underdetermined) 역문제에서의 선명한 출력이라는 장점을 제공하는 대신 네 가지 본질적 난제를 안고 있습니다. (i) 명시적 가능도 평가 불가, (ii) 튜닝된 그레이디언트 페널티가 필요한 두 신경망 결합 미니맥스 동역학, (iii) 누락된 모드에 대한 약한 내재적 페널티(16.1.3.3절), (iv) 대규모 확장 시 잠재적인 훈련 불안정성 (Brock 기타 2019년) 입니다. 다음 장(17장)에서는 미니맥스 훈련을 다단계 반복 디노이징으로 대체하는 확산 모델과 플로 매칭 모델로 넘어갑니다.

16.7.4 요약

제곱 오차 \(\mathbb{E}[\|x - g(c)\|^2]\) 를 최소화하면 예측기가 조건부 평균 \(\mu(c) = \mathbb{E}[x \mid c]\) (식 16.7.1) 쪽으로 내몰리는데, 이는 \(c\) 가 주어졌을 때 타깃 \(x\) 가 모호할 때마다 서로 다른 모드들을 가로질러 평균 내 버립니다. 예측기를 \(\log(p(x, c)/q(x, c))\) 를 추정하는 조건부 판별자 \(D(x, c)\) 와 짝지으면 모드 사이의 저밀도 통로에 놓인 예측에 페널티를 매겨 출력을 데이터 다양체 위로 밀어 올리며 최대 두 배의 MSE 증가(PSNR \(3\text{ dB}\))와 맞바꾸어 지각 사실성을 얻습니다 (Blau 와/과 Michaeli 2018년). 확산 디노이저 역시 사후 평균 \(\mathbb{E}[x_0 \mid x_\tau]\) 를 계산하므로 고잡음 디노이저에 직접 회귀시켜 1스텝 생성자를 증류하면 적대적 크리틱을 함께 넣지 않는 한 흐릿한 평균으로 수축합니다. 바로 같은 이유로 잠재 이미지 오토인코더, 신경망 음성 보코더, 1스텝 증류 확산 생성자에서 적대적 판별자는 여전히 필수 구성 요소로 남아 있습니다.

16.7.5 연습 문제

  1. 이상적 샘플러의 지각–왜곡 트레이드오프. 예측기가 참 조건부 분포 \(p(x \mid c)\) 와 정확히 일치하도록 \(c\) 가 주어졌을 때 \(x\) 와 독립적으로 \(\hat x \sim p(x \mid c)\) 를 뽑는다고 합시다 (Blau 와/과 Michaeli 2018년).
    1. 식 16.7.1 의 분해를 이용해 \(\mathbb{E}\big[(x - \hat x)^2\big] = 2\, \mathbb{E}\big[(x - \mu(c))^2\big]\) 임을 증명하십시오. 정확한 샘플러는 조건부 평균 \(\mu(c)\) 대비 몇 데시벨의 PSNR(\(10 \log_{10}(x_{\max}^2 / \text{MSE})\))을 잃습니까?
    2. 2-띠 분포 식 16.7.2 위에서 정확한 샘플러의 기대 제곱 오차를 \(\mu(c) = c\)(\(1.0025\)) 및 단일 띠 예측기 \(g(c) = c + 1\)(\(2.0025\))과 비교하십시오. 셋 중 최적 크리틱 \(D(x, c)\) 가 참 데이터와 구별할 수 없는 것은 어느 것입니까?
    3. \(x \sim \mathcal{N}(0, 1)\) 이고 독립인 \(\xi \sim \mathcal{N}(0, 1)\) 에 대해 \(c = x + \tau\xi\) 라 합시다. 결정론적 선형 예측기 \(\hat x = c / \sqrt{1 + \tau^2}\) 가 \(x\) 의 주변 분포 \(\mathcal{N}(0, 1)\) 과 일치함을 보이고 \(\tau \in \{0.1, 1, 10\}\) 에 대해 조건부 평균 \(\mathbb{E}[x \mid c]\) 의 MSE 대비 그 MSE 비율을 계산하십시오.
  2. [code] 조건부 평균 대 조건부 중앙값(\(L_2\) 대 \(L_1\)). 절대 오차 \(\mathbb{E}[|x - g(c)|]\) 를 최소화하면 \(P(x \leq x_{\textrm{med}}(c) \mid c) = \tfrac12\) 을 만족하는 조건부 중앙값 \(x_{\textrm{med}}(c)\) 를 얻습니다.
    1. 식 16.7.2 의 오프셋 \(b\) 가 확률 \((\tfrac13, \tfrac13, \tfrac13)\) 또는 \((\tfrac14, \tfrac14, \tfrac12)\) 로 값 \((-1, 0, +1)\) 을 취할 때 각 경우의 조건부 평균과 조건부 중앙값을 구하고 각각이 데이터 띠 위에 놓이는지 밝히십시오.
    2. 비대칭 사전 확률 \(P(b = +1) = r\) 인 2-띠 문제에서 조건부 평균을 \(r\) 의 함수로 계산하고 \(r = \tfrac34\) 일 때 조건부 중앙값이 위쪽 띠에 놓임을 보인 뒤, \(r = \tfrac12\) 일 때 통로 \(g(c) - c \in (-1, 1)\) 에 걸친 \(L_1\) 위험을 규명하십시오.
    3. (a)번과 (b)번 설정 위에서 \(L_1\) 손실을 사용해 g_mse 복사본을 훈련하고 학습된 곡선들을 해석적 예측과 비교하십시오.
  3. [code] 이진 잠재 변수 추가하기. ● 크리틱은 여전히 \((x, c)\) 쌍을 채점하게 둔 채 \(\hat x = g(c, z)\) 가 되도록 16.7.1.2절 의 학생 모델에 독립 균등 이진 잠재 변수 \(z \in \{-1, +1\}\) 을 추가하십시오.
    1. 제곱 오차로 학생 하나, 적대적 손실로 학생 하나를 훈련하고 \(z = -1\) 과 \(z = +1\) 이 각각 어느 띠로 사상되는지 확인하십시오. 제곱 오차 학생은 왜 \(z\) 를 무시합니까?
    2. 암묵적 최대 가능도 추정(IMLE, Li 와/과 Malik (2018년))은 크리틱 없이 \(\mathbb{E}_{(c, x)}[\min_{z \in \{-1, +1\}} (g(c, z) - x)^2]\) 을 최소화합니다. 이 손실로 학생 모델을 훈련하고 각 데이터 점마다 \(z\) 에 대한 최솟값을 취하면 왜 두 잠재 상태가 서로 다른 띠를 덮도록 강제되는지 설명하십시오.
  4. 직접 판별 최적화(DDO). DDO (Zheng 기타 2025년) 는 크리틱을 직접 로그 가능도비 \(D_\theta(x) = \log(q_\theta(x) / q_{\textrm{ref}}(x))\) 로 매개변수화하고 \(\theta = \theta_{\textrm{ref}}\) 에서 출발해 로지스틱 판별자 손실 \(J(\theta) = -\mathbb{E}_{x \sim p}[\log \sigma(D_\theta(x))] - \mathbb{E}_{x \sim q_{\textrm{ref}}}[\log \sigma(-D_\theta(x))]\) 를 최소화함으로써 동결된 기준 복사본 \(q_{\textrm{ref}}\) 대비 가능도 모델 \(q_\theta\) 를 미세 조정합니다.
    1. \(q_\theta = p\) 이면 \(D_\theta(x)\) 가 \(p\) 와 \(q_{\textrm{ref}}\) 사이의 최적 크리틱 \(D^\star(x)\) 와 같음을 보이십시오.
    2. \(\mathbb{E}_{x \sim q_\theta}[\nabla_\theta \log q_\theta(x)] = 0\) 을 이용해 초기화 시점(\(D_\theta(x) = 0\) 인 \(\theta = \theta_{\textrm{ref}}\))에서 그레이디언트 \(\nabla_\theta J(\theta)\) 가 음의 로그 가능도 그레이디언트 \(-\nabla_\theta \mathbb{E}_{x \sim p}[\log q_\theta(x)]\) 의 \(\tfrac12\) 배와 같음을 보이십시오.
  5. 음성 보코더의 위상 모호성과 파형 평균화. 길이 \(N\) 인 단일 오디오 프레임을 \(n = 0, \ldots, N - 1\) 에 대해 정현파 \(x_n = \sin(\omega n + \vartheta)\) 로 모델링합시다(여기서 주파수 \(\omega\) 는 스펙트로그램으로부터 알려져 있고 위상 \(\vartheta \sim \textrm{Uniform}[-a, a]\), \(0 < a \leq \pi\) 는 관측되지 않습니다).
    1. 조건부 평균 파형 \(\mathbb{E}_\vartheta[x_n] = \frac{\sin a}{a}\sin(\omega n)\) 의 진폭이 \(\frac{\sin a}{a}\) 배로 감쇠됨을 보이십시오(\(a = \pi\) 일 때 침묵으로 소멸).
    2. \(\omega = 2\pi k / N\)(\(0 < k < N/2\))일 때 이산 푸리에 변환 크기 \(|\hat x_m|\) 들이 \(\vartheta\) 와 무관함을 보이십시오.
    3. 인접한 두 프레임이 독립 위상 \(\vartheta_1 \neq \vartheta_2\) 로 생성되면 프레임별 DFT 크기 손실은 각 프레임에서 개별적으로 0이 됩니다. 이때 프레임 경계에서 어떤 아티팩트가 발생하며 시간 영역 파형 판별자는 왜 이를 감지해 냅니까?

토론