Skip to content
BIASED

StyleGAN: a style-based generator

Why a GAN's input noise is entangled, how a mapping network, AdaIN styles and noise inputs split control across layers, what style mixing and truncation give, how to measure disentanglement, and how StyleGAN2 removes the droplets.

Why the code is entangled

The extension Scaling GANs: ProGAN, SAGAN and BigGAN brought adversarial training to sharp 1024×10241024 \times 1024 faces. Control is another matter. The noise zz enters the generator once, at the first layer, and moving along one of its coordinates usually changes pose, identity and lighting all at once. Such a code is called entangled.

The reason is the fixed prior. The generator must turn p(z)=N(0,I)p(z) = \mathcal N(0, I) into the data distribution, so every region of zz-space has to produce a realistic image, at the frequencies of the training set. Suppose two factors, how masculine a face looks and how long its hair is, sit on two axes of zz, and the data contain no long-haired men. Straight axes would fill that corner with exactly the images the data lack. To avoid it, the generator bends the axes, and then one coordinate of zz changes both factors. Nothing in the GAN loss pushes back: the discriminator judges whole images, not how the code is organized.

StyleGAN (Karras, Laine and Aila, 2019) no longer feeds zz to the image layers. A mapping network, an 8-layer MLP, first turns z∈R512z \in \mathbb R^{512} into an intermediate code. We call this network MM, because ff is the critic in this course, and write its output as

w=M(z)∈W=R512.w = M(z) \in \mathcal W = \mathbb R^{512}.

The distribution of ww is not fixed in advance; it is whatever MM makes it. So the bending can happen inside MM, and W\mathcal W is free to keep the factors on straighter axes. Free to, not forced to: the bet is that realistic images are easier to draw from a less entangled code. Two measurements later in this topic check the bet.

The synthesis network and AdaIN

The image itself is drawn by the synthesis network SS, so the generator is Gθ(z)=S(M(z))G_\theta(z) = S\big(M(z)\big). Like ProGAN's generator, it goes from 4×44 \times 4 to 1024×10241024 \times 1024 with two convolutional layers per resolution, 18 in all; the discriminator is ProGAN's. Its input is not zz but a learned 4×4×5124 \times 4 \times 512 constant, the same for every image. All variation comes from outside, through ww.

Each layer ℓ\ell has its own learned affine map AℓA_\ell. It turns ww into a style for that layer: a scale ys,iy_{s,i} and a bias yb,iy_{b,i} for every channel ii. The style is applied by adaptive instance normalization, AdaIN (Huang and Belongie, 2017). Write hih_i for channel ii of a feature map, and μ(hi)\mu(h_i), σ(hi)\sigma(h_i) for its mean and standard deviation over the spatial positions. Then

AdaIN(hi,y)=ys,i hi−μ(hi)σ(hi)+yb,i.\mathrm{AdaIN}(h_i, y) = y_{s,i}\,\frac{h_i - \mu(h_i)}{\sigma(h_i)} + y_{b,i}.

The fraction is instance normalization from the topic Batch normalization, gradients and convolutions. The style then gives the channel a new scale and offset.

A worked example. A channel with values (1,3,5,7)(1, 3, 5, 7) has mean 44 and standard deviation 5≈2.236\sqrt 5 \approx 2.236, so it normalizes to (−1.342, −0.447, 0.447, 1.342)(-1.342,\ -0.447,\ 0.447,\ 1.342). The style ys,i=2y_{s,i} = 2, yb,i=0.5y_{b,i} = 0.5 turns that into (−2.18, −0.39, 1.39, 3.18)(-2.18,\ -0.39,\ 1.39,\ 3.18).

Replacing zz by a constant cost nothing: the paper's image-quality score on faces stayed practically the same. The generator does not need zz at the input once ww reaches every layer.

Local styles and noise

AdaIN does more than inject a style. Its first step throws away the mean and standard deviation of every channel, the very numbers the previous style set. So a style shapes one convolution, and the next AdaIN overrides it. Each style controls its own layer, and what it passes on is only the spatial pattern inside each channel, not the channel's overall scale.

Styles are global: one scale and one bias per channel, the same at every pixel. They cannot place individual hairs, freckles or pores. A traditional generator has to fake such randomness from its input, which costs capacity and tends to produce repeating patterns. StyleGAN gives it real randomness. After each convolution, a fresh noise image ε\varepsilon, one N(0,1)\mathcal N(0, 1) value per pixel, is added to every channel with a learned per-channel weight bib_i:

