Build a GPT from Scratch

Read Build a GPT from Scratch free online
Build a GPT from Scratch takes one small language model from text input to generated output. We work through each tensor operation, connect it to the underlying math, and implement the model in readable PyTorch.
The book is inspired by Andrej Karpathy's educational work, especially nanoGPT and microGPT. The aim is not to copy those projects line by line. The aim is to explain the tensor shapes and mathematical decisions underneath them so that the implementation becomes readable.
Author and edition details
About the author and this edition

Michael Brenndoerfer
Michael has spent more than a decade working across software engineering, data, AI, and business. He writes to understand difficult ideas more deeply and to share what he learns in a clear, practical way.
- Edition
- First edition
- Published
- Last reviewed
Key Topics
Track Your Progress
Sign in to mark chapters as complete, track quiz scores, and see your reading journey
Understanding the System
Math and Learning Foundations
From Raw Text to Training Data
Language Models Before Transformers
Build GPT One Component at a Time
Train a Base Model Reliably
Scaling Training
Turn the Base Model into an Assistant
Inference, Evaluation, and Deployment
From GPT-2 to Modern LLMs
Final Capstone
Table of Contents
Part I: Understanding the System
4 chapters
Part I: Understanding the System
What Is a Language Model?
SoonStart with a small next-token probability table. A rule-based generator exposes every choice and makes the difference between training and inference concrete.
The Complete LLM Pipeline
SoonFollow one sentence through tokenization, batching, model output, sampling, and decoding. Each stage gets an interface that later chapters will replace with working code.
Setting Up the Project
SoonSet up the Python environment, tests, configuration, run directories, and random seeds. The same project works on CPU and moves to a GPU when one is available.
Capstone: Trace One Sentence Through an LLM
SoonAssemble the mock pipeline and account for every value and shape. Save the trace so later implementations can be checked against it.
Part II: Math and Learning Foundations
9 chapters
Part II: Math and Learning Foundations
Scalars, Functions, and Computation
SoonAttach mathematical notation to executable scalar functions. Work through a small neuron and inspect the floating-point behavior of each operation.
Vectors, Dot Products, and Representations
SoonCalculate vector operations by hand, then reproduce them in Python. Dot products, norms, and projections lead directly to token representations and attention scores.
Matrices, Tensor Shapes, and Broadcasting
SoonWork from row-by-column multiplication to batched tensors. Track the shapes used by GPT and learn where reshaping or broadcasting can silently change their meaning.
Probability for Language Modeling
SoonBuild conditional probabilities from a tiny corpus and calculate the probability of a complete sentence. Sampling experiments connect the equations to generated text.
Softmax, Cross-Entropy, and Perplexity
SoonTurn a short vector of logits into probabilities and a loss. The NumPy implementation is checked against hand calculations and PyTorch.
Derivatives, Gradients, and the Chain Rule
SoonTrace a loss backward through a small computation graph. Manual derivatives, finite differences, and autograd must agree before gradient descent begins.
Automatic Differentiation from Scratch
SoonWrite a scalar reverse-mode autodiff engine. Tests cover branching graphs, reused values, gradient accumulation, and numerical agreement.
Neurons, Layers, and Gradient Descent
SoonBuild an MLP from the custom autodiff values and train it on a plotted two-dimensional dataset. Broken learning rates and missing gradient resets become debugging exercises.
Capstone: Build a Neural-Network Engine
SoonPackage autodiff, layers, optimization, and tests into a small library. Train a nonlinear classifier and submit the gradients, loss curve, and decision surface as evidence.
Part III: From Raw Text to Training Data
5 chapters
Part III: From Raw Text to Training Data
Constructing a Corpus
SoonCreate a public-domain corpus whose documents have recorded sources, licenses, and checksums. Cleaning, deduplication, rejected records, and train-validation splits remain inspectable.
Characters, Bytes, Unicode, and Tokens
SoonInspect English, accented text, Chinese characters, emoji, and code as Unicode and UTF-8 bytes. Then write reversible character and byte tokenizers.
Byte-Pair Encoding from Scratch
SoonCount byte pairs, apply merges, and train a BPE tokenizer on the book corpus. Each learned token can be traced through its merge history.
Training Examples, Splits, and Batches
SoonTurn encoded documents into shifted input-target windows and deterministic batches. Decode sampled rows to catch boundary, mask, and split errors early.
Capstone: Produce a Training-Ready Dataset
SoonRun the data pipeline from source documents to encoded shards. Deliver the tokenizer, manifests, leakage checks, and decoded sample batches needed for training.
Part IV: Language Models Before Transformers
5 chapters
Part IV: Language Models Before Transformers
The Count-Based Bigram Model
SoonCount token transitions, smooth the table, score held-out text, and generate samples. Because the table fits on the page, every probability can be inspected.
The Neural Bigram Model
SoonReplace the count table with learned logits and optimize it with gradients. Direct comparison shows what changed and what remained a bigram model.
Embeddings and Fixed Context
SoonLook up dense token vectors and feed several previous tokens into an MLP. Experiments vary the context length and test whether order matters.
A Reliable Training Loop
SoonMove training out of ad hoc notebook cells. The shared loop handles updates, validation, metrics, checkpoints, and the one-batch overfit test.
Capstone: Compare Three Language Models
SoonTrain the count bigram, neural bigram, and fixed-context model on the same data. Compare loss, runtime, parameter count, context, and fixed-seed samples.
Part V: Build GPT One Component at a Time
11 chapters
Part V: Build GPT One Component at a Time
The Token-Communication Problem
SoonLet each token gather information from earlier positions through causal averaging. Loop, cumulative-sum, and matrix versions must return the same values.
Attention as Learned Retrieval
SoonCalculate queries, keys, values, attention scores, and weighted sums for three small vectors. The same numbers are then produced by one attention head.
Causal Attention and Numerical Stability
SoonAdd the causal mask, scaled dot products, and stable softmax. Intervention tests prove that changing a future token cannot alter an earlier output.
Multi-Head Attention
SoonSplit channels across heads and put them back together without losing their meaning. A readable reference version checks the vectorized implementation.
Position Information
SoonShow what attention does with permuted input when it has no positions. Learned position embeddings make order available and introduce a fixed context limit.
The Feed-Forward Network
SoonBuild the per-token MLP and reconcile its dimensions and parameter count. Activation plots and short runs compare ReLU, GELU, and expansion size.
Residual Connections and Normalization
SoonCalculate LayerNorm for one token vector and check the implementation against PyTorch. Deep-stack experiments measure what residual paths and normalization do to gradients.
The Transformer Block
SoonCombine attention and the MLP in a pre-norm residual block. A shape trace follows one batch through every projection, normalization, and addition.
Assembling GPT
SoonStack the decoder blocks between token embeddings and vocabulary logits. Verify the forward contract, initialization, parameter count, and causal behavior.
Autoregressive Text Generation
SoonWrite the decoding loop and compare greedy, temperature, top-k, and top-p sampling on fixed logits and prompts. Seeded runs make the comparison repeatable.
Capstone: Train Tiny GPT
SoonTrain the complete model on the book corpus. Submit causal tests, shape and parameter ledgers, loss curves, checkpoints, runtime measurements, and fixed-seed samples.
Part VI: Train a Base Model Reliably
8 chapters
Part VI: Train a Base Model Reliably
Designing the Model and Training Budget
SoonCalculate model parameters, memory use, token count, training time, and cost before choosing a run. Measured throughput checks the estimate on available hardware.
Initialization and Trusted Baselines
SoonCheck expected initial loss, activation variance, gradient flow, and one-batch overfitting before a long run. Bad initializations provide useful counterexamples.
AdamW and Learning-Rate Scheduling
SoonWork through the first AdamW updates by hand, including moment estimates and bias correction. Then add parameter groups, warmup, decay, clipping, and accumulation.
Diagnosing Training Failures
SoonInvestigate deliberately broken runs with high and low learning rates, bad masks, shifted targets, corrupt data, and non-finite gradients. Each confirmed bug becomes a regression test.
Evaluating the Base Model
SoonMeasure token loss on fixed held-out data, inspect samples, and test memorization. Small ablations and uncertainty estimates keep the conclusions within the evidence.
Checkpoints and Reproducibility
SoonSave the full state needed to resume training, including the random streams and data position. A split run must match an uninterrupted run step for step.
Efficient GPU Training
SoonEstablish a timing baseline, find the bottleneck, and change one thing at a time. Mixed precision, fused attention, compilation, and data transfer are kept only when measurements support them.
Capstone: Run a Defensible Pretraining Experiment
SoonPlan and run pretraining within a stated budget. The report records the configuration, artifact hashes, performance, loss curves, checkpoint choice, samples, and limitations.
Part VII: Scaling Training
4 chapters
Part VII: Scaling Training
Scaling the Data Pipeline
SoonStore tokens in shards and read datasets larger than memory. Tests cover deterministic shuffling, worker partitioning, prefetching, and resume position.
Distributed Training
SoonCalculate gradient averaging for two replicas before running a small multiprocess job. The optional GPU track measures communication cost and scaling efficiency.
Scaling Laws and Experiment Design
SoonRun a small grid of model and token budgets, fit learning curves, and test the fit on a held-out configuration. Noisy pilots set bounds on what can be extrapolated.
Capstone: Scale the Training Run
SoonUse measured loader speed, training throughput, memory, and pilot loss to choose the largest sensible run. A supported decision to stay small also satisfies the project.
Part VIII: Turn the Base Model into an Assistant
5 chapters
Part VIII: Turn the Base Model into an Assistant
Preparing Instruction Data
SoonCreate conversation records with source and license fields, render the chat template, and inspect the token-level loss mask. Packing and truncation receive explicit tests.
Supervised Fine-Tuning
SoonFine-tune the base checkpoint on assistant responses and compare it with the untouched model. Measure instruction behavior alongside forgetting on base text.
Preference Alignment
SoonCalculate sequence log probabilities for chosen and rejected responses, then implement a small DPO loss. The chapter also locates reward models and policy optimization within RLHF.
Safety and Responsible Development
SoonTest the actual small model for memorization, privacy leakage, harmful output, bias, and prompt injection. Use the results to write the model card and release decision.
Capstone: Build a Tiny Assistant
SoonInstruction-tune the base model and compare both checkpoints on a frozen test set. Deliver the lineage, response table, forgetting results, safety checks, and model card.
Part IX: Inference, Evaluation, and Deployment
6 chapters
Part IX: Inference, Evaluation, and Deployment
Understanding Inference
SoonTime checkpoint loading, tokenization, prefill, and token-by-token decoding separately. Memory and latency are measured as prompts and outputs grow.
The Key-Value Cache
SoonReuse keys and values from earlier positions instead of recomputing them. Cached and uncached logits must agree before speed and memory are compared.
Quantization and Efficient Generation
SoonQuantize a short weight vector by hand, then apply the same ideas to the model. Report storage, runtime memory, speed, and evaluation changes on the target hardware.
Serving the Model
SoonPackage the tokenizer, weights, and configuration behind a small streaming API. Validate requests and test limits, cancellation, concurrency, and startup failures.
Evaluating the Assistant
SoonBuild a versioned test set with exact checks, pairwise review, prompt variations, and controlled factual questions. Quality results sit beside latency and failure rates.
Capstone: Deploy and Evaluate the Assistant
SoonServe the selected checkpoint with a verified KV cache and optional quantization. Compare the final service with the original baseline on the same prompts and hardware.
Part X: From GPT-2 to Modern LLMs
5 chapters
Part X: From GPT-2 to Modern LLMs
Modernizing the Architecture
SoonReplace LayerNorm, learned positions, GELU, and standard multi-head attention one component at a time. RMSNorm, RoPE, SwiGLU, and GQA each get a numerical example and unit tests.
Controlled Architecture Experiments
SoonCompare architecture changes under a stated matching rule, such as equal parameters, tokens, compute, or time. Repeated runs show how much of the result is noise.
Reading and Reproducing Research
SoonTake one paper equation, map its symbols to tensor shapes, and implement the smallest useful test. A reduced experiment records every assumption the paper leaves open.
Where to Go Next
SoonConnect the model already built to continued pretraining, retrieval, tools, sparse models, long context, multimodality, and distillation. Each path starts from a specific limitation.
Capstone: Build a Modern Model Variant
SoonTrain a small Llama-style variant beside the original GPT under a matched budget. Compare correctness, loss, training cost, cache memory, decoding speed, and samples.
Part XI: Final Capstone
1 chapter
Part XI: Final Capstone
Final Capstone: From Raw Documents to a Working LLM
SoonStart with raw documents and produce the tokenizer, base model, assistant checkpoint, evaluation, inference service, and documentation. Every result must trace back to its data and configuration.
In Progress
This comprehensive handbook is currently in development. Each chapter will be published as it's completed, with practical examples, code implementations, and real-world applications.
Reference
Citation details
Cite or share this article.
Stay up to date
Get articles, book updates, and news delivered to your inbox.
No spam, unsubscribe anytime.
Join the community
Sign in to remove popups, track your reading progress, and join the discussion.