llm.guideChapter 3Neural Network Fundamentals

Neural Network Fundamentals

Neurons, loss, backprop, optimizers, learning rates and the plumbing that lets deep stacks train.

Part 2: Foundations. 11 sections, about 25 minutes.

loss 0.9loss 5.2loss 13startminimum
startminimum
  • Plain gradient descent
  • Momentum
  • Adam
Three optimizers on one loss surface, same start, 60 steps each. These are real runs, explained in section 3.5. The contours are levels of the loss; the valley is 18× steeper across than along.

Every knob you will touch at the product layer is one of the ideas in this chapter: the learning rate on a fine-tune, the reason LoRA fits on one GPU, the loss curve someone pastes into Slack, the “why can’t we just train longer?” question. Chapter 2 showed how a trained model runs. This chapter shows how its weights got there.

Every chart below comes from code that was actually run: small numpy models on the same tiny-Shakespeare text the Chapter 7 model uses. Section 3.10 has you build a working autograd engine in about 100 lines, and section 3.11 turns the whole chapter into a debugging table for real training runs.

3.1Neurons and layers

A neural network is a differentiable function with millions of knobs, and a layer is a matrix multiply plus a bend.

A neuron takes a weighted sum of its inputs, adds a bias, and passes the result through a nonlinear function φ (the activation): y = φ(w·x + b). Put several neurons side by side and you have a layer. Push a whole batch through a layer at once and it becomes a single matrix multiply: H = φ(XW + b), where X is batch × inputs and W is inputs × outputs. Stack layers and you have a multilayer perceptron (MLP). That is the whole family. A transformer (Chapter 5) is MLPs plus attention plus the plumbing in section 3.9.

x1w1x2w2x3w3Σ+ bφy
H = φ(XW + b)Xbatch × 3·W3 × 4+ bφHbatch × 4
Figure 3.1 Left: one neuron. Right: four neurons applied to a batch is one matrix multiply, which is why neural networks run on GPUs.

Three consequences you will use constantly:

  • Parameters are countable. A linear layer from din to dout has din·dout + dout parameters. Chapter 7’s transformer MLP (384 → 1,536 → 384) is about 1.18M parameters per block, which is where “the MLP is twice the attention” comes from.
  • Compute is countable. A forward pass costs about 2 FLOPs per parameter per token: one multiply and one add. Section 3.4 adds the backward pass and gives you Chapter 8’s training cost, 6 × parameters × tokens.
  • Universal approximation is an existence proof, not a recipe. One wide enough hidden layer can approximate any continuous function, but the theorem says nothing about whether gradient descent finds those weights or how much data it takes. Depth wins in practice because layers compose simple features into complex ones.

Common take“Neural networks are inspired by the brain.”

Sharper take“A layer is a matmul plus a nonlinearity, and a network is a differentiable function we fit by gradient descent. That’s why it runs on GPUs and why its cost is something I can calculate.”

3.2Activations

Without the bend, depth is an illusion, and the bend you choose decides whether gradients survive.

Two linear layers compose into one: W2(W1x) = (W2W1)x. Without a nonlinearity between them, a 100-layer network is a single matrix. The activation is what lets each layer build on the last. But backprop (section 3.4) multiplies by the activation’s slope at every layer, so the shape of that slope decides whether a learning signal can travel through a deep stack. Switch the chart to slopes and look at the flat tails.

−10123−4−2023outputinput xGELU dips just below 000.250.51−4−2023slope (what backprop multiplies by)input xsigmoid′ ceiling: 0.25
−10123−4−202outputinput xGELU dips below 000.250.51−4−202slopeinput xmax 0.25
  • sigmoid
  • tanh
  • ReLU
  • GELU
Figure 3.2 Where a slope is near zero, almost no gradient passes through. Sigmoid’s slope never exceeds 0.25, so ten sigmoid layers can shrink a signal by 0.2510, about one millionth.
ActivationWhere you’ll meet itIts gradient story
SigmoidGates inside LSTMs (Chapter 4), output probabilitiesSlope at most 0.25, near zero in the tails. Deep stacks of it vanish (section 3.8).
tanhRNNs, the lab in section 3.10Zero-centered, slope up to 1, but still saturates for large inputs.
ReLU, max(0, x)CNNs and most MLPs from 2012 to about 2018Slope exactly 1 when active, so no shrinkage. Slope 0 when inactive: a neuron pushed negative for every input is “dead” and never recovers.
GELUBERT, GPT-2, GPT-3A smooth ReLU. The small negative region keeps a trickle of gradient flowing.
SwiGLULlama and most current open modelsA gated MLP, SiLU(xW) ⊙ (xV): three weight matrices instead of two, so the hidden width shrinks to about 8⁄3 of the model width to keep the parameter count equal.

