AI Logic

Optimizers

LARS

Updated:

How LARS works. The left side shows one step: for each layer, a local learning rate is computed from the weight and gradient norms, multiplied by the global learning rate, and used to update the momentum and weights. The right side is a bar chart showing that the ratio of weight norm to gradient norm in AlexNet-BN varies widely across layers, from 5.76 to 1345

Background and Overview

LARS (Layer-wise Adaptive Rate Scaling) is an optimizer that sets a learning rate for each layer from the ratio of the weight norm (magnitude) to the gradient norm. It is used with momentum SGD, multiplying in this per-layer learning rate. Proposed by You, Gitman, and Ginsburg in 2017, it showed that ResNet-50 can be trained with a batch size of 32K (about 32,768) with almost no loss in accuracy.

To speed up training of large networks, more machines are added and the model is trained with data parallelism. More machines also mean a larger batch per update. For the same number of epochs, multiplying the batch by kk reduces the number of updates to 1/k1/k, so the standard practice at the time was "linear scaling", which also multiplies the learning rate by kk, combined with warmup, which raises the learning rate gradually at the start. However, when the authors tried this on AlexNet, raising the learning rate beyond a batch of 2K made training diverge, and at a batch of 8K the accuracy dropped from 58% to 44.8%.

The authors noticed that early in training, the ratio of the weight norm to the gradient norm, ∥w∥/∥∇L(w)∥\lVert w\rVert / \lVert \nabla L(w)\rVert, differs by more than 200x across layers. With a single global learning rate, matching the layers with a small ratio leaves the layers with a large ratio barely moving, while matching the layers with a large ratio makes the update exceed the weights in the layers with a small ratio, causing divergence. LARS stabilizes training at large learning rates by equalizing, per layer, "how far to move in one step relative to the size of the weights."

Theory (One Step of the Computation)

At each training step tt, LARS performs the following computation for each layer ll (Algorithm 1 in the paper, an example with weight decay, momentum, and a polynomially decaying learning rate). The paper's tables treat the weights and biases of each layer separately.

  1. Compute the gradient gtl=∇L(wtl)g^l_t = \nabla L(w^l_t) of the weights wtlw^l_t of layer ll on a mini-batch.
  2. Set the global learning rate γt\gamma_t with polynomial decay (power 2). γ0\gamma_0 is the initial learning rate and TT is the total number of steps. γt=γ0(1−tT)2\gamma_t = \gamma_0 \left(1 - \frac{t}{T}\right)^2
  3. Compute the per-layer local learning rate λl\lambda^l from the weight norm and the gradient norm (Eq. (6) in the paper). η\eta is the trust coefficient and β\beta is the weight decay strength. λl=η×∥wtl∥∥gtl∥+β∥wtl∥\lambda^l = \eta \times \frac{\lVert w^l_t \rVert}{\lVert g^l_t \rVert + \beta \lVert w^l_t \rVert}
  4. Multiply the global and local learning rates and update the momentum vlv^l. mm is the momentum coefficient. vt+1l=m vtl+γt+1 λl(gtl+β wtl)v^l_{t+1} = m\, v^l_t + \gamma_{t+1}\, \lambda^l \left(g^l_t + \beta\, w^l_t\right)
  5. Update the weights. wt+1l=wtl−vt+1lw^l_{t+1} = w^l_t - v^l_{t+1}

The paper's experiments use η=0.001\eta = 0.001, m=0.9m = 0.9, and β=0.0005\beta = 0.0005 (AlexNet) or 0.00010.0001 (ResNet-50).

Without weight decay (β=0\beta = 0), the local learning rate in step 3 is λl=η∥wl∥/∥gl∥\lambda^l = \eta \lVert w^l \rVert / \lVert g^l \rVert. The magnitude of a single update without momentum, γλlgl\gamma\lambda^l g^l, becomes γ η ∥wl∥\gamma\,\eta\,\lVert w^l \rVert: a fixed fraction of the weight magnitude, regardless of the gradient magnitude. η\eta expresses "how much the layer's weights can be trusted to change in one update." Because update sizes are equalized even in layers with extremely small or large gradients, the paper notes that it also partially mitigates vanishing gradients and exploding gradients.

Why Use a Different Learning Rate per Layer

The right side of the figure at the top shows ∥w∥/∥∇L(w)∥\lVert w\rVert / \lVert \nabla L(w)\rVert for the weights of each layer at the first update of AlexNet with Batch Normalization (AlexNet-BN), from Table 2 of the paper. It is 5.76 in the first convolutional layer (conv1) but 1345 in the first fully connected layer (fc6), a difference of more than 200x.

