AI Compass
Compass

Gradient descent

The algorithm that trains practically every modern model: what one step does, why batches are needed, and how to recognise a broken training run.

·2 min read·By Fachredaktion Technik
DETAIL
3 sections

The idea

The model makes a prediction, compares it with the right answer, and shifts its parameters a little in the direction that reduces the error. That is the whole algorithm. Everything else is a variation on those three steps.

What it is good for

It is why models with billions of parameters are trainable at all: you never have to try every possibility, only follow the local slope.

The three variants

VariantBatch sizeProperty
Full-batchall dataSmooth but very expensive per step
Stochastic (SGD)1Very noisy, rarely sensible
Mini-batch8 to 4096The normal case, a good compromise

A complete training loop by hand

import numpy as np
rng = np.random.default_rng(0)

X = rng.normal(size=(500, 3))
w_true = np.array([2.0, -1.0, 0.5])
y = X @ w_true + rng.normal(0, 0.1, 500)

w, lr, batch = np.zeros(3), 0.05, 32
for epoch in range(30):
    idx = rng.permutation(500)                 # shuffling each epoch matters:
    for start in range(0, 500, batch):         # otherwise the model learns
        b = idx[start:start + batch]           # the ordering as well.
        pred = X[b] @ w
        grad = 2 * X[b].T @ (pred - y[b]) / len(b)
        w -= lr * grad
    if epoch % 10 == 0:
        print(epoch, np.round(w, 3), round(float(((X @ w - y) ** 2).mean()), 5))

Diagnosis from the loss curve

  • Loss falls then flattens: healthy.
  • Loss jumps sharply: lower the learning rate or raise the batch size.
  • Loss falls, validation rises: overfitting, see regularisation.
  • Loss stays flat: learning rate too small, data badly scaled, or no gradient flowing.
  • Loss turns NaN: number format or missing gradient clipping.

The update rule

Mini-batch gradient descent

θ ← θ − η · (1/|B|) · Σ_{i∈B} ∇θ L(f(xᵢ; θ), yᵢ)

The parameters move by the learning rate times the mean gradient over the mini-batch.

θ
the parameters
η
the learning rate
B
a mini-batch of size |B|
L
the per-example loss

Why noise helps

A mini-batch gradient is an unbiased estimator of the full gradient with variance proportional to 1/|B|. That noise acts like a temperature: it keeps the system out of narrow, deep minima. Empirically, wide minima generalise better, which is why an overly large batch without a learning-rate adjustment measurably degrades test scores.

The usual remedy is the linear scaling rule: double the batch, double the learning rate, with a warmup over the first few hundred steps. Beyond roughly 8,000 examples per batch the rule stops holding.

Schedules

ScheduleShapeUsed for
ConstantunchangedShort runs, debugging
Step×0.1 every k epochsClassical image classification
Cosinesmoothly to zeroLanguage models, today's default
One-cycleup then downFast fine-tuning

Cosine with warmup is effectively standard for transformers: the first 2 to 5 percent of steps raise the rate linearly, after which it follows a cosine arc down to nearly zero.

Related courses and sources

PaperFreeEN

Adam

The optimiser practically every network today is trained with. Short and readable.

Short and readable; the optimiser practically every network today is trained with.

CoursePartly free5400 minEN

Machine Learning Specialization

Andrew Ng's course in its reworked form. Regression, classification, neural networks and the mistakes that actually happen in practice. The maths is included.

Free to audit; the certificate costs. If you only want to understand it, you do not need one.

DeepLearning.AIGo to offer
VideoFree150 minEN

Neural networks, explained visually

From a single weight through gradient descent to the attention mechanism. The best available intuition for what the formulas describe.

Watch it before your first textbook, not after. It saves weeks of confusion.

3Blue1BrownGo to offer
ToolFreeEN

TensorFlow Playground

A neural network in the browser with sliders for layers, activation and learning rate. You see in seconds what each knob does.

For anyone who wants to see what learning rate, layers and activation actually do.

Was this page helpful?
Gradient descent