AI Logic

Optimizers

Lookahead

Updated:

How Lookahead works. Left: the flow of updating the fast weights k times with the inner optimizer and moving the slow weights by α in that direction. Right: a graph of the expected loss of SGD and of Lookahead's fast and slow weights, computed analytically on a noisy quadratic, showing that the slow weights settle at a lower value

Background and Overview

Lookahead is an optimizer that keeps two sets of weights and moves the "slow weights" a fixed fraction α\alpha toward the "fast weights", which have been advanced kk steps by an ordinary optimizer. Zhang, Lucas, Hinton, and Ba presented it at NeurIPS in 2019. The subtitle, "k steps forward, 1 step back", describes this behavior.

Earlier improvements fell broadly into two families.

Lookahead is orthogonal to (can be combined with) both. The inner optimizer AA can be anything; it wraps SGD or Adam as is. The paper reports that Lookahead reduces the variance of the inner optimizer and stabilizes training. The extra computation is small, and the extra memory is just one set of slow weights.

As a mountain-trail analogy, a scout (the fast weights) is sent kk steps ahead, and the main party (the slow weights) advances about halfway toward where the scout ended up. Even if the scout zigzags between both sides of a valley, the main party can travel between them and keep moving forward.

Theory (One Outer Update)

Following Algorithm 1 of the paper, with slow weights ϕ\phi, fast weights θ\theta, inner optimizer AA, synchronization period kk, and slow-weight step size α\alpha, the following procedure is repeated.

  1. Reset the fast weights to the slow weights (θt,0=ϕt−1\theta_{t,0} = \phi_{t-1}).
  2. Sample a mini-batch and update the fast weights once with the inner optimizer AA. Repeat this kk times.
  3. Move the slow weights a fraction α\alpha toward the fast weights θt,k\theta_{t,k} reached after kk steps.

In formulas:

θt,i=θt,i−1+A(L,θt,i−1,d)(i=1,…,k)\theta_{t,i} = \theta_{t,i-1} + A(L, \theta_{t,i-1}, d) \quad (i = 1, \dots, k) ϕt=ϕt−1+α (θt,k−ϕt−1)\phi_t = \phi_{t-1} + \alpha\, (\theta_{t,k} - \phi_{t-1})

With α=1\alpha = 1 it reduces to the inner optimizer itself; with α=0\alpha = 0 the slow weights never move. Most experiments in the paper use k=5k = 5 and α=0.5\alpha = 0.5.

Expanding the slow-weight formula shows that it is an exponential moving average of the fast weights' endpoints at each round (Eq. (2)).

ϕt+1=α[θt,k+(1−α) θt−1,k+⋯+(1−α)t−1θ0,k]+(1−α)tϕ0\phi_{t+1} = \alpha \left[\theta_{t,k} + (1-\alpha)\,\theta_{t-1,k} + \cdots + (1-\alpha)^{t-1}\theta_{0,k}\right] + (1-\alpha)^t \phi_0

Recent endpoints are weighted heavily, while older endpoints still have a small influence.

At synchronization, the inner optimizer's state (the momentum buffer or Adam's moments) can be "kept as is", "averaged", or "reset to 0". The paper confirmed on CIFAR that all of these speed up convergence, and uses the keep as is approach in the other experiments.

Why It Works (Reducing Variance)

The paper explains that while ordinary optimizers require careful learning-rate tuning to avoid oscillation and slow convergence, Lookahead allows a larger learning rate to be used in the inner loop.

  • The fast weights oscillate along high-curvature directions while moving quickly along low-curvature directions: Because the learning rate is large, they bounce back and forth across the valley but make big progress along it.
  • The slow weights smooth out the oscillation: Because they interpolate linearly toward the fast weights, they pass through roughly the middle of the two ends of the oscillation.

The paper analyzes this with a noisy quadratic model (a model in which the location of the loss minimum shifts with each mini-batch). Compared with SGD at the same learning rate, it shows that the variance of Lookahead's slow weights converges to a value strictly smaller than that of SGD (Proposition 2).

