Skip to content
ImagineWorld

Building a Frontier LLM from Scratch

node_idnode-book_building-frontier-llm-from-scratch
node_typenode-book
schema_profileworld.node_book.v1
statusactive
orthogonal_scopemanifold, entropy, authority, state
manifoldworld
entropymedium
authorityinforms
stateexternal
domainimagineworld.net
node_interiorrosetta_contract
unisonone evidence claim read five ways: seated in the llms field, the work builds a frontier LLM from scratch — pushing the from-scratch build toward the frontier — its framework, regime, and stance agreeing on what it is
governed_byWORLD-MANIFOLD
constitutional_citationCONSTITUTION
evidence_bundleworld-bundle-publication
compared_byworld-comparison-pillar-f-compiler-trinity-and-training-infrastructure
grounded_by
anchors_into
peer_node_books
pillar_membershipF — training_infrastructure
book_titleBuilding a Frontier LLM from Scratch
book_subtitleArchitecture, Training, Alignment, and Serving of a DeepSeek-Style Mixture-of-Experts Reasoning Model
book_authorChong Lip Phang
total_chapters45
total_source_pages417
total_nodes53
source_pdfbuilding-frontier-llm-from-scratch_author_chong-lip-phang.pdf
source_pdf_sha256daf07e4fcaa854943082847b84bc310cf3cd0d764740d3fcfefe8a49efb3ab05
source_text_output_slugbuilding-frontier-llm-from-scratch
ocr_sourceQwen3-VL-8B-Instruct via llama-server (scaffold-ocr-batch-v2; pdftoppm 150dpi grayscale)
ocr_quality_classdraft
verification_statusunverified
verification_progress{"all_nodes":"stitched from OCR output; frontier verification status per node"}
stitched_bykimi-k3-frontier-transposition-pass
generated_at2026-09-20
pillar_normalizedF-training_infrastructure
updated_at2026-10-14T05:45:16Z
local graph

Building a Frontier LLM from Scratch — Chong Lip Phang

Section titled “Building a Frontier LLM from Scratch — Chong Lip Phang”

Architecture, Training, Alignment, and Serving of a DeepSeek-Style Mixture-of-Experts Reasoning Model.

The book is organized as 45 chapters under eleven parts — Foundations; Data and Tokenization; The Transformer; Modern LLM Architecture; Training at Scale; Post-Training and Alignment; Inference, Serving, and Evaluation; Capstone and Frontiers; Generative AI Systems in Practice; The Research Frontier; Case Studies — followed by appendices A–F and a closing Exercises section. Scan anomalies: printed pages 2–3 (front matter) are absent; printed 23 survives only as a garbled duplicate shoot (dropped, PDF 021); printed 356–357 — Chapter 43’s opening — are missing from the scan, so that chapter node begins mid-sentence; the printed-page markers for PDF 065 and PDF 297 were lost in OCR but their content is continuous.

node-book_building-frontier-llm-from-scratch_chapter-01-the-landscape-of-large-language-models — The Landscape of Large Language Models

node-book_building-frontier-llm-from-scratch_chapter-02-mathematical-and-computational-foundations — Mathematical and Computational Foundations

node-book_building-frontier-llm-from-scratch_chapter-03-tensors-autograd-and-pytorch — Tensors, Autograd, and PyTorch

node-book_building-frontier-llm-from-scratch_chapter-04-language-modeling-fundamentals — Language Modeling Fundamentals

node-book_building-frontier-llm-from-scratch_chapter-05-tokenization — Tokenization

node-book_building-frontier-llm-from-scratch_chapter-06-pretraining-data-pipelines — Pretraining Data Pipelines

node-book_building-frontier-llm-from-scratch_chapter-07-attention-from-first-principles — Attention from First Principles

node-book_building-frontier-llm-from-scratch_chapter-08-multi-head-attention-and-the-transformer-block — Multi-Head Attention and the Transformer Block

node-book_building-frontier-llm-from-scratch_chapter-09-positional-information — Positional Information

node-book_building-frontier-llm-from-scratch_chapter-10-building-gpt-from-scratch — Building GPT from Scratch

node-book_building-frontier-llm-from-scratch_chapter-11-mixture-of-experts — Mixture-of-Experts

node-book_building-frontier-llm-from-scratch_chapter-12-multi-head-latent-attention — Multi-Head Latent Attention

node-book_building-frontier-llm-from-scratch_chapter-13-training-objective-innovations-multi-token-prediction — Training-Objective Innovations: Multi-Token Prediction

