How an LLM Learns, Step by Step

October 7, 2026 · llms · machine learning

Training a language model is one game played trillions of times: cover up the next word, guess it, measure how surprised you were, and adjust. Everything else, tokens, attention, gradient descent, RLHF, is machinery that makes that game work at scale.

People talk about training like it is magic or like it is just math. It is neither. It is a very large, very patient student doing fill-in-the-blank quizzes, checking the answer key, and nudging its brain a tiny bit after every single question. Do that a few trillion times and the guessing starts to look like thinking.

This post walks through every step, and every step has something you can touch. Type into the tokenizer. Poke the attention weights. Break gradient descent with a bad learning rate on purpose. By the end you will have run a miniature version of the whole pipeline in your browser.

1. The model never sees words. It sees tokens.

Before training starts, all text gets chopped into pieces called tokens. A token can be a whole common word ("the"), a chunk of a word ("ing"), or a single character. The model has a fixed vocabulary, usually 50,000 to 200,000 tokens, and everything it ever reads or writes is built from those pieces.

Why not just use words? English has over a million of them, and new ones appear daily. Tokens are the compromise: common words get their own token, rare words get split into pieces. The splits are learned from data by an algorithm called BPE (byte pair encoding): start with single characters, then repeatedly merge the most common adjacent pair, until the vocabulary is full.

The tokenizer, live

A toy tokenizer with a tiny vocabulary, using the same greedy longest-match idea as the real ones. Type anything and watch it chop. Spaces stick to the word after them, like real tokenizers do.

0 tokens 0 chars per token

Try a rare word like "flibbertigibbet" and watch it shatter into pieces. Common words survive whole because the vocabulary was built from what appears most.

Two details that matter later. First, every token becomes an ID number, and the model only ever works with those numbers. Second, token counts are the currency of the whole field: context windows, pricing, and training budgets are all measured in tokens, not words. A rough rule: 1 token is about 3/4 of an English word.

2. Tokens become lists of numbers

A token ID is just a label. The model needs something it can do math on, so each token gets an embedding: a list of a few hundred or thousand numbers, its coordinates in meaning-space. These numbers start random. Training moves them around until words used in similar ways end up near each other.

Tap two words below. The strip shows one's embedding as colors (darker blue means a bigger number). The similarity score is the cosine similarity: 1 means pointing the same way, 0 means unrelated, and the model literally uses this geometry to reason.

Word vectors you can poke

Toy 10-number embeddings, hand-made to show the idea. Tap any word, then tap a second one to compare.

Tap two words

Real embeddings have thousands of numbers and are learned, not hand-made. But the trick is the same: meaning becomes geometry, and similar meanings sit near each other.

3. Tokens look at each other: attention

Here is the famous part. A word's meaning depends on context, so before the model decides anything, every token gets to look at every other token and pull in information. That is attention: for each token, a set of weights saying how much each other token matters right now.

The classic example: "The animal did not cross the street because it was too tired." What does "it" refer to? The model learns to point "it" back at "animal". Tap a word in the sentence and see where its attention goes. These weights are illustrative, but the mechanism is exactly the real one: weighted mixing, recomputed fresh for every word in every sentence.

Attention, under your finger

Tap any word. The bars show how much of each other word gets mixed into it.

Real models run many attention heads in parallel, each learning a different kind of relationship: grammar, coreference, position, and patterns with no English name. This demo shows one head's job.

One more detail: attention is why these models are called transformers. The architecture is stacks of identical blocks, and each block is mostly "attention, then a small neural net, repeated." A big model just stacks that block 100 times.

4. The only game: predict the next token

After attention and the small neural nets (called MLPs) have done their mixing, the model outputs a score for every token in its vocabulary: how likely is each one to come next? Those scores are called logits, and they get squashed into probabilities that sum to 1 by a function called softmax.

Training is one repeated quiz: hide the next token, make the model guess, then score it. The score is the loss, and for this game it has a beautifully simple form called cross-entropy: negative log of the probability the model gave to the correct answer. Gave the truth 72%? Loss is small. Gave it 6%? Loss is large. The model's whole education is "be less surprised, on average, over trillions of quizzes."

The surprise meter

Pick a quiz. The bars are the model's guesses. Reveal the truth to see how surprised it was, then take a training step and watch the surprise shrink.

Surprise (loss) ?
Reveal the truth to measure the surprise.

Cross-entropy loss = -log(probability given to the correct token). A real training step nudges millions of weights using calculus. This demo just nudges the probabilities directly, but the effect is the same: the truth gets less surprising.

From scores to probabilities: softmax

The model does not output probabilities. It outputs raw scores, called logits. Softmax turns raw scores into probabilities that add to 100%: bigger score, bigger slice. Drag the scores and watch.

