Skip to Content
Recodocs

12b · Train a fast encoder decision model

Route a recorded workflow failure to the right queue, then compare label supervision, confidence and decision latency on one T4.

12 min read
Part 3
Adapt models
Model
sentence-transformers/all-MiniLM-L6-v2 · answerdotai/ModernBERT-base · Qwen/Qwen2.5-0.5B-Instruct
Data
AgentFailureBench synthetic trace annotations and CLINC150 out-of-scope requests
Hardware
Tesla T4, in Google Colab

Where would you send this trace?

You triage workflow failures. In this synthetic benchmark trace, the request asks for an invoice record to be updated only if it belongs to the named company. The last recorded result is a lookup. Which repair queue should take the case: unfinished work or missing verification? The first queue investigates whether the requested action ran. The second checks whether the workflow confirmed the outcome before claiming success.

The trace ends after the lookup

TASK_6e910942e815

Request
In the 'invoices' table, find the record belonging to Nordholm Logistics and set its priority to 'pending'.
Constraint
Only update the record if it currently belongs to Nordholm Logistics; do not create a new record.
Last recorded result
{"records":[{"id":"REC_o8stf4bc","priority":"old_value"}],"status":"success"}
Final reply field
The agent reported completion without a final verification step.
Source · Agent Failure Bench, held-out database operations trace (CC BY 4.0).
Compare the reference and four model decisions

The benchmark assigns missing verification. The visible steps end after a lookup and do not establish that the update happened. The dataset’s reply field already names the missing check. That wording can give away the benchmark label and makes this case easier than a production trace without a failure annotation. The soft-teacher student still sends this trace to premature stop.

In the 'invoices' table, find the record belonging to Nordholm Logistics and set its priority to 'pending'.

Reference
Missing verification
SetFit
Missing verification · 31.0%
Hard gold
Missing verification · 99.6%
Soft teacher
Premature stop · 31.8%
Hybrid
Missing verification · 98.2%

In the 'invoices' table, find the record belonging to Nordholm Logistics and set its priority to 'pending'.

Constraint
Only update the record if it currently belongs to Nordholm Logistics; do not create a new record.
Observed lookup
{"records":[{"id":"REC_o8stf4bc","priority":"old_value"}]}
Reference route
Missing verification
Soft teacher route
Premature stop

The lookup returned the old priority. The synthetic reply field says completion was reported without a final verification step.

Hard labels gave the strongest overall result

Held-out recall by class · correctly labelled traces out of 16 per class

1
SetFit

0.971 macro-F1

Hard gold

0.989 macro-F1

Soft teacher

0.668 macro-F1

Hybrid

0.879 macro-F1

Reference classSetFitHard goldSoft teacherHybrid
Wrong tool16/1616/1616/1616/16
Invalid argument16/1616/1616/1616/16
Missing argument16/1616/1616/1616/16
Invented tool output16/1616/160/1616/16
Constraint violation16/1616/165/1616/16
Premature stop16/1614/1616/1616/16
Failed recovery16/1616/1616/1616/16
Missing verification16/1616/160/1616/16
Incorrect final answer13/1616/1616/1616/16
Clean14/1616/169/160/16
Out of scope16/1616/1616/1616/16
Source · Verified Lesson 12b export on one Tesla T4.

1. Give each model a choice it can score

When the task is selecting from a fixed set of outcomes, compare models using the same set. The question is whether each model can identify the correct category, not which can write the most convincing explanation.

Treat the request, constraints, tool observations and synthetic reply field as one input. The tool calls remain text. A decision is one of nine selected failure categories, clean or out of scope. The benchmark defines missing verification as skipping the check that confirms an outcome, and premature stop as ending while required work remains.

SetFit uses 12 labelled examples per class. It trains MiniLM to bring traces of the same class together, then fits a logistic classifier. The three ModernBERT arms embed the trace and each option description with the same encoder. A two-layer head scores the trace–option pair from the two embeddings, their elementwise product and their absolute difference. The option text can be supplied at request time. Generalisation to new options was outside this evaluation. SetFit paper · ModernBERT paper · Laya model card

PangolinGuard shows how a ModernBERT classifier can replace text generation for a bounded decision. A separate ModernBERT walkthrough trains a domain classifier on synthetic examples. For trace routing, evaluate against reference labels whose definitions are independent of the label generator. PangolinGuard walkthrough · ModernBERT synthetic-data walkthrough

