Optimal Learning Order — Why This Sequence?

  1. Encoders & Decoders — the raw building blocks everything else uses
  2. Autoencoders (all variants) — encoders + decoders with a learning objective
  3. Attention Mechanism — one powerful idea you need before transformers
  4. Transformer Architecture — built entirely on attention
  5. Vision Transformer (ViT) — transformers applied to images
  6. GANs & Modern GAN Works — separate generative paradigm
  7. Transfer Learning & Fine-tuning — reusing learned models
  8. Knowledge Distillation & Transfer — compressing and moving knowledge
  9. Domain Adaptation — when distributions shift
  10. Active Learning & Semi-supervised AL — when labels are scarce
  11. Large Foundation Models — the big picture
  12. LLMs, LVMs, CLIP, BLIP — specific large model types
  13. LLaVA — ties vision + language together, capstone topic
CH 01

Encoders Foundation

1.1 What Is an Encoder?

An encoder takes raw input — an image, a sentence, a signal — and turns it into a smaller, compressed form that still carries the important information. Think of it like summarizing a 300-page book into 3 paragraphs. You lose some detail, but the core meaning stays.

The compressed form is called a latent representation (or embedding). It lives in a space called latent space. Latent space is lower-dimensional, meaning it has fewer numbers but packs in more meaning per number.

Why do we want this? Two reasons. First, it is computationally cheaper to work with smaller representations. Second, similar inputs tend to produce similar embeddings — so the geometry of latent space reflects semantic similarity. Two sentences with the same meaning will end up close together in latent space, even if they use different words.

1.2 How Encoders Work

An encoder is typically a neural network — layers of matrix multiplications followed by activation functions (like ReLU). Each layer transforms the data a bit more, gradually compressing and abstracting it.

For images
Encoders often use convolutional layers — filters that slide across the image detecting patterns like edges, textures, and shapes.
For text
Encoders use layers that process word sequences and capture context between words.
Bottleneck
The encoder's output is sometimes called a bottleneck — information is squeezed through a narrow passage, forcing the model to be selective about what it keeps.

1.3 Types of Encoders

Deterministic Encoders
Given the same input, always produce the same output. Used in standard autoencoders, classifiers.
Stochastic Encoders
Produce a distribution over possible encodings. Given an input, the encoder outputs a mean and variance, and you sample from that distribution. Used in Variational Autoencoders (VAEs).
Bidirectional Encoders
Process input in both directions simultaneously. BERT uses a transformer encoder that sees the full context around each word — not just what came before.
🧠 Check Your Understanding
  • What is latent space and why is its lower dimensionality useful?
  • What is the difference between a deterministic and a stochastic encoder?
  • Name two types of layers commonly used in image encoders.
CH 02

Decoders Foundation

2.1 What Is a Decoder?

A decoder is the reverse of an encoder. It takes a compressed latent representation and reconstructs an output — either the original input, or something generated in the same format.

Encoder–Decoder Relationship Encoder: x → z (compress)
Decoder: z → x̂ (reconstruct)

The output does not have to be exactly the original input. In generative models, the decoder generates new things from new latent vectors never seen during training. This is how we generate new images or text.

2.2 How Decoders Work

Decoders mirror encoders in structure but do the reverse operation.

For images
Transposed convolutions (deconvolutions) up-sample the spatial size — the reverse of convolutions. An alternative is upsampling + regular convolution, which avoids checkerboard artifacts.
For text
Decoders generate tokens one at a time, conditioning each new token on everything generated so far. This is called autoregressive generation.

2.3 Encoder-Only vs Decoder-Only vs Encoder-Decoder

This distinction is critical for understanding modern architectures.

ArchitectureExamplesGood For
Encoder-onlyBERT, ViT, CLIP image encoderClassification, understanding, retrieval
Decoder-onlyGPT, LLaMA, MistralText generation, completion
Encoder-DecoderT5, BART, original TransformerTranslation, summarization, seq2seq tasks
CH 03

Autoencoders Foundation

3.1 The Core Idea

An autoencoder (AE) is a neural network trained to take an input, compress it into a small latent vector, and then reconstruct the original input from that vector — as accurately as possible.

Autoencoder Objective Encoder: z = f(x)
Decoder: x̂ = g(z)
Loss: minimize ||x − x̂||²

The bottleneck forces the network to learn what is actually important in the data. If you compress a 784-dimensional image into a 32-dimensional vector, the network has no choice but to learn the essential structure.

3.2 Architecture

Input x (784-dim)
     ↓
[Encoder Layer 1: 784 → 256]  ReLU
     ↓
[Encoder Layer 2: 256 → 128]  ReLU
     ↓
[Bottleneck: 128 → 32]        ← Latent code z
     ↓
[Decoder Layer 1: 32 → 128]   ReLU
     ↓
[Decoder Layer 2: 128 → 256]  ReLU
     ↓
[Output Layer: 256 → 784]     Sigmoid

3.3 Applications

Dimensionality reduction
Like PCA, but nonlinear — can capture curved structure in data.
Anomaly detection
Train on normal data; unusual inputs reconstruct poorly (high error = anomaly).
Feature learning
Pretrain an encoder, then fine-tune for a downstream task.
Data denoising
A trained AE can clean noisy inputs (covered in next chapter).

3.4 The Problem with Vanilla AEs — Motivating the Variants

Key weakness: A plain AE can overfit the training data. It memorizes specific inputs rather than learning a smooth, generalizable latent space. This means: the latent space has "holes" (random vectors that decode to garbage), and you cannot sample from it to generate new things.

This is exactly why we need the variants: Denoising AE, Stacked AE, Contractive AE, and Variational AE (VAE).

CH 04

Denoising Autoencoders Foundation

4.1 The Main Idea

