Skip to main content
Unsupervised Deep Learning

Variants of Generative Adversarial Networks

Published: 2026-08-25
Level: postgraduate
Audience: Postgraduate students studying generative models

Prerequisite Knowledge

This lecture builds on the following concepts from earlier lectures. If any feel unfamiliar, review the linked notes before proceeding.

Previously Covered in This Subject

  • Generative Adversarial Networks — generator versus discriminator, min-max training and its brittleness, transposed convolutions for parallel generation — covered in Lecture 1
  • Attention and Transformers — attention as a mechanism that lets one position gather information from others — covered in Lecture 5

These notes cover the main branches of the GAN family built on the Wasserstein idea. First comes the refresher: how the Wasserstein distance and the critic replace the shaky original GAN loss. Then three ways to enforce the smoothness demand that makes the Wasserstein setup work: weight clipping, the gradient penalty, and spectral normalization. Two quality boosters follow — self-attention, which lets every image position consult every other position, and progressive growing, which builds huge images resolution by resolution.

The second half turns random generation into directed generation: the conditional GAN steers samples with class labels, Pix2Pix converts one image into another rendering of it, the auxiliary classifier GAN adds label prediction to the judge, and CycleGAN learns style changes without paired examples. Each section keeps the spoken explanation next to every formula, so you can trace how each equation was introduced and why each design exists.

12.1 WGAN Refresher: Wasserstein Distance and the Critic

Before new material, we rebuild the base. The Wasserstein GAN replaces the unstable divergence used in the original GAN with a smoother way to measure how far two probability distributions sit from each other. Everything later in these notes — clipping, gradient penalty, spectral normalization — depends on this one shift.

Hook: The original GAN measures "how different are these two distributions" with a yardstick that breaks exactly when training gets hard. What if we swapped in a ruler that keeps giving useful readings even when the two distributions do not overlap at all?

12.1.1 Wasserstein Distance and Duality

The Wasserstein distance is a distance metric on probability densities. It is well behaved and stable, and it can measure when two probability densities differ. The picture to hold in mind is earth moving: the distance is about "finding the best possible plan of converting one particular discrete probability distribution to another discrete probability distribution". You decide how much mass to move from each pile of the first distribution to each pile of the second, and you pick the cheapest such plan.

Intuition: Think of a freight company moving sand between warehouses. Each warehouse holds some fraction of the total sand (a probability value). A transport plan says how many truckloads go from every origin warehouse to every destination warehouse. The cost of a plan is the sum over routes of (mass moved) times (distance traveled). The cheapest plan's price is the Wasserstein distance: the least work needed to reshape one distribution into the other. The analogy breaks at high dimensions — real images are not piles on a line, they are points in a thousand-dimensional space — but the logic of "cheapest complete reshaping plan" survives unchanged.

Now formalize this. Let be the real distribution over bins and the target distribution, both defined over discrete bins. Let be the cost of moving one unit of mass from bin to bin — a natural choice is the index gap . A transport plan is a matrix , where entry records how much mass travels from bin to bin . The Wasserstein distance is the price of the best plan:

subject to three constraints that make a legal shipping schedule:

Read the constraints out loud: each row must ship out exactly what bin owns; each column must deliver exactly what bin expects; no route can carry negative cargo. Every symbol here is a plain quantity — nothing exotic. The minimization picks the single cheapest schedule among all schedules that satisfy those rules.

This plan search is costly. With support points there are plan entries to decide, so the computation grows on the order of — "order n square for sure", as it was put. Solving a full transport problem inside a training loop, which runs thousands of updates, is impractical.

The escape is a duality principle from linear programming. It says the same value can be reached from another direction: instead of planning transports, look for one scoring function whose gap between the two distributions equals the distance. In its primal form the transport problem minimizes a cost over plans ; the dual problem maximizes a score over per-bin values , subject to the rule that adjacent scores cannot differ by more than one. For the continuous version used in GANs, the dual reads:

where the maximization runs over functions whose slope never exceeds one in absolute value. That slope cap is exactly the "adjacent values cannot change by more than one" rule lifted from bins to a continuum. The scoring function is what the GAN world calls the discriminator, and in the Wasserstein setting it is called the critic. Training a network to be the critic trains it to compute the distance — without ever building a transport plan.

Worked example — duality on a two-bin problem. Let the real distribution be and the target be , with cost .

Primal side. Bin 1 must empty out (its row sums to 0.5 but column 1 demands 0), so 0.5 units travel from bin 1 to bin 2. Work done: . No cheaper plan exists because the move is forced. So the Wasserstein distance is 0.5.

Dual side. Pick scores — adjacent scores differ by exactly one, which is allowed. Then . Both directions land on the same number — that agreement is the duality principle doing its job. Sense check: the answer cannot exceed total moved mass times unit distance, and 0.5 sits right at that ceiling.

12.1.2 The Critic Function and Its Value Range

The critic gives a high value or a low value — a continuous value — depending on how good the generated data is. Unlike the classic discriminator output, this number does not live between zero and one. It is "a number between minus infinity to plus infinity". Nothing forces it to be a straight-line function either; the point is only that it spans negative values up to positive values.

Scope: Because the critic's output is an unbounded score, it is not a probability. Do not pass it through a sigmoid and read it as "% real" — the sigmoid would squash away the very differences the Wasserstein objective cares about. The only restriction placed on the critic is on its slope, not its range.

That slope restriction has a name. A K-Lipschitz function satisfies

for all input pairs . Here is the critic function, and are any two inputs, and bounds how fast the output may change relative to input change. Spoken form: "the derivative of the function, if it is less than or equal to one, then it is one Lipschitz; it is K Lipschitz if it is less than or equal to K in absolute value". The one-Lipschitz case is simply : tilt your hand holding a pencil along the critic's graph, and the steepest tilt you can meet is 45 degrees.

Visual intuition: plot two narrow, non-overlapping bell curves on the same axes — horizontal axis is the data value, vertical axis is density. The original GAN's loss goes flat between them: zero gradient, no learning signal. Now draw a gently rising line above them with slope at most 1, higher over the right curve than the left one. That line is the critic. Because its height difference encodes the distance, sliding either curve changes the line's tilt, and gradients keep flowing even across the empty gap.

Why does this matter for training? A Lipschitz critic has well-behaved derivative values almost everywhere, and those derivatives are what flow into the generator update. Bounded slopes mean the generator always receives a usable push toward realism — this is why the Wasserstein setup trains smoothly where the old setup stalled.

12.1.3 The WGAN Objective

Here is the value function optimized in WGAN training, with a generated sample, a real training sample, a latent vector drawn from a noise distribution , and the generator network:

Every symbol: is the real data distribution, is the distribution induced by the generator, and means the search over critics is restricted to one-Lipschitz functions. The spoken walk-through, rephrased: minimize the whole expression with respect to ; for real data, should return the high value, and for fake data that number will be small, so you subtract a small number from a large number — the goal is to maximize with respect to .

Reading the objective in two directions.

  • The critic's move (inner max): open the gap. Score real samples high and generated samples low. At the optimum, the size of that gap equals the Wasserstein distance between and .
  • The generator's move (outer min): close the gap. If makes samples that fool the critic, then rises, the subtraction bites, and the generator's loss falls.

Each iteration plays one move per player. The critic climbs toward the true distance; the generator then walks down a landscape that always points it toward the real data. Neither player ever sees a dead zone with no gradient.

Why bother switching divergences? Using Jensen-Shannon divergence or KL divergence to compare the two distributions is what triggers instability and mode collapse, where the generator produces only a few kinds of outputs — imagine a digit generator that draws 1s and 7s forever and never attempts an 8. Those divergences behave badly when the two distributions barely overlap: the measured difference shoots to a constant and the gradient dies. The Wasserstein measure alleviates that problem to a great extent, gives much better control over mode collapse, and stays forgiving about architectural choices.

Pitfalls:

  1. Reading as a confidence probability. It is an unbounded score; the sigmoid interpretation belongs to the original GAN only.
  2. Forgetting which direction optimizes which player. The critic maximizes the expected gap; the generator minimizes the whole expression. Mixing them up flips the sign of your update.
  3. Believing the Wasserstein distance is computed numerically during training. It is estimated indirectly through the critic, via duality. The transport plan is never built.
  4. Dropping the Lipschitz restriction. Without it the maximization is unbounded — the critic can separate any two distributions by an infinite margin, and the "distance" reading collapses.

