AI State of the Art
SOTA/Alignement : instruction, RLHF, DPO et apprentissage par renforcement/29 min
Section 112

RLHF in Practice: Tools (TRL, OpenRLHF)

Listen as a podcast →

From Raw GPT-3.5 to ChatGPT: Alignment in Action

OpenAI used RLHF (Reinforcement Learning from Human Feedback) to transform GPT-3.5, a raw model that completed text without caring about the user, into ChatGPT, a helpful and (relatively) safe assistant. Anthropic did the same for Claude. This is the process that transforms an instructed model into one aligned with what humans actually want: helpful, honest, and harmless responses.

Let's see how it works in practice, with tools you can use today.

The Three Steps of RLHF
  1. SFT (Supervised Fine-Tuning): learn to follow instructions by training on good answers. This is the subject of Instruction tuning.
  2. Reward model: learn what humans prefer, by having them compare pairs of answers.
  3. Reinforcement learning, here through the PPO algorithm (Proximal Policy Optimization): adjust the model so it earns better scores from the reward model.

The vocabulary of reinforcement learning, in two words, since it recurs everywhere: the model that decides what to produce is called the policy, and the score it is given afterwards is the reward. Nothing more mysterious than that.

Step 1: SFT (Supervised Fine-Tuning)

This is classic fine-tuning on instructions. You take your base model and train it on (instruction, good response) pairs. It's the essential starting point: without SFT, the model doesn't even know it's supposed to answer questions.

With TRL (Transformer Reinforcement Learning), Hugging Face's library:

from trl import SFTTrainer, SFTConfig

config = SFTConfig(
    output_dir="./sft_model",
    per_device_train_batch_size=4,
    gradient_accumulation_steps=4,
    learning_rate=2e-5,
    num_train_epochs=3,
)

trainer = SFTTrainer(
    model=model,
    args=config,
    train_dataset=dataset,
)
trainer.train()

Result: a model capable of following instructions. Not yet aligned, but at least cooperative.

Step 2: Training the Reward Model

The fundamental problem: what is a "good" response? Humans know intuitively, but you need to encode this intuition into a model.

The solution: a reward model trained on comparison pairs. You show two answers to a human annotator, who says which one they prefer. No absolute score, just "A is better than B."

Why the detour? Because comparing is far more reliable than scoring. Ask ten people to score an answer out of ten and you get ten different scores, and the same people will not score it the same way tomorrow. Ask them to pick between two answers and they will largely agree. The reward model exists precisely to reconstruct a score out of comparisons.

Preference Data Format

{
  "prompt": "Explain general relativity simply.",
  "chosen": "General relativity is Einstein's theory...",
  "rejected": "E=mc2 is a physics equation..."
}

The Bradley-Terry Loss

L=−log⁡(σ(r(chosen)−r(rejected)))\mathcal{L} = -\log\left(\sigma\left(r(\text{chosen}) - r(\text{rejected})\right)\right)

Symbol by symbol:

  • rr is the reward model itself: it takes an answer and returns a number, larger the better it judges it. It is a learned neural network.
  • r(chosen)−r(rejected)r(\text{chosen}) - r(\text{rejected}) is the score gap between the answer the human picked and the one they discarded. We want it positive and large.
  • σ\sigma is the sigmoid function, which squashes any number into the 0-to-1 range: very negative becomes almost 0, very positive almost 1. It turns a gap into a probability.
  • −log⁡-\log turns that probability into a cost: near 1 the cost is almost nil; near 0 it blows up.
  • L\mathcal{L} is that cost, the thing training pushes down.

In one sentence: the cost is low when the model scores the human-preferred answer higher, and explodes when it gets it backwards. The Bradley-Terry name is that of the classic statistical model which infers a ranking from a series of head-to-head duels, the same one used to rank chess players.

Annotation Quality Is the Bottleneck

The reward model cannot be better than the judgements it is drawn from. If annotators frequently contradict each other, there is nothing coherent to learn: the model will merely average incompatible opinions, and the final model will inherit that incoherence.

The risk is measured by the inter-annotator agreement rate: the proportion of pairs on which two independent annotators make the same choice. We give no numerical threshold (the figures in circulation trace back to no reference measurement we could verify) but the direction is certain: it is that proportion, not the number of annotations, that caps the quality of everything downstream.

Step 3: PPO Optimization

At this stage you have two ingredients: the model that came out of SFT, which is the policy you want to improve, and the reward model, which plays the judge.

PPO runs them in a loop: the policy produces answers, the judge scores them, and PPO corrects the policy's weights so it scores better next time. The word "proximal" in the name means each correction is bounded: the policy is forbidden from changing too much from one step to the next, or training goes off the rails. The detailed mechanics are in PPO, value functions and actor-critic.

