Looper Documentation
Looper Cookbook

RL with your own loop

This page is for running reinforcement learning (RL) with your own training loop, calling the SDK directly instead of using the cookbook's train_rl or train_rl_async. If the cookbook's loops fit what you're doing, Reinforcement learning is simpler. The cookbook or your own loop explains when you'd write your own.

An RL loop uses both the trainer and the sampler. If you haven't yet, read How training works first. It explains how they work together, and what synchronous and asynchronous RL mean.

This page covers:

Before you start, set up the SDK and your API key, as in Quickstart. Training and Sampling explain every call used here, with all its options.

A complete example

This script takes one step of reinforcement learning (RL). Instead of showing the model correct answers, you let it answer, score its answers, and train it to write more answers like the high-scoring ones. How training works explains the idea.

The question is "What is 3847 * 29?", and the right answer is 111563. The script:

  1. Creates a training run and its own sampler. The sampler generates answers with the run's current weights. publish_weights copies the run's weights to the sampler. A run's sampler has nothing to serve until the first publish.
  2. Asks for eight answers to the question. These eight answers to the same question are called a group.
  3. Scores each answer with reward, which is your own code. It gives 1 if the answer is exactly 111563, and 0 if not.
  4. Turns each answer into a Datum with its reward, and trains one step on the group with the Grpo loss.
  5. Publishes the new weights to the sampler, so the next answers would come from the trained model.

In a real RL run, you'd repeat steps 2 to 5 over many questions. Turn it into a real loop covers that.

Save it as rl.py:

import asyncio
import os

from transformers import AutoTokenizer

from looper_sdk import (
    AdamW,
    Datum,
    Grpo,
    Lora,
    SamplingParams,
    ServiceClient,
    TrainingConfig,
)

MODEL = "Qwen/Qwen3.5-9B"
GROUP_SIZE = 8
MAX_SEQ_LEN = 256
tokenizer = AutoTokenizer.from_pretrained(MODEL)


def chat_prompt(question):
    text = tokenizer.apply_chat_template(
        [{"role": "user", "content": question}],
        add_generation_prompt=True,
        tokenize=False,
        enable_thinking=False,
    )
    return tokenizer(text, add_special_tokens=False)["input_ids"]


def reward(sequence):
    text = tokenizer.decode(sequence.token_ids, skip_special_tokens=True)
    return float(text.strip() == "111563")


async def main():
    config = ServiceClient.Config(
        project=os.environ["LOOPER_PROJECT"],
    )
    training_config = TrainingConfig(
        model=MODEL,
        kind=Lora(rank=32),
        tokens_per_step=GROUP_SIZE * MAX_SEQ_LEN,
        max_seq_len=MAX_SEQ_LEN,
        optimizer=AdamW(learning_rate=8e-5, betas=(0.9, 0.95), max_grad_norm=1.0),
    )
    params = SamplingParams(
        max_tokens=32, temperature=1.0, stop_token_ids=(tokenizer.eos_token_id,)
    )
    prompt = chat_prompt("What is 3847 * 29? Reply with the number only.")

    async with await config.build() as service:
        print("starting the run and its sampler...")
        training_client = await service.create_training_client(training_config, timeout_s=20 * 60)
        sampling_client = await training_client.create_sampling_client(
            max_seq_len=MAX_SEQ_LEN, max_concurrent_sequences=GROUP_SIZE, timeout_s=20 * 60
        )
        published = await (await training_client.publish_weights()).result()
        print(f"the sampler serves step {published.version.step}")

        operation = await sampling_client.sample(prompt, params=params, n=GROUP_SIZE)
        result = await operation.result()
        data = []
        for sequence in result.sequences:
            data.append(
                Datum(
                    tokens=[*prompt, *sequence.token_ids],
                    weights=[0] * len(prompt) + [1] * len(sequence.token_ids),
                    columns={"logprobs": [0.0] * len(prompt) + list(sequence.logprobs)},
                    reward=reward(sequence),
                    group_id="quickstart",
                    group_size=GROUP_SIZE,
                )
            )
        print("rewards:", [datum.reward for datum in data])

        await training_client.forward_backward(data, Grpo())
        step = await (await training_client.optim_step()).result()
        published = await (await training_client.publish_weights()).result()
        print(f"trained step {step.step}; the sampler serves step {published.version.step}")


asyncio.run(main())
starting the run and its sampler...
the sampler serves step 0
rewards: [0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]
trained step 1; the sampler serves step 1

Here one of the eight answers was right, so it scored 1 and the rest scored 0. The run trained one step on that, and the sampler now serves the new weights, step 1.

Things to know:

104: Your first RL run goes through this same script step by step, as a notebook, and repeats it for a few rounds.

Turn it into a real loop

The example takes one step on one question. A real run trains on many questions over many steps. These are the parts you'd add, and where each is explained:

302: The RL loop shows the cookbook's loop, which does all of this. Its code is a useful reference for your own.

Next steps