পাঠ ৫ · ৩৩-এর মধ্যে · মডিউল ১
Home / AI Courses / MLOps / Reproducibility

Reproducibility — কেন ও কীভাবে

Reproducibility — why and how
৭ মিনিট পড়া মধ্য · Intermediate Python

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

  • ML reproducibility-এর ৪টি axis — কোথায় কী fix করতে হয়
  • Seed setup — Python, NumPy, PyTorch/TF
  • Environment lock — pip-tools, conda-lock, Docker pinning
  • Hardware ও cuDNN non-determinism — কখন accept, কখন strict

১ · কেন reproducibility গুরুত্বপূর্ণ

Reproducibility = "একই code, একই data, একই environment চালিয়ে — একই model পাব"। এটি বিজ্ঞান-এর ভিত্তি। কিন্তু ML system-এ এটা trivially অর্জিত হয় না।

  • Debugging: "৩ মাস আগের model এত ভাল ছিল — এখন এমন কেন?" — reproduce না করতে পারলে answer নেই।
  • Compliance: bank, healthcare — regulator চায় "এই decision কীভাবে এলো"।
  • Collaboration: অন্য team member-কে অভিন্ন setup দিতে।
  • A/B test integrity: control vs treatment — uniquely identifiable।

২ · ৪টি axis-এ reproducibility

Reproducibility-এর ৪টি pillar

১) Code: git commit hash।
২) Data: dataset version (DVC hash)।
৩) Environment: Docker image SHA + pinned packages।
৪) Randomness: seed (Python, NumPy, framework, CUDA)।

৩ · Code reproducibility

Git commit hash log করুন প্রতি training run-এ। MLflow auto-log করে — কিন্তু custom pipeline-এ explicitly log করতে হবে।

"Uncommitted changes না নিয়ে train" rule — দলে আবশ্যক। কারণ untracked changes কেউ আবার করতে পারবে না।

৪ · Data reproducibility

Data git-এ ভাল কাজ করে না (binary, large)। সমাধান:

  • DVCDVC (Data Version Control)git-এর মতো workflow কিন্তু large file/data-এর জন্য। Hash track করে; actual file remote storage-এ (S3, GCS, SSH)। Lesson 10। — Lesson 10-এ বিস্তারিত।
  • Git LFS — ছোট binary-এর জন্য।
  • S3 versioning — explicit version-id reference।
  • Snapshot timestamp — "as of 2025-01-15 02:00 UTC"।

৫ · Environment reproducibility

  • requirements.txt unpinned খারাপ: numpy মানে latest। আজ 1.26, কাল 2.0 — break।
  • requirements.txt pinned: numpy==1.26.4 — better।
  • Lock file: pip-tools (requirements.lock), conda-lock, Poetry — transitive dependencies-ও pin।
  • Docker: base image SHA pin (python:3.11.7-slim@sha256:...)।
  • OS-level deps: apt package version pin।

৬ · Randomness — seed everywhere

ML-এ randomness অনেক জায়গায়:

  • Train/test split shuffle।
  • DataLoader batch shuffle।
  • Weight initialization।
  • Dropout।
  • Data augmentation (random crop, flip)।
  • Negative sampling (recommender, contrastive)।

প্রতিটি Python interpreter-এ ৩টি PRNG state থাকে — Python random, NumPy, framework। তিনটিই set করতে হবে।

৭ · একটি seed-fix recipe

Python · Reproducibility utility
import os
import random
import numpy as np
import torch

def set_seed(seed: int = 42, strict: bool = False):
    """ML reproducibility — set all seeds + cuDNN flags."""
    random.seed(seed)
    np.random.seed(seed)
    torch.manual_seed(seed)
    torch.cuda.manual_seed_all(seed)
    os.environ["PYTHONHASHSEED"] = str(seed)

    if strict:
        # পরিপূর্ণ reproducibility — slower
        torch.backends.cudnn.deterministic = True
        torch.backends.cudnn.benchmark = False
        # PyTorch 1.8+
        torch.use_deterministic_algorithms(True, warn_only=True)
        os.environ["CUBLAS_WORKSPACE_CONFIG"] = ":4096:8"

def log_environment():
    import subprocess
    info = {
        "git_sha": subprocess.check_output(
            ["git", "rev-parse", "HEAD"]
        ).decode().strip(),
        "python": __import__("sys").version,
        "torch": torch.__version__,
        "cuda": torch.version.cuda,
        "gpu": torch.cuda.get_device_name(0) if torch.cuda.is_available() else "cpu",
    }
    print("=== Environment ===")
    for k, v in info.items():
        print(f"{k}: {v}")
    return info

