Build a Large Language Model From Scratch

This book takes you from zero to a working GPT-style language model that you write yourself, one component at a time. You will learn how text becomes tokens and embeddings, how attention and transformer blocks work, and how to pretrain, evaluate and fine-tune a small model on ordinary hardware. Clear diagrams, runnable code, exercises and chapter summaries make each idea concrete before moving on to the next.

Level: beginner · 17 chapters · about 9 h · Free · Created by Sandip Das

What you will learn

Contents

Part 1. Foundations: Language Models, Python and Neural Networks

Explains what a language model is and how it evolved, then gives you the Python, PyTorch and neural network basics needed for the rest of the book.

  1. What Large Language Models Are and How They Evolved (25 min) · free preview
    Explains next-token prediction and traces the path from counting-based n-gram models through RNNs to the Transformer and GPT-style decoder-only models. Gives a map of the pipeline the book builds: text to tokens, embeddings, transformer blocks, output probabilities.
  2. Python, NumPy and PyTorch Essentials (35 min)
    Installs PyTorch and Jupyter on an ordinary laptop and introduces the tensor operations the book relies on: shapes, indexing, matrix multiplication, broadcasting and moving work to a GPU when one is available.
  3. Neural Networks and Gradient Descent (35 min)
    Introduces neurons, layers, activation functions, loss functions and gradient descent, then shows how PyTorch autograd computes gradients so that a small classifier can be trained end to end with an optimizer such as AdamW.

Part 2. From Text to Tensors

Turns raw text into training-ready batches of token ids and embedding vectors.

  1. Tokenization and Byte-Pair Encoding (35 min)
    Shows why word-level vocabularies fail on rare words, builds a simple tokenizer, then implements byte-level BPE training, encoding and decoding step by step, and compares it with OpenAI's tiktoken GPT-2 encoding.
  2. Token Embeddings, Positional Embeddings and Data Loading (30 min)
    Builds a sliding-window dataset of input and target token sequences with context length and stride, wraps it in a DataLoader, and converts token ids into vectors with nn.Embedding plus learned positional embeddings. Briefly introduces rotary position embeddings used by newer models.

Part 3. Attention and the Transformer Block

Builds the attention mechanism from first principles and combines it into a complete transformer block.

  1. Self-Attention From First Principles (35 min)
    Motivates attention as a way for each token to gather information from the others, starting from a simplified version without weights and then adding trainable query, key and value projections and the square-root scaling.
  2. Causal Masking and Multi-Head Attention (35 min)
    Adds a causal mask so tokens cannot see the future, applies dropout to attention weights, and builds an efficient multi-head attention class; checks it against PyTorch's scaled_dot_product_attention and introduces grouped-query attention as a modern variant.
  3. Building the Transformer Block (35 min)
    Combines multi-head attention with layer normalization, a GELU feed-forward network and residual connections into the pre-norm block used by GPT-2, and explains why pre-norm trains more stably than post-norm.

Part 4. Assembling GPT and Generating Text

Stacks transformer blocks into a complete GPT-style model and uses it to generate text with several decoding strategies.

  1. Assembling a GPT-Style Model (35 min)
    Puts embeddings, a stack of transformer blocks, a final layer norm and an output head together into a GPT model, counts its parameters and memory, and traces a batch from token ids to logits.
  2. Text Generation and Decoding Strategies (30 min)
    Turns logits into text with an autoregressive generation loop and compares greedy decoding, temperature scaling, top-k and top-p (nucleus) sampling, with a short look at KV caching for faster generation.

Part 5. Pretraining and Evaluation

Trains the model on unlabeled text, measures progress and handles the practical problems that arise on ordinary hardware.

  1. Pretraining on Unlabeled Text (40 min)
    Writes the training loop: computing next-token cross-entropy loss over flattened logits, training and validation splits, AdamW updates, periodic sample generation, and learning-rate warmup, cosine decay and gradient clipping, using a small dataset such as TinyStories.
  2. Evaluating Language Models: Loss, Perplexity and Qualitative Checks (25 min)
    Explains what loss and perplexity measure, how to compute perplexity from cross-entropy, why it cannot be compared across tokenizers, and how to complement numbers with qualitative checks of generated text.
  3. Practical Training: Hardware, Memory and Troubleshooting (40 min)
    Estimates training memory for parameters, gradients, optimizer states and activations, uses mixed precision and checkpoints to train and resume safely, and works through a troubleshooting guide for unstable loss, overfitting and out-of-memory errors.

Part 6. Fine-Tuning and Next Steps

Adapts a pretrained model to classification and instruction following, makes fine-tuning cheaper with LoRA, and looks ahead to alignment and safety.

  1. Loading Pretrained Weights and Fine-Tuning for Classification (40 min)
    Loads OpenAI's GPT-2 weights into the model built in this book, then replaces the output head and fine-tunes it as a spam classifier, measuring accuracy on a held-out set.
  2. Instruction Fine-Tuning (35 min)
    Prepares an instruction dataset with Alpaca-style prompt templates, batches and masks it, fine-tunes the pretrained model to follow instructions, and evaluates its responses.
  3. Parameter-Efficient Fine-Tuning with LoRA (30 min)
    Explains why full fine-tuning is costly, implements a LoRA layer with low-rank matrices A and B from scratch, attaches it to the model's linear layers and compares cost and results with full fine-tuning.
  4. Alignment, Safety and Next Steps (25 min)
    Gives a brief overview of RLHF and DPO, the limits of LLMs such as hallucination, and how modern open models extend what you built, with pointers for further learning.

Read the ebook on LearnXops · LearnXops members can download it as PDF and EPUB.