পাঠ ১০ · ২৮-এর মধ্যে · মডিউল ২
Home / AI Courses / জেনারেটিভ AI / WGAN ও mode collapse

Mode collapse ও WGAN — Earth Mover-এর গণিত

WGAN & mode collapse
৭ মিনিট পড়া মধ্যম · Intermediate PyTorch কোডসহ

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

  • Mode collapse কী, কেন ঘটে — saddle point ও weak feedback
  • JSD-এর pathology — disjoint support-এ vanishing gradient
  • Wasserstein distance — দু'টি distribution মেলানোর "earth-moving" cost
  • WGAN-GP — gradient penalty দিয়ে Lipschitz enforce; PyTorch implementation

১ · Mode collapse — সমস্যা

Real data-তে অনেক mode থাকে — MNIST-এ ১০টি digit, CelebA-তে অসংখ্য face। Mode collapseMode collapseGAN-এর কুখ্যাত failure mode — generator কয়েকটি sample-এই আটকে যায়, data-র full diversity capture করে না। কারণ minimax saddle point-এ generator একটি "safe" sample বাছে যা discriminator-কে fool করে। মানে generator শুধু একটি বা কয়েকটি mode-ই output দেয়।

MNIST GAN-এ mode collapse মানে — generator শুধু "৩" বা শুধু "৭" বানায়। FID ভালো দেখাতে পারে, কিন্তু diversity শূন্য।

কেন ঘটে?

১) Generator একটি "safe" sample বাছে যা সবসময় discriminator-কে ঠকায়।
২) Discriminator updated হলে generator অন্য একটি safe mode-এ shift।
৩) এই "whack-a-mole" oscillation — কখনো full distribution learn হয় না।
৪) Saddle point optimization: minimax-এর Nash equilibrium guarantee নেই।

ভাবুন একজন জালিয়াত — পুলিশ ৫০০ টাকার নকল ধরছে। জালিয়াত শুধু ১০০ টাকার নকল বানাতে শুরু করে — পুলিশ adapt না করা পর্যন্ত। তারপর পুলিশ ১০০ টাকার নকল ধরা শিখলে, জালিয়াত ১০০০-এ যায়। সবসময় একটি single denomination — কখনো diversity না।

২ · JSD-এর pathology

Goodfellow-র GAN আসলে Jensen-Shannon divergence minimize করে। সমস্যা — যদি $p_g$ ও $p_{\text{data}}$-এর support disjoint হয়:

$$\mathrm{JSD}(p_g \| p_{\text{data}}) = \log 2 \quad \text{(constant)}$$

Constant function-এর gradient = 0। Generator কোন direction-এ যাবে — কোনো signal নেই। Real-world image data low-dim manifold-এ থাকে; random initialization-এ generator-এর support অন্য manifold-এ — overlap সম্ভাবনা ০।

৩ · Wasserstein distance — Earth Mover's

Wasserstein-1 distanceWasserstein-1 / Earth Mover's distanceOptimal transport theory-এর central concept। Monge ১৭৮১; Kantorovich ১৯৪২ formal version। Arjovsky ২০১৭-এ deep learning-এ আনলেন।:

$$W(p_r, p_g) = \inf_{\gamma \in \Pi(p_r, p_g)} \mathbb{E}_{(x, y) \sim \gamma} \big[\|x - y\|\big]$$

Intuition: $p_g$-এর "মাটি"-কে $p_r$-এর shape-এ রূপান্তরিত করতে — প্রতিটি কণা সরানোর "কাজ" (mass × distance)-এর সর্বনিম্ন total। তাই "Earth Mover's"।

JSD থেকে কেন superior:

  • Disjoint support-এও finite, smoothly decreasing — gradient meaningful।
  • সবসময় defined; KL/JSD-র মতো singularity না।
  • দু'টি distribution-এর সঠিক geometric দূরত্ব।

৪ · Kantorovich-Rubinstein duality

Wasserstein-এর সরাসরি computation কঠিন। Kantorovich-Rubinstein duality দেয়:

$$W(p_r, p_g) = \sup_{\|f\|_L \leq 1} \mathbb{E}_{x \sim p_r}[f(x)] - \mathbb{E}_{x \sim p_g}[f(x)]$$

যেখানে supremum সব 1-LipschitzLipschitz function$\|f(x) - f(y)\| \leq K \|x - y\|$ যেখানে $K$ = Lipschitz constant। Bounded slope। Calculus-এ continuous derivative-এর smooth analogue। function $f$-এর উপর। GAN setting-এ এই $f$ = "critic" (discriminator-এর analogue, কিন্তু probability output না, scalar)।

৫ · WGAN — Lipschitz enforcing

Critic $f_w$ neural network — Lipschitz constraint কীভাবে enforce করব?

Original WGAN (Arjovsky et al., ২০১৭): weight clipping। সব $w \in [-c, c]$ (যেমন $c = 0.01$)। Crude কিন্তু কাজ করে।

সমস্যা: clipping crude — capacity restrict, "pathological behavior" — Gulrajani et al. (২০১৭) দেখালেন।

৬ · WGAN-GP — gradient penalty

WGAN-GP (Gulrajani et al., ২০১৭) — Lipschitz-এর gradient definition থেকে: $\|\nabla_x f(x)\| \leq 1$ everywhere। Soft constraint হিসেবে penalty:

$$\mathcal{L}_{\text{GP}} = \lambda \, \mathbb{E}_{\hat{x} \sim p_{\hat{x}}} \big[ (\|\nabla_{\hat{x}} f(\hat{x})\|_2 - 1)^2 \big]$$

যেখানে $\hat{x} = \alpha x + (1-\alpha) G(z)$, $\alpha \sim \mathrm{Uniform}[0, 1]$ — real ও fake-এর interpolation। $\lambda = 10$ default।

পূর্ণ WGAN-GP loss:

$$\mathcal{L}_D = \mathbb{E}_g[f(G(z))] - \mathbb{E}_r[f(x)] + \lambda \cdot \mathcal{L}_{\text{GP}}, \qquad \mathcal{L}_G = -\mathbb{E}_g[f(G(z))]$$

Mode collapse বনাম full coverage (WGAN) Mode collapse Vanilla GAN — JSD pathology 3 7 9 2 Real distribution (4 mode) 3 3 3 G output: শুধু "3" Full coverage WGAN-GP — Wasserstein gradient 3 7 9 2 Real distribution 3 7 9 2 G output: সব mode
বাঁয়ে — vanilla GAN-এ mode collapse: একটি mode-এ আটকা। ডানে — WGAN-GP-তে full coverage: distribution-এর সব mode generate।

৭ · PyTorch — WGAN-GP critic step

Python · PyTorch
def gradient_penalty(critic, real, fake, device):
    bs = real.size(0)
    alpha = torch.rand(bs, 1, 1, 1, device=device)
    interp = alpha * real + (1 - alpha) * fake
    interp.requires_grad_(True)
    d_interp = critic(interp)
    grads = torch.autograd.grad(
        outputs=d_interp, inputs=interp,
        grad_outputs=torch.ones_like(d_interp),
        create_graph=True, retain_graph=True
    )[0]
    grads = grads.view(bs, -1)
    gp = ((grads.norm(2, dim=1) - 1) ** 2).mean()
    return gp

# critic step
fake = G(z).detach()
loss_C = critic(fake).mean() - critic(real).mean() \
       + 10.0 * gradient_penalty(critic, real, fake, device)
opt_C.zero_grad(); loss_C.backward(); opt_C.step()

# generator step (every 5 critic steps)
fake = G(z)
loss_G = -critic(fake).mean()
opt_G.zero_grad(); loss_G.backward(); opt_G.step()

    
Critic-এর output Sigmoid-বিহীন — scalar। Generator step critic-এর every $5$ step-এ একবার (Gulrajani-এর পেপার অনুসরণ করে)। BatchNorm critic-এ ব্যবহার করবেন না — Layer Norm বা Instance Norm।

৮ · মূল্যায়ন — diagnostic

