A primer in nine parts
Mechanism, not metaphor  ·  read the panels

A language model is a machine for guessing the next token.

Everything else — the conversation, the code, the apology when it gets something wrong — is engineering built on top of that one operation, repeated a few hundred times a second.

This page takes that sentence apart. What a token is, how meaning gets turned into numbers, what attention computes, what training actually changes, and why a system this capable still confidently invents things.

Three of the sections are instruments rather than prose. Type in them, drag them, break them. The concepts are exact; where a demo uses stand-in numbers instead of a live model, it says so.

Est. 20 min No maths beyond multiplication Sources listed at the end
Part 01

It never sees letters. It sees tokens.

Before anything else happens, your text is chopped into pieces from a fixed vocabulary. Almost every strange behaviour you have noticed starts here.

A model has a vocabulary — typically somewhere between 32,000 and 200,000 entries — and text must be expressed entirely in those entries. Common words get one token each. Rarer words get broken into fragments. The algorithm is usually byte-pair encoding: start from raw bytes, then repeatedly merge whichever adjacent pair occurs most often in the training corpus, until you have filled the vocabulary. Frequency buys wholeness.

Leading spaces belong to the token, which is why the and the are different entries. As a rough English rule: one token ≈ 4 characters ≈ 0.75 words.

Instrument 01 · Segmenter Type to re-segment
Tokens0
Characters0
Chars / token0.00

Faithful reproduction of GPT-2/3-style pre-tokenisation (the regex that splits contractions, leading spaces, digit runs and punctuation), followed by a simplified merge step standing in for the real learned merge table. Segment boundaries and counts are close to a production tokeniser, not identical to it.

What this explains

  • Letter puzzles. Asked how many r's are in "strawberry," the model is looking at two or three opaque chunks, not eleven letters. It has to infer spelling it cannot see.
  • Arithmetic wobble. 1234567 may arrive as several digit-group tokens, so column alignment is something the model reconstructs rather than perceives.
  • Language cost. Text in languages under-represented in the merge table fragments into more tokens — the same paragraph can cost several times more in Thai or Telugu than in English, and eats the context window faster.
  • Rhyme and wordplay are harder than they look, for the same reason.
Part 02

Every token becomes a direction in space

Token 3,290 means nothing. The model's first move is to swap that ID for a long list of numbers — and those numbers are where meaning lives.

The embedding matrix is a lookup table with one row per vocabulary entry. Each row is a vector of a few thousand numbers. Nothing about it is hand-designed; the values are learned during training, adjusted by the same gradient descent that shapes everything else.

What emerges is geometry. Tokens used in similar contexts end up pointing in similar directions, and direction can carry relationships. The famous early demonstration came from word2vec in 2013: take the vector for king, subtract man, add woman, and the nearest neighbour is often queen. Relationships like gender, plurality and capital-of behave, loosely, like consistent offsets you can add.

Where the tidy story breaks Those analogies are approximate and cherry-picked in the retelling — results depend heavily on which candidates you exclude from the search. More importantly, the same statistics that capture capital-of also capture human bias in the training text. Geometry is descriptive, not virtuous.

One more thing matters, and it is the upgrade the transformer brought. A raw embedding is static — one vector per token, identical everywhere. As the vector passes up through the model's layers it becomes contextual: the representation of "bank" in river bank genuinely diverges from "bank" in bank transfer. The mechanism that does the diverging is the subject of the next part.

Part 03

Attention is a weighted lookup, and that is the whole trick

Each position asks a question, every earlier position answers, and the answers get averaged in proportion to how well they match.

From each token's vector the model projects three new vectors: a query (what I am looking for), a key (what I offer), and a value (what I will hand over if chosen). To update a position, take the dot product of its query against every key, turn those scores into percentages with a softmax, and mix the values by those percentages.

Attention(Q, K, V) = softmax( Q Kᵀ / √dk ) V The √dk divisor keeps dot products from growing with vector size; without it the softmax saturates into a hard pick and gradients vanish. Vaswani et al., 2017.

Two structural details do a lot of work. A causal mask sets every future position's score to −∞ before the softmax, so a token can only ever look backwards — that is what makes the model a valid next-token predictor. And attention runs in parallel heads, each with its own projections, so one head can track subject–verb agreement while another tracks quotation marks.

Instrument 02 · Attention pattern Click a row = pick a query token
Rows are query positions; columns are keys being attended to. Hatched cells are masked — the future is not readable. Row values sum to 100%.

Weights here are illustrative, hand-set to show patterns that interpretability research does find in real heads — long-range subject tracking, pronoun and relative-clause binding. A live model's heads are messier and mostly uninterpretable at a glance.

