Learning-rate schedules: define the clock first
学习率调度
Compare exact rate sequences and expose a microbatch/update clock mismatch in a real optimization loop.
learning-rate-schedulesA schedule is a function and a clock
“Halve the learning rate every two steps” is incomplete until a step is defined. Two optimizer updates, two microbatches and two epochs can represent very different amounts of work. The formula may be right while the training loop advances its clock at the wrong event.
Stanford CS 231n’s annealing section discusses step, exponential and inverse-time decay. The fixed PyTorch 2.8 StepLR documentation illustrates a scheduler advanced once after each training epoch. Our example deliberately uses an optimizer-update clock, which must be stated rather than inferred from a variable name.
Write down the rate used by the first update
Let t=0 label the first optimizer update, η₀ be the initial rate, K a positive integer period, γ in (0,1] a decay factor, and c a nonnegative inverse-time coefficient. Four deterministic choices are:
The exponential form equals continuous exponential decay sampled at integer t when γ=exp(−k). A time-driven schedule differs from a plateau rule, which waits for a measured validation criterion and needs its own patience and threshold definitions.
For the quadratic in our program, the full gradient is θ−3. Every update has an exact error recurrence:
This makes the entire rate sequence—not just its final value—relevant. Rates strictly between zero and one contract this particular error at every step. Yet arbitrarily fast decay need not reach the optimum: with ηₜ=2⁻ᵗ⁻¹, the total future step budget is finite, and the product of contractions stays positive. The program’s long exponential run settles short of three. Small late updates can mean the schedule has run out of movement, not that the gradient vanished.
Gradient accumulation changes the event count
Suppose G microbatches are averaged per optimizer update, with no partial tail. After b completed microbatches there are u completed updates. At update u, accidentally using the microbatch counter produces:
For G=3 and K=2, the intended first rates are 1/2,1/2,1/4. The wrong clock gives 1/2,1/4,1/16. Both runs see the same gradients per update in this controlled example; the difference comes solely from timekeeping.
Log the applied rate with each parameter update
The complete standard-library Python 3.12 program uses exact fractions. Each microbatch deliberately yields the same scalar gradient, so averaging is easy to audit. It logs the rate actually applied before each update, not merely the scheduler’s next stored value.
from fractions import Fraction as F
def rate_at(t,kind='step',base=F(1,2),gamma=F(1,2),period=2,c=F(1,2)):
base,gamma,c=F(base),F(gamma),F(c)
if type(t) is not int or not 0<=t<=1000 or type(period) is not int or period<1:raise ValueError('bounded nonnegative counter and positive period required')
if not 0<base<1 or not 0<gamma<=1 or c<0:raise ValueError('invalid schedule parameters')
if kind=='constant':return base
if kind=='step':return base*gamma**(t//period)
if kind=='exponential':return base*gamma**t
if kind=='inverse':return base/(1+c*t)
raise ValueError('unknown schedule')
def train(updates=6,microbatches=3,clock='update',kind='step',start=0,theta=F(0)):
if type(updates) is not int or not 0<=updates<=32 or type(microbatches) is not int or not 1<=microbatches<=8:raise ValueError('bounded update and accumulation counts required')
if clock not in ('update','microbatch'):raise ValueError('unknown clock')
theta=F(theta);rows=[]
for t in range(start,start+updates):
gradients=[theta-3 for _ in range(microbatches)]
gradient=sum(gradients)/microbatches
tick=t if clock=='update' else t*microbatches
rate=rate_at(tick,kind);theta-=rate*gradient
rows.append((tick,rate,theta))
return rows
if __name__=='__main__':
for kind in ('constant','step','exponential','inverse'):
rows=train(kind=kind);print(kind,'rates:',[str(r[1]) for r in rows],'endpoint:',str(rows[-1][2]))
wrong=train(clock='microbatch');print('microbatch-clock rates:',[str(r[1]) for r in wrong]);print('microbatch-clock endpoint:',str(wrong[-1][2]))
prefix=train(updates=3);resumed=train(updates=3,start=3,theta=prefix[-1][2])
print('resumed update clock matches:',resumed[-1]==train()[-1])
print('32-step exponential endpoint:',round(float(train(updates=32,kind='exponential')[-1][2]),9))
Actual output:
constant rates: ['1/2', '1/2', '1/2', '1/2', '1/2', '1/2'] endpoint: 189/64
step rates: ['1/2', '1/2', '1/4', '1/4', '1/8', '1/8'] endpoint: 10965/4096
exponential rates: ['1/2', '1/4', '1/8', '1/16', '1/32', '1/64'] endpoint: 4445871/2097152
inverse rates: ['1/2', '1/3', '1/4', '1/5', '1/6', '1/7'] endpoint: 18/7
microbatch-clock rates: ['1/2', '1/4', '1/16', '1/32', '1/128', '1/256']
microbatch-clock endpoint: 267121959/134217728
resumed update clock matches: True
32-step exponential endpoint: 2.133635715
The resume test saves θ and the completed update count. Reusing the correct absolute counter reproduces the uninterrupted endpoint. Restarting the counter at zero would replay large rates and change the run.
Schedule evaluation here is O(1) arithmetic per update, apart from exact rational-number bit cost. A real network’s gradient computation remains dominant. The toy loop stores a trace for inspection; production logging can sample rates without retaining every tensor.
Match the budget before interpreting the curve
An epoch-based schedule changes when dataset size or batch size changes; an update-based schedule does not preserve the same number of data exposures automatically. Report the chosen clock, number of optimizer updates, accumulation policy and first/last applied rates.
Calling a framework scheduler before its intended update can shift the rate sequence. Check the actual API contract and log values around every boundary. A warmup or another scheduler can multiply or replace rates, so an isolated closed form may no longer describe the combined run.
The example uses ordinary gradient descent and a fixed convex objective. In momentum and adaptive optimizers, the same scalar rate also interacts with stored state. Neither the exponential plateau here nor a particular preferred decay pattern should be generalized to every training task. Hyperparameter choices need validation under the intended compute budget.
Audit the boundaries
- What rate is applied at t=0 in the step schedule?
Answer 1: The base rate η₀.
- With K=2, which update first uses the halved rate?
Answer 2: The update indexed t=2, the third update.
- Does a very small final learning rate prove convergence?
Answer 3: No. The exponential example retains a nonzero gradient while its updates become tiny.
- What counter must be restored for exact update-clock continuation?
Answer 4: The number of completed optimizer updates, together with the optimizer’s parameter and state checkpoint.
Add shape only after fixing the clock
The course supplies decay families and the fixed API an explicit call pattern. The accumulation-clock counterexample, contraction product and exact resume test are original. Continue with warmup, cosine annealing and cyclical rates.
Make a prediction, then check
With a zero-based update clock and period two, when is the first decay applied?
Learning objectives
- Define the applied-rate clock and boundary convention.
- Resume without shifting the rate sequence.
Prerequisites & connections
Explore related knowledge →References
- CS231n: Neural Networks, Part 3 — Learning
Stanford CS231n course staff - lr_scheduler.StepLR — 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.
- Bilingual charts generated with Matplotlib3.9.1 from the executed schedule functions; plotted values may extend past the printed run and are explicitly labeled as schedule samples. Both SVGs and source samples are hash-bound.
Source locations checked:
- CS231n: Neural Networks, Part 3 — Learning · Annealing the learning rate subsection: step, exponential, inverse-time and validation-triggered decay; recommendations treated as contextual.
- lr_scheduler.StepLR — PyTorch 2.8 · Fixed2.8 StepLR definition and example: periodic multiplicative change, calls after each training epoch, explicit scheduler state.
Related topics