Common take“ReLU is the standard activation.”

Sharper take“I choose activations for gradient flow. Sigmoid’s 0.25 maximum slope is why deep sigmoid nets didn’t train, and gated units like SwiGLU are what modern LLM MLPs use.”

3.3Cross-entropy loss

Cross-entropy measures how surprised the model was by the right answer, and its value at step 0 is a free unit test.

The network outputs one score (logit) per vocabulary token. Softmax turns the scores into probabilities, and the loss for one example is −ln p(correct token), averaged over the batch. Minimizing it is the same as maximizing the probability the model assigns to the training data. Its gradient with respect to the logits is strikingly simple:

∂loss/∂logits = p − onehot(y)

The right answer gets pushed up by (1 − p), and every wrong answer gets pushed down by its own probability. The more confidently wrong the model is, the harder the push. That is why classifiers use cross-entropy rather than mean-squared error: with a softmax or sigmoid output, MSE’s gradient gets multiplied by the activation’s slope, which is near zero exactly when the model is confidently wrong.

0481210⁻⁶10⁻⁴0.011loss = −ln p (nats)probability given to the correct token (log scale)10× less likely+2.30 natsGPT-2 vocab, uniform guess: 10.8265-char model at step 0: 4.17
0481210⁻⁶10⁻³1loss = −ln p (nats)probability on the right token10× less likely+2.30GPT-2 vocab: 10.8265 chars: 4.17
Figure 3.3 Against log probability, cross-entropy is a straight line: every 10× less probability on the right token costs ln 10 ≈ 2.30 nats. Even a fairly confident p = 0.5 still costs 0.69.

Three numbers worth memorizing:

  • Step-0 loss is ln(vocab size). A freshly initialized model should be maximally unsure: uniform over V tokens gives loss ln V. For 65 characters that’s 4.17 (your Chapter 7 model), for GPT-2’s 50,257 tokens it’s 10.82, and for Llama 3’s 128,256 it’s 11.76.
  • Perplexity is eloss, the effective number of equally likely choices. A loss of 1.5 means a perplexity of about 4.5: the model is choosing among four or five characters.
  • Loss is not the metric. Cross-entropy is what you optimize; task success is what you ship. Chapter 23 lives in the gap between them.

The free unit test, run for real. I trained the same 15.7K-parameter character model twice, changing only the scale of the output layer’s initial weights:

04812160100200300400training losstraining stepln 65 = 4.17output weights 100× larger: starts at 15.7tiny output init: starts at 4.18
04812160200400training losstraining stepln 65 = 4.17output ×100: starts at 15.7tiny init: starts at 4.18
Figure 3.4 Real runs, plain SGD at learning rate 0.1. The well-initialized model starts at 4.18, matching ln 65. With output weights 100× larger it starts confidently wrong at 15.7 and spends its early steps unlearning overconfidence. This small model catches up by step 400; in a large run those steps are wasted compute, and the oversized early gradients can destabilize training.

Common take“The loss started high and came down, so training worked.”

Sharper take“Step-0 loss should be ln(vocab). If it isn’t, the wiring is wrong before training even starts. It’s the cheapest unit test in machine learning.”

3.4Backpropagation

The chain rule run backwards over the computation graph, which is why training costs about 3× a forward pass and must store every activation.

Every computation builds a graph of simple operations. The forward pass computes each node’s value and keeps the intermediate results. The backward pass starts at the loss with ∂L/∂L = 1 and walks the graph in reverse. At each node it multiplies the incoming gradient by that operation’s local derivative (the chain rule) and adds up contributions where paths merge. One backward pass yields the gradient for every parameter at once. That property, called reverse-mode automatic differentiation, is what makes training a billion-parameter model possible at all.

x = 2∂L/∂x = −18w = 3∂L/∂w = −12×z₁ = 6∂L/∂z₁ = −6b = 1∂L/∂b = −6+z = 7∂L/∂z = −6y = 10−e = −3∂L/∂e = 2e = −6( )²L = 9∂L/∂L = 1forward values−6gradients (backward)
Figure 3.5 A worked example you will reproduce in section 3.10’s lab: L = (w·x + b − y)². Read values top to bottom, then gradients bottom to top.

Walk it once by hand. Forward: 3 × 2 = 6, plus 1 is 7, minus 10 is −3, squared is 9. Backward: the square’s local derivative is 2e = −6. Addition and subtraction pass the gradient through unchanged, so ∂L/∂b = −6. Multiplication swaps in the other input: ∂L/∂w = −6 × x = −12 and ∂L/∂x = −6 × w = −18. Now take one gradient step with learning rate 0.01: w becomes 3.12, b becomes 1.06, the prediction rises from 7 to 7.30, and the loss falls from 9 to 7.29. That is training. Everything else is scale.