Real-world: this stability is why WGAN-family models became the default backbone for many image-generation pipelines, from super-resolution systems to synthetic-data generators used in medical imaging research. Any product that needs reliable day-after-day GAN training inherited this design decision.

Recap + bridge: The Wasserstein distance is the cheapest way to reshuffle one distribution into another; duality turns that planning problem into a search for a bounded-slope scorer, the critic; the WGAN objective is just that scorer's real-versus-fake gap, maximized by the critic and minimized by the generator. Next question: the critic promised to stay one-Lipschitz — who enforces that promise during training? Section 12.2 answers with the first, blunt enforcement tool.

12.2 Weight Clipping in Standard WGAN

The first WGAN enforced the one-Lipschitz demand with a blunt tool: squeeze the weights. It worked well enough to prove the idea, and it exposed exactly why a smarter tool was needed. Even the authors of the original paper said at the time that clipping was not the right long-term answer — they simply lacked something better.

Hook: How do you force a deep neural network to keep a gentle slope everywhere, without changing its architecture or loss? The first answer was almost comically simple: put every single weight in a tiny box.

12.2.1 Clipping Weights to Enforce One-Lipschitz

After every critic update, clamp every weight into a fixed box:

Here is any weight of the critic and is the weight clipping parameter — a small positive constant you pick. The clip operator returns unchanged when , snaps up to when , and snaps down to when . When you implement standard WGAN, this parameter is the knob you set.

Worked example — one clipping step. Take a critic weight vector and clipping bound .

  • First entry: → snapped up to .
  • Second entry: sits inside → left alone.
  • Third entry: → snapped down to .

Result: . Every weight now lives inside the box. Sense check: no output value can fall outside , no matter what the gradient update tried to do.

Why does boxing weights control slope? A network's output changes when its inputs change through a chain of weighted multiplications. If each weight is small, each multiplication can only stretch its input by a bounded amount, so the composed function cannot swing steeply — with all weights boxed, the critic function cannot grow an arbitrarily steep tilt, and the -Lipschitz condition holds in practice.

12.2.2 Gradient Control and Depth Limits

Why must be small? One diagnostic plot makes the danger visible. Its horizontal axis lists the discriminator layers from input to output; its vertical axis shows the gradient magnitude on a log scale; one curve is drawn per value of . With large boxes, the curves climb out of control as they cross layers — the exploding-gradient regime, where each successive layer multiplies the problem. So you must use a small value of , and you must also restrict the number of layers in the critic. Deep critics plus loose boxes invite the same explosion, because more layers mean more multiplicative stretch opportunities stacked in a row.

The original WGAN paper used a box of roughly — tight enough that gradients stay tame, loose enough that some learning still happens.

12.2.3 The Capacity Problem at the Two Extremes

Clipping has a hidden flaw that people observed during training. You clip so that and act as minimum and maximum values for the weights once training ends. But the weights do not spread out evenly inside the box: they pile up pressed against the two walls. Almost no weights sit at intermediate values.

Visual intuition: draw a histogram of the trained weights with weight value on the horizontal axis and count on the vertical axis. A healthy network gives a hill-shaped histogram centered near zero. A clipped WGAN gives two tall spikes at exactly and with an empty valley between them — the training pushes weights against the walls, and the clip keeps snapping them back there.

Warning — wasted capacity: Because the weights are stuck at the extreme range, the critic never uses the flexibility that varied weight magnitudes could offer. It stops using the capacity of the system: most intermediate functions the box technically permits become unreachable in practice. The critic that results is a poor approximation of the ideal scorer, and everything downstream inherits that weakness.

The side effect shows up in the metric that matters: your FID score will not be low for vanilla clipped WGAN. The FID score (Fréchet Inception Distance) is a realism measure where lower is better. It passes many real images and many generated images through a pretrained image network, summarizes each set by a mean vector and a covariance matrix of internal features, and scores how far apart those two statistical fingerprints sit. A generator producing rich, varied, realistic samples drives the score down; a capacity-starved critic fails to guide the generator there, so the score stays high.

Exam note: In the assignment you are asked to experiment with different values of in the WGAN implementation to reach reasonably low FID scores. No particular value is prescribed, because handing one out would make the exercise unproductive; the point is to learn hyperparameter tuning firsthand.

Real-world: tuning such knobs is treated as job training. In the workplace you often need not just to choose the right technique but to produce results with it — knowing how to turn the knobs transfers directly to day-to-day work, where the same skill decides whether a model ships or stalls.

Recap + bridge: Weight clamping enforces the Lipschitz promise cheaply, but it starves the critic of usable weights, invites exploding gradients when mis-set, and caps achievable sample quality. Section 12.3 replaces the box with a soft, principled demand on slopes: the gradient penalty.

12.3 WGAN with Gradient Penalty (WGAN-GP)

The gradient penalty replaces weight boxing with a soft, mathematically grounded demand on slopes. Instead of squeezing weights and hoping the slope behaves, you measure the slope directly on meaningful points and push it toward exactly one. It is a significant piece of work, and it is the version you will implement in the assignment.

12.3.1 The Convex Combination Input

Place the two distributions side by side: one cloud is the real training images, the other is the generated images. The penalty lives on the straight line joining a real point to a generated point. Concretely, draw one real sample from the training set, one generated sample , and mix them:

Here is the mixed point, and is a fresh uniform draw between zero and one for each mixed sample — means every value in that interval is equally likely. When you stand on the real image; when you stand on the generated one; in between you stand somewhere on the segment connecting them. Because the two weights and are non-negative and add to one, this mixture is called a convex combination — a weighted average that can never leave the segment.

Worked example — mixing two tiny images. Let a real image be represented by two pixel values and a generated image by . Draw .

The mixed point sits one quarter of the way from the fake toward the real. Sense check: each coordinate lies between the corresponding coordinates of and , exactly as a point on the connecting segment should.

A stressed point about geometry: the figure showing the two clouds and the connecting segment is drawn in two dimensions with coordinates , but real images live in a very high dimensional space — even 32 by 32 images give a 1024-dimensional input. The "straight line" between two samples is a line through that high-dimensional space, not through picture space.

12.3.2 The Gradient Penalty Term and the Full Objective

The penalty asks one thing of the critic: on those mixed points, the gradient magnitude should sit near one. Written out, with a weighting coefficient:

Every symbol: is the gradient of the critic output with respect to its input — how fast the score changes as you nudge the mixed image; is the L2 norm, which turns that gradient vector into a single magnitude; squaring makes the penalty zero exactly when the magnitude equals one and grows smoothly on both sides of that target. Spoken form, rephrased: take the partial derivative of with respect to ; take its absolute value — or L2 norm — the gradient magnitude with respect to the input, where the input is a convex combination of the training data and a generated sample; the penalty value goes down if the average of the gradient magnitude becomes close to one.

Why target slope one? The optimal critic satisfies an optimality property: between corresponding points of the two distributions, its slope equals the density ratio, and enforcing unit gradient norm on the connecting segments drives the critic toward the exact one-Lipschitz optimum. Spoken: if along with a generated image there is a sample point such that for all points along the segment the derivative equals the ratio it should — then the function is one-Lipschitz along precisely the paths where optimality lives. Penalizing deviations from slope one does double duty: it enforces the constraint and steers the critic toward the best possible scorer.

Put together, the critic minimizes the original critic loss plus the penalty:

The first bracket is small when the critic separates real from generated well — high , low . The second bracket vanishes when the average gradient magnitude over all mixed points is about one; otherwise it grows quadratically and pulls back whenever the slope drifts off one. Note the sign flip relative to Section 12.1: here the expression is written as a loss to minimize, so the terms are reversed. The generator then maximizes the critic's score on fakes:

A quick numeric feel for the penalty: if the measured gradient norm on a mixed point is , that point contributes . If the norm collapses to , the contribution jumps to — six times larger, because flat critics are just as bad as steep ones.

12.3.3 Pseudo-code Walkthrough of the Training Loop

You will implement this loop in the assignment, so here is the full sequence with every quantity named.

Worked example — the WGAN-GP training loop trace.

