AI Logic

Weight Initialization

GradInit

Updated:

The GradInit procedure. On the left, a network from a minibatch to the loss, where each weight block W_i (convolution, BN scale, fully connected, etc.) is multiplied by a learned factor α_i. On the right, one iteration of learning α: at the bottom, the gradient g on minibatch S is measured and compared with the bound γ; at the top, if ‖g‖ > γ then ‖g‖ is reduced, and if ‖g‖ ≤ γ the loss on another minibatch S̃ is measured with the weights after one step and reduced. The bottom box describes A[g], how S̃ is built, and how the procedure ends

Background and overview

GradInit is a method that multiplies each block of randomly initialized weights (layer weights, biases, normalization-layer scales, and so on) by a single scale factor, and learns those factors briefly to set the scale of the initial values. The factors are chosen so that "the loss after a single update step with the optimizer used for training is as small as possible". It was proposed in 2021 by Chen Zhu et al. (NeurIPS 2021, "GradInit: Learning to Initialize Neural Networks for Stable and Efficient Training").

Earlier initializations derived a formula for each network architecture. Xavier initialization and He initialization assume plain feed-forward networks without normalization layers or residual connections, Fixup assumes residual networks, and T-Fixup assumes the Transformer. Re-deriving a formula every time a new architecture is tried is laborious, and once the formula's assumptions no longer hold, training becomes unstable. For example, the original Transformer (Post-LN) does not converge with ordinary initialization without learning rate warmup.

Instead of deriving formulas, GradInit finds the scale factors numerically using training data and the actual optimizer, so it works with any architecture. The paper showed the following.

  • VGG and ResNet, both with and without batch normalization, trained faster and to higher accuracy than with He initialization.
  • A 1,202-layer ResNet was trained and beat the accuracy of a 110-layer ResNet.
  • The original Post-LN Transformer, unmodified, was trained without learning rate warmup using both Adam and SGD.

In every experiment it took less than 1% of the total training time. The left side of the figure at the top shows where in the network the factors are applied, and the right side shows one iteration of learning the factors.

Theory (procedure)

This section walks through the procedure in Section 3 of the paper.

  1. Initialize the weights randomly: Fill all weights W1,…,WMW_1, \dots, W_M from a zero-mean Gaussian. The paper used He initialization for its image classification experiments and Xavier initialization for machine translation. Normalization-layer scales are 1 and biases are 0. "Weights" here includes fully connected weights, convolution kernels, biases, and normalization-layer scales.

  2. Multiply each weight block by a scale factor: Multiply each WiW_i by a learnable scalar αi\alpha_i (initialized to 1). WiW_i itself is frozen, and only αi\alpha_i is learned. Write m={α1,…,αM}m = \{\alpha_1, \dots, \alpha_M\} and θm={α1W1,…,αMWM}\theta_m = \{\alpha_1 W_1, \dots, \alpha_M W_M\}.

  3. Learn mm to solve the following problem (Eq. (1) in the paper):

    min⁡m  L(S~;  θm−η A[gS,θm])subject to∥gS,θm∥pA≤γ\min_m \; L\big(\tilde S;\; \theta_m - \eta\, \mathcal{A}[g_{S,\theta_m}]\big) \quad \text{subject to} \quad \lVert g_{S,\theta_m} \rVert_{p_\mathcal{A}} \le \gamma

    SS and S~\tilde S are different minibatches, gS,θmg_{S,\theta_m} is the gradient of the loss on SS, η\eta is the learning rate used for actual training, and A\mathcal{A} is the operation by which the optimizer turns the gradient into the direction of its first step. For SGD, A[g]=γ g/∥g∥2\mathcal{A}[g] = \gamma\, g / \lVert g \rVert_2 (pA=2p_\mathcal{A} = 2); for the first step of Adam, A[g]=sign(g)\mathcal{A}[g] = \mathrm{sign}(g) (pA=1p_\mathcal{A} = 1).

  4. In each iteration, branch on whether the constraint holds (Algorithm 1 in the paper): Compute the gradient gg on minibatch SS, and

    • if ∥g∥pA>γ\lVert g \rVert_{p_\mathcal{A}} > \gamma, take one step on mm in the direction that reduces ∥g∥pA\lVert g \rVert_{p_\mathcal{A}}.
    • otherwise, compute the loss L~\tilde L on S~\tilde S with the weights after one step, θm−ηA[g]\theta_m - \eta \mathcal{A}[g], and take one step on mm in the direction that reduces L~\tilde L.

    After either step, clip αi\alpha_i so that it does not fall below 0.01.

  5. After the iterations, fold the factors into the weights and remove them: Set Wi←αiWiW_i \leftarrow \alpha_i W_i, remove αi\alpha_i, and start ordinary training.

