7 routes42 sections324 units

Unit 1.1 · about 4 h

170 / 324

Affine 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

  1. Shallow and deep affine structure
    Understanding 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

  2. MLP math and activation curves
    D2L - 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

Closed-book, for \(X\) \((4 \times 3)\), \(W\) \((3 \times 5)\), \(b\) (5,) and upstream \(G = dL/dY\): write \(Y\) shape \((4 \times 5)\) and derive \(dL/dW = X^\top G\), \(dL/db\) = sum of \(G\) over rows, \(dL/dX = G W^\top\). Then derive the sigmoid, tanh and ReLU derivatives and state each maximum.

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

  1. \(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\)?

  2. Why do two stacked affine layers without an activation collapse?

  3. What are the maximum slopes of the sigmoid and tanh, and where?

  4. What are GELU(0) and the GELU slope at 0?

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

Resources for this unit

  • Understanding Deep Learning - Chapters 3 to 7
    Simon J. D. Princeprimarytheory
    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
    D2L authorsrequiredimplementation
    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
    TensorTonicrequiredpractice
    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
    Deep-MLoptionalpractice
    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
    Stanford CS231nreferencereference
    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
    Stanford CS231nreferencereference
    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
    PyTorchreferencereference
    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
    PyTorchreferencereference
    Read the gradcheck signature defaults (eps 1e-6, atol 1e-5, rtol 1e-3) and the note that inputs with overlapping memory, such as expand outputs, will likely fail the check.
  • `torch.nn.functional.cross_entropy` - `reduction` and `ignore_index`
    PyTorchreferencereference
    Read the ignore_index and reduction parameters: ignored targets contribute no gradient, and mean reduction averages over the non-ignored targets only.
  • PyTorch Tensor Views
    PyTorchreferencereference
    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: reshape may copy, contiguous copies only when needed, basic indexing returns views while advanced indexing copies.
  • `torch.Tensor.stride` - stride and storage offset
    PyTorchreferencereference
    Read the stride definition: strides are per-dimension element steps, and with storage_offset they locate every element. Combine with the Tensor Views page for transposed and expanded layouts.
  • PyTorch Autograd mechanics - in-place operations
    PyTorchreferencereference
    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
    PyTorchreferencereference
    Read the parameters and buffers documentation: modules collect parameters recursively for the optimizer, while register_buffer holds persistent non-parameter tensors saved alongside them.

Quick find

Search Michi

Type to search every route, section, unit, topic and resource.

Enter opens the first result Esc closes

Reference

Keyboard shortcuts

n
Continue to the first unit not passed
j / k
Next / previous unit
1 2 3
Toggle learned, practised, passed
/
Open search
?
Show this help
Esc
Close open panels