Derive the closed-form Direct Preference Optimization (DPO) objective from the KL-constrained RLHF reward, eliminate the Value Critic via Group Relative Policy Optimization (GRPO), and examine how HybridFlow (veRL) orchestrates distributed RL dataflows.
1.The systems crisis of four-model PPO in RLHF#
Pretraining minimizes next-token cross-entropy over internet text, producing a base model that completes documents rather than solving user instructions or verifying multi-step proofs. Ouyang et al. (InstructGPT, arXiv:2203.02155[1]Training language models to follow instructions with human feedbackOpen arXiv:2203.02155 ↗) established the three-stage RLHF pipeline: Supervised Fine-Tuning (SFT), fitting a Bradley-Terry Reward Model on human preference pairs , and optimizing the policy via Proximal Policy Optimization (PPO) under a reverse-KL penalty from the reference model :
While effective, online PPO creates a severe AI Infrastructure bottleneck: four 70B-class models must reside and execute concurrently in GPU memory:
- Actor Policy (trainable: weights + gradients + FP32 AdamW state).
- Value Critic (trainable: another full model of weights + gradients + AdamW state to estimate token-level Generalized Advantage Estimation baselines).
- Reference Policy (frozen: forward-only log-probabilities).
- Reward Model (frozen: forward-only scalar scoring).
At scale, holding two trainable models () and two inference models () requires over of aggregate VRAM before activation buffers, while alternating between memory-bound autoregressive rollout generation and compute-bound backward passes.
2.Direct Preference Optimization (DPO): Your LLM is secretly a reward model#
Rafailov et al. (DPO, arXiv:2305.18290[2]Direct Preference Optimization: Your Language Model is Secretly a Reward ModelOpen arXiv:2305.18290 ↗) asked whether we can optimize the exact KL-constrained RLHF objective in closed form without ever training an explicit reward model or running online RL sampling.
Start with the KL-constrained reward maximization objective at fixed prompt :
where is the partition function independent of . Because the KL divergence is minimized at when the two distributions are identical, the unique global optimal policy is the Gibbs distribution:
Take the logarithm and solve algebraically for the ground-truth reward in terms of :
Now substitute this reparameterized reward into the Bradley-Terry preference model . Because the intractable partition term depends only on the prompt , it cancels out identically in the difference ! Replacing with our parameterized policy yields the exact DPO Loss:
Furthermore, taking the gradient with respect to reveals why DPO behaves like a self-normalizing contrastive update:
where is the implicit reward margin.
3.DeepSeek-R1 and Group Relative Policy Optimization (GRPO)#
While offline DPO excels at stylistic and instruction alignment, unlocking frontier multi-step mathematical, coding, and scientific reasoning requires online exploration where the model generates its own chain-of-thought trajectories and learns from verifiable outcomes.
To make large-scale online RL economically tractable, DeepSeek-R1 (arXiv:2501.12948[4]DeepSeek-R1: Incentivizing Reasoning Capability in LLMs via Reinforcement LearningOpen arXiv:2501.12948 ↗) replaces PPO with Group Relative Policy Optimization (GRPO) and replaces neural reward models (which suffer from reward hacking on long reasoning chains) with deterministic rule-based verifiers (exact answer matching, compiler/unit-test execution, and format checks).
Instead of maintaining a / Value Critic to predict baseline returns, GRPO samples a group of completions from the old policy for each prompt , scores them to obtain scalar rewards , and uses the group z-score directly as the advantage for every token in completion :
The GRPO objective combines PPO's clipped importance-sampling ratio with Schulman's unbiased, strictly non-negative KL divergence estimator placed directly outside the clip operator:
where and the per-token KL penalty is:
def grpo_step_loss(
logp_new: Tensor,
logp_old: Tensor,
logp_ref: Tensor,
rewards: Tensor,
eps_clip: float = 0.2,
beta_kl: float = 0.04,
) -> tuple[Tensor, Tensor]:
"""
Compute DeepSeek-R1 Group Relative Policy Optimization (GRPO) loss over a group of G completions.
Shapes: logp_* [G, T], rewards [G].
"""
# 1. Group-relative normalized advantage (eliminates the separate Value Critic network)
mean_r = rewards.mean()
std_r = rewards.std(unbiased=False)
advantages = ((rewards - mean_r) / (std_r + 1e-8)).unsqueeze(-1) # [G, 1] broadcast across tokens
# 2. Importance sampling ratio & PPO clipped surrogate objective
ratio = torch.exp(logp_new - logp_old.detach())
surr1 = ratio * advantages
surr2 = torch.clamp(ratio, 1.0 - eps_clip, 1.0 + eps_clip) * advantages
policy_objective = torch.minimum(surr1, surr2)
# 3. Unbiased non-negative Schulman k3 KL penalty estimator: exp(log_ref - log_new) - (log_ref - log_new) - 1
log_diff = logp_ref.detach() - logp_new
kl_penalty = torch.exp(log_diff) - log_diff - 1.0
loss = -(policy_objective - beta_kl * kl_penalty).mean()
return loss, advantages.squeeze(-1)
def dpo_preference_loss(
policy_chosen_logp: Tensor,
policy_rejected_logp: Tensor,
ref_chosen_logp: Tensor,
ref_rejected_logp: Tensor,
beta: float = 0.1,
) -> tuple[Tensor, Tensor]:
"""Closed-form Direct Preference Optimization (DPO) loss and implicit reward margin."""
chosen_logratios = policy_chosen_logp - ref_chosen_logp
rejected_logratios = policy_rejected_logp - ref_rejected_logp
logits = beta * (chosen_logratios - rejected_logratios)
loss = -F.logsigmoid(logits).mean()
reward_margin = (beta * chosen_logratios - beta * rejected_logratios).detach()
return loss, reward_marginIn DeepSeek-R1-Zero, applying pure GRPO directly to the base model without any supervised warm-start triggered an emergent phase transition: average thinking length scaled naturally from hundreds to thousands of tokens as the model autonomously discovered self-verification, backtracking, and reflection ("aha moments"). Adding a small cold-start SFT stage followed by reasoning RL, rejection sampling SFT, and a second all-scenario RL pass produced the final DeepSeek-R1.
4.HybridFlow (veRL): 3D-HybridEngine for RLHF dataflows#
Even after GRPO deletes the Value Critic, an online RL step alternates between two conflicting parallel execution layouts for the Actor :
- Rollout Generation () is memory-bound autoregressive decoding: it demands smaller Tensor Parallel groups (e.g., or with vLLM PagedAttention) and large Data Parallelism across prompts.
- Policy Training () is compute-bound and memory-capacity-bound: it requires wide 3D parallelism () across nodes.
Sheng et al. (HybridFlow / veRL, arXiv:2409.19256[3]HybridFlow: A Flexible and Efficient RLHF FrameworkOpen arXiv:2409.19256 ↗) solved this mismatch by decoupling a single-controller control plane (coordinating inter-node RL dataflow graphs) from a multi-controller SPMD computation plane powered by the 3D-HybridEngine. Between the training step and the rollout step, 3D-HybridEngine gathers and reshards Actor weights across heterogeneous parallelism topologies (Micro-AllGather over TP/PP groups) with zero redundant weight copies, cutting transition overhead by up to and boosting end-to-end RL throughput by .
5.References and next chapter#
- Ouyang et al., Training language models to follow instructions with human feedback (2022).
- Rafailov et al., Direct Preference Optimization: Your Language Model is Secretly a Reward Model (2023).
- Sheng et al., HybridFlow: A Flexible and Efficient RLHF Framework (2024).
- DeepSeek-AI, DeepSeek-R1: Incentivizing Reasoning Capability in LLMs via Reinforcement Learning (2025).
- Continue to Chapter 5: Hardware-Algorithm Co-Design at Frontier Scale: DeepSeek-V2/V3 MLA, DualPipe, and DistServe.
References
- [1]
- [2]
- [3]
- [4]