↓ Luncat ka eusi utama
  1. Catetan Rékayasa & Artikel Téknis/

Mathematical Optimization — Tina SGD sareng AdamW ka Learning Rate Schedules

Daptar eusi
Dasar Machine Learning - Artikel ieu mangrupikeun bagian tina hiji séri.
Bagian 3: Artikel ieu

1. Masalah Inti: Naonkeun Naive Gradient Descent Bisa Runtuh dina Skala
#

Dina Part 2, urang ngabuktikeun sanajan classifier biner basajan sapertos Logistic Regression ngahasilkeun persamaan gradient transcendental tanpa solusi aljabar closed-form. Mendakan parameter optimal $w^*$ peryogi iterative numerical optimization—ngalakukeun langkah anu diulang nurun ka handap dina objective surface $J(w)$.

Algoritma pangbasajanana nyaeta Batch Gradient Descent:

$$w_{t+1} = w_t - \eta \nabla_w J(w_t), \qquad \nabla_w J(w_t) = \frac{1}{n} \sum_{i=1}^{n} \nabla_w L(h_{w_t}(x_i), y_i)$$

Dina parabola textbook bersih sareng sabaraha ratus sampel, hiji persamaan ieu jalan tanpa usaha. Dina machine learning sareng deep learning dunya nyata, eta runtuh dina opat sumbu anu beda:

  1. Computational Bottleneck: Ngitung hiji gradient persis peryogi sakali langkungan sadaya $n$ training samples. Lamun $n$ nepi ka jutaan rekaman atawa triliunan tokens, hiji update nyandak jam.
  2. Ill-Conditioned Ravines: Objective surfaces dunya nyata jarang symmetric bowls. Eta ngandung dinding canyon curam dipasang sareng dasar lembah anu datar pisan. Hiji learning rate global $\eta$ tunggal boh diverges kencang kaluar ti dinding canyon atanapi nyingus dina lembah.
  3. High-Dimensional Saddle Points: Dina landscape non-convex, plateau gradient nol mayoritasna saddle points—teu local minima—dimana vanilla gradient descent ngadeukeut.
  4. Parameter Scale Mismatch: Features sareng neural layers anu beda ngabalukarkeun gradients anu beda sabaraha ordo, ngabalukarkeun step size seragam tunggal teu optimal dina sadaya coordinates.

Unggal optimizer utama anu diwangun salila tujuh dekade—tina SGD sareng Momentum nepi ka Adam sareng AdamW—dirancang husus pikeun ngarengsekeun salah sahiji atawa langkung tina modes kagagalan ieu.


2. Intuisi Konsep: Ngarobah Ravines, Noise, sareng Saddle Points
#

Bayangkeun anjeun nangtung buta di jero narrow, steep-walled mountain gorge anu nuur kalayan landai ka danau sabaraha mil ngajar. Ngan hiji instrumen anu aya nyaeta local altimeter anu ngabejakeun arah pangalusna turun sacara langsung handapeun telapak sapatu anjeun.

  • Vanilla Gradient Descent ngalangkah sampurna perpendicular ka contour lines. Sabab dinding gorge langkung curam tibatan dasar lembah, gradient tetep tungtungna ngalintas canyon alih-alih turun kana canyon. Anjeun mantul pulang-pulang antara dinding anu beda sambil kajalan langkung saeutik.
  • Momentum ngaganti telapak sapatu anu teu ngabogaan massa sareng hiji bola basi resep nurun ka gorge. Bounces kenca-katuhu ngalintas dinding curam batalkeun unggalna dina langkah anu runtuyan, sambil slope kajaran leutik anu tetep ngahijikeun velocity nepi ka bola ngalangkah langsung nurun ka lembah.
  • Adaptive Optimizers (RMSProp, Adam) nyaluyukeun panjang langkah sacara mandiri pikeun unggal arah compass—ngalangkah ati-ati, leutik dina sumbu anu curam kencang sareng langkah anjang dina sumbu datar landai.

Kalayan gambaran fisika eta nangtukeun, mari urang mbedah matematika loss surface sareng unggal optimizer anu ngarobah eta.


3. Rumusan Matematis: Geometri Loss Landscape
#

Convexity sareng Condition Number
#

Samemeh minimum smooth $w^*$, Taylor expansion second-order nga-aproksimasi objective function sacara lokal salaku quadratic bowl anu dikadalikeun ku Hessian matrix $H = \nabla^2 J(w^*)$:

$$J(w) \approx J(w^*) + \frac{1}{2} (w - w^*)^\top H (w - w^*)$$

Sabab $H$ symmetric, eigenvalues-na $\lambda_1 \ge \lambda_2 \ge \dots \ge \lambda_d$ ngajelaskeun curvature dina unggal sumbu principal orthogonal. Upami unggal eigenvalue positip kilat ($\lambda_i \gt 0$), surfacena strictly convex.

Kacepetan convergence vanilla gradient descent dikadalikeun ku condition number $\kappa$:

$$\kappa = \frac{\lambda_{\max}}{\lambda_{\min}}$$

Pikeun nyegah iterates diverge dina steepest eigenvector ($\lambda_{\max}$), learning rate kedah muat wates stability kilat:

$$\eta \lt \frac{2}{\lambda_{\max}}$$

Dina optimal fixed step size $\eta^* = \frac{2}{\lambda_{\max} + \lambda_{\min}}$, worst-case error nyumput unggal iterasi ku faktor:

$$\frac{\kappa - 1}{\kappa + 1}$$

Lamun $\kappa = 1$ (perfect circular bowl), gradient descent converge dina hiji langkah. Lamun $\kappa = 1000$ (ravine panjang), error nyumput ngan $0.998$ per iterasi—perlu sarebuan langkah zig-zag pikeun kuluar ti kahulagan modest.

