Dive into Deep Learning
  • Slides
  • Courses
  • GitHub
  • Discuss
  • PDF
    • PyTorch
    • JAX
    • TensorFlow
    • MXNet

    • Parts (PyTorch)
    • Basics
    • Advanced
    • Language Models
    • Mathematics for Deep Learning
  • Notebooks
    • PyTorch
    • JAX
    • TensorFlow
    • MXNet
    • en · English
    • zh · 中文
    • pt · Português
    • tr · Türkçe
    • vi · Tiếng Việt
    • ko · 한국어
    • ja · 日本語

    • en · English (old)
  1. index.html
  • index.html
  • Preface
    • Installation
    • Notation
    • Introduction
  • Basics
    • 1  Preliminaries
    • 1.1  Data Manipulation
    • 1.2  Data Preprocessing
    • 1.3  Linear Algebra
    • 1.4  Calculus
    • 1.5  Automatic Differentiation
    • 1.6  Probability and Statistics
    • 2  Linear Regression
    • 2.1  Linear Regression
    • 2.2  Synthetic Data
    • 2.3  Linear Regression Implementation from Scratch
    • 2.4  Object-Oriented Design for Implementation
    • 2.5  Concise Implementation of Linear Regression
    • 2.6  Generalization
    • 2.7  Weight Decay
    • 3  Linear Classification
    • 3.1  Softmax Regression
    • 3.2  Image Classification Data
    • 3.3  Softmax Regression Implementation
    • 3.4  Measuring Classifiers
    • 3.5  Generalization in Classification
    • 3.6  Environment and Distribution Shift
    • 4  Multilayer Perceptrons
    • 4.1  Multilayer Perceptrons
    • 4.2  Implementation
    • 4.3  Backpropagation
    • 4.4  Numerical Stability and Initialization
    • 4.5  Generalization in Deep Learning
    • 4.6  Dropout
    • 4.7  Predicting House Prices on Kaggle
    • 5  Computation
    • 5.1  Modules and Model Construction
    • 5.2  Parameters, State, and Memory
    • 5.3  Initialization
    • 5.4  Custom Layers and Functions
    • 5.5  Numerical Formats
    • 5.6  Saving, Loading, and Pretrained Weights
    • 5.7  GPUs, Devices, and Memory
    • 5.8  Reproducibility and Inspection
    • 6  Convolutional Neural Networks
    • 6.1  From Fully Connected Layers to Convolutions
    • 6.2  Convolutions for Images
    • 6.3  Padding, Stride, and Dilation
    • 6.4  Multiple Input and Multiple Output Channels
    • 6.5  Pooling
    • 6.6  LeNet
    • 7  Modern Convolutional Neural Networks
    • 7.1  AlexNet and Learned Image Representations
    • 7.2  Blocks, Bottlenecks, and Branches: VGG, NiN, GoogLeNet
    • 7.3  Normalization Layers
    • 7.4  Residual Networks
    • 7.5  Efficient Convnets
    • 7.6  Modern Training Recipes for Convnets
    • 7.7  ConvNeXt: Modernizing a ResNet Step by Step
    • 7.8  Convolutional Network Design Spaces
    • 8  Sequence Models
    • 8.1  Working with Sequences
    • 8.2  From Text to Tokens
    • 8.3  Language Models
    • 8.4  Recurrent Neural Networks
    • 8.5  Backpropagation Through Time
    • 8.6  Decoding and Generation
  • Advanced
    • 9  Optimization Algorithms
    • 9.1  Landscapes and Gradient Descent
    • 9.2  Stochastic and Minibatch Gradient Descent
    • 9.3  Two Test Models
    • 9.4  Momentum
    • 9.5  Adam and AdamW
    • 9.6  Muon
    • 9.7  Schedules
    • 9.8  Batch Size
    • 9.9  Scaling Up
    • 9.10  Practice
    • 9.11  Further Reading
    • 10  Attention
    • 10.1  Queries, Keys, and Values
    • 10.2  Attention Scoring and Masking
    • 10.3  Self-Attention and Multiple Heads
    • 10.4  Positional Information
    • 10.5  The Cost of Attention
    • 10.6  Windowed and Linear Attention
    • 10.7  Attention Circuits
    • 10.8  Further Reading
    • 11  Transformers
    • 11.1  The Transformer Block
    • 11.2  Decoder-Only Language Models (GPT)
    • 11.3  The KV Cache and Cache Reduction
    • 11.4  Encoders, Decoders, and Cross-Attention
    • 11.5  Vision Transformer (ViT)
    • 11.6  Scaling Laws
    • 11.7  Mixture of Experts (MoE)
    • 11.8  Further Reading
    • 12  State Space Models
    • 12.1  Gated Recurrent Networks
    • 12.2  Sequence-to-Sequence Learning
    • 12.3  Linear Recurrences and Parallel Scans
    • 12.4  State Space Models
    • 12.5  Selective State Space Models
    • 12.6  Matrix-State Recurrences
    • 12.7  The Delta Rule
    • 12.8  Hybrid Architectures
    • 12.9  Further Reading
    • 13  Computational Performance
    • 13.1  The Performance Model
    • 13.2  Hardware
    • 13.3  Computation Graphs and Compilation
    • 13.4  Memory and Precision
    • 13.5  Multi-GPU from First Principles
    • 13.6  Data Parallelism in Practice
    • 13.7  Sharding the Training State
    • 13.8  Case Study: Optimizing a Transformer
    • 13.9  Further Reading
    • 14  Reinforcement Learning
    • 14.1  Markov Decision Processes
    • 14.2  Dynamic Programming
    • 14.3  Temporal-Difference Learning
    • 14.4  Exploration
    • 14.5  Learning from Demonstrations
    • 14.6  Optimal Control, LQR, and Model Predictive Control
    • 14.7  Policy Gradient
    • 14.8  Baselines and Variance Reduction
    • 14.9  Function Approximation in Reinforcement Learning
    • 15  Deep Reinforcement Learning
    • 15.1  Actor-Critic Methods and Multi-Step Returns
    • 15.2  Trust Regions and Proximal Policy Optimization
    • 15.3  KL-Regularized Policy Optimization
    • 15.4  Deep Q-Networks
    • 15.5  Soft Actor-Critic
    • 15.6  Learned Models and Planning
    • 15.7  Offline Reinforcement Learning
    • 15.8  Reinforcement Learning for Sequence Generation
    • 15.9  Further Reading
    • 16  Generative Adversarial Networks
    • 16.1  Generative Adversarial Networks
    • 16.2  Adversarial Objectives and Divergences
    • 16.3  Relativistic Objectives
    • 16.4  Gradient Penalties and Convergence
    • 16.5  Adversarial Image Generation
    • 16.6  Conditional Generation
    • 16.7  Adversarial Losses Beyond GANs
    • 16.8  Further Reading
    • 17  Diffusion Models
    • 17.1  Denoising and the Score
    • 17.2  Gaussian Paths: Diffusion and Flow Matching
    • 17.3  Sampling by Integration
    • 17.4  Diffusion for Images
    • 17.5  Samplers, Inversion and Editing
    • 17.6  Likelihood, Weighting and the Design Space
    • 17.7  Latent Diffusion and Transformers
    • 17.8  Few-Step Generation
    • 17.9  Discrete Diffusion
    • 17.10  Further Reading
  • Language Models
    • 18  Working with Pretrained Language Models
    • 18.1  Pretrained Models with Hugging Face
    • 18.2  A Released Checkpoint in the Book’s Own Code
    • 18.3  Prompting and In-Context Learning
    • 18.4  Scoring Language Models
    • 18.5  Evaluation Suites, Judges and Error Bars
    • 18.6  Interpretability
    • 18.7  Models behind an API
    • 19  Encoders, Embeddings and Retrieval
    • 19.1  Word Embeddings
    • 19.2  Pretrained Encoders
    • 19.3  Text Embeddings from Contrastive Training
    • 19.4  Sparse, Dense and Approximate Retrieval
    • 19.5  Retrieval-Augmented Generation
    • 19.6  Failures and Fixes in Retrieval-Augmented Generation
    • 19.7  Further Reading
    • 20  Data for Language Models
    • 20.1  Document Extraction from Web Crawls
    • 20.2  Quality Filtering
    • 20.3  Deduplication and Decontamination
    • 20.4  Data Mixtures
    • 20.5  Synthetic and Rephrased Data
    • 20.6  Tokenizers at Scale
    • 21  Pretraining
    • 21.1  The Pretraining Data Path
    • 21.2  The Reference Pretraining Run
    • 21.3  Low-Precision Training
    • 21.4  Continued Pretraining and Mid-Training
    • 21.5  Long-Context Training
    • 21.6  Training Budgets beyond the Compute Optimum
    • 22  Hardware for Training and Inference
    • 22.1  Accelerator Design
    • 22.2  Kernels, Tiles and Fusion
    • 22.3  Training, Prefill and Decode Workloads
    • 22.4  Memory and Storage Tiers
    • 22.5  Data Paths inside a Server
    • 22.6  Scale-Up Domains and Scale-Out Networks
    • 22.7  Collective Communication at Scale
    • 22.8  Energy, Power and Cost
    • 23  Parallelism Beyond One Node
    • 23.1  Multi-Node Jobs and Hang Diagnosis
    • 23.2  Sharded Data Parallelism at Scale
    • 23.3  Tensor and Sequence Parallelism
    • 23.4  Pipeline Parallelism
    • 23.5  Context Parallelism
    • 23.6  Expert Parallelism
    • 23.7  Composed Parallelism and Topology
    • 23.8  Profiling and Performance Debugging of Distributed Runs
    • 23.9  Checkpoints at Scale
    • 23.10  Failures, Elasticity and Goodput
    • 24  Fine-Tuning
    • 24.1  Full Fine-Tuning
    • 24.2  Supervised Instruction Tuning
    • 24.3  Instruction Data
    • 24.4  Low-Rank Adaptation
    • 24.5  Quantized Fine-Tuning
    • 24.6  Fine-Tuning at Scale and Toolchains
    • 24.7  Merging and Retaining Capabilities
    • 25  Preference Optimization and Reinforcement Learning
    • 25.1  Reward Models
    • 25.2  RLHF with PPO at Language-Model Scale
    • 25.3  Direct Preference Optimization and Its Variants
    • 25.4  RL with Verifiable Rewards
    • 25.5  RL Training Systems
    • 25.6  Reward Overoptimization
    • 25.7  Safety Evaluation and Red-Teaming
    • 25.8  Further Reading
    • 26  Distillation and Reasoning
    • 26.1  Knowledge Distillation
    • 26.2  On-Policy Distillation
    • 26.3  Training Reasoning Models
    • 26.4  Verifiers and Process Supervision
    • 26.5  Parallel Test-Time Compute
    • 26.6  Sequential and Adaptive Test-Time Compute
    • 27  Agents and Tool Use
    • 27.1  Tool Calling
    • 27.2  Structured Outputs and Constrained Decoding
    • 27.3  Agent Loops and Harnesses
    • 27.4  Training Agents with Reinforcement Learning
    • 27.5  Evaluating and Securing Agents
    • 28  Model Compression
    • 28.1  Quantization for Inference
    • 28.2  Activation Outliers and Equivalent Rescaling
    • 28.3  Reconstruction-Based Quantization
    • 28.4  Rotations and Incoherence
    • 28.5  Quantization-Aware Training and Native Low-Bit Formats
    • 28.6  Pruning and Sparsity
    • 28.7  Further Reading
    • 29  Efficient Inference
    • 29.1  A Fast Decoder on One GPU
    • 29.2  Decode Attention Kernels
    • 29.3  Deterministic and Batch-Invariant Inference
    • 29.4  Speculative Decoding
    • 29.5  Drafters and Multi-Token Prediction
    • 29.6  KV-Cache Quantization
    • 29.7  KV-Cache Eviction and Selective Reading
    • 29.8  Inference on CPUs and Devices
    • 30  Serving Systems
    • 30.1  Workloads and Service Objectives
    • 30.2  Continuous Batching and Chunked Prefill
    • 30.3  Paged KV Memory
    • 30.4  Prefix Caching and Shared-Prefix Workloads
    • 30.5  Scheduling under Overload
    • 30.6  KV-Cache Offload, Stores and Prefix-Aware Routing
    • 30.7  Tensor and Expert Parallelism for Serving
    • 30.8  Prefill and Decode Disaggregation
    • 30.9  Serving Many Adapters
    • 31  Advanced Architectures
    • 31.1  Architecture Configurations
    • 31.2  Mixture-of-Experts Design at Scale
    • 31.3  Latent Attention and Cross-Layer KV Sharing
    • 31.4  Softmax Attention Refinements
    • 31.5  Learned Sparse Attention
    • 31.6  Hybrid Models at Scale
    • 31.7  The Residual Stream across Depth
    • 31.8  Further Reading
  • Image Models
    • 32  Computer Vision
    • 32.1  Image Augmentation
    • 32.2  Fine-Tuning
    • 32.3  Object Detection and Bounding Boxes
    • 32.4  Anchor Boxes
    • 32.5  Multiscale Object Detection
    • 32.6  The Object Detection Dataset
    • 32.7  Single Shot Multibox Detection
    • 32.8  Region-based CNNs (R-CNNs)
    • 32.9  Semantic Segmentation and the Dataset
    • 32.10  Transposed Convolution
    • 32.11  Fully Convolutional Networks
    • 32.12  Neural Style Transfer
    • 32.13  Image Classification (CIFAR-10) on Kaggle
    • 32.14  Dog Breed Identification (ImageNet Dogs) on Kaggle
  • Mathematics for Deep Learning
    • 33  Linear Algebra
    • 33.1  Vectors, Angles, and Projections
    • 33.2  Matrices as Linear Maps
    • 33.3  Eigendecompositions
    • 33.4  Spectra in Practice
    • 33.5  Singular Value Decomposition and Low-Rank Approximation
    • 33.6  Further Reading
    • 34  Calculus and Automatic Differentiation
    • 34.1  Single Variable Calculus
    • 34.2  Multivariable Calculus
    • 34.3  The Chain Rule on Computational Graphs
    • 34.4  Matrix Calculus
    • 34.5  Automatic Differentiation
    • 34.6  Integral Calculus
    • 34.7  Expectations and Their Gradients
    • 34.8  Further Reading
    • 35  Optimization
    • 35.1  Gradient Descent and Curvature
    • 35.2  Curvature Methods: Newton, Quasi-Newton, and Trust Regions
    • 35.3  Convexity
    • 35.4  Stochastic Gradient Methods
    • 35.5  Adaptive Methods
    • 35.6  Constrained Optimization
    • 35.7  Duality
    • 35.8  Numerical Stability and Conditioning
    • 35.9  Further Reading
    • 36  Probability and Statistical Learning
    • 36.1  Random Variables
    • 36.2  Joint Distributions and Transformations
    • 36.3  Distributions
    • 36.4  The Exponential Family
    • 36.5  Statistics
    • 36.6  Maximum Likelihood
    • 36.7  Latent Variables, EM, and the ELBO
    • 36.8  Bayesian Computation
    • 36.9  Concentration Inequalities
    • 36.10  Uniform Convergence and Generalization
    • 36.11  Naive Bayes
    • 36.12  Further Reading
    • 37  Information Theory and Divergences
    • 37.1  Entropy, Cross-Entropy, and KL Divergence
    • 37.2  Codes, Compression, and Perplexity
    • 37.3  f-Divergences
    • 37.4  Test Functions and Transport
    • 37.5  Score-Based Comparisons
    • 37.6  Mutual Information
    • 37.7  Estimating Mutual Information
    • 37.8  Further Reading
    • 38  Dynamics: Differential Equations and Generative Flows
    • 38.1  Ordinary Differential Equations
    • 38.2  Numerical Solvers
    • 38.3  Neural ODEs, Adjoints, and Continuous Flows
    • 38.4  Stochastic Differential Equations
    • 38.5  The Fokker–Planck Equation and Probability Flow
    • 38.6  Score Matching and Diffusion Models
    • 38.7  Flow Matching and Optimal Transport
    • 38.8  Further Reading
  • Tools for Deep Learning
    • 39  Tools for Deep Learning
    • 39.1  Notebooks
    • 39.2  Colab and Kaggle
    • 39.3  Cloud Computing
    • 39.4  Hardware
    • 39.5  Ecosystem
    • 39.6  Distributed Model Training
    • 39.7  Model Serving
    • 39.8  Contributor Guide
    • 39.9  Utility Functions and Classes
    • 39.10  The d2l API Reference
  • Attic
    • 40  Gaussian Processes
    • 40.1  Introduction to Gaussian Processes
    • 40.2  Gaussian Process Priors
    • 40.3  Gaussian Process Inference
    • 41  Hyperparameter Optimization
    • 41.1  What Is Hyperparameter Optimization?
    • 41.2  Hyperparameter Optimization API
    • 41.3  Asynchronous Random Search
    • 41.4  Multi-Fidelity Hyperparameter Optimization
    • 41.5  Asynchronous Successive Halving
    • 42  Recommender Systems
    • 42.1  Overview of Recommender Systems
    • 42.2  The MovieLens Dataset
    • 42.3  Matrix Factorization
    • 42.4  AutoRec: Rating Prediction with Autoencoders
    • 42.5  Personalized Ranking for Recommender Systems
    • 42.6  Neural Collaborative Filtering for Personalized Ranking
    • 42.7  Sequence-Aware Recommender Systems
    • 42.8  Feature-Rich Recommender Systems
    • 42.9  Factorization Machines
    • 42.10  Deep Factorization Machines
  • References

