56 / 90

Day 56: Week 8 Consolidation: Optimizer to Checkpoint, plus Resource Planning

Retrieve and connect Days 50-55 (AdamW, schedules, the training step, sampling, evaluation, checkpoints) and add the one new tool the cloud runs need: parameter, memory, and compute arithmetic.

Models and Pretraining 480 active minutes (8 hours)
01 120 min

New Material: Parameter, Memory, and Compute Arithmetic

Agent-Assisted Engineering Check

Prerequisites

Day 47 block accounting, Day 48 weight tying, Day 50 AdamW, and Day 55 checkpoints.

Learning Objective

Count GPT parameters exactly, convert them to inference and training memory, and estimate training FLOPs, hours, and cost with the 6ND rule.

Instructions

This is the only new topic today; the rest of the day reviews Week 8. Days 58, 59, 64 and 65 reuse these formulas.
1. Parameters (d = n_embd, V = vocab, L = context): embeddings V*d + L*d; per block 12*d^2 (attention 4*d^2, MLP 8*d^2) + 4*d (two LayerNorms); final LayerNorm 2*d; a tied head adds nothing. This formula leaves out linear-layer biases: GPT-2 has 9*d of them per block (QKV 3d, attention output d, MLP 4d + d). Check your count with PyTorch's sum(p.numel()); the same formula gives GPT-2 Medium (350M: d = 1,024, 24 blocks) 354,601,984, or 354,823,168 with biases.
2. Weights-only memory: bytes per parameter is 4 (FP32), 2 (FP16/BF16), 1 (INT8), 0.5 (INT4).
3. Mixed-precision AdamW training holds 16 bytes per parameter (ZeRO paper): FP16 weights 2 + FP16 gradients 2 + FP32 master weights, first moment and second moment 4 + 4 + 4. Activations come on top and grow with batch size and context; add about 1 GB for the CUDA context.
4. Compute: C = 6 * N * D FLOPs (2ND forward, 4ND backward). Hours = C / (num_gpus * peak FLOP/s * MFU * 3600), with MFU usually 30-50%.

Practice & Prediction Log

1. GPT-2 Small: V = 50,257, L = 1,024, n_layer = 12, n_embd = 768, tied head. Count the parameters with the formula above, and again with GPT-2's linear biases. How many bytes are the weights in FP16?
2. A 1B-parameter model trains with mixed-precision AdamW and needs 8 GB of activations at your batch size. Does it fit on a 24 GB GPU?
3. Train a 125M model on 10B tokens on one A100 (312 TFLOP/s BF16 peak) at 40% MFU and $1.50/hour. Give FLOPs, hours, and cost.

Independent Mastery Criterion

Learner reproduces the exact parameter count with and without linear biases, applies the 16 bytes/parameter rule to predict out-of-memory, and turns 6ND plus MFU into hours and cost.

Authoritative Source Resources & Provenance

linking arXiv non-exclusive license / Open Access

Scaling Laws for Neural Language Models

Author: Jared Kaplan, Sam McCandlish, Tom Henighan, Tom B. Brown, Benjamin Chess, Rewon Child, Scott Gray, Alec Radford, Jeffrey Wu, Dario Amodei | Original Source Link ↗

Relevant Section / Range: Section 2.1 Parameter and Compute Scaling of Transformers (C ≈ 6N FLOPs per token)

Verified Version & Date: arXiv:2001.08361v1 (Verified: 2026-10-30)

Selection Rationale:

Foundational empirical study formulating power laws governing cross-entropy loss with respect to model parameters N, dataset size D, and compute C.

Source Prerequisites:

Basic calculus, logarithms, and parameter counting fundamentals.

Safe Fallback (Offline Resilience):

Scaling formulas, power-law exponents, and parameter compute trade-offs are derived in the lesson text.

Compared Candidate Sources & Selection Analysis (2)

Early formulation of power-law scaling; Kaplan focuses explicitly on autoregressive transformer language models.

General vision/translation scaling; Kaplan specifically establishes modern decoder-only LLM compute budgeting.

linking CC-BY 4.0

Transformer Math 101

Author: Quentin Anthony, Stella Biderman, Hailey Schoelkopf | Original Source Link ↗

Relevant Section / Range: Compute Requirements (C = 6PD) and Memory Requirements: Training

Verified Version & Date: EleutherAI Research Blog (Verified: 2026-10-30)

Selection Rationale:

Widely cited, practical industry guide deriving 6ND compute FLOPs, activation memory, KV cache size, and VRAM estimation.

Source Prerequisites:

Transformer matrix dimensions and matrix multiplication FLOP counting.

Safe Fallback (Offline Resilience):

The 6ND derivation (2ND forward, 4ND backward) and peak VRAM estimation models are fully worked out in the curriculum.

Compared Candidate Sources & Selection Analysis (2)

Rigorous academic formulation; Transformer Math 101 provides accessible step-by-step arithmetic equations.

Kaplan et al. Section 2.1 Compute Budgeting ↗ compared_alternative [Open Access]

