AI and ML FoundationsVol. 14A · Part XIV
0 / 0

Shelves / AI and ML Foundations

AI·153

Neural Architectures

How a network's wiring encodes assumptions about data: inductive bias, convolutional networks (convolution as weight sharing, kernels, stride, padding, receptive fields, pooling, output-size arithmetic, LeNet to ResNet, depthwise separable convolutions, U-Net), recurrent networks and backpropagation through time, why vanilla RNNs forget, LSTM gates and the cell state, GRUs, sequence-to-sequence models and the bottleneck that motivated attention, autoencoders and variational autoencoders with the reparameterisation trick, GANs and their training dynamics, a preview of diffusion, graph neural networks, mixture-of-experts, state-space models such as Mamba, and the Transformer's place in the family, with PyTorch implementations and shape walkthroughs.

27 topics · ~19 min read · 31-question quiz
Updated Suggest a correction

Start here: wiring that encodes what you know about the data

An MLP treats its input as a flat list of numbers: it doesn't know that neighbouring pixels are related, or that a "7" in the corner is still a 7. Architectures build such knowledge into the wiring, which is called inductive bias. A convolutional network (CNN) slides the same small filter over every position of an image (weight sharing), so a pattern learned in one place is recognised everywhere. Recurrent networks process sequences step by step; Transformers (chapter 154) let every position look at every other. Choosing an architecture means choosing assumptions.

An MLP versus a CNN on moved digits

Both trained only on digits centred on a 16×16 canvas, then tested with the digit moved diagonally:

Text
                       parameters   centred   moved 1 px   moved 2 px   moved 3 px
MLP (256 → 128 → 10)       34,186    97.5%       12.4%         4.4%         8.4%
CNN (two 3×3 conv layers)   5,130    97.5%       57.3%        97.2%        52.6%

Both scored 97.5% on centred digits. Moving a digit by a single pixel destroyed the MLP (12.4%, close to guessing) because, to an MLP, every pixel is a separate input with its own weights. The CNN, with one seventh of the parameters, handled a 2-pixel move almost perfectly, because its filters respond to strokes wherever they are.

But the CNN isn't fully shift-invariant

Moves of 1 and 3 pixels hurt the CNN badly (57.3%, 52.6%) while 2 pixels didn't. The culprit is the 2×2 max-pooling step, which keeps one value per 2×2 block: shifting by an even number of pixels moves the image exactly one block, while an odd shift changes which pixels fall into each block. Convolution itself is shift-equivariant (shift the input, the output shifts); downsampling breaks it. Fixes include blurring before downsampling (anti-aliased pooling), training with shifted images (data augmentation), or both. It's a good example of an architecture's assumption holding only partly.

The arithmetic of convolutions

The output size of a convolution on an n×n input with kernel k, stride s and padding p is ⌊(n + 2p − k)/s⌋ + 1:

Text
224×224 input:  k=3 s=1 p=1 → 224×224    k=3 s=2 p=1 → 112×112    k=7 s=2 p=3 → 112×112    k=5 s=1 p=0 → 220×220

Each formula matched PyTorch's actual output. Getting these shapes right by hand is a daily skill when designing or debugging vision models.

How deep to go in neural architectures

Volume 17 defines six mastery levels. For this chapter they look like this; the chapter aims at L3 everywhere, and its lab at L4.

Level What you can do
L1 Name MLPs, CNNs, RNNs, Transformers and the data each suits
L2 Build and train a CNN or sequence model with correct shapes
L3 Explain inductive biases, receptive fields, residual connections and normalisation
L4 Diagnose architecture-related failures (aliasing, vanishing gradients, shape bugs)
L5 Choose or adapt architectures for a product's data, compute and latency constraints
L6 Design new architectures or scale existing ones for frontier workloads

Inductive bias

An architecture is a set of assumptions about the data, built into the network's structure:

Architecture Assumption (inductive bias) Natural data
MLP None beyond smoothness; every input connects to every unit Small tabular vectors
CNN Locality and translation equivariance: nearby pixels relate; a pattern means the same thing anywhere Images, audio spectrograms, some sequences
RNN / LSTM / GRU Sequential order; a fixed-size state summarises the past Time series, (historically) text and speech
Transformer Little structure; any position can attend to any other; order supplied by positional encodings Text, code, images (patches), audio, multimodal; scales best with data
GNN Relational structure; permutation invariance over neighbours Molecules, social graphs, recommendation
State-space models Linear recurrence with learned dynamics; long sequences at linear cost Long sequences, audio, hybrids with attention

Strong biases help when data is limited; with huge datasets, more flexible architectures (Transformers) can learn the structure themselves. That is the "bitter lesson" (Rich Sutton, 2019): general methods that scale with compute tend to win.

Convolutional neural networks

Convolution

A convolution slides a small kernel (e.g. 3×3 weights) across the input, computing a dot product at each position. (Deep learning "convolution" is technically cross-correlation: the kernel isn't flipped.)

  • Weight sharing: the same kernel is applied everywhere: a 3×3 conv from 64 to 128 channels has 3·3·64·128 + 128 ≈ 74k parameters regardless of image size; a dense layer on a 224×224×64 input would need billions.
  • Translation equivariance: shifting the input shifts the feature map.
  • Channels: input has C_in channels (RGB = 3); a layer has C_out kernels, each spanning all input channels: weight tensor [C_out, C_in, k, k].
  • Stride s skips positions (downsampling); padding p adds a border (often zeros) to preserve size; dilation spreads the kernel taps.

Output size per spatial dimension:

out = ⌊(in + 2p − d·(k − 1) − 1) / s⌋ + 1

e.g. in = 224, k = 7, s = 2, p = 3, d = 1 → ⌊(224 + 6 − 6 − 1)/2⌋ + 1 = 112.

input 6×6 10-1 20-2 10-1 kernel 3×3(edge detector) output 4×4 = (6 − 3)/1 + 1 Σ patch ⊙ kernel
A 3 by 3 convolution kernel sliding over a 6 by 6 input with stride 1 and no padding produces a 4 by 4 feature map. Each output value is the dot product of the kernel with the 3 by 3 patch beneath it, and the same nine weights are reused at every position.

Receptive fields and hierarchy

Each layer sees a small neighbourhood of the previous one; stacking layers grows the receptive field (two 3×3 layers see 5×5; three see 7×7, with fewer parameters than one 7×7). Early layers learn edges and colours; middle layers textures and parts; deep layers objects. Pooling (max or average over windows) and strided convolutions downsample, building invariance to small shifts and reducing computation; global average pooling collapses spatial dimensions before the classifier.

Milestones

Model Year Contribution
LeNet-5 1998 Convolution + pooling for digit recognition
AlexNet 2012 Deep CNN on GPUs with ReLU and dropout; won ImageNet by a wide margin: the start of the deep learning boom
VGG 2014 Simple stacks of 3×3 convolutions
GoogLeNet/Inception 2014 Parallel multi-scale branches, 1×1 bottlenecks
ResNet 2015 Residual connections enable 100+ layers (chapter 151)
MobileNet / EfficientNet 2017–19 Depthwise separable convolutions, compound scaling for mobile
U-Net 2015 Encoder-decoder with skip connections for segmentation; the backbone of many diffusion models
Vision Transformer (ViT) 2020 Image patches as tokens; competitive at scale
ConvNeXt 2022 Modernised CNN matching Transformers

Depthwise separable convolution splits a standard convolution into a per-channel spatial convolution plus a 1×1 pointwise convolution, cutting computation by roughly a factor of k² for large channel counts.

Python
import torch, torch.nn as nn, torch.nn.functional as F

class SmallCNN(nn.Module):
    """For 1×28×28 images (MNIST-like). Shapes noted for a batch of B."""
    def __init__(self, n_classes=10):
        super().__init__()
        self.features = nn.Sequential(
            nn.Conv2d(1, 32, 3, padding=1), nn.BatchNorm2d(32), nn.ReLU(),   # B×32×28×28
            nn.MaxPool2d(2),                                                 # B×32×14×14
            nn.Conv2d(32, 64, 3, padding=1), nn.BatchNorm2d(64), nn.ReLU(),  # B×64×14×14
            nn.MaxPool2d(2),                                                 # B×64×7×7
            nn.Conv2d(64, 128, 3, padding=1), nn.ReLU(),                     # B×128×7×7
            nn.AdaptiveAvgPool2d(1),                                         # B×128×1×1
        )
        self.head = nn.Linear(128, n_classes)
    def forward(self, x):
        return self.head(self.features(x).flatten(1))

m = SmallCNN()
m(torch.randn(8, 1, 28, 28)).shape, sum(p.numel() for p in m.parameters())   # [8, 10], 94,154

class ResidualBlock(nn.Module):
    def __init__(self, c):
        super().__init__()
        self.c1 = nn.Conv2d(c, c, 3, padding=1, bias=False); self.b1 = nn.BatchNorm2d(c)
        self.c2 = nn.Conv2d(c, c, 3, padding=1, bias=False); self.b2 = nn.BatchNorm2d(c)
    def forward(self, x):
        h = F.relu(self.b1(self.c1(x)))
        return F.relu(x + self.b2(self.c2(h)))       # identity shortcut

In practice, start from a pre-trained backbone (torchvision, timm, Hugging Face) and fine-tune: transfer learning beats training from scratch on most vision tasks with modest data.

Recurrent neural networks

The recurrence

An RNN processes a sequence one step at a time, carrying a hidden state:

hₜ = tanh(W_h hₜ₋₁ + W_x xₜ + b), yₜ = W_y hₜ

The same weights are used at every step (weight sharing over time). Training unrolls the loop and backpropagates through all steps: backpropagation through time (BPTT), usually truncated to a window.

Why vanilla RNNs forget

The gradient from step t back to step k contains the product Π ∂hᵢ/∂hᵢ₋₁, each roughly W_hᵀ·diag(tanh′). If the largest singular value is below 1, the product shrinks exponentially (vanishing: long-range dependencies can't be learned); above 1 it grows (exploding: clip gradients). In practice simple RNNs struggle beyond 10–20 steps.

LSTM

The Long Short-Term Memory (Hochreiter and Schmidhuber, 1997) adds a cell state cₜ, a conveyor belt updated additively and controlled by gates (sigmoids in [0, 1]):

fₜ = σ(W_f[hₜ₋₁, xₜ] + b_f) forget gate: how much old memory to keep iₜ = σ(W_i[hₜ₋₁, xₜ] + b_i) input gate: how much new content to write c̃ₜ = tanh(W_c[hₜ₋₁, xₜ] + b_c) candidate content cₜ = fₜ ⊙ cₜ₋₁ + iₜ ⊙ c̃ₜ cell update (additive) oₜ = σ(W_o[hₜ₋₁, xₜ] + b_o) output gate hₜ = oₜ ⊙ tanh(cₜ)

Because cₜ depends on cₜ₋₁ through multiplication by fₜ (which can stay near 1) rather than repeated squashing matrix products, gradients survive over hundreds of steps: the same insight as residual connections.

c_{t−1}c_t × + σ forget σ input tanh c̃ σ output × tanh × h_t [h_{t−1}, x_t] → every gate
An LSTM cell. The cell state runs along the top as a conveyor belt; the forget gate scales the old cell state, the input gate adds new candidate content, and the output gate decides how much of the squashed cell state becomes the hidden state. Every gate is a sigmoid layer reading the previous hidden state and the current input.

GRU

The Gated Recurrent Unit (2014) merges the cell and hidden state and uses two gates (update zₜ, reset rₜ): hₜ = (1 − zₜ) ⊙ hₜ₋₁ + zₜ ⊙ h̃ₜ. Fewer parameters, often similar accuracy.

Python
lstm = nn.LSTM(input_size=32, hidden_size=64, num_layers=2, batch_first=True, bidirectional=False)
x = torch.randn(8, 50, 32)                    # batch 8, 50 time steps, 32 features
out, (h_n, c_n) = lstm(x)
out.shape, h_n.shape                          # [8, 50, 64] (every step), [2, 8, 64] (last step per layer)

# Many-to-one classifier: use the final hidden state of the top layer
head = nn.Linear(64, 5)
logits = head(h_n[-1])                        # [8, 5]

Sequence-to-sequence and the bottleneck

Machine translation with RNNs used an encoder that compresses the source sentence into a final hidden state and a decoder that generates the target from it. A single fixed-size vector became a bottleneck for long sentences. Attention (Bahdanau et al., 2014) let the decoder look back at all encoder states, weighting them by relevance at each output step. The Transformer (2017) kept attention and dropped recurrence entirely, allowing full parallelism over positions during training: the subject of chapter 154.

RNN limitations that the Transformer removed: sequential computation (no parallelism across time during training), difficulty with very long dependencies, and the fixed-size state. Recurrence is returning in new forms (state-space models, linear attention) to get constant-memory inference on long sequences.

Autoencoders

An autoencoder learns to reconstruct its input through a narrow bottleneck: encoder z = f(x), decoder x̂ = g(z), loss ‖x − x̂‖². The bottleneck forces a compressed representation.

  • Uses: dimensionality reduction (nonlinear PCA), denoising (train to reconstruct clean x from corrupted x: denoising autoencoder), anomaly detection (high reconstruction error = unusual), pre-training representations.
  • Masked autoencoders (MAE for images; BERT's masked language modelling is the same idea for text) hide parts of the input and predict them: self-supervised learning at scale.
  • Sparse autoencoders are now a key interpretability tool: trained on a model's internal activations to decompose them into human-interpretable features.

Variational autoencoders

A VAE (Kingma and Welling, 2013) makes the latent space probabilistic so you can sample new data:

  • The encoder outputs a distribution q(z|x) = N(μ(x), σ²(x)).
  • Loss = reconstruction loss + KL(q(z|x) ‖ N(0, I)) (chapter 147): keeps the latent space smooth and close to a standard normal, so sampling z ~ N(0, I) and decoding produces plausible outputs.
  • Reparameterisation trick: z = μ + σ ⊙ ε, ε ~ N(0, I), so gradients flow through μ and σ despite the sampling.
  • Modern image generators (Stable Diffusion and successors) run diffusion in the latent space of a VAE-like autoencoder, because latents are far smaller than pixels.
x enc μ σ z = μ + σ·εε ~ N(0, I) dec x̂ loss = reconstruction ‖x − x̂‖² + KL(q(z|x) ‖ N(0, I)) generate: sample z ~ N(0, I) → decoder
An autoencoder and a variational autoencoder. A plain autoencoder squeezes the input through a small code and reconstructs it. A VAE's encoder outputs a mean and a standard deviation; a latent is sampled as mean plus standard deviation times noise, so gradients can flow, and a KL term keeps the latent distribution close to a standard normal so new samples can be generated.
Python
class VAE(nn.Module):
    def __init__(self, d_in=784, d_h=256, d_z=16):
        super().__init__()
        self.enc = nn.Sequential(nn.Linear(d_in, d_h), nn.ReLU())
        self.mu, self.logvar = nn.Linear(d_h, d_z), nn.Linear(d_h, d_z)
        self.dec = nn.Sequential(nn.Linear(d_z, d_h), nn.ReLU(), nn.Linear(d_h, d_in))
    def forward(self, x):
        h = self.enc(x); mu, logvar = self.mu(h), self.logvar(h)
        z = mu + torch.exp(0.5 * logvar) * torch.randn_like(mu)          # reparameterisation
        return self.dec(z), mu, logvar

def vae_loss(x_logits, x, mu, logvar):
    recon = F.binary_cross_entropy_with_logits(x_logits, x, reduction="sum")
    kl = -0.5 * torch.sum(1 + logvar - mu.pow(2) - logvar.exp())          # closed-form KL to N(0, I)
    return (recon + kl) / x.shape[0]

Generative adversarial networks

A GAN (Goodfellow et al., 2014) pits two networks against each other:

  • Generator G maps noise z to fake samples G(z).
  • Discriminator D outputs the probability that its input is real.
  • D maximises log D(x) + log(1 − D(G(z))); G tries to fool D (in practice maximising log D(G(z))). At the ideal equilibrium G reproduces the data distribution and D outputs 0.5 everywhere.

Strengths: sharp, realistic images (StyleGAN faces), fast single-step generation. Weaknesses: unstable training (oscillation, one side overpowering the other), mode collapse (G produces a few outputs that fool D), no likelihood for evaluation. Techniques: Wasserstein loss with gradient penalty, spectral normalisation, two-time-scale learning rates. Diffusion models (chapter 174) displaced GANs for most image generation because they train stably and cover modes better, though adversarial losses still appear in distillation of fast generators and in audio codecs.

noise z generator G fake G(z) real x discriminator D P(real) G learns via D's gradients: fool D D learns: real → 1, fake → 0 minimax game; risks: instability, mode collapse
A generative adversarial network. The generator turns random noise into fake samples; the discriminator sees real and fake samples and predicts which is which. The discriminator is trained to tell them apart, and the generator is trained, through the discriminator's gradients, to make its fakes indistinguishable from real data.

Diffusion models (preview of chapter 174): add noise to data step by step until it is pure Gaussian noise; train a network (often a U-Net or a Transformer, "DiT") to predict and remove the noise; generate by starting from noise and denoising iteratively. Flow matching learns a velocity field transporting noise to data along straight-ish paths and underlies many 2025–2026 image, video and audio models.

Other architectures worth knowing

Graph neural networks

Data as nodes and edges (molecules, citation networks, fraud rings, road networks). Message passing: each node updates its representation by aggregating transformed messages from its neighbours (sum/mean/max: permutation-invariant), stacked for multi-hop reasoning. Variants: GCN, GraphSAGE, GAT (attention over neighbours), graph Transformers. Libraries: PyTorch Geometric, DGL.

Mixture of experts (MoE)

Replace a dense MLP with many expert MLPs and a router that sends each token to the top-k experts (often 2 of 8, or 8 of 128+). Total parameters grow while active parameters (and compute per token) stay small. Used in many leading open-weight LLMs (Mixtral, DeepSeek-V3, Qwen3-MoE, Llama 4, gpt-oss). Challenges: load balancing across experts (auxiliary losses or bias-based balancing), communication in distributed training (expert parallelism), memory to hold all experts at inference.

State-space models and hybrids

Structured state-space models (S4, Mamba, Mamba-2) process sequences with a learned linear recurrence that can be computed as a parallel scan in training and as an RNN with constant memory at inference. Mamba made the recurrence input-dependent ("selective"), matching Transformers on many language tasks at small to medium scale. Several 2025–2026 models are hybrids interleaving attention layers with SSM or linear-attention layers to cut long-context cost while keeping attention's precise recall.

Where the Transformer fits

The Transformer (chapter 154) combines: embeddings, attention for content-based mixing across positions, MLPs for per-position computation, residual connections and normalisation (from ResNets), and positional information. It is the backbone of LLMs, ViTs, speech models (Whisper), diffusion Transformers, protein models and multimodal models: one architecture family across modalities, distinguished mostly by tokenisation and training data.

Lab: inductive bias under translation

PyTorch 2.14.1 on the lab machine's CPU. Digits (8×8) zero-padded to the centre of a 16×16 canvas; 1,200 training and 597 test images; both models trained 40 epochs with AdamW (lr 3e-3, batch 32) on centred digits only. Test images were shifted with torch.roll (wrap-around, harmless here because the borders are zero).

Experiment 1: MLP versus CNN

Python
mlp = nn.Sequential(nn.Flatten(), nn.Linear(256, 128), nn.ReLU(), nn.Linear(128, 10))
cnn = nn.Sequential(nn.Conv2d(1, 16, 3, padding=1), nn.ReLU(), nn.MaxPool2d(2),
                    nn.Conv2d(16, 32, 3, padding=1), nn.ReLU(),
                    nn.AdaptiveMaxPool2d(1), nn.Flatten(), nn.Linear(32, 10))
Model Parameters Train time Shift 0 1 px 2 px 3 px
MLP 34,186 3.1 s 97.5% 12.4% 4.4% 8.4%
CNN 5,130 6.3 s 97.5% 57.3% 97.2% 52.6%

The CNN's global max pool at the end (AdaptiveMaxPool2d(1)) discards position entirely, which is what made the 2-pixel case nearly perfect; the stride-2 max pool before it is what made odd shifts fail. Richard Zhang's 2019 paper "Making Convolutional Networks Shift-Invariant Again" documented this aliasing in standard ImageNet models and fixed it by low-pass filtering before subsampling (BlurPool). The CNN took longer per epoch on a CPU despite having fewer parameters: convolutions do more arithmetic per parameter (each weight is used at every position), which is the compute/parameter trade-off of weight sharing.

Experiment 2: output-size arithmetic

Kernel Stride Padding 224 → Formula
3 1 1 224 ⌊(224 + 2 − 3)/1⌋ + 1
3 2 1 112 ⌊(224 + 2 − 3)/2⌋ + 1
7 2 3 112 ⌊(224 + 6 − 7)/2⌋ + 1 (ResNet's stem)
5 1 0 220 ⌊(224 − 5)/1⌋ + 1

The receptive field (how much of the input one output unit sees) grows with depth: two stacked 3×3 convolutions see 5×5, three see 7×7, and each stride-2 step doubles the growth rate after it. Deep CNNs reach whole-image receptive fields; Vision Transformers get global context from the first layer through attention, with a weaker locality bias that they compensate for with more data.

Experiment 3: architecture families at a glance

Family Bias Typical data
MLP none beyond smoothness tabular features, small embeddings
CNN locality, translation equivariance images, audio spectrograms
RNN / LSTM / GRU sequential order, recurrence streaming sequences, small time series
Transformer all-pairs interactions, positions encoded explicitly text, code, images (ViT), audio, multimodal
Graph neural network permutation invariance over neighbours molecules, networks, recommendations

Try it yourself

  1. Train the CNN with random shifts of ±3 px as augmentation and remeasure all four columns.
  2. Replace MaxPool2d(2) with a blur followed by stride-2 subsampling (average pooling of a 3×3 box filter) and remeasure odd shifts.
  3. Train the MLP with the same augmentation. How close does it get to the CNN, and with how many epochs?
  4. Compute the receptive field of the CNN above by hand, then verify it by back-propagating from one output unit to the input.

Revision sheet: neural architectures

Key ideas

  • Inductive bias: architecture encodes assumptions; the right bias needs less data.
  • CNNs: convolution (weight sharing, locality), stride, padding, pooling, receptive fields; output size ⌊(n + 2p − k)/s⌋ + 1; equivariance vs invariance; aliasing from downsampling.
  • Residual connections (ResNet) and normalisation (batch, layer, RMS) make deep networks trainable.
  • RNNs, LSTMs, GRUs: recurrence for sequences; gating against vanishing gradients; sequential computation limits parallelism.
  • Attention and Transformers: all-pairs interactions, parallel over positions, positional information added explicitly (chapter 154).
  • Other families: GNNs (graphs), autoencoders and VAEs, diffusion models (generation), mixture-of-experts layers.
  • Augmentation teaches invariances the architecture lacks.

Numbers to remember

  • Lab: a 1-pixel shift dropped an MLP from 97.5% to 12.4%; the CNN (1/7 the parameters) kept 97.2% at 2 px.
  • Lab: odd shifts dropped the CNN to 52–57% (stride-2 pooling aliasing).
  • Two 3×3 convs = 5×5 receptive field; three = 7×7.

Pitfalls

  • Flattening images into MLPs for vision tasks.
  • Assuming CNNs are perfectly shift-invariant.
  • Shape errors from kernel/stride/padding arithmetic.
  • Deep stacks without residuals or normalisation.
  • Using recurrent models where parallel attention would train far faster.

Glossary

  • Receptive field: input region influencing one output unit.
  • Pooling: downsampling by max or average over neighbourhoods.
  • Residual connection: adding a layer's input to its output.
  • Layer norm / RMSNorm: per-example normalisation used in Transformers.
  • Mixture of experts: routing each token to a few of many sub-networks.