Compute Adafactor's factored second moment

HardOptimizersPro

Why it matters T5 and PaLM were trained with Adafactor to save optimizer memory.

Adafactor saves memory by storing only row and column averages of the squared gradient instead of the full matrix.

Write adafactor_update(G, R, C, beta2, eps=1e-30). G is the (n, m) gradient, R (n,) and C (m,) are running row and column means of G^2 + eps. Update R = beta2 * R + (1 - beta2) * mean(G^2 + eps, axis=1) and C = beta2 * C + (1 - beta2) * mean(G^2 + eps, axis=0). The estimate is V = outer(R, C) / mean(R). Return (U, R, C) where U = G / sqrt(V).

Signaturedef adafactor_update(G, R, C, beta2, eps=1e-30)

Example

G = [[2]] with R = [0], C = [0], beta2 = 0 gives R [4], C [4], V [[4]], U [[1.0]].

Understand the idea

Adam stores a second-moment number for every weight, which for a big matrix doubles memory. Adafactor keeps only one running mean per row (R) and one per column (C) of the squared gradient, then rebuilds an estimate of the full matrix from them. That is n + m numbers instead of n * m. Worked example with beta2 = 0, ignoring the tiny eps: G = [[1, 2], [2, 4]], so G^2 = [[1, 4], [4, 16]]. Row means R = [2.5, 10], column means C = [2.5, 10], and mean(R) = 6.25. V = outer(R, C) / 6.25 = [[1, 4], [4, 16]], which matches G^2 exactly because this G^2 is rank 1. Then U = G / sqrt(V) = [[1, 1], [1, 1]]. Rule: R = beta2 * R + (1 - beta2) * row mean of (G^2 + eps); C = beta2 * C + (1 - beta2) * column mean of (G^2 + eps); V = outer(R, C) / mean(R); U = G / sqrt(V). Return U with the new R and C. The division by mean(R) is what keeps the scale right. Used in: training T5 and other large models when optimizer memory is tight.

Shapes and data flow

G (n, m) -> row means R (n,), col means C (m,)
V = outer(R, C) / mean(R) -> (n, m)
memory n + m instead of n * m
solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks the hidden tests with Pro.

  • Sample 1: exampleadafactor_update([[2.0]], [0.0], [0.0], 0.0)
  • Sample 2: rank one exactadafactor_update(np.outer([1, 2], [3, 1, 2]), np.zeros(2), np.zeros(3), 0.0)