AI Logic

Weight Initialization

Data-dependent Initialization

Updated:

The data-dependent initialization procedure. On the left, a network into which a sample of training images flows from the bottom through layer 1, layer k, and layer N, with gradients flowing back from a random linear loss Ξ·α΅€z_N at the top. On the right, from bottom to top: step 1 sets the weight shape with a Gaussian, PCA, or k-means; step 2 corrects weights and biases with per-channel mean and standard deviation; step 3 equalizes per-layer change rates to their geometric mean

Background and overview

Data-dependent initialization is an umbrella term for methods that pass a small amount of real training data through the network before training starts and set the initial weights and biases to match the measured statistics. Unlike Xavier initialization or He initialization, which derive the variance of the random weights from a formula, these methods equalize the output scale of every layer without making assumptions about the activation function or layer type.

The best-known method under this name was proposed by Philipp KrΓ€henbΓΌhl et al. in 2015 (ICLR 2016, "Data-dependent Initializations of Convolutional Neural Networks"). This article centers on that method and also covers two closely related methods from the same period: the initialization in Section 3 of the Weight Normalization paper, and LSUV.

The problem KrΓ€henbΓΌhl et al. address is that even networks that represent the same function can train at very different speeds per layer, depending on how weight magnitude is distributed across layers. For example, take two convolutional layers with a ReLU between them. Multiplying the weights and bias of the lower layer by Ξ±\alpha and dividing the weights of the upper layer by Ξ±\alpha leaves the output of the whole network unchanged. The gradients, however, become 1/Ξ±1/\alpha times as large in the lower layer and Ξ±\alpha times as large in the upper layer. On top of that, the lower layer now has larger weights, so an update of the same size has less effect. As a result, one layer may barely learn, or may suffer exploding gradients, even though the represented function is the same.

The method measures two things on data and corrects them:

  • Within a layer: make every output channel of each layer have the same mean and variance.
  • Between layers: make the weights of every layer change at the same rate relative to their magnitude (i.e., learn at the same speed).

On PASCAL VOC 2007 classification and detection, where training data is scarce, the paper substantially improved networks trained from random initialization, reaching accuracy close to unsupervised pre-training that takes weeks, with an initialization that takes only 54 seconds.

The left side of the figure at the top shows what is passed through the network during measurement, and the right side shows the three steps that set the weights.

Theory (procedure)

