Training on traces that deserve imitation
A consistent-looking dataset can teach incorrect actions. Coverage and trace validity matter before optimization. Control the update and evaluate generated behavior, not only a falling demonstration loss.
#Section 46Dataset quality
A trace says 3 bolts were reserved while the environment shows 4. Training on it teaches the model to misreport a mistake. A pleasing final answer does not make a demonstration correct.
Correct traces, consistent formats, and valid schemas
Dataset quality means demonstrations accurately show the behavior we want. Correct traces keep request values, action preconditions, observed transitions, and supported final answers. Consistent formats share one role schema, call representation, and template version. Valid schemas cover only part of this.
Noise control
Noise control removes or repairs mislabeled, contradictory, incomplete, and corrupted examples, recording why. A schema error followed by a corrected, successful action is a useful recovery demonstration when the correction and result are present. It is noise if the error vanishes and the answer claims an unobserved success.
Check available_before - quantity = available_after only after a successful reservation; a refusal leaves availability unchanged. Against a real concurrent service, use the transaction receipt’s state, not unrelated reads.
Validate the final serialized batch as well as source rows, since templates, masking, and truncation can damage a correct trace. Keep rejected examples out unless they become explicitly labeled error-handling demonstrations.
#Section 47Dataset balance
Every training row uses a tool, so the assistant learns that every request deserves a call and starts querying stock when the user wants a definition. The action distribution in the data becomes a behavioral prior.
Tool vs non-tool examples and different tools
Dataset balance describes how examples and supervised tokens spread across behaviors. Include tool and non-tool examples, different tools, and valid refusals in proportions matching the application or a deliberate reweighting. Equal counts are a choice, not an optimum.
Easy/hard examples and error-handling examples
Easy reads teach syntax; conditional actions require using observations; error-handling examples teach recovery, reconciliation, or refusal. Do not let always-commit demonstrations drown out correct refusals.
Vary environment conditions as well as wording, so the dataset covers action, refusal, and no-tool paths.
Under token-average loss, long traces contribute more supervised tokens than short answers, so a set balanced by conversation count can be dominated by one verbose family. Report token counts per behavior and sample or weight deliberately. Relabeling one trace as several examples does not add diversity.
#Section 48SFT training loop
The adapter attaches correctly and examples render correctly. Training is now a concrete sequence of operations, and the smallest useful check is one batch whose supervised spans and loss you can verify.
Load model, attach LoRA, batch, and forward pass
Load the recorded checkpoint with its tokenizer and template, attach LoRA to the chosen modules, and confirm initial parity. A batch groups encoded examples with input IDs, attention masks, and labels. The forward pass computes causal next-token logits.
Masked loss and backpropagation
Backpropagation computes gradients of the masked loss through the graph, and only the trainable parameters reach the optimizer. Padding and non-assistant targets stay ignored. A batch with no supervised targets should fail preprocessing or be skipped explicitly, not report a misleading zero loss.
Validation and save adapter
Validation measures held-out loss and generated task behavior without updating weights. Save the adapter configuration and factors from the checkpoint the declared criterion selects, with enough state to reproduce it and compare it to the initial model.
optimizer.zero_grad()
for batch in microbatches:
logits = model(batch["input_ids"], batch["attention_mask"])
loss = masked_next_token_loss(logits, batch["labels"])
(loss / len(microbatches)).backward()
optimizer.step()This averages microbatch mean losses, which equals a global token average only when supervised-token counts match. With unequal counts, accumulate summed token losses and divide by the update’s total supervised tokens. Precision scaling and clipping add detail without changing what the targets mean.
#Section 49SFT hyperparameters
The run sees the same data, but a shorter sequence length cuts off most reservation receipts, and the loss still falls. Some hyperparameters change optimization; others change which evidence survives.
Learning rate, batch size, sequence length, and epochs
A learning rate sets update size. Batch size counts examples or tokens processed together and needs a stated unit. Sequence length caps the encoded span and can truncate dependencies. An epoch is one pass over the dataset’s sampling order.
Gradient accumulation and warmup
Gradient accumulation combines microbatch gradients before one update. Its effective batch differs from the group processed in one forward pass.
Warmup increases the learning rate early in training. Check logged values and the scheduler’s update order.
LoRA rank and LoRA alpha
Rank changes factor shapes; alpha changes their scale. Choose both using held-out behavior and resource limits.
#Section 50SFT overfitting
The assistant reproduces every training call perfectly and fails when the user says “set aside” instead of “reserve.” Falling training loss shows imitation of the examples, not general competence.
Memorization and template overfitting
Memorization reproduces specific training values or traces without learning the mapping. Template overfitting ties performance to the exact wording or layout of demonstrations. Vary names, quantities, states, and phrasings, and hold out combinations or families that test the generalization you want.
Loss of general behavior and validation
Loss of general behavior is regression on capabilities the specialization should keep, such as ordinary chat or non-tool reasoning. Keep a regression set independent of the tool corpus; a small adapter changes few parameters but can still do harm.
Validation can worsen while training loss keeps falling. Check generated tool behavior too, since easy syntax tokens can dominate the loss.