The right side of the figure at the top computes this model in one dimension (learning rate 0.5, k=5k = 5, α=0.5\alpha = 0.5).

  • SGD drops quickly but stalls at 0.167: Because of the noise, it wanders around the minimum and goes no lower.
  • Lookahead's slow weights are slow at first but drop to 0.057: With α=0.5\alpha = 0.5, the mean approaches more slowly than with SGD. On the other hand, the noise is averaged and becomes smaller.
  • The fast weights restart from the slow weights at each synchronization and climb back to the same level as SGD: It is the slow weights that reduce the variance.

The paper also shows by calculation that, even in a comparison where learning rates are adjusted to reach the same steady-state value, there are settings where Lookahead reaches that value faster (Figure 3). It also shows that on a noise-free quadratic, Lookahead greatly speeds up convergence when momentum oscillates (is under-damped) (Figure 4). When momentum is too small and the approach is monotonic, it becomes slightly slower.

Experimental Results

The paper compares Lookahead with using the inner optimizer alone on image classification, language modeling, and machine translation. In every experiment, the amount of training data used is the same.

ResNet-18 on CIFAR (final validation accuracy %, mean of 3 runs) (Table 1 in the paper). Lookahead and Polyak averaging wrap SGD, and the compared methods have their learning rate and weight decay tuned.

MethodCIFAR-10CIFAR-100
SGD95.23 ± .1978.24 ± .18
Polyak averaging95.26 ± .0477.99 ± .42
Adam94.84 ± .1676.88 ± .39
Lookahead95.27 ± .0678.34 ± .05

ResNet-50 on ImageNet (single-crop validation accuracy %) (Table 2 in the paper). SGD uses learning rate 0.1 and momentum 0.9, Lookahead uses k=5k = 5 and α=0.5\alpha = 0.5, with a fast schedule that divides the learning rate by 10 at epochs 30, 48, and 58.

EpochLookahead top-1SGD top-1Lookahead top-5SGD top-5
5075.1374.4392.2292.15
6075.4975.1592.5392.56

LSTM language model on Penn Treebank (perplexity, lower is better) (Table 3 in the paper)

MethodTrainValidationTest
SGD43.6266.063.90
Lookahead (SGD)35.0265.1063.04
Adam33.5461.6459.33
Lookahead (Adam)31.9260.2857.72
Polyak averaging-61.1858.79

Other results are as follows.

  • ResNet-152 on ImageNet: With the fast schedule, it reached 77% top-1 at epoch 49 and 77.96% at epoch 60.
  • Transformer on WMT 2014 English-German translation (Base, 50K steps): BLEU was 24.6/24.6 for Adam, 24.68/24.70 for Lookahead (Adam), 24.3/24.4 for Lookahead (Adam) without warmup, and 24.17/24.51 for Adafactor (newstest13/newstest14). It reached nearly the same level even without warmup. Learning rates of 0.02, 0.04, and 0.06 all converged to similar final losses.
  • Robustness to hyperparameters: On CIFAR-100, all four combinations of k∈{5,10}k \in \{5, 10\} and α∈{0.5,0.8}\alpha \in \{0.5, 0.8\} reached higher validation accuracy (77.94-78.27%) than SGD (77.72%) (Table 5). Lookahead also converged quickly when the inner SGD's learning rate and momentum were varied.

Practical Considerations

Use the slow weights for evaluation and saving. Fast weights in the middle of the inner loop can have much lower test accuracy, as shown in Figure 10 of the paper. Evaluate right after an outer update (when the fast and slow weights coincide), or write the slow weights back into the model before evaluation.

  • Not included in PyTorch's torch.optim: Use the paper authors' public implementation or a small wrapper like the example below. The way the inner optimizer is constructed does not need to change.
  • Keep the learning-rate schedule designed for the inner optimizer: The paper's CIFAR experiments note that convergence was faster even with a schedule tuned for the inner optimizer, and schedules designed for Lookahead are left as future work.
  • Early progress can be slower: The slow weights move only a fraction α\alpha toward the fast weights, so at the start of training, when the loss drops a lot, it can look slower than the inner optimizer at the same learning rate.
  • The extra computation and memory are small: Computation is about (k+1)/k(k+1)/k times that of the inner optimizer, and memory is one set of slow weights.
  • A fixed α\alpha is fine: The paper also presents a method to set α\alpha automatically from a quadratic approximation, but a fixed α\alpha gave similar convergence speed and tended to generalize better, so the experiments use a fixed value.

