পাঠ ৩৫ · ৪০-এর মধ্যে · মডিউল ৫
Home / AI Courses / ডিপ লার্নিং / Autoencoder ও VAE

Autoencoder ও VAE

Autoencoders & Variational Autoencoders
৮ মিনিট পড়া মাঝারি · Intermediate PyTorch hands-on

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

  • Autoencoder architecture — bottleneck এর গুরুত্ব
  • VAE-এর probabilistic latent — কেন regularization দরকার
  • ELBO loss-এর দু'টি term — reconstruction ও KL
  • Reparameterization trick — backprop সম্ভব করার কৌশল
  • PyTorch দিয়ে MNIST AE ও VAE
  • Latent space interpolation ও sampling

১ · Autoencoder — সংক্ষিপ্ত ধারণা

Autoencoder একটি self-supervised neural network — input কে নিজে predict করে। কাঠামো:

$$x \xrightarrow{\text{Encoder}} z \xrightarrow{\text{Decoder}} \hat{x}$$

  • Encoder $f_\phi$: input $x$ (যেমন ৭৮৪-D MNIST image) → low-dim latent $z$ (২০-D bottleneck)।
  • Decoder $g_\theta$: latent $z$ → reconstructed $\hat{x}$।
  • Loss: $\mathcal{L} = \|x - \hat{x}\|^2$ — pixel-wise MSE বা binary cross-entropy।

Bottleneck dimension ছোট হওয়া critical — না হলে network identity function শিখে কাজ করবে না।

কেন কাজ করে

Compress করতে গিয়ে network বাধ্য হয় — সবচেয়ে important feature বাছতে। Reconstruction-এর জন্য প্রয়োজনীয় তথ্য $z$-এ সংরক্ষিত। তাই $z$ একটি compact representation — যা অনেক downstream task-এ কাজে লাগে।

২ · Autoencoder-এর ভাইবোন

  • Denoising AE: input-এ noise add করে — clean reconstruct করতে শেখানো। Robust feature।
  • Sparse AE: $z$-এ L1 regularization — overcomplete latent কিন্তু sparse activation।
  • Contractive AE: Jacobian penalty — input-এর small change-এ stable representation।
  • Convolutional AE: Conv encoder + Conv-transpose decoder — image-এ ভালো।
  • Variational AE: probabilistic latent — generative। নিচে বিস্তারিত।

৩ · Vanilla AE-এর সমস্যা — kena VAE

Vanilla AE-এর latent space-এ structure নেই। যদি দু'টি training image-এর latent $z_1, z_2$ থাকে — মাঝখানে $0.5(z_1 + z_2)$ point থেকে decode করলে — সাধারণত garbage।

Latent space-এ "holes" — কিছু region-এ training data নেই। Generation-এর জন্য random $z$ sample করে valid sample পাওয়া কঠিন।

VAE-এর সমাধান: latent space-কে continuous, structured করা — Gaussian distribution-এ regularize।

৪ · VAE — probabilistic encoder

VAE-তে encoder একটি distribution output করে — single point নয়:

$$q_\phi(z|x) = \mathcal{N}(z; \mu_\phi(x), \sigma_\phi^2(x))$$

Encoder দু'টি vector return — $\mu$ ও $\log \sigma^2$। Latent $z$ এই distribution থেকে sample।

Vanilla AE — প্রতিটি image-কে map করে latent space-এ একটি "point"। VAE — প্রতিটি image map হয় একটি "cloud" (Gaussian)। Cloud-গুলো overlap করে — মাঝখানের point-ও meaningful। সেই cloud-গুলো একসাথে standard normal-এর মতো ভরে রাখতে চাই — তাই KL term।

৫ · ELBO loss — দু'টি term

VAE training-এ minimize:

