StyleGAN: Style-Based Generator

StyleGAN (Karras et al., NVIDIA, 2018) is a GAN generator architecture that injects a learned "style" vector into every layer rather than feeding noise in only at the input. The result was a large jump in photorealism at up to 1024×1024 and, more importantly for practitioners, an intermediate latent space W that is far more disentangled than the input noise space — which made semantic image editing practical.


1. Architecture

StyleGAN Generator: Mapping Network + Synthesis Network z ∈ Z512-d Gaussian Mapping f8-layer MLPz → w w ∈ Wdisentangled Const 4×4learned input Block 4×4mod conv + noise Block 8×8mod conv + noise Block 16×16mod conv + noise … 1024²to RGB A(w): learned affine → per-layer style noise noise noise Styles at coarse blocks control pose and shape; fine blocks control color and texture.

A mapping network (an 8-layer MLP) transforms z into w. The synthesis network starts from a learned constant tensor, not from z. At each resolution block, a learned affine transform turns w into per-channel scales that modulate the convolution, and per-pixel Gaussian noise is added to provide stochastic detail (hair strands, freckles, pores). Because W does not have to follow a fixed Gaussian shape, the mapping network can "unwarp" the data manifold, making directions in W correspond more closely to individual factors of variation.

2. Modulation and Demodulation

