SRM Day 3 Hub | Prev Session | Next Session

Emergence of Generative AI, Transformers, BERT & GPT

From Probabilistic Sequence Models to Self-Attention, Bidirectional Encoding, and Autoregressive Text Generation

VAEs & GANs Self-Attention Math BERT & GPT

The Genesis of Generative Models

Before modern transformers, AI shifted from static classification to generating synthetic sequential data.

HMMs

Hidden Markov Models captured short-term state transitions. Great for speech, but failed at long context.

RBMs

Restricted Boltzmann Machines learned compressed representations by reconstructing inputs via energy states.

PixelCNN

Generated images pixel-by-pixel sequentially. Ensured local consistency, but suffered from extremely slow generation.

WaveNet

Breakthrough audio model generating raw waveforms. Produced human-like speech, but computationally expensive.

The Core Challenge: Early probabilistic models captured local patterns, but lacked diversity, long-range coherence, and creativity. This spurred the development of continuous latent space models.

Variational Autoencoders (VAEs)

Autoencoder vs VAE

Classic Autoencoder: Encodes input into a single fixed vector. Good for compression, but cannot generate new data.

VAE: Encodes input into a probabilistic distribution (Mean $\mu$ and Variance $\sigma^2$), allowing sampling of brand new points!

The Reparameterization Trick

Direct sampling is non-differentiable. VAEs sample noise $\epsilon \sim \mathcal{N}(0, I)$ and scale it:

$$z = \mu + \sigma \odot \epsilon$$

This allows backpropagation to flow smoothly through the encoder!

VAE Loss Function

VAEs balance reconstruction quality with a continuous latent space:

$$\mathcal{L}_{VAE} = \text{Reconstruction Loss} + D_{KL}(q(z|x) \,||\, p(z))$$
  • KL Divergence: Forces the latent distribution to match a standard normal prior $\mathcal{N}(0, I)$.
  • Smooth Interpolation: Enables smooth morphing between images or handwritten digits without gaps in latent space.

Generative Adversarial Networks (GANs)

Introduced by Ian Goodfellow (2014), GANs framed generation as a zero-sum game between two competing networks.

The Generator (The Forger)

Takes random noise vector $z$ and creates synthetic samples $G(z)$. Objective: Fool the discriminator into thinking the fake sample is real!

The Discriminator (The Detective)

Evaluates real images $x$ and generated images $G(z)$. Objective: Correctly classify real as 1 and fake as 0!

$$\min_G \max_D V(D, G) = \mathbb{E}_{x \sim p_{data}}[\log D(x)] + \mathbb{E}_{z \sim p_z}[\log(1 - D(G(z)))]$$

🌟 Strengths: Produces hyper-realistic, high-frequency image details without blurriness.

⚠️ Challenges: Training instability & Mode Collapse (generator repeats identical samples).

The Bottleneck: Why Attention Was Needed

Traditional Encoder-Decoder Limit

Seq2Seq models (RNN/LSTM) compressed an entire 100-word sentence into a single fixed vector.

Information Loss Bottleneck

Like forcing someone to memorize an entire textbook page and summarize it in one single word!

The Attention Solution

Instead of one fixed summary vector, Attention allows the model to look back at all input tokens at every decoding step!

Dynamic Weighting per Step

Acts like a highlighter—dynamically zooming in on relevant source words when generating each output word!

Anatomy of Attention: Query, Key, and Value

Attention converts retrieval into a continuous, differentiable database lookup.

Query ($Q$)

Represents the target token's question: "What information am I looking for right now?"

Key ($K$)

Represents the input tokens' labels: "What content or topic do I contain?"

Value ($V$)

Represents the actual information content to be passed forward if matched.

The 3-Step Attention Recipe

  1. Dot-Product Similarity: Compute $\text{Score} = Q \cdot K^T$ to measure how well query matches each key.
  2. Softmax Normalization: Scale by $\sqrt{d_k}$ and apply $\text{softmax}()$ to convert scores into attention weights (summing to 1).
  3. Weighted Sum: Multiply weights by Values $V$ to construct a custom contextual vector.

Scaled Dot-Product Attention

$$\text{Attention}(Q, K, V) = \text{softmax}\left(\frac{QK^T}{\sqrt{d_k}}\right)V$$

Why Scale by $\sqrt{d_k}$?

For large vector dimensions $d_k$, dot products grow large in magnitude, pushing softmax into regions with extremely small gradients (vanishing gradient problem).

Scaling by $\sqrt{d_k}$ keeps variance at 1 and keeps gradients stable!

Matrix Parallelization

Instead of looping over words one-by-one, $Q, K, V$ are packed into matrices, allowing GPU tensor math to compute attention for all words simultaneously!

The Transformer Architecture (Vaswani et al., 2017)

"Attention Is All You Need" replaced recurrent loops completely with self-attention layers.

Encoder Stack

  • Multi-Head Self-Attention: Words inspect all other words bidirectionally.
  • Residual Connections & LayerNorm: $x + \text{SubLayer}(x)$ maintains gradient stability.
  • Position-wise Feed Forward: Applies point-wise non-linear projections.

Decoder Stack

  • Masked Self-Attention: Prevents looking ahead to future tokens.
  • Cross-Attention: Queries come from decoder; Keys/Values come from encoder.
  • Autoregressive Generation: Predicts tokens step-by-step.

Multi-Head Attention: Multiple Perspectives

A single attention head might focus on subject-verb relationships. Multi-Head Attention runs multiple operations in parallel.

$$\text{MultiHead}(Q, K, V) = \text{Concat}(\text{head}_1, \dots, \text{head}_h)W^O$$

Head 1: Syntactic

Tracks grammatical links (e.g. connecting verb "flew" to subject "bat").

