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:
- A complete example: a short script that fine-tunes a LoRA on four examples, saves it, and samples it.
- Turn it into a real loop: what to add for real data and longer training, and where each part is explained.
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:
- Turns each example into a
Datum, indatum(). A datum holds the tokens of the question and answer, and a weight for each token that says whether to train on it. - 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. - Trains for 10 steps. Each step is
forward_backward, which works out how to change the weights, andoptim_step, which changes them. - Saves the trained model as a checkpoint, and waits for it to upload.
- 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:
- A
Datum's weights say what to learn. The question's tokens get weight 0, because they're context, not something to learn. The answer's tokens get weight 1, because those are what the model should learn to write. You pass the whole sequence, and Looper trains the model to predict each token from the ones before it. Prepare data explains more. forward_backwardandoptim_stepare one training step.forward_backwardworks out how the weights should change (the gradients), andoptim_stepchanges them, at theAdamWlearning rate.optim_stepalso reports the loss. The script prints it as the average per trained token.- Saving takes two waits.
save_state(...).result()returns once the run has written the checkpoint, while it's still uploading.wait_checkpointwaits until the upload is done, which a sampler needs before it can load it. See Checkpoint. - Checkpoint names are shared across your project, so the script adds a random suffix to make its name unique.
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:
- Batches. Split your data into batches, and send a different batch in each step. A single
forward_backwardcall is capped at 16 MiB. To train one step on more than that, send several calls and then oneoptim_step. See Size limit per call. - Chat data. If your data is conversations, the cookbook's message formatters can turn each one into a
Datumfor you, even in your own loop. See Chat data. - A learning-rate schedule. Looper trains at a fixed rate unless you pass a rate to each
optim_step, for example to warm up or decay. See Set the learning rate. - Keeping the GPUs busy. Send the next steps before the last ones finish, so the run always has work queued. See Submit ahead.
- Saving. Save checkpoints during training, not only at the end. See Checkpoint.
- Keeping your program running. Your program has to run for the whole training run, because it sends each step and keeps the session open. If it stops, for example because your laptop goes to sleep, the session expires after 60 seconds and the run is shut down. A run can't be resumed from a checkpoint yet. So run long training on a machine that stays on. See When a session expires.
- Failures. If the run loses its GPUs, it restarts from step 0, and your loop decides what to train again. See When a run rolls back.
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
- Training: every training call in detail.
- Checkpoint: saving, waiting for the upload, and sampling what you saved.
- RL with your own loop: the same, for RL.