AI Logic

Optimizers

Adafactor

Updated:

How Adafactor works. The left shows one step for a weight matrix: the second moment is stored split into rows and columns, the gradient is divided by it to get the update direction, the update is clipped, and the weights are updated with a step size proportional to their scale (the factorization of the second moment is marked with a yellow frame). The right shows the inside of the yellow frame: from the n × m squared gradients, only n row sums and m column sums are stored, and their outer product divided by the total sum reconstructs the n × m second moment

Background and overview

Adafactor is an optimizer that stores Adam's average of squared gradients approximately, using only the row sums and column sums of each weight matrix, greatly reducing optimizer memory. Shazeer and Stern (Google Brain) proposed it in 2018 (ICML 2018). It also drops momentum and adds a mechanism that limits the size of updates and a step size proportional to the scale of the weights.

Adam keeps two values for every parameter: the average of the gradient and the average of the squared gradient. The paper points out that this requires twice the memory of the model weights on top of the weights themselves, tripling memory usage. Because memory had not kept pace with compute and had become the limit on model size, this extra memory was a problem.

Adafactor reduces this memory in two ways.

  • Store the second moment in factored form: for an n×mn \times m weight matrix, instead of keeping all n×mn \times m moving averages of squared gradients, it keeps only the row sums (nn values) and the column sums (mm values). For a 1000×40001000 \times 4000 matrix, for example, 4 million values become 5,000.
  • Use no momentum (first moment): since it does not keep the average of the gradient either, the only extra memory is for the row and column sums.

Dropping momentum, however, can make training unstable. The paper traces the cause to stale second-moment estimates that make updates too large, and addresses it with "update clipping", which limits the size of updates, and a schedule that gradually increases the decay rate of the second moment. As an analogy, instead of memorizing every cell of a table, it remembers only the row totals and the column totals and estimates each cell when needed.

Theory (one step of computation)

For an n×mn \times m weight matrix XX, Adafactor performs the following computation at each training step tt (Algorithm 4 of the paper). Gt2G_t^2 is the elementwise square, 1n1_n is a vector of length nn whose entries are all 1, and RMS(⋅)\mathrm{RMS}(\cdot) is the root mean square of all entries of a matrix.

  1. Determine this step's step size αt\alpha_t from the scale of the weights.
  2. Compute the gradient GtG_t on a mini-batch.
  3. Update the row sums RtR_t (nn values) and column sums CtC_t (mm values) of the squared gradient with exponential moving averages.
  4. Reconstruct the n×mn \times m second moment V^t\hat{V}_t from RtR_t and CtC_t, and divide the gradient by it to get the update direction UtU_t.
  5. If the RMS of UtU_t exceeds dd, shrink it until it equals dd (update clipping).
  6. Multiply by the step size and update the parameters.

The equations for steps 1 and 3 are as follows. ρt\rho_t is the relative step size (a fraction of the weight scale), β^2t\hat{\beta}_{2t} is the decay rate of the second moment, and ϵ1\epsilon_1 and ϵ2\epsilon_2 are small constants.

αt=max⁡(ϵ2, RMS(Xt−1))ρt\alpha_t = \max\left(\epsilon_2,\ \mathrm{RMS}(X_{t-1})\right) \rho_t Rt=β^2tRt−1+(1−β^2t)(Gt2+ϵ11n1m⊤)1m,Ct=β^2tCt−1+(1−β^2t) 1n⊤(Gt2+ϵ11n1m⊤)R_t = \hat{\beta}_{2t} R_{t-1} + (1-\hat{\beta}_{2t}) \left(G_t^2 + \epsilon_1 1_n 1_m^\top\right) 1_m, \qquad C_t = \hat{\beta}_{2t} C_{t-1} + (1-\hat{\beta}_{2t})\, 1_n^\top \left(G_t^2 + \epsilon_1 1_n 1_m^\top\right)

The equations for steps 4 to 6 are as follows.