Plain SGD updates all layers with the same learning rate γ\gamma as w←w−γ∇L(w)w \leftarrow w - \gamma \nabla L(w).

  • Layers where the learning rate is too large: when the update size ∥γ∇L(w)∥\lVert \gamma \nabla L(w) \rVert exceeds the weight size ∥w∥\lVert w \rVert, training can diverge. For conv1, with a ratio of 5.76, this happens once γ\gamma exceeds 5.76.
  • Layers where the learning rate is too small: for fc6, with a ratio of 1345, the same γ\gamma barely changes the weights in one step.

Warmup starts every layer at a small, safe learning rate and raises it once the weights have grown. LARS addresses the problem directly by using the ratio itself as the local learning rate, matching the update size to the weight size in each layer.

The paper gives two differences from other adaptive methods such as Adam and RMSprop.

  • The learning rate is set per layer, not per weight: the paper states that this improves stability.
  • The update size is set relative to the weight norm: this makes the training speed easier to control.

The paper also reports that this ratio is large early in training and drops sharply within a few epochs (Figure 2). The local learning rate of LARS also varies widely with the layer and the batch size.

Experimental Results

The paper compared top-1 accuracy on ImageNet image classification as the batch size grows. All runs use SGD with momentum 0.9 and a polynomial (power 2) learning rate decay.

AlexNet-BN. "Without LARS" uses the best learning rate found for each batch size (no warmup).

Batch sizeWithout LARSWith LARS (5-epoch warmup)
51260.2%60.2%
4K58.9%60.4%
8K58.0%60.1%
16K—59.3%
32K—57.8%

For AlexNet (without Batch Normalization), without LARS the accuracy fell to 53.1% at a batch of 4K and 44.8% at 8K even with linear scaling and warmup (58.8% at a batch of 512). With LARS it reached 58.5% at 4K, 58.2% at 8K, and 55.0% at 16K.

ResNet-50 (90 epochs, weight decay 0.0001, 5-epoch warmup).

Batch sizeTraining methodLearning rate γ\gammaAccuracy
256SGD (baseline)0.273.0%
8KLARS0.672.7%
16KLARS2.573.0%
32KLARS2.972.3%
  • ResNet-50 stays close to the baseline accuracy even at a batch of 32K: the paper reports a drop of only 0.7% from the baseline.
  • The range of good learning rates is wide: for AlexNet-BN at a batch of 16K, learning rates from 13 to 22 gave almost the same accuracy (about 59.3%).
  • At even larger batches, longer training recovers accuracy: AlexNet-BN at a batch of 32K reached 57.8% after 100 epochs, but 59.2% after 125 epochs and 59.9% after 200 epochs. The paper explains that with a very large batch the gradient is already close to the true gradient, so increasing the batch adds little information.

The paper notes that its 73.0% baseline is lower than the best published value (about 75%) because it uses minimal data augmentation during training and evaluates with a single model and a single center crop at test time.

Practical Considerations

PyTorch has no built-in LARS (there is no LARS in torch.optim). Write it yourself as in the implementation example below, or use an external library. Implementations differ slightly in the local learning rate formula (whether β∥w∥\beta\lVert w\rVert is in the denominator), where weight decay is applied, and which parameters LARS is applied to, so check the formula itself when reproducing the settings of the paper or another implementation.

  • Combine it with warmup: all LARS experiments in the paper use it together with warmup (2 to 5 epochs). LARS alone does not make warmup unnecessary.
  • The global learning rate becomes much larger than for plain SGD: the local learning rate λl\lambda^l is small because it is multiplied by η=0.001\eta = 0.001, so the global learning rate γ\gamma takes large values of 0.6 to 23 in the paper's experiments. Do not reuse the learning rate from plain SGD.
  • With too large a batch, accuracy drops for the same number of epochs: for AlexNet-BN, accuracy fell from 60.2% to 57.8% at a batch of 32K. More epochs recover it, but at the cost of more computation.
  • The benefit is small for small batches: the purpose of LARS is to allow large learning rates with large batches. If the batch is small and plain SGD trains stably, there is little reason to use it.

Comparison with Other Optimizers

The table lines up LARS and closely related optimizers from the same perspectives.

MethodUnit of learning rate adaptationHow the step size is setExtra memoryTypical use
SGD (with momentum)None (one global rate)Learning rate × gradientOne copy of the parametersCNNs at ordinary batch sizes
LARSPer layerWeight norm ÷ gradient normOne copy of the parametersCNNs at very large batch sizes, self-supervised learning
AdaGradPer parameterSum of squared gradientsOne copy of the parametersLinear models with many sparse features
Adam / AdamWPer parameterMoving average of squared gradientsTwo copies of the parametersThe default for many models

