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

Chapters

  1. Text to numbers (data/shakespeare_char/prepare.py)

    Download Tiny Shakespeare and save it the way the trainer expects — one character, one id.

  2. The GPT (model.py)

    The network itself: embeddings, attention blocks, and a guess for the next token.

  3. One training step (train.py)

    Pull a batch of ids, measure how wrong the guesses are, and update the weights once.

  4. Text out the other side (sample.py)

    Load a checkpoint and print new Shakespeare-ish lines.

  5. The small run (config/train_shakespeare_char.py)

    The cozy settings: a 6-layer model, 256 characters of context, character vocabulary.

  6. 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.