AI Logic

Weight Initialization

Mimetic Initialization

Updated:

A diagram of mimetic initialization. The left shows the ViT flow: image patches, patch embedding, sinusoidal position embeddings, then layer normalization, self-attention, layer normalization, and MLP repeated L times, leading to the class prediction; only the four self-attention weights are initialized. The right shows, at the bottom, the target query–key product α1Z1 + β1I (a grid with a positive diagonal) split by singular value decomposition into W_Q and W_K, and at the top, the target value–output projection product α2Z2 − β2I (a grid with a negative diagonal) split by singular value decomposition into W_V and W_proj. The bottom box lists the symbols, coefficient values, and color meanings

Background and overview

Mimetic initialization is a method that initializes the self-attention weights of a Transformer to resemble the structure seen in the weights of pre-trained models. It builds the weights from matrices that mix random numbers with the identity, so that the product of the query and key weights is close to the identity matrix and the product of the value and output projection weights is close to the "negative" identity matrix. It was proposed in 2023 by Asher Trockman and J. Zico Kolter (ICML 2023, "Mimetic Initialization of Self-Attention Layers").

The Transformer is known to be hard to train from scratch on small datasets. For images, ViT loses badly to CNNs such as ResNet on small data, and the gap has only been narrowed by adding self-supervised pre-training, auxiliary losses, convolution-inspired components, and so on. As a result, a model pre-trained on large data is usually the starting point.

The question the paper asks is whether "part of the benefit of pre-training simply comes from providing good initial values". So the authors observed the weights of pre-trained ViTs and built an initialization that reproduces their characteristics with formulas alone, without any training.

  • No pre-training or training required: It is determined by formulas and singular value decomposition alone, at almost no computational cost.
  • No change to the architecture: It works with an ordinary Transformer with residual connections and layer normalization.
  • Large gains on small image datasets: When training ViT from scratch, accuracy rose by up to over 5% on CIFAR-10 and up to about 4% on ImageNet. Improvements for language models were smaller.

The left side of the figure at the top shows where in ViT the initialization changes, and the right side shows how the two pairs of self-attention weights are built.

Theory (observation and procedure)

Observation: the structure of pre-trained ViT weights (Section 3 of the paper, Figure 1)

Examining the self-attention weights of a ViT-Tiny pre-trained on ImageNet, two patterns appeared in many layers and heads.

  • The diagonal of the product of the query and key weights, WQWK⊤W_Q W_K^\top, is clearly positive
  • The diagonal of the product of the value and output projection weights, WVWprojW_V W_{\mathrm{proj}}, is clearly negative

WQ,WK∈Rd×kW_Q, W_K \in \mathbb{R}^{d \times k} are the query and key weights of one head, dd is the model width, and k=d/(number of heads)k = d / (\text{number of heads}) is the head dimension. WV,Wproj∈Rd×dW_V, W_{\mathrm{proj}} \in \mathbb{R}^{d \times d} are the value and output projection weights. The self-attention map is Softmax(1kXWQWK⊤X⊤)\mathrm{Softmax}\left(\frac{1}{\sqrt{k}} X W_Q W_K^\top X^\top\right), where XX is the input with the position embeddings added.