A Denoising Autoencoder (DAE) deliberately corrupts the input before feeding it to the encoder — then trains the network to recover the clean original. The training signal says: "here is noisy data, now reconstruct the clean version."

Take clean input x

Add noise → x̃ (corrupted version)

Feed x̃ to the encoder → latent z

Decode z → reconstruction x̂

Loss: minimize ||x − x̂||² (compare to the clean original, not the noisy one)

4.2 Types of Noise

Gaussian noise
Add random values drawn from a normal distribution to input features.
Masking noise
Randomly set some input features (pixels) to zero.
Salt-and-pepper noise
Randomly set some features to maximum or minimum values.
Dropout noise
Randomly zero out features with some probability p.

4.3 Why This Works Better

By forcing the encoder to see corrupted inputs and still reconstruct clean outputs, you push it to learn the underlying data manifold — the smooth surface in high-dimensional space where real data lives. Noise pushes data off the manifold; the network learns to project it back.

Historical connection: Denoising autoencoders are conceptually related to modern diffusion models (DALL-E 3, Stable Diffusion). Diffusion models are essentially very deep denoising networks trained across many noise levels simultaneously. The DAE is where this idea first appeared.
🧠 Check Your Understanding
  • What is the key difference between a vanilla AE's loss and a DAE's loss?
  • Why does noisy training produce a smoother latent space?
  • What is a data manifold?
CH 05

Stacked Autoencoders Foundation

5.1 The Idea

A stacked autoencoder is multiple autoencoders layered on top of each other. The compressed output of one AE becomes the input to the next. The motivation is greedy layer-wise pretraining — a technique from 2006 that made it possible to train deep networks before modern tricks like batch normalization existed.

5.2 Training Procedure

Phase 1: Layer-wise Pretraining

Train AE₁ on raw input x → get encoder₁

Pass x through encoder₁ → get z₁ (compressed)

Train AE₂ on z₁ → get encoder₂

Continue for as many layers as desired

Phase 2: Fine-tuning (Unrolling)

Stack all encoders and all decoders (in reverse). Train the whole network end-to-end with a small learning rate to refine everything together.

5.3 Why Layer-wise Pretraining Helps

If you try to learn everything at once in a deep network, gradients get confused — they weaken dramatically by the time they reach early layers (the vanishing gradient problem). Layer-wise training gives each layer a chance to learn something meaningful before the next layer is added.

The concept lives on in modern deep pretraining — BERT pretraining, LLM pretraining, MAE — all train hierarchically in some sense.

CH 06

Contractive Autoencoders Foundation

6.1 Motivation

The contractive AE (CAE) addresses a specific problem: a vanilla AE's encoder is sensitive to small changes in input. If you perturb x slightly, the latent code z might change wildly. We want the opposite — a stable encoder that ignores small, irrelevant variations.

6.2 The Contractive Penalty

CAE Loss L = ||x − x̂||² + λ × ||J_f(x)||²_F

Where J_f(x) is the Jacobian matrix of the encoder — it measures how much each output of the encoder changes when each input dimension changes. ||·||²_F is the Frobenius norm (sum of squared entries).

Minimizing the Frobenius norm pushes the encoder to be insensitive to small input changes. This is the "contractive" property.

6.3 CAE vs DAE Comparison

PropertyDAECAE
How robustness is enforcedCorrupted input at training timeAnalytic penalty on encoder Jacobian
What is penalizedSensitivity (implicitly)Sensitivity (explicitly, via gradient)
Computational costLowerHigher (computing Jacobian is expensive)
Latent space qualitySmooth manifold structureSmooth, insensitive to perturbations

6.4 Missing Variant: Variational Autoencoder (VAE)

The most important AE variant. VAEs impose a prior distribution (standard normal N(0,I)) on the latent space. The encoder outputs μ and σ instead of a single vector; you sample z ∼ N(μ, σ²). The loss adds a KL divergence term to keep the latent distribution close to N(0,I). This creates a continuous, organized latent space you can sample from to generate new things.
VAE Loss (ELBO) L = E[log p(x|z)] − KL(N(μ,σ²) || N(0,I))
= Reconstruction term − KL regularization
CH 07

Attention Mechanism Architecture

7.1 The Problem Attention Solves

Before attention, sequence models (RNNs) processed sequences step by step and had to compress the entire history into a fixed-size vector. Long sequences were a disaster — by the time you got to the end, the beginning was mostly forgotten.

Attention solves this by letting every position in the output look directly at any position in the input. No compression. No forgetting.

7.2 Query–Key–Value Framework

Think of attention like a database lookup:

Query (Q)
What am I looking for?
Key (K)
What does each piece of information say it contains?
Value (V)
What is the actual content of each piece?
Scaled Dot-Product Attention Attention(Q, K, V) = softmax(QKᵀ / √d_k) × V

The division by √d_k prevents dot products from growing too large (which would push softmax into flat saturation regions, killing gradients).

7.3 Step-by-Step Walkthrough

Sentence: "The cat sat on the mat." We want the representation of "sat" that incorporates context.

"sat" becomes a Query vector q

Every word becomes a Key vector k_i

Compute dot products: q·k_i for each word, then divide by √d_k

Apply softmax → get attention weights (sum to 1)

Multiply each word's Value vector v_i by its attention weight

Sum weighted Values → contextual representation of "sat"

7.4 Self-Attention vs Cross-Attention

Self-Attention

  • Q, K, V all come from the same sequence
  • Each position attends to every other position
  • Used in transformer encoders (BERT)
  • Used in decoder-only models (GPT)

Cross-Attention

  • Q from one sequence, K and V from another
  • Decoder queries look into encoder output
  • Used in encoder-decoder transformers
  • Used in multi-modal models (image → text)

7.5 Multi-Head Attention

Instead of one attention function, compute h parallel attention functions with different learned projections:

MultiHead(Q, K, V) = Concat(head₁, ..., headₕ) × W_O
head_i = Attention(Q·W_Qi, K·W_Ki, V·W_Vi)

Each head can focus on different relationship types: one head might track syntactic dependencies, another semantic similarity, another positional patterns. Richer than single-head attention.

7.6 Positional Encoding

Attention has no notion of order — it treats input as a set, not a sequence. Positional encodings are added to input embeddings to inject order information.

Sinusoidal (original Transformer)
Fixed mathematical formula using sine and cosine at different frequencies. Does not need to be learned.
Learned embeddings
A lookup table — one vector per position, learned during training (used in BERT, GPT).
RoPE (Rotary Position Embeddings)
Rotates embedding vectors in complex space. Used in LLaMA, Mistral. Generalizes better to longer sequences than seen during training.
🧠 Check Your Understanding
  • Why do we divide by √d_k in the attention formula?
  • What is the difference between self-attention and cross-attention?
  • Why do we need positional encodings in attention?
  • What does each "head" in multi-head attention potentially specialize in?
CH 08

Transformer Architecture Architecture

8.1 The Big Picture

The Transformer (Vaswani et al., "Attention Is All You Need," 2017) replaced recurrent networks for sequence-to-sequence tasks. It is built entirely on attention — no RNNs, no convolutions in the core architecture. The key insight: attention can replace sequential processing with parallel processing.

8.2 Full Architecture

INPUT TOKENS
     ↓
Token Embedding + Positional Encoding
     ↓
┌─────────────────────────────┐
│  ENCODER BLOCK (×N layers)  │
│  ┌───────────────────────┐  │
│  │ Multi-Head Self-Attn  │  │
│  └──────────┬────────────┘  │
│      + residual connection   │
│       Layer Normalization    │
│  ┌───────────────────────┐  │
│  │ Feed-Forward Network  │  │
│  └──────────┬────────────┘  │
│      + residual connection   │
│       Layer Normalization    │
└─────────────────────────────┘
     ↓ Encoder Output (context)
┌─────────────────────────────┐
│  DECODER BLOCK (×N layers)  │
│  ┌───────────────────────┐  │
│  │ Masked Self-Attention │  │ ← Causal: can't see future
│  └──────────┬────────────┘  │
│      + residual + LayerNorm  │
│  ┌───────────────────────┐  │
│  │  Cross-Attention      │  │ ← Attends to encoder output
│  └──────────┬────────────┘  │
│      + residual + LayerNorm  │
│  ┌───────────────────────┐  │
│  │ Feed-Forward Network  │  │
│  └──────────┬────────────┘  │
│      + residual + LayerNorm  │
└─────────────────────────────┘
     ↓
Linear + Softmax → token probabilities

8.3 Key Components

Residual Connections
After each sub-layer, the input is added back to the output: output = sublayer(x) + x. Prevents vanishing gradients in deep stacks.
Layer Normalization
Normalizes activations across feature dimensions. Stabilizes training. Applied after residual addition.
Feed-Forward Network (FFN)
Applied independently at each position: FFN(x) = max(0, xW₁+b₁)W₂+b₂. Expands to 4× the model dimension, then contracts. Stores a lot of factual knowledge.
Masked Self-Attention (Decoder)
A causal mask prevents each position from attending to future positions — essential for autoregressive generation.

8.4 Computational Complexity

Self-attention is O(n²d) in time and O(n²) in memory, where n is sequence length. This quadratic scaling is the main bottleneck for long sequences.

Efficient attention variants: FlashAttention (hardware-optimized, exact), Longformer (local + global attention), Performer (linear approximation). These are practical solutions to the quadratic problem.
CH 09

Vision Transformer (ViT) Architecture

9.1 The Core Idea

ViT (Dosovitskiy et al., 2020) asked a simple question: what if we just split an image into patches and treat them like a sequence of tokens, then apply a standard transformer? Turns out — it works extremely well, especially at scale.

9.2 Step-by-Step Architecture

Patch Embedding: Split 224×224 image into 16×16 patches → 196 patches. Each patch (16×16×3 = 768 values) is flattened and linearly projected to dimension d.

Class Token [CLS]: A special learnable token prepended to the sequence. Its final representation is used for classification. (Borrowed from BERT.)

Position Embeddings: Learned 1D position embeddings added to each patch embedding. The model learns which positions are where.

Transformer Encoder: L layers of multi-head self-attention + FFN. Each patch attends to every other patch. No convolutions.

Classification Head: Take the final [CLS] token → small MLP → class probabilities.

9.3 ViT vs CNN

PropertyCNNViT
Inductive biasStrong (locality, translation equivariance baked in)Weak (must learn from data)
Data efficiencyHigh — works with small datasetsLower — needs more data to learn what CNNs assume
ScalabilityGoodExcellent — scales very well with data and compute
Long-range dependenciesHard (limited receptive field)Easy — global attention from the first layer

9.4 Important ViT Variants

DeiT
Data-efficient ViT. Trained on ImageNet-1K alone (no extra data) using knowledge distillation from a CNN teacher. Shows ViT works without massive external datasets.
Swin Transformer
Hierarchical ViT with local attention within shifted windows. Restores spatial locality and hierarchy. Very widely used as a backbone for detection, segmentation.
MAE (Masked Autoencoder)
He et al., 2021. Masks 75% of image patches, trains a ViT encoder + lightweight decoder to reconstruct missing patches. Simple, scalable, excellent self-supervised pretraining.
BEiT
BERT-style pretraining for ViT. Masks patches and predicts their discrete visual tokens (from a trained discrete VAE).
🧠 Check Your Understanding
  • A 224×224 image with 16×16 patches produces how many patches?
  • What is the [CLS] token and why is it useful?
  • Why does ViT need more data than a CNN to perform well?
  • What does MAE do and how is it related to denoising autoencoders?
