gpt-from-scratch
Two GPT language models built from scratch, following the transformer from the 2017 paper Attention Is All You Need, and trained on a laptop. One learned Shakespeare, the other children's stories. Pick one, give it a starting line, and watch it write.
Try it
The two models
Both use the same design underneath, the transformer from the paper above, and were trained the same way. What differs is what they read, how they cut it into pieces, and how big they are.
ShakespeareTinyStories
What happens when you press Generate
The model writes one small piece at a time. Here is how it picks the next one, step by step, for a fixed example.
-
The text is cut into tokens
The model can't read letters directly. It cuts the text into pieces called tokens, and each token has an ID number.
-
Each token becomes a list of numbers
Every token ID is swapped for a list of numbers the model learned during training. Similar tokens end up with similar numbers.
-
It looks back at the earlier tokens
This is called attention. To choose what comes next, the last token looks back at the ones before it. Each row is one layer of the model. Brighter means it looked there more.
Show the mathHide the math the attention equation, symbol by symbol
Equation (1) from Attention Is All You Need
Attention(Q, K, V) = softmax(QKT√dk) VQqueryWhat the current token is looking for.
KkeyWhat each earlier token has to offer.
QKTmatch scoresQuery times every key: one score per earlier token, how well they match.
√dkscalesoftmaxto percentagesScores become percentages that add up to 100%. Later tokens are masked to 0%, so it can't peek ahead.
VvalueThe information each token passes on, mixed by those percentages.
-
It scores every possible next token
The model gives each token in its vocabulary a probability of coming next. These are its ten favourites.
Show the mathHide the math softmax, with this example's real numbers
Softmax: from raw scores to chances
pi = eziΣj ezjziraw scoreThe model's score for token i (a logit). Any number, even negative.
ezexponentMakes every score positive, and big scores much bigger.
Σtotal -
It picks one, adds it, and repeats
It picks a token at random, weighted by those probabilities, so the likely ones win most of the time but not always. Then it adds the token to the text and goes back to step 1.
How it learned
Training means showing the model real text, letting it guess the next token, and nudging its numbers whenever it guesses wrong. "Loss" measures how wrong it is, so lower is better.
The story it wrote every 500 steps while training, from random noise at step 0 to real stories.
After step 2,000 it began memorising its training text (that line kept falling while the unseen-text line rose), so the step 2,000 version is the one kept.