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

Sampling — কীভাবে নতুন ডেটা তৈরি হয়

Sampling techniques — turning probability into data
৬ মিনিট পড়া উচ্চ · Advanced Inverse-CDF · MCMC · Langevin

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

  • Sampling-এর মূল প্রশ্ন — density জানা সহজ, কিন্তু sample হার্ড কেন
  • Classical methods: inverse-CDF, rejection, ancestral, MCMC
  • Score-based & Langevin dynamics — Diffusion-এর foundation
  • GAN, VAE, Diffusion-এর sampling কীভাবে আলাদা

১ · Sampling-এর মৌলিক প্রশ্ন

SamplingSamplingএকটি probability distribution থেকে concrete realization তোলা। গাণিতিকভাবে $x \sim p(x)$ — random variable-এর "instantiation"। Generative AI-র সব output sampling। মানে — distribution থেকে concrete value তোলা। Density $p(x)$ জানা থাকলেও — সেই distribution থেকে actually sample তোলা সবসময় easy না।

Computer-এ মূলত একটাই random source — uniform $[0,1]$। সব complex sampling এই uniform থেকে transform-এর মাধ্যমে।

দু'টি ভিন্ন প্রশ্ন

১) Density evaluate: "এই $x$-এর probability কত?" — সহজ।
২) Sample generate: "এই distribution থেকে নতুন $x$ দাও।" — অনেক সময় কঠিন।

২ · Inverse-CDF — সবচেয়ে সরল

১-D-এ যেকোনো distribution থেকে sample-এর universal trick:

  1. $u \sim \text{Uniform}(0, 1)$।
  2. $x = F^{-1}(u)$ যেখানে $F$ — CDF।

Theorem (Probability Integral Transform): যদি $u \sim U(0,1)$, তাহলে $F^{-1}(u)$ distribution $F$ থেকে sample।

একটি লটারি ভাবুন। Uniform $u \in [0,1]$ — এক টিকিট। CDF $F$ — কোন winner কত range cover করে। গুলশান-এ ৪০%, ধানমন্ডি-তে ৩০%, পুরান ঢাকা-তে ৩০% হলে — $u = 0.55$ → ধানমন্ডি জিতল। এটাই inverse-CDF।

সমস্যা: $F^{-1}$ closed form-এ থাকতেই হবে। Gaussian-এর জন্য নেই — Box-Muller transform ব্যবহার হয়।

৩ · Rejection Sampling

Target $p(x)$ থেকে sample চাই, কিন্তু $F^{-1}$ unavailable। Solution: একটি easy distribution $q(x)$ বাছুন (যা থেকে easy sample) এবং $p(x) \leq M \cdot q(x)$ for সব $x$।

  1. $x \sim q(x)$ — easy distribution থেকে।
  2. $u \sim U(0, 1)$।
  3. If $u \leq \frac{p(x)}{M \cdot q(x)}$, accept; নয়তো reject।

সমস্যা: High-D-এ acceptance rate exponentially small। ১০০-D-এ $1/10^{50}$ rate — practical না।

৪ · Ancestral Sampling — graphical model-এ

Latent variable model-এ — যেখানে $p(x, z) = p(z) p(x|z)$ — sampling trivial:

  1. $z \sim p(z)$।
  2. $x \sim p(x|z)$।

VAE, GAN — উভয়েই ancestral। GAN: $z \sim \mathcal{N}(0, I)$, $x = G(z)$। VAE: একই pattern, $G$-র জায়গায় decoder।

৫ · Markov Chain Monte Carlo (MCMC)

যখন কেবল unnormalized density জানা — $\tilde{p}(x) = Z \cdot p(x)$ — যেখানে $Z$ unknown। তখন MCMCMarkov Chain Monte Carloএকটি Markov chain construct করে যেখানে stationary distribution = target $p(x)$। Long enough run করলে — chain-এর state target থেকে sample। Bayesian inference-এর মেরুদণ্ড।।

