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

DCGAN ও StyleGAN — convolutional ও style-based GAN

DCGAN & StyleGAN architectures
৭ মিনিট পড়া মধ্যম · Intermediate PyTorch কোডসহ

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

  • DCGAN-এর architectural guideline — কেন strided conv, BatchNorm, no FC
  • StyleGAN-এর mapping network ও latent space-এর tier-ভিত্তিক control
  • AdaIN — adaptive instance normalization দিয়ে style injection
  • StyleGAN2 ও 3-এর progression; মুখ generation-এ এর বিপ্লব

১ · কেন DCGAN দরকার ছিল

২০১৪-এ Goodfellow-এর GAN MNIST-এ ৬৪×৬৪-এ digit generate করতে পারল, কিন্তু complex image (face, scene) — হোঁচট খেল। সমস্যা — fully-connected MLP architecture। ছবি মানে spatial structure, MLP তা ধরতে পারে না।

DCGANDeep Convolutional GANRadford, Metz, Chintala (২০১৫) — GAN-এর প্রথম stable convolutional architecture। আজও সব image GAN-এর "starting recipe"। ছোট-মাঝারি resolution-এ baseline। (Radford, Metz, Chintala, ২০১৫) এই ব্যবধান ভেঙে দিল — কয়েকটি precise architectural guideline দিয়ে।

DCGAN architectural guidelines

১) Pooling-এর বদলে strided convolution ($D$-এ) ও transposed convolution ($G$-এ)।
২) সব hidden layer-এ BatchNorm; output layer-এ না।
৩) Fully-connected hidden layer বাদ — শুধু conv।
৪) $G$-এ ReLU, output-এ Tanh; $D$-এ LeakyReLU।

২ · DCGAN Generator architecture

Noise $z \in \mathbb{R}^{100}$ → reshape $(1024, 4, 4)$ → upsample step by step:

$4 \times 4 \times 1024 \to 8 \times 8 \times 512 \to 16 \times 16 \times 256 \to 32 \times 32 \times 128 \to 64 \times 64 \times 3$

প্রতিটি step-এ একটি transposed convolutionTransposed convolution"deconvolution"-ও বলা হয়। Spatial resolution বাড়ায় — যেমন stride-2 transposed conv ছবিকে ২× করে। GAN-এর upsampling, autoencoder decoder-এ ব্যবহৃত। (stride 2) দিয়ে spatial dimension দ্বিগুণ, channel অর্ধেক।

Python · PyTorch
import torch.nn as nn

class DCGANGen(nn.Module):
    def __init__(self, z_dim=100, ngf=64):
        super().__init__()
        self.net = nn.Sequential(
            # z (B, 100, 1, 1) → 4×4
            nn.ConvTranspose2d(z_dim, ngf*8, 4, 1, 0, bias=False),
            nn.BatchNorm2d(ngf*8), nn.ReLU(True),
            # 4 → 8
            nn.ConvTranspose2d(ngf*8, ngf*4, 4, 2, 1, bias=False),
            nn.BatchNorm2d(ngf*4), nn.ReLU(True),
            # 8 → 16
            nn.ConvTranspose2d(ngf*4, ngf*2, 4, 2, 1, bias=False),
            nn.BatchNorm2d(ngf*2), nn.ReLU(True),
            # 16 → 32
            nn.ConvTranspose2d(ngf*2, ngf, 4, 2, 1, bias=False),
            nn.BatchNorm2d(ngf), nn.ReLU(True),
            # 32 → 64
            nn.ConvTranspose2d(ngf, 3, 4, 2, 1, bias=False),
            nn.Tanh(),
        )

    def forward(self, z):
        return self.net(z)

    

৩ · DCGAN-এর সীমাবদ্ধতা

DCGAN ৬৪×৬৪ পর্যন্ত ভাল — কিন্তু ১০২৪×১০২৪ photorealistic face? অসম্ভব। কারণ:

  • $z$ vector পুরো image-কে control করে — fine vs coarse feature আলাদা না।
  • হাইয়ার resolution-এ training instability বাড়ে।
  • "Style" আর "content" disentangled না।

৪ · StyleGAN — Karras et al. (২০১৮)

NVIDIA-র Karras-এর দল ২০১৭-এ Progressive GAN ($1024 \times 1024$ face — প্রথমবার), ২০১৮-এ StyleGAN দিল — যা generative AI-র history পাল্টে দিল। This-Person-Does-Not-Exist.com — viral হলো।

StyleGAN-এর তিন innovation