Attention's cost is the reason long context is expensive: comparing every position against every other is quadratic in sequence length. Double the context, quadruple the attention work. Most of the last few years of systems research — FlashAttention, sliding windows, grouped-query attention, KV caching — is about paying that bill more cheaply.

Part 04

One forward pass, start to finish

Here is the entire journey from your text to a single next token. Then it happens again.

Trace · text in, one token out n = tokens, d = model width
1Tokenise "Write a haiku" → [8144, 261, 6023, 23996] · n integers
2Embed + position look up a vector per token, encode order (RoPE in most modern models) · n × d
3Transformer block — attention every position gathers from every earlier position · n × d
4Transformer block — MLP each position processed independently; where most parameters live · n × d
Repeat blocks 3–4, dozens of times residual connections carry the signal; layer norm keeps it stable
5Unembed to logits project the final position to one raw score per vocabulary entry · V numbers
6Softmax → probabilities → sample one the only step that is not deterministic arithmetic
7Append the token to the input, return to step 2 this loop is what "generating" means

Two things worth holding onto. First, the residual stream — each block adds its output back into a running total rather than replacing it, so information can skip layers untouched. This is what makes networks hundreds of layers deep trainable at all.

Second, every token costs the same compute. The model cannot think harder about a difficult token; it can only produce more tokens. That single fact explains chain-of-thought prompting: asking for step-by-step working is not a psychological trick, it literally buys more forward passes to compute in. Reasoning models are trained with reinforcement learning to do this well, and to keep doing it until the answer stabilises.

Part 05

Three passes, and only one of them is expensive

A base model and a chat assistant are the same network at different points in the same process. Knowing which stage does what tells you which problems are fixable.

Pretraining — where the knowledge comes from

Feed the model an enormous amount of text and ask it, over and over, to predict the next token. Compare its distribution to the token that actually came next, measure the gap with cross-entropy loss, and nudge every weight to make the truth slightly more likely. No labels are needed — the text labels itself, which is why this scales to trillions of tokens. This stage is typically upwards of 98% of the total compute, and it is where essentially all factual knowledge and language ability is acquired.

The output is a base model: fluent, knowledgeable, and useless as an assistant. Ask it a question and it may well continue with more questions, because that is what a page of questions usually does.

Supervised fine-tuning — learning the shape of an answer

Now train on a much smaller, curated set of written demonstrations: prompt, then an ideal response. Thousands to hundreds of thousands of examples, not trillions. The model learns the format of being helpful — answer the question, stop when done, hold a turn in a conversation. It learns almost no new facts here.

Preference training — learning which answer is better

Demonstrations cannot express "this reply is a bit too smug." So instead: show humans two candidate responses, ask which they prefer, and use those comparisons as the signal. In classic RLHF the comparisons train a reward model, and the language model is then optimised against it with reinforcement learning. DPO and its relatives skip the separate reward model and optimise on the preference pairs directly. Anthropic's Constitutional AI variant has the model critique and revise its own outputs against an explicit written set of principles, so a large share of the preference labels are generated by AI rather than by people.

This is the stage that produces tone, refusals, formatting habits, and hedging. It is also where sycophancy comes from: if raters reliably prefer agreeable answers, agreeableness is exactly what gets optimised.

The diagnostic that follows from this Wrong facts are usually a pretraining or retrieval problem — fine-tuning will not install knowledge, it will teach the model to sound confident about it. Wrong behaviour — format, tone, refusal boundaries — is a preference-training problem, and is genuinely fixable downstream. People routinely reach for the second tool to fix the first problem.
Part 06

Why the same question gives different answers

The network's output is not a word. It is a probability for every word. Something then has to choose — and how it chooses is a dial you control.

The final layer emits one raw score, a logit, per vocabulary entry. Softmax turns those into probabilities summing to 1. Temperature divides the logits before the softmax: below 1 it sharpens the distribution toward the favourite, above 1 it flattens it toward the field. Top-p (nucleus sampling) then keeps only the smallest set of candidates whose probabilities add up to p, and discards the long tail entirely.

Instrument 03 · Sampler Distribution over the next token

Prompt type: . The same two dials behave completely differently across these.

Notice what the extremes do. Near zero, the model always picks its favourite — repeatable, and prone to loops and flat prose. Above roughly 1.3 the tail gets real probability mass, and text drifts from creative to incoherent. Top-p is the safety rail: it lets you raise temperature for variety while still refusing to ever sample genuine nonsense.

