16.6 Conditional Generation

The generators in Section 16.1 and Section 16.5 are unconditional: they draw random samples from the marginal data distribution p(x)p(x) without any way to specify a desired class, text prompt, or input image. Shortly after the original GAN paper, Mirza and Osindero (2014) introduced conditional GANs (cGANs) by feeding a conditioning variable cc to both the generator G(z,c)G(z, c) and the discriminator D(x,c)D(x, c).

In this section, we address three questions:

  1. What objective does the conditional formulation optimize, and what does its optimal critic estimate?
  2. How should the conditioning variable cc be incorporated into the generator and discriminator architectures?
  3. How do we evaluate a conditional generator separately for condition alignment, sample fidelity, and within-class diversity?

We illustrate these concepts by training and evaluating a class-conditional generator on the 10 classes of CIFAR-10.

16.6.1 The Conditional Objective#

16.6.1.1 The Optimal Conditional Critic#

Let data–condition pairs (x,c)∼p(x,c)(x, c) \sim p(x, c) be drawn from the joint data distribution, where cc may be a discrete class label, a text embedding, or an image. To match the condition marginal p(c)p(c), we sample c∼p(c)c \sim p(c) from the real data and generate x′=G(z,c)∼q(⋅∣c)x' = G(z, c) \sim q(\cdot \mid c), inducing the generated joint distribution q(x,c)=p(c) q(x∣c)q(x, c) = p(c)\,q(x \mid c). The conditional log-loss objective applies the classic binary log-loss formulation (Section 16.1) to the pairs (x,c)(x, c):

V(D)=E(x,c)∼p[log⁡σ(D(x,c))]+Ec∼p(c),  x′∼q(⋅∣c)[log⁡σ(−D(x′,c))].(16.6.1)\begin{aligned} V(D) &= \mathbb{E}_{(x, c) \sim p}\big[\log \sigma(D(x, c))\big] \\ &\quad + \mathbb{E}_{c \sim p(c),\; x' \sim q(\cdot \mid c)}\big[\log \sigma(-D(x', c))\big]. \end{aligned} \tag{16.6.1}

Because the pointwise optimization over D(x,c)D(x, c) is identical to the unconditional derivation on the product space X×C\mathcal{X} \times \mathcal{C}, the optimal conditional critic is the log ratio of the joint densities, from which the shared marginal p(c)p(c) cancels:

D⋆(x,c)=log⁡p(x,c)q(x,c)=log⁡p(c) p(x∣c)p(c) q(x∣c)=log⁡p(x∣c)q(x∣c).(16.6.2)\begin{aligned} D^\star(x, c) &= \log \frac{p(x, c)}{q(x, c)} = \log \frac{p(c)\, p(x \mid c)}{p(c)\, q(x \mid c)} = \log \frac{p(x \mid c)}{q(x \mid c)} . \end{aligned} \tag{16.6.2}

Thus, for each condition cc, the optimal critic computes the log density ratio between the conditional distributions p(⋅∣c)p(\cdot \mid c) and q(⋅∣c)q(\cdot \mid c). Substituting D⋆(x,c)D^\star(x, c) back into (16.6.1) yields the expected conditional Jensen–Shannon divergence:

max⁡DV(D)=Ec∼p(c)[ 2 JS(p(⋅∣c), q(⋅∣c))]−2log⁡2.(16.6.3)\begin{aligned} \max_D V(D) &= \mathbb{E}_{c \sim p(c)}\Big[\, 2\, \mathrm{JS}\big(p(\cdot \mid c),\, q(\cdot \mid c)\big) \Big] - 2 \log 2 . \end{aligned} \tag{16.6.3}

This attains its global minimum −2log⁡2-2\log 2 if and only if q(⋅∣c)=p(⋅∣c)q(\cdot \mid c) = p(\cdot \mid c) for every condition cc with p(c)>0p(c) > 0.

16.6.1.2 Conditional versus Marginal Matching#

Matching every conditional slice q(⋅∣c)=p(⋅∣c)q(\cdot \mid c) = p(\cdot \mid c) is strictly stronger than matching the marginal image distribution q(x)=p(x)q(x) = p(x). For example, suppose a CIFAR-10 generator produces realistic images but shifts all class labels cyclically (q(⋅∣c)=p(⋅∣c+1)q(\cdot \mid c) = p(\cdot \mid c + 1)). Because all 10 classes have equal prior probability p(c)=1/10p(c) = 1/10, its marginal image distribution q(x)q(x) matches p(x)p(x) exactly, achieving the minimum unconditional divergence JS(p(x),q(x))=0\mathrm{JS}(p(x), q(x)) = 0. In the conditional objective (16.6.3), however, every slice is compared against a mismatched class (JS(p(⋅∣c),p(⋅∣c+1))≈log⁡2\mathrm{JS}(p(\cdot \mid c), p(\cdot \mid c+1)) \approx \log 2), yielding a near-maximal conditional divergence (Exercise 1).