Dive into Deep Learning

Alexander J. Smola

2026-11-25

Dive into Deep Learning

Version 2026.11.25

Master the theory, design, and engineering of deep learning by building it from scratch. Each section weaves together intuition, mathematics, working code, and applications—and doubles as an interactive notebook you can run, modify, and experiment with directly.

By Alexander J. Smola. First edition by Aston Zhang, Zachary C. Lipton, Mu Li, and Alexander J. Smola (Cambridge University Press, 2023).

Read freely online, download the PDFs, or run the notebooks directly. Choose your framework: Basics and the math appendix support PyTorch, JAX, TensorFlow, and MXNet; Advanced supports PyTorch and JAX; and Language Models will focus on PyTorch.

Start with the Introduction →

Dive into Deep Learning, second edition, book cover
Download the complete book as a single PDF (PyTorch, 75 MB)

Start with the part you need

Cover of Basics, PDF

Basics

Chapters 1–8 · PyTorch, JAX, TensorFlow, MXNet

Begin here if you are new to deep learning. Starting from tensors and automatic differentiation, you will build linear models, multilayer perceptrons, convolutional networks, and sequence models from the ground up.

By the end, you will be able to train, debug, and evaluate neural networks on images and text, with a solid grasp of core techniques such as dropout and batch normalization.