Weight Demodulation (StyleGAN2) Style s = A(w)per input channel Modulatew'ijk = si · wijk Demodulatew'' = w' / √(Σ w'² + ε) Conv3×3on features Replaces StyleGAN1's AdaIN, which normalized feature statistics explicitly and caused 'droplet' artifacts. Demodulation normalizes the expected output scale through the weights instead.

StyleGAN2 moved style injection into the convolution weights. The scale is applied to the weights per input channel, then the weights are renormalized so outputs have unit expected variance. This removed artifacts and enabled other changes: skip / residual architectures instead of progressive growing, a path length regularizer encouraging a smooth mapping from W to images, and lazy regularization (applying R1 and path length penalties only every 16 steps).

3. Style Mixing, Truncation, and Inversion

4. Sampling and Truncation in PyTorch

The official NVIDIA repositories (stylegan2-ada-pytorch, stylegan3) ship pickled networks. This sketch assumes you have cloned one of them so that dnnlib and torch_utils are importable.

import pickle, torch, numpy as np
from PIL import Image

with open("ffhq.pkl", "rb") as f:            # a pretrained StyleGAN2-ADA / StyleGAN3 pickle
    G = pickle.load(f)["G_ema"].cuda().eval()  # the EMA generator

z = torch.randn(4, G.z_dim, device="cuda")
c = None                                       # class label (None for unconditional)

# Full call: mapping + synthesis, with truncation
img = G(z, c, truncation_psi=0.7, noise_mode="const")

# Same thing, but explicit so we can edit w
w = G.mapping(z, c, truncation_psi=0.7)        # (4, num_ws, 512): W+ layout
w_mix = w.clone()
w_mix[:, 8:] = w[0:1, 8:]                      # style mixing: fine layers from sample 0
img_mix = G.synthesis(w_mix, noise_mode="const")

def to_pil(x):
    x = (x.clamp(-1, 1) + 1) * 127.5
    return Image.fromarray(x.permute(1, 2, 0).to(torch.uint8).cpu().numpy())

for i, t in enumerate(img_mix):
    to_pil(t).save(f"mix_{i}.png")

5. Versions

StyleGAN Lineage 2017 ProGANprogressive growing 2018 StyleGANmapping net, AdaIN 2019 StyleGAN2demod, path length reg 2020–21 ADA / StyleGAN3aug, alias-free

StyleGAN2-ADA added adaptive discriminator augmentation so training works with a few thousand images instead of tens of thousands. StyleGAN3 redesigned the synthesis network around signal-processing principles so details move with the object rather than sticking to pixel coordinates ("texture sticking"), which matters for video and animation. StyleGAN-XL and StyleGAN-T explored scaling to ImageNet and text conditioning.

6. Trade-offs and Pitfalls

7. Losses and Regularisation

StyleGAN and StyleGAN2 use the non-saturating logistic loss from the original GAN paper: the discriminator minimises softplus(D(G(z))) + softplus(−D(x)) and the generator minimises softplus(−D(G(z))). Stability comes mostly from regularisation rather than the loss itself.

Mixed-precision training is used in the higher-resolution layers, and the mapping network uses a learning rate about 100 times lower than the synthesis network, which keeps W stable during training.

8. Training on Small Datasets with ADA

Adaptive Discriminator Augmentation (ADA) Batch real + fake images Augment flips, rotations, colour, cutout with probability p Discriminator sees only augmented images Overfit check r_t = E[sign D(real)] target ~0.6 r_t too high: raise p; too low: lower p (applied to G and D paths alike)

GAN discriminators overfit small datasets quickly: they memorise the training images, their outputs on real and validation images diverge, and generated images degrade. Ordinary data augmentation would teach the generator to produce augmented-looking images (rotated, colour-shifted). ADA (Karras et al., 2020) avoids this "leaking" by augmenting every image the discriminator sees, real and fake alike, with a probability p kept below the level at which the augmentations become ambiguous. The heuristic rt = E[sign(D(xreal))] measures how confidently D classifies training reals; p is increased when it exceeds the target of 0.6 and decreased otherwise. In the paper this made training feasible from a few thousand images and improved transfer learning from pretrained checkpoints, which is the usual route for custom domains such as artwork, product photos or medical textures.

9. Real-Image Editing Workflow

Editing a Real Photo Align detect, crop and align the face like training data Invert encoder (e4e, pSp) and/or optimisation into W or W+ Tune (optional) pivotal tuning: fine-tune G around the found code Edit w + a * direction (age, smile, pose) Blend paste back into the original photo

Editing a real photograph means first finding latent codes that reproduce it. Faces must be aligned exactly as in the training data (FFHQ uses landmark-based alignment), otherwise inversion fails. Encoders such as pSp and e4e predict W+ codes in one pass; optimisation-based inversion is slower but more faithful. Codes in plain W are easier to edit but reconstruct less accurately; W+ reconstructs better but edits can produce artefacts, which is the distortion-editability trade-off. Pivotal Tuning Inversion (Roich et al., 2021) resolves much of it by first finding an editable code, then briefly fine-tuning the generator so that code reproduces the photo exactly. An edit is then a vector addition along a direction found by InterFaceGAN, GANSpace or StyleCLIP, followed by blending the result into the original photo outside the face region.

10. Evaluation and Use Cases

MetricWhat it measuresNote
FIDDistance between Inception feature statistics of real and generated imagesStandard headline number, usually on 50k samples
Precision / recall (Kynkäänniemi et al., 2019)Fidelity and coverage separatelyShows the truncation trade-off clearly: lower ψ raises precision and lowers recall
Perceptual path lengthHow smoothly images change along latent interpolationsIntroduced with StyleGAN; lower indicates a more regular latent space
Equivariance metricsWhether details move with translations and rotationsIntroduced with StyleGAN3

Practical uses include face and avatar generation for games and research, synthetic training data for narrow domains, interactive editing tools, super-resolution and restoration with a StyleGAN prior (as in GFPGAN), and anonymisation studies. Generated faces have been used for fake social-media profiles; detection classifiers exist but generalise poorly to new generators, so provenance metadata and disclosure are the more reliable safeguards. Compared with diffusion models, StyleGAN gives a compact, editable latent space and single-pass generation, while diffusion gives better coverage of diverse data and text conditioning.

Further reading: Karras, Laine & Aila, "A Style-Based Generator Architecture for GANs" (2018, arXiv:1812.04948); Karras et al., "Analyzing and Improving the Image Quality of StyleGAN" (StyleGAN2, 2019); Karras et al., "Training Generative Adversarial Networks with Limited Data" (ADA, 2020); Karras et al., "Alias-Free Generative Adversarial Networks" (StyleGAN3, 2021); Tov et al., "Designing an Encoder for StyleGAN Image Manipulation" (e4e, 2021); Roich et al., "Pivotal Tuning for Latent-based Editing of Real Images" (2021).