Looper Documentation
Looper Cookbook

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 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:

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:

  1. 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.
  2. It asks Looper to start the run with create_training_client, and waits until the run is ready. timeout_s=20 * 60 gives 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:

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

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:

  1. forward_backward runs 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.
  2. optim_step updates 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:

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:

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:

  1. Start a sampler for the run, and publish the run's weights to it.
  2. Generate several answers to a prompt.
  3. Score each answer, and turn it into a Datum with its reward.
  4. 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:

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:

  1. await training_client.forward_backward(...) returns an Operation as soon as Looper accepts the call and adds it to the run's queue.
  2. 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)

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:

Operations that finished before the rollback still return their results.

The error tells you:

What happens next:

Read and delete a run

You can see each run's metrics on the Runs page of the portal.