liveBook · Manning

What you will learn in Deep Learning with PyTorch, Second Edition

Training and applying deep learning and generative AI models

by Howard Huang, Eli Stevens, Luca Antiga, Thomas Viehmann

Chapter by chapter

Chapter 1: Introducing deep learning and the PyTorch library

The introduction positions PyTorch as an approachable Python library for building deep learning projects.

1.1 What is deep learning? · 1.2 The shift from machine learning to deep learning · 1.3 What to expect · 1.4 Why PyTorch? · 1.4.1 The deep learning competitive landscape · 1.5 How PyTorch supports deep learning projects · 1.6 Hardware and software requirements · 1.6.1 Using Jupyter Notebooks · 1.7 Exercises · 1.8 Summary

What you learn in chapter 1 →

Chapter 2: Pretrained networks

The introduction explains why deep learning has had a major impact on computer vision and why pretrained models are useful starting points.

2.1 A pretrained network that recognizes the subject of an image · 2.1.1 Obtaining a pretrained network for image recognition · 2.1.2 AlexNet · 2.1.3 The Vision Transformer · 2.1.4 Ready, set, almost run · 2.1.5 Run! · 2.2 Generating and editing images · 2.2.1 The inpainting process · 2.2.2 A network that turns horses into zebras · 2.3 Model Zoo: Hugging Face · 2.4 A pretrained network that describes scenes · 2.4.1 BLIP in action · 2.5 Conclusion · 2.6 Exercises · 2.7 Summary

What you learn in chapter 2 →

Chapter 3: It starts with a tensor

The introduction frames deep learning as learning transformations between data representations and explains why PyTorch begins with numeric inputs and tensors.

3.1 The world as floating-point numbers · 3.2 Tensors: Multidimensional arrays · 3.2.1 From Python lists to PyTorch tensors · 3.2.2 Constructing our first tensors · 3.2.3 The essence of tensors · 3.3 Indexing tensors · 3.4 Broadcasting · 3.5 Named tensors · 3.6 Tensor element types · 3.6.1 Specifying the numeric type with dtype · 3.6.2 A dtype for every occasion · 3.6.3 Managing a tensor’s dtype attribute · 3.7 The tensor API · 3.8 Tensors: Scenic views of storage · 3.8.1 Indexing into storage · 3.8.2 Modifying stored values: In-place operations · 3.9 Tensor metadata: Size, offset, and stride · 3.9.1 Views of another tensor’s storage · 3.9.2 Transposing without copying · 3.9.3 Transposing in higher dimensions · 3.9.4 Contiguous tensors · 3.10 Moving tensors to the GPU · 3.10.1 Managing a tensor’s device attribute · 3.11 NumPy interoperability · 3.12 Generalized tensors are tensors, too · 3.13 Serializing tensors · 3.13.1 Serializing to HDF5 with h5py · 3.14 Conclusion · 3.15 Exercises · 3.16 Summary

What you learn in chapter 3 →

Chapter 4: Real-world data representation using tensors

This introduction explains why representing real-world data as tensors matters for using PyTorch neural networks.

4.1 Working with images · 4.1.1 Adding color channels · 4.1.2 Loading an image file · 4.1.3 Changing the layout · 4.1.4 Normalizing the data · 4.2 3D images: Volumetric data · 4.2.1 Loading a specialized format · 4.3 Representing tabular data · 4.3.1 Using a real-world dataset · 4.3.2 Loading a wine data tensor · 4.3.3 Representing scores · 4.3.4 One-hot encoding · 4.3.5 When to categorize · 4.3.6 Finding thresholds · 4.4 Working with time series · 4.4.1 Adding a time dimension · 4.4.2 Shaping the data by time period · 4.4.3 Ready for training · 4.5 Representing text · 4.5.1 Converting text to numbers · 4.5.2 One-hot-encoding characters · 4.5.3 One-hot encoding whole words · 4.5.4 Text embeddings · 4.5.5 Text embeddings as a blueprint · 4.6 Conclusion · 4.7 Exercises · 4.8 Summary

What you learn in chapter 4 →

