LLM Masterclass / Module 7 of 10 Phase 3: Post-Training Alignment, Human-in-the-Loop & High-Throughput Serving

Post-Training Alignment — RLHF (PPO), Direct Preference Optimization (DPO), KTO & GRPO Reasoning

30 min study + 2 Live Wasm Labs
⚡ Answer-First Executive Summary (TL;DR) Module 7 Key Takeaways
  • ✓ Classic RLHF fits a Bradley-Terry Reward Model r_φ(x, y) on human pairwise preferences (y_w ≻ y_l) and optimizes the policy π_θ via PPO with a KL-divergence penalty β D_KL(π_θ || π_ref) to prevent reward hacking—requiring 4 models in memory (Actor, Reference, Critic, Reward).
  • ✓ Direct Preference Optimization (DPO, Rafailov et al. 2023) analytically solves the KL-constrained reward maximization objective to express the reward directly in terms of the optimal policy log-ratio β log(π_θ(y|x) / π_ref(y|x)), eliminating both the separate Reward Model and online RL rollouts.
  • ✓ KTO (Kahneman-Tversky Optimization) trains directly on abundant unpaired binary thumbs-up / thumbs-down production logs without requiring paired (chosen, rejected) completions for the exact same prompt.
  • ✓ Group Relative Policy Optimization (GRPO, powering DeepSeek-R1) eliminates the PPO Value/Critic network (saving ~50% RL memory) by sampling a group of G responses per prompt, scoring them with deterministic code/math verifiers, and normalizing advantage against the group mean and standard deviation.

01. Post-Training Alignment Algorithms Comparison (PPO vs. DPO vs. KTO vs. ORPO vs. GRPO)

Table 7.1 — Frontier LLM Post-Training & Alignment Paradigms
Method Models in VRAM Data Format Required Core Objective / Loss Best Production Use Case
RLHF (PPO) 4 (Actor, Ref, Critic, RM) Pairwise (x, yw, yl) for RM + prompts for RL max E[rφ(x,y) - β DKL(πθ ‖ πref)] Large-scale multi-objective safety + helpfulness tuning.
DPO 2 (Actor + Frozen Ref) Paired preference triples (x, yw, yl) -log σ(β log(πθ(yw)/πref(yw)) - β log(πθ(yl)/πref(yl))) Fast, stable offline preference alignment (no RL instability).
KTO 2 (Actor + Frozen Ref) Unpaired (x, y, label ∈ {+1, -1}) Prospect-theory utility over log-ratio vs. zref Aligning directly on production thumbs-up / thumbs-down user logs!
ORPO / SimPO 1 (Actor only!) Paired preference triples (x, yw, yl) LSFT(yw) - λ log σ(log(oddsθ(yw) / oddsθ(yl))) Single-stage joint SFT + preference alignment on constrained VRAM.
GRPO (RLVR) 2 (Actor + Ref + Code/Math Verifier) Prompts + deterministic verifier tests Clipped surrogate with group advantage Ai = (ri - μr) / σr Training reasoning models (DeepSeek-R1 style) on code, SQL, and math.

💻 Hands-On WebAssembly LLM Engineering Labs (Module 7)

Click Run & Edit Live (Wasm) on any lab below to execute and modify the algorithm in our browser Pyodide runtime.

▶ Interactive Wasm Lab

Lab 7.1: Implementing Direct Preference Optimization (DPO) Loss & Implicit Reward Margins

Compute exact DPO loss, implicit Bradley-Terry rewards r_hat(x, y) = β log(π_θ / π_ref), and preference accuracy over chosen vs. rejected completions.

import math

def log_sigmoid(x: float) -> float:
    # Numerically stable log(1 / (1 + exp(-x)))
    return -math.log1p(math.exp(-x)) if x >= 0 else x - math.log1p(math.exp(x))

def compute_dpo_step(
    *,
    policy_chosen_logp: float,
    policy_rejected_logp: float,
    ref_chosen_logp: float,
    ref_rejected_logp: float,
    beta: float = 0.1,
) -> dict[str, float]:
    # Log-ratios between active policy π_θ and frozen reference policy π_ref
    chosen_logratios = policy_chosen_logp - ref_chosen_logp
    rejected_logratios = policy_rejected_logp - ref_rejected_logp

    # DPO implicit rewards: r_hat(x, y) = beta * log(π_θ(y|x) / π_ref(y|x))
    reward_chosen = beta * chosen_logratios
    reward_rejected = beta * rejected_logratios
    reward_margin = reward_chosen - reward_rejected

    # DPO Loss: -log σ(r_chosen - r_rejected)
    loss = -log_sigmoid(reward_margin)
    pref_prob = 1.0 / (1.0 + math.exp(-reward_margin))

    return {
        "dpo_loss": round(loss, 5),
        "reward_chosen": round(reward_chosen, 4),
        "reward_rejected": round(reward_rejected, 4),
        "margin": round(reward_margin, 4),
        "win_prob": round(pref_prob, 4),
    }

