Deep Learning Specializations

Advanced Deep Learning & Generative AI

Lesson 5: Advanced Deep Learning & Generative AI | Beginner Guide
Deep Learning · Lesson 5

Advanced Deep Learning
& Generative AI

A beginner-friendly guide to how machines generate new images, text, and ideas: from Autoencoders, VAE, and GANs, through Diffusion and Stable Diffusion, to Multimodal AI, RLHF, Fine-Tuning, model deployment, and capstone projects — with real-life analogies and simple examples.

✍ Abdurrahman Al-Rifai
9 sections
Autoencoder → Diffusion
Simple examples
Autoencoder VAE GAN Diffusion Multimodal RLHF Fine-Tune Deploy Projects
01 Section One

Autoencoders

So far we have trained networks to classify or predict. But what if we want to compress information and then rebuild it? That is exactly what an Autoencoder does — and it is the first step toward understanding generation in AI.

Analogy: lecture notes

You listen to a two-hour lecture and write a one-page summary (compression). Later you read the summary and try to recall the main points (reconstruction). If the summary is good, you recover the core idea even though fine details are gone.

Encoder

The Encoder takes input (an image, audio, text as vectors…) and turns it into a much smaller representation called a latent representation. Like taking a high-resolution photo and saving a compressed JPEG — the file is smaller, but the essence of the image remains.

Simple numeric example

A 28×28 image = 784 pixels → the Encoder outputs a vector of only 32 numbers. Can 32 numbers capture every detail? No — but enough for the big picture: “this is the digit 7.”

Decoder

The Decoder takes the compressed vector and tries to reconstruct the original input. The training goal: make the difference between the original and the rebuilt version as small as possible (reconstruction loss).

Input Encoder Latent Space Decoder Output
Compress → latent space → reconstruct

Latent Space

Latent space is a “map” of hidden numbers. Each point represents a kind of data. Similar items (two 7s) sit close together; different ones (7 vs 3) are far apart. This space matters because later we generate new data by picking points from it.

ComponentRole in plain wordsAnalogy
EncoderCompresses inputLecture summarizer
Latent SpaceHome of compressed ideasNotebook of notes
DecoderRebuilds outputStudent re-explaining the lecture

Denoising Autoencoder

We feed the network a corrupted image (noise, blur, random pixels) and ask it to restore the clean image. It learns what matters in the data — not random junk — very useful for image and audio processing.

Real-life example

You hear a friend in a noisy café. Your brain filters the sound and you understand the words. A denoising autoencoder learns the same idea: ignore noise, keep the true shape.

# Denoising Autoencoder idea (simplified PyTorch)
noisy = image + 0.3 * torch.randn_like(image)
latent = encoder(noisy)
reconstructed = decoder(latent)
loss = MSE(reconstructed, image) # compare to clean original
Uses: data compression, anomaly detection, stepping stone to VAE and GAN.
Limits: a plain autoencoder does not “invent” easily — it mostly replays what it learned.
02 Section Two

Variational Autoencoders (VAE)

A VAE pushes the autoencoder idea further: instead of one point in latent space, it learns a probability distribution. That lets you generate new data by sampling randomly from that distribution.

Analogy: describing a person

Instead of “exactly 175 cm tall,” you say “about 170–180 cm.” That is a range, not a single number. A VAE stores mean and variance for each dimension in latent space.

Latent Variables

Latent variables (z) are hidden numbers that capture the “essence” of the data. In a VAE, the Encoder does not output z directly — it outputs:

  • μ (mu): the mean — where is the center of the distribution?
  • σ (sigma): spread — how far values scatter around the center?

Then we sample: z = μ + σ × ε where ε is random from a normal distribution.

Sampling

During training we sample from the distribution (reparameterization trick) so gradients can flow. At generation time: pick random z from a standard N(0,1) distribution, pass it to the Decoder — out comes a new face, digit, or shape you have never seen exactly before.

Face generation example

After training a VAE on thousands of faces: z = [0.2, -1.1, 0.8, …] → Decoder → a new face that “fits” the training set but is not a copy of anyone.

KL Loss