node-book_building-frontier-llm-from-scratch_chapter-14-efficient-and-sparse-attention-at-scale — Efficient and Sparse Attention at Scale

node-book_building-frontier-llm-from-scratch_chapter-15-normalization-activations-and-position-revisited — Normalization, Activations, and Position Revisited

node-book_building-frontier-llm-from-scratch_chapter-16-putting-the-architecture-together — Putting the Architecture Together

node-book_building-frontier-llm-from-scratch_chapter-17-the-pretraining-loop-at-scale — The Pretraining Loop at Scale

node-book_building-frontier-llm-from-scratch_chapter-18-fp8-and-mixed-precision-training — FP8 and Mixed-Precision Training

node-book_building-frontier-llm-from-scratch_chapter-19-distributed-training — Distributed Training

node-book_building-frontier-llm-from-scratch_chapter-20-training-infrastructure-and-economics — Training Infrastructure and Economics

node-book_building-frontier-llm-from-scratch_chapter-21-training-stability — Training Stability

node-book_building-frontier-llm-from-scratch_chapter-22-supervised-fine-tuning — Supervised Fine-Tuning

node-book_building-frontier-llm-from-scratch_chapter-23-learning-from-human-feedback — Learning from Human Feedback

node-book_building-frontier-llm-from-scratch_chapter-24-direct-preference-optimization — Direct Preference Optimization

node-book_building-frontier-llm-from-scratch_chapter-25-reasoning-with-reinforcement-learning — Reasoning with Reinforcement Learning

node-book_building-frontier-llm-from-scratch_chapter-26-distillation-and-quantization — Distillation and Quantization

node-book_building-frontier-llm-from-scratch_chapter-27-inference-how-generation-works — Inference: How Generation Works

node-book_building-frontier-llm-from-scratch_chapter-28-serving-models-at-scale — Serving Models at Scale

node-book_building-frontier-llm-from-scratch_chapter-29-evaluating-language-models — Evaluating Language Models

node-book_building-frontier-llm-from-scratch_chapter-30-capstone-ii-build-your-own-model — Capstone II — Build Your Own Model

node-book_building-frontier-llm-from-scratch_chapter-31-multimodal-systems-tools-and-agents — Multimodal Systems, Tools, and Agents

node-book_building-frontier-llm-from-scratch_chapter-32-the-frontier — The Frontier

node-book_building-frontier-llm-from-scratch_chapter-33-the-open-source-ecosystem — The Open-Source Ecosystem

node-book_building-frontier-llm-from-scratch_chapter-34-the-industry-landscape — The Industry Landscape

node-book_building-frontier-llm-from-scratch_chapter-35-cloud-clusters-and-kubernetes — Cloud, Clusters, and Kubernetes

node-book_building-frontier-llm-from-scratch_chapter-36-an-end-to-end-system-blueprint — An End-to-End System Blueprint

node-book_building-frontier-llm-from-scratch_chapter-37-beyond-quadratic-attention — Beyond Quadratic Attention

node-book_building-frontier-llm-from-scratch_chapter-38-reasoning-and-test-time-compute — Reasoning and Test-Time Compute

node-book_building-frontier-llm-from-scratch_chapter-39-agents-and-long-horizon-autonomy — Agents and Long-Horizon Autonomy

node-book_building-frontier-llm-from-scratch_chapter-40-multimodality-and-world-models — Multimodality and World Models

node-book_building-frontier-llm-from-scratch_chapter-41-efficiency-and-compression-frontiers — Efficiency and Compression Frontiers

node-book_building-frontier-llm-from-scratch_chapter-42-data-synthetic-data-and-self-improvement — Data, Synthetic Data, and Self-Improvement

node-book_building-frontier-llm-from-scratch_chapter-43-alignment-interpretability-and-safety — Alignment, Interpretability, and Safety

node-book_building-frontier-llm-from-scratch_chapter-44-glm-52-anatomy-of-a-frontier-open-model — GLM-5.2: Anatomy of a Frontier Open Model

node-book_building-frontier-llm-from-scratch_chapter-45-deepseek-v3-the-efficient-frontier — DeepSeek-V3: The Efficient Frontier

node-book_building-frontier-llm-from-scratch_appendix-a-repository-atlas — Appendix A: Repository Atlas

node-book_building-frontier-llm-from-scratch_appendix-b-notation-and-glossary — Appendix B: Notation and Glossary

node-book_building-frontier-llm-from-scratch_appendix-c-hyperparameter-cheat-sheet — Appendix C: Hyperparameter Cheat-Sheet