V^t=RtCt1n⊤Rt,Ut=GtV^t,U^t=Utmax⁡(1, RMS(Ut)/d),Xt=Xt−1−αtU^t\hat{V}_t = \frac{R_t C_t}{1_n^\top R_t}, \qquad U_t = \frac{G_t}{\sqrt{\hat{V}_t}}, \qquad \hat{U}_t = \frac{U_t}{\max\left(1,\ \mathrm{RMS}(U_t)/d\right)}, \qquad X_t = X_{t-1} - \alpha_t \hat{U}_t

The values the paper recommends are ϵ1=10−30\epsilon_1 = 10^{-30}, ϵ2=10−3\epsilon_2 = 10^{-3}, d=1d = 1, ρt=min⁡(10−2,1/t)\rho_t = \min(10^{-2}, 1/\sqrt{t}), and β^2t=1−t−0.8\hat{\beta}_{2t} = 1 - t^{-0.8} (Algorithm 6 of the paper). Vector parameters such as biases cannot be factored, so their second moment is kept elementwise, as in Adam (Algorithm 5 of the paper).

The step size αt\alpha_t is the RMS of the weights times ρt\rho_t. With the defaults, ρt\rho_t is at most 10−210^{-2}, so each update is at most about 1% of the weight scale. The paper's acknowledgments mention Hinton's claim that "training works well when the size of parameter updates is about 10−210^{-2} to 10−310^{-3} times the size of the parameters." ϵ2\epsilon_2 is a lower bound that lets weights initialized to 0 start moving.

Four techniques and why each works

This section explains what each of Adafactor's four techniques solves.

Approximating the second moment with row and column sums (Section 3 of the paper). The paper considers approximating a nonnegative matrix VV with a rank-1 matrix (the product of a column vector and a row vector) that minimizes the elementwise generalized KL divergence (I-divergence). The solution is

RS=V1m 1n⊤V1n⊤V1mRS = \frac{V 1_m\, 1_n^\top V}{1_n^\top V 1_m}

which can be written using only the row sums V1mV 1_m and the column sums 1n⊤V1_n^\top V (Lemma 1 of the paper). Because row and column sums are linear functions of VV, "the row sums of the moving average" equal "the moving average of the row sums". So there is no need to store VV itself; storing moving averages of the row and column sums is enough. If VV is rank 1 to begin with, the approximation is exact. The right side of the figure at the top shows how an n×mn \times m matrix is reconstructed from the row and column sums. The paper explains that an approximation by singular value decomposition cannot be used, because it is incompatible with moving averages and can produce negative values.

Update clipping (Sections 5 and 6 of the paper). The paper analyzes why Adam without momentum becomes unstable without warmup: the second-moment estimate becomes stale. When β2\beta_2 is large (slow decay), v^t\hat{v}_t is based on gradients from long ago and, while the model is changing quickly, deviates from the current squared gradient. If the estimate were accurate, the average of gt2/v^tg_t^2 / \hat{v}_t would be close to 1, so the paper takes RMS(Ut)\mathrm{RMS}(U_t) of each weight matrix deviating far from 1 as a sign that updates are larger (or smaller) than intended. Clipping shrinks the update when this value exceeds dd. Unlike gradient clipping, which shrinks the gradient, it limits the size of the actual update after division by the second moment.

Gradually increasing the decay rate (Section 7 of the paper). The paper shows that Adam's bias correction is equivalent to gradually increasing the decay rate from 0 to β2\beta_2 as β^2t=β2(1−β2t−1)/(1−β2t)\hat{\beta}_{2t} = \beta_2 (1-\beta_2^{t-1})/(1-\beta_2^t). Building on this, it proposes β^2t=1−t−c\hat{\beta}_{2t} = 1 - t^{-c}. Since it starts at 0 when t=1t = 1, no bias correction is needed, and decay is fast early in training (stable) and slow later (good convergence). For the weight on past gradients to eventually approach 0, however, c≤1c \le 1 is required; with c=1c = 1 it becomes a simple average of the squared gradients.

