AI Wiki中文/EN

Cosine annealing: decide what happens at the end

余弦退火

Test cosine endpoints, actual sampled rates and weight-preserving restart boundaries.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

The cosine is easy; the end of the cycle is the trap

A cosine ramp lowers the learning rate smoothly from an upper value to a lower one. The easy mistake is to draw a curve that reaches its minimum at T, then run only updates 0 through T−1 and claim the last update used that minimum.

Loshchilov and Hutter’s SGDR manuscript, Equation 5, uses a cosine inside repeated runs. The fixed PyTorch 2.8 CosineAnnealingLR documentation explicitly distinguishes its no-restart counter. A cosine formula, a horizon and a boundary policy together define the schedule.

Separate continuous phase from applied integer updates

Let T be a positive duration and u the position inside one half-cosine. The endpoint rates are nonnegative and ordered:

η(u)=ηmin⁡+ηmax⁡−ηmin⁡2(1+cos⁡πuT),0≤u≤T.\eta(u)=\eta_{\min}+\frac{\eta_{\max}-\eta_{\min}}2 \left(1+\cos\frac{\pi u}{T}\right),\qquad 0\leq u\leq T.

The derivative and three reference points give immediate checks:

η′(u)=−π(ηmax⁡−ηmin⁡)2Tsin⁡πuT,η(0)=ηmax⁡,η(T/2)=ηmin⁡+ηmax⁡2,η(T)=ηmin⁡.\eta'(u)=-\frac{\pi(\eta_{\max}-\eta_{\min})}{2T} \sin\frac{\pi u}{T},\qquad \eta(0)=\eta_{\max},\quad\eta(T/2)=\frac{\eta_{\min}+\eta_{\max}}2,\quad\eta(T)=\eta_{\min}.

The slope is zero at both endpoints and nonpositive in between. “Smooth” describes this phase, not a guarantee about training loss. Restarting from the minimum to a larger maximum introduces a jump in the rate even though each individual descent is smooth.

With integer update index t, we implement three policies. clamp uses u=min(t,T), holding the minimum after the horizon. restart uses u=t mod T, resetting the phase while retaining parameters. raw keeps u=t, illustrating that continuing the cosine beyond T makes it rise again. The clamp is our policy; we do not claim the cited PyTorch scheduler automatically clamps.

Which samples actually get used?

For T=4, lower rate 0.1 and upper rate 0.5, the samples at 0 through 4 are 0.5, about 0.441421, 0.3, about 0.158579, and 0.1. Four updates use only the first four. A reset every four integer updates starts the next cycle at t=4, so it never applies the exact minimum at an integer update in that cycle.

Pairing cosine samples shows that their sum over 0 through T−1 is one. Therefore the discrete rate budget and the quadratic trajectory satisfy:

∑t=0T−1η(t)=T(ηmin⁡+ηmax⁡)2+ηmax⁡−ηmin⁡2,θn=θ0∏t=0n−1(1−ηt).\sum_{t=0}^{T-1}\eta(t) =\frac{T(\eta_{\min}+\eta_{\max})}{2}+\frac{\eta_{\max}-\eta_{\min}}2, \qquad \theta_n=\theta_0\prod_{t=0}^{n-1}(1-\eta_t).

The trajectory formula is for the program’s f(θ)=θ²/2. The discrete sum differs from T times the mean endpoint rate. The continuous integral has that latter value, but an integral is not the sum of the rates actually used by a discrete optimizer.

Scheduled rates: Clamp, Restart, Raw continuation
Points are schedule values computed at integer update indices; connecting lines aid comparison. A plotted endpoint is used only if the training run reaches that update.

Compare three boundary policies with the same weights

The complete Python 3.12 standard-library program evaluates the schedule and actually updates a scalar parameter. The phase helper accepts a continuous position for derivative checks; the applied-rate function requires an integer update counter.

from math import cos,pi,isfinite


def phase_rate(u,period,low,high):
    return low+(high-low)*(1+cos(pi*u/period))/2


def rate_at(t,period=4,low=.1,high=.5,mode='clamp'):
    if type(t) is not int or not 0<=t<=10000 or type(period) is not int or not 1<=period<=1000:raise ValueError('bounded integer clock and positive period required')
    if not isfinite(low) or not isfinite(high) or not 0<=low<=high<=1:raise ValueError('ordered finite rates in [0,1] required')
    if mode=='clamp':phase=min(t,period)
    elif mode=='restart':phase=t%period
    elif mode=='raw':phase=t
    else:raise ValueError('unknown boundary policy')
    return phase_rate(phase,period,low,high)


