The Agentic AI Codex
Ch 05 · Deep Learning Architectures
Chapter 05 · Architectures

The architectures that changed everything

CNNs taught machines to see. RNNs / LSTMs taught them to remember. Autoencoders compressed reality. GANs and diffusion made them dream. Transformers made all of it scale. This chapter walks the family tree — so when you meet any new architecture, you can place it on the map.

5.1 · The family tree

Neural Network CNN (vision) RNN / LSTM Autoencoder Transformer ResNet, EfficientNet, ViT seq2seq, attention VAE, diffusion BERT, GPT, LLaMA, Claude Everything is differentiable layers — the difference is the inductive bias.

5.2 · Convolutional Neural Networks (CNNs)

Definition. A CNN is a neural network that processes grid-shaped data (images, audio spectrograms) by sliding small filters across the input. Each filter detects a local pattern — an edge, a colour blob, a corner — and the network stacks these into increasingly abstract concepts (edges → eyes → faces).

Why it works. Two built-in priors: locality (a pixel relates most to its neighbours) and translation invariance (a cat is a cat wherever it appears in the frame).

A CNN, drawn

image 224×224 conv + ReLU pool deeper conv blocks flatten dense classifier "cat"
OperationDefinitionExample
ConvolutionSlides a small $k \times k$ filter across the input; output pixel = dot product of filter and patch.A 3×3 edge filter highlights vertical lines.
ReLUNon-linearity after each conv so the network can model curved features.Negative activations zeroed out.
PoolingDown-samples a region into a single value (max or avg).Max-pool 2×2 turns 224 → 112; cuts compute by 4×.
Stride / paddingStride = step size of the slide; padding = pixels added at borders.Stride 2 halves resolution; "same" padding keeps it.
Skip connectionsAdd the input to the output of a block: $y = x + f(x)$.ResNet — lets gradients flow through 100+ layers.

Everyday example. A photo-app tags pictures as "beach", "dog", or "food". A CNN trained on ImageNet recognises objects with super-human accuracy on common categories.

Landmark architectures: LeNet (1998) → AlexNet (2012, the spark) → VGG → GoogLeNet → ResNet → EfficientNet → Vision Transformer (ViT, 2020 — applies the transformer to image patches).

5.3 · Recurrent Neural Networks (RNN / LSTM / GRU)

Definition. An RNN is a network that processes sequences one element at a time, carrying a hidden state $\mathbf{h}_t$ that summarises everything it has seen so far. At each step:

$\mathbf{h}_t = \tanh(\mathbf{W}_h \mathbf{h}_{t-1} + \mathbf{W}_x \mathbf{x}_t + \mathbf{b})$

An RNN unrolled in time

x₁ "The" x₂ "cat" x₃ "sat" x₄ "on" h₁ h₂ h₃ h₄ "the" predict next

Everyday example. Predict the next word in a sentence; classify the sentiment of a tweet; translate "Hello" → "Bonjour". Anything where order matters.

VariantDefinitionWhy it exists
Vanilla RNNThe simple recurrence above.Suffers from vanishing gradients — forgets things from > 20 steps ago.
LSTMAdds three gates (input, forget, output) and a separate cell state that flows largely unchanged.Preserves information across hundreds of steps. Powered Google Translate (2016) and Alexa.
GRUA lighter LSTM with only update + reset gates.Fewer parameters, similar quality.
BidirectionalTwo RNNs — one reading left→right, one right→left — concatenated.Useful when you can see the whole sequence (e.g. tagging), not for live generation.
Why we moved on
RNNs must process tokens in order — they can't easily parallelize across positions during training. The Transformer fixed that by replacing recurrence with attention, which is why every modern LLM is transformer-based.

5.4 · Autoencoders & VAEs

Definition. An autoencoder is a network with a deliberate bottleneck. It learns to compress an input down to a tiny latent vector $\mathbf{z}$ and then reconstruct the original from that vector. The reconstruction loss forces $\mathbf{z}$ to keep only what matters.

Encoder z latent Decoder input x reconstruction x̂ VAE: z becomes a Gaussian → sample new x̂'s by drawing z