The paper updates mm with Adam at learning rate τ\tau, and τ\tau in the range 10−310^{-3} to 10−110^{-1} worked well. The iterations converged in under 400 iterations on CIFAR-10 and within 2,000 on ImageNet.

To keep computation light, A[g]\mathcal{A}[g] in step 4 is treated as a constant and not backpropagated through. This is also because Adam's sign function is not differentiable in the first place. As a result, the ordinary iterations where the constraint holds need no second-order derivatives. Second-order derivatives are needed only in iterations where the gradient is too large and ∥g∥\lVert g \rVert is reduced.

Choosing the bound γ\gamma: A first-order estimate of how much the first step lowers the loss is η∥g∥22\eta \lVert g \rVert_2^2 for SGD and η∥g∥1\eta \lVert g \rVert_1 for Adam. The paper therefore recommends choosing γ\gamma so that ηγ2=0.1\eta \gamma^2 = 0.1 for SGD and ηγ=0.1\eta \gamma = 0.1 for Adam. This means capping the first-order decrease of the loss in the first step at 0.1, and all of the paper's experiments used this rule.

Choosing the two minibatches: S~\tilde S is built by mixing half of SS with a freshly drawn half. Setting S~=S\tilde S = S drifted toward a cheating solution that lowers the loss by enlarging the gradient, and training became unstable. Conversely, making SS and S~\tilde S completely different turned the first update into an almost random perturbation for networks with high initial gradient variance, reducing the benefit (Table 1 in the paper).

Why it works

The reasons GradInit works come down to three points.

  • It chooses a scale at which the "first step" goes well, accounting for the optimizer and learning rate: Formula-based initializations aim to keep the signal variance unchanged across layers. GradInit directly checks whether the first step actually lowers the loss under the optimizer, learning rate, and minibatch noise used in real training. The same network gets different factors for SGD and Adam.
  • The bound on the gradient norm prevents cheating solutions: Without the bound, the method would pick solutions that lower the loss by enlarging the gradient and moving a long way in one step. The bound forces the loss to go down by choosing a good direction rather than a big step. The paper reports that this constrained form, compared with adding a penalty term, allows the same γ\gamma across architectures and is cheaper to compute (Table 2).
  • As a result, gradient variance shrinks: In Figure 1 of the paper, for ResNet-110 (CIFAR-10) and ResNet-50 (ImageNet), the gradient variance across minibatches decreased in every layer except the final fully connected layer. For VGG-19 with batch normalization, the gradient variance was 4 orders of magnitude smaller than with He initialization.

The learned factors showed tendencies similar to hand-derived initializations.

  • Shrinking the final fully connected layer: This points in the same direction as Fixup setting the final fully connected layer to 0.
  • Inside residual blocks, shrinking the scale of the second batch normalization and enlarging the first: Deeper layers had smaller residual block outputs, preventing variance from growing as layers are stacked.
  • Enlarging the weights of convolutions before batch normalization: This differs from Fixup, which only shrinks weights. The paper explains that batch normalization amplifies gradient variance during backpropagation when its input variance is below 1, and analyzes that enlarging the input prevented this.
  • In the Transformer, shrinking the encoder weights overall, as well as the FFN and output projections: This makes the residual branches relatively smaller than the shortcuts, close to the idea behind the initialization called Admin.

As an analogy, it is like adjusting the saddle and handlebar height of an unfamiliar bicycle by actually pedaling once instead of calculating them. A big first push is pointless if the bike wobbles, so a cap is placed on the momentum.