def train(steps=8,mode='clamp',initial=1.,start=0):
    if type(steps) is not int or not 0<=steps<=64 or not isfinite(initial):raise ValueError('bounded steps and finite initial value required')
    theta=float(initial);rows=[]
    for t in range(start,start+steps):
        rate=rate_at(t,mode=mode);theta-=rate*theta;rows.append((rate,theta,theta*theta/2))
    return rows


if __name__=='__main__':
    for mode in ('clamp','restart','raw'):
        rows=train(mode=mode);print(mode,'rates:',[round(r[0],9) for r in rows],'endpoint:',round(rows[-1][1],9))
    print('closed-interval samples 0..T:',[round(rate_at(t),9) for t in range(5)])
    print('four applied-rate sum:',round(sum(rate_at(t) for t in range(4)),9))
    a=train(steps=4,mode='restart');b=train(steps=4,mode='restart',initial=a[-1][1],start=4)
    print('restart preserves weights:',abs(b[-1][1]-train(mode='restart')[-1][1])<1e-15)

Actual output:

clamp rates: [0.5, 0.441421356, 0.3, 0.158578644, 0.1, 0.1, 0.1, 0.1] endpoint: 0.10792845
restart rates: [0.5, 0.441421356, 0.3, 0.158578644, 0.5, 0.441421356, 0.3, 0.158578644] endpoint: 0.02706025
raw rates: [0.5, 0.441421356, 0.3, 0.158578644, 0.1, 0.158578644, 0.3, 0.441421356] endpoint: 0.04870845
closed-interval samples 0..T: [0.5, 0.441421356, 0.3, 0.158578644, 0.1]
four applied-rate sum: 1.4
restart preserves weights: True

The first four applied rates sum to 1.4, while the continuous four-unit integral is 1.2. A restart changes the next rate without resetting θ. The split-run check carries the learned weight into the second cycle and matches the uninterrupted run.

Computing a rate costs O(1) arithmetic and one cosine evaluation. A schedule does not itself add a model-sized state vector; a resume needs the counter, cycle policy and optimizer checkpoint. These curves and scalar trajectories are original examples, not reproductions of SGDR’s image-classification results.

A restart is not a new random initialization

SGDR’s warm restarts reuse the current weights while increasing the rate. Resetting weights or moment buffers would define additional operations. Our restart policy has fixed period and amplitude; growing periods and changing amplitudes require extra rules.

A horizon in epochs and one in optimizer updates are different if the number of updates per epoch changes. Warmup also changes where the cosine phase begins. Record the complete piecewise schedule and the rate actually used on the transition step.

Cosine annealing is not universally superior to step decay. The maximum can still be unstable for the model, and a near-zero minimum can make the final updates negligible. End-of-cycle checkpoint selection must respect validation and deployment objectives; the last weight in every possible schedule is not automatically the best one.

Count the consumed endpoints

  1. Does a four-update run indexed 0…3 use the sample at T=4?

Answer 1: No. That is the next sample.

  1. What does raw do after T?

Answer 2: The cosine rises again; it is neither clamped nor reset.

  1. Does the shown restart erase learned weights?

Answer 3: No. It resets the phase while retaining the parameter.

  1. What is the sum of the first four rates in the example?

Answer 4: 1.4, not the continuous integral 1.2.

Keep the boundary policy next to the equation

The primary paper supplies the cosine and weight-preserving restart idea; the fixed API clarifies its own no-restart convention. Our clamped/raw comparison, discrete sum and boundary tests are original. Continue with warmup and cyclical learning rates.

Make a prediction, then check

What is reset by the shown cosine restart?

Choose one answer

Learning objectives

  • Distinguish horizon endpoint from the last applied update.
  • Specify clamp, continuation or restart.

Prerequisites & connections

Explore related knowledge →

References

  1. SGDR: Stochastic Gradient Descent with Restarts — arXiv1608.03983v1
    Ilya Loshchilov; Frank Hutter · 2016
  2. lr_scheduler.CosineAnnealingLR — 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:

Related topics

No matches. Try a synonym or acronym.

0 results shown

Wrap the whole query in double quotes for a phrase match.