How a Large Language Model Works
An interactive 3D walkthrough of a working GPT-style transformer — watch a real (tiny) model run inference, token by token, layer by layer. Everything is self-hosted and runs locally in your browser: no external downloads, no tracking.
Why learn the internals?
Prompt engineering, fine-tuning, and debugging model behaviour all get dramatically easier once you can picture what happens between typing a prompt and reading a reply. Scroll through the 3D model below to see every matrix multiply, then read the stage-by-stage breakdown underneath — each stage has a plain-English summary plus an expandable deep-dive.
The 3D model
Drag to orbit · scroll to zoom · use the sidebar on the right to step through the walkthrough.
This 3D visualization requires WebGL2. Please open this page in a recent version of Chrome, Firefox, Safari, or Edge.
The pipeline, stage by stage
The animation above is a client-side WebGL render, so here is the same journey in words — from raw text to a sampled next token. Each card starts with a one-paragraph summary; expand 'Go deeper' for the details, a plain-English analogy, and why it matters.
1 · Tokenize
Raw text is chopped into tokens — usually subword pieces — and each token is mapped to an integer ID via a fixed vocabulary. From here on the model only ever sees these integers, never the letters.
▸Go deeper
In detail
- ▸A token is not always a whole word. Common words are single tokens (" the"), but rarer words get split into pieces ("tokenization" → "token" + "ization"), and a leading space is usually part of the token.
- ▸The vocabulary is fixed and finite — GPT-2 has 50,257 entries. Every possible input must be expressed as a sequence of these known tokens.
- ▸The algorithm that decides the splits is Byte-Pair Encoding (BPE): it starts from individual bytes and repeatedly merges the most frequent adjacent pairs until it reaches the target vocabulary size.
- ▸Because it falls back to bytes, BPE can encode literally any text — emoji, code, other languages — without ever hitting an 'unknown word'.
Plain-English analogy
Think of it like typing on an old phone with a fixed dictionary: you can only send words the phone already knows, so anything unusual gets spelled out from smaller known chunks.
Why it matters
Tokenization quietly shapes a lot of model behaviour. It's why models are billed per token, why they sometimes miscount characters in a word (they see chunks, not letters), and why the same idea can cost more tokens in one language than another. When people say a model has a '128k context window', they mean 128k tokens — not characters or words.
Further reading — familiar examples
"unhappiness" → "un" + "happiness"
A word the model has never seen as a whole is still spelled out from familiar pieces it has — so it can handle brand-new words without choking.
"strawberry" and the letter 'r'
Ask a model how many r's are in 'strawberry' and it often stumbles — because it sees the word as a couple of tokens, not as individual letters.
Emoji and code
A 🙂 or a snippet of Python still becomes tokens. BPE falls back to raw bytes, so nothing is ever truly 'unknown' to the tokenizer.
2 · Embedding
Each token ID looks up a row in a learned embedding table, turning it into a vector of numbers. A positional embedding is added so the model knows each token's place in the sequence.
▸Go deeper
In detail
- ▸The embedding table is just a big matrix: one row per vocabulary token, each row a vector of length d_model (768 in GPT-2 small, 12,288 in GPT-3).
- ▸These vectors are learned during training, not hand-designed. Tokens with related meanings end up with nearby vectors.
- ▸Attention has no built-in notion of order, so a separate positional embedding is added to encode 'I am the 1st / 2nd / 3rd token'.
- ▸Token embedding + positional embedding = the first vector that actually enters the transformer stack.
Plain-English analogy
Imagine giving every word a set of GPS coordinates in a huge 'meaning space', where 'king' and 'queen' are neighbours. The positional embedding then stamps each one with 'and I arrived at seat number 4'.
Why it matters
This is where discrete symbols become continuous geometry — the crucial move that lets a network do calculus on language. The famous 'king − man + woman ≈ queen' arithmetic works precisely because meaning is now encoded as direction and distance in this space. Everything downstream is just reshaping these vectors.
Further reading — familiar examples
king − man + woman ≈ queen
The classic word-vector result: relationships like gender or royalty become consistent directions you can literally add and subtract.
"Apple" the fruit vs. Apple the company
Early embeddings gave each word one fixed vector; transformers refine it with context, so 'Apple' near 'iPhone' drifts toward the company, near 'orange' toward the fruit.
"The cat sat" vs. "Sat the cat"
Same words, different order, different meaning. Positional embeddings are what let the model tell these two apart.
3 · Layer Norm
Before each sub-layer, every token vector is normalized to mean 0 and unit spread, then rescaled by two learned parameters. This keeps values well-behaved so very deep networks train reliably.
▸Go deeper
In detail
- ▸For each token vector independently: subtract its mean, divide by its standard deviation, then apply a learned scale (γ) and shift (β).
- ▸A tiny epsilon (~1e-5) is added inside the square root to avoid dividing by zero.
- ▸Modern GPTs apply it before attention and before the MLP ('pre-norm'), which makes very deep stacks trainable.
- ▸It normalizes across the features of one token — it never mixes information between different tokens.
Plain-English analogy
Like an audio compressor that keeps every track at a consistent volume: no single instrument blows out the mix, so the next stage always receives a clean, balanced signal.
Why it matters
Layer norm looks boring but it's load-bearing. Without it, the numbers flowing through dozens of layers tend to explode or vanish, and training simply falls apart. It's one of a handful of 'plumbing' tricks (alongside residual connections) that made it practical to stack transformers dozens or hundreds deep.
Further reading — familiar examples
Grading on a curve
A teacher who rescales every exam to the same mean and spread makes scores comparable across classes — layer norm does the same to each token's numbers.
Auto-gain on a microphone
Whether you whisper or shout, auto-gain keeps the recorded level steady. Layer norm keeps each vector's 'loudness' steady before the next stage.
Why 100-layer models train at all
Stack 100 raw layers and signals blow up or die; add layer norm + residuals and suddenly very deep networks converge — the practical unlock behind modern LLMs.
4 · Self-Attention
Each token forms a Query, Key, and Value. The dot product of Queries and Keys decides how much each token attends to the others; a softmax turns those scores into weights used to blend the Values.
▸Go deeper
In detail
- ▸From each token vector we compute three new vectors: Query (what am I looking for?), Key (what do I offer?), and Value (what will I pass on?).
- ▸Relevance of token j to token i is the dot product Qᵢ·Kⱼ, scaled by 1/√dₖ to keep the numbers stable.
- ▸A softmax over each row turns those raw scores into weights that sum to 1, which are used to take a weighted average of the Value vectors.
- ▸Causal masking blocks attention to future tokens — a token can only look at itself and the past.
Plain-English analogy
It's like a room of people each asking a question out loud (Query) and everyone else holding up a name-tag (Key). You listen most closely to the people whose tag best matches your question, and take notes (Value) weighted by how relevant they are.
Why it matters
Attention is the one component that lets tokens actually communicate — everything else processes tokens in isolation. It's why a model can resolve 'it' to the right noun sentences earlier, or match an opening bracket to its close. This 'let every position look at every other position' idea is the single innovation that made the 2017 'Attention Is All You Need' paper so influential.
Further reading — familiar examples
"The trophy didn't fit in the suitcase because it was too big."
What is 'it'? Attention lets the model link 'it' back to 'trophy' rather than 'suitcase' — a classic test of understanding reference.
Matching brackets in code
When a model writes a closing ')' to match an opening '(', attention heads that track bracket pairs are doing the bookkeeping.
Search engine intuition
Your search box is the Query, page titles are Keys, page contents are Values. You read most from the pages whose titles best match your query — exactly how attention weights work.
5 · Attention Matrix
Laying out every token's attention to every other token gives a triangular matrix (future tokens are masked out). Many heads run in parallel, each learning a different relationship between tokens.
▸Go deeper
In detail
- ▸Row i, column j of the matrix = how much token i attends to token j. Each row sums to 1 after softmax.
- ▸Causal masking blanks out the upper triangle (future positions), giving the matrix its staircase shape.
- ▸A layer runs several attention 'heads' in parallel — 12 in GPT-2 small, 96 in GPT-3 — and concatenates their outputs.
- ▸Different heads specialize: one might track subject–verb agreement, another follows quotes, another links pronouns to nouns.
Plain-English analogy
Picture a seating chart where each guest notes how much they're listening to every earlier guest. Run several such charts at once — one for grammar, one for topic, one for punctuation — and you have multi-head attention.
Why it matters
These matrices are one of the few windows into what a model has actually learned — the whole field of 'mechanistic interpretability' grows out of reading them. Multiple heads matter because a single attention pattern can only capture one kind of relationship at a time; running many in parallel lets one layer track grammar, reference, and topic simultaneously.
Further reading — familiar examples
"induction heads"
Researchers found specific heads that spot a pattern like 'A B … A' and predict 'B' next — a concrete, discovered circuit for in-context copying.
A staircase you can see
Because a token can't attend to the future, the matrix is always triangular — the blank upper-right corner is causal masking made visible.
Panel of specialists
Think of 12 or 96 experts reading the same sentence, one watching grammar, one watching names, one watching tone — then pooling their notes.
6 · MLP (Feed-Forward)
After attention mixes information across tokens, each token is processed on its own by a two-layer network that expands, applies a non-linearity (GELU), and projects back down. Most parameters live here.
▸Go deeper
In detail
- ▸Step 1: a linear layer expands the vector to 4× its width (e.g. 768 → 3072).
- ▸Step 2: a non-linear activation (GELU, a smooth cousin of ReLU) is applied element-wise.
- ▸Step 3: a second linear layer projects back down to the original width.
- ▸It's applied identically and independently to every token position — no cross-token mixing happens here.
Plain-English analogy
If attention is the group discussion where everyone shares notes, the MLP is each person going back to their desk to privately think through what they just heard before writing anything down.
Why it matters
Two thirds of a transformer's parameters typically live in the MLP, and a growing body of research suggests this is where much of a model's factual knowledge is stored — almost like a giant key-value memory. The 4× expansion isn't magic; it just gives the network room to compute richer intermediate features before compressing back down.
Further reading — familiar examples
"The capital of France is ___"
Recall of a fact like 'Paris' is thought to live largely in MLP weights — edit those weights and you can literally change what the model 'knows'.
Zip and unzip
Expand to 4× width (unzip into a roomy workspace), do the thinking, then project back down (zip it up) — the classic wide-then-narrow sandwich.
Model editing (ROME)
Researchers changed a model's answer to 'the Eiffel Tower is in ___' from Paris to Rome by tweaking a few MLP weights — evidence that facts really do sit here.
7 · Transformer Block
Layer-norm, attention, residual add, layer-norm, MLP, residual add — one block. A GPT is just this block repeated (12 times in GPT-2 small, 96 in GPT-3), each pass refining the token vectors.
▸Go deeper
In detail
- ▸The order is: norm → attention → add the input back (residual) → norm → MLP → add back again.
- ▸Residual connections let the original signal skip past each sub-layer, so gradients can flow through very deep stacks without vanishing.
- ▸Every block has the same shape but its own independently learned weights.
- ▸The running sum that blocks read from and write to is often called the 'residual stream'.
Plain-English analogy
Think of an assembly line of identical workstations. Each station makes a small improvement to the product and passes it on — and there's a conveyor belt underneath (the residual) carrying the original along so nothing gets lost.
Why it matters
This repetition is why transformers scale so smoothly: to make a model 'smarter', you mostly just add more identical blocks and widen them — no new mechanism required. Rough intuition is that earlier blocks handle low-level patterns (grammar, syntax) while later ones capture abstract, context-dependent meaning, though the reality is messier than any clean story.
Further reading — familiar examples
GPT-2 vs GPT-3
Same block, stacked deeper and wider: GPT-2 small = 12 blocks, GPT-3 = 96. Almost all the capability jump came from 'more of the same'.
A conveyor belt with a bypass lane
The residual stream is the belt carrying the original along; each block adds a tweak. If a block has nothing to add, the signal simply passes through untouched.
Scaling laws
Add more data, parameters and compute and quality keeps improving predictably — the empirical 'scaling laws' that justified building ever-bigger models.
8 · Unembedding & Softmax
The final token vector is multiplied by the unembedding matrix to produce one logit per vocabulary token, then softmax turns those logits into a probability distribution that sums to 1.
▸Go deeper
In detail
- ▸The unembedding matrix maps the final vector (length d_model) to one raw score per vocabulary token (length ~50k). It's often the tied transpose of the input embedding.
- ▸Those raw scores are called logits — bigger means 'more likely to come next'. They can be any real number.
- ▸Softmax exponentiates every logit and divides by the total, producing values in [0,1] that sum to 1.
- ▸Temperature divides the logits before softmax: T<1 sharpens the distribution, T>1 flattens it.
Plain-English analogy
Logits are like raw votes for each candidate word — some positive, some negative, any size. Softmax is the returning officer that converts those messy votes into clean percentages that add up to 100%.
Why it matters
Only the very last token's prediction is used when generating the next word, even though the model computes a prediction at every position (that's what makes training efficient). The word 'logit' comes from 'log-odds', a nod to the exponentiation softmax applies. Temperature, which you set in almost every chat API, acts right here — turning a peaky, confident distribution into a flat, adventurous one.
Further reading — familiar examples
"The capital of France is ___"
The logit for ' Paris' towers over everything else, so after softmax it might get 95% probability while every other word splits the remaining 5%.
Turning scores into percentages
Like converting exam raw scores into 'you have a 70% / 20% / 10% chance' — softmax is just the exponentiate-then-normalize recipe that guarantees they sum to 100%.
The temperature dial
temperature=0 makes the model almost always pick 'Paris'; temperature=1.5 gives quirkier answers a real chance — same logits, different sharpness.
9 · Sampling
One token is sampled from the distribution — tuned by temperature, top-k, or top-p — appended to the input, and the whole pipeline runs again. That autoregressive loop is how a model writes text.
▸Go deeper
In detail
- ▸Greedy decoding always picks the single most likely token — fast but repetitive and robotic.
- ▸Temperature controls randomness: low = focused and deterministic, high = creative and surprising.
- ▸Top-k keeps only the k most likely tokens; top-p (nucleus) keeps the smallest set whose probabilities sum to p.
- ▸The chosen token is appended and the entire pipeline runs again — this is the 'autoregressive' loop.
Plain-English analogy
It's like writing a story one word at a time by drawing from a weighted bag of options. Temperature decides how wild your draws are; top-k / top-p decide how many options you even allow into the bag.
Why it matters
This loop is the whole reason a model can 'ramble' coherently: every new word is conditioned on everything written so far, including its own earlier output. It also explains hallucination — the model is always sampling a plausible next token, never checking a fact. And it's why the same prompt can give different answers each time unless you pin temperature to 0.
Further reading — familiar examples
Predictive text on steroids
Your phone suggesting the next word is the same idea; an LLM just does it with a far better model and then feeds its own choice back in to keep going.
Why ChatGPT 'types' word by word
The streaming, token-by-token output you watch is literally this loop running: sample a token, show it, append it, predict the next.
Why it sometimes makes things up
Ask for a citation and a model may invent a real-looking but fake reference — it's sampling a plausible next token, not looking anything up.
Frequently asked questions
What model does this visualization show?
A tiny GPT-style network (nano-GPT) trained to sort the letters A, B, and C — the demo model from Andrej Karpathy's minGPT. It is small enough to render every weight and activation, yet uses the exact same architecture as GPT-2 and GPT-3.
Does anything get uploaded or downloaded from a server?
No. The model weights, font atlas, and all rendering assets are served from this site itself and run entirely in your browser via WebGL. Nothing you do is uploaded, logged, or sent to any third party.
Why can't I see the 3D model?
The visualization needs WebGL2, which every modern browser supports. If the canvas stays blank, try a recent version of Chrome, Firefox, Safari, or Edge, and make sure hardware acceleration is enabled.
How does this relate to real models like ChatGPT?
The pipeline is identical — tokenize, embed, stack transformer blocks, unembed, softmax, sample. Frontier models just scale it up: bigger vocabulary, wider vectors, more heads, and far more layers. GPT-3 has 175 billion parameters running this same machinery.
I'm new to this — where should I start?
Read the nine stages below in order; each one has a short summary plus an expandable section with deeper detail, a plain-English analogy, and a discussion of why it matters. Then scrub through the 3D model above and try to match what you see to each stage.
Credits & license
The 3D visualization is based on the open-source llm-viz project by Brendan Bycroft (MIT license), self-hosted here with no external dependencies. The demo model is the A/B/C sorting nano-GPT from Andrej Karpathy's minGPT.