small-model-lab · Part 0 · Concepts

How a language model works

The ideas, in plain English, with no code: what a language model actually is, how text becomes numbers, what “learning” means, and how the pieces fit. This chapter is optional theory. Read it first if you like the why before the how, or skip ahead: Part 1 builds every one of these ideas in real, runnable code, and Part 2 fine-tunes a real model into a useful expert.

The whole thing in one breath: a language model is a mathematical function with a great many adjustable numbers: its parameters (you'll also hear them called its weights), the dials of the function. Given some text so far, it predicts what comes next. Training tunes those dials (countless tiny nudges) until coherent language falls out. Generation runs the function in a loop to write.

Everything below unpacks that: how text becomes numbers, how the model “looks back” at what it has read, how it measures its own mistakes, and how it slowly improves.

No Python here. This page is concepts and pictures only. Every idea reappears as real code in Part 1 · Pre-training; each section links across to where it's built.

Part 0 · Concepts

1

What a model actually does

Strip away the mystique and a language model does one narrow thing: given the text so far, it predicts what comes next. Not whole thoughts, just the next small chunk (a token: a word or word-piece). To write a sentence it just does this over and over, each new token appended and fed back in. That's it. Everything else is machinery in service of making that one prediction good.

So “a model that writes” is really a model that scores what's likely next, run in a loop. The skill isn't generating; it's the prediction underneath. Here is that one prediction, for real, from the tiny model this lab builds in Part 1:

“One day, Lily went to the ___” the model’s scores for what comes next — its real output, one number per vocabulary chunk park 68.1% store 10.3% beach 4.0% zoo 2.1% river 1.0% everything else (~8,000 chunks) 14.5% The scores sum to 100% across all 8,192 chunks. Training (§7) nudges the weights so the chunk that actually came next gets a bigger share; generating (§8) means picking from this menu, appending, and scoring again.
Fig. 1One real prediction from the tiny tuned model this lab builds in Part 1: given the text so far, it puts a score on every chunk in its vocabulary. “park” isn't a stored fact; it's the strongest statistical echo of the stories it read.
2

Text becomes numbers (tokens)

A model can't do arithmetic on letters, so the first move is to turn text into numbers. The text is chopped into tokens: common chunks (whole words like fox, or word-pieces), each with an integer ID (its index in a fixed list called the vocabulary). “fox” might be token #1234. That's all a token is to the model: an ID. There's more than one way to chop, and the choice matters enormously:

① One number per character — how the from-scratch model (notebook 01) reads O 36 n 61 c 50 e 52 ␣ 1 u 68 p 63 o 62 n 61 ␣ 1 a 48 ␣ 1 t 67 i 56 m 60 e 52 16 characters → 16 numbers. The model must learn spelling before it can learn anything else. ② One number per word-chunk (BPE) — how the tuned model (notebook 02) reads ␣Once #5381 ␣upon #284 ␣a #103 ␣time #240 Same text: 4 numbers instead of 16 (␣ marks the space each chunk carries). The model now reasons over meaningful pieces, and the same context window holds ~4× more story — most of the v1 → v2 quality leap in Part 1. ③ How big is a chunk? Frequency decides — the same tokenizer, three words ␣butterfly 1 chunk — the stories used it constantly ␣thunder storm 2 chunks — both meaningful ␣un bel ie v able 5 chunks — rare, spelled from pieces Words the training text used constantly earn a chunk of their own; rarer ones are spelled out of reusable pieces — and the pieces themselves often carry meaning (␣thunder, storm, ␣un…, …able). Nothing is ever out-of-vocabulary.
Fig. 2The same sentence, tokenized two ways, with real numbers from Part 1's notebooks (character IDs from notebook 01, BPE chunk IDs from notebook 02). Below them: what happens to words the corpus saw rarely; the same tokenizer splits them into reusable, often meaningful pieces.

The reverse runs at the end: the model's predicted ID is mapped back to its chunk of text, and the pieces are glued together into words. Part 1 builds the tokenizer →

3

Tokens become vectors (embeddings)

If the ID is just a ticket, where does meaning live? In what the ticket fetches: each token's ID points to a list of numbers, its embedding (a vector of 384 numbers, in our tiny model). Think of those numbers as coordinates that place the token in a vast “meaning space,” where tokens used in similar ways land near each other.

Start with the fetch itself. The ID is nothing but an index; what matters is the row it lands on: that row of numbers is the embedding, the token's vector. The first hint of meaning is already visible in it: words that behave alike carry similar rows, while a pure grammar word like “the” looks nothing like them.

A token’s ID indexes the embedding table: row #ID is its vector fox ID #1234 row #1234 0.31 -1.20 0.05 ⋮ 384 numbers cat ID #882 row #882 0.28 -1.05 0.12 ⋮ 384 numbers dog ID #905 row #905 0.35 -1.31 -0.02 ⋮ 384 numbers the ID #14 row #14 -0.92 0.44 -0.61 ⋮ 384 numbers fox · cat · dog → similar rows (similar meaning) “the” → different
Fig. 3The lookup, drawn: an ID indexes the embedding table, and row #ID simply is the token's embedding vector: all 384 of its numbers (4 shown; values illustrative). The cell colours make it visible at a glance: fox, cat and dog get similar rows; “the” gets a different one.

That's one token's row. Now zoom out: there's a row like it for every token in the vocabulary: thousands of them, stacked into one enormous table. That table has a name, WE, and it holds essentially everything the model knows about individual words.

All tokens, ~8k Abbie #6170 Abby #7079 Abi #6567 Abigail #4964 able #1344 about #511 ⋯ ⋯ zooming #5071 Zoomy #6888 âĢĵ #4058 âĢĶ #7805 âĢĺ #6044 âĢľ #798 token id → WE = +0.04 +0.00 −0.01 −0.04 +0.07 −0.01 −0.01 −0.02 −0.05 +0.04 +0.02 ⋮ −0.06 +0.04 −0.02 −0.03 −0.07 +0.04 −0.03 −0.01 −0.03 +0.02 +0.02 −0.02 ⋮ −0.01 +0.04 −0.01 −0.06 −0.04 +0.04 −0.05 −0.05 +0.05 +0.02 +0.01 +0.04 ⋮ +0.05 +0.04 +0.01 −0.02 −0.04 +0.03 −0.04 +0.05 −0.02 −0.09 −0.02 +0.02 ⋮ +0.00 −0.07 +0.05 +0.00 −0.02 −0.02 −0.02 −0.07 −0.08 +0.01 +0.02 −0.04 ⋮ −0.05 +0.00 +0.00 +0.06 +0.03 −0.05 −0.01 +0.14 −0.09 +0.03 −0.06 −0.03 ⋮ +0.10 ⋯ ⋯ ⋯ ⋯ ⋯ ⋯ ⋯ ⋯ ⋯ ⋯ ⋯ ⋮ ⋯ −0.06 −0.02 −0.10 +0.02 +0.05 −0.06 −0.02 +0.06 −0.05 +0.03 −0.02 ⋮ +0.04 +0.00 +0.06 −0.04 −0.02 +0.04 +0.00 +0.04 −0.07 +0.00 −0.02 +0.01 ⋮ −0.01 −0.02 +0.05 +0.07 −0.01 +0.01 −0.03 +0.00 −0.03 +0.06 +0.05 +0.01 ⋮ +0.09 +0.01 −0.04 −0.02 −0.02 +0.02 +0.01 +0.09 −0.05 +0.00 +0.02 +0.02 ⋮ +0.00 +0.02 −0.08 −0.03 +0.00 +0.00 −0.05 +0.00 +0.05 −0.03 +0.08 −0.02 ⋮ +0.07 −0.03 −0.06 −0.03 +0.01 +0.05 −0.02 −0.01 +0.01 −0.09 +0.05 +0.01 ⋮ +0.08 384 dims Embedding matrix each cell is one real learned number: + red stronger positive, − blue stronger negative
Fig. 4The real W_E from the trained model: 8,192 token columns × 384 dimension rows, every cell a learned value (12 tokens shown, swept A→Z; ⋯ stands in for the other ~8,180). Each column also carries its real token id (scrambled: the columns are alphabetical, the ids are not, per §2). Each column is one token’s vector, the “meaning coordinates” this section is about. Measured, not illustrative (and small: this model trains in the ±0.2 range).

Rows of numbers are hard to read meaning from directly, so picture them as positions instead. Give each token the coordinates in its row and the “meaning space” stops being a metaphor: related tokens gather into neighbourhoods, unrelated ones drift apart.

Attribute A (dimension 1) — loosely, “animal-ness” → Attribute B (dimension 2) — loosely, “concreteness” ↑ (2 of fox's 384 dimensions shown) animals cat fox dog wolf actions ran jumped function words the a of
Fig. 5Each token is its own point in 384-dimensional space (2 dimensions shown here); similar meanings cluster. The axes are two of the 384 learned attributes/dimensions, loosely 'animal-ness' across and 'concreteness' up: touchable things high, actions in the middle, pure grammar words low (held lightly).
4

The linear layer (the core operation)

Almost the entire network is one operation, repeated: the linear layer, y = Wx + b. It takes a vector of numbers in and produces a new vector out, where each output is a weighted sum of all the inputs plus an offset. Stack the per-output weight-rows into a grid W and the offsets into a vector b, and that's the whole layer: the school-line y = mx + c, vectorised. The diagram below builds it from one output up to the whole model.

① One output (a "neuron"): a token's 384 numbers → one number vocabulary the fox cat ⋮ look up fox's embedding (x: #1–3, then #384) 0.31 −1.20 0.05 ⋮ 0.12 × × × × its weights (one per number) 0.80 −0.40 1.10 ⋮ −0.70 add them up y₁ = 0.31×0.80 + (−1.20)×(−0.40) + 0.05×1.10 + ⋯ + 0.12×(−0.70) + b₁ = 0.62 ✗ NOT one number per letter. "fox" is one token → one lookup → all 384 dimensions of its embedding vector, at once. The values shown are dimensions 1–3 and 384 of fox's vector — each a learned coordinate in meaning-space (see the embedding figures). ② A layer = MANY such neurons stacked: one row of weights each → the matrix W (so y = Wx + b) 0.80 −0.40 1.10 −0.70 ⋯ ⋯ ⋯ ⋮ ⋮ ⋮ ⋮ W (parameters) ← top row = output ① (the neuron above) columns = inputs · rows = outputs 3 output rows shown; each is one neuron (one weighted sum → one output number) × x: inputs 0.31 −1.20 0.05 ⋮ 0.12 + b: biases 0.10 −0.04 0.21 ⋮ = y: outputs 0.62 −1.07 0.38 ⋮ Each output is its own ①-style neuron: all 384 inputs × that output's own weights + its own bias → one number. So y₁ = 0.62 is exactly panel ① (from ALL of x, not just x₁); rows 2, 3, … are more outputs, each from the same 384 inputs. A layer can have any number of output neurons — call it m. So y and b are m-entry vectors; m sets the output size (e.g. 384 → 1,536). One token (384 numbers) goes IN → a NEW vector of m numbers comes OUT. The final head → softmax gives next-token probabilities. Written compactly, the whole layer is y = Wx + b. ③ Zoom out: one such layer is a tiny slice of the whole model tokens input Block 1 attn + MLP Block 2 attn + MLP ⋯ blocks 3–5 Block 6 attn + MLP head next token probs embed ↑ a layer like ①② is one W in here Each block pairs attention (reads context) with an MLP (multi-layer perceptron: stacked linear layers, like ①②). Head → next-token probs. Of the ~17M parameters: ~3.24M the token + position embeddings; ~10.6M the 6 blocks' shared W's; ~3.15M the head. So a token's 384 numbers are a tiny slice; the bulk is the model's shared weights, applied to every token (fixed after training).
Fig. 6A linear layer, drawn. ① one output (a "neuron") is a weighted sum of the numbers in one token's vector; ② stack a row of weights per output → the matrix W, so the layer is y = Wx + b (a vector in, a new vector out); ③ one such layer is a tiny slice of the whole ~17M-parameter model, whose weights are shared across every token.
5

The bend (activations)

Stacking linear layers has a catch: by itself, it buys nothing. Double a number, then triple it. Two steps, yet all you've really done is multiply by six, which is one step. Every stack of straight-line operations collapses this way into a single straight-line operation. So no matter how deep the model went, it could still only draw lines. The fix: after each linear step, apply one simple nonlinear function, a bend. That bend is what lets depth model curves and combinations, not just proportions.

Ours is GELU (a smooth version of ReLU). The famous textbook ones are ReLU (keep positives, zero the rest) and the sigmoid (squash any number into 0–1). The whole kit is just this: Wx + b, then a bend, stacked, plus the two ideas below.

One natural misreading is worth heading off: these curves aren't there to squash numbers into a tidy range. The sigmoid happens to (everything lands between 0 and 1), but ReLU and GELU, the ones modern models actually use, are unbounded: a big input sails through nearly unchanged. (Bounded activations in fact fell out of favour: their flat tails make the learning signal of §7 vanish.) Keeping the network's numbers in a sane, comparable range is a different component's job: LayerNorm, a normalisation step you'll meet inside the block in Part 1. The bend has exactly one job: be not-a-straight-line, so stacking layers buys new shapes instead of collapsing into one.

ReLU keep positives, zero the rest -3 3 in → GELU ★ the smooth version — ours -3 3 in → 1 0 sigmoid squash anything into 0–1 -6 6 in → dashed line = no bend (y = x); sigmoid shown over a wider input range to show it flattening against 0 and 1 ★ what our tiny GPT uses
Fig. 7The three bends, plotted: each takes the number a linear layer just produced (in) and reshapes it (out). Set against the dashed no-bend line, you can see exactly what nonlinearity adds. Note ReLU and GELU are unbounded; only the sigmoid squashes into a range, and that bounding isn't the job (it's incidental, even costly). The tiny kink, stacked thousands of times, is what lets the network model curves instead of only straight lines.
6

Attention: letting tokens talk

Linear layers process each token on its own. But meaning depends on context: “bank” near “river” vs near “money.” Attention is the one step where positions look at each other: each token forms a query and asks “which earlier tokens matter to me?”, then pulls in a blend of their information. It's how the model carries context forward, the part that makes it a language model and not a bag of independent words.

And this isn't a metaphor; it's measurable. Here is the sentence from above, run through the trained Part 1 model, with one attention head's actual weights drawn as arcs:

Where does it look? — one real attention head, measured the trained Part 1 model, layer 2 of 6, head 4 of 6 — each arc’s thickness = how much of the blend 4% 43% 15% 1% 5% 5% The dragon looked at the boy and it the token asking (its “query”) — keeps 27% for itself the best-matching “key” “the” get ≈0%. This head has learned to track who the sentence is about; other heads in the same model attend to different things (recent words, sentence starts) — together they give the next layer rich context.
Fig. 8Attention, measured (not illustrated): when “it” builds its understanding, this head hands 43% of the blend to “dragon” — eight times what it gives “boy”, the other thing “it” could mean. The thickness of each arc is the real weight from the trained model, the q·k matching from Part 1's formula, drawn.

Part 0 · How learning works

7

How it learns: loss, gradients, gradient descent

Where do the millions of parameters come from? Training. Show the model real text with the next token hidden, let it guess, and measure how wrong the guess was with a single number: the loss (low = confident and right; high = wrong). Training is nothing more than making that number smaller, over and over.

The trick is knowing which way to nudge each of the millions of parameters. That's the gradient: for every parameter, the slope of the loss, telling you which direction, and how hard, reduces the error. Nudge every parameter a little down its slope, and the loss drops. Do it a few thousand times and coherent language emerges. This is gradient descent.

high loss (how wrong) a single weight (one of our model’s ~3.2 million) lowest loss current weights one step downhill
Fig. 9Gradient descent with ONE weight: picture the loss as a curve and the model as a ball. The gradient is the downhill direction; each training step rolls the ball one step lower.
lowest loss start: random weights loss (height) ↑ weight 1 → ← weight 2 each hop = one update · click to pause / resume
Fig. 10Now with TWO weights the loss becomes a landscape, and the ball replays a real gradient-descent run on this very surface (gen_loss_surface.py, constant step-size dial): at every step, feel the slope, step downhill. Watch the hops shrink on their own: nobody slows the ball down; the flatter the valley, the smaller the gradient, the smaller the update. (Real training is noisier, each batch gives a slightly different slope, which is why Part 1 §13 also shrinks the step size on a schedule.) Our model has millions of weights, a landscape in millions of dimensions, but the move never changes.

One pass of training is a loop of four steps, repeated on batch after batch of text:

① Forward pass run data → predictions model(x) ② Loss how wrong is it? cross_entropy ③ Backward pass which way is downhill loss_and_grad ④ Update one step downhill optimizer.update repeat ~2,500 times
Fig. 11The training loop: a forward pass (guess the next tokens) → compute the loss (how wrong) → a backward pass (backpropagation: work the slopes back through every layer to get each parameter's gradient) → update (nudge every parameter a little downhill). Then repeat.
8

Generating text, and the one knob: temperature

Once trained, the model generates by running its prediction in a loop: feed the text so far, get a probability for every next token, pick one, append it, repeat. “Inference” and “generation” are the same thing: running the function forward (no learning).

How you pick from the probabilities is the one knob worth feeling: temperature. Low temperature (~0.5) almost always grabs the most likely token: safe, repetitive. High (~1.1) samples more adventurously: varied, riskier, sometimes incoherent. It's the dial between “careful” and “creative,” and it changes nothing in the model, only how its output is sampled. Part 1 lets you feel it →

“Tom was very ___” same model, same scores — only the sampling temperature changes temperature 0.5 — plays it safe excited 32.8% happy 26.6% sad 21.3% scared 5.2% proud 2.9% everything else 11.2% temperature 1.1 — adventurous excited 10.9% happy 9.9% sad 8.9% scared 4.7% proud 3.6% everything else 62.0% ↑ the long tail gets a real chance Temperature reshapes how the menu is sampled, not the menu itself: at 0.5, “excited” wins ~33% of draws; at 1.1, nearly half the draws come from outside the top five — that’s where the surprises (good and bad) come from.
Fig. 12Temperature, measured on the real model: the same scores sampled two ways. Low temperature concentrates the draws on the favourite; high temperature hands nearly half of them to the long tail of everything else.
9

The honest ceiling, and where this goes

That's the whole machine: text → tokens → embeddings → stacks of (attention + Wx+b + a bend) → a final prediction, all tuned by gradient descent. A frontier model is exactly this, scaled up: more dimensions, more layers, vastly more text and compute. Same ideas; different magnitude.

And the honest ceiling: Part 1's tiny GPT produces believable shapes of language, never knowledge or reasoning. That holds even for the tuned version that writes coherent little stories. A laptop's worth of training can't buy more, and that's fine: the tiny build is for seeing every moving part, not for using. Getting something useful is a different move entirely. Part 2 sets the tiny model aside and starts from a big pretrained open model (4 billion parameters, trained at a scale no laptop can touch; that cost was paid by someone else), then specialises it for one narrow job.