$$\mathcal{L}_{VAE} = \underbrace{-\mathbb{E}_{z \sim q_\phi(z|x)}[\log p_\theta(x|z)]}_{\text{reconstruction loss}} + \underbrace{D_{KL}(q_\phi(z|x) \| p(z))}_{\text{KL divergence}}$$

  • Reconstruction: input $x$ থেকে sampled $z$ → decoder $\to \hat{x}$ — Pixel-wise BCE বা MSE।
  • KL term: encoder distribution $q_\phi(z|x)$ — prior $p(z) = \mathcal{N}(0, I)$-এর কাছাকাছি রাখো।

Gaussian-Gaussian KL closed-form:

$$D_{KL} = \frac{1}{2} \sum_i \left( \mu_i^2 + \sigma_i^2 - 1 - \log \sigma_i^2 \right)$$

৬ · Reparameterization trick

Sample করা একটি stochastic operation — backprop সরাসরি যায় না। Trick:

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

Randomness $\epsilon$-এ আলাদা — gradient $\mu, \sigma$ দিয়ে flow করতে পারে। Kingma & Welling (২০১৪)-এর key contribution।

VAE — encoder → latent distribution → decoder x → (μ, σ) → z = μ + σε → x̂ Input x Encoder q_φ(z|x) → (μ, log σ²) μ σ ε ~ N(0,I) z = μ + σε reparam trick Decoder p_θ(x|z) → x̂ Loss = Reconstruction(x, x̂) + β · KL(q_φ ∥ N(0,I))
VAE-এর pipeline — encoder distribution output, reparameterization trick দিয়ে z sample, decoder reconstruct। Loss-এ KL term latent space-কে structured রাখে।

৭ · PyTorch — vanilla autoencoder

Python · Vanilla AE (MNIST)
import torch
import torch.nn as nn

class Autoencoder(nn.Module):
    def __init__(self, latent_dim=20):
        super().__init__()
        self.encoder = nn.Sequential(
            nn.Linear(784, 256), nn.ReLU(),
            nn.Linear(256, 64),  nn.ReLU(),
            nn.Linear(64, latent_dim),
        )
        self.decoder = nn.Sequential(
            nn.Linear(latent_dim, 64), nn.ReLU(),
            nn.Linear(64, 256), nn.ReLU(),
            nn.Linear(256, 784), nn.Sigmoid(),
        )

    def forward(self, x):
        z = self.encoder(x)
        x_hat = self.decoder(z)
        return x_hat, z

ae = Autoencoder()
x = torch.rand(8, 784)
x_hat, z = ae(x)
print(x_hat.shape, z.shape)   # (8,784) (8,20)
loss = nn.functional.mse_loss(x_hat, x)
print(f"loss: {loss.item():.4f}")

    

৮ · PyTorch — VAE

Python · VAE (MNIST)
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_logvar = nn.Linear(400, latent_dim)
        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_logvar(h)

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

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

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

def vae_loss(x_hat, x, mu, logvar):
    bce = F.binary_cross_entropy(x_hat, x, reduction='sum')
    kl = -0.5 * torch.sum(1 + logvar - mu.pow(2) - logvar.exp())
    return bce + kl

vae = VAE()
x = torch.rand(8, 784)
x_hat, mu, logvar = vae(x)
print(vae_loss(x_hat, x, mu, logvar).item())

    

৯ · Latent space — interpolation ও sampling

Trained VAE-এর দু'টি capability:

  • Sampling: $z \sim \mathcal{N}(0, I)$ থেকে → decoder → new image। Generative model।
  • Interpolation: দু'টি real image-এর latent $z_1, z_2$ — মাঝখানে $z_t = (1-t)z_1 + t z_2$ → smooth transition। "Face morphing"-এর মূল।
  • Attribute arithmetic: "smiling" direction → image-এ smile add।

১০ · Application

  • Anomaly detection: normal data-এ trained AE — abnormal sample reconstruction error বেশি।
  • Denoising: Photoshop-এর smart noise reduction-এর ancestor।
  • Compression: Pretty good visual compression।
  • Pretraining: Encoder feature extractor — downstream classification।
  • Generation: VAE → image, music, molecular structure।
  • Modern era: Stable Diffusion-এর VAE — latent space-এ diffusion।
