17 / 34 · GANs
StyleGAN: a style-based generator
How to make the code of a GAN mean something: InfoGAN's information term, StyleGAN's mapping network and per-layer styles, StyleGAN2's weight demodulation, and StyleGAN3's alias-free layers.
Generative adversarial networks · Scaling GANs: progressive growing, self-attention and BigGAN · LPIPS
On this page 9
Move a face generator’s input a little along one coordinate: the head turns, but the person, the hair and the light change too. You would like one direction to change only the pose. The scaled-up GANs of the previous note draw convincing faces at , yet nothing ties a direction of to one attribute.
Two approaches expose controls without attribute labels during generator training. InfoGAN (Chen et al., 2016) rewards information about part of the input surviving in the output. StyleGAN (Karras, Laine and Aila, 2019) injects the latent code at many layers and gives noise a separate path. Neither construction guarantees that a coordinate means “pose” or “identity”.
Why z is entangled#
We call a representation disentangled when one direction changes one factor of variation (pose) and leaves the others (identity) alone, as in the β-VAE note. The GAN objective does not ask for it: judges whole images, however the generator uses .
A small probability model isolates one obstacle. Let binary attributes have joint probabilities
Both marginals are uniform, but . If we insist on and for independent , the outputs are independent; matching the uniform marginals then gives . That restricted coordinate-by-coordinate construction cannot fit the table. A joint construction can: draw independent , set , and use when , otherwise . A fixed prior permits this dependence; it does not prove that every semantic direction must be curved.
InfoGAN: a code the image must reveal#
InfoGAN splits the input into noise and a code with a factorized prior and generates . A plain GAN could ignore , since an image distribution independent of fools the discriminator as well, so InfoGAN asks for a large mutual information between the code and the image,
where is entropy in nats. For continuous codes we use differential entropy and densities, assuming the displayed entropies and expectations are finite. Mutual information is zero exactly under independence; the finite-entropy identity must not be used as an undefined difference of infinities. With the GAN value function and weight , the game is
A lower bound on mutual information#
The generator’s posterior is unknown, so InfoGAN adds an auxiliary network that guesses the code from the image. Write inside the conditional entropy; averaged over , the second term is the KL divergence from to , by definition:
The last step drops the KL term, which is never negative (the entropy note proves by Jensen’s inequality) and zero only when the distributions coincide. The remaining expectation is over by the product rule, so pairs are sampled forwards, , , , and the posterior is never needed. Adding gives the bound
tight when equals the posterior. is a constant, so the game becomes
Over this fits the guesser to the generator; over it makes the code easy to guess. Dropping a non-negative KL to an approximate posterior also gives the ELBO.
In most reported experiments, the guesser shares the convolutional layers with the discriminator and adds one head: a softmax for a categorical code, so is a cross-entropy, and for a continuous code a mean and a positive standard deviation , with
a squared error weighted by the network’s confidence.
For an original finite example, interpret the preceding table as . The posterior assigns probability to . Let the auxiliary predictor assign only to agreement. Then
The gap, nats, is exactly the conditional KL dropped above. The generator can preserve information even when the auxiliary predictor has not yet recovered all of it. For continuous codes, may be positive because a density can exceed 1.
What InfoGAN found#
In the authors’ MNIST experiment, with one 10-way and two continuous codes and no labels, the categorical code separated digit classes (a 5% error when matched to digit types), and the continuous codes control rotation and width. On faces, codes find pose, lighting and glasses.
Where InfoGAN stops#
The codes are designed by hand, and which factor each one controls can change between runs. Mutual information also asks for less than disentanglement: must be readable from the image, but nothing says that each controls a single factor absent from . The remaining noise has no such information constraint; the reported experiments reach .
StyleGAN takes the other route: it changes where and how the code enters the network.
StyleGAN: a style-based generator#
A traditional generator, such as Progressive GAN, feeds the code through its first layer only. StyleGAN instead sends through a mapping network , an 8-layer MLP, to . The synthesis network starts from a learned constant, and reaches each of its 18 layers, two per resolution from to , as a style; . Here collects the layer noise maps. The discriminator architecture follows Progressive GAN.
The mapping network and the space W#
The density in is induced by : its coordinates can become dependent even when those of are independent. In the binary example, this would allow the intermediate variables themselves to follow the correlated table. Rendering an attribute need not also solve the probability-matching problem. This is a useful freedom, not a theorem about the geometry learned by a GAN.
Nothing forces training to use this freedom; the authors argue that a disentangled is easier to render, and the two metrics below test the claim.
Styles through AdaIN#
A learned affine map turns into the style of layer : one scale and one bias per channel. The style acts through adaptive instance normalization (Huang and Belongie, 2017), defined for channel of a feature map as
where and are the mean and standard deviation of channel over its spatial positions, as in instance normalization.
Take an original four-position channel and a fixed noise pattern . For with , the mean is 0 and the population variance is . With style , AdaIN gives . Changing the style to changes the output mean to 1 and standard deviation to 2. Changing the noise coefficient to instead changes the spatial pattern while retaining the first style’s moments.
Style changes moments; noise changes the spatial pattern
These statements ignore the stabilizing and require nonzero input variance. Normalization removes a positive input rescaling; a negative one reverses signs. In general the output standard deviation is and the mean is . The four-position calculation omits convolution and activation: it isolates statistics, not semantic control in a trained image generator.
Each AdaIN replaces the channel mean and scale. Earlier layers still determine the normalized spatial pattern, so their influence can persist through later AdaIN operations. The style parameters are spatially uniform within a channel; the trained network determines which image properties they affect.
With styles in place, the code at the first layer no longer helped: a learned constant instead moved FID from 5.34 to 5.07 on CelebA-HQ and from 4.85 to 4.88 on FFHQ (Karras, Laine and Aila, 2019, Table 1). Those are authors’ benchmark results: a 50,000-image training-set reference, minimum FID over training, no truncation for FID. The learned weights and constant remain fixed; sample-dependent variation enters through styles and noise.
Noise for stochastic detail#
Much of a portrait is harmlessly random: hairs, freckles and pores. Instead of spending capacity to produce it from the input, StyleGAN adds to each layer a fresh single-channel image of Gaussian noise, scaled per channel by learned factors .
In the paper’s trained face models, redrawing noise at fixed mainly changed small details while identity and pose appeared stable. This is an empirical separation, not an invariance guaranteed by AdaIN. Channel-wide styles provide a coherent global signal; independent noise provides spatial variation. How training uses them depends on the model and data.
Style mixing: coarse, middle and fine styles#
Nothing forces all layers to use the same . Style mixing maps to and switches from to at a random crossover layer, on 90% of the training images, so the network cannot assume adjacent styles are correlated. Single-code FID stays at 4.40 against 4.42 on FFHQ; two-code images improve from 8.22 to 5.11 (Karras, Laine and Aila, 2019, Table 2).
The authors observed the following tendencies when mixing their trained face models:
- coarse styles, to : pose, general hair style, face shape and eyeglasses;
- middle styles, to : smaller facial features, hair style, eyes open or closed;
- fine styles, to : mainly the colour scheme and microstructure.
These layer roles are empirical and overlap; they are not a universal partition of semantics. A separate per layer defines the extended space , which the drag-editing note uses.
Truncation in W#
Rare regions can be harder to learn, so sampling near the centre can trade variety for quality. StyleGAN shrinks each toward the centre of mass, with :
At , a code keeps 70% of its distance from the centre. At , the affected styles all use , but noise may still change the output. A nonlinear generator evaluated at the mean code is not the mean image. Negative reflects codes across without guaranteeing opposite semantic attributes. Unlike BigGAN’s truncation in , this operation changes the intermediate code and can be restricted to coarse layers.
Measuring disentanglement without an encoder#
StyleGAN evaluates latent geometry without an image-to-code encoder. The measurements still use external information: PPL needs a perceptual network, and linear separability needs attribute classifiers. Neither score certifies independent semantic control.
Perceptual path length (PPL) asks how fast the image changes along an interpolation; in an entangled space a path can pass through features absent at both ends. With the LPIPS distance (Zhang et al., 2018), , , and , holding noise fixed within each image pair,
In -space slerp replaces lerp, since a straight line between two Gaussian samples dips inside their shell. Why divide by ? LPIPS is a weighted sum of squared differences of normalized features (LPIPS note), and to first order (Taylor) a small step changes the features by times their derivative along the path. So (squared speed).
Linear separability asks whether a binary attribute such as gender is cut off by a hyperplane in the latent space. Attribute classifiers label generated images, a linear SVM predicts each label from the code, and the score is the exponential of the summed conditional entropies of the labels given the side: 1 when every measured conditional entropy is zero. This describes the chosen predicted labels and sample, not all semantic factors.
Both metrics favour : a traditional generator with a mapping network in front has separability 6.52 in and 170.29 in its input space. PPL also crept up late in training while FID kept falling: the authors interpret this as a trade-off with entanglement; the metric trend alone does not establish its cause.
StyleGAN2: removing the artifacts#
StyleGAN images often contain a blob like a water droplet, and details such as teeth can stay fixed while the face turns. StyleGAN2 (Karras et al., 2020) traces the first to AdaIN and the second to progressive growing, and adds a smoothness regularizer.
Droplets and the normalization in AdaIN#
The droplet appears around in the feature maps. Instance normalization sets the mean and variance of each feature map separately, destroying the information in the relative sizes of the features; the hypothesis is that the generator smuggles it past the normalization with a strong local spike that dominates the statistics. Without the normalization step, the droplets disappear.
A toy map shows it: 16 positions, a pattern on 15 of them (8 positive, 7 negative) and a spike on the 16th. With and , the normalized pattern has half-gap 1.035 for every : the scale is lost. With and , 10, 40 the half-gap is 0.737, 0.386, 0.103, so it depends on , and the spike itself becomes 3.85 at : a volume knob the normalization cannot remove.
StyleGAN2 first splits AdaIN into modulation and normalization, moves the bias and the noise outside the styled part and normalizes the standard deviation only, so that the normalization can be replaced.
Weight modulation and demodulation#
Write for the weight from input channel to output channel at kernel position (not the latent), and for the style’s scale of input channel .
Modulation is a weight change: convolution is linear in each input channel, so scaling channel by and convolving equals convolving with .
Assume pairwise uncorrelated unit-variance inputs. Output at one position is , and the covariance terms vanish, so
For , dividing output by removes the effect of on the output scale, and the division folds into the weights:
The style block is now one convolution with style-dependent weights, scaled from the weights and the style, never from the feature maps, so a spike no longer changes the scaling and the droplet loses its purpose. The per-sample weights run as one grouped convolution.
For the following toy calculation set and keep inputs uncorrelated: one output channel of a convolution has weights , so unit-variance inputs give output variance 1.
| Quantity | Value |
|---|---|
| style | |
| modulated | |
| output variance | |
| 1.844 | |
| demodulated | |
| output variance |
The style still decides the mix (the first input carries 95% of the variance instead of 36%) but no longer the overall scale.
Correlation changes the result. With correlation 0.5, the same weights give
For uncorrelated unit-variance inputs and positive , the variance is , below 1 and close to it only when the summed squared weights greatly exceed the stabilizer. With general correlated inputs it may be larger or smaller. Demodulation predicts a scale from weights; it does not measure and fix the actual feature variance. The figure compares both cases on a convolution.
Demodulation predicts scale; correlation changes the result
Path-length regularization#
Models with equal FID can differ visibly in quality, and PPL tracks the difference: the generator, the authors suggest, stretches the regions of that give good images and squeezes bad ones into small regions of rapid change. They ask that a fixed step in give a fixed-size change in the image, in every direction:
where , is a random vector in image space, and tracks the global mean length. If equalled that mean exactly, the loss would be the variance over both and . It penalizes local directional variation and differences in mean scale between latent locations. To understand one part, hold fixed and examine the singular values of its Jacobian.
Derivation
The Jacobian is never formed: is a constant, so by linearity of differentiation component of the gradient of the scalar is , and one backward pass gives . Take the singular value decomposition with singular values , including zeros, for a code of dimension ; take in the numerical example. preserves lengths, and is again , because an affine map sends to . So . Then:
- The mean uses and linearity of expectation.
- The variance adds over the independent terms, and : integration by parts with for the standard normal density gives , the boundary terms vanishing.
- The last line expands to first order around , , a good approximation when concentrates. From the first two lines, : for equal singular values , a relative spread , small unless a few dominate.
For a fixed , the Cauchy–Schwarz inequality bounds from below, with equality only when all are equal: the local variance approximation is smallest when all singular values are equal. This fixes the total squared scale: without that constraint, a collapsed zero Jacobian would also remove the variance.
The local calculation gives approximately 0.50 for equal singular values and 0.82 when half are three times larger, with the same squared norm. Actual StyleGAN2 averages derivatives over layer-specific styles; the single-code analysis isolates its conditioning idea (Karras et al., 2020, Appendix B).
The FFHQ StyleGAN setup and StyleGAN2 also use R1 on the discriminator’s real-valued score,
See Mescheder, Geiger and Nowozin (2018) and the conditions discussed with StarGAN. In StyleGAN2, lazy regularization evaluates R1 every 16 and path length every 8 minibatches. The regularization term is multiplied by its interval, and optimizer parameters are adjusted; simply skipping updates is not the same procedure.
Without progressive growing#
The StyleGAN2 authors associate progressive growing with details that hold position and then jump. Their explanation is that intermediate layers once trained as outputs retain excessive high-frequency content. They replace growth with a fixed network: the generator adds upsampled RGB outputs at successive resolutions, and the discriminator uses residual blocks. Coarse-to-fine development is observed during training; skip connections do not force equal use of resolutions. Their full configuration improves FFHQ FID from 4.40 to 2.84 (Table 1), a combined ablation result rather than the effect of one change.
StyleGAN3: details glued to the pixel grid#
In a latent interpolation of StyleGAN2, fine detail such as hair stays fixed in pixel coordinates instead of moving with the face: texture sticking (Karras et al., 2021). The network uses unintended positional references: image borders, the per-pixel noise, and aliasing, faint after-images of the pixel grid left by imperfect upsampling filters and by pointwise nonlinearities such as ReLU.
The fix treats every feature map as samples of a continuous, bandlimited signal. Sampling cannot tell some frequencies apart: on a grid of 8 samples per unit, , and
because cosine has period and is even. The same ambiguity relates frequencies and on a grid sampled at rate . The Nyquist–Shannon sampling theorem states that an appropriately regular signal bandlimited strictly below can be reconstructed from its entire infinite uniform sample grid by sinc interpolation (Karras et al., 2021, Section 2). A finite crop needs boundary assumptions; eight samples do not determine an arbitrary continuous signal.
An operation is translation equivariant when shifting its continuous input shifts its continuous output. A pointwise ReLU has this property in the continuous domain. Its sampled implementation must also represent the frequencies the operation creates; otherwise aliasing breaks that correspondence.
Consider this bandwidth issue directly. Take a wave of frequency 3 on 8 samples per unit, below the limit of 4. With , the coefficient of , frequency 6, in the Fourier series of is
where the integral shrinks to because the ReLU output is zero elsewhere, and the second line is the product-to-sum identity. Frequency 6 folds to . The table gives the amplitude of the discrete Fourier transform of samples: the mean at frequency 0, half the cosine coefficient elsewhere. The continuous output has amplitudes , at frequency 3 and at 6; on the grid, harmonics 12, 18, 24 and higher fold too, giving the alias 0.125 and the mean 0.302. A half-pixel shift, of a unit, only changes phases in the continuous domain, where the pointwise ReLU commutes with it; on the grid the amplitudes change:
| Amplitude after ReLU | 8 per unit | 8, shifted | 16 per unit | 16, shifted |
|---|---|---|---|---|
| frequency 0 (the mean) | 0.302 | 0.327 | 0.314 | 0.320 |
| frequency 2 (the alias) | 0.125 | 0.096 | 0.015 | 0.006 |
| frequency 3 | 0.250 | 0.250 | 0.250 | 0.250 |
This toy’s grid alignment changes the frequency-2 amplitude by about on the coarse grid and on the finer grid. The last two columns retain frequencies below 4 after evaluating ReLU at twice the rate. Each shift is half of that grid’s pixel, so the physical shifts differ; this is a worked aliasing example, not a general error-reduction factor or an equivariance benchmark. Higher harmonics still fold into the retained band.
The actual StyleGAN3 ablation used unaligned FFHQ at . Raising temporary upsampling from to improved its translation-equivariance score from 66.65 to 74.21 dB and multiplied training time by 2.31 (Karras et al., 2021, Figure 3). Those are the authors’ trained-model measurements, separate from the scalar calculation.
StyleGAN3 combines carefully filtered resampling, nonlinearities evaluated on a finer grid, continuously shiftable Fourier inputs, no per-pixel noise, and margins around the image. Translation and rotation require different filter constraints. Its FFHQ runs cost 1,576 GPU-hours for StyleGAN3-T and 2,248 for StyleGAN3-R, against 1,106 for the StyleGAN2 baseline (Section 4). Similar FID does not mean identical training cost or semantics. The final designs also omit path-length regularization; the paper reports that adding it back harms FID.
Where control breaks#
StyleGAN controls images it produced from a known . Editing a photograph first needs a that reproduces it, GAN inversion, explained with its fidelity–editability trade-off in the drag-editing note. What lies outside the generator’s range cannot be reached; the path-length regularized StyleGAN2 is markedly easier to invert.
Nothing guarantees disentanglement: the separability of stays well above its floor of 1, PPL rises again late in training, and factors such as hair style spread over several layer groups. The claims are tied to particular training distributions. StyleGAN3 also evaluates unaligned images and beaches; none of these experiments guarantees faithful editing of arbitrary photographs.
What changed#
| Traditional generator | InfoGAN | StyleGAN | StyleGAN2 | StyleGAN3 | |
|---|---|---|---|---|---|
| Where the code enters | first layer | first layer, as | every layer, as AdaIN styles of | every layer, as weight modulation | the same |
| Source of control | input latent | an information term | the architecture | the same | the same |
| Random detail | from | from | per-pixel noise | per-pixel noise | no per-pixel noise |
| Main problem addressed | – | the code is ignored | control across scales | droplets, details tied to positions | texture sticking |
What you should remember#
- Independent coordinates passed through separate attribute functions cannot reproduce correlated attributes.
- InfoGAN: maximize ; the codes are chosen by hand.
- StyleGAN: , a learned constant, per-layer AdaIN styles, per-pixel noise; in the reported face models, coarse layers mainly affect layout and fine layers texture, with overlapping roles.
- StyleGAN2: unit output variance follows from uncorrelated unit-variance inputs and zero stabilizer; correlations change it.
- StyleGAN3: run nonlinearities at twice the resolution and filter, against aliases.
Code#
Three local NumPy experiments isolate modulation, local Jacobian conditioning and aliasing. They use synthetic arrays and download nothing. The printed values below are saved results of this code; they are not StyleGAN training or image-quality measurements.
import numpy as np
from numpy.lib.stride_tricks import sliding_window_view
rng = np.random.default_rng(0)
# 1. A modulated 3x3 convolution with one style vector per sample.
N, C, k, H = 4, 64, 3, 32 # 4 samples, 64 channels in and out
x = rng.standard_normal((N, C, H, H)) # i.i.d. unit-variance inputs
w = rng.standard_normal((C, C, k, k)) / np.sqrt(C * k * k) # (out, in, k, k)
s = np.exp(1.5 * rng.standard_normal((N, C))) # styles s_i, one vector per sample
wm = w[None] * s[:, None, :, None, None] # modulate: (N, out, in, k, k)
wd = wm / np.sqrt((wm ** 2).sum(axis=(2, 3, 4), keepdims=True) + 1e-8) # demodulate
patches = sliding_window_view(x, (k, k), axis=(2, 3)) # (N, in, 30, 30, k, k)
for name, wt in [("modulated", wm), ("demodulated", wd)]:
y = np.einsum("nichab,noiab->noch", patches, wt) # per-sample weights
sd = y.std(axis=(2, 3))
print(f"{name:12s} channel std: min {sd.min():.2f}, max {sd.max():.2f}")
# modulated channel std: min 1.97, max 7.12
# demodulated channel std: min 0.92, max 1.07
# 2. Compare local length variance at fixed total squared singular-value scale.
L = 512
y = rng.standard_normal((20000, L))
for name, sig in [("equal", np.ones(L)), ("half 3x larger", np.r_[np.ones(256), 3 * np.ones(256)])]:
sig = sig * np.sqrt(L / (sig ** 2).sum()) # same sum of sigma_i^2 = 512
length = np.sqrt((sig ** 2 * y ** 2).sum(axis=1))
print(f"{name:15s} Var|J^T y| = {length.var():.2f}, formula {(sig**4).sum() / (2 * (sig**2).sum()):.2f}")
# equal Var|J^T y| = 0.51, formula 0.50
# half 3x larger Var|J^T y| = 0.84, formula 0.82
# 3. Aliasing: ReLU of a frequency-3 wave on a grid, shifted by half a pixel.
def relu_spectrum(pixels_per_unit, shift):
t = np.arange(pixels_per_unit) / pixels_per_unit
out = np.maximum(0, np.cos(2 * np.pi * 3 * (t - shift)))
return np.abs(np.fft.rfft(out))[:4] / pixels_per_unit # amplitudes at frequencies 0..3
for m in [8, 16]: # 8: the layer's grid; 16: twice the resolution, then low-pass
print(m, relu_spectrum(m, 0).round(3), relu_spectrum(m, 1 / (2 * m)).round(3)) # shift by half of its pixel
# 8 [0.302 0. 0.125 0.25 ] [0.327 0. 0.096 0.25 ]
# 16 [0.314 0. 0.015 0.25 ] [0.32 0. 0.006 0.25 ]
Next#
The original StyleGAN training does not learn an image-to-code encoder. Inversion can use optimization, a separately trained encoder, or both, and cannot guarantee a good code for every photograph. The next note studies learning an encoder together with the generator through adversarial autoencoders and α-GAN.
Where to see the images#
Figure numbers refer to the linked arXiv versions.
- InfoGAN (arXiv v1): MNIST codes varied one at a time, Figure 2.
- StyleGAN (arXiv v3): uncurated faces, Figure 2; style mixing, Figure 3; noise, Figure 4; truncation, Figure 8.
- StyleGAN2 (arXiv v2): droplets, Figure 1; details stuck under progressive growing, Figure 6.
- StyleGAN3 (project page with videos): texture sticking shows only in motion.
References#
- Xi Chen, Yan Duan, Rein Houthooft, John Schulman, Ilya Sutskever, Pieter Abbeel. InfoGAN: Interpretable Representation Learning by Information Maximizing Generative Adversarial Nets. NeurIPS, 2016. Sections 3–7; Appendix C.
- Tero Karras, Samuli Laine, Timo Aila. A Style-Based Generator Architecture for Generative Adversarial Networks. CVPR, 2019. Sections 2–4; Tables 1, 2, 4; Appendices B–C.
- Tero Karras, Samuli Laine, Miika Aittala, Janne Hellsten, Jaakko Lehtinen, Timo Aila. Analyzing and Improving the Image Quality of StyleGAN. CVPR, 2020. Sections 2–4; Table 1; Appendices B–C.
- Tero Karras, Miika Aittala, Samuli Laine, Erik Härkönen, Janne Hellsten, Jaakko Lehtinen, Timo Aila. Alias-Free Generative Adversarial Networks. NeurIPS, 2021. Sections 2–4; Figure 3; Appendices B, F.
- Lars Mescheder, Andreas Geiger, Sebastian Nowozin. Which Training Methods for GANs Do Actually Converge?. ICML, 2018. Section 4.1, Eq. 9.
- Xun Huang, Serge Belongie. Arbitrary Style Transfer in Real-time with Adaptive Instance Normalization. ICCV, 2017. Section 5, Eq. 8.
- Richard Zhang, Phillip Isola, Alexei A. Efros, Eli Shechtman, Oliver Wang. The Unreasonable Effectiveness of Deep Features as a Perceptual Metric. CVPR, 2018. Section 3, Eq. 1.