# Use:
set_seed(42, strict=True)
log_environment()

    
প্রতিটি training script-এর শুরুতে এই দু'টো call। MLflow এই info auto-log করতে পারে; না হলে explicit log করুন।

৮ · Hardware non-determinism

cuDNN-এর কিছু operation (যেমন backward) non-deterministic — performance optimize করতে। এটি কখনো কখনো ০.১% accuracy variation দিতে পারে।

Bit-exact reproducibility বনাম practical reproducibility: বেশিরভাগ team-এর জন্য "same hyperparam + same data → ±0.5% accuracy" enough। Bit-exact (cuDNN deterministic) ১০-২০% slower। শুধু compliance-critical setup-এ on।

৯ · Reproducibility tax

  • Time: strict reproducibility setup — ১০-২০% slower training।
  • Storage: data version snapshots — অতিরিক্ত GB/TB।
  • Discipline: "uncommitted code-এ train করব না" — habit গড়তে সময় লাগে।
  • Infra cost: MLflow, DVC remote, registry — managed হলে monthly bill।

কিন্তু দীর্ঘমেয়াদে — debugging time, compliance fine, audit failure-এর তুলনায় এই cost ছোট।

Reproducibility — চারটি axis একসাথে fix model = f(code, data, environment, randomness) Model output 📝 Code git commit hash 📊 Data DVC hash / S3 version ⚙️ Environment Docker SHA + lock file 🎲 Randomness seed × 3 + cuDNN flag যেকোনো একটি axis fix না — model reproduce অসম্ভব
Model reproducibility = চার-axis একসাথে fix। যেকোনো একটি axis open হলে — same input থাকলেও ভিন্ন model আসতে পারে।
Practical recipe: প্রতিটি training run-এ MLflow-তে এই ৪টি axis log করুন। যেকোনো model later reproduce করতে — এই metadata থেকে environment recreate, seed apply।

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

প্র ০১ "Reproducibility tax" কী? কোন domain-এ কতটুকু strict reproducibility দরকার? Bangladesh-এর banking, healthcare, e-commerce — এই ৩টি প্রসঙ্গে।

Reproducibility-র cost সবসময়ই থাকে — কখন এই tax pay করা যুক্তিসঙ্গত, সেটা domain-নির্ভর।

Banking (high stakes, regulated):

  • Bangladesh Bank guideline (২০২৩) — AI credit decision-এর audit trail বাধ্যতামূলক।
  • "এই loan reject কেন হলো" — model-এর exact version + input + decision logic reproducible হতে হবে।
  • Strict reproducibility মাস্ট: cuDNN deterministic + immutable model registry + data snapshot per decision।
  • Tax: ১৫-২০% slower training, কয়েক কোটি storage cost — কিন্তু regulator fine ১০x বেশি।

Healthcare (life-critical):

  • Diagnosis support — "এই AI কেন এই recommendation দিল"। Doctor accountable।
  • Strict reproducibility absolute necessary। Plus: model audit + clinician sign-off chain।
  • Bangladesh-এ এই domain emerging — Praava, Maya সাবধানতা দরকার।
  • Tax acceptable, এমনকি wider — additional explainability also required।

E-commerce (low-stakes per decision):

  • Recommendation, search ranking — single decision-এ life-impact কম।
  • Statistical reproducibility ("similar quality model") যথেষ্ট। Bit-exact overkill।
  • A/B test-এ randomization handle হবে — perfect reproducibility না দরকার।
  • Tax minimization: lighter discipline — git commit log + seed + Docker, কিন্তু cuDNN deterministic না।

Decision framework:

  • প্রশ্ন ১: "এই decision-এর review লাগতে পারে?" Y → strict।
  • প্রশ্ন ২: "Single mistake-এ life/money impact কত?" High → strict।
  • প্রশ্ন ৩: "Audit/compliance-এ regulator আছে?" Y → strict।
  • সব না হলে → "practical reproducibility" — ±0.5% accuracy tolerance acceptable।

Hidden cost — false economy:

  • "Reproducibility skip করি, fast move" — ৬ মাস পর problem আসলে — debug-এ ৫ এর বেশি engineer-week।
  • সাম্প্রতিক সেট-আপ-এর reproducibility সবসময় cheap; legacy fix retroactively ব্যয়বহুল।
  • "Pay early, pay less" rule applies।