A VAE has two losses:

  1. Reconstruction loss: did we rebuild the input well?
  2. KL divergence: is the Encoder’s learned distribution close to a simple “normal” prior?

KL loss stops the Encoder from stuffing everything into one point — it forces latent space to stay smooth and organized so you can wander it and generate diverse samples.

Loss = Reconstruction + β × KL(q(z|x) || p(z))

Autoencoder

Fixed point in latent space — reconstruction only.

VAE

Distribution in latent space — reconstruction + new generation.

VAE strength: smooth generation, organized latent space, foundation for bigger models (e.g. Diffusion later).
VAE weakness: generated images can look “blurry” compared to GANs.
03 Section Three

GANs — Generative Adversarial Networks

A GAN is like a game between two teams: one forges art, the other tries to spot fakes. Over time the forger gets very good — and the result is stunningly realistic images.

Generator

Takes random noise — a vector of random numbers — and turns it into an image (or sound, or any data). At first it outputs garbage; with training it learns convincing shapes.

Discriminator

A classifier network: “Is this image real or fake?” It sees real training images plus Generator outputs. If it catches fakes easily, the Generator must improve. If it gets fooled, the Discriminator must improve.

Noise z Generator Fake image Discriminator Real / Fake Real image
Generator forges — Discriminator judges
Analogy: counterfeit money

The forger (Generator) prints bills. The police (Discriminator) inspect them. As bills get sharper, inspection gets sharper too. In the end: fakes that are nearly indistinguishable — that is realistic generation.

DCGAN — Deep Convolutional GAN

DCGAN uses convolution layers instead of fully connected ones — suited for images. Practical rules helped stability: BatchNorm, stride instead of pooling, ConvTranspose in the Generator.

CycleGAN — Unpaired domain translation

Turn a horse into a zebra without paired “this horse = this zebra” images. Cycle consistency: horse → zebra → horse should land close to the original. Uses: summer/winter, photo/painting, MRI modalities.

StyleGAN — Style control

StyleGAN (NVIDIA) generates high-quality faces with fine control: face shape, hair color, expression… via style mixing — blend styles from different latent vectors. Powers many famous AI face sites and academic deepfake research.

TypeWhat it doesExample
DCGANImages from noiseMNIST digits, faces
CycleGANStyle/domain transferPhoto → painting
StyleGANHigh-res + controlthispersondoesnotexist.com
GAN strength: sharp, realistic images; visually impressive results.
Challenges: unstable training (mode collapse), needs tuning and experience.
04 Section Four

Diffusion Models

Diffusion models power Stable Diffusion, Midjourney, and DALL·E 3 (partly). The idea: gradually corrupt an image with noise, then teach a network to reverse the process — from noise back to image.

Analogy: melting then reshaping a statue

Imagine a wax statue. Each day you heat it a little until it loses shape (forward). Then you learn, step by step, how to cool and reshape it (reverse). After thousands of practice runs, you can sculpt new statues from random wax blobs.

Forward Process

Start with a real image x₀. At each step t add a bit of Gaussian noise:

xₜ = √αₜ · xₜ₋₁ + √(1−αₜ) · ε

After T steps (e.g. 1000), the image is pure noise. This process is fixed — we do not learn it; we only apply it to training data.

Reverse Process

A U-Net (usually) learns: “Given a noisy image at step t, what noise was added?” — it predicts ε. Repeat from t=T down to t=0, remove noise step by step, and you get a new image.

Generation example

1) Start with random 512×512 noise
2) Repeat 50–1000 denoise steps
3) Result: “a cat wearing glasses on a beach at sunset” — guided by text if provided (conditional diffusion)

Stable Diffusion

Instead of full pixels (slow), Stable Diffusion works in a compressed latent space (VAE encoder). Faster and lighter. It combines:

  • Text encoder (CLIP): turns your prompt into a vector.
  • U-Net + cross-attention: links text to the image during denoising.
  • VAE decoder: turns latent back into the final image.
# Generate with Stable Diffusion (Hugging Face Diffusers)
from diffusers import StableDiffusionPipeline
pipe = StableDiffusionPipeline.from_pretrained("runwayml/stable-diffusion-v1-5")
image = pipe("cat on a beach at sunset, watercolor style").images[0]

