AI Logic

Weight Initialization

Orthogonal Initialization

Updated:

A graph of the singular values of the whole network's mapping in descending order (log-scale vertical axis, 64Γ—64 matrices). With orthogonal initialization, all singular values are 1 for 1, 5, and 30 layers alike. With Gaussian initialization of standard deviation 1/√N, they spread around 1 for 1 layer, fall to a minimum of about 2.4Γ—10^βˆ’7 for 5 layers, and to a minimum of about 3.8Γ—10^βˆ’36 for 30 layers

Background and overview

Orthogonal initialization is a weight initialization method that sets each layer's weight matrix WW to a random orthogonal matrix satisfying W⊀W=IW^\top W = I. An orthogonal matrix only rotates (and reflects) vectors and does not change the length of a vector in any direction. As a result, no matter how many layers are stacked, signals and gradients are transmitted with the same factor in every direction. It was introduced in 2013 by Andrew Saxe, James McClelland, and Surya Ganguli in a paper analyzing how deep linear networks learn (arXiv:1312.6120).

The earlier Gaussian initialization, which draws each entry from a distribution with mean 0 and standard deviation 1/N1/\sqrt{N} (NN is the layer width), also preserves the length of a typical vector on average. However, the paper showed that in deep linear networks, training takes longer as layers are added with this initialization, whereas with orthogonal initialization the training time barely changes as layers are added. The difference is between "preserving length on average" and "preserving length in every direction".

The figure at the top plots, in descending order, the singular values (how much a vector in that direction is stretched or shrunk) of the overall mapping of a network with stacked layers. With orthogonal initialization they are all 1 no matter how many layers are stacked, but with Gaussian initialization they spread out as layers are added, and at 30 layers most directions are squashed by a factor smaller than 10βˆ’1010^{-10}.

Theory (constructing orthogonal matrices and their properties)

This section walks through the content of Sections 3 and 4 of the paper.

  1. Construct a random orthogonal matrix: Make an NΓ—NN \times N matrix from a zero-mean Gaussian and take the orthogonal matrix QQ from its QR decomposition (Appendix C of the paper). Use it as each layer's weights.
  2. Consider the whole linear network: A network of NlN_l layers without activation functions can be written as a single matrix product (Eq. (19)). Wtot=∏i=1Nlβˆ’1W(i+1,i)W_{tot} = \prod_{i=1}^{N_l - 1} W^{(i+1,i)}
  3. A product of orthogonal matrices is orthogonal: If every layer is orthogonal, WtotW_{tot} is also orthogonal and all its singular values are 1. Signals and errors in every direction are transmitted without changing length.
  4. A product of Gaussian matrices stretches and shrinks greatly depending on direction: A Gaussian matrix with standard deviation 1/N1/\sqrt{N} satisfies ⟨v⊀W⊀Wv⟩=v⊀v\langle v^\top W^\top W v \rangle = v^\top v, so it preserves vector length on average. But even a single matrix has spread-out singular values (the Marchenko–Pastur distribution), and multiplying many of them widens this spread: only a tiny fraction of directions are greatly stretched while most are squashed to nearly 0.
  5. Aim for dynamical isometry: The paper names the state in which as many singular values as possible of the product of Jacobians applied to errors in backpropagation lie in a narrow range around 1 "dynamical isometry", and proposes it as a condition for fast training. The key point is that preserving length on average is not enough (it is a necessary but not sufficient condition).
  6. For nonlinear networks, match the gain gg: With an activation function Ο•\phi in between, consider the following form (Eq. (20)). xil+1=βˆ‘jg Wij(l+1,l) ϕ(xjl)x^{l+1}_i = \sum_j g\, W^{(l+1,l)}_{ij}\, \phi(x^l_j) WW is a random orthogonal matrix and gg is a gain. With Ο•=tanh⁑\phi = \tanh, if gg is below the critical value gc=1g_c = 1, the signal vanishes layer by layer; if it is above, the signal propagates without vanishing. The paper calls this boundary the "edge of chaos".

An orthogonal matrix is a transformation that "only rotates and does not stretch or shrink". Just as rotating a map does not change its scale, distances are preserved no matter how many times it is rotated. A Gaussian matrix includes, on top of rotation, stretching and shrinking that varies by direction, so after many repetitions some directions stretch extremely while others shrink extremely.

Why training becomes faster

The reason is that in backpropagation, every component of the error reaches the input-side layers with the same magnitude.

