AI Logic

Weight Initialization

MetaInit

Updated:

The MetaInit procedure. On the left, a network from random input x ~ N(0, 1) through layer 1 and layer M to the loss; each layer's weight matrix keeps its direction and only its size ‖W_i‖ is adjusted, while biases stay at 0. On the right, one iteration: at the bottom, the gradient quotient GQ is computed from the gradient g(θ) and the gradient after one step g(θ − g(θ)); at the top, each ‖W_i‖ is updated by sign only in the direction that lowers GQ. At the very bottom, four examples of the gradient quotient with two parameters

Background and overview

MetaInit is an initialization method that tunes the size (norm) of each layer's weight matrix by gradient descent so that training can start from a place where taking one gradient descent step barely changes the gradient. It was proposed in 2019 by Yann Dauphin and Samuel Schoenholz (NeurIPS 2019, "MetaInit: Initializing learning by learning to initialize").

Whether training a deep network succeeds depends heavily on the initial values. Xavier initialization, He initialization, orthogonal initialization, Fixup, and others have derived the scale of initial values through specialized analysis for each architecture and activation function. However, such analysis no longer applies once the architecture changes. The paper gives examples such as orthogonal initialization working poorly when combined with ReLU, and LSUV not suiting pre-activation residual networks.

MetaInit provides a single objective that applies to any architecture and automatically sets the scale of the initial values to minimize it. That objective is the gradient quotient (GQ), which measures by what fraction the gradient of each parameter changes after one update step. Places where the gradient changes abruptly are strongly affected by curvature and are difficult for gradient descent.

The paper showed the following.

  • Even when starting from deliberately too small or too large initial values, MetaInit corrected the weight scales to values close to well-known good initializations.
  • A 28-layer CNN with neither batch normalization nor residual connections was trained on CIFAR-10 to an error rate of 3.7%, beating the same network with batch normalization (6.0%).
  • It can also be used for ResNet-50 on ImageNet, taking just under 1% of total training time.

No training data is used; random numbers from a normal distribution serve as input. The left side of the figure at the top shows which parts of the network are adjusted, and the right side shows one iteration of the adjustment.

Theory (procedure)

This section walks through the procedure in Sections 2–3 of the paper. θ\theta denotes all network parameters, L(θ)L(\theta) the mean loss over a minibatch, g(θ)=∇L(θ)g(\theta) = \nabla L(\theta) the gradient, and H(θ)=∇2L(θ)H(\theta) = \nabla^2 L(\theta) the Hessian (the matrix of second derivatives of the loss).

  1. Initialize the weights randomly: Fill the weights with an ordinary random distribution such as a Gaussian or an orthogonal matrix. Biases are set to 0 and are not adjusted by MetaInit.
  2. Prepare random data: Draw inputs from a standard normal distribution x∼N(0,1)x \sim \mathcal{N}(0, 1) and generate labels randomly as well. No training data is used.
  3. Compute the gradient quotient (Eq. (1) in the paper): GQ(L,θ)=1N∥g(θ)−H(θ)g(θ)g(θ)+ϵ−1∥1≈1N∥g(θ−g(θ))g(θ)+ϵ−1∥1\mathrm{GQ}(L, \theta) = \frac{1}{N} \left\lVert \frac{g(\theta) - H(\theta) g(\theta)}{g(\theta) + \epsilon} - 1 \right\rVert_1 \approx \frac{1}{N} \left\lVert \frac{g\big(\theta - g(\theta)\big)}{g(\theta) + \epsilon} - 1 \right\rVert_1 The division is per parameter, NN is the number of parameters, and ∥⋅∥1\lVert \cdot \rVert_1 is the sum of absolute values. g(θ−g(θ))g(\theta - g(\theta)) on the right is the gradient at the point reached by one step of size 1, and g−Hgg - Hg on the left is its first-order approximation. ϵ=ϵ0(2⋅[g(θ)≥0]−1)\epsilon = \epsilon_0 \big(2 \cdot [g(\theta) \ge 0] - 1\big) is a small number with the same sign as the gradient that keeps the division from blowing up when the gradient is close to 0.
  4. Update only the norms of the weight matrices in the direction that lowers the gradient quotient (Eq. (3) in the paper): For each weight matrix ww, compute the gradient with respect to its norm as w∥w∥⋅∇wGQ\frac{w}{\lVert w \rVert} \cdot \nabla_w \mathrm{GQ}, and update using only its sign (signSGD). The direction stays random; only the size changes.
  5. Repeat 2–4: The defaults in the paper's code are 500 iterations, learning rate 0.1, and momentum 0.9. When finished, start ordinary training.

