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 base model, as it was published, to try it out.
- A checkpoint you saved, to see what your training changed.
- A training run, to generate answers from the model while it trains. Reinforcement learning works this way: How training works explains it.
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 cookbook or your own code: when to let the cookbook sample for you, and when to sample yourself.
- Create a sampling client: start a sampler, and choose which model it uses and how big it is.
- Generate answers: send prompts, and choose how the answers are written.
- Read results: what each answer contains.
- Count tokens: see how many tokens you used, which is what sampling is billed by.
- Sample a run's own weights: generate answers from a model while it trains, for RL.
- Errors, timeouts and stopping: what can go wrong, and how to shut a sampler down.
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:
- You want to try a model out, or compare a base model with a checkpoint, without training anything.
- You're generating text to use somewhere else, such as building a dataset.
- You're writing your own RL loop, and need to decide when to sample and which weights to use.
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:
max_seq_len: the longest prompt plus answer that one request can have, in tokens.max_concurrent_sequences: how many answers the sampler can write at the same time. A request fornanswers usesnof them.
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:
CheckpointNotReady: the checkpoint is still being uploaded or exported. Wait for it, then create the sampler again.NotFound: there's no checkpoint with that name, its save or export failed, or Looper doesn't offer that model.InvalidArgument: the model doesn't support the sizes you asked for.
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.
temperaturesets how much randomness goes into each pick.- 0 always picks the most likely token, so the same prompt gives the same answer almost every time. Use it to measure a model's best answer.
- 1 picks each token with exactly the model's own probability, so the answers vary the way the model does. RL uses this.
- Between 0 and 1, such as 0.7, the answers vary less than the model's own, but still vary. This is a common choice for trying a model out.
- Above 1, the answers vary more than the model's own, and are often worse.
top_pleaves out unlikely tokens before the pick. At 0.9, the sampler keeps only the most likely tokens whose chances add up to 90%, and picks among those. This stops a rare, odd token from being picked. At 1, the default, nothing is left out.max_tokensis the longest an answer can be. An answer that reaches it is cut off, and itsfinish_reasonislength.stop_token_idsare tokens that end the answer when the model writes one, such as the token a chat model writes at the end of its turn. Without one, the model may keep writing untilmax_tokens.nasks for several answers to the same prompt in one request. With a temperature above 0, they differ.
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:
num_prompt_tokens: the prompt's tokens. They're counted once per request, however many answers it asks for.num_generated_tokens: the tokens the sampler wrote, across all of the request's answers.num_cached_tokens: the prompt tokens the sampler reused from an earlier request instead of processing them again.
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:
- Publish before your first sample. Until the run publishes, the sampler has no weights. Calling
sample()before that raisesInvalidArgument. - 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.
- Each answer records which weights wrote it, in
version. If a publish lands while an answer is being written,versionnames the older weights. Use it to skip answers that are too old to train on. - A run can have only one sampler at a time. Stop the current one before you create another, or creation raises
CreationErrorwithInvalidArgument. If the sampler has failed or stopped, you can just create a new one.
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:
- the prompt plus
max_tokensis longer thanmax_seq_len, nis more thanmax_concurrent_sequences, or- the prompt is empty.
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.