Conversely, note that each condition cc is weighted by its prior frequency p(c)p(c) in (16.6.3): a rare condition with probability p(c)=ϵp(c) = \epsilon contributes at most 2ϵlog⁡22\epsilon \log 2 to the objective, so imbalanced datasets often require class-balanced sampling to prevent the generator from ignoring rare classes.

16.6.2 Conditioning Architectures#

16.6.2.1 Three Conditioning Mechanisms#

Figure 16.6.1 illustrates the three primary ways to feed a condition cc into a generator or discriminator:

  1. Concatenation (Mirza and Osindero, 2014) embeds cc into a vector ece_c and concatenates it with the latent vector zz (or broadcasts and concatenates it with spatial feature maps).
  2. Feature modulation scales and shifts each channel of an intermediate feature map hh via learned functions of cc: a(c)⊙h+b(c)a(c) \odot h + b(c). When hh is normalized first, this is conditional batch normalization (de Vries et al., 2017; Brock et al., 2019) (or AdaIN / FiLM), injecting the condition at every resolution of the generator.
  3. Projection discriminator head (Miyato and Koyama, 2018) takes the inner product of a class embedding ece_c with the discriminator's pooled feature vector ϕ(x)\phi(x) and adds an unconditional score ψ0(x)\psi_0(x).
Figure 16.6.1:

Three conditioning mechanisms for GANs. Left: concatenation appends an embedding ece_c to the input or feature map. Middle: feature modulation applies a condition-dependent channelwise scale and shift a(c)⊙h+b(c)a(c) \odot h + b(c). Right: the projection discriminator head computes ec⊤ϕ(x)+ψ0(x)e_c^\top \phi(x) + \psi_0(x).

Below, we implement Modulate with per-class scale and shift embedding tables initialized to a(c)=1a(c) = 1 and b(c)=0b(c) = 0 (the identity mapping), and verify that a gradient step on class 3 updates only row 3 of the embedding tables.

class Modulate(nn.Module):
    """Scale and shift each channel of h by a(c) and b(c), one row per class."""
    def __init__(self, num_classes, channels):
        super().__init__()
        self.a = nn.Embedding(num_classes, channels)
        self.b = nn.Embedding(num_classes, channels)
        nn.init.ones_(self.a.weight)   # a(c) = 1, b(c) = 0: the identity
        nn.init.zeros_(self.b.weight)

    def forward(self, h, c):
        return self.a(c)[:, :, None, None] * h + self.b(c)[:, :, None, None]

Before running the layer, we can predict two things. At initialization the output must equal the input, whatever the class. And a gradient step on a batch that requests only class 3 (cat, in the CIFAR-10 order used below) must change row 3 of each table and no other, because an embedding lookup passes gradient only to the rows it read. The check takes one such step toward the toy target 2h+12h + 1.

torch.manual_seed(0)
mod = Modulate(10, 8)
h = torch.randn(10, 8, 4, 4)  # one feature map per class
with torch.no_grad():
    print('at initialization: max |out - h| =',
          float((mod(h, torch.arange(10)) - h).abs().max()))
a0, b0 = mod.a.weight.detach().clone(), mod.b.weight.detach().clone()
c3 = torch.full((10,), 3)  # a batch that requests class 3 only
loss = ((mod(h, c3) - (2 * h + 1)) ** 2).mean()
loss.backward()
torch.optim.SGD(mod.parameters(), lr=0.1).step()
rows = lambda w, w0: (w != w0).any(1).nonzero().flatten().tolist()
print('after one step on class 3: rows changed in a', rows(mod.a.weight, a0),
      'and in b', rows(mod.b.weight, b0))
at initialization: max |out - h| = 0.0
after one step on class 3: rows changed in a [3] and in b [3]

16.6.2.2 Deriving the Projection Head via Bayes' Rule#

Applying Bayes' rule p(x∣c)=p(c∣x)p(x)/p(c)p(x \mid c) = p(c \mid x)p(x)/p(c) to the numerator and denominator of (16.6.2) (with shared prior p(c)p(c)) decomposes the optimal conditional critic into two terms:

log⁡p(x∣c)q(x∣c)  =  log⁡p(c∣x)q(c∣x)+log⁡p(x)q(x).(16.6.4)\log \frac{p(x \mid c)}{q(x \mid c)} \;=\; \log \frac{p(c \mid x)}{q(c \mid x)} + \log \frac{p(x)}{q(x)} . \tag{16.6.4}

The first term measures class alignment (the log ratio of the real and generated class posteriors at xx), while the second measures unconditional sample realism. If we model both class posteriors as softmax classifiers over a shared feature representation ϕ(x)\phi(x), namely p(c∣x)∝exp⁡(uc⊤ϕ(x))p(c \mid x) \propto \exp(u_c^\top \phi(x)) and q(c∣x)∝exp⁡(wc⊤ϕ(x))q(c \mid x) \propto \exp(w_c^\top \phi(x)), their log ratio is (uc−wc)⊤ϕ(x)(u_c - w_c)^\top \phi(x) plus a cc-independent log-partition difference. Absorbing the log-partition difference and log⁡(p(x)/q(x))\log(p(x)/q(x)) into a single scalar head ψ0(x)\psi_0(x) and setting ec=uc−wce_c = u_c - w_c yields the projection discriminator of Miyato and Koyama (2018) (Exercise 2; compare with the auxiliary classifier GAN in Exercise 6):

D(x,c)  =  ec⊤ϕ(x)+ψ0(x).(16.6.5)D(x, c) \;=\; e_c^\top \phi(x) + \psi_0(x). \tag{16.6.5}

16.6.3 Class-Conditional Generation on CIFAR-10#

We now train a class-conditional generator on the 50,000 labeled 32×3232 \times 32 training images of CIFAR-10 (5,000 per class, loaded via d2l.load_cifar10_arrays).

classes = ['airplane', 'automobile', 'bird', 'cat', 'deer',
           'dog', 'frog', 'horse', 'ship', 'truck']
device = d2l.try_gpu()
train_X, train_y, test_X, test_y = d2l.load_cifar10_arrays()
first = [int((train_y == c).nonzero()[0]) for c in range(10)]
d2l.show_images(train_X[first].cpu().permute(0, 2, 3, 1) / 2 + 0.5,
                num_rows=2, num_cols=5, titles=classes);

16.6.3.1 Conditional Generator and Projection Critic#

We extend d2l.Generator and d2l.Discriminator (Section 16.5) at 32×3232 \times 32 resolution:

  • CondGenerator passes a 64D unit-variance class embedding broadcast to 4×4×644 \times 4 \times 64 into the generator's extra input slot (Exercise 4 compares this input concatenation with per-block Modulate layers).
  • ProjectionCritic sums the 4×44 \times 4 feature map self.phi(x) spatially to obtain ϕ(x)\phi(x) and evaluates ec⊤ϕ(x)+ψ0(ϕ(x))e_c^\top \phi(x) + \psi_0(\phi(x)) ((16.6.5)), initializing ec=0e_c = 0 so the critic starts as an unconditional discriminator.
class CondGenerator(d2l.Generator):
    """The backbone generator with a class embedding as extra 4x4 maps."""
    def __init__(self, latent_dim, resolution, base_ch, embed_dim=64,
                 num_classes=10):
        super().__init__(latent_dim, resolution, base_ch, extra_ch=embed_dim)
        self.embed = nn.Embedding(num_classes, embed_dim)  # unit variance

    def forward(self, z, y):
        ec = self.embed(y)[:, :, None, None].expand(-1, -1, 4, 4)
        return super().forward(z, ec)

ProjectionCritic implements (16.6.5). The base class's phi returns the 4×44 \times 4 feature map after the mixing convolution; summing it over positions gives ϕ(x)\phi(x). A linear head on ϕ(x)\phi(x) gives ψ0(x)\psi_0(x) and replaces the base head, which reads the flattened map, and a table holds one embedding ece_c per class. The table starts at zero, so the critic begins as an unconditional critic and learns the label term from the data.

class ProjectionCritic(d2l.Discriminator):
    """The backbone critic with a projection head: e_c . phi(x) + psi_0(x)."""
    def __init__(self, resolution, base_ch, num_classes=10):
        super().__init__(resolution, base_ch)
        width = self.mix.out_channels
        self.head = nn.Linear(width, 1)  # psi_0 on the pooled features
        d2l.fan_in_init(self.head)
        self.embed = nn.Embedding(num_classes, width)
        nn.init.zeros_(self.embed.weight)  # start as an unconditional critic

    def forward(self, x, y):
        phi = self.phi(x).sum(dim=(2, 3))  # sum over the 4x4 positions
        return (self.embed(y) * phi).sum(dim=1) + self.head(phi).squeeze(-1)