Rough guidelines for choosing:

  • Consider LARS when adding machines pushes the batch to several thousand or more: it helps when plain SGD becomes unstable even with linear scaling and warmup.
  • At ordinary batch sizes, momentum SGD or AdamW is enough: the benefit of LARS is small relative to the extra effort.
  • It is also used in self-supervised learning: for example, SimCLR trains with a batch size of 4096, uses LARS for all batch sizes, and sets the learning rate to 0.3×BatchSize/2560.3 \times \text{BatchSize}/256 (4.8 at a batch of 4096) and weight decay to 10−610^{-6}. The SimCLR paper reports that with LARS, scaling the learning rate with the square root of the batch size can work better.

PyTorch example

Show code
python
import torch
import torch.nn as nn


class LARS(torch.optim.Optimizer):
    """A minimal implementation following Algorithm 1 of the paper (with weight decay and momentum).
    Computes a local learning rate for each parameter tensor (each layer's weight and bias)."""

    def __init__(self, params, lr, momentum=0.9, weight_decay=5e-4, eta=0.001):
        defaults = dict(lr=lr, momentum=momentum, weight_decay=weight_decay, eta=eta)
        super().__init__(params, defaults)

    @torch.no_grad()
    def step(self):
        for group in self.param_groups:
            lr, m, beta, eta = group["lr"], group["momentum"], group["weight_decay"], group["eta"]
            for w in group["params"]:
                if w.grad is None:
                    continue
                g = w.grad
                w_norm, g_norm = w.norm(), g.norm()
                # Local learning rate λ = η‖w‖ / (‖g‖ + β‖w‖) (Eq. (6))
                # Use 1 when a norm is 0 (e.g., biases initialized to 0); this choice is specific to this implementation, not the paper
                denom = g_norm + beta * w_norm
                local_lr = eta * w_norm / denom if (w_norm > 0 and denom > 0) else torch.tensor(1.0)
                state = self.state[w]
                if "v" not in state:
                    state["v"] = torch.zeros_like(w)
                v = state["v"]
                v.mul_(m).add_(lr * local_lr * (g + beta * w))  # v ← m v + γ λ (g + β w)
                w.sub_(v)                                        # w ← w − v


model = nn.Sequential(
    nn.Conv2d(3, 64, 3, padding=1), nn.BatchNorm2d(64), nn.ReLU(),
    nn.AdaptiveAvgPool2d(1), nn.Flatten(), nn.Linear(64, 10),
)
total_steps = 1000
optimizer = LARS(model.parameters(), lr=2.0, momentum=0.9, weight_decay=5e-4, eta=0.001)
# Global learning rate γ_t = γ_0 (1 − t/T)^2 (polynomial decay). In practice, combine it with warmup as well
scheduler = torch.optim.lr_scheduler.PolynomialLR(optimizer, total_iters=total_steps, power=2.0)
criterion = nn.CrossEntropyLoss()

images = torch.randn(256, 3, 32, 32)          # Dummy mini-batch (thousands to tens of thousands in practice)
labels = torch.randint(0, 10, (256,))
model.train()
optimizer.zero_grad()
loss = criterion(model(images), labels)
loss.backward()
optimizer.step()
scheduler.step()

FAQ

Q. When should LARS be used?
A.

When the batch size is increased to several thousand or more and plain SGD diverges or loses accuracy even with linear scaling and warmup. In the paper, AlexNet trained up to a batch of 8K and ResNet-50 up to a batch of 32K with almost no loss in accuracy.

Q. How should the trust coefficient η be chosen?
A.

The paper's experiments use η=0.001\eta = 0.001. η\eta corresponds to the fraction by which a layer's weights may change in one update. Since it acts multiplied by the global learning rate γ\gamma, η\eta is usually kept fixed and γ\gamma is tuned instead.

Q. How does LARS differ from Adam?
A.

They differ in the unit and the basis for adapting the learning rate. Adam sets the step size for each individual parameter from a moving average of squared gradients. LARS sets the step size for each layer from the ratio of the weight norm to the gradient norm. The paper states that working per layer improves stability and that using the weight norm as the reference makes the training speed easier to control.

References

  1. Y. You, I. Gitman, and B. Ginsburg, "Large Batch Training of Convolutional Networks," arXiv:1708.03888, 2017.
  2. T. Chen, S. Kornblith, M. Norouzi, and G. Hinton, "A Simple Framework for Contrastive Learning of Visual Representations," ICML, 2020.
  3. PyTorch Documentation, "torch.optim.lr_scheduler.PolynomialLR."