How Neural Networks Learn: Loss, Gradient Descent and Backpropagation
By the end of this lesson, you should be able to explain why a forward pass alone does not constitute learning, distinguish Mean Squared Error from Cross-Entropy Loss and perplexity, perform a two-layer backpropagation step using the chain rule, explain why modern LLMs train with AdamW and learning-rate schedules, and link training mechanics to bias, overfitting, and data-poisoning risk.
##
- Intuition first: turning random weights into useful behaviour
In Module 02, you saw how a single neuron multiplies inputs by weights, adds a bias, and applies an activation function. That explains how a *trained* model produces an output. At initialisation, however, every weight in a neural network is simply a small random number.
Training is the mechanical feedback loop that turns random parameters into calibrated predictions:
- Forward pass: run a batch of inputs through the network to produce predictions.
- Loss calculation: score how wrong those predictions are as a single differentiable number.
- Backpropagation: trace backward from the loss using calculus to measure how each individual parameter pushed the error up or down.
- Optimiser update: nudge every parameter slightly in the direction that lowers the loss.
Imagine descending a rugged mountain range in thick fog. Altitude is your loss, the slope under your boots is the gradient, your stride length is the learning rate, and backpropagation is how a network of billions of weights coordinates which way each knob should turn.
##
- Loss functions: MSE vs. Cross-Entropy and Perplexity
Different tasks require different error scorecards:
- Mean Squared Error (MSE) is used for continuous numeric targets (such as forecasting latency or estimating risk scores):
- Cross-Entropy Loss (Negative Log-Likelihood) is the standard training loss for classification and Large Language Models. When an LLM predicts a probability distribution across its entire vocabulary and assigns probability to the true next token, the loss is:
Notice how sharply Cross-Entropy punishes confident mistakes, and how it connects directly to Perplexity ()—the effective number of equally likely choices the model is hesitating between:
| Probability assigned to true next token () | Cross-Entropy Loss () | Perplexity () | Interpretation |
|---|---|---|---|
0.90 | 0.1054 | 1.11 | Confident and accurate |
0.50 | 0.6931 | 2.00 | Torn evenly between 2 choices |
0.10 | 2.3026 | 10.00 | Spread across ~10 candidates |
0.01 | 4.6052 | 100.00 | Severely wrong—massive gradient signal |
##
- Worked example: a full 2-layer backpropagation step by hand
A single-neuron example hides why backpropagation actually matters. Let us trace a two-layer network (one hidden ReLU neuron feeding one output neuron) predicting a credit-approval target from collateral score .
Initial parameters:
- Layer 1: ,
- Layer 2: ,
- Learning rate:
### Step A: Forward pass
Layer 1 pre-activation: z1 = (w1 * x) + b1 = (0.5 * 2.0) + 0.1 = 1.1000
Layer 1 activation: h = ReLU(z1) = max(0, 1.1000) = 1.1000
Layer 2 prediction: y_hat = (w2 * h) + b2 = (0.3 * 1.1) + 0.05 = 0.3800
Squared error loss: L = 0.5 * (y_hat - y)^2
= 0.5 * (0.3800 - 1.0)^2 = 0.5 * (-0.6200)^2 = 0.1922### Step B: Backward pass (chain rule from output to Layer 1) First, how sensitive is the loss to the output prediction?
dL / dy_hat = (y_hat - y) = 0.3800 - 1.0 = -0.6200Now compute Layer 2 gradients directly:
dL / dw2 = (dL / dy_hat) * h = -0.6200 * 1.1000 = -0.6820
dL / db2 = (dL / dy_hat) * 1 = -0.6200Now propagate the error signal backward through $w_2$ to reach the hidden neuron , then through the ReLU gate (whose derivative is 1 when and 0 when ):
dL / dh = (dL / dy_hat) * w2 = -0.6200 * 0.3 = -0.1860
dh / dz1 = 1.0 (since z1 = 1.1000 >
0)
dL / dz1 = dL / dh * dh / dz1 = -0.1860
dL / dw1 = (dL / dz1) * x = -0.1860 * 2.0 = -0.3720
dL / db1 = (dL / dz1) * 1 = -0.1860Notice the elegance: intermediate values saved during the forward pass ($h$ and $z_1$) are reused during the backward pass. That is also why *training* consumes far more GPU memory than *inference*—the GPU must store activations from every layer until the backward pass finishes.
### Step C: Gradient descent update ()
w2_new = 0.3000 - (0.1 * -0.6820) = 0.3682
b2_new = 0.0500 - (0.1 * -0.6200) = 0.1120
w1_new = 0.5000 - (0.1 * -0.3720) = 0.5372
b1_new = 0.1000 - (0.1 * -0.1860) = 0.1186Re-running the forward pass with these updated weights gives , , and new Loss = `0.1007`—nearly cutting the error in half in a single gradient step.
##
- Batches, epochs, AdamW and training stability
Scaling this loop to billions of parameters requires careful engineering:
- Mini-batches and Gradient Accumulation: Updating weights after every single example is noisy and under-utilises GPUs; averaging gradients across the entire internet before one step is impossibly slow. Training therefore averages gradients over a mini-batch (for LLMs, often millions of tokens per optimiser step via gradient accumulation across GPUs).
- Epochs: One complete pass through the training dataset. While small classifiers train for 20–100 epochs, massive LLMs often train for only 1 to 4 epochs across trillions of tokens to avoid memorising duplicates.
- Why AdamW beats plain SGD: Different parameters sit on wildly different slope curvatures. AdamW maintains two running estimates per weight—a first moment (momentum, smoothing direction) and a second moment (adaptive variance, scaling step sizes down on steep coordinates and up on flat ones)—plus decoupled weight decay, which gently shrinks large weights to improve generalisation.
- Learning-Rate Schedules (Warmup + Cosine Decay): Starting with a high learning rate while weights are still random causes gradient explosions. Standard LLM training linearly ramps up from
0during warmup, then smoothly lowers it along a cosine curve so the model can settle into narrow, high-quality minima. - Vanishing, Exploding and Dead Gradients: Multiplying many derivatives less than
1across 80 layers shrinks early-layer gradients toward zero (vanishing gradients); multiplying derivatives greater than1causes numbers to hitNaN(exploding gradients). Modern Transformers fight these with gradient clipping, normalisation, and residual connections (Lesson 26).
##
- Generalisation vs. overfitting
A training loss approaching zero is not automatically good news. If a model memorises quirks and noise in the training set, training loss drops while validation loss rises—classic overfitting. Practitioners monitor held-out validation splits, apply weight decay, deduplicate training corpora, and stop or adjust when generalisation stalls.
##
- AI GRC and security implications
Understanding the learning loop reveals why governance cannot be bolted on purely as a final policy PDF:
- Encoded historical bias: Gradient descent optimises whatever objective and label distribution you supply. Biased historical underwriting, hiring, or triage labels become mathematically optimal directions in weight space.
- Data and model poisoning (OWASP LLM04): If an attacker injects even a tiny fraction of poisoned pairs (for example, a rare trigger phrase paired with an unsafe approval) into pre-training or fine-tuning corpora, backpropagation faithfully learns that shortcut.
- Training-data memorisation and privacy leakage: Duplicate or outlier sensitive records exert disproportionately strong gradient pulls, increasing the risk that a model reproduces private text verbatim at inference time.
- Auditability gap: Because knowledge is distributed across millions or billions of continuously adjusted weights, regulators and internal auditors must govern dataset provenance, deduplication, objective functions, training logs, and held-out evaluation evidence rather than expecting human-readable
if/elserules.
##
- Common misconceptions
- “A neuron’s forward pass is how the model learns.” No—the forward pass only generates a guess. Learning happens only when loss, backpropagation, and weight updates run.
- “Lower training loss always means a better production model.” False. Beyond a point, lower training loss signals memorisation and overfitting.
- “Training and inference have the same GPU memory footprint.” False. Training must store weights, gradients, AdamW optimiser states (first + second moments), and layer activations—often 4× to 12× more VRAM than inference.
- “Backpropagation checks whether data is factually true.” False. It only checks whether predictions match the training targets provided.
##
- Practical exercise
Using our worked two-layer example (x = 2.0, y = 1.0, updated parameters w1 = 0.5372, b1 = 0.1186, w2 = 0.3682, b2 = 0.1120):
- Compute one more complete forward pass and backward pass with , verifying that the loss drops further below
0.1007. - Next, suppose
w1started at-0.5andb1 = -0.1so that . CalculateReLU(z1)anddh/dz1. Observe howdL/dw1becomes exactly0—you have just reproduced the dying ReLU failure mode by hand. - Write a short risk note explaining how an attacker could exploit a weakly vetted fine-tuning dataset via this exact gradient loop.
##
- Knowledge check
- Why do LLMs train with Cross-Entropy Loss rather than MSE?
- What does a perplexity of
10.0mean intuitively? - Why does training require significantly more GPU VRAM than inference?
- What does AdamW track that plain SGD does not?
- Why can biased or poisoned data remain hidden inside model weights?
Answer key:
- Cross-Entropy measures distance on probability distributions over the vocabulary, heavily penalising confident wrong predictions and pairing cleanly with Softmax gradients.
- On average, the model is as uncertain about the next token as choosing uniformly among 10 candidates.
- Training must hold weights, gradients, optimiser momentum/variance states, and intermediate forward-pass activations needed for backpropagation.
- Per-parameter first moments (momentum), second moments (adaptive variance scaling), and decoupled weight decay.
- Gradient descent minimises statistical loss on supplied labels without semantic truth checks, encoding biased or poisoned correlations across distributed weights.
##
- Checklist
- [ ] Trace all four steps of the training loop on a multi-layer network.
- [ ] Explain Cross-Entropy Loss and convert a loss value into Perplexity.
- [ ] Distinguish mini-batch, epoch, learning rate, warmup, and AdamW weight decay.
- [ ] Track both training loss and held-out validation loss to detect overfitting.
- [ ] Document dataset provenance, deduplication, and poisoning controls before fine-tuning or training.
- [ ] Retain evaluation evidence alongside model checkpoints for governance review.
##
- Further reading
Help improve this learning path.
Suggest a concept we should teach, or tell us what is unclear. No account is required. Email is optional and only for a reply. Do not include confidential or sensitive information.