Course contents 17 / 34

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.

On this page 9

Move a face generator’s input zz 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 1024×10241024 \times 1024, yet nothing ties a direction of zz 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: DD judges whole images, however the generator uses zz.

A small probability model isolates one obstacle. Let binary attributes A,BA,B have joint probabilities

B=0B=0B=1B=1
A=0A=07/167/161/161/16
A=1A=11/161/167/167/16

Both marginals are uniform, but P(A=B)=7/8P(A=B)=7/8. If we insist on A=h1(Z1)A=h_1(Z_1) and B=h2(Z2)B=h_2(Z_2) for independent Z1,Z2Z_1,Z_2, the outputs are independent; matching the uniform marginals then gives P(A=B)=1/2P(A=B)=1/2. That restricted coordinate-by-coordinate construction cannot fit the table. A joint construction can: draw independent U,V∼U(0,1)U,V\sim U(0,1), set A=1[U<1/2]A=\mathbf1[U<1/2], and use B=AB=A when V<7/8V<7/8, otherwise B=1−AB=1-A. 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 zz and a code c=(c1,…,cM)c = (c_1, \dots, c_M) with a factorized prior p(c)=∏ip(ci)p(c) = \prod_i p(c_i) and generates x=G(z,c)x = G(z, c). A plain GAN could ignore cc, since an image distribution independent of cc fools the discriminator as well, so InfoGAN asks for a large mutual information between the code and the image,

I(c;x)=H(c)−H(c∣x),H(c∣x)=−E(c,x)log⁡p(c∣x),\begin{aligned} I(c; x) &= H(c) - H(c \mid x), \\ H(c \mid x) &= -\mathbb E_{(c, x)} \log p(c \mid x), \end{aligned}

where HH 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 VV and weight λ≥0\lambda\ge0, the game is

min⁡Gmax⁡D  V(D,G)−λ I(c;G(z,c)).\min_G \max_D \; V(D, G) - \lambda\, I\big(c; G(z, c)\big) .

A lower bound on mutual information#

The generator’s posterior p(c∣x)p(c \mid x) is unknown, so InfoGAN adds an auxiliary network qϕ(c∣x)q_\phi(c \mid x) that guesses the code from the image. Write log⁡p=log⁡qϕ+log⁡(p/qϕ)\log p = \log q_\phi + \log(p/q_\phi) inside the conditional entropy; averaged over c∼p(c∣x)c \sim p(c \mid x), the second term is the KL divergence from p(⋅∣x)p(\cdot \mid x) to qϕ(⋅∣x)q_\phi(\cdot \mid x), by definition:

−H(c∣x)=Ex Ec∼p(c∣x)log⁡p(c∣x)=Ex Ec∼p(c∣x)log⁡qϕ(c∣x)+Ex DKL(p(⋅∣x) ∥ qϕ(⋅∣x))≥Ex Ec∼p(c∣x)log⁡qϕ(c∣x).\begin{aligned} -H(c \mid x) &= \mathbb E_{x}\, \mathbb E_{c \sim p(c \mid x)} \log p(c \mid x) \\ &= \mathbb E_{x}\, \mathbb E_{c \sim p(c \mid x)} \log q_\phi(c \mid x) \\ &\quad + \mathbb E_x\, D_{\mathrm{KL}}\big(p(\cdot \mid x) \,\|\, q_\phi(\cdot \mid x)\big) \\ &\ge \mathbb E_{x}\, \mathbb E_{c \sim p(c \mid x)} \log q_\phi(c \mid x) . \end{aligned}

The last step drops the KL term, which is never negative (the entropy note proves DKL≥0D_{\mathrm{KL}} \ge 0 by Jensen’s inequality) and zero only when the distributions coincide. The remaining expectation is over p(x) p(c∣x)=p(c) p(x∣c)p(x)\,p(c \mid x) = p(c)\,p(x \mid c) by the product rule, so pairs are sampled forwards, c∼p(c)c \sim p(c), z∼p(z)z \sim p(z), x=G(z,c)x = G(z, c), and the posterior is never needed. Adding H(c)H(c) gives the bound

