পাঠ ১৩ · ২৮-এর মধ্যে · মডিউল ৩

DDPM — গণিত ও কোড

DDPM in detail — math & PyTorch implementation
৯ মিনিট পড়া মাঝারি+ · Intermediate+ ELBO derivation

এই পাঠে যা শিখবেন

  • DDPM-এর forward/reverse process — পূর্ণ গাণিতিক derivation
  • ELBO থেকে $\mathcal{L}_{\text{simple}}$-এ পৌঁছানোর পথ
  • Linear ও cosine noise schedule — কোনটি কেন
  • U-Net architecture ও PyTorch training/sampling — পূর্ণ implementation

১ · Forward process — re-cap

Ho, Jain, Abbeel (NeurIPS 2020) DDPM define করেছিলেন এভাবে:

$$q(\mathbf{x}_{1:T} \mid \mathbf{x}_0) = \prod_{t=1}^{T} q(\mathbf{x}_t \mid \mathbf{x}_{t-1}), \quad q(\mathbf{x}_t \mid \mathbf{x}_{t-1}) = \mathcal{N}(\mathbf{x}_t; \sqrt{1-\beta_t}\,\mathbf{x}_{t-1}, \beta_t\mathbf{I})$$

Variance scheduleVariance Schedule$\beta_1, \beta_2, \ldots, \beta_T$ — প্রতি timestep-এ কতটা noise যোগ হবে। DDPM-এ linear $1\!\!\times\!\!10^{-4}$ থেকে $0.02$। Improved DDPM-এ cosine। $\beta_t \in (0, 1)$। আমরা শেখাই $\mathbf{x}_T \approx \mathcal{N}(0, \mathbf{I})$ — মূল data-র কোনো trace নেই।

২ · Closed-form $q(\mathbf{x}_t \mid \mathbf{x}_0)$

$\alpha_t = 1-\beta_t$, $\bar\alpha_t = \prod_{s=1}^{t}\alpha_s$ define করুন। তখন:

$$q(\mathbf{x}_t \mid \mathbf{x}_0) = \mathcal{N}(\mathbf{x}_t; \sqrt{\bar\alpha_t}\,\mathbf{x}_0, (1-\bar\alpha_t)\mathbf{I})$$

Reparameterization: $\mathbf{x}_t = \sqrt{\bar\alpha_t}\mathbf{x}_0 + \sqrt{1-\bar\alpha_t}\,\boldsymbol\epsilon, \; \boldsymbol\epsilon\sim\mathcal{N}(0,\mathbf{I})$.

৩ · Reverse posterior — $q(\mathbf{x}_{t-1} \mid \mathbf{x}_t, \mathbf{x}_0)$

ম্যাজিক — $\mathbf{x}_0$ জানলে reverse step closed-form Gaussian:

$$q(\mathbf{x}_{t-1} \mid \mathbf{x}_t, \mathbf{x}_0) = \mathcal{N}(\mathbf{x}_{t-1}; \tilde\mu_t(\mathbf{x}_t, \mathbf{x}_0), \tilde\beta_t \mathbf{I})$$

যেখানে $$\tilde\mu_t = \frac{\sqrt{\bar\alpha_{t-1}}\beta_t}{1-\bar\alpha_t}\mathbf{x}_0 + \frac{\sqrt{\alpha_t}(1-\bar\alpha_{t-1})}{1-\bar\alpha_t}\mathbf{x}_t, \quad \tilde\beta_t = \frac{1-\bar\alpha_{t-1}}{1-\bar\alpha_t}\beta_t$$

Network কী predict করে

$p_\theta(\mathbf{x}_{t-1}\mid\mathbf{x}_t) = \mathcal{N}(\mathbf{x}_{t-1}; \mu_\theta(\mathbf{x}_t, t), \sigma_t^2\mathbf{I})$ — variance fixed ($\sigma_t^2 = \tilde\beta_t$ বা $\beta_t$); শুধু mean network learn করে। Mean-কে $\epsilon$-form-এ লিখলে — network actually $\epsilon_\theta(\mathbf{x}_t, t)$ predict করে।

৪ · Loss — ELBO থেকে $\mathcal{L}_{\text{simple}}$

