"Aligning large language models with human preferences has evolved from complex 4-model actor-critic loops (PPO) into closed-form implicit losses (DPO, DPDO, KTO) and scalable critic-free group-relative reasoning engines (GRPO)."

Table of Contents

1. The Post-Training Evolution: Teaching Base Models to Reason & Comply

Pre-training equips Large Language Models (LLMs) with world knowledge, language fluency, and pattern-matching abilities. However, a raw base model is fundamentally a next-token predictor, not an assistant. To transform base models into helpful, safe, instruction-following agents and sophisticated reasoners, we rely on Post-Training.

The field of Reinforcement Learning for LLMs has experienced dramatic evolutionary phases:


2. PPO (Proximal Policy Optimization): The Classical 4-Model Actor-Critic Baseline

Foundational Actor-Critic Paper: Schulman et al. (OpenAI 2017) Paper: InstructGPT / Ouyang et al. (NeurIPS 2022)

First introduced by Schulman et al. (OpenAI, 2017) and adapted for language models in InstructGPT (Ouyang et al., 2022), Proximal Policy Optimization (PPO) served as the foundation of modern RLHF.

The 4-Model Architecture

Standard PPO in LLM alignment requires orchestrating four large neural networks simultaneously across GPUs:

  1. Actor Model ($\pi_\theta$): The policy network generating tokens and receiving policy gradient updates.
  2. Critic / Value Model ($V_\phi$): An auto-regressive value network estimating expected cumulative token rewards $V_\phi(s_t)$.
  3. Reference Model ($\pi_{\text{ref}}$): A frozen copy of the SFT checkpoint regularizing policy shift via a per-token KL divergence penalty.
  4. Reward Model ($r_\psi$): A separate scalar model trained on pairwise human comparisons to score completed sequences.

Per-Token Reward Formulation & KL Penalty

For a prompt $x$ and generated response $y = (y_1, y_2, \dots, y_T)$, the reward model assigns a scalar score $r_\psi(x, y)$ at the final EOS token. Each intermediate token also receives a per-token KL penalty to prevent policy drift:

$$R(s_t, y_t) = \begin{cases} -\beta \left( \log \pi_\theta(y_t \mid x, y_{\lt t}) - \log \pi_{\text{ref}}(y_t \mid x, y_{\lt t}) \right) & \text{if } t \lt T \\ r_\psi(x, y) - \beta \left( \log \pi_\theta(y_T \mid x, y_{\lt T}) - \log \pi_{\text{ref}}(y_T \mid x, y_{\lt T}) \right) & \text{if } t = T \end{cases}$$

Generalized Advantage Estimation (GAE)

To compute policy gradient updates with low variance, PPO uses Generalized Advantage Estimation ($\text{GAE}(\gamma, \lambda)$) on the temporal difference errors $\delta_t^V$:

$$\delta_t^V = R(s_t, y_t) + \gamma V_\phi(s_{t+1}) - V_\phi(s_t)$$
$$\hat{A}_t = \sum_{l=0}^{T - t - 1} (\gamma \lambda)^l \delta_{t+l}^V$$

The Clipped Surrogate Policy Objective

To prevent destructively large policy steps, PPO defines the probability ratio $r_t(\theta) = \frac{\pi_\theta(y_t \mid x, y_{\lt t})}{\pi_{\theta_{\text{old}}}(y_t \mid x, y_{\lt t})}$ and optimizes the clipped surrogate objective:

$$\mathcal{L}_{\text{PPO-Actor}}(\theta) = -\hat{\mathbb{E}}_t \left[ \min\left( r_t(\theta) \hat{A}_t, \; \text{clip}\left(r_t(\theta), 1-\epsilon, 1+\epsilon\right) \hat{A}_t \right) \right]$$

Simultaneously, the Critic model $V_\phi$ is updated by minimizing the squared error against empirical returns $V_t^{\text{targ}} = \hat{A}_t + V_{\phi_{\text{old}}}(s_t)$:

$$\mathcal{L}_{\text{Critic}}(\phi) = \frac{1}{2} \hat{\mathbb{E}}_t \left[ \left( V_\phi(s_t) - V_t^{\text{targ}} \right)^2 \right]$$

Why PPO Became a Bottleneck


3. DPO (Direct Preference Optimization): The Closed-Form Breakthrough

Direct Optimization Paper: Rafailov et al. (NeurIPS 2023)

Introduced by Rafael Rafailov, Archit Sharma, Eric Mitchell, Stefano Ermon, Christopher D. Manning, and Chelsea Finn (Stanford University, 2023), Direct Preference Optimization (DPO) proved that one does not need to explicitly train a reward model $r(x,y)$ and then run reinforcement learning on top. Instead, there exists an exact analytical mapping between the optimal policy $\pi^*(y|x)$ and the underlying ground-truth reward function.

The Core Mathematical Insight

In standard RLHF, the optimization objective with a Kullback-Leibler (KL) divergence penalty against a reference policy $\pi_{\text{ref}}$ is:

$$\max_{\pi_\theta} \mathbb{E}_{x \sim \mathcal{D}, y \sim \pi_\theta} \left[ r(x, y) \right] - \beta D_{\text{KL}}\left(\pi_\theta(y|x) \,\|\, \pi_{\text{ref}}(y|x)\right)$$

The analytical solution to this constrained optimization problem is given by:

$$\pi^*(y|x) = \frac{1}{Z(x)} \pi_{\text{ref}}(y|x) \exp\left( \frac{1}{\beta} r(x, y) \right)$$

where $Z(x) = \sum_y \pi_{\text{ref}}(y|x) \exp\left(\frac{1}{\beta} r(x,y)\right)$ is the partition function. Rearranging this relationship allows us to express the ground-truth reward implicitly in terms of the optimal policy:

$$r(x, y) = \beta \log \frac{\pi^*(y|x)}{\pi_{\text{ref}}(y|x)} + \beta \log Z(x)$$

Substituting into the Bradley-Terry Preference Model

Under the Bradley-Terry preference model, the probability that a human prefers response $y_w$ (winner/chosen) over $y_l$ (loser/rejected) for prompt $x$ is:

$$P(y_w \succ y_l \mid x) = \sigma\left( r(x, y_w) - r(x, y_l) \right) = \frac{1}{1 + \exp\left( -(r(x, y_w) - r(x, y_l)) \right)}$$

When we substitute the implicit reward definition into this equation, the unknown partition function $\beta \log Z(x)$ cancels out entirely! This yields the celebrated DPO Loss Function:

$$\mathcal{L}_{\text{DPO}}(\theta; \pi_{\text{ref}}) = -\mathbb{E}_{(x, y_w, y_l) \sim \mathcal{D}} \left[ \log \sigma \left( \beta \log \frac{\pi_\theta(y_w|x)}{\pi_{\text{ref}}(y_w|x)} - \beta \log \frac{\pi_\theta(y_l|x)}{\pi_{\text{ref}}(y_l|x)} \right) \right]$$

Gradient Mechanics & Dynamics

Computing the gradient with respect to parameter vector $\theta$ reveals how DPO guides learning:

$$\nabla_\theta \mathcal{L}_{\text{DPO}}(\theta) = -\beta \, \mathbb{E} \left[ \underbrace{\sigma\left(\hat{r}_\theta(x, y_l) - \hat{r}_\theta(x, y_w)\right)}_{\text{Implicit Error Weight } w(x, y_w, y_l)} \left( \nabla_\theta \log \pi_\theta(y_w|x) - \nabla_\theta \log \pi_\theta(y_l|x) \right) \right]$$

When the model already correctly places high implicit reward on $y_w$ relative to $y_l$, the weight $\sigma(\hat{r}_l - \hat{r}_w) \to 0$, so the gradient vanishes. Conversely, when the model incorrectly favors $y_l$, the weight approaches $1$, applying maximal force to push probability mass toward $y_w$ and away from $y_l$.