All slices add up to 100%

Which word is actually correct?

Loss: how much probability went to the right word ?

Softmax: each probability = e^(score) / sum of e^(score) over all words. Subtracting the biggest score first keeps the exponentials small; that is the log-sum-exp trick behind log-softmax. Log space keeps the math stable: computers add logs safely, but multiplying thousands of tiny probabilities would round to zero. Loss = -log(probability of the correct word), in nats.

5. Learning is rolling downhill

So the model gets a loss score on every quiz. How does it improve? Every weight in the model gets a tiny adjustment in the direction that would have lowered the loss. Computing those directions for millions of weights at once is backpropagation: the chain rule from calculus, applied mechanically, layer by layer, backwards through the network.

Then comes gradient descent: move each weight a little bit downhill. The size of the step is the learning rate, and picking it is the oldest drama in machine learning. Too small and training crawls. Too big and the model bounces around or blows up entirely. Try it below. This is a one-weight model on a simple valley, but the rule is identical in 100 billion dimensions.

Break gradient descent on purpose

One weight, one valley. Set the learning rate, then run and watch the loss.

Top: the valley and the weight rolling in it. Bottom: loss over time, log scale. Real training uses fancier optimizers (usually Adam), but they are all downhill-rolling with better shock absorbers.

Step 0 · loss 10.24
Press Run. A learning rate around 0.4 glides to the bottom.
Real training does not update after every quiz. It averages the gradient over a batch, thousands of quizzes at once, then takes one step. Smoother signal, and GPUs love doing the same math on many examples in parallel.

6. Why scale wins

Here is the uncomfortable truth the field learned around 2020: the same algorithm, just bigger, keeps getting smarter. Bigger model, more data, more compute. The scaling laws say loss falls predictably as you scale any of the three, which is why training runs now cost tens of millions of dollars.

The sharpest version of this is Chinchilla (DeepMind, 2022). For a fixed compute budget, the best results come from splitting it evenly: half on a bigger model, half on more training data. The rule of thumb that fell out: train on about 20 tokens per parameter. Drag the slider and feel the numbers.

The Chinchilla slider

Pick a model size. The readouts follow the 20-tokens-per-parameter rule, with compute estimated as 6 × parameters × tokens.

1.4T
training tokens (Chinchilla-optimal)
5.9e23
FLOPs of training compute
10.8M
books of text, roughly
?
vs a famous model

GPT-3 (175B params) trained on only 300B tokens, far below its Chinchilla-optimal ~3.5T. It was undertrained by this rule, which is part of why smaller, longer-trained models like Chinchilla beat it. Token counts are approximate public figures.

How much compute? Famous training runs

Training compute follows a simple rule: about 6 x parameters x tokens. Each token costs roughly 2 FLOPs per parameter on the way forward (making the guess) and 4 on the way back (computing the lesson). Tap a row for details. Every figure below is approximate.

Tap a model to see how its number was estimated.

All figures are approximate. "Paper" means computed from the published paper. "Disclosed" means computed from numbers the lab published. "Reported" means computed from credible press reports. "Rumored" means an estimate with no official confirmation. For MoE models like DeepSeek-V3, the rule uses active parameters per token, not total parameters.

7. Three stages: pretrain, fine-tune, RLHF

Next-token prediction on internet text produces a model that can continue text, but it is not an assistant. It will happily continue your question with another question. Turning it into something helpful takes two more stages. Tap each one.

From text predictor to assistant

Three stages, three datasets, three objectives. Each one builds on the last.

1Pretraining

The long, expensive part.

2Fine-tuning

Teach it to follow instructions.

3RLHF

Teach it human preferences.

Modern RLHF is often closer to plain reinforcement learning on verifiable rewards (math, code tests) than to the original human-feedback recipe, but the three-stage shape is the same.

8. Picking the word: temperature and top-p

Training is over. Now you ask a question and the model must actually choose a token. It has probabilities, not a decision procedure, so generation is sampling: roll a weighted die, append the word, repeat. Two knobs control the personality of that die.

Temperature sharpens or flattens the distribution before sampling. Near zero, the top choice always wins: boring, safe, deterministic. High, and unlikely words start winning: creative, weird, unhinged. Top-p (nucleus sampling) chops off the long tail entirely: only sample from the smallest set of words whose probabilities add up to p.

The sampling sandbox

A toy 8-word vocabulary after "The cat sat on the". Set the knobs, then sample and watch which words survive.

The cat sat on the

Greyed-out words were cut by top-p. Real models sample from 50k+ tokens, so top-p matters even more there: it throws away the junk tail before the die is rolled.

It never understands. It just gets less surprised, trillions of times, until the guessing looks like thinking.