Code Architecture — Improved Training of Wasserstein GANs (WGAN-GP) Notebook
Overview
The notebook implements the WGAN-GP gradient penalty from scratch in PyTorch and trains it on a 2D ring of 8 Gaussians. For comparison it trains the same networks as a WGAN with weight clipping. It then compares loss curves, samples, mode coverage, critic weights and the critic’s gradient norm over the plane. It runs on the CPU (the saved Kaggle run had no GPU).
Notebook Structure
1. Setup & Imports
- PyTorch, NumPy, matplotlib; nothing is installed
CUBLAS_WORKSPACE_CONFIGset before importing torch; seeds 42; cuDNN deterministic,torch.use_deterministic_algorithms(True, warn_only=True)- Figures as JPEG at 80 dpi; on Kaggle an
atexithook and a small background process copy the executed notebook toexecuted_solution.ipynb
2. Toy Data Distribution — 2D Gaussian Ring
- 8 mode centers on a circle of radius
RING_RADIUS = 2.0; each mode has standard deviationMODE_STD = 0.02 sample_real(n)picks a random mode per sample and adds Gaussian noise; returns an (n, 2) tensor
3. Generator Network (Generator)
- MLP: Linear(2, 128) → LeakyReLU(0.2) → Linear(128, 128) → LeakyReLU(0.2) → Linear(128, 2)
- Linear output (no Tanh), so the generator can reach the ring at radius 2
sample_noise(n): z ~ N(0, I) of shape (n, 2)
4. Critic Network (Critic)
- MLP: Linear(2, 128) → LeakyReLU(0.2) → Linear(128, 128) → LeakyReLU(0.2) → Linear(128, 1)
- No sigmoid and no batch normalization (the penalty is per sample, Section 4)
5. Gradient Penalty (gradient_penalty(critic, real, fake, lambda_gp=10.0))
- ε ~ U[0, 1] per sample, x̂ = ε · real + (1 − ε) · fake
torch.autograd.gradof the critic scores with respect to x̂, withcreate_graph=Trueso the penalty can be backpropagated- Returns λ · mean((‖∇‖₂ − 1)²) and the mean gradient norm
6. WGAN-GP Training Loop
- Settings from Algorithm 1:
N_CRITIC = 5, Adam withLR_GP = 1e-4,BETA1 = 0.0,BETA2 = 0.9,LAMBDA_GP = 10.0 N_ITERATIONS = 3000generator iterations,BATCH_SIZE = 256- Critic loss: mean D(fake) − mean D(real) + penalty; generator loss: −mean D(G(z))
- Records the Wasserstein estimate, penalty, gradient norm and generator loss each iteration, and samples at checkpoint iterations 0, 100, 500, 1000, 2000 and 3000
7. WGAN (Weight Clipping) Training
- Same networks and data; RMSProp with
LR_WGAN = 5e-5, 5 critic steps, every critic weight clamped to [−0.01, 0.01] (CLIP_VALUE) after each critic step - Records the same curves and checkpoint samples
8. Results
- 2×2 plot: Wasserstein estimates of both models, the GP term, the gradient norm against the target 1, and generator losses
- Prints the final Wasserstein estimates, gradient norm and penalty
- 8.2: samples at each checkpoint for both models over 2,000 real points
- 8.3: final 2,000 samples of each model next to the real data
9. Mode Coverage & Stability
count_modes_coveredandmode_coverage_distributionassign each of 5,000 generated samples to the nearest mode if it is within 0.5- Prints modes covered, the share of samples near a mode, samples per mode, and the share near a mode at each checkpoint; bar charts of samples per mode
10. Critic Weight Distribution
- Histograms of all critic weights for both models
- Prints the weight range and standard deviation, and the share of WGAN weights at the clipping limit
11. Gradient Penalty in Input Space
- 50×50 grid over [−3.5, 3.5]²; critic score contours and gradient norms at every grid point
- Prints the grid gradient-norm mean and range; draws the ‖∇‖ = 1 contour only if the norm crosses 1 on the grid
12. Summary
### What the run above showswith the saved run’s numbers
Key Shapes
| Tensor | Shape |
|---|---|
| Noise z | (256, 2) |
| Real / fake batch | (256, 2) |
| ε | (256, 1) |
| Critic score | (256, 1) |
| Gradient at x̂ | (256, 2) |
| Grid points (Section 11) | (2500, 2) |
Deliberate Simplifications vs Full Paper
- Data: a 2D toy ring instead of CIFAR-10, LSUN bedrooms, ImageNet 32×32 or text.
- Networks: small MLPs instead of DCGAN-style or ResNet networks; the critic has no normalization layer at all (the paper recommends layer normalization).
- Length: 3,000 generator iterations and one seed, instead of up to 200K iterations (Section 5.2).
- Metric: the share of samples near a mode, not the Inception score.
- Baseline: the clipped WGAN uses the original WGAN optimizer (RMSProp, 5e-5) rather than the same Adam settings.