Comparison with Other Methods

Methods that average weights or use outer and inner loops, side by side:

MethodWhat it doesWhen it averages or interpolatesEffect on training trajectoryGoal
LookaheadMoves slow weights a fraction α\alpha toward the fast weights' endpoint and resets the fast weightsDuring training, every kk stepsChanges it (next round starts from the averaged point)Fast convergence and stability
Polyak averagingAverages all weights so farKeeps the average during training, but training continues with the original weightsNo changeReduce variance of the final weights
SWAKeeps the learning rate relatively high and averages weights from several pointsMainly at the end of trainingNo changeGeneralization
ReptileTrains on each task in an inner loop and moves the initialization in that directionEvery outer loopChanges itInitialization for new tasks

The paper positions Lookahead, unlike conventional averaging methods that "build an ensemble of weights at the end of training", as an optimizer that averages during training to speed up convergence. It resembles Reptile in form, but differs in that Reptile picks a different task for each outer loop, while Lookahead exploits the shape of the loss on the same task.

Rough guidelines for choosing:

  • To stabilize training without significantly changing the current optimizer settings, use Lookahead: It works as a simple wrapper, and in the paper it improved both SGD and Adam.
  • To squeeze a little more generalization at the end of training, averaging methods such as SWA are also candidates: They take an average at the end without changing the training trajectory.

PyTorch example

Show code
python
import torch
import torch.nn as nn


class Lookahead:
    # Lookahead exactly as in Algorithm 1 of the paper. inner can be any optimizer, such as SGD or Adam
    def __init__(self, inner, k=5, alpha=0.5):
        self.inner, self.k, self.alpha = inner, k, alpha
        self.step_count = 0
        # slow weights φ (the fast weights θ are the model parameters themselves)
        self.slow = [[p.detach().clone() for p in g["params"]] for g in inner.param_groups]

    def zero_grad(self):
        self.inner.zero_grad()

    @torch.no_grad()
    def step(self):
        self.inner.step()                       # update the fast weights once with the inner optimizer
        self.step_count += 1
        if self.step_count % self.k == 0:       # outer update every k steps
            for group, slow in zip(self.inner.param_groups, self.slow):
                for p, s in zip(group["params"], slow):
                    s.add_(p - s, alpha=self.alpha)   # φ ← φ + α(θ_k − φ)
                    p.copy_(s)                         # θ ← φ (inner state is kept as is)


model = nn.Sequential(nn.Linear(20, 64), nn.ReLU(), nn.Linear(64, 10))
inner = torch.optim.SGD(model.parameters(), lr=0.1, momentum=0.9)
optimizer = Lookahead(inner, k=5, alpha=0.5)      # the paper's ImageNet setting

model.train()
for step in range(20):
    x = torch.randn(32, 20)
    y = torch.randint(0, 10, (32,))
    loss = nn.functional.cross_entropy(model(x), y)
    optimizer.zero_grad()
    loss.backward()
    optimizer.step()

# 20 is a multiple of k=5, so fast weights = slow weights now; it is fine to evaluate or save as is
model.eval()

FAQ

Q. What values should k and α be set to?
A.

Most experiments in the paper use k=5k = 5 and α=0.5\alpha = 0.5. On CIFAR-100, every combination of k∈{5,10}k \in \{5, 10\} and α∈{0.5,0.8}\alpha \in \{0.5, 0.8\} achieved higher accuracy than SGD, and the paper reports that the method is not very sensitive to this choice.

Q. Can Lookahead replace Adam?
A.

It is not a replacement but a "wrapper" that uses Adam or SGD internally. The inner optimizer runs as is, and interpolation with the slow weights is added every kk steps. In the paper, Lookahead (Adam) achieved lower perplexity than Adam alone.

Q. How does it differ from Polyak averaging and SWA?
A.

Polyak averaging and SWA keep a separate average of the weights without changing the training trajectory. Lookahead starts the next inner loop from the averaged position (the slow weights), so the training trajectory itself changes.

References

  1. M. R. Zhang, J. Lucas, G. Hinton, and J. Ba, "Lookahead Optimizer: k steps forward, 1 step back," NeurIPS, 2019.
  2. M. R. Zhang, "lookahead" (public implementation of the paper), GitHub.