Train a tiny GPT πΈ (it names frogs)
You've heard that ChatGPT "just predicts the next word". Fine. But how does guessing the next letter turn into inventing a frog that doesn't exist? Most explanations show a diagram of boxes labelled "attention", you nod along, and the magic stays magic.
Let's find out the only honest way: by training one, right here, in about a minute.by opening one up and looking at every number. In this article you train a real GPT (a tiny one, with about 107,000 knobs) on your own graphics card, and it learns to invent names of plants and animals.In this article a real GPT (a tiny one, with about 107,000 knobs) trains on a graphics card, and it learns to invent names of plants and animals. You tell it what to invent with an emoji: π π¦ π πΈ π π³ πΈ πΎ. Nothing is pre-recorded. Every number you see is computed in your browser while you watch.Your browser doesn't have WebGPU, so the training demos replay runs recorded with this exact code, and say so. Every other number you see is computed in your browser while you watch.Your browser doesn't have WebGPU, so the training demos can't run here. Every other number you see is computed in your browser while you watch. β¨
How to read this page: under each demo there are three drawers. β¦ Numbers shows the current values, β Math the exact formulas with live numbers, and π Python NumPy code you can edit and run right here, on the same model the demo uses. The main text makes sense with every drawer closed, so open them only when you want to go deeper. Some demos end with a small Try this challenge: the page checks it on the demo itself, and your β stays.
The whole idea in one picture
A GPT is a next-letter guesser. Give it the start of a name and it gives back a probability for every letter that could come next. Pick one, stick it on the end, and ask again, until it picks "the name ends here". That's all generating text is. The πΈ at the front is just the first token, and every guess depends on it: a prompt is just the first tokens. Training is the red loop: show the model real names, measure how surprised it was by each real next letter, and nudge every knob so it's a little less surprised next time. The rest of this article opens up each box.
About the π Python drawers: once this page has loaded, it downloads Pyodide (CPython compiled to WebAssembly) plus NumPy in the background, about 10 MB, so by the time you open a drawer Python is usually ready. Your code runs entirely in your browser; nothing is sent to a server.
A model that has read every frog: the dataset
Before a model can invent a frog, it has to read a lot of real ones. Ours learns from 9,997 names of real plants and animals, taken from Wikidata, a free public database. They come in eight types, each with its emoji: dogs, birds, fish, frogs, snakes, trees, wildflowers and grasses. Every name is lowercase, at most 24 characters long, and uses only the letters a to z, spaces, hyphens and apostrophes.
β¦ Numbers
π Python
What to notice: each type has a sound. 72% of the frog names end in "frog", and 59% of the snakes in "snake". Trees end in "oak" or "willow", grasses in "grass" or in long words like "panicgrass" and "alkaligrass". Birds and wildflowers are much more varied: their most common last words, "warbler" and "daisy", cover only 3 or 4% of them. The model has to pick up these patterns by itself, and the emoji is how we'll ask for one type or another.
We hold 999 of the names aside as the validation set. The model never trains on them. They're how we'll check whether it learned the patterns or just memorised the list.
Letters to numbers: tokens
A model can't read letters. It only does arithmetic, so first we turn each name into numbers. The simplest way is one number per character, and each of those pieces is called a token. Our vocabulary has 38 of them: the 29 characters that appear in the names, one token for each of the 8 emoji, and one special token, ".", which means "the name ends here".
β¦ Numbers
π Python
What to notice: every name starts with its emoji and ends with ".", token 0. The emoji isn't part of the name. It's there so the model knows what to invent, and every guess after it can look back at it. That's all a prompt is: the first tokens. When you type a question into ChatGPT, it works the same way, with many more tokens.
Big models use bigger tokens: whole words or pieces of words like "frog" and "ing", tens of thousands of different ones. We use single characters, so the vocabulary is tiny and you can see every token.
Guess the next letter: counting
Now the real question: given the tokens so far, what comes next? Let's start with the simplest model that could possibly work, one that doesn't learn at all. Look only at the last token, and count. In the training names, how often does "r" come after "f"? How often does a name end right after "g"? Count every pair of neighbours in the 8,998 training names and you get a 38 Γ 38 table of counts, called a bigram model. To guess the next token, look up the row of the last one.
β¦ Numbers
β Math
Write \(N_{a,b}\) for how many times token \(b\) follows token \(a\) in the training names, and \(V = 38\) for the number of tokens. The probability of \(b\) after \(a\) is its share of row \(a\), with one twist:
$$p(b \mid a) = \frac{N_{a,b} + 1}{\sum_c N_{a,c} + V}$$The +1 is add-one smoothing (also called Laplace smoothing): pretend every pair was seen once more than it was. Without it, a pair that never happened in training gets \(p = 0\), its surprise \(-\log 0\) is infinite, and one unusual validation name would make the whole loss infinite. Generate samples from the raw counts, without the +1.
The surprise of one guess is \(-\log p\) (the natural log) of the probability given to the token that really came next. The loss is the average surprise over all \(n\) predicted tokens of the validation names, every letter and every end:
$$L = \frac{1}{n}\sum_{i=1}^{n} -\log p(x_{i+1} \mid x_i)$$Right now, for the selected cell, and for the whole validation set (\(\log 38\) is the loss of guessing every token equally often):
π Python
What to notice: the generated names look letter-shaped. A "q" is followed by "u" (156 times out of 157), vowels and consonants mostly take turns, and names stop after letters that often end a word. But look at the πΈ name. The emoji's row picks the first letter, and that's the only time the emoji is ever looked at. After one letter, the model has forgotten what it was making. The row for "r" is the same whether it's writing a frog or an oak.
How good is it, as a number? Let's score it on the 999 validation names. For each real next token, look up the probability the counts gave it, \(p\), and take \(-\log p\), the surprise. A sure, right guess (\(p = 1\)) costs 0. A guess that gave the right answer only a 1% chance costs 4.6. The average surprise over every next token is the loss, the same cross-entropy as in the neural network article. For counting pairs it's 2.59. Guessing all 38 tokens equally often would score \(\log 38 = 3.64\). Remember 2.59: it's the number our GPT has to beat.
Why counting can't remember: context
The counting model forgets everything but the last token. The obvious fix is to count longer contexts: instead of "what follows r?", ask "what follows πΈ fr?". But then the table needs one row for every possible run of \(k\) tokens: 38 rows for one token, 38 Γ 38 = 1,444 for two, 38Β³ = 54,872 for three. Let's see how many of those rows the training names actually fill.
β¦ Numbers
π Python
What to notice: at \(k = 1\), 37 of the 38 rows have data (only "." never comes before anything). At \(k = 3\), 86.4% of the 54,872 rows are empty. At \(k = 6\) the table has 3,010,936,384 rows and the training names fill 50,202 of them: 99.998% of the table is empty. Worse, the rows we'd need are often missing. In the validation names, 31% of the guesses that have six tokens before them follow six tokens that never appear together in training, so a six-token counting table has nothing to say about almost a third of its guesses.
Our names are at most 24 characters long. A chatbot looks back over thousands of tokens, and no table could ever hold that. We need a model that learns which earlier tokens matter, so that "slender bush fr" and "giant tree fr" can share what they know about frogs instead of each needing a row of its own. That's what a GPT does, and it starts by turning every token into a little arrow of numbers.
Each letter becomes a little arrow: embeddings
The first thing our GPT does with a token is look it up in a table. The table is called wte.weight (GPT-2's name for it: word token embeddings), and it has one row for each of the 38 tokens, 64 numbers per row. "a" is token 12, so its row is row 12. That row is the token's embedding: an arrow in a space with 64 directions. Nobody picks these numbers. They start random, and training nudges them along with every other weight, so letters the model can use in the same way end up pointing the same way.
We can't draw 64 directions. So the map below does what a shadow does to a 3-D object: it finds the two directions in which the 29 letters spread out the most, and shows where each letter falls on that flat plane. This is called principal component analysis, or PCA. Two kinds of token are left out. The model never reads "." (it only ever predicts it), so training never pushes on its row. And the 8 emoji only ever come first; they get their turn in the next section.
β¦ Numbers
β Math
Write \(e_t\) for the 64 numbers of letter \(t\) (its row of wte.weight). Take the average arrow \(\mu\) of the 29 letters, and the 64 Γ 64 table \(C\) of how the numbers vary together (the covariance):
The direction of largest spread is the eigenvector \(v_1\) of \(C\) with the largest eigenvalue \(\lambda_1\); \(v_2\) is the next one, at a right angle to it. Each letter's place on the map is how far it reaches along each:
$$C\,v_1 = \lambda_1 v_1 \qquad x_t = (e_t-\mu)\cdot v_1 \qquad y_t = (e_t-\mu)\cdot v_2$$\(\lambda_1\) is the spread (variance) along \(v_1\), so \(\lambda_1 / \operatorname{tr} C\) is axis 1's share of all the spread. The page finds the eigenvectors with Jacobi rotations. An eigenvector can point either way, so the page flips each axis so that the letter farthest out lands on the positive side; that keeps the picture from flipping. The closest letters use the cosine similarity, which compares directions and ignores lengths (1 means the same direction, 0 a right angle):
$$\cos(a, b) = \frac{a\cdot b}{\lVert a\rVert\,\lVert b\rVert}$$Right now, for the selected letter and its closest one:
π Python
What to notice. Nobody told the model what a vowel is, yet all five vowels land on the left of the map, and j, z and q on the right, with q the farthest out of all. That fits: q is the rarest letter in the training names, and there it's followed by "u" 156 times out of 157, so it has a job no other letter shares. Tap a vowel: its closest letters, measured with all 64 numbers, are mostly other vowels. And the space and the hyphen are each other's closest letter, which makes sense, since both separate the words of a name. I trained the model four times from different random starts (the one above, a PyTorch version, and two more runs of this page's trainer), and all of this held every time.
One warning: the map is a shadow. Its two axes hold only about a fifth of the spread (the labels say how much), so two letters that look close on the map can still be far apart in the other 62 directions. That's why the closest letters are measured with all 64 numbers. Big models do the same with tens of thousands of tokens and thousands of numbers per token, and the same thing happens there: tokens used in similar places end up pointing in similar directions.
But an embedding is the same arrow for every "r", whether it's in a frog or an oak. There's a second table, wpe.weight, with one row for each of the 26 positions, and the model adds the position's row to the token's row, so it knows where each letter sits. Still, to know what it's making, a letter has to look at the letters before it. That's the next idea, and the most important one.
Looking back: attention
Here's the trick that makes a GPT a GPT. At every position, the model asks a question of all the tokens before it and decides how much to listen to each one. From its arrow of 64 numbers, each token makes three short arrows of 16: a query ("what am I looking for?"), a key ("what do I have?") and a value ("what I pass on"). A letter's query is compared with the key of every earlier token by a dot product (multiply the matching numbers and add them up), and a big result means a good match. A softmax turns those scores into weights that add up to 100%, and the letter takes that mix of the values. A letter only ever looks back: when the model is writing, what comes next doesn't exist yet.
Our model does this with 4 heads side by side, each with its own query, key and value, so each can look for something different. And it does it twice, in 2 layers, the second one looking at what the first one gathered. That's 8 attention maps for every name.
β¦ Numbers
β Math
Take the letter at position \(i\) and one head. Write \(h_j\) for token \(j\)'s 64 numbers as this layer reads them (after layer norm, which rescales each arrow to a standard size; more on it in the next section). The head's query and key matrices \(W_Q\), \(W_K\) are its 16 columns of attn.c_attn.weight, with their biases:
The score of every earlier token \(j \le i\) is a dot product, divided by \(\sqrt{16} = 4\) so the scores don't grow just because the arrows have more numbers. The softmax turns scores into weights \(a_{ij}\) that add up to 1:
$$s_{ij} = \frac{q_i \cdot k_j}{\sqrt{16}} \qquad a_{ij} = \frac{e^{\,s_{ij}}}{\sum_{j' \le i} e^{\,s_{ij'}}}$$Subtracting the largest score \(m\) before taking \(e^{s}\) doesn't change the weights; it only keeps the numbers small. The head then passes on \(\sum_j a_{ij} v_j\), its mix of the values. Right now, for the selected letter:
π Python
What to notice. Does the πΈ still steer, a dozen letters later? The demo starts on the "g" of "frog": look at the small maps of layer 1. To check that it isn't a fluke of one name, I measured it over 20 frog names from the validation set. In the pretrained model, head 3 of layer 1 puts on average 55% of the attention of "f", "r", "o" and "g" on the πΈ, and head 1 puts 31%. Spread evenly over everything before them, each token would get 6%. In layer 2, no head goes above 7%. And it isn't only "frog": in the same names, the other letters from the fifth token on give that head's πΈ 40% too, where an even spread would give them 11%. Every letter can read the prompt directly, however far back it is, and that's how the emoji keeps steering until the name ends.
Which head does the job depends on the random start. The other three models from the embedding section, each trained from different random numbers, agree on the shape: each time, one head of layer 1 put between 38% and 62% of the letters' attention on the πΈ, and in layer 2 no head went above 7%. Your own model from the nursery below starts from the same random numbers as mine, so it should look much like the pretrained one. Does it? Train it, then switch the model chip here and look.A model trained in the nursery below starts from the same random numbers as mine, so it should look much like the pretrained one. Checking that needs WebGPU, which your browser doesn't have. A chatbot uses this very trick at a much larger scale: the last word of a long answer can still look straight back at your question, thousands of tokens earlier. Attention gathers; what the model does with what it gathered comes next.
Thinking about what it saw: the block
Attention lets each letter gather what it needs from the tokens before it. Now each letter has to do something with what it gathered. That happens in a block, and a block has only two steps: attention, then a small neural network called the MLP (a multi-layer perceptron, the same stack of weighted sums from the neural network article). Our model has two blocks, one on top of the other: those are its 2 layers.
Each letter keeps its own arrow of 64 numbers all the way through. Think of it as a stream running down the page: the token's row of wte.weight plus its position's row of wpe.weight go in at the top, and every step reads the stream, works something out, and adds its answer back in. Nothing ever replaces the stream; it only gets added to. That's why it's called the residual stream.
Before each step there's one more small move, layer norm. The stream's arrow can be long or short, and a step works better when its input always has the same size. So layer norm takes the 64 numbers, subtracts their average, and divides by their spread (the standard deviation). Whatever came in, out comes an arrow with average 0, spread 1 and size \(\sqrt{64} = 8\). Then it multiplies each number by a learned gain and adds a learned bias (ln_1.weight and ln_1.bias before attention, ln_2 before the MLP), so the model can still stretch the directions it cares about.
β¦ Numbers
β Math
Write \(x\) for the letter's 64 numbers as they enter the block. Layer norm uses their mean \(\mu\) and variance \(\sigma^2\), with a tiny \(\epsilon = 10^{-5}\) so it never divides by zero, then the learned gain \(\gamma\) and bias \(\beta\):
$$\mu = \frac{1}{64}\sum_j x_j \qquad \sigma^2 = \frac{1}{64}\sum_j (x_j-\mu)^2 \qquad z_j = \frac{x_j-\mu}{\sqrt{\sigma^2+\epsilon}} \qquad \text{LN}(x)_j = \gamma_j z_j + \beta_j$$The size of \(z\) is \(\sqrt{64\,\sigma^2/(\sigma^2+\epsilon)}\), a hair under 8 for any arrow. The block is two adds. The MLP turns 64 numbers into 256 with mlp.c_fc, squashes them with GELU, and turns them back into 64 with mlp.c_proj; it sees only this letter's own arrow:
Right now, for the selected letter and layer:
π Python
What to notice. Follow the "g" of πΈ slender bush frog in the pretrained model. It enters with size 1.42. Attention in layer 1 adds a little (2.24), then the first MLP hands back an arrow of 9.89 and the stream jumps to 10.33. That isn't one odd letter: averaged over all 17,420 positions of the validation names, the size goes 1.5 β 2.6 β 10.6 β 11.2 β 12.2, and layer 1's MLP does most of the growing. Now look at layer 2's attention. It hands back an arrow of 4.99, yet the stream only goes from 10.33 to 10.70. The new arrow mostly points sideways, so it turns the stream rather than stretching it: the size alone doesn't show everything a step does. And at every layer norm, whether 1.42 or 10.33 comes in, the arrow is rescaled to size 8 before the learned gain and bias stretch it again; the boxes show its size after them.
That's the whole architecture of a GPT: blocks of attention and MLP, each wrapped in a layer norm and an add, stacked. GPT-2 small stacks 12 of these blocks and GPT-3 stacks 96, with longer arrows, but each one is this same block. After our second block, one last layer norm (ln_f) and one last table, lm_head.weight, turn each letter's 64 numbers into 38 scores, one for every token that could come next. Let's see how scores become a guess.
Scoring the guess: softmax and the loss
The 38 scores are called logits. They can be any numbers, negative or positive, so the model turns them into probabilities with a softmax: raise \(e\) to the power of each score (which makes it positive) and divide by the total (which makes them add up to 1). A bigger score means a bigger share. That's the same softmax attention uses to share out its weights; here it shares out the guess.
β¦ Numbers
β Math
Write \(z_k\) for the logit of token \(k\) (the row of ln_f's output times lm_head.weight, plus lm_head.bias). The softmax gives every token its probability; subtracting the largest logit \(m\) first changes nothing but keeps the numbers small:
The surprise of the token that really came next is \(-\log p\), and the loss is its average over every next token: each letter, and the end. This is the cross-entropy, exactly as for counting pairs, so the numbers can be compared:
$$L = \frac{1}{n}\sum_{i=1}^{n} -\log p(x_{i+1} \mid x_1, \dots, x_i)$$The difference from counting is in the bar: \(p\) now depends on every token before, not just the last one. Right now:
π Python
What to notice. After "πΈ slender bush ", the pretrained model gives "f" 92%: it knows it's writing a frog, so the surprise of the real "f" is only 0.08. The very first letter is a different story. Frogs start with almost anything, so the real "s" got just 12%, a surprise of 2.15. And after "slender " the model bet on "r" (19%) ahead of the real "b" (10%, surprise 2.29). Averaged over every letter and the end, this name's loss is 0.58.
Now score the whole validation set the same way we scored counting pairs: the surprise of every next token, letters and ends, in all 999 held-out names. The pretrained GPT gets 1.45, against 2.59 for counting pairs and 3.64 for guessing blindly. Same names, same tokens, same definition (the cross-entropy from the neural network article): the only difference is that each guess can look back at the whole name, emoji included, instead of at one token. The demo works out this number live for whichever model is active, so once you've trained your own, it shows yours.The demo works out this number live, for the model the page uses.
The 1.45 belongs to weights I trained. Training is nothing more than the search for weights that make this number small, by nudging all of them, again and again, in the direction that lowers it.
Training: your GPUa GPU does the arithmetic
Time to raise one. The model below starts with random weights, so its first names are random letters of random lengths. Press Train, and your graphics card runs 4,000 training steps.Training needs WebGPU, which your browser doesn't have, so the grid below replays a run of this exact code on an M1 GPU: 4,000 training steps.Training needs WebGPU, which your browser doesn't have, and the recorded run couldn't load, so the grid below only shows the untrained model's first guesses. A full run is 4,000 training steps. Each step shows the model 32 real names, measures its surprise at every real next letter, and nudges all 106,662 weights a little downhill (the same gradient descent and backpropagation as in the neural network article). Every 100 steps, the page copies the weights back from the GPU, asks the model for five fresh names of each type, and adds a row to the grid.
The bar under each emoji is a style check. A simple letter-pattern check guesses which type each name looks like, and the bar shows how many of the five names it thinks belong to their emoji.
β¦ Numbers
The training state, updated while this drawer is open. The gradient norm βgβ of each tensor is from the last step's batch, read back from the GPU at each checkpoint; βwβ is the size of the weights themselves. Tensor names are GPT-2's.
β Math
Each step, the GPU computes the gradient \(g\) of the loss for every weight \(w\) (backpropagation), then updates every weight with AdamW. It keeps two running averages per weight: \(m\), the recent direction, and \(v\), the recent size of the gradient:
$$m \leftarrow \beta_1 m + (1-\beta_1)\,g \qquad v \leftarrow \beta_2 v + (1-\beta_2)\,g^2$$ $$w \leftarrow w\,(1 - \eta_t\lambda) \;-\; \eta_t\,\frac{m / (1-\beta_1^{\,t})}{\sqrt{v / (1-\beta_2^{\,t})} + \epsilon}$$Dividing by \(\sqrt{v}\) gives every weight a step of roughly the same size \(\eta_t\), whether its gradient is tiny or huge. The \(1-\beta^t\) terms undo the averages' start at zero, and \((1-\eta_t\lambda)\) is the weight decay, a gentle pull toward zero. Here \(\beta_1 = 0.9\), \(\beta_2 = 0.999\), \(\lambda = 0.01\), \(\epsilon = 10^{-8}\). The learning rate \(\eta_t\) climbs from 0 to 0.003 over the first 100 steps, then follows a cosine down to 0.0003 at step 4,000:
$$\eta_t = \eta_{\min} + \tfrac12(\eta_{\max} - \eta_{\min})\left(1 + \cos\frac{\pi\,(t - 100)}{4000 - 100}\right)$$Right now:
π Python
What to notice. Step 0 is random letters, often 20 or more of them. After only 100 steps the model already writes short made-up words separated by spaces, but it still mixes up the types (in my run, a π name ended in "frake"). The πΈ column is the quick learner: in my run most frog names ended in "frog" by step 300, while snakes and grasses needed a few hundred steps more to sound like themselves. Then look at the end of the loss curve. The dark training loss keeps falling, while the red validation loss, measured on 999 names the model never trains on, falls more slowly and stays above it. The model is getting better at the names it has seen than at names in general. Keep that gap in mind; we'll come back to it.
Your laptop just didA GPU running this code does what the big labs do, at a smaller scale: the same loop of guess, measure the surprise, nudge every weight, repeated thousands of times. A large language model runs this loop with billions of weights instead of 106,662, on trillions of tokens instead of about 9,000 names, across thousands of GPUs instead of one.
Steering it: prompts and temperature
You've now seen every piece, so let's write with it. Generating is the loop from the first picture: put the emoji in, take the bar of probabilities for the next token, draw one token at random in proportion to its bar, stick it on the end, and repeat until the model draws "the end" (or the name reaches 25 letters, all the model can hold). The emoji tokens are switched off while drawing, so one can never turn up in the middle of a name. Two knobs steer the result.
The first is the prompt, the emoji. It's just the first token, but as the attention section showed, every later letter can look back at it. The second is the temperature. Before the softmax, every logit is divided by it. Below 1, the gaps between the scores grow, so the favourites take even more of the bar and the model plays safe. Above 1, the gaps shrink, the bar flattens, and unlikely letters get a real chance. The nursery's names are drawn at 0.8.
β¦ Numbers
β Math
With temperature \(\tau\), token \(k\) gets
$$p_k = \frac{e^{\,z_k/\tau}}{\sum_{k'} e^{\,z_{k'}/\tau}}$$where the sum leaves out the 8 emoji. At \(\tau = 1\) this is the plain softmax the loss uses. As \(\tau \to 0\), all the probability goes to the largest logit; as \(\tau\) grows, every token heads toward the same share. The entropy \(-\sum_k p_k \log p_k\) measures how spread out the bar is (0 for a sure thing, \(\log 30 = 3.40\) for 30 equal keys). Drawing a token: take a uniform random \(u\) between 0 and 1 and walk the keys, subtracting each \(p_k\), until \(u\) drops below 0. Right now, for the bar in be the sampler:
π Python
What to notice. I generated 40 names with the pretrained model at temperature 0.3 and 40 more at 1.6, five per emoji, with the same random numbers both times, and counted. At 0.3 the model plays it safe. 89% of the words in its names are words from real names, a letter-pattern check matches every one of the 40 to its emoji, and 5 of them are real names. It also leans on the same few safe words: the π³ names were "chinese willow" (twice), "chinese oak", "bare-leaved willow" and "swamp willow". At 1.6 none of the 40 are real, only 21% of the words are words from real names, and the letter-pattern check matches just 55% to their emoji. The π names include "darteybianstasss". The default, 0.8, sits in between (54% real words, 85% matched), which is why the nursery uses it: new names that still sound right. Other random numbers give the same picture.
When you play the sampler yourself, you're doing exactly what Generate does, with your own taste in place of the random draw. Chatbots have this same temperature knob: low for answers that should be predictable, higher for brainstorming. But look at the badges. At low temperature the model writes some real names, ones that are in Wikidata's list. Did it learn that they sound right, or did it just memorise the list it trained on? That's the next question.
Learning by heart: overfitting
Those real names raise a fair worry. Maybe the model didn't learn what a frog name sounds like at all, and simply memorised its list. The nursery's loss curve already hinted at it: by the end, the dark training loss sits below the red validation loss. Let's push that to the extreme. Give the same model only 50 names per type, 400 in all instead of about 9,000, and train it for 1,500 steps. With 32 names per step, it sees each of its 400 names about 120 times.
Watch the two curves. The dark one is the surprise on the names it trains on. The red one is the surprise on the 999 validation names, which it never trains on: the same held-out names, and the same loss, as in the nursery. The bars underneath count how many of the 40 names it writes at each checkpoint are real.
β¦ Numbers
β Math
Both curves are the same cross-entropy, the average surprise \(-\log p\) of each real next token, measured on two different sets of names:
$$L_{\text{train}} = \frac{1}{n}\sum_{\text{its 400 names}} -\log p(\text{next} \mid \text{before}) \qquad L_{\text{val}} = \frac{1}{m}\sum_{\text{999 held-out names}} -\log p(\text{next} \mid \text{before})$$Training only ever lowers \(L_{\text{train}}\): the gradient comes from its own names. \(L_{\text{val}}\) is the honest score. When the gap \(L_{\text{val}} - L_{\text{train}}\) keeps growing, the model is fitting its own names at the expense of names in general. Right now:
π Python
What to notice. In my run the red curve bottoms out at step 200, at 2.50, nowhere near the 1.45 of the full run. Then it turns upward and never comes back. By step 1,500 it reaches 5.63, worse than the random weights at step 0 (3.63), while the dark training loss falls to 0.25. The bars tell the same story in names. There are no real names up to step 400. Then they flood in: from step 900 on, 34 to 38 of the 40 names are real, and 38 of 40 at the end. Every single one of them is one of its own 400 training names. Runs from seeds 2 and 3 do the same: the low point comes by step 200, the validation loss ends above 5.6, and at least 38 of the 40 final names are real.
This is overfitting: the model has learned its 400 names by heart instead of learning what names sound like. A training loss of 0.25 is memory, not skill, and only the held-out names can tell the two apart. The full run in the nursery had about 9,000 names and stopped at 4,000 steps, while its validation loss was still edging down. That's the point of the validation split. It's also why big models need so much data: a model with billions of weights could memorise a small dataset easily, so labs feed it trillions of tokens and keep watching a held-out loss the whole time.
One model or eight: sharing what it learned
Our model learns all eight types at once, and the emoji tells it which one to write. Is that a good idea? Take πΎ grasses, the smallest type (782 names). A model trained on grasses alone wouldn't have to share its weights with frogs and birds. But it would see only 704 training names instead of about 9,000, and miss everything the other types teach about names in general: where spaces go, words like "common" and "giant", hyphens. Which effect wins? Let's train one and see.Here is one, trained.
The πΎ-only model has the same shape (2 blocks, 64 numbers per token, 4 heads), is trained for 1,500 steps from seed 1, and has its own 31-token vocabulary: the end, πΎ and the 29 characters. It has no use for the other 7 emoji. Both models are scored on the same 78 πΎ validation names, which neither trains on. Those 7 emoji are the only tokens the two vocabularies don't share, and they never come up as an answer. Taking them out of the 8-type model's softmax changes its loss by less than 0.001, so the two losses can be compared directly.
β¦ Numbers
β Math
Both losses average \(-\log p\) over the same targets: every letter and the end of the 78 πΎ validation names, each read after its πΎ token. The 8-type model spreads \(p\) over 38 tokens, the πΎ-only one over 31. To check that the 7 extra emoji don't handicap it, score the 8-type model with its softmax over the 31 shared tokens \(S\) only:
$$p_S(k) = \frac{e^{\,z_k}}{\sum_{k' \in S} e^{\,z_{k'}}} \quad (k \in S)$$The style match is the share of the 200 names, drawn at temperature 0.8, that the trigram check from the nursery files under πΎ; new is the share that isn't one of the 704 πΎ training names. Both models are measured with their weights rounded to 16-bit numbers, the way the pretrained model ships. Right now:
π Python
What to notice. I trained the πΎ-only model three times, from seeds 1, 2 and 3, and compared each with an 8-type model trained from the same seed: seed 1 is the pretrained model, and seeds 2 and 3 are two more runs of the full training. Each row scores 200 names per model.
| seed | πΎ only: val loss (lowest, at step) | style | new | 8 types: val loss | style | new |
|---|---|---|---|---|---|---|
| 1 | 2.18 (1.68 at 400) | 94% | 12% | 1.46 | 89% | 99% |
| 2 | 2.34 (1.74 at 600) | 98% | 8% | 1.51 | 86% | 98% |
| 3 | 2.33 (1.71 at 400) | 97% | 9% | 1.49 | 83% | 98% |
On the loss, the shared model wins every run, and by a lot: 1.46 to 1.51 against 2.18 to 2.34. The πΎ-only model overfits like the 50-name lab. Its validation loss bottoms out early (1.68 to 1.74, at step 400 or 600) and climbs after that, and even caught at its best moment it loses. The style check seems to say the opposite: 94 to 98% of the πΎ-only names sound like grasses, against 83 to 89% for the shared model. But look at the last column. Only 8 to 12% of the πΎ-only model's names are new. The rest are copied straight from its 704 training names, and copies score well on a style check almost automatically: the check files 97% of those 704 real grass names under πΎ. The shared model writes 98 to 99% new names. The πΎ-only model writes so few new ones (16 to 23 of 200) that they can't tell us whether its inventions sound any better.
So for grasses, the small type I checked, one shared model beats a model of its own: it predicts unseen grass names better, and it invents instead of copying. The other seven types teach it how names are spelled in general, and the emoji only has to steer. That's the bet behind large language models too: one model trained on everything and steered by its prompt, rather than one model per task.
Your list, your GPTYour list, its own GPT: the playground
Nothing in the model knows about frogs. It sees tokens, and the tokens came from a list. So let's give it a different list. Paste anything, one name per line: dishes, street names, PokΓ©mon, your team's project names. Put an emoji and a space in front of a line to give it a type, like the πΈ in the nursery, or leave them off for a single kind of name.
The page builds a vocabulary just for your list: the end token, your emoji (up to 8), then every character your names use, up to 128 tokens in all. Characters are normalised first (NFC), so an "Γ©" typed two different ways is one token, and lowercased unless you untick lowercase. The context grows to fit your longest name, up to 48 tokens. The rest is the model you already know: 2 blocks, 64 numbers per token, 4 heads, AdamW, seed 1. To start you off, I've pasted 301 everyday names in three types: π fruit, π₯ vegetables, πΏ herbs and spices. The π Vietnamese dishes chip swaps in 50 dishes instead.
β¦ Numbers
β Math
Your list changes two numbers of the model, the vocabulary size \(V\) and the context length \(T\). Everything else stays: \(d = 64\) numbers per token, \(L = 2\) blocks. The number of weights is the token table and the position table, then per block two layer norms (\(2 \cdot 2d\)), the attention (\(d \cdot 3d + 3d\) and \(d \cdot d + d\)) and the MLP (\(d \cdot 4d + 4d\) and \(4d \cdot d + d\)), then the last layer norm and the output layer:
$$N = Vd + Td + L\,(12d^2 + 13d) + 2d + dV + V$$For your list right now:
π Python
What to notice. A list of 301 names is small: the nursery trained on about 9,000. So the playground trains for about 15 passes over your list (at least 200 steps), and it keeps the checkpoint where the red validation loss was lowest, marked with a ring. With the starting list that's step 100. The validation loss fell from 3.53 to 2.62 there, then started to rise (2.65 at step 200) as the model began to learn its list by heart. Every one of 300 names I drew from the kept model was New!, like "rotterd sager" πΏ and "hy pean" π₯: made-up words with the shape of the real ones, spaces and all, though not good names yet. More names make better inventions. With 2,000 π¦ birds and πΈ frogs from this article's own data (900 steps, about 4 s at β‘ full), the validation loss kept falling, to 1.58, and 99% of 200 names were New!, like "polinesan swarbler" and "yellow-leasted warbler". The 50 dishes go the other way. By step 200 their validation loss is back up to 3.17, and even the kept step-100 model copies about half its names straight from the list.
The model never knew it was naming frogs. Give the same few hundred lines of code a different list and it learns that list's patterns instead. That's the general part of a GPT: the architecture doesn't change, only the data does.
From here to the big ones
Your modelThis page's model has 106,662 knobs. The models behind chatbots have billions. What changes between the two? Less than you'd think. GPT-2, the model OpenAI released in 2019, has exactly the pieces you met on this page: a token table and a position table, blocks of layer norm, attention and MLP adding into a residual stream, a softmax over the vocabulary, and a cross-entropy loss. Its layer norms even come first in each block, like ours. That's why the tensors in your model fileits model file carry GPT-2's own names: wte.weight, h.0.attn.c_attn.weight, lm_head.weight. A modern open model like Llama 3.1 8B changes a few pieces, but the loop is the same: guess the next token, measure the surprise, nudge every knob.
| this page's model | GPT-2 small1 | Llama 3.1 8B2 | |
|---|---|---|---|
| parameters | 106,662 | 124 million | 8 billion |
| layers (blocks) | 2 | 12 | 32 |
| width d | 64 | 768 | 4,096 |
| attention heads | 4, of 16 numbers each | 12, of 64 each | 32, of 128 each (sharing 8 key/value heads) |
| MLP hidden size | 256 (GELU) | 3,072 (GELU) | 14,336 (SwiGLU) |
| positions | learned table | learned table | RoPE (rotations, no table) |
| context | 26 tokens | 1,024 tokens | 128K tokens (8K during most of pre-training) |
| vocabulary | 38: the end, 8 emoji, 29 characters | 50,257 byte-level BPE tokens | 128,000 BPE tokens |
| training data | 8,998 names, about 168,000 tokens | WebText: 8 million documents, 40 GB of text | about 15 trillion tokens |
| training compute | your GPUa laptop GPU (M1): about a minute at π’, less at β‘ | not published | 1.46 million H100 GPU hours |
From left to right the parameter count grows about 1,200 times, then about 65 times more. The shape stays. Llama's changes are refinements, not a new idea: positions are mixed in by rotating the queries and keys (RoPE) instead of adding a learned row, the MLP uses a gated activation (SwiGLU) instead of GELU, and groups of 4 query heads share one key/value head, which saves memory when generating long texts.
The biggest visible difference is the tokens. Ours are single characters, so πΈ slender bush frog is 19 tokens: the πΈ, 17 characters and the end. GPT-2 uses BPE (byte-pair encoding): start from raw bytes and repeatedly merge the most common neighbouring pair into a new token, 50,000 times. Common words end up as one token, with their leading space attached. GPT-2's tokenizer reads slender bush frog as 4 tokens: sl ender β£bush β£frog. A rarer word gets cut into pieces (varian keelback is v arian β£ke el back), and the πΈ isn't in its vocabulary at all: its 4 UTF-8 bytes come out as 3 tokens that mean nothing on their own. The trade: fewer tokens per sentence, so the same context holds far more text, but a much bigger table. GPT-2's wte.weight alone is 50,257 Γ 768, 38.6 million numbers, almost a third of the whole model. For names made of 29 characters, letters are the honest choice; for the whole internet, BPE wins.
.safetensors file, a format the Hugging Face hub uses for model weights. It's the pretrained model until you train your own in the nursery; then it's yours, with your run's seed, steps and validation loss (its loss on the 999 held-out names at the last checkpoint) written inside.Press Download the model to save the pretrained model as a .safetensors file, a format the Hugging Face hub uses for model weights. Its seed, steps and validation loss are written inside. Training your own needs WebGPU. Nothing is uploaded: the file is made in your browser.β¦ Numbers
Inside it: 8 bytes that give the header's length, a JSON header that names every tensor with its shape and where its bytes are, and then 106,662 float32 numbers, one after another. That's all a model file is. GPT-2's file on the Hugging Face hub has the same layout and mostly the same names; Llama's uses the same format with names of its own. The next article opens one up: what's inside a model file, byte by byte, with yourthis frog-namer next to the real GPT-2.
- GPT-2 small: Radford et al., Language Models are Unsupervised Multitask Learners (2019) for layers, width, context, the 50,257-token vocabulary, pre-layer-norm and WebText; heads (
n_head12), GELU (gelu_new) and the MLP size (left unset, so 4 Γ 768) from the released config.json. The BPE examples come from running its releasedvocab.jsonandmerges.txt. The paper's table says 117M parameters; counting the released weights gives 124,439,808. - Llama 3.1 8B: Llama Team, AI @ Meta, The Llama 3 Herd of Models (2024), Table 3, for layers, width, MLP size, heads, key/value heads, SwiGLU, RoPE and the 128K vocabulary, and the 8K pre-training context; the Llama 3.1 model card for 8B parameters, the 128K context, 15T+ training tokens and 1.46M H100 GPU hours.
Cheat sheet
| idea | formula | meaning |
|---|---|---|
| token embedding | \(x_i = \text{wte}[t_i] + \text{wpe}[i]\) | each token becomes its row of 64 numbers, plus the row for its position |
| attention | \(a_{ij} = \operatorname{softmax}_{j \le i}\!\left(\dfrac{q_i \cdot k_j}{\sqrt{16}}\right)\) \(y_i = \sum_{j \le i} a_{ij}\, v_j\) | each token scores every token up to itself, then takes a weighted blend of their values |
| block (pre-LN) | \(x \leftarrow x + \text{Attn}(\text{LN}_1(x))\) \(x \leftarrow x + \text{MLP}(\text{LN}_2(x))\) | normalise, work something out, add it back into the residual stream; twice per block, two blocks |
| softmax | \(p_k = \dfrac{e^{\,z_k/\tau}}{\sum_{k'} e^{\,z_{k'}/\tau}}\) | turns 38 scores into probabilities that sum to 1; \(\tau = 1\) for the loss, the temperature slider when sampling |
| cross-entropy | \(L = \dfrac{1}{n}\sum_{i=1}^{n} -\log p(x_{i+1} \mid x_1, \dots, x_i)\) | the average surprise at the real next token; training pushes it down |
| AdamW | \(m \leftarrow \beta_1 m + (1-\beta_1)\,g\) \(v \leftarrow \beta_2 v + (1-\beta_2)\,g^2\) \(w \leftarrow w\,(1 - \eta_t\lambda) - \eta_t\,\dfrac{m / (1-\beta_1^{\,t})}{\sqrt{v / (1-\beta_2^{\,t})} + \epsilon}\) | a step downhill sized by each weight's own gradient history, plus a tiny pull toward 0 on every weight (\(\beta_1 = 0.9,\ \beta_2 = 0.999,\ \epsilon = 10^{-8},\ \lambda = 0.01\)) |
Conclusion
A GPT is not a mind that has read the internet. It's a next-token guesser. Tokens become little arrows of numbers. Attention lets each one gather what it needs from the tokens before it, a few blocks of weighted sums turn that into a score for every possible next token, and softmax turns the scores into probabilities. Training lowers the average surprise at the real next token, one small step at a time, on a graphics card. Generating is picking a token, sticking it on the end and asking again. And a prompt is just the first tokens: here a πΈ, in a chatbot your whole conversation.
Keep the model you trained: download it.Keep the model: download it (the pretrained one: training your own needs WebGPU). The next article (coming soon) opens a file just like it and shows what's inside a model, number by number.
If you want to go further: Andrej Karpathy's makemore trains character-level models on a list of names, much like this page, and his nanoGPT is a GPT in about 300 lines of PyTorch that can load the real GPT-2 weights. Then read the 2017 paper that introduced this architecture, Attention Is All You Need. It describes an encoder and a decoder; a GPT is the decoder half, without the part that reads the encoder. Happy trainingHappy reading, and may all your frogs be new! πΈβ¨
Data. Names from Wikidata (CC0), snapshot 2026-12-02, fetched with this SPARQL script.