AI Wiki中文/EN

StyleGAN: styles, noise and the limits of control

StyleGAN

Trace a styled generator, differentiate all parameters and distinguish three architecture generations.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

Which input should change a face, and which should change a strand of hair?

A generator can receive one random vector and eventually output an image, but that description hides where different variations enter. In a teaching experiment, we would like to change a later-stage input while preserving an earlier feature map, or change a spatial noise map while holding the style inputs fixed. Those are testable interventions, even before a model learns recognizable objects.

StyleGAN separates a latent mapping network, layer-specific style controls and spatial noise inputs. Karras, Laine and Aila first submitted the work in December2018; the version read here is the March2019 revision for CVPR2019. “Style” names an internal control mechanism, not a promise that every coordinate means an independently editable human attribute. Read GANs, convolution and backpropagation first.

Style-routing differences, noise after truncation and a demodulation counterexample separate three computational effects.
Style-routing differences, noise after truncation and a demodulation counterexample separate three computational effects.

A mapped vector, a learned constant and separate noise

In the original architecture, a normalized latent vector z is mapped to an intermediate vector w by an eight-layer MLP; the paper uses 512 dimensions for both spaces. Learned affine maps convert w to the styles required at individual synthesis layers. Synthesis starts from a learned 4×4×512 constant rather than directly reshaping z into the first feature map. The constant is shared across generated samples but updated during training.

w=M(z),(γℓ,βℓ)=Aℓw+bℓ,h0=C.w=M(z),\qquad (\gamma_\ell,\beta_\ell)=A_\ell w+b_\ell,\qquad h_0=C.

For each sample and feature channel, adaptive instance normalization, or AdaIN, subtracts the spatial mean, divides by spatial standard deviation and applies a style-dependent scale and bias. In the numerically stabilized version used by our example:

uncj=hncj−h‾ncvnc+ε,yncj=γncuncj+βnc,vnc=1L∑j(hncj−h‾nc)2.u_{ncj}=\frac{h_{ncj}-\overline h_{nc}}{\sqrt{v_{nc}+\varepsilon}},\qquad y_{ncj}=\gamma_{nc}u_{ncj}+\beta_{nc},\quad v_{nc}=\frac1L\sum_j(h_{ncj}-\overline h_{nc})^2.

n indexes samples, c channels and j spatial positions; L is the number of positions. These are per-sample, per-channel statistics, not batch statistics. The same style scale applies across the positions of a channel, whereas noise varies by position.

The original generator supplies a single-channel noise image at each layer, broadcast across feature channels with learned per-channel strengths. Holding w fixed does not hold those noise samples fixed:

h~ncj=hncj+αcηnj+bc.\widetilde h_{ncj}=h_{ncj}+\alpha_c\eta_{nj}+b_c.

The paper’s architecture and noise description and the pinned author implementation agree on this distinction. In the default original epilogue, noise and bias precede the activation; instance normalization and style modulation follow it. Our small implementation follows that order, with the simplifications specified below.

Mixing styles and shrinking them answer different questions

Style mixing uses one mapped vector for earlier layers and another after a crossover. In the paper this is also a training regularizer: it discourages a layer from relying on the same style code being used everywhere. The rule describes a routing intervention; whether it corresponds to pose, hair or texture depends on what a trained model has learned.