With Gaussian initialization, the overall mapping of the network takes the form "greatly stretch a few directions and strongly shrink the rest". The components of the backpropagated error in the shrinking directions are almost 0 by the time they reach the input-side layers, so nearly no gradient arises for those directions. The paper explains that this is why deep networks take long to train with Gaussian initialization. With orthogonal initialization all singular values are 1, so this imbalance does not occur.

According to the paper's analysis, a deep linear network started from a special initial state in which the "coupling modes" of each layer's weights grow independently of one another can learn, no matter how many layers are added, with only a finite delay compared with a shallow network. Unsupervised layer-wise pre-training (training one layer at a time with an autoencoder and using the result as initial values) finds initial values close to this state when conditions are right. Random orthogonal initialization achieves similar speed without pre-training.

For nonlinear networks, the paper numerically examined the distribution of singular values of the input-to-output Jacobian for a 100-layer Tanh network with N=1000N = 1000 (Figure 7).

  • g<1g < 1 (below the edge of chaos): The singular values become very small, and gradients vanish.
  • g=1g = 1 (the edge of chaos): Even through 100 layers, a constant fraction of singular values cluster in a range around 1, and dynamical isometry is approximately preserved. This property remained even when the input variance was made larger than 1 to enter Tanh's nonlinear range.
  • g>1g > 1: The singular values become skewed, but the skew at g=1.1g = 1.1 was much smaller than for a linear network with Gaussian initialization. The paper suggests that just beyond the edge of chaos may be well suited to training.

Experimental results

The paper trained deep linear networks on MNIST and compared, for each number of layers, the number of iterations until the training error fell below a fixed threshold (training time) (Figure 6A). The setup was as follows.

ItemSetting
ModelLinear network without activation functions (hidden width 1000)
Number of layers3–100 (15 settings)
Training methodFull-batch gradient descent. For each depth, the fastest of 20 learning rates from 10βˆ’410^{-4} to 10βˆ’710^{-7} is chosen
Initializations comparedScaled random initialization of Glorot and Bengio (Xavier initialization; preserves error length in backpropagation), layer-wise unsupervised pre-training, random orthogonal matrices

The results were as follows (the paper shows them as graphs; there is no table of numbers).

  • Scaled random initialization: Training time grew as layers were added. The paper's main text analyzes this as Gaussian initialization with standard deviation 1/N1/\sqrt{N} (the caption of Figure 6A says uniform distribution).
  • Orthogonal initialization: Training time stayed nearly constant as layers were added, matching pre-training so closely that the two are indistinguishable on the graph.
  • Depth at which the difference appears: The paper says the difference is small at around 6 layers, as commonly used in large-scale applications, and becomes large at greater depths.

Practical caveats

The theory holds for linear networks and for activation functions that saturate symmetrically around 0, such as Tanh. The orthogonal matrix itself preserves length, but the activation functions in between shrink or stretch the signal, so the gain gain must be matched to the activation function. The paper suggests that for Tanh, a gain around 1 (the edge of chaos) or slightly above is good.

Keep the following points in mind as well.

  • The gain of PyTorch's orthogonal_: nn.init.orthogonal_(w, gain=1) multiplies the orthogonal matrix by gain. PyTorch's nn.init.calculate_gain("tanh") returns 5/3, but that is the value PyTorch recommends as a guide for preserving variance and comes from a different idea than the paper's gg (where the edge of chaos is g=1g = 1). Which is better depends on the model, so choose by looking at training stability.
  • When the matrix is not square: For layers whose input and output widths differ, the result is a "semi-orthogonal matrix" in which whichever of the rows or columns is fewer are mutually orthogonal. PyTorch's orthogonal_ also produces this form.
  • Convolutional layers are flattened first: PyTorch's orthogonal_ treats weights with more than 2 dimensions (output channels Γ— input channels Γ— kΓ—kk \times k) as an "output channels Γ— (input channels Γ— k2k^2)" matrix by merging the trailing dimensions, and orthogonalizes that. This does not make the mapping as a convolution orthogonal.
  • It is orthogonal only at initialization: Once training starts, the weights change freely and are no longer orthogonal. To keep them orthogonal during training, use a mechanism that constrains the weights to the form of an orthogonal matrix, such as torch.nn.utils.parametrizations.orthogonal.

Comparison with other initializations

The table lines up orthogonal initialization with initializations it is often compared with, from the same angles.