Two production consequences follow directly:

  • Compute. The backward pass computes gradients for both activations and weights, so it costs about twice the forward pass. A training step is about 3× a forward pass: 2 FLOPs forward plus 4 backward, 6 per parameter per token. That is the 6·N·D rule in Chapter 8’s cost math.
  • Memory. The backward pass needs the forward intermediates, so training stores activations for every layer and every token in the batch. Activation checkpointing trades compute for memory: discard most activations and recompute them during the backward pass, for roughly one extra forward pass.

Common take“PyTorch computes the gradients for you.”

Sharper take“Backprop is the chain rule with caching. Its compute bill is about twice the forward pass, and its memory bill is every activation, which is why training needs far more GPU memory than serving.”

3.5Optimizers

SGD, then momentum, then Adam and AdamW, and the 16-bytes-per-parameter bill that explains LoRA.

Gradient descent steps against the gradient: θ ← θ − η·g, where η is the learning rate. Stochastic gradient descent (SGD) estimates g from a minibatch: noisy, but cheap, and the noise helps it escape sharp regions. Momentum keeps a running velocity, v ← βv + g, and steps along it, like a heavy ball that smooths out zigzags and speeds up along consistent directions. Adam keeps two running averages for every parameter, the mean gradient m and the mean squared gradient v, and steps by m/√v. Each parameter gets its own effective step size, normalized to the scale of its own gradients. AdamW applies weight decay directly to the weights instead of folding it into the gradient, where Adam’s normalization would distort it. AdamW is the default for essentially every LLM.

The opening figure of this chapter is a real run of all three on a narrow valley, one direction 18× steeper than the other. Plain gradient descent at learning rate 0.1, just under the stability limit of 2⁄18 ≈ 0.11 (section 3.6), bounces between the valley walls. Momentum cuts across and is fastest early: loss 0.50 at step 10 against 1.50 for gradient descent. Adam heads diagonally, then jitters near the bottom, because a constant learning rate never shrinks its steps; after 60 steps its loss is 0.012 while gradient descent has reached 0.00004. The lesson is not that one optimizer always wins. Each failure has a recognizable shape. On real networks, with millions of parameters whose gradients differ in scale by orders of magnitude, Adam’s per-parameter scaling wins by default, and section 3.6’s decay schedules fix its end-of-run jitter.

LLM defaults worth knowing by heart: AdamW with β1 = 0.9, β2 = 0.95, weight decay 0.1, and gradient clipping at a global norm of 1.0.

Serving: weights only2 bytes per parameter: 14 GB for a 7B modelTraining with AdamW, mixed precisionweights2 Bgrads2 Bfp32 master4 BAdam m4 BAdam v4 B16 bytes per parameter: about 112 GB for a 7B model, before activations
Serving: weights only2 B per parameter: 14 GB for 7BTraining: AdamW, mixed precision2 B2 B4 B4 B4 Bbf16 weightsbf16 gradientsfp32 master copy of the weightsAdam m: running mean of gradientsAdam v: running mean of squared gradients16 B per parameter: about 112 GBfor a 7B model, before activations
Figure 3.6 Optimizer state is the hidden cost of training. Adam’s two running averages, kept in fp32 alongside an fp32 master copy of the weights, make training cost 8× the memory of serving, before counting activations.

That 8× gap is the whole motivation for parameter-efficient fine-tuning. LoRA trains 0.1–1% of the parameters, so optimizer state nearly disappears; QLoRA also shrinks the frozen weights to 4 bits. This is Chapter 17’s memory wall, and it’s the same arithmetic as the memory section in chapter 7 of Chip Huyen’s AI Engineering, seen here from the optimizer’s side.

On the frontier: Muon, an optimizer that orthogonalizes momentum updates for matrix-shaped weights, became the first serious challenger to AdamW at large scale in 2025. Know the name; default to AdamW.

Common take“We use Adam because it converges faster.”

Sharper take“Adam buys per-parameter step sizes with two extra fp32 states, so training costs 16 bytes per parameter against 2 for serving. That ratio is why parameter-efficient fine-tuning exists.”

3.6Learning rate

The hyperparameter that matters most. Warm it up, decay it down, clip what explodes.

Too high and each step overshoots the valley floor by more than it corrects, so the loss grows. On a quadratic you can say exactly when: divergence starts once the learning rate exceeds 2 divided by the curvature of the steepest direction. Too low and you crawl. Drag the slider past 0.111 and watch it happen.

