# Snowflake Native App rewards

GRPO and other reinforcement learning over table rows need a reward: a score for each completion the model writes. In the Arena Native App you set it in the manifest’s `environment.reward`. Pick a built-in reward, or write the reward as a Snowflake function in your account and bind it to the app.

The app takes no reward file. Snowflake does not let a Native App run code from outside its package, so the app does not load Python files you pass to it.

The examples on this page call the app `arena_app`. Replace it with the name you gave the app at install. For installing the app, binding a table and submitting runs, see [Snowflake Native App](snowflake-native-app.md).

## Prerequisites

- The app is installed and connected to Arena, and it has compute pools.
- A table or view is bound to the app. Each row has a prompt column and an answer column, such as `QUESTION` and `ANSWER`.
- To bind your own function: a role that holds `app_admin` and can grant `USAGE` on the function, such as the function’s owner.

## Choose a reward

| Use               | When                                                                                                                                               |
|-------------------|----------------------------------------------------------------------------------------------------------------------------------------------------|
| A built-in reward | The answer column holds the right answer, and a fixed check is enough: equal text, the same number, a pattern, valid JSON, or the right tool call. |
| Your own function | The check needs your own logic, other data in your account, or an LLM grader.                                                                      |

## Built-in rewards

A built-in reward runs inside the app. It scores the model’s final answer, which is the text of its last reply after any reasoning. It compares that answer with the row’s `answer` column and gives 1 or 0.

Map your answer column onto `answer` in `environment.columns`. This GRPO run reads `QUESTION` and `ANSWER` from the bound table and scores with `numeric`:

```postgresql
CALL arena_app.app_code.submit(
  $$
algorithm:
  name: GRPO
  batch_size: 8
  group_size: 4
environment:
  env_type: rollout
  columns:
    question: QUESTION
    answer: ANSWER
  prompt_template:
    system_0: Think step by step, then give the final number inside <answer></answer>.
    user_1: "{question}"
  reward:
    type: numeric
    answer_pattern: "<answer>(.*)</answer>"
  max_reward: 1.0
network:
  pretrained_model_name_or_path: Qwen/Qwen3.5-0.8B
  max_context_length: 2048
training:
  max_steps: 200
$$,
  2,
  'source_table',
  '<alias>',
  'GPU_NV_S'
);
```

`max_reward` is the reward at which a completion counts as solved in the success metric. With a built-in reward, use `1.0`.

The five types are below. Patterns are Python regular expressions. They are case-sensitive, and `.` also matches a new line. Put `(?i)` at the very start of a pattern to ignore case.

### Read the answer out of a longer reply

