AI Logic

Optimizers

Sophia

Updated:

How Sophia works. Left: one step that averages the gradient, divides it by the average of a diagonal Hessian estimated once every k steps, clips it elementwise to ±1, and then updates. Right: a graph comparing how the loss decreases for GD, SignGD, and Sophia on a quadratic function with a sharp direction and a flat direction

Background and Overview

Sophia (Second-order Clipped Stochastic Optimization) is an optimizer that uses second-order information: it divides a moving average of the gradient by a moving average of the "diagonal Hessian" and clips the magnitude elementwise before updating. It was published in 2023 by Liu, Li, Hall, Liang, and Ma with the goal of speeding up language model pretraining.

Pretraining large language models requires enormous compute, so even a slightly faster optimizer can greatly reduce time and cost. Nevertheless, Adam and its variants (such as AdamW) have remained in use for a long time.

  • Adam's weakness: It cannot fully adapt to differences in the curvature of the loss (the Hessian) across parameters.
  • The weakness of second-order methods that use the Hessian: Methods such as K-FAC have heavy per-step computation, so even with fewer steps they rarely win in total time.

By using a cheaply estimated diagonal Hessian as the preconditioner and re-estimating it only once every few steps, Sophia keeps the extra per-step computation to about 5%. In addition, elementwise clipping prevents runaway updates when the Hessian estimate is off or the loss is non-convex.

The paper reports that on GPT-style models from 125M to 1.5B parameters, Sophia reached the same validation loss (perplexity) as Adam with about half the steps, total compute, and wall-clock time.

Why Divide by the Hessian and Clip

The paper explains the weaknesses of other methods using a loss with two directions of very different curvature (a sharp direction θ1\theta_1 and a flat direction θ2\theta_2) (Figure 2 of the paper).

  • Gradient descent (GD): The learning rate can only be raised to about 1/h11/h_1, matching the curvature h1h_1 of the sharp direction. Since 1/h21/h_2 is optimal for the flat direction θ2\theta_2, progress there is slow.
  • SignGD and Adam: Since the update magnitude is the same in every direction, they bounce back and forth across the valley in the sharp direction, and the loss decreases only slowly in the flat direction. The paper notes that Adam's trajectory is also close to SignGD's.
  • Newton's method: It divides the gradient in each direction by the curvature (θi←θi−η Li′/hi\theta_i \leftarrow \theta_i - \eta\, L'_i / h_i), so it moves little in the sharp direction and a lot in the flat direction, which is ideal for convex problems. However, where the curvature is negative it heads toward saddle points or maxima, and where the curvature changes abruptly the second-order information is unreliable.

Sophia adds two safeguards to the Newton update (Eq. (4)).