CH 10

Generative Adversarial Networks Generative

10.1 The Core Idea — A Two-Player Game

A GAN (Goodfellow et al., 2014) consists of two networks trained in opposition:

Generator G
Takes random noise z and generates fake samples G(z). Wants to fool D.
Discriminator D
Takes real or fake samples and outputs a probability that the input is real. Wants to correctly identify fakes.
GAN Minimax Objective min_G max_D 𝔼_x[log D(x)] + 𝔼_z[log(1 − D(G(z)))]

10.2 Training Loop

For each training step:

1. Sample batch of real data {x₁, ..., xₘ}
2. Sample batch of noise {z₁, ..., zₘ}
3. Generate fakes: {G(z₁), ..., G(zₘ)}

Update Discriminator:
  Real samples → D should output 1
  Fake samples → D should output 0
  Minimize: −[log D(x) + log(1 − D(G(z)))]

Update Generator:
  Want D(G(z)) ≈ 1 (fool D)
  Minimize: −log D(G(z))   ← non-saturating loss

10.3 Why the Non-Saturating Loss?

The original G loss was log(1 − D(G(z))). Early in training, D can easily spot fakes (since G is terrible), so D(G(z)) ≈ 0 and the gradient ≈ 0 — G cannot learn.

The fix: use −log D(G(z)). When D(G(z)) ≈ 0, this loss is large, giving G a strong gradient to improve.

10.4 Common GAN Problems

Mode Collapse
G learns to generate only a few types of output (e.g., only one digit) because this reliably fools D. The generator stops being diverse.
Training Instability
G and D need to improve at roughly the same rate. If D becomes too strong too fast, G cannot learn. If G jumps ahead, D collapses.
Vanishing Gradients
If D is perfect, its output is always 0 for fakes, and G gets no gradient signal at all.

10.5 Evaluation Metrics

Inception Score (IS)
Measures quality (each image should look like one clear class) and diversity (all classes should appear). Higher is better.
FID (Fréchet Inception Distance)
Compares statistics of deep features from real and generated images using Fréchet distance. Lower is better. More reliable than IS.
CH 11

Modern GAN Works Generative

11.1 DCGAN (2015)

The first practically successful image GAN. Key contributions: transposed convolutions in G, strided convolutions in D (no pooling), batch normalization, LeakyReLU in D. This architecture guideline became the universal GAN starting point.

11.2 Conditional GAN (cGAN, 2014)

Feed a class label (or other conditioning) to both G and D. G(z, y) → image conditioned on label y. Lets you control what the generator produces — ask for a "7" and get a 7.

11.3 Pix2Pix (2017)

Conditional GAN for paired image-to-image translation. Given (input image, target image) pairs, learn to translate between domains: sketch→photo, day→night, satellite→map. Loss = adversarial loss + L1 pixel-level reconstruction loss.

11.4 CycleGAN (2017)

Unpaired image-to-image translation. No need for matched pairs — just two sets of images (horses and zebras). Uses two generators and two discriminators, plus a cycle consistency loss: translating A→B→A should recover A.

Cycle Consistency ||G_BA(G_AB(x)) − x||₁ ≈ 0

11.5 StyleGAN (2019) / StyleGAN2 (2020)

Radical generator architecture redesign. Key ideas:

Mapping network
Maps noise z → intermediate latent w through 8 FC layers. The w space is more disentangled than z space.
AdaIN (Adaptive Instance Normalization)
Style vector w controls the "style" at each layer via scale and shift parameters — coarse styles at low resolution, fine styles at high resolution.
Style mixing
Use one latent for early layers and another for later layers → combine two identities in interesting ways.

StyleGAN2 fixes blob artifacts from AdaIN. Powers "This Person Does Not Exist."

11.6 WGAN (Wasserstein GAN, 2017)

Addresses GAN instability theoretically. Replaces Jensen-Shannon divergence (implicit in standard GAN) with Wasserstein distance — a more stable training signal.

Key change 1
Remove sigmoid from D — it becomes a "critic" outputting real values, not probabilities.
Key change 2
Clip D's weights to [-0.01, 0.01] to enforce the Lipschitz constraint (or use gradient penalty: WGAN-GP).
Key change 3
Train D 5× more than G per iteration. A better critic gives G a better signal.

11.7 Progressive Growing (ProGAN, 2018)

Start generating 4×4 images, gradually increase to 8×8, 16×16, ... 1024×1024. Add new layers with smooth blending transitions. Makes training stable because the task starts easy (4×4) and the model builds on what it has already learned.

CH 12

Transfer Learning Adaptation

12.1 What Is Transfer Learning?

Transfer learning uses knowledge gained from solving one problem to help solve a different (but related) problem. The core empirical observation: neural networks trained on one task learn feature representations that are useful for many other tasks.

Early layers of an image classifier learn edges, textures, colors — universally useful features. Later layers learn task-specific features. Even these can be adapted. This is the foundation of the entire modern ML paradigm.

12.2 Why It Matters

Training large models from scratch requires millions of labeled examples, weeks of GPU time, and enormous cost. Transfer learning lets practitioners start from a powerful pretrained model and adapt it with a small dataset in hours.

12.3 When to Use Which Strategy

Dataset SizeSimilarity to Pretraining DataRecommended Strategy
SmallHighFeature extraction only (freeze all pretrained weights)
SmallLowFeature extraction (risky) or few-shot methods
LargeHighFine-tune all layers
LargeLowFine-tune all layers or train from scratch

12.4 Negative Transfer

Transfer learning can sometimes hurt performance. This happens when source and target domains are very different (e.g., pretraining on natural photos, target is medical X-rays). Recognizing when transfer helps vs hurts is an important practical skill.
CH 13

