Learning log · language models from scratch

Building a tiny LLM, one idea at a time

A small language model built from scratch in eight steps. Each step has my explanation of the concept and an interactive visual.

Method. Claude acted as tutor. For each concept I gave my own explanation, and Claude corrected it before we built the visual. Quotes are my spoken answers, condensed; corrections follow each one.

The journey

Step 01

Text becomes tokens

Tokenization "digitises" language: words have to become numbers before they can go through all the matrix multiplications. The main design choice is where to draw the line between characters and words. BPE finds common chunks and forms a middle ground.

In my words

Correction: IDs are arbitrary labels, so their numeric order carries no meaning. The model reads and writes IDs; decoding maps them back to text.

BPE starts from 65 characters and repeatedly merges the most frequent adjacent pair, learned here from about 40 lines of Shakespeare. At 0 merges it is a character tokenizer; more merges turn chunks like ·the into single tokens. Words mode maps unseen words to UNK.

Step 02

Tokens become vectors

We can't use token IDs directly because they imply false relationships: if ING is 39 and A is 40, they look close on the number line but aren't. Instead each token gets a vector, a row in a matrix, which starts random and is learned in training. The vector size is a training parameter: bigger captures more nuance but needs more parameters; smaller is easier to train but loses information. It gives us a vector database of tokens, I guess, and relationships between them.

In my words

Correction: vector size is a hyperparameter, fixed before training. The parameters are the numbers in the table, which training adjusts. The table is a lookup inside the model: token 39 selects row 39.

  • vowels
  • consonants
  • capitals
  • punctuation & space

The table
65 × 16

Row

Nearest in all 16 dimensions:

Real embeddings from a tiny model trained on Shakespeare (train/step02_embeddings.py). Hover or tap a character to see its row (16 numbers, blue negative, red positive) and its five nearest neighbours. Before training the table is random. After training, without any labels, a sits near u o e, . near ? ! ; :, and capitals cluster. The 2D view is a PCA projection and loses most of the 16 dimensions; the neighbour list is exact.

Step 03

The whole job: predict the next token

The model outputs a probability distribution over all tokens. You'd pick the max, or maybe use some epsilon strategy so you don't always take the top one. It actually outputs logits, which can be anything, and softmax squashes them between 0 and 1 so they sum to 1. The nice part is you train on the text itself: in "to be or not to be", T should be followed by O, O by a space, and so on. You get lots of training from each sentence, with no labelling or grammar rules, unlike the NLP I did at university.

In my words

Correction: each example conditions on the whole prefix, so the input grows at every position: T→o, To→·, To·→b. Better models make better use of that prefix. Picking randomly from the distribution is called sampling (Step 08).

Pick a cut point: everything before it is the input, the character at it is the answer.

A 42-character sentence gives 42 training examples. These probabilities are counts of what followed the same few characters in tiny-Shakespeare (train/step03_next_token.py); a trained model must learn to produce them. At To be → , the comma gets 0.001, because "be" is almost always followed by a space. Training penalises low-probability answers like this.

Step 04

The simplest possible model

A bigram model predicts the second token from the first. With 65 tokens that's a 65 × 65 lookup table of co-occurrence counts. Or a neural net with random values, trained with gradient descent and Adam. Either way there's no memory or attention.

In my words

Claude asked If counting works, why use a net? Consider predicting from the last 10 characters instead of 1.

That'd be a 10-dimensional grid, 65 × 65 × 65 and so on. Absolutely massive.

Claude asked Almost every cell would also be empty. How does a net handle that? See Step 02.

Its embeddings learn which characters are similar. So even with sparse data it can say: A is close to E, they're both vowels, so both come between consonants.

In my words

Correction: generation samples from the row; always taking the top character gets stuck in loops. Both versions reach the same loss: 2.455 counted, 2.459 trained.

Sampled from the table, one character at a time



          

Why a lookup table can't just get longer

Context lengthContexts in ShakespearePossibleShare ever seen
Rows are the current character, columns the next; darker is more likely. Hover a row: q is almost always followed by u, and . by a space or newline. The generated text has Shakespeare's word lengths, punctuation and line breaks, but no meaning, since each step sees one character. The table shows the limit of counting: at 10 characters, almost no possible context has ever occurred. A network generalises to unseen contexts through embeddings (train/step04_bigram.py).

Step 05

Measuring wrongness, then fixing it

Loss measures the gap between a probability of 1 for the right answer and the probability the model actually gave it. If it gave the space after "to" a probability of 0.001, loss is −log(0.001) = 6.9. We use log because it scales up exponentially (I think) the more wrong you are. Backprop gives the gradient, the slope towards zero loss, and step size is a hyperparameter. Then mini-batches for speed, Adam, and train/test splits plus a holdout set, as in standard ML.

In my words

Correction: −log is unbounded: each 10× drop in probability adds 2.3, so confident mistakes are heavily penalised. The gradient is the local slope, one number per parameter, so training takes many small steps and recomputes it each time.

Loss is −log(p), where p is the probability given to the right answer. On a log axis it is a straight line: each 10× drop in p adds 2.3.
Learning rate
  • training loss (one mini-batch)
  • validation loss (held-out 10%)
  • previous run

A bigram model training in the browser: a random 65 × 65 table of logits, trained with Adam on mini-batches of 512 character pairs from the first 90% of tiny-Shakespeare (js/bigram-trainer.js). Training loss is noisy because each mini-batch differs; validation loss is exact on the held-out 10%. A learning rate of 0.001 is slow; 3 overshoots.

Step 06

Letting tokens look at each other