Chapter 5: The mechanics of learning

The introduction describes learning in terms of paired examples and the ability to produce outputs for sufficiently similar new inputs.

5.1 A timeless lesson in modeling · 5.2 Learning is just parameter estimation · 5.2.1 A hot problem · 5.2.2 Gathering some data · 5.2.3 Visualizing the data · 5.2.4 Choosing a linear model as a first try · 5.3 Less loss is what we want · 5.3.1 From problem back to PyTorch · 5.4 Down along the gradient · 5.4.1 Decreasing loss · 5.4.2 Getting analytical · 5.4.3 Iterating to fit the model · 5.4.4 Normalizing inputs · 5.4.5 Visualizing (again) · 5.5 PyTorch’s autograd: Backpropagating all things · 5.5.1 Computing the gradient automatically · 5.5.2 Optimizers à la carte · 5.5.3 Training, validation, and overfitting · 5.5.4 Training set · 5.5.5 Autograd nits and switching it off · 5.6 Conclusion · 5.7 Exercises · 5.8 Summary

What you learn in chapter 5 →

Chapter 6: Using a neural network to fit the data

The introduction connects the previous chapter’s training process to neural networks and explains why merely choosing a different fixed-form model is not enough for more complex problems.

6.1 Artificial neurons · 6.1.1 Composing a multilayer network · 6.1.2 Understanding the error function · 6.1.3 Adding nonlinearity with activation functions · 6.1.4 More activation functions · 6.1.5 Choosing the best activation function · 6.1.6 What learning means for a neural network · 6.2 The PyTorch nn module · 6.2.1 Using nn.Module as a callable · 6.2.2 Returning to the linear model · 6.3 Finally, a neural network · 6.3.1 Replacing the linear model · 6.3.2 Inspecting the parameters · 6.3.3 Comparing to the linear model · 6.4 Conclusion · 6.5 Exercises · 6.6 Summary

What you learn in chapter 6 →

Chapter 7: Telling birds from airplanes: Learning from images

The introduction shifts from a simple regression example to an upcoming image-recognition task using tiny images.

7.1 A dataset of tiny images · 7.1.1 Downloading CIFAR-10 · 7.1.2 The Dataset class · 7.1.3 Dataset transforms · 7.1.4 Normalizing data · 7.2 Distinguishing birds from airplanes · 7.2.1 Building the dataset · 7.2.2 A fully connected model · 7.2.3 Output of a classifier · 7.2.4 Representing the output as probabilities · 7.2.5 Training the classifier · 7.2.6 The limits of going fully connected · 7.3 Conclusion · 7.4 Exercises · 7.5 Summary

What you learn in chapter 7 →

Chapter 8: Using convolutions to generalize

The introduction explains why the fully connected image classifier struggles to generalize and motivates replacing its dense transformation with convolution.

8.1 The case for convolutions · 8.1.1 What convolutions do · 8.2 Convolutions in action · 8.2.1 Padding the boundary · 8.2.2 Detecting features with convolutions · 8.2.3 Looking further with depth and pooling · 8.2.4 Putting it all together for our network · 8.3 Subclassing nn.Module · 8.3.1 Our network as an nn.Module · 8.3.2 How PyTorch keeps track of parameters and submodules · 8.3.3 The functional API · 8.4 Training our convolutional neural network · 8.4.1 Measuring accuracy · 8.4.2 Saving and loading our model · 8.4.3 Training on the GPU · 8.5 Model design · 8.5.1 Adding memory capacity: Width · 8.5.2 Helping our model to converge and generalize: Regularization · 8.5.3 Going deeper to learn more complex structures: Depth · 8.5.4 Comparing the designs from this section · 8.5.5 It’s already outdated · 8.6 Conclusion · 8.7 Exercises · 8.8 Summary

What you learn in chapter 8 →

Chapter 9: How transformers work

The introduction contrasts generative modeling with earlier prediction tasks and uses ELIZA to show why realistic text generation requires more than fixed response rules.

