Project P06

My own GPT from scratch

What does it take, line by line, to train your own language model comparable to GPT-2 small on an 8 GB GPU and turn it into an assistant?

stages
9
duration
15 h 30 min
concepts
24
available in English
9 / 9
completed by you
0 of 9

Where it fits

Overview

In this central project you build a complete GPT without model libraries. Develop a byte-level BPE tokenizer, a sharded data pipeline over FineWeb-Edu, and a GPT-2 model verified by loading public weights. Build a training loop with sanity checks, optimize throughput on the RTX 4060 using bf16, torch.compile, fused attention, and gradient accumulation, and run a monitored, resumable pretraining of a 124M-parameter model over billions of tokens. Evaluate validation loss and HellaSwag against public GPT-2, modernize the architecture with controlled ablations, and finish with instruction tuning to create a small chat assistant.

Why it matters

This is one of the curriculum's central goals and a foundation for several later projects. The inference engine, mechanistic interpretability, and scaling-law replication all build on this model. Training an LLM end to end with limited resources shows where errors hide, including data, initialization, numerical precision, masks, and evaluation, and builds confidence to read and reproduce architecture and training papers.

Stages 9

  1. 01Byte-level BPE tokenizerBuild a byte-level BPE tokenizer from scratch, including regular-expression pretokenization, incremental pair-count training, efficient encoding, and special tokens. Verify it by loading GPT-2 merges and comparing with tiktoken, then train a custom vocabulary on a sample of the pretraining corpus. GPUAdvanced110 min
  2. 02Pretraining data in shardsPrepare the corpus with a multi-billion-token FineWeb-Edu sample, exact deduplication, parallel tokenization over 24 cores, uint16 shards, and a resumable memory-mapped loader. Measure whether the loader delivers tokens much faster than the GPU consumes them. GPUAdvanced90 min
  3. 03The GPT model and parity with GPT-2Implement the complete model in pure PyTorch: token and position embeddings, pre-norm causal-attention and MLP blocks, tied weights, a language head, and GPT-2 initialization. Test it rigorously by loading public 124M GPT-2 weights and reproducing the reference implementation's logits. GPUAdvanced100 min
  4. 04Training loop, sanity checks and pilot runWrite a training loop with AdamW, gradient clipping, learning-rate warmup and decay, and periodic evaluation. Apply sanity checks for initial loss, single-batch overfitting, and per-layer norms. Before long training, validate the entire system with a TinyStories pilot that produces coherent stories in under an hour. GPUAdvanced100 min
  5. 05Squeezing the RTX 4060: throughput and memoryOptimize training step by step while measuring each change: bf16 autocast, TF32, fused attention, torch.compile, fused AdamW, padded vocabulary, and microbatching with gradient accumulation. Calculate MFU, profile with torch.profiler, and fit a 124M model with context 1024 and an effective batch of hundreds of thousands of tokens into 8 GB. GPUAdvanced110 min
  6. 06The long pretraining runLaunch pretraining of the 124M architecture with a budget of 1 to 3 billion tokens across several nights. This stage covers long-run engineering: atomic checkpoints with exact resumption, monitoring and alerts, periodic samples, and diagnosis of loss spikes and instability. GPUAdvanced100 min
  7. 07Evaluating the base modelEvaluate the pretrained model through validation loss and perplexity, HellaSwag completion likelihood, and qualitative samples under different sampling parameters. Compare everything with public 124M GPT-2 evaluated by the same script, with intervals and an honest discussion of data and compute differences. GPUAdvanced90 min
  8. 08Modernizing the architecture with ablationsTransform GPT-2 into a modern Llama-style block with RoPE, RMSNorm, SwiGLU, no biases, grouped-query attention, and QK-norm. Measure each change using a small-scale ablation protocol with fixed token and parameter budgets, per-variant learning-rate tuning, and multiple seeds. GPUResearch120 min
  9. 09From base model to assistant: instruction tuningTurn the custom base model into a small assistant using a chat template with special tokens, conversation packing with document masks, assistant-only loss, and supervised fine-tuning on an open conversation dataset. Evaluate it on a custom instruction set and publish locally with a model card. GPUAdvanced110 min

Final deliverable

A documented, reproducible GPT of your own

A repository with tokenizer, data, modern model, resumable training, evaluations against GPT-2, and a chat version. It can be reproduced from scratch with one configuration file and includes its model card.

Check what you already know

  • Train a byte-level BPE tokenizer and guarantee an exact round trip for any byte sequence
  • Build memory-mapped token shards and a loader that does not become the bottleneck
  • Implement GPT-2 and reproduce the public model's logits by loading its weights
  • Apply pretraining sanity checks including initial loss, single-batch overfitting, and gradient norms
  • Measure and maximize training MFU on a consumer GPU
  • Evaluate a base model on HellaSwag using completion likelihood

References

  • nanoGPTAndrej Karpathy
  • Language Models are Unsupervised Multitask LearnersAlec Radford, Jeffrey Wu, Rewon Child, David Luan, Dario Amodei, Ilya Sutskever, 2019
  • Scaling Laws for Neural Language ModelsJared Kaplan, Sam McCandlish, Tom Henighan et al., 2020