Score matching ও SDE
এই পাঠে যা শিখবেন
- Score function ও score matching — গাণিতিক সংজ্ঞা ও geometric intuition
- Denoising Score Matching (Vincent 2011) — DDPM-এর সাথে সংযোগ
- Forward & reverse SDE — Anderson 1982-এর reverse-time formulation
- Langevin sampling ও probability flow ODE
১ · Score function কী
একটি probability density $p(\mathbf{x})$-এর scoreScore Function$\nabla_{\mathbf{x}} \log p(\mathbf{x})$ — log-density-এর gradient। প্রতিটি বিন্দুতে দেখায় density বাড়ানোর দিক। Statistics-এ Stein score। ML-এ score-based generative modeling-এর ভিত্তি।:
$$s(\mathbf{x}) = \nabla_{\mathbf{x}} \log p(\mathbf{x})$$
এটি একটি vector field — প্রতিটি $\mathbf{x}$-এ একটি ভেক্টর। ভেক্টরটি দেখায় কোন দিকে গেলে density বাড়বে। Modes (peak)-এ score শূন্য, valley-তে বড়।
$p(\mathbf{x})$ জানা প্রায়ই অসম্ভব (normalization constant unknown)। কিন্তু $\nabla \log p = \nabla \log [\tilde p / Z] = \nabla \log \tilde p$ — $Z$ vanishes! তাই score শেখা likelihood শেখার চেয়ে সহজ।
২ · Score matching loss
আমরা একটি network $s_\theta(\mathbf{x}) \approx \nabla_{\mathbf{x}} \log p(\mathbf{x})$ চাই। Hyvärinen (২০০৫) score matching:
$$\mathcal{L}_{SM} = \mathbb{E}_{p(\mathbf{x})}\Big[\frac{1}{2}\|s_\theta(\mathbf{x}) - \nabla_{\mathbf{x}}\log p(\mathbf{x})\|^2\Big]$$
সমস্যা — ground-truth score-ই অজানা। Trick: integration by parts:
$$\mathcal{L}_{SM} = \mathbb{E}_p\Big[\frac{1}{2}\|s_\theta(\mathbf{x})\|^2 + \text{tr}(\nabla_{\mathbf{x}} s_\theta(\mathbf{x}))\Big] + \text{const}$$
কিন্তু trace high-dim-এ expensive। তাই — Denoising Score Matching।
৩ · Denoising Score Matching (Vincent 2011)
Data perturb করুন: $\tilde{\mathbf{x}} = \mathbf{x} + \sigma \boldsymbol\epsilon, \; \boldsymbol\epsilon \sim \mathcal{N}(0, \mathbf{I})$। তখন:
$$\nabla_{\tilde{\mathbf{x}}} \log q(\tilde{\mathbf{x}} \mid \mathbf{x}) = -\frac{\tilde{\mathbf{x}} - \mathbf{x}}{\sigma^2} = -\frac{\boldsymbol\epsilon}{\sigma}$$
DSM loss:
$$\mathcal{L}_{DSM} = \mathbb{E}\Big[\big\|s_\theta(\tilde{\mathbf{x}}, \sigma) + \boldsymbol\epsilon/\sigma\big\|^2\Big]$$
৪ · NCSN — Noise Conditional Score Network
Song & Ermon (২০১৯) দেখালেন — একটি $\sigma$ যথেষ্ট নয়। Multi-scale:
- $\sigma_1 > \sigma_2 > \ldots > \sigma_L$ (geometric scale)।
- একটি network $s_\theta(\mathbf{x}, \sigma)$ — সব scale-এ score শেখে।
- Loss: $\sum_i \lambda(\sigma_i) \mathcal{L}_{DSM}^{(i)}$।
- Sampling: Langevin dynamicsLangevin Dynamics$\mathbf{x}_{k+1} = \mathbf{x}_k + (\eta/2) s(\mathbf{x}_k) + \sqrt{\eta}\,\boldsymbol\epsilon$ — score ব্যবহার করে high-density region-এ sample। Statistical physics-এর Langevin equation থেকে। annealed scale-এ।
৫ · SDE — continuous time
Song et al. (২০২১, "Score-Based Generative Modeling through SDEs") সব unify করলেন।
Forward SDE: $$d\mathbf{x} = f(\mathbf{x}, t)\,dt + g(t)\,d\mathbf{w}$$
$\mathbf{w}$ — standard Brownian motion। $f$ drift, $g$ diffusion coefficient।
Two famous cases:
- VP-SDE (Variance Preserving): $d\mathbf{x} = -\frac{1}{2}\beta(t)\mathbf{x}\,dt + \sqrt{\beta(t)}\,d\mathbf{w}$ — DDPM-এর continuous limit। Variance bounded।
- VE-SDE (Variance Exploding): $d\mathbf{x} = \sqrt{\frac{d[\sigma^2(t)]}{dt}}\,d\mathbf{w}$ — SMLD/NCSN-এর continuous limit। Variance বাড়তে থাকে।
- sub-VP, EDM-style: hybrid family।
৬ · Reverse SDE — Anderson 1982
Anderson-এর তত্ত্ব — যেকোনো forward SDE-র reverse-time SDE আছে:
$$d\mathbf{x} = \big[f(\mathbf{x}, t) - g(t)^2 \nabla_{\mathbf{x}} \log p_t(\mathbf{x})\big]\,dt + g(t)\,d\bar{\mathbf{w}}$$
যদি আমরা $\nabla_{\mathbf{x}} \log p_t$ (score) জানি — pure noise থেকে data sample করা যায়। DDPM, NCSN — দু'টোই এই reverse SDE-র discretization।
৭ · Probability Flow ODE
একটি গভীর fact: প্রতিটি SDE-র সাথে একটি deterministic ODE আছে যা একই marginal distribution preserve করে:
$$d\mathbf{x} = \Big[f(\mathbf{x}, t) - \frac{1}{2}g(t)^2 \nabla_{\mathbf{x}} \log p_t(\mathbf{x})\Big]\,dt$$
- Stochasticity নেই — pure ODE।
- Adaptive ODE solver (RK45, DPM-Solver) দিয়ে দ্রুত sample।
- Exact likelihood compute করা যায় (instantaneous change of variables)।
- Latent variable $\mathbf{x}_T$ ↔ data $\mathbf{x}_0$ — invertible।
৮ · PyTorch — score network training
import torch, torch.nn as nn, torch.nn.functional as F
# VE-SDE: σ_min < σ < σ_max, geometric
sigma_min, sigma_max = 0.01, 50.0
def marginal_std(t):
"""σ(t) = σ_min · (σ_max/σ_min)^t, t ∈ [0, 1]"""
return sigma_min * (sigma_max / sigma_min) ** t
def dsm_loss(score_net, x0):
B = x0.shape[0]
t = torch.rand(B, device=x0.device) * (1 - 1e-5) + 1e-5
sigma = marginal_std(t).view(-1, 1, 1, 1)
eps = torch.randn_like(x0)
x_t = x0 + sigma * eps
score = score_net(x_t, t) # ≈ -eps/σ
loss = ((score * sigma + eps) ** 2).sum(dim=(1,2,3))
return (loss * sigma.view(-1) ** 2).mean() # λ(σ) = σ²
# Langevin sampling at fixed σ
@torch.no_grad()
def langevin_step(score_net, x, sigma, n_steps=10, eta=2e-5):
for _ in range(n_steps):
score = score_net(x, sigma)
x = x + eta * score + (2 * eta) ** 0.5 * torch.randn_like(x)
return x
ভাবনার প্রশ্ন
প্রতিটি প্রশ্ন নিজে কিছুক্ষণ ভাবুন — তারপর "→ উত্তর" চাপুন।
প্র ০১ "Score" শেখা "likelihood" শেখার চেয়ে সহজ — কেন? Energy-based model (EBM)-এর সাথে কী সংযোগ এবং কেন EBM ছেড়ে score-based model জনপ্রিয় হলো?
Likelihood vs score — generative modeling-এর সবচেয়ে গভীর tension।
Likelihood-এর সমস্যা:
- $p(\mathbf{x}) = \tilde p(\mathbf{x}) / Z$ — partition function $Z$ high-dim-এ intractable।
- $Z = \int \tilde p\,d\mathbf{x}$ — integration over $10^5+$ dim image space।
- VAE: variational lower bound, কিন্তু blurry sample।
- Normalizing flow: invertible architecture দরকার — restrictive।
- Autoregressive: factorization order arbitrary, slow sampling।
Score-এর সুবিধা:
- $\nabla \log p = \nabla \log \tilde p - \nabla \log Z = \nabla \log \tilde p$ — $Z$-নির্ভর নয়!
- যেকোনো network architecture — flow-এর মতো invertible লাগে না।
- Sampling-এর জন্য Langevin/SDE — flexible।
- Multimodal distribution capture করা সহজ।
Energy-based model (EBM) connection:
- EBM: $p(\mathbf{x}) = \exp(-E_\theta(\mathbf{x}))/Z$, $E_\theta$ network।
- Score = $-\nabla E_\theta$ (gradient of energy)।
- Score-based model = EBM-এর gradient-only training।
EBM-এর struggle:
- Training instability: Contrastive Divergence, MCMC sampling — slow & unstable।
- Sample quality: Sample to high-density region difficult।
- Mode coverage: Often miss modes।
- Compute heavy: Each step needs MCMC chain।
Score-based যা সমাধান করল:
- DSM (Vincent 2011): Closed-form ground-truth score — supervised learning। MCMC-র দরকার নেই training-এ।
- Multi-noise scale (Song & Ermon 2019): High-noise-এ score শেখা সহজ — gradually clean। Annealed Langevin।
- SDE framework: Continuous limit elegant, mathematical guarantee।
Modern unification:
- Diffusion ≈ Score-based ≈ EBM (gradient training) — all interconnected।
- Recent EBM revival (Du & Mordatch 2019, JEM) — diffusion technique-এর help।
- Flow Matching (Lipman 2023): vector field directly শেখা, score-এর alternative — কিন্তু same family।
Practical consequence:
- Today সব generation (image, audio, video) score/diffusion-এ চলেছে।
- EBM মূলত theoretical interest, niche applications।
- Hybrid approach — diffusion + EBM regularization — research direction।
মূল উপলব্ধি: Generative modeling-এ "intractable normalizing constant" ছিল ৩০ বছরের bottleneck। Score idea — tractable structure exploit করে gradient-only learn করা — এই bottleneck ভাঙল। আজকের সব GenAI-এর mathematical foundation এটিই।
প্র ০২ VP-SDE ও VE-SDE — দুটোর difference কী, কখন কোনটি use করব? EDM (Karras et al. 2022) "preconditioning" trick কেন এত effective?
SDE choice diffusion-এর core design decision। Subtle কিন্তু sample quality-এ বড় পার্থক্য।
VP-SDE (Variance Preserving):
- $d\mathbf{x} = -\frac{1}{2}\beta(t)\mathbf{x}\,dt + \sqrt{\beta(t)}\,d\mathbf{w}$।
- Mean shrinks toward 0, variance approaches identity।
- $T \to \infty$-এ $\mathbf{x}_T \sim \mathcal{N}(0, \mathbf{I})$ — bounded।
- DDPM-এর continuous limit।
- Numerically stable — bounded variance।
VE-SDE (Variance Exploding):
- $d\mathbf{x} = \sqrt{d[\sigma^2(t)]/dt}\,d\mathbf{w}$।
- Mean preserved, variance explodes ($\sigma \to \infty$)।
- $\mathbf{x}_T \sim \mathbf{x}_0 + \mathcal{N}(0, \sigma_{max}^2 \mathbf{I})$ — large variance Gaussian।
- NCSN/SMLD-এর continuous limit।
- High-resolution image-এ ভাল — mode coverage strong।
Comparison practical:
- VP নিচু-resolution-এ marginally better, training simpler।
- VE high-resolution image-এ FID better।
- VE-তে $\sigma$ scale বড় — input scaling carefully করতে হয়।
- VP-এ $\beta$ schedule tuning critical।
EDM (Elucidating Diffusion Models, Karras et al. 2022):
- $\sigma$-কে সরাসরি parameterize, $t$ implicit।
- Continuous-time formulation: $\mathbf{x}_\sigma = \mathbf{x}_0 + \sigma \boldsymbol\epsilon$ — VE-এর sub-case।
- Training $\sigma$ log-normal sampled, $P_{mean} = -1.2, P_{std} = 1.2$।
- Heun's 2nd-order ODE solver — 35 step-এ FID 1.79 ImageNet (!)।
EDM preconditioning:
- $D_\theta(\mathbf{x}, \sigma) = c_{skip}(\sigma) \mathbf{x} + c_{out}(\sigma) F_\theta(c_{in}(\sigma) \mathbf{x}, c_{noise}(\sigma))$।
- Network input/output scale balanced — সব $\sigma$-তে similar magnitude।
- $c_{skip}, c_{out}, c_{in}$ — derived from optimal Tweedie's formula।
- Result: training drastically stable, faster convergence।
কেন এত effective:
- Network output unconditioned magnitude wildly varies across $\sigma$।
- Without preconditioning — gradient mostly from one $\sigma$ regime।
- EDM normalizes — uniform learning, all noise levels।
- Mathematically derived — no hand-tuning।
২০২৫ landscape:
- EDM2 (Karras 2024): magnitude-preserving network, even better।
- Flow Matching (Lipman 2023): straight paths, OT-inspired।
- Rectified Flow (Liu 2022): used in SD3, Flux।
- সব এই unified perspective-এর descendant।
Practical recommendation:
- New project — EDM/EDM2 framework দিয়ে শুরু করুন।
- Pre-trained model ব্যবহার — SD3 (rectified flow)/SDXL (VP)।
- VP/VE choice আজ legacy — modern frameworks unified।
মূল উপলব্ধি: Theory-empiricism interplay — VP/VE শুধু derivation start point ছিল। EDM প্রমাণ করল proper preconditioning + sigma-parameterization sufficient। Math এবং engineering-এর সমন্বয়ই SOTA তৈরি করে।
প্র ০৩ Probability Flow ODE — deterministic mapping noise ↔ data। এটি কেন এত গুরুত্বপূর্ণ এবং DDIM-এর সাথে কী সম্পর্ক? Latent space arithmetic ও interpolation-এ কীভাবে use হয়?
Probability Flow ODE (PF-ODE) — diffusion-এর একটি গভীর mathematical insight।
Key claim (Song et al. 2021): SDE-এর সাথে একটি deterministic ODE আছে যা একই marginal distribution $p_t(\mathbf{x})$ produce করে।
কেন গুরুত্বপূর্ণ:
- Bijective mapping: $\mathbf{x}_T \leftrightarrow \mathbf{x}_0$ — same noise → same image। Reproducibility।
- Likelihood compute: Instantaneous change of variables — exact $\log p_0(\mathbf{x}_0)$ পাওয়া যায়।
- Adaptive solver: RK45, DPM-Solver — high-order, ১০-৫০ step যথেষ্ট।
- Latent encoding: Real image $\mathbf{x}_0$ → noise $\mathbf{x}_T$ (forward ODE) → manipulate → decode।
DDIM connection:
- DDIM (Song et al. 2020) — discrete-time non-Markovian process।
- $\eta = 0$-এ DDIM deterministic — exactly PF-ODE-এর Euler discretization।
- $\eta = 1$ — DDPM-এর equivalent।
- $\eta \in (0, 1)$ — interpolated stochasticity।
- 50-step DDIM ≈ PF-ODE Euler 50-step।
Latent space arithmetic:
- SDEdit (Meng et al. 2021): Real image → noise (partial forward) → reverse with new prompt → edited image।
- Image inversion: $\mathbf{x}_0$ → $\mathbf{x}_T$ via PF-ODE → guarantee that reverse → $\mathbf{x}_0$।
- Null-text inversion (Mokady 2022): SDXL-এ exact reconstruction trick।
- Prompt-to-prompt editing: Same latent, different prompt — controlled edit।
Interpolation:
- Two image: $\mathbf{x}_0^A, \mathbf{x}_0^B$ → invert → $\mathbf{x}_T^A, \mathbf{x}_T^B$।
- Spherical linear interpolation (slerp): $\mathbf{x}_T(\alpha) = \text{slerp}(\mathbf{x}_T^A, \mathbf{x}_T^B, \alpha)$।
- Reverse → smooth morph between two images।
- Linear interpolation Gaussian-এ statistically wrong — slerp ব্যবহার করুন।
Practical applications:
- Stable Diffusion img2img: Strength parameter — কতদূর forward ODE → reverse with new prompt।
- Video interpolation: Frame-to-frame smooth latent path।
- Style transfer: Content image-এর latent + style prompt = stylized।
- Animation: Latent space-এ trajectory → temporally consistent video।
Limitations:
- Inversion accuracy CFG (classifier-free guidance)-এ কম — exact reconstruction কঠিন।
- ODE solver error accumulates — high $w$-এ drift।
- Truncation: $T = \infty$ ideal, practical $T \approx 1000$ approximation।
২০২৪-২৫ developments:
- Consistency Models (Song 2023): one-step generation via PF-ODE distillation।
- Rectified Flow: straight-path PF-ODE — SD3, Flux।
- Latent Consistency Models — 2-4 step inference।
মূল উপলব্ধি: PF-ODE প্রমাণ করে diffusion শুধু stochastic sampling নয় — একটি deterministic geometric mapping। এই view থেকে editing, inversion, fast sampling, distillation সব এসেছে। Theory-র elegance practical applications-কে enable করে।
প্র ০৪ Score matching বনাম Flow Matching (Lipman 2023)—২০২৪-২৫-এ flow matching কেন SD3, Flux-এ adopted? Mathematical ও practical advantage কী?
Flow Matching — diffusion-এর next generation, ২০২২-২৪-এ rapid adoption।
Score matching summary:
- Loss: $\|\nabla \log p_t - s_\theta\|^2$ (DSM-এ ε-loss equivalent)।
- SDE/ODE-এ noise schedule নির্দিষ্ট।
- Path data → noise determined by $\beta(t)$ schedule।
Flow Matching idea (Lipman, Chen, Lipman 2023):
- Probability path $p_t(\mathbf{x})$ — data ($t=0$) থেকে noise ($t=1$) — design choice।
- Vector field $v_t(\mathbf{x})$ এই path generate করে: $dp/dt + \nabla \cdot (p v) = 0$।
- Network $v_\theta(\mathbf{x}, t)$ — সরাসরি vector field শেখে।
- Loss: $\|v_\theta - v_t^{target}\|^2$।
Conditional Flow Matching trick:
- Per-sample path: $\mathbf{x}_t = (1-t) \mathbf{x}_0 + t \mathbf{x}_1$ (linear interp data ↔ noise)।
- Conditional vector field: $v_t = \mathbf{x}_1 - \mathbf{x}_0$ (constant!)।
- Marginal vector field expectation — score-based equivalent।
- Training: $\|\mathbf{x}_1 - \mathbf{x}_0 - v_\theta(\mathbf{x}_t, t)\|^2$ — straight path।
Rectified Flow (Liu et al. 2022):
- Same as Conditional FM — straight-line path।
- "Reflow" iteration — straighten further।
- 1-step generation possible after distillation।
Mathematical advantages:
- Path flexibility: Any continuous path চয়েস। Optimal Transport path possible।
- Straight paths: ODE solver-এর জন্য easier — fewer steps needed।
- No SDE complexity: Pure ODE formulation — simpler theory।
- Better mode coverage: OT paths preserve geometry।
Practical advantages:
- Faster sampling: Straight path → fewer ODE steps। 4-step generation feasible।
- Better high-resolution: SD3 quality jump partly FM-related।
- Unified framework: Image, video, audio — same FM training।
- Distillation friendly: SD3-Turbo, Flux-Schnell — fast inference variants।
SD3 (Stability AI, March 2024):
- MMDiT architecture + Rectified Flow training।
- Logit-normal $t$ sampling — high-resolution-এ better signal।
- Compared to SDXL: better text rendering, fewer artifacts।
Flux.1 (Black Forest Labs, Aug 2024):
- Original SD authors-এর startup।
- Flow matching + 12B parameters — quality SOTA, open weights।
- Schnell variant 1-4 step inference।
Score matching vs Flow Matching trade-offs:
- SM: Massive ecosystem (SD1.5, SDXL), well-understood, lots of LoRA/ControlNet।
- FM: Faster, cleaner theory, growing ecosystem, future direction।
- Practical: ২০২৫-এ both used, FM-এর momentum বেশি।
Open questions:
- Optimal Transport path practical-এ কতটুকু ভাল? Linear path simpler & sufficient?
- Discrete data (text) FM extension কতটুকু effective?
- Video-এ FM vs SM — long-horizon-এ কী better?
মূল উপলব্ধি: Score matching → Flow matching gradual generalization। Each abstraction level টেকনিক simpler, more flexible। DL-এ pattern repeated — initial complex formulation → cleaner reformulation → faster progress। আগামী ৫ বছরে আরো generalization আসবে।
অনুশীলন
-
Score derivation: $p(\mathbf{x}) = \mathcal{N}(\mathbf{x}; \boldsymbol\mu, \sigma^2 \mathbf{I})$। $\nabla_{\mathbf{x}} \log p(\mathbf{x})$ derive করুন।
$\log p = -\frac{1}{2\sigma^2}\|\mathbf{x} - \boldsymbol\mu\|^2 + \text{const}$।
$\nabla_{\mathbf{x}} \log p = -(\mathbf{x} - \boldsymbol\mu)/\sigma^2$।
মানে — score বিন্দু থেকে mean-এর দিকে নির্দেশ করে, $1/\sigma^2$-এ scaled।
-
DDPM-DSM equivalence: দেখান কেন DDPM-এর $\epsilon$-loss DSM-এর সমতুল্য (scaling বাদে)।
$q(\mathbf{x}_t \mid \mathbf{x}_0) = \mathcal{N}(\sqrt{\bar\alpha_t}\mathbf{x}_0, (1-\bar\alpha_t)\mathbf{I})$।
$\nabla_{\mathbf{x}_t} \log q = -(\mathbf{x}_t - \sqrt{\bar\alpha_t}\mathbf{x}_0)/(1-\bar\alpha_t) = -\boldsymbol\epsilon/\sqrt{1-\bar\alpha_t}$।
তাই $s_\theta(\mathbf{x}_t, t) = -\epsilon_\theta(\mathbf{x}_t, t)/\sqrt{1-\bar\alpha_t}$ — score ও noise prediction equivalent।
-
Reverse SDE: VP-SDE-এর reverse SDE লিখুন।
Forward: $d\mathbf{x} = -\frac{1}{2}\beta(t)\mathbf{x}\,dt + \sqrt{\beta(t)}\,d\mathbf{w}$।
Reverse: $d\mathbf{x} = \big[-\frac{1}{2}\beta(t)\mathbf{x} - \beta(t)\nabla_{\mathbf{x}} \log p_t(\mathbf{x})\big]\,dt + \sqrt{\beta(t)}\,d\bar{\mathbf{w}}$।
Network-এ score replace করলে DDPM-এর reverse process পান।
আরও পড়ুন · ABCL TECH-এ আপনার পরবর্তী পদক্ষেপ
- পাঠ ১৫ · DDIM — দ্রুত sampling পরবর্তী পাঠ PF-ODE-এর discrete version — 50 step-এ ভাল sample।
- পাঠ ১৩ · DDPM আগের পাঠ Discrete-time formulation — score-এর সাথে link।
- পাঠ ১৬ · Latent Diffusion এই পাঠের সাথে সম্পর্কিত Score-based model latent space-এ apply — Stable Diffusion-এর ভিত্তি।
- সব AI Courses দেখুন ABCL TECH Python, ML, DL, NLP, CV, GenAI, RL, MLOps — সব AI কোর্স একসাথে।