One token, from scratch: what a language model actually does to predict the next word
For two months I built a distributed database from scratch — storage, consensus, sharding, a
replicated log. This week I went one layer up the stack, into the systems that run on top of
exactly those primitives: AI. And I started where every language model starts — with a single
token. I wrote GPT-2’s forward pass by hand, in ~200 lines of numpy, just to watch it predict
one word.
What I built
A from-scratch GPT-2 small forward pass + sampling — no PyTorch doing the heavy lifting. It
loads the real pretrained weights, tokenizes text, runs twelve transformer blocks, and emits a
probability for every one of 50,257 possible next tokens. The done-bar isn’t “looks plausible”:
a test pins it to reproduce canonical GPT-2’s greedy output token for token. If my attention
or layernorm were subtly wrong, that test goes red.
tokens ──▶ embed + position ──▶ [ 12 transformer blocks ] ──▶ logits ──▶ sample ──▶ one token
"Alan Turing theorem" (the residual stream) 50,257 probs "."
└──────────────── append the token, then run the whole thing again ◀───────────────┘
The concepts that made it work
- It’s one function in a loop. Tokens in → a probability for all 50,257 next tokens. Pick
one, append it, run again. Chat, agents, autocomplete — every one of them is this single
function called repeatedly. That loop has a name: autoregression. - The residual stream — and you can watch it think. The model is a stack of vectors that
each block edits by addition, never replacement (x = x + attention(x), then
x = x + mlp(x)). Decode that half-finished stream after each block — the “logit lens” — and
you catch the model echoing the word it just read for ten layers, then committing to a full
stop only in the final two. Early layers copy; the last layers decide. - Attention is the only place tokens talk — and one line stops it cheating. A causal mask
sets everything to a token’s right to −∞ before the softmax, so it can only attend to what
came before. That single mask is the entire difference between predicting the future and
peeking at it. - Weight tying. The matrix that turns tokens into vectors at the input is the very same one
(transposed) that turns vectors back into word-scores at the output. Embedding and
un-embedding are literally the same parameters, used twice.
The thing that bit me
I wrote the punchline first: “per-token latency grows with context — that’s why you need a
KV-cache.” Then I ran the benchmark over 20 tokens and the numbers flatly refused to
cooperate — the first token was the slowest, and generation got faster from there. The
growth is real, but it only surfaces once the context is long and BLAS warmup stops dominating:
a forward pass over 16 tokens vs 512 is a clean 5.1×. The lesson is an old one in a new
costume — a performance claim you haven’t actually measured is just a guess. It’s the same
reason I never trusted last series’ Raft code until it survived the race detector a dozen times:
measure, don’t assert.
The smaller, more humbling bite: I asked the finished model “The capital of France is ___”,
expecting “Paris.” It greedily answered “the.” Paris was fifth, at 3%. A small model
doesn’t know facts and look them up — it predicts plausible text, and “…is the largest
city…” is a perfectly natural way for that sentence to continue. A good thing to feel in your
hands before you trust a model that sounds confident.
Tradeoffs & the road not taken
- Off-the-shelf tokenizer. I used tiktoken’s byte-pair encoder rather than building BPE
myself — a rabbit hole worth its own week, not this one. - No cache, no batch, CPU, float32. This is built to be understood, not to be fast — both
are deliberately next week’s problem. - numpy on purpose. If PyTorch’s autograd and fused attention kernels do the work, you never
find out what the work is. The whole point was to have nowhere to hide.
Where this sits in the system
Last series: a distributed database from scratch — the storage, logs, and consensus that
infrastructure is made of. This series goes up a level, into the AI stack that sits on top of
it. This week was the forward pass: one token, start to finish. Next week: the KV-cache —
stop recomputing the entire sequence every step, which is exactly the O(T²) cost this week’s
benchmark ended on. Same spine as before, new domain — one system, revealed layer by layer.
Part of a new series: building a modern AI stack from scratch, told visually.