Variational bound: $$-\log p_\theta(\mathbf{x}_0) \le \mathbb{E}_q\Big[\underbrace{D_{KL}(q(\mathbf{x}_T \mid \mathbf{x}_0) \| p(\mathbf{x}_T))}_{L_T} + \sum_{t>1}\underbrace{D_{KL}(q(\mathbf{x}_{t-1}\mid\mathbf{x}_t,\mathbf{x}_0)\|p_\theta(\mathbf{x}_{t-1}\mid\mathbf{x}_t))}_{L_{t-1}} \underbrace{- \log p_\theta(\mathbf{x}_0\mid\mathbf{x}_1)}_{L_0}\Big]$$

$L_T$ — constant ($\theta$ নেই)। $L_{t-1}$ — দু'টি Gaussian-এর KL — closed form। $\epsilon$-parameterization-এ simplify করলে:

$$\mathcal{L}_{\text{simple}} = \mathbb{E}_{t \sim U[1,T], \mathbf{x}_0, \boldsymbol\epsilon}\Big[\big\|\boldsymbol\epsilon - \epsilon_\theta(\sqrt{\bar\alpha_t}\mathbf{x}_0 + \sqrt{1-\bar\alpha_t}\boldsymbol\epsilon, t)\big\|^2\Big]$$

Ho et al. দেখালেন — full ELBO-র চেয়ে এই simplified objective sample quality-তে ভালো। এটি reweighted loss — প্রতিটি $t$-কে সমান weight দেয়।

৫ · Noise schedule — linear vs cosine

  • Linear (DDPM): $\beta_t$ linearly $10^{-4} \to 0.02$, $T=1000$।
  • Cosine (Improved DDPM, Nichol & Dhariwal 2021): $\bar\alpha_t = \cos^2\left(\frac{t/T + s}{1+s}\frac{\pi}{2}\right)$, $s=0.008$।
  • Linear-এ শেষের দিকে ছবি দ্রুত destroyed — শেষ ২০-৩০% step "অপচয়"। Cosine আরো সুষম।

৬ · U-Net architecture

DDPM-এ standard noise prediction network — U-Net:

  • Encoder: $C \times H \times W$ → ছোট spatial, বেশি channel। Downsample blocks।
  • Bottleneck: Self-attention layer — global context।
  • Decoder: Upsample + skip connections (encoder থেকে)।
  • Time embedding: $t$-কে sinusoidal encode → MLP → প্রতি ResBlock-এ inject।
  • Output: input-এর মতোই shape — predicted $\boldsymbol\epsilon$।
DDPM U-Net — ε prediction input xₜ → predicted ε xₜ noisy Down 1 64ch 32×32 Down 2 128ch 16×16 Down 3 256ch 8×8 Mid+Attn 512ch Up 1 256ch 8×8 Up 2 128ch 16×16 Up 3 64ch 32×32 skip connections Sinusoidal(t) → MLP → 512 প্রতি ResBlock-এ inject → ε̂ β-schedule: linear (DDPM) বা cosine (improved DDPM) Loss: ‖ε − ε̂‖²
U-Net encoder-decoder + skip connections + sinusoidal time embedding। প্রতি ResBlock-এ time signal যোগ করে network জানে এখন কোন noise level।

৭ · PyTorch — training loop

Python · PyTorch
import torch, torch.nn as nn, torch.nn.functional as F

class DDPM:
    def __init__(self, T=1000, beta_start=1e-4, beta_end=0.02, device='cuda'):
        self.T = T
        self.betas = torch.linspace(beta_start, beta_end, T, device=device)
        self.alphas = 1. - self.betas
        self.alpha_bar = torch.cumprod(self.alphas, dim=0)

    def q_sample(self, x0, t, noise):
        a = self.alpha_bar[t].view(-1, 1, 1, 1)
        return a.sqrt() * x0 + (1 - a).sqrt() * noise

    def loss(self, model, x0):
        B = x0.shape[0]
        t = torch.randint(0, self.T, (B,), device=x0.device)
        noise = torch.randn_like(x0)
        xt = self.q_sample(x0, t, noise)
        pred = model(xt, t)
        return F.mse_loss(pred, noise)

    @torch.no_grad()
    def sample(self, model, shape):
        x = torch.randn(shape, device=self.betas.device)
        for t in reversed(range(self.T)):
            t_b = torch.full((shape[0],), t, device=x.device, dtype=torch.long)
            eps = model(x, t_b)
            a_t = self.alphas[t]; ab_t = self.alpha_bar[t]; b_t = self.betas[t]
            mean = (1/a_t.sqrt()) * (x - (b_t / (1 - ab_t).sqrt()) * eps)
            if t > 0:
                x = mean + b_t.sqrt() * torch.randn_like(x)
            else:
                x = mean
        return x

    
