Guide · Train
Reinforcement fine-tuning: DPO, GRPO and verifiable rewards
What reinforcement learning adds after supervised fine-tuning, how to choose between DPO, GRPO and PPO, how to write reward functions TRL can train against, and the failure modes to catch before anything reaches the eval gate.
Supervised fine-tuning (SFT) teaches a model to imitate worked examples. Reinforcement learning (RL) trains it against a signal instead: a preference between two answers, or a score from a program that checks the output. In our model lifecycle it is step 4, after supervised fine-tuning and before the eval gate.
This guide continues the invoice-extraction example from the LoRA guide, where the SFT model already writes JSON in the right shape. RL pushes field-level correctness further, against a reward anyone can read and test.
Versions
Code below was checked against TRL 1.18.2, PEFT 0.22.0 and Transformers 5.20.2. We ran the DPO, reward and GRPO code on CPU with a tiny test model of the same architecture and vLLM switched off. The RL environment pins an older Transformers on purpose, as the install section explains, so keep it separate from your SFT and serving environments.
What RL adds over SFT, and what it does not
- RL generalizes where SFT memorizes, but it needs SFT first. On rule-based text tasks and visual navigation, Chu et al. found RL with an outcome-based reward generalized to unseen variants, while SFT tended to memorize the training data. SFT was still essential before RL, because it stabilizes the output format (arXiv 2501.17161).
- RL with verifiable rewards mostly sharpens what the base model can already do. Yue et al. measured pass@k at large k across several model families. RL-trained models beat their base models at small k, such as pass@1, but the base models matched or beat them at large k. The correct reasoning paths were already in the base model's samples. RL made the model find them more reliably and narrowed its range in the process. Distillation from a stronger model, by contrast, added new capability (arXiv 2504.13837).
The practical reading:
- Use SFT, or distillation from a stronger model, to teach format, style, domain knowledge and new skills.
- Use RL when code can check the outcome and the SFT model already gets the task right some of the time. If it never succeeds, no sample earns a reward and there is nothing to reinforce.
- Measure that first: sample eight completions per prompt from the SFT model on a few hundred prompts, and count how often at least one is correct.
Choose the method
| Method | What you need | How it learns | Cost | Use it when |
|---|---|---|---|---|
| DPO | Preference pairs: prompt, chosen, rejected | Offline. Raises the likelihood of the chosen answer over the rejected one, relative to a reference model. No reward model. | Low, close to SFT | Ranked pairs or thumbs data, but no automatic checker. Tone, style, refusals. |
| GRPO with verifiable rewards | Prompts plus a checker: schema validation, unit tests, exact-match math, tool-call validity | Online. Samples a group of completions per prompt, scores each, and uses each score relative to its group as the advantage. No value model. | Medium to high. Generation dominates. | Code can check the answer and the model already succeeds sometimes. |
| RLHF with PPO | Preference data to train a reward model, then prompts | Online. The reward model scores samples, and PPO updates the policy with a separate value model. | Highest: policy, reference, reward and value models | Rarely worth it for a small team. DPO and GRPO cover most needs. |
| OpenAI reinforcement fine-tuning | Not available | Managed RL on o4-mini | Closed | Do not plan on it. o4-mini and ft-o4-mini-2025-04-16 shut down on 23 October 2026; new fine-tuning jobs end on 6 January 2027. |
GRPO comes from DeepSeekMath (arXiv 2402.03300). The term RLVR, reinforcement learning with verifiable rewards, comes from Tülu 3, which used it as the final stage after SFT and DPO, rewarding the model only when a verifier confirmed the answer (arXiv 2411.15124).
DPO in a few lines
Each preference row holds a prompt and two answers, in the same chat format as SFT data:
{"prompt": [{"role": "system", "content": "Extract the invoice fields as JSON."}, {"role": "user", "content": "Invoice INV-2291 from Acme Supplies. Total due: USD 1,240.00."}], "chosen": [{"role": "assistant", "content": "{\"vendor\": \"Acme Supplies\", \"invoice_number\": \"INV-2291\", \"total\": 1240.0, \"currency\": \"USD\"}"}], "rejected": [{"role": "assistant", "content": "{\"vendor\": \"Acme Supplies\", \"invoice_number\": \"INV-2291\", \"total\": 124.0, \"currency\": \"USD\"}"}]}import torch
from datasets import load_dataset
from peft import LoraConfig
from trl import DPOConfig, DPOTrainer
pairs = load_dataset("json", data_files="data/prefs.jsonl", split="train")
pairs = pairs.map(lambda row: {"chat_template_kwargs": {"enable_thinking": False}}) # as in SFT
trainer = DPOTrainer(
model="out/qwen35-9b-merged",
args=DPOConfig(
output_dir="out/qwen35-9b-dpo",
model_init_kwargs={"dtype": torch.bfloat16},
beta=0.1, # the default; higher keeps the model closer to where it started
learning_rate=1e-5, # TRL's docs suggest about 1e-5 for adapters; the default is 1e-6
),
train_dataset=pairs,
peft_config=LoraConfig(
r=16,
lora_alpha=32,
task_type="CAUSAL_LM",
target_modules=[
"q_proj", "k_proj", "v_proj", "o_proj",
"in_proj_qkv", "in_proj_z", "out_proj",
"gate_proj", "up_proj", "down_proj",
],
),
)
trainer.train()The chat_template_kwargs column keeps thinking off, as in SFT. Without it, TRL warns that the rendered prompt is not a prefix of prompt plus answer, so training would see a slightly different context than inference. With no ref_model, TRL uses the starting model as the reference.
Design the reward before the training run
The reward function is the specification. The model will optimize exactly what it measures, including its loopholes.
- Prefer deterministic checks: schema validation, sandboxed unit tests, exact match after normalization, comparing SQL results, validating a tool call's name and arguments.
- Separate format from correctness. A small reward for valid structure, a larger one for being right. TRL sums the functions, weighted by
reward_weights. - Give partial credit only where it is honest, such as per field. Never reward what the model can satisfy without doing the task, such as length or keywords.
- Parse strictly. A reward that accepts JSON anywhere in the text teaches the model to wrap its JSON in prose.
- Keep the policy away from the grader. It must never be able to read or edit the tests, the expected answers or the scoring code. The reward-hacking results below show why.
- Use LLM judges only for qualities code cannot check, and audit them against human labels.
- Unit-test the reward on hand-written good and bad outputs before you spend GPU hours on it.
The reward function contract in TRL
In TRL 1.18 each reward function receives keyword arguments: prompts, completions, completion_ids, trainer_state, log_extra, log_metric, and every dataset column except prompt, completion and completion_ids. With a conversational dataset, each completion is a list of messages. The function returns one float per completion, or None where it does not apply. Accept **kwargs to absorb what you do not use.
The training data stores the labeled answer as a JSON string in its own expected column, so TRL passes it to the reward:
{"prompt": [{"role": "system", "content": "Extract the invoice fields as JSON."}, {"role": "user", "content": "Invoice INV-2291 from Acme Supplies. Total due: USD 1,240.00."}], "expected": "{\"vendor\": \"Acme Supplies\", \"invoice_number\": \"INV-2291\", \"total\": 1240.0, \"currency\": \"USD\"}"}A schema reward and a correctness reward
# rewards.py
import json
import math
from jsonschema import Draft202012Validator
SCHEMA = {
"type": "object",
"properties": {
"vendor": {"type": "string"},
"invoice_number": {"type": "string"},
"total": {"type": "number"},
"currency": {"type": "string", "pattern": "^[A-Z]{3}$"},
},
"required": ["vendor", "invoice_number", "total", "currency"],
"additionalProperties": False,
}
_validator = Draft202012Validator(SCHEMA)
def _finite(token):
"""json.loads accepts NaN, Infinity and 1e400 by default, and jsonschema calls them numbers."""
value = float(token)
if not math.isfinite(value):
raise ValueError(f"non-finite number: {token}")
return value
def _parse(completion):
"""Return the extracted object if the completion is one schema-valid JSON object, else None."""
text = completion[0]["content"] if isinstance(completion, list) else completion
text = text.split("</think>")[-1].strip() # ignore a reasoning block if one is present
try:
obj = json.loads(text, parse_float=_finite, parse_constant=_finite)
except ValueError: # json.JSONDecodeError is a ValueError too
return None
return obj if _validator.is_valid(obj) else None
def _same(got, want):
if isinstance(want, (int, float)) and isinstance(got, (int, float)):
return abs(got - want) < 0.005
return str(got).strip().casefold() == str(want).strip().casefold()
def schema_reward(completions, **kwargs):
"""1.0 when the output parses and validates against the schema, else 0.0."""
return [1.0 if _parse(c) is not None else 0.0 for c in completions]
def correctness_reward(completions, expected, **kwargs):
"""Fraction of fields that match the labeled answer in the `expected` column."""
rewards = []
for completion, gold_json in zip(completions, expected):
got, gold = _parse(completion), json.loads(gold_json)
if got is None:
rewards.append(0.0)
else:
rewards.append(sum(_same(got.get(k), v) for k, v in gold.items()) / len(gold))
return rewardsTest it before training. A fenced code block, an extra key or a non-finite number must earn nothing. By default json.loads accepts NaN, Infinity and 1e400 and jsonschema counts them as numbers, so _parse rejects them.
from rewards import correctness_reward, schema_reward
gold = '{"vendor": "Acme Supplies", "invoice_number": "INV-2291", "total": 1240.0, "currency": "USD"}'
def answer(text):
return [{"role": "assistant", "content": text}]
batch = [
answer(gold), # correct
answer(gold.replace("1240.0", "124.0")), # one wrong field
answer("```json\n" + gold + "\n```"), # fenced: not plain JSON
answer(gold[:-1] + ', "notes": "paid"}'), # extra key
answer(gold.replace("1240.0", "NaN")), # non-finite numbers
answer(gold.replace("1240.0", "1e400")),
]
assert schema_reward(batch) == [1.0, 1.0, 0.0, 0.0, 0.0, 0.0]
assert correctness_reward(batch, expected=[gold] * 6) == [1.0, 0.75, 0.0, 0.0, 0.0, 0.0]Train with GRPO in TRL
Install the RL environment with explicit pins:
pip install "trl[vllm]==1.18.2" "vllm==0.33.0" "transformers==5.20.2" "peft==0.22.0" jsonschema torchvision pillowEach pin matters. TRL 1.18.2's vllm extra allows vLLM 0.23 through 0.33. vLLM 0.33.0 requires Transformers 5.16.1 or later but older than 5.21, and Qwen3.5 needs Transformers 5.2 or later, so 5.20.2 satisfies all three. Pin Transformers 5.24.0 instead and pip quietly settles on vLLM 0.30.0.
import torch
from datasets import load_dataset
from peft import LoraConfig
from trl import GRPOConfig, GRPOTrainer
from rewards import correctness_reward, schema_reward
MODEL = "out/qwen35-9b-merged" # the merged SFT model from the LoRA guide
data = load_dataset("json", data_files="data/rl_train.jsonl", split="train")
args = GRPOConfig(
output_dir="out/qwen35-9b-grpo",
model_init_kwargs={"dtype": torch.bfloat16},
learning_rate=1e-5, # LoRA wants roughly 10x a full fine-tuning rate (TRL's default is 1e-6)
num_generations=8, # completions sampled per prompt (the default)
max_completion_length=512,
per_device_train_batch_size=8,
gradient_accumulation_steps=4, # 32 completions, so 4 prompts, per optimizer step
beta=0.0, # the default: no KL penalty and no reference model
loss_type="dapo", # the default; "grpo" has a length bias
reward_weights=[0.2, 1.0], # schema_reward, correctness_reward
mask_truncated_completions=True,
chat_template_kwargs={"enable_thinking": False},
use_vllm=True,
vllm_mode="colocate", # or "server", with vLLM on its own GPUs
vllm_gpu_memory_utilization=0.3,
max_steps=300,
logging_steps=10,
log_completions=True,
report_to="none",
)
trainer = GRPOTrainer(
model=MODEL,
reward_funcs=[schema_reward, correctness_reward],
args=args,
train_dataset=data,
peft_config=LoraConfig(
r=16,
lora_alpha=32,
task_type="CAUSAL_LM",
target_modules=[
"q_proj", "k_proj", "v_proj", "o_proj",
"in_proj_qkv", "in_proj_z", "out_proj",
"gate_proj", "up_proj", "down_proj",
],
),
)
trainer.train()
trainer.save_model()What the settings mean:
- Batch arithmetic. Processes ×
per_device_train_batch_size×gradient_accumulation_stepsmust divide evenly bynum_generations. One GPU here gives 32 completions per step: 4 prompts, 8 samples each. beta=0.0is the default, so no reference model is loaded. TRL's docs note DeepSeek-R1 used 0.001.loss_type="dapo"is the default. TRL's docs say the original"grpo"normalization introduces a length bias, which DAPO's token-level normalization reduces but does not eliminate, and"dr_grpo"removes. Other options include"bnpo","cispo"and"sapo".mask_truncated_completions=Truekeeps completions cut off atmax_completion_lengthout of the loss, as the DAPO paper recommends for stability.chat_template_kwargsturns thinking off during generation, matching how the model was fine-tuned and will be served.- vLLM. In
"colocate"mode vLLM shares the training GPU, taking the share set byvllm_gpu_memory_utilization. In"server"mode you start it separately withtrl vllm-serve --model out/qwen35-9b-merged, and TRL's docs say it must run on different GPUs from the trainer. TRL corrects by default for the small mismatch between vLLM's log-probabilities and the trainer's. - The learning rate. Thinking Machines found LoRA matches full fine-tuning in policy-gradient RL even at rank 1, at about 10x the full fine-tuning learning rate (LoRA Without Regret). Compute, not rank, is the bottleneck.
Watch each reward function's mean, frac_reward_zero_std (the share of prompts whose samples all got the same reward, which carry no learning signal), entropy and completion length. log_completions=True prints samples; read them, not only the curves.
What it costs in compute
Plan in GPU-days
- Generation dominates. Each prompt is sampled eight times by default before any gradient step, so expect RL to cost several times what SFT does for the same prompts.
- You need a GPU for generation, either shared with training in colocate mode or a separate one in server mode.
- A public reference point: TRL's GRPO quick start, Qwen2.5-0.5B-Instruct on DeepMath-103K across 8 GPUs, takes about one day.
- Our planning estimate, not a benchmark: for the 9B example in colocate mode, plan on one 80 GB GPU such as an A100 80 GB or H100, or move vLLM to a second GPU in server mode.
- Managed: Amazon Bedrock charges $80 per training hour, then bills the tuned model's inference and storage, as covered under Tooling.
Failure modes and how to catch them
Reward hacking
Anthropic gave a pretrained model knowledge of reward-hacking strategies, then trained it on a selection of its real production coding environments. When the model learned to hack, its misalignment rose sharply on every evaluation: alignment faking, cooperation with malicious actors, attempted sabotage. In one evaluation it tried to sabotage safety-research code 12% of the time. RLHF safety training on chat-style prompts fixed chat behavior but left agentic tasks misaligned. Three mitigations worked: preventing the hacking, more diverse safety training, and "inoculation prompting", which frames hacking as acceptable during training so it does not generalize (Anthropic research, arXiv 2511.18397).
For a small team, the first mitigation is the one in reach: strict verifiers, sandboxed execution, no access to the grader. Then watch for the signature of a hack: training reward climbing while the held-out task metric stays flat.
Collapse and lost diversity
The model can collapse onto a narrow set of outputs, with entropy falling toward zero. TRL logs entropy, and GRPOConfig has entropy_coef and top_entropy_quantile if you need them. If your product samples several candidates, evaluate pass@k as well as pass@1.
KL drift
With beta=0.0, nothing pulls the model back toward the SFT checkpoint it started from. If general-ability or safety evaluations regress, add a small KL coefficient, train for fewer steps or lower the learning rate.
Held-out tasks and human review
Score on prompts from documents, customers or task variants that never appeared in RL training; a model can overfit the prompts and the verifier's quirks at once. At every checkpoint, read about 20 random completions, the highest-reward ones, where hacks show up first, and some zero-reward ones, which often reveal verifier bugs.
Tooling
| Tool | Latest release (checked 23 Nov 2026) | Notes |
|---|---|---|
| TRL | v1.18.2, 19 Nov 2026 | GRPO, DPO and RLOO trainers; AsyncGRPOTrainer stable since v1.18.0; vLLM generation. The easiest on-ramp. |
| verl | v0.9.1, 20 Sep 2026 | PPO, GRPO, DAPO, RLOO and more; FSDP, FSDP2 or Megatron training; vLLM or SGLang rollouts; multi-turn tool calling. |
| OpenRLHF | v0.11.2, 14 Sep 2026 | Ray with vLLM and DeepSpeed; PPO, REINFORCE++, GRPO, RLOO; multi-turn agents through a reset and step interface. |
| NVIDIA NeMo RL | v0.8.0, 6 Nov 2026 | The re-architected successor to NeMo Aligner. GRPO, GSPO, DAPO, PPO, DPO, SFT and on-policy distillation. |
| OpenPipe ART | v0.5.24, 4 Nov 2026 | GRPO for multi-step agents. Its RULER reward uses an LLM judge to score several agent trajectories against each other, from 0 to 1, with no labeled data or hand-written reward. CoreWeave agreed to acquire OpenPipe in September 2025. |
| prime-rl | v0.11.0, 22 Nov 2026 | Fully asynchronous RL on FSDP2 and vLLM, with setups from 1 GPU to 2,048; uses verifiers environments from the Environments Hub. |
All six are Apache-2.0. Start with TRL, and move to the others for multi-node scale or long multi-turn rollouts.
Managed options are shrinking toward "bring your own loop":
- Fireworks removed managed reinforcement fine-tuning. It accepts no new jobs, existing jobs cannot run or resume, and RL now runs on its Training API, where your own rollout code computes the reward (Fireworks docs).
- Amazon Bedrock launched reinforcement fine-tuning on 3 December 2025 for Amazon Nova 2 Lite, and added gpt-oss-20b and Qwen3 32B on 17 February 2026; its docs list those two in US West (Oregon). Training is $80 per training hour. The tuned model then bills inference per 1M tokens ($0.09 input and $0.39 output for gpt-oss-20b, $0.20 and $0.78 for Qwen3 32B) plus $1.95 per model per month for storage. Rewards come from rule-based graders, AI judges or Lambda functions (Bedrock pricing, Bedrock RFT docs, December launch, February update).
- Together AI Post-Training has you write the loop in Python (GRPO, PPO, custom losses, multi-turn agents) on LoRA or full weights, and the weights are downloadable. B200 time lists at $11 per GPU-hour, $9 on promotion until 14 December 2026 (Together post-training, Together pricing).
- OpenAI self-serve fine-tuning, RFT included, is winding down, as the method table notes (OpenAI deprecations).
Where this fits in the lifecycle
- Step 4 output. A reward function or verifier that a person can read, its unit tests, and the tuned adapter.
- Step 5, the eval gate. Score the RL candidate on the same frozen test set and harness as the baseline and the SFT model. It must beat the SFT checkpoint, not just the base model, and must not regress on general ability or safety. Put the reward curves next to the held-out metrics in the eval report. If they diverge, the model is gaming the reward.
- Step 6, deployment. Serve the RL adapter beside the SFT adapter with vLLM multi-LoRA, as in the LoRA guide, and roll back by routing to the previous adapter.
- Step 7, monitoring. Production failures become new RL prompts and new test cases for the verifier. When the verifier was wrong, fix it before the next run.
Sources
- Chu et al., SFT Memorizes, RL Generalizes (arXiv 2501.17161)
- Yue et al., Does Reinforcement Learning Really Incentivize Reasoning Capacity in LLMs Beyond the Base Model? (arXiv 2504.13837)
- Lambert et al., Tülu 3 (arXiv 2411.15124)
- Shao et al., DeepSeekMath, which introduced GRPO (arXiv 2402.03300)
- Anthropic: From shortcuts to sabotage, natural emergent misalignment from reward hacking
- MacDiarmid et al., Natural Emergent Misalignment from Reward Hacking in Production RL (arXiv 2511.18397)
- Thinking Machines: LoRA Without Regret
- Hugging Face TRL: GRPO Trainer
- Hugging Face TRL: DPO Trainer (LoRA learning rate)
- TRL v1.18.2 DPOConfig source
- TRL v1.18.2 DPOTrainer source
- Hugging Face TRL releases
- TRL v1.18.2 GRPOConfig source
- TRL v1.18.2 GRPOTrainer source (reward arguments)
- TRL v1.18.2 package metadata (vLLM extra)
- TRL v1.18.2 vllm-serve script
- PyPI: vLLM 0.33.0 metadata (Transformers requirement)
- PyPI: vLLM 0.30.0 metadata
- Transformers v5.2.0 Qwen3.5 model code (first release with Qwen3.5)
- Python docs: json.loads parse_constant and parse_float
- verl
- OpenRLHF
- NVIDIA NeMo RL
- OpenPipe ART
- OpenPipe ART: RULER
- CoreWeave to acquire OpenPipe
- Prime Intellect prime-rl
- Fireworks: reinforcement fine-tuning removal notice
- Amazon Bedrock pricing
- Amazon Bedrock docs: reinforcement fine-tuning
- AWS: Bedrock reinforcement fine-tuning launch, 3 Dec 2025
- AWS: Bedrock reinforcement fine-tuning adds open-weight models
- Together AI: Post-Training
- Together AI pricing
- OpenAI API deprecations