Reward models
Train a small model to score how good another model's answers are.
When to train a reward model#
Most teams do not need to train a reward model. Pick the simplest grader that fits your task:
- Use a
Scorer(code check) first whenever correctness can be checked deterministically in code (JSON schema, SQL parser, unit tests). It's instant and free. - Use a
Judgewith a frontier or open model and a rubric as your default for everything else. For most tasks, a prompted judge with clear criteria is the best route: it needs no training data and is easy to update as your requirements change. - Train a reward model (
RewardModelRecipe) when you want to strongly encode specific taste or domain-specific reward behavior from preference pairs, or when you need millisecond scoring inside your app or evaluation loop.
Before training a reward model, try a prompted Judge with a Rubric first:
from grad import Judge, Rubric, Scorer, validators
rubric = Rubric([
Scorer("starts_like_sql", weight=0.3, fn=validators.Regex(r"^\s*(SELECT|WITH)\b", flags="i")),
Judge(
name="accurate_query",
model="anthropic/claude-sonnet-5-5",
prompt="Verify the SQL answers the user's question accurately without hallucinated columns.",
weight=0.7,
),
])
If a prompted judge is still missing subtle preferences you can demonstrate with examples, train a dedicated reward model with RewardModelRecipe. You can use the trained Artifact to:
- Score draft answers from a fast 8B model in your app so low-scoring answers fall back to a larger model.
- Rank multiple candidate answers (best-of-N) and return the highest-scoring one.
- Score a
Datasetoffline before filtering it.
What data you need#
- Minimum volume: 500 to 2,000
(chosen, rejected)pairs in aDataset, in the same format as Preference tuning (DPO): one{"prompt", "chosen", "rejected"}record per pair, or two trajectories sharing agroup_id. A record whoseexpected_outputcorrects its logged answer (a synced correction) is a pair too: the correction is chosen and the logged answer rejected. - To try it first on public data:
client.datasets.from_hf("trl-lib/ultrafeedback_binarized", split="train", chosen="chosen", rejected="rejected", limit=2000)gives you a ready-made preference dataset.
Train with RewardModelRecipe#
from grad import Grad
from grad.recipes import RewardModelRecipe
client = Grad()
pairs_ds = client.datasets.get("sql-preferences") # pushed or imported earlier
run = client.runs.create(
dataset=pairs_ds,
name="sql-verifier",
recipe=RewardModelRecipe(model="qwen/qwen3-8b"),
).wait()
print(run.artifact.id, run.eval_report)
Parameters you might change#
model: start with a fast 4B to 8B model ("qwen/qwen3-8b"). A reward model scores an output in a single forward pass, so an 8B model runs in milliseconds.adapter:adapters.LoRA(rank=32)on the backbone by default, trained together with the scoring head. The artifact always keeps the adapter separate (merge_on_exportdoesn't apply).rubric: also train on single scored answers. Pass the name of a score in[0, 1]already on your records (rubric="resolved", or--score resolvedin the CLI), and records that end in an assistant turn with that score train the head pointwise, next to the pairs.
Pairs always stay together in the same train or eval split, and run.artifact is the checkpoint with the best held-out pair accuracy (run.eval_report.preference_accuracy; the report also has reward_margin and, with rubric=, pointwise_brier). Every other setting has a default; see the training parameters reference.
Use your reward model#
The artifact is a reward_bundle: a LoRA adapter for the base model, a small scoring head (reward_head.safetensors) and reward_config.json. A score is sigmoid(head(h)), where h is the base model's last hidden state at the end of the whole conversation, answer included. Download it and load it with transformers and peft (the artifact formats spec has the full reference loader):
import json
from pathlib import Path
import torch
from peft import PeftModel
from safetensors.torch import load_file
from transformers import AutoModelForCausalLM, AutoTokenizer
path = Path(run.artifact.download("./sql-verifier", format="files"))
config = json.loads((path / "reward_config.json").read_text())
pin = {"revision": config["base_model_revision"]}
tokenizer = AutoTokenizer.from_pretrained(config["base_model_repo"], **pin)
model = AutoModelForCausalLM.from_pretrained(config["base_model_repo"], dtype=torch.bfloat16, **pin)
if config["adapter"]["kind"] == "lora":
model = PeftModel.from_pretrained(model, str(path)).get_base_model()
head = load_file(str(path / config["head_file"]))
@torch.no_grad()
def score(messages):
"""A score in [0, 1] for the last assistant turn of `messages`."""
text = tokenizer.apply_chat_template(messages, tokenize=False, **config["chat_template_kwargs"])
ids = tokenizer(text, add_special_tokens=False, return_tensors="pt").input_ids[:, -config["max_seq_len"] :]
h = model.model(input_ids=ids).last_hidden_state[0, -1].float()
return torch.sigmoid(head["weight"][0] @ h + head["bias"][0]).item()
Then gate a fast model in your app: check its draft before returning it, and fall back to a larger model only when the score is low:
from openai import OpenAI
oai = OpenAI(base_url="http://localhost:8000/v1", api_key="unused") # vLLM serving your fine-tuned sql-agent
messages = [{"role": "user", "content": "How many orders shipped to Canada last month?"}]
draft = oai.chat.completions.create(model="sql-agent", messages=messages).choices[0].message.content
if score([*messages, {"role": "assistant", "content": draft}]) < 0.75:
draft = oai.chat.completions.create(model="Qwen/Qwen3-32B", messages=messages).choices[0].message.content
With pairs only, scores rank answers to the same prompt; they are not calibrated probabilities, so pick the threshold on held-out answers. Hosted reward-model serving is coming soon on Gradiated Cloud, and passing a reward model to a Judge is coming soon too.
Want more control?#
Step-by-step Process Reward Models (PRMs) and custom PyTorch losses are coming soon with Advanced objectives and Custom loops.