CHAPTER COLLECTION

Build LLM From Scratch

From tokenization to pretraining: verified visual architecture screens.

Mathematics visual
Lesson 01LESSON · 12 picturesPreface

How did machine conversation begin, and how does ELIZA differ from a modern language model?

Open lesson →
Mathematics visual
Lesson 02LESSON · 12 picturesSetting Python Environment

What core mathematical principle governs read the project before you run it?

Open lesson →
Mathematics visual
Lesson 03LESSON · 16 picturesIntro to LLM

What core mathematical principle governs from task specific nlp to general purpose llms?

Open lesson →
Mathematics visual
Lesson 04LESSON · 1 picturesTokenization & Vector Embedding Space

How do discrete token identifiers translate into continuous vector embeddings along high-dimensional semantic axes?

Open lesson →
Mathematics visual
Lesson 05LESSON · 7 picturesPretraining vs Finetuning

Why is the lifecycle of an LLM fundamentally separated into self-supervised pretraining and supervised fine-tuning?

Open lesson →
Mathematics visual
Lesson 06LESSON · 4 picturesAttention Mechanisms & Multi-Head Subspace Routing

How do query-key projections, softmax budgeting, and multi-head subspace synthesis route contextual information across tokens?

Open lesson →
Mathematics visual
Lesson 07LESSON · 5 picturesBasics Of Transformers

What core breakthrough did Attention Is All You Need introduce?

Open lesson →
Mathematics visual
Lesson 08LESSON · 3 picturesHow ChatGPT Works

How does minimizing cross-entropy on next-token prediction induce high-level reasoning, code synthesis, and world models?

Open lesson →
Mathematics visual
Lesson 09LESSON · 3 picturesPretraining Pipeline & Sampling Dynamics

How do numerical stability shields, temperature scaling, and multinomial sampling steer the autoregressive pretraining engine?

Open lesson →
Mathematics visual
Lesson 10LESSON · 3 picturesFour Stages Of Building LLM

What is the complete roadmap from a raw text file to a conversational AI assistant?

Open lesson →
Mathematics visual
Lesson 11LESSON · 15 picturesTokenization

How does the tokenization pipeline transform raw Unicode text into integer tensors for neural network consumption?

Open lesson →
Mathematics visual
Lesson 12LESSON · 4 picturesInput Output Pairs

How does continuous text turn into supervised training targets for LLM pretraining?

Open lesson →
Mathematics visual
Lesson 13LESSON · 13 picturesToken Embedding

What core mathematical principle governs bridge token ids versus learned values?

Open lesson →
Mathematics visual
Lesson 14LESSON · 9 picturesPositional Embedding

Why does standard self-attention treat 'dog bites man' and 'man bites dog' identically without positional encodings?

Open lesson →
Mathematics visual
Lesson 15LESSON · 3 picturesPreprocessing Summary

What is the complete journey from raw text strings to GPU tensor inputs?

Open lesson →
Mathematics visual
Lesson 16LESSON · 10 picturesAttention Mechanism

Why are static word embeddings insufficient for words with multiple meanings, and how does attention dynamically contextualize them?

Open lesson →
Mathematics visual
Lesson 17LESSON · 5 picturesSimplified Attention

What is the simplest mathematical formulation of self-attention without trainable weights?

Open lesson →
Mathematics visual
Lesson 18LESSON · 10 picturesSelf Attention With Weights

Why cannot self-attention just use raw input vectors, and what are Queries, Keys, and Values?

Open lesson →
Mathematics visual
Lesson 19LESSON · 6 picturesCausal Attention

Why must generative LLMs conceal future token positions, and how does causal masking enforce autoregression?

Open lesson →
Mathematics visual
Lesson 20LESSON · 6 picturesMultihead Attention Part 1

Why are multiple attention heads better than one single head, and how is the embedding dimension partitioned?

Open lesson →
Mathematics visual
Lesson 21LESSON · 4 picturesMultihead Attention Part 2

How do multiple head outputs recombine, and how do 4D tensors flow through multi-head attention?

Open lesson →
Mathematics visual
Lesson 22LESSON · 7 picturesLLM Architecture

How are Transformer blocks composed, stacked, and projected to predict next tokens?

