Looper Documentation
Looper Cookbook

Sampling

A sampler is a model running on Looper's GPUs, ready to generate text. You send it a prompt, and it writes one or more answers. You don't need to train anything to use one.

You can start a sampler from:

A sampler keeps running until you stop it or close your session, so you can send it as many prompts as you like.

This page covers:

The code on this page assumes you've already connected to Looper and have a service to work with. See Open a session.

The cookbook or your own code

During training, the cookbook can do the sampling for you. Its RL loops, train_rl and train_rl_async, send the prompts, collect the answers, track which weights wrote each one and handle publishing. Its evaluation runs held-out tasks on a sampler and reports their scores. You still create the sampler yourself.

Let the cookbook sample when you're training with its RL loops, or measuring a model on held-out tasks.

Sample with the calls on this page when you want direct control. For example:

What you build explains what the cookbook does and doesn't do.

Create a sampling client

A sampling client is your connection to one sampler on Looper. When you create it, Looper reserves GPUs for the sampler and loads the model onto them.

Each sampler generates text from one source, which you choose when you create it and can't change later:

Source What it is checkpoint_name Create it with
A base model The model as it was before any training base:<model>, such as base:Qwen/Qwen3.5-9B service.create_sampling_client
A checkpoint A model your project saved The checkpoint's name service.create_sampling_client
A training run The model a run is training right now Filled in for you training_client.create_sampling_client

You also choose two sizes, which can't be changed later either:

Each model only supports certain sizes. Available models lists them.

The code below starts a sampler of the base Qwen/Qwen3.5-9B model that handles up to 4,096 tokens per request and writes up to 16 answers at once. timeout_s=20 * 60 gives up after 20 minutes.

from looper_sdk import SamplerConfig

sampler_config = SamplerConfig(
    checkpoint_name="base:Qwen/Qwen3.5-9B", max_seq_len=4096, max_concurrent_sequences=16
)
sampling_client = await service.create_sampling_client(sampler_config, timeout_s=20 * 60)

create_sampling_client returns once the sampler is ready, which can take a few minutes while the model loads.

If you use a checkpoint, the sampler loads the checkpoint with that name at the moment you create it. If you later save a new checkpoint under the same name, this sampler keeps using the old one.

If creation fails

If Looper can't start the sampler, you get a CreationError. Its .cause tells you why:

Timeouts and retries covers CreationTimeout, and how to try again safely.

Generate answers

Looper works with token ids, not text, so you turn your prompt into tokens on your own machine before sending it. Use the model's chat template, so the prompt is in the format the model was trained on.

SamplingParams sets how the answers are written:

Setting Default What it does
max_tokens Required The longest an answer can be, in tokens
temperature 1.0 How random the answers are. 0 always gives the most likely answer
top_p 1.0 Leaves out the least likely tokens. 1 leaves out none
stop_token_ids () Tokens that end an answer, such as the end-of-text token

sample also takes n, the number of answers to write for the prompt, which is 1 by default.

What the settings mean

A model writes an answer one token at a time. A token is a word or a piece of a word. For each token, the model gives every possible next token a probability, such as 70% for "84", 20% for "eighty" and smaller chances for the rest. The sampler then picks one, adds it to the answer, and repeats. The settings change how it picks, and when it stops.

For RL, keep temperature and top_p at 1. RL learns by comparing several answers to the same prompt, so it needs them to vary. Also, each answer records how likely each of its tokens was, and the RL loss treats those numbers as the model's own probabilities. Any other temperature or top_p changes them, so the loss would be wrong. The cookbook's RL loops refuse other values for this reason.

The code below turns a question into tokens, asks the sampler for 4 answers, and prints them:

from transformers import AutoTokenizer

from looper_sdk import SamplingParams

tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen3.5-9B")


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"]


params = SamplingParams(max_tokens=256, temperature=0.7, stop_token_ids=(tokenizer.eos_token_id,))
operation = await sampling_client.sample(chat_prompt("What is 12 times 7?"), params=params, n=4)
result = await operation.result(timeout_s=600)
for sequence in result.sequences:
    print(tokenizer.decode(sequence.token_ids, skip_special_tokens=True))

