Book companion · CC BY-SA 4.0
Dive into Deep Learning: summary and chapter guide
Quotations are used under CC BY-SA 4.0, and this page’s own text is shared under the same license. Read it free.
What is Dive into Deep Learning about?AI-assisted
Each new learning machine fixes what the one before left undone
Taken as a whole, this is a book about how deep learning is actually learned and practiced, and it answers that by interleaving concept, mathematics and runnable code in one medium — one self-contained notebook per example, a shared d2l package, and every component built first from scratch and then in a concise framework API — because applying deep learning demands problem framing, model mathematics, optimization, statistics and engineering at once. Its main line is that tasks resisting hand-coded rules should be learned from data through four components (data, model, objective, optimization), and from that starting point each new piece of machinery is introduced only as the fix for a limitation of the one before: linear regression already supplies a parameterized model, a maximum-likelihood loss and minibatch SGD; softmax classification recasts prediction as a draw from a distribution; hidden layers with nonlinear activations undo the collapse of composed affine maps; convolution exploits the pixel adjacency that order-invariant dense layers ignore; recurrence, gating, bidirectionality and encoder–decoder pairs absorb variable-length sequences; and attention removes the fixed-length context bottleneck, with Transformers dropping recurrence entirely and enabling pretrained foundation models. The book then grounds all of this in optimization theory — training error is not generalization error, saddle points dominate local minima in high dimensions, and convexity supplies the Hessian tests, Lagrangians, penalties and projections that justify gradient descent despite nonconvexity — before turning to putting the methods to work: compilation and hardware-aware execution, data versus model parallelism, computer vision from augmentation and fine-tuning to anchor-based detection with IoU labeling and non-maximum suppression, NLP from word2vec and its sampling approximations to BERT and its sequence- and token-level fine-tuning, and reinforcement learning's Markov decision processes solved by value iteration and Q-learning. Its closing stretch makes the practice principled rather than ad hoc, with Gaussian processes placing interpretable priors over functions, hyperparameter optimization recast as noisy gradient-free search sped up by multi-fidelity schemes like successive halving and ASHA, GANs turning a two-sample test into a minimax signal, recommender systems moving from explicit ratings to personalized ranking over implicit feedback, and an appendix exhibiting linear algebra, calculus and probability as one geometric chain in which matrices only skew, rotate and scale space. The final conclusion is that competence here is inseparable from infrastructure and workflow — notebooks read, run and edited in Jupyter with reviewable markdown sources feeding back through fork-edit-commit-pull-request, GPUs chosen by compute power, memory size and bandwidth with low precision as a throughput-per-dollar lever, and cloud instances reached over SSH port forwarding and stopped to control cost — so that understanding, code and the machines running them form a single practice.
A fable for the whole bookAI-assisted
One story that carries the book’s central idea — and an honest note on where the story breaks.
The apprentice learned pricing from data when rules could not be said
Once there was a village whose baker was famous for guessing the price of any loaf a stranger brought in. Her apprentice begged for the rule. She tried: 'weigh it, then... well, if the crust is dark but the crumb is open, unless it is rye...' The rule kept escaping her, because her hands knew what her mouth could not say, and the market shifted each season anyway. So the apprentice stopped asking and did something else. He kept a ledger of every loaf sold: its weight, its days of rising, and the coin it fetched. He wrote on a slate a guess-machine with two dials — so many coins per ounce, so many per day of rising, plus a fixed sum — and a rule for scoring himself: for each loaf, take the gap between his guess and the true price, square it, halve it, and average. Then each morning he took a handful of ledger lines, not the whole book, saw which way to nudge each dial to shrink the gap, and nudged. The first week he overfit the summer loaves and insulted a winter customer, so he set aside a sealed page of loaves he never trained on, and only trusted himself when the sealed page agreed. An elder scolded him: 'A true craftsman derives the rule.' The apprentice answered, 'I cannot derive what the baker cannot speak. But I can turn the dials and watch the gap shrink, and show you the ledger.' Years on, his slate had grown many dials and many stacked slates, but it was still the same four things: the ledger, the dials, the gap, and the nudging. The old two-dial slate hung above the oven, because every newcomer could see the whole of it at once.
What the story stands for
| In the story | In the book |
|---|---|
| The baker who cannot state her pricing rule, yet prices correctly | Tasks whose rules cannot be hand-coded — the pattern shifts or the mapping lies beyond conscious understanding — which is exactly where machine learning belongs |
| The apprentice's ledger of weights, rising days and prices | Data: labeled examples, and the preprocessing/loading that turns messy records into tensors the learning algorithm can consume |
| The slate with two dials plus a fixed sum | Model and model family: linear regression as a weighted sum of features plus a bias; all reachable dial settings form the space searched |
| Squaring and halving the gap, then averaging | Squared error loss as the objective function — and its maximum-likelihood justification under additive Gaussian noise, not an arbitrary convenience |
| Taking a handful of ledger lines each morning and nudging the dials | Minibatch stochastic gradient descent as the default learning algorithm, rather than a closed-form solution |
| The sealed page of loaves never trained on | Generalization and hyperparameters: training error is not generalization error, so judgment rests on a held-out validation set |
| The elder demanding a derived rule versus 'turn the dials and watch the gap shrink' | The book's stance that where formal theory lags, intuition is built by tweaking runnable code and observing results |
| Many dials and stacked slates, still the same four things | The four-component decomposition — data, model, objective, optimization — as the frame in which every later method is read as a substitution |
Where the fable breaks
The fable distorts by making the dials legible: an apprentice can read 'coins per ounce' and explain it, so the story smuggles back the very interpretability the baker lacked. The book's concept holds things the fable cannot carry — that stacked slates are not more dials but composed nonlinear layers, and that composing affine maps alone collapses back to one affine map; that the nudging depends on forward and backward propagation, gradient scaling and symmetry-breaking initialization, none of which a hand on a dial resembles; that in high dimensions the landscape is ruled by saddle points rather than the single valley 'shrink the gap' implies; that structure in the data (pixel adjacency, variable-length sequences) demands changing the model's shape, not its dial count; and that the engineering substrate — vectorization, avoided memory allocation, GPUs, the shared d2l package and a reproducible environment — is a precondition for training at all, whereas a slate needs only chalk. The fable also hides the book's own unresolved tensions: that the apprentice's two features are assumed to explain all variation, and that implementing from scratch and then discarding it for a framework API leaves open which abstraction he should actually reason in.
Dive into Deep Learning: the core arguments
10 theses the book defends, in the order the argument needs them.
- Deep learning cannot be taught by prose, mathematics or code alone, because applying it demands problem framing, model mathematics, optimization, statistical generalization and engineering simultaneously; the three must be interleaved in one medium.
“Testing the potential of deep learning presents unique challenges because any single application brings together various disciplines.”
PrefaceRead in context → - Because formal theory often cannot explain why techniques work, intuition should be built by tweaking runnable code and observing results rather than by waiting for proofs.
- When a task's rules cannot be stated — because the pattern shifts or the mapping lies beyond conscious understanding — the right move is to write a program that learns the mapping from labeled examples instead of designing the recognizer by hand.
- Every machine learning problem decomposes into the same four components — data, model, objective function and optimization algorithm — so new methods should be read as substitutions within that frame.
- Linear regression deserves to be taught first because, despite being shallow, it already contains nearly every component of deep learning and is intuitive enough that two billing examples recover its parameters.
- Analytic closed-form solutions are a lucky special case rather than a model for learning, so gradient-based optimization on minibatches should be treated as the default method.
- Loss functions are not arbitrary conveniences: minimizing squared error is exactly maximum likelihood under additive Gaussian noise.
- Engineering details — vectorized computation, avoided memory allocation, and pandas preprocessing of messy data — are not peripheral but required for models to train at all.
- Mathematical objects should be read as transformations rather than bookkeeping: multiplying by a matrix maps vectors between spaces, which is what a neural network layer does.
- A CPU-only machine suffices to start, so lack of a GPU should not block a reader from beginning.
Chapter by chapter
Every chapter is on this page: how the argument unfolds, its key claims, common misreadings and key concepts. Pick one from the list.
Chapter 1: Introduction
How does splitting into training and test sets expose overfitting?
How Chapter 1 unfoldsAI-assisted
How the chapter opens. The chapter begins not with a definition of machine learning but with a contrast designed to carve out the need for it. Ordinary programming works beautifully when a problem can be enumerated: the logic for adding an item to a shopping cart can be written out case by case and shipped with confidence before a single customer arrives. The author then sets a second kind of task beside it — forecasting weather, recognizing objects, waking a device on a spoken trigger phrase — where the step-by-step route from input to answer simply isn't available to conscious inspection, and where the input itself is overwhelming: a microphone hands you roughly 44,000 amplitude numbers every second, and no rule you could write turns them into yes or no. The opening move is therefore a diagnosis rather than a proof, and the author is candid that the wake-word case is one illustrative example of where enumeration breaks down, not a demonstration that it always must. From that diagnosis the alternative follows directly: if you cannot state the rule, collect examples of the task being performed correctly and let an optimization algorithm adjust the parameters of a flexible program until it reproduces them. This is what sets up the four-component scaffolding — data, model, objective, optimization — that the rest of the chapter hangs its taxonomy on.
How it develops. Having established that parameters should be fitted rather than written, the author's next step is reassurance: the basic case is something readers already do intuitively. A contractor who bills $350 for three hours and $250 for two invites anyone to back out $100 per hour plus a $50 show-up fee — which is precisely a fitted linear model, and the author flags the condition attached to it, that the inference holds only if those two assumed features genuinely account for all the variation in the bill. With regression defined by the numerical form of its target and illustrated through house prices and that bill, the development proceeds by varying the target rather than the method: classification answers which one?, and from there the survey widens through hierarchical class structures, tagging (where labels are not mutually exclusive), search, recommender systems, and sequence learning. The pivotal cautionary note lands inside the classification discussion: the most probable label is not automatically the right action. A mushroom judged 20 percent likely to be a death cap carries an expected harm of 0.2 times infinity if eaten, against a loss of only 0.8 of a meal if discarded — so the rational decision contradicts the top-ranked prediction. Decisions require weighting outcomes by consequence, not merely ranking probabilities, which is how the chapter keeps loss function and decision rule conceptually distinct.
Where it turns. The turn comes when the author steps back from the whole supervised survey and names its shared limitation. Every task to that point learned from a fixed pile of data gathered in advance, and the argument is that this offline setting cannot by itself support an intelligent agent. Once something acts, its actions shape what it subsequently observes — whether the environment remembers it, cooperates with it or competes against it, and whether its dynamics drift over time. The consequence is distribution shift between training and deployment, so a method that assumes a frozen dataset is mismatched to the problem. This is what motivates the reinforcement learning framing that follows: an agent interacting with an environment, receiving reward rather than correct answers. The author is careful about why this is genuinely harder. The learner is never told which action was optimal; in chess, or in a career, reward arrives long after the moves that produced it, so the learner must infer which of many earlier unlabeled actions deserves credit or blame. Add partial observability and the exploration-versus-exploitation tradeoff, and sparse delayed feedback emerges as a qualitatively different difficulty from labeled supervision — with bandits and Markov decision processes positioned as the tractable special cases.
How it closes. The closing section does two jobs. First it deflates the sci-fi register of AI anxiety and relocates the real risks: routine labor automation and careless statistical bias. The illustrative case is agricultural robotics, which will cut costs for organic farmers while simultaneously automating harvesting and eliminating menial work that currently employs very large numbers of people — a visible, already-unfolding effect the author judges more pressing than speculative malevolent superintelligence. Then comes the chapter's actual definition of its subject, placed deliberately at the end rather than the beginning. Deep learning is characterized not by depth as such but by joint learning of many layers of representation. The author anticipates the obvious misreading here: nearly all earlier machine learning already involved multiple layers of computation, the early ones being human-designed feature extraction, with only the final shallow model fitted to data. The shift is that every transformation is now learned together with the predictor, so millions of candidate filters can be evaluated automatically rather than invented by hand — which is how learned filters displaced engineered ones in computer vision and raised accuracy. Because such layers can consume raw audio, raw pixels and variable-length text directly, much field-specific preprocessing dissolves and the boundaries between application areas blur. The chapter ends by situating this inside broader methodological shifts — toward models whose form is dictated by data, toward empiricism, toward open sharing of code and weights — while attaching an honest condition to the first of these: assumption-light models make sense when data is abundant, scarce data still calls for simplifying assumptions, and the accuracy gain typically costs interpretability. The analogy offered is physics moving from hand-solved approximations to numerical simulation, presented as an analogy and not as proof.
Key claims, with the lines that support them
Hand-written rules are enough for some problems but hopeless for others, because the pattern drifts or the input-to-output relation is beyond what we can articulate.
The author contrasts two cases: e-commerce logic such as adding an item to a cart can be enumerated case by case and shipped confidently before any customer arrives, whereas a wake-word detector faces roughly 44,000 microphone samples per second with no writable rule turning them into yes or no. The second case is one illustrative task, not a proof, but it shows where enumeration breaks down.
“In the case of image recognition, the precise steps required to perform the task lie beyond our conscious understanding, even though our subconscious cognitive processes execute the task effortlessly.”
Chapter 1. IntroductionRead in context →
Having established that parameters should be fitted from data, the author argues the basic case is already familiar: linear regression is something readers intuitively do.
Given a contractor who bills 350 dollars for three hours and 250 dollars for two hours, anyone can back out 100 dollars per hour plus a 50-dollar show-up fee — exactly a fitted linear model. The author flags the condition: this works only if the two assumed features really explain all the variation in the bill.
“If you followed that much, then you already understand the high-level idea behind linear regression.”
Chapter 1. IntroductionRead in context →
Turning from regression to classification, the author warns that the class with the highest probability is not automatically the action to take.
A mushroom judged 20 percent likely to be a death cap carries an expected harm of 0.2 times infinity if eaten, against a loss of only 0.8 of a meal if thrown away, so the rational choice contradicts the most probable label. Decisions therefore require weighting outcomes by their consequences, not just ranking probabilities.
“Note that the most likely class is not necessarily the one that you are going to use for your decision.”
Chapter 1. IntroductionRead in context →
3 more claims
Having surveyed tasks learned from fixed piles of data, the author argues that this offline setting cannot support an intelligent agent.
Once an agent acts, its actions shape what it later observes: whether the environment remembers it, cooperates or competes with it, and whether its dynamics change over time. These possibilities produce distribution shift between training and deployment, so learning that assumes a frozen dataset mismatches the problem — which is what motivates the reinforcement learning framing that follows.
“If we want to train an intelligent agent, we must account for the way its actions might impact the future observations of the agent, and so offline learning is inappropriate.”
Chapter 1. IntroductionRead in context →
Closing the survey, the author holds that automated routine labor and careless statistical bias are the urgent risks, not a malevolent superintelligence.
Farm robots will cut costs for organic farmers while also automating harvesting, eliminating menial work that employs large numbers of people — a concrete, already-visible effect that the author judges more pressing than speculative scenarios.
“With what we know today, this strikes us as a much more pressing concern than the potential of malevolent superintelligence for destroying humanity.”
Chapter 1. IntroductionRead in context →
What makes deep learning distinctive is that all the layers of representation are learned together, and this dissolves the old split between domain preprocessing and modeling.
The author points to computer vision, where pipelines once separated hand-engineered feature extractors from a shallow model, until learned filters replaced those extractors with better accuracy. Because the learned layers can consume raw audio, raw pixels and variable-length text for translation — low-level perceptual data earlier tools could not handle — much of the field-specific preprocessing disappears and the boundaries between application areas blur.
“Arguably, all machine learning has many layers of computation, the first consisting of feature processing steps.”
Chapter 1. IntroductionRead in context →
How it works
The 3 mechanisms the chapter’s argument runs on.
Mechanism 1
Why rules fail, fitting works
For perception tasks the step-by-step mapping from input to answer is not available to conscious inspection, and the raw input is huge — a microphone alone delivers about 44,000 amplitude numbers each second. Since no rule can be written out, one collects examples of the task being done correctly and lets an optimization algorithm tweak a flexible program's parameters until it matches them.
Mechanism 2
Delayed reward blurs blame
A reinforcement learner is never told which action was optimal; it only receives reward, and in chess or a career the reward arrives long after the actions that caused it. The learner must therefore infer which of many earlier unlabeled moves deserves the credit or blame, which is why sparse delayed feedback is far harder than labeled supervision.
Mechanism 3
Joint layers beat hand-built features
Classical pipelines also had layers, but a human designed the feature extractor and only the final shallow model was fitted. Deep learning learns every transformation together with the predictor from data, so millions of candidate filters can be evaluated automatically rather than invented by hand — which is how learned filters displaced engineered ones and raised accuracy.
Common misreadings
Deep learning is just the same old machine learning with more layers stacked on top, so depth is the whole trick.
The author notes that nearly all machine learning already had multiple layers of computation — the early ones being human-designed feature extraction. The real shift is that every layer is learned jointly from data instead of hand-designed, which is why automatically learned filters outperformed engineered ones.
“Arguably, all machine learning has many layers of computation, the first consisting of feature processing steps.”
Chapter 1. IntroductionRead in context →
Since letting data determine a model's form beats imposing assumptions, one should always prefer flexible, assumption-light models.
The author presents this shift as conditional: models that let data dictate their form only make sense when data is abundant, scarce data still calls for simplifying assumptions, and the gain in accuracy typically costs interpretability — the same tradeoff physics accepted when it moved from hand-solved approximations to numerical simulation, which is offered as an analogy rather than proof.
“When data is abundant, these can be replaced by nonparametric models that better fit the data.”
Chapter 1. IntroductionRead in context →
Key concepts in Chapter 1
- Machine learning
- Algorithms whose performance improves as they accumulate data or interaction.
- Where it applies: Not needed when a rule-based solution works 100% of the time.
- Model and model family
- A program with fixed parameter settings is a model; all reachable settings form its family.
- Where it applies: Fundamentally different input/output types may require a different family.
- Learning algorithm
- The meta-program that uses the dataset to pick parameter values.
- Where it applies: Needs the problem's inputs, outputs, and model family defined first.
- Supervised learning
- Predicting a designated unknown label from known inputs using labeled examples.
- Where it applies: Only one among several kinds of machine learning problems.
- Regression
- Predicting a label that can take arbitrary numerical values.
- Where it applies: Applies when labels are numeric, not discrete categories.
- Classification
- Predicting which category among a discrete set an example belongs to.
- Where it applies: Needs a known, discrete class set; uses cross-entropy rather than squared error.
10 more concepts
- Multi-label classification
- Predicting several tags at once because classes can co-occur.
- Where it applies: Used when classes are not mutually exclusive, as in an image with four animals.
- Sequence learning
- Tasks whose inputs or outputs are variable-length sequences needing context.
- Where it applies: Required when successive observations are dependent, unlike fixed-input tasks.
- offline learning
- Learning that happens after the algorithm is cut off from the environment, using one fixed pile of data.
- Where it applies: Inappropriate when an agent's actions change its future observations.
- policy
- A rule that turns what the agent observes into the action it takes.
- Where it applies: Defined only inside the observation-action-reward loop.
- credit assignment problem
- Figuring out which earlier actions deserve praise or blame for a much later outcome.
- Where it applies: Arises when reward is sparse and delayed, as in chess or a promotion.
- exploration versus exploitation
- Choosing between using the best known strategy and testing unknown ones for possible gains.
- Where it applies: Trades short-term reward for knowledge.
- Deep learning
- Machine learning with many-layered neural networks whose layers of transformations are learned together from data.
- Where it applies: Depth alone is not the point; traditional pipelines also have layers, but theirs are hand-designed rather than jointly learned.
- End-to-end training
- Building the whole system first and tuning its parts jointly, instead of assembling separately tuned components.
- Where it applies: Not always the default; some settings still favor separately engineered components.
- Feature engineering
- Manually inventing transformations that turn raw data into vectors a shallow model can use.
- Where it applies: Human ingenuity cannot match automatic evaluation over millions of choices, so learned filters displaced it.
- Nonparametric models
- Models that let abundant data, rather than simplifying assumptions, determine their form.
- Where it applies: Only sensible when data is abundant; scarce data still needs simplifying assumptions, and accuracy may cost interpretability.
Reader’s notes on Chapter 1AI reading companion
“And when you are able to devise solutions that work \(100\%\) of the time, you typically should not be worrying about machine learning.”
Read in context →A refreshingly honest boundary marker for a textbook that's about to sell you 1000 pages of ML. The field defined by its complement: what rules can't reach.
“the precise steps required to perform the task lie beyond our conscious understanding, even though our subconscious cognitive processes execute the task effortlessly”
Read in context →This is the real argument of the chapter — not that tasks are hard, but that we are opaque to ourselves. ML enters through the gap between doing and explaining.
“While this story was fabricated for pedagogical convenience”
Read in context →The parenthetical wink is doing work: admitting the anecdote is staged keeps the authors honest while still letting them use its warmth. Nice rhetorical hygiene.
17 more notes
“Every second, the microphone will collect roughly 44,000 samples.”
Read in context →The single most persuasive line here. One concrete number does what three paragraphs of "it's hard" couldn't.
“You can think of the parameters as knobs that we can turn”
Read in context →The knob metaphor is the whole book's load-bearing beam. Worth noting what it hides though: knobs suggest a few interpretable dials, not a billion entangled ones.
“Note that this can all happen without the data scientist actively conspiring, or even being aware.”
Read in context →The sharpest sentence in the section. Harm doesn't need a villain — just a pipeline. Placing this inside a chapter on "key components" quietly makes ethics structural rather than optional.
“the student might begin to memorize the practice questions, appearing to master the topic but faltering when faced with previously unseen questions”
Read in context →The analogy lands because every reader has been that student. But notice it also smuggles in a value judgment: memorization is failure. In humans too, arguably.
“100 dollars per hour plus 50 dollars to show up at your house. If you followed that much, then you already understand the high-level idea behind linear regression.”
Read in context →Two data points, two parameters, solved exactly — and then they immediately take the exactness away. The honest part is admitting the noise comes next.
“the certain benefit of a delicious dinner is not worth a 20% risk of dying from it”
Read in context →The mushroom is where the chapter quietly stops being about prediction and becomes about decision. Accuracy is not the objective function; consequence is. Most deployed ML forgets this.
“0.2 \times \infty + 0.8 \times 0 = \infty”
Read in context →Writing infinity into an expectation is a rhetorical move, not math — any nonzero probability of death makes the integral blow up, which also means the framework can't distinguish a 20% risk from a 0.0001% one. Death isn't actually infinitely bad or no one would drive.
“mistaking a rattler for a garter could have fatal consequences”
Read in context →Nice undercutting of their own example: the hierarchy isn't in nature, it's in your use case. Phylogeny and consequence are different trees, and the model should be trained on the one that can hurt you.
“typically there is a one-year lag between archiving and tagging”
Read in context →The MeSH detail is the most persuasive argument in the section — not benchmark glory but a year of latency in medical literature. Concrete institutional pain beats any accuracy table.
“Weirdly, the scoring provided by PageRank did not depend on the actual query”
Read in context →"Weirdly" is doing a lot of work. Query-independence wasn't an oversight, it was what made it computable once offline for the whole web. The oddity is retrospective.
“we only observe censored feedback: users preferentially rate movies that they feel strongly about”
Read in context →The missing three-star ratings are the ghost in every recommender. The data isn't noisy, it's systematically absent — and absent in a way correlated with the thing you're predicting.
“feedback loops to form where a recommender system preferentially pushes an item that is then taken to be better”
Read in context →Here the book admits the model is part of the system it measures. Everything before this assumed data came from the world; here data comes from the previous model. That's the whole modern crisis in one paragraph.
“an extremely specialized job and an extremely dictatorial boss”
Read in context →The boss analogy flatters supervised learning by making its weakness sound like comfort. The real cost isn't tedium — it's that the dictator's labels encode his biases, and imitation inherits them.
“the type and number of questions we can ask is limited only by our creativity”
Read in context →Honest translation: unsupervised learning has no ground truth, so it has no way to tell a discovery from an artifact. "Limited only by creativity" is also "unfalsifiable by construction."
“taking exams written by a lecturer, while the homework was composed by their teaching assistants”
Read in context →Best analogy in the chapter — distribution shift as the universal student grievance. It lands because everyone has felt the loss, not just read about it.
“supervised learning can be recast as reinforcement learning”
Read in context →True and almost useless. Generality buys nothing if the special case solves in closed form while the general one needs millions of episodes. Framework breadth is not framework power.
“That promotion likely reflects a number of well-chosen actions over the previous year”
Read in context →Credit assignment smuggled in through office politics — and the analogy is sharper than intended, since promotions are also partly noise and patronage. Learning from a sparse reward you don't fully control is exactly the hard case.
A reader’s takeAI reading companion
The knob metaphor is so elegant it hides a billion entangled parameters
The chapter's arc is quieter than it looks: it opens by drawing a boundary around itself — if you can solve it with rules 100% of the time, go do that — and then spends the rest of the chapter mapping the territory outside that line. The real argument isn't that the excluded tasks are hard; it's that we are opaque to ourselves. We recognize a face, hear a wake word, catch a tone of voice, and cannot say how. Machine learning enters through the gap between doing and explaining, and the chapter's most persuasive moves are concrete rather than conceptual: 44,000 samples a second does what paragraphs of 'this is difficult' could not.
From there the knob metaphor carries everything — a parameterized program whose dials get turned by data — and it earns its place as the book's load-bearing beam while hiding exactly what will matter later, since knobs imply a handful of readable dials, not a billion entangled ones. Then comes the taxonomy: regression defined by the numeric shape of its target, classification for which-one questions, and the hourly-rate example that gets linear regression across in two data points before honestly taking the exactness back. The mushroom is the hinge of the whole chapter. Up to that point the subject is prediction; after it, the subject is decision.
Continue reading
Accuracy stops being the objective and consequence takes over, which most deployed systems forget. The infinity written into that expectation is rhetoric rather than mathematics — any nonzero death probability blows it up, so the framework can't tell 20% from 0.0001%, and we do in fact drive cars — but the point it dramatizes survives the bad arithmetic. The same insight recurs when hierarchy appears: the rattler-versus-garter aside undercuts the authors' own example, because the tree that matters isn't phylogeny, it's the tree of what can hurt you. Tagging, search, recommenders, and sequence learning then move the discussion from toy settings to institutions, and the texture gets better as it goes: a year of lag between archiving and MeSH tagging is a more convincing argument for automation than any benchmark table; PageRank's query-independence, called 'weird,' was precisely the design choice that made the web computable offline; censored feedback means the missing three-star ratings are systematically absent in a way correlated with what you're trying to predict.
The feedback-loop paragraph is where the chapter turns on its own premises — everything before assumes data arrives from the world, and here data arrives from the previous model. That single paragraph contains the modern crisis. The learning-regimes section is where I'd push back hardest on the framing's comfort. Supervised learning's 'dictatorial boss' is made to sound merely tedious, when the real cost is that the dictator's labels carry his biases and imitation inherits them. Unsupervised learning's questions being 'limited only by our creativity' is a generous way of saying there's no ground truth, hence no way to distinguish a discovery from an artifact — unfalsifiable by construction.
The claim that supervised learning is recastable as reinforcement learning is true and nearly useless: generality buys nothing when the special case has a closed form and the general one needs millions of episodes. Framework breadth is not framework power. What does land is the exam-written-by-the-lecturer, homework-by-the-TAs analogy — distribution shift as universal student grievance, felt rather than read — and credit assignment arriving through office politics, sharper than intended, since promotions are also part noise and patronage. The chapter's ethical thread is its most underrated feature, because it's structural rather than bolted on.
The line about harm occurring without the data scientist conspiring or even being aware sits inside a section on 'key components,' not in an appendix on responsibility, which quietly makes it part of the machinery. The closing survey keeps that posture: real risks — automation, encoded bias, feedback — over cinematic ones, and then a definition of deep learning as jointly learned many-layered representations, end-to-end training swallowing feature engineering, alongside shifts toward nonparametric models, empiricism over theory, and open sharing. What I'd tell a reader: read this chapter as an argument about limits, not capabilities.
It tells you where rules stop, where accuracy stops being the goal, where your data stops being a sample of the world and becomes an echo of your last model, and where a framework's generality stops being useful. The pedagogy is warm and the analogies are unusually good — good enough that you should watch what each one smuggles in. Every comparison here flatters the method it illustrates, and the chapter is honest enough to leave the seams visible if you're reading for them.
Read Chapter 1 with these cards beside each passage.
Open in FeedLitraChapter 2: Preliminaries
How does automatic differentiation actually use the tensor's stored history?
How Chapter 2 unfoldsAI-assisted
The opening: a toolkit framed as survival skills. The chapter does not begin with a thesis but with an inventory — seven skills the reader will need before any model can be built. The first of them, data manipulation, sets the pattern for everything after: the tensor, an n-dimensional array, is introduced as the single interface through which data enters and leaves a deep learning system. The chapter immediately justifies this choice rather than assuming it, naming two concrete capabilities a plain numerical array library lacks — automatic differentiation and GPU execution — and arguing that these two together are precisely what makes neural networks both easy to write and fast to run. A small mechanical point is slipped in here that pays off later: ordinary arithmetic builds a new object each time (Y = Y + X changes Y's identity, while Z[:] = X + Y does not), and since models carry hundreds of megabytes of parameters updated many times a second, in-place writes are a memory discipline, not a stylistic preference. The opening then takes a detour through pandas, because real data arrives messy: a tiny house-price table with missing entries, its categorical roof-type column expanded into indicator columns (with "missing" promoted to a category of its own) and its numeric room count filled with the mean, before anything becomes a tensor. The chapter is explicit that this is a crash course, not a substitute for learning the library properly.
The development: linear algebra built from the ground up, then reframed. From scalars the chapter ramps to vectors, matrices, transposes and symmetry, higher-order tensors, and then the operational vocabulary — elementwise arithmetic, reductions, dot products, matrix–vector and matrix–matrix products, and norms. What keeps this from being a list of operations is a persistent interpretive instruction: a matrix product should be read as transforming vectors, not as bookkeeping. The chapter supports this by noting that such a product carries vectors from one space into another of possibly different dimension, offering rotation by a square matrix as the familiar case, and observing that the matrix–vector product is literally how a neural network layer computes its output. The section's real turn comes at norms, which are presented not as a closing technicality but as the language learning objectives are written in: making observed data as probable as possible, pulling predictions toward ground truth, pushing apart representations of different people while pulling together those of the same person — each of these is a claim about distance, and distances in practice are norms. Having established that objectives are distance statements, the chapter hands itself over to the calculus that minimizes them.
The first turn: differentiation becomes mechanical. Calculus enters through the limit definition of the derivative and the definition of differentiability, moves through notation, basic rules, and some matplotlib plotting utilities, then generalizes to partial derivatives and gradients. The pivot of this chapter arrives at the chain rule. For nested functions derivatives multiply; written multivariately, this becomes a matrix of partial derivatives times a gradient vector. Two consequences follow, and the chapter draws both. First, every gradient computation is a vector–matrix product, which retroactively explains why the linear algebra section was not a preliminary to the preliminaries but the engine itself. Second — and this is the conceptual payoff — the procedure is mechanical enough to automate: walk the dependency graph forward to evaluate, backward to differentiate. Alongside this comes a sobering qualification about what gradients can act on. Accuracy and area-under-curve are the objectives we actually care about, and neither is differentiable, so no derivative-based optimizer can touch them. Training therefore minimizes a smooth stand-in whose gradients indicate which way to move the parameters, and the quantity optimized is never quite the quantity desired.
The second turn: from quantities that exist to quantities we estimate. Probability opens by framing itself as formal reasoning under uncertainty, with the frequentist and Bayesian readings distinguished, and statistics as the discipline that runs the inference backwards from data. The chapter's organizing distinction is laid out with a fair coin: that one-half is a property of the coin, argued by symmetry — every outcome with a given split of heads and tails is matched by its mirror image. If the chance of heads is unknown, however, no symmetry argument is available; one must gather tosses and design an estimator, such as the ratio of heads to tosses, and then ask whether it is consistent. The demonstration is deliberately anticlimactic: simulated draws from an explicitly fair pair of probabilities still return unequal counts, and only as the tosses climb toward ten thousand do the running estimates settle onto the true value, the law of large numbers doing its work slowly and visibly. The lesson is that theoretical probabilities and the statistics computed from data are different objects connected by an estimator, not synonyms.
The close: conditioning, aggregation, and the limits of more data. The chapter's most-quoted illustration arrives next. Two positive HIV tests raise the author's probability from 13.06% to 83.07% — but the chapter is careful that the arithmetic is not the point. A second measurement is informative only if, given the true state, its errors are unrelated to the first test's; under that assumption the jump holds even though the second test is markedly less accurate, and the counterexample makes the boundary unmistakable: rerun the identical test and it reproduces its own result, adding nothing. Conditional independence, not repetition, is what buys confidence. The remaining machinery — expectation, variance, covariance, Bayes read as likelihood times prior, Chebyshev's inequality — follows, and the chapter uses it to puncture two intuitions on the way out. An expectation is not a decision rule: an investment with an expected return of 1.8 times the stake can carry an expected utility of 0.7, a 30% expected loss, so under that utility function keeping the money wins; and an average says nothing about spread or risk. Nor is uncertainty merely a shortage of data. Estimation error falls only about as fast as one over the square root of the sample size, so the gains front-load and then stall — 10 to 1000 observations cuts uncertainty roughly tenfold, the next 1000 buys a factor of about 1.41 — and in any case some uncertainty is aleatoric, inherent in the phenomenon, where no quantity of further observation helps at all. The chapter thus ends where its toolkit began, but with the reader's expectations calibrated: the instruments are powerful, and each one has a stated edge.
Key claims, with the lines that support them
For deep learning, tensors are worth using instead of plain numerical arrays.
The author points to two concrete additions over an ordinary n-dimensional array library: automatic differentiation and the ability to run on GPUs. The argument is that these two features together are exactly what makes neural networks both easy to write and fast to execute.
“First, the tensor class supports automatic differentiation. Second, it leverages GPUs to accelerate numerical computation, whereas NumPy only runs on CPUs.”
§2.1 Data ManipulationRead in context →
Before any modeling, messy real-world data has to be cleaned up with table-handling tools.
The author walks through a tiny house-price table containing missing entries: the categorical roof-type column is turned into indicator columns (missing becoming its own category) and the numeric room-count column is filled with its mean, only then converted into a tensor. The author frames this as a crash course, not a replacement for a real tutorial on the library.
“However, to apply deep learning in the wild we must extract messy data stored in arbitrary formats, and preprocess it to suit our needs.”
§2.2 Data PreprocessingRead in context →
Multiplying by a matrix should be read as transforming vectors, not as bookkeeping; this follows from the author's build-up from scalars and vectors.
The author notes that such a product carries vectors from one space into another of possibly different size, gives rotations as a familiar case of multiplication by a square matrix, and points out that a matrix–vector product is precisely how each neural network layer computes its output.
“We can think of multiplication with a matrix \(\mathbf{A}\in \mathbb{R}^{m \times n}\) as a transformation that projects vectors from \(\mathbb{R}^{n}\) to \(\mathbb{R}^{m”
§2.3 Linear AlgebraRead in context →
3 more claims
Norms are not an optional aside but the language in which learning objectives are written.
The author lists the goals of deep learning—making observed data as probable as possible, pulling predictions close to ground truth, pushing apart representations of different people while pulling together those of the same person—and observes that each is a statement about distance, with distances in practice expressed as norms. This hands the discussion directly to the calculus that optimizes such objectives.
“These distances, which constitute the objectives of deep learning algorithms, are often expressed as norms.”
§2.3 Linear AlgebraRead in context →
Following on from that, training does not optimize the quantity we actually care about but a smooth stand-in for it.
The author names accuracy and area-under-curve as objectives we genuinely want yet cannot differentiate, so no derivative-based optimizer can act on them; the practical route is to minimize a differentiable substitute whose gradients indicate how to move the parameters to lower the loss.
“Not all functions are differentiable, including many that we wish to optimize, such as accuracy and the area under the receiving operating characteristic (AUC).”
§2.4 CalculusRead in context →
A probability belongs to the process that generates data, while the numbers we compute from data are statistics that run the inference in the opposite direction.
The author argues by symmetry that a fair coin's one-half is a property of the coin: every outcome with a given split of heads and tails is matched by its mirror image. To study an unknown chance of heads one must instead gather tosses and design an estimator such as the head-to-toss ratio; simulated draws from an explicitly fair pair of probabilities still return unequal counts, and only as tosses grow to ten thousand do the running estimates settle onto the true value.
“Here, the probability \(1/2\) is a property of the coin itself.”
§2.6 Probability and StatisticsRead in context →
How it works
The 3 mechanisms the chapter’s argument runs on.
Mechanism 1
Why in-place writes save memory
Each ordinary arithmetic expression builds a fresh object, which the author shows by noting that Y = Y + X changes Y's identity while Z[:] = X + Y leaves Z's identity intact. Since models carry hundreds of megabytes of parameters updated many times a second, repeated allocation wastes memory and leaves stale references pointing at outdated values; writing into existing storage avoids both.
Mechanism 2
Chain rule turns into matrix work
For nested functions the derivatives multiply, and the author writes the multivariate version as a matrix of partial derivatives times a gradient vector. Because every gradient computation is therefore a vector–matrix product, linear algebra becomes the engine of deep learning, and the whole process is mechanical enough to automate by walking the dependency graph forward to evaluate and backward to differentiate.
Mechanism 3
Why a second test adds confidence
A second measurement is informative only when, given the true state, its errors are unrelated to the first test's errors. Under that assumption two positive results push the author's HIV probability from 13.06% to 83.07%, even though the second test is markedly less accurate. The author's counterexample shows the limit: rerunning the identical test reproduces the same outcome and adds nothing.
Common misreadings
If a gamble's expected payoff is bigger than what you put in, taking it is the rational move.
The right aggregate to compare is utility, not raw return. In the author's example the investment has an expected return of 1.8 times the stake yet an expected utility of 0.7—a 30% expected loss in utility—so under that utility function keeping the money is the better choice. An average also says nothing on its own about spread or risk.
“If indeed this were your utility function, you might be best off keeping the money in the bank.”
§2.6 Probability and StatisticsRead in context →
Uncertainty is just a shortage of data, so collecting enough observations will drive it away.
Estimation error falls only about as fast as one over the square root of the sample size, so gains arrive early and then stall: moving from 10 to 1000 observations cuts uncertainty roughly tenfold, while the next 1000 improves it by only about 1.41 times. On top of that, part of the uncertainty is inherent in the phenomenon rather than in our ignorance, and no amount of extra data removes it.
“This is a persistent feature of machine learning: while there are often easy gains, it takes a very large amount of data, and often with it an enormous amount of computation, to make further gains.”
§2.6 Probability and StatisticsRead in context →
Key concepts in Chapter 2
- Tensor (n-dimensional array)
- An array of numbers with any number of axes; a vector has one axis, a matrix two, and beyond that we just say kth-order tensor.
- Where it applies: Resembles NumPy's ndarray but adds automatic differentiation and GPU execution; order counts axes while dimensionality counts components.
- Broadcasting
- A rule that lets two differently shaped tensors be combined elementwise by first copying along length-1 axes until shapes match.
- Where it applies: Only works when the mismatched axes have length 1; otherwise shapes must already agree.
- Missing values (imputation vs deletion)
- Entries pandas marks NaN; you either estimate replacements (imputation) or throw away the affected rows or columns (deletion).
- Where it applies: Which option fits depends on context; categorical NaN can become its own category, numerical NaN is often filled with the column mean.
- In-place operation
- Writing a result into already allocated memory, e.g. Y[:] = X + Y, instead of letting a new object be created.
- Where it applies: Only safe when the overwritten value is not needed later in the computation.
- Transpose
- Flipping a matrix's rows and columns, so entry (i,j) becomes entry (j,i).
- Where it applies: An m×n matrix becomes n×m; only square matrices can equal their own transpose.
- Symmetric matrix
- A square matrix identical to its own transpose.
- Where it applies: Only defined for square matrices.
18 more concepts
- Hadamard product
- Elementwise multiplication of two same-shaped matrices.
- Where it applies: Requires matching shapes; not matrix multiplication.
- Dot product
- Sum of products of elements at the same position in two equal-length vectors.
- Where it applies: Vectors must share the same dimension d.
- Norm
- A function sending a vector to a scalar that measures how big it is.
- Where it applies: Must satisfy scaling, triangle inequality and positivity; measures magnitude, not dimensionality.
- Reduction
- Collapsing a tensor along chosen axes by summing or averaging, which removes those axes from the output shape.
- Where it applies: keepdims preserves axis count for broadcasting.
- Differentiable surrogate
- A smooth stand-in loss optimized because the metric we truly care about has no usable derivative.
- Where it applies: Needed only when the target metric, like accuracy or AUC, is non-differentiable.
- Gradient
- The vector collecting a scalar function's partial derivatives with respect to every input variable.
- Where it applies: Defined for functions mapping an n-dimensional vector to a scalar.
- Chain rule
- Derivatives of nested functions multiply, so a gradient becomes a vector–matrix product.
- Where it applies: Requires each component function to be differentiable.
- The d2l package
- A shared code library where #@save-marked functions are stored for later reuse.
- Where it applies: A book-engineering convenience, not a mathematical idea.
- Probability vs statistics
- Probability describes the true generating process; statistics are numbers computed from observed data.
- Where it applies: Frequencies estimate probabilities but are never identical to them in finite samples.
- Bayesian probability
- Using probability to express degrees of belief, including for one-off events, updated by evidence.
- Where it applies: Allows different individuals to begin with different priors, so conclusions are subjective.
- Estimator and consistency
- A statistic designed to estimate a parameter; consistency means estimates converge to the true value with more data.
- Where it applies: Convergence is asymptotic; small samples can deviate noticeably from the true probability.
- Sampling
- Drawing actual outcomes from an underlying random process, e.g. tossing a coin repeatedly.
- Where it applies: Simulated sampling needs a random number generator or multinomial draws.
- Law of large numbers
- As repetitions grow, averages converge to the true probability, with error shrinking about as fast as one over the square root of n.
- Where it applies: Applies to averages of repeated events, not to single non-repeatable events.
- Conditional independence of tests
- Two measurements add information only if, given the true state, their errors are unrelated.
- Where it applies: Fails when you repeat the identical test, which yields no new insight.
- Expectation
- The probability-weighted average value of a random variable.
- Where it applies: A mean alone says nothing about spread or risk.
- Variance
- Expected squared deviation from the mean, used as a measure of risk.
- Where it applies: The raw difference from the mean has expectation zero, so squaring is needed.
- Covariance matrix
- Matrix of expected outer products of mean-centered vectors; gives the variance of any linear function.
- Where it applies: Off-diagonal entries only report correlation strength, not causation.
- Aleatoric vs epistemic uncertainty
- Randomness intrinsic to the problem versus uncertainty about model parameters that more data can shrink.
- Where it applies: The authors note the labels are a slight abuse of language, since all uncertainty is epistemic philosophically.
Reader’s notes on Chapter 2AI reading companion
“the ability to automatically compute derivatives so that you can forget much of the calculus you just learned”
Read in context →The book's wit doing real pedagogical work: it tells you upfront which knowledge is scaffolding and which is load-bearing. Honest about how little calculus a practitioner actually carries.
“some aptitude for finding answers in the official documentation when you get stuck”
Read in context →Listing doc-reading alongside linear algebra is a quiet thesis: this is a craft, not just a theory. The seventh survival skill is the least mathematical and probably the most used.
“First, the tensor class supports automatic differentiation. Second, it leverages GPUs to accelerate numerical computation”
Read in context →The whole deep learning revolution compressed into two bullet points. Neither is a mathematical idea — both are engineering. Worth pausing on how much of the field rests here.
17 more notes
“Notice that the elements of our vector are laid out one row at a time and thus x[3] == X[0, 3]”
Read in context →This throwaway sentence is the one that bites people later. Reshape is a reinterpretation of a flat buffer, not a rearrangement — row-major ordering is the invisible contract behind every later shape bug.
“we might point at the same parameters from multiple variables. If we do not update in place, we must be careful to update all of these references”
Read in context →Here the tutorial briefly stops being math and becomes systems programming. Aliasing, stale references, leaks — the tensor is a pointer wearing a vector's clothes.
“The torch tensor and NumPy array will share their underlying memory, and changing one through an in-place operation will also change the other.”
Read in context →Stated as convenience, but it's a trap door. "Conversion is easy" and "they're the same memory" are quite different claims, and the second is the one that will surprise you at 2am.
“missing values and they are the “bed bugs” of data science, a persistent menace that you will confront throughout your career”
Read in context →The metaphor is doing more than color — bed bugs don't get solved, they get managed. A rare admission that the messiest part of the job has no clean theory.
“For categorical input fields, we can treat NaN as a category.”
Read in context →Smuggled in as a heuristic, but it's a modeling decision with teeth: it assumes missingness carries signal. Sometimes true, sometimes leakage. The text doesn't flag the difference.
“one common heuristic is to replace the NaN entries with the mean value of the corresponding column”
Read in context →Note the asymmetry with the categorical case: there, absence became information; here, it gets erased into the average. Same dataset, two opposite philosophies, one paragraph apart.
“we use order to refer to the number of axes and dimensionality exclusively to refer to the number of components”
Read in context →A small act of terminological hygiene, and the book is right to insist. "3-dimensional tensor" is the single most overloaded phrase in the field.
“in Python, as in most programming languages, vector indices start at \(0\), also known as zero-based indexing, whereas in linear algebra subscripts begin at \(1”
Read in context →The off-by-one seam between the math and the code runs through the entire book, and they're flagging it once and moving on. Every reader will trip here anyway.
“While it may be confusing to use the word tensor for both the mathematical object and its realization in code, our meaning should usually be clear from context.”
Read in context →Admirably candid, and also a shrug. The ML "tensor" has essentially nothing to do with the tensor of differential geometry — it's just an n-D array. Borrowed prestige.
“And if this was all we could do, linear algebra would not deserve its own section.”
Read in context →A rare moment of the authors admitting a subject needs to earn its keep. The dot product is being framed as the point where bookkeeping becomes mathematics.
“We can think of multiplication with a matrix \(\mathbf{A}\in \mathbb{R}^{m \times n}\) as a transformation that projects vectors from \(\mathbb{R}^{n}\) to \(\mathbb{R}^{m”
Read in context →"Projects" is loose here — a general linear map isn't a projection. Minor, but it's the one word a careful reader will trip on later when actual projections arrive.
“Not all functions are differentiable, including many that we wish to optimize, such as accuracy”
Read in context →The quiet confession of the whole field: we rarely optimize what we care about. Everything downstream — cross-entropy standing in for accuracy — follows from this one sentence.
“Compared to the \(\ell_2\) norm, it is less sensitive to outliers.”
Read in context →Dropped in as a throwaway, but this is the seed of Lasso, robust regression, and half of regularization practice. Squaring punishes the extreme; absolute value merely notices it.
“minimize the distance between representations of photos of the same person while maximizing the distance between representations of photos of different people”
Read in context →Suddenly the abstract norm has a face. This is contrastive learning smuggled in as an example — and it's the clearest statement in the section of why "how big is this vector" ever mattered.
“we believe you will be more inclined to learn more mathematics once you have gotten your hands dirty”
Read in context →An honest pedagogical wager, not a mathematical claim. It explains every omission in the chapter — and quietly bets that curiosity is produced by use rather than preceding it.
“the ratio between arc and secant approaches 1 for a large number of vertices”
Read in context →Archimedes' trick is doing double duty: it introduces limits, and it demonstrates that calculus began as a way to compute something you already believed was true.
“While this experiment lacks the rigor of a mathematical proof, we can quickly see that indeed \(f'(1) = 2”
Read in context →Note the loop they print will drift at h=1e-6 — numerical differentiation betrays itself precisely where the math says it should be best. The text doesn't say so, but the reader who runs it will see it.
A reader’s takeAI reading companion
The Chapter Bets You Learn More Math After Getting Hands Dirty
Read as one piece, this chapter is an argument disguised as a toolkit. It opens by naming seven survival skills — and the fact that "finding answers in the official documentation" sits beside linear algebra is the chapter's real thesis in miniature: deep learning is a craft with a mathematical substrate, not mathematics with some code attached. Everything that follows honors that order. Tensors come first, justified not by elegance but by two engineering facts (autodiff, GPUs) that between them carry most of the field's recent history. Then pandas and missing values, which the book calls the "bed bugs" of data science — a metaphor conceding that the messiest part of the work has no clean theory, only management. Only then does the math arrive, and it arrives rationed: linear algebra up to norms, calculus up to the chain rule, probability up to Chebyshev. The arc is deliberately upside-down relative to a math curriculum, and the authors say why — they wager that curiosity follows use rather than preceding it, and that you will learn more mathematics once your hands are dirty. That wager explains every omission, and it is the single most important thing to read the chapter in light of.
What I saw through, reading closely, is that the chapter's most consequential sentences are its asides. Reshape is introduced with a throwaway remark about row-major layout — and that remark, not any formula, is the invisible contract behind every later shape bug. In-place operations are motivated by aliasing and multiple references to the same parameters, at which point the tutorial quietly stops being math and becomes systems programming: the tensor is a pointer wearing a vector's clothes. NumPy interop is sold as convenience, but "conversion is easy" and "they share memory" are different claims, and only the second will wake you at 2am. The ℓ1 norm's lower sensitivity to outliers is dropped in a half-sentence that is actually the seed of Lasso and half of regularization practice. And the frankest line in the chapter — that many functions we wish to optimize, such as accuracy, are not differentiable — is the field's standing confession: we almost never optimize what we care about, and every surrogate loss downstream descends from that concession. The preliminaries are load-bearing in places the prose doesn't mark.
Continue reading
My sharpest judgement is that the chapter is honest about its scaffolding but inconsistent about its heuristics. It performs real terminological hygiene — order for axes, dimensionality for components; the zero-versus-one indexing seam between math and code; an open admission that the ML "tensor" shares little but a name with the tensor of differential geometry. Yet within a single paragraph on missing data it offers two opposite philosophies without flagging the tension: treating NaN as a category makes absence informative, while mean imputation erases it into the average. Both are defensible; choosing between them is a modeling decision with teeth, and it is presented as housekeeping. Smaller slips in the same register: calling a general linear map a "projection," and inviting you to verify a derivative numerically with a loop that will visibly drift at h=1e-6 — the finite-difference estimate betraying itself exactly where the limit says it should be sharpest. The probability sections, by contrast, are the chapter at full strength: the HIV example earns its surprise honestly by making conditional independence the load-bearing assumption rather than hiding it, and the frequentist/Bayesian framing, the aleatoric/epistemic split, and the 1/√n rate together give you a vocabulary for saying what kind of not-knowing you are in.
What I'd tell the reader: do not treat this chapter as a hurdle to clear before the interesting part. Read it twice — once now, once after your first model surprises you — because its payload is distributed in the parentheses. Run the code, especially the numerical-derivative loop and the shared-memory conversions; the places where the output disagrees with the prose are where you actually learn something. Hold onto the four or five sentences that are doing structural work (row-major layout, aliasing, non-differentiable objectives, ℓ1 versus ℓ2, conditional independence) and let the identities go — the library will remember those for you. And take the authors' wager seriously in both directions: they are right that you can start with this much math, and they are also telling you, politely, that you will have to come back.
Read Chapter 2 with these cards beside each passage.
Open in FeedLitraChapter 3: Linear Neural Networks for Regression
How does the bias term change what functions the model can express?
How Chapter 3 unfoldsAI-assisted
The opening: the simplest possible learning problem, fully solved. The chapter starts where almost nothing can go wrong. House prices give it a concrete regression setting — a handful of features, one numeric label — and two assumptions do all the work: the label is a linear function of the features, and whatever the linear part misses is Gaussian noise. From those assumptions the squared loss is not a stylistic preference but a consequence: write down the likelihood of the observed data, take its negative logarithm, and what remains is a squared-error term plus a constant that mentions neither the weights nor the bias. With the noise variance held fixed, minimizing squared loss is maximizing likelihood. This early identification of a loss function with a probabilistic story is the chapter's way of establishing that the objects it will use for the rest of the book are derived, not stipulated.
The first development: how to actually get the parameters, and why the easy answer doesn't generalize. Linear least squares admits a closed form, w\* = (XᵀX)⁻¹Xᵀy, and the author presents it — then immediately deflates it. The formula exists and is unique only when XᵀX is invertible, meaning the design matrix has full rank, and the entire derivation is confined to this one model family. Precisely because almost no interesting model offers such a shortcut, the text pivots to minibatch stochastic gradient descent as the general-purpose method. The defense of minibatch specifically is made on two fronts at once: full-dataset passes waste computation, while single examples waste hardware, since a matrix–vector product can be an order of magnitude more efficient than many separate operations, memory movement dominates the real cost, and layers like batch normalization misbehave outright at batch size one. The vectorization demonstration — adding two 10,000-dimensional vectors in bulk versus in a Python loop — makes the speed argument vivid, though it is worth noting it is a single micro-benchmark on a single operation, illustrative rather than decisive.
The reframing: a regression becomes a network. With the mechanics settled, the chapter performs its first conceptual turn: it redraws linear regression as a single-layer fully connected network, d given inputs feeding one computed output neuron. This is the hinge on which the whole book swings, since every later architecture is an elaboration of this picture. The author introduces the biological neuron analogy to motivate the weighted sum, then deliberately limits it — borrowing Russell and Norvig's comparison of airplanes to birds, where the initial inspiration was real but ornithology has not guided aeronautics for centuries. Biology still supplies the high-level idea of composing many simple units; the actual drivers are now mathematics, statistics and other fields. That this is an analogy rather than measured evidence is exactly its intended register: it is a caution against over-reading, not a claim about the brain.
The implementation pair: by hand, then by library. The synthetic-data section closes with framework data loaders, and the chapter then builds the same model twice. The from-scratch version — model, squared loss, an SGD routine, the epoch loop — uses nothing but tensors and automatic differentiation, on the argument that anyone who later wants a custom layer or loss must know what sits underneath. Having made that case, the text reverses its own emphasis: the concise rewrite throws out the manual parameters, loss and optimizer in favor of LazyLinear, MSELoss and torch.optim.SGD, and the shrunken code is presented as the preferred route whenever the framework already covers the need, since the library versions are optimized and tested. The manual path is reserved for researchers inventing new components, and for the cases where input dimensions require care. The two implementations are not redundant; each is doing work the other cannot.
The turn: optimization was never the real problem. Here the chapter changes subject in a way that reframes everything before it. Fitting is easy; the goal is finding patterns rather than memorizing, and training error cannot tell the two apart. The reason is structural, not incidental: the model is chosen using the very sample it is then scored on, so its training error is an optimistic, biased estimate of population error. On held-out data the model is already fixed and independent of the sample, which reduces the measurement to ordinary mean estimation and yields an honest number. The author pushes the point harder — a sufficiently powerful model can fit arbitrary labels, so low training error certifies nothing — while taking care to block the opposite misreading: it does not indicate poor generalization either, since deep networks are exactly such models and generalize well anyway. The tempting shortcut of consulting the test set is closed off by citing Ong et al. (2005), where letting test data into model selection produces absurd results even for tightly complexity-controlled models. What remains is a dedicated validation set, or K-fold cross-validation when the data is too scarce to spare one. A related correction lands in the same stretch: the target is accurate prediction on unseen inputs, not recovery of the true generating weights, since deep models generally have no unique parameter solution and even linear regression requires linearly independent features before "the" answer is defined.
The close: from a blunt instrument to a continuous dial. Having diagnosed under- and overfitting, the chapter needs a control for complexity. It first rejects the crude option — dropping features — because the count of degree-d monomials over k variables explodes, so moving a polynomial from degree 2 to degree 3 swings complexity drastically; the knob has too few, too widely spaced settings. Penalizing the squared L2 norm of the weights is the fine adjustment. Mechanically, adding that norm to the loss makes every update pull each weight toward zero, so weights shrink continuously; and because squaring punishes large components disproportionately, the cheapest way to keep the penalty small is to spread influence across many features rather than lean on a few. After contrasting L2 with L1 and deriving the update, the author demonstrates it on a deliberately harsh synthetic task — 200 dimensions, 20 training examples — where λ = 0 overfits badly and λ = 3 raises training error while lowering validation error. That trade is identified as regularization working as designed, and it is the chapter's final statement: the dataset was built to exaggerate overfitting, so the demonstration shows the mechanism clearly rather than proving a typical effect size. The chapter ends by folding weight decay into the framework's optimizer, closing the loop with the implementation lesson from its middle — the idea is now a parameter, not a piece of code you write.
Key claims, with the lines that support them
The closed-form solution for linear regression is a lucky exception, not a template for how learning should work.
The author notes the normal-equation answer w* = (XᵀX)⁻¹Xᵀy only exists and is unique when XᵀX is invertible — i.e. the design matrix has full rank — and the whole derivation applies only to linear least squares. Precisely because almost no other model offers such a formula, the chapter immediately pivots to minibatch stochastic gradient descent as the general-purpose method.
“Although analytic solutions allow for nice mathematical analysis, the requirement of an analytic solution is so restrictive that it would exclude almost all exciting aspects of deep learning.”
§3.1 Linear RegressionRead in context →
Updating on small random batches is better than either using the whole dataset or one example at a time.
Following from that pivot, the author argues on two fronts: whole-dataset passes are wasteful, while single examples squander hardware because a matrix–vector product can be an order of magnitude more efficient than many separate operations, memory movement dominates the cost, and layers such as batch normalization simply do not behave well with batches of size one. The same vectorization point is demonstrated by adding two 10,000-dimensional vectors, where one bulk operation is dramatically faster than a Python loop — though that is a single micro-benchmark on one operation.
“It is up to an order of magnitude more efficient to perform a matrix–vector multiplication than a corresponding number of vector–vector operations.”
§3.1 Linear RegressionRead in context →
Biology inspired the first artificial neurons but is no longer what drives deep learning.
The author concedes the weighted-sum unit was modeled on a cartoon of a real neuron and that biology still supplies the high-level idea of assembling many simple units. The argument against reading more into it is the analogy, borrowed from Russell and Norvig, that airplanes were inspired by birds yet ornithology has not steered aeronautics for centuries; progress now draws equally or more from mathematics, statistics and other fields. It is an analogy rather than evidence from measurement.
“Likewise, inspiration in deep learning these days comes in equal or greater measure from mathematics, linguistics, psychology, statistics, computer science, and many other fields.”
§3.1 Linear RegressionRead in context →
3 more claims
Build it by hand first, then switch to the framework — each step teaches something the other cannot.
The author first implements model, squared loss, an SGD routine and the epoch training loop using only tensors and automatic differentiation, on the grounds that anyone who later wants custom layers or losses must know what happens underneath. Having made that point, the chapter reverses the emphasis: the concise rewrite drops manual parameters, loss and optimizer for LazyLinear, MSELoss and torch.optim.SGD, shrinking the code and relying on library versions that are optimized and tested — the preferred route whenever the framework already covers what you need, with the manual path reserved for researchers inventing new components and for cases where input dimensions need care.
“Moreover, when it is time to customize models, defining our own layers or loss functions, understanding how things work under the hood will prove handy.”
§3.4 Linear Regression Implementation from ScratchRead in context →
The test set can never be used to choose a model, so a separate validation set is indispensable.
The author's reasoning starts from the fact that a sufficiently powerful model can fit arbitrary labels, so low training error alone certifies nothing about generalization — deep networks generalize well in practice yet are exactly this kind of model. Since the training score cannot adjudicate, people reach for the test set; the author cites Ong et al. (2005) showing that letting test data into model selection produces absurd results even for models whose complexity is tightly controlled. Hence a dedicated validation set, or K-fold cross-validation when data is too scarce to spare one.
“All we can say with confidence is that low training error alone is not enough to certify low generalization error.”
§3.6 GeneralizationRead in context →
Weight decay works by accepting worse training error in exchange for better validation error.
The author first rejects the cruder alternative: dropping features is too blunt, since the number of degree-d monomials over k variables explodes and even moving the polynomial degree from 2 to 3 changes complexity drastically. Penalizing the weight norm is the finer dial. On a deliberately harsh synthetic task — 200 dimensions with only 20 training examples — setting lambda to 0 overfits badly, while lambda = 3 raises training error and lowers validation error, which the author identifies as regularization working as intended. The dataset was constructed to exaggerate overfitting.
“However, simply tossing aside features can be too blunt an instrument.”
§3.7 Weight DecayRead in context →
How it works
The 3 mechanisms the chapter’s argument runs on.
Mechanism 1
Why squared loss is the natural choice
Assume the label equals a linear prediction plus Gaussian noise. Writing down the likelihood of the data and taking its negative logarithm leaves a squared-error term plus a constant that does not involve the weights or bias, so with fixed noise variance, minimizing squared loss is exactly maximizing likelihood.
Mechanism 2
Why training error flatters the model
The fitted model is chosen using the very sample it is scored on, so its training error is an optimistic, biased estimate of population error. On held-out data the model is already fixed and independent of the sample, so measuring its error becomes ordinary mean estimation and gives an honest number.
Mechanism 3
How the weight penalty shrinks and spreads weights
Adding the squared L2 norm to the loss makes the gradient pull every weight toward zero at each update, so weights shrink continuously. Because squaring punishes large components out of proportion, the cheapest way to keep the penalty low is to spread influence across many features rather than lean on a few.
Common misreadings
If a model drives its training error down to nearly zero, it must have learned the real pattern.
Because a model powerful enough to fit arbitrary labels can reach low training error regardless of whether a pattern exists, that number licenses no conclusion about new data; the author is careful to add that it does not imply poor generalization either — deep networks score low on training error and still generalize well. The honest estimate comes from held-out data, where the model is fixed before it is scored.
“All we can say with confidence is that low training error alone is not enough to certify low generalization error.”
§3.6 GeneralizationRead in context →
Training succeeds only if it recovers the true underlying weights that generated the data.
The practical target is parameters that predict accurately on unseen inputs. The author points out that for deep models unique parameter solutions generally do not exist at all, and even linear regression needs features with no linear dependence before a unique answer is defined — so exact recovery is the wrong yardstick.
“However, in machine learning, we are often less concerned with recovering true underlying parameters, but rather with parameters that lead to highly accurate prediction”
§3.4 Linear Regression Implementation from ScratchRead in context →
Key concepts in Chapter 3
- Linear regression
- Predicting a numerical target as a weighted sum of features plus a bias.
- Where it applies: Assumes the conditional mean is approximately linear and noise is well behaved; not for category prediction.
- Squared error loss
- Half the squared gap between prediction and label, averaged over examples.
- Where it applies: Its quadratic form punishes big errors but is overly sensitive to outliers.
- Minibatch stochastic gradient descent
- Update parameters using gradients from a small random batch each step. Estimate the loss gradient on a small random batch, then step the parameters against it.
- Where it applies: Batch size and learning rate are hyperparameters; randomness breaks determinism. Used here even though linear regression has a closed-form solution, because general networks do not.
- Hyperparameters
- Tunable settings not updated by the training loop, judged on a validation set.
- Where it applies: Tuned externally, e.g. by Bayesian optimization, not by gradient descent.
- Generalization
- Getting accurate predictions on data never seen during training. Whether a model's discovered pattern holds on new, unseen data rather than just the training set.
- Where it applies: Distinct from merely minimizing training loss, which is usually easy in deep learning. Only meaningful under the IID assumption; if distributions shift, nothing can be said without further assumptions.
- Single-layer fully connected neural network
- A network where every given input wires directly to the output neuron, with only one computed unit.
- Where it applies: Only one computed neuron and no hidden layers, so it cannot express nonlinear functions.
10 more concepts
- Feature dimensionality
- The number d of inputs in the input layer.
- Where it applies: Describes input width only; it says nothing about the number of outputs or layers.
- Artificial neuron
- A unit that weights incoming signals, sums them with a bias, and optionally applies a nonlinearity.
- Where it applies: A cartoonish abstraction of real neurons, not a faithful neuroscientific model.
- Data loader
- A reusable wrapper that loads, shuffles and batches data so the learning algorithm never touches raw storage details.
- Where it applies: Helps only with data plumbing; it says nothing about model quality or whether the data fits in memory.
- From scratch plus high-level API
- The book's habit of implementing a method by hand first, then redoing it with framework shortcuts.
- Where it applies: The scratch version is functional but not production-grade.
- Overfitting
- Fitting the training data more closely than the underlying distribution.
- Where it applies: Not always bad: in deep learning the best models often score far better on training than holdout data.
- IID assumption
- Training and test data are drawn independently from the same distribution.
- Where it applies: Strong, but absent it we cannot justify transferring predictions from P to a different Q.
- Model complexity
- How wide a range of labels or functions a model class can fit; measured by parameter count and by the range of values parameters may take.
- Where it applies: Hard to compare across different model classes, e.g. decision trees vs. neural networks.
- Weight decay
- Adding a penalty on the squared L2 norm of the weights to the loss, controlled by a constant lambda. Each update shrinks the weights toward zero because the L2 penalty's gradient pulls them in.
- Where it applies: Restricts parameter values rather than parameter count; lambda is a hyperparameter fit on validation data. L2 regularization may not equal weight decay for other optimizers, though shrinking weights still helps.
- Cross-validation
- Splitting training data into K subsets and rotating which one serves as validation, then averaging errors.
- Where it applies: Used when data is too scarce to hold out a proper validation set; computationally expensive.
- L1 versus L2 penalty
- L2 spreads weight across many features; L1 zeroes most out, acting as feature selection.
- Where it applies: Either is valid; the choice depends on whether even spreading or sparsity is wanted.
Reader’s notes on Chapter 3AI reading companion
“this class of shallow networks happens to comprise the set of linear models, which subsumes many classical methods of statistical prediction”
Read in context →Neat rhetorical inversion: instead of linear regression being a baby neural net, the neural net frame swallows two centuries of statistics. Pedagogically convenient, historically backwards.
“Even though we will never see any newly-built homes with precisely zero area, we still need the bias”
Read in context →Good instinct to kill the naive reading of the intercept. The bias isn't a prediction about zero-area houses; it's just the freedom to not pass through the origin.
“this quadraticity can be a double-edge sword; while it encourages the model to avoid large errors it can also lead to excessive sensitivity to anomalous data”
Read in context →The one honest crack in an otherwise smooth presentation. Squared loss is a choice with a temperament, not a neutral ruler — and that temperament is cowardice before outliers.
17 more notes
“the requirement of an analytic solution is so restrictive that it would exclude almost all exciting aspects of deep learning”
Read in context →Worth noticing the reversal: the closed form is presented as a liability, not a prize. Giving up exact answers is the price of admission to the interesting models.
“processors are a lot faster multiplying and adding numbers than they are at moving data from main memory to processor cache”
Read in context →The minibatch is usually sold as statistical variance reduction. Here the real reason is memory bandwidth. Hardware, not theory, picked the hyperparameter.
“a number between 32 and 256, preferably a multiple of a large power of \(2\), is a good start”
Read in context →Suddenly no derivation at all, just a number smuggled in with the confidence of a theorem. The honest admission is in the phrase 'a good start.'
“even if our function is truly linear and noiseless, these parameters will not be the exact minimizers of the loss, nor even deterministic”
Read in context →Quietly dismantles the fantasy that training recovers truth. Even in the best possible world the answer wobbles — and that wobble is built into the method, not the data.
“Deep learning practitioners have taken to calling the prediction phase inference but this is a bit of a misnomer”
Read in context →A rare terminological grievance aired in public. The field renamed a word it borrowed, and the authors clearly resent it on statistics' behalf.
“minimizing the mean squared error is equivalent to the maximum likelihood estimation of a linear model under the assumption of additive Gaussian noise”
Read in context →The payoff: squared loss wasn't chosen for elegance, it encodes a specific belief about noise. Which also means every time you use MSE you've assumed Gaussian errors, whether you meant to or not.
“although airplanes might have been inspired by birds, ornithology has not been the primary driver of aeronautics innovation for some centuries”
Read in context →Elegant way of letting the biology section down gently — the neuron picture earns its place as origin story and nothing more.
“What if we change the loss from \(\sum_i (x_i - b)^2\) to \(\sum_i |x_i-b”
Read in context →The whole exercise sequence is quietly teaching one lesson: your loss is a hidden claim about noise. Mean vs median, Gaussian vs Laplace — the same data, a different belief.
“Why would such a naive composition not work?”
Read in context →One line that justifies every activation function in the rest of the book. Stacking linear maps just gives you another linear map — depth without nonlinearity is theater.
“Hint: you are selling apples, not oil.”
Read in context →Best line in the exercises. Apples come in integers and never go negative; oil is continuous and divisible. Gaussian noise forgets both.
“Notebook readability demands short code fragments, interspersed with explanations, a requirement incompatible with the style of programming common for Python libraries.”
Read in context →Rare honesty: add_to_class is not good engineering, it's a pedagogical workaround for the notebook medium. Worth remembering before importing this trick into real projects — even though they invite you to.
“what could we possibly learn from synthetic data?”
Read in context →The answer is the one beginners skip: synthetic data tests the algorithm, not the world. Known ground truth is the only debugger you have for learning code.
“being able to read data in a pre-defined order may be important for debugging purposes”
Read in context →A small detail carrying real discipline: reproducibility is a design decision made differently per mode, not a global flag you flip once.
“it requires that we load all the data in memory and that we perform lots of random memory access”
Read in context →They write the slow version, then immediately name exactly why it's slow before replacing it. That's the right order — you can't appreciate DataLoader until you've felt what it hides.
“The magic number 0.01 often works well in practice”
Read in context →"Magic number" said out loud, unapologetically. Initialization scale will later turn out to matter enormously; here it's a shrug. The shrug is itself a promissory note.
“Since our loss is computed as an average over the minibatch, we do not need to adjust the learning rate against the batch size.”
Read in context →Easy to read past, but this is the coupling that bites everyone scaling up later — mean vs sum reduction silently rescales your effective step size.
“We should not take the ability to exactly recover the ground truth parameters for granted.”
Read in context →Good of them to puncture their own demo. The synthetic setup is rigged to succeed, and they say so instead of letting you mistake luck for method.
A reader’s takeAI reading companion
A perfect fit on your data proves almost nothing about learning
Read as one piece, this chapter has a double spine: it builds the simplest possible model all the way down to working code, and then immediately turns around and attacks the confidence that building it produced. The first half descends — house prices, a linearity assumption, squared loss, closed-form solution, minibatch SGD, vectorization, the maximum-likelihood reinterpretation, and finally the drawing of linear regression as a one-layer network with d inputs and one output neuron. The second half ascends into generalization — training error as a biased estimate, held-out data, validation sets and K-fold cross-validation, under- and overfitting, weight decay as an L2 penalty — and the arc only makes sense when you see that the second half is the bill for the first. You fit a model; the chapter then asks what, if anything, you have learned about the world rather than about your 20 rows of data, and answers it with a 200-dimensional synthetic task deliberately rigged so that fitting succeeds and generalizing fails.
What I saw through, mostly, is the framing. Presenting linear models as a 'class of shallow networks' that 'subsumes' classical statistical prediction is a rhetorical inversion: pedagogically smooth, historically backwards, and it quietly recruits two centuries of regression theory as a prologue to deep learning rather than its ancestor. The same move surfaces in the authors' own irritation at 'inference' being renamed to mean prediction — a borrowed word the field bent, resented here on statistics' behalf. The biological-neuron detour is given the same treatment, let down gently by the ornithology line: origin story, nothing more. Be aware of the frame while you use it, because the frame is doing argumentative work the derivations don't.
Continue reading
The sharpest judgement I'd offer is that this chapter is really a chapter about hidden assumptions, and the single most valuable thread in it is the one connecting squared loss to Gaussian noise. MSE is not a neutral ruler. Its quadraticity — the one honest crack the authors cut into their own smooth presentation — is a temperament, and that temperament is cowardice before outliers. Once you accept the maximum-likelihood equivalence, you accept that every use of MSE is an unspoken claim about how your errors are distributed, and the exercise sequence drives this home relentlessly: swap the sum of squares for the sum of absolute values and the mean becomes the median, Gaussian becomes Laplace, same data, different belief. The apples-not-oil hint is the best line in the chapter precisely because it breaks the assumption from the other direction: apples are integers and never negative, and additive Gaussian noise forgets both facts. Weight decay belongs to the same family of disguised beliefs — penalizing the squared L2 norm is a prior that small weights are more plausible, not a neutral regularity, and contrasting it with L1 makes the choice visible rather than automatic.
The second thing worth seeing through is how often the 'theory' is actually hardware or pedagogy wearing theory's clothes. Minibatching is usually sold as variance reduction; here the stated reason is that processors multiply far faster than they move data from memory to cache — bandwidth, not statistics, picked that hyperparameter. The follow-up, 'a number between 32 and 256, preferably a multiple of a large power of 2,' arrives with no derivation at all, carrying the confidence of a theorem; the honest word in the sentence is 'start.' Initialization at 0.01 is explicitly labeled a magic number, a shrug that is really a promissory note, since initialization scale will later matter enormously. And add_to_class is admitted outright to be a workaround for the notebook medium, not good engineering — remember that before you import the trick into real code, however warmly they invite you to. Likewise the closed-form solution, which is introduced and then demoted: exactness is presented as a liability, because requiring it would exclude almost everything interesting. Giving up exact answers is the price of admission.
A few quieter details reward attention more than their size suggests. Because the loss averages over the minibatch, the learning rate needs no rescaling with batch size — easy to skim, and exactly the mean-versus-sum coupling that silently rescales effective step size for everyone who later scales up. Reading data in a fixed order for debugging while shuffling for training is reproducibility as a per-mode design decision, not a global flag. Writing the slow in-memory loader first and naming precisely why it is slow before replacing it is the right order; you cannot appreciate what DataLoader hides until you have felt it. And the parameters recovered by SGD are not the exact minimizers, nor even deterministic, even when the function truly is linear and noiseless — the wobble is a property of the method, not of the data.
What I'd tell the reader: the from-scratch implementation and the concise PyTorch rewrite are the same model twice, and the point is not the second one. Write the first, and the synthetic-data section is what makes it possible to debug — known ground truth is the only oracle your learning code will ever have, which is the whole answer to the beginner's question of what you could possibly learn from fake data. Then take seriously the authors' own warning not to take exact recovery of ground-truth parameters for granted; they puncture their own demo so you don't mistake a rigged success for a method. Finally, do not skip the exercise asking why composing two linear layers gets you nothing. That one line, answered honestly, is the justification for every activation function in the rest of the book: stacking linear maps yields another linear map, and depth without nonlinearity is theater. The chapter closes having given you a working model, a loss you now know is an assumption, an optimizer shaped by cache lines, a penalty that is really a prior, and an honest account of why none of it guarantees you have learned anything — which is a better foundation than a tidier chapter would have left.
Read Chapter 3 with these cards beside each passage.
Open in FeedLitraChapter 4: Linear Neural Networks for Classification
Why does a redundant parametrization with one output per class beat using q-1 outputs?
How Chapter 4 unfoldsAI-assisted
The opening: a change of question. The chapter begins by swapping out the question that regression answered. Instead of "how much," the task is now "which category," and the author works through what that substitution costs structurally. Labels become one-hot vectors; the output layer grows to one affine unit per class; and because those raw scores can be negative or sum to anything at all — the mansion example shows a linear estimate of purchase likelihood sailing past 1 — they need to be squashed into something readable as a probability. Softmax does the job in two moves: exponentiate to force positivity, divide by the sum to force totality. The loss then arrives not by stipulation but by derivation. Assuming labels are drawn independently, the dataset's likelihood is the product of per-example probabilities; products are awkward to optimize, so taking the negative logarithm converts the product into a sum — and that sum is cross-entropy. The author closes the opening by reading the same objective information-theoretically, so that one formula has been reached from two directions before any code is written.
The development: from exercises to working tooling. Having established the objective, the chapter shifts register and starts building. Fashion-MNIST is introduced to replace MNIST as the benchmark — a deliberate upgrade in difficulty rather than a neutral change of dataset. A Classifier base class is factored out to report accuracy, and softmax regression is implemented from scratch against the cross-entropy loss just derived. The concise framework implementation follows, and it is here that the chapter makes its most pointed engineering observation: softmax and cross-entropy should not be computed as two separate steps. Single-precision floats span roughly 1e-38 to 1e38, so logits outside about [-90, 90] destroy a naive softmax. Shifting every logit by the largest one leaves the result mathematically identical while capping the numerator at 1 and bounding the denominator between 1 and the number of classes. Worth noting what the chapter does not claim: the LogSumExp fusion rules out overflow, but strongly negative shifted logits can still underflow to zero, and the logarithm of zero yields NaNs that only surface during backpropagation. The fix is directional, not total.
The turn: training accuracy proves nothing. The chapter's hinge is the admission that everything built so far measures the wrong thing. It pivots to the test set — and then, in a characteristic double movement, undermines the pivot. A fresh test set gives an unbiased estimate of population error, but only at a rate of one over the square root of the sample size: about 10,000 examples for ±0.01 at 95% confidence, roughly 15,000 if you want a finite-sample guarantee via Hoeffding, with the finite-sample bound being the more conservative. Doubling precision quadruples the data. Worse, the guarantee evaporates on reuse. The "3am idea" story makes this concrete: having seen how f1 scored on the holdout, the researcher designs f2, which is therefore shaped by test data; across twenty candidate classifiers, there may be no power left to rule out chance at all. The chapter then escalates to statistical learning theory, looking for uniform convergence bounds — and VC dimension delivers them cleanly on simple classes (a linear model on d inputs has VC dimension d+1; a line can shatter three points in the plane but not every arrangement of four). The escalation ends in honest failure. Deep networks have millions of parameters, can memorize random labels, and often generalize better as they grow; a priori guarantees in that regime would demand something like trillions of examples while practitioners succeed with thousands. Both tools — holdout and uniform convergence — are shown to formalize generalization without explaining it.
The second turn: the distribution itself moves. Having exhausted what can be said while assuming train and test come from the same source, the chapter attacks that assumption. It first establishes why shift must be restricted rather than treated in general: with unconstrained shift, the inputs could stay pixel-for-pixel identical while every cat/dog label is swapped, a scenario indistinguishable from no shift whatsoever, so no robust learning is possible. This licenses the taxonomy that follows. Covariate shift admits a genuinely clever correction — you cannot observe either input density, but you can label training points "source" and test points "target," fit a logistic classifier, and read its odds as the density ratio, so exp(h(x)) becomes the importance weight each training example carries into a reweighted risk minimization. The correction has a hard precondition the chapter is explicit about: where the target assigns positive probability and training assigns zero, the weight is infinite and the method breaks. Coverage is required, not merely desirable. Label shift is recovered from the confusion matrix and mean test predictions; concept shift calls for gradual fine-tuning. The failures motivating all this are historical, not hypothetical — the Army tank detector that had learned trees-with-shadows versus trees-without, and the startup that used campus student donations as healthy controls and burned its funding on extreme covariate shift.
The close: accuracy is the wrong thing to optimize. The chapter ends by widening the frame past the i.i.d.-and-static picture entirely, sketching a taxonomy of learning settings — batch, online, bandits, control, reinforcement learning — and then landing on the consequence that makes this chapter's accuracy talk look insufficient. Deploying a model means automating decisions, and automated decisions reshape the distribution they were evaluated on. Predictive policing closes the loop visibly: flagged neighborhoods get more patrols, more patrols surface more recorded crime there, that record trains the next model, and each round escalates. The loan example is the same mechanism in miniature and in comic form — grant credit by footwear and soon every applicant wears Oxfords, with no improvement at all in actual credit-worthiness. So the chapter that opened by deriving a clean loss from maximum likelihood closes by arguing that minimizing that loss well is not the same as having built something that works, and that feedback loops and fairness belong inside the evaluation rather than after it.
Key claims, with the lines that support them
Cross-entropy is not an arbitrary scoring rule — it drops out of maximum likelihood estimation.
If each label is drawn independently, the likelihood of the whole dataset is the product of the per-example label probabilities. Products are awkward to optimize, so the author takes the negative logarithm, which turns the product into a sum of per-example losses — exactly cross-entropy. The step depends on the independence assumption.
“We will rely on maximum likelihood estimation, the very same method that we encountered when providing a probabilistic justification for the mean squared error loss in Section 3.1.3.”
§4.1 Softmax RegressionRead in context →
A test set's error approaches the true population error only at a rate of one over the square root of the sample size, so extra precision is bought at a steep price.
To be 95% confident that the measured error sits within ±0.01 of the truth, roughly 10,000 test examples are needed, and a guarantee that also holds in finite samples (Hoeffding) demands about 15,000 — finite-sample bounds being the more conservative of the two. Doubling precision therefore means quadrupling the data.
“Thus, to estimate our test error twice as precisely, we must collect four times as large a test set.”
§4.6 Generalization in ClassificationRead in context →
Having granted that a fresh test set gives an unbiased error estimate, the author immediately warns that it stops being trustworthy the moment it is reused.
The '3am idea' story makes it concrete: after seeing how f1 scored on the holdout, the researcher designs f2, so the second model was itself shaped by test data. With twenty candidate classifiers one may have no power left to rule out chance at all. How bad it gets depends on holdout size and on whether the set merely tunes hyperparameters or leaks information straight into model design.
“Once the same test set is used to evaluate multiple models, controlling for false discovery can be difficult.”
§4.6 Generalization in ClassificationRead in context →
3 more claims
Classical complexity measures cannot account for why deep networks generalize, so guarantees derived from them are intellectually valuable but practically unusable.
The theory works cleanly on simple classes — a linear model on d inputs has VC dimension d+1, and a line can label any three points in the plane but not every arrangement of four. Deep networks, by contrast, have millions of parameters and can memorize random labels, yet they generalize on real tasks and often get better as they get bigger; a priori guarantees in that regime would call for something like trillions of examples while practitioners succeed with thousands.
“Nevertheless, they generalize well on practical problems and, surprisingly, they often generalize better, when they are larger and deeper, despite incurring higher VC dimensions.”
§4.6 Generalization in ClassificationRead in context →
Without some assumption about how training and test distributions relate, no robust learning is possible — which is why the chapter names specific, restricted kinds of shift instead of treating shift in general.
If the shift is unconstrained, the inputs could stay pixel-for-pixel identical while every cat/dog label is swapped, a situation indistinguishable from no shift at all. The failures are real, not hypothetical: an Army tank detector turned out to have learned only trees-with-shadows versus trees-without, and a startup that used campus student donations as healthy controls met extreme covariate shift and burned its money.
“Absent any assumptions on how \(p_S\) and \(p_T\) relate to each other, learning a robust classifier is impossible.”
§4.7 Environment and Distribution ShiftRead in context →
Putting a model into production means automating decisions, so accuracy alone is the wrong thing to evaluate — the deployment can reshape the very distribution it was measured on.
Predictive policing closes a loop: neighborhoods flagged as high-crime receive more patrols, more patrols uncover more crime there, and that data trains the next model, escalating with each round. The author's loan example runs the same way in miniature — grant credit by footwear and soon every applicant wears Oxfords, with no improvement whatsoever in actual credit-worthiness.
“Among other consequences of this change of scope, we will find that accuracy is seldom the right measure.”
§4.7 Environment and Distribution ShiftRead in context →
How it works
The 3 mechanisms the chapter’s argument runs on.
Mechanism 1
Softmax turns scores into probabilities
An affine layer's outputs can be negative or add up to anything; the author's mansion example shows a linear estimate of purchase likelihood running past 1. Exponentiating each score makes it positive and dividing by the sum forces the outputs to total one, so they can finally be read as class probabilities.
Mechanism 2
Subtracting the max logit stops overflow
Softmax computed naively exponentiates raw logits, and single-precision floats only span about 1e-38 to 1e38, so logits outside roughly [-90,90] blow up. Shifting every logit by the largest one leaves the result unchanged but caps the numerator at 1 and keeps the denominator between 1 and the number of classes, so the exponentials stay in range.
Mechanism 3
A source-vs-target classifier supplies the weights
Under covariate shift you cannot see the two input densities, but you can label training points as 'source' and test points as 'target' and fit a logistic classifier. Its odds equal the ratio of the two densities, so exp(h(x)) becomes the importance weight that each training example carries into a reweighted risk minimization.
Common misreadings
Once softmax is folded into the cross-entropy loss, the numerical trouble is handled and the computation is safe for any inputs.
The trick genuinely rules out overflow, because shifting by the largest logit caps the numerator at 1 and bounds the denominator. What remains is the other direction: strongly negative shifted logits can underflow all the way to zero, and taking the logarithm of zero produces NaN values that surface during backpropagation.
“But instead of passing softmax probabilities into our new loss function, we just pass the logits and compute the softmax and its log all at once inside the cross-entropy loss function, which does smart things like the “LogSumExp trick”.”
§4.5 Concise Implementation of Softmax RegressionRead in context →
Importance weighting repairs any covariate shift, as long as you have some unlabeled data from the target domain.
The reweighting only works where the training distribution actually covers the target's support. At a point the target assigns positive probability while the training distribution assigns zero, the weight is infinite and the correction breaks down — so coverage is a precondition, not a detail.
“For this scheme to work, we need that each data example in the target (e.g., test time) distribution had nonzero probability of occurring at training time.”
§4.7 Environment and Distribution ShiftRead in context →
Key concepts in Chapter 4
- Classification
- Predicting which category an example belongs to instead of how much. Predicting which of several discrete classes an example belongs to, usually by picking the highest predicted probability.
- Where it applies: Practitioners use one word for hard assignments and for probability estimates. Hard prediction discards the probability information that some applications need.
- One-hot encoding
- A vector with one component per category, 1 for the true class and 0 elsewhere.
- Where it applies: Used because classification classes usually have no natural ordering; ordered classes may suit ordinal regression.
- Softmax
- Exponentiate each output then divide by the sum, turning logits into a valid probability vector.
- Where it applies: Order-preserving, so argmax needs no softmax; large values risk overflow.
- Cross-entropy loss
- Negative log-probability the model assigns to the true label, summed over classes. A trainable loss such as cross-entropy stands in for the non-differentiable metric we actually care about.
- Where it applies: Bounded below by 0 for probability vectors; zero is unreachable with finite weights. A naive log implementation is numerically unsafe near zero probabilities.
- Entropy
- Expected surprisal under the true distribution; the floor on how far data can be compressed.
- Where it applies: Measured in nats when using base e rather than bits.
- Surprisal
- How surprised you are by an event, measured as minus the log of the probability you gave it.
- Where it applies: Subjective: depends on the probabilities the observer assigned.
20 more concepts
- Fashion-MNIST dataset
- A 10-category clothing image dataset at 28x28 pixels, used as a small stand-in for ImageNet.
- Where it applies: Still tiny and grayscale, so it cannot reveal problems that only appear with large multi-channel data.
- Classification accuracy
- The fraction of predictions that match the true label.
- Where it applies: Not differentiable, so it is measured rather than directly optimized.
- Numerical overflow and underflow in softmax
- Exponentiating large positive or large negative logits exceeds or collapses below what a float can represent.
- Where it applies: Mitigated by subtracting the max logit, but log 0 can still appear downstream.
- LogSumExp trick
- Compute log-softmax directly from logits as o_j - max - log sum exp(o_k - max), never forming raw probabilities.
- Where it applies: Keep plain softmax around when you actually want output probabilities.
- Population error vs empirical error
- The true expected error over the data distribution versus the observed error fraction on a finite dataset.
- Where it applies: The estimator is unbiased only for a classifier chosen without touching that dataset.
- Adaptive overfitting
- Once test results influence which model you build next, the test set stops being a clean test set.
- Where it applies: Worst-case theory is bleak, but practice suggests these analyses may be too conservative.
- Uniform convergence
- A guarantee that every classifier in a function class has empirical error close to true error simultaneously. Every model in a class has its training error close to its true error at once, so picking the best training model is safe.
- Where it applies: Needed because learned classifiers are selected using the same data they are scored on. Must depend on some property of the model class; impossible for memorizers.
- VC dimension
- The largest number of points a model class can label in every possible way.
- Where it applies: Useful in statistical theory, but powerless as applied to deep networks.
- Bias-variance trade-off
- Flexible classes fit training data but may overfit; rigid classes generalize but may underfit.
- Where it applies: Framed historically as the central question of learning.
- Covariate shift
- Input distribution changes while the labeling rule P(y|x) stays fixed.
- Where it applies: Natural when x causes y; correction needs features from the target distribution, not labels.
- Label shift
- The label marginal P(y) changes while P(x|y) stays fixed.
- Where it applies: Reasonable when y causes x, e.g. diseases causing symptoms.
- Concept shift
- The meanings of the labels themselves drift over time or place.
- Where it applies: Often gradual in time or geography, which makes it hard to notice.
- Empirical risk
- Average loss on the training data, used as a stand-in for the true expected loss.
- Where it applies: Only an approximation, since the whole population is unavailable.
- Importance reweighting
- Weight each training example by p(x)/q(x) so wrong-source data imitates the target distribution.
- Where it applies: The ratio is unknown and must be estimated, e.g. by logistic regression.
- Covariate shift correction
- Separate source from target data with a classifier, then weight each training point by exp(h(x)) when minimizing empirical risk.
- Where it applies: Requires every target point to have had nonzero probability at training time; otherwise weights blow up.
- Label shift correction
- Labels change frequency but class-conditional inputs do not, so weights are label likelihood ratios p(y)/q(y).
- Where it applies: Needs an accurate classifier, an invertible confusion matrix, and no unseen categories.
- Confusion matrix
- A k-by-k table whose cell c_ij is the fraction of validation predictions where the truth was j and the model said i.
- Where it applies: Estimated on validation data from the training distribution, not on unlabeled target data.
- Concept shift correction
- The task itself drifts slowly, so you fine-tune existing weights on new data instead of retraining from scratch.
- Where it applies: Abrupt redefinition of the task may require collecting new labels and starting over.
- Online learning
- Data arrives one sample at a time; you predict first, then see the label and incur a loss, updating the model each round.
- Where it applies: Distinct from batch learning, where a trained model is deployed and never updated.
- Runaway feedback loop
- A model's own decisions reshape the data it later trains on, amplifying its initial bias.
- Where it applies: Arises only when deployed predictions influence future data collection.
Reader’s notes on Chapter 4AI reading companion
“Regression is the hammer we reach for when we want to answer how much? or how many? questions.”
Read in context →Nice framing, but the hammer metaphor cuts against the authors: the next paragraph is entirely about how often the hammer is the wrong tool.
“Which section of the book are you going to read next?”
Read in context →They slip the reader into the example list — you become a classification target mid-sentence. Cheeky, and it makes the abstraction stick.
“even when we only care about hard assignments, we still use models that make soft assignments”
Read in context →This throwaway line is the real reason softmax exists. Soft outputs aren't for us, they're for the gradient — hard decisions have nothing to descend.
17 more notes
“but for reasons of symmetry we use a slightly redundant parametrization”
Read in context →Worth pausing: they admit the model is over-parametrized and shrug. That redundancy means the weights aren't unique — a whole class of solutions gives identical predictions.
“the probability might exceed \(1\) when it comes to buying a mansion!”
Read in context →The joke does real work — it shows the failure isn't abstract, it's what linearity does the moment you extrapolate.
“Following Gibbs’ idea, energy equates to error.”
Read in context →Six words doing enormous conceptual lifting. The whole physics digression exists to license this one analogy — and it's genuinely why "temperature" survives in sampling code today.
“This can never happen for any finite setting of the weights”
Read in context →So the loss has an infimum it can never reach. Training is permanently chasing an unattainable zero — which is also, quietly, why weights drift ever larger without regularization.
“the derivative is the difference between the probability assigned by our model”
Read in context →The payoff of the whole section. All that exp-and-normalize machinery collapses to prediction minus truth — same shape as squared error, and they're right that it's no coincidence.
“Easy to predict, easy to compress.”
Read in context →Five words that make the entire prediction-compression equivalence feel obvious in hindsight. This is the sentence the rest of modern language modeling rests on.
“This skewed algorithmic development towards specific families of algorithms”
Read in context →A sharp historical claim buried in a dataset description: the benchmark shaped the research, not just measured it. Benchmarks are never neutral.
“Humans are very good at spotting oddities and because of that, visualization serves as an additional safeguard”
Read in context →The one genuinely human step in the pipeline, and it's framed as a debugging tool. Your eyes as a unit test.
“Although it can be difficult to optimize accuracy directly (it is not differentiable), it is often the performance measure that we care about the most.”
Read in context →The quiet admission that the whole apparatus optimizes a proxy. Cross-entropy is a stand-in we tolerate because it has gradients.
“The (logarithm of the) denominator is called the (log) partition function. It was introduced in statistical physics”
Read in context →A nice reminder that softmax is Boltzmann in disguise — the normalization isn't a trick, it's borrowed thermodynamics.
“you should not use this code verbatim for any serious purpose”
Read in context →Teaching code that announces its own unfitness. Honest, and oddly rare — most tutorials let you find out via NaN.
“we have reached what would arguably be the state of the art of 1960–1970s of statistical modeling”
Read in context →Deflating in the best way. Fifty pages of machinery to arrive at where statisticians already were — the point is the scaffolding, not the model.
“hiding the sharp edges also comes with a price: a disincentive to add new and different components on your own”
Read in context →The sharpest paragraph in the segment. Abstraction protects you from the bug and from the knowledge of the bug.
“Is it always a good idea to return the most likely label? For example, would you do this for medical diagnosis?”
Read in context →An exercise smuggling in the real question: argmax assumes all errors cost the same, which is almost never true outside benchmarks.
“we can attain perfect accuracy on the training set by just memorizing the dataset on the first training epoch”
Read in context →The cleanest refutation of training accuracy I've seen — not a warning but a constructive proof that the number is worthless.
“these guarantees suggest that ensuring generalization of deep neural networks a priori requires an absurd number of examples (perhaps trillions or more)”
Read in context →Rare for a textbook to admit upfront that the theory it's about to teach doesn't work on the thing you care about. Honest, but it makes the next ten pages feel like a museum tour.
“thus be 95% confident that \(\epsilon_\mathcal{D}(f) \in \epsilon(f) \pm 0.01\), then we will need 10,000 samples!”
Read in context →And then the quiet punchline: that's exactly why benchmark test sets are 10,000. The number wasn't chosen by nature, it was chosen by this calculation.
A reader’s takeAI reading companion
Temperature still appears in sampling code because of partition functions
Read end to end, this chapter has a shape that its title doesn't advertise. It opens as a tidy derivation — swap 'how much' for 'which one', encode labels as one-hot vectors, give each class its own affine score, squash the scores into a simplex with softmax, and recover cross-entropy as nothing more than maximum likelihood written out. That part is beautifully economical, and its best moments are the asides: that we use soft outputs even when we only want hard answers (hard decisions have no gradient to descend), that the parametrization is knowingly redundant so the solution is a whole equivalence class rather than a point, that the loss has an infimum it can never attain — which is quietly why unregularized weights wander outward forever. The physics detour pays for itself in one line, 'energy equates to error', and that single analogy is why the word 'temperature' still appears in sampling code sixty years later; the normalizing denominator isn't a convenience, it's a partition function on loan from thermodynamics. All of it lands on a derivative that is just prediction minus truth, the same shape as squared error, and the authors are right that the coincidence isn't one.
Then the register shifts twice, and the shifts are the real content. First into tooling: Fashion-MNIST, a Classifier base class, from-scratch then concise implementations. Buried in the dataset description is the sharpest historical claim in the chapter — that an easy benchmark skewed which algorithm families got developed. Benchmarks don't measure a field, they steer it. The implementation sections are unusually honest about their own limits: code that announces it shouldn't be used verbatim, an admission that accuracy — the thing we actually care about — isn't differentiable and so cross-entropy stands in as a tolerated proxy, and the observation that the framework's fused softmax-plus-log-sum-exp hides a numerical cliff you'd otherwise meet as a NaN. The paragraph on abstraction's price is the best in the segment: hiding sharp edges protects you from the bug and from knowing the bug exists. And the deflation at the end — fifty pages to arrive at 1960s statistics — is correct and worth sitting with. The payoff was never the model; it was the scaffolding you can now hang anything on.
Continue reading
The second shift, into generalization, is where the chapter stops being a tutorial and starts being an argument. Training accuracy is dismissed not by warning but by constructive proof: memorize the set on epoch one. Test error estimates population error at O(1/√n), and the chapter does the arithmetic — ±0.01 at 95% confidence needs 10,000 samples — which is precisely why benchmark test sets are that size. That number was chosen by this calculation, not by nature. Then reuse of test sets, adaptive overfitting, false discovery; then uniform convergence and VC dimension, introduced alongside a frank admission that these bounds would demand trillions of examples for the networks we actually train. Teaching a theory while conceding it doesn't cover your object of interest is rare and admirable, though it does make the detour feel like a museum tour. The closing material on distribution shift is the most practically useful in the chapter — covariate shift corrected by a source-versus-target logistic classifier and exp(h(x)) reweighting, label shift recovered from a confusion matrix and mean test predictions, concept shift handled by gradual fine-tuning — and then the taxonomy and the fairness and feedback-loop discussion, which is where an exercise about medical diagnosis finally cashes out: argmax presumes every error costs the same, which is true on benchmarks and almost nowhere else.
What I'd tell a reader: the chapter's title undersells it. Linear classification is a half-hour idea; the other nine-tenths is a sustained lesson in how to distrust your own numbers. Train accuracy is worthless, test accuracy decays with reuse, theory can't certify the models we deploy, the loss we minimize isn't the quantity we want, and the data we'll meet won't be drawn from the distribution we trained on. The authors never resolve this into reassurance, and that's the honest move. Read the derivation for fluency, but read the generalization and shift sections for judgement — they're the part that stays useful after you've forgotten how to differentiate a softmax.
Read Chapter 4 with these cards beside each passage.
Open in FeedLitraChapter 5: Multilayer Perceptrons
Why are deeper networks more compact than wider ones?
How Chapter 5 unfoldsAI-assisted
The opening: dismantling the linear model. The chapter begins not with multilayer perceptrons but with an argument against what came before. Linear models, the author points out, silently commit to monotonicity — every feature pushes the output in one direction, always. Two examples break this in opposite ways. Health rises with body temperature below 37 °C and falls above it, so no single-signed coefficient can describe the relationship. And a photograph of a cat or dog keeps its label when the brightness is inverted, which ruins any rule that reads pixels one at a time. The second case points past monotonicity to a deeper problem: a feature's meaning depends on the features around it, and linear models have no way to represent interaction. So the chapter sets itself a search problem, and then immediately rules out the obvious answer. Stacking affine layers does not help, because the algebra folds weights-and-bias followed by weights-and-bias into a single weight matrix and a single bias; the extra layer buys nothing. What breaks the collapse is an elementwise nonlinearity inserted between layers, and among the candidates ReLU becomes the default — not through a training bake-off, but by comparing derivatives. ReLU's derivative either passes the input through unchanged or is zero, while sigmoid's peaks at only 0.25 at the origin and decays on both sides, so signal fades through deep stacks. Sigmoid is kept for probability outputs and for gating in recurrent models. The section ends with the universal approximation result, stated with a caveat the rest of the chapter depends on: being able to express a function says nothing about gradient descent finding it, and deeper networks are often far more compact than one enormous layer.
The development: implementation, then the mechanics underneath. Having settled the architecture, the chapter builds it twice — once from scratch, once concisely with Sequential — and observes in passing that the training loop is modular enough to carry over unchanged. Then it goes beneath the code to derive forward propagation and backpropagation and, crucially, their interdependence. Backpropagation reuses the intermediate values the forward pass produced, which means those values must stay alive until the gradients are finished. Their total size grows with both depth and batch size, which is the chapter's explanation for why training consumes far more memory than prediction and why deep networks with large batches run out of it. The derivation then hands the chapter its next topic: numerical stability. Gradients that vanish or explode as they traverse many layers, and a second, stranger failure — permutation symmetry.
The turn: from diagnosis to initialization. This is where the chapter pivots from describing the model to repairing it. The symmetry problem is the sharper of the two because optimization cannot touch it. If every hidden unit starts with identical weights, each computes the same value, so each gradient element is identical, so every unit receives the same update — forever. A wide hidden layer behaves like a single unit, and no amount of gradient descent will separate them. The remedy has to come from before training starts, which makes initialization the chapter's answer to both failures at once. The author computes an output's variance as n<sub>in</sub>·σ²·γ², which demands n<sub>in</sub>·σ² = 1; running the same calculation backward demands n<sub>out</sub>·σ² = 1. Both cannot hold, so Xavier initialization splits the difference at 2/(n<sub>in</sub> + n<sub>out</sub>). The derivation's assumptions are stated plainly — zero-mean independent inputs, nonlinearities ignored — along with the observation that it works anyway, and that initialization remains an open research area.
The second remedy: dropout as structured noise. Dropout follows as a different kind of intervention, injected during training rather than before it. Each activation is zeroed with probability p and the survivors divided by 1 − p, so the layer's expected output is unchanged while its exact pattern keeps shifting from batch to batch. The mechanism is best read through what a dropped unit does not do: it contributes no value forward and no gradient backward, so the output layer has no stable single unit to lean on and reliance spreads across the layer. Because the noise is a training device and not part of the model, it is switched off at test time.
The close: the Kaggle house-price pipeline. The chapter ends in applied mode, assembling everything into a submission. Preprocessing follows standard recipes — standardize the numeric features, fill blanks with the column mean, one-hot encode the categoricals — and these are offered as sensible defaults for this dataset rather than universal boilerplate; mean imputation in particular assumes values are missing at random, and biases the data when they are not. The loss function gets the most careful justification. Being off by \$100,000 is ruinous for a \$125,000 rural Ohio home and nearly accurate where the median passes \$4 million, so no absolute-error target serves both; taking the root mean squared gap between logarithms makes proportional error the quantity minimized, which is the right move for positive values spanning wide scales. Model and hyperparameter selection then goes through K-fold cross-validation — split the training data into K folds, validate on each in turn, average — explicitly instead of through feedback from the test set, with a wide gap between low training error and high K-fold error read as overfitting that regularization may address. The chapter closes on exercises rather than results, directing the reader to improve their score by tuning this way, to test what breaks when each preprocessing default is removed, and warning that cross-validation itself degrades if an unreasonable number of configurations is tried against it.
Key claims, with the lines that support them
Linear models are inadequate whenever a feature's meaning depends on the other features around it.
The author shows monotonicity failing in both directions: health rises with temperature below 37°C but falls above it, and a cat/dog image keeps its label when inverted, which destroys any rule that reads brightness pixel by pixel. These cases open the chapter and set up the search for a nonlinear model.
“That is, because the significance of any pixel depends in complex ways on its context (the values of the surrounding pixels).”
§5.1 Multilayer PerceptronsRead in context →
Among activations, ReLU is the default because its derivative is unusually well behaved for optimization.
Having argued that some nonlinearity is required, the author compares derivatives: ReLU's is either zero or passes the input through unchanged, while the sigmoid's derivative peaks at just 0.25 at the origin and decays toward zero on both sides, so signal fades through deep stacks. The author notes this is a property of the curves rather than a full training comparison, and keeps sigmoid for probability outputs and gating in recurrent models.
“The reason for using ReLU is that its derivatives are particularly well behaved: either they vanish or they just let the argument through.”
§5.1 Multilayer PerceptronsRead in context →
Training consumes far more memory than prediction because the backward pass depends on what the forward pass stored.
Backpropagation reuses the intermediate values produced going forward, so those values must be kept alive until gradients are finished; their total size grows with both depth and batch size, which is why deep networks with large batches run out of memory. This follows directly from the chapter's derivation of the two passes.
“Note that backpropagation reuses the stored intermediate values from forward propagation to avoid duplicate calculations.”
§5.3 Forward Propagation, Backward Propagation, and Computational GraphsRead in context →
3 more claims
No single weight variance can keep both forward activations and backward gradients stable, so Xavier initialization splits the difference.
Turning the diagnosis of vanishing and exploding gradients into a remedy, the author computes an output's variance as n_in·σ²·γ², which calls for n_in·σ² = 1, while the same calculation run backward demands n_out·σ² = 1. The two cannot both hold, so the variance is set to 2/(n_in+n_out) — a compromise derived under zero-mean independent inputs and with nonlinearities ignored, yet effective in practice.
“This leaves us in a dilemma: we cannot possibly satisfy both conditions simultaneously.”
§5.4 Numerical Stability and InitializationRead in context →
For house prices, what matters is relative error, which is why the competition scores predictions on a log scale.
Being off by $100,000 is ruinous for a $125,000 rural Ohio home but near-accurate where the median passes $4 million, so a single absolute-error target cannot serve both; measuring the root mean squared gap between logarithms makes proportional error the thing being minimized. This applies to positive quantities spanning wide scales, such as prices.
“With house prices, as with stock prices, we care about relative quantities more than absolute quantities.”
§5.7 Predicting House Prices on KaggleRead in context →
Models and hyperparameters should be chosen by K-fold cross-validation, not by feedback from the test set.
The hands-on walkthrough splits the training data into K folds, validates on each in turn and averages, and the exercises then direct the reader to raise their score by tuning hyperparameters this way; a large gap between low training error and much higher K-fold error is read as overfitting that regularization may fix. The author presents these as tasks without reporting outcomes, and warns the method breaks down if an unreasonable number of configurations is tried.
“To select the model and adjust the hyperparameters, we can use \(K\)-fold cross-validation”
§5.7 Predicting House Prices on KaggleRead in context →
How it works
The 3 mechanisms the chapter’s argument runs on.
Mechanism 1
Why stacked affine layers collapse
If a hidden layer only applies weights and a bias and is then fed into another such layer, the algebra folds the two steps into one weight matrix and one bias, so the extra layer buys no new expressive power. That is why this chapter inserts an elementwise nonlinearity between layers: it blocks the collapse and lets the stack represent non-monotone, interacting behavior.
Mechanism 2
How equal weights freeze a layer
If every hidden unit starts with the same weights, each unit computes the same value, so every element of the gradient is identical too. Gradient descent then applies the same update everywhere, and the units stay identical forever, leaving a wide hidden layer behaving like a single unit.
Mechanism 3
How dropout spreads reliance
During training each activation is zeroed with probability p and the survivors are divided by 1-p, so the layer's expected output is unchanged while its exact pattern keeps shifting. A dropped unit contributes neither a value forward nor a gradient backward, so the output layer cannot lean on any one hidden unit.
Common misreadings
Since one hidden layer with enough units can represent essentially any function, depth is a nicety and a big enough network will learn whatever you need.
Representability and learnability are separate questions: the author stresses that being able to express a function says nothing about gradient descent finding it, and that deeper networks are often far more compact than a single huge layer. This is exactly why the chapter spends its remaining pages on activation choice, gradient stability and initialization rather than on width.
“Actually learning that function is the hard part, though.”
§5.1 Multilayer PerceptronsRead in context →
The chapter's preprocessing recipe is safe boilerplate, so standardizing, filling blanks with the column mean, and one-hot encoding can be applied to any tabular data without thought.
These are presented as sensible defaults for this dataset, not guarantees — mean imputation in particular assumes the values are missing at random, and otherwise it biases the data. The author deliberately ends the section with exercises that ask what breaks when each default is removed.
“Rescaling real-valued data to zero mean and unit variance is a good default.”
§5.7 Predicting House Prices on KaggleRead in context →
Key concepts in Chapter 5
- Multilayer perceptron
- Stacked fully connected layers where the first L-1 layers learn a representation and the last acts as a linear predictor.
- Where it applies: Needs a nonlinearity between layers, otherwise it is equivalent to a single linear layer.
- Monotonicity assumption
- Linearity forces each feature to always push the output the same direction.
- Where it applies: Fails for cases like body temperature risk around 37°C.
- Activation function
- An elementwise differentiable transform, usually nonlinear, applied after the affine part of a layer.
- Where it applies: Sigmoid and tanh saturate, so their gradients vanish far from zero.
- Universal approximator
- Even one hidden layer with enough units can represent essentially any function.
- Where it applies: Representability is not learnability, and deeper nets are often far more compact.
- Forward propagation
- Computing and storing every intermediate value from input layer to output layer.
- Where it applies: Describes only value computation, not gradients.
- Backpropagation
- Walking the network backwards with the chain rule to get parameter gradients.
- Where it applies: Needs stored forward values; it computes gradients, not updates.
11 more concepts
- Vanishing and exploding gradients
- Long products of layer Jacobians can shrink to nothing or blow up, breaking optimization.
- Where it applies: Arises from depth plus activation and initialization choices.
- Permutation symmetry
- Hidden units of a layer are interchangeable, so identical initialization keeps them identical.
- Where it applies: A parametrization property; constant init makes it a practical failure.
- Xavier Initialization
- Sampling weights with variance 2/(n_in+n_out) so output and gradient scales stay roughly constant across layers.
- Where it applies: Derived assuming no nonlinearities and independent zero-mean inputs, yet works well in practice.
- Minibatch stochastic gradient descent
- Iterative parameter updates on small batches; cannot by itself break identical-weight symmetry.
- Where it applies: Dropout regularization can break the symmetry that SGD alone cannot.
- Dropout
- Randomly zeroing some activations in each layer during training and rescaling the rest, so the layer's expected output is unchanged.
- Where it applies: Applied during training only; typically disabled at test time, with uncertainty estimation as an exception.
- Co-adaptation
- A layer leaning on one specific activation pattern of the previous layer, which the authors treat as a signature of overfitting.
- Where it applies: An intuition from the original paper, not a proven mechanism.
- Smoothness
- A function should not react strongly to small input changes; training with input noise is one way to enforce it.
- Where it applies: Bishop's equivalence was proven for input noise on a linear model.
- Log-RMSE error measure
- Scoring house-price predictions by the root mean squared difference of log prices, so relative rather than absolute error matters.
- Where it applies: Appropriate when quantities span wide scales, as with prices.
- Cross-validation
- Splitting training data into K folds, validating on each in turn, and averaging the validation error to pick hyperparameters. Splitting training data into K parts to pick models and hyperparameters without touching test data.
- Where it applies: Breaks down if an unreasonably large number of hyperparameter options is tried. Costs K trainings and still only estimates generalization.
- Missing values (imputation vs deletion)
- Filling in absent entries, by default with the feature's mean.
- Where it applies: Mean replacement assumes values are missing at random; otherwise it biases the data.
- Relative error via log prediction
- Measuring discrepancy on the logarithm so proportional, not absolute, gaps count.
- Where it applies: Only for positive targets where ratios matter, such as prices.
Reader’s notes on Chapter 5AI reading companion
“linearity implies the weaker assumption of monotonicity”
Read in context →Nice ordering: they attack linearity through its cheapest consequence. If even monotonicity fails, linearity is dead without touching the harder parts.
“This approach is doomed to fail in a world where inverting an image preserves the category.”
Read in context →The one-line kill shot. Not "hard to fit" but logically incompatible — invert the pixels, label unchanged, so no fixed sign of weight can survive.
“we simply do not know how to calculate it by hand”
Read in context →Here's the real pivot of the whole chapter: not that linear models are weak, but that human feature engineering runs out. Deep learning is sold as an admission of ignorance.
17 more notes
“we gain nothing for our troubles!”
Read in context →Teaching by building a broken thing first. The reader has to feel the collapse before the nonlinearity feels necessary rather than decorative.
“Actually learning that function is the hard part, though.”
Read in context →Universal approximation is quietly demoted the moment it's introduced — existence theorem, not an engineering promise. The C-language analogy does more work than the citations.
“if subtle boundary conditions matter, we are probably doing (real) mathematics, not engineering”
Read in context →Charming, and also a confession of the field's working style. Measure zero saves them — but it's a convention, not a theorem, and they say so.
“in this case kernel methods are way more effective, since they are capable of solving the problem exactly even in infinite dimensional spaces”
Read in context →Unusually generous to the rivals in a deep learning textbook. The honest implication: depth wins on compactness, not on representational supremacy.
“imagine wanting to insert another layer between layers 42 and 43”
Read in context →The argument for abstraction is bookkeeping, not math. Frameworks exist because naming things is unbearable — a surprisingly human reason.
“in the eternal words of funk virtuoso James Brown, you must “pay the cost to be the boss”
Read in context →The textbook's one joke per section, deployed exactly where the reader is about to skim. It's bribery, and it works.
“academic papers had to allocate numerous pages to deriving update rules”
Read in context →A quiet history of labor: autodiff didn't just save time, it deleted a whole genre of publishable work.
“we need to retain the intermediate values until backpropagation is complete”
Read in context →Here's the real payoff of the whole derivation — not the chain rule, but why your GPU runs out of memory. Theory cashed out as an error message.
“Thus we are susceptible to the same problems of numerical underflow that often crop up when multiplying together too many probabilities”
Read in context →Nice move: borrow the reader's existing intuition, then immediately revoke it — matrices don't have a log-space escape hatch.
“The hidden layer would behave as if it had only a single unit.”
Read in context →Symmetry as a trap: the model stays expressive on paper while being crippled in fact. Gradient descent can't see its own degeneracy.
“This leaves us in a dilemma: we cannot possibly satisfy both conditions simultaneously. Instead, we simply try to satisfy”
Read in context →"We simply try" — the whole of Xavier init is an averaged compromise between two unsatisfiable constraints. Honest, and a little deflating.
“Though the assumption for nonexistence of nonlinearities in the above mathematical reasoning can be easily violated”
Read in context →The derivation assumed away the one thing that makes the network a network. It works anyway — which should bother us more than it does.
“optimization is merely a means to an end”
Read in context →After pages of gradients and variances, the pivot: all this machinery serves a statistical question it cannot itself answer.
“then you might want to pour yourself a drink”
Read in context →The joke is doing real work — it's how a textbook admits it can't explain its own subject without losing authority.
“our understanding of deep learning still resembles the wild west on both fronts”
Read in context →Striking that the field's canonical textbook opens its generalization chapter by conceding theory lost. Folk knowledge is named as a legitimate category of knowing.
“we can actually reduce the generalization error further by making the model even more expressive”
Read in context →This single sentence voids the complexity-vs-loss curve the book taught two chapters earlier. Note they never retract Fig. 3.6.1 — just let it stand, wounded.
“some of which seemingly restrict the model in some fashion and others that seemingly make it even more expressive, and all of which, in some sense, are applied to mitigate overfitting”
Read in context →Two opposite moves with the same justification means the justification explains nothing. Honest of them to say so; worth noticing the triple hedge of "seemingly...seemingly...in some sense."
A reader’s takeAI reading companion
Affine layers collapse back to linearity before ReLU makes it stick
Read as one movement, this chapter is a sustained argument that proceeds by first building something broken. It opens not by praising neural networks but by prosecuting linear models — and shrewdly prosecutes them through their cheapest consequence, monotonicity, since if even that fails the whole edifice falls without touching the hard parts. The image-inversion example is the kill shot: not 'linear models fit poorly' but 'no fixed sign of weight can logically survive a transformation that preserves the label.' Then comes the chapter's real pivot, easy to read past: the problem isn't that linear models are weak, it's that we no longer know how to hand-compute the features that would rescue them. Deep learning is introduced as an admission of human ignorance, not a claim of machine supremacy. The chapter then stacks affine layers, shows the collapse back to linearity, and lets the reader feel that 'we gain nothing' before ReLU arrives — so nonlinearity reads as necessary rather than decorative. Universal approximation is granted and immediately demoted in the same breath: an existence theorem, not an engineering promise, with the C-language analogy carrying more weight than the citations, and an unusually generous nod to kernel methods that concedes depth wins on compactness, not representational supremacy.
From there the texture changes from argument to engineering, and the honesty gets more interesting. The case for frameworks and Sequential turns out to be bookkeeping, not mathematics — you cannot bear to renumber layers 42 and 43 — which is a surprisingly human reason to build an abstraction. The forward/backprop derivation's true payoff is not the chain rule but the sentence about retaining intermediates: theory cashed out as the GPU out-of-memory error you will actually meet. Numerical stability borrows your intuition about multiplying many probabilities and then revokes the log-space escape hatch, because matrices don't have one. Permutation symmetry is the sharpest trap in the chapter: a model fully expressive on paper and crippled in fact, with gradient descent structurally blind to its own degeneracy. And Xavier initialization, when you read the fine print, is an averaged compromise between two constraints that cannot both be met, derived under an assumption — no nonlinearities — that assumes away the very thing making a network a network. It works anyway. That should unsettle us more than the book lets on.
Continue reading
The last third is where the chapter quietly turns on the book itself. 'Optimization is merely a means to an end' reframes everything prior as machinery serving a statistical question it cannot answer. The field's canonical textbook then concedes that theory lost — the wild west on both fronts — and promotes folk knowledge to a legitimate category of knowing. One sentence voids the complexity-versus-loss curve taught two chapters earlier, noting that more expressive models can generalize better; Fig. 3.6.1 is never retracted, only left standing, wounded. Dropout follows, and the justification for the whole regularization toolkit is admitted to cover moves in opposite directions — some restricting, some expanding — all 'in some sense' mitigating overfitting, a triple hedge that amounts to saying the justification explains nothing. The jokes (James Brown, pour yourself a drink) land exactly where a reader is about to skim, and they do real work: they are how a textbook confesses it cannot explain its own subject without forfeiting authority. The Kaggle house-price finale then drops to pure craft — standardize, mean-impute, one-hot, log-RMSE because relative error is what matters on prices, K-fold because you have no principled selection theory left to lean on.
What I'd tell a reader: the chapter's value is not the MLP, which is three lines of code, but its unusual willingness to show its seams. Read the hedges as content, not filler — 'we simply try,' 'seemingly,' 'in some sense' mark exactly where understanding stops and practice takes over. Notice that nearly every memorable result here is an existence claim or an averaged heuristic defended after the fact by its working. The derivations are worth doing not because they predict performance but because they explain failures you will otherwise meet blind: exhausted memory, dead symmetric units, gradients that vanish or blow up. And hold on to the deflating truth the chapter half-buries — depth is adopted because feature engineering ran out of ideas, and most of its machinery is honest guesswork that happens to work. That is not a reason to distrust the field; it's the right posture for working in it.
Read Chapter 5 with these cards beside each passage.
Open in FeedLitraChapter 6: Builders' Guide
How does the module abstraction change once you need custom layers with their own backward behavior?
How Chapter 6 unfoldsAI-assisted
The opening: a motivated step down in abstraction. The chapter begins not with code but with a historical argument about tooling. Deep learning libraries, the author observes, have steadily climbed in abstraction — from individual neurons, to layers, to coarse-grained blocks you assemble in a few lines — exactly as chip design climbed from specifying single transistors, to logic circuits, to writing code. That climb is the premise of the chapter and also its problem: a reader who has only ever used the high-level API has been handed finished blocks without ever seeing what they are made of. So the chapter announces itself as a "builders' guide" and lays out its itinerary up front: model construction, parameters, custom layers, saving models, and GPUs. The framing move is deliberate — this is a chapter about turning an API user into someone who can build the API's pieces.
The development: the module as the missing middle rung. The first substantive section argues that something is genuinely needed between the single layer and the finished model, and the argument is empirical rather than aesthetic. Real architectures repeat groups of layers over and over; ResNet-152, a workhorse of computer vision, is built from a pattern repeated hundreds of times, and describing it layer by layer would be impractical. (The author notes the design's pedigree — the 2015 ImageNet and COCO wins — and that the repeating-group style then spread into language and speech work.) The module is introduced as that middle rung, and its defining property is recursive composability: a module may hold other modules as children, and those children may hold modules of their own. This is what makes short code describe huge networks — you write code that manufactures and nests modules on demand rather than enumerating layers. The chapter then shows how little it takes to write your own: a constructor and a forward pass, with the rest inherited, because automatic differentiation supplies the backward pass. The hand-rolled MLP in the text defines exactly those two things. The one caveat the author flags is that inventing a genuinely new layer does require thinking about gradients.
The turn: the module is a class, not a stack. The chapter's pivotal move is to pry the module concept loose from Sequential, which is the shape most readers will have mistaken for the whole idea. Sequential is only one special kind of module — one that keeps its children in order and pipes each output into the next — and so it fits plain chains and nothing else. A module, properly understood, is just a class that defines a forward pass and holds whatever parameters it needs, which means arbitrary code is admissible inside it: branching, untrained constant terms, even loops. The demonstration is the network that keeps halving its output in a while loop until the norm falls below one — a model no stack of layers could express. From there the chapter works through the practical consequences of parameters being objects you can reach: accessing them, initializing them, and tying them so that two places in a network share one tensor.
The close: four loose ends, each a consequence of the same design. The remaining sections read as the practical residue of what came before. Lazy initialization addresses the fact that a layer's weight shape depends on how wide its input is, which the author may not know while writing the architecture; the framework therefore creates no parameters at definition time, and inspecting the first layer's weight before any data flows yields nothing at all. Push a batch of shape (2, 20) through, and the framework reads off the input width of 20 and settles the shapes forward from there. Custom layers generalizes the earlier lesson: new layers are made by subclassing the base class, with and without parameters. File I/O delivers the chapter's sharpest correction: saving a model must be split in two, because the architecture stays in code and only the parameters are written out. The author saves an MLP's parameter dictionary, constructs a fresh instance of the same class, loads the file into it, and shows the two networks agreeing on the same input. The split is forced, not stylistic — the arbitrary Python the chapter spent its middle section licensing is precisely what cannot be serialized, so a parameter file is only a mapping from names to tensors and never a self-contained model. GPUs closes on device placement: because CPU–GPU transfers are far slower than the arithmetic itself, and because the runtime has no basis for deciding where a result belongs when operands sit on different devices, it refuses to copy silently and errors out instead. The cautionary example is printing per-minibatch loss to the terminal, which trips the global interpreter lock and stalls every GPU — whereas keeping the log in GPU memory and shipping it out in large chunks does not. The chapter thus ends where it began, with the cost of abstractions you cannot see through.
Key claims, with the lines that support them
Deep learning tooling has steadily moved up in abstraction, from single neurons to layers to whole coarse-grained blocks.
The author draws a parallel with chip design, which climbed from specifying individual transistors to logic circuits to writing code; the same climb happened in neural network libraries, which is why this chapter goes back to examine what the coarse abstractions are made of.
“Over time, deep learning’s libraries have evolved to offer increasingly coarse abstractions.”
Chapter 6. Builders' GuideRead in context →
A rung between the single layer and the finished model is genuinely needed, because real architectures repeat groups of layers over and over.
ResNet-152, a mainstay of computer vision, is built from a pattern of layers repeated hundreds of times, so describing it layer by layer is impractical; this design won the 2015 ImageNet and COCO competitions and the repeating-group style then spread into language and speech work. Hence the chapter introduces the module as that middle rung.
“For example, the ResNet-152 architecture, which is wildly popular in computer vision, possesses hundreds of layers.”
§6.1 Layers and ModulesRead in context →
Writing your own module takes only a constructor and a forward pass, because automatic differentiation handles the backward pass for you.
The hand-rolled MLP in the text defines just its initializer and its forward computation and inherits the rest from the parent module class; the author notes the exception, namely that you do have to think about gradients when you are inventing a genuinely new layer.
“Note that unless we implement a new layer, we need not worry about the backpropagation method or parameter initialization. The system will generate these methods automatically.”
§6.1 Layers and ModulesRead in context →
3 more claims
Deferring initialization frees you from knowing the input dimensionality when you write the architecture.
Looking at the first layer's weight before any data has flowed through yields nothing at all, since no parameters exist yet; once a batch of shape (2, 20) is pushed through, the framework reads off the input width of 20 and fixes that layer's weight shape.
“As soon as we know the input dimensionality, 20, the framework can identify the shape of the first layer’s weight matrix by plugging in the value of 20.”
§6.4 Lazy InitializationRead in context →
Saving a model has to be split in two: the architecture stays in code and only the parameters get written out.
The author saves an MLP's parameter dictionary to a file, then builds a fresh instance of the same class in code and loads the file into it; the two networks return identical outputs on the same input. The split is forced by the fact that arbitrary Python inside a model's forward pass cannot be serialized.
“Thus, in order to reinstate a model, we need to generate the architecture in code and then load the parameters from disk.”
§6.6 File I/ORead in context →
Because cross-device traffic is expensive, the framework will not copy data for you behind your back.
Transfers between CPU and GPU are much slower than the arithmetic itself, and with operands on different devices the runtime cannot locate them together or decide where the answer belongs, so it errors out instead of guessing. The author's cautionary example is printing per-minibatch loss to the terminal: that trips the global interpreter lock and stalls every GPU, whereas keeping the log in GPU memory and shipping it out in large chunks does not.
“But transferring variables between devices is slow: much slower than computation.”
§6.7 GPUsRead in context →
How it works
The 3 mechanisms the chapter’s argument runs on.
Mechanism 1
Nesting lets short code build huge nets
A module can hold other modules as its children, and those children can hold modules of their own. So instead of spelling out every layer, you write code that manufactures modules on demand and nests them, and a handful of lines can describe a network whose repeated groups run into the hundreds.
Mechanism 2
Waiting for data to fix shapes
A layer's weight shape depends on how wide its input is, which the author may not know while writing the architecture. The framework therefore creates no parameters at definition time; the moment the first real batch arrives and the input width is known, it works forward from the first layer and settles each shape.
Mechanism 3
Why mixed-device math is refused
Moving tensors between CPU and GPU is far slower than computing on them. When operands sit on different devices the runtime has no basis for choosing where to put or compute the result, so rather than silently copying data it stops and makes the author move things explicitly.
Common misreadings
The module abstraction is basically just a stack of layers, so Sequential can express anything you need.
Sequential is only one special kind of module, one that keeps its children in order and pipes each output into the next, so it fits plain chains alone. A module is simply a class that defines a forward pass and holds whatever parameters it needs, which means a custom one can contain branching, untrained constant terms, and even loops, as with the example network that keeps halving its output in a while-loop until the norm drops below one.
“A module could describe a single layer, a component consisting of multiple layers, or the entire model itself!”
§6.1 Layers and ModulesRead in context →
Once the parameter file is on disk, the saved model is complete and can be reloaded on its own.
The file is only a mapping from names to tensors; you must first reconstruct the same architecture in code and then pour the parameters into it. The author is explicit that arbitrary code sitting inside a model does not serialize naturally, so the structure cannot travel in the parameter file.
“Thus, in order to reinstate a model, we need to generate the architecture in code and then load the parameters from disk.”
§6.6 File I/ORead in context →
Key concepts in Chapter 6
- Neural network module
- A reusable unit that can be one layer, a group of layers, or the whole model, and that nests inside bigger units.
- Where it applies: Programmatically it is just a class that must define forward propagation and store needed parameters; some modules hold no parameters at all.
- Sequential module
- A special module keeping an ordered list of child modules and feeding each one's output into the next.
- Where it applies: Only fits architectures that are plain daisy chains; anything with branching or control flow needs a custom module.
- Constant parameters
- Terms in the computation that are neither layer activations nor trainable weights, so backpropagation never updates them.
- Where it applies: They live inside the module but are excluded from optimization, e.g. a randomly drawn fixed weight matrix.
- Tied parameters
- Making two layers literally share one tensor, so editing one edits the other and their gradients sum.
- Where it applies: Requires running forward propagation once before the shared parameters can be accessed.
- Lazy initialization
- The framework waits for the first batch of real data before deciding parameter shapes.
- Where it applies: Only layers with unknown input dimension need it, but the framework still initializes sequentially from the first layer onward.
- Custom layer
- A new layer you write yourself by inheriting the base layer class and defining forward propagation.
- Where it applies: Local parameters should be created with built-in parameter functions so access, sharing, saving, and loading keep working.
2 more concepts
- Parameter dictionary
- A name-to-tensor mapping that stores a whole network's weights in one file.
- Where it applies: It stores parameters only; the architecture must be recreated in code before loading.
- Computing device
- The CPU or a specific GPU where a tensor lives and where its computation runs.
- Where it applies: cpu covers all physical CPUs and memory, while a gpu device is one card only.
Reader’s notes on Chapter 6AI reading companion
“Just as semiconductor designers went from specifying transistors to logical circuits to writing code”
Read in context →A seductive analogy — but chips abstract upward because the lower layers are correct; neural layers abstract upward while the lower layers stay statistically murky. The ladder hides more than it does in hardware.
“These insights will move you from end user to power user”
Read in context →The chapter's real pitch: not new models, but a change of social position in the field. Note how carefully it warns there's nothing new here — and still insists you can't skip it.
“we often find it convenient to speak about components that are larger than an individual layer but smaller than the entire model”
Read in context →The honest origin of the module concept: not a discovery about networks, but a convenience of speech. ResNet-152's hundreds of layers made writing them by hand tedious, and tedium bred an abstraction.
15 more notes
“A module could describe a single layer, a component consisting of multiple layers, or the entire model itself!”
Read in context →This self-similarity is the whole chapter in one line — the same interface at every scale, so composition never bottoms out. It's why nn.Sequential(NestMLP(), ..., FixedHiddenMLP()) is even sayable.
“we only need to worry about parameters and the forward propagation method”
Read in context →Autodiff is what makes the module abstraction cheap. Without it, every custom block would owe a hand-derived backward pass and nobody would compose anything for fun.
“To our knowledge, no standard neural network performs this operation.”
Read in context →A rare moment of the authors shrugging at their own example. The while-loop is deliberately useless — pedagogy choosing clarity of mechanism over plausibility, and admitting it out loud.
“In this way the system knows the added modules, and it will properly initialize each module’s parameters”
Read in context →And here's the answer to Exercise 1, planted a page early: a plain Python list is invisible to the framework's registry. The abstraction leaks exactly where bookkeeping lives.
“They are not just equal, they are represented by the same exact tensor.”
Read in context →Identity versus equality — the distinction the = 100 assignment is designed to expose. Clever teaching: mutation as proof of aliasing.
“the gradients of the second hidden layer and the third hidden layer are added together during backpropagation”
Read in context →Tossed off in one sentence, but it's the deep fact about weight tying — one tensor, two paths, summed signal. The whole reason tying works in RNNs and embeddings lives here.
“module.weight.data *= module.weight.data.abs() >= 5”
Read in context →Rejection sampling by masking — multiply by a boolean. It reproduces the stated distribution only because zeroing is one of the three cases. A neat trick that would quietly fail for almost any other target.
“it might seem that we got away with being sloppy in setting up our networks”
Read in context →Good move: name the reader's unease before explaining. They'd been writing LazyLinear for a whole chapter without asking what the shape was.
“only the first layer requires lazy initialization, but the framework initializes sequentially”
Read in context →A small confession that the mechanism is cruder than the story — shapes propagate forward one at a time, not solved globally. Hence the dummy forward pass in apply_init.
“return X - X.mean”
Read in context →A layer whose output depends on the whole batch's mean — subtly not a per-sample function. Innocent-looking, but it leaks information across examples at inference time. The book doesn't flag this.
“torch.matmul(X, self.weight.data) + self.bias.data”
Read in context →Using .data here detaches from autograd — the parameters would never receive gradients. A teaching example that quietly breaks the thing it's teaching.
“the models themselves can contain arbitrary code, hence they cannot be serialized as naturally”
Read in context →The real admission of the chapter: a neural network is a program, not a data structure. Weights are the only part that's genuinely portable.
“So we want you to be 100% certain that you want to do something slow before we let you do it.”
Read in context →A rare moment where the framework's refusal to help is framed as pedagogy. The error message is the teacher.
“like ordering your coffee in a queue rather than pre-ordering it by phone”
Read in context →The analogy is charming but sells the point short — the real cost isn't your wait, it's that the barista stands idle. Device starvation, not latency.
“it is now subject to the dreaded global interpreter lock that makes everything wait for Python”
Read in context →Thousands of dollars of silicon held hostage by a print statement. The most expensive line in deep learning is often print(loss).
A reader’s takeAI reading companion
How much of the machine can you safely forget about
This chapter reads like a toolbox being handed over, but it is really a chapter about where abstraction sits and what it costs. It opens with the semiconductor analogy and the promise of moving from end user to power user — a pitch about social position in the field rather than new models — then builds its central object: the module, admitted upfront to be a convenience of speech rather than a discovery about networks. Hundreds of ResNet layers bred tedium, tedium bred an interface, and that interface turned out to be self-similar at every scale, which is why a layer, a block, and a whole model can all be dropped into the same Sequential call. From there the chapter walks parameters (access, sharing, initialization), lazy shape inference, custom layers, serialization, and finally devices — and each stop is really the same question asked again: how much of the machine can you forget about, and what bites you when you forget the wrong part?
What I saw through is that nearly every section quietly marks where the abstraction leaks, sometimes on purpose and sometimes not. Modules compose freely only because autodiff pays for the backward pass; a plain Python list of layers vanishes from the framework's registry because bookkeeping, not math, is what the magic actually consists of; tied weights are the same tensor, so their gradients sum — one sentence that carries the entire reason weight tying works in embeddings and RNNs; lazy initialization works forward one layer at a time rather than solving shapes globally, which is why a dummy forward pass has to be smuggled into apply_init. The serialization section contains the chapter's most honest line: a network is a program, not a data structure, so only weights travel and the architecture must be rebuilt in code. And the GPU section stages the same lesson as hardware economics — the asynchronous-coffee analogy undersells it, since the cost of a stray print(loss) is not your waiting but an idle accelerator held hostage by the interpreter lock.
Continue reading
My sharpest judgement is that the teaching examples are less safe than they look, and the book does not always say so. The centered layer that subtracts a batch mean is not a per-sample function at all and leaks across examples at inference; the custom linear layer written with .data detaches from autograd, so the parameters it is teaching you to register would never actually learn; the magnitude-masking initializer reproduces its stated distribution only by accident, because zeroing happens to be one of the allowed outcomes. These are small, and a careful reader fixes them in a line — but they matter precisely because this is the chapter where you stop copying and start writing your own pieces, and the examples are the template.
To the reader: do not skim this chapter because it introduces no new model. Read it as a map of the seams. Treat every convenience — module registration, lazy shapes, saved state dicts, implicit device placement — as a contract you should be able to state in your own words, because debugging later means knowing exactly which of them you relied on. And keep the hardware analogy at arm's length: chips abstract upward from layers that are provably correct, while neural layers abstract upward from layers that remain statistically murky. The ladder here hides more than it does in silicon, and knowing what it hides is the actual promotion the chapter offers.
Read Chapter 6 with these cards beside each passage.
Open in FeedLitraChapter 7: Convolutional Neural Networks
How exactly does a convolutional layer encode pixel adjacency?
How Chapter 7 unfoldsAI-assisted
The opening: a diagnosis, not an introduction. The chapter begins by indicting the model it has just finished teaching. Flattening an image into a vector, the author observes, destroys the only thing that makes it an image: a fully connected network treats its input as an unordered list of features, so the pixels could be reshuffled at random and the model would be none the wiser. That structural argument — if the ordering can be scrambled without consequence, the spatial layout carries no information — is what creates the chapter's agenda. The promise that follows is unusually strong: convolutional networks win on two fronts at once, needing both fewer samples and less computation, with ImageNet offered as the historical verdict (it was the convolutional approach, the author says, that finally moved accuracy). That double win is also the stated reason CNNs have since migrated out of vision into sequences, graphs, and recommenders.
The development: build the operator, then hand it to gradient descent. From the motivation the text drops straight to mechanics. A convolutional layer turns out to be cross-correlation plus a scalar bias — and the author pauses to defuse the obvious objection, that true convolution flips the kernel. The flip is immaterial because the kernel is learned: a strict-convolution layer simply fits the flipped weights and emits identical outputs, so only the stored numbers differ, never the behavior. The pedagogical sequence then runs hand-designed first, learned second. The [1,-1] finite-difference edge detector is elegant precisely because the target operator was already known — and the author is careful to say that this luxury vanishes as kernels grow and layers stack. So a randomly initialized kernel is trained on a single input–output pair, and ten gradient steps drive the error to near zero and recover something almost identical to the handwritten filter. Two structural asides round out the section: stacking widens what a unit sees (after a second 2×2 layer, one output traces back through all four intermediate values to all nine original inputs, which is why depth exists), and unpadded convolution quietly eats the image — ten 5×5 layers reduce 240×240 to 200×200, discarding roughly 30%, and precisely the boundary at that. A ring of zeros buys back both size and edges. Underneath it all sits the deeper claim: because the arithmetic is simple and strictly local, nothing has to travel far in memory, so chip designers can spend their budget on fast compute rather than large memory — which is what made affordable computer vision possible, with the honest caveat that such hardware need not suit other workloads.
The turn: expressiveness arrives with a bill attached. The chapter's pivot is channels, and its tone shifts with it. Inputs and kernels become higher-dimensional tensors — multi-input kernels sum per-channel cross-correlations, multi-output kernels stack $c_o$ of them — and the 1×1 convolution emerges as the pure limiting case, a per-pixel fully connected layer that mixes channels and nothing else. Two warnings are issued here rather than celebrations. First, against the intuitive picture in which each channel privately owns a feature — one for edges, one for corners: channels are trained jointly to be useful together, so a feature typically lives as a direction in channel space, and the author explicitly sets aside the naive reading of per-channel or per-pixel independent learning. Second, against the assumption that few parameters means cheap: the cost scales as $c_i \times c_o$, and the concrete figure lands hard — a 256×256 image, a 5×5 kernel, 128 channels in and out, over 53 billion operations. Each weight is reused across a great many sliding multiplications, so parameter count and computation come apart entirely. (Block-diagonal designs are flagged as a later remedy, and a GPU as the immediate one.)
The close: the pieces assembled, and a verdict on what was actually missing. LeNet-5 arrives as the chapter's integration exercise — a two-layer convolutional encoder with sigmoid activations and average pooling, feeding dense layers of 120, 84, and 10 units — and the author trains it on Fashion-MNIST. The closing judgment is historical rather than technical: LeNet's error rates sit much nearer to those of advanced modern architectures than to the best an MLP can manage, which the author reads as evidence that the architectural idea was already right in the 1990s and only compute was absent. The final note turns that into a remark on the present: what once took months of low-level engineering is now a few minutes of framework code — an ending that quietly justifies the chapter's own from-scratch corr2d implementation as something you do once in order to understand, not every time you build.
Key claims, with the lines that support them
A fully connected network cannot take advantage of the fact that neighboring pixels belong together.
The author's reasoning is structural: such networks treat the input as an unordered list of features, so any reshuffling of the pixels would yield the same model. If the ordering can be scrambled without consequence, the spatial layout of an image carries no information for the network — which is why the chapter sets out to build layers that encode the prior that nearby pixels are related.
“Because these networks are invariant to the order of the features, we could get similar results regardless of whether we preserve an order corresponding to the spatial structure of the pixels or if we permute the columns of our design matrix before fitting the MLP’s parameters.”
Chapter 7. Convolutional Neural NetworksRead in context →
Having rejected the flattened-vector approach, the author argues convolutional networks win on two fronts at once — they need fewer samples and less computation — which explains their spread beyond vision.
The supporting case is the ImageNet benchmark, where according to the author it was only the convolutional approach that produced significant gains in accuracy; the claim is made at the level of a historical outcome rather than with detailed numbers in this part of the text.
“In addition to their sample efficiency in achieving accurate models, CNNs tend to be computationally efficient, both because they require fewer parameters than fully connected architectures and because convolutions are easy to parallelize across GPU cores”
Chapter 7. Convolutional Neural NetworksRead in context →
Filters do not have to be invented by an engineer — gradient descent can recover them from examples of inputs and their desired outputs.
The author first shows the opposite case: the [1,-1] finite-difference edge detector is elegant precisely because the target operator was already known, and that luxury disappears once kernels grow larger and layers are stacked. From there, a randomly initialized kernel trained on a single input-output pair for ten gradient steps drives the squared error to near zero and ends up almost identical to the hand-written kernel — a toy demonstration with the bias term ignored.
“Most importantly, it is not necessary that the statistician (or engineer) invents suitable filters. Instead, we can simply learn them from data.”
§7.2 Convolutions for ImagesRead in context →
3 more claims
Convolution's deeper appeal is that its arithmetic is simple and strictly local, which makes it worth building specialized hardware for.
Because each output value touches only a small neighborhood, data does not have to be shuttled from far away in memory; the author notes this lets chip designers spend their budget on fast computation instead of large memory, which is what made affordable computer vision possible. The caveat is that hardware tuned this way need not be optimal for other kinds of applications.
“As can be seen, the computation is straightforward and, most importantly, highly local. This affords significant hardware optimization and many recent results in computer vision are only possible because of that.”
§7.2 Convolutions for ImagesRead in context →
Turning to channels, the author grants they add real expressive power, then immediately warns that the flexibility is paid for by a multiplicative blow-up in computation.
The cost scales with the number of input channels times output channels, and the author makes it concrete: a 256x256 image processed with a 5x5 kernel and 128 channels in and 128 out requires over 53 billion operations, counting multiplications and additions separately. The text notes that later block-diagonal designs are one way to bring this figure down.
“Note, though, that this flexibility comes at a price.”
§7.4 Multiple Input and Multiple Output ChannelsRead in context →
Closing the chapter, the author places LeNet-5 on the modern side of the divide rather than with the earlier fully connected models, with available computation as the main thing separating it from today's networks.
The comparison runs on Fashion-MNIST: LeNet-5's error rates come out much closer to those of advanced architectures than to the best results obtainable from multilayer perceptrons, which is read as evidence that the architectural idea was already right and only compute was missing.
“One of the primary differences, as we shall see, is that greater amounts of computation enabled significantly more complex architectures.”
§7.6 Convolutional Neural Networks (LeNet)Read in context →
How it works
The 3 mechanisms the chapter’s argument runs on.
Mechanism 1
Why the flip doesn't matter
A strict convolution differs from cross-correlation only by flipping the kernel horizontally and vertically. Since the kernel is not fixed in advance but fitted to data, a strict-convolution layer simply learns the flipped weights and emits exactly the same outputs; only the stored weights differ, not the layer's behavior.
Mechanism 2
Stacking widens what a unit sees
Each output element depends only on the small input window its kernel covers, so one layer sees little. Feeding that output into another layer makes the new element depend on all the windows beneath it: after a second 2x2 layer, a single output traces back to all four intermediate values and all nine original inputs, so depth is the way to detect features over a broader area.
Mechanism 3
Why borders need padding
Every convolution without padding trims pixels off each edge, and the losses accumulate layer after layer: ten 5x5 layers turn a 240x240 image into a 200x200 one, discarding about 30% of it, and the discarded part is precisely the boundary. Adding a ring of (usually zero) pixels around the input gives the kernel room to shift, preserving both size and edge information.
Common misreadings
Each channel is a detector for one particular visual feature, learned on its own — one channel for edges, another for corners.
Channels are trained together to be jointly useful, so a single feature is often represented as a direction in channel space rather than owned by one channel; the author explicitly sets aside the naive reading in which representations are learned independently per pixel or per channel.
“Instead, channels are optimized to be jointly useful.”
§7.4 Multiple Input and Multiple Output ChannelsRead in context →
Since convolutional networks have far fewer parameters than fully connected ones, they must also be cheaper to run.
Parameter count and computation come apart here: each kernel weight is reused in a great many multiplications as the window slides, so a small parameter set can still drive an enormous number of operations — the 53-billion-operation estimate for one multi-channel layer shows the scale. This is why the author reaches for a GPU when training the model.
“While CNNs have fewer parameters, they can still be more expensive to compute than similarly deep MLPs because each parameter participates in many more multiplications.”
§7.6 Convolutional Neural Networks (LeNet)Read in context →
Key concepts in Chapter 7
- Convolutional neural network (CNN)
- A network family designed to use the spatial structure of grid data such as images.
- Where it applies: Works best where nearby elements are genuinely related; also adapted to audio, text, graphs.
- Feature dimensionality
- Images become long flat vectors when their 2D pixel grid is discarded.
- Where it applies: Flattening is only acceptable when no spatial prior exists, as with tabular data.
- Convolutional layer
- A layer that slides a kernel over the input computing cross-correlation, then adds one scalar bias; kernel and bias are its only parameters.
- Where it applies: Here single-channel and two-dimensional only; bias is a single scalar and padding is not yet applied.
- Finite difference edge detector
- The 1x2 kernel [1, -1], which outputs zero where neighboring pixels match and nonzero where they differ, approximating a horizontal derivative.
- Where it applies: Only detects vertical edges; applied to the transposed image the response vanishes.
- Learning a kernel
- Instead of designing filter weights by hand, initialize them randomly and update them by gradient descent on squared error against known outputs.
- Where it applies: Demonstrated on one known input-output pair with bias ignored; realistic cases involve many layers and channels.
- Feature engineering
- Hand-crafting the filters or features a model uses, which learned kernels replace with data-driven estimates.
- Where it applies: Still useful when the desired operator is known exactly, as with the [1, -1] edge detector.
10 more concepts
- Receptive field
- For any element of a layer, all elements of previous layers that can influence its value during forward propagation.
- Where it applies: May be larger than the actual input size; enlarging it requires stacking more layers.
- Feature map
- The output of a convolutional layer, viewed as learned spatial representations passed to the next layer.
- Where it applies: Spatial dimensions only, e.g. width and height.
- Padding
- Adding extra, usually zero-valued, pixels around the input border so the kernel has room to shift and the output does not shrink.
- Where it applies: Setting padding to kernel size minus one preserves shape; odd kernels allow symmetric padding on both sides.
- Stride
- The number of rows and columns the convolution window moves per slide; larger strides downsample the output.
- Where it applies: By default the padding is 0 and the stride is 1; output size uses a floor division.
- Channel dimension
- The extra axis (size 3 for RGB) that makes inputs and hidden representations three-dimensional tensors.
- Where it applies: Applies to inputs and hidden layers; pooling leaves it untouched while convolution sums over it.
- Multi-input-channel convolution kernel
- A kernel holding one k_h x k_w slice per input channel; per-channel results are added together.
- Where it applies: Requires the kernel's input-channel count to equal the data's.
- 1x1 convolutional layer
- A convolution whose only computation is a linear combination across channels at each pixel position.
- Where it applies: Cannot capture spatial interaction among adjacent elements; needs following nonlinearities to not be foldable.
- LeNet-5
- An early CNN: two conv layers with sigmoid and average pooling, then three fully connected layers ending in 10 class outputs.
- Where it applies: Reproduced here with a softmax layer replacing the original Gaussian activation layer.
- Convolutional encoder
- The stack of conv-plus-pooling blocks that turns an image into feature maps with more channels but smaller height and width.
- Where it applies: Its 4D output must be flattened before any fully connected layer can read it.
- Fashion-MNIST dataset
- The 28x28 grayscale clothing benchmark used here to train and judge LeNet-5.
- Where it applies: Used as a comparison point against both MLPs and far more advanced architectures like ResNet.
Reader’s notes on Chapter 7AI reading companion
“This deeply unsatisfying approach was necessary in order to feed the resulting one-dimensional vectors through a fully connected MLP”
Read in context →The word "unsatisfying" is doing real rhetorical work — the authors frame flattening as an aesthetic offense, so the fix feels inevitable rather than invented.
“Pigs usually do not fly and planes usually do not swim.”
Read in context →A sly aside: it quietly admits the prior is statistical, not absolute — and the next sentence immediately walks it back. The hedge "usually" is the whole epistemology of inductive bias in one word.
“what Waldo looks like does not depend upon where Waldo is located”
Read in context →The cleanest possible statement of weight sharing — and notice it's a claim about the world, not about math. Everything downstream is just this sentence in index notation.
17 more notes
“The switch from \(\mathsf{W}\) to \(\mathsf{V}\) is entirely cosmetic for now”
Read in context →Worth pausing: nothing has been gained yet. Re-indexing is free; the real move is that the new coordinates make the next assumption expressible. Good notation is where the argument hides.
“This is only possible if \(\mathsf{V}\) and \(\mathbf{U}\) do not actually depend on \((i, j”
Read in context →Here's the sleight of hand I want to press on — what's derived is equivariance (shift in, shift out), yet the section is titled invariance. The book flags the conflation parenthetically earlier and then uses the terms interchangeably.
“All learning depends on imposing inductive bias.”
Read in context →The chapter's honest center. The parameter savings aren't free lunch — they're a bet on the world, and the next clause names the cost of losing the bet.
“Our original definition in (7.1.3) more properly describes a cross-correlation.”
Read in context →Confessing the field's naming error and then shrugging at it. Since the kernel is learned, the flip is absorbed into the learned weights — which is why nobody cares, though the book doesn't quite say so here.
“Adding channels allowed us to bring back some of the complexity that was lost”
Read in context →This is the quiet accounting trick of the whole section: locality and sharing strip capacity out along space, channels smuggle it back in along depth. The budget was never really cut — it was relocated to where the structure actually varies.
“Note that this kernel is a special case of a finite difference operator.”
Read in context →The bridge back to classical signal processing — and it reframes "learning a kernel" as learning a differential operator. Suddenly the edge detector isn't a toy, it's calculus discretized.
“it might be impossible to specify precisely what each filter should be doing manually”
Read in context →The pivot from engineering to learning, stated as surrender rather than triumph. Gradient descent enters not because it's better in principle but because hand-design runs out of room.
“Indeed, the learned kernel tensor is remarkably close to the kernel tensor K we defined earlier.”
Read in context →A tiny, rigged demo — one unambiguous edge, one 1×2 kernel — yet it carries the book's whole thesis: don't design the filter, recover it. The modesty of the example is the point.
“the outputs of convolutional layers remain unaffected no matter such layers perform either the strict convolution operations or the cross-correlation operations”
Read in context →Learning absorbs the mathematician's complaint. If the kernel is free, flipping it is a change of coordinates, not of model — so the field keeps the wrong word with a clear conscience.
“Note that the receptive field may be larger than the actual size of the input.”
Read in context →Dropped in as a footnote, but it's the quiet justification for depth itself — the dark side of padding, where a neuron "sees" invented zeros.
“This gives us confidence that we are on the right track.”
Read in context →Here the textbook voice slips into faith. Biology resembling our architecture is reassurance, not evidence — the brain also has plenty of features we've no intention of copying.
“it allows CNNs to encode implicit position information within an image, simply by learning where the “whitespace” is”
Read in context →Delicious inversion: the zeros we added as a bookkeeping convenience become a signal the network exploits. The scaffolding leaks into the building.
“it may simply mean that some direction in channel space corresponds to detecting edges”
Read in context →The one place this section resists its own pedagogy — "channel = feature detector" is the intuition every course teaches, and it's gently withdrawn here.
“convolutional layers are typically followed by nonlinearities. This ensures that \(1 \times 1\) convolutions cannot simply be folded into other convolutions”
Read in context →Without that sentence 1×1 convolutions would be a redundancy; with it they're a design primitive. The whole justification hangs on a single activation function.
“this amounts to over 53 billion operations”
Read in context →The one number that punctures the whole "convolutions are cheap" story. Parameter savings and compute savings are not the same thing, and the book only admits it in a footnote-ish aside.
“In almost all cases, max-pooling, as it is also referred to, is preferable to average pooling.”
Read in context →Asserted twice in this section, argued nowhere. Hidden in the exercises is "why do you expect them to work differently?" — so the book knows it owes a reason and outsources it to the reader.
“vibration of the camera due to the movement of the shutter might shift everything by a pixel or so”
Read in context →Lovely move: the justification for pooling is grounded in physical hardware, not math. Invariance isn't a theoretical nicety — it's shutter slap.
A reader’s takeAI reading companion
How an aesthetic complaint becomes proof that learning needs inductive bias
Read as one piece, this chapter is an argument disguised as a tutorial, and its spine is a single move repeated at three scales: notice a structure in the world, encode it as a constraint, then pay to buy back what the constraint took away. It opens with an aesthetic complaint — flattening an image is 'deeply unsatisfying' — and that word does more work than any equation, because it makes the fix feel discovered rather than invented. From there the derivation is almost too smooth: the MLP's weight matrix is re-indexed from W to V ('entirely cosmetic for now', the book admits, which is exactly where the real argument hides, since the new coordinates are what make the next assumption sayable), then translation equivariance and locality are imposed, and the parameter count collapses. The honest center arrives in one sentence — 'All learning depends on imposing inductive bias' — and the Waldo line is its best gloss, because it is a claim about the world, not about mathematics. Everything after is that claim in index notation, hedged by 'usually': pigs usually do not fly. I'd press on two things here. First, what is derived is equivariance, yet the section is titled invariance; the book flags the conflation parenthetically and then uses the words interchangeably, which is the kind of slippage a careful reader should hold onto rather than forgive. Second, the appeal to visual cortex — 'this gives us confidence that we are on the right track' — is reassurance, not evidence; the brain has many features we have no intention of copying.
The middle sections are where the chapter quietly undoes its own economy. Padding and stride are presented as bookkeeping, but two asides outrun that framing: a receptive field can exceed the input, which is the real justification for depth, and the zeros we added for convenience become a signal the network learns to read as position — the scaffolding leaks into the building. Channels are the central accounting trick: locality and sharing strip capacity out along space, channels smuggle it back in along depth, and the budget was never cut so much as relocated to where structure actually varies. The 1×1 convolution exists as a design primitive only because nonlinearities keep it from folding into its neighbors — an entire architectural idea resting on one activation function. And then the number that punctures the chapter's own sales pitch: 53 billion operations. Parameter savings and compute savings are not the same thing, and the book concedes this almost in passing. Pooling, by contrast, gets its best justification from hardware rather than theory — shutter vibration shifting everything by a pixel — though 'max-pooling is preferable' is asserted twice and argued nowhere, with the reason outsourced to an exercise. The book knows it owes you that one.
Continue reading
The code sections are modest on purpose and that modesty is the thesis. A [1,-1] kernel detecting a vertical edge is a discretized derivative, which reframes 'learning a kernel' as learning a differential operator and pulls the whole enterprise back into classical signal processing. Then gradient descent recovers that kernel from a rigged little example — and the pivot is stated as surrender, not triumph: hand-design simply runs out of room once you cannot say what each filter should do. The cross-correlation confession belongs to the same logic. The field uses the wrong word, and nobody cares, because a learned kernel absorbs the flip; it is a change of coordinates, not of model. LeNet-5 closes the arc by showing the pieces assembled into something that works, and the aside that months of low-level engineering now take minutes is both true and worth distrusting slightly — ease of implementation is not understanding.
What I'd tell a reader: do not let the smoothness of the derivation convince you that CNNs were deduced. They were bet on. Every saving in this chapter is a wager about images — that nearby pixels relate, that identity is independent of position — and the chapter is unusually candid that losing such a bet costs you accuracy with no way to recover it from data. Read the asides as carefully as the equations; this chapter's honesty lives in its parentheses, its footnotes, and its exercises, where the conflations are flagged, the compute cost is admitted, and the unargued claims are handed to you. The equations are the easy part.
Read Chapter 7 with these cards beside each passage.
Open in FeedLitraChapter 8: Modern Convolutional Neural Networks
How exactly do dropout and ReLU change AlexNet's trainability versus LeNet?
How Chapter 8 unfoldsAI-assisted
The opening: a chronological frame and a founding argument. The chapter announces itself as a guided tour of modern CNN architectures in the order they appeared, from AlexNet to RegNet, and then immediately uses AlexNet to make its central historical claim. Before 2012, computer vision was a pipeline discipline: hand-engineered descriptors such as SIFT or SURF were extracted first and pushed into a linear or kernel classifier, with the learning algorithm treated as an afterthought. AlexNet's victory, the text argues, did not come from a clever new trick but from replacing that pipeline with learned hierarchical features — a move that only became possible once two external conditions arrived at once: ImageNet (2009), supplying roughly a million 224×224 images across 1000 categories, more than an order of magnitude beyond earlier datasets and labeled by crowdsourced vetting of search-engine candidates; and GPU compute, in the form of two 3GB GTX 580s at 1.5 TFLOPs each, whose fast convolution code became the industry-standard cuda-convnet. The opening closes on a deliberately deflationary note: the breakthrough's adoption still lagged, because the tooling did not exist — no DistBelief, no Caffe, a feature-poor Theano — until TensorFlow changed the landscape.
The development: four successive answers to "how should we spend a parameter budget?" Having established AlexNet's cost as the live problem, the chapter advances through architectures that each refine the same question. VGG answers that the budget belongs in depth organized into repeated blocks, resting on a piece of arithmetic the text treats as the mechanism behind the whole design: two stacked 3×3 convolutions reach the same pixels as one 5×5, and three of them cost about the parameters of a single 5×5 — so the same receptive field can be purchased with extra nonlinearities rather than a wider kernel, which is why deep-and-narrow stacks beat shallow-and-wide ones at equal parameter counts. VGG-11 instantiates this as five blocks with channels doubling to 512, and because those blocks are parametrized it defines a family of models rather than one network, which is why the author floats — as an arguable label, not a settled one — the idea that VGG is the first truly modern CNN. NiN then attacks what the author identifies as VGG's real bottleneck, the oversized fully connected head: a single matrix occupying nearly 400MB in FP32, against the 512MB total on a contemporaneous iPhone 4S, so the head alone could exceed a device. NiN's remedy is to delete it, ending instead with a block whose channel count equals the number of classes followed by global average pooling, cutting parameters sharply at the possible cost of slower training. GoogLeNet closes the sequence by refusing the kernel-size question altogether: where others argued which convolution width was superior, the Inception block runs several in parallel and concatenates, and nine such blocks in three groups — with a global-average-pooling head and the stem–body–head skeleton — won the 2014 ImageNet Challenge. Assembled into five stages with hand-tuned channel ratios and trained here on 96×96 Fashion-MNIST, it comes out both cheaper and more accurate, which is the result that legitimizes block-level design as the unit of thought.
The first turn: from architecture to training, and a lesson about intuition. The chapter then pivots away from topology toward normalization. Batch normalization is first presented constructively, motivated by an argument from ordinary practice: standardizing inputs keeps the estimation problem controlled and suits the optimizer, so why not do the same inside the network? It is packaged as a layer that separates the mathematics from the bookkeeping, demonstrated inside LeNet in both from-scratch and high-level forms. Then comes the chapter's most pointed critical passage. The popular explanation — that BatchNorm works by removing "internal covariate shift" — is dismissed as a misnomer and held up as the prime illustration of why guiding intuitions must be kept separate from established fact; Ali Rahimi's 2017 NeurIPS Test of Time speech invoked exactly this to compare deep learning practice to alchemy. What survives the critique is the empirical package: preprocessing, numerical stability, and a regularization effect the author frames as a serendipitous bonus rather than a design goal, in which the noise of minibatch statistics is a feature — hence the sweet spot around 50–100 examples, which Teye et al. (2018) and Luo et al. (2018) connect to Bayesian priors and penalty terms, while conceding the effect remains poorly characterized theoretically. The technique works extremely well; the story told about why does not.
The second turn: nested function classes, and the correction of a tempting inference. From there the chapter moves to what makes depth trustworthy, and here it explicitly blocks a misreading its own earlier argument invites. If deep-and-narrow beats shallow-and-wide, surely more layers are always better? No: extra layers add power only when the enlarged function class contains the smaller one. With non-nested classes, growing complexity can carry the model away from the target function, so depth is not automatically progress. Residual blocks exist precisely to guarantee nesting — each added layer can easily represent the identity, which shifts the default assumption from f(x)=0 to f(x)=x, to the point that a layer can be inserted mid-training initialized as a no-op. Only under that condition does extreme depth, like the original ResNet's 152 layers, become trainable at all. The variations follow as cost-and-capacity engineering: ResNeXt notes that widening channels is penalized quadratically whereas splitting them into g groups divides both computation and parameters by roughly g, and repairs grouping's defect — groups never see one another — by sandwiching the grouped convolution between 1×1 layers that restore cross-channel mixing at only the cheap O(c·b) cost on top of the grouped O(b²/g) work. DenseNet pushes in a different direction, replacing residual addition with concatenation, which forces transition layers to keep channel counts in check and is paid for in GPU memory.
The close: design hands the wheel to search, and then to scale. The final movement reframes everything preceding it as a story about who makes architectural decisions. GoogLeNet's channel allocations — stage three's 2:4:1:1 branch ratio obtained by cutting inputs to 96 and 16 channels — look arbitrary only because automatic design-exploration tools did not yet exist; even tensor dimensionalities had to be declared by hand, where frameworks now infer them. Manual design is workable but expensive in human time with no optimality guarantee, and exhaustive search is worse: AnyNet's 17 free parameters already yield 2¹⁷ = 131,072 combinations at merely two options each, and training stochasticity makes single runs irreproducible, so nothing general is learned (full architecture search is usually enormously expensive and returns a single network, though EfficientNets show the investment can pay). Radosavovic et al. (2020) therefore optimize distributions of networks, assuming general design rules exist, using cheap low-fidelity proxies, and comparing empirical error CDFs. The findings are concrete: tying bottleneck ratio and group width across stages costs no accuracy, widths and depths should grow across stages, and the best bottleneck ratio is k=1 — that is, none. The result is RegNetX, demonstrated here as a 32-layer model with g=16, channels 32 and 80, depths 4 and 6, trained on 96×96 Fashion-MNIST rather than ImageNet. The chapter's last word extends the trajectory one step further: with collections such as LAION-400m and LAION-5B, learned structure now beats built-in priors, so scalability outranks locality and translation invariance as a design principle — even though Transformer-derived gains can be backported into CNNs, at higher compute cost.
Key claims, with the lines that support them
Vision progress before 2012 came from hand-engineered features, and the switch to learned features only became possible once large labeled datasets and GPU compute arrived.
The author notes classical pipelines pushed SIFT or SURF descriptors into a linear or kernel model, with the learning algorithm treated as an afterthought. Then ImageNet (2009) supplied about a million 224x224 images over 1000 categories — more than an order of magnitude beyond earlier sets, labeled by crowdsourced checking of search-engine candidates — and Krizhevsky and Sutskever ran fast convolutions on two 3GB GTX 580s capable of 1.5 TFLOPs each, with the resulting cuda-convnet becoming an industry standard. Even so, adoption lagged for want of tooling: DistBelief and Caffe did not exist and Theano lacked features until TensorFlow changed the picture.
“The learning algorithm was often considered an afterthought.”
§8.1 Deep Convolutional Neural Networks (AlexNet)Read in context →
Building on AlexNet's cost, the lesson is that a parameter budget is best spent on depth organized into repeated blocks — which arguably makes VGG the first truly modern CNN.
A detailed analysis showed deep-and-narrow networks clearly outperform shallow-and-wide ones at comparable parameter counts, resting on the arithmetic that two 3x3 convolutions touch the same pixels as one 5x5 while three of them cost about the parameters of one 5x5. VGG-11 instantiates this as five blocks with channels doubling up to 512, eight convolutional and three fully connected layers, and because the blocks are parametrized it defines a whole family of models rather than a single network — the author presents the 'first modern CNN' label as arguable, not settled.
“In a rather detailed analysis they showed that deep and narrow networks significantly outperform their shallow counterparts.”
§8.2 Networks Using Blocks (VGG)Read in context →
Carrying VGG's burden forward, the author argues the oversized fully connected head is the true memory bottleneck, so NiN removes it outright.
VGG-11's single giant matrix occupies almost 400MB in FP32, against the 512MB of memory on an iPhone 4S of that era, so the head alone can exceed a device's budget. NiN therefore ends with a block whose channel count equals the number of classes plus global average pooling, which sharply reduces parameters — at the possible price of longer training.
“First, the fully connected layers at the end of the architecture consume tremendous numbers of parameters.”
§8.3 Network in Network (NiN)Read in context →
3 more claims
Instead of picking one best kernel size, the right move is to run several sizes in parallel and concatenate their outputs.
Where other work tried to determine which convolution size, starting from 1x1, was superior, the Inception block simply uses multiple branch sizes at once. The payoff is concrete: GoogLeNet, built from nine inception blocks in three groups with global average pooling in its head, won the 2014 ImageNet Challenge.
“While other works tried to identify which convolution, ranging from \(1 \times 1\) to \(11 \times 11\) would be best, it simply concatenated multi-branch convolutions.”
§8.4 Multi-Branch Networks (GoogLeNet)Read in context →
Batch normalization is valuable because it bundles three things at once — input preprocessing, numerical stability, and regularization — and the noise in its minibatch statistics is a feature, not a defect.
The argument starts from ordinary standardization: putting inputs on a similar scale keeps the estimation problem controlled and suits the optimizer, which motivates doing the same inside the network; the author calls the regularization benefit a serendipitous bonus rather than a design goal. Teye et al. (2018) and Luo et al. (2018) then tied batch normalization to Bayesian priors and penalty terms, which illuminates why minibatches of roughly 50-100 inject the right amount of noise and work best — though the effect is still poorly characterized theoretically.
“As it turns out, quite serendipitously, batch normalization conveys all three benefits: preprocessing, numerical stability, and regularization.”
§8.5 Batch NormalizationRead in context →
Architecture decisions progressively moved out of human hands — first into searched design spaces with general rules, and finally to models that simply scale.
GoogLeNet's channel allocations look arbitrary only because automatic design-exploration tools did not exist: stage three pins a 2:4:1:1 branch ratio by cutting inputs to 96 and 16 channels, and even tensor dimensionalities had to be stated by hand, whereas frameworks now infer them. Manual design is feasible but costly in human time with no optimality guarantee, while exhaustive search is worse — AnyNet's 17 free parameters already give 2^17 = 131072 combinations with only two options each, and training stochasticity makes single runs irreproducible, so nothing general is learned (full neural architecture search is usually enormously expensive and returns one network, though EfficientNets show it can pay off). Radosavovic et al. (2020) instead optimized distributions of networks, comparing empirical error CDFs: tying bottleneck ratio and group width across stages costs no accuracy, widths and depths should grow across stages, and the best bottleneck ratio turns out to be k=1, i.e. none — as in a 32-layer RegNetX with g=16, channels 32 and 80 and depths 4 and 6, trained here on 96x96 Fashion-MNIST rather than ImageNet. The chapter closes by noting that huge collections such as LAION-400m and LAION-5B let learned structure beat built-in priors, so scalability now outranks locality and translation invariance, even if Transformer gains can be backported into CNNs at higher compute cost.
“Much of it is due to the fact that at the time when GoogLeNet was introduced, automatic tools for network definition or design exploration were not yet available.”
§8.4 Multi-Branch Networks (GoogLeNet)Read in context →
How it works
The 3 mechanisms the chapter’s argument runs on.
Mechanism 1
Why stacked 3x3 kernels win
Two 3x3 convolutions reach the same pixels as one 5x5, and three of them cost roughly the parameters of a single 5x5. So the same receptive field can be bought with extra nonlinear layers instead of a wider kernel, which is why deep-and-narrow stacks of small kernels beat shallow-and-wide ones at equal parameter budgets.
Mechanism 2
Groups cut cost, 1x1 layers restore mixing
Buying capacity by widening channels is penalized quadratically, whereas splitting channels into g groups divides both computation and parameter count by roughly g. Grouping's flaw is that groups never see each other, so a 1x1 convolution placed before and after restores cross-channel mixing while paying only the cheap O(c·b) kernel cost on top of the grouped O(b^2/g) work.
Mechanism 3
Identity bias makes depth safe
If the enlarged function class does not contain the smaller one, adding layers can move the model away from the target function, so depth is not automatically progress. Residual blocks let each added layer represent the identity easily, which nests the classes and shifts the default assumption from f(x)=0 to f(x)=x — the reason networks as deep as 152 layers became trainable.
Common misreadings
Batch normalization works because it removes 'internal covariate shift' inside the network.
The author treats that phrase as a misnomer and as the prime example of why guiding intuitions must be kept separate from established scientific fact — Ali Rahimi's 2017 NeurIPS Test of Time speech used it to liken deep learning practice to alchemy. What stands up is the empirical package: the regularizing noise of minibatch statistics (hence the sweet spot around 50-100 examples, linked by Teye et al. and Luo et al. to Bayesian priors and penalties) plus preprocessing and numerical stability. The technique works extremely well even though the mechanism is still poorly characterized.
“However, we believe that it is important to separate these guiding intuitions from established scientific fact.”
§8.5 Batch NormalizationRead in context →
Since deep-and-narrow beats shallow-and-wide, piling on more layers must always make a network stronger.
Extra layers add real power only when the enlarged function class contains the smaller one; with non-nested classes, a larger class can drift away from the target function even as complexity grows. That is exactly why residual blocks are built so every added layer can easily behave as the identity — a layer can even be inserted mid-training initialized as a no-op — and only under that condition does extreme depth, like the original ResNet's 152 layers, pay off.
“At the heart of their proposed residual network (ResNet) is the idea that every additional layer should more easily contain the identity function as one of its elements.”
§8.6 Residual Networks (ResNet) and ResNeXtRead in context →
Key concepts in Chapter 8
- Representation learning
- Letting the model learn its own layered features from data instead of a human designing feature extractors.
- Where it applies: Needs large data and compute; with tiny datasets hand-crafted features plus convex methods can win.
- Feature engineering
- Hand-designing extractors such as SIFT or SURF so a simple classifier can work on top of them.
- Where it applies: Dominant before 2012; still useful when data is scarce or interpretability matters.
- AlexNet
- An 8-layer CNN that won ImageNet 2012: bigger than LeNet, ReLU activations, dropout, GPU-trained.
- Where it applies: Inefficient by modern standards; its huge fully connected layers dominate memory and FLOPs.
- GPU requirement
- Thousands of weak parallel cores give far more FLOPs and memory bandwidth than a CPU, which is what deep nets need.
- Where it applies: Advantage holds for dense parallel math, not for branchy general-purpose control flow.
- VGG block
- A stack of padded 3x3 convolutions with ReLU, ended by a 2x2 max-pooling that halves height and width.
- Where it applies: Resolution only drops at the pooling step, so depth is no longer capped by log2 of input size.
- Network in network (NiN) block
- One ordinary convolution followed by 1x1 convolutions that act like a fully connected layer at each pixel.
- Where it applies: Works only because the added nonlinearities make the later global average pooling effective.
20 more concepts
- Global average pooling
- Averaging each channel over all spatial positions to produce logits instead of a huge learned matrix. Collapsing each channel's height and width to 1 before the classifier, as in NiN.
- Where it applies: Surprisingly does not hurt accuracy, and adds translation invariance, but may lengthen training. Used only at the head, after the fifth module of GoogLeNet.
- Inception block
- Four parallel branches with different kernel sizes and pooling, concatenated along channels.
- Where it applies: Sidesteps kernel selection rather than solving it; main hyperparameter is channel allocation per branch.
- Foundation models
- Entire pretrained models reused as components for different but related tasks.
- Where it applies: Mentioned as the later stage of the same abstraction trend, not developed in this chapter here.
- Stem, body, and head
- Early convolutions ingest the image, convolutional blocks process it, and a final part maps features to the task.
- Where it applies: A naming convention for structure; the real contribution of GoogLeNet was the body design.
- Block-level network design
- Building a net from repeated multi-branch stages whose channel splits are tuned per stage rather than per layer.
- Where it applies: At the time of GoogLeNet this tuning was entirely manual, so the numbers are largely arbitrary.
- Batch normalization
- Normalizing a layer's inputs by the current minibatch mean and standard deviation, then rescaling and shifting with learned parameters.
- Where it applies: Useless with minibatch size 1 in the fully connected case; behaves differently in training versus prediction mode.
- Layer normalization
- The same standardization applied to one observation at a time, so it ignores the batch entirely.
- Where it applies: Scale independent and identical in training and test, but loses batch-noise regularization.
- Internal covariate shift
- The original claim that BatchNorm helps because layer value distributions drift during training.
- Where it applies: Named misleadingly and never rigorously established; closer to concept drift.
- Nested function classes
- Bigger architectures help reliably only when they contain the smaller ones. Adding capacity should strictly enlarge the reachable function set rather than shift it sideways; identity pass-through makes this possible.
- Where it applies: Non-nested enlargement gives no guarantee of moving closer to the truth function. Nesting alone does not justify unbounded complexity growth.
- Residual block
- A block that learns f(x)-x and adds the input back through a shortcut, so identity is easy to represent.
- Where it applies: Requires matching shapes; a 1x1 convolution is needed when channels or resolution change.
- Grouped convolution
- Split input and output channels into g independent groups so each group convolves only within itself, cutting cost and parameters g-fold.
- Where it applies: Assumes both channel counts are divisible by g, and no information crosses groups unless 1x1 convolutions are added.
- ResNeXt block
- A residual block whose 3x3 grouped convolution sits between two 1x1 convolutions that mix channels and restore width.
- Where it applies: It is a bottleneck block only when intermediate channels b are smaller than c.
- DenseNet
- A network where each layer concatenates with all preceding layers' outputs instead of adding them, reusing earlier features.
- Where it applies: Feature reuse is cheap in parameters but costly in GPU memory.
- Transition layer
- A 1x1 convolution plus stride-2 average pooling that shrinks channel count and spatial size between dense blocks.
- Where it applies: Needed precisely because each dense block keeps adding growth_rate channels.
- Growth rate
- The number of output channels each convolution block in a dense block contributes, controlling channel growth.
- Where it applies: Only describes added channels; total width also depends on input channels.
- AnyNet design space
- A template of stem, body and head, with the body split into stages of blocks at decreasing resolution, parameterized by depth, channels, groups and bottleneck ratio. A whole family of networks described by shared parameters, judged as a distribution rather than one model.
- Where it applies: It optimizes distributions of networks, not one instance like NAS does. Only useful if good designs are common enough to be sampled.
- Neural architecture search
- Automatic architecture selection by brute-force search, genetic algorithms or reinforcement learning, returning a single best network.
- Where it applies: Usually enormously expensive, which is why this chapter largely omits it.
- Multi-fidelity optimization
- Judging candidates by cheap approximate signals, like accuracy after a few epochs, instead of full training.
- Where it applies: Breaks down if early accuracy does not rank final accuracy.
- Empirical CDF of errors
- The sampled distribution of errors from a design space; one space beats another if its curve majorizes the other's.
- Where it applies: Depends on the sampling distribution p and sample size.
- RegNetX design principles
- Share bottleneck ratio and group width; increase width and depth across stages; best with no bottleneck at all.
- Where it applies: Derived from ImageNet-scale vision experiments, though it held at larger scale and for RegNetY.
Reader’s notes on Chapter 8AI reading companion
“The learning algorithm was often considered an afterthought.”
Read in context →A whole era's priorities in nine words. Worth remembering that today's consensus — architecture matters, features are learned — was once the fringe position of about six people.
“occasionally on the serendipitous discoveries by lucky graduate students”
Read in context →The one joke in a dry list, and it's also the most honest line about how research actually worked. Feature engineering as institutionalized luck.
“This apparent strength, however, is also its Achilles heel: general-purpose cores are very expensive to build.”
Read in context →The real argument of the hardware section: deep learning won not because GPUs were fast but because its math happened to be dumb enough to parallelize. A lucky coincidence with the gaming industry.
17 more notes
“if the model parameters are not properly initialized, the sigmoid function may obtain a gradient of almost 0 in the positive interval”
Read in context →This sentence is garbled — sigmoid saturates at extreme inputs, not in "the positive interval," and the clause contradicts the comparison it's drawing with ReLU. A rare slip in an otherwise careful text.
“the last two layers have more than 40 million parameters, trained on a datasets of 60 thousand images), there is hardly any overfitting”
Read in context →Quietly one of the deepest observations in the chapter: parameter count is nearly useless as a capacity measure. Classical learning theory should have forbidden this result.
“it took the academic community many years to embrace this conceptual change”
Read in context →Attributing the lag to missing tools is too kind. Kernel methods had theorems and respectability; CNNs had benchmarks. The field resisted on taste, not tooling.
“Why do engineers no longer report performance benchmarks on AlexNet?”
Read in context →The sharpest exercise here, because it isn't about AlexNet. It asks what makes a benchmark stop being informative — and the answer applies to ImageNet itself.
“this imposes a hard limit of \(\log_2 d\) convolutional layers on the network before all dimensions (\(d\)) are used up”
Read in context →A geometric accounting argument, not an empirical one — depth was bottlenecked by arithmetic. Reframing the problem this way makes the block design look inevitable rather than clever.
“the latter uses approximately as many parameters (\(25 \cdot c^2\)) as three \(3 \times 3\) convolutions do (\(3 \cdot 9 \cdot c^2”
Read in context →Note the sleight: same receptive field claimed for two 3×3s, but the parameter comparison quietly switches to three. The honest version is 5×5 ≈ 25 vs two 3×3 = 18 — cheaper AND more nonlinear.
“a design decision only to be revisited recently by Liu et al. (2022)”
Read in context →Eight years of an unexamined default. The parenthesis is the author admitting that "gold standard" mostly means nobody re-ran the experiment.
“VGG defines a family of networks rather than just a specific manifestation”
Read in context →The real contribution is a shift in object of study: from publishing a model to publishing a parameterized generator of models. arch as a list of tuples is that idea made small enough to type.
“It is no longer necessary to generate XML configuration files to specify a network”
Read in context →A quiet reminder that architectural imagination is rate-limited by notation. Blocks became thinkable partly because loops became writable.
“even high-end mobile phones sport no more than 8GB of RAM”
Read in context →The one sentence in the chapter that will date fastest — and it's doing the argumentative work for NiN. The principle survives the number, but notice the motivation is deployment economics, not accuracy.
“Note that global average pooling would not be effective, were it not for the added nonlinearities.”
Read in context →The load-bearing sentence of the whole section, and it's a throwaway aside. Averaging is only harmless because the 1×1 layers already did the per-location mixing that the FC head used to do.
“What surprised researchers at the time was the fact that this averaging operation did not harm accuracy.”
Read in context →Worth sitting with the surprise rather than skipping it: it meant the giant FC head had been mostly redundant capacity, and the field had been paying 400MB for it.
“it simply concatenated multi-branch convolutions”
Read in context →The move is refusing to answer the question. Instead of choosing a kernel size, make the choice a learnable channel allocation — architecture search smuggled inside a block.
“stemming from the meme “we need to go deeper” from the movie Inception”
Read in context →A field confident enough to name its core primitive after a joke. Charming, and also a small marker of how much of this design was vibes awaiting justification.
“the large number of relatively arbitrary hyperparameters in terms of the number of channels chosen”
Read in context →Refreshingly candid. All those 192/208/48/64 ratios get narrated as if principled, then the author admits they're brute-force residue — the explanation was retrofitted to the search result.
“the original design included a number of tricks for stabilizing training through intermediate loss functions”
Read in context →Auxiliary losses were the scaffolding depth needed before better optimization existed. Half of architecture history is crutches that later vanished.
“it is actually cheaper to compute than its predecessors while simultaneously providing improved accuracy”
Read in context →Here the chapter's real plot surfaces: the metric stops being accuracy alone and becomes accuracy per FLOP. Everything after this reads as optimization under a two-term objective.
A reader’s takeAI reading companion
Forty million parameters, sixty thousand images: AlexNet violated capacity theory
Read as one piece, this chapter is not really a museum tour of seven architectures — it is the story of how a field learned to stop designing networks and start designing spaces of networks, and the chronological order is the argument. AlexNet opens it as a historical claim: the 2012 break came less from a clever model than from the coincidence of learned hierarchical features with ImageNet-scale data and hardware whose arithmetic happened to be dumb enough to parallelize. The chapter is honest that the learning algorithm had been 'an afterthought' and that feature engineering ran on institutionalized luck, but it is too generous in blaming the field's slow turn on missing tooling; kernel methods had theorems and respectability, CNNs only had benchmarks, and the resistance was a matter of taste. What AlexNet also smuggles in — 40M parameters on 60k images with hardly any overfitting — should have been illegal under classical capacity theory, and the text drops it in a parenthesis instead of flagging it as one of the deepest unresolved facts in the book.
From there each section strips away one thing people thought was essential. VGG's real contribution is not 3×3 stacks but a change in the object of publication: a parameterized family rather than a specific manifestation, made typable as a list of tuples — architectural imagination turns out to be rate-limited by notation, and blocks became thinkable largely because loops became writable. NiN removes the fully connected head, and the load-bearing justification arrives as a throwaway aside: global average pooling is only harmless because the 1×1 convolutions already did the per-location mixing the FC layers used to do. The surprise that averaging cost no accuracy deserves more dwelling than it gets — it means the field had been paying hundreds of megabytes for redundant capacity. GoogLeNet then refuses the kernel-size question entirely, converting a design choice into a learnable channel allocation: architecture search hidden inside a block, dressed in principled-sounding 192/208/48/64 ratios that the author candidly concedes are brute-force residue with explanations retrofitted afterward. Its auxiliary losses are the honest tell that half of architecture history is scaffolding for optimization problems later solved elsewhere.
Continue reading
The middle of the chapter — batch and layer normalization — is where the book is at its best methodologically, because it separates the mathematics from the bookkeeping, demonstrates the layer twice, and then publicly retracts the folk explanation: internal covariate shift is a misnomer, while the regularization and convergence effects are real. That is a model of how to teach a technique whose why is still unsettled. ResNet follows with the one genuinely theoretical idea here, nested function classes and a bias toward identity, which reframes depth as something you can add without risk rather than something you gamble on. ResNeXt and DenseNet are then best read as the same idea under a budget: grouped convolutions buy width cheaply, concatenation buys feature reuse at the price of GPU memory, and transition layers exist to pay that bill. Notice the quiet pivot that happens around GoogLeNet and never reverses — the metric stops being accuracy and becomes accuracy per FLOP. Everything afterward is optimization under a two-term objective, which is why AnyNet/RegNet is the chapter's proper ending rather than an appendix: with 17 free parameters, you cannot search, so you must assume general design rules exist, test them with cheap low-fidelity proxies, and compare error distributions instead of single champions. Tying bottleneck ratio and group width is free; widths and depths should grow with depth. That is empirical science applied to architecture itself.
What I would tell a reader: do not memorize the seven networks, memorize the three moves — replace a hand-made choice with a learned one, replace a model with a family, replace a family with a distribution you can measure. Read the parentheses and the admissions, because that is where the chapter tells the truth about itself: the eight-year-unexamined default revisited only by Liu et al. in 2022, the arbitrary channel ratios, the misnamed justification for BatchNorm. And treat the closing claim — that scalability beats inductive bias — as the chapter's thesis rather than its conclusion: it is well supported by everything that came before, but it is also the sort of consensus that, on this chapter's own evidence, lasts until someone bothers to re-run the experiment. The exercise asking why nobody benchmarks AlexNet anymore is the sharpest thing in the text, because the same question is waiting to be asked of ImageNet, of FLOPs as a cost proxy, and of RegNet itself.
Read Chapter 8 with these cards beside each passage.
Open in FeedLitraChapter 9: Recurrent Neural Networks
How exactly does the hidden state update turn into trainable parameters in an RNN?
How Chapter 9 unfoldsAI-assisted
Opening: a gap in the toolkit. The chapter opens by pointing out that everything handled so far — tabular rows, images — arrives as a fixed-length vector, and that a great deal of interesting data does not. The author lists tasks whose inputs or outputs or both are sequences: image captioning, speech synthesis, music generation, time series prediction, video analysis, translation, dialogue, robot control; documents are sequences of words, medical records sequences of events, video sequences of frames. None of these fits a fixed-length slot, so a different class of model is needed, and recurrent neural networks are introduced as models that capture sequence dynamics through recurrent connections — a network unrolled over time, reusing the same parameters at each step. From there the chapter builds the notation: a sequence factorized left to right by the chain rule, Markov conditions that truncate how far back we look, decoding one token at a time, and a synthetic training example to make the setup concrete. A small but important concession is made here: the reverse factorization is just as valid mathematically, so forward order is a practical choice, defended on three grounds — it is intuitive, it extends to arbitrarily long sequences, and it respects causal structure, since future events cannot shape past ones and the next value can usually be written as a function of the current one plus noise while the inverse relation fails. Hence the standing advice to respect temporal order in training.
First development and first turn: prediction horizons and the move to text. The chapter then presses the autoregressive setup until it breaks. One-step prediction is easy when the true past is available; multi-step prediction is not, because the model must feed its own outputs back in as inputs. A small error perturbs the next step's input, and the deviation grows by roughly a recursion of the form "error plus a constant times the previous error." The sine-wave plots make this visible: four-step forecasts remain usable, anything beyond is nearly worthless — the same reason a 24-hour weather forecast behaves far better than a long-horizon one. With that limit established, the chapter turns from synthetic signals to real text, and the question becomes mechanical: tokenize the raw string, build a vocabulary, index the tokens. The frequency statistics that emerge then deliver the chapter's second argument. Word frequencies fall off sharply — the tenth most common word appears less than a fifth as often as the first — and among the ten most frequent word pairs, nine consist only of stop words, with just "the time" tied to the book's actual content. Longer n-grams are therefore overwhelmingly rare. Counting works acceptably for frequent single words and collapses beyond that, which is the concrete case for neural language models rather than count-based ones.
Second development: measuring quality, and the recurrent fix. Before building the model, the chapter settles how to judge one. Raw likelihood favors short texts, so War and Peace would score far worse than The Little Prince for reasons having nothing to do with model quality; what was missing was an average. Averaging cross-entropy per token and exponentiating gives perplexity, whose limits read cleanly: 1 for perfect prediction, infinity when the model assigns probability zero to something that occurs, and exactly the vocabulary size for uniform guessing — a nontrivial baseline any useful model must beat. Data loading is also specified: sequences partitioned with a random offset into length-n inputs, with targets shifted one position. Then comes the structural payoff. A Markov model of order n requires on the order of |V|^n stored numbers, so lengthening the context grows parameters exponentially; the recurrent alternative keeps a latent summary h of everything seen so far and models the next token given that summary, at bounded cost. The formula is a small edit of the familiar MLP hidden layer — add the previous hidden state times a recurrent weight matrix — after which the layer's output is the hidden state. The parameters are just input, recurrent, and output weights with their biases, reused at every step, so the count does not grow with sequence length. A short code demonstration shows the two matrix products equal a single product of concatenated inputs against stacked weights, and because recurrent edges only pass information between adjacent steps under shared parameters, the unrolled network is an ordinary feedforward computation with no ambiguity about evaluation order.
Third turn: a new kind of depth, and a frankly labeled hack. Having gained bounded parameters, the chapter immediately charges the cost. Sequence length introduces a second kind of depth: an input at step one must travel through T time steps, so the backward pass multiplies a chain of roughly T matrices, and gradients become unstable. The remedy offered is gradient clipping — projecting the gradient onto a ball of radius θ. The justification is a bound, not an elegance claim: under Lipschitz continuity the objective cannot change by more than the Lipschitz constant times learning rate times gradient norm, so capping the norm directly caps the damage a single step can do and limits how much any one minibatch dominates. Without it, one enormous gradient can erase thousands of iterations and tip training into divergence or loss spikes. The author grants the price — reduced fidelity to the true gradient, a possibly slower decrease, side effects that resist analysis — and calls it a hack worth keeping. In practice it is enough to make character-level training stable and to support prefix-conditioned decoding. It is worth not over-reading this: clipping bounds update size, so it tames the exploding side only; vanishing gradients are untouched.
Close: the detailed derivation. The chapter ends by going back under the hood rather than moving on. It first addresses randomized truncation, the theoretically more principled way to cut the time chain, and reports that plain fixed truncation works at least as well, with three likely reasons: gradients over a short span already capture what matters, the added variance cancels the gain in accuracy, and short-range interaction models are in fact what we want — so fixed truncation even acts as mild regularization. These are offered as the probable explanation, not as a measured comparison. Then backpropagation through time is derived in detail for a bias-free linear RNN, where the gradient turns out to be dominated by high powers of the recurrent weight matrix, driving it toward explosion or vanishing depending on that matrix. This is the chapter's real diagnosis, and it closes by assigning the remedies correctly: truncation and caching are what address this instability, while clipping remains the separate, cruder guard on step size.
Key claims, with the lines that support them
Ordered, variable-length data calls for a different class of model than the fixed-length tables and images handled earlier.
The author lists tasks whose inputs, outputs, or both are sequences — image captioning, speech synthesis, music generation, time series prediction, video analysis, translation, dialogue, robot control — and notes that documents, medical records, and videos are naturally represented as sequences of words, events, or frames, none of which fit a fixed-length vector.
“These demands often arise simultaneously: tasks such as translating passages of text from one natural language to another, engaging in dialogue, or controlling a robot, demand that models both ingest and output sequentially structured data.”
Chapter 9. Recurrent Neural NetworksRead in context →
Factorizing a sequence left to right is a practical choice rather than a mathematical requirement.
Building on the chain-rule view of language modeling, the author concedes the reverse factorization is equally valid mathematically, then argues forward order is intuitive, extends to arbitrarily long sequences, and matches causal structure: future events cannot shape the past, and one can often write the next value as a function of the current one plus noise while the inverse relation fails. Hence the advice to always respect temporal order when training.
“Third, we have stronger predictive models for predicting adjacent words than words at arbitrary other locations.”
§9.1 Working with SequencesRead in context →
Counting-based language models cannot carry the weight of language statistics, which is why neural models are needed.
Word frequencies fall off sharply — the tenth most common word appears less than a fifth as often as the most common — and among the ten most frequent word pairs, nine consist only of stop words, with just "the time" tied to the book's content. Longer n-grams are therefore mostly extremely rare, so methods that rely on counts break down even though counting works acceptably for frequent single words.
“Third, many \(n\)-grams occur very rarely. This makes certain methods unsuitable for language modeling and motivates the use of deep learning models.”
§9.2 Converting Raw Text into Sequence DataRead in context →
3 more claims
Averaging cross-entropy over tokens and exponentiating it yields a length-independent quality measure.
Raw likelihood favors short texts, so War and Peace would score far worse than The Little Prince for reasons having nothing to do with model quality — what was missing was an average. The resulting perplexity has readable limits: 1 for perfect prediction, infinity when the model assigns probability zero to what occurs, and exactly the vocabulary size for uniform guessing, which gives a nontrivial bound any useful model must beat.
“This makes the performance on documents of different lengths comparable.”
§9.3 Language ModelsRead in context →
Adding a single recurrent term to the familiar hidden-layer formula gives a model whose parameter count does not grow with sequence length.
Compared with the MLP hidden layer, the recurrent layer only adds the previous hidden state times a weight matrix, after which the layer's output is a hidden state; the parameters are just the input, recurrent, and output weights with their biases, reused at every step. A short code demonstration shows the two matrix products equal one product of concatenated inputs and stacked weights, and because recurrent edges pass information only between adjacent steps with shared parameters, the unrolled network is an ordinary feedforward computation with no ambiguity in order.
Gradient clipping is an admitted hack that is nevertheless worth it because it bounds the harm a single update can do.
Under Lipschitz continuity the objective cannot change by more than the Lipschitz constant times learning rate times gradient norm, so projecting the gradient onto a ball of radius theta directly caps the damage of one step and limits any one minibatch's influence; without it, a single huge gradient can erase thousands of iterations of progress and send training into divergence or loss spikes. The price is reduced fidelity to the true gradient and a slower possible decrease, and the author grants the side effects resist analysis.
“To be clear, it is a hack.”
§9.5 Recurrent Neural Network Implementation from ScratchRead in context →
How it works
The 3 mechanisms the chapter’s argument runs on.
Mechanism 1
Errors snowball in k-step forecasts
With no future observations available, multi-step forecasting must feed its own outputs back as inputs, so a small error at one step perturbs the next step's input and the deviation grows roughly like a bar-plus-c-times-previous recursion. The author's sine-wave plots show 4-step predictions still usable and anything further nearly worthless, and 24-hour weather forecasts behaving far better than longer horizons.
Mechanism 2
Hidden state beats a longer context window
A Markov model of order n needs on the order of |V|^n stored numbers, so lengthening the context makes parameters and storage grow exponentially. Instead, the author keeps a latent summary h of everything seen so far and models the next token given h, which keeps cost bounded; with a powerful enough update function the latent model is exact, though the summary itself can become expensive to store.
Mechanism 3
Time depth makes gradients blow up or die
Sequence length adds a second kind of depth: an input at step one must pass through T time steps, so the backward pass multiplies a chain of about T matrices. Working through a bias-free linear RNN, the author shows the gradient is dominated by high powers of the recurrent weight matrix, which drive it toward explosion or vanishing depending on that matrix.
Common misreadings
Since clipping keeps training stable, it must have solved the gradient problem that long sequences create.
Clipping only bounds the size of an update, so it tames exploding gradients and keeps character-level training and prefix-conditioned generation workable; the vanishing side remains untouched, which is why the author derives the powers-of-the-recurrent-matrix instability explicitly and treats truncation and caching, not clipping, as what addresses it.
“To be clear, it is a hack.”
§9.5 Recurrent Neural Network Implementation from ScratchRead in context →
Randomized truncation, being the theoretically more principled way to cut the time chain, should train better than simply truncating after a fixed number of steps.
The author reports that regular truncation works at least as well, offering three likely reasons: gradients over a short span already capture what matters, the extra variance from randomization cancels the gains in accuracy, and short-range interaction models are in fact what we want, so fixed truncation even acts as mild regularization. These are presented as the probable explanation rather than a measured comparison.
“Hence, regularly truncated backpropagation through time has a slight regularizing effect that can be desirable.”
§9.7 Backpropagation Through TimeRead in context →
Key concepts in Chapter 9
- Recurrent neural network
- A network with cycles that carry information from one time step to the next, reusing the same parameters at every step. A network whose hidden state at each step is computed from the current input plus the previous hidden state, using the same weights throughout.
- Where it applies: Not the only way to handle variable length; CNNs and Transformers can also model sequences. Backpropagating through very long sequences raises gradient problems; applies to sequence data with ordered time steps.
- Autoregressive model
- A model that predicts the next value of a signal from earlier values of that same signal.
- Where it applies: The raw history grows with t, so the input length varies unless a window or summary state is used.
- Markov condition
- The assumption that only the last few steps matter, so older history can be discarded without losing predictive power.
- Where it applies: Usually only approximately true for text; more context still helps but with rapidly diminishing gains.
- Sequence model
- A model of the joint probability of a whole sequence; called a language model when the tokens are words.
- Where it applies: The term 'language model' is used even for non-language sequence data.
- Latent autoregressive model
- A model that keeps an unobserved running summary of the past and updates it alongside each prediction.
- Where it applies: The summary state is never observed, so it must be learned indirectly.
- IID assumption
- Here relaxed: whole sequences are drawn independently, but the items inside one sequence are not independent of each other.
- Where it applies: Neither independence nor stationarity within a sequence is required, only a fixed distribution over whole sequences.
17 more concepts
- k-step-ahead prediction
- Forecasting k time steps past the last observed value, reusing your own predictions as inputs.
- Where it applies: Reliable only for small k; past a few steps the output can decay to a constant.
- Error accumulation
- Each predicted input carries error that the next step amplifies, so deviations snowball.
- Where it applies: Arises specifically when model outputs are fed back as inputs.
- Token
- The smallest indivisible text unit a model consumes; one time step holds one token.
- Where it applies: What counts as a token is a design choice: characters, words, or word pieces.
- Vocabulary
- A dictionary mapping each distinct token to a unique integer index, with unknowns sent to a special token.
- Where it applies: Rare tokens may be dropped and replaced by "<unk>".
- Zipf's law
- Word frequency falls off as a power of its rank, giving a straight line on a log-log plot.
- Where it applies: Holds for n-grams too, but with a smaller exponent depending on sequence length.
- Laplace smoothing
- Adding a small constant to all counts so unseen word combinations get nonzero probability.
- Where it applies: Primitive and unsuitable when many n-grams are extremely rare.
- Perplexity
- A way of scoring a language model by how surprised it is by the actual next tokens. The exponential of the average per-token cross-entropy; read it as the effective number of equally likely next-token choices.
- Where it applies: Raw sequence likelihood is hard to interpret and compare, which motivates this measure. Only comparable when models share a vocabulary and tokenization; uniform prediction gives perplexity equal to vocabulary size.
- Hidden state
- A vector that stores sequence information up to the previous time step and feeds the current step's computation.
- Where it applies: Different from hidden layers; it can only be computed from data at previous time steps.
- Sequence partitioning with random offset
- Each epoch drops a random number d of leading tokens, then cuts the rest into length-n subsequences so different windows are seen.
- Where it applies: It does not give a perfectly uniform distribution over all possible subsequences; complete-sentence examples break fixed-length batching.
- Character-level language model
- A model that predicts the next character rather than the next word, so the vocabulary is small.
- Where it applies: Chosen here to simplify training; loss at a step depends only on characters seen so far.
- One-hot encoding
- Representing a token index as a vector of length equal to vocabulary size with a single nonzero entry. Representing each token as a vector of zeros with a single 1 at the token's index.
- Where it applies: Needed because vocabulary indices carry no similarity information; cost grows with vocabulary size. Equivalent to a fixed per-token embedding; learnable embeddings can replace it.
- Gradient clipping
- Rescaling a too-large gradient down onto a ball of fixed radius while keeping its direction.
- Where it applies: Mitigates exploding gradients only; it does nothing for vanishing gradients and biases updates away from the true gradient.
- Backpropagation through time
- Unrolling the RNN one time step at a time and summing each shared parameter's gradient over every place it appears. Running backpropagation across an unrolled RNN, computing and storing gradients time step by time step.
- Where it applies: Exact over long sequences it is costly and unstable, so truncated or randomized variants are used instead. Applies to sequence models with a hidden state; full BPTT over a long sequence is computationally infeasible.
- Warm-up period
- Feeding a prefix through the model to build hidden state without emitting predictions.
- Where it applies: Applies only while ingesting user-supplied prefix characters, before generation begins.
- Truncation of time steps
- Cutting the backward chain after a fixed or random number of steps, in practice by detaching the gradient.
- Where it applies: Regular truncation is standard; randomized truncation does not perform much better in practice.
- Vanishing and exploding gradients
- Repeated multiplication by the recurrent weight matrix shrinks gradients toward zero or blows them up.
- Where it applies: Driven by eigenvalues of the recurrent matrix being below or above 1; shown here even for a linear, bias-free RNN.
- Chain rule
- Composing partial derivatives along a computational graph, here traversed against the arrow directions.
- Where it applies: Needs the prod operator to handle differently shaped matrices, vectors and scalars.
Reader’s notes on Chapter 9AI reading companion
“it is the feedforward nature of neural networks that makes the order of computation unambiguous”
Read in context →Nice preemptive move — the author names the reader's objection before the reader can voice it, then defuses it with "defined in a precise way." A bit of hand-waving dressed as reassurance.
“they can often nevertheless be represented as varying-length sequences of fixed-length vectors”
Read in context →This is the whole chapter in one line. The trick isn't escaping fixed length — it's demoting it one level, from the example to the token.
“RNNs have recently ceded considerable market share to Transformer models”
Read in context →Market share — an oddly commercial metaphor for architectures. Honest about obsolescence while still asking you to read on; the justification that follows is pedagogical, not technical.
17 more notes
“If we did not believe that the elements in a sequence were related, we would not have bothered to model them as a sequence in the first place.”
Read in context →Circular, but usefully so: the modeling choice is itself a claim about the world. The data doesn't announce that it's a sequence; we decide it is.
“we require only that the sequences themselves are sampled from some fixed underlying distribution over entire sequences”
Read in context →The i.i.d. assumption isn't abandoned, just pushed up a level — from timestep to whole document. Every "flexible" result below is bought with that single surviving rigidity.
“After all we all read text every day, and this process is guided by our ability to anticipate which words”
Read in context →The first reason for left-to-right is frankly anthropocentric — our intuition, not the math. Admirably candid that convenience of thought counts as a reason.
“in some cases, we can find \(x_{t+1} = f(x_t) + \epsilon\) for some additive noise \(\epsilon\), whereas the converse is not true”
Read in context →The only genuinely non-arbitrary reason in the list: asymmetry of noise, i.e. causal direction. The two preceding reasons were ergonomics; this one is physics.
“Unfortunately, in this case we fail spectacularly.”
Read in context →The textbook stages its own failure, and this is the most instructive paragraph so far. One-step predictions looked beautiful precisely because they were never asked to stand on their own output.
“weather forecasts for the next 24 hours tend to be pretty accurate but beyond that, accuracy declines rapidly”
Read in context →The error-compounding analysis is really a lesson about any autoregressive generator — including the ones writing text today. Feed a model its own output long enough and it drifts to a constant, or to a loop.
“However, they carry meaning and it is not necessary to filter them out when working with modern RNN- and Transformer-based neural models”
Read in context →A quiet obituary for a whole era of NLP craft. Stop-word lists were a concession to weak models, not a fact about language.
“Out of the ten most frequent word pairs, nine are composed of both stop words and only one is relevant to the actual book”
Read in context →The bigram table is doing the argument's work: climb the n-gram ladder and content barely surfaces. Frequency and meaning are near-orthogonal.
“the number of distinct \(n\)-grams is not that large. This gives us hope that there is quite a lot of structure in language”
Read in context →Nice inference: sparsity of the observed combinatorial space is read as evidence of constraint, not of insufficient data. That inversion is the whole case for learning.
“it would need to understand the text rather than just generate grammatically sensible content”
Read in context →Written before the line blurred. A 2021-era caution that now reads as a question the field never actually settled, only outran.
“I want to eat grandma” is a rather disturbing statement, whereas “I want to eat, grandma” is much more benign”
Read in context →The joke smuggles in a real point: the model's job is arbitrating between readings a human never even perceives as ambiguous.
“this entirely ignores the meaning of the words. For instance, “cat” and “feline” should occur in related contexts”
Read in context →Here's the actual indictment of counting — not that data is scarce, but that counting has no mechanism for similarity. Everything is an unrelated atom.
“the reciprocal of the geometric mean of the number of real choices that we have when deciding which token to pick next”
Read in context →Best sentence in the section. Perplexity stops being a formula and becomes a count of how confused you are, in units of branching.
“this provides a nontrivial upper bound that any useful model must beat”
Read in context →Worth pinning: the honest baseline is vocabulary size. Any reported perplexity means nothing until you know |V|.
“discard the first \(d\) tokens, where \(d\in [0,n)\) is uniformly sampled at random”
Read in context →An elegant hack — random phase offset gives you all n alignments across epochs for free. Though the exercise immediately admits it's not truly uniform.
“For a sufficiently powerful function \(f\) in (9.4.2), the latent variable model is not an approximation.”
Read in context →The pivot of the chapter. Exponential parameter blowup in n is traded for one recursive function — losslessly in principle, and the cost merely relocates to h's capacity.
“Hidden states are technically speaking inputs to whatever we do at a given step”
Read in context →The crucial reframing: a hidden state isn't a layer, it's an input you manufactured yourself. Naming collision in the field, quietly cleaned up here.
A reader’s takeAI reading companion
Burdens don't vanish, they just relocate: track where they go
Read as one piece, this chapter is an argument about relocation rather than escape, and it is honest enough to show its own seams. It opens by setting sequential data against the fixed-length tabular and image inputs of earlier chapters, and the pivotal concession comes early: sequences can be handled as varying-length sequences of fixed-length vectors. Fixed length is never defeated, only demoted one level — from the example to the token. The same move repeats throughout. The i.i.d. assumption is not abandoned but pushed up from timestep to whole document, and every later claim of flexibility is bought with that one surviving rigidity. The exponential parameter blowup of n-grams is traded for a single recursive function f, with the striking admission that for a sufficiently powerful f the latent-variable model is not an approximation at all — the cost merely moves into the capacity of the hidden state. Even the hidden state itself gets reframed: not a layer, but an input you manufactured for yourself. The chapter's intellectual spine is a chain of such relocations, and the sharpest reading is to track where each burden lands rather than to accept that it vanished.
The unfolding is deliberate. Notation, autoregressive factorization, Markov conditions, and left-to-right decoding come first, with the motivations for left-to-right laid out in ascending order of respectability: our own reading habits (frankly anthropocentric, and candidly labeled as such), convenience, and finally the one genuinely non-arbitrary reason — the asymmetry of additive noise, which is to say causal direction. Two ergonomics and one piece of physics. Then the textbook stages its own failure, and that is its finest pedagogical instinct. One-step predictions on synthetic data look beautiful precisely because they are never made to stand on their own output; the k-step plots decay past roughly four steps, and the weather-forecast analogy generalizes the lesson well beyond this chapter. Feed any autoregressive generator its own output long enough and it drifts to a constant or into a loop — a diagnosis that applies squarely to today's text models, written as if about a toy.
Continue reading
The text-processing section then does quiet historical work. Tokenize, build a vocabulary, index, and look at the frequency structure: Zipf's law holds for unigrams and for n-grams, and the bigram table carries the argument almost by itself, since nine of the ten most frequent pairs are stop-word compounds. Frequency and meaning are near-orthogonal. The aside that stop words carry meaning and need not be filtered for modern models is a one-line obituary for an era of NLP craft — those lists were a concession to weak models, never a fact about language. The decisive indictment of counting, though, is not data scarcity but the absence of any mechanism for similarity: counting treats "cat" and "feline" as unrelated atoms. Conversely, the observation that distinct n-grams are far fewer than the combinatorial space allows is read as evidence of linguistic constraint rather than of insufficient data, and that inversion is the entire case for learning instead of tabulating. The "I want to eat grandma" joke smuggles in the real job description: arbitrating between readings a human never perceives as ambiguous.
Perplexity gets the chapter's best sentence — the reciprocal of the geometric mean of the number of real choices at each step — which converts a formula into a unit of branching confusion. Pin the companion remark too: uniform guessing over the vocabulary is a nontrivial upper bound any useful model must beat, so a reported perplexity is meaningless until you know the vocabulary size. The partitioning scheme that follows, discarding a uniformly random offset of d tokens, is an elegant trick that buys all n alignments across epochs for free, and the exercises immediately concede it is not truly uniform — a small instance of the chapter's general willingness to mark its own approximations.
The final movement treats sequence length as a new axis of depth and pays for it. Backpropagation through time produces O(T) matrix products, high powers of the recurrent weight matrix, and gradients that vanish or explode; the detailed derivation for the bias-free linear RNN makes the mechanism visible rather than asserted. Gradient clipping, projecting onto a ball of radius theta, is correctly presented as a hack: it caps the damage a single step can do and does nothing about vanishing gradients, which is precisely why the chapter must argue separately that randomized truncation does not beat regular truncation, and why truncation plus caching bear the real load. That clipping suffices for stable character-level training and prefix-conditioned decoding is a result about engineering tolerance, not about the problem being solved — and the unsolved half is what the chapters on LSTMs and GRUs exist to address.
What I would tell a reader: the admission that RNNs have ceded considerable market share to Transformers — an oddly commercial metaphor — is pedagogical honesty, not technical justification, and that is fine, because what survives here is not the architecture but the conceptual apparatus. Sequence as a modeling decision rather than a property of the data (the circular-but-useful line that we would not model elements as a sequence unless we believed them related); perplexity as branching factor; error compounding under self-feeding generation; the trade of parameter count for recursion; gradient pathology from repeated multiplication. All of it transfers. Two cautions. First, the reassurance that the feedforward structure makes computation order unambiguous because it is "defined in a precise way" is hand-waving dressed as preemption — a well-executed move that names your objection before you can, then declines to answer it. Second, the remark that a truly good model would need to understand text rather than merely produce grammatically sensible content was written before that line blurred; it now reads as a question the field never settled, only outran. Read this chapter for its relocations and its staged failure, and keep asking the question it trains you to ask: when a difficulty disappears from the page, where did it actually go?
Read Chapter 9 with these cards beside each passage.
Open in FeedLitraChapter 10: Modern Recurrent Neural Networks
How do GRU's reset and update gates map onto LSTM's three gates?
How Chapter 10 unfoldsAI-assisted
The opening: an unfinished argument. The chapter does not begin with a new model but with a debt left over from the plain RNN. Gradient clipping had been introduced earlier as the remedy for unstable training, and the author now reopens that case to show it was only half a remedy: clipping caps gradients that explode, but it does nothing for gradients that fade. Long-range dependencies therefore remained unlearnable, and no tuning of the old architecture could change that. This framing matters because it sets the chapter's logic — the problem is structural, so the answer must be structural too. The LSTM arrives as that answer, and its decisive feature is not the gates themselves but the memory cell they guard: an internal value carried forward on a self-loop of weight 1, modified only by what the gates choose to add or flush. Because the state is mostly passed along untouched, the error signal can travel back across many steps intact. The author proves the point by taking the limit — forget gate pinned at 1, input gate at 0, and the cell's value is provably constant forever. It is worth noting how carefully this is flagged as idealized: in a trained network the gates take soft intermediate values, so gradient preservation depends on whether the model learns sensible keep-and-flush timing. The common reading that LSTMs "solve" vanishing gradients outright overstates what the chapter actually claims. The GRU then follows as a streamlining of the same idea, keeping the gating logic with fewer moving parts.
The development: extending the architecture along two axes. With gating in place and GRU code trained, the chapter stops improving the cell and starts rearranging the network. The first move is depth. Here the author corrects a tempting misreading: an RNN already looks deep, since an input at step one passes through T applications of the recurrent layer before reaching a late prediction. But that is depth along time; from input to output at any single step, only one transformation intervenes. Complex same-step relationships need more, which is what stacking layers provides. The second move looks along the sequence in the other direction. Bidirectional RNNs are presented not as a free upgrade but as a task-dependent choice, argued through fill-in-the-blank sentences where the words after the gap decide which filler is plausible — "not" fits one continuation and not another. Rightward context genuinely helps when filling masked positions or encoding a sequence, but it is simply unavailable when the next token is the thing being predicted, and such models are expensive to train besides. The principle the author is establishing is that architecture should follow the information structure of the task.
The turn: from modeling sequences to mapping them. The chapter's pivot comes when the problem itself changes shape. Language modeling predicts the next element of one sequence; machine translation maps one sequence onto another of different length, with no alignment between positions. This reframing immediately generates practical demands, and the chapter works through them in order: English–French pairs must be tokenized, then padded or truncated into uniform-length minibatches. Padding, however, introduces a fresh hazard — pad tokens carry no target information, so counting them in the loss would reward the model for predicting filler. The fix is the masked loss: compare each target position against the pad id, zero out the masked positions, and average only over genuine tokens. This is a good example of the chapter's habit of letting an engineering convenience create a problem and then paying for it explicitly.
The architecture that answers it. The encoder–decoder interface is introduced as the abstraction for unaligned mapping: the encoder compresses the variable-length input into a fixed-shape state, which the decoder consumes. The concrete instance is an RNN seq2seq model with a GRU encoder and a decoder that concatenates the encoder's context summary with its own input at every time step, with its initial state taken from the encoder. The author's most clarifying move here is deflationary — imagine deleting the encoder, and what remains is a model emitting one token at a time from the preceding tokens, which is to say an ordinary language model. The decoder is nothing exotic; it is a conditional language model, and the concatenated context is where the conditioning becomes visible. Training uses teacher forcing, feeding the true previous target rather than the model's own output, and the masked loss from the data-preparation step applies here.
The close: evaluating and then searching. Having built and trained the model, the chapter needs a way to judge its output, and BLEU supplies it: n-gram matches scored as a precision. The author is explicit about the loophole this creates — a very short prediction has few n-grams available to get wrong, so precision can approach its maximum while most of the target goes untranslated. BLEU closes the loophole by multiplying the precisions by an exponential penalty based on the ratio of target length to prediction length, making early stopping a losing strategy. The final section then turns from scoring to decoding and lays the options out as a spectrum priced in computation. Greedy search takes the locally most probable token at each step, which is cheap but carries no guarantee of finding the most probable whole sequence. Exhaustive search is optimal but, for a vocabulary of 10,000 and length 10, would require on the order of 10^40 scorings against greedy's 10^5. Beam search occupies the practical middle: keep k candidates at each step, costing roughly k·|Y|·T', and rank the finalists with a length-normalized score. The chapter ends on an honest note rather than a triumphant one — beam search remains a heuristic, with greedy search as the k = 1 special case, so the beam width is a dial the practitioner tunes rather than a problem solved.
Key claims, with the lines that support them
Gradient clipping was never a real cure for long-range learning: it stops gradients from blowing up but does nothing about them fading away, so a change of architecture was required.
The author recalls that clipping, introduced for plain RNNs earlier in the book, was a blunt heuristic that merely caps gradient size; it leaves the vanishing-gradient problem untouched. This unresolved gap is what the chapter uses to motivate gated architectures.
“Despite the efficacy of this hack, it leaves open the problem of vanishing gradients.”
Chapter 10. Modern Recurrent Neural NetworksRead in context →
Following directly from that gap, the fix is structural: a state that is simply carried forward on a weight-1 loop is what lets gradients survive many time steps.
The author argues it by taking the limiting case — if the forget gate is permanently 1 and the input gate permanently 0, the internal value is provably unchanged across all time steps, so nothing decays. The author flags this as an idealized case, since real behavior depends on what the gates learn.
“Intuitively, the memory cell avoids the vanishing gradient problem by keeping values in each memory cell’s internal state cascading along a recurrent edge with weight 1 across many successive time steps.”
Chapter 10. Modern Recurrent Neural NetworksRead in context →
Reading an RNN as already "deep" is only half true: it is deep in time but shallow from input to output, which is why layers are stacked.
The author points out that an input at the first time step passes through T applications of the recurrent layer before it affects a late prediction — plenty of depth along the time axis — yet only one transformation separates input from output at any single step. Expressing complex same-step relationships therefore needs extra stacked layers.
“However, we often also wish to retain the ability to express complex relationships between the inputs at a given time step and the outputs at that same time step.”
§10.3 Deep Recurrent Neural NetworksRead in context →
3 more claims
Looking in the other direction along the sequence, whether future context should be used is a property of the task, not a free upgrade.
The author uses fill-in-the-blank sentences where the words after the gap decide which filler is plausible — "not" works in one continuation but not another — showing rightward context genuinely matters for filling in masked tokens and for encoding, while being unavailable when the job is predicting the next token. The author also notes training such models is expensive because of long gradient chains.
“Bidirectional RNNs are mostly useful for sequence encoding and the estimation of observations given bidirectional context.”
§10.4 Bidirectional Recurrent Neural NetworksRead in context →
In a sequence-to-sequence decoder, nothing exotic is happening: it is a language model over the target that happens to be conditioned on the encoded source.
The author's reasoning is to delete the encoder in thought: what remains is a model emitting one token at a time from the preceding tokens, i.e. an ordinary language model. The implementation makes the conditioning explicit by concatenating the encoder's context summary with the decoder input at every time step and initializing the decoder state from the encoder.
“Note that if we ignore the encoder, the decoder in a sequence-to-sequence architecture behaves just like a normal language model.”
§10.7 Sequence-to-Sequence Learning for Machine TranslationRead in context →
At prediction time, search strategies lie on a spectrum, and beam search is the practical middle point bought with a tunable beam width.
The author first notes that taking the locally most probable token at each step gives no guarantee of the most probable whole sequence, then prices the alternatives: with a vocabulary of 10,000 and length 10, exhaustive search would need about 10^40 scorings against 10^5 for greedy, while beam search costs roughly k·|Y|·T' by keeping k candidates per step and ranking finalists with a length-normalized score. The author stresses it remains a heuristic, with greedy search as the k=1 case.
“Unfortunately, there is no guarantee that greedy search will give us this sequence.”
§10.8 Beam SearchRead in context →
How it works
The 3 mechanisms the chapter’s argument runs on.
Mechanism 1
Why the memory cell keeps gradients alive
Instead of rewriting its state through a weight matrix each step, the cell carries an internal value on a self-loop of weight 1 and only lets multiplicative gates decide what is added or flushed. Because the state is mostly passed along unchanged, the error signal travels back across many steps without shrinking away; in the limiting case of forget gate 1 and input gate 0 the state stays exactly constant.
Mechanism 2
Zeroing out padding in the loss
Uniform-length minibatches are made by appending pad tokens, which carry no real target information, so counting them would reward the model for predicting filler. The training loss therefore builds a mask by comparing each target position against the pad token id, multiplies masked positions by zero, and averages only over the genuine tokens.
Mechanism 3
Why BLEU penalizes short outputs
BLEU rewards matched n-grams as a precision, and a very short prediction has few n-grams to get wrong, so precision can hit its maximum while most of the target is missing. BLEU therefore multiplies the precisions by an exponential penalty based on the ratio of target to prediction length, so cheating by stopping early lowers the final score.
Common misreadings
LSTM's memory cell solves vanishing gradients outright, so a gated RNN can learn arbitrarily long dependencies.
The guarantee only holds in an idealized limit the author constructs for intuition — forget gate pinned at 1 and input gate at 0. In a trained model the gates take soft values in between, so gradient preservation depends on whether the network learns sensible keep-and-flush timing, and very long sequences remain costly.
“Intuitively, the memory cell avoids the vanishing gradient problem by keeping values in each memory cell’s internal state cascading along a recurrent edge with weight 1 across many successive time steps.”
Chapter 10. Modern Recurrent Neural NetworksRead in context →
Since more context can only help, a bidirectional RNN is the better default and should be used for predicting the next token too.
A bidirectional model only produces its output after seeing the whole sequence, which makes it right for encoding and for filling in masked positions but unusable when the future tokens are exactly what must be predicted; it is also expensive to train. The choice follows the task's information structure.
“Bidirectional RNNs are mostly useful for sequence encoding and the estimation of observations given bidirectional context.”
§10.4 Bidirectional Recurrent Neural NetworksRead in context →
Key concepts in Chapter 10
- Memory cell
- A composite unit replacing a plain recurrent node, holding an internal state on a self-loop of weight 1.
- Where it applies: Only helps when gates learn useful keep/flush timing; still costly on long sequences.
- Multiplicative gates
- Sigmoid-valued switches deciding what enters the state, what is forgotten, and what leaves as output.
- Where it applies: Gate values live in (0,1), so they soften rather than hard-switch information flow.
- Gated recurrent unit (GRU)
- A lighter gated cell with only reset and update gates, usually as accurate but faster.
- Where it applies: No separate memory cell state; trades expressiveness for speed.
- Bidirectional RNN
- Reads a sequence forward and backward so each output sees both past and future tokens.
- Where it applies: Needs the whole sequence, so it suits labeling rather than live generation.
- Deep recurrent neural network
- RNN layers stacked so each layer's output sequence feeds the next layer's input, giving depth in both time and input-to-output directions.
- Where it applies: Common depths are only 1 to 8 layers, and convergence needs careful learning rate and clipping.
- Bidirectional recurrent neural network
- Two unidirectional RNNs run over the same input in opposite directions, with their outputs concatenated at each time step.
- Where it applies: Useful for encoding and filling in masked tokens, not for left-to-right language modeling; costly to train.
10 more concepts
- Sequence-to-sequence problem
- Tasks mapping one sequence to another of possibly different length and word order, such as translation or question answering.
- Where it applies: Defined by unaligned pairs; it needs paired source/target data rather than a single text stream.
- Truncation and padding
- Forcing every sequence in a minibatch to the same length by appending a pad token or cutting off extra tokens.
- Where it applies: Requires recording true source length, since some later models must ignore padding.
- Encoder--decoder architecture
- One network compresses a variable-length input into a state; a second network expands that state into a variable-length output.
- Where it applies: Needed when input and output lengths differ and tokens are unaligned.
- Context variable
- A fixed-shape summary of all encoder hidden states, often just the last one.
- Where it applies: A single fixed vector bottlenecks long inputs, motivating attention in Chapter 11.
- Teacher forcing
- During training the decoder reads the true target tokens, shifted by one, instead of its own predictions.
- Where it applies: Only available at training time; at test time the model must consume its own outputs.
- Masked loss
- Padding positions are multiplied by zero so they contribute nothing to the cross-entropy.
- Where it applies: Requires knowing the padding token id of the target vocabulary.
- BLEU
- A score that checks how many n-grams of the prediction appear in the target, multiplied by a penalty for predictions that are too short.
- Where it applies: Only measures n-gram overlap up to length k; equals 1 only when prediction matches target.
- Greedy search
- At every step pick the single highest-probability next token until <eos>.
- Where it applies: Cheap at O(|Y|T') but gives no guarantee of the most likely whole sequence.
- Exhaustive search
- Enumerate every possible output sequence and keep the highest-probability one.
- Where it applies: Cost O(|Y|^{T'}) is infeasible: 10000 tokens and length 10 means 10^40 sequences.
- Beam search
- Keep the k best partial sequences at each step instead of just one, then score finalists with a length-normalized log probability.
- Where it applies: Cost O(k|Y|T'); greedy search is the special case k=1.
Reader’s notes on Chapter 10AI reading companion
“Despite the efficacy of this hack, it leaves open the problem of vanishing gradients.”
Read in context →Rare honesty in a textbook: clipping is called a hack outright. Exploding gradients get a bandage; vanishing ones need architecture.
“although the results were not widely known because the thesis was written in German”
Read in context →A field's memory is language-bound. Six years of delay purchased by a translation gap.
“a node with a self-connected recurrent edge of fixed weight 1”
Read in context →The whole trick in one clause. Multiplying by 1 forever is the only way to survive repeated multiplication.
17 more notes
“Simple recurrent neural networks have long-term memory in the form of weights.”
Read in context →The name finally parses: not "long/short-term" but a long short-term memory, a third timescale wedged between slow weights and fleeting activations.
“accrue information across many time steps without impacting the rest of the network”
Read in context →The output gate buys privacy for the cell. A network that can hold something without saying it — that's closer to intention than to arithmetic.
“why does the hidden state need to use the \(\tanh\) function again”
Read in context →Good exercise — the answer is that C_t is a sum of many tanh-bounded terms, so it isn't bounded at all. The book quietly left that gap for you to fall into.
“mathbf{H}_t = \mathbf{Z}_t \odot \mathbf{H}_{t-1} + (1 - \mathbf{Z}_t) \odot \tilde{\mathbf{H}}_t”
Read in context →GRU's economy: tie LSTM's input and forget gates together so they must sum to one. One parameter saved, and the state can no longer grow without bound.
“there is a sense in which these networks are deep”
Read in context →Depth in time is free and unavoidable; depth in representation has to be built. The chapter is drawing a distinction most readers conflate.
“The standard method for building this sort of deep RNN is strikingly simple: we stack the RNNs on top of each other.”
Read in context →"Strikingly simple" is doing rhetorical work — it frames the absence of a clever idea as itself the insight. Depth in time was already free; depth in abstraction had to be bolted on.
“the weights \(\mathbf{W}_{\textrm{xh}}^{(l)} \in \mathbb{R}^{h \times h”
Read in context →For l=1 the input is X_t with d columns, so the first layer's W_xh must be d×h. The text quietly inherits the l>1 case into a blanket claim — the code's num_inputs if i==0 else num_hiddens knows better than the formula.
“Common RNN layer widths (\(h\)) are in the range \((64, 2056”
Read in context →2056 is almost certainly a typo for 2048 — a power of two fat-fingered. Small thing, but it reveals how these ranges are folklore transcribed rather than measured.
“Overall, deep RNNs require considerable amount of work (such as learning rate and clipping) to ensure proper convergence.”
Read in context →The honest sentence of the section, and it's buried in the summary. Stacking is one line of code and a week of babysitting.
“Would you want to combine sources of different authors when modeling text? Why is this a good idea? What could go wrong?”
Read in context →The exercise that outgrew the chapter. This is the entire training-data-mixture question of modern LLMs, asked in 2021 as a homework aside.
“I am ___ hungry, and I can eat half a pig.”
Read in context →A three-line escalation that teaches bidirectionality better than the equations do — the blank's meaning is revised twice by words that haven't arrived yet. And it's the masked-LM objective, BERT in miniature, before anyone says so.
“Bidirectional RNNs are very costly to train due to long gradient chains.”
Read in context →The real objection is the one they don't lead with: a bidirectional model cannot be used to generate. Cost is the lesser sin; the architecture simply forbids the task the chapter opened with.
“How can we design a neural network model such that given a context sequence and a word, a vector representation of the word in the correct context will be returned?”
Read in context →They're describing contextual embeddings and then asking the reader to invent them. The answer is two sections away, and it isn't an RNN.
“statistical formulations of translation between languages had been popular (Brown et al., 1990, Brown et al., 1988), even before researchers got neural network approaches working (methods were often lumped together under the term neural machine”
Read in context →The parenthetical is attached to the wrong clause — pre-neural statistical methods were never called neural machine translation. A sentence that collapsed in editing.
“num_steps=9, num_train=512, num_val=128”
Read in context →512 training pairs out of ~170k, truncated at nine tokens. The dataset is a unit test wearing a translation task's clothes; any BLEU score from here is theater.
“Modern implementations often bucket sequences with similar lengths to avoid wasting excessive computation on padding.”
Read in context →Dropped in as trivia after the chapter spent a page teaching the thing bucketing exists to avoid. Padding to a global num_steps is the pedagogical choice, not the practical one — worth saying louder.
“a decoder that acts as a conditional language model”
Read in context →This is the chapter's keystone phrase. Everything since section 9 — next-token prediction — is recycled whole, with the condition bolted on front. Translation turns out to be language modeling with a hint.
A reader’s takeAI reading companion
The GRU proves LSTM complexity is engineering taste
Read whole, this chapter is one long argument with a single villain: the vanishing gradient, and a single escape route: build an additive path through time. The chapter is unusually candid about this — it calls gradient clipping a 'hack' outright, admits it only bandages the exploding half, and then spends the rest of its length showing that the other half can't be patched, only designed around. The LSTM's answer sits in one clause — a self-connected recurrent edge of fixed weight 1 — and once you see it, the name finally parses: not 'long/short-term' but a long short-term memory, a third timescale wedged between slow weights and fleeting activations. The output gate is the quietly radical part: it lets the cell accrue information without exposing it, a network that can hold something without saying it. The GRU then arrives as an economy measure — tie the input and forget gates so they sum to one — and the chapter's willingness to show the cheaper variant right after the canonical one is honest about how much of this is engineering taste rather than derivation. The book does leave gaps: the exercise asking why the hidden state needs tanh again is a real hole in the exposition, since the cell state is a sum of bounded terms and so isn't bounded at all; the stacked-RNN weight shapes silently assume l>1 while the code knows better; and '2056' as a layer width is folklore transcribed, not measured. Small things, but they mark where the text is reporting practice rather than deriving it.
The middle act is about a distinction most readers conflate and the chapter draws cleanly: depth in time is free and unavoidable, depth in representation has to be bolted on. 'Strikingly simple' does rhetorical work there — framing the absence of a clever idea as itself the insight — and the honest sentence, buried in a summary, is that deep RNNs take considerable work on learning rate and clipping to converge. Stacking is one line of code and a week of babysitting. Bidirectional RNNs are the chapter's sharpest piece of self-limitation, and it under-sells its own objection: it leads with training cost when the real point is that a bidirectional model structurally cannot generate. It forbids the very task the chapter opened with. What it can do — revise a blank's meaning by words that haven't arrived yet, as in that three-line 'I am ___ hungry' escalation — is the masked-language-model objective in miniature, BERT before anyone says BERT. The exercises keep outrunning the text this way: mixing authors in training data is the entire LLM data-mixture question asked as homework in 2021; 'return a vector for a word in its correct context' is asking the reader to invent contextual embeddings two sections before the real answer arrives, and the real answer isn't an RNN.
Continue reading
The final act earns the chapter its title. Encoder–decoder, then seq2seq with teacher forcing, masked loss, greedy decoding, BLEU. The keystone phrase is 'a decoder that acts as a conditional language model': everything from the plain next-token chapter is recycled whole, with a condition bolted on the front. Translation turns out to be language modeling with a hint — and that reframing, more than any gate equation, is what the chapter is really for. Be skeptical of the demonstrations, though. 512 training pairs truncated at nine tokens is a unit test wearing a translation task's clothes; any BLEU from there is theater, useful only to prove the plumbing runs. And the aside that real systems bucket by length, dropped as trivia after a page spent teaching global padding, deserves to be said louder: the padding you're taught is the pedagogical choice, not the practical one. The closing decoding section is the cleanest piece of reasoning in the chapter — greedy is cheap and can miss the most likely sequence, exhaustive is optimal and exponential, beam search buys a tunable point between them with a length-normalized score — and it's worth noticing that this is pure search, independent of every architecture that preceded it.
What I'd tell a reader: don't memorize the gate diagrams. Carry three things instead. First, the additive-path idea — weight-1 carry, gated updates — which outlives the RNN entirely and reappears as residual connections and as every modern architecture's answer to depth. Second, the conditional-language-model framing, which is the actual bridge to everything after this chapter. Third, a working distrust of the gap between a book's code and a book's claims: this chapter is at its best when it admits the hack, the cost, the babysitting, and at its weakest when a toy run is allowed to look like a result. Read it as the last chapter before attention — the architectures here are historically essential and largely superseded, but the problems they were built to solve, and the honesty with which this text names them, are not.
Read Chapter 10 with these cards beside each passage.
Open in FeedLitraChapter 11: Attention Mechanisms and Transformers
Where do queries, keys and values actually come from in a Transformer?
How Chapter 11 unfoldsAI-assisted
The chapter opens by stating its destination before explaining it — Transformers now dominate both NLP and vision — and then immediately reframes that dominance as something that needs accounting for. The framing device is a historical claim: for roughly three decades, deep learning advanced mainly by adding compute and data rather than by inventing better architectures, with CNN-like models holding vision and LSTM-like models holding NLP despite thousands of proposed alternatives. That sets the chapter's real question: why did the Transformer break the pattern? The answer is traced to a single component, attention, introduced with a modest origin story — it was a patch for a specific failure, the fixed-length context vector in encoder–decoder translation, where the whole source sentence is squeezed into one state and long inputs simply overflow it. The chapter then performs its first and most consequential generalization: attention is not a patch but a database lookup over key–value pairs. The last-name-to-first-name example does the work here — querying "Li" returns "Mu" regardless of how many entries the store holds, and inexact matches are permitted. Because the lookup carries almost no parameters and never requires the store to be simplified, attention inherits the ability to serve variable-size inputs without compression.
Development: a deliberate detour through hand-crafted weighting
Rather than jumping to the learned version, the text takes a detour through Gaussian-kernel regression, and it justifies the detour explicitly on three grounds: it is the earliest precursor, it is easy to visualize, and it exposes the limits of hand design. The third reason is the load-bearing one. Plots at kernel widths of 0.1, 0.2, 0.5 and 1 show the trade the designer cannot escape — narrower kernels concentrate weight on fewer neighbors and yield a less smooth estimate — and Silverman's 1986 heuristic had already been forced to make the width depend on local data density rather than fix it. Hand-tuning hits a wall, and that wall motivates the move to learned scoring. The chapter then supplies the machinery: dot-product and additive scoring functions, masked softmax, batched matrix multiplication. The pivotal point is why softmax matters. It converts arbitrary compatibility scores into nonnegative weights summing to one, and because that step is differentiable with non-vanishing gradients, the weighting itself is learned by backpropagation alongside every other parameter instead of being set by hand. Bahdanau attention is the first payoff: the frozen context vector is replaced by one recomputed fresh at every decoding step.
Development: from a decoder patch to a general architecture
The chapter grounds the idea before extending it — the Bahdanau decoder is implemented, trained on English–French translation, and its attention weights are visualized — and only then begins generalizing. Multi-head attention arrives, followed by self-attention, which needs positional information because the operation itself is order-blind. The sinusoidal solution is explained by analogy: frequencies decrease along the embedding dimension much as higher bits in binary counting flip more slowly than lower ones, and for any fixed offset the move from one position to another is a small, position-independent rotation, so relative distance becomes a linear relation the model can exploit. The chapter then stages a direct comparison against CNNs and RNNs, and this comparison is the hinge of the whole argument. Recurrent layers cost O(nd²) but require O(n) sequential steps with an O(n) longest path; convolutional layers cost O(knd²) with O(1) sequential steps and an O(n/k) path; self-attention connects every token to every other, giving O(1) sequential operations and O(1) maximum path length, at O(n²d) computation. The text is careful about what this buys. The gain is latency structure, not arithmetic — computation actually grows quadratically in sequence length and becomes worse than recurrence for long inputs, which is precisely why later vision work such as Swin Transformers exists to remove that dependence.
The turn: recurrence abandoned, and the trade made explicit
Armed with that comparison, the chapter abandons recurrence outright. The Transformer is assembled from stacked self-attention and positionwise FFN sublayers joined by residual connections and layer normalization; the decoder adds encoder–decoder attention and masks its own self-attention to remain autoregressive. The extension to vision follows directly: ViT treats image patches as tokens, with patch embedding via strided convolution, pre-normalization blocks using GELU MLPs, and a <cls> representation projected to labels. Here the chapter does something structurally honest — it reports its own negative result. Its ViT does not beat the earlier ResNet on Fashion-MNIST, and the author notes similar findings even on ImageNet's 1.2 million images, attributing the gap to the absence of convolutional priors; earlier attempts using 2×2 patches or special attention patterns scaled poorly too. This crystallizes the chapter's central bargain: the Transformer surrenders built-in inductive bias in exchange for scalability. It loses on small data and keeps improving as model, data and compute grow together.
Close: scaling laws, and then the limit of scaling
The final movement cashes in the scalability side of that trade and then qualifies it. Pretraining is organized into three modes — encoder-only (BERT), encoder–decoder (T5), decoder-only (GPT) — and the evidence turns empirical: GPT-2, at 1.5 billion parameters pretrained on 40 GB of text, reached state-of-the-art language modeling without changing parameters or architecture, though the text is scrupulous that its other-task results were merely promising. Loss then follows power laws in parameter count, training tokens, and PetaFLOP/s-days, with GPT-3 tracking the predicted curve across two further orders of magnitude of compute. The chapter closes by turning this against itself. Scale buys capability but not obedience: enlarging a model does not make it follow user intent. That has to be trained in separately — fine-tuning on instruction-phrased datasets improves zero-shot performance on held-out tasks, and InstructGPT-style alignment with human feedback is what produced ChatGPT's human-like behavior. The survey from Megatron-Turing through Llama, with instruction tuning, RLHF and chain-of-thought prompting, extends the GPT line toward multimodal scaling, while two open questions are left standing: how to raise model size, data and compute together is still debated, and under a fixed compute budget more training tokens may matter more than more parameters. The chapter thus ends where it began — with scale as the engine of progress — but with the engine's limits now named rather than assumed.
Key claims, with the lines that support them
Up to the arrival of Transformers, deep learning advanced mainly by adding compute and data, not by inventing better architectures.
The author notes that despite thousands of papers proposing alternatives, models resembling classic CNNs stayed state of the art in vision and LSTM-like models ruled NLP for roughly three decades of little architectural change; this framing sets up the chapter's question of why the Transformer broke the pattern.
“Arguably, to that point, the rapid emergence of deep learning appeared to be primarily attributable to shifts in the available computational resources (thanks to innovations in parallel computing with GPUs) and the availability of massive data resources (thanks to cheap storage and Internet services).”
Chapter 11. Attention Mechanisms and TransformersRead in context →
Thinking of attention as a database lookup explains how it serves inputs of any size with few parameters and no compression.
The author uses a last-name-to-first-name database: the query "Li" returns "Mu" no matter how many entries the database holds, and approximate matches are allowed. Since the lookup operation itself carries almost no parameters and never needs the store simplified, attention inherits the same ability to handle variable-size collections of key-value pairs.
“There is no need to compress or simplify the database to make the operations effective.”
§11.1 Queries, Keys, and ValuesRead in context →
Hand-crafted attention hits a wall because its kernel width must trade smoothness against local detail, which is why the chapter revives a half-century-old method only to move past it.
Plots with widths of 0.1, 0.2, 0.5 and 1 show that narrower kernels concentrate large weights on fewer neighbors and give a less smooth estimate, and Silverman's 1986 heuristic already had to make the width depend on local data density instead of fixing it. The author gives three reasons for the detour — earliest precursor, easy to visualize, and exposing the limits of hand design — and the third is what leads directly into learned scoring functions.
“Clearly, the narrower the kernel, the less smooth the estimate. At the same time, it adapts better to the local variations.”
§11.2 Attention Pooling by SimilarityRead in context →
3 more claims
Following from that comparison, self-attention's parallelism and short connection paths justify abandoning recurrence altogether, though the saving is not in raw computation.
Laid side by side, recurrent layers cost O(nd^2) but need O(n) sequential steps and have an O(n) longest path; convolutional layers cost O(knd^2) with O(1) sequential steps and an O(n/k) path; self-attention connects every token directly to every other, giving O(1) sequential operations and an O(1) maximum path at a computational cost of O(n^2 d).
“Notably, self-attention enjoys both parallel computation and the shortest maximum path length. Therefore, it is appealing to design deep architectures by using self-attention.”
§11.7 The Transformer ArchitectureRead in context →
Transformers give up built-in inductive bias in exchange for scalability, so they lose on small data but keep improving as models, data and compute grow together.
The chapter's own ViT does not beat the earlier ResNet on Fashion-MNIST, and the author reports similar findings even on ImageNet's 1.2 million images, attributing the gap to missing convolutional priors; earlier attempts with 2x2 patches or special attention patterns also scaled poorly. On the other side, GPT-2 with 1.5 billion parameters pretrained on 40 GB of text reached state-of-the-art language modeling without changing parameters or architecture (its other-task results were merely promising), and loss follows power laws in parameter count, training tokens and PetaFLOP/s-days, with GPT-3 tracking the predicted curve for two further orders of magnitude of compute.
“However, the picture changes when training larger models on larger datasets (e.g., 300 million images), where vision Transformers outperform ResNets by a large margin in image classification, demonstrating intrinsic superiority of Transformers in scalability”
§11.8 Transformers for VisionRead in context →
Turning it around: scale buys capability but not obedience, so following human instructions has to be trained in separately.
The author points out that simply enlarging a model does not make it follow intent, then cites work showing that fine-tuning on datasets described by instructions improves zero-shot performance on held-out tasks, and that InstructGPT-style alignment with human feedback is what produced ChatGPT's human-like zero-shot behavior.
“However, simply increasing model size does not inherently make models follow human instructions better.”
§11.9 Large-Scale Pretraining with TransformersRead in context →
How it works
The 3 mechanisms the chapter’s argument runs on.
Mechanism 1
Why one fixed context vector fails
A classic encoder squeezes the whole source sentence into a single fixed-size state, so long inputs overflow it and the decoder mistranslates. Attention instead keeps every encoder timestep and rebuilds a fresh weighted mixture at each decoding step, so nothing has to be compressed away.
Mechanism 2
Softmax makes attention learnable
Any compatibility score between a query and a key is pushed through a softmax, which turns raw scores into nonnegative weights that sum to one. Because that step is differentiable and its gradient does not vanish, the weighting itself is trained by backpropagation together with every other parameter, rather than being hand-set.
Mechanism 3
Sinusoids encode relative position
Position is written as sine and cosine pairs whose frequencies drop along the dimension, much as higher bits in binary counting flip more slowly than lower bits. For any fixed offset, moving from one position to another is a small rotation that does not depend on where you are, so relative distance becomes a simple linear relation the model can exploit.
Common misreadings
Since self-attention runs in parallel and links every token directly, it must be cheaper than a recurrent layer.
What improves is latency structure, not arithmetic: sequential steps and maximum path length drop to O(1), while computation rises to O(n^2 d) and therefore grows quadratically with sequence length — worse than a recurrent layer's O(nd^2) once sequences get long. Later vision work such as Swin Transformers exists precisely to remove that quadratic dependence on input size.
“As a result, the self-attention has a \(\mathcal{O}(n^2d)\) computational complexity.”
§11.6 Self-Attention and Positional EncodingRead in context →
If performance scales as a power law, then making the model big enough will eventually make it do what users ask.
The scaling laws describe loss against parameters, tokens and compute, not instruction following; the author states plainly that size alone does not produce it, and that fine-tuning on instruction-phrased tasks or training with human feedback is what delivers it. The chapter also notes the recipe for raising the three factors together is still debated, and that under a fixed compute budget more training tokens can matter more than more parameters.
“However, simply increasing model size does not inherently make models follow human instructions better.”
§11.9 Large-Scale Pretraining with TransformersRead in context →
Key concepts in Chapter 11
- attention mechanism
- A way to pool many (key, value) pairs into one output by weighting each value according to how well its key matches a query.
- Where it applies: The weights are only an intuition about relevance; what they truly mean interpretively stays unsettled.
- queries, keys, and values
- A database analogy: the query is the lookup request, keys are what can be matched, values are what gets returned.
- Where it applies: Where queries, keys and values come from is left unexplained in this segment; the regression reading comes later.
- Transformer architecture
- A machine-translation architecture that drops recurrence entirely and uses arranged attention to relate all input and output tokens. An encoder--decoder model built only from attention, feed-forward layers, residual connections and layer normalization.
- Where it applies: Introduced for translation, later extended to vision, speech, RL and graphs. Originally for sequence-to-sequence text; encoder or decoder can also be used alone.
- foundation models
- Large models pretrained on generic corpora with a self-supervised objective, then fine-tuned for specific downstream tasks.
- Where it applies: The Transformer advantage over older architectures is described as especially wide specifically under this pretraining paradigm.
- Nadaraya--Watson estimator
- Kernel-weighted averaging of observed labels, read as attention where the query is the evaluation point and training pairs are keys and values.
- Where it applies: Requires no training and is consistent if the kernel narrows with more data; kernels themselves are heuristic.
- Scaled dot product attention
- Score a query against a key by their dot product divided by the square root of the vector length, keeping the score variance near one.
- Where it applies: Requires query and key to share dimension d unless a translating matrix is inserted.
19 more concepts
- Additive attention
- Feed query and key through a small one-hidden-layer MLP with tanh to produce a scalar score, so their dimensions need not match.
- Where it applies: Adds learnable parameters W_q, W_k, w_v; chosen mainly when query and key lengths differ.
- Masked softmax operation
- Before normalizing, push padded positions to a huge negative score so their weights become effectively zero.
- Where it applies: An engineering shortcut: it is deliberately wasteful in computation to avoid GPU-unfriendly conditionals.
- Bahdanau attention mechanism
- The decoder recomputes its context vector at every step by attending over all encoder states instead of reusing one fixed state. The decoder's previous hidden state acts as the query while all encoder hidden states serve as keys and values, so the context variable is an attention-pooling output.
- Where it applies: Removes the unidirectional alignment limit of earlier handwriting-generation attention models. Defined for RNN encoder--decoder translation where decoder steps attend to encoder steps, not to each other.
- Multi-head attention
- Queries, keys and values are linearly projected h ways, pooled in parallel, then concatenated and projected again, so each head can look at different parts of the input.
- Where it applies: Cost is kept flat only by setting each head's width to p_o/h.
- Self-attention
- Every token forms its own query, keys and values, so each token attends to every other token in the same sequence.
- Where it applies: O(n^2 d) complexity makes it impractical for very long sequences.
- Positional encoding
- Extra per-token inputs, here fixed sine and cosine values, added to embeddings so the model can tell token order.
- Where it applies: Needed because self-attention alone discards sequence order; can be fixed or learned.
- Positionwise feed-forward network
- The same two-layer MLP applied independently at every sequence position.
- Where it applies: Shares weights across positions, so identical inputs give identical outputs.
- Masked decoder self-attention
- Decoder attention restricted so each query sees only positions up to itself.
- Where it applies: Needed because at prediction time only already-generated tokens exist.
- Layer normalization in Transformers
- Normalizing across the feature dimension instead of across the minibatch.
- Where it applies: Preferred over batch normalization for variable-length language inputs.
- Vision Transformer
- A model that cuts an image into patches and feeds them to a Transformer encoder for classification.
- Where it applies: Advantage appears mainly with larger models and larger datasets.
- Patch Embedding
- Cutting an image into fixed squares and projecting each into a vector, done as one convolution whose kernel and stride both equal the patch size.
- Where it applies: Requires image size divisible by patch size; patch count grows quadratically with resolution.
- Pre-normalization
- Putting layer normalization just before attention or the MLP instead of after the residual connection.
- Where it applies: A training-stability choice; it changes efficiency, not the layer's input/output shape.
- In-context learning
- Letting a pretrained language model solve a task from a description plus zero, one, or a few examples in the prompt, with no weight updates. Shaping the text input so the model performs the task without updating weights; also called prompting.
- Where it applies: Needs a large pretrained decoder; limited by context length and no parameter update. No weight update happens, so the task must be expressible in the context window.
- Causal attention
- A masking pattern letting each target token attend only to past and present tokens.
- Where it applies: The book warns the name has little to do with the study of causality.
- Power-law scaling
- Performance improves as a straight line on log-log axes against model size, data, or compute, as long as the other two are not the bottleneck.
- Where it applies: Holds per factor only when the other two factors are not limiting; the right way to scale them together is still debated.
- Sample efficiency
- How few training tokens a model needs to reach a given performance level; bigger models need fewer.
- Where it applies: Measured in tokens processed at equal performance, not in total compute spent.
- Emergent abilities
- Capabilities that appear in larger models but are absent in smaller ones.
- Where it applies: Size alone does not produce instruction following; that needs fine-tuning or human feedback.
- Chain-of-thought prompting
- Demonstrating intermediate reasoning steps in the prompt so the model reasons through hard problems.
- Where it applies: Works few-shot and even zero-shot with cues like "Let's think step by step"; extends to multimodal inputs.
- Instruction tuning with human feedback
- Fine-tuning a pretrained model on instruction-style data, optionally with reinforcement learning from human judgments, so it follows human intent.
- Where it applies: Human inputs can be partly replaced by model outputs (reinforcement learning from AI feedback).
Reader’s notes on Chapter 11AI reading companion
“the core underlying architectures were clearly recognizable as scaled-up implementations of classic ideas”
Read in context →A quietly deflationary admission for a field that markets novelty: thirty years of progress, same bones. The honesty earns the later claim that something did finally change.
“primarily attributable to shifts in the available computational resources”
Read in context →So the first decade was hardware and storage wearing an architecture costume. Worth holding onto when the Transformer chapter starts sounding like destiny.
“although what precisely the attention weights mean—i.e., how, if at all, they should be interpreted remains a hazy research topic”
Read in context →The "if at all" is the sharpest phrase so far. The cute "feet"/"pieds" example is offered and then immediately defused — a textbook refusing to sell its own best anecdote.
17 more notes
“There is no need to compress or simplify the database to make the operations effective.”
Read in context →This is the real indictment of the fixed-length bottleneck: not that compression is lossy, but that it was never necessary. The database analogy does more work than most diagrams.
“This is akin to a traditional database query.”
Read in context →Neat framing: hard lookup is the degenerate corner of soft attention. Attention isn't a new operation so much as a differentiable relaxation of one we already had.
“we can design a non-differentiable attention model that can be trained using reinforcement learning methods”
Read in context →The road not taken, named in one sentence. Differentiability won not because it's more faithful to "attention" but because gradients are cheap — a selection effect in disguise.
“While this is a good intuition, it is important to remember that it is just that, an intuition.”
Read in context →Second warning on the same point within two pages. The repetition reads less like pedagogy and more like the authors flinching at how the field actually uses heatmaps.
“One of the convenient properties of this estimator is that it requires no training.”
Read in context →Fifty-year-old nonparametric method, consistent, no parameters — and it's the honest baseline the whole chapter is building away from. Makes you ask what learning actually buys.
“despite the different functional form of the kernel. This raises the question as to whether this is always the case.”
Read in context →Good move: three kernels agreeing is evidence that the shape of the similarity function barely matters. The teasing question is the setup for why learned representations, not cleverer kernels, are the lever.
“it demonstrates the limits of hand-crafted attention mechanisms”
Read in context →The detour's real purpose, finally stated. Nadaraya–Watson fixes similarity in input space; Transformers get to choose the space. That's the whole chapter in one contrast.
“it is faster to be slightly wasteful in computation rather than to have code with conditional (if then else) statements”
Read in context →The honest admission: hardware shapes the math. Masking isn't a theoretical device, it's a bribe paid to the GPU.
“Actually, the implementation cheats ever so slightly by setting the values of \(\mathbf{v}_i\), for \(i > l\), to zero”
Read in context →-1e6 instead of -inf is a soft lie too — finite, so gradients merely vanish rather than truly disappear. In fp16 that bound would overflow.
“Normalizing the attention weights to \(1\), as is done in (11.1.3), ensures that this term disappears entirely”
Read in context →Nice derivation move: the famous QK/√d is reverse-engineered from a Gaussian kernel by discarding two terms. The scaled dot product is a stripped-down distance, not a first principle.
“This is the case, for instance, whenever the keys \(\mathbf{k}_i\) were generated by a layer norm.”
Read in context →Circular convenience — we drop ‖k‖² because layer norm happens to make it constant, and layer norm sits there partly because attention needs it. Two hacks propping each other up.
“the sequence-to-sequence mechanism treats the intermediate state as a sufficient statistic of whatever string might have served as input”
Read in context →Naming the flaw in statistical language makes it sharper than any hand-waving about bottlenecks: the old architecture asserted sufficiency where none exists.
“the alignment moves only in one direction”
Read in context →Worth pausing: Graves had attention first but chained it to monotonic order. Bahdanau's contribution was mostly removing a constraint — the deletion, not the invention, became history.
“Another benefit is that, as its name indicates, the attention is additive. This can lead to some minor computational savings.”
Read in context →This claim is thin and the book half-knows it — additive attention needs an h-dim tanh per query-key pair, which is strictly worse than one matmul. "Savings" only exist in a world without BLAS.
“We used \(\mathbf{s}_{t' - 1}\) as the query, and \(\mathbf{h}_{t}\) as both the key and the value.”
Read in context →The whole QKV vocabulary is retrofitted onto Bahdanau, who wrote none of it. Clean pedagogy, mild anachronism.
“it may be beneficial to allow our attention mechanism to jointly use different representation subspaces”
Read in context →Note the hedging — "may be beneficial." Multi-head is justified by hope, not proof; later work finds many heads prunable with no loss.
“we set \(p_q = p_k = p_v = p_o / h”
Read in context →The textbook presents this as a cost-control convenience, but it's the choice that makes "multi-head" free: same FLOPs as one big head, just partitioned. The subspaces are carved out of a fixed budget, not added to it.
A reader’s takeAI reading companion
Authors noticeably more confident about scale than learning
Read as one piece, this chapter has a shape that its own section numbering hides: it is not "here is attention, here is the Transformer, here is GPT," but a sustained argument about what learning buys you over hand-crafting, followed by an argument about what scale buys you over learning — and the authors are noticeably more confident about the second than the first. It opens with a deflation that pays for everything after it: thirty years of progress on the same architectural bones, with the gains attributable mostly to compute and data. That admission is the chapter's moral anchor, and it's worth carrying forward, because once the Transformer arrives the prose starts to sound like destiny, and the opening has already told you destiny was mostly hardware in an architecture costume.
The unfolding is genuinely well-staged. The fixed-length bottleneck is indicted not for being lossy but for being unnecessary — the database analogy makes the point that a query can simply address the whole store, no summary required, and that hard lookup is the degenerate corner of soft attention rather than a different species of operation. The Nadaraya–Watson detour is the chapter's best pedagogical decision: a fifty-year-old estimator that needs no training, is consistent, and works about equally well under three different kernels. The payoff of that equivalence is the chapter's real thesis, stated almost in passing — the functional form of the similarity barely matters; what matters is that the comparison happens in a learned space rather than in raw input space. Hand-crafted attention fixes the metric; Transformers get to choose it. Everything from scaled dot products to multi-head is downstream of that single contrast.
Continue reading
What I saw through, reading closely, is how much of the canonical machinery is retro-justified rather than derived. The famous QK/√d is reverse-engineered out of a Gaussian kernel by discarding two terms, one of which is discarded on the grounds that layer norm makes key norms constant — while layer norm itself sits in the architecture partly because attention needs the conditioning. Two conveniences holding each other up, presented as a clean derivation. Masking is openly a bribe paid to the GPU: wasteful arithmetic beats branching, and the mask is implemented with a large finite negative rather than true −∞, so gradients merely vanish instead of vanishing by construction (and that bound is not safe in half precision). Additive attention's advertised "computational savings" don't survive contact with BLAS — a tanh per query–key pair is strictly worse than one matmul. Bahdanau's contribution was largely the removal of Graves's monotonicity constraint: the deletion, not the invention, became the history. And the QKV vocabulary is draped retroactively over a paper that used none of it — clean teaching, mild anachronism. The multi-head story is the sharpest case: p_q = p_k = p_v = p_o/h is presented as cost control, but it is the choice that makes multi-head free. The subspaces are carved out of a fixed budget, not added to it, and the justification is a hedged "may be beneficial" — hope rather than proof, a hedge later pruning work largely vindicated.
The most honest thread is the one about interpretation. Twice within a few pages the authors warn that the heatmap intuition is only an intuition, and the phrase "if at all" in "how, if at all, they should be interpreted" is the single sharpest clause in the chapter. They offer the charming feet/pieds alignment and then immediately defuse it — a textbook declining to sell its own best anecdote. The repetition reads less like pedagogy than like flinching at how the field actually uses those pictures. Equally telling is the one-sentence mention that non-differentiable attention could be trained by reinforcement learning. That road wasn't abandoned because it was less faithful to attention; it was abandoned because gradients are cheap. A selection effect, named and then left behind.
The back half changes genre. Once ViT appears, the argument stops being mechanical and becomes empirical: patches as tokens, pre-norm blocks, a cls vector projected to labels — and the finding that ViT loses to ResNet on small data and wins at scale. That result is the hinge of the whole chapter, because it converts an architectural claim into a claim about regimes. The Transformer's inductive bias is weaker, which is a liability when data is scarce and an asset when it is not. From there the chapter rides power laws through BERT, T5, GPT, Megatron-Turing, Llama, then instruction tuning, RLHF, and chain-of-thought — and here the writing gets thinner and more list-like, because there is less theory to offer. The scaling laws are robust empirical regularities, not explanations, and the chapter does not pretend otherwise, but a reader should notice the register shift: derivations give way to citations.
My sharpest judgement: this chapter is best read as the story of a constraint budget being spent well. Sequence-to-sequence asserted that one intermediate state was a sufficient statistic for the input — a claim false by construction, and naming it in statistical language is far more damning than any talk of bottlenecks. Attention bought back that lost information by relaxing a hard lookup into a differentiable one. Then every subsequent step removed a further constraint: monotonic alignment, fixed similarity metric, single representation subspace, recurrence itself. The Transformer is less an invention than the limit of that deletion process — what remains when you strip out every structural assumption a GPU is willing to pay for in compute instead. Positional encoding is the one constraint added back, and it's worth noticing that it's added back grudgingly, because removing recurrence took the order information with it.
What I'd tell a reader: don't let the elegance of the final diagram convince you the design was deduced. Read the chapter twice, the second time tracking which choices are principled (attend to everything; learn the comparison space), which are hardware-shaped (masking, head partitioning, dot products over additive scores), and which are hopeful conventions that stuck (√d, head counts, the interpretive value of attention maps). Hold on to the Nadaraya–Watson baseline as a reference point for what training actually earns you. Treat the attention heatmaps as diagnostics, never as explanations — the authors warned you twice. And read the scaling-law sections as a report on observed regularities, not a law of nature: the chapter's own opening said that the last decade's leaps came from compute, and the honest version of that claim cuts both ways. If the Transformer's advantage is that it has fewer built-in assumptions and therefore absorbs more data, then its story is still a story about resources, told in a better costume.
Read Chapter 11 with these cards beside each passage.
Open in FeedLitraChapter 12: Optimization Algorithms
Why does ReLU relieve the vanishing-gradient stall?
How Chapter 12 unfoldsAI-assisted
The opening: a deliberate gap between two goals. The chapter begins not with an algorithm but with a distinction. Optimization is the engine that drives deep learning training, yet its target — training error — is not deep learning's target, which is generalization error. The author makes this vivid with a hand-drawn pair of curves: a smooth risk curve and a bumpier empirical-risk curve whose minima sit at different places, so pushing the training curve all the way down to its floor need not land you at the better model. The author is candid that this is a one-dimensional illustration rather than a real network, but it sets the frame for everything that follows. The opening also names the obstacles the rest of the chapter will keep bumping into — local minima, saddle points, and vanishing gradients — and supplies the memorable argument for why saddles, not local minima, are the typical place where descent stalls: at a zero-gradient point the signs of the Hessian's eigenvalues decide the verdict, and requiring every one of many eigenvalues to be positive becomes vanishingly unlikely as dimension grows. A second framing claim lands here too: although virtually every deep learning objective is nonconvex, convexity is where method behavior can actually be proven, which justifies the convexity primer and the full convergence proof the chapter will carry out.
The development: from exact curvature to cheap curvature. With the frame set, the chapter finishes its convexity machinery (the Hessian test) and handles constraints three ways — Lagrangian, penalties, projections — before turning to gradient descent proper: the Taylor-expansion justification, the effect of the learning rate, the trap of local minima, the multivariate update, and then Newton's method with its quadratic convergence. Newton is the chapter's pivot point, because it is introduced in order to be scaled back. The Hessian is a d-by-d object whose roughly d² entries are too large to store and too costly to backpropagate; its quadratic convergence holds only under convexity; and where the second derivative is negative it will happily walk uphill, a failure a learning rate of 0.5 rescues on a nonconvex test function. From this the chapter extracts the idea that survives: keep only the diagonal. Preconditioning gives each coordinate its own learning rate, which is enough to repair a scale mismatch between a variable measured in millimeters and one in kilometers, at a small fraction of the cost. The same "theoretically fast, practically dead" verdict then falls on line search, since every step would require evaluating the objective over the whole dataset.
The turn: stochasticity, and the price it charges. That verdict is what hands the chapter over to SGD. Sampling a single example drops per-iteration cost from order n to constant while leaving the gradient an unbiased estimate of the full one — but the noise has to be paid for. Because a one-example gradient is right on average and noisy in fact, the jitter does not vanish near the minimum and a fixed step keeps the iterate bouncing; the rate must decay. The author demonstrates the asymmetry concretely: inverse-square-root decay improves within fifty steps, while exponential decay kills progress before the iterate arrives. Convex analysis then delivers the promised proof, an O(1/√T) bound with the rate chosen as r/(L·√T), and sampling without replacement is recommended. Minibatching enters as the negotiated settlement between the two extremes. Averaging b examples leaves the gradient's expectation untouched and cuts its standard deviation by b^(−1/2) — a sublinear return against linearly rising compute, which is precisely why "the biggest batch the hardware allows" is the wrong conclusion. The hardware side of the argument comes from vectorized and blocked matrix multiplication and CPU caches: multiplying in blocks of 64 columns is already about as fast as the full 256×256 product. On the 1,500-example airfoil task, full batch stalls after six steps and single-example updates are slow per example, while batch size 100 beats full-batch descent on wall-clock time — with the author noting the caveat that this is one small whitened dataset with a linear model, and that lower batch noise also weakens the regularizing effect batch normalization draws from it.
The build-out: the adaptive family, assembled rather than invented. The chapter's most elegant structural move is to present the modern optimizers as accumulations of fixes already motivated. Leaky averaging of past gradients, introduced in the minibatch discussion, leads straight into momentum, whose job is to repair ill-conditioned descent: directions where gradients keep agreeing accumulate, directions where they flip sign cancel, so the step grows along the useful axis and calms along the steep one, with the geometric series making the effective step about η/(1−β) and the effective sample size 1/(1−β). Momentum gets hands-on code and a quadratic-convex analysis showing coordinate-wise decomposition and a wider convergence range. Adagrad then arrives from a different motivation — sparse features — and reuses accumulated squared gradients as a cheap proxy for the Hessian diagonal. From there each successor fixes its predecessor: RMSProp replaces Adagrad's unbounded running sum, which shrinks steps on a fixed t^(−1/2) schedule regardless of the actual geometry, with a leaky average; Adadelta removes the learning rate entirely by using parameter-change statistics; Adam fuses momentum with second-moment scaling and adds bias correction. Crucially, Adam is not offered as a switch-it-on-and-forget default: the author immediately flags that it can fail to converge even on convex problems when the second moment is poorly controlled, which is exactly what Yogi's sign-based second-moment update and initialization (Zaheer et al., 2018) were proposed to tame.
The close: the schedule matters as much as the algorithm. Having shown that no optimizer removes the need to choose step sizes, the chapter ends on learning rate scheduling. Schedulers set the rate per update — square-root, factor, multi-step, cosine — and warmup ramps the rate up from near zero to avoid early divergence. The final observation closes the loop back to the opening: decaying rates not only smooth convergence but improve accuracy and, somewhat oddly, reduce overfitting. The Fashion-MNIST runs show scheduling changing both the smoothness of training and the amount of overfitting, which is the chapter's concrete payoff on its first page's claim — that two runs can reach the same training error and still generalize differently, so optimization choices are never purely about descending faster.
Key claims, with the lines that support them
Optimization and deep learning pull toward different targets: one lowers error on the training set, the other lowers error on unseen data.
The author draws a smooth risk curve against a bumpier empirical-risk curve and points out their lowest points sit in different places, so driving the training curve to its floor need not land you at the better model — admittedly a hand-built one-dimensional picture, not a real network. Later the author adds that different algorithms and schedules can give different generalization at the same training error.
“Although optimization provides a way to minimize the loss function for deep learning, in essence, the goals of optimization and deep learning are fundamentally different.”
§12.1 Optimization and Deep LearningRead in context →
Even though virtually every deep learning objective is nonconvex, learning convex optimization still pays off.
The author's reason is practical: convexity is where the behavior of the methods can actually be proven, so this chapter includes a convexity primer and a full convergence proof for a simple stochastic method on a convex objective, and those insights then guide how the nonconvex case is handled.
“Almost all optimization problems arising in deep learning are nonconvex. Nonetheless, the design and analysis of algorithms in the context of convex problems have proven to be very instructive.”
Chapter 12. Optimization AlgorithmsRead in context →
Curvature information helps a lot, but in deep learning it has to be approximated cheaply rather than computed exactly.
Building on Newton's method, the author notes the Hessian is a d-by-d object whose roughly d-squared entries are too big to store and too expensive to backpropagate; Newton also only converges quadratically under convexity and can walk uphill where the second derivative is negative (a learning rate of 0.5 rescues it on a nonconvex test function). Keeping just the diagonal gives each coordinate its own rate — enough to fix the mismatch when one variable is measured in millimeters and another in kilometers, at a small fraction of the cost.
“While these methods cannot be applied to deep learning directly due to the computational cost, they provide useful intuition into how to design advanced optimization algorithms that mimic many of the desirable properties of the algorithms outlined below.”
§12.3 Gradient DescentRead in context →
3 more claims
Line search and other full-dataset step rules are theoretically fast but practically dead in deep learning, which is why the stochastic gradient takes over.
Every line-search step requires evaluating the objective over the entire dataset, which the author calls far too costly; by contrast sampling one example drops per-iteration cost from order n to constant while leaving the gradient an unbiased estimate of the full one. The convex analysis then gives a bound on the order of one over the square root of the number of steps with the rate chosen as r/(L·sqrt(T)).
“However, for the purpose of deep learning this is not quite so feasible, since each step of the line search would require us to evaluate the objective function on the entire dataset.”
§12.3 Gradient DescentRead in context →
Minibatches are the right middle ground, and on a real regression run they win on wall-clock time.
Averaging b randomly drawn examples leaves the gradient's expectation untouched while cutting its standard deviation by one over the square root of b, yet past a point extra variance reduction is negligible while compute grows linearly — multiplying in blocks of 64 columns is already about as fast as the full 256-by-256 product. On the 1,500-example airfoil task, full batch stalls after 6 steps and single-example updates are slow per example, while batch size 100 beats full-batch descent in runtime. Caveat: it is one small whitened dataset with a linear model, and smaller batch noise also weakens batch normalization's regularizing effect.
“Since the minibatch gradient is composed of \(b \stackrel{\textrm{def}}{=} |\mathcal{B}_t|\) independent gradients which are being averaged, its standard deviation is reduced by a factor of \(b^{-\frac{1}{2”
§12.5 Minibatch Stochastic Gradient DescentRead in context →
Adaptive methods are assembled from the earlier fixes and are not automatically safe, so the second moment has to be controlled carefully.
The author walks through the lineage — minibatching, momentum, per-coordinate scaling, and the decoupling of the learning rate from that scaling — and presents Adam as their combination. Adagrad's plain running sum of squared gradients grows without bound and shrinks steps on a fixed order-t-to-the-minus-half schedule regardless of the actual geometry, which RMSProp's leaky average repairs; Adam in turn can fail to converge even on convex problems, prompting the refined sign-based second-moment update and initialization of Zaheer et al. (2018).
“Adam combines features of many optimization algorithms into a fairly robust update rule.”
§12.10 AdamRead in context →
How it works
The 3 mechanisms the chapter’s argument runs on.
Mechanism 1
Why saddles beat local minima
At a zero-gradient point the signs of the Hessian's eigenvalues decide whether it is a minimum, maximum, or saddle. A true minimum needs every one of the many eigenvalues to be positive, and that gets less and less likely as dimension grows, so mixed signs — saddles — become the typical stalling point.
Mechanism 2
Why SGD must shrink its steps
A single-example gradient is right on average but noisy, so near the minimum the noise does not vanish and a fixed step keeps bouncing the iterate around. Shrinking the rate over time damps that jitter; the author shows inverse-square-root decay improves within 50 steps while exponential decay kills progress before arriving.
Mechanism 3
How momentum fixes oscillation
Momentum replaces the raw gradient with a decaying average of past gradients. Directions where gradients keep pointing the same way add up, while directions where they flip sign cancel out, so the step grows along the useful axis and calms down along the steep one — the geometric series makes the effective step about eta/(1-beta).
Common misreadings
Since Adam bundles together momentum, per-coordinate scaling, and bias correction, it is a robust default you can just switch on and stop worrying about step sizes.
The author presents Adam as a useful combination but immediately flags that it can fail to converge even on convex problems when its second-moment estimate is poorly controlled, which is exactly why a refined update and initialization were proposed as a fix. And the rate schedule still has to be chosen by hand — the Fashion-MNIST runs show scheduling changing both the smoothness of training and the amount of overfitting.
“Adam combines features of many optimization algorithms into a fairly robust update rule.”
§12.10 AdamRead in context →
Because averaging b examples shrinks gradient noise, the biggest batch your hardware allows is the best choice.
The noise only falls as one over the square root of the batch size, so the gain flattens out while compute keeps rising in proportion to b — the author shows 64-column minibatches already running about as fast as the whole matrix product, and on the airfoil task the full batch of 1,500 stalled after six steps while a batch of 100 beat it on runtime. Less batch noise also removes some of the regularizing effect that batch normalization gets from that noise.
“Since the minibatch gradient is composed of \(b \stackrel{\textrm{def}}{=} |\mathcal{B}_t|\) independent gradients which are being averaged, its standard deviation is reduced by a factor of \(b^{-\frac{1}{2”
§12.5 Minibatch Stochastic Gradient DescentRead in context →
Key concepts in Chapter 12
- Empirical risk
- The average loss measured on the finite training set, as opposed to expected loss over the whole population.
- Where it applies: Its minimum can sit at a different location than the minimum of the true risk.
- Saddle point
- A point where all gradients vanish but which is neither a local nor global minimum.
- Where it applies: Identified by mixed-sign Hessian eigenvalues; becomes more likely than local minima in high dimensions.
- Vanishing gradient
- Gradients so near zero that parameter updates stall for a long time.
- Where it applies: Tied to saturating activation functions; mitigated by ReLU and reparametrization.
- Convex function
- A function whose chord never lies below the function, equivalently whose Hessian is never negative.
- Where it applies: Most deep learning problems are nonconvex, yet convex analysis remains instructive.
- Lagrangian
- Add each constraint, scaled by a nonnegative multiplier, to the objective; solving the constrained problem becomes finding a saddle point.
- Where it applies: Optimality guarantees rely on convexity; multipliers of inactive constraints go to zero.
- Penalty method
- Instead of enforcing a constraint exactly, add its scaled violation to the loss so it is never badly broken.
- Where it applies: Only approximate satisfaction; in nonconvex problems convex-case guarantees are lost.
26 more concepts
- Projection
- Snap a point back to the nearest point of a convex set; points already inside are untouched.
- Where it applies: Direction is preserved for l2 balls but not for sets like the l1 diamond.
- Weight decay
- Adding a squared-norm penalty to the loss, which is really an approximate norm-ball constraint on the weights.
- Where it applies: Equivalent to a radius constraint only approximately; the radius is controlled indirectly via lambda.
- Gradient descent
- Repeatedly step against the gradient; a first-order Taylor expansion shows small steps lower the objective.
- Where it applies: Only decreases the value when the step is small enough that higher-order terms stay negligible.
- Learning rate
- The fixed step size; too small crawls, too large overshoots and can diverge.
- Where it applies: Chosen by the designer; its safe range depends on curvature and conditioning.
- Newton's method
- Use curvature by multiplying the gradient by the inverse Hessian, giving very fast steps near a minimum.
- Where it applies: Hessian storage is O(d^2) and a negative second derivative can send the step uphill.
- Hessian positive semidefiniteness
- A twice-differentiable function is convex exactly when its matrix of second derivatives never curves downward in any direction.
- Where it applies: Requires twice differentiability; reduces to the one-dimensional test along every line segment.
- Preconditioning
- Use only the diagonal of the Hessian to rescale each coordinate, i.e. one learning rate per variable. Rescaling coordinates so eigenvalues become comparable, making descent easier; exact rescaling needs eigenvalues, so cheap approximations are used.
- Where it applies: Weaker than full Newton's method and it does not capture cross-coordinate curvature. Exact eigendecomposition costs more than solving the problem; diagonal rescaling is the practical compromise.
- Gradient Descent with Line Search
- Keep the gradient direction but binary-search the step size that minimizes the objective.
- Where it applies: Infeasible for deep learning since each search step needs a full-dataset objective evaluation.
- Minibatch stochastic gradient descent
- A middle ground between full-batch gradient descent and one-example SGD, chosen mainly for computational efficiency. Updating parameters with the averaged gradient of a small random batch instead of one example or the whole set.
- Where it applies: Its size is driven by hardware: device count, vectorization width and cache bandwidth. Gains stop once extra variance reduction is tiny relative to linearly growing compute cost, and batch must fit GPU memory.
- Dynamic learning rate
- A time-dependent schedule eta(t): piecewise constant, exponential decay, or polynomial decay.
- Where it applies: Decay too fast and optimization stops early; too slow and time is wasted.
- Vectorization
- Doing many arithmetic operations in one framework call so data stays in cache and interpreter overhead is paid once.
- Where it applies: Helps only when the matrices or blocks involved fit usefully into cache; libraries handle the blocking.
- Leaky average (velocity)
- A running sum v_t = beta*v_{t-1} + g_t that mixes past gradients into the current step direction.
- Where it applies: Large beta averages over a long range; beta = 0 recovers plain gradient descent.
- Momentum
- Using the accumulated velocity instead of the raw gradient, so aligned directions build up and oscillating ones cancel.
- Where it applies: Most valuable for ill-conditioned problems; too small a beta barely converges.
- Ill-conditioned problem
- An objective whose curvature differs wildly by direction, so one learning rate is either too slow or divergent.
- Where it applies: Illustrated here by the stretched quadratic f(x) = 0.1 x_1^2 + 2 x_2^2.
- Effective sample weight
- Because past gradients decay by beta, momentum effectively averages about 1/(1-beta) gradients and takes a step of size eta/(1-beta).
- Where it applies: Holds in the limit of many steps with constant beta; needs the learning rate lowered to stay stable.
- Condition number
- Ratio of largest to smallest eigenvalue of the quadratic matrix; large values make the problem hard to solve accurately.
- Where it applies: Defined for positive definite quadratic objectives; only an intuition in nonconvex deep learning.
- Adagrad
- Optimizer that accumulates squared gradients per coordinate and divides the learning rate by their square root, giving each coordinate its own schedule.
- Where it applies: Adequate for convex problems; in deep learning its decay can be too aggressive.
- Sparse features
- Features that occur only rarely, so their parameters get few meaningful updates under a globally decaying learning rate.
- Where it applies: The counter-based fix fails when data is not truly sparse but merely has rarely-large gradients.
- RMSProp
- Adagrad with a leaky (exponentially weighted) average of squared gradients, so the learning rate is no longer forced to decay.
- Where it applies: The experimenter must still schedule the learning rate; gamma controls history length.
- Adadelta
- A variant that keeps two leaky averages — of squared gradients and of squared parameter changes — and so needs no learning rate.
- Where it applies: Uses rho as its single parameter; adaptivity across coordinates is reduced.
- Adam
- Combines leaky-averaged momentum and second moment, with bias correction, then rescales the gradient like RMSProp.
- Where it applies: Can diverge when the second moment estimate blows up or gradient variance is high.
- Yogi
- An Adam fix whose second-moment update size depends only on the squared gradient, not on how far it deviates from the old estimate.
- Where it applies: Addresses divergence from sparse or high-variance updates; other details are omitted here.
- Learning rate scheduling
- Deliberately choosing the size, decay, and warmup of the learning rate over training. An initial phase where the learning rate rises linearly to its maximum before decaying.
- Where it applies: Cyclical schedules are out of scope here; frameworks provide scheduler tools. Applies to any scheduler; most useful for deep or unstable architectures.
- Learning rate scheduler
- A function that returns the learning rate given the update count, instead of keeping it fixed.
- Where it applies: Needs a chosen policy and horizon; gains are empirical, not guaranteed.
- Cosine scheduler
- A schedule that decays the rate along a cosine curve from an initial to a final value.
- Where it applies: Popular in computer vision; improvements are not guaranteed.
- Overfitting
- Training accuracy keeps rising while test accuracy stalls, leaving a gap between curves.
- Where it applies: Here it is affected by optimization choices, not only by model capacity.
Reader’s notes on Chapter 12AI reading companion
“might well content oneself with the knowledge that there exists an array of incantations”
Read in context →"Incantations" is the authors winking at their own readers — magic words you chant without understanding. The whole chapter's pitch is in that one sarcastic noun.
“As a result, here g is less smooth than f.”
Read in context →Neat sleight of hand: finite data is modeled as a cosine ripple added on top. Honest as a cartoon, but real sampling noise isn't a tidy periodic wiggle — the picture is persuasive partly because it's rigged.
“Only some degree of noise might knock the parameter out of the local minimum.”
Read in context →The bug becomes the feature — minibatch sampling error, elsewhere a nuisance, is rebranded as an escape mechanism. Deep learning's recurring trick: sloppiness that pays.
17 more notes
“For high-dimensional problems the likelihood that at least some of the eigenvalues are negative is quite high.”
Read in context →This is the real payoff of the section: in high dimensions, needing all k eigenvalues to agree in sign is a coincidence. So local minima are rare and saddles everywhere — which quietly dissolves the folk fear about getting trapped.
“it is not really necessary to find the best solution”
Read in context →After pages of listing traps, the escape is to lower the bar. Not resignation — it follows from the first section: the true objective was never the training minimum anyway.
“if the algorithm performs poorly even in the convex setting, typically we should not hope to see great results otherwise”
Read in context →The honest justification for a convexity chapter in a nonconvex book: convexity is a filter, not a model. It can refute an algorithm, never endorse one.
“This can lead to exciting new optimization variants such as”
Read in context →The sentence just stops. A dangling citation that never got filled in — a fossil of the book's build pipeline left in the prose.
“To see that the converse is not true, consider two disjoint sets”
Read in context →Careless phrasing: what's being shown isn't a converse at all, it's that unions fail to inherit convexity. The proof is right; the logical label on it is wrong.
“lambda f(x) + (1-\lambda) f(x') \geq f(\lambda x + (1-\lambda) x”
Read in context →Worth pausing on the geometry rather than the symbols: the chord sits above the curve. Everything later — Jensen, below sets, local=global — is just this one picture reused.
“the expectation of a convex function is no less than the convex function of an expectation”
Read in context →Jensen isn't a new fact, it's convexity with infinitely many λ's. Calling it a tool to "bound a complicated expression by a simpler one" is the practitioner's reading — and it's exactly how the variational bound later earns its keep.
“this does not mean that there cannot be more than one global minimum or that there might even exist one”
Read in context →The caveat I respect most here. Convexity buys you no traps, not a destination — exp(x) descends forever and never arrives.
“we have \(f(x^{\ast}) < f(x”
Read in context →Strict inequality smuggled into the definition of local minimum — with the usual ≤ this contradiction proof needs more care. Small slip in an otherwise tidy argument.
“the forces of gravity will be balanced out with the forces that the sides of the box can impose”
Read in context →The ball-in-a-box is the best thing in this section: multipliers as contact forces, and inactive constraints as walls the ball never touches, so α=0. Physics explains complementary slackness without naming it.
“In fact, we have been using this trick all along. Consider weight decay”
Read in context →The retroactive reveal — weight decay was a Lagrangian in disguise. This is the book's signature move: tell you the machinery, then show you've been driving it blind for nine chapters.
“In practice this turns out to be much more robust than exact satisfaction”
Read in context →Asserted, not argued. Why is approximate more robust? The honest answer — gradients hate hard walls — goes unsaid.
“While for \(\ell_2\) balls this leaves the direction unchanged, this need not be the case”
Read in context →The quiet heart of why L1 gives sparsity: the diamond's corners bend direction, so projection snaps coordinates to zero. The text points at it and walks on.
“the main purpose of convex functions is to motivate optimization algorithms”
Read in context →A rare admission: the whole convexity apparatus is scaffolding, not foundation. Deep learning is nonconvex and we reason with borrowed intuitions anyway.
“the value of function \(f(x)\) might decline”
Read in context →"Might." The whole edifice of modern training rests on a hedged verb, and the hedge is correct.
“This means that if the second derivative is negative we may walk into the direction of increasing”
Read in context →Newton's method doesn't seek minima — it seeks stationary points. On a saddle it climbs happily. Worth remembering when people call second-order methods "smarter."
“optimization researchers call this linear convergence”
Read in context →This is backwards — quadratic error decay is called quadratic convergence; linear is the α|e| case. A genuine slip in a careful book, and a confusing one for a first reader.
A reader’s takeAI reading companion
The wedge between what we optimize and what we want never closes
Read as one piece, this chapter is an honest book about dishonest terrain. It opens by driving a wedge between optimization's goal and deep learning's — training error versus generalization error — and that wedge never closes; it is the reason the chapter can catalogue local minima, saddles, and vanishing gradients and then shrug that we need not find the best solution. The shrug is not defeatism, it is the first section's logic cashed in: the training minimum was never the target. Along the way the chapter performs its signature reversal, turning minibatch noise from a defect into the escape hatch that knocks parameters out of bad basins, and showing in high dimensions that requiring all eigenvalues to share a sign is a coincidence — so saddles, not traps, are the real landscape, and the folk fear of local minima quietly dissolves.
The convexity section is scaffolding, and the book says so: convexity is a filter that can refute an algorithm but never endorse one, and its whole apparatus reduces to one picture, the chord above the curve, reused as Jensen, as sublevel sets, as local-equals-global. Constraints arrive with the chapter's best image — the ball in the box, multipliers as contact forces, untouched walls contributing nothing — and then the retroactive reveal that weight decay was a Lagrangian all along, the book's habit of letting you drive the machinery for nine chapters before naming it. From there the arc is relentlessly economic: gradient descent justified by a hedged Taylor 'might'; Newton's method exposed as a seeker of stationary points, cheerfully climbing saddles, which should temper anyone's reverence for second-order 'smartness'; preconditioning keeping only the Hessian's diagonal because that is what we can afford; line search discarded outright because a full-dataset step is unaffordable; SGD trading an O(n) gradient for an O(1) unbiased one and paying in noise that forces polynomial, not exponential, decay; minibatches buying a b^(-1/2) cut in gradient deviation plus cache-friendly vectorization.
Continue reading
Then the adaptive family, which is one idea refined four times: accumulate gradient statistics as a poor man's Hessian diagonal (Adagrad), stop the accumulation from strangling the step (RMSProp), remove the learning rate entirely using parameter-change units (Adadelta), fuse first and second moments with bias correction (Adam), and tame the resulting variance (Yogi). The closing twist is the quietest and most useful: after all that algorithm design, scheduling the learning rate — warmup to survive the early steps, cosine or multi-step decay afterwards — matters as much as the choice of optimizer, and decay improves accuracy while oddly reducing overfitting, which loops straight back to the generalization gap the chapter opened with.
What I would tell a reader: the chapter is trustworthy but not infallible — it mislabels quadratic convergence as linear, calls a non-converse a converse, smuggles a strict inequality into a local-minimum definition, leaves a dangling 'such as.' that never got its citation, and illustrates empirical risk's roughness with a tidy cosine ripple that is more cartoon than sampling noise. Read the geometry, not the symbols; notice what is asserted rather than argued (projection being 'more robust' than exact satisfaction, the L1 diamond's corners that produce sparsity and get one passing sentence); and take the opening joke about 'incantations' seriously, because the chapter's real achievement is converting a handful of them into reasons, while being candid that the rest remain incantations we use anyway.
Read Chapter 12 with these cards beside each passage.
Open in FeedLitraChapter 13: Computational Performance
How does hybridization keep imperative debugging while gaining symbolic speed?
How Chapter 13 unfoldsAI-assisted
This chapter opens by establishing why computational performance deserves a chapter of its own: once data and models grow large, the cost of getting work done becomes as consequential as the modeling choices themselves. The entry point is a programming-style contrast. Imperative Python hands each statement to the interpreter separately, so per-call overhead is paid again and again, and every intermediate value stays alive until the enclosing function returns. On a single slow device this bookkeeping hides inside the arithmetic; once the arithmetic moves to fast GPUs, it starts to dominate. Symbolic programming is set against this: a compiler that sees the whole program first can rewrite print(1+2+3+4) as print((1+2)+(3+4)) or fold it to print(10), and can free memory the moment a value is dead — optimizations unavailable to step-by-step execution, at the cost of harder debugging. Hybridization is the chapter's resolution, keeping the imperative authoring experience while handing a compiled graph to the runtime.
From there the chapter descends into hardware, touring the machine part by part as a catalogue of bottlenecks: PCIe-linked components, memory, storage, caches and vector units, GPUs with tensor cores, and networks. Two mechanisms carry the section. First, the opening read dominates memory cost — sending an address and setting up a transfer runs about 100 ns while each subsequent record arrives in roughly 0.2 ns, making the first access hundreds of times dearer than its successors; long consecutive runs amortize that setup, scattered access pays it every time. Second, caches exist because cores would otherwise starve: a 2 GHz quad-core with vector units could consume around 256 GB/s while its memory interface supplies only 20–40 GB/s, so expensive chip area goes to L1/L2/L3 to hold a reusable working set. Storage carries a warning against a tempting simplification: an SSD is not merely a quick hard disk. Its throughput advantage is enormous — 100,000–500,000 IOPs against a disk's roughly 100, and 1–3 GB/s against 100–200 MB/s — yet writes happen in blocks of 256 KB or more and cells wear out, so bit-wise random writes perform badly; controllers soften this without removing it.
The pivot comes when the chapter converts these latency and bandwidth facts into a training strategy. Three ways to split work across GPUs are laid out — partitioning the network across devices, splitting by layers, and splitting the data — and data parallelism is chosen, provided the model fits on one GPU. Each GPU keeps a full copy and processes a different slice of the minibatch, so synchronization happens once per minibatch and the scheme generalizes everywhere. The argument against model parallelism is explicitly about communication rather than arithmetic: carving a network by layers or channels demands a great many synchronization and barrier operations, and the interfaces between layers must ship activations and gradients in volumes that can swamp the bus, with NVLink's 300 Gbit/s per server link against 100 Gbit/s on consumer cards marking how hard that ceiling is. AlexNet's layer split is read as an artifact of 2 GB GPUs, a constraint since lifted. The honest limits are stated too: data parallelism cannot train a model larger than one GPU's memory, and with k GPUs the effective batch grows k-fold.
Implementation follows the argument. A from-scratch LeNet version builds allreduce and minibatch splitting by hand, then a concise high-level DataParallel version trains ResNet-18. The LeNet experiment doubles as a corrective to the assumption that more GPUs mean faster training: with batch size and learning rate unchanged, two GPUs leave test accuracy roughly where it was and yield no meaningful speedup, because the model is too small to keep a second device busy. Speedup requires enough work per GPU, not merely more GPUs.
The closing movement generalizes the bus lessons into distributed infrastructure. Where gradients are summed turns out to matter by a large factor even though the mathematics is unchanged: aggregating 160 MB onto one GPU costs about 60 ms and routing it through the CPU about 80 ms, while splitting the same data into four 40 MB parts aggregated in parallel takes 15 ms, because real buses differ in bandwidth. Ring synchronization pushes this further — on an idealized ring, cutting gradients into n chunks each launched from a different node gives total time (n−1)/n, about 1 regardless of n, and a measured 160 MB ring over eight V100s runs in roughly 6 ms, beating PCIe, though real figures degrade when frameworks fail to assemble large burst transfers. Scaling to many machines, a single server's finite bandwidth makes send time grow as O(m) with m workers, whereas n servers each holding O(1/n) of the parameters reduce it to O(m/n), restoring constant scaling. The chapter ends on the abstraction that makes this tractable: workers push gradients and pull updated values by key, a design justified by the fact that gradient summation is a commutative reduction, so arrival order does not matter.
Key claims, with the lines that support them
Compiling the whole program before running it lets the system optimize in ways step-by-step execution cannot.
Set against the line-by-line style just criticized, a compiler gets to see all the code first: the sample program could be rewritten as print((1 + 2) + (3 + 4)) or collapsed outright to print(10), and memory can be freed as soon as a value is no longer needed — the trade-off being that such code is harder to debug.
“This is possible since a compiler gets to see the full code before turning it into machine instructions.”
§13.1 Compilers and InterpretersRead in context →
For training across several GPUs, splitting the data is the default to reach for, provided each GPU can hold the model.
Every GPU keeps a full copy of the model and processes a different slice of the minibatch, so synchronization is needed only once per minibatch and the scheme applies in any situation; the author points out that AlexNet split layers across devices only because GPUs then had 2 GB of memory, a constraint since largely lifted. It still cannot train a model larger than one GPU's memory, and with k GPUs the effective batch grows k-fold.
“By and large, data parallelism is the most convenient way to proceed, provided that we have access to GPUs with sufficiently large memory.”
§13.5 Training on Multiple GPUsRead in context →
Model parallelism fails on communication cost, not on arithmetic.
This is the author's reason for preferring the data split: carving a network up by layers or by channels forces a very large number of synchronization and barrier operations, and the interfaces between layers must ship activations and gradients in volumes that can swamp the GPU bus — NVLink's 300 Gbit/s per link on server cards against 100 Gbit/s on consumer ones shows how real that interconnect limit is.
“However, we need a very large number of synchronization or barrier operations since each layer depends on the results from all the other layers.”
§13.5 Training on Multiple GPUsRead in context →
3 more claims
Even though the mathematics is identical, where gradients are summed changes synchronization time by a large factor.
Turning the bus-level lessons into practice: aggregating 160 MB onto one GPU costs about 60 ms and routing it through the CPU about 80 ms, but splitting the same data into four 40 MB parts aggregated in parallel takes only 15 ms, because real hardware buses differ in bandwidth.
“However, we are dealing with real physical hardware where different buses have different bandwidth as discussed in Section 13.4.”
§13.7 Parameter ServersRead in context →
Passing gradient chunks around a ring makes aggregation time roughly independent of how many devices take part.
Following on from the point about aggregation sites: on an idealized ring, cutting the gradients into n chunks each launched from a different node gives a total time of (n-1)/n, about 1 regardless of n, and in measurement a ring synchronization of 160 MB over eight V100 GPUs takes roughly 6 ms, beating the PCIe bus. Real figures are worse when frameworks fail to assemble large burst transfers.
“In other words, the time spent to aggregate gradients does not grow as we increase the size of the ring.”
§13.7 Parameter ServersRead in context →
Spreading parameters over many servers removes the single-server bandwidth bottleneck and restores constant scaling.
Generalizing the same aggregation lesson to many machines: one server's bandwidth is finite, so with m workers the send time grows as O(m), whereas n servers each storing only O(1/n) of the parameters cut it to O(m/n). Workers then push gradients and pull back updated values by key, which is sound because gradient summation is a commutative reduction and arrival order does not matter.
“At this point each server only needs to store \(\mathcal{O}(1/n)\) of the parameters, hence the total time for updates and optimization becomes \(\mathcal{O}(m/n)”
§13.7 Parameter ServersRead in context →
How it works
The 3 mechanisms the chapter’s argument runs on.
Mechanism 1
Why line-by-line Python runs slow
Each statement is handed to the interpreter on its own, so the per-call overhead is paid over and over, and every intermediate value must be kept alive until the function finishes. On a single slow device this barely shows; once the arithmetic runs on fast GPUs the bookkeeping starts to dominate.
Mechanism 2
The first read dominates memory cost
Sending an address and setting up a transfer costs roughly 100 ns, while each record that follows arrives in about 0.2 ns. The opening read is therefore hundreds of times dearer than its successors, so reading long consecutive runs spreads that setup over many records, whereas scattered access pays it again every time.
Mechanism 3
Caches keep starved cores fed
A 2 GHz quad-core with vector units could consume about 256 GB/s, but its memory interface supplies only 20-40 GB/s, so cores would sit idle waiting for data. Small fast local memories (L1/L2/L3) hold the working set so it is reused rather than refetched, which is why chip area is spent on them.
Common misreadings
Once data parallelism is in place, adding more GPUs will shorten training time.
Speedup appears only when there is enough work per GPU. Training LeNet on Fashion-MNIST with the batch size and learning rate unchanged and two GPUs leaves test accuracy roughly the same and brings no meaningful speedup, because the model is simply too small to keep the extra device busy.
“Unfortunately there is no meaningful speedup to be gained here: the model is simply too small; moreover we only have a small dataset, where our slightly unsophisticated approach to implementing multi-GPU training suffered from significant Python overhead.”
§13.5 Training on Multiple GPUsRead in context →
An SSD is just a faster hard disk, so any access pattern on it will be fast.
SSDs do win hugely on throughput — 100,000 to 500,000 IOPs against a hard disk's roughly 100, and 1-3 GB/s against 100-200 MB/s — but they are written in whole blocks of 256 KB or larger and their cells wear out, so bit-wise random writes perform very poorly. Controllers and firmware soften this penalty without removing it.
“Consequently bit-wise random writes on SSD have very poor performance.”
§13.4 HardwareRead in context →
Key concepts in Chapter 13
- Imperative programming
- Writing statements that run one by one and change program state as Python interprets them.
- Where it applies: Convenient and easy to debug, but interpreter overhead grows on fast or multiple GPUs.
- Symbolic programming
- Define the whole computation first, compile it, then run it with inputs.
- Where it applies: Harder to debug, but enables compiler optimization and Python-independent deployment.
- Burst read
- Reading a long run of consecutive memory records after paying the address setup cost once.
- Where it applies: Only helps when access is sequential; random reads lose the advantage.
- Vectorization
- One instruction operating on many numbers at once inside wide registers.
- Where it applies: Boosts CPU throughput but is still dwarfed by GPU core counts.
- Cache hierarchy
- Small fast local memories (L1/L2/L3) that keep cores fed when main memory is too slow.
- Where it applies: Costs chip area, and misses or false sharing can make parallel code slower.
- Tensor cores
- Dedicated GPU circuits for small matrix multiplications used in deep learning.
- Where it applies: Optimized only for small matrices between 4x4 and 16x16 depending on precision.
7 more concepts
- Data parallelism
- Every GPU holds a full copy of the model and processes a different slice of the minibatch; gradients are summed and broadcast back.
- Where it applies: Does not let you train models larger than one GPU's memory.
- Model parallelism
- Splitting the network itself across GPUs, either by assigning layers to devices or by splitting each layer's channels/units.
- Where it applies: Needs tight synchronization and heavy inter-GPU transfer; not recommended without strong framework support.
- allreduce
- An operation that sums a vector across all devices and broadcasts the result back to each of them.
- Where it applies: Requires copying data to the accumulating device first.
- Minibatch stochastic gradient descent
- Training updates computed on small random batches; here each GPU computes a partial gradient on its shard.
- Where it applies: With k GPUs the effective batch grows k-fold, so learning rate may need adjusting.
- Parameter server
- A central (or sharded) store that aggregates gradients from workers and sends back updated parameters.
- Where it applies: A single server's finite bandwidth makes it a bottleneck; sharding across n servers restores scaling.
- Ring synchronization
- Splitting gradients into chunks and passing them around a ring of GPUs so all links work at once.
- Where it applies: Optimal for p3 and DGX-2 style NVLink topologies, not for every server.
- Key--value store with push and pull
- An abstraction where workers push gradients keyed by layer and pull back aggregated values.
- Where it applies: Works because gradient aggregation is a commutative reduction, so arrival order does not matter.
Reader’s notes on Chapter 13AI reading companion
“a compiler might optimize and rewrite the above code into print((1 + 2) + (3 + 4)) or even print(10)”
Read in context →The cleanest illustration in the section — but notice it quietly flatters symbolic programming by picking an example where all inputs are constants. Real networks have no such luxury.
“This is because we do not know whether the variables e and f will be used by other parts of the program”
Read in context →The real cost of imperative code isn't the arithmetic, it's the ignorance. Interpreters must hoard because they can't see ahead.
“This seems almost too good to be true: write the same code as before and simply convert the model”
Read in context →The author half-admits it with that phrasing. In practice torch.jit.script chokes on anything with interesting control flow — which is exactly the code imperative style was praised for.
17 more notes
“Python is single-threaded and this is unlikely to change in the future”
Read in context →Written confidently, and already dated — the GIL-removal work landed after. Worth reading as a snapshot of 2020 assumptions.
“The benchmark output via PyTorch is orders of magnitude faster.”
Read in context →A deliberately planted false conclusion, retracted two sentences later. Good pedagogy: let the reader feel the trap of unsynchronized timing before naming it.
“the first read is 500 times as expensive as subsequent ones”
Read in context →This single ratio explains more about deep learning performance than most of the chapter — contiguous layouts, batching, why strided access kills you.
“the difference between being able to train a network (e.g., in a week) and not at all (in 3 months, thus missing the deadline)”
Read in context →Candid framing: infeasible here means institutional, not mathematical. The hardware chapter's real subject is deadlines.
“If they were much faster they would shatter due to the centrifugal force exerted on the platters”
Read in context →The bluntest sentence in the chapter: the 100 IOPs ceiling isn't engineering laziness, it's material science. Physics sets the number, not Moore's law.
“the bit rate only scales with the square root of the information density”
Read in context →A lovely, under-advertised consequence — capacity grows as area, throughput only as a line across it. Denser disks get relatively slower to drain.
“it is not recommended to use SSDs for swapping files or for large aggregations of log-files”
Read in context →Note what this implies: the storage device has a lifetime measured in writes, so your access pattern literally consumes hardware. Few programmers think in those units.
“the memory interface of such a chip only supports 20–40 GB/s data transfer, i.e., one order of magnitude less”
Read in context →This arithmetic is the whole hardware chapter in miniature — compute outran memory by 10x, and every cache, every tiling trick, is reparations for that gap.
“During this operation both processors wait.”
Read in context →False sharing is the chapter's best cautionary tale: two threads touching nothing in common logically, serialized by a cache line. Parallelism punished by geometry.
“This co-evolution of hardware and algorithms has led to a situation where for better or worse deep learning is the preferable statistical modeling paradigm.”
Read in context →"For better or worse" is doing heavy lifting. The authors admit the method won partly because silicon happened to favor dense matrix multiply — a fact about chips masquerading as a fact about intelligence.
“the access pattern of sparse matrices and vectors do not go well with the high bandwidth burst read operations where GPUs excel”
Read in context →The flip side of the previous admission: whatever is sparse or irregular gets exiled from research fashion, not because it's wrong but because it benchmarks badly.
“individual blocks can be added or removed as needed to allow for more compact chips and to deal with yield issues (faulty modules might not be activated)”
Read in context →So the product tiers you shop between are partly a map of manufacturing defects. The "mid-range" GPU is often a broken flagship, sold honestly.
“No machine learning researcher within their right mind would use it to build a cluster of servers.”
Read in context →A rare joke, and it earns its place — it makes the four design parameters memorable by showing one corner of the space being absurd.
“We recommend that you sketch out the performance of a novel algorithm on paper before verifying the experimental results.”
Read in context →The real moral of the section, and it's methodological, not factual: if you can't predict your throughput within an order of magnitude, you don't understand your own code.
“It remains a difficult problem and it is unclear whether it is possible to achieve good (linear) scaling on nontrivial problems.”
Read in context →Refreshing to see a textbook end a subsection with an open shrug rather than a recipe. Model parallelism gets named and then politely waved off.
“Thus, we do not recommend this approach due to its bandwidth cost and complexity.”
Read in context →Blunt verdict mid-exposition. The book explains model parallelism mostly to tell you not to use it — a historical artifact of 2 GB GPUs, kept for pedagogy.
“However, adding more GPUs does not allow us to train larger models.”
Read in context →The one sentence that dates the chapter. Written when models fit on a card; today's LLM era reinstated exactly the model parallelism just dismissed.
A reader’s takeAI reading companion
Computing outpaces memory feeding it: root of optimization
This chapter is the one place in the book where deep learning stops being mathematics and becomes an engineering problem with a budget, and its arc is a steady descent from abstraction into matter. It opens with programming paradigms — imperative versus symbolic — and the honest diagnosis that the interpreter's sin is not slow arithmetic but ignorance: it must hoard every intermediate because it cannot see what the next line will want. The illustration chosen (all-constant inputs, folded to print(10)) quietly flatters the symbolic side, and the book's own hedge, 'this seems almost too good to be true,' tells you what the scripting tools actually deliver on code with interesting control flow.
Then the floor drops to hardware, and here the chapter becomes genuinely excellent: a single arithmetic comparison — a chip that computes faster than its memory interface can feed it by an order of magnitude — silently explains every cache, tile and batching trick that follows. The 500-to-1 cost of a first read over subsequent ones explains contiguous layouts; the spinning-platter IOPs ceiling is set by centrifugal force, not by Moore's law; bit rate scales only as the square root of density, so denser disks get relatively slower to drain; SSD lifetime is measured in writes, meaning your access pattern literally consumes the hardware.
Continue reading
False sharing is the best cautionary tale in the book: two threads that share nothing logically, serialized by the geometry of a cache line. From there it climbs back up to multi-GPU training — network partitioning and layerwise splitting named and then politely dismissed, data parallelism implemented from scratch with allreduce and then handed to the framework — and finally to parameter servers, ring synchronization and the push/pull key-value abstraction, where the organizing principle is always bandwidth topology rather than elegance. What I saw through, and what I think is the chapter's bravest moment, is the parenthetical 'for better or worse': the admission that deep learning won partly because silicon happened to reward dense matrix multiplication, and that whatever is sparse or irregular gets exiled from research fashion for benchmarking badly rather than for being wrong.
That is a fact about chips wearing the costume of a fact about intelligence, and the authors let it stand. The same candour runs through the framing of infeasibility as institutional — a week versus three months and a missed deadline — and through the GPU product tiers that are partly a map of manufacturing defects, the mid-range card being a flagship with blocks switched off. The chapter is also visibly a document of around 2020. 'Python is single-threaded and this is unlikely to change' has since been overtaken; and the line 'adding more GPUs does not allow us to train larger models' is the sentence that dates everything, because the LLM era reinstated precisely the model parallelism this chapter explains mostly in order to warn you off.
Read those not as errors but as a fossil record of what the constraints used to be. What I would tell the reader: take the methodological advice seriously, because it is the real moral and it outlasts every number here — sketch the expected performance of your algorithm on paper before you measure it. The planted false conclusion about PyTorch being 'orders of magnitude faster,' retracted two sentences later once synchronization is explained, is there to teach you that benchmarks lie by default. If you cannot predict your own throughput to within an order of magnitude, you do not yet understand your code, and no framework will understand it for you.
Learn the ratios, not the specifications; the specifications expire, the ratios keep governing.
Read Chapter 13 with these cards beside each passage.
Open in FeedLitraChapter 14: Computer Vision
How exactly do image augmentation and fine-tuning improve generalization differently?
How Chapter 14 unfoldsAI-assisted
Opening. The chapter begins by grounding computer vision in everyday stakes rather than in theory: medical diagnosis, self-driving vehicles, camera monitoring, smart filters. The claim attached to these examples is that deep learning is the engine behind recent progress, and the organizing idea follows from it — the layerwise image representations a CNN learns can be reused across tasks. From that premise the author lays out a route for the chapter: first image augmentation and fine-tuning, presented as tools for generalization; then object detection; then semantic segmentation; then style transfer; and finally two popular benchmark datasets where this chapter's material and earlier chapters' material get applied together. The opening is thus both a motivation and a map, and the map is honored in order.
First development: from "what" to "what and where." Object detection enters as a widening of the classification problem — the model must name the category and locate it — and the chapter spends its longest stretch building the machinery that makes location trainable. Positions become bounding boxes in two interconvertible formats; anchor boxes are then generated per pixel across scales and aspect ratios; IoU supplies a similarity measure; and an assignment algorithm turns every anchor into a labeled training example. The worked IoU matrix is the pedagogical core here: the largest entry assigns ground truth B3 to anchor A2, that row and column are struck out, and the procedure repeats to give B1→A7, B4→A5, B2→A9, after which leftover anchors are matched only if their IoU clears 0.5. Run against a dog and a cat, this makes A4 cat, A1 dog, A2 cat by threshold, while A0 and A3 fall below the threshold and become background — the negative anchors. Prediction then runs the labeling in reverse: offsets are inverted to recover boxes, and non-maximum suppression prunes the overlaps.
The turn inside detection: a cost constraint reshapes the design. The chapter's most consequential move is to let a counting argument dictate architecture. Covering every scale–ratio pair would produce w·h·n·m boxes, and even five per pixel on a 561×728 image already yields over two million boxes to label and predict. The author therefore keeps only pairs sharing the first scale or first ratio — n+m−1 per pixel — and samples pixels rather than using all of them, openly accepting that some ground-truth shapes will be missed. Because anchors must be capped this way, predictions cannot come from fully connected layers over pixels; they are made convolutionally on feature maps at several scales. A 3×3 convolution with padding 1 shares parameters across positions, units at one spatial position share a receptive field, and ten 4×4 maps give sixteen anchor sets with three anchors per shared center. Smaller top maps carry larger receptive fields and so suit larger objects. SSD operationalizes exactly this: a base network plus multiscale blocks that, on a 256×256 input, yield maps of 32, 16, 8, 4 and 1 — 5444 anchors with scales from 0.2 to 0.88 — whose outputs differ in three dimensions and are flattened so they can be concatenated. Minibatch labels are padded to (batch, m, 5) with −1 marking illegal boxes, and loss refinements (smooth L1, focal loss) close the section.
Second development: the same efficiency logic applied to the R-CNN family. The chapter then retells detection history as a sequence of removed redundancies. R-CNN runs the CNN once per region proposal, so thousands of proposals mean thousands of forward passes over heavily overlapping pixels; fast R-CNN runs the CNN once on the whole image and lets RoI pooling crop each proposal's features to a fixed shape by subwindow maxima, computing the overlapping work only once. Once redundant computation is gone, the next gain comes from learning the proposals themselves: faster R-CNN folds the region proposal network's own binary class and box predictions into the objective, so proposals are trained end to end and accuracy holds with far fewer of them. Mask R-CNN takes the last step by exploiting pixel-level labels — RoI pooling gives way to RoI alignment with bilinear interpolation to preserve spatial information, plus a fully convolutional head predicting pixel-level positions. That final move is also the hinge into the next task.
Third development: down to the pixel. Semantic segmentation and the Pascal VOC2012 dataset shift labeling to the pixel level, where labels are themselves images whose identically colored pixels share a class. This is where the chapter pauses to correct a tempting shortcut: segmentation data cannot be resized the way classification images are, because rescaling predicted pixel classes back to the original size is inaccurate — so features and labels are cropped together to a fixed 320×480 region instead. The mechanism that makes pixel-resolution output possible is transposed convolution, introduced first intuitively (broadcasting the input through the kernel) and then algebraically: write a convolution as y = Wx with a sparse 4×9 matrix, and the upsampling operation is simply multiplication by Wᵀ of shape 9×4. Hence the layer merely swaps a convolution's forward and backward passes, and the second correction follows: it is not an inverse. With matching hyperparameters a 10→20 convolution followed by a 20→10 transposed convolution returns a tensor shaped (1, 10, 16, 16) — but agreement of shape says nothing about agreement of values. FCNs then stack CNN features, a 1×1 layer, and transposed convolution to emit one class prediction per input pixel.
Closing: what else can be trained, and what happens on real data. Style transfer provides the chapter's conceptual inversion: here the trainable thing is the synthesized image itself. It is stored as a model parameter whose forward pass simply returns it, making it the only variable updated, while a frozen pretrained VGG supplies features — content from the last convolutional layer of the fourth block, style from the first convolutional layer of each block, with style encoded as Gram matrices. Content, style and total variation losses weighted 1, 1e4 and 10 over 500 epochs produce an image that keeps the content photo's scenery while taking the style image's color blocks; the author is candid that this is one qualitative run judged by eye and that the weights are experiment-specific knobs trading retention against stylization and smoothness. The chapter then lands on two Kaggle benchmarks, where the work visibly shifts from model design to data plumbing and feature reuse. CIFAR-10 means reorganizing raw image files into per-class folders with a held-out validation split (50000 training and 300000 test images, 290000 unevaluated to deter cheating), augmenting, training ResNet-18, retraining on training plus validation to use all labels, and submitting. The 120-breed dog task scales the same recipe to larger ImageNet-style images — random resized crop to 224 with scale 0.08–1.0 plus color jitter — and feeds a frozen pretrained ResNet-34's 1000-dimensional output into a small 1000-256-120 head. Only the head is iterated, which saves compute and memory but, as the author notes, leaves the extractor unable to adapt to the new task. The chapter thus ends where it began — on reused pretrained representations — but now with the cost and the limitation both made explicit.
Key claims, with the lines that support them
Deep learning is the force behind recent computer vision progress, and this chapter is organized around reusing the layerwise image representations CNNs learn.
The author names medical diagnosis, self-driving vehicles, camera monitoring and smart filters as everyday systems resting on vision, then sets the chapter's route: image augmentation and fine-tuning to help generalization, then object detection, semantic segmentation and style transfer, closing by applying this chapter's and earlier chapters' material to two popular benchmark datasets.
“In recent years, deep learning has been the transformative power for advancing the performance of computer vision systems.”
Chapter 14. Computer VisionRead in context →
Detection turns every anchor box into a training example, whose class and offset labels come from a greedy largest-IoU assignment with a threshold fallback.
In the worked IoU matrix the largest entry assigns ground truth B3 to anchor A2, its row and column are struck out, and the procedure repeats to give B1→A7, B4→A5, B2→A9; only then are leftover anchors matched, and only if their IoU clears a predefined 0.5. Running this on five anchors against a dog and a cat makes A4 cat, A1 dog, A2 cat by threshold, while A0 and A3 fall below 0.5 and become background — the negative anchor boxes.
“In order to train an object detection model, we need class and offset labels for each anchor box, where the former is the class of the object relevant to the anchor box and the latter is the offset of the ground-truth bounding box relative to the anchor box.”
§14.4 Anchor BoxesRead in context →
Because anchors must be capped, predictions are made convolutionally on feature maps of several scales rather than by fully connected layers on pixels.
Classifying h·w·a anchors per scale with fully connected layers is called infeasible, so a 3×3 convolution with padding 1 shares parameters across all positions; units at one spatial position share a receptive field, so ten 4×4 maps give 16 anchor sets with 3 anchors per shared center. Smaller top maps have larger receptive fields and so suit larger objects: SSD's five blocks on a 256×256 input give maps of 32, 16, 8, 4 and 1, i.e. 5444 anchors with scales from 0.2 to 0.88, and outputs that differ in three dimensions are flattened so they can be concatenated.
“we use the information of the input image in a certain receptive field to predict the classes and offsets of the anchor boxes that are close to that receptive field on the input image.”
§14.5 Multiscale Object DetectionRead in context →
3 more claims
Having removed redundant computation, the next gain comes from learning the proposals themselves and then aligning features to pixels.
Faster R-CNN's objective function includes the region proposal network's own binary class and box predictions, so proposals are trained end to end and the network learns to generate high-quality ones — accuracy holds with far fewer proposals. Mask R-CNN then exploits pixel-level labels by replacing RoI pooling with an RoI alignment layer that uses bilinear interpolation to preserve spatial information, plus a fully convolutional head that predicts pixel-level positions.
“As a result of the end-to-end training, the region proposal network learns how to generate high-quality region proposals, so as to stay accurate in object detection with a reduced number of region proposals that are learned from data.”
§14.8 Region-based CNNs (R-CNNs)Read in context →
In style transfer the trainable thing is the synthesized image itself, with the pretrained network held fixed and three weighted losses deciding the result.
The author stores the synthesized image as a model parameter whose forward pass just returns it, so it is the only variable updated during training, while a frozen pretrained VGG supplies features — content from the last convolutional layer of the fourth block, style from the first convolutional layer of each block, with style encoded as Gram matrices. Content, style and total variation losses weighted 1, 1e4 and 10 over 500 epochs give an image that keeps the content photo's scenery and objects while taking the style image's color blocks; this is one qualitative run judged by eye, and those weights are experiment-specific knobs for trading retention against stylization and smoothness.
“This synthesized image is the only variable that needs to be updated during the style transfer process, i.e., the model parameters to be updated during training.”
§14.12 Neural Style TransferRead in context →
On real competition data the work shifts from model design to organizing files and reusing frozen pretrained features sized to the dataset.
Raw Kaggle images are reorganized into per-class folders with a held-out validation split — the CIFAR-10 competition set has 50000 training and 300000 test images, 290000 of them unevaluated to deter cheating, and the final model is retrained on training plus validation to use all labels. For 120 dog breeds the larger, varying-size ImageNet-style images get different augmentation (random resized crop to 224 with scale 0.08–1.0, plus color jitter), and a pretrained ResNet-34 feeds 1000-dimensional features into a small 1000-256-120 head; only the head's parameters are iterated, which saves compute and memory but leaves the extractor unable to adapt to the new task.
“After organizing the dataset, images of the same class will be placed under the same folder.”
§14.13 Image Classification (CIFAR-10) on KaggleRead in context →
How it works
The 3 mechanisms the chapter’s argument runs on.
Mechanism 1
Why anchor boxes get capped per pixel
Covering every scale–ratio pair would create w·h·n·m boxes, and even five per pixel on a 561×728 image already yields over two million boxes to label and predict. So the author keeps only pairs sharing the first scale or first ratio, n+m−1 per pixel, and samples pixels instead — accepting that some ground-truth shapes are missed.
Mechanism 2
One CNN pass shared by all proposals
R-CNN runs the CNN once per region proposal, so thousands of proposals per image mean thousands of forward passes over heavily overlapping pixels. Fast R-CNN runs the CNN once on the whole image and lets RoI pooling crop each proposal's features to a fixed shape by subwindow maxima, so overlapping work is computed only once.
Mechanism 3
Transposed convolution is a matrix transpose
Write a convolution as y = Wx with a sparse 4×9 matrix W; the upsampling operation is just multiplication by Wᵀ of shape 9×4, which is why the layer merely swaps a convolution's forward and backward passes. Matching hyperparameters then return the input's shape — shape only, not values — letting a network emit one prediction per input pixel.
Common misreadings
Transposed convolution is the inverse of convolution, so running it after a convolution gives back the original input.
It only exchanges the forward and backward propagation of a convolution — equivalently, multiplies by the transposed weight matrix. With matching hyperparameters it restores the input's shape, as when a 10→20 convolution followed by a 20→10 transposed convolution returns a tensor shaped like the original (1, 10, 16, 16), but agreement of shape says nothing about agreement of values.
“Therefore, the transposed convolutional layer can just exchange the forward propagation function and the backpropagation function of the convolutional layer: its forward propagation and backpropagation functions multiply their input vector with \(\mathbf{W}^\top\) and \(\mathbf{W}\), respectively.”
§14.10 Transposed ConvolutionRead in context →
Segmentation data can be resized to a fixed shape the way classification images are, since any output can be scaled back afterwards.
Labels here are images in which identically colored pixels share a semantic class, and rescaling predicted pixel classes back to the original size is inaccurate; the author therefore crops features and labels together to a fixed 320×480 region instead of rescaling.
“To avoid this issue, we crop the image to a fixed shape instead of rescaling.”
§14.9 Semantic Segmentation and the DatasetRead in context →
Key concepts in Chapter 14
- Generalization
- How well a trained model performs on data it has not seen, rather than just on its training images.
- Where it applies: Here it is pursued through data-side and initialization-side tricks, not through new architectures.
- Layerwise representations
- Deep networks encode an image at several levels of abstraction at once, and those levels can be reused by many vision tasks.
- Where it applies: Stated as the organizing idea of this chapter's later sections, not yet demonstrated in this segment.
- Object detection
- A vision task that finds both what objects are in an image and where they are.
- Where it applies: Unlike classification, it assumes multiple objects of interest may be present.
- Bounding box
- A rectangle marking an object's location, given either by two opposite corners or by center plus width and height.
- Where it applies: Rectangular only; it cannot describe exact object outlines.
- Anchor box
- One of many candidate boxes generated at each pixel with varied scales and aspect ratios, later adjusted toward true boxes.
- Where it applies: Using all scale-ratio combinations is too costly, so only combinations containing the first scale or first ratio are kept.
- Intersection over union (IoU)
- The Jaccard index of two boxes' pixel sets: intersection area divided by union area.
- Where it applies: Ranges from 0 (no overlap) to 1 (identical boxes).
21 more concepts
- Non-maximum suppression
- Sort predicted boxes by confidence, keep the top one, and drop any box overlapping it above an IoU threshold; repeat.
- Where it applies: A greedy removal rule, so useful boxes may be deleted; soft variants exist.
- Anchor box labeling
- Each anchor gets a class from its best-IoU ground-truth box, or background if that IoU is under the threshold.
- Where it applies: Depends on a chosen IoU threshold such as 0.5; background offsets are masked out.
- Multiscale anchor boxes
- Use feature maps of different resolutions to place few large anchors or many small anchors instead of anchoring every pixel.
- Where it applies: Assumes units at one feature-map position share a receptive field on the input.
- Offset mask
- A zero/one mask that zeroes offset labels of background anchors so they do not affect the loss.
- Where it applies: Only filters offsets, not class labels.
- Single shot multibox detection (SSD)
- A detection model that stacks a base network and several shrinking feature map blocks, predicting anchor box classes and offsets at every scale.
- Where it applies: One model among many detectors, though its design principles carry over.
- Padded illegal bounding box
- A dummy label row added so every image has m boxes; its class is -1 so it can be ignored.
- Where it applies: Only needed because minibatch concatenation requires equal box counts.
- Class prediction layer
- A 3x3 convolution that outputs a(q+1) channels, so each spatial position carries class scores for all anchors centered there.
- Where it applies: Replaces fully connected layers to avoid heavy parametrization.
- Downsampling block
- Two padded 3x3 convolutions plus 2x2 max-pooling with stride 2, halving height and width and enlarging the receptive field.
- Where it applies: Borrows the VGG block design.
- Focal loss
- A reweighted cross-entropy that shrinks the loss of already well-classified examples so training focuses on hard ones.
- Where it applies: Needs hyperparameters gamma and alpha; useful mainly when easy negatives dominate.
- Region of interest (RoI) pooling layer
- A pooling layer whose output shape you specify directly, so differently shaped regions yield same-shape features.
- Where it applies: Rounds subwindow sizes, so it loses fine spatial precision compared with RoI alignment.
- Region proposal network
- A small network that predicts object/background and boxes on anchor boxes to produce proposals, trained jointly with the detector.
- Where it applies: Replaces selective search only; the rest of the fast R-CNN pipeline is unchanged.
- Semantic segmentation
- Dividing an image into regions by semantic class, labeling and predicting at the pixel level.
- Where it applies: Does not separate individual instances; that is instance segmentation.
- Transposed convolution
- A CNN layer that enlarges height and width by spreading each input element through the kernel and summing overlapping results.
- Where it applies: Padding is applied to the output and strides refer to intermediate results, not the input; same shape as input does not mean same values.
- Fully convolutional network
- A network that extracts CNN features, maps channels to classes with a 1x1 convolution, then upsamples back to input height and width.
- Where it applies: With stride 32 upsampling, inputs whose height or width is indivisible by 32 need cropping into multiples of 32.
- Bilinear interpolation upsampling
- Scaling an image by mapping each output pixel back to real-valued input coordinates and blending the four nearest pixels by distance.
- Where it applies: Used here mainly as an initialization for the transposed convolutional kernel, while the 1x1 layer uses Xavier initialization.
- Style transfer
- Optimizing an image so it keeps one image's content while taking another's style.
- Where it applies: Needs a pretrained feature extractor and per-image optimization, not a single feed-forward pass.
- Gram matrix style representation
- Channel-by-channel correlations of a layer's features, used as the style signature.
- Where it applies: Divided by chw so the value does not grow with feature map size.
- Total variation loss
- A penalty on differences between neighboring pixels that smooths high-frequency noise.
- Where it applies: Reduces noise but too much weight oversmooths detail.
- Content layer and style layers
- Chosen VGG layers whose outputs define content and style features.
- Where it applies: Layers near the input catch details, layers near the output catch global information.
- Frozen pretrained feature extractor
- Keep a pretrained network's weights fixed and use its outputs as fixed image features.
- Where it applies: Works when the new task's data is close to the pretraining distribution, e.g. an ImageNet subset.
- Image augmentation
- Random transforms applied only during training to enlarge effective data variety.
- Where it applies: Augmentation randomness must be dropped at validation and prediction time.
Reader’s notes on Chapter 14AI reading companion
“It is probably true that image augmentation was indispensable for the success of AlexNet at that time.”
Read in context →"Probably true" is an odd hedge in a textbook. Honest, but it reveals how much of deep learning folklore rests on untested attribution rather than ablation.
“random tweaks of training examples allow models to rely less on certain attributes”
Read in context →This is the real argument, and it's stronger than "more data." Augmentation is an encoded prior about which invariances we want — a claim about the world, smuggled in as a data trick.
“Flipping up and down is not as common as flipping left and right.”
Read in context →The book never says why, and the reason matters: gravity. Our visual world is vertically asymmetric, so a vertical flip can produce an image that never occurs. The silence here hides a genuinely interesting principle.
16 more notes
“Can this comparative experiment support the argument that image augmentation can mitigate overfitting? Why?”
Read in context →The sharpest line in the section, and it's in the exercises. It quietly invites the reader to doubt what the prose just asserted — a single run on CIFAR-10 proves very little.
“researchers have spent millions of dollars from research funding”
Read in context →A rare moment where the economics surfaces. Transfer learning is pitched as a technical method, but it's really a way of amortizing someone else's capital — the pretrained weights are a subsidy.
“We assume that these model parameters contain the knowledge learned from the source dataset and this knowledge will also be applicable to the target dataset.”
Read in context →Two assumptions stacked, both unverifiable in advance. Fine-tuning works, and nobody can tell you beforehand whether your source and target are close enough. The method is empirical all the way down.
“a learning rate of \(10\eta\) will be used to iterate the model parameters in the output layer”
Read in context →Where did 10 come from? Nowhere — it's a working heuristic dressed in notation. Worth noticing how often deep learning practice runs on numbers like this.
“In fact, there is a “hotdog” class in the ImageNet dataset.”
Read in context →A delightful punchline: the whole demo fine-tunes a model that already knew the answer. The exercise turns the tutorial's own setup into the joke, and then asks you to exploit it.
“we assume that there is only one major object in the image and we only focus on how to recognize its category”
Read in context →Here the book finally admits the fiction every earlier chapter rested on. Classification was never a description of seeing; it was a convenient amputation of it.
“Although these anchor boxes may cover all the ground-truth bounding boxes, the computational complexity is easily too high.”
Read in context →The honest admission behind every anchor scheme: exhaustiveness is affordable only if you cripple it. The n+m-1 trick is pure budget arithmetic dressed as design.
“in_height / in_width # Handle rectangular inputs”
Read in context →A whole geometric headache buried in a trailing comment. Normalized coordinates make the aspect ratio r mean something different from what the formula above promised — the text never says so.
“we need class and offset labels for each anchor box”
Read in context →This is the real conceptual pivot: detection stops being "find the box" and becomes classification plus regression over a fixed grid of guesses. Everything after follows mechanically.
“assign \(B_j\) to \(A_i\) only if this IoU is greater than a predefined threshold”
Read in context →Two assignment regimes glued together — a greedy global matching for n_b boxes, then a thresholded free-for-all. The seams show in the example where A0 and A3 fall out as background.
“we can apply transformations to those relative positions and sizes that may lead to more uniformly distributed offsets that are easier to fit”
Read in context →The most candid sentence in the section. Those 10s and 5s in the code aren't physics, they're whitening constants chosen so gradients behave. Deep learning's craft layer, briefly visible.
“Since we do not care about background detection, offsets of this negative class should not affect the objective function”
Read in context →The mask is how you teach a loss function to shut up. Negatives still vote on class, just not on geometry — an asymmetry worth noticing.
“those with non-maximum confidence scores are suppressed”
Read in context →NMS is a confession that the model never learned to output one box per object. We bolt on a hand-written greedy filter at inference and call the pipeline end-to-end.
“combined = torch.cat((keep, all_idx))”
Read in context →A set-difference done by counting duplicates — clever, but it only works because all_idx is guaranteed unique. Fragile idiom passed off as idiom.
“conf[below_min_idx] = 1 - conf[below_min_idx]”
Read in context →Quietly reinterprets the confidence column: for background entries it now means confidence in background. Easy to misread the output tensor.
“1 \times 1\), \(1 \times 2\), and \(2 \times 2\) objects can appear on a \(2 \times 2\) image in 4, 2, and 1 possible ways”
Read in context →A combinatorial argument standing in for a statistical claim. Counting placements isn't the same as small objects being more frequent in real photos — the intuition is cute, not derived.
A reader’s takeAI reading companion
A textbook chapter that confesses classification was an amputation of vision
This chapter reads like a slow confession. It opens with two generalization tricks and ends with two Kaggle leaderboards, and in between it dismantles the premise every earlier chapter stood on. The giveaway is a single sentence in the object-detection opener: until now 'we assume that there is only one major object in the image.' That assumption was never a fact about images; it was an amputation of seeing, convenient enough that we called it classification. Once the chapter admits it, everything that follows is a series of attempts to put the missing structure back — boxes, then pixels, then, in style transfer, the image itself as the thing being optimized.
What unfolds is remarkably honest about its own machinery, and the honesty is mostly in the margins. Augmentation is pitched as 'more data' but the real argument is buried a line later: random tweaks make the model rely less on particular attributes. That is not a data trick, it is a prior about which invariances the world has — which is why left-right flips are standard and up-down flips are not. The book never says the word gravity, and the silence costs the reader a genuinely interesting principle. Fine-tuning is framed as technique, but the text slips and mentions millions of dollars of research funding; pretrained weights are a subsidy, and transfer learning is the accounting method for spending someone else's capital. Two stacked and unverifiable assumptions hold it up — that the parameters contain knowledge, and that the knowledge transfers — and no one can tell you in advance whether your source and target are close enough. The 10× learning rate on the output layer comes from nowhere. The hotdog demo fine-tunes a network that already had a hotdog class in ImageNet, and the exercise, to its credit, turns that into the joke and then asks you to exploit it.
Continue reading
The detection sections are where the craft layer shows through most clearly. Anchor boxes begin as exhaustive coverage and immediately get crippled into affordability: the n+m−1 trick is budget arithmetic wearing the costume of design. The pivot that matters is quiet — 'we need class and offset labels for each anchor box' — and after it, detection is no longer 'find the object' but classification plus regression over a fixed grid of guesses, which is why everything downstream follows mechanically. Assignment glues two incompatible regimes together, a greedy global matching and then a thresholded free-for-all, and the seams are visible in the worked example where two anchors simply fall out as background. The offset transform is the most candid sentence in the chapter: those magic 10s and 5s exist so gradients behave, not because geometry demands them. The mask on background offsets teaches the loss to stay silent about geometry while still voting on class. And NMS is the frankest admission of all — a hand-written greedy filter bolted on at inference, in a pipeline we keep calling end-to-end, because the model never learned to emit one box per object. Zeroing the offsets in the demo isolates NMS cleanly, which is pedagogically right and practically misleading: real offsets can make IoU suppression delete the correct box. Watch the implementation details too — the set difference by duplicate-counting works only because the index array is unique, and the confidence column silently flips meaning for background rows.
From SSD the chapter climbs the R-CNN family, and read as one arc it is a single idea repeated: stop recomputing what you can share. Per-proposal features become shared features, hand-made proposals become learned ones, coarse pooling becomes pixel-aligned. Then semantic segmentation moves labeling down to the pixel, transposed convolution supplies the arithmetic for going back up — and the matrix-transpose framing is the one place the chapter gives you a real reason rather than a recipe — and the FCN is almost anticlimactic, just features plus 1×1 plus upsampling. Style transfer then inverts the whole setup: the network is frozen, the image is the parameter, and three weighted losses negotiate content, Gram-matrix style, and smoothness. It is the clearest demonstration in the book that a loss function is a statement of preference, not a measurement.
My sharpest judgement: the chapter's most rigorous moment is a question in the exercises — can this comparative experiment support the claim that augmentation mitigates overfitting? One run on CIFAR-10 cannot, and the exercise invites you to doubt the prose on the page above it. That tension runs throughout. The prose asserts; the exercises and trailing comments undercut. Even the cute combinatorial argument that small objects have more possible placements on a grid is counting, not statistics about real photographs.
So what I would tell a reader: do not read this chapter for the architectures, which date fast. Read it for where the numbers come from. Every time you meet a constant with no derivation — 10η, the 10s and 5s, an IoU threshold, a focal-loss γ, a style weight — mark it. Those marks are the actual map of computer vision as a discipline: a thin layer of principle over a thick layer of calibrated craft, held in place by benchmarks. The two Kaggle sections at the end are not filler; they are the chapter's real thesis in operational form. Organizing image folders, choosing augmentations, freezing a ResNet-34 and training only a small head — that is what the work is. The theory told you upsampling is a transpose. The competition tells you that someone else's pretrained features, plus careful plumbing, is what wins. Both are true, and the gap between them is where you will actually live.
Read Chapter 14 with these cards beside each passage.
Open in FeedLitraChapter 15: Natural Language Processing: Pretraining
How does BERT actually make one token's vector change with context?
How Chapter 15 unfoldsAI-assisted
Opening. The chapter begins by naming its own premise: that useful text representations can be learned from large raw corpora without annotation, because the text supplies its own supervision. That framing immediately splits the territory the chapter will cover — word2vec and GloVe produce one fixed vector per token regardless of where it appears, while BERT produces vectors that bend to context — and the rest of the chapter is essentially the journey from the first kind to the second. Section 15.1 then starts from the bottom by asking what a word embedding is for, and answers negatively first: one-hot encoding is structurally useless for similarity, since the cosine similarity between the one-hot vectors of any two distinct words is exactly zero. Similarity cannot be read off such a code; it has to be learned into real-valued vectors. From that gap the author introduces skip-gram (predict surrounding words from a center word) and CBOW (the reverse), derives their losses and gradients, and classifies both as self-supervised: the conditional probabilities they fit are simply read off a raw corpus, so no human labeling is involved.
First development: making the training affordable. The gradients just derived expose a cost problem, and Section 15.2 is the response. Because both models normalize their predictions over the whole dictionary, every gradient carries a sum across all words, so cost scales with vocabulary size. Negative sampling replaces that single normalized prediction with a handful of independent yes/no judgments — one on the true context word, K on sampled noise words — so cost tracks K rather than the dictionary; hierarchical softmax is offered as the alternative approximation. The chapter then becomes concrete and builds the PTB pipeline: subsampling high-frequency words, extracting center/context pairs, drawing negatives, and padding minibatches with masks and labels so that variable-length context sets can be batched. Subsampling deserves a note, because it is easy to mistake for stop-word removal. The discarding is probabilistic and frequency-dependent: only words above a relative-frequency threshold are even eligible, and eligible words still survive some of the time. On PTB with the threshold at 1e-4, "the" is retained at under a twentieth of its original rate rather than deleted, while a rare word like "join" is kept in full. The rationale is informational as much as computational — words that appear in nearly every window say little about meaning while consuming most of the compute. With the pipeline in place, skip-gram is pretrained using masked binary cross-entropy.
The turn to global statistics. The chapter's first real pivot is interpretive rather than architectural: it rereads the skip-gram loss as a cross-entropy against corpus-wide co-occurrence distributions. That reframing is useful precisely because it exposes two flaws. Normalizing the predicted distributions still demands a sum over the vocabulary, and cross-entropy assigns disproportionate weight to the enormous tail of rare co-occurrence events a large corpus produces. GloVe is then presented as the answer to both: fit the logarithms of co-occurrence counts with a weighted squared loss, adding per-word bias terms and a weighting function that damps the rare events cross-entropy over-rewarded. The author is careful to show this form is not arbitrary. Derived the other way, from ratios of co-occurrence probabilities, the table of p(w|ice)/p(w|steam) — roughly 8.9 for "solid" and 0.085 for "gas" — shows the ratio tracking which of the two words a term belongs with, and demanding that swapping the indices invert the ratio forces the exponential form and the bias-plus-log-count equation. Because one word appearing in another's window implies the converse, counts are symmetric (x_ij = x_ji), so a word's center and context vectors are mathematically interchangeable and are simply summed. The limitation is flagged rather than hidden: "water" (1.36) and "fashion" (0.96) both sit near 1 despite standing in opposite relationships to the pair. The section closes the word-level thread by attacking rare and unseen words from a different direction — fastText's subword n-grams, and BPE's learned variable-length subwords for a fixed-size vocabulary.
The second turn: context. Everything so far shares a defect no amount of better fitting can repair. If a token gets one fixed vector, polysemy is unrepresentable: "crane" in "a crane is flying" and "a crane driver came" means two different things yet receives the same vector, as does "bank" in a money sentence and a sitting-down sentence. This motivates representations that depend on the surrounding sequence, and the chapter walks the lineage in order. ELMo supplies frozen bidirectional features that are bolted onto existing task-specific models — and here the author makes a sharper argument than "features got better." He grants that ELMo advanced the state of the art on six NLP tasks, then turns the concession around: each of those systems still needed an architecture hand-crafted for its own task, which does not scale across problems. The bottleneck was the architectures, not the features, so the field moved toward task-agnostic pretraining. GPT is that step, but it is left-to-right, and direction turns out to matter substantively, not cosmetically: an autoregressive model conditions only on what precedes, so meaning carried by the right-hand context is invisible. "Bank" in "i went to the bank to deposit cash" versus "i went to the bank to sit down" gets an identical representation from GPT. Any claim that merely reading a sentence makes a model context-sensitive fails here. BERT is positioned as the fusion of ELMo's bidirectionality with GPT's task-agnosticism, which is exactly why it predicts masked tokens from both sides.
Implementation and close. The chapter's final movement is constructive: BERT's input embeddings and its two pretraining tasks — masked language modeling and next sentence prediction — are implemented in code. The masking recipe gets its own justification, since the 80/10/10 split looks like a quirk until the mismatch it fixes is named. The artificial mask symbol exists only during pretraining and never appears at fine-tuning time, so training exclusively on it would train the model on inputs it will never see again; replacing a slice of the chosen positions with a random word or with the original token keeps inputs realistic, and the random substitutions act as noise that stops the model from relying entirely on the masked slot. The chapter then assembles the MLM data extraction, padding, and a WikiText-2 Dataset class, pretrains a small BERT on that corpus, and ends by closing the loop it opened: the token "crane" is shown to receive demonstrably different representations in different contexts. The example that diagnosed the limitation of static vectors becomes the demonstration that the limitation has been overcome — which is how the chapter earns its own arc rather than merely listing four models.
Key claims, with the lines that support them
One-hot vectors are a dead end for representing words, which is why the chapter starts from learned embeddings instead.
The author points out that the cosine similarity between the one-hot vectors of any two different words is exactly zero, so the encoding is structurally incapable of saying that two words are alike — similarity has to be learned into real-valued vectors instead.
“A main reason is that one-hot word vectors cannot accurately express the similarity between different words, such as the cosine similarity that we often use.”
§15.1 Word Embedding (word2vec)Read in context →
Word embeddings can be learned without any human labeling, because the text itself provides the supervision.
Skip-gram and CBOW are trained on conditional probabilities of predicting a word from the words around it; since those targets are simply read off a raw corpus, the author classifies both as self-supervised rather than as supervised learning that happens to lack labels.
“Since supervision comes from the data without labels, both skip-gram and continuous bag of words are self-supervised models.”
§15.1 Word Embedding (word2vec)Read in context →
Reading the skip-gram objective as a fit to corpus-wide co-occurrence statistics exposes two flaws, and that reframing is what leads into GloVe.
The author shows the skip-gram loss amounts to a cross-entropy against global co-occurrence distributions, but normalizing those predicted distributions again requires a sum over the whole vocabulary, and cross-entropy hands too much weight to the many rare events a large corpus produces; GloVe's answer is to fit logarithms of counts with a weighted squared loss instead.
“Though being commonly used for measuring the distance between probability distributions, the cross-entropy loss function may not be a good choice here.”
§15.5 Word Embedding with Global Vectors (GloVe)Read in context →
3 more claims
GloVe's form is not an arbitrary choice: it can be derived from ratios of co-occurrence probabilities, which is also why its two vectors per word are interchangeable.
The author tabulates ratios of p(w|ice) to p(w|steam) — about 8.9 for "solid" and 0.085 for "gas" — showing the ratio tracks which word a term belongs with; requiring that swapping the indices invert the ratio forces an exponential form and the bias-plus-log-count equation. Because a word in another's window implies the converse, counts satisfy x_ij = x_ji, so the center and context vectors are mathematically equivalent and are simply added. The author also flags the limit: "water" (1.36) and "fashion" (0.96) both land near 1 despite opposite relationships.
“Switching word indices \(j\) and \(k\) in (15.5.5), it must hold that \(f(x)f(-x)=1\), so one possibility is \(f(x)=\exp(x)\), i.e.,”
§15.5 Word Embedding with Global Vectors (GloVe)Read in context →
Giving every token one fixed vector cannot work for words with several senses, which motivates representations that depend on the surrounding sequence.
The author's example is "crane": in "a crane is flying" and "a crane driver came" the word means different things, yet word2vec and GloVe assign it the same vector; the same point is made with "bank" in a money sentence versus a sitting-down sentence. At the end of the chapter a small BERT is pretrained and the token "crane" demonstrably receives different representations in different contexts.
“This motivates the development of context-sensitive word representations, where representations of words depend on their contexts.”
§15.8 Bidirectional Encoder Representations from Transformers (BERT)Read in context →
Better features alone were not enough — hand-built, task-specific architectures were the real bottleneck, so the field moved to task-agnostic pretraining.
The author grants that bolting ELMo's frozen bidirectional features onto existing models pushed the state of the art on six different NLP tasks, then turns the point around: each of those solutions still needed an architecture crafted for its own task, which is impractical to repeat for every problem.
“However, it is practically non-trivial to craft a specific architecture for every natural language processing task.”
§15.8 Bidirectional Encoder Representations from Transformers (BERT)Read in context →
How it works
The 3 mechanisms the chapter’s argument runs on.
Mechanism 1
Why full softmax is unaffordable
Skip-gram and CBOW normalize over the entire dictionary, so every gradient contains a sum across all words and cost grows with vocabulary size. Negative sampling sidesteps this by turning one prediction into a handful of yes/no judgments on the true context word plus K sampled noise words, so cost tracks K instead of dictionary size.
Mechanism 2
Dropping frequent words helps
Very common words sit in almost every context window, so their co-occurrences say little about meaning while still consuming most of the computation. The author therefore discards them at random with a probability tied to their relative frequency, so informative pairs dominate training and each pass gets cheaper.
Mechanism 3
Why masking mixes in real tokens
The artificial mask symbol exists only during pretraining and never shows up when the model is fine-tuned, so training purely on it creates a mismatch. Replacing a slice of the chosen positions with a random word or the original word keeps the inputs realistic and, because the random insertions act as noise, stops the model from leaning entirely on the masked position.
Common misreadings
Subsampling means throwing out the stop words — once you strip "the" and "a", the corpus is clean.
The discarding is probabilistic and frequency-dependent: only words whose relative frequency passes the threshold are eligible to be dropped at all, and even then they survive some of the time. On the PTB corpus with the threshold at 1e-4, "the" is still kept at under a twentieth of its original rate rather than deleted outright, while a rare word like "join" is retained in full.
“We can see that only when the relative frequency \(f(w_i) > t\) can the (high-frequency) word \(w_i\) be discarded, and the higher the relative frequency of the word, the greater the probability of being discarded.”
§15.3 The Dataset for Pretraining Word EmbeddingsRead in context →
Any model that reads a sentence is context-sensitive, so a left-to-right language model like GPT already handles multiple word senses.
Direction matters: an autoregressive model only conditions on what came before, so meaning carried by the right-hand context is invisible to it. The author's example is "bank" in "i went to the bank to deposit cash" versus "i went to the bank to sit down" — GPT gives the identical representation even though the senses differ, which is exactly why BERT predicts masked tokens using both sides.
“However, due to the autoregressive nature of language models, GPT only looks forward (left-to-right).”
§15.8 Bidirectional Encoder Representations from Transformers (BERT)Read in context →
Key concepts in Chapter 15
- Word embedding
- Mapping each word to a real-valued vector that acts as its feature representation.
- Where it applies: Classic embeddings give one fixed vector per token regardless of context.
- Self-supervised pretraining of text representations
- Learning from raw text by predicting a hidden part of it from surrounding text, so no manual labels are needed.
- Where it applies: Needs large corpora; supervision signal comes only from text co-occurrence.
- One-hot encoding
- A length-N vector of zeros with a single 1 at the word's index.
- Where it applies: Cosine similarity between any two different one-hot vectors is 0, so similarity is unencodable.
- Skip-gram model
- Uses a center word to predict its surrounding context words, giving each word a center vector and a context vector.
- Where it applies: Softmax normalization over the whole vocabulary makes exact gradients costly.
- Continuous bag of words (CBOW)
- Predicts the center word from averaged context word vectors.
- Where it applies: Typically uses context word vectors as the final representations, unlike skip-gram.
- Negative sampling
- Replaces full softmax with binary events over one true context word and K sampled noise words. Approximate training that pairs each center-context pair with a few sampled noise words instead of normalizing over the whole vocabulary.
- Where it applies: Cost scales with K, not dictionary size; needs a predefined noise distribution. Sampled noise words must not be actual context words of that center word.
16 more concepts
- Hierarchical softmax
- Computes word probability as a product of binary decisions along a binary-tree path to the word's leaf.
- Where it applies: Cost is logarithmic in vocabulary size; depends on the chosen tree structure.
- Subsampling of high-frequency words
- Randomly dropping very common words so training focuses on informative co-occurrences and runs faster.
- Where it applies: Only words whose relative frequency exceeds the threshold t can be discarded at all.
- Masking for padded minibatches
- A 0/1 variable marking which concatenated context/noise slots are real so padding is excluded from the loss.
- Where it applies: Masks mark padding; a separate labels variable marks positive versus negative examples.
- Global co-occurrence count
- How often word wj appears in a context window centered on wi across the whole corpus.
- Where it applies: It is a corpus-level statistic, precomputable rather than re-sampled per minibatch.
- GloVe weighted squared loss
- A loss that fits inner product plus two biases to log co-occurrence count, weighted by h(x).
- Where it applies: Only non-zero co-occurrence counts contribute, since h(0)=0.
- Ratio of co-occurrence probabilities
- Dividing p(w_k|ice) by p(w_k|steam) reveals which word w_k is related to.
- Where it applies: Ratios near 1 cannot distinguish related-to-both from unrelated-to-both.
- Subword embedding
- Representing a word as the sum of its character n-gram vectors.
- Where it applies: Larger vocabulary and higher computational cost than skip-gram.
- Byte pair encoding
- Greedily merging the most frequent adjacent symbol pair to build variable-length subwords.
- Where it applies: Pairs crossing word boundaries are excluded; results depend on the dataset.
- Context-sensitive representation
- A word vector that depends on the surrounding sequence, not just the token.
- Where it applies: word2vec and GloVe are context-independent and cannot handle polysemy.
- BERT input sequence
- A single token stream wrapping one or two texts with <cls> and <sep> markers.
- Where it applies: Holds at most two text sequences; its embeddings sum token, segment and positional parts.
- Masked language model
- Pretraining by hiding 15% of tokens and predicting them from both sides.
- Where it applies: The artificial <mask> token never appears in fine-tuning, so replacement is randomized.
- Next sentence prediction
- A binary task asking whether the second sentence truly follows the first.
- Where it applies: Labels come free from the corpus; half the pairs are randomly sampled negatives.
- Task-agnostic pretraining
- One pretrained model fine-tuned for many tasks with only a new output layer.
- Where it applies: Contrasts with ELMo, whose pretrained weights are frozen and fed into custom architectures.
- Masked language modeling 80/10/10 replacement
- Among the 15% chosen positions, 80% become '<mask>', 10% stay unchanged, 10% become a random word.
- Where it applies: Applies only to non-special tokens; '<cls>' and '<sep>' are never predicted.
- MLM weights padding
- Padded prediction slots get weight 0.0 so they contribute nothing to the loss.
- Where it applies: Only filters padded prediction positions, not padded input tokens.
- Context-sensitive BERT representation
- The same token gets different encoded vectors depending on surrounding text.
- Where it applies: Demonstrated with a tiny 2-layer BERT, not the original model size.
Reader’s notes on Chapter 15AI reading companion
“the vector representation of “bank” is the same in both “go to the bank to deposit some money” and “go to the bank to sit down”
Read in context →The whole chapter's motivation compressed into one homonym. Note the quiet admission: word2vec is already framed as a thing to be superseded before we've even learned it.
“models learn through supervision from massive text data without expensive labeling efforts!”
Read in context →The exclamation mark is doing persuasive work. The labels aren't absent — they're just free, harvested from word order. Calling it "without labeling" hides that someone decided context counts as truth.
“Since the cosine similarity between one-hot vectors of any two different words is 0, one-hot vectors cannot encode similarities among words”
Read in context →Clean one-line demolition. But the real indictment isn't zero similarity — it's that every pair is equally zero, so the geometry carries no information at all.
17 more notes
“Assume that the context words are independently generated given the center word (i.e., conditional independence)”
Read in context →A frankly false assumption — "the" and "man" are hardly independent given "loves". Yet the model works. Worth sitting with: the factorization is a computational convenience that the embeddings survive.
“each word has two \(d\)-dimensional-vector representations”
Read in context →The under-explained design choice of the whole section. Why two? Because a word shouldn't predict itself with high probability — one vector would force u·v self-similarity to dominate. The text never says so.
“the center word vectors of the skip-gram model are typically used as the word representations”
Read in context →"Typically" is the tell. After all that derivation, half the learned parameters get thrown away by convention rather than by argument.
“the joint probability in (15.2.3) is maximized to 1 only if all the word vectors are equal to infinity”
Read in context →The sharpest moment in the segment: the honest exhibition of a degenerate objective before the fix. Negative sampling isn't an optimization trick here — it's what stops the problem from being vacuous.
“its co-occurrence with a low-frequency word “intel” is more useful in training than the co-occurrence with a high-frequency word “a”
Read in context →Subsampling is smuggled in as efficiency but it's really an information-theoretic correction — frequent words are low-surprise, hence low-signal. Deleting data makes the representations better, not just faster.
“window_size = random.randint(1, max_window_size)”
Read in context →The window size is re-rolled per center word — a quiet trick that weights nearby words more heavily without any explicit distance decay. Randomness doing the job of a kernel.
“while len(negatives) < len(contexts) * K:”
Read in context →Negatives scale with the context count, so K is per-pair, not per-center. Easy to misread as 5 noise words total.
“Noise words cannot be context words”
Read in context →A purity check that costs a list scan per draw — and is only local to this center word. Globally, your "noise" is somebody else's context. The approximation tolerates that cheerfully.
“raised to the power of 0.75”
Read in context →The famous magic exponent, introduced here with nothing but "according to the suggestions in the word2vec paper." An empirical fudge that flattens frequency, passed down as scripture.
“a large number of rare events from a large corpus are often modeled by the cross-entropy loss to be assigned with too much weight”
Read in context →This is the real motivation for GloVe, and it's stated almost in passing. Cross-entropy insists on explaining the tail; squared loss with h(x) lets you shrug at it.
“because \(h(0)=0\), the squared loss term for any \(x_{ij}=0\) can be omitted”
Read in context →Here's the sleight of hand: log x_ij is undefined at zero, and the weight function conveniently makes that term vanish. Elegance and evasion in the same line.
“owing to different initialization values, the same word may still get different values in these two vectors after training”
Read in context →Mathematically identical, practically divergent — so GloVe just adds them. A theorem about symmetry answered by an averaging hack.
“it must hold that \(f(x)f(-x)=1\), so one possibility is \(f(x)=\exp(x”
Read in context →"One possibility" is doing heavy lifting. The derivation is really a reverse-engineering: they knew exp was wanted, then found constraints that permit it.
“the internal structure of words was neither explored in word2vec nor in GloVe”
Read in context →A whole chapter of machinery, and this one sentence names its blind spot: both models treat "help" and "helping" as unrelated strangers.
“rare words and even out-of-vocabulary words may obtain better vector representations in fastText”
Read in context →The whole payoff in one clause — and it comes only after two costs are admitted. Honest trade accounting, rare in a textbook.
“the vocabulary size cannot be predefined”
Read in context →This is the real indictment of fastText's n-grams: not accuracy but uncontrollability. BPE is introduced as a budgeting tool, not a smarter linguist.
“pairs crossing word boundaries are not considered”
Read in context →Smuggled in as an efficiency note, but it's a linguistic commitment: words are sealed units. Modern tokenizers blur exactly this.
A reader’s takeAI reading companion
Not improving accuracy, just admissions about what models refuse to see
Read end to end, this chapter is an argument that keeps undercutting itself in productive ways — and that is its real pedagogy. It opens by promising that self-supervision gives you representations for free, then spends five segments showing how much is quietly paid: the 'no labeling' framing hides that word order has been declared ground truth; conditional independence between context words is asserted and immediately violated by any real sentence; the degenerate objective that would send all vectors to infinity is displayed honestly before negative sampling rescues it; log co-occurrence is undefined at zero until a weighting function politely makes that term disappear.
The chapter's arc is not word2vec → GloVe → fastText → BERT as a ladder of accuracy. It is a sequence of admissions about what each representation refuses to see, each fix narrower than the problem it answers. What I saw through most clearly: the text repeatedly presents engineering conveniences in the costume of theory. The 0.75 exponent arrives as scripture with a citation and no reason. Two vectors per word is a structural necessity — without it a word's self-similarity would dominate its own prediction — but the book never says so, and then throws half the parameters away on the word 'typically.
Continue reading
' GloVe proves center and context vectors are symmetric, then adds them because initialization makes them differ anyway; a theorem answered by an averaging hack. The exp derivation is reverse-engineered from the answer. Subsampling is sold as speed when it is really information theory: deleting frequent words improves the embeddings, because low-surprise tokens carry low signal. Even the random window size is a distance kernel in disguise. None of these are scandals — they are what a working method actually looks like — but a reader who takes the derivations as the load-bearing part will have learned the wrong lesson.
My sharpest judgement is about the chapter's hinge, which is quieter than it looks. The decisive limitation of word2vec and GloVe is never accuracy; it is that both treat 'help' and 'helping' as strangers, and treat every occurrence of 'bank' as the same word. fastText answers the first with subword n-grams and promptly loses control of vocabulary size — so BPE enters not as a smarter linguist but as a budget. BERT answers the second, and the chapter's closing demonstration, 'crane' receiving different vectors in different sentences, is the exact homonym complaint from the first page finally discharged.
The chapter is a loop, and it tells you its ending in its opening paragraph. What I'd tell the reader: the static-embedding half is not obsolete background to skim on the way to BERT. It is where you learn that every modern design choice — subword units, sampled objectives, bidirectionality, masking at 80/10/10 — exists because something earlier was vacuous, uncontrollable, or blind. Read BPE's refusal to cross word boundaries as the linguistic commitment it is, not the efficiency note it is dressed as. And notice that the book's most valuable sentences are the ones conceding a cost: rare-word gains bought with vocabulary bloat, cross-entropy's insistence on explaining a tail that squared loss can shrug off.
Those concessions, not the gradients, are what transfer.
Read Chapter 15 with these cards beside each passage.
Open in FeedLitraChapter 16: Natural Language Processing: Applications
How does truncation and padding to 500 tokens affect long reviews?
How Chapter 16 unfoldsAI-assisted
Opening. This chapter opens by cashing in on what came before. Having built pretrained text representations, the chapter states its premise: those representations are inputs, and what matters now is feeding them into architectures that do actual work. Two downstream tasks are named as the vehicles — sentiment analysis and natural language inference — with BERT fine-tuning held in reserve as a third movement. The framing is deliberately applied rather than theoretical: the question is no longer how to learn word meaning but what to build on top of it.
Development. Sentiment analysis comes first, and the chapter immediately reduces it to something already familiar. Because sentiments collapse into discrete polarities or scales, the task is just mapping a variable-length sequence to one fixed label — plain text classification. Stanford's IMDb corpus supplies exactly that shape, 25,000 reviews in each of the training and test splits with positive and negative labels balanced, though the chapter is candid that this is binary polarity in a single domain of movie reviews. Two architectures are then run over GloVe embeddings in turn, an RNN design and a textCNN design, and the section closes with textCNN's training. The implicit lesson of this stretch is that a pretrained embedding plus a modest task-specific body is enough.
The turn to sentence pairs. The chapter then shifts from single texts to relations between texts. Natural language inference asks what a hypothesis's truth owes to a premise, and the verdict space is exactly three: entailment, contradiction, or neutral. Each is pinned to a worked example — hugging someone entails showing affection, running code contradicts sleeping, and musicians performing for us leaves their fame undetermined, neutral being defined residually as whatever the first two labels fail to cover. SNLI and its loader are introduced, and then the decomposable attention model with its attend–compare–aggregate pipeline. Here the chapter makes its sharpest mechanistic claim: what inference needs is which words correspond to which, not the order in which they appear. Walking "i do need sleep" against "i am tired," linking sleep to tired is what settles the relation, so attention over all token pairs suffices and neither recurrence nor convolution is required. Two cautions ride along. The one-to-one links in the diagrams are a display convenience; the real mechanism is soft alignment, weighing every token against every token. And that is precisely why cost gets discussed: the MLP f is fed one token at a time rather than each pair, so it runs m + n times instead of m × n, decomposing a quadratic scoring problem into a linear one and making the attend step affordable at all.
The second turn, and the trade. The chapter's real pivot comes when it turns its own preceding pages around. Hand-designing a separate architecture per task — an RNN here, a textCNN there, a decomposable attention model for pairs — does not scale, and BERT is offered as the alternative that did scale: state of the art across many tasks at the time of its proposal, with only minimal architectural change. The reason is a single body with different read-outs. BERT returns a representation for the <cls> token and one for every input token; whole-sequence tasks read only <cls>, token-level tasks read each token, and swapping in a continuous output with squared loss converts classification into regression. So across whole task families, only the input format and which representations feed the added layers actually change. The chapter marches through the families with concrete cases — CoLA judging grammatical acceptability ("I should study." yes, "I should studying." no), semantic textual similarity scored 0 to 5 needing just a continuous output and mean squared error, and question answering scoring each passage token as a span start and end with separate parameters, as when "mask makers" is extracted as the answer about N95 masks.
Close. The chapter ends by doing the thing it has just argued for: fine-tuning a small pretrained BERT on SNLI with nothing more than a two-layer MLP over the <cls> representation, at batch size 512, maximum length 128, learning rate 1e-4, for 5 epochs. The closing note is honest about both sides of the bargain. The small version is chosen so the demo runs on most machines, which means the reported accuracy sits below what the base model would reach. And the modest added head conceals the real bill: fine-tuning updates BERT's own parameters, 110 million in the base release and 340 million in the large one. BERT buys away design effort by spending parameters — so where memory or time is constrained, the hand-crafted RNN, CNN, and attention models from earlier in the chapter are not obsolete but remain the workable choice.
Key claims, with the lines that support them
Sentiment analysis can be handled as plain text classification.
Because sentiments collapse into discrete polarities or scales, the task becomes mapping a variable-length sequence to one fixed label; Stanford's IMDb corpus supplies exactly that, with 25000 reviews in each of the training and test sets and positive and negative labels balanced — though it covers only binary polarity in the single domain of movie reviews.
“Since sentiments can be categorized as discrete polarities or scales (e.g., positive and negative), we can consider sentiment analysis as a text classification task, which transforms a varying-length text sequence into a fixed-length text category.”
§16.1 Sentiment Analysis and the DatasetRead in context →
Inference over a sentence pair has only three possible verdicts: entailment, contradiction, or neutral.
The author pins each label to a worked pair: hugging someone entails showing affection; running code contradicts sleeping; musicians performing for us leaves their fame undetermined, so it is neutral, defined as everything the first two labels do not cover.
“Neutral: all the other cases.”
§16.4 Natural Language Inference and the DatasetRead in context →
What the model needs for inference is which words correspond to which, not the order they appear in.
Building on the pair-reasoning setup, the author walks through the premise "i do need sleep" against the hypothesis "i am tired", where linking "sleep" to "tired" is what settles the relation. The illustration uses one-to-one links only for display; the actual mechanism weighs all pairs.
“With attention mechanisms, we can align tokens in one text sequence to every token in the other, and vice versa.”
§16.5 Natural Language Inference: Using AttentionRead in context →
3 more claims
Hand-designing a separate architecture for each NLP task does not scale, which is the reason to fine-tune a single pretrained model instead.
Turning the earlier task-specific designs around, the author notes that BERT, when proposed, pushed the state of the art across many tasks while requiring only minimal architectural change — the trade-off being its two released versions at 110 and 340 million parameters.
“These models are helpful when there is space or time constraint, however, crafting a specific model for every natural language processing task is practically infeasible.”
§16.6 Fine-Tuning BERT for Sequence-Level and Token-Level ApplicationsRead in context →
Single-text classification, pair classification or regression, tagging, and question answering can all be covered by adding fully connected layers to BERT.
The author moves through the families with concrete cases: CoLA asks whether a sentence is grammatically acceptable ("I should study." yes, "I should studying." no); semantic textual similarity is scored 0 to 5 and needs only a continuous output with mean squared loss; question answering scores each passage token as a span start and end using separate parameters, as when "mask makers" is extracted as the answer about N95 masks.
“Comparing with Fig. 16.6.1, the only distinction lies in that in text tagging, the BERT representation of every token of the input text is fed into the same extra fully connected layers to output the label of the token, such as a part-of-speech tag.”
§16.6 Fine-Tuning BERT for Sequence-Level and Token-Level ApplicationsRead in context →
For SNLI, fine-tuning BERT needs nothing more than a two-layer MLP on top of the "<cls>" representation.
The author demonstrates this by loading a small pretrained BERT and fine-tuning it on SNLI with batch size 512, maximum length 128, learning rate 1e-4 and 5 epochs; the small version is picked so the demo runs on most machines, so the resulting accuracy sits below what the base model could reach.
“As Fig. 16.6.2 indicates, fine-tuning BERT for natural language inference requires only an extra MLP consisting of two fully connected layers (see self.hidden and self.output in the following BERTClassifier class).”
§16.7 Natural Language Inference: Fine-Tuning BERTRead in context →
How it works
The 3 mechanisms the chapter’s argument runs on.
Mechanism 1
Alignment over word order
Attention lets every token of one sentence be weighted against every token of the other, so the premise word "sleep" can be matched with the hypothesis word "tired". The relation is then read off these matched pairs, which is why the model needs no recurrence or convolution to track order.
Mechanism 2
Why scoring stays linear
The MLP f is fed one token at a time instead of each pair, so it runs m + n times rather than m x n. Decomposing the scoring this way turns a quadratic cost into a linear one and is what makes the attend step affordable.
Mechanism 3
One body, different read-outs
BERT returns a representation for the "<cls>" token and for every input token. Whole-sequence tasks read only "<cls>", token-level tasks read each token, and swapping a continuous output plus squared loss covers regression, so across task families only the input format and which representations feed the added layers change.
Common misreadings
Since BERT only needs a couple of extra layers bolted on, it is the cheap option and makes hand-built MLP, CNN, RNN or attention models obsolete.
The small added head hides the real bill: fine-tuning updates BERT's own parameters, and the original versions hold 110 and 340 million of them. Where space or time is constrained, the crafted task-specific models remain the workable choice.
“However, this benefit comes at the cost of fine-tuning a huge number of BERT parameters for the downstream applications.”
Chapter 16. Natural Language Processing: ApplicationsRead in context →
The alignment diagrams mean each word gets paired with exactly one word in the other sentence.
Those one-to-one pairings appear only to make the idea visible. The model relies on soft alignment, weighing every token of one sequence against every token of the other, which is also why the attend step's cost is discussed at all.
“With attention mechanisms, we can align tokens in one text sequence to every token in the other, and vice versa.”
§16.5 Natural Language Inference: Using AttentionRead in context →
Key concepts in Chapter 16
- Sentiment analysis
- Studying people's sentiments in text they produce, treated as text classification.
- Where it applies: Works when sentiments reduce to discrete polarities or scales.
- Downstream task
- A concrete NLP problem solved by feeding pretrained representations into a task model.
- Where it applies: Assumes useful pretrained representations already exist.
- BERT fine-tuning
- Adapting a pretrained BERT with minimal architecture change to sequence- or token-level tasks. Reusing a pretrained BERT and adding small extra layers, training those from scratch while updating BERT's own parameters.
- Where it applies: Costly in space and time because all BERT parameters are updated. Needs sufficient compute, since the original versions hold 110 and 340 million parameters.
- Natural language inference
- Deciding the logical relation between a premise sentence and a hypothesis sentence.
- Where it applies: Needs sentence pairs; single-sequence classification is insufficient.
- Decomposable attention model
- An attention-plus-MLP model with no recurrence or convolution that attends, compares, then aggregates.
- Where it applies: Ignores token order; relies on soft alignment only.
- SNLI dataset
- A large benchmark of labeled English sentence pairs for inference.
- Where it applies: Test vocabulary must come from the training set, so new test tokens are unknown.
2 more concepts
- Sequence-level versus token-level applications
- Tasks whose output is one label for the whole input versus one label per token.
- Where it applies: Sequence-level uses only the "<cls>" representation; token-level uses every token's representation.
- Stale gradient parameters
- Pretraining-only heads such as MaskLM and NextSentencePred stay unchanged during fine-tuning.
- Where it applies: Requires allowing stale gradients in the training step.
Reader’s notes on Chapter 16AI reading companion
“this benefit comes at the cost of fine-tuning a huge number of BERT parameters”
Read in context →A rare moment of honesty in a textbook — the strongest tool isn't the default one. Written in 2021, and the "space or time is limited" caveat has only grown more relevant.
“we set the length of each review to 500 with truncation and padding”
Read in context →500 tokens of fixed length for a histogram where most reviews sit well under 250 — the batch's convenience silently buys a sea of <pad>. Nobody asks what that does to the model.
“the hidden states (at the last layer) of the bidirectional LSTM at both the initial and final time steps are concatenated”
Read in context →Sounds elegant, but with 500 padded steps the "final time step" is often reading padding. The design is clean on paper and leaky in practice.
17 more notes
“self.pool = nn.AdaptiveAvgPool1d(1)”
Read in context →The text says max-over-time pooling three times, and the code quietly uses average pooling. A genuine mismatch — and precisely the one that lets a reader confirm they actually read the code.
“just think of any text sequence as a one-dimensional image”
Read in context →The whole section rests on this one analogy. It works because n-grams really are local — but it also quietly concedes that convolution doesn't care what the data means, only that it's adjacent.
“one with trainable weights and the other with fixed weights”
Read in context →A hedge dressed as architecture: let one copy adapt, freeze the other against overfitting. Two bets at once on a 25000-sample dataset.
“Neutral: all the other cases.”
Read in context →The third class is defined by exclusion — a waste-basket label. Which is exactly why NLI annotations are noisy and models learn the annotators' habits rather than logic.
“Premise: A man is running the coding example from Dive into Deep Learning.”
Read in context →The textbook writes itself into its own example. Cute, but it also quietly shows how much world-knowledge a "logical" label smuggles in — running code implies awake only because we know humans.
“neither “famous” nor “not famous” can be inferred from the fact that “are performing for us”
Read in context →Neutral is the honest category and also the dumping ground — anything the annotator couldn't decide lands here. Three balanced classes look clean; the boundary is anything but.
“we must use the vocabulary constructed from the training set as that of the testing set”
Read in context →One line of discipline against a whole genre of silent leakage. Worth more than it looks.
“Simpler than preserving the order of tokens in premises and hypotheses, we can just align tokens”
Read in context →The entire bet of the model: throw away word order and still get logic. Startling that it worked — and a hint of why it eventually wouldn't.
“This decomposition trick leads to only \(m + n\) applications (linear complexity) of \(f”
Read in context →Here's where the name comes from, and the real insight: cheapness is bought by refusing to let the pair interact before the dot product. Everything expressive happens later, in comparing.
“predict_snli(net, vocab, ['he', 'is', 'good', '.'], ['he', 'is', 'bad',”
Read in context →A test case chosen to be easy — lexical antonymy, exactly the cue a bag-of-aligned-words model can catch. The hard cases (negation scope, quantifiers) go unasked.
“crafting a specific model for every natural language processing task is practically infeasible”
Read in context →The pivot of the whole chapter, stated almost apologetically. Everything we just built is being reframed as a museum piece.
“the “minimal architecture changes” required by BERT across different applications are the extra fully connected layers”
Read in context →"Minimal" is doing heavy lifting: the architecture barely changes because 340M parameters already absorbed the difficulty. The simplicity is paid for upstream.
“the only distinction lies in that in text tagging, the BERT representation of every token”
Read in context →Sequence-level reads <cls>, token-level reads each position — the same body, different tap points. That's the actual unifying idea, and it's almost embarrassingly plain.
“we can compute the score \(s_i + e_j\) for a valid span from position \(i\) to position \(j\) (\(i \leq j\)), and output the span with the highest score”
Read in context →Note the asymmetry the text glides past: training optimizes start and end independently, but inference couples them via a constraint. The model never learns i≤j — it's imposed afterward by hand.
“BERT requires minimal architecture changes (extra fully connected layers)”
Read in context →The whole chapter's thesis in one clause. "Minimal" is doing rhetorical work — the architecture is minimal only because the pretraining was maximal. Cost moved, not vanished.
“How can we leverage BERT in training language models?”
Read in context →A quietly loaded exercise. BERT is bidirectional, so it can't be a left-to-right LM without cheating — the question is really asking students to discover a limitation, not an application.
“num_heads=4, num_blks=2, dropout=0.2, max_len=max_len)”
Read in context →A real bug, not pedagogy: the function takes num_heads, num_blks, dropout as parameters and then hardcodes over them. Pass 12 heads for bert.base and you'll silently build a 4-head model — exactly the exercise the section sets.
A reader’s takeAI reading companion
A pedagogical trick: build models well enough to feel their cost
Read as one piece, this chapter is a pivot disguised as a survey. It opens by promising that pretrained text representations can be fed into whatever architecture a downstream task needs, then spends its first half doing exactly that by hand — GloVe plus a bidirectional LSTM, then GloVe plus a one-dimensional CNN, both on IMDb sentiment — before turning to sentence pairs with SNLI and the decomposable attention model, and finally announcing that 'crafting a specific model for every NLP task is practically infeasible' and handing everything over to BERT fine-tuning. The architecture of the chapter is therefore an argument: build the bespoke models well enough that you feel their cost, then retire them. It works pedagogically, but it means the first half is written as a museum exhibit by an author who already knows the ending, and the reader should notice that the exhibits are curated to be flattering.
What I saw through, mostly, is the gap between the prose and the code. The text says max-over-time pooling three times and then instantiates AdaptiveAvgPool1d — a real mismatch, and a useful one, because it is exactly the sort of thing only a reader who actually opens the code can catch. The BERT fine-tuning section takes num_heads, num_blks and dropout as arguments and then hardcodes over them, so the very exercise that asks you to scale up to bert.base will silently build a four-head model. Elsewhere the slippage is quieter: padding every review to 500 tokens when most sit under 250, and then concatenating the bidirectional LSTM's hidden states at 'the initial and final time steps' — a design that is clean on paper and, in practice, often reads padding. And the span-prediction head optimizes start and end independently during training while inference couples them through an i≤j constraint bolted on afterward; the model never learns the ordering it is credited with respecting. None of these are fatal, but together they show a book whose explanations are more polished than its implementations.
Continue reading
My sharpest judgement concerns the word 'minimal'. The chapter's thesis — that BERT needs only extra fully connected layers to cover single-text classification, pair classification and regression, tagging, and question answering — is true and genuinely elegant: the unifying idea is just where you tap the representation, <cls> for sequence-level decisions and each token position for token-level ones. The same body, different taps. But the architecture is minimal only because the pretraining was maximal; the difficulty was absorbed by 340M parameters upstream, not dissolved. The book is admirably honest about this once, in the line conceding that the benefit 'comes at the cost of fine-tuning a huge number of BERT parameters' and that this matters when space or time is limited — a caveat written in 2021 that has only grown teeth since. Cost moved; it did not vanish. Related: the decomposable attention model earns its name by refusing to let premise and hypothesis interact before the dot product, which buys linear rather than quadratic cost and pushes all expressiveness into the later comparing step. That is the honest shape of the trade, and it is worth more than the accuracy number attached to it.
I would also tell the reader to distrust the evaluation throughout. SNLI's neutral class is defined by exclusion — 'all the other cases' — which makes it a waste-basket label, and it is the main reason NLI annotations are noisy and models end up learning annotator habits rather than inference. The chapter's own illustrations show how much world knowledge a 'logical' label smuggles in: running a code example implies being awake only because we already know what humans are. And the demo cases are chosen kindly. 'He is good' versus 'he is bad' is lexical antonymy, precisely the cue a bag-of-aligned-tokens model can catch; negation scope, quantifiers, and monotonicity go unasked. Against that, one line of real discipline deserves credit — the insistence on building the test-set vocabulary from the training set, which quietly closes off a whole genre of silent leakage.
Two last things. The textCNN section rests entirely on one analogy, 'think of any text sequence as a one-dimensional image', and it holds because n-grams really are local — but it also concedes that convolution cares only about adjacency, never meaning. And its dual-embedding trick, one trainable copy and one frozen, is a hedge dressed up as architecture: two bets at once on 25,000 examples. Read the chapter, then, for its clear exposition of the taps-and-heads idea and its honest accounting of attention's complexity; read the code with suspicion; and treat the exercise asking how to leverage BERT for language modeling as what it really is — not an application prompt but an invitation to discover that a bidirectional encoder cannot be a left-to-right language model without cheating.
Read Chapter 16 with these cards beside each passage.
Open in FeedLitraChapter 17: Reinforcement Learning
How does Q-Learning drop the assumption that the environment's behavior is known?
How Chapter 17 unfoldsAI-assisted
The opening: a different kind of problem. The chapter begins not with a formalism but with a contrast. In ordinary deep learning, the author observes, each prediction at test time stands on its own — classify this image, then the next, and nothing about the first choice changes the second. Reinforcement learning breaks that independence. Here every decision reshapes the situation in which later decisions are made, and it does so under variables the learner does not control. The examples offered are deliberately varied — routing a delivery, playing a move in Go, choosing what to recommend on Netflix — but they make a single point: an early choice narrows what is possible later. Having established that the coupling across time is the problem, the chapter previews its route through it: the Markov decision process as the formal object, value iteration and Q-learning as the two algorithms, deep RL as the horizon beyond.
The development: formalizing, then decomposing. The MDP arrives as the apparatus that makes sequential decisions tractable — states, actions, a transition function, a reward, and a discounted return summing the future. The load-bearing piece is the Markov assumption, that the next state depends only on the current state and the action taken. The author treats this less as a restriction than as a design choice about bookkeeping: if the next state cannot be predicted from the current description, the remedy is to redefine what counts as a state rather than abandon the model. A robot steered by acceleration is not predictable from its location alone, but pair location with velocity and the next pair is a function of the current pair and the action. The price is a larger state space, paid willingly. From this assumption follows the identity this chapter runs on: because the future hinges only on where you land, a trajectory can be cut after its first step, so the average return from now equals the average reward of the one step taken plus the discounted average return from the resulting state — with the discount guaranteeing the total stays finite even over endless trajectories. Value Iteration is then derived as nothing more than applying this identity over and over; the dynamic programming argument shows that as the number of rounds grows without bound the estimates converge on the optimal values regardless of where they started. The demonstration is the 4×4 FrozenLake grid, where the sole reward of 1 sits at the goal, simplified by assuming actions move the robot reliably so transitions are deterministic.
The turn: dropping the model. The pivot is a limitation, stated plainly — Value Iteration can only run if the entire MDP is already known, transition probabilities included, which is rarely the case. Q-Learning's answer is to replace the transition-weighted average over all possible next states with the single next state the robot actually lands in. The author is careful that this not look like sleight of hand: that landing state is itself drawn from the transition probabilities while the robot acts, so the dynamics still enter the objective — delivered through collected experience rather than an explicit formula. What Q-Learning escapes is the need for the model written down in advance, not dependence on the environment's behavior. This reframing immediately raises the question of which experience to collect. Because each update is a constraint tying the value at one state-action pair to values at others, data that covers only a narrow slice of the space corrupts the estimate everywhere, not merely where the robot failed to go. Hence exploration: ε-greedy or softmax mixing of random choices into the greedy policy. And the mixture is not a compromise but a mechanism — acting mostly greedily is precisely what makes overestimates self-correcting. An action whose value is inflated gets selected and actually executed; the weak reward it returns feeds the next update and pushes the estimate down. A fully random policy would reach every state eventually but demands an enormous number of trajectories, and it severs the link between exploration and the evolving estimate that drives the correction.
The close: an accounting of what was traded. The chapter ends by naming the cost of model-free freedom in the currency of information. Value Iteration may consult the full model at every update; Q-Learning must infer the same content from its own trajectories, so it needs far more rounds. On the identical FrozenLake grid with deterministic actions it does arrive at the optimal solution — but only after roughly 250 iterations. The closing note thus mirrors the structure of this chapter: each step toward fewer assumptions about the environment is paid for in samples, and the reader is left positioned for deep RL, where function approximation is what makes that bill payable at scale.
Key claims, with the lines that support them
Reinforcement learning is a different problem from ordinary deep learning because the decisions are linked through time instead of standing alone.
The author opens the chapter by pointing out that in standard deep learning each test prediction is independent, whereas here every choice reshapes the situation in which later choices are made, under variables the learner does not control. Delivering packages, playing moves in Go and recommending shows on Netflix are all offered as cases where an early choice narrows what is possible later.
“The key idea is that at each stage these variables that we do not often control affect the entire sequence of events in the future, e.g., if there were delays in packing the box in the warehouse the retailer may need to send the package via air instead of ground to ensure a timely delivery.”
Chapter 17. Reinforcement LearningRead in context →
Value Iteration is practical because repeated application of the reward-plus-next-value identity settles on the optimal values no matter where the estimates start.
The author argues from the dynamic programming identity that as the number of update rounds grows without bound the estimates approach the optimal value function regardless of initialization, and then demonstrates it on the 4x4 FrozenLake grid where the only reward of 1 comes at the goal. The demonstration is simplified by assuming actions move the robot reliably, so transitions are deterministic.
“It turns out that as \(k \to \infty\) the value function estimated by the Value Iteration algorithm converges to the optimal value function irrespective of the initialization \(V_0\), \[V^*(s) = \lim_{k \to \infty} V_k(s);\ \textrm{for all states } s \in \mathcal{S”
§17.2 Value IterationRead in context →
Dropping the transition function from the Q-Learning objective is legitimate rather than a sleight of hand.
Following from Value Iteration's requirement that the whole model be known, the author replaces the transition-weighted average over next states with the single next state the robot actually lands in. Since that state is itself drawn from the transition probabilities while the robot acts, the dynamics still enter the objective — just through the collected data instead of an explicit formula.
“So the optimization objective also has access to the transition function, but implicitly in terms of the data collected by the robot.”
§17.3 Q-LearningRead in context →
2 more claims
A data-collection policy that visits only a narrow slice of the space spoils the value estimate everywhere, not just where it failed to go.
The author stresses that the Q-Learning update is a constraint tying the value at one state-action pair to values at others, so thin coverage of the space leaves the whole estimate a poor approximation of the optimal one. This is why actions are mixed with random choices instead of always taking the current best.
“This is because the Q-Learning objective (or value iteration) is a constraint that ties together the value of all state-action pairs.”
§17.3 Q-LearningRead in context →
The freedom to learn without a model of the environment is paid for in sample cost.
Closing the chapter, the author attributes the gap to information: Value Iteration can consult the full model, while Q-Learning must infer the same thing from its own trajectories, and so needs far more rounds. On the same FrozenLake grid with deterministic actions it does reach the optimal solution, but only after roughly 250 iterations.
“This happens because the Value Iteration algorithm has access to the full MDP whereas Q-learning does not.”
§17.3 Q-LearningRead in context →
How it works
The 3 mechanisms the chapter’s argument runs on.
Mechanism 1
Why value now splits into reward plus next value
Because the next state depends only on the current state and action, a trajectory can be cut into its first step and everything after it. The average return from now therefore equals the average reward of the one step taken plus the discounted average return starting from wherever you land, and the discount keeps that total finite even for endless trajectories. This identity is what every algorithm in the chapter iterates on.
Mechanism 2
Enlarging the state restores the Markov property
If the next state cannot be predicted from the current description alone, the fix is to redefine what counts as a state rather than abandon the model. A robot controlled by acceleration is not predictable from its location alone, but pairing location with velocity makes the next pair a function of the current pair and the action. The price is a larger state space.
Mechanism 3
How overvalued actions demote themselves
The data-collecting policy mostly picks whichever action currently looks best, so an action whose value is overestimated gets chosen and actually executed. The poor reward it returns feeds into the next update and pushes its estimate down. This only works because exploration stays tied to the evolving estimate instead of being fixed in advance.
Common misreadings
Since the transition probabilities vanish from the Q-Learning objective, the method works without any dependence on how the environment behaves.
The dependence moves rather than disappears: the next state used in each update is a sample from the very transition probabilities that were dropped, so the dynamics are supplied by the robot's own experience. What Q-Learning avoids is needing the model written down in advance, which is exactly why it needs many more rounds of data.
“So the optimization objective also has access to the transition function, but implicitly in terms of the data collected by the robot.”
§17.3 Q-LearningRead in context →
If narrow data coverage is the problem, then acting completely at random is the safest way to collect data.
A fully random policy does eventually reach every state, but the author notes it requires a very large number of trajectories. The recommended approach keeps mostly choosing the currently best action with some randomness mixed in, which also makes the self-correction work: an overrated action gets tried, returns a weak reward, and is pushed down at the next update.
“This particular \(\pi_e\) is called an \(\epsilon\)-greedy exploration policy because it chooses the optimal action (under the current estimate \(\hat{Q}\)) with probability \(1-\epsilon\) but explores randomly with the remainder probability \(\epsilon”
§17.3 Q-LearningRead in context →
Key concepts in Chapter 17
- Reinforcement learning
- Techniques for building systems that make decisions one after another, where each choice changes what comes later.
- Where it applies: Applies when future decisions depend on past ones; unlike standard deep learning, test predictions are not independent.
- Markov decision process
- A four-part model of how a system's state changes as actions are applied: states, actions, transition probabilities, reward.
- Where it applies: Requires that the next state depend only on the current state and action; otherwise enlarge the state (e.g., add velocity).
- Discount factor
- A number below one that shrinks far-future rewards so even endless trajectories have a finite return.
- Where it applies: Small values push short goal-reaching paths; values near 0.99 encourage exploration before committing.
- Value function
- The expected discounted return if you start in a state and keep acting according to a given policy.
- Where it applies: Defined relative to a policy; the optimal one is attained by the optimal policy.
- Principle of dynamic programming
- The value of now equals immediate reward plus the averaged value of wherever you land next; the tail of an optimal path is itself optimal.
- Where it applies: Rests on the Markov assumption; it is the base of all RL algorithms in this chapter.
- Value Iteration
- Repeatedly updating value estimates with the dynamic programming identity until they settle on the optimal values.
- Where it applies: Assumes known environment behavior; Q-Learning generalizes it to unknown environments.
4 more concepts
- policy
- A conditional distribution over actions given the state; deterministic policies are the special case that put all probability on one action.
- Where it applies: Probabilities must sum to one at every state.
- Q-Learning
- Updating action values from sampled transitions instead of a known transition function.
- Where it applies: Values of state-action pairs absent from the dataset are set to minus infinity.
- exploration versus exploitation
- Mixing the currently best action with random actions so data covers the whole space.
- Where it applies: A purely random policy reaches all states but needs very many trajectories.
- Self-correcting property
- Overvalued actions get picked, yield poor rewards, and are demoted at the next update.
- Where it applies: Relies on the exploration policy being tied to the evolving estimate of Q.
Reader’s notes on Chapter 17AI reading companion
“the retailer finding the clothes in the warehouse closest to your house”
Read in context →Opening with a package delivery is clever: it smuggles in the whole structure — many actors, no single controller, and a utility only realized at the end. But note the sleight of hand: real logistics are optimized by humans and solvers, not RL. The example teaches the shape of the problem, not RL's actual victories.
“in standard deep learning the prediction of a trained model on one test datum does not affect the predictions on a future test datum”
Read in context →This is the cleanest one-sentence statement of the distinction I've read. The whole difficulty of RL lives in that broken independence: once your own output becomes your next input's cause, i.i.d. dies and with it most of the comfortable guarantees of supervised learning.
“It is important to note that the reward is designed by the user (the person who creates the reinforcement learning algorithm) with the goal in mind.”
Read in context →Dropped in as a footnote, but it's the whole ethical and engineering crux. The agent optimizes exactly what you wrote down, not what you meant. The textbook hands you the lever and walks past the fact that misspecification is where most real RL projects die.
15 more notes
“For large values of the discount factor, say \(\gamma = 0.99\), the robot is encouraged to explore and then find the best trajectory”
Read in context →Careful here — γ doesn't encourage exploration. It just makes the agent patient about delayed reward. Exploration is a separate problem, handled by ε-greedy, entropy bonuses, and so on. This sentence conflates farsightedness with curiosity, and a beginner will carry that confusion forward.
“if we chose our state \(s_t\) to the tuple \((\textrm{location}, \textrm{velocity})\) then the system is Markovian”
Read in context →The honest move of the chapter. Markovianness isn't a property of the world; it's a property of how you carve up the world. Any history-dependence can be absorbed into the state — which is also the quiet escape hatch: push it far enough and the state space explodes. Atari's four-frame stack is exactly this trick.
“the average return from the current state is the sum of the average return from the next state and the average reward of going to the next state”
Read in context →"Quite intuitive" is doing a lot of work. The decomposition only holds because of the Markov assumption plus the linearity of expectation — it's intuitive after you accept that the future doesn't care how you arrived. Everything downstream, value iteration and Q-learning alike, is just this one line rearranged.
“V^*(s) = \mathrm{argmax}_{a \in \mathcal{A}} \Big\{ r(s,a) + \gamma \sum_{s' \in \mathcal{S}} P(s' \mid s, a) V^*(s') \Big”
Read in context →A typo with real teeth: this should be max, not argmax. One returns a value, the other an action. The line just above, for π*, is the argmax version. Worth flagging because a reader reconstructing the Bellman equation from here would build it wrong.
“the remainder of an optimal trajectory is also optimal”
Read in context →Bellman's whole empire in nine words. And the converse is what makes it usable: you never need to search over trajectories, only over single steps. That compression from exponential to polynomial is the actual discovery.
“actions that are “up” (\(\uparrow\)), “down” (\(\rightarrow\)), “left” (\(\leftarrow\)), and “right” (\(\rightarrow”
Read in context →Down is drawn as a right arrow and right is drawn as a right arrow too — two glyph errors in one parenthetical. Minor, but telling: the prose has been proofread, the notation hasn't.
“the robot has reliable actions, i.e. \(P(s' \mid s, a) = 1”
Read in context →Note what simplification costs: FrozenLake's entire point is the slippery ice, and they've frozen it solid. With deterministic transitions this is just shortest-path search, and value iteration's real selling point — handling stochasticity — never gets demonstrated.
“The key idea behind Q-Learning is to replace the summation over all \(s' \in \mathcal{S}\) in the above expression by a summation over the states visited by the robot.”
Read in context →The pivot of the chapter, stated almost casually. Replacing an expectation with samples from experience is the move that turns planning into learning — and it means the agent's own behavior now determines what it can know. Which is precisely why exploration becomes unavoidable from here on.
“We have not cheated: as the robot uses the policy \(\pi_e\) to take an action \(a_t^i\) at state \(s_t^i\), the next state \(s_{t+1}^i\) is a sample drawn from the transition function”
Read in context →The defensive "we have not cheated" is the honest heart of model-free RL: the transition model never disappears, it just hides inside the data. Sampling is the model, in disguise.
“The value of state-action tuples \((s, a)\) that are not a part of the dataset is set to \(-\infty”
Read in context →A startling choice slipped in as a footnote — and it quietly contradicts the code below, which initializes Q to zeros. Negative infinity would also poison every max over unseen actions.
“the estimate of \(Q^*\) at all states \(s \in \mathcal{S}\) will be bad, not just the ones visited by \(\pi_e”
Read in context →This is the strongest sentence in the section. Bellman consistency is a global constraint, so local ignorance is not locally contained — error travels backwards along every chain of states.
“Bad actions, e.g., ones whose value is overestimated in \(\hat{Q}(s,a)\), are explored by the robot but their value is correct in the next update”
Read in context →The optimism is what does the work: overestimation is self-punishing because it invites the very trial that refutes it. Though "their value is correct" reads like a typo for "corrected" — and in practice the max operator means overestimation often isn't corrected so tidily.
“This ability to not only collect new data but also collect the right kind of data is the central feature of reinforcement learning algorithms”
Read in context →Here is the real dividing line — not rewards versus labels, but who chooses the dataset. Supervised learning inherits its data; RL authors its own, and must live with what it failed to look at.
“we assume the robot has reliable actions, i.e. \(P(s' \mid s, a) = 1”
Read in context →A large simplification stated casually — FrozenLake is famous precisely for its slipperiness, and removing it removes the stochasticity that makes the expectation in the objective matter at all.
“Q-learning can find the optimal solution for this problem roughly after 250 iterations”
Read in context →An honest and underrated admission: the price of not knowing the MDP is paid in experience. Worth noting too that epsilon stays at 0.9 throughout — almost pure random walking, with no decay schedule.
A reader’s takeAI reading companion
Honest MDPs and sharp core framing, undercut by a misleading opening example
Read as one piece, this chapter is a compressed descent from problem to algorithm, and its architecture is better than its execution. It opens with a package delivery — many actors, no central controller, a payoff realized only at the end — which smuggles in the whole shape of sequential decision making before naming a single symbol. That opening is pedagogically clever but quietly misleading: real logistics are solved by human planners and combinatorial solvers, not RL, so the example teaches the structure of the problem rather than any of RL's actual victories. The chapter then earns its keep with one sentence that is the sharpest framing of the field I have read: in standard deep learning, the prediction on one test datum does not affect predictions on future ones. Everything hard about RL lives in that broken independence. Once your own output causes your next input, i.i.d. dies, and the comfortable guarantees of supervised learning go with it.
The MDP section is the chapter's strongest stretch, mostly because it is honest where textbooks usually bluff. It admits that Markovianness is not a property of the world but of how you carve the world into states — append velocity to location and the system becomes Markovian, which is also the quiet escape hatch that Atari's four-frame stack exploits, and the quiet trap, since pushed far enough the state space explodes. The Bellman decomposition is presented as 'quite intuitive,' which does a great deal of unacknowledged work: it holds because of the Markov assumption plus linearity of expectation, and it is intuitive only after you have accepted that the future does not care how you arrived. Everything downstream — value iteration, Q-learning, and by extension deep RL — is that single line rearranged. The principle of optimality in nine words ('the remainder of an optimal trajectory is also optimal') is Bellman's whole empire, and its real payload is the converse: you never search over trajectories, only over single steps. That collapse from exponential to polynomial is the actual discovery, and the chapter states it without quite celebrating it.
Continue reading
Two weaknesses recur and are worth naming. First, the notation has not been proofread with the care the prose has. The optimal value equation is written with argmax where it needs max — one returns a value, the other an action, and a reader reconstructing Bellman from this page builds it wrong. The action glyphs render 'down' and 'right' both as right arrows. The claim that unvisited state-action pairs are set to negative infinity flatly contradicts the code, which initializes Q to zeros; and negative infinity would poison every max over unseen actions. These are small individually and corrosive collectively, because this is precisely the material where a reader cannot distinguish a typo from a subtlety.
Second, and more substantively, the running example is defanged. FrozenLake is famous for its slippery ice, and the chapter freezes it solid by assuming deterministic transitions. With P(s'|s,a)=1 the problem reduces to shortest-path search, the expectation in the objective carries no weight, and value iteration's actual selling point — handling stochasticity — is never demonstrated. The chapter also conflates patience with curiosity when it says a large discount factor 'encourages exploration'; γ makes the agent farsighted about delayed reward, nothing more. Exploration is a separate problem, solved by ε-greedy and entropy bonuses, and a beginner who merges the two will carry that confusion into every later algorithm. The Q-learning demo compounds this by holding ε at 0.9 throughout with no decay schedule — near-pure random walking dressed as a policy.
The Q-learning section is where the chapter's real argument lands. The pivot is stated almost casually: replace the summation over all next states with a summation over states actually visited. That one substitution converts planning into learning, and it carries a consequence the text names with unusual candor — 'we have not cheated,' because the next state really is a sample from the transition function. The transition model never disappears in model-free RL; it hides inside the data. Sampling is the model in disguise. From that follows the best observation in the whole chapter: if your exploration policy neglects part of the state space, the estimate of Q* is bad everywhere, not just in the neglected region. Bellman consistency is a global constraint, so local ignorance is not locally contained — error propagates backwards along every chain of states. And the chapter's closing insight is the correct dividing line for the field: not rewards versus labels, but who authors the dataset. Supervised learning inherits its data; RL writes its own and must live with whatever it declined to look at. The optimism of the max operator is what makes this tractable — an overestimated action invites the very trial that refutes it — though the text oversells the tidiness here, since in practice the max is also precisely what makes overestimation bias persist.
What I would tell a reader: take the MDP formalism and the Bellman recursion from this chapter and trust them, because they are clearly and honestly presented. Treat the equations as drafts and re-derive them rather than copying. Mentally restore the ice — turn the slipperiness back on and watch what value iteration does — because the deterministic version teaches the algorithm's mechanics while hiding its purpose. And keep hold of the one footnote the chapter walks straight past: the reward is designed by you, and the agent optimizes exactly what you wrote down, not what you meant. The chapter hands you that lever and moves on, but misspecification is where most real RL projects die. Read this as a clean, compact map of the problem and the two canonical algorithms, not as a guide to making RL work.
Read Chapter 17 with these cards beside each passage.
Open in FeedLitraChapter 18: Gaussian Processes
How does marginal likelihood pick the length-scale automatically?
How Chapter 18 unfoldsAI-assisted
Opening: relocating the modelling assumptions. The chapter begins with a reframing rather than a technique. Ordinary models hide their commitments in weights — numerous, individually meaningless parameters that no one can inspect and judge. A Gaussian process instead places the assumptions directly on functions: any model linear in Gaussian parameters already is a GP, so the move costs nothing in generality. The straight-line case makes the swap concrete, a prior over slope and intercept becoming a zero mean function and the covariance 1 + xx′, after which one samples functions directly and never touches a parameter again. From there the author introduces the kernel as the real interface to the model, with two knobs you can actually reason about. A length-scale sweep from 0.1 to 10 shows what they do: once two inputs are separated by more than the length-scale their function values are essentially uncorrelated, so the curve is free to swing between them — short length-scales give fast-varying samples and error bars that balloon as soon as you leave the data, long ones give smooth fits. The amplitude merely stretches everything vertically. Two honest caveats are attached: these values were chosen by eye, with principled selection deferred, and the figures' vertical scales differ.
Development: closed-form prediction, then the function-space view. Having set up a prior over functions, the author shows you never need infinitely many samples to use it. Conditioning the joint Gaussian on observations yields the predictive mean and covariance analytically, so beyond the kernel hyperparameters there is nothing to train. A single-observation illustration carries the point: f(x₁) = 1.2 with correlation 0.9 pulls a prediction to about 1.08; raising the correlation to 0.95 pulls it to 1.14 with tighter bars, though the uncertainty stays wide on one data point. Two structural facts fall out — the mean depends on observed targets while the predictive variance does not, and the exactness historically carried cubic cost, capping training sets near ten thousand points. The chapter then formalizes the shift into function space proper: a GP is pinned down entirely by its mean and covariance functions.
The turn: the infinite limit, where model classes merge. The pivot is the derivation that takes a weighted sum of radial basis functions with Gaussian weights, whose covariance is a finite sum over basis centres, and lets the number of centres grow without bound. The sum becomes a Riemann integral, and the integral evaluates to something proportional to the RBF kernel. The conclusion is pointed: an infinitely parametrized model needs no parameters at runtime, because the entire prior over functions is carried by a closed-form covariance. The author then turns the argument outward via Neal's 1994 result — an infinitely wide Bayesian neural network is a Gaussian process with a particular kernel — so networks and kernel methods are far less distinct than they are usually portrayed. The caveats keep it from becoming a slogan: closed forms are known only for certain transfer functions such as erf units, and the resulting neural-network kernel is non-stationary, behaving differently near the origin, unlike the RBF kernel which looks the same everywhere. This is also where the chapter pre-empts the obvious objection: infinite capacity does not imply overfitting, because the prior concentrates its mass on a narrow family of smoothly varying functions, and the kernel's assumptions do the regularizing that a parameter count otherwise would.
Closing: the practical recipe, and what the error bars mean. The final movement is a hands-on walkthrough that deliberately contradicts the "nothing to train" reading. First, inspect the prior: a length-scale of 0.2 produced sample functions varying far too fast for the data, so the author re-initialized at 0.4 before fitting. Then learn the hyperparameters by maximizing the marginal likelihood, which recovers a length-scale of 0.299 and a noise standard deviation of 0.24 — the latter nearly exact. But the success is explicitly not guaranteed, and the chapter explains why the objective has rival optima: a long length-scale makes the function nearly flat and charges the data's variation to large noise, while a short one lets the function chase the data and leaves noise little to explain. Both stories are locally coherent, the objective is non-convex and non-decomposable (hence full-batch Adam or L-BFGS, no mini-batching), and a bad start settles in the wrong basin. The chapter ends on an interpretive discipline rather than a result: the posterior separates reducible epistemic uncertainty about the latent function from irreducible aleatoric noise, and an error bar means nothing until you say which one it is and on what scale. The author's evidence is the sorry state of practice — undefined error bars, slippage between variances and standard deviations, standard deviations and standard errors, confidence intervals and credible sets — and the worked consequence is sharp: a 95% credible set for the latent function should not swallow the observed points; covering those requires adding back the noise variance. A final pass in GPyTorch reproduces the whole pipeline in production tooling.
Key claims, with the lines that support them
It is better to put your modelling assumptions on functions than on parameters.
The author's opening move: weights in a typical model are numerous and mean little on their own, whereas a kernel lets you state high-level properties — how wiggly, how large in scale — that you can actually judge. The straight-line example makes the swap concrete: a prior on slope and intercept turns into a mean function of zero and a covariance of 1+xx', after which functions can be sampled directly without ever touching a parameter. And because any model linear in Gaussian parameters (including infinitely wide networks) is a Gaussian process, function space covers many familiar model classes at once.
“These parameters are often numerous and relatively uninterpretable — such as the weights of a neural network.”
§18.1 Introduction to Gaussian ProcessesRead in context →
A handful of interpretable kernel knobs fix the smoothness, the vertical scale, and how fast uncertainty grows.
Having moved the modelling to function space, the author shows what the knobs do by sweeping the length-scale from 0.1 to 10: samples get visibly less wiggly as it grows, because inputs separated by more than the length-scale become essentially uncorrelated. The amplitude, by contrast, only stretches the function vertically without changing how fast it varies. The caveat is stated too — these values were picked by eye here, with automatic selection by marginal likelihood deferred, and the vertical scales of the figures differ.
“We see the amplitude parameter affects the scale of the function, but not the rate of variation.”
§18.1 Introduction to Gaussian ProcessesRead in context →
Predictions and their error bars come out of simple Gaussian conditioning, in closed form.
Following from the prior over functions, the author notes you never need to draw infinitely many samples: conditioning the joint Gaussian on observations gives the predictive mean and covariance analytically, so apart from learning kernel hyperparameters there is nothing to train. A single-point illustration carries the idea — observing f(x₁)=1.2 with correlation 0.9 pulls the prediction to a mean of about 1.08, and raising the correlation to 0.95 pulls it to 1.14 with tighter error bars, though uncertainty stays wide because only one point was seen. Notably the mean depends on the observed targets while the predictive uncertainty does not, and the exactness historically came at cubic cost, capping training sets near ten thousand points.
“Note that we do not actually have to take an infinite number of samples to compute this expectation; as we will see later, we can compute the expectation in closed form.”
§18.1 Introduction to Gaussian ProcessesRead in context →
3 more claims
Taken to the infinite limit, neural networks and Gaussian processes stop being separate model classes.
This is where the author turns the argument around: having built a GP out of infinitely many basis functions, he points to Neal's 1994 result that a Bayesian neural network with infinitely many hidden units becomes a Gaussian process with a particular kernel, so networks are not as distinct from kernel methods as usually portrayed. The caveat is that closed-form kernels are known only for certain transfer functions, such as erf units, and the resulting neural-network kernel is non-stationary — it behaves differently near the origin, unlike the RBF kernel whose behaviour looks the same everywhere.
“Neural networks are not as distinct as we make them out to be.”
§18.2 Gaussian Process PriorsRead in context →
Look at samples from the prior before fitting, and remember that fitting the hyperparameters is a non-convex problem.
In the hands-on walkthrough, a length-scale of 0.2 produced prior functions that varied far too quickly for the data at hand, so the author re-initialized at 0.4 before fitting — sanity-checking the prior is part of the recipe. Maximizing the marginal likelihood then recovered a length-scale of 0.299 and a noise standard deviation of 0.24, the latter extremely close to the truth. But the author warns that this robustness is not guaranteed: because a long length-scale is only credible together with large noise and a short one leaves little variation to blame on noise, the objective has local optima and a poor starting point can land in one.
“Before we fit the data, it is important to consider whether we have specified a reasonable prior.”
§18.3 Gaussian Process InferenceRead in context →
An error bar means nothing until you say which uncertainty it is and on what scale it is drawn.
Having produced a posterior with two separable sources — reducible doubt about the noise-free function (epistemic, shrinking with data) and irreducible observation noise (aleatoric) — the author insists on labelling which one a plot shows. His evidence is the state of practice: papers routinely display undefined error bars and slide between variances and standard deviations, standard deviations and standard errors, confidence intervals and credible sets. The practical consequence in the worked example is that a 95% credible set for the latent function, being two standard deviations of the epistemic part, should not swallow the observed points; covering the observations requires adding the noise variance.
“Without being precise about what the uncertainty represents, it is essentially meaningless.”
§18.3 Gaussian Process InferenceRead in context →
How it works
The 3 mechanisms the chapter’s argument runs on.
Mechanism 1
How the length-scale makes functions wiggle
The kernel says how strongly two function values are correlated as a function of how far apart their inputs are. Once two inputs sit farther apart than the length-scale, their values are almost uncorrelated, so the function is free to swing between them and far-away data barely constrains a prediction. A short length-scale therefore yields fast-varying samples and uncertainty that balloons quickly away from the data, while a long one yields smooth fits; the amplitude only rescales the vertical spread.
Mechanism 2
Infinitely many bumps collapse into one kernel
Start with a model that is a weighted sum of radial basis functions with Gaussian weights; its covariance is a finite sum over basis centres. Let the number of basis functions grow without bound and that sum becomes a Riemann integral, which evaluates to something proportional to the RBF kernel. So an infinitely parametrized model needs no parameters at runtime at all — the whole prior over functions is carried by a closed-form covariance function.
Mechanism 3
Why hyperparameter fitting has rival optima
The marginal likelihood has to explain all the observed variation, and it can do so in two incompatible ways. A long length-scale makes the underlying function nearly flat, so the wiggles in the data must be charged to a large noise variance; a short length-scale lets the function itself chase the data, leaving little variation for noise to explain. Both stories are locally plausible, so the non-convex objective has separate basins and a bad start can settle in the wrong one.
Common misreadings
A model with infinitely many parameters that can fit any continuous function will surely overfit a small dataset.
Capacity and overfitting are separate issues here: the RBF Gaussian process is a universal approximator yet generalizes well on little data, because its prior assigns most of its weight to a narrow family of plausible, smoothly varying functions. The strong assumptions encoded in the kernel — correlation decaying with input distance, at a particular length-scale and amplitude — do the regularizing that a parameter count would otherwise have to.
“A Gaussian process with an RBF kernel is a universal approximator, capable of representing any continuous function to arbitrary precision.”
§18.2 Gaussian Process PriorsRead in context →
Since the author says there is essentially no training in GP regression, the method works out of the box with nothing to tune.
What is training-free is the posterior itself, which drops out of Gaussian conditioning once the kernel is fixed. The kernel's length-scale, amplitude, and noise level still have to be learned, and the author does so by maximizing the marginal likelihood — an objective that is neither convex nor decomposable over data points, so it cannot be mini-batched and is run full-batch with Adam or L-BFGS, with initialization chosen deliberately after inspecting prior samples.
“The predictive mean explicitly depends on the target values \(\textbf{y}\) but the predictive variance does not.”
§18.3 Gaussian Process InferenceRead in context →
Key concepts in Chapter 18
- Gaussian process
- A distribution over functions: any finite set of function values is jointly Gaussian. A prior over functions fixed entirely by a mean function and a covariance (kernel) function.
- Where it applies: Requires Gaussian parameters or basis-function form; needs a mean and covariance function. Needs joint Gaussianity of function values; non-Gaussian likelihoods require approximate inference.
- Covariance function (kernel)
- The function giving covariance between function values at two inputs; it sets generalization behavior.
- Where it applies: RBF assumes correlation decays with input distance, which may not fit all data.
- Aleatoric vs epistemic uncertainty
- Epistemic uncertainty comes from missing information and shrinks as data accumulates. Epistemic uncertainty is reducible doubt about the true noise-free function; aleatoric uncertainty is the observation noise that more data cannot remove.
- Where it applies: Distinct from observation noise, which adds a diagonal term to the kernel. Here epistemic shows up as np.diag(post_cov) and aleatoric as post_sig_est**2; the split assumes the noise model is correct.
- Hyperparameters
- Here the kernel's amplitude and length-scale, interpretable knobs on function scale and smoothness.
- Where it applies: Good values matter for generalization; marginal likelihood can set them automatically.
- RBF kernel
- The most common covariance function, with an amplitude and a lengthscale controlling variation.
- Where it applies: Stationary, so it cannot express properties that change across input space.
- Stationary kernel
- A kernel depending only on the difference between inputs, so function behaviour looks the same everywhere.
- Where it applies: The neural network kernel is non-stationary and looks different near the origin.
4 more concepts
- Marginal likelihood
- The probability of the data given hyperparameters, used to learn kernel settings.
- Where it applies: Costs O(n^3) through log determinants and linear solves.
- Marginal likelihood for hyperparameter learning
- Integrating out the function gives a likelihood of the data given only kernel hyperparameters and noise, which you can maximize to learn them.
- Where it applies: Not convex and does not factorize over data points, so no mini-batching and poor initializations can land in local optima.
- Exact GP inference
- Closed-form posterior predictions, available only when the likelihood is Gaussian.
- Where it applies: Breaks down for classification or non-Gaussian likelihoods, and for datasets beyond roughly 10,000 points.
- 95% credible set
- Two standard deviations around the predictive mean, expressing belief about where the ground-truth function lies.
- Where it applies: For the latent function it should not contain the data points; covering observations requires adding the noise variance.
Reader’s notes on Chapter 18AI reading companion
“There is a running joke that “everything is a special case of a Gaussian process”
Read in context →The joke is also a warning: a frame that explains everything constrains nothing. Linear-in-parameters with Gaussian weights is a real restriction, and the joke quietly hides where it bites.
“GPs and and deep neural networks are not competing approaches, but highly complementary”
Read in context →Note the defensive posture — a chapter in a deep learning book has to justify why kernels still matter. The typo in the duplicated 'and' is a nice reminder this is living text.
“each of these functions are entirely consistent with our data, perfectly running through each observation”
Read in context →True only because noise-free is assumed here, which isn't admitted until the very end. Readers will carry away a false picture of interpolation as what GPs do.
17 more notes
“creating a credible interval that has a 95% probability of containing the true value of the function”
Read in context →Slipped in without qualification: that's 95% under the model, pointwise, not jointly. The honest phrasing would hurt the figure's rhetoric.
“Fortunately, there is a robust and automatic way to specify these hyperparameters, using what is called the marginal likelihood”
Read in context →'Robust and automatic' is doing a lot of work — marginal likelihood optimization is nonconvex and happily collapses the length-scale on sparse data. The promissory note is dated to a later notebook.
“our uncertainty is still righly quite large, because we have only observed a single data point!”
Read in context →The two-panel correlation demo is the best pedagogy in the segment: conditioning as drawing a horizontal line through an ellipse. Everything about GP regression is in that picture.
“Moreover, any Gaussian process f(x) can be expressed in the form of equation (18.2.1)”
Read in context →The converse is where the real content lives, and it's asserted in one clause with no proof — it needs possibly-infinite basis vectors and a Mercer-type argument.
“it is relatively tedious to reason about the parameters, which are largely uninterpretable”
Read in context →'Tedious' understates it. The genuine move is that function space has the same information in coordinates we can actually hold opinions about — smoothness, periodicity — rather than weights.
“Let \(c_J = \log J\), \(c_1 = -\log J\), and \(c_{i+1}-c_{i} = \Delta c = 2\frac{\log J}{J”
Read in context →Here's the payoff: infinitely many RBF bumps with shrinking weights become one closed-form kernel. Infinite parameters stop being scary once you only ever touch their covariance.
“Perhaps all the fuss about overparametrized neural networks is misplaced.”
Read in context →A polemical aside slipped into a textbook. The author has a horse in this race, and this chapter is quietly an argument, not just an exposition.
“later published in 1996, as it was one of the most infamous NeurIPS rejections”
Read in context →The best sentence in the section, and it's a footnote about peer review. Field lore smuggled into a derivation — a reminder that what counts as important is decided late.
“This connection, discovered by Radford Neal, triggered machine learning researchers to move away from neural networks, and towards Gaussian processes.”
Read in context →Note the irony the summary doesn't name: the same result that emptied the neural-net room in the 90s is now cited to defend neural nets. The theorem didn't change; the fashion did.
“The predictive mean explicitly depends on the target values \(\textbf{y}\) but the predictive variance does not.”
Read in context →The strangest fact in GP regression. Your error bars are drawn by where you looked, not what you saw — geometry of sampling, not evidence. The hedge about hyperparameters afterwards is doing a lot of work.
“have given GPs a reputation for “being slow” that has been inaccurate now for almost a decade”
Read in context →Audible irritation. Reputations outlive their causes, in methods as in people.
“Without being precise about what the uncertainty represents, it is essentially meaningless.”
Read in context →The moral center of the whole chapter, and it's about writing figures honestly rather than about math. Error bars as a literacy problem.
“We would not want nor expect it to contain the data points.”
Read in context →Good teaching: naming what should not happen. Most readers' instinct is that a good band swallows the dots.
“the learned noise is extremely close to the true noise, which helps indicate that our GP is a very well-specified to this problem”
Read in context →Convenient — the data were generated from a smooth sine plus Gaussian noise, exactly the kernel's assumptions. A demo that validates itself.
“This may seem like a lot of code to simply reproduce the basic regression above, and in a sense, it is.”
Read in context →Rare honesty from a textbook — admitting the library version is worse for the toy case, and justifying it only by the future. That's the real argument for frameworks: you pay upfront for optionality.
“Because the marginal likelihood does not factorize over data instances, we cannot use an optimizer over “mini-batches” of data and be guaranteed convergence.”
Read in context →Here's the quiet structural reason GPs never rode the deep-learning scaling wave. No factorization means no SGD means no cheap scale. One sentence explains a decade of divergence.
“Unlike in standard deep learning, doing a good job of optimizing the marginal likelihood corresponds strongly with good generalization”
Read in context →A striking inversion — in deep nets, optimizing harder can hurt; here the objective is actually trustworthy. The marginal likelihood already contains the Occam penalty, so there's nothing to protect yourself from.
A reader’s takeAI reading companion
Readers absorb from early figures that GPs work through interpolation
The chapter moves in three steps — intuition, theory, practice — and the move is the argument. It opens by selling GPs as distributions over functions, where you stop fiddling with uninterpretable weights and instead state what you believe about the function itself: how wiggly, how tall, how smooth. The running joke that everything is a special case of a GP is offered as charm, but it is really the chapter's load-bearing claim and its weakest moment: a frame that covers everything constrains nothing, and the actual restriction — linear in Gaussian parameters — is tucked behind the laughter. The middle segment pays the theory debt: the RBF kernel falls out as an infinite limit of shrinking basis bumps, infinite-width nets turn into GPs, and the posterior and marginal likelihood arrive in closed form. The last segment runs the whole loop by hand and then again in GPyTorch, and that repetition is the honest part of the book — it admits the library is worse for the toy problem and defensible only as a down payment on scale.
What I saw through is mostly rhetorical. The early figures draw noise-free functions threading every observation, so readers absorb interpolation as what GPs do, and the noise model is only confessed at the end. Credible intervals are described as having 95% probability of containing the truth, with no 'under this model' and no 'pointwise'. Marginal likelihood optimization is called robust and automatic when it is nonconvex and will cheerfully collapse the length-scale on sparse data. The final demo validates itself: sine plus Gaussian noise, fit by a kernel that assumes exactly that, and the recovered noise matches the truth because it was built to. None of this is dishonest, but all of it is a textbook flattering its method, and the chapter is in fact a quiet polemic — the aside that the fuss over overparametrized networks may be misplaced is an author with a horse in the race, and the defensive insistence that GPs and deep nets are complementary is the tell of a kernel chapter in a deep learning book.
Continue reading
The sharpest thing in the chapter is also the one it half-hides: the predictive variance does not depend on y. Your error bars are drawn by where you chose to look, not by what you saw there — sampling geometry, not evidence. Sitting next to that is the structural fact that explains everything about where GPs went: the marginal likelihood does not factorize over data, so no mini-batches, no SGD, no cheap scaling. One sentence accounts for a decade of divergence. And the inversion worth carrying out: unlike deep learning, optimizing the GP objective harder tends to generalize better, because the Occam penalty is already inside the objective rather than bolted on as regularization. The historical irony goes unnamed — Neal's infinite-width result emptied the neural-net room in the nineties and is now cited to defend neural nets; the theorem never changed, only the fashion.
What I would tell a reader: the best pedagogy is the two-panel correlated-Gaussian picture, conditioning as a horizontal slice through an ellipse — everything about GP regression lives there, so sit with it before any algebra. The moral center is a sentence about figures, not math: uncertainty without being precise about what it represents is meaningless. Read the chapter for the function-space reframing and that discipline, and read its noise-free pictures, its self-confirming demos, and its 'robust and automatic' with the suspicion they have earned.
Read Chapter 18 with these cards beside each passage.
Open in FeedLitraChapter 19: Hyperparameter Optimization
How do searcher and scheduler split the decisions in the HPO API?
How Chapter 19 unfoldsAI-assisted
The opening: a problem posed as an economic one. The chapter begins by naming hyperparameters as the settings that govern learning and model structure — learning rate, weight decay, dropout, layer and filter counts — and observing that in practice they are set by hand, by trial and error. The first move is to establish that this is untenable, and the argument is made with a price tag rather than an appeal to elegance: one ResNet run on CIFAR-10 takes over two hours on an EC2 g4dn.xlarge, so trying ten configurations sequentially consumes roughly a day, and because good values shift between datasets and models, that day must be spent again on the next problem. From this cost the chapter derives its central reframing: tuning becomes a nested global optimization problem, an outer search over a configuration space wrapped around the inner training loop. Two constraints on that outer problem are fixed immediately. The objective must be validation error, not training loss, because training loss is minimized by switching regularization off — set dropout or weight decay to zero and the training numbers improve while generalization degrades, so optimizing training loss would systematically select the wrong settings. And the search must be gradient-free: a gradient of validation error with respect to hyperparameters would require differentiating through the whole training run, stochastic training makes every measurement noisy regardless, and approximate hypergradient methods are not yet competitive. What remains is sample-efficient black-box search, and the chapter's first instance of it is random search — presented concretely on a single hyperparameter, sampling learning rates for softmax classification and keeping whichever scored lowest. It is endorsed as the right general-purpose baseline, simple and better than grid search, whose equally-spaced grid blows up with dimension; but the same passage marks its defect, which the rest of the chapter attacks: random search never adapts its sampling distribution, and spends a full training budget on hopeless configurations and promising ones alike.
The development: three successive repairs. From the baseline the chapter builds outward in layers. First comes a methodological correction rather than an algorithmic one: an HPO method cannot be judged from a single run. The comparison of random search against Bayesian optimization is repeated 50 times with different seeds and reported as statistics, and the resulting curves make the point — they are indistinguishable up to roughly 1000 seconds, with Bayesian optimization pulling ahead only afterwards, a gap any single noisy run could easily have shown backwards. Second comes parallelism. Configurations with more layers or filters simply take longer to train, so a synchronous batch leaves fast trials waiting on slow ones; dispatching a new trial the instant a worker frees up removes that idling and makes random search roughly as many times faster as there are workers. The chapter is careful about what is being claimed — the gain is in wall-clock time, not total compute, and it buys that gain with more hardware — and notes that the asynchrony is trivial here precisely because random search draws independently, whereas methods that reuse past observations need extra machinery. Third comes multi-fidelity. A resource budget r is introduced on the observation that training error tends to fall as r grows while cost rises with it, which makes a short run a cheap preview of a long one. Successive halving exploits this: run many configurations for r_min epochs, keep only the top 1/η, multiply the survivors' budget by η, and repeat — so the same total spend covers far more candidates.
The turn: the chapter's own fix is diagnosed with the chapter's own diagnosis. The pivot is that successive halving reintroduces exactly the flaw parallelism had just removed. A rung cannot promote until every observation at that rung has arrived, so stragglers — configurations with more filters per layer training more slowly than lean ones — strand workers, as in the two-worker schedule where Worker-1 waits on the slow Trial-2; idling also appears whenever a rung's size is not a multiple of the worker count. ASHA is the resolution: promote a configuration as soon as η observations exist at a rung, without waiting for the rung to fill. The chapter is explicit that this is a trade and not a free improvement. Promotions made on η results are sometimes wrong, and the justification is probabilistic rather than guaranteed — rankings stay fairly consistent from rung to rung, and each rung grows more informative as it fills, so only the earliest, most sparsely-informed promotions are shaky. Notably, this is the same honesty the chapter applies to multi-fidelity generally: early rungs are treated as merely informative, not as reliable judges, since noisy learning curves mean low-budget rankings can mislead and a future winner can be discarded. The claim is that the damage is modest, not that it is absent.
The close: the method made operational. Having argued the trade, the chapter ends by cashing it out. ASHA's payoff is stated in the terms this chapter has been accumulating — zero idle synchronization — and the method is then run concretely in Syne Tune, parameterized by grace_period (the minimum budget r_min before any configuration may be judged) and reduction_factor (η, the fraction kept and the multiplier on survivors' budgets). The closing therefore lands where the opening's cost argument pointed: a search that is automated, parallel, budget-aware, and leaves no worker waiting.
Key claims, with the lines that support them
Tuning hyperparameters by hand is too slow to be practical and the results do not carry over to new tasks.
The author prices it out: one ResNet run on CIFAR-10 takes over two hours on an EC2 g4dn.xlarge instance, so merely trying ten configurations one after another burns about a day — and since good values shift from dataset to dataset and model to model, that day's work has to be repeated for the next problem. This cost is what motivates automating the search.
Because each evaluation is costly, gradient-free and noisy, HPO algorithms have to find good configurations from very few samples.
The author reasons that computing a gradient of validation error with respect to the hyperparameters would mean differentiating through the entire training run, and that the randomness of stochastic training makes every measurement noisy anyway; approximate hypergradient methods exist but are not yet competitive. Having ruled out gradients, only sample-efficient black-box search is left.
“Furthermore, the computational burden of evaluating \(f\) requires HPO algorithms to approach the global optimum with as few samples as possible.”
§19.1 What Is Hyperparameter Optimization?Read in context →
Random search is the right general-purpose baseline, yet it throws away budget because it never learns from what it has already seen.
The author shows it working on a single hyperparameter — tune the learning rate of softmax classification by sampling values and keeping whichever gave the lowest validation error — which is why it is simple and widely used, and better than grid search, whose fixed equally-spaced grid blows up with the number of dimensions. The flip side is that it never adapts its sampling distribution and spends the same full training budget on hopeless configurations as on promising ones.
“First, it does not adapt the sampling distribution based on the previous observations it collected so far.”
§19.1 What Is Hyperparameter Optimization?Read in context →
3 more claims
An HPO algorithm cannot be judged from a single run; each experiment must be repeated with different random seeds and reported as statistics.
The author's comparison runs random search and Bayesian optimization 50 times each with a different seed. The two curves are indistinguishable up to roughly 1000 seconds and only afterwards does Bayesian optimization pull ahead — a gap that any single noisy run could easily have shown backwards.
“Hence, when comparing different algorithms, it is crucial to run each experiment several times and report statistics, such as mean or median, across a population of multiple repetitions of an algorithm based on different seeds of the random number generator.”
§19.2 Hyperparameter Optimization APIRead in context →
Starting a new trial the moment a worker frees up removes synchronization idling and makes random search roughly as many times faster as there are parallel workers.
The author notes that configurations with more layers or filters simply take longer, so in a synchronous batch the fast trials sit waiting for the slow ones; dispatching asynchronously eliminates that wait. Because random search draws its samples independently, this is trivial to do — methods that reuse past observations need extra machinery. The author is explicit that the gain is in wall-clock time, not in total compute, and that it requires more hardware than the sequential setting.
Successive halving inherits exactly the same synchronization problem, and dropping the synchronization is worth the sloppier promotion decisions it causes.
The author explains that a rung cannot promote until every observation at that rung is in, so stragglers — e.g. configurations with more filters per layer training slower than lean ones — leave workers idle, as in the two-worker schedule where Worker-1 waits for the slow Trial-2; idling also appears whenever a rung's size is not a multiple of the worker count. ASHA's asynchronous promotions are occasionally wrong, but the author judges that in practice this does not hurt much and the gains outweigh it.
“In any distributed system, synchronization typically implies idle time for workers.”
§19.5 Asynchronous Successive HalvingRead in context →
How it works
The 3 mechanisms the chapter’s argument runs on.
Mechanism 1
Why training loss cannot pick settings
Hyperparameters are not learned during training, and minimizing training loss pushes every regularizer toward nothing: zero dropout or zero weight decay fits the training set better while generalizing worse. So the search must score each configuration on held-out validation error instead.
Mechanism 2
How cheap short runs buy more trials
Training error tends to fall as the budget r grows while cost rises with it, so a short run is a cheap preview. Successive halving runs many configurations for r_min epochs, keeps only the top 1/eta, and multiplies the survivors' budget by eta, so the same total spend covers far more candidates.
Mechanism 3
Why promoting on eta results is tolerable
ASHA promotes a configuration as soon as eta results exist at a rung instead of waiting for the full rung. Rankings stay fairly consistent from rung to rung and each rung grows more informative as it fills, so the early, sparsely-informed promotions are the only shaky ones and no worker ever idles.
Common misreadings
If a configuration reaches a lower training loss, it is the better configuration, so the search objective can just be training loss.
The objective has to be error on held-out validation data. Training loss is minimized by switching regularization off — set dropout or weight decay to zero and the training numbers improve while generalization degrades — so optimizing it would systematically select the wrong settings.
“Unfortunately, we cannot simply adjust these hyperparameters by minimizing the training loss, because this would lead to overfitting on the training data.”
§19.1 What Is Hyperparameter Optimization?Read in context →
Since weak trials get stopped early, early rungs must be reliable judges, and multi-fidelity methods can be trusted to never discard a configuration that would have won.
The author treats early evidence as merely informative, not reliable: learning curves are noisy, so rankings at low budgets can mislead, and ASHA's promotions made from as few as eta results are acknowledged to be sometimes suboptimal — the argument is that rankings are consistent enough and rungs become more informative as they fill, so the damage is modest rather than absent.
“Most of the configurations are stopped early and only the better performing configurations survive until \(r_{max”
§19.4 Multi-Fidelity Hyperparameter OptimizationRead in context →
Key concepts in Chapter 19
- Hyperparameters
- Settings the user must configure, such as learning rate, batch size, weight decay or layer count, that are not learned during training.
- Where it applies: They cannot be tuned by minimizing training loss, since that drives regularization toward zero.
- Hyperparameter optimization
- Automated search for hyperparameters framed as a global optimization problem, usually minimizing hold-out validation error.
- Where it applies: Each evaluation requires full training, so it is nested and expensive; gradients of the objective are not readily available.
- Configuration space
- The feasible set of hyperparameter values, each with a data type, bounded range and prior distribution to sample from.
- Where it applies: Too narrow and the optimum is excluded; too wide and the budget becomes infeasible; dependent hyperparameters are out of scope here.
- Random search
- Sampling configurations independently from the configuration space until a budget runs out and returning the best observed one.
- Where it applies: It ignores past observations and spends equal resources on every configuration, good and bad alike.
- Asynchronous random search
- Start a new trial the moment a worker frees up, instead of waiting for a whole batch to finish.
- Where it applies: Trivial for random search because samples are independent; methods using past observations need extra work.
- Multi-fidelity hyperparameter optimization
- Evaluate configurations at varying budgets r, spending full training only on the ones that look good.
- Where it applies: Assumes error decreases with r while cost increases, and that early curves are informative though noisy.
4 more concepts
- Successive halving
- Run N configurations for r_min epochs, keep the best 1/eta, retrain survivors eta times longer, repeat.
- Where it applies: With N = eta^K only one trial reaches the full budget r_max.
- Asynchronous successive halving (ASHA)
- A version of successive halving that promotes a configuration up a rung as soon as eta results exist there, so no worker waits for a full rung.
- Where it applies: Promotion decisions can be wrong early on, since rungs are sparsely populated at the start.
- Rung level synchronization
- Synchronous SH must gather every observation at a rung before promoting, which forces workers to wait on the slowest trial.
- Where it applies: Only a problem when training times vary or rung slots are not a multiple of worker count.
- Pause-and-resume scheduling
- Instead of stopping weak trials, each promoted trial restarts from scratch unless training state is checkpointed after every epoch.
- Where it applies: Efficient only with checkpointing; this chapter's ASHA run avoids it by stopping trials early.
Reader’s notes on Chapter 19AI reading companion
“hyperparameters are often set in a trial-and-error manner or sometimes left to their default values by practitioners, leading to suboptimal generalization”
Read in context →A quietly damning opening: the field's most common practice is named as guesswork. The whole chapter exists because defaults are a confession, not a choice.
“hyperparameter optimization is a nested one, where each iteration requires training and validating a machine learning model”
Read in context →This is the real cost center of the chapter, stated in one clause. Every clever trick later is just an attempt to cheat this nesting.
“we cannot simply adjust these hyperparameters by minimizing the training loss, because this would lead to overfitting”
Read in context →Neat: the reason HPO needs a separate objective is the same reason regularization exists. Dropout set to zero is the perfect illustration — the knob that helps generalization always hurts the training loss.
14 more notes
“Even just trying ten hyperparameter configurations in sequence, this would already take us roughly one day.”
Read in context →Concrete numbers do more persuading here than any theory. And note what the arithmetic implies: ten draws is a laughably thin sample of a continuous space, yet it already costs a day.
“none of the existing approaches are competitive with the state-of-the-art yet, and we will not discuss them here”
Read in context →Honest about a dead end — rare in a textbook. Differentiating through training is the obvious idea, and the exercises later make you feel exactly why it fails.
“we usually try to identify a small set of well performing hyperparameter configurations quickly, instead of hitting the global optima exactly”
Read in context →The goal quietly downgrades from argmin to "good enough, fast." Worth noticing that the noisy objective makes exact optimization not just expensive but meaningless.
“no algorithms can find something that is not included in the configuration space”
Read in context →The search space is itself a hyperparameter chosen by hand — so automation doesn't eliminate human judgment, it relocates it one level up.
“it is equally likely to sample a poorly performing configuration than a better performing configuration”
Read in context →The honest indictment of random search: memoryless. It never learns from the day of compute it just burned.
“Random search somewhat mitigates the curse of dimensionality (Bellman, 1966), and can be far more efficient than grid search”
Read in context →The underrated point: grid search wastes its budget resampling the same values of the hyperparameter that matters, while random search gives every dimension distinct values on every trial.
“the original FashionMNIST training set (60000 examples) for training, and the original test set (10000 examples) for validation”
Read in context →The chapter plants its own methodological sin in an exercise. Tuning on the test set is exactly the leak it warns about — teaching by deliberate bad example.
“it is crucial to run each experiment several times and report statistics”
Read in context →Two layers of randomness means a single HPO curve is nearly uninformative. Most papers' pretty comparison plots would not survive this paragraph.
“random search and Bayesian optimization perform roughly the same up to ~1000 seconds, but Bayesian optimization can make use of the past observation”
Read in context →The crossover is the whole story: modeling only pays once you've bought enough observations to model. On a small budget, sophistication buys nothing.
“After a few epochs we are already able to visually distinguish between well-performing and suboptimal configurations. However, the learning curves are noisy”
Read in context →The entire bet of multi-fidelity stated as a tension rather than a theorem: early signal is real but unreliable. Everything after is just how much you're willing to gamble on it.
“We assume that the error \(f(\mathbf{x}, r)\) decreases with \(r”
Read in context →Quietly assumed away overfitting. Plenty of configurations get worse with more epochs, and that's exactly where cheap proxies mislead you.
“only a single trial will be trained to the full budget \(r_{max”
Read in context →So the winner of a halving round is determined almost entirely at low fidelity — the full-budget run is a coronation, not a comparison.
“promote configurations to the next rung level as soon as we collected at least \(\eta\) observations”
Read in context →Two data points as a promotion committee. Brazen — and the justification is statistical patience: the rungs fill in later and quietly correct your early mistakes.
“rungs grow over time and reflect the distribution of metric values at this level better and better”
Read in context →The real argument for ASHA: the comparison threshold is a running estimate, so the algorithm gets more accurate as it goes. Errors are front-loaded and cheap.
A reader’s takeAI reading companion
Each hyperparameter technique leaves a bill that the next one must address
This chapter reads less like a tutorial on a technique and more like an honest accounting of what it costs to not guess. It opens by naming the field's default practice — trial and error, or just leaving the defaults — as a source of suboptimal generalization, and then spends the rest of its length showing why the obvious fix is expensive and the clever fixes are all compromises. The arc is tight: define HPO as a nested global optimization with validation error as the objective (nested, because every single evaluation means training a model end to end); establish random search as the baseline; discover that a baseline you can't measure reliably is no baseline, so run repeated seeds and report statistics; parallelize asynchronously to stop workers idling on stragglers; then, when parallelism turns out to buy wall-clock time but not compute, introduce a resource dimension r and start evaluating configurations cheaply — successive halving, then ASHA to remove the synchronization barriers that halving reintroduces. Each section exists because the previous one left a specific bill unpaid, which is rare structural honesty in a textbook.
What I saw through, reading it closely: nearly every advance in the chapter is purchased with a weakened guarantee, and the text mostly admits this rather than hiding it. The objective is downgraded early from argmin to 'a small set of well-performing configurations, quickly' — justified not only by cost but by noise, since an exactly optimal point in a stochastic objective is not a meaningful target. Random search's perfect linear speed-up under parallelism is a reward for being memoryless; it scales flawlessly precisely because it learns nothing, and the Bayesian-optimization comparison makes the complementary point — modeling only pays after you've bought enough observations to model with, so on small budgets sophistication is wasted money. Multi-fidelity is the biggest wager of all, and the chapter states it as a tension rather than a theorem: early learning curves separate good from bad configurations visibly, but they are noisy. The assumption that error decreases with r quietly assumes away overfitting, which is exactly the regime where cheap proxies mislead. Successive halving means the winner is essentially chosen at low fidelity and the full-budget run is a coronation rather than a comparison; ASHA goes further and lets two observations constitute a promotion committee. Its real defense is not that early decisions are correct but that they are cheap and front-loaded, while the rungs fill in over time and the comparison threshold becomes a better running estimate of the metric distribution — the algorithm self-corrects as it goes.
Continue reading
My sharpest judgement is about where human judgement actually went. Automation did not remove it; it relocated it one level up, into the configuration space, since no algorithm can find what the space does not contain. That also makes the chapter's own exercise — training on FashionMNIST's training set and validating on its test set — the most instructive moment in the text, a deliberate demonstration of the exact leak the chapter warns against. To the reader: take the arithmetic seriously (ten sequential configurations, roughly a day, and ten draws is a laughably thin sample of a continuous space), run every comparison with multiple seeds before believing any curve, and remember that the chapter's candour about gradient-based HPO not being competitive is the model for how to hold all of these methods — as cost-shaped bets with known failure modes, not as solutions.
Read Chapter 19 with these cards beside each passage.
Open in FeedLitraChapter 20: Generative Adversarial Networks
Does an equilibrium exist where the discriminator can no longer tell the two distributions apart?
How Chapter 20 unfoldsAI-assisted
Opening: a pivot from discrimination to generation. The chapter begins by looking back over the rest of the book, which has been about prediction — mapping data to labels, discriminating cats from dogs, regressing and classifying. It concedes how spectacularly well backpropagation-trained networks do this, then opens a door: machine learning can also aim at modeling the data itself, learning a distribution concisely enough that new samples can be drawn from it. Photorealistic synthesis is named as the goal that had, until recently, no good method. The bridge the text builds is historical and conceptual: discriminative nets had become so strong that people began repurposing them for problems that were not supervised at all (RNN language models are the cited precedent). That sets up the 2014 GAN idea as a specific instance of that trend — borrow the power of a classifier and use it as a training signal.
Development: the two-sample test made constructive, then formalized. The core intuition is framed statistically: a generator is good if no test can tell its samples from real ones, which is the classical two-sample test. The text's key claim is that GANs differ from statistics not in the idea but in its use — instead of merely reporting "these look different," the test's verdict is fed back as gradient to improve the generator. From there the exposition turns mechanical: the generator/discriminator pair, the competitive loop in which each adaptation provokes the other, then the mathematics. The discriminator is a binary classifier with sigmoid output minimizing cross-entropy; the generator maps latent noise $\mathbf z$ through $G$ and wants $D(G(\mathbf z))\approx 1$. Here the chapter makes an honest technical detour worth noting: the "natural" objective of maximizing $-\log(1-D(G(\mathbf z)))$ yields vanishing gradients, so practice substitutes minimizing $-\log D(G(\mathbf z))$ — the same forward pass with the label flipped to $y=1$. Only after that is the minimax objective stated as a summary. The theory then lands deliberately low: rather than images, the first demonstration is "the world's most inefficient estimator of parameters for a Gaussian" — linearly transformed 2D normal data, a single-linear-layer generator, a three-layer MLP discriminator, and the paired update_D/update_G functions whose only asymmetry is the label and the detach() that keeps the generator out of the discriminator's gradient.
The turn: from toy to photorealism. Section 20.2 announces the shift explicitly — the 2D Gaussian "got the point across" but is "not especially exciting" — and swaps in DCGAN on a Pokémon sprite dataset. The structure of the argument does not change; the substance of the two networks does. Convolutional machinery proven on discriminative vision is imported wholesale and run in reverse for the generator: G_block stacks transposed convolution, batch norm, and ReLU, with the arithmetic spelled out to show each block doubles spatial size, so four blocks plus a final layer carry a $1\times1\times100$ latent vector to $3\times64\times64$, with tanh matching the $[-1,1]$ range that the data normalization was chosen to produce. The discriminator is then presented as a literal mirror — D_block halving resolution at each step down to a single scalar — with one substantive change motivated on its own terms: leaky ReLU, defined piecewise and plotted across $\alpha$, introduced to cure the dying-ReLU problem so gradients keep flowing. Training changes only in two tuned details, both justified by the adversarial setting: a shared learning rate because the networks now resemble each other, and Adam's $\beta_1$ dropped from 0.9 to 0.5 to reduce momentum smoothing under rapidly shifting gradients.
Closing: a summary that stays architectural, and exercises that reopen the questions. The chapter ends without claiming a solved problem. Its summaries restate the min/max pair and catalog the DCGAN layer counts and design choices rather than evaluating sample quality, and it openly notes that the demonstration runs too few epochs for good results. The exercises then push back on exactly the places the text smoothed over: whether an equilibrium exists in which the generator truly wins on finite samples (the stability question the minimax formulation raises but does not answer), what breaks if plain ReLU replaces leaky ReLU (testing the one motivated deviation), and how DCGAN fares across Fashion-MNIST categories (probing whether the method generalizes evenly). The overall shape, then, is intuition → formalism with its practical correction → minimal toy verification → convolutional scale-up → deliberately unfinished close.
Key claims, with the lines that support them
GANs' real novelty is using the two-sample test constructively rather than just as a verdict.
Building on the previous point, the author contrasts statistics papers, which stop at announcing that two datasets look different, with GANs, which convert that same comparison into a training signal that keeps improving the generator until its samples resemble real data.
“To sum up, \(D\) and \(G\) are playing a “minimax” game with the comprehensive objective function:”
§20.1 Generative Adversarial NetworksRead in context →
The whole setup can be written as one minimax game over a single cross-entropy objective.
The author collapses the two separate updates into one expression in which the discriminator minimizes and the generator maximizes the expected cross-entropy taken over real data and over noise samples, making explicit that the two networks optimize the same quantity in opposite directions.
“To sum up, \(D\) and \(G\) are playing a “minimax” game with the comprehensive objective function:”
§20.1 Generative Adversarial NetworksRead in context →
In practice the generator's half of that clean objective must be replaced to make training work.
Immediately after stating the elegant minimax form, the author notes its weakness: a successful generator drives the original term's value near zero and its gradients near zero too, so one instead minimizes -log D(G(z)) by passing the fake sample in with the true-data label. The symmetry is sacrificed for usable gradients.
“If the generator does a perfect job, then \(D(\mathbf x')\approx 1\), so the above loss is near 0, which results in the gradients that are too small to make good progress for the discriminator.”
§20.1 Generative Adversarial NetworksRead in context →
1 more claim
Convolutional designs that proved themselves on recognition tasks can be turned around to synthesize images.
The author points out that discriminative nets had already been repurposed before (a character-prediction language model doubles as a text generator), then builds DCGAN by mirroring a standard convnet: four transposed-convolution blocks expand a 100-dimensional noise vector from 1x1 up to 32x32 while halving channels, a final transposed convolution reaches 3x64x64, and tanh squeezes outputs into (-1,1) to match the Pokemon images normalized the same way.
“We will borrow the convolutional architecture that have proven so successful for discriminative computer vision problems and show how via GANs, they can be leveraged to generate photorealistic images.”
§20.2 Deep Convolutional Generative Adversarial NetworksRead in context →
How it works
The 3 mechanisms the chapter’s argument runs on.
Mechanism 1
Competition turns judging into training
A discriminator is trained to label real data 1 and generated data 0, and its verdict becomes the generator's learning signal. Each time the generator learns to fool it, the discriminator re-adapts to the new fakes, and that sharper judgment is fed back to push the generator further, so the two improve by chasing each other.
Mechanism 2
Relabeling fakes to keep gradients alive
If the generator asks to maximize -log(1-D(G(z))), then once it succeeds and D(G(z)) is near 1 the loss sits near zero and the gradients shrink to almost nothing, stalling progress. The fix is to feed the generated sample to the discriminator but claim the label 1 and minimize -log D(G(z)), which pushes in the same direction while still producing a usable gradient.
Mechanism 3
Why a leaky negative slope helps
Plain ReLU has zero gradient wherever its input is negative, so a unit that keeps producing negative pre-activations receives no gradient and can never recover. Leaky ReLU passes a small fraction alpha of negative inputs instead, so gradient keeps flowing through such units and they can still move during training.
Common misreadings
Swapping the generator's objective from maximizing -log(1-D(G(z))) to minimizing -log D(G(z)) is just algebraic tidying, since both reward fooling the discriminator.
The two agree on direction but not on gradient magnitude: as the generator starts succeeding and D(G(z)) approaches 1, the first form flattens out to nearly zero value and nearly zero gradient, so learning stalls right when it should continue. Relabeling the fake sample as true and minimizing -log D(G(z)) keeps the gradient large in exactly that regime, which is why the author calls it the common choice.
“If the generator does a perfect job, then \(D(\mathbf x')\approx 1\), so the above loss is near 0, which results in the gradients that are too small to make good progress for the discriminator.”
§20.1 Generative Adversarial NetworksRead in context →
Since leaky ReLU helps by letting negative inputs through, a larger alpha should be strictly better.
The useful range is alpha strictly between 0 and 1: at alpha=0 the function is plain ReLU, and at alpha=1 it becomes the identity, a purely linear map with no nonlinearity left for the network to exploit. The default used in the discriminator blocks is a small leak of 0.2, enough to keep gradients flowing without giving up nonlinearity.
“leaky ReLU is a nonlinear function that give a non-zero output for a negative input.”
§20.2 Deep Convolutional Generative Adversarial NetworksRead in context →
Key concepts in Chapter 20
- Generative adversarial networks (GANs)
- Two networks trained against each other: one makes fake data, one judges it.
- Where it applies: Needs a discriminator strong enough to give useful signal; training is unstable because both sides move.
- generative modeling
- Learning a data distribution well enough to sample new examples that look like the training data.
- Where it applies: Unlike classification it needs no labels, but success is hard to score numerically.
- latent variable
- The random noise vector the generator transforms into a sample.
- Where it applies: Drawn from a fixed simple source such as a normal distribution, not learned.
- leaky ReLU
- A ReLU variant that leaks a small slope for negative inputs so gradients never fully die.
- Where it applies: Equals plain ReLU at alpha=0 and the identity at alpha=1; only alpha in (0,1) is useful.
0 more concepts
Reader’s notes on Chapter 20AI reading companion
“GANs rely on the idea that a data generator is good if we cannot tell fake data apart from real data”
Read in context →The whole field in one sentence — and note the quiet sleight of hand: "we" gets replaced by "a neural net of fixed capacity." Indistinguishable-to-a-CNN is not indistinguishable.
“rather than just training a model to say “hey, these two datasets do not look like they came from the same distribution”
Read in context →The real move: turning a test statistic into a gradient. Statistics asks whether; GANs ask which way to walk. Worth pausing on how rare that conversion is.
“If the generator does a perfect job, then \(D(\mathbf x')\approx 1\), so the above loss is near 0, which results in the gradients that are too small to make good progress for the discriminator.”
Read in context →This is garbled. The vanishing-gradient problem bites when the generator is bad (D≈0), not perfect, and it starves the generator, not the discriminator. The fix given is right; the justification printed here is backwards.
11 more notes
“min_D \max_G \{ -E_{x \sim \textrm{Data}} \log D(\mathbf x) - E_{z \sim \textrm{Noise}} \log(1 - D(G(\mathbf z”
Read in context →The min and max are swapped relative to Goodfellow's objective: D should maximize this quantity's negation, i.e. minimize the loss, while G maximizes it. Written as-is the roles are inverted — and min-max vs max-min is not a cosmetic ordering, it changes who gets the inner optimum.
“the world’s most inefficient estimator of parameters for a Gaussian”
Read in context →Honest and funny, and pedagogically the right choice: use a toy where you know the answer in closed form, so when the GAN wobbles you know it's the method, not the data.
“it literally only needs to learn the parameters to fake things perfectly”
Read in context →Rare luxury: the generator's hypothesis class exactly contains the truth. Every real GAN failure you'll ever debug lives outside this condition, so don't let the demo's success teach optimism.
“we will use an MLP with 3 layers to make things a bit more interesting”
Read in context →The asymmetry is the actual lesson, understated into a joke. A linear G against a nonlinear D — capacity mismatch is the dial GAN practitioners spend their lives turning.
“Recomputing `fake_Y` is needed since `net_D` is changed”
Read in context →Two comments, two opposite lessons: reuse fake_X (cheap, valid), recompute fake_Y (D moved). This is exactly where people silently break alternating optimization by caching one line too many.
“Does an equilibrium exist where the generator wins, i.e. the discriminator ends up unable to distinguish the two distributions on finite samples?”
Read in context →A sharper question than it looks. On finite samples, yes trivially — memorize the training set and D is helpless. Which reveals that this criterion cannot by itself distinguish generation from copying.
“4 + 2 \times (16-1)- 2 \times 1] \times [(4 + 2 \times (16-1)- 2 \times 1]\\ &= 32 \times 32”
Read in context →Arithmetic check: 4+30−2 = 32. ✓. But the formula is written in a needlessly baroque way — transposed conv output is just s(n−1)+k−2p; line one is that identity in disguise.
“the output will have its width and height increased by 3 respectively”
Read in context →"Increased by 3" — from 1×1 to 4×4, so technically true and maximally confusing. The honest statement is k−2p = 4, i.e. stride-1 unpadded transposed conv projects a point into a k×k patch.
“It decreases the smoothness of the momentum, the exponentially weighted moving average of past gradients, to take care of the rapid changing gradients because the generator and the discriminator fight”
Read in context →The best sentence in the DCGAN section. β₁=0.5 isn't a magic number from the paper — it's an admission that the loss landscape is non-stationary by construction, so long-memory momentum is averaging over an opponent who has already changed.
“The Discriminator is a 4-layer strided convolutions with batch normalization (except its input layer)”
Read in context →The summary claims the exception; the code doesn't implement it — the first D_block(n_D) carries a BatchNorm. DCGAN's paper explicitly omits BN on D's input layer. Summary and code disagree.
“What will happen if we use standard ReLU activation rather than leaky ReLU?”
Read in context →The interesting answer isn't "dying neurons" but the gradient path: D's gradient is the generator's only teacher. Zero out half of it and you're not slowing D down, you're cutting G's supervision signal.
A reader’s takeAI reading companion
Reframing statistical tests as gradients is brilliant, the mathematical exposition is careless
A chapter that teaches the idea beautifully and the mathematics carelessly. The conceptual spine is genuinely excellent: the reframing of a two-sample test as a differentiable training signal is one of the great moves in modern ML, and the authors convey it in a paragraph. The toy Gaussian is well-chosen pedagogy — closed-form truth, a generator whose hypothesis class exactly contains it, so every failure is attributable. And the β₁=0.5 explanation is the rare case where a book explains a hyperparameter rather than reciting it: momentum assumes stationarity, adversarial training destroys stationarity, so shorten the memory.
But the formal passages need an errata. The non-saturating-loss justification is stated backwards — vanishing gradients afflict a failing generator and starve G, not a perfect generator starving D — and the minimax objective has min and max attached to the wrong players. The DCGAN summary asserts no batch-norm on the discriminator's input layer while the code applies it. The transposed-convolution algebra is correct but written in a form that hides the simple identity s(n−1)+k−2p underneath. Two deeper omissions bothered me. First, the chapter never says what the adversarial game is actually minimizing — the Jensen–Shannon divergence at optimal D — so mode collapse, non-convergence, and the whole Wasserstein line of work have no place to attach; the reader leaves with a recipe and no diagnostic vocabulary.
Continue reading
Second, the lone exercise accidentally exposes the framework's soft spot: on finite samples a generator that memorizes the training set wins outright. The indistinguishability criterion cannot, by itself, tell generation from copying. That tension deserves the chapter's attention rather than its exercises.
Read Chapter 20 with these cards beside each passage.
Open in FeedLitraChapter 21: Recommender Systems
How does matrix factorization turn collaborative filtering into a trainable model?
How Chapter 21 unfoldsAI-assisted
Opening: the problem and the vocabulary. The chapter begins by framing recommender systems as information filters — tools that cut an overwhelming catalog down to what one person plausibly wants. The author argues the payoff runs both ways: users spend less effort searching, and businesses earn more, with Amazon, Netflix and YouTube offered as evidence that recommendation sits at the core of these services rather than decorating their edges. From there the chapter lays out its working vocabulary: collaborative filtering in its memory-based, model-based and hybrid forms, and the distinction between explicit feedback (a deliberate star rating) and implicit feedback (clicks, purchases, browsing history that accumulate for free). A key mechanical point is planted here. Memory-based CF measures similarity by counting items two users have in common, so on a sparse, enormous interaction matrix two users rarely overlap enough for that similarity to mean anything — which is precisely why model-based methods, learning compact latent factors instead of counting overlaps, came to dominate and why they extend naturally into neural networks. The author also concedes the price of implicit signals: having watched a movie does not mean the viewer liked it.
Development and first turn: from predicting ratings to ranking. Having established that most deployed systems run on implicit feedback, the chapter turns against the models it just introduced. Rating predictors such as matrix factorization and AutoRec simply discard user-item pairs with no observation, so they cannot distinguish an observed pair from an unobserved one — and because what is missing is not missing at random, the fitted model is biased for ranking purposes. The remedy is to optimize relative order rather than absolute scores. The chapter surveys pointwise, pairwise and listwise objectives, then settles on the pairwise family: hinge ranking loss pushing a sampled negative away from a positive by a safety margin, treated as interchangeable in spirit with Bayesian personalized ranking, since both attend only to the gap between a positive and a negative, which is what a ranked list actually requires. Listwise methods target ranking metrics more directly but are flagged as far more compute-hungry. This section is also where the chapter's standing warning lives: an absent interaction blends genuine dislike with items the user has simply never seen, so absence is not proof of a negative opinion — hence sampling negatives rather than assuming them. Architecturally, the development continues with NeuMF, which fuses a generalized matrix factorization branch with an MLP branch, and Caser, which treats the interaction history as a sequence so that short-term and long-term interests are modeled separately.
Second turn: the shift to feature-rich CTR prediction and factorization machines. The chapter then changes setting again, moving from user-item identifiers alone to click-through-rate prediction over rich categorical features. After a dataset wrapper for CTR data, it introduces factorization machines, and the argument for them is computational. Enumerating every feature pair costs time quadratic in the number of features; the author rewrites the interaction term as half of the squared sum of embedding-weighted features minus the sum of their squares, so a single pass suffices, and since only non-zero entries contribute, the cost drops to linear in feature count. That is the decisive property for advertising data, where one-hot encoded features are both high-dimensional and overwhelmingly zero. The author also shows FM absorbing familiar models: its first two terms are ordinary linear regression, and if one feature indexes a user and another an item, the interaction term is exactly the matrix-factorization dot product.
Closing: reversing the praise, and DeepFM. The chapter closes by turning on FM in the same way it earlier turned on rating prediction. FM's second-order bilinear form, however cheap, is too rigid for the complex nonlinear crossings that occur in real data. The obvious extension — third- or fourth-order FM counting triples and quadruples — is acknowledged as theoretically available but rejected in practice as numerically unstable and expensive. DeepFM is the chapter's answer instead: an MLP running in parallel with the FM block over one shared embedding table, their outputs summed before the sigmoid. Because gradients from both branches flow back into the same embeddings, the second-order crossings and the deep nonlinear combinations are fitted jointly rather than in two separate stages — which the author credits for the reported result that DeepFM, with a three-layer 30-20-10 MLP and FM's other hyperparameters held fixed, converged faster and scored better than FM on an online advertising dataset. A final note closes the arc: unlike Wide & Deep, DeepFM discovers feature combinations automatically, sparing the hand-crafted feature engineering that approach demands.
Key claims, with the lines that support them
Recommender systems pay off on both sides: users spend less effort finding things, and businesses earn more.
The author points to Amazon, Netflix and YouTube, where recommendation sits at the core of the service rather than at its edge, as proof that filtering an overwhelming catalog is commercially central and not a mere convenience feature.
“The benefits of employing recommender systems are two-folds: On the one hand, it can largely reduce users’ effort in finding items and alleviate the issue of information overload.”
§21.1 Overview of Recommender SystemsRead in context →
Most recommender systems are built on implicit feedback, which is plentiful even though it is noisy.
The author contrasts the two signal types: a star rating on IMDb requires the user to go out of their way, whereas clicks, purchases and browsing history accumulate for free from ordinary use. The stated price is unreliability — the author notes that having watched a movie does not actually mean the viewer liked it.
“As such, many recommender systems are centered on implicit feedback which indirectly reflects user’s opinion through observing user behavior.”
§21.1 Overview of Recommender SystemsRead in context →
Building on that shift to implicit signals, models trained to predict explicit ratings are the wrong tool for personalized ranking.
The author's reasoning is that matrix factorization and AutoRec simply drop the user-item pairs with no observation, so they cannot tell an observed pair from an unobserved one; since what is missing is not missing at random, the resulting model is biased for ranking purposes.
“Clearly, these models are incapable of distinguishing between observed and non-observed pairs and are usually not suitable for personalized ranking tasks.”
§21.5 Personalized Ranking for Recommender SystemsRead in context →
3 more claims
The fix is to optimize relative order instead of absolute scores, which is what pairwise objectives do.
The author shows hinge ranking loss pushing negative items away from positives by a safety margin, and treats it as interchangeable with Bayesian personalized ranking: both care only about the gap between a positive and a sampled negative, which is exactly what a ranked list needs. The stated trade-off is that listwise methods target ranking metrics even more directly but are far more compute-hungry.
“Similar to BPR, it aims to optimize for relevant distance between positive and negative samples instead of absolute outputs, making it well suited to recommender systems.”
§21.5 Personalized Ranking for Recommender SystemsRead in context →
Turning to feature-rich CTR prediction, factorization machines are attractive because their interaction term can be reorganized into linear-time form.
The author derives the rewritten pairwise term and notes that only non-zero elements need computing, dropping cost from quadratic to linear in the number of features — the decisive property for click prediction, where one-hot encoded ad features are both high-dimensional and mostly zero. The author also shows FM subsumes familiar models: its first two terms are plain linear regression, and if one feature indexes an item and another a user, the interaction term is precisely the matrix-factorization dot product.
“To solve this inefficiency problem, we can reorganize the third term of FM which could greatly reduce the computation cost, leading to a linear time complexity (\(\mathcal{O}(kd)”
§21.9 Factorization MachinesRead in context →
Reversing the earlier praise for FM, its bilinear second-order form is too rigid for real feature crossings, so a deep network is bolted on alongside it.
The author argues real-world crossings are complex and nonlinear, then reports a concrete comparison: DeepFM with a three-layer 30-20-10 MLP, holding FM's other hyperparameters fixed, converged faster and scored better than FM on an online advertising dataset. The author also notes higher-order FM is possible on paper but is avoided as numerically unstable and expensive, and that DeepFM's automatic discovery of combinations spares the hand-crafted feature work that Wide & Deep requires.
“Adding nonlinear transformation layers to factorization machines gives it the capability to model both low-order feature combinations and high-order feature combinations.”
§21.10 Deep Factorization MachinesRead in context →
How it works
The 3 mechanisms the chapter’s argument runs on.
Mechanism 1
Why memory-based CF fails on sparse data
Memory-based collaborative filtering scores similarity between users or items from the items they have in common, so when the interaction matrix is sparse and huge, two users rarely overlap enough for the similarity to mean anything. The author uses this to explain why model-based methods, which learn compact latent factors instead of counting overlaps, became dominant and extend naturally to neural nets.
Mechanism 2
How FM gets pairwise terms cheaply
Counting every feature pair directly costs time proportional to the squared number of features. The author rewrites the interaction term as half of the squared sum of embedding-weighted features minus the sum of their squares, so one pass suffices; since only non-zero entries contribute, cost falls to linear in feature count, which is what makes FM practical on high-dimensional sparse advertising data.
Mechanism 3
How DeepFM learns low and high order together
DeepFM places the FM block and an MLP side by side over one shared embedding table and adds their outputs before the sigmoid. Because the gradients from both branches flow into the same embeddings, the second-order crossings and the deep nonlinear combinations are fitted jointly rather than in two separate stages, which the author credits for its faster convergence.
Common misreadings
If a user never clicked or bought an item, that counts as evidence they dislike it, so treating those pairs as negatives is safe.
An absent interaction mixes genuine dislikes with items the user has simply not encountered yet, so absence is not proof of a negative opinion. This is why the author treats the dropped non-observed pairs in rating models as a bias problem — the data is missing not at random — and why ranking losses sample negatives rather than assume them.
“Non-observed user-item pairs are a mixture of real negative feedback (users are not interested in the items) and missing values (the user might interact with the items in the future).”
§21.5 Personalized Ranking for Recommender SystemsRead in context →
Since FM only captures pairs, the natural upgrade is a third- or fourth-order FM that counts triples and quadruples of features.
The author notes higher-degree FM is theoretically available but is not used in practice because it becomes numerically unstable and costly; the chapter's answer is instead to run a multilayer network in parallel over the same embeddings, letting the deep branch absorb high-order nonlinear combinations while FM keeps the second-order ones.
“Factorization machines (FM), proposed by Rendle (2010), is a supervised algorithm that can be used for classification, regression, and ranking tasks.”
§21.9 Factorization MachinesRead in context →
Key concepts in Chapter 21
- Recommender system
- A system that filters a huge catalog to surface items a given user is likely to prefer.
- Where it applies: Useful when item catalogs are large and user preference data exists; it supplements rather than fully replaces explicit search.
- Collaborative filtering
- Predicting one user's preferences by leveraging patterns across many users, agents, and data sources.
- Where it applies: In general it uses only user-item interaction data; content or context signals need other model types.
- Explicit feedback
- Preference signals users deliberately give, such as star ratings or thumbs up and down.
- Where it applies: Often scarce because many users will not rate products.
- Implicit feedback
- Preference inferred from observed behavior like clicks, purchases, browsing, or watches. Signals like clicks, buys and watches that reveal preference without an explicit rating.
- Where it applies: Inherently noisy: observed behavior does not reliably reveal true motives. Non-observed pairs mix true negatives with future interactions, so absence is not proof of dislike.
- Personalized ranking
- Training a model to order items for each user rather than predict absolute scores.
- Where it applies: Pairwise losses fit ranking well; listwise ones optimize metrics directly but cost far more compute.
- Bayesian personalized ranking loss
- A pairwise loss from a maximum posterior estimator assuming a user prefers observed items over unobserved ones.
- Where it applies: Needs sampled negatives; interchangeable with hinge loss for ranking.
7 more concepts
- NeuMF
- A model concatenating a generalized matrix factorization pathway and an MLP pathway to score user-item pairs.
- Where it applies: The MLP deliberately does not share embeddings with GMF, raising parameter count.
- Sequence-aware recommendation
- Using the time-ordered list of a user's past actions to predict the next item.
- Where it applies: Horizontal filters catch union-level patterns, vertical filters point-level ones; L bounds the history used.
- Click-through rate prediction
- Estimating how likely a displayed item or ad is to be clicked, using rich categorical features.
- Where it applies: Useful when interaction data alone is sparse or noisy; relies on side information quality.
- Factorization machines
- A model that adds learned pairwise feature interactions, via dot products of feature embeddings, on top of linear regression.
- Where it applies: Usually limited to degree two; higher orders are theoretically possible but numerically unstable.
- Feature engineering
- Hand-designing which feature combinations a model sees; FM reduces this by learning hidden interactions from data.
- Where it applies: Expert-designed interactions still help when they are easy to understand; most are hidden in data.
- Deep factorization machines
- FM and an MLP run in parallel over shared embeddings, with their outputs summed and passed through a sigmoid.
- Where it applies: Not the only way to merge deep nets with FM; nonlinear layers could instead sit over the interactions.
- One-hot encoding
- Each categorical field value is stored as the index of its one-hot entry, which is what the CTR dataset fields hold.
- Where it applies: Criteo has real-valued features, so the same wrapper needs code changes.
Reader’s notes on Chapter 21AI reading companion
“Recommender systems are replacements of search engines by reducing the efforts in proactive searches”
Read in context →Overstated — search answers a stated want, recommendation guesses an unstated one. They coexist; one doesn't replace the other. Textbook marketing voice leaking into technical prose.
“surprising users with offers they never searched for”
Read in context →Framed purely as delight. Not a word here about whose interest the surprise serves — the chapter's only stated goals are user experience and "incremental revenue," and it never asks when those diverge.
“people collaborate to help one another perform the filtering process”
Read in context →Lovely origin: collaboration was literal, humans helping humans. Modern CF keeps the word but the collaboration is now involuntary — your clicks filter for strangers who never agreed to help.
17 more notes
“A user watched a movie does not necessarily indicate a positive view of that movie.”
Read in context →The most honest sentence in the overview. The field pivoted to implicit feedback because it's cheap, then spent decades patching the noise it bought. Availability drove the method, not validity.
“These latent factors might measure obvious dimensions as mentioned in those examples or are completely uninterpretable.”
Read in context →Said in passing, but it's the whole bargain of latent models: the genre story is a teaching fiction, the math owes us no meaning. Refreshing that they don't pretend otherwise.
“As expected, it appears to be a normal distribution, with most ratings centered at 3-4.”
Read in context →It isn't normal — it's bounded, discrete, left-skewed, and the J-shape is a famous artifact of who bothers to rate. Calling it "as expected" skips the most interesting thing about rating data.
“ratings are not missing at random but because of users’ preferences”
Read in context →Here's the bias the earlier histogram comment walked right past, now load-bearing. Missing-not-at-random is the real reason MF/AutoRec are the wrong tool, deeper than "linear model."
“confirming the effectiveness of neural networks in the rating prediction task”
Read in context →One run on one 100K dataset, no variance, no tuned baseline — and the word is "confirming." The classic deep-learning-era overclaim; later replication work found tuned MF often matches these models.
“It assumes that the user prefers the positive item over all other non-observed items.”
Read in context →BPR's whole engine is an assumption the text just admitted is false — non-observed is a mixture of dislike and not-yet-seen. Useful fiction, but notice it's the same noise problem relabeled as a prior.
“These two losses are interchangeable for personalized ranking in recommendation.”
Read in context →Asserted twice in two paragraphs, never argued. BPR is a smooth log-sigmoid probability model; hinge truncates at a margin. They behave differently once the margin is satisfied — one keeps pushing, one stops caring.
“the MLP subnetwork does not share user and item embeddings with GMF”
Read in context →The quiet cost of this design: double the embedding parameters on data that's already sparse. Flexibility bought with the one resource recommender systems never have.
“buying both milk and butter together leads to higher probability of buying flour than just buying one of them”
Read in context →Finally a sentence with a kitchen in it. Union-level vs point-level pattern was abstract until baking appeared — and the example also smuggles in the real claim: order matters less than co-occurrence here.
“We can view the input matrix \(\mathbf{E}^{(u, t)}\) as an image”
Read in context →The whole Caser trick is this analogy, and it's shakier than it sounds — image pixels have spatial locality in both axes, embedding dimensions have none. That's exactly why vertical filters span all L rows and horizontal ones span all k columns: nobody dares convolve within the embedding axis.
“The real semantics of the features are undisclosed due to anonymization and privacy concern”
Read in context →A whole pedagogy built on 34 nameless columns. You can learn to fit this data but never to reason about it — which is, uncomfortably, the actual condition of industrial CTR work.
“Some feature interactions can be easily understood so they can be designed by experts. However, most other feature interactions are hidden in data”
Read in context →This is FM's real selling point, buried mid-paragraph: it isn't about accuracy, it's about firing the feature engineer. The economic argument, dressed as a modeling one.
“Nevertheless, the numerical stability might weaken the generalization.”
Read in context →Stated three times across two sections as the reason higher-order FM is abandoned, never once with a number or a mechanism. The field's standard way of saying "it didn't work and we moved on."
“it reduces the effort of hand-crafted feature engineering by identifying feature combinations automatically”
Read in context →The honest claim is narrower than it sounds: DeepFM automates the second-order crosses FM already handled, and hands the rest to an MLP that nobody can inspect. Wide & Deep's hand-crafted features were at least readable.
“These two components share the same inputs/embeddings and their outputs are summed up as the final prediction.”
Read in context →Shared embeddings is the real design decision here, quietly stated. It means the FM's gradient and the MLP's gradient fight over the same vectors — which is either elegant joint training or a tug-of-war, depending on your mood.
“Adding nonlinear transformation layers to factorization machines gives it the capability to model both low-order feature combinations and high-order feature combinations.”
Read in context →"Capability to model" is doing heavy lifting. A deep net has the capability to model almost anything; whether it finds high-order interactions from sparse click data is an empirical question the sentence sidesteps.
“We can also add nonlinear layers over the feature interactions”
Read in context →A one-line aside that opens a whole family of models (NFM, xDeepFM). Parallel vs. stacked composition is a genuine fork in the road, and the text waves at it on the way past.
A reader’s takeAI reading companion
The Field Keeps Renaming the Noise Instead of Solving It
The chapter arcs cleanly from framing to machinery: what recommenders are and why they matter, then explicit-rating models (MF, AutoRec), then the pivot to implicit feedback and ranking losses (BPR, hinge), then neural fusions (NeuMF), sequence models (Caser), and finally the feature-rich CTR line from FM to DeepFM. Read as one piece, two threads run underneath the whole thing and neither is ever named. The first is the noise bargain. The chapter states plainly, early on, that a watch is not an endorsement — and then builds every subsequent model on exactly that signal, because it is cheap and abundant.
BPR's core assumption that unobserved means dispreferred is the same noise problem relabeled as a prior; the missing-not-at-random remark later is the same problem again, now load-bearing enough to justify abandoning MF. The field didn't solve this; it kept renaming it and moving one layer up. The second thread is the quiet substitution of capability for evidence. Latent factors 'might be uninterpretable' — admitted and dropped. A single 100K run 'confirms' neural effectiveness. Higher-order FM fails for 'numerical stability' asserted three times without a number. DeepFM 'gives the capability to model high-order combinations' — which is true of any sufficiently deep net and says nothing about whether such combinations are found in sparse click data.
Continue reading
My sharpest judgement: FM and DeepFM's real selling point is economic, not statistical. They fire the feature engineer. That is a legitimate and large win, but the chapter dresses it as an accuracy argument, and later replication work has not been kind to the accuracy claims. Alongside that, the chapter is strikingly incurious about interests other than the platform's — 'surprising users' and 'incremental revenue' are presented as the same goal, and the question of when they diverge is never asked; neither is the fact that modern collaborative filtering inherited the word 'collaborate' from a setting where humans actually volunteered.
To the reader: use this chapter as a map of the architectures, which it draws well and implements cleanly, and distrust its verbs. Read 'confirming', 'interchangeable', 'reduces the effort', and 'gives the capability' as hypotheses, not results. Pay attention to the asides the text hurries past — the parallel-versus-stacked fork after DeepFM, the shared-embedding tug-of-war, the fact that nobody dares convolve within the embedding axis in Caser because the image analogy only half-holds. Those throwaway lines are where the actual design decisions live. And notice that you will learn to fit 34 anonymous columns without ever being able to reason about them — which the chapter presents as a data limitation, but is in fact an honest preview of the job.
Read Chapter 21 with these cards beside each passage.
Open in FeedLitraChapter 22: Appendix: Mathematics for Deep Learning
How does rank formalize how much a matrix compresses space?
How Chapter 22 unfoldsAI-assisted
The opening: a concession that turns into an argument. The appendix begins by admitting what readers may already suspect — you can do a great deal of deep learning without deep mathematics. But the concession is a setup. The author immediately names cases the practitioner meets anyway: you cannot say what entropy actually measures, or read a bits-per-character score, without the underlying formalism. The point is not that math is prerequisite to building models but that architectures, losses and metrics carry assumptions baked into them, and only the mathematics makes those assumptions visible — makes the model's own reports interpretable. From there the chapter previews its five movements (linear algebra, calculus, probability, statistics, information theory) and starts with the most concrete object available: a vector, read either as a point or as a direction. Dot products give angles, angles give cosine similarity, and the first real argument of the chapter arrives through an image dimmed to 10% brightness: by straight-line distance it is far from the original, but it sits at a zero angle from it. Where length carries no meaning, angle is the measurement that respects the invariance we want — a qualification the author is careful to state rather than let the example overreach.
Linear algebra develops toward a single question. Hyperplanes, linear transformations, linear dependence and rank follow, and rank is where the thread tightens: it counts the largest independent set of columns, and full rank is exactly the condition for invertibility. The determinant then re-describes the same fact geometrically. Because a matrix can only skew, rotate and scale the grid uniformly, the one way it can destroy information is by flattening space into fewer dimensions — and flattening sends the signed area of the unit square to zero. A vanishing determinant is therefore not a coincidence that accompanies non-invertibility; it is its signature, because the lost dimension cannot be recovered. Tensor contraction and Einstein notation give all of this a common notation, and eigendecomposition delivers the payoff: written as $W\Sigma W^{-1}$, a matrix reveals its own action. The toy model $A^N v$ makes that concrete — repeated multiplication becomes repeated multiplication of eigenvalues, so after many layers the largest eigenvalue dominates and fixes a stable stretching rate. Divide by it and random vector norms settle rather than exploding or vanishing. That is the chapter's first arrival at a practical concern: eigenvalues of random matrices are why weight initialization works the way it does.
Calculus repeats the same move — local linearity — and arrives at backpropagation. Zooming in makes a function look linear, which defines the derivative as a scaling factor and yields the sum, product and chain rules almost mechanically. The second derivative adds curvature; matching derivatives with polynomials gives quadratic approximation and then the Taylor series. Going multivariate produces partial derivatives and the gradient, and here the author argues for gradient descent rather than asserting it: write the change in loss along a direction as the gradient's length times the cosine of the angle between them, and the drop is largest precisely where the cosine hits $-1$ — the negative gradient. The chapter then turns the chain rule around. Keeping $\partial f$ in the numerator reorganizes the computation into one forward pass that records values and single-step partials and one backward sweep that reuses them to produce every gradient at once. The contrast is historical and sharp: finite differences need two loss evaluations per parameter, so a few thousand parameters would mean thousands of passes over the data — which is why the problem waited for backpropagation in 1986. Hessians close the section by collecting second derivatives into the best local quadratic, with the note that matrix derivatives often echo their single-variable forms.
The turn into probability comes through integration. Area under a curve, approximated by rectangles; the fundamental theorem converting area-finding into derivative-reversing; change of variables, signed areas, iterated integrals with Fubini and the Jacobian determinant — and that Jacobian is the hinge, because it is what lets integration become the language of densities. Continuous random variables get p.d.f.s integrating to one and c.d.f.s that read off probabilities directly, and the author uses the distinction to correct a natural error: a density is probability per unit length, not a probability. Any exact point has probability zero, since each extra digit of precision shrinks its chance; a density may exceed ten so long as it does so narrowly enough. Summary statistics follow, with a second argument made by example — earning ten dollars give or take one is nothing like ten give or take ten, and in the three-point example the mean holds still while the variance moves, so the mean simply cannot see spread. Chebyshev's inequality then makes the standard deviation interpretable for any distribution, and the author shows the bound is attained exactly at one parameter value: sharp in the worst case, which is why it tends to be loose for well-behaved data. Joint densities, marginalization and covariance extend the picture to correlated variables, and the Cauchy distribution closes the section with a caution: its density integrates to one, yet its variance diverges and its mean collapses to $\log\infty$. Not every distribution has those two numbers — and the reassurance offered is the narrow one, that ML models are usually built so such tails do not arise, not that they cannot.
Probability consolidates, then becomes practice. Covariance normalizes into the correlation coefficient, unit-free, bounded in $[-1,1]$, and readable as a cosine — which quietly reconnects to the chapter's opening geometry. Maximum likelihood arrives next: choose $\theta$ maximizing $P(X\mid\theta)$, but optimize the negative log-likelihood instead, for three stated reasons — a product of a billion probabilities near one half underflows machine precision while its logarithm sits comfortably in a 32-bit float; differentiating the product costs quadratic time while the log form needs $n$ divisions and $n-1$ additions; and the log form is what links the objective to information theory, a promise the chapter redeems at the end. A tour of the common distributions follows — discrete and continuous uniform, binomial, Poisson, Gaussian, each with mass or density, c.d.f., mean, variance and sampling code — unified by limits and then subsumed into the exponential family. Naive Bayes on MNIST turns all of it into a working classifier: training by counting, Laplace smoothing, a log-space fix for underflow, and an honest accounting of what the independence assumption costs.
Statistics and information theory close the arc. Estimators bring MSE, bias, variance and the bias–variance decomposition; hypothesis testing brings significance, power, sample size, test statistics, $p$-values, one- versus two-sided tests and a five-step procedure; confidence intervals get a definition, the correct frequentist reading, three named fallacies and the Gaussian/$t$ formula for 95%. Then information theory, which is where the chapter has been heading since the negative log-likelihood: joint and conditional entropy, mutual information with its pointwise form and properties, KL divergence and its asymmetry, and finally cross-entropy as the multi-class objective — shown to be equivalent to maximum likelihood, which closes the loop on the earlier promise. The exercises enforce exactly that reading: convert a language model's word perplexity into bits of randomness per character, justify $I(X,Y) = H(X) - H(X\mid Y)$ both intuitively and as an expectation over the joint, and derive the KL divergence between two Gaussians. The chapter ends where the practitioner's daily loss function lives, having spent fifty pages earning the right to interpret it.
Key claims, with the lines that support them
Even a hands-on practitioner needs mathematics, because the choices baked into architectures, losses and metrics carry hidden assumptions that only math exposes.
The author opens by naming concrete cases a practitioner meets anyway: you cannot tell what entropy actually measures, or read a bits-per-character score, without the underlying mathematics, so the formalism is what makes the model's own reports interpretable.
“In practice, you will sometimes need to understand how architectural choices influence gradient flow, or the implicit assumptions you make by training with a certain loss function.”
Chapter 22. Appendix: Mathematics for Deep LearningRead in context →
When the length of a data vector carries no meaning, angles rather than distances capture the scale invariance we want from representations.
A copy of an image dimmed to 10% brightness sits far away if you measure straight-line distance, yet forms a zero angle with the original, so the angle treats the darker picture as the same thing. The author notes this only holds where length genuinely carries no information.
“The angle considers the darker image identical.”
§22.1 Geometry and Linear Algebraic OperationsRead in context →
Having set up derivatives as local scaling factors, the author argues that the steepest way downhill is the negative gradient, which is precisely what justifies the gradient descent update.
Writing the change in the loss along a chosen direction as the gradient's length times the cosine of the angle between them shows the drop is largest exactly when the direction points opposite the gradient, since that is where the cosine reaches minus one.
“This brings us to one of the most important mathematical concepts in machine learning: the direction of steepest decent points in the direction of \(-\nabla_{\mathbf{w}}L(\mathbf{w”
§22.4 Multivariable CalculusRead in context →
3 more claims
Hand-computed finite differences were never a viable way to train networks, and the problem was only solved by backpropagation in 1986.
Estimating a derivative by differences requires evaluating the loss twice per parameter, so even a few thousand parameters would demand thousands of sweeps through the whole dataset — a cost the author contrasts with the two passes backpropagation needs.
“It was not solved until 1986 that the backpropagation algorithm introduced in Rumelhart et al. (1988) provided a way to calculate how any change of the weights together would change the loss in the same computation time as a single prediction of the network over the dataset.”
§22.3 Single Variable CalculusRead in context →
A mean by itself does not describe a random quantity; spread must be reported too, and the standard deviation is interpretable because Chebyshev's inequality turns it into a universal guarantee.
Earning ten dollars give or take one is nothing like earning ten give or take ten, and in the author's three-point example the mean stays fixed while the variance moves with the parameter, so the mean cannot see spread at all. Chebyshev then bounds how often samples stray beyond a multiple of the standard deviation for any distribution, and the author shows the bound is exactly attained at one parameter value — meaning it is sharp in the worst case, hence often loose for tame distributions.
“Making a profit of \(\$10 \pm \$1\) per sale is very different from making \(\$10 \pm \$15\) per sale despite having the same average value.”
§22.6 Random VariablesRead in context →
Having established maximum likelihood, the author recommends optimizing the negative logarithm of the likelihood instead of the likelihood itself.
Three reasons are given: a product of a billion probabilities near one half underflows machine precision while its logarithm fits comfortably in a 32-bit float; differentiating the product directly costs quadratic time whereas the log form needs only n divisions and n-1 additions; and the log form connects the objective to information theory.
“Often people work with the negative log-likelihood instead for a variety of reasons: numerical stability, conversion of products to sums (and the resulting simplification of gradient computations), and theoretical ties to information theory.”
§22.7 Maximum LikelihoodRead in context →
How it works
The 3 mechanisms the chapter’s argument runs on.
Mechanism 1
Why zero determinant means no inverse
A matrix can only skew, rotate and scale the entire grid uniformly, so the only way it can lose information is by flattening space into fewer dimensions. Flattening drives the signed area of the unit square to zero, and that lost dimension can never be recovered, so a zero determinant is exactly the signature of a non-invertible map.
Mechanism 2
Largest eigenvalue sets the growth rate
Writing a matrix as its eigendecomposition turns repeated multiplication into repeated multiplication of eigenvalues alone, so after many layers the biggest eigenvalue dominates and fixes a stable stretching ratio. Dividing the matrix by that value makes random vector norms settle instead of exploding or vanishing, which is why eigenvalues govern initialization.
Mechanism 3
How backpropagation gets all gradients in two passes
Fully expanding a composed function repeats the same subterms over and over, so derivatives must be taken stepwise. Reordering the chain rule so the loss stays in the numerator lets one forward pass record values and single-step partial derivatives, after which a single backward sweep reuses them to deliver the derivative with respect to every input at once.
Common misreadings
A density value at a point tells you the probability of that value, so a density above 1 must be a mistake.
A density is probability per unit of length, and only its integral over an interval is a probability — for a continuous quantity any exact point has probability zero, since each extra digit of precision shrinks the chance further. A density may exceed ten as long as it does so over a narrow enough region, which is why the author points to the cumulative distribution function as the object that reads off probabilities directly.
“What this means is that in essence each additional digit of accuracy we require should decrease probability of matching by a factor of \(10”
§22.6 Random VariablesRead in context →
Every probability distribution has a mean and a variance, so you can always summarize one with those two numbers.
Some perfectly legitimate distributions have neither. The Cauchy density integrates to one, yet its variance integral diverges and its mean reduces to the logarithm of infinity, so both quantities simply fail to exist. The author's reassurance is narrower than it looks: machine learning models are usually built so such heavy tails do not arise, not that they cannot.
“Machine learning scientists define their models so that we most often do not need to deal with these issues, and will in the vast majority of cases deal with random variables with well-defined means and variances.”
§22.6 Random VariablesRead in context →
Key concepts in Chapter 22
- Dot product
- Sum of elementwise products of two vectors; its value also encodes the angle between them.
- Where it applies: Angle formula needs nonzero norms; dimension-independent.
- Cosine similarity
- The normalized dot product, measuring direction agreement while ignoring vector length.
- Where it applies: In high dimensions random vectors have cosine near 0; it discards magnitude information.
- Hyperplane
- A flat d-1 dimensional surface that cuts a d-dimensional space into two half-spaces.
- Where it applies: Only linear separation; nonlinear boundaries need an embedding first.
- Linear dependence
- Some nonzero weighted combination of the vectors equals zero, so one is redundant.
- Where it applies: Dependence in a matrix's columns signals irreversible compression of space.
- Rank of a matrix
- The size of the largest group of columns that are linearly independent.
- Where it applies: Defined by checking subsets, which is exponential in the number of columns, so it is a definition rather than a practical algorithm.
- Inverse matrix
- A second matrix that exactly undoes what the first one did to the data.
- Where it applies: Exists only for full-rank square matrices, and even then is usually avoided numerically.
49 more concepts
- Determinant
- The signed factor by which a matrix scales areas or volumes.
- Where it applies: Can be negative when the figure is flipped, and is laborious to compute for large matrices.
- Tensor contraction
- Summing a product of tensors over chosen shared indices, generalizing matrix multiplication.
- Where it applies: Needs the summed indices specified explicitly; no single universal choice exists for tensors.
- Eigendecomposition
- Writing a matrix as stretching along special directions that it does not rotate.
- Where it applies: Requires a full set of linearly independent eigenvectors; guaranteed for symmetric matrices.
- Principal eigenvalue
- The eigenvalue with the largest magnitude; its eigenvector is the direction a repeatedly multiplied random vector ends up pointing in.
- Where it applies: Applies to repeated application of one fixed matrix on a generic random vector, ignoring non-linearity.
- Power iteration
- Repeatedly multiplying a vector by a matrix to converge on its largest eigenvalue and eigenvector.
- Where it applies: Needs the starting vector to have some component along the principal eigenvector.
- Linear approximation
- Near a point, a function behaves like a straight line through it with slope equal to the derivative.
- Where it applies: Only valid in a small enough range and for familiar, differentiable functions.
- Chain rule
- The derivative of a composition multiplies the outer derivative at the inner value by the inner derivative. To get a derivative through composed functions, multiply along each path and add up all paths. Derivatives multiply along a computation path; the order you nest them decides which partials you get cheaply.
- Where it applies: Here justified only up to higher order terms in epsilon. Naive expansion repeats work; backpropagation reuses single-step partials. Keeping ∂w in the denominator gives one input's effect; keeping ∂f in the numerator gives all inputs at once.
- Higher-order term
- A term carrying epsilon squared or more; negligible as epsilon shrinks to zero.
- Where it applies: Can be ignored for first derivatives but matters for later expansions.
- Taylor series
- A polynomial built from a function's derivatives at one point that approximates the function near that point.
- Where it applies: Reproduces the function exactly in the infinite limit only for well behaved (real analytic) functions.
- Gradient
- The vector of all partial derivatives, telling how a multivariable function changes under any small input nudge.
- Where it applies: Only valid for small perturbations; higher order cross terms are discarded.
- Backpropagation
- Computing derivatives from the output back to the inputs, in a forward pass plus a backward pass.
- Where it applies: It is a bookkeeping order for the chain rule, not a new differentiation rule.
- Hessian
- The matrix of all second partial derivatives of a multi-variable function.
- Where it applies: Has n^2 entries, but mixed partials are symmetric when they exist and are continuous.
- Denominator layout matrix derivative
- Arranging partial derivatives into the same shape as the thing in the denominator.
- Where it applies: This shape convention is why transposes appear in matrix derivative results.
- Fundamental theorem of calculus
- The derivative of the running area function equals the integrated function, so integrating means reversing a derivative.
- Where it applies: Fixes F only up to an additive constant, which cancels for definite integrals.
- Change of variables
- Substituting a new variable rescales the integrand by how much the substitution stretches the axis.
- Where it applies: In n dimensions needs an injective reparametrization and the absolute Jacobian determinant.
- Signed area
- Areas carry a sign: negative integrand or right-to-left limits give negative values.
- Where it applies: Two flips cancel back to a positive area.
- Fubini's Theorem
- A double integral can be computed by iterating one-variable integrals in either order.
- Where it applies: Not always true; fails for some non-continuous-enough functions, though safe for machine learning's continuous functions.
- Probability density function
- A nonnegative function whose value times a tiny interval width gives the probability of landing in that interval. A non-negative function whose total integral is one; you integrate it over an interval to get a probability, so its own values are not probabilities.
- Where it applies: Must integrate to one over the real line; point probabilities are zero. Only for continuous random variables; density values may exceed 1 and carry no direct probability meaning.
- Jacobian
- The matrix of partial derivatives giving the best linear approximation of a multivariable map.
- Where it applies: Its determinant's absolute value is the local volume-scaling factor.
- Cumulative distribution function
- F(x) is the probability the variable is at most x, so it is itself a probability and works for discrete, continuous and mixed variables alike.
- Where it applies: Continuous without jumps only when the variable is continuous; discrete variables give step functions.
- Variance
- The average squared distance from the mean, measuring how widely a variable fluctuates; its units are the squared original units.
- Where it applies: Zero only for constants; undefined for heavy-tailed variables like the Cauchy distribution.
- Standard deviation
- The square root of the variance, restoring the original units so it describes the typical range of variation.
- Where it applies: Interpretable as a range via Chebyshev's inequality, which is loose but sharp in the worst case.
- Joint density function
- A function p(x,y) whose integral over a region gives the probability the pair lands there, letting correlated variables be modeled together.
- Where it applies: Needs multiple integrals; extends to p(x_1,...,x_n) with the same non-negativity and unit-integral rules.
- Marginal distribution
- The distribution of one variable alone, obtained by integrating the joint density over the variables you do not care about.
- Where it applies: Discards all information about correlation with the integrated-out variables.
- Covariance
- A summary statistic for how much two variables fluctuate together: positive when they rise together, negative when they move oppositely, zero when unrelated. A measure of how two random variables move together; it carries the product of their units.
- Where it applies: Captures only linear relationships; can be zero even when one variable is a deterministic function of the other. Independence implies zero covariance, but zero covariance does not imply independence; units make it hard to interpret.
- Correlation coefficient
- Covariance divided by both standard deviations, giving a unit-free number between -1 and 1.
- Where it applies: Captures direction and strength of linear relation only, not scale or nonlinear dependence.
- Maximum likelihood
- Choose the parameters under which the observed data had the highest probability.
- Where it applies: Equivalent to the Bayesian posterior mode only under an uninformative prior.
- Negative log-likelihood
- Minus the log of the likelihood, used as a loss to be minimized.
- Where it applies: Same optimum as likelihood because log is increasing; preferred for numerics, calculus, and information theory.
- Entropy
- The average negative log probability, measuring randomness of a source. A measure of how much information or randomness a signal carries; it is maximal when outcomes are spread evenly. The average randomness, here measured as bits per character observed from a model's predictions.
- Where it applies: Links NLL to information theory; average NLL over a dataset is a relative of entropy. For continuous variables the story needs a bounded support before uniform becomes the maximum-entropy choice. In these exercises entropy is read off a perplexity number rather than from a known distribution.
- Bernoulli
- The simplest random variable: 1 with probability p, 0 with probability 1-p.
- Where it applies: Mean p and variance p(1-p); the building block for coin-flip style models.
- Poisson random variable
- The limit you get when you chop one time window into infinitely many tiny Bernoulli trials; it counts rare arrivals, with mean and variance both equal to the rate.
- Where it applies: Needs the arrival probability to shrink as the subdivisions grow; otherwise the binomial does not stabilize.
- Gaussian distribution
- The limit of a standardized sum of many independent pieces; also the most random (maximum entropy) distribution once mean and variance are fixed.
- Where it applies: Requires extra conditions such as a finite fourth moment, and its c.d.f. has no closed form in elementary functions.
- Exponential family
- A template where a base measure is reweighted by an exponential of natural parameters dotted with sufficient statistics, normalized by a cumulant function.
- Where it applies: What matters is only that the density can be written in this form; the exact split into terms is somewhat arbitrary.
- Conditional independence of tests
- Naive Bayes assumes each pixel is independent of the others once the digit label is known, collapsing a product chain into simple per-feature factors.
- Where it applies: The assumption is usually false in real images, but it buys inductive bias and tractability.
- Central limit theorem
- Subtract the mean and divide by the standard deviation of a large sum of i.i.d. variables, and the result looks Gaussian regardless of the original distribution.
- Where it applies: Applies to sums of many small independent contributions, with moment conditions attached.
- Laplace Smoothing
- Add pseudo counts so never-observed pixel values do not force a zero probability.
- Where it applies: Here the +1/+2 form fits binary pixels; the Bayesian justification is a Beta-binomial model.
- Numerical overflow and underflow in softmax
- Multiplying hundreds of small probabilities rounds to zero on a computer; summing logarithms avoids it.
- Where it applies: Works because the logarithm is increasing, so the argmax is unchanged.
- Estimator and consistency
- A function of samples used to guess the population's true parameter.
- Where it applies: Assumed here to target a scalar true parameter theta.
- Bias-variance trade-off
- MSE splits into squared bias, variance, and irreducible error.
- Where it applies: High bias means underfitting; high variance means overfitting; the last term is noise in theta itself.
- Hypothesis test
- A procedure weighing evidence against a default statement about a population. The chance a test detects a real difference of at least some size, equal to 1 minus the type II error rate.
- Where it applies: Significance controls false rejection of a true H0; power controls failure to reject a false H0. Only meaningful relative to a stated effect size and significance level.
- Test statistic
- A single number summarizing the sample so different distributions can be told apart.
- Where it applies: Different choices give tests with very different power.
- Confidence interval
- A sample-computed random interval that covers the true parameter with at least probability 1 minus alpha.
- Where it applies: The randomness lies in the interval, not in the fixed parameter.
- Joint entropy
- Total randomness in a pair of variables taken together.
- Where it applies: Bounded below by either single entropy and above by their sum; equals the sum only under independence.
- Conditional entropy
- How much information remains in Y once X is already known.
- Where it applies: It is a difference of entropies, not a probability, so it can be zero while Y is still random unconditionally.
- Mutual information
- The information shared by two variables, beyond linear correlation.
- Where it applies: Symmetric and non-negative; zero exactly under independence, and equal to full entropy when one variable is an invertible function of the other.
- Pointwise mutual information
- How much more or less likely a specific pair of outcomes is than if the variables were independent.
- Where it applies: It is per-outcome, so it can be large while the average mutual information stays small.
- Kullback–Leibler divergence
- A measure of how far an estimated distribution sits from the true one.
- Where it applies: Not a distance: it is non-symmetric and becomes infinite when q assigns zero mass where p does not.
- Cross-entropy loss
- The expected surprisal of the true distribution under the estimated one; the standard classification loss.
- Where it applies: Equivalence with minimizing KL divergence holds only as long as the true data entropy H(P) is constant.
- Character perplexity
- The inverse geometric mean of the per-character probabilities a model assigns inside a word.
- Where it applies: Defined here per word of length l; converting it to bits per character needs the word length, e.g. the stated 4.5 letters.
Reader’s notes on Chapter 22AI reading companion
“But, we are not quite there yet.”
Read in context →A five-word paragraph doing all the rhetorical work — the preceding comfort was a setup, and this line pulls the chair away. Honest about the field's half-maturity.
“we can start considering tasks abstractly as collections of points in space and picturing the task as discovering how to separate two distinct clusters of points”
Read in context →This is the whole ideological move of ML stated in one breath: cats and dogs dissolve into point clouds. Enormously powerful, and also exactly where the semantics get lost.
“However, if we consider the angle, it is not hard to see that for any vector \(\mathbf{v}\), the angle between \(\mathbf{v}\) and \(0.1\cdot\mathbf{v}\) is zero.”
Read in context →Good motivation: the metric should encode the invariance you believe in. But note the direction of fit — we chose angle because we already knew brightness shouldn't matter. The math doesn't discover invariance, it ratifies it.
17 more notes
“Note that if the components of high-dimensional vectors are sampled randomly with mean \(0\), their cosine will nearly always be close to \(0”
Read in context →Dropped as a footnote, but it's the most consequential sentence in the section: in high dimensions everything is almost orthogonal, so a cosine of 0.3 may be remarkable rather than weak. Concentration of measure smuggled in parenthetically.
“In this case, I simply eyeballed a threshold that looked good on the training data by hand.”
Read in context →The sudden first person is charming, and the honesty is the pedagogy — a mean-difference vector plus a guessed threshold gets respectable accuracy, which quietly says how much of the problem is already linear.
“Matrices are incapable of distorting some parts of space differently than others.”
Read in context →The cleanest statement of linearity's limit I've read, and it explains the entire existence of activation functions. Deep nets are stacks of things that can't bend space, glued by things that can.
“was it \([1,1]^\top\) or \([0, -1]^\top”
Read in context →Information destruction made concrete by a question nobody can answer. Rank, invertibility, and determinant all follow from this one irretrievable fact.
“It requires looking at every subset of the columns of our given matrix, and thus is potentially exponential in the number of columns.”
Read in context →A definition that's mathematically clean and computationally absurd — worth noticing that the book admits the gap instead of papering over it. Definition and algorithm are different animals.
“so can inversion of a matrix which is close to having low rank”
Read in context →The crucial correction to everything above: rank is binary in theory but continuous in floating point. "Nearly dependent" columns are the real-world case, and they punish you quietly.
“the inverse will typically have almost every entry non-negative, requiring us to store all \(1\textrm{M}^2\) entries”
Read in context →"non-negative" is a typo for "non-zero" — the whole point is density, not sign. Small slip, but it muddies the one sentence carrying the argument.
“generally avoiding inversion in practice is a good rule of thumb”
Read in context →The most practically useful line in the section, and it's delivered as a throwaway. Solve the system, don't build the inverse.
“torch.det(torch.tensor([[1, -1], [2, 3]], dtype=torch.float32))”
Read in context →The code silently transposes the matrix from the prose. Determinant survives transposition, so the check passes and nobody notices — a lucky invariant covering sloppiness.
“we can decompose that figure into a collection of little squares so that the area of the figure is in essence just the number of squares”
Read in context →"Thinking like computer scientists" is a nice dodge — this is the Riemann integral, and the hand-wave is exactly where the real proof lives.
“there is no one case of what to sum over that can be universally chosen”
Read in context →This is the honest reason einsum exists: matrices had a canonical contraction, tensors don't, so the notation must carry the choice.
“the sum is over exactly those indices that occur more than once in the expression”
Read in context →Stated as observation, but it's a convention with teeth — it's false for v_i v_i if you meant no sum, and einsum's arrow syntax exists precisely because the rule underdetermines intent.
“PyTorch does not support this type of notation.”
Read in context →A comment where a code cell should be, then "Either notation allows..." — the text promises two options the framework can't deliver. Multi-framework source bleeding through.
“mathbf{A} - \lambda \mathbf{I})\) must compress some direction down to zero, hence it is not invertible”
Read in context →Here the geometric determinant work earns its keep: the characteristic equation isn't an algebraic trick, it's "this map must flatten something."
“0 = (2-\lambda)(3-\lambda)-2 = (4-\lambda)(1-\lambda”
Read in context →Check: (2−λ)(3−λ)−2 = λ²−5λ+4 = (4−λ)(1−λ). Signs work out because the two sign flips cancel. Fine, but the reader who verifies the naive way gets briefly spooked.
“whatever stretching \(\mathbf{W}\) does, \(W^{-1}\) undoes it, so in the end the only stretching that happens is by multiplication by the diagonal matrix”
Read in context →The cleanest argument in the chapter — det as a volume factor makes det(W)det(W⁻¹)=1 almost wordless.
“the rank is the same as the number of non-zero eigenvalues of \(\mathbf{A”
Read in context →Only true for diagonalizable matrices, which the section has just finished admitting isn't always the case. The [[1,1],[0,1]] example two paragraphs later quietly refutes the general reading.
A reader’s takeAI reading companion
The appendix is what the book was quietly leaning on
This appendix is the chapter the rest of the book was quietly leaning on, and reading it end to end feels like being shown the scaffolding after the building is already occupied. It opens with a promise and then withdraws it — deep learning can be practiced without much mathematics, but gradient flow, loss assumptions and entropy cannot be understood without it, and the five-word paragraph 'But, we are not quite there yet' does more honest work than pages of hedging. That sentence sets the register for everything after: a tour that is genuinely useful, occasionally sloppy, and most interesting exactly where it admits its own limits.
The arc is well chosen. Linear algebra comes first, and comes geometrically: vectors as points or directions, dot products as angles, cosine similarity, hyperplanes as decision boundaries. The ideological move of the whole field is stated in a single breath — tasks become collections of points and learning becomes separating clusters — which is enormously powerful and also precisely where the semantics of 'cat' and 'dog' evaporate. Watch the direction of fit in the brightness example: we reach for angle because we already believed scale shouldn't matter. The mathematics does not discover the invariance, it ratifies a choice we made first. And the most consequential sentence in the section is dropped parenthetically — random high-dimensional vectors are almost always nearly orthogonal — so a cosine of 0.3 may be striking rather than weak. Concentration of measure, smuggled in as a footnote. The hand-eyeballed threshold on MNIST is charming in its first person and devastating in its implication: a mean-difference vector plus a guess gets respectable accuracy, which tells you how much of the problem was already linear.
Continue reading
From there the thread is tight: linear transformations cannot distort some parts of space differently than others — the cleanest statement of linearity's limit in the book, and the entire justification for activation functions. Deep networks are stacks of things that cannot bend space, glued together by things that can. Information destruction made concrete ('was it [1,1] or [0,−1]?') generates rank, invertibility and determinant in one stroke, and the determinant-as-volume reading later pays for itself twice over: det(W)det(W⁻¹)=1 becomes almost wordless, and the characteristic equation stops being an algebraic trick and becomes 'this map must flatten something.' The numerical asides are the best practical content here — rank is binary in theory and continuous in floating point, nearly-dependent columns punish you quietly, the inverse of a sparse matrix is dense, and 'avoid inversion in practice' arrives as a throwaway when it should be a boxed rule. Solve the system; don't build the inverse. The eigenvalue payoff — repeated multiplication growing at the rate of the largest eigenvalue, rescaling to stabilize, random matrices connecting to initialization — is where abstraction finally cashes out in something you would actually change in your code.
The calculus half rests on one idea repeated at every scale: zoom in and everything looks linear. Derivative as a scaling factor, second derivative as curvature, Taylor series as matching derivatives with polynomials, gradient as steepest ascent, Hessian as the best local quadratic — and then the genuinely illuminating reframe, that backpropagation is nothing but writing the chain rule with ∂f kept in the numerator so one forward pass of local partials and one backward sweep yields every gradient. That is the single best explanatory moment in the appendix. Integration then runs the same move in reverse: rectangles under a curve, the fundamental theorem converting area-finding into derivative-reversing, change of variables and the Jacobian determinant tying back to the volume-scaling story from the first section. The chapter is more architecturally coherent than it looks.
Probability and statistics are handled with unusual candour. Densities and c.d.f.'s, mean and variance made interpretable by Chebyshev, marginalization by integrating out, covariance normalized into a correlation coefficient that is readable as a cosine — the geometry returning, deliberately. The Cauchy distribution is included precisely to break the comfortable assumption that summary statistics always exist. Maximum likelihood is motivated well and then immediately reframed through the negative log-likelihood for numerical stability and linear-time gradients, which is the version you will actually implement. The distribution catalogue is reference material, but the exponential-family unification at the end turns a list into a structure. Naive Bayes is the honest set piece: counting, Laplace smoothing, log-space to dodge underflow, and a blatantly false independence assumption that works anyway. Then estimators, bias, variance, the bias-variance decomposition, hypothesis testing with its five steps, power and sample size, p-values, and confidence intervals with three fallacies named outright — a frequentist interval is a statement about the procedure, not about this interval containing the parameter. Teaching the misreadings explicitly is better pedagogy than most statistics textbooks manage.
Information theory closes the loop and closes the book's own argument: joint and conditional entropy, mutual information, KL divergence with its non-symmetry flagged, and cross-entropy revealed as the same object as maximum likelihood seen from the other side. The exercises are chosen to force that unification — bits per character from perplexity, I(X,Y)=H(X)−H(X|Y) argued both intuitively and as an expectation, KL between two Gaussians derived by hand.
The sharpest judgement: the chapter is strongest when it is geometric and weakest when it is encyclopedic, and its blemishes cluster in the hurried seams. 'Non-negative' where it means 'non-zero' muddies the one sentence carrying the sparsity argument. A determinant code cell silently transposes the matrix from the prose and is rescued only by the accident that determinants survive transposition. A PyTorch comment sits where a code cell should be, promising notation the framework will not deliver — multi-framework source bleeding through. Einstein summation is presented as an observed rule when it is a convention with teeth, underdetermined enough that einsum's arrow syntax exists to repair it. And the claim that rank equals the number of non-zero eigenvalues holds only for diagonalizable matrices, quietly refuted by the shear example two paragraphs later. These are small, but a careful reader will trip on each one.
What I would tell the reader: do not treat this as a chapter to be completed. Read the geometric sections slowly and the catalogue sections as lookup. Hold on to four things — matrices cannot bend space, so nonlinearities are not decoration; everything is locally linear, which is why gradients work at all; exact mathematics and finite-precision arithmetic diverge, and rank is the place you will feel it first; and maximum likelihood, cross-entropy and KL divergence are one idea wearing three costumes. Verify the arithmetic yourself, because the text's slips are real and the ones that pass silently are the instructive ones. Most of all, notice the recurring pattern this appendix never quite names aloud: at nearly every turn the mathematics does not tell us what the world is like, it encodes an assumption we brought with us — about scale, about independence, about linearity — and then follows it with perfect fidelity. The formalism's rigour is real; its premises are ours. Knowing which is which is the actual reason to read a chapter like this.
Read Chapter 22 with these cards beside each passage.
Open in FeedLitraChapter 23: Appendix: Tools for Deep Learning
How much cheaper are spot instances than on-demand GPU instances?
How Chapter 23 unfoldsAI-assisted
Opening: the workbench before the work
This chapter begins not with theory but with logistics, on the premise that a reader who cannot run the code cannot really learn from it. The first move is to get the book's notebooks open and executing in Jupyter on the reader's own machine. Immediately after that comes a less obvious refinement: rather than working in Jupyter's native .ipynb files, the reader is steered toward editing the book's markdown source, with notedown supplying the bridge that lets markdown be opened and run as if it were a notebook. The reasoning is about version control. A .ipynb file stores execution metadata alongside the prose, so a one-word fix produces a diff crowded with unrelated machine output, and Git cannot distinguish the real edit from the noise. Editing markdown keeps the diff to the words that changed — a point that only pays off much later in the chapter, when contribution is taken up directly, but which is set in place here.
Development: outward from the laptop
From the local setup the chapter widens in a single consistent direction: what to do when your own machine is not enough. SSH port forwarding comes first, the trick that makes a notebook running on a remote server appear in a local browser and so makes remote compute feel like local compute. Then the cloud proper — SageMaker, EC2, Colab — carrying one practical warning the chapter is careful to isolate. Because billing is by time, idle instances should be shut down; but stopping is not deleting. A stopped instance stops costing compute while still charging a small amount for the disk it retains, and can be restarted. Terminating erases everything attached, disk included, leaving nothing to restart. If the aim is to discard an instance but keep the environment, the move is to save an image first. The distinction is easy to collapse and expensive to collapse.
The turn: from software to silicon
The chapter's pivot is from how to access compute to how to buy it. Hardware guidance opens with the whole-server view and an ordering principle: the GPUs are the point, and the rest of the machine exists to feed them. This is what makes the counterintuitive CPU advice follow. Because Python's global interpreter lock means the process dispatching work to four to eight accelerators effectively runs on one thread, single-thread speed is the bottleneck, so a 6-core 4 GHz part beats an 8-core 3.5 GHz one — and PCIe lanes matter because they are the channel carrying data to each card. Attached to this is the reminder that none of the hardware yields any speedup without drivers, CUDA, and a GPU-enabled framework.
Development continued: choosing the card
Narrowing to the GPU itself, the chapter makes three nested recommendations. Buy NVIDIA, because it entered deep learning first and CUDA has the better framework support. Within NVIDIA, a lab or small-to-medium outfit should buy consumer RTX rather than Tesla: compute is broadly comparable, and what Tesla adds — ECC memory, passive cooling — justifies roughly ten times the price only at 100-server scale or in the cloud. At ten-plus servers, the practical path is preconfigured Supermicro or Asus chassis holding four to eight RTX cards. Selection within a line turns on three parameters — compute power, memory size, bandwidth — and on a pattern drawn from price-performance data: within one generation, price and performance track each other roughly proportionally, so the real gain lives in the generational jump. Comparing a 980 Ti with a 1080 Ti shows the GTX 1000 series about twice as cost-effective. The RTX 2000 series complicates this honestly: its advantage appears in low-precision work rather than plain 32-bit price-performance, which is where TensorCores and FP16/INT8/INT4 arithmetic pay off — with the stated caveats that low-precision training was not yet widespread and the prices came from Wikipedia at the time of writing. A second chart shows energy use rising almost linearly with computation, newer generations being more efficient.
Close: contributing back, and the toolbox
The chapter ends by returning to the reader-as-contributor thread opened by the markdown advice. The argument is that improvement is genuinely feasible here: a printed book waits years for the next print run to fix a typo, whereas version control and continuous integration bring this one's turnaround down to hours or days. The concrete sequence follows — fork, clone, edit, git status, add, commit, push, open a pull request — with trivial typos editable straight on GitHub, so that one fix becomes one small, reviewable submission. A final segment catalogues the reusable d2l utilities: plotting, loss, download and extract, tokenization, gradient clipping, then the machine-translation pieces. Among these the masked loss deserves note, since it explains a mechanism rather than merely providing one: batched translation sentences are padded to equal length, so raw per-token loss counts positions holding no real target, and a weight tensor built from each example's valid length zeroes those out before averaging, leaving only genuine tokens to shape the gradient. The seq2seq training and prediction functions close the listing, and they mark a boundary worth keeping straight — feeding the ground-truth previous token belongs to training alone. At prediction the model goes into evaluation mode and each step consumes the argmax of its own previous output, fed back until the end-of-sequence token, which is precisely why an early error can drag a whole generated translation off course. The chapter finishes with the alphabetical d2l API document, the index that makes all of this retrievable.
Key claims, with the lines that support them
Contributors should edit the book's markdown source rather than notebook files.
The author points out that .ipynb files carry a lot of auxiliary execution information, which confuses Git and makes contributions very hard to review; the notedown setup lets you open and run the markdown source in Jupyter directly, so you get the notebook experience without the dirty diffs.
“The former matters since Jupyter’s native ipynb format stores a lot of auxiliary data that is irrelevant to the content, mostly related to how and where the code is run.”
§23.1 Using Jupyter NotebooksRead in context →
When your own machine lacks the GPU power, rent it in the cloud — but shut instances down, and know that shutting down is not the same as deleting.
Because cloud services bill by time used, the author tells readers to close instances they are not using, while noting the catch that a stopped instance still incurs a small charge for the disk it keeps. The contrast is with terminating, which erases everything attached to the instance, including the disk, so it cannot be restarted; saving an image first preserves the environment. Remote work is made usable by forwarding the server's Jupyter port over SSH so the notebook appears to run locally.
“As cloud services are billed by the time of use, you should close instances that are not being used.”
§23.3 Using AWS EC2 InstancesRead in context →
For a multi-GPU server, pick a CPU for clock speed and PCIe lanes, not for the number of cores.
The author's comparison of a 6-core 4 GHz chip against an 8-core 3.5 GHz chip favors the former, because Python's global interpreter lock makes single-thread performance the bottleneck once one process has to keep four to eight GPUs fed. This follows from treating the GPUs as the thing the rest of the machine exists to serve — together with the drivers, CUDA and a GPU-enabled framework, without which the hardware gives no speedup at all.
“For example, when choosing between a 6-core 4 GHz and an 8-core 3.5 GHz CPU, the former is much preferable, even though its aggregate speed is less.”
§23.5 Selecting Servers and GPUsRead in context →
3 more claims
Buy NVIDIA, and for a lab or small-to-medium outfit buy the consumer RTX line rather than data-center cards.
NVIDIA entered deep learning first and its CUDA stack has better framework support, which is why the author says most buyers choose it. Building on that, he notes consumer and Tesla cards have broadly similar compute, while Tesla adds ECC memory and passive cooling at roughly ten times the price — worth it mainly at 100+ server scale or in the cloud. For 10+ servers the practical path he describes is preconfigured Supermicro or Asus chassis holding 4-8 RTX cards.
“NVIDIA was the first to enter the deep learning field and provides better support for deep learning frameworks via CUDA.”
§23.5 Selecting Servers and GPUsRead in context →
Each new GPU generation buys more performance per dollar, though for the RTX 2000 series the gain shows up in low-precision work rather than in plain 32-bit price-performance.
Comparing a 980 Ti with a 1080 Ti, the author finds the GTX 1000 series about twice as cost-effective, while within any one series price and performance track each other roughly proportionally, so the generation jump is where the gain lives. A second chart shows energy use rising almost linearly with computation and newer generations being more efficient, with TensorCores bending the curve — which is why FP16, INT8 and INT4 arithmetic is where the newest cards pay off, with the caveat that low-precision training methods were not yet widespread and the prices came from Wikipedia at the time of writing.
“The performance-to-cost ratio of the GTX 1000 series is about two times greater than the 900 series.”
§23.5 Selecting Servers and GPUsRead in context →
Readers can actually improve this book, because version control and automated testing let fixes land fast.
The author contrasts printed books, where a typo correction waits years for the next print run, with this book's hours-to-days turnaround made possible by version control and continuous integration. He then walks through the concrete sequence — fork, clone, edit, git status, add, commit, push, open a pull request — showing how one typo fix becomes one small, reviewable submission, with trivial typos editable straight on GitHub.
“This is all possible due to version control and continuous integration (CI) testing.”
§23.6 Contributing to This BookRead in context →
How it works
The 3 mechanisms the chapter’s argument runs on.
Mechanism 1
Why notebook files make Git diffs unreadable
Jupyter's native .ipynb files store execution metadata alongside the text, so even a one-word change produces a diff full of unrelated machine output. Git cannot tell the real edit from the noise, which makes review painful; editing the markdown source inside Jupyter keeps the diff down to the words that actually changed.
Mechanism 2
Why CPU clock speed beats core count
Python's global interpreter lock means the process feeding the GPUs effectively runs on one thread, so a faster single core dispatches work to 4-8 accelerators better than more slower cores. That is why a 6-core 4 GHz part can be the better buy than an 8-core 3.5 GHz one, with PCIe lanes mattering because they carry the data to each card.
Mechanism 3
How masking removes padding from the loss
Batched translation sentences are padded to equal length, so the raw per-token loss includes positions that carry no real target. A weight tensor built from each example's valid length zeroes out those positions before averaging, so only genuine tokens shape the gradient.
Common misreadings
Stopping a cloud instance and terminating it are basically the same thing, and either way you stop paying.
Stopping pauses billing for compute but you keep paying a small amount for the retained disk, and the instance can be started again later; terminating deletes everything associated with it, the disk included, so there is nothing left to restart. If you want to discard an instance but keep the setup, create an image of it first.
“As cloud services are billed by the time of use, you should close instances that are not being used.”
§23.3 Using AWS EC2 InstancesRead in context →
Since the decoder is trained on the true previous target token, it must also be given the correct tokens at prediction time.
Feeding the ground-truth previous token belongs to training only. At prediction the model is put in evaluation mode and each step's input is the token the model itself judged most likely, taken as the argmax of its own output and fed back until the end-of-sequence token appears — which is exactly why a mistake early in a generated translation can drag the rest of it off course.
“We use the token with the highest prediction likelihood as input”
§23.7 Utility Functions and ClassesRead in context →
Key concepts in Chapter 23
- Markdown source editing with notedown
- Editing the book's .md source files directly inside Jupyter instead of .ipynb, so Git diffs stay readable.
- Where it applies: Only relevant for contributing content; running code locally does not require it.
- SSH port forwarding for Jupyter
- Tunneling a remote server's Jupyter port to your own machine so you browse it as if local.
- Where it applies: Needs SSH access; on Windows it requires third-party software such as PuTTY.
- GPU requirement
- GPUs are the practical accelerators for deep learning, and they need matching drivers, CUDA, and a GPU-enabled framework.
- Where it applies: Without suitable drivers and a GPU-enabled framework, a GPU instance brings no speedup.
- GPU performance parameters
- The three things to compare when buying: compute power, memory size, and memory bandwidth.
- Where it applies: For most users compute power alone suffices; bandwidth matters mainly with GDDR6.
- Consumer versus enterprise GPUs
- GTX/RTX for individuals, Tesla for data centers; similar compute but Tesla adds ECC memory, passive cooling, and ten times the price.
- Where it applies: Tesla is worth it mainly at 100+ server scale or in the cloud.
- Low precision acceleration
- Using FP16, INT8, or INT4 arithmetic to get more throughput per dollar and per watt.
- Where it applies: Training algorithms for low precision were not yet widespread at the time of writing.
4 more concepts
- Contributing via pull request
- Fork, clone, edit locally, commit, push, then open a pull request that authors review and merge.
- Where it applies: Minor typos can be edited directly on GitHub without forking.
- The d2l package
- A shared library of saved functions and classes so chapters can reuse code instead of redefining it.
- Where it applies: It is a teaching convenience, not a production deep learning framework.
- Sequence masking in loss
- Padding positions are given zero weight so they do not contribute to the training loss.
- Where it applies: Needs valid lengths per example; useless when sequences are already equal length.
- Teacher forcing
- During training the decoder reads the true previous target token rather than its own prediction.
- Where it applies: Only applies at training time; prediction feeds back the model's own argmax token.
Reader’s notes on Chapter 23AI reading companion
“This is confusing for Git, making reviewing contributions very difficult.”
Read in context →The one sentence in this appendix with a real argument in it — the file format is a social problem, not a technical one. Notebooks fail at collaboration, so the book quietly writes itself in markdown.
“It is also a good idea to set up detailed billing and spending alerts to avoid any surprise”
Read in context →Tucked into step one of signing up: the real hazard of cloud GPU isn't misconfiguration, it's forgetting. Note how often this chapter returns to "stop the instance."
“simply discard all your local changes with the following commands”
Read in context →git reset --hard handed to beginners with one hedging sentence before it. For readers whose notes live in those notebooks this is the most destructive line in the appendix.
16 more notes
“Recall that in Section 23.2 we discussed how to use Amazon SageMaker, while building an instance by yourself costs less on AWS.”
Read in context →Three paths to the same GPU, ordered by decreasing price and increasing labor. The appendix is really a lesson in buying compute, not in Jupyter.
“the former is much preferable, even though its aggregate speed is less”
Read in context →Nice inversion: the GIL, a language design accident, bends your hardware purchase toward clock speed over cores. Python's constraints reach all the way into the motherboard.
“This server will probably run loud and hot. You do not want it under your desk.”
Read in context →The voice finally drops the manual register. Four GPUs stops being a config list and becomes a thing in a room with you.
“as one of the coauthors painfully discovered”
Read in context →An aside that earns more trust than the whole spec table — the knowledge here was paid for in a cable that didn't fit.
“usually cost ten times more than consumer GPUs”
Read in context →Ten times the price for the same compute, bought for ECC and cooling. The honest reading: you're paying for reliability and permission, not speed.
“However, this is a consequence of the TensorCores that draw disproportionately much energy.”
Read in context →Twice in two paragraphs the RTX anomaly gets explained away by the same escape hatch. Convenient — and unfalsifiable as written, since no FP16-normalized plot is shown.
“Use FP16 or lower precision for high efficiency.”
Read in context →Stated as pure upside. Not a word about where reduced precision actually bites — loss scaling, convergence, debugging numerics.
“the delay between print runs (and thus between typo corrections) can be measured in years, it typically takes hours to days”
Read in context →The real argument of this section: the book is bragging about its own metabolism, not teaching Git. Years-to-hours is the whole pitch for the medium.
“When your pull request is merged into the code repository by the authors, you will become a contributor.”
Read in context →Neat incentive design — the reward is identity, not money. A textbook that pays in belonging.
“Try not to submit huge pull requests since this makes them hard to understand and incorporate. Better send several smaller ones.”
Read in context →The one line here with genuine craft wisdom, and it's buried in a summary bullet. Reviewability as a first-class design constraint applies far past this repo.
“A bunch of functions that will be deprecated:”
Read in context →Startlingly candid for a textbook. A whole appendix of code the authors have already disowned but can't delete, because earlier chapters still lean on it. The seam where a living book shows its scar tissue.
“raise ValueError("%s env is not supported in this Notebook")”
Read in context →The format string has no argument — the error prints a literal %s. A small bug sitting inside the chapter that invites readers to send pull requests. Almost too perfect.
“frame = inspect.currentframe().f_back”
Read in context →Reaching into the caller's stack frame to auto-assign every argument as an attribute. Magical for teaching, terrifying as a habit — the reader learns a trick whose cost they can't yet see.
“show_Q_function_progress(env_desc, V_all, pi_all)”
Read in context →Near-verbatim duplicate of the function above it, differing only in which iterations get sampled. The book that urges elegant code just copy-pasted sixty lines.
“X[~mask] = value”
Read in context →An in-place write hiding inside a utility that reads like a pure function. Anyone passing a tensor they still need gets it silently overwritten — and here it's fine only because weights was freshly created.
“weighted_loss = (unweighted_loss * weights).mean(dim=1)”
Read in context →Note it's mean over all num_steps, not over valid tokens — so a short sentence in a long-padded batch gets its loss diluted. Then training divides by Y_valid_len.sum() anyway, mixing two normalizations.
A reader’s takeAI reading companion
JSON diffs destroy review, making notebook format a social problem
The appendix presents itself as housekeeping — install Jupyter, rent a GPU, send a pull request, here are the utility functions — and that modesty is the most misleading thing about it. Read straight through, it is actually three arguments in a trench coat, and the chapter is most honest exactly where it sounds least like a textbook.
The first argument is about formats and collaboration. The line that notebooks are 'confusing for Git, making reviewing contributions very difficult' is the only sentence in the opening pages carrying real intellectual weight: the book writes itself in markdown not for elegance but because JSON diffs destroy review. That is a social diagnosis, not a technical one, and it rhymes with the craft advice buried much later in a summary bullet — send several small pull requests rather than one huge one. Reviewability as a first-class constraint is the actual lesson of the Git section, and it is worth more than the git commands around it. Those commands, incidentally, include the appendix's most dangerous line: git reset --hard offered to beginners with a single hedge, in a chapter whose readers keep their notes inside the very notebooks being discarded.
Continue reading
The second argument is about buying compute, and the chapter never admits that's what it is. Local Jupyter, SSH tunneling, SageMaker, self-built EC2, Colab, then a desk server with four GPUs — three or four paths to the same tensor cores, ordered by falling price and rising labor. The recurring hazard is never misconfiguration; it is forgetting. 'Set up billing alerts,' 'stop the instance,' repeated like a liturgy, because the failure mode of cloud GPU is inattention. The hardware guidance is at its best when the manual register cracks: a four-GPU box will 'run loud and hot' and you do not want it under your desk; a coauthor 'painfully discovered' that a cable did not fit. Those asides earn more trust than the spec tables, because they are the only places the knowledge is visibly paid for. And one genuinely elegant observation sits there almost unremarked — Python's GIL pushing you toward clock speed over core count. A language design accident reaching into your motherboard purchase is the kind of cross-layer insight the rest of the chapter does not attempt.
Where the hardware section weakens is where it starts defending conclusions. The RTX energy anomaly gets explained twice by the same TensorCore escape hatch, with no FP16-normalized plot to test it — convenient and, as written, unfalsifiable. 'Ten times the price' for Tesla cards is stated plainly, but the honest reading is that you are buying ECC, cooling, and institutional permission, not speed. And 'use FP16 or lower precision for high efficiency' is pure upside with no mention of loss scaling, convergence instability, or how much harder numerics get to debug. These are the moments to read with a hand on the brake.
The third argument is about the medium itself. Years-to-hours — print corrections versus merged pull requests — is the real pitch of the contribution section; it is bragging about the book's metabolism more than teaching version control. And it pays contributors in identity rather than money: merge a fix and you become a contributor. Neat incentive design for a textbook that is also a repository.
Then the utilities appendix, which is where the living book shows its scar tissue, and where I'd send a skeptical reader first. 'A bunch of functions that will be deprecated' is startlingly candid — code the authors have already disowned but cannot delete because earlier chapters lean on it. A ValueError whose format string has no argument will literally print %s. inspect.currentframe().f_back, reaching into the caller's stack to auto-assign attributes, is magical pedagogy and a terrible habit whose cost a learner cannot yet price. Two near-identical sixty-line plotting functions sit adjacent, differing only in which iterations they sample, in a book that elsewhere preaches elegance. X[~mask] = value writes in place inside a function that reads as pure — safe here only because weights was freshly created, which is exactly the kind of accident that stops being safe when copied. And the masked loss averages over all num_steps rather than valid tokens, diluting short sentences in a long-padded batch, after which training divides by Y_valid_len.sum() anyway — two normalizations mixed in one loop.
The sharpest single line in the whole chapter is dec_input = concat([bos, Y[:, :-1]], 1) # Teacher forcing. The entire exposure-bias problem — train on ground truth, infer on your own guesses — reduced to a two-word comment, as if it were a formatting detail. Nothing in the appendix flags it as a structural mismatch; the alphabetized API document that closes the chapter certainly doesn't.
What I'd tell a reader: this appendix is not optional filler, but it is the chapter where the authors' guard is down, and that cuts both ways. Treat the asides and the deprecation notes as the honest parts — they tell you what the work actually costs. Treat the clean imperatives, 'use FP16,' 'reset --hard,' the helper that silently mutates your tensor, as claims needing a second look. Most of all, do not mistake the utility listings for settled reference code. They are a working snapshot of a book under revision, with real bugs and real seams in them — and the fact that a reader can spot a broken format string and open a pull request within hours is, by the chapter's own argument, the point.
Read Chapter 23 with these cards beside each passage.
Open in FeedLitraWhere the argument strains
Not a rebuttal — the places a careful reader will want to push.
- The book urges building intuition by running code while also insisting on principled derivations such as the maximum-likelihood justification of squared loss; it does not resolve how much a reader should trust empirical tweaking when theory is absent.
“It follows that minimizing the mean squared error is equivalent to the maximum likelihood estimation of a linear model under the assumption of additive Gaussian noise.”
§3.1 Linear RegressionRead in context → - Closed-form solutions are dismissed as a lucky special case, yet linear regression — whose analytic solution exists — is held up as the model containing nearly every component of deep learning.
“Although analytic solutions allow for nice mathematical analysis, the requirement of an analytic solution is so restrictive that it would exclude almost all exciting aspects of deep learning.”
§3.1 Linear RegressionRead in context → - Just-in-time teaching conflicts with the front-loaded preliminaries, notation and installation chapters, which cover material before any task demands it.
“For example, “\(x\): a scalar” means that lowercased letters generally represent scalar values, but “\(\mathbb{Z}\): the set of integers” refers specifically to the symbol \(\mathbb{Z”
NotationRead in context → - Readers are reassured that a CPU suffices, while the engineering argument stresses that models hold hundreds of megabytes of parameters updated many times per second and that GPU acceleration is a reason to prefer tensors.
“If your machine does not house any GPU, there is no need to worry just yet.”
InstallationRead in context →
2 more tensions and 8 limits of the evidence
- Implementing everything from scratch and then discarding it for the high-level API leaves unclear which layer of abstraction a practitioner should actually reason in.
“In Section 3.4, we relied only on (i) tensors for data storage and linear algebra; and (ii) automatic differentiation for calculating gradients.”
§3.5 Concise Implementation of Linear RegressionRead in context → - Offline learning on one fixed pile of data sits uneasily with the claim that learning systems improve through accumulating interaction with an environment.
“Because all the learning takes place after the algorithm is disconnected from the environment, this is sometimes called offline learning.”
Chapter 1. IntroductionRead in context →
Limits of the evidence
- The claim that CPU-only machines suffice to begin is asserted without any benchmarks.
“If your machine does not house any GPU, there is no need to worry just yet.”
InstallationRead in context → - The speedup argument for vectorization rests on a single micro-benchmark of one elementwise operation on 10,000-dimensional vectors.
“Vectorizing code often yields order-of-magnitude speedups.”
§3.1 Linear RegressionRead in context → - The closed-form least-squares solution applies only to linear least squares and only when the relevant matrix is invertible, so conclusions drawn from it do not transfer to general models.
“Although analytic solutions allow for nice mathematical analysis, the requirement of an analytic solution is so restrictive that it would exclude almost all exciting aspects of deep learning.”
§3.1 Linear RegressionRead in context → - The intuitive billing illustration of linear regression works only if the two assumed features explain all variation in the target.
“If you followed that much, then you already understand the high-level idea behind linear regression.”
Chapter 1. IntroductionRead in context → - The authors concede their self-built publishing system is not perfect, so the claimed advantage over existing resources is partly aspirational.
- The explanation for why formal theory lags — hard mathematics, ill-defined data properties, recency of serious inquiry — is reasoning rather than evidence, so the prescription to learn by tweaking code is not empirically validated.
- The four-component decomposition of machine learning is illustrated only by objective-function examples such as squared error and error rate, leaving the other three components unevidenced.
“An objective function that quantifies how well (or badly) the model is doing.”
Chapter 1. IntroductionRead in context → - Preprocessing guidance is demonstrated on one tiny house dataset, a scale at which imputation and dummy encoding choices carry little consequence.
“However, to apply deep learning in the wild we must extract messy data stored in arbitrary formats, and preprocess it to suit our needs.”
§2.2 Data PreprocessingRead in context →
Mind map of the whole book
5 clusters of ideas: a plain-English label, a one-line explanation, and the term the text itself uses.
1 · Learn by running the code
- Each idea arrives right when a task needs it
- Introducing each concept exactly when a practical task requires it, rather than front-loading theory.In the text: Just-in-time teaching
- Build it by hand first, then the one-line library version
- The book's recurring pedagogy: implement a component by hand first, then redo it with the concise framework version used thereafter.In the text: From scratch plus high-level API
- Every example is a standalone notebook you can tweak
- Each self-contained example lives in its own notebook so readers can copy and modify it.In the text: One working example, one notebook
- A fixed, isolated setup that runs fine on a laptop CPU
- An isolated Miniconda Python 3.9 environment that must be activated in every new shell, with GPU availability mattering only for larger models.In the text: Reproducible runtime environment
2 · When rules can't be written down
- Programs that get better as they see more data
- Algorithms whose performance improves as they accumulate data or interaction, used where rules cannot be stated by hand.In the text: Machine learning
- Learning from examples that already carry the answer
- Predicting a designated unknown label from known inputs using labeled examples; its subtypes are organized by the form of the output.In the text: Supervised learning
- Picking which category an example belongs to
- Predicting which category among a discrete set an example belongs to, extended to multi-label prediction when classes co-occur.In the text: Classification and its variants
- Handling inputs or answers that arrive as sequences
- Tasks whose inputs or outputs are variable-length sequences requiring context.In the text: Sequence learning
3 · Four parts in every method
- One parameter setting is a model; all of them, a family
- A program with fixed parameter settings is a model; all reachable settings form its family, the space the learning algorithm searches.In the text: Model and model family
- The routine that picks the parameters from the data
- The meta-program that uses the dataset to pick parameter values, instantiated in this book mainly as minibatch stochastic gradient descent.In the text: Learning algorithm
- Training on a fixed pile of data, not a live environment
- Learning cut off from the environment using one fixed pile of data, contrasted with a policy that maps observations to actions.In the text: Offline learning and policy
4 · The math and data plumbing
- Numbers in a grid of any shape — the one data interface
- An array of numbers with any number of axes — the book's core data interface — adding automatic differentiation and GPU acceleration, with broadcasting and in-place operations as key mechanics.In the text: Tensor (n-dimensional array)
- Matrix moves that map vectors from one space to another
- Transpose, symmetry, Hadamard and dot products, and reductions along axes — the vocabulary in which layer computations are written.In the text: Linear algebra operations
- Turning messy real tables into clean tensors to feed in
- Turning messy real data into tensors — handling missing values by imputation or deletion and dummy encoding — then wrapping loading, shuffling and batching so the learning algorithm never touches raw storage.In the text: Data preprocessing and loading
- Symbols whose shape tells you number, vector or matrix
- A uniform symbol convention where case and font encode an object's rank — scalar, vector, matrix, general tensor — and placeholders are distinguished from specifically named objects, with marked definitional equality.In the text: Typographic notation system
5 · Linear regression as miniature
- Predicting a plain number, like a price
- Predicting a label that can take arbitrary numerical values, realized concretely as a weighted sum of features plus a bias.In the text: Regression
- Squared gap as loss — the best fit under bell-curve noise
- Half the squared gap between prediction and label, averaged over examples; equivalent to maximum likelihood under additive Gaussian noise.In the text: Squared error loss
- Measuring a vector's size, which is what the loss counts
- A function sending a vector to a scalar that measures its size, supplying the language in which learning objectives are expressed.In the text: Norm
- How well it does on unseen data, steered by knobs you set
- Accuracy on unseen data, governed by settings the training loop does not update and judged on a held-out validation set.In the text: Generalization and hyperparameters
Annotated passagesAI reading companion
Lines worth stopping on, each with a note on why it matters to the whole book.
“the precise steps required to perform the task lie beyond our conscious understanding, even though our subconscious cognitive processes execute the task effortlessly”
Read in context →Placed against the whole book, this is the founding premise: every chapter that follows exists only because human competence outruns human explanation.
“And when you are able to devise solutions that work \(100\%\) of the time, you typically should not be worrying about machine learning.”
Read in context →The book's own boundary marker — it tells you where the next thousand pages do not apply, which is rarer and more useful than anything they assert.
“we simply do not know how to calculate it by hand”
Read in context →The hinge of the entire arc from linear models to deep nets: depth is adopted not as triumph but as a confession that hand-designed features ran out.
9 more notes
“what Waldo looks like does not depend upon where Waldo is located”
Read in context →The cleanest instance of the book's deepest recurring pattern — architectures are claims about the world, and the math is just that claim in index notation.
“primarily attributable to shifts in the available computational resources”
Read in context →Read across the whole volume, this is the uncomfortable thesis: much of the chapter-by-chapter progress narrative was compute and data wearing an architecture costume.
“This apparent strength, however, is also its Achilles heel: general-purpose cores are very expensive to build.”
Read in context →Pairs with the compute argument to explain why these operations won — deep learning's math was parallelizable enough to ride someone else's hardware market.
“First, the tensor class supports automatic differentiation. Second, it leverages GPUs to accelerate numerical computation”
Read in context →Both of the field's load-bearing enablers turn out to be engineering, not mathematics — a framing the later theory chapters never quite reckon with.
“even when we only care about hard assignments, we still use models that make soft assignments”
Read in context →The quiet constraint shaping nearly every model in the book: everything must be differentiable, so hard decisions get softened for the gradient's sake, not ours.
“Only some degree of noise might knock the parameter out of the local minimum.”
Read in context →Names the book's signature move across optimization, dropout, and augmentation alike — noise reclassified from defect to mechanism.
“in standard deep learning the prediction of a trained model on one test datum does not affect the predictions on a future test datum”
Read in context →The sharpest statement of what the first twenty chapters silently assumed; once i.i.d. breaks, the comfortable guarantees of the whole book go with it.
“although what precisely the attention weights mean—i.e., how, if at all, they should be interpreted remains a hazy research topic”
Read in context →The book at its most honest about interpretability: the mechanism that now dominates the field resists explanation, and 'if at all' refuses to pretend otherwise.
“If the generator does a perfect job, then \(D(\mathbf x')\approx 1\), so the above loss is near 0, which results in the gradients that are too small to make good progress for the discriminator.”
Read in context →Worth keeping as a reader's discipline — a textbook this careful still prints a backwards justification, so trust the derivation you can check over the prose around it.
A reader’s verdictAI reading companion
When rules fail, replace answers with spaces to search
Read cover to cover, Dive into Deep Learning is not a survey of techniques but a single argument repeated at every scale: when a task cannot be reduced to rules you can state, stop specifying the answer and specify instead a space of answers plus a way to search it — and then pay honestly for what that move costs. The spine runs from Preface and Notation (knowledge as a design problem; symbols as types) through Preliminaries' interlocking toolkit, into linear and softmax regression, where the book's real obsession first surfaces: it builds the simplest working model twice and then immediately attacks the confidence that building it produced, because training error is not generalization.
From there the pattern recurs with different furniture. MLPs show that stacking affine maps buys nothing without nonlinearity, and that the decisive problems become numerical rather than conceptual — vanishing gradients, symmetry, initialization variance. The Builders' Guide reveals the one structural idea underneath everything: the module as a recursive building block, so layers, blocks and whole models share one interface. CNNs encode a prior about the world (locality, translation invariance) as a constraint, then spend the rest of the chapter buying back what the constraint took away via channels, padding and depth; modern CNNs narrate a field learning to stop designing networks and start designing design spaces.
Continue reading
RNNs relocate the variable-context problem into a hidden state rather than escaping it, and modern RNNs fight one villain — the vanishing gradient — with one weapon, an additive path through time, while candidly calling clipping a hack. Attention then dissolves the bottleneck entirely by making the lookup itself learned and differentiable, and the Transformer's lack of built-in priors becomes a strength precisely because smooth power-law scaling makes it a universal backbone. The final third is the book turning to face its own bill: optimization on dishonest terrain, computational performance where mathematics becomes an engineering budget and hardware is matter, computer vision's slow confession that earlier chapters' premises were conveniences, NLP pretraining's cycle of promising free representations and then exposing each one's limit, RL's purchase of model-freedom with sample inefficiency, GPs' priors over functions, and HPO's accounting of what it costs not to guess.
Its sharpest judgments are the uncomfortable ones: generalization, not fitting, is the fundamental problem; classical complexity theory is too pessimistic to explain deep networks; a deployed model can alter the distribution it was trained on; bespoke per-task architecture is impractical at scale yet still right when resources are tight; and for large-scale vision, scalability has simply outvoted the inductive biases that made CNNs dominant. To the reader: do not mine this book for recipes. Read the chapters as the arguments they are, run every piece of code and break it, and treat the appendices — the mathematics and the tools — not as optional backmatter but as the scaffolding the whole building was quietly resting on.
The book's deepest lesson is a habit rather than a result: state your assumptions, notice when they fail, and know the price of every abstraction you accept.
What reviewers say
Chinese readers on Douban rate this highly, praising hands-on code, open-source availability, author responsiveness and companion video lectures; critics call the Chinese translation clumsy, the explanations thin on underlying principles, and the later chapters on CNNs and RNNs too steep for true beginners. A deeplearning.ai forum poster recommends it mainly as a reference work.
A synthesis of published reviews. Ratings are not shown; follow the links for each review in full.
- Short reviews of Dive into Deep Learning (PyTorch edition), in Chinese
- Recommended first books on deep learning (Dive into Deep Learning) — review in Chinese
- A poor experience — is it because I read the second edition? (Dive into Deep Learning review, in Chinese)
- Dive Into Deep Learning - Book - DeepLearning.AI Community
Sources and license
CC BY-SA 4.0The text
- Dive into Deep Learning by Aston Zhang, Zachary C. Lipton, Mu Li and Alexander J. Smola (Cambridge University Press, 2023; online at d2l.ai). Copyright 2019 Amazon.com, Inc. or its affiliates. The text is licensed under the Creative Commons Attribution-ShareAlike 4.0 International License; sample code under a modified MIT license. Read it free · License
- This page’s own text (summaries, notes and essays) is shared under CC BY-SA 4.0.
- Summaries, claims, notes and essays are AI-assisted: generated by FeedLitra from the full text, with quotations checked against the source. Last updated October 21, 2026.
Read Dive into Deep Learning with these cards beside the text.
Open in FeedLitra