50 / 90

Day 50: Optimization Mechanics: AdamW Decoupled Weight Decay and Schedules

Derive AdamW update equations, contrast decoupled weight decay with L2 regularization, and implement linear warmup with cosine decay.

Models, Pretraining & LoRA 480 active minutes (8 hours focused study)
01 120 min

AdamW Decoupled Weight Decay Mathematical Derivation

Agent-Assisted Engineering Check

Prerequisites

Gradient descent and momentum from Days 31-33; L2 regularization concepts.

Learning Objective

Derive the AdamW update equation w_{t+1} = w_t (1 - eta * lambda) - eta * m_hat_t / (sqrt(v_hat_t) + eps) and explain why L2 regularization fails in Adam.

Instructions

In standard Adam with L2 regularization, the loss gradient is modified by adding lambda * w. When scaled by the adaptive second moment sqrt(v_t), weights with large historical gradients experience suppressed regularization, while weights with small gradients undergo excessive decay. Loshchilov & Hutter (2019) resolved this by decoupling weight decay directly from gradient scaling. Compute the step 1 update for w_0 = 1.0, lambda = 0.1, eta = 0.01, g_1 = 0.5, beta_1 = 0.9, beta_2 = 0.999, eps = 1e-8.

Practice & Prediction Log

1. Write the update equation for Adam with L2 regularization vs AdamW.
2. Compute step 1 values for m_hat_1, v_hat_1, and updated weight w_1 under AdamW.
3. Why does decoupled weight decay significantly improve Transformer generalization?

Independent Mastery Criterion

Learner derives both update formulas and verifies step 1 numerical values by hand.

Authoritative Source Resources & Provenance

linking arXiv non-exclusive license / Open Access

Decoupled Weight Decay Regularization

Author: Ilya Loshchilov, Frank Hutter | Original Source Link ↗

Relevant Section / Range: Section 2 Decoupling the Weight Decay from the Gradient-Based Update (Algorithm 2, AdamW)

Verified Version & Date: ICLR 2019 / arXiv:1711.05101v3 (Verified: 2026-10-30)

Selection Rationale:

Foundational primary literature defining AdamW, demonstrating that L2 regularization does not equal decoupled weight decay in adaptive gradient algorithms.

Source Prerequisites:

Stochastic gradient descent, L2 regularization, and momentum concepts from Days 31-33.

Safe Fallback (Offline Resilience):

All update equations and mathematical proofs are self-contained in the curriculum lessons.

Compared Candidate Sources & Selection Analysis (2)

Original Adam algorithm implementing L2 regularization via gradient addition, leading to sub-optimal generalization compared to decoupled weight decay.

PyTorch torch.optim.AdamW documentation ↗ compared_alternative [Modified BSD]

Standard library reference; Loshchilov & Hutter provides theoretical mathematical derivations and empirical justification.

linking MIT

nanoGPT: train.py pretraining loop

Author: Andrej Karpathy | Original Source Link ↗

Relevant Section / Range: train.py: optimizer = model.configure_optimizers(weight_decay, learning_rate, (beta1, beta2), device_type)

Verified Version & Date: Git master commit 71c3905 (Verified: 2026-10-30)

Selection Rationale:

Compact historical code reference for the named implementation functions; CS336 spring2025 provides the lead component exercises. Do not infer top-p, atomic persistence or cloud budget enforcement from nanoGPT.

Source Prerequisites:

Python, PyTorch, and Day 46-48 Transformer model architecture.

Safe Fallback (Offline Resilience):

Runnable pretraining scripts and step-by-step tensor mechanics are fully self-contained in the curriculum lessons.

Compared Candidate Sources & Selection Analysis (2)
Hugging Face Accelerate / Trainer ↗ compared_alternative [Apache-2.0]

Heavy abstraction layer wrapping distributed training; nanoGPT exposes raw PyTorch loops without framework overhead.

Megatron-LM (NVIDIA) ↗ compared_alternative [BSD-3-Clause]

High-performance enterprise distributed framework; unsuitable for local educational first-principles comprehension.

02 120 min