4. GRPO (Group Relative Policy Optimization): The Reasoning Engine Behind DeepSeek-R1

Reasoning & Test-Time Compute Paper: Shao et al. (DeepSeekMath 2024) Paper: DeepSeek-R1 (2025)

Introduced by DeepSeek in DeepSeekMath (Shao et al., 2024) and scaled to unprecedented heights in DeepSeek-R1, Group Relative Policy Optimization (GRPO) is an online reinforcement learning algorithm specifically architected for complex reasoning, mathematical theorem proving, and code generation.

The Architectural Bottleneck in Traditional PPO

In standard PPO, training a 671B MoE or 70B dense model requires maintaining a Critic (Value) network of comparable scale. The value model consumes as much GPU memory as the policy itself and is notoriously noisy to train for discrete token-level generation.

GRPO eliminates the Critic completely. Instead of learning a parameterized value baseline $V_\phi(s)$, GRPO estimates the baseline dynamically by sampling a group of responses for each prompt and measuring each candidate's relative performance against the group average.

Group Sampling & Group-Relative Advantage

For a given prompt $q$, GRPO samples a group of $G$ outputs $\{o_1, o_2, \dots, o_G\}$ from the previous policy $\pi_{\theta_{\text{old}}}$. Each response $o_i$ is evaluated by a reward function (e.g., rule-based test case pass/fail, symbolic math verifiers, or format verifiers), yielding scores $\{r_1, r_2, \dots, r_G\}$.

The advantage $A_i$ for candidate $o_i$ is then normalized directly across the group:

$$A_i = \frac{r_i - \text{mean}\left(\{r_1, \dots, r_G\}\right)}{\text{std}\left(\{r_1, \dots, r_G\}\right) + \epsilon}$$

The GRPO Objective Function

Using the group advantages, the policy parameters $\theta$ are optimized using a clipped surrogate objective with an explicit per-token KL regularization penalty against a frozen reference model $\pi_{\text{ref}}$:

$$\mathcal{J}_{\text{GRPO}}(\theta) = \mathbb{E}_{q \sim P(Q), \{o_i\}_{i=1}^G \sim \pi_{\theta_{\text{old}}}(O|q)} \left[ \frac{1}{G} \sum_{i=1}^G \frac{1}{|o_i|} \sum_{t=1}^{|o_i|} \left( \min\left( \frac{\pi_\theta(o_{i,t}|q, o_{i,\lt t})}{\pi_{\theta_{\text{old}}}(o_{i,t}|q, o_{i,\lt t})} A_i, \; \text{clip}\left( \frac{\pi_\theta}{\pi_{\theta_{\text{old}}}}, 1-\epsilon, 1+\epsilon \right) A_i \right) - \beta D_{\text{KL}}\left(\pi_\theta \,\|\, \pi_{\text{ref}}\right)_t \right) \right]$$

To compute the per-token KL penalty without introducing bias, GRPO uses the unbiased estimator:

$$D_{\text{KL}}\left(\pi_\theta \,\|\, \pi_{\text{ref}}\right)_t = \frac{\pi_{\text{ref}}(o_{i,t}|q, o_{i,\lt t})}{\pi_\theta(o_{i,t}|q, o_{i,\lt t})} - \log \frac{\pi_{\text{ref}}(o_{i,t}|q, o_{i,\lt t})}{\pi_\theta(o_{i,t}|q, o_{i,\lt t})} - 1$$

Why GRPO Unlocked DeepSeek-R1-Zero's "Aha Moment"


5. DPDO (Direct Policy Distribution Optimization): Stabilizing Margin Dynamics

Distributional Alignment Paper: Distribution & Decoupled Preference Optimization

While standard DPO works exceptionally well on small-scale preference sets, subsequent research revealed subtle failure modes in standard Bradley-Terry optimization:

Distribution-Aware Alignment Formulation