Then switch prompts, because this is the part that gets missed. On the factual prompt the dials barely matter — the evidence for Paris is so overwhelming that you have to push temperature past 1.5 before anything else gets a serious look, and top-p does nothing until it is almost at 1. On the open-ended prompt the same dials transform the output, because ten continuations were already close to tied. Temperature does not add creativity; it decides how much to respect a distribution the model has already committed to. Where that distribution is peaked, turning the dial mostly buys you errors rather than variety.

Temperature 0 is not a guarantee of identical output Greedy decoding is deterministic in exact arithmetic, but floating-point addition is not associative, so batching, GPU kernel choice and mixed precision can flip a near-tie between two logits. Same prompt, same seed, occasionally different token. Treat low temperature as stable, not as reproducible.
Part 07

Scale is a curve someone measured

The decision to build very large models was not a hunch. It came from plotting loss against compute and finding a straight line on a log scale.

In 2020 Kaplan and colleagues showed that test loss falls as a smooth power law in model size, dataset size and compute — remarkably predictable across many orders of magnitude. That predictability is what made spending nine figures on a training run a defensible engineering decision rather than a gamble.

In 2022 the Chinchilla paper corrected the recipe. Given a fixed compute budget, the earlier generation had made models too big and trained them on too little data. Compute-optimal training, they found, scales parameters and tokens together — roughly 20 training tokens per parameter. The proof was direct: Chinchilla at 70B parameters outperformed Gopher at 280B, using the same compute budget spent differently.

ModelParamsTraining tokensTokens / paramWhat it showed
GPT-3 (2020)175B~300B1.7Scale alone produced few-shot learning
Gopher (2021)280B~300B1.1Bigger, similarly under-trained on data
Chinchilla (2022)70B1.4T20Beat Gopher at a quarter the size
Llama 3 8B (2024)8B15T~1875Deliberately trained far past optimal

That last row is the part people miss. Chinchilla optimises training cost. If a model will serve billions of requests, inference cost dominates the budget, and it is worth over-training a small model well past the compute-optimal point to get a permanently cheaper one. Modern open models are trained on hundreds of times more data per parameter than the 2022 rule recommends — not because the rule was wrong, but because it answered a different question.

A second lever changes the arithmetic again: mixture of experts. Route each token to a small subset of many parallel feed-forward blocks, and total parameters can be far larger than the parameters actually used per token — capacity without proportional cost.

Part 08

The failure modes are structural, not bugs

Each of these follows directly from something described above. That is what makes them predictable — and what tells you which ones tooling can fix.

Fabrication

The training objective rewards plausible, not true. There is no fact table inside the weights to consult and no internal signal that says "this next part is a guess" — a fabricated citation is generated by exactly the same machinery, at similar confidence, as a correct one. Fluency and accuracy are separate axes, and the model is optimised hard on one of them. Worse, saying "I don't know" is only produced if preference training rewarded it, which requires raters who can tell honest uncertainty from unhelpful hedging.

What helps: retrieval, so the answer is grounded in supplied text rather than recalled; tool use for anything computable; asking for sources you can check; and treating any specific number, name or citation as unverified by default.

No memory between conversations

The weights are frozen after training. The context window is working memory, and it is the only memory — start a new conversation and everything is gone. Products that appear to remember you are re-inserting stored notes into the prompt behind the scenes. Nothing you say is learned in the moment.

In-context learning is real, and is not learning

Show a model three examples of a format it has never seen and it will follow the pattern — with no weight update whatsoever. The pattern-matching happens inside a single forward pass, in the activations. This is why few-shot prompting works, and why its effects vanish the moment the conversation ends.

Confidence is not calibrated to correctness

Base models are reasonably well calibrated — their probabilities roughly track how often they are right. Preference training tends to degrade that: optimising for answers humans like pushes toward confident phrasing regardless of underlying uncertainty. Assertive tone carries almost no information about reliability.

Everything in the context window is input, not instruction

A model reading a web page, an email or a document cannot cryptographically distinguish your instructions from text that merely looks like instructions. That is the root of prompt injection, and it is a structural consequence of the fact that there is only one stream of tokens. Mitigations reduce it; nothing yet eliminates it.

Part 09

Six things that are commonly said

Each of these is a reasonable inference from watching a model behave. Each is wrong in a way that changes how you should use one.