Parameter Group Segregation: 2D vs 1D Tensor Decay Rules

Independent Mastery Check

Prerequisites

Activity 50-01 and Transformer architecture from Day 46-48.

Learning Objective

Segregate model parameters into weight decay (2D matrices) and non-decay (1D vectors/biases) groups for optimizer construction.

Instructions

Study source: within this activity's existing reading/practice time, use CS336 Assignment 1: Basics (Spring 2025 tagged release), tests/adapters.py: get_adamw_cls; tests/test_optimizer.py: test_adamw, then explain one connection to the local task in your own words. Keep the local exercise and acceptance checks; use its original explanation if the external source is unavailable. In modern language model training (GPT-3, nanoGPT, LLaMA), weight decay must ONLY be applied to 2D weight matrices (linear projections, attention projections, FFN layers). Biases and 1D normalization parameters (LayerNorm or RMSNorm scale vectors gamma) must NOT be decayed. Decaying normalization scales drives them toward zero, which artificially magnifies activation variances and destabilizes training.

Practice & Prediction Log

1. Write the Python function configure_optimizers(model, weight_decay, learning_rate, betas, device).
2. Given a model with a Linear layer (weight shape (768, 768), bias shape (768)) and an RMSNorm layer (weight shape (768)), specify which parameters receive weight decay.
3. What failure mode occurs if RMSNorm scale gamma is mistakenly subjected to weight decay?

Independent Mastery Criterion

Learner implements parameter segregation based on tensor dimensionality and provides sound architectural rationale for excluding 1D vectors.

Authoritative Source Resources & Provenance

linking MIT

CS336 Assignment 1: Basics (Spring 2025 tagged release)

Author: Stanford University CS336 Staff | Original Source Link ↗

Relevant Section / Range: tests/adapters.py: get_adamw_cls; tests/test_optimizer.py: test_adamw

Verified Version & Date: spring2025 tag; README, tests and MIT LICENSE checked 2026-11-01

Selection Rationale:

Lead assignment-driven source for pretraining component practice and tests. nanoGPT remains a compact historical code-reading companion, not the current recommended training curriculum.

Source Prerequisites:

Fluent Python, PyTorch, and linear algebra

Safe Fallback (Offline Resilience):

Local self-contained pretraining scripts run on standard local CPUs or budget GPUs without Stanford cluster dependency.

Compared Candidate Sources & Selection Analysis (2)
Karpathy nanoGPT ↗ compared_alternative [MIT]

Simpler code layout, useful complementary reference for minimal PyTorch Transformer.

Hugging Face Transformers Course ↗ compared_alternative [Apache-2.0]

High-level API focus rather than building from raw tensor fundamentals.

linking MIT

nanoGPT: train.py pretraining loop

Author: Andrej Karpathy | Original Source Link ↗

Relevant Section / Range: train.py: optimizer = model.configure_optimizers(weight_decay, learning_rate, (beta1, beta2), device_type); the 2D-decay / 1D-no-decay split is in model.py GPT.configure_optimizers

Verified Version & Date: Git master commit 71c3905 (Verified: 2026-10-30)

Selection Rationale:

Compact historical code reference for the named implementation functions; CS336 spring2025 provides the lead component exercises. Do not infer top-p, atomic persistence or cloud budget enforcement from nanoGPT.

Source Prerequisites:

Python, PyTorch, and Day 46-48 Transformer model architecture.

Safe Fallback (Offline Resilience):

Runnable pretraining scripts and step-by-step tensor mechanics are fully self-contained in the curriculum lessons.

Compared Candidate Sources & Selection Analysis (2)
Hugging Face Accelerate / Trainer ↗ compared_alternative [Apache-2.0]

Heavy abstraction layer wrapping distributed training; nanoGPT exposes raw PyTorch loops without framework overhead.

Megatron-LM (NVIDIA) ↗ compared_alternative [BSD-3-Clause]

High-performance enterprise distributed framework; unsuitable for local educational first-principles comprehension.

03 120 min

Learning Rate Scheduling: Linear Warmup and Cosine Decay

Agent-Assisted Engineering Check

