How it works · small GPT you can train yourself

How nanoGPT works

Text becomes numbers, a model learns to guess the next number, and guessing again and again writes new text.

Think of it like this. Autocomplete, trained from nothing: show it a lot of writing and it learns what tends to come next.

  1. Prepare Turns a text file into a long list of numbers (tokens) and saves it. data/shakespeare_char/prepare.py
  2. The model The whole GPT in about 300 lines: attention, the layers, and the function that writes text. model.py
  3. Training Shows the model random pieces of the text, measures how wrong its guesses are, and nudges it. train.py
  4. Sampling Loads a trained model and lets it write. sample.py
  5. Configs Small files that set the size of the model and how long to train. config

Follow one thing through: Training on Shakespeare, then asking it to write

  1. prepare.py gives every character a number and writes the text out as numbers.data/shakespeare_char/prepare.py
  2. train.py picks random stretches of those numbers. The target for each is the same stretch moved along by one.train.py
  3. The model guesses the next number at every position, and the loss says how wrong it was.model.py
  4. The error flows backwards, and every weight moves a little in the direction that would have been less wrong.train.py
  5. After many rounds, a checkpoint is saved.
  6. sample.py feeds in a start, takes the model’s guess for the next character, adds it on, and repeats.sample.py

The clever bit: It is never allowed to look ahead

In training the model sees a whole stretch of text at once and learns a guess for every position in a single pass. That would be cheating, since the answer to “what comes next” is sitting right there. The causal mask stops it: each position can only attend to the ones before it. One mask turns one stretch of text into hundreds of honest practice questions.

model.py

Words you’ll meet

token
A piece of text as a number. Here, one character; in bigger models, a chunk of a word.
attention
How each position looks back at earlier ones and decides which matter for its guess.
loss
One number for how wrong the guesses were. Training is making it go down.
temperature
How adventurous the writing is. Low picks the likeliest next token; high takes more chances.

Good questions to ask next

Open nanoGPT in Bento and ask them there. It reads the project in your browser, draws its parts as a map you can press, and opens the real code behind each one.

Take nanoGPT apart yourself.

Free and open source. Nothing to install, no account.

More projects, taken apart

Written by hand from the code as it was on 2025-11-12 (commit 3adf61e). nanoGPT belongs to its authors; this page is an independent explanation. Spot a mistake? Tell us.