# Train math reasoning with GRPO

> **About this page**
>
> - Kind: Example
> - Summary: Trains a model on math word problems with TRL's GRPO, rewarding answers that match the reference, and compares its GSM8K score before and after.
> - Last changed: 2026-12-03
> - Page: https://docs.swale.io/examples/grpo-math
> - 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/grpo-math`](https://github.com/swaleio/examples/tree/main/workflows/grpo-math) folder, with its [README](https://github.com/swaleio/examples/blob/main/workflows/grpo-math/README.md) and its [workflow file](https://github.com/swaleio/examples/blob/main/workflows/grpo-math/workflow.yaml).

Trains a model to solve math word problems with group relative policy
optimization. For each question the model writes several answers;
TRL's `accuracy_reward` gives 1 to the answers whose final result matches the
reference, checked with `math-verify`, and the model learns to favor them. The
base model and the trained model are both scored on GSM8K's test split.

| Step | Task definition | Compute |
|------|-----------------|---------|
| Turn GSM8K questions into chat prompts and reference solutions | [`swaleio/duckdb`](https://hub.swale.io/swaleio/duckdb) | `cpu-4` |
| Write the training config | [`swaleio/bash`](https://hub.swale.io/swaleio/bash) | `cpu-4` |
| Train | [`swaleio/trl-grpo`](https://hub.swale.io/swaleio/trl-grpo) | `a100-1` |
| Evaluate the base model, and the trained model | [`swaleio/lm-eval`](https://hub.swale.io/swaleio/lm-eval) | `a100-1` each |
| Compare the two scores | [`swaleio/duckdb`](https://hub.swale.io/swaleio/duckdb) | `cpu-4` |
| Upload the trained 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 base model is scored while the other model
trains.

## Inputs

| Input | Default | Description |
|-------|---------|-------------|
| `model` | `Qwen/Qwen2.5-0.5B-Instruct` | Chat model to train; all of its weights are trained. |
| `train_questions` | `2000` | GSM8K training questions to train on. |
| `hub_repo` | empty | Hugging Face model repo to upload the trained model to. |

Training, the base model's evaluation and the upload read the secret
`hf_token`.

## Output

The trained model in `trained/` on the workspace, the scores in `eval-base/`
and `eval-trained/`, and the comparison in the last task's log.

## 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 math reasoning with GRPO
description: Trains a model on math word problems with TRL's GRPO, rewarding answers that match the reference, and compares its GSM8K score before and after.
compute_type: cpu-4

inputs:
  model:
    description: Hugging Face repo id of the chat model to train. All of its weights are trained.
    default: Qwen/Qwen2.5-0.5B-Instruct
  train_questions:
    description: Number of GSM8K training questions to train on.
    default: "2000"
  hub_repo:
    description: Hugging Face model repo to upload the trained model to, as namespace/name. Leave empty to keep it on the workspace only.
    default: ""

entry_point: main

blocks:
  main:
    tasks:
      prepare:
        name: Prepare prompts and solutions
        uses: swaleio/duckdb
        args:
          sql: |
            -- GRPO reads a prompt column of chat messages; accuracy_reward compares each
            -- answer with the solution column, the number after #### in GSM8K's answers.
            COPY (
              SELECT [{'role': 'user', 'content': question || '\nPut the final answer in \boxed{}.'}] AS prompt,
                     trim(split_part(answer, '####', 2)) AS solution
              FROM 'hf://datasets/openai/gsm8k/main/train-*.parquet'
              LIMIT ${{inputs.train_questions}}
            ) TO '${{env.WORKFLOW_STORAGE}}/grpo-train.parquet' (FORMAT parquet);
            SELECT count(*) AS questions FROM '${{env.WORKFLOW_STORAGE}}/grpo-train.parquet';

      write_config:
        name: Write training config
        uses: swaleio/bash
        args:
          script: |
            cat > "$WORKFLOW_STORAGE/grpo.yaml" <<EOF
            model_name_or_path: ${{inputs.model}}
            datasets:
              - path: parquet
                data_files: $WORKFLOW_STORAGE/grpo-train.parquet
                split: train
            reward_funcs:
              - accuracy_reward
            learning_rate: 1.0e-6
            num_train_epochs: 1
            per_device_train_batch_size: 16
            num_generations: 8
            max_completion_length: 512
            bf16: true
            report_to: none
            save_strategy: "no"
            output_dir: $WORKFLOW_STORAGE/trained
            EOF

      train:
        name: Train with GRPO
        uses: swaleio/trl-grpo
        compute_type: a100-1
        start_on:
          - prepare
          - write_config
        args:
          config: ${{env.WORKFLOW_STORAGE}}/grpo.yaml
          token: ${{secrets.hf_token}}

      evaluate_base:
        name: Evaluate the base model
        uses: swaleio/lm-eval
        compute_type: a100-1
        args:
          model_dir: ${{inputs.model}}
          tasks: gsm8k
          output_path: ${{env.WORKFLOW_STORAGE}}/eval-base
          token: ${{secrets.hf_token}}

      evaluate_trained:
        name: Evaluate the trained model
        uses: swaleio/lm-eval
        compute_type: a100-1
        start_on:
          - train
        args:
          model_dir: ${{env.WORKFLOW_STORAGE}}/trained
          tasks: gsm8k
          output_path: ${{env.WORKFLOW_STORAGE}}/eval-trained

      compare:
        name: Compare
        uses: swaleio/duckdb
        start_on:
          - evaluate_base
          - evaluate_trained
        args:
          sql: |
            SELECT CASE WHEN filename LIKE '%/eval-base/%' THEN 'base' ELSE 'trained' END AS model,
                   round((results.gsm8k->>'$."exact_match,strict-match"')::DOUBLE, 4) AS strict_match,
                   round((results.gsm8k->>'$."exact_match,flexible-extract"')::DOUBLE, 4) AS flexible_extract
            FROM read_json(['${{env.WORKFLOW_STORAGE}}/eval-base/*/results_*.json',
                            '${{env.WORKFLOW_STORAGE}}/eval-trained/*/results_*.json'],
                           filename = true, columns = {'results': 'STRUCT(gsm8k JSON)'})
            ORDER BY model;

      publish:
        name: Upload when asked
        start_on:
          - compare
        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}}/trained
          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: [openai/gsm8k](https://huggingface.co/datasets/openai/gsm8k), MIT.