Smooth but slow. No overshoot, but progress along the flat valley floor is gradual. Loss after 40 steps: 0.199 (started at 15.1).

Figure 3.7 Forty steps of gradient descent from the same start on the same valley as the opening figure. Below 1⁄18 ≈ 0.056 the path is smooth; between 0.056 and 0.111 it zigzags but converges; above 0.111 it diverges.

The same story on a real model. Here is the 15.7K-parameter character model trained with plain SGD at four learning rates for 3,000 steps each:

234501k2k3ktraining loss (smoothed)training stepuniform guessing: 4.17lr 8.0: diverges, ends at 18.6lr 0.01: crawls (val 2.69)lr 1.0: fast start, val 2.28lr 0.1: val 2.19
234501k2k3ktraining loss (smoothed)training stepuniform guess: 4.17lr 8.0: diverged (18.6)lr 0.01lr 1.0lr 0.1
  • lr 0.01
  • lr 0.1
  • lr 1.0
  • lr 8.0
Figure 3.8 Real runs. 0.01 crawls. 0.1 is the sweet spot. 1.0 is fastest for the first few hundred steps, then finishes noisier and worse on validation. 8.0 diverges within 25 steps and ends far worse than random guessing.

Real training runs don’t hold the learning rate constant. They follow a schedule:

02e-44e-46e-4025k50k75k100klearning ratetraining stepwarmup: 2k stepscosine decay to 10% of peakWSD: hold, then decay
02e-44e-46e-4050k100klearning ratetraining stepwarmup 2kcosine to 10%WSD
Figure 3.9 Two common schedules over 100k steps with a 6×10⁻⁴ peak: GPT-style cosine decay, and warmup–stable–decay (WSD).
  • Warmup. Ramp from near zero to the peak over the first few thousand steps. At step 0, Adam’s squared-gradient average is built from a handful of noisy batches and the activations aren’t calibrated yet, so full-size steps can wreck the network. Post-norm transformers (section 3.9) were especially fragile without it.
  • Decay. Cosine decay to about 10% of the peak was the GPT-era default. WSD holds the peak and decays only at the end, so you can branch a run or extend training without restarting the schedule. Recent training recipes increasingly use it.
  • Clipping. Rescale the gradient whenever its global norm exceeds a threshold, usually 1.0. It is cheap insurance against one bad batch.
  • Batch size. Larger batches give less noisy gradients and tolerate larger learning rates, with diminishing returns past a “critical batch size.”

Numbers that come up: pretraining peak learning rates sit around 10⁻⁴ to 10⁻³ and shrink as models grow. Full fine-tuning typically uses 1–2×10⁻⁵, and LoRA typically 1–2×10⁻⁴, because only the small adapters move. Loss spikes, sudden jumps in long runs, usually trace to a bad batch or an optimizer-state blowup. The standard response is to roll back to the last checkpoint, skip the offending data, and lower the learning rate or tighten clipping.

Common take“I used the default learning rate.”

Sharper take“When a run misbehaves, the learning rate is my first suspect and my first experiment: warmup, decay, and clipping at norm 1 are the defaults I check before anything else.”

3.7Generalization

Overfitting is memorizing the training set. LLM pretraining almost never does it; your fine-tune will by epoch three.

What matters is loss on data the model hasn’t seen. Hold out a validation set and watch both curves. Training loss can almost always go down, since a big enough model can memorize anything. Validation loss tells you whether it’s learning patterns or memorizing examples. Here is that failure, run for real: the character model widened to 45K parameters and trained on just 3,000 characters of Shakespeare, so it has 15 parameters per training example.

02461101001000losstraining step (log scale)random guessing: 4.176.13.70.6best checkpoint: step 30
02461101001000lossstep (log scale)random guess: 4.176.13.70.6best: step 30
  • training, no regularization
  • validation, no regularization
  • training, weight decay + dropout
  • validation, weight decay + dropout
Figure 3.10 Real runs with AdamW. Training loss falls to about 0.6: the model can nearly recite its 3,000 characters. Validation loss bottoms out within the first 60 steps, then climbs to 6.1, far worse than random guessing. Weight decay (0.05) plus dropout (0.3) slows the damage to 3.7 but doesn’t cure it. The cure is more data per parameter.