The gradient quotient is the average, over parameters, of the relative change in the gradient after one update step. If the loss is nearly linear and H(θ)≈0H(\theta) \approx 0, the gradient does not change and the gradient quotient approaches its minimum of 0.

The gradient quotient does not become small when gradients vanish. If g(θ)=g(θ−g(θ))=0g(\theta) = g(\theta - g(\theta)) = 0, the numerator becomes 0 and the gradient quotient becomes 1. Because shrinking the gradient cannot game the objective, it works toward avoiding both vanishing gradients and exploding gradients.

Only the sign is used so that the update is not dragged by a single large gradient and still takes a step of fixed size even when gradients are nearly vanishing. The paper also shows that measuring the gradient quotient with the sum of squares (L2 norm) instead of the sum of absolute values (L1 norm) makes minimization much slower (Figure 4).

Why it works

The idea behind MetaInit is the hypothesis that "good initial values lie where, from gradient descent's point of view, the loss is locally close to linear (second-order effects are small)". Gradient descent looks only at first derivatives, so in places where curvature abruptly changes the direction or size of the gradient, each step misses its mark.

The paper rewrites the gradient quotient in terms of the Hessian's eigenvalues λi\lambda_i and eigenvectors viv_i, and shows that it becomes small in either of two ways.

  • Concentrating the Hessian's eigenvalues near 0: Curvature is small in every direction and the condition number is good.
  • Pointing the gradient along the Hessian's flat directions: Components along directions with eigenvalues near 0 make up most of the gradient.

Both are properties known to be related to trainability. The paper also cites prior work showing that gradients concentrating in the directions of the Hessian's large eigenvalues are a sign of training failure. It further notes that the Hessian, the Fisher information matrix, and the neural tangent kernel share nearly the same nonzero eigenvalues, and says the gradient quotient is related to these quantities as well.

As an analogy, it is like choosing where to start skiing down a slope. Starting where the slope stays at the same incline for a while, rather than where it changes abruptly, lets the skier descend stably just by looking at their feet (using only first-order information).

Why random data is enough: The paper confirms experimentally that the gradient quotient can measure the quality of initial values even on random data, and calls this "task-agnostic meta-learning". It notes that this agrees with the fact that earlier analyses of initialization also assumed random data, and with prior work suggesting that good initializations depend little on the dataset. Not using training data also has the advantage that the initialization cannot overfit to the data.

Why gradients rarely vanish despite this being meta-learning: In meta-learning that unrolls many steps of training and differentiates through them, as in MAML, if gradients vanish in the underlying training, the meta-gradient vanishes too. The gradient quotient directly contains each parameter's gradient value, giving each parameter a "shortcut" to the objective, so it can still be adjusted when gradients are nearly vanishing.

Examples of the initial values found: In a 28-layer linear network (removing the effect of the activation function), starting from a bad Gaussian with standard deviation 0.01 or 0.1, MetaInit corrected the per-layer weight norms to values close to Xavier initialization. In residual networks, it corrected them to values close to Fixup (without the zero-initialized layers) (Figure 3). Because MetaInit does not try to imitate any particular initialization, the paper calls this a surprising result.

Experimental results

These are the results reported in the paper. All compared networks have no normalization layers (except the batch normalization rows). MetaInit starts from DeltaOrthogonal (an orthogonal initialization for convolutional layers) without architecture-specific scaling.

CIFAR-10 (test error, lower is better. The gradient quotient is computed before training. Table 1)

NetworkMethodGradient quotientError
28 layers without residual connections (10× width)Batch normalization-6.0%
LSUV-3.7%
DeltaOrthogonal (no adjustment)1.0090.0%
DeltaOrthogonal → MetaInit0.543.7%
WideResNet 202-4Batch normalization-3.4%
LSUV-6.9%
DeltaOrthogonal (no adjustment)2.726.7%
DeltaOrthogonal → MetaInit0.533.8%
WideResNet 28-10Batch normalization-2.8%
LSUV-4.8%
DeltaOrthogonal (no adjustment)0.873.2%
DeltaOrthogonal → MetaInit0.452.9%

The activation function is β-Swish (a Swish with a learned slope; β\beta initialized to 0), which is linear at initialization, and every method uses Mixup and a cosine learning rate schedule. Gradient clipping is applied to the networks without residual connections.

  • Unadjusted initialization broke down when the architecture changed: With plain DeltaOrthogonal, the 28-layer network without residual connections could not be trained (90.0%), and for WideResNet, going deeper from 28 layers (10× width) to 202 layers (4× width) raised the error from 3.2% to 6.7%. This is because it does not account for β-Swish halving the input at every layer at initialization, and gradients vanished in the network without residual connections. MetaInit lowered the gradient quotient for every architecture and trained them to error rates close to or better than batch normalization.
  • Better than batch normalization for networks without residual connections: The paper says this agrees with prior findings that batch normalization is ill-suited to networks without residual connections.
  • LSUV got worse on residual networks: The paper explains that LSUV cannot shrink the residual branches according to depth. To prevent divergence, LSUV required lowering the learning rate to 0.01 (WideResNet 28-10) or 0.001 (202-4).
  • No change when combined with batch normalization: Combining batch normalization with MetaInit on WideResNet 28-10 gave an error of 2.8%, the same as batch normalization alone. Batch normalization weakens the influence of the initial values.

