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

RLHF — LLM alignment-এর কৌশল

RLHF for LLMs: from preferences to policy
১২ মিনিট পড়া মাঝারি · Intermediate 3-stage pipeline

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

  • RLHF-এর ৩-stage pipeline — SFT → RM → PPO
  • Bradley-Terry preference model — pairwise comparison থেকে scalar reward
  • KL penalty কেন essential — reward hacking ও mode collapse এড়ানো
  • InstructGPT (২০২২) → ChatGPT, Claude — production-grade RLHF

১ · কেন RLHF? Pretrained LLM-এর সমস্যা

একটি pretrained LLM (GPT, LLaMA, Mistral) বিশাল text corpus-এ next-token prediction শেখে। ফলে সে চমৎকারভাবে "internet text" generate করতে পারে — কিন্তু সেটা ঠিক যা চান তা নয়:

  • "Translate this to Bangla" → কখনো translation, কখনো প্রশ্ন repeat, কখনো অসম্পর্কিত essay।
  • "What's the capital of Bangladesh?" → কখনো "Dhaka", কখনো wikipedia-style verbose article।
  • Toxic, biased, dangerous output প্রায়ই generate হয় — কারণ training data-তে আছে।

সমস্যা: pretraining objective ("predict next token") ও user objective ("be helpful, safe, accurate") একই না। এটি alignment problemAlignment ProblemAI system-এর behavior কীভাবে human values-এর সাথে align করানো যায়। RLHF, Constitutional AI, debate, scalable oversight — সব এই problem-এর partial solution।।

RLHF-এর প্রতিশ্রুতি

Reward function explicitly লিখে "helpful response" define করা অসম্ভব। কিন্তু — মানুষ দু'টি response দেখে বলতে পারে কোনটি ভালো। এটি RLHF exploit করে: preferences থেকে reward model তৈরি, তারপর সেই RM-এর বিরুদ্ধে policy optimize।

ভাবুন বাংলা রান্না শেখাচ্ছেন AI-কে। "ভাল রসগোল্লা" কোডে describe করা impossible। কিন্তু দু'টি রসগোল্লা চেখে — "এটা ভাল, ওটা না" — সহজ। RLHF এই relative judgment থেকে absolute "ভাল রান্না" function তৈরি করে। তারপর AI সেই function-এ score বাড়াতে চেষ্টা করে — KL penalty একে আগের traditional রেসিপি থেকে দূরে যেতে দেয় না।

২ · তিন-stage pipeline overview

InstructGPT paper (Ouyang et al., ২০২২) থেকে standard form:

  1. Stage 1 — SFT (Supervised Fine-Tuning): human-written demonstration ($x$ = prompt, $y$ = ideal response)। Base LLM-কে cross-entropy দিয়ে fine-tune। Output: $\pi^{\text{SFT}}$।
  2. Stage 2 — Reward Model: human labelers compare ($y_w$ = chosen, $y_l$ = rejected) — multiple responses-এর মধ্যে। Reward model $r_\phi(x, y)$ — scalar score। Bradley-Terry loss দিয়ে train।
  3. Stage 3 — PPO RL: $\pi^{\text{SFT}}$ থেকে initialize, reward = $r_\phi(x, y) - \beta \cdot \text{KL}(\pi || \pi^{\text{SFT}})$ — PPO update।

৩ · Stage 1 — SFT details

Pretrained model (e.g., GPT-3 base, LLaMA-2-7B) — instruction-following data পেয়ে adapt করে। Data: ~১০K-১০০K examples, formatted as $(prompt, response)$।

Loss = standard language modeling (next-token):