১) Mapping network: $z \in \mathcal{Z}$ → $w \in \mathcal{W}$ (8-layer MLP)। $\mathcal{W}$ space disentangled।
২) AdaIN: প্রতিটি conv layer-এর output-এ $w$-derived style inject।
৩) Stochastic noise: প্রতিটি layer-এ per-pixel noise — fine detail-এ randomness।

৫ · AdaIN — Adaptive Instance Normalization

প্রতিটি feature map $x_i$-কে normalize করে style $y$ inject:

$$\mathrm{AdaIN}(x_i, y) = y_{s,i} \cdot \frac{x_i - \mu(x_i)}{\sigma(x_i)} + y_{b,i}$$

যেখানে $y_{s,i}, y_{b,i}$ — $w$ vector থেকে learned affine transformation। প্রতিটি layer-এ ভিন্ন $y$ inject — কারণ একই $w$ থেকে আলাদা layer-এ আলাদা scale-bias শেখা হয়।

ভাবুন একটি ছবি আঁকার সময় আপনার কয়েকটি tool আছে — coarse brush (overall pose), medium brush (face shape), fine brush (eye color, freckles)। StyleGAN-এ প্রতিটি resolution-এর layer একটি tool। Mapping network আপনাকে বলে কোন layer-এ কোন style লাগবে।

৬ · Style mixing ও hierarchical control

StyleGAN-এ training-এ "style mixing regularization" — দু'টি random $z_1, z_2$ → $w_1, w_2$, কিছু layer-এ $w_1$, বাকি-তে $w_2$ inject। ফলে প্রতিটি layer স্বাধীন meaning বহন করতে শেখে:

  • Coarse layers (4²–8²): pose, hair style, face shape — overall identity।
  • Middle layers (16²–32²): facial features — eye, nose shape; expressions।
  • Fine layers (64²–1024²): color scheme, micro structure, freckles, hair color।
StyleGAN — mapping network + AdaIN per layer z Mapping 8-layer MLP z → w w disentangled style space 4² · 8² Coarse pose, identity + AdaIN(w) 16² · 32² Middle features, expr + AdaIN(w) 64² · 128² Fine color, texture + AdaIN(w) 256² · 1024² Ultra-fine freckles, hair Photorealistic face 1024 × 1024 + stochastic noise per layer (skin pore, hair strand)
StyleGAN — mapping network $z \to w$; প্রতিটি resolution layer-এ AdaIN দিয়ে style inject; প্রতিটি layer-এ stochastic noise। Coarse → fine, semantic hierarchy।

৭ · StyleGAN2 — droplet artifact দূর

StyleGAN-এ একটি কুখ্যাত artifact ছিল — feature map-এ "droplet" pattern (যা AdaIN-এর instance norm-এ feature scale uniform না হওয়ায় হয়)। StyleGAN2 (Karras et al., ২০২০) সমাধান:

  • Weight modulation/demodulation — AdaIN-এর বদলে conv weight নিজেই $w$-modulated, তারপর normalize।
  • Path length regularization — generator output-এর $w$-জড়িত smoothness।
  • Skip connection ও residual — progressive growing লাগে না।

৮ · StyleGAN3 — alias-free

StyleGAN2-এও সমস্যা — head ঘুরালে কিছু feature (চুল, ভ্রু) "stick" করে position-এ, ঘুরে না। কারণ — neural network signal-এ aliasingAliasingSignal processing-এর ধারণা — high-frequency signal-কে low sample rate-এ sample করলে false low-frequency artifact। StyleGAN3-এ Karras দেখালেন pointwise nonlinearity ও improper upsampling aliasing তৈরি করে।।

StyleGAN3 (Karras et al., ২০২১) — Fourier feature, properly bandlimited filter, alias-free upsampling। ফলে rotation ও translation-এ feature consistent থাকে — animated video natural দেখায়।

StyleGAN3 train করা গুরুতর — হাজার হাজার H100 GPU-hour। Production-এ pretrained weight (FFHQ, AFHQ) ব্যবহার করুন; ছোট কাস্টম dataset হলে fine-tune বা LoRA-style adaptation।

৯ · StyleGAN আজ — কোথায় ব্যবহৃত

  • This-Person-Does-Not-Exist — viral demo।
  • FaceApp, Snapchat-এর age/gender filter — StyleGAN inversion।
  • Animation industry — character variation।
  • Bangladesh: Mediacom, GP-এর campaign visual diverse face — synthetic model।
  • Forensic: police age-progression sketch।
  • Diffusion-এর সাথে competition: Stable Diffusion-এর photorealism এখন StyleGAN-এর তুলনায় বেশি flexible (text-conditioned)।

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

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

