Adversarial Losses Beyond GANs

Dive into Deep Learning · §16.7

Adversarial Losses Beyond Standalone GANs
conditional-mean blurring · perception–distortion trade-off · diffusion distillation (ADD & DMD2) · VQGAN patch critics · HiFi-GAN speech vocoders

Why Pixelwise Regression Blurs Multimodal Targets

Motivation

  • The averaging failure of pointwise losses: On tasks with multiple plausible outputs x per condition c (super-resolution, inpainting, spectrogram inversion), minimizing pixelwise L_2 or L_1 forces a predictor g(c) to output the conditional mean or median—a blur belonging to none of the modes.
  • Where adversarial critics remain essential today: (1) One-step diffusion distillation (ADD / SDXL-Turbo, DMD2), (2) latent image autoencoders (VQGAN, Stable Diffusion VAE), and (3) neural speech vocoders (HiFi-GAN).

The Conditional-Mean Orthogonal Decomposition

Why L₂ Averages Ambiguity

\mathbb{E}\big[(x - g(c))^2\big] = \underbrace{\mathbb{E}\big[(x - \mu(c))^2\big]}_{\mathrm{Var}(x \mid c)} + \underbrace{\mathbb{E}\big[(\mu(c) - g(c))^2\big]}_{\text{minimized at } g(c) = \mu(c)}

  • Unique L_2 minimizer: Adding and subtracting \mu(c) = \mathbb{E}[x \mid c] eliminates the cross term by iterated expectation, proving g^\star(c) = \mu(c) pixel by pixel.
  • Multimodal void: When p(x \mid c) is bimodal, both the conditional mean \mu(c) (L_2) and conditional median (L_1) sit in the empty low-density void between modes.

The Bimodal Two-Band Benchmark

Minimal Analytical Benchmark

x = c + b + 0.05\,\xi, \qquad b \in \{-1, +1\}\text{ w.p. }\tfrac{1}{2}

  • Conditional mean \mu(c) = c (empty corridor): Lies 20\sigma away from every data point, yet achieves the minimum possible MSE of 1.0025.
  • On-band predictor g(c) = c + 1: Always lands on valid data, yet incurs 2.0025 MSE (2\times larger).
  • Adversarial critic D(x, c): Penalizes the empty corridor (D^\star = \log(p/q) \ll 0) and pushes predictions onto a valid band.

Training Squared-Error vs. Adversarial Predictors

Controlled Code Comparison

We train two identical 2-hidden-layer \tanh MLPs (g_mse and g_adv, 1 \to 32 \to 32 \to 1) from the same initial weights. g_adv adds the data’s observation noise 0.05\,\xi' and trains against a leaky-ReLU critic D(x, c) via gan_loss_D and gan_loss_G:

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)
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)

Two-Band Results: Corridor vs. Mode Commitment

Empirical Verification

Evaluating both trained predictors across 201 inputs c \in [-1, 1] confirms our analytical prediction:

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
  • Squared-error student (g_mse): Tracks the conditional mean x = c down the empty corridor (about one unit from either band; 100\% of predictions off the bands).
  • Adversarial student (g_adv): Commits to a valid data band (a few hundredths from the nearer band on average; at most 2\% of points off the bands where the continuous curve switches branches).

The Perception–Distortion Trade-Off

Blau and Michaeli Theorem

\mathbb{E}\big[(x - \hat{x})^2\big] = \mathbb{E}\big[(x - \mu(c))^2\big] + \mathbb{E}\big[(\mu(c) - \hat{x})^2\big] = 2\,\mathbb{E}\big[(x - \mu(c))^2\big]

  • Exact factor of 2 in MSE: For an ideal stochastic sampler \hat{x} \sim p(x \mid c) matching the conditional data distribution perfectly (q = p), expected squared error is twice that of the conditional mean \mu(c) (2.0050 vs. 1.0025).
  • 3 dB PSNR penalty (Blau & Michaeli, 2018): Perfect perceptual realism inherently costs up to 10\log_{10} 2 \approx 3.01\text{ dB} in PSNR compared to the blurry conditional mean.

Target Ambiguity vs. Model Capacity

Why a Latent Variable Is Required

  • 1. Target ambiguity (aleatoric uncertainty): Because c carries zero bits of information about the band sign b \in \{-1, +1\}, no deterministic function g(c), regardless of width or depth, can cover both bands at the same c.
  • 2. Model capacity limit: Even when a deterministic map exists (like a diffusion ODE), a small 1-step network averages across sharp jumps under L_2 regression.
  • Stochastic latent routing: Equipping the student with z \sim \mathcal{N}(0, 1) lets \hat{x} = g(c, z) route z > 0 and z < 0 to both data bands evenly.

Diffusion Denoisers and One-Step Distillation

Why High-Noise Teachers Blur

