jaxverse
Contents

jaxverse

A little universe of learning machines, designed and built by Neo Mohsenvand.

Prologue · Optimization · ≈10 min

The Descent

Learning is falling downhill on a landscape of error. Meet the loss surface, the gradient, and the little step rule the rest of this book repeats.

Strip any learning machine down — the ones that read handwriting, the ones that talk — and you find a function with knobs. The knobs are numbers called parameters, written θ\htmlClass{eq-model}{\theta}, and turning them changes what the function computes. Feed it an example, compare what it produced with what you wanted, and you can score the disagreement with a single number. That number is the loss, written L(θ)\mathcal{L}(\htmlClass{eq-model}{\theta}) — the machine's whole report card, one value that says how wrong its current knobs are.

Framed this way, learning stops being a mystery and becomes a landscape. Give every knob its own axis and add one more for the loss: each possible setting of the machine is a point on a surface, bad settings up on the ridges, good ones down in the valleys. Learning is descending that surface. One rule does the descending, and the rest of this book repeats it like a heartbeat:

θt+1  =  θt    ηL(θt)\htmlClass{eq-model}{\theta_{t+1}} \;=\; \htmlClass{eq-model}{\theta_t} \;-\; \htmlClass{eq-knob}{\eta}\,\htmlClass{eq-world}{\nabla \mathcal{L}(\theta_t)}

Read it term by term. The gradient L(θt)\htmlClass{eq-world}{\nabla \mathcal{L}(\theta_t)} is a list with one entry per knob: nudge this knob up, it says, and the loss rises by this much. Taken together the entries point in the direction of steepest ascent — the quickest way to make things worse — which is exactly why the rule subtracts them. The learning rate η\htmlClass{eq-knob}{\eta} sets the stride: how far to trust each reading of the slope before stopping to feel the ground again. The direction is the world's to give; the stride is yours to choose. There is nothing else in the rule. (Other books write that stride α\alpha, and some write γ\gamma. This one keeps η\htmlClass{eq-knob}{\eta} throughout, because γ\gamma has a different job waiting for it in Chapter 6.)

All of it rests on one requirement, and that requirement is the premise the rest of this book is built on. The walker is blind: no map, no view of the valley, only the tilt of the ground directly under its feet. If the landscape had cliffs and teleports — if a whisker of change in some knob could throw the loss anywhere at all — that local tilt would tell it nothing, and no amount of walking would help. So we build our machines entirely from smooth parts, arranged so the loss turns gently whenever a knob turns: the landscape is differentiable, and that is the price of admission. On smooth ground, a blind walker feeling only the slope beneath its feet can find its way down a landscape it will never see.

Five walkers, one landscape

Below is a real loss surface, drawn the way a hiker would draw it: contour lines join settings of equal loss, and the shaded pools mark the basins. Five walkers run the update rule on it, each with its own temperament — plain gradient descent, the bare rule and nothing more; momentum1 , which keeps a running average of its recent gradients; Adam2 , which gives every knob its own step size; and, off by default, AdamW3 and Lion4 . Click anywhere on the map to drop all of them there at once, and flip the view to 3-D to see the terrain the contours are describing. One dial drives all five: each walker's stride is pre-scaled to its temperament, because the raw-gradient pair barely move at a η\htmlClass{eq-knob}{\eta} the adaptive pair finds comfortable.

Plate I The descent race t = 0 · η = 0.050
Gradient descent 0.608 Momentum 0.608 Adam 0.608
0.050
Five walkers, one landscape, the same gradient at every point — only the rule for taking the step differs; three run by default and the legend switches the other two on. Click anywhere to drop them all there together: on the saddle's ridge, plain descent stalls where the ground flattens, momentum coasts through on stored velocity, and Adam's per-coordinate stride shrugs the geometry off. Raise η until somebody overshoots; flip to 3-D and drag to see the terrain the contours were hiding.

Reading the race

Choose the ravine and the temperaments separate within seconds. Its walls are steep and its floor is nearly flat, so the gradient points almost entirely across the trench: plain descent zigzags wall to wall, each step mostly undoing the last, and only creeps toward the minimum. Momentum averages its recent steps, so the wall-to-wall part cancels itself out while the along-the-floor part quietly accumulates — it ends up surfing the very trench it was bouncing across.