Relative step size (Section 8 of the paper). Adam's learning rate is an absolute measure of "how much to move per step", whereas Adafactor sets the step size as a fraction ρt\rho_t of the parameter scale. This makes it easier to use the same settings for parameters of different scales (for example, embeddings and other weight matrices).

Experimental results

The paper compared settings one at a time on English-to-German machine translation (WMT 2014) with a Transformer. Every run trains for 100,000 steps, and the values are BLEU on the development set (newstest2013; higher is better). With warmup, the step size is proportional to min⁡(10−6t,1/t)\min(10^{-6} t, 1/\sqrt{t}); without warmup, to min⁡(10−2,1/t)\min(10^{-2}, 1/\sqrt{t}). The main rows are excerpted below (Table 2 of the paper).

RowFactored second momentβ1\beta_1β^2t\hat{\beta}_{2t}Clipping ddStep sizeWith warmupWithout warmup
(A)No00.999NoneAbsolute25.60.1
(B)No0.90.999NoneAbsolute25.423.1
(C)Yes00.999NoneAbsolute25.40.2
(G)No00.9NoneAbsolute18.415.6
(H)No00.9991.0Absolute25.421.5
(J)Yes00.9991.0Absolute25.622.4
(N)No01−t−0.81 - t^{-0.8}1.0Absolute25.922.4
(O)Yes01−t−0.81 - t^{-0.8}1.0Relative25.025.5
(P)Yes0.91−t−0.81 - t^{-0.8}1.0Relative24.925.3

(B) corresponds to standard Adam with momentum, and (O) to the proposed setting (Adafactor).

  • Factoring barely changes the results: the differences between (A) and (C), and between (H) and (J), were small. Approximating with only the row means gave 25.2, nearly the same, but approximating with only the column means gave 0.3 and failed to train. The paper speculates that this is due to the weight matrix shared between the embedding and the output, where rows for frequent words have larger gradients.
  • Without momentum, training is unstable without warmup: (A) without warmup scored 0.1, far from the 23.1 of (B) with momentum.
  • Clipping, fast decay, and an increasing decay rate ease the instability: (H) with clipping d=1d = 1 recovered to 21.5 (with d=2d = 2 it stayed at 0.2). (G) with fast decay β2=0.9\beta_2 = 0.9 was stable, but converged poorly, reaching only 18.4 even with warmup.
  • Even the low-memory settings match Adam with momentum: the paper states that (J) and (N) achieved convergence and stability comparable to Adam with momentum (B), while keeping the extra memory to just the row and column sums.
  • SGD was unstable and highly sensitive to the learning rate: SGD with the same step-size shape and varying learning rates reached at most 24.3 with warmup, and without warmup it diverged when the learning rate was increased 100-fold or more.

Relative step size (Table 3 of the paper). Adam (the settings of Vaswani et al., 2017) and Adafactor (the paper's recommended values) were compared while varying the scale of the embedding initialization (50,000 steps).

Std. dev. of embedding initMultiplier in computationAdamAdafactor
1/dmodel1/\sqrt{d_{\text{model}}}dmodel\sqrt{d_{\text{model}}}26.426.6
1125.826.4
1/dmodel1/\sqrt{d_{\text{model}}}124.225.4

Even without the trick of matching the embedding scale to the other weights, as in the original Transformer settings (first row), Adafactor's BLEU dropped less, showing that it is robust to differences in parameter scale.

Practical caveats

With its defaults (relative_step=True, scale_parameter=True), Adafactor in Hugging Face transformers determines the learning rate itself, so passing lr raises an error. To specify the learning rate externally and change it with a scheduler, set relative_step=False and scale_parameter=False (and warmup_init=False) and pass lr. Conversely, to use the paper's relative step size, leave lr=None, and use AdafactorSchedule when combining it with Trainer. warmup_init=True can only be used with relative_step=True and sets the step size to min⁡(10−6t,1/t)\min(10^{-6} t, 1/\sqrt{t}) (the paper's warmup form).