Procedure: building this structure with formulas (Section 4 of the paper, Eqs. (1)–(7))

  1. Set the target products as sums of random matrices and the identity: WQWK⊤≈α1Z1+β1I,WVWproj⊤≈α2Z2−β2IW_Q W_K^\top \approx \alpha_1 Z_1 + \beta_1 I, \qquad W_V W_{\mathrm{proj}}^\top \approx \alpha_2 Z_2 - \beta_2 I ZiZ_i is a d×dd \times d matrix of normal random numbers with mean 0 and covariance 1dI\frac{1}{d} I, and αi,βi∈[0,1]\alpha_i, \beta_i \in [0, 1] are coefficients that set the strength of the random part and of the diagonal. The larger β\beta is, the more prominent the diagonal.
  2. Split the query–key product into two with a truncated singular value decomposition: Write α1Z1+β1I=UΣV⊤\alpha_1 Z_1 + \beta_1 I = U \Sigma V^\top and, using only the top kk singular values, set WQ=U[:,:k] Σ[:k,:k]1/2,WK=V[:,:k] Σ[:k,:k]1/2W_Q = U_{[:, :k]}\, \Sigma_{[:k, :k]}^{1/2}, \qquad W_K = V_{[:, :k]}\, \Sigma_{[:k, :k]}^{1/2} Then WQWK⊤W_Q W_K^\top is the rank-kk matrix closest to the target. Z1Z_1 is redrawn for each head.
  3. Split the value–output projection product into two with a singular value decomposition as well: Decompose α2Z2−β2I\alpha_2 Z_2 - \beta_2 I and split it into WVW_V and WprojW_{\mathrm{proj}} so that their product equals this matrix. Here the matrices are d×dd \times d, so no rank reduction is needed.
  4. Use sinusoidal position embeddings: Instead of randomly initializing learned position embeddings, use sinusoidal positional encoding. This initialization works in combination with the position embeddings, so this step is essential.
  5. Initialize the other weights as usual: The patch embedding, MLP, and so on are unchanged.

All image experiments used α1=β1=0.7\alpha_1 = \beta_1 = 0.7 and α2=β2=0.4\alpha_2 = \beta_2 = 0.4.

Simply setting WQ=WKW_Q = W_K to the same random matrix also makes the diagonal of the product positive, because a suitably scaled matrix of normal random numbers is nearly orthogonal. With this approach, however, the ratio between diagonal and off-diagonal entries stays the same no matter how the scale of the random numbers is changed. Using a singular value decomposition lets α\alpha and β\beta be chosen separately, so the prominence of the diagonal can be set freely (Figure 3 of the paper).

Why it works

The paper considers why it works from three angles (Sections 4 and 6 of the paper).

Query and key: the attention map starts out mixing nearby tokens

If the input XX after layer normalization roughly follows a standard normal distribution and WQWK⊤=αZ+βIW_Q W_K^\top = \alpha Z + \beta I, the only terms whose mean is not 0 are XX⊤≈dIXX^\top \approx dI and the product of position embeddings PP⊤PP^\top. The initial attention map therefore has roughly the following form (Eq. (8) in the paper).

Softmax(1k(β1dI+β1PP⊤))\mathrm{Softmax}\left(\frac{1}{\sqrt{k}} \left(\beta_1 d I + \beta_1 P P^\top\right)\right)

In other words, each token attends strongly to itself and to nearby tokens with similar position embeddings. In Figure 2 of the paper, the attention maps of an untrained ViT with only this initialization resembled those of a ViT pre-trained on ImageNet. Citing prior work showing that making the attention map exactly the identity prevents gradients from flowing to the queries and keys so that nothing can be learned, the paper considers this initialization to sit at a sweet spot between the scattered maps of an untrained model and the identity. If the position embeddings are not sinusoidal, PP⊤PP^\top does not represent proximity, and this effect does not appear.

Value and output projection: an effect on the residual connection similar to LayerScale

If the attention map is close to the identity, the output of the self-attention block is roughly

Xl+XlWVWproj≈(I−β)Xl+αXlZX_l + X_l W_V W_{\mathrm{proj}} \approx (I - \beta) X_l + \alpha X_l Z

(Eqs. (10)–(13) in the paper). This shrinks the shortcut side by a factor of (1−β)(1 - \beta), which is similar in spirit to LayerScale, which shrinks residual branches with a diagonal matrix. However, because replacing it with LayerScale lowered accuracy by about 1.5%, the paper concludes that this similarity alone does not explain the effect.

Value and output projection: spatial mixing that includes negative values