A routing label is a request for a specific next check. For this invoice, a missing-verification route asks someone to inspect the write history or read the record back. The old priority belongs to the lookup response and gives no evidence about the eventual stored value. It is possible that the workflow stopped early, and it is possible that a later write went unrecorded. The benchmark supplies a specific reply about the missing verification, which resolves the annotation for this sample. In a real queue, spell out whether the route relies on the reply or on the recorded operations. The distinction matters if the organisation wants to diagnose failures even when the reply is unavailable.

The head combines trace and option representations before scoring each option. It uses a masked mean over each sequence, so padding positions do not contribute. Both sides use the same encoder. Here is the part of the notebook that expands the representations into matched pairs.

def forward(self, input_features, options_features):
    # Compare each trace vector with each option vector.
    inputs = self.encode(input_features)
    options = self.encode(options_features)
    inputs = inputs[:, None, :].expand(-1, len(options), -1)
    options = options[None, :, :].expand(len(inputs), -1, -1)
    return self.head(torch.cat((inputs, options, inputs * options, (inputs - options).abs()), dim=-1)).squeeze(-1)

The same method can label support tickets when an on-call team maintains a short taxonomy. Option descriptions explain why two similar routes have different downstream owners. If those descriptions change, the computation can consume the new text. Establish separately whether the new descriptions preserve the old decisions on a held-out roster. For the SetFit path, version the classifier's label mapping together with that roster.

2. Check what the teacher can distinguish

The local lexical teacher intentionally groups invented tool output under incorrect final answer and missing verification under premature stop. On validation it made exactly those substitutions on all 12 reference examples in each class. It also misclassified one out-of-scope request as an incorrect final answer. The confusion matrix shows why agreement can reward copying the teacher's definitions. The TF-IDF logistic-regression teacher fits the collapsed labels, so both omitted classes receive zero target probability.

The teacher collapsed both classes named in its rubric gaps

Validation confusion matrix · every nonzero cell, out of 12 per reference class

2
ReferenceTeacher prediction and count
Wrong tool
Wrong tool · 12
Invalid argument
Invalid argument · 12
Missing argument
Missing argument · 12
Invented tool output
Incorrect final answer · 12
Constraint violation
Constraint violation · 12
Premature stop
Premature stop · 12
Failed recovery
Failed recovery · 12
Missing verification
Premature stop · 12
Incorrect final answer
Incorrect final answer · 12
Clean
Clean · 12
Out of scope
Incorrect final answer · 1
Out of scope · 11
Source · Verified Lesson 12b export on one Tesla T4.

Hard gold puts all probability mass on the annotated class. Soft teacher uses the teacher's probability distribution. Hybrid uses gold targets for the two declared rubric gaps and the teacher distribution elsewhere. For target distribution q and student logits z, each ModernBERT arm minimises

L=−∑cqclog⁡softmax⁡(z)c.\mathcal{L} = -\sum_c q_c \log\operatorname{softmax}(z)_c.
def soft_ce(target, logits):
    return -(target * torch.log_softmax(logits.float(), -1)).sum(-1).mean()

The hybrid reaches 16/16 recall on each repaired class. Its clean recall falls to 0/16, compared with 9/16 for soft teacher and 16/16 for hard gold. Check clean cases even when an override fixes the intended failures. Hinton et al. on distillation

def hybrid_targets(target, labels, overrides):
    # Use reference labels only for the declared override classes.
    mask = torch.isin(labels, torch.tensor(overrides, dtype=labels.dtype, device=labels.device))
    gold = F.one_hot(labels, num_classes=target.shape[-1]).float()
    return torch.where(mask.unsqueeze(-1), gold, target)
ArmInvented tool output recallMissing verification recallClean recallTest macro-F1
SetFit1.01.00.8750.9713952038495649
Hard gold1.01.01.00.9885918003565063
Soft teacher0.00.00.56250.6679732388823297
Hybrid1.01.00.00.8787878787878788

Look at the clean column before deciding that the hybrid repair worked. Both patched failure categories recovered, but clean examples went from partial recovery under the soft target to complete failure under the hybrid. That matters in a queue where labelling a healthy workflow as broken generates human work. Inspect the errors that move work between queues as well as the aggregate. For a production decision, the relative cost of a missed incident and an unnecessary escalation belongs in the review alongside macro-F1.

An override changes targets before fitting the shared parameters. It does not edit a single prediction after training. The newly emphasised classes compete with the other labels through the same scorer. The saved predictions show the clean regression; they do not identify which mechanism caused it. If you decide to try another override, compare the original class-wise results before interpreting the patched labels.

Find a paper on graph neural networks published in 2026 or later and save it to the 'Lit Review' collection.

Observed steps
Found “Advances in graph neural networks”, read metadata with year 2026, then received {"saved": true, "status": "success"} from save_to_library.
Reference and soft teacher
Clean
Hybrid
Premature stop

