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:
- A complete example: a short script that takes one RL step on one question.
- Turn it into a real loop: what to add for many questions and many steps, and where each part is explained.
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:
- Creates a training run and its own sampler. The sampler generates answers with the run's current weights.
publish_weightscopies the run's weights to the sampler. A run's sampler has nothing to serve until the first publish. - Asks for eight answers to the question. These eight answers to the same question are called a group.
- Scores each answer with
reward, which is your own code. It gives 1 if the answer is exactly 111563, and 0 if not. - Turns each answer into a
Datumwith its reward, and trains one step on the group with theGrpoloss. - 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:
- Wait for a publish before you sample its weights. The run's sampler serves nothing until the first
publish_weights, and after that, it serves each version you publish once it's ready. The script awaits each publish'sresult()for that reason. - Each answer becomes a
Datum. It holds the prompt at weight 0, the answer at weight 1, the answer'slogprobs(how likely the sampler was to write each token), and itsreward. All eight share agroup_idandgroup_size, so the trainer knows they're answers to the same question. A group must be sent whole, in one call. Grpocompares the answers within the group. For each answer, it works out how much better or worse it scored than the group's average, by taking its reward minus the group's mean and dividing by the group's standard deviation. This is called the answer's advantage. Answers that scored above average are made more likely, and those below less likely. If every answer gets the same reward, there's nothing to compare, and the step trains nothing.rewardis the part you'd change for your own task. In the cookbook, this scoring is done by a verifier.
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:
- Many questions per step. Sample a group for each question in a batch, and send all the groups to one
forward_backwardcall, keeping each group whole. See Train on rewards. - Your scoring. Replace
rewardwith your own scoring. The cookbook's verifiers can be used on their own, even in your own loop. - Publishing and waiting. Publish after each step. Then decide whether to wait for each publish before sampling again (synchronous RL), or keep sampling while the trainer works (asynchronous RL). See Sample a run's own weights and Synchronous and asynchronous RL.
- Old answers. In asynchronous RL, each answer's
versionsays which weights wrote it. Use it to skip answers that are too old to train on. - Saving. Save checkpoints during training, not only at the end. See Checkpoint.
- Keeping your program running. Your program has to run for the whole training run, because it sends each step and keeps the session open. If it stops, for example because your laptop goes to sleep, the session expires after 60 seconds and the run is shut down. A run can't be resumed from a checkpoint yet. So run long training on a machine that stays on. See When a session expires.
- Failures. If the run loses its GPUs, it restarts from step 0 and its sampler stops. Your loop decides what to train again, and creates a new sampler. See When a run rolls back.
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
- Training: every training call in detail, especially Choose a loss.
- Sampling: starting samplers and reading their results.
- SFT with your own loop: the same, for SFT.