SBU · MSc · Exam Deck · 14 chapters

Artificial Neural
Networks

The whole course, compressed: every formula, architecture and trade-off you need to walk into the exam with. Arrow keys to move, T for contents, R to hide formulas and quiz yourself.

Σ

Part I · Chapters 1–4

Foundations

I

CH 01 · Introduction · neuron model

One neuron — weighted sum, then squash

x1 x2 xn w1 w2 wn b Σ f y z
net input — soma $$ z=\sum_{i=1}^{n} w_i x_i + b $$

weights = synaptic strength: $w\gt0$ excitatory, $w\lt0$ inhibitory. Bias shifts the firing threshold.

output — axon $$ y=f(z)=f\!\Big(\sum_i w_i x_i+b\Big),\qquad f(z)=\frac{1}{1+e^{-z}} $$

$z \ne y$. Net input in, activation out — classic exam trap.

bio → math mapping
dendrite → input soma → Σ axon hillock → f synapse → w

CH 01 · Introduction · why parallelism wins

Slow parts, smart whole

Intelligence is emergent — many simple units, massively parallel, asynchronous, with plastic connectivity (= learning).

BrainComputer
Switching time~1 ms (10⁻³ s)~1 ns (10⁻⁹ s)
Signal speed~100 m/s~3×10⁸ m/s
Speed gapmachine ≈ 10⁶× faster per unit
Units~10¹¹ neurons · 10¹³ synapses~10¹⁰ transistors
Wins atperception, robustnessarithmetic, precision
course scope

In: engineering view — neuron → layer → network. Out: neurobiology, VLSI hardware.

paradigm 1 · adaptive weight learning

Local, direct weight updates — MCP · Hebb · Perceptron · Adaline · RBF · SOM · Hopfield

paradigm 2 · error backpropagation

Chain rule pushes error backward — MLP · Deep nets · CNN · RNN · Autoencoders (+ SGD, dropout, batch-norm)

big numbers
10¹¹ neurons10⁴ synapses / neuron cortex 2×10¹⁰ n10¹³ connections

CH 01 · Introduction · 70 years in one line

Two springs, one winter

WINTER 1943McCulloch& Pitts 1949Hebb rule 1958Rosenblattperceptron 1960Adaline 1969Minsky–PapertXOR critique 1982Hopfield ·Kohonen 1986backprop(RHW) 1989LeCun CNN 1997LSTM 2012AlexNet
the winter

1969: single-layer perceptron can't do XOR — wrongly generalized to all neural nets → funding collapse.

the thaw

1986: backprop trains hidden layers → non-separable problems solved, critique voided.

the boom

2012: AlexNet = depth + GPUs + data. Deep learning era begins.

CH 02 · Origins · McCulloch–Pitts 1943

Logic from a threshold

mcp rule $$ y=\begin{cases}1 & \sum_i x_i \ge \theta\\[2pt] 0 & \text{otherwise}\end{cases} $$

Unweighted binary inputs; the only free parameter is θ. Inhibitory input = absolute veto, not a negative weight.

gateweightsθnote
AND+1, +12line $x_1{+}x_2{=}2$
OR+1, +11line $x_1{+}x_2{=}1$
NOTinhibitory0$y=1-x_1$ · veto
XORimpossible in one layer
4 limits → 4 upgrades
binary inputs→ real-valued $x_i$
hand-set θ→ learnable bias
equal weights→ free weights $w_i$
separable only→ hidden layers
threshold ↔ bias $$ b=-\theta \qquad\text{(bias = weight on a constant input } x_0{=}1) $$

Same summing hardware, but now the threshold is learnable like any weight. Watch the sign flip.

CH 02 · Origins · XOR · depth · UAT

XOR breaks the line — depth fixes it

0,01,0 0,11,1 1 ≤ x₁+x₂ < 2

no single line separates ● from ○ — band needs two lines

minimal fix · 2 hidden units $$ y=\mathrm{OR}(x_1,x_2)-\mathrm{AND}(x_1,x_2) $$
why nonlinearity — collapse proof $$ (\mathbf{x}W_1{+}\mathbf{b}_1)W_2{+}\mathbf{b}_2=\mathbf{x}(W_1W_2)+(\mathbf{b}_1W_2{+}\mathbf{b}_2) $$

