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

VAE — ELBO ও reparameterization trick

Variational autoencoders
৮ মিনিট পড়া মধ্যম · Intermediate PyTorch কোডসহ

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

  • VAE-র probabilistic motivation — কেন stochastic encoder
  • ELBO derivation — log-likelihood-এর lower bound
  • Reparameterization trick — backprop সম্ভব করার চাবি
  • PyTorch দিয়ে MNIST VAE; posterior collapse, β-VAE-র ভূমিকা

১ · Plain AE-র সমস্যা

গত পাঠে আমরা দেখলাম — plain autoencoder reconstruction-এ ভাল, কিন্তু generation-এ অক্ষম। কারণ training-এ যে $z$ point-গুলো এসেছে, latent space-এ তারা একটি অজানা distribution তৈরি করে — random $z \sim \mathcal{N}(0, I)$ নিলে decoder চিনতে পারে না।

সমাধান: এমনভাবে train করো যাতে latent distribution একটি জানা prior (যেমন $\mathcal{N}(0, I)$)-এর কাছাকাছি থাকে। তাহলে generation-এ আমরা সেই prior থেকে sample নিতে পারি। এটাই VAEVariational AutoencoderKingma ও Welling (২০১৩) এবং Rezende et al. (২০১৪)-র যুগান্তকারী কাজ। Bayesian inference + neural network-এর মেলবন্ধন। আজকের diffusion model-এর pre-cursor।।

VAE-র মূল ধারণা

Encoder এখন একটি deterministic $z$ না দিয়ে — একটি probability distribution $q_\phi(z|x) = \mathcal{N}(\mu_\phi(x), \sigma_\phi^2(x))$ output করে।
Decoder এই distribution থেকে sample করা $z$-এর উপর নির্ভর করে $\hat{x}$ generate করে।
Loss-এ একটি term যোগ করি যা $q(z|x)$-কে prior $p(z) = \mathcal{N}(0, I)$-এর কাছে টানে।

২ · ELBO — Evidence Lower BOund

আমরা চাই data-র marginal likelihood $\log p(x)$ সর্বোচ্চ করতে। কিন্তু এর integral $\log p(x) = \log \int p(x|z) p(z) \, dz$ সাধারণত intractable। তাই Jensen's inequality দিয়ে একটি lower bound নির্মাণ:

$$\log p(x) \geq \mathbb{E}_{q_\phi(z|x)}[\log p_\theta(x|z)] - \mathrm{KL}\big(q_\phi(z|x) \,\|\, p(z)\big) = \mathcal{L}_{\text{ELBO}}$$

দু'টি term-এর অর্থ:

  • Reconstruction: $\mathbb{E}_q[\log p_\theta(x|z)]$ — sample-করা $z$ থেকে $x$ ভাল reconstruct।
  • KL regularizer: $\mathrm{KL}(q\|p)$ — encoder-এর distribution prior $\mathcal{N}(0,I)$-এর কাছে।

Gaussian-Gaussian KL-এর closed form (একই বা isotropic):

$$\mathrm{KL}\big(\mathcal{N}(\mu, \sigma^2) \,\|\, \mathcal{N}(0, 1)\big) = \tfrac{1}{2} \sum_j \big(\mu_j^2 + \sigma_j^2 - \log \sigma_j^2 - 1\big)$$

৩ · Reparameterization trick

সমস্যা: $z \sim \mathcal{N}(\mu, \sigma^2)$ — sampling একটি stochastic operation, gradient flow করে না। সমাধান (reparameterizationReparameterization trickKingma ও Welling-এর ২০১৩ পেপারের সবচেয়ে প্রভাবশালী contribution। এই trick ছাড়া modern variational deep learning সম্ভব ছিল না — diffusion ও flow-এর backbone।):

$$z = \mu + \sigma \odot \epsilon, \quad \epsilon \sim \mathcal{N}(0, I)$$

এখন $\mu, \sigma$ deterministic — তাদের উপর backprop সম্ভব। Randomness পুরোটাই $\epsilon$-এ — যা parameter নয়।