Read online · Download the PDF

Cover of Advanced, PDF

Advanced

Chapters 9–17 · PyTorch, JAX

Continue here once you are comfortable training neural networks. You will cover modern optimization (all the way to Muon), attention and Transformers, state space models (from Mamba to hybrid architectures), GPU performance and distributed training, reinforcement learning, GANs, and diffusion models.

By the end, you will be able to build and train a Transformer, diagnose performance bottlenecks on single or multiple GPUs, and train both RL agents and modern generative models.

Read online · Download the PDF

Cover of Language Models, PDF

Language Models In preparation

Chapters 18–31 · PyTorch

Follow the full lifecycle of building a state-of-the-art large language model—from data curation and pretraining to post-training, systems, and serving.

Currently published as chapter outlines—full chapters coming soon.

Read the outline · Download the PDF

Cover of Mathematics for Deep Learning, PDF

Mathematics for Deep Learning

Chapters 33–38 · PyTorch, JAX, TensorFlow, MXNet

Use it as a quick reference or work through all six chapters: linear algebra, calculus, optimization, probability and statistical learning, information theory, and dynamics.

By the end, you will be able to follow every derivation in the main text and read research papers that take this background for granted.

Read online · Download the PDF

Two additional sections are still in transition. Image Models (Chapter 32, carried over from the first edition’s computer vision chapter) is slated for a full rewrite and expansion. Meanwhile, the Attic (Chapters 40–44: Gaussian processes, hyperparameter optimization, and recommender systems) preserves first-edition chapters that have not yet been updated for the second edition.