θi←θi−η⋅clip ⁣(Li′(θi)max⁡{hi,ϵ}, ρ),clip(z,ρ)=max⁡{min⁡{z,ρ},−ρ}\theta_i \leftarrow \theta_i - \eta \cdot \mathrm{clip}\!\left(\frac{L'_i(\theta_i)}{\max\{h_i, \epsilon\}},\ \rho\right), \qquad \mathrm{clip}(z, \rho) = \max\{\min\{z, \rho\}, -\rho\}
  • Use only positive curvature: Thanks to max⁡{hi,ϵ}\max\{h_i, \epsilon\}, it does not over-divide even in directions where the curvature is negative or close to 0.
  • Clip elementwise: The size of a single update never exceeds ηρ\eta\rho in any direction. In directions where the curvature is unreliable and the update would be too large, clipping kicks in and the behavior falls back to SignSGD with momentum.

The right side of the figure at the top shows an example computed on a convex quadratic function (curvature 10 in the sharp direction, 0.1 in the flat direction) of how the loss decreases. GD and SignGD take a long time in the flat direction, with the loss still around 1 even after 60 steps. Sophia moves at a constant speed while far away in the flat direction, because clipping is active, and once close it drops the loss rapidly like Newton's method.

Theory (Computation in One Step)

Following Algorithm 3 of the paper, the following computation is performed at each step tt. All operations are elementwise, starting from m0=0m_0 = 0 and h1−k=0h_{1-k} = 0.

  1. Compute the gradient gtg_t of the minibatch loss and update its moving average mtm_t.
  2. Once every kk steps (when t mod k=1t \bmod k = 1), compute the diagonal Hessian estimate h^t\hat{h}_t and update its moving average hth_t. On other steps, ht=ht−1h_t = h_{t-1}.
  3. Apply weight decay (θt←θt−ηtλθt\theta_t \leftarrow \theta_t - \eta_t \lambda \theta_t).
  4. Divide mtm_t by max⁡{γht,ϵ}\max\{\gamma h_t, \epsilon\}, clip elementwise to [−1,1][-1, 1], and update.
mt=β1mt−1+(1−β1) gt,ht=β2ht−k+(1−β2) h^t(t mod k=1)m_t = \beta_1 m_{t-1} + (1-\beta_1)\, g_t, \qquad h_t = \beta_2 h_{t-k} + (1-\beta_2)\, \hat{h}_t \quad (t \bmod k = 1) θt+1=θt−ηt⋅clip ⁣(mtmax⁡{γ⋅ht, ϵ}, 1)\theta_{t+1} = \theta_t - \eta_t \cdot \mathrm{clip}\!\left(\frac{m_t}{\max\{\gamma \cdot h_t,\ \epsilon\}},\ 1\right)

γ\gamma is a coefficient that determines the fraction of elements that get clipped. Since ηt⋅clip(mt/max⁡{γht,ϵ},1)=(ηt/γ)⋅clip(mt/max⁡{ht,ϵ/γ},γ)\eta_t \cdot \mathrm{clip}(m_t / \max\{\gamma h_t, \epsilon\}, 1) = (\eta_t / \gamma) \cdot \mathrm{clip}(m_t / \max\{h_t, \epsilon/\gamma\}, \gamma), this is equivalent to clipping the original update mt/htm_t / h_t at γ\gamma and scaling the whole by 1/γ1/\gamma.

There are two ways to estimate the diagonal Hessian. Both cost about as much as one gradient computation.

  • Hutchinson's estimator (Sophia-H): Draw uu from a standard normal distribution and compute h^=u⊙(∇2ℓ(θ) u)\hat{h} = u \odot (\nabla^2 \ell(\theta)\, u). Only a Hessian-vector product is needed, and its expectation equals the diagonal Hessian (an unbiased estimate).
  • Gauss-Newton-Bartlett estimator (Sophia-G): Only for cross-entropy loss, resample labels from the model's output (softmax) and compute h^=B⋅g^⊙g^\hat{h} = B \cdot \hat{g} \odot \hat{g} (BB is the batch size) from the gradient g^\hat{g} of that loss. It estimates the diagonal of the Gauss-Newton matrix; it is biased, but in the paper's experiments it gave better results than Sophia-H.

The key point of the Gauss-Newton-Bartlett estimator is that the gradient is computed with labels resampled from the model's own predictions, not the true labels. The squared gradient with the true labels is the same quantity as Adam's second moment and does not estimate curvature.

Experimental Results

The paper pretrains GPT-2 125M, 355M, and 770M on OpenWebText and GPT NeoX 1.5B and 6.6B on the Pile, comparing against AdamW, Lion, and AdaHessian. The AdamW baseline is compared in a demanding way: its learning rate is tuned for each total step count TT, and it is compared with Sophia at T/2T/2 steps.

  • About 2x faster: On GPT-2 125M–770M, Sophia reached the same validation loss as AdamW in half the number of steps. Since the time per step is almost the same, total compute and wall-clock time are also roughly halved.
  • The gap widens with model size: After 100K steps of training, the validation loss was lower than AdamW's by 0.04 at 355M and 0.05 at 770M. A 540M model trained with Sophia for 100K steps reached the same loss as a 770M model trained with AdamW for the same number of steps; the latter costs 40% more for training and inference.
  • Sophia-G is better: Both Sophia-G and Sophia-H achieved lower loss than AdamW, Lion, and AdaHessian, with Sophia-G slightly better.

Time and compute per step (A100 GPU) (Table 1 of the paper)

MethodModelTime per stepOf which Hessian estimationCompute (TFLOPs)
AdamW770M3.25 s-2550
Sophia-H770M3.40 s0.12 s2708
Sophia-G770M3.42 s0.17 s2678
AdamW355M1.77 s-1195
Sophia-H355M1.88 s0.09 s1249
Sophia-G355M1.86 s0.09 s1255

Because the Hessian is estimated only once every 10 steps and on only part of the minibatch (32 examples for Sophia-H, 240 for Sophia-G), it accounts for about 6% of total compute, and the increase in wall-clock time is under 5%. The state consists of two quantities, mm and hh, so memory is the same as AdamW.

Practical Considerations

Choose γ\gamma by looking at the fraction of elements that are not clipped. The paper recommends tuning γ\gamma on a small model so that the fraction of elements with ∣mt/max⁡{γht,ϵ}∣<1|m_t / \max\{\gamma h_t, \epsilon\}| < 1 (not clipped) is 10–50%, halving γ\gamma if it is too high and doubling it if too low. The paper's values are γ=0.01\gamma = 0.01 for Sophia-H and γ=0.05\gamma = 0.05 for Sophia-G. If all elements are clipped, the update becomes the same as SignSGD with momentum.

  • Learning rate guideline: After fixing γ\gamma, using 3–5 times the learning rate used for Lion, or 0.8 times that used for AdamW, gave results nearly identical to the paper's grid search.
  • Settings in the paper: β1=0.96\beta_1 = 0.96, β2=0.99\beta_2 = 0.99, ϵ=10−12\epsilon = 10^{-12}, with Hessian estimation every k=10k = 10 steps. The learning rate follows 2,000 steps of warmup and then a cosine decay whose final value is 0.05 times the peak, and the gradient norm is clipped at 1.0.
  • Hyperparameters can be tuned on a small model and transferred: Values found on a 30M model (γ=0.01\gamma = 0.01, β2=0.99\beta_2 = 0.99) are used as is for the 125M–770M models.
  • Sophia-G assumes cross-entropy loss: Since labels are resampled from the model's output distribution, it suits models with classification-style outputs (such as language models). The paper also gives a formula for squared-error loss.
  • Not included in PyTorch's torch.optim: Use the authors' official implementation (the Sophia repository on GitHub, Sophia-G) or write one as in the code example below. The official implementation uses different argument names from the paper: the ρ\rho in its update rule clip(mt/(ρht+ϵ),1)\mathrm{clip}(m_t / (\rho h_t + \epsilon), 1) sits where the paper's γ\gamma is. The README example uses lr=2e-4, betas=(0.965, 0.99), rho=0.01, and weight_decay=0.1. Hessian estimation requires an extra forward and backward pass once every kk steps.
  • Be careful how you compare: The paper cautions that because the learning rate schedule depends on the total step count, comparing "intermediate checkpoints of the same run" overestimates the speedup, so it tunes the baseline for each total step count.

Comparison with Other Optimizers

The table below compares methods that adapt the step size per parameter from the same perspective.

MethodDenominator (preconditioner)Estimation frequencySafeguard against overly large updatesState kept
Adam, AdamWSquare root of the moving average of squared gradientsEvery stepNone (naturally bounded by the denominator)2x parameters
LionNone (takes the sign)-Update is always ±η\pm\eta1x parameters
AdaHessianDiagonal Hessian estimateEvery step (per-step compute more than 2x AdamW)None2x parameters
ShampooRoots of per-dimension preconditioner matricesOnce every few dozen steps (root computation)NoneDepends on matrix sizes
SophiaMoving average of diagonal Hessian estimatesOnce every k=10k = 10 stepsElementwise clipping2x parameters

The paper notes that methods using the diagonal Hessian as a preconditioner existed before, but they required frequent estimation and were computationally heavy, and attributes this to the lack of a clipping safeguard.

Rough guidelines for choosing are as follows.

  • To pretrain a GPT-style language model with less compute, use Sophia: In the paper it reached the same loss as AdamW in about half the steps.
  • If you value ease of implementation and a proven track record, use AdamW: Sophia adds the work of Hessian estimation and tuning γ\gamma.
  • To reduce memory, use Lion: It needs only one state, but in the paper's language model experiments it did not achieve as much speedup as Sophia.

PyTorch example

Show code
python
import torch
import torch.nn as nn


class SophiaG(torch.optim.Optimizer):
    # Algorithm 3 of the paper. The h update (once every k steps) is done in update_hessian()
    def __init__(self, params, lr=1e-4, betas=(0.96, 0.99), gamma=0.05, eps=1e-12, weight_decay=0.1):
        super().__init__(params, dict(lr=lr, betas=betas, gamma=gamma, eps=eps, weight_decay=weight_decay))

    @torch.no_grad()
    def update_hessian(self, batch_size):
        # Gauss-Newton-Bartlett: ĥ = B · ĝ ⊙ ĝ from the gradient ĝ with resampled labels
        for group in self.param_groups:
            beta2 = group["betas"][1]
            for p in group["params"]:
                if p.grad is None:
                    continue
                st = self.state[p]
                if "h" not in st:
                    st["h"] = torch.zeros_like(p)
                st["h"].mul_(beta2).add_(batch_size * p.grad * p.grad, alpha=1 - beta2)

    @torch.no_grad()
    def step(self):
        for group in self.param_groups:
            beta1 = group["betas"][0]
            lr, gamma, eps, wd = group["lr"], group["gamma"], group["eps"], group["weight_decay"]
            for p in group["params"]:
                if p.grad is None:
                    continue
                st = self.state[p]
                if "m" not in st:
                    st["m"] = torch.zeros_like(p)
                if "h" not in st:
                    st["h"] = torch.zeros_like(p)
                st["m"].mul_(beta1).add_(p.grad, alpha=1 - beta1)          # m_t
                p.mul_(1 - lr * wd)                                         # weight decay
                ratio = st["m"] / torch.clamp(gamma * st["h"], min=eps)    # m_t / max{γ h_t, ε}
                p.add_(ratio.clamp(-1, 1), alpha=-lr)                       # clip elementwise to ±1


vocab, dim, B, k = 100, 32, 16, 10
model = nn.Sequential(nn.Embedding(vocab, dim), nn.Linear(dim, vocab))
optimizer = SophiaG(model.parameters(), lr=1e-4)

model.train()
for t in range(1, 21):
    x = torch.randint(0, vocab, (B,))
    y = torch.randint(0, vocab, (B,))
    loss = nn.functional.cross_entropy(model(x), y)
    optimizer.zero_grad()
    loss.backward()
    optimizer.step()

    if t % k == 1:                                   # estimate the diagonal Hessian once every k steps
        logits = model(x)
        y_hat = torch.distributions.Categorical(logits=logits).sample()   # resample labels from the model's output
        optimizer.zero_grad()
        nn.functional.cross_entropy(logits, y_hat).backward()
        optimizer.update_hessian(batch_size=B)
        optimizer.zero_grad()

FAQ

Q. Is Sophia really a second-order method?
A.

Yes, it uses second-order information, since it estimates the diagonal of the Hessian (second derivative) and uses it as a preconditioner. However, it estimates only the diagonal, not the full Hessian, and only once every 10 steps, so the extra computation is kept to about 5%.

Q. Should I use Sophia-H or Sophia-G?
A.

In the paper's language model experiments, Sophia-G gave slightly better results. Sophia-G assumes cross-entropy loss (or a variant of it), while Sophia-H can be used with any loss as long as Hessian-vector products can be computed.

Q. What happens without clipping?
A.

Updates become extremely large in directions where the curvature is negative or close to 0, or where the estimate is off. The paper believes that earlier diagonal-Hessian methods needed frequent estimation precisely because they lacked this safeguard. In Sophia, the worst-case update size is bounded by the learning rate η\eta.

References

  1. H. Liu, Z. Li, D. Hall, P. Liang, and T. Ma, "Sophia: A Scalable Stochastic Second-order Optimizer for Language Model Pre-training," arXiv:2305.14342, 2023.
  2. H. Liu, "Sophia" (public implementation of the paper), GitHub.