GAN

Direct adversarial game — fast but sometimes unstable.

Diffusion

Denoise steps — slower but often higher quality and diversity.

Stable Diffusion

Latent diffusion + text — runs on mid-range GPUs.

05 Section Five

Multimodal AI

Multimodal means the model understands more than one data type together: image + text, audio + video, document + table… The real world is multimodal — and modern models follow.

Analogy: a child learning language

You show a child an apple 🍎 and say the word. They link shape, sound, and word. Multimodal AI links pixels to tokens in a shared space.

Vision + Language

Common tasks:

  • Image captioning: image → text description.
  • VQA: question about an image → answer.
  • Text-to-image: description → image (Stable Diffusion).
  • Image search: search by image or by sentence.

CLIP — Contrastive Language-Image Pre-training

OpenAI CLIP trains on millions of (image, text) pairs. It learns that “cat” sits near cat images in a shared embedding space. Uses:

  • Zero-shot classification (no training on fixed classes).
  • Search engine: “dog playing ball” → finds similar images.
  • Foundation for Stable Diffusion (text encoder).
CLIP zero-shot example

Labels: ["cat", "dog", "car"] + one image → CLIP scores similarity for each label → highest = “cat.” Multilingual CLIP / OpenCLIP supports more languages.

BLIP — Bootstrapping Language-Image Pre-training

BLIP / BLIP-2 combines image understanding and text generation. It captions images, answers questions, and connects to an LLM (e.g. Flan-T5 or Llama) for stronger abilities. Good for VQA and image-aware chatbots.

Florence — Microsoft’s vision foundation model

Florence (and Florence-2) is a vision foundation model: captioning, detection, segmentation, OCR… from one text prompt. “Natural language commands for images” — like GPT but for vision tasks.

ModelStrengthExample use
CLIPImage↔text link, zero-shotImage search, content filtering
BLIP-2Caption + VQA + LLM“What is happening in this image?”
Florence-2Many vision tasks via promptOCR, detection, caption
06 Section Six

RLHF — Reinforcement Learning from Human Feedback

After internet pre-training, an LLM knows “text completion” — but it may be rude, unsafe, or unhelpful. RLHF teaches it what humans prefer: useful, safe, clear answers — like ChatGPT.

Analogy: training a new employee

The employee read every book (pre-training). A colleague coached them (instruction fine-tuning). Then the manager rates replies and gives stars (reward) — so they improve for customers (human feedback).

Reward Model

Collect human comparisons: “Response A is better than B” for the same question. Train a network to assign a score to each reply — higher when it matches human taste. That reward model becomes the automated coach.

PPO — Proximal Policy Optimization

PPO is an RL algorithm that updates the LLM carefully: generate replies, reward model scores them, adjust weights to increase reward — without breaking what was learned (KL penalty keeps it near the original model).

Human comparison example

Question: “How do I learn Python?”
Reply A: 4-week plan + resources
Reply B: “Python is a language” only
Rater picks A → reward model learns to score A higher

Preference Optimization

Instead of a heavy RL loop, newer methods optimize the model directly from preference data (A better than B) without long generation cycles.

DPO — Direct Preference Optimization

DPO (Stanford) turns RLHF into a simple loss like classification: raise probability of the preferred reply, lower the other — sometimes without a separate reward model. Faster and easier — used in Llama 2/3 and Mistral tuning.

SFT

Instructions + good answers (supervised).

Reward Model

Learns “what is a good reply?”

PPO

RL to improve the LLM

DPO

Direct preferences — simpler

Pre-train SFT Reward / DPO ChatGPT-like
07 Section Seven

Fine-Tuning LLMs

A general model (GPT, Llama, Mistral) knows a lot — but you want it expert in your domain: medicine, law, customer support, your tone… Fine-tuning = continue training on your data.

Analogy: general doctor → specialist

A general practitioner knows basics of every field. After cardiology residency, they are sharper in heart care. Fine-tuning is “residency” on your data.

Full Fine-Tuning

Update every weight in the model. Strongest fit to your data, but:

  • Needs huge GPUs (70B = tens of GB VRAM).
  • Risk of catastrophic forgetting.
  • High cost.