Try a section now

Below is a short example from the softmax regression chapter: the model definition and the four lines that train it on Fashion-MNIST for ten epochs, alongside the resulting training and validation curves (reaching ~83% validation accuracy). Switch frameworks using the tabs—the site will remember your preference—or open the notebook in Colab to run and modify it yourself.

  • PyTorch
  • TensorFlow
  • JAX
  • MXNet
class SoftmaxRegression(d2l.Classifier):
    """The softmax regression model."""
    def __init__(self, num_outputs, lr):
        super().__init__()
        self.save_hyperparameters()
        self.net = nn.Sequential(nn.Flatten(),
                                 nn.LazyLinear(num_outputs))

    def weight_init(self, module):
        # The Trainer calls this after the lazy layer has learned its shape
        if isinstance(module, nn.Linear):
            nn.init.normal_(module.weight, std=0.01)
            nn.init.zeros_(module.bias)

    def forward(self, X):
        return self.net(X)
data = d2l.FashionMNIST(batch_size=256)
model = SoftmaxRegression(num_outputs=10, lr=0.1)
trainer = d2l.Trainer(max_epochs=10)
trainer.fit(model, data)
Training loss, validation loss and validation accuracy per epoch (PyTorch)
Training loss, validation loss, and validation accuracy over ten epochs (PyTorch). Read this section · Open in Colab
class SoftmaxRegression(d2l.Classifier):
    """The softmax regression model."""
    def __init__(self, num_outputs, lr):
        super().__init__()
        self.save_hyperparameters()
        self.net = tf.keras.models.Sequential()
        self.net.add(tf.keras.layers.Flatten())
        self.net.add(tf.keras.layers.Dense(
            num_outputs,
            kernel_initializer=tf.initializers.RandomNormal(stddev=0.01)))

    def forward(self, X):
        return self.net(X)
data = d2l.FashionMNIST(batch_size=256)
model = SoftmaxRegression(num_outputs=10, lr=0.1)
trainer = d2l.Trainer(max_epochs=10)
trainer.fit(model, data)
Training loss, validation loss and validation accuracy per epoch (TensorFlow)
Training loss, validation loss, and validation accuracy over ten epochs (TensorFlow). Read this section · Open in Colab
class SoftmaxRegression(d2l.Classifier):
    """The softmax regression model."""
    def __init__(self, num_outputs, lr, num_inputs=784, rngs=None):
        super().__init__()
        self.save_hyperparameters(ignore=['rngs'])
        rngs = nnx.Rngs(d2l.get_key()) if rngs is None else rngs
        self.net = nnx.Linear(num_inputs, num_outputs,
                              kernel_init=nnx.initializers.normal(0.01),
                              rngs=rngs)

    def forward(self, X):
        X = X.reshape((X.shape[0], -1))  # Flatten
        return self.net(X)
