Weight decay: follow the update rule
权重衰减
Separate an objective penalty from direct shrinkage using exact SGD identities, a preconditioner counterexample and a schedule audit.
weight-decayWhere does the penalty enter the update?
Two training runs both say “weight decay 0.2.” One shrinks the vector (2, −1) to (1.96, −0.92); the other reaches (1.96, −0.98). Neither number alone identifies a bug. The missing information is whether the shrinkage enters the gradient before coordinate scaling, or acts directly on the parameters.
An L 2 penalty changes an objective. Decoupled weight decay changes an update rule. For plain gradient descent they can produce the same step under matched coefficient conventions. Once the optimizer treats coordinates differently, that shortcut needs checking. Deep Learning, Section 7.1.1, equations 7.2–7.5 derives the plain-gradient case. Loshchilov and Hutter, Section 2 of the fixed v 3 paper makes the distinction explicit for adaptive optimization.
First specify what the coefficient means
Write the data loss as L, its gradient as g, learning rate as η, and penalty as λ times half the squared Euclidean norm. For a plain gradient step:
The gradient of the penalty is λθ. Distributing the subtraction gives the last expression; no statistical assumption is needed for this algebra. The same coordinates must be penalized in both versions, and the loss gradient must be evaluated at the same original θ. Shrinking θ first and then recomputing g is a different algorithm.
Our λ is multiplied by the learning rate. Equation 1 of the cited paper instead writes its decay coefficient directly in the per-step factor. Call that coefficient δ: here δ=ηλ. A number copied between these conventions does not describe the same update unless it is converted.
A two-coordinate counterexample
Let P be a positive diagonal preconditioner, meaning that each gradient coordinate gets its own positive scale. Hold P fixed for this comparison:
Set θ=(2, −1), g=(0, 0), η=1/10, λ=1/5 and P=diag(1, 4). Coupled L 2 subtracts a penalty gradient that is amplified fourfold on the second coordinate: the result is (49/25, −23/25). Decoupled decay gives (49/25, −49/50). Their second coordinates differ by 3/50.
With P=I, the difference vanishes for every θ and g. For a particular vector it may also vanish accidentally; disagreement is not mandatory on every step. The counterexample establishes that the two rules are not generally identical. It is deliberately not an implementation of Adam: real adaptive moments may themselves change when the penalty is mixed into past gradients.
The training schedule changes total shrinkage
If every data gradient is zero and only our decoupled rule acts, repeated substitution yields:
This product does not describe the full parameter trajectory when data gradients are nonzero. It does isolate the decay contribution. At rate 1/10 and λ=1/5, each step retains 49/50: ten steps retain about 0.817073, twenty about 0.667608. “Same epochs and same weight decay” is insufficient if different batch policies produce different numbers of updates.
Compare update rules with exact fractions
This complete Python 3.12 program uses standard-library rational arithmetic. It returns new tuples, leaves its inputs untouched and accepts short vectors, bounded rational values, nonnegative rates/penalties at most one and positive diagonal scales at most 32. These bounds define a teaching contract, not a universal optimizer restriction.
from fractions import Fraction as F
def rational(x, bound=32):
if type(x) not in (int, F) or abs(x)>bound:
raise ValueError('bounded integer or Fraction required')
return F(x)
def step(theta, gradient, lr, decay, scales, mode):
if not 1<=len(theta)<=8 or len(theta)!=len(gradient) or len(theta)!=len(scales):
raise ValueError('matching vectors of length 1 through 8 required')
t,g,p=[tuple(rational(x) for x in v) for v in (theta,gradient,scales)]
eta,lam=rational(lr,1),rational(decay,1)
if eta<0 or lam<0 or any(x<=0 for x in p):raise ValueError('invalid rate, decay or scales')
if mode=='coupled':return tuple(x-eta*s*(v+lam*x) for x,v,s in zip(t,g,p))
if mode=='decoupled':return tuple((1-eta*lam)*x-eta*s*v for x,v,s in zip(t,g,p))
raise ValueError('mode must be coupled or decoupled')
if __name__=='__main__':
for scales in [(1,1),(1,4)]:
for mode in ('coupled','decoupled'):
result=step((2,-1),(0,0),F(1,10),F(1,5),scales,mode)
print('scales:',scales,mode,tuple(str(x) for x in result))
for count in (10,20):
theta=(F(1),)
for _ in range(count):theta=step(theta,(0,),F(1,10),F(1,5),(1,),'decoupled')
print('zero-gradient steps:',count,'retained:',f'{float(theta[0]):.9f}')
Actual output:
scales: (1, 1) coupled ('49/25', '-49/50')
scales: (1, 1) decoupled ('49/25', '-49/50')
scales: (1, 4) coupled ('49/25', '-23/25')
scales: (1, 4) decoupled ('49/25', '-49/50')
zero-gradient steps: 10 retained: 0.817072807
zero-gradient steps: 20 retained: 0.667607972
Tests compare the two literal counterexample vectors, check plain-SGD equality for several gradients and rates, and verify the repeated-update product for a varying schedule. They also check zero learning rate, zero penalty, mismatched shapes, nonfinite input and invalid modes. Each step costs O(d) arithmetic and O(d) output storage for d coordinates. Exact fractions may grow in bit length across many steps; production tensor optimizers use floating-point arithmetic instead.
Shrinking a parameter is not a generalization guarantee
The Euclidean penalty favors small coordinates in the chosen parameterization. Rescaling an input feature can change what a fixed numerical penalty means. Neural networks can also represent the same function with differently scaled parameters, so smaller weight norm does not by itself prove a simpler prediction function or better test accuracy.
Deciding whether to decay biases or normalization scale parameters is part of the model specification. This example decays every supplied coordinate. It does not establish a best exclusion policy, decay value or learning-rate schedule. Those choices require validation under the actual data split and objective.
Our coefficient still interacts with the learning rate through ηλ. “Decoupled” means the decay bypasses the preconditioned gradient path in the displayed rule; it does not mean all hyperparameters become independent. Adding both an explicit L 2 loss and an optimizer decay can apply two penalties, so inspect the effective update before assuming one setting overrides the other.
Can two decay settings really be compared?
- What per-step δ matches η=1/10 and λ=1/5 in our convention?
Answer 1: δ=1/50, so the retained factor is 49/50.
- What are the two second coordinates with P=diag(1, 4) in the zero-gradient example?
Answer 2: Coupled L 2 gives −23/25; decoupled decay gives −49/50.
- If P=I, can a nonzero data gradient alone break the one-step equivalence?
Answer 3: No. The algebra holds for every shared g under the stated conventions.
- Why does doubling the number of zero-gradient steps change the retained norm?
Answer 4: The same shrink factor is multiplied more times: the ten-step factor is squared to obtain the twenty-step factor.
Compare formulas before comparing names
The textbook provides the plain-gradient identity; the AdamW paper distinguishes objective penalties from decay under adaptive updates. The rational counterexample, schedule audit and exercises here are original. No optimizer source code or reported training experiment has been reproduced.
Continue with regularization for the broader statistical problem and epochs and steps for the update counter. A useful experiment record names the penalized parameters, objective reduction, update rule, coefficient convention and number of optimizer steps.
Make a prediction, then check
When do the displayed coupled and decoupled updates agree for all parameter vectors and gradients?
Learning objectives
- Distinguish objective regularization from a parameter-update operation.
- Compare coefficient conventions and cumulative shrinkage.
Prerequisites & connections
Explore related knowledge →References
- Deep Learning — Chapter 7: Regularization for Deep Learning
Ian Goodfellow; Yoshua Bengio; Aaron Courville · 2016 - Decoupled Weight Decay Regularization
Ilya Loshchilov; Frank Hutter · 2019
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. Decay paths, exact dropout distributions, checkpoint restoration and batch-normalization derivatives/state are checked against literal references, analytic identities and finite differences. Three examples use the standard library; BatchNorm uses NumPy1.26.4.
- 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:
- Deep Learning — Chapter 7: Regularization for Deep Learning · Section7.1.1 printed227, equations7.2–7.5: plain-gradient L2 identity; original example and coefficient convention stated separately.
- Decoupled Weight Decay Regularization · Fixedv3 Section2 printed2–3, Eq1 per-step coefficient and diagonal preconditioning distinction; no colored Algorithm2 reconstruction or empirical replication.
Related topics