Skip to content

B.4 Pass 2: Foundations

The tracer’s bigram was fitted by counting, which works for a bigram and for nothing larger. Every later model is trained by gradient descent, and gradient descent needs an autograd engine you can trust, which in turn needs the mathematics underneath it: logarithms and units of information, derivatives and finite differences, Taylor series, linear algebra, probability, floating point, and optimization. This pass builds all of it. It is the longest pass in the course and the one that pays off most often later.

Concepts from other sections (47)

This section uses these ideas. Each has a short definition and a link to the section that explains it in full. Tap a dotted term in the text to preview it.

The pass reads in two movements. The first is mathematics, from Mathematics, with a problem set after each topic so you can check that the ideas hold under your own hands. The second is the autograd itself, from AI Engineering: tensors with broadcasting backward passes, an op library checked by gradcheck, fused losses, modules, a training loop, and atomic checkpoints with a token stream. At the end the autograd retrains the tracer’s bigram by gradient descent, gets the count MLE back, and the engine serves the result unchanged, because the checkpoint contract fixed in Pass 1 has not moved.

Learning objectives

  • Derive the calculus, linear algebra, probability, and numerics results the autograd relies on, and work each problem set.
  • Explain how gradcheck compares analytic gradients with central differences and how its tolerance is chosen.
  • Explain each op’s backward pass, the fused softmax cross-entropy backward, and how the module system registers parameters.
  • Trace a training step and explain why the autograd bigram converges to the count bigram.
  • Explain why checkpoints are written atomically and how a resumed run ends bitwise equal to an uninterrupted one.

This pass needs Pass 1. In particular, the byte bigram and its checkpoint format are the target the autograd must reproduce.