node-book_building-frontier-llm-from-scratch_appendix-d-hardware-and-cost-reference — Appendix D: Hardware and Cost Reference

node-book_building-frontier-llm-from-scratch_appendix-e-licensing-and-responsible-use — Appendix E: Licensing and Responsible Use

node-book_building-frontier-llm-from-scratch_appendix-f-further-reading — Appendix F: Further Reading

node-book_building-frontier-llm-from-scratch_back-exercises — Exercises

Table of Contents Preface…3 Part I — The Landscape and the Foundations…24 Chapter 1 — The Landscape of Large Language Models…25 1.1 Open-Source, Open-Weight, and Closed…25 1.2 A Family Tree of Modern Models…26 1.3 The Field at a Glance…27 1.4 Architectural Methodologies, Side by Side…29 1.5 The Defining Split: Dense versus Sparse…30 1.6 Reading Benchmarks Without Fooling Yourself…32 1.7 What Modern LLMs Can Actually Do…33 1.8 How This Book Is Organized, and Why It Is Different…35 1.9 The Scaling Hypothesis, Quantified…36 Chapter 2 — Mathematical and Computational Foundations…38 2.1 Linear Algebra for Deep Learning…38 Vectors, matrices, tensors, and shapes…39 Matrix multiplication is the atom…39 Low-rank structure: the idea behind MLA and LoRA…39 2.2 Probability and Information Theory…40 2.3 Calculus and Optimization…41 Gradients and the chain rule…41 The optimizers that train language models…41 2.4 The Compute Stack…42 The memory hierarchy and why bandwidth is destiny…42 Arithmetic intensity and the roofline…43 Numerical precision: the formats that make training affordable…44 2.5 Backpropagation by Hand…45

Chapter 3 — Tensors, Autograd, and PyTorch…46 3.1 Tensors in PyTorch…46 Shapes, strides, and broadcasting…46 3.2 Building Autograd from Scratch…47 3.3 From Scalars to Tensors: nn.Module and Optimizers…50 3.4 A Minimal Training Loop…51 3.5 A Minimal Training Loop…53 Chapter 4 — Language Modeling Fundamentals…55 4.1 What a Language Model Is…55 4.2 The Next-Token Objective…56 4.3 Tokens In, Distribution Out…57 4.4 Decoding: Turning Distributions into Text…57 4.5 A Baseline You Can Train Tonight…58 4.6 Perplexity: Measuring a Language Model…60 4.7 The Generation Gap: Teacher Forcing versus Autoregression…61 4.8 Why Next-Token Prediction Is Enough…61 Part II — Data and Tokenization…63 Chapter 5 — Tokenization…64 5.1 From Characters to Subwords…64 5.2 Byte-Pair Encoding from Scratch…65 Byte-level BPE and the pre-tokenizer…66 5.3 SentencePiece and the Unigram Alternative…68 5.4 Building Your Own Tokenizer, and How the Big Models Differ…68 5.5 Byte-Pair Encoding, Step by Step…70 5.6 Tokenization Pitfalls…71 5.7 Byte-Level, Character, and Word Tokenization…72

Chapter 6 — Pretraining Data Pipelines…73 6.1 Sourcing and the Scale of Modern Corpora…73 6.2 Cleaning and Quality Filtering…74 6.3 Deduplication…74 6.4 Tokenize, Shard, and Pack…75 6.5 Deduplication and Why It Matters…77 6.6 Data Mixing and Curriculum…78 6.7 Quality Filtering with Classifiers…79 Part III — The Transformer…81 hapter 7 — Attention from First Principles…82 7.1 The Intuition: Content-Based Routing…82 7.2 Scaled Dot-Product Attention…82 Why divide by the square root of the head dimension…83 7.3 Causal Masking…83 7.4 Worked Example: Attention on a Toy Sequence…86 7.5 The Cost of Attention…87 7.6 Grouped-Query and Multi-Query Attention…87 7.7 What Attention Heads Learn…88 Chapter 8 — Multi-Head Attention and the Transformer Block…90 8.1 Multi-Head Attention…90 8.2 The Feed-Forward Network…91 8.3 Normalization and the Residual Stream…92 8.4 Assembling the Transformer Block…93 8.5 The Residual Stream as a Communication Channel…95 8.6 The Feed-Forward Network: Where Knowledge Lives…96 8.7 Depth versus Width…97