Difference from MetaInit: MetaInit also adjusts the scale of each weight block by gradient descent. The paper lists three differences from GradInit. MetaInit uses third-order derivatives, so it is heavy in computation and memory: on CIFAR-10 with a minibatch of 64 it needed 3 GPUs, whereas GradInit needed 1. MetaInit examines curvature on a single minibatch of random Gaussian samples, so it does not account for variance across minibatches. MetaInit does not consider the type of optimizer or the learning rate.

Experimental results

These are the results reported in the paper.

CIFAR-10 (test accuracy. Accuracy after the first epoch / best accuracy over all epochs, average of 4 runs. Table 3)

InitializationVGG-19 (no BN)VGG-19 (BN)ResNet-110 (no BN)ResNet-110 (BN)ResNet-1202 (BN)
He initialization29.1 / 94.512.6 / 94.416.1 / 94.223.2 / 95.012.9 / 94.4
+1 epoch (constant learning rate)37.2 / 94.419.6 / 94.521.0 / 93.932.5 / 94.712.6 / 94.0
+1 epoch (warmup)37.4 / 94.453.5 / 94.719.8 / 94.148.7 / 95.128.1 / 95.4
MetaInit30.5 / 94.635.1 / 94.614.6 / 94.229.0 / 94.811.7 / 95.0
GradInit29.3 / 94.747.8 / 95.136.2 / 94.638.2 / 95.429.0 / 96.2

Values are in %. "+1 epoch" means training for one epoch from He initialization before starting the actual training. GradInit learned the factors with SGD, learning rate 0.1, and γ=1\gamma = 1, followed by 200 epochs of training with cosine annealing. Networks without BN use gradient clipping (max norm 1) with every initialization.

  • GradInit had the highest best accuracy on all 5 networks.
  • The 1,202-layer ResNet beat the 110-layer one: With He initialization, the 1,202-layer ResNet (94.4%) was less accurate than the 110-layer one (95.0%), but with GradInit it reached 96.2%, surpassing the 110-layer network.
  • Both the batch normalization scales and the other layers' weights must be adjusted: Applying GradInit with the batch normalization scales frozen gave a best accuracy of 94.6% for VGG-19 (BN), and adjusting only the batch normalization scales gave 94.4%, both short of the 95.1% obtained by adjusting both (Table 4).
  • Learning the factors during ordinary training is not a substitute: When per-block factors were learned together with the weights from the start of training, VGG-19 (BN) did not converge at learning rate 0.1 (Table 5).
  • It also worked with Adam: For ResNet-110 (BN) trained with AdamW, He initialization scored 36.6 / 94.9 and GradInit (A\mathcal{A} set to Adam, γ=25\gamma = 25) scored 40.2 / 95.3.

ImageNet, ResNet-50 (accuracy after the first epoch / best accuracy. Table 6)

InitializationWith BNWithout BN
He initialization14.6 / 75.9-
Fixup-18.0 / 75.7
MetaInit-- / 75.4
GradInit19.2 / 76.219.2 / 75.8

Values are in %. The ResNet-50 without BN follows the Fixup architecture. The MetaInit values are taken from the MetaInit paper, and - marks missing values.

Machine translation, Post-LN Transformer (IWSLT-14 German→English, BLEU. Excerpt from Table 7)

