AI Logic

Optimizers

LAMB

Updated:

How LAMB works. The left shows one step per layer: weight decay is added to the update direction computed from the same moments as Adam, and its size is equalized by the ratio of that direction's norm to the weight norm (the trust ratio) before updating (the difference from Adam is marked with a yellow frame). The right is a graph comparing LAMB and LARS on SQuAD F1 in BERT pre-training as the batch size grows from 512 to 32K (LARS diverges at 32K)

Background and overview

LAMB is an optimizer that normalizes the Adam update to unit size per layer and then scales it by the size of that layer's weights. You et al. (Google) published it in 2019 (ICLR 2020). It is known for scaling BERT pre-training up to a batch size of 32K (about 30,000) without losing accuracy, cutting training time from 3 days to 76 minutes.

To train large models quickly, more machines are added for data-parallel training, and the batch used for each update is made larger. But when the batch is enlarged and the learning rate is raised along with it, training tends to become unstable. One answer to this problem was LARS, which sets the learning rate per layer from the ratio of the norms (sizes) of the weights and the gradients, making it possible to train ResNet-50 in minutes. According to the paper, however, LARS does not work well on models that use attention, such as BERT, and its effectiveness varies by task.

LAMB applies LARS's idea of "matching each layer's update size to its weight size" to Adam instead of SGD with momentum (SGD). It therefore adjusts the update size in two stages.

  • Per-element adjustment (same as Adam): divide by the average of squared gradients, varying the step size for each parameter element.
  • Per-layer adjustment (same idea as LARS): match the size of the whole layer's update to the size of that layer's weights.

As an analogy, it is like setting the same cap for every layer on "what fraction of the current weights may move in one update". Layers with very large gradients and layers with small ones move by the same proportion, so no single layer runs wild even with a large learning rate.

Theory (one step of computation)

At each training step tt, LAMB performs the following computation (Algorithm 2 of the paper). Steps 1 to 3 are applied per parameter element, and steps 4 and 5 per layer ii. θ(i)\theta^{(i)} denotes the parameters of layer ii (x(i)x^{(i)} in the paper).

  1. Compute the gradient gtg_t on a large mini-batch.
  2. As in Adam, update the first moment mtm_t and the second moment vtv_t with exponential moving averages and apply bias correction.
  3. Compute Adam's update direction rtr_t and add the weight decay term λθt\lambda\theta_t.
  4. For each layer, compute the ratio of the weight norm to the norm of the direction from step 3 (the trust ratio).
  5. Normalize the direction to unit size per layer, multiply by the trust ratio and the learning rate, and update.

The equations for step 2 are the same as Adam's, starting from m0=v0=0m_0 = v_0 = 0.

mt=β1mt−1+(1−β1) gt,vt=β2vt−1+(1−β2) gt2,m^t=mt1−β1t,v^t=vt1−β2tm_t = \beta_1 m_{t-1} + (1-\beta_1)\, g_t, \qquad v_t = \beta_2 v_{t-1} + (1-\beta_2)\, g_t^2, \qquad \hat{m}_t = \frac{m_t}{1-\beta_1^t}, \qquad \hat{v}_t = \frac{v_t}{1-\beta_2^t}

The equations for steps 3 to 5 are as follows. ηt\eta_t is the learning rate, λ\lambda is the weight decay strength, and ∥⋅∥\lVert \cdot \rVert is the L2 norm over all elements of the layer.

rt=m^tv^t+ϵ,θt+1(i)=θt(i)−ηt ϕ(∥θt(i)∥)∥rt(i)+λθt(i)∥ (rt(i)+λθt(i))r_t = \frac{\hat{m}_t}{\sqrt{\hat{v}_t} + \epsilon}, \qquad \theta^{(i)}_{t+1} = \theta^{(i)}_t - \eta_t\, \frac{\phi(\lVert \theta^{(i)}_t \rVert)}{\lVert r^{(i)}_t + \lambda \theta^{(i)}_t \rVert}\, \left(r^{(i)}_t + \lambda \theta^{(i)}_t\right)

ϕ\phi is a function that adjusts the weight norm; the paper states that ϕ(z)=min⁡(max⁡(z,γl),γu)\phi(z) = \min(\max(z, \gamma_l), \gamma_u) (clamping the norm between a lower bound γl\gamma_l and an upper bound γu\gamma_u) works well in practice. The defaults given in the paper's appendix are β1=0.9\beta_1 = 0.9, β2=0.999\beta_2 = 0.999, ϵ=10−6\epsilon = 10^{-6}, and λ=0.01\lambda = 0.01.

