AI Logic

Normalization

Weight Normalization

Updated:

What Weight Normalization does to the weights. The left shows a weight matrix, normalized per weight vector (one row) of each output neuron. The center shows the weight vector split into a direction v/‖v‖ and a length g, with w lying on a circle of radius g; the right shows that the gradient is projected perpendicular to w, so ‖v‖ grows with every update. The bottom shows the computation that builds w from v and g and multiplies it by the input x

What is Weight Normalization?

Weight Normalization represents a neuron's weight vector w\mathbf{w} as a scalar gg for its length and a vector v\mathbf{v} for its direction, and learns these two instead. Salimans and Kingma (OpenAI) proposed it in 2016.

Whereas batch normalization normalizes activations with the mini-batch mean and variance, weight normalization changes how the weights themselves are represented. Because it uses no statistics of the input data, it has the following advantages.

  • Samples in a batch do not depend on each other. It is independent of batch size and works as is in recurrent models such as LSTM.
  • It adds no noise. Batch normalization injects noise into the gradient through fluctuations in per-mini-batch statistics, but weight normalization is a deterministic computation. It suits noise-sensitive tasks such as reinforcement learning and generative models.
  • It is cheap. It needs no extra memory, and the extra computation is negligible.

In the figure at the top of the article, the left shows which part of the weight matrix is normalized (one row per output neuron), the center shows the split into length and direction, and the right shows the direction of the gradient and how ∄v∄\lVert\mathbf{v}\rVert grows.

How it is computed

A neuron takes a weighted sum of kk inputs x\mathbf{x}, adds a bias bb, and passes the result through an activation function Ļ•\phi (Eq. (1) of the paper). y=Ļ•(wā‹…x+b)y = \phi(\mathbf{w} \cdot \mathbf{x} + b)

Weight normalization computes the following in order.

  1. Express the weights with v\mathbf{v} and gg. v\mathbf{v} is a kk-dimensional vector and gg is a scalar; both are learnable parameters (Eq. (2) of the paper). w=g∄v∄v\mathbf{w} = \frac{g}{\lVert\mathbf{v}\rVert} \mathbf{v} This makes ∄w∄=g\lVert\mathbf{w}\rVert = g regardless of the value of v\mathbf{v}. The direction is set by v\mathbf{v} alone, and the length by gg alone.
  2. The forward pass uses the resulting w\mathbf{w} as usual: y=Ļ•(wā‹…x+b)y = \phi(\mathbf{w} \cdot \mathbf{x} + b).
  3. Update v\mathbf{v} and gg directly by gradient descent. Their gradients follow from the ordinary weight gradient āˆ‡wL\nabla_{\mathbf{w}} L (Eq. (3) of the paper). āˆ‡gL=āˆ‡wLā‹…v∄v∄,āˆ‡vL=g∄vāˆ„āˆ‡wLāˆ’gāˆ‡gL∄v∄2v\nabla_g L = \frac{\nabla_{\mathbf{w}} L \cdot \mathbf{v}}{\lVert\mathbf{v}\rVert}, \qquad \nabla_{\mathbf{v}} L = \frac{g}{\lVert\mathbf{v}\rVert} \nabla_{\mathbf{w}} L - \frac{g \nabla_g L}{\lVert\mathbf{v}\rVert^2} \mathbf{v}

The idea of normalizing weight vectors existed before, but earlier methods updated w\mathbf{w} directly and rescaled its length after each update. Weight normalization differs in that it reparameterizes the weights as v\mathbf{v} and gg from the start and learns those two.

In a convolutional layer, the whole filter of one output channel (input channels Ɨ kernel height Ɨ width) is treated as one weight vector, and each output channel gets its own gg.

The paper also tried learning gg as g=esg = e^s through its logarithm ss, but test performance was nearly unchanged and training was slightly slower. Normally gg is learned directly.

Why training becomes faster

