Implement AdamW and Adam with an L2 penalty in NumPy and compare their trajectories

Quick Overview

Implement Adam in NumPy with a switch between decoupled weight decay (AdamW) and an L2 penalty folded into the gradient, then record and compare the two trajectories. It tests moment estimates, bias correction, and how the adaptive denominator changes what weight decay does.

Implement AdamW and Adam with an L2 penalty in NumPy and compare their trajectories

Role: Machine Learning Engineer

Category: Machine Learning

Difficulty: medium

Interview Round: Other

Implement one step of the Adam optimizer in NumPy with a switch that controls how weight decay is applied, then use it to record and compare optimization trajectories. With `decoupled=True` the optimizer is AdamW: the moment estimates see only the loss gradient, and weight decay is applied to the weights directly. With `decoupled=False` it is Adam with an L2 penalty: the decay term is added to the gradient before the moments are updated. ```python class AdamW: def __init__(self, lr=1e-3, beta1=0.9, beta2=0.999, eps=1e-8, weight_decay=0.01, decoupled=True): ... def step(self, params, grad): ... def run_adam(grad_fn, x0, n_steps, lr=1e-3, beta1=0.9, beta2=0.999, eps=1e-8, weight_decay=0.01, decoupled=True): ... def compare_weight_decay(grad_fn, x0, n_steps, lr=1e-3, beta1=0.9, beta2=0.999, eps=1e-8, weight_decay=0.01): ... ``` The pieces must behave as follows: - `step` lazily initializes the moment buffers `m` and `v` to zeros on the first call, increments the step counter `t`, applies bias correction, and returns `p - lr * m_hat / (sqrt(v_hat) + eps)` as a new array. The input arrays are not mutated. - Coupled (`decoupled=False`): use `g + weight_decay * p` as the gradient for both moments. - Decoupled (`decoupled=True`): the moments use the raw `g`, and the update is `p - lr * (adam_update + weight_decay * p)`, where `adam_update` is `m_hat / (sqrt(v_hat) + eps)`. - `run_adam` flattens `x0`, calls `grad_fn(x)` at the current point on every step, and returns an array of shape `(n_steps + 1, d)` with row 0 equal to `x0`. - `compare_weight_decay` returns `{"adamw": ..., "adam_l2": ...}`, the decoupled and coupled trajectories run with the same hyperparameters. Example: ```python opt = AdamW(lr=0.1, weight_decay=0.1, decoupled=True) opt.step(np.array([1.0, -2.0]), np.array([0.5, 0.1])) # -> approx [0.89, -2.08] (the first Adam update is about sign(g)) ``` ```hint Where the decay goes Follow the term `weight_decay * p` through each variant and list every later operation that touches it. ``` ```hint Check the first step by hand At `t = 1`, bias correction turns `m_hat` and `v_hat` into simple functions of `g`. Use that to verify the example before you write the loop. ``` ### Constraints & Assumptions - `params` and `grad` are float arrays of the same shape, and one optimizer instance tracks one parameter array. - `run_adam` treats `x0` as a flat vector of length `d`; `grad_fn` takes and returns a 1-D array of that length. - Hyperparameter defaults are `lr=1e-3`, `beta1=0.9`, `beta2=0.999`, `eps=1e-8` and `weight_decay=0.01`. - NumPy only, with no autograd framework. ### What a Strong Answer Covers - Moment updates, step counter and bias correction in the right order, with the buffers created lazily on the first call - The decay term added to the gradient in the coupled variant and applied straight to the weights in the decoupled one - New arrays returned from `step`, and a trajectory of shape `(n_steps + 1, d)` with `x0` in row 0 - Both runs in `compare_weight_decay` sharing every hyperparameter except `decoupled`, each with its own optimizer state - An explanation of why the adaptive denominator makes the two kinds of decay behave differently ### Follow-up Questions - With a zero loss gradient, why does `adam_l2` move each weight by about `lr` per step while `adamw` shrinks it geometrically? - On the quadratic `0.5 x^T A x - b^T x`, where does the coupled variant converge, and why is that different for AdamW? - Should weight decay apply to biases and LayerNorm parameters?

