AI Logic

Optimizers

Shampoo

Updated:

How Shampoo works. Left: one step that updates two preconditioner matrices (left and right) from the gradient, sandwiches the gradient between their −1/4 powers, and updates the weights. Right: a bar chart comparing the number of values stored for preconditioning by full-matrix AdaGrad, Shampoo, and diagonal AdaGrad for a fully connected layer (2000, 256) and a convolutional layer (256, 3, 3, 256)

Background and Overview

Shampoo is an optimizer that exploits the fact that weights are matrices or tensors, keeping a small preconditioner matrix for each dimension and conditioning the gradient by sandwiching it between these matrices. It was published by Gupta, Koren, and Singer in 2018.

Methods that multiply the gradient by a matrix before taking a step are called preconditioned gradient methods. Examples include Newton's method (using the Hessian) and full-matrix AdaGrad (using the gradient covariance); because they can correct the step direction while accounting for relationships between parameters, they can converge faster. However, with dd parameters the preconditioner becomes d×dd \times d, which is far too large to store or compute in deep learning. As a result, AdaGrad and Adam, which use only the diagonal, have been widely used in practice.

Rather than reducing to the diagonal, Shampoo factorizes the full matrix by exploiting the shape of the parameters. For an m×nm \times n weight matrix, it keeps only two matrices: an m×mm \times m matrix representing relationships among rows, and an n×nn \times n matrix representing relationships among columns.

  • Full-matrix preconditioning: An mn×mnmn \times mn matrix, storing m2n2m^2 n^2 values, with O(m3n3)O(m^3 n^3) computation for inverses and the like
  • Shampoo: Two matrices, m×mm \times m and n×nn \times n, storing m2+n2m^2 + n^2 values, with O(m3+n3)O(m^3 + n^3) computation

According to a footnote in the paper, the name Shampoo was chosen "because it has to do with preconditioning."

Theory (Computation in One Step)

When the weight is a matrix W∈Rm×nW \in \mathbb{R}^{m \times n}, following Algorithm 1 of the paper, the following computation is performed at each step tt. The preconditioners start from L0=ϵImL_0 = \epsilon I_m and R0=ϵInR_0 = \epsilon I_n.

  1. Compute the gradient GtG_t (an m×nm \times n matrix).
  2. Add GtGt⊤G_t G_t^\top to the left preconditioner LtL_t and Gt⊤GtG_t^\top G_t to the right preconditioner RtR_t.
  3. Sandwich the gradient between Lt−1/4L_t^{-1/4} on the left and Rt−1/4R_t^{-1/4} on the right, and update the parameters.
Lt=Lt−1+GtGt⊤,Rt=Rt−1+Gt⊤GtL_t = L_{t-1} + G_t G_t^\top, \qquad R_t = R_{t-1} + G_t^\top G_t Wt+1=Wt−η Lt−1/4 Gt Rt−1/4W_{t+1} = W_t - \eta\, L_t^{-1/4}\, G_t\, R_t^{-1/4}

Lt−1/4L_t^{-1/4} is the matrix obtained by eigendecomposing the matrix, raising the eigenvalues to the −1/4-1/4 power, and reassembling it. LtL_t and RtR_t accumulate, as in AdaGrad, the sums of squares (second-order statistics) among the rows and among the columns of the gradient, respectively.

Why the −1/4-1/4 power: If WW and GG are flattened into single vectors, this update is equivalent to a gradient method whose preconditioner is the Kronecker product of Lt1/4L_t^{1/4} and Rt1/4R_t^{1/4}. The paper shows that this Kronecker product corresponds well to the full-matrix AdaGrad preconditioner (the 1/21/2 power of the gradient covariance). Using the 1/41/4 power on each side amounts to the 1/21/2 power overall, and the step size decreases at a rate of O(1/t)O(1/\sqrt{t}).

The tensor case (Algorithm 2): For a kk-dimensional tensor (convolution weights are 4D), a preconditioner HtiH^i_t of size ni×nin_i \times n_i is kept for each dimension ii, and Gt(i)G^{(i)}_t, obtained by contracting over all other dimensions, is added to it. Each dimension of the gradient is multiplied by (Hti)−1/(2k)(H^i_t)^{-1/(2k)} before the update. For a matrix (k=2k = 2) this becomes the −1/4-1/4 power and coincides with Algorithm 1.

The paper proves that for convex problems Shampoo's regret is bounded by O(T)O(\sqrt{T}). The proof uses matrix geometric means and trace inequalities, and shows that splitting the preconditioner in two still yields the same rate guarantee as full-matrix AdaGrad.

Why It Works (Structure-Aware Preconditioning)

