StyleGAN is a model that redesigns the GAN generator: instead of feeding the random latent into the first layer, it uses "styles" derived from the latent to modulate the strength of the feature maps at every layer. The generator starts from a learned constant and, at each convolutional layer, uses a style to reset the mean and variance of the feature maps (AdaIN). It also adds noise at each layer to produce fine stochastic variation such as the flow of individual hairs.
It was proposed by Karras, Laine, and Aila at NVIDIA in 2018 in the paper "A Style-Based Generator Architecture for Generative Adversarial Networks" (CVPR 2019).
While GAN image quality and resolution had been improving rapidly, the generator itself remained a black box. It was unclear which part of the latent controlled which aspect of the image, making controlled editing difficult. StyleGAN brought ideas from style transfer research into the generator and showed the following.
Higher image quality: FID on face images improved by nearly 20% over the traditional generator.
Coarse attributes and fine variation are separated: For faces, styles handle pose and identity, while noise handles freckles and the exact placement of hairs, without any supervision.
Control at each resolution: Styles at low-resolution layers determine face pose and shape, while styles at high-resolution layers determine color and fine details. Styles from two images can be mixed per resolution.
A more tractable latent space: Because the random latent is first mapped to another space, changes in attributes become more linear.
The discriminator and loss function are unchanged. Only the generator architecture differs, so it can be combined independently with loss improvements such as WGAN. The paper also released a new face dataset, FFHQ (Flickr-Faces-HQ, 70,000 images at 1024×1024).
As an everyday analogy, a traditional generator is like a painter who is handed a blueprint (the random latent) once at the start and interprets it alone. StyleGAN is like a painter who starts from a blank canvas and receives separate instructions (styles) at each stage: rough composition, facial features, and coloring.
Architecture
The StyleGAN generator consists of two parts: a mapping network and a synthesis network (left side of the figure at the top of the article; Figure 1 (b) of the paper).
Mapping network
The input latent z (512 dimensions) is normalized and mapped by an 8-layer fully connected network (multilayer perceptron) f to an intermediate latentw=f(z) (512 dimensions). The space of z is written Z and the space of w is written W.
Synthesis network
The synthesis network g has no input layer that receives the random latent; it starts generating from a learned constant (4×4×512). Image content enters only through the following two paths.
Styles: At each layer, a learned affine transform (A in the figure) maps w to a style y=(ys,yb). The dimension of y is twice the number of feature maps (channels) in that layer.
Noise: At each layer, a single-channel image of uncorrelated Gaussian noise is prepared. It is multiplied by learned per-channel scaling factors (B in the figure) and added to the convolution output.
Within one layer, computation proceeds in this order.
Apply a 3×3 convolution (the first layer at each resolution upsamples first). Only the first 4×4 layer starts from the constant instead of a convolution.
Scale the noise image and add it (before the nonlinearity).
Apply AdaIN using the style.
AdaIN (adaptive instance normalization) is defined as follows (Eq. 1).
AdaIN(xi,y)=ys,iσ(xi)xi−μ(xi)+yb,i
xi is the i-th feature map, and μ(xi) and σ(xi) are its mean and standard deviation. Each feature map is normalized to zero mean and unit variance (the same as Instance Normalization), and then the style components reapply a scale ys,i and a bias yb,i (right side of the figure at the top of the article).
There are two layers per resolution, from 4×4 to 1024×1024, for 18 layers in total. The output of the last layer is converted to an RGB image by a separate 1×1 convolution. The generator has 26.2 million parameters, only slightly more than the traditional generator (23.1 million).
Style mixing (during training)
A given percentage of training images are generated from two latents. z1,z2 are passed through the mapping network to get w1,w2, and at a randomly chosen crossover point in the synthesis network, layers before it use the style from w1 and layers after it use the style from w2. This prevents the network from assuming that adjacent styles are correlated (Section 3.1).
Truncation (during generation)
The generator cannot learn sparsely represented regions of the training data well. So at generation time, w is sometimes pulled toward the mean wˉ=Ez[f(z)] (Appendix B).
w′=wˉ+ψ(w−wˉ),ψ<1
Smaller ψ raises average image quality and reduces diversity. As ψ→0, every image approaches FFHQ's "average face". Truncation can also be applied only to low-resolution layers so that fine details are unaffected.
The training setup is inherited from Progressive GAN (a GAN trained by progressively adding layers from low to high resolution). The discriminator architecture, Adam settings, and exponential moving average of generator weights are the same. The loss is WGAN-GP for CelebA-HQ and the non-saturating GAN loss with R1 regularization (γ=10) for FFHQ. All layers use Leaky ReLU (α=0.2) and equalized learning rate, and the mapping network's learning rate is reduced by a factor of 100 (Appendix C).
Why Attributes Can Be Controlled Separately
StyleGAN's properties are explained by three mechanisms: AdaIN, noise, and the intermediate latent space W.
Each style affects only one convolution
AdaIN first normalizes the feature map to zero mean and unit variance and then applies the style's scale and bias. The new statistics (mean and variance) change which features the next convolution weights more heavily, but because normalization erases the previous statistics, they are overwritten by the next AdaIN. As a result, each style's effect is confined to one convolution. Training with style mixing strengthens this localization further, so that each resolution comes to control different things (Figure 3 of the paper).
Styles swapped
What is inherited
Coarse (42–82)
Pose, general hairstyle, face shape, eyeglasses
Middle (162–322)
Smaller facial features, hairstyle, eyes open or closed
Fine (642–10242)
Mainly color scheme and microstructure
Noise handles only fine variation
Human portraits contain aspects that can be random as long as they follow the right distribution, such as the exact placement of individual hairs, stubble, freckles, and skin pores. A traditional generator receives randomness only through its input layer, so it has to create this "randomness" from earlier activations, which consumes network capacity and can produce repetitive patterns in generated images. In StyleGAN, fresh noise is available at every layer, and the network uses it.
Changing the noise left identity and pose unchanged and altered only things like hair placement (Figure 4). Removing the noise produced flat, painterly images; noise at coarse layers created large-scale curling of hair, while noise at fine layers created finer curls and skin pores (Figure 5).
Because a style applies the same scale and bias to an entire feature map, it can consistently change global properties such as pose and lighting. Noise is independent per pixel, so it suits local variation. If the network tried to control pose with noise, it would make inconsistent decisions at different locations and be caught by the discriminator. Thus the division of labor between the two is learned without supervision (Section 3.3).
The intermediate latent space W is less warped
Because z is drawn from a fixed distribution, the shape of Z must match the frequencies of attribute combinations in the training data. For example, if the training data contains no "men with long hair", the mapping from Z to attributes becomes curved so that this combination is never sampled from Z (Figure 6). W need not follow a fixed distribution, and the mapping network can undo this curvature, so attribute changes become closer to linear.
The paper proposed two metrics to measure this.
Perceptual path length: When moving in small steps between two points in latent space, it sums how abruptly the image changes, measured with a distance based on VGG features. Shorter means a smoother latent space.
Linear separability: Generated images are labeled with 40 attributes (such as gender), and a linear SVM separates the latent points; how cleanly they separate is measured by conditional entropy. Smaller means clearer attribute directions.
The paper itself calls it "quite remarkable" that the synthesis network can generate images when its only input is the styles. After adding the mapping network and styles, feeding the random latent into the first convolutional layer no longer helped, so the input layer was removed and generation starts from a constant.
Experimental Results
The paper applied changes one at a time to the traditional generator (Progressive GAN) and measured FID (lower is better) on CelebA-HQ and FFHQ (Table 1). FID is computed from 50,000 randomly selected training images, and the lowest value during training is reported. Truncation is not used.
D: + Remove traditional input layer (start from constant)
5.07
4.88
E: + Noise inputs
5.06
4.42
F: + Style mixing (StyleGAN)
5.17
4.40
Compared with the traditional generator (B), the style-based generator (E) improved FID by nearly 20%.
Effect of style mixing
On FFHQ, the paper mixed 1–4 latents at generation time and measured how much FID degraded (Table 2).
Mixing ratio during training
1 latent
2 latents
3 latents
4 latents
0% (config E)
4.42
8.22
12.88
17.41
50%
4.41
6.10
8.71
11.61
90% (config F)
4.40
5.11
6.88
9.03
100%
4.83
5.17
6.63
8.40
Mixing during training makes quality degrade less when mixing at generation time.
Effect of the mapping network
On FFHQ, the paper compared different mapping network depths (Table 4; path length is over full paths, and separability is linear separability; lower is better for all).
Generator
Mapping layers
Space measured
FID
Path length
Separability
Traditional (B)
0
Z
5.25
412.0
10.78
Traditional
8
Z
4.87
896.2
170.29
Traditional
8
W
4.87
324.5
6.52
Style-based
0
Z
5.06
283.5
9.88
Style-based
1
W
4.60
219.9
6.81
Style-based
2
W
4.43
217.8
6.25
Style-based (F)
8
W
4.40
234.0
3.79
The mapping network helped both the traditional and the style-based generator, and deeper was generally better. Adding a mapping network in front of the traditional generator made separability in Z much worse while improving it in W. This shows that the space into which the random latent is fed directly can become arbitrarily entangled.
Other datasets
The paper also trained on LSUN with the same setup (Appendix E). FID was 2.65 for bedrooms (256×256), 3.27 for cars (512×384), and 8.53 for cats (256×256). For bedrooms, coarse styles controlled the camera viewpoint, middle styles the furniture, and fine styles the details of color and materials.
Practical Considerations
Keep the following points in mind when using StyleGAN.
Training is computationally expensive: Training in the paper took about one week on an NVIDIA DGX-1 (8 Tesla V100 GPUs). It is a large model that generates 1024×1024 images.
Lower the mapping network's learning rate: Deep mapping networks became unstable with high learning rates. The paper reduces the mapping network's learning rate by a factor of 100.
Truncation trades quality for diversity: Setting ψ<1 raises average quality but reduces diversity. All FIDs in the paper are computed without truncation, which is used only for presenting figures and videos.
Initialization rules: Weights of convolutional, fully connected, and affine transform layers are initialized from N(0,1), the synthesis network's constant to 1, and biases and noise scaling factors to 0, except that the bias of ys is initialized to 1 (Appendix C).
Better FID and a smoother latent space do not necessarily go together. In Appendix D of the paper, perceptual path length gradually increased (more entanglement) while FID kept falling during training. The paper also reports that training with style mixing slightly warps W (in Table 3, path length is longer with 50% and 90% mixing than with none).
Comparison with Other Methods
The traditional GAN generators and the StyleGAN generator compare as follows.
Mapped to w by the mapping network and fed to all layers via AdaIN
Start of synthesis
Tensor projected from z
Tensor built from z
Learned constant 4×4×512
Fine variation
Indirectly derived from the latent
Indirectly derived from the latent
Per-layer noise inputs
Normalization
Batch normalization
Pixelwise feature normalization
AdaIN
Maximum resolution (in the paper)
64×64
1024×1024
1024×1024
Per-resolution control
Not possible
Not possible
Possible through style mixing
Rough guidelines for choosing:
Generating high-resolution, high-quality images: The StyleGAN architecture is well suited. It has been trained not only on faces but also on bedrooms, cars, and cats.
Editing image attributes (pose, hairstyle, color, etc.): Because the intermediate latent space W is close to linear, attribute directions are easy to find, and per-resolution style mixing is also available.
Trying out GAN mechanics with limited compute: Start with a simple architecture such as DCGAN.
Improving training stability: StyleGAN leaves the loss unchanged, so combine it with loss and regularization techniques such as WGAN-family losses or R1 regularization.
Training by likelihood, or also wanting a mapping into the latent space: VAE or the normalizing flow Glow are candidates.
PyTorch example
▶Show code
python
import torch
import torch.nn as nn
import torch.nn.functional as F
"""
A small implementation of the core of the StyleGAN generator by Karras et al. (2018) (Figure 1 (b), Eq. 1, Section 3.1, Appendices B and C)
- Mapping network: normalize z → 8 fully connected layers (Leaky ReLU 0.2) → w (512 dimensions)
- Synthesis network: start from a learned 4×4×512 constant; each layer does conv → noise (B) → activation → AdaIN (A)
- Style mixing (during training) and truncation in W (during generation)
PyTorch has no built-in StyleGAN. Equalized learning rate, bilinear filtering, and the Progressive GAN discriminator and loss are omitted
(the official implementation is NVlabs/stylegan on GitHub, in TensorFlow)
"""
LATENT = 512
class MappingNetwork(nn.Module):
def __init__(self, depth=8):
super().__init__()
layers = []
for _ in range(depth):
layers += [nn.Linear(LATENT, LATENT), nn.LeakyReLU(0.2)]
self.net = nn.Sequential(*layers)
def forward(self, z):
z = z * torch.rsqrt(z.pow(2).mean(dim=1, keepdim=True) + 1e-8) # normalize the input (Normalize)
return self.net(z)
class AdaIN(nn.Module):
"""AdaIN(x_i, y) = y_s,i * (x_i − μ(x_i)) / σ(x_i) + y_b,i (Eq. 1)"""
def __init__(self, channels):
super().__init__()
self.norm = nn.InstanceNorm2d(channels, affine=False) # normalize each feature map separately
self.affine = nn.Linear(LATENT, channels * 2) # A: w → style y = (y_s, y_b)
nn.init.zeros_(self.affine.bias)
self.affine.bias.data[:channels] = 1.0 # initialize the bias of y_s to 1 (Appendix C)
def forward(self, x, w):
y_s, y_b = self.affine(w)[:, :, None, None].chunk(2, dim=1)
return y_s * self.norm(x) + y_b
class NoiseInput(nn.Module):
"""Add a single-channel Gaussian noise image scaled by per-channel factors (B)"""
def __init__(self, channels):
super().__init__()
self.scale = nn.Parameter(torch.zeros(1, channels, 1, 1)) # scaling factors initialized to 0 (Appendix C)
def forward(self, x):
noise = torch.randn(x.size(0), 1, x.size(2), x.size(3), device=x.device)
return x + self.scale * noise
class StyleLayer(nn.Module):
def __init__(self, cin, cout, upsample=False):
super().__init__()
self.upsample = upsample
self.conv = nn.Conv2d(cin, cout, 3, padding=1)
self.noise, self.act, self.adain = NoiseInput(cout), nn.LeakyReLU(0.2), AdaIN(cout)
def forward(self, x, w):
if self.upsample:
x = F.interpolate(x, scale_factor=2, mode="bilinear", align_corners=False)
return self.adain(self.act(self.noise(self.conv(x))), w) # noise is added before the nonlinearity
class SynthesisNetwork(nn.Module):
def __init__(self, channels=(512, 512, 256, 128)): # 4×4 → 8×8 → 16×16 → 32×32 (kept small for the example)
super().__init__()
c0 = channels[0]
self.const = nn.Parameter(torch.ones(1, c0, 4, 4)) # learned constant (initialized to 1)
self.noise0, self.act0, self.adain0 = NoiseInput(c0), nn.LeakyReLU(0.2), AdaIN(c0)
self.layers = nn.ModuleList([StyleLayer(c0, c0)]) # second layer at 4×4
for cin, cout in zip(channels[:-1], channels[1:]): # two layers per resolution
self.layers += [StyleLayer(cin, cout, upsample=True), StyleLayer(cout, cout)]
self.to_rgb = nn.Conv2d(channels[-1], 3, 1) # 1×1 convolution to RGB
self.num_styles = 1 + len(self.layers)
def forward(self, ws):
"""ws: [batch, number of layers, 512]. The w used at each layer (kept per layer for style mixing)"""
x = self.const.expand(ws.size(0), -1, -1, -1)
# The paper's figure does not show where the nonlinearity goes after the constant; here an activation is applied to match the other layers
x = self.adain0(self.act0(self.noise0(x)), ws[:, 0])
for i, layer in enumerate(self.layers, start=1):
x = layer(x, ws[:, i])
return self.to_rgb(x)
class StyleGenerator(nn.Module):
def __init__(self):
super().__init__()
self.mapping, self.synthesis = MappingNetwork(), SynthesisNetwork()
def forward(self, z1, z2=None, mix_prob=0.9, psi=1.0, w_avg=None):
n = self.synthesis.num_styles
w1 = self.mapping(z1)
ws = w1[:, None].repeat(1, n, 1)
if self.training and z2 is not None and torch.rand(()) < mix_prob:
# Style mixing: from a random crossover layer onward, use the style from w2 (90% for FFHQ in the paper)
cut = int(torch.randint(1, n, ()))
ws[:, cut:] = self.mapping(z2)[:, None]
if psi < 1.0 and w_avg is not None:
ws = w_avg + psi * (ws - w_avg) # truncation in W: w' = w̄ + ψ(w − w̄)
return self.synthesis(ws)
G = StyleGenerator()
# During training: G.train(). Reduce the mapping network's learning rate by a factor of 100 (Appendix C)
lr = 1e-3
opt = torch.optim.Adam([
{"params": G.synthesis.parameters(), "lr": lr},
{"params": G.mapping.parameters(), "lr": lr * 0.01},
], betas=(0.0, 0.99)) # betas are values chosen for this example
fake = G(torch.randn(4, LATENT), torch.randn(4, LATENT)) # [4, 3, 32, 32]
# During generation: compute the mean of w and truncate
G.eval()
with torch.no_grad():
w_avg = G.mapping(torch.randn(10000, LATENT)).mean(dim=0)
images = G(torch.randn(8, LATENT), psi=0.7, w_avg=w_avg)
FAQ
Q. What is a "style" in StyleGAN?
A.
It is the value y=(ys,yb) obtained by mapping the intermediate latent w through a per-layer affine transform. AdaIN normalizes the layer's feature maps and then reapplies ys as a scale and yb as a bias. The name comes from style transfer research, where the mean and variance of feature maps were known to represent an image's "style". In StyleGAN, styles are computed from w rather than from an example image.
Q. Why map the random latent z to w with a mapping network instead of using z directly?
A.
Because z is drawn from a fixed distribution, the mapping from z to attributes becomes curved to match the frequencies of attribute combinations in the training data. w need not follow a fixed distribution, so it can form a space where attribute changes are more linear. In the paper, adding the mapping network improved FID, perceptual path length, and linear separability, and 8 layers gave the best FID.
Q. What does the noise fed into the generator do?
A.
It produces details that can be random, such as the exact placement of hairs and skin texture. At each layer, a fresh noise image is scaled by per-channel factors and added to the convolution output. Changing the noise leaves identity and pose unchanged and alters only the details. Removing the noise produced flat, painterly images.