AdamW: separate shrinkage from moment history
AdamW
Inspect decay masks, coefficient conventions and the lasting effects of coupled penalties on Adam state.
adamwKeep the shrinkage out of the moment history
Adding an L 2 penalty to a loss adds its derivative to the gradient. In Adam that derivative then enters both moving moments. AdamW instead shrinks selected weights separately, so the moment history can continue to represent the data-loss gradients.
Loshchilov and Hutter’s ICLR 2019 paper, Algorithm 2 separates these alternatives with color-coded terms. They must not both be applied when implementing one variant. The fixed PyTorch 2.8 AdamW interface gives the rate-scaled shrinkage convention used in our program.
The mask, coefficient and update order are part of the definition
Let gₜ be the data-loss gradient at the old weights. M is a coordinate mask with entries zero or one, ηₜ is the actual learning rate, and λ is our decay coefficient. The hats use Adam’s ordinary zero-initialization corrections:
The decay uses the old parameter vector and is absent from gₜ. M=0 exempts a coordinate from shrinkage but not from the data gradient. Selecting biases or normalization parameters for exemption is an explicit modeling policy, not something the algebra detects automatically.
Under coupled L 2 regularization, the gradient entering the moments changes. Under pure decoupled decay with zero initial moments and explicit zero data gradients, the state has a simple closed form:
This product makes schedule dependence visible: equal λ with different learning rates or numbers of steps does not give equal total shrinkage. The paper writes a base rate α and schedule multiplier sₜ, with decay sₜλpaper. Our API-style convention uses ηₜλ=αsₜλ, so matching these definitions requires λpaper=αλ. Copying the same numerical coefficient between the two notations need not match an experiment.
Shrinking after the whole update adds a cross term
For a scalar adaptive direction u, compare decay of the old weight with shrinking the already updated weight:
For θ=2, η=0.1, λ=0.2, g=0.3, and a first corrected Adam step with ε=0.1, u=0.75. The intended update gives 1.885; shrinking after the adaptive update gives 1.8865. Both may be reasonable algorithms, but they are not algebraically identical.
Turn off the coefficient and watch what remains
The complete Python 3.12 / NumPy 1.26.4 program compares coupled and decoupled updates with β₁=β₂=1/2 and ε=0.1. It uses explicit zero data gradients to isolate regularization, then switches the coefficient off on the second step.
import numpy as np
def update(state,gradient,rate=.1,decay=.2,mask=None,decoupled=True,betas=(.5,.5),eps=.1):
p,m,v,t=state;p,m,v,g=[np.array(x,dtype=np.float64,copy=True) for x in (p,m,v,gradient)]
select=np.ones_like(p) if mask is None else np.asarray(mask,dtype=np.float64)
b1,b2=betas
if p.ndim!=1 or not 1<=p.size<=8 or any(x.shape!=p.shape for x in (m,v,g,select)):raise ValueError('matching bounded vectors required')
if not all(np.isfinite(x).all() for x in (p,m,v,g,select)) or np.any(v<0) or not np.isin(select,[0,1]).all():raise ValueError('finite state, nonnegative moment and binary mask required')
if type(t) is not int or not 0<=t<10000 or not all(np.isfinite(x) for x in (rate,decay,b1,b2,eps)):raise ValueError('valid counter and finite options required')
if not 0<=rate<=1 or not 0<=decay<=1 or not 0<=b1<1 or not 0<=b2<1 or not 0<eps<=1:raise ValueError('invalid optimizer options')
old=p.copy()
if not decoupled:g+=decay*select*old
t+=1;m=b1*m+(1-b1)*g;v=b2*v+(1-b2)*g*g
adaptive=(m/(1-b1**t))/(np.sqrt(v/(1-b2**t))+eps)
p=old-rate*adaptive
if decoupled:p-=rate*decay*select*old
if not all(np.isfinite(x).all() for x in (p,m,v)):raise ValueError('nonfinite update')
return p,m,v,t
def initial():return np.array([2.,-1.]),np.zeros(2),np.zeros(2),0
if __name__=='__main__':
for mode in (True,False):
state=update(initial(),[0,0],decoupled=mode)
later=update(state,[0,0],decay=0,decoupled=mode)
print('decoupled' if mode else 'coupled','first position / first moment / second moment:',*[np.round(x,9).tolist() for x in state[:3]])
print('coefficient switched off, next position:',np.round(later[0],9).tolist())
state=initial()
for rate in (.1,.2,.05):state=update(state,[0,0],rate=rate,mask=[1,0])
print('masked pure-decay endpoint:',np.round(state[0],9).tolist())
state=(np.array([2.]),np.zeros(1),np.zeros(1),0)
correct=update(state,[.3])[0][0];wrong=(2-.1*.3/(.3+.1))*(1-.1*.2)
print('old-weight decay / shrink-after-update:',round(correct,9),round(wrong,9))
Actual output:
decoupled first position / first moment / second moment: [1.96, -0.98] [0.0, 0.0] [0.0, 0.0]
coefficient switched off, next position: [1.96, -0.98]
coupled first position / first moment / second moment: [1.92, -0.933333333] [0.2, -0.1] [0.08, 0.02]
coefficient switched off, next position: [1.879710736, -0.902393226]
masked pure-decay endpoint: [1.862784, -1.0]
old-weight decay / shrink-after-update: 1.885 1.8865
The decoupled first position is (1.96,−0.98), with both moments still zero. The coupled run has stored nonzero regularizer gradients in its moments. Setting its coefficient to zero later does not erase that history, so another step still moves the parameters. This isolates a mechanism; it is not a comparison of equally tuned predictive models.
The masked run shrinks only the first coordinate by 0.98×0.96×0.99 while leaving the second at −1. Tests compare that endpoint with the product formula and verify that zero decay makes the two update branches coincide for arbitrary supplied data gradients. Ordinary work and extra moment storage are O(d) per d-coordinate update.
Decoupled does not mean independent of every training choice
Decoupling removes the penalty from the adaptive moments. It does not make decay independent of the learning-rate schedule, parameterization, selected coordinates or training duration. The pure-decay product applies only with zero initial moments and zero data gradients; existing momentum can still move a weight.
A zero rate leaves parameters fixed in this implementation but still updates the moments and counter. A missing gradient may cause a framework to skip an entire parameter update, including decay, which differs from passing a numerical zero. Our program does not implement skipped-gradient semantics.
The paper motivates decoupling and reports particular experiments; it does not prove that AdamW dominates every optimizer on every task. Generalization needs held-out evaluation and tuned baselines. The implementation here has no AMSGrad, clipping, mixed precision, sparse parameters or full framework compatibility claim.
Separate today’s coefficient from yesterday’s history
- Do decoupled decay terms enter m and v here?
Answer 1: No. Only the supplied data gradients enter those moments.
- Does switching off coupled L 2 erase its earlier contribution to Adam’s state?
Answer 2: No. Earlier contributions remain until the moment recurrences attenuate them.
- Does an excluded coordinate stop receiving data-gradient updates?
Answer 3: No. The mask controls decay only.
- Is shrinking the entire post-gradient parameter the same update?
Answer 4: Generally no. The scalar difference is η²λu under the displayed conventions.
Record which coefficient was actually used
The paper and API use related but differently factored coefficients. The moment-contamination, mask and ordering experiments are original, with no external training benchmark reproduced. Continue with Adam, weight decay and learning-rate schedules.
Make a prediction, then check
What survives after switching off a previously coupled L2 penalty?
Learning objectives
- Keep penalty gradients out of adaptive moments.
- Match rate, mask and coefficient conventions.
Prerequisites & connections
Explore related knowledge →References
- Decoupled Weight Decay Regularization
Ilya Loshchilov; Frank Hutter · 2019 - AdamW — PyTorch 2.8
PyTorch contributors
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-06 · Codex single-agent authored technical review: cited primary-source scope, explicit assumptions, original calculations and counterexamples, runnable tests and bilingual review; not independent human or second-agent review.
- Single-agent authored technical review: bounded primary-source locations, assumptions, original derivations, exact/literal references and matching bilingual equations/examples/exercises. Not independent human or second-agent review.
- Four focused CPython3.12.4 tests passed per chapter. Adaptive accumulators and moments, coefficient/update ordering, checkpoint continuation and schedule boundaries are checked against expanded histories, exact products, literal values and known stability cases. Adagrad/Adam/AdamW use NumPy1.26.4; the other five use the standard library.
- Promoted the full prose, equations, code and exercises. Tests read formal MDX only; removed temporary fallbacks/draft skips and updated review assertion to checked. Algorithm and independent references are unchanged; final record binds both locale hashes.
- Publication navigation points published topics to complete articles and removes corresponding pending wording, retaining directory entries for unwritten targets. Principles, equations, programs and exercises are unchanged; final article SHA values rebound.
Source locations checked:
- Decoupled Weight Decay Regularization · Fixedv3 Algorithm2 physical3 visually inspected: colored coupled versus decoupled terms, schedule/base-rate factoring and discussion after Proposition2.
- AdamW — PyTorch 2.8 · Fixed2.8 main AdamW algorithm: pre-update gradient, old-weight rate-scaled decay, moments excluding penalty; ordinary no-AMSGrad case.
Related topics