PyTorch provides torch.optim.Adafactor. It differs from the paper and other implementations in the following ways.

  • PyTorch's lr is the upper bound of the relative step size: PyTorch uses ρt=min⁡(lr,1/t)\rho_t = \min(\text{lr}, 1/\sqrt{t}), and the default lr=0.01 corresponds to the paper's 10−210^{-2}. lr also multiplies the weight decay coefficient.
  • ϵ1\epsilon_1 is added in a different place than in the paper: the PyTorch documentation states explicitly that ϵ1\epsilon_1 is used as a lower bound in the denominator rather than added to the squared gradient. It also uses row and column "means" instead of "sums" (the result is the same, and it is numerically more stable).
  • Momentum is not available: PyTorch's Adafactor has no first moment. The Hugging Face implementation supports momentum when beta1 is passed (corresponding to (P) in Table 2 of the paper).

Also keep the following in mind.

  • Do not remove warmup and update clipping: as Table 2 of the paper shows, without momentum, clipping, or warmup, training can break down. The Hugging Face documentation also recommends using learning rate warmup and clip_threshold=1.0 for fine-tuning T5, and not applying extra operations such as gradient clipping together with Adafactor.
  • Only parameters with two or more dimensions are factored: vectors such as biases and the weights of Layer Normalization keep an elementwise second moment, as in Adam. The memory savings come from the large weight matrices.
  • The paper's experiments cover only a Transformer for machine translation: whether the factored approximation works as well for other models and tasks was not verified in the paper.

Comparison with other optimizers

The table lists Adafactor and closely related optimizers from the same viewpoints (extra optimizer memory per n×mn \times m weight matrix).

MethodFirst momentSecond moment storageExtra memoryHow the step size is set
SGD (no momentum)NoNoneNoneLearning rate × gradient
MomentumYesNonenmnmLearning rate × average gradient
Adam, AdamWYesElementwise2nm2nmLearning rate (absolute scale)
AdafactorNo (optional)Row sums and column sumsn+mn + mWeight RMS × relative step size
AMSGradYesElementwise (also keeps the maximum)3nm3nm (PyTorch)Learning rate (absolute scale)

A rough guide for choosing:

  • If memory is short and Adam keeps the model or batch from growing, use Adafactor: the more large weight matrices a Transformer has, the more memory it saves.
  • If memory is plentiful and less tuning effort is preferred, Adam or AdamW is fine: Adafactor has many settings that differ from Adam, such as the relative step size, clipping, and the decay-rate schedule, and the meaning of its arguments differs between implementations.
  • Adafactor's mechanisms are used in other methods too: the idea of increasing β2\beta_2 over time builds on the proposal in the AMSGrad paper (Reddi et al., 2018).

PyTorch example

Show code
python
import math
import torch
import torch.nn as nn


# 1. A small implementation following Algorithms 4 (matrices) and 5 (vectors) of the paper. Recommended values from Algorithm 6
def rms(x):
    return x.pow(2).mean().sqrt()


@torch.no_grad()
def adafactor_step(p, state, eps1=1e-30, eps2=1e-3, d=1.0, c=0.8):
    state["t"] = state.get("t", 0) + 1
    t, g = state["t"], p.grad
    rho = min(1e-2, 1 / math.sqrt(t))                     # relative step size ρ_t
    alpha = max(eps2, rms(p).item()) * rho                # α_t = max(ε2, RMS(X)) ρ_t
    beta2 = 1 - t ** (-c)                                 # β̂_2t = 1 − t^(−0.8) (0 at t = 1)
    g2 = g * g + eps1
    if p.ndim == 2:                                       # matrix: keep only row sums R and column sums C
        R = state.setdefault("R", torch.zeros(p.shape[0], device=p.device))
        C = state.setdefault("C", torch.zeros(p.shape[1], device=p.device))
        R.mul_(beta2).add_(g2.sum(dim=1), alpha=1 - beta2)
        C.mul_(beta2).add_(g2.sum(dim=0), alpha=1 - beta2)
        v_hat = torch.outer(R, C) / R.sum()               # V̂ = R C / 1ᵀR
    else:                                                 # vector: keep elementwise
        V = state.setdefault("V", torch.zeros_like(p))
        V.mul_(beta2).add_(g2, alpha=1 - beta2)
        v_hat = V
    u = g / v_hat.sqrt()                                  # no momentum
    u = u / max(1.0, (rms(u) / d).item())                 # update clipping
    p.sub_(alpha * u)