The idea behind Shampoo is to preserve, along the shape of the weights, the relationships between parameters that diagonal preconditioning throws away.

  • Diagonal preconditioning (AdaGrad, Adam): Treats each parameter separately and adjusts the step size only by the gradient magnitude. It does not consider directions in which parameters move together.
  • Full-matrix preconditioning: Considers the relationships between all pairs of parameters, but cannot be stored or computed for large models.
  • Shampoo: Keeps separately the relationships among parameters in the same row (LtL_t) and among parameters in the same column (RtR_t). For a fully connected layer, these correspond to the relationships among output units and among input units.

The right side of the figure at the top shows the number of values stored for preconditioning, computed for the largest layer shapes appearing in the paper's experiments. For the fully connected layer (2000,256)(2000, 256), full-matrix preconditioning needs about 2.6×10112.6 \times 10^{11} values, whereas Shampoo needs about 4.1×1064.1 \times 10^6. For the 4D convolution weight (256,3,3,256)(256, 3, 3, 256), the per-dimension matrices are small (including 3×33 \times 3), so Shampoo needs about 1.3×1051.3 \times 10^5 values, fewer than the number of parameters itself (about 5.9×1055.9 \times 10^5, the same as diagonal preconditioning).

The paper also explains the difference from K-FAC, which likewise factorizes the preconditioner as a Kronecker product. K-FAC approximates the Fisher information matrix of a neural network viewed as a generative model, and depends heavily on the model structure and the form of backpropagation. Shampoo uses only gradients and is a more general method that can be applied without knowing the model structure.

Experimental Results

The paper replaces only the optimizer in existing TensorFlow training code with Shampoo and compares results on CIFAR-10/100 image classification and LM1B language modeling. The minibatch size is 128. The baselines are AdaGrad, Adam, and momentum, with learning rates chosen from 10 values between 0.01 and 10.0.

  • ResNet-32 and an Inception-style network on CIFAR-10: Shampoo's training loss decreased faster than the baselines (Figure 2 of the paper).
  • 55-layer ResNet on CIFAR-100 (without batch normalization): Likewise, Shampoo reduced the loss fastest (Figure 3).
  • Attention model (Transformer) on LM1B: Shampoo was used with its default learning rate η=1.0\eta = 1.0, while the learning rates of the other methods were searched. Shampoo reduced the test log-perplexity fastest (Figure 4).

The paper presents its results as learning-curve figures and has no table of final accuracy values. What it does report numerically is the number of steps per second (Table 1 of the paper, Tesla K40 GPU, batch size 128).

Dataset (model)SGDAdamAdaGradShampoo
CIFAR-10 (ResNet-32)2.1842.1842.1972.151
CIFAR-10 (Inception)3.6383.6673.6823.506
CIFAR-100 (ResNet-55)1.2101.2031.2101.249
LM1B (Attention)4.9194.8714.9083.509

Although each step involves more computation, the actual speed is not much different from the other methods, and for ResNet-55 it is even faster.

The paper adds two techniques to improve performance.

  • Computing the preconditioner roots less often: Lt−1/4L_t^{-1/4} and the like were recomputed only once every 20–100 steps. This had almost no effect on accuracy and reduced the time per step.
  • Adding momentum: Using a moving average of gradients (coefficient 0.9) slightly improved convergence.

Practical Considerations

The −1/4-1/4 power of the preconditioner (the −1/(2k)-1/(2k) power for tensors) requires a matrix decomposition, which becomes expensive for large dimensions. The paper's implementation computes it with singular value decomposition and automatically switches to diagonal preconditioning for any dimension larger than about 1200. For layers with extremely large dimensions, such as embedding layers with large vocabularies, this fallback and computing roots less often are essential.

  • Not included in PyTorch's torch.optim: The paper's implementation is in TensorFlow. To use it in PyTorch, use an external implementation or write a small implementation like the code example below.
  • Preconditioning is per weight tensor: The paper's implementation treats each tensor in the model separately. The preconditioner is block-diagonal by tensor, and relationships between parameters in different tensors are not considered.
  • Compute roots less often: The paper reports that computing once every 20–100 steps was sufficient. Computing every step is slow.
  • ϵ\epsilon stabilizes the inverse: Since the preconditioners start from L0=ϵIL_0 = \epsilon I, the −1/4-1/4 power does not blow up even in directions with few gradients.
  • Watch numerical precision: Matrix decompositions tend to become unstable at low precision (such as half precision), so it is safer to keep the preconditioners in high precision.

Comparison with Other Optimizers

The table below arranges optimizers by how they precondition (the weight is an m×nm \times n matrix).

