Skip to main content
← CONCEPTS / AI-MACHINE-LEARNING-SYSTEMS
An end-to-end domain learning journey

Distributed RLHF, DPO
& GRPO Post-Training.

Distributed post-training aligns base LLMs via multi-model RL loops (PPO/GRPO) or offline preference optimization (DPO), coordinating high-throughput vLLM rollout actors, reward/verifier pools, frozen reference KL penalties, and FSDP policy trainers.
Start the journey7 sections· Last modified Nov 24, 2026
FIRST PRINCIPLES. PRODUCTION SCALE.
The idea to keep with you

When inference latency or GPU memory limits bind throughput, DPO & GRPO Post-Training, GRPO eliminates the memory-heavy PPO Critic model by computing group-relative advantages across G sampled completions per prompt, while disaggregated vLLM rollout engines + NCCL weight sync eliminate training-inference GPU bubbles.

TL;DR30-second simplified summary
▾

GRPO drops the PPO Value Critic by computing group-relative advantages over G=8 rollouts per prompt, masking zero-variance groups and regularizing with the Schulman k3 KL estimator. Sandboxed code/math verifiers prevent neural reward hacking.

At scale, disaggregated vLLM rollout engines backfill freed KV slots via continuous batching and stream finished trajectories into a Ray Object Store replay buffer (staleness <=3 steps). FSDP2 trainers update weights and broadcast layer-pipelined deltas directly over NCCL RDMA.

Before you begin · Building blocksAlready know these? Jump to Stage 01 ↓
Verifier-Guided Self-Play & Synthetic Data Pipelines
Verifier-guided self-play pairs an entropy-bounded curriculum mutator with deterministic execution sandboxes (Lean4, Pytest, Z3), 13-gram/MinHash decontamination, and step-level Process Reward Models (PRM).
LLM Guardrails, Red Teaming & Evaluation
Production LLM safety and quality combine sub-25ms inline guardrail meshes (PII, prompt-injection, topic routing) with streaming output verifiers and asynchronous LLM-as-a-Judge + automated red-teaming loops.
Full walkthrough · 7 stages
01
foundation

The Post-Training Spectrum: SFT, DPO, PPO & GRPO.

Why this matters: Compare offline preference tuning (DPO) against online RL (PPO and GRPO) in memory, stability, and ceiling.

Supervised Fine-Tuning (SFT) teaches format, but struggles to surpass human demonstrations.

Direct Preference Optimization (DPO) skips online rollouts by optimizing a closed-form contrastive loss over static (prompt, chosen, rejected) pairs—needing only Policy + Frozen Reference weights, though it suffers from off-policy distribution shift. Online RLHF (PPO) explores new trajectories and fixes distribution shift, but requires 4 models in GPU memory (Actor, Critic, Reference, Reward).

STAGE 1 · ALGORITHMS

DPO vs. PPO vs. GRPO Memory & Compute Trade-offs

SFT (1 Model)baseline-stageDPO (2 Models)offline-prefPPO (4 Models)online-criticGRPO (3 Models)online-criticlessMoves on-policy w/ Critic

1.When to Use DPO: Fastest path for style/tone alignment when you already have clean human preference pairs.

2.When GRPO Dominates: Math, code, and agentic tool-use where deterministic verifiers provide exact group rewards.

GRPO achieves online RL exploration without a separate Value Critic by normalizing rewards across G sampled completions per prompt.

02
foundation

The 4-Model / 3-Model Memory & Compute Split.

Why this matters: Understand why co-locating rollout inference, reference logprobs, reward scoring, and FSDP training saturates HBM.

Think of The 4-Model / 3-Model Memory & Compute Split as the intuition layer for Distributed RLHF, DPO & GRPO Post-Training: Understand why co-locating rollout inference, reference logprobs, reward scoring, and FSDP training saturates HBM.

For a 70B parameter policy in BF16 (140 GB weights alone), storing Policy weights + AdamW optimizer states (FP32 master weights + momentum + variance = ~12x bytes/param = 840 GB) + activations + Frozen Reference weights (140 GB) + KV-caches for G=8 rollouts exceeds single-node HBM. Distributed trainers partition these roles using FSDP2/ZeRO-3 sharding for the Policy Trainer, tensor-parallel TP=4/8 vLLM engines for rollouts, and lightweight quantized/offloaded or shared-weight Reference evaluation (computing log pi_ref in a single forward pass before updating).

STAGE 2 · RESOURCE SPLIT