VAE-এর image quality GAN বা diffusion-এর চেয়ে blurry — pixel-wise loss-এর কারণে। কিন্তু stable training, principled probabilistic foundation, latent structure — এই কারণে আজও ব্যবহৃত (latent-space diffusion)। L36-এ GAN — sharp image generation-এর সরাসরি প্রতিদ্বন্দ্বী।

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

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

প্র ০১ VAE-এর image generation blurry হয় কেন? Pixel MSE/BCE loss-এর কী fundamental সমস্যা?

VAE blurry — image generation research-এর well-known problem। Multiple cause overlap।

(১) Pixel-wise loss — averaging effect:

  • MSE/BCE — প্রতিটি pixel independently optimize।
  • একটি image-এর বহু "valid" reconstruction।
  • Average minimize করে — পরিচয় blurry।
  • Gauss noise effectively।

(২) ELBO bound — not exact likelihood:

  • Lower bound — actual likelihood underestimate।
  • Optimization tighter bound search নয়।
  • True maximum likelihood নয়।

(৩) Posterior collapse:

  • Decoder powerful হলে — latent ignore করে।
  • $z$-এ information loss।
  • KL term-এর pull dominate করে।
  • Generation quality drop।

(৪) Gaussian assumption:

  • Pixel-wise output → Gaussian likelihood = MSE।
  • Real image distribution multimodal।
  • Gaussian fit poor।
  • Mode-averaging behavior।

Solutions tried:

  • VQ-VAE: discrete latent — sharper।
  • NVAE: hierarchical — better quality।
  • VAE-GAN hybrid: adversarial loss combine।
  • Perceptual loss: VGG features-এ loss।
  • Latent diffusion: VAE encoder + diffusion in latent।

Modern landscape:

  • Pure VAE generation — superseded by diffusion।
  • VAE encoder-decoder still used (Stable Diffusion-এ)।
  • Latent space property valuable।
  • Reconstruction quality acceptable for compression।

Why diffusion better:

  • Iterative refinement — sharp।
  • Markov chain — multimodal natural।
  • No averaging trap।
  • Theoretical foundation different।

VAE strengths preserved:

  • Encoder for representation learning।
  • Latent interpolation smooth।
  • Probabilistic structure।
  • Anomaly detection useful।

মূল উপলব্ধি: Blur — pixel loss + ELBO bound + Gaussian assumption combined। Modern hybrid (VAE + diffusion) best-of-both। Pure VAE generation rare now। Encoder-decoder paradigm still essential। Trade-off: stability vs sharpness।

প্র ০২ Reparameterization trick — কেন এটা lifesaver? Direct sampling-এ backprop কেন কাজ করে না?

Reparameterization — VAE-এর mathematical brilliance। Without it — VAE existence থাকতই না।

Direct sampling:

  • $z \sim \mathcal{N}(\mu, \sigma^2)$ — Python-এ torch.normal(mu, sigma)।
  • Gradient $\partial z / \partial \mu$ undefined — discrete random operation।
  • Backprop through sampling impossible।

Reparameterization fix:

  • $z = \mu + \sigma \cdot \epsilon$, $\epsilon \sim \mathcal{N}(0, 1)$।
  • $\epsilon$ external — independent of $\mu, \sigma$।
  • $z$ now deterministic function of $\mu, \sigma, \epsilon$।
  • $\partial z / \partial \mu = 1$, $\partial z / \partial \sigma = \epsilon$।
  • Gradient flows!

Mathematical insight:

  • Stochasticity পুরোপুরি $\epsilon$-এ।
  • Deterministic transformation Gaussian-এ map।
  • Location-scale family-এর property।

Generalization:

  • Other distribution-এ similar trick।
  • Concrete (Gumbel-Softmax) — discrete categorical।
  • Implicit reparameterization — more complex distribution।

Without reparam alternatives:

  • Score function (REINFORCE): high variance, slow।
  • Pathwise derivative: reparam-এর general name।
  • Reparam — lowest variance estimator usually।