The paper also experimented with adding a convolution matrix CC to self-attention. Adding γC\gamma C outside the softmax raised accuracy, but restricting CC to positive values only lowered it substantially. From this, the paper hypothesizes that the negative diagonal enables "mixing with negative weights", such as edge detection, providing a good starting point for image recognition.

As an analogy, it is like teaching a complete newcomer only the "form" of how a veteran works. The substantive knowledge (the features gained through pre-training) is not taught, but just having the form lets the newcomer improve quickly from little experience.

Experimental results

These are the results reported in the paper. All ViTs are trained from scratch.

CIFAR-10 (test accuracy, 100 epochs. Excerpt from Table 1)

WidthDepthHeadsStandard initializationMimeticDifference
9612384.75%88.84%+4.09
19212386.07%90.78%+4.71
19212686.74%91.38%+4.64
19224386.36%91.85%+5.49
38412684.40%92.17%+7.77
384121286.39%92.30%+5.91

Patch size 2, 32×32 input, AdamW (learning rate 3×10−33 \times 10^{-3}, weight decay 0.01), minibatch 512, with RandAugment and Cutout for data augmentation. The paper notes a tendency for larger models to benefit more.

Which parts matter (CIFAR-10, ViT-Tiny, test accuracy. Table 2)

ConditionAccuracy
Mimetic (all)91.38%
Random position embeddings88.70%
No initialization (sinusoidal position embeddings only)87.39%
Initialize only WQ,WKW_Q, W_K89.17%
Initialize only WV,WprojW_V, W_{\mathrm{proj}}87.23%
Make the diagonal of WVWprojW_V W_{\mathrm{proj}} positive89.65%
Transfer WQ,WK,WV,WprojW_Q, W_K, W_V, W_{\mathrm{proj}} and position embeddings from a pre-trained ViT91.15%

Removing any part lowered accuracy; all parts worked together. It was slightly more accurate than transferring the actual weights of a ViT pre-trained on ImageNet. Making the position embeddings about twice as large raised accuracy by another 0.5% or so (Figure 4).

ImageNet (ViT, patch 16, input 224. Top-1 accuracy. Table 3)

Training recipeModelMinibatchStandard initializationMimeticDifference
ResNet-style (150 epochs)ViT-Tiny64070.28%73.08%+2.8
ResNet-style (150 epochs)ViT-Tiny1,02467.80%71.92%+4.1
DeiT-style (300 epochs)ViT-Tiny1,02472.08%72.65%+0.57
DeiT-style (300 epochs)ViT-Small1,02479.83%80.36%+0.53

ViT was known not to train well with a recipe designed for ResNet, and this initialization substantially narrowed that gap. With the DeiT-style recipe, which uses strong data augmentation and long training, the improvement was about 0.5%.

Other datasets (ViT-Tiny, 100 epochs. Table 4)

DatasetStandard initializationMimeticDifference
Tiny ImageNet45.24%50.87%+5.63
CIFAR-10060.94%67.33%+6.39
SVHN96.40%96.79%+0.39

Comparison with other initializations (CIFAR-10, ViT-Tiny, test accuracy. Table 5)