9.1 A motivating example: Generating names character by character · 9.2 Self-supervised learning · 9.2.1 Limits of the bigram model · 9.3 Generating our training data · 9.4 Embeddings and linear layers · 9.4.1 Visualizing embeddings · 9.5 Attention · 9.5.1 Dot product self-attention · 9.5.2 Scaled dot product causal self-attention · 9.6 Transformers · 9.6.1 The decoder · 9.7 Other Transformer architectures · 9.7.1 The encoder · 9.7.2 The encoder-decoder · 9.8 Tokenization · 9.8.1 Generating sentences · 9.9 The Vision Transformer · 9.10 Conclusion · 9.11 Exercises · 9.12 Summary

What you learn in chapter 9 →

Chapter 10: Diffusion models for images

The introduction contrasts image generation with text generation while identifying their shared goal of learning data patterns to produce plausible new samples.

10.1 History of VAEs and GANs · 10.2 Motivator for diffusion models · 10.3 Diffusion in detail · 10.4 Setting up the data · 10.5 The forward process · 10.6 Training · 10.6.1 Loss · 10.7 Reversing diffusion (how to sample) · 10.8 Conclusion · 10.9 Exercises · 10.10 Summary

What you learn in chapter 10 →

Chapter 11: Using PyTorch to fight cancer

This introduction previews the lung cancer project’s overall plan and the data and domain context to be covered in the chapter.

11.1 Introduction to the use case · 11.2 Preparing for a large-scale project · 11.3 What is a CT scan, exactly? · 11.4 The project: An end-to-end detector for lung cancer · 11.4.1 Why can’t we just throw data at a neural network until it works? · 11.4.2 Our data source: The LUNA Grand Challenge · 11.4.3 Downloading the LUNA data · 11.5 Conclusion · 11.6 Summary

What you learn in chapter 11 →

Chapter 12: Combining data sources into a unified dataset

This introduction frames data loading as the work of turning raw CT scans and their annotations into training samples.

12.1 Raw CT data files · 12.2 Parsing LUNA’s annotation data · 12.2.1 Training and validation sets · 12.2.2 Unifying our annotation and candidate data · 12.3 Loading individual CT scans · 12.3.1 Hounsfield Units · 12.4 Locating a nodule using the patient coordinate system · 12.4.1 The patient coordinate system · 12.4.2 CT scan shape and voxel sizes · 12.4.3 Converting between millimeters and voxel addresses · 12.4.4 Extracting a nodule from a CT scan · 12.5 Straightforward dataset implementation · 12.5.1 Caching candidate arrays with the getCtRawCandidate function · 12.5.2 Constructing our dataset in LunaDataset.__init__ · 12.5.3 A training/validation split · 12.5.4 Rendering the data · 12.6 Conclusion · 12.7 Exercises · 12.8 Summary

What you learn in chapter 12 →

Chapter 13: Training a classification model to detect suspected tumors

The chapter introduction connects the previously prepared CT-scan dataset to the upcoming work of loading data, training a classifier, and tracking its performance.

13.1 A foundational model and training loop · 13.2 The main entry point for our application · 13.3 Pretraining setup and initialization · 13.3.1 Initializing the model and optimizer · 13.3.2 Care and feeding of data loaders · 13.4 Our first-pass neural network design · 13.4.1 The core convolutions · 13.4.2 The full model · 13.5 Training and validating the model · 13.5.1 The computeBatchLoss function · 13.5.2 The validation loop is similar · 13.6 Outputting performance metrics · 13.6.1 The logMetrics function · 13.7 Running the training script · 13.7.1 Data needed for training · 13.7.2 Interlude: The tqdm function · 13.8 Evaluating the model: Getting 99.7% correct means we’re done, right? · 13.9 Graphing training metrics with TensorBoard · 13.9.1 Running TensorBoard · 13.9.2 Adding TensorBoard support to the metrics logging function · 13.10 Why isn’t the model learning to detect nodules? · 13.11 Conclusion · 13.12 Exercises · 13.13 Summary

What you learn in chapter 13 →

Chapter 14: Improving training with metrics and augmentation

The chapter introduction explains why high overall accuracy did not mean the lung-nodule classifier was useful.