Diagram of the RLHF loop. On the left, text data feeds in parallel a trained language model (Trained LM, marked with a crown) and a frozen language model (Frozen LM). The text produced by the trained model goes into a Reward Model that outputs a score r theta. The probabilities from both models feed a KL Loss, which is added to the score to form the final reward, which feeds an RL Update PPO box. That box updates the trained model weights and the loop repeats N times. A note says the KL term constrains the LM so it does not output gibberish and fool the reward model.
The whole PPO loop in one picture, and above all the models that must sit in memory at the same time: the one being trained, its frozen copy used as the reference for the KL term, and the reward model that scores the answers. The final reward sent to PPO is the reward model score corrected by the KL penalty.Source : João Lages, simplified RLHF diagram (GitHub gist)

The KL Penalty: The Essential Safeguard

Without control, the model will inevitably "hack" the reward model. It will find patterns that maximize the score without actually improving quality, for example, generating absurdly long responses because the reward model gives slightly more points to detailed answers.

The remedy is a penalty that stops the model straying too far from where it started:

objective=E[reward]−β×KL(πθ ∥ πref)\text{objective} = \mathbb{E}[\text{reward}] - \beta \times \text{KL}(\pi_\theta \, \| \, \pi_{\text{ref}})

Symbol by symbol:

  • E[reward]\mathbb{E}[\text{reward}] is the expected average score. That is what we want to maximize.
  • πθ\pi_\theta is the policy being trained, the Greek letter pi conventionally denotes a policy, and θ\theta its parameters, the ones that move.
  • πref\pi_{\text{ref}} is the reference policy: a frozen copy of the SFT model, taken before training starts. It never changes.
  • KL stands for Kullback-Leibler, after the two authors of the measure. The Kullback-Leibler divergence between two probability distributions quantifies how much they differ: it is zero when they are identical and grows as they separate. Here it measures how far the trained model has drifted from its original in the words it chooses.
  • β\beta is the weight of that penalty, the knob you set.

In one sentence: earn points by scoring well, lose points by straying from where you started. If β\beta is too low, the model hacks the reward; too high, and it stops moving at all.

Reward Hacking Is the Central Danger

Without the penalty, the model degenerates fast: it learns to please the judge instead of answering well. The textbook case is repeating phrases the judge likes, producing text that sounds good and says nothing.

The figure below makes the phenomenon visible, and repays a careful look: the score from the judge being optimized keeps climbing, while real quality, measured by an independent judge, plateaus and then falls. The model is no longer improving; it is learning the judge. Setting β\beta is the most critical decision in all of RLHF, and What breaks when you do RL on an LLM catalogues the other ways to fail.

Plot. The horizontal axis is the KL distance between the RL-tuned policy and the initial policy, from 0 to 100. The vertical axis is the score given by the reward model. Dashed curves, corresponding to the proxy reward model actually being optimized, rise continuously. Solid curves, corresponding to the reference or gold reward model, rise at first, reach a peak, then fall. Colors correspond to reward model sizes ranging from 3 million to 3 billion parameters.
Reward hacking, measured. The further the model drifts from its starting point (horizontal axis, the KL distance), the higher the score given by the reward model being optimized (dashed lines), while actual quality, measured by a reference judge, plateaus and then collapses (solid lines). This is exactly what the KL penalty is there to prevent.Source : Gao, Schulman and Hilton 2022 paper on reward model overoptimization, via RLHFlow Alignment Guidebook

TRL: The Reference Framework for Experimentation

TRL (Transformer Reinforcement Learning) from Hugging Face makes RLHF accessible to practitioners:

  • SFTTrainer: instruction fine-tuning in a few lines.
  • RewardTrainer: reward model training on preference data.
  • PPOTrainer: the full reinforcement learning loop.
  • Direct integration with the PEFT library, hence with LoRA and QLoRA, essential rather than a nicety, since the next section shows memory is the real obstacle.
  • Spreading across several graphics cards via DeepSpeed, a Microsoft library that splits models and optimizer states between cards.

It's the reference tool for experimentation and moderate-sized models (7-13B parameters).

OpenRLHF: When You Need to Scale

TRL works great for 7 to 13 billion parameter models. But for large models (34B, 70B and beyond), you need more sophisticated infrastructure.

OpenRLHF spreads the work across machines using Ray, a distributed-computing orchestration library. Each role gets its own cards:

  • the actor, the model being trained; the critic, which estimates the expected quality of an answer as it is being produced; the reward model, which scores; and the reference model, the frozen copy used to compute the Kullback-Leibler penalty.
  • Models beyond 70 billion parameters.
  • Two memory savings: offloading idle data to main memory, and activation recomputation (gradient checkpointing), which redoes computations rather than keeping their results.
  • Several algorithms: PPO, DPO, GRPO and others.