data = d2l.FashionMNIST(batch_size=256)
model = SoftmaxRegression(num_outputs=10, lr=0.1)
trainer = d2l.Trainer(max_epochs=10)
trainer.fit(model, data)
Training loss, validation loss and validation accuracy per epoch (JAX)
Training loss, validation loss, and validation accuracy over ten epochs (JAX). Read this section · Open in Colab
class SoftmaxRegression(d2l.Classifier):
    """The softmax regression model."""
    def __init__(self, num_outputs, lr):
        super().__init__()
        self.save_hyperparameters()
        self.net = nn.Dense(num_outputs)
        self.net.initialize(init.Normal(sigma=0.01))

    def forward(self, X):
        return self.net(X)
data = d2l.FashionMNIST(batch_size=256)
model = SoftmaxRegression(num_outputs=10, lr=0.1)
trainer = d2l.Trainer(max_epochs=10)
trainer.fit(model, data)
Training loss, validation loss and validation accuracy per epoch (MXNet)
Training loss, validation loss, and validation accuracy over ten epochs (MXNet). Read this section · Open in Colab

Every figure and result in the book comes from its runnable notebooks (221 in PyTorch, 115 in TensorFlow, 188 in JAX, and 121 in MXNet).

What you get with the book

Run every notebook

Launch any section in Colab or Kaggle—or download it as a Jupyter notebook—using the links at the top of the page. See how to run the notebooks.

Or download them all in one zip: PyTorch · JAX · TensorFlow · MXNet

Present from the slides

Every section of Basics, Advanced, and the math appendix comes with a matching slide deck containing the exact same code and outputs as the book. Browse all slide decks and feel free to adapt them for your own courses.

Practice what you learned

Every section closes with a range of exercises, from checking mathematical derivations to extending the code with hands-on experiments. Try the exercises from the softmax regression section above.

Ask in the forum

Stuck on a concept or exercise? Every section links at the bottom to its dedicated Discourse thread, where you can ask questions, compare solutions, or report an error.

Check the math

Whenever the main text references a proof or deeper derivation, you can find the full treatment across the six chapters of Mathematics for Deep Learning.

Choose your framework

Basics and the math appendix are available in PyTorch, JAX, TensorFlow, and MXNet. Advanced is implemented in PyTorch and JAX—the two primary frameworks for modern deep learning research—and Language Models will focus on PyTorch, the standard ecosystem for sharing pretrained models (such as on Hugging Face). Pick a framework tab once, and the rest of the book follows automatically.

What’s new in the second edition

New or rebuilt

  • Modular multi-part structure: Now spanning over 3,000 pages, the book is organized into self-contained parts so you can jump straight to what you need—with Basics designed as a standalone companion for an introductory course.
  • Substantially new Advanced part: Brings you close to the current frontier across optimization, Transformers, state space models, reinforcement learning, GANs, and diffusion models.
  • Expanded math appendix: More than doubled in length, adding deeper coverage of optimization, information theory, and the continuous-time dynamics underlying diffusion and flow models.
  • Up-to-date, verified code: Every notebook runs on current framework releases, and every framework supported in a chapter is verified to reach comparable results on the same benchmark.
  • Community-driven polish: Pending GitHub issues, pull requests, and forum bug reports have been resolved, and code, prose, experiments, and equations have been audited end to end for consistency.

Still in progress

  • Language Models: Planned and outlined, with full chapters still to be written. You can read the outline today—feedback is warmly welcome.
  • Image Models: Currently retains the first edition’s computer vision chapter; like Language Models, it awaits a full rewrite expanding into modern vision and graphics.
  • Topics outside our current scope: We do not yet cover other modalities such as audio and speech. A thorough treatment of agents likely warrants a part of its own (though some material will appear in Language Models), and rich areas such as graph and geometric deep learning, semi-supervised learning, and interpretability remain uncovered. Inevitably, the field moves faster than any single book can fully keep pace with.

Read the preface to the second edition

Teach with the book

Build an introductory deep learning course around Basics, or pair it with Mathematics for Deep Learning as a companion math text. All slides, notebooks, exercises, and forum resources are free for classroom use. The text is licensed under CC BY-SA 4.0 (LICENSE), and the sample and reference code under a modified MIT license (LICENSE-SAMPLECODE).

500+ universities in 70+ countries have taught with Dive into Deep Learning. Browse their courses below.

World map with a dot for each university that has taught with the book
Universities that have taught with the book (as of November 2026).

Featuring 406 universities across 65 countries with linked course pages using the book:

Università degli Studi di Bologna Hong Kong University of Science and Technology University of Michigan Australian National University National University of Sciences and Technology University of Illinois Urbana Champaign Brown University Carnegie Mellon University Chennai Mathematical Institute Chinese University of Hong Kong Chinese University of Hong Kong Shenzhen Cornell University EPFL Escuela Superior Politecnica del Litoral Hong Kong Baptist University Indian Institute of Technology Bombay Indian Institute of Technology Delhi Indian Institute of Technology Gandhinagar Indian Institute of Technology Guwahati Indian Institute of Technology Kanpur Indian Institute of Technology Madras Indian Institute of Technology Patna London School of Economics and Political Science McGill University Monash University National Institute of Technology Delhi National Taiwan University National University of Singapore Norwegian University of Science and Technology Pohang University of Science and Technology Pontificia Universidad Catolica de Chile Princeton University Purdue University Rensselaer Polytechnic Institute San Jose State University Singapore University of Technology and Design Stevens Institute of Technology Technion   Israel Institute of Technology Texas A&M University Universidad San Francisco de Quito Universidade de Coimbra University of Cagliari University of California, Berkeley University of Cambridge University of Florida University of Klagenfurt University of Liege University of Maryland University of Minnesota, Twin Cities University of North Carolina at Chapel Hill University of North Texas University of Pennsylvania University of Southern Maine University of Toronto University of Washington University of Wisconsin–Madison Università degli Studi di Milano-Bicocca VIT (Vellore Institute of Technology), Vellore Yonsei University Abasyn University Islamabad Campus AGH University of Krakow Ain Shams University Alexandria University Amity University Amrita Vishwa Vidyapeetham Andhra University Anna University Ateneo de Naga University Australian Catholic University Autonomous University of Barcelona Bar Ilan University Barnard College Beijing Institute of Mathematical Sciences and Applications Beykoz University Birla Institute of Technology and Science Pilani BML Munjal University Boston College Boston University Brac University Brandeis University Budapest University of Technology and Economics Bursa Uludag University Cairo University Cankaya University Carnegie Mellon University Africa Charles University China Ocean University Chongqing University of Science and Technology Christ University Bengaluru Chulalongkorn University CINVESTAV City University of Hong Kong Cochin University of Science and Technology College of Engineering Pune Colorado State University Columbia University
All 474 universities, by country