Metropolis-Hastings algorithm:

  1. Start at $x_0$।
  2. Propose $x' \sim q(x' | x_t)$।
  3. Compute $\alpha = \min\left(1, \frac{\tilde{p}(x') q(x_t | x')}{\tilde{p}(x_t) q(x' | x_t)}\right)$।
  4. Accept $x'$ with probability $\alpha$।
  5. Repeat — eventually $x_t \sim p(x)$।

Metropolis-Hastings (Metropolis ১৯৫৩, Hastings ১৯৭০) — physics থেকে statistics-এ মাইগ্রেট। Stan, PyMC — সব Bayesian library-র backbone।

সমস্যা: Slow mixing, autocorrelated samples, high-D-এ rejection বেশি।

৬ · Langevin Dynamics — score-based sampling

MCMC-এর gradient-aware variant। Idea: density-র gradient (score) follow করো:

$$x_{t+1} = x_t + \frac{\eta}{2} \nabla_x \log p(x_t) + \sqrt{\eta} \, \epsilon_t, \quad \epsilon_t \sim \mathcal{N}(0, I)$$

Physics-এ Langevin equation — particle-এর random + drift motion। Statistics-এ — high-density region-এর দিকে বরাবর "চলা" + noise।

Score function $\nabla_x \log p(x)$ — generative AI-র heart। Diffusion model-এ এটাই শেখা হয়, এবং Langevin sampling দিয়ে data generate। Song & Ermon (২০১৯) — score-based generative modeling-এর foundational paper।

৭ · Modern generative model-এর sampling

  • GAN: $z \sim \mathcal{N}(0, I)$, $x = G(z)$। Single forward pass — fast। Density unknown।
  • VAE: $z \sim \mathcal{N}(0, I)$, $x \sim p(x|z) = \mathcal{N}(x; \mu_\theta(z), \sigma_\theta(z))$। Ancestral, fast।
  • Autoregressive (GPT, PixelCNN): $x_i \sim p(x_i | x_{
  • Normalizing Flow: $z \sim p(z)$, $x = f(z)$ (invertible)। Single pass, exact density।
  • Diffusion: $x_T \sim \mathcal{N}(0, I)$, iteratively $x_{t-1} = $ denoise$(x_t)$ for $t = T, T-1, \ldots, 1$। Slow (১,০০০ step originally, এখন ৪-৫০)।
Sampling — Uniform থেকে Complex Data all start with u ~ U(0,1) Uniform U(0, 1) Inverse-CDF x = F⁻¹(u) — ১-D best Ancestral (z → x) VAE, GAN — fast Rejection accept/reject — fails high-D MCMC Metropolis, Gibbs — Bayesian Langevin / Score Diffusion — modern SOTA → যেকোনো distribution থেকে concrete sample x₁ x₂ x₃ … xₙ → ছবি, লেখা, audio, video
সব sampling-এর source uniform $U(0,1)$। ভিন্ন method ভিন্ন complexity ও applicability — modern AI-তে Langevin/score dominant।

৮ · Python-এ চারটি sampling method

প্রতিটি method-এর demo — same target distribution-এ।

Python · NumPy
import numpy as np

# Target: exponential distribution p(x) = e^(-x) for x > 0
# True mean = 1.0

# (1) Inverse-CDF: F(x) = 1 - e^(-x), F⁻¹(u) = -log(1-u)
n = 5000
u = np.random.uniform(0, 1, n)
x_inv = -np.log(1 - u)
print(f"Inverse-CDF mean: {x_inv.mean():.3f} (expected 1.0)")

# (2) Rejection: q = uniform on [0, 10], M = 1
x_rej = []
while len(x_rej) < n:
    x_prop = np.random.uniform(0, 10)
    u = np.random.uniform(0, 1)
    if u <= np.exp(-x_prop):  # p(x) / (M*q(x)) = e^(-x)
        x_rej.append(x_prop)
x_rej = np.array(x_rej)
print(f"Rejection mean: {x_rej.mean():.3f}")

# (3) Metropolis-Hastings (MCMC)
x_mcmc = [1.0]
for _ in range(n - 1):
    x_curr = x_mcmc[-1]
    x_prop = x_curr + np.random.normal(0, 0.5)
    if x_prop > 0:
        ratio = np.exp(-(x_prop - x_curr))
        if np.random.uniform() < ratio:
            x_mcmc.append(x_prop)
            continue
    x_mcmc.append(x_curr)
x_mcmc = np.array(x_mcmc[1000:])  # burn-in
print(f"MCMC mean: {x_mcmc.mean():.3f}")

# (4) Langevin (score = -1 for exponential)
x_lan = 1.0
samples = []
eta = 0.05
for _ in range(n + 1000):
    score = -1.0  # for exponential, ∇log p = -1
    x_lan = x_lan + 0.5 * eta * score + np.sqrt(eta) * np.random.normal()
    if x_lan > 0:
        samples.append(x_lan)
samples = np.array(samples[1000:])
print(f"Langevin mean: {samples.mean():.3f}")

    
চারটি method-ই ~১.০ mean পাবে — সব valid sampling। কিন্তু efficiency, scalability, generality-তে পার্থক্য বিশাল। High-D-এ inverse-CDF impossible, rejection wasteful, MCMC slow, Langevin ভালো।

৯ · Sampling speed — modern AI-র চ্যালেঞ্জ

Generation speed = practical bottleneck:

  • GAN: ১ forward pass → ০.১ second per image (StyleGAN3)। Real-time ভাল।
  • VAE: ১ pass + decoder, similar speed।
  • Autoregressive (GPT-4): Token-by-token, ৫০-১০০ tokens/sec। Long output-এ slow।
  • Diffusion (original DDPM): ১,০০০ step × ১ pass = ১,০০০ pass per image। Stable Diffusion-এ ৫০ step optimized।
  • Modern Diffusion (DDIM, DPM-Solver, LCM): ৪-৮ step possible — distillation-এর মাধ্যমে।
Sampling speed = AI's biggest UX bottleneck। ChatGPT response time ১-৫ sec — token-by-token generation। Sora-র video generation-এ minutes লাগে। Distillation, parallel sampling, speculative decoding — সব এই speed-এর জন্য।

১০ · Controlled Sampling — modern era

Plain sampling বাদ দিয়ে — আজ control-যুক্ত sampling মূলধারায়:

  • Conditional sampling: $x \sim p(x | y)$ — text → image। Classifier guidance (Dhariwal & Nichol, ২০২১), CFG (Ho & Salimans, ২০২২)।
  • Temperature: $p(x)^{1/T}$ — $T = 1$ default; $T > 1$ diverse, $T < 1$ peaky।
  • Top-k, top-p (nucleus): LLM-এ token sampling regulate।
  • Beam search: Greedy alternative — multiple path explore।
  • RLHF guided: Reward model-এর preferences-এ aligned sampling।
Sampling subtle — temperature, top-p একটু এদিক ওদিক করলে ChatGPT-র character-ই বদলে যায়। Production-এ এই hyperparameter careful tuning দরকার। Engineering art।

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

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

প্র ০১ Diffusion model ১,০০০ step নেয় — GAN ১ step। তবু Diffusion আজ SOTA। এই সময়-quality trade-off-এর গভীর কারণ কী? Sampling speed-up-এর research কোথায়?

এটা ২০২০-পরবর্তী generative AI-র সবচেয়ে গুরুত্বপূর্ণ debate। GAN ৫ বছর dominant ছিল; Diffusion ২০২২-এ সবকিছু পাল্টে দিল।

কেন iterative sampling ভালো:

  • (১) Easier optimization: Single-step generation-এ — model-কে $z \to x$ একবারে শিখতে হয়। High-D non-linear mapping unstable। Iterative-এ — প্রতিটি step ছোট, smooth, easier।
  • (২) Mode coverage: GAN-এর mode collapse — sample diversity কম। Diffusion প্রতিটি step-এ noise inject — সব mode reach।
  • (৩) Score function geometry: $\nabla \log p$ everywhere defined, smooth। Direct generator-এ এই smoothness নেই।
  • (৪) Composition & control: Each step intervene-able — guidance, inpainting, super-resolution easily implement।

কেন slow সমস্যা:

  • UI latency — user 5 sec-এর বেশি wait করতে চায় না।
  • Cost — ১,০০০ step = ১,০০০x compute = ১,০০০x dollar।
  • Mobile inference impossible at full step count।
  • Real-time application (game, video) infeasible।

Speed-up research — পাঁচটি direction:

  • (১) Better solvers: DDIM (Song et al., ২০২১) — deterministic, ১,০০০ → ৫০ step। DPM-Solver (Lu et al., ২০২২) — ১০-২০ step। ODE-based, mathematically motivated।
  • (২) Distillation:
    • Progressive distillation (Salimans & Ho, ২০২২) — student model teacher-এর ২ step একসাথে শিখে।
    • Consistency models (Song et al., ২০২৩) — single-step generation।
    • Latent Consistency Model (LCM, ২০২৩) — Stable Diffusion ২-৪ step।
  • (৩) Latent diffusion: Pixel space-এ না, low-D latent space-এ diffuse। Stable Diffusion-এর core idea — ৬৪x compute reduction।
  • (৪) Hybrid GAN-Diffusion: Adversarial Diffusion (ADD) — Stability AI-র SDXL Turbo, ১ step real-time।
  • (৫) Caching: Common prefix-এর computation cache — repeated query optimize।

2024-25 state of the art:

  • SDXL Turbo: 1 step, 207ms per image।
  • Flux Schnell: 4 step, near-instant।
  • SD3: 28 step balanced quality।
  • Sora (video): minutes per clip — still slow।

Theoretical question:

  • Single-step quality ceiling কী? Distillation lossy — original-এর কাছে পৌঁছানো যায় না সম্পূর্ণ।
  • "4-step Diffusion ≈ 50-step quality?" — প্রায়, কিন্তু subtle artifact।
  • Inference compute scaling (o1, o3) — same trend reasoning-এ।

Bangladesh implications:

  • Mobile-first market — fast sampling critical।
  • Bandwidth limited — on-device inference জরুরি।
  • Distilled models — Bangladesh startups-এর জন্য affordable AI-র চাবিকাঠি।

মূল উপলব্ধি: Iterative sampling Diffusion-এর strength (quality, control) এবং weakness (speed)। ২০২২-২০২৫ research অনেকটা এই trade-off optimize-এ centered। Future: 1-step quality matching 1000-step — distillation-এর holy grail। GAN-এর speed + Diffusion-এর quality = next-gen generative AI।

প্র ০২ ChatGPT-এ "temperature = 0" দিলে deterministic, "temperature = 2" দিলে gibberish। এই sampling parameter-এর গাণিতিক ভিত্তি কী, এবং production-এ choice কীভাবে?

Temperature — language model sampling-এর সবচেয়ে important hyperparameter। Boltzmann distribution থেকে borrowed।

গাণিতিক ভিত্তি:

LLM token output হয় logits $\ell_i$ vector (vocabulary size, e.g. ৫০,০০০)। Probability:

$$p_i = \frac{\exp(\ell_i / T)}{\sum_j \exp(\ell_j / T)}$$

  • $T = 1$ — softmax default।
  • $T \to 0$ — argmax (greedy)। Top probability = 1, others = 0।
  • $T \to \infty$ — uniform। সব token সমান।
  • $T = 0.7$ — common default — slight diversity।

Boltzmann analogy:

  • Physics-এ — high $T$ = high entropy, particles চারদিকে ছড়ায়; low $T$ = particles ground state-এ।
  • LLM-এ — high $T$ = creative; low $T$ = boring but accurate।

Pure temperature-এর সমস্যা:

  • Even at moderate $T$ — long tail-এর low-probability garbage token sometimes selected।
  • Rare event accumulate over hundreds of tokens — single nonsense token whole response break।

Top-k sampling:

  • Top $k$ token-এ truncate, normalize, sample।
  • $k = 50$ — common। Tail nonsense block।
  • সমস্যা: $k$ fixed; কখনো ৩-টা token-ই plausible, কখনো ১০০।

Top-p (nucleus) sampling — Holtzman et al. (২০২০):

  • Cumulative probability $\geq p$ পর্যন্ত token-এ truncate।
  • $p = 0.9$ — adaptive set size।
  • Production-এ default — flexibility বেশি।

আরো advanced:

  • Min-p (২০২৩): Top token-এর $p \cdot p_{\max}$-এর নিচে cut। Better at low-temperature।
  • Typical sampling: "Average information" preserve।
  • Mirostat: Adaptive temperature — perplexity target follow।
  • Repetition penalty: Recently-used token-এর probability discount।

Use case-অনুযায়ী choice:

  • Code generation: $T = 0.0$-$0.2$। Single best answer চাই।
  • Factual QA: $T = 0.0$-$0.3$। Hallucination কম।
  • Summarization: $T = 0.3$-$0.5$। Slight variation।
  • Creative writing: $T = 0.7$-$1.0$। Diversity।
  • Brainstorming: $T = 1.0$-$1.3$ + top-p 0.95। Wild ideas।
  • Roleplay/chat: $T = 0.7$-$0.9$ + repetition penalty।

Production engineering wisdom:

  • A/B test temperature — user satisfaction signal।
  • Different task-এ different temperature — system prompt-এ override।
  • Beam search expensive — sampling preferred।
  • Reproducibility-এর জন্য seed save।

Bangladesh-specific:

  • Bangla generation-এ — slightly higher temperature, কারণ token vocabulary-এ Bangla underrepresented।
  • Code-mixed (Banglish) — moderate temp; full Bangla — higher।
  • Customer service bot — low temp (consistency)।

মূল উপলব্ধি: Sampling parameter — generative AI-র "personality knob"। Same model-এ ভিন্ন temperature ভিন্ন agent-এর মতো behave। Engineering art = use case-অনুযায়ী tune। ChatGPT, Claude — production-এ এই tuning হাজার ঘণ্টার A/B testing-এর result।

প্র ০৩ Bangladesh-এর dengue outbreak prediction — Bayesian inference + MCMC sampling-এ। কীভাবে এই pipeline design হবে, এবং traditional epidemiology-র সাথে পার্থক্য কী?

Bangladesh-এ dengue ২০২৩-এ ৩,০০০+ মৃত্যু — record high। Climate change + urban density এ রোগ আরো dangerous করেছে। Bayesian + MCMC এ context-এ powerful।

Traditional epidemiology approach:

  • SIR model — Susceptible, Infected, Recovered। ODE-based deterministic।
  • Parameter (R0, recovery rate) point estimate।
  • Output: single trajectory prediction।
  • সমস্যা: uncertainty quantification weak; rare event modeling poor; data heterogeneity miss।

Bayesian + MCMC approach:

Step 1 — Hierarchical model:

  • Per-district transmission rate $R_d$ — district-specific।
  • Hyper-prior: $R_d \sim \mathcal{N}(\mu_R, \sigma_R^2)$ — district-গুলো related।
  • Observation: weekly case count → likelihood (Poisson)।
  • Latent: actual infection (under-reporting consider)।

Step 2 — Covariate inclusion:

  • Rainfall (lag 2-3 weeks) — Aedes mosquito breeding driver।
  • Temperature — vector survival।
  • Population density — contact rate।
  • Drainage quality — water stagnation।
  • Past outbreak — herd immunity proxy।

Step 3 — MCMC sampling:

  • Posterior $p(\theta | \text{data})$ — analytically intractable।
  • Stan, PyMC দিয়ে NUTS (No-U-Turn Sampler) — modern HMC variant।
  • 4 chains, 10,000 iterations — convergence check (R-hat $< 1.01$)।
  • Output: full posterior — uncertainty quantified।

Step 4 — Predictive sampling:

  • Posterior থেকে parameter sample → forward simulate।
  • Each district-এ prediction interval।
  • "Dhaka-তে next 4 weeks-এ ৯৫% probability ১০,০০০-৩০,০০০ case।"
  • Single number-এর চেয়ে অনেক বেশি actionable।

Operational dashboards:

  • DGHS (Directorate General of Health Services) দৈনিক update।
  • District-level risk heatmap।
  • Hospital bed allocation forecast।
  • Vector control deployment optimization।

Why MCMC over alternatives:

  • vs ML (XGBoost): ML accuracy ভালো, but uncertainty estimate poor; causal interpretation নেই।
  • vs deterministic ODE: No uncertainty; single scenario।
  • vs variational inference: VI faster, but approximate posterior; rare-event modeling MCMC better।

Bangladesh-specific challenges:

  • Data quality: Many cases unreported — likelihood under-estimate।
  • Spatial heterogeneity: Dhaka, Chittagong, Sylhet — distinct dynamics।
  • Climate input: BMD weather data integrate।
  • Strain variation: DENV-1, DENV-2, etc. — different severity profile।
  • Computational: MCMC slow; cloud compute দরকার।

Real-world precedent:

  • Imperial College London-এর COVID model — Bayesian hierarchical।
  • Stockholm-এর dengue surveillance।
  • ICDDR,B Bangladesh-এ — collaboration possible।

Decision-making impact:

  • "$৩-week peak in zone X" → hospital beds pre-allocated।
  • Spray timing — mosquito breeding peak before।
  • Public messaging — risk-based, not blanket।
  • Ambulance routing — predicted hotspot।

মূল উপলব্ধি: Sampling গাণিতিক tool, কিন্তু impact অনেক বড় — public health, policy, life-and-death decision। Bangladesh-এ এই capability-র জন্য — Bayesian-trained statistician, ML engineer, epidemiologist-এর collaboration। DGHS + IT/AI startup + universities — এই triad সম্ভাবনা।

প্র ০৪ "Mode collapse" GAN-এর কুখ্যাত সমস্যা। কেন ঘটে, কেন diversity matters, এবং Diffusion এই সমস্যা কীভাবে সমাধান করে?

Mode collapse — GAN-এর সবচেয়ে frustrating problem। ২০১৪ থেকে ২০২২ — research-এর অনেকটা এর সমাধানে spent।

কী ঘটে:

  • GAN trained on diverse data — face, dog, car।
  • Output: শুধু কিছু "easy" face বার বার generate। Dog, car miss।
  • Even within faces — same age, ethnicity, expression repeated।
  • Diversity quantitatively poor — IS, FID metric capture।

কেন ঘটে — গাণিতিকভাবে:

  • (১) Min-max non-convexity: $$\min_G \max_D \mathbb{E}[\log D(x)] + \mathbb{E}[\log(1 - D(G(z)))]$$ Saddle point — equilibrium achieve কঠিন।
  • (২) Discriminator local minima: Generator-এর কিছু "good fakes" — discriminator distinguish করতে পারে না — generator সেখানেই stuck।
  • (৩) Reverse KL behavior: GAN effectively reverse KL minimize — "mode seeking" — single mode-এ collapse natural tendency।
  • (৪) Gradient signal weak: Discriminator confident-এ — generator-এ vanishing gradient। Diversity exploration impossible।

কেন diversity matters:

  • Realism: Real data diverse — model-ও হতে হবে।
  • Fairness: Mode collapse-এ minority group erased। AI-generated stock photos: শুধু white face — ethical disaster।
  • Downstream task: Synthetic data augmentation — diversity না থাকলে কাজে লাগে না।
  • Scientific use: Drug discovery — diverse molecules essential।
  • Creative: Art, music — same output বারবার boring।

GAN solutions — যা কাজ করেছে:

  • Mini-batch discrimination: Discriminator-কে batch দেখায়, similarity penalize।
  • Wasserstein GAN (২০১৭): Different loss — smoother gradient।
  • Spectral normalization: Discriminator stable।
  • Progressive growing (PGGAN): Low-res থেকে শুরু — diversity preserve।
  • StyleGAN truncation trick: Latent space restrict — quality vs diversity trade-off explicit।

Diffusion কেন better:

  • (১) Likelihood-based training: Forward KL — mode covering। সব mode-এ probability assign বাধ্য।
  • (২) Stable training: Single network, denoising loss — minimax নয়। Convergence reliable।
  • (৩) Stochastic sampling: Each step-এ noise inject — exploration natural। Even if model biased, sampling diverse।
  • (৪) Score function geometric: $\nabla \log p$ everywhere defined — no "dead zone" generator-এর moded।
  • (৫) Empirical: Stable Diffusion, Sora — vastly more diverse than equivalent GAN।

Diffusion-এর own mode issues:

  • Training data bias — model bias। "Doctor" prompt → mostly male।
  • Lower-frequency mode under-represented at fewer steps।
  • CFG (classifier-free guidance) high-scale — diversity hurt।

Modern hybrid ideas:

  • Adversarial Diffusion (SDXL Turbo): Diffusion training + adversarial fine-tune — speed + diversity।
  • Flow matching: Diffusion-এর simpler variant — similar diversity।
  • Consistency models: Single-step + diversity preserved।

Bangladesh implications:

  • Bangla content generation — model "Dhaka middle-class" mode-এ collapse risk। Rural, regional — under-represented।
  • Image generation — South Asian face under-represented in many models।
  • Awareness + local data + bias evaluation — production deployment-এ critical।

মূল উপলব্ধি: Mode collapse generative AI-র "diversity vs ease" tension-এর representative। GAN sharp but narrow; Diffusion wide but slow। Modern era — দু'টোর সমন্বয়। Engineering ও ethics — উভয় aspect-এ এই issue critical। সঠিক sampling মানে সব mode-এ honest representation — শুধু statistics না, সমাজিক বিবেচনাও।

অনুশীলন

  1. হিসাব করুন: Inverse-CDF দিয়ে exponential distribution ($\lambda = 2$) থেকে sample। $u = 0.7$ হলে $x$ কত? ($p(x) = 2 e^{-2x}$, $F(x) = 1 - e^{-2x}$)

    $F(x) = u \implies 1 - e^{-2x} = 0.7 \implies e^{-2x} = 0.3$

    $\implies -2x = \ln(0.3) \approx -1.204$

    $\implies x \approx 0.602$।

  2. Code চেষ্টা: NumPy দিয়ে একটি Mixture of two Gaussians থেকে sample করুন (mean $-3, +3$; std $1$ both; weights $0.4, 0.6$)। Ancestral sampling ব্যবহার করুন।
    import numpy as np
    import matplotlib.pyplot as plt
    
    n = 2000
    # Step 1: latent z (component selection)
    z = np.random.choice([0, 1], size=n, p=[0.4, 0.6])
    
    # Step 2: sample x given z
    means = np.array([-3.0, 3.0])
    x = np.random.normal(means[z], 1.0)
    
    print(f"Mean: {x.mean():.2f}")
    print(f"Std: {x.std():.2f}")
    plt.hist(x, bins=50, color='#7c3aed', edgecolor='white')
    plt.title('Mixture of two Gaussians — ancestral sampling')
    plt.show()

    Histogram-এ দু'টি peak দেখা যাবে, weight-অনুযায়ী।

  3. ভাবুন: ChatGPT-কে আপনি ৫টি ভিন্ন creative writing prompt দিচ্ছেন। কোন temperature/top-p combination বাছবেন? Why?

    Recommended: $T = 0.8$, top-p $= 0.95$।

    • $T = 0.8$: যথেষ্ট creativity, কিন্তু coherence preserved।
    • top-p = 0.95: tail garbage block, ৫% থেকে নিচের token cut।
    • ৫টি prompt-এ ভিন্ন output — diversity বজায়।

    Alternative: $T = 1.0$, top-p $= 0.9$ — wilder; অথবা $T = 0.7$, top-p $= 1.0$ — more focused।

    Practical tip: একই prompt ৩-৫ বার generate, best select — production-এ common pattern।

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

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