Module 4 · Alignment

RLHF explained: SFT, reward model, PPO

8 min read

Supervised fine-tuning teaches the model to imitate answers. But for many qualities — being helpful without being verbose, refusing what must be refused, not making things up — it is easier to judge an answer than to write the ideal one. RLHF (Reinforcement Learning from Human Feedback) exploits this asymmetry: humans compare answers, a model learns their preferences, and reinforcement learning pushes the model towards what is preferred. This lesson explains the three classic steps, then implements their modern descendant, GRPO, on Forge's triage task.

The three steps of classic RLHF

1. SFT        : démonstrations humaines ─► modèle qui suit des consignes
2. Récompense : paires comparées par des humains ─► modèle de récompense r(prompt, réponse)
3. RL (PPO)   : le modèle génère, r note, PPO met à jour — sans trop s'éloigner du modèle SFT

(1. SFT: human demonstrations → a model that follows instructions; 2. reward: pairs compared by humans → a reward model r(prompt, answer); 3. RL (PPO): the model generates, r scores, PPO updates — without straying too far from the SFT model.)

Step 1 gives a reasonable starting point: a model that answers in the right format.

Step 2 turns preferences into a score. Annotators see two answers to the same prompt and pick the better one; a reward model learns to give a higher score to the chosen answer (Bradley-Terry loss, lesson 4.3).

Step 3 optimizes the model to maximize that score. The historical algorithm is PPO (Proximal Policy Optimization): the model generates answers, the reward model scores them, and PPO updates the model while limiting the size of each step. A KL divergence penalty relative to the SFT model prevents the model from drifting towards absurd answers that would fool the reward model.

Why PPO is heavy

PPO keeps four models in memory: the trained model (the "policy"), a frozen reference copy (for the KL), the reward model, and a critic (value model) that estimates the expected reward at each token, to reduce the variance of learning. Add generation during training, which is very expensive, and notorious instability (many sensitive hyperparameters): RLHF with PPO is reserved for well-equipped teams. TRL 1.15 no longer even offers a PPO trainer, neither in its main API nor in its experimental modules: it highlights DPO (offline, lesson 4.2) and GRPO/RLOO (online).

GRPO: doing without the critic

GRPO (Group Relative Policy Optimization), popularized by reasoning models in 2024-2025, removes the critic. For each prompt, the model generates a group of answers; each is scored; an answer's "advantage" is its score compared with the group average (normalized by the standard deviation). Answers better than their siblings are reinforced, the worse ones weakened.

prompt ─► 4 réponses ─► scores [0.25, 1.0, 0.0, 0.75] ─► moyenne 0.5
       ─► avantages  [-0.25, +0.5, -0.5, +0.25] / écart-type ─► mise à jour

(Prompt → 4 answers → scores → mean 0.5 → advantages divided by the standard deviation → update.) Less memory (no critic), fewer hyperparameters, and a precious property: the reward can be a function rather than a model.

Verifiable rewards

When an answer can be verified by a program — a calculation, a unit test, a format, a known label — you need neither annotators nor a reward model. This is reinforcement learning with verifiable rewards (RLVR). For Forge's triage:

def json_reward(completions, **kwargs) -> list[float]:
    """1 si la sortie est un JSON valide avec les bonnes clés et valeurs autorisées, sinon 0."""
    return [1.0 if metrics.parse(_text(c)) else 0.0 for c in completions]


def fields_reward(completions, target: list[str], **kwargs) -> list[float]:
    """Part des quatre champs justes (0 si sortie invalide). `target` vient d'une colonne du dataset."""
    import json

    out = []
    for c, t in zip(completions, target):
        data, expected = metrics.parse(_text(c)), json.loads(t)
        out.append(sum(data[k] == expected[k] for k in expected) / len(expected) if data else 0.0)
    return out

TRL passes the generated answers to the reward functions, and every dataset column as a keyword argument (here target, the expected answer). Several rewards add up: one for the format, one for the substance.

args = GRPOConfig(
    output_dir=output_dir, max_steps=max_steps, learning_rate=learning_rate,
    # lot = prompts × générations
    per_device_train_batch_size=batch_size, num_generations=num_generations,
    max_completion_length=64, temperature=1.0, beta=0.0, bf16=bf16, fp16=False,
    gradient_checkpointing=True, logging_steps=5, save_strategy="no", report_to="none", seed=seed,
)
trainer = GRPOTrainer(model=model, reward_funcs=[json_reward, fields_reward], args=args,
                      train_dataset=dataset, processing_class=tokenizer, peft_config=lora_config())

beta=0.0 (TRL 1.15's default) removes the KL penalty: with a verifiable reward, hard to "fool", recent work often does without it, which saves the reference copy. With a learned reward model, keep a KL.

The result on Forge

Two experiments of 100 steps each (4 answers per message, batch of 8 messages), on the training messages:

StartDurationReward at step 20 → 100 (JSON + fields, max 2)Test: valid JSONTest: exact match
Base model6.8 min0.61 → 1.390.94 (versus 0.00 before)0.00
SFT model (LoRA from lesson 3.2)5.8 min2.00 → 2.001.000.65 (unchanged)

Starting from the base model, GRPO first learns what the reward makes easy: the format. In 100 steps, without ever seeing a single reference answer, the model goes from 0% to 94% valid JSON on the test set — something pages of instructions had not achieved (lesson 1.4). Substance follows much more slowly: the share of correct fields rises from 0.21 to 0.46 during training, but no test answer has all four fields right yet, and the category (0.15) is even worse than chance — the model got into the habit of always answering the same thing. RL learns what is rewarded, in the order in which it is easy to find; it would need many more steps for the rest.

Starting from the SFT model, nothing moves: the reward is maximal from the first step. The model already succeeds on every training message; the four answers in each group are identical and perfect; their advantage — the gap to the group average — is zero; and so is the gradient. GRPO only learns from groups where some answers fail. Yet the SFT model's errors concern phrasings it has never seen (lesson 2.4): RL cannot fix them with training messages it already gets right.

Hence a practical rule: RL needs prompts of the right difficulty, neither always solved nor always failed. RL pipelines filter their prompts by first measuring the model's success rate on each, and keep only those it sometimes gets right — here, you would need new, labeled messages of the kind where it makes mistakes.

SFT or RL?

SFTRL (GRPO, PPO)
What you needThe right answer for each exampleA way to score an answer
SignalDense: every token of the reference answerSparse: one score per answer
CostLowGeneration during training: much more expensive
StrengthLearning a format, a style, knowledgeOptimizing an objective you can verify but not demonstrate

The common pattern combines both: SFT for the format and basics, then RL to push what you can measure (accuracy, passing tests, rule compliance).

Key takeaways

  • Classic RLHF: SFT, a reward model learned from human preferences, then PPO with a KL penalty.
  • PPO keeps four models in memory and remains unstable; TRL 1.15 no longer offers it.
  • GRPO compares answers within a group: no critic, less memory.
  • With a reward verifiable by program (RLVR), no annotators and no reward model.
  • RL first learns what is easy to reward (the format), and only on prompts neither always solved nor always failed.
  • SFT to imitate, RL to optimize what you can score; they are often chained.

Practice

  1. Run examples/07_grpo.py 50 and follow the evolution of both rewards in the log.
  2. Add a third reward that penalizes outputs longer than 40 tokens, and observe its effect.
  3. Measure the SFT model's success rate over 4 attempts per message, keep the messages it gets right one to three times out of four, and rerun GRPO on those only.

Resources