VAE breakthrough:

  • Kingma-Welling ২০১৪ paper।
  • Variational inference + neural network combine।
  • Reparam — practical training enabler।
  • Field-defining contribution।

Modern applications:

  • Bayesian neural networks।
  • Reinforcement learning policy gradient।
  • Normalizing flows।
  • Diffusion model training।

মূল উপলব্ধি: Reparam — randomness factor out, gradient flow restore। VAE practical existence depend on this। Probabilistic DL-এর foundational technique। Math elegance + practical impact rare। Modern DL এর প্রায় সব probabilistic component এই trick কোনো না কোনো রূপে ব্যবহার করে।

প্র ০৩ Anomaly detection-এ AE/VAE — Bangladesh-এর একটি bank credit card fraud detection-এ কীভাবে ব্যবহার করা যাবে?

Practical Bangladesh use case — AE-based fraud detection। Well-suited problem।

Why AE for fraud:

  • Fraud rare — labeled data scarce।
  • Normal pattern abundant।
  • Unsupervised learning natural।
  • Reconstruction error → anomaly score।

Pipeline design:

(১) Feature engineering:

  • Transaction amount (log-scaled)।
  • Time of day।
  • Merchant category।
  • Location।
  • Days since last transaction।
  • User profile aggregates।

(২) Train normal AE:

  • Only legitimate transactions।
  • Latent dim ~১০।
  • Reconstruction loss minimize।

(৩) Inference:

  • New transaction encode-decode।
  • Reconstruction error compute।
  • Threshold above → flag।

VAE advantages over vanilla AE:

  • Probabilistic anomaly score।
  • $\log p(x)$ proxy via ELBO।
  • Better calibrated।
  • Latent space interpretable।

Bangladesh-specific patterns:

  • Rural-urban transaction difference।
  • Mobile banking (bKash, Nagad) integration।
  • Eid-period high volume — seasonal model।
  • Card-not-present transaction rise।

Implementation:

import torch
import torch.nn as nn

class FraudAE(nn.Module):
    def __init__(self, n_features=20, latent=8):
        super().__init__()
        self.encoder = nn.Sequential(
            nn.Linear(n_features, 16), nn.ReLU(),
            nn.Linear(16, latent))
        self.decoder = nn.Sequential(
            nn.Linear(latent, 16), nn.ReLU(),
            nn.Linear(16, n_features))

    def forward(self, x):
        z = self.encoder(x)
        return self.decoder(z)

# Train on normal transactions
# Inference: high reconstruction error = anomaly
def anomaly_score(model, x):
    x_hat = model(x)
    return ((x - x_hat) ** 2).sum(dim=1)

Threshold setting:

  • Validation set distribution analysis।
  • ৯৯-percentile reconstruction error।
  • Cost-sensitive — false negative > false positive in fraud।
  • Continuous tuning।

Production challenges:

  • Real-time inference (~১০০ms requirement)।
  • Concept drift — fraudster adapt।
  • Continuous retraining।
  • Explainability — regulator demand।

Compared to alternatives:

  • Isolation Forest — simpler, strong baseline।
  • One-class SVM — small scale।
  • XGBoost on labeled data — supervised।
  • AE — best when normal pattern complex।

Hybrid approach:

  • AE anomaly score → input feature।
  • XGBoost final classifier।
  • Best of unsupervised + supervised।
  • Production standard।

Bangladesh deployment:

  • Bank infrastructure modernizing।
  • Mobile banking explosion।
  • Fraud sophistication rising।
  • AI-based detection essential।

মূল উপলব্ধি: AE/VAE — fraud detection natural fit। Reconstruction error → anomaly score। Bangladesh banking — modernization opportunity। Hybrid (AE + supervised) production winner। Continuous adaptation key। Practical AI use case।

প্র ০৪ Stable Diffusion-এর "Latent Diffusion" — VAE encoder ব্যবহার। Why? Pure pixel diffusion-এর সাথে compare।

Stable Diffusion (Rombach et al., ২০২২) — generative AI revolution। VAE component critical।