Open lesson →
Mathematics visual
Lesson 23LESSON · 11 picturesLayer Normalization

Why do deep transformer networks suffer from internal covariate shift and exploding/vanishing gradients without normalization?

Open lesson →
Mathematics visual
Lesson 24LESSON · 6 picturesGelu Activation

How does the Gaussian Error Linear Unit (GELU) introduce probabilistic gating compared to deterministic ReLU?

Open lesson →
Mathematics visual
Lesson 25LESSON · 5 picturesShortcut Connections

How do residual shortcut connections create an unhindered gradient highway across deep transformer layers?

Open lesson →
Mathematics visual
Lesson 26LESSON · 4 picturesTransformer Block

How are all sub-components assembled into a Pre-LN Transformer Block, and what is its shape ledger?

Open lesson →
Mathematics visual
Lesson 27LESSON · 8 picturesGPT-2 (124M)

How does GPT-2 (124M) construct its unified input tensor from discrete token IDs and positional embeddings?

Open lesson →
Mathematics visual
Lesson 28LESSON · 12 picturesText Generation: Logit Decoding, Argmax & Context Caching

How do raw 3D unnormalized logits from the final transformer layer get converted into coherent, auto-regressively generated natural language tokens?

Open lesson →
Mathematics visual
Lesson 29LESSON · 20 picturesLLM Loss Engine: Target Shifting, Cross-Entropy & Perplexity

How do we mathematically quantify prediction error across billions of tokens, and how does cross-entropy loss translate directly into language perplexity?

Open lesson →
Mathematics visual
Lesson 30LESSON · 3 picturesValidation Loss

How does perplexity and overfitting intuition solve the underlying computational bottleneck?

Open lesson →
Mathematics visual
Lesson 31LESSON · 7 picturesValidation Loss & Overfitting Diagnostics on Real Text

How do we detect when a language model stops learning linguistic grammar and starts memorizing training noise, and how do train/validation splits prevent overfitting?

Open lesson →
Mathematics visual
Lesson 32LESSON · 7 picturesLLM Pretraining: Optimization Loops, Cosine Schedules & Stability

How do learning rate schedules, gradient clipping, and AdamW optimization integrate into a production pretraining loop that trains billions of parameters without loss spikes or divergence?

Open lesson →
Mathematics visual
Lesson 33LESSON · 12 picturesTemperature Scaling, Top-k & Nucleus (Top-p) Sampling

How do temperature scaling, top-k filtering, and nucleus (top-p) sampling mathematically reshape probability distributions to eliminate repetitive loops and hallucinated tail tokens?

Open lesson →
Mathematics visual
Lesson 34LESSON · 8 picturesModel Checkpointing: State Dicts, Safetensors & Zero-Copy Loading

How do billions of floating-point weights and optimizer moments get safely serialized to disk without memory duplication or arbitrary code execution vulnerabilities?

Open lesson →
Mathematics visual
Lesson 35LESSON · 7 picturesOpenAI Pretrained Weights: Checkpoints, Transposition & Verification

How do official TensorFlow-format GPT-2 model weights from OpenAI get downloaded, mapped, transposed, and verified byte-for-byte inside a from-scratch PyTorch architecture?

Open lesson →
Mathematics visual
Lesson 36LESSON · 7 picturesInstruction Finetuning: The SFT Paradigm, Alpaca & Prompt Formats

Why does a base pretrained language model fail to answer simple questions, and how does supervised instruction finetuning (SFT) transform a raw document completer into a helpful, obedient AI assistant?

Open lesson →
Mathematics visual
Lesson 37LESSON · 7 picturesInstruction Data Batching: Dynamic Collation, Padding & Loss Masking

How do variable-length prompt-response pairs get transformed into rectangular batches without computing loss on padding or prompt tokens?

Open lesson →
Mathematics visual
Lesson 38LESSON · 1 picturesLlm Finetuning Intro

How does head surgery classification replacement solve the underlying computational bottleneck?

Open lesson →
Mathematics visual
Lesson 39LESSON · 6 picturesSupervised Finetuning (SFT) Execution Loop & Training Dynamics

How does the full-parameter supervised finetuning loop orchestrate forward passes, masked loss computation, gradient accumulation, and checkpoint saving?

