CNSLT ACADEMY / INSIDE MODERN AI MODELS

How Neural Networks Learn: Loss, Gradient Descent and Backpropagation

FOUNDATIONSBEGINNERFREE TEXT LESSONVIDEO 🔒 PRO

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.

How Neural Networks Learn: Loss, Gradient Descent and Backpropagation

##

  1. 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:

  1. Forward pass: run a batch of inputs through the network to produce predictions.
  2. Loss calculation: score how wrong those predictions are as a single differentiable number.
  3. Backpropagation: trace backward from the loss using calculus to measure how each individual parameter pushed the error up or down.
  4. 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.

##

  1. 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):
LMSE=12(y^−y)2L_{\text{MSE}} = \frac{1}{2}(\hat{y} - y)^2
  • 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 pp to the true next token, the loss is:
LCE=−ln⁡(p)L_{\text{CE}} = -\ln(p)

Notice how sharply Cross-Entropy punishes confident mistakes, and how it connects directly to Perplexity (PPL=eLCE\text{PPL} = e^{L_{\text{CE}}})—the effective number of equally likely choices the model is hesitating between:

Probability assigned to true next token (pp)Cross-Entropy Loss (−ln⁡p-\ln p)Perplexity (eLe^L)Interpretation
0.900.10541.11Confident and accurate
0.500.69312.00Torn evenly between 2 choices
0.102.302610.00Spread across ~10 candidates
0.014.6052100.00Severely wrong—massive gradient signal

##

  1. 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 y=1.0y = 1.0 from collateral score x=2.0x = 2.0.

Initial parameters:

  • Layer 1: w1=0.5w_1 = 0.5, b1=0.1b_1 = 0.1
  • Layer 2: w2=0.3w_2 = 0.3, b2=0.05b_2 = 0.05
  • Learning rate: η=0.1\eta = 0.1

### 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.6200

Now compute Layer 2 gradients directly:

dL / dw2 = (dL / dy_hat) * h = -0.6200 * 1.1000 = -0.6820
dL / db2 = (dL / dy_hat) * 1 = -0.6200

Now propagate the error signal backward through $w_2$ to reach the hidden neuron hh, then through the ReLU gate (whose derivative is 1 when z1>0z_1 > 0 and 0 when z1≤0z_1 \le 0):

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.1860

Notice 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 (wnew=w−η⋅gradw_{\text{new}} = w - \eta \cdot \text{grad})

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.1186

Re-running the forward pass with these updated weights gives z1=1.1930z_1 = 1.1930, y^=0.5513\hat{y} = 0.5513, and new Loss = `0.1007`—nearly cutting the error in half in a single gradient step.

##

  1. 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 η\eta up from 0 during 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 1 across 80 layers shrinks early-layer gradients toward zero (vanishing gradients); multiplying derivatives greater than 1 causes numbers to hit NaN (exploding gradients). Modern Transformers fight these with gradient clipping, normalisation, and residual connections (Lesson 26).

##

  1. 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.

##

  1. 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/else rules.

##

  1. 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.

##

  1. 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):

  1. Compute one more complete forward pass and backward pass with η=0.1\eta = 0.1, verifying that the loss drops further below 0.1007.
  2. Next, suppose w1 started at -0.5 and b1 = -0.1 so that z1=−1.1z_1 = -1.1. Calculate ReLU(z1) and dh/dz1. Observe how dL/dw1 becomes exactly 0—you have just reproduced the dying ReLU failure mode by hand.
  3. Write a short risk note explaining how an attacker could exploit a weakly vetted fine-tuning dataset via this exact gradient loop.

##

  1. Knowledge check
  2. Why do LLMs train with Cross-Entropy Loss rather than MSE?
  3. What does a perplexity of 10.0 mean intuitively?
  4. Why does training require significantly more GPU VRAM than inference?
  5. What does AdamW track that plain SGD does not?
  6. Why can biased or poisoned data remain hidden inside model weights?

Answer key:

  1. Cross-Entropy measures distance on probability distributions over the vocabulary, heavily penalising confident wrong predictions and pairing cleanly with Softmax gradients.
  2. On average, the model is as uncertain about the next token as choosing uniformly among 10 candidates.
  3. Training must hold weights, gradients, optimiser momentum/variance states, and intermediate forward-pass activations needed for backpropagation.
  4. Per-parameter first moments (momentum), second moments (adaptive variance scaling), and decoupled weight decay.
  5. Gradient descent minimises statistical loss on supplied labels without semantic truth checks, encoding biased or poisoned correlations across distributed weights.

##

  1. 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.

##

  1. Further reading
LEARNER FEEDBACK

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.

COURSE PROGRESS0/29 complete
Not yet completed
CHECK YOUR UNDERSTANDING