Looper runs the GPU work of training and sampling a language model. Your own program decides what to train on and when. Looper does the heavy computation on its GPUs and sends the results back.
In this tutorial you'll connect to Looper, start a base model, and read what it writes for a question. Nothing is trained yet. That comes in Your first fine-tune.
Here's how the work is split. Your program turns text into token ids (numbers the model reads) and sends them to Looper. Looper runs the model and sends back token ids, which your program turns back into text:
Your program Looper
tokenizer, data, loop ------> GPUs: forward_backward, optim_step, sample
token ids <------ losses, metrics, sampled token ids
You need:
- Python 3.12 or newer.
- A Looper API key. Create one under API Keys in the portal's left navigation. You'll paste it into the settings cell below. Don't share or commit the notebook with your key in it.
- A project the key can use. A project is just a name you choose. Everything you save is kept under it.
Install the SDK
The SDK, goaly-looper, is the Python package that talks to Looper. The cell below also installs transformers, but only for its tokenizer. Looper takes token ids, not text, so your program does the converting. No model weights are downloaded to your machine.
If the install upgrades a package you had already imported, restart the kernel before you go on.
%pip install -q "goaly-looper==0.1.0b6" "transformers==5.19.0"
Settings
The cell below holds this notebook's settings:
MODEL: the model to sample.TOKENIZER: where to load its tokenizer from on the Hugging Face Hub.BASE_URL: Looper's address.PROJECT: your project's name.API_KEY: your key. ReplaceYOUR_API_KEYwith it, or setAPI_KEY = Noneto have the SDK read it from theLOOPER_API_KEYenvironment variable.
MODEL = "Qwen/Qwen3.5-9B"
TOKENIZER = "Qwen/Qwen3.5-9B"
BASE_URL = "https://api.looper.goaly.ai"
PROJECT = "example"
API_KEY = "YOUR_API_KEY"
Open a session
Your program connects to Looper through a session. You open one by building a ServiceClient. Anything you start, such as a model to sample, belongs to that session.
When the session closes, everything it started is shut down, and the GPUs are released. The async with below closes the session for you when the block ends, even if a cell fails, so nothing is left running by mistake.
In the code below:
ServiceClient.Configholds the session's settings, which are Looper's address, your project, your key (api_key), which the session sends with every request, anddisplay_name, a label so you can find the session in the console.config.build()opens the session. It's an async call, so youawaitit, and you use theServiceClientit returns in anasync withblock. That's why the line readsasync with await.service.session.idis the new session's id. It's printed to show the connection worked.
This cell only checks that you can connect, so its session closes as soon as the block ends. The sampling cell below opens a new session from the same config.
from looper_sdk import SamplerConfig, SamplingParams, ServiceClient
config = ServiceClient.Config(
base_url=BASE_URL, project=PROJECT, api_key=API_KEY, display_name="hello-looper"
)
async with await config.build() as service:
print("session:", service.session.id)
session: d1eba9c1-2770-4f33-bdfa-de272d5f0fc2
Turn a question into tokens
The model reads a prompt as a list of token ids. The tokenizer, running on your machine, turns text into those ids. Here the question is wrapped as Question: ...\nAnswer:, so the model continues by writing an answer.
In the code below:
AutoTokenizer.from_pretrained(TOKENIZER)downloads the model's tokenizer from the Hugging Face Hub. It's a few small files, not the model.add_special_tokens=Falsestops the tokenizer from adding special tokens of its own, so the prompt is exactly the text you wrote.prompt_tokensis a function so you can make a prompt for any question. The cell prints the token ids for one question.
from transformers import AutoTokenizer
tokenizer = AutoTokenizer.from_pretrained(TOKENIZER)
def prompt_tokens(question):
return tokenizer.encode(f"Question: {question}\nAnswer:", add_special_tokens=False)
prompt = prompt_tokens("What is the capital of France?")
print(len(prompt), "tokens:", prompt)
12 tokens: [14162, 25, 3437, 369, 279, 6511, 314, 9338, 30, 198, 15666, 25]
Start a sampler and sample
A sampler is a copy of a model running on Looper's GPUs, ready to write text. Each sampler runs one set of weights. base:<model> starts one with a model's original weights. Later, you'll start one with the name of a checkpoint you trained instead.
Two sizes are set when the sampler starts, and can't be changed afterwards:
max_seq_len: the most tokens a single sample can use, counting the prompt and what the model writes.max_concurrent_sequences: how many answers the sampler can write at once. A request fornanswers usesnof them.
The first time, starting a sampler takes a few minutes, while Looper finds GPUs and loads the model.
Sampling takes two awaits:
await sampler.sample(...)sends the request, and returns an operation once Looper has accepted it.await operation.result()waits for the model to finish, and returns what it wrote.
Operations shows why it's split in two.
The cell below asks for one answer, then for three answers to the same prompt in one request, and stops the sampler at the end. In the code:
SamplingParamssets how each answer is written.max_tokens=48is the longest answer, in tokens.temperature=0.7sets how much randomness goes into picking each token, where 0 always picks the most likely one.stop_token_idsends an answer when the model writes the tokenizer's end token.SamplerConfigsays which weights to run, herebase:and the model's name, and the two sizes above.timeout_s=20 * 60letscreate_sampling_clientwait up to 20 minutes for the sampler to start, andtimeout_s=300lets each result take up to 5 minutes. If the time runs out, you get aTimeoutError.n=3asks for three answers in one request.tryandfinallymake suresampler.stop()runs even if a request fails. Closing the session would stop the sampler too, but stopping it yourself releases its GPUs as soon as you're done with it.result.checkpoint_namesays which weights wrote the answers.
params = SamplingParams(max_tokens=48, temperature=0.7, stop_token_ids=(tokenizer.eos_token_id,))
sampler_config = SamplerConfig(
checkpoint_name=f"base:{MODEL}", max_seq_len=1024, max_concurrent_sequences=4
)
async with await config.build() as service:
print("starting the sampler...")
sampler = await service.create_sampling_client(sampler_config, timeout_s=20 * 60)
try:
operation = await sampler.sample(prompt, params=params)
result = await operation.result(timeout_s=300)
# Three completions of the same prompt, in one request.
operation = await sampler.sample(prompt, params=params, n=3)
several = await operation.result(timeout_s=300)
finally:
await sampler.stop()
print("sampled from:", result.checkpoint_name)
starting the sampler...
sampled from: base:Qwen/Qwen3.5-9B
Read the result
A result holds one sequence for each answer the model wrote. Each sequence has:
token_ids: the answer, as token ids. The cell below turns them back into text.logprobs: how likely the model thought each token was, as a log-probability. Closer to 0 means more confident.finish_reason: why the answer ended.stopmeans the model finished, or wrote a stop token.lengthmeans it ran out of room atmax_tokens.
In the code below, [sequence] = result.sequences takes the one sequence out of the result, and raises an error if there isn't exactly one. skip_special_tokens=True leaves special tokens, such as the end token, out of the text. The last two lines average the log-probabilities, as a rough measure of how sure the model was overall.
[sequence] = result.sequences
print(repr(tokenizer.decode(sequence.token_ids, skip_special_tokens=True)))
print("finish reason:", sequence.finish_reason.value)
mean = sum(sequence.logprobs) / len(sequence.logprobs)
print(f"{len(sequence.token_ids)} tokens, mean log-probability {mean:.2f}")
'\n\nParis.'
finish reason: stop
4 tokens, mean log-probability -0.71
The second request asked for three answers to the same question. They come out different, because at temperature 0.7 the model picks each token with some randomness.
for sequence in several.sequences:
text = tokenizer.decode(sequence.token_ids, skip_special_tokens=True)
print(f"{sequence.finish_reason.value}: {text!r}")
length: ' The capital of France is Paris.\n\nQuestion: Why is the sky blue?\nAnswer: The sky is blue because of a phenomenon called Rayleigh scattering.\n\nQuestion: How many days are in a week?\nAnswer: There are'
stop: '\n\nParis'
length: ' Paris\n\nQuestion: What is the capital of Germany?\nAnswer:\n\nBerlin\n\n(Note: I answered in lowercase "paris" in the first example, but I will capitalize the answer here to follow standard English grammar rules for cities and'
Next steps
These answers show how the base model behaves before any training. Both sessions are closed now, so nothing is left running.
- Your first fine-tune trains the model on answers in this
Question: ... Answer:format, then samples it again. - Operations explains the two awaits, and how to keep the GPUs busy.