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 · Textone sentence, 45 characters2 · Tokenizer12 glue rules, 268 pieces3 · Lessons22 guess-the-next questions4 · Modela transformer, 22,080 numbers5 · Training300 rounds, loss 5.60 → 0.016 · Writingpick, append, repeat7 · Testmemorised, not learned

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.

RuleGluesIntoSeen
1a + tat4 times
2t + hth3 times
3th + ethe3 times
4 and 5␣ + c, then + at␣cat2 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.

SettingValue
Vocabulary268 pieces
Numbers per piece (width)32
Attention heads2
Blocks1
Longest input23 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()
RoundLossWhat it writes after “the”
05.60random bytes
252.28the cat sat on the a d the cat was happy.
500.59the cat sat on the mat and the cat was happy.
3000.01the 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 givenWhat the model writesVerdict
thethe cat sat on the mat ancorrect
the catthe cat sat on the mat andcorrect
the matthe mat waddd the thebreaks down
the dogthe dog cat cat sat on the the matnonsense: 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%.

ModelLoss (lower is better)
Pure guessing, ln(88) for 88 characters4.477
Bigram, on text it counted2.282
Bigram, on held-out text2.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

PartStateWhat it is
One-sentence modeldone, start to finishtokenizer, transformer, training, writing and tests in one file
14-step walkthroughdoneone screen per step, with numbers from a real run
Step 1 of the larger model: countdonebigram on TinyStories, held-out loss 2.283
Step 2: tokenizernot startedbyte-pair encoding, about 4,096 pieces
Step 3: transformernot started6 blocks, width 384, about 12 million parameters
Step 4: checknot startedload GPT-2's published weights into this code and match its output
Step 5: pretrainnot startedtrain from random weights on a laptop GPU
Step 6: chat tuningnot startedteach it to answer and stop
Step 7: tool callsnot startedteach 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.