Conditional Generation and Projection Discriminators conditional minimax game · slice-wise JS divergence · feature modulation · Miyato–Koyama projection head · alignment vs. diversity evaluation
Why Unconditional GANs Cannot Obey Class Requests
Motivation
Unconditional generators draw random samples from the marginal image distribution p(x) without any mechanism to request a specific class c (e.g., “bird” or “ship”), text caption, or source image:
Marginal matching \neq conditional alignment: Suppose a 10-class CIFAR-10 generator produces realistic images but shifts every label cyclically: q(x \mid c) = p(x \mid c + 1 \bmod 10).
Because all 10 classes have equal prior p(c) = \frac{1}{10}, its marginal distribution q(x) = \sum_c p(c)q(x \mid c) = p(x) matches the data perfectly(\mathrm{JS}(p(x), q(x)) = 0), even though every class request returns the wrong object.
Solution (Mirza & Osindero, 2014): Feed the condition c to both the generator G(z, c) and the discriminator D(x, c).
Joint real vs. generated pairs: Compare real pairs (x, c) \sim p(x, c) against generated pairs where c \sim p(c) is drawn from the real marginal and x' = G(z, c) \sim q(\cdot \mid c).
Cancellation of the shared prior p(c): Pointwise optimization on \mathcal{X} \times \mathcal{C} cancels p(c) in numerator and denominator, recovering the exact slice-wise log density ratio.
Expected Conditional JS Divergence and Rare Classes
Independent game per condition slice c: Attains global minimum -2\log 2 iff q(\cdot \mid c) = p(\cdot \mid c) for every c with p(c) > 0 (detecting cyclic label shifts immediately).
Rare-class pitfall: Because slice c is weighted by p(c), a rare class with p(c) = 10^{-3} contributes at most 0.0014 nats—motivating class-balanced minibatch sampling.
Three Architectural Mechanisms for Conditioning
Generator & Critic Conditioning
Concatenation (Mirza & Osindero, 2014): Embed c \mapsto e_c and concatenate with the latent vector z or broadcast across spatial feature maps (e.g., 4 \times 4 \times d_e).
Feature modulation (Conditional BatchNorm / AdaIN / FiLM): Apply a condition-dependent channelwise scale and shift a(c) \odot h + b(c) after convolutions across the generator.
Projection discriminator head (Miyato & Koyama, 2018): Compute the inner product e_c^\top \phi(x) + \psi_0(x) between a class embedding e_c and the critic’s pooled feature vector \phi(x).
Channelwise Feature Modulation Layer
Identity Init & Sparse Gradients
Modulate stores per-class scale a(c) and shift b(c) embedding tables initialized to the identity transform a(c) = \mathbf{1}, b(c) = \mathbf{0}. Because an embedding lookup backpropagates gradients only to the rows read in the minibatch, a step on class 3 updates only row 3:
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):returnself.a(c)[:, :, None, None] * h +self.b(c)[:, :, None, None]
at initialization: max |out - h| = 0.0
after one step on class 3: rows changed in a [3] and in b [3]
Additive decomposition: Bayes’ rule splits the conditional log-ratio into class alignment\log(p(c \mid x)/q(c \mid x)) plus unconditional realism\log(p(x)/q(x)).
Inner-product head (Miyato & Koyama, 2018): Modeling p(c \mid x) and q(c \mid x) as softmax classifiers over critic features \phi(x) makes their log-ratio linear in \phi(x) with class embedding e_c = u_c - w_c.
Entropy-reduction bias of AC-GAN (Odena et al., 2017): Minimizing H(q(\cdot \mid x')) penalizes the generator for placing samples where true classes overlap (H(p(\cdot \mid x)) > 0), collapsing intra-class diversity toward exaggerated canonical prototypes.
Unbiased projection critic: Estimates \log(p(c \mid x)/q(c \mid x)), which vanishes at q(\cdot \mid c) = p(\cdot \mid c) without forcing conditional entropy to zero.
Implementing CondGenerator and ProjectionCritic
32×32 CIFAR-10 Backbone
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 variancedef forward(self, z, y): ec =self.embed(y)[:, :, None, None].expand(-1, -1, 4, 4)returnsuper().forward(z, ec)
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_channelsself.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 criticdef forward(self, x, y): phi =self.phi(x).sum(dim=(2, 3)) # sum over the 4x4 positionsreturn (self.embed(y) * phi).sum(dim=1) +self.head(phi).squeeze(-1)
Implementing CondGenerator and ProjectionCritic (cont.)
32×32 CIFAR-10 Backbone
A shape check: the generator maps 100-dimensional latents and labels to 32 \times 32 RGB images, and the critic returns one score per image:
We train CondGenerator and ProjectionCritic on 50{,}000 CIFAR-10 images (32 \times 32) for 15{,}000 steps via train_r3gan (batch size 128, \gamma = 0.5), pairing each real image with a generated image of the same class c:
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
Same-class pairing loss:-\mathbb{E}_{c}[\log \sigma(D(x, c) - D(x', c))] stabilizes near 0.52 (below \log 2 \approx 0.69), with held-out same-class ranking accuracy settling around 0.80.
Per-class shift invariance: Because comparisons occur only within each class c, shifting D(x, c) \mapsto D(x, c) + \zeta_c by an arbitrary class-dependent constant \zeta_c leaves the pairing loss unchanged.
Class-Conditioned CIFAR-10 Samples
Visualizing 10 Requested Classes
Generating 9 random latent draws for each of the 10 requested CIFAR-10 classes from the EMA generator ema_G:
Three Orthogonal Failure Axes in Evaluation
Evaluation Taxonomy
Axis 1: Wrong class (q(\cdot \mid c) = p(\cdot \mid c')): Detected immediately by an independent referee classifier, whereas marginal FD and \mathrm{MMD}^2 are completely blind if the marginal mixture matches.
Axis 2: Poor sample fidelity (blur/artifacts): Detected by marginal FD and per-class K-NN precision.
Axis 3: Low intra-class diversity (prototype collapse): Referee accuracy and precision actually reward canonical prototypes; per-class K-NN recall is required to catch mode dropping within class c.
Measuring Class Alignment with a Referee CNN
Axis 1: Condition Alignment
We train our 3-block CIFAR-10 classifier FeatureCNN (with horizontal flips and 4-pixel shifts) for 15 epochs as an independent referee (78\% test accuracy) and evaluate its accuracy on 500 generated images per class:
CIFAR-10 test accuracy: 0.779
Close match to real photographs: Mean class alignment across the 10 classes is 0.72\text{--}0.74, only 4\text{--}6 percentage points below the referee’s accuracy on real CIFAR-10 test images (0.78).
Both real and generated images find cat(0.51\text{--}0.58) hardest and automobile/ship/truck(\ge 0.79) easiest.
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
Marginal Feature Distances vs. Real Test Floor
Axis 2: Marginal Distribution Match
Splitting the 10{,}000 CIFAR-10 test images into a 5{,}000-image reference set (f_real,500 per class) and a 5{,}000-image real floor (f_real2,500 per class) benchmarks our 5{,}000 generated images in the referee’s 128D feature space:
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
The generated set scores \mathrm{FD} \approx 1.6\text{--}2.0(10\text{--}12\times the finite-sample real floor of 0.16) and \mathrm{MMD}^2 \approx 0.11, with a second latent draw shifting FD by < 0.1. Less than 1\% of raw generator outputs fall outside [-1, 1] before clamping.
Per-Class Precision and Recall on CIFAR-10
Axis 3: Within-Class Coverage
Computing 3-NN precision and recall separately within each class c against the 500 reference test images of class c separates sample realism from within-class diversity:
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
Higher precision than the real floor (0.90 vs. 0.85): Generated features lie well inside the high-density core of each real class cluster.
Lower recall (0.58 vs. 0.83) and 20\% lower intra-class variance: Roughly 42\% of real test images have no generated neighbor within their 3-NN ball—showing that the generator concentrates near canonical class modes rather than covering the full diversity of each class.
The Prototype Trap: Alignment Rewards Collapse
Centroid-Prototype Baseline
To prove that high classifier alignment and high precision can mask a collapse in diversity, we construct a prototype baseline by selecting the 100 real floor images per class nearest their class feature centroid:
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
The prototype paradox: Selecting only the 100 most canonical real images per class boosts class alignment to \approx 0.9 (beating random real images at \approx 0.8) and precision to \approx 0.97, while collapsing recall from \approx 0.85 \to \approx 0.37 and worsening FD sevenfold (0.43 \to \approx 3). BigGAN’s truncation trick deliberately exploits this trade-off by truncating z \in [-\tau, \tau].
Concept Check: Conditional Critics and Metrics
Check Your Understanding
Test your understanding of conditional GAN architectures and evaluation:
Comparing critic scores across classes: After same-class RpGAN training on CIFAR-10, your projection critic has mean score +4.2 on real cats and -1.5 on real trucks. Does this mean the critic finds cats more realistic than trucks?
Effect of latent truncation (\tau \downarrow): BigGAN’s truncation trick samples each latent coordinate from a standard normal truncated to [-\tau, \tau]. As \tau decreases from \infty toward 0.5, in which direction will class alignment, per-class precision, per-class recall, and FD move?
Answers:
No. Because same-class pairing only ever evaluates differences D(x, c) - D(x', c) within the same class c, adding an arbitrary per-class offset \zeta_c leaves the objective unchanged. Scores across different classes are not on a shared scale.
Truncating z pulls generated samples toward the high-density centroid of each class, mimicking the nearest-centroid prototype baseline: class alignment and precision increase, while per-class recall drops and FD worsens (increases).
Concept Check: Conditional Critics and Metrics (cont.)
Check Your Understanding
Using the critic as a post-hoc classifier: Why must a shift-corrected optimal conditional critic D^\star(x, c) = \log(p(x \mid c)/q(x \mid c)) drop to random-guessing classification accuracy (1/10) as the generator converges (q(\cdot \mid c) \to p(\cdot \mid c))?
Answer:
By Bayes’ rule, D^\star(x, c) - D^\star(x, c')= \log \frac{p(c \mid x)}{p(c' \mid x)} - \log \frac{q(c \mid x)}{q(c' \mid x)}. As q(\cdot \mid c) \to p(\cdot \mid c), the generated posterior matches the true posterior and D^\star(x, c) \to 0 for every class c.