LI(G,qϕ)=Ec, zlog⁡qϕ(c∣G(z,c))+H(c)≤I(c;G(z,c)),\begin{aligned} \mathcal L_I(G, q_\phi) &= \mathbb E_{c,\, z} \log q_\phi\big(c \mid G(z, c)\big) + H(c) \\ &\le I\big(c; G(z, c)\big), \end{aligned}

tight when qϕq_\phi equals the posterior. H(c)H(c) is a constant, so the game becomes

min⁡G, qϕmax⁡D  V(D,G)−λ LI(G,qϕ).\min_{G,\, q_\phi} \max_D \; V(D, G) - \lambda\, \mathcal L_I(G, q_\phi) .

Over qϕq_\phi this fits the guesser to the generator; over GG 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 −log⁡qϕ-\log q_\phi is a cross-entropy, and for a continuous code a mean μ(x)\mu(x) and a positive standard deviation σ(x)\sigma(x), with

log⁡qϕ(c∣x)=−(c−μ(x))22σ(x)2−ln⁡σ(x)−12ln⁡2π,\log q_\phi(c \mid x) = -\frac{(c - \mu(x))^2}{2\sigma(x)^2} - \ln \sigma(x) - \tfrac12 \ln 2\pi ,

a squared error weighted by the network’s confidence.

For an original finite example, interpret the preceding table as (C,X)(C,X). The posterior assigns probability 7/87/8 to C=XC=X. Let the auxiliary predictor assign only 3/43/4 to agreement. Then

I(C;X)=ln⁡2+78ln⁡78+18ln⁡18≈0.316377,LI=ln⁡2+78ln⁡34+18ln⁡14≈0.268139.\begin{aligned} I(C;X)&=\ln2+\tfrac78\ln\tfrac78+\tfrac18\ln\tfrac18\\ &\approx0.316377,\\ \mathcal L_I&=\ln2+\tfrac78\ln\tfrac34+\tfrac18\ln\tfrac14\\ &\approx0.268139. \end{aligned}

The gap, 0.0482380.048238 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, log⁡qϕ\log q_\phi 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: cc must be readable from the image, but nothing says that each cic_i controls a single factor absent from zz. The remaining noise zz has no such information constraint; the reported experiments reach 64×6464 \times 64.

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 z∈R512z \in \mathbb R^{512} through a mapping network ff, an 8-layer MLP, to w=f(z)∈W=R512w = f(z) \in \mathcal W = \mathbb R^{512}. The synthesis network gg starts from a learned 4×4×5124 \times 4 \times 512 constant, and ww reaches each of its 18 layers, two per resolution from 424^2 to 102421024^2, as a style; G(z,n)=g(f(z),n)G(z,n)=g(f(z),n). Here nn collects the layer noise maps. The discriminator architecture follows Progressive GAN.

The mapping network and the space W#

The density in W\mathcal W is induced by ff: its coordinates can become dependent even when those of zz 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 W\mathcal W is easier to render, and the two metrics below test the claim.

Styles through AdaIN#

A learned affine map AℓA_\ell turns ww into the style yℓ=(ys,yb)y_\ell = (y_s, y_b) of layer ℓ\ell: one scale and one bias per channel. The style acts through adaptive instance normalization (Huang and Belongie, 2017), defined for channel ii of a feature map xx as

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

where μ(xi)\mu(x_i) and σ(xi)\sigma(x_i) are the mean and standard deviation of channel ii over its spatial positions, as in instance normalization.

Take an original four-position channel x=(−3,−1,1,3)x=(-3,-1,1,3) and a fixed noise pattern n=(1,−1,−1,1)n=(1,-1,-1,1). For r=x+bnr=x+bn with b=0.5b=0.5, the mean is 0 and the population variance is 5.255.25. With style (ys,yb)=(1,0)(y_s,y_b)=(1,0), AdaIN gives (−1.091,−0.655,0.218,1.528)(-1.091,-0.655,0.218,1.528). Changing the style to (2,1)(2,1) changes the output mean to 1 and standard deviation to 2. Changing the noise coefficient to −0.5-0.5 instead changes the spatial pattern while retaining the first style’s moments.