hi←hi+bi ε.h_i \leftarrow h_i + b_i\,\varepsilon .

Keep ww fixed and redraw the noise: strands of hair, stubble and skin pores rearrange, while identity and pose stay. Remove the noise and the images look painterly.

Nobody tells the network to split the work this way. The noise is independent from pixel to pixel, so using it for a global property such as pose would produce inconsistent images, and the discriminator punishes those. Global decisions go to the styles, local randomness to the noise.

Style mixing

If every layer receives the same ww, the network can still learn that neighbouring styles always come together. Style mixing breaks this habit. During training, for 90% of the images, two codes z1,z2z_1, z_2 go through the mapping network, and at a random layer the synthesis network switches from w1w_1 to w2w_2. A layer can no longer rely on its neighbours seeing the same code.

After training, mixing becomes an editing tool. Take the styles of one group of layers from image A and all the others from image B. The paper (Karras et al., 2019, Figure 3) groups the layers by resolution:

  • coarse styles, 424^2–828^2: pose, general hair style, face shape, eyeglasses;
  • middle styles, 16216^2–32232^2: smaller facial features, hair style, eyes open or closed;
  • fine styles, 64264^2–102421024^2: mainly the colour scheme and the microstructure.

The order makes sense. A low-resolution layer can only decide the large-scale layout, and by 64×6464 \times 64 the layout is settled, so only colour and texture are left to choose.

A separate code for every layer gives the extended space W+\mathcal W^+: 18 codes of 512 numbers instead of one. It can express more images than W\mathcal W, which will matter at the end of this topic.

Truncation in W

BigGAN traded variety for quality by resampling large coordinates of zz (see Scaling GANs: ProGAN, SAGAN and BigGAN). StyleGAN truncates in W\mathcal W instead. Let wˉ\bar w be the centre of mass of W\mathcal W, in practice an average of many mapped codes:

wˉ=Ez∼p(z) M(z).\bar w = \mathbb E_{z \sim p(z)}\, M(z).

Each code is pulled towards it with a factor ψ<1\psi < 1:

w′=wˉ+ψ (w−wˉ).w' = \bar w + \psi\,(w - \bar w).

With ψ=0.7\psi = 0.7 every code keeps 70% of its distance from the centre. Rare, poorly learned regions of W\mathcal W are avoided, and samples become cleaner and less varied. At ψ=0\psi = 0 every sample is the same "mean face". A negative ψ\psi reflects the code through the centre, and attributes flip to their opposites: viewpoint, glasses, age, hair length.

Two practical differences from BigGAN. The generator needs no special training to tolerate truncation, while BigGAN added orthogonal regularization for that. And truncation can be applied to some layers only. The paper's showcase images use ψ=0.7\psi = 0.7 at resolutions 424^2–32232^2: the layout is tamed, the fine detail is left alone.

Measuring disentanglement

Is W\mathcal W really less entangled than Z\mathcal Z? There are no labels for the factors, so the paper measures it in two ways that need no encoder.

Perceptual path length (PPL) asks how smoothly the image changes along a straight path between two codes. In an entangled space the path has to bend around missing combinations, and somewhere along it the image changes abruptly. Take two codes w1,w2w_1, w_2, a random point t∼U(0,1)t \sim U(0, 1) on the segment between them, and a tiny step ϵ=10−4\epsilon = 10^{-4}. Let dd be a perceptual distance between two images: a squared distance between their deep-network features. This is LPIPS, which gets its own topic later in the course. With lerp(w1,w2;t)=(1−t) w1+t w2\mathrm{lerp}(w_1, w_2; t) = (1 - t)\,w_1 + t\,w_2, the path length is

lW=E[1ϵ2 d(S(lerp(w1,w2;t)), S(lerp(w1,w2;t+ϵ)))].l_{\mathcal W} = \mathbb E\Big[\frac{1}{\epsilon^2}\, d\big(S(\mathrm{lerp}(w_1, w_2; t)),\ S(\mathrm{lerp}(w_1, w_2; t + \epsilon))\big)\Big].

Because dd is a squared distance, for a small step it is about ϵ2\epsilon^2 times the squared speed at which the image changes. Dividing by ϵ2\epsilon^2 leaves that squared speed, whatever the step. In Z\mathcal Z the same is done with spherical interpolation, because Gaussian codes concentrate on a shell. On faces, the traditional generator scores 412412 in Z\mathcal Z, the style-based one 234234 in W\mathcal W; lower is smoother.

