Deep Learning: Training Dynamics & Vision
A deep network is nothing but a composition of affine maps and elementwise nonlinearities; training it is plain gradient descent. Two facts make that practical: backprop computes every gradient in one backward sweep (reverse-mode autodiff on the computation graph), and a stack of techniques — initialization, normalization, adaptive optimizers, regularization — keeps that gradient well-scaled so the net actually converges and generalizes. A single thread runs through the whole subject: in a deep net the gradient to an early layer is a product of Jacobians, and almost every trick here (ReLU, He init, batch norm, residual connections) exists to keep that product near 1. The second half specializes the architecture to images — convolution bakes in locality and translation equivariance — and closes on a unifying capstone: backprop differentiates w.r.t. anything in the graph, including the input, which gives adversarial examples, saliency, style transfer, and GANs. Prerequisites cashed in: logistic regression and cross-entropy (tracks 4, 6); the chain rule, Jacobians, , norms (track 2); SGD and the convex/non-convex split (track 10); bias–variance (track 6); MLE (track 3).
1. From a neuron to a deep network
- A neuron is logistic regression. Pre-activation , activation . With this is exactly the logistic unit of track 4. Stack neurons side by side into a layer (vectorize: , rows of are the individual neurons’ weights), and stack layers in sequence. The whole network is a composition
Layer indices are bracketed ; training examples parenthesized ; stacking examples as columns of vectorizes everything (, broadcasting ).
- Why a nonlinearity is non-negotiable. Compose two affine maps and you get an affine map: . Without , an -layer net collapses to a single linear layer — depth buys nothing. The nonlinearity is the entire source of expressive power.
- Why depth — hierarchical representation. Each layer’s output is a richer encoding of the input than its own input: layer 1 fires on edges, layer 2 on parts (eyes, corners), layer 3 on objects. Depth lets features be reused compositionally, which is exponentially more parameter-efficient than width for the functions that occur in practice. “Deep learning” is representation learning: the net discovers the intermediate features instead of being handed them.
- Activations, judged by their derivative (because multiplies into every backprop step, §2 — a saturating throttles learning):
- sigmoid , derivative . Saturates to gradient in both tails, and its output is not zero-centered (biases the next layer’s gradients). Use only at a binary output, never in hidden layers.
- tanh , derivative . Zero-centered (strictly better hidden unit than sigmoid) but still saturates in the tails.
- ReLU , derivative . No saturation for — the gradient passes through undamped — so learning is fast; this single change (sigmoid → ReLU) is the biggest reason deep nets became trainable. Risk: a unit stuck at is “dead” (zero gradient forever); Leaky ReLU keeps a small negative slope to avoid it.
- Output layer matches the task: sigmoid + binary cross-entropy (two classes), softmax + cross-entropy (multiclass), linear + squared error (regression).
Implications
- A deep net is a parameterized function class; everything downstream is fitting it (§2–5) or structuring it (§6).
- The activation choice is a gradient-flow decision, not a modeling nicety — it reappears as the vanishing-gradient story in §2 and motivates ReLU, batch norm, and residual connections.
Core competency set
- Write a layer’s forward map and the full-network composition; explain why removing collapses depth.
- State and rank the three by gradient flow; say why ReLU fixed trainability.
2. Backpropagation = reverse-mode autodiff
- The training loop. Forward pass: evaluate and the scalar cost . Backward pass: compute . Update: . Backprop is just the efficient way to do the middle step.
- The computation graph. Write as a DAG of elementary operations. The forward pass evaluates it left-to-right; the backward pass applies the chain rule right-to-left, caching and reusing every intermediate. Key efficiency fact: one backward pass costs the same as one forward pass, versus separate evaluations for finite differences — this is why training billion-parameter nets is feasible at all.
- One layer, with the trick. Setup: , , scalar loss . Define the local error signal — the gradient sitting just below the nonlinearity. The upstream gradient arrives from the layer above. Push it through the activation:
( = elementwise, since acts coordinatewise). Then to the parameters:
and the signal handed down to the layer below:
That last line is the next layer’s upstream gradient — backprop is this block repeated down the stack.
- The shape convention. A textbook Jacobian of a scalar w.r.t. a matrix would be a row vector of length — useless for the update . NN convention: the gradient takes the shape of its parameter, so is and the update is elementwise. The outer product is exactly what makes the dimensions line up (error signal input signal).
- Reverse-mode in general. Initialize the output gradient to 1, visit nodes in reverse topological order; each node receives the upstream , multiplies by its local Jacobian , and passes the result down. Gate behavior: a + node distributes the upstream gradient unchanged, a max node routes it to the arg-max input only, a × node switches the inputs; fan-out sums (a value used in two places sums the two upstream gradients).
- Worked: logistic / softmax gradient. With cross-entropy on top of sigmoid (or softmax), the messy and collapse:
i.e. the error signal is just predicted minus observed. Then . (This observed − expected form recurs everywhere — softmax, and the word2vec gradient of 11b.)
- Numeric anchor (one logistic neuron): , , , label . Forward: , . Backward: , . One step (): — nudging up toward , as it should.
- Picture (draw it): the computation graph — a DAG with inputs and weights as source nodes and operations as interior nodes; the forward pass flows values left→right to the scalar loss, the backward pass flows gradients right→left, each node multiplying the upstream gradient by its local derivative. A + node copies the gradient to both inputs, a max routes it to the winner only, a × swaps the two inputs.
- Vanishing / exploding gradients. Unrolling backprop, the gradient reaching an early layer is a product of Jacobians
Repeated multiplication is unstable: factors with magnitude drive the product (and the early-layer gradient) to — those layers stop learning, and signal from far back is lost; factors blow it up to overflow. Exploding is patched bluntly by gradient clipping (rescale if exceeds a threshold); vanishing is the harder one, and §1’s ReLU plus §4’s init/batch-norm and §6’s residual connections are all aimed at keeping this product near 1.
Implications
- Backprop is mechanical once the forward graph is written — modern frameworks autodiff it; the skill is reading off , , .
- The Jacobian-product view is the single lens unifying the rest of the guide’s training tricks.
Core competency set
- Derive the four backprop equations for one layer with the trick; state the shape convention and why .
- Give the gate rules (+, max, ×, fan-out) and the simplification.
- Explain vanishing/exploding as a Jacobian product and name clipping vs the structural fixes.
3. Optimization — escaping saddles, not local minima
- The loss surface is non-convex — but that’s not the obstacle you’d expect. Unlike track 10, has no convexity guarantee. Yet gradient descent works, because in high dimensions a critical point is almost never a local minimum: being a min requires the curvature to be positive in all directions, and with in the millions the overwhelmingly likely critical points are saddle points (mixed curvature) and plateaus (near-flat regions). So the optimizer’s real job is to cross saddles and plateaus quickly — which is what momentum and adaptive methods buy. Picture (draw it): a saddle — a surface curving up along one axis and down along another (a Pringle); the gradient vanishes at the center but it is not a minimum. In high dimensions almost every flat point looks like this, so progress means sliding off along the down direction — which momentum’s accumulated velocity carries you through.
- Minibatch SGD. Full-batch GD is one exact step per pass over all examples — too slow at scale. Pure SGD (batch = 1) throws away vectorization and jitters wildly. Minibatches of 64–512 are the practical middle: vectorized speed plus frequent, slightly noisy steps (the noise itself helps jump saddles). One epoch = one pass through the data; the cost curve is jittery, not monotone, since each step sees a different batch. Batch size a power of 2 to fit hardware; → just use full batch.
- Exponentially weighted average — the shared building block.
averages roughly the last values ( ~10). Initialized at it underestimates early; bias-correct with (denominator as grows).
- Momentum — average the gradient, then step. On iteration :
On an elliptical bowl GD zig-zags across the narrow axis; averaging cancels the oscillating component while the consistent down-valley component accumulates — faster, smoother. (Mechanical picture: is acceleration, velocity, friction.)
- RMSprop — equalize step sizes per coordinate by dividing out the recent gradient magnitude:
Large-gradient directions get damped, small-gradient directions sped up.
- Adam = momentum + RMSprop with bias correction. On iteration :
Defaults ; tune . The default first choice for most nets.
- Learning-rate decay, e.g. : big steps early to traverse the landscape, small steps late to settle into a tight neighborhood instead of orbiting the minimum.
Implications
- Non-convexity is survivable because saddles, not bad minima, dominate — and noise + momentum cross saddles.
- Adam is EWMA applied twice (to the gradient and to its square); knowing the EWMA primitive collapses momentum/RMSprop/Adam into one idea.
Core competency set
- Argue why high-dimensional critical points are saddles, and why minibatch noise helps.
- Write EWMA + bias correction, and the momentum / RMSprop / Adam updates from it; give Adam’s defaults.
4. Making training work — initialization & normalization
- The init problem, straight from §2. Forward activations and backward gradients both scale like a product of ‘s; too-large weights explode them, too-small weights vanish them. Goal: choose the initial weight scale so the variance is preserved across layers, forward and backward.
- The variance argument. For with independent, zero-mean, unit-variance inputs and weights,
To hold , set :
- Xavier (tanh/sigmoid): , or to balance the forward and backward passes at once.
- He (ReLU): — the extra factor 2 because ReLU zeros roughly half its inputs, halving the variance that survives.
- In code:
W = randn(shape) * sqrt(2 / n_prev). Numeric anchor: a layer with ReLU inputs → , i.e. initialize from , sd . (Xavier would use , sd — smaller, matched to tanh, which doesn’t zero half its inputs.) - Input normalization. Subtract the mean, divide by the std (statistics from the training set, applied identically to dev/test). Unnormalized features stretch the loss contours into long ellipses, so GD zig-zags and needs a tiny learning rate; normalized features round the contours and let GD head almost straight to the minimum.
- Batch normalization — normalize the pre-activations of each layer within the minibatch, then give the network back the freedom to rescale. For layer over a minibatch:
are learned (so the layer can recover any mean/variance it needs — even undo the normalization by ); the bias becomes redundant and is dropped. Which axis: the statistics are computed per feature, across the batch (and any spatial/sequence positions), so have one entry per feature — this batch-coupling is exactly why there’s no batch to use at test time. Why it helps: each layer’s input distribution stays stable as earlier layers update (less internal covariate shift), so deep layers aren’t chasing a moving target; it also smooths the loss landscape and adds mild regularization (each batch’s stats are noisy). At test time there’s no batch — use the exponentially weighted running accumulated during training. (Contrast layer norm, which normalizes each example across its own features — batch-independent, the right choice for sequences; full comparison and the pre/post-norm placement question in 11b §6.)
- Gradient checking (debugging only, never training): centered difference has error (vs one-sided); compare to backprop and expect . Include any regularizer; turn off dropout (its randomness breaks the check).
Implications
- Init, input norm, and batch norm are the same move at different points — hold the signal’s variance near 1 so the Jacobian product of §2 doesn’t drift.
- Batch norm decouples layers, which is why it lets you train deeper nets with larger learning rates and less init care.
Core competency set
- Derive and give Xavier vs He (and why He’s factor 2).
- Write the four batch-norm equations, say why and why drops, and what happens at test time.
5. Generalization & regularization
- The deep-learning puzzle. A large net can memorize random labels (zero training error) yet still generalize on real data — the classic bias–variance U-curve doesn’t cleanly describe the over-parameterized regime. Practical diagnosis still uses the two numbers: high training error → underfitting / bias; low training but high dev error → overfitting / variance; both high → both problems.
- The orthogonal recipe. Fix bias first (look at training fit: bigger net, train longer, better architecture), then variance (look at the dev gap: more data, regularize). Different levers for different problems — diagnose before treating. In DL the two are largely decoupled: a bigger net cuts bias and more data cuts variance, each at little cost to the other.
- L2 / weight decay. Add to . Its gradient contributes , so the update becomes
— is multiplied by a factor just under 1 each step (“decay”) before the data gradient. Shrinking weights yields a smaller effective network (many units near-off) and pushes tanh units into their near-linear region → a smoother decision boundary.
- Dropout. At training, zero each unit independently with probability ; inverted dropout divides the surviving activations by so the expected activation is unchanged. At test, run the full network (no dropout). Two readings: (1) it trains an ensemble of weight-sharing subnetworks; (2) it prevents co-adaptation — a unit can’t count on any specific partner surviving, so weight spreads across units (an L2-like shrinkage). Heavy in computer vision (chronically data-starved); elsewhere reach for it once you see overfitting. Costs the monotone-cost debugging signal (turn it off to sanity-check ).
- Early stopping: halt at the dev-error minimum. Equivalent to limiting how far travels from its small init (≈ implicit L2). Downside: it couples fitting and regularizing into one knob (non-orthogonal), so L2 + full training is often cleaner.
- Data augmentation: cheap label-preserving input transforms (mirror, crop, color shift) enlarge the dataset — but only label-preserving ones (rotating a handwritten 6 into a 9 corrupts the label).
Implications
- L2, dropout, early stopping, and augmentation all reduce effective capacity or enlarge effective data — the two halves of the variance fix.
- The “memorize yet generalize” phenomenon is why DL regularization is applied empirically (watch the dev gap), not derived from a capacity bound.
Core competency set
- Diagnose bias vs variance from train/dev errors and give the orthogonal recipe.
- Show L2 = weight decay ; explain inverted dropout (÷, off at test) and its two interpretations.
6. Convolutional networks
-
Why not fully connected on images. A image is 3M inputs; a single FC layer to even 1000 units is billions of weights — untrainable and hopeless on limited data. Two structural priors fix it:
- parameter sharing — a feature detector useful at one location is useful everywhere, so slide one small filter across the whole image (one weight set for all positions);
- sparse connectivity — each output depends only on a small local receptive field.
Together they give translation equivariance (shift the input → the feature map shifts) and slash the parameter count.
-
Convolution mechanics. A filter of size slides over the input volume; at each position take the elementwise product-and-sum to one scalar. The filter’s depth always equals the input’s channel count; each filter produces one 2D feature map; stacking filters gives output depth . Worked (vertical-edge filter): convolving a left-bright/right-dark region with the filter yields a bright stripe exactly at the edge (elsewhere the products cancel) — and these filter weights are learned, not hand-set.
-
Conv arithmetic (memorize). Output side length
Padding: valid (, image shrinks and edge pixels are under-counted) vs same ( with odd , preserves size). Parameters in a conv layer: — independent of image size (the sharing payoff).
- Numeric anchor (LeNet conv-1): input , , , , filters. Output side → volume . Parameters — versus a fully-connected layer to the same outputs, which would need weights. That gap is the sharing payoff.
- Picture (draw it): one small filter sliding across the input volume, dotting into a single scalar at each stop to paint one 2D feature map; stack such filters (each its own slid kernel) for the output depth. The same weights at every position is the parameter sharing; the small window is the sparse connectivity.
- Pooling: downsample each channel over an window with stride (max — keep the strongest activation; or average), no learnable parameters, output . Shrinks H×W and adds a little translation invariance.
- Typical architecture: ; spatial size shrinks while channel depth grows.
- The classic ladder.
- LeNet-5 (~60k params): the conv–pool–conv–pool–FC template, on digits.
- AlexNet (~60M): much bigger, ReLU — launched the deep-vision era.
- VGG: uniform same-convs, doubling channels / halving spatial at each block — depth through uniformity (~138M params).
- ResNet — the key idea. A residual block adds a skip connection around two layers:
Now the identity is *free*: $W^{[l+2]} = 0$ gives $a^{[l+2]} = a^{[l]}$, so extra layers can never hurt and the block only has to learn a *residual* on top of the identity. The skip is also a direct gradient path back (the additive term keeps the Jacobian product near 1), which is what finally made 100+-layer nets train — training error decreases monotonically with depth instead of the empirical U-curve. (Dimension mismatch on the skip: insert a $W_s a^{[l]}$.) *Same additive gradient-highway idea as the LSTM cell, 11b.*
- convolution (“network in network”): a per-pixel FC across depth — multiplies/sums across channels. Cheap way to reduce the channel count (or just add a nonlinearity at fixed depth).
- Inception: run , , , and pooling in parallel and concatenate — let the net pick the filter size. A “bottleneck” before the big filters cuts compute ~10× (e.g. channels conv).
- Transfer learning — almost always the right move. Take an ImageNet-pretrained net, replace the final layer with your classes, freeze early layers (generic edges/textures), and train the rest; with more data, unfreeze more. Strong performance even on small datasets.
- Application — detection. Localization adds bounding-box outputs to the class: target , where flags object-present (and when the rest is “don’t care”). YOLO lays a grid on the image and predicts one such vector per cell in a single forward pass (object assigned to the cell holding its midpoint). IoU = intersection/union of boxes scores overlap (correct if ). Non-max suppression keeps the highest- box and discards others overlapping it (IoU ), removing duplicate detections. Anchor boxes give each cell several box shapes so it can predict multiple overlapping objects.
- Application — face recognition. It’s a one-shot problem (recognize a person from a single enrolled photo), so learn an encoding, not a classifier. A Siamese network maps each image to ; similarity is . Triplet loss trains it on (Anchor, Positive, Negative):
Pull anchor–positive together, push anchor–negative apart, by a margin — the margin is what blocks the trivial all-zero encoding (same margin idea as the SVM, track 6). Mine hard triplets () or gradient descent has nothing to do.
Implications
- Convolution is an architectural prior — sharing + locality — that encodes “images are translation-equivariant,” cutting parameters by orders of magnitude.
- ResNet’s skip connection is the §2 Jacobian-product fix made structural; it recurs as the LSTM cell highway in 11b.
Core competency set
- State the two CNN priors and the conv output-size and parameter-count formulas; same vs valid padding.
- Explain the residual block: why identity is free and why it fixes deep training.
- Give the detection toolkit (YOLO/IoU/NMS/anchors) and the Siamese + triplet-loss recipe with the role of .
7. Gradients beyond the weights
- The unifying move. Backprop computes the gradient w.r.t. any node of the graph. Freeze the weights and differentiate w.r.t. the input , and a whole family of techniques drops out.
- Adversarial examples. Find an input classified wrongly while staying near a real image. The fast gradient sign method perturbs every pixel by along the loss gradient’s sign:
Why a tiny perturbation flips the prediction: its effect on a logit is , which grows with dimension — so a change imperceptible per-pixel moves the output a lot in high dimensions. Defense: adversarial training, adding to the loss.
- Interpretability via input gradients.
- Saliency map: over pixels — use the pre-softmax score (it depends only on class ‘s evidence, whereas post-softmax mixes in other classes); the magnitude highlights which pixels matter, drawing the object’s silhouette.
- Occlusion sensitivity: slide a gray patch across the image and watch the class probability drop where the object is.
- Class activation map (CAM): replace the flatten+FC head with global-average-pool → FC → softmax; the FC weights say which feature maps drive the class, and each map localizes back to image regions — fast enough for real time.
- Neural style transfer. Optimize the image (not the weights) to carry the content of and the style of , using a fixed pretrained net:
Content matches mid-layer activations: . Style matches the Gram matrix of channel correlations — style is how features co-occur, with spatial layout discarded.
- GANs. A generator maps noise to fake samples; a discriminator classifies real vs fake; they play a minimax game.
- minimizes binary cross-entropy: reward and .
- wants to fool . The naive objective saturates early — when easily wins, and the gradient is tiny. Fix with the non-saturating loss
same optimum, large gradient early in training. Train $D$ and $G$ alternately (sometimes $D$ for $k$ steps per $G$ step). The loss value does *not* track sample quality (it's relative to $D$'s current strength) — judge by inspecting samples.
Implications
- “Differentiate w.r.t. the input” is one idea behind attacks, explanations, art, and (with a second network) generative modeling.
- Adversarial vulnerability is a property of high-dimensional linear-ish models, not a bug to be fully patched — it reframes robustness as part of the loss.
Core competency set
- State FGSM and the dimension argument for why small perturbations flip predictions.
- Give saliency (pre-softmax, ), CAM, the style-transfer content/Gram split, and the GAN / losses with the non-saturating fix.
8. Memorize cold
- Network = composition ; drop and the whole net collapses to one affine map.
- Activation derivatives: , , . ReLU avoids tail saturation → fixes vanishing gradients.
- Backprop, one layer: ; ; ; . Cross-entropy+sigmoid/softmax: .
- Vanishing/exploding = product of Jacobians drifting from 1; clip to tame exploding.
- EWMA (~ window), bias-correct . Momentum = avg gradient; RMSprop = ÷; Adam = both + correction ().
- Init variance: (Xavier, tanh), (He, ReLU).
- Batch norm: per-batch , then ( learned, dropped); test uses running .
- L2 = weight decay . Dropout = ensemble / anti-co-adaptation (÷ at train, off at test).
- Conv output ; same pad ; layer params , image-size-independent.
- ResNet skip → identity free, gradient highway.
- Triplet loss .
- FGSM .
- GAN: maximizes real/fake CE; non-saturating .
Named moves (cross-track glossary): compose-affine-and-nonlinearity (the network); reverse-mode-autodiff (the backward sweep); observed-minus-expected (, shared with softmax and word2vec, 11b); keep-the-Jacobian-product-near-1 (ReLU / He init / batch norm / residual all unify here); EWMA-the-gradient (momentum/RMSprop/Adam); normalize-the-activations (input norm + batch norm); decay-the-weights (L2); ensemble-by-dropout; share-and-localize (convolution); skip-connection (ResNet, and the LSTM highway in 11b); bottleneck-with-; differentiate-w.r.t.-the-input (adversarial / saliency / style transfer); minimax-game (GAN); margin (triplet loss, SVM track 6).