AI Logic

Normalization

Spectral Normalization

Updated:

What Spectral Normalization does to the weights. Left: the entire weight matrix of a layer is divided by a single number σ(W). Center: the weight matrix W stretches the unit circle into an ellipse, with maximum stretch σ(W). Right: with W/σ(W), the maximum stretch becomes 1 and the ellipse fits inside the unit circle. Below: the computation flow of finding σ(W) by power iteration and dividing the weights

What Is Spectral Normalization?

Spectral Normalization divides the weight matrix WW of each layer of a neural network by its largest singular value σ(W)\sigma(W). Miyato et al. proposed it in 2018 to stabilize the training of the GAN discriminator.

The largest singular value represents the maximum factor by which the layer can stretch an input vector. If every layer's maximum stretch is set to 1, small differences in the input are not greatly amplified in the output of the whole network either (the Lipschitz constant is bounded by 1).

In GAN training, if the discriminator becomes too strong or becomes a function that changes abruptly with respect to its input, useful gradients do not reach the generator, and training stalls or becomes unstable. Spectral Normalization mitigates this by restricting the discriminator to smooth functions. Its features are as follows.

  • There are almost no hyperparameters to tune. In the paper, it worked well without tuning its only hyperparameter, the Lipschitz constant.
  • It is cheap and easy to incorporate. A single round of power iteration approximates the largest singular value.
  • It does not use data statistics. Like Weight Normalization, it normalizes weights rather than activations.

The figure at the top of the article shows, on the left, the range being normalized (the entire weight matrix of a layer); in the center, how the weight matrix stretches the unit circle into an ellipse, with maximum stretch σ(W)\sigma(W); and on the right, the result after taking W/σ(W)W / \sigma(W).

Computation Steps

The spectral norm of a matrix AA is the maximum length to which AA can stretch a vector of length 1, and equals the largest singular value of AA (Eq. (6) in the paper). σ(A)=max⁡h≠0∥Ah∥2∥h∥2=max⁡∥h∥2≤1∥Ah∥2\sigma(A) = \max_{\mathbf{h} \neq 0} \frac{\lVert A\mathbf{h} \rVert_2}{\lVert \mathbf{h} \rVert_2} = \max_{\lVert \mathbf{h} \rVert_2 \leq 1} \lVert A\mathbf{h} \rVert_2

Spectral Normalization divides the weight matrix by this value (Eq. (8) in the paper). WˉSN(W)=Wσ(W)\bar{W}_{\mathrm{SN}}(W) = \frac{W}{\sigma(W)}

Since performing a singular value decomposition every time is expensive, the paper approximates σ(W)\sigma(W) with power iteration. For each layer, the following is computed in order (Algorithm 1 in the paper).

  1. Prepare a vector u~\tilde{\mathbf{u}}. At the start of training it is initialized randomly for each layer, and thereafter the one obtained in the previous update is reused.
  2. Run one round of power iteration. (Eqs. (20) and (21) in the paper) v~←W⊤u~∥W⊤u~∥2,u~←Wv~∥Wv~∥2\tilde{\mathbf{v}} \leftarrow \frac{W^\top \tilde{\mathbf{u}}}{\lVert W^\top \tilde{\mathbf{u}} \rVert_2}, \qquad \tilde{\mathbf{u}} \leftarrow \frac{W \tilde{\mathbf{v}}}{\lVert W \tilde{\mathbf{v}} \rVert_2}
  3. Approximate the largest singular value and divide the weights. (Eq. (22) in the paper) σ(W)≈u~⊤Wv~,WˉSN=Wσ(W)\sigma(W) \approx \tilde{\mathbf{u}}^\top W \tilde{\mathbf{v}}, \qquad \bar{W}_{\mathrm{SN}} = \frac{W}{\sigma(W)}
  4. Run the forward pass with the divided weights WˉSN\bar{W}_{\mathrm{SN}}, and update the original WW with the gradient.

Because WW changes only slightly in each update, its largest singular value also changes only slightly. The paper therefore reports that, by reusing u~\tilde{\mathbf{u}}, a single round of power iteration was sufficient.

The weights of a convolutional layer W∈Rdout×din×h×wW \in \mathbb{R}^{d_{\mathrm{out}} \times d_{\mathrm{in}} \times h \times w} are treated as a 2D matrix of size dout×(dinhw)d_{\mathrm{out}} \times (d_{\mathrm{in}} h w).

Why It Stabilizes the Discriminator