With ϕ(z)=z\phi(z) = z, the size of one update is ηt∥θt(i)∥\eta_t \lVert \theta^{(i)}_t \rVert. In other words, however large or small the gradient is, the update is set to "weight size × learning rate". The paper explains that this ratio ∥θ∥/∥g∥\lVert \theta \rVert / \lVert g \rVert can be interpreted as an estimate of the inverse of the gradient's Lipschitz constant (how sharply the gradient changes). Steeper layers move less, and flatter layers move more.

Why sizes are equalized per layer

As a general approach to adapting for large batches, the paper proposes applying the following two changes per layer to the update utu_t of a base method (SGD or Adam). LARS uses SGD with momentum as the base method, and LAMB uses Adam.

  • Normalize the update to unit size per layer: replace utu_t with ut/∥ut∥u_t / \lVert u_t \rVert. Because only the direction is used and the gradient's magnitude is ignored, it is robust to layers whose gradients are extremely large (exploding gradients) or extremely small (stalled). Discarding the magnitude introduces a bias into the update, but the paper states that it can be shown that with large batches the gradient direction is well preserved and this bias is small.
  • Multiply the learning rate per layer by ϕ(∥θt∥)\phi(\lVert \theta_t \rVert): this makes the update size comparable to the parameter size. The paper states that this often speeds up convergence in deep networks.

Because LAMB applies both changes to Adam, it adapts in two stages: per-element adjustment (dividing by the second moment) and per-layer adjustment (equalizing norms). The paper also notes that with β1=β2=0\beta_1 = \beta_2 = 0, LAMB becomes SignSGD, which uses only the sign of the gradient, multiplied by the square root of the number of elements in the layer.

The paper shows that on general non-convex problems, LARS and LAMB converge to a stationary point (a point where the gradient is 0) (Theorems 2 and 3). The convergence rate of SGD is governed by the value of the steepest layer (L∞L_\infty), whereas that of LARS and LAMB is governed by the average over layers (LavgL_{\text{avg}}). According to the paper, when gradients are sufficiently dense (many elements are nonzero), this can be considerably faster than SGD.

Experimental results

The paper tested LAMB on BERT pre-training and on ResNet-50 on ImageNet. β1=0.9\beta_1 = 0.9 and β2=0.999\beta_2 = 0.999 were fixed, and only the learning rate was tuned. The learning rate follows polynomial decay ηt=η0(1−t/T)\eta_t = \eta_0 (1 - t/T), and when the batch is enlarged, it is set automatically by making the learning rate proportional to the square root of the batch size and the length of warmup proportional to the number of epochs. The compared methods (Adam, AdaGrad, AdamW, LARS) were tuned by grid search.

BERT (BERT-Large; F1 on the SQuAD v1.1 development set; all with the same number of epochs; Table 1 of the paper).

MethodBatch sizeUpdatesF1TPUsTraining time
Baseline (public BERT model)5121000k90.3951681.4 hours
LAMB5121000k91.7521682.8 hours
LAMB4K125k91.137128693.6 minutes
LAMB16K3125091.345512200.0 minutes
LAMB32K1562591.4751024101.2 minutes
LAMB64K / 32K859990.584102476.19 minutes

The last row trains the first phase (sequence length 128) with a batch of 64K and the second phase (sequence length 512) with 32K, re-warming the learning rate from 0 at the start of the second phase.

Comparison with LARS (also F1; Table 2 of the paper; the right side of the figure at the top).

Batch size5121K2K4K8K16K32K
LARS90.71790.36990.74890.53790.54889.589Diverged
LAMB91.75291.76191.94691.13791.26391.34591.475

ResNet-50 (ImageNet, batch 16K, top-1 accuracy after 90 epochs; Table 3 of the paper). "+" adds 5 epochs of warmup and dividing the learning rate by 10 at epochs 30, 60, and 80. The momentum value is reported by Goyal et al. (2017).

AdaGrad / +Adam / +AdamW / +SGD with momentumLAMB
55.38% / 72.01%66.04% / 73.48%67.27% / 73.07%75.20%76.66%
  • BERT trained at batch 32K with higher F1 than the baseline: the paper reports that at 32K, training time dropped from 3 days to about 100 minutes, a 49.1× speedup with 64× the compute (76.7% efficiency).
  • AdamW and LARS did not scale to large batches: AdamW did not reach the target F1 at batch 16K (88.1 vs. 90.4), and at 64K / 32K it produced no reasonable results even with tuning. LARS fell below the baseline at 16K and diverged at 32K.
  • Even as an adaptive method, it reached the target accuracy on ResNet-50: adaptive methods such as Adam did not reach the target (about 76.3%) even with tuning, but LAMB did. At batch 32K, LAMB reached 76.4% and LARS 76.3%; at 2K, LAMB 77.11% and LARS 76.6%, slightly ahead of LARS.

