Every call that puts Looper's GPUs to work gives you two things to wait for. First, Looper accepts the call, and later, the call finishes running. You've already seen this as the two awaits in the earlier tutorials.
This tutorial shows why it's split that way. You'll train a run twice. The first time, you'll wait for each call to finish before sending the next. The second time, you'll send every call ahead and wait at the end. Then you'll compare how long each took. You'll also see where an error shows up when a call fails.
It uses the SDK alone, and the same eight examples as Your first fine-tune. Put your API key in the settings cell's API_KEY.
Install the SDK and tokenizer
%pip install -q "goaly-looper==0.1.0b6" "transformers==5.19.0"
Settings
As before, the settings are the model, its tokenizer, Looper's address, your project and your API key. STEPS is how many training steps each of the two ways runs, and MAX_SEQ_LEN is 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"
STEPS = 8
MAX_SEQ_LEN = 512
A batch to train on
This uses the same eight questions and answers as Your first fine-tune, turned into Datums the same way. Each question gets weight 0, and its answer and the end token get weight 1, so only the answers are trained.
import time
from transformers import AutoTokenizer
from looper_sdk import CrossEntropy, Datum, EmptyStep, Lora, ServiceClient, TrainingConfig
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."),
]
data = []
for question, answer in PAIRS:
prompt = tokenizer.encode(f"Question: {question}\nAnswer:", add_special_tokens=False)
reply = tokenizer.encode(f" {answer}", add_special_tokens=False) + [tokenizer.eos_token_id]
data.append(Datum(tokens=(*prompt, *reply), weights=(0,) * len(prompt) + (1,) * len(reply)))
config = ServiceClient.Config(
base_url=BASE_URL, project=PROJECT, api_key=API_KEY, display_name="operations"
)
training = TrainingConfig(
model=MODEL,
kind=Lora(rank=32),
tokens_per_step=max(1024, MAX_SEQ_LEN, sum(len(datum.tokens) for datum in data)),
max_seq_len=MAX_SEQ_LEN,
)
print(len(data), "datums")
8 datums
Two awaits
A training call, such as forward_backward, has two awaits:
await training_client.forward_backward(...)returns an operation once Looper has accepted the call and given it its place in the run's queue. That place is the operation'sseq. This takes one round trip to Looper, not the time to run the call.await operation.result()returns what the call computed, once it has actually run.
The first way of training, below, waits for each call's result before it sends the next call. That's simple, but it wastes time, because while your program waits for a result and then sends the next call, the GPUs have nothing to do.
In step_by_step, each await ... .result() pauses the loop until that call has run on the GPUs. The loop sends the next call only after that.
async def step_by_step(training_client, steps):
results = []
for _ in range(steps):
backward = await training_client.forward_backward(data, CrossEntropy())
await backward.result(timeout_s=300)
update = await training_client.optim_step()
results.append(await update.result(timeout_s=300))
return results
Sending ahead
Looper runs a run's operations in the order it accepted them. So you don't have to wait for one call to finish before sending the next. An optim_step applies the gradients from the forward_backward calls accepted before it, whenever those run.
The second way of training, below, sends every call first, and only waits for the results at the end. The run always has its next call waiting, so the GPUs never sit idle.
In submitted_ahead, the loop only awaits the first await of each call, which takes one round trip. It keeps each optim_step's operation in updates. The last line then waits for each one's result, in order.
async def submitted_ahead(training_client, steps):
updates = []
for _ in range(steps):
await training_client.forward_backward(data, CrossEntropy())
updates.append(await training_client.optim_step())
return [await update.result(timeout_s=300) for update in updates]
Where an error shows up
Since Looper accepts an operation before running it, a call that can't succeed is still accepted. It fails later, and you find out when you await its result().
The simplest example is an optim_step with no gradients to apply, because no forward_backward came before it. It's accepted like any other call, and its result raises EmptyStep.
A failed operation doesn't stop the ones queued after it, so they still run. That's why a real loop only sends a few steps ahead, not all of them. If a step fails, only those few have already been sent.
In the code below, update.kind and update.seq are known as soon as Looper accepts the call. The error only comes from result(). update.state() asks Looper where the operation is now, which here is failed.
async def an_empty_step(training_client):
update = await training_client.optim_step()
print(f"accepted: {update.kind}, seq {update.seq}")
try:
await update.result(timeout_s=300)
except EmptyStep as error:
print("EmptyStep:", error.message)
print("state:", (await update.state()).value)
Run all three
This cell runs both ways of training, then the failing step, all on one training run in one session.
A run's first step is slower than the rest, so the cell takes one step before it starts timing. That way the comparison is fair.
In the code below:
await step_by_step(training_client, 1)is that first, untimed step.time.perf_counter()reads a clock before each way of training, so the cell can print how long each took.- The last three lines train one more step after the failed one, to show the run carries on.
async with await config.build() as service:
print("starting the run...")
training_client = await service.create_training_client(training, timeout_s=20 * 60)
await step_by_step(training_client, 1)
started = time.perf_counter()
await step_by_step(training_client, STEPS)
print(f"step by step: {STEPS} steps in {time.perf_counter() - started:.1f} s")
started = time.perf_counter()
results = await submitted_ahead(training_client, STEPS)
print(f"submitted ahead: {STEPS} steps in {time.perf_counter() - started:.1f} s")
await an_empty_step(training_client)
# The run goes on after the failed step.
await training_client.forward_backward(data, CrossEntropy())
last = await (await training_client.optim_step()).result(timeout_s=300)
print("the run is at step", last.step)
starting the run...
step by step: 8 steps in 8.1 s
submitted ahead: 8 steps in 6.7 s
accepted: optim_step, seq 35
EmptyStep: Nothing of nonzero weight was accumulated for this step: FAILED_PRECONDITION: EMPTY_STEP: no gradient accumulated since the last step
state: failed
the run is at step 18
What the steps reported
The steps ran in the order they were accepted, so the results come back in step order, even though they were all sent at once. Each result, a StepResult, holds the step's number, its loss (as a sum and the number of tokens it was summed over), its learning rate and its gradient norm.
for result in results:
loss = result.loss_sum / result.weighted_targets
print(f"step {result.step:2d}: loss {loss:.4f}, grad norm {result.grad_norm:.3f}")
step 10: loss 0.0023, grad norm 0.091
step 11: loss 0.0013, grad norm 0.052
step 12: loss 0.0008, grad norm 0.032
step 13: loss 0.0005, grad norm 0.034
step 14: loss 0.0003, grad norm 0.015
step 15: loss 0.0001, grad norm 0.006
step 16: loss 0.0001, grad norm 0.003
step 17: loss 0.0000, grad norm 0.002
Next steps
Sending ahead is how a training loop keeps the GPUs busy while your program gets the next batch ready. A real loop sends a few steps ahead, not all of them, so a failure only affects those few.
- The SFT loop uses the cookbook's SFT loop, which sends ahead in this way for you.
- Chat data turns conversations into training data.