The regularizers, ordered by how much modern LLM work relies on them:

  • More data is the real fix. Pretraining sees most tokens about once, so the data itself does the regularizing and classic overfitting is rare. Memorization still happens on text that appears many times, which is why deduplication matters (Chapters 8 and 25).
  • Weight decay pulls weights toward zero every step. 0.1 is standard in LLM recipes.
  • Early stopping means keeping the checkpoint with the best validation score. It’s standard for fine-tunes.
  • Dropout randomly zeroes activations during training so no single path can be relied on. GPT-2 used 0.1; most modern pretraining sets it to 0 because single-pass data makes it unnecessary. It still helps on small fine-tuning sets.

Fine-tuning flips the regime. Two thousand examples for three epochs on a 7B model is figure 3.10 at scale, so watch validation, stop early, and remember that LoRA’s small trainable parameter count is itself a regularizer. One more idea worth knowing: double descent. Past the point where a model can fit its training data exactly, making it even larger can improve validation loss again. It helps explain why “bigger works,” but don’t lead with it.

Common take“The fine-tuned model gets 99% on the training data.”

Sharper take“What does the validation curve look like, and is the eval set deduplicated against the training set?”

3.8Initialization

Vanishing and exploding gradients. Initialization is variance bookkeeping.

Backprop multiplies one local factor per layer on its way down. Multiply 20 numbers slightly below 1 and the product vanishes; slightly above 1 and it explodes. Each layer’s factor depends on the scale of its weights and the slope of its activation, so the fix is to choose the initial weight scale that keeps the signal’s variance roughly constant from layer to layer. Xavier (Glorot) initialization uses a variance of about 1/fan-in for tanh and sigmoid. He (Kaiming) initialization uses 2/fan-in for ReLU; the 2 compensates for ReLU zeroing half its inputs.

10⁻¹⁴10⁻¹⁰10⁻⁶0.0110015101520gradient signal reaching the layerlayer (20 is next to the loss)ReLU, weights 25% too large: grows ~60×sigmoid + Xavier init: vanishesHe init and residual + LayerNorm: flatbackprop travels this way
10⁻¹⁴10⁻⁹10⁻⁴1011020gradient signal reaching the layerlayer (20 is next to the loss)grows ~60×vanishesflatbackprop
  • sigmoid, Xavier init
  • ReLU, weights 25% too large
  • ReLU, He init
  • pre-norm residual + LayerNorm
Figure 3.11 Real measurement in 20-layer, 256-wide networks at initialization: the size of the gradient signal arriving at each layer. With sigmoid, layer 1 receives about 10⁻¹² of what layer 20 receives, so early layers cannot learn. ReLU with weights at standard deviation 0.11 instead of He’s 0.088 grows about 60× on the way down. He initialization stays flat, and so does the residual design from section 3.9, at any depth.

Two LLM-specific details. GPT-2 scales the initial weights of each residual block’s output projection by 1/√(2 × layers), so the residual stream’s variance doesn’t grow with depth; the pre-norm curve in figure 3.11 uses the same trick. And every serious training run logs the global gradient norm: a steady climb is an early warning before a loss spike or NaN.

Common take“I initialized the weights randomly.”

Sharper take“Initialization is variance bookkeeping. Keep each layer’s output variance close to its input variance and the gradient survives the trip in both directions.”

3.9Normalization and residuals

Normalization and residual connections, the plumbing in every transformer block.

Normalization rescales activations to zero mean and unit variance, followed by a learnable gain and shift, so every layer sees inputs on a stable scale no matter what the previous layers are doing. The difference between the variants is which numbers get averaged together:

BatchNorm

featuresbatchone feature, across the batch

LayerNorm and RMSNorm

featurestokensone token, across its features
Figure 3.12 Highlighted cells share one mean and variance. BatchNorm averages a feature across the batch; LayerNorm averages one token’s features.
  • BatchNorm (2015, built for CNNs) depends on what else is in the batch, needs running averages at inference time (so training and serving behave differently), and mixes information across sequences. All three are bad fits for language models.
  • LayerNorm normalizes each token on its own. It is independent of batch size and sequence length, and identical in training and serving. Transformers use it.
  • RMSNorm is LayerNorm without the mean subtraction: divide by the root-mean-square and apply a gain. It does less work with the same stability, and Llama and most current LLMs use it.

Residual connections change h = F(x) to h = x + F(x). The identity path has a slope of exactly 1, so every layer has a direct route to the loss however deep the stack: a gradient highway. In a transformer, think of a residual stream that runs straight through the model; each block reads from it through a norm and writes back into it by addition.

residual stream xto the next blockNormAttention+x + Attention(Norm(x))NormMLP+x + MLP(Norm(x))identity path:slope 1
Figure 3.13 The pre-norm block you will take apart in Chapter 5. The stream itself is never normalized or transformed; blocks only add to it.

