Source: llm ยท llm.md ยท updated 2026-07-25 ยท ๐Ÿ”’ secret gist

Synced verbatim from gist.github.com/bl9.

How an LLM Actually Works

A mental model for someone who already knows transformers on paper but can't reconcile "matrix multiplications over vectors" with "it understood what I meant."


Contents

Part I โ€” The object

Part II โ€” Putting it together

Part III โ€” How it got that way

Part IV โ€” Applied

Part V โ€” Reference


0. The one thing to unlearn first

If your intuition for "text โ†’ vector" comes from embedding models (sentence-transformers, bi-encoders, HNSW indexes), that intuition is actively blocking you.

Embedding modelTransformer LM
Output per inputOne vector for the whole textOne vector per token position
Vector meaningA point in a static semantic spaceA running computation, mid-flight
How many times writtenOnce~80โ€“120 times (once per layer)
Information flowNone between docsEvery position reads from every earlier position, at every layer
NatureA noun โ€” a stored representationA verb โ€” an unfolding process

An embedding is a photograph. A transformer forward pass is a film โ€” and the frames modify each other.

That is the whole reason one can only do retrieval while the other can write a compiler pass.


1. Concrete anchor: a real model's dimensions

Vague talk about "dimensions" is why this feels like magic. Here are actual numbers, using a Llama-3-70B-class model:

d_model (residual stream width)   8,192
layers                               80
attention heads per layer            64
head dimension                      128
MLP hidden width                 28,672
vocabulary                      128,256
context window                  128,000 tokens
total parameters             70,000,000,000

Derived facts worth internalizing:

  • Attention head computations per token: 80 ร— 64 = 5,120. Not one similarity lookup โ€” five thousand of them, each with its own learned notion of what to look for and what to bring back.
  • Parameter split: roughly 1/3 attention, 2/3 MLP. Most of the model is memory, not routing.
  • FLOPs per generated token: ~2 ร— 70B = 140 billion. For a 500-token answer, ~70 trillion floating point operations. It is not a lookup. It is a lot of computation.
  • 8,192 numbers per position. In fp16 that's 16 KB. That 16 KB is the model's entire working belief about that word in that context, at that depth.

2. Tokenization โ€” the layer everyone skips, and shouldn't

Text is split into subword tokens by BPE. Rough rule: 1 token โ‰ˆ 3.5โ€“4 characters of English.

"the tests are failing"     โ†’ ["the", " tests", " are", " failing"]        4 tokens
"unfortunately"             โ†’ ["unfort", "unately"]                        2 tokens
"strawberry"                โ†’ ["str", "aw", "berry"]                       3 tokens
"getUserByID"               โ†’ ["get", "User", "By", "ID"]                  4 tokens
"128256"                    โ†’ ["128", "256"]                               2 tokens
"่‰ฒๅณๆ˜ฏ็ฉบ"                   โ†’ ["่‰ฒ", "ๅณ", "ๆ˜ฏ", "็ฉบ"] or worse            4+ tokens

Two consequences that explain real behavior:

  1. The model cannot see letters. "strawberry" arrives as three opaque chunks. Asking it to count the r's is asking someone to count letters in a word they only ever heard spoken. This single fact explains a whole genre of "how is it so dumb about this" failures.
  2. Non-English and code are tokenized less efficiently. The same sentence in Thai or Tamil may cost 3โ€“5ร— the tokens of English. Since compute is per-token, this is also a fairness and cost issue in multilingual retrieval systems โ€” the tokenizer is a quiet source of bias before any model math happens.

Each token ID indexes a row of the embedding matrix: 128,256 ร— 8,192. That row is the starting value of the residual stream at that position. It encodes essentially nothing contextual yet โ€” just "this token, generically."

Position is added separately (modern models use RoPE, which rotates query and key vectors by an angle proportional to position, so attention naturally sees relative distance rather than absolute index).


3. The residual stream โ€” the single most important object

Picture a spreadsheet:

  • Columns = token positions in your prompt
  • Rows = layers, 80 of them, bottom to top
  • Each cell = an 8,192-dimensional vector
                 "the"     "tests"    "are"    "failing"
             โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
Layer 80     โ”‚ v80,1    โ”‚ v80,2    โ”‚ v80,3    โ”‚ v80,4    โ”‚ โ† this one becomes the prediction
             โ”œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ค
    ...      โ”‚   ...    โ”‚   ...    โ”‚   ...    โ”‚   ...    โ”‚
             โ”œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ค
Layer 2      โ”‚ v2,1     โ”‚ v2,2     โ”‚ v2,3     โ”‚ v2,4     โ”‚
             โ”œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ค
Layer 1      โ”‚ v1,1     โ”‚ v1,2     โ”‚ v1,3     โ”‚ v1,4     โ”‚
             โ”œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ค
Embedding    โ”‚ e(the)   โ”‚ e(tests) โ”‚ e(are)   โ”‚ e(failโ€ฆ) โ”‚
             โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Critically, the update rule is additive:

x โ† x + attention_output(x)
x โ† x + mlp_output(x)

Not x โ† f(x). The stream is a shared workspace that every component reads from and writes into. Nothing is overwritten; contributions accumulate.

This is why the mental model of "a bus" or "a whiteboard" is better than "a pipeline." Layer 3 can write a fact that nothing touches until layer 61 reads it. Components communicate across depth by leaving things in the stream.

Two directions of information flow:

  • Vertical (within a column): MLPs. Enrich this position's representation with knowledge.
  • Horizontal (between columns): Attention. This is the only mechanism by which positions see each other. Remove attention and you have 4 independent MLPs that have never heard of one another.

4. Attention, dissected properly

The textbook formula is softmax(QKแต€/โˆšd)V. The useful decomposition is different โ€” split it into two independent learned circuits:

The QK circuit โ€” "where do I look?"

Each position produces a query ("what am I looking for right now?") and a key ("what am I, advertised to others?"). Dot product, scaled, softmaxed over all earlier positions โ†’ attention weights.

This is exactly the retrieval you know from vector search, with three differences that change everything:

  1. The corpus is your own prompt, not a static index.
  2. The query is recomputed from the current stream state at every layer โ€” so a position's question at layer 60 is informed by what it learned at layers 1โ€“59.
  3. It runs 5,120 times per token.

The OV circuit โ€” "what do I bring back?"

Separately, each position produces a value vector, and the head has an output matrix. What gets copied back into the stream is attention_weights ร— values ร— W_O.

The decoupling is the point. What matched and what gets copied are different learned functions. A head can attend to the word "France" but write a country-code direction rather than the France representation. Retrieval systems don't do this; they return the document they matched.

Multi-head = parallel specialists

64 heads per layer, each with a 128-dim subspace. They specialize sharply:

Head typeJobObserved in
Previous-token headAttend to position iโˆ’1Every model, layer 1โ€“2
Duplicate-token headFind earlier copies of the current tokenEarly-mid layers
Induction headPattern [A][B] โ€ฆ [A] โ†’ predict [B]Layers ~2+
Name-mover headCopy a specific name to the output positionMid-late
Syntax headsSubjectโ†’verb, nounโ†’adjective, bracket matchingEarly-mid
Suppression headsActively reduce a candidate's probabilityLate

