Notes
All notes

Deep Learning: the mathematics of modern networks

Deep learning is often taught as a stack of diagrams: boxes for layers, arrows for data flow, a hand-wave where the learning happens. But every one of those boxes is a differentiable function, and training is the chain rule applied a few million times. If you can follow the math — matrix products, gradients, the chain rule, and one derivation each for softmax, convolution, backprop-through-time, and attention — the architectures stop being magic and start being engineering.

This post covers the Deep Learning node of the machine learning roadmap — fully connected networks, CNNs, RNNs, LSTMs, transformers, and transfer learning — and it covers the mathematics at each step rather than hiding it. Code is interleaved to make the equations concrete, and self-test questions follow each section. Classical ML is in the companion Machine Learning guide.

What deep learning is

Deep learning is machine learning with models that learn a hierarchy of representations: early layers learn simple features (edges, n-grams), later layers compose them into complex ones (faces, syntax, meaning). “Deep” means many composed nonlinear layers, and the key theoretical fact is that a composition of linear maps is still linear — the nonlinear activations are what let depth buy expressiveness.

The roadmap node names the family we will cover:

\begin{tikzpicture}[font=\rmfamily, >=stealth,
  b/.style={draw, thick, rounded corners=3pt, minimum width=1.9cm, minimum height=0.62cm, font=\small\ttfamily},
  a/.style={->, thick}]
  \node[b, fill=blue!10] (x) at (0,0) {input $x$};
  \node[b, fill=orange!16] (l1) at (2.2,0.9) {linear+$\sigma$};
  \node[b, fill=orange!16] (l2) at (2.2,-0.9) {linear+$\sigma$};
  \node[b, fill=green!14] (out) at (4.6,0) {$\hat{y}$};
  \draw[a] (x) -- (l1); \draw[a] (x) -- (l2);
  \draw[a] (l1) -- (out); \draw[a] (l2) -- (out);
  \node[font=\rmfamily\small, text=black!60, anchor=north] at (2.2,-1.5) {composition of nonlinear functions $\hat y = f_L \circ \cdots \circ f_1(x)$};
\end{tikzpicture}
QQuestionWhat makes a network “deep”, and why does depth help?
ASolution

Depth means many composed nonlinear layers, so the model learns a hierarchy of representations — simple features early, complex ones later. A composition of linear maps is still linear, so the nonlinear activations are what let depth buy expressiveness beyond a single linear model.

QQuestionWhy are activation functions necessary?
ASolution

Without a nonlinearity between layers, the whole stack collapses to one linear transform, so the network could only model linear functions. Non-linear activations (ReLU, sigmoid, tanh) give it the capacity to approximate complex functions.

Notation and linear algebra

We work with tensors (multi-dimensional arrays). A minibatch is a matrix \(X \in \mathbb{R}^{B \times d}\) with batch size \(B\) and feature dimension \(d\). Weights are matrices \(W \in \mathbb{R}^{d_{\text{in}} \times d_{\text{out}}}\), biases are vectors. The core operation is the matrix product, a sum of scaled columns:

\[ (XW)_{ij} = \sum_{k=1}^{d_{\text{in}}} X_{ik} W_{kj} \]

The pieces of linear algebra that actually matter:

import numpy as np
X = np.random.randn(32, 10)          # batch of 32, 10 features
W = np.random.randn(10, 4) * 0.1     # 10 -> 4
b = np.zeros(4)
H = X @ W + b                        # (32, 4)
print(H.shape)
\begin{tikzpicture}[font=\rmfamily, >=stealth,
  m/.style={draw, thick, fill=blue!10, minimum size=0.42cm, font=\scriptsize}]
  \foreach \i in {0,...,3} \foreach \j in {0,...,1} \node[m] at (\i*0.46,\j*0.46) {};
  \node at (1.6,-0.4) {$X$};
  \foreach \i in {0,...,1} \foreach \j in {0,...,2} \node[m, fill=orange!18] at (2.4+\i*0.46,\j*0.46) {};
  \node at (3.0,-0.4) {$W$};
  \foreach \i in {0,...,3} \foreach \j in {0,...,2} \node[m, fill=green!16] at (4.2+\i*0.46,\j*0.46) {};
  \node at (4.9,-0.4) {$XW$};
\end{tikzpicture}
QQuestionWhy represent data as matrices and tensors?
ASolution