Adam keeps a second running average — the typical size of the gradient, tracked separately for each knob — and divides by it. Steep directions get reined in, flat ones get amplified, and every axis ends up moving at a steady walking pace; that is why Adam strides along the ravine's flat floor where plain descent crawls.

Neither half of Adam was new. AdaGrad5 had already given every parameter its own step size by dividing through by the gradients it had seen so far — but it added those up forever, so the steps shrank toward nothing and training ground to a halt. RMSProp6 fixed that by making the average forgetful: recent gradients count, old ones fade. Adam is RMSProp with momentum bolted on and a small correction for the opening steps, when an average that started at zero has almost nothing to average yet.

The opt-in pair are variations. AdamW adds weight decay, a constant gentle pull toward small parameters — watch it settle deliberately short of where Adam does. The name marks a finer point than it looks: adding a penalty on large weights to the loss and shrinking the weights directly are the same operation for plain descent, and are not the same operation once Adam divides by the gradient's typical size, which had quietly been weakening the penalty exactly where gradients were loud. Lion discards magnitude altogether and steps a fixed η\htmlClass{eq-knob}{\eta} along the sign of its momentum, which makes it quick off the mark and restless at the bottom, dancing in place forever.

Now break it. Raise η\htmlClass{eq-knob}{\eta} and watch Adam begin to ring across the basin instead of settling into it; raise it further and plain descent and momentum are flung off the map entirely — the ledger under the field reads diverged, and it means precisely what it says: the step outran the valley it was measuring. Notice whose knob that was. Nobody learned η\htmlClass{eq-knob}{\eta}; you chose it. It is a hyperparameter — a knob about the knobs — and it matters enough to deserve a landscape with nothing else in it.

One dimension, three fates

On the parabola L(θ)=θ2\mathcal{L}(\htmlClass{eq-model}{\theta}) = \htmlClass{eq-model}{\theta}^2 the gradient is 2θ\htmlClass{eq-world}{2\theta}, and the update rule collapses into a single multiplication:

θt+1  =  θtη2θt  =  (12η)θt\htmlClass{eq-model}{\theta_{t+1}} \;=\; \htmlClass{eq-model}{\theta_t} - \htmlClass{eq-knob}{\eta}\cdot \htmlClass{eq-world}{2\theta_t} \;=\; \bigl(1 - 2\htmlClass{eq-knob}{\eta}\bigr)\,\htmlClass{eq-model}{\theta_t}

Every step multiplies θ\htmlClass{eq-model}{\theta} by the same factor, so the walker's fate hangs on whether 12η\lvert 1 - 2\htmlClass{eq-knob}{\eta} \rvert is smaller than one. Keep η\htmlClass{eq-knob}{\eta} below 0.5 and the factor is a gentle fraction: the ball slides down its own side of the bowl. At 0.5 the factor is zero — the bottom, in one step. Past 0.5 each step overshoots the minimum and lands on the far side, still lower than before; past 1.0 the factor outgrows one, and every bounce carries the ball higher than the last. Feel all three with the dial, then try the other two curves: a double well, where a bold η\htmlClass{eq-knob}{\eta} hops the ball between two valleys, and θ\lvert\htmlClass{eq-model}{\theta}\rvert, whose kink never lets the steps shrink — a first taste of why smoothness was the price of admission.

That threshold is not a quirk of this parabola. Close enough up, every smooth valley looks like one, and the number that decides the fate of the step is how fast the slope itself changes — the sharpness of the tightest direction. Gradient descent holds together while the stride stays under two divided by that sharpness, and flies apart above it, just as the bowl did at η=1\htmlClass{eq-knob}{\eta} = 1.

Which makes what real networks do with that rule genuinely odd. Train one by gradient descent and it does not find a gentle valley and settle in. The sharpness along its path climbs — the ground it chooses keeps getting tighter — until it reaches almost exactly the largest value the chosen stride can survive. And then it stays there, balanced on the threshold for the rest of the run, the loss coming down in a slow sawtooth rather than a smooth glide.7 The step size is not only a setting you tune to fit the landscape. It decides which landscape you end up on.

