Training
On this page you will learn how to create a training run, turn your data into the right format, and run the training through Looper. As stated in previous sections, Looper handles the infrastructure part of training. What the model is trained on and how comes from you.
This page covers:
- The cookbook or your own loop: when to let the cookbook run training for you, and when to write your own loop.
- Create a training client: start a training run and choose its model and settings.
- Prepare data: turn your examples into tokens and weights that Looper can train on.
- Run optimizer steps: train the model step by step, and read the loss.
- Set the learning rate: change the learning rate during training, for example to decay it.
- Choose a loss: pick between supervised fine-tuning and reinforcement learning.
- Train on rewards: generate answers, score them, and train on the scores.
- Submit ahead: queue steps so the GPUs never wait, and resend failed calls safely.
- When a run rolls back: what happens if a run loses its GPUs, and what to do.
- Read and delete a run: check a run's progress, and shut it down.
The code on this page assumes you've already connected to Looper and have a service to work with:
config = ServiceClient.Config(project="my-project")
async with await config.build() as service:
...
See Open a session for details.
The cookbook or your own loop
The cookbook's training loops can make most of the calls on this page for you. train_sft runs supervised fine-tuning, and train_rl and train_rl_async run RL. They prepare the data, run the optimizer steps, publish the weights and, for async RL, keep the trainer and sampler busy. You still create the training client, provide your data and, for RL, choose how answers are scored.
Use the cookbook's loops when your training follows their pattern: SFT on conversations, or RL on tasks where each answer is scored on its own. You write less code, and the details on this page, such as groups, publishing and queuing steps ahead, are handled for you.
Write your own loop with the calls on this page when your training needs something the loops don't do. For example:
- You want to alternate between SFT and RL steps as training goes. The loops do one kind of training each, though you can run one after the other on the same run.
- An answer's reward depends on the other answers to the same prompt, for example when a judge model picks the best of the group. The cookbook's verifiers score each answer on its own. (Comparing rewards within a group, as
Grpodoes when it works out each answer's advantage, is separate, and the cookbook handles it.) - You want a learning-rate schedule for RL. The RL loops train at the run's fixed rate. (
train_sfthas schedules built in.) - You want your own rules for which answers to train on, or when to publish. The RL loops train every group they collect, and publish after every step.
A middle option is to copy one of the cookbook's loops and change it. What you build compares all three.
Even if you use the cookbook, this page is worth reading. It explains what the loops do for you, which helps when something goes wrong.
Create a training client
A training client is your connection to one training run on Looper. When you create it, Looper reserves GPUs for the run and loads the model onto them. After that, every training call goes through it: forward_backward, optim_step, saves, and starting a sampler of the run's weights.
The code below does two things:
- It describes the run in a
TrainingConfig: which model to train, whether to train a LoRA adapter or all of the model's weights, the longest example you'll train on, how many tokens each step trains on, and the optimizer settings. The table after the code explains each setting. - It asks Looper to start the run with
create_training_client, and waits until the run is ready.timeout_s=20 * 60gives up after 20 minutes.
from looper_sdk import AdamW, Lora, TrainingConfig
config = TrainingConfig(
model="Qwen/Qwen3.5-9B",
kind=Lora(rank=32),
max_seq_len=1024,
tokens_per_step=16_384,
optimizer=AdamW(learning_rate=1e-4, max_grad_norm=1.0),
)
training_client = await service.create_training_client(config, timeout_s=20 * 60)
| Field | What it sets |
|---|---|
model |
A model of Available models, by its Hugging Face name |
kind |
Lora(rank=...) over the frozen base, or Full() for every parameter |
max_seq_len |
The longest sequence the run trains. The number of GPUs will be influenced based on this. |
tokens_per_step |
The tokens a step trains, at least max_seq_len. A larger batch still trains. |
optimizer |
AdamW(...), or None for the model's default (Optimizers) |
All of them are fixed for the run's life. Creation returns once the run's GPUs are ready and the model is loaded, which can take minutes. timeout_s bounds the whole wait; by default there is none.
A creation that times out raises CreationTimeout, and one the service refuses raises CreationError, whose .cause names a length, rank or optimizer the model does not offer (Available models). Timeouts and retries says how to call again safely.
Closing the session, as leaving async with does, ends its runs and releases their GPUs, also when your program fails.
Prepare data
Looper trains on token ids, not text, so you turn each training example into a Datum before sending it. A Datum holds two lists of the same length:
tokens: the example's token ids, with the prompt and answer together.weights: one number per token.1means "train the model to produce this token."0means "use this token only as context." Usually the prompt gets0and the answer gets1.
The code below turns question-and-answer pairs into datums. The question's tokens get weight 0. The answer, plus an end-of-sequence token after it, gets weight 1, so the model learns to give the answer and then stop.
from transformers import AutoTokenizer
from looper_sdk import Datum
tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen3.5-9B")
PAIRS = [
("What is the capital of France?", "Paris."),
("How many legs does a spider have?", "Eight."),
]
def prompt_tokens(question):
return tokenizer.encode(f"Question: {question}\nAnswer:", add_special_tokens=False)
data = []
for question, answer in PAIRS:
prompt = prompt_tokens(question)
reply = tokenizer.encode(f" {answer}", add_special_tokens=False)
reply.append(tokenizer.eos_token_id) # teaches the model to stop after the answer
data.append(
Datum(
tokens=(*prompt, *reply),
weights=(0,) * len(prompt) + (1,) * len(reply), # learn the reply only
)
)
Rules for a datum
- The first weight must be 0, because no token comes before it to predict it from. At least one other weight must be 1.
- Don't shift the tokens. Some training libraries ask you to pass the labels shifted by one position. Looper does that itself, so pass the same token list for both.
- Keep each datum within the run's
max_seq_len. A longer one makes itsforward_backwardcall fail. - Invalid tokens or weights raise an error right away. You get
InvalidArgument(a kind ofValueError) as soon as you create theDatum, not later when you send it.
Size limit per call
One forward_backward call can send at most 16 MiB, which is about 2.4 million tokens. Each token takes about 7 bytes, or 11 bytes if the datum has a logprobs column. A call can also include at most 8,000,000 tokens with weight 1. A bigger call raises PayloadTooLarge.
To train one step on more data than that, split it across several forward_backward calls, then call optim_step once. The gradients from all the calls add up.
Chat data
If your data is conversations, you don't need to build the tokens and weights by hand. The cookbook's message formatters put each conversation into the model's chat format and set the weights for you. The Chat data tutorial walks through it.
Run optimizer steps
Training happens in steps. Each step has two parts:
forward_backwardruns your data through the model and works out how the weights should change (the gradients). It doesn't change the weights yet. You can call it more than once per step, and the gradients from each call add up.optim_stepupdates the weights using those gradients, then clears them so the next step starts fresh.
This loop trains for 10 steps on the data from Prepare data and prints the loss after each one:
from looper_sdk import CrossEntropy
for _ in range(10):
await training_client.forward_backward(data, CrossEntropy())
update = await training_client.optim_step()
step = await update.result(timeout_s=300) # wait up to 5 minutes for the step to finish
loss = step.loss_sum / step.weighted_targets
print(f"step {step.step}: loss {loss:.4f}, grad norm {step.grad_norm:.3f}")
Reading the step's result
You get the loss from optim_step's result, not from forward_backward. The result, a StepResult, adds up the loss over every token with weight 1, so to get the average loss per token you divide:
loss = step.loss_sum / step.weighted_targets
It also includes:
| Field | What it tells you |
|---|---|
step |
How many steps the run has completed, this one included |
grad_norm |
The size of the gradients, measured before clipping |
clipped |
Whether the gradients were clipped to max_grad_norm |
lr |
The learning rate this step used |
metrics |
Extra numbers reported by the loss |
version |
The version of the weights this step produced |
num_tokens |
The number of tokens you're billed for |
When a step fails
Waiting on a step's result raises an error if the step couldn't train:
EmptyStep: none of the data sent since the last step had any tokens with weight 1, so there was nothing to learn from.IncompleteAccumulation: one of theforward_backwardcalls since the last step failed. Wait on that call'sresult()to see why.
When a step fails, its gradients are thrown away, so the next step starts fresh.
Limitations
Looper can't compute a loss without also training yet, so you can't measure loss on a separate validation set. To keep what you trained, save a checkpoint: see Checkpoint.
Set the learning rate
The optimizer settings you choose when you create the run, in AdamW, can't be changed later: learning_rate, betas, eps, weight_decay and max_grad_norm. max_grad_norm is the largest the gradients can get before they're scaled down ("clipped"). Set it to None to turn clipping off.
Looper doesn't change the learning rate over time for you. If you want it to warm up or decay during training, you choose the rate for each step yourself.
To do that, pass learning_rate to optim_step. That step uses the rate you give, which must be 0 or more. Steps where you don't pass one use the learning_rate from the run's AdamW settings.
The example below lowers the rate in a straight line from PEAK_RATE to 0 over 100 steps:
PEAK_RATE, STEPS = 1e-4, 100
n = (await training_client.status()).step
while n < STEPS:
await training_client.forward_backward(data, CrossEntropy())
rate = PEAK_RATE * (1 - n / STEPS)
n = (await (await training_client.optim_step(learning_rate=rate)).result()).step
It reads the step number from the run itself (training_client.status().step) instead of counting in your program. That way, if your program restarts, it picks up the schedule where the run left off instead of starting over at the peak rate.
Runs on Looper only use AdamW: see Optimizers.
Choose a loss
The loss decides what the model learns from your data. You pass one to each forward_backward call. Looper has three:
| Loss | Use it for | Each datum needs | Settings (defaults) |
|---|---|---|---|
CrossEntropy() |
Supervised fine-tuning (SFT): teaching the model to reproduce example answers | tokens and weights |
None |
Grpo() |
Reinforcement learning (RL): the model writes several answers to a prompt, you score them, and it learns to favor the better ones | tokens, weights, reward, group_id, group_size and a logprobs column |
clip_low=0.2, clip_high=0.2, kl_weight=0.0, scale_by_std=True |
Dapo() |
RL, like Grpo, but it lets each step push further toward good answers |
The same as Grpo |
The same as Grpo, except clip_high=0.28 |
How the RL losses work:
- Answers are compared within their group. A group is the set of answers written for the same prompt. For each answer, Looper subtracts the group's average reward from the answer's reward, then divides by the group's standard deviation (set
scale_by_std=Falseto skip dividing). This is the answer's advantage. Answers better than average are reinforced and worse ones discouraged. If every answer in a group gets the same reward, the group teaches nothing. clip_lowandclip_highlimit how far one step moves the model. Each answer'slogprobsrecord how likely its tokens were when it was written. Once a token's probability has fallen below 1 −clip_lowtimes that, or risen above 1 +clip_hightimes that, the step stops pushing it further.kl_weightkeeps the model close to the sampler. Above 0, it adds a penalty for drifting away from the weights that wrote the answers. The default, 0, adds no penalty.
A datum that doesn't match its loss, such as a CrossEntropy datum with a reward, raises InvalidArgument when you send it.
Train on rewards
In RL, the run writes answers with its own current weights, you score them, and it trains on the scores. One round has four parts:
- Start a sampler for the run, and publish the run's weights to it.
- Generate several answers to a prompt.
- Score each answer, and turn it into a
Datumwith its reward. - Train on the group with
Grpo(), then publish the new weights so the next round samples from them.
The code below runs one round. It asks "What is two plus three?" eight times, and gives each answer a reward of 1 if it contains "5" and 0 if not:
from looper_sdk import Grpo, SamplingParams
sampling_client = await training_client.create_sampling_client(
max_seq_len=1024, max_concurrent_sequences=8, timeout_s=20 * 60
)
params = SamplingParams(max_tokens=64, stop_token_ids=(tokenizer.eos_token_id,))
await (await training_client.publish_weights()).result()
prompt = prompt_tokens("What is two plus three?")
result = await (await sampling_client.sample(prompt, params=params, n=8)).result()
group = []
for sequence in result.sequences:
text = tokenizer.decode(sequence.token_ids, skip_special_tokens=True)
group.append(
Datum(
tokens=(*prompt, *sequence.token_ids),
weights=(0,) * len(prompt) + (1,) * len(sequence.token_ids),
columns={"logprobs": (0.0,) * len(prompt) + tuple(sequence.logprobs)},
reward=float("5" in text),
group_id="q1",
group_size=len(result.sequences),
)
)
await training_client.forward_backward(group, Grpo())
await training_client.optim_step()
await training_client.publish_weights()
The cookbook's train_rl and train_rl_async run these rounds for you, including the publishing and the timing. If you write your own loop, keep these in mind:
- Decide whether to wait for each publish. If you wait for a publish to finish before sampling, every answer comes from the newest weights. If you don't, some answers may be written by the older weights. That's how async RL works, and the loss accounts for it: see Synchronous and asynchronous RL.
- Only publish between steps. Publishing or saving after a
forward_backwardbut before itsoptim_stepraisesGradientsPending. - Send each group whole, in one
forward_backwardcall. A group needs at least 2 datums with the samegroup_idandgroup_size. Each datum carries its ownrewardand thelogprobsit was sampled with.
To go further, Tutorial 104, your first RL run, repeats these steps over several rounds. Tutorial 302, the RL loop, trains on math problems with the cookbook's RL loop.
Submit ahead
You await each call that sends work to a run twice:
await training_client.forward_backward(...)returns anOperationas soon as Looper accepts the call and adds it to the run's queue.await operation.result()waits for the work to run and returns its output.
A run carries out its operations in the order you sent them, so you don't have to wait for one step to finish before sending the next. If you keep a few steps queued, the GPUs always have work ready, instead of sitting idle while your program waits for results.
This loop keeps up to three steps queued, and prints each step's number as it finishes:
in_flight = []
for batch in [data] * 8:
await training_client.forward_backward(batch, CrossEntropy())
in_flight.append(await training_client.optim_step())
if len(in_flight) > 2:
print((await in_flight.pop(0).result()).step)
- Keep only a few steps queued. A failed operation raises its error only when you await its result, and the operations after it still run. With many steps queued, the run keeps training past a failure before you find out about it.
- A run holds at most 64 unfinished operations. Past that, the SDK keeps resending the call until one finishes, for up to
retry_timeout_s. - To wait on another run, pass
after=[operation]. The new operation waits for that operation of another run in your session. If that operation fails, the new one fails withDependencyFailedwithout running.
Resend safely with keys
Every call that sends work carries a key, a unique ID. The SDK makes a new one for each call unless you pass key=. Looper uses the key to recognize a resent call: sending the same key again returns the operation it already accepted, instead of running the work twice. Sending the same key with different data raises IdempotencyConflict.
The SDK already resends calls that fail with a temporary error. If it gives up, Looper may still have accepted the call. Resend it with the key from the error, not a new key, or the same batch could train twice:
from looper_sdk import LooperError
try:
operation = await training_client.forward_backward(data, CrossEntropy())
except LooperError as error:
if not error.retryable:
raise
operation = await training_client.forward_backward(data, CrossEntropy(), key=error.key)
To check whether Looper accepted a call without sending it again, use await training_client.find_operation(key). It returns the operation, or None if Looper never received it.
Tutorial 103, Operations, compares how long training takes when you wait for each step and when you queue steps ahead.
When a run rolls back
If a run loses its GPUs, for example when a machine fails, Looper restores it on new ones. The restored run starts a new epoch, a new numbered phase of the run. A restore always takes the run back to step 0.
After a rollback, you get RunRolledBack when you:
- await the result of an operation the rollback lost, or
- send a call under the old epoch.
Operations that finished before the rollback still return their results.
The error tells you:
epoch: the new epoch's number.restored_step: the step the run went back to.first_lost_seqtolast_lost_seq: the range of operations that were lost.
What happens next:
- Your training client switches to the new epoch by itself. Keys start fresh in each epoch.
- You decide what to train again. Looper doesn't resend lost work. Pick up from
restored_step. - The run's sampler stops with
SamplerFailed. Create a new one once the run is active again.
Read and delete a run
- Check a run with
await training_client.status(). It returns aRunStatuswith:state: the run's state, such asactiveorrecovering.epoch: the run's current epoch.step: how many optimizer steps the run has completed.durable_step: the newest step covered by a state checkpoint or a restore point.
- Delete a run with
await training_client.delete(). It cancels the run's queued operations, lets the one already running finish, and frees the run's GPUs. - Detailed results expire. After a run ends, Looper deletes its operations' detailed results, and
result()raisesResultExpired. The run's status and per-step metrics are kept.
You can see each run's metrics on the Runs page of the portal.