মূল উপলব্ধি: Reproducibility একটি spectrum — bit-exact থেকে statistical pretty good পর্যন্ত। Domain-এর regulatory + impact profile দেখে fit decide করুন। Bangladesh-এ banking ও health critical, e-commerce relaxed — এটাই common sense।

প্র ০২ "একই code, same seed, same data, same Docker — কিন্তু GPU আলাদা।" এই situation-এ কী ঘটতে পারে? কীভাবে handle?

GPU non-determinism — একটি subtle ও common সমস্যা।

কী ঘটে:

  • Float operation associative না (a+b)+c ≠ a+(b+c) edge cases-এ।
  • Different GPU model (V100 vs A100) — different parallelization → different reduction order।
  • Tensor Core (Ampere+) vs CUDA core — different precision pathways।
  • Mixed precision (FP16) — accumulation order matters।

Magnitude:

  • Same architecture GPU (e.g., 2x V100): ±0.001% loss difference. Usually invisible।
  • Different generation (V100 vs A100): ±0.05-0.1% accuracy। Noticeable on small dataset।
  • CPU vs GPU: ±0.5-1% potentially। Significant।

Practical handling:

  • Log GPU model explicitly: torch.cuda.get_device_name(0)।
  • Production training fixed GPU type (e.g., always A100)।
  • Multi-GPU — same type within a job।
  • Test-set reproducibility check — "tolerance ০.০৫% accuracy" — flag if exceeded।
  • For audit: training infrastructure-ও metadata-এ।

Bit-exact across GPUs প্রায় অসম্ভব:

  • হলেও — ১.৫-২× slower।
  • NVIDIA documentation: "deterministic algorithms might differ across GPU generations"।
  • Practical: "deterministic within a fixed GPU model" achievable; cross-model not guaranteed।

Bangladesh ডেটা সেন্টার context:

  • Cloud GPU pool — যেকোনো instance allocate। Reproducible setup-এ instance type pin।
  • On-prem mixed GPU — careful scheduling।
  • Spot instance — interruption + replace, GPU type vary। Avoid for reproducibility-critical।

Workaround — multi-seed average:

  • 5-10 seed-এ train, average performance report। Hardware-induced noise average হয়ে যায়।
  • "Best seed" cherrypick avoid — adversarial।
  • Cross-validation strategy-এর মতো।

মূল উপলব্ধি: Hardware-level reproducibility achievable but expensive. সাধারণত GPU model pin + seed + same Docker = practical reproducibility। Bit-exact cross-GPU ramp up করার জন্য — usually worth it na, except in specific compliance scenarios।

প্র ০৩ একটি ৩ বছরের পুরোনো model আজ reproduce করতে হবে। কী challenges, কোন data থেকে শুরু?

Legacy model reproduction — MLOps-এর সবচেয়ে কঠিন practical exercise। প্রতিটি axis-এ ক্ষয়।

Code reproducibility issues:

  • Git history থাকলে — hash থেকে exact code পাওয়া যায়।
  • Issue: dependencies repo gone (private package, fork deleted)।
  • Solution: "vendored" dependencies বা archived mirror।

Data reproducibility issues:

  • ৩ বছরের data — DVC track ছিল কি?
  • Even if DVC tracked — remote storage retention policy?
  • Worst case: PII regulation ৩ বছর data delete force করেছে।
  • Mitigation: hash + statistical signature; পুরো data না, statistical equivalence enough হতে পারে।

Environment reproducibility issues:

  • ৩ বছর আগের Python 3.7, TensorFlow 1.15 — pip install হয়তো এখন fail (yanked package, broken transitive)।
  • Solution: Docker image তখনই build ও push করা হলে — image now run করা যায়।
  • Image not preserved — manual reconstruction কঠিন।

Hardware reproducibility issues:

  • ৩ বছর আগের V100, এখন available না (cloud-এ A100 default)।
  • Older CUDA driver — modern OS-এ struggle।
  • Mitigation: bit-exact reproduce অসম্ভব; statistical equivalence accept।

Library/framework drift:

  • 3-year-old TF model → silent behavior change।
  • Solution: Docker pinned।
  • Without pinning — accept that "bit-exact reproduction not possible, statistical reproduction is the goal"।

Practical recipe — start order:

  1. Find the model artifact (registry / S3)।
  2. Find training metadata (MLflow run / log file)।
  3. Find the Docker image used (image SHA log)।
  4. Find data version reference (DVC hash / S3 version-id)।
  5. Run inference on stored validation set — same predictions?
  6. If yes: reproduce achieved (inference-level)।
  7. If no: code-level reproduction needed — much harder।