Fine-Tuning Adaptation

13.1 What Is Fine-Tuning?

Fine-tuning means taking a pretrained model and continuing training it on a new (typically smaller) dataset, adjusting weights to fit the new task. Unlike feature extraction (frozen backbone), fine-tuning lets the internal representations shift.

13.2 Standard Procedure

Load pretrained model weights

Replace the final classification head with a new one (random init) matching the new task's number of classes

Choose a small learning rate — usually 10–100× smaller than original training LR

Optionally freeze early layers initially, then unfreeze gradually ("unfreezing schedule")

Train on new dataset; monitor validation loss for overfitting

13.3 Parameter-Efficient Fine-Tuning (PEFT)

Modern LLMs have billions of parameters — full fine-tuning is expensive and risks overfitting. PEFT methods update only a small fraction of parameters:

Adapter Layers
Insert small trainable layers between existing frozen layers. Only adapters are trained (~1–3% of parameters).
Prefix Tuning
Add trainable prefix tokens to the input sequence. Only the prefix embeddings are optimized.
LoRA (Low-Rank Adaptation)
For each weight matrix W, learn a low-rank update: W' = W + AB where A ∈ ℝ^(d×r) and B ∈ ℝ^(r×k) with rank r ≪ min(d,k). Extremely popular for LLM fine-tuning. Fast, cheap, avoids forgetting.
LoRA Update W' = W + ΔW = W + A × B
where rank r ≪ min(d, k)
Parameters trained: d×r + r×k instead of d×k

13.4 Catastrophic Forgetting

When you fine-tune on a new task, the network can "forget" what it learned before. New gradient updates overwrite old knowledge. Mitigation: small LR, replay (mix old + new data), EWC (Elastic Weight Consolidation), or PEFT methods (frozen backbone prevents forgetting).

CH 14

Knowledge Distillation Adaptation

14.1 The Core Idea

Knowledge distillation (Hinton et al., 2015) transfers knowledge from a large, accurate model (the teacher) into a smaller, faster model (the student). The student learns from the teacher's soft output probabilities, not just hard labels.

14.2 Why Soft Labels Carry More Information

A hard label says: "this image is a cat." That is all. The teacher's output probabilities say: "95% cat, 4% dog, 1% tiger." These soft labels reveal which classes are similar — a dog is more like a cat than a car is. This extra signal helps the student learn better representations.

14.3 Distillation Loss

Distillation Objective L = α × L_CE(student, true_labels)
+ (1−α) × L_KL(softmax(student/T) || softmax(teacher/T))

Where T is temperature — higher T makes soft labels softer (less peaked), making the small probabilities more readable and useful for the student.

14.4 Variants of Distillation

Response-based
Student matches teacher's final output (logits/probabilities). The classical approach.
Feature-based
Student matches teacher's intermediate representations (hidden layer activations). Richer signal, more complex to implement.
Relation-based
Student matches relationships between different samples in teacher's representation space (e.g., pairwise distances, Gram matrices).

14.5 Real-World Applications

DistilBERT
60% the size of BERT, 97% of its performance, 60% faster at inference.
DeiT
ViT trained on ImageNet-1K alone by distilling from a CNN (RegNet) teacher. Makes ViT practical without huge datasets.
TinyBERT
Distillation at multiple layers (attention matrices + hidden states), giving a very compact model.
CH 15

Knowledge Transfer Adaptation

15.1 Broader Than Distillation

Knowledge distillation is one specific method of knowledge transfer. Knowledge transfer is the broader idea — any method by which knowledge learned in one setting is made useful in another. This includes: transfer learning, fine-tuning, distillation, multi-task learning, zero-shot transfer, and few-shot transfer.

15.2 Zero-Shot Transfer

The model is tested on a task it was never explicitly trained on. Works when the model has learned sufficiently general representations. CLIP is the canonical example — trained to align image and text, it can classify images into any category by comparing image embeddings to text embeddings of class names. No task-specific training needed.

15.3 Few-Shot Transfer

The model sees only K examples (K = 1, 5, or 10) of the new task and must generalize. This is the goal of meta-learning — training models to be good at learning quickly.

Prototypical Networks
Compute a class prototype (mean embedding) from K examples. Classify new examples by finding the nearest prototype.
MAML (Model-Agnostic Meta-Learning)
Learn an initialization that can be fine-tuned to any new task in a few gradient steps.
Matching Networks
Use attention to match test examples to the K support examples directly.
CH 16

Domain Adaptation Adaptation

16.1 The Problem

You train a model on data from one distribution (source domain) and deploy it on data from a different distribution (target domain). Performance degrades — sometimes catastrophically. Example: train on California sunshine photos, deploy in winter fog in Germany.

16.2 Types of Distribution Shift

Covariate shift
P(X) changes between source and target, but P(Y|X) stays the same. The input distribution changes, but the relationship between input and label does not. Most common type.
Label shift
P(Y) changes — different class frequencies in source and target.
Concept drift
P(Y|X) changes — the actual relationship between input and output changes over time.

16.3 Key Methods

DANN (Domain-Adversarial Neural Network)
Add a domain classifier that tries to distinguish source from target features. The feature extractor is trained to fool the domain classifier — like a GAN. A gradient reversal layer flips the gradient sign to achieve this elegantly.
Deep CORAL
Align second-order statistics (covariance matrices) of source and target features. Simpler than DANN but effective.
MMD (Maximum Mean Discrepancy)
Minimize the statistical distance between source and target feature distributions in a kernel space.
Self-training
Train on source, predict pseudo-labels for target, retrain using high-confidence predictions. Iterate until convergence.
🧠 Check Your Understanding
  • What is covariate shift and why does it degrade model performance?
  • How does DANN use an adversarial objective — and how is it similar to GANs?
  • What is unsupervised domain adaptation and why is it the hardest variant?