Original 6ND approximation; EleutherAI expands on activation memory and KV cache.

linking arXiv non-exclusive license / Open Access

ZeRO: Memory Optimizations Toward Training Trillion Parameter Models

Author: Samyam Rajbhandari, Jeff Rasley, Olatunji Ruwase, Yuxiong He | Original Source Link ↗

Relevant Section / Range: Section 3.1 Model States: Optimizer States, Gradients and Parameters (2Ψ + 2Ψ + KΨ = 16Ψ bytes, K = 12)

Verified Version & Date: SC20 / arXiv:1910.02054v3 (Verified: 2026-10-30)

Selection Rationale:

Source of the 16 bytes per parameter accounting for mixed-precision Adam that the lesson's memory arithmetic uses.

Source Prerequisites:

Adam optimizer mechanics from Day 34 and parameter memory arithmetic.

Safe Fallback (Offline Resilience):

Complete analytical formulas for bytes-per-parameter across AdamW vs SGD and mixed precision are fully provided.

Compared Candidate Sources & Selection Analysis (2)

Focuses on tensor slicing and inter-GPU communication; ZeRO provides the standard breakdown of optimizer and parameter memory footprints.

Micikevicius et al. Mixed Precision Training ↗ compared_alternative [Open Access]

Foundational mixed-precision paper; ZeRO formalizes the exact 16-byte Adam state footprint.

02 120 min

Review Drill: AdamW, Schedules, Clipping, and Sampling (Days 50-52)

Independent Mastery Check (no AI assistance).

Prerequisites

Day 50 AdamW and learning-rate schedules, Day 51 the training step and clipping, Day 52 sampling. Work closed-book; check your Day 50-52 notes only afterwards.

Learning Objective

Recompute one AdamW step, schedule milestones, a clipping factor, and a temperature plus top-p distribution from memory.

Instructions

Retrieval practice: answer first, then check against your notes. 1) Write the AdamW update with bias correction and decoupled weight decay as on Day 50, and recall which tensors get no decay. 2) Write get_lr(it) with linear warmup and cosine decay from Day 50. 3) Write the five-line training step from Day 51 and the clipping rule. 4) Apply temperature and top-p as on Day 52.

Practice & Prediction Log

1. One AdamW step: w0 = 2.0, g = 0.4, lr = 0.01, weight_decay = 0.1, beta1 = 0.9, beta2 = 0.999, ignore eps. Compute m_hat, v_hat, and w1.
2. Which of these get weight decay under the Day 50 rule: attention W^Q, LayerNorm gain, MLP bias, token embedding?
3. Warmup 100 steps to lr_max = 1e-3, cosine to lr_min = 1e-4 at step 1,100. Give lr at steps 50, 100, 600, 1,100 and 2,000.
4. The global gradient norm is 4.0 and max_norm = 1.0. What does clip_grad_norm_ multiply every gradient by? Write the training step in order.
5. Logits [2, 1, 0] at temperature 0.5: give the probabilities, then the distribution after top-p = 0.9.

Independent Mastery Criterion

Learner gets w1 = 1.988, all five schedule values, the 0.25 clip factor, and the top-p distribution right without notes, and gives the correct decay grouping.

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); train.py: get_lr(it): linear warmup over warmup_iters, cosine decay to min_lr by lr_decay_iters; clip_grad_norm_(grad_clip) in the training loop

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

Review Practice: Honest Evaluation and Resumable Checkpoints (Days 53-55)

Agent-Assisted Engineering Check

Prerequisites

Day 53 evaluation and perplexity, Day 54 the failure gallery and ablations, Day 55 checkpoints, and Day 56 activity 1 for sizing.

Learning Objective

Use the Week 8 evaluation and checkpoint rules on one small pretraining run: read its numbers honestly, diagnose its failures, and size a resumable checkpoint.

Instructions

You are reviewing a teammate's 124M-parameter run (N = 124,356,864 from activity 1). 1) Convert validation loss to perplexity and judge overfitting as on Day 53. 2) Classify its sample failures with the Day 54 gallery and compute a Distinct-2 score. 3) Check its checkpoint against the Day 55 rules, and size it with today's arithmetic.

Practice & Prediction Log

1. Final train loss 1.62, best val loss 2.0794 at step 3,000, val loss 2.31 at step 5,000. Give the best perplexity, say whether the run overfits, and say which checkpoint to keep.
2. The teammate split the data by shuffling tokens and then cutting 90/10. What is wrong, and what is the correct split?
3. A greedy sample reads "a b a b a b". Name the failure and compute Distinct-2.
4. Their checkpoint saves only model.state_dict(). After a resume the loss jumps. Explain why, and write a payload that resumes cleanly with an atomic write.
5. How large is that checkpoint with FP32 weights plus the two AdamW moments?

Independent Mastery Criterion

Learner gives PPL 8.0 and the correct checkpoint choice, names the leak and the loop, computes Distinct-2 = 0.4, explains the resume spike, writes a complete atomic payload, and sizes it at about 1.49 GB.

