51 / 90

Day 51: Running the Pretraining Loop: Loss Tracking, Checkpointing, and Failure Diagnosis

Assemble the forward-loss-backward-step loop, implement train/eval loss estimation, save/resume checkpoints, and diagnose loss explosion.

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

The Core Pretraining Step: Forward, Loss, Backward, and Gradient Clipping

Agent-Assisted Engineering Check

Prerequisites

Dataloader from Day 49 and AdamW optimizer from Day 50.

Learning Objective

Execute the canonical 5-step pretraining iteration, understand memory deallocation via set_to_none=True, and apply L2 gradient norm clipping.

Instructions

Study source: within this activity's existing reading/practice time, use CS336 Assignment 1: Basics (Spring 2025 tagged release), tests/adapters.py: run_gradient_clipping; tests/test_nn_utils.py: test_gradient_clipping, 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 every pretraining step: (1) optimizer.zero_grad(set_to_none=True) deallocates gradient buffers; (2) logits, loss = model(x, y) computes forward activations and cross-entropy; (3) loss.backward() accumulates partial derivatives; (4) torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0) clamps the total gradient vector norm to 1.0; (5) optimizer.step() applies AdamW updates. Trace why gradient clipping prevents catastrophic weight corruption.

Practice & Prediction Log

1. Write the Python code executing one full training step.
2. If the unclipped global gradient norm is ||g||_2 = 5.0 and max_norm = 1.0, what scaling multiplier is applied to every parameter's gradient?
3. Why is optimizer.zero_grad(set_to_none=True) strictly superior to optimizer.zero_grad()?

Independent Mastery Criterion

Learner implements the canonical 5-step training step, calculates gradient scaling factors, and articulates memory benefits of set_to_none=True.

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_gradient_clipping; tests/test_nn_utils.py: test_gradient_clipping

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: training loop (while True): forward under ctx, scaler.scale(loss).backward(), clip_grad_norm_(grad_clip), scaler.step(optimizer)

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

Train vs Validation Loss Estimation and Overfitting Tracking

Independent Mastery Check

Prerequisites

Activity 51-01 and PyTorch autograd mechanics.

Learning Objective

Implement stochastic evaluation function estimate_loss(model, eval_iters=200) under torch.no_grad() and model.eval() to monitor generalization.

Instructions

Per-batch training loss fluctuates due to batch variance. To measure true progress, evaluate the model over 200 batches for both 'train' and 'val' splits at regular intervals (e.g. every 250 steps). Switch to model.eval() to disable dropout, and wrap in with torch.no_grad(): to prevent computation graph creation in GPU memory.

Practice & Prediction Log

1. Write the estimate_loss(model, eval_iters) helper function.
2. What critical GPU memory failure occurs if estimate_loss is executed without torch.no_grad()?
3. How do diverging train loss and validation loss curves identify the onset of overfitting?

Independent Mastery Criterion

Learner implements an evaluation loop under eval mode and no_grad context, correctly identifying overfitting indicators.

Authoritative Source Resources & Provenance

linking MIT

nanoGPT: train.py pretraining loop

Author: Andrej Karpathy | Original Source Link ↗

Relevant Section / Range: train.py: estimate_loss() averages eval_iters batches per split; run every eval_interval

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.

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.

03 120 min

Checkpoint Serialization, Atomic Saving, and Resumption

Agent-Assisted Engineering Check

Prerequisites

Activities 51-01 and 51-02.

Learning Objective

Serialize model weights, AdamW optimizer moments, iteration count, and validation loss into a checkpoint; implement bit-for-bit resume logic.

Instructions

Study source: within this activity's existing reading/practice time, use CS336 Assignment 1: Basics (Spring 2025 tagged release), tests/adapters.py: run_save_checkpoint, run_load_checkpoint; tests/test_serialization.py: test_checkpointing, 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 runs take hours or days and can be interrupted by node preemptions. Save checkpoints containing model.state_dict(), optimizer.state_dict(), iter_num, best_val_loss, and config. To prevent file corruption if a process dies during torch.save(), write to a temporary file first and atomically rename using os.replace.

Practice & Prediction Log

1. Provide the complete checkpoint saving code snippet with atomic write pattern.
2. Write the resumption code restoring model, optimizer, iter_num, and best_val_loss.
3. What optimization anomaly occurs if you resume training from model weights but omit optimizer.state_dict()?

Independent Mastery Criterion

Learner writes robust checkpoint saving and resumption routines and explains the consequences of cold optimizer states.

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_save_checkpoint, run_load_checkpoint; tests/test_serialization.py: test_checkpointing

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: checkpoint dict {'model', 'optimizer', 'model_args', 'iter_num', 'best_val_loss', 'config'} written with torch.save to out_dir/ckpt.pt; the init_from == 'resume' branch reloads it

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

Pretraining Loop Execution and Anomaly Diagnosis Exam

Independent Mastery Check

Prerequisites

Activities 51-01 through 51-03.

Learning Objective

Operate a complete pretraining script, inspect observed metrics without unsupported claims, and diagnose pretraining anomalies (NaN loss, plateau).

Instructions

In a closed-book capstone setting, analyze and diagnose common failure modes in pretraining runs: (1) Sudden loss explosion to NaN; (2) Persistent loss plateau at ln(V) ≈ 10.8; (3) Gradual drift after 500 steps. Execute a reference run on a small dataset and report verified loss reduction.

Practice & Prediction Log

1. State the top 3 root causes for loss turning into NaN during pretraining and their respective remedies.
2. If loss remains stuck at ~10.8 across hundreds of steps, what failure has occurred?
3. Report expected loss behavior over 50 steps on a small character or token dataset without making unsupported convergence claims.

Independent Mastery Criterion

Learner accurately diagnoses pretraining failure modes and explains training dynamics without making unsupported claims.

Authoritative Source Resources & Provenance

linking MIT

nanoGPT: train.py pretraining loop

Author: Andrej Karpathy | Original Source Link ↗

Relevant Section / Range: train.py: config defaults, get_lr(it) and the training loop (while True)

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.

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.