Pure pixel diffusion problem:

  • 5১২×৫১২×৩ = ৭৮৬,৪৩২ dimensions।
  • Diffusion ১০০০ step — extremely expensive।
  • Memory bottleneck।
  • Training cost prohibitive।

Latent diffusion idea:

  • VAE encoder: 5১২×৫১২×৩ → ৬৪×৬৪×৪।
  • ৪৮x dimension reduction।
  • Diffusion in compressed latent।
  • VAE decoder: latent → image।

Architecture:

  • Step ১: VAE-GAN train — high quality reconstruction।
  • Step ২: Freeze VAE, train diffusion in latent।
  • Inference: latent sample → VAE decode → image।

Speed gains:

  • Compute ~৫০x faster।
  • Consumer GPU viable।
  • Mass adoption enabled।

Why VAE specifically:

  • Continuous latent — diffusion natural।
  • Smooth interpolation।
  • Probabilistic foundation।
  • Reconstruction quality acceptable।

VAE-GAN hybrid:

  • VAE alone — blurry।
  • + Adversarial discriminator — sharp।
  • + Perceptual loss — realistic।
  • Best of both worlds।

VQ-VAE alternative:

  • Discrete latent — codebook।
  • VQ-VAE-2 — high quality।
  • DALL-E 1 ব্যবহার করেছিল।
  • Continuous (LDM) easier-to-train।

Trade-offs:

  • VAE compression lossy।
  • Fine detail সামান্য lost।
  • Two-stage training।
  • Latent space size — perception trade-off।

Modern variants:

  • SDXL — larger, refined VAE।
  • SD3 — flow matching + better VAE।
  • FLUX — improved encoder।
  • VAE quality ongoing research।

Other applications:

  • Sora (video) — VAE temporal compression।
  • Audio LDM — spectrogram VAE।
  • 3D — point cloud VAE।
  • Universal compression-then-generate paradigm।

Bangladesh implication:

  • Stable Diffusion fine-tune — Bangla art style।
  • Consumer GPU sufficient — accessible।
  • VAE freezing reduce compute।
  • LoRA on diffusion — minimal training data।

মূল উপলব্ধি: Latent Diffusion = VAE compression + Diffusion generation। ৫০x speedup। VAE encoder-decoder modern essential। Pure pixel diffusion impractical scale-এ। Compress-then-generate universal paradigm। VAE renaissance via diffusion।

অনুশীলন

  1. KL gradient: Single sample $\mu = 0.5, \log\sigma^2 = -0.2$ — KL term value ও $\partial KL / \partial \mu$ compute।
    • $\sigma^2 = e^{-0.2} \approx 0.819$।
    • $KL = 0.5(\mu^2 + \sigma^2 - 1 - \log\sigma^2) = 0.5(0.25 + 0.819 - 1 - (-0.2)) = 0.5 \times 0.269 \approx 0.135$।
    • $\partial KL/\partial \mu = \mu = 0.5$।
  2. Reparameterization code: $\mu, \log\sigma^2$ থেকে $z$ sample করুন PyTorch-এ।
    import torch
    mu = torch.tensor([0.5, -0.2, 1.0])
    logvar = torch.tensor([-0.2, 0.0, 0.5])
    std = torch.exp(0.5 * logvar)
    eps = torch.randn_like(std)
    z = mu + eps * std
    print(z)
  3. চিন্তা: $\beta$-VAE — KL term-এ weight $\beta > 1$। Disentanglement বাড়ায়। কেন? কী trade-off?

    $\beta > 1$ — KL pressure বাড়ে — latent dimensions আরও Gaussian-like ও independent হতে বাধ্য। Independent dimension → factorized representation → disentangled (e.g., color, shape, position আলাদা dim-এ)।

    Trade-off: reconstruction quality drop — bottleneck tighter। Higgins et al. (২০১৭) — $\beta=4$-এ MNIST-এ smile, rotation আলাদা latent। Production-এ rarely pure $\beta$-VAE — সাধারণত controlled annealing।

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

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