How LLMs Work: The Mechanical Model
The next-token loop, tokens, attention, the KV cache and hallucination, mechanically.
Chapter 1 was the map; this is the engine. A handful of mechanisms explain nearly every production behavior you’ll debug: why output streams, why letters get miscounted, why long prompts are slow and expensive, why the same input gives different answers, why GPUs run out of room, and why models hallucinate.
The figures use the 15.7K-parameter character model from Chapter 3 and a byte-level tokenizer trained on the same Shakespeare text, so the numbers are real. This chapter is the fast overview; Chapters 3 to 10 go deep on each mechanism.
2.1The next-token loop
The whole machine is one loop: predict the next token, append it, repeat.
tokens = tokenize(prompt)
while True:
logits = model(tokens) # a score for every token in the vocabulary
next_t = sample(softmax(logits / T)) # a dice roll over a probability distribution
tokens.append(next_t) # append it and feed everything back in
stream(next_t) # why streaming is the natural delivery format
if next_t == EOS or len(tokens) >= max_len:
break
That is the entire runtime. There is no plan, no lookup and no “understanding” module. Anything that looks like checking or remembering, such as tools, retrieval and agents, is scaffolding bolted around this loop (Chapters 15 and 18). The ribbon at the top of this chapter is the loop running for real: one dice roll per character.
Two production behaviors come straight from it. Output arrives one token at a time, so streaming is the native delivery format rather than a feature. And the loop must always emit some token, which is the first ingredient of hallucination (section 2.11).
Common take“The model lied.”
Sharper take“The model sampled a plausible continuation with no grounding, so I ground it and verify it.”
2.2Tokens
The model’s alphabet is subwords, and four production bills come due because of it.
Models don’t read characters. A tokenizer splits text into chunks from a fixed vocabulary, and the model only ever sees chunk IDs. To show what that does, I trained a byte-level BPE tokenizer (the same algorithm family GPT models use) on 110 KB of Shakespeare: start from the 256 possible bytes, then repeatedly merge the most frequent adjacent pair, 420 times. Its first merges were “e␣”, “th”, “t␣”, “s␣” and “ou”. Here is how it splits six strings:
To be, or not to be, that is the question.
To␣be,␣or␣not␣to␣be,␣that␣is␣the␣question.
42 characters, 16 tokens
strawberry
strawberry
10 characters, 7 tokens
Transformers use self-attention.
Transformers␣use␣self-attention.
32 characters, 18 tokens
12345.67
12345.67
8 characters, 8 tokens
{"amount": 1}
{"amount":␣1}
13 characters, 9 tokens
नमस्ते
E0A4A8E0A4AEE0A4B8E0A58DE0A4A4E0A587
6 characters, 18 bytes, 18 tokens
Each row is a bill you’ll pay in production:
- Letters are invisible. “strawberry” arrives as seven opaque pieces, not ten letters, so “count the r’s” fights the representation itself.
- Numbers split arbitrarily. This tokenizer learned no digit merges, so 12345.67 is eight tokens; real tokenizers chunk digits in their own ways, which is one reason models are flaky at arithmetic and exact copying of figures.
- Formatting costs tokens. The braces, quotes and colon of a tiny JSON object are billed like words.
- Other languages cost more. The Hindi greeting is 6 characters but 18 bytes in UTF-8, and with no Devanagari in the training text, every byte stays its own token: 3 tokens per character. Production tokenizers are trained on multilingual web text with vocabularies of 50K–200K tokens, so the gap is smaller, but non-English text still typically costs more tokens for the same meaning.
Notice too that modern English (“Transformers use self-attention.”) splits into more pieces per character than Shakespeare’s line: a tokenizer compresses best the text it was trained on. Chapter 6 builds this tokenizer step by step.
Common take“The model is bad at spelling.”
Sharper take“I check whether the task is fighting the tokenizer before blaming the model.”
2.3Embeddings
Token IDs become vectors, and meaning becomes geometry, once there’s enough data.
Each token ID looks up a learned vector, with thousands of dimensions in a large model and 16 in the tiny one. Training pushes tokens that behave similarly toward each other, and every layer then remixes these vectors using context, so by the middle of the network “bank” already leans toward rivers or money depending on its neighbors.
The geometry is earned, not given. Here are the nearest neighbors, by cosine similarity, of three characters in the tiny model’s embedding table:
| Character | Nearest neighbors (cosine similarity) | Reading |
|---|---|---|
| “t” | “T” 0.62, “h” 0.50, “,” 0.42 | Learned: “t” and “T” behave alike |
| “a” | “i” 0.41, “T” 0.39, “’” 0.31 | Partly learned: another vowel comes first |
| “q” | “B” 0.76, “K” 0.61, “new line” 0.52 | Noise: “q” is too rare to have learned anything |
“t” and “T” ended up close because they behave alike in the text. “q” sits next to “B” and “K” for no linguistic reason: it appears so rarely in a million characters that its vector barely moved from its random start. That is the whole story of embedding quality in miniature, and it’s why production embedding models train on billions of examples. Chapter 14 uses the same idea at the level of whole passages: one vector per text, similarity as distance, which is the backbone of vector search and RAG.
In short: meaning as position, similarity as distance.
2.4Attention
Every token scores every earlier token, and the work grows as n².
This is how “it” finds its antecedent, and it’s the n² tax behind long-context pricing and latency. Every layer and every head computes a score for every pair of tokens:
| Prompt length | Pairs scored per layer and head | Relative work |
|---|---|---|
| 2,000 tokens | 4 million | 1× |
| 20,000 tokens | 400 million | 100× (10× the input) |
| 200,000 tokens | 40 billion | 10,000× (100× the input) |
The causal mask halves the count, since each token only looks backward, but the growth stays quadratic. Two consequences: prefill time and cost climb steeply with prompt length (section 2.7), and long context is not reliable context. Models tend to use the start and end of a long window better than the middle, the effect known as “lost in the middle,” which needle-in-a-haystack tests measure.
Common take“The new model has a million-token context, so we can drop RAG.”
Sharper take“I use long context when the whole input genuinely matters, and retrieval when only slices do. Attention quality and prefill cost both argue for slices.”
2.5Position
Attention is order-blind, so position has to be injected, and how it’s injected decides how far context stretches.
Attention compares tokens by content alone. Without extra information, “dog bites man” and “man bites dog” look the same to it. So every transformer adds positional information, and the method matters for long context:
| Method | Idea | Where you’ll meet it |
|---|---|---|
| Sinusoidal | Add fixed sine and cosine waves of different frequencies to each position | The original 2017 Transformer |
| Learned absolute | Learn one vector per position, up to a maximum length | GPT-2, and your Chapter 7 model |
| RoPE (rotary) | Rotate query and key vectors by position-dependent angles, so their dot product depends on relative distance | Llama and most current open models |
| ALiBi | Penalize attention scores in proportion to distance | BLOOM, MPT |
Context windows grew from a few thousand tokens to hundreds of thousands largely by stretching RoPE: models trained on shorter sequences are extended by rescaling the rotation frequencies (position interpolation, NTK-aware scaling, YaRN) and then trained a little on long documents. The practical consequence: advertised context is not effective context. Recall and reasoning degrade over long ranges in model-specific ways, so test long-range behavior on your own tasks before you design around a big window (Chapter 20).
Common take“It supports 200K tokens, so it can handle our documents.”
Sharper take“Advertised context isn’t effective context. I measure recall at the depths and lengths my product actually uses.”
2.6Sampling knobs
The knobs reshape the distribution before the dice roll.
After the context “␣th”, the tiny model emits one logit per character. Softmax turns them into the probabilities below: “e” is likely (the, thee, then), “a”, “i”, “o” and “y” follow (that, this, thou, thy). Temperature divides the logits before softmax: below 1 it sharpens the distribution, above 1 it flattens it, and near 0 it becomes greedy argmax. Top-p keeps the smallest set of tokens whose probabilities add up to p, renormalizes, and cuts off the weird tail regardless of temperature. Move the sliders:
Effective choices: 4.00. Top-p keeps 65 of 65 characters.
Decision rule: temperature 0–0.3 for anything with a right answer (extraction, JSON, classification); 0.7–1.0 for prose variety. Tune temperature or top-p deliberately, not both blindly: both narrow the distribution, and stacking them makes behavior hard to reason about. Two facts worth remembering: temperature 0 means greedy, not correct, because the top token can be confidently wrong; and even temperature 0 isn’t perfectly reproducible in production, because GPU batching and floating-point order introduce nondeterminism (Chapter 24).
2.7KV cache
Prefill versus decode, the two-phase machine under your latency metrics.
The trick: each token’s key and value vectors are computed once and cached, so decode steps attend over the cache instead of reprocessing the whole sequence.
| Prefill | Decode | |
|---|---|---|
| Processes | The entire prompt, in parallel | One new token at a time |
| Bound by | Compute (FLOPs, plus the n² attention) | Memory bandwidth (reading weights and cache) |
| Sets which metric | Time to first token (TTFT) | Tokens per second |
| Grows with | Prompt length | Output length |
| Levers | Shorter prompts, prompt caching | Batching, quantization, smaller models |
And the cache is why GPUs run out of room. For a Llama-3-8B-class model in fp16: 2 (keys and values) × 32 layers × 8 KV heads × 128 dimensions × 2 bytes ≈ 128 KB per token. An 8K-token conversation holds about 1 GB of cache.
Common take“The model is slow.”
Sharper take“TTFT is a prefill problem and throughput is a decode problem. I optimize them separately.”
2.8Mixture of experts
Total parameters set the memory bill, active parameters set the compute bill.
Many current large models replace each transformer block’s single MLP with several “expert” MLPs and a small router that sends each token to a few of them. Mixtral 8x7B, for example, has about 47B parameters in total but uses about 13B per token; DeepSeek-V3 has 671B in total and activates about 37B.
What that means in practice:
- Self-hosting is a memory problem. Every expert has to sit in GPU memory, so a large MoE model needs multi-GPU serving even though each token is computed like a much smaller dense model.
- Per-token compute is small. Throughput and API pricing track active parameters, which is why MoE models can be fast and cheap for their capability.
- Batching gets uneven. Tokens in a batch pile onto popular experts, so serving systems balance load across them.
- The parameter count in a headline needs a follow-up question: total or active?
Common take“It’s a 47B model, so it’s as expensive to run as a dense 47B model.”
Sharper take“Memory follows total parameters and compute follows active ones. That’s 47B to hold in memory and about 13B of work per token.”
2.9Training stages
Pretraining, SFT, preference tuning, RL: four stages, four questions answered.
| Stage | Data | Objective | “What is 2 + 2?” becomes |
|---|---|---|---|
| Pretraining | Trillions of tokens of web text, code and books | Predict the next token | “What is 3 + 3? What is 4 + 4? Answers on page 12.” It’s a document continuer, and quizzes are documents. |
| Supervised fine-tuning (SFT) | Tens of thousands to millions of curated instruction–response pairs | Imitate good answers | “4.” It learned the assistant format. |
| Preference tuning (RLHF, DPO) | Human or AI rankings of candidate answers | Produce what raters prefer | “4! Happy to help with anything else.” It learned taste, tone and refusals. |
| RL with verifiable rewards | Problems whose answers can be checked: math with known results, code with tests | Maximize the verifier’s reward | Works through the problem step by step before answering. This stage produced reasoning models (Chapter 10). |
Underneath all four: scale. Capability came from scaling parameters, data and compute together. Training costs about 6 × parameters × tokens FLOPs, and the Chinchilla result suggests about 20 training tokens per parameter for the best model at a fixed compute budget. Modern models deliberately train far beyond that, because a smaller model trained longer is cheaper to serve: Llama 3’s 8B model saw roughly 15 trillion tokens, close to 1,900 per parameter (Chapter 8).
Why the later rows run your production life: refusals are learned preferences, not rules, which is why phrasing can flip them and why jailbreaks exist (Chapter 26). Sycophancy is a preference-tuning scar: raters reward agreeableness, so models fold under pushback even when they were right, which matters when you build LLM judges (Chapter 23). And provider “model updates” are often post-training changes, which explains Chapter 1’s silent-regression war story.
2.10Context budget
The context window is a hard buffer: budget it like memory, with an allocator.
The window is a hard limit on prompt plus output tokens combined, and everything competes for it. Here is a real product’s allocation in a 128K window:
The whole 128K window: 21,500 tokens in use (17%)
Zoom into the 21,500 in use
- System prompt 1,200
- Tool schemas 2,500 (these get large fast)
- Few-shot examples 1,800
- Retrieved chunks 6,000
- Conversation history 8,000, the only slice that grows every turn
- Answer headroom 2,000
Why the allocator view matters. Naive chat apps hit the edge and either error out or silently drop the oldest messages: “the bot forgot the user’s name after 40 turns” is history truncation, not model amnesia, and real products summarize or window history deliberately. Placement matters too, because of section 2.4: put instructions and the freshest facts near the start or end. And context is a cost surface: every turn re-sends the whole history, so a 100-turn chat bills the same prefix 100 times unless prompt caching absorbs it.
Common take“We have 128K tokens, so space isn’t a problem.”
Sharper take“Every subsystem gets a slice, and I know who’s overspending.”
2.11Hallucination
Hallucination, assembled from parts, with fixes ranked.
Three ingredients from this chapter combine into the famous behavior. The loop must always emit a token, so there is no native “I don’t know” state (section 2.1). The pretraining objective rewards the plausible continuation, and truth was never the target (section 2.9). Sampling then rolls dice over that distribution, and even the top token can be confidently wrong (section 2.6). Fluent, confident and wrong is the machine working exactly as designed. The opening figure shows it at toy scale: Shakespeare-shaped words that mean nothing.
| Rank | Fix | Mechanism | Honest size |
|---|---|---|---|
| 5 (weakest) | Prompt scolding: “do not make things up” | Nudges the distribution slightly | Marginal; never load-bearing |
| 4 | Lower temperature | Less variance | Fixes inconsistency, not wrongness |
| 3 | An abstention path: “answer only from the provided context, otherwise say you don’t know” | Gives the loop a legal way out | Works decently, but only when context exists |
| 2 (strong) | Grounding: retrieval and tools (Chapters 15 and 18) | Puts the truth in context, so the truth becomes the likely continuation | The single biggest lever |
| 1 (backstop) | Verification: evals, citation checks, judges (Chapter 23) | Catches what slips through | A safety net, not prevention; you need both |
Common take“We told the model not to hallucinate.”
Sharper take“I make truth the likely continuation with grounding, give the model permission to abstain, and verify the residual. Scolding is decoration.”
Key takeaways
- An LLM is a next-token loop. Hallucination is that loop working as designed without grounding, not a malfunction.
- Hallucination fixes, ranked: scolding is decoration, temperature fixes variance not truth, grounding makes truth the likely continuation, evals catch the residual.
- TTFT is a prefill problem; tokens per second is a decode problem. The KV cache is the line between them.
- Concurrency on a GPU is capped by KV-cache memory, not by how fast the model is. That’s the problem PagedAttention solves.
- Long context isn’t reliable context: attention blurs the middle and prefill grows quadratically. That’s the mechanical case for retrieval.
- Temperature 0 means greedy, not correct, and not even perfectly reproducible on real GPUs.
- In a mixture of experts, memory follows total parameters and compute follows active ones.
- Refusals live in the post-training layer: learned preferences, not rules. That’s why guardrails live outside the model.
Check your understanding
-
Your service’s p95 time to first token crept from 400 ms to 6 s over four weeks. Tokens per second per request is flat, concurrency is flat, and the model is unchanged. Using the prefill/decode table, name what almost certainly grew, the log field that proves it, and two fixes at different layers.
Answer outline
Prompt length grew: TTFT is set by prefill, and decode is unchanged. The usual culprits are accumulating conversation history, more retrieved chunks, or growing tool schemas. Prove it with input tokens per request (prompt tokens) over the same four weeks, broken down by component if you log them. Prompt-side fix: summarize or window history, cap retrieved chunks, prune tools. Infra-side fix: prompt caching for the stable prefix, or more prefill capacity.
-
An invoice-extraction endpoint had a steady 0.2% JSON-parse failure rate for months. The week after someone raised temperature to 0.9 “for better reasoning,” failures jump to 6%, and separately, amounts like 12345.67 are sometimes wrong even on responses that parse. Name the two failure modes, the mechanism behind each, and why fixing the first won’t touch the second.
Answer outline
The parse failures are sampling variance (section 2.6): a flatter distribution picks malformed tokens more often. Fix with low temperature plus structured outputs and schema validation. The wrong amounts are tokenization (section 2.2): digits arrive in arbitrary chunks, so copying figures exactly is error-prone at any temperature. Fix by extracting numbers deterministically from the source text and validating the model’s amounts against it. Lowering the temperature makes the wrong amounts consistent, not correct.
-
Leadership replaces your top-5 retrieval with “paste all 800 support articles into every request” on a very long-context model. Golden-set accuracy drops from 91% to 78%, correct answers cluster on articles that happened to land near the start of the paste, and cost per request rises 12×. Explain both symptoms mechanically, do the rough token math, and name the one scenario where pasting everything wins.
Answer outline
Accuracy and the position effect come from attention (section 2.4): with hundreds of thousands of tokens competing, relevant passages get diluted, and the middle of the window is used worst. Token math: at roughly 1,000 tokens per article, that’s about 800K input tokens per request against about 3–5K for top-5 retrieval, so prefill cost and TTFT explode; prompt caching on the static corpus prefix is likely why the bill rose “only” 12×. Pasting everything wins when the corpus is small, stable and cacheable, traffic is low, and questions genuinely need synthesis across many documents at once.
Further reading
- Chip Huyen, AI Engineering: chapter 2, on how foundation models are trained, how architecture and size are chosen, post-training, and sampling.
- Hands-On Large Language Models (Alammar and Grootendorst): chapters 1–3, on tokens, embeddings and the inside of a transformer.
- Andrej Karpathy, “Deep Dive into LLMs like ChatGPT” (video), the whole pipeline from pretraining data to post-training in one sitting.