High-Dimensional Saddle Point Trap
#

Dina masalah non-convex (sapertos neural networks), intuisi ti plot 2D nunjukkeun optimization kanjebak dina local minima anu goreng. Dauphin et al. (2014) ngajelaskeun sacara matematis sareng empiris intuisi eta gagal dina dimensi luhur.

Dina unggal critical point dimana $\nabla J(w) = 0$:

  • local minimum peryogi sadaya $d$ eigenvalues tina Hessian positip.
  • local maximum peryogi sadaya $d$ eigenvalues negatip.
  • saddle point kajadian nalika sabaraha eigenvalues positip sareng sabaraha negatip.

Upami tanda unggal eigenvalue dianggap kitu salaku coin flip mandiri dina critical point anu error luhur, probability sadaya $d$ eigenvalues positip scales $2^{-d}$. Dina parameter space sareng $d = 10^6$ weights, hampir unggal stationary point anu ditembong dina latihan mangrupikeun saddle point anu dikurung ku plateau datar dimana gradients ndeukeut ka nol, sanajan arah escape turun tetep aya.


4. Evolusi Iterative Optimizers
#

1. Stochastic & Mini-Batch Gradient Descent (SGD)
#

Ngawangun kana rengking Stochastic Approximation tina Robbins & Monro (1951), Mini-Batch SGD ngalepas gradients persis sadaya-dataset. Dina langkah $t$, urang narik random mini-batch $\mathcal{B}_t \subset S$ ukuran $B \ll n$ sareng ngitung estimasi stochastic gradient anu teu bias:

$$g_t = \frac{1}{B} \sum_{i \in \mathcal{B}_t} \nabla_w L(h_{w_t}(x_i), y_i), \qquad \mathbb{E}[g_t] = \nabla_w J(w_t)$$$$w_{t+1} = w_t - \eta_t g_t$$

Ngaganti $n$ sareng $B$ (biasana 32 nepi ka 4,096) nyadiakeun dua kauntungan kritis:

  • Orders-of-magnitude speedup: Computation per update jadi teu gumantung kana total dataset size $n$.
  • Implicit Saddle-Point Escape: Sabab $g_t = \nabla J(w_t) + \xi_t$ ngadatangan noise sampling zero-mean $\xi_t$, SGD sacara alami jitter kaluar ti saddle point datar dimana Batch GD deterministik bakal mulih.

Trade-off-na asymptotic variance: sareng constant learning rate $\eta$, SGD teu kalaulaweun ngadeukeutkeun $w^*$ persis, tapi orbit di jero noise ball anu radiusna scales sareng $\eta$. Convergence persis peryogi kaayaan jadwal Robbins–Monro:

$$\sum_{t=1}^{\infty} \eta_t = \infty \quad \text{and} \quad \sum_{t=1}^{\infty} \eta_t^2 \lt \infty$$

Dina praktek modern, ieu ngamotive learning rate decay schedules (sapertos cosine annealing).


2. Polyak Momentum (The Heavy Ball Method)
#

Dikenalkeun ku Boris Polyak (1964), Momentum ngajaga velocity vector $v_t$ anu ngahijikeun riwayat gradients kiwari sareng mazmur anu decaying exponential:

$$v_t = \beta v_{t-1} + g_t$$$$w_{t+1} = w_t - \eta v_t$$

Di dieu $\beta \in [0, 1)$ mangrupikeun momentum coefficient (biasana $\beta = 0.9$). Ngabuka recurrence nunjukkeun naonkeun eta ngarengsekeun masalah ravine:

$$v_t = \sum_{k=0}^{t-1} \beta^k g_{t-k}$$
  • Dina arah lembah anu konsisten (dimana $g_t \approx g$ tetep sami tanda), geometric series ngahasilkeun terminal velocity $\frac{1}{1-\beta} g$—ngaronjatkeun effective step size 10× lamun $\beta = 0.9$.
  • Dina dinding canyon anu osilasi (dimana $g_t$ beda tanda), istilah positip sareng negatip batalkeun, nyumputkeun osilasi transverse.

Sacara matematis, Polyak ngabuktikeun optimal momentum ngaronjatkeun worst-case contraction rate dina strongly convex quadratics tina $\frac{\kappa - 1}{\kappa + 1}$ turun ka $\frac{\sqrt{\kappa} - 1}{\sqrt{\kappa} + 1}$—ngarobah condition number $\kappa = 1000$ jadi effective $\sqrt{\kappa} \approx 31.6$.


3. Adaptive Learning Rates: AdaGrad sareng RMSProp
#

Momentum tetep nerapkeun learning rate scalar anu sami $\eta$ ka unggal parameter coordinate. Lamun sabaraha parameter nampi gradients ageung sering sareng sejenna nampi gradients leutik sparse, scaling per-coordinate diperyogikeun.

AdaGrad (Duchi et al., 2011) ngalacak jumlah kumulatif squared gradients per parameter (dimana $\odot$ nandakeun element-wise multiplication):

$$G_t = G_{t-1} + g_t \odot g_t, \qquad w_{t+1} = w_t - \frac{\eta}{\sqrt{G_t} + \epsilon} \odot g_t$$

Coordinates sareng gradients ageung dijero historical ngan di-scale-down kalayan agresif, sambil features sparse anu jarang ngajaga langkah anu langkung ageung. Tapi, sabab $g_t \odot g_t \ge 0$, $G_t$ naek monoton tanpa wates—ngabalukarkeun effective learning rate nyumput sateuacan nepi ka nol dina latihan non-convex lila.