InitializationHow weights are setWhat it preservesMain assumptionsPyTorch function
Gaussian (standard deviation 1/N1/\sqrt{N})Each entry drawn independentlyVector length (on average)Nearly linear activationsnn.init.normal_(w, std=N ** -0.5)
Xavier initializationEach entry drawn independently (variance 2/(nin+nout)2/(n_{in}+n_{out}))Forward and backward variance (on average)Tanh, etc.nn.init.xavier_uniform_
He initializationEach entry drawn independently (variance 2/nin2/n_{in})Forward variance (on average)ReLU and its relativesnn.init.kaiming_normal_
Orthogonal initializationWhole matrix set to an orthogonal matrixVector length in every direction (all singular values 1)Linear, or Tanh etc. with an adjusted gainnn.init.orthogonal_
LSUVAfter orthogonal initialization, passes data through and matches each layer's output variance to 1Output variance on real dataUses dataNone (write it yourself)

The other initializations equalize the "variance", i.e., the average magnitude, whereas orthogonal initialization equalizes the entire distribution of singular values.

Rough guidelines for choosing:

  • For very deep, nearly linear networks or many stacked Tanh layers, use orthogonal initialization: The singular values do not spread as layers are stacked, and gradients reach every direction.
  • For typical networks using ReLU, start with He initialization: The theory of orthogonal initialization does not assume ReLU, so when using it, adjust the gain and check the behavior.
  • With normalization, the difference tends to be small: Batch normalization and the like re-equalize each layer's output scale, so differences in initialization have less effect on training.

PyTorch example

Show code
python
import torch
import torch.nn as nn

# set the weights of a fully connected layer to a random orthogonal matrix
layer = nn.Linear(256, 256, bias=False)
nn.init.orthogonal_(layer.weight, gain=1.0)

with torch.no_grad():
    w = layer.weight
    # check that W^T W = I
    print("difference between W^T W and the identity:", (w.T @ w - torch.eye(256)).abs().max().item())
    # all singular values are 1
    s = torch.linalg.svdvals(w)
    print(f"max singular value {s.max().item():.4f}, min {s.min().item():.4f}")


# compare the singular values of a whole 30-layer linear network under orthogonal and Gaussian initialization
def end_to_end_singular_values(init_fn, depth=30, width=64):
    torch.manual_seed(0)
    total = torch.eye(width, dtype=torch.float64)
    for _ in range(depth):
        w = torch.empty(width, width, dtype=torch.float64)
        init_fn(w)
        total = w @ total
    return torch.linalg.svdvals(total)


with torch.no_grad():
    orth = end_to_end_singular_values(nn.init.orthogonal_)
    gauss = end_to_end_singular_values(lambda w: nn.init.normal_(w, std=w.shape[1] ** -0.5))

print(f"orthogonal: max {orth.max().item():.3g}, median {orth.median().item():.3g}")   # both 1
print(f"gaussian  : max {gauss.max().item():.3g}, median {gauss.median().item():.3g}")  # median is very small


# with Tanh in between, match the gain (the paper suggests about 1 for Tanh; PyTorch suggests 5/3)
def init_orthogonal(module: nn.Module, gain: float = 1.0) -> None:
    if isinstance(module, (nn.Linear, nn.Conv2d)):
        # convolution weights are flattened to [out_ch, in_ch * k * k] and orthogonalized
        nn.init.orthogonal_(module.weight, gain=gain)
        if module.bias is not None:
            nn.init.zeros_(module.bias)


model = nn.Sequential(*[m for _ in range(20) for m in (nn.Linear(256, 256), nn.Tanh())])
model.apply(lambda m: init_orthogonal(m, gain=1.0))

FAQ

Q. Can orthogonal initialization be used for layers whose matrices are not square?
A.

Yes. The result is a "semi-orthogonal matrix" in which the fewer of the rows or columns are mutually orthogonal. PyTorch's nn.init.orthogonal_ produces this matrix according to the shape.

Q. Gaussian initialization also preserves length, so why is orthogonal initialization better?
A.

What Gaussian initialization preserves is the "average" length of random vectors. When layers are stacked, some directions stretch greatly and most are squashed to nearly 0. Errors in the squashed directions do not reach the input-side layers, so training slows down. Orthogonal initialization preserves length in every direction, so this imbalance does not occur.

Q. Do the weights stay orthogonal during training?
A.

No. They are orthogonal only at initialization; once training starts, the weights change freely. To keep them orthogonal during training, constrain the weights to the form of an orthogonal matrix with torch.nn.utils.parametrizations.orthogonal.

References

  1. A. M. Saxe, J. L. McClelland, and S. Ganguli, "Exact solutions to the nonlinear dynamics of learning in deep linear neural networks," arXiv:1312.6120, 2013.
  2. PyTorch Documentation, "torch.nn.init."
  3. PyTorch Documentation, "torch.nn.utils.parametrizations.orthogonal."