Figure

Style changes moments; noise changes the spatial pattern

Style changes moments; noise changes the spatial patternThree rows show computed values. Changing style doubles standard deviation and shifts the mean; changing noise preserves those moments but changes individual positions.Four output positionsInitial settingb = 0.5; yₛ = 1; yᵦ = 0−1.09−0.650.221.53mean: 0std: 1Different styleb = 0.5; yₛ = 2; yᵦ = 1−1.18−0.311.444.06mean: 1std: 2Different noiseb = -0.5; yₛ = 1; yᵦ = 0−1.53−0.220.651.09mean: 0std: 1Style changes moments; noise changes the spatial patternThree rows show computed values. Changing style doubles standard deviation and shifts the mean; changing noise preserves those moments but changes individual positions.Four output positionsInitial settingb = 0.5; yₛ = 1; yᵦ = 0−1.09−0.650.221.53mean: 0; std: 1Different styleb = 0.5; yₛ = 2; yᵦ = 1−1.18−0.311.444.06mean: 1; std: 2Different noiseb = -0.5; yₛ = 1; yᵦ = 0−1.53−0.220.651.09mean: 0; std: 1
Four positions: x = (−3, −1, 1, 3), n = (1, −1, −1, 1). Normalize x + bn, then apply the style. The second row changes style; the third reverses noise. Convolution, activation and the stabilizer are omitted.

These statements ignore the stabilizing ϵ\epsilon and require nonzero input variance. Normalization removes a positive input rescaling; a negative one reverses signs. In general the output standard deviation is ∣ys∣|y_s| and the mean is yby_b. 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 BB.

In the paper’s trained face models, redrawing noise at fixed ww 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 ww. Style mixing maps z1,z2z_1, z_2 to w1,w2w_1, w_2 and switches from w1w_1 to w2w_2 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, 424^2 to 828^2: pose, general hair style, face shape and eyeglasses;
  • middle styles, 16216^2 to 32232^2: smaller facial features, hair style, eyes open or closed;
  • fine styles, 64264^2 to 102421024^2: mainly the colour scheme and microstructure.

These layer roles are empirical and overlap; they are not a universal partition of semantics. A separate ww per layer defines the extended space W+\mathcal W^+, 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 ww toward the centre of mass, with 0≤ψ<10\le\psi<1:

wˉ=Ez∼p(z)f(z),w′=wˉ+ψ (w−wˉ).\begin{aligned} \bar w &= \mathbb E_{z \sim p(z)} f(z), \\ w' &= \bar w + \psi\,(w - \bar w) . \end{aligned}

At ψ=0.7\psi=0.7, a code keeps 70% of its distance from the centre. At ψ=0\psi=0, the affected styles all use wˉ\bar w, but noise may still change the output. A nonlinear generator evaluated at the mean code is not the mean image. Negative ψ\psi reflects codes across wˉ\bar w without guaranteeing opposite semantic attributes. Unlike BigGAN’s truncation in zz, 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 dd (Zhang et al., 2018), w1=f(z1)w_1 = f(z_1), w2=f(z2)w_2 = f(z_2), t∼U(0,1)t \sim U(0, 1) and ε=10−4\varepsilon = 10^{-4}, holding noise fixed within each image pair,

lW=E[1ε2 d(g(lerp(w1,w2;t)),g(lerp(w1,w2;t+ε)))].\begin{aligned} l_{\mathcal W} = \mathbb E\Big[\tfrac{1}{\varepsilon^2}\, d\big(&g(\mathrm{lerp}(w_1, w_2; t)),\\ &g(\mathrm{lerp}(w_1, w_2; t + \varepsilon))\big)\Big] . \end{aligned}