Read the sections in order. The problem sets come right after the topics they exercise:

  1. Problem set: functions, logarithms, trigonometry, series, polynomials, and inequalities. Afterwards you can work every problem in the set and explain each answer.
  2. Exponents, logarithms, and units of information. Afterwards you can explain how logs convert between bases and units of information (bits, nats).
  3. Trigonometry, rotations, complex numbers, and Euler’s formula. Afterwards you can explain how a 2D rotation is a multiplication by a unit complex number via Euler’s formula.
  4. Sequences, geometric series, and frequency ladders. Afterwards you can explain how a geometric series builds a frequency ladder and what its sum is.
  5. Polynomials, Horner’s rule, and stable quadratic roots. Afterwards you can explain why Horner’s rule evaluates a polynomial in n multiplies and why the stable quadratic formula avoids cancellation.
  6. Derivatives and Finite Differences. Afterwards you can explain why the central difference is second-order accurate and how the step size balances truncation against rounding error.
  7. Newton’s Method. Afterwards you can explain why Newton’s method converges quadratically near a simple root and when it fails.
  8. Taylor series, remainder bounds, and range reduction. Afterwards you can explain how range reduction keeps a Taylor series short and how the remainder bound sets the number of terms.
  9. Activation Functions and Their Derivatives. Afterwards you can derive each activation function’s derivative and explain how the solution keeps it numerically stable.
  10. Calculus 1 Problem Set. Afterwards you can work every problem in the set and explain each answer.
  11. Series convergence, the EMA as a geometric series, and bias correction. Afterwards you can explain why an EMA is a geometric series and why bias correction divides by 1 - beta^t.
  12. Calculus 2 problem set: integration techniques, the Gaussian, series, Taylor, polar, and ODEs. Afterwards you can work every problem in the set and explain each answer.
  13. Partial derivatives, gradients, and gradcheck. Afterwards you can explain how gradcheck compares an analytic gradient with central differences and how its tolerance is chosen.
  14. Jacobians, the multivariable chain rule, and numeric JVP/VJP. Afterwards you can explain how the multivariable chain rule composes Jacobians and how numeric JVPs and VJPs are computed.
  15. Calculus 3 problem set: vectors, gradients, the chain rule, Hessians, multiple integrals, Lagrange. Afterwards you can work every problem in the set and explain each answer.
  16. Discrete math 1 problem set: sets, counting, proofs, induction, relations, bijections. Afterwards you can work every problem in the set and explain each answer.
  17. Graphs, DAGs, and an iterative topological sort. Afterwards you can explain how the iterative topological sort orders a DAG and how it detects a cycle.
  18. Discrete math 2 problem set, part a: DAGs, modular arithmetic, hashing. Afterwards you can work every problem in the set and explain each answer.
  19. Modular arithmetic, hashing, and PCG32 in Python. Afterwards you can explain how PCG32 advances its state with modular arithmetic and permutes its output, and how the hash is computed.
  20. Gaussian elimination and LU with partial pivoting. Afterwards you can explain why LU needs partial pivoting and how it solves a linear system.
  21. Random variables, expectation, variance, and normal draws by Box-Muller. Afterwards you can explain how Box-Muller turns two uniforms into normal draws and how expectation and variance are estimated.
  22. Orthogonality, Householder QR, and orthogonal initialization. Afterwards you can explain how Householder reflections build QR and how that gives an orthogonal initialization.
  23. Eigenvalues, power iteration, and the spectral radius. Afterwards you can explain why power iteration converges to the dominant eigenvector and what the spectral radius says about a recurrence.
  24. Linear algebra problem set, part a: elimination, LU, bases, rank, determinants, eigenvalues, QR. Afterwards you can work every problem in the set and explain each answer.
  25. Probability problem set, part a: axioms, Bayes, random variables, Box-Muller. Afterwards you can work every problem in the set and explain each answer.
  26. IEEE 754 anatomy, ulps, and round to nearest even. Afterwards you can decode an IEEE 754 value by hand, measure its ulp, and explain how round to nearest even produces bf16 and fp16.
  27. Stable numerics: logsumexp, softmax, and compensated sums. Afterwards you can explain why logsumexp subtracts the max and how a compensated sum recovers lost low-order bits.
  28. Problem set A: representation, rounding, and cancellation. Afterwards you can work every problem in the set and explain each answer.
  29. Entropy, cross-entropy, KL, JS, and the k3 estimator. Afterwards you can explain how entropy, cross-entropy, KL, and JS relate and why the k3 estimator is unbiased and non-negative.
  30. Information theory problem set, part a: entropy, chain rules, KL and cross-entropy. Afterwards you can work every problem in the set and explain each answer.
  31. Dual numbers and forward-mode autodiff. Afterwards you can explain how dual numbers carry a derivative through forward-mode autodiff.
  32. Scalar reverse mode: the Value graph. Afterwards you can trace how the Value graph is topologically sorted and how backward accumulates gradients in reverse.
  33. Matrix differentials, the trace trick, and closed-form VJPs. Afterwards you can derive closed-form VJPs with matrix differentials and the trace trick.
  34. Matrix calculus problem set: differentials, trace trick, VJPs, SDPA Jacobian. Afterwards you can work every problem in the set and explain each answer.
  35. Convexity, smoothness, gradient descent, and Armijo line search. Afterwards you can explain how smoothness bounds the gradient-descent step and how Armijo line search picks a step that decreases the loss.
  36. The Optimizer protocol: SGD, momentum, Nesterov, weight decay. Afterwards you can explain how the Optimizer protocol implements SGD, momentum, Nesterov, and weight decay.
  37. Adam and AdamW: bias correction and decoupled weight decay. Afterwards you can explain why Adam corrects its moment bias and why AdamW decouples weight decay from the gradient.
  38. Learning-rate schedules (cosine, WSD, Noam) and gradient clipping. Afterwards you can explain how cosine, WSD, and Noam schedules set the learning rate and how global-norm clipping rescales gradients.
  39. Optimization problem set, part a: convexity, GD rates, momentum, Adam. Afterwards you can work every problem in the set and explain each answer.
  40. Variance propagation and initialization. Afterwards you can derive how variance propagates through a layer and why that sets the initialization scale.
  41. TDD, unit tests, and how your tests are graded. Afterwards you can explain how test-first unit tests pin down behavior and what a mutation score says about a test suite.
  42. Tensor, broadcasting backward, and no_grad. Afterwards you can explain how broadcasting backward sums gradients over broadcast axes and how no_grad stops graph building.
  43. The op library and gradcheck_all. Afterwards you can explain each op’s backward in the op library and how gradcheck_all verifies them.
  44. Losses with a fused backward. Afterwards you can derive the fused softmax cross-entropy backward and explain why fusing it is more stable.
  45. Module system and basic layers. Afterwards you can explain how the module system registers parameters and how the basic layers are built on it.
  46. Training loop and the autograd bigram. Afterwards you can trace one training step and explain why the autograd bigram converges to the count bigram.
  47. Safetensors for every dtype, atomic checkpoints, and the token stream. Afterwards you can explain the safetensors layout for every dtype, why checkpoints are written atomically, and how the token stream is read.
  48. What the System Does After Pass 2. Afterwards you can explain how the course’s own autograd retrains the tracer bigram, checks its gradients, and resumes bitwise from a checkpoint.