The paper explains this by rewriting the gradient āˆ‡vL\nabla_{\mathbf{v}} L as follows (Eq. (4) of the paper). āˆ‡vL=g∄v∄Mwāˆ‡wL,Mw=Iāˆ’ww⊤∄w∄2\nabla_{\mathbf{v}} L = \frac{g}{\lVert\mathbf{v}\rVert} M_{\mathbf{w}} \nabla_{\mathbf{w}} L, \qquad M_{\mathbf{w}} = I - \frac{\mathbf{w}\mathbf{w}^\top}{\lVert\mathbf{w}\rVert^2}

MwM_{\mathbf{w}} is a projection matrix that removes the component along w\mathbf{w}. The equation shows that weight normalization does two things.

  • It scales the gradient by g/∄v∄g / \lVert\mathbf{v}\rVert.
  • It removes the component along the current weight direction from the gradient. Noise that was riding on that component disappears along with it. The paper notes that w\mathbf{w} is often close to the dominant eigenvector of the gradient covariance matrix, so removing it brings the covariance matrix closer to the identity, which may speed up training.

Another important effect is that ∄v∄\lVert\mathbf{v}\rVert grows naturally and adjusts the effective learning rate. Because the update Ī”v\Delta\mathbf{v} of v\mathbf{v} is perpendicular to w\mathbf{w} (and thus to v\mathbf{v}), the Pythagorean theorem says the length grows with every update. With āˆ„Ī”v∄/∄v∄=c\lVert\Delta\mathbf{v}\rVert / \lVert\mathbf{v}\rVert = c, ∄vā€²āˆ„=1+c2ā€‰āˆ„vāˆ„ā‰„āˆ„v∄\lVert\mathbf{v}'\rVert = \sqrt{1 + c^2}\, \lVert\mathbf{v}\rVert \geq \lVert\mathbf{v}\rVert

If the learning rate is too large and updates are big, ∄v∄\lVert\mathbf{v}\rVert grows quickly and the gradient scale g/∄v∄g / \lVert\mathbf{v}\rVert shrinks. Once updates become small, 1+c2ā‰ˆ1\sqrt{1 + c^2} \approx 1 and the growth stops. For this reason, the paper reports that networks with weight normalization train well over a wide range of learning rates.

This property holds exactly for gradient descent without momentum. It does not hold exactly for methods with per-parameter learning rates such as Adam or when using momentum, but the paper observed the same tendency in its experiments.

Relation to batch normalization: in a single-layer network whose inputs are whitened (independent components with mean 0 and variance 1), the pre-activation t=vā‹…xt = \mathbf{v} \cdot \mathbf{x} has mean 0 and standard deviation ∄v∄\lVert\mathbf{v}\rVert. In that case, normalizing the pre-activation with batch normalization is equivalent to normalizing the weights with weight normalization. The paper describes weight normalization as a "cheaper and less noisy approximation" of batch normalization.

Initialization and mean-only batch normalization

Batch normalization also keeps the scale of each layer's output constant, which makes training robust to poor initialization. Weight normalization lacks this effect, so the paper also proposes data-dependent initialization (Section 3 of the paper).

  1. Sample each component of v\mathbf{v} from a normal distribution with mean 0 and standard deviation 0.05.
  2. Feed one mini-batch through and, for each neuron, compute the mini-batch mean μ[t]\mu[t] and standard deviation σ[t]\sigma[t] of t=vā‹…x∄v∄t = \frac{\mathbf{v} \cdot \mathbf{x}}{\lVert\mathbf{v}\rVert}.
  3. Set gg and bb as follows (Eq. (6) of the paper). The pre-activation values for the first mini-batch then have mean 0 and variance 1. g←1σ[t],bā†āˆ’Ī¼[t]σ[t]g \leftarrow \frac{1}{\sigma[t]}, \qquad b \leftarrow \frac{-\mu[t]}{\sigma[t]}

This initialization is done only once, before training. See the article on data-dependent initialization for details. It cannot be applied to recurrent models such as RNNs and LSTMs, however, which must rely on standard initialization.

