← THE FOUNDATIONS / COURSE MAP
LESSON 04 / A COMPLETE LEARNING STEP

What actually changes when a model learns?

Follow one prediction, one loss, one derivative, and one parameter update—in plain numbers, NumPy, and PyTorch.

On this page Explore the sections +
Before you begin Prerequisites & learning goal +

Builds on: Lessons 1–3: numerical representations, weighted operations, and distributions.

Your goal: Separate inputs, parameters, activations, targets, loss, and gradients; predict the direction of one learning update.

Our first model has one parameter: a weight of 0.5. Given input 2, it multiplies by that weight and predicts 1. The desired target is 3. Learning will change the weight so that this example’s prediction moves closer to its target.

This tiny model has no attention, but the learning distinction is the same. A model computes outputs with its current parameters; a training procedure adjusts those parameters using an objective and data.

1. Separate six things that often get mixed together

NameIn this exampleRole
Input2The observed information supplied to the model.
ParameterWeight 0.5A stored value training is allowed to change.
ActivationPrediction 1A temporary value computed from the input and current parameter.
Target3The desired answer provided by the training task.
LossSquared error 4A scalar measure of prediction error.
Gradient−8The local rate at which loss changes as the weight changes.

The training target is not secretly changed to match the prediction. The model’s parameter is changed to improve the objective. In a language model, a next-token target can be constructed from the text itself; it still plays the role of a target during the update.

2. Make a prediction and measure its error

$$ \hat y=wx,\qquad L=(\hat y-y)^2. $$
READ THE EQUATION

Predict by multiplying the weight and input. Subtract the desired target, then square that error to obtain the loss.

TermWhat it is and doesWhat it controls
\(\hat y\)The prediction; the hat distinguishes it from the target.The output made by the current model.
\(w\), \(x\), \(wx\)Trainable weight, supplied input, and their product.w controls the input-to-output scaling; x specifies the example.
\(y\)The desired target.The reference used to judge the prediction.
\(\hat y-y\)Signed prediction error.Direction and size of the mismatch.
\((\cdot)^2\), \(L\)Squaring makes a nonnegative penalty; L names that loss.Larger absolute errors receive larger penalties; exact predictions have zero loss.

Check: With w=0.5 and x=2, the prediction is 1. With target 3, error is −2 and loss is 4. A prediction of 5 would also have loss 4: squaring removes the error’s sign.

The forward pass is this input-to-prediction-to-loss calculation. A larger model performs more operations, but it still produces intermediate values using its current parameters.

3. A derivative answers a local question

A derivative asks: if we change one quantity by a very small amount, how quickly does another quantity change? Here we want the loss’s rate of change with respect to the weight.

First, loss changes with error at a rate of twice the error. Second, error changes with the weight at a rate of x, because the prediction is w times x and the target stays fixed. The chain rule multiplies these local rates along the path.

$$ g=\frac{\partial L}{\partial w}=2(wx-y)x. $$
READ THE EQUATION

The loss slope with respect to the weight is twice the prediction error, multiplied by the input.

TermWhat it is and doesWhat it controls
\(g\)A short name for this parameter’s gradient.The update direction and local sensitivity.
\(\partial L/\partial w\)Read as “the rate of change of loss with respect to weight.” This is derivative notation, not a ratio of measured loss and weight values.How a small change in w affects L while other inputs are fixed.
\(2\), \(wx-y\)Twice the signed prediction error, from differentiating its square.Error magnitude and sign.
Final \(x\)The sensitivity of prediction to weight. The chain rule multiplies by it.How strongly this example’s input exposes the weight to the loss.
\(w,x,y\)Current weight, input, and target from the forward calculation.Which point and example the local slope describes.

Check: 2×(0.5×2−3)×2 = −8. Increasing the weight slightly lowers the loss here. If x were zero, changing w could not change this prediction, and this example’s weight gradient would be zero.

A gradient collects such derivatives for all parameters. Our one-parameter gradient is one number. A weight matrix has a gradient with a matching shape: one local sensitivity for each weight entry.

4. Turn that slope into an update

$$ w_{\text{new}}=w-\eta g. $$
READ THE EQUATION

Move the weight opposite the loss gradient, using a positive learning rate to choose the step size.