Inputs: generator with weights ; critic with weights ; latent distribution ; real dataset ; penalty weight .

  1. Set : the number of critic updates per generator update. Five is the stated working value.
  2. Sample a real image from , the training set. For the assignment this is CIFAR-10, which holds 60,000 images in total: 50,000 for training and 10,000 for test, so at least 50,000 images serve as real samples.
  3. Draw a latent vector from . The stated choice is a normal Gaussian distribution — an initial "uniform" was corrected mid-sentence to normal.
  4. Compute , the generated image.
  5. Form the mixture .
  6. Evaluate the critic loss on , , and — remember secretly contains , so the generator sits inside the penalty term too. The only piece left aside in the critic step is the pure generator loss.
  7. Update the critic weights with the Adam optimizer. Repeat steps 2 through 7 for all rounds, changing only the critic.
  8. Sample fresh , compute , and run Adam again on the generator loss to improve the generator weights .
  9. Repeat until convergence.

Trace of one outer cycle: five passes improve only while stays frozen; the sixth update improves only while freezes. Over many cycles the critic stays strong enough to grade honestly while the generator slowly catches up. Sense check: count updates — five critic steps per one generator step, matching the stated ratio.

12.3.4 Practical Rules: Batch Normalization and Architecture Freedom

One rule surprises everyone: there is no batch normalization in the critic. Batch normalization rescales each layer's values using statistics computed over the whole mini-batch, but the penalty judges each instance by its own slope within the group — mixing batch-level averages into those judgments corrupts what the penalty measures. People observed empirically that adding it does not work well, so the critic simply omits it. The generator remains free to use batch normalization as usual.

Warning — implementation trap: forgetting to strip batch normalization from the critic is one of the most common reasons an otherwise-correct WGAN-GP implementation underperforms. Check your critic architecture twice before debugging anything else.

Second rule: WGAN-GP is forgiving about architecture. You can vary activation functions, vary the depth of and , and vary the base filter counts — the convolution widths used in generator and discriminator — and training still works. Compare that with the plain DCGAN recipe, where a long prescription applies: strided convolutions, batch normalization in specific spots, none at the end of the generator or the start of the discriminator. Deviate from that recipe and results degrade. The gradient penalty eliminates that brittleness broadly. Vanilla WGAN sits in between: it is fragile, and shuffling components can make it fail outright, because clipping starves the critic of usable capacity.

Dataset context matters when judging results. The showcase samples for this method come from LSUN, a dataset of indoor scene pictures — complex because objects occupy a spatial organization inside a room. CIFAR-10, the assignment dataset, is relatively simple: one object against a background. Expect WGAN-GP to produce solid samples at CIFAR-10 difficulty.

The price is time. The penalty computation itself is long: build the convex combinations, push them through the critic, observe outputs, then differentiate through all of it. Gradient-penalized training takes visibly longer per step than clipped training — accept slower steps as the price of principled constraint enforcement.

Exam note: the assignment expects this exact pseudo-code implemented on CIFAR-10 with WGAN and WGAN-GP, reporting the resulting FID scores side by side.

12.3.5 Reproducibility Concerns

These methods start from random initial points, so run-to-run variation is real, and you should plan for it. The everyday illustration: ask ChatGPT the same prompt with memory turned off, on different days and at different times, and the answers will not be exact replicas of each other. That does not make one answer right and the other wrong; randomness is baked into how such systems learn. For industrial deployments, though, customers expect dependable behavior, so teams add heuristics and engineering controls — fixed random seeds, pinned configurations — to show reproducibility on demand.

12.3.6 Student Questions and Answers

Q: How sensitive are the results to sampling choices, for example the epsilon mixing value?

A: Epsilon runs from zero to one, and different choices give varying results, so expect some spread across runs. Treat the learning rate with the same care — it should not be set casually. Because every run starts from a random point, reproducibility has to be produced deliberately rather than assumed.

Recap + bridge: WGAN-GP replaces the weight box with a squared demand — gradient magnitude near one on lines between real and fake samples — and gains stable training plus freedom of architecture at the cost of extra compute per step. Next question: can we enforce the slope bound directly on the weights themselves instead of penalizing slopes after the fact? Spectral normalization says yes.

12.4 Spectral Normalization GAN (SNGAN)

Clipping was the first mechanism for the Lipschitz demand, and even its inventors said at the time that it was not the right way to achieve it — they lacked a better one. The gradient penalty is principled but slow. Spectral normalization is the third route: constrain the weight matrices themselves, layer by layer, so the critic physically cannot have a steep slope. Instead of punishing violations after they happen, this design prevents them by construction.

Hook: What if you could guarantee a network's slope stays bounded — not by clipping weights, not by measuring gradients, but by dividing each layer's weights by exactly the one number that controls how hard that layer can stretch its inputs?

12.4.1 From the GAN Objective to the Lipschitz Constraint

Start from the original GAN formulation for reference:

Spoken: "for the actual training data, log of D(x)... and for the data coming out of the generator, log of one minus D... you want to maximize with respect to D and minimize with respect to G." Here is the real data distribution, the latent noise distribution, and the generated sample fed to the discriminator .

The WGAN reformulation restricts the scorer to a bounded-slope class:

where is the critic network with weights , and the Lipschitz constant — the steepest possible local slope — must stay at most , a fixed bound. Spoken: "F is the class of functions that implements this critic; this Lipschitz value for that function has got to be less than or equal to K, for a fixed K."

What pins down is the slope definition. For two nearby inputs,

and in the infinitesimal limit the finite difference on the left becomes the derivative: "in the infinitesimal sense, this finite difference, numerator over denominator, can be replaced by the partial derivative." So the whole game is bounding the critic's derivative. Spectral normalization does it matrix by matrix.

12.4.2 Spectral Norm Definition

Recall from the linear-algebra part of the mathematical foundations (MFML) course: the spectral norm of a matrix tracks its largest eigenvalue. The precise statement, guarding against a zero denominator:

Here is a weight matrix, is an input vector to that layer, and is the Euclidean norm (the usual square root of the sum of squared entries). Spoken: "spectral norm of A is given by the dot product of A times h; you take the L2 norm of it and divide by the L2 norm of h, with h not equal to zero... for magnitude of h less than or equal to one." During the lecture the first wording was "sum of eigenvalues", corrected midstream to "not sum — the eigenvalue associated with the largest eigenvalue".

Reconciling "eigenvalue" with the formula. Both statements are right, on different domains. For a square, symmetric matrix, the largest absolute eigenvalue equals the largest singular value, so the spoken description matches the formula exactly — this is the setting where the MFML course met the object. Weight matrices in neural networks are generally rectangular and not symmetric; there, the quantity defined by the max-ratio above is formally called the largest singular value, written , and the eigenvalue language is shorthand. Notation note: texts may write either name for the same formula; what matters operationally is the number it returns — the loudest stretch the matrix can apply to any direction. Sanity check on a concrete case: for , the input maps to a vector of length 3 while , so the ratio hits , which equals both the largest absolute eigenvalue and the largest singular value. No other direction stretches more.

Why does this control slope? Take a linear layer with input vector and weight matrix . Then

The layer's Lipschitz constant equals the spectral norm of its weight matrix — the loudest stretch the layer can apply to any direction. If the activation function's derivative never exceeds one in absolute value, the activation adds no further stretch, and the Lipschitz condition survives it.

12.4.3 Composition Across Layers

Deep networks chain layers, and slopes multiply along the chain. If layer applies weights followed by activation , then the whole network obeys

Spoken: "the Lipschitz value associated with the overall combination of the functions implemented by the layers is going to be less than or equal to the multiplication of the Lipschitz values of the individual pieces." The composition symbol just means: run the stages in order, layer 1 first. Starting from input , each stage maps through into the total inputs of layer 's nodes, then through activation to produce .

So the recipe is mechanical: for every weight matrix in the discriminator, compute its spectral norm, and divide all its weights by that number. After division, every equals one — a matrix divided by its own loudest stretch can stretch nothing louder than one — and the composed network lands at Lipschitz constant one. Normalizing each tames every stage in that chain.

12.4.4 Power Method Computation

Computing a spectral norm sounds heavy — a full eigendecomposition per layer per step would be crushing. How is it done cheaply? By the power method — an iterative scheme that estimates the largest-magnitude stretch direction of a matrix without ever decomposing it.

You initialize a random vector of the appropriate dimension, sampled from an isotropic Gaussian (every direction equally likely), then repeatedly push it through the matrix and renormalize:

Each pass multiplies by the matrix, which amplifies the dominant direction relative to all others; renormalizing keeps lengths at one so nothing overflows. Repeat a few rounds, and the pair converges toward the dominant directions. The scalar estimate falls out as

which is a scalar: one row-vector, one matrix, one column-vector.

