CONTENTS
CHAPTER 2

How LLMs Actually Work

9 MIN READ

You can build with LLMs without knowing how they work, the same way you can use React without knowing about the fiber reconciler. But when things go wrong (and with LLMs they go wrong in strange ways), understanding the machine lets you reason about causes instead of guessing. This chapter builds the mental model from the ground up.

2.1 The one-sentence version

A large language model is a function that takes a sequence of tokens and outputs a probability distribution over the next token. Text generation is calling that function in a loop: sample a token, append it, repeat.

def generate(model, prompt_tokens, max_new_tokens):
    tokens = list(prompt_tokens)
    for _ in range(max_new_tokens):
        probs = model(tokens)          # distribution over ~100k–200k vocab entries
        next_token = sample(probs)     # pick one (temperature, top-p, ...)
        tokens.append(next_token)
        if next_token == END_OF_TEXT:
            break
    return tokens

Everything else (chat, reasoning, tool use, agents) is built on this loop. Keep it in mind; many confusing behaviors become obvious once you remember that the model is always just predicting the next token given everything before it.

2.2 Tokens: the model’s alphabet

Models don’t see characters or words; they see tokens, chunks produced by an algorithm like Byte-Pair Encoding (BPE). BPE starts with individual bytes and repeatedly merges the most frequent adjacent pairs into new tokens, building a vocabulary of roughly 50k–250k entries.

"Unbelievable React Native performance!"
→ ["Un", "bel", "iev", "able", " React", " Native", " performance", "!"]

Why this matters in practice:

  • Cost and limits are measured in tokens. In English, one token is about ¾ of a word on average. Code, non-English languages, and unusual strings use more tokens per character.
  • Character-level tasks are hard. “How many r’s in strawberry?” was famously tricky because the model sees straw + berry, not letters. Spelling, reversing strings, and counting characters fight the tokenization.
  • Numbers tokenize oddly. 1234567 might split into 123, 456, 7. This is part of why arithmetic used to be unreliable, and why giving models a calculator or code tool helps.
  • Whitespace and formatting are tokens too. Trailing spaces and odd formatting in prompts change what the model sees.

2.3 Embeddings: turning tokens into meaning

Each token ID maps to a learned vector, its embedding: a list of a few thousand numbers. Initially random, these vectors are adjusted during training so that tokens used in similar contexts end up near each other in this high-dimensional space.

The classic illustration: vector("king") - vector("man") + vector("woman") ≈ vector("queen"). Directions in the space encode concepts. This same idea powers semantic search (Chapter 6): embed documents and queries, then find the nearest neighbors.

Concept to really internalize: a neural network represents everything (words, ideas, facts, intentions) as vectors, and does all its “thinking” as geometric transformations of those vectors. This is the “linear algebra” in “you need linear algebra.”

2.4 The Transformer

The architecture behind essentially all modern LLMs is the Transformer (Vaswani et al., 2017, “Attention Is All You Need”). Modern LLMs use the decoder-only variant. Here’s the structure:

tokens → [Embedding] → x
         ┌──────────────────────────────┐
         │  Transformer Block  × N      │   (N ≈ 30 to 100+ layers)
         │                              │
         │   x = x + Attention(Norm(x)) │   ← tokens exchange information
         │   x = x + MLP(Norm(x))       │   ← each token "thinks" individually
         └──────────────────────────────┘
         → [Norm] → [Unembedding] → logits over vocabulary → softmax → probabilities

Two operations alternate: attention (communication between positions) and the MLP (computation at each position). Let’s take them one at a time.

Self-attention: how tokens talk to each other

Consider: “The trophy didn’t fit in the suitcase because it was too big.” To understand “it,” the model must look back and decide it refers to “trophy.” Attention is the mechanism for that.

For every token, the model computes three vectors by multiplying its current representation by three learned matrices:

  • Query (Q): “What am I looking for?”
  • Key (K): “What do I contain?”
  • Value (V): “What information will I pass along if attended to?”

Then for each token:

  1. Compare its query against every previous token’s key (a dot product, which measures similarity).
  2. Turn those scores into weights that sum to 1 (softmax).
  3. Take the weighted sum of the values.

Attention(Q,K,V)=softmax(QK⊤dk)V\text{Attention}(Q,K,V) = \text{softmax}\left( \frac{QK^{\top}}{\sqrt{d_{k}}} \right)V

