Looper Documentation
Looper Cookbook

The RL loop: train on rewards

In this tutorial you'll train a model with reinforcement learning (RL) on a few grade-school math problems, using the cookbook's RL loop, train_rl.train.

In Your first RL run, you wrote each round of RL yourself. Here, the loop does it for you. Each step, it:

  1. has the model answer each problem in the batch several times, using the run's own sampler;
  2. scores every answer;
  3. trains the run on the scores;
  4. sends the new weights to the sampler, so the next step's answers come from the updated model.

You'll also keep some problems out of training, and use them to measure the model before and after.

The SFT loop introduces the cookbook's loops. Verifiers explains tasks and how answers are scored.

This notebook uses the cookbook's package, looper_cookbook, which isn't on PyPI yet, so install it from a clone of its repository first, as The cookbook shows. Put your API key in the settings cell's API_KEY.

Settings

As before, the first settings are the model, its tokenizer, Looper's address, your project and your API key. Then come the settings for the run:

MODEL = "Qwen/Qwen3.5-9B"
TOKENIZER = "Qwen/Qwen3.5-9B"
BASE_URL = "https://api.looper.goaly.ai"
PROJECT = "example"
API_KEY = "YOUR_API_KEY"
LORA_RANK = 32
LEARNING_RATE = 8e-5
MAX_TURN_TOKENS = 512
BATCH_SIZE = 8
GROUP_SIZE = 8
STEPS = 8
HELD_OUT = 8

Turn the problems into tasks

The example file has 32 grade-school math problems from GSM8K's training set, each with its answer, which is a number.

Each problem becomes a task, which is one question for the model together with how to score its answers. A task has:

One try at a task is an attempt, which the cookbook also calls an episode. The task's config type, AgentSession.Config, comes from the cookbook's AgentSession, which runs one attempt. These tasks don't use tools, so an attempt is just one answer from the model.

TaskDataset splits the training tasks into batches, one per step. The last HELD_OUT problems are kept out of it, to measure the model with.

In the code below:

import json
from importlib import resources

from transformers import AutoTokenizer

from looper_cookbook import train_rl
from looper_cookbook.datasets.tasks import TaskDataset
from looper_cookbook.episode_sessions.agent_session import AgentSession
from looper_cookbook.message_formatters.models import message_formatter
from looper_cookbook.verifiers.final_number import FinalNumber
from looper_sdk import AdamW, Lora, SamplingParams, ServiceClient, TrainingConfig

tokenizer = AutoTokenizer.from_pretrained(TOKENIZER)
formatter = message_formatter(MODEL, tokenizer, enable_thinking=False)
path = resources.files("looper_cookbook") / "example_data" / "math_problems.jsonl"
problems = [json.loads(line) for line in path.read_text().splitlines()]
INSTRUCTION = "Solve it step by step, then give the final answer as a number after '####'."


def asked(problem):
    return [{"role": "user", "content": f"{problem['question']}\n{INSTRUCTION}"}]


# An attempt here is one turn, so an episode's token budget is the longest prompt
# and a turn's budget. The run and its sampler are sized to hold it.
prompts = [formatter.build_generation_prompt(asked(problem)) for problem in problems]
episode_tokens = max(len(prompt) for prompt in prompts) + MAX_TURN_TOKENS


def task(problem):
    return AgentSession.Config(
        messages=asked(problem),
        verifier=FinalNumber.Config(answer=str(problem["answer"])),
        max_episode_tokens=episode_tokens,
    )


tasks = [task(problem) for problem in problems]
train_tasks, held_out = tasks[:-HELD_OUT], tasks[-HELD_OUT:]
dataset = TaskDataset(train_tasks, batch_size=BATCH_SIZE, seed=0)
print(f"{len(train_tasks)} tasks in {len(dataset)} batches a pass, and {len(held_out)} held out")
print(f"an episode, a prompt and its one turn, holds at most {episode_tokens} tokens")

The run and its sampler

TrainingConfig sets up the training run, with the model, the LoRA, and the AdamW optimizer. Every step trains at LEARNING_RATE, because the RL loop doesn't change the learning rate. The run's sizes decide which GPUs it gets. max_seq_len must hold the longest attempt, and tokens_per_step is the most tokens one step trains on.

A training run only trains. For the model to write answers with the weights it's training, the run needs its own sampler. You create it from the training client, with training_client.create_sampling_client(...). Its sizes are the longest sequence it takes, and how many answers it writes at once.

