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.
- 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.
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
10.971 macro-F1
0.989 macro-F1
0.668 macro-F1
0.879 macro-F1
| Reference class | SetFit | Hard gold | Soft teacher | Hybrid |
|---|---|---|---|---|
| Wrong tool | 16/16 | 16/16 | 16/16 | 16/16 |
| Invalid argument | 16/16 | 16/16 | 16/16 | 16/16 |
| Missing argument | 16/16 | 16/16 | 16/16 | 16/16 |
| Invented tool output | 16/16 | 16/16 | 0/16 | 16/16 |
| Constraint violation | 16/16 | 16/16 | 5/16 | 16/16 |
| Premature stop | 16/16 | 14/16 | 16/16 | 16/16 |
| Failed recovery | 16/16 | 16/16 | 16/16 | 16/16 |
| Missing verification | 16/16 | 16/16 | 0/16 | 16/16 |
| Incorrect final answer | 13/16 | 16/16 | 16/16 | 16/16 |
| Clean | 14/16 | 16/16 | 9/16 | 0/16 |
| Out of scope | 16/16 | 16/16 | 16/16 | 16/16 |
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| Reference | Teacher 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 |
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
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)| Arm | Invented tool output recall | Missing verification recall | Clean recall | Test macro-F1 |
|---|---|---|---|---|
| SetFit | 1.0 | 1.0 | 0.875 | 0.9713952038495649 |
| Hard gold | 1.0 | 1.0 | 1.0 | 0.9885918003565063 |
| Soft teacher | 0.0 | 0.0 | 0.5625 | 0.6679732388823297 |
| Hybrid | 1.0 | 1.0 | 0.0 | 0.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
3def 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_epochThe 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
4Train · 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
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
5Before scaling · ECE 45.2% · NLL 0.914
| Bin | n | Confidence | Accuracy |
|---|---|---|---|
| 20–30% | 54 | 26.7% | 70.4% |
| 30–40% | 55 | 34.4% | 100.0% |
| 40–50% | 35 | 44.6% | 100.0% |
| 80–90% | 1 | 82.9% | 100.0% |
| 90–100% | 31 | 98.9% | 100.0% |
After scaling · ECE 7.0% · NLL 0.126
| Bin | n | Confidence | Accuracy |
|---|---|---|---|
| 40–50% | 1 | 48.9% | 0.0% |
| 50–60% | 7 | 54.6% | 0.0% |
| 60–70% | 3 | 66.2% | 0.0% |
| 70–80% | 5 | 75.0% | 20.0% |
| 80–90% | 10 | 86.4% | 90.0% |
| 90–100% | 150 | 98.1% | 100.0% |
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| Path | Median | p95 |
|---|---|---|
| SetFit | 12.49 | 13.31 |
| Qwen forced choice | 31.17 | 40.98 |
| Hybrid | 59.14 | 163.73 |
| Timed implementation | Median (ms) | Nearest-rank p95 (ms) |
|---|---|---|
| SetFit | 12.487147499996354 | 13.306919999990896 |
| Hybrid | 59.14070649998848 | 163.72571299996252 |
| Qwen forced choice | 31.16505299999517 | 40.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 point | Why choose it | What to inspect before routing |
|---|---|---|
| Hard gold | Best observed macro-F1 on the scored roster. | Coverage of new domains and ambiguous completion evidence. |
| SetFit | Lowest observed median and p95 in the timed comparison. | Clean cases sent for unnecessary review. |
| Soft teacher | Reveals where a student can reproduce the teacher. | Both declared missing distinctions and the reference score. |
| Hybrid | Recovers 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
| Item | Setting |
|---|---|
| Base model | ModernBERT-base and all-MiniLM-L6-v2. Qwen2.5-0.5B-Instruct serves as the forced-choice timing comparator. |
| Data | Agent Failure Bench traces and CLINC out-of-scope requests. |
| Test | 176 labelled rows across the held-out domain groups and CLINC. Separate calibration split of 132 rows. |
| Method | SetFit comparison and ModernBERT option scoring with hard, soft and hybrid targets. |
| Training | FP16 for the three option scorers, four epochs, encoder learning rate 2e-5 and head learning rate 1e-4. |
| Decoding | Largest option score wins, with a separate positive temperature for hybrid probabilities. |
| Hardware | One 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.
- 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. - 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.
- 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