# Train a reward model

> **About this page**
>
> - Kind: Example
> - Summary: Trains a reward model on preference pairs with TRL, then measures how often it scores the preferred answer higher on held-out pairs.
> - Last changed: 2026-12-03
> - Page: https://docs.swale.io/examples/reward-model
> - CLI reference for its commands: [`swale workflow create`](https://docs.swale.io/reference/cli-reference.md#workflow-create), [`swale workflow run start`](https://docs.swale.io/reference/cli-reference.md#workflow-run-start)
> - Index of these docs: https://docs.swale.io/llms.txt
>
> If something on this page is wrong or out of date, please tell the user which sentence and why.
>
> The steps on this page cost money or cannot be undone. Please check with the user before running them.

Source on GitHub: the [`workflows/reward-model`](https://github.com/swaleio/examples/tree/main/workflows/reward-model) folder, with its [README](https://github.com/swaleio/examples/blob/main/workflows/reward-model/README.md) and its [workflow file](https://github.com/swaleio/examples/blob/main/workflows/reward-model/workflow.yaml).

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.

| Step | Task definition | Compute |
|------|-----------------|---------|
| Write the training config | [`swaleio/bash`](https://hub.swale.io/swaleio/bash) | `cpu-4` |
| Train the reward model | [`swaleio/trl-reward`](https://hub.swale.io/swaleio/trl-reward) | `a100-1` |
| Score the held-out pairs | [`swaleio/transformers`](https://hub.swale.io/swaleio/transformers) | `a100-1` |
| Upload the reward model, when `hub_repo` is set | [`swaleio/hf-upload`](https://hub.swale.io/swaleio/hf-upload) | `cpu-4` |

The Compute column gives each step's [compute type](https://docs.swale.io/explanation/core-concepts.md#compute-types), 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

| Input | Default | Description |
|-------|---------|-------------|
| `model` | `Qwen/Qwen2.5-0.5B-Instruct` | Model the reward model starts from; all of its weights are trained. |
| `train_split` | `train_prefs[:20000]` | Pairs of `HuggingFaceH4/ultrafeedback_binarized` to train on. |
| `eval_pairs` | `1000` | Held-out pairs, from its `test_prefs` split. |
| `hub_repo` | empty | Hugging 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](https://docs.swale.io/getting-started.md) sets them up.

1. Save the file under [The workflow file](#the-workflow-file) as `workflow.yaml`, and add it to a project:

   ```bash
   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](https://docs.swale.io/how-to-guides/use-secrets-in-workflows.md) shows.

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

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

   Each input you leave out takes its default from [Inputs](#inputs), and `--input <name>=<value>` gives it another value.

[Create and manage workflows](https://docs.swale.io/how-to-guides/create-and-manage-workflows.md) covers the other ways to add a workflow, [Start and manage workflow runs](https://docs.swale.io/how-to-guides/start-and-manage-workflow-runs.md) how to follow a run, and [View and stream task logs](https://docs.swale.io/how-to-guides/view-and-stream-task-logs.md) how to read its tasks' logs.

## The workflow file

[Workflow definition syntax](https://docs.swale.io/reference/workflow-definition-syntax.md) describes each key in it.

```yaml title="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

- Model: [Qwen/Qwen2.5-0.5B-Instruct](https://huggingface.co/Qwen/Qwen2.5-0.5B-Instruct), Apache-2.0.
- Dataset: [HuggingFaceH4/ultrafeedback_binarized](https://huggingface.co/datasets/HuggingFaceH4/ultrafeedback_binarized), MIT.