Like the training calls, sample is awaited twice. await sampling_client.sample(...) returns an operation as soon as Looper accepts the request. await operation.result() waits for the answers.

Send many prompts at once

A sampler works on many requests at the same time, and they can finish in any order. To send several prompts without waiting for each one, use asyncio.gather. It returns the results in the order you sent the prompts:

import asyncio

questions = ["What is 12 times 7?", "What is 9 plus 4?"]
operations = await asyncio.gather(
    *(sampling_client.sample(chat_prompt(q), params=params) for q in questions)
)
results = await asyncio.gather(*(op.result(timeout_s=600) for op in operations))

Read results

result() returns a SampleResult. Its sequences list has one entry per answer, each a SampleSequence with these fields:

Field What it holds
token_ids The answer's tokens. The prompt isn't included
logprobs How likely each token of the answer was, as a log probability. RL uses these when training
finish_reason Why the answer ended: FinishReason.STOP if it reached a stop token or the end of the text, or FinishReason.LENGTH if it hit max_tokens
version Which weights wrote the answer, as a Version: the run, epoch and step. None for a base model
cached_tokens How many of the prompt's tokens the sampler reused from an earlier request with the same beginning, instead of processing them again

Count tokens

Sampling is billed by tokens, in three counts. A SamplingUsage holds them:

To see the usage of one request, call await operation.usage(). It returns None until the request succeeds. To see the total for the whole sampler, use (await sampling_client.status()).usage, which adds up all of its successful requests.

Sample a run's own weights

In RL, the model being trained writes the answers it learns from. To do that, you create a sampler from the training run, and send it the run's latest weights with publish_weights. How training works explains why the two are separate.

The code below starts a sampler for the run, publishes the run's weights to it, and asks for 8 answers. Sampling sizes lists how many answers each model's sampler can write at once.

sampling_client = await training_client.create_sampling_client(
    max_seq_len=4096, max_concurrent_sequences=64, timeout_s=20 * 60
)
published = await (await training_client.publish_weights()).result(timeout_s=300)
operation = await sampling_client.sample(chat_prompt("What is 12 times 7?"), params=params, n=8)
result = await operation.result(timeout_s=600)
print(published.version.step, {sequence.version.step for sequence in result.sequences})

The last line prints the step of the weights you published, and the steps of the weights that wrote the answers.

If you use the cookbook's RL loops, you don't need to manage any of this. train_rl and train_rl_async publish the weights, decide when to sample, and keep track of which weights wrote each answer for you.

If you write your own RL loop with the SDK, keep these in mind:

Train on rewards shows how to turn the answers into training data.

Errors, timeouts and stopping

Errors before a request is sent

sample() checks each request before sending it. If the sampler could never handle it, sample() raises InvalidArgument (a kind of ValueError) and sends nothing. That happens when:

Errors after a request is accepted

Once Looper has accepted a request, result() can raise:

Error What happened What to do
QueueTimeout The request waited 15 minutes for its turn and never started Send it again
SamplerFailed The sampler stopped working for good: it stopped responding, or its training run lost its GPUs Create a new sampler
Cancelled The sampler was stopped before the request finished Send it to a sampler that's running
ResultExpired The sampler has shut down, and its results have been deleted usage() still works

Some errors are temporary, and are marked retryable. For those, result() sends the request again by itself, up to 3 tries in total. You can change this with sample()'s max_attempts. Each try is a new request, so if the run published in between, it may be written by newer weights. All other errors are raised straight away.

Timeouts

A timeout_s on result() only limits how long you wait. When it runs out, you get a TimeoutError, but the request keeps running, and you can call result() again to keep waiting.

Stopping a sampler

await sampling_client.stop() shuts the sampler down and frees its GPUs. Requests that haven't finished are cancelled. Results that already finished can still be read for a while, until Looper cleans up the stopped sampler. After that, result() raises ResultExpired.

Closing your session stops every sampler it created.