Home › Learn › Small model from scratch
A language model from scratch, on one sentence
Every part of a language model, built and run from start to finish on the smallest corpus there can be. It is small enough to read in one sitting, and it trains in a few seconds on a laptop.
the cat sat on the mat and the cat was happy.
That line is the whole training text. The model has the same kinds of parts as a large one: a tokenizer, a transformer, a training loop and a writing loop. Only the sizes differ.
Walk through it in 14 stepsThen serve it: inferenceRun it yourself
1 · The text
A model learns only from the text it is given. Here that is 45 characters. With so little, you can check every number by eye, and you can see exactly where the model's knowledge ends.
2 · The tokenizer: cut the text into pieces
The model reads numbers, not letters. We start with the 256 possible bytes, then repeatedly find the pair of neighbours that appears most often and glue it into a new piece. This method is called byte-pair encoding. Twelve rounds give 12 new pieces, so the code book has 268 entries.
| Rule | Glues | Into | Seen |
|---|---|---|---|
| 1 | a + t | at | 4 times |
| 2 | t + h | th | 3 times |
| 3 | th + e | the | 3 times |
| 4 and 5 | ␣ + c, then + at | ␣cat | 2 times |
The sentence becomes 23 pieces: the | ␣cat | ␣sat | ␣on | ␣the | ␣mat | ␣ | a | n | d | … The sign ␣ stands for a space.
3 · The lessons: the text is its own answer key
At every position the model sees the pieces so far and has to guess the next one. After the it should say ␣cat. After the cat it should say ␣sat. Twenty-three pieces give 22 such lessons. Nobody labels anything.
4 · The model: a very small transformer
Each piece is looked up in a table to get 32 numbers, and its position adds 32 more. One block follows. In it, attention lets each piece look back at the earlier ones, and a small feed-forward layer then works on each piece by itself. At the end, the model gives a score to each of the 268 pieces.
| Setting | Value |
|---|---|
| Vocabulary | 268 pieces |
| Numbers per piece (width) | 32 |
| Attention heads | 2 |
| Blocks | 1 |
| Longest input | 23 pieces |
| Parameters (numbers the model can change) | 22,080 |
class Block(nn.Module):
def __init__(self):
super().__init__()
self.ln1, self.ln2 = nn.LayerNorm(D), nn.LayerNorm(D)
self.attn = nn.MultiheadAttention(D, HEADS, batch_first=True)
self.mlp = nn.Sequential(nn.Linear(D, 4 * D), nn.GELU(), nn.Linear(4 * D, D))
def forward(self, h):
T = h.shape[1]
no_peeking = torch.triu(torch.ones(T, T, dtype=torch.bool), diagonal=1)
a = self.ln1(h)
h = h + self.attn(a, a, a, attn_mask=no_peeking, need_weights=False)[0]
return h + self.mlp(self.ln2(h))
class TinyGPT(nn.Module):
def __init__(self):
super().__init__()
self.tok = nn.Embedding(VOCAB_SIZE, D) # brick number -> 32 numbers
self.pos = nn.Embedding(CTX, D) # position -> 32 numbers
self.blocks = nn.Sequential(*[Block() for _ in range(BLOCKS)])
self.ln = nn.LayerNorm(D)
# Start with small numbers, as GPT-2 does. PyTorch's default (std 1.0)
# makes the first scores huge: first loss ~20 instead of ~ln(vocab).
nn.init.normal_(self.tok.weight, std=0.02)
nn.init.normal_(self.pos.weight, std=0.02)
def forward(self, idx):
h = self.tok(idx) + self.pos(torch.arange(idx.shape[1]))
h = self.ln(self.blocks(h))
return h @ self.tok.weight.T # a score for every brick (weight tying)5 · Training: guess, score, nudge
The score is the loss: how surprised the model was by the right answer. Lower is better. Each round runs all 22 lessons, measures the loss, and nudges every one of the 22,080 numbers slightly in the direction that lowers it.
opt = torch.optim.AdamW(model.parameters(), lr=3e-3)
for step in range(301):
loss = loss_now()
if step in (0, 25, 50, 100, 200, 300):
out = generate("the", len(ids) - 1)
print(f" step {step:3} loss {loss.item():5.2f} writes: {out!r}")
opt.zero_grad()
loss.backward()
opt.step()| Round | Loss | What it writes after “the” |
|---|---|---|
| 0 | 5.60 | random bytes |
| 25 | 2.28 | the cat sat on the a d the cat was happy. |
| 50 | 0.59 | the cat sat on the mat and the cat was happy. |
| 300 | 0.01 | the cat sat on the mat and the cat was happy. |
The check that caught a bug. A model that knows nothing should give each of the 268 pieces an equal chance, so its first loss should be close to ln(268) = 5.59. An early version started at 19.8. The cause was PyTorch's default starting numbers for the lookup tables, which are far too large. Starting them small, as GPT-2 does, brought the first loss to 5.60. Compare the first loss with ln(vocabulary size) in any model you train.
6 · Writing: the same model in a loop
Give the model a start, take the next piece it rates highest, add it to the text, and run it again. This loop is what a serving engine does for a large model too. Here we always take the top choice; real systems usually sample, so answers vary.
@torch.no_grad()
def generate(prompt, n):
seq = encode(prompt)
for _ in range(n):
logits = model(torch.tensor(seq[-CTX:]).unsqueeze(0))[0, -1]
seq.append(int(logits.argmax())) # greedy: always the top score
return decode(seq)7 · The test: what did it learn?
| Start given | What the model writes | Verdict |
|---|---|---|
the | the cat sat on the mat an | correct |
the cat | the cat sat on the mat and | correct |
the mat | the mat waddd the the | breaks down |
the dog | the dog cat cat sat on the the mat | nonsense: it never saw “dog” |
The model has memorised one sentence. It has not learned English. A near-zero loss on the training text says nothing about new text, which is why real projects keep some text aside and score the model only on that.
What came next: a score on text the model never saw
The next model is simpler but is tested honestly. It is a bigram model: for each character, count which character came after it. It uses the validation file of TinyStories (a public set of short children's stories, about 22 MB). It counts the first 90% and is scored on the last 10%.
| Model | Loss (lower is better) |
|---|---|
| Pure guessing, ln(88) for 88 characters | 4.477 |
| Bigram, on text it counted | 2.282 |
| Bigram, on held-out text | 2.283, the number every later model must beat |
The two scores are almost equal because a table of 88 × 88 counts is too small to memorise 20 million characters. It writes things like Ont Surilked henyoom'm he!: believable letters and word lengths, no meaning. Its memory is one character.
Project details
| Part | State | What it is |
|---|---|---|
| One-sentence model | done, start to finish | tokenizer, transformer, training, writing and tests in one file |
| 14-step walkthrough | done | one screen per step, with numbers from a real run |
| Step 1 of the larger model: count | done | bigram on TinyStories, held-out loss 2.283 |
| Step 2: tokenizer | not started | byte-pair encoding, about 4,096 pieces |
| Step 3: transformer | not started | 6 blocks, width 384, about 12 million parameters |
| Step 4: check | not started | load GPT-2's published weights into this code and match its output |
| Step 5: pretrain | not started | train from random weights on a laptop GPU |
| Step 6: chat tuning | not started | teach it to answer and stop |
| Step 7: tool calls | not started | teach it to ask for a tool |
This is the first layer of LearnLLMStack, which builds a small version of every layer between an agent's question and a model's reply.
Run it yourself
The one-sentence model needs Python and PyTorch. On a recent laptop it takes a few seconds and about 300 MB of memory.
pip install torch python one_sentence_llm.py
The bigram model needs only Python. Put the two files in this layout, because the script looks for the data one folder up:
own-model/ get_tinystories.py # run first: downloads about 22 MB into own-model/data/ step1_count/bigram.py # then: python step1_count/bigram.py (about 8 seconds)
one_sentence_llm.pybigram.pyget_tinystories.py
Try this: add a second sentence about a dog, change nothing else, and run it again. Watch what happens to the loss and to the “the dog” prompt.