Mode collapse detect করার ব্যবহারিক উপায়:

  • Sample diversity: ১০,০০০ sample generate, pairwise cosine similarity histogram। Sharp peak মানে collapse।
  • Inception Score (IS): Salimans et al. (২০১৬) — class diversity প্লাস confidence।
  • FID (Heusel et al., ২০১৭) — real ও generated feature distribution-এর Fréchet distance। Standard metric।
  • Precision-Recall for generative models (Sajjadi et al., ২০১৮) — quality (precision) vs coverage (recall) আলাদা।
WGAN-GP সব সমস্যার সমাধান না — training এখনো অস্থির। Spectral normalization (Miyato, ২০১৮), R1 regularization (Mescheder, ২০১৮) — modern GAN-এর backbone। সব হারিয়ে gেলে diffusion-এ চলে যান — সেখানে mode collapse নেই।

৯ · WGAN-এর উত্তরাধিকার

  • BigGAN — class-conditional ImageNet, hinge loss + spectral norm।
  • StyleGAN2 — non-saturating + R1 regularization, WGAN-GP-এর variant।
  • Optimal Transport — diffusion model-এও deep connection (Schrödinger bridge, OT-CFM)।
  • Bangladesh: bKash transaction synthetic generation — diversity critical।

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

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

প্র ০১ Wasserstein distance কেন "earth mover's"? Transport plan-এর intuition কী, এবং discrete vs continuous case-এ আলাদা কেন?

Wasserstein distance বা Earth Mover's distance (EMD) — optimal transport theory-এর central object। Monge ১৭৮১-তে formulated, Kantorovich ১৯৪২-এ tractable rewrite করেছেন (১৯৭৫-এ Nobel-এ অংশ পেয়েছেন তিনি)।

Intuitive picture:

  • $p_r$ একটি মাটির গাদার আকৃতি; $p_g$ আরেকটি।
  • $p_g$-কে ঠিক $p_r$-এর shape-এ রূপান্তরিত করতে চাই।
  • প্রতিটি "মাটির কণা"-কে কোথা থেকে কোথায় সরালে — total work (mass × distance) সর্বনিম্ন?
  • সেই minimum total work = $W(p_r, p_g)$।

Transport plan $\gamma$:

  • $\gamma(x, y)$ — $x$ থেকে $y$-তে কত mass পাঠাচ্ছি।
  • Marginal constraint: $\int \gamma(x, y) \, dy = p_r(x)$, $\int \gamma(x, y) \, dx = p_g(y)$।
  • "Coupling" — joint distribution যার দু'টো marginal $p_r, p_g$।
  • সব valid coupling-এর মধ্যে cheapest খুঁজি।

Discrete case:

  • $N$ source point, $M$ target point।
  • Linear programming problem: minimize $\sum_{ij} \gamma_{ij} c_{ij}$ s.t. row/col sum constraint।
  • Sinkhorn algorithm (Cuturi, ২০১৩) — entropy-regularized, fast।
  • $O(N^3)$ exact, $O(N^2 \log N / \epsilon^2)$ approximate।

Continuous case:

  • Infinite-dim LP — intractable directly।
  • Kantorovich-Rubinstein duality save: $W = \sup_{\|f\|_L \leq 1} \mathbb{E}_r[f] - \mathbb{E}_g[f]$।
  • Single function $f$ optimize করো — neural network দিয়ে। এটাই WGAN-এর critic।
  • Lipschitz constraint enforce-এর প্রয়োজন।

Why "1"-Wasserstein:

  • $W_p$ family — cost = $\|x-y\|^p$।
  • $p = 1$ — most popular, KR duality clean।
  • $p = 2$ — physics-relevant (kinetic energy interpretation)।
  • $p \to \infty$ — Hausdorff-like।

Practical computation:

  • POT library (Python) — Sinkhorn, EMD।
  • WGAN-এ critic = neural approximate of optimal $f$।
  • Sliced Wasserstein — high-dim projection trick।

আধুনিক ব্যবহার:

  • Domain adaptation — source ও target distribution match।
  • Diffusion model — Schrödinger bridge, OT flow matching।
  • Neural style transfer — content-style distance।
  • Single-cell genomics — cell trajectory inference।

