llm.guideChapter 2How LLMs Work: The Mechanical Model

How LLMs Work: The Mechanical Model

The next-token loop, tokens, attention, the KV cache and hallucination, mechanically.

Part 1: Orientation. 11 sections, about 15 minutes.

MIO:↵Wawn·dearamyest·be·and·sine↵For·Cramt.↵↵PARETHE↵NICHAUS
MIO:↵Wawn·dearamyest·be·and·sine↵For·Cramt.↵↵PARETHE↵NICHAUS
Sixty characters generated one at a time by the tiny model you build in Chapter 3. Under each character, the bar is the probability the model gave the character it picked: tall bars are predictable continuations, short bars are dice rolls. ↵ marks a new line and · a space.

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
Tokens so farThe␣cat␣sat␣onjust addedModelone forward passProbabilities␣on0.41␣down0.22␣quietly0.08␣in0.0750,000 other tokens: 0.22Sampletemperature Tstream it to the userappend the sampled token, then run the whole loop againor stop:end tokenor limit
Figure 2.1 The loop the code runs, with illustrative probabilities. Nothing outside it checks facts or plans ahead; the only choice made at each step is one sample from this distribution.

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

Figure 2.2 Real output of a byte-level BPE tokenizer trained on 110 KB of Shakespeare with 420 merges (a vocabulary of 676). ␣ marks a space inside a token; orange chips are raw bytes the tokenizer never learned to merge.

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:

CharacterNearest neighbors (cosine similarity)Reading
“t”“T” 0.62, “h” 0.50, “,” 0.42Learned: “t” and “T” behave alike
“a”“i” 0.41, “T” 0.39, “’” 0.31Partly learned: another vowel comes first
“q”“B” 0.76, “K” 0.61, “new line” 0.52Noise: “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.

token id“bank” → 4,512Embedding tableone learned row per tokena vector16 numbers here,thousands at scale“river bank”after a few layers:near water, shore“bank loan”after a few layers:near money, account
Figure 2.3 From id to meaning. The table gives every occurrence of a token the same starting vector; context, added layer by layer, pulls it apart.

2.4Attention

Every token scores every earlier token, and the work grows as n².

ThecatsatonthematThecatsatonthematattends to (earlier tokens only)grey: masked, the future is invisible
Figure 2.4 Each row is one token scoring all earlier tokens for relevance, then blending the relevant ones. Darker cells show the kind of link attention learns: “sat” looks back at “cat”, and “mat” at the scene.

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 lengthPairs scored per layer and headRelative work
2,000 tokens4 million1×
20,000 tokens400 million100× (10× the input)
200,000 tokens40 billion10,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:

MethodIdeaWhere you’ll meet it
SinusoidalAdd fixed sine and cosine waves of different frequencies to each positionThe original 2017 Transformer
Learned absoluteLearn one vector per position, up to a maximum lengthGPT-2, and your Chapter 7 model
RoPE (rotary)Rotate query and key vectors by position-dependent angles, so their dot product depends on relative distanceLlama and most current open models
ALiBiPenalize attention scores in proportion to distanceBLOOM, 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).

query at 2key at 5positions 2 and 5: three apartquery at 7key at 10positions 7 and 10: three apartsame angle between them,so the same attention score
Figure 2.5 Rotary position embeddings in two dimensions. Both pairs are three positions apart, so the rotation between query and key is the same, and only relative distance reaches the score.

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:

e55.6%
a17.5%
i10.0%
o7.0%
y6.9%
r1.4%
u0.8%
space0.2%
other 570.6%

Effective choices: 4.00. Top-p keeps 65 of 65 characters.

Figure 2.6 The tiny model’s real next-character distribution after “␣th”. “Effective choices” is the perplexity of the distribution, eentropy: how many equally likely options it behaves like.

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.

timePrefillwhole prompt at oncet1t2t3t4t5t6Decode: one token per stepfirst token: TTFTspeed here: tokens per secondgrows with prompt length
Figure 2.7 Prefill processes the whole prompt in one parallel pass and fills the cache; decode then produces one token per step, reading the cache instead of recomputing everything.

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.

PrefillDecode
ProcessesThe entire prompt, in parallelOne new token at a time
Bound byCompute (FLOPs, plus the n² attention)Memory bandwidth (reading weights and cache)
Sets which metricTime to first token (TTFT)Tokens per second
Grows withPrompt lengthOutput length
LeversShorter prompts, prompt cachingBatching, 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.

18645121K4K16K64K128Kconversations that fit at oncetokens per conversationbelow this line, not even one fits24 GB card (8 GB free)80 GB card (64 GB free)8K chats: 8 at once
18645121K8K128Kconversations that fit at oncetokens per conversationbelow this line, not even one fits24 GB card (8 GB free)80 GB card (64 GB free)8K chats: 8 at once
Figure 2.8 Concurrency is capped by cache memory. On a 24 GB card with about 16 GB taken by the weights, the 8 GB left holds eight 8K-token conversations at once, and a single 128K-token conversation doesn’t fit. Computed from the 128 KB-per-token figure above.

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.

tokenrouterE1E2E3E4E5E6E7E8all 8 experts sit in memory; only 2 run for this tokenmemory follows total parameters, compute follows active ones
Figure 2.9 A router picks 2 of 8 experts for each token at each MoE layer. Different tokens pick different experts, so all of them must stay loaded.

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.

StageDataObjective“What is 2 + 2?” becomes
PretrainingTrillions of tokens of web text, code and booksPredict 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 pairsImitate good answers“4.” It learned the assistant format.
Preference tuning (RLHF, DPO)Human or AI rankings of candidate answersProduce what raters prefer“4! Happy to help with anything else.” It learned taste, tone and refusals.
RL with verifiable rewardsProblems whose answers can be checked: math with known results, code with testsMaximize the verifier’s rewardWorks 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.

Pretrainingtrillions of tokens of webtext, code and booksWhat does text look like?Supervised fine-tuningcurated instruction andresponse pairsHow does an assistantanswer?Preference tuningrankings of candidateanswersWhich answer do peopleprefer?RL, verifiable rewardsproblems with checkableanswersHow do I reach a rightanswer?compute: pretraining is by far the largest share; the later stages are small but change behavior most
Figure 2.10 Four stages, four questions. The bar is a qualitative picture of compute, not a measurement: the share spent after pretraining has been growing with reinforcement learning.

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:

Figure 2.11 An example allocation in a 128K window, drawn to scale. It looks fine until the history compounds.

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.

RankFixMechanismHonest size
5 (weakest)Prompt scolding: “do not make things up”Nudges the distribution slightlyMarginal; never load-bearing
4Lower temperatureLess varianceFixes inconsistency, not wrongness
3An abstention path: “answer only from the provided context, otherwise say you don’t know”Gives the loop a legal way outWorks 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 continuationThe single biggest lever
1 (backstop)Verification: evals, citation checks, judges (Chapter 23)Catches what slips throughA safety net, not prevention; you need both
5 Prompt scoldingnudges the distribution slightly4 Lower temperaturefixes inconsistency, not wrongness3 An abstention pathlets the model say it doesn’t know2 Grounding in sourcesanswers built from retrieved text1 Verificationclaims checked against sources in code
Figure 2.12 The ranked fixes, drawn by how much each one holds. Only the bottom two change what the model has to work from.

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

  1. 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.

  2. 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.

  3. 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.

↑↓ to move↵ to openesc to close