Braj Kishore
JourneyVaultML FoundationsAI PM GuideAgenticNewsWork With MeMentorshipPulseNow
Say hi

Hiring · Building · Investing

Have a system — or a team —that needs to scale?

info@avyxon.ai

Usually replies within a day · track record here

JourneyVaultML FoundationsAI PM GuideAgenticNewsWork With MeMentorshipPulseNow
LinkedInXYouTubeSubstackInstagramThreadsFacebookDiscordGitHubTopmate
© 2026 Braj Kishore · Bengaluru, INThink Big · Start Small · Scale Fast
ML Foundations
05Track 2 · The training loop

Gradient descent

The algorithm that does the learning: read the slope, step downhill, repeat — and the one hyperparameter that decides whether it converges or explodes.

55 min1 interactive6 sources

You're on a hillside in thick fog with no map. You can feel the slope under your feet and you want the valley. So you feel which way is steepest, take a step that way, and repeat. That is gradient descent, and a frontier model is trained by doing it a few hundred thousand times on a surface with a trillion dimensions.

The intuition

The gradient is the direction of steepest ascent, so you step against it. The learning rate is your stride length. Too short and you're still on the hill at sunset; too long and you stride straight over the valley onto the opposite slope, higher than you started.

Unlearn this

That the danger is getting stuck in local minima. In high dimensions, true local minima are vanishingly rare — for a point to be a local minimum, the loss must curve upward in every one of a million directions at once. The real obstacles are saddle points, long flat plateaus, and ravines where the surface is far steeper across than along.

01The update rule, and why the learning rate is everything

Compute the gradient of the loss with respect to every parameter, then move each parameter a small step in the opposite direction. One line, and it is the entire learning algorithm.

The learning rate η scales that step. It is, by a wide margin, the most consequential hyperparameter in deep learning, and it is the first thing to tune when a model won't train. Too small and training crawls, or stalls on a plateau and looks converged when it isn't. Too large and each step overshoots the minimum, the loss oscillates, and past a threshold it diverges to NaN within a few dozen steps.

The failure signatures are distinguishable and worth memorising. Loss flat from step one: learning rate far too low, or the gradient isn't flowing (dead units, a detached graph, a bug). Loss decreasing then oscillating on a plateau: learning rate slightly too high — decay it. Loss spiking to NaN: far too high, or exploding gradients — lower it and clip.

θ ← θ − η ∇θ L(θ)

The whole of learning. θ is every parameter; ∇θL is backprop's output; η is the learning rate.

Gradient descent, how neural networks learn (Chapter 2)3Blue1Brown

Try it

Step downhill — but how far?

Two dials: where you start and how far you step. Every training failure you'll debug lives on them.

02Batch, stochastic, mini-batch

Batch gradient descent computes the gradient over the entire training set before taking one step. The gradient is exact and the path is smooth, but you do a full pass per update, which is unusable for any dataset that doesn't fit in memory.

Stochastic gradient descent updates after every single example. Updates are cheap and frequent, and the noise can bounce the optimiser out of bad regions, but the path is jagged and it wastes the hardware — a GPU doing one example at a time is a supercomputer doing scalar arithmetic.

Mini-batch is the answer everyone uses: 32 to 512 examples per step for typical training, far larger for big distributed runs. It's a full matrix multiply, so the GPU is saturated, and the gradient noise acts as a mild regulariser. Batch size interacts with learning rate — the common heuristic is that if you multiply batch size by k you can scale the learning rate by roughly k (or √k), with a warmup period to keep the first steps from blowing up.

The trap

'Batch size' in an interview usually means mini-batch. If asked for the trade-off, answer with three axes: gradient noise (small batches regularise), hardware utilisation (large batches saturate the GPU), and memory (activations scale with batch size).

Stochastic Gradient Descent, Clearly ExplainedStatQuest with Josh Starmer

03Momentum, RMSProp, Adam — what each one fixes

Plain SGD struggles in a ravine: a surface much steeper across one axis than along another. It bounces between the walls and creeps along the floor. Momentum fixes this by accumulating an exponentially weighted average of past gradients, so consistent directions build speed and oscillating ones cancel out. The physical analogy is a ball with mass rolling down the surface rather than a point re-deciding at every step.