Chapter 9 — Positional Information …99 9.1 Absolute Positions …99 9.2 Rotary Position Embeddings …99 9.3 Relative Biases: ALiBi and Friends …101 9.4 Extending the Context Window …102 9.5 Worked Example: Rotary Embeddings by Hand …103 9.6 Context-Length Extension …103 9.7 Why Absolute Position Embeddings Fell Out of Favor …104 Chapter 10 — Building GPT from Scratch — Capstone I …106 10.1 Wiring the Model …106 10.2 Counting Parameters and Scaling the Same Code …109 10.3 Training the Model …110 10.4 Generating Text …111 10.5 What We Built, and What Comes Next …111 10.6 Worked Example: Autoregressive Generation …112 10.7 The Decoder-Only Choice …113 Part IV — Modern LLM Architecture …114 Chapter 11 — Mixture-of-Experts …115 11.1 Conditional Computation …115 11.2 The Router and Top-k Selection …115 11.3 DeepSeekMoE: Fine-Grained and Shared Experts …116 11.4 Load Balancing Without Hurting the Loss …118 11.5 Expert Parallelism, in One Paragraph …119 11.6 Worked Example: Routing a Token Through the Experts …120 11.7 Fine-Grained Experts and the Shared Expert …121 11.8 Routing Collapse and Load Balancing …122

Chapter 12 — Multi-Head Latent Attention …123 12.1 The KV-Cache Bottleneck…123 12.2 From MHA to GQA to MLA…123 12.3 Low-Rank Compression of Keys and Values…124 12.4 The Wrinkle: Decoupled RoPE…124 12.5 The Memory Math…125 12.6 Fast Decoding with FlashMLA…126 12.7 Worked Example: How MLA Shrinks the KV Cache …128 12.8 MLA and RoPE: The Decoupled Position Trick…129 12.9 The KV Cache in Numbers …129 Chapter 13 — Training-Objective Innovations: Multi-Token Prediction …131 13.1 Predicting Several Tokens at Once …131 13.2 MTP in DeepSeek-V3…131 13.3 A Free Draft Model: MTP and Speculative Decoding …132 13.4 Worked Example: The Multi-Token Prediction Loss …133 13.5 MTP at Inference: A Built-In Draft Model …134 13.6 How Many Tokens to Predict?…135 Chapter 14 — Efficient and Sparse Attention at Scale …136 14.1 The Quadratic Problem…136 14.2 FlashAttention: Exact but IO-Aware…137 14.3 Sparse Attention: Attending to Less…137 14.4 The Long-Context Frontier…138 14.5 Worked Example: The Indexer’s Top-k Selection …139 14.6 Sparse Attention Patterns: Sliding Window and Global Tokens…140 14.7 The Long-Context Problem, Assembled…141

Chapter 15 — Normalization, Activations, and Position Revisited…143 15.1 Normalization, in Detail…143 15.2 Activations and the Gated FFN…144 15.3 Position, Revisited…144 15.4 The Cumulative Picture…145 15.5 Worked Example: RMSNorm versus LayerNorm…146 15.6 Where to Place the Norm: Pre-Norm, Post-Norm, and QK-Norm…147 15.7 Could We Remove Normalization?…148 Chapter 16 — Putting the Architecture Together…149 16.1 The Modern Block: MLA plus MoE…149 16.2 The Complete Model…150 16.3 DeepSeek-V3 by the Numbers…151 16.4 From Baseline GPT to Frontier Model…152 16.5 Worked Example: Counting the Parameters…153 16.6 The Configuration File as Architecture…154 16.7 Tied Embeddings…154 Part V — Training at Scale…156 Chapter 17 — The Pretraining Loop at Scale…157 17.1 The Objective at Scale…157 17.2 Learning-Rate Schedules…157 17.3 Batch Size and the Token Budget…158 17.4 Continued Pre-Training…159 17.5 Checkpointing and Determinism…160 17.6 Worked Example: One Real Training Step…161 17.7 Gradient Accumulation and Effective Batch Size…161 17.8 Worked Example: One Optimizer Step, End to End…162 17.9 AdamW and the Cost of Optimizer State…162 17.10 Reproducibility: Seeds, Determinism, and Why It Is Hard…163