A minibatch is a matrix \(X \in \mathbb{R}^{B \times d}\), weights are matrices, and a layer is a matrix product — so entire batches are processed with one optimized operation instead of Python loops. Tensors generalize this to images (batch × channels × H × W) and sequences (batch × time × features).

QQuestionWhat does the SVD give you, and where is it used?
ASolution

The singular value decomposition \(X = U\Sigma V^\top\) exposes the dominant directions (singular vectors) and their importance (singular values). It underlies PCA, low-rank compression, and recommender systems, and it is how you reduce dimensionality while keeping the most variance.

Calculus and the chain rule

Training a network is minimizing a scalar loss \(L\) over parameters. For a function \(f: \mathbb{R}^n \to \mathbb{R}\), the gradient stacks the partial derivatives and points uphill:

\[ \nabla_\theta L = \left(\frac{\partial L}{\partial \theta_1}, \dots, \frac{\partial L}{\partial \theta_n}\right)^\top \]

For vector-valued functions, the Jacobian \(J_{ij} = \partial y_i / \partial x_j\) collects all first derivatives. The chain rule for composed functions is the entire basis of learning:

\[ \frac{\partial L}{\partial \theta} = \frac{\partial L}{\partial y} \cdot \frac{\partial y}{\partial \theta} \qquad\text{(scalar case)}, \qquad J_{f \circ g} = J_f\, J_g \quad\text{(vector case)} \]

The Hessian \(H_{ij} = \partial^2 L / \partial\theta_i \partial\theta_j\) describes curvature — convexity, saddle points, and second-order optimizers. In practice we almost never form the full Hessian; we use first-order gradients.

QQuestionState the chain rule, and why is it the basis of learning?
ASolution

For composed functions, \(\partial L/\partial \theta = (\partial L/\partial y)(\partial y/\partial \theta)\), and in the vector case Jacobians multiply, \(J_{f\circ g} = J_f J_g\). Backpropagation is exactly this rule applied layer by layer, which is how the gradient of the loss with respect to every weight is computed.

QQuestionWhat is the difference between a gradient, a Jacobian, and a Hessian?
ASolution

The gradient is the vector of first derivatives of a scalar function; the Jacobian is the matrix of first derivatives of a vector-valued function; the Hessian is the matrix of second derivatives, describing curvature. Training uses gradients; the Hessian appears in second-order methods and convexity analysis.

Automatic differentiation and backpropagation

Modern frameworks compute gradients with automatic differentiation (autodiff). There are two modes:

A neural network has one output (the scalar loss) and millions of parameters, so reverse mode wins by a huge factor — and reverse-mode autodiff is backpropagation. Every operation in the forward pass is recorded on a computational graph; the backward pass walks it in reverse, applying the chain rule with a vector–Jacobian product (VJP) at each node.

\begin{tikzpicture}[font=\rmfamily, >=stealth,
  b/.style={draw, thick, rounded corners=3pt, minimum width=1.1cm, minimum height=0.56cm, font=\small\ttfamily},
  a/.style={->, thick}]
  \node[b, fill=blue!10] (x) at (0,0) {$x$};
  \node[b, fill=orange!16] (w) at (0,-1.0) {$w$};
  \node[b, fill=orange!16] (z) at (1.6,-0.5) {$z=wx$};
  \node[b, fill=green!14] (l) at (3.2,-0.5) {$L$};
  \draw[a] (x) -- (z); \draw[a] (w) -- (z); \draw[a] (z) -- (l);
  \draw[a, dashed, red!60] (l) to[bend right=32] node[below, font=\scriptsize, text=red!60] {$\partial L/\partial z$} (z);
  \draw[a, dashed, red!60] (z) to[bend right=32] node[below, font=\scriptsize, text=red!60] {$\partial L/\partial w, \partial L/\partial x$} (x);
\end{tikzpicture}
QQuestionWhat is the difference between forward-mode and reverse-mode autodiff?
ASolution

Forward mode propagates derivatives from inputs to outputs and costs about one pass per input; reverse mode propagates the output gradient back to inputs and costs about one pass per output. Since a network has one scalar loss and millions of parameters, reverse mode is vastly cheaper — and reverse-mode autodiff is backpropagation.

QQuestionWhat is a computational graph?
ASolution

