Foundations to Frontier
Tests
H. Generative Models › H4 Generative Adversarial Networks

StyleGAN, StyleGAN2 and StyleGAN3

StyleGAN (Karras, Laine and Aila, CVPR 2019) redesigned the GAN generator. An 8-layer mapping network turns the latent z into an intermediate latent w. Each synthesis layer starts from a learned constant and receives w as a style through adaptive instance normalisation (AdaIN), plus per-pixel noise for stochastic detail. The result was photorealistic 1024 × 1024 faces (the FFHQ dataset) and controls that separate coarse attributes (pose, face shape) from fine ones (colour, freckles). StyleGAN2 (2020) replaced AdaIN with weight demodulation to remove droplet artifacts, dropped progressive growing, and added path-length regularisation. StyleGAN3 (2021) made the generator alias-free, so details move with the object instead of sticking to the pixel grid. This page covers the architecture, style mixing, the truncation trick in W, perceptual path length, and GAN inversion and editing. In the exercises you build AdaIN, modulation and demodulation, truncation and style mixing. You then train generators with and without a mapping network on an L-shaped 2D distribution. Truncation in W behaved as expected: precision rose from 0.82 to 0.93 as recall fell from 0.14 to 0.05. The mapping network itself did not help on this toy. It gave smoother latent paths (path length 0.094 vs 0.209) but much lower recall on every seed.

Level 0: Foundation

★☆☆☆☆ Introductory⏱ 5 minGeneral audience. No mathematics required.

Dials for coarse and fine features

StyleGAN does not feed random noise straight into the image-making network. A separate small network first turns the noise into a ‘style’, and the style is injected into every layer. Early layers control big things such as pose and face shape; late layers control colours and fine texture. Mixing the early styles of one face with the late styles of another gives a blend, and pulling styles towards the average gives safer, more typical images. The demo shows that pull: the truncation trick in style space.

GAN lab 2: applications and stability
ψ = 0.7: every w moves to w̄ + ψ(w − w̄). Smaller ψ gives typical, high-quality samples (precision up) but less variety (recall down); ψ = 1 is no truncation.
Why engineers care

StyleGAN-family models are used for realistic synthetic imagery and data augmentation. Their latent spaces are used for controllable editing and for inverting real images to study what a model has learned. The same realism raises deepfake concerns, which is why detection and provenance tools matter.

📝 Quick check (Level 0)
0/3 answered
  1. 1. StyleGAN's mapping network turns z into…
  2. 2. Early layers' styles control…
  3. 3. Pulling w towards the average gives…

Level 1: Beginner

★★☆☆☆ Basic⏱ 20 minSecondary-school mathematics: arithmetic and elementary algebra.

By hand

  • StyleGAN (2019). Mapping network: 8 fully connected layers, 512-dimensional z → w. Synthesis network: starts from a learned 4 × 4 constant. At each layer, AdaIN(x, y) = y_s (x − μ(x))/σ(x) + y_b with (y_s, y_b) = affine(w), plus per-pixel scaled noise. A 1024² generator has 18 style inputs (two per resolution). Style-mixing regularisation: switch from w₁ to w₂ at a random layer during training. It introduced the FFHQ dataset (70,000 faces), perceptual path length (PPL) and linear separability.
  • Truncation in W. w’ = w̄ + ψ(w − w̄); with ψ below 1, samples are more typical and of higher quality, but less varied.
  • StyleGAN2 (2020). Water-droplet artifacts came from AdaIN normalising away magnitude information. Fix: modulate weights by the style, then demodulate, i.e. divide each output channel by √(Σ w’²) so that statistics are normalised in expectation, not per instance. It replaced progressive growing with skip-connection G and residual D. Path-length regularisation makes ‖J_wᵀy‖ constant. Lazy regularisation computes R1 and PL every 16 steps. FFHQ FID 2.84.
  • StyleGAN2-ADA (2020): adaptive discriminator augmentation for small datasets.
  • StyleGAN3 (2021), ‘alias-free GAN’. Texture sticking came from aliasing: pixel-grid positional information leaking through padding, upsampling and pointwise nonlinearities. Fix: treat feature maps as continuous signals, low-pass filter around each nonlinearity (upsample → nonlinearity → filter → downsample), Fourier-feature input. This made G equivariant to translation (config T) and rotation (config R).
  • Inversion and editing. Projecting real images into W or W+ (Image2StyleGAN 2019, e4e 2021, pivotal tuning 2022); editing directions (InterFaceGAN, GANSpace); DragGAN (2023) point dragging. Later: StyleGAN-XL (ImageNet, 2022), StyleGAN-T (text-to-image, 2023).