The second problem is that one learning rate has to serve every parameter, when some features are dense and some are rare. AdaGrad gave each parameter its own effective rate by dividing by the accumulated squared gradient — good, except the accumulator only grows, so the rate decays to zero and learning stops. RMSProp fixed that with an exponentially decaying average instead of a sum.

Adam combines both: momentum on the first moment, RMSProp-style scaling from the second moment, plus a bias correction for the early steps when both estimates start at zero. It's robust enough to be the default for most deep learning, and AdamW — Adam with weight decay decoupled from the gradient update — is the standard for training transformers.

The honest caveat, because it's a good follow-up: for some vision tasks, well-tuned SGD with momentum still generalises slightly better than Adam. Adam's advantage is that it works acceptably without much tuning, which is worth a great deal in practice.

v ← βv + (1−β)∇L ; θ ← θ − ηv

Momentum: an EWMA of gradients. Consistent directions accumulate, oscillations cancel.

θ ← θ − η · m̂ / (√v̂ + ε)

Adam: momentum in the numerator, per-parameter scaling in the denominator, both bias-corrected.

Why Momentum Really WorksGoh, DistillAdam: A Method for Stochastic OptimizationKingma & Ba · 2014

04Schedules, warmup and clipping

A fixed learning rate is a compromise between the large steps you want early and the fine steps you need near the optimum. Schedules resolve it: step decay, cosine annealing, or reduce-on-plateau. Cosine decay to near-zero is the default for large model training.

Warmup — starting near zero and ramping up over the first few hundred or few thousand steps — matters for transformers specifically. At initialisation the adaptive optimiser's variance estimates are based on almost no data and are unreliable, and large early steps can wreck the model before it stabilises. Warmup plus cosine decay is the standard recipe you'll see in essentially every LLM training report.

Gradient clipping caps the global norm of the gradient vector before the update. It doesn't change the direction, only the magnitude, and it turns a rare exploding-gradient spike from a run-ending NaN into a slightly odd step. For recurrent networks it's effectively mandatory; for transformers it's standard insurance at around norm 1.0.

The loop, written out. Five lines that every framework wraps.
for epoch in range(epochs):
    for xb, yb in loader:                 # 1. a mini-batch
        pred = model(xb)                  # 2. forward pass
        loss = criterion(pred, yb)        # 3. how wrong?

        optimizer.zero_grad()             # 4. clear last step's gradients
        loss.backward()                   #    backprop: fill .grad on every parameter
        torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
        optimizer.step()                  # 5. theta -= lr * grad
    scheduler.step()                      # decay the learning rate

# Forgetting zero_grad() is the classic bug: PyTorch ACCUMULATES gradients,
# so without it step 5 uses the sum of every batch so far and training diverges.
Neural Networks Part 3: Learning and EvaluationStanford CS231n

05What the loss surface actually looks like

Textbook pictures show a smooth bowl with one troublesome dip on the side. Real loss surfaces in high dimensions behave differently, and the difference is a favourite senior-level question.

For a critical point to be a local minimum, the loss must curve upwards along every one of the millions of directions. The probability of that happening by chance falls off exponentially with dimension, so almost every critical point is a saddle — up in some directions, down in others. Saddles slow training rather than stopping it, and momentum plus gradient noise generally escapes them.

The practical consequences: the flat regions that look like convergence usually aren't, so give training more patience than feels reasonable; different random initialisations converge to different minima with similar loss but genuinely different behaviour on edge cases; and there is evidence that flatter minima generalise better, which is part of why small-batch noise and weight decay help.

A Recipe for Training Neural NetworksAndrej Karpathy
The vocabulary, defined once
Gradient
The vector of partial derivatives of the loss w.r.t. every parameter. Points uphill, so you step against it.
Learning rate (η)
Step size. The most important hyperparameter; too high diverges, too low stalls.
Mini-batch
The 32–512 examples per update that balance gradient noise, GPU utilisation and memory.
Momentum
An EWMA of past gradients that builds speed in consistent directions and cancels oscillation in ravines.
Adam / AdamW
Momentum plus per-parameter adaptive scaling, bias-corrected. AdamW decouples weight decay; the transformer default.
Warmup + cosine decay
Ramp the LR up over early steps, then anneal it down. The standard schedule for large-model training.
Gradient clipping
Cap the gradient's global norm before the update. Converts exploding-gradient spikes into survivable steps.
Saddle point
A critical point that curves up in some directions and down in others. In high dimensions these, not local minima, are the real obstacle.