In zz-space slerp replaces lerp, since a straight line between two Gaussian samples dips inside their shell. Why divide by ε2\varepsilon^2? 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 ε\varepsilon times their derivative along the path. So d≈ε2×d \approx \varepsilon^2 \times (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 W\mathcal W: a traditional generator with a mapping network in front has separability 6.52 in W\mathcal W 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 64×6464 \times 64 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 ±a\pm a on 15 of them (8 positive, 7 negative) and a spike SS on the 16th. With S=0S=0 and a>0a>0, the normalized pattern has half-gap 1.035 for every aa: the scale aa is lost. With a=1a = 1 and S=4S = 4, 10, 40 the half-gap is 0.737, 0.386, 0.103, so it depends on S/aS/a, and the spike itself becomes 3.85 at S=40S = 40: 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 wijkw_{ijk} for the weight from input channel ii to output channel jj at kernel position kk (not the latent), and sis_i for the style’s scale of input channel ii.

Modulation is a weight change: convolution is linear in each input channel, so scaling channel ii by sis_i and convolving equals convolving with wijk′=si wijkw'_{ijk} = s_i\, w_{ijk}.

Assume pairwise uncorrelated unit-variance inputs. Output jj at one position is ∑i,kwijk′ xi,k\sum_{i,k} w'_{ijk}\, x_{i,k}, and the covariance terms vanish, so

σj=∑i,kwijk′2.\sigma_j = \sqrt{\textstyle\sum_{i,k} w'^2_{ijk}} .

For σj>0\sigma_j>0, dividing output jj by σj\sigma_j removes the effect of ss on the output scale, and the division folds into the weights:

wijk′′=wijk′∑i,kwijk′2+ϵ.w''_{ijk} = \frac{w'_{ijk}}{\sqrt{\sum_{i,k} w'^2_{ijk} + \epsilon}} .

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 ϵ=0\epsilon=0 and keep inputs uncorrelated: one output channel of a 1×11 \times 1 convolution has weights w=(0.6,0.8)w = (0.6, 0.8), so unit-variance inputs give output variance 1.

QuantityValue
style ss(3,0.5)(3, 0.5)
modulated w′w'(1.8,0.4)(1.8, 0.4)
output variance ∑w′2\sum w'^23.24+0.16=3.43.24 + 0.16 = 3.4
σ=3.4\sigma = \sqrt{3.4}1.844
demodulated w′′w''(0.976,0.217)(0.976, 0.217)
output variance0.953+0.047=10.953 + 0.047 = 1

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

Var⁡(aX+bY)=a2+b2+2abρ≈1.212.\operatorname{Var}(aX+bY)=a^2+b^2+2ab\rho\approx1.212.

For uncorrelated unit-variance inputs and positive ϵ\epsilon, the variance is ∑w′2/(∑w′2+ϵ)\sum w'^2/(\sum w'^2+\epsilon), 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 3×33\times3 convolution.

Figure

Demodulation predicts scale; correlation changes the result

Output standard deviations of a modulated convolutionFor six samples, three columns of dots on a logarithmic axis from 0.5 to 20. Amber dots spread from 1.4 to 14.9, blue dots sit on the dashed line at 1, hollow dots range from 0.65 to 1.2.0.51251020output std (log scale)sample 1sample 2sample 3sample 4sample 5sample 6modulation onlydemodulated, i.i.d.demodulated, smooth inputOutput standard deviations of a modulated convolutionFor six samples, three columns of dots on a logarithmic axis from 0.5 to 20. Amber dots spread from 1.4 to 14.9, blue dots sit on the dashed line at 1, hollow dots range from 0.65 to 1.2.0.51251020output std (log scale)123456modulation onlydemodulated, i.i.d.demodulated, smooth inputsample
A 3×3 convolution: eight channels, six styles. Dots are output standard deviations. Amber: modulation, 1.4–14.9; blue: demodulation with independent inputs, 0.93–1.05; hollow: demodulation with spatially correlated inputs, 0.65–1.20. All values are computed from synthetic arrays.

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 W\mathcal W that give good images and squeezes bad ones into small regions of rapid change. They ask that a fixed step in W\mathcal W give a fixed-size change in the image, in every direction:

Lpl=Ew, y(∥Jw⊤y∥2−a)2,\mathcal L_{\mathrm{pl}} = \mathbb E_{w,\, y} \big(\lVert J_w^\top y \rVert_2 - a\big)^2 ,