প্র ০১ StyleGAN-এর mapping network $z \to w$ কেন গুরুত্বপূর্ণ? "Disentanglement"-এর গাণিতিক ব্যাখ্যা ও প্রভাব ব্যাখ্যা করুন।

Mapping network — StyleGAN-এর সবচেয়ে subtle কিন্তু প্রভাবশালী innovation। এটি ছাড়া photorealism সম্ভব হতো না।

Vanilla GAN-এ সমস্যা:

  • $z \sim \mathcal{N}(0, I)$ — Gaussian, isotropic।
  • Real-world face distribution Gaussian না — "অল্প বয়স + ধূসর চুল" rare combination।
  • $z$-কে directly inject করলে — generator-কে এই unrealistic combination "force" করতে হয়।
  • ফলে latent-এ entangled features — একটি direction পাল্টালে multiple feature change।

Mapping network-এর সমাধান:

  • $f(z) = w$, $f$ একটি 8-layer MLP।
  • $\mathcal{W}$ space সীমাবদ্ধ data manifold-এ — Gaussian shape থেকে মুক্ত।
  • Generator $w$-কে input হিসেবে নেয়, $z$ না।
  • $\mathcal{W}$-এর axis-aligned direction prefer-able — disentangled feature।

Disentanglement মেট্রিক্স:

  • Perceptual Path Length (PPL): $w$-space-এ short interpolation path → smaller perceptual change. StyleGAN paper-এর Figure ৩ এই ভাল।
  • Linear separability: "smile/no-smile" linear classifier $\mathcal{W}$-তে অনেক ভাল কাজ করে $\mathcal{Z}$-র চেয়ে।

Practical impact:

  • Image editing: "InterFaceGAN" (Shen et al., ২০২০) — $\mathcal{W}$-তে linear direction খুঁজে "older/smile/glasses" edit।
  • Style mixing: কয়েক layer-এ এক $w$, বাকিতে অন্য — coarse vs fine swap।
  • Inversion: "real photo + StyleGAN" — image কে $w$-এ map করে edit। Pivotal Tuning (Roich et al., ২০২২)।

Theoretical link:

  • $\mathcal{Z}$ হলো prior distribution; $\mathcal{W}$ "learned latent"।
  • Diffusion-এর $\mathcal{W}+$-style intermediate space (StyleGAN-এর per-layer $w$) — একই idea।
  • LDM (latent diffusion)-এ VAE encoder-এর latent এই principle ছড়িয়ে।

মূল উপলব্ধি: "Latent space হোক structured" — এই principle modern generative AI-র backbone। Mapping network এই principle-এর সবচেয়ে প্রভাবশালী implementation।

প্র ০২ StyleGAN3-এর "alias-free" approach — signal processing-এর কোন principle এখানে কাজ করছে? Aliasing CNN-এ কেন artifact তৈরি করে?

StyleGAN3 (Karras et al., ২০২১, NeurIPS) generative AI-তে signal processing-এর fundamental principle ফিরিয়ে আনল। এটি একটি rare পেপার যেখানে DSP theory deep learning architecture পাল্টায়।

Aliasing — basics:

  • Nyquist-Shannon sampling theorem (১৯৪৯): sample rate $f_s$-এ signal-এ $f > f_s/2$ frequency থাকলে — aliased low-frequency artifact দেখা যায়।
  • Spinning wheel video-তে wheel "পিছনে ঘুরছে" দেখা — classic aliasing।
  • Audio-তে high-pitch signal অপ্রত্যাশিত low-pitch হয়ে আসা।

CNN-এ aliasing কোথায়:

  • Pointwise nonlinearity (ReLU, GELU): input bandlimited হলেও — output infinite frequency content। Subsequent downsampling/upsampling alias।
  • Strided convolution & nearest-neighbor upsampling: proper anti-aliasing filter ছাড়াই signal sample।
  • Result: "texture sticking" — head ঘুরালে কিছু feature pixel grid-এ আটকে থাকে, ঘুরে না।

StyleGAN3-এর ফিক্স:

  • Continuous interpretation: feature map-কে discrete grid না, continuous signal হিসেবে চিন্তা।
  • Proper bandlimit: upsample-এর আগে low-pass filter; nonlinearity-এর আগে oversampling।
  • Translation/rotation equivariance: input shift হলে output হুবহু shift।
  • Fourier features-এ transition: মূলত একটি rotational pattern শেখা।