net_G, net_D = CondGenerator(100, 32, 256), ProjectionCritic(32, 64)
print(net_G(torch.zeros(2, 100), torch.zeros(2, dtype=torch.long)).shape)
print(net_D(torch.zeros(2, 3, 32, 32),
            torch.zeros(2, dtype=torch.long)).shape)
torch.Size([2, 3, 32, 32])
torch.Size([2])

16.6.3.2 Training with Same-Class Pairs#

We train with d2l.train_r3gan (Section 16.5) for 15,000 steps using batch size 128 and gradient penalty weight γ=0.5\gamma = 0.5. In each minibatch, the generated images are conditioned on the exact class labels yy of the real minibatch, so the relativistic pairing loss log⁡σ(D(x,c)−D(x′,c))\log \sigma(D(x, c) - D(x', c)) always compares a real image and a generated image of the same class cc. Note that because comparisons are purely within-class, D(x,c)D(x, c) is shift-invariant up to an independent additive constant ζc\zeta_c per class (Exercise 3); the logged held-out pairwise ranking accuracy P^(D(x,c)>D(x′,c))\hat P(D(x, c) > D(x', c)) on 512 test pairs is invariant to these per-class shifts.

torch.manual_seed(0)  # the initialization
net_G = CondGenerator(100, 32, 256).to(device)
net_D = ProjectionCritic(32, 64).to(device)
gamma = 0.5
ema_G, history = d2l.train_r3gan(
    net_G, net_D, d2l.rpgan_loss_D, d2l.rpgan_loss_G, gamma, 15000, train_X,
    train_y, eval_images=test_X, eval_labels=test_y, eval_size=512,
    batch_size=128, seed=1)

We average the logs over the last 5,000 steps, and the pair accuracy also over the first 2,000.