Pre-norm versus post-norm. The original 2017 Transformer normalized after each addition (post-norm), which put the norm on the residual path and made deep models hard to train without careful warmup. From GPT-2 on, models normalize inside the branch, before attention or the MLP (pre-norm), leaving the residual path clean. It is markedly more stable at depth, and it ties section 3.6’s warmup story to section 3.8’s variance story.

Common take“Transformers use layer norm and skip connections.”

Sharper take“Residuals give gradients a highway and norms keep every layer’s inputs on the same scale. Together, they’re why 100-layer transformers train at all.”

3.10Lab: an autograd engine

Build an autograd engine in about 100 lines, the whole chapter in code you can run.

This is what PyTorch’s autograd does, for scalars, in plain Python with no dependencies. Each Value remembers which values produced it and how to send gradients back to them (section 3.4). backward() sorts the graph so every node comes after its inputs, then applies the chain rule in reverse. On top sit a neuron, a layer and an MLP (section 3.1), trained with plain gradient descent (section 3.5). Save it as tinygrad_lab.py and run it.

import math, random

class Value:
    """A scalar that remembers how it was made, so it can send gradients back."""
    def __init__(self, data, parents=(), op=''):
        self.data = data
        self.grad = 0.0
        self._parents = parents
        self._op = op
        self._backward = lambda: None   # set by the op that created this node

    def __add__(self, other):
        other = other if isinstance(other, Value) else Value(other)
        out = Value(self.data + other.data, (self, other), '+')
        def _backward():                 # d(a+b)/da = 1, d(a+b)/db = 1
            self.grad += out.grad
            other.grad += out.grad
        out._backward = _backward
        return out

    def __mul__(self, other):
        other = other if isinstance(other, Value) else Value(other)
        out = Value(self.data * other.data, (self, other), '*')
        def _backward():                 # d(a*b)/da = b, d(a*b)/db = a
            self.grad += other.data * out.grad
            other.grad += self.data * out.grad
        out._backward = _backward
        return out

    def __pow__(self, k):                # k is a plain number
        out = Value(self.data ** k, (self,), f'**{k}')
        def _backward():
            self.grad += k * self.data ** (k - 1) * out.grad
        out._backward = _backward
        return out

    def tanh(self):
        t = math.tanh(self.data)
        out = Value(t, (self,), 'tanh')
        def _backward():                 # d tanh(x)/dx = 1 - tanh(x)^2
            self.grad += (1 - t * t) * out.grad
        out._backward = _backward
        return out

    def backward(self):
        order, seen = [], set()
        def visit(v):                    # topological sort: parents before children
            if v not in seen:
                seen.add(v)
                for p in v._parents:
                    visit(p)
                order.append(v)
        visit(self)
        self.grad = 1.0                  # dL/dL = 1
        for v in reversed(order):        # walk the graph backwards, applying the chain rule
            v._backward()

    # conveniences so expressions read naturally
    def __neg__(self): return self * -1
    def __sub__(self, other): return self + (-other)
    def __radd__(self, other): return self + other
    def __rmul__(self, other): return self * other


class Neuron:
    def __init__(self, n_in):
        self.w = [Value(random.uniform(-1, 1)) for _ in range(n_in)]
        self.b = Value(0.0)
    def __call__(self, x):
        return sum((wi * xi for wi, xi in zip(self.w, x)), self.b).tanh()
    def params(self):
        return self.w + [self.b]

class Layer:
    def __init__(self, n_in, n_out):
        self.neurons = [Neuron(n_in) for _ in range(n_out)]
    def __call__(self, x):
        out = [n(x) for n in self.neurons]
        return out[0] if len(out) == 1 else out
    def params(self):
        return [p for n in self.neurons for p in n.params()]

class MLP:
    def __init__(self, n_in, sizes):
        dims = [n_in] + sizes
        self.layers = [Layer(dims[i], dims[i + 1]) for i in range(len(sizes))]
    def __call__(self, x):
        for layer in self.layers:
            x = layer(x)
        return x
    def params(self):
        return [p for layer in self.layers for p in layer.params()]


