Building Large Language Models from Scratch
A Practical Guide to Training Your Own Transformer-Based AI in Python
Introduction: Why Build from Scratch?
- The Black Box Problem
- What You Will Build
- Prerequisites and How to Use This Book
- A Note on Hardware Requirements
Chapter 1: Tokens, Vocabularies, and Tokenization
- From Text to Numbers: The Tokenization Pipeline
- Character-Level vs Word-Level vs Subword Tokenization
- Building a Byte-Pair Encoding (BPE) Tokenizer
- Vocabulary Size, Special Tokens, and Edge Cases
- Exercise: Tokenize the Shakespeare Corpus
Chapter 2: Embeddings: Turning Tokens into Vectors
- The Embedding Layer as a Lookup Table
- Learning vs Pre-trained Embeddings
- Vector Space Geometry and Similarity
- Implementing Embedding Layers in PyTorch
- Exercise: Visualize an Embedding Space
Chapter 3: The Attention Mechanism
- What Is Attention and Why It Matters
- Scaled Dot-Product Attention from First Principles
- Multi-Head Attention: Parallelizing Understanding
- Causal Masking for Decoder-Only Models
- Exercise: Trace Attention Through a Sentence
Chapter 4: Positional Encoding and Sequence Structure
- The Permutation Invariance Problem
- Sinusoidal Absolute Positional Encodings
- Learned Position Embeddings
- Rotary Positional Embeddings (RoPE)
- Exercise: Implement Three Position Encoding Schemes
Chapter 5: Building the Decoder-Only Transformer Architecture
- The Decoder-Only Design Decision
- Feed-Forward Networks and MLP Blocks
- Residual Connections and Layer Normalization
- Assembling the Full Transformer Block
- The Complete Decoder-Only Model
- Exercise: Build a 3-Layer Decoder from Scratch
Chapter 6: Data Preparation for Language Model Training
- The Data Landscape: Where Does Training Data Come From?
- Cleaning and Filtering Pipeline Design
- Deduplication Strategies
- Dataset Mixing and Domain Balancing
- Synthetic Data Generation Strategies
- Exercise: Build a Mini C4 Dataset
Chapter 7: The Training Loop: Loss, Optimizers, and Gradient Flow
- Cross-Entropy Loss and Next-Token Prediction
- The AdamW Optimizer and Why It Works
- Learning Rate Schedules: Warmup, Cosine Decay, and Beyond
- Gradient Clipping and Training Stability
- The Complete Training Loop
- Exercise: Train on a Tiny Dataset and Monitor Loss Curves
Chapter 8: Memory-Efficient Training Patterns
- The Memory Wall: Why Models Don’t Fit in GPU RAM
- Mixed-Precision Training with BF16/FP16
- Gradient Accumulation for Effective Batch Sizes
- Activation Checkpointing and Recomputation
- Exercise: Train a 10x Larger Model on the Same Hardware
Chapter 9: Distributed Training and Parallelism Strategies
- Data Parallelism and Distributed Data Parallel (DDP)
- Tensor Parallelism for Massive Models
- Pipeline Parallelism: Splitting the Forward Pass
- Fully Sharded Data Parallel (FSDP)
- Exercise: Multi-GPU Training Setup
Chapter 10: Checkpointing, Experiment Tracking, and Reproducibility
- Checkpointing Strategies and Recovery
- Experiment Tracking: Metrics, Configs, and Artifacts
- Reproducibility: Seeds, Determinism, and Hardware Variability
- Logging Design for Long Training Runs
- Exercise: Set Up a Production-Style Training Dashboard
Chapter 11: Fine-Tuning: LoRA, QLoRA, and Instruction Tuning
- The Fine-Tuning Landscape: Full vs Parameter-Efficient
- Low-Rank Adaptation (LoRA) from First Principles
- Quantized LoRA (QLoRA) for Memory-Constrained Fine-Tuning
- Instruction Tuning Dataset Design
- Exercise: Fine-Tune a Model on a Custom Task
Chapter 12: Alignment: RLHF and Beyond
- Why Raw Models Need Alignment
- The RLHF Pipeline: Reward Models and PPO
- Direct Preference Optimization (DPO) as a Simpler Alternative
- Constitutional AI and Rule-Based Alignment
- Exercise: Build a Simple Preference Dataset
Chapter 13: Evaluation: Metrics, Benchmarks, and Red Teaming
- Perplexity as a Training Metric vs Real-World Performance
- Standard Benchmark Suites (MMLU, GSM8K, HumanEval)
- Qualitative Evaluation and LLM-as-Judge
- Safety Testing and Red Teaming Methodologies
- Exercise: Build an Evaluation Harness
Chapter 14: Deployment: Inference, Quantization, and Serving
- Inference Optimization: KV Cache and Speculative Decoding
- Quantization Strategies: FP16 -> INT8 -> INT4
- Building a Serving API with FastAPI
- Containerization and Production Deployment Patterns
- Exercise: Deploy Your Model Behind a Live API
Capstone Project: From Raw Data to Live Inference
- Project Setup and Architecture Overview
- Data Preparation: Curating a 100M-Token Dataset
- Training Run: Configuration, Execution, and Monitoring
- Evaluation: Benchmarking Against Baselines
- Deployment: Containerized API with Health Checks
- Post-Mortem: What Went Well and What Would Be Different
Conclusion: The Road Ahead
- What You Have Accomplished
- Where to Go From Here: Scaling Up
- The Future of Language Models
- A Final Word on Building vs Using