where Jw=∂g(w)/∂wJ_w=\partial g(w)/\partial w, y∼N(0,I)y\sim\mathcal N(0,I) is a random vector in image space, and aa tracks the global mean length. If aa equalled that mean exactly, the loss would be the variance over both ww and yy. It penalizes local directional variation and differences in mean scale between latent locations. To understand one part, hold ww fixed and examine the singular values of its Jacobian.

Derivation

The Jacobian is never formed: yy is a constant, so by linearity of differentiation component kk of the gradient of the scalar g(w)⋅y=∑iyi gi(w)g(w) \cdot y = \sum_i y_i\, g_i(w) is ∑iyi ∂gi/∂wk=(Jw⊤y)k\sum_i y_i\, \partial g_i / \partial w_k = (J_w^\top y)_k, and one backward pass gives Jw⊤yJ_w^\top y. Take the singular value decomposition Jw⊤=UΣV⊤J_w^\top = U \Sigma V^\top with singular values σ1,…,σL\sigma_1,\dots,\sigma_L, including zeros, for a code of dimension LL; take L=512L=512 in the numerical example. UU preserves lengths, and y~=V⊤y\tilde y = V^\top y is again N(0,I)\mathcal N(0, I), because an affine map sends N(0,I)\mathcal N(0, I) to N(0,V⊤V)=N(0,I)\mathcal N(0, V^\top V) = \mathcal N(0, I). So ℓ2=Q=∑iσi2y~i2\ell^2 = Q = \sum_i \sigma_i^2 \tilde y_i^2. Then:

E Q=∑iσi2,Var⁡Q=2∑iσi4,Var⁡ℓ≈Var⁡Q4 E Q=∑iσi42∑iσi2.\begin{aligned} \mathbb E\, Q &= \textstyle\sum_i \sigma_i^2 , \\ \operatorname{Var} Q &= 2 \textstyle\sum_i \sigma_i^4 , \\ \operatorname{Var} \ell &\approx \frac{\operatorname{Var} Q}{4\, \mathbb E\, Q} = \frac{\sum_i \sigma_i^4}{2 \sum_i \sigma_i^2} . \end{aligned}
  1. The mean uses E y~i2=1\mathbb E\, \tilde y_i^2 = 1 and linearity of expectation.
  2. The variance adds over the independent terms, and Var⁡y~i2=E y~i4−1=2\operatorname{Var} \tilde y_i^2 = \mathbb E\, \tilde y_i^4 - 1 = 2: integration by parts with φ′(y)=−yφ(y)\varphi'(y) = -y\varphi(y) for the standard normal density gives ∫y3⋅yφ(y) dy=∫3y2φ(y) dy=3\int y^3 \cdot y\varphi(y)\,dy = \int 3y^2\varphi(y)\,dy = 3, the boundary terms vanishing.
  3. The last line expands ℓ=Q\ell = \sqrt Q to first order around E Q\mathbb E\, Q, Q≈EQ+(Q−EQ)/(2EQ)\sqrt Q \approx \sqrt{\mathbb E Q} + (Q - \mathbb E Q)/(2\sqrt{\mathbb E Q}), a good approximation when QQ concentrates. From the first two lines, Var⁡Q/(EQ)2=2∑iσi4/(∑iσi2)2≤2max⁡iσi2/∑iσi2\operatorname{Var} Q/(\mathbb E Q)^2 = 2\sum_i \sigma_i^4/(\sum_i \sigma_i^2)^2 \le 2\max_i \sigma_i^2/\sum_i \sigma_i^2: for equal singular values 2/L2/L, a relative spread 2/512≈6%\sqrt{2/512} \approx 6\%, small unless a few σi\sigma_i dominate.

For a fixed ∑iσi2\sum_i \sigma_i^2, the Cauchy–Schwarz inequality (∑iσi2⋅1)2≤L∑iσi4\big(\sum_i \sigma_i^2 \cdot 1\big)^2 \le L \sum_i \sigma_i^4 bounds ∑iσi4\sum_i \sigma_i^4 from below, with equality only when all σi\sigma_i 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,