মূল উপলব্ধি: Earth Mover's distance শুধু GAN-এর tool না — modern AI-র কেন্দ্রীয় geometric notion। দু'টি distribution-এর মধ্যে "কতটা দূর" — এই প্রশ্নের সবচেয়ে natural উত্তর।

প্র ০২ WGAN-এর weight clipping কেন pathological? Gradient penalty কেন superior, এবং spectral normalization কীভাবে এই দু'টোর alternative?

Lipschitz constraint enforce করার তিনটি প্রধান approach — প্রতিটিরই trade-off আছে। আজকের best practice spectral norm + R1, কিন্তু সব technique বুঝা দরকার।

Weight clipping (original WGAN):

  • Recipe: প্রতিটি $w \in [-c, c]$, $c = 0.01$।
  • Lipschitz constant $\leq c \cdot $depth — কিন্তু crude bound।
  • Pathology Gulrajani et al. ২০১৭-এ:
  • (ক) সব weight clip-এর extreme value-এ — capacity waste।
  • (খ) Critic effectively simple function বানায় — complex distribution capture কঠিন।
  • (গ) Vanishing/exploding gradient — depth-এর সাথে problem।

Gradient penalty (WGAN-GP):

  • Soft constraint: $\|\nabla_x f\| \approx 1$ on interpolated point।
  • Two-sided penalty $(\|\nabla\| - 1)^2$ — exactly 1 হতে চায়।
  • সুবিধা: smoother training, capacity unrestricted।
  • সমস্যা: extra forward+backward pass per critic step — slow।
  • BatchNorm critic-এ break — Layer/Instance Norm ব্যবহার।
  • Hyperparameter $\lambda = 10$ — sometimes domain-specific tuning।

Spectral normalization (Miyato et al., ২০১৮):

  • প্রতিটি weight matrix $W$ কে তার spectral norm দিয়ে normalize: $\hat{W} = W / \sigma_{\max}(W)$।
  • Power iteration একটি step — efficient।
  • Per-layer Lipschitz $\leq 1$ → entire critic Lipschitz $\leq 1$।
  • সুবিধা: no extra forward pass, simple, BatchNorm-compatible।
  • সমস্যা: spectral norm conservative bound — tight না।

R1 regularization (Mescheder et al., ২০১৮):

  • Real data-এ gradient penalty: $\frac{\lambda}{2} \mathbb{E}_r[\|\nabla_x f(x)\|^2]$।
  • "Zero-centered" — Lipschitz approximate, very stable।
  • StyleGAN2 default।

Comparison summary:

MethodSpeedStabilityCapacity
ClippingFastMediumRestricted
WGAN-GPSlowHighFull
SNFastHighConservative
R1MediumVery highFull

আধুনিক best practice:

  • BigGAN: spectral norm everywhere।
  • StyleGAN2/3: R1 + non-saturating loss।
  • Diffusion: কোনোটাই লাগে না — different paradigm।

মূল উপলব্ধি: Lipschitz constraint enforce করা একটি art — multiple valid approach, প্রতিটি trade-off। Spectral norm + R1 আজকের de facto, কিন্তু তোমার domain-specific need অনুসারে বাছাই করো।

প্র ০৩ Mode collapse detect করতে FID যথেষ্ট কেন না? "Precision-recall for generative models" কী, এবং বাস্তব dataset evaluation-এ এর ভূমিকা?

Generative model evaluation generative AI-র সবচেয়ে কঠিন প্রশ্ন। FID single number-এ অনেক aspect mix করে — diagnostic-এ insufficient।

FID (Heusel et al., ২০১৭):

  • Real ও generated image-কে Inception-V3 feature space-এ project।
  • দু'টি multi-variate Gaussian fit, Fréchet distance compute।
  • $\mathrm{FID} = \|\mu_r - \mu_g\|^2 + \mathrm{Tr}(\Sigma_r + \Sigma_g - 2\sqrt{\Sigma_r \Sigma_g})$।
  • Lower better।

