The SFT loop: fine-tune on a file of conversations
In Your first fine-tune, you wrote the training loop yourself. In this tutorial, the cookbook does most of that work. You'll fine-tune a model on a file of conversations using three cookbook pieces:
- a dataset,
ChatDataset, which splits the conversations into batches, one for each training step; - the model's message formatter, which turns each conversation into training data in the model's chat format;
- the SFT loop,
train_sft.train, which trains the run on the batches, one step at a time.
Then you'll sample the model you trained.
Chat data explains the message formatter and the training data it makes. Operations explains sending steps ahead, which the loop does for you.
This notebook uses the cookbook's package, looper_cookbook, which isn't on PyPI yet, so install it from a clone of its repository first, as The cookbook shows. Put your API key in the settings cell's API_KEY.
Settings
As before, the first settings are the model, its tokenizer, Looper's address, your project and your API key. Then come the settings for the run:
LORA_RANK: the size of the LoRA.MAX_SEQ_LEN: the longest training example, in tokens.BATCH_SIZE: how many conversations each training step trains on.EPOCHS: how many times to go through the whole file.LEARNING_RATE: the learning rate at the first step. The loop lowers it as training goes on.
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
MAX_SEQ_LEN = 2048
BATCH_SIZE = 8
EPOCHS = 4
LEARNING_RATE = 5e-4
Load the conversations
The example file has 16 conversations. In each, the user asks about an animal, and the assistant answers with a three-line card of Habitat, Diet and Fun fact. Your own file would have the same shape, with one {"messages": [...]} per line.
ChatDataset splits the conversations into batches, one per training step, and uses the formatter to turn each conversation into training data, one example per assistant reply. Each pass through the file uses a different order, and seed makes that order the same each time you run the notebook.
The run's step k, counting from 0, trains on dataset.batch(k). So EPOCHS passes through the file is EPOCHS * len(dataset) steps.
The cell prints what the first example of the first step trains on, which is the assistant's reply.
In the code below, resources.files("looper_cookbook") finds the example file inside the installed cookbook. read_conversations reads it. len(dataset) is the number of batches in one pass, and dataset.batch(0)[0] is the first datum of step 0's batch.
from importlib import resources
from uuid import uuid4
from transformers import AutoTokenizer
from looper_cookbook import train_sft
from looper_cookbook.datasets.conversations import ChatDataset, read_conversations
from looper_cookbook.message_formatters.models import message_formatter
from looper_sdk import (
AdamW,
Lora,
SamplerConfig,
SamplingParams,
ServiceClient,
StateCheckpoint,
TrainingConfig,
)
tokenizer = AutoTokenizer.from_pretrained(TOKENIZER)
formatter = message_formatter(MODEL, tokenizer, enable_thinking=False)
path = resources.files("looper_cookbook") / "example_data" / "conversations.jsonl"
dataset = ChatDataset(
read_conversations(path), formatter, batch_size=BATCH_SIZE, max_seq_len=MAX_SEQ_LEN, seed=0
)
steps = EPOCHS * len(dataset)
print(f"{len(dataset)} batches a pass, {steps} steps. The first step's first datum trains:")
for text in formatter.targets(dataset.batch(0)[0]):
print(repr(text))
The run and the loop
There are two configs, for two different things:
TrainingConfigsets up the training run on Looper, including the model, the LoRA and the optimizer. Its sizes decide which GPUs the run gets.max_seq_lenis the longest example, andtokens_per_stepis the most tokens one step trains on. The cell works out the largest batch, sotokens_per_stepis big enough for it.train_sft.Configsets up the cookbook's loop, which runs in your program. Looper's optimizer doesn't change the learning rate by itself, so the loop sets it for each step. Here,schedule="linear"lowers it in a straight line fromLEARNING_RATEat the start to 0 at the end.steps_ahead=1lets the loop send one extra step while it waits for the current one to finish, so the GPUs don't sit idle.
In the code below, largest goes through every step's batch and finds the one with the most tokens. Batches differ in size, because conversations differ in length, so tokens_per_step is set from the largest.
config = ServiceClient.Config(
base_url=BASE_URL, project=PROJECT, api_key=API_KEY, display_name="sft-loop"
)
largest = max(sum(len(datum.tokens) for datum in dataset.batch(step)) for step in range(steps))
training = TrainingConfig(
model=MODEL,
kind=Lora(rank=LORA_RANK),
tokens_per_step=max(MAX_SEQ_LEN, largest),
max_seq_len=MAX_SEQ_LEN,
optimizer=AdamW(learning_rate=LEARNING_RATE, betas=(0.9, 0.95), max_grad_norm=1.0),
)
loop_config = train_sft.Config(learning_rate=LEARNING_RATE, schedule="linear", steps_ahead=1)
print(f"{steps} steps, at most {largest} tokens in one")
Train and save
train_sft.train trains the run, taking one training step per batch. After each step, it calls your on_step function with the step's result. Here, report prints the step's learning rate and loss.
The loss is the step's total loss divided by the number of tokens it trained. It should go down from one pass through the file to the next.
The loop only trains. Creating the run before it, and saving a checkpoint after it, are up to you, as in Your first fine-tune.
In the code below:
train_sft.train(training_client, dataset, loop_config, steps=steps, on_step=report)takes the training client, the batches, the loop's config, how many steps to train in total, and the function to call after each step.step.lris the learning rate the step used, whichschedule="linear"lowers each step.- The save works the same way as in Your first fine-tune.
save_statewrites the checkpoint, andwait_checkpointwaits until a sampler can load it.
def report(step):
loss = step.loss_sum / step.weighted_targets
print(f"step {step.step:2d}/{steps}: lr {step.lr:.2e}, loss {loss:.4f}")
async def train_and_save() -> StateCheckpoint:
async with await config.build() as service:
print("starting the run...")
training_client = await service.create_training_client(training, timeout_s=20 * 60)
await train_sft.train(training_client, dataset, loop_config, steps=steps, on_step=report)
name = f"sft-loop-{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
checkpoint = None
checkpoint = await train_and_save()
Sample the trained model
This cell asks the trained model about a puffin, an animal the file never mentions, to see whether it learned the card format in general.
The prompt is written with the same formatter that made the training data, so it's in the same format the model was trained on, which is the model's chat format with thinking off. The sampler stops on the formatter's end token, and parse_response turns the reply back into a message.
In the code below, stop_token_ids=formatter.stop_token_ids ends the reply where the chat format ends an assistant message. message, _ = formatter.parse_response(...) keeps the message and ignores whether it ended on its end token, since the finish reason is printed anyway. message["content"] is the reply's text.
async def sample_checkpoint(name, question):
params = SamplingParams(max_tokens=96, temperature=0.7, stop_token_ids=formatter.stop_token_ids)
sampler_config = SamplerConfig(
checkpoint_name=name, max_seq_len=MAX_SEQ_LEN, max_concurrent_sequences=4
)
async with await config.build() as service:
print(f"starting a sampler of {name!r}...")
sampler = await service.create_sampling_client(sampler_config, timeout_s=20 * 60)
try:
prompt = formatter.build_generation_prompt([{"role": "user", "content": question}])
operation = await sampler.sample(prompt, params=params)
return await operation.result(timeout_s=300)
finally:
await sampler.stop()
result = await sample_checkpoint(checkpoint.name, "Tell me about the puffin.")
[sequence] = result.sequences
message, _ = formatter.parse_response(sequence.token_ids)
print(message["content"])
print("finish reason:", sequence.finish_reason.value)
What the loop does for you
looper_cookbook/train_sft.py is short enough to read. It's meant to be copied and changed when your training needs something it doesn't do. If you write a loop of your own, it needs to handle the same four things this one does:
- A step can take several calls. A batch too large for one call (each call can send at most 16 MiB) is split across several
forward_backwardcalls. Their gradients add up, and oneoptim_stepthen applies them all.max_call_tokenssets how many tokens go in one call. - It sends steps ahead, but only a few. It keeps
steps_aheadextra steps queued, so the GPUs never wait for your program. If a step fails, only those few have already been sent. - The run's step number decides the batch and the learning rate. The loop starts from the step the run is already at. So if the run has already trained some steps, the loop only trains the steps that are left, each with its own batch and learning rate.
- It checks each result's step number, against the step it expected. If something else trained the run, or the run rolled back, the numbers don't match and the loop raises an error.
Next steps
The same fine-tune also runs as a script, with options for the model, the data and the schedule. Without --data, it trains on a public dataset of math problems, GSM8K:
python -m looper_cookbook.recipes.sft_basic --data my_conversations.jsonl