17.11 Activation Checkpointing: Trading Compute for Memory…164 17.12 Effective Batch Size and the Linear Scaling Rule…165 Chapter 18 — FP8 and Mixed-Precision Training …166 18.1 Why Lower Precision…166 18.2 Mixed Precision, Recapped …166 18.3 The FP8 Challenge…167 18.4 Fine-Grained Quantization and DeepGEMM…167 18.5 Worked Example: Casting a Tensor to FP8…169 18.6 Delayed Scaling and the Amax History …169 18.7 Worked Example: What Stays in High Precision …170 18.8 The Granularity of Scaling: Per-Tensor to Per-Block…170 18.9 The Two FP8 Formats: E4M3 and E5M2…171 18.10 Stochastic Rounding…172 18.11 Why Matrix Multiplication Dominates…173 Chapter 19 — Distributed Training…175 19.1 Data Parallelism, ZeRO, and FSDP…175 19.2 Tensor Parallelism…175 19.3 Pipeline Parallelism and DualPipe…176 19.4 Expert Parallelism…176 19.5 Combining the Dimensions…177 19.6 Worked Example: Sharding a Model with FSDP…178 19.7 The Collective Operations Underneath…178 19.8 Worked Example: Mapping a Model onto 1,024 GPUs…179 19.9 Overlapping Communication with Computation…180 19.10 Sequence Parallelism…181 19.11 The 1F1B Pipeline Schedule…181

Chapter 20 — Training Infrastructure and Economics…183 20.1 Feeding the GPUs: Storage and Data…183 20.2 The Open Kernel and Systems Stack…183 20.3 Measuring Efficiency: Model FLOPs Utilization…184 20.4 The Economics of a Run…185 20.5 Worked Example: Sharded Checkpointing…186 20.6 Fault Tolerance: Surviving Hardware at Scale…186 20.7 Worked Example: Profiling to Find the Bottleneck…187 20.8 When the Data Loader Is the Bottleneck…188 20.9 Kernel Fusion and FlashAttention as a Systems Win…189 Chapter 21 — Training Stability…191 21.1 Loss Spikes…191 21.2 Surviving Spikes…192 21.3 What to Monitor…193 21.4 Worked Example: Detecting and Surviving a Loss Spike…193 21.5 NaNs, Infs, and Where They Come From…194 21.6 The Practitioner’s Monitoring Dashboard…194 21.7 Recovering from a Loss Spike: A Runbook…195 21.8 Why Weight Decay and z-loss Stabilize Training…196 21.9 Silent Failures…197 21.10 Initialization and Stability from Step One…198 Part VI — Post-Training and Alignment…200 Chapter 22 — Supervised Fine-Tuning…201 22.1 From Base Model to Assistant…201 22.2 Instruction Data and Chat Templates…201 22.3 The SFT Training Loop…202 22.4 Parameter-Efficient Fine-Tuning: LoRA…202

22.5 Worked Example: Loss Masking for SFT …204 22.6 Sequence Packing …205 22.7 Worked Example: A Chat Template, Tokenized …205 22.8 LoRA and Parameter-Efficient Fine-Tuning …206 22.9 Data Quality and Diversity in SFT …207 22.10 Special Tokens and the Chat Template …208 22.11 Sequence Packing …208 Chapter 23 — Learning from Human Feedback …210 23.1 Why Learn from Preferences …210 23.2 The Reward Model …210 23.3 Optimizing the Policy with PPO …211 23.4 The Difficulties That Motivated What Came Next …212 23.5 Worked Example: The PPO Clipped Objective …213 23.6 Reward Hacking and the KL Leash …213 23.7 Worked Example: From Sequence Reward to Per-Token Signal …214 23.8 The Four Models of PPO …215 23.9 Training the Reward Model: Bradley–Terry …215 23.10 Generalized Advantage Estimation …216 Chapter 24 — Direct Preference Optimization …218 24.1 The Key Insight …218 24.2 The DPO Loss …218 24.3 Variants and When to Use Which …219 24.4 Worked Example: The DPO Loss in One Line …220 24.5 Why DPO Drifts, and How to Anchor It …221 24.6 Worked Example: One DPO Step, by the Numbers …222 24.7 The DPO Family: IPO, KTO, and Beyond …222 24.8 The Implicit Reward in DPO …223 24.9 Length Bias in Preference Optimization …224

Chapter 25 — Reasoning with Reinforcement Learning …226 25.1 Reasoning as a Learnable Skill …226 25.2 GRPO: Group Relative Policy Optimization …226 25.3 DeepSeek-R1-Zero: Reasoning from Pure RL …228 25.4 DeepSeek-R1: The Full Recipe …228 25.5 Distilling Reasoning into Small Models …229 25.6 Worked Example: The GRPO Advantage …230 25.7 Verifiable Rewards and Reward Design …231 25.8 Worked Example: A GRPO Update from One Group …232 25.9 Clipping and the KL Term in GRPO …232 25.10 R1-Zero versus R1: The Role of Cold-Start Data …233 25.11 Designing Verifiable Rewards …234 25.12 On-Policy versus Off-Policy …235 Chapter 26 — Distillation and Quantization …236 26.1 Knowledge Distillation …236 26.2 Quantization for Inference …237 26.3 Post-Training Quantization Methods …237 26.4 Small, Fast, and Deployable …238 26.5 Worked Example: The Distillation Loss …239 26.6 Quantization-Aware Training …240 26.7 Worked Example: Sizing a Quantized Model …241 26.8 Distillation with Soft Targets …241 26.9 Pruning and Structured Sparsity …242 26.10 GPTQ and AWQ: Post-Training Quantization Methods …243 Part VII — Inference, Serving, and Evaluation …245 Chapter 27 — Inference: How Generation Works …246 27.1 Two Phases: Prefill and Decode …246 27.2 The KV Cache …247