Head 2: Semantic

Tracks contextual meaning (e.g. connecting "bat" to "cave" to infer animal).

Head 3: Positional

Tracks adjacent token relationships and phrase boundaries.

Positional Encoding: Giving Order to Tokens

Since self-attention operates on sets (permutation-invariant), we must inject word order explicitly into token embeddings!

Absolute (Sinusoidal)

Uses fixed sine & cosine functions of different frequencies:

$$PE_{(pos, 2i)} = \sin\left(\frac{pos}{10000^{2i/d}}\right)$$

Extrapolates to longer sequences, but fixed.

Learned Position

Assigns a dedicated trainable vector to every index (0 to 512).

Used in BERT & GPT-2. Simple, but cannot extend beyond max length.

Rotary Embeddings (RoPE)

Rotates token vectors in complex space based on position.

Used in LLaMA, Mistral, GPT-4. Generalizes to long contexts!

BERT: Bidirectional Encoder Representations

Released by Google (2018), BERT is an Encoder-Only architecture designed for deep language understanding.

Why Bidirectional?

Traditional left-to-right models miss context following a word. BERT reads the entire sentence simultaneously!

"The bat flew out of the cave."

BERT uses both "flew" (left) and "cave" (right) to know bat means an animal, not sports gear.

Input Embeddings Trio

  • Token Embeddings: WordPiece subwords (e.g. playing $\to$ play + ##ing).
  • Segment Embeddings: Identifies Sentence A vs Sentence B.
  • Position Embeddings: Identifies sequence position.

How BERT Learns: MLM & NSP

BERT is pretrained on unlabelled text (Wikipedia & BookCorpus) via two self-supervised tasks:

1. Masked Language Modeling (MLM)

15% of input tokens are randomly replaced with a [MASK] token.

Input: The [MASK] sat on the mat.
Target: "cat"

Forces BERT to use bidirectional context to fill in the blanks!

2. Next Sentence Prediction (NSP)

Model is fed pairs of sentences and predicts if Sentence B logically follows Sentence A.

[CLS] Sun shines [SEP] Kids play [SEP] $\to$ IsNext
[CLS] Sun shines [SEP] Stock market [SEP] $\to$ NotNext

GPT: Generative Pre-trained Transformer

Introduced by OpenAI (2018), GPT flips the script: an Decoder-Only architecture designed for text creation.

Autoregressive Text Generation

GPT predicts the next token in a sequence based on past tokens, one step at a time.

$$P(w_1, w_2, \dots, w_N) = \prod_{i=1}^N P(w_i \mid w_1, \dots, w_{i-1})$$

Causal Masked Self-Attention

To prevent the model from "cheating" by peeking at future words during training, an upper-triangular mask sets future attention weights to $-\infty$.

Token at index $i$ can ONLY attend to tokens at indices $\le i$!

Scaling GPT: Pretraining & RLHF Alignment

1. Unsupervised Pretraining

Trained on billions of tokens (web text, books, code) to minimize next-token prediction error.

Learns grammar, world facts, reasoning patterns, and coding syntax automatically!

2. RLHF Alignment (InstructGPT / ChatGPT)

Raw LLMs complete text, but can output harmful or unhelpful responses. Reinforcement Learning from Human Feedback aligns the model:

  1. Collect human rank-orderings of responses.
  2. Train a Reward Model.
  3. Fine-tune LLM using PPO (Proximal Policy Optimization).

Live Code: Computing Self-Attention in Python

import numpy as np

def softmax(x):
    e_x = np.exp(x - np.max(x, axis=-1, keepdims=True))
    return e_x / np.sum(e_x, axis=-1, keepdims=True)

# Toy Embeddings (4 words, dim=4)
np.random.seed(42)
X = np.random.randn(4, 4)

# Linear Projections Q, K, V
W_q = np.random.randn(4, 4)
W_k = np.random.randn(4, 4)
W_v = np.random.randn(4, 4)

Q = np.dot(X, W_q)
K = np.dot(X, W_k)
V = np.dot(X, W_v)

# Scaled Dot-Product Attention
d_k = Q.shape[-1]
scores = np.dot(Q, K.T) / np.sqrt(d_k)
weights = softmax(scores)
output = np.dot(weights, V)

print("Attention Weights Matrix:\n", np.round(weights, 3))
print("\nContextualized Vector:\n", np.round(output[0], 3))

Code Explanation

1. Takes input token embeddings X.

2. Projects into Query, Key, and Value matrices (Q, K, V).

3. Computes dot-product $Q \cdot K^T / \sqrt{d_k}$.

4. Applies softmax to produce probability weights.

5. Multiplies weights by V to get contextual embeddings!

Model Paradigm Comparison

Architecture Type Attention Mask Primary Strengths Famous Models
BERT Encoder-Only None (Bidirectional) Deep language comprehension, classification, QA, NER BERT, RoBERTa, DeBERTa
GPT Decoder-Only Causal (Left-to-Right) Fluent text generation, dialogue, coding, zero-shot tasks GPT-4, LLaMA, Claude, Mistral
T5 / BART Encoder-Decoder Encoder: Bidirectional
Decoder: Causal
Translation, summarization, text-to-text transformation T5, BART, Whisper
VAEs / GANs Latent / Adversarial N/A Image synthesis, audio generation, style transfer StyleGAN, VAE, Stable Diffusion
Session 7 Summary

The Generative AI Revolution

1. Probabilistic to Latent

VAEs and GANs proved neural networks could generate authentic new data distributions.

2. Attention Mechanism

Removed recurrent bottlenecks and fixed information loss in long sequences.

3. Scale & Alignment

Decoder-only scaling combined with RLHF unlocked modern conversational foundation models.

Return to SRM PDP Talk Hub
1 / 17