4.5.9 · D4Generative Models

Exercises — DCGAN, WGAN, StyleGAN

3,833 words17 min readBack to topic
Figure — DCGAN, WGAN, StyleGAN

Before we start, one shared piece of arithmetic you will reuse everywhere. A transposed convolution (the generator's upsampling layer) maps an input of spatial size to an output size. First, the three knobs it depends on, each defined plainly:

We call this the output-size formula. Read it as: stretch the input by the stride, chop off padding from both edges, add back the kernel's reach, and finally add an optional (a framework knob — PyTorch's ConvTranspose2d exposes it — used to disambiguate size when a stride could produce two valid outputs; it defaults to ). Every exercise below uses , so it quietly drops out, but know it exists when you meet real code. Keep this formula handy.

Figure 2 shows the whole upsampling ladder this formula produces — trace it as you read Level 2 and Level 4.

Figure — DCGAN, WGAN, StyleGAN

Level 1 — Recognition

Exercise 1.1 (L1)

Match each DCGAN guideline to the problem it solves: (a) LeakyReLU in discriminator, (b) tanh at generator output, (c) no BatchNorm on discriminator input, (d) strided convolutions instead of pooling.

Recall Solution
  • (a) LeakyReLU → cures the dying ReLU problem; negative pre-activations still leak a gradient, so neurons keep learning.
  • (b) tanh → squashes output to , matching the range of images that were normalised to .
  • (c) no BatchNorm on discriminator input → recall BatchNorm rescales activations across the batch; on the input layer that would mix real and fake samples together, leaking information across the batch, so each image can no longer be judged on its own.
  • (d) strided convolutions → let the network learn its own down/upsampling instead of a fixed pooling rule, and enable clean upsampling in the generator.

Exercise 1.2 (L1)

In WGAN, the discriminator is renamed the critic. What is the one mathematical property the critic must satisfy that a standard discriminator does not?

Recall Solution

The critic must be 1-Lipschitz: for all inputs. This bounds how fast the critic's output can change. Where this requirement comes from (the Kantorovich–Rubinstein duality, in plain words): the Wasserstein distance is originally defined as a hard "move all the dirt for minimal total work" problem. A classic theorem in optimal transport says that exact same number can instead be computed by searching over functions and taking but only if we restrict to functions whose slope never exceeds 1 (1-Lipschitz). That restriction is what makes the two viewpoints equal, which is why the critic must obey it. A standard discriminator has no such requirement (it just outputs a probability through a sigmoid).

Exercise 1.3 (L1) — StyleGAN

StyleGAN's generator does not feed the latent code straight into the convolutions. It first passes through a small network to get an intermediate code , then injects at every resolution via a mechanism called AdaIN. Name (a) the network that turns into , and (b) what "coarse" layers vs "fine" layers each control.

Recall Solution
  • (a) The mapping network — a small multi-layer perceptron that maps (a plain Gaussian sample) into the intermediate latent code . Why bother: lives on a fixed round Gaussian, which forces unnatural entanglement of features; is free to unwarp into a space where directions line up with real, disentangled attributes.
  • (b) Coarse layers (low resolution, e.g. ) control big-picture attributes — pose, face shape, hairstyle. Fine layers (high resolution) control small details — skin texture, freckles, micro-colour. This split is exactly the independent control the later Level-5 synthesis problem exploits.

Level 2 — Application

Exercise 2.1 (L2)

A DCGAN generator layer receives a feature map of spatial size and applies ConvTranspose2d(kernel=4, stride=2, padding=1). What is the output spatial size?

Recall Solution

Apply the output-size formula (with ) using , , , : Output is . The layer doubles resolution — exactly what we want when climbing , the ladder drawn in Figure 2.

Exercise 2.2 (L2)

The generator projects to a tensor of shape via a fully connected layer. How many output units must that FC layer produce, and how many weights (ignoring bias) does it hold?

Recall Solution

Output units = . Weight count = (input dim) (output dim) weights. This single dense layer is the only fully connected layer allowed — it builds the initial "seed" grid, after which everything is convolutional.

Exercise 2.3 (L2)

A WGAN critic is trained with weight clipping and learning rate . In one critic step the raw gradient for a particular weight is and its current value is . Compute the weight (a) after the gradient descent update, then (b) after clipping.

Recall Solution

