Neural Networks • Neural Network Foundations • 12 min read

Forward Propagation and Backpropagation

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:

  1. Obtain a batch of inputs and corresponding target values.
  2. Run a forward pass to compute predictions.
  3. Compute a loss that measures disagreement between predictions and targets.
  4. Run backpropagation to compute derivatives of the loss with respect to trainable parameters.
  5. Use an optimizer to update those parameters.
  6. 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.

Forward propagation moves from input through hidden layer to prediction and loss; backward propagation carries gradient information from loss toward the parameters
Data and activations flow forward. During training, derivatives are computed backward through the computational graph.

2. Mathematical model of a forward pass

Consider a fully connected layer with input vector a(l−1)\mathbf{a}^{(l-1)}, weight matrix W(l)W^{(l)}, bias vector b(l)\mathbf{b}^{(l)}, and activation function ϕ(l)\phi^{(l)}.

Its computation is:

z(l)=W(l)a(l−1)+b(l),\mathbf{z}^{(l)}=W^{(l)}\mathbf{a}^{(l-1)}+\mathbf{b}^{(l)}, a(l)=ϕ(l)(z(l)).\mathbf{a}^{(l)}=\phi^{(l)}(\mathbf{z}^{(l)}).

Here, ll identifies the layer; a(0)=x\mathbf{a}^{(0)}=\mathbf{x} is the input. The function ϕ\phi generally acts elementwise for a conventional dense hidden layer.

If a layer contains mm output units and receives nn inputs, its parameter shapes are:

  • W(l)∈Rm×nW^{(l)}\in\mathbb{R}^{m\times n}.
  • b(l)∈Rm\mathbf{b}^{(l)}\in\mathbb{R}^{m}.
  • z(l),a(l)∈Rm\mathbf{z}^{(l)},\mathbf{a}^{(l)}\in\mathbb{R}^{m}.

The output of one layer becomes the input to the next. A network with LL parameterized layers composes these transformations to obtain its final prediction y^=a(L)\hat{\mathbf{y}}=\mathbf{a}^{(L)}.

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:

ReLU⁡(z)=max⁡(0,z).\operatorname{ReLU}(z)=\max(0,z).

Its derivative is 00 for z<0z<0 and 11 for z>0z>0. At z=0z=0, 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 x=2x=2 and choose initial parameters:

w1=0.5,b1=0,w2=2,b2=0.w_1=0.5,\quad b_1=0,\quad w_2=2,\quad b_2=0.

The hidden neuron calculates:

z1=w1x+b1=(0.5)(2)=1,z_1=w_1x+b_1=(0.5)(2)=1, h=ReLU⁡(z1)=1.h=\operatorname{ReLU}(z_1)=1.

The output neuron calculates:

y^=w2h+b2=2.\hat{y}=w_2h+b_2=2.

Suppose the correct target is y=3y=3. For one example, use half the squared error as the loss:

L=12(y^−y)2=12(2−3)2=0.5.L=\frac{1}{2}(\hat{y}-y)^2 =\frac{1}{2}(2-3)^2=0.5.

The factor 1/21/2 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 z1=1z_1=1, h=1h=1, prediction y^=2\hat y=2, and loss L=0.5L=0.5.

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 LL depends on uu, and uu depends on ww, then:

∂L∂w=∂L∂u∂u∂w.\frac{\partial L}{\partial w} =\frac{\partial L}{\partial u} \frac{\partial u}{\partial w}.

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 ∂L/∂w\partial L/\partial w indicates that a sufficiently small increase in ww, 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:

∂L∂y^=y^−y=2−3=−1.\frac{\partial L}{\partial\hat{y}}=\hat{y}-y=2-3=-1.

Because y^=w2h+b2\hat{y}=w_2h+b_2:

∂L∂w2=∂L∂y^∂y^∂w2=(−1)h=−1,\frac{\partial L}{\partial w_2} =\frac{\partial L}{\partial\hat{y}} \frac{\partial\hat{y}}{\partial w_2} =(-1)h=-1, ∂L∂b2=−1.\frac{\partial L}{\partial b_2}=-1.

To propagate the gradient into the hidden neuron:

∂L∂h=∂L∂y^∂y^∂h=(−1)w2=−2.\frac{\partial L}{\partial h} =\frac{\partial L}{\partial\hat{y}} \frac{\partial\hat{y}}{\partial h} =(-1)w_2=-2.

Since z1=1>0z_1=1>0, the ReLU derivative at this point is 11:

