The algorithms inside AI
Twelve algorithms do most of the work behind the AI you use: how a model learns, how it reads text, how it picks its next word and how it learns what people prefer. Each tile here runs one of them for real on a model small enough to read.
What you'll take away
- Follow a training step, backprop then gradient descent, and why too big a step flies off
- Explain how BPE cuts an unseen word and how attention weighs the tokens before it
- Tell greedy, beam search, top-k and temperature apart by how they pick words
- Know how RLHF turns people's picks between two answers into a reward
The 1-minute version
Tap a point and the picture below plays that step.
Step downhill along the slope, as far as the learning rate says
Gradient descent's loss won't come down; it swings further every step. What is the likely cause?
The picture: the city's AI quarter, one algorithm and one event a step. Classic machine learning works in the data yard (points are pins, k-means centres are posts, a tree's cuts are fences); gradient descent is a ball stepping down the loss, drawn as ground; backpropagation, dropout, the BPE tokenizer and attention run on the model hall's roof, with tokens as tiles and attention as lines as thick as their weight; the next-word board shows each word's chance as a bar; at the counter people compare answers. Every number comes from the code below; the data sets, the attention scores, the next-word table and the people's choices are made up for teaching. In BPE, _ marks the end of a word.
Compare them all: AI algorithms
One table of next words, four ways to write a sentence. Greedy goes round in circles; beam search finds the likeliest sentence, the same one every time; the two that draw write a new sentence each run.
Use it when Short answers that must be the same every time, like pulling fields out as JSON or picking a category
Skip it when Long text: it can go round in circles, since it never looks past the next word
The table of next words is made up for the picture. The drawn sentences use this page's random numbers (seed 4), and "5 runs" counts the different sentences from seeds 1 to 5. A real model has tens of thousands of words, but the rules for picking are the same. Press any tile to see it large above, with when it fits.
Twelve algorithms and where you meet them
| Algorithm | The idea | Where you meet it |
|---|---|---|
| k-means | Grouping: move each centre to the middle of its points, again and again | Grouping customers; boiling a picture down to a few colours |
| k-nearest neighbours | A new point takes the label of its k nearest neighbours | Recommendations, and search over embeddings (finding the nearest neighbours) |
| Decision tree | Try every threshold, keep the one whose two sides are least mixed | Tables of data: risk scores, fraud checks, usually as forests or gradient boosting |
| Gradient descent | Step downhill along the slope, as far as the learning rate says | Training every neural network (as SGD, Adam) |
| Backpropagation | Values forward, gradients backward, then nudge the weights | Training every neural network, LLMs included |
| Dropout | While training, switch random units off; in use, all on | Training many networks; the original Transformer used 0.1 |
| BPE (the tokenizer) | Merge the most common neighbouring pair into one piece, again and again | The tokenizers of many LLMs (GPT-2's is byte-level BPE) |
| Attention | Each token asks which tokens to look at; softmax gives the weights | Every transformer: LLMs, ViT, Whisper |
| Softmax + temperature | Scores into probabilities; temperature sharpens or flattens them | The last step of every LLM, and of classifiers |
| Top-k / top-p | Cut off the unlikely tail, then draw from what is left | The top_k and top_p settings of model APIs and libraries |
| Beam search | Keep the few most likely sentences so far, not just one | Translation and speech recognition |
| RLHF: preferences | People compare answers in pairs; a reward follows, and the model leans towards it | Tuning chat assistants towards answers people prefer (InstructGPT) |
How a model learns
Training is a loop: run the examples through the model, measure how wrong it is (the loss), let backpropagation work out how the loss moves with every weight, and let gradient descent step each weight the other way. The learning rate sets the step: too small and training crawls, too big and it overshoots and flies off. Dropout switches random units off during training so no unit can lean on another, and switches nothing off in use.
Picking the next word
A language model gives every word a score; softmax turns the scores into probabilities and temperature sharpens or flattens them. Then a rule picks. Greedy takes the likeliest word every time and can go round in circles; beam search keeps several sentences and finds the likeliest one; top-k and top-p cut off the unlikely tail and draw from the rest, which is what most chat apps do.
Learning from preferences
People are better at choosing between two answers than at writing a score. RLHF collects those choices, fits a reward model to them (Bradley-Terry: the chance one answer wins is the sigmoid of the difference in reward), and then tunes the model towards higher reward while a term weighted by β keeps it close to where it started.
In real code
# How a model learns, on models small enough to check by hand.
# 1. Gradient descent: walk downhill on a loss. Here the loss is (w - 3)^2, so the best w is 3 and the slope is 2(w - 3).
# 2. Backpropagation: the chain rule, run backwards through a tiny network x -> h = w1*x -> y = w2*h -> loss = (y - t)^2,
# checked against nudging each weight a little (a finite difference).
# 3. Dropout: while training, switch off each unit with probability p and scale the rest by 1 / (1 - p), so the layer's
# output is the same on average; at inference time, switch nothing off.
# Run: python3 learning.py
import random
def descend(lr, steps=12, w=0.0):
path = [w]
for _ in range(steps):
w = w - lr * 2 * (w - 3) # step against the slope
path.append(w)
return path
for lr in (0.05, 0.15, 0.9, 1.05):
path = descend(lr)
print(f"learning rate {lr}: w after 12 steps {path[-1]:.2f}, loss {(path[-1] - 3) ** 2:.4f}")
assert abs(descend(0.15)[-1] - 3) < 0.05 # a good rate settles near 3
assert abs(descend(0.05)[-1] - 3) > 0.5 # too small: still on the way
assert abs(descend(1.05)[-1] - 3) > 9 # too big: every step overshoots further
def forward(w1, w2, x=2.0, t=3.0):
h = w1 * x
y = w2 * h
return h, y, (y - t) ** 2
def backward(w1, w2, x=2.0, t=3.0):
h, y, loss = forward(w1, w2, x, t)
dy = 2 * (y - t) # how the loss moves with y
dw2 = dy * h # y = w2 * h, so y moves with w2 by h
dh = dy * w2 # ... and with h by w2
dw1 = dh * x # h = w1 * x
return dw1, dw2
w1, w2 = 0.5, 1.5
h, y, loss = forward(w1, w2)
dw1, dw2 = backward(w1, w2)
eps = 1e-6
num_dw1 = (forward(w1 + eps, w2)[2] - forward(w1 - eps, w2)[2]) / (2 * eps)
num_dw2 = (forward(w1, w2 + eps)[2] - forward(w1, w2 - eps)[2]) / (2 * eps)
assert abs(num_dw1 - dw1) < 1e-6 and abs(num_dw2 - dw2) < 1e-6
lr = 0.05
w1, w2 = w1 - lr * dw1, w2 - lr * dw2
print(f"forward: h {h:g}, y {y:g}, loss {loss:g}; backward: dloss/dw2 {dw2:g}, dloss/dw1 {dw1:g} (a nudge agrees)")
print(f"one step at learning rate {lr}: w1 {w1:.2f}, w2 {w2:.2f}, loss {forward(w1, w2)[2]:.4f}")
assert (h, y, loss, dw2, dw1) == (1.0, 1.5, 2.25, -3.0, -9.0)
ACT = [0.8, 0.3, 0.6, 0.9, 0.2, 0.7, 0.5, 0.4]
def dropout(xs, p, rng):
return [0.0 if rng.random() < p else x / (1 - p) for x in xs]
rng = random.Random(7)
runs = 20000
mean = sum(sum(dropout(ACT, 0.5, rng)) for _ in range(runs)) / runs
print(f"dropout p 0.5: one pass {[round(v, 1) for v in dropout(ACT, 0.5, rng)]}; "
f"the sum over {runs:,} passes averages {mean:.2f}, the layer without dropout {sum(ACT):.1f}")
assert abs(mean - sum(ACT)) < 0.05
python3 learning.pyIt printed:learning rate 0.05: w after 12 steps 2.15, loss 0.7179 learning rate 0.15: w after 12 steps 2.96, loss 0.0017 learning rate 0.9: w after 12 steps 2.79, loss 0.0425 learning rate 1.05: w after 12 steps -6.42, loss 88.6476 forward: h 1, y 1.5, loss 2.25; backward: dloss/dw2 -3, dloss/dw1 -9 (a nudge agrees) one step at learning rate 0.05: w1 0.95, w2 1.65, loss 0.0182 dropout p 0.5: one pass [1.6, 0.6, 0.0, 1.8, 0.4, 0.0, 0.0, 0.8]; the sum over 20,000 passes averages 4.39, the layer without dropout 4.4
Gradient descent on (w − 3)² at four learning rates; one backward pass through a two-weight network, checked against nudging each weight; and inverted dropout, whose sum over 20,000 passes averages what the layer gives without it. Really run.
Common questions
What is the learning rate, and how is it set?
The size of gradient descent's step: a step is the learning rate times the slope. Too small is slow; too big and each step overshoots the bottom by more until it flies off. In practice people try several values, watch the loss, and often lower it during training. Turn the knob in the play tab.
How is backpropagation different from gradient descent?
Backpropagation finds the slopes: the chain rule, run back from the loss one layer at a time, gives how much each weight moves the loss. Gradient descent uses those slopes to take a step. The two work together on every round of training.
How is a token different from a word?
A token is a piece the tokenizer learned: a common word is one piece, a rarer one splits into several. BPE starts from letters and keeps merging the most common pair. On this page, lowest, never seen, is cut into low and est_.
How does attention give an LLM its context?
Each token scores every token before it by the dot product of its query and their keys, and softmax turns the scores into weights. What it gets is those tokens' values mixed by the weights; here, it reads cat at 70%. Done in every layer and every head, information spreads through the sentence.
Why does an AI answer the same question differently each time?
Because it draws its words: the model gives each next word a probability and the system draws by it, usually after cutting the tail with top-k or top-p. A low temperature or greedy decoding makes answers steadier, though long text may then repeat.
Why not use beam search for everything?
Beam search finds the likeliest sentence, which suits jobs with one right answer, like translation or speech-to-text. For open-ended writing the likeliest sentence tends to be bland and repetitive (Holtzman et al., 2019), so chat usually samples with top-p.
What is RLHF?
Reinforcement learning from human feedback: people compare the model's answers in pairs, a reward model learns to score the preferred ones higher, and the model is tuned towards higher reward without straying too far. DPO reaches the same target without training a separate reward model.
Is classic machine learning still used?
Every day. Decision trees (and forests of them) are a first choice for tables of data, k-means groups customers or colours, and nearest-neighbour search sits behind search over embeddings. They are fast, explainable and need no GPU.
Next lesson
Agent harnessLevel: Intermediate
A model picks one word after another; next, the loop around it that lets it act: tools, rules and a context to keep.