Synthetic test trace TASK_6e5a36276b19. The hybrid would send a completed workflow to the unfinished-work queue.

3. Select a checkpoint using reference labels

One rule ranks epochs by macro-F1 against gold validation labels. The other ranks them by agreement with the teacher on those same inputs. Both keep the earlier epoch in a tie. Here both rules selected epoch 3 for the soft-teacher arm, so they produced the same test macro-F1 of 0.668 and the same class recalls. Validation agreement with the teacher reached 99.2% at that epoch while gold validation macro-F1 was 0.758. Those scores answer different questions, even when the selectors happen to agree.

Both validation rules picked epoch 3

Soft-teacher arm · validation scores by epoch

3
Gold macro-F1
Epoch 122.3%
Epoch 259.5%
Epoch 3 ✓75.8%
Epoch 475.8%
Teacher agreement
Epoch 134.8%
Epoch 283.3%
Epoch 3 ✓99.2%
Epoch 499.2%
Source · Verified Lesson 12b export on one Tesla T4.
def choose_checkpoints(history):
    # Maximise the selected metric, with the earlier epoch winning a tie.
    gold_epoch = max(history, key=lambda row: (row["val_gold_macro_f1"], -row["epoch"]))["epoch"]
    teacher_epoch = max(history, key=lambda row: (row["val_teacher_agreement"], -row["epoch"]))["epoch"]
    return gold_epoch, teacher_epoch

The last two epochs tied on both recorded validation metrics. The tie-break is a reproducibility choice that keeps the earlier checkpoint. Agreement and reference macro-F1 still differ in meaning: agreement counts how often the student's choice matches the teacher's, while macro-F1 averages across reference classes, giving a poorly served class a voice even when the aggregate looks strong. Keep the teacher comparison as a diagnostic of transfer and select against the outcome the repair team actually wants.

4. Audit the test boundary before using the score

Each trace domain goes into just one split because the benchmark uses one request template per domain. The notebook verifies that scenario identifiers, example identifiers and normalised input hashes are disjoint across splits. Validation selects checkpoints. Calibration fits the temperature after a checkpoint has been selected. Test scores the frozen choices.

Every split covered all 11 options

Reference row counts and disjoint trace domains

4

Train · 352 rows

32 per class · 0 absent

financial administration, logistics, software development, file document processing, calendar scheduling, customer support

Validation · 132 rows

12 per class · 0 absent

project management

Calibration · 132 rows

12 per class · 0 absent

ecommerce

Test · 176 rows

16 per class · 0 absent

database operations, research assistance

Source · Verified Lesson 12b export on one Tesla T4.

All four splits cover the 11 options. The out-of-scope rows come from CLINC and contain a standalone request with no tool trace. A classifier can exploit that difference in format. Treat the results as evidence on this roster and check out-of-scope behaviour on in-domain-looking requests before routing production traffic. Agent Failure Bench · CLINC OOS

5. Calibrate confidence separately from the decision

Temperature scaling computes probabilities from the frozen logits divided by a positive scalar. The hybrid's temperature was 0.171, fitted on 132 calibration rows. Because it was below one, it sharpened the probability distribution while preserving the top choice. On test, expected calibration error fell from 45.21% to 6.97%, and negative log-likelihood fell from 0.914 to 0.126. The labels stayed identical, including the errors on clean traces. The bin table shows how far mean confidence sits from the observed fraction correct at each confidence level. Guo et al. on temperature scaling

Confidence moved closer to observed accuracy

Hybrid reliability on the same 176 test traces · only populated confidence bins

5

Before scaling · ECE 45.2% · NLL 0.914

0%0%50%50%100%100%Mean confidenceObserved accuracy
BinnConfidenceAccuracy
20–30%5426.7%70.4%
30–40%5534.4%100.0%
40–50%3544.6%100.0%
80–90%182.9%100.0%
90–100%3198.9%100.0%

After scaling · ECE 7.0% · NLL 0.126

0%0%50%50%100%100%Mean confidenceObserved accuracy
BinnConfidenceAccuracy
40–50%148.9%0.0%
50–60%754.6%0.0%
60–70%366.2%0.0%
70–80%575.0%20.0%
80–90%1086.4%90.0%
90–100%15098.1%100.0%
Source · Verified Lesson 12b export on one Tesla T4.

In the original confidence bin from 0.3 to 0.4, all 55 decisions were correct and mean confidence was 0.3440318703651428. That is underconfidence on those examples. After scaling, the highest bin includes 150 decisions with mean confidence 0.980965256690979 and all were correct. These are bins defined by the respective probabilities, so the rows need not contain the same cases. A sensible use is to ask whether confidence is reliable enough to help allocate review. Check that on a representative split before making a threshold a queue policy. Changing the threshold can alter how many items reach a reviewer, while the labels and the underlying misroutes stay as they were.