Training loop-এ opt.zero_grad(); ddpm.loss(model, x).backward(); opt.step()। MNIST-এ ১০-২০ epoch-এ ভাল sample।

৮ · Practical training tips

  • EMA: Model weights-এর exponential moving average — sampling-এ ব্যবহার করুন (decay 0.999)।
  • Mixed precision: bf16/fp16 — 2× faster, similar quality।
  • Gradient clipping: $\|g\| \le 1$ — early training stable।
  • Larger batch: diffusion batch-size-এ scaling ভাল — ১২৮+ recommended।
DDPM-এর sampling slow — ১০০০ U-Net call ছবিপ্রতি। Production-এ DDIM (50 step) বা DPM-Solver++ (10-20 step) ব্যবহার করুন।

ভাবনার প্রশ্ন

প্রতিটি প্রশ্ন নিজে কিছুক্ষণ ভাবুন — তারপর "→ উত্তর" চাপুন।

প্র ০১ Ho et al. ELBO-র সব $L_{t-1}$-এ আলাদা weight ছিল। $\mathcal{L}_{\text{simple}}$-এ সব সমান weight। তবু empirically ভাল কাজ করে — কেন এটি counterintuitive এবং পরবর্তী research কী বলে?

এটি diffusion research-এর সবচেয়ে subtle অথচ গুরুত্বপূর্ণ observation।

Original ELBO-তে weight:

  • $L_{t-1}$-এর coefficient $\frac{\beta_t^2}{2\sigma_t^2 \alpha_t (1-\bar\alpha_t)}$ — $t$-নির্ভর।
  • ছোট $t$ (কম noise) → large weight; বড় $t$ → small weight।
  • Theory অনুযায়ী এটি tight bound দেয়।

$\mathcal{L}_{\text{simple}}$ সব $t$-এ uniform weight — তবু ভাল কেন:

  • Perceptual quality vs likelihood mismatch: Higher $t$ (বেশি noise)-এ predict করা কঠিন কিন্তু perceptually গুরুত্বপূর্ণ — global structure ঠিক করতে। Uniform weight এই কঠিন ধাপে বেশি focus দেয়।
  • Lower variance estimator: Uniform weight stochastic gradient-এর variance কমায়। Optimization stable।
  • Trade-off: Likelihood (NLL) ELBO-র চেয়ে worse, কিন্তু FID/IS sample quality ভাল। আমরা সাধারণত sample quality-ই চাই।

পরবর্তী research:

  • P2 weighting (Choi et al. 2022): "Perception Prioritized Training" — middle $t$-তে বেশি weight, যেখানে perceptual feature গঠিত হয়। FID আরো ভাল।
  • Min-SNR (Hang et al. 2023): $\min(\text{SNR}_t, \gamma)$ weight — high-SNR step over-weight রোধ। SDXL-এ ব্যবহৃত।
  • v-parameterization (Salimans & Ho 2022): $v = \alpha_t \epsilon - \sigma_t \mathbf{x}_0$ predict — distillation-এ চমৎকার।
  • Variational Diffusion (Kingma et al. 2021): Variance schedule-কেই learnable করল — SOTA likelihood।
  • EDM (Karras et al. 2022): Continuous-time formulation, $\sigma$ কে directly parameterize, Heun sampler — ImageNet SOTA।

Core insight:

  • Diffusion-এ "loss weighting" = "কোন noise level-এ network capacity কোথায় লাগবে"।
  • Empirical finding প্রায়ই theoretical bound-এর চেয়ে ভাল practical result দেয়।
  • Sample quality ও likelihood ভিন্ন objective — সব scenario-তে align করে না।

মূল উপলব্ধি: ML-এ "theoretically optimal" আর "empirically best"-এর gap অনেক — DL throughout এই pattern দেখা যায়। DDPM-এর simplification এর প্রতীকী example।

