Lesson 5.2 — GANs & Normalizing Flows
Previous lesson · 5.1 Variational Autoencoders · Course overview · Next lesson · 5.3 Denoising Diffusion Probabilistic Models
Implicit and Explicit Generative Models
A GAN specifies how to sample from its model by transforming noise. An invertible normalizing flow also supplies the density at an observed point through a change of variables. A VAE provides a likelihood model whose marginal density generally requires integrating over latent variables.
A pushforward is the distribution obtained by applying a map to a random input. Mapping one noise coordinate into two dimensions can place the entire output distribution on a curve. A two-dimensional density then need not exist, even though drawing and plotting samples is straightforward.
Imagine that a generator outputs . Drawing a sample takes one operation. Working backward from a positive reveals two possible sources, and . Both contribute probability near the output. A GAN can train such a many-to-one generator from samples. A normalizing flow chooses invertible layers so every output has one source to trace, together with a computable local change in volume.
Inspect samples from maps with different latent dimensions
Implicit Distribution Sampling
Generator and Discriminator
The generator maps a noise vector to a candidate observation. The discriminator evaluates real and generated observations. Its scalar logit becomes a probability after applying the sigmoid.
| Update | What enters the discriminator | Where the gradient goes |
|---|---|---|
| Learn to distinguish | A real observation and a generated observation, each scored separately | Update the discriminator. Detach the generated observation from the generator. |
| Improve the generator | A generated observation | Hold the discriminator weights fixed. Differentiate its score with respect to the observation and back through the generator. |
In the experiment, the generator uses widths 2, 12, and 2, for 62 parameters. The discriminator uses widths 2, 12, and 1, for 49 parameters. Both use tanh hidden units and linear output layers. Detach generated samples during a discriminator update. During a generator update, keep the derivative through the discriminator input while holding the discriminator parameters fixed.
Trace one forward pass through both networks
Generator–Discriminator Dataflow
Adversarial Objectives and Gradients
The original minimax objective rewards the discriminator for classifying real and generated data correctly. For a fixed generator and densities with respect to a common measure, maximize the integrand over the discriminator output at each point. Writing the density weights as and gives the stationary condition where both are positive. The optimum extends to the endpoints when one weight is zero.
Substituting the optimum gives the Jensen–Shannon divergence expression. The identity describes the ideal optimal discriminator. Alternating finite gradient steps in the experiment need not decrease the divergence monotonically.
The last derivatives are for the per-sample logit terms before averaging. With a very negative fake logit, the minimax derivative approaches zero and the non-saturating derivative approaches minus one. The actual parameter gradient also depends on the discriminator's derivative with respect to its input and the generator's parameter Jacobian. The implementation uses softplus or a logits-based binary cross-entropy to handle extreme logits.
Adversarial Loss & Gradient
Mode Collapse and Evaluation
A generator can send many different inputs to one small region of data space, leaving entire modes unsampled. The two players can also oscillate. Compare the generated and validation distributions directly to understand these effects.
The common target is an equally weighted mixture of four isotropic Gaussians centered at with marginal standard deviation 0.30. The empirical sliced Wasserstein-2 statistic projects equal-sized sets of points onto fixed unit directions. It sorts each projection before matching the values and averages squared distances before taking the square root.
The mode count assigns generated points to the nearest center within radius 0.75. A center is counted as covered when it receives at least 13 of the 256 draws. Read the fraction of points within the radius along with the covered mode count to see how many generated samples belong to those neighborhoods.
Mode Collapse Explorer
Change of Variables