Overview: Implement Adam in NumPy with a switch between decoupled weight decay (AdamW) and an L2 penalty folded into the gradient, then record and compare the two trajectories. It tests moment estimates, bias correction, and how the adaptive denominator changes what weight decay does.

PracHub logo
General
Nov 25, 2026
mediumMachine Learning EngineerOtherMachine Learning
0
0

Implement one step of the Adam optimizer in NumPy with a switch that controls how weight decay is applied, then use it to record and compare optimization trajectories.

With decoupled=True the optimizer is AdamW: the moment estimates see only the loss gradient, and weight decay is applied to the weights directly. With decoupled=False it is Adam with an L2 penalty: the decay term is added to the gradient before the moments are updated.

class AdamW:
    def __init__(self, lr=1e-3, beta1=0.9, beta2=0.999, eps=1e-8,
                 weight_decay=0.01, decoupled=True): ...

    def step(self, params, grad): ...


def run_adam(grad_fn, x0, n_steps, lr=1e-3, beta1=0.9, beta2=0.999,
             eps=1e-8, weight_decay=0.01, decoupled=True): ...


def compare_weight_decay(grad_fn, x0, n_steps, lr=1e-3, beta1=0.9,
                         beta2=0.999, eps=1e-8, weight_decay=0.01): ...

The pieces must behave as follows:

  • step lazily initializes the moment buffers m and v to zeros on the first call, increments the step counter t , applies bias correction, and returns p - lr * m_hat / (sqrt(v_hat) + eps) as a new array. The input arrays are not mutated.
  • Coupled ( decoupled=False ): use g + weight_decay * p as the gradient for both moments.
  • Decoupled ( decoupled=True ): the moments use the raw g , and the update is p - lr * (adam_update + weight_decay * p) , where adam_update is m_hat / (sqrt(v_hat) + eps) .
  • run_adam flattens x0 , calls grad_fn(x) at the current point on every step, and returns an array of shape (n_steps + 1, d) with row 0 equal to x0 .
  • compare_weight_decay returns {"adamw": ..., "adam_l2": ...} , the decoupled and coupled trajectories run with the same hyperparameters.

Example:

opt = AdamW(lr=0.1, weight_decay=0.1, decoupled=True)
opt.step(np.array([1.0, -2.0]), np.array([0.5, 0.1]))
# -> approx [0.89, -2.08]   (the first Adam update is about sign(g))

Constraints & Assumptions

  • params and grad are float arrays of the same shape, and one optimizer instance tracks one parameter array.
  • run_adam treats x0 as a flat vector of length d ; grad_fn takes and returns a 1-D array of that length.
  • Hyperparameter defaults are lr=1e-3 , beta1=0.9 , beta2=0.999 , eps=1e-8 and weight_decay=0.01 .
  • NumPy only, with no autograd framework.

What a Strong Answer Covers Guidance

  • Moment updates, step counter and bias correction in the right order, with the buffers created lazily on the first call
  • The decay term added to the gradient in the coupled variant and applied straight to the weights in the decoupled one
  • New arrays returned from step , and a trajectory of shape (n_steps + 1, d) with x0 in row 0
  • Both runs in compare_weight_decay sharing every hyperparameter except decoupled , each with its own optimizer state
  • An explanation of why the adaptive denominator makes the two kinds of decay behave differently

Follow-up Questions Guidance

  • With a zero loss gradient, why does adam_l2 move each weight by about lr per step while adamw shrinks it geometrically?
  • On the quadratic 0.5 x^T A x - b^T x , where does the coupled variant converge, and why is that different for AdamW?
  • Should weight decay apply to biases and LayerNorm parameters?