`exact_match` and `numeric` take an optional `answer_pattern`. It is a regular expression whose first capturing group is the answer, such as `"Answer: (.*)"` or `"<answer>(.*)</answer>"`. When the pattern matches more than once, the last match counts. A reply with no match scores 0. Without `answer_pattern`, `exact_match` compares the whole reply, and `numeric` reads the number as described in [numeric](#numeric).

A pattern without a capturing group is refused when you submit.

### exact_match

Scores 1 when the answer equals the row’s `answer`.

| Parameter        | Meaning                                                                                                                          | Default     |
|------------------|----------------------------------------------------------------------------------------------------------------------------------|-------------|
| `normalize`      | Ignore case, extra spaces and one trailing full stop before comparing. With `false` the text must match character for character. | `true`      |
| `answer_pattern` | Reads the answer out of the reply. See [Read the answer out of a longer reply](#read-the-answer-out-of-a-longer-reply).          | Whole reply |
```yaml
reward:
  type: exact_match
  answer_pattern: "Answer: (.*)"
```

Use it for short text answers such as a label, a name or a yes or no. For numbers, use `numeric`, so that `42`, `42.0` and `42.` all count.

### numeric

Scores 1 when the answer is a number within `tolerance` of the row’s `answer`.

| Parameter        | Meaning                                                                                | Default   |
|------------------|----------------------------------------------------------------------------------------|-----------|
| `tolerance`      | Largest absolute difference that still counts as correct.                              | `1e-6`    |
| `answer_pattern` | Reads the answer out of the reply. The last number in the captured text is the answer. | See below |

Without `answer_pattern`, the answer is the last number inside the last `\boxed{...}` in the reply. A reply with no `\boxed{...}` uses its last number. Commas between digits are ignored, so `1,250` reads as 1250.

The row’s `answer` can be a number, or text that holds one. Its last number is used. A row with no number scores 0.

```yaml
reward:
  type: numeric
  tolerance: 0.01
```

### regex

Scores 1 when the reply matches `pattern`. It does not read the row’s `answer`.

| Parameter    | Meaning                                                              | Default   |
|--------------|----------------------------------------------------------------------|-----------|
| `pattern`    | Python regular expression.                                           | Required  |
| `full_match` | Match the whole reply instead of finding the pattern anywhere in it. | `false`   |
```yaml
reward:
  type: regex
  pattern: "(?i)(positive|negative|neutral)"
  full_match: true
```

Use it to reward a format, such as one label from a fixed list.

### json_schema

Scores 1 when the first JSON object in the reply is valid against `schema`. It does not read the row’s `answer`.

| Parameter   | Meaning                              | Default   |
|-------------|--------------------------------------|-----------|
| `schema`    | JSON Schema the object must satisfy. | Required  |

The object starts at the first `{` in the reply. Text before it is ignored. If the JSON that starts there does not parse, the reply scores 0.

```yaml
reward:
  type: json_schema
  schema:
    type: object
    required: [name, email]
    properties:
      name: {type: string}
      email: {type: string}
    additionalProperties: false
```

Use it for structured extraction, where the shape of the output is what you train for.

### tool_call

Scores 1 when the first tool call in the reply is the expected one. A tool call is a JSON object with `name` and `arguments`, written bare or inside `<tool_call></tool_call>` tags. The tags are read first when the reply has them.

| Parameter            | Meaning                                         | Default   |
|----------------------|-------------------------------------------------|-----------|
| `name`               | Tool the call must use.                         | Unset     |
| `required_arguments` | Argument keys the call must pass. Needs `name`. | `[]`      |

With `name` set, the call scores 1 when it uses that tool and passes every key in `required_arguments`. The argument values are not checked, and the row’s `answer` is not read:

```yaml
reward:
  type: tool_call
  name: get_weather
  required_arguments: [city]
```

Without `name`, the row’s `answer` holds the expected call as JSON text, such as `{"name": "get_weather", "arguments": {"city": "Paris"}}`. The call scores 1 when both its name and its arguments equal that call:

```yaml
reward:
  type: tool_call
```

## Your own reward function

Write the reward as a function in your Snowflake account and bind it to the app’s `reward_function` reference. Snowflake runs the function in your account, as your object. The app calls it with SQL and never reads its code. You can use any Snowflake function with the right signature: Python, SQL, Java, or one that calls `AI_COMPLETE` to grade with an LLM.

### The function’s inputs and output

The function takes three `STRING` arguments, in this order, and returns `FLOAT`:

| Argument     | Value                                                                                                                |
|--------------|----------------------------------------------------------------------------------------------------------------------|
| `prompt`     | The row’s `question` column. With no `question` mapped, the first prompt of the episode.                             |
| `completion` | The model’s final answer: the text of its last reply after any reasoning.                                            |
| `answer`     | The row’s `answer` column as text. A value that is not text arrives as JSON text. `NULL` when the row has no answer. |

Return a finite number for every row. The score can be any number, not just 0 or 1. Set `max_reward` in the manifest to the score at which a completion counts as solved.

### A Python function

This function gives 1 when the last number in the completion equals the answer:

```postgresql
CREATE OR REPLACE FUNCTION my_db.rewards.score_answer(
    prompt STRING, completion STRING, answer STRING)
  RETURNS FLOAT
  LANGUAGE PYTHON
  RUNTIME_VERSION = '3.12'
  HANDLER = 'score'
AS $$
import re

def score(prompt, completion, answer):
    numbers = re.findall(r"-?\d+(?:\.\d+)?", completion or "")
    if not numbers or answer is None:
        return 0.0
    try:
        expected = float(answer)
    except ValueError:
        return 0.0
    return 1.0 if abs(float(numbers[-1]) - expected) < 1e-6 else 0.0
$$;
```

An empty answer, or one that is not a plain number, scores 0. `float` raises on that input, and a function that raises stops the run.

### A SQL function

A SQL function is the fastest to call. This one gives 1 when the completion contains the answer, ignoring case:

```postgresql
CREATE OR REPLACE FUNCTION my_db.rewards.contains_answer(
    prompt STRING, completion STRING, answer STRING)
  RETURNS FLOAT
AS $$
  IFF(CONTAINS(LOWER(completion), LOWER(answer)), 1.0, 0.0)::FLOAT
$$;
```

Cast the result to `FLOAT`. `IFF(..., 1.0, 0.0)` on its own is a `NUMBER`, and `CREATE FUNCTION` fails. When `answer` is `NULL`, `CONTAINS` returns `NULL` and `IFF` gives 0.0, so the function never returns `NULL`.

### Bind the function to the app

Bind the function to `reward_function`. Name the function with its argument types:

```text
CALL arena_app.app_code.register_reference(
  'reward_function', 'ADD',
  SYSTEM$REFERENCE('FUNCTION', 'my_db.rewards.score_answer(STRING, STRING, STRING)', 'PERSISTENT', 'USAGE')
);
```

For the SQL function above, name it the same way:

```text
CALL arena_app.app_code.register_reference(
  'reward_function', 'ADD',
  SYSTEM$REFERENCE('FUNCTION', 'my_db.rewards.contains_answer(STRING, STRING, STRING)', 'PERSISTENT', 'USAGE')
);
```

Run either call as a role that holds `app_admin` and can grant `USAGE` on the function, such as the function’s owner. You can also bind the function in Snowsight, on the app’s references.

The reference holds one function. Binding another replaces it. Check the binding with:

```sql
SHOW REFERENCES IN APPLICATION arena_app;
```

### Use the function in a run

Set `environment.reward` to `snowflake_function`:

```postgresql
CALL arena_app.app_code.submit(
  $$
algorithm:
  name: GRPO
  batch_size: 8
  group_size: 4
environment:
  env_type: rollout
  columns:
    question: QUESTION
    answer: ANSWER
  prompt_template:
    system_0: Think step by step, then give the final number.
    user_1: "{question}"
  reward:
    type: snowflake_function
  max_reward: 1.0
network:
  pretrained_model_name_or_path: Qwen/Qwen3.5-0.8B
  max_context_length: 2048
training:
  max_steps: 200
$$,
  2,
  'source_table',
  '<alias>',
  'GPU_NV_S'
);
```

`submit` checks that a function is bound before it starts anything.

### How the app calls the function

- The app scores each group of completions once the whole group has finished. Each group is one prompt with `group_size` completions.
- Each training process sends groups to the function in one query on the app’s XSMALL warehouse. Groups that finish while a query runs go into the next query together. One query costs about the same whatever its size: about 1.3 seconds for a Python function and 0.15 seconds for a SQL function, from 64 to 2,048 rows.
- Each GPU worker runs its own training process, so several queries can run at once and queue on the warehouse.
- The first query after the warehouse resumes takes about 20 seconds, so the first training step is that much slower.
- The queries run on the app’s warehouse in your account, and Snowflake bills them to your account like any other query.
- If the connection to Snowflake drops, the app reconnects and tries the query again, up to 4 times. A function that fails, returns `NULL`, or returns a value that is not a finite number stops the run with that error.

To keep training fast, prefer a SQL function, and keep slow work such as an LLM grader for when you need it.

## Common messages

| Message                                                                                                                       | What to do                                                                                           |
|-------------------------------------------------------------------------------------------------------------------------------|------------------------------------------------------------------------------------------------------|
| `reward_file is not available in the Snowflake app.`                                                                          | Leave `reward_file` out of `submit`, and set `environment.reward` in the manifest instead.           |
| `environment.rubric_file_path is not available in the Snowflake app.`                                                         | Remove `rubric_file_path` from the manifest, and set `environment.reward` instead.                   |
| `A dataset-backed rollout needs reward or rubric_file_path`                                                                   | Add `environment.reward` to the manifest.                                                            |
| `environment.reward is snowflake_function, but no function is bound to the app's reward_function reference.`                  | [Bind the function](#bind-the-function-to-the-app), then submit again.                               |
| `reward replaces the rubric file; drop ...`                                                                                   | Remove the fields the message lists from the manifest.                                               |
| `reward scores rollouts; a dataset environment trains on its rows.`                                                           | Use `environment.reward` only with `env_type: rollout`.                                              |
| `answer_pattern needs a capturing group, for example 'Answer: (.*)'.`                                                         | Put the answer part of the pattern in parentheses.                                                   |
| `required_arguments needs name; without it answer is the expected call.`                                                      | Add `name` to the `tool_call` reward, or remove `required_arguments`.                                |
| `The function bound to reward_function returned None for completion <n>. It must return a finite FLOAT for every completion.` | Make the function return a number for every input, including a `NULL` answer or an empty completion. |
| `The function bound to reward_function returned <m> rewards for <n> completions.`                                             | Use a scalar function that returns one value per row.                                                |

`submit` refuses each of these before it starts anything, except the last two. Those stop a run that is already training.

## Related

- [Snowflake Native App](snowflake-native-app.md)