14.1 High-level plan for improvement · 14.2 Good dogs vs. bad guys: False positives and false negatives · 14.3 Graphing the positives and negatives · 14.3.1 Recall is Chirpy’s strength · 14.3.2 Precision is Dozer’s forte · 14.3.3 Implementing precision and recall in logMetrics · 14.3.4 Our ultimate performance metric: The F1 score · 14.3.5 How does our model perform with our new metrics? · 14.4 What does an ideal dataset look like? · 14.4.1 Making the data look less like the actual and more like the “ideal” · 14.4.2 Contrasting training with a balanced LunaDataset to previous runs · 14.4.3 Recognizing the symptoms of overfitting · 14.5 Revisiting the problem of overfitting · 14.5.1 An overfit face-to-age prediction model · 14.6 Preventing overfitting with data augmentation · 14.6.1 Specific data augmentation techniques · 14.6.2 Seeing the improvement from data augmentation · 14.7 Conclusion · 14.8 Exercises · 14.9 Summary

What you learn in chapter 14 →

Chapter 15: Using segmentation to find suspected nodules

The introduction explains why the existing nodule classifier needs an automatic way to find candidates in CT scans and places that need within a multistage project design.

15.1 Utilizing a second model in our project · 15.2 Various types of segmentation · 15.3 Semantic segmentation: Per-pixel classification · 15.3.1 The Segment Anything model (SAM) · 15.4 SAM architecture · 15.4.1 Trying out an off-the-shelf model for our project · 15.5 Using the SAM model directly · 15.6 Updating the dataset for segmentation · 15.6.1 Working around SAM’s limitation on 2D data · 15.6.2 Building the segmentation dataset · 15.6.3 Training a model to flag potential candidates · 15.7 Updating our training for fine-tuning · 15.7.1 How to fine-tune a model · 15.7.2 Using the AdamW optimizer · 15.7.3 Designing our training loop · 15.7.4 Saving our model · 15.8 Inference and results · 15.9 Conclusion · 15.10 Exercises · 15.11 Summary

What you learn in chapter 15 →

Chapter 16: Training models on multiple GPUs

This introduction explains why growing models and datasets can make training on a single GPU infeasible.

16.1 Introduction to parallel programming · 16.1.1 Distributed computing terminology · 16.1.2 Hardware requirements · 16.1.3 Initializing a distributed program · 16.2 Collective communication · 16.3 Introduction to parallelisms · 16.4 Data parallelism · 16.5 Model parallelism · 16.5.1 Pipeline parallelism · 16.5.2 Tensor parallelism · 16.5.3 Deciding between pipeline and tensor parallelism · 16.6 n-dimensional parallelism · 16.7 Fully sharded data parallelism · 16.8 Large language model–specific parallelisms · 16.8.1 Context parallelism · 16.8.2 Expert Parallelism · 16.9 Tying all parallelisms together · 16.10 Conclusion · 16.11 Exercises · 16.12 Summary

What you learn in chapter 16 →

Chapter 17: Deploying to production

The introduction explains why deployment choices depend on how people need to access a model and where it needs to run.

17.1 Serving PyTorch models · 17.1.1 Our model served by Gradio · 17.1.2 Our model behind a FastAPI server · 17.1.3 What we want from deployment · 17.1.4 Request batching and streaming responses · 17.1.5 How to make PyTorch models even faster · 17.2 Exporting models · 17.2.1 Interoperability beyond PyTorch with ONNX · 17.2.2 PyTorch’s own export: torch.export · 17.3 Expanding on torch.compile · 17.3.1 Full graph capture vs. disjoint graphs · 17.4 Understanding execution with torch.profiler · 17.5 Using PyTorch outside of Python · 17.5.1 LibTorch: PyTorch in C++ · 17.6 Going mobile: ExecuTorch · 17.7 Conclusion · 17.8 Exercises · 17.9 Summary

What you learn in chapter 17 →

Concepts explained in this book

These guides are generated from the text of Manning books by Manning's knowledge graph and link to the sections they draw on. The full books are available on liveBook and at manning.com.