RMSProp (anu diajanjian ku Geoffrey Hinton dina Coursera lecture 2012-na) ngaleungitkeun flawe AdaGrad’s decay ku ngaganti jumlah tak hingga sareng Exponential Moving Average (EMA) tina squared gradients:

$$s_t = \beta_2 s_{t-1} + (1 - \beta_2)(g_t \odot g_t), \qquad w_{t+1} = w_t - \frac{\eta}{\sqrt{s_t} + \epsilon} \odot g_t$$

Ku ngelingkeun riwayat gradient jauh dina rate $\beta_2$ (biasana $0.99$ atawa $0.999$), RMSProp nga-estimasi magnitude root-mean-square lokal tina gradients kiwari tanpa marebutkeun step size.


4. Adam: Adaptive Moment Estimation
#

Diederik Kingma sareng Jimmy Ba (2015) ngahijikeun Momentum (first moment / mean) sareng RMSProp (second raw moment / uncentered variance) ka Adam (Adaptive Moment Estimation):

$$m_t = \beta_1 m_{t-1} + (1 - \beta_1) g_t \qquad \text{(1st moment estimate)}$$$$v_t = \beta_2 v_{t-1} + (1 - \beta_2) (g_t \odot g_t) \qquad \text{(2nd raw moment estimate)}$$

Naonkeun Bias Correction Penting
#

$m_0$ sareng $v_0$ duanana diinisialisasi ka zero vectors. Ngabuka $v_t$ sacara eksplisit nunjukkeun distortion early-step anu parah:

$$v_t = (1 - \beta_2) \sum_{i=1}^{t} \beta_2^{t-i} g_i^2$$

Nyandak ekspektasi (ngasumsikeun roughly stationary gradient second moments $\mathbb{E}[g_i^2] \approx \mathbb{E}[g_t^2]$):

$$\mathbb{E}[v_t] \approx \mathbb{E}[g_t^2] (1 - \beta_2) \sum_{i=1}^{t} \beta_2^{t-i} = \mathbb{E}[g_t^2] (1 - \beta_2^t)$$

Dina langkah $t = 1$ sareng $\beta_2 = 0.999$ standar, $(1 - \beta_2^1) = 0.001$—hartina $v_1$ underestimates true squared gradient scale ku faktor 1,000×. Ngabagi ku $\sqrt{v_1}$ tanpa koreksi bakal ngarobah early-step explosions anu kalacak.

Adam ngeleungitkeun initialization bias ieu kalayan bersih ngalangkungan bias-corrected moments persis:

$$\hat{m}_t = \frac{m_t}{1 - \beta_1^t}, \qquad \hat{v}_t = \frac{v_t}{1 - \beta_2^t}$$$$w_{t+1} = w_t - \eta \frac{\hat{m}_t}{\sqrt{\hat{v}_t} + \epsilon}$$

Catet scale-invariance property tina Adam: upami anjeun ngalikeun sakabeh loss function ku 1,000, $\hat{m}_t$ sareng $\sqrt{\hat{v}_t}$ duanana scale ku 1,000 sareng batalkeun. Unggal parameter update katingal kitu salaku langkah anu smooth, signal-to-noise-ratio-bounded kalayan magnitude $\pm \eta$.


5. The Subtle Flaw in Adam + $L_2$: Decoupled Weight Decay (AdamW)
#

Salila sabaraha taon, practitioners nerapkeun regularization dina Adam sami sareng dina SGD—ku nambahan penalty $L_2$ $\frac{\lambda}{2}\Vert{}w\Vert{}_2^2$ langsung ka loss function, ngarobah gradient jadi $g_t^{\text{reg}} = g_t + \lambda w_t$.

Dina vanilla SGD, regularization $L_2$ sareng multiplicative weight decay sacara aljabar sami:

$$w_{t+1} = w_t - \eta (g_t + \lambda w_t) = (1 - \eta \lambda) w_t - \eta g_t$$

Ilya Loshchilov sareng Frank Hutter (2019) ngabuktikeun ekivalensi ieu leungit sampurna dina adaptive optimizers sapertos Adam.

Lamun anjeun nyocokkeun $\lambda w_t$ ka $g_t$ sateuacan ngitung Adam’s moments, istilah regularization ka-absorb ka $m_t$ sareng $v_t$ sareng lajeng dibagi ku $\sqrt{\hat{v}_t} + \epsilon$:

$$\text{Effective decay in Adam+}L_2 \propto \frac{\eta \lambda}{\sqrt{\hat{v}_t} + \epsilon} w_t$$

Ieu ngahasilkeun distorsi patologis:

  • Parameters sareng gradients historical ageung ($\sqrt{\hat{v}_t}$ ageung) ka-regularization lemah.
  • Parameters sareng gradients historical leutik ($\sqrt{\hat{v}_t}$ leutik) ka-shrinkage agresif anu teu proporsional.
  • Tuning learning rate $\eta$ ngarangkep optimization gradient sareng kekuatan regularization.

AdamW ngarengsekeun ieu kalayan bersih ku decoupling weight decay tina adaptive gradient step:

  1. Ngitung $m_t, v_t, \hat{m}_t, \hat{v}_t$ ngan make gradient data-loss murni $g_t = \nabla_w J(w_t)$.
  2. Nerapkeun multiplicative weight decay langsung ka weights di luar adaptive denominator:
$$w_{t+1} = (1 - \eta \lambda) w_t - \eta \frac{\hat{m}_t}{\sqrt{\hat{v}_t} + \epsilon}$$

Unggal weight ayeuna decay dina rate anu bersih, predictable, teu gumantung kana variance gradient-na. Koreksi aljabar tunggal eta anu ngajelaskeun naonkeun AdamW ngagantikeun standard Adam salaku default optimizer pikeun hampir sadaya pipeline latihan Transformer sareng Large Language Model modern.