Algeria 1

Ecole Nationale Superieure dInformatique

Argentina 4

Instituto Tecnologico de Buenos Aires Universidad de Buenos Aires Universidad Nacional de Tierra del Fuego Universidad Tecnológica Nacional

Australia 12

Australian Catholic University Australian National University Deakin University Monash University Murdoch University University of Canberra University of Melbourne University of New South Wales University of Newcastle University of South Australia University of Sydney University of Technology Sydney

Austria 2

St. Polten University of Applied Sciences University of Klagenfurt

Bangladesh 3

Brac University Leading University United International University

Belgium 2

KU Leuven University of Liege

Brazil 16

Pontificia Universidade Catolica do Rio de Janeiro Universidade Catolica de Brasilia Universidade Estadual de Campinas Universidade Federal de Goiás Universidade Federal de Minas Gerais Universidade Federal de Ouro Preto Universidade Federal de Pernambuco Universidade Federal de Santa Catarina Universidade Federal de São Carlos Universidade Federal de Viçosa Universidade Federal do Pampa Universidade Federal do Rio de Janeiro Universidade Federal do Rio Grande Universidade Presbiteriana Mackenzie Universidade Tecnológica Federal do Paraná University of Sao Paulo

Canada 9

Concordia University McGill University Ontario Tech University Queen's University Simon Fraser University University of British Columbia University of Toronto University of Waterloo Western University

Chile 2

Pontificia Universidad Catolica de Chile Universidad de Chile

China 34

Beijing Institute of Mathematical Sciences and Applications China Ocean University Chinese University of Hong Kong Shenzhen Chongqing University of Science and Technology Dalian University of Technology East China Normal University Fudan University Guangdong University of Technology Hangzhou Dianzi University Harbin Institute of Technology Heilongjiang University of Science and Technology Huazhong University of Science and Technology Liuzhou Institute of Technology Nanchang Hangkong University Nanjing Normal University Zhongbei College Nanjing University Nanjing University of Finance and Economics Peking University Sanya University Shandong University Shanghai Jiao Tong University Shanghai University of Electric Power Shanghai University of Finance and Economics ShanghaiTech University Shenzhen University Tsinghua University University of Chinese Academy of Sciences University of International Business and Economics University of Science and Technology of China Xi'an Jiaotong Liverpool University Xiamen University Yunnan University Zhejiang University Zhengzhou Tourism College

Colombia 7

Universidad de Ibagué Universidad de los Andes Universidad del Norte Universidad Icesi Universidad Militar Nueva Granada Universidad Nacional de Colombia Sede Manizales Universidad Tecnologica de Pereira

Cyprus 2

Cyprus Institute Eastern Mediterranean University

Czech Republic 2

Charles University Masaryk University

Denmark 2

IT Universitetet i Kobenhavn University of Copenhagen

Ecuador 4

Escuela Politecnica Nacional Escuela Superior Politecnica del Litoral Universidad Politécnica Salesiana, Cuenca Universidad San Francisco de Quito

Egypt 5

Ain Shams University Alexandria University Cairo University Menoufia University Minia University

Finland 1

University of Jyväskylä

France 8

IMT Mines Ales Institut catholique d'arts et metiers (ICAM) Institut de recherche en informatique de Toulouse Institut Superieur De L'electronique Et Du Numerique Universite Cote dAzur Universite de technologie de Compiegne Universite Paris Saclay Université Grenoble Alpes

Germany 18

Free University of Berlin Hasso Plattner Institut Heinrich Heine Universitat Dusseldorf Hertie School Hochschule Bremen Hochschule fur Technik und Wirtschaft Humboldt University of Berlin Leibniz Universitat Hannover Leuphana University of Luneburg LMU Munich Technical University of Darmstadt Technical University of Munich Technische Universitat Berlin Universitat Heidelberg Universitat Tubingen University of Augsburg University of Bamberg University of Hamburg

Ghana 1

University of Ghana

Greece 3

Harokopio University National Technical University of Athens University of Patras

Guatemala 1

Universidad Rafael Landívar

Hong Kong 5

Chinese University of Hong Kong City University of Hong Kong Hong Kong Baptist University Hong Kong Polytechnic University Hong Kong University of Science and Technology

Hungary 3

Budapest University of Technology and Economics Eötvös Loránd University (ELTE), Budapest University of Szeged

Iceland 1

University of Iceland

India 58

