AI Run Lab

All chapters

Build and test a small language model

Train a baseline on the room questions and compare its result with a working Transformer.

Open this chapter with experiments and audio

Define the job before choosing the model

Write down a request, the information available and the result that would count as correct. Here the requests are fixed English and Dutch questions about rectangular rooms. The target is an area, a unit and a stop marker. Keep the exact multiplication as an independent answer key. It is also a sensible component if the product requirement is reliable arithmetic.

Set a harder test before tuning: keep every 8 × 8 question out of training, in both languages. If an English version went into training and the Dutch translation went into testing, the model would already have seen that combination of sides. Save the split with the project so that another developer can repeat it.

How to hold out an example · Fit a first baseline using ordinary Python

Turn a question into training targets

Start with the sides 3, 5 and 8. Pair each possible length with each possible width. Nine ordered pairs in each of two languages gives 18 prompts. Hold out the two translations of 8 × 8. The remaining 16 each supply three targets, hence 48 supervised answer positions.

Input seen so farTarget at the final position
… five metres by five metres?25
… five metres by five metres? 25m²
… five metres by five metres? 25 m²<end>

During training the correct preceding answer tokens are supplied. During generation each next prediction depends on the token the model actually selected. A test that always supplies the correct prefix can hide a problem that appears as soon as the model makes its first mistake.

Create token IDs · Compare this answer-only objective with next-token pretraining on ordinary text

Fit the baseline and inspect its first mistake

For each observed answer token, increment one table entry. In code this is counts[previous, target] += 1. To predict, divide each entry in that row by the row total. This is a bigram model fitted on answer positions. It can run on the same vocabulary as our Transformer and has just one token of context. Tied highest counts use the lowest token ID.

With all 16 questions, 15, 24 and 40 each followed the question mark four times. One tie-break therefore decides the first answer token for every room. After an observed number, the unit is much easier: all of its training continuations are m². Fitting the format of the answer required less information than determining its value.

Jurafsky & Martin · N-gram language models

Give a decoder access to the room dimensions

Use the same split, vocabulary and target positions. Change the architecture so the calculation at the question mark can depend on earlier words. In the supplied decoder, x = E[ids] + positions produces a feature row per token. Causal attention mixes information from earlier rows. A feed-forward sublayer transforms each row and the output projection gives 31 scores per position. Its six coordinates per token, single attention head and one block keep every step small enough to inspect.

The trainer compares scores with target IDs using cross-entropy. The final question mark predicts the area. Only that position and the following two answer positions contribute to the loss. All other positions, including padding, receive the ignored target −100. loss.backward() computes derivatives. optimizer.step() updates the weights. After 1,200 Adam updates the included checkpoint predicts all 48 fitted target positions. Its greedy answer for the held-out room is still 24 m². Looking farther back solved one limitation of the baseline. The vocabulary includes the correct token 64, even though it never occurs as a training target. The held-out error therefore cannot be explained by a missing output token.

Inspect a trained attention calculation · Build a neural language model in PyTorch · PyTorch · Cross-entropy and ignored targets

Reproduce the model and choose the next development step

The editable source archive contains the actual trainer under training/train_decoder.py. With Python and the PyTorch version listed there, run python training/train_decoder.py --output checkpoint.json from the extracted source folder. Inspect the vocabulary and the eight weight matrices in the JSON. The HTML reader already includes the trained model. Exporting a new file lets you compare checkpoints without changing the reader.

Use node verify-decoder.cjs on the shipped version to check the fitted cases, the held-out result, causal masking and agreement between full and cached execution. To design a new test, change the wording while keeping the dimensions fixed. Then hold the wording fixed and change the dimensions. If only the first change breaks the system, examine vocabulary coverage and wording variation. If it fails on new products, try a different training distribution or an explicit calculator.

For a shop assistant the same decisions recur at larger scale. Choose the data and licences, record the split and tokenizer version, measure a baseline, inspect its failures, and decide which part to change. New private facts can come from retrieval, actions from a tool and consistent formatting from adaptation. Each has a different cost and a different test. Adapt a model · Supply evidence · Evaluate a release · Design an agent harness