CH 17

Active Learning Adaptation

17.1 The Setting

You have a large pool of unlabeled data. Labeling is expensive (requires human annotators). You have a limited labeling budget. The question: which examples should you label to maximize model performance?

17.2 The Active Learning Loop

1. Start with small labeled set L, large unlabeled pool U
2. Train model on L
3. Score each unlabeled example using an acquisition function
4. Select top-K highest scoring examples from U
5. Have humans label those K examples
6. Add to L; go to step 2
7. Repeat until labeling budget is exhausted

17.3 Acquisition Functions

Least Confidence
Select x where P(y*|x) is lowest — the model is least sure of even its top prediction.
Margin Sampling
Select x where the gap between top-2 class probabilities is smallest — the model cannot decide between two options.
Entropy Sampling
Select x with highest entropy H = −Σ p log p over all classes. Most general uncertainty measure.
Query by Committee (QbC)
Train multiple models with different random seeds. Select examples where committee members disagree the most.
Core-Set Selection
Select examples that best "cover" the unlabeled set in feature space — maximize geometric diversity, not just uncertainty.
BALD
Bayesian Active Learning by Disagreement. Maximizes mutual information between predictions and model parameters. Requires MC Dropout or a Bayesian model.

17.4 Batch Active Learning

Most real scenarios require selecting a batch of K examples at once. Naive approach: pick top-K by individual score. Problem: they might all be similar (redundant). Better: balance informativeness with diversity.

BADGE
Batch Active Learning by Diverse Gradient Embeddings. Compute gradient embeddings for each unlabeled example; use k-means++ to select a batch that is both uncertain (large gradient) and diverse (different gradient directions).
CoreSet (k-center greedy)
Greedily select points that minimize the maximum distance from any unlabeled point to the nearest selected point — covers feature space uniformly.
CH 18

Semi-Supervised Active Learning Adaptation

18.1 Combining Two Paradigms

Semi-supervised learning (SSL) uses both labeled and unlabeled data to improve the model. Active learning selects which examples to label. Together: use unlabeled data to improve the model, then use the improved model to better choose what to label next. A virtuous cycle.

18.2 Semi-Supervised Learning Methods (Background)

Pseudo-labeling (Self-training)
Train on labeled data → predict on unlabeled → use high-confidence predictions as pseudo-labels → retrain. Iterate.
Consistency Regularization
Perturb an unlabeled example (augmentation, noise) and force the model output to be consistent across perturbations.
FixMatch
Use weak augmentation to generate pseudo-labels; use strong augmentation to get predictions; enforce consistency only when pseudo-label confidence > threshold. Strong baseline for SSL.
Mean Teacher
Maintain student (gradient-updated) and teacher (exponential moving average of student) networks. Teacher produces targets for unlabeled data. Student learns from those targets.

18.3 VAAL (Variational Adversarial Active Learning)

Trains a VAE on all data (labeled + unlabeled). Trains a discriminator to distinguish labeled from unlabeled data in latent space. Query examples the discriminator cannot tell apart from labeled data — regions of latent space not yet covered by labeled examples.

18.4 Why Combine SSL and AL?

SSL changes what the model is uncertain about — it extracts information from unlabeled data before labeling. This changes the acquisition function's output. Without SSL, active learning picks "hard" examples. With SSL, the model already partially understands unlabeled data, so it picks examples that are still hard — these are genuinely informative, not just out-of-distribution.
CH 19

Large AI Foundation Models Frontier

19.1 What Is a Foundation Model?

A foundation model is a large model trained on vast amounts of broad data that can be adapted to many downstream tasks. Term coined by Stanford HAI in 2021. Properties: massive scale (billions of parameters), generality (not one task), emergent capabilities (appear at scale), adaptability (fine-tune / prompt for specific applications).

19.2 Pretraining Paradigms

ParadigmMethodUsed In
Masked Language ModelingMask tokens, predict themBERT, RoBERTa
Causal Language ModelingPredict next tokenGPT, LLaMA, Mistral
Contrastive PretrainingAlign representations from different modalitiesCLIP, ALIGN
Masked Image ModelingMask patches, reconstruct themMAE, BEiT
Multi-task PretrainingMany tasks with different promptsT5, FLAN, Gemini

19.3 Emergent Abilities

Certain capabilities appear only above a scale threshold. Below: near-random performance. Above: sudden, dramatic improvement. Examples: few-shot learning (GPT-3+), chain-of-thought reasoning, multi-step arithmetic, instruction following without explicit training. Not fully understood — active research area.

19.4 RLHF — Making Models Behave

Reinforcement Learning from Human Feedback shapes model behavior toward being helpful, honest, and harmless.

Fine-tune LLM with supervised learning on high-quality human demonstrations

Collect human preferences: show pairs of model responses, humans pick which is better

Train a reward model to predict human preferences from these pairs

Use RL (PPO) to optimize the LLM to maximize the reward model's score

DPO (Direct Preference Optimization): Skips the separate reward model entirely. Directly optimizes the LLM on preference pairs using a closed-form objective derived from RLHF theory. Simpler, often equally effective.
CH 20

Large Language Models (LLMs) Frontier

20.1 Architecture

Modern LLMs are transformer decoder-only models: causal self-attention only, trained to predict the next token autoregressively. No encoder, no cross-attention.

RMSNorm
Replaces LayerNorm — more computationally efficient (no mean subtraction).
SwiGLU activation
Replaces ReLU in the FFN. Better empirical performance.
Rotary Position Embeddings (RoPE)
Rotates in embedding space; better generalization to longer sequences than seen in training.
Grouped Query Attention (GQA)
Shares key/value heads across multiple query heads. Reduces memory and speeds up inference. Used in LLaMA-3, Mistral.
KV Cache
During inference, store computed key and value tensors from previous tokens. Avoids recomputing them each step. Essential for practical autoregressive generation.