model = nn.Sequential(nn.Linear(512, 2048), nn.ReLU(), nn.Linear(2048, 512))
states = {p: {} for p in model.parameters()}
x = torch.randn(32, 512)
loss = (model(x) - x).pow(2).mean()
loss.backward()
for p in model.parameters():
    adafactor_step(p, states[p])
# For the two weight matrices (2048 × 512 and 512 × 2048), Adafactor keeps (2048 + 512) × 2 = 5,120 values
# Adam's second moment would need 2048 × 512 × 2 = 2,097,152 values
print(sum(s["R"].numel() + s["C"].numel() for s in states.values() if "R" in s))


# 2. PyTorch built-in: lr is the upper bound of the relative step size (ρ_t = min(lr, 1/√t)), and there is no momentum
optimizer = torch.optim.Adafactor(model.parameters(), lr=1e-2, beta2_decay=-0.8, d=1.0)


# 3. Adafactor in Hugging Face transformers (requires pip install transformers)
# from transformers.optimization import Adafactor, AdafactorSchedule
# (a) As in the paper, the optimizer sets the learning rate itself: leave lr as None (passing lr raises ValueError)
# optimizer = Adafactor(model.parameters(), lr=None, relative_step=True,
#                       scale_parameter=True, warmup_init=True)
# lr_scheduler = AdafactorSchedule(optimizer)        # when combined with Trainer
# (b) Specify the learning rate externally (the setting recommended for fine-tuning T5)
# optimizer = Adafactor(model.parameters(), lr=1e-3, relative_step=False,
#                       scale_parameter=False, warmup_init=False, clip_threshold=1.0)

FAQ

Q. How much memory can Adafactor save?
A.

For one n×mn \times m weight matrix, Adam keeps 2nm2nm values for the first and second moments, whereas Adafactor (without momentum) keeps only the n+mn + m row and column sums. For a 2048×5122048 \times 512 matrix, for example, about 2.1 million values become 2,560. Vectors such as biases are still stored elementwise, however, so the savings come from the large weight matrices.

Q. Can Adafactor use momentum?
A.

Yes. The paper says a first moment may be added as in Adam, and tests it as (P) in Table 2 (BLEU 25.3 without warmup). The Hugging Face implementation enables it when beta1 is passed, but PyTorch's torch.optim.Adafactor does not support it. Adding momentum costs memory equal to one value per parameter.

Q. How should the learning rate be set?
A.

Following the paper, the step size is set automatically as the weight RMS × min⁡(10−2,1/t)\min(10^{-2}, 1/\sqrt{t}), so no separate learning rate is needed. To specify a learning rate externally in the Hugging Face implementation, set relative_step=False and scale_parameter=False and pass lr. PyTorch's lr is the upper bound of the relative step size, so do not choose it the way you would choose Adam's learning rate.

References

  1. N. Shazeer and M. Stern, "Adafactor: Adaptive Learning Rates with Sublinear Memory Cost," ICML, 2018.
  2. S. J. Reddi, S. Kale, and S. Kumar, "On the Convergence of Adam and Beyond," ICLR, 2018.
  3. A. Vaswani, N. Shazeer, N. Parmar, J. Uszkoreit, L. Jones, A. N. Gomez, Ł. Kaiser, and I. Polosukhin, "Attention Is All You Need," NeurIPS, 2017.
  4. PyTorch Documentation, "torch.optim.Adafactor."
  5. Hugging Face Transformers Documentation, "Optimization: Adafactor."