In the appendix, the paper also reports that on CIFAR-10 with an ordinary batch size (512) (DavidNet, 24 epochs), test accuracy was AdaGrad 90.74%, Adam 92.25%, AdamW 92.71%, momentum 93.72%, and LAMB 94.08%.

Practical caveats

PyTorch has no built-in LAMB (there is no Lamb in torch.optim). Write it yourself as in the implementation example below, or use an external library. Implementations differ in whether ϕ\phi has upper and lower bounds (the TensorFlow Addons implementation released by the paper's authors uses ϕ(z)=z\phi(z) = z), whether the trust ratio is set to 1 when a norm is 0, whether biases and Layer Normalization parameters are excluded from weight decay and per-layer adjustment, and whether bias correction is applied. When reproducing results from the paper or other implementations, check these settings too.

  • Combine it with warmup that starts from a small learning rate: all of the paper's experiments use warmup. The larger the batch, the larger the warmup fraction (1/5 of the total for BERT at batch 32K).
  • The "layer" unit is each parameter tensor: typical implementations treat each layer's weight and bias as separate tensors and compute the norm per tensor. Results change depending on the unit of normalization, so check how the implementation decides it.
  • Bias correction can be omitted: according to the paper's appendix, Adam's bias correction has an effect similar to learning rate warmup, and removing it from LAMB did not lower accuracy on BERT or ImageNet.
  • The type of norm matters little: the paper's appendix also tried norms other than L2, and the difference in ImageNet validation accuracy was less than 0.1%.
  • With large batches, look at accuracy rather than validation loss: the paper states that in large-batch training, low validation loss did not necessarily mean high accuracy, so it compared methods by accuracy and F1.

Comparison with other optimizers

The table lists LAMB and closely related optimizers from the same viewpoints.

MethodBase updateUnit at which the learning rate variesExtra memoryMain uses
SGD (with momentum)Average of gradientsDoes not varyOne copy of the parametersCNNs with ordinary batches
LARSSGD with momentumPer layerOne copy of the parametersCNNs with very large batches
Adam, AdamWAverage of gradients ÷ square root of the average of squaresPer elementTwo copies of the parametersStandard for many models
LAMBAdam (with weight decay)Per element + per layerTwo copies of the parametersTransformers and CNNs with very large batches

A rough guide for choosing:

  • When training a Transformer with large batches of thousands or more, consider LAMB: in the paper, LAMB kept its accuracy even at batch sizes where AdamW and LARS failed.
  • When training CNNs with large batches, both LARS and LAMB are candidates: on ResNet-50, the difference between them was small, with LAMB only slightly ahead.
  • For ordinary batch sizes, AdamW is fine: the paper says LAMB can also be used with small batches, but there is no built-in implementation and the settings vary a lot, so weigh the benefit against the effort.
  • It can be combined with other improvements: the paper's appendix tries N-LAMB, which gives the first moment the same form as Nadam, and NN-LAMB, which uses the same form for the second moment too, and reports accuracy comparable to LAMB on ResNet-50 at batch 32K.

PyTorch example

Show code
python
import torch
import torch.nn as nn


class LAMB(torch.optim.Optimizer):
    """A small implementation following Algorithm 2 of the paper. The trust ratio is computed per parameter tensor (each layer's weight and bias).
    Passing phi_bounds=(γ_l, γ_u) gives φ(z) = min(max(z, γ_l), γ_u); None gives φ(z) = z."""

    def __init__(self, params, lr=1e-3, betas=(0.9, 0.999), eps=1e-6, weight_decay=0.01,
                 phi_bounds=None):
        defaults = dict(lr=lr, betas=betas, eps=eps, weight_decay=weight_decay, phi_bounds=phi_bounds)
        super().__init__(params, defaults)

    @torch.no_grad()
    def step(self):
        for group in self.param_groups:
            beta1, beta2 = group["betas"]
            lr, eps, lam, bounds = group["lr"], group["eps"], group["weight_decay"], group["phi_bounds"]
            for p in group["params"]:
                if p.grad is None:
                    continue
                state = self.state[p]
                if not state:
                    state["t"] = 0
                    state["m"] = torch.zeros_like(p)
                    state["v"] = torch.zeros_like(p)
                state["t"] += 1
                t, m, v, g = state["t"], state["m"], state["v"], p.grad
                m.mul_(beta1).add_(g, alpha=1 - beta1)               # first moment
                v.mul_(beta2).addcmul_(g, g, value=1 - beta2)        # second moment
                m_hat = m / (1 - beta1 ** t)                         # bias correction
                v_hat = v / (1 - beta2 ** t)
                update = m_hat / (v_hat.sqrt() + eps) + lam * p      # r_t + λθ (Adam direction + weight decay)
                w_norm = p.norm()
                if bounds is not None:
                    w_norm = w_norm.clamp(bounds[0], bounds[1])      # φ(‖θ‖)
                u_norm = update.norm()
                # Trust ratio φ(‖θ‖) / ‖r + λθ‖. Set to 1 when a norm is 0 (e.g., biases initialized to 0); an implementation choice not in the paper
                trust = w_norm / u_norm if (w_norm > 0 and u_norm > 0) else torch.tensor(1.0)
                p.sub_(lr * trust * update)


# Usage: biases and LayerNorm parameters are often excluded from weight decay (a common implementation setting, not in the paper)
model = nn.Sequential(nn.Linear(128, 512), nn.GELU(), nn.LayerNorm(512), nn.Linear(512, 10))
decay = [p for n, p in model.named_parameters() if p.ndim >= 2]
no_decay = [p for n, p in model.named_parameters() if p.ndim < 2]
optimizer = LAMB([{"params": decay, "weight_decay": 0.01},
                  {"params": no_decay, "weight_decay": 0.0}], lr=2e-3)

# Learning rate: after warmup, decrease as η_t = η_0 (1 − t/T) (the same form as the paper's experiments)
total_steps, warmup_steps = 10000, 1000
scheduler = torch.optim.lr_scheduler.LambdaLR(
    optimizer, lambda s: (s + 1) / warmup_steps if s < warmup_steps else max(0.0, 1 - s / total_steps))
criterion = nn.CrossEntropyLoss()

x = torch.randn(4096, 128)                         # large mini-batch (dummy)
y = torch.randint(0, 10, (4096,))
loss = criterion(model(x), y)
optimizer.zero_grad()
loss.backward()
optimizer.step()
scheduler.step()

FAQ

Q. How do LAMB and LARS differ?
A.

They share the idea of matching each layer's update size to its weight size, but differ in the base method. LARS normalizes the update of SGD with momentum per layer, while LAMB normalizes the Adam update (divided by the second moment) per layer. LAMB therefore adjusts the step size in two stages, per element and per layer. In the paper's BERT training, LARS diverged at batch 32K, while LAMB kept its accuracy.

Q. With LAMB, can the batch size be made as large as desired?
A.

No. Even in the paper, it is combined with other settings, such as making the learning rate proportional to the square root of the batch size and lengthening warmup. The paper also reports that for BERT, increasing the batch from 64K to 131072 did not make training faster. How large the batch can go depends on the model and the task.

Q. What is the trust ratio?
A.

It is the per-layer ϕ(∥θ∥)/∥r+λθ∥\phi(\lVert \theta \rVert) / \lVert r + \lambda\theta \rVert, which, after normalizing the update direction to unit size, determines how far to move relative to the weight size. The paper's appendix shows that in ResNet-50 training this ratio differs greatly between layers, and explains that LAMB uses the trust ratio to speed up learning in slow-learning layers.

References

  1. Y. You, J. Li, S. Reddi, J. Hseu, S. Kumar, S. Bhojanapalli, X. Song, J. Demmel, K. Keutzer, and C.-J. Hsieh, "Large Batch Optimization for Deep Learning: Training BERT in 76 minutes," ICLR, 2020.
  2. Y. You, I. Gitman, and B. Ginsburg, "Large Batch Training of Convolutional Networks," arXiv:1708.03888, 2017.
  3. P. Goyal, P. Dollár, R. Girshick, P. Noordhuis, L. Wesolowski, A. Kyrola, A. Tulloch, Y. Jia, and K. He, "Accurate, Large Minibatch SGD: Training ImageNet in 1 Hour," arXiv:1706.02677, 2017.
  4. TensorFlow Addons, "tfa.optimizers.LAMB" (the implementation referenced by the paper), GitHub.