Practical impact:

  • Animation video-এ চুল natural ভাবে নড়ে — "stuck to camera" না।
  • Latent interpolation সময় feature smooth flow করে।
  • FFHQ-এ FID প্রায় same (StyleGAN2-এর তুলনায়), কিন্তু video quality অসাধারণ ভাল।

খরচ:

  • Training compute ২× বাড়ে (oversampling-এর জন্য)।
  • Inference একই — actual deployment-এ overhead নেই।

Wider lesson — DL-এ signal processing:

  • Anti-aliased CNN classifiers (Zhang, ২০১৯) — translation invariance বাড়ে।
  • Diffusion model-এ Fourier feature embedding — timestep encoding।
  • NeRF, Gaussian splatting — continuous representation। StyleGAN3 এই trend-এর অংশ।

মূল উপলব্ধি: Deep learning সবসময় শুধু "data দাও, training চালাও" না। Classical signal processing/physics principle properly apply করলে — quality leap সম্ভব। StyleGAN3 এই দর্শনের একটি landmark example।

প্র ০৩ Diffusion model-এর তুলনায় StyleGAN আজ কোথায় এগিয়ে, কোথায় পিছিয়ে? Application-ভেদে কোনটি বাছবেন?

২০১৮-২০২১ পর্যন্ত StyleGAN ছিল image generation-এর গোল্ড স্ট্যান্ডার্ড। ২০২২ থেকে diffusion (Stable Diffusion, DALL-E 2, Imagen) প্রায় সব front-এ এগিয়ে। কিন্তু StyleGAN আজও কিছু area-তে dominant।

StyleGAN-এর সুবিধা:

  • Inference গতি: single forward pass — milliseconds। Diffusion-এ ২০-৫০ steps।
  • Latent space structure: $\mathcal{W}/\mathcal{W}+$ explicit, edit-able। Diffusion-এর latent ততটা clean না।
  • Quality at narrow domain: FFHQ face-এ এখনো top-tier।
  • Smaller model: ~৩০M parameter, mobile inference সম্ভব।
  • GAN inversion mature: real photo → latent → edit — well-studied।

Diffusion-এর সুবিধা:

  • Diversity: mode collapse নেই; full distribution capture।
  • Training stable: GAN-এর adversarial instability নেই — single MSE-style objective।
  • Text conditioning: CLIP/T5 text encoder + cross-attention — "Bangladeshi village scene" prompt কাজ করে।
  • Multi-domain: face, scene, art — সব domain একই model।
  • Compositional: ControlNet, inpainting, IP-Adapter — extension সহজ।
  • Quality at scale: large compute দিলে diffusion StyleGAN-কে ছাড়িয়ে যায়।

Application-ভেদে recommendation:

  • Real-time face filter (mobile app): StyleGAN3 — fast inference।
  • Open-domain text-to-image: Stable Diffusion।
  • Specific domain (medical X-ray, astronomy): StyleGAN-এ fine-tune ভাল কাজ করে।
  • Image editing (semantic): StyleGAN inversion + W-direction edit — fastest।
  • Compositional control: ControlNet (diffusion)।
  • Animation (consistent identity): StyleGAN3 অথবা diffusion + identity loss।

Hybrid approaches:

  • StyleGAN-XL — diffusion-এর কাছাকাছি quality, GAN-এর gতি।
  • GigaGAN (Adobe, ২০২৩) — text-to-image GAN reborn।
  • Diffusion-GAN hybrid (Adversarial Diffusion Distillation) — diffusion-কে fast করে।

Bangladesh context:

  • Daraz product: Stable Diffusion-এ inpainting + LoRA।
  • Bangla wedding photo enhancement: StyleGAN inversion + edit।
  • Telco campaign synthetic models: StyleGAN3 fine-tune small dataset-এ।

মূল উপলব্ধি: "GAN dead, diffusion winner" — এই narrative oversimplified। প্রতিটি technology নিজস্ব niche রাখে। আজকের best engineer দু'টোই জানেন এবং right tool বাছেন।

প্র ০৪ StyleGAN-এ একটি বাংলা পুরুষ মুখের realistic image generate করতে চান — কী challenge? FFHQ pretrained model কেন insufficient হতে পারে, কী করবেন?

FFHQ (Flickr Faces HQ) — StyleGAN-এর মূল face dataset, ৭০,০০০ image। কিন্তু এটি predominantly Western face — South Asian faces underrepresented। বাংলা context-এ deploy করতে এটি critical issue।

