Skip to content

mvGPT

Minimum Viable GPT is a small decoder-only transformer, written from scratch in PyTorch, that you can read from one end to the other. It has about 14.6 million parameters, and it's trained on TinyStories, a dataset of short children's stories, so it learns to write believable English in minutes on a laptop.

It's the code of the YouTube series Minimum Viable GPT, which builds it one tagged step at a time and then takes it through the training pipeline of a language model. Each episode adds a page here.

The model at a glance

Property Value
Parameters 14,585,856
Vocabulary 10,000 tokens
Context window 256 tokens
Transformer blocks 6
Attention heads 6 per block, 64 dimensions each
Embedding size 384
MLP hidden size 1,536 (4 x 384)
Activation GELU
Normalisation LayerNorm before each sublayer (pre-norm)
Positions Learned embeddings
Output head Tied to the token embeddings

All of these come from one dataclass, GPTConfig, in model.py. A trained model only loads into a GPT built with the config it was trained with, since the config fixes every tensor's shape.

Run it

git clone https://github.com/nenuadrian/mvGPT
cd mvGPT
python -m venv .venv && source .venv/bin/activate
pip install -r requirements.txt

python summary.py
python data.py
python pretrain.py 10
python sample.py checkpoints/pretrain/model.pt "Once upon a time"
python sft.py 10
python sample.py checkpoints/sft/model.pt "Words: dog, ball, happy. Story:"
tensorboard --logdir runs

summary.py builds the model and prints it the way PyTorch sees it: the modules, the parameters by layer, the shape of the data after each layer, and a few tokens generated before any training. data.py downloads TinyStories and tokenizes it, pretrain.py trains the model for ten minutes, and sample.py writes stories with it. sft.py then fine-tunes it to write the story an instruction asks for. Both training runs log to TensorBoard, under runs/.

Pages

  • Architecture: the transformer, layer by layer, with the data flow and where the parameters are.
  • Pretraining: the tokenizer, the data, next-token prediction and the training loop, sampling, and how we measure a model.
  • Supervised fine-tuning: instructions and stories, a loss on the story alone, and how well the model follows instructions before and after.
  • Watching training: the runs in TensorBoard, and reading their logs in Python to plot them with matplotlib.
  • The KV cache: keeping the keys and values of earlier tokens, so each new token runs through the model on its own, and how much faster it writes on a CPU and a GPU.
  • Sharing and serving: the model on the Hugging Face Hub as a GPT-2, a version per episode, a Gradio app in Docker on a server, and the model in the browser with Transformers.js.
  • Profiling: the model as a graph in Model Explorer, PyTorch's profiler on the CPU and the GPU, and decisions in the code, measured.
  • Preferences, with DPO: pairs of the model's stories, scored by the words they use, and direct preference optimisation, with what it gains and what it costs.
  • Reinforcement learning, with PPO: the model writes, a reward scores it, and PPO's clipped objective, with a critic and a KL penalty, improves it, next to DPO.
  • LoRA: fine-tuning a low-rank update beside frozen weights, with what it saves and what it learns, next to full fine-tuning.
  • Rotary position embeddings: positions as rotations of the queries and keys, a cache that slides past the window, and RoPE next to learned positions.
  • Flash attention: attention without its table of scores, in PyTorch on the Mac, then as a Triton kernel on an NVIDIA GPU, forwards and backwards, next to PyTorch's own.
  • Serving many at once: the model as an OpenAI-style completions API, the requests waiting written together as a batch, measured under a crowd of players, in Docker, and vLLM.
  • Text diffusion: the same transformer, attending both ways, trained to fill in hidden tokens and writing a story by unhiding it, next to next-token prediction and LLaDA.
  • Reinforcement learning, with GRPO: eight stories per instruction, each scored against its group in place of PPO's critic, as DeepSeekMath and DeepSeek-R1 train, next to PPO.
  • A modern transformer block: RMSNorm, SwiGLU, QK-norm and no biases, as options, from the papers that introduced them, with the parameters counted and tests against PyTorch's.
  • Grouped-query attention: query heads that share their keys and values in groups, for a smaller KV cache and smaller key and value projections, checked against multi-head attention.
  • Pretraining on the web: FineWeb-Edu with merges of its own, a night on one rented GPU with gradient accumulation and resuming, and the model on HellaSwag next to GPT-2 small.
  • Tool use, a calculator: calls as plain text, a calculator that takes arithmetic alone, generated questions, fine-tuning with the results masked out, and the calls measured, the calculator on and off.
  • An agent, with subagents: one model in three roles, files in a sandbox, subagents in fresh contexts, and the agent against one context on a long task, then in a chat.
  • A longer context: the web model's rotary embeddings stretched to four times its window, four ways, measured by position and with a pass key, then fifteen minutes of fine-tuning.
  • Optimizers: AdamW from scratch, then a fair race against Lion, Sophia and Muon on the stories model, each with its own sweep of the learning rate, with seeds, AdamW's steps, time and memory.
  • A graph database, smollerGraph: the mammals and birds on Wikidata, in the database built in smollerGraph's series, asked in Cypher, questions answered by the graph, and the queries measured, the graph on and off.
  • The agent asks the graph: the graph as a fourth role of the agent, which hands back its sentence, tasks that combine facts from the graph with the calculator, and what the new role cost the old ones.
  • Constrained decoding: the graph role's names kept to a list by a mask on the logits, with two tries walked a byte at a time, the graph's names against the task's words, and both measured.
  • Speculative decoding: what a pass costs by its tokens, a draft's guesses checked in the pass that writes each token, prompt lookup and a small draft model, and the agent's tasks timed with each.
  • Inside the model: attention written out to keep its weights, the logit lens, a page to look at the 144 heads with, the heads that look at the name a query copies, and heads turned off to test them.
  • A GPT without attention: Hyena's long convolutions with the FFT, between two gates, its matrices and filters, a hybrid, and our own attention models against it on speed, loss, long context and recall.
  • GRPO, with Hugging Face's TRL: our model saved as a GPT-2 for TRL's GRPO trainer, our settings in its config, a folder for its reference, and TRL's defaults, measured next to our own GRPO.
  • A mixture of experts: eight experts and a router in place of each block's MLP, as a loop and as one batched multiply, balanced by Switch Transformer's loss, by DeepSeek-V3's bias or not at all, against the dense model, and the words each expert gets.
  • Our GPT in MLX: the model in Apple's array library with PyTorch's weights, the same logits and story, a race at writing and training on a Mac, and a run trained in MLX and brought back to PyTorch.
  • Features, with a sparse autoencoder: the attention sink in the stream, a TopK autoencoder trained on the web model's stream after block 6, what it costs the model, features for cities, carbon and the moon, and steering.
  • The tokenizer, measured and fixed: the C++ BPE tokenizer measured on web pages, its memory, its time, its threads and its long chunks, then an LRU cache, bytes to NumPy, the GIL let go, a data race that ThreadSanitizer finds, a cache per call, and a heap for long chunks.
  • Our GPT's kernels in Mojo: the path a token takes as Mojo GPU kernels called from Python, PyTorch's logits and story, three versions raced against PyTorch and MLX on a Mac, and what a kernel launch costs.