20.2 Scaling Laws

Chinchilla (2022) showed the optimal relationship: train on ~20 tokens per parameter. Many earlier models were over-parameterized and under-trained (too big, too little data). Loss follows power laws with both model size and training data size.

20.3 In-Context Learning

GPT-3 showed that LLMs can perform few-shot learning just from prompt formatting — no gradient updates. Give the model a few examples in the prompt; it infers the task from context and answers. The model is learning from context at inference time, without updating weights.

20.4 Chain-of-Thought Prompting

Adding "Let's think step by step" dramatically improves performance on reasoning tasks. The model generates intermediate reasoning steps before the final answer. The final answer is conditioned on the reasoning chain — externalizing computation that would otherwise need to happen implicitly.

CH 21

Large Vision Models (LVMs) Frontier

21.1 What Are LVMs?

Large Vision Models are foundation models for visual data — pretrained on massive image datasets, adaptable to many vision tasks. Same philosophy as LLMs: pretrain at scale, adapt as needed.

21.2 Key Models

DINO / DINOv2
Self-supervised ViT trained with knowledge distillation from a momentum encoder (teacher = EMA of student). No labels required. Learns interpretable segmentation features. DINOv2 (2023) trained on curated 142M images — excellent general-purpose visual features.
SAM (Segment Anything Model)
Trained on 1B masks from 11M images. Segments any object given a point, box, or text prompt. Remarkable zero-shot generalization — works on images it has never seen before.
MAE
Masks 75% of image patches, reconstructs them. Simple, scalable, effective for ViT pretraining.

21.3 Self-Supervised Methods for Vision (Important Background)

SimCLR
Two augmented views of the same image → push representations together; push different images apart. No labels.
MoCo (Momentum Contrast)
Momentum encoder (slow EMA) produces stable targets. Enables large effective batch sizes without storing them in memory.
MAE
Mask 75% of patches, reconstruct them. Simple but extremely effective.
CH 22

Multi-Modal LLMs — CLIP, BLIP & Beyond Frontier

22.1 What Makes a Model Multi-Modal?

A multi-modal model processes data from multiple modalities simultaneously — text, images, audio, video. The challenge is learning a joint representation space where different modalities can communicate with each other meaningfully.

22.2 CLIP (OpenAI, 2021)

Trained on 400 million (image, text) pairs from the internet. Learns to align image and text embeddings in a shared space.

Architecture
Image encoder (ViT or ResNet) + Text encoder (Transformer). Both project to the same d-dimensional space.
Contrastive Loss (InfoNCE)
In a batch of N pairs, maximize cosine similarity on the diagonal (matched pairs), minimize off-diagonal (mismatched pairs).
Zero-shot classification
Encode class names as text ("a photo of a cat"). Encode test image. Predict: class with highest cosine similarity to the image. No task-specific fine-tuning needed.
CLIP InfoNCE Loss (for images) L = −log [ exp(sim(Iᵢ,Tᵢ)/τ) / Σⱼ exp(sim(Iᵢ,Tⱼ)/τ) ]

22.3 BLIP (2022)

Addresses CLIP's weakness: noisy web training data. BLIP bootstraps cleaner training data.

Architecture additions
Adds a multimodal encoder (image+text with cross-attention) and an image-grounded text decoder. Three objectives trained simultaneously: ITC (contrastive), ITM (image-text matching), LM (language modeling).
CapFilt
Captioner generates synthetic captions for web images. Filter removes noisy web captions and bad synthetic ones. This bootstrapping creates cleaner pseudo-labeled training data.

22.4 BLIP-2 (2023)

Freeze a pretrained image encoder AND a pretrained LLM. Bridge them with a lightweight Q-Former — 32 learnable query tokens that attend to image features. Only the Q-Former is trained. Extremely parameter-efficient.

Frozen Image Encoder → Q-Former → Frozen LLM
                         ↑
               32 learnable query tokens

22.5 Flamingo (DeepMind, 2022)

Connects a frozen vision encoder to a frozen LLM using cross-attention layers inserted between LLM layers. Trained on interleaved image-text sequences. Enables few-shot visual question answering — give a few (image, question, answer) examples, then ask about a new image.

22.6 ImageBind (Meta, 2023)

Extends CLIP to 6 modalities: image, text, audio, depth, thermal, IMU. Uses images as the binding modality — aligning all modalities to images implicitly aligns them to each other. Enables cross-modal retrieval between modalities that were never directly paired in training (e.g., retrieve audio from text).

🧠 Check Your Understanding
  • What is contrastive learning and why does it train CLIP effectively?
  • How does CLIP perform zero-shot classification without being explicitly trained on classification?
  • What problem does BLIP's CapFilt solve?
  • What does the Q-Former do in BLIP-2, and why is freezing both encoder and LLM advantageous?
CH 23

LLaVA Frontier

23.1 What Is LLaVA?

LLaVA (Large Language and Vision Assistant, Liu et al., 2023) connects a CLIP vision encoder to a LLaMA/Vicuna LLM using a simple linear projection layer. Despite its architectural simplicity, it achieves strong performance on visual dialogue and question answering. It democratized multi-modal LLM research.

23.2 Architecture

Image Input
    ↓
CLIP Image Encoder (frozen ViT-L/14)
    ↓  visual features [N × D_clip]
Linear Projection Layer (trainable)
    ↓  visual tokens [N × D_llm]
    ↕
LLM (LLaMA / Vicuna) — processes [visual tokens + text tokens] together
    ↓
Text output (answer to the question)

The visual features are projected into the LLM's embedding space and prepended to the text token sequence. The LLM sees them as "extra tokens" at the start of the sequence.