loss_D, loss_G, pen, acc = (np.mean(v[-5000 // 250:]) for v in (
    history['loss_D'], history['loss_G'], history['R1'] + history['R2'],
    history['accuracy']))
acc_early = history['accuracy'][history['step'] <= 2000].mean()
print(f'last 5,000 steps: critic loss {loss_D:.2f} (+ penalty '
      f'{gamma / 2 * pen:.3f}), generator loss {loss_G:.2f}, '
      f'pair accuracy {acc:.2f}')
print(f'first 2,000 steps: pair accuracy {acc_early:.2f}')
last 5,000 steps: critic loss 0.52 (+ penalty 0.062), generator loss 1.05, pair accuracy 0.79
first 2,000 steps: pair accuracy 0.83

Plotting the full trajectories of loss_D, loss_G, and held-out accuracy across all 15,000 steps shows how quickly the projection critic and conditional generator settle into a steady game:

steps = history['step']
fig, axes = d2l.plt.subplots(1, 2, figsize=(9, 3.2))
d2l.plot(steps, [history['loss_D'], history['loss_G'],
                 np.full_like(steps, np.log(2))], 'step', 'loss',
         legend=['critic (pairing part)', 'generator', 'log 2'],
         fmts=('-', '--', 'k:'), yscale='log', axes=axes[0])
d2l.plot(steps, [history['accuracy'], np.full_like(steps, 0.5)], 'step',
         'held-out pair accuracy', ylim=[0.3, 1], fmts=('-', 'k:'),
         axes=axes[1]);

After an initial transient, the critic's pairing loss stabilizes near 0.520.52 (below log⁡2≈0.69\log 2 \approx 0.69) and held-out same-class pair ranking accuracy settles around 0.800.80.

16.6.3.3 Class-Conditioned Samples#

Below, we generate 9 samples for each of the 10 CIFAR-10 classes from ema_G.

torch.manual_seed(42)
z = torch.randn(90, 100, device=device)
y = torch.arange(10, device=device).repeat_interleave(9)  # nine per class
with torch.no_grad():
    imgs = ema_G(z, y)
panels = [d2l.tile_images(imgs[9 * c:9 * (c + 1)], 3) for c in range(10)]
d2l.show_images(panels, 2, 5, titles=classes, scale=2);

Each 3×33 \times 3 panel reflects the visual characteristics of its requested class (e.g., blue skies and water for airplanes and ships, green foliage for frogs and deer, road backgrounds for automobiles and trucks) while varying pose and color across the 9 latent draws.

16.6.4 Evaluating a Conditional Generator#

A conditional generator can fail along three distinct axes:

  1. Wrong class (poor condition alignment),
  2. Unrealistic images (poor sample fidelity), or
  3. Lack of within-class diversity (mode dropping within each class).

As summarized in Table 16.6.1, no single metric captures all three failure modes. We therefore combine a referee classifier (measuring class alignment) with marginal feature distances (FD and MMD2\mathrm{MMD}^2) and per-class KK-NN precision and recall.

Table 16.6.1. Sensitivity of evaluation metrics to conditional generation failure modes.
failure modeclass alignmentmarginal FD, MMD2\mathrm{MMD}^2per-class precisionper-class recall
wrong classdetectsblinddetectsdetects
poor image fidelitypartialdetectsdetectspartial
low within-class diversityblind (may reward)detectsblind (may reward)detects

16.6.4.1 Referee Classifier and Class Alignment#

We train the 3-block CIFAR-10 classifier d2l.FeatureCNN (Section 16.5) for 15 epochs as our independent referee (achieving ∼78%\sim 78\% test accuracy) and use both its class predictions and its 128D penultimate feature layer.

torch.manual_seed(0)
cnn = d2l.FeatureCNN(resolution=32).to(device)
d2l.train_feature_cnn(cnn, train_X, train_y, shift=4)
pred = d2l.batched(cnn, test_X).argmax(1)
cls_acc = [float((pred[test_y == c] == c).float().mean())
           for c in range(10)]
print(f'CIFAR-10 test accuracy: {float((pred == test_y).float().mean()):.3f}')
CIFAR-10 test accuracy: 0.779

We generate 500 images per class from ema_G and compare the referee's classification accuracy on generated images (alignment) against its accuracy on real test images of each class.

def generate(seed, n=500):
    """n images of each class from the EMA generator, in class order."""
    torch.manual_seed(seed)
    z = torch.randn(10 * n, 100, device=device)
    y = torch.arange(10, device=device).repeat_interleave(n)
    with torch.no_grad():
        return torch.cat([ema_G(z_k, y_k) for z_k, y_k in
                          zip(z.split(1000), y.split(1000))])

raw = generate(7)
gen = raw.clamp(-1, 1)
yg = np.repeat(np.arange(10), 500)  # the requested classes
pred_gen = d2l.batched(cnn, gen).argmax(1).cpu().numpy()
align = [float((pred_gen[yg == c] == c).mean()) for c in range(10)]

Tabulating align alongside the referee's accuracy cls_acc on real test images for each of the 10 classes shows how well ema_G respects the requested class label:

print(f'{"class":12s}{"alignment":>11s}{"real":>7s}{"gap":>7s}')
for name, a, r in zip(classes + ['mean'], align + [np.mean(align)],
                      cls_acc + [np.mean(cls_acc)]):
    print(f'{name:12s}{a:11.2f}{r:7.2f}{a - r:+7.2f}')
class         alignment   real    gap
airplane           0.80   0.78  +0.01
automobile         0.82   0.91  -0.09
bird               0.66   0.67  -0.01
cat                0.54   0.57  -0.03
deer               0.66   0.71  -0.05
dog                0.69   0.76  -0.06
frog               0.78   0.85  -0.07
horse              0.76   0.80  -0.05
ship               0.86   0.87  -0.01
truck              0.79   0.87  -0.08
mean               0.74   0.78  -0.04

Mean class alignment across the 10 classes is 0.72–0.740.72\text{--}0.74, only 4–64\text{--}6 percentage points below the referee's accuracy on real CIFAR-10 test images (0.780.78).

16.6.4.2 Fidelity and Within-Class Diversity#

Next, we split the 1,000 test images per class into a 500-image reference set (f_real) and a 500-image real floor set (f_real2), and compute marginal FD and MMD2\mathrm{MMD}^2 (d2l.fid_score, d2l.kid_score) as well as per-class KK-NN precision and recall (d2l.precision_recall with K=3K = 3).

features = lambda imgs: d2l.batched(cnn.features, imgs).cpu().numpy()
out_of_range = float((raw.abs() > 1).float().mean())
idx = test_y.argsort(stable=True).reshape(10, 1000)  # row c: class c
f_real = features(test_X[idx[:, :500].flatten()])    # the reference
f_real2 = features(test_X[idx[:, 500:].flatten()])   # the floor
f_gen = features(gen)
f_gen2 = features(generate(8).clamp(-1, 1))          # a second draw
idx, pred_real = idx.cpu().numpy(), pred.cpu().numpy()

We now compare the marginal feature distance (d2l.fid_score) and squared MMD (d2l.kid_score) against the reference set f_real for the real test floor f_real2 and both generated draws (f_gen, f_gen2), and check the fraction of raw pixel values out_of_range:

draws = {'real (the floor)': f_real2, 'generated': f_gen,
         'generated, second draw': f_gen2}
print(f'{"against the reference":24s}{"FD (CIFAR-CNN)":>16s}'
      f'{"MMD^2 (CIFAR-CNN)":>19s}')
for name, f in draws.items():
    print(f'{name:24s}{d2l.fid_score(f, f_real):16.2f}'
          f'{d2l.kid_score(f, f_real):19.3f}')
print(f'generated values outside [-1, 1]: {out_of_range:.3f}')
against the reference     FD (CIFAR-CNN)  MMD^2 (CIFAR-CNN)
real (the floor)                    0.15             -0.001
generated                           1.60              0.105
generated, second draw              1.65              0.108
generated values outside [-1, 1]: 0.010

In FD the generated set lies ten to twelve times as far from the reference as the floor does, and the second draw moves FD by less than a tenth, so the distance belongs to the generator, not to the draw. In MMD2\mathrm{MMD}^2 the floor sits at zero within its noise and the generated set at about 0.11. About one raw value in a hundred lies outside [−1,1][-1, 1] before the clamp, so the clamp changes few pixels and hides little.

The distances fold every difference into one number. Per-class precision and recall separate two kinds of difference: generated images unlike any real image of their class, and real images unlike any generated one. Around each feature vector, draw a ball that reaches to its third-nearest neighbor in its own set (Section 16.5.4.3). Precision is the fraction of generated images of class cc that fall inside some real ball of class cc, and recall is the fraction of real images of class cc that fall inside some generated ball. The cell computes both for each class against the reference, prints their means over classes and the worst class, and ends with the within-class feature variance, the variance of the features within each class averaged over features and classes.

by_class = lambda f: np.asarray(f).reshape(10, -1, f.shape[-1])

def pr_by_class(f):
    """Precision and recall of each class of f against the reference."""
    return np.array([d2l.precision_recall(r, g) for r, g in
                     zip(by_class(f_real), by_class(f))])

print(f'{"per class, k = 3":24s}{"precision":>10s}{"worst class":>17s}'
      f'{"recall":>8s}{"worst class":>17s}')
for name, f in draws.items():
    pr = pr_by_class(f)
    lo = pr.argmin(0)
    print(f'{name:24s}{pr[:, 0].mean():10.2f}{classes[lo[0]]:>12s}'
          f'{pr[lo[0], 0]:5.2f}{pr[:, 1].mean():8.2f}'
          f'{classes[lo[1]]:>12s}{pr[lo[1], 1]:5.2f}')
# Variance within each class, averaged over features and classes
cvar = lambda f: float(by_class(f).astype(np.float64).var(1).mean())
print(f'within-class feature variance: generated {cvar(f_gen):.3f}, '
      f'real {cvar(f_real):.3f}, the floor {cvar(f_real2):.3f}')
per class, k = 3         precision      worst class  recall      worst class
real (the floor)              0.85       truck 0.77    0.84        bird 0.80
generated                     0.90       truck 0.85    0.59       horse 0.52
generated, second draw        0.90       truck 0.84    0.59       truck 0.53
within-class feature variance: generated 0.174, real 0.217, the floor 0.212

Per-class precision is actually higher for generated images (0.900.90) than for the real floor (0.850.85), indicating that generated features lie well inside the real class clusters, whereas per-class recall is substantially lower (0.580.58 vs. 0.830.83, accompanied by a ~20% lower within-class feature variance), showing that the generator concentrates near the modes of each class rather than covering their full diversity.

16.6.4.3 A Centroid-Prototype Baseline#

To see why high alignment and high precision can mask a lack of diversity, we construct a prototype baseline by selecting the 100 real floor images per class whose features lie closest to their class centroid, and compare them against 100 random real floor images and 100 generated images per class.

floor = by_class(f_real2)  # test images 500-999 of each class
dist = ((floor - floor.mean(1, keepdims=True)) ** 2).sum(-1)
near = np.argsort(dist, axis=1)[:, :100]  # 100 distinct images per class
rows = np.arange(10)[:, None]
sets = {  # 100 images per class: features and the referee's predictions
    'real, random': (floor[:, :100], pred_real[idx[:, 500:600]]),
    'real, nearest centroid': (floor[rows, near],
                               pred_real[idx[:, 500:][rows, near]]),
    'generated': (by_class(f_gen)[:, :100],
                  pred_gen.reshape(10, 500)[:, :100])}
print(f'{"100 per class":24s}{"alignment":>10s}{"FD":>7s}{"MMD^2":>8s}'
      f'{"precision":>10s}{"recall":>8s}')
for name, (f, p) in sets.items():
    f = f.reshape(1000, -1)
    prec, rec = pr_by_class(f).mean(0)
    print(f'{name:24s}{(p == rows).mean():10.2f}'
          f'{d2l.fid_score(f, f_real):7.2f}{d2l.kid_score(f, f_real):8.3f}'
          f'{prec:10.2f}{rec:8.2f}')
100 per class            alignment     FD   MMD^2 precision  recall
real, random                  0.78   0.43  -0.003      0.85    0.85
real, nearest centroid        0.91   3.03   0.123      0.97    0.37
generated                     0.74   1.59   0.077      0.89    0.67

As predicted in Table 16.6.1, the nearest-centroid prototypes achieve near-perfect alignment (about 0.90.9, higher than random real images) and precision (about 0.970.97), but suffer from severely degraded recall (under 0.40.4 vs. about 0.850.85) and worse FD (about 33 vs. 0.430.43) because their feature covariance is artificially contracted. BigGAN's truncation trick deliberately trades recall for higher precision and alignment by truncating the latent distribution zz toward zero (Exercise 5).

16.6.5 Summary#

Conditioning both the generator G(z,c)G(z, c) and critic D(x,c)D(x, c) on c∼p(c)c \sim p(c) yields the optimal slice-wise critic D⋆(x,c)=log⁡(p(x∣c)/q(x∣c))D^\star(x, c) = \log(p(x \mid c)/q(x \mid c)) and minimizes the expected conditional divergence Ec∼p(c)[2 JS(p(⋅∣c),q(⋅∣c))]−2log⁡2\mathbb{E}_{c \sim p(c)}[2\,\mathrm{JS}(p(\cdot \mid c), q(\cdot \mid c))] - 2\log 2. Applying Bayes' rule decomposes D⋆(x,c)D^\star(x, c) into a class-alignment term log⁡(p(c∣x)/q(c∣x))\log(p(c \mid x)/q(c \mid x)) and an unconditional realism term log⁡(p(x)/q(x))\log(p(x)/q(x)), motivating the projection discriminator head D(x,c)=ec⊤ϕ(x)+ψ0(x)D(x, c) = e_c^\top \phi(x) + \psi_0(x) (Miyato and Koyama, 2018). Evaluating a conditional generator requires separating condition alignment (via an independent referee classifier), sample fidelity (per-class precision), and within-class diversity (per-class recall and feature distances). Without a recall metric, a generator that emits only canonical class prototypes can achieve high classifier alignment and high precision while collapsing intra-class diversity.

16.6.6 Exercises#

  1. [code] Two Gaussian slices with known densities. Let c∈{1,2}c \in \{1, 2\} be equiprobable with p(⋅∣1)=N(−2,1)p(\cdot \mid 1) = \mathcal{N}(-2, 1) and p(⋅∣2)=N(2,1)p(\cdot \mid 2) = \mathcal{N}(2, 1), and suppose q(⋅∣1)=N(0,1)q(\cdot \mid 1) = \mathcal{N}(0, 1) while q(⋅∣2)=N(2,1)q(\cdot \mid 2) = \mathcal{N}(2, 1).

    1. Compute the theoretical value (16.6.3) by 1D numerical quadrature.
    2. Train a small MLP critic on (x,one_hot(c))(x, \text{one\_hot}(c)) to maximize (16.6.1), verify that its converged objective matches (a), and plot D(x,c)D(x, c) against the exact log density ratio (16.6.2) for both slices.
    3. Now suppose the generator swaps the two classes: q(⋅∣1)=N(2,1)q(\cdot \mid 1) = \mathcal{N}(2, 1) and q(⋅∣2)=N(−2,1)q(\cdot \mid 2) = \mathcal{N}(-2, 1). Compute both the conditional value (16.6.3) and the marginal unconditional value (ignoring cc), and verify by training.
  2. Expressiveness of the projection discriminator head. The derivation of (16.6.5) assumed a shared feature map ϕ(x)\phi(x) for both p(c∣x)p(c \mid x) and q(c∣x)q(c \mid x).

    1. If p(c∣x)∝exp⁡(uc⊤ϕp(x))p(c \mid x) \propto \exp(u_c^\top \phi_p(x)) and q(c∣x)∝exp⁡(wc⊤ϕq(x))q(c \mid x) \propto \exp(w_c^\top \phi_q(x)) use distinct feature maps, show that the resulting optimal critic still has the projection form (16.6.5) over the concatenated feature vector (ϕp(x),ϕq(x))(\phi_p(x), \phi_q(x)).
    2. For KK discrete classes, show that any function D(x,c)D(x, c) can be written in the form ec⊤ϕ(x)+ψ0(x)e_c^\top \phi(x) + \psi_0(x) whenever dim⁡(ϕ(x))≥K\dim(\phi(x)) \geq K.
  3. [short-code] Using the projection critic as a classifier. The trained projection critic net_D assigns ten scores Sic=D(xi,c)S_{ic} = D(x_i, c) to each image xix_i.

    1. Use (16.6.4) to express D⋆(x,c)−D⋆(x,c′)D^\star(x, c) - D^\star(x, c') in terms of p(c∣x)p(c \mid x) and q(c∣x)q(c \mid x). Why does arg⁡max⁡cD⋆(x,c)\arg\max_c D^\star(x, c) differ from the Bayes classifier arg⁡max⁡cp(c∣x)\arg\max_c p(c \mid x)?
    2. Because same-class pairing leaves an arbitrary per-class shift ζc\zeta_c in D(x,c)D(x, c), estimate ζ^c\hat\zeta_c as the mean critic score on generated images of class cc, and compare the classification accuracy on test_X of raw arg⁡max⁡cSic\arg\max_c S_{ic} versus shift-corrected arg⁡max⁡c(Sic−ζ^c)\arg\max_c (S_{ic} - \hat\zeta_c).
    3. Why must the shift-corrected critic accuracy approach random guessing (1/101/10) as q(⋅∣c)→p(⋅∣c)q(\cdot \mid c) \to p(\cdot \mid c)?
  4. [code] Modulated generator versus input concatenation. ● Build a conditional generator in which class information enters via a Modulate layer after every convolution block rather than input concatenation.

    1. At initialization (a(c)=1,b(c)=0a(c) = 1, b(c) = 0), the modulated generator's output is independent of cc. Trace how nonzero gradients with respect to a(c)a(c) and b(c)b(c) arise on the first generator step from the projection critic.
    2. Train both the modulated generator and CondGenerator for 4,000 steps across two seeds each, and compare their mean class alignment and per-class recall.
  5. [code] The truncation trick and the precision–recall trade-off. The truncation trick (Brock et al., 2019) samples each latent coordinate from a standard normal distribution truncated to [−τ,τ][-\tau, \tau].

    1. For a 100D latent vector and τ∈{0.5,1,2}\tau \in \{0.5, 1, 2\}, compute the expected squared norm E[∥z∥2]\mathbb{E}[\|z\|^2] under truncated sampling and compare it with E[∥z∥2]=100\mathbb{E}[\|z\|^2] = 100 during training.
    2. Evaluate ema_G under truncated sampling for τ∈{0.5,1,2,∞}\tau \in \{0.5, 1, 2, \infty\} and report class alignment, per-class precision and recall, and FD against f_real. Verify that decreasing τ\tau trades recall for higher alignment and precision, moving the generator toward the centroid-prototype regime.

    Adapted from Simon Prince, Understanding Deep Learning, Problem 15.6.

  6. Auxiliary Classifier GAN (AC-GAN) bias. ● An AC-GAN (Odena et al., 2017) trains an auxiliary classifier C(c∣x)C(c \mid x) and adds the cross-entropy −Ec∼p(c),x∼q(⋅∣c)[log⁡C(c∣x)]-\mathbb{E}_{c \sim p(c), x \sim q(\cdot \mid c)}[\log C(c \mid x)] to the generator loss.

    1. Show that this auxiliary generator loss equals
Ex∼q[H(q(⋅∣x))+DKL(q(⋅∣x) ∥ C(⋅∣x))].\mathbb{E}_{x \sim q}\Big[H\big(q(\cdot \mid x)\big) + D_{\textrm{KL}}\big(q(\cdot \mid x) \,\|\, C(\cdot \mid x)\big)\Big].
  1. When C(c∣x)=p(c∣x)C(c \mid x) = p(c \mid x) and classes overlap (H(p(⋅∣x))>0H(p(\cdot \mid x)) > 0), explain why minimizing this term encourages the generator to avoid overlapping regions of the data distribution, reducing within-class diversity compared to the projection discriminator ((16.6.4)).

Discussions