27.3 Speculative Decoding…248 27.4 Worked Example: The KV Cache…248 27.5 Worked Example: Speculative Decoding…249 27.6 Decoding Strategies: Temperature, Top-k, and Nucleus…249 27.7 Worked Example: KV-Cache Memory at Long Context…250 27.8 Beam Search and Why Sampling Won …251 27.9 Constrained Decoding: Grammars and JSON…252 27.10 KV-Cache Quantization…253 Chapter 28 — Serving Models at Scale …254 28.1 The Economics of Serving…254 28.2 Continuous Batching…254 28.3 Paged Attention…255 28.4 The Serving Stack…255 28.5 Worked Example: Continuous Batching…257 28.6 Prefix Caching for Shared Prompts…257 28.7 Worked Example: The Throughput-Latency Trade-off…258 28.8 Disaggregated Prefill and Decode…259 28.9 Autoscaling and Load Balancing Across Replicas…259 28.10 Chunked Prefill…260 Chapter 29 — Evaluating Language Models…262 29.1 The Benchmark Landscape…262 29.2 Why Benchmarks Mislead…263 29.3 Evaluating Honestly…263 29.4 Reasoning and Long Context…264 29.5 Worked Example: A Minimal Evaluation Harness …265 29.6 Contamination and Leakage…266 29.7 Worked Example: LLM-as-a-Judge …266 29.8 Pass@k and Sampling-Based Metrics…267

29.9 Human Evaluation and A/B Testing…268 29.10 Benchmark Contamination…269 29.11 The Major Benchmark Suites…270 Part VIII — Capstone and Frontiers…272 Chapter 30 — Capstone II — Build Your Own Model…273 30.1 Scope It to What You Can Afford…273 30.2 The End-to-End Checklist…273 30.3 A Concrete Small Configuration…274 30.4 Practical Advice…274 30.5 Worked Example: The Whole Book as One Pipeline…275 30.6 Common Pitfalls and How They Show Up…276 30.7 Worked Example: A Training Budget on a Single Node…276 30.8 From Capstone to Production: What Is Still Missing…277 30.9 Debugging a Training Run…278 Chapter 31 — Multimodal Systems, Tools, and Agents…279 31.1 Vision-Language Models…279 31.2 Other Modalities, and Generation…280 31.3 Tool Use and Function Calling…280 31.4 Agents…281 31.5 Worked Example: Training the Vision Projector…282 31.6 Connecting a Vision Encoder: The Full Path…282 31.7 Worked Example: How Many Tokens Is an Image?…283 31.8 Audio and Speech…283 31.9 Cross-Modal Alignment…284 Chapter 32 — The Frontier…286 32.1 Where the Architecture Is Going…286 32.2 Training, Reasoning, and Test-Time Compute…286 32.3 Efficiency and Access…287

32.4 Open Problems, and a Closing Word…287 32.5 The Road Ahead: A Map of Part X…288 32.6 Adjacent Capabilities the Model Does Not Provide …289 32.7 The Pace of Progress and How to Keep Up …290 Part IX — Generative AI Systems in Practice…292 Chapter 33 — The Open-Source Ecosystem…293 33.1 The Layers of the Stack…293 33.2 The Numerical Foundation: PyTorch and JAX …294 33.3 Training Frameworks…294 33.4 Data, Fine-Tuning, and Evaluation…295 33.5 Inference and Edge…295 33.6 Worked Example: Running an Open-Weights Frontier Model Locally …296 33.7 The Open versus Closed Model Debate…296 33.8 The Hub and Model Distribution…297 Chapter 34 — The Industry Landscape…299 34.1 How the Money Works…299 34.2 The Frontier Labs…300 34.3 The Open-Weight Challengers…300 34.4 The Pick-and-Shovel Businesses…301 34.5 Worked Example: API, Fine-Tune, or Pretrain?…301 34.6 The Inference Cost Curve…302 34.7 Total Cost of Ownership over Time…303 Chapter 35 — Cloud, Clusters, and Kubernetes…305 35.1 Why Train in the Cloud…305 35.2 Why Kubernetes…305 35.3 Requesting GPUs…306 35.4 Distributed Training with PyTorchJob…306 35.5 Beyond the Basics…307

