AdamW With Decay and No-Decay Parameter Groups

Quick Overview

Split a dict of named NumPy parameters into weight decay and no-decay groups, then implement a grouped AdamW optimizer with bias correction and per-group learning rates. It tests decoupled weight decay, input validation, optimizer state across steps and which parameters should skip decay.

AdamW With Decay and No-Decay Parameter Groups

Role: Machine Learning Engineer

Category: Machine Learning

Difficulty: medium

Interview Round: Other

Implement `make_param_groups(params, lr, weight_decay, no_decay_lr=None)`, which splits a dict of named NumPy arrays into a decay group and a no-decay group. Then implement `GroupedAdamW(params, groups, betas=(0.9, 0.999), eps=1e-8)`, a bias-corrected AdamW optimizer whose `step(grads)` updates every parameter with its own group's `lr` and `weight_decay`. For one parameter `p` with gradient `g` at step `t`, using its group's `lr` and `wd`: ```python m = b1*m + (1-b1)*g v = b2*v + (1-b2)*g*g m_hat = m/(1-b1**t) v_hat = v/(1-b2**t) p = p - lr*wd*p - lr*m_hat/(sqrt(v_hat) + eps) # decay uses pre-step p ``` Example: ```python params = {"fc.weight": np.ones((3, 2)), "fc.bias": np.zeros(3), "ln.weight": np.ones(3)} groups = make_param_groups(params, lr=0.01, weight_decay=0.1) # [{'names': ['fc.weight'], 'lr': 0.01, 'weight_decay': 0.1}, # {'names': ['fc.bias', 'ln.weight'], 'lr': 0.01, 'weight_decay': 0.0}] opt = GroupedAdamW(params, groups) out = opt.step({"fc.weight": np.full((3, 2), 0.5)}) # out["fc.weight"] -> every entry ~0.989 (1 - 0.01*0.1*1 - 0.01*1) # out["fc.bias"] -> [0., 0., 0.] # out["ln.weight"] -> [1., 1., 1.] # opt.t == 1 ``` `ln.weight` lands in the no-decay group because it is 1-D. On the first step `fc.weight` loses `0.001` to decay and about `0.01` to the Adam step, while the two no-decay parameters have no gradient and no decay, so they keep their values. ```hint Trace a missing gradient Follow a decayed parameter that has no entry in `grads`, once on the first step and once on a step after it received a real gradient. Compare what moves it in each case. ``` ```hint Validate in one pass The constructor has to catch a name that is unknown, listed twice, or never listed. Pick a structure that lets one walk over the groups detect the first two, then compare it with the parameter names for the third. ``` ### Constraints & Assumptions - A parameter is no-decay if `ndim < 2`, its lowercased name ends with `"bias"`, or its lowercased name contains `"norm"`. Every other parameter decays. - `make_param_groups` returns `[decay, no_decay]`: two dicts with keys `names` (in input order), `lr` and `weight_decay`. The no-decay group uses `weight_decay=0.0` and `no_decay_lr`, which defaults to `lr` when it is `None`. - The constructor raises `ValueError` for a group name that is not in `params`, a name that appears in two groups, or a parameter that is in no group. - Store state as float64 arrays in `self.params`, `self.m` and `self.v`, keyed by name. Initialise `m` and `v` to zeros and `self.t` to 0. - `step(grads)` takes a dict of gradients keyed by name. It increments `t`, updates `m` and `v`, and applies the update above. A missing grad counts as zero. - `step` returns a copy of all params as a dict keyed by name. Never mutate the input params or grads. ### What a Strong Answer Covers - The classification rule applied to each name, with input order kept inside each group and the `no_decay_lr` fallback. - Constructor validation for unknown, duplicated and ungrouped names, and float64 copies of the inputs. - One step counter and one pair of bias-correction factors shared by all groups, with each group's own `lr` and `weight_decay`. - Decay computed from the pre-step weights and kept out of the adaptive denominator. - Handling of missing gradients, and returning copies so callers cannot alter optimizer state. ### Follow-up Questions - Why does AdamW decouple weight decay instead of adding `wd * p` to the gradient? - Why exclude biases and normalization parameters from weight decay? - How would you add a learning-rate schedule that respects per-group base rates?