📝 Quick check (Level 1)
0/3 answered
  1. 1. StyleGAN2 replaced AdaIN with…
  2. 2. StyleGAN3 fixed…
  3. 3. FFHQ contains…

Level 2: Intermediate

★★★☆☆ Intermediate⏱ 25 minUndergraduate students and practising engineers.

Using StyleGAN models

Exercise 1.

  • Adaptive instance normalisation.
  • Weight modulation and demodulation.
  • Truncation in W.
  • Style mixing across layers.

Practice.

  • Start from official PyTorch code (stylegan2-ada-pytorch, stylegan3) and pretrained FFHQ, AFHQ or MetFaces models; fine-tune with ADA for small datasets of a few thousand images.
  • Pick ψ per use: 0.5–0.7 for demos, 1.0 (none) for measuring FID or making training data.
  • Invert carefully: W+ inversion reconstructs better but edits worse; e4e or pivotal tuning balances both.
  • Measure FID and precision/recall at ψ = 1, plus PPL for smoothness.
  • Use StyleGAN3 config T or R when objects should move smoothly (video, animation); StyleGAN2 when only stills matter (it is cheaper).
# StyleGAN2-ADA / StyleGAN3 official code (NVlabs); pickles contain G_ema
import pickle, torch
with open("stylegan3-t-ffhq-1024x1024.pkl", "rb") as f:
    G = pickle.load(f)["G_ema"].cuda()
z = torch.randn([4, G.z_dim]).cuda()
w = G.mapping(z, None, truncation_psi=0.7)            # [4, 16, 512]: one w per layer
w[:, 8:] = G.mapping(torch.randn_like(z), None)[:, 8:]   # style mixing: new fine styles
img = G.synthesis(w, noise_mode="const")               # [4, 3, 1024, 1024] in [-1, 1]
🐍 Exercise 1: StyleGAN building blocks
Implement AdaIN, StyleGAN2's modulation and demodulation, truncation in W and style mixing.
📝 Quick check (Level 2)
0/3 answered
  1. 1. For measuring FID use ψ =…
  2. 2. W+ inversion…
  3. 3. Small datasets need…

Level 3: Advanced

★★★★☆ Advanced⏱ 25 minGraduate level, with full derivations and proofs.

Theory

Why a mapping network. The training data may have missing combinations of factors, such as no long-haired men in a dataset. A fixed Gaussian z must cover every combination, so G has to warp z space, entangling factors. W is learned and need not follow a fixed distribution, so it can be shaped to the data and untangled. StyleGAN supported this with lower PPL and better linear separability in W than in Z.

Demodulation as normalisation in expectation. For an output channel j, y_j = Σ_i w’_ij x_i. If the x_i are independent with unit variance, Var(y_j) = Σ_i w’_ij². Dividing w’_ij by √(Σ_i w’_ij²) restores unit variance without looking at the actual activations, so there is no per-instance normalisation for the generator to cheat with droplets.

Path-length regularisation. It penalises (‖J_wᵀ y‖ − a)² for random image-space directions y, with a running average a. A fixed step in W then produces a fixed-size change in the image, which improves PPL and makes inversion easier.