Pretrained FFHQ-এর limitation:

  • Skin tone distribution skewed lighter towards European।
  • Facial structure (cheekbones, eye shape) South Asian থেকে আলাদা।
  • Cultural attire (পাঞ্জাবী, টুপি, ফেজ) absent।
  • Beard pattern, hair texture South Asian-specific।
  • "Average" face → বাংলা context-এ "অপরিচিত" দেখায়।

Strategy:

(১) Data collection:

  • Public Bangladeshi face dataset — খুব কম। নিজে সংগ্রহ করতে হবে (consent issue)।
  • Bangla movie/TV celebrity public photo (with rights)।
  • YouTube channel scrape (face detect + crop) — copyright/ethical caution।
  • Commercial face dataset (FaceLab, ATTRIBUTES) — license check।
  • Bangla wedding photographer-দের সাথে partnership।

(২) Privacy & ethics:

  • Consent — synthetic face generate করলে "real person resemblance" issue।
  • Bangladesh Data Protection guideline।
  • Differential privacy training consider।
  • Watermarking (SynthID-style) — synthetic flag।
  • Deepfake misuse — strong terms of service।

(৩) Model adaptation:

  • FreezeD fine-tune: FFHQ pretrained → small Bangla dataset (১,০০০-৫,০০০)। Discriminator-এর কিছু layer freeze।
  • StyleGAN-NADA (Gal et al., ২০২১) — CLIP-guided domain adaptation, very few image-এ কাজ করে।
  • LoRA-style adaptation — few parameter update।
  • Mining-অভ্যাস (StyleGAN2-ADA) — small dataset-এ adaptive augmentation।

(৪) Quality evaluation:

  • FID limited — Inception ImageNet-trained, South Asian face-এ bias।
  • Native Bangladeshi reviewer panel — "এটা real-looking?", "Cultural appropriate?"।
  • Skin tone distribution check — ITA value diverse।
  • Memorization check — training image নিকটতম nearest neighbor।

(৫) Production safeguards:

  • API-তে real face inversion disable।
  • Generated face-এ visible watermark।
  • Deepfake detection integration।
  • Content moderation — no real person resemblance threshold।

Alternative:

  • Stable Diffusion XL + Bangla LoRA — text prompt "Bangladeshi man, traditional attire" + LoRA fine-tune।
  • Diversity + flexibility বেশি — কিন্তু inference ধীর।

মূল উপলব্ধি: Generative AI Bangladesh-এ deploy করা শুধু technical না — data, ethics, cultural validation-এর সমন্বয়। ABCL TECH-এর মতো প্রতিষ্ঠানের জন্য এটি responsibility ও opportunity দু'টোই।

অনুশীলন

  1. হাতে-কলমে: $4 \times 4 \times 1024 \to 64 \times 64 \times 3$ DCGAN generator-এ কয়টি transposed conv layer? প্রতিটি stage-এ output shape লিখুন।

    ৪টি stride-2 layer (each 2× upsample): $4 \to 8 \to 16 \to 32 \to 64$।

    • L1: (1024, 4, 4) → (512, 8, 8)
    • L2: (512, 8, 8) → (256, 16, 16)
    • L3: (256, 16, 16) → (128, 32, 32)
    • L4: (128, 32, 32) → (3, 64, 64) — Tanh output।
  2. কোডে চেষ্টা: StyleGAN-এর AdaIN-কে PyTorch-এ implement করুন একটি function হিসেবে।
    def adaIN(x, y_s, y_b, eps=1e-8):
        # x: (B, C, H, W); y_s, y_b: (B, C)
        mu = x.mean(dim=(2,3), keepdim=True)
        std = x.std(dim=(2,3), keepdim=True) + eps
        x_norm = (x - mu) / std
        return y_s.unsqueeze(2).unsqueeze(3) * x_norm \
             + y_b.unsqueeze(2).unsqueeze(3)

    $y_s, y_b$ একটি linear layer থেকে আসে যা $w$-কে input হিসেবে নেয়।

  3. ভাবুন: বাংলাদেশী fashion model এর জন্য StyleGAN ব্যবহার করতে চান। ১,০০০ image আছে। কী strategy?
    • FFHQ pretrained → freeze coarse layers, fine-tune middle/fine।
    • StyleGAN2-ADA-র adaptive augmentation (১,০০০ image-এ doable)।
    • StyleGAN-NADA-style CLIP-guided domain shift consider।
    • প্র ০৪-এ বিস্তারিত আছে।

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

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