ভাবুন একটি দোকান থেকে দাম নির্ধারণ করছেন: $\text{দাম} = \text{base} + \text{discount} \times \text{coupon}$। Coupon (random) আপনার নিয়ন্ত্রণে নেই, কিন্তু base ও discount আপনি optimize করতে পারেন। একইভাবে $\mu, \sigma$ optimize হয়, $\epsilon$ random থাকে।
VAE — μ, σ, reparameterize, decode x → μ,σ → z = μ + σ⊙ε → x̂ x Encoder φ μ(x) σ(x) ε N(0, I) z = μ + σ⊙ε reparameterize Decoder θ x̂ Recon: ‖x − x̂‖² KL(q‖p) regularizer ELBO total
VAE pipeline — encoder $\mu, \sigma$ output করে; reparameterize-এ $z$ sample; decoder reconstruct। Loss = recon + KL।

৪ · PyTorch — VAE implementation

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

class VAE(nn.Module):
    def __init__(self, latent_dim=20):
        super().__init__()
        self.fc1   = nn.Linear(784, 400)
        self.fc_mu  = nn.Linear(400, latent_dim)
        self.fc_lv  = nn.Linear(400, latent_dim)   # log σ²
        self.fc2   = nn.Linear(latent_dim, 400)
        self.fc3   = nn.Linear(400, 784)

    def encode(self, x):
        h = F.relu(self.fc1(x))
        return self.fc_mu(h), self.fc_lv(h)

    def reparameterize(self, mu, logvar):
        std = (0.5 * logvar).exp()
        eps = torch.randn_like(std)
        return mu + eps * std

    def decode(self, z):
        h = F.relu(self.fc2(z))
        return torch.sigmoid(self.fc3(h))

    def forward(self, x):
        mu, logvar = self.encode(x)
        z = self.reparameterize(mu, logvar)
        return self.decode(z), mu, logvar

    
Encoder $\mu$ ও $\log \sigma^2$ output করে — log-variance numerical stability-র জন্য। reparameterize trick gradient flow সম্ভব করে।

৫ · ELBO loss function

Python · PyTorch
def vae_loss(x_hat, x, mu, logvar, beta=1.0):
    # Reconstruction (BCE — pixel-wise)
    bce = F.binary_cross_entropy(x_hat, x, reduction='sum')
    # KL divergence — closed form for N(μ,σ²) ‖ N(0,I)
    kl = -0.5 * torch.sum(1 + logvar - mu.pow(2) - logvar.exp())
    return bce + beta * kl

# training step
x_hat, mu, lv = model(x.view(-1, 784))
loss = vae_loss(x_hat, x.view(-1, 784), mu, lv, beta=1.0)
loss.backward()

    

৬ · Sampling — নতুন digit তৈরি

Python · PyTorch
model.eval()
with torch.no_grad():
    z = torch.randn(16, 20)         # prior থেকে sample
    samples = model.decode(z)        # 16টি নতুন digit
    samples = samples.view(-1, 28, 28)
print(samples.shape)   # torch.Size([16, 28, 28])

    

৭ · Posterior collapse ও β-VAE

Posterior collapse: KL term-এর চাপে encoder $q(z|x) \approx p(z)$ হয়ে যায় — অর্থাৎ $z$-এ input-এর কোনো information নেই। Decoder নিজেই sufficient হয়ে গেলে এটি ঘটে। সমাধান: KL-annealing (training-এর শুরুতে $\beta$ ছোট, ধীরে বাড়ানো) বা KL-free bits।

β-VAE (Higgins et al., ২০১৭) — KL term-এর সামনে weight $\beta > 1$ বসিয়ে disentangled representation শেখার চেষ্টা। $\beta < 1$ better reconstruction, $\beta > 1$ better disentanglement — trade-off।

VAE-র sample সাধারণত GAN-এর তুলনায় blurry — কারণ MSE/BCE-এর "average" effect। সমাধান হিসেবে VQ-VAE (van den Oord, ২০১৭) discrete latent ব্যবহার, NVAE hierarchical structure।

৮ · আজকের দিনে VAE

  • Stable Diffusion-এর VAE encoder-decoder — diffusion latent space-এ চালানোর ভিত্তি।
  • VQ-VAE → DALL-E-1, Jukebox — discrete tokens।
  • NVAE (NVIDIA, ২০২০) — hierarchical VAE, diffusion-এর কাছাকাছি quality।
  • Bangla TTS-এ — speech latent শেখাতে VAE-style architecture জনপ্রিয়।

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

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

