AI Engineering
This book follows an AI system from its learning assumptions to a model you can build, train, serve, evaluate, and operate responsibly. The learning foundations explain the statistical and neural models; the construction chapters expose numerics, autograd, tokenization, attention, and inference; the production parts build retrieval, agents, evaluation, and serving around them. Read the worked implementations alongside the reasoning, commit to predictions before revealing answers, and validate each claim against a small example or a controlled failure.
266 sections
Start readingGlossaryContents
Section titled “Contents”Learning foundations
Section titled “Learning foundations”Build a model
Section titled “Build a model”- 6.1 Byte bigram: counts, logits, safetensors v0
- 6.2 Tensor, broadcasting backward, and no_grad
- 6.3 The op library and gradcheck_all
- 6.4 Losses with a fused backward
- 6.5 Module system and basic layers
- 6.6 Training loop and the autograd bigram
- 6.7 Safetensors for every dtype, atomic checkpoints, and the token stream
- 12.1 GPT: the decoder-only language model
- 12.2 BERT: the bidirectional encoder and masked language modeling
- 12.3 ELECTRA: replaced-token detection
- 12.4 T5: span corruption and relative position buckets
- 12.5 Fine-tuning heads and the linear-head export
- 12.6 LoRA: low-rank adaptation with PiSSA initialization and merging
- 12.7 The evaluation harness and the model zoo
- 13.1 Pre-LN and RMSNorm
- 13.2 Gated MLPs: SwiGLU and GeGLU
- 13.3 Rotary Position Embeddings
- 13.4 Context Extension: PI, NTK, YaRN, Llama 3 Scaling, and ALiBi
- 13.5 Grouped-Query Attention with a Cache Hook, Windows, and Sinks
- 13.6 Multi-Head Latent Attention and Weight Absorption
- 13.7 Sliding Windows and Attention Sinks
- 13.8 Mixture of Experts
- 13.9 The Llama-Family Model: Config, Weight Loading, and Download
Train and serve models
Section titled “Train and serve models”- 18.1 Supervised fine-tuning: chat rendering, assistant-only loss, packing
- 18.2 Direct preference optimization and IPO
- 18.3 Group relative policy optimization with verifiable rewards
- 18.4 Distillation with forward and reverse KL
- 18.5 On-policy, off-policy, offline, and online learning
- 18.6 PPO with a critic and generalized advantage estimation
- 18.7 Rewards, preference models, and independent evaluation
- 18.8 Rollout systems, GRPO variants, and training diagnostics
- 18.9 Distillation data, student rollouts, and deployment
- 18.10 SFT recipes, data strategies, and parameter updates
- 18.11 Preference optimization: DPO variants and related objectives
19. Choosing Training and Adaptation Methods
Section titled “19. Choosing Training and Adaptation Methods”- 19.1 Training lifecycle and learning signals
- 19.2 Pretraining compute and scaling
- 19.3 Memory, precision, and parallelism
- 19.4 Choosing post-training signals
- 19.5 Parameter-efficient fine-tuning
- 19.6 Evaluation and fine-tune scope
- 19.7 The training step and validation
- 19.8 How models learn: signals, objectives, and the training loop
- Code for Training and Post-Training
- 20.1 Quantization: Math to Code
- 20.1.1 Quantization error and granularity
- 20.1.2 Calibration and kernel execution
- 20.1.3 Weight and KV quantization methods
- 20.1.4 Choosing and validating quantization
- 20.2 Inference Frameworks: The Cross-Language Landscape
- 20.3 Model Loading: Hub to GPU
- 20.3.1 Repository and tensor contract
- 20.3.2 Downloads, loaders, and sharding
- 20.3.3 Cold starts and tokenizer equivalence
- 20.3.4 Portability and load triage
- Model Loading Code
- 20.4 Serving, Capacity & Load Testing: Math to Code
- 20.4.1 Step time and the roofline
- 20.4.2 Memory budget and serving SLOs
- 20.4.3 Parallelism and disaggregation
- 20.4.4 Engine controls and speculation
- 20.4.5 Adapters and elastic capacity
- 20.4.6 Load tests and the deployment runbook
- Serving and Load Code
- 20.5 LLM Serving Platforms: How They Work and When to Use Them
- 20.6 Inside an Inference Engine: How vLLM and SGLang Run a Model
- 20.7 Deploying LLMs on Kubernetes: GPUs, Replicas, and Rollouts
- 20.7.1 Capacity and GPU nodes
- 20.7.2 Weight staging and deployment
- 20.7.3 Rollouts, autoscaling, and routing
- 20.7.4 Disaggregated pools and failover
- 20.7.5 Adapter fleets and operations
- 20.8 From Training Run to Shared Model: Packaging, Publishing, and Use Cases
- 20.9 Architecture choices and performance limits
- 20.10 Runtime controls and inference flags
- 20.11 Serving layouts: one process, replicas, and distributed pools
- 20.12 Performance experiments and correctness gates
- 20.13 Batch invariance and numerical reproducibility
- 20.14 Local training, serving, and validation lab
- 21.1 Sampling and logit processors
- 21.2 The KV cache, incremental decoding, and generate
- 21.3 A paged KV cache in Python
- 21.4 A radix prefix cache
- 21.5 Quantization: int8, int4 groups, fp8, and the KV cache
- 21.6 Speculative decoding: n-gram, prompt-lookup, and model drafts
- 21.7 Constrained decoding: from regex to token masks
- 21.8 A paged KV block pool in C
- 22.1 C runtime support and an arena allocator with marks
- 22.2 Thread pool and tl_parallel_for
- 22.3 Cache-blocked, packed, batch-invariant matmul in C
- 22.4 Softmax in C: three-pass and online two-pass
- 22.5 FlashAttention forward in C
- 22.6 Paged attention for decode in C
- 22.7 Fused int4 and int8 dequantize-matmul in C
- 22.8 Elementwise kernels in C: RMSNorm, RoPE, SiLU-mul, embedding, add, argmax
- 23.1 Your first endpoint: a std-only Rust HTTP/1.1 + SSE server
- 23.2 Candle model runner (Llama + bigram, int4), Rust KV cache, sampler and PCG32
- 23.3 Continuous batching scheduler with priority and preemption
- 23.4 Chunked prefill (mixed prefill + decode batches)
- 23.5 Block manager with prefix cache (none, hash, radix)
- 23.6 tl-serve: OpenAI-compatible HTTP + SSE on tokio/hyper
- 23.7 Disaggregated prefill and decode
- 23.8 Serving metrics and tracing
- 23.9 Speculative decoding in the engine
- 23.10 Tool calls and constrained decoding
- 23.11 An open-loop load generator
- 23.12 Run comparison and the regression gate
- 23.13 Inference stack: from tokens to an interface
Applications and evaluation
Section titled “Applications and evaluation”Responsible deployment
Section titled “Responsible deployment”Appendices
Section titled “Appendices”- B.1 The course path
- B.2 Pass 0: Setup
- B.2.1 What the System Does After Pass 0
- B.3 Pass 1: The Tracer
- B.3.1 What the System Does After Pass 1
- B.4 Pass 2: Foundations
- B.4.1 What the System Does After Pass 2
- B.5 Pass 3: Tokens and Data
- B.5.1 What the System Does After Pass 3
- B.6 Pass 4: Sequence Models
- B.6.1 What the System Does After Pass 4
- B.7 Pass 5: The Transformer
- B.7.1 What the System Does After Pass 5
- B.8 Pass 6: Inference and Kernels
- B.8.1 What the System Does After Pass 6
- B.9 Pass 7: The Serving Platform
- B.9.1 What the System Does After Pass 7
- B.10 Pass 8: Durable Execution
- B.10.1 What the System Does After Pass 8
- B.11 Pass 9: Capstone Training
- B.11.1 What the System Does After Pass 9
- B.12 Pass 10: Agents
- B.12.1 What the System Does After Pass 10
- B.13 Pass 11: Operating the System
- B.13.1 What the System Does After Pass 11
- B.14 Pass 12: Multimodal
- B.14.1 What the System Does After Pass 12
- B.15 Learning foundations
- B.16 Model construction
- B.17 Production AI
- B.18 Responsible deployment
What you will be able to do
Section titled “What you will be able to do”- Derive a model or learning objective from its assumptions and check it on a small example.
- Build and explain autograd, tokenizers, language models, attention, and an inference engine.
- Choose training, adaptation, routing, and serving strategies using measured constraints.
- Build retrieval and agent applications with explicit evaluation and failure tests.
- Validate data rights, privacy, safety, and deployment policies alongside model behavior.
Ways through this book
Section titled “Ways through this book”Read the parts in order for the full progression, or choose a route below and follow its prerequisites. Pause at the review questions before revealing worked answers.
- Understanding learning: Statistical Learning, then Deep Learning, then Reinforcement Learning.
- Building and training a model: Numerics and Autograd, then Tokenizers, then The Modern Decoder Block. Follow the training-to-inference route for learning methods, PPO/GRPO, distillation, local serving, batch invariance, and scale.
- Shipping AI applications: Inference Engines and GPU Deployment, then Retrieval and RAG, then Agent SDK, then LLM Evaluation.
- Responsible deployment: Data Licensing, then Privacy and PII, then Bias and Safety Evaluations.
Before you start
Section titled “Before you start”The mathematical prerequisites are in Mathematics, and the programming background is in Programming and Algorithms. Data Engineering owns ingestion, corpus pipelines, and data quality. Systems Engineering owns shared protocols, caching, durable execution, Kubernetes, and observability. Software Engineering owns testing, authorization, design practices, and documentation. Follow those links when a chapter needs a shared mechanism; the AI-specific behavior stays here.
How to read these books explains the shared first-principles, prediction, reasoning, testing, and validation method.