Worked example — two rounds of the power method. Take the symmetric matrix , whose true spectral norm is . Start from unit vector .

Round 1. Compute , with norm . So . Next, , with norm , giving .

Estimate: .

Round 2 repeats the same three multiplications and yields . The estimates climb toward the true value 2 — each round shrinks the leftover wrong-direction component by the ratio of the smaller to the larger stretch (here ). Sense check: the estimate must never exceed the true spectral norm, and indeed .

Only two or three power iterations are needed to reach a reasonable degree of precision, which is why the whole scheme earns the label "fast computation". In practice SNGAN even reuses the previous step's direction vector as the starting point, because it barely moved between updates.

12.4.5 Weight Update After Normalization

During training, each critic step uses the spectrally normalized weights in the forward pass and then takes an ordinary gradient step on them:

Here is the normalized weight matrix, is the critic loss, and is the learning-rate step size. Spoken: "the new weights become the old weights minus epsilon times the gradient of the loss function with respect to the normalized weights."

Notation: the spoken sentence says "epsilon" where the written formula uses — both stand for the same thing, the small positive step size (many texts do write for it). The reliable reading of the update is the standard gradient-descent form shown above: subtract the step size times the gradient of the critic loss, taken with respect to the normalized weights. Normalization happens fresh at every forward pass, so any drift the raw update introduces gets corrected immediately.

12.4.6 Hinge Loss in SNGAN

SNGAN changes the loss, not just the constraint. It adopts the hinge loss, the same loss family used in SVMs (support vector machines), and it behaves differently from the log losses of WGAN and WGAN-GP:

Here ranges over real samples, over generated ones, and the target scores are for real and for fake. Walk through the values one state at a time.

Worked example — hinge loss value walkthrough. Evaluate both real-side terms and fake-side terms in three states.

State Score Real-side term Fake-side term
Trained critic, good generator ,
Trained critic, weak generator ,
Untrained critic ,

For critic training you maximize the two hinge terms, and the best possible value of each term is zero. Say the target for a real sample is , or 5 — any value at least one works, because once , the min clamps at zero: no more reward for being extra confident. An untrained system leaves each term near (roughly or territory), so the total loss starts as some negative number pushed through the leading minus signs, and training climbs every score until both terms sit at zero. Push everything to zero: that is the goal. Sense check: no assignment of scores can push either term above zero, so the trained loss floor is exactly zero. The recorded takeaway: "hinge loss is more stable than the log loss function".

12.4.7 Comparing the Four Designs

Line the designs up in order.

Design Distribution measure Slope enforcement Loss Known weakness
Plain GAN Jensen-Shannon divergence none log loss instability, mode collapse
WGAN Wasserstein distance weight clipping into critic gap weights pile at box edges, capacity wasted
WGAN-GP Wasserstein distance gradient penalty on mixed points critic gap slow per-step computation
SNGAN Wasserstein-style gap divide each weight matrix by its spectral norm hinge loss needs power-method estimate each step

A plain GAN pays for its simple loss with instability and mode collapse. WGAN switches to the Wasserstein distance, gains stable training, curbs mode collapse, and improves FID scores — but its weight clipping piles weights at the box edges and wastes critic capacity, so results stay mediocre. WGAN-GP fixes the constraint properly: compute gradient magnitudes on convex combinations of training and generated data, and penalize any deviation of that magnitude from one. This produces significantly better results at the cost of computational complexity. SNGAN prevents the violation instead of penalizing it: divide each weight matrix in the critic by its spectral norm, estimated by the fast power method, gaining a computational benefit over WGAN-GP — and it swaps the loss to the hinge form. When to pick which: if you can afford compute, WGAN-GP; if per-step speed matters, SNGAN.

12.4.8 Student Questions and Answers

Q: How expensive is it to calculate the spectral norm?

A: It reduces to the largest-eigenvalue calculation of a matrix. It is an iterative method, the power method, and only two or three power iterations are enough to reach a reasonable degree of precision. So the per-step overhead is small, and the computation counts as fast.

Q: Was the spectral norm covered in earlier coursework?

A: Yes — it appears in the mathematical foundations (MFML) course in the first semester, and the class confirmed recalling it there. The same power method connection was revived: largest eigenvalue, iterative estimation, a handful of iterations.

Recap + bridge: Spectral normalization enforces the Lipschitz promise at the source — every weight matrix is divided by its loudest stretch, estimated cheaply by the power method — and pairs it with a hinge loss whose optimum sits at a clean zero. All four designs so far still generate whatever the noise vector feels like. Section 12.5 asks whether every pixel should really have to look only at its immediate neighbors, and answers with self-attention.

12.5 Self-Attention GAN (SAGAN)

Convolution windows see only local neighborhoods. SAGAN bolts an attention mechanism onto the GAN stack so every output position can consult every other position, weighted by relevance.

Hook: A convolution kernel looking at a 3 by 3 patch cannot know that the sky it is coloring must match the sky three hundred pixels away. What if each position could directly ask every other position "how relevant are you to me?" and borrow exactly what it needs?

12.5.1 Attention Over Feature Maps

Attention first appeared in deep networks for sequences: the prediction gets influenced by the past context, and the context that matters more receives more weight. SAGAN imports the same idea into images. The feature maps flowing out of each convolutional layer — in both the generator and the discriminator — become the raw material for attention maps. Visualizing those maps shows bright spots where the model attends strongly and dim regions it mostly ignores.

Intuition: Picture a painter filling in a wall-sized fresco one tile at a time. A conv layer works like painting each tile while glancing only at the tiles touching it. Attention is like letting the painter look up at any tile already painted anywhere on the wall, judge which ones matter for the tile in hand, and copy shading from them in proportion to relevance. The analogy breaks where images differ from walls: image "positions" are feature vectors in a learned space, not literal tiles, so "relevance" is computed from content, not from physical adjacency.

Because the model can pull information from relevant distant locations instead of just the immediate window, results often come out much better: proper weight goes to the information sitting in the wider neighborhood. Long-range coherence — matched sky colors, consistent object parts, aligned textures — improves visibly.

12.5.2 Query, Key, Value Computation

The engine is the query-key-value trio. From the layer's features, learned projections produce a query , a key , and a value :

Spoken: "you use the QKT concept — Q is the query, K is the key, V is the value — and you implement that with softmax. Out of softmax we get different weights that you multiply element by element with the feature vector to create the self-attention feature maps."

Shapes make this precise. Suppose a feature map has spatial positions (for a height-by-width grid, counts all cells) and each position carries a feature vector. Learned matrices project each position into three roles: a query vector ("what am I looking for"), a key vector ("what do I offer"), and a value vector ("what I pass along if chosen"). The product builds an table whose entry scores how much position should listen to position . The softmax turns each row of that table into positive weights adding to one — a relevance budget per position. Multiplying by gathers the attended values into the output : each output position becomes a relevance-weighted blend of value vectors from everywhere in the image.

Worked example — one attention row by hand. Let an image have just three positions , and suppose the score row for position comes out as — high affinity to itself, medium to , low to .

Softmax: exponentiate each score — , , — then normalize by their sum, :

Let the value vectors be , , . Then

Position A's new feature is mostly its own value, tinted slightly by B and barely by C. Sense check: the three weights add to one, so the output stays inside the convex hull of the value vectors.

12.5.3 Residual Output with Gamma

The attention output merges back through a residual gate:

Here is the layer's input, is the attention output, and is a learned scale — a single number trained by gradient descent, initialized at zero. Spoken: "your output becomes nothing but the input to the layer plus gamma times the O." Starting at , training begins with attention nearly switched off — the network behaves like a plain convolutional stack — and grows only as the task rewards long-range mixing. This keeps early training stable while leaving the door open for global context. The result: the output of a convolution layer now also carries information about the broader context, not just the local patch.

12.5.4 Where SAGAN Fits

