AI Logic

Optimizers

Lion

Updated:

How Lion works. Left: the flow of one step, mixing momentum and gradient, taking only the sign to update together with weight decay, and updating the momentum with a different coefficient. Right: a bar chart of Lion's top-1 accuracy gain over AdamW when training from scratch on ImageNet, with and without strong data augmentation

Background and Overview

Lion is an optimizer that uses only the sign (+1+1 or −1-1) of a mix of the momentum and the current gradient for its update. The name stands for EvoLved Sign Momentum (sign momentum discovered through evolution). Chen et al. presented it in 2023.

Lion was not designed by hand; it was found automatically by representing optimizers as programs and running an evolutionary search. Candidates were searched on small proxy tasks, those that also held up on large tasks were selected, and unnecessary lines were removed to simplify them, leaving a short procedure.

Compared with AdamW, Lion has the following characteristics.

  • The only state it keeps is the momentum: AdamW keeps two quantities, the average of the gradient and the average of its square, while Lion keeps one, so it uses less memory.
  • The update magnitude is the same for every parameter: Because it takes the sign, apart from weight decay, the update for each element is ±1\pm 1 times the learning rate. The principle differs from methods like AdamW, which adjust the magnitude per parameter by division.
  • Fewer hyperparameters: AdamW's ϵ\epsilon is not needed.

The paper reports that Lion improves the accuracy of ViT on ImageNet by up to 2%, and matches or beats AdamW on image-text contrastive learning, diffusion models, and language models.

Theory (Computation in One Step)

Following Algorithm 2 (Program 1) of the paper, the following computation is performed at each step tt. The computation is element-wise over the parameters and starts from m0=0m_0 = 0.

  1. Compute the gradient gtg_t on a mini-batch.
  2. Compute ctc_t by mixing the momentum mt−1m_{t-1} and the current gradient gtg_t with coefficient β1\beta_1.
  3. Add weight decay to the sign of ctc_t, multiply by the learning rate, and update the parameters.
  4. Update the momentum with a different coefficient β2\beta_2.

In formulas:

ct=β1mt−1+(1−β1) gt,θt=θt−1−ηt(sign(ct)+λ θt−1)c_t = \beta_1 m_{t-1} + (1-\beta_1)\, g_t, \qquad \theta_t = \theta_{t-1} - \eta_t \left(\mathrm{sign}(c_t) + \lambda\, \theta_{t-1}\right) mt=β2mt−1+(1−β2) gtm_t = \beta_2 m_{t-1} + (1-\beta_2)\, g_t

The defaults are β1=0.9\beta_1 = 0.9 and β2=0.99\beta_2 = 0.99, values that came out of the search. λ\lambda is the strength of weight decay that shrinks weights separately from the gradient (the same form as AdamW).

Why there are two coefficients: The momentum memory uses β2=0.99\beta_2 = 0.99, remembering gradients over a period about 10 times longer than the 0.9 commonly used in AdamW and SGD with momentum. When determining the update direction, on the other hand, β1=0.9\beta_1 = 0.9 mixes in the current gradient with more weight. The paper explains that this combination makes use of both the long history and the current gradient. It also confirms that using only one of the coefficients degrades performance.

The original program found by the search also had a second moment and bias correction, but they disappeared during simplification. With a sign-based update, bias correction, which does not change the direction, is meaningless. This left a short procedure whose only state is a single momentum.

Why It Works (Sign-Based Updates)

The paper analyzes Lion's characteristics as follows.

  • The sign acts as regularization: Taking the sign adds noise to the update. The paper considers that this helps generalization as a form of regularization. In fact, for ViT-B/16 trained on ImageNet, Lion had higher training error than AdamW but 2% higher validation accuracy. It also tends to converge to flatter regions of the loss landscape.
  • The update magnitude is large: Apart from weight decay, the update is ±η\pm\eta for every element. Its magnitude (norm) is larger than updates of SGD or adaptive methods, so the learning rate must be smaller and the weight decay coefficient λ\lambda larger.
  • Advantageous with large batches: For ViT-B/16 on ImageNet, the optimal batch size was 256 for AdamW and 4,096 for Lion. At batch size 32K (only 11K training steps), Lion was 2.5 points more accurate than AdamW (77.9% vs. 75.4%). Performance is also maintained at batch size 64.

