Run the sign-based Lion optimizer with decoupled weight decay

Lion is a memory-light optimizer: it keeps one momentum buffer and moves every weight by exactly lr times the sign of an interpolated gradient. Getting the order of the two momentum updates right is the whole trick.

Write lion(grad_fn, w0, lr, steps, b1=0.9, b2=0.99, wd=0.0). grad_fn(w) returns the gradient array for weights w. Start with m = zeros. Each step:
1. g = grad_fn(w)
2. c = b1 * m + (1 - b1) * g
3. w = w - lr * (sign(c) + wd * w), using w from before this step inside wd * w. Use np.sign, so sign(0) = 0.
4. m = b2 * m + (1 - b2) * g
Return the final w as an array after all steps. steps = 0 returns w0 as a float array.

Signaturedef lion(grad_fn, w0, lr, steps, b1=0.9, b2=0.99, wd=0.0)

Example

grad_fn(w) = 2 * w, w0 = [1.0, -1.0], lr 0.1, 1 step gives [0.9, -0.9].

Understand the idea

Lion keeps one momentum buffer and moves every weight by the same amount, lr, in the direction given by the sign of a blend of momentum and the current gradient. It uses two betas: b1 to build the step direction, then b2 to update the stored momentum afterwards. Weight decay is added outside the sign. Worked example: grad_fn(w) = 2w, w0 = [2], lr = 0.1, b1 = 0.9, b2 = 0.99, wd = 0.1. Step 1: g = 4, m = 0, c = 0.9 * 0 + 0.1 * 4 = 0.4, sign(c) = 1. w = 2 - 0.1 * (1 + 0.1 * 2) = 2 - 0.12 = 1.88. Then m = 0.99 * 0 + 0.01 * 4 = 0.04. Rule per step: g = grad(w); c = b1 * m + (1 - b1) * g; w = w - lr * (sign(c) + wd * w_old); m = b2 * m + (1 - b2) * g. sign(0) is 0. Doing the momentum update before building c, or putting wd inside the sign, gives different weights. Lion is used to train large vision and language models with less optimizer memory than Adam.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks all 4.

  • Sample 1: examplelion(_quad, [1.0, -1.0], 0.1, 1)
  • Sample 2: zero stepslion(_quad, [1.0, 2.0], 0.1, 0)
  • Test 3: ten steps with decaylion(_shift, [0.0, 0.0, 0.0], 0.05, 10, wd=0.5)
  • Test 4: wavy loss 25 stepslion(_wavy, [2.0, -1.0, 0.3], 0.02, 25, wd=0.1)