Everything else stays on the same rails as before: spectral normalization applied to both generator and discriminator weights, hinge-form losses, and self-attention modules inside both networks. The headline claim: SAGAN was the first variant of the GAN to produce good unconditional full-image samples at ImageNet scale. ImageNet is the standard large-scale image corpus — many million labeled pictures, with the widely used classification benchmark built on 1000 everyday classes (the lecture's slides quoted a smaller class figure; the canonical benchmark count is 1000). "Unconditional" means generation is not steered toward any particular class: the model draws random images that look like members of the image population. Against CIFAR-10 — a far smaller dataset with very few classes — the jump matters less, but for creating data similar to ImageNet yet distinct from it, SAGAN beat every earlier variant discussed. Reported FID scores differ noticeably across SAGAN versions, which is why benchmark tables list several.

Real-world: long-range consistency is exactly what product pipelines need when synthesizing scenes — furniture catalogs generate whole rooms where floor lighting must agree across the frame, and game studios build texture generators whose distant patches must not clash. Self-attention modules from this line later became standard equipment in the vision backbones behind such systems.

Recap + bridge: SAGAN adds query-key-value attention on top of convolution so any position can gather information from any other, gated gently through a learned . Attention fixes where information comes from; it does nothing about how big the generated image can be. For giant resolutions, the next section grows the network itself.

12.6 Progressive Growing GAN

How do you synthesize a 1024 by 1024 image when your generator starts from a tiny random vector? Do not train the whole monster at once. Grow it.

Hook: Nobody learns to write by starting with a full-page essay. You learn letters, then words, then sentences. Progressive growing applies the same ladder to GANs — and it turned out to work much better and faster than one-shot training.

12.6.1 Building a Resolution Pyramid

Suppose the target is large images, say 512 or 1024 by 1024. From the training set of full-resolution images, manufacture smaller copies: 512 by 512, 256 by 256, and so on, down to an extreme case of 4 by 4. Simple subsampling does it — mean pooling with stride equal to 2 progressively shrinks the images, halving each side per stage. You end up with a pyramid of the same content at every resolution: nine levels connect 1024 down to 4 (1024 → 512 → 256 → 128 → 64 → 32 → 16 → 8 → 4), each step cutting both width and height in half.

Worked example — one mean-pooling step. Take a 4 by 4 image and shrink it to 2 by 2 with stride-2, window-size-2 mean pooling. The input grid:

Each non-overlapping 2 by 2 window becomes its average. Top-left window : mean . Top-right : . Bottom-left : . Bottom-right : . Output:

Each output pixel summarizes exactly one quadrant — the content survived, the resolution dropped. Sense check: four windows consumed sixteen pixels, so the side length halved.

12.6.2 Growing the Networks Step by Step

First train a small game — a compact generator-discriminator pair — that works well on the 4 by 4 versions of the images. Then extend: add layers to the generator and discriminator so the next pair handles 8 by 8, train it, continue through 16 by 16, and onward until the full 1024 by 1024 pair stands. The generator pathway starts from a small random latent vector — about 128 values spoken of as the input size; the key point is that this input is a flat, low-dimensional vector, not an array of pixels — and expands through feature maps of 4 by 4 with 1024 filters, then 8 by 8 with 512 filters, doubling resolution while halving filter counts as it climbs. So the earliest layer already works on tiny spatial grids but with many channels, and each growth stage trades channel count for spatial detail.

One refinement made this ladder stable in practice: new layers fade in gradually. When a higher-resolution stage is added, its output initially blends with a simple upscaled copy of the previous stage's result through a residual connection, and the new layers take over only as their influence ramps up. The network never experiences a harsh architectural jump.

Visual intuition: imagine two staircases rising together, one for the generator (small blurry grid growing into a sharp large image) and one for the discriminator (large sharp input shrinking back to a single real-or-fake verdict). Each staircase step on the left must match a step on the right, or the game falls out of balance.

The payoff is simple: this process works much better and faster than trying to train a one-shot generator that jumps straight from a small latent vector to a 1024 by 1024 image. Training progresses 4 by 4, then 8 by 8, then 16 by 16, finally 1024 by 1024 — a genuinely powerful technique that delivers good results quickly. Early resolutions teach global layout cheaply; late resolutions spend capacity only on fine detail.

Real-world: progressive growing is what first made photorealistic human-face generation practical — the face images produced by this family are famous enough that synthetic faces built this way have been used as stock avatars and privacy-preserving profile photos.

Recap + bridge: Build a pyramid of downsampled training images, grow the generator-discriminator pair level by level with gentle fade-ins, and full-resolution synthesis becomes tractable. Everything so far generates whatever the noise draws. Section 12.7 hands over the steering wheel: pick a class, get that class.

12.7 Conditional GAN (CGAN)

Random generation is fun; directed generation is useful. The conditional GAN adds a steering wheel: generate images belonging to one particular class of the training data.

Hook: An unconditional generator is a vending machine with one button — press it and something random drops out. What if you want the machine to dispense a cat when you ask for a cat? The answer is to feed your request into both the maker and the judge.

12.7.1 Conditioning on Class Labels

Take CIFAR-10 as the running example: 50,000 training images spread across 10 classes — airplane, automobile, bird, cat, deer, dog, frog, horse, ship, truck. That class information is gold at generation time — feed it to the generator so it creates samples from the requested class.

Mechanically, the class label travels with the noise: alongside the latent vector , the model receives the label, encoded as a vector. Labels like cat or dog are symbolic words, and networks compute on numbers, so they need an embedding — a numeric vector standing in for the category. The simplest embedding is one-hot encoding: with 10 classes, each label becomes a 10-slot vector holding zeros everywhere except a single 1 at its own slot. Concatenate that one-hot label onto , or otherwise fuse the two, and hand the pair to the generator.

The discriminator gets the label treatment too: it sees the label along with whatever image it judges, real or generated. Its job becomes sharper — "is this a real horse?" rather than "is this real?" In implementation terms, the label can be appended to the input for flat data, or reshaped into a map of values and added as an extra channel alongside the image channels for convolutional judges. So the whole pipeline restricts itself class by class — the class acts as the condition inside the generator itself. Training then updates both models: the discriminator learns real-versus-fake classification per label, and the updates improve the convolutional filter weights in both the generator and the discriminator.

12.7.2 Conditional Loss Functions

With samples in a mini-batch, a real image, its class label, a latent vector, and the conditioning label fed to the generator, the real-sample loss for the discriminator is

Spoken, rephrased: average minus the log of the judge's score on true images paired with their true labels — the minus sign flips the small negative logarithm into a positive loss, so minimizing pushes scores toward one. The fake-sample loss passes the label through the generator and the judge:

The notation reads "the sample generated from noise given condition " — the vertical bar marks which information steers generation.

Worked example — conditional losses on a tiny batch. Let the requested class be cat (slot 3 in the CIFAR-10 order), so its embedding is

Take a mini-batch of two real images with judge scores and :

Now two generated samples judged while claiming the cat label: scores and (unconvincing fakes):

Total discriminator loss: . The generator's loss is just the fake part, . Sense check: if the judge were perfect (real scored 1, fake scored 0), both losses would fall to zero.

Trace the arithmetic logic once more in words: on a convincing fake, outputs a value near zero — not near one — so sits close to one, its logarithm sits close to zero, and the leading minus leaves only a small number to add. Minimizing teaches to produce images that both look real and carry the demanded label; the label inside the loss is what makes the demand stick.

Real-world: class-conditioned generation powers data augmentation for rare categories — self-driving simulators request exactly "truck in fog" style samples to balance training sets, and designers use conditioned generators to draft variations of one product category without touching others.

Recap + bridge: The conditional GAN wires a class embedding into both players, so the adversarial game runs per label and the generator obeys requests. But the condition so far is just a word from a fixed list. Section 12.8 conditions on something far richer — an entire image.

12.8 Pix2Pix GAN

Every GAN so far started from noise. Pix2Pix starts from an image and produces a different rendering of it — the flagship of the conditional family.

Hook: What if the "condition" were not a one-word label but an entire picture — hand the network a sketch, receive the finished product; hand it a grayscale photo, receive color?

12.8.1 Image-to-Image Translation

The input to Pix2Pix is not a random vector. It is a version of an image, and the goal is to change the type of that image — this task shape is called image-to-image translation. Canonical cases: a grayscale photograph becomes a realistic color photograph; the outline of a sneaker shoe becomes the actual rendered sneaker; a silhouette fills in the object and background. Outline images have a more technical name: edge images. The mapping idea extends beyond pictures — feeding an English sentence and receiving the German counterpart fits the same shape, source in, closely related target out. That sentence view is exactly how neural machine translation works, which is why the two tasks share a name.

The generator takes an image and creates another image out of it; the discriminator tries to expose the synthesized one as fake, exactly as in a standard GAN. It counts as a conditional GAN because the input image plays the role the class label played before — the condition the generator is conditioned on.

12.8.2 Pair-Based Discrimination

Training leans on pairs. The discriminator receives two images together: the generated image and its corresponding training counterpart. Its verdict applies to the pair as a whole — a real pair earns a high value, a fabricated pair earns a low value. Picture the training bank: real images of cold-drink bottles, cats, dogs, and so on, each stored alongside its alternate version, black-and-white or edge-rendered, aligned pixel by pixel. The generator learns to render a realistic version of whatever input it receives, where "realistic" means matching the reality captured by the training pairs.

The strict pairing rule: even if the generator colors a bottle so well that the result resembles training bottles, the pair still counts fake — the genuine article is the specific paired color image for that exact outline. A beautiful rendering of the wrong content loses. Mismatches lose; only the true partner wins.

This strictness is what makes paired data both powerful and expensive to collect: every training outline must come with its own photographed twin.

12.8.3 Adversarial Loss Plus L1 Reconstruction

The adversarial piece scores pairs, with the input image, the true partner from training data, and the generated candidate:

Maximize it over , minimize over — the same two-sided game as before, except the logs now score pairs rather than single images. On a fake pair, outputs a small number, so grows toward one and the second logarithm turns large-negative, punishing the generator through minimization; on a genuine pair the first logarithm rewards the discriminator for recognizing the true match.

Adversarial pressure alone leaves room for drift: the output could be realistic-looking yet structurally off from the input — a plausible bottle standing at a different angle. So a reconstruction term joins the objective:

Here denotes the best generator found by solving the two-sided problem, and balances realism against faithfulness. The L1 norm — the sum of absolute pixel differences — pulls toward pixel by pixel.

Worked example — computing the L1 reconstruction term. Let the true output be and the generated candidate . Then

For comparison, the squared-error route gives . L1 charges linearly per missed pixel, so one badly wrong pixel hurts more than many slightly-off ones — which keeps outputs sharp instead of blurry. Spoken rationale for including the term: minimizing this value "ensures that given a drink-bottle image you create a drink-bottle image, not a drink-bottle image oriented differently or anything like that". Sense check: identical images give zero distance, and any deviation adds positive cost. Swapping L1 for L2-based regularization handles certain structured-prediction tasks — another documented operating mode.

12.8.4 The Patch Discriminator

Whole-image judgment is wasteful and coarse. The Pix2Pix discriminator instead breaks both images into smaller pieces and compares patch against patch — this piece of the generated image against the aligned piece of the true one, and so on across all overlapping windows — penalizing each patch in the output that looks fake. This is the PatchGAN design, often just called a patch-wise discriminator.

Worked example — choosing the patch size. The ladder climbs like this:

Patch size Judgment scope Observed outcome
1 by 1 single pixel blurry, unsatisfying outputs
16 by 16 small neighborhood visibly improved structure
70 by 70 larger neighborhood best of the shown sizes, common default

A 1 by 1 judge can only ask "does this pixel look plausible alone?" — after training, outputs look poor, because structure lives in groups of pixels, not single ones. At 16 by 16 patches, structures spanning several pixels finally get judged as wholes, and outputs improve visibly. At 70 by 70 the results look better still, which is why many versions of Pix2Pix ship with a 70 by 70 patch discriminator. There is also a computational dividend: a patch judge is a stack of small convolutional layers whose receptive field covers just 70 by 70 pixels, so it carries far fewer parameters than a judge that must digest entire 1024 by 1024 images at once — think thousands of weights per layer instead of millions of connections. Sense check: smaller judgment scope, smaller network, more of them applied — that trade is exactly why the patch design scales.

12.8.5 Results and Failure Modes

The gallery of successes: outlines turning into realistic color images, food and dessert photographs synthesized from sketches, a crisp button-slide image colored convincingly, sneakers rendered from their edges. Then the cautionary exhibits.

Failure mode: occasionally the generator emits something strange — an output whose shapes suggest a cat, complete with eye-like circles, born from an input that was no cat at all. Such artifacts can slip past the discriminator untouched. A passing discriminator grade is not a guarantee of semantic correctness; human inspection remains part of the quality loop.

Real-world: the English-to-German framing above is the same shape as neural machine translation, and sketch-to-product rendering — the sneaker case — is a direct e-commerce workflow where shoppers or designers draft products by drawing outlines.

Recap + bridge: Pix2Pix conditions on an input image, judges pairs strictly, anchors structure with an L1 term, and checks realism locally through patches. Its appetite for pixel-aligned pairs is also its weakness — Section 12.10 removes that requirement entirely. First, a quick stop at a sibling that predicts labels instead of translating images.

12.9 Auxiliary Classifier GAN (ACGAN)

ACGAN sits in the conditional family alongside Pix2Pix-style conditioning, with one twist: the discriminator wears two hats.

12.9.1 Class-Conditioned Real-Fake Scores

Beyond declaring an image real or fake, the ACGAN judge also predicts the class label. One network, two output jobs:

The two-headed discriminator. The generator receives a class label together with the latent vector and must draw that class. The discriminator then takes each image and produces two kinds of answers at once: a real-versus-fake score, and a full probability distribution over the classes. For a discrete attribute with categories this means outputs — one passed through a sigmoid for the real/fake verdict, and the rest passed through a softmax so they read as class probabilities summing to one.

Its discriminative loss distinguishes between real and fake examples conditioned on their respective class labels — a real-sample loss and a fake-sample loss, each computed with the label attached, combine into the training signal. The classification branch adds its own demand: when the judge guesses the wrong class for an image it believes is real, it pays, and that pressure travels back into the generator as "make samples not just realistic but recognizable". On the generation side the goal stays the familiar conditional one from Section 12.7: produce images that belong to a requested particular class.

Compared with plain CGAN, the division of labor differs. CGAN shows the label to the judge as extra input information; ACGAN makes the judge recover the label from pixels alone, which sharpens class separation inside the learned features. Know the architecture split — generation branch plus classification branch inside the judge — and the label-conditioned loss structure, and you have this variant's essence.

Recap + bridge: ACGAN folds a classifier into the GAN judge so every sample is graded on realism and class identity together. Next, the conditional family's boldest member removes the need for paired training data altogether.

12.10 CycleGAN

Pix2Pix has an appetite that is hard to feed: paired data. CycleGAN drops that requirement and learns mappings between two image collections that share a concept but have no point-to-point alignment.

Hook: Nobody owns a photograph of Monet standing at his easel painting any specific modern photo — yet people can look at thousands of photos and thousands of paintings and learn to translate between the styles. Can a network do the same without ever seeing a single matched pair?

12.10.1 Learning from Unpaired Sets

Paired training, as Pix2Pix needs it, means for every outline boot a matching photo of that same boot, dress shoes with dress shoes, sneakers with sneakers — correspondence pixel by pixel, same background included. Such pairs are difficult to acquire. CycleGAN accepts two unrelated piles: lots of photos, lots of paintings, nothing aligned — an unpaired setup.

The classroom moment that planted the idea went like this:

Q: Looking at these two collections of images, what is common within each set, and what differs between the sets?

A: One side looks like original photographic images; the other side looks like an animated image, a painting or drawing. The confirmed framing: domain X reads as a real captured image while domain Y reads as a painting.

That observation is the entire task specification: learn the transformation that takes an original photo and renders it as a painting — the examples shown belonged to the oil-painting class, in the style of Monet — or runs the other way, taking something that looks like a painted canvas and making it look like a mobile-phone capture. Feed a Van Gogh-style image and receive a Monet-style image out. The correspondence is abstract: the model captures the concept of painting versus realism, not a pixel map. No teacher ever says which painted stroke matches which photo pixel; the shared idea of "style" is all that links the piles.

The horse-and-zebra demo makes it concrete: train on lots of arbitrary horse images and lots of arbitrary zebra images — multiple zebras welcome, no shared backgrounds — and the trained system paints zebra stripes onto a given horse, producing a zebra image that exists nowhere in training. Other mappings shown: satellite imagery to street maps, cloudy-day images to bright-day images and back. Results are not perfect — stripe placement occasionally wanders onto sky or grass — but as contextual texture transfer it is striking.

12.10.2 Two Generators, Two Discriminators

One generator cannot police itself, so CycleGAN deploys two generators and two discriminators. Generator maps domain X to domain Y — horse to zebra. Generator maps Y back to X — zebra to horse. Discriminator judges whether an image presented as Y looks like a genuine member of the zebra pile; discriminator does the symmetric duty for horses, separating from real samples . Each half is a complete adversarial game on its own; the magic lies in forcing the two halves to close a loop.

12.10.3 Forward and Backward Cycle Consistency Loss

Here is the loop. Take a horse , apply , get ; apply to , and you should land back near . Symbolically . Run it backward too: . The cycle consistency loss measures both round trips:

Here is the collection of real images (horses) and the collection of target-style images (zebras); each expectation averages over its whole collection. The L1 norm is the stated preference over squared error, because it resists noise better — outlier pixels drag an L1 penalty less than they drag a squared penalty.

Worked example — one forward cycle, measured. Track two pixels through the round trip. A horse patch arrives as . The stripe painter outputs . Painting back gives .

A small round-trip cost — content survived, only style flipped twice. Now imagine instead that decoded into a completely different horse pose, say : the cost would jump to , and training would punish exactly that. Sense check: identical round trips cost zero, so the loss floor sits at zero when both generators are perfect inverses.

Without this loss the system would happily learn a mapping and an inverse that agree on nothing: could shuffle every horse into an arbitrary encoding that decodes however it likes, and both discriminators would still be satisfied. Round-trip agreement is what forces the learned transformation to preserve content while changing style.

12.10.4 Adversarial Terms and the Full Objective

Each direction also carries a standard adversarial push, written here in least-squares form as presented:

Driving 's score on the generated zebra toward one is exactly what drives this term toward zero — proof that a real-looking zebra was manufactured.

The canonical pieces of the objective. Two clarifications complete the picture. First, the full adversarial term for each direction contains two halves: the generated half shown above, plus a real-data half , which rewards the judge for scoring genuine zebras near one — the judge trains on both halves while each generator attacks only the generated half. Second, the framework includes an optional identity loss: pass an image from domain Y straight through generator (whose job is X-to-Y) and it should come back unchanged, , symmetrically for . Weighted by its own coefficient and added to the objective, this check anchors color composition — a mapping asked to turn photos into paintings should leave actual paintings untouched rather than repaint them. It stabilizes training and preserves input colors wherever style transfer is not needed.

Assemble everything, optimizing over generators and judges :

One generator-judge pair fights over the X-to-Y direction, the other over Y-to-X, and both round-trip penalties tie the knot. Applications extend past animals and art: camera photos to oil paintings, satellite views to maps, weather shifts between cloudy and bright — anywhere two visual domains relate by style or sensor rather than by alignment. Film studios use the same recipe for era conversion of archival footage, and autonomous-driving teams convert sunny recorded drives into rainy ones to widen test coverage without new data collection.

Recap + bridge: CycleGAN learns both directions between two domains with four networks, then locks content in place by demanding that every round trip return home. With that, the conditional family is complete — from class labels through paired translation to unpaired style transfer. The closing sections collect exam guidance and industry applications.

Exam Guidance Summary

  • Past question papers for the regular exam are being released; use them for practice.
  • Expect comprehensive-exam questions drawn directly from the assignments, both the current one and the earlier one — doing the group work diligently is exam preparation, and this deliberately raises the weight on experiential learning. Treat every assignment run you complete as one fewer surprise on exam day.
  • The assignment spans implementing VAEs at different beta values (an ordinary VAE is the special case beta equals one), VQ-VAE at different codebook sizes, and WGAN versus WGAN-GP — understand the pros and cons of each from running them, not just from reading about them.
  • Marks are reserved for achieving expected evaluation quality: know the typical FID and PSNR ranges these techniques reach on CIFAR-10-like data, and treat falling-short metrics as a signal to retune architectures rather than to accept. Code-generation tools can write code, but they will not hand you results commensurate with the techniques — the results come from tuning and debugging.
  • Experiment with the weight clipping parameter in the WGAN part to reach reasonably low FID scores; no value is prescribed on purpose, because hyperparameter search is itself the skill being trained.
  • Implement the WGAN-GP training loop exactly as specified: five critic iterations per generator update, Adam optimizer, normal Gaussian latents, and no batch normalization in the critic.
  • Pretrained models and transfer learning are permitted in the assignment — smart reuse is a practical technique, especially where teams do not build such products from scratch. FID computation uses pretrained Keras InceptionV3 weights, so learn how that scoring pipeline is wired.
  • Know the power-method route to spectral norms, the hinge-loss value walkthrough, and the paired-versus-unpaired distinction between Pix2Pix and CycleGAN — these three items compress most of this lecture's testable detail into a short revision list.

Key Industry Applications

  • Hyperparameter fluency: choosing a technique is table stakes; producing results with it — by tuning knobs like the clip constant or patch size — mirrors day-to-day industry expectations, where the deliverable is a working metric, not a working sketch.
  • Reproducibility engineering: generative systems are stochastic, so industrial deployments wrap them in fixed seeds, pinned configurations, and evaluation harnesses to show dependable behavior on demand — the same reason chat assistants give slightly different answers to identical prompts.
  • Pretrained-model economics: organizations that do not specialize in building such products routinely start from pretrained networks and adapt them with limited proprietary data via transfer-learning principles, trading training cost for fine-tuning effort.
  • Synthetic data creation: SAGAN-class models generate full-image samples resembling a large curated corpus while remaining distinct from it — useful wherever new training data is needed but collection is costly or privacy-sensitive.
  • Vision-to-vision workflows: grayscale colorization, sketch-to-product rendering, satellite-to-map generation, and photo-to-painting styling all follow the Pix2Pix or CycleGAN recipes covered here; e-commerce catalogs and media studios run production variants of exactly these pipelines.
  • Evaluation practice: FID scoring with InceptionV3 embeddings is the standard yardstick for comparing GAN variants in production experiments, which is why fluency in reading (and distrusting) FID tables transfers across teams.

UDL Lecture 12 notes · Variants of Generative Adversarial Networks

Unsupervised Deep Learning· postgraduate· 2026-08-25

Sections Breakdown

1WGAN Refresher: Wasserstein Distance and the Critic

The Wasserstein distance measures the cheapest way to transport one distribution into another; linear-programming duality replaces that costly plan search with a bounded-slope scoring function called the critic, giving the stable WGAN objective.

2Weight Clipping in Standard WGAN

Standard WGAN enforces the one-Lipschitz constraint by clamping every critic weight into [-c, c] after each update; small c values control gradients, but weights pile up at the box walls, wasting critic capacity and keeping FID scores high.

3WGAN with Gradient Penalty (WGAN-GP)

WGAN-GP penalizes the squared deviation of the critic's input-gradient L2 norm from one, evaluated on convex combinations of real and generated samples; training uses five critic updates per generator update with Adam and no batch normalization in the critic.

4Spectral Normalization GAN (SNGAN)

SNGAN enforces the Lipschitz constraint by dividing every critic weight matrix by its spectral norm (largest singular value, equal to the largest absolute eigenvalue for symmetric matrices), estimated cheaply with two or three power-method iterations; the loss switches to the hinge form whose trained optimum is exactly zero.

5Self-Attention GAN (SAGAN)

SAGAN adds query-key-value self-attention to generator and discriminator feature maps so every position can gather relevance-weighted information from every other position, merged through y = x + gamma*o with a learned gate initialized at zero.

6Progressive Growing GAN

Progressive growing trains a tiny 4x4 generator-discriminator pair first, then adds layers to climb a resolution pyramid (8x8 up to 1024x1024), with new layers fading in through residual connections; this beats one-shot full-resolution training in both speed and quality.

7Conditional GAN (CGAN)

The conditional GAN feeds a class-label embedding (simplest form: one-hot) into both generator and discriminator, so generation is steered per class; the discriminator loss scores real and fake samples with labels attached.

8Pix2Pix GAN

Pix2Pix performs image-to-image translation with paired data: a generator maps an input image to a new rendering, a pair-based discriminator scores (input, output) couples strictly, an L1 reconstruction term anchors structure, and a PatchGAN judge checks realism patch by patch.

9Auxiliary Classifier GAN (ACGAN)

ACGAN's discriminator wears two hats: it scores real versus fake and simultaneously predicts the class label (C+1 outputs: sigmoid verdict plus softmax over C classes), sharpening class separation while the generator produces label-requested images.

10CycleGAN

CycleGAN learns translations between two unpaired image collections using two generators (G: X to Y, F: Y to X) and two discriminators, tied together by a forward-and-backward L1 cycle consistency loss so content survives while style changes; an optional identity loss preserves already-valid samples.

11Exam Guidance Summary

Carried-through appendix collecting exam logistics and assignment expectations: past papers, comprehensive-exam questions from both assignments, VAE/VQ-VAE/WGAN-WGAN-GP coverage, expected FID/PSNR ranges, the WGAN-GP loop spec, transfer-learning permission with Keras InceptionV3 scoring, and the SNGAN/Pix2Pix/CycleGAN revision list.

12Key Industry Applications

Carried-through appendix mapping lecture techniques to industry practice: hyperparameter fluency, reproducibility engineering, pretrained-model economics, synthetic data creation, vision-to-vision workflows, and FID-based evaluation practice.

Postgraduate students studying generative models

Exam Revision Notes

Below is the distilled, exam-ready core. Every entry comes from the full explanation above. Use this section for rapid review; return to the main notes when a point needs more context.

WGAN Refresher: Wasserstein Distance and the Critic

Must-know: The WGAN objective maximizes E_real[D(x)] - E_fake[D(x)] over one-Lipschitz critics; the critic output is an unbounded score, not a probability.

⚠️ Top pitfall: Treating the critic score as a probability in [0,1] or dropping the Lipschitz restriction (which makes the maximization unbounded).

Self-check: Why does the Wasserstein measure give useful gradients when the real and generated distributions do not overlap?

Connects to: §12.2 weight clipping, §12.3 WGAN-GP, §12.4 SNGAN

Weight Clipping in Standard WGAN

Must-know: Weight clipping bounds the critic's slope by clamping all weights into [-c, c]; small c avoids exploding gradients, but weights pile at +/-c so critic capacity goes unused and FID stays mediocre.

⚠️ Top pitfall: Setting c too large (exploding gradients) or expecting low FID from vanilla clipped WGAN despite its wasted capacity.

Self-check: What does the histogram of trained clipped-WGAN weights look like, and why?

Connects to: §12.1 WGAN refresher, §12.3 WGAN-GP

WGAN with Gradient Penalty (WGAN-GP)

Must-know: The WGAN-GP critic loss adds lambda times E[(||grad D||_2 - 1)^2] on mixed points x-hat = eps*x + (1-eps)*x-tilde; loop: 5 critic steps per generator step, Adam optimizer, normal Gaussian latents, no batch normalization in the critic.

⚠️ Top pitfall: Leaving batch normalization inside the critic, or forgetting that x-hat contains G(z) so the penalty also backpropagates into the generator.

Self-check: What does the gradient penalty evaluate, on which points, and what value should it approach?

Connects to: §12.1 WGAN refresher, §12.2 weight clipping, §12.4 SNGAN

Spectral Normalization GAN (SNGAN)

Must-know: Spectral norm sigma(A) = max over nonzero h of ||Ah||_2/||h||_2 equals the largest singular value (largest absolute eigenvalue for symmetric matrices); Lip(linear layer) = sigma(W); network bound = product of per-layer constants; power method needs only 2-3 iterations.

⚠️ Top pitfall: Confusing the spectral norm with the sum of eigenvalues (it is the largest one), or forgetting SNGAN also swaps the loss to hinge form with targets +1 real / -1 fake.

Self-check: Evaluate min(0, D(x)-1) for a trained critic with D(x)=3 and explain why extra confidence earns nothing.

Connects to: §12.1 WGAN refresher, §12.2 weight clipping, §12.3 WGAN-GP, §12.5 SAGAN

Self-Attention GAN (SAGAN)

Must-know: Attention output o = softmax(QK^T)V with an N x N relevance table row-normalized by softmax, merged residually as y = x + gamma*o where gamma is learned and starts at zero.

⚠️ Top pitfall: Forgetting softmax rows must sum to one per querying position, or expecting attention to help from step one (gamma starts at zero).

Self-check: Why does SAGAN initialize gamma at zero instead of one?

Connects to: §12.4 SNGAN, §12.6 progressive growing

Progressive Growing GAN

Must-know: Build the pyramid by mean pooling with stride 2 (each side halves per stage); grow G and D together level by level; new layers fade in gradually; generator starts from a flat low-dimensional latent vector (~128 values) expanding to 4x4x1024 feature maps.

⚠️ Top pitfall: Reading '128 by 128 random vector' as an image-sized input — it is a flat ~128-dimensional latent vector.

Self-check: How many resolution levels connect 1024x1024 down to 4x4, and what pooling operation builds them?

Connects to: §12.5 SAGAN, §12.7 CGAN

Conditional GAN (CGAN)

Must-know: CGAN passes the label to BOTH players: one-hot (or learned embedding) fused with z for the generator, label shown alongside the image for the judge; losses are the standard log forms evaluated on (image, label) pairs.

⚠️ Top pitfall: Feeding the label only to the generator — without the label at the judge, nothing forces generated content to match the requested class.

Self-check: Compute L_D^real for a batch of two with judge scores 0.9 and 0.8.

Connects to: §12.6 progressive growing, §12.8 Pix2Pix, §12.9 ACGAN

Pix2Pix GAN

Must-know: Objective G* = argmin_G max_D L_cGAN(G,D) + lambda*E[||y - G(x)||_1]; discriminator verdicts apply to PAIRS; PatchGAN sizes 1x1 (poor) < 16x16 < 70x70 (common default); strict pairing means even good-but-unmatched outputs count fake.

⚠️ Top pitfall: Assuming a passing discriminator guarantees semantic correctness — cat-like artifacts can slip through untouched.

Self-check: Compute the L1 distance between y = (0.9, 0.4) and G(x) = (0.7, 0.5).

Connects to: §12.7 CGAN, §12.10 CycleGAN

Auxiliary Classifier GAN (ACGAN)

Must-know: ACGAN judge outputs C+1 values: one sigmoid real/fake score plus a softmax over C classes; unlike CGAN, the judge must recover the label from pixels instead of receiving it as input.

⚠️ Top pitfall: Mixing up CGAN (judge sees the label as input) with ACGAN (judge predicts the label from the image).

Self-check: How many output heads does an ACGAN discriminator need for 10 classes, and what activation does each use?

Connects to: §12.7 CGAN, §12.10 CycleGAN

CycleGAN

Must-know: CycleGAN = two generators + two judges + cycle consistency loss E||F(G(x))-x||_1 + E||G(F(y))-y||_1; full objective min over G,F max over D_X,D_Y of both adversarial terms plus lambda*cyc; optional identity loss keeps valid target-domain images unchanged.

⚠️ Top pitfall: Forgetting the cycle loss is what prevents G and F from colluding on an arbitrary code — without it both adversarial games can be won while translations become meaningless.

Self-check: What breaks in CycleGAN training if you delete the cycle consistency term?

Connects to: §12.8 Pix2Pix, §12.9 ACGAN

Exam Guidance Summary

Must-know: Comprehensive-exam questions come directly from the assignments: VAE beta values, VQ-VAE codebook sizes, WGAN vs WGAN-GP with expected FID/PSNR ranges; WGAN-GP loop must match the spec exactly.

⚠️ Top pitfall: Relying on code-generation tools instead of tuning — marks are reserved for results commensurate with each technique.

Self-check: Which optimizer, critic-to-generator update ratio, latent distribution, and normalization rule does the WGAN-GP assignment specify?

Connects to: §12.2 weight clipping, §12.3 WGAN-GP, §12.4 SNGAN, §12.8 Pix2Pix, §12.10 CycleGAN

Key Industry Applications

Must-know: Industry practice wraps stochastic generative systems in seeds and evaluation harnesses; FID with InceptionV3 embeddings is the standard comparison yardstick.

⚠️ Top pitfall: Assuming choosing the right technique alone suffices — producing tuned results with it is what industry expects.

Self-check: Name three vision-to-vision workflows from this lecture that follow Pix2Pix or CycleGAN recipes.

Connects to: §12.5 SAGAN, §12.8 Pix2Pix, §12.10 CycleGAN

Was this lecture useful?

Loading comments…
🤖

BitsNotes AI Assistant

Subject Notes Assistant

Configure AI Chat

Choose how to access the chatbot
Have your own API key?

Switch to "Bring Your Own Key" tab above for unlimited access with any OpenAI-compatible provider.

🔑 Enter API key above to fetch live models from provider, or enter model name manually.
OpenAI-Compatible API Support

Choose any provider preset (Gemini, DeepSeek, Kimi, GLM, MiniMax, Qwen, OpenAI, Groq, Ollama, etc.) or enter a custom endpoint URL.

Security & Privacy First

Your API key is sent directly from your browser to your specified provider. BitsNotes servers never store or see your key.