Everyday examples.

  • Anomaly detection. Train on normal credit-card transactions; flag anything that reconstructs poorly.
  • Denoising. Add noise to the input, ask the network to recover the clean version → image denoising.
  • Representation learning. The bottleneck $\mathbf{z}$ is the linear ancestor of every "embedding" you use today.

VAE (Variational Autoencoder) — the bottleneck is forced to be a probability distribution (mean + variance). You can then sample new points and decode them — generating novel images, molecules, etc.

5.5 · GANs — the adversarial duet

Definition. A GAN (Generative Adversarial Network) pits two networks against each other in a minimax game:

  • Generator $G$: takes random noise $z$ and produces a fake sample $G(z)$.
  • Discriminator $D$: looks at a sample and tries to tell real from fake.

$G$ improves by fooling $D$; $D$ improves by catching $G$. At equilibrium, $G$ produces samples indistinguishable from real ones.

noise z Generator G real samples fake samples Discriminator D real / fake?

Example. StyleGAN-generated faces of people who never existed; deepfake images. GANs dominated photoreal generation 2017–2022 but training is famously unstable, which is one reason diffusion took over.

5.6 · Diffusion models

Definition. A diffusion model learns to reverse a noising process. Imagine taking a clean image and gradually adding Gaussian noise until it's pure static. The model is trained to do the opposite — starting from noise, predict slightly cleaner versions step by step until a sharp image emerges.

clean image pure noise ← reverse process (denoise) — what the model learns forward process (add noise) →

Example. Stable Diffusion, DALL·E 3, Midjourney, Sora, Veo — virtually every modern image / video generator. Conditioning on a text prompt steers the denoising toward "an astronaut riding a horse on Mars".

Diffusion has three structural advantages:

  • Stable training (no adversarial game).
  • Controllable via classifier-free guidance and additional conditions (text, depth, sketches, poses).
  • Composable — works for images, audio, video, 3D, even action sequences in robotics.

5.7 · The Transformer

The Transformer replaced recurrence with self-attention: every token can directly attend to every other token, in parallel.

Token embed + positional N × Transformer block Self-attention Feed-forward LayerNorm + Residual Output head

The core operation, scaled dot-product attention:

$\mathrm{Attn}(\mathbf{Q}, \mathbf{K}, \mathbf{V}) = \mathrm{softmax}\!\left(\dfrac{\mathbf{Q}\mathbf{K}^\top}{\sqrt{d_k}}\right)\mathbf{V}$

Each token computes how much to "pay attention" to every other token via $\mathbf{Q}\mathbf{K}^\top$, then mixes their values $\mathbf{V}$. We unpack this in detail in Chapter 6.

5.8 · One table to compare them all

ArchitectureInductive biasStrong atWeak at
MLPNoneTabular featuresSequences, images
CNNLocal + translation invariantImages, audio spectrogramsLong-range deps
RNN / LSTMRecurrenceStreaming sequencesParallelization
Autoencoder / VAEBottleneckCompression, anomaly detectionHigh fidelity gen
GANAdversarialPhotoreal generationStability, diversity
DiffusionIterative denoisingControlled gen, multi-modalSlow sampling
TransformerPairwise attentionAlmost everything$O(n^2)$ in sequence length

5.9 · Evaluation metrics — by architecture / task

Deep models inherit the classification & regression metrics from Ch 3 — but each modality has its own gold-standard metrics. Use the right column to know which numbers to report.

TaskMetricDefinition
Image classificationTop-1 / Top-5 accuracyDid the true class appear in the top 1 / 5 predictions? Standard on ImageNet.
Object detectionIoU (Intersection over Union)Area of overlap between predicted & ground-truth box, divided by their union.
Object detection[email protected] / [email protected]:.95Mean Average Precision averaged across IoU thresholds. COCO benchmark.
Semantic segmentationPixel accuracy, mIoU, DicePixel-wise correctness; mean IoU across classes; Dice = $2|A \cap B|/(|A|+|B|)$.
Instance segmentationAP_mask, AR_maskMask-level versions of AP and Average Recall.
Pose estimationPCK, OKSPercent of Correct Keypoints; Object Keypoint Similarity.