PEFT — Parameter-Efficient Fine-Tuning

PEFT updates only a small slice of parameters. The base model stays frozen; you add tiny layers or adapters. Cheaper and faster — right for most projects.

LoRA — Low-Rank Adaptation

LoRA adds two small matrices (A and B) beside an attention layer: W' = W + A×B. Small rank (r=8 or 16) — millions of parameters instead of billions. A LoRA file may be only 50–200 MB!

W' = W + (α/r) · A · B

QLoRA — LoRA + Quantization

QLoRA quantizes the base model to 4-bit (NF4) — so Llama 7B fits in a 16 GB GPU. LoRA adapters stay fp16. This made LLM fine-tuning on Colab accessible to many people.

# QLoRA idea (Hugging Face + PEFT)
from peft import LoraConfig, get_peft_model
config = LoraConfig(r=16, lora_alpha=32, target_modules=["q_proj","v_proj"])
model = get_peft_model(base_model_4bit, config)
# Train on JSON: {"instruction": "...", "output": "..."}
MethodApprox. VRAM (7B)When?
Full fine-tune80 GB+Big budget, full control
LoRA24–48 GBMost domain use cases
QLoRA12–16 GBSingle GPU, experiments, startups
Project example

500 Q&A pairs for your store’s support → QLoRA on Mistral-7B → a model that speaks in your company voice and knows your products — without training all 7B parameters.

08 Section Eight

Model Deployment

After training, a model in Jupyter is not enough — you need to run it in production: fast, stable, on CPU, GPU, or edge. Each tool has a role.

Analogy: home kitchen → restaurant

Training = testing recipes at home. Deployment = opening a branch that serves thousands quickly — you need a standard recipe (format), trained cooks (runtime), and an order queue (serving).

ONNX — Open format

Open Neural Network Exchange: convert PyTorch/TensorFlow to a .onnx file for ONNX Runtime — cross-platform, sometimes faster, CPU/GPU/edge.

TensorRT — NVIDIA acceleration

NVIDIA optimizer for GPU inference: fusion, FP16/INT8 precision, low latency — ideal for production on NVIDIA servers.

TorchScript — PyTorch for production

Export PyTorch to TorchScript (trace or script) — runs with less Python overhead, or via LibTorch in C++.

GGUF — LLMs on CPU

llama.cpp format: quantized models (Q4_K_M, Q8…) — run Llama/Mistral on a laptop without GPU. Single file, easy to share.

llama.cpp

C++ engine for local LLMs. Command: ./main -m model.gguf -p "Hello". Powers Ollama, KoboldCpp, and others.

vLLM — fast LLM inference

Serving library with PagedAttention — high throughput for APIs: many parallel requests on GPU. For cloud production (chatbot API).

Ollama — easy local run

ollama run llama3 — downloads and runs the model. Great for developers on Mac/Windows/Linux.

TensorFlow Serving

Google’s system for TensorFlow models: REST/gRPC, versioning, A/B testing — for companies on TF stack.

ToolMain use
ONNXGeneral export, vision/classification
TensorRTFast GPU inference
GGUF + llama.cppLocal LLM on CPU
vLLMProduction LLM API
OllamaEasy local dev and testing
# Local Ollama API
curl http://localhost:11434/api/generate -d '{
"model": "llama3",
"prompt": "Explain autoencoders in two sentences"
}'
09 Section Nine

Capstone Projects — From Idea to Application

Here we tie everything together into real projects you can start as a beginner — with a clear learning path for each.

Build Local ChatGPT

Idea: LLM + chat UI on your machine.

  1. Install Ollama or LM Studio.
  2. Download Llama 3 or Mistral (7B Q4).
  3. UI: Open WebUI or a simple Streamlit app.
  4. Optional: LoRA adapter for your domain.
# Simple Streamlit chatbot
import streamlit as st, ollama
prompt = st.chat_input("Type your message")
if prompt:
r = ollama.chat(model="llama3", messages=[{"role":"user","content":prompt}])
st.write(r["message"]["content"])

Image Generator

Stable Diffusion via Diffusers or Automatic1111/ComfyUI. Start with simple prompts, try negative prompts, add ControlNet later for pose control.

