Neural networks & backpropagation
A neural network stacks linear layers with nonlinear activations; backpropagation runs the chain rule backward from the loss to get every weight's gradient in one pass, which gradient descent then uses.
Analogy: An assembly line: each station (layer) reshapes the part a little. When the final product is off, blame flows backward station by station, and each one adjusts in proportion to how much it caused the defect.
How it works
- Without the nonlinearity, stacked layers collapse into one linear map; it is what makes depth useful.
- Backprop reuses the stored activations and costs ~2× the forward pass.
- Gradients multiply one factor per layer, so they vanish or explode exponentially with depth.
- Fixes: He/Xavier init, normalization, residual connections (y = x + F(x)) and gradient clipping.
- If a deeper model has worse training loss, fix optimization (architecture, init, LR), not data.
Check yourself
Answer to mark it learned; your answers aren't scored.
Your 56-layer plain CNN has higher training error than your 20-layer one, and both use BatchNorm. A teammate calls it overfitting and wants more dropout. What do you do?
Go deeper
Full explanation
A neuron computes a weighted sum plus a bias, then a nonlinearity: a = φ(w·x + b). A layer does many at once as a matrix multiply, h = φ(Wx + b), and a network stacks layers. Without φ the whole stack collapses into one linear map; the nonlinearity is what makes depth useful.
Activations: ReLU, max(0, z), is cheap and doesn't saturate for z > 0. GELU is a smooth variant used in BERT and GPT-2; many recent LLMs (LLaMA, PaLM) use SwiGLU. Sigmoid and tanh saturate, so they survive mainly in gates and outputs.
Training loops three steps: the forward pass computes outputs and the loss; backprop applies the chain rule from the loss back to every weight, reusing the stored activations, for ~2× the forward cost; then a Loss functions & gradient descent step updates the weights.
Vanishing/exploding gradients: backprop multiplies one factor per layer, so gradients shrink or blow up exponentially with depth. Fixes: ReLU-family activations, He/Xavier init (keeps activation variance stable), normalization (BatchNorm, LayerNorm), residual connections (y = x + F(x) gives gradients a direct path) and gradient clipping.
Universal approximation: one wide-enough hidden layer can approximate any continuous function on a bounded domain. In practice, depth gets there with far fewer parameters.
Code A tiny MLP and the 4-step training loop (PyTorch)
import torch, torch.nn as nn
from sklearn.datasets import make_moons
X, y = make_moons(n_samples=2000, noise=0.2, random_state=0) # not linearly separable
X, y = torch.tensor(X, dtype=torch.float32), torch.tensor(y)
# 2 -> 64 -> 64 -> 2 MLP. Remove the ReLUs and it collapses to one linear map.
model = nn.Sequential(
nn.Linear(2, 64), nn.ReLU(),
nn.Linear(64, 64), nn.ReLU(),
nn.Linear(64, 2), # raw logits: CrossEntropyLoss applies log-softmax
)
loss_fn = nn.CrossEntropyLoss()
opt = torch.optim.AdamW(model.parameters(), lr=1e-2)
for epoch in range(101):
for idx in torch.randperm(len(X)).split(128): # shuffled mini-batches
logits = model(X[idx]) # 1. forward pass
loss = loss_fn(logits, y[idx]) # 2. loss
opt.zero_grad() # grads accumulate unless cleared
loss.backward() # 3. backprop: chain rule via autograd
opt.step() # 4. gradient-descent update
if epoch % 25 == 0:
with torch.no_grad():
acc = (model(X).argmax(dim=1) == y).float().mean()
print(f"epoch {epoch:3d} loss {loss.item():.3f} acc {acc:.3f}") # acc ~0.97
# Per-layer gradient norms: the first thing to log when training stalls or explodes
for name, p in model.named_parameters():
print(f"{name:10s} grad norm {p.grad.norm():.4f}")Real example
In the ResNet paper, a 56-layer plain CNN had higher training error than a 20-layer one on CIFAR-10. That isn't overfitting (train error is worse) but an optimization problem; the authors even checked that BatchNorm kept gradient norms healthy. Identity shortcuts, y = x + F(x), make the identity trivial to learn and give gradients a direct path: a 110-layer ResNet trained fine on CIFAR-10, and an ensemble of ResNets up to 152 layers won ImageNet 2015 at 3.57% top-5 error. Debugging rule: if a deeper model is worse on training loss, fix optimization (architecture, init, LR), not data.
Trade-offs +3 · −3
+ You gain
- Learn features straight from raw pixels, tokens or audio instead of hand-engineering them.
- Backprop gets every gradient for ~2× a forward pass, whatever the parameter count.
- Quality keeps improving predictably with more data and compute (scaling laws).
− You pay
- Data- and compute-hungry; on medium-sized tabular data gradient-boosted trees usually still win.
- Hard to interpret, and confidently wrong on out-of-distribution inputs.
- Many interacting knobs (init, LR, normalization); failures are often silent stalls or NaNs.
Use it when
Unstructured data (images, text, audio), very large datasets, or when you want learned embeddings you can reuse across tasks.
Avoid it when
Small or medium tabular data, where XGBoost/LightGBM are usually stronger, cheaper and easier to explain, or when a regulator requires a fully interpretable model.
Numbers to know 4
- Sigmoid's derivative peaks at 0.25: across 10 sigmoid layers the activation factors alone can shrink gradients to 0.25¹⁰ ≈ 10⁻⁶.
- Training ≈ 6·N FLOPs per token (2N forward, ~4N backward), i.e. ~3× inference (Kaplan et al., 2020).
- He init for ReLU: weight variance 2/fan_in; Xavier/Glorot: 2/(fan_in + fan_out).
- Activation checkpointing recomputes activations instead of storing them: ~one extra forward pass (~33% more compute) for much less memory.
Common pitfalls 4
- Forgetting
optimizer.zero_grad(): PyTorch accumulates gradients, so each step adds up all previous ones. - Adding a softmax before
nn.CrossEntropyLoss, which expects raw logits: the double softmax squashes gradients. - Zero or identical init: every neuron in a layer gets the same gradient and they never differentiate.
- Dead ReLUs after a too-high LR: units output 0 for every input and stop learning. Track the fraction of zero activations.
Interview questions 3
Answer out loud first, then reveal.
Explain backpropagation.Show answer
It's the chain rule applied efficiently. In the forward pass each layer computes its output, and we keep those activations. Going backward from the loss, each layer receives the gradient of the loss w.r.t. its output, multiplies by its local derivative to get the gradient for its own weights, and passes the gradient w.r.t. its input to the layer below. Because every intermediate result is reused, all gradients cost about two forward passes. That's why training is ~3× inference FLOPs per token, and why stored activations are a big chunk of training memory.
What causes vanishing gradients, and how do modern networks avoid them?Show answer
The gradient at an early layer is a product of one factor per later layer. If those factors are mostly below 1 (sigmoid's derivative is at most 0.25), it shrinks exponentially with depth; above 1, it explodes. Modern stacks attack it at every level: ReLU or GELU, which don't saturate for positive inputs; He or Xavier init to keep variance stable; LayerNorm or BatchNorm; and residual connections, an identity path the gradient flows through unmultiplied. For explosions I add gradient clipping at norm 1.0, and I monitor per-layer gradient norms.
If one hidden layer is a universal approximator, why go deep?Show answer
The theorem says a wide enough single layer can represent any continuous function, not that it's efficient or learnable from finite data. Some functions need exponentially more units when the network is shallow. Depth composes features, edges into textures into parts into objects, so the same function takes far fewer parameters and the reusable hierarchy generalizes better. The cost is harder optimization, which is why I pair depth with residuals, normalization and good init, and pick width and depth by compute budget.