Distributed Memory Partitioning Across RLHF Roles

vLLM RolloutClusteractor-inferenceReward / VerifierPoolreward-scorerFrozen ReferencePolicykl-anchorFSDP2 PolicyTrainergradient-updaterQueries ref log-probs

1.Shared Reference Trick: With LoRA policy training, toggling adapters off yields exact pi_ref logprobs with zero extra HBM.

2.KV-Cache Pressure: Long 8K-token reasoning rollouts make rollout inference memory-bandwidth bound, not FLOP bound.

Disaggregating vLLM rollout engines from ZeRO-3 FSDP2 trainers prevents KV-caches and AdamW optimizer states from fighting over the same HBM.

Engineering Decision Framework
Problem
How to implement Distributed RLHF, DPO & GRPO Post-Training without hitting unbounded tail latency, state divergence, or operational fragility.
Naive Solution
Use a single unpartitioned path with unbounded retries and synchronous global coordination.
Why It Fails
Global coordination serializes throughput under load, while unbounded retries amplify transient stalls into full outages.
Alternatives
Compare synchronous strict-consistency paths against bounded asynchronous replication, local caching, or partitioned ownership.
Engineering Decision
When inference latency or GPU memory limits bind throughput, DPO & GRPO Post-Training, GRPO eliminates the memory-heavy PPO Critic model by computing group-relative advantages across G sampled completions per prompt, while disaggregated vLLM rollout engines + NCCL weight sync eliminate training-inference GPU bubbles.
Trade-Offs
Gains predictable p99 latency and fault isolation in exchange for explicit bounding, observability, and slightly higher implementation complexity.
Decision Exercise · Make the Call

When Distributed RLHF, DPO & GRPO Post-Training experiences a sudden 5x traffic spike alongside a slow downstream dependency, which engineering choice best protects system stability?

03
intermediate

Group-Relative Advantage & Clipped Surrogate Objective.

Why this matters: Compute GRPO advantages safely, handle zero-variance groups, and prevent policy collapse via KL penalties.

Given a prompt q and G=8 sampled completions {o_1, ..., o_G} with scalar rewards {r_1, ..., r_G}, GRPO computes the normalized advantage A_i = (r_i - mean(R)) / (std(R) + eps).

If all 8 completions score identically (e.g., all 0 or all 1), std(R) == 0; naive division causes NaNs, so zero-variance groups are masked out (advantage = 0.0) or skipped.

STAGE 3 · OBJECTIVE MATH

Numerically Safe GRPO Advantage & Schulman KL Loss

G=8 Reward Vectorreward-groupSafe GroupNormalizeradvantage-calcPPO-Clip Surrogatepolicy-lossSchulman k3 KLEstimatorkl-regularizerApplies clipped ratio

1.Schulman k3 KL: Using exp(r)-r-1 guarantees non-negative unbiased KL estimates, avoiding negative KL spikes.

2.Zero-Std Masking: Skipping prompts where all G=8 answers are right or wrong avoids wasting backward-pass compute.

Safe group normalization, ratio clamping, and the non-negative k3 KL estimator stabilize GRPO training against NaNs and policy collapse.

04
intermediate

Hybrid Reward & Verifier Pools (Mitigating Reward Hacking).

Why this matters: Combine deterministic sandboxes with calibrated neural reward models to stop length and format hacking.

Policies trained solely against a neural Reward Model (RM) rapidly discover reward hacks—inflating response length, inserting markdown boilerplate, or echoing confident-sounding nonsense that fools the RM.

Production pipelines combine: (1) Deterministic Verifiers (Firecracker/gVisor sandboxes running unit tests, Lean/SymPy math equivalence, JSON schema checks) with exact binary rewards; and (2) Process/Outcome Neural RMs with length-penalty normalization and format gates.

STAGE 4 · REWARD POOL

Sandboxed Verifiers + Length-Normalized Neural RM

SampledTrajectoriestrajectory-ingVisor / FirecrackerPoolcode-verifierNeural Outcome RMneural-rmComposite RewardGatereward-combinerScores helpfulness/safety

1.Format-First Gate: Multiply or gate total reward by format validity so the model never trades syntax for RM score.

2.Sandbox Isolation: Policy-generated code is untrusted; run with seccomp, cgroup RAM caps, and zero network.

Sandboxed deterministic verifiers and length-normalized neural RMs block reward hacking while safely executing untrusted policy code.

05
intermediate

Eliminating Rollout Stragglers & GPU Bubbles.