Plate II Too big, too small step 0 of 30
-101θ 1e-61e-41e-2step30
η = 0.15 η = 0.45 η = 0.80 η = 1.05
Four step sizes let down the same slope together, from the same start, so the difference is the picture rather than something to remember between two settings of a dial. On θ² a step is θ ← (1 − 2η)θ, and that one number decides everything: at η = 0.15 it multiplies θ by 0.70 each time and the ball closes in from one side; at 0.45, by 0.10, and it is essentially there in one move; at 0.80, by −0.60, so it crosses the bottom every step and still closes; at 1.05, by −1.10, and each crossing lands further out than the last. The chart underneath is the same four runs as height above the floor of the valley, on a log axis, where a constant multiplier is a straight line — so each step size is a slope, and the one that diverges is the slope pointing the wrong way. Switch landscapes and the same four steps sort themselves differently. On the double well the two small steps settle into whichever valley they were dropped beside, 0.80 is bold enough to cross into the other one, and only 1.05 leaves the frame — a bigger step is not simply worse, it is a different search. On |θ| the slope never softens as you approach the bottom, so the step never shrinks either: all four stride back and forth across the kink forever, and not one of the four lines ever reaches the floor.

The picture is honest

A fair objection: real models do not have two knobs. The first network you will train has a few hundred; the model that plays chess in Chapter 8 has 1.3 million; the models in the news have billions. Nobody can draw those landscapes. But nothing on this page was a cartoon of the algorithm — the rule you have been racing is, line for line, the rule they all train by, and in the next chapter you will watch this same subtraction sculpt a real neural network, live, as you read.

Two things do change on the way up.

The first is noise. Every gradient on this page was exact: the landscape is a formula, so the slope at a point can simply be computed. No real training run can afford that. The loss is an average over millions of examples, and evaluating all of them to take one step would be absurd, so the gradient is estimated from a few dozen examples at a time and every reading of the ground is slightly wrong. That is the S in SGD, and the licence for it is older than neural networks: Robbins and Monro showed in 19518 that a walker stepping on noisy estimates still converges, provided its steps shrink neither too fast nor too slowly. The noise is not a cost to be tolerated. A rough gradient is a cheap gradient — a few dozen examples rather than a few million — so the same compute buys thousands of steps for the price of one, and the jitter shakes the walker off the first flat place it stumbles into. And that condition on shrinking steps is honoured to this day: a real run decays η\htmlClass{eq-knob}{\eta} on a schedule fixed before training starts — long strides early, when almost any direction is an improvement, short ones late, when the walker is placing its feet.9 Every plate in this book holds η\htmlClass{eq-knob}{\eta} still instead, so you can feel one number at a time.

The second is the shape of the ground. The picture of a walker stranded in a shallow valley, unable to see the deeper one next door, is the most repeated image in popular accounts of this subject, and in high dimensions it is very nearly a myth. For a flat spot to be a floor, the surface has to curve upward along every one of the model's directions at once, and with a million directions to agree that is an extraordinary coincidence. Almost every flat spot is a saddle instead — uphill in most directions, downhill in a few — and a walker carrying any momentum or any noise at all eventually finds one of the few.10 What actually costs a training run its time is not being trapped at the bottom of the wrong bowl. It is crawling across ground that is nearly level in almost every direction at once.

Plate III The two kinds of flat
a floor
every direction curves up
a saddle
one of them curves down

both patches turn on their own; drag to steer them

Two patches of ground, each perfectly flat inside the small ring painted at its centre, lit the same way and seen from the same angle. They differ by one sign. Left: the ground curves up whichever way you leave — a floor, and a walker that arrives there is staying. Right: it curves up along one axis and down along the other — a saddle, and a walker carrying any momentum or any noise will eventually find the way off. The heavy circle drawn on each patch is the loss one step out in every direction at once: level and entirely above the point on the floor, a wave that crosses the point's own height four times on the saddle, in ultramarine where the ground rises and vermilion where it falls. The dashed ring holds that height level, to judge the wave against. Now count directions. With two of them to agree, floors are easy to come by; with a million, a floor is an extraordinary coincidence, and almost every flat place a large network stalls at is the picture on the right.

Some of this can be checked directly. Take a network's random starting weights and its trained ones, draw the straight line between them in parameter space, and read the loss along it: it falls the whole way, with no ridge to climb over.11 Training does not walk that line — the route it takes is long and curved — but the fact that a straight one exists tells you the terrain is kinder than the cartoon. And when you do meet a rendered picture of a loss surface, ridges and basins and all, remember what it is: a two-dimensional slice through something with a million axes, whose apparent ruggedness depends on how the slice was scaled.12