TermWhat it is and doesWhat it controls
\(w_{\text{new}}\), \(w\)Updated and current parameter values.What is stored for the next forward pass.
\(g\)The loss slope just calculated.Which direction increases loss locally.
\(\eta\)Positive learning rate, pronounced eta.The size of the change per unit gradient.
Minus sign, \(\eta g\)Subtract the scaled gradient to move downhill locally.Positive gradients decrease w; negative gradients increase it.

Check: With learning rate 0.1 and gradient −8, the new weight is 0.5−0.1×(−8)=1.3. Its prediction is 2.6 and its new loss is 0.16. A step size of 1 would instead give weight 8.5 and loss 196: a downhill direction does not make every step size safe.

FIG. B04 — Forward values measure the error; a gradient guides the parameter update. The input and target stay fixed.PREDICTMEASUREDIFFERENTIATEUPDATEw = 0.5, x = 2PREDICTION = 1TARGET = 3LOSS = (1−3)² = 42 × (1−3) × 2GRADIENT = −80.5 − 0.1 × (−8)NEW w = 1.3NEXT FORWARD PASS: PREDICTION 2.6, LOSS 0.16THE WEIGHT CHANGES. INPUT 2 AND TARGET 3 DO NOT.
FIG. B04 — Forward values measure the error; a gradient guides the parameter update. The input and target stay fixed.

5. Explicit arithmetic and automatic differentiation

PYTHON
NumPy / inspect the operations
def learn_step(weight: float, x: float, target: float, rate: float = 0.1) -> tuple[float, float, float]:
    """One squared-error gradient step for prediction = weight * x."""
    prediction = weight * x
    error = prediction - target
    loss = error ** 2
    gradient = 2.0 * error * x
    updated = weight - rate * gradient
    return updated, loss, gradient

Typed Python · Shapes are documented alongside the code. Open the full file for imports and dependencies, or step through a concrete example.

The NumPy-side example uses scalar arithmetic to make the derivative explicit. It returns the updated weight, loss before the update, and gradient. All three are floats; the return annotation tuple[float, float, float] makes their structure visible. The loss does not retroactively change when we compute a new weight.

PyTorch creates a trainable scalar with requires_grad=True. Operations build a computation graph, and loss.backward() applies derivative rules backward through that graph. The gradient is available in parameter.grad. This is automatic differentiation, not a finite-difference approximation and not an automatic parameter update.

An optimizer performs the update. The simple rule above is gradient descent; the later Transformer example uses Adam, which maintains additional state from gradients to adjust updates. The separation still holds: clear old gradients, compute a loss, run backward, then update parameters. See PyTorch’s autograd explanation for how the graph is recorded.

6. What this means for a neural network

A neural network composes parameterized operations. A linear projection mixes features; an activation such as ReLU changes how combinations behave by replacing negative values with zero. Without intervening nonlinear operations, a stack of affine feature projections can be collapsed into a single affine projection. Extra boxes alone do not automatically create a more expressive computation.

In attention, embedding rows and projection matrices are parameters. Token representations, Q/K/V arrays, and attention weights are activations recalculated for each input. The loss gradient can flow through the weighted mixture, softmax, matching scores, and projections to change the stored parameters that produced those activations.

This explains why “learned attention” does not mean storing one permanent attention map. Training learns the transformations used to construct a map for a particular input. A new input can produce a different map with the same stored parameters.

7. Learning on examples is not proof of generalization

Training repeatedly uses a dataset to improve its objective. Evaluation asks whether the resulting behavior also works on examples that did not supply those updates. A low training loss can coexist with poor held-out performance.

During inference, we normally keep parameters fixed and compute predictions. We may build temporary state such as a KV cache; that state is not automatically a weight update. Evaluation mode and disabling gradient recording are also separate controls: one selects module behavior, the other avoids building a gradient graph.

CHECK YOUR UNDERSTANDINGAfter loss.backward(), has the parameter necessarily changed? Which quantities would you inspect to prove an optimizer update happened?Think first. Open to check your reasoning.

No. Backward computes and accumulates gradients. Compare the parameter value before and after the optimizer step; inspecting the gradient alone does not prove an update occurred. Our scalar example stores the result explicitly in updated.

You now have the missing foundation

You can read tensor axes, project features, combine values, turn scores into weights, and explain what learning updates. Continue to Attention & Transformers . When a diagram introduces a new box, ask which of these operations it combines and what new problem it solves.

END OF LESSON 04