প্র ০২ Linear vs cosine schedule — Improved DDPM (Nichol & Dhariwal) দেখাল cosine ভাল। গাণিতিকভাবে কী ঘটছে এবং SNR-এর ভাষায় কীভাবে ব্যাখ্যা করা যায়?

Schedule choice আসলে "কখন কতটুকু noise" — যা training signal-কে drastically প্রভাবিত করে।

Signal-to-Noise Ratio (SNR):

  • $\text{SNR}(t) = \bar\alpha_t / (1-\bar\alpha_t)$।
  • $t=0$ — SNR অসীম (pure signal)। $t=T$ — SNR ≈ 0 (pure noise)।
  • Training নির্ভর করে $\log\text{SNR}(t)$-এর distribution-এর উপর।

Linear schedule সমস্যা:

  • $\beta_t$ linear $10^{-4} \to 0.02$ → $\bar\alpha_t$ early দ্রুত drop, পরে slowly।
  • Image $256\times 256$-এ $t=200$-তেই প্রায় pure noise।
  • $t \in [200, 1000]$ "wasted" — শুধু noise, কিছু শিখছে না।
  • $\log\text{SNR}$ distribution skewed — শেষের দিকে অনেক empty step।

Cosine schedule সমাধান: $\bar\alpha_t = \cos^2\left(\frac{t/T+s}{1+s}\frac{\pi}{2}\right)$

  • $\bar\alpha_t$ smoother — শুরুতে slowly drop, মাঝে faster, শেষে আবার slow।
  • Image বেশি timestep জুড়ে partially noisy — প্রতি $t$-তে useful signal।
  • $\log\text{SNR}$ approximately linear in $t$ — uniform learning across timesteps।
  • $s = 0.008$ small offset — প্রথম step extreme না হয়।

Empirical impact:

  • ImageNet $64\times 64$ FID: linear ৩.৪১ → cosine ৩.১৭।
  • Higher resolution ($256+$)-এ পার্থক্য আরো বেশি।
  • Faster convergence — একই FID কম step-এ।

আরো advanced schedules:

  • Sigmoid schedule (Jabri et al. 2022): high-resolution image-এ আরো ভাল।
  • EDM (Karras 2022): $\sigma$-parameterization, log-normal sampling of $\sigma$।
  • SD3 (Stability AI 2024): Logit-normal $t$ sampling — rectified flow।
  • Resolution-dependent shift: SD3, Flux — high-resolution-এ schedule shift।

Practical guidance:

  • $32 \times 32$ MNIST/CIFAR — linear ঠিক আছে।
  • $64+$ — cosine বা sigmoid use করুন।
  • Latent diffusion ($64 \times 64$ latent for $512 \times 512$ image) — cosine standard।
  • Schedule-কে hyperparameter হিসেবে ablate করুন — sample quality-এ বড় effect।

মূল উপলব্ধি: Diffusion-এ schedule "training curriculum" — কোন noise level-এ কতটুকু সময় কাটাবে। Wrong schedule = অর্ধেক network capacity wasted। SD3/Flux-এর rectified flow এই concept-কেই extreme limit-এ নিয়ে গেছে।

প্র ০৩ U-Net কেন diffusion-এর জন্য idealized architecture? Transformer (DiT, U-ViT) ও Mamba-based diffusion-এর সাথে তুলনা — সাম্প্রতিক gradient কোন দিকে?

U-Net Ronneberger et al. (২০১৫) বায়োমেডিকাল segmentation-এর জন্য ছিল। আজ এটি diffusion-এর de facto backbone।

U-Net-এর শক্তি diffusion-এ:

  • Multi-scale feature: Encoder সংকুচিত, decoder পুনর্নির্মাণ — বিভিন্ন scale-এ feature। Image-এ low-level (texture) ও high-level (object) দু'টোই দরকার।
  • Skip connections: Encoder থেকে decoder-এ direct connection — pixel-precise reconstruction। Diffusion-এ ε prediction same shape হিসেবে output, এই symmetry আদর্শ।
  • Locality: Convolution local pattern শেখায় — early diffusion (CIFAR, MNIST)-এ যথেষ্ট।
  • Time conditioning: ResBlock-এ AdaGN/FiLM সহজে inject।
  • Memory efficient: Conv-based — memory linear in image size।