35.6 Worked Example: A Kubernetes Inference Deployment …308 35.7 Multi-Region Deployment and Latency …309 35.8 Spot Instances and Cost Optimization …310 Chapter 36 — An End-to-End System Blueprint …311 36.1 The Stages, End to End …311 36.2 Pseudocode for the Overall Design …312 36.3 Reading the Blueprint …312 36.4 The Reference Architecture, End to End …313 36.5 Observability: Logging, Metrics, and Tracing …314 36.6 Versioning, Canary, and Rollback …315 Part X — The Research Frontier …316 Chapter 37 — Beyond Quadratic Attention …317 37.1 The Quadratic Wall …317 37.2 Linear Attention …317 37.3 State-Space Models …318 37.4 Hybrid Architectures …319 37.5 Open Questions …319 37.6 Worked Example: When Linear Attention Wins …320 37.7 Mamba and Selective State Spaces …321 37.8 Linear Attention and the Kernel View …321 37.9 Hybrid Architectures …322 Chapter 38 — Reasoning and Test-Time Compute …324 38.1 A Second Scaling Axis …324 38.2 The Simplest Form: Sampling and Voting …324 38.3 Learning to Think: RL with Verifiable Rewards …325 38.4 Spending the Budget Wisely …326 38.5 The Boundary of What RL Can Teach …326 38.6 Worked Example: Allocating a Test-Time Compute Budget …327

38.7 Process Reward versus Outcome Reward…328 38.8 Inference-Time Search: Tree of Thought…329 38.9 Self-Consistency: Sampling and Voting…329 Chapter 39 — Agents and Long-Horizon Autonomy…331 39.1 The Agent Loop…331 39.2 Why Long Horizons Are Hard…331 39.3 What Makes Agents Better…332 39.4 Multi-Agent Systems…333 39.5 Worked Example: The Agent Loop with Tool Calls…333 39.6 Memory and Context Management for Agents…334 39.7 Multi-Agent Systems…335 39.8 Tool-Use Protocols and Standardization…336 Chapter 40 — Multimodality and World Models…337 40.1 The Bolt-On Pattern…337 40.2 Toward Native Multimodality…338 40.3 World Models…338 40.4 Why It Matters…339 40.5 Worked Example: Interleaving Modalities in One Sequence…339 40.6 Diffusion versus Autoregressive Generation…340 40.7 Toward Any-to-Any Unified Models…341 40.8 Video Understanding…342 Chapter 41 — Efficiency and Compression Frontiers…344 41.1 The Quality-per-Compute Frontier…344 41.2 Quantization Beyond 4 Bits…344 41.3 Compressing the KV Cache and the Compute…345 41.4 The Edge Frontier…346 41.5 Worked Example: The Speculative Decoding Speedup…346 41.6 Mixture-of-Depths and Adaptive Compute…347

41.7 Extreme Low-Bit and Quantization-Aware Training…348 41.8 Cross-Layer KV Sharing…349 Chapter 42 — Data, Synthetic Data, and Self-Improvement …350 42.1 The End of Easy Data …350 42.2 Data Quality and Curation …350 42.3 Synthetic Data …351 42.4 Self-Improvement and Its Limits …351 42.5 The Hazard: Model Collapse …352 42.6 Worked Example: Model Collapse from Synthetic Data …353 42.7 RLAIF and Constitutional Feedback …354 42.8 Synthetic Data and Self-Improvement …354 42.9 Curating Data at the Frontier …355 Chapter 43 — Alignment, Interpretability, and Safety …357 43.1 The Limits of Current Alignment …357 43.2 Scalable Oversight …357 43.3 Interpretability …358 43.4 Safety and Robustness …359 43.5 Why This Frontier Is Different …359 43.6 Worked Example: A Simple Interpretability Probe …360 43.7 Jailbreaks and the Robustness Arms Race …361 43.8 Interpretability and Mechanistic Understanding …361 43.9 Scalable Oversight …362 Part XI — Case Studies …364 Chapter 44 — GLM-5.2: Anatomy of a Frontier Open Model …365 38.1 The Configuration …365 38.2 Normalization and Routing, Unchanged …366 38.3 DeepSeek Sparse Attention: The Indexer …367 38.4 IndexShare: The One New Idea …367

