If you’ve written a Kubernetes controller, you already understand the most important algorithm in machine learning.
A controller reads desired state, reads observed state, computes the gap, and takes one step to close it. Then it does it again, forever, without trusting that its last step worked. Training a model is the same loop. The desired state is your data. The observed state is what the model predicts. The gap is the loss. The step is a nudge to every parameter, in whichever direction makes the loss smaller.
The only new idea is how you pick the direction. A controller knows that three replicas minus two means “create one Pod”. A model with eight billion parameters has no such rule, so it uses calculus to ask each parameter: if I nudge you up, does the error grow or shrink, and how fast? That answer is the gradient. Everything else is bookkeeping.
Here it is in forty lines with nothing but the standard library.
The whole algorithm
The model is a straight line, y = w·x + b. I generate 200 points from a line I pretend not to know (w = 3, b = 2) and add a little noise. Training has to discover those two numbers starting from zero.
"""Gradient descent from scratch: fit y = w*x + b with nothing but the standard library."""
import random
random.seed(7)
# Synthetic data: the "desired state" is a line we pretend not to know (w=3, b=2), plus noise.
XS = [random.uniform(0, 1) for _ in range(200)]
YS = [3.0 * x + 2.0 + random.gauss(0, 0.1) for x in XS]
def loss(w, b):
"""Mean squared error: how far the model's predictions are from the data."""
return sum((w * x + b - y) ** 2 for x, y in zip(XS, YS)) / len(XS)
def grad(w, b):
"""Analytic partial derivatives of the loss with respect to w and b."""
n = len(XS)
dw = sum(2 * (w * x + b - y) * x for x, y in zip(XS, YS)) / n
db = sum(2 * (w * x + b - y) for x, y in zip(XS, YS)) / n
return dw, db
def train(lr, steps, log_every=None):
w, b = 0.0, 0.0 # start from nothing
for step in range(steps + 1):
if log_every and step % log_every == 0:
print(f" step {step:4d} loss {loss(w, b):10.4f} w {w:7.3f} b {b:7.3f}")
dw, db = grad(w, b) # observe: which way is downhill?
w -= lr * dw # act: one small step that way
b -= lr * db
return w, b
print("1. Train with learning rate 0.5")
w, b = train(lr=0.5, steps=200, log_every=40)
Three functions. loss is the diff: square each prediction’s error so that misses in either direction count, then average. grad is the direction, derived by hand from the loss with the chain rule. train is the loop. The two lines that start with w -= and b -= are the entire “learning” in machine learning.
1. Train with learning rate 0.5
step 0 loss 12.3935 w 0.000 b 0.000
step 40 loss 0.0118 w 2.916 b 2.045
step 80 loss 0.0112 w 2.996 b 2.005
step 120 loss 0.0112 w 3.000 b 2.002
step 160 loss 0.0112 w 3.000 b 2.002
step 200 loss 0.0112 w 3.000 b 2.002
By step 120 it has found w = 3.000 and b = 2.002. Then it stops improving, and the reason is worth a minute.
The loss has a floor, and the floor is the noise
The loss settles at 0.0112, not zero. I added noise with a standard deviation of 0.1 to every point, which means a variance of 0.01. No straight line can predict random noise, so the best possible mean squared error is about the noise variance. 0.0112 is that floor plus a little sampling luck.
This is the first habit to carry over from operations. A loss that stops falling isn’t always a bug. Sometimes it means the model has explained everything the data can explain, the same way an SLO can’t be better than the availability of the dependency underneath it. Before you tune anything, ask what the floor should be.
Check the gradient the way you’d smoke-test a deploy
A hand-derived gradient is code, and code has bugs. The standard check needs no calculus at all: nudge one parameter up and down by a tiny amount, measure how much the loss moves, divide by the size of the nudge. That’s a finite difference, and it should match the analytic gradient.
w0, b0, h = 1.0, 1.0, 1e-6
num_dw = (loss(w0 + h, b0) - loss(w0 - h, b0)) / (2 * h)
num_db = (loss(w0, b0 + h) - loss(w0, b0 - h)) / (2 * h)
an_dw, an_db = grad(w0, b0)
2. Check the analytic gradient against a finite difference
dL/dw analytic -2.161937 numeric -2.161937
dL/db analytic -3.874969 numeric -3.874969
Six matching decimal places. If I had dropped the * x in dw, this check would catch it immediately, while the training loop would still run and still produce numbers, just wrong ones. That’s the failure mode that makes gradient bugs nasty: nothing crashes.
You won’t write gradients by hand for real models. PyTorch and JAX compute them automatically by recording every operation in the forward pass and replaying the chain rule backwards (autograd, or “the backward pass”). But a finite-difference comparison is exactly how those gradient implementations are tested, and it’s the first thing to reach for when a custom layer misbehaves.
The learning rate is controller gain
Same data, same 200 steps, three learning rates:
for lr in (0.01, 0.5, 1.5):
w, b = train(lr=lr, steps=200)
print(f" lr {lr:<5} final loss {loss(w, b):10.4g} w {w:10.4g} b {b:10.4g}")
3. Same data, same steps, different learning rates
lr 0.01 final loss 0.1387 w 1.795 b 2.586
lr 0.5 final loss 0.01118 w 3 b 2.002
lr 1.5 final loss 7.305e+174 w 1.093e+87 b 2.172e+87
At 0.01 the steps are too small: after 200 of them the slope is 1.795, not 3. At 1.5 each step jumps past the minimum and lands higher up the opposite wall than where it started, so the error grows every iteration until the numbers are astronomically large. In a real framework, that’s the moment the loss turns into inf and then NaN, because floating point has run out of room.
If you’ve tuned a feedback controller, you’ve seen both. Low gain is sluggish. High gain oscillates, and past a certain point the oscillation grows instead of dying out. For a model this simple you can compute exactly where that point is, from the curvature of the loss surface:
n = len(XS)
a = 2 * sum(x * x for x in XS) / n # curvature of the loss: the Hessian of MSE
c = 2 * sum(XS) / n # [[a, c], [c, 2]]
tr, det = a + 2, a * 2 - c * c
lam_max = (tr + (tr * tr - 4 * det) ** 0.5) / 2
lam_min = (tr - (tr * tr - 4 * det) ** 0.5) / 2
print(f" steepest curvature {lam_max:.3f} -> diverges above lr {2 / lam_max:.3f}")
print(f" flattest curvature {lam_min:.3f} -> at lr 0.01, each step removes {0.01 * lam_min:.2%} of the remaining error")
4. Where the learning rate stops converging, computed from the data
steepest curvature 2.470 -> diverges above lr 0.810
flattest curvature 0.142 -> at lr 0.01, each step removes 0.14% of the remaining error
I checked the boundary by brute force: a learning rate of 0.80 converges to the noise floor, and 0.82 blows up to 1e45 within 2,000 steps. The math and the experiment agree.
The second line explains the slow run. The bowl is steep in one direction and nearly flat in another, so a step size that’s safe for the steep direction barely moves along the flat one. That tension (one learning rate, many directions with different curvature) is the whole reason optimisers like Adam exist. Adam keeps a running estimate of each parameter’s gradient scale and sizes each parameter’s step separately.
What changes when the model has eight billion parameters
Less than you’d expect. Compare this loop with the training loop in Karpathy’s nanoGPT train.py, a few hundred lines that train a GPT-2 class model. You’ll find the same four moves: compute the loss on a batch, call backward() on it to get the gradients, step the optimizer to move the weights, repeat. (It wraps both calls in a gradient scaler for fp16 training, which doesn’t change the loop.) Three things are different:
- Batches instead of the whole dataset. Computing the exact gradient over billions of tokens per step is unaffordable, so each step uses a random mini-batch. The gradient is noisier but far cheaper. That’s stochastic gradient descent.
- Autograd instead of a hand-written
grad. The framework derives the gradient for any composition of operations, which is what makes a transformer with hundreds of layers trainable at all. - Schedules instead of one learning rate. Large runs warm the learning rate up from near zero, then decay it. Warm-up avoids the overshoot you saw at 1.5 while the early gradients are large and erratic.
The loop itself, observe, diff, pick a direction, take one bounded step, never changes. Neither does the operational lesson: a control loop with the wrong gain either never arrives or tears itself apart, and both look like “it’s running” until you graph the error.
Run the script, then change the noise from 0.1 to 0.5 and watch where the floor moves. That one edit teaches more about what “the model stopped learning” means than any amount of reading.
Comments