Transformers through nanoGPT
Read through a small GPT in six chapters, from the raw training text to the first line it generates.
A language model learns to predict the next token. In nanoGPT’s smallest Shakespeare experiment, a token is just one character. That gives us a simple thread to follow through the Python: where the characters become numbers, how the model learns from them, and how its predictions become text again.
What you’ll learn
- How a Shakespeare file becomes a trainable stream of character ids.
- What a GPT module is doing when it scores the next character.
- What happens in a single training step (loss in, updated weights out).
- How sampling turns scores into readable text.
- How the README's small Shakespeare run is wired up.
- Where "config" files actually plug into the training script.
Chapters
- Text to numbers (data/shakespeare_char/prepare.py)
Download Tiny Shakespeare and save it the way the trainer expects — one character, one id.
- The GPT (model.py)
The network itself: embeddings, attention blocks, and a guess for the next token.
- One training step (train.py)
Pull a batch of ids, measure how wrong the guesses are, and update the weights once.
- Text out the other side (sample.py)
Load a checkpoint and print new Shakespeare-ish lines.
- The small run (config/train_shakespeare_char.py)
The cozy settings: a 6-layer model, 256 characters of context, character vocabulary.
- How a config lands (configurator.py)
The tiny script that copies those settings into train.py when you run the README command.
Based on Andrej Karpathy’s nanoGPT, licensed under the MIT license.