Attention is a smart way to use the context before a token. Averaging it gives a murky blob; instead we learn which tokens should attend to each other. Each token gets three vectors, Q, K and V, from learned weights WQ, WK, WV. Q is what I'm looking for, K is what I offer, V is what I give when attended to. For every earlier token (with a position embedding to keep the order), the dot product of my Q with its K says how well they match, and a weighted sum of the V vectors gives a "context-aware" vector.

In my words

Claude asked Why only earlier tokens? In training the whole sequence goes in at once. What goes wrong if position 5 can see position 6?

You can't predict the next token if you can see it. So we mask to only the tokens that came earlier.

In my words

Correction: the scores pass through softmax (Step 03) before the weighted sum, so each token's attention weights sum to 1. Without the mask the model would learn to copy the answer, which fails at generation time.

Hover a character to make it the query. Shading shows where its attention goes; greyed characters are the masked future.

One row per query, one column per key, and every row sums to 1. The empty upper triangle is the causal mask.

Real attention weights from a one-layer, four-head model (train/step06_attention.py, 29k parameters). Validation loss fell from 2.48 (bigram) to 2.02. Compared with the plain average, the learned heads are selective, but a single layer mostly attends 1–3 characters back, which amounts to a learned 4-gram. Longer-range use of context needs more layers.

Step 07

Stacking it into a transformer

Stacked transformer blocks take a token embedding and add an attention component and an MLP component. The MLP I'm not sure about: it expands the token through two layers and shrinks it back. Is that just useful learning about the token itself? LayerNorm, I think, keeps the numbers from blowing up across many blocks.

My first attempt

Claude explained Attention only blends; the MLP does the "if this and that" computation. Then it asked about the parts I'd skipped: residual connections and stacking.

… I still don't get the point of the MLP. It takes x, expands it and shrinks it. But what does that vector represent?

Claude reframed it x is each token's notepad: one vector per position that every layer reads and adds to. An MLP neuron is a pattern detector, like a CNN filter. Weights +1, +1, +1 and a bias of −2 under a ReLU fire only for -eak. Averaging can't express "only if all three".

Without attention, the input is an n × 384 matrix with an MLP in each block. Is it one MLP applied to each row, or a separately trained MLP per row? … And WQ, WK, WV are three learned matrices that turn each embedding into its own Q, K and V?

Questions I asked

Claude answered One MLP per block, shared by every row, like one conv filter sliding over an image. And with no attention, no row ever sees another, so the whole stack collapses back into a bigram.

Attention learns relationships between tokens: a weighting over everything before. The MLP learns nonlinear combinations within each token's own vector. A block needs both, because attention only decides how much to weigh the context, not what to output. […] We add to the notepad rather than rewrite it, so one weird layer can't wipe out what earlier layers learned; the combination of layers gives depth and range. Layer 2 has more baked in, so it can learn more.

Where I landed

Correction: attention moves information between positions; the MLP processes it. By layer 2, a's notepad already holds information about its neighbours, so when k reads a it gets two hops of context. Each layer adds one hop.

The trained model. Hover any part. The vertical line is the residual stream; each block reads from it twice and adds its output back. GPT-3 uses the same design with 96 blocks instead of 6.

  • training loss
  • validation loss
Read a sample from step


          

Training the full model (train/step07_transformer.py). Samples progress from noise to letter frequencies, word shapes, names, line breaks and script format. After about 1,500 steps validation loss rises while training loss keeps falling: 10.8M parameters on 1 MB of text begin to overfit. No sample copies more than about 24 characters from the training text; overfitting shows up as overconfidence on seen text. The rest of the page uses the best-validation checkpoint (early stopping). Dashed lines are earlier models on the same held-out text.

Same seed, three models

Step 08

Making it talk

The loop does a full forward pass per character, using a KV cache so it doesn't redo the ones it's already done. The context window slides once we pass the max length. We can't go back and try a different branch once we've committed. Temperature sets how far we stray from greedy. A prompt is just the start of the text.

In my words

Claude noted A KV cache is an optional optimisation; this model reruns the whole window for every character. It then asked which way temperature goes, and what top-k is for.

Temp 0 is ice cold, total greed; higher is more random. I don't know why 1 is the "real" distribution. Top-k cuts the long tail in case it derails the whole thing.

Claude answered Dividing by 1 changes nothing, so T = 1 is the distribution training produced: cross-entropy (Step 05) fits softmax(logits) to observed frequencies. Other temperatures adjust it at generation time.

Correction: each rare character is unlikely, but together they account for a few percent per step. In the replay below, the chance of 300 characters with no pick outside the top 10 is tiny. A bad pick stays in the context and affects everything after it.


          
Top-k

The real model's next-character probabilities at each step of one generation, with temperature and top-k applied to its logits. Faint marks show the T = 1 distribution. The text was sampled at T = 1 without top-k, which explains the invented words. Below about 0.5 the top choice dominates; above 1.5 probability spreads across the alphabet. Near the end the prompt leaves the 256-character window.
Prompt
Top-k
Temperature

          

Finished 300-character generations (train/step08_generate.py), all from one seed. At 0.1 the output is real words in repetitive loops: "the sea of the sea of the field". At 2.5 it is mostly noise. Top-k has the most effect at high temperatures, roughly doubling the share of real words. HAMLET does not appear in the training text, but the model still continues it as a script.

Where I ended up

The result is a 10.8M-parameter transformer that writes plausible Shakespeare-style text. Validation loss fell from 4.17 (uniform guessing) to 2.48 (bigram), 2.02 (one attention layer) and 1.46 (full model). Each improvement came from using more context.

Production chat models use the same loop at far larger scale, with subword tokens, more parameters and data, and further training on conversations.