Stacked linear layers = one linear layer. Without $f$, depth buys nothing. (ReLU's corner at 0 is its nonlinearity.)

hidden layersboundary you can draw
0straight line only
≥ 1closed / connected curves
≥ 2disjoint, arbitrary regions
universal approximation · 1989 $$ |g(\mathbf{x})-f(\mathbf{x})|\lt\varepsilon \quad\text{(one hidden layer suffices)} $$

Existence only — says nothing about width needed or learnability. Params grow $(L{-}1)n^2$: linear in depth, quadratic in width → deep beats wide.

CH 02 · Origins · parameter sharing

Convolution — one kernel, every position

discrete convolution $$ [f*g](i)=\sum_a f(a)\,g(i-a) \qquad V(x,y)=\sum_m\sum_n I(x{+}m,y{+}n)\,K(m,n) $$

The image version is really cross-correlation (no kernel flip) — identical for symmetric kernels.

kernel 3×3effect
sharpen0,−1,0 / −1,5,−1 / 0,−1,0 — boost contrast
blur(1/16)·[1,2,1 / 2,4,2 / 1,2,1] — smooth
outline−1 ring around 8 — all edges
Sobel1,2,1 / 0,0,0 / −1,−2,−1 — horizontal edges
fully connected vs conv
FCone weight per input×output — params scale with image size
Conv9 weights + 1 bias (3×3), any image size
biological root · hubel & wiesel

Cat visual cortex (1959, Nobel 1981): simple → complex → hypercomplex cells = kernel → stacked conv layers. Local receptive fields, hierarchy of features.

CH 03 · Neuron models · hagan notation

The general neuron and its dimensions

neuron → layer → network $$ a=f(\mathbf{Wp}+b) \qquad\Rightarrow\qquad \mathbf{a}^{l}=f^{l}\!\big(\mathbf{W}^{l}\mathbf{a}^{l-1}+\mathbf{b}^{l}\big),\;\; \mathbf{a}^0=\mathbf{p} $$

Whole feedforward net = composition: $\mathbf{a}^3=f^3(\mathbf{W}^3 f^2(\mathbf{W}^2 f^1(\mathbf{W}^1\mathbf{p}+\mathbf{b}^1)+\mathbf{b}^2)+\mathbf{b}^3)$

dimension check — free marks
$\mathbf p$ R×1$\mathbf W$ S×R $\mathbf b$ S×1$\mathbf n,\mathbf a$ S×1 S neurons · R inputs
depth — off-by-one trap

Depth = number of weight layers. Input layer computes nothing and is not counted. First $L{-}1$ layers hidden, last is output.

most realistic — hodgkin–huxley 1952 $$ I=C_m\frac{dV_m}{dt}+g_K(V_m{-}V_K)+g_{Na}(V_m{-}V_{Na})+g_l(V_m{-}V_l) $$

Membrane as RC circuit; Nobel 1963. Model spectrum: HH → … → integrate-and-fire → our neuron (only the I/O relation survives).

MCPgeneral
inputs{0,1}
weightsfixed ±1learnable
thresholdhand-set θbias b = −θ
activationhardlimany f

CH 03 · Neuron models · interactive

Activation functions — click to explore

solid = f(n) · dashed = f′(n)

namerangeuse
hardlim / hardlims{0,1} / {−1,1}perceptron
purelinregression, Adaline
satlin / satlins[0,1] / [−1,1]clipped linear
logsig(0,1)output prob.
tansig(−1,1)hidden (zero-centered)
poslin = ReLU[0,∞)deep nets
competone-hotwinner-take-all (layer-wise)
gradient rule of thumb

Corners (hardlim, satlin) break differentiability; sigmoids saturate; ReLU keeps gradient = 1 for n>0.

CH 03 · Neuron models · architectures

Static map vs dynamical system

feedforwardrecurrent phiddenout f(Wa+b) D p a(t)
recurrent dynamics + fixed point $$ \mathbf{a}(t{+}1)=f(\mathbf{W}\mathbf{a}(t)+\mathbf{b}),\quad \mathbf{a}(0)=\mathbf{p} \qquad\; \mathbf{a}^{*}=\mathbf{W}\mathbf{a}^{*}+\mathbf{b} $$
feedforwardrecurrent
computesstatic $a{=}F(p)$trajectory $a(t)$
feedbacknonedelay block D
needsinitial state $a(0)$
behaviorone passconverge · oscillate · diverge
recurrent ≠ deep

Depth counts forward weight layers; recurrence is feedback to an already-visited point. A 1-layer net can be fully recurrent.

layer receptive field

Fully connected → sees entire input. Convolutional → local subset. Same math $f(\mathbf{Wp}+\mathbf{b})$, different sparsity of W.

CH 04 · Perceptron · rosenblatt 1958

The boundary is a hyperplane — and w is normal to it

w a=1 a=0 wᵀp + b = 0
hand-design recipe

1. pick $\mathbf w$ ⊥ desired boundary, pointing at class 1 · 2. plug one boundary point into $\mathbf w^T\mathbf p+b=0$, solve $b$. Any positive scaling works — solutions not unique.

perceptron $$ \mathbf a=\mathrm{hardlim}(\mathbf W\mathbf p+\mathbf b),\qquad \mathrm{hardlim}(n)=\begin{cases}1 & n\ge 0\\ 0 & n\lt 0\end{cases} $$

Convention: $n=0$ outputs 1 — easy to miss under pressure.

why w ⊥ boundary $$ \mathbf w^T\mathbf p_a+b=0,\;\; \mathbf w^T\mathbf p_b+b=0 \;\Rightarrow\; \mathbf w^T(\mathbf p_a-\mathbf p_b)=0 $$
capacity

$S$ neurons → $S$-bit code → up to $2^S$ classes (upper bound, not all realizable). OR: $\mathbf w=[0.5,0.5]^T, b=-0.25$ · AND: $[1,1]^T, b=-1.5$

CH 04 · Perceptron · learning rule + convergence

Add the sample, subtract the sample

the rule — one line, three cases $$ e=t-a\in\{-1,0,1\}\qquad \mathbf w^{new}=\mathbf w^{old}+e\,\mathbf p,\quad b^{new}=b^{old}+e $$ $$ \text{matrix form: }\; \mathbf W^{new}=\mathbf W^{old}+\mathbf e\,\mathbf p^{T},\quad \mathbf b^{new}=\mathbf b^{old}+\mathbf e $$

Don't forget the bias update — top exam error. Trace protocol: show $n, a, e$ for every sample before updating.

errormeaningaction
e = +1said 0, truth 1w += p (pull toward)
e = −1said 1, truth 0w −= p (push away)
e = 0correctno change
novikoff convergence bound $$ \#\text{updates}\;\le\;\frac{R^{2}}{\gamma_g^{2}} \qquad (\|\mathbf p_i\|\le R,\ \text{margin }\gamma_g) $$

Proof skeleton: alignment grows linearly $\mathbf u^T\mathbf w^{(k)}\ge k\gamma_g$, norm grows as √k $\|\mathbf w^{(k)}\|\le\sqrt{k}R$; Cauchy–Schwarz squeezes $k\le R^2/\gamma_g^2$.

xor impossibility — contradiction

Need $b\lt0$, $w_1\ge-b$, $w_2\ge-b$ → $w_1{+}w_2{+}b\ge-b\gt0$, but XOR(1,1)=0 needs it $\lt0$. ∎ Converges iff linearly separable — else updates forever.

worked numbers
R=3, γ=0.5 → ≤36 updatesEx 4.2: 3 corrections

Part II · Chapters 5–8

Training

II

CH 05 · MLP · why hidden layers

Make the basis functions trainable

forward pass — index 0 is the bias unit $$ a_j=\sum_{i=0}^{D}w^{(1)}_{ji}x_i,\quad z_j=h(a_j) \qquad a_k=\sum_{j=0}^{M}w^{(2)}_{kj}z_j,\quad y_k=f(a_k) $$

Index convention: first = destination, second = source. Params: $M(D{+}1)+K(M{+}1)$.

glm vs mlp $$ y=f\Big(\textstyle\sum_i w_i\,\phi_i(\mathbf x)\Big)\;\longrightarrow\; y=f\Big(\textstyle\sum_i w_i\,\phi_i(\mathbf x,\mathbf w^{i})\Big) $$

GLM: features $\phi_i$ fixed by hand (engineering doesn't scale — $\binom{D+p}{p}$ monomials). MLP: hidden units are learned features.

output activationloss (from ML)task
identitySSE (Gaussian noise)regression
sigmoidbinary CE (Bernoulli)2-class
softmaxmulti-class CEK-class
three notes, three marks

1. all-linear layers collapse: $\sum_j w^{(2)}_{kj}w^{(1)}_{ji}=W_{ki}$ · 2. output $f$ only interprets range · 3. power lives in hidden nonlinearity.

two hidden families

Ridge (σ, tanh — global directions) vs RBF $e^{-\|\mathbf x-\boldsymbol\mu\|^2/2s^2}$ (local regions). tanh $=2\sigma(2a)-1$ — same model class.

CH 05 · MLP · the exam derivation

Backprop in four boxed steps

1 · local rule — gradient = δ × source activation $$ \frac{\partial E_n}{\partial w_{ki}}=\delta_k\,z_i \qquad \delta_k\equiv\frac{\partial E_n}{\partial a_k} $$

δ is sensitivity to the net input, not the weight gradient itself.

2 · output δ — all canonical pairs collapse $$ \delta_k = y_k - t_k $$

identity+SSE, sigmoid+BCE, softmax+CE — all give the same line (softmax: $\sum_k t_k{=}1$ one-hot).

3 · hidden δ — the backward recurrence $$ \boxed{\;\delta_i = h'(a_i)\sum_k w_{ki}\,\delta_k\;} $$

Sum over downstream units; reuses forward weights in reverse. Deep nets: apply per layer, $\delta^{(l)}_i=h'(a^{(l)}_i)\sum_k w^{(l+1)}_{ki}\delta^{(l+1)}_k$.

4 · first layer + update $$ \frac{\partial E_n}{\partial w^{(1)}_{ji}}=\delta_j\,x_i \qquad \mathbf w\leftarrow\mathbf w-\eta\,\nabla E $$

tanh: $h'(a)=1-z^2$. Cost: one multiply per weight — vs finite differences' full pass per weight.

CH 05 · MLP · symmetry · init · early stop

Non-convex, symmetric, overfittable

weight-space symmetry $$ 2^M\,M! \;\text{ equivalent minima} $$

permute hidden units (M!) × sign-flip odd activations ($2^M$). M=5 → 3840 copies of every minimum.

never zero-init

Equal weights → equal δ → identical updates forever → one effective hidden unit. Random init breaks the symmetry.

train validation stop here epoch

early stopping = capacity control by epochs

rules of the loss

$E(\mathbf w)$ non-convex → only local minima guaranteed; use random restarts. Validation set touches no gradients.

worked backprop numbers

x=(1, .5), tanh hidden: $z_1{=}.2913$, y=.1222, t=1 → $\delta_y{=}-.8778$, $\delta_1=h'(a_1)w^{(2)}_{11}\delta_y=-.4017$ — know how each number is produced.

CH 06 · SGD · three batch regimes

Noisy gradients are a feature

Training loss is a surrogate — the true target is unseen-data loss, so cheap noisy gradient estimates are legitimate.

batchstochasticmini-batch
mN132–512
gradientexactunbiased, very noisynoise ∝ 1/√m
cost/updateO(N)O(1)O(m)
near minimumstep → 0noise ball — needs η decay
sgd update + linear decay $$ \hat g\leftarrow\tfrac1m\nabla_\theta\textstyle\sum_i L_i,\quad \theta\leftarrow\theta-\epsilon_k\hat g \qquad \epsilon_k=(1{-}\alpha)\epsilon_0+\alpha\epsilon_\tau,\ \alpha=\tfrac{k}{\tau} $$
robbins–monro — when does SGD converge $$ \lim_{k\to\infty}\epsilon_k=0,\qquad \sum_k\epsilon_k=\infty,\qquad \sum_k\epsilon_k^2\lt\infty $$

Steps shrink, total travel unbounded, total noise variance bounded.

why mini-batch — both reasons for full credit

1. vectorized hardware (matrix–matrix ≫ matrix–vector) · 2. 1/√m noise reduction with diminishing returns (100× data → only 10× less noise). Stability: $\epsilon\lt 2/H$.

CH 06 · SGD · heavy ball 1964 · nesterov 1983

Velocity remembers ≈ 1/(1−α) gradients

classical momentum $$ v\leftarrow\alpha v-\epsilon\,\nabla_\theta J(\theta),\qquad \theta\leftarrow\theta+v $$

Sign trap: $v$ already contains $-\epsilon g$, so update is $\theta{+}v$. Unrolled: $v_t=-\epsilon\sum_i\alpha^i g_{t-i}$ — an EWMA. α=0.9 → horizon ≈10; α=0.99 → ≈100.

nesterov — look ahead first $$ \tilde\theta=\theta+\alpha v,\qquad v\leftarrow\alpha v-\epsilon\,\nabla_{\tilde\theta}J(\tilde\theta),\qquad \theta\leftarrow\theta+v $$

Only difference: gradient at $\tilde\theta$, not θ. First step identical when $v_0=0$. Faster on smooth convex problems.

momentum helps exactly when
high curvatureopposing gradients cancel → no zig-zag
small steady gaccumulates → bigger step
noisy gaveraged over horizon
the oscillation demo

$L=0.5w_1^2+10w_2^2$, ε=0.1: plain GD gives $w_2\leftarrow-w_2$ — oscillates forever; momentum (α=0.5) kills it in 2 steps. Cause: one shared ε capped by the steepest Hessian direction.

practice
SGD(lr=.01, momentum=.9, nesterov=True)

CH 07 · Adaptive rates · live race, real update rules

One η can't fit an anisotropic bowl

L = 0.05·w₁² + w₂² · start (−9, 2.6)

■ SGD · ■ momentum · ■ RMSProp · ■ Adam

adagrad — accumulate forever $$ r\leftarrow r+g\odot g,\qquad \Delta\theta=-\frac{\epsilon}{\delta+\sqrt r}\odot g $$

Equalizes scales, but $r$ only grows → η → 0 → premature stall on non-convex problems.

rmsprop — forget with an ewma $$ r\leftarrow\rho r+(1-\rho)\,g\odot g,\qquad \Delta\theta=-\frac{\epsilon}{\sqrt{\delta+r}}\odot g $$

ρ=0.9. Accumulator saturates at $g^2$ → effective rate stabilizes non-zero. All ops elementwise ⊙ — never $g^Tg$.

CH 07 · Adaptive rates · kingma & ba 2015

Adam = RMSProp + momentum + bias correction

adam — the full update $$ s\leftarrow\rho_1 s+(1{-}\rho_1)g \qquad r\leftarrow\rho_2 r+(1{-}\rho_2)g\odot g $$ $$ \hat s=\frac{s}{1-\rho_1^{\,t}},\quad \hat r=\frac{r}{1-\rho_2^{\,t}} \qquad \Delta\theta=-\epsilon\frac{\hat s}{\sqrt{\hat r}+\delta} $$

Why correct: zero-init EWMAs underestimate by $(1-\rho^t)$ — $\mathbb E[s^{(t)}]=\mathbb E[g](1-\rho_1^t)$; dividing removes the bias exactly, matters most at small $t$.

ε=0.001ρ₁=0.9ρ₂=0.999δ=1e-8
methodone-line identity
Delta-bar-deltagrow η if sign stable — full-batch only
AdaGrad÷√(sum g²) — rate dies
RMSProp÷√(EWMA g²) — the go-to
Adam+ 1st moment + bias fix
AdaDeltanumerator = RMS(Δθ) — no ε to tune
AdaMaxℓ∞ norm: u←max(ρ₂u,|g|)
NadamAdam + Nesterov look-ahead
empirics — no universal winner

Adam fastest early; tuned SGD+Nesterov often lowest at epoch 45; AdaGrad lags badly non-convex. Adaptive methods damp dropout noise.

CH 08 · Regularization · penalized loss

Shrink by percent or shrink by amount

l2 · weight decay $$ L+\tfrac{\lambda}{2}\textstyle\sum_j w_j^2 \;\Rightarrow\; w^{new}=(1-\eta\lambda)\,w^{old}-\eta\nabla_w f $$

Constant percentage shrink — never exact zeros. Gaussian prior, $\lambda=1/\sigma^2$. Unhalved penalty ⇒ $(1-2\eta\lambda)$ — watch the convention.

l1 · sparsity $$ L+\lambda\textstyle\sum_j|w_j| \;\Rightarrow\; w\leftarrow w-\eta\lambda\,\mathrm{sign}(w)-\eta\nabla_w f $$

Constant amount $\eta\lambda$ per step → exact zeros → feature selection. Laplace prior, $\lambda=1/b$.

never penalize biases

Biases don't multiply inputs — penalizing them just shifts outputs wrong.

L1 → corner, w₁=0 L2 → both ≠ 0
diagnosissignaturefix
underfitboth errors highcapacity / optimize
overfittrain low, val high (gap)regularize

CH 08 · Regularization · hinton 2012 · ioffe–szegedy 2015

Cripple the net, normalize the batch

dropout — forward, backward, test $$ h^{(k)}=g(a^{(k)})\odot\mathbf m^{(k)},\quad m_j\!\sim\!\text{Bern}(1{-}p) \qquad \nabla_{a}=\big(\nabla_h\odot g'\big)\odot\mathbf m $$

Same mask forward and backward (fresh mask = corrupted gradient). Output layer never masked. Test: scale by $1{-}p$, or inverted dropout $\tfrac{1}{1-p}$ at train.

why it works

Kills co-adaptation; trains an implicit ensemble of $2^{\#units}$ weight-sharing subnets; p=0.5 default. ≈ adaptive data-dependent L2.

batch norm — per unit, per mini-batch $$ \mu=\tfrac1m\textstyle\sum_i Z_i,\;\; \sigma^2=\tfrac1m\sum_i(Z_i{-}\mu)^2,\;\; \hat Z=\frac{Z-\mu}{\sqrt{\epsilon+\sigma^2}} $$ $$ H=\max\{0,\ \gamma\odot\hat Z+\beta\} $$

Between linear map and nonlinearity. γ, β can undo normalization ($\gamma{=}\sqrt{\epsilon+\sigma^2},\beta{=}\mu$) → capacity unchanged, only optimization dynamics.

test time + fine print

Inference uses running averages, not batch stats → deterministic. Batch noise = incidental regularizer; modern view (2018): benefit = smoother loss landscape, not covariate shift.

Part III · Chapters 9–11

Convolutional
Networks

III

CH 09 · CNNs · the workhorse formula, live

Output size & parameters — drag the sliders

the two formulas that always appear $$ O=\left\lfloor\frac{W-F+2P}{S}\right\rfloor+1 \qquad \#\text{params}=F{\cdot}F{\cdot}C_{in}{\cdot}C_{out}+C_{out} $$
7
3
1
2

forward pass · weight sharing $$ Z_{r,s}=f\!\Big(\sum_{i,j} w_{i-r,\,j-s}\,x_{i,j}\Big) $$

Weights independent of position (r,s) = sharing. DL "convolution" = cross-correlation (no flip) — irrelevant for learned kernels.

blue = kernel footprint · gray ring = zero padding

why not fully connected

Images are stationary — same local statistics everywhere. LeNet C1: conv = 156 params vs FC alternative > 4.8 M.

CH 09 · CNNs · favorite exam distinction

Equivariant conv, invariant-ish pooling

the distinction $$ \text{equivariance: } g(\mathrm{shift}(x))=\mathrm{shift}(g(x)) \qquad \text{invariance: } g(\mathrm{shift}(x))=g(x) $$

Convolution is equivariant to translation, NOT invariant. Pooling supplies local approximate invariance.

pooling facts

Fixed rule, zero parameters. Typically 2×2 stride 2. Max ≳ average empirically. Cost: precise positions unrecoverable after a few rounds — genuine trade-off.

mcnemar's test — comparing models $$ \chi^2=\frac{(|b-c|-1)^2}{b+c}\;\gt\;3.84 $$

Paired test on disagreements; same error totals can be significant (9²/12=6.75) or not (9²/40=2.03).

max vs average · worked 4×4 → 2×2
input 1 32 4 5 61 2 0 29 3 1 42 7 max 6 44 9 average 2.75 1.752.0  3.5
imagenet vs mnist — 5 axes harder
1000 classes100× pixels 3D scenescluttermulti-object

CH 09 · CNNs · landmark architectures

LeNet-5 → AlexNet — 14 years, same recipe

lenet-5 · 1998 · 82 errors on mnist · read ~10% of US checks
32×32×1input
6@28×28C1 · 5×5 · 156p
6@14×14S2 avg pool
16@10×10C3 partial conn.
16@5×5S4
120C5 conv=FC
84F6
10output
alexnet · 2012 · ilsvrc top-5 16.4% vs 26.1% runner-up
227×227×3"224" is errata
96@55×5511×11 s4
256@27×27conv+pool
13×13conv3–5
256@6×6pool
4096 ×2FC + dropout
1000softmax
alexnet's 5 ingredients

ReLU · local response norm · dropout p=.5 in FC · augmentation (crops+flips, 10-patch test) · 2× GTX 580 GPUs

dimension check (exam!)

$\lfloor(224{-}11)/4\rfloor{+}1=54\ne55$; solving gives $W=227$.

canonical pattern

[conv+ReLU ×n → pool]* → flatten → FC → softmax. Spatial ↓ while channels ↑ — resolution traded for representation.

CH 10 · CNN backprop · the headline results

Shared weight ⇒ sum over every reuse

forward · 4-D kernel, stride s $$ Z_{i,j,k}=\sum_{l,m,n} V_{l,(j-1)s+m,\,(k-1)s+n}\;K_{i,l,m,n} $$
gradient w.r.t. kernel — updates the layer $$ \frac{\partial J}{\partial K_{i,j,k,l}}=g(\mathbf G,\mathbf V,s)=\sum_{m,n} G_{i,m,n}\,V_{j,(m-1)s+k,\,(n-1)s+l} $$

FC: each weight used once → single product $g_ih_j$. Conv: kernel reused at every position → sum over all positions.

gradient w.r.t. input — passes upstream $$ \frac{\partial J}{\partial V}=h(\mathbf K,\mathbf G,s) \;=\; \text{transposed conv with }180^\circ\text{-flipped kernel} $$

Same op used forward as upsampling (segmentation, generative nets). "Deconvolution" is not an inverse — it's $W^\top$, not $W^{-1}$.

what comes out of backward
conv layer2 gradients: ∂J/∂K + ∂J/∂V
pooling layer1 gradient: ∂J/∂V only (no params)
the universal primitive $$ \texttt{op.bprop}=\sum_i(\nabla_X\,\texttt{op.f})_i\,G_i \quad\text{(vector–Jacobian product)} $$

Generic backprop: recurse over consumers with a memo table; cost ∝ #edges ≈ forward pass. Symbol-to-symbol graphs enable higher-order grads.

worked check (know it)

V 3×3, K=[[1,0],[−1,2]], G=[[1,−1],[2,0]] → ∂J/∂K=[[−1,4],[3,0]], ∂J/∂V=[[1,−1,0],[1,3,−2],[−2,4,0]].

CH 10 · CNN backprop · routing the gradient

Max routes, average splits

pooling gradients $$ \text{max: } \frac{\partial J}{\partial V_c}=\sum_{W\ni c} G_W\,[\,c=\arg\max_{c'\in W}V_{c'}] \qquad \text{avg: } \sum_{W\ni c}\frac{G_W}{|W|} $$

Common mistake: dividing the max gradient by window size. All of $G$ goes to the argmax; losers get exactly 0 — and zero training signal.

∇P 1 23 4 ∇V (argmax cells only) 0 00 2 0 10 0 0 04 0 0 30 0

worked ex 10.3 — each G lands on its window's max

sharing spectrum · who owns weights
fully connectedno locality, no sharing
locally connectedlocal, private per position
tiled (period t)t kernels cycle; bias $C_{out}{\times}t{\times}t$
standard convt=1 · full sharing · bias $C_{out}$
strided conv forward $$ Z_{i,j,k}=\sum_{l,m,n}V_{l,(j-1)s+m,(k-1)s+n}K_{i,l,m,n} $$

Index shift $j{+}m{-}1\to(j{-}1)s{+}m$; s=1 recovers standard. Can replace pooling.

differentiability

Max pool: a.e. differentiable (ties = measure zero). Average: smooth everywhere.

CH 11 · CNN design · three structural priors

Sparse, shared, equivariant

320×280 img · 2×1 kernelstored floatsops
dense matrix> 8×10⁹> 16×10⁹
sparse matrix178,640267,960
convolution2267,960

Sparsity fixes the op count; only sharing fixes storage — the sparse→conv gap is entirely parameter sharing.

param spectrum · 5 in → 4 out, kernel 2
FC 20local 8 tiled t=2 4conv 2
receptive field grows with depth

Width-3 kernels: layer-2 unit already sees 5 inputs. Deep stacks of small kernels capture long-range structure.

padding decides depth $$ W-(F-1)L\ \ge\ F \quad\Rightarrow\quad 32-4L\ge5 \Rightarrow L\le6 $$

No padding: lose $F{-}1$ width per layer → forced shallow. "Same" padding → arbitrarily deep.

layer anatomy — fixed order
convaffine
detectorReLU
poolinvariance

CH 11 · CNN design · from trunk to prediction

Three heads, four families, one skip

head (trunk → 16×16×64)extra paramsvar. size?
flatten + dense 1000≈ 16.4 Mno
pool to 3×3 + dense≈ 0.58 Myes
fully conv + global avg pool≈ 0yes
familyone-line identity
spatial transducerfully convolutional, no dense anywhere
all-convolutionalno pooling — strided conv downsamples
Inceptionparallel multi-scale kernels per stage
ResNetadditive identity skips → extreme depth
conv·ReLU conv + identity → ReLU

y = ReLU( x + F(x) ) — gradient rides the skip undiminished

biology, briefly

Trained first-layer kernels ≈ Gabor functions (V1 simple cells) — real but limited analogy: first layer only, backprop implausible.

Part IV · Chapters 12–14

Sequence Models

IV

CH 12 · RNNs · three matrices, any length

Share weights across time

h = h₁ x₁ ŷ₁ h₂ x₂ ŷ₂ h₃ x₃ ŷ₃ WₕₕWₕₕ WₓₕWₕᵧ

folded self-loop = unrolled chain · same three matrices at every step

vanilla rnn $$ h_t=\tanh\!\big(W_{hh}h_{t-1}+W_{xh}x_t\big),\qquad \hat y_t=W_{hy}h_t $$

$h_t$ is an activation, not a parameter — init to zeros, reset between sequences (stale-context bug).

4 design criteria (naive ideas fail)
variable length✓ recurrence
long-term deps✗ fixed window
order matters✗ bag-of-words
share params✗ big slotted window
param math

|V|=10k, window 20, H=100: slotted = 20 M weights; shared = 1 M, independent of length. CNN shares across space, RNN across time.

CH 12 · RNNs · karpathy taxonomy

Four wirings, one cell

1→1 · image cls 1→n · captioning n→1 · sentiment n→n · tagging

two axes only: input single/sequence × output single/sequence — cell equations never change

loss across time $$ L=\sum_{t=1}^{T}L_t \qquad \frac{\partial L}{\partial W_{hh}}=\sum_{t=1}^{T}\frac{\partial L_t}{\partial W_{hh}} $$

Each shared weight collects one gradient contribution per step used — that sum is BPTT.

synced ≠ general n→n

Aligned equal-length (POS tags, music) works directly; translation needs encoder–decoder — whole input → one bottleneck vector → decode.

CH 13 · BPTT · werbos 1990

A product of Jacobians — geometric fate

backward recursion — direct + indirect path $$ g_t=\underbrace{W_{hy}^{\top}\delta_t^{y}}_{\text{via }\hat y_t}+\underbrace{W_{hh}^{\top}\big(g_{t+1}\odot\tanh'(a_{t+1})\big)}_{\text{from the future}} $$

Recurrent term absent only at $t{=}T$. Omitting it = most common error. Then $\partial L/\partial W_{hh}=\sum_t\delta_t^a h_{t-1}^\top$ with $\delta_t^a=g_t\odot(1-h_t^2)$.

why gradients die (or explode) $$ \frac{\partial h_k}{\partial h_t}=\prod_{i=t+1}^{k}\mathrm{diag}\big(\tanh'(a_i)\big)W_{hh},\qquad \Big\|\tfrac{\partial h_k}{\partial h_t}\Big\|\le\rho^{\,k-t} $$

$\rho\gt1$ → explode; $\rho\lt1$ (typical — $|\tanh'|\le1$) → vanish. Systematic bias toward short-term deps: "clouds → sky" survives, "France → French" dies.

exploding fix — clipping $$ \tilde g=g\cdot\min\!\Big(1,\tfrac{\text{thr}}{\|g\|_2}\Big) \quad\text{(norm, keeps direction)} $$

By value: $\mathrm{sign}(g_i)\min(|g_i|,\text{thr})$ — can bend direction. Clipping cannot fix vanishing — it only shrinks. Classic trap.

vanishing remedies, ranked
ReLUf′=1 for a>0, but W_hh untouched
identity initW_hh=I — drifts during training
gated cellsthe only architectural fix →
feel the decay
×0.6/step → 0.13 after 4σ′ ≤ 0.25tanh′ ≤ 1

CH 13 · LSTM · hochreiter & schmidhuber 1997 · hover a gate

A protected cell-state highway

c(t−1) c(t) × σ f + × σ i tanh c̃ σ o × tanh h(t) x(t), h(t−1)

memory crosses time through × and + only — never a matrix multiply

1 · forget $$ f_t=\sigma(W_f h_{t-1}+U_f x_t+b_f) $$
2 · store → 3 · update $$ i_t=\sigma(\cdot),\;\; \tilde c_t=\tanh(\cdot) \qquad c_t=f_t\odot c_{t-1}+i_t\odot\tilde c_t $$
4 · output $$ o_t=\sigma(\cdot),\qquad h_t=o_t\odot\tanh(c_t) $$
why it survives time $$ \partial c_t/\partial c_{t-1}\approx\mathrm{diag}(f_t) $$

No $W_{hh}$ factor — with $f_t\!\approx\!1$ the product needn't vanish. Two states $(c_t,h_t)$; the weights of vanilla.

CH 13 · GRU · cho et al. 2014

Two gates, one state — the final table

gru — interpolation replaces forget+input $$ r_t=\sigma(W_r h_{t-1}+U_r x_t+b_r),\qquad z_t=\sigma(W_z h_{t-1}+U_z x_t+b_z) $$ $$ \tilde h_t=\tanh\big(W_h(r_t\odot h_{t-1})+U_h x_t+b_h\big) $$ $$ h_t=(1-z_t)\odot h_{t-1}+z_t\odot\tilde h_t $$

$z_t$ couples keep/write ($1{-}z_t$ and $z_t$ sum to 1) ≈ combined $f_t,i_t$; $r_t$ gates the candidate's view of the past; no output gate, no $c_t$.

which to pick

Empirically comparable. GRU cheaper (3× weight sets); LSTM can keep old memory and write lots of new info at once — GRU's coupling can't. Neither universally wins.

vanilla RNNLSTMGRU
state$h_t$$c_t$ + $h_t$$h_t$
gatesf, i, o + c̃r, z + h̃
updatefull overwriteadditiveinterpolation
memory Jacobiandiag(tanh′)·Whh≈ diag(ft)≈ diag(1−zt)
vanishingseveremitigatedmitigated
weight sets
worked step — same inputs, both cells

$h_{t-1}{=}.5, c_{t-1}{=}.2, x_t{=}1$: LSTM → $f{=}.818, i{=}.777, \tilde c{=}.762, c_t{=}.755, h_t{=}\mathbf{.522}$ · GRU → $r{=}.818, z{=}.777, \tilde h{=}.721, h_t{=}\mathbf{.672}$

CH 14 · Transformers · vaswani et al. 2017

Attention — a soft dictionary lookup

scaled dot-product attention $$ \mathrm{Attention}(Q,K,V)=\mathrm{softmax}\!\Big(\frac{QK^{T}}{\sqrt{d_k}}\Big)V $$

Each query scores every key by dot product; softmax turns scores into weights; output = weighted average of values. A dictionary lookup, but soft — every entry contributes.

why divide by √dk $$ q\!\cdot\!k=\textstyle\sum_{i=1}^{d_k} q_i k_i \;\Rightarrow\; \mathrm{Var}(q\!\cdot\!k)=d_k $$

Dot products grow with dimension → softmax saturates at one-hot → gradients vanish. Scaling keeps variance ≈ 1. Same saturation story as sigmoids in ch 3.

tensorroleasks
Q querywhat I'm looking for"who is relevant to me?"
K keywhat I advertise"match me against queries"
V valuewhat I hand over"take this if I win"
the seq2seq bottleneck it fixes

Encoder–decoder RNNs squeeze the whole source sentence into one fixed vector — long sentences degrade. Attention lets the decoder look back at all encoder states, weighted per step (Bahdanau 2014).

cost
scores n×ntime O(n²d)path length O(1)

CH 14 · Transformers · self-attention · heads · position

The sequence attends to itself

self-attention — Q, K, V from the same X $$ Q=XW^{Q},\quad K=XW^{K},\quad V=XW^{V} $$

Every token queries every token — including itself. The three learned projections let "what I seek", "what I show" and "what I give" differ; without them attention would be plain symmetric similarity.

multi-head — h parallel subspaces $$ \mathrm{head}_i=\mathrm{Attn}(XW_i^{Q},XW_i^{K},XW_i^{V}),\quad \mathrm{MH}=\mathrm{concat}(\mathrm{head}_1..\mathrm{head}_h)W^{O} $$

$d_k=d_{model}/h$ (512/8 = 64): h views for ≈ the price of one full-width head. Heads specialize — syntax, coreference, position — emergently, never by supervision.

positional encoding — order must be injected $$ PE_{(pos,2i)}=\sin\!\frac{pos}{10000^{2i/d}},\qquad PE_{(pos,2i+1)}=\cos\!\frac{pos}{10000^{2i/d}} $$

Self-attention is permutation-equivariant — shuffle the tokens, outputs shuffle identically. Adding a position fingerprint to each embedding breaks the tie.

why sinusoids

Geometric wavelengths $2\pi\!\to\!10000\!\cdot\!2\pi$: each position gets a unique multi-frequency code, and $PE_{pos+k}$ is a linear function of $PE_{pos}$ — relative offsets are easy to learn. Learned position embeddings work equally well (BERT uses them).

exam trap

"Multi-head = more parameters" — false. Heads split $d_{model}$; total projection cost stays ≈ constant. The win is diversity of attention patterns, not capacity.

CH 14 · Transformers · attention is all you need

The block — and why it retired the RNN

input + positional enc. multi-head self-attn add & layer norm feed-forward ×4 add & layer norm ×N

residual skips (dashed) = the gradient highway

RNN / LSTMTransformer
max path lengthO(n)O(1)
sequential opsO(n) — no parallel trainO(1) — fully parallel
per-layer costO(n·d²)O(n²·d) — length hurts
order handlingbuilt-in recurrenceinjected via PE
long memorygated (ch 13)direct access
decoder — causal mask $$ \mathrm{score}_{ij}=\begin{cases}q_i\!\cdot\!k_j/\sqrt{d_k} & j\le i\\[2pt] -\infty & j\gt i\end{cases} $$

−∞ before softmax → weight exactly 0: no peeking at the future. Plus cross-attention: Q from decoder, K,V from encoder.

lineage
BERT — encoder, masked LMGPT — decoder, causalViT — patches as tokens

Finale · if you remember nothing else

The whole course in ten formulas

1 · neuron$$ y=f(\mathbf w^{T}\mathbf x+b) $$
2 · perceptron rule$$ \mathbf w\!\leftarrow\!\mathbf w+(t-a)\mathbf p,\;\; b\!\leftarrow\!b+e $$
3 · backprop δ$$ \delta_i=h'(a_i)\textstyle\sum_k w_{ki}\delta_k,\;\; \delta^{out}=y-t $$
4 · momentum$$ v\!\leftarrow\!\alpha v-\epsilon g,\;\; \theta\!\leftarrow\!\theta+v $$
5 · adam$$ \Delta\theta=-\epsilon\,\hat s\,/(\sqrt{\hat r}+\delta) $$
6 · weight decay$$ w\!\leftarrow\!(1-\eta\lambda)w-\eta\nabla f $$
7 · conv size$$ O=\lfloor(W\!-\!F\!+\!2P)/S\rfloor+1 $$
8 · bptt fate$$ \|\partial h_k/\partial h_t\|\le\rho^{\,k-t} $$
9 · lstm heart$$ c_t=f_t\odot c_{t-1}+i_t\odot\tilde c_t $$
10 · attention — where the story goes next$$ \mathrm{Attention}(Q,K,V)=\mathrm{softmax}\!\big(QK^{T}\!/\sqrt{d_k}\big)V $$

Press R and run the deck again — if you can recall each card from its label alone, you're ready. Good luck. Σ

RECALL move · T contents · R recall · M more 1/1