Looper Documentation
Looper Cookbook

SFT with your own loop

This page is for running supervised fine-tuning (SFT) with your own training loop, calling the SDK directly instead of using the cookbook's train_sft. If the cookbook's loop fits what you're doing, Supervised learning is simpler. The cookbook or your own loop explains when you'd write your own.

This page covers:

Before you start, set up the SDK and your API key, as in Quickstart. Training explains every call used here, with all its options.

A complete example

This script fine-tunes the model with supervised fine-tuning (SFT), where you show the model example answers and it learns to write answers like them. The examples are four short questions, each with a one-word answer. After training, the model should answer a new question in the same short style.

It trains a LoRA. Instead of changing all the model's weights, a LoRA adds a small set of extra weights on top of them and trains only those. rank=32 sets how big that set is.

The script:

  1. Turns each example into a Datum, in datum(). A datum holds the tokens of the question and answer, and a weight for each token that says whether to train on it.
  2. Creates a training run with TrainingConfig, which sets the model, LoRA, how many tokens to train on per step, the longest example, and the optimizer with its learning rate.
  3. Trains for 10 steps. Each step is forward_backward, which works out how to change the weights, and optim_step, which changes them.
  4. Saves the trained model as a checkpoint, and waits for it to upload.
  5. Starts a sampler of the checkpoint, and asks it a question it wasn't trained on.

Save it as sft.py:

import asyncio
import os
from uuid import uuid4

from transformers import AutoTokenizer

from looper_sdk import (
    AdamW,
    CrossEntropy,
    Datum,
    Lora,
    SamplerConfig,
    SamplingParams,
    ServiceClient,
    TrainingConfig,
)

MODEL = "Qwen/Qwen3.5-9B"
MAX_SEQ_LEN = 256
PAIRS = [
    ("What is the capital of France?", "Paris."),
    ("What is two plus three?", "Five."),
    ("How many legs does a spider have?", "Eight."),
    ("What do bees make?", "Honey."),
]
tokenizer = AutoTokenizer.from_pretrained(MODEL)


def prompt_tokens(question):
    return tokenizer.encode(f"Question: {question}\nAnswer:", add_special_tokens=False)


def datum(question, answer):
    prompt = prompt_tokens(question)
    reply = tokenizer.encode(f" {answer}", add_special_tokens=False) + [tokenizer.eos_token_id]
    return Datum(tokens=prompt + reply, weights=[0] * len(prompt) + [1] * len(reply))


async def main():
    config = ServiceClient.Config(
        project=os.environ["LOOPER_PROJECT"],
    )
    training_config = TrainingConfig(
        model=MODEL,
        kind=Lora(rank=32),
        tokens_per_step=1024,
        max_seq_len=MAX_SEQ_LEN,
        optimizer=AdamW(learning_rate=4e-4),
    )
    data = [datum(question, answer) for question, answer in PAIRS]

    async with await config.build() as service:
        print("starting the run...")
        training_client = await service.create_training_client(training_config, timeout_s=20 * 60)
        for _ in range(10):
            await training_client.forward_backward(data, CrossEntropy())
            step = await (await training_client.optim_step()).result()
            print(f"step {step.step}: loss {step.loss_sum / step.weighted_targets:.3f}")

        # Names belong to the project, so make yours unique.
        name = f"quickstart-sft-{uuid4().hex[:8]}"
        saved = await (await training_client.save_state(name)).result()
        ready = await service.wait_checkpoint(saved.id)
        print(f"checkpoint {name}: {ready.state.value}")

        sampler_config = SamplerConfig(
            checkpoint_name=name, max_seq_len=MAX_SEQ_LEN, max_concurrent_sequences=4
        )
        sampling_client = await service.create_sampling_client(sampler_config, timeout_s=20 * 60)
        params = SamplingParams(
            max_tokens=16, temperature=0.0, stop_token_ids=(tokenizer.eos_token_id,)
        )
        question = "What is the capital of Italy?"
        operation = await sampling_client.sample(prompt_tokens(question), params=params)
        [sequence] = (await operation.result()).sequences
        answer = tokenizer.decode(sequence.token_ids, skip_special_tokens=True)
        print(f"{question} {answer.strip()!r} ({sequence.finish_reason.value})")


asyncio.run(main())
starting the run...
step 1: loss 3.048
step 2: loss 1.244
step 3: loss 0.741
step 4: loss 0.023
step 5: loss 0.005
step 6: loss 0.003
step 7: loss 0.005
step 8: loss 0.006
step 9: loss 0.002
step 10: loss 0.002
checkpoint quickstart-sft-cc1e0881: ready_to_use
What is the capital of Italy? 'Rome.' (stop)

The loss drops as the model learns the examples, and the trained model answers the new question in one word, "Rome.", like the examples.

Things to know:

102: Your first fine-tune goes through this same script step by step, as a notebook.

Turn it into a real loop

The example trains on four examples, sent whole in every step. A real run has more data and trains for longer. These are the parts you'd add, and where each is explained:

301: The SFT loop shows the cookbook's loop, which does all of this. Its code is a useful reference for your own.

Next steps