This repository collects lecture slides, assignments (CAs), code notebooks, reports, and reference papers used in the "Deep Generative Models" course (University of Tehran). The materials are organized to be reproducible and educational: each assignment contains an annotated Jupyter notebook, supporting code, and a report.Deep Generative Models
Jupyter Notebook
21
385 commits
updated Feb 14, 2026
This repository collects lecture slides, assignments (CAs), code notebooks, reports, and reference papers used in the "Deep Generative Models" course (University of Tehran). The materials are organized to be reproducible and educational: each assignment contains an annotated Jupyter notebook, supporting code, and a report.
Course Overview
The "Deep Generative Models" (DGM) course covers advanced topics in machine learning focused on generative modeling techniques. Generative models learn the underlying distribution of data to generate new samples, enabling applications in image synthesis, anomaly detection, data augmentation, and more.
Key topics covered in the course include:
The course assignments (CA1-CA4) progressively build skills in implementing and evaluating these models on real datasets like CelebA, FashionMNIST, and custom image datasets.
This section provides a high-level overview of the core mathematical and conceptual foundations that unify the different generative modeling approaches covered in the course.
Generative models aim to learn the underlying data distribution $p(\mathbf{x})$ from samples $\mathbf{x} \sim p_{\text{data}}$. The goal is to:
Most generative models are trained by maximizing the log-likelihood:
$$ \theta^* = \arg\max_\theta \mathbb{E}{\mathbf{x} \sim p{\text{data}}} [\log p_\theta(\mathbf{x})] $$
This is equivalent to minimizing the KL divergence between data and model distributions:
$$ \theta^* = \arg\min_\theta \text{KL}(p_{\text{data}} || p_\theta) $$
Many generative models introduce latent variables $\mathbf{z}$ to simplify modeling:
Exact inference in latent models is often intractable. Variational inference approximates posteriors using a recognition model:
Normalizing flows provide exact density estimation through invertible transformations:
GANs use adversarial objectives instead of explicit likelihoods:
Diffusion models gradually add noise and learn to reverse the process:
Score-based models learn the score function (gradient of log-density):
Assessing generative model quality requires both quantitative and qualitative measures:
Understanding these unifying principles helps in choosing appropriate models for different applications and in developing new generative techniques.
Prerequisites: Strong background in deep learning (PyTorch/TensorFlow), probability theory, and optimization. Specifically:
Students without this background may find the course challenging and are encouraged to review these topics beforehand.
CA1_Variational_Autoencoders/ — Course Assignment 1: Variational Autoencoders
code/ — Jupyter notebooks and code used for experiments (e.g., code.ipynb).description/ — Assignment description PDF.report/ — PDF reports and figures.images/ — Generated images and visualizations.train/ — Training datasets (CelebA subset: smile/non-smile images).README.md — Detailed documentation for CA1.CA2_GANs_Normalizing_Flows/ — Course Assignment 2: GANs and Normalizing Flows
code/ — Jupyter notebooks (e.g., CA2_DGM.ipynb, Q2_final_res.ipynb).description/ — Assignment description PDF.report/ — PDF reports and figures.images/ — Generated samples and visualizations.README.md — Detailed documentation for CA2.CA3_Diffusion_Models/ — Course Assignment 3: Diffusion and Score-based Models
codes/ — Jupyter notebooks (e.g., Diffusion_Models.ipynb, score_based_models.ipynb).description/ — Assignment description PDF.report/ — PDF reports and figures.images/ — Generated samples and visualizations.README.md — Detailed documentation for CA3.CA4_Vision_Language_Model/ — Course Assignment 4: Vision-Language Models
code/ — Jupyter notebooks (e.g., final_CA4_training.ipynb, evaluation notebooks).description/ — Assignment description PDF.report/ — PDF reports and figures.images/ — Generated images and visualizations.README.md — Detailed documentation for CA4.Slides/ — Lecture slides and course material used in class.
DGM_Fall_2023_Slides/ — Course lecture slides.Stanford_slides/ — Supplementary slides from Stanford's CS236 course.MITSlides/ — Additional slides from MIT and other sources.Exams/ — Past exams and solutions.ExtraNotes/ — Additional notes, homework templates, supplementary PDFs, and exploratory materials (e.g., homework_template/, research papers on D-separation).OtherTermAssignments/ — Assignments from other terms or related courses, including CA1, CA2, CA3 from previous semesters.OtherUniversityLecturs/ — Lecture materials from other universities and courses.
CS236_DGM/ — Complete materials from Stanford's CS236 Deep Generative Models course.SUT/ — Materials from Sharif University of Technology.notes/ — General notes and documentation.ssi2023/ — Materials from SSI 2023.PaperSLecturs/ — Research papers, codes, and lecture materials on advanced topics.
AI4Science_Codes/ — Code implementations for AI for Science applications.AI4Science_Papers/ — Research papers on AI for Science.Generative_Codes/ — Codes for generative models (e.g., conditional flow matching, Mamba).Generative_Models_Papers/ — Papers on generative models.LLM_Codes/ — Large Language Model implementations.LLM_Papers/ — Papers on LLMs.Vision_Codes/ — Computer vision codes.Vision_Papers/ — Papers on computer vision.This repository is primarily an educational resource. Notebooks are annotated for readability and (where possible) reorganized to centralize imports and configuration.
Recommended steps to set up a local, reproducible environment. We recommend using virtual environments to isolate dependencies.
python -m venv .venv
source .venv/bin/activate # On Windows: .venv\Scripts\activate
pip install -U pip
pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu118 # Example for CUDA 11.8
pip install matplotlib numpy scipy scikit-learn jupyterlab pytorch-fid tqdm
conda create -n dgm python=3.10
conda activate dgm
conda install pytorch torchvision torchaudio pytorch-cuda=11.8 -c pytorch -c nvidia # Adjust CUDA version
conda install matplotlib numpy scipy scikit-learn jupyterlab tqdm
pip install pytorch-fid
pip install torchdiffeq (for ODE solvers in score-based models).pip install seaborn plotly.pip install wandb (optional, for experiment tracking).Notes:
torch/torchvision binaries using the official instructions at https://pytorch.org. For CPU-only, omit CUDA-specific installs.pytorch-fid is used in CA2 for FID computation. If installation fails, consider alternatives like clean-fid.jupyter lab
Setup and Configuration cell in each notebook and run smoke tests described below.This section summarizes the primary assignments and their current status in the repository.
CA1 (folder: CA1_Variational_Autoencoders/)
code/code.ipynb, report/DGM_CA1_final_EN.pdf, README.md.train/smile/ and train/non_smile/.CA2 (folder: CA2_GANs_Normalizing_Flows/)
code/CA2_DGM.ipynb, code/Q2_final_res.ipynb, README.md.CA3 (folder: CA3_Diffusion_Models/)
codes/Diffusion_Models.ipynb, codes/score_based_models.ipynb, report/DGM_CA3_EN_final.pdf, README.md.CA4 (folder: CA4_Vision_Language_Model/)
code/final_CA4_training.ipynb, code/eval_p1/final_CA4_results1.ipynb, code/eval_p2/final_CA4_results2.ipynb, README.md.Other folders (Slides/, Extra/, Exams/) contain lecture materials, relevant readings, and supporting documents.
CA1 introduces Variational Autoencoders (VAEs), a cornerstone of generative modeling that combines variational inference with autoencoder architectures.
Variational Autoencoders (VAEs) are generative models that learn to encode input data into a low-dimensional latent space and decode it back to reconstruct the original data. Unlike traditional autoencoders, VAEs learn a probabilistic latent representation, allowing them to generate new samples by sampling from the learned distribution.
VAEs balance reconstruction fidelity with latent space regularization, making them useful for tasks like image generation, anomaly detection, and representation learning.
Encoder Network: The encoder progressively reduces spatial dimensions while increasing feature depth using convolutional layers, batch normalization, dropout, and LeakyReLU activations, culminating in linear layers that output mean (μ) and log variance (log σ²) for the latent distribution.
Reparameterization Trick: z = μ + σ ⊙ ε, where ε ~ N(0, I) and σ = exp(0.5 × logvar), enabling gradient flow through stochastic sampling.
Decoder Network: Mirrors the encoder with transposed convolutions, reconstructing images from latent vectors.
The Evidence Lower Bound (ELBO) combines reconstruction loss (MSE) and KL divergence regularization to balance fidelity and generalization.
Training Progress: Loss reduced by ~57% over training, with stable convergence and good generalization (validation loss tracks training loss closely).
Image Reconstruction: Effective preservation of facial features with slight smoothing; quantitative metrics show significant error reduction.
Image Generation: Diverse, realistic facial images generated by sampling from the prior, demonstrating generative capabilities.
Latent Space Analysis: Embeddings show clustering by smile/non-smile classes, with successful interpolation and classification performance.
Key components in CA1_Variational_Autoencoders/code/code.ipynb:
Why run CA1?
Files of interest in CA1_Variational_Autoencoders/:
code/code.ipynb — the annotated notebook (imports consolidated and configuration cell added).README.md — detailed documentation with synthesized report summary.train/ — contains CelebA subset (smile/non-smile) for training.report/ — PDF reports including DGM_CA1_final_EN.pdf.images/ — generated visualizations and outputs.High-level suggested execution order:
CA2 is both pedagogical and experimental. It demonstrates two complementary approaches to deep generative modeling:
Normalizing Flows are generative models that learn invertible transformations to map a simple base distribution (like a standard normal) to a complex data distribution. They provide exact likelihood computation and can be trained via maximum likelihood.
Generative Adversarial Networks (GANs) consist of two neural networks trained simultaneously: a generator that creates fake data and a discriminator that distinguishes real from fake. They learn through adversarial training without requiring explicit density estimation.
These approaches complement each other: flows provide mathematical rigor and exact evaluation, while GANs excel at generating high-quality samples.
GAN Training on FashionMNIST: Best FID score of 171.67 achieved at epoch 8, with overall ~23% improvement over 10 epochs. Samples show progressive quality improvement from blurry initial images to sharp, detailed fashion items.
Normalizing Flows: RealNVP implementation with coupling layers for invertible transformations, enabling exact density estimation and OOD detection via log-likelihoods on MNIST/KMNIST.
RealNVP (normalizing flows): an explicit density model trained by maximum likelihood. The notebook contains:
GAN (DCGAN-style): an adversarial generator trained to produce realistic fashion images. The notebook contains:
Generator and Discriminator classes implemented in PyTorch.pytorch-fid computed per-epoch.Why run CA2?
Files of interest in CA2_GANs_Normalizing_Flows/:
code/CA2_DGM.ipynb — the annotated notebook (imports consolidated and a configuration cell added).code/Q2_final_res.ipynb — additional results and experiments.README.md — localized instructions, reproducibility notes and quick-start steps.report/ — PDF reports including DGM_CA2_final_EN.pdf.images/ — generated samples and training progress visualizations.High-level suggested execution order (no code is run by the editor):
Setup and Configuration cell to set device, latent_dim, batch_size, epochs, and image_size.CA3 explores cutting-edge generative modeling techniques: Denoising Diffusion Probabilistic Models (DDPM) and Score-based Generative Models.
Denoising Diffusion Probabilistic Models (DDPM) are generative models that learn to reverse a gradual noising process. They consist of two processes:
Score-based Generative Models learn the score function (gradient of the log-density) of the data distribution. They can generate samples using stochastic processes:
These models represent the current state-of-the-art in generative modeling, offering superior sample quality compared to earlier approaches like VAEs and GANs.
Score-based Models: Trained on 2D Gaussian mixture data with different noise levels (σ=1,3,7). Best performance at σ=3 with final loss 0.012, demonstrating effective score field learning and sampling via Langevin dynamics. Annealed sampling provides robust results across noise levels.
Diffusion Models: Implementation of DDPM with forward diffusion process and reverse denoising, enabling high-quality image generation through iterative noise removal.
Key components in CA3_Diffusion_Models/codes/:
Why run CA3?
Files of interest in CA3_Diffusion_Models/:
codes/Diffusion_Models.ipynb — Implementation of DDPM.codes/score_based_models.ipynb — Score-based generative modeling.report/DGM_CA3_EN_final.pdf — Detailed report on experiments and results.README.md — Comprehensive documentation for CA3.images/ — Generated samples and visualizations from diffusion and score-based models.High-level suggested execution order:
CA4 explores advanced applications of deep generative models in vision-language tasks, specifically fine-tuning Google's Paligemma Vision-Language Model (VLM) on the CLEVR dataset using Parameter-Efficient Fine-Tuning (PEFT) techniques like Low-Rank Adaptation (LoRA).
Vision-Language Models (VLMs) are multi-modal models that can process both visual and textual information simultaneously. They typically consist of:
Parameter-Efficient Fine-Tuning (PEFT) addresses the challenge of adapting large pre-trained models without updating all parameters:
Fine-Tuning VLMs involves adapting general-purpose models to specific tasks:
CLEVR Dataset is designed for evaluating visual reasoning:
This assignment bridges traditional generative modeling with modern multi-modal AI, showing how generative techniques extend beyond image synthesis to language and reasoning tasks.
Fine-Tuning PaliGemma on CLEVR: Achieved 73% validation loss reduction (to 0.0234) with only 3% trainable parameters (~90M out of 3B). Training completed in ~2.5 hours on single GPU. Evaluation showed ROUGE scores indicating challenges with exact matching but successful adaptation.
Key components in CA4_Vision_Language_Model/code/final_CA4_training.ipynb:
Why run CA4?
Files of interest in CA4_Vision_Language_Model/:
code/final_CA4_training.ipynb — Complete implementation of Paligemma fine-tuning on CLEVR with LoRA.code/eval_p1/final_CA4_results1.ipynb — Evaluation notebook for part 1.code/eval_p2/final_CA4_results2.ipynb — Evaluation notebook for part 2.description/DGM_HW4.pdf — Assignment description and requirements.report/ — Student analysis and experimental results.README.md — Comprehensive documentation for CA4.High-level suggested execution order:
Proper data and artifact management is crucial for reproducible experiments in generative modeling.
torchvision into ./data/ by default. To avoid re-downloads and manage storage:
torchvision data directory: export TORCH_HOME=./data before running notebooks.CA1_Variational_Autoencoders/train/ folder contains pre-split smile/non-smile images. Verify integrity and consider backing up..pth files) for generators, discriminators, VAEs, flows, etc.
torch.save(generator.state_dict(), 'generator_epoch_50.pth')run_info.json for each experiment including hyperparameters, random seed, Git commit, and timestamps.Organize outputs like this:
experiments/
├── run_2023_10_01_vae_baseline/
│ ├── checkpoints/
│ │ ├── vae_epoch_10.pth
│ │ └── vae_final.pth
│ ├── samples/
│ │ ├── reconstructions.png
│ │ └── latent_interpolations.png
│ ├── logs/
│ │ └── tensorboard_logs/
│ └── run_info.json
└── run_2023_10_02_gan_fid/
├── ...
real_images/ fixed: create a reproducible reference set (e.g., 2048 images sampled from training set with fixed RNG) and reuse across runs.Reproducibility is essential in machine learning research. Follow these steps for reliable, comparable results.
requirements.txt or environment.yml and commit it.
requirements.txt:
torch==2.0.1
torchvision==0.15.2
numpy==1.24.3
matplotlib==3.7.1
pytorch-fid==0.10.1
Seeds: Set seeds for all sources of randomness at the start of each notebook's configuration cell.
Example:
import random
import numpy as np
import torch
seed = 42
random.seed(seed)
np.random.seed(seed)
torch.manual_seed(seed)
if torch.cuda.is_available():
torch.cuda.manual_seed_all(seed)
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False
Deterministic Operations: For PyTorch, set torch.backends.cudnn.deterministic = True to ensure reproducible convolutions.
git rev-parse --short HEAD
run_info.json for each run.
{
"experiment_name": "vae_baseline",
"commit": "abc123d",
"timestamp": "2023-10-01T12:00:00Z",
"seed": 42,
"hyperparameters": {
"latent_dim": 128,
"lr": 1e-3,
"batch_size": 64,
"epochs": 50
},
"model_config": {
"encoder_layers": [784, 512, 256, 128],
"decoder_layers": [128, 256, 512, 784]
},
"dataset": "CelebA_smile",
"notes": "Baseline VAE with KL annealing"
}
By following this checklist, experiments should be reproducible across different machines and time.
Before committing to long training runs (which can take hours or days), perform these quick checks to catch issues early.
VAE (CA1):
assert mu.shape == (batch_size, latent_dim)RealNVP (CA2):
(z, log_det_jacobian) with correct shapes.torch.allclose(x, inverse(z), atol=1e-5)GAN (CA2):
(batch_size, channels, height, width)Diffusion/Score-based (CA3):
batch_size=16, epochs=1, latent_dim=10, N=128 samples.FID (CA2):
Log-Likelihood (CA2):
Reconstruction/Generation Quality:
Consider adding unit tests using pytest:
def test_vae_forward():
vae = VAE(latent_dim=10)
x = torch.randn(4, 3, 64, 64)
recon, mu, logvar = vae(x)
assert recon.shape == x.shape
assert mu.shape == (4, 10)
Run tests: pytest tests/ (create a tests/ directory with test files).
This section covers frequent problems encountered when running the notebooks and suggested fixes.
nvidia-smi to check CUDA version, then install matching PyTorch from https://pytorch.org.calculate_fid_given_paths fails, try pip install clean-fid and use clean_fid.compute_fid instead. Ensure images are in [0,1] range and RGB.torchdiffeq for ODE integration. If ODE solvers fail, fall back to simpler Euler discretization.batch_size (e.g., from 64 to 16), or use gradient accumulation. Enable mixed precision: scaler = torch.cuda.amp.GradScaler().torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0). Verify input normalization.print(x.shape) liberally during debugging.torch.profiler or cProfile. Ensure data loading is not bottlenecked.log_prob = torch.clamp(log_prob, min=-1e10).wget or browser to download and place in ./data/.conda list or pip list to verify.torch.compile (PyTorch 2.0+) for speedups: model = torch.compile(model).torch.nn.DataParallel or DDP.torch.cuda.memory_summary().If issues persist, check GitHub issues for similar problems or post with full error traceback and environment details.
This section lists key papers, books, and resources related to the course topics.
VAEs:
Normalizing Flows:
GANs:
Diffusion Models:
For the latest research, check arXiv, NeurIPS, ICML, ICLR proceedings.
DGM_Fall_2023_Slides/: Course lecture slides with annotated versions and PDFs on topics like Mean-Field VI, Normalizing Flows, VAEs, Diffusion Models.Stanford_slides/: Supplementary slides from Stanford's CS236 (Deep Generative Models) course.MITSlides/: Additional slides from MIT and other sources.homework_template/: Homework templates and utility scripts.CS236_DGM/: Complete Stanford CS236 course materials.SUT/: Sharif University of Technology resources.notes/: General academic notes.ssi2023/: SSI 2023 materials.If you encounter issues with the course materials:
When posting issues, provide minimal reproducible examples and avoid sharing sensitive data.
The field of deep generative models is rapidly evolving. Based on this course, consider exploring:
This course provides a solid foundation for contributing to these exciting research directions.
This repository contains course materials for the Deep Generative Models course. The code and notebooks are intended for educational and research use. If you reuse code or figures derived from these materials in publications or public projects, please credit the course author and repository.
Jupyter Notebook
89.1%
Python
7.5%
TeX
2.3%
This repository collects lecture slides, assignments (CAs), code notebooks, reports, and reference papers used in the "Deep Generative Models" course (University of Tehran). The materials are organized to be reproducible and educational: each assignment contains an annotated Jupyter notebook, supporting code, and a report.Deep Generative Models
Jupyter Notebook
21
385 commits
updated Feb 14, 2026
This repository collects lecture slides, assignments (CAs), code notebooks, reports, and reference papers used in the "Deep Generative Models" course (University of Tehran). The materials are organized to be reproducible and educational: each assignment contains an annotated Jupyter notebook, supporting code, and a report.
Course Overview
The "Deep Generative Models" (DGM) course covers advanced topics in machine learning focused on generative modeling techniques. Generative models learn the underlying distribution of data to generate new samples, enabling applications in image synthesis, anomaly detection, data augmentation, and more.
Key topics covered in the course include:
The course assignments (CA1-CA4) progressively build skills in implementing and evaluating these models on real datasets like CelebA, FashionMNIST, and custom image datasets.
This section provides a high-level overview of the core mathematical and conceptual foundations that unify the different generative modeling approaches covered in the course.
Generative models aim to learn the underlying data distribution $p(\mathbf{x})$ from samples $\mathbf{x} \sim p_{\text{data}}$. The goal is to:
Most generative models are trained by maximizing the log-likelihood:
$$ \theta^* = \arg\max_\theta \mathbb{E}{\mathbf{x} \sim p{\text{data}}} [\log p_\theta(\mathbf{x})] $$
This is equivalent to minimizing the KL divergence between data and model distributions:
$$ \theta^* = \arg\min_\theta \text{KL}(p_{\text{data}} || p_\theta) $$
Many generative models introduce latent variables $\mathbf{z}$ to simplify modeling:
Exact inference in latent models is often intractable. Variational inference approximates posteriors using a recognition model:
Normalizing flows provide exact density estimation through invertible transformations:
GANs use adversarial objectives instead of explicit likelihoods:
Diffusion models gradually add noise and learn to reverse the process:
Score-based models learn the score function (gradient of log-density):
Assessing generative model quality requires both quantitative and qualitative measures:
Understanding these unifying principles helps in choosing appropriate models for different applications and in developing new generative techniques.
Prerequisites: Strong background in deep learning (PyTorch/TensorFlow), probability theory, and optimization. Specifically:
Students without this background may find the course challenging and are encouraged to review these topics beforehand.
CA1_Variational_Autoencoders/ — Course Assignment 1: Variational Autoencoders
code/ — Jupyter notebooks and code used for experiments (e.g., code.ipynb).description/ — Assignment description PDF.report/ — PDF reports and figures.images/ — Generated images and visualizations.train/ — Training datasets (CelebA subset: smile/non-smile images).README.md — Detailed documentation for CA1.CA2_GANs_Normalizing_Flows/ — Course Assignment 2: GANs and Normalizing Flows
code/ — Jupyter notebooks (e.g., CA2_DGM.ipynb, Q2_final_res.ipynb).description/ — Assignment description PDF.report/ — PDF reports and figures.images/ — Generated samples and visualizations.README.md — Detailed documentation for CA2.CA3_Diffusion_Models/ — Course Assignment 3: Diffusion and Score-based Models
codes/ — Jupyter notebooks (e.g., Diffusion_Models.ipynb, score_based_models.ipynb).description/ — Assignment description PDF.report/ — PDF reports and figures.images/ — Generated samples and visualizations.README.md — Detailed documentation for CA3.CA4_Vision_Language_Model/ — Course Assignment 4: Vision-Language Models
code/ — Jupyter notebooks (e.g., final_CA4_training.ipynb, evaluation notebooks).description/ — Assignment description PDF.report/ — PDF reports and figures.images/ — Generated images and visualizations.README.md — Detailed documentation for CA4.Slides/ — Lecture slides and course material used in class.
DGM_Fall_2023_Slides/ — Course lecture slides.Stanford_slides/ — Supplementary slides from Stanford's CS236 course.MITSlides/ — Additional slides from MIT and other sources.Exams/ — Past exams and solutions.ExtraNotes/ — Additional notes, homework templates, supplementary PDFs, and exploratory materials (e.g., homework_template/, research papers on D-separation).OtherTermAssignments/ — Assignments from other terms or related courses, including CA1, CA2, CA3 from previous semesters.OtherUniversityLecturs/ — Lecture materials from other universities and courses.
CS236_DGM/ — Complete materials from Stanford's CS236 Deep Generative Models course.SUT/ — Materials from Sharif University of Technology.notes/ — General notes and documentation.ssi2023/ — Materials from SSI 2023.PaperSLecturs/ — Research papers, codes, and lecture materials on advanced topics.
AI4Science_Codes/ — Code implementations for AI for Science applications.AI4Science_Papers/ — Research papers on AI for Science.Generative_Codes/ — Codes for generative models (e.g., conditional flow matching, Mamba).Generative_Models_Papers/ — Papers on generative models.LLM_Codes/ — Large Language Model implementations.LLM_Papers/ — Papers on LLMs.Vision_Codes/ — Computer vision codes.Vision_Papers/ — Papers on computer vision.This repository is primarily an educational resource. Notebooks are annotated for readability and (where possible) reorganized to centralize imports and configuration.
Recommended steps to set up a local, reproducible environment. We recommend using virtual environments to isolate dependencies.
python -m venv .venv
source .venv/bin/activate # On Windows: .venv\Scripts\activate
pip install -U pip
pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu118 # Example for CUDA 11.8
pip install matplotlib numpy scipy scikit-learn jupyterlab pytorch-fid tqdm
conda create -n dgm python=3.10
conda activate dgm
conda install pytorch torchvision torchaudio pytorch-cuda=11.8 -c pytorch -c nvidia # Adjust CUDA version
conda install matplotlib numpy scipy scikit-learn jupyterlab tqdm
pip install pytorch-fid
pip install torchdiffeq (for ODE solvers in score-based models).pip install seaborn plotly.pip install wandb (optional, for experiment tracking).Notes:
torch/torchvision binaries using the official instructions at https://pytorch.org. For CPU-only, omit CUDA-specific installs.pytorch-fid is used in CA2 for FID computation. If installation fails, consider alternatives like clean-fid.jupyter lab
Setup and Configuration cell in each notebook and run smoke tests described below.This section summarizes the primary assignments and their current status in the repository.
CA1 (folder: CA1_Variational_Autoencoders/)
code/code.ipynb, report/DGM_CA1_final_EN.pdf, README.md.train/smile/ and train/non_smile/.CA2 (folder: CA2_GANs_Normalizing_Flows/)
code/CA2_DGM.ipynb, code/Q2_final_res.ipynb, README.md.CA3 (folder: CA3_Diffusion_Models/)
codes/Diffusion_Models.ipynb, codes/score_based_models.ipynb, report/DGM_CA3_EN_final.pdf, README.md.CA4 (folder: CA4_Vision_Language_Model/)
code/final_CA4_training.ipynb, code/eval_p1/final_CA4_results1.ipynb, code/eval_p2/final_CA4_results2.ipynb, README.md.Other folders (Slides/, Extra/, Exams/) contain lecture materials, relevant readings, and supporting documents.
CA1 introduces Variational Autoencoders (VAEs), a cornerstone of generative modeling that combines variational inference with autoencoder architectures.
Variational Autoencoders (VAEs) are generative models that learn to encode input data into a low-dimensional latent space and decode it back to reconstruct the original data. Unlike traditional autoencoders, VAEs learn a probabilistic latent representation, allowing them to generate new samples by sampling from the learned distribution.
VAEs balance reconstruction fidelity with latent space regularization, making them useful for tasks like image generation, anomaly detection, and representation learning.
Encoder Network: The encoder progressively reduces spatial dimensions while increasing feature depth using convolutional layers, batch normalization, dropout, and LeakyReLU activations, culminating in linear layers that output mean (μ) and log variance (log σ²) for the latent distribution.
Reparameterization Trick: z = μ + σ ⊙ ε, where ε ~ N(0, I) and σ = exp(0.5 × logvar), enabling gradient flow through stochastic sampling.
Decoder Network: Mirrors the encoder with transposed convolutions, reconstructing images from latent vectors.
The Evidence Lower Bound (ELBO) combines reconstruction loss (MSE) and KL divergence regularization to balance fidelity and generalization.
Training Progress: Loss reduced by ~57% over training, with stable convergence and good generalization (validation loss tracks training loss closely).
Image Reconstruction: Effective preservation of facial features with slight smoothing; quantitative metrics show significant error reduction.
Image Generation: Diverse, realistic facial images generated by sampling from the prior, demonstrating generative capabilities.
Latent Space Analysis: Embeddings show clustering by smile/non-smile classes, with successful interpolation and classification performance.
Key components in CA1_Variational_Autoencoders/code/code.ipynb:
Why run CA1?
Files of interest in CA1_Variational_Autoencoders/:
code/code.ipynb — the annotated notebook (imports consolidated and configuration cell added).README.md — detailed documentation with synthesized report summary.train/ — contains CelebA subset (smile/non-smile) for training.report/ — PDF reports including DGM_CA1_final_EN.pdf.images/ — generated visualizations and outputs.High-level suggested execution order:
CA2 is both pedagogical and experimental. It demonstrates two complementary approaches to deep generative modeling:
Normalizing Flows are generative models that learn invertible transformations to map a simple base distribution (like a standard normal) to a complex data distribution. They provide exact likelihood computation and can be trained via maximum likelihood.
Generative Adversarial Networks (GANs) consist of two neural networks trained simultaneously: a generator that creates fake data and a discriminator that distinguishes real from fake. They learn through adversarial training without requiring explicit density estimation.
These approaches complement each other: flows provide mathematical rigor and exact evaluation, while GANs excel at generating high-quality samples.
GAN Training on FashionMNIST: Best FID score of 171.67 achieved at epoch 8, with overall ~23% improvement over 10 epochs. Samples show progressive quality improvement from blurry initial images to sharp, detailed fashion items.
Normalizing Flows: RealNVP implementation with coupling layers for invertible transformations, enabling exact density estimation and OOD detection via log-likelihoods on MNIST/KMNIST.
RealNVP (normalizing flows): an explicit density model trained by maximum likelihood. The notebook contains:
GAN (DCGAN-style): an adversarial generator trained to produce realistic fashion images. The notebook contains:
Generator and Discriminator classes implemented in PyTorch.pytorch-fid computed per-epoch.Why run CA2?
Files of interest in CA2_GANs_Normalizing_Flows/:
code/CA2_DGM.ipynb — the annotated notebook (imports consolidated and a configuration cell added).code/Q2_final_res.ipynb — additional results and experiments.README.md — localized instructions, reproducibility notes and quick-start steps.report/ — PDF reports including DGM_CA2_final_EN.pdf.images/ — generated samples and training progress visualizations.High-level suggested execution order (no code is run by the editor):
Setup and Configuration cell to set device, latent_dim, batch_size, epochs, and image_size.CA3 explores cutting-edge generative modeling techniques: Denoising Diffusion Probabilistic Models (DDPM) and Score-based Generative Models.
Denoising Diffusion Probabilistic Models (DDPM) are generative models that learn to reverse a gradual noising process. They consist of two processes:
Score-based Generative Models learn the score function (gradient of the log-density) of the data distribution. They can generate samples using stochastic processes:
These models represent the current state-of-the-art in generative modeling, offering superior sample quality compared to earlier approaches like VAEs and GANs.
Score-based Models: Trained on 2D Gaussian mixture data with different noise levels (σ=1,3,7). Best performance at σ=3 with final loss 0.012, demonstrating effective score field learning and sampling via Langevin dynamics. Annealed sampling provides robust results across noise levels.
Diffusion Models: Implementation of DDPM with forward diffusion process and reverse denoising, enabling high-quality image generation through iterative noise removal.
Key components in CA3_Diffusion_Models/codes/:
Why run CA3?
Files of interest in CA3_Diffusion_Models/:
codes/Diffusion_Models.ipynb — Implementation of DDPM.codes/score_based_models.ipynb — Score-based generative modeling.report/DGM_CA3_EN_final.pdf — Detailed report on experiments and results.README.md — Comprehensive documentation for CA3.images/ — Generated samples and visualizations from diffusion and score-based models.High-level suggested execution order:
CA4 explores advanced applications of deep generative models in vision-language tasks, specifically fine-tuning Google's Paligemma Vision-Language Model (VLM) on the CLEVR dataset using Parameter-Efficient Fine-Tuning (PEFT) techniques like Low-Rank Adaptation (LoRA).
Vision-Language Models (VLMs) are multi-modal models that can process both visual and textual information simultaneously. They typically consist of:
Parameter-Efficient Fine-Tuning (PEFT) addresses the challenge of adapting large pre-trained models without updating all parameters:
Fine-Tuning VLMs involves adapting general-purpose models to specific tasks:
CLEVR Dataset is designed for evaluating visual reasoning:
This assignment bridges traditional generative modeling with modern multi-modal AI, showing how generative techniques extend beyond image synthesis to language and reasoning tasks.
Fine-Tuning PaliGemma on CLEVR: Achieved 73% validation loss reduction (to 0.0234) with only 3% trainable parameters (~90M out of 3B). Training completed in ~2.5 hours on single GPU. Evaluation showed ROUGE scores indicating challenges with exact matching but successful adaptation.
Key components in CA4_Vision_Language_Model/code/final_CA4_training.ipynb:
Why run CA4?
Files of interest in CA4_Vision_Language_Model/:
code/final_CA4_training.ipynb — Complete implementation of Paligemma fine-tuning on CLEVR with LoRA.code/eval_p1/final_CA4_results1.ipynb — Evaluation notebook for part 1.code/eval_p2/final_CA4_results2.ipynb — Evaluation notebook for part 2.description/DGM_HW4.pdf — Assignment description and requirements.report/ — Student analysis and experimental results.README.md — Comprehensive documentation for CA4.High-level suggested execution order:
Proper data and artifact management is crucial for reproducible experiments in generative modeling.
torchvision into ./data/ by default. To avoid re-downloads and manage storage:
torchvision data directory: export TORCH_HOME=./data before running notebooks.CA1_Variational_Autoencoders/train/ folder contains pre-split smile/non-smile images. Verify integrity and consider backing up..pth files) for generators, discriminators, VAEs, flows, etc.
torch.save(generator.state_dict(), 'generator_epoch_50.pth')run_info.json for each experiment including hyperparameters, random seed, Git commit, and timestamps.Organize outputs like this:
experiments/
├── run_2023_10_01_vae_baseline/
│ ├── checkpoints/
│ │ ├── vae_epoch_10.pth
│ │ └── vae_final.pth
│ ├── samples/
│ │ ├── reconstructions.png
│ │ └── latent_interpolations.png
│ ├── logs/
│ │ └── tensorboard_logs/
│ └── run_info.json
└── run_2023_10_02_gan_fid/
├── ...
real_images/ fixed: create a reproducible reference set (e.g., 2048 images sampled from training set with fixed RNG) and reuse across runs.Reproducibility is essential in machine learning research. Follow these steps for reliable, comparable results.
requirements.txt or environment.yml and commit it.
requirements.txt:
torch==2.0.1
torchvision==0.15.2
numpy==1.24.3
matplotlib==3.7.1
pytorch-fid==0.10.1
Seeds: Set seeds for all sources of randomness at the start of each notebook's configuration cell.
Example:
import random
import numpy as np
import torch
seed = 42
random.seed(seed)
np.random.seed(seed)
torch.manual_seed(seed)
if torch.cuda.is_available():
torch.cuda.manual_seed_all(seed)
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False
Deterministic Operations: For PyTorch, set torch.backends.cudnn.deterministic = True to ensure reproducible convolutions.
git rev-parse --short HEAD
run_info.json for each run.
{
"experiment_name": "vae_baseline",
"commit": "abc123d",
"timestamp": "2023-10-01T12:00:00Z",
"seed": 42,
"hyperparameters": {
"latent_dim": 128,
"lr": 1e-3,
"batch_size": 64,
"epochs": 50
},
"model_config": {
"encoder_layers": [784, 512, 256, 128],
"decoder_layers": [128, 256, 512, 784]
},
"dataset": "CelebA_smile",
"notes": "Baseline VAE with KL annealing"
}
By following this checklist, experiments should be reproducible across different machines and time.
Before committing to long training runs (which can take hours or days), perform these quick checks to catch issues early.
VAE (CA1):
assert mu.shape == (batch_size, latent_dim)RealNVP (CA2):
(z, log_det_jacobian) with correct shapes.torch.allclose(x, inverse(z), atol=1e-5)GAN (CA2):
(batch_size, channels, height, width)Diffusion/Score-based (CA3):
batch_size=16, epochs=1, latent_dim=10, N=128 samples.FID (CA2):
Log-Likelihood (CA2):
Reconstruction/Generation Quality:
Consider adding unit tests using pytest:
def test_vae_forward():
vae = VAE(latent_dim=10)
x = torch.randn(4, 3, 64, 64)
recon, mu, logvar = vae(x)
assert recon.shape == x.shape
assert mu.shape == (4, 10)
Run tests: pytest tests/ (create a tests/ directory with test files).
This section covers frequent problems encountered when running the notebooks and suggested fixes.
nvidia-smi to check CUDA version, then install matching PyTorch from https://pytorch.org.calculate_fid_given_paths fails, try pip install clean-fid and use clean_fid.compute_fid instead. Ensure images are in [0,1] range and RGB.torchdiffeq for ODE integration. If ODE solvers fail, fall back to simpler Euler discretization.batch_size (e.g., from 64 to 16), or use gradient accumulation. Enable mixed precision: scaler = torch.cuda.amp.GradScaler().torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0). Verify input normalization.print(x.shape) liberally during debugging.torch.profiler or cProfile. Ensure data loading is not bottlenecked.log_prob = torch.clamp(log_prob, min=-1e10).wget or browser to download and place in ./data/.conda list or pip list to verify.torch.compile (PyTorch 2.0+) for speedups: model = torch.compile(model).torch.nn.DataParallel or DDP.torch.cuda.memory_summary().If issues persist, check GitHub issues for similar problems or post with full error traceback and environment details.
This section lists key papers, books, and resources related to the course topics.
VAEs:
Normalizing Flows:
GANs:
Diffusion Models:
For the latest research, check arXiv, NeurIPS, ICML, ICLR proceedings.
DGM_Fall_2023_Slides/: Course lecture slides with annotated versions and PDFs on topics like Mean-Field VI, Normalizing Flows, VAEs, Diffusion Models.Stanford_slides/: Supplementary slides from Stanford's CS236 (Deep Generative Models) course.MITSlides/: Additional slides from MIT and other sources.homework_template/: Homework templates and utility scripts.CS236_DGM/: Complete Stanford CS236 course materials.SUT/: Sharif University of Technology resources.notes/: General academic notes.ssi2023/: SSI 2023 materials.If you encounter issues with the course materials:
When posting issues, provide minimal reproducible examples and avoid sharing sensitive data.
The field of deep generative models is rapidly evolving. Based on this course, consider exploring:
This course provides a solid foundation for contributing to these exciting research directions.
This repository contains course materials for the Deep Generative Models course. The code and notebooks are intended for educational and research use. If you reuse code or figures derived from these materials in publications or public projects, please credit the course author and repository.
Jupyter Notebook
89.1%
Python
7.5%
TeX
2.3%