T-FixupZerOLayerScale (original)LayerScale (paper's variant)Mimetic
85.38%87.41%89.90%88.68%91.38%

ZerO is applied only to the self-attention layers, and T-Fixup to both self-attention and the MLP. The two LayerScale variants are used in place of the WVWprojW_V W_{\mathrm{proj}} initialization, keeping the WQWK⊤W_Q W_K^\top initialization.

Language models (lower is better. Table 6)

TaskMetricStandard initializationMimetic
Character-level Penn Treebankbpc1.2331.210
Word-level Penn TreebankPerplexity84.8482.34
WikiText-103Perplexity28.8728.21

For language models, α1=0\alpha_1 = 0, β1=0.5\beta_1 = 0.5, and α2=β2=0.2\alpha_2 = \beta_2 = 0.2 were used. There was an improvement, but not as large as for images.

Practical caveats

This initialization is meant to be used together with sinusoidal position embeddings. With randomly initialized position embeddings, CIFAR-10 accuracy dropped from 91.38% to 88.70%, which the paper describes as "critical". Simply adding it to a model with learned position embeddings should not be expected to help.

Keep the following points in mind as well.

  • It is designed for images: The underlying observations come from pre-trained ViTs. In pre-trained GPT-2, different structures appeared, such as the value–output projection product becoming positive in deeper layers. The paper suggests that a mimetic initialization tailored further to language might do even better.
  • The coefficients were chosen on ViT-Tiny for CIFAR-10: αi,βi\alpha_i, \beta_i were set by grid search on a ViT-Tiny trained for 100 epochs on CIFAR-10. The same values also worked on ImageNet, but tuning may be needed when the model or data differs substantially.
  • A strong training recipe narrows the gap: With the DeiT-style recipe (strong data augmentation, 300 epochs), the improvement was about 0.5%.
  • Less data does not necessarily mean a bigger benefit: The paper reports that varying the amount of CIFAR-10 training data showed no relationship in which less data led to larger improvements.
  • PyTorch has no built-in version: Rewrite the weights by hand (see the implementation example below). In nn.MultiheadAttention, the query, key, and value weights are stacked vertically in in_proj_weight, stored in the output × input orientation, as in nn.Linear.

Comparison with other initializations

The table lines up initialization methods for Transformers and for whole networks, from the same angles.

MethodWhat it setsBased onTraining / dataArchitecture change
Xavier initializationWeight varianceAnalysis preserving signal varianceNot neededNone
T-FixupWeight scale (shrunk according to the number of layers)Analysis bounding update sizeNot neededRemoves layer normalization
LayerScaleDiagonal matrix on residual branches (from small values)Stabilizing deep ViTsNot neededAdds a learned diagonal matrix
GradInitPer-block scale factorsLoss after the first stepFactors learned on training dataNone
MimeticStructure of self-attention weights (diagonal of the products)Observation of pre-trained model weightsNot neededNone (assumes sinusoidal position embeddings)
Pre-trainingAll weightsTraining on large dataLarge data and computeNone

Most other initializations set the scale of the weights. Mimetic initialization differs in setting the structure of the weight matrices (whether the diagonal of the products is positive or negative).

Rough guidelines for choosing:

  • If a usable pre-trained model exists, pre-trained weights are also a candidate: Mimetic reproduces only the part of pre-training's benefit that comes from the self-attention initial values. On CIFAR-10 in the paper, transferring only the self-attention weights (91.15%) and Mimetic (91.38%) were almost the same, but the paper says this comparison tells nothing about the initial values of the patch embedding and the MLP.
  • To train ViT from scratch on small image data without pre-training, use Mimetic: Just switch to sinusoidal position embeddings and rewrite the four self-attention weights, and accuracy improves without changing the architecture.
  • To stabilize deep Transformers without normalization, use T-Fixup or similar methods: Mimetic is not an initialization for stabilizing training; it assumes an ordinary Transformer with layer normalization and residual connections.

PyTorch example

Show code
python
import math

import torch
import torch.nn as nn


@torch.no_grad()
def mimetic_init_(attn: nn.MultiheadAttention, a1: float = 0.7, b1: float = 0.7,
                  a2: float = 0.4, b2: float = 0.4) -> None:
    """Eqs. (1)–(7) of the paper. With tokens as row vectors x, make x W_Q W_K^T x^T and x W_V W_proj match the target matrices"""
    d, h = attn.embed_dim, attn.num_heads
    k = d // h
    eye = torch.eye(d)
    w = attn.in_proj_weight                      # (3d, d): W_q, W_k, W_v from top (output × input, as in nn.Linear)

    # query and key: build α1 Z1 + β1 I per head and split with the top k singular values (Z1 redrawn per head)
    for i in range(h):
        m = a1 * torch.randn(d, d) / math.sqrt(d) + b1 * eye
        u, s, vh = torch.linalg.svd(m)
        wq = u[:, :k] * s[:k].sqrt()             # W_Q:(d, k)
        wk = vh[:k].T * s[:k].sqrt()             # W_K:(d, k)、W_Q W_K^T ≈ α1 Z1 + β1 I
        w[i * k:(i + 1) * k] = wq.T              # PyTorch computes q = x W^T, so store the transpose
        w[d + i * k:d + (i + 1) * k] = wk.T

    # value and output projection: build α2 Z2 − β2 I and split into two matrices (no rank reduction)
    m = a2 * torch.randn(d, d) / math.sqrt(d) - b2 * eye
    u, s, vh = torch.linalg.svd(m)
    wv = u * s.sqrt()                            # W_V:(d, d)
    wo = s.sqrt()[:, None] * vh                  # W_proj:(d, d)、W_V W_proj = α2 Z2 − β2 I
    w[2 * d:] = wv.T
    attn.out_proj.weight.copy_(wo.T)


def sinusoidal_positions(n: int, d: int, scale: float = 1.0) -> torch.Tensor:
    """sinusoidal position embeddings (a prerequisite for this initialization). On CIFAR-10 in the paper, doubling their scale improved accuracy"""
    pos = torch.arange(n, dtype=torch.float32)[:, None]
    div = torch.exp(torch.arange(0, d, 2, dtype=torch.float32) * (-math.log(10000.0) / d))
    pe = torch.zeros(n, d)
    pe[:, 0::2] = torch.sin(pos * div)
    pe[:, 1::2] = torch.cos(pos * div)
    return scale * pe


# Usage example (ViT-Tiny-like encoder layers, Pre-LN)
d_model, n_heads, depth = 192, 3, 12
layers = nn.ModuleList(
    nn.TransformerEncoderLayer(d_model, n_heads, dim_feedforward=4 * d_model,
                               batch_first=True, norm_first=True)
    for _ in range(depth)
)
for layer in layers:
    mimetic_init_(layer.self_attn)               # rewrite only the four self-attention weights (MLP unchanged)

pos_embed = sinusoidal_positions(n=197, d=d_model)  # no learned position embeddings (class token + 14×14 patches: input 224, patch 16)

FAQ

Q. How does this differ from using the weights of a pre-trained model?
A.

Mimetic initialization does not use the weights of a pre-trained model themselves; it reproduces only the structure seen in them ("the diagonals of the products are positive / negative") from random numbers and the identity using formulas. It needs neither data nor training. In the paper's CIFAR-10 experiments, it reached almost the same accuracy (91.38%) as transferring the self-attention weights and position embeddings from a ViT pre-trained on ImageNet (91.15%).

Q. Why is the diagonal of the value–output projection product negative?
A.

The exact reason is not yet known, and the paper offers two hypotheses. One is an effect similar to LayerScale, shrinking the shortcut side of the residual connection by a factor of (1−β)(1 - \beta). The other is that it enables spatial mixing with negative weights, as in edge detection. In fact, making the diagonal positive lowered CIFAR-10 accuracy from 91.38% to 89.65%.

Q. Can it be used for language models?
A.

Yes, but the effect is smaller than for images. In the paper, word-level perplexity on Penn Treebank dropped from 84.84 to 82.34, and on WikiText-103 from 28.87 to 28.21. The weights of pre-trained GPT-2 have a different structure from ViT, so the paper says a mimetic initialization tailored to language might do even better.

References

  1. A. Trockman and J. Z. Kolter, "Mimetic Initialization of Self-Attention Layers," ICML, 2023.
  2. H. Touvron, M. Cord, A. Sablayrolles, G. Synnaeve, and H. Jégou, "Going deeper with Image Transformers," ICCV, 2021.
  3. X. S. Huang, F. Perez, J. Ba, and M. Volkovs, "Improving Transformer Optimization Through Better Initialization," ICML, 2020.
  4. PyTorch Documentation, "torch.nn.MultiheadAttention."