In this tutorial you'll train Qwen/Qwen3.5-9B with reinforcement learning (RL) to multiply numbers. You'll write each round of RL yourself, with the SDK alone, and run it four times.
In Your first fine-tune, the model learned from answers you wrote. In RL, it learns from its own answers instead. Each round:
- The model writes several answers to each multiplication problem.
- Your program scores each answer, giving 1 if it's right and 0 if not.
- The run trains on those scores, so right answers become more likely.
- The run sends its new weights to the sampler, so the next round's answers come from the updated model.
How training works explains these ideas in more detail. Every call below uses the two awaits from Operations. Put your API key in the settings cell's API_KEY.
Install the SDK and tokenizer
As before, transformers is only used for its tokenizer. No model weights are downloaded to your machine.
%pip install -q "goaly-looper==0.1.0b6" "transformers==5.19.0"
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:
LORA_RANKandLEARNING_RATE: the size of the LoRA, and how big each training update is.PROBLEMS: how many multiplication problems each round uses.GROUP_SIZE: how many answers the model writes to each problem. These answers are a group.ROUNDS: how many rounds to run.MAX_TOKENS: the longest answer the model can write, in tokens.
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
PROBLEMS = 8
GROUP_SIZE = 8
ROUNDS = 4
MAX_TOKENS = 64
The problems and how they're scored
Each problem multiplies two three-digit numbers, such as "What is 123 × 456?". The prompt is put into the model's own chat format, with thinking turned off, and turned into token ids.
The reward function gives an answer a score of 1 if the last number in it is the right product, and 0 if not. This is your code, running on your machine. Looper never sees the right answers. It only gets the scores, inside the training data you send.
In the code below:
random.Random(0)makes a random number generator with a fixed seed, so you get the same problems each time you run the notebook.apply_chat_templatewrites the question in the model's chat format.add_generation_prompt=Trueadds the start of the assistant's reply, so the model's next tokens are its answer.tokenize=Falsereturns text, which the next line turns into token ids. That line usesadd_special_tokens=False, because the chat format already has every special token it needs.- In
reward, the reply is turned into text, commas are removed so56,088reads as one number, andre.findallfinds every number in it. The reward is 1.0 if there's at least one number and the last one is the product, and 0.0 otherwise. longestis the longest prompt plus the longest answer. The next cell sizes the run with it.
import asyncio
import random
import re
from transformers import AutoTokenizer
from looper_sdk import AdamW, Datum, Grpo, Lora, SamplingParams, ServiceClient, TrainingConfig
tokenizer = AutoTokenizer.from_pretrained(TOKENIZER)
rng = random.Random(0)
problems = [(rng.randint(100, 999), rng.randint(100, 999)) for _ in range(PROBLEMS)]
def prompt(a, b):
text = tokenizer.apply_chat_template(
[{"role": "user", "content": f"What is {a} × {b}? Answer with the number only."}],
add_generation_prompt=True,
tokenize=False,
enable_thinking=False,
)
return tokenizer(text, add_special_tokens=False)["input_ids"]
def reward(sequence, a, b):
text = tokenizer.decode(sequence.token_ids, skip_special_tokens=True)
numbers = re.findall(r"\d+", text.replace(",", ""))
return float(bool(numbers) and int(numbers[-1]) == a * b)
prompts = [prompt(a, b) for a, b in problems]
longest = max(len(tokens) for tokens in prompts) + MAX_TOKENS
a, b = problems[0]
print(f"{len(problems)} problems, such as {a} × {b} = {a * b}; at most {longest} tokens each")
8 problems, such as 964 × 494 = 476216; at most 94 tokens each
The run and its sampler
TrainingConfig sets up the training run, with the model, the LoRA, and the AdamW optimizer at LEARNING_RATE. tokens_per_step is set large enough to hold one whole round, which is every answer together with its prompt.
A training run only trains. For the model to write answers with the weights it's training, the run needs its own sampler, which you'll create from the training client in the cell under Train. Its sizes are the longest sequence it takes, and how many answers it writes at once.
The sampler has no weights until the run first publishes them, so each round starts by publishing.
params sets how answers are sampled. RL samples at temperature 1.0, so the answers vary and the model can learn from the differences.
In the code below:
tokens_per_stepis the number of answers in a round,PROBLEMS * GROUP_SIZE, times the longest any one can be. So a whole round always fits in one step.max_seq_len=longestis the longest sequence the run takes.AdamW(...)is the optimizer.betassets how much it averages over earlier steps, and(0.9, 0.95)is a common choice for language models.max_grad_norm=1.0scales the gradients down when they're large, so no single step changes the weights too much.
config = ServiceClient.Config(
base_url=BASE_URL, project=PROJECT, api_key=API_KEY, display_name="first-rl"
)
training = TrainingConfig(
model=MODEL,
kind=Lora(rank=LORA_RANK),
tokens_per_step=PROBLEMS * GROUP_SIZE * longest,
max_seq_len=longest,
optimizer=AdamW(learning_rate=LEARNING_RATE, betas=(0.9, 0.95), max_grad_norm=1.0),
)
params = SamplingParams(
max_tokens=MAX_TOKENS, temperature=1.0, stop_token_ids=(tokenizer.eos_token_id,)
)
One round
The one_round function below runs one round of RL, in four parts:
-
Publish.
publish_weights()sends the run's latest weights to its sampler. Its result gives the version the sampler now has, which is the run's step number. -
Sample.
sample(prompt, n=GROUP_SIZE)asks for a group of answers to one problem. The requests for every problem are sent before waiting for any result, so the sampler works on them all at once. Each answer records which version of the weights wrote it. -
Score. The
rewardfunction scores each answer. -
Train. Each answer becomes a
Datum:- the prompt, with weight 0, as context;
- the answer's tokens, with weight 1, and the log-probabilities they were sampled with, in the
logprobscolumn; - its reward, and a
group_idshared by every answer to the same problem.
Grpois the RL loss. For each answer, it compares its reward with the rest of its group. Answers that scored above the group's average are made more likely, and those below are made less likely.optim_stepthen applies the update.
If every answer in a group gets the same score, all right or all wrong, there's nothing to compare, and that group trains nothing. So each round also prints how many groups had answers with different scores.
In the code below:
groupis the list of rewards for one problem's answers.varied += len(set(group)) > 1counts the problem if its answers didn't all get the same score.- The
logprobscolumn has one number per token, like the weights. The prompt's tokens get 0.0, since they aren't trained, and the answer's tokens get the log-probabilities the sampler recorded.Grpouses them to see how much the model has changed since it wrote the answer. group_idandgroup_sizetell the trainer which answers belong together, and how many there are. The trainer checks that each group arrives whole.versionscollects which weights wrote the round's answers. It should hold one step, the one just published.
async def one_round(training_client, sampler):
published = await (await training_client.publish_weights()).result(timeout_s=300)
# Submit every problem's group, then wait for all of them.
requests = await asyncio.gather(
*(sampler.sample(tokens, params=params, n=GROUP_SIZE) for tokens in prompts)
)
results = await asyncio.gather(*(request.result(timeout_s=300) for request in requests))
data, rewards, varied = [], [], 0
for index, ((a, b), tokens, result) in enumerate(zip(problems, prompts, results, strict=True)):
group = [reward(sequence, a, b) for sequence in result.sequences]
rewards += group
varied += len(set(group)) > 1
for sequence, score in zip(result.sequences, group, strict=True):
answer = list(sequence.token_ids)
data.append(
Datum(
tokens=[*tokens, *answer],
weights=[0] * len(tokens) + [1] * len(answer),
columns={"logprobs": [0.0] * len(tokens) + list(sequence.logprobs)},
reward=score,
group_id=f"problem-{index}",
group_size=len(result.sequences),
)
)
versions = sorted(
{sequence.version.step for result in results for sequence in result.sequences}
)
mean = sum(rewards) / len(rewards)
print(
f"the sampler serves step {published.version.step}; {len(rewards)} answers from step "
f"{versions}: mean reward {mean:.3f}, {varied} of {len(problems)} groups varied"
)
await training_client.forward_backward(data, Grpo())
step = await (await training_client.optim_step()).result(timeout_s=300)
print(f"trained step {step.step}")
Train
This cell starts the training run and its sampler, then runs the rounds, all in one session. Starting them can take a few minutes, while Looper finds GPUs and loads the model. When the async with block ends, the session closes, which shuts down the run and its sampler, even if a call fails.
In the code below, the sampler is created from the training client, rather than from service, so it's connected to the run and gets its weights when they're published. max_concurrent_sequences=PROBLEMS * GROUP_SIZE lets it write every answer in a round at once.
With only eight problems, the mean reward jumps around a lot from round to round. What matters here is the loop itself, where each round samples from the weights the round before it trained.
async def train():
async with await config.build() as service:
print("Starting the run and its sampler; this can take several minutes...")
training_client = await service.create_training_client(training, timeout_s=20 * 60)
sampler = await training_client.create_sampling_client(
max_seq_len=longest, max_concurrent_sequences=PROBLEMS * GROUP_SIZE, timeout_s=20 * 60
)
for _ in range(ROUNDS):
await one_round(training_client, sampler)
await train()
Starting the run and its sampler; this can take several minutes...
the sampler serves step 0; 64 answers from step [0]: mean reward 0.984, 1 of 8 groups varied
trained step 1
the sampler serves step 1; 64 answers from step [1]: mean reward 0.938, 1 of 8 groups varied
trained step 2
the sampler serves step 2; 64 answers from step [2]: mean reward 0.984, 1 of 8 groups varied
trained step 3
the sampler serves step 3; 64 answers from step [3]: mean reward 1.000, 0 of 8 groups varied
trained step 4
What the rounds show
Qwen3.5-9B can already multiply three-digit numbers. Nearly every answer is right, so at most one group per round has answers with different scores, and the model learns very little. The mean reward moves by chance, not because the model is learning.
This is worth remembering for your own tasks. Grpo only learns from problems where the model sometimes gets it right and sometimes doesn't. If the model always solves a problem, or always fails it, every answer in its group scores the same, and nothing trains. So pick problems the model gets right about half the time. While training, watch how many groups have different scores, as well as the mean reward.
Next steps
The run and its sampler shut down with the session, and nothing was saved. Your first fine-tune shows how to save a run's weights and sample them later.
- The RL loop runs these same rounds with the cookbook's RL loop,
train_rl.train, on grade-school math problems. - Operations shows how to send steps ahead, so the GPUs never wait for your program.