Skip to main content

Train a reward model

Source on GitHub: the workflows/reward-model folder, with its README and its workflow file.

Trains a reward model, the scorer that RLHF methods and best-of-n sampling rank answers with, on human preference pairs, then measures it on pairs it did not see: how often it scores the preferred answer above the other one, and by how much on average.

StepTask definitionCompute
Write the training configswaleio/bashcpu-4
Train the reward modelswaleio/trl-rewarda100-1
Score the held-out pairsswaleio/transformersa100-1
Upload the reward model, when hub_repo is setswaleio/hf-uploadcpu-4

The Compute column gives each step's compute type, the compute its tasks are allocated.

Every step is its own task. The scoring step is a short Python script inside the workflow, run by the transformers task.

The result can drive swaleio/trl-grpo or swaleio/trl-rloo through reward_model_name_or_path.

Inputs​

InputDefaultDescription
modelQwen/Qwen2.5-0.5B-InstructModel the reward model starts from; all of its weights are trained.
train_splittrain_prefs[:20000]Pairs of HuggingFaceH4/ultrafeedback_binarized to train on.
eval_pairs1000Held-out pairs, from its test_prefs split.
hub_repoemptyHugging Face model repo to upload the reward model to.

Training and the upload read the secret hf_token.

Output​

The reward model in reward-model/ on the workspace, each held-out pair's two rewards in reward-scores.jsonl, and the accuracy and mean margin in reward-metrics.json.

Run it​

You need the CLI, logged in to your account, and a project to add the workflow to; Getting started sets them up.

  1. Save the file under The workflow file as workflow.yaml, and add it to a project:

    swale workflow create --project-name my-project --file workflow.yaml

    The command prints Workflow created: followed by the workflow's ID.

  2. The workflow reads the secret hf_token. Create it as a project secret, or as an account secret that allows the project, as Use secrets in workflows shows.

  3. Start a run with the workflow's ID:

    swale workflow run start --project-name my-project --workflow-id <workflow-id>

    Each input you leave out takes its default from Inputs, and --input <name>=<value> gives it another value.

Create and manage workflows covers the other ways to add a workflow, Start and manage workflow runs how to follow a run, and View and stream task logs how to read its tasks' logs.

The workflow file​

Workflow definition syntax describes each key in it.

workflow.yaml
name: Train a reward model
description: Trains a reward model on preference pairs with TRL, then measures how often it scores the preferred answer higher on held-out pairs.
compute_type: cpu-4

inputs:
model:
description: Hugging Face repo id of the model the reward model starts from. All of its weights are trained.
default: Qwen/Qwen2.5-0.5B-Instruct
train_split:
description: Preference pairs to train on, from HuggingFaceH4/ultrafeedback_binarized.
default: train_prefs[:20000]
eval_pairs:
description: Number of held-out pairs to score.
default: "1000"
hub_repo:
description: Hugging Face model repo to upload the reward model to, as namespace/name. Leave empty to keep it on the workspace only.
default: ""

entry_point: main

blocks:
main:
tasks:
write_config:
name: Write training config
uses: swaleio/bash
args:
script: |
cat > "$WORKFLOW_STORAGE/reward.yaml" <<EOF
model_name_or_path: ${{inputs.model}}
datasets:
- path: HuggingFaceH4/ultrafeedback_binarized
split: ${{inputs.train_split}}
columns: [chosen, rejected]
learning_rate: 1.0e-5
num_train_epochs: 1
per_device_train_batch_size: 8
gradient_accumulation_steps: 2
max_length: 1024
bf16: true
report_to: none
save_strategy: "no"
output_dir: $WORKFLOW_STORAGE/reward-model
EOF

train:
name: Train the reward model
uses: swaleio/trl-reward
compute_type: a100-1
start_on:
- write_config
args:
config: ${{env.WORKFLOW_STORAGE}}/reward.yaml
token: ${{secrets.hf_token}}

score:
name: Score held-out pairs
uses: swaleio/transformers
compute_type: a100-1
start_on:
- train
args:
script: |
import json, os
import torch
from datasets import load_dataset
from transformers import AutoModelForSequenceClassification, AutoTokenizer

storage = os.environ["WORKFLOW_STORAGE"]
path = f"{storage}/reward-model"
tokenizer = AutoTokenizer.from_pretrained(path)
model = AutoModelForSequenceClassification.from_pretrained(path, dtype=torch.bfloat16).cuda().eval()
pairs = load_dataset("HuggingFaceH4/ultrafeedback_binarized", split="test_prefs[:${{inputs.eval_pairs}}]")

@torch.no_grad()
def reward(messages):
text = tokenizer.apply_chat_template(messages, tokenize=False)
ids = tokenizer(text, return_tensors="pt", truncation=True, max_length=1024).to("cuda")
return model(**ids).logits[0, 0].item()

rows = []
for pair in pairs:
chosen, rejected = reward(pair["chosen"]), reward(pair["rejected"])
rows.append({"prompt_id": pair["prompt_id"], "chosen": chosen, "rejected": rejected})
correct = sum(r["chosen"] > r["rejected"] for r in rows)
metrics = {"pairs": len(rows), "accuracy": round(correct / len(rows), 4),
"mean_margin": round(sum(r["chosen"] - r["rejected"] for r in rows) / len(rows), 4)}
with open(f"{storage}/reward-scores.jsonl", "w") as f:
f.writelines(json.dumps(r) + "\n" for r in rows)
with open(f"{storage}/reward-metrics.json", "w") as f:
json.dump(metrics, f, indent=2)
print(json.dumps(metrics))

publish:
name: Upload when asked
start_on:
- score
if:
condition: ${{inputs.hub_repo}}
true: upload

upload:
tasks:
upload_model:
name: Upload to the Hugging Face Hub
uses: swaleio/hf-upload
args:
repo: ${{inputs.hub_repo}}
source: ${{env.WORKFLOW_STORAGE}}/reward-model
token: ${{secrets.hf_token}}

Licenses of the defaults​