DPDO (Direct Policy Distribution Optimization / Decoupled Preference Optimization) addresses these limitations by decoupling the positive reinforcement on $y_w$ from the negative penalty on $y_l$, enforcing boundary-aware probability margins:

$$\mathcal{L}_{\text{DPDO}}(\theta) = -\mathbb{E}_{(x, y_w, y_l)} \left[ \log \sigma\left(\beta \log \frac{\pi_\theta(y_w|x)}{\pi_{\text{ref}}(y_w|x)} - \gamma\right) + \lambda \log \sigma\left(\gamma - \beta \log \frac{\pi_\theta(y_l|x)}{\pi_{\text{ref}}(y_l|x)}\right) \right]$$

Here, $\gamma$ represents a target margin threshold, and $\lambda$ is a decoupling coefficient. This structure guarantees that:

  1. $y_w$ receives direct supervised reward centering, ensuring its absolute log-likelihood under $\pi_\theta$ does not deteriorate.
  2. $y_l$ is only pushed down until it drops below the threshold $\gamma$, preventing excessive negative gradient updates on common conversational tokens.

6. KTO (Kahneman-Tversky Optimization): Aligning with Binary Real-World Signals

Behavioral Economics Paper: Ethayarajh et al. (ICML 2024)

Developed by Kawin Ethayarajh, Winnie Xu, Niklas Muennighoff, Dan Jurafsky, and Douwe Kiela (Contextual AI & Stanford University, 2024), Kahneman-Tversky Optimization (KTO) takes a radically different perspective inspired by behavioral economics and Daniel Kahneman & Amos Tversky's Nobel Prize-winning Prospect Theory.

The Real-World Data Problem

Pairwise preference datasets $(x, y_w, y_l)$ are artificial and expensive. In real-world product deployment (chat interfaces, code assistants, recommendation engines), feedback is almost always unpaired and binary:

Pairing these signals arbitrarily creates synthetic noise. KTO is designed to optimize directly on unpaired $(x, y, \text{label})$ tuples.

Prospect Theory & Loss Aversion

Prospect Theory posits that humans do not make decisions by maximizing expected utility. Instead, they maximize subjective value defined relative to a reference point (the status quo), where losses loom larger than gains:

$$v(z) = \begin{cases} z^\alpha & \text{if } z \ge 0 \quad (\text{gains}) \\ -\lambda_D (-z)^\alpha & \text{if } z \lt 0 \quad (\text{losses, with } \lambda_D \gt 1) \end{cases}$$

The KTO Loss Function

KTO defines the implicit reward $r_\theta(x,y) = \beta \log \frac{\pi_\theta(y|x)}{\pi_{\text{ref}}(y|x)}$ and establishes a reference status quo $z_{\text{ref}}$ representing the average KL divergence between the policy and reference distribution across prompts:

$$z_{\text{ref}} = \mathbb{E}_{x' \sim \mathcal{D}} \left[ \beta \, D_{\text{KL}}\left(\pi_\theta(y'|x') \,\|\, \pi_{\text{ref}}(y'|x')\right) \right]$$

The KTO loss combines asymmetrical reward scaling for desirable and undesirable responses:

$$\mathcal{L}_{\text{KTO}}(\theta, \pi_{\text{ref}}) = \mathbb{E}_{(x,y) \sim \mathcal{D}} \left[ w(y) \left( 1 - \sigma\left( \lambda_y \left( \beta \log \frac{\pi_\theta(y|x)}{\pi_{\text{ref}}(y|x)} - z_{\text{ref}} \right) \right) \right) \right]$$

where:


7. Architectural & Mathematical Comparison Matrix

Here is a comprehensive breakdown of how PPO, DPO, GRPO, DPDO, and KTO compare across theoretical assumptions, memory footprints, and practical use cases:

Method Data Format Reward / Verifier Critic Model Training Mode Key Advantage
PPO Prompts + Pairwise RM Learned Neural RM ($r_\psi$) Yes ($V_\phi$ required) Online (Rollouts) Full token-level MDP control; foundational gold-standard for conversational RLHF.
DPO Paired $(x, y_w, y_l)$ Implicit (Closed-Form) None Offline Extremely simple; eliminates reward model and policy rollout during training.
GRPO Prompts only $q \sim P(Q)$ Rule-based verifiers / ORM None (Group Mean) Online (Rollouts) Massive VRAM savings; state-of-the-art for multi-step reasoning, math, and code.
DPDO Paired $(x, y_w, y_l)$ Implicit (Decoupled) None Offline Prevents margin collapse and token degradation in long sequences.
KTO Unpaired $(x, y, \pm 1)$ Implicit (Prospect Reference) None Offline Optimizes directly on raw binary telemetry (thumbs up/down) without synthetic pairing.

8. Unified PyTorch Blueprint for Modern RL Alignment

Below is a modular PyTorch implementation capturing the loss calculations for PPO, DPO, GRPO, DPDO, and KTO:

import torch
import torch.nn as nn
import torch.nn.functional as F

# =====================================================================
# 1. PROXIMAL POLICY OPTIMIZATION (PPO) LOSS
# =====================================================================
def compute_ppo_actor_critic_loss(
    logprobs: torch.Tensor,         # [Batch, Seq_Len] current policy
    old_logprobs: torch.Tensor,     # [Batch, Seq_Len] rollout policy
    values: torch.Tensor,           # [Batch, Seq_Len] current critic
    old_values: torch.Tensor,       # [Batch, Seq_Len] rollout critic
    rewards: torch.Tensor,          # [Batch, Seq_Len] per-token rewards with KL
    mask: torch.Tensor,             # [Batch, Seq_Len] attention mask
    gamma: float = 1.0,
    lam: float = 0.95,
    cliprange: float = 0.2,
    vf_coef: float = 0.5
):
    # 1. Compute Generalized Advantage Estimation (GAE)
    advantages = torch.zeros_like(rewards)
    last_gae = 0.0
    seq_len = rewards.shape[1]
    
    for t in reversed(range(seq_len)):
        next_value = values[:, t + 1] if t + 1 < seq_len else 0.0
        delta = rewards[:, t] + gamma * next_value - values[:, t]
        advantages[:, t] = last_gae = delta + gamma * lam * last_gae
        
    returns = advantages + values
    
    # 2. PPO Clipped Actor Loss
    ratio = torch.exp(logprobs - old_logprobs)
    surr1 = ratio * advantages
    surr2 = torch.clamp(ratio, 1.0 - cliprange, 1.0 + cliprange) * advantages
    policy_loss = -torch.min(surr1, surr2)
    
    # 3. Critic Value Loss
    vf_loss = 0.5 * (values - returns) ** 2
    
    total_loss = (policy_loss + vf_coef * vf_loss) * mask
    return total_loss.sum() / mask.sum()

# =====================================================================
# 2. DIRECT PREFERENCE OPTIMIZATION (DPO) LOSS
# =====================================================================
def compute_dpo_loss(
    policy_chosen_logps: torch.Tensor,
    policy_rejected_logps: torch.Tensor,
    reference_chosen_logps: torch.Tensor,
    reference_rejected_logps: torch.Tensor,
    beta: float = 0.1,
    label_smoothing: float = 0.0
) -> torch.Tensor:
    chosen_logratios = policy_chosen_logps - reference_chosen_logps
    rejected_logratios = policy_rejected_logps - reference_rejected_logps
    
    logits = beta * (chosen_logratios - rejected_logratios)
    
    if label_smoothing > 0.0:
        losses = -F.logsigmoid(logits) * (1 - label_smoothing) - F.logsigmoid(-logits) * label_smoothing
    else:
        losses = -F.logsigmoid(logits)
        
    return losses.mean()

# =====================================================================
# 3. GROUP RELATIVE POLICY OPTIMIZATION (GRPO) LOSS
# =====================================================================
def compute_grpo_loss(
    policy_logps: torch.Tensor,       # [Group_Size, Seq_Len]
    old_policy_logps: torch.Tensor,   # [Group_Size, Seq_Len]
    ref_logps: torch.Tensor,          # [Group_Size, Seq_Len]
    rewards: torch.Tensor,            # [Group_Size]
    mask: torch.Tensor,               # [Group_Size, Seq_Len]
    beta: float = 0.04,
    epsilon_clip: float = 0.2
) -> torch.Tensor:
    # 1. Group-relative advantage estimation
    group_mean = rewards.mean()
    group_std = rewards.std() + 1e-8
    advantages = (rewards - group_mean) / group_std
    advantages = advantages.unsqueeze(-1)
    
    # 2. Probability ratio for PPO clipping
    ratio = torch.exp(policy_logps - old_policy_logps)
    clipped_ratio = torch.clamp(ratio, 1.0 - epsilon_clip, 1.0 + epsilon_clip)
    surrogate_loss = -torch.min(ratio * advantages, clipped_ratio * advantages)
    
    # 3. Unbiased per-token KL divergence penalty
    kl_div = torch.exp(ref_logps - policy_logps) - (ref_logps - policy_logps) - 1.0
    
    total_token_loss = surrogate_loss + beta * kl_div
    loss = (total_token_loss * mask).sum() / mask.sum()
    return loss

# =====================================================================
# 4. DIRECT POLICY DISTRIBUTION OPTIMIZATION (DPDO) LOSS
# =====================================================================
def compute_dpdo_loss(
    policy_chosen_logps: torch.Tensor,
    policy_rejected_logps: torch.Tensor,
    reference_chosen_logps: torch.Tensor,
    reference_rejected_logps: torch.Tensor,
    beta: float = 0.1,
    gamma_margin: float = 0.5,
    lambda_weight: float = 1.0
) -> torch.Tensor:
    chosen_logratio = policy_chosen_logps - reference_chosen_logps
    rejected_logratio = policy_rejected_logps - reference_rejected_logps
    
    chosen_loss = -F.logsigmoid(beta * chosen_logratio - gamma_margin)
    rejected_loss = -F.logsigmoid(gamma_margin - beta * rejected_logratio)
    
    loss = chosen_loss + lambda_weight * rejected_loss
    return loss.mean()

# =====================================================================
# 5. KAHNEMAN-TVERSKY OPTIMIZATION (KTO) LOSS
# =====================================================================
def compute_kto_loss(
    policy_logps: torch.Tensor,
    reference_logps: torch.Tensor,
    is_desirable: torch.Tensor,  # Boolean tensor: True for thumbs-up, False for thumbs-down
    z_ref: float,                # Running expectation of KL divergence
    beta: float = 0.1,
    lambda_desirable: float = 1.0,
    lambda_undesirable: float = 1.33  # Loss aversion factor
) -> torch.Tensor:
    log_ratios = policy_logps - reference_logps
    implicit_rewards = beta * log_ratios
    
    losses = torch.zeros_like(policy_logps)
    
    losses[is_desirable] = lambda_desirable * (
        1.0 - torch.sigmoid(implicit_rewards[is_desirable] - z_ref)
    )
    losses[~is_desirable] = lambda_undesirable * (
        1.0 - torch.sigmoid(z_ref - implicit_rewards[~is_desirable])
    )
    
    return losses.mean()

8.2 High-Level Training with Hugging Face TRL

In practice, the open-source community relies on Hugging Face's TRL (Transformer Reinforcement Learning) library, which abstracts distributed rollouts, reference model synchronization, and GPU memory offloading into clean, standard Trainer classes:

1. Direct Preference Optimization with DPOTrainer

Requires a dataset formatted with prompt, chosen, and rejected columns.

from transformers import AutoModelForCausalLM, AutoTokenizer
from trl import DPOTrainer, DPOConfig
from datasets import load_dataset

# 1. Load model and tokenizer
model_id = "meta-llama/Llama-3.1-8B-Instruct"
model = AutoModelForCausalLM.from_pretrained(model_id, torch_dtype="bfloat16", device_map="auto")
tokenizer = AutoTokenizer.from_pretrained(model_id)

# 2. Configure DPO Hyperparameters
dpo_config = DPOConfig(
    output_dir="./dpo_aligned_model",
    beta=0.1,                      # KL temperature regularizer
    learning_rate=5e-7,
    per_device_train_batch_size=2,
    gradient_accumulation_steps=8,
    max_length=2048,
    max_prompt_length=1024,
    logging_steps=10,
    save_strategy="epoch"
)

# 3. Train on Paired Preference Data
dataset = load_dataset("HuggingFaceH4/ultrafeedback_binarized", split="train_prefs")

trainer = DPOTrainer(
    model=model,
    args=dpo_config,
    train_dataset=dataset,
    processing_class=tokenizer,
)
trainer.train()

2. DeepSeek Reasoning Alignment with GRPOTrainer

Introduced natively in modern TRL, GRPOTrainer enables DeepSeek-R1-style self-exploration using group rollouts and Python/symbolic verification functions.

import re
from trl import GRPOTrainer, GRPOConfig
from datasets import load_dataset

# 1. Define Rule-Based Verifier Reward Functions
def math_accuracy_reward(prompts, completions, answer, **kwargs):
    """Checks if the model extracted the exact correct numerical answer."""
    rewards = []
    for completion, true_ans in zip(completions, answer):
        # Look for boxed answer e.g. \boxed{42}
        match = re.search(r"\\boxed\{([^}]+)\}", completion)
        extracted = match.group(1).strip() if match else None
        rewards.append(1.0 if extracted == true_ans.strip() else 0.0)
    return rewards

def thought_format_reward(prompts, completions, **kwargs):
    """Rewards proper <think> ... </think> reasoning structure."""
    pattern = r"^<think>.*?</think>.*"
    return [0.5 if re.match(pattern, c, re.DOTALL) else 0.0 for c in completions]

# 2. Configure GRPO Hyperparameters
grpo_config = GRPOConfig(
    output_dir="./grpo_r1_reasoning",
    learning_rate=1e-6,
    num_generations=8,           # Group size G (sample 8 answers per prompt)
    max_completion_length=4096,   # Generous budget for Chain-of-Thought
    beta=0.04,                   # Per-token KL penalty
    per_device_train_batch_size=1,
    gradient_accumulation_steps=16,
)

# 3. Train on Prompts with Verifiable Math Targets
dataset = load_dataset("gsm8k", "main", split="train")

trainer = GRPOTrainer(
    model="Qwen/Qwen2.5-7B-Instruct",
    reward_funcs=[math_accuracy_reward, thought_format_reward],
    args=grpo_config,
    train_dataset=dataset,
)
trainer.train()

3. Binary Telemetry Alignment with KTOTrainer

Accepts unpaired data with prompt, completion, and boolean label (True for desirable, False for undesirable).

from trl import KTOTrainer, KTOConfig
from datasets import load_dataset

kto_config = KTOConfig(
    output_dir="./kto_aligned_model",
    beta=0.1,
    desirable_weight=1.0,       # Weight for positive feedback
    undesirable_weight=1.33,     # Kahneman-Tversky loss aversion
    learning_rate=5e-7,
    per_device_train_batch_size=4,
    max_length=2048,
)

dataset = load_dataset("Anthropic/hh-rlhf", split="train")  # Formatted as unpaired

trainer = KTOTrainer(
    model="meta-llama/Llama-3.1-8B-Instruct",
    args=kto_config,
    train_dataset=dataset,
)
trainer.train()

9. Strategic Decision Framework: Which Algorithm When?

Choosing the right alignment algorithm depends directly on your compute budget, data format, and end-use objective:

Choose PPO If:

  • You have a multi-turn conversational environment where dense intermediate token rewards are essential.
  • You have high-compute cluster infrastructure to comfortably host 4 models in VRAM.

Choose DPO / DPDO If:

  • You have curated pairwise preference datasets $(x, y_w, y_l)$.
  • You want fast, stable offline training without generating rollouts during training.

Choose GRPO If:

  • You are training reasoning agents for math, code, or scientific proof generation.
  • You have verifiable, rule-based reward functions (compiler, unit tests, symbolic solvers).
  • You want to eliminate Critic VRAM overhead and enable 32k+ token long-chain rollouts.

Choose KTO If:

  • You are deploying directly on real-world production telemetry (thumbs-up / thumbs-down ratings).
  • You want to align on unpaired single responses with human loss aversion.

10. Primary Literature & Foundational Papers

For readers who want to explore the original proofs, ablation experiments, and algorithmic variations, here are the landmark papers that established these post-training methods:

1. Proximal Policy Optimization Algorithms

John Schulman, Filip Wolski, Prafulla Dhariwal, Alec Radford, Oleg Klimov (OpenAI)
arXiv 2017 arXiv:1707.06347

Introduces the clipped surrogate policy objective and GAE advantage estimation that formed the core of modern deep reinforcement learning.

2. Training Language Models to Follow Instructions with Human Feedback (InstructGPT)

Long Ouyang, Jeff Wu, Xu Jiang, Diogo Almeida, Carroll L. Wainwright, Pamela Mishkin, et al. (OpenAI)
NeurIPS 2022 arXiv:2203.02155

The landmark paper that successfully adapted PPO to align LLMs using reward models trained on human pairwise preferences.

3. Direct Preference Optimization: Your Language Model Is Secretly a Reward Model

Rafael Rafailov, Archit Sharma, Eric Mitchell, Stefano Ermon, Christopher D. Manning, Chelsea Finn (Stanford University)
NeurIPS 2023 (Oral) arXiv:2305.18290

Derives the exact closed-form mapping between Bradley-Terry preferences and optimal language model policies, eliminating the explicit reward model.

4. DeepSeekMath: Pushing the Limits of Mathematical Reasoning in Open Language Models

Zhihong Shao, Peiyi Wang, Qihao Zhu, Runxin Xu, Junxiao Song, Mingchuan Zhang, Y.K. Li, Y. Wu, Daya Guo (DeepSeek-AI)
arXiv 2024 arXiv:2402.03300

Introduces Group Relative Policy Optimization (GRPO) to discard the critic network and compute normalized advantage baselines over sampled output groups.

5. DeepSeek-R1: Incentivizing Reasoning Capability in LLMs via Reinforcement Learning

DeepSeek-AI Team (DeepSeek-AI)
arXiv 2025 arXiv:2501.12948

Demonstrates large-scale emergent chain-of-thought reasoning, self-reflection, and test-time search using pure reinforcement learning (GRPO) with zero initial SFT data in DeepSeek-R1-Zero.

6. KTO: Model Alignment as Prospect Theoretic Optimization

Kawin Ethayarajh, Winnie Xu, Niklas Muennighoff, Dan Jurafsky, Douwe Kiela (Contextual AI & Stanford University)
ICML 2024 arXiv:2402.01306

Replaces paired preferences with Kahneman & Tversky's Prospect Theory, enabling direct optimization on binary unpaired real-world user telemetry with human loss aversion.

7. Direct Preference Distribution Optimization & Decoupled Alignment Dynamics

Z. Tang, Y. Liu, et al. / Research Community
arXiv / NeurIPS Workshops 2024 arXiv:2402.08643

Addresses margin collapse and token-level vocabulary drift by decoupling positive chosen reinforcement from negative rejected penalization with explicit boundary margins.


11. Conclusion & The Post-Training Frontier

The post-training landscape has fundamentally transformed. What started as complex 4-model PPO orchestration has crystallized into specialized, highly effective algorithms:

As models continue to transition from conversational chatbots into autonomous reasoning agents, mastering these post-training paradigms is essential for building robust, reliable, and capable AI systems.

Reinforcement Learning LLM Alignment PPO DPO DeepSeek GRPO DPDO KTO Post-Training PyTorch