U-Net-এর সীমাবদ্ধতা:

  • Long-range dependency দুর্বল: Conv local — global structure-এ struggle।
  • Scaling law unclear: Width বাড়ালে কতটুকু gain?
  • Architecture engineering hand-crafted: Transformer-এর মতো clean না।

DiT — Diffusion Transformer (Peebles & Xie 2022):

  • Image-কে patch-এ ভাঙো, ViT-এর মতো transformer apply করো।
  • Time + class conditioning — adaLN (adaptive LayerNorm) দিয়ে।
  • Result: U-Net-এর চেয়ে clean scaling — model size 2× → FID consistently better।
  • Sora, Stable Diffusion 3, Flux — সবই DiT-ভিত্তিক।

U-ViT (Bao et al. 2022):

  • U-Net + ViT হাইব্রিড — long skip connections + transformer blocks।
  • U-Net-এর inductive bias + transformer-এর global attention।

Mamba/SSM diffusion (2024):

  • State Space Model — linear complexity in sequence length।
  • High-resolution video-এ transformer cost prohibitive — Mamba alternative।
  • DiM (Diffusion Mamba), Zigma — early experiments।

২০২৪-২৫-এর ট্রেন্ড:

  • Sora (OpenAI 2024): Spacetime patches + DiT — video diffusion।
  • SD3 (Stability AI): MMDiT — multi-modal DiT, text-image joint attention।
  • Flux.1 (Black Forest Labs): Hybrid double-stream + single-stream DiT।
  • Hybrid CNN+Transformer: low-resolution-এ ViT, high-resolution-এ U-Net residual।

কখন কোনটি:

  • Small dataset, low-resolution: U-Net যথেষ্ট, simpler।
  • Large-scale text-to-image: DiT/MMDiT।
  • Video, 3D: SSM-hybrid বা spatial-temporal DiT।
  • Edge deployment: U-Net-এর দিকে ফিরে আসা hardware efficiency-র জন্য।

মূল উপলব্ধি: Architecture choice scale-নির্ভর। NLP-তে যেমন CNN→RNN→Transformer, vision-এ একই rotation। U-Net diffusion-কে শুরু করেছিল, DiT scale করছে — আগামী ৫ বছরে আরো convergence আসবে।

প্র ০৪ আপনি একটি একটি স্থানীয় startup-এ সাত্রী-ভিত্তিক যন্ত্র (NLP-CV mix) তৈরি করছেন এবং একটি custom DDPM train করতে চান (যেমন বাংলা ক্যালিগ্রাফি ছবি)। কী কী practical challenge মোকাবিলা করবেন এবং কোন pre-trained model থেকে শুরু করবেন?

Custom diffusion training — startup-এ অসম্ভব নয় কিন্তু বাস্তব challenge প্রচুর।

Challenge ১: Compute

  • From-scratch DDPM CIFAR ($32\times32$): 1×V100, 2 দিন। MNIST: 1×T4, 4 ঘন্টা।
  • $256\times 256$ ImageNet-quality: 8×A100, 2 সপ্তাহ ($25K+ AWS bill)।
  • Stable Diffusion-quality: 256×A100, 1 মাস ($600K)।
  • সমাধান: Pre-trained থেকে fine-tune। Latent diffusion ব্যবহার (১০× cheaper)।

Challenge ২: Data

  • বাংলা ক্যালিগ্রাফি — সম্ভবত ৫০০-৫০০০ ছবি available।
  • From scratch — minimum ১০K, ভাল হলে ১০০K+।
  • সমাধান:
    • Web scraping (copyright respect)।
    • Synthetic augmentation (rotation, scale, contrast)।
    • Manual collection — ART college, Bangla Academy archive।
    • LoRA fine-tune (পাঠ ১৯) — ৩০-১০০ ছবি যথেষ্ট।

Challenge ৩: Engineering

  • Distributed training — DDP/FSDP, torch elastic।
  • Checkpointing, mixed precision, EMA।
  • Evaluation metric — FID, CLIP score। Human evaluation।
  • Safety — NSFW filter, watermarking।

Challenge ৪: Cultural & Linguistic

  • Bangla text-to-image — text encoder problem। CLIP English-heavy।
  • সমাধান: BanglaCLIP (UCLA, BUET research) বা multilingual CLIP।
  • বাংলা script accurately render করা — text-in-image diffusion-এর সবচেয়ে বড় challenge।