∂L∂z1=∂L∂h∂h∂z1=(−2)(1)=−2.\frac{\partial L}{\partial z_1} =\frac{\partial L}{\partial h} \frac{\partial h}{\partial z_1} =(-2)(1)=-2.

Finally, using z1=w1x+b1z_1=w_1x+b_1:

∂L∂w1=∂L∂z1x=(−2)(2)=−4,\frac{\partial L}{\partial w_1} =\frac{\partial L}{\partial z_1}x=(-2)(2)=-4, ∂L∂b1=−2.\frac{\partial L}{\partial b_1}=-2.

All four trainable parameter gradients have now been computed:

ParameterCurrent valueGradient
w1w_10.50.5−4-4
b1b_100−2-2
w2w_222−1-1
b2b_200−1-1

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 η\eta, each parameter follows:

θnew=θold−η∂L∂θ.\theta_{\mathrm{new}}=\theta_{\mathrm{old}}- \eta\frac{\partial L}{\partial\theta}.

Choose η=0.05\eta=0.05. Substituting the gradients above gives:

w1′=0.5−0.05(−4)=0.7,w_1'=0.5-0.05(-4)=0.7, b1′=0−0.05(−2)=0.1,b_1'=0-0.05(-2)=0.1, w2′=2−0.05(−1)=2.05,w_2'=2-0.05(-1)=2.05, b2′=0−0.05(−1)=0.05.b_2'=0-0.05(-1)=0.05.

A second forward pass with the new parameters gives:

h′=ReLU⁡(0.7(2)+0.1)=1.5,h'=\operatorname{ReLU}(0.7(2)+0.1)=1.5, y^′=2.05(1.5)+0.05=3.125,\hat{y}'=2.05(1.5)+0.05=3.125, L′=12(3.125−3)2=0.0078125.L'=\frac12(3.125-3)^2=0.0078125.

The loss decreased from 0.50.5 to 0.00781250.0078125 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:

δ(l)=∂L∂z(l).\boldsymbol{\delta}^{(l)} =\frac{\partial L}{\partial\mathbf{z}^{(l)}}.

For a standard dense layer with elementwise activation, the backward recursion for a hidden layer is:

δ(l)=((W(l+1))Tδ(l+1))⊙ϕ′(l)(z(l)),\boldsymbol{\delta}^{(l)} =\left((W^{(l+1)})^T\boldsymbol{\delta}^{(l+1)}\right) \odot\phi'^{(l)}(\mathbf{z}^{(l)}),

where ⊙\odot denotes elementwise multiplication. At the output layer, δ(L)\boldsymbol{\delta}^{(L)} 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:

∂L∂W(l)=δ(l)(a(l−1))T,\frac{\partial L}{\partial W^{(l)}} =\boldsymbol{\delta}^{(l)}(\mathbf{a}^{(l-1)})^T, ∂L∂b(l)=δ(l).\frac{\partial L}{\partial\mathbf{b}^{(l)}} =\boldsymbol{\delta}^{(l)}.

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:

∂L∂θ≈L(θ+ε)−L(θ−ε)2ε.\frac{\partial L}{\partial\theta} \approx\frac{L(\theta+\varepsilon)-L(\theta-\varepsilon)}{2\varepsilon}.

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

ComponentMain questionOutputRequired at inference?
Forward propagationWhat does the network predict?Activations and predictionsYes
Loss calculationHow far is the prediction from the target?Scalar or aggregated lossNot normally
BackpropagationHow does loss change with each parameter?Parameter gradientsNot normally
OptimizerHow should parameters change?Updated parametersNo

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

  1. Why is a forward pass required before backpropagation in a conventional training step?
  2. In the worked example, why is the derivative of ReLU equal to 11?
  3. What is the difference between ∂L/∂w\partial L/\partial w and an updated value of ww?
  4. Why should a training loop generally clear accumulated gradients before its next step?
  5. Can ordinary inference produce a prediction without running backpropagation?
Show worked answers
  1. The backward calculation requires the current loss and intermediate forward-pass values, including activations, to apply local derivatives.
  2. The pre-activation is z1=1>0z_1=1>0, and ReLU has derivative 11 at positive inputs.
  3. The derivative measures local sensitivity of loss to ww; the optimizer uses that derivative and a learning rate or another update rule to produce a new ww.
  4. Many frameworks accumulate gradients, so old contributions would otherwise be mixed with the new step unintentionally.
  5. Yes. Inference normally performs only the operations needed to produce an output.

Prerequisites

Continue learning

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

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.

Image preview

Fit