In this tutorial you'll fine-tune a model for the first time. You'll train Qwen/Qwen3.5-9B on eight short questions and answers, save the result, and then sample the trained model to see what it learned.
This is supervised fine-tuning (SFT): you show the model example answers, and it learns to write answers like them. The tutorial uses the SDK alone, one call at a time, so you can see every step. How training works explains the ideas behind it.
You need a Looper API key and a project, as in Hello Looper. Put your API key in the settings cell's API_KEY.
Install the SDK and tokenizer
As before, transformers is only used for its tokenizer. No model weights are downloaded to your machine. If the install upgrades a package you had already imported, restart the kernel and run the notebook again.
%pip install -q "goaly-looper==0.1.0b6" "transformers==5.19.0"
Settings
The first five settings are the same as in Hello Looper. The last three set the size of the training run:
LORA_RANK: the size of the LoRA. LoRA trains a small set of extra weights on top of the model, instead of changing every weight, which is much cheaper. A higher rank means more extra weights to train.STEPS: how many training steps to run.MAX_SEQ_LEN: the longest example the run can train on, in tokens.
MODEL = "Qwen/Qwen3.5-9B"
TOKENIZER = "Qwen/Qwen3.5-9B"
BASE_URL = "https://api.looper.goaly.ai"
PROJECT = "example"
API_KEY = "YOUR_API_KEY"
LORA_RANK = 32
STEPS = 10
MAX_SEQ_LEN = 512
Connect to Looper
This cell imports what the notebook uses and sets the session's settings, which say where Looper is and which project to use. Nothing is sent to Looper yet. The session opens later, when the config is built.
The new imports from the SDK are:
Datum, one training example;CrossEntropy, the loss used for SFT;LoraandTrainingConfig, which describe the training run;StateCheckpoint, the kind of checkpoint this notebook saves.
uuid4 makes random ids, which the notebook uses to give the checkpoint a name no one else is using.
import asyncio
from uuid import uuid4
from transformers import AutoTokenizer
from looper_sdk import (
CrossEntropy,
Datum,
Lora,
SamplerConfig,
SamplingParams,
ServiceClient,
StateCheckpoint,
TrainingConfig,
)
service_config = ServiceClient.Config(
base_url=BASE_URL, project=PROJECT, api_key=API_KEY, display_name="first-sft"
)
print(f"Model: {MODEL}; LoRA rank: {LORA_RANK}")
Model: Qwen/Qwen3.5-9B; LoRA rank: 32
Turn the examples into training data
Looper trains on token ids, not text, so each question-and-answer pair is turned into tokens. The question comes first as the prompt, then the answer, then the tokenizer's end token, which teaches the model to stop.
Each example becomes a Datum, which holds the tokens plus one weight per token that says whether to train on it.
- The prompt tokens get weight 0. They're only there as context, so the model isn't trained to write questions.
- The answer tokens and the end token get weight 1. These are what the model learns to write.
You pass the whole sequence as it is. Looper trains the model to predict each token from the ones before it, so you don't need to shift anything yourself.
The prompts use the same Question: ... Answer: format as Hello Looper, and sampling will use it too.
In the code below:
f" {answer}"starts the answer with a space, since in the text it followsAnswer:with a space between them.reply.append(tokenizer.eos_token_id)adds the end token after the answer.(0,) * len(prompt) + (1,) * len(reply)makes the weights, one 0 for each prompt token and one 1 for each answer token, so there's one weight per token.batch_tokenscounts the tokens in all eight examples. The next cell uses it to size the run.
tokenizer = AutoTokenizer.from_pretrained(TOKENIZER)
PAIRS = [
("What is the capital of France?", "Paris."),
("What is two plus three?", "Five."),
("What color is a clear daytime sky?", "Blue."),
("How many legs does a spider have?", "Eight."),
("What is the opposite of hot?", "Cold."),
("Which planet do we live on?", "Earth."),
("What do bees make?", "Honey."),
("How many days are in a week?", "Seven."),
]
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)
data.append(Datum(tokens=(*prompt, *reply), weights=(0,) * len(prompt) + (1,) * len(reply)))
batch_tokens = sum(len(datum.tokens) for datum in data)
print(f"{len(data)} examples, {batch_tokens} tokens per batch")
8 examples, 120 tokens per batch
Train and save the LoRA
Training happens in steps. Each step has two calls:
forward_backwardruns the model on the examples and works out how to change the weights (the gradients).optim_stepapplies those changes to the weights.
After each step, the cell prints the loss, which measures how far the model's predictions are from your answers, averaged over the tokens with weight 1. It should fall as the model learns these answers. Since the model trains on the same eight examples every step, a falling loss only shows it's learning these examples, not that it will answer new questions well.
Starting the training run can take a few minutes, while Looper finds GPUs and loads the model.
After the last step, the cell saves a checkpoint, which is a copy of the trained weights, stored under a name in your project. Saving takes two waits:
save_state(...)'s result returns once the checkpoint is written on the run's own disk.wait_checkpointreturns once it's uploaded to storage, which a sampler needs before it can load it. If you were only going to keep training, you could skip this wait.
As in Hello Looper, everything runs inside async with, so the session closes and its GPUs are released even if a call fails.
In the code below:
TrainingConfigdescribes the run.kind=Lora(rank=LORA_RANK)makes it a LoRA run.tokens_per_stepis how many tokens one step trains, which Looper uses to choose the run's GPUs. It's set big enough for the whole batch, and never smaller thanmax_seq_len, which the SDK requires.create_training_clientstarts the run, and returns a training client, which is how you send it calls.forward_backward(data, CrossEntropy())sends the batch with the SFT loss. The loop doesn't wait for its result, because Looper runs a run's calls in order. Once theoptim_stepafter it has a result, theforward_backwardhas run too.step.loss_sum / step.weighted_targetsturns the step's total loss into the average loss per trained token.step.grad_normis the size of the gradients before the update. A sudden jump can be a sign that training has gone wrong.await (await training_client.save_state(name)).result(...)is the save's two awaits written on one line. The innerawaitsends the save, and the outer one waits for its result.
async def train_and_save() -> StateCheckpoint:
training_config = TrainingConfig(
model=MODEL,
kind=Lora(rank=LORA_RANK),
tokens_per_step=max(1024, MAX_SEQ_LEN, batch_tokens),
max_seq_len=MAX_SEQ_LEN,
)
async with await service_config.build() as service:
print("Starting the training run; GPU allocation and model loading can take minutes...")
training_client = await service.create_training_client(training_config, timeout_s=20 * 60)
print("Trainer is ready!")
for _ in range(STEPS):
# Accumulate this batch's gradients.
await training_client.forward_backward(data, CrossEntropy())
# Apply them, and wait for the step's result.
update = await training_client.optim_step()
step = await update.result(timeout_s=300)
loss = step.loss_sum / step.weighted_targets
print(f"Step {step.step:2d}: loss={loss:.4f}, grad_norm={step.grad_norm:.3f}")
# A name belongs to the project, so a random one avoids conflicts.
name = f"first-sft-{uuid4().hex[:8]}"
saved = await (await training_client.save_state(name)).result(timeout_s=300)
ready = await service.wait_checkpoint(saved.id, timeout_s=15 * 60)
print(f"checkpoint {name!r}: {ready.state.value}, {ready.size_bytes} bytes")
return saved
# Clear an earlier result, so a failed rerun cannot silently sample an older checkpoint.
checkpoint = None
checkpoint = await train_and_save()
print("Training session closed. Keep this checkpoint name:", checkpoint.name)
Starting the training run; GPU allocation and model loading can take minutes...
Trainer is ready!
Step 1: loss=3.1632, grad_norm=12.504
Step 2: loss=1.3143, grad_norm=9.061
Step 3: loss=0.8945, grad_norm=6.799
Step 4: loss=0.0185, grad_norm=0.233
Step 5: loss=0.0048, grad_norm=0.074
Step 6: loss=0.0040, grad_norm=0.087
Step 7: loss=0.0088, grad_norm=0.331
Step 8: loss=0.0046, grad_norm=0.154
Step 9: loss=0.0032, grad_norm=0.114
Step 10: loss=0.0022, grad_norm=0.087
checkpoint 'first-sft-3aa901d7': ready_to_use, 1137259483 bytes
Training session closed. Keep this checkpoint name: first-sft-3aa901d7
Sample the trained model
Now try the model you trained. This cell opens a new session and starts a sampler with the checkpoint's name, instead of base:<model>. Looper loads the base model with your trained LoRA on top. Starting it can take a few minutes.
The questions are taken from the training examples, so you can see the model give the answers it was trained on. To test whether it learned something general, you'd ask questions it hasn't seen.
The cell sends all four questions before waiting for any answer, so the sampler works on them at the same time. As before, the sampler is stopped and the session closed at the end, even if a request fails.
In the code below, the first asyncio.gather sends every request and collects their operations. The second waits for all their results. zip(QUESTIONS, results, strict=True) then pairs each question with its result, and raises an error if the counts don't match.
QUESTIONS = [question for question, _ in PAIRS[:4]]
async def sample_checkpoint(name: str):
params = SamplingParams(
max_tokens=64,
temperature=0.7,
stop_token_ids=(tokenizer.eos_token_id,),
)
sampler_config = SamplerConfig(
checkpoint_name=name,
max_seq_len=MAX_SEQ_LEN,
max_concurrent_sequences=8,
)
prompts = [prompt_tokens(question) for question in QUESTIONS]
async with await service_config.build() as service:
print(f"Starting a sampler of trained checkpoint {name!r}...")
sampler = await service.create_sampling_client(sampler_config, timeout_s=20 * 60)
try:
# Submit every request, then wait for all the results.
requests = await asyncio.gather(
*(sampler.sample(prompt, params=params) for prompt in prompts)
)
results = await asyncio.gather(*(op.result(timeout_s=300) for op in requests))
for question, result in zip(QUESTIONS, results, strict=True):
print(f"\n{question}")
for sequence in result.sequences:
answer = tokenizer.decode(sequence.token_ids, skip_special_tokens=True)
print(f" {answer.strip()!r} (finish: {sequence.finish_reason.value})")
return results
finally:
await sampler.stop()
sample_results = await sample_checkpoint(checkpoint.name)
Starting a sampler of trained checkpoint 'first-sft-3aa901d7'...
What is the capital of France?
'Paris.' (finish: stop)
What is two plus three?
'Five.' (finish: stop)
What color is a clear daytime sky?
'Blue.' (finish: stop)
How many legs does a spider have?
'Eight.' (finish: stop)
Next steps
The checkpoint stays in your project under its name until you delete it. See Checkpoint.
- Operations shows how to send steps ahead, so the GPUs never wait for your program.
- Chat data turns conversations into training data in the model's own chat format.
- The SFT loop trains on a file of conversations with the cookbook's SFT loop.