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.
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.
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.
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).
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.
| Component | Role in plain words | Analogy |
|---|---|---|
| Encoder | Compresses input | Lecture summarizer |
| Latent Space | Home of compressed ideas | Notebook of notes |
| Decoder | Rebuilds output | Student 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.
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.
noisy = image + 0.3 * torch.randn_like(image)
latent = encoder(noisy)
reconstructed = decoder(latent)
loss = MSE(reconstructed, image) # compare to clean original
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.
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.
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:
- Reconstruction loss: did we rebuild the input well?
- 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.
Autoencoder
Fixed point in latent space — reconstruction only.
VAE
Distribution in latent space — reconstruction + new generation.
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.
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.
| Type | What it does | Example |
|---|---|---|
| DCGAN | Images from noise | MNIST digits, faces |
| CycleGAN | Style/domain transfer | Photo → painting |
| StyleGAN | High-res + control | thispersondoesnotexist.com |
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.
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:
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.
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.
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.
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.
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).
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.
| Model | Strength | Example use |
|---|---|---|
| CLIP | Image↔text link, zero-shot | Image search, content filtering |
| BLIP-2 | Caption + VQA + LLM | “What is happening in this image?” |
| Florence-2 | Many vision tasks via prompt | OCR, detection, caption |
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.
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).
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
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.
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!
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.
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": "..."}
| Method | Approx. VRAM (7B) | When? |
|---|---|---|
| Full fine-tune | 80 GB+ | Big budget, full control |
| LoRA | 24–48 GB | Most domain use cases |
| QLoRA | 12–16 GB | Single GPU, experiments, startups |
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.
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.
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.
| Tool | Main use |
|---|---|
| ONNX | General export, vision/classification |
| TensorRT | Fast GPU inference |
| GGUF + llama.cpp | Local LLM on CPU |
| vLLM | Production LLM API |
| Ollama | Easy local dev and testing |
curl http://localhost:11434/api/generate -d '{
"model": "llama3",
"prompt": "Explain autoencoders in two sentences"
}'
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.
- Install Ollama or LM Studio.
- Download Llama 3 or Mistral (7B Q4).
- UI: Open WebUI or a simple Streamlit app.
- Optional: LoRA adapter for your domain.
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.
“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.
- Split documents → chunks.
- Embed (OpenAI / sentence-transformers).
- Vector DB (Chroma, FAISS, Pinecone).
- On question: find relevant chunks → attach to prompt → LLM answers.
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.
“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
- Week 1: Autoencoder on MNIST (PyTorch tutorial).
- Week 2: Try Stable Diffusion locally — 20 images with different prompts.
- Week 3: Ollama + chat — learn limits of a small model.
- Week 4: RAG on a 10-page PDF (LangChain + Chroma).
- Week 5: Small QLoRA fine-tune on 100 instruction examples.
- Week 6: CLIP zero-shot on your photos — or a ready VLM.
- Week 7: Simple agent with 2 tools (calculator + search).
- Week 8: One capstone project + README + short demo video.