A directed graph recording every operation of the forward pass (add, multiply, softmax, …). The backward pass traverses it in reverse, applying the chain rule (a vector–Jacobian product) at each node, which is how frameworks like PyTorch compute gradients automatically.

The fully connected network

A dense layer applies an affine map then a nonlinear activation:

\[ z^{(l)} = W^{(l)} a^{(l-1)} + b^{(l)}, \qquad a^{(l)} = \sigma\big(z^{(l)}\big) \]

Activations and their derivatives (the derivative is what flows backward):

Activation Function Derivative
Sigmoid \(\sigma(z) = \frac{1}{1+e^{-z}}\) \(\sigma(z)(1-\sigma(z))\)
Tanh \(\tanh(z)\) \(1-\tanh^2(z)\)
ReLU \(\max(0, z)\) \(1\) if \(z>0\) else \(0\)
Leaky ReLU \(\max(\alpha z, z)\) \(1\) if \(z>0\) else \(\alpha\)
Softmax \(\frac{e^{z_i}}{\sum_j e^{z_j}}\) Jacobian, see below

ReLU is the default because its gradient does not saturate, which mitigates vanishing gradients. The universal approximation theorem says a network with enough hidden units can approximate any continuous function on a compact set — but it says nothing about how many units, how much data, or how to find the weights, which is why depth and training matter.

import numpy as np
def relu(z): return np.maximum(0, z)
def relu_grad(z): return (z > 0).astype(float)
QQuestionWhy is ReLU usually preferred over sigmoid or tanh in hidden layers?
ASolution

Sigmoid and tanh saturate for large inputs, so their derivatives approach zero and gradients vanish in deep stacks. ReLU has derivative 1 for positive inputs, so it does not saturate (and is cheap); its weakness is “dead” units, addressed by Leaky ReLU/GELU.

QQuestionWhat does the universal approximation theorem actually claim?
ASolution

That a feed-forward network with enough hidden units can approximate any continuous function on a compact set to arbitrary accuracy. It says nothing about how many units are needed, how much data, or whether gradient descent will find the weights — which is why depth, optimization, and regularization still matter.

Loss functions

The loss defines what “wrong” means, and its gradient is what training follows.

Regression: mean squared error.

\[ L_{\text{MSE}} = \frac{1}{B}\sum_{i=1}^{B} (\hat{y}_i - y_i)^2, \qquad \frac{\partial L}{\partial \hat{y}_i} = \frac{2}{B}(\hat{y}_i - y_i) \]

Classification: cross-entropy. The model outputs logits \(z\), converted to probabilities by the softmax:

\[ \hat{p}_k = \mathrm{softmax}(z)_k = \frac{e^{z_k}}{\sum_j e^{z_j}}, \qquad L = -\sum_k y_k \log \hat{p}_k \]

where \(y\) is a one-hot target. The softmax Jacobian is \(\partial \hat{p}_i / \partial z_j = \hat{p}_i(\delta_{ij} - \hat{p}_j)\), and combined with cross-entropy it collapses to a beautifully simple gradient:

\[ \frac{\partial L}{\partial z_k} = \hat{p}_k - y_k \]

That is why frameworks fuse softmax and cross-entropy: the gradient is just the prediction minus the target. Cross-entropy and KL divergence are the same up to an entropy constant, \(\mathrm{KL}(y\|\hat p) = -H(y) + L\), so minimizing one minimizes the other.

def softmax(z):
    z = z - z.max(axis=-1, keepdims=True)   # numerical stability
    e = np.exp(z)
    return e / e.sum(axis=-1, keepdims=True)

def ce_grad(logits, y_onehot):
    return softmax(logits) - y_onehot       # dL/dlogits
QQuestionWhy cross-entropy instead of MSE for classification?
ASolution

The model outputs probabilities, and cross-entropy is the negative log-likelihood of the true class. It penalizes confident errors heavily and, combined with softmax, yields the clean gradient \(\hat{p} - y\). MSE on a sigmoid gives vanishing gradients and poor calibration.

QQuestionWhy subtract the maximum logit before softmax?
ASolution

\(e^{z}\) overflows for large \(z\). Subtracting the row maximum gives the same probabilities mathematically (\(\mathrm{softmax}(z) = \mathrm{softmax}(z - c)\)) but keeps the exponentials in a safe range. It is a numerical-stability step, not a modeling choice.