wℓ={M(zA)ℓ<k,M(zB)ℓ≥k.w_\ell=\begin{cases}M(z_A)&\ell<k,\\M(z_B)&\ell\ge k.\end{cases}

Truncation instead shrinks mapped vectors toward their mean under the latent sampling distribution. The original paper discusses a quality–variation tradeoff in AppendixB. In practice that mean can be estimated from mapped reference samples:

w‾=Ez[M(z)],w′=w‾+ψ(w−w‾),0≤ψ≤1.\overline w=\mathbb E_z[M(z)],\qquad w'=\overline w+\psi(w-\overline w),\quad 0\le\psi\le1.

At ψ=1 nothing changes. At ψ=0 all styles collapse to the chosen center, but independent spatial noise can still change the output. Our program takes an explicit fixed anchor to isolate this calculation; it does not claim that the arbitrary demonstration anchor estimates a trained model’s population mean.

AdaIN itself has a detail worth checking. With positive ε, the output variance is slightly below the square of its style scale whenever the input variance is positive:

Var⁡j(y)=γ2vv+ε.\operatorname{Var}_j(y)=\gamma^2\frac{v}{v+\varepsilon}.

For a constant channel v=0, the normalized feature is zero and the output is β. To backpropagate, write r=dy·γ and σ=√(v+ε). Centering and variance normalization both contribute:

∂L∂h=r−r‾−u ru‾σ,∂L∂γ=∑j∂L∂yjuj,∂L∂β=∑j∂L∂yj.\frac{\partial L}{\partial h}=\frac{r-\overline r-u\,\overline{ru}}{\sigma},\qquad \frac{\partial L}{\partial\gamma}=\sum_j\frac{\partial L}{\partial y_j}u_j,\qquad \frac{\partial L}{\partial\beta}=\sum_j\frac{\partial L}{\partial y_j}.

These are the derivatives used in the complete toy generator, including gradients of its learned constant, mapping, convolution and both style routes.

What changed in the next versions?

VersionMechanism covered hereEvidence boundary
StyleGAN, 2018 preprint / CVPR2019Mapped styles, AdaIN, learned constant, noise and mixingOriginal architecture and selected method sections; no image benchmark reproduction
StyleGAN2, 2019 preprint / 2020 revisionReplace activation-based normalization with a redesigned block using weight demodulationFigure2 and Equations1–3 plus fixed author code; not the entire training recipe
StyleGAN3, 2021Address aliasing and the attachment of detail to image coordinates through a continuous-signal/equivariance viewAuthor abstract only; no full architecture or implementation claim

StyleGAN2 first modulates convolution weights by the style for each input channel, then normalizes each output channel’s weight vector. With i an input channel, o an output channel and k a kernel position:

Woik′=siWoik,Woik′′=Woik′∑i,k(Woik′)2+ε.W'_{oik}=s_iW_{oik},\qquad W''_{oik}=\frac{W'_{oik}}{\sqrt{\sum_{i,k}(W'_{oik})^2+\varepsilon}}.

The variance calculation assumes independent unit-variance input activations. It uses weight statistics, not the measured variance of the current activation map; correlated inputs need not give unit output variance. The fixed implementation makes the input/output channel roles explicit. StyleGAN3’s abstract identifies a different problem, aliasing; merely changing AdaIN to weight demodulation does not implement StyleGAN3.

A generator small enough to differentiate every parameter

Save as stylegan.py, using Python3.12 and NumPy1.26.4. This is an original one-dimensional signal generator with two channels and lengths four and eight. It has one two-dimensional mapping layer, two style affine maps, a learned constant, nearest-neighbor upsampling, a circular three-tap convolution, noise strengths and a linear readout: 61 trainable parameters in total.

It is deliberately smaller than the paper: one mapping layer instead of eight, signals instead of images, circular boundaries and ε=10⁻⁵. Its affine style scales use biases initialized near one; there is no extra fixed addition of one on every forward pass. Two latent arrays make the early/late routing visible. The separate demodulated_weights helper illustrates a StyleGAN2 calculation but is not used to silently turn this StyleGAN1-style generator into StyleGAN2.

For N samples, C channels, L positions and kernel width K, a dense same-width convolution costs O(NLC²K); feature storage is O(NLC), plus the parameters and cached layers. This program fixes C=2 and K=3, so its time and activation memory scale linearly with N. Actual image networks need many more layers, channels, pixels, training data and a discriminator.

"""Original 61-parameter styled 1D generator, not an image GAN reproduction.

Two channels, resolutions 4 and 8, explicit backpropagation. The optional fit
is supervised synthetic regression; it has no discriminator or GAN objective.
"""
import json
import numpy as np

EPS = 1e-5


def unpack(p):
    p = np.asarray(p, float)
    if p.shape != (61,) or not np.all(np.isfinite(p)) or np.max(np.abs(p)) > 10:
        raise ValueError('Expected 61 finite parameters of magnitude <= 10.')
    return (p[:4].reshape(2, 2), p[4:6], p[6:14].reshape(2, 4),
            p[14:22].reshape(2, 4), p[22:26], p[26:34].reshape(2, 4), p[34:38],
            p[38:50].reshape(2, 2, 3), p[50:54].reshape(2, 2),
            p[54:58].reshape(2, 2), p[58:60], p[60])


def initial(seed=7):
    p = np.random.default_rng(seed).normal(0, .25, 61)
    p[6:14] = np.array([-.8, -.1, .3, .9, .6, -.5, .7, -.2])
    p[22:24] += 1
    p[34:36] += 1
    return p


def noise(seed, n):
    rng = np.random.default_rng(seed)
    return (rng.normal(size=(n, 1, 4)), rng.normal(size=(n, 1, 8)))


def adain(x, style):
    centered = x-x.mean(axis=2, keepdims=True)
    std = np.sqrt(np.mean(centered*centered, axis=2, keepdims=True)+EPS)
    unit = centered/std
    return unit*style[:, :2, None]+style[:, 2:, None], (unit, std, style)


def adain_backward(dy, cache):
    unit, std, style = cache
    du = dy*style[:, :2, None]
    dx = (du-du.mean(axis=2, keepdims=True)-unit*np.mean(du*unit, axis=2, keepdims=True))/std
    ds = np.concatenate([np.sum(dy*unit, axis=2), dy.sum(axis=2)], axis=1)
    return dx, ds


def forward(p, za, zb, noises, psi=1., anchor=(0., 0.)):
    mapping, bias, constant, wa, ba, wb, bb, kernel, gains, biases, readout, intercept = unpack(p)
    za, zb, anchor = np.asarray(za, float), np.asarray(zb, float), np.asarray(anchor, float)
    if za.ndim != 2 or za.shape[1] != 2 or zb.shape != za.shape or not 1 <= len(za) <= 256:
        raise ValueError('Expected matching nonempty Nx2 latent arrays, N <= 256.')
    if anchor.shape != (2,) or not np.isfinite(psi) or not 0 <= psi <= 1:
        raise ValueError('Expected finite two-vector anchor and psi in [0,1].')
    if len(noises) != 2:
        raise ValueError('Two noise maps are required.')
    noises = tuple(np.asarray(v, float) for v in noises)
    values = (za, zb, anchor, *noises)
    if not all(np.all(np.isfinite(v)) and np.max(np.abs(v)) <= 20 for v in values):
        raise ValueError('Inputs must be finite, magnitude <= 20.')
    if noises[0].shape != (len(za), 1, 4) or noises[1].shape != (len(za), 1, 8):
        raise ValueError('Noise maps must be Nx1x4 and Nx1x8.')
    blocks, maps = [], []
    h = np.broadcast_to(constant, (len(za), 2, 4)).copy()
    first = None
    for layer, (z, weight, offset) in enumerate(((za, wa, ba), (zb, wb, bb))):
        pre = z@mapping+bias
        w = anchor+psi*(np.where(pre >= 0, pre, .2*pre)-anchor)
        maps.append((z, pre, w))
        if layer:
            up = np.repeat(h, 2, axis=2)
            h = sum(np.einsum('oi,nil->nol', kernel[:, :, k], np.roll(up, k-1, axis=2)) for k in range(3))
        hpre = h+gains[layer][None, :, None]*noises[layer]+biases[layer][None, :, None]
        activated = np.where(hpre >= 0, hpre, .2*hpre)
        h, acache = adain(activated, w@weight+offset)
        blocks.append((hpre, acache))
        if layer == 0:
            first = h.copy()
    output = np.einsum('c,ncl->nl', readout, h)+intercept
    return output, {'maps': maps, 'blocks': blocks, 'first': first, 'last': h,
                    'up': up, 'noise': noises, 'psi': psi}


def objective(p, za, zb, noises, target):
    output, cache = forward(p, za, zb, noises)
    target = np.asarray(target, float)
    if target.shape != output.shape or not np.all(np.isfinite(target)):
        raise ValueError('Target must match the finite Nx8 output.')
    delta = output-target
    loss = .5*np.mean(delta*delta)
    dy = delta/delta.size
    grad = np.zeros(61)
    mapping, _, _, wa, _, wb, _, kernel, _, _, readout, _ = unpack(p)
    grad[58:60] = np.einsum('nl,ncl->c', dy, cache['last'])
    grad[60] = dy.sum()
    dh = dy[:, None, :]*readout[None, :, None]
    for layer in (1, 0):
        hpre, acache = cache['blocks'][layer]
        z, pre, w = cache['maps'][layer]
        dh, ds = adain_backward(dh, acache)
        dh *= np.where(hpre >= 0, 1., .2)
        grad[50+2*layer:52+2*layer] = np.sum(dh*cache['noise'][layer], axis=(0, 2))
        grad[54+2*layer:56+2*layer] = dh.sum(axis=(0, 2))
        start = 14+12*layer
        grad[start:start+8] = (w.T@ds).ravel()
        grad[start+8:start+12] = ds.sum(axis=0)
        dw = ds@(wb if layer else wa).T
        dpre = dw*np.where(pre >= 0, 1., .2)
        grad[:4] += (z.T@dpre).ravel()
        grad[4:6] += dpre.sum(axis=0)
        if layer:
            up = cache['up']
            dk = np.stack([np.einsum('nol,nil->oi', dh, np.roll(up, k-1, axis=2)) for k in range(3)], axis=2)
            grad[38:50] = dk.ravel()
            dup = sum(np.roll(np.einsum('oi,nol->nil', kernel[:, :, k], dh), 1-k, axis=2) for k in range(3))
            dh = dup.reshape(len(za), 2, 4, 2).sum(axis=3)
        else:
            grad[6:14] = dh.sum(axis=0).ravel()
    return float(loss), grad


def demodulated_weights(weight, style):
    weight, style = np.asarray(weight, float), np.asarray(style, float)
    if weight.shape != (2, 2, 3) or style.shape != (2,) or not all(np.all(np.isfinite(v)) and np.max(np.abs(v)) <= 20 for v in (weight, style)):
        raise ValueError('Expected finite 2x2x3 weights and 2-vector styles of magnitude <= 20.')
    modulated = weight*style[None, :, None]
    return modulated/np.sqrt(np.sum(modulated**2, axis=(1, 2), keepdims=True)+EPS)


def demo():
    rng = np.random.default_rng(1205)
    za, zb = rng.normal(size=(8, 2)), rng.normal(size=(8, 2))
    fixed = noise(10, 8)
    teacher = initial(19)
    target = forward(teacher, za, zb, fixed)[0]
    p = initial()
    history = [objective(p, za, zb, fixed, target)[0]]
    for step in range(120):
        p -= .04*objective(p, za, zb, fixed, target)[1]
        if (step+1) % 30 == 0:
            history.append(objective(p, za, zb, fixed, target)[0])
    ordinary, a = forward(p, za, za, fixed)
    mixed, b = forward(p, za, zb, fixed)
    anchor = np.array([.1, -.2])
    zero_a = forward(p, za, za, fixed, psi=0, anchor=anchor)[0]
    zero_b = forward(p, zb, zb, fixed, psi=0, anchor=anchor)[0]
    return {'supervised_mse_half': history, 'mix_first_stage_error': float(np.max(np.abs(a['first']-b['first']))),
            'mix_output_change': float(np.linalg.norm(ordinary-mixed)),
            'psi_zero_fixed_noise_error': float(np.max(np.abs(zero_a-zero_b))),
            'noise_change': float(np.linalg.norm(zero_a-forward(p, za, za, noise(11, 8), psi=0, anchor=anchor)[0]))}


if __name__ == '__main__':
    print(json.dumps(demo(), indent=2))

Three interventions and one explicitly supervised fit

First, use zA at both stages, then replace only the second-stage vector with zB. With identical noise, the first feature map is exactly unchanged while the final signal changes. Second, set ψ=0: changing latent arrays no longer matters with fixed noise. Third, resample noise: the output can change even at ψ=0. Setting all noise gains to zero removes that dependence instead.

For a learning demonstration, eight fixed pairs of latent vectors and fixed noise maps are fed through a known teacher generator. A second generator fits those target signals for 120 gradient steps with learning rate .04. Half mean-squared error decreases from .155377924918 to .009645992213. This is supervised synthetic regression, with no discriminator and no adversarial objective. It demonstrates trainable paths, not GAN image generation.

All 61 parameter gradients are checked by centered finite differences away from activation kinks. Separate checks verify AdaIN’s ε-dependent variance and style-routing invariants. For the demodulation helper, six perfectly correlated unit-variance inputs and all-one weights produce variance approximately six, not one. Under independent unit-variance inputs the same normalized weight vector gives variance close to one. The counterexample tests the assumption behind the formula.

A control route does not guarantee a semantic control

The architecture offers places to inject variation; the dataset, losses and optimization determine what they learn. A direction that appears to change one facial attribute may also change others. Noise and styles have different computational routes, but their learned effects are not guaranteed to be statistically independent or cleanly separated at every scale.

Truncation changes the sampling distribution and can reduce variation. A more typical-looking output does not by itself establish greater coverage or fairness. This program uses no face images, pretrained weights or human-attribute labels, and cannot measure such properties.

The NVIDIA repositories are public reference implementations with noncommercial license restrictions at the cited commits; public availability is not unrestricted permission to reuse their code or assets. Our formulas, NumPy example and synthetic experiments are independently organized. Full image training, perceptual evaluation, inversion of real photographs and editing reliability require separate implementations and evidence.

Separate route, statistic and learned meaning

  1. Routing. Only the second-stage style changes while noise stays fixed. Must the first feature map change? Answer: No. The second-stage style has no path backward into the first stage during the forward calculation. Later outputs can change; gradients during training are a different question.
  2. Hand calculation. An input channel has variance three, style scale two and ε=one. What is its output variance? What if the channel is constant? Answer: Four times 3/(3+1)=3. For a constant channel it is zero and every output position equals β. The commonly stated value γ² is exact only when the stabilizer is absent and normalization is defined.
  3. Counterexample. Does ψ=0 guarantee the same output on every call? Answer: Only if the other stochastic inputs are fixed too. It fixes the styles at the anchor but does not fix newly sampled noise. Zero noise gains would make that noise irrelevant.
  4. Method choice. Can the supplied fit establish StyleGAN2 image quality or prove that styles correspond to independent attributes? Answer: Neither. It fits short teacher signals with supervised MSE and mainly uses a StyleGAN1-style block. Weight demodulation is a separate small calculation; image quality and semantic independence need their own data, models and evaluations.

Reading the sources

Read the original architecture and truncation sections before comparing StyleGAN2 Figure2 and its weight equations. The StyleGAN3 account here is limited to its abstract. The version table records different reading depths rather than implying a full review of every generation.

Make a prediction, then check

Does zero truncation remove all output randomness?

Choose one answer

Learning objectives

  • Separate mapped styles, constants and spatial noise.
  • Derive AdaIN and its gradients.
  • Test mixing and truncation interventions.
  • State demodulation assumptions and version limits.

Prerequisites & connections

Explore related knowledge →

References

  1. A Style-Based Generator Architecture for Generative Adversarial Networks (v3)
    Tero Karras; Samuli Laine; Timo Aila · 2019
  2. Analyzing and Improving the Image Quality of StyleGAN (v2)
    Tero Karras; Samuli Laine; Miika Aittala; Janne Hellsten; Jaakko Lehtinen; Timo Aila · 2020
  3. Alias-Free Generative Adversarial Networks (v4 abstract)
    Tero Karras; Miika Aittala; Samuli Laine; Erik Härkönen; Janne Hellsten; Jaakko Lehtinen; Timo Aila · 2021
  4. StyleGAN network implementation at 1e0d5c7
    NVIDIA and StyleGAN contributors · 2021
  5. StyleGAN2 modulated convolution at bf0fe0b
    NVIDIA and StyleGAN2 contributors · 2021

Version1 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Codex · 2026-09-20 · Single AI author checked selected StyleGAN1 architecture/mixing/truncation, StyleGAN2 weight demodulation, fixed author code and StyleGAN3 abstract only. Eight paired equations and four exercises; original61-parameter 1D generator and all gradients. Fit is supervised teacher regression, not GAN training or semantic-control evidence.

  • Checked all61 gradients, AdaIN epsilon/constant channel, fixed-noise style mixing, zero truncation versus random noise, demodulation iid assumption/correlated counterexample. Version and noncommercial-reference limits explicit.
  • Four SVG variants bind each actual bilingual program. Group passed14 numerical/geometry checks and18 responsive cases at390/768/1536 with four fallback fonts; six final representative screenshots actually viewed. Coupling-axis and title corrections and explicit style difference plot preserve original evidence. Full article acceptance is separate.

Source locations checked:

Related topics

No matches. Try a synonym or acronym.

0 results shown

Wrap the whole query in double quotes for a phrase match.