Why this matters: Solve the 40% idle-GPU bubble caused by heavy-tailed Chain-of-Thought completion lengths.

Think of Eliminating Rollout Stragglers & GPU Bubbles as the intuition layer for Distributed RLHF, DPO & GRPO Post-Training: Solve the 40% idle-GPU bubble caused by heavy-tailed Chain-of-Thought completion lengths.

In synchronous RLHF, a batch of 512 prompts waits for the single longest completion (e.g., a 12,000-token reasoning trace) while 511 other sequences finished at 800 tokens—leaving GPUs 40–60% idle! Disaggregated continuous batching solves this in three ways: (1) vLLM's continuous batching immediately slots new prompts into freed KV-cache space as shorter rollouts finish; (2) Dynamic Length-Bucketing groups prompts by predicted response length; and (3) Bounded Off-Policy Staleness lets the trainer pull completed batches from a replay buffer while stragglers finish asynchronously (capped at K<=2–4 policy steps old).

STAGE 5 · THROUGHPUT

Continuous Rollout Batching & Bounded-Staleness Buffer

Length-BucketedQueueprompt-schedulervLLM ContinuousBatchingrollout-engineReplay Buffer (RayStore)trajectory-bufferFSDP2 Trainer GPUstrainer-consumerStreams finished rollouts

1.Staleness Guard: Drop or importance-weight trajectories older than K=3 policy updates to keep RL on-policy.

2.2.4x GPU Utilization: Disaggregated streaming raises cluster MFU from ~28% (sync) to >65%.

Continuous batching, length bucketing, and a bounded-staleness replay buffer eliminate straggler stalls across rollout and trainer GPUs.

06
advanced

Non-Blocking NCCL Weight Sync (Trainer -> Rollout Actors).

Why this matters: Broadcast updated 70B policy weights from FSDP2 trainers to vLLM actors in seconds without halting the cluster.

After each FSDP2 optimizer step, the vLLM rollout engines need the new policy weights.

Saving a 140 GB BF16 checkpoint to S3/Lustre and reloading it into vLLM takes 45–90 seconds—wasting more time than the gradient step itself! Instead, trainers gather sharded parameters via all_gather into contiguous CUDA IPC / RDMA InfiniBand buffers and stream them directly into vLLM worker memory over a dedicated NCCL Weight-Sync process group (ncclBroadcast).

STAGE 6 · WEIGHT SYNC

Direct RDMA / NCCL Weight-Sync Ring (Zero Disk I/O)

FSDP2 ShardedWeightsweight-sourceBucketed All-Gathershard-reassemblerNCCL RDMA Broadcastsync-transportvLLM Weight Swapinference-targetStreams over IB RDMA

1.Layer-Wise Pipelining: Gather and broadcast one transformer layer at a time to avoid a 140 GB HBM spike.

2.LoRA Delta Fast-Path: Syncing 200 MB LoRA weights takes <80ms vs. ~3s for full 70B BF16 weights.

Layer-pipelined NCCL RDMA broadcasts replace slow disk checkpointing, syncing 70B weights directly into vLLM HBM in seconds.

07
advanced

Training Stability Telemetry & Automated Collapse Recovery.

Why this matters: Detect KL explosion, entropy collapse, and length drift early with automatic checkpoint rollback.

Online RL can silently collapse: entropy drops to zero (deterministic repetitive outputs), KL divergence spikes past 0.15 (forgetting pre-trained capabilities), or response length explodes to hit max_tokens.

Continuous telemetry logs kl_div, policy_entropy, clip_fraction, grad_norm, and zero_std_group_ratio at every step.

STAGE 7 · STABILITY

KL/Entropy Watchdog & Automated Checkpoint Rollback

Step TelemetryStreamstability-probeCollapse Detectoranomaly-detectorAsync NVMe/LustreCkptrecovery-storeAuto-Rollback &Tunerecovery-controllerFetches last clean step

1.Clip Fraction Signal: Healthy PPO/GRPO clip fraction sits at 5-15%; >35% signals overly aggressive LR.

2.Non-Blocking Snapshots: Copy weights to pinned CPU RAM first so Lustre writes never stall training GPUs.

Tracking KL divergence, entropy, and clip fraction enables automated rollback and hyperparameter dampening before RL collapse ruins a run.

Practice · Explain the consequences

Practice: Make the trade-off yourself.

Question 1 of 3
Score: 0/3

How does GRPO (Group Relative Policy Optimization) reduce GPU memory usage compared to standard PPO?

Recommended Learning Flow