QQuestionWhat is the gradient of softmax plus cross-entropy with respect to the logits?
ASolution

\(\partial L / \partial z = \hat{p} - y\), where \(\hat{p}\) is the softmax output and \(y\) is the one-hot target. The softmax Jacobian and the log cancel, which is why frameworks fuse softmax and cross-entropy into one op.

Backpropagation, derived

Consider a network of \(L\) layers with per-layer losses aggregated to a scalar \(L\). Define the error signal at layer \(l\):

\[ \delta^{(l)} = \frac{\partial L}{\partial z^{(l)}} \]

The backward pass uses two equations. First, propagate the error from layer \(l+1\) to \(l\) through the weights and the activation derivative:

\[ \delta^{(l)} = \big(\delta^{(l+1)} W^{(l+1)\top}\big) \odot \sigma'\!\big(z^{(l)}\big) \]

where \(\odot\) is elementwise multiplication (the activation derivative acts elementwise). Second, compute the parameter gradients:

\[ \frac{\partial L}{\partial W^{(l)}} = a^{(l-1)\top} \delta^{(l)}, \qquad \frac{\partial L}{\partial b^{(l)}} = \sum_i \delta^{(l)}_i \]

The \(\delta\) at the output layer is just \(\hat{p} - y\) for softmax-cross-entropy. Then a gradient step updates every weight, \(\theta \leftarrow \theta - \eta\, \partial L/\partial\theta\). That is the whole algorithm: forward to get activations, backward to get \(\delta\), multiply to get gradients.

\begin{tikzpicture}[font=\rmfamily, >=stealth,
  b/.style={draw, thick, rounded corners=3pt, minimum width=1.7cm, minimum height=0.6cm, font=\small\ttfamily},
  a/.style={->, thick}]
  \node[b, fill=blue!10] (a0) at (0,0) {$a^{(0)}$};
  \node[b, fill=orange!16] (a1) at (2.0,0) {$a^{(1)}$};
  \node[b, fill=orange!16] (a2) at (4.0,0) {$a^{(2)}$};
  \node[b, fill=green!14] (l) at (6.0,0) {$L$};
  \draw[a] (a0) -- node[above, font=\scriptsize] {$W^{(1)}$} (a1);
  \draw[a] (a1) -- node[above, font=\scriptsize] {$W^{(2)}$} (a2);
  \draw[a] (a2) -- (l);
  \draw[a, dashed, red!60] (l) to[bend left=34] node[below, font=\scriptsize, text=red!60] {$\delta^{(2)}$} (a2);
  \draw[a, dashed, red!60] (a2) to[bend left=34] node[below, font=\scriptsize, text=red!60] {$\delta^{(1)}$} (a1);
  \draw[a, dashed, red!60] (a1) to[bend left=34] node[below, font=\scriptsize, text=red!60] {$\delta^{(0)}$} (a0);
\end{tikzpicture}
QQuestionWrite the two core backpropagation equations.
ASolution

The error signal propagates as \(\delta^{(l)} = (\delta^{(l+1)} W^{(l+1)\top}) \odot \sigma'(z^{(l)})\), and the parameters follow as \(\partial L/\partial W^{(l)} = a^{(l-1)\top} \delta^{(l)}\) and \(\partial L/\partial b^{(l)} = \sum_i \delta^{(l)}_i\). Forward computes activations; backward computes \(\delta\); multiply for gradients.

QQuestionHow does backpropagation’s cost compare to numerical differentiation?
ASolution

Numerical differentiation perturbs each parameter and re-runs the forward pass, costing one pass per parameter — impossible for millions of weights. Backprop computes all gradients in roughly one forward pass plus one backward pass, independent of the parameter count.

Optimization

We minimize a non-convex, high-dimensional loss. Plain gradient descent steps against the gradient; stochastic gradient descent uses a minibatch, which is noisy but far cheaper per step and the noise even helps escape bad regions.

Momentum accumulates a velocity to smooth and accelerate:

\[ v_t = \beta v_{t-1} + \nabla L, \qquad \theta_t = \theta_{t-1} - \eta v_t \]

Adam combines momentum with per-parameter adaptive step sizes via running estimates of the first and second moments \(m_t, v_t\), with bias correction:

\[ m_t = \beta_1 m_{t-1} + (1-\beta_1) g_t, \quad v_t = \beta_2 v_{t-1} + (1-\beta_2) g_t^2, \quad \theta_t = \theta_{t-1} - \eta \frac{\hat{m}_t}{\sqrt{\hat{v}_t}+\epsilon} \]

The learning-rate schedule matters as much as the optimizer: warmup, cosine decay, or step decay all improve final performance. In high dimensions, saddle points (not local minima) are the common obstacle, and the noise in SGD helps.

QQuestionWhat is the difference between batch, stochastic, and mini-batch gradient descent?
ASolution

Batch GD uses the entire dataset per step (accurate but slow and memory-heavy); stochastic GD uses one sample (fast, noisy, high variance); mini-batch uses a small batch, balancing gradient quality and speed, and is what production training uses.

QQuestionHow does Adam work?
ASolution

It keeps exponentially decaying averages of the gradient (first moment \(m_t\)) and its square (second moment \(v_t\)), corrects their bias, and takes a step scaled by \(1/\sqrt{\hat v_t}\). That gives momentum-like smoothing plus per-parameter adaptive step sizes.

QQuestionWhy are saddle points a bigger obstacle than local minima in high dimensions?
ASolution

In high-dimensional non-convex landscapes, critical points with zero gradient are far more likely to be saddles than true minima, and they can stall optimization. Momentum and stochastic gradient noise help escape them.

Regularization

Regularization fights overfitting (high variance). The mathematically interesting ones:

L2 weight decay adds \(\frac{\lambda}{2}\|W\|^2\) to the loss, whose gradient is \(\lambda W\) — equivalently, shrinking weights each step. Dropout randomly zeroes activations with probability \(p\) during training, which approximates an ensemble of exponentially many subnetworks; at test time activations are scaled by \(1-p\) to match expectations. Batch normalization re-centers and re-scales each feature across the batch:

\[ \hat{x}_i = \frac{x_i - \mu_B}{\sqrt{\sigma_B^2 + \epsilon}}, \qquad y_i = \gamma \hat{x}_i + \beta \]

with learnable \(\gamma, \beta\). It stabilizes and accelerates training by keeping layer input distributions steady, and adds a mild regularizing effect. Early stopping, data augmentation, and weight tying round out the toolbox.

QQuestionHow does dropout regularize, and why scale activations at test time?
ASolution

Dropout randomly zeroes activations during training, preventing units from co-adapting and approximating an ensemble of subnetworks. At test time all units are active, so activations are scaled by the keep probability to match the expected magnitude seen during training.

QQuestionWhat does batch normalization do, and how does it help training?
ASolution

It normalizes each feature across the batch to zero mean and unit variance, then applies learnable scale \(\gamma\) and shift \(\beta\). This keeps layer input distributions stable, allowing higher learning rates and faster, more stable training, with a mild regularizing effect.

QQuestionWhat is L2 weight decay, mathematically?
ASolution

It adds \(\frac{\lambda}{2}\|W\|^2\) to the loss, whose gradient is \(\lambda W\), so each update also shrinks the weights toward zero. It limits effective model capacity and reduces variance (overfitting).

Convolutional neural networks

A convolution layer slides a small filter over the input, sharing weights across positions. In deep-learning libraries it is technically cross-correlation:

\[ (X * K)_{ij} = \sum_{m}\sum_{n} X_{i+m,\, j+n}\, K_{mn} \]

Weight sharing gives translation equivariance and drastically fewer parameters than a dense layer. Two formulas you should be able to recall: the output size and the receptive field.

\[ H_{\text{out}} = \left\lfloor \frac{H + 2P - K}{S} \right\rfloor + 1 \]

where \(H\) is input size, \(K\) kernel size, \(P\) padding, \(S\) stride. Pooling (usually max) down-samples and enlarges the receptive field; strides reduce resolution within the convolution itself. A \(1\times1\) convolution mixes channels without spatial mixing, used to shrink or expand depth cheaply. Backprop through a convolution is itself a convolution (with a flipped kernel), which is why the operation is efficient in both directions.

import torch
conv = torch.nn.Conv2d(in_channels=3, out_channels=16, kernel_size=3, padding=1, stride=1)
x = torch.randn(8, 3, 32, 32)      # (batch, channels, H, W)
print(conv(x).shape)               # (8, 16, 32, 32)
\begin{tikzpicture}[font=\rmfamily, >=stealth,
  g/.style={draw, thick, minimum size=0.4cm},
  k/.style={draw, thick, fill=orange!30, minimum size=0.4cm}]
  \foreach \i in {0,...,4} \foreach \j in {0,...,4} \node[g, fill=blue!8] at (\i*0.42,\j*0.42) {};
  \foreach \i in {1,2} \foreach \j in {1,2} \node[k] at (\i*0.42,\j*0.42) {};
  \node[font=\small, anchor=north] at (0.84,-0.3) {input + $3\times3$ kernel};
  \node[font=\small, anchor=west] at (2.4,0.6) {$\to$ feature map};
\end{tikzpicture}
QQuestionWhy do CNNs work better than dense networks on images?
ASolution

They exploit spatial structure through weight sharing (a filter is reused at every position) and locality, giving translation equivariance and dramatically fewer parameters. A dense layer on a large image would have millions of independent weights per layer and no notion of nearby pixels.

QQuestionWhat is the output-size formula for a convolution, and what do pooling and strides do?
ASolution

\(H_{\text{out}} = \lfloor (H + 2P - K)/S \rfloor + 1\) for input size \(H\), kernel \(K\), padding \(P\), stride \(S\). Pooling down-samples (usually max) to enlarge the receptive field and cut computation; strides reduce resolution inside the convolution itself.

QQuestionWhat is a \(1\times1\) convolution used for?
ASolution

It mixes information across channels without any spatial mixing, at very low cost. Stacked with a nonlinearity it acts like a per-pixel fully connected layer, commonly used to shrink or expand channel depth (as in the bottleneck blocks of ResNet).

Recurrent neural networks

An RNN processes a sequence one step at a time, carrying a hidden state \(h_t\):

\[ h_t = \sigma(W_h h_{t-1} + W_x x_t + b), \qquad \hat{y}_t = W_o h_t + b_o \]

The same weights are reused at every timestep. Training uses backpropagation through time (BPTT): unroll the sequence and apply the chain rule across timesteps. The gradient with respect to an early state involves a product of per-step Jacobians:

\[ \frac{\partial h_T}{\partial h_t} = \prod_{k=t+1}^{T} \frac{\partial h_k}{\partial h_{k-1}} \]

If the spectral radius of those Jacobians is below 1, the product vanishes exponentially with distance, and the network cannot learn long-range dependencies. If above 1, it explodes. The fixes are architectural (gating, residual connections), initialization (identity/orthogonal), and gradient clipping for the exploding case:

\[ g \leftarrow g \cdot \min\!\left(1, \frac{\text{threshold}}{\|g\|}\right) \]

QQuestionWhat is backpropagation through time?
ASolution

BPTT unrolls the RNN across timesteps and applies the chain rule backward through the sequence, accumulating gradients for the shared weights at every step. The gradient to an early state involves a product of per-step Jacobians, which is the source of vanishing/exploding gradients.

QQuestionWhy do vanishing and exploding gradients happen in RNNs, and how do you fix them?
ASolution

The gradient across \(T-t\) steps is a product of \(T-t\) Jacobians; if their norms are consistently below 1 the product vanishes exponentially, and if above 1 it explodes. Fix with gating (LSTM/GRU), good/orthogonal initialization, residual connections, and gradient clipping for the exploding case.

LSTM and GRU

The LSTM solves vanishing gradients with a cell state \(c_t\) and multiplicative gates that control what to forget, store, and output:

\[ f_t = \sigma(W_f[h_{t-1}, x_t]), \quad i_t = \sigma(W_i[h_{t-1}, x_t]), \quad o_t = \sigma(W_o[h_{t-1}, x_t]) \]

\[ \tilde{c}_t = \tanh(W_c[h_{t-1}, x_t]), \qquad c_t = f_t \odot c_{t-1} + i_t \odot \tilde{c}_t, \qquad h_t = o_t \odot \tanh(c_t) \]

The additive cell-state update means the gradient can flow along \(c_t\) with a factor near 1 instead of a product of derivatives — the “gradient highway”. The GRU simplifies this to two gates (update and reset). Both are largely superseded by transformers for language, but remain useful for streaming and small-data sequence tasks.

\begin{tikzpicture}[font=\rmfamily, >=stealth,
  b/.style={draw, thick, rounded corners=3pt, minimum width=1.3cm, minimum height=0.56cm, font=\small\ttfamily},
  a/.style={->, thick}]
  \node[b, fill=blue!10] (x) at (0,0) {$x_t$};
  \node[b, fill=orange!16] (g) at (1.7,0) {gates};
  \node[b, fill=green!14] (h) at (3.6,0) {$h_t$};
  \node[b, fill=green!14] (c) at (3.6,-1.0) {$c_t$};
  \draw[a] (x) -- (g); \draw[a] (g) -- (h);
  \draw[a] (c) -- (h);
  \draw[a, dashed] (c.west) to[out=180,in=180] node[left, font=\scriptsize] {$c_{t-1}$} (1.2,-1.0);
\end{tikzpicture}
QQuestionHow do LSTM gates mitigate vanishing gradients?
ASolution

The cell state is updated additively, \(c_t = f_t \odot c_{t-1} + i_t \odot \tilde{c}_t\), so the gradient can flow along \(c_t\) with a near-constant factor instead of a long product of derivatives — the “gradient highway”. The forget, input, and output gates learn what to keep, write, and expose.

QQuestionLSTM versus GRU versus transformer?
ASolution

An LSTM has three gates and a separate cell state; a GRU has two gates and no cell state, so it is cheaper and often comparable. Both process sequences step by step and struggle with very long range. Transformers replace recurrence with attention, parallelize over the sequence, and dominate large-scale language tasks.

Attention and transformers

Attention lets a position gather information from all other positions. Given queries \(Q\), keys \(K\), and values \(V\) (linear projections of the input), scaled dot-product attention is:

\[ \mathrm{Attention}(Q,K,V) = \mathrm{softmax}\!\left(\frac{QK^\top}{\sqrt{d_k}}\right) V \]

The \(1/\sqrt{d_k}\) scaling keeps the logits from growing with dimension, which would saturate the softmax and kill gradients. The matrix \(QK^\top\) holds pairwise similarities; the softmax turns each row into weights; multiplying by \(V\) produces a weighted average of values. Self-attention uses the same sequence for \(Q\), \(K\), and \(V\), so every token attends to every other in one step, with an \(O(n^2)\) cost.

Multi-head attention runs \(h\) attention operations in parallel on projected subspaces and concatenates the results, letting the model attend to different relationships at once:

\[ \mathrm{MHA}(X) = [\,\mathrm{head}_1; \dots; \mathrm{head}_h\,] W^O, \qquad \mathrm{head}_i = \mathrm{Attention}(XW_i^Q, XW_i^K, XW_i^V) \]

Because attention is order-agnostic, positional encodings (sinusoidal or learned) are added to inject sequence order. Each transformer block wraps attention and a position-wise feed-forward network in residual connections and layer normalization:

\[ \mathrm{Block}(X) = \mathrm{LN}\big(X + \mathrm{FFN}(\mathrm{LN}(X + \mathrm{Attn}(X)))\big) \]

Residual connections give gradients a direct path (again fighting vanishing gradients); layer norm stabilizes activations. Stack \(N\) blocks and you have the transformer behind GPT and every modern LLM. Its complexity is \(O(n^2 d)\) in sequence length, which is why long-context efficiency (sparse/linear attention, flash attention) is an active area.

\begin{tikzpicture}[font=\rmfamily, >=stealth,
  b/.style={draw, thick, rounded corners=3pt, minimum width=1.9cm, minimum height=0.56cm, font=\small\ttfamily},
  a/.style={->, thick}]
  \node[b, fill=blue!10] (x) at (0,0) {tokens};
  \node[b, fill=orange!16] (q) at (2.1,0.9) {$Q$};
  \node[b, fill=orange!16] (k) at (2.1,0) {$K$};
  \node[b, fill=orange!16] (v) at (2.1,-0.9) {$V$};
  \node[b, fill=green!14] (s) at (4.3,0) {$\mathrm{softmax}(QK^\top/\sqrt{d})V$};
  \draw[a] (x) -- (q); \draw[a] (x) -- (k); \draw[a] (x) -- (v);
  \draw[a] (q) -- (s); \draw[a] (k) -- (s); \draw[a] (v) -- (s);
\end{tikzpicture}
QQuestionWrite scaled dot-product attention and explain the scaling.
ASolution

\(\mathrm{Attention}(Q,K,V) = \mathrm{softmax}(QK^\top/\sqrt{d_k})V\). The \(1/\sqrt{d_k}\) keeps the dot products from growing with dimension, which would push the softmax into saturation and produce tiny gradients. Rows of the softmax are the attention weights; multiplying by \(V\) gives a weighted average.

QQuestionWhy multi-head attention instead of one attention operation?
ASolution

Different heads attend to different relationships (syntax, position, coreference) in parallel projected subspaces. Concatenating and projecting the heads gives the model several views of the sequence at once, which a single head cannot represent.

QQuestionWhy do transformers need positional encodings, residual connections, and layer norm?
ASolution

Attention is permutation-invariant, so positional encodings inject order. Residual connections give gradients a direct path and allow deep stacks, layer norm stabilizes activation distributions, and both make training deep transformers feasible.

QQuestionWhat is the computational complexity of self-attention, and why does it matter?
ASolution

\(O(n^2 d)\) in sequence length \(n\), because every position attends to every other. It is why long-context models need efficiency tricks (flash attention, sparse or linear attention) and why \(n\) is a first-order cost in LLM serving.

Transfer learning

Transfer learning reuses a network pretrained on a large dataset for a new task. The pretrained layers have learned general features (edges, textures, syntax), so you often need far less labeled data.

Two cautions with math behind them: catastrophic forgetting — large updates overwrite pretrained features, mitigated by a small learning rate and freezing; and distribution shift between the pretraining and target data, which limits how much transfers.

import torch, torchvision
model = torchvision.models.resnet18(weights="IMAGENET1K_V1")
for p in model.parameters():
    p.requires_grad = False                 # freeze the body
model.fc = torch.nn.Linear(model.fc.in_features, 10)   # new head
# only model.fc parameters are trained
QQuestionWhat is the difference between feature extraction and fine-tuning?
ASolution

Feature extraction freezes the pretrained body and trains only a new head; it is fast and works with little data. Fine-tuning unfreezes some or all layers and continues training with a small learning rate, adapting features to the target task at the cost of more data and compute.

QQuestionWhat is catastrophic forgetting, and how do you avoid it?
ASolution

Large updates on a new task overwrite the pretrained weights that encoded general features, so performance on the original task collapses. Avoid it with a small learning rate, freezing early layers, discriminative learning rates, or regularization that anchors important weights.

Training in practice

The math of initialization tells you why random weights must be scaled. If inputs have variance \(\sigma_x^2\), a layer with \(n\) inputs gives output variance \(n \sigma_w^2 \sigma_x^2\); to keep it constant you need \(\sigma_w^2 = 1/n\) (Xavier/Glorot for tanh-like activations) or \(\sigma_w^2 = 2/n\) (He for ReLU). Too small and activations vanish; too large and they explode.

The rest of the practical loop: shuffle and batch data, normalize inputs, choose an optimizer and schedule, monitor train/validation loss, regularize, and use cross-validation or a held-out set for honest evaluation. Scaling laws show that loss falls predictably as a power law in data, parameters, and compute — which is why large models train on enormous corpora, and why the AI Engineering course cares about serving and efficiency.

QQuestionWhy does weight initialization scale matter?
ASolution

A layer with \(n\) inputs multiplies the input variance by roughly \(n\sigma_w^2\); to keep activations from vanishing or exploding you need \(\sigma_w^2 \approx 1/n\) (Xavier/Glorot, tanh-like) or \(2/n\) (He, ReLU). Bad initialization makes deep networks untrainable regardless of architecture.

QQuestionWhat are neural scaling laws?
ASolution

Empirical power laws showing that loss falls predictably as a power of model size, dataset size, and compute, over a wide range. They guide how to allocate a fixed compute budget and explain why frontier models train on enormous corpora.

Pitfalls

QQuestionSelf-check

Why is reverse-mode autodiff the right choice for neural networks? Write the softmax-cross-entropy gradient and explain why it is so simple.

ASolution

A network has one scalar output (the loss) and millions of parameters; reverse mode costs about one forward pass regardless of parameter count, whereas forward mode would cost one pass per parameter. For softmax followed by cross-entropy the gradient with respect to the logits is \(\hat{p} - y\) (prediction minus one-hot target) — the softmax Jacobian and the log cancel — which is why frameworks fuse the two.