This section walks through the procedure in Section 3 of the paper. zkz_k is the output (activation) of layer kk, and WkW_k and bkb_k are the weights and bias of a convolutional or fully connected layer (an "affine layer" in the paper's terms).

  1. Choose the weight shape (Section 3.3): Set the weights with one of the following.

    • Gaussian random numbers
    • PCA: use the principal components of the activations entering the layer as weights
    • k-means: run spherical k-means on whitened activations and use the cluster centers as weights

    PCA and k-means are used only for convolutional layers, because there is not enough data to estimate them for the others. Fully connected layers use Gaussian random numbers.

  2. Normalize within each layer (Section 3.1, Algorithm 1): Starting from the input side, pass the sample images up to layer kk and compute the mean ΞΌ^k(i)\hat\mu_k(i) and standard deviation Οƒ^k(i)\hat\sigma_k(i) of each output channel ii. The mean and variance are computed over all images and all spatial positions. Then replace the weight rows and biases as follows.

    Wk(i,:)←Wk(i,:)Οƒ^k(i),bk(i)β†Ξ²βˆ’ΞΌ^k(i)Οƒ^k(i)W_k(i,:) \leftarrow \frac{W_k(i,:)}{\hat\sigma_k(i)}, \qquad b_k(i) \leftarrow \beta - \frac{\hat\mu_k(i)}{\hat\sigma_k(i)}

    Every output channel of layer kk now has mean Ξ²\beta and variance 1.

  3. Measure the change rate of each layer (Equations (1)–(4) in Section 3): How fast the weights learn is measured by the "change rate", the gradient magnitude divided by the weight magnitude. To avoid using labels, the loss is a random linear function β„“(zN)=η⊀zN\ell(z_N) = \eta^\top z_N (η∼N(0,I)\eta \sim \mathcal{N}(0, I), redrawn for each image). The change rate of column jj of the weights of layer kk is approximated as follows.

    C~k,j2β‰ˆE[zkβˆ’1(j)2] E[βˆ₯ykβˆ₯22]Nβˆ₯Wkβˆ₯22\tilde C_{k,j}^2 \approx \frac{\mathbb{E}\left[z_{k-1}(j)^2\right]\,\mathbb{E}\left[\lVert y_k \rVert_2^2\right]}{N \lVert W_k \rVert_2^2}

    yk=βˆ‚β„“/βˆ‚zky_k = \partial \ell / \partial z_k is the gradient that reaches layer kk through backpropagation, and NN is the number of rows of the weight matrix. The change rate C~k\tilde C_k of layer kk is this quantity averaged over columns.

  4. Equalize scale between layers (Section 3.2, Algorithm 2): Take the geometric mean of all layers' change rates, C~=(∏kC~k)1/N\tilde C = \left(\prod_k \tilde C_k\right)^{1/N}, as the target and set a scale factor for each layer (here NN is the number of layers).

    rk=(C~kC~)Ξ±/2,Wk←rkWk,bk←rkbkr_k = \left(\frac{\tilde C_k}{\tilde C}\right)^{\alpha/2}, \qquad W_k \leftarrow r_k W_k, \quad b_k \leftarrow r_k b_k

    At the same time, divide the weights of the next layer up by rkr_k so that the output of the whole network does not change.

  5. Repeat step 4: Repeat steps 3–4 until the change rates agree. The paper uses about 10 iterations. Ξ±<1\alpha < 1 is a damping factor that prevents oscillation from moving all layers at once; typically Ξ±=0.25\alpha = 0.25.

The upper layer can cancel the scaling in step 4 because ReLU, pooling, and local response normalization are positively homogeneous: multiplying the input by a positive number rr multiplies the output by rr. For activation functions without this property, the paper inserts an auxiliary layer after each layer that undoes the scaling.

The scale factor in step 4 takes this form for the following reason. Scaling layer kk by rr and cancelling it in the upper layer leaves the output unchanged, while the gradient of layer kk becomes 1/r1/r times as large and the weight magnitude rr times as large. Since the change rate is the gradient divided by the weight magnitude, it becomes 1/r21/r^2 times as large, and setting r=(C~k/C~)1/2r = (\tilde C_k / \tilde C)^{1/2} hits the target C~\tilde C exactly. Ξ±\alpha shrinks this step.

Why it works

The reasons the method works come down to three points.

  • Within-layer normalization equalizes the inputs to the next layer: ReLU and sigmoid apply the same transformation to every channel. If the input channels share the same distribution, so do the output channels. The paper notes that this property holds in practice for layers such as pooling and local response normalization, which apply the same operation to windows of the same size. As a result, the channels that layer k+1k+1 receives have equal scale without deriving a formula for each activation function.
  • Between-layer adjustment makes every layer learn at the same speed: As in the opening example, the distribution of weight magnitude across layers changes only each layer's learning speed, not the represented function. Making the change rate equal across all layers makes it unlikely that one particular layer stops learning or blows up. The target is the geometric mean so that the output scale stays unchanged in homogeneous networks such as ReLU networks.
  • It can be measured without labels: The change rate is measured with gradients from a random linear loss. Because no labeled data is needed, it can be used both to rescale pre-trained networks and to initialize before labels are available.

As an analogy, it is like arranging the rowers in a boat. If the ratio of each rower's oar length (weight magnitude) to rowing force (gradient) is not matched, the boat does not go straight. Before setting off, the crew actually pulls a few strokes and matches the ratios.

Figure 1 of the paper measures the per-layer change rates of CaffeNet (a small variant of AlexNet) on 100 images. With this method and with a model pre-trained on ImageNet, every layer had nearly the same change rate. With a Gaussian of standard deviation 0.01, or with k-means initialization without rescaling, the change rates differed widely across layers.

Related methods: Weight Normalization initialization and LSUV

Two other methods that set initial values by passing data through the network were proposed around the same time.

  • Weight Normalization initialization (Salimans and Kingma, 2016, Section 3 of the paper): Draw the weight direction v\mathbf{v} from a normal distribution with mean 0 and standard deviation 0.05, pass one minibatch through, and measure the mean ΞΌ[t]\mu[t] and standard deviation Οƒ[t]\sigma[t] of the pre-activation values tt. Then set the scale g←1/Οƒ[t]g \leftarrow 1/\sigma[t] and bias bβ†βˆ’ΞΌ[t]/Οƒ[t]b \leftarrow -\mu[t]/\sigma[t] so that each feature has mean 0 and variance 1 on the first minibatch. This corresponds to step 2 of KrΓ€henbΓΌhl et al. with Ξ²=0\beta = 0, and the paper itself notes that this initialization was proposed independently by KrΓ€henbΓΌhl et al. and by LSUV.
  • LSUV (Mishkin and Matas, 2016): After orthogonal initialization, go through the layers from the input side and divide all weights of each layer until the output variance is 1. It divides by a single number per layer rather than per channel, and does not adjust biases or rebalance between layers.

The differences among the three are summarized in the table in the final section, "Comparison with other initializations".

Experimental results

These are the results reported in the paper by KrΓ€henbΓΌhl et al. CaffeNet was trained without pre-training on PASCAL VOC 2007 (5,011 training images, 4,952 test images). Initialization used 160 training images. Values are mAP (higher is better).

Combinations of rescaling and training method (VOC 2007 classification. Excerpt from Table 1, omitting the Adam-only columns)

RescalingSGD, GaussianSGD, k-meansSGD+BN, GaussianSGD+BN, k-meansAdam+BN, GaussianAdam+BN, k-means
None50.8%41.2%51.6%49.4%55.7%53.8%
Within-layer only47.6%41.2%--53.2%53.1%
Between-layer only52.7%55.7%--54.5%57.2%
Both53.3%56.6%56.6%60.0%56.9%59.8%

BN is batch normalization, and - marks values not given in the paper (with Adam alone, the results were 50.9% and 52.0% without rescaling versus 53.1% and 56.9% with both). Within-layer normalization alone sometimes made things worse, because it upset the distribution of scale between layers. Doing both beat no rescaling in every combination. Adam or batch normalization alone did not reach SGD with this method's k-means (56.6%), and combining them raised accuracy further.

Comparison with other initializations (VOC 2007. Table 2)

InitializationClassificationDetection
Xavier initialization51.1%40.4%
He initialization43.3%37.2%
Hand-tuned Gaussian53.4%41.3%
This method (Gaussian)53.3%43.4%
This method (PCA)52.8%43.1%
This method (k-means)56.6%45.6%

Following the recommendation of its paper, He initialization was applied only to convolutional layers, with Gaussian random numbers for fully connected layers. Xavier and He initialization scored lower than the hand-tuned Gaussian. The paper suggests this may be because their formulas do not account for the max pooling and local response normalization in CaffeNet.

Comparison with unsupervised pre-training (VOC 2007. Table 3)

MethodPre-training timeClassificationDetection
Trained with ImageNet labels (1,000 classes)3 days78.2%56.8%
Doersch et al. (predicting the arrangement of image patches)4 weeks55.3%46.6%
This method (k-means)54 seconds56.6%45.6%
Doersch et al. + this method's between-layer adjustment4 weeks65.3%51.1%

Applying only the between-layer adjustment to pre-trained weights improved accuracy for two of the three unsupervised or self-supervised pre-training methods.

  • On ImageNet, early training was faster: For CaffeNet, the error dropped faster than with the reference initialization and He initialization during the first 100,000 updates. However, when trained to 320,000 updates, the reference initialization overtook it after the second learning rate drop, and the paper says the reason is not yet understood.
  • GoogLeNet trained without auxiliary classifiers: Training GoogLeNet with k-means initialization progressed faster than with the reference initialization. A model with the auxiliary classifiers branching from intermediate layers removed trained at almost the same speed. The final top-5 validation error was 11.57% for the reference model, 10.85% without auxiliary classifiers, and 10.69% with them.
  • Deeper networks did not improve VOC accuracy: GoogLeNet and 16-layer VGG were trained on VOC, but neither beat CaffeNet. The paper suggests this may be due to the small amount of training data.

Practical caveats

Within-layer normalization assumes that the input channels of each layer share the same distribution. In architectures like GoogLeNet, where outputs from different branches are concatenated and fed into the next convolution, this assumption does not necessarily hold. The paper itself advises caution with non-sequential architectures. The Weight Normalization paper also notes that initializing by passing data through the network cannot be used for recurrent models such as RNNs and LSTMs.

Keep the following points in mind as well.

  • PyTorch has no built-in version: torch.nn.init has no function for this method, so activations and gradients must be extracted with hooks and the method written by hand (see the implementation example below). The paper's implementation is written in Caffe, and the code is published on GitHub as philkr/magic_init.
  • The statistics only match on the initialization data: The mean and variance are estimated from a few images, so they drift slightly on other minibatches. The paper says a few dozen images suffice, and the experiments used 160. This is because even a single image yields tens of thousands of activations across spatial positions.
  • Use model.eval() while measuring: With Dropout present, the output fluctuates on every measurement.
  • Nothing happens during training: Scale is equalized only before training. It is not maintained after the weights change as training proceeds.
  • Ξ²\beta is a free choice: The paper's main text does not give a value for the mean Ξ²\beta in step 2. Setting Ξ²=0\beta = 0 before a ReLU makes roughly half the outputs zero at the start.

Comparison with other initializations

The table lines up data-dependent initializations with representative initializations and normalizations that do not use data, from the same angles.

MethodHow scale is setUnit of equalizationBetween-layer adjustmentComputation during training
He initializationVariance 2/nin2/n_{\mathrm{in}} from a formula (no data)LayerNoneNone
This article's method (KrΓ€henbΓΌhl et al.)Correct weight rows and biases with the measured mean and standard deviationOutput channelEqualizes change ratesNone
Weight Normalization initializationMeasure on one minibatch and set gg and bbOutput channelNoneNone (only the weight normalization computation)
LSUVAfter orthogonal initialization, divide all weights by the measured varianceLayerNoneNone
Batch normalizationNormalize with the mean and variance of each minibatchOutput channelNone (re-normalizes every time)Every step

Some methods instead set initial values by looking at the gradients themselves before training. GradInit learns a scale factor for each block of weights so that the loss after one update step is as small as possible, and MetaInit adjusts weight magnitudes so that the gradient barely changes after one update step (i.e., curvature has little effect).

Rough guidelines for choosing:

  • For a typical ReLU network with normalization layers, start with He initialization: No data needs to be prepared, and the normalization layers re-equalize the scale.
  • For a network without normalization layers that mixes layer types, use a data-dependent initialization: Even with pooling and local response normalization in the mix, the scale can be measured on data and equalized. For a quick fix, use LSUV; to also equalize the learning speed of each layer, use this article's method.
  • When fine-tuning pre-trained weights on a different, small dataset, apply only the between-layer adjustment: In the paper, this sometimes improved fine-tuning accuracy without changing the represented function (see fine-tuning).
  • When using Weight Normalization, use the initialization from its paper as well: Weight normalization alone does not equalize the output scale of each layer.

PyTorch example

Show code
python
import torch
import torch.nn as nn


def affine_layers(model: nn.Module) -> list[nn.Module]:
    return [m for m in model.modules() if isinstance(m, (nn.Conv2d, nn.Linear))]


@torch.no_grad()
def within_layer_init(model: nn.Module, x: torch.Tensor, beta: float = 0.0) -> None:
    """Algorithm 1: from the input side, give each output channel mean beta and variance 1"""
    for layer in affine_layers(model):
        nn.init.normal_(layer.weight)               # W_k ~ N(0, I)
        nn.init.zeros_(layer.bias)                  # b_k = 0
        out = {}
        h = layer.register_forward_hook(lambda m, i, o: out.__setitem__("z", o))
        model(x)                                    # pass the samples through (capture this layer's output)
        h.remove()
        z = out["z"]
        dims = [d for d in range(z.dim()) if d != 1]  # pool over images and spatial positions
        mu, sigma = z.mean(dim=dims), z.std(dim=dims)
        shape = (-1,) + (1,) * (layer.weight.dim() - 1)
        layer.weight.div_(sigma.view(shape))        # W_k(i,:) ← W_k(i,:) / Οƒ_k(i)
        layer.bias.copy_(beta - mu / sigma)         # b_k(i) ← Ξ² βˆ’ ΞΌ_k(i) / Οƒ_k(i)


def change_rates(model: nn.Module, x: torch.Tensor) -> torch.Tensor:
    """compute the change rate C̃_k of Eq. (4) for each layer (for convolutions, input channels are the columns)"""
    layers = affine_layers(model)
    acts, grads, hooks = {}, {}, []
    for m in layers:
        hooks.append(m.register_forward_hook(lambda m, i, o: acts.__setitem__(m, i[0].detach())))
        hooks.append(m.register_full_backward_hook(lambda m, gi, go: grads.__setitem__(m, go[0].detach())))
    model.zero_grad()
    z_n = model(x)
    eta = torch.randn_like(z_n)                     # random linear loss Ξ·^T z_N (a different Ξ· for each image)
    (eta * z_n).sum().backward()
    for h in hooks:
        h.remove()
    rates = []
    for m in layers:
        z, y = acts[m], grads[m]
        dims = [d for d in range(z.dim()) if d != 1]
        ez2 = (z ** 2).mean(dim=dims)               # E[z_{k-1}(j)^2] (per column j)
        ey2 = (y ** 2).flatten(1).sum(1).mean()     # E[||y_k||^2]
        n_rows = m.weight.shape[0]
        c2 = ez2 * ey2 / (n_rows * m.weight.detach().pow(2).sum())
        rates.append(c2.sqrt().mean())              # C̃_k = E_j[C̃_{k,j}]
    return torch.stack(rates)


def between_layer_init(model: nn.Module, x: torch.Tensor, alpha: float = 0.25, iters: int = 10) -> None:
    """Algorithm 2: equalize per-layer change rates to their geometric mean (assumes only ReLU and pooling in between)"""
    layers = affine_layers(model)
    for _ in range(iters):
        c = change_rates(model, x)
        c_bar = c.log().mean().exp()                # geometric mean C̃
        r = (c / c_bar) ** (alpha / 2)              # r_k = (C̃_k / C̃)^(α/2)
        with torch.no_grad():
            for k, m in enumerate(layers):
                m.weight.mul_(r[k])                 # W_k ← r_k W_k
                m.bias.mul_(r[k])                   # b_k ← r_k b_k
                if k > 0:
                    m.weight.div_(r[k - 1])         # cancel r_{k-1} of the layer below (biases are not divided)


# Usage example (a small CNN without normalization layers)
model = nn.Sequential(
    nn.Conv2d(3, 64, 3, padding=1), nn.ReLU(), nn.MaxPool2d(2),
    nn.Conv2d(64, 128, 3, padding=1), nn.ReLU(), nn.MaxPool2d(2),
    nn.Flatten(), nn.Linear(128 * 8 * 8, 256), nn.ReLU(), nn.Linear(256, 10),
)
model.eval()                                        # keep Dropout etc. from making the output fluctuate
x = torch.randn(160, 3, 32, 32)                     # in practice, preprocessed training images (160 in the paper)
within_layer_init(model, x)
between_layer_init(model, x)
model.train()                                       # after initialization, train as usual

FAQ

Q. How does data-dependent initialization differ from LSUV?
A.

Both pass training data through the network to equalize the output scale of each layer, but LSUV simply divides all weights of a layer by one number so that the whole layer's variance is 1. The method of KrΓ€henbΓΌhl et al. equalizes the mean and variance of each output channel and also sets the biases. It then adds an adjustment that equalizes the learning speed (change rate) of every layer.

Q. How many images are needed for initialization?
A.

According to the paper, a few dozen are often enough, and the experiments used 160. In convolutional layers, even a single image yields many activations across spatial positions, so the mean and variance can be estimated stably from few images. Initialization took 54 seconds.

Q. Can it be used on pre-trained models?
A.

Yes. The paper applied only the between-layer adjustment (step 4) to weights obtained by unsupervised pre-training. It only redistributes weight magnitude across layers without changing the represented function, and it raised VOC 2007 classification and detection accuracy for two of the three pre-training methods (for example, classification with the method of Doersch et al. went from 55.3% to 65.3%).

References

  1. P. KrΓ€henbΓΌhl, C. Doersch, J. Donahue, and T. Darrell, "Data-dependent Initializations of Convolutional Neural Networks," ICLR, 2016.
  2. P. KrΓ€henbΓΌhl, "magic_init" (official implementation), GitHub.
  3. T. Salimans and D. P. Kingma, "Weight Normalization: A Simple Reparameterization to Accelerate Training of Deep Neural Networks," NeurIPS, 2016.
  4. D. Mishkin and J. Matas, "All you need is a good init," ICLR, 2016.