The stages are also in this pass’s manifest, path.tsv. With a trusted autograd in hand, Pass 3 turns to what the models read: tokens and the corpus they come from.

Generated from path.tsv.

StageReadDone when
1Solve set: functions, exp/log, trig and Euler, series, polynomials, inequalities
6.5 Problem set: functions, logarithms, trigonometry, series, polynomials, and inequalities
You can work every S-M00 problem and explain each answer.
2Exponents, logs, change of base, units of information
6.1 Exponents, logarithms, and units of information
You can explain how logs convert between bases and units of information (bits, nats) (M00.1).
3Trig, unit circle, 2D rotations, complex numbers, Euler’s formula
6.2 Trigonometry, rotations, complex numbers, and Euler’s formula
You can explain how a 2D rotation is a multiplication by a unit complex number via Euler’s formula (M00.2).
4Sequences, geometric series, frequency ladders
6.3 Sequences, geometric series, and frequency ladders
You can explain how a geometric series builds a frequency ladder and what its sum is (M00.3).
5Polynomials, Horner, stable quadratic roots
6.4 Polynomials, Horner’s rule, and stable quadratic roots
You can explain why Horner’s rule evaluates a polynomial in n multiplies and why the stable quadratic formula avoids cancellation (M00.4).
6Derivative as a limit, finite differences, step-size choice
7.1 Derivatives and Finite Differences
You can explain why the central difference is second-order accurate and how the step size balances truncation against rounding error (M01.1).
7Newton’s method
7.2 Newton’s Method
You can explain why Newton’s method converges quadratically near a simple root and when it fails (M01.2).
8Taylor series, remainder bounds, range reduction
8.1 Taylor series, remainder bounds, and range reduction
You can explain how range reduction keeps a Taylor series short and how the remainder bound sets the number of terms (M02.1).
9Activation functions and their derivatives
7.3 Activation Functions and Their Derivatives
You can derive each activation function’s derivative and explain how the solution keeps it numerically stable (M01.3).
10Calculus 1 problem set: limits, derivatives, rates, optimization, integrals, L’Hôpital
7.5 Calculus 1 Problem Set
You can work every S-M01 problem and explain each answer.
11Series convergence, EMA as a geometric series, bias correction
8.2 Series convergence, the EMA as a geometric series, and bias correction
You can explain why an EMA is a geometric series and why bias correction divides by 1 - beta^t (M02.2).
12Calculus 2 problem set: integration techniques, the Gaussian, series, Taylor, polar, ODEs
8.3 Calculus 2 problem set: integration techniques, the Gaussian, series, Taylor, polar, and ODEs
You can work every S-M02 problem and explain each answer.
13Partial derivatives, gradients, gradcheck
10.1 Partial derivatives, gradients, and gradcheck
You can explain how gradcheck compares an analytic gradient with central differences and how its tolerance is chosen (M04.1).
14Jacobians, multivariable chain rule, numeric JVP/VJP
10.2 Jacobians, the multivariable chain rule, and numeric JVP/VJP
You can explain how the multivariable chain rule composes Jacobians and how numeric JVPs and VJPs are computed (M04.2).
15Calculus 3 problem set: vectors, gradients, the chain rule, Hessians, multiple integrals, Lagrange
10.3 Calculus 3 problem set: vectors, gradients, the chain rule, Hessians, multiple integrals, Lagrange
You can work every S-M04 problem and explain each answer.
16Discrete math 1 problem set: sets, counting, proofs, induction, relations, bijections
11.3 Discrete math 1 problem set: sets, counting, proofs, induction, relations, bijections
You can work every S-M05 problem and explain each answer.
17Graphs, DAGs, and an iterative topological sort
12.1 Graphs, DAGs, and an iterative topological sort
You can explain how the iterative topological sort orders a DAG and how it detects a cycle (M06.1).
18Discrete math 2 problem set, part a: DAGs, modular arithmetic, hashing
12.4 Discrete math 2 problem set, part a: DAGs, modular arithmetic, hashing
You can work every S-M06a problem and explain each answer.
19Modular arithmetic, hashing, and PCG32 in Python
12.3 Modular arithmetic, hashing, and PCG32 in Python
You can explain how PCG32 advances its state with modular arithmetic and permutes its output, and how the hash is computed (M06.3).
20Gaussian elimination and LU with partial pivoting
9.2 Gaussian elimination and LU with partial pivoting
You can explain why LU needs partial pivoting and how it solves a linear system (M03.2).
21Random variables, expectation, variance, and normal draws by Box-Muller
13.1 Random variables, expectation, variance, and normal draws by Box-Muller
You can explain how Box-Muller turns two uniforms into normal draws and how expectation and variance are estimated (M07.0).
22Orthogonality, Householder QR, and orthogonal initialization
9.3 Orthogonality, Householder QR, and orthogonal initialization
You can explain how Householder reflections build QR and how that gives an orthogonal initialization (M03.3).
23Eigenvalues, power iteration, and the spectral radius
9.4 Eigenvalues, power iteration, and the spectral radius
You can explain why power iteration converges to the dominant eigenvector and what the spectral radius says about a recurrence (M03.4).
24Linear algebra problem set, part a: elimination, LU, bases, rank, determinants, eigenvalues, QR
9.7 Linear algebra problem set, part a: elimination, LU, bases, rank, determinants, eigenvalues, QR
You can work every S-M03a problem and explain each answer.
25Probability problem set, part a: axioms, Bayes, random variables, Box-Muller
13.9 Probability problem set, part a: axioms, Bayes, random variables, Box-Muller
You can work every S-M07a problem and explain each answer.
26IEEE 754 anatomy, ulp, round to nearest even, and bf16 and fp16 emulation
15.1 IEEE 754 anatomy, ulps, and round to nearest even
You can decode an IEEE 754 value by hand, measure its ulp, and explain how round to nearest even produces bf16 and fp16 (M09.1).
27Stable numerics: logsumexp, softmax, compensated sums
15.2 Stable numerics: logsumexp, softmax, and compensated sums
You can explain why logsumexp subtracts the max and how a compensated sum recovers lost low-order bits (M09.2).
28Floating point problem set, part a: representation, rounding, cancellation
15.8 Problem set A: representation, rounding, and cancellation
You can work every S-M09a problem and explain each answer.
29Entropy, cross-entropy, KL, JS, and the k3 estimator
17.1 Entropy, cross-entropy, KL, JS, and the k3 estimator
You can explain how entropy, cross-entropy, KL, and JS relate and why the k3 estimator is unbiased and non-negative (M11.1).
30Information theory problem set, part a: entropy, chain rules, KL and cross-entropy
17.4 Information theory problem set, part a: entropy, chain rules, KL and cross-entropy
You can work every S-M11a problem and explain each answer.
31Dual numbers and forward-mode autodiff
14.1 Dual numbers and forward-mode autodiff
You can explain how dual numbers carry a derivative through forward-mode autodiff (M08.1).
32Scalar reverse mode: the Value graph
14.2 Scalar reverse mode: the Value graph
You can trace how the Value graph is topologically sorted and how backward accumulates gradients in reverse (M08.2).
33Matrix differentials, the trace trick, and closed-form VJPs
14.3 Matrix differentials, the trace trick, and closed-form VJPs
You can derive closed-form VJPs with matrix differentials and the trace trick (M08.3).
34Matrix calculus problem set: differentials, trace trick, VJPs, SDPA Jacobian
14.5 Matrix calculus problem set: differentials, trace trick, VJPs, SDPA Jacobian
You can work every S-M08 problem and explain each answer.
35Convexity, smoothness, gradient descent, and Armijo line search
16.1 Convexity, smoothness, gradient descent, and Armijo line search
You can explain how smoothness bounds the gradient-descent step and how Armijo line search picks a step that decreases the loss (M10.1).
36The Optimizer protocol: SGD, momentum, Nesterov, weight decay
16.2 The Optimizer protocol: SGD, momentum, Nesterov, weight decay
You can explain how the Optimizer protocol implements SGD, momentum, Nesterov, and weight decay (M10.2).
37Adam and AdamW: bias correction and decoupled weight decay
16.3 Adam and AdamW: bias correction and decoupled weight decay
You can explain why Adam corrects its moment bias and why AdamW decouples weight decay from the gradient (M10.3).
38Learning-rate schedules (cosine, WSD, Noam) and gradient clipping
16.4 Learning-rate schedules (cosine, WSD, Noam) and gradient clipping
You can explain how cosine, WSD, and Noam schedules set the learning rate and how global-norm clipping rescales gradients (M10.4).
39Optimization problem set, part a: convexity, GD rates, momentum, Adam
16.5 Optimization problem set, part a: convexity, GD rates, momentum, Adam
You can work every S-M10a problem and explain each answer.
40Variance propagation and initialization
13.4 Variance propagation and initialization
You can derive how variance propagates through a layer and why that sets the initialization scale (M07.3).
41TDD, unit tests, and how your tests are graded
3.1 TDD, unit tests, and mutation testing
You can explain how test-first unit tests pin down behavior and what a mutation score says about a test suite (craft.03).
42Tensor, broadcasting backward, and no_grad
6.2 Tensor, broadcasting backward, and no_grad
You can explain how broadcasting backward sums gradients over broadcast axes and how no_grad stops graph building (L0.1).
43The op library and gradcheck_all
6.3 The op library and gradcheck_all
You can explain each op’s backward in the op library and how gradcheck_all verifies them (L0.2).
44Losses with a fused backward
6.4 Losses with a fused backward
You can derive the fused softmax cross-entropy backward and explain why fusing it is more stable (L0.3).
45Module system and basic layers
6.5 Module system and basic layers
You can explain how the module system registers parameters and how the basic layers are built on it (L0.4).
46Training loop and the autograd bigram
6.6 Training loop and the autograd bigram
You can trace one training step and explain why the autograd bigram converges to the count bigram (L0.5).
47Safetensors for every dtype, atomic checkpoints, and the token stream
6.7 Safetensors for every dtype, atomic checkpoints, and the token stream
You can explain the safetensors layout for every dtype, why checkpoints are written atomically, and how the token stream is read (L0.6).
48What the system does after Pass 2
B.4.1 What the System Does After Pass 2
You can explain how the course’s own autograd retrains the tracer bigram, checks its gradients, and resumes bitwise from a checkpoint.