Skip to content
ml-recall

Topic notes

Alignment & Reasoning

Steering a pretrained LLM toward preferred behaviour and better reasoning — RLHF (reward model, PPO, KL penalty), DPO, reward hacking, GRPO and DeepSeek-R1, and self-consistency.

4-min read AI-checked

Practise 26 questions Take a test

Key ideas

Formulas

LDPO=−log⁡σ(βlog⁡πθ(yw∣x)πref(yw∣x)−βlog⁡πθ(yl∣x)πref(yl∣x))\mathcal{L}_{\text{DPO}} = -\log \sigma\Big(\beta \log \frac{\pi_\theta(y_w \mid x)}{\pi_{\text{ref}}(y_w \mid x)} - \beta \log \frac{\pi_\theta(y_l \mid x)}{\pi_{\text{ref}}(y_l \mid x)}\Big)

Worked example

In code

import torch
import torch.nn.functional as F

def rm_loss(r_chosen, r_rejected):                     # Bradley-Terry pairwise loss
    return -F.logsigmoid(r_chosen - r_rejected)

def dpo_loss(pi_w, pi_l, ref_w, ref_l, beta=0.1):     # summed log-probs of whole responses
    return -F.logsigmoid(beta * ((pi_w - ref_w) - (pi_l - ref_l)))

t = torch.tensor
print(round(rm_loss(t(1.0), t(0.2)).item(), 3))              # 0.371
print(round(rm_loss(t(6.0), t(5.2)).item(), 3))              # 0.371: a shift changes nothing
print(round(dpo_loss(t(-40.), t(-60.), t(-42.), t(-57.)).item(), 3))  # 0.474
r = t([1.0, 0.0, 0.0, 1.0])                                  # rewards of one GRPO group
print(((r - r.mean()) / r.std(unbiased=False)).tolist())     # [1.0, -1.0, -1.0, 1.0]

Common pitfalls

References

  1. Hugging Face LLM Course — Ch. 12, Introduction to Reinforcement Learning and its Role in LLMs (What is RL?, RLHF)
  2. Ouyang et al. (2022), Training language models to follow instructions with human feedback (InstructGPT) — Sec. 3.1 High-level methodology, 3.5 Models (Reward modeling, Reinforcement learning)
  3. Gao, Schulman & Hilton (2022), Scaling Laws for Reward Model Overoptimization — Sec. 1 Introduction, 2 Methodology (synthetic gold reward model setup)
  4. Rafailov et al. (2023), Direct Preference Optimization: Your Language Model is Secretly a Reward Model — Sec. 3 Preliminaries, 4 Direct Preference Optimization
  5. DeepSeek-AI (2025), DeepSeek-R1: Incentivizing Reasoning Capability in LLMs via Reinforcement Learning — Sec. 2 DeepSeek-R1-Zero (2.1 GRPO, 2.2 Reward Design), 3 DeepSeek-R1
  6. Wang et al. (2023), Self-Consistency Improves Chain of Thought Reasoning in Language Models — Sec. 2 Self-Consistency over Diverse Reasoning Paths
  7. Wikipedia: Reward hacking — Reward hacking in modern language models (length bias, sycophancy, modifying test code)
  8. Bai et al. (2022), Constitutional AI: Harmlessness from AI Feedback — Abstract; Sec. 3 Critiques, Revisions, and Supervised Learning; Sec. 4 Reinforcement Learning from AI Feedback