Amity University Amrita Vishwa Vidyapeetham Andhra University Anna University Birla Institute of Technology and Science Pilani BML Munjal University Chennai Mathematical Institute Christ University Bengaluru Cochin University of Science and Technology College of Engineering Pune Dayananda Sagar University Gayatri Vidya Parishad College of Engineering (Autonomous) Goa University Great Lakes Institute of Management Indian Institute of Information Technology Lucknow Indian Institute of Information Technology Una Indian Institute of Science Bangalore Indian Institute of Technology Bombay Indian Institute of Technology Delhi Indian Institute of Technology Gandhinagar Indian Institute of Technology Guwahati Indian Institute of Technology Hyderabad Indian Institute of Technology Jodhpur Indian Institute of Technology Kanpur Indian Institute of Technology Kharagpur Indian Institute of Technology Madras Indian Institute of Technology Mandi Indian Institute of Technology Patna Indian Institute of Technology Ropar Indian Institute of Technology Tirupati Indira Gandhi National Open University Indraprastha Institute of Information Technology, Delhi International Institute of Information Technology, Hyderabad Kongu Engineering College KPR Institute of Engineering and Technology Mar Baselios College of Engineering and Technology National Institute of Technical Teachers Training & Research National Institute of Technology Delhi National Institute of Technology Kurukshetra National Institute of Technology Rourkela National Institute of Technology Tiruchirappalli National Institute of Technology, Warangal Noida Institute of Engineering and Technology NRI Institute of Technology PES University Prasad V. Potluri Siddhartha Institute of Technology RV University Bengaluru Sant Longowal Institute of Engineering Technology Sardar Vallabhbhai National Institute of Technology, Surat Shiv Nadar University Shivaji University Kolhapur SRM Institute of Science and Technology Thapar Institute of Engineering and Technology Vardhaman College of Engineering Vardhman Mahaveer Open University Visvesvaraya National Institute of Technology Nagpur VIT (Vellore Institute of Technology), Vellore Xavier University Bhubaneswar

Indonesia 7

Diponegoro University Institut Teknologi Bandung Pakuan University Universitas Andalas, Padang Universitas Indonesia Universitas Negeri Yogyakarta Universitas Udayana

Iran 3

Shahid Beheshti University Sharif University of Technology University of Tehran

Iraq 2

University of Baghdad University of Mosul

Ireland 2

Trinity College Dublin University College Dublin

Israel 3

Bar Ilan University Hebrew University of Jerusalem Technion   Israel Institute of Technology

Italy 14

Politecnico di Milano Sapienza Universita di Roma Universita Bocconi Universita degli Studi di Bari Aldo Moro Universita degli Studi di Brescia Universita degli Studi di Padova University of Cagliari University of Catania University of Florence University of Milan Università degli Studi di Bologna Università degli Studi di Milano-Bicocca Università degli Studi di Pavia Università degli Studi di Roma Tor Vergata

Japan 7

Hiroshima University Keio University Nagoya University Oita University Rikkyo University Tohoku University University of Tokyo

Kazakhstan 1

Nazarbayev University

Luxembourg 1

University of Luxembourg

Malaysia 1

Multimedia University

Mexico 5

CINVESTAV Instituto Politécnico Nacional Instituto Tecnologico Autonomo de Mexico Tecnológico de Monterrey, Campus Guadalajara Universidad Nacional Autonoma de Mexico

Morocco 1

Mohammed V University in Rabat

Netherlands 6

Radboud Universiteit Technische Universiteit Delft Universiteit Leiden Universiteit van Amsterdam University of Groningen Wageningen University

Nigeria 1

Federal University Lokoja

Norway 2

Norwegian University of Science and Technology University of Oslo

Pakistan 6

Abasyn University Islamabad Campus Habib University Information Technology University Lahore Lahore University of Management Sciences National University of Sciences and Technology Quaid-i-Azam University

Peru 3

Pontificia Universidad Catolica del Peru Universidad de Ingeniería y Tecnología Universidad Nacional Agraria La Molina

Philippines 2

Ateneo de Naga University University of Northern Philippines

Poland 2

AGH University of Krakow University of Warsaw

Portugal 5

Universidade de Coimbra Universidade Lusófona Universidade NOVA de Lisboa University of Aveiro University of Lisbon

Qatar 1

Hamad Bin Khalifa University

Romania 2

Universitatea Babes Bolyai Universitatea de Vest din Timisoara

Russia 2

North Ossetian State University Skolkovo Institute of Science and Technology

Rwanda 1

Carnegie Mellon University Africa

Saudi Arabia 4

Islamic University of Medina King Abdullah University of Science and Technology King Fahd University of Petroleum and Minerals King Faisal University

Singapore 2

National University of Singapore Singapore University of Technology and Design

Slovakia 1

Univerzita Komenskeho v Bratislave

Slovenia 1

University of Ljubljana

South Africa 2

Durban University of Technology Stellenbosch University

South Korea 14

Ewha Womans University Gwangju Institute of Science and Technology Hankuk University of Foreign Studies Jeonbuk National University Korea Aerospace University Kyung Hee University Kyungpook National University Pohang University of Science and Technology Seoul National University Seoul National University of Science and Technology Sogang University Sookmyung Women's University Sungkyunkwan University Yonsei University

South Sudan 1

University of Juba

Spain 10

Autonomous University of Barcelona Autonomous University of Madrid Universidad Carlos III de Madrid Universidad de Salamanca Universidad de Zaragoza Universidad Politecnica de Madrid Universidad Rey Juan Carlos Universitat de Barcelona Universitat Politecnica de Catalunya University of Granada

Sri Lanka 1

University of Moratuwa

Sweden 4

Linköping University Lund University Stockholm University Umea University

Switzerland 2

EPFL University of Basel

Taiwan 9

Feng Chia University National Central University National Cheng Kung University National Chengchi University National Chung Hsing University National Sun Yat sen University National Taiwan University National United University Tunghai University

Thailand 1

Chulalongkorn University

Tunisia 1

Institut Superieur d'Informatique et des Techniques de Communication

Turkey 15

Beykoz University Bursa Uludag University Cankaya University Fenerbahce University Gazi Universitesi Istanbul Atlas University Istanbul Teknik Universitesi Istinye University Marmara University MEF University Middle East Technical University Sabanci University Tekirdag Namik Kemal Universitesi Van Yuzuncu Yil University Yildiz Technical University