Sign-based optimizers such as Rprop and signSGD have existed before. The closest, signSGD (and its momentum variant), aims to reduce communication in distributed training, and updates its momentum differently from Lion. According to the paper, signSGD had been reported to underperform on CNNs for image classification. Nadam also combines the updated first moment with the gradient, but Lion differs in using β2\beta_2 to decouple the momentum memory from how it is used in the update.

Experimental Results

The paper mainly compares Lion with AdamW (or Adafactor when memory is insufficient), tuning the learning rate and weight decay on a logarithmic grid for both. The learning rate is decayed with a cosine schedule after a 10K-step warmup, and the momentum is stored in bfloat16.

Top-1 accuracy (%, average of 3 runs) when training from scratch on ImageNet (from Table 2 in the paper; the right side of the figure at the top shows the difference from AdamW in this table)

ModelStrong data augmentationAdamWLion
ResNet-50None76.3476.45
MLP-Mixer-S/16None69.2669.92
MLP-Mixer-B/16None68.1270.11
ViT-S/16None76.1276.70
ViT-S/16RandAugment + Mixup78.8979.46
ViT-B/16None75.4877.44
ViT-B/16RandAugment + Mixup80.1280.77

On ResNet-50, differences are small, including SGD (76.22%), and the gap widens for models that are harder to optimize, such as Transformers and MLP-Mixer. With strong data augmentation, the gap narrows.

Other results are as follows.

  • Image-text contrastive learning (BASIC-L): ImageNet zero-shot accuracy of 88.3% (Adafactor 85.7%) and fine-tuning accuracy of 91.1% (Adafactor 90.9%).
  • Pretraining on JFT: Reduced the compute for ViT pretraining by up to 5×.
  • Diffusion models: Achieved better FID than Adam and reduced training compute by up to 2.3×.
  • Language models and fine-tuning: On autoregressive and masked language models and on fine-tuning, results were on par with or slightly better than AdamW.
  • Speed and memory: Depending on the task, it ran 2-15% faster than AdamW or Adafactor. Training ViT-B/16 (resolution 224, batch 4,096) required at least 16 TPU v4 chips with AdamW but only 8 with Lion.

Practical Considerations

Do not reuse AdamW's learning rate and weight decay as is. In the paper's experience, the learning rate suited to Lion is 3-10× smaller than AdamW's. Since the effective strength of weight decay is "learning rate × λ\lambda", increase λ\lambda by 3-10× to keep the same strength. For the learning-rate schedule, scale down the initial, peak, and final values by the same ratio.

Examples of settings used in the paper:

TaskAdamW (Adafactor) learning rate, λ\lambdaLion learning rate, λ\lambda
ViT-B/16 on ImageNet (with strong data augmentation)10−310^{-3}, 1.010−410^{-4}, 10.0
Diffusion model3×10−43 \times 10^{-4}, 0.013×10−53 \times 10^{-5}, 0.1
7.5B language model (compared with Adafactor)10−310^{-3}, 0.00110−410^{-4}, 0.01
  • For language models, β1=0.95\beta_1 = 0.95 and β2=0.98\beta_2 = 0.98: The paper states that a smaller β2\beta_2 shortens the history memory and stabilizes training.
  • Benefits are hard to obtain with small batches: The paper states that with batch sizes smaller than 64, it may not beat AdamW.
  • Some tasks show small differences: For CNNs like ResNet, when strong data augmentation is used, and on large high-quality datasets (perplexity of large language models, masked language modeling on C4, etc.), the difference from AdamW was small or nonexistent.
  • Not included in PyTorch's torch.optim: Use the paper's public implementation (Google's automl repository) or a small implementation like the example below.

Comparison with Other Optimizers

Commonly used optimizers, side by side:

MethodUpdate directionUpdate magnitudeState keptMain hyperparameters
SGD with momentumMomentumProportional to gradient magnitude1× parametersLearning rate, momentum
AdamWFirst momentAdjusted by dividing by square root of second moment2× parametersLearning rate, β1\beta_1, β2\beta_2, ϵ\epsilon, weight decay
AdafactorFirst moment (can be omitted)Adjusted by second moment factored into rows and columnsRows and columns (+ first moment)Learning rate, decay rate, etc.
LionSign of mix of momentum and gradientSame for every element (±η\pm\eta)1× parametersLearning rate, β1\beta_1, β2\beta_2, weight decay

Rough guidelines for choosing:

  • To train Transformers or MLP-Mixer with large batches and reduce memory, use Lion: These are the conditions where the paper found large differences. Always re-tune the learning rate and weight decay.
  • For small batches, or tasks where AdamW settings are already established, stay with AdamW: Lion's benefits may be small or outweighed by the tuning effort.
  • For CNNs such as ResNet, SGD with momentum is also sufficient: On ResNet-50 in the paper, SGD, AdamW, and Lion were within 0.3 points of each other.

PyTorch example

Show code
python
import torch
import torch.nn as nn


class Lion(torch.optim.Optimizer):
    # Lion exactly as in Algorithm 2 (Program 1) of the paper
    def __init__(self, params, lr=1e-4, betas=(0.9, 0.99), weight_decay=0.0):
        super().__init__(params, dict(lr=lr, betas=betas, weight_decay=weight_decay))

    @torch.no_grad()
    def step(self):
        for group in self.param_groups:
            beta1, beta2 = group["betas"]
            lr, wd = group["lr"], group["weight_decay"]
            for p in group["params"]:
                if p.grad is None:
                    continue
                g = p.grad
                state = self.state[p]
                if not state:
                    state["m"] = torch.zeros_like(p)               # m_0 = 0 (this is the only state)
                m = state["m"]
                c = beta1 * m + (1 - beta1) * g                     # c_t: mix momentum and gradient
                p.add_(torch.sign(c) + wd * p, alpha=-lr)           # θ ← θ − η (sign(c_t) + λθ)
                m.mul_(beta2).add_(g, alpha=1 - beta2)              # m_t: update with a different coefficient β2


# Example of porting an AdamW setup with lr=1e-3, weight_decay=1.0 (the paper's ViT-B/16 setting)
model = nn.Sequential(nn.Linear(32, 64), nn.GELU(), nn.Linear(64, 10))
optimizer = Lion(model.parameters(), lr=1e-4, betas=(0.9, 0.99), weight_decay=10.0)

model.train()
x = torch.randn(16, 32)
y = torch.randint(0, 10, (16,))
loss = nn.functional.cross_entropy(model(x), y)
optimizer.zero_grad()
loss.backward()
optimizer.step()

FAQ

Q. What learning rate should be used for Lion?
A.

In the paper's experience, a good guideline is 3-10× smaller than the learning rate that worked for AdamW. At the same time, increase the weight decay coefficient λ\lambda by 3-10× to keep the effective weight decay strength (learning rate × λ\lambda).

Q. How much less memory does Lion use than AdamW?
A.

Lion keeps only one state, the momentum, so it uses one parameter-sized buffer less than AdamW (which keeps two: the first and second moments). In the paper, the TPU v4 chips needed to train ViT-B/16 dropped from 16 to 8.

Q. In what situations is Lion a good choice?
A.

The paper found the largest differences when training ViT, MLP-Mixer, and similar models with large batches. For CNNs, strong data augmentation, or batch sizes below 64, the difference from AdamW may be small or there may be no improvement.

References

  1. X. Chen, C. Liang, D. Huang, E. Real, K. Wang, Y. Liu, H. Pham, X. Dong, T. Luong, C.-J. Hsieh, Y. Lu, and Q. V. Le, "Symbolic Discovery of Optimization Algorithms," arXiv:2302.06675, 2023.
  2. Google, "automl/lion" (public implementation of the paper), GitHub.
  3. I. Loshchilov and F. Hutter, "Decoupled Weight Decay Regularization," ICLR, 2019.