"Don't fix what works":

  • Often goal না exact-bit reproduce; "model স্বাভাবিকভাবে retrain করি যা একই বৈশিষ্ট্য দেয়"।
  • "Equivalent retraining" — সাধারণত enough for compliance এবং debugging both।

Lessons for future:

  • Today-এর model artifact + metadata strict রাখুন। ৩ বছর পরের self ধন্যবাদ দেবে।
  • Storage cheap; reconstruction expensive।

মূল উপলব্ধি: Legacy reproducibility-এর কাজ — current discipline-এর importance বোঝায়। ৩ বছর পরে সব axis fully recoverable নয় — সেই disposition আজই MLOps practice strict করতে motivate করে।

প্র ০৪ "Random seed fix করা হলে model কম generalize করবে" — এই myth কতটা সত্য? Practical implication।

এটি widespread myth — কিন্তু আংশিক সত্য একটি subtle কারণে।

Myth: "Seed fix → overfit"। ভুল।

  • Seed শুধু randomness reproducibility — model-এর capacity বদলায় না।
  • Same seed-এ ৫ run = same model (assuming all axes fixed)।
  • Generalization train data-এর variety + regularization-এর function। Seed irrelevant এই দিক থেকে।

আংশিক সত্য — "single seed-এ বিচার বিভ্রান্তিকর":

  • একটি hyperparameter ভাল seed-এ ৯২%, খারাপ seed-এ ৮৮%।
  • "Best of 10 runs" report — adversarial cherrypicking।
  • Solution: ৫-১০ seed average; mean ± std report।
  • Reproducibility-এর জন্য each seed independently reproducible — কিন্তু judgment multi-seed।

"Lucky seed" phenomenon:

  • Smith et al., "Don't Stop the Lottery" — neural network training lottery-ticket-like।
  • Some seeds give consistently better results across runs।
  • Hyperparameter tuning-এ — seed-ও hyperparameter হিসেবে treat না করা ভাল (cheating)।

Production setting:

  • Production model-এ best-of-N seed acceptable, document করুন: "validated across N seeds, mean accuracy X ± Y"।
  • Single seed পুরোপুরি — fragile; one bad luck = one bad model।
  • Ensemble of multi-seed often slightly better — multiple models combine।

Compliance implication:

  • Audit-এ — "যে seed used"। Model retrain চাইলে — same seed available থাকতে হবে।
  • Production model-এর seed registry-তে log।

Test/eval-এ seed:

  • Test set evaluation deterministic হওয়া উচিত — random selection এই কনটেক্সট-এ ঠিক না।
  • Validation seed differ from training seed — independence।

Bayesian / dropout-based uncertainty:

  • Production-এ inference-time-ও randomness থাকতে পারে (MC dropout)।
  • সেক্ষেত্রে — predictable randomness (seed-based) vs true stochasticity ভিন্ন।

মূল উপলব্ধি: Seed fix করলে — generalization কমে না। কিন্তু single-seed-এর evaluation misleading। Multi-seed mean ± std report করুন। Production-এ — seed log + multi-seed validation দু'টো-ই করুন। যা reproduce-able না — সেটা trustworthy না।

অনুশীলন

  1. Audit: আপনার নিজের একটি ML project-এর ৪-axis reproducibility audit করুন। কোন axis-এ gap?

    সাধারণ findings: Code git ✓, Data — সম্ভবত untracked, Environment — requirements.txt unpinned, Randomness — seed কিছু জায়গায় missing। অগ্রাধিকার: data versioning + lock file।

  2. লিখুন: উপরের set_seed function-এ আপনার নিজের training script-এ apply করুন। Output কি deterministic হলো — verify।

    ২ বার পরপর train run, final loss compare। ±1e-6 difference → effectively deterministic। Larger gap → কোন seed missed হয়েছে। Common miss: dropout-এর জন্য torch seed, GPU-এর জন্য torch.cuda।

  3. চিন্তা: একটি "lottery ticket" hyperparameter search — কীভাবে design করবেন যাতে seed-cherrypicking না হয়?

    প্রতিটি hyperparameter combo ৫ seed-এ run, mean accuracy report। Best combo selection mean-এ, max-এ না। Final model retrain on different held-out seed। Multi-seed std reporting standard।

আরও পড়ুন

পূর্ববর্তী পাঠ
পাঠ ৪ · DevOps বনাম MLOps