Open lesson →
Mathematics visual
Lesson 40LESSON · 12 picturesClassification Finetuning: Head Surgery, Freezing & Last-Token Pooling

How are generative autoregressive transformers repurposed into high-precision discrete classifiers through linear head surgery and selective parameter freezing?

Open lesson →
Mathematics visual
Lesson 41LESSON · 7 picturesFinetuning Classification Accuracy: Training Loop & Confusion Matrix Audit

How are unnormalized scalar logits converted into discrete binary or multi-class decisions, and why is softmax mathematically redundant for argmax?

Open lesson →
Mathematics visual
Lesson 42LESSON · 8 picturesStanford Alpaca: Supervised Instruction Finetuning From Scratch

Master the complete Stanford Alpaca instruction finetuning pipeline: parse 52,000 JSON records, implement structured prompt templates, execute dynamic batch collation with prompt loss shielding, run the SFT training loop with cosine warmup, and benchmark qualitative responses.

Open lesson →
Mathematics visual
Lesson 43LESSON · 7 picturesFinetuned LLM Evaluation: Metrics, Hierarchy, and Benchmarking

Why do traditional n-gram matching metrics like BLEU and ROUGE fail to fully capture generative LLM quality, and how do precision and recall trade off mathematically?

Open lesson →
Mathematics visual
Lesson 44LESSON · 8 picturesPEFT & LoRA: Parameter-Efficient Low-Rank Adaptation

Why is full-parameter fine-tuning computationally prohibitive on modern GPUs, and how does PEFT solve the memory crisis?

Open lesson →
Mathematics visual
Lesson 45LESSON · 4 picturesLoRA Attention Targets, QLoRA, and Foundation Tradeoffs

Which specific projection layers inside a transformer block yield the highest performance gains when adapted with LoRA?

Open lesson →
Mathematics visual
Lesson 46LESSON · 5 picturesInstruction Finetuning Loop Execution, Convergence, and Capstone Stress Testing

How is the complete instruction finetuning training loop structured in PyTorch with AdamW, learning rate schedules, and masked loss?

Open lesson →
Mathematics visual
Lesson 47LESSON · 10 picturesDirect Preference Optimization (DPO): Calculus, Gradients, and Geometry

Why is supervised fine-tuning insufficient for aligning generative behavior, and why is a reference KL anchor required?

Open lesson →
Mathematics visual
Lesson 48LESSON · 7 picturesRLHF & PPO Mechanics: Reward Modeling, Advantage, and Trust Regions

How is a generative autoregressive transformer modified into a scalar reward model, and how is it trained on preference pairs?

Open lesson →
Mathematics visual
Lesson 49LESSON · 6 picturesModern Preference Optimization: KTO, ORPO, IPO, and GRPO

How does KTO align models using unpaired binary feedback (thumbs up / thumbs down) inspired by behavioral economics?

Open lesson →
Mathematics visual
Lesson 50LESSON · 7 picturesVerification, Search & Speculation: PRMs, MCTS, and Medusa

Why do Outcome Reward Models (ORMs) fail in multi-step reasoning, and how do Process Reward Models (PRMs) assign step-level credit?

Open lesson →
Mathematics visual
Lesson 51LESSON · 8 picturesInference Optimization: The Bandwidth Wall, PagedAttention, and FlashAttention

Why is autoregressive token generation bottlenecked by memory bandwidth rather than GPU compute, and how does the KV cache scale?

Open lesson →
Mathematics visual
Lesson 52LESSON · 6 picturesDistributed Scaling and Quantization: MoE, Megatron-LM, Pipeline 1F1B, and ZeRO

How does Sparse MoE scale total parameter capacity without increasing active FLOPs per token?

Open lesson →
Mathematics visual
Lesson 53LESSON · 5 picturesFrontier Scaling and Capstone: FP8 Precision, Mixture of Depths, NIAH, and Unified LLM Architecture

How does 8-bit floating point training double GPU GEMM throughput while preventing gradient underflow via delayed scaling?

Open lesson →
Mathematics visual
Lesson 54LESSON · 8 picturesElementary Math Bridges: High School Arithmetic to AI Intuition

How does a 2D Cartesian plane turn discrete text words into continuous geometric thought space where distance measures meaning?

Open lesson →