Skip to content
Adrian Mircea Nenu computo, ergo sum
← Blog
ai machine learning

Understanding Language Models by Building a GPT from Scratch

In mvGPT, short for Minimum Viable GPT, I build a language model from scratch in PyTorch to understand it from one end to the other, and then take it through the whole pipeline around it, from pretraining and fine-tuning to reinforcement learning, evaluation and deployment.

Why build one

Most of us use language models every day now, and a lot of engineers build products on top of them, but far fewer of us know what actually goes on inside one, and with my own research being in reinforcement learning and reasoning, I wanted to understand the whole of it, from the blocks of parameters inside a model to the way it's trained. My interest in complex software engineering at scale, after years in industry at Morgan Stanley and Google building large distributed systems, means I'm just as curious about the engineering around a model, from profiling it and training it across several GPUs to serving it to many users at once, where the practices that keep large systems running matter as much for language models as for anything else, so the series makes room for those too.

mvGPT is a series that shows how those blocks work together, in code you can read line by line, without the engineering tricks a model needs at scale getting in the way, and with the maths coming in only where the code needs it, right next to the lines that use it.

It's for engineers and researchers who want to know what goes on inside a language model rather than only call one, and some Python and PyTorch help, although every change is typed out on screen, with the reasons behind it.

Where it starts

The model starts out with 14.6 million parameters, small enough to train in about ten minutes on a laptop, and it begins by writing short children's stories from TinyStories. The series opens with Attention Is All You Need and what we change from it, writes our decoder-only architecture in PyTorch, class by class, and then pretrains it from random tokens to short stories, with a tokenizer, the next-token objective, a training loop and an evaluation all written from scratch.

From there, we fine-tune it to write the story an instruction asks for, add a KV cache so each new token runs on its own rather than the whole story again, and deploy it, saving it as a GPT-2 on the Hugging Face Hub, serving it from a Gradio app on a VPS and running it right in the browser with Transformers.js, which you can still try on the series' website.

The training pipeline

With a model that follows instructions, we go through the ways models learn from preferences and rewards, starting with DPO, where our model learns from pairs of its own stories in which the one that uses more of the words it was asked for is preferred, and PPO, where it learns from its own stories as they're scored, with a critic and a penalty for drifting too far from where it started. Later on, GRPO replaces PPO's critic by having the model write eight stories per instruction and scoring each against the others, which is the reinforcement learning behind DeepSeek-R1, and a later episode trains the same thing with Hugging Face's TRL to see how it compares with the version we wrote by hand. LoRA fine-tunes the model again while training only about 2% of its weights, in a small low-rank update next to the frozen ones, and we measure what that saves and what it learns against full fine-tuning.

Scaling up, a little

Most episodes stay on a laptop on purpose, but a few rent GPUs by the hour, starting with one that pretrains a model about six times bigger, in GPT-2 small's shape, on four RTX 4090s with PyTorch's DistributedDataParallel, to see how the speed scales from one GPU to four. A later episode pretrains a model of that shape on educational web pages overnight, on a single RTX 4090 rented for under four dollars, and on HellaSwag it ends up within ten questions of GPT-2 small, out of just over ten thousand, which isn't bad at all for what it cost.

Newer ideas from the research

A lot of the series follows ideas from recent papers, each built from scratch and measured, so the model gets rotary position embeddings, and later YaRN to stretch them to four times its context window, a byte-level BPE tokenizer written in C++, flash attention written in PyTorch and then as a Triton kernel, and a modern transformer block with RMSNorm, SwiGLU and QK-norm, followed by grouped-query attention for a smaller KV cache and a mixture of experts with a router in place of each block's MLP. We race AdamW against Lion, Sophia and Muon, each with its own sweep of the learning rate, turn our GPT into a masked diffusion model that writes a story all at once by unhiding it, and replace attention altogether with Hyena's long convolutions, measuring each of them against what we had before.

On the inference side, we write speculative decoding, where a draft guesses the next few tokens and the model checks them in a single pass, constrained decoding, which keeps a model's output within a list of names without any training, and batching, to serve the model as an API to many users at once, with vLLM as the alternative. More recently, we've looked inside the model too, writing out what each attention head looks at while it copies a name into a query, and training a sparse autoencoder on its residual stream to find features we can read and steer its writing with, and we've ported it to Apple's MLX and written its GPU kernels in Mojo, racing them against PyTorch on a Mac.

Tools, agents and a graph database

Once the web model was trained, we fine-tuned it to call a calculator in plain text, and then into an agent that writes files and hands work to subagents, each a fresh context of the same model, so we could measure what the subagents buy. That agent then learned to write Cypher to ask smollerGraph, the graph database I'm building in another of my series, for facts, so it can take two facts from the graph and combine them with the calculator, which is where the two series start to meet. mvGPT meets nanoMMO too, as the game has a storyteller NPC that writes you a story from a few words with our model, and the episode on batching measures the server against a crowd of players from the game.

Following along

The code is on GitHub, under the MIT licence, with its docs and the trained models on Hugging Face, and every step of every episode is a tag in the repository, so you can check out the code at any point in a video and run it yourself, or open each episode's notebook in Google Colab and run it on a Colab GPU. New episodes go up on the YouTube playlist, and the series' website has a page for each one, with its code at each step.

Latest videos

YouTube ↗