Architecture diagram of OpenRLHF. At the top, a Ray box described as distributed scheduler and controller, linked by Data and control arrows to a DeepSpeed box on the right containing Critic Model, Reward Model, Actor Model and Reference Model. That box points to a Transformers box handling model weight format and states, itself linked to a vLLM box acting as the inference engine. The label NCCL slash CUDA IPC appears under the arrows.
How OpenRLHF splits the work: Ray acts as the conductor, DeepSpeed hosts the four models (actor, critic, reward, reference) on separate GPUs, and vLLM takes over the slowest part, generating the responses. This separation of roles is what makes 70B-plus models tractable.Source : OpenRLHF (README figure), via Hands-on Modern RL
TRL vs OpenRLHF: How to Choose

TRL: for experimentation, 7-13B models. Easy to get started with, perfectly integrated into the Hugging Face ecosystem. OpenRLHF: for production, 34B-70B+ models. More complex to set up, but designed for massive scaling.

The Practical Challenges of RLHF

PPO Instability on LLMs

PPO applied to large language models has a reputation for being finicky. At least four settings demand extreme care: the learning rate (the size of each correction), the β\beta of the Kullback-Leibler penalty, the clip ratio (the bound past which a correction gets truncated, this is the "proximal" of PPO's name), and the number of passes over each batch of data.

A learning rate slightly too high makes training diverge within a few steps. It is a tightrope act.

The Memory Cost Is Brutal

Full RLHF needs four models in memory at once, and it is worth being clear about which ones learn:

ModelRoleStatus
The policywhat we want to improvetrained
The criticestimates expected quality, to guide the correctionstrained
The reference modelcopy of the SFT model, used for the Kullback-Leibler divergencefrozen
The reward modelscores the answersfrozen

The arithmetic, for a 7-billion-parameter model in 16 bits, i.e. 2 bytes per parameter:

4×2×7×109=56 GB4 \times 2 \times 7 \times 10^9 = 56 \text{ GB}

And that is weight storage only. Add the gradients and optimizer states of the two trained models, plus the activations. This is why LoRA integration is not a refinement but a necessity: it removes the optimizer states, and even lets the policy and its reference share a single set of frozen weights, by switching the adapter on or off.

Generation Is the Bottleneck

PPO requires generating complete answers at every step, not merely pushing an existing text through the network. And generation is autoregressive: each token is produced from all the previous ones, hence one after another, with no way to parallelize. Where supervised fine-tuning processes an already-written answer in a single pass, PPO has to build it word by word.

This is the bottleneck, and it is why OpenRLHF hands that step to vLLM, a specialized inference engine.

Alternatives to PPO: Simplifying the Pipeline

The complexity of classic RLHF has motivated the development of simpler alternatives:

Each one removes a specific ingredient from the list above.

  • DPO (Direct Preference Optimization) removes two models: the reward model and the critic. It trains directly on preference pairs, never generating anything.
  • GRPO (Group Relative Policy Optimization) removes the critic: instead of a model estimating expected quality, it compares several answers to the same question against each other.
  • KTO (Kahneman-Tversky Optimization, after the two psychologists behind prospect theory) removes the need for pairs: a single "good" or "bad" label per answer suffices, which is far easier to collect.
  • ORPO (Odds Ratio Preference Optimization) removes a stage: it merges supervised fine-tuning and alignment into one training run.
Why DPO Won Over Small Teams

DPO needs only two models in memory instead of four (the policy and its frozen reference) i.e. 28 GB instead of 56 for a 7-billion-parameter model. And it generates nothing, which removes the bottleneck described above.

Two fewer models, no generation: that explains its adoption better than any quality argument. PPO stays the reference when you have the infrastructure, notably because it can optimize rewards that are not human preferences, passing an automated test, for instance.


The bottom line: RLHF is the process that transforms an instructed model into one aligned with human preferences. It's complex, expensive, and requires considerable care at every step. But it's precisely what makes the difference between an LLM that completes text and an assistant that is genuinely useful to you.

Check your understanding0 / 5

1. To train the reward model, annotators are asked to compare two answers rather than score each one out of ten. Why the detour?

2. A team has a large annotation budget and wants the best possible reward model. According to the page, what caps the quality of everything downstream?

3. During PPO training, the score given by the reward model climbs steadily. Why does the page refuse to read this as proof of progress?

4. Full RLHF requires four models in memory at the same time. Which ones actually learn during training?

5. According to the page, what explains DPO's massive adoption by small teams?