IoU — Intersection over Union, drawn

predicted ground truth intersection IoU = |∩| / |∪|
TaskMetricDefinition
Sequence labelling (NER, POS)Token / Entity F1Per-token or per-entity precision & recall; CONLL-style evaluation.
Sequence forecastingMAPE / sMAPE / RMSESame as regression metrics, applied per time step.
Language modellingPerplexity = $\exp(\text{cross-entropy})$Average uncertainty per token; lower is better.
Sequence classificationAccuracy / F1 / ROC-AUCStandard classification metrics on the final-state head.
TaskMetricDefinition
Machine translationBLEUModified n-gram precision vs reference(s), with brevity penalty.
Translation (newer)chrF / chrF++Character-n-gram F-score; tolerant of morphology.
Translation (learned)COMET / BLEURTLearned regressors that predict human quality scores; SOTA for MT eval.
SummarisationROUGE-1 / ROUGE-2 / ROUGE-LRecall of unigrams, bigrams, longest-common-subsequence.
Question answeringExact Match, F1, SQuADEM = exact string match; F1 = token overlap with answer.
Semantic similarityBERTScoreCosine similarity of contextual embeddings between candidate & reference.
ModalityMetricDefinition
Image generationFID (Fréchet Inception Distance)Distance between feature distributions of real vs generated images. Lower = better, more realistic.
Image generationInception Score (IS)Combines image classifier confidence (sharpness) and label diversity. Higher = better.
Text → imageCLIP ScoreCosine similarity between CLIP embedding of prompt and generated image.
Image qualityPSNR, SSIM, LPIPSPeak-signal-to-noise; structural similarity; learned perceptual distance.
Video generationFVD (Fréchet Video Distance)FID extended over temporal features.
DiversityPrecision & Recall for generative modelsEstimate how much of the real manifold the model covers (recall) vs how realistic its samples are (precision).
Human side-by-sidePairwise preference / Elo% of times judges prefer model A over B; Elo aggregates many pairwise comparisons.
AspectMetricDefinition
Language modellingPerplexity$\exp(\text{cross-entropy})$ on held-out tokens.
Multi-task benchmarkMMLU, BBH, GSM8K, MATH, HumanEval, ARC, HellaSwagStandardised academic suites covering reasoning, code, knowledge.
ReasoningPass@kProbability that at least one of k samples is correct (code & math).
Instruction followingIFEval, MT-BenchVerifiable instructions; GPT-4 judge on multi-turn.
Open-ended generationLLM-as-Judge, Pairwise EloA strong LLM scores against a rubric; LMSys arena uses pairwise Elo.
SafetyJailbreak success rate, Toxicity, PII leak rateRed-team and safety-specific metrics (see Ch 19).
RAG-styleContext recall, faithfulnessDid retrieved context support the answer? See Ch 9.
TaskMetricDefinition
Speech recognition (ASR)WER (Word Error Rate)$(S + D + I) / N$ — substitutions + deletions + insertions over reference words.
Speech recognitionCER (Character Error Rate)Character-level version of WER; better for ideographic scripts.
Text-to-speech (TTS)MOS (Mean Opinion Score)1–5 human rating of naturalness; the gold standard.
TTS automatedMCD, F0-RMSEMel-cepstral distortion; pitch error vs reference.
Speaker recognitionEER (Equal Error Rate)Threshold where false accept rate = false reject rate.
Audio source separationSI-SDR, PESQ, STOISignal-distortion ratio; perceptual quality; intelligibility.
Rule of thumb
Use the community-standard metric for that benchmark when comparing models, plus at least one human or judge-based metric when you can. Automated metrics often disagree with humans on generative quality — never report only one number.

5.10 · Self-check

Q1 · What makes self-attention scale better than recurrence in training?
It can be parallelized across positions
It uses less memory
It uses a smaller optimizer
It is sequence-length-independent
Q2 · Which model class powers ChatGPT, Claude, Gemini, Llama and Mistral?
CNN
LSTM
Transformer
GAN