MethodPreconditioner formValues stored for preconditioningPreconditioner computationRelationships between parameters
SGDNone0NoneNot considered
AdaGrad (diagonal), AdamDiagonalmnmnElementwiseNot considered
Full-matrix AdaGradFull mn×mnmn \times mn matrixm2n2m^2 n^2O(m3n3)O(m^3 n^3)All pairs
K-FACPer-layer Fisher matrix approximated by a Kronecker productTwo small matricesInverses of small matricesWithin-layer relationships (depends on model structure)
ShampooTwo matrices for rows and columns (Kronecker product)m2+n2m^2 + n^2O(m3+n3)O(m^3 + n^3)Among rows and among columns
AdafactorSecond moment factored into row and column sums (still diagonal)m+nm + nElementwiseNot considered (aims to save memory)

Rough guidelines for choosing are as follows.

  • If you want faster convergence per step and have compute to spare, use Shampoo: It provides preconditioning that accounts for relationships between parameters at a practical cost.
  • If you value ease of implementation and tuning, use Adam or AdamW: Only elementwise computation is needed.
  • If you want to reduce memory, use Adafactor: In contrast to Shampoo, it saves memory by compressing the second moment into row and column sums.

PyTorch example

Show code
python
import torch
import torch.nn as nn


def matrix_power(mat, p):
    # p-th power of a symmetric positive definite matrix (eigendecompose and raise the eigenvalues to p)
    vals, vecs = torch.linalg.eigh(mat)
    return vecs @ torch.diag(vals.clamp_min(1e-12) ** p) @ vecs.T


class Shampoo(torch.optim.Optimizer):
    # Algorithm 1 of the paper (for matrix weights). 1D parameters (biases) are updated with diagonal AdaGrad
    def __init__(self, params, lr=1.0, eps=1e-4, update_every=20):
        super().__init__(params, dict(lr=lr, eps=eps, update_every=update_every))

    @torch.no_grad()
    def step(self):
        for group in self.param_groups:
            lr, eps, every = group["lr"], group["eps"], group["update_every"]
            for W in group["params"]:
                if W.grad is None:
                    continue
                G = W.grad
                st = self.state[W]
                if W.dim() == 2:
                    m, n = G.shape
                    if not st:
                        st["t"] = 0
                        st["L"] = eps * torch.eye(m)            # L_0 = εI_m
                        st["R"] = eps * torch.eye(n)            # R_0 = εI_n
                    st["t"] += 1
                    st["L"] += G @ G.T                          # L_t = L_{t-1} + G G^T
                    st["R"] += G.T @ G                          # R_t = R_{t-1} + G^T G
                    if st["t"] % every == 1 or every == 1:      # compute roots less often (every 20–100 steps in the paper)
                        st["L_root"] = matrix_power(st["L"], -0.25)
                        st["R_root"] = matrix_power(st["R"], -0.25)
                    W -= lr * st["L_root"] @ G @ st["R_root"]   # W ← W − η L^{-1/4} G R^{-1/4}
                else:
                    if not st:
                        st["H"] = torch.full_like(W, eps)
                    st["H"] += G * G
                    W -= lr * G / st["H"].sqrt()


model = nn.Sequential(nn.Linear(64, 32), nn.ReLU(), nn.Linear(32, 10))
optimizer = Shampoo(model.parameters(), lr=0.1)

model.train()
for step in range(3):
    x = torch.randn(128, 64)                                    # minibatch of 128, as in the paper
    y = torch.randint(0, 10, (128,))
    loss = nn.functional.cross_entropy(model(x), y)
    optimizer.zero_grad()
    loss.backward()
    optimizer.step()

FAQ

Q. What is the difference between Shampoo and Adam?
A.

Adam uses diagonal preconditioning that treats each parameter separately. Shampoo keeps two matrices, LtL_t and RtR_t, representing relationships among the rows and among the columns of the weight matrix, and conditions the gradient by sandwiching it as Lt−1/4GtRt−1/4L_t^{-1/4} G_t R_t^{-1/4}. Because it also accounts for relationships between parameters, it requires more computation.

Q. Why the −1/4 power?
A.

Because the Kronecker product of the 1/41/4 powers on the left and right corresponds to the full-matrix AdaGrad preconditioner (the 1/21/2 power of the gradient covariance). With this choice the paper proves an O(T)O(\sqrt{T}) regret bound, and the step size decreases as O(1/t)O(1/\sqrt{t}). For a kk-dimensional tensor, each dimension is raised to the −1/(2k)-1/(2k) power.

Q. Doesn't the computation become heavy?
A.

Computing the preconditioner roots is expensive, but the paper recomputed them only once every 20–100 steps and switched overly large dimensions to diagonal preconditioning. As a result, the number of steps per second was nearly the same as for SGD and Adam (about 70% on LM1B).

References

  1. V. Gupta, T. Koren, and Y. Singer, "Shampoo: Preconditioned Stochastic Tensor Optimization," arXiv:1802.09568, 2018.
  2. J. Duchi, E. Hazan, and Y. Singer, "Adaptive Subgradient Methods for Online Learning and Stochastic Optimization," Journal of Machine Learning Research, 12, 2011.