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 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 to both the generator and the discriminator .
In this section, we address three questions:
- What objective does the conditional formulation optimize, and what does its optimal critic estimate?
- How should the conditioning variable be incorporated into the generator and discriminator architectures?
- 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 be drawn from the joint data distribution, where may be a discrete class label, a text embedding, or an image. To match the condition marginal , we sample from the real data and generate , inducing the generated joint distribution . The conditional log-loss objective applies the classic binary log-loss formulation (Section 16.1) to the pairs :
Because the pointwise optimization over is identical to the unconditional derivation on the product space , the optimal conditional critic is the log ratio of the joint densities, from which the shared marginal cancels:
Thus, for each condition , the optimal critic computes the log density ratio between the conditional distributions and . Substituting back into (16.6.1) yields the expected conditional Jensen–Shannon divergence:
This attains its global minimum if and only if for every condition with .
16.6.1.2 Conditional versus Marginal Matching#
Matching every conditional slice is strictly stronger than matching the marginal image distribution . For example, suppose a CIFAR-10 generator produces realistic images but shifts all class labels cyclically (). Because all 10 classes have equal prior probability , its marginal image distribution matches exactly, achieving the minimum unconditional divergence . In the conditional objective (16.6.3), however, every slice is compared against a mismatched class (), yielding a near-maximal conditional divergence (Exercise 1).
Conversely, note that each condition is weighted by its prior frequency in (16.6.3): a rare condition with probability contributes at most 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 into a generator or discriminator:
- Concatenation (Mirza and Osindero, 2014) embeds into a vector and concatenates it with the latent vector (or broadcasts and concatenates it with spatial feature maps).
- Feature modulation scales and shifts each channel of an intermediate feature map via learned functions of : . When 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.
- Projection discriminator head (Miyato and Koyama, 2018) takes the inner product of a class embedding with the discriminator's pooled feature vector and adds an unconditional score .
Three conditioning mechanisms for GANs. Left: concatenation appends an embedding to the input or feature map. Middle: feature modulation applies a condition-dependent channelwise scale and shift . Right: the projection discriminator head computes .
Below, we implement Modulate with per-class scale and shift embedding tables initialized to and (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 .
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 to the numerator and denominator of (16.6.2) (with shared prior ) decomposes the optimal conditional critic into two terms:
The first term measures class alignment (the log ratio of the real and generated class posteriors at ), while the second measures unconditional sample realism. If we model both class posteriors as softmax classifiers over a shared feature representation , namely and , their log ratio is plus a -independent log-partition difference. Absorbing the log-partition difference and into a single scalar head and setting yields the projection discriminator of Miyato and Koyama (2018) (Exercise 2; compare with the auxiliary classifier GAN in Exercise 6):
16.6.3 Class-Conditional Generation on CIFAR-10#
We now train a class-conditional generator on the 50,000 labeled 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 resolution:
CondGeneratorpasses a 64D unit-variance class embedding broadcast to into the generator'sextrainput slot (Exercise 4 compares this input concatenation with per-blockModulatelayers).ProjectionCriticsums the feature mapself.phi(x)spatially to obtain and evaluates ((16.6.5)), initializing 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 feature map after the mixing convolution; summing it over positions gives . A linear head on gives and replaces the base head, which reads the flattened map, and a table holds one embedding 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 . In each minibatch, the generated images are conditioned on the exact class labels of the real minibatch, so the relativistic pairing loss always compares a real image and a generated image of the same class . Note that because comparisons are purely within-class, is shift-invariant up to an independent additive constant per class (Exercise 3); the logged held-out pairwise ranking accuracy 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 (below ) and held-out same-class pair ranking accuracy settles around .
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 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:
- Wrong class (poor condition alignment),
- Unrealistic images (poor sample fidelity), or
- 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 ) and per-class -NN precision and recall.
| failure mode | class alignment | marginal FD, | per-class precision | per-class recall |
|---|---|---|---|---|
| wrong class | detects | blind | detects | detects |
| poor image fidelity | partial | detects | detects | partial |
| low within-class diversity | blind (may reward) | detects | blind (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 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 , only percentage points below the referee's accuracy on real CIFAR-10 test images ().
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 (d2l.fid_score, d2l.kid_score) as well as per-class -NN precision and recall (d2l.precision_recall with ).
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 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 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 that fall inside some real ball of class , and recall is the fraction of real images of class 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 () than for the real floor (), indicating that generated features lie well inside the real class clusters, whereas per-class recall is substantially lower ( vs. , 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 , higher than random real images) and precision (about ), but suffer from severely degraded recall (under vs. about ) and worse FD (about vs. ) because their feature covariance is artificially contracted. BigGAN's truncation trick deliberately trades recall for higher precision and alignment by truncating the latent distribution toward zero (Exercise 5).
16.6.5 Summary#
Conditioning both the generator and critic on yields the optimal slice-wise critic and minimizes the expected conditional divergence . Applying Bayes' rule decomposes into a class-alignment term and an unconditional realism term , motivating the projection discriminator head (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#
-
[code] Two Gaussian slices with known densities. Let be equiprobable with and , and suppose while .
- Compute the theoretical value (16.6.3) by 1D numerical quadrature.
- Train a small MLP critic on to maximize (16.6.1), verify that its converged objective matches (a), and plot against the exact log density ratio (16.6.2) for both slices.
- Now suppose the generator swaps the two classes: and . Compute both the conditional value (16.6.3) and the marginal unconditional value (ignoring ), and verify by training.
-
Expressiveness of the projection discriminator head. The derivation of (16.6.5) assumed a shared feature map for both and .
- If and use distinct feature maps, show that the resulting optimal critic still has the projection form (16.6.5) over the concatenated feature vector .
- For discrete classes, show that any function can be written in the form whenever .
-
[short-code] Using the projection critic as a classifier. The trained projection critic
net_Dassigns ten scores to each image .- Use (16.6.4) to express in terms of and . Why does differ from the Bayes classifier ?
- Because same-class pairing leaves an arbitrary per-class shift in , estimate as the mean critic score on generated images of class , and compare the classification accuracy on
test_Xof raw versus shift-corrected . - Why must the shift-corrected critic accuracy approach random guessing () as ?
-
[code] Modulated generator versus input concatenation. ● Build a conditional generator in which class information enters via a
Modulatelayer after every convolution block rather than input concatenation.- At initialization (), the modulated generator's output is independent of . Trace how nonzero gradients with respect to and arise on the first generator step from the projection critic.
- Train both the modulated generator and
CondGeneratorfor 4,000 steps across two seeds each, and compare their mean class alignment and per-class recall.
-
[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 .
- For a 100D latent vector and , compute the expected squared norm under truncated sampling and compare it with during training.
- Evaluate
ema_Gunder truncated sampling for and report class alignment, per-class precision and recall, and FD againstf_real. Verify that decreasing 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.
-
Auxiliary Classifier GAN (AC-GAN) bias. ● An AC-GAN (Odena et al., 2017) trains an auxiliary classifier and adds the cross-entropy to the generator loss.
- Show that this auxiliary generator loss equals
- When and classes overlap (), 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)).