Backpropagation Algorithm
Backpropagation is the algorithm used to minimize the neural network cost function. It computes the gradients of the cost function with respect to the parameters, allowing us to perform gradient descent and update our model.
⏪ Backpropagation Algorithm (BP)
Core Insight
Backpropagation is:
- Repeated application of the chain rule
- Error flowing from output to input
- Weighted by connection strengths
- Modulated by the activation derivative
In short:
Forward pass computes predictions.
Backward pass computes gradients.
Training flow:
flowchart TD
A["Forward Pass"]
--> B["Prediction"]
B --> C["Loss Calculation"]
C --> D["Backpropagation"]
D --> E["Gradient Updates"]
Gradients tell each layer:
- how much to adjust weights
Why we do Backward Propagation?
Backpropagation is the algorithm used to minimize the neural network cost function.
Just like gradient descent in linear and logistic regression, our goal is:
That is, we want to find parameters that minimize the cost function.
Where
Objective
We want to compute the partial derivatives:
These derivatives are used in gradient descent to update the parameters.
How Backpropagation Works
Backpropagation computes errors from right to left.
We start at the output layer:
Then propagate backward using:
For sigmoid activation:
So equivalently:
❗ Loss Function
A loss function measures how wrong your model’s prediction is compared to the actual value.
It answers one simple question: How far off was the prediction?
Error is represented as:
where represents the error of unit in layer .
Loss function converts error into a number the model can optimize.
More formally:
So:
- is the derivative of the cost with respect to
- It measures how much that unit contributed to the error
- Larger magnitude → steeper slope → more incorrect
Example: House Price
If actual house price = €500,000
The model makes a prediction: Model predicts = €480,000
The loss function calculates the error :
Error = €500,000 -€480,000 = €20,000
So
The optimizer adjusts the parameters to reduce that error.
- The training process tries to minimize this loss.
- Repeat this thousands of times → model improves.
⚖️ Loss vs Cost Function
- ❗ Loss → error for one example
- 💰 Cost → average loss over the dataset
🎢 Backpropagation Gradient Computation
- Forward propagation → computes activations.
- Backpropagation → computes errors ( values).
- Errors are propagated from right to left.
- Gradients are accumulated in .
- Regularization is added for non-bias weights.
- Finally, we divide by to obtain the average gradient.
Backpropagation Algorithm
Given training set:
Step 1: 🌱 Initialize Accumulators
Set:
for all .
This creates matrices of zeros to accumulate gradients.
Step 2: For each training example to
Backpropagation works per example, and gradients are summed (or averaged) over the dataset.
Example: For two training examples and
- compute FP for , Compute BP for
- compute FP for , Compute BP for
- Finally Average (or sum) the gradients
2.1 ⏩ Forward Propagation
Set:
Compute forward propagation for:
to obtain activations for any Network layer :
Or when look Forward
Where
- = activations of layer
- = linear combination before activation
- = weight matrix between layer and
- = activation function
2.2 ❗Compute Output Layer Error ()
Using the true label :
This is the error of the output layer.
2.3 ⏪ Backpropagate the Errors
For layers:
Compute:
For sigmoid activation:
So equivalently:
The operator denotes element-wise multiplication.
2.4 📥 Accumulate Gradients
Update:
Vectorized form:
Step 3: 🎢 Compute Gradients
After processing all training examples:
For (non-bias terms):
For bias terms ():
Final Result
The gradient of the cost function is:
The matrix gives the partial derivatives used in gradient descent.
Example:
Given one training example
Layer 1 (Input)
⏩ Forward Propagation
⏪ Backward Propagation
No Error Term Associated with Input Term
Layer 2
⏩ Forward Propagation
(Add bias unit if applicable.)
⏪ Backward Propagation
Layer 3
⏩ Forward Propagation
⏪ Backward Propagation
Layer 4 (Output)
⏩ Forward Propagation
⏪ Backward Propagation
Output Layer Error = Calculated Value - Actual Value
Geometric Interpretation
Think of the network as a graph:
- Nodes = neurons
- Edges = weights
- Errors flow backward through edges
To compute :
- Take all connections going forward from unit
- Multiply each weight by the corresponding
- Sum them up
This is simply the chain rule applied repeatedly.
Example:
To compute:
We sum over the next layer:
Example
To compute:
We sum contributions from the next layer:
Modern Relevance
Backpropagation is what made training deep neural networks possible — and it runs at massive scale in production today, mostly hidden behind a single line of code.
In PyTorch, the entire backward pass is loss.backward(). PyTorch's autograd engine builds a computation graph during the forward pass (recording every operation and its local gradient function), then traverses it in reverse order to compute ∂J/∂θ for every parameter. The delta values δ⁽ˡ⁾ computed here are exactly what autograd propagates through each node.
Gradient checkpointing is a direct trade-off against the memory cost of backpropagation. The standard approach stores all intermediate activations a⁽ˡ⁾ during the forward pass so the backward pass can use them. For a 70B model, this requires ~100s of GB. Gradient checkpointing discards intermediate activations and recomputes them during the backward pass — trading ~33% extra compute for a large memory saving. This is why 70B fine-tuning on limited hardware uses gradient checkpointing.
Mixed precision backpropagation: On H100s, the forward pass uses BF16, but gradients are accumulated in FP32. The reason: BF16 has only 8 bits of mantissa. Summing millions of small gradient updates in BF16 loses precision through catastrophic cancellation. FP32 accumulation preserves numerical accuracy, at the cost of double the memory for the gradient buffer.
LoRA's gradient efficiency: LoRA (Low-Rank Adaptation) freezes W₀ during fine-tuning so backpropagation only computes ∂J/∂B and ∂J/∂A — the two small adapter matrices. This reduces the backward-pass memory from 840 GB (full fine-tuning of 70B) to ~1 GB for the adapter gradients, while the frozen W₀ contributes zero gradient memory.
Custom CUDA kernels must implement their own backward pass. Flash Attention's custom CUDA kernel cannot use PyTorch autograd. The Flash Attention team derived and implemented the backward pass manually — the same chain rule computation shown here, but rewritten to avoid materializing the N×N attention score matrix in HBM.
Related Posts
- Cost Function for Neural Networks — backpropagation minimizes the cost function defined here; the delta values are partial derivatives of this cost
- Forward Propagation in Neural Networks — forward propagation must run first to compute activations; backpropagation then flows those gradients in reverse
- Stochastic Gradient Descent — SGD uses the gradients backpropagation computes; the two algorithms together form the complete training loop
- TensorRT and High-Performance AI Inference — the trained neural network produced by backpropagation is what TensorRT compiles and optimizes for GPU inference