প্র ০১ Reparameterization trick ছাড়া কি VAE train করা সম্ভব? "Score function estimator" বা REINFORCE কী, এবং কেন reparameterization superior?

Reparameterization trick — Kingma-Welling-এর পেপারের সবচেয়ে প্রভাবশালী contribution। এটি ছাড়াও gradient estimation সম্ভব, কিন্তু variance অনেক বেশি।

Score function estimator (REINFORCE):

  • $\nabla_\phi \mathbb{E}_{q_\phi(z)}[f(z)] = \mathbb{E}_{q_\phi(z)}[f(z) \nabla_\phi \log q_\phi(z)]$
  • RL-এ Williams (১৯৯২) — REINFORCE নামে পরিচিত।
  • সব distribution-এ কাজ করে — discrete-ও।
  • কিন্তু variance বিশাল — convergence ধীর, baseline বা control variate দরকার।

Reparameterization trick:

  • $z = g_\phi(\epsilon, x)$ যেখানে $\epsilon$ parameter-free।
  • $\nabla_\phi \mathbb{E}_\epsilon[f(g_\phi(\epsilon, x))] = \mathbb{E}_\epsilon[\nabla_\phi f(g_\phi(\epsilon, x))]$
  • Variance অনেক কম — gradient estimate stable।
  • সীমাবদ্ধতা: distribution reparameterizable হতে হবে। Gaussian, uniform, exponential হ্যাঁ; Bernoulli, categorical না।

Discrete VAE-র জন্য কী করি?

  • Gumbel-Softmax / Concrete distribution (Jang et al., ২০১৬; Maddison et al., ২০১৬) — discrete-কে continuous-এ relax করে reparameterize।
  • Straight-through estimator — VQ-VAE-এ ব্যবহৃত।
  • REBAR, RELAX — control variate-এর smarter version।

আধুনিক context:

  • Diffusion model নিজেই reparameterization-এর extreme version — সব step-এ noise reparameterize।
  • Normalizing flow-এ reparameterization explicit বিজ্ঞান।
  • RLHF-এ score function estimator ফিরে আসে — reward differentiable নয় বলে।

মূল উপলব্ধি: reparameterization একটি deceptively simple algebraic trick — কিন্তু modern generative AI-র backbone। এটি ছাড়া VAE, diffusion, flow সবই অসম্ভব হতো।

প্র ০২ VAE-এর sample blurry কেন? GAN-এর তুলনায় কোথায় পিছিয়ে, কোথায় এগিয়ে? "Likelihood vs adversarial" trade-off ব্যাখ্যা করুন।

এটি generative modeling-এর সবচেয়ে গুরুত্বপূর্ণ trade-off। ২০১৪-২০১৯ পর্যন্ত VAE বনাম GAN-এর বিতর্ক generative AI-র কেন্দ্রীয় আলোচনা ছিল।

VAE blurry কেন?

  • Pixel-wise loss-এর gotcha: MSE/BCE প্রতিটি pixel-কে independent ধরে। দু'টি plausible reconstruction (একই content, slight shift) থাকলে — model এদের average output দেয়, যা blurry।
  • Mean-seeking behavior: KL$(q\|p)$ — encoder distribution-কে prior-এর কাছে চাপে। Decoder mean-prediction shortcut নেয়।
  • Multi-modal output: এক $z$-এ multiple valid $x$ থাকলে, MSE শুধু mean দেয়। GAN একটি বাছে।

GAN-এর সুবিধা:

  • Discriminator-এর adversarial loss "real-looking" sample-কে reward — blur অপছন্দ।
  • Sharp, photorealistic image — StyleGAN-এর human face quality VAE-র চেয়ে অনেক ভাল।

VAE-এর সুবিধা:

  • Stable training — single objective minimize, GAN-এর mode collapse নেই।
  • Likelihood বের হয় — anomaly detection, density estimation সম্ভব।
  • Smooth latent space — interpolation মসৃণ, GAN-এর latent কখনো discontinuous।
  • Better diversity — সব mode cover করে, GAN-এর mode collapse risk।
  • Encoder free — image → latent inversion সরাসরি, GAN-এ optimization দরকার।