ImageNet, ResNet-50 (top-1 error. Table 2)

Activation functionBatch normalizationGroup NormalizationFixupDeltaOrthogonal (no adjustment)MetaInit
ReLU23.3%23.9%24.0%24.3%24.6%
Swish---99.9%24.0%

The batch normalization, Group Normalization, and Fixup values are taken from the Fixup paper, so the initialization conditions are not identical. With ReLU, unadjusted DeltaOrthogonal happened to work, but switching to Swish made training impossible (99.9%). MetaInit trained with both activation functions. With ReLU, however, MetaInit (24.6%) had a slightly higher error than unadjusted DeltaOrthogonal (24.3%). In this experiment, to estimate the gradient quotient well, 4,096 minibatches of small 32×32 random inputs were used, and momentum was chosen from 0.5 and 0.9 by cross-validation. MetaInit on ResNet-50 took 11 minutes on 8 V100 GPUs, just under 1% of total training time.

Practical caveats

MetaInit is computationally heavy and can fail on large models. The gradient that lowers the gradient quotient involves differentiating a Hessian-vector product. The paper itself lists as a limitation that for very large models or inputs, very large minibatches are needed to estimate the gradient and the Hessian-vector product well, and the meta-learning gradient descent can fail. The GradInit paper reports that MetaInit needed 3 GPUs on CIFAR-10 with a minibatch of 64, using 2–3 times the memory of GradInit.

Keep the following points in mind as well.

  • PyTorch has no built-in version: torch.nn.init has no MetaInit function. Figure 2 of the paper contains short PyTorch code that can be used as is (the implementation example below rewrites it to run on either CPU or GPU).
  • The meta-learning settings may need tuning: The paper says the meta-learning settings (momentum and number of iterations) may need tuning to work well. On ImageNet, momentum was chosen by cross-validation, and for WideResNet 202-4 the iterations were reduced to 200.
  • Only the weight scale is adjusted: The shape of the weight distribution (Gaussian or orthogonal) is chosen by hand. The paper notes that some architectures may require adjusting all initial values.
  • Initialization alone does not remove numerical instability: The paper notes that training without normalization layers at low numerical precision (such as half precision) is especially unstable.
  • Use model.eval() while measuring: The paper's code also computes the gradient quotient under model.eval(), because with Dropout present the value fluctuates on every computation.

Comparison with other initializations

The table focuses on methods that automatically set the scale of initial values before training, compared from the same angles.

MethodCriterionDataWhat is adjustedInitialization cost
He initializationSignal variance unchanged across layers (formula)NoneVarianceAlmost none
LSUVOutput variance of each layer is 1Training dataPer-layer factorA few forward passes
Data-dependent initializationChannel distributions and per-layer learning speedTraining dataPer-row factors and biasesA few forward and backward passes
MetaInitGradient unchanged after one update step (gradient quotient)Random numbersWeight matrix normsDifferentiating Hessian-vector products; heavy
GradInitLoss after one update step (with a gradient bound)Training dataPer-block factors for weights, biases, and normalization scalesSecond-order derivatives only when the gradient is too large

GradInit, which appeared two years after MetaInit, is a method with a similar goal. The GradInit paper lists its differences from MetaInit as lighter computation and memory, accounting for variance across minibatches, and accounting for the optimizer and learning rate used for training. On ImageNet with ResNet-50 (no normalization layers), the best accuracy was 75.4% for MetaInit and 75.8% for GradInit (Table 6 of the GradInit paper).

Rough guidelines for choosing:

  • If an initialization designed for the architecture exists, use it first: He initialization for plain ReLU feed-forward networks, and Fixup or SkipInit for residual networks. No computation is needed.
  • When changing the activation function or architecture breaks the assumptions of existing initializations, use MetaInit or GradInit: MetaInit can set weight scales for any architecture without training data.
  • With limited compute, use GradInit: It serves the same goal with lighter computation and memory.
  • With batch normalization, MetaInit has little effect: In the paper, too, combining it with batch normalization did not change the error.

PyTorch example

Show code
python
import torch
import torch.nn as nn


