Unit 1.1 · about 4 h
170 / 324Affine maps, nonlinearities and logits
Every network is affine maps plus nonlinearities, and the raw affine outputs (logits) feed every loss in this section. Wrong shapes or a dead activation here break everything downstream.
- explain
- derive
You can now
- Write the batched affine map \(Y = XW + 1 b^\top\) with exact shapes, and derive its weight, bias and input gradients.
- Derive ReLU, sigmoid and tanh derivatives from their definitions, and state where each saturates or dies.
- Explain why stacked affine maps without a nonlinearity collapse to one affine map, and what logits are.
Covers
- Affine maps, nonlinearities, logits and tensor shapes
- ReLU, GELU, sigmoid and tanh behavior
Study, in this order
2 steps
- Shallow and deep affine structureUnderstanding Deep Learning - Chapters 3 to 7
Chapter 3, Sections 3.1 to 3.5 (Eq 3.1 to 3.12, printed pp. 25 to 35) for the scalar, multivariate and general affine-plus-activation forms; Chapter 4, Sections 4.1 to 4.4 (Eq 4.1 to 4.16, printed pp. 41 to 49) for composed maps and matrix notation
- MLP math and activation curvesD2L - tensors, autograd, MLP and backpropagation
Hidden Layers: the linear-collapse derivation \(W = W_1 W_2\), \(b = b_1 W_2 + b_2\) with \(X \in \mathbb{R}^{n \times d}\), \(H \in \mathbb{R}^{n \times h}\); Activation Functions: ReLU, sigmoid and tanh definitions, plots and derivative maxima
Depth · Skip the Universal Approximators discussion and the Exercises until practice. For the convention that this book calls affine maps linear, read the Chapter 3 Notes paragraph "Linear, affine, and nonlinear functions" in UDL (p. 39).
Focus on
- Batched affine: \(X\) \((n \times d)\), \(W\) \((d \times h)\), \(b\) \((h,)\) broadcasts over rows, so \(Y = XW + 1 b^\top\) has shape \((n, h)\). The bias gradient is the row sum of the upstream gradient.
- Without a nonlinearity, two affine layers collapse to one: substituting \(H = XW_1 + b_1\) into \(O = HW_2 + b_2\) gives \(W = W_1 W_2\) and \(b = b_1 W_2 + b_2\). Depth without activation adds no function class.
- Sigmoid slope peaks at 0.25 at input 0; tanh peaks at 1 at input 0; both decay toward 0 for large \(|x|\). ReLU has slope 0 below 0 and 1 above; D2L takes the left derivative, 0, exactly at 0.
- GELU is \(x\) times the standard Gaussian CDF, smooth rather than piecewise linear, with \(\operatorname{GELU}(0) = 0\) and slope 0.5 at 0. UDL Figure 3.13 (p. 37) names it Gaussian error linear unit.
Reproduce closed-book
Traps
- Returning \(G\) itself, or its mean, as the bias gradient. The bias is broadcast over the \(n\) rows, so \(dL/db = 1^\top G\), the sum over the batch with shape \((h,)\). A mean belongs only to an explicit mean in the loss.
- Reading ReLU slope at 0 as mathematically settled. Frameworks pick a subgradient (D2L uses 0); the kink matters for gradient checks in a later unit.
- Assuming tanh fixes the sigmoid saturation problem. It is zero-centered but still saturates, and its per-layer factor is at most 1.
Practice
TensorTonic: Evaluate a Dense Layer (autograd-l07-dense-layer-forward)
Neural-Network Modules section: Evaluate a Dense Layer; implement the batched affine forward in your own repository
Check your output shape and bias broadcasting against the reproduce derivation before submitting.
TensorTonic: Differentiate a Tanh Activation (autograd-l04-tanh-forward-backward)
Neurons and Activation Gradients section: Differentiate a Tanh Activation, then Backpropagate Through a Scalar Neuron
Derive \(1 - \tanh^2\) by hand first; confirm the peak value 1 at input 0.
Self-test
-
\(X\) is \((4 \times 3)\), \(W\) is \((3 \times 5)\), \(b\) has 5 entries. What is the shape of \(Y = XW + b\), and of \(dL/dW\) in terms of \(G = dL/dY\)?
\(Y\) is \((4 \times 5)\). \(dL/dW = X^\top G\) is \((3 \times 4)\) times \((4 \times 5)\) = \(3 \times 5\). \(dL/db\) is the sum of \(G\) over the 4 rows. -
Why do two stacked affine layers without an activation collapse?
Substitution gives a single affine map with \(W = W_1 W_2\) and \(b = b_1 W_2 + b_2\), so the pair expresses nothing a single layer cannot. -
What are the maximum slopes of the sigmoid and tanh, and where?
Sigmoid peaks at 0.25 at input 0; tanh peaks at 1 at input 0. Both approach 0 for large positive or negative inputs. -
What are GELU(0) and the GELU slope at 0?
\(\operatorname{GELU}(0) = 0\) since 0 times \(\Phi(0)\) is 0. The derivative is \(\Phi(x) + x \phi(x)\), so at 0 it equals \(\Phi(0) = 0.5\).
Completion criterion
Stop when
You write the \((4 \times 3)\) example gradients and all three activation derivatives from memory, and both TensorTonic problems pass with failures, if any, limited to sign conventions you can fix on sight.
Mark passed, then open 1.2 Only mark this when you can do it without notes.Leads to
- 1.2 Stable softmax, cross-entropy and loss reductions Feed logits into a stable softmax and cross-entropy.
- 1.3 Computation graphs and reverse accumulation Differentiate affine chains with the chain rule.
Resources for this unit
- Understanding Deep Learning - Chapters 3 to 7 Read Chapters 3-7, emphasizing Chapter 5 for likelihood-derived losses and Chapter 7 for backpropagation and initialization. Use notebooks 3.1, 4.1, 5.1, 6.1 and 7.1 only as equation and plot companions.
- D2L - tensors, autograd, MLP and backpropagation Use chapter_preliminaries ndarray and autograd, then MLP, backpropagation, and numerical stability and initialization. Recreate scalar operations, affine maps, activation, reduction, stable cross-entropy, topological backward and unbroadcast in a blank file.
Also in this section
- TensorTonic - Build Micrograd from Scratch Use the 25-problem Micrograd study plan in order for derivatives, gradient checks, value graphs, reverse mode, accumulation, operators, modules, losses and training. Preserve local tests as the evidence instead of a platform score.
- Deep-ML candidate - autograd and loss problems After the five-sample platform check passes, use at most one of 26 Basic Autograd Operations, 997 Manual Cross-Entropy Backprop or 1227 Stable Softmax as a changed-prompt drill.
- CS231n Linear Classification - Softmax classifier and numeric stability Read the Softmax classifier section for the cross-entropy form \(L_i = -f_{y_i} + \log \sum_j e^{f_j}\), then the Practical issues: Numeric stability part for the max-subtraction code
f -= np.max(f). - CS231n Neural Networks 3 - Gradient checks Read the Gradient Checks section only: centered formula with \(O(h^2)\) error, relative error with thresholds, double precision, step size \(h\) near 1e-5, kinks, few datapoints, burn-in, regularization and dropout discipline, and checking a few dimensions per parameter.
- PyTorch Broadcasting semantics Read General semantics for the trailing-dimension rules, prepend-1 alignment and max-size result, with the
(5, 1, 4, 1)plus(3, 1, 1)examples; read In-place semantics for why an in-place tensor may not change shape. - `torch.autograd.gradcheck` API and tolerances Read the
gradchecksignature defaults (eps1e-6,atol1e-5,rtol1e-3) and the note that inputs with overlapping memory, such asexpandoutputs, will likely fail the check. - `torch.nn.functional.cross_entropy` - `reduction` and `ignore_index` Read the
ignore_indexandreductionparameters: ignored targets contribute no gradient, and mean reduction averages over the non-ignored targets only. - PyTorch Tensor Views Read the view and storage sharing example (
data_ptr, mutating the view changes the base), the transpose non-contiguous example, the full view-ops list, and the special notes:reshapemay copy,contiguouscopies only when needed, basic indexing returns views while advanced indexing copies. - `torch.Tensor.stride` - stride and storage offset Read the stride definition: strides are per-dimension element steps, and with
storage_offsetthey locate every element. Combine with the Tensor Views page for transposed and expanded layouts. - PyTorch Autograd mechanics - in-place operations Read In-place operations with autograd (why in-place rewrites the graph and is discouraged) and In-place correctness checks (the version counter and the error on accessing a modified saved tensor).
- `torch.nn.Module` - parameters, buffers and state Read the parameters and buffers documentation: modules collect parameters recursively for the optimizer, while
register_bufferholds persistent non-parameter tensors saved alongside them.