R1=γ2 Ex∼P∥∇xD(x)∥2.R_1=\tfrac\gamma2\,\mathbb E_{x\sim P}\lVert\nabla_xD(x)\rVert^2.

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, t=n/8t = n/8, and

cos⁡(2π⋅5n8)=cos⁡(2πn−2π⋅3n8)=cos⁡(2π⋅3n8),\begin{aligned} \cos\big(2\pi \cdot 5 \tfrac n8\big) &= \cos\big(2\pi n - 2\pi \cdot 3 \tfrac n8\big) \\ &= \cos\big(2\pi \cdot 3 \tfrac n8\big), \end{aligned}

because cosine has period 2π2\pi and is even. The same ambiguity relates frequencies ff and s−fs-f on a grid sampled at rate ss. The Nyquist–Shannon sampling theorem states that an appropriately regular signal bandlimited strictly below s/2s/2 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 θ=2π⋅3t\theta = 2\pi \cdot 3t, the coefficient of cos⁡2θ\cos 2\theta, frequency 6, in the Fourier series of max⁡(0,cos⁡θ)\max(0, \cos\theta) is

a2=1π∫−π/2π/2cos⁡θcos⁡2θ dθ=12π∫−π/2π/2(cos⁡3θ+cos⁡θ) dθ=12π(−23+2)=23π≈0.21,\begin{aligned} a_2 &= \frac1\pi \int_{-\pi/2}^{\pi/2} \cos\theta \cos 2\theta \, d\theta \\ &= \frac{1}{2\pi} \int_{-\pi/2}^{\pi/2} (\cos 3\theta + \cos\theta)\, d\theta \\ &= \frac{1}{2\pi}\Big(-\frac23 + 2\Big) = \frac{2}{3\pi} \approx 0.21 , \end{aligned}

where the integral shrinks to [−π/2,π/2][-\pi/2, \pi/2] because the ReLU output is zero elsewhere, and the second line is the product-to-sum identity. Frequency 6 folds to 8−6=28 - 6 = 2. The table gives the amplitude ∣x^k∣/N\lvert \hat x_k\rvert/N of the discrete Fourier transform of NN samples: the mean at frequency 0, half the cosine coefficient elsewhere. The continuous output has amplitudes 1/π≈0.3181/\pi \approx 0.318, 0.250.25 at frequency 3 and 12⋅23π≈0.106\tfrac12 \cdot \tfrac{2}{3\pi} \approx 0.106 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, 116\tfrac1{16} 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 ReLU8 per unit8, shifted 116\tfrac1{16}16 per unit16, shifted 132\tfrac1{32}
frequency 0 (the mean)0.3020.3270.3140.320
frequency 2 (the alias)0.1250.0960.0150.006
frequency 30.2500.2500.2500.250

This toy’s grid alignment changes the frequency-2 amplitude by about 0.02930.0293 on the coarse grid and 0.00890.0089 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 2562256^2. Raising temporary upsampling from 2×2\times to 4×4\times 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 102421024^2 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 ww. Editing a photograph first needs a ww 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 W\mathcal W 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 generatorInfoGANStyleGANStyleGAN2StyleGAN3
Where the code entersfirst layerfirst layer, as (z,c)(z, c)every layer, as AdaIN styles of w=f(z)w = f(z)every layer, as weight modulationthe same
Source of controlinput latentan information termthe architecturethe samethe same
Random detailfrom zzfrom zzper-pixel noiseper-pixel noiseno per-pixel noise
Main problem addressed–the code is ignoredcontrol across scalesdroplets, details tied to positionstexture sticking

What you should remember#

  • Independent coordinates passed through separate attribute functions cannot reproduce correlated attributes.
  • InfoGAN: maximize Elog⁡qϕ(c∣G(z,c))+H(c)≤I(c;x)\mathbb E \log q_\phi(c \mid G(z, c)) + H(c) \le I(c; x); the codes are chosen by hand.
  • StyleGAN: w=f(z)w = f(z), 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#