38.5 Multi-Token Prediction, Context, and Effort…368 38.6 Running GLM-5.2…369 44.7 Worked Example: What IndexShare Saves …369 44.8 The Decoder Layer, Assembled…370 44.9 Controllable Reasoning Effort…371 44.10 GLM-5.2 in the Lineage…372 Chapter 45 — DeepSeek-V3: The Efficient Frontier …373 45.1 The Specification…373 45.2 Four Compounding Efficiencies…373 45.3 The Innovation That Ties It Together: Aux-Loss-Free Routing…374 45.4 From V3 to R1: Reasoning on Top …375 45.5 Why It Mattered…375 45.6 Worked Example: Active versus Total Parameters…375 45.7 Auxiliary-Loss-Free Load Balancing…376 45.8 Multi-Token Prediction and Its Inference Dividend…377 45.9 Training Efficiency: Capability Without Brute Force…377 45.10 The Recipe as a Reusable Template…378 Appendices…380 Appendix A — Repository Atlas…381 Training and Serving Frameworks…382 Appendix B — Notation and Glossary…384 Glossary of Core Terms…385 Glossary: Systems and Infrastructure…388 Appendix C — Hyperparameter Cheat-Sheet…389 Hyperparameter Reference Tables…390 Reference: Representative Model Configurations…391 Appendix D — Hardware and Cost Reference…393 Memory budgeting…393

Compute and cost…394 Reference Tables: Hardware, Memory, and Cost…394 Reference: Parallelism Strategies…395 Appendix E — Licensing and Responsible Use …397 A note on responsible use…397 Open-Source Licenses at a Glance…398 Responsible Use in Practice…399 Appendix F — Further Reading…400 Key Works by Topic…401 Broader Learning Resources…402 Exercises…404 Chapter 1 — The Landscape of Large Language Models…404 Chapter 2 — Mathematical and Computational Foundations…404 Chapter 3 — Tensors, Autograd, and PyTorch…405 Chapter 4 — Language Modeling Fundamentals…405 Chapter 5 — Tokenization…405 Chapter 6 — Pretraining Data Pipelines …406 Chapter 7 — Attention from First Principles …406 Chapter 8 — Multi-Head Attention and the Transformer Block…406 Chapter 9 — Positional Information…407 Chapter 10 — Building GPT from Scratch — Capstone I…407 Chapter 11 — Mixture-of-Experts…408 Chapter 12 — Multi-Head Latent Attention…408 Chapter 13 — Training-Objective Innovations …408 Chapter 14 — Efficient and Sparse Attention at Scale …409 Chapter 15 — Normalization, Activations, and Position Revisited …409 Chapter 16 — Putting the Architecture Together…409 Chapter 17 — The Pretraining Loop…410

Chapter 18 — Numerical Precision and FP8…410 Chapter 19 — Distributed Training…411 Chapter 20 — Infrastructure and Systems…411 Chapter 21 — Stability and Debugging Large Runs…412 Chapter 22 — Supervised Fine-Tuning…412 Chapter 23 — Reward Modeling and RLHF…413 Chapter 24 — Direct Preference Optimization and Variants…413 Chapter 25 — Reinforcement Learning for Reasoning — GRPO and DeepSeek-R1…414 Chapter 26 — Distillation and Compression…414 Chapter 27 — Inference and Decoding…415 Chapter 28 — Serving Systems…415 Chapter 29 — Evaluation and Benchmarking…416 Chapter 30 — Capstone II — Build, Train, and Align Your Own LLM…416 Chapter 31 — Multimodal and Beyond…416 Chapter 32 — The Frontier and What Comes Next…417 Chapter 33 — The Open-Source Ecosystem…417 Chapter 34 — The Industry Landscape…417 Chapter 35 — Cloud, Clusters, and Kubernetes…418 Chapter 36 — An End-to-End System Blueprint…418 Chapter 37 — Beyond Quadratic Attention…418 Chapter 38 — Reasoning and Test-Time Compute…419 Chapter 39 — Agents and Long-Horizon Autonomy…419 Chapter 40 — Multimodality and World Models…419 Chapter 41 — Efficiency and Compression Frontiers…420 Chapter 42 — Data, Synthetic Data, and Self-Improvement…420 Chapter 43 — Alignment, Interpretability, and Safety…420 Chapter 44 — GLM-5.2: Anatomy of a Frontier Open Model…421 Chapter 45 — DeepSeek-V3: The Efficient Frontier…421