Beginner prompt

“Mountain landscape at sunrise, watercolor style, high detail”
negative: “blurry, low quality, text”

RAG System — Retrieve then Generate

RAG = Retrieval-Augmented Generation. Instead of relying only on the LLM’s memory, it searches your documents (PDF, wiki, knowledge base) then answers.

  1. Split documents → chunks.
  2. Embed (OpenAI / sentence-transformers).
  3. Vector DB (Chroma, FAISS, Pinecone).
  4. On question: find relevant chunks → attach to prompt → LLM answers.
# Simplified RAG pipeline
chunks = split_documents("company_handbook.pdf")
vectors = embed(chunks)
store = VectorDB(vectors, chunks)
context = store.search(user_question, k=3)
answer = llm(f"Context: {context}\nQuestion: {user_question}")

AI Agent

LLM + tools: search, calculator, APIs, file writes. It plans steps and executes — LangChain, LlamaIndex, or OpenAI Assistants API.

Agent example

“What is BTC price today and how much is $1000 in SAR?” → Agent calls crypto API + forex API → combines the answer.

Vision Language Model — See and Speak

LLaVA, GPT-4V, Qwen-VL: upload an image + ask questions. Project idea: “kitchen assistant” — photo of fridge → suggested recipes.

Medical AI (with caution)

X-ray classification (CNN), tumor segmentation (U-Net), or LLM summaries (not a substitute for a doctor). Start with public sets: ChestX-ray, ISIC skin lesions — with ethics and privacy in mind.

Recommendation System

Collaborative filtering + embeddings, or two-tower models (user/item). Netflix/Spotify spirit: “users who watched X also watched Y.” You can add an LLM to describe content.

Time Series Forecasting

LSTM/Transformer for prices, demand, energy. Project: forecast monthly sales from CSV — or ready models: Prophet, Temporal Fusion Transformer.

Local ChatGPT

Ollama + Open WebUI · Week 1

Image generator

Stable Diffusion · Week 2

RAG

PDF + Chroma + Llama · Weeks 3–4

Agent

LangChain tools · Week 5

Vision + LLM

LLaVA / API · Week 6

Forecasting

LSTM on CSV · Week 7

8-week plan for beginners
  1. Week 1: Autoencoder on MNIST (PyTorch tutorial).
  2. Week 2: Try Stable Diffusion locally — 20 images with different prompts.
  3. Week 3: Ollama + chat — learn limits of a small model.
  4. Week 4: RAG on a 10-page PDF (LangChain + Chroma).
  5. Week 5: Small QLoRA fine-tune on 100 instruction examples.
  6. Week 6: CLIP zero-shot on your photos — or a ready VLM.
  7. Week 7: Simple agent with 2 tools (calculator + search).
  8. Week 8: One capstone project + README + short demo video.
FAQ Questions

FAQ on Generative AI

What is the difference between Autoencoder, VAE, and GAN?
Autoencoder compresses and reconstructs — it does not generate easily. VAE adds a probabilistic latent space so you can sample. GAN pits generator vs discriminator for sharp images. Today Diffusion often wins on diversity and stability.
Do I need a GPU to learn Generative AI?
For learning: small Autoencoder/VAE on CPU or free Colab. Stable Diffusion and LLM fine-tuning: GPU helps (16 GB+ for QLoRA). For usage only: Ollama on CPU works with quantized models.
Stable Diffusion vs Midjourney?
Stable Diffusion is open source — run and modify locally. Midjourney is a closed cloud service — easier for beginners with no setup, but less control over the stack.
What is RLHF in one sentence?
Teaching an LLM to reply the way humans prefer — via comparisons (A better than B) and a reward model or DPO — so it becomes a helpful assistant, not a random text completer.
LoRA or full fine-tune?
Always start with LoRA/QLoRA — enough for ~90% of domain cases. Full fine-tune only for large teams and big budgets.
How do I start a RAG project?
10–50 PDF pages → chunk → embed → Chroma → Llama via Ollama → ask questions about the content. LangChain docs include ready templates.
What next after this lesson?
Review Lesson 4 (LLM basics) if you skipped it, then pick one project from Section 9 and ship it within a month — GitHub + README.