The dk\sqrt{d_{k}} keeps the dot products from growing too large as dimensions increase, which would make the softmax saturate. In a decoder, a causal mask stops each token from attending to future tokens, because the model must predict the next token without peeking at it.

Multi-head attention runs many of these in parallel (e.g., 32–128 heads), each with its own Q/K/V matrices, so different heads can specialize: one tracks syntax, another coreference, another “copy the token that followed this pattern last time” (the famous induction heads, which are part of how in-context learning works).

The React analogy. Think of attention as a fully dynamic context system. Every component (token) broadcasts what it offers (key, value) and what it needs (query), and each one subscribes to a learned, content-dependent mix of everyone upstream. The “subscriptions” are recomputed for every input.

The MLP: where knowledge lives

After attention mixes information across positions, each token’s vector passes independently through a two-layer neural network (expand roughly 4×, apply a nonlinearity, project back). Interpretability research suggests a lot of factual knowledge is stored in these MLP weights: “Paris is the capital of ___” gets completed largely by MLP layers acting like a giant soft key-value memory.

Residual stream

Notice the x = x + ... pattern. Each block adds its output to a running vector, the residual stream, rather than replacing it. A useful mental model: the residual stream is a shared scratchpad that flows through the network, and each attention or MLP layer reads from it and writes small updates back. This design is what makes very deep networks trainable.

Positional information

Attention by itself is order-agnostic; “dog bites man” and “man bites dog” would look the same. Models inject position information, today mostly via RoPE (Rotary Position Embeddings), which rotates Q and K vectors by an angle that depends on position, so relative distance affects attention scores. Techniques for extending RoPE are a big part of how context windows grew from 4k tokens to hundreds of thousands and beyond.

2.5 Training: how the weights get their values

A model with hundreds of billions of random parameters knows nothing. Training happens in stages.

Stage 1: Pretraining

Feed the model trillions of tokens of text (web pages, books, code, papers) and train it on one objective: predict the next token. The loss is cross-entropy, which measures how much probability the model assigned to the token that actually came next. Gradient descent nudges all parameters to make the correct token more likely. Repeat trillions of times.

Why does something as simple as next-token prediction produce something that looks like intelligence? Because to predict text well, you need to model whatever produced the text. Predicting the next line of a proof requires modeling the math. Predicting what a character says requires modeling their beliefs. Predicting the next line of code requires modeling the program. Compression forces understanding, or at least something that functions a lot like it.

The output is a base model: an extraordinary autocomplete that will continue any document but doesn’t follow instructions. Ask it “What is the capital of France?” and it might continue with “What is the capital of Germany? What is the capital of…” because that looks like a quiz document.

Stage 2: Post-training

Post-training turns the base model into an assistant:

  • Supervised Fine-Tuning (SFT): Train on curated examples of (prompt, ideal response) pairs. This teaches the format and style of being a helpful assistant.
  • Preference optimization (RLHF and relatives): Humans (or AI models guided by principles, as in RLAIF and Constitutional AI) compare responses. A reward model learns those preferences, and reinforcement learning optimizes the model against it. DPO and similar methods skip the explicit reward model and optimize directly on preference pairs.
  • Reinforcement Learning from Verifiable Rewards (RLVR): For domains with checkable answers (math with known solutions, code with unit tests, tasks with automatic graders), let the model attempt problems and reward correct outcomes. This is a major driver behind the leap in reasoning and coding ability since 2024, and it is central to training agentic behavior: the model attempts multi-step tasks in environments and gets rewarded for success.

Chat templates. Under the hood, a “conversation” is a single token sequence with special tokens marking roles, roughly:

<|system|>You are a helpful assistant.<|end|>
<|user|>What's 2+2?<|end|>
<|assistant|>4<|end|>

The API hides this, but knowing it explains a lot. The “system prompt” isn’t magic; it’s text at the start of the sequence that the model was trained to weight heavily. Tool calls are also just structured tokens the model emits and your code parses.

2.6 Reasoning models and test-time compute

A major development from late 2024 onward: models trained (largely via RL) to think before answering, producing a long internal chain of reasoning tokens before the final response.