Recommended starting points:

  • Stable Diffusion 1.5 (RunwayML): Most compatible, huge community, LoRA ecosystem। Permissive license।
  • SDXL (Stability AI): $1024\times 1024$, ভাল text rendering। Bigger VRAM (16GB+)।
  • SD3 medium: Latest architecture, MMDiT, transformer-based।
  • Flux.1 dev: Best quality 2024, but heavy ($24GB+ VRAM)।
  • HuggingFace diffusers library: All above + training scripts ready।

Practical workflow (বাংলা ক্যালিগ্রাফি):

  1. ২০০-৫০০ ছবি collect → manual cleanup ($512\times 512$)।
  2. SDXL + LoRA fine-tune — Colab Pro ($10/মাস), 4-8 ঘন্টা।
  3. Trigger word: "bangla calligraphy style"।
  4. Eval: hand-pick 50 generation, native speaker rate।
  5. Iterate dataset cleanup, prompt tuning।
  6. Deploy: ComfyUI workflow, FastAPI backend।

Cost estimate:

  • Compute (LoRA train + experiments): ৳৫,০০০-১৫,০০০ Colab।
  • Cloud GPU (A100): ৳৫০-১০০/ঘন্টা, total ৳২০,০০০-৫০,০০০।
  • Production hosting: Replicate, RunPod — ৳০.৫-২/ছবি।

Common pitfalls:

  • Train from scratch — startup-এ আত্মঘাতী।
  • Quality vs quantity ভুল — ১০০ ভাল ছবি > ১০০০ noisy।
  • Trigger word খুব generic — overfitting বা undertraining।
  • License ignore — SDXL non-commercial vs SD1.5 permissive।

মূল কথা: ২০২৫-এ "নতুন diffusion train" প্রায়ই "fine-tune existing"। Compute, data, engineering balance — pragmatic engineering choice উদ্ভাবনের চেয়ে গুরুত্বপূর্ণ। বাংলা cultural content-এ specialized fine-tune large opportunity — কেউ এখনো ভাল করেনি।

অনুশীলন

  1. $\bar\alpha_t$ ও SNR: Linear schedule $\beta_1=0.0001, \beta_T=0.02, T=1000$-তে $t=500$-এ $\bar\alpha_{500}$ (approximate) ও SNR কত? পথ দেখান।

    $\beta_{500} \approx 0.0001 + (500/1000)(0.02 - 0.0001) \approx 0.01$।

    $\bar\alpha_{500} = \prod_{s=1}^{500}(1-\beta_s)$। Approximately $\exp(-\sum \beta_s) \approx \exp(-2.5) \approx 0.082$।

    SNR $= 0.082/(1-0.082) \approx 0.089$ — অর্থাৎ noise dominates already।

  2. Sampling step verify: উপরের sample() function-এ $t=0$-তে কেন noise যোগ করা হয় না? কেন $t > 0$-তে যোগ করি?

    $t=0$ — final step। আমরা $\mathbf{x}_0$-এর mean চাই, randomness যোগ করলে অপ্রয়োজনীয় noise। $t > 0$-তে $p_\theta$ Gaussian — variance term sampling diversity দেয়। $t=0$-তে variance term-ই $\beta_0 \to 0$ effectively।

  3. Code modification: উপরের DDPM class-এ cosine_schedule() method যোগ করুন — Improved DDPM-এর formula দিয়ে।
    def cosine_schedule(self, T, s=0.008):
        t = torch.linspace(0, T, T+1) / T
        f = torch.cos((t + s) / (1 + s) * torch.pi/2) ** 2
        alpha_bar = f / f[0]
        betas = 1 - alpha_bar[1:] / alpha_bar[:-1]
        return torch.clip(betas, 0.0001, 0.999)

আরও পড়ুন · ABCL TECH-এ আপনার পরবর্তী পদক্ষেপ

কোড রানার কাজ না করলে? Google Colab ব্যবহার করুন — ফ্রি GPU পাবেন। MNIST DDPM ১-২ ঘন্টায় train হয়।
পূর্ববর্তী পাঠ
পাঠ ১২ · Diffusion intuition