D_\tau^\star(x_\tau) = \arg\min_g \mathbb{E}\big[\|x_0 - g(x_\tau)\|^2\big] = \mathbb{E}\big[x_0 \mid x_\tau\big]

  • Low noise (\tau \ll 1) vs. high noise (\tau \gg 1): At low noise, x_\tau = x_0 + \tau\xi fixes x_0 so \mathbb{E}[x_0 \mid x_\tau] is sharp; at high noise, many clean images match x_\tau so \mathbb{E}[x_0 \mid x_\tau] is a blurry average.
  • One-step distillation hazard: Regressing a 1-step student \hat{x} = g(c, z) directly onto a frozen high-noise teacher \mathbb{E}[x_0 \mid \hat{x} + \tau\xi] pulls the student straight toward the conditional mean.

Closed-Form Denoising Teacher on the Two Bands

Analytical Distillation Model

\mathbb{E}\big[c + b \mid \tilde{x}, c\big] = c + \tanh\!\left(\frac{\tilde{x} - c}{\tau^2 + 0.05^2}\right)

  • Exact posterior teacher: By Bayes’ rule on \tilde{x} = x + \tau\xi, the optimal denoiser applies \tanh with slope (\tau^2 + 0.05^2)^{-1}.
  • Contraction to the empty corridor at \tau = 2: Since slope \le (4.0025)^{-1} \approx 0.25 < 1 everywhere, the fixed-point equation u = \mathbb{E}_\xi[\tanh(\frac{u + \sqrt{\tau^2 + 0.05^2}\xi}{\tau^2 + 0.05^2})] contracts every latent z to the unique fixed point u^\star = 0 (the empty corridor).

Implementing One-Step Distillation with a Critic

Code Experiment

train_student trains a stochastic student g(c, z) (z \sim \mathcal{N}(0, 1)) using either the frozen denoising teacher regression loss (\tau = 2.0), an adversarial critic D(x, c), or both combined (critic + regression):

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)

Implementing One-Step Distillation with a Critic (cont.)

Code Experiment

Each step updates the critic (if any), then moves the student toward the critic and toward the teacher’s fixed estimate:

    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()

Distillation Results: Critic Restores Both Bands

Three-Seed Comparison

Evaluating all three student configurations across 201 inputs c and 64 latent quantiles z over three random seeds confirms our fixed-point analysis:

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
  • 1. Teacher regression only: Collapses 100\% of outputs into the empty corridor (about one unit from either band), ignoring z.
  • 2. Critic only & Critic + regression: Both place 98\text{--}99\% of outputs directly on the two data bands (a few hundredths away), splitting probability mass evenly (\sim 49\% / 49\%) between the upper and lower bands via z. Because the band width is \sigma = 0.05, the critic’s sharp restoring force (\sim \delta / 0.05^2 = 400\delta) easily dominates the gentle inward pull of the high-noise teacher (\delta \approx 0.008).

Adversarial Diffusion Distillation (ADD & DMD2)

One-Step Foundation Model Distillation

  • ADD / SDXL-Turbo (Sauer et al., 2023): Pairs squared-error regression toward a frozen diffusion teacher’s denoised estimate with a conditional discriminator built on frozen DINOv2 vision features.
  • DMD & DMD2 (Yin et al., 2024): DMD uses a frozen teacher score \nabla_x \log p_\tau minus a fake score \nabla_x \log q_\tau to move student samples along \nabla_x \log(p_\tau/q_\tau) (the exact input gradient of an optimal log-loss critic), while DMD2 adds a real-image GAN critic to prevent mode dropping.

Latent Image Tokenizers (VQGAN) and PatchGAN

Autoencoders for Latent Diffusion

  • 8× spatial latent compression: Latent diffusion models (Stable Diffusion, Flux) compress H \times W \times 3 images into a compact latent grid via an autoencoder (VQGAN or KL-VAE; Esser et al., 2021; Rombach et al., 2022).
  • Three complementary decoder losses:
    1. Pixelwise L_1/L_2 anchors low-frequency color and layout.
    2. Perceptual LPIPS matches mid-level VGG feature statistics.
    3. PatchGAN critic scores local N \times N patches to enforce crisp high-frequency textures.

Speech Vocoders (HiFi-GAN) and Phase Ambiguity

Why Waveform Regression Collapses to Silence

\mathbb{E}_\vartheta\big[\sin(\omega n + \vartheta)\big] = \frac{\sin a}{a}\,\sin(\omega n) \xrightarrow{a = \pi} 0

  • Why time-domain L_2 waveform regression fails: A mel-spectrogram specifies frequency magnitude \omega but discards phase \vartheta \sim \textrm{Uniform}[-\pi, \pi] (a = \pi), so the conditional-mean waveform is complete silence (\frac{\sin\pi}{\pi} = 0).
  • HiFi-GAN (Kong et al., 2020): Pairs mel-spectrogram L_1 loss with multi-period and multi-scale time-domain waveform critics to enforce coherent phases across frames.

Synthesis: Every Adversarial Game of Chapter 16

Comparing the Six Formulations