23.3 Training Data — The Key Innovation

LLaVA's training data was generated using GPT-4. The authors gave GPT-4 image captions and bounding boxes (text descriptions of visual content — not the actual images) and asked it to generate:

Conversation data
Multi-turn Q&A about the image — questions a curious person might ask.
Detailed descriptions
Long, rich descriptions of the image content.
Complex reasoning
Questions requiring multi-step reasoning about what is shown.

Total: 158K samples generated this way. High quality instruction-following data without expensive human annotation.

23.4 Two-Stage Training

Stage 1 — Feature Alignment

  • Freeze: CLIP encoder + LLM
  • Train: projection layer only
  • Data: 595K image-caption pairs (CC-595K)
  • Goal: make visual tokens meaningful to LLM

Stage 2 — End-to-End Fine-tuning

  • Freeze: CLIP encoder only
  • Train: projection layer + LLM
  • Data: 158K GPT-4 generated instructions
  • Goal: teach visual instruction following

23.5 LLaVA-1.5 and Beyond

LLaVA-1.5 (2023)
Replace linear projection with a 2-layer MLP. Use higher resolution (336×336). More instruction data. Significant performance improvement.
LLaVA-NeXT (2024)
Handle even higher resolutions by splitting images into sub-images, processing each separately, concatenating. Supports resolutions up to 672×672+.

23.6 Why LLaVA Matters

LLaVA showed that a simple linear projection between a frozen vision encoder and an LLM — trained on GPT-4 generated instruction data — is enough to build a powerful visual assistant. This principle (freeze → bridge → freeze) has become the dominant paradigm for building multi-modal models cheaply and effectively.
REF

Summary Table — All Topics

TopicWhat It DoesKey IdeaRelated To
EncoderCompress input to latentLearn compact representationsAutoencoders, ViT, CLIP
DecoderReconstruct from latentGenerate from representationAutoencoders, Transformers
Autoencoder (vanilla)Reconstruct input via bottleneckBottleneck compressionFoundation for all AE variants
Denoising AEReconstruct from corrupted inputLearn the data manifoldDiffusion models
Stacked AEHierarchical layer-wise pretrainingTrain deep networks layer by layerDeep pretraining, BERT
Contractive AEInsensitive encoder via Jacobian penaltyPenalize sensitivity explicitlyRobust representations
VAEGenerate new data by sampling latentProbabilistic latent space + KL priorGANs, BLIP, generative models
AttentionSelective, weighted combination of contextQuery-Key-Value lookupTransformers, ViT, CLIP, LLaVA
TransformerSequence processing via stacked attentionFully parallel, long-range dependenciesLLMs, ViT, BERT, T5
ViTImage processing via transformerPatches as tokensLVMs, CLIP image encoder, LLaVA
GANGenerate realistic data via adversarial gameGenerator vs DiscriminatorCycleGAN, StyleGAN, domain adaptation
Modern GANsBetter, controllable generationStability tricks + architectural innovationsStyleGAN, CycleGAN, WGAN
Transfer LearningReuse pretrained knowledgePretrained features are generalFine-tuning, distillation
Fine-tuningAdapt pretrained model to new taskUpdate weights on new task dataLoRA, PEFT, LLaVA Stage 2
Knowledge DistillationCompress large model into small oneSoft label transfer with temperatureDistilBERT, DeiT, TinyBERT
Knowledge TransferMove knowledge between settingsBroad paradigm: zero/few-shot, meta-learningCLIP zero-shot, MAML
Domain AdaptationHandle distribution shiftLearn domain-invariant representationsDANN, CORAL, self-training
Active LearningLabel most informative examplesAcquisition function selects queriesEntropy, CoreSet, BADGE
Semi-supervised ALCombine SSL and active learningUse unlabeled data to improve queryingVAAL, FixMatch, Mean Teacher
Foundation ModelsPretrain at scale, adapt anywhereGeneral + emergent + adaptableLLMs, LVMs, CLIP, LLaVA
LLMsLanguage understanding and generationDecoder-only transformers + scalingGPT, LLaMA, ChatGPT
LVMsVisual features at scaleSelf-supervised ViT pretrainingSAM, DINOv2, CLIP image encoder
CLIPAlign image and text in shared spaceContrastive pretraining on 400M pairsZero-shot classification, LLaVA, BLIP
BLIP / BLIP-2Image-text understanding + generationCapFilt bootstrapping + Q-Former bridgeVQA, captioning, multi-modal
LLaVAVisual dialogue and instruction followingCLIP encoder → linear projection → LLMTies everything together
REF

Key Equations Reference

Autoencoder Loss
L = ||x − g(f(x))||²
VAE ELBO
L = E[log p(x|z)] − KL(q(z|x) || p(z))
GAN Objective
min_G max_D E[log D(x)] + E[log(1−D(G(z)))]
Scaled Dot-Product Attention
Attn(Q,K,V) = softmax(QKᵀ / √d_k) V
Knowledge Distillation
L = α·L_CE + (1−α)·L_KL(stu/T || tea/T)
CLIP InfoNCE Loss
L = −log[exp(sim(Iᵢ,Tᵢ)/τ) / Σⱼ exp(sim(Iᵢ,Tⱼ)/τ)]
LoRA Update
W' = W + AB, A∈ℝ^(d×r), B∈ℝ^(r×k), r≪min(d,k)
Entropy (Active Learning)
H(p) = −Σᵢ pᵢ log pᵢ
CAE Loss
L = ||x−x̂||² + λ||J_f(x)||²_F
Cycle Consistency (CycleGAN)
||G_BA(G_AB(x)) − x||₁ ≈ 0
Sinusoidal Position Encoding
PE(pos,2i) = sin(pos/10000^(2i/d))
WGAN Critic Loss
L_W = −D(x) + D(G(z))