Weight normalization also largely decouples the scale of activations from v\mathbf{v}, but the mean still depends on v\mathbf{v}. The paper therefore also proposes combining it with mean-only batch normalization, which subtracts the mini-batch mean but does not divide by the standard deviation (Eq. (7) of the paper). At inference time, a moving average of the training-time means is used. With the mean alone, the paper explains, there is no spiky noise from estimating the variance, and the noise is gentle and close to Gaussian.

Experimental results

Image classification: the same CNN was trained on CIFAR-10 without data augmentation, changing only how its weights are represented (Adam, 200 epochs, mini-batch size 100). Test error rates are as follows (table in Figure 2 of the paper).

MethodTest error
Standard weights8.43%
Mean-only batch normalization8.52%
Weight normalization8.46%
Batch normalization8.05%
Weight normalization + mean-only batch normalization7.31%

In terms of training speed, both weight normalization and batch normalization progressed much faster than standard weights. Batch normalization made slightly more progress per epoch early in training, but its computation was about 16% slower than standard weights, whereas weight normalization was not noticeably slower. In final error rate, weight normalization alone was on par with standard weights, and the best result came from combining it with mean-only batch normalization.

Generative models: in a convolutional VAE (MNIST and CIFAR-10), weight normalization reduced the variance across random seeds and converged to better values (Figure 3 of the paper). In DRAW, a generative model built from LSTMs (MNIST), adding weight normalization to the weights alone, while keeping the initialization and learning rate tuned for the original model, made convergence much faster (Figure 4 of the paper).

Reinforcement learning: DQN was trained on Atari games. The paper states that batch normalization could not be run at realistic mini-batch sizes, because noise in the mini-batch statistics destabilized training. The best evaluation scores are as follows (table in Figure 6 of the paper).

GameStandard weightsWeight normalization
Breakout410403
Enduro1,2501,448
Seaquest7,1887,375
Space Invaders1,7792,179

Scores improved in three of the four games.

Practical caveats

Weight normalization alone does not equalize the output scale of each layer. Unlike batch normalization, it does not correct the scale of activations every time, so with poor initialization the output scale drifts from layer to layer. The paper recommends using it together with data-dependent initialization. PyTorch's weight_norm does not perform this initialization automatically (right after registration, it starts from the same values as the original weights).

In PyTorch, use torch.nn.utils.parametrizations.weight_norm. The older torch.nn.utils.weight_norm is deprecated. In the new function, gg is named parametrizations.weight.original0 and v\mathbf{v} is named parametrizations.weight.original1 (weight_g and weight_v in the old function). Code that refers to these names directly must be rewritten.

Also keep the following in mind.

  • dim determines the unit over which the length is normalized. The default dim=0 is per output (per row in nn.Linear, per output channel in nn.Conv2d), which matches the paper. With dim=None, the whole weight tensor shares a single length.
  • The computation is the same during training and inference. Weight normalization uses no data statistics, so the output is the same under model.train() and model.eval() (when combined with mean-only batch normalization, only that part uses a moving average at inference).
  • In image classification accuracy, it may fall short of batch normalization. On CIFAR-10 in the paper, weight normalization alone reached 8.46%, short of batch normalization (8.05%). In the group normalization paper, ResNet-50 on ImageNet had an error rate of 28.2%, higher than batch normalization (23.6%).
  • In GAN discriminators, it has been pointed out to lower the rank of weight matrices. The Spectral Normalization paper (Miyato et al. 2018) argues that weight normalization, which equalizes the length of each row, tends to favor low-rank weights that use only a few features, reducing the features the discriminator uses.

Comparison with other normalization methods

