Two passes through the same network
Imagine a neural network predicting the price of a used laptop from its age and memory size. To learn, the network must first make a prediction and then work out how to improve that prediction.
The first process is forward propagation: input values pass through layers until the network produces an output. A loss function measures the difference between that output and the desired result.
The second process is backpropagation: starting from the loss, the network uses the chain rule to calculate how sensitive the loss is to each trainable weight and bias. These sensitivities are called gradients. An optimizer then uses the gradients to update the parameters. Backpropagation calculates gradients; it is not, by itself, the rule that changes the weights.
A useful distinction is that the forward pass answers “What does the current network predict?” while the backward pass answers “How would changing each parameter affect the loss?” This article builds from a small numerical example to the general equations, then connects the calculations to an implementation.
A neural network performs two closely related computations during training. Forward propagation computes an output from an input using the network’s current parameters. Backpropagation computes how a chosen loss changes with respect to those parameters, allowing an optimizer to update them.
These are different operations. A forward pass produces predictions; a backward pass produces gradients. Gradient descent or another optimizer uses those gradients to change weights and biases. Backpropagation by itself does not update parameters.
1. The training computation in context
A typical supervised neural-network training step follows this sequence:
- Obtain a batch of inputs and corresponding target values.
- Run a forward pass to compute predictions.
- Compute a loss that measures disagreement between predictions and targets.
- Run backpropagation to compute derivatives of the loss with respect to trainable parameters.
- Use an optimizer to update those parameters.
- Repeat across batches and training iterations.
During ordinary inference, a network generally needs only the forward pass. It does not need target labels, a loss calculation, or backpropagation to make a prediction.
2. Mathematical model of a forward pass
Consider a fully connected layer with input vector , weight matrix , bias vector , and activation function .
Its computation is:
Here, identifies the layer; is the input. The function generally acts elementwise for a conventional dense hidden layer.
If a layer contains output units and receives inputs, its parameter shapes are:
- .
- .
- .
The output of one layer becomes the input to the next. A network with parameterized layers composes these transformations to obtain its final prediction .
Why activation functions matter
With no nonlinear activation between dense layers, several affine transformations collapse into one affine transformation. Nonlinear activations, such as ReLU, allow a network to represent nonlinear input-output relationships.
A common hidden-layer activation is ReLU:
Its derivative is for and for . At , ReLU is not mathematically differentiable; software frameworks use a defined convention for the backward calculation.
Other activation functions, such as sigmoid and tanh, have different derivatives. The output layer’s activation must be chosen to suit the prediction task and loss function.
3. A complete forward-pass example
Consider a small network with one scalar input, one hidden ReLU neuron, and one linear output neuron. Let the input be and choose initial parameters:
The hidden neuron calculates:
The output neuron calculates:
Suppose the correct target is . For one example, use half the squared error as the loss:
The factor simplifies the derivative and does not change where this loss is minimized. Production regression systems may use mean squared error or another loss aggregated across a batch.
The forward pass is finished: it has produced the intermediate values , , prediction , and loss .
4. What backpropagation calculates
Backpropagation is an efficient application of the chain rule to compute gradients through a sequence of differentiable operations. Starting from the loss, it works backward through the network and reuses intermediate derivatives rather than independently differentiating the entire model for each parameter.
If a quantity depends on , and depends on , then:
For multiple intermediate computations, the chain rule multiplies local derivatives along relevant paths; contributions from multiple paths are added.
A gradient describes local sensitivity. For instance, a positive indicates that a sufficiently small increase in , with other variables fixed, locally increases the loss. The magnitude and sign guide optimization, but do not guarantee improvement for arbitrarily large updates.
Backward through the worked example
Start at the loss:
Because :
To propagate the gradient into the hidden neuron:
Since , the ReLU derivative at this point is :
Finally, using :
All four trainable parameter gradients have now been computed:
| Parameter | Current value | Gradient |
|---|---|---|
Notice the direction: the calculation begins at the loss and traces its dependence on the output parameters, hidden activation, and then earlier parameters.
5. How an optimizer uses the gradients
For standard gradient descent with learning rate , each parameter follows:
Choose . Substituting the gradients above gives:
A second forward pass with the new parameters gives:
The loss decreased from to for this particular example and update. Gradient descent does not guarantee that every step decreases the loss, especially with a large learning rate or stochastic batches.
6. Backpropagation in a multilayer network
For compact notation, define a layer’s error signal as the gradient of the loss with respect to its pre-activation:
For a standard dense layer with elementwise activation, the backward recursion for a hidden layer is:
where denotes elementwise multiplication. At the output layer, is found by differentiating the chosen loss and output activation, with simplifications possible for some common combinations.
The parameter gradients for each dense layer then follow:
These equations describe a single example and assume the shapes and operations given earlier. For a batch, implementations aggregate or average contributions according to the defined loss reduction. Convolutional layers, attention blocks, normalization, and other architectures use the same chain-rule principle but different local derivative calculations.
7. Implementing one training step with NumPy
The following program reproduces the scalar example. It deliberately calculates derivatives manually so the role of backpropagation remains visible.
import numpy as np
x = 2.0
y = 3.0
learning_rate = 0.05
w1, b1 = 0.5, 0.0
w2, b2 = 2.0, 0.0
# Forward propagation
z1 = w1 * x + b1
h = np.maximum(0.0, z1)
y_pred = w2 * h + b2
loss_before = 0.5 * (y_pred - y) ** 2
# Backpropagation: calculate gradients
d_loss_d_pred = y_pred - y
d_w2 = d_loss_d_pred * h
d_b2 = d_loss_d_pred
d_h = d_loss_d_pred * w2
d_z1 = d_h * (1.0 if z1 > 0 else 0.0)
d_w1 = d_z1 * x
d_b1 = d_z1
# Gradient descent: update the parameters
w1 -= learning_rate * d_w1
b1 -= learning_rate * d_b1
w2 -= learning_rate * d_w2
b2 -= learning_rate * d_b2
# Evaluate the same example after the update
new_h = np.maximum(0.0, w1 * x + b1)
new_prediction = w2 * new_h + b2
loss_after = 0.5 * (new_prediction - y) ** 2
print(f"Before: {loss_before:.7f}")
print(f"After: {loss_after:.7f}")
print(f"New prediction: {new_prediction:.3f}")
Expected output:
Before: 0.5000000
After: 0.0078125
New prediction: 3.125
The manually written derivatives are useful for understanding a tiny network. For larger models, deep-learning frameworks such as PyTorch provide automatic differentiation, often called autograd, to compute gradients from a recorded computational graph.
Automatic differentiation is not numerical approximation
Automatic differentiation applies exact derivative rules to the elementary operations represented in a program, subject to floating-point arithmetic and defined derivative conventions. This differs from finite differences, which approximate a derivative using nearby function evaluations:
Finite differences can be valuable for gradient checking small models, but are usually too expensive and numerically delicate to use as the main gradient method in large networks.
8. Backpropagation with PyTorch
In PyTorch, trainable tensors can track gradients. The .backward() call computes derivatives; an optimizer such as stochastic gradient descent changes the parameters in a separate operation.
import torch
torch.manual_seed(7)
model = torch.nn.Sequential(
torch.nn.Linear(1, 4),
torch.nn.ReLU(),
torch.nn.Linear(4, 1),
)
optimizer = torch.optim.SGD(model.parameters(), lr=0.01)
loss_function = torch.nn.MSELoss()
x = torch.tensor([[1.0], [2.0], [3.0]])
y = torch.tensor([[2.0], [4.0], [6.0]])
optimizer.zero_grad() # Clear gradients from earlier steps
predictions = model(x) # Forward propagation
loss = loss_function(predictions, y)
loss.backward() # Backpropagation: populate gradients
optimizer.step() # Update weights and biases
print("Training step completed")
The example performs a single optimization step, not a complete training process. A full experiment normally repeats such steps, evaluates predictions on held-out data, and monitors whether the model generalizes.
PyTorch typically accumulates gradients into parameter .grad fields. Calling optimizer.zero_grad() before each standard training step prevents unintended accumulation, though deliberate accumulation across several batches is also possible.
9. Common difficulties in backward propagation
Vanishing gradients
Gradients can become very small as they propagate through many operations. Early layers may then receive weak update signals. Saturating activation functions, depth, and certain parameter configurations can contribute to the problem.
Exploding gradients
Gradients can also grow excessively, making updates unstable. Techniques such as gradient clipping, careful initialization, suitable learning rates, and architectural choices can help.
Inactive ReLU units
If a ReLU input is negative, its local derivative is zero. A unit that remains inactive across relevant inputs may receive no useful gradient through that path. ReLU variants and initialization choices can reduce this risk.
Non-differentiable operations
Not every program operation has a useful derivative. Hard thresholding, discrete choices, and changes in control flow can block or alter gradient propagation. Specialized methods or surrogate estimators may be needed for such systems.
Wrong loss or output configuration
For example, applying an inappropriate output activation or combining probabilities and logits incorrectly can cause poor learning or numerical instability. Frameworks often provide numerically stable loss functions that accept logits, so check their expected inputs.
Training versus inference mode
Dropout and batch normalization may behave differently in training and evaluation. A forward pass can therefore produce different outputs under different modes even when the model parameters are unchanged.
10. Forward propagation, backpropagation, and optimization compared
| Component | Main question | Output | Required at inference? |
|---|---|---|---|
| Forward propagation | What does the network predict? | Activations and predictions | Yes |
| Loss calculation | How far is the prediction from the target? | Scalar or aggregated loss | Not normally |
| Backpropagation | How does loss change with each parameter? | Parameter gradients | Not normally |
| Optimizer | How should parameters change? | Updated parameters | No |
Backpropagation is a gradient-computation algorithm, not a learning objective. The objective comes from the loss function; the update policy comes from the optimizer. These distinctions become important when studying SGD, momentum, Adam, regularization, and training large neural networks.
11. Check your understanding
- Why is a forward pass required before backpropagation in a conventional training step?
- In the worked example, why is the derivative of ReLU equal to ?
- What is the difference between and an updated value of ?
- Why should a training loop generally clear accumulated gradients before its next step?
- Can ordinary inference produce a prediction without running backpropagation?
Show worked answers
- The backward calculation requires the current loss and intermediate forward-pass values, including activations, to apply local derivatives.
- The pre-activation is , and ReLU has derivative at positive inputs.
- The derivative measures local sensitivity of loss to ; the optimizer uses that derivative and a learning rate or another update rule to produce a new .
- Many frameworks accumulate gradients, so old contributions would otherwise be mixed with the new step unintentionally.
- Yes. Inference normally performs only the operations needed to produce an output.
12. Related PlainCS articles
Prerequisites
- Neural Networks: Neurons, Layers, Weights, and Biases
- Derivatives, Gradients, and the Chain Rule
- Vector and Matrix Operations
- Optimization and Gradient Descent
Continue learning
- Training Neural Networks: Loss, Optimizers, and Regularization
- Convolutional and Recurrent Neural Networks
- Deep Learning with PyTorch
- AI Knowledge Map
The follow-on article links are planned in the PlainCS AI Knowledge Map and become active when their pages are published.
13. References and further reading
- Goodfellow, Bengio, and Courville, Deep Learning, Chapter 6, on feedforward networks and gradient-based learning.
- Michael Nielsen, Neural Networks and Deep Learning, Chapter 2, on the backpropagation algorithm.
- PyTorch: A Gentle Introduction to
torch.autograd, on automatic differentiation. - Google Machine Learning Crash Course: Neural Networks, on neural-network fundamentals.
Related articles in
- Convolutional and Recurrent Neural Networks — Understand convolutional networks for spatial data and recurrent networks for sequences, including CNN filters, RNN state, LSTMs, GRUs, and practical PyTorch examples.
- Deep Learning with PyTorch — Build, train, evaluate, and save a neural network with PyTorch using tensors, automatic differentiation, datasets, and optimization loops.
- Neural Networks: Neurons, Layers, Weights, and Biases — Understand the fundamental components of artificial neural networks, including neurons, weights, biases, layers, activation functions, and how networks represent learned patterns.