Linear separability asks whether each attribute is split by a hyperplane in the code space. Attribute classifiers (gender, smile and so on, 40 in all) label generated images, and a linear SVM predicts each label from the code. With YiY_i the classifier's label and XiX_i the SVM's, the score is exp⁡(∑iH(Yi∣Xi))\exp\big(\sum_i H(Y_i \mid X_i)\big), using the conditional entropy from Entropy, cross-entropy and KL. It equals 11 when every attribute is perfectly linear. It falls from 10.7810.78 for the traditional generator in Z\mathcal Z to 3.793.79 for StyleGAN in W\mathcal W.

A telling detail: put the same mapping network in front of a traditional generator. Its W\mathcal W scores 6.526.52, while its Z\mathcal Z scores 170.29170.29. The mapping network absorbs the bending, and zz becomes even more tangled than before.

StyleGAN2: styles in the weights

StyleGAN images carry a tell-tale artifact: a blob like a water droplet, present in the feature maps from about 64×6464 \times 64 in nearly every image (Karras et al., 2020). The culprit is AdaIN. Normalizing each channel separately erases how strong the channels are relative to one another. The generator smuggles that information past the normalization with a strong local spike: one huge value dominates the channel's statistics and so controls how everything else gets scaled. Remove the normalization and the droplets disappear.

StyleGAN2 keeps the styles but moves them into the weights. A style is now just a scale sis_i per input channel, computed from ww by AℓA_\ell as before. Write κijk\kappa_{ijk} for a convolution weight from input channel ii to output channel jj at kernel tap kk; the letter ww is taken by the code. Modulation scales each input channel by its style:

κijk′=si κijk.\kappa'_{ijk} = s_i\,\kappa_{ijk}.

If the inputs are independent with unit variance, output channel jj then has standard deviation ∑i,kκijk′2\sqrt{\sum_{i,k} \kappa'^2_{ijk}}. Demodulation divides by it, so every output channel returns to unit variance (implementations add a tiny constant under the root):

κijk′′=κijk′∑i,kκijk′2.\kappa''_{ijk} = \frac{\kappa'_{ijk}}{\sqrt{\sum_{i,k} \kappa'^2_{ijk}}}.

A toy: one output, two inputs, one tap, weights (0.6,0.8)(0.6, 0.8) and styles (3,0.5)(3, 0.5). Modulation gives (1.8,0.4)(1.8, 0.4), and 1.82+0.42=3.4≈1.844\sqrt{1.8^2 + 0.4^2} = \sqrt{3.4} \approx 1.844, so demodulation gives (0.976,0.217)(0.976, 0.217). The output variance is 11, and the first input now carries 95% of it instead of 36%. That is the style at work, without normalizing any actual feature map. The price is an assumption: if the two inputs are correlated with ρ=0.5\rho = 0.5, the variance is 1+2⋅0.976⋅0.217⋅0.5≈1.211 + 2 \cdot 0.976 \cdot 0.217 \cdot 0.5 \approx 1.21, not 11.

Two more changes. A path length regularizer trains a fixed-size step in W\mathcal W to produce a fixed-size change in the image, which directly lowers PPL. And progressive growing gives way to a fixed network with skip connections. With larger networks on top, the paper's quality score on faces improves from 4.404.40 to 2.842.84 (lower is better; it is FID, from the evaluation topics later in the course).

Where control breaks

All this control works for images the generator made itself, where ww is known. A real photo comes with no code. To edit one, you first need a ww, or a point of W+\mathcal W^+, whose image matches it. Finding it is called GAN inversion: an optimization for each photo, gradient descent on a reconstruction loss through the frozen SS. It is slow, and a face outside the generator's range can only be approximated. StyleGAN2's path length regularization makes inversion noticeably easier, but does not make it unnecessary.

Disentanglement itself is a tendency, not a guarantee. The separability of W\mathcal W stays well above its floor of 11, and an attribute such as hair style is spread over the coarse and the middle groups. Each model also covers one category of images, mostly aligned crops: one network for faces, another for cars.

The missing piece is a way back from image to code that comes with the model. The next extension, Autoencoding GANs: AAE and α-GAN, trains an encoder together with the generator. The main line takes another route in The change of variables: normalizing flows make the generator itself invertible, so every image has exactly one zz, and with it an exact likelihood.

Check your understanding

The same questions as in Pulse. Answers are shared between modes.

Full notes

Answers are saved on the server and tied to this browser until you sign in.