The Lipschitz constant ∥f∥Lip\lVert f \rVert_{\mathrm{Lip}} of a function ff is an upper bound on how much the output can change relative to a change in the input. ∥f(x)−f(x′)∥≤∥f∥Lip⋅∥x−x′∥\lVert f(\mathbf{x}) - f(\mathbf{x}') \rVert \leq \lVert f \rVert_{\mathrm{Lip}} \cdot \lVert \mathbf{x} - \mathbf{x}' \rVert

The Lipschitz constant of a linear layer h↦Wh\mathbf{h} \mapsto W\mathbf{h} is σ(W)\sigma(W). If the activation functions have Lipschitz constant 1, as with ReLU and Leaky ReLU, the Lipschitz constant of the whole stacked network is bounded above by the product of the σ\sigma of each layer (Eq. (7) in the paper). ∥f∥Lip≤∏l=1L+1σ(Wl)\lVert f \rVert_{\mathrm{Lip}} \leq \prod_{l=1}^{L+1} \sigma(W^l)

Setting σ(WˉSN)=1\sigma(\bar{W}_{\mathrm{SN}}) = 1 for every layer makes the Lipschitz constant of the whole discriminator at most 1.

As an analogy, it is like making each layer a magnifying glass that enlarges its input by at most 1×. No matter how many are stacked, the image is never enlarged beyond its original size.

Differences from other methods: The paper points out the following in comparison with other methods with the same goal (Section 3 of the paper).

  • Difference from Weight Normalization: Weight Normalization equalizes the length of each row of the weight matrix. This is equivalent to fixing the sum of squared singular values, and trying to keep the input large favors near-rank-1 matrices that concentrate the singular values into one. The discriminator may end up using only a few features. Spectral Normalization fixes only the largest singular value, so it is not constrained in rank and can use many features.
  • Difference from orthogonal regularization: Adding ∥W⊤W−I∥F2\lVert W^\top W - I \rVert_F^2 to the loss pushes all singular values toward 1, erasing the information in the singular values. Spectral Normalization only shrinks the whole matrix so the maximum becomes 1, preserving the ratios between singular values.
  • Difference from gradient penalty (WGAN-GP): The gradient penalty pushes the gradient norm toward 1 at points between real and generated samples, so its effect changes as the generator's distribution changes. It also requires computing gradients of gradients, which is expensive. The paper states that Spectral Normalization constrains the weights directly, so it depends less on how batches are chosen and is cheaper to compute.

Experimental Results

The paper compares normalization and regularization methods for the discriminator on image generation with CIFAR-10 and STL-10. Evaluation uses the Inception Score (higher is better) and FID (lower is better). During training, the spectral norm of each spectrally normalized layer stayed around 1–1.05.

The results with the best settings are as follows (Table 2 in the paper, standard CNN, standard GAN loss). For comparison, the learnable scale γ\gamma is removed from Weight Normalization, Batch Normalization, and Layer Normalization.

Discriminator methodIS (CIFAR-10)IS (STL-10)FID (CIFAR-10)FID (STL-10)
Weight clipping6.417.5742.664.2
WGAN-GP6.688.4240.255.1
Batch Normalization6.27—56.3—
Layer Normalization7.197.6133.975.6
Weight Normalization6.847.1634.773.4
Orthogonal regularization7.408.5629.046.7
Spectral Normalization7.428.2829.353.1

On CIFAR-10, Spectral Normalization was the best; on STL-10, it was second to orthogonal regularization. With the hinge loss, it improved further to IS 7.58 and FID 25.5 on CIFAR-10, and with a ResNet architecture and hinge loss it achieved IS 8.22 and FID 21.7 on CIFAR-10, and IS 9.10 and FID 40.1 on STL-10.

Other results are as follows.

  • Robustness to settings: Spectral Normalization remained relatively stable even with larger Adam learning rates and momentum coefficients. WGAN-GP failed to train well with high learning rates and momentum (Figures 1 and 2 in the paper).
  • Singular values of the weights: In discriminators trained with weight clipping or Weight Normalization, the singular values of the early layers concentrated in a few components (lower rank), whereas with Spectral Normalization they were more widely distributed (Figure 3 in the paper).
  • Computation time: On CIFAR-10, it took about 110–120% of the computation time of Weight Normalization, considerably faster than WGAN-GP.
  • ImageNet: For a 1000-class conditional GAN (128 × 128 pixels), no normalization and Layer Normalization collapsed early in training and could not produce meaningful images, whereas Spectral Normalization produced images with an Inception Score of 21.1.

Practical Considerations

PyTorch's spectral_norm runs one round of power iteration every time the weight is accessed in training mode (model.train()), and uses the stored u~\tilde{\mathbf{u}} and v~\tilde{\mathbf{v}} as is in evaluation mode (model.eval()). Running inference or evaluation in training mode updates the estimate each time. Switch to eval() before generation or evaluation.

For convolutional layers, the divisor is the largest singular value of the weights reshaped into a 2D matrix. This does not match the spectral norm of the convolution as a linear map itself. The paper also notes that the actual value depends on stride and padding and differs by a fixed constant factor. It is not a method that makes the Lipschitz constant exactly 1.

Also keep the following in mind.

  • The paper applies it to the discriminator. In the paper's experiments, the generator is trained with Batch Normalization, and Spectral Normalization is applied only to the discriminator.
  • Use PyTorch's newer function. torch.nn.utils.parametrizations.spectral_norm is a rewrite of the older torch.nn.utils.spectral_norm. n_power_iterations (default 1) is the number of power iterations, and dim is the axis kept when forming the matrix, defaulting to 0 (1 for ConvTranspose).
  • Adding a learnable scale breaks the Lipschitz constraint. In the paper's comparison, γ\gamma was removed from the other normalizations as well so as not to break the constraint.

Comparison with Other Methods

AspectSpectral NormalizationWeight NormalizationGradient penalty (WGAN-GP)Orthogonal regularization
What is constrainedLargest singular value of the weight matrix to 1Length of each weight row to ggNorm of the input gradient at sample pointsWeight matrix toward orthogonality
HowDivides the weights (reparameterization)Reparameterizes the weightsAdds a term to the lossAdds a term to the loss
Effect on singular valuesOnly the maximum set to 1; ratios preservedRank tends to dropNot directly affectedAll pushed toward 1
Extra computationOne round of power iterationNegligibleGradient of gradient (one extra forward/backward pass)Loss term
CIFAR-10 in the paper (IS / FID)7.42 / 29.36.84 / 34.76.68 / 40.27.40 / 29.0

Rough guidelines for choosing:

  • Stabilizing a GAN discriminator with little tuning: Spectral Normalization.
  • Speeding up training without needing a Lipschitz constraint (RNNs, reinforcement learning, etc.): Weight Normalization.
  • Equalizing the scale of activations: Batch Normalization or Layer Normalization. Spectral Normalization does not equalize the distribution of activations itself.

PyTorch example

Show code
python
import torch
import torch.nn as nn
from torch.nn.utils.parametrizations import spectral_norm

# Apply Spectral Normalization to each discriminator layer (discriminator only, as in the paper's experiments)
D = nn.Sequential(
    spectral_norm(nn.Conv2d(3, 64, 3, stride=1, padding=1)),
    nn.LeakyReLU(0.1),
    spectral_norm(nn.Conv2d(64, 128, 4, stride=2, padding=1)),
    nn.LeakyReLU(0.1),
    nn.Flatten(),
    spectral_norm(nn.Linear(128 * 16 * 16, 1)),
)

x = torch.randn(8, 3, 32, 32)
D.train()
for _ in range(5):
    _ = D(x)          # in training mode, one round of power iteration runs each time the weight is accessed

# The largest singular value of the divided weight is close to 1 (a conv is treated as a [d_out, d_in*h*w] matrix)
w = D[2].weight                                   # normalized weight
print(torch.linalg.matrix_norm(w.reshape(w.shape[0], -1), ord=2))   # close to 1

D.eval()              # use eval() for inference/evaluation: stored u, v are used as is and the estimate is not updated
with torch.no_grad():
    score = D(x)

# Computation following Algorithm 1 of the paper (linear layer weight W: [d_out, d_in])
def spectral_normalize(W, u, n_iter=1, eps=1e-12):
    for _ in range(n_iter):
        v = W.T @ u; v = v / (v.norm() + eps)     # Eq. (20)
        u = W @ v;   u = u / (u.norm() + eps)     # Eq. (21)
    sigma = u @ W @ v                             # Eq. (22): σ(W) ≈ uᵀ W v
    return W / sigma, u.detach()                  # u is reused in the next update

W = torch.randn(64, 128)
u = torch.randn(64); u = u / u.norm()
for _ in range(20):                               # one round per update; converges as u is reused
    W_sn, u = spectral_normalize(W, u)
print(torch.linalg.matrix_norm(W_sn, ord=2))      # ≈ 1

FAQ

Q. Should Spectral Normalization also be applied to the generator?
A.

In this paper, the goal is to bound the discriminator's Lipschitz constant; the generator uses Batch Normalization and Spectral Normalization is not applied to it. Applying it only to the discriminator first is the usage that follows the paper.

Q. Is a single round of power iteration really enough?
A.

In the paper, one round was sufficient. The weights change only slightly with each update, so by reusing the vector u from the previous update, the estimate catches up with the largest singular value over successive updates. PyTorch's n_power_iterations also defaults to 1.

Q. How does it differ from Weight Normalization?
A.

Weight Normalization equalizes the length of each row of the weights, while Spectral Normalization sets the largest singular value of the whole matrix to 1. The paper points out that because the former fixes the sum of squared singular values, it tends to produce low-rank weights in GAN discriminators. The latter fixes only the maximum, so many features can be used. Moreover, Weight Normalization aims to speed up training and does not bound the Lipschitz constant.

References

  1. T. Miyato, T. Kataoka, M. Koyama, and Y. Yoshida, "Spectral Normalization for Generative Adversarial Networks," ICLR, 2018.
  2. T. Salimans and D. P. Kingma, "Weight Normalization: A Simple Reparameterization to Accelerate Training of Deep Neural Networks," NIPS, 2016.
  3. PyTorch Documentation, "torch.nn.utils.parametrizations.spectral_norm."