The critic descends its loss: . (a) . (b) Clip to : since is inside the range, it is unchanged → . Why clip at all (tie back to WGAN): the critic must stay 1-Lipschitz — its slope must never exceed 1. By the chain rule the critic's slope is bounded by a product of its weights, so if we force every weight to live inside we bound the slope and (crudely) enforce the Lipschitz constraint that makes the Wasserstein estimate — and therefore training — stable. Here the clip does not bite because is already inside the box; it only activates when a weight leaves .


Level 3 — Analysis

Exercise 3.1 (L3)

Two 1-D distributions live on a line (drawn in Figure 3). is all its mass at ; is all its mass at , a single number you control. They do not overlap whenever . (a) What is the Jensen–Shannon divergence for ? (b) What is the Wasserstein distance ? (c) Which one gives a usable gradient , and why does that matter for training?

(Throughout, all logarithms are natural logs, base ; that is why the JS constant reads rather than the base-2 value .)

Figure — DCGAN, WGAN, StyleGAN
Recall Solution

(a) For disjoint supports the JS divergence saturates at the constant (natural log), for every nonzero . It is flat. Figure 3 shows this as the horizontal dashed line. (b) With all mass at and all at , the only coupling moves that single grain a distance , so — the V-shaped magenta line in Figure 3. (c) Differentiate: JS gives zero gradient — the generator learns nothing about which way to move . Wasserstein gives , a constant nonzero push toward . This is precisely why WGAN keeps training when distributions barely overlap: its loss slopes toward the answer instead of sitting on a plateau.

Exercise 3.2 (L3)

You run critic updates per generator update. A colleague says "let's set to train twice as fast." Explain why WGAN specifically wants the critic trained more than the generator, unlike a vanilla GAN where an over-strong discriminator is a disaster.

Recall Solution

In WGAN the critic's job is to estimate the Wasserstein distance: the generator's gradient is only trustworthy once is close to the true supremum . A poorly optimised critic gives a biased distance estimate, so we train it steps to near-optimality before each generator step. In a vanilla GAN the opposite holds: a near-perfect discriminator drives , and the generator's gradient (which contains a -type factor) collapses — the compass goes dead. The difference is that WGAN's critic never saturates (no sigmoid, no plateau), so "stronger critic" means "better distance estimate", not "vanishing signal".

Exercise 3.3 (L3) — StyleGAN

In StyleGAN, AdaIN (adaptive instance normalisation) at a layer first normalises each feature-map channel to mean , variance , then rescales it by a style-derived scale and shift drawn from : . Analyse: why does this design make the style at each resolution overwrite the previous style, giving clean layer-wise control, rather than accumulating?

Recall Solution

The key is the normalisation step happens first, every layer. Because AdaIN divides out the current mean and standard deviation before applying the new , it erases the statistics injected by the previous layer and stamps in fresh ones from .

  • Consequence: the style controlling one resolution is localised to that resolution — it does not leak forward as an accumulating bias.
  • This is what lets "style mixing" work: feed to coarse layers and to fine layers, and you get person A's pose with person B's skin texture, because each block's contribution is overwritten cleanly at the next normalisation. Contrast with simply adding a style vector: additions accumulate, so early-layer choices would bleed into and entangle later ones — exactly the disentanglement AdaIN's normalise-then-modulate order avoids.

Level 4 — Synthesis

Exercise 4.1 (L4)

Design the full generator channel/spatial schedule for RGB output, starting from a seed, doubling spatial size each layer with kernel=4, stride=2, padding=1. Channel rule: every hidden layer halves the channel count of the layer before it; the final layer instead outputs exactly 3 channels (RGB), regardless of what halving would give. List each layer's output shape and count how many transposed-conv layers are needed.

Recall Solution

Doubling from : . That is 5 doublings, so 5 transposed-conv layers. Halving channels through the hidden layers , and then the final layer replaces the halved value with 3 (the RGB requirement — it is not ):