The call returns once the sampler is ready and connected to the run. The sampler has no weights until the run first publishes them, which the loop does before its first step.

The start function below creates both. It runs in the last cell.

In the code below, tokens_per_step is the number of attempts in a step, BATCH_SIZE * GROUP_SIZE, times the most tokens one can use, so a whole step fits. max_concurrent_sequences is set to the same number of attempts, so the sampler writes all of a step's answers at once.

config = ServiceClient.Config(
    base_url=BASE_URL, project=PROJECT, api_key=API_KEY, display_name="rl-loop"
)
training = TrainingConfig(
    model=MODEL,
    kind=Lora(rank=LORA_RANK),
    tokens_per_step=BATCH_SIZE * GROUP_SIZE * episode_tokens,
    max_seq_len=episode_tokens,
    optimizer=AdamW(learning_rate=LEARNING_RATE, betas=(0.9, 0.95), max_grad_norm=1.0),
)


async def start(service):
    print("starting the run and its sampler...")
    training_client = await service.create_training_client(training, timeout_s=20 * 60)
    sampler = await training_client.create_sampling_client(
        max_seq_len=episode_tokens,
        max_concurrent_sequences=BATCH_SIZE * GROUP_SIZE,
        timeout_s=20 * 60,
    )
    return training_client, sampler

Measuring on held-out problems

The loop can measure the model as well as train it. Pass the held-out tasks as eval_tasks, and the loop has the model answer each of them once before the first training step, which gives you a starting score, and once again after the last step. These answers are only measured, never trained on.

The loop reports the mean reward on the held-out tasks as eval/reward. Here, that's the share of held-out problems the model got right. eval/reward_stderr is its standard error, which tells you how much the score could vary by chance.

By default, these answers are sampled at temperature 0, so the model always picks its most likely next token. This measures its best answer, rather than a random one. You can change that with the loop config's eval_params.

The loop

train_rl.train takes the run, its sampler, the dataset and the loop's config. Each step, it:

  1. Has the model attempt every task in the step's batch GROUP_SIZE times, all at once.
  2. Scores each attempt with its task's verifier.
  3. Sends each task's attempts to the trainer as one group. Grpo, the RL loss, compares each attempt's reward with the rest of its group. Attempts that scored above the group's average are made more likely, and those below are made less likely.
  4. Takes the training step, and publishes the new weights to the sampler.

The loop publishes before its first step, and waits for each publish to finish before sampling again. So every step trains on answers written by the weights from the step just before it.

After each step, the loop calls your on_step function with a report. The report holds the step's result, the version of the weights its answers came from, and a set of metrics. With eval_tasks, the first report comes before any training, and holds only the starting score. The report function below prints each one.

If every attempt in a group gets the same score, all right or all wrong, there's nothing to compare, and that group trains nothing. The report's groups_trained metric counts the groups whose scores differed.

As before, the session holds the run and its sampler. When the async with block ends, the session closes, and both shut down.

params sets how training answers are sampled. RL loops require temperature 1.0, so the loss sees the model's true probabilities.

In the code below:

loop_config = train_rl.Config(
    params=SamplingParams(max_tokens=MAX_TURN_TOKENS, temperature=1.0), group_size=GROUP_SIZE
)


def report(step):
    if step.result is None:
        print(f"before training: held out {step.metrics['eval/reward']:.3f}")
        return
    line = (
        f"step {step.step}/{STEPS}: reward {step.metrics['reward']:.3f} "
        f"on answers of step {step.version.step}, "
        f"{step.metrics['groups_trained']:.0f} of {step.metrics['groups']:.0f} groups trained"
    )
    if "eval/reward" in step.metrics:
        line += f", held out {step.metrics['eval/reward']:.3f}"
    print(line)


async def train_on_rewards():
    async with await config.build() as service:
        training_client, sampler = await start(service)
        return await train_rl.train(
            training_client,
            sampler,
            dataset,
            loop_config,
            formatter=formatter,
            steps=STEPS,
            eval_tasks=held_out,
            on_step=report,
        )


reports = None
reports = await train_on_rewards()

What the loop does for you

looper_cookbook/train_rl.py is short enough to read. It's meant to be copied and changed when your training needs something it doesn't do. If you write a loop of your own, it needs to handle the same five things this one does:

Next steps

The same loop also runs as a script, on all of GSM8K's training set, measured on its test set, with options for the model, the sizes and the number of steps:

python -m looper_cookbook.recipes.rl_basic --steps 20