Looper Documentation
Looper Cookbook

Your first fine-tune

Open in Colab

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:

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:

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.

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:

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:

  1. forward_backward runs the model on the examples and works out how to change the weights (the gradients).
  2. optim_step applies 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:

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:

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.