That last row is worth pausing on. Some heads exist to say no. The network implements something like negation and inhibition using attention.

Causal masking

Position i can only attend to positions โ‰ค i. This is what makes training efficient โ€” one forward pass over a 4,000-token document yields 4,000 training signals at once, each a legitimate "predict the next token" problem. It's also why the whole thing generates left to right.

KV cache โ€” why the first token is slow and the rest are fast

  • Prefill: your whole prompt is processed in one parallel pass. All keys and values for all positions are computed and cached. This is compute-bound and is the delay before the first token appears.
  • Decode: each new token attends against the cache. Only one new column is computed per step. This is memory-bandwidth-bound.

Cache size scales linearly with context length. At 128K context this is tens of GB. This is the real reason long context is expensive โ€” not the attention math, the memory.


5. The MLP โ€” where knowledge is stored

Two-thirds of the parameters live here, and the structure is a key-value memory (Geva et al., 2021):

h = GELU(W_in ยท x)        # 8,192 โ†’ 28,672 : 28,672 pattern detectors
out = W_out ยท h           # 28,672 โ†’ 8,192 : each fires, writes its associated vector back
  • Each of the 28,672 rows of W_in is a key: a direction in stream-space it detects.
  • Each corresponding column of W_out is a value: what to add to the stream when that key fires.

So: "if the stream currently contains [Paris-ness] + [capital-of-relation-active], add [France-direction]."

Multiply by 80 layers: 2.3 million key-value slots, chained so later ones read the results of earlier ones. That's the fact store โ€” and because it's composed across depth, it does multi-hop lookups, not just single retrievals.


6. Superposition โ€” the answer to "how can dimensions do this"

The intuitive objection: 8,192 dimensions can't hold millions of concepts.

The intuition is wrong, and here's the geometry.

In 8,192 dimensions you can only fit 8,192 perfectly orthogonal vectors. But if you relax to "almost orthogonal" โ€” say, any pair within 85โ€“95ยฐ โ€” you can fit an exponential number. This is the Johnsonโ€“Lindenstrauss lemma. Concretely, in d dimensions you can pack roughly exp(ฮตd) near-orthogonal directions.

At d = 8,192 that number is astronomically larger than the millions of concepts a model needs.

The tradeoff: features interfere slightly. Every feature bleeds a little noise into every other. This is tolerable if only a handful of features are active at any moment โ€” which is exactly the case, since any given token in any given context is only a few things at once. This is sparse coding, and the network learns it because it's the optimal use of limited width.

This has been verified empirically, not just theorized. Anthropic's sparse autoencoder work on Claude 3 Sonnet extracted tens of millions of interpretable directions from the residual stream: a Golden Gate Bridge feature, a "code with a security vulnerability" feature, a "sycophantic praise" feature, an "inner conflict" feature. Amplify one and the model's behavior changes accordingly and predictably.

So the correct reformulation:

A residual stream vector is not a point in an 8,192-concept space. It is a sparse sum of a few dozen active features drawn from a dictionary of ~10โท learned directions.

That reframing is what makes "8,192 numbers" stop feeling too small.


7. Circuits โ€” worked examples of the machinery

These aren't hypotheses. They've been reverse-engineered and causally verified by ablation.

7a. Induction heads โ€” the origin of in-context learning

Setup. A two-head circuit spanning two layers:

  1. A previous-token head in layer L: at each position, copies the identity of the token before it into the stream. So position i now carries "I am preceded by X."
  2. An induction head in layer L+1: its query is "find positions preceded by the token I currently am." It matches, then copies that position's own token to the output.

Net effect: given [A][B] โ€ฆ [A], predict [B].

Worked example โ€” why the model can track your made-up variable names:

const zqBuffer = new ArrayBuffer(1024);
...200 lines...
const view = new Uint8Array(zqโ–ฎ

zqBuffer appears nowhere in training data. There is no stored fact. Yet the completion is Buffer, near-certainly.

Trace:

  • Position of the final zq emits a query: "where else have I seen zq?"
  • Duplicate-token / previous-token machinery has tagged the earlier occurrence.
  • The induction head attends to the token after the earlier zq โ€” which is Buffer.
  • OV circuit copies Buffer into the output stream.
  • Unembedding turns it into a very high logit.

Why this matters far beyond variable names: induction heads generalize from exact-match copying to fuzzy, abstract pattern completion. The same circuit family is what lets few-shot prompting work. When you write:

sea otter -> loutre de mer
peppermint -> menthe poivrรฉe
plush girafe ->

induction-style heads recognize the X -> Y structure, identify the transformation as translation, and apply it. No weights changed. The "learning" happened entirely as data movement inside one forward pass.

There is a striking empirical detail: during pretraining, induction heads form abruptly at a specific point, and the loss curve visibly bends at exactly that moment. In-context learning is not a smooth emergent haze โ€” you can watch the mechanism switch on.

7b. The IOI circuit โ€” indirect object identification

Prompt: "When Mary and John went to the store, John gave a drink to ___"

Correct answer: Mary. Both names appear; the model must pick the one that isn't the repeated subject. The full circuit was reverse-engineered in GPT-2 small (Wang et al., 2022) โ€” 26 heads in three groups:

GroupFunction
Duplicate-token headsDetect that John appeared twice
S-inhibition headsWrite a signal that suppresses attention to John
Name-mover headsAttend to the remaining name and copy it to the output

So the algorithm is literally: find all names โ†’ detect which one is duplicated โ†’ inhibit it โ†’ copy the survivor.

This is a genuine algorithm, discovered by gradient descent, implemented in attention patterns, verified by ablating individual heads and watching the answer flip to John. Nobody designed it. Nobody wrote "if duplicate then suppress." It was the lowest-loss way to model English discourse.

When you ask "how does it know what I meant" โ€” this is the shape of the answer. Thousands of circuits like this, composed.


8. Depth = composition, and where intent physically lives

A rough map of what happens as you climb the 80 layers:

LayersWhat forms
0โ€“5Detokenization: reassembling word pieces, resolving word sense, basic syntax
5โ€“25Phrases, entities, grammatical relations, factual lookups
25โ€“55Abstract task representation, relationships between entities, register and intent, plan formation
55โ€“75Concretizing the plan into specific content
75โ€“80Converting to a distribution over the 128K vocabulary

The middle band is the interesting one, and there's direct evidence for it.

Task vectors / function vectors

Take a few-shot prompt for some task (say, "translate English to French"). Read the residual stream at a mid layer at the final position. Average across many examples. You get a single vector.

Now take a completely unrelated prompt, with no examples and no instructions, and add that vector into the stream at the same layer.

The model starts translating to French.

Let that land. There is a specific vector, in a specific place, that is the concept "the task right now is: translate to French," represented independently of any wording that expressed it. You can extract it, store it, transplant it.

This is the mechanistic answer to "how does it know what I meant." Your intent stops being words and becomes a vector somewhere in the middle of the network. Different phrasings of the same request converge to nearby vectors โ€” which is exactly why "make this faster," "this is too slow," and "optimize perf here" all get you the same kind of help.

Logit lens โ€” reading the model's mind mid-computation

You can apply the final unembedding matrix to intermediate layers to see what the model would predict if it stopped there. Typical trajectory for a factual question:

Layer 10 : generic function words ("the", "a", "of")
Layer 30 : right category, wrong specifics ("city", "place", "region")
Layer 55 : right answer starting to appear, low confidence
Layer 70 : right answer dominant
Layer 80 : sharpened, high confidence

The prediction is built up, progressively refined. It is not looked up.


9. From vector to token: the output side

At the last position, after layer 80:

  1. Unembed: logits = W_U ยท x โ†’ 128,256 raw scores.
  2. Softmax with temperature: p = softmax(logits / T). T=0 โ†’ always the argmax (deterministic). T=1 โ†’ the raw learned distribution. T>1 โ†’ flatter, more random.
  3. Truncate: top-k (keep the k best) or top-p / nucleus (keep the smallest set summing to p, typically 0.9โ€“0.95). This cuts the long tail of garbage tokens.
  4. Sample one token.
  5. Append it to the input and run the entire thing again.

That last step is the loop, and it's why the model can't un-say something. Each token is committed and becomes input. There's no backtracking, no edit buffer.

Dissecting an actual distribution. For the prompt "The tests are failing after I added the cache":

token          logit    prob
" layer"        18.2    0.41
" ."            17.6    0.23
" to"           16.9    0.11
" middleware"   16.1    0.05
" and"          15.8    0.04
" invalidation" 15.4    0.03
...128,250 more tokens, together ~0.13

Two things to notice:

  • The model is never certain. Even "obvious" continuations carry substantial mass elsewhere. Confidence is a distribution, not a boolean.
  • The whole answer is present in embryo. The distribution already encodes "this is a technical debugging context, in English, mid-sentence, about caching." Every subsequent token narrows further.

10. Full worked trace

Prompt: "the tests are failing after I added the cache layer"

Note what is not in that sentence: no question mark, no request, no "please help," no specification of what output you want. Yet you'd get back a ranked list of likely causes with debugging steps. Let's trace how.

Prefill โ€” layers 1 through 80, at the final position

DepthWhat accumulates in the stream
L1โ€“4Token pieces reassembled. " cache" is disambiguated โ€” CPU cache? cache-money? Attention to " tests", " layer" resolves it toward software caching.
L5โ€“12Syntax: tests is the subject, failing the predicate, after establishes temporal-causal ordering. added the cache layer binds as a completed action by the speaker.
L12โ€“25Domain features light up: software-engineering, test-suite, caching, regression. Related knowledge is pulled in by MLPs: cache invalidation, TTL, memoization, test isolation, singletons, mocking.
L25โ€“40Discourse-intent features. This is the crucial band. The stream acquires: speaker-is-blocked, implicit-request-for-diagnosis, causal-hypothesis-expected, speaker-is-a-developer, register-is-technical-peer, not-a-beginner (they said "cache layer," an architectural term).
L40โ€“60Response plan. Features for enumerate-probable-causes, ordered-by-likelihood, include-diagnostic-steps, format-as-list, assume-familiarity-with-testing-tools. Simultaneously, specific hypotheses get ranked: shared cache state leaking across tests, cache not cleared between runs, stale reads, serialization of cached objects, timing/TTL flakiness, a singleton surviving teardown.
L60โ€“75Concretization. Abstract "shared state leaks across tests" becomes lexical material โ€” words like isolation, teardown, fixture, singleton gain probability mass.
L75โ€“80Projection to vocabulary.

Where did the "request" come from?

Nowhere in the text. It was inferred, and here's the mechanism, not the hand-wave:

During pretraining, the model saw millions of instances of this exact discourse pattern โ€” a Stack Overflow post, a Slack thread, a GitHub issue, an IRC log โ€” where someone states a symptom and the very next thing in the document is a diagnostic response. To minimize prediction loss on those documents, the model had to learn: "symptom stated by developer" โ†’ "diagnosis follows."

Post-training then sharpened which of the many possible continuations it produces (a helpful diagnosis rather than, say, a snarky reply or another user's unrelated question), but the underlying inference was already there in the base model.

Your intent was reconstructed from statistical regularities in how humans structure conversations. Not from a rule. Not from an intent classifier. From compression.

Decode โ€” dissecting the actual answer

Suppose the response begins:

"A few likely culprits, roughly in order of how often they bite:

  1. Cache state leaking between tests โ€” the cache isn't cleared in teardown, so test B sees what test A wrote."

Dissect where each part came from:

FragmentOrigin
"A few likely culprits"The enumerate-causes plan feature from L40โ€“60, plus a register feature choosing casual-technical over formal
"roughly in order of"An epistemic-hedging feature โ€” the model represents its own uncertainty and, post-RLHF, expresses it
"1."Format feature; list structure was decided at L~50, before any token was emitted
"Cache state leaking between tests"Highest-ranked hypothesis. This ranking came from frequency in training data โ€” this is genuinely the most common cause, and the model absorbed that base rate
"isn't cleared in teardown"MLP knowledge: cache + test + state-leak โ†’ teardown is the associated concept
"test B sees what test A wrote"Concretization โ€” the abstract feature rendered as a minimal example, a style pattern learned from good technical writing

Nothing here was retrieved. There is no stored answer to "tests failing after cache layer." Every token was computed. The reason it's right is that the machinery for reasoning about cache-and-test interactions is genuinely encoded in the weights, in the form of features and circuits that generalize.


11. Why next-token prediction produces intent modeling

This is the philosophical crux, and it's actually rigorous.

The setup. Minimize โˆ’log P(next token | all previous tokens) over ~15 trillion tokens of human-written text.

The critical observation: that text was not generated randomly. It was generated by humans with goals, knowledge, moods, expertise levels, and plans. The text is a downstream shadow of those hidden variables.

So to predict it well, you must model the hidden variables. There is no shortcut:

  • To predict the next line of a Stack Overflow answer, you must model what the asker needs.
  • To predict the next token of a legal brief, you must model the argument being constructed.
  • To predict the closing brace of a C function, you must model the scope structure.
  • To predict the punchline, you must model what the audience finds surprising.
  • To predict the next move in a chess transcript, you must model the position.

And memorization is unavailable. 70B parameters versus 15T training tokens is roughly 200 tokens compressed per parameter. A lookup table is not on the table. The only representation that fits is general machinery.

This gives the chain:

accurate prediction โ†’ requires compression โ†’ requires generalization โ†’
requires modeling the generating process โ†’ and the generating process is
a human with an intent

Intent modeling is not a feature that was added. It is the lowest-loss solution to the objective, and gradient descent found it because it was cheapest.

The same argument explains capabilities that look unrelated to text: arithmetic, code execution traces, spatial reasoning, theory of mind. Each is a compression win on some slice of the corpus.


12. In-context learning โ€” learning without learning

Weights are frozen at inference. Nothing is stored. Yet:

Prompt:
  gxlfj -> 5
  hqm   -> 3
  aabbccdd -> 8
  zzz ->

Answer: 3. The task ("count characters") was never named, never trained on with these strings, and no gradient was computed.

What actually happens: induction-style heads recognize the input -> output structure, mid-layer circuits form a task representation from the demonstrations, and later layers apply it to the new input. The forward pass implements a learning algorithm.

There's evidence that in some settings this is literally gradient descent implemented inside the attention layers โ€” a linear-regression task in-context produces internal updates that approximate one or more gradient steps on that task. The transformer learned to run an optimizer as a subroutine, because doing so lowers prediction loss on documents containing patterns.

Practical corollary: your prompt isn't a query. It's a program that reconfigures the model's effective computation. That's why prompt structure matters so much โ€” you're not phrasing a search, you're building a temporary specialist.


13. Chain of thought = renting more serial compute

Fixed architecture means fixed serial depth: 80 layers. Some problems require more sequential steps than that, no matter how wide the model is.

The escape hatch is the output itself. Every emitted token is fed back as input, so:

serial computation available = 80 layers ร— number of tokens generated

Writing intermediate steps turns the context window into external working memory and buys unbounded serial depth.

Direct:  "What is 47 ร— 83?"  โ†’  "3,901"        โ† one 80-layer pass. Often wrong.

CoT:     "47 ร— 83
          = 47 ร— 80 + 47 ร— 3
          = 3,760 + 141
          = 3,901"                              โ† ~40 tokens = ~3,200 layers of serial work

Each line is computed, then read back as ground truth for the next line. This is why "think step by step" works, and why reasoning-tuned models generate long internal traces. They're not being verbose โ€” they're allocating compute.

Important caveat: the written trace is not guaranteed to be the actual causal path. Models can reach an answer internally and then generate a plausible-looking justification. Chain of thought is a compute mechanism and a post-hoc narrative, and telling those apart is an open research problem.


14. Training: SGD as a compiler

14.1 The reframe: the training loop is the compiler

If you know compilers, you already have the right structure in your head โ€” it just sits one level up from where you're looking.

gcc pipeline
  C source  โ”€โ”€โ–บ  gcc  โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ–บ  binary  โ”€โ”€โ–บ  CPU
  human-written  passes by hand     ~5 MB       can reject

LLM pipeline
  15T tokens โ”€โ”€โ–บ  SGD  โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ–บ  weights โ”€โ”€โ–บ  forward pass
  human-written  passes by search   ~140 GB     never rejects

Same shape. Two differences carry all the weight:

  1. Nobody wrote the passes. In gcc, a human wrote constant folding, a human wrote loop unrolling, and each is provably correct. In an LLM, a stochastic search over a 70-billion-dimensional program space found the passes. The 80 layers genuinely contain bracket matching, scope tracking, type propagation, dead-branch suppression โ€” but they were discovered, not authored, and nobody has fully read them back.
  2. The runtime has no reject state. More on this in ยง14.9; it's the single most clarifying fact about why the thing "accepts everything."

The closest thing in your world is superoptimization โ€” searching the space of instruction sequences for one better than a human would write. SGD is superoptimization with a different objective, a vastly larger search space, and no proof of anything.

14.2 What one SGD step actually does

Forget "training" as a vague process. A single step is small and entirely mechanical. Say the batch contains this snippet scraped from GitHub:

def process(items):
    result = []
    for item in items:
        result.append(transform(item))
    return โ–ฎ

Step 1 โ€” forward pass. The model produces a distribution over all 128,256 tokens at that position. Suppose it assigns p(" result") = 0.31.

Step 2 โ€” loss. Cross-entropy is just the negative log of the probability assigned to the actual next token:

loss = โˆ’ln(0.31) = 1.17 nats

If it had been confident:  โˆ’ln(0.95) = 0.05
If it had been clueless:   โˆ’ln(1/128256) = 11.76

The loss is literally "how surprised were you." Nothing more.

Step 3 โ€” backward pass. Backpropagation computes โˆ‚loss/โˆ‚w for every one of the 70 billion weights โ€” one number per weight saying "nudge me this direction to have been less surprised." This is the chain rule applied to a computation graph, executed in reverse.

Step 4 โ€” update.

w โ† w โˆ’ learning_rate ร— ฤ

With a learning rate around 1e-4 (decaying on a cosine schedule), each weight moves by roughly one part in ten thousand. In practice the optimizer is AdamW, which keeps running averages of the gradient and its variance so each weight gets its own effective step size.

That's the entire step. In isolation it is nearly worthless โ€” the model became microscopically less surprised by one snippet. Everything comes from doing this ~10โถ times over ~10ยนยณ tokens.

14.3 Why one update improves a million unrelated cases

This is the crux, and it has no compiler analogue.

To predict result correctly, the network had to run a real inference chain:

  • result was bound at the top of this scope
  • it's an accumulator โ€” mutated in a loop, never otherwise read
  • Python functions conventionally return their accumulator
  • we are at return, in this function's scope, not the enclosing one

The gradient does not reward "the string result." It rewards whichever circuits performed that inference: the variable-binding tracker, the scope-boundary detector, the accumulator-pattern recognizer.

And those circuits are shared. The identical variable-binding machinery fires for:

  • Rust let bindings
  • SQL aliases in a CTE
  • pronoun resolution in English prose
  • "the aforementioned party" in a contract
  • a defined term in a mathematical proof

So one Python snippet measurably improves the model's handling of legal documents. Not by analogy โ€” literally, the same weights, updated once, better everywhere.

This is the generalization mechanism, and it explains the otherwise baffling fact that 15 trillion tokens of miscellaneous internet text produces something that can write a compiler pass. There's a well-documented empirical consequence: adding code to the training mixture improves reasoning on non-code benchmarks, because code is unusually dense in explicit logical structure and, crucially, was checked by a compiler before being committed.

14.4 Why it cannot memorize, even if it wanted to

15,000,000,000,000  training tokens
    70,000,000,000  parameters
โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
              ~200  tokens compressed per parameter

At 2 bytes per parameter in fp16, that's roughly 0.01 bytes of storage per training token. Lossless memorization is off the table by three orders of magnitude.

SGD is therefore under brutal compression pressure, and the resolution is the one you'd reach yourself if you were hand-writing a codec: store the rules, not the instances.

  • A generative rule for "how Python scoping works" costs a few thousand parameters and covers billions of tokens.
  • Memorizing those same tokens costs billions of parameters and generalizes to nothing.

Gradient descent finds the first solution because the second doesn't fit. Generalization is not an achievement the model unlocks. It is the only thing that fits in the space available.

This is also the cleanest answer to "how does it know almost everything." It doesn't store everything. It stores the generative structure of everything, and re-derives specifics at inference time โ€” which is exactly why it's fluent on common things and confidently wrong on rare ones.

14.5 The numbers, for calibration

Tokens per batch~4 million (thousands of sequences in parallel)
Optimizer steps~10โตโ€“10โถ
Sequence length during training4Kโ€“32K, extended later
Total FLOPs~6 ร— params ร— tokens โ‰ˆ 6ร—10ยฒโด
Hardware10โดโ€“10โต accelerators, weeks to months
Costtens to hundreds of millions of dollars
OptimizerAdamW โ€” needs ~2 extra states per weight, so ~3ร— the model's memory just to train
Passes over the data~1. It sees most tokens exactly once.

That last row deserves a pause. There is no drilling, no repetition, no curriculum of the same material. The model learns Python scoping from seeing millions of different correct examples one time each โ€” which is precisely the setup that forces it to learn the rule instead of the instances. Repetition would encourage memorization; the single pass forbids it.

The 6 ร— params ร— tokens figure decomposes as 2 for the forward pass and 4 for the backward pass (backward costs roughly twice forward). Handy for estimating any training run.

14.6 The loss curve has structure

Training loss is not a smooth glide. Capabilities arrive as phase transitions:

loss
 โ”‚โ•ฒ
 โ”‚ โ•ฒ___                    learning token frequencies, basic syntax
 โ”‚     โ•ฒ
 โ”‚      โ•ฒ__               โ† visible bend: induction heads form
 โ”‚         โ•ฒ___             in-context learning switches ON here
 โ”‚             โ•ฒ__        โ† arithmetic circuits consolidate
 โ”‚                โ•ฒ____
 โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ–บ tokens seen

The induction-head bend is the famous one. Before it, few-shot prompting essentially doesn't work. After it, it does. You can watch a mechanism switch on by looking at a loss curve โ€” the capability is not a smooth emergent haze, it's a circuit forming.

This is the same shape as grokking: a network can sit at memorization-level performance for a long time and then abruptly generalize, when the general circuit finally beats the memorized lookup on the loss. You are watching a search find a better program and swap it in.

14.7 Where the modern gains actually come from

Architecture is roughly frozen. A 2019 transformer with modern normalization and RoPE is close to a 2026 one. Two things moved instead:

1. Data curation โ€” the real secret sauce, and the least published part.

  • Aggressive deduplication (near-duplicate web pages are actively harmful โ€” they induce memorization)
  • Quality classifiers trained to recognize "textbook-like" writing
  • Mixture ratios: how much code vs. web vs. books vs. math vs. multilingual, tuned empirically
  • Annealing: saving the highest-quality data for the last few percent of training, where the learning rate is tiny and the effect is disproportionate. The model's final impressions are its most durable ones.
  • Synthetic data: using a strong model to generate clean training material for the next one

2. RLVR โ€” reinforcement learning from verifiable rewards. This is the stage that made code good, and it's the one a compiler person will find most familiar:

sample N candidate solutions
  โ†“
run the test suite / check the proof / execute the program
  โ†“
reward the trajectories that passed
  โ†“
gradient-ascend toward those

Unlike RLHF ("did a human prefer this?"), the reward here is ground truth. You can optimize against it hard without immediately Goodharting, because a test suite has no taste to exploit. This is why RLVR adds genuine capability while RLHF mostly adds manners.

It also explains the capability profile you observe in practice: models are disproportionately strong in domains with cheap automated verification (code, math, formal logic) and weaker where correctness is a matter of judgment.

14.8 The post-training stages in detail

StageDataWhat it addsWhat it doesn't
Pretraining~15T tokens of web, books, codeEssentially all knowledge, reasoning ability, world model, intent modelingAny notion of being an assistant. A base model given a question is as likely to write more questions.
SFT~10โดโ€“10โถ curated dialoguesThe assistant format; the mapping "user turn โ†’ helpful response"New knowledge, in any meaningful quantity
Reward modelingHuman preference comparisons (A vs. B)A learned scorer that approximates human judgmentAnything, directly โ€” it's scaffolding for the next stage
RLHF / RLAIFThe reward model's scoresTone, helpfulness, honesty, refusal behavior, calibrated hedgingNew capabilities
RLVRMath/code with automatic checkingGenuine reasoning improvementAnything where correctness isn't checkable

The mental model for the middle three: the base model can simulate an enormous range of authors. Post-training doesn't teach it anything new; it selects which author it becomes when addressed as an assistant, and makes that selection reliable.

The cost asymmetry is stark โ€” pretraining is 98%+ of the compute, post-training is a rounding error. Yet post-training is what makes the artifact usable. It is a thin, cheap layer of steering over an enormously expensive engine.

The known downside: RLHF optimizes a proxy for human approval, and approval is not truth. This is the mechanistic origin of sycophancy โ€” reversing a correct position under pushback is what the reward signal rewarded.

14.9 The disanalogy that resolves "it accepts everything"

You're conflating two properties. Separate them and most of the mystery dissolves.

Property 1: "It accepts anything." This is architectural, and not impressive.

Look at where a compiler can fail versus where a transformer can:

Compiler stageCan fail?Transformer equivalentCan fail?
Lexeryes โ€” invalid characterBPE tokenizerno โ€” total function, always emits tokens
Parseryes โ€” syntax error(none exists)โ€”
Type checkeryes โ€” type error(none exists)โ€”
Linkeryes โ€” undefined symbol(none exists)โ€”
Codegenyessoftmaxno โ€” always a valid distribution

There is no code path in a transformer for "I don't understand this input." No grammar, no parser, no error state, no partial-failure mode. Every stage is a total function over its input domain. Feed it line noise and it will confidently predict the next token of line noise.

That's not intelligence โ€” it's the absence of a rejection mechanism. And it's the direct architectural cause of hallucination: a system that cannot fail to parse also cannot fail to answer. When the model doesn't know something, there is no representational slot for "unknown" and no branch to take. The output head produces a peaked distribution regardless, because that's the only thing it can do.

Everything that looks like the model saying "I'm not sure" is learned behavior from post-training, generated as ordinary tokens โ€” not a structural check. It's a string, not a status code.

Property 2: "It knows almost everything." This is capacity plus compression โ€” and it's less true than it feels.

It knows the high-frequency structure of nearly everything, and degrades smoothly into the tail:

frequency in training data
       high โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ–บ low
       โ”‚                                     โ”‚
   reliable                            plausible
   and correct                         and wrong
       โ”‚                                     โ”‚
  "how does a         "LLVM             "the signature of
   dominator           dominator          getAnalysisUsage
   tree work"          tree API"          in LLVM 17.0.3"

And the confidence is flat across that entire axis, because nothing in the architecture measures how well-supported a fact was. The useful heuristic that falls out: trust its structure, verify its specifics. Algorithms and architecture generalize from circuits. API signatures, version numbers, and citations are memorized facts, and memorized facts decay with training frequency and go stale with time.


15. Worked scenario: "build me a landing page for a dog-walking service"

Why does this work, when the exact page was never in training data?

The abstractions that exist in the weights:

  • landing-page schema: hero, value proposition, social proof, pricing, CTA, footer
  • local-service-business schema: service area, trust signals, booking mechanism
  • HTML/CSS syntax circuits: matched tags, valid property names, correct nesting
  • Design conventions: contrast, hierarchy, whitespace, mobile-first

What the forward pass does:

  1. L25โ€“45: composes landing-page โˆฉ local-service โˆฉ pet-industry into a joint plan. Pet industry contributes warm colors, photography-forward, informal-but-trustworthy tone.
  2. L45โ€“65: instantiates concrete sections in order.
  3. Decode: emits HTML. Here the syntactic circuits do heavy lifting โ€” an open <div> creates a strong attention signal that must eventually be discharged by </div>. This is bracket-matching implemented as attention, and it's why generated code is structurally valid even when semantically wrong.
  4. Each token conditions the rest. Having written a hero section with a specific headline, the CTA later in the page will echo its phrasing โ€” because that's what coherent documents do, and coherence is what was optimized.

Where it breaks and why: it will confidently produce a plausible-looking page that may use a CSS property that doesn't exist, or a framework API from a version that changed. It's generating from a distribution over plausible code, and plausible โ‰  correct. It has no compiler.


16. Worked scenario: a compiler pass

Prompt: "Write an LLVM pass that eliminates redundant loads."

Knowledge assembled from the MLPs: SSA form, dominance relations, alias analysis, LoadInst and StoreInst APIs, the runOnFunction signature, memory dependence.

Reasoning assembled from circuits: the actual algorithm โ€” walk the dominator tree, track available loads, kill on any aliasing store, replace dominated redundant loads with the earlier value.

Why it can do this: the LLVM codebase, its documentation, dozens of textbooks, and thousands of blog posts are in the training data. But more importantly, the abstractions generalize: "dominance," "available expressions," "kill sets" are structures the model represents, not strings it memorized. Ask for the same pass targeting a different IR and it adapts, because the structure transfers.

Where it breaks: it will get the algorithm right and the API version wrong. Reasoning circuits generalize; specific API signatures are memorized facts, and memorized facts decay with training-data frequency and go stale with time. The intuition to carry: trust its structure, verify its specifics.


17. Failure modes, and what each one reveals about the architecture

Failures are the best evidence for the mechanism, because they map onto architectural constraints exactly.

FailureRoot cause
Can't count letters in "strawberry"Tokenization โ€” it never sees characters
Arithmetic on large numbersFixed serial depth; digits are badly tokenized. CoT partially fixes it
Confident wrong facts (hallucination)Sparse-in-training-data facts have weak feature representations, but the output head still produces a peaked distribution. Fluency and truth are separate axes
Loses the thread in very long contextsAttention mass is finite and spread over more positions; "lost in the middle" is real
Repetition loopsLow-temperature sampling entering a self-reinforcing attractor
Fails at genuinely novel deep reasoningNo search, no backtracking. Layer-by-layer refinement isn't tree search
Reverses its position under pushbackPost-training partially selected for agreeableness โ€” Goodharting on human preference
Cites a real-looking but nonexistent paperAuthor, venue, year, and title-style are each high-probability independently; the joint doesn't exist

Notice that none of these are random. Every one falls out of a structural property. That's a good sign your mental model is correct โ€” a correct model predicts the failures.


18. What is honestly still unknown

Intellectual honesty matters here, because a lot of writing on this topic overclaims.

Established: the architecture; superposition; specific circuits (induction, IOI, and dozens more); feature extraction via sparse autoencoders; task vectors; scaling laws.

Not established:

  • No end-to-end account of any complex behavior. Nobody can trace why a specific 500-token compiler answer came out correct. We have footholds, not a map.
  • Why in-context learning is as good as it is. Mechanisms are known in pieces; the full story isn't.
  • Whether chain of thought is faithful to the actual computation.
  • What the mid-layer "planning" representations really are โ€” evidence exists that models plan several tokens ahead (e.g. picking a rhyme word before writing the line that leads to it), but the general structure is unclear.
  • Whether anything like understanding is present in a sense beyond functional. This is partly empirical and partly a question about what the word means, and pretending it's settled in either direction is unjustified.

19. Every concept, defined and modeled

Each entry: what it literally is, then the mental model that makes it make sense. Where a compiler analogy helps, it's there.

19.1 The substrate: numbers and shapes

TermWhat it literally isMental model
ParameterOne number, learned during training. A 70B model has 70 billion.A single knob. Meaningless alone โ€” like asking what byte 4,182,993 of a compiled binary "means." Meaning lives in groups.
WeightA parameter used as a multiplier on an input. The overwhelming majority of parameters.How strongly one thing influences another. Learned "conductance" in a circuit.
BiasA parameter added, not multiplied. A constant offset.A default lean. "Assume this is slightly true unless told otherwise." Many modern models drop them โ€” barely matters.
Weight matrixA 2D grid of weights, e.g. W_in at 8,192 ร— 28,672.A learned transformation from one space to another. Each row is a pattern being detected; each column is a pattern being written.
ActivationA number computed during a forward pass. Not learned; depends on your input.The runtime values. Weights are the program, activations are the stack and registers.
NeuronOne dimension of an MLP's hidden layer. 28,672 per layer.A single pattern detector with a learned trigger and a learned response. Individually usually polysemantic โ€” it fires for several unrelated things (see superposition).
TensorAn n-dimensional array. Scalars, vectors, matrices generalized.Just the shape of the data. [batch, sequence, d_model] is the shape you'll see everywhere.
Matrix multiplicationThe core operation. Rows dotted with columns.Asking "how much does this vector resemble each of these learned patterns?" โ€” thousands of dot products at once. GPUs exist for this.
d_modelThe width of the residual stream. 8,192 in our reference model.The bandwidth of the shared workspace. How much information one position can carry at once.
PrecisionBits per parameter: fp32, bf16, fp8, int4.How finely each knob is calibrated. bf16 is the training default. Inference often drops to int8/int4 โ€” cheaper, slightly lossier.

19.2 Architecture

TermWhat it literally isMental model
TokenA subword unit, ~3.5โ€“4 chars. The model's atomic symbol.The model's alphabet. It cannot see below this level โ€” the reason letter-counting fails.
VocabularyThe full token set, ~128K entries.The model's fixed symbol table, built once by BPE before training.
BPEByte-pair encoding: iteratively merge the most frequent adjacent pair.A learned compression scheme for text. It is a total function โ€” unlike a lexer, it can never reject input.
Embedding matrixvocab ร— d_model. One learned vector per token.The lookup that converts a symbol into a starting vector. Context-free โ€” pure "this token, generically."
Positional encoding / RoPERotates Q and K vectors by an angle proportional to position.How the model knows word order. RoPE makes attention naturally see relative distance, which is why it extrapolates to longer contexts.
Layer / blockOne attention sublayer + one MLP sublayer. 80 of them stacked.One optimization pass โ€” except nobody wrote it. Each reads the workspace and writes back.
Residual streamThe running vector at each position that every sublayer adds into.The shared whiteboard. The single most important object. Not overwritten, only accumulated.
Skip / residual connectionx โ† x + f(x) instead of x โ† f(x).What makes the whiteboard a whiteboard. Also what lets gradients reach layer 1 from layer 80 without vanishing โ€” the reason deep networks train at all.
Attentionsoftmax(QKแต€/โˆšd)VLearned retrieval, recomputed at every layer. The only mechanism moving information between positions.
Query"What am I looking for right now?"Your search query โ€” but recomputed at every layer from the current state.
Key"What am I, advertised to searchers?"The index entry.
Value"What gets copied if you match me."The payload โ€” deliberately decoupled from the key. You can match on "France" and return a country-code vector.
Attention headOne independent Q/K/V/O set, 128 dims. 64 per layer.One specialist doing one job: previous-token, duplicate-detection, name-moving, bracket-matching. 5,120 of them per token.
Attention patternThe softmaxed weight matrix โ€” who attended to whom, how much.The wiring diagram for this specific input. Fixed weights, variable data flow. This is the programmability.
Causal maskPosition i can't attend to j > i.Enforces left-to-right. Also why one document yields thousands of training signals in one pass.
GQA / MQAMultiple query heads sharing fewer key/value heads.A KV-cache size optimization. Pure engineering; almost no capability cost.
MLP / FFNW_out ยท GELU(W_in ยท x). ~2/3 of all parameters.A key-value memory. ~28,672 slots per layer: "if you see pattern P, add fact F." Where knowledge lives.
Activation functionGELU, SwiGLU โ€” a nonlinearity.The thing that makes 80 layers more expressive than one. Without it, stacked linear maps collapse into a single linear map.
LayerNorm / RMSNormRescale a vector to a standard magnitude.Automatic gain control. Keeps values in a workable range so training doesn't explode. Boring but load-bearing.
Unembedding / LM headd_model ร— vocab matrix at the very end.Projects the final vector onto every possible token. Often tied to the embedding matrix.
LogitsRaw pre-softmax scores, one per vocab entry.Unnormalized evidence for each token. Differences matter; absolute values don't.
Context windowMax tokens processable at once. 128Kโ€“2M.Working memory. Hard-walled. Nothing outside it exists โ€” no gradual forgetting, just a cliff.
MoE (mixture of experts)Many MLP "experts"; a router activates only a few per token.Decouples stored knowledge from compute per token. A 400B MoE may activate only 30B per token โ€” big brain, cheap thinking.

19.3 Training

TermWhat it literally isMental model
Lossโˆ’ln P(actual next token)."How surprised were you?" Zero means certain and right. That's the entire objective.
Cross-entropyThe formal name for that loss.Measures the gap between the model's distribution and reality.
Perplexityexp(loss)."Effectively how many tokens was it choosing between?" Perplexity 10 = as confused as a fair 10-way guess. More intuitive than nats.
Gradientโˆ‚loss/โˆ‚w โ€” one number per parameter.A per-knob arrow: "turn me this way to be less wrong." 70 billion arrows per step.
BackpropagationThe chain rule applied backward through the computation graph.Blame assignment. Distributes responsibility for the error across every weight that contributed. Costs ~2ร— the forward pass.
SGDTake a batch, compute gradients, step downhill. Repeat.Blind hill-descent in 70-billion-dimensional space, one tiny step at a time. Stupid per step; extraordinary in aggregate.
Adam / AdamWSGD plus per-parameter running averages of gradient and variance.Adaptive step sizes โ€” cautious on noisy knobs, bold on consistent ones. Costs 2 extra states per weight (~3ร— memory to train).
Learning rateStep size multiplier, ~1e-4, decaying.How far to move per step. Too high: divergence. Too low: never arrives. The most important hyperparameter.
Warmup + decayRamp the LR up over early steps, then cosine-decay to near zero.Ease in while the model is fragile; fine-tune gently at the end. The final low-LR phase is when high-quality data matters most (see annealing).
BatchThe set of sequences processed before one update. ~4M tokens.Averaging over many examples so the gradient points at a real trend, not one document's noise.
Gradient accumulationSum gradients over several forward passes before stepping.Simulating a huge batch when it won't fit in memory.
EpochOne full pass over the dataset.Mostly irrelevant here โ€” LLM pretraining does ~1 epoch. Each token is seen once. That's what forces rules over memorization.
CheckpointA saved snapshot of all weights.A build artifact. What actually gets shipped.
OverfittingMemorizing training data instead of learning the pattern.Barely a concern at LLM scale โ€” there's no capacity to memorize 15T tokens. The compression ratio is the regularizer.
Scaling lawsLoss falls as a predictable power law in params, data, and compute.Loss is forecastable before you spend the money. Chinchilla's finding: optimal is ~20 tokens per parameter โ€” most early models were badly undertrained.
EmergenceA capability appearing abruptly at some scale.Usually a circuit forming (see induction heads), sometimes an artifact of a threshold-based metric. Real, but often overstated.
GrokkingSudden jump from memorization to generalization after long training.The general circuit finally out-competing the lookup table on loss. Watching search swap in a better program.
PretrainingNext-token prediction on ~15T tokens.Where all knowledge and reasoning comes from. 98%+ of the compute.
SFTSupervised fine-tuning on curated dialogues.Teaching the format, not the content. Selects "helpful assistant" from the range of authors the base model can simulate.
Reward modelA model trained on human A/B preferences to score outputs.A learned approximation of human taste. Scaffolding for RLHF.
RLHF / RLAIFRL against the reward model's scores.Manners, tone, refusals, calibrated hedging. Adds almost no capability. Optimizing approval, not truth โ€” hence sycophancy.
RLVRRL against automatic verification โ€” tests pass, proof checks.The one post-training stage that adds real capability, because the reward is ground truth and has no taste to exploit.
DistillationTraining a small model on a large model's outputs.Compiling with the big compiler, shipping the small binary. Most small fast models are distilled.
LoRA / PEFTTrain small low-rank adapter matrices; freeze the base.A patch file instead of a rebuild. Cheap, swappable, adds style and domain shape โ€” not new reasoning.
Catastrophic forgettingFine-tuning on narrow data degrades general ability.Overwriting shared circuits. The reason naive fine-tuning often makes a model worse overall.

19.4 Inference

TermWhat it literally isMental model
Forward passInput โ†’ 80 layers โ†’ logits. No weights change.Running the compiled program. Same weights every time; the data flow is what your prompt reconfigures.
PrefillProcessing your whole prompt in one parallel pass.The compile step before output starts. Compute-bound. This is your time-to-first-token.
DecodeGenerating one token at a time, reusing the cache.The execution loop. Memory-bandwidth-bound, not compute-bound โ€” which is why batching helps throughput so much.
KV cacheStored keys and values for all prior positions.Memoization. Without it you'd recompute the whole prompt per token. Grows linearly with context โ€” tens of GB at 128K. The real cost of long context.
SamplingDrawing a token from the output distribution.The one deliberately nondeterministic step. Why the same prompt gives different answers.
TemperatureDivide logits by T before softmax.A confidence dial. T=0: always argmax, deterministic. T=1: the model's honest distribution. T>1: flattened, more surprising, more wrong.
Top-k / top-pKeep only the k best tokens, or the smallest set summing to probability p.Truncating the garbage tail. Top-p โ‰ˆ 0.9โ€“0.95 is the usual default.
Greedy decodingAlways take the highest-probability token.Deterministic, and often worse โ€” it produces flat, repetitive text and can dead-end into loops.
Beam searchTrack multiple candidate continuations.Standard in translation, mostly abandoned for open generation โ€” it collapses into bland high-probability text.
Stop sequenceA string that halts generation.An explicit terminator, since the model has no intrinsic sense of "done" beyond a learned end-of-turn token.
PromptEverything in the context before generation starts.Not a query โ€” a program. It reconfigures which circuits fire. That's why structure matters more than politeness.
System promptInstructions placed at the front of context.Highest-leverage position: everything else attends back to it. Not privileged by the architecture, only by position and training.
Zero-shot / few-shotNo examples / a handful of examples in the prompt.Few-shot works via induction-head machinery โ€” pattern completion, not learning. Weights never move.
In-context learningAcquiring a task from the prompt alone.The forward pass implementing a learning algorithm. Sometimes literally approximating gradient descent inside the attention layers.
Chain of thoughtGenerating intermediate reasoning tokens.Renting serial compute. Fixed 80-layer depth ร— N tokens generated. The context window becomes external working memory.
Speculative decodingA small model drafts several tokens; the big one verifies in parallel.Branch prediction. Free speedup when the draft is right, no loss when it isn't.
QuantizationDropping to int8/int4 at inference.Shrinking the binary. Big memory and speed wins, small quality cost.

19.5 Interpretability

TermWhat it literally isMental model
FeatureA direction in activation space corresponding to a human-meaningful concept.The real unit of meaning โ€” not the neuron. "Golden Gate Bridge," "code with a security bug," "sycophantic tone."
SuperpositionStoring more features than dimensions using near-orthogonal directions.The answer to "how can 8,192 numbers hold everything." ~10โท directions packed into 8,192 dims, only a few dozen active at once.
PolysemanticOne neuron firing for several unrelated things.The symptom of superposition. Why reading individual neurons fails.
MonosemanticOne unit, one clean concept.The goal of feature extraction โ€” recovered by sparse autoencoders, not found in raw neurons.
Sparse autoencoder (SAE)An overcomplete autoencoder trained to reconstruct activations sparsely.The decoder ring. Unpacks superposed activations into millions of individually interpretable features.
CircuitA set of components implementing a specific algorithm.A discovered subroutine. Induction heads, the IOI circuit. Real algorithms nobody wrote.
Induction headA two-layer circuit doing [A][B]โ€ฆ[A] โ†’ [B].Why in-context learning works. Also why the model tracks variable names it has never seen.
AblationZeroing a component and measuring the damage.#ifdef 0 on part of the network. How circuit claims get causally verified rather than just observed.
Activation patchingCopying activations from one run into another.A/B testing internals. Isolates which component carries which information.
Logit lensApplying the output head to intermediate layers.Reading the model's mind mid-computation. Shows the answer being built, not looked up.
Task / function vectorA mid-layer vector encoding "the task is X," extractable and transplantable.Your intent, as a physical object. Add it to an unrelated prompt and the model performs the task.

19.6 Practical and operational

TermWhat it literally isMental model
FLOPsFloating-point operations.The currency. Inference โ‰ˆ 2 ร— params per token. Training โ‰ˆ 6 ร— params ร— tokens. Everything else is bookkeeping.
TTFTTime to first token.Dominated by prefill โ€” i.e. by prompt length. Long prompts cost you latency before a single word appears.
Tokens/secDecode throughput.Bounded by memory bandwidth, not FLOPs. Batching many requests together is nearly free on compute.
Throughput vs latencyTotal tokens across all users vs. speed for one.Directly in tension. Big batches maximize throughput and hurt individual latency.
RAGRetrieve documents, insert into the prompt, generate.Giving the model an open book. Fixes staleness and citation, does nothing for reasoning ability.
Fine-tune vs. prompt vs. RAGThree ways to specialize.Prompt = configuration. RAG = knowledge injection. Fine-tune = behavior and format. Most "we need to fine-tune" problems are prompt or RAG problems.
Context length vs. costCost is superlinear-ish in context.Attention is O(nยฒ) in compute, KV cache is O(n) in memory. The memory usually bites first.
DeterminismSame input, same output?Not by default โ€” sampling is stochastic, and even at T=0, GPU floating-point non-associativity across varying batch sizes can flip a near-tie. Bit-exact reproducibility is genuinely hard.

19.7 Behavior and failure

TermWhat it literally isMental model
HallucinationFluent, confident, false output.Not a bug in the usual sense. There is no reject state. A system that cannot fail to parse cannot fail to answer. Weak features still produce peaked distributions.
SycophancyCaving to pushback, over-agreeing.RLHF optimizing a proxy for approval. Approval and truth are correlated but not identical, and the gap is where this lives.
GoodhartingOptimizing the measure until it stops measuring the thing.Why RLVR (ground-truth reward) is safer to push hard than RLHF (taste-based reward).
Lost in the middleDegraded recall of mid-context information.Attention mass is finite and softmax-normalized. More positions, less each. Beginnings and ends survive best.
Repetition loopThe model cycling the same phrase.Low-temperature sampling entering a self-reinforcing attractor โ€” each repeat raises the probability of the next.
Prompt injectionUntrusted text in context issuing instructions.The architectural consequence of having no privilege separation. Your system prompt and a hostile web page are the same kind of tokens in the same stream. There is no const in the context window.
JailbreakPrompting past post-training guardrails.Post-training is a learned bias over a base model that can simulate anyone. It's a strong prior, not a wall.
Knowledge cutoffThe date training data ends.The build date. Everything after is invisible unless supplied in context.

Appendix A: the compressed mental model

  1. Your text becomes tokens; tokens become vectors.
  2. Those vectors are a shared workspace, one column per position, and every layer adds to rather than replaces them.
  3. Attention moves information sideways โ€” learned retrieval, recomputed 5,120 times per token, where "what to match" and "what to copy" are separate learned functions.
  4. MLPs add knowledge vertically โ€” ~2.3 million learned key-value slots.
  5. Each vector holds a sparse combination of millions of learned features, packed via near-orthogonality. Width was never the constraint.
  6. Depth is composition. By mid-network, your intent exists as an extractable vector, independent of your wording.
  7. The final vector projects to a distribution over 128K tokens; one is sampled; the loop runs again.
  8. It knows what you meant because predicting text written by intentional agents requires modeling intent, and compression made that the cheapest available strategy.
  9. Generating tokens buys serial compute; that's what chain of thought is for.
  10. It fails exactly where the architecture says it should. That's the strongest evidence the model above is right.

Appendix B: the analogy that actually holds

Not a search engine. Not a database. Not a person.

A very large, very fast, learned interpreter โ€” running a program written by gradient descent, on data supplied by your prompt. The weights are the program. Your prompt is the input and a runtime reconfiguration of which parts of the program execute. The output is what that program computes.

The reason it feels like understanding is that the program it learned is, in substantial part, a model of the people who wrote its training data โ€” including their intentions.


Further reading (primary sources)

  • A Mathematical Framework for Transformer Circuits โ€” Elhage et al., 2021
  • In-context Learning and Induction Heads โ€” Olsson et al., 2022
  • Toy Models of Superposition โ€” Elhage et al., 2022
  • Interpretability in the Wild (the IOI circuit) โ€” Wang et al., 2022
  • Transformer Feed-Forward Layers Are Key-Value Memories โ€” Geva et al., 2021
  • Scaling Monosemanticity โ€” Anthropic, 2024
  • Function Vectors in Large Language Models โ€” Todd et al., 2023
  • Training Compute-Optimal Language Models (Chinchilla) โ€” Hoffmann et al., 2022