def gradient_quotient(loss, params, eps: float = 1e-5):
    """Eq. (1): GQ = (1/N) ‖ (g − Hg) / (g + ε) − 1 ‖_1 (code from Figure 2 of the paper)"""
    grad = torch.autograd.grad(loss, params, retain_graph=True, create_graph=True)
    # Hg (Hessian times gradient) is computed as the gradient of (1/2)‖g‖^2
    prod = torch.autograd.grad(sum((g ** 2).sum() / 2 for g in grad), params,
                               retain_graph=True, create_graph=True)
    out = sum((((g - p) / (g + eps * (2 * (g >= 0).float() - 1).detach())) - 1).abs().sum()
              for g, p in zip(grad, prod))
    return out / sum(p.numel() for p in params)


def metainit(model: nn.Module, criterion, x_size, n_classes: int,
             lr: float = 0.1, momentum: float = 0.9, steps: int = 500, eps: float = 1e-5) -> None:
    """Eq. (3): adjust only the weight matrix norms with signed gradients (signSGD + momentum)"""
    device = next(model.parameters()).device
    model.eval()                                                       # keep Dropout etc. from making values fluctuate
    weights = [p for p in model.parameters() if p.requires_grad and p.dim() >= 2]  # biases are not adjusted
    memory = [0.0] * len(weights)
    for _ in range(steps):
        x = torch.randn(*x_size, device=device)                        # random input x ~ N(0, 1)
        y = torch.randint(0, n_classes, (x_size[0],), device=device)   # labels are random too
        loss = criterion(model(x), y)
        gq = gradient_quotient(loss, list(model.parameters()), eps)
        grads = torch.autograd.grad(gq, weights)
        with torch.no_grad():
            for j, (w, g_all) in enumerate(zip(weights, grads)):
                norm = w.norm().item()
                g = torch.sign((w * g_all).sum() / norm).item()        # sign of the gradient w.r.t. the norm, (w/‖w‖)·∇_w
                memory[j] = momentum * memory[j] - lr * g
                w.mul_((norm + memory[j]) / norm)                      # change only the norm, not the direction


# Usage example (a CNN without normalization layers; biases 0)
model = nn.Sequential(
    nn.Conv2d(3, 64, 3, padding=1), nn.ReLU(),
    nn.Conv2d(64, 64, 3, padding=1), nn.ReLU(),
    nn.Conv2d(64, 128, 3, padding=1, stride=2), nn.ReLU(),
    nn.AdaptiveAvgPool2d(1), nn.Flatten(), nn.Linear(128, 10),
)
for m in model.modules():
    if isinstance(m, (nn.Conv2d, nn.Linear)):
        nn.init.orthogonal_(m.weight)
        nn.init.zeros_(m.bias)

metainit(model, nn.CrossEntropyLoss(), x_size=(32, 3, 32, 32), n_classes=10, steps=20)
model.train()  # after initialization, train as usual

FAQ

Q. How can MetaInit find good initial values without using training data?
A.

MetaInit does not look at whether the network gets the answers right, but at whether the landscape is easy for gradient descent to move through (whether the gradient barely changes after one step). This property is determined mainly by the weight scale and the network architecture and depends little on the data. The paper confirms experimentally that the gradient quotient can measure the quality of initial values even on random data. Because no data is used, a model initialized once can also be used for a different task.

Q. If the goal is just a small gradient quotient, why not make the gradient 0?
A.

That does not work. If the gradient is 0, it stays 0 after one step, so g(θ−g(θ))/(g(θ)+ϵ)−1g(\theta - g(\theta)) / (g(\theta) + \epsilon) - 1 is −1-1 for every parameter and the gradient quotient becomes 1. This is much larger than when the gradient does not change (close to 0), so the optimization does not move toward vanishing gradients.

Q. How do MetaInit and GradInit differ?
A.

Both set the scale of each weight block by gradient descent, but their objectives differ. MetaInit minimizes the change in the gradient after one step (the effect of curvature) and uses random data. GradInit minimizes the loss after one step of the actual optimizer, with a bound on the gradient norm, and uses training data. The GradInit paper lists as differences that it is lighter in computation and memory than MetaInit and that it accounts for the optimizer, learning rate, and variance across minibatches.

References

  1. Y. N. Dauphin and S. Schoenholz, "MetaInit: Initializing learning by learning to initialize," NeurIPS, 2019.
  2. C. Zhu, R. Ni, Z. Xu, K. Kong, W. R. Huang, and T. Goldstein, "GradInit: Learning to Initialize Neural Networks for Stable and Efficient Training," NeurIPS, 2021.
  3. H. Zhang, Y. N. Dauphin, and T. Ma, "Fixup Initialization: Residual Learning Without Normalization," ICLR, 2019.
  4. D. Mishkin and J. Matas, "All you need is a good init," ICLR, 2016.