Authoritative Source Resources & Provenance

linking MIT

nanoGPT: model.py architecture implementation

Author: Andrej Karpathy | Original Source Link ↗

Relevant Section / Range: N/A

Verified Version & Date: Git master (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 43-45 attention fundamentals.

Safe Fallback (Offline Resilience):

Local models and classes in the curriculum mirror nanoGPT semantics directly.

Compared Candidate Sources & Selection Analysis (2)
GPT-2 TensorFlow source (OpenAI) ↗ compared_alternative [Modified MIT License]

Original legacy TensorFlow 1.x code; nanoGPT provides clean modern PyTorch equivalent.

Llama 2 / 3 PyTorch source (Meta) ↗ compared_alternative [Llama 2 Community License]

Includes advanced production features (RoPE, GQA), but nanoGPT's simplicity is ideal for the core Days 46-48 assembly.

linking arXiv non-exclusive license / Open Access

The Curious Case of Neural Text Degeneration

Author: Ari Holtzman, Jan Buys, Li Du, Maxwell Forbes, Yejin Choi | Original Source Link ↗

Relevant Section / Range: N/A

Verified Version & Date: ICLR 2020 / arXiv:1904.09751v2 (Verified: 2026-10-30)

Selection Rationale:

Primary source introducing Nucleus (Top-p) sampling and analyzing the failure of greedy decoding (loops, repetition).

Source Prerequisites:

Softmax probabilities, cumulative probability distributions from Days 25-27 and 41-42.

Safe Fallback (Offline Resilience):

Top-p truncation algorithms and worked probability cutoffs are completely explained in the lesson.

Compared Candidate Sources & Selection Analysis (2)

Introduces top-k sampling; Holtzman et al. dynamic nucleus threshold is compared directly against top-k.

Hugging Face Generation Strategies Guide ↗ compared_alternative [Apache 2.0]

Practical library guide; Holtzman provides the foundational mathematical reasoning.

04 120 min

Week 8 Assessment: Pre-flight Plan for a 124M Pretraining Run (Days 50-56)

Independent Mastery Check (no AI assistance).

Prerequisites

Days 50-55 and Day 56 activities 1-3. Closed-book, declared AI-free; a calculator is allowed.

Learning Objective

Independently write a complete, checkable pre-flight plan that joins the Week 8 optimizer, loop, evaluation, and checkpoint rules with today's resource arithmetic.

Instructions

Plan a pretraining run of the activity 1 model (N = 124,356,864) on 2.5B tokens, using one A100 40 GB (312 TFLOP/s peak, assume 35% MFU) at $1.20/hour. Each optimizer step uses 524,288 tokens (micro-batch 16 x 1,024 tokens, 32 accumulation steps). Every number in the plan must show its formula, and the plan must say which numbers are predictions to check against the first real steps.

Practice & Prediction Log

1. How many optimizer steps cover 2.5B tokens? With 2% warmup, how many warmup steps? With lr_max = 6e-4 and lr_min = 6e-5, what is lr halfway through the cosine phase (Day 50)?
2. Static training memory under the 16 bytes/parameter rule. Does it fit in 40 GB, and what limits the micro-batch instead?
3. Total FLOPs, hours, and cost.
4. Write the evaluation and checkpoint policy: how often to call estimate_loss, how to choose the kept checkpoint, what the checkpoint contains, and what you report (Days 51, 53 and 55).
5. Write two sentences for the final report on what a model this size can and cannot show (Day 54).

Independent Mastery Criterion

Learner produces a plan with 4,769 steps, about 95 warmup steps, lr 3.3e-4 at the midpoint, about 1.99 GB static memory, 1.865e18 FLOPs, about 4.74 hours and $5.69, a complete evaluation and checkpoint policy, and an honest capability statement, with each number's formula shown.

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: N/A

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 BSD-3-Clause

PyTorch Tutorial: Saving and Loading Models

Author: PyTorch Documentation Team | Original Source Link ↗

Relevant Section / Range: Saving & Loading a General Checkpoint for Inference and/or Resuming Training

Verified Version & Date: PyTorch 2.x Documentation (Verified: 2026-10-30)

Selection Rationale:

Official documentation detailing state_dict serialization, optimizer state saving, and safe loading patterns.

Source Prerequisites:

Python, PyTorch tensors and nn.Module basics.

Safe Fallback (Offline Resilience):

All checkpoint serialization semantics, dictionary schema keys, and safe recovery steps are self-contained in lesson code.

Compared Candidate Sources & Selection Analysis (2)
TensorFlow tf.train.Checkpoint Guide ↗ compared_alternative [Apache 2.0]

TensorFlow trackable checkpoint architecture; PyTorch's explicit dictionary is our target implementation standard.

Hugging Face Safetensors Documentation ↗ compared_alternative [Apache 2.0]

Safetensors provides safe zero-copy tensor storage without pickle, compared directly when discussing pickle execution risks.