Skip to content
E
Educatum

What is backpropagation?

Curated by Educatum AI teamLast updated:
Neural Networks and Deep LearningNN
Direct Answer

Backpropagation is the reverse-mode automatic differentiation algorithm used to compute exact gradients of a loss function with respect to every weight and bias in a neural network. After a forward pass caches intermediate activations, backpropagation applies the chain rule from output to input in time proportional to a single forward pass. Optimization algorithms such as SGD or Adam then use these gradients to update parameters and minimize the loss.

Study Card: What is Backpropagation?

Direct Answer

Backpropagation (short for backward propagation of errors) is an algorithm that computes the gradient of a scalar loss function L\mathcal{L} with respect to all trainable parameters in a neural network. It is a specific application of reverse-mode automatic differentiation using the chain rule of calculus.

For layer ll with pre-activation z(l)=W(l)a(l−1)+b(l)\mathbf{z}^{(l)} = W^{(l)} \mathbf{a}^{(l-1)} + \mathbf{b}^{(l)} and activation a(l)=ϕ(z(l))\mathbf{a}^{(l)} = \phi(\mathbf{z}^{(l)}), define the local error signal δ(l)=∂L∂z(l)\boldsymbol{\delta}^{(l)} = \frac{\partial \mathcal{L}}{\partial \mathbf{z}^{(l)}}. Backpropagation propagates this signal backward from layer LL down to layer 11:

δ(l)=((W(l+1))⊤δ(l+1))⊙ϕ′(z(l)),∂L∂W(l)=δ(l)(a(l−1))⊤,∂L∂b(l)=δ(l)\boldsymbol{\delta}^{(l)} = \left((W^{(l+1)})^\top \boldsymbol{\delta}^{(l+1)}\right) \odot \phi'(\mathbf{z}^{(l)}), \qquad \frac{\partial \mathcal{L}}{\partial W^{(l)}} = \boldsymbol{\delta}^{(l)} (\mathbf{a}^{(l-1)})^\top, \qquad \frac{\partial \mathcal{L}}{\partial \mathbf{b}^{(l)}} = \boldsymbol{\delta}^{(l)}

Computing gradients for all parameters takes roughly the same asymptotic compute as one forward pass (O(forward)O(\text{forward})), while storing intermediate activations requires O(depth)O(\text{depth}) memory unless activation checkpointing is used. Optimizers (SGD, Adam) then use these gradients to update weights.

Key Terms

  • Loss Function: Scalar objective L(y,y^)\mathcal{L}(y, \hat{y}) quantifying the mismatch between predictions and targets.
  • Gradient: Vector of partial derivatives indicating the direction and magnitude of steepest increase of the loss.
  • Chain Rule: Calculus rule for differentiating composite functions, allowing local derivatives at each operation to be reused efficiently across all upstream parameters.
  • Forward Pass: Evaluating the network from input to loss while caching intermediate tensors needed for the backward pass.
  • Optimization Algorithm: Update rule (such as SGD or Adam) that steps parameters opposite the gradient to minimize L\mathcal{L}.

Example

Consider a two-layer network predicting house prices from features like square footage and location. During the forward pass, inputs travel through hidden activations to produce a predicted price, and MSE compares it to the true price. If the prediction is too high, backpropagation computes ∂L∂y^>0\frac{\partial \mathcal{L}}{\partial \hat{y}} > 0, propagates that error signal backward across the output weights and hidden-layer activation derivatives, and produces parameter gradients ∂L∂W(2)\frac{\partial \mathcal{L}}{\partial W^{(2)}} and ∂L∂W(1)\frac{\partial \mathcal{L}}{\partial W^{(1)}}. Gradient descent then adjusts each weight proportionally to reduce the error on the next step.

Code Implementation

import numpy as np
import tensorflow as tf


def sigmoid(z):
    return 1.0 / (1.0 + np.exp(-z))


# 1. Automatic differentiation with TensorFlow GradientTape
model = tf.keras.Sequential([
    tf.keras.layers.Input(shape=(3,)),
    tf.keras.layers.Dense(2, activation="sigmoid"),
    tf.keras.layers.Dense(1),
])

loss_fn = tf.keras.losses.MeanSquaredError()
X = tf.constant([[1.0, 2.0, 3.0]])
y_true = tf.constant([[4.0]])

with tf.GradientTape() as tape:
    y_pred = model(X)
    loss_value = loss_fn(y_true, y_pred)

gradients = tape.gradient(loss_value, model.trainable_variables)
print("TensorFlow autograd gradients:")
for var, grad in zip(model.trainable_variables, gradients):
    print(f"{var.name}:\n{grad.numpy()}\n")

# 2. Manual backpropagation through both layers in NumPy
w1 = np.array([[0.1, 0.2], [0.3, 0.4], [0.5, 0.6]])  # shape (3, 2)
b1 = np.array([0.1, 0.2])                             # shape (2,)
w2 = np.array([[0.7], [0.8]])                         # shape (2, 1)
b2 = np.array([0.3])                                  # shape (1,)

x_np = np.array([1.0, 2.0, 3.0])
y_np = np.array([4.0])

# Forward pass
z1 = x_np @ w1 + b1
a1 = sigmoid(z1)
z2 = a1 @ w2 + b2
y_pred_np = z2
loss = np.mean((y_pred_np - y_np) ** 2)

# Backward pass (output layer -> hidden layer)
dL_dz2 = 2.0 * (y_pred_np - y_np)                     # shape (1,)
dL_dw2 = np.outer(a1, dL_dz2)                         # shape (2, 1)
dL_db2 = dL_dz2                                       # shape (1,)

dL_da1 = dL_dz2 @ w2.T                                # shape (2,)
dL_dz1 = dL_da1 * (a1 * (1.0 - a1))                   # sigmoid derivative
dL_dw1 = np.outer(x_np, dL_dz1)                       # shape (3, 2)
dL_db1 = dL_dz1                                       # shape (2,)

print("Manual NumPy backpropagation:")
print("dL/dw2:\n", dL_dw2)
print("dL/db2:", dL_db2)
print("dL/dw1:\n", dL_dw1)
print("dL/db1:", dL_db1)
  • Gradient Descent: Uses backpropagated gradients to iteratively update network weights (θ←θ−η∇θL\theta \leftarrow \theta - \eta \nabla_\theta \mathcal{L}).
  • Computational Graphs: Directed acyclic graphs representing tensor operations so frameworks can traverse dependencies in reverse topological order.
  • Reverse-Mode vs. Forward-Mode Autodiff: Reverse-mode is efficient when there are many parameters and one scalar loss; forward-mode is preferable when outputs outnumber inputs.
  • Activation Checkpointing: Trades extra forward recomputation for reduced O(L)O(\sqrt{L}) activation memory in very deep networks.
  • Vanishing/Exploding Gradients: Numerical instability across long chains of layer Jacobians during backpropagation.
View all →

Try keywords like RoPE, FlashAttention, DPO, or Blind 75.