What survives once the picture is gone is the curve. In a million dimensions the landscape is invisible, but the walker's altitude is still a single number at every step, and plotting it against tt gives the training loss curve — the landscape's shadow. Every chapter ahead shows you that curve while its model trains. When you see it fall, stall on some plateau, then find a way down again, you will know what you are watching edge-on: a ball, a valley, a rule.

That is the whole trick, and you have now held every part of it: a smooth function, a score for wrongness, and a walk downhill taken one step at a time. Everything from here on — telling digits apart, drawing a map of meaning, learning chess from a rulebook nobody showed it — is this same walker, set loose on richer ground.

Sources

  1. 1 Some methods of speeding up the convergence of iteration methods Polyak · 1964 · USSR Computational Mathematics and Mathematical Physics 4(5) · mathnet.ru Momentum, as a heavy ball rolling on the surface rather than a walker stepping on it.
  2. 2 Adam: A Method for Stochastic Optimization Kingma & Ba · 2015 · ICLR 2015 · arXiv:1412.6980 Momentum and RMSProp in one update, with a bias correction for the first few steps.
  3. 3 Decoupled Weight Decay Regularization Loshchilov & Hutter · 2019 · ICLR 2019 · arXiv:1711.05101 AdamW. The finding is subtler than its fame: weight decay folded into the gradient is not the same thing as weight decay applied to the weights, and for Adam the difference is large.
  4. 4 Symbolic Discovery of Optimization Algorithms Chen et al. · 2023 · NeurIPS 2023 · arXiv:2302.06675 Lion, found by a program search over update rules rather than derived by hand.
  5. 5 Adaptive Subgradient Methods for Online Learning and Stochastic Optimization Duchi, Hazan & Singer · 2011 · JMLR 12 · jmlr.org AdaGrad — the first widely used optimizer to give every parameter its own step size, scaled by the gradients it has seen so far.
  6. 6 Lecture 6.5 — RMSProp Tieleman & Hinton · 2012 · COURSERA: Neural Networks for Machine Learning · cs.toronto.edu RMSProp was never written up as a paper. It was slide 29 of a lecture, and half the field adopted it anyway.
  7. 7 Gradient Descent on Neural Networks Typically Occurs at the Edge of Stability Cohen et al. · 2021 · ICLR 2021 · arXiv:2103.00065 Full-batch gradient descent does not settle into a curvature it can handle. It climbs until the curvature is exactly as sharp as its step size can survive, and then stays there, half-unstable, for the rest of training.
  8. 8 A Stochastic Approximation Method Robbins & Monro · 1951 · Annals of Mathematical Statistics 22(3) · projecteuclid.org The proof that you may take your steps from noisy estimates of the slope and still arrive, if the steps shrink at the right rate. Every minibatch since is a corollary.
  9. 9 SGDR: Stochastic Gradient Descent with Warm Restarts Loshchilov & Hutter · 2017 · ICLR 2017 · arXiv:1608.03983 Where the shape of almost every modern schedule comes from: walk the stride down a cosine from its starting value toward nothing, then — the paper's actual proposal — jump it back up and do it again. The cosine was adopted everywhere. The restarts, mostly not.
  10. 10 Identifying and attacking the saddle point problem in high-dimensional non-convex optimization Dauphin et al. · 2014 · NeurIPS 2014 · arXiv:1406.2572 The argument that the folk fear of local minima is misplaced: in many dimensions, the flat places a walker gets stuck at are overwhelmingly saddles, not basins.
  11. 11 Qualitatively characterizing neural network optimization problems Goodfellow, Vinyals & Saxe · 2015 · ICLR 2015 · arXiv:1412.6544 Walk the straight line from a network’s starting weights to its trained ones and the loss falls the whole way. The path training takes is not straight, but it never has to cross a wall.
  12. 12 Visualizing the Loss Landscape of Neural Nets Li et al. · 2018 · NeurIPS 2018 · arXiv:1712.09913 What a real loss surface looks like once you slice it honestly — and how much of its apparent shape is an artifact of how you scaled the slice.