AspectWeight normalizationBatch normalizationLayer normalizationSpectral Normalization
What is normalizedWeights (length of each output's weight vector set to gg)Activations (per channel, statistics over the batch)Activations (per sample, statistics over all features)Weights (largest singular value of the matrix set to 1)
Data statisticsNot usedUsedUsedNot used
Sensitivity to batch sizeNoYesNoNo
Training vs. inferenceSame computationComputation differs (moving average)Same computationSame values (power iteration stopped at inference)
Extra computationNegligibleStatistics per activationStatistics per activationOne power iteration
Main usesRNNs, reinforcement learning, generative modelsImage classification with CNNsTransformers, RNNsGAN discriminators

A rough guide for choosing:

  • To avoid noise from batch statistics (reinforcement learning, RNNs, generative models with small batches): weight normalization, combined with data-dependent initialization.
  • Image classification with CNNs and sufficiently large batches: batch normalization.
  • Transformers or RNNs where activation scales should be equalized every time: layer normalization.
  • To stabilize GAN discriminators (to bound the Lipschitz constant): Spectral Normalization.

PyTorch example

Show code
python
import torch
import torch.nn as nn
from torch.nn.utils.parametrizations import weight_norm
from torch.nn.utils import parametrize

# Add weight normalization to Linear. dim=0: a length g per output (per row)
m = weight_norm(nn.Linear(20, 40), name="weight", dim=0)
g = m.parametrizations.weight.original0   # length g     shape [40, 1]
v = m.parametrizations.weight.original1   # direction v  shape [40, 20]
print(g.shape, v.shape)

# Right after registration, the values equal the original weights (starts with g = ‖v‖)
w = m.weight                               # w = g Ā· v / ‖v‖ is computed on every access
print(torch.allclose(w.norm(dim=1, keepdim=True), g))   # True: ‖w‖ = g

# Computation exactly as in Eq. (2) of the paper
w_manual = g * v / v.norm(dim=1, keepdim=True)
print(torch.allclose(w_manual, w))          # True

# In convolutions, each output channel has one g
conv = weight_norm(nn.Conv2d(3, 16, kernel_size=3))
print(conv.parametrizations.weight.original0.shape)   # [16, 1, 1, 1]

# Data-dependent initialization from Section 3 of the paper (Linear example). Done once before training
@torch.no_grad()
def data_dependent_init(layer, x):
    v = layer.parametrizations.weight.original1
    v.normal_(0, 0.05)                                   # v: mean 0, standard deviation 0.05
    t = x @ (v / v.norm(dim=1, keepdim=True)).T          # t = vĀ·x / ‖v‖
    mu, sigma = t.mean(dim=0), t.std(dim=0)
    layer.parametrizations.weight.original0.copy_((1 / sigma).unsqueeze(1))   # g ← 1/σ[t]
    layer.bias.copy_(-mu / sigma)                                            # b ← āˆ’Ī¼[t]/σ[t]

x = torch.randn(256, 20)
data_dependent_init(m, x)
y = m(x)
print(y.mean(dim=0).abs().max() < 1e-4, y.std(dim=0).mean())   # mean ā‰ˆ 0, standard deviation ā‰ˆ 1

# After training, convert back to an ordinary weight
parametrize.remove_parametrizations(m, "weight")
print(type(m.weight))   # Parameter (the value of w is kept as is)

FAQ

Q. Can weight normalization and batch normalization be used together?
A.

Yes. In the paper, combining weight normalization with "mean-only batch normalization" (subtracting only the mini-batch mean, without dividing by the standard deviation) gave the lowest error rate on CIFAR-10 (7.31%). The roles are split: weight normalization handles the scale, and mean-only batch normalization handles the mean.

Q. How should the learning rate be chosen?
A.

With weight normalization, ‖v‖ grows and automatically lowers the effective learning rate, so the paper reports that training works over a wider range of learning rates than with standard weights. In the paper's CIFAR-10 experiments, the Adam learning rate was chosen from 0.0003 to 0.01, and the best was 0.003 with weight normalization and 0.0003 with standard weights. In DQN as well, 0.0003 worked well with weight normalization and 0.0001 with standard weights. Starting from a somewhat larger learning rate than for standard weights is reasonable.

Q. Does model.eval() change its behavior?
A.

No. Weight normalization only changes how the weights are represented and uses no data statistics. To speed up inference, remove_parametrizations can also convert it back to an ordinary weight with w fixed.

References

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