5. Learning Rate Schedules: Linear Warmup, Cosine Annealing & WSD
#

Sanajan AdamW nyaluyukeun step sizes per coordinate, ngajaga base learning rate $\eta$ global tetep konstan sakabeh latihan gagal dina skala. Catet Robbins–Monro conditions tina Section 4.1: convergence asymptotic persis dina bawah stochastic gradients peryogi $\sum_{t=1}^{\infty} \eta_t = \infty$ sareng $\sum_{t=1}^{\infty} \eta_t^2 \lt \infty$.

Dina deep neural networks sareng Large Language Models (LLMs), $\eta$ statik ngadaptar dua mode kagagalan anu beda dina dua pungkur latihan:

  • Early training is fragile: Dina random initialization, curvature loss kaos sareng adaptive second-moment estimates $v_t$ noisy sacara statistik. Ngamimitian langsung dina puncak $\eta_{\max}$ bisa ngabalukarkeun divergence anu teu bisa diulah deui atawa ngunci attention heads ka pola degenerate.
  • Late training is noise-limited: Samemeh minimum, variance gradient mini-batch nyegah parameters ngadeukeut. Ngajaga $\eta$ ageung maksa weights mantul salila dina noise ball anu error luhur alih-alih nurun ka dasar basin.

Latihan LLM modern ngarengsekeun pertentangan ieu ngalangkungan learning rate schedule $\eta(t)$—anu dijero dikadalikeun ku Linear Warmup + Cosine Annealing, sareng langkung langkung ngalangkungan Warmup–Stable–Decay (WSD).


5.1 Phase 1: Linear Warmup
#