Ukraine 1

National Technical University of Ukraine

United Kingdom 12

Heriot-Watt University Imperial College London Lancaster University London School of Economics and Political Science Newman University Queen Mary University of London University of Bristol University of Cambridge University of Edinburgh University of Hull University of Nottingham University of St Andrews

United States 99

Barnard College Boston College Boston University Brandeis University Brown University Carnegie Mellon University Colorado State University Columbia University Cornell University CUNY Graduate Center DePaul University Duke University Emory University George Mason University Georgetown University Georgia Institute of Technology Golden Gate University Harvard University Johns Hopkins University Kansas State University Kennesaw State University Make School Massachusetts Institute of Technology Michigan State University Middlebury College Milwaukee School of Engineering New Jersey Institute of Technology New York University North Carolina State University Northeastern University Northwestern University Ohio University Pennsylvania State University Pomona College Portland State University Princeton University Purdue University Rensselaer Polytechnic Institute Rowan University Rutgers, The State University of New Jersey San Jose State University Santa Clara University Southern New Hampshire University Southern Utah University Stanford University State University of New York at Binghamton Stevens Institute of Technology Stony Brook University Texas A&M University Texas Christian University Tufts University University at Buffalo University of Arkansas University of California, Berkeley University of California, Irvine University of California, Los Angeles University of California, San Diego University of California, Santa Barbara University of California, Santa Cruz University of Central Florida University of Cincinnati University of Colorado Denver University of Connecticut University of Delaware University of Florida University of Hawaii at Manoa University of Idaho University of Illinois at Chicago University of Illinois Urbana Champaign University of Kentucky University of Louisville University of Maryland University of Maryland Baltimore County University of Michigan University of Minnesota, Twin Cities University of Nebraska-Lincoln University of Nevada, Reno University of New Hampshire University of North Carolina at Chapel Hill University of North Carolina at Charlotte University of North Texas University of Oklahoma University of Pennsylvania University of Pittsburgh University of Rhode Island University of Rochester University of Southern California University of Southern Maine University of Texas at Arlington University of Texas at Austin University of Texas at Dallas University of Virginia University of Washington University of Wisconsin–Madison Virginia Commonwealth University Virginia Tech West Virginia University Yale University Yeshiva University

Vietnam 7

FPT University Hanoi University of Science and Technology Ho Chi Minh City University of Foreign Languages and Information Technology Ho Chi Minh City University of Technology Vietnam National University, Hanoi Vietnamese German University VNU-HCM University of Science

Zimbabwe 1

Harare Institute of Technology

What readers say about the first edition

Dive into Deep Learning strikes an excellent balance between hands-on learning and in-depth explanation. I’ve used it in my deep learning course and recommend it to anyone who wants to develop a thorough and practical understanding of deep learning.
Colin Raffel, Assistant Professor, UNC Chapel Hill
This is a highly welcome addition to the machine learning literature, with a focus on hands-on experience implemented via the integration of Jupyter notebooks. Students of deep learning should find this invaluable to become proficient in this field.
Bernhard Schölkopf, Director, Max Planck Institute for Intelligent Systems
This is a timely, fascinating book, providing with not only a comprehensive overview of deep learning principles but also detailed algorithms with hands-on programming code, and moreover, a state-of-the-art introduction to deep learning in computer vision and natural language processing. Dive into this book if you want to dive into deep learning!
Jiawei Han, Michael Aiken Chair Professor, University of Illinois Urbana-Champaign
In less than a decade, the AI revolution has swept from research labs to broad industries to every corner of our daily life. Dive into Deep Learning is an excellent text on deep learning and deserves attention from anyone who wants to learn why deep learning has ignited the AI revolution: the most powerful technology force of our time.
Jensen Huang, Founder and CEO, NVIDIA

Authors

Second edition: Alexander J. Smola. First edition: Aston Zhang, Zachary C. Lipton, Mu Li, and Alexander J. Smola.

Alexander J. Smola Alexander J. Smola Boson AI First and second edition
Aston Zhang Aston Zhang OpenAI First edition
Zachary C. Lipton Zachary C. Lipton CMU · Abridge First edition
Mu Li Mu Li Boson AI First edition

Chapter and code contributors

  • Rasool Fakoor ModalReinforcement learning and diffusion models
  • Brent Werness AmazonMathematics for Deep Learning
  • Rachel Hu Energent.aiMathematics for Deep Learning
  • Pratik Chaudhari University of PennsylvaniaReinforcement learning (first edition)
  • Kavosh Asadi MetaReinforcement learning (first edition)
  • Andrew Gordon Wilson NYU · PerplexityGaussian processes
  • Aaron Klein ELLIS Institute TübingenHyperparameter optimization
  • Matthias Seeger AmazonHyperparameter optimization
  • Cedric Archambeau HelsingHyperparameter optimization
  • Shuai Zhang StealthRecommender systems; the first edition’s PDF style
  • Yi Tay Google DeepMindRecommender systems
  • Anirudh Dagar AmazonPyTorch and JAX code (first edition)
  • Yuan Tang TensorScale AITensorFlow code (first edition)

The acknowledgments in the preface recognize the many readers who have improved the book through GitHub and the forum. Spotted an issue or have a suggestion? Join them by posting in the forum.

Cite the book in your work

Second edition

@book{smola2026dive,
  title   = {Dive into Deep Learning},
  author  = {Smola, Alexander J.},
  year    = {2026},
  version = {2026.11.25},
  note    = {\url{https://d2l.ai}}
}

First edition

@book{zhang2023dive,
  title     = {Dive into Deep Learning},
  author    = {Zhang, Aston and Lipton, Zachary C. and Li, Mu and Smola, Alexander J.},
  publisher = {Cambridge University Press},
  year      = {2023},
  note      = {\url{https://D2L.ai}}
}
Preface
 
Cookie Preferences