MethodArchitecture changeWarmupOptimizerBLEU
Standard initializationNoneYesRAdam35.6
FixupRemoves layer normalizationYesAdam34.5
T-FixupRemoves layer normalizationNoAdam35.5
Admin (authors' reimplementation)Adds a learnable wskipw_{\mathrm{skip}}NoAdam36.1
Admin (authors' reimplementation)Adds a learnable wskipw_{\mathrm{skip}}NoSGD33.7
GradInitNoneNoAdam36.1
GradInitNoneNoSGD35.6

GradInit trained the Transformer without changing its architecture and without warmup, with both Adam and SGD. Even with SGD it scored 35.6, the same as the Adam variant with warmup (RAdam). Learning the factors took 780 iterations, shorter than the usual warmup (4,000 iterations), and shortening warmup to 780 iterations failed to converge at learning rates of 3×10−43 \times 10^{-4} or higher.

Practical caveats

GradInit's factors are tailored to the optimizer and learning rate used for training. In the paper, the factors learned for Adam and for SGD showed different tendencies. Substantially changing the optimizer or learning rate after learning the factors breaks the assumptions behind the chosen initial values. Use the same A\mathcal{A} and η\eta in step 3 as in actual training.

Keep the following points in mind as well.

  • PyTorch has no built-in version: torch.nn.init has no GradInit function. The authors' implementation is published on GitHub as zhuchen03/gradinit. The implementation example below is a compact version of Algorithm 1 from the paper for SGD.
  • The factor learning rate τ\tau needs to be searched: The paper fixed γ\gamma by the rule above and tuned only τ\tau. Even so, it ran a grid search over 10−310^{-3} to 10−110^{-1} and reported the best result.
  • It can use more memory than training: Iterations that reduce the gradient use second-order derivatives. The paper says that on ImageNet, GPU memory limits forced it to apply GradInit with smaller minibatches than in actual training. Compared with MetaInit, it used one half to one third of the memory.
  • Nothing happens during training: After the factors are folded into the weights, they are removed and training proceeds normally. There is no mechanism to maintain scale during training.
  • For networks with batch normalization, keep model.train() while learning the factors: GradInit imitates the first step of actual training, so batch normalization runs on minibatch statistics.

Comparison with other initializations

The table lines up formula-based initializations, data-measured initializations, and initializations that learn by looking at gradients, from the same angles.

MethodHow scale is setUses dataAssumed networkInitialization cost
He initializationVariance 2/nin2/n_{\mathrm{in}} from a formulaNoPlain ReLU feed-forward networkAlmost none
FixupShrinks residual branches according to depth and sets the last layer to 0NoResidual networkAlmost none
LSUVPasses data through and makes each layer's output variance 1YesAny (does not consider residual accumulation)A few forward passes
MetaInitAdjusts the scale of each weight matrix so the gradient barely changes across one update stepNo (random samples)AnyThird-order derivatives; heavy
GradInitLearns per-block factors to minimize the loss after the first stepYesAnyUnder 1% of total training
WarmupLeaves initial values unchanged and starts with a small learning rate-AnyNone (training gets longer)

Rough guidelines for choosing:

  • For common architectures, use the initialization designed for that architecture: He initialization for plain feed-forward networks, Fixup or SkipInit for residual networks, T-Fixup for Transformers, and so on. These are determined by formulas alone and take no effort.
  • For new architectures, or networks with branches or mixed components, use GradInit: Initial values can be set without deriving formulas. It also suits training very deep residual networks or a Post-LN Transformer without warmup.
  • To equalize scale with data while adding almost no computation, use LSUV: It needs only a few forward passes. However, it does not look at the first optimization step.
  • If warmup is enough, use warmup: In the paper as well, for the 1,202-layer ResNet, warmup worked better than MetaInit. GradInit was 0.8 points higher still, but warmup only changes the learning rate schedule without touching the initial values.

PyTorch example

Show code
python
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.func import functional_call


def gradinit(model: nn.Module, batches, lr: float = 0.1, gamma: float = 1.0,
             tau: float = 1e-2, iters: int = 390, alpha_min: float = 0.01) -> None:
    """Algorithm 1 of the paper (A is SGD). batches is an iterator that yields (input, label) minibatches.
    lr is the learning rate η used for actual training. For SGD, aim for η γ^2 = 0.1 (gamma=1 when lr=0.1)"""
    names = [n for n, _ in model.named_parameters()]
    base = {n: p.detach().clone() for n, p in model.named_parameters()}     # W_i (frozen)
    alphas = {n: torch.ones((), requires_grad=True) for n in names}         # α_i (initialized to 1)
    opt = torch.optim.Adam(alphas.values(), lr=tau)                         # α is learned with Adam

    def loss_on(params, x, y):
        return F.cross_entropy(functional_call(model, params, (x,)), y)

    model.train()  # as in the first real step, BN uses minibatch statistics
    for _ in range(iters):
        x, y = next(batches)
        x2, y2 = next(batches)
        half = x.shape[0] // 2
        xt = torch.cat([x[:half], x2[half:]])                               # S̃: half of S + a fresh half
        yt = torch.cat([y[:half], y2[half:]])

        params = {n: alphas[n] * base[n] for n in names}                    # θ_m = {α_i W_i}
        grads = torch.autograd.grad(loss_on(params, x, y), list(params.values()), create_graph=True)
        gnorm = torch.sqrt(sum((g ** 2).sum() for g in grads))              # ‖g‖_2 (p_A = 2 for SGD)

        opt.zero_grad()
        if gnorm.item() > gamma:
            gnorm.backward()                                                # gradient too large: reduce ‖g‖ (second-order derivative)
        else:
            step = [(gamma * g / gnorm).detach() for g in grads]            # A[g] = γ g / ‖g‖_2 (treated as a constant)
            stepped = {n: params[n] - lr * s for n, s in zip(names, step)}  # θ_m − η A[g]
            loss_on(stepped, xt, yt).backward()                             # reduce the loss on S̃ after one step
        opt.step()
        with torch.no_grad():
            for a in alphas.values():
                a.clamp_(min=alpha_min)                                     # α_i ≥ 0.01

    with torch.no_grad():                                                   # set W_i ← α_i W_i and remove α
        for n, p in model.named_parameters():
            p.copy_(alphas[n] * base[n])


# Usage example (starting from He initialization)
model = nn.Sequential(
    nn.Conv2d(3, 64, 3, padding=1), nn.BatchNorm2d(64), nn.ReLU(), nn.MaxPool2d(2),
    nn.Conv2d(64, 128, 3, padding=1), nn.BatchNorm2d(128), 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.kaiming_normal_(m.weight, nonlinearity="relu")
        nn.init.zeros_(m.bias)

# in practice, take training data from a DataLoader; here, random tensors of the right shape
def random_batches():
    while True:
        yield torch.randn(128, 3, 32, 32), torch.randint(0, 10, (128,))

gradinit(model, random_batches(), lr=0.1, gamma=1.0, iters=20)
optimizer = torch.optim.SGD(model.parameters(), lr=0.1, momentum=0.9)   # start actual training with the same learning rate

FAQ

Q. Isn't GradInit the same as training twice?
A.

No. GradInit learns only one factor αi\alpha_i per weight block, while the weights themselves stay frozen at their random values. The iterations also numbered under 400 on CIFAR-10 and within 2,000 on ImageNet, taking less than 1% of total training time. The paper also compared it with training for one epoch from He initialization first, and showed that GradInit reaches higher final accuracy.

Q. Wouldn't learning the factors together with the weights from the start make GradInit unnecessary?
A.

The paper tried this and showed that it does not work. When learnable factors were attached to each weight block and learned along with ordinary training, VGG-19 with batch normalization did not converge at learning rate 0.1. Lowering the learning rate to 0.01 made it converge, but the best accuracy was 93.4%, lower than GradInit's 95.1%. GradInit's benefit comes not from having factors but from choosing them with the objectives of "loss after the first step" and "a bound on the gradient".

Q. How should the bound $\gamma$ be chosen?
A.

The paper's rule is to set it, relative to the actual training learning rate η\eta, so that ηγ2=0.1\eta \gamma^2 = 0.1 for SGD and ηγ=0.1\eta \gamma = 0.1 for Adam. This means capping the first-order decrease of the loss in the first step at 0.1. The paper used γ=1\gamma = 1 for image classification (SGD, η=0.1\eta = 0.1) and γ=103\gamma = 10^3 for the Transformer (Adam, η=5×10−4\eta = 5 \times 10^{-4}).

References

  1. 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.
  2. C. Zhu, "gradinit" (official implementation), GitHub.
  3. Y. N. Dauphin and S. Schoenholz, "MetaInit: Initializing learning by learning to initialize," NeurIPS, 2019.
  4. H. Zhang, Y. N. Dauphin, and T. Ma, "Fixup Initialization: Residual Learning Without Normalization," ICLR, 2019.
  5. L. Liu, X. Liu, J. Gao, W. Chen, and J. Han, "Understanding the Difficulty of Training Transformers," EMNLP, 2020.