if __name__ == '__main__':
    # 1) the worked example from section 3.4: L = (w*x + b - y)^2
    x, w, b, y = Value(2.0), Value(3.0), Value(1.0), Value(10.0)
    L = (w * x + b - y) ** 2
    L.backward()
    print('worked example: L =', L.data, '| dL/dw =', w.grad, '| dL/db =', b.grad, '| dL/dx =', x.grad)

    # 2) train a tiny MLP on four points
    random.seed(42)
    net = MLP(3, [4, 4, 1])
    xs = [[2.0, 3.0, -1.0], [3.0, -1.0, 0.5], [0.5, 1.0, 1.0], [1.0, 1.0, -1.0]]
    ys = [1.0, -1.0, -1.0, 1.0]
    print('parameters:', len(net.params()))
    for step in range(60):
        preds = [net(xi) for xi in xs]
        loss = sum((p - t) ** 2 for p, t in zip(preds, ys))
        for p in net.params():
            p.grad = 0.0                 # forget this line and gradients pile up across steps
        loss.backward()
        for p in net.params():
            p.data -= 0.05 * p.grad      # plain gradient descent
        if step % 10 == 0 or step == 59:
            print(f'step {step:2d}  loss {loss.data:.4f}')
    print('predictions:', [round(net(xi).data, 3) for xi in xs])

    # 3) gradient check: compare backprop with a finite difference for one weight
    p = net.params()[0]
    def total_loss():
        return sum((net(xi) - t) ** 2 for xi, t in zip(xs, ys))
    for q in net.params():
        q.grad = 0.0
    lo = total_loss(); lo.backward(); analytic = p.grad
    h = 1e-5; p.data += h; up = total_loss().data; p.data -= 2 * h; down = total_loss().data; p.data += h
    print(f'gradient check: backprop {analytic:.6f} vs finite difference {(up - down) / (2 * h):.6f}')

The output, from an actual run:

worked example: L = 9.0 | dL/dw = -12.0 | dL/db = -6.0 | dL/dx = -18.0 parameters: 41 step 0 loss 5.2788 step 10 loss 0.3966 step 20 loss 0.1106 step 30 loss 0.0577 step 40 loss 0.0377 step 50 loss 0.0274 step 59 loss 0.0219 predictions: [0.952, -0.913, -0.937, 0.913] gradient check: backprop 0.001230 vs finite difference 0.001230

The first line reproduces figure 3.5 exactly. The training run takes 41 parameters from a loss of 5.28 to 0.022 in 60 steps, and the final check confirms that backprop agrees with a finite-difference estimate to six decimal places. Then make it yours:

  1. Add relu() and exp() with their local derivatives, and retrain with ReLU hidden layers.
  2. Extend the gradient check to every parameter. This is how you would test a new operation in a real framework.
  3. Delete the line p.grad = 0.0 and rerun. On this toy, loss falls even faster (0.0001 by step 20), because gradients accumulating across steps act like momentum with no friction. That is exactly how this bug survives code review; on a real model it oscillates or diverges.
  4. Replace plain gradient descent with momentum, then with Adam, keeping m and v on each Value.
  5. Rebuild the worked example in PyTorch and confirm that w.grad is −12.

3.11Reading a training run

Reading a training run, from symptom to mechanism to fix.

This is the chapter compressed into one working skill: someone shows you a loss curve and you say what is going on. Each row points back to the mechanism that explains it.

Healthykeep goingstepsDiverges to NaNlower the rate; clip at 1.0NaNstepsSpike, partial recoveryroll back; skip that batchstepsOverfittingmore data; stop earlystepsPlateau, highsweep the learning ratestepsStuck at ln(vocab)check gradients are nonzerosteps
Healthykeep goingstepsDiverges to NaNlower the rate; clip at 1.0NaNstepsSpike, partial recoveryroll back; skip that batchstepsOverfittingmore data; stop earlystepsPlateau, highsweep the learning ratestepsStuck at ln(vocab)check gradients are nonzerosteps
  • training loss
  • validation loss
Figure 3.14 Illustrative shapes, not real runs: six curves worth recognizing on sight, each with the first thing to try. The table below gives the mechanism behind each.
What you seeMost likely mechanismFirst thing to tryPoint
Step-0 loss far above ln(vocab)Overconfident output initializationTiny or zero init for the last layer3, 8
Loss stuck at ln(vocab)Nothing is learning: zero learning rate, detached graph, frozen parameters, label bugCheck that every layer’s gradient is nonzero3, 4
Loss goes NaN after a few hundred steps, gradient norm rising beforehandExploding gradients or learning rate too highLower the learning rate, clip at norm 1.0, check init and norms6, 8
Sudden loss spike, then partial recoveryA bad batch or an optimizer-state blowupRoll back to a checkpoint, skip that data, lower the learning rate6
Training loss falls while validation loss risesOverfittingMore data, early stopping, weight decay7
Loss plateaus high and falls very slowlyLearning rate too low, or vanishing gradientsRun a learning-rate sweep; log per-layer gradient norms6, 8
Many ReLU units output zero for every inputDead neurons after a high-learning-rate startLower the learning rate, add warmup, or switch to GELU or SiLU2, 6
Out of memory in training but fine in servingActivations plus optimizer state, 16 bytes per parameterGradient accumulation, activation checkpointing, LoRA4, 5
A fine-tune forgets general skillsLearning rate too high or too many epochs10× lower learning rate, fewer epochs, LoRA, mix in general data6, 7
Validation loss improves but task quality doesn’tLoss is not the metricTask-level evals (Chapter 23)3

