Skip to content
AgenticAIWiki
  1. Learn
  2. Part 1
  3. 9. Machine learning basics for LLM builders
  4. 9.3

Lesson 9.3 · 3 of 5 · 7 min read · Reviewed 24 Nov 2026

Gradient descent and backpropagation

By the end, you can

  • Work one step of gradient descent on a single weight.
  • Explain what backpropagation computes and why it runs backwards.
  • Spot a learning rate that is too high from a loss curve.

A new network starts with random weights and gives useless answers. Training makes it better, one small nudge at a time. Two ideas do the work: gradient descent decides how to nudge, and backpropagation works out the nudge for every weight at once.

Step 1: measure how wrong you are

A loss function turns “how wrong” into one number. For predicting a value, a common choice is squared error: (prediction - target)^2. For predicting the next token, LLMsLarge language model (LLM): A neural network trained on large amounts of text to predict the next token, which lets it generate and transform language. use cross-entropy: minus the log of the probability the model gave the correct tokenToken: The unit a model reads and writes: a word, part of a word, a space or a symbol, mapped to an integer id.. Give the right token probability 0.9 and the loss is small (0.11). Give it 0.01 and the loss is large (5.6).

Step 2: find the downhill direction

Picture the loss as a landscape, with one direction for each weight. The gradient is the slope: for each weight it says how much the loss would rise if that weight grew a little. To go downhill, step the other way:

w_new = w - learning_rate * gradient

A worked example with one weight

Model: prediction = w * x. One training example: x = 2, target 6. Start at w = 1, learning rate 0.05.

Step w Prediction Loss (pred - 6)^2 Gradient 2(pred - 6)x
0 1.00 2.00 16.00 -16.0
1 1.80 3.60 5.76 -9.6
2 2.28 4.56 2.07 -5.8
3 2.57 5.14 0.75 -3.5

The gradient is negative, so w goes up, and the loss falls each step towards w = 3. Now try a learning rate of 0.3: the first step jumps w to 5.8, the prediction to 11.6 and the loss to 31.4. The next step overshoots the other way. The loss explodes. That is the classic sign of a learning rate that is too high.

Step 3: backpropagation

A real network has millions or billions of weights in many layers. Each weight affects the loss only through the layers after it. The chain rule says: the effect of a weight on the loss is its effect on the next value, times that value’s effect on the loss, and so on to the end.

Backpropagation uses this from the end backwards. It starts at the loss, computes the gradient for the last layer, then passes a gradient signal back one layer at a time, reusing the values saved during the forward pass. One backward sweep gives every gradient for about twice the cost of the forward pass. Frameworks such as PyTorch and JAX do this automatically (autograd), so you rarely write it by hand. Lesson 9.5 does it once by hand so you can see it.

In practice

  • Training uses mini-batches: the gradient is averaged over a batch of examples, not one, which is cheaper than the whole dataset and less noisy than a single example. That is stochastic gradient descent.
  • Optimisers such as Adam adapt the step size for each weight and are the usual default.
  • One full pass over the training data is an epoch.

Common mistakes

  • Reading only training loss. If training loss falls while loss on held-out data rises, the model is overfitting: memorising rather than learning.
  • Changing the learning rate and the batch size together, then not knowing which one helped.
  • ThinkingExtended thinking: A mode in which the model reasons step by step in thinking blocks before giving its final answer. backpropagation is a learning algorithm on its own. It only computes gradients. The optimiser decides the step.

Key points

  • A loss function scores how wrong the model is; training tries to make it smaller.
  • The gradient says which way each parameter should move to raise the loss, so gradient descent steps the opposite way, scaled by the learning rate.
  • Backpropagation applies the chain rule from the loss back through each layer, reusing values from the forward pass to get every gradient in one sweep.
  • Too high a learning rate makes the loss bounce or explode; too low makes training crawl.
Hands-on labRuns in the Playground

Fit one weight with gradient descent

Run gradient descent on one weight, check the gradient numerically and find the learning rate that breaks it.

You will have: A loss table for the lesson example and a comparison of four learning rates after 10 steps.

Steps

  1. Fill in grad: the derivative of (w x 2 - 6) squared with respect to w.
  2. Fill in the update so each step moves w against the gradient.
  3. Run it and check the first rows match the lesson table: loss 16.00, 5.76, 2.07.
  4. Compare learning rates 0.01, 0.05, 0.2 and 0.3, and note which one diverges.
  5. Confirm the analytic gradient matches the numeric one from nudging w.

Done when

  • Step 1 shows w = 1.80 and loss 5.76.
  • Learning rate 0.3 is reported as diverged; 0.05 converges.
  • Analytic and numeric gradients both print as -16.00.

Open in the Playground No API key needed.

Starter code (Python)
# Fit prediction = w * x to one example (x = 2, target 6) with gradient descent.
X, TARGET = 2.0, 6.0

def loss(w):
    return (w * X - TARGET) ** 2

def grad(w):
    # TODO: return the derivative of (w * X - TARGET) ** 2 with respect to w.
    return 0.0

def descend(w, lr, steps):
    history = [(w, loss(w))]
    for _ in range(steps):
        # TODO: step against the gradient: w = w - lr * grad(w)
        w = w
        history.append((w, loss(w)))
    return history

print("step   w      loss   (lr 0.05)")
for i, (w, l) in enumerate(descend(1.0, 0.05, 4)):
    print(f"{i:>4} {w:6.2f} {l:8.2f}")

for lr in (0.01, 0.05, 0.2, 0.3):
    final_w, final_loss = descend(1.0, lr, 10)[-1]
    verdict = "diverged" if final_loss > loss(1.0) else "converging"
    print(f"lr {lr}: loss after 10 steps {final_loss:.3f} ({verdict})")

# Check the gradient numerically: nudge w a little and see how the loss changes.
eps = 1e-5
numeric = (loss(1.0 + eps) - loss(1.0 - eps)) / (2 * eps)
print(f"analytic gradient {grad(1.0):.2f}, numeric {numeric:.2f}")
Show a solution
# Fit prediction = w * x to one example (x = 2, target 6) with gradient descent.
X, TARGET = 2.0, 6.0

def loss(w):
    return (w * X - TARGET) ** 2

def grad(w):
    return 2 * (w * X - TARGET) * X   # derivative of the loss with respect to w

def descend(w, lr, steps):
    history = [(w, loss(w))]
    for _ in range(steps):
        w = w - lr * grad(w)          # step against the gradient
        history.append((w, loss(w)))
    return history

print("step   w      loss   (lr 0.05)")
for i, (w, l) in enumerate(descend(1.0, 0.05, 4)):
    print(f"{i:>4} {w:6.2f} {l:8.2f}")

for lr in (0.01, 0.05, 0.2, 0.3):
    final_w, final_loss = descend(1.0, lr, 10)[-1]
    verdict = "diverged" if final_loss > loss(1.0) else "converging"
    print(f"lr {lr}: loss after 10 steps {final_loss:.3f} ({verdict})")

# Check the gradient numerically: nudge w a little and see how the loss changes.
eps = 1e-5
numeric = (loss(1.0 + eps) - loss(1.0 - eps)) / (2 * eps)
print(f"analytic gradient {grad(1.0):.2f}, numeric {numeric:.2f}")
Quick checkDuring training, the loss jumps around and then shoots up to huge values after a few hundred steps. What is the most likely cause?
How sure are you?
Pick an answer and how sure you are