Dina $T_{\text{warmup}}$ langkah awal (typically ## 5. Summary Comparison of Optimizers.1%$ to $5%$ of total training steps), learning rate naek linier ti nol ka puncakna $\eta_{\max}$:

$\eta_t = \eta_{\max} \cdot \frac{t}{T_{\text{warmup}}}, \qquad 1 \le t \le T_{\text{warmup}}$

Anu dijeropenerapkeun salaku engineering heuristic pikeun ngastabilkeun latihan large-batch ResNet ku Goyal et al. (2017), Linear Warmup kadaptar dina dua mekanisme matematis konkret dina optimization Transformer sareng LLM:

  1. Taming Adaptive Denominator Variance (Liu et al., 2020): Sanajan Adam’s bias correction $\hat{v}_t = v_t / (1 - \beta_2^t)$, early iterations ($t \ll (1 - \beta_2)^{-1}$) nga-estimasi second moment tina ngan sabaraha mini-batches. Liu et al. (2020) ngabuktikeun variance tina adaptive scaling term $1 / \sqrt{\hat{v}_t}$ unbounded dina earliest steps, ngabalukarkeun update anu erratic, oversized sateuacan $v_t$ ngastabilkeun. Linear warmup nyumputkeun step magnitudes sacara persis sambil optimizer ngumpulkeun gradient history anu cukup pikeun ngahasilkeun $\hat{v}_t$ reliable sacara statistik.
  2. Surviving Sharp Initial Curvature & Transformer Gradients (Xiong et al., 2020): Dina initialization, weights aya dina wewengkon high-curvature dimana gradients fluktuasi kencang dina sadaya layer. Xiong et al. (2020) nunjukkeun sacara analitis dina Post-LN Transformers, expected gradient norms sabudeureun output layer disproportionately ageung dina langkah nol; tanpa warmup, early updates ngaruksak representation stability. Sanajan dina Pre-LN Transformers modern (anu ngaronjatkeun gradient flow sacara dramatis), warmup tetep penting dina skala billion-parameter pikeun nyegah early loss spikes.

5.2 Phase 2: Cosine Annealing
#

Sakali warmup rengse dina langkah $T_{\text{warmup}}$, learning rate kedah decay supados optimizer ngaliwatan tina broad exploration ka fine-grained convergence.

Dikenalkeun ku Loshchilov & Hutter (2017) dina SGDR (Stochastic Gradient Descent with Warm Restarts), Cosine Annealing ngalakukeun learning rate decay dina kurva half-cosine smooth ti $\eta_{\max}$ turun ka floor $\eta_{\min}$ dina sisa training horizon $T_{\text{total}}$:

$\eta_t = \eta_{\min} + \frac{1}{2}(\eta_{\max} - \eta_{\min}) \left( 1 + \cos\left( \pi \frac{t - T_{\text{warmup}}}{T_{\text{total}} - T_{\text{warmup}}} \right) \right), \qquad T_{\text{warmup}} \lt t \le T_{\text{total}}$

Dina LLM pre-training, periodic “restarts” tina paper SGDR asalna hampir salawasna dileungitkeun pikeun single cosine decay cycle, sareng terminal floor biasana disetel ka $\eta_{\min} = 0.1\,\eta_{\max}$ (rather than ## 5. Summary Comparison of Optimizers$) supados parameters tetep responsive dina final tokens.

Naonkeun Cosine Shape Jalan
#

Harti normalized decay progress $u = \frac{t - T_{\text{warmup}}}{T_{\text{total}} - T_{\text{warmup}}} \in [0, 1]$. Nyandak turunan dina progress nunjukkeun tilu phase dynamical anu beda:

$\frac{d\eta}{du} = -\frac{\pi}{2}(\eta_{\max} - \eta_{\min}) \sin(\pi u)$

  • Prolonged High-Energy Exploration ($u \approx 0$): Sabab $\sin(\pi u) \approx 0$, learning rate kira-kira teu turun langsung sanggeus warmup, masihan AdamW momentum salila pikeun ngalangkungan broad plateaus sareng kaluar ti sharp basins.
  • Rapid Transition ($u \approx 0.5$): Slope nepi ka nilai negatip pangcuraman, nyumputkeun stochastic noise ball kalayan agresif sambil model ngunci ka loss valley anu menarik.
  • Gentle Final Settling ($u \approx 1$): Slope ngaleungeun deui salaku $\eta_t \to \eta_{\min}$, ngidinan convergence fine-grained tanpa brutal ngateukeun optimization sateuacan.

The Chinchilla Sensitivity Finding
#

Dina ulikan skala Chinchilla ti DeepMind, Hoffmann et al. (2022) nembongkeun persaratan operasional kilat tina Cosine Annealing: cosine cycle length $T_{\text{total}}$ kedah cocog pisan sareng training token budget salaku. Upami anjeun ngonpigurasi jadwal cosine pikeun 100B tokens tapi ngateukeun latihan dina 75B tokens, learning rate teu parantos decay cukup, ninggalkeun substantial validation loss dibandingkeun sareng jadwal anu kalibrasi leres ka 75B tokens.


5.3 The Modern LLM Shift: Warmup–Stable–Decay (WSD)
#

Sensitivitas horizon persis eta nembongkeun major engineering limitation of Cosine Annealing dina frontier LLM pre-training: anjeun kedah nangtukeun $T_{\text{total}}$ sateuacan langkah 1.

Upami hiji organisasi ngelatih model dina 4 triliun tokens make Cosine Annealing sareng langkung milik 2 triliun tokens anu bedua kualitas, continuing pre-training tina final checkpoint nyangsar—learning rate parantos runtuh ka $\eta_{\min}$, sareng re-warming sering ngarobah early destabilizing loss spikes.

Pikeun ngeleungitkeun rigid horizon lock-in ieu, pipeline latihan LLM kiwari—anu dijeropenerapkeun ku MiniCPM (Hu et al., 2024) sareng analisis kilat ku Hägele et al. (2024)—ngadaptar Warmup–Stable–Decay (WSD) (atawa trapezoidal) schedule:

$\eta_t = \begin{cases} \eta_{\max} \cdot \dfrac{t}{T_{\text{warmup}}}, & 1 \le t \le T_{\text{warmup}} \quad \text{(Warmup)} \\ \eta_{\max}, & T_{\text{warmup}} \lt t \le T_{\text{decay}} \quad \text{(Stable Plateau)} \\ \eta_{\min} + (\eta_{\max} - \eta_{\min}) \cdot f_{\text{decay}}\!\left(\dfrac{t - T_{\text{decay}}}{T_{\text{total}} - T_{\text{decay}}}\right), & T_{\text{decay}} \lt t \le T_{\text{total}} \quad \text{(Cooldown)} \end{cases}$

dimana $f_{\text{decay}}(s)$ biasana make linear decay $(1 - s)$ atawa inverse square-root decay $(1 - \sqrt{s})$ dina 10% to 20% final training steps.

WSD nyadiakeun dua kauntungan tetep dibandingkeun sareng Cosine Annealing:

  1. Infinite Continual Pre-Training: Sabab model ngaleuwihan 80–90% waktosna dina plateau $\eta_{\max}$ konstan, researchers bisa tetep ngelatih tanpa wates dina data streams anyar sareng ngarobah cooldown branch anu cepet ti unggal intermediate checkpoint nalika rek ngirim release.
  2. Matching Performance & Annealing Synergy: Hägele et al. (2024) ngajelaskeun dina scaling-law experiments WSD cocog atawa ngaliwatan Cosine schedules anu di-tuning sampurna tanpa ngaterangan $T_{\text{total}}$ sateuacan. Dina resep LLM modern, rapid cooldown phase sering dipasang sareng data quality upshift (math, code, sareng curated reasoning corpora), ngahasilkeun sharp late-stage benchmark gains.

5.4 Schedule Comparison
#

Schedule Functional Form Knows $T_{\text{total}}$ Upfront? Primary Strength Key Limitation
Constant $\eta$ $\eta_t = \eta_0$ No Simplest baseline; easy to resume Early divergence if too high; trapped in noise ball if never cooled
Step Decay Drops by factor $\gamma$ at fixed milestones Yes Clean, predictable drops (classic CNN standard) Requires manual milestone tuning; abrupt loss jolts
Warmup + Cosine Linear ramp + half-cosine to $\eta_{\min}$ Yes (strictly) Smooth exploration-to-convergence curve; battle-tested across LLMs Cannot cheaply extend training past $T_{\text{total}}$ without re-warmup
WSD (Trapezoidal) Linear ramp + constant plateau + fast cooldown No (until cooldown) Supports continual training & cheap multi-horizon scaling laws Validation loss looks artificially high until the cooldown branch runs

5.5 Minimal Implementation: Warmup + Cosine vs. WSD dina NumPy
#

Snippet di handap nerapkeun Linear Warmup + Cosine Annealing sareng WSD ti nol, lajeng ngabandingkeun Constant LR, Cosine (No Warmup), Warmup + Cosine, sareng WSD dina objective noisy, ill-conditioned anu diinisialisasi sareng early gradient shock (ngasimulasikeun early Transformer variance).

import numpy as np

def warmup_cosine_lr(
    step: int,
    total_steps: int,
    warmup_steps: int,
    lr_max: float,
    lr_min: float = 0.0,
) -> float:
    if step <= warmup_steps:
        return lr_max * (step / max(1, warmup_steps))
    progress = (step - warmup_steps) / max(1, total_steps - warmup_steps)
    progress = min(max(progress, 0.0), 1.0)
    return lr_min + 0.5 * (lr_max - lr_min) * (1.0 + np.cos(np.pi * progress))

def wsd_lr(
    step: int,
    total_steps: int,
    warmup_steps: int,
    decay_steps: int,
    lr_max: float,
    lr_min: float = 0.0,
) -> float:
    decay_start = total_steps - decay_steps
    if step <= warmup_steps:
        return lr_max * (step / max(1, warmup_steps))
    if step <= decay_start:
        return lr_max
    progress = (step - decay_start) / max(1, decay_steps)
    progress = min(max(progress, 0.0), 1.0)
    # 1 - sqrt(progress) cooldown curve (Hagele et al., 2024)
    return lr_min + (lr_max - lr_min) * (1.0 - np.sqrt(progress))

# =====================================================================
# Noisy Ill-Conditioned Quadratic + Early Gradient Shock Benchmark
# J(w) = 0.5 * (w0^2 + 50 * w1^2), observed with stochastic gradient noise
# =====================================================================
def run_schedule_experiment(schedule_name: str, lr_fn, total_steps: int = 400):
    rng = np.random.default_rng(123)
    H_diag = np.array([1.0, 50.0])
    w = np.array([8.0, 4.0])
    m, v = np.zeros(2), np.zeros(2)
    b1, b2, eps, lam = 0.9, 0.99, 1e-8, 0.01

    for t in range(1, total_steps + 1):
        # Simulate noisy early-step gradient instability + steady mini-batch noise
        noise_scale = 25.0 if t <= 15 else 2.5
        grad_noise = rng.normal(0.0, noise_scale, size=2)
        g = H_diag * w + grad_noise

        eta = lr_fn(t)

        # AdamW update with scheduled learning rate
        m = b1 * m + (1.0 - b1) * g
        v = b2 * v + (1.0 - b2) * (g ** 2)
        m_hat = m / (1.0 - b1 ** t)
        v_hat = v / (1.0 - b2 ** t)
        w = (1.0 - eta * lam) * w - eta * m_hat / (np.sqrt(v_hat) + eps)

    final_loss = float(0.5 * np.sum(H_diag * (w ** 2)))
    print(f"{schedule_name:<22} | Final Loss: {final_loss:.6f} | w = {np.round(w, 4)}")

T = 400
LR_MAX = 0.25
LR_MIN = 0.025  # 0.1 * LR_MAX

print("=== Learning Rate Schedule Comparison under AdamW (400 steps) ===")
run_schedule_experiment("Constant High LR", lambda t: LR_MAX, T)
run_schedule_experiment(
    "Cosine (No Warmup)", lambda t: warmup_cosine_lr(t, T, 0, LR_MAX, LR_MIN), T
)
run_schedule_experiment(
    "Warmup + Cosine", lambda t: warmup_cosine_lr(t, T, 40, LR_MAX, LR_MIN), T
)
run_schedule_experiment(
    "WSD (1-sqrt decay)", lambda t: wsd_lr(t, T, 40, 80, LR_MAX, LR_MIN), T
)

Ngajelaskeun Kiarana
#

Tilu pola katingal langsung lamun ngajalankeun benchmark ieu:

  1. Constant High LR nurun cepet mimiti, lajeng orbit di jero noisy residual floor sabab step size-na teu kalaulaweun nurun handap tina gradient variance scale.
  2. Cosine (No Warmup) ngalangkah kalayan agresif dina noisy first 15 steps sambil Adam’s second-moment accumulator $v_t$ tetep teu calibrated, ngaroksak weights off-trajectory sateuacan recovery dimimitian.
  3. Warmup + Cosine sareng WSD duanana nyerep early gradient shock kalayan smooth dina first 40 warmup steps, ngalangkah cepet ngalintas flat $w_0$ axis dina $\eta_{\max}$ sampurna, lajeng ngalakukeun cooldown bersih ka dasar lembah—ngahasilkeun final loss anu langkung handap sacara dramatis.

Optimizer trajectories on an ill-conditioned ravine and learning rate schedules

Figure 3. Kenca: Vanilla GD, Momentum, sareng Adam racing turun dina ill-conditioned ravine (kappa = 30). Katuhu: constant LR vs. Linear Warmup + Cosine Annealing vs. WSD.

6. Ringkasan Perbandingan Optimizer
#

Optimizer Core Mechanism Memory Overhead (per param) Primary Strength Key Failure Mode / Limitation
Batch GD Exact full-dataset gradient $0$ Guaranteed monotonic descent on smooth convex surfaces Prohibitive $O(n)$ step cost; stalls on saddle points
Mini-Batch SGD Unbiased noisy gradient over batch $B$ $0$ Fast $O(B)$ updates; noise escapes saddle points; strong generalization Oscillates violently in high-$\kappa$ ravines; sensitive to feature scaling
SGD + Momentum EMA velocity accumulation ($\beta$) $1\times$ ($v_t$) Cancels orthogonal oscillations; accelerates flat valleys ($\kappa \to \sqrt{\kappa}$) Shared scalar $\eta$ still struggles across mismatched parameter scales
AdaGrad Cumulative squared gradient scaling $1\times$ ($G_t$) Excels on sparse tabular/NLP features Monotonic $G_t$ kills learning rate permanently in long runs
RMSProp EMA of squared gradients ($\beta_2$) $1\times$ ($s_t$) Adapts to local curvature without dying learning rate Lacks momentum smoothing and early-step bias correction
Adam 1st + 2nd EMA moments + bias correction $2\times$ ($m_t, v_t$) Fast, robust convergence across scales with minimal tuning Coupled $L_2$ regularization distorts weight shrinkage; higher memory
AdamW Adam + decoupled multiplicative weight decay $2\times$ ($m_t, v_t$) Clean, scale-invariant regularization; standard for Transformers/LLMs $2\times$ optimizer state memory (a bottleneck for multi-billion parameter models)

7. Minimal Implementation: Ravine Race & The Adam vs. AdamW Contrast
#

Script NumPy di handap ngaverifikasi dua klaim teoretis sentral langsung ti nol:

  1. Part A (Ravine Dynamics): Racing Vanilla SGD, SGD + Polyak Momentum, sareng Adam dina ill-conditioned 2D quadratic canyon $J(w_1, w_2) = \frac{1}{2}(w_1^2 + 100 w_2^2)$ sareng condition number $\kappa = 100$.
  2. Part B (Coupled $L_2$ vs. Decoupled Weight Decay): Ngabandingkeun Adam + $L_2$ sareng AdamW dina dua weights anu kajeroan zero-mean oscillating gradients anu skala beda 1,000× ($100.0$ vs. $0.1$).
import numpy as np

# =====================================================================
# PART A: Ill-Conditioned Ravine — J(w) = 0.5 * (w0^2 + 100 * w1^2)
# Condition number kappa = 100; SGD stability limit is lr < 2/100 = 0.02
# =====================================================================
H_diag = np.array([1.0, 100.0])

def ravine_loss(w: np.ndarray) -> float:
    return float(0.5 * np.sum(H_diag * (w ** 2)))

def ravine_grad(w: np.ndarray) -> np.ndarray:
    return H_diag * w

w_init = np.array([10.0, 2.0])
n_steps = 150

# 1. Vanilla SGD (lr near stability ceiling to move as fast as safely possible)
w_sgd = w_init.copy()
for _ in range(n_steps):
    w_sgd -= 0.018 * ravine_grad(w_sgd)

# 2. SGD + Polyak Momentum (beta = 0.9)
w_mom = w_init.copy()
v_mom = np.zeros_like(w_mom)
for _ in range(n_steps):
    v_mom = 0.9 * v_mom + ravine_grad(w_mom)
    w_mom -= 0.018 * v_mom

# 3. Adam (beta1 = 0.9, beta2 = 0.999, eps = 1e-8)
w_adam = w_init.copy()
m = np.zeros_like(w_adam)
v = np.zeros_like(w_adam)
b1, b2, eps = 0.9, 0.999, 1e-8
for t in range(1, n_steps + 1):
    g = ravine_grad(w_adam)
    m = b1 * m + (1.0 - b1) * g
    v = b2 * v + (1.0 - b2) * (g ** 2)
    m_hat = m / (1.0 - b1 ** t)
    v_hat = v / (1.0 - b2 ** t)
    w_adam -= 0.25 * m_hat / (np.sqrt(v_hat) + eps)

print("=== PART A: Ill-Conditioned Ravine (kappa = 100, 150 steps) ===")
print(f"Initial Loss : {ravine_loss(w_init):.4f}  | w = {w_init}")
print(f"Vanilla SGD  : {ravine_loss(w_sgd):.6f} | w = {np.round(w_sgd, 4)}")
print(f"SGD+Momentum : {ravine_loss(w_mom):.6f} | w = {np.round(w_mom, 4)}")
print(f"Adam         : {ravine_loss(w_adam):.6f} | w = {np.round(w_adam, 4)}\n")

# =====================================================================
# PART B: Why Adam + L2 != AdamW under Mismatched Gradient Scales
# Two parameters start at w = [5.0, 5.0] under zero-mean oscillating
# gradients of amplitude [100.0, 0.1] and decay coefficient lam = 0.5
# =====================================================================
lr = 0.01
lam = 0.5
grad_scales = np.array([100.0, 0.1])

w_adam_l2 = np.array([5.0, 5.0])
m_l2, v_l2 = np.zeros(2), np.zeros(2)

w_adamw = np.array([5.0, 5.0])
m_w, v_w = np.zeros(2), np.zeros(2)

for t in range(1, 201):
    g_data = ((-1.0) ** t) * grad_scales  # Pure zero-mean oscillating gradient

    # --- Adam + Coupled L2 Regularization ---
    g_reg = g_data + lam * w_adam_l2
    m_l2 = b1 * m_l2 + (1.0 - b1) * g_reg
    v_l2 = b2 * v_l2 + (1.0 - b2) * (g_reg ** 2)
    m_l2_hat = m_l2 / (1.0 - b1 ** t)
    v_l2_hat = v_l2 / (1.0 - b2 ** t)
    w_adam_l2 -= lr * m_l2_hat / (np.sqrt(v_l2_hat) + eps)

    # --- AdamW (Decoupled Weight Decay) ---
    m_w = b1 * m_w + (1.0 - b1) * g_data
    v_w = b2 * v_w + (1.0 - b2) * (g_data ** 2)
    m_w_hat = m_w / (1.0 - b1 ** t)
    v_w_hat = v_w / (1.0 - b2 ** t)
    w_adamw = (1.0 - lr * lam) * w_adamw - lr * m_w_hat / (np.sqrt(v_w_hat) + eps)

expected_decay = 5.0 * ((1.0 - lr * lam) ** 200)
print("=== PART B: Adam + L2 vs. AdamW (200 steps, lam=0.5, lr=0.01) ===")
print(f"Theoretical uniform decay target : [{expected_decay:.3f}, {expected_decay:.3f}]")
print(f"Adam + L2 weights [big_g, small_g]: {np.round(w_adam_l2, 3)}")
print(f"AdamW     weights [big_g, small_g]: {np.round(w_adamw, 3)}")

Ngajelaskeun Kiarana
#

Ngajalankeun script ieu nembongkeun dua mekanisme inti kalayan bersih:

  1. Ravine Collapse (Part A): Sanajan learning rate-na dikuatkeun dina wates stability ceiling (0.018), Vanilla SGD tetep beres sareng residual loss dina flat axis $w_0$ sabab teu bisa ngalangkah agresif tanpa ngahirup dina $w_1$. Polyak Momentum nyumputkeun loss sabaraha ordo make learning rate anu sami persis, sambing Adam nyamikeun curvature dina dua coordinate sareng nepi ka origin kalayan bersih.
  2. Regularization Asymmetry (Part B): Sabab dua weights duanana dimimitian 5.0 dina pure zero-mean gradient noise, uniform weight decay kedah nyumputkeun duanana sacara symmetric ka ~1.835. AdamW nepi ka [1.835, 1.835] kalayan bersih. Adam + $L_2$, sanajan, kira-kira teu nyumputkeun large-gradient coordinate (tetep sabudeureun 4.95) sambing nyumputkeun small-gradient coordinate kalayan agresif (turun ka ~3.0)—ngabuktikeun sacara numeris kumaha coupled $L_2$ runtuh di jero adaptive denominators.

8. Wates & Jembatan ka Part 4
#

Optimizers sapertos SGD, Momentum, sareng AdamW ngarengsekeun empirical risk minimization—mendakan parameters anu nurunkeun training loss $\hat{R}_n(w)$ kalayan cepet sareng reliable.

Sanajan optimization anu cepet mangrupikeun pedang loro. Optimizer anu agresif dipasang sareng model anu lentur bisa nurunkeun training loss ka nol sambing ngahasilkeun test error anu kalacak—atawa, anu kawenang dina model modern anu overparameterized, tetep ngaronjatkeun test error sanggeus training loss nepi ka nol.

Dina Part 4: Generalization, Bias–Variance Tradeoff & The Double Descent Phenomenon, urang bakal mbedah anatomi matematis tina generalization error, ngabandingkeun geometri regularization $L_1$ vs. $L_2$, sareng ningali kumaha ulikan modern ngahijikeun teori bias–variance klasik sareng regime Double Descent anu ngadalikeun overparameterized AI systems.


Rujukan
#

  1. Robbins, H., & Monro, S. (1951). “A Stochastic Approximation Method.” The Annals of Mathematical Statistics, 22(3), 400–407. (Theoretical foundation of Stochastic Gradient Descent).
  2. Polyak, B. T. (1964). “Some Methods of Speeding Up the Convergence of Iteration Methods.” USSR Computational Mathematics and Mathematical Physics, 4(5), 1–17. (Original formulation of the Heavy Ball / Momentum method).
  3. Duchi, J., Hazan, E., & Singer, Y. (2011). “Adaptive Subgradient Methods for Online Learning and Stochastic Optimization.” Journal of Machine Learning Research (JMLR), 12(61), 2121–2159. (AdaGrad).
  4. Dauphin, Y. N., Pascanu, R., Gulcehre, C., Cho, K., Ganguli, S., & Bengio, Y. (2014). “Identifying and Attacking the Saddle Point Problem in High-Dimensional Non-Convex Optimization.” Advances in Neural Information Processing Systems (NeurIPS 2014).
  5. Kingma, D. P., & Ba, J. (2015). “Adam: A Method for Stochastic Optimization.” International Conference on Learning Representations (ICLR 2015). arXiv:1412.6980.
  6. Loshchilov, I., & Hutter, F. (2019). “Decoupled Weight Decay Regularization.” International Conference on Learning Representations (ICLR 2019). arXiv:1711.05101. (AdamW).
  7. Goyal, P., Dollár, P., Girshick, R., Noordhuis, P., Wesolowski, L., Kyrola, A., Tulloch, A., Jia, Y., & He, K. (2017). “Accurate, Large Minibatch SGD: Training ImageNet in 1 Hour.” arXiv:1706.02677. (Linear scaling rule and gradual warmup).
  8. Loshchilov, I., & Hutter, F. (2017). “SGDR: Stochastic Gradient Descent with Warm Restarts.” International Conference on Learning Representations (ICLR 2017). arXiv:1608.03983. (Cosine Annealing).
  9. Liu, L., Jiang, H., He, P., Chen, W., Liu, X., Gao, J., & Han, J. (2020). “On the Variance of the Adaptive Learning Rate and Beyond.” International Conference on Learning Representations (ICLR 2020). arXiv:1908.03265. (Mathematical proof of early-step adaptive variance and why warmup stabilizes Adam).
  10. Xiong, R., Yang, Y., He, D., Zheng, K., Zheng, S., Xing, C., Zhang, H., Lan, Y., Wang, L., & Liu, T.-Y. (2020). “On Layer Normalization in the Transformer Architecture.” International Conference on Machine Learning (ICML 2020). arXiv:2002.04745. (Analysis of warmup and gradient norms in Post-LN vs. Pre-LN Transformers).
  11. Hoffmann, J., Borgeaud, S., Mensch, A., et al. (2022). “Training Compute-Optimal Large Language Models.” Advances in Neural Information Processing Systems (NeurIPS 2022). arXiv:2203.15556. (Chinchilla empirical findings on matching cosine decay length to token budget).
  12. Hu, S., Tu, Y., Han, X., et al. (2024). “MiniCPM: Unveiling the Potential of Small Language Models with Scalable Training Strategies.” arXiv:2404.06395. (Warmup–Stable–Decay schedule in LLM training).
  13. Hägele, A., Bakouch, E., Kosson, A., Allal, L. B., Von Werra, L., & Jaggi, M. (2024). “Scaling Laws and Compute-Optimal Training Beyond Fixed Training Durations.” Advances in Neural Information Processing Systems (NeurIPS 2024). arXiv:2405.18392. (Systematic analysis of WSD vs. Cosine Annealing and $1 - \sqrt{s}$ cooldown).
Dasar Machine Learning - Artikel ieu mangrupikeun bagian tina hiji séri.
Bagian 3: Artikel ieu