Common take“The loss is going down.”

Sharper take“I read a loss curve the way I read a latency graph. The step-0 value, the slope, the noise, and the gap between training and validation each tell me something different.”

Key takeaways

  • A layer is a matmul plus a nonlinearity. Without the nonlinearity, a hundred layers collapse into one matrix.
  • Step-0 loss should be ln(vocab): 4.17 for 65 characters, 10.8 for GPT-2’s vocabulary. It’s the cheapest unit test in ML.
  • Cross-entropy’s gradient is just p minus the one-hot target, so confidently wrong predictions get the biggest push. MSE can’t promise that.
  • Backprop is the chain rule with caching: about twice the forward pass in compute, and every activation held in memory.
  • Training with AdamW costs about 16 bytes per parameter against 2 to serve. That 8× gap is why LoRA exists.
  • When a run misbehaves, the learning rate is my first suspect: warm it up, decay it down, clip the gradient norm at 1.
  • Pretraining rarely overfits because it sees each token about once. Fine-tunes overfit fast because they see a few thousand examples many times.
  • Residual connections give gradients a highway and normalization keeps scales stable. Together they’re why 100-layer transformers train.

Check your understanding

  1. A teammate’s from-scratch character model (vocabulary of 96) logs a step-0 loss of 23.4. By step 500 it reaches 3.1 and from then on tracks a colleague’s run that started at 4.6. What does 23.4 tell you and what should it have been, what is the one-line fix, and why should you still care at 70B scale when the runs converge anyway?

    Answer outline

    ln 96 ≈ 4.56, so the colleague’s 4.6 is correct. 23.4 means the model starts confidently wrong: the output layer’s weights, or the logit scale, are far too large. The fix is to initialize the last layer near zero. At scale it still matters: the early hockey stick burns real GPU-hours, the oversized early gradients corrupt Adam’s running averages and can trigger spikes or dead units, and a wrong step-0 loss is often a symptom of other wiring bugs.

  2. You must fully fine-tune an 8B model with AdamW in bf16 mixed precision on 80 GB GPUs. Estimate the memory for weights, gradients and optimizer state before activations, the minimum number of GPUs that holds that state if it is sharded perfectly, and what switching to LoRA with about 0.5% of parameters trainable changes, and what it doesn’t.

    Answer outline

    8B × 16 bytes ≈ 128 GB, so at least two 80 GB GPUs just for state with perfect sharding (FSDP or ZeRO-3), and realistically more once activations are added. With LoRA the frozen base is about 16 GB in bf16, and the roughly 40M trainable parameters × 16 bytes ≈ 0.64 GB, so it fits on one GPU. What doesn’t change: activation memory still grows with batch × sequence length, and compute drops only modestly, because you still backpropagate through every layer to reach the adapters. QLoRA would shrink the base to about 4–5 GB.

  3. Two curves from the same fine-tuning job land in Slack. Training loss falls smoothly from 1.9 to 0.3 over four epochs; validation loss falls to 1.1 by the middle of epoch 1, then climbs to 1.6 by epoch 4. Separately, the gradient norm jumped from about 0.8 to 40 at step 1,900 and the training loss spiked, then recovered. Diagnose both events, say which checkpoint you would ship and why, and give one change for each problem before the next run.

    Answer outline

    The diverging curves are overfitting, with the validation minimum around mid-epoch 1, so ship that checkpoint (early stopping), not the last one. Next run: fewer epochs, more or deduplicated data, a lower learning rate, or LoRA. The spike is a gradient explosion from a bad batch or a learning rate near the edge: turn on or tighten clipping at norm 1.0, lengthen warmup or lower the peak, and inspect the batch at step 1,900 for corrupted or extreme examples.

Further reading

  • Chip Huyen, AI Engineering: chapter 2 for how foundation models are trained and sized, and the memory-bottleneck section of chapter 7 for backprop, numerical formats and memory math from the product side.
  • Understanding Deep Learning (Prince), free online: chapters 3–9 for networks, losses, fitting, gradients, initialization and regularization, and chapter 11 for residual networks.
  • Andrej Karpathy, “The spelled-out intro to neural networks and backpropagation: building micrograd”, then the makemore videos, which build the character models used for this chapter’s charts.

↑↓ to move↵ to openesc to close