Inverse RL ও imitation learning
এই পাঠে যা শিখবেন
- Behavioral Cloning — কেন simple কিন্তু distribution shift-এ ভেঙে পড়ে
- DAgger algorithm — interactive expert query
- Inverse RL formulation — observed behavior থেকে reward recovery
- GAIL — adversarial training imitation-এ
১ · কেন imitation learning?
RL-এর সবচেয়ে কঠিন অংশ — reward function design। "ভালো ড্রাইভিং" reward কী? কেউ বলে $-\text{collision} - 0.1 \cdot \text{lane-change}$, কেউ যোগ করে $+\text{progress}$। প্রতিটি engineer ভিন্ন reward, ভিন্ন behavior। Reward hackingReward HackingAgent reward function-এর শূন্যপথ exploit করে — কাজ "শুদ্ধ"-ভাবে না করেও score বাড়ায়। যেমন boat racing-এ reward hack করে turbo গোলে স্পিন। সর্বত্র — agent reward maximize করে, কিন্তু "সঠিক" কাজ না।
Imitation learning-এর প্রস্তাব: reward design ছেড়ে দাও। মানুষের demonstration দাও, agent সেটা mimic শিখুক। ড্রাইভিং শেখাতে — হাজার হাজার ঘণ্টা মানুষের ড্রাইভ video; surgical robot-এ — surgeon-এর হাতের motion।
১) Imitation Learning (BC, DAgger): direct policy copy। expert action mimic।
২) Inverse RL (IRL, GAIL): demonstration থেকে reward function infer, তারপর সেই reward-এ RL train।
২ · Behavioral Cloning — সবচেয়ে সরল
Expert dataset $\mathcal{D} = \{(s_i, a_i)\}_{i=1}^N$ — supervised classification/regression: $$\theta^* = \arg\min_\theta \sum_i \mathcal{L}(\pi_\theta(s_i), a_i)$$
Discrete action: cross-entropy। Continuous: MSE বা negative log-likelihood (Gaussian)। This is exactly supervised learning — কোনো RL loop নেই।
সমস্যা — covariate shift:
- Train: states from $\rho_\pi^{\text{expert}}$ — expert visit-এর distribution।
- Test: agent rolls out নিজের policy — slight error। সে state-এ পৌঁছায় যেখানে expert কখনো ছিল না।
- সেখানে action prediction terrible — error grows compounding।
Mathematical statement (Ross & Bagnell, ২০১০): horizon $T$-এ BC-র sub-optimality bound $O(T^2 \epsilon)$ যেখানে $\epsilon$ per-step error। RL-এ $O(T \epsilon)$ — quadratic vs linear। Long horizon-এ BC dramatically worse।
৩ · DAgger — Distribution shift-এর সমাধান
DAgger (Dataset Aggregation, Ross et al. ২০১১) — সরল কিন্তু game-changing trick:
- Initial $\pi_0$ — BC trained।
- Iteration $i$: agent $\pi_i$ rolls out, visit করা সব state record।
- সেই state-গুলোর জন্য — expert query। "এখানে আপনি কী করতেন?" Expert answer।
- New $(s, a^*)$ pairs যোগ করো dataset-এ।
- $\pi_{i+1}$ retrain করো aggregated dataset-এ।
মূল idea — agent যেসব state-এ যায়, সেগুলোর জন্যই training data থাকা উচিত। Expert online correction-এ distribution match হয়।
৪ · Inverse Reinforcement Learning
IRL (Ng & Russell, ২০০০) ভিন্ন কোণ থেকে দেখে: demonstration $\tau^* = (s_0, a_0, s_1, a_1, \ldots)$ দিলে — reward function $R$ infer যেখানে $\tau^*$ optimal।
সমস্যা: ill-posed। অনেক reward একই behavior explain করতে পারে — যেমন $R = 0$ সবসময় optimal (trivially)।
সমাধান:
- Max-margin IRL (Abbeel & Ng, ২০০৪): $R$ এমন বাছো যাতে expert other policies-এর চেয়ে significant margin-এ ভাল।
- Max-entropy IRL (Ziebart, ২০০৮): $p(\tau) \propto e^{R(\tau)}$ — expert behavior probabilistic, ambiguity হ্যান্ডল করে। এটি সবচেয়ে jolt-এ ব্যবহৃত formulation।
- GAIL (২০১৬): reward explicitly recover করার বদলে — directly imitator policy train। নিচে।
৫ · GAIL — adversarial imitation
Ho & Ermon (২০১৬) GAN-এর architecture imitation-এ আনলেন। দু'টি network:
- Discriminator $D$: input $(s, a)$ — predict probability "এটি expert demo কি না"।
- Generator/Policy $\pi$: environment-এ act করে — discriminator-কে fool করতে চায়।
Objective:
$$\min_\pi \max_D \mathbb{E}_{(s,a) \sim \pi_E}[\log D(s,a)] + \mathbb{E}_{(s,a) \sim \pi}[\log(1 - D(s,a))]$$
Implementation-এ — discriminator-এর output থেকে surrogate reward: $r(s,a) = -\log(1 - D(s,a))$। সেই reward দিয়ে policy TRPO/PPO update। Discriminator gradient descent — binary classification।
GAIL-এর সুবিধা — হাজার-হাজার expert demonstration-এ scalable, reward design লাগে না, MuJoCo/Atari-তে BC-র চেয়ে অনেক ভালো generalization।
৬ · BC code — সরল PyTorch implementation
import torch, torch.nn as nn
import torch.nn.functional as F
from torch.utils.data import DataLoader, TensorDataset
# Synthetic expert data: (state, action)
N = 10_000
S = torch.randn(N, 4)
A = (S[:, 0] + S[:, 2] > 0).long() # rule the "expert" follows
class Policy(nn.Module):
def __init__(self):
super().__init__()
self.net = nn.Sequential(
nn.Linear(4, 64), nn.ReLU(),
nn.Linear(64, 64), nn.ReLU(),
nn.Linear(64, 2),
)
def forward(self, s):
return self.net(s)
policy = Policy()
opt = torch.optim.Adam(policy.parameters(), lr=3e-4)
loader = DataLoader(TensorDataset(S, A), batch_size=128, shuffle=True)
for epoch in range(10):
total = 0.0
for s, a in loader:
logits = policy(s)
loss = F.cross_entropy(logits, a)
opt.zero_grad(); loss.backward(); opt.step()
total += loss.item()
print(f"epoch {epoch}: loss {total/len(loader):.4f}")
# Evaluation
with torch.no_grad():
pred = policy(S).argmax(-1)
acc = (pred == A).float().mean()
print(f"BC accuracy: {acc:.3f}")
৭ · GAIL discriminator — minimal sketch
import torch, torch.nn as nn
import torch.nn.functional as F
class Discriminator(nn.Module):
def __init__(self, s_dim, a_dim):
super().__init__()
self.net = nn.Sequential(
nn.Linear(s_dim + a_dim, 128), nn.Tanh(),
nn.Linear(128, 128), nn.Tanh(),
nn.Linear(128, 1),
)
def forward(self, s, a):
return self.net(torch.cat([s, a], -1))
D = Discriminator(s_dim=11, a_dim=3)
opt_D = torch.optim.Adam(D.parameters(), lr=3e-4)
def disc_step(expert_sa, agent_sa):
"""One D update — binary classification."""
es, ea = expert_sa
gs, ga = agent_sa
e_logit = D(es, ea)
g_logit = D(gs, ga)
loss = F.binary_cross_entropy_with_logits(e_logit, torch.ones_like(e_logit)) \
+ F.binary_cross_entropy_with_logits(g_logit, torch.zeros_like(g_logit))
opt_D.zero_grad(); loss.backward(); opt_D.step()
return loss.item()
# Surrogate reward for the policy
def gail_reward(s, a):
with torch.no_grad():
return -F.logsigmoid(-D(s, a)).squeeze(-1) # = -log(1 - σ(D))
# Then plug `gail_reward` into a standard PPO/TRPO loop in place of env reward.
৮ · Imitation কোথায় production-এ?
- Self-driving: Wayve, Tesla — billions miles human driving। BC + LfD foundation।
- Robot manipulation: Diffusion Policy, ACT — teleoperation demonstration থেকে।
- Game AI: AlphaStar — replay imitation থেকে শুরু, পরে self-play।
- RLHF (next lesson!): human preferences-এর ওপর reward model — implicit IRL।
ভাবনার প্রশ্ন
প্রতিটি প্রশ্ন নিজে কিছুক্ষণ ভাবুন — তারপর "→ উত্তর" চাপুন।
প্র ০১ BC-র "compounding error" কেন quadratic-এ grow করে? সরল linear না কেন?
চমৎকার theoretical question। Ross & Bagnell-এর paper-এর core।
Setup: Expert policy $\pi^*$, agent BC policy $\hat{\pi}$, per-step error rate $\epsilon$ — meaning $P(\hat{\pi}(s) \neq \pi^*(s)) \leq \epsilon$ for $s \sim \rho^{\pi^*}$।
Why quadratic:
- Step 1: error probability $\epsilon$ — agent goes off-distribution।
- Step 2: agent now in unfamiliar state। Per-step error here might be near $1$ (not just $\epsilon$)। Worst-case: drift continues।
- Cumulative damage: at step $t$, total accumulated error ≤ $t\epsilon$ to first order, কিন্তু off-distribution amplification সহ — $T \times T \epsilon = T^2 \epsilon$।
Formal proof sketch (informal):
- সম্ভাব্য reward gap $J(\pi^*) - J(\hat{\pi})$।
- Each step disagreement-এ — worst-case loss bound by $T R_{\max}$ (rest-of-trajectory damage)।
- Probability of disagreement at step $t$ ≤ $t\epsilon$ (cumulative)।
- Sum: $\sum_{t=1}^T t\epsilon \cdot R_{\max} = O(T^2 \epsilon R_{\max})$।
RL-এর সাথে তুলনা:
- Online RL — agent নিজে own state-distribution-এ practice করে। $O(T \epsilon)$।
- BC — fixed expert distribution-এ training। $O(T^2 \epsilon)$।
- DAgger — own distribution-এ feedback → linear back।
Practical implication:
- Short horizon (T=10): difference negligible।
- Long horizon (T=1000): BC error 1000× worse। Self-driving-এ catastrophic।
- Why Tesla/Wayve hybrid — BC pretrain + online RL/safety filter।
Empirical confirmation: CARLA benchmark — naïve BC ৩০% success rate, DAgger ৭০%, RL ৭৫%। Quadratic gap বাস্তবে দৃশ্যমান।
(একটু subtle) এই bound worst-case। যদি $\hat{\pi}$ "close enough"-এ error self-correct — practical performance বেশি ভাল হতে পারে। তাই BC dominant approach আজও অনেক applications-এ — distribution-shift bounded থাকলে।
প্র ০২ GAIL "reward function explicitly recover করে না" — কেন তবু এটাকে inverse RL বলা হয়? IRL-এর সাথে গভীর সম্পর্ক কী?
চমৎকার subtle question। GAIL paper-এর interpretive heart।
(১) Implicit reward: GAIL-এ discriminator $D(s,a)$ — যা output করে, সেটা একটি অনুপাত। Surrogate reward $r(s,a) = -\log(1-D)$ — যত close to expert, reward তত বেশি। তাই reward exists, just implicit।
(২) Connection to MaxEnt IRL: Ho & Ermon paper-এর Theorem 1 দেখায় — GAIL maximum-entropy IRL-এর exact dual। MaxEnt IRL-এ Lagrangian dual problem solve — GAIL সেই dual-এর gradient form। Math formally equivalent।
(৩) Why "imitation" framing: Reward recover না করে directly policy পেলেই অনেক applications-এ যথেষ্ট। MaxEnt IRL দু'টি step (reward → RL); GAIL একটি step (joint adversarial)। Computational simpler।
(৪) Trade-offs:
- Explicit IRL — interpretable। Reward function inspect করে — "agent কি শিখেছে?"। Safety critical applications-এ valuable।
- GAIL — black-box। Reward inspect করা কঠিন। কিন্তু high-D continuous action-এ explicit IRL intractable।
(৫) AIRL (Fu et al., ২০১৮) — middle ground: GAIL-এর variant যেটা explicitly disentangled reward recover। Discriminator এ structure: $D = \sigma(r(s,a) + \gamma V(s') - V(s) - \log \pi)$। $r$ explicit, transferable।
(৬) Reward transferability: True reward জানলে — different dynamics-এ একই agent transfer। "Bangladesh roads"-এর reward Tokyo-তে work করার সম্ভাবনা। GAIL — policy-নির্ভর, transfer fails।
(৭) GAN parallels: JS-divergence vs। Wasserstein, mode collapse, training instability — GAIL সব GAN problem inherit করেছে। Recent variants: DAC, ValueDICE।
(৮) Modern view: RLHF — preference-based reward model + RL — IRL/GAIL-এর descendant। ChatGPT-র alignment foundation এই IRL traditions-এ।
মূল উপলব্ধি: "Imitation vs IRL" সবসময় hard split না — অনেকটা spectrum। GAIL operationally imitation, theoretically IRL। RLHF-ও তাই।
প্র ০৩ Self-driving-এ Tesla, Wayve সবাই massive imitation learning ব্যবহার করে। কিন্তু "100% imitation" production-এ কেন কেউ deploy করে না?
চমৎকার applied question।
(১) Long-tail problem: normal driving easy mimic — কিন্তু rare/dangerous situation expert demo-তে underrepresented। Black-ice, animal sudden appearance, debris। BC সেগুলো শেখে না। Real-world deployment-এ exactly সেই rare event-এ failure unacceptable।
(২) Compounding error in continuous control: highway-এ minor lane-deviation → off-distribution → larger deviation → barrier hit। Quadratic error bound বাস্তব physics।
(৩) Causal confusion: Expert brakes when traffic light red। BC শেখে — "red light + car behind = brake"। কিন্তু "car behind" আসলে causally irrelevant; BC spurious correlation। ICRA 2019 papers এই issue বহু documented।
(৪) Multi-modal expert: highway-এ driver lane-1 বা lane-2 — দু'টোই valid। BC averaging → "মাঝখানে drift"। Mode collapse। Solution: mixture-density network, diffusion policy।
(৫) Hybrid architecture (industry):
- BC pretrain: billions of human-driver miles → strong prior।
- Rule-based safety filter: "always maintain 2-second gap", "never cross double-line"। Deterministic guardrails।
- Online correction (Wayve "AV2.0"): shadow mode → human takeover triggers data collection → continual improvement।
- Sim-based RL fine-tune: CARLA, Wayve Infinity simulator — corner case explicit train।
(৬) Liability ও regulation: "Pure neural net controller" regulator-দের কাছে scary। Interpretable rules + bounded behavior লাগে। Pure imitation-এ behavior unbounded (worst-case unknown)।
(৭) Cost of demo collection: Tesla — fleet-collected, cheap। Wayve — paid drivers, expensive। ছোট companies-এর জন্য — pure imitation infeasible। RL + self-play সম্ভব।
(৮) Continuous improvement: Pure BC — কথা বললে, "training data ছাড়াই improve হবে কীভাবে?" — RL দরকার interaction-driven improvement-এর জন্য।
মূল কথা: Self-driving = imitation foundation + safety engineering + simulation RL + careful productization। কেউ "শুধু-একটি-paradigm" দিয়ে ছাড়েনি — production reality multi-stack।
প্র ০৪ Bangladesh-এ একটি rural healthcare diagnosis chatbot — অভিজ্ঞ doctor-দের consultation থেকে train করতে চাচ্ছেন। BC, DAgger, IRL, GAIL — কোনটি বাছবেন?
আকর্ষণীয় বাস্তব scenario।
Setup:
- Input (state): patient symptoms, history, vital signs (যা rural setting-এ available)।
- Output (action): triage decision (urgent/non-urgent), recommended next step (test, refer, treat)।
- Demonstration: ~৫,০০০ doctor consultations text/structured data।
Recommended pipeline — BC + RAG + DAgger-lite:
- Step 1 — Behavioral Cloning: base LLM (mT5, BanglaBERT) finetune on doctor-patient dialogue। Strong prior।
- Step 2 — RAG (Retrieval-Augmented): medical guidelines (WHO, BMDC) embed। Each query — relevant guidelines retrieve, BC + retrieval combined। Hallucination কমে।
- Step 3 — DAgger-lite: deployment-এ — bot uncertain হলে (low-confidence flag) — doctor pop up, override। সেই (state, doctor-action) data collect, weekly retrain।
- Step 4 — Safety filter: red-flag rule based — "chest pain + sweating" → ALWAYS urgent referral, regardless of model। Deterministic guardrail।
কেন এই combination:
- BC ভাল: cheap, leverages existing data, domain-aligned।
- Pure DAgger না কেন: doctor-time precious। Constant query infeasible। DAgger-lite (uncertainty-triggered) practical।
- IRL/GAIL না কেন: reward function explicitly modeling impractical। Doctor decisions multi-objective (cost, side-effects, family preference) — single reward inadequate।
- RLHF-style: phase 2-এ — patient feedback "এই advice helpful ছিল?" — reward signal। future।
Bangladesh-specific considerations:
- Language: Bangla + English code-switching। Multilingual base model।
- Cultural: "Tin masher por dactar er kaaste jaben" — patient hesitancy। Bot empathetic + culturally-aware required।
- Trust: rural patients skeptical of AI। "Dr. ABCL TECH" branding + endorsement by local hospitals।
- Liability: bot diagnosis-প্রদানকারী না — "screening assistant"। Always defer to qualified doctor for treatment।
- Connectivity: rural internet patchy — offline mode (compressed model on device) useful।
Ethics ও safety:
- Out-of-scope refusal (mental health crisis → hotline)।
- Bias monitoring — gender/ethnicity-based recommendation gap audit।
- Transparent "I don't know" response।
- Data privacy — Bangladesh-এর Health Care Data Protection rules follow।
Evaluation:
- Doctor-rated accuracy (gold standard)।
- Sensitivity/specificity for emergency triage।
- Patient satisfaction score।
- Time-to-correct-referral metric।
মূল কথা: Healthcare AI সবচেয়ে high-stakes imitation domain। BC একটি baseline, কিন্তু safety + retrieval + iterative human feedback ছাড়া unsafe। Course এর knowledge পুরোপুরি apply।
অনুশীলন
-
BC limitation: ১,০০০ expert demonstrations দিয়ে BC train করে CartPole-এ ৯৫% accuracy পেলেন। Deploy-এ — episode-এ গড়ে ১৫০ step টিকে। Pure expert ৪৯৭+। ব্যাখ্যা করুন কেন।
Per-step accuracy ৯৫% মানে ৫% error/step। ১৫০ steps × ৫% = ৭.৫ accumulated errors গড়ে — এদের কোনো একটিতে state off-distribution → cascade failure → episode terminate। Quadratic error compounding-এর সরাসরি manifestation। সমাধান: DAgger বা PPO/RL fine-tune।
-
GAIL reward derivation: $r(s,a) = -\log(1-D(s,a))$ কেন? $D$ output meaning কী?
$D(s,a) \in [0,1]$ = probability "এটি expert"। $D \approx 1$ মানে expert-look। $-\log(1-D)$ → $D=1$ এ $\infty$ (high reward), $D=0$ এ $0$। অর্থাৎ — যত expert-like behavior, reward তত বেশি। Policy এই surrogate reward maximize করে → expert distribution match।
-
Method choice: নিচের scenario-তে কোন imitation method? (a) ১ million YouTube cooking video থেকে cooking robot, (b) ১০টি expert chess game থেকে chess bot, (c) Real-time interactive surgery skill transfer।
(a) YouTube cooking — GAIL/AIRL। Massive observation-only data, no explicit action labels, adversarial works well। (b) ১০ chess games — too few for BC; AlphaZero-style self-play after BC pretrain ভাল। (c) Surgery — DAgger or HG-DAgger; expert (surgeon) interactively available, safety-critical, real-time correction crucial।
আরও পড়ুন · ABCL TECH-এ আপনার পরবর্তী পদক্ষেপ
- পাঠ ২৮ · RLHF — LLM alignment পরবর্তী পাঠ IRL-এর মতই — preferences থেকে reward model, তারপর PPO।
- পাঠ ২৬ · Multi-agent RL আগের পাঠ AlphaStar imitation থেকে শুরু, পরে league self-play।
- পাঠ ৩২ · কোর্সের চূড়ান্ত পর্যালোচনা কোর্স review কখন imitation, কখন RL — choice tree।
- সব AI Courses দেখুন ABCL TECH Python, ML, DL, NLP, CV, GenAI, RL — সব AI কোর্স একসাথে।