Adversarial Formulation Optimal Critic Estimate Scoring Mechanism Critic Constraint / Penalty Disjoint-Support Gradient (at D^\star)
Logistic / f-GAN (§16.1–16.2) \log(p/q) or f'(p/q) Single-sample classification Unconstrained Saturates (\mathrm{JS} = \log 2)
Hinge (§16.2) \operatorname{sign}(\log(p/q)) Margin classification Unconstrained or spectral norm Saturates (linear to 2/\kappa with \kappa-Lip)
MMD (§16.2) Kernel-smoothed p - q Difference of means RKHS unit ball (no critic net) Nonzero within kernel bandwidth s
Wasserstein-1 (§16.2) Kantorovich potential Difference of means 1-Lipschitz ball (WGAN-GP) Constant unit slope at all distances
RpGAN (§16.3) \log(p/q) + c Pairwise Bradley–Terry ranking Unconstrained Saturates (d_{\mathrm{Rp}} = \log 2)
R3GAN (§16.4–16.6) \log(p/q) filtered above 2\sqrt{\gamma} Pairwise Bradley–Terry ranking Zero-centered R_1 + R_2 on p, q Smooth interpolation via damped critic

Concept Check: Blurring, Distillation, and Phase

Check Your Understanding

Test your understanding of conditional-mean blurring and adversarial losses in modern generative pipelines:

  1. PSNR cost of exact sampling: Using Blau and Michaeli’s identity \mathbb{E}[\|x - \hat{x}\|^2] = 2\,\mathbb{E}[\|x - \mu(c)\|^2] for an ideal sampler \hat{x} \sim p(x \mid c), how many decibels of Peak Signal-to-Noise Ratio (\mathrm{PSNR} = 10\log_{10}(x_{\max}^2 / \mathrm{MSE})) does a perfectly realistic generator lose relative to the blurry conditional mean \mu(c)?
  2. Partial phase uncertainty in vocoders: In the sinusoidal audio frame model x_n = \sin(\omega n + \vartheta) with phase \vartheta \sim \textrm{Uniform}[-\pi/2, \pi/2], to what fraction of the true amplitude does L_2 waveform regression shrink the signal? What artifact occurs if a vocoder minimizes only frame-level DFT magnitude error without a time-domain waveform critic?

Answers:

  1. Doubling the MSE reduces \mathrm{PSNR} = 10\log_{10}(x_{\max}^2 / \mathrm{MSE}) by 10\log_{10}(2) \approx \mathbf{3.01\text{ dB}}.
  2. At a = \pi / 2, the amplitude shrinks by \frac{\sin(\pi/2)}{\pi/2} = \mathbf{\frac{2}{\pi} \approx 0.637}. Minimizing only frame-level DFT magnitude error leaves each frame’s phase \vartheta_k independent, creating phase-discontinuity clicks at every frame boundary that a time-domain waveform discriminator immediately penalizes.

Concept Check: Blurring, Distillation, and Phase (cont.)

Check Your Understanding

  1. Selecting the right training paradigm: Among (a) pretraining a general text-to-image foundation model from scratch, (b) distilling a 50-step diffusion model into a 1-step generator, and (c) training a latent diffusion image tokenizer decoder, which tasks use an adversarial critic today?

Answer:

  1. (a) uses multi-step diffusion/flow regression (for broad coverage and stable scaling), whereas (b) one-step diffusion distillation (ADD/DMD2) and (c) latent autoencoder decoders (VQGAN/SD-VAE) both pair regression/perceptual anchors with an adversarial critic to prevent conditional-mean blurring.

Summary: Adversarial Losses Beyond GANs

Key Takeaways

Application / Concept Core Mathematical Identity Why Regression Alone Fails Role of the Adversarial Critic
Conditional-Mean Decomposition \mathbb{E}[(x - g(c))^2] = \mathrm{Var}(x \mid c) + \mathbb{E}[(\mu(c) - g(c))^2] Unique L_2 minimizer \mu(c) = \mathbb{E}[x \mid c] averages across distinct modes Penalizes low-density corridors (D^\star = \log\frac{p}{q} \ll 0) to force mode commitment
Perception–Distortion Trade-Off \mathrm{MSE}(\hat{x} \sim p(\cdot \mid c)) = 2\,\mathrm{MSE}(\mu(c)) Optimizing PSNR/MSE (-3\text{ dB} for exact samples) rewards blurry averages Trades pointwise distortion for distributional realism (q(x \mid c) = p(x \mid c))
One-Step Diffusion Distillation D_\tau^\star(x_\tau) = \mathbb{E}[x_0 \mid x_\tau] (teacher posterior mean) High-noise teacher targets contract one-step students into the conditional mean ADD & DMD2 pair teacher/score regression with a feature critic on real images
Image Tokenizers (VQGAN / VAE) \mathcal{L}_{L_1} + \lambda_{\textrm{perc}}\mathcal{L}_{\textrm{LPIPS}} + \lambda_{\textrm{adv}}\mathcal{L}_{\textrm{PatchGAN}} 8\times latent bottleneck leaves fine local textures ambiguous under L_1/LPIPS PatchGAN critic enforces crisp high-frequency textures across local patches
Speech Vocoders (HiFi-GAN) \mathbb{E}_\vartheta[\sin(\omega n + \vartheta)] = \frac{\sin a}{a}\sin(\omega n) Unknown phase (a = \pi) collapses L_2 waveform predictions to silence (0) Multi-period & multi-scale waveform critics enforce amplitude and phase continuity