Every layer except the last: BatchNorm → ReLU (recall BatchNorm keeps the activations well-scaled so this deep upsampling stack stays trainable). Last layer: tanh. Trace the widths in Figure 2 — the schedule is the same ladder with one extra rung. (Contrast with the parent's generator, which needed only 4 layers.)

Exercise 4.2 (L4)

Combine ideas: a student replaces WGAN's weight clipping with a hypothetical rule "clip all activations to " and claims this also enforces 1-Lipschitzness. Argue whether bounding outputs is the same as bounding the Lipschitz constant, using a concrete function.

Recall Solution

They are not the same. Lipschitzness bounds the slope, not the range. Consider : its output is always inside (bounded!), yet near its slope is , so its Lipschitz constant is .

  • Bounded output bounded derivative.
  • Weight clipping instead bounds the weights, which by the chain rule bounds the gradient — i.e. the slope — which is what 1-Lipschitz actually requires. So the student's activation-clipping rule fails: a critic could still change arbitrarily fast between two nearby inputs. (This is exactly why later work replaced clipping with a gradient penalty that pins directly.)

Level 5 — Mastery

Exercise 5.1 (L5)

A WGAN critic on the 1-D setup of Exercise 3.1 is the optimal 1-Lipschitz function. Real mass sits at , fake mass at . (a) Recall the critic maximises subject to slope ; show which orientation of a slope-1 line this forces, and evaluate the objective. (b) The generator minimises . Compute and state which direction moves. (c) Show the generator's update drives toward , i.e. fake mass toward real mass.

Recall Solution

(a) Deriving the critic's orientation — this is the WHY that fixes the sign. The critic maximises over all functions with slope at most 1. On the interval the biggest possible gap between and under a slope- cap is achieved when decreases as fast as allowed, i.e. slope , giving (up to a constant). Check the alternative : it gives , so it would minimise, not maximise — the critic would never choose it. Hence the optimiser converges to , and the objective value is ✓. The negative orientation is forced by the maximisation, not chosen by hand. (b) With the correctly-oriented critic : , so . Gradient descent moves : fake mass slides down toward 0. (c) Each step subtracts from , monotonically decreasing until where real and fake coincide — the training goal. The key mastery point: because has slope exactly everywhere, the gradient magnitude stays the whole way, never vanishing regardless of how far apart the piles started.

Exercise 5.2 (L5)

Synthesise all three architectures into one flow: given a task "generate 1024×1024 faces with control over pose vs. skin texture, training stably from disjoint early distributions", state which single contribution from each of DCGAN, WGAN, StyleGAN you would keep, and why the combination is necessary.

Recall Solution
  • From DCGAN: the convolutional generator/discriminator backbone with strided (transposed) convolutions and BatchNorm — it gives spatially-coherent upsampling from a seed to high resolution. Without it you have no scalable image network at all.
  • From WGAN: the Wasserstein/critic loss — the disjoint early distributions would kill a JS-based generator's gradient ( plateau), whereas Wasserstein keeps a meaningful slope, so training starts at all.
  • From StyleGAN: the style-based generator injecting the intermediate code at multiple resolutions via AdaIN — coarse layers control pose, fine layers control skin texture, giving the requested independent control the other two cannot provide. Necessity: DCGAN gives the how to build, WGAN gives the how to train stably, StyleGAN gives the how to control. Drop any one and the requirement (high-res and stable and controllable) fails.

Exercise 5.3 (L5) — StyleGAN

Mastery of the style split: you have two intermediate codes, (a person with a round face, front pose) and (a person with fine freckled skin). You feed to the layers at resolutions and to layers . Predict the generated face, and justify using the AdaIN-overwrite property from Exercise 3.3.

Recall Solution

Prediction: the face keeps person A's pose and overall shape (round face, front-facing) but wears person B's fine skin detail and freckles. Justification: coarse layers () receive , so the big-picture geometry is stamped in there. When we reach , AdaIN first normalises away the running statistics and then re-modulates with 's scale/shift — this overwrites only the fine-scale style, and because normalisation is re-applied at every subsequent layer, owns all the high-frequency detail without disturbing the coarse geometry already realised. This clean separation is only possible because AdaIN normalises before modulating (Exercise 3.3); with additive styles the two codes would entangle and you'd get a muddled blend rather than a crisp A-pose / B-skin combination.


Recall Self-test cloze recap

The transposed-conv output size is ==. JS divergence between disjoint distributions saturates at == (natural log ), giving zero gradient. Wasserstein between point masses at and equals ==. The WGAN critic must be 1-Lipschitz== (bounded slope, not bounded output). StyleGAN maps to via the mapping network, and injects per-layer via AdaIN. AdaIN normalises before modulating, which is why each layer's style overwrites rather than accumulates. "1-Lipschitz" means the graph's slope never exceeds :::