It looks things up when you ask it something
There is no database inside. Facts are diffusely encoded in billions of weights and re-derived every time — which is why recall degrades gracefully into plausible invention rather than failing cleanly like a missing row.
A bigger context window means it remembers more
The window is scratch space for one conversation, not storage. Across sessions nothing persists. And attention quality is uneven within a long window — material in the middle is measurably less well used than material at either end.
Fine-tuning is how you teach it your company's data
Fine-tuning is excellent at teaching form, tone and task structure, and poor at installing facts. For knowledge that must be current or citable, retrieve it into the prompt. Fine-tuning facts mostly teaches confident recitation of a snapshot.
It understands nothing, it's just autocomplete
"Just autocomplete" is accurate about the objective and misleading about the result — predicting text well at scale requires internal structure that demonstrably includes world models, arithmetic circuits and abstraction. The honest position is that the mechanism is simple and what it produces is not fully understood.
Prompt engineering is about finding magic words
What reliably works is unglamorous: supply the actual context, show examples of the output you want, state constraints explicitly, and leave room for the model to work step by step before it commits to an answer. Incantations are mostly noise.
Its confidence tells you how likely it is to be right
Assertive phrasing is a product of preference training, not a measure of internal certainty. Verify anything load-bearing — a specific number, a citation, an API signature — regardless of how the answer is worded.
Ref ?

The questions people actually ask

Short answers to the things that bring most people here. Each one links to the part of the page that works through it properly.

How does a large language model work?

It converts your text into tokens, turns each token into a vector, passes those vectors through dozens of transformer layers that let every position read from earlier positions, and emits a probability for every entry in its vocabulary. One token is sampled from that distribution, appended to the input, and the whole process repeats. See the full trace →

What is a token in a language model?

A token is a chunk of text from a fixed vocabulary — usually a common word, a fragment of a rarer word, or punctuation. Models never see individual letters, only these chunks. In English one token averages about four characters, or roughly ¾ of a word. Try the segmenter →

Why do language models hallucinate?

Because the training objective rewards plausible text, not true text. There is no fact database inside to consult, and no internal signal marking a claim as a guess — a fabricated citation is produced by the same machinery, at similar confidence, as a correct one. Retrieval, tool use and checkable sources help; the tendency is structural, not a bug to be patched. Read why →

What does temperature do in an LLM?

Temperature divides the model's raw scores before they become probabilities. Below 1 it sharpens the distribution toward the single most likely token; above 1 it flattens it so unlikely tokens get a real chance. It does not add creativity — it decides how strictly to respect a distribution the model already computed. Drag the dial →

What is attention in a transformer?

A weighted lookup. Each position emits a query, every position offers a key and a value; the dot product of query against key becomes a percentage after softmax, and the values are mixed in those proportions. A causal mask stops any position reading the future. See the pattern →

Do language models remember previous conversations?

No. The weights are frozen after training, and the context window is the only memory — it is cleared when the conversation ends. Products that appear to remember you are storing notes separately and re-inserting them into the prompt. More on this →

Should I use RAG or fine-tuning?

Use retrieval for knowledge — anything that changes, needs citing, or must be current. Use fine-tuning for behaviour — format, tone, task structure. Fine-tuning is poor at installing facts; it mostly teaches the model to recite a snapshot confidently. Why that follows →

How much data does it take to train a large language model?

The 2022 Chinchilla result put the compute-optimal ratio at roughly 20 training tokens per parameter — a 70B model on about 1.4 trillion tokens. Models today are deliberately trained far past that point, because over-training a smaller model makes it permanently cheaper to run. The numbers →

Ref A

The vocabulary, in one place

token
The unit a model reads and writes. A word, a word fragment, or punctuation. Roughly four English characters.
embedding
The vector a token ID is converted into. Similar meanings occupy similar directions.
logit
A raw, unnormalised score for one vocabulary entry, before softmax turns it into a probability.
softmax
Converts a list of scores into positive numbers that sum to 1. The step that makes an output a distribution.
attention head
One query/key/value lookup. Models run many in parallel, each learning a different relationship.
context window
The maximum number of tokens the model can attend to at once. Prompt and reply share it.
temperature
Divides logits before softmax. Low sharpens toward the favourite; high flattens toward the field.
top-p / nucleus
Keeps only the smallest set of candidates whose probability sums to p; discards the tail.
RLHF
Reinforcement learning from human feedback. Trains a reward model on human preferences, then optimises against it.
RAG
Retrieval-augmented generation. Fetch relevant documents, put them in the prompt, answer from them.
KV cache
Stored keys and values for tokens already processed, so generating each new token does not recompute the whole sequence.
mixture of experts
Routes each token through a small subset of many parallel sub-networks. Large total capacity, modest cost per token.
Ref B

Read the primary sources

Every claim above traces to one of these. They are more readable than their reputation suggests — start with the abstract and the figures.