FID-এর সমস্যা:

  • Single number: quality vs coverage আলাদা না। একটি model perfect quality কিন্তু low coverage হতে পারে — তবু moderate FID।
  • Inception bias: ImageNet-এ pretrained — non-natural domain (medical, satellite) এ unreliable।
  • Sample size sensitive: ১০K vs ৫০K image FID আলাদা।
  • Adversarial gameable: একটি network FID-কে "target" করে train করলে — বাস্তব quality না বাড়িয়েই FID কমে।

Precision-Recall for generative models (Sajjadi et al., ২০১৮):

  • Two metrics আলাদা — quality (precision) ও diversity (recall)।
  • Precision: generated sample-এর কত % "real-looking"?
  • Recall: real distribution-এর কত % generated cover করে?
  • Mode collapse → low recall, high precision (sample সব ভাল কিন্তু variety নেই)।
  • Blurry diverse output → low precision, high recall।

Computation:

  • Real ও generated feature embedding (Inception/CLIP)।
  • Real manifold = real points-এর k-NN ball-এর union।
  • Precision: generated points-এর কত % real manifold-এ।
  • Recall: real points-এর কত % generated manifold-এ।

Improved P-R (Kynkäänniemi et al., ২০১৯):

  • Density ও Coverage — outlier-এর প্রতি robust।
  • Modern paper-এ "FID + Precision + Recall + Density + Coverage" report হয়।

Mode collapse-specific diagnostics:

  • Coverage histogram: ১০K sample, pairwise distance distribution। Tight peak = collapse।
  • Class distribution: conditional GAN-এ class ratio check।
  • k-NN to training: generated → training image-এর nearest neighbor। সব same neighbor হলে collapse।
  • Visual inspection: ৬৪টি sample grid plot — quick eye-check।
  • Number of statistically distinct samples (Birthday paradox test, Arora & Zhang, ২০১৭)।

Bangladesh dataset-এর জন্য:

  • Bangla calligraphy GAN — character class distribution check critical। সব "অ" বানালে evaluate ব্যর্থ।
  • Bangla face GAN — skin tone diversity, age diversity ম্যানুয়াল evaluate।
  • Native speaker reviewer panel — quantitative metric-এর সাথে।

আধুনিক metric:

  • CLIP-FID — CLIP feature, more semantic।
  • HumanEval — actual user study।
  • VQA-based — "is this image real?" generate প্রশ্ন।

মূল উপলব্ধি: Single metric-এ ভরসা না করে multiple complementary metric report করুন — এবং সবচেয়ে গুরুত্বপূর্ণ — visual sample inspect করুন। Number-এ deceive হওয়া সহজ।

প্র ০৪ Diffusion model-এ কেন mode collapse নেই, কিন্তু GAN-এ আছে? কোন structural difference এই asymmetry-র কারণ?

Mode collapse GAN-এর জন্য পরিচিত সমস্যা — diffusion-এ অপ্রাসঙ্গিক। এই asymmetry training objective-এর fundamental difference থেকে আসে।

GAN — কেন mode collapse:

  • Minimax saddle point optimization — Nash equilibrium guarantee নেই।
  • Generator একটি "winning" sample বাছলে discriminator-কে fool করে → কোনো penalty নেই sample diversity-র অভাবে।
  • "Adversarial gaming" — discriminator একটি mode-এ adapt হলে, generator অন্য mode-এ shift। Whack-a-mole।
  • Likelihood না — coverage-এর কোনো explicit measure নেই।
  • Training data-এর কাছে কতটা match — discriminator-এর judgement, যা imperfect।

Diffusion — কেন mode collapse নেই:

  • Likelihood-based objective: diffusion effectively maximizes ELBO/data likelihood। Coverage explicit।
  • Forward process fixed: data → noise — কোনো "adversary" না।
  • Score matching/denoising objective: $\mathbb{E}_{x \sim p_{\text{data}}}[\|\epsilon_\theta - \epsilon\|^2]$ — সব training point equally penalize।
  • No saddle point: single objective minimize — convex-ish neighborhood।
  • Stochasticity in sampling: প্রতিটি sample ভিন্ন noise trajectory — diverse output natural।
  • Mode coverage proven: Score-based diffusion provably learns full distribution under regularity।