Here the numbers explain the minus sign in the log-density formula. Start with a uniform draw on . Its density is , so the narrow shaded interval contains probability . The map sends that interval to . Its mass is still . Since its width is now one, its density must be . Tracing an observation back identifies the source. Dividing by the stretch converts source density to output density.
For a differentiable invertible map between spaces of the same dimension with a nonsingular Jacobian, small volumes scale by . Probability mass carried by the volume stays the same. An expansion lowers the density of the transported mass.
The inverse map takes an observation to the base distribution for evaluation. Its log absolute determinant is added. The forward map takes noise to an observation for generation, and its log absolute determinant is subtracted in the density formula. In one dimension, with turns a standard normal into a Gaussian with mean and standard deviation .
Change of Variables Simulator
Jacobian and Local Volume
The Jacobian is a matrix of partial derivatives. It predicts how short displacements move near the evaluation point, and the absolute determinant gives the local volume ratio.
In the triangular example, shear changes the shape of the deformed cell. Its area scales by for any shear value. For a triangular Jacobian, the determinant follows from the diagonal, and the log of its absolute value is a sum over diagonal entries.
Jacobian & Volume Transformation
RealNVP Affine Coupling
An affine coupling layer leaves one block fixed. That block determines the scale and shift applied to the other block. The fixed block stays available in both directions, so both the inverse and Jacobian are cheap to evaluate even when the scale and shift functions themselves lack inverses.
Alternate the fixed and transformed coordinates so both can change. Add the log absolute determinants of successive layers at the corresponding intermediate states. The exact likelihood is the density of the fitted model. Its expressiveness is still constrained by the choice of invertible layers and the topology of the base distribution.
The experiment uses four affine coupling layers with 12 trainable parameters per layer and alternates the two coordinates. Each scale and shift uses the basis . The scale limits the exponential multiplier, while sets the shift.
Affine Coupling Layer Inspector
Engineering Experiment · GAN versus Normalizing Flow
Train on 256 mixture points and validate on an independently drawn set of the same size. Each update samples 32 training points with replacement. The GAN performs one Adam update for each of its two networks, and the flow performs one update. Defaults are seed 3, 600 iterations, and learning rate 0.005. Both models generate from the same 256 held-out base-noise vectors.
Live GAN vs. Normalizing Flow
Results on the default split
At update 600, the GAN covers one of the four target modes and the flow covers four. About 43% of the flow samples fall within the evaluation radius. The flow's validation NLL changes from 4.3786 to 2.8123, while empirical sliced Wasserstein-2 changes from 0.7937 to 0.7741. All samples enter the metrics, including points outside the scatter plot's displayed range. The GAN trains 111 parameters over two optimizers and the flow trains 48, so the measurements describe these configurations on this synthetic task.
Reproducible PyTorch implementation
The script uses CPU float64, the browser experiment's pseudorandom stream, and PyTorch autograd and Adam. It includes forward and inverse coupling, density evaluation, and the same metrics for both sample sets. A round-trip check compares the recovered base vector and the signed log determinants.
import math, torch
from torch import nn
import torch.nn.functional as F
torch.set_default_dtype(torch.float64);torch.set_num_threads(1)
def rng(seed):
def r():
nonlocal seed
seed=(1664525*seed+1013904223)&0xffffffff
return seed/4294967296
return r
def normal(r):return math.sqrt(-2*math.log(max(r(),1e-15)))*math.cos(2*math.pi*r())
def noise(r,n):return torch.tensor([[normal(r),normal(r)] for _ in range(n)])
CENTERS=torch.tensor([[-1.6,-1.6],[-1.6,1.6],[1.6,-1.6],[1.6,1.6]])
def data(seed,n=256):
r=rng(seed);return torch.tensor([[float(c)+.30*normal(r) for c in CENTERS[int(4*r())]] for _ in range(n)])
class MLP(nn.Module):
def __init__(self,out,r):
super().__init__();self.w=nn.Parameter(torch.tensor([.8*(r()-.5) for _ in range(12*2)]).reshape(12,2));self.b=nn.Parameter(torch.zeros(12));self.v=nn.Parameter(torch.tensor([.8*(r()-.5) for _ in range(out*12)]).reshape(out,12));self.c=nn.Parameter(torch.zeros(out))
def forward(self,x):return torch.tanh(x@self.w.T+self.b)@self.v.T+self.c
def flat(self):return torch.cat([p.flatten() for p in self.parameters()]).tolist()
def basis(x):return torch.stack([torch.ones_like(x),x,x.tanh(),(2*x).tanh(),x.sin(),x.cos()],-1)
class Flow(nn.Module):
def __init__(self,r):
super().__init__();self.p=nn.Parameter(torch.tensor([.06*(r()-.5) for _ in range(48)]).reshape(4,2,6))
def transform(self,x,inverse=False):
ld=torch.zeros(len(x));a,b=x.unbind(-1)
for i in (reversed(range(4)) if inverse else range(4)):
u,v=(a,b) if i%2==0 else (b,a);q=basis(u)@self.p[i].T;s=.8*q[:,0].tanh();t=q[:,1];v=(v-t)*(-s).exp() if inverse else v*s.exp()+t;ld=ld+(-s if inverse else s);a,b=(u,v) if i%2==0 else (v,u)
return torch.stack([a,b],-1),ld
def nll(self,x):
z,ld=self.transform(x,True);return .5*z.square().sum(-1)+math.log(2*math.pi)-ld
def flat(self):return self.p.flatten().tolist()
def metrics(x,y):
# fixed 24 projection angles; equally sized generated and holdout sets
a=torch.arange(24)*math.pi/24;d=torch.stack([a.cos(),a.sin()],1);sw=(torch.sort(x@d.T,dim=0).values-torch.sort(y@d.T,dim=0).values).square().mean().sqrt().item();dist=torch.cdist(x,CENTERS);v,i=dist.min(1);counts=torch.bincount(i[v<=.75],minlength=4);return dict(swd=sw,counts=counts.tolist(),valid=(v<=.75).double().mean().item(),coverage=int((counts>=13).sum()))
def run(seed=3,steps=600,lr=.005):
tr=data(seed);va=data(seed+1000);zv=noise(rng(seed+2000),256);r=rng(seed+3000);g=MLP(2,r);d=MLP(1,r);f=Flow(r);og=torch.optim.Adam(g.parameters(),lr=lr);od=torch.optim.Adam(d.parameters(),lr=lr);of=torch.optim.Adam(f.parameters(),lr=lr);r=rng(seed+4000);hist=[]
for i in range(steps+1):
if i%20==0 or i==steps:
with torch.no_grad():
gx=g(zv);fx,_=f.transform(zv);hist.append(dict(i=i,gan=metrics(gx,va),flow=metrics(fx,va),nll=f.nll(va).mean().item(),g=g.flat(),d=d.flat(),f=f.flat()))
if i==steps:break
x=tr[[int(r()*len(tr)) for _ in range(32)]];z=noise(r,32);zz=noise(r,32)
od.zero_grad();dl=F.softplus(-d(x)).mean()+F.softplus(d(g(z).detach())).mean();dl.backward();od.step()
og.zero_grad();gl=F.softplus(-d(g(zz))).mean();gl.backward();og.step()
of.zero_grad();fl=f.nll(x).mean();fl.backward();of.step()
return hist
if __name__=='__main__':
import json
h=run();print(json.dumps([{k:v for k,v in a.items() if k not in ('g','d','f')} for a in (h[0],h[-1])],indent=2))
References and Chapter Connection
| Mechanism | GAN | Flow |
|---|---|---|
| Training | Adversarial optimization | Maximum likelihood |
| Generation | G(z) | f(z) |
| Exact density | Not generally tractable | Tractable under invertibility |
| Typical risks | Mode collapse, oscillation | Limited expressivity, costly transforms |
- Goodfellow et al. derive the adversarial objective and ideal discriminator. Generative Adversarial Nets
- Dinh, Sohl-Dickstein, and Bengio describe affine coupling and likelihood evaluation. Density Estimation using Real NVP
- Chapters 15 and 16 compare GANs and normalizing flows. Understanding Deep Learning
- Papamakarios et al. survey invertible density models. Normalizing Flows for Probabilistic Modeling and Inference
- The PyTorch reference documents stable binary cross-entropy from logits. BCEWithLogitsLoss
The diffusion lesson uses the same target mixture and replaces the single generation map with a sequence of denoising steps.
Previous lesson · 5.1 Variational Autoencoders · Course overview · Next lesson · 5.3 Denoising Diffusion Probabilistic Models