Overview: Split a dict of named NumPy parameters into weight decay and no-decay groups, then implement a grouped AdamW optimizer with bias correction and per-group learning rates. It tests decoupled weight decay, input validation, optimizer state across steps and which parameters should skip decay.

General logo
General
Nov 24, 2026
mediumMachine Learning EngineerOtherMachine Learning
0
0

Implement make_param_groups(params, lr, weight_decay, no_decay_lr=None), which splits a dict of named NumPy arrays into a decay group and a no-decay group. Then implement GroupedAdamW(params, groups, betas=(0.9, 0.999), eps=1e-8), a bias-corrected AdamW optimizer whose step(grads) updates every parameter with its own group's lr and weight_decay.

For one parameter p with gradient g at step t, using its group's lr and wd:

m = b1*m + (1-b1)*g
v = b2*v + (1-b2)*g*g
m_hat = m/(1-b1**t)
v_hat = v/(1-b2**t)
p = p - lr*wd*p - lr*m_hat/(sqrt(v_hat) + eps)   # decay uses pre-step p

Example:

params = {"fc.weight": np.ones((3, 2)), "fc.bias": np.zeros(3),
          "ln.weight": np.ones(3)}
groups = make_param_groups(params, lr=0.01, weight_decay=0.1)
# [{'names': ['fc.weight'], 'lr': 0.01, 'weight_decay': 0.1},
#  {'names': ['fc.bias', 'ln.weight'], 'lr': 0.01, 'weight_decay': 0.0}]

opt = GroupedAdamW(params, groups)
out = opt.step({"fc.weight": np.full((3, 2), 0.5)})
# out["fc.weight"] -> every entry ~0.989  (1 - 0.01*0.1*1 - 0.01*1)
# out["fc.bias"]   -> [0., 0., 0.]
# out["ln.weight"] -> [1., 1., 1.]
# opt.t == 1

ln.weight lands in the no-decay group because it is 1-D. On the first step fc.weight loses 0.001 to decay and about 0.01 to the Adam step, while the two no-decay parameters have no gradient and no decay, so they keep their values.

Constraints & Assumptions

  • A parameter is no-decay if ndim < 2 , its lowercased name ends with "bias" , or its lowercased name contains "norm" . Every other parameter decays.
  • make_param_groups returns [decay, no_decay] : two dicts with keys names (in input order), lr and weight_decay . The no-decay group uses weight_decay=0.0 and no_decay_lr , which defaults to lr when it is None .
  • The constructor raises ValueError for a group name that is not in params , a name that appears in two groups, or a parameter that is in no group.
  • Store state as float64 arrays in self.params , self.m and self.v , keyed by name. Initialise m and v to zeros and self.t to 0.
  • step(grads) takes a dict of gradients keyed by name. It increments t , updates m and v , and applies the update above. A missing grad counts as zero.
  • step returns a copy of all params as a dict keyed by name. Never mutate the input params or grads.

What a Strong Answer Covers Guidance

  • The classification rule applied to each name, with input order kept inside each group and the no_decay_lr fallback.
  • Constructor validation for unknown, duplicated and ungrouped names, and float64 copies of the inputs.
  • One step counter and one pair of bias-correction factors shared by all groups, with each group's own lr and weight_decay .
  • Decay computed from the pre-step weights and kept out of the adaptive denominator.
  • Handling of missing gradients, and returning copies so callers cannot alter optimizer state.

Follow-up Questions Guidance

  • Why does AdamW decouple weight decay instead of adding wd * p to the gradient?
  • Why exclude biases and normalization parameters from weight decay?
  • How would you add a learning-rate schedule that respects per-group base rates?