One token at a time
Every answer a language model gives is built the same way: read everything so far, score every possible next token, pick one, append it, repeat. This is a walk through that loop, from the characters you type to the characters that come back, with something to play with at each step.
16 min read
When you ask a language model a question, it does not write you an answer. It predicts one token. Then it predicts another, with the first one now part of the input. Then another. A paragraph-long reply is a few hundred predictions in a row, each made by the same machinery, each seeing only what came before it.
That is the whole trick. Everything else in a model, and there is a lot of it, exists to make that single prediction good: to turn a stretch of text into a probability distribution over what should come next. Once you can see the loop, a lot of behaviour that looks mysterious stops being mysterious.
The widgets below run entirely in your browser, on tiny hand-built models and data. They are illustrations, not the real thing. But the shape of each step is faithful, and the shape is what matters.
Text becomes tokens
A model never sees letters. Before anything else happens, your text is cut into tokens: chunks that are usually a word, a common piece of a word, or a punctuation mark. Each token is then replaced by an integer, its index in a fixed vocabulary of around a hundred thousand entries.
The vocabulary is learned from data before the model is trained, by repeatedly merging the pair of adjacent symbols that occurs most often. So common words get a single token, rare words shatter into several, and a space usually attaches to the start of the word after it. Type into the box and watch where the cuts land.
44 characters became 11 tokens · 4.0 characters per token
Grey: whole words. Green: pieces of words and digit runs. Dashed: raw bytes. Hover a token for its id.
Several famous quirks fall straight out of this step. Models are bad at counting the letters in a word because they never see the letters, only a token id for the whole word. Arithmetic is awkward because numbers arrive in arbitrary three-digit slices. Text in languages that were rare in the training data costs more tokens per sentence, which means less fits in the context and it costs more to process.
Key idea
A token is the model’s atom. Nothing smaller exists for it. When it seems to misread a word, check how that word was cut.
Tokens become vectors
An integer is not something you can do maths on in any useful way. So the second step swaps each token id for a long list of numbers, its embedding. Think of it as a lookup table with one row per vocabulary entry and a few thousand columns. The rows start out random and are adjusted during training until tokens that behave similarly in text end up pointing in similar directions.
Below, each word has an eight-dimensional vector that I wrote by hand, squashed down to two dimensions so you can see it. Real embeddings have thousands of dimensions and nobody writes them, but the properties you can play with here are real: nearby words mean similar things, and differences between vectors capture relationships. Subtract man from king, add woman, and the nearest word to where you land is queen.
Selected
king
Its vector
Nearest
- 0.84
- 0.78
- 0.54
One more thing is folded in at this stage. An embedding on its own says nothing about where a token sits in the sentence, and “dog bites man” needs to differ from “man bites dog”. So each position’s vector also gets a signal that encodes its place in the sequence. From here on, every token is a vector that knows what it is and roughly where it is. That stack of vectors, one per token, is what flows through the rest of the model. It is called the residual stream, and the next two sections are about how it gets refined.
Attention: every token looks back
So far each token’s vector only knows about itself. The word it in “the cat sat on the mat because it was tired” has no idea that it refers to the cat. Attention is the mechanism that fixes this, and it is the heart of the transformer.
For every token, the model computes three small vectors from its embedding: a query (what am I looking for?), a key (what do I contain?), and a value (what will I pass on if someone looks at me?). Each token’s query is compared with every earlier token’s key. High matches become high weights, the weights are normalised to sum to one, and the token is updated with a weighted blend of the earlier tokens’ values.
A model has many of these running in parallel, called heads, and each learns to look for something different. Hover the tokens below and switch between three heads with jobs you can see.
A head that resolves references. When the query is "it", almost all of its attention lands on "cat".
The new vector for it is a blend: 0.87·cat + 0.04·mat + 0.02·it + 0.01·The + …
Rows are queries, columns are keys. Grey cells are masked: a token cannot look forward. Each row sums to 100%.
Notice what attention is not. It is not a search over a database, and it is not a rule. It is a soft, differentiable way for information to move between positions, learned from nothing but the pressure to predict the next token well. Previous-token heads, grammar heads, and heads that resolve pronouns all show up in trained models because each one makes prediction a little easier.
Layers: the same trick, dozens of times
One round of attention is not enough. A transformer stacks the same block many times, from a dozen in small models to over a hundred in large ones. Each block does two things to every token’s vector. Attention lets it gather information from earlier positions. Then a small feed-forward network, the MLP, transforms the vector on its own, with no cross-talk between positions. This is where most of a model’s stored knowledge seems to live: the MLP layers are what turn “the capital of France” into a push towards Paris.
Crucially, neither step replaces the vector. Each adds a correction to it. The residual stream that enters layer one is still recognisably there at the output, with sixty layers of edits piled on. Because of that, you can take the stream at any layer, run it through the final decoding step early, and see what the model would predict if it had to stop there. Step through the layers below.
Embedding
Nothing has mixed yet. The vector is just "the", so the guesses are the words that most often follow "the" anywhere.
Residual stream, one column per token
If we decoded the last column now, the next token would be…
Everything else shares the remaining 66%.
At the very end, the last token’s vector is multiplied by one more matrix, the unembedding, which produces one raw score per vocabulary entry. These scores are called logits, and there are about a hundred thousand of them. A softmax turns them into probabilities. All of the work above, every layer and every head, exists to produce this one list of numbers.
Key idea
The model’s output is not a word. It is a probability for every word it knows. Choosing one is a separate step, and it is the step you have most control over.
A distribution, not an answer
Given “The capital of France is”, a good model will put most of its probability on Paris, but not all of it. Some goes to a, because the sentence might continue “a city on the Seine”. A little goes to not. Something has to decide what to actually emit, and that something is the sampler.
Always picking the most likely token is called greedy decoding. It sounds sensible and it produces dull, repetitive text, because the most probable continuation of a sentence is usually the blandest one. Instead, models sample: they draw a token at random, weighted by the probabilities. Two knobs shape that draw.
Temperature divides the logits before the softmax. Below one, the distribution sharpens and the favourite dominates. Above one, it flattens and unlikely tokens get a real chance. Top-p, or nucleus sampling, sorts the tokens by probability and keeps only the smallest set whose probabilities add up to p, then renormalises. It chops off the long tail of nonsense without touching the shape of the head.
Dashed line: the distribution at temperature 1 with no cut-off. Hatched: mass top-p removed.
12 of 12 candidates kept · 1.6 effective choices
Try pushing temperature to two on the colour prompt and sampling twenty times. Then set top-p to 0.5 and do it again. Those two settings are most of the difference between a model that sounds careful and one that sounds creative, and they are applied after the model has done its thinking. The same forward pass, the same distribution, different dice.
The loop
Now the part that turns a predictor into a writer. Take the token the sampler chose, append it to the input, and run the whole thing again. The new token gets embedded, attention lets every position see it, the layers refine, the unembedding produces a fresh distribution, the sampler picks. Repeat until the model emits a special end-of-sequence token, or hits a length limit.
The widget below does exactly this with a model that is genuinely trained in your browser: a trigram model that counts which word follows which pair of words in forty-four sentences. It is a thousand lines of maths short of a transformer, but the loop around it is identical. Step it one token at a time and watch the distribution change as the context grows.
Context window · 2 tokens
Next token, most likely first
The other 93 tokens share the remaining 1%.
A trigram model trained in your browser on 44 sentences: nowhere near a transformer, but the loop is the same loop.
Three consequences of the loop are worth holding on to. First, a model cannot go back. Once a token is out it is part of the context, and everything after it is conditioned on it, which is why an early mistake tends to be defended rather than corrected. Second, every token costs a full pass through the network, which is why responses stream word by word and why long answers are slow and expensive. Real systems soften this by caching each token’s keys and values so earlier positions are not recomputed, but the new token still has to attend to all of them. Third, the model has no plan. Whatever structure a reply has emerged from a sequence of local decisions, each one made by the same stateless function of what came before.
Where training fits
Nothing above mentioned learning, and that is deliberate: generation is the same loop whether the weights are good or terrible. Training is what makes them good, and it happens in roughly three stages.
Pretraining runs the loop over trillions of tokens of text and nudges every weight so that the predicted distribution puts more mass on the token that actually came next. That alone produces a model that completes text very well, but it completes it the way the internet would. Ask it a question and it may answer with another question, a forum signature, or “[deleted]”.
Supervised fine-tuning continues training on a much smaller set of example conversations written to show the behaviour we want. Then reinforcement learning from human feedback has people compare pairs of model outputs, trains a second model to predict which they prefer, and uses that as a reward to push the language model’s distributions towards the preferred kind of answer. None of this changes the architecture or the loop. It changes which tokens get the probability.
Prompt: “How do I get better at running?”
Dark dot: tokens that start a helpful answer. Light: tokens that start forum chatter. Helpful share: 15%.
A likely completion
I have the same question. Posted 3 years ago. Thanks in advance! Any advice welcome.
What the loop explains
Once you hold the whole pipeline in your head, a lot of day-to-day behaviour becomes predictable. Models confabulate because the sampler must pick something and a plausible-sounding token is often more probable than “I don’t know”. They are confident in tone because confident prose is what high-probability text looks like. They are sensitive to phrasing because the prompt is the entire input to the function, and a different prompt is a different distribution. They work better when asked to reason step by step because each intermediate token becomes context for the next, and the loop can carry a chain that a single pass cannot.
It is also worth noticing what is not in the picture: no database of facts, no symbol table, no planner, no memory between conversations beyond what you paste back in. Just a very large function from a sequence of tokens to a distribution over the next one, and a loop that calls it until it says stop.