Highlights

Contents

Part VIII
08

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.

THE AGENT AND ITS TRAINING PATHDefine tools01Run the loop02Measure tasks03Choose training04Build LoRA05Count adapters06Serialize traces07Train and validate08Generate tasks09Check traces10Compare models11Prepare inference12

#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.

CHECK THE TRANSITIONS BEFORE TEACHING THE TRACEuser: reserve 3 boltstool: available = 12call: reserve(bolt, 3, r1)tool: remaining = 9answer: 3 reserved; 9 remainintent preservedobservation before actionschema + authorization12 - 3 = 9answer matches receipta valid conversation format can still contain a false story
Figure 5.42The illustrative successful trace reconciles the request, the quantity sent, the transition from 12 to 9, and the final report.

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.

python
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.

FOUR MICROBATCHES FORM ONE OPTIMIZER UPDATE2 examples2 examples2 examples2 examplesupdate on 8 examples96 examples / 8 = 12 updates per epoch
Figure 5.43The illustrative update groups four microbatches of two examples. At equal target counts this matches an effective batch of eight; unequal counts need token weighting.

#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.

96 EXAMPLES, EFFECTIVE BATCH 8: 12 UPDATES PER EPOCH, 36 IN THREE EPOCHSoptimizer updatelearning rate0122436epoch 1epoch 2epoch 30.000050.00024 linear warmup updates; the flat rate afterwards is illustrative, not a recommended schedule
Figure 5.44Computed update counts and warmup values for the illustrative run. Dashed lines mark epoch boundaries at updates 12 and 24; the flat rate after warmup is a placeholder, not a recommendation.

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.

THE TRAINING LOSS CAN FALL WHILE VALIDATION GETS WORSEcheckpointmasked losstrainingvalidationselect with held-out behavior as well as loss
Figure 5.45Illustrative loss fixtures show training improving after validation starts to worsen. The curves are not Finch-24 measurements, and checkpoint choice should also weigh task outcomes.

Validation can worsen while training loss keeps falling. Check generated tool behavior too, since easy syntax tokens can dominate the loss.