print("[1] Epoch 0 (Policy == Reference -> Margin=0, Loss=ln(2)=0.69315):")
print("   ", compute_dpo_step(policy_chosen_logp=-12.0, policy_rejected_logp=-14.0, ref_chosen_logp=-12.0, ref_rejected_logp=-14.0, beta=0.2))

print("\n[2] Epoch 2 (Policy shifts probability mass toward Chosen & away from Rejected):")
print("   ", compute_dpo_step(policy_chosen_logp=-9.5, policy_rejected_logp=-18.0, ref_chosen_logp=-12.0, ref_rejected_logp=-14.0, beta=0.2))
▶ Interactive Wasm Lab

Lab 7.2: DeepSeek-R1 Style GRPO (Group Relative Policy Optimization) with Verifiable Rewards

Simulate a Critic-free GRPO training step over a group of G=6 sampled reasoning chains scored by a deterministic math/format verifier.

import math
import re

# Group of G=6 sampled rollouts for prompt: "Compute 17 * 24 and wrap answer in <answer>...</answer>"
rollouts = [
    "<think>17*20=340, 17*4=68, 340+68=408.</think><answer>408</answer>",
    "<think>17*24 = 408</think><answer>408</answer>",
    "<think>17*20=340, 17*4=58, 340+58=398.</think><answer>398</answer>",
    "The answer is 408",
    "<think>Let me double check: 24*10=240, 24*7=168, sum=408.</think><answer>408</answer>",
    "<think>17*24 = 418</think><answer>418</answer>",
]

def verifiable_reward_fn(response: str, ground_truth: str = "408") -> float:
    reward = 0.0
    # 1. Structural Format Reward (+0.25 for <think>...</think><answer>...</answer>)
    if re.search(r"<think>.*?</think>s*<answer>.*?</answer>", response):
        reward += 0.25
    # 2. Deterministic Correctness Reward (+1.0 for exact answer match)
    m = re.search(r"<answer>(.*?)</answer>", response)
    if m and m.group(1).strip() == ground_truth:
        reward += 1.0
    return reward

rewards = [verifiable_reward_fn(r) for r in rollouts]
mean_r = sum(rewards) / len(rewards)
std_r = math.sqrt(sum((r - mean_r) ** 2 for r in rewards) / len(rewards)) + 1e-8
# GRPO Advantage: A_i = (r_i - mean(r)) / std(r) — Zero Critic network needed!
advantages = [(r - mean_r) / std_r for r in rewards]

print(f"GRPO Group Stats (G={len(rollouts)}): mean_reward={mean_r:.3f}, std_reward={std_r:.3f}")
print("-" * 78)
for idx, (resp, r, adv) in enumerate(zip(rollouts, rewards, advantages), 1):
    direction = "▲ REINFORCE" if adv > 0 else "▼ PENALIZE "
    print(f"  Rollout #{idx} | R={r:>4.2f} | Advantage A_i={adv:>+6.3f} ({direction}) | {resp[:50]}")

Frequently Asked Staff LLM Interview Questions (Module 7)

Why do both PPO and DPO require a frozen Reference Policy (π_ref) and KL regularizer β? ▸

Without a KL-divergence penalty anchoring the active policy π_θ to the pre-aligned SFT model π_ref, the policy rapidly exploits narrow flaws in the reward signal (Goodhart’s Law / Reward Hacking)—for example, outputting gibberish suffixes or repetitive markdown headers that trick a reward model into outputting high scores while destroying language fluency.

When does Online RL (PPO / GRPO) outperform Offline DPO? ▸

Offline DPO trains on a static dataset of pre-collected (y_w, y_l) pairs, which can drift off-policy as π_θ updates. Online RL (especially GRPO with Verifiable Rewards on math, code compilation, SQL execution, and formal logic) samples fresh on-policy rollouts from π_θ at every step and checks them against ground-truth verifiers, enabling self-correction and emergent chain-of-thought reasoning.

How does GRPO eliminate the Critic model required by PPO? ▸

In standard PPO, estimating the baseline advantage A_t = R_t - V_ψ(s_t) requires a separate Critic neural network V_ψ of the same size as the Actor LLM. GRPO instead samples G completions (e.g., G = 8 or 16) for the same prompt x, computes scalar rewards r_1..r_G, and uses the group’s empirical z-score A_i = (r_i - mean(r)) / (std(r) + ε) as the baseline!