Loss functions & gradient descent
Training means minimizing a loss: compute the gradient on a mini-batch and step weights the opposite way, scaled by the learning rate. Cross-entropy for classification, MSE for regression, AdamW with warmup for transformers.
Analogy: Walking downhill in thick fog: you only feel the slope under your feet, so you step downhill and check again. The learning rate is your stride: too long overshoots the valley, too short never gets there.
How it works
- Cross-entropy is −log p(true class); its gradient p − y is large when the model is confidently wrong.
- Each step is w ← w − η·∇L; the learning rate η matters most: too high diverges, too low crawls.
- Adam adds momentum and a per-parameter step size; AdamW decouples weight decay and is the transformer default.
- Warmup ramps the LR up while Adam's statistics are noisy; then cosine or linear decay lets it settle.
- Fine-tuning wants a far smaller LR: BERT uses 2e-5 to 5e-5, not Adam's default 1e-3.
Check yourself
Answer to mark it learned; your answers aren't scored.
You fine-tune pretrained BERT-base for ticket classification with Adam at its textbook lr = 1e-3. Within a few hundred steps it predicts only the majority class. What's your first fix?
Go deeper
Full explanation
A loss function turns "how wrong is the model" into one number to minimize:
- MSE (mean squared error) for regression: squares errors, so big misses dominate.
- Cross-entropy / log loss for classification: −log p(true class). It's the negative log-likelihood of a softmax or sigmoid output, so minimizing it is maximum likelihood; its gradient w.r.t. the logits is simply p − y, large when the model is confidently wrong.
Gradient descent moves every weight downhill: w ← w − η·∇L(w). The learning rate η is the most important hyperparameter: too high diverges, too low crawls.
- Mini-batch SGD: estimate the gradient on ~32–4,096 examples instead of the full dataset. Cheap per step, GPU-friendly, and the noise is a mild regularizer.
- Momentum (β ≈ 0.9): a running average of gradients, so you roll along narrow valleys instead of zig-zagging.
- Adam: momentum plus a per-parameter step size from a running average of squared gradients. AdamW applies weight decay separately from that adaptive step; it's the default for transformers.
- Schedules: warmup ramps the LR up over the first few hundred to few thousand steps, while Adam's statistics are still noisy; then cosine or linear decay lets the model settle.
Code Mini-batch SGD with momentum on logistic regression (numpy)
import numpy as np
# Tiny logistic regression trained with mini-batch SGD + momentum
rng = np.random.default_rng(0)
X = rng.normal(size=(2000, 2))
true_w, true_b = np.array([2.0, -3.0]), 0.5
y = (X @ true_w + true_b + rng.logistic(size=2000) > 0).astype(float)
def sigmoid(z): return 1 / (1 + np.exp(-z))
def log_loss(w, b): # binary cross-entropy = negative log-likelihood
p = np.clip(sigmoid(X @ w + b), 1e-7, 1 - 1e-7)
return -np.mean(y * np.log(p) + (1 - y) * np.log(1 - p))
w, b = np.zeros(2), 0.0
vw, vb = np.zeros(2), 0.0 # momentum buffers
lr, beta, batch = 0.05, 0.9, 64
for step in range(2001):
idx = rng.integers(0, len(X), batch) # sample a mini-batch
p = sigmoid(X[idx] @ w + b)
err = p - y[idx] # dLoss/dlogit for sigmoid + cross-entropy
gw, gb = X[idx].T @ err / batch, err.mean()
vw = beta * vw + gw # momentum: running sum of gradients
vb = beta * vb + gb
w, b = w - lr * vw, b - lr * vb # step against the gradient
if step % 500 == 0:
print(f"step {step:4d} loss {log_loss(w, b):.3f}") # 0.688 -> ~0.33
print("learned:", w.round(2), round(b, 2), " true:", true_w, true_b) # ~[1.9 -2.8] 0.55
# Transformer-style in PyTorch: AdamW + warmup + cosine decay
# opt = torch.optim.AdamW(model.parameters(), lr=3e-4, betas=(0.9, 0.95), weight_decay=0.1)
# sched = transformers.get_cosine_schedule_with_warmup(opt, 2_000, 100_000)Real example
You fine-tune BERT-base for ticket classification with Adam's textbook LR of 1e-3. Within a few hundred steps the model collapses to predicting the majority class: the pretrained weights get wrecked. You switch to the BERT paper's range: LR 2e-5 to 5e-5, batch 16–32, 2–4 epochs, with linear warmup over the first 10% of steps, then linear decay. Loss falls smoothly and validation accuracy plateaus by epoch 3. Lesson: check the LR first, and fine-tuning wants a far smaller LR than training from scratch.
Trade-offs +3 · −3
+ You gain
- Cost per step doesn't depend on dataset size: mini-batch SGD scales to billions of examples and parameters.
- AdamW works across architectures with little tuning beyond the learning rate.
- Cross-entropy yields probabilities you can threshold and calibrate, not just a ranking.
− You pay
- Adam stores two moment tensors per parameter: optimizer state is 2× the weights at equal precision, more in mixed precision.
- Very sensitive to the learning rate; a wrong one wastes a whole run.
- On non-convex losses there's no global-optimum guarantee; results vary with seed and init.
Use it when
AdamW + warmup + cosine decay for transformers and most deep nets. SGD + momentum remains a strong choice for CNNs on vision (the ResNet recipe).
Avoid it when
Small convex problems: closed-form least squares or L-BFGS (scikit-learn's default for LogisticRegression) are faster and need no LR. Gradient-boosted trees fit each tree to gradients, not via backprop.
Numbers to know 5
- Adam defaults: lr 1e-3, β1 0.9, β2 0.999, ε 1e-8 (Kingma & Ba); LLM pretraining often uses β2 0.95 (GPT-3, LLaMA).
- LLaMA recipe: AdamW, weight decay 0.1, 2,000 warmup steps, cosine decay to 10% of peak LR, gradient clipping 1.0.
- BERT fine-tuning grid: LR 5e-5, 3e-5 or 2e-5; batch 16 or 32; 2–4 epochs.
- Mixed-precision Adam needs ~16 bytes per parameter (weights, grads, fp32 master + 2 moments): ~112 GB for 7B, before activations.
- Original Transformer: 4,000 warmup steps, then LR decays ∝ 1/√step.
Common pitfalls 4
- MSE on sigmoid outputs for classification: gradients vanish exactly when the model is confidently wrong.
- Adam + L2 in the loss instead of AdamW: the adaptive step rescales the penalty and weakens it.
- Changing batch size without retuning LR; for SGD start from the linear-scaling rule plus warmup (Goyal et al., 2017).
- Training transformers without warmup or gradient clipping: early loss spikes and NaNs.
Interview questions 3
Answer out loud first, then reveal.
Why cross-entropy and not MSE for classification?Show answer
Three reasons. First, cross-entropy is the negative log-likelihood of a categorical model, so minimizing it is maximum likelihood and gives usable probabilities. Second, gradients: with sigmoid or softmax, the gradient w.r.t. the logits is p − y, big when the model is confidently wrong. With MSE on a sigmoid it gets multiplied by p(1 − p), which goes to zero when the output saturates, so learning stalls exactly when the model is most wrong. Third, for logistic regression cross-entropy is convex in the weights; MSE isn't.
Your training loss spikes to NaN after a few hundred steps. What do you check?Show answer
In order of likelihood. Learning rate: cut it 3–10× or lengthen warmup, because early Adam steps are large while its variance estimate is noisy. Gradient norm: log it every step and clip at 1.0. Numerics: fp16 overflow, so switch to bf16 or use loss scaling, and check custom losses for log(0). Data: log the batch that spiked; empty, corrupt or extreme examples are common culprits. I reproduce on a small model first so each experiment takes minutes, not hours.
Adam or SGD with momentum: which and why?Show answer
For transformers, AdamW: per-parameter step sizes cope with the very different gradient scales across embeddings, attention and MLP layers, and it converges fast with little tuning. SGD with momentum keeps one state buffer instead of two and is still standard for CNN image classification, where it generalizes as well or slightly better. If Adam's memory blocks a huge model, I shard optimizer state with FSDP/ZeRO or try a memory-light optimizer like Adafactor before giving up adaptivity.