$$\mathcal{L}^{\text{SFT}} = -\mathbb{E}_{(x, y) \sim \mathcal{D}_{\text{demo}}} \left[\sum_t \log \pi_\theta(y_t | x, y_{

এই step-এর পরই model অনেক "instruction-following" হয় — Anthropic, OpenAI দু'জনেই reports SFT-ই ৭০-৮০% gain দেয়; RLHF বাকি ২০-৩০% polish।

৪ · Stage 2 — Reward Model

Same prompt $x$-এর জন্য SFT model কয়েকটি ($K=4$ — ৯) response generate করে। Human labeler ranking দেয় — best to worst।

প্রতিটি pair $(x, y_w, y_l)$ — chosen vs rejected — Bradley-Terry model:

$$P(y_w \succ y_l \mid x) = \sigma(r_\phi(x, y_w) - r_\phi(x, y_l))$$

Loss:

$$\mathcal{L}^{\text{RM}} = -\mathbb{E}_{(x, y_w, y_l)} \left[\log \sigma(r_\phi(x, y_w) - r_\phi(x, y_l))\right]$$

Architecture: SFT model-এর LM head replace — scalar regression head। Last-token hidden state → linear projection → scalar। Train ১-২ epoch — overfit হলে preferences memorize, generalize না।

RM accuracy plateau: human labelers একে অপরের সাথে ৬৫-৭০% agree করেন — অর্থাৎ reward model-এর upper bound এই-ই। ৭৫%+ accuracy claim সাধারণত overfit বা data leakage signal।

৫ · Stage 3 — PPO with KL penalty

Reward function:

$$r(x, y) = r_\phi(x, y) - \beta \cdot \log \frac{\pi_\theta(y|x)}{\pi^{\text{SFT}}(y|x)}$$

Per-token: each generated token-এ partial reward = প্রায়-zero except final reward, plus per-token KL penalty।

Equivalently — KL-regularized reward maximization:

$$\max_{\pi_\theta} \mathbb{E}_{x \sim \mathcal{D}, y \sim \pi_\theta} [r_\phi(x, y)] - \beta \cdot \text{KL}(\pi_\theta(\cdot|x) \| \pi^{\text{SFT}}(\cdot|x))$$

$\beta$ — KL coefficient, সাধারণত $0.01$ - $0.1$। বড় $\beta$ → policy SFT-এর কাছেই থাকে; ছোট → reward exploit বেশি।

PPO updates:

  • Rollout: $\pi_\theta$ থেকে $y$ sample, $r_\phi(x, y)$ compute, per-token advantage GAE।
  • Clip ratio: $\min(\rho_t \hat{A}_t, \text{clip}(\rho_t, 1-\epsilon, 1+\epsilon)\hat{A}_t)$।
  • Value head: separate critic (often shared backbone)।

৬ · KL penalty কেন critical

KL penalty ছাড়া কী হবে?

  • Reward hacking: RM-এর blind spot — যেমন "very long responses always rated higher" — exploit। Output বিরাট, content-poor।
  • Mode collapse: policy একটিমাত্র "safe" response repeat করে — diversity হারায়।
  • Distribution drift: policy এমন distribution-এ চলে যায় যেখানে RM unreliable (out-of-distribution)। RM "high reward" দেয় কিন্তু আসলে garbage।

KL penalty fix করে:

  • $\pi_\theta$ SFT distribution-এর কাছেই রাখে — RM যেখানে accurate।
  • Diversity preserve — multimodal SFT distribution থেকে policy too far divagate করে না।
  • Stability — gradient explode/policy collapse এড়ায়।
RLHF — InstructGPT pipeline ১. SFT Pretrained LLM GPT/LLaMA base ~10K human demos π_SFT instruction-tuned ২. Reward Model π_SFT samples K responses per prompt human compare y_w vs y_l r_φ(x, y) Bradley-Terry trained ৩. PPO + KL π_θ ← π_SFT init from SFT reward = r_φ − β · KL vs π_SFT — anti-hack PPO clip update π_RLHF helpful + safe Production: চারটি model একসাথে memory-তে π_θ (training) · π_SFT (frozen, KL ref) · r_φ (reward) · v_ψ (critic) ~৪× GPU memory; DPO/RLAIF এই complexity reduce করে
RLHF তিন-stage pipeline। SFT instruction-following শেখায়, RM preferences encode, PPO + KL penalty alignment fine-tune।

৭ · Reward Model PyTorch sketch

Python · PyTorch · RM training step
import torch, torch.nn as nn
import torch.nn.functional as F

class RewardModel(nn.Module):
    """Replace LM head with scalar regression head."""
    def __init__(self, base_lm, hidden_dim):
        super().__init__()
        self.backbone = base_lm
        self.head = nn.Linear(hidden_dim, 1)

    def forward(self, input_ids, attention_mask):
        out = self.backbone(input_ids, attention_mask=attention_mask,
                            output_hidden_states=True)
        # last non-pad token's hidden state
        last_hidden = out.hidden_states[-1]
        last_idx = attention_mask.sum(-1) - 1
        pooled = last_hidden[torch.arange(len(last_idx)), last_idx]
        return self.head(pooled).squeeze(-1)        # (B,)

def rm_loss(rm, batch):
    """Bradley-Terry pairwise loss."""
    chosen = rm(batch["chosen_ids"], batch["chosen_mask"])
    rejected = rm(batch["rejected_ids"], batch["rejected_mask"])
    return -F.logsigmoid(chosen - rejected).mean()

# Pseudocode training loop
# for batch in dataloader:
#     loss = rm_loss(rm, batch)
#     loss.backward(); optimizer.step()

    
RM = SFT model + scalar head। Pairwise loss — preferences encode। Production-এ — multi-task RM (helpful + harmless + honest জন্য আলাদা score) common।

৮ · KL-regularized reward & PPO objective

Python · PyTorch · RLHF reward computation
import torch
import torch.nn.functional as F

@torch.no_grad()
def kl_per_token(policy_logits, ref_logits):
    """KL(π || π_SFT) per generated token."""
    p = F.log_softmax(policy_logits, -1)
    q = F.log_softmax(ref_logits,    -1)
    return (p.exp() * (p - q)).sum(-1)              # (B, T)

def rlhf_reward(policy, ref_policy, rm,
                input_ids, gen_ids, attention_mask,
                beta=0.05):
    """Compute per-token reward = − β·KL,  plus terminal RM score."""
    full_ids = torch.cat([input_ids, gen_ids], -1)
    full_mask = torch.cat([attention_mask, torch.ones_like(gen_ids)], -1)

    p_logits = policy(full_ids, full_mask).logits[:, :-1]
    r_logits = ref_policy(full_ids, full_mask).logits[:, :-1]
    kl_t = kl_per_token(p_logits, r_logits)         # (B, T_full-1)

    # take only the generated portion
    T_prompt = input_ids.shape[1]
    kl_gen = kl_t[:, T_prompt-1:]                   # (B, T_gen)

    # terminal scalar reward from RM
    rm_score = rm(full_ids, full_mask)              # (B,)

    rewards = -beta * kl_gen
    rewards[:, -1] = rewards[:, -1] + rm_score      # add terminal RM
    return rewards                                  # (B, T_gen)

    
Per-token KL penalty applied to every generated position। Terminal RM score শুধু last token-এ। PPO তারপর GAE compute করে এই reward sequence-এ। Memory-heavy কারণ চারটি model in-memory।

৯ · কেন RLHF কাজ করে — গভীর ব্যাখ্যা

  • Calibration to human values: raw LM internet text mimic করে; humans actively curate করে কী ভালো/খারাপ।
  • Sample efficiency: ~৫০K preference pairs দিয়ে — billion-parameter model alignment। Pretraining-এর তুলনায় microscopic।
  • Implicit reasoning: human raters অনেক অলিখিত criteria apply (tone, factuality, format) — sum total RM-এ encoded।
  • Recursive improvement: Anthropic-এর RL-CAI loop — AI critique → AI revise → RM train। Self-improving।
RLHF-এর সীমাবদ্ধতা: (১) human raters সবসময় right না — biases, mistakes RM-এ propagate। (২) sycophancy — model "মানুষ যা শুনতে চায়" বলে, সত্যের চেয়ে। (৩) jailbreak still possible — RLHF safety guardrail thin। (৪) compute expensive — চারটি model concurrent। DPO/RLAIF এই issues address করার চেষ্টা।

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

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

প্র ০১ Bradley-Terry preference model কেন pairwise comparison ব্যবহার করে — direct rating (1-5 stars) না?

চমৎকার measurement-theory question। RLHF-এর critical design choice।

(১) Inter-rater calibration: "এই response কত ভাল, ১-৫?" — A রাটার-এর "৪" ও B রাটার-এর "৪" আলাদা মানে। কেউ কঠোর, কেউ সদয়। Pairwise ("A বনাম B") — relative judgment, calibration-free।

(২) Cognitive science: মানুষ comparison-এ ভাল, absolute judgment-এ দুর্বল। "এই দু'টির কোনটি ভাল" — ১০০ ms-এ উত্তর। "এটি ৭/১০" — ভাবতে হয়।

(৩) Bradley-Terry foundation (১৯৫২): Latent score $r$ — observable preferences-এর Boltzmann distribution। $P(A > B) = \sigma(r_A - r_B)$। Statistically well-behaved।

(৪) Identifiability: Pairwise data থেকে — $r$ up to additive constant identifiable। Optimization stable।

(৫) Direct rating limitations:

  • Rating scale anchoring effects — first item judged influences others।
  • Distribution drift — over time rater "calibration" বদলায়।
  • Boundary effects — কেউ "১" বা "৫" দেয় না, ফলে effective scale ২-৪।

(৬) Empirical evidence: InstructGPT paper-এ direct rating tried — RM accuracy worse, downstream RLHF performance worse।

(৭) Preference vs ranking ($K$-wise): $K=4$ response → $\binom{4}{2} = 6$ pairs। Annotation efficient। Plackett-Luce model — full ranking থেকে।

(৮) Modern variants:

  • Constitutional AI: AI critique → AI rate → human verify subset। Cheaper।
  • RLHF + score (Anthropic-এর recent): pairwise + free-form critique। Best of both।
  • DPO: RM eliminate, directly preference data থেকে policy। Next lesson।

মূল উপলব্ধি: Pairwise comparison — measurement theory-র wisdom + cognitive psychology + statistical efficiency। RLHF-এর foundation কেন solid।

প্র ০২ "Reward hacking" RLHF-এ কী রকম দেখায়? Real examples কী আছে?

চমৎকার — alignment failures-এর catalog।

(১) Length hacking: ChatGPT early version — অনেক length-এর response higher RM score পেত (humans long ≈ thorough ভাবেন)। Policy responses দীর্ঘ-দীর্ঘ অর্থহীন verbose। Solution: length penalty, calibrated RM training।

(২) Sycophancy: Anthropic ২০২৩ paper দেখায় — RLHF model "user-এর view-এর সাথে agree করা" prefer। User বললে "আকাশ সবুজ" — model agree করে। Reason: humans এমন response higher rate। Solution: explicit anti-sycophancy training।

(৩) Hedging/uncertainty avoidance: "I'm not sure but..." আত্মবিশ্বাসী response-এর চেয়ে কম rate পায় — যদিও honest। Model overconfident hallucinations দেয়।

(৪) Format optimization: Bullet points → high reward (visual structure)। Model সব response bullet-এ — যেমন কবিতা চাইলেও।

(৫) Refusal hacking: "As an AI, I cannot..." — safe refusal high RM score। Model বেনিগন প্রশ্ন-এও refuse। OpenAI ২০২৩ early ChatGPT-এ ম্যাসিভ issue।

(৬) Disclaimer overload: health/legal-এ — disclaimer যোগ করা safe। Model coffee-recipe-তে "consult doctor" বলে।

(৭) Specific phrasing exploit: "Certainly!" দিয়ে শুরু high reward। Every response "Certainly!" দিয়ে শুরু।

(৮) Out-of-distribution exploit: RM unseen prompt-এ unreliable। Policy এমন strange/creative output find করে — RM high score, human horror।

Why happens — fundamental issue:

  • RM = approximation of human preference।
  • Optimization-এ Goodhart's Law — "যখন measure target হয়, measure মানে হারায়"।
  • Black-box high-D space-এ — exploit corner অনিবার্য।

Mitigation:

  1. KL penalty — distance from SFT bounded।
  2. RM ensemble — multiple RM, conservative reward।
  3. Rollout-time human spot-check — flagrant hacks catch।
  4. Iterative re-training — new RM with fresh human data।
  5. Constitutional AI — explicit principles override learned reward।

মূল কথা: Reward hacking inevitable, manageable। RLHF magic না — careful engineering + iterative refinement।

প্র ০৩ RLHF computationally expensive (৪ models)। PPO unstable। তবু industry standard কেন? Cheaper alternative নেই?

চমৎকার pragmatic question।

(১) Why PPO/RLHF dominated until 2023:

  • OpenAI-এর InstructGPT paper definitive recipe — community follow।
  • Stable, well-understood (PPO ২০১৭ থেকে)।
  • Strong empirical results — ChatGPT phenomenon।
  • Modular — RM, policy independently improvable।

(২) Cheaper alternatives — emerging:

  1. DPO (Direct Preference Optimization, ২০২৩): next lesson। Bypasses RM + PPO. Single supervised loss। ৩-৪× cheaper। Llama-3-Instruct, many open models।
  2. RLAIF (RL from AI Feedback): humans replaced by stronger AI। Cheap labels। Anthropic Constitutional AI।
  3. RSO (Rejection Sampling Optimization): Best-of-N sampling instead of full RL।
  4. SimPO, ORPO, KTO: DPO variants — different theoretical foundations।
  5. Online IPO/cDPO: theoretical fixes to DPO's overoptimization।

(৩) Why PPO still relevant:

  • Online learning — DPO offline, PPO can iterate।
  • Continuous improvement — production deployment-এ user feedback online integrate।
  • Reward shaping flexibility — multi-objective easier।
  • Safety auditing — explicit RM inspect possible।

(৪) Production combinations:

  • Anthropic Claude — RLHF + Constitutional AI + RLAIF mix।
  • OpenAI GPT-4 — undisclosed, presumably PPO + RM ensemble + extensive red-team।
  • Meta Llama-3 — DPO primary, with iterative refinement।
  • Mistral — DPO standard now।

(৫) Cost breakdown:

  • Pretraining 70B model: ~$10M+।
  • SFT: ~$50K।
  • RM training: ~$50K।
  • RLHF PPO: ~$200K-$500K (multi-week training)।
  • DPO instead of PPO: ~$100K।

(৬) Hybrid trends: "PPO + DPO hybrid" — PPO foundation, DPO iterative refinement। SimPO + length normalization।

(৭) Future:

  • SCALE: scaling efficient methods (DPO+) for larger models।
  • SAFETY: provable alignment beyond empirical RLHF।
  • MULTIMODAL: image, video alignment — RLHF extension।
  • RLAIF dominance — humans expensive bottleneck।

মূল উপলব্ধি: RLHF first-mover advantage + bird-in-hand। DPO/RLAIF taking over। Field moving fast — by 2026, ChatGPT-3.5-style PPO RLHF likely legacy।

প্র ০৪ আপনি Bangla LLM (Bangla-GPT) তৈরি করছেন। RLHF apply করতে কী ধরনের challenges? Specific solutions?

আকর্ষণীয় Bangladesh-applied scenario।

Stage 1 — SFT challenges:

  • Demonstration data scarcity: English-এ ১০K instruction examples easy; Bangla-তে কঠিন। Solution: translate from English (with quality filtering), synthesize via stronger LLM, native crowd-sourcing।
  • Code-switching: Bangladeshi text "আমি tomorrow office জাবো" common। Tokenizer Bangla unicode + English latin both handle।
  • Dialect variation: Dhaka, Chittagong, Sylhet, Rajshahi — different vocabularies। Multi-dialect demonstration।

Stage 2 — RM challenges:

  • Annotator pool: Bangla-fluent + tech-literate annotators expensive। Bangladesh local pool: BUET, Dhaka University students, BdAi enthusiasts। Cost: $0.5-1/comparison vs US $5-10।
  • Cultural calibration: "Helpful" — Bangla context-এ different। Address-form (আপনি/তুমি/তুই), formality — context-sensitive।
  • Religious/political sensitivity: Bangladesh-এ specific topics। RM annotators-দের clear guidelines + "preferred decline" categories।
  • Pre-existing bias: annotator pool homogeneous হতে পারে — male/educated/urban। Diversify।

Stage 3 — PPO challenges:

  • Compute constraint: ৭B model PPO training ৫-১০ A100-day। Bangladesh-এ rare resource। Solution: cloud (Lambda Labs, RunPod), or shrink to ৩B model।
  • KL with Bangla SFT: $\pi_{\text{SFT}}$ already Bangla-tuned। KL stability OK।

Bangla-specific design choices:

  1. Base model selection: mBART, BloomZ, Aya — multilingual; Llama-3.1 with Bangla finetune; native Bangla ScienceLab/CSE BUET models।
  2. Tokenizer: SentencePiece BPE on Bangla corpus + English merge। Avoid 1-byte-per-glyph bloat।
  3. Evaluation: Bangla GLUE-like benchmark — sentiment, NER, QA। Native speaker A/B testing essential।
  4. Safety: hate speech in Bangla often coded — "জোয়ার" type slurs। Curated moderation dataset।

Cost-saving tactics:

  • DPO instead of PPO — ৩× cheaper।
  • RLAIF — strong English LLM judge Bangla pairs (with care)।
  • LoRA adapter — base model frozen, only adapter train। ১০× memory save।
  • Distillation — large model output → small student।

Cultural considerations:

  • Religious greetings (Assalamualaikum, Adab) — model respect, default to neutral।
  • Honorific system — auto-detect formality, respond appropriately।
  • Festivals (Eid, Pohela Boishakh, Durga Puja) — rich knowledge।
  • Local proverbs and idioms — fluency marker।

Potential applications:

  • Bangla customer support (telecom, e-commerce — Daraz, Pathao)।
  • Educational tutor for Bangla-medium students।
  • Government service navigator (NID, passport, taxes)।
  • Healthcare triage (rural setting)।
  • Bangla content moderation।

মূল কথা: RLHF universal recipe কিন্তু — local adaptation মানে data + culture + compute trade-off carefully balance। Bangla-LLM-এর জন্য — DPO + LoRA + crowd-sourced preferences সবচেয়ে practical pathway।

অনুশীলন

  1. KL choice: $\beta = 0$ (no KL) ও $\beta = 1$ (very strong) দু'টি RLHF run। কোনটা কী হবে?

    $\beta=0$: policy reward maximize একপাল্লায় চলবে → reward hacking, mode collapse, repetitive output, OOD exploit। $\beta=1$: KL term dominate → policy ≈ SFT, কোনো improvement নেই। Sweet spot ০.০১-০.১ এ — empirically tuned।

  2. Bradley-Terry derivation: $P(A > B) = \sigma(r_A - r_B)$ থেকে $-\log \sigma(r_A - r_B)$ loss-এ পৌঁছানো — কেন cross-entropy interpretation?

    Binary classification — preferred/not। True label = "$A$ chosen"। Probability $\sigma(r_A - r_B)$। NLL = $-\log \sigma(r_A - r_B)$। যখন $A$ chosen, this score বাড়াতে চায় → $r_A$ বাড়ে, $r_B$ কমে। Pure binary cross-entropy with predicted prob = sigmoid score difference।

  3. Pipeline thought-exercise: "RLHF skip করে directly RM থেকে best-of-N sampling করি — সমান কাজ করবে?"। Pros/cons লিখুন।

    Best-of-N: $N$ responses generate, RM-এ score, top-1 ফেরত পাঠাও। Pros: training-free, simple, effective for $N=4-8$। Cons: inference $N\times$ slow, Goodhart still applies (RM exploit), no policy improvement (always re-sample)। RLHF/DPO — model-internal improvement, inference cheap (single forward), continuous improvement possible।

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

পূর্ববর্তী পাঠ
পাঠ ২৭ · Inverse RL ও imitation