Generative AI
Generative AI
This document serves as a rigorous, self-contained reference for university students and faculty
exploring the full landscape of Generative Artificial Intelligence. From foundational probability
theory to state-of-the-art diffusion models, transformer architectures, alignment techniques, and
deployment considerations, every major topic is treated with academic precision and practical
intuition. Content is structured to progress naturally from first principles to advanced concepts,
ensuring both conceptual clarity and mathematical grounding throughout.
Foundations Architectures
Probability, latent spaces, likelihood VAEs, GANs, Diffusion Models,
estimation, generative vs. discriminative Transformers, Encoder-Decoder
models frameworks
The intuition is straightforward: imagine you have studied ten thousand hand-written digits. A
generative model does not merely learn to classify which digit is which — it learns the texture,
stroke patterns, curvature tendencies, and spatial distributions so intimately that it can
independently produce a new digit that looks authentically hand-written, even though it was never
in the training set. This is the core distinction between generation and recognition.
Models the full joint distribution p(x, y). Can Models only the conditional p(y | x). Learns
synthesize new data. Examples: VAE, GAN, decision boundaries. Examples: Logistic
Diffusion, GPT. Regression, SVM, BERT (for classification).
A helpful numerical analogy: suppose you observe the dataset {2, 4, 6, 8, 10}. A discriminative
model learns "even numbers go to class A." A generative model learns the underlying pattern well
enough to produce 12 or 3.7 as plausible continuations. The difference is between boundary
learning and distribution learning. This distinction has profound implications for architecture
design, loss functions, and evaluation strategies.
The decade of the 2010s witnessed three landmark architectural innovations. In 2013, Variational
Autoencoders (VAEs) introduced the reparameterization trick, enabling gradient-based
optimization of a lower bound on the data likelihood while simultaneously learning a structured
latent space. In 2014, Generative Adversarial Networks (GANs) reframed generation as a minimax
game between a generator and a discriminator — a radical departure from explicit likelihood
maximization. By the late 2010s, Autoregressive models (PixelCNN, WaveNet, GPT) demonstrated
that simply predicting the next token in a sequence — given all previous tokens — could produce
remarkably coherent text and images when scaled sufficiently.
1985 1
Boltzmann Machines — energy-based
generative models
2 2013
Variational Autoencoders (VAE) — latent
variable models with ELBO
2014 3
Generative Adversarial Networks (GAN)
— adversarial minimax training
4 2017
Transformers ("Attention is All You
Need") — attention-based sequence
2020–23 5 modeling
Diffusion Models + LLMs — DALL-E,
Stable Diffusion, GPT-4, Gemini
The most recent paradigm shift came with Denoising Diffusion Probabilistic Models (DDPMs), which
model generation as the reversal of a Markov chain of incremental Gaussian noise additions. Score-
based variants (Song & Ermon, 2020) unified the theoretical framework via stochastic differential
equations. Concurrently, transformer-based language models scaled to billions of parameters,
demonstrating emergent capabilities in code generation, reasoning, and cross-modal synthesis.
Autoregressive Models VAE
Factorize joint distribution as a product Learn a compressed latent
of conditionals: p(x) = ∏ p(xᵢ | x₁,...,xᵢ₋₁). representation z and reconstruct data
Exact likelihood, sequential generation. via decoder. Optimize the Evidence
Examples: GPT, PixelCNN. Lower BOund (ELBO). Enables smooth
interpolation in latent space.
In practice, we maximize the log-likelihood for numerical stability: ℓ(θ) = Σᵢ log p_θ(xᵢ). Consider a simple
Gaussian model where p_θ(x) = N(x; μ, σ²). Given five data points {1.0, 2.0, 3.0, 4.0, 5.0}, the MLE estimates
= 3.0 and σ̂ ² = 2.0. This means the learned model assigns highest probability density around x = 3, and
are μ̂
samples drawn from N(3, 2) will resemble the training distribution.
0.25
0.2
0.15
0.1
0.05
0
0 0.5 1 1.5 2 2.5 3 3.5 4 4.5 5 5.5 6
Data Value (x)
The chart above shows the MLE-fitted Gaussian density over the data range. Maximum density at x = 3.0
corresponds precisely to the estimated mean μ̂ = 3.0, confirming that MLE correctly identifies the center of
the data distribution. Generating new samples means drawing random values from this bell curve.
Latent Variable Modeling
Many real-world distributions are too complex to model directly. Latent variable models introduce
an unobserved variable z such that p_θ(x) = ∫ p_θ(x | z) p(z) dz. The key insight is that conditioning
on z makes the generative process tractable: for a given z, generating x is simple, even though the
marginal p(x) is complex. The prior p(z) is typically chosen as a standard Gaussian N(0, I) for
mathematical convenience and sampling simplicity.
Variational Autoencoders (VAE)
The Variational Autoencoder, introduced by Kingma and Welling in 2013, is one of the most
theoretically elegant generative architectures in deep learning. It addresses the intractability of
computing p_θ(x) = ∫ p_θ(x|z)p(z)dz by introducing a variational approximation: an encoder network
q_φ(z|x) that approximates the true posterior p_θ(z|x). The encoder and decoder are jointly trained
by maximizing the Evidence Lower BOund (ELBO).
The first term is the reconstruction loss — how well the decoder reproduces the input from the
latent code. The second term is the KL divergence regularizer — it penalizes the encoder for
producing a posterior that deviates from the standard Gaussian prior. Together, these two terms
create a productive tension: the model must compress data meaningfully while keeping the latent
space well-structured.
Reparameterization Trick
Sampling from z ~ q_φ(z|x) = N(μ_φ(x), σ²_φ(x)) is non-differentiable. The reparameterization trick
rewrites this as z = μ_φ(x) + σ_φ(x) · ε where ε ~ N(0, I). This moves randomness outside the
computational graph, enabling clean backpropagation through the encoder. It is one of the most
impactful "tricks" in modern deep learning.
1. Input x → Encoder → outputs μ and log σ² Let encoder output μ = 0.5, σ = 0.8. Sample ε =
Adversarial Objective
min max V (D, G) = Ex∼pdata [log D(x)] + Ez∼pz [log(1 − D(G(z)))]
G D
The discriminator D maximizes this expression: it wants D(x) → 1 for real data and D(G(z)) → 0 for
fakes. The generator G minimizes it: it wants D(G(z)) → 1, i.e., to fool the discriminator completely.
At the theoretical Nash equilibrium, p_G = p_data and D(x) = 0.5 everywhere — the discriminator is
maximally confused.
Discriminate
D scores real versus fake Backpropagate
Update G and D with
gradients
The diagram above captures the adversarial feedback cycle that drives GAN training. Each iteration
tightens the discriminator's judgment and sharpens the generator's output, in an escalating
competition that converges (ideally) to photorealistic synthesis.
Generator Network Discriminator Network
Input: random noise vector z ~ N(0, I), typically Input: either real image x or fake G(z).
100-dimensional. Architecture: series of Architecture: standard convolutional
transposed convolutions (deconvolutions) that classifier. Output: scalar probability D(x) ∈
upsample from dense latent code to full image [0,1] — probability input is real. Uses
resolution. Output: synthetic image G(z). Uses LeakyReLU activations and no batch
Tanh activation at final layer to match pixel normalization in early layers to maintain
value range [-1, 1]. gradient flow.
1 2 3
Forward Process
The forward process is a fixed Markov chain that adds Gaussian noise at each of T timesteps:
where β_t ∈ (0,1) is a noise schedule. By t = T, the data x_T is approximately standard Gaussian —
all structure has been destroyed. A key mathematical identity allows sampling at any arbitrary
timestep directly: x_t = √ᾱ_t · x_0 + √(1-ᾱ_t) · ε, where ᾱ_t = ∏ₛ(1-βₛ) and ε ~ N(0,I).
The model learns to predict the noise ε that was added at step t. This is equivalent to score
matching — estimating the gradient of the log data density. During inference, generation proceeds
by sampling x_T ~ N(0,I) and iteratively applying the learned denoiser for T steps.
Noise 1ᾱ_t) Signal (ᾱ_t)
0.8
0.6
0.4
0.2
0
0 50 100 150 200 250 300 350 400 450 500 550 600 650 700 750 800 850 900 950 1k
Timestep t
The chart illustrates the signal-to-noise ratio throughout the forward diffusion process. At t = 0, the
data is clean (signal = 1.0). By t = 1000, the signal is fully destroyed and only noise remains. The
reverse process must reconstruct this journey in the opposite direction — recovering structure
from randomness — which is what the neural network learns.
Transformer-Based Generative Models
The Transformer architecture (Vaswani et al., 2017) is the foundational backbone for virtually all
modern large-scale generative AI systems. Its key innovation — scaled dot-product self-attention
— allows every token in a sequence to attend directly to every other token, capturing long-range
dependencies that recurrent architectures (LSTMs, GRUs) struggled with. The attention mechanism
is defined as:
QK T
Attention(Q, K, V ) = softmax ( )V
dk
Here, Q (queries), K (keys), and V (values) are linear projections of the input embeddings. The
scaling by √d_k prevents vanishing gradients in the softmax when dimensionality is large. Multi-
head attention runs this operation in parallel with h different projection matrices, allowing the
model to attend to multiple "aspects" of context simultaneously.
Token a is sampled 65.9% of the time under greedy/temperature-1 sampling. Changing the
temperature parameter T rescales logits as logit/T: T → 0 produces greedy deterministic output; T
> 1 increases diversity and randomness. This simple parameter dramatically influences generation
style.
Training Techniques: Pretraining, Fine-
Tuning & Instruction Tuning
Modern large generative models are trained in a carefully orchestrated multi-stage pipeline. Each
stage serves a distinct objective, and understanding the interplay between stages is essential for
practitioners who wish to build domain-specific or task-aligned AI systems.
Stage 1: Pretraining
Pretraining is the large-scale unsupervised (or self-supervised) phase where the model is exposed
to enormous text corpora — often trillions of tokens scraped from web pages, books, code
repositories, and scientific papers. The objective is simply next-token prediction. During this phase,
the model does not receive any task-specific guidance; it learns the statistical regularities of
language, factual associations, grammatical structures, and implicit reasoning patterns purely from
the distributional statistics of text. This phase requires immense computational resources: GPT-3
required approximately 3.14 × 10²³ FLOPS to train on 300 billion tokens.
Stage 2: Fine-Tuning
Fine-tuning adapts the pretrained model to a specific domain or task using a smaller, curated
labeled dataset. Standard fine-tuning updates all model parameters. A fine-tuned model will
converge faster than training from scratch and typically requires orders of magnitude less data,
because the pretrained weights encode rich general representations that need only minor
adjustment.
retraining Fine-Tuning
Massive corpus, self-supervised, next-token Curated labeled data, task-specific
prediction. Builds world knowledge. adaptation. Transfers pretrained
representations.
3 4
Zero-Shot Few-Shot
Directly state the task. Example: "Classify Provide 2–8 input-output examples before
the sentiment of the following review: the target query. Leverages in-context
[review]". Relies entirely on pretrained learning. Highly effective for structured
knowledge. No examples provided. tasks like classification, extraction,
translation.
Zero-Shot (GPT-3)
Few-Shot (8 examples)
Chain-of-Thought
CoT + Self-Consistency
0 10 20 30 40 50 60 70 80
Accuracy (%) on GSM8K
The accuracy gains from chain-of-thought prompting are substantial — a 3× improvement over
zero-shot, with self-consistency (sampling multiple CoT paths and taking the majority answer)
pushing accuracy to 74% without any weight updates. This chart demonstrates that how you
prompt can matter as much as which model you use.
Retrieval-Augmented Generation
(RAG)
Retrieval-Augmented Generation (RAG), introduced by Lewis et al. (2020), addresses one of the
most critical limitations of standalone language models: their knowledge is static, bounded by the
training cutoff date, and prone to hallucination on factual queries. RAG hybridizes a parametric
language model (which stores knowledge in weights) with a non-parametric external knowledge
store (which stores documents in a searchable format), enabling the model to ground its responses
in retrieved evidence.
User Query
Encode Query
Retrieve Chunks
Concatenate Context
The five-stage pipeline above shows how RAG elegantly separates the retrieval problem from the
generation problem. The retrieval component is responsible for finding relevant evidence; the
generation component is responsible for synthesizing a coherent, grounded answer from that
evidence. This separation enables independent updates — the knowledge base can be refreshed
without retraining the language model.
Text-to-Image
CLIP embeddings align text and image spaces. Diffusion models conditioned on text
embeddings synthesize photorealistic images. Examples: DALL-E 3, Stable Diffusion
XL, Midjourney v6.
Text-to-Video
Extends image diffusion with temporal attention layers for coherent motion.
Challenges: maintaining cross-frame consistency, physics plausibility. Examples:
Sora, Gen-2, Lumiere.
Image-to-Text
Vision encoders (ViT, CLIP) extract visual features; language decoder generates
descriptions. Enables image captioning, VQA, OCR. Examples: GPT-4V, LLaVA,
Flamingo.
Audio Generation
Autoregressive (AudioLM) or diffusion-based (AudioLDM) models generate speech,
music, and sound effects from text descriptions or conditioning signals. Examples:
Bark, MusicGen, ElevenLabs.
0 1 ~0 ~0
Perplexity BLEU Score (0–1) ROUGE (0–1) FID Score
Ideal value; lower is Bilingual Evaluation Recall-Oriented Fréchet Inception
better. Measures how Understudy. Measures Understudy for Gisting Distance for image
well the model n-gram overlap Evaluation. Recall- generation. Compares
predicts a test corpus. between generated focused n-gram feature-space
PP(W) = and reference text. overlap. ROUGE-L distributions. Lower is
p(w₁,...,wₙ)^(-1/n). GPT- Widely used in uses longest common better; state-of-the-
2 achieves ~35 on translation; criticized subsequence. art diffusion models
Penn Treebank; GPT-3 for penalizing valid Standard for achieve FID < 5 on
~20. paraphrases. summarization CIFAR-10.
evaluation.
Average log-probability = -(0.434 + 0.250 + 0.580 + 0.330) = -1.594. Perplexity = 2^(1.594) = 3.02.
Interpretation: the model is, on average, as uncertain as choosing uniformly among 3 options at
each step. A better model would reduce this to closer to 1.0 (perfect certainty) or at least below 2.0
for well-structured text.
RLHF, Alignment & Bias/Hallucination
Reinforcement Learning from Human Feedback (RLHF) is the training paradigm that transformed
instruction-following base models into aligned assistants like ChatGPT and Claude. The fundamental
challenge is that the objective of "be helpful, harmless, and honest" is difficult to encode as a simple
mathematical loss function. RLHF solves this by training a reward model on human preference data,
then using that reward model as an optimization signal through reinforcement learning.
Reward Model
Training
Learn human
preference
comparisons (A vs
B)
PPO
Supervised Reinforcement
Fine-Tuning Learning
Train on (prompt, Update LLM to
response) maximize reward
demonstrations scores
Hallucination in LLMs
Hallucination refers to the generation of text that is fluent and confident but factually incorrect or
fabricated. It arises because LLMs are trained to predict statistically likely next tokens, not to verify
factual accuracy. A model trained on biased internet text may reproduce plausible-sounding
falsehoods. Mitigation strategies include RAG (grounding generation in retrieved evidence), chain-of-
thought verification, calibration training, and Constitutional AI principles (Anthropic). Critically,
perplexity-based metrics do not detect hallucination — a hallucinated sentence may have low perplexity
if the fabricated fact sounds linguistically plausible.
Data Bias Hallucination Reward Hacking
Training corpora over- Model generates confident In RLHF, models learn to
represent certain but false statements. exploit weaknesses in the
demographics, languages, Exacerbated by insufficient reward model — producing
and viewpoints. Models grounding, long-tail outputs that score highly by
inherit these biases, knowledge gaps, and reward the reward model but are not
producing systematically hacking. Mitigation: RAG, genuinely helpful. Requires
skewed outputs. Mitigation: fact-checking pipelines, reward model regularization
dataset curation, debiasing uncertainty quantification. and red-teaming.
embeddings, counterfactual
data augmentation.
Parameter-Efficient Fine-Tuning: LoRA,
Adapters & Prefix Tuning
Full fine-tuning of large language models — updating all billions of parameters — is prohibitively
expensive for most research groups and companies. Parameter-Efficient Fine-Tuning (PEFT)
methods address this by freezing the pretrained model's weights and introducing a small number
of trainable parameters that adapt the model's behavior. This enables high-quality task adaptation
at a fraction of the computational cost.
W ′ = W + ΔW = W + BA
where B ∈ ℝ^{d×r} and A ∈ ℝ^{r×k} with rank r ≪ min(d, k). Only A and B are trained; W is frozen.
For a typical d = k = 4096 matrix, full fine-tuning trains 16.7 million parameters. With r = 8, LoRA
trains only 2 × 4096 × 8 = 65,536 parameters — a 256× reduction.
6k
4k
2k
0
Full Fine-Tuning Adapter Layers Prefix Tuning LoRA (r=16) LoRA (r=4)
Fine-Tuning Method
Adapter Layers Prefix Tuning QLoRA
Small bottleneck modules Prepends k learned Combines LoRA with 4-bit
inserted between "virtual" token quantization of the frozen
transformer layers. Each embeddings to every base model. Enables fine-
adapter has a down- layer's key and value tuning of 70B-parameter
projection (d → r), non- matrices. These soft models on a single 48GB
linearity, and up- prompts modulate GPU. The dominant
projection (r → d). Frozen attention without approach for academic
pretrained layers pass modifying any pretrained and resource-constrained
activations through; only weights. Effective for practitioners (Dettmers et
adapter weights are table-to-text and al., 2023).
trained. 0.5–3% of total summarization tasks.
parameters.
Computational Considerations &
Deployment
Understanding the computational demands of generative models is essential for responsible
research and engineering practice. The economics of large-scale generative AI are dominated by
three factors: training cost, memory usage, and inference latency. Each presents unique
optimization challenges and has driven a rich ecosystem of specialized techniques.
$100M ~1T 6x
GPT-4 Training Cost Parameters in GPT-4 FLOPs per Parameter
Estimated compute cost for a Estimated parameter count Training each parameter
single training run of GPT-4, (unconfirmed). At BF16 requires approximately 6× its
not including R&D, failed runs, precision, storing weights count in FLOPs. A 1B parameter
or infrastructure. Highlights requires ~2TB of VRAM — far model trained on 1T tokens
why only a few organizations exceeding any single GPU's requires ~6×10²¹ FLOPs
can train frontier models. capacity. (Chinchilla scaling law).
Inference Optimization
While training cost is a one-time expenditure, inference cost accumulates across every query
served in production. Key optimization techniques include:
Drug Discovery
Variational autoencoders and graph neural networks generate novel molecular
structures with desired pharmacological properties. Models like AlphaFold2 and
RoseTTAFold predict protein 3D structures with experimental accuracy, compressing
decades of experimental biology into hours of computation. Insilico Medicine used
generative AI to identify a novel fibrosis drug candidate, advancing it to Phase II
clinical trials in approximately 18 months — a fraction of the typical 5–10 year timeline.
Code Generation
GitHub Copilot, powered by OpenAI Codex (a fine-tuned GPT model), completes 40–
55% of newly written code in participating developers, according to GitHub's own
telemetry. Autoregressive code models are trained on billions of lines of source code
from public repositories, learning not just syntax but idiomatic patterns, API usage,
and algorithmic structures across dozens of programming languages.
Healthcare Reporting
Radiology report generation systems fine-tune language models on electronic health
records to produce structured diagnostic summaries from medical imaging. RAG-
enhanced clinical decision support tools retrieve relevant literature and drug
interaction databases in real time, grounding LLM responses in current medical
evidence.
Padding in Neural Networks: Real-Life
Problem & Step-by-Step Solution
Padding is an essential preprocessing and architectural operation in convolutional neural networks
(CNNs) and transformer models. In CNNs, padding adds extra values (typically zeros) around the
border of an input feature map before applying a convolutional filter, controlling the spatial
dimensions of the output. Without padding, repeated convolution operations progressively shrink
the feature map, discarding boundary information and limiting network depth. Understanding
padding numerically is critical for correctly computing output dimensions, receptive fields, and
feature map shapes throughout a deep network.
R1 2 4 1 3 2
R2 5 6 7 2 1
R3 3 8 5 4 6
R4 1 2 9 3 7
R5 4 5 6 1 2
Step 1: Apply Zero Padding (p=1)
We add a border of zeros around the entire 5×5 input, creating a 7×7 padded matrix:
Row\Col 0 1 2 3 4 5 0
0 0 0 0 0 0 0 0
1 0 2 4 1 3 2 0
2 0 5 6 7 2 1 0
3 0 3 8 5 4 6 0
4 0 1 2 9 3 7 0
5 0 4 5 6 1 2 0
0 0 0 0 0 0 0 0
Padding: Convolution Computation &
Output Analysis
Step 2: Define the 3×3 Convolution Filter
1 0 -1
1 0 -1
1 0 -1
This is a standard vertical edge detection filter (Sobel-style). It responds strongly to regions where pixel
intensity transitions from high to low horizontally — exactly the type of boundary a radiologist or
segmentation network needs to detect in medical imaging.
0 0 0
0 2 4
0 5 6
0 0 0
4 1 3
6 7 2
(
(0×1)+(0×0)+(0×-1)+(4×1)+(1×0)+(3×-1)+(6×1)+(7×0)+(2×-1) = 0+0+0+4+0-3+6+0-2 = 5
-5
-10
(1,1) (1,2) (1,3) (2,1) (2,3) (3,3) (4,4) (5,5)
Output Position (row, col)
The bar chart confirms that padding allows the convolution to produce a full 5×5 output with
meaningful responses at boundary positions — the corner value of -10 indicates a strong left-
boundary edge, while central positions near zero indicate flat regions. Without padding, positions (1,1)
and (5,5) would not exist in the output at all, causing the network to lose critical boundary context
entirely. This demonstrates why padding is not merely an implementation detail — it is a principled
design choice that directly affects the network's ability to detect features at all spatial locations,
including the boundaries most relevant for object detection and medical segmentation tasks.
When TO Use Padding When NOT TO Use Padding
Use padding when preserving spatial Avoid padding when intentional spatial
resolution through deep networks, when downsampling is desired (use stride instead),
boundary features matter (edge detection, when the network architecture is designed
segmentation, medical imaging), when for classification only and boundary detail is
building fully-convolutional architectures, or irrelevant, or when computational budget is
when output must match input dimensions extremely constrained and the additional
exactly (image-to-image translation). padded operations cannot be afforded.