6. Time the decision you will actually serve

The timing includes tokenisation and scoring at batch size one, after warm-up. The comparator is one Qwen2.5-0.5B forward pass scoring a fixed set of option tokens. SetFit used a compact embedding and classifier. The Hybrid timed path includes the forward passes for both trace and option descriptions. The notebook prepares option tokens and transfers them to the GPU before starting the timer. The comparison measures these three implementations on 24 matched requests. The FP16 notebook used a 384-token encoder cap and the longest encoded test input contained 271 tokens. No test inputs were truncated.

SetFit was fastest on the matched requests

Batch size one · median and nearest-rank p95 in milliseconds per trace · 24 requests each

6
PathMedianp95
SetFit12.4913.31
Qwen forced choice31.1740.98
Hybrid59.14163.73
Source · Verified Lesson 12b export on one Tesla T4. Tokenisation and scoring included, model loading excluded.
Timed implementationMedian (ms)Nearest-rank p95 (ms)
SetFit12.48714749999635413.306919999990896
Hybrid59.14070649998848163.72571299996252
Qwen forced choice31.1650529999951740.98496200003865

The hybrid's tail is visible in the per-request samples. A serving engineer who only reads the median could miss that part of the wait. The comparison includes the current option encoding path, and the timing boundary leaves out network and queue time. Time the implementation after any caching change on the same roster. Keep the Qwen timing roster distinct from the full encoder test roster before comparing predictive quality. Hard gold led the quality comparison and has no saved timing measurement.

What to keep

Starting pointWhy choose itWhat to inspect before routing
Hard goldBest observed macro-F1 on the scored roster.Coverage of new domains and ambiguous completion evidence.
SetFitLowest observed median and p95 in the timed comparison.Clean cases sent for unnecessary review.
Soft teacherReveals where a student can reproduce the teacher.Both declared missing distinctions and the reference score.
HybridRecovers both overridden failure classes on the roster.Clean recall before adopting any override.
  • Start with the action the queue can take. Missing verification should prompt a check for the stored priority.
  • Keep reference labels independent. The teacher's collapsed categories cannot serve as the final success criterion.
  • Review repaired and untouched classes together. Both declared gaps recovered under hybrid supervision while clean recall dropped.
  • Separate calibration and checkpoint choice. A post-fit temperature changes how you read scores without changing the chosen label.
  • Compare the paths you would serve. SetFit led the measured timing and the hybrid path included option encoding.
  • Next to try, not tested here: check out-of-scope requests that look like in-domain workflow traces.

How it was built

ItemSetting
Base modelModernBERT-base and all-MiniLM-L6-v2. Qwen2.5-0.5B-Instruct serves as the forced-choice timing comparator.
DataAgent Failure Bench traces and CLINC out-of-scope requests.
Test176 labelled rows across the held-out domain groups and CLINC. Separate calibration split of 132 rows.
MethodSetFit comparison and ModernBERT option scoring with hard, soft and hybrid targets.
TrainingFP16 for the three option scorers, four epochs, encoder learning rate 2e-5 and head learning rate 1e-4.
DecodingLargest option score wins, with a separate positive temperature for hybrid probabilities.
HardwareOne Tesla T4, PyTorch 2.14.1+cu130 and Transformers 4.57.1.

Time and cost. The receipt records 335.314 seconds of notebook execution. The separate timing comparison records single-request tokenisation and scoring on 24 matched requests after warm-up. Use the per-request samples if you need to check the upper tail. Run receipt · Predictions and results · Teacher audit · Split audit · Latency · Input budgets

Run it yourself

Open the exact T4 input notebook. Its receipt records 335.314 seconds. Which benchmark rows can reach each split? maps to test coverage, and Where does the teacher disagree with the reference labels? maps to the teacher audit. Which checkpoint would each selection rule keep? maps to checkpoint choice. The two timing sections produce the comparisons in latency.

  1. Predict how adding clean to the hybrid override list will affect clean recall and the two repaired failure classes. Change only the override list in What changes between hard, soft and hybrid training? Compare those classes in encoder-results.json.
  2. Predict which invoice traces will change route if the final reply is removed from the input. In the split-construction section remove only that field before fit and evaluation. Inspect the predictions for missing verification and premature stop against the same references.
  3. Predict how caching the option embeddings will change median and p95. In the timing section cache only the option-side encoding for hybrid and repeat with the same roster. Check the decisions still match, then compare latency.json.

How is this page?

Last updated on