Prerequisites

Activity 50-01 and 50-02.

Learning Objective

Implement learning rate schedule function get_lr(it) combining linear warmup with cosine annealing to eta_min, evaluating exact milestone values.

Instructions

Study source: within this activity's existing reading/practice time, use CS336 Assignment 1: Basics (Spring 2025 tagged release), tests/adapters.py: run_get_lr_cosine_schedule; tests/test_optimizer.py: test_get_lr_cosine_schedule, then explain one connection to the local task in your own words. Keep the local exercise and acceptance checks; use its original explanation if the external source is unavailable. Pretraining requires a dynamic learning rate schedule. During the first T_warmup steps, the learning rate increases linearly from 0 to eta_max to prevent early divergence from massive, noisy initial gradients. Afterward, the learning rate decays along a cosine curve down to eta_min = 0.1 * eta_max across T_max steps. For it > T_max, the learning rate remains constant at eta_min.

Practice & Prediction Log

1. State the piecewise mathematical formula for eta(t).
2. Calculate exact learning rates at steps t=0, t=1000, t=3000, and t=5000 given eta_max = 6e-4, eta_min = 6e-5, T_warmup = 1000, and T_max = 5000.
3. Why is smooth cosine decay preferred over discrete step-drop schedules in LLM pretraining?

Independent Mastery Criterion

Learner calculates exact milestone learning rates and implements verified cosine scheduling code.

Authoritative Source Resources & Provenance

linking MIT

CS336 Assignment 1: Basics (Spring 2025 tagged release)

Author: Stanford University CS336 Staff | Original Source Link ↗

Relevant Section / Range: tests/adapters.py: run_get_lr_cosine_schedule; tests/test_optimizer.py: test_get_lr_cosine_schedule

Verified Version & Date: spring2025 tag; README, tests and MIT LICENSE checked 2026-11-01

Selection Rationale:

Lead assignment-driven source for pretraining component practice and tests. nanoGPT remains a compact historical code-reading companion, not the current recommended training curriculum.

Source Prerequisites:

Fluent Python, PyTorch, and linear algebra

Safe Fallback (Offline Resilience):

Local self-contained pretraining scripts run on standard local CPUs or budget GPUs without Stanford cluster dependency.

Compared Candidate Sources & Selection Analysis (2)
Karpathy nanoGPT ↗ compared_alternative [MIT]

Simpler code layout, useful complementary reference for minimal PyTorch Transformer.

Hugging Face Transformers Course ↗ compared_alternative [Apache-2.0]

High-level API focus rather than building from raw tensor fundamentals.

linking arXiv non-exclusive license / Open Access

Decoupled Weight Decay Regularization

Author: Ilya Loshchilov, Frank Hutter | Original Source Link ↗

Relevant Section / Range: Appendix B.2 Adam with Cosine Annealing and Warm Restarts

Verified Version & Date: ICLR 2019 / arXiv:1711.05101v3 (Verified: 2026-10-30)

Selection Rationale:

Foundational primary literature defining AdamW, demonstrating that L2 regularization does not equal decoupled weight decay in adaptive gradient algorithms.

Source Prerequisites:

Stochastic gradient descent, L2 regularization, and momentum concepts from Days 31-33.

Safe Fallback (Offline Resilience):

All update equations and mathematical proofs are self-contained in the curriculum lessons.

Compared Candidate Sources & Selection Analysis (2)

Original Adam algorithm implementing L2 regularization via gradient addition, leading to sub-optimal generalization compared to decoupled weight decay.

PyTorch torch.optim.AdamW documentation ↗ compared_alternative [Modified BSD]

Standard library reference; Loshchilov & Hutter provides theoretical mathematical derivations and empirical justification.

linking MIT

nanoGPT: train.py pretraining loop

Author: Andrej Karpathy | Original Source Link ↗

Relevant Section / Range: train.py: get_lr(it): linear warmup over warmup_iters, cosine decay to min_lr by lr_decay_iters

Verified Version & Date: Git master commit 71c3905 (Verified: 2026-10-30)

Selection Rationale:

Compact historical code reference for the named implementation functions; CS336 spring2025 provides the lead component exercises. Do not infer top-p, atomic persistence or cloud budget enforcement from nanoGPT.

Source Prerequisites:

Python, PyTorch, and Day 46-48 Transformer model architecture.

Safe Fallback (Offline Resilience):

Runnable pretraining scripts and step-by-step tensor mechanics are fully self-contained in the curriculum lessons.

Compared Candidate Sources & Selection Analysis (2)
Hugging Face Accelerate / Trainer ↗ compared_alternative [Apache-2.0]

Heavy abstraction layer wrapping distributed training; nanoGPT exposes raw PyTorch loops without framework overhead.

Megatron-LM (NVIDIA) ↗ compared_alternative [BSD-3-Clause]

High-performance enterprise distributed framework; unsuitable for local educational first-principles comprehension.

04 120 min

Independent Optimizer Configuration and Numerical Verification Exam

Independent Mastery Check

Prerequisites

Activities 50-01 through 50-03.

Learning Objective

Independently write a standalone optimizer setup and schedule module, validating parameter groups and learning rate evolution.

Instructions

In a closed-book assessment, configure an AdamW optimizer for a Transformer with decoupled groups, apply the warmup-cosine schedule, and assert that 1D parameters are never decayed.

Practice & Prediction Log

1. Write the complete script configuring AdamW with betas=(0.9, 0.95), eps=1e-8, and weight_decay=0.1.
2. Provide an assertion checking that no parameter with ndim < 2 has weight_decay > 0.
3. Why is beta_2 often set to 0.95 instead of the classic 0.999 in large language model pretraining?

Independent Mastery Criterion

Learner delivers verified optimizer configuration with strict parameter group assertions and explains the rationale for beta_2=0.95.

Authoritative Source Resources & Provenance

linking arXiv non-exclusive license / Open Access

Decoupled Weight Decay Regularization

Author: Ilya Loshchilov, Frank Hutter | Original Source Link ↗

Relevant Section / Range: Section 2 Decoupling the Weight Decay from the Gradient-Based Update (Algorithm 2, AdamW)

Verified Version & Date: ICLR 2019 / arXiv:1711.05101v3 (Verified: 2026-10-30)

Selection Rationale:

Foundational primary literature defining AdamW, demonstrating that L2 regularization does not equal decoupled weight decay in adaptive gradient algorithms.

Source Prerequisites:

Stochastic gradient descent, L2 regularization, and momentum concepts from Days 31-33.

Safe Fallback (Offline Resilience):

All update equations and mathematical proofs are self-contained in the curriculum lessons.

Compared Candidate Sources & Selection Analysis (2)

Original Adam algorithm implementing L2 regularization via gradient addition, leading to sub-optimal generalization compared to decoupled weight decay.

PyTorch torch.optim.AdamW documentation ↗ compared_alternative [Modified BSD]

Standard library reference; Loshchilov & Hutter provides theoretical mathematical derivations and empirical justification.

linking MIT

CS336 Assignment 1: Basics (Spring 2025 tagged release)

Author: Stanford University CS336 Staff | Original Source Link ↗

Relevant Section / Range: README setup; tests/adapters.py; tests/test_optimizer.py; tests/test_nn_utils.py; tests/test_serialization.py

Verified Version & Date: spring2025 tag; README, tests and MIT LICENSE checked 2026-11-01

Selection Rationale:

Lead assignment-driven source for pretraining component practice and tests. nanoGPT remains a compact historical code-reading companion, not the current recommended training curriculum.

Source Prerequisites:

Fluent Python, PyTorch, and linear algebra

Safe Fallback (Offline Resilience):

Local self-contained pretraining scripts run on standard local CPUs or budget GPUs without Stanford cluster dependency.

Compared Candidate Sources & Selection Analysis (2)
Karpathy nanoGPT ↗ compared_alternative [MIT]

Simpler code layout, useful complementary reference for minimal PyTorch Transformer.

Hugging Face Transformers Course ↗ compared_alternative [Apache-2.0]

High-level API focus rather than building from raw tensor fundamentals.