The lab

Everything above, with the dials exposed. Break it deliberately — the failure modes are where the understanding is.

Try it

Step downhill — but how far?

Two dials: where you start and how far you step. Every training failure you'll debug lives on them.

What they actually ask

Gradient descent — the interview questions

QExplain gradient descent to me.Answer it out loud first, then open this

Compute how the loss changes with respect to each parameter — that's the gradient — then move every parameter a small step in the opposite direction, because the gradient points uphill. Repeat over mini-batches. The step size is the learning rate, and it's the hyperparameter that decides whether you converge, crawl or diverge.

QAdam or SGD?Answer it out loud first, then open this

Adam by default: it adapts a per-parameter rate so it works without much tuning, which matters when you have one shot at a training run. AdamW specifically for transformers, because decoupled weight decay regularises properly. But well-tuned SGD with momentum still generalises slightly better on some vision benchmarks, so if I had budget for a sweep and a fixed architecture, I'd compare rather than assume.

What they're listening for
Knowing that Adam isn't automatically better is the differentiator; most candidates answer 'Adam, it's adaptive' and stop.

QWhy do transformer training runs use learning-rate warmup?Answer it out loud first, then open this

At the start, Adam's second-moment estimates come from a handful of samples and are unreliable, so early large steps can destabilise a model that hasn't found any structure yet. Ramping from near zero over the first few thousand steps lets those estimates settle, then cosine decay takes it down for fine convergence.

QAre local minima a problem in deep learning?Answer it out loud first, then open this

Much less than the textbook picture suggests. In very high dimensions a critical point must curve upward in every direction to be a local minimum, which is exponentially unlikely — so nearly all critical points are saddles. Momentum and mini-batch noise get you off saddles. The real practical problems are plateaus, ravines and a badly chosen learning rate.

Before you move on

Recall beats re-reading, every time. Answer before you flip.

Gradient descent · self-test1 / 3

Your loss goes to NaN after 50 steps. First three things you check?

Go to the primary sources

Where each claim above comes from. Open them alongside the lesson rather than after it — the papers are shorter than you think, and the figures usually carry the whole argument.

Paper
  • Adam: A Method for Stochastic Optimization(2014)Kingma & BaThe original. Algorithm 1 on page 2 is short enough to read in full and is worth reading in full.
Watch
  • Gradient descent, how neural networks learn (Chapter 2)3Blue1BrownThe loss-surface visualisation that makes 'step against the gradient' physical rather than symbolic.
  • Stochastic Gradient Descent, Clearly ExplainedStatQuest with Josh StarmerTen minutes on why we stopped using the full dataset per step, worked through with actual numbers.
Read
  • Why Momentum Really WorksGoh, DistillInteractive, rigorous and genuinely beautiful. Drag the momentum and learning rate and watch the optimisation path change under you.
  • A Recipe for Training Neural NetworksAndrej KarpathyThe debugging methodology. "Neural net training fails silently" — read this before your first real training run, not after it.
Docs
  • Neural Networks Part 3: Learning and EvaluationStanford CS231nThe practical chapter: learning-rate diagnostics from the shape of the loss curve, schedules, and what a healthy run looks like.

External links open in a new tab. Every URL was reachable when this page was written; links rot, so treat the list as a map rather than a guarantee.

Got it? Tick it off — progress saves on this device.

← PreviousMeasuring wrongnessNext →Backpropagation
Step downhill — but how far?step 0
local minimumglobal minimumthe humpslope -3.31parameter w →loss ↑
Optimiser
press Run to plot the loss curve
Current gradient is -3.307, so the next step moves w by 1.654. Notice the step size shrinks automatically as the slope flattens — you don't need a schedule to slow down near a minimum, though a schedule helps you get there without oscillating.

The gradient tells you which way is uphill; the learning rate decides how far you commit. Every training failure you will ever debug lives somewhere on these two sliders.

Step downhill — but how far?step 0
local minimumglobal minimumthe humpslope -3.31parameter w →loss ↑
Optimiser
press Run to plot the loss curve
Current gradient is -3.307, so the next step moves w by 1.654. Notice the step size shrinks automatically as the slope flattens — you don't need a schedule to slow down near a minimum, though a schedule helps you get there without oscillating.

The gradient tells you which way is uphill; the learning rate decides how far you commit. Every training failure you will ever debug lives somewhere on these two sliders.