Aliasing. A pointwise nonlinearity such as ReLU creates frequencies above the Nyquist limit of the current resolution. Sampled on a grid, they fold back as aliases tied to pixel positions. StyleGAN3 upsamples, applies the nonlinearity, low-pass filters and downsamples, so the network’s output depends only on the continuous signal.

📝 Quick check (Level 3)
0/3 answered
  1. 1. Demodulation normalises activations…
  2. 2. Path-length regularisation makes a step in W produce…
  3. 3. Pointwise nonlinearities create…

Level 4: Expert

★★★★★ Expert⏱ 30 minResearchers: original papers and open problems.

Does a mapping network help on data with a missing corner, and does truncation in W trade recall for precision?

History.

  • T. Karras, S. Laine and T. Aila, “A style-based generator architecture for GANs” (2019).
  • T. Karras et al., “Analyzing and improving the image quality of StyleGAN” (2020).
  • T. Karras et al., “Alias-free generative adversarial networks” (2021).

Exercise 2. The StyleGAN entanglement argument in miniature.

  • Data: uniform on [−1, 1]² minus the quadrant x > 0, y > 0 (an L-shape with a missing corner).
  • Generators: with a mapping network, z (4) → 32 → 32 → w (4) → 32 → 32 → 2. Without, z → 32 → 32 → 32 → 32 → 2 (same depth). Same D and loss, Adam (β1 = 0.5), 800 steps.
  • Metrics: precision = share of samples inside the L (margin 0.1); recall = share of 1000 real points with a sample within 0.1; path length = mean ‖G(z + εδ) − G(z)‖²/ε².
  • Truncation: w’ = w̄ + ψ(w − w̄) applied to the mapping model.
seed 0 precision recall path length
no mapping 0.888 0.569 0.209
mapping network 0.821 0.137 0.094
mapping, ψ 0.7 0.868 0.098 –
mapping, ψ 0.4 0.927 0.051 –
  • Truncation worked as advertised on every seed: precision up and recall down (seed 1: 0.967 → 1.0 and 0.155 → 0.066; seed 2: 0.766 → 0.976 and 0.313 → 0.148).
  • The mapping network did not help here; negative result. Recall was lower on all seeds (0.137, 0.155, 0.313 against 0.569, 0.989, 0.442 without it). The smoother paths (0.094, 0.067, 0.24 against 0.209, 0.358, 0.299) partly reflect a generator covering a smaller region.
  • Interpretation: StyleGAN’s mapping network pays off with high-dimensional w, many layers each receiving w, and long training. A 4-dimensional w feeding one small MLP for 800 steps is a different regime. Do not read this as evidence against StyleGAN.
  • Caveat: no AdaIN, noise inputs or style mixing in the toy; GAN training at this size is noisy (no-mapping recall ranged from 0.442 to 0.989 across seeds).
🐍 Exercise 2 (research): does a mapping network help on data with a missing corner, and does truncation in W trade recall for precision?
Train small generators with and without a mapping network on an L-shaped distribution; compare precision, recall and path length, and apply truncation in W.

Style-based generators in AI, robotics and aerospace

  • Synthetic imagery with control: style mixing separates layout from appearance, which is useful for varying lighting and texture of synthetic scenes while keeping geometry.
  • Latent-space analysis: inverting real images into W lets you probe and edit attributes; similar ideas are used for interpretable anomaly analysis.
  • Deepfake detection and provenance: StyleGAN faces are common in disinformation; detectors and content credentials (C2PA) are the countermeasures.

References

  1. T. Karras, S. Laine and T. Aila (2019). “A style-based generator architecture for generative adversarial networks.” CVPR.
  2. T. Karras et al. (2020). “Analyzing and improving the image quality of StyleGAN.” CVPR.
  3. T. Karras et al. (2020). “Training generative adversarial networks with limited data.” NeurIPS.
  4. T. Karras et al. (2021). “Alias-free generative adversarial networks.” NeurIPS.
  5. X. Huang and S. Belongie (2017). “Arbitrary style transfer in real-time with adaptive instance normalization.” ICCV.