Your first RL run
Improve a model with rewards instead of examples. Sample several answers per prompt, score them, and push the model toward the better ones.
Define the task and reward
An environment says what the model sees and how its answer scores. Start simple and verifiable: exact match, unit tests passing, or a grader model you trust.
from rsi.forge import rl
class Math(rl.Env):
def reset(self, row):
return [{"role": "user", "content": row["question"]}]
def reward(self, traj, row):
return float(extract_answer(traj.final_text) == row["answer"])Run the loop
The rollout engine samples a group of answers per question from the model's live weights; the trainer scores them, turns rewards into advantages (each answer's reward minus its group's mean), and updates the model. Groups where every answer scored the same carry no signal and are skipped.
with client.session(run="math-rl") as session:
model = session.create_model("Qwen3.8-27B", lora=rsi.LoraConfig(rank=16))
engine = rl.RolloutEngine(model, env=Math, budget=rl.Budget(max_turns=1, segment_tokens=4096))
trainer = rl.AsyncTrainer(
engine=engine,
optimizer=rl.Adam(lr=4e-5, schedule=rl.cosine(warmup=10)),
groups_per_step=16,
group_size=8,
loss=rl.CISPO(),
max_staleness=2,
)
for step in trainer.run(questions, steps=200):
model.log({"reward/mean": step.metrics["reward/mean"]})
if step.n % 50 == 49:
model.save_weights(f"step-{step.n + 1}")Sampling keeps running while the model trains. max_staleness bounds how many updates old a sampled answer may be when it is trained on; set it to 0 for strictly on-policy training.
Agents with tools
Give the environment tools and the model can call them. Each tool's schema comes from its type hints and docstring; the default turn handler runs the calls (in parallel) and returns their results to the model until it answers.
@rl.tool
def search(query: str) -> str:
"""Search the knowledge base.
Args:
query: What to look for.
"""
return kb.search(query)
class Support(rl.Env):
tools = (search,)
def reset(self, row):
return [{"role": "user", "content": row["ticket"]}]
def reward(self, traj, row):
return grade(traj.final_text, row["resolution"])Each environment class gets a fresh instance per rollout. Raise rl.InfrastructureError when your side fails (a sandbox or service is down): the run stops instead of training the model on the outage.
Settings that matter
| Setting | What it controls |
|---|---|
rl.Budget | Turns, generated tokens, context tokens and tokens per turn for each rollout |
rl.Truncation | How rollouts cut off by the budget train: zero reward (default), their own reward, or not at all |
max_staleness, rl.Schedule | How far sampling may run ahead of training, and how many rollouts run at once |
loss | rl.CISPO() (default), rl.PPO(), rl.ImportanceSampling() or rl.DRO(), each with normalize = token, sequence or sum |
advantage | rl.GroupCentered() (default), rl.Batchwise(), or any function of the rewards |
environment_timeout | Stops a stuck environment; its rollout is dropped, not scored |
Long runs
Step and evaluation metrics appear on the run's page in the Console as training goes. For runs that take hours, add recovery and evaluation:
trainer = rl.AsyncTrainer(
engine=engine,
optimizer=rl.Adam(lr=4e-5),
groups_per_step=16,
group_size=8,
checkpoint=rl.Checkpointing("runs/math-rl", weights_every=20),
evaluator=rl.Evaluator(holdout, every=20, group_size=4),
sinks=[rl.WandbSink(wandb_run)], # optional
)- Every 20 steps the trainer saves the weights and optimizer state and records where the run is. If the process stops, run the same script again: it continues from that step with the same plan. A
SIGTERMsaves and stops cleanly. - Rollouts that were in flight are dropped by default. Set
recovery = "stateless"on the environment to rerun them, or"snapshot"(withsnapshotandrestore) to continue them where they were. - The evaluator runs the held-out rows against a saved copy of the weights in a separate session while training continues, plus a final evaluation at the end. Held-out rows are never trained on.
Under the hood
The library is built on Layer 1 calls you can use directly. One step by hand: sample a group, score it, and train on the sampled tokens with their advantages.
groups = model.sample(model_input=[[{"role": "user", "content": q}] for q in questions],
num_samples=8, max_tokens=4096)
data = []
for samples, answer in zip(groups, answers):
rewards = [float(extract_answer(s.text) == answer) for s in samples]
baseline = sum(rewards) / len(rewards)
for s, r in zip(samples, rewards):
p, n = len(s.prompt_token_ids), len(s.tokens)
ids = s.prompt_token_ids + s.tokens
data.append({
"input_ids": ids,
"target_tokens": ids[1:] + [0],
"old_logprobs": [0.0] * (p - 1) + s.logprobs + [0.0],
"advantages": [0.0] * (p - 1) + [r - baseline] * n + [0.0],
})
model.train_step(data, lr=4e-5, loss_fn="importance_sampling")Evaluate and save
Save checkpoints as you go and compare them on private evals.