Mathematical perspective:

  • GAN: $\min_G \max_D V(D, G)$ — saddle point।
  • Diffusion: $\min_\theta \mathbb{E}[\|\epsilon_\theta - \epsilon\|^2]$ — pure minimization।
  • Saddle point hard to converge; pure minimization easy।

Trade-off: কেন তবে GAN আজও আছে?

  • Diffusion inference slow — ২০-৫০ steps। GAN single forward।
  • Diffusion training stable but expensive — lots of timesteps।
  • GAN small model, mobile deployment সম্ভব।
  • Latent space structure — GAN-এর (StyleGAN-এর $\mathcal{W}$) prefer-able কিছু application-এ।

Hybrid approaches:

  • Adversarial Diffusion Distillation (Sauer et al., ২০২৩): diffusion-কে GAN-style discriminator দিয়ে distill — fast inference।
  • Consistency models (Song et al., ২০২৩): single-step diffusion।
  • GigaGAN: text-to-image GAN return — diffusion-এর কাছাকাছি।

Theoretical insight:

  • Diffusion-এর forward process — Wasserstein flow।
  • WGAN-GP-এর Wasserstein gradient idea diffusion-এ "natural" — Schrödinger bridge, OT flow matching।
  • একটা সেন্সে — diffusion = "infinitely deep WGAN"।

Practical lesson:

  • "Mode collapse" এড়াতে চান → diffusion।
  • Speed চাই → GAN (with mode collapse mitigation)।
  • সর্বোত্তম quality + flexibility → latent diffusion।

মূল উপলব্ধি: Likelihood-based training-এর "natural coverage" property generative AI-র subtle কিন্তু important advantage। Mode collapse-এর সমস্যা GAN-এর engineering frustration ছাড়িয়ে — fundamental optimization-গণিতের সমস্যা। Diffusion-এর জনপ্রিয়তার এটি একটি প্রধান কারণ।

অনুশীলন

  1. হাতে-কলমে: দু'টি 1-D distribution: $p_r$ uniform on $[0, 1]$, $p_g$ uniform on $[2, 3]$। JSD ও $W_1$ কত?
    • JSD: support disjoint → JSD = $\log 2 \approx 0.693$ (max value)।
    • $W_1$: প্রতিটি কণা ২ unit সরাতে হবে → $W_1 = 2$।
    • Distribution closer হলে $W_1$ smoothly decrease, JSD constant। এটাই WGAN-এর গাণিতিক সুবিধা।
  2. কোডে চেষ্টা: উপরের WGAN-GP-তে $\lambda$ (gradient penalty weight) ০, ১, ১০, ১০০ বাছাই করে training behavior দেখুন।
    • $\lambda = 0$: critic Lipschitz না — training divergent বা mode collapse।
    • $\lambda = 1$: weak constraint — partially এ stable।
    • $\lambda = 10$: standard — best balance।
    • $\lambda = 100$: over-constraint — critic capacity limited, slow learning।

    $\lambda = 10$ Gulrajani-র paper-এর recommendation, এবং অধিকাংশ dataset-এ কাজ করে।

  3. ভাবুন: bKash-এর synthetic transaction generator train করছেন। কী mode-এ collapse হতে পারে, কীভাবে detect ও prevent করবেন?
    • Mode collapse risk: একই amount range, একই geographic pattern, একই time-of-day।
    • Detect: feature distribution histogram (amount, recipient type, time)।
    • Prevent: WGAN-GP, conditional generation (class-conditional on transaction type)।
    • Evaluate: native domain expert (compliance team) review; downstream fraud detector accuracy।
    • Privacy: differential privacy training; nearest-neighbor distance check (memorization)।

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

কোড রানার কাজ না করলে? ব্রাউজারে কাজ না করলে Google Colab ব্যবহার করুন — Google-এর ফ্রি অনলাইন Python পরিবেশ, শুধু Gmail অ্যাকাউন্ট লাগে।
পূর্ববর্তী পাঠ
পাঠ ৯ · DCGAN ও StyleGAN