Why this works: each forward pass through the network does a fixed amount of computation. A hard problem may need more computation than one pass provides. Generating intermediate reasoning tokens lets the model spend more passes, more serial computation, on the problem, and write intermediate results to a scratchpad it can attend to. RL training teaches it to use that scratchpad productively: trying approaches, checking work, backtracking.

This created a new scaling axis. Besides scaling training compute (bigger models, more data), you can scale test-time compute (let the model think longer). For engineers this means a new knob: reasoning effort or thinking budget, which trades latency and cost for accuracy.

2.7 Sampling: from probabilities to text

The model outputs probabilities; sampling picks the token:

  • Temperature scales the logits before softmax. Low (→0) makes the distribution sharper, so output is more deterministic and repetitive. High (>1) flattens it, so output is more random and creative.
  • Top-p (nucleus): sample only from the smallest set of tokens whose probabilities sum to p.
  • Top-k: sample only from the k most likely tokens.

Important: temperature 0 is not a guarantee of determinism in production APIs. Floating-point non-associativity, batching effects, and mixture-of-experts routing can all introduce variation. Design your systems to tolerate variance.

2.8 Inference mechanics that affect your engineering

Prefill vs. decode. Processing the prompt (prefill) is parallel and fast per token. Generating output (decode) is sequential, one token at a time. That’s why output tokens cost more and why time-to-first-token and tokens-per-second are separate latency metrics.

KV cache. During decoding, the keys and values for all previous tokens are cached so they aren’t recomputed. This is why long contexts consume GPU memory, and it’s the mechanism behind prompt caching: if many requests share the same prefix (system prompt, tool definitions, documents), the provider can reuse the cached KV state, which is much cheaper and faster. Design prompts with stable content first and variable content last to take advantage of it.

Mixture of Experts (MoE). Many frontier and open models replace each MLP with many “expert” MLPs and a router that sends each token to only a few of them. You get a model with huge total parameters (knowledge capacity) but much lower per-token compute.

Context windows and “context rot”. Models can accept very long inputs, but attention quality isn’t uniform. Information buried in the middle of a huge context can be used less reliably than information near the start or end, and performance tends to degrade as irrelevant content accumulates. A large context window is a capability, not a license to dump everything in. This is the root of context engineering (Chapter 5).

2.9 Why models fail the way they do

With this model in mind, common failure modes become predictable:

Failure Mechanical explanation
Hallucination The model produces plausible continuations. With no knowledge to ground an answer, “plausible-sounding fact” is still a high-probability continuation. Post-training reduces this but can’t remove it.
Sycophancy Preference training rewards responses humans liked, and humans tend to like agreement.
Knowledge cutoff Pretraining data stops at a date. The model doesn’t know what happened after unless you give it context.
Prompt sensitivity Small wording changes shift the token distribution in ways that can compound over long generations.
Losing track in long tasks Errors compound: each step conditions on previous outputs, including mistakes.
Prompt injection Instructions and data share one token stream. The model has no hard boundary between “text from my developer” and “text from a web page I fetched.”

That last one is fundamental and gets serious attention in Chapter 7.

Key takeaways

  • An LLM is a next-token probability function called in a loop. Everything else is built on that.
  • Tokens, not characters, are the unit of computation, cost, and context.
  • Transformers alternate attention (tokens share information) and MLPs (per-token computation and stored knowledge), connected through a residual stream.
  • Pretraining builds knowledge via next-token prediction. Post-training (SFT, preference optimization, RL with verifiable rewards) builds assistant behavior, reasoning, and agentic skill.
  • Reasoning models trade test-time compute for accuracy.
  • KV caching, prefill vs. decode, and context quality shape cost and latency design.
  • Failure modes like hallucination and prompt injection follow directly from the mechanics.

Exercises

  1. Use a tokenizer visualizer (search “tiktoken visualizer” or use your provider’s token-counting endpoint) to tokenize a paragraph of English, a JSON blob, a Swift function, and a sentence in another language you know. Compare token counts per character.
  2. Watch Andrej Karpathy’s “Let’s build GPT: from scratch, in code, spelled out” and code along. It is the single best investment for this chapter.
  3. Call a model API with the same prompt 20 times at temperature 0 and 20 times at temperature 1. Diff the outputs. What changes?
  4. Explain to a colleague, without notes, why prompt caching requires a stable prefix. If you can explain the KV cache, you understand it.