Trade-off summary:

  • VAE: principled, stable, diverse, blurry।
  • GAN: sharp, hard to train, mode collapse risk, no likelihood।
  • Diffusion (২০২০+): দু'টোরই সুবিধা একসাথে — sharp, principled, stable, কিন্তু slow inference।

আধুনিক সমাধান:

  • VAE-GAN (Larsen et al., ২০১৫): দু'টো একসাথে — recon perceptual + adversarial।
  • VQ-VAE-2: sharp discrete latent।
  • NVAE: hierarchical, near-GAN quality।
  • Latent Diffusion: VAE encoder-decoder + diffusion in latent — Stable Diffusion।

মূল উপলব্ধি: "Likelihood-based" (VAE, flow, autoregressive) মডেল principle-এ শক্তিশালী কিন্তু perceptually আবছা; "Adversarial" sharp কিন্তু unstable। আজকের best system দু'টিরই idea মেশায়।

প্র ০৩ β-VAE-এর "disentanglement" কী? একটি face dataset-এ কেন আমরা চাই — এক $z$ dimension শুধু "smile", আরেকটি শুধু "age" represent করুক?

Disentangled representation — interpretable AI-র একটি কেন্দ্রীয় গবেষণা দিশা। Higgins et al. (২০১৭)-এর β-VAE পেপার এই দিকে প্রভাবশালী।

Disentanglement মানে কী:

  • একটি $z_i$ dimension একটি একক, semantically-meaningful factor (smile, age, lighting) capture করে।
  • অন্য dimension গুলো independent factor capture করে।
  • Latent space-এ axis-aligned interpretation সম্ভব।

β-VAE-র ধারণা:

  • Loss = recon + $\beta$·KL, $\beta > 1$।
  • বেশি KL pressure → encoder প্রতিটি $z_i$-কে independent ও standard normal-এর কাছে রাখতে বাধ্য।
  • Independence + simplicity → disentanglement।

কেন গুরুত্বপূর্ণ:

  • Interpretability: "এই neuron কী represent করছে" বোঝা যায়।
  • Controllable generation: shopping app-এ "একই মুখ কিন্তু smile বাড়াও" — directly $z_i$ adjust।
  • Compositional generalization: training-এ unseen combination (পুরুষ + smiling + glasses) generate।
  • Fairness: "race" dimension আলাদা হলে, downstream classifier থেকে remove সহজ।

সমস্যা:

  • Locatello et al. (২০১৯) — "unsupervised disentanglement is impossible" theorem। Inductive bias বা label ছাড়া guarantee নেই।
  • $\beta$ বাড়ালে reconstruction quality পড়ে।
  • "Disentangled" subjective — কোন factor "natural"?

পরবর্তী কাজ:

  • FactorVAE (Kim & Mnih, ২০১৮), TC-VAE (Chen et al., ২০১৮) — total correlation penalty।
  • StyleGAN-এর mapping network — implicit disentanglement।
  • Diffusion controllable generation — text/sketch/depth condition।

বাংলাদেশ context: Bangla face/identity protection-এ disentangled representation কাজে লাগে — biometric data থেকে identity বাদ দিয়ে শুধু "expression" extract।

মূল উপলব্ধি: Disentanglement একটি ideal — সম্পূর্ণ অর্জন কঠিন, কিন্তু partially অর্জনই AI-কে interpretable ও controllable করে। Generative AI-র UX-এর ভিত্তি।

প্র ০৪ VQ-VAE কীভাবে কাজ করে? "Continuous z" বনাম "discrete codebook" — কেন discrete বাছা গুরুত্বপূর্ণ, এবং DALL-E ও MusicLM-এ এর ভূমিকা কী?

VQ-VAE (van den Oord et al., ২০১৭) VAE-এর একটি দারুণ variant — latent continuous না, একটি discrete codebook থেকে বাছাই। Generative AI-র অনেক recent breakthrough এই foundation-এর উপর।

VQ-VAE কীভাবে কাজ করে:

  • Encoder একটি continuous $z_e$ output করে।
  • একটি learnable codebook $\{e_1, e_2, \ldots, e_K\}$ থাকে — $K$ vectors।
  • $z_e$-এর nearest neighbor codebook entry $e_k$ বাছা হয়; decoder সেই $e_k$ ব্যবহার করে।
  • Loss: reconstruction + codebook commitment loss + straight-through gradient (sg operator)।

Discrete কেন superior:

  • Sharper output: Continuous VAE-র blur নেই — discrete code দিয়ে decoder confident।
  • Posterior collapse নেই: Discrete codes meaningful থাকতে বাধ্য।
  • Sequence modeling সহজ: Discrete codes = tokens। Transformer/PixelCNN দিয়ে $p(\text{tokens})$ model করা যায়।
  • Compression: $\log_2 K$ bits per code — efficient storage।

Two-stage training paradigm:

  1. Stage 1: VQ-VAE train — image → token sequence।
  2. Stage 2: একটি autoregressive model (Transformer/PixelCNN) token sequence-এর distribution শেখে।
  3. Generate: Transformer থেকে tokens sample → VQ-VAE decoder → image।

Real-world impact:

  • DALL-E 1 (OpenAI, ২০২১): dVAE (VQ-VAE-এর variant) image-কে ১০২৪ token-এ রূপান্তর; text + image tokens একসাথে Transformer।
  • VQ-VAE-2 (Razavi et al., ২০১৯): hierarchical codes, ImageNet-এ near-BigGAN quality।
  • Jukebox (OpenAI, ২০২০): raw audio → VQ tokens → Transformer। নতুন গান generate।
  • MusicLM (Google, ২০২৩): hierarchical audio tokens।
  • VideoPoet, AudioLM: token-based unified models।

Limitation:

  • Codebook utilization — অনেক code unused হয়ে যায়।
  • Inference slow — autoregressive token generation ধীর।
  • Diffusion-এর pixel-quality প্রায়ই ছাড়িয়ে যায়।

আধুনিক direction:

  • FSQ (Finite Scalar Quantization, ২০২৩) — VQ-এর simpler replacement।
  • Hybrid approach: SDXL-এর VAE continuous, কিন্তু latent diffusion।
  • Tokenizer for everything: video, audio, action — tokenize করো, Transformer-এ feed।

মূল উপলব্ধি: "Tokenize the world" paradigm — VQ-VAE-এর সবচেয়ে বড় উত্তরাধিকার। যা কিছু tokens-এ রূপান্তর হয়, তা LLM-style modeling-এর আওতায় আসে। এই principle multimodal AI-র ভিত্তি।

অনুশীলন

  1. হাতে-কলমে: $q = \mathcal{N}(\mu, \sigma^2) = \mathcal{N}(0.5, 1.0)$ এবং $p = \mathcal{N}(0, 1)$। $\mathrm{KL}(q\|p)$ হিসাব করুন।

    $\mathrm{KL} = \tfrac{1}{2}(\mu^2 + \sigma^2 - \log \sigma^2 - 1) = \tfrac{1}{2}(0.25 + 1 - 0 - 1) = 0.125$।

    $\mu = 0, \sigma = 1$ হলে KL = 0 — perfect match।

  2. কোডে চেষ্টা: উপরের VAE-তে $\beta$-এর মান $0.1, 1.0, 4.0$ try করে দেখুন। Reconstruction quality ও sample diversity-তে কী পার্থক্য?
    • $\beta = 0.1$: KL দুর্বল → encoder almost deterministic → reconstruction ভাল কিন্তু prior থেকে sample বাজে।
    • $\beta = 1.0$: standard VAE — balance।
    • $\beta = 4.0$: reconstruction blurry, কিন্তু latent disentangled।

    Trade-off সরাসরি দেখা যায়।

  3. ভাবুন: বাংলা handwritten digit dataset-এ VAE train করছেন। $z$ dimension কত বাছবেন? কেন?

    Bangla digit ১০টি (০-৯)। MNIST-style dataset হলে — intrinsic complexity প্রায় MNIST-এর সমান। সাধারণত $d = 16$-$32$ ভাল কাজ করে। বেশি style variation থাকলে (যেমন বহু লেখকের handwriting) — $d = 32$-$64$।

    Iterative experiment করুন — validation reconstruction loss vs $d$ plot। Elbow point-এ থামুন।

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

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