Skip to Content
Recodocs

05 · Distil traces and protect existing skills

Check what the teacher wrote, choose which invoices the student sees, and measure the cost to familiar extraction.

12 min read
Part 2
Compare training stages
Model
Qwen/Qwen2.5-0.5B-Instruct
Data
Course Invoice v1, visible text with separately stored gold records
Hardware
Tesla T4, in Google Colab

You review training answers for an accounts-payable parser. On invoice SF-157375, a candidate shows a correct subtotal calculation, then supplies "total_minor":115781. The synthetic invoice below says USD 1,158.82 is due. Which amount should the training record carry? If the parser silently rewrites the supplier's stated amount, the reviewer loses the discrepancy they need to investigate.

Supplier: Sample Supplier 8777
Invoice: SF-157375
Issued: 2026-06-12
Currency: USD
Description | Quantity | Unit price
Cooling filter | 9 | 21.85
Packing insert | 3 | 87.63
Mounting plate | 3 | 207.51
Subtotal: 1,082.07
Tax: 75.74
Amount due: 1,158.82
Reveal the approved record and rejected variants

Copy "total_minor":115882. The calculation shows that the line items add to USD 1,082.07. The subtotal and tax imply USD 1,157.81. Preserve the printed amount and route the discrepancy to review. The accepted answer keeps both the checked calculation and the source record.

SF-157375 · recorded candidate ledger

verified · accepted
CALC 9 * 2185 + 3 * 8763 + 3 * 20751 = 108207 RECORD {"invoice_id":"SF-157375","issued_on":"2026-06-12","supplier":"Sample Supplier 8777","currency":"USD","line_items":[{"description":"Cooling filter","quantity":9,"unit_minor":2185},{"description":"Packing insert","quantity":3,"unit_minor":8763},{"description":"Mounting plate","quantity":3,"unit_minor":20751}],"subtotal_minor":108207,"tax_minor":7574,"total_minor":115882}
truncated · truncated
CALC 9 * 2185 + 3 * 8763 + 3 * 20751 = 108207 RECORD {"invoice_id":"SF-157375","issued_on":"2026-06-12","supplier":"Sample Supplier 8777","currency":"USD","line_items":[{"description":"Cooling filter","quantity":9,"unit_minor":2185},{"description":"Packing insert","quantity":3,"unit_minor":8763},{"description":"Mounting plate","quantity":3,"unit_minor":20751}],"subtotal_minor":108207,"tax_minor":7574,"total_minor"
wrong-record · record_verifier
CALC 9 * 2185 + 3 * 8763 + 3 * 20751 = 108207 RECORD {"invoice_id":"SF-157375","issued_on":"2026-06-12","supplier":"Sample Supplier 8777","currency":"USD","line_items":[{"description":"Cooling filter","quantity":9,"unit_minor":2185},{"description":"Packing insert","quantity":3,"unit_minor":8763},{"description":"Mounting plate","quantity":3,"unit_minor":20751}],"subtotal_minor":108207,"tax_minor":7574,"total_minor":115781}
wrong-trace · arithmetic_trace
CALC 9 * 2185 + 3 * 8763 + 3 * 20751 = 108208 RECORD {"invoice_id":"SF-157375","issued_on":"2026-06-12","supplier":"Sample Supplier 8777","currency":"USD","line_items":[{"description":"Cooling filter","quantity":9,"unit_minor":2185},{"description":"Packing insert","quantity":3,"unit_minor":8763},{"description":"Mounting plate","quantity":3,"unit_minor":20751}],"subtotal_minor":108207,"tax_minor":7574,"total_minor":115882}

The mix improved familiar extraction and gave up some difficult hits

Exact-record share and paired changes, by held-out slice

1
Difficult · 45 invoices · 12 supplier families
0%25%50%75%100%Prompted base0.0%Direct answers35.6%Target-only traces40.0%Mixed traces31.1%

Mixed minus Target-only -8.9 pp · 95% -24.5 to +7.7

Mixed minus Prompted base +31.1 pp · 95% +10.2 to +53.3

Familiar · 25 invoices · 8 supplier families
0%25%50%75%100%Prompted base0.0%Direct answers100.0%Target-only traces0.0%Mixed traces100.0%

Mixed minus Target-only +100.0 pp · 95% +100.0 to +100.0

Mixed minus Prompted base +100.0 pp · 95% +100.0 to +100.0

Source · Lab 05, Tesla T4 · 05-report.json. Points and intervals derived from reported family bootstrap results.

Familiar means one line on a known layout from a held-out supplier. Difficult means three lines on novel or independent layouts, so line count and layout both change. The development probe used familiar layout types, and Prompted base scored zero exact records on both line-count groups. It did stop naturally on 19/19 one-line records and only 7/28 three-line records. The fitted methods demonstrate a familiar skill within the experiment. The baseline gives no evidence that this skill was already present.

Filter the proposed answers

The teacher's reasoning is a candidate, not an authority. Only independently checked outputs become supervision; judge the student on work it has not seen.

A response must finish, contain the expected calculation, and match the independently verified record. The deliberately corrupted candidates let you test each rejection separately. The opening candidate passes the arithmetic check and fails the record check.

# Separate the checked calculation from the record that goes to the ledger.
prefix, marker, record = output.content.partition(RECORD_MARKER)
if prefix != calculation(invoice) or not marker:
    return "arithmetic_trace"
if not score_record(record, invoice)["exact"]:
    return "record_verifier"

A plausible calculation can conceal a rejected record

442 constructed candidate answers to eligible training invoices

2
0100200300400Accepted381Truncated23Record mismatch21Arithmetic mismatch17
Source · Lab 05, Tesla T4 · 05-report.json and 05-audit.json candidate ledger.
Candidate decisionRecorded count
Accepted381
Truncated23
Failed the record verifier21
Failed the arithmetic check17

The counts are decisions on the scripted candidate pool. Read them in the order the checks run. A truncated response can also have a wrong amount, but it stops at the termination check. The ledger preserves the completion and decision so we can inspect later errors without treating these counts as independent estimates of failure probability.

For SF-157375, read the calculation and the record as answers to different questions. The calculation establishes what the visible quantities and prices imply. The record establishes what the supplier actually asks to be paid. A standardised trace gives a reviewer a place to look for the calculation, while the fixture tells the verifier which amount belongs in the extraction target. If you move that distinction into another billing system, define the part of the record that should trigger an exception and the part that should retain the original source value. Only a separate reconciliation step has authority to settle the discrepancy.

Lightricks filtered proposed video-editing parameters using users’ actual exports. Its industry paper reports that FlanT5-base reached 99% of the Llama-2-7B-chat completion rate in a separate A/B test. Here the filter has a fixture contract that can verify every field. DeepSeek-R1 likewise describes filtering reasoning trajectories before fitting compact models, with different tasks and criteria. Lightricks, §§3.1 and 4.2 · DeepSeek-R1, §§B.3.3 and B.4.3

NovaSky estimates about US$450 for its Sky-T1-32B-Preview training run at Lambda Cloud rates. Its pipeline sampled and filtered reasoning traces, then rewrote retained traces into a form that made the final answers easier to parse. For an invoice trace, standardise the format so the checker can find the answer, then verify the amounts and rows separately. NovaSky’s Sky-T1 training report

Hugging Face’s Open-R1 project publishes scripts for generating synthetic examples, checking solutions on verifiable tasks and training with those checks. OpenThoughts tested filters directly and found that their benefit varied by domain and strategy. On the invoice task, compare filtered and unfiltered examples at a fixed fit budget and measure complete records and retention separately. Hugging Face’s Open-R1 project · OpenThoughts, §4.5

Count what the student sees

Target-only traces uses 128 difficult examples. Mixed traces spends half of those positions on familiar examples. Direct answers uses the same ordered inputs as Mixed traces but supervises only the final record. On SF-157375, both see the same 245 prompt tokens in update 1. Direct answers supervises 129 response tokens and Mixed traces supervises 169, including the end marker. The prompt and padding carry no loss.

# Include the end token in the response target.
response = tok.encode(answer, add_special_tokens=False) + [tok.eos_token_id]
sequence, = split_turns([Turn(prompt, response)])
Lu=−∑i,tmitlog⁡pθ(yit∣xi,yi,<t)∑i,tmit.\mathcal L_u = -\frac{\sum_{i,t}m_{it}\log p_\theta(y_{it}\mid x_i,y_{i,<t})} {\sum_{i,t}m_{it}}.

The same update budget can buy different examples

Difficult and familiar training rows, supervised tokens, trainer seconds and allocated GPU GiB

3

Direct answers

64 difficult · 64 familiar

32 updates · 28,403 prompt tokens

14,102 supervised tokens

11.61 s · 5.23 GiB

Target-only traces

128 difficult · 0 familiar

32 updates · 30,478 prompt tokens

21,739 supervised tokens

12.14 s · 5.72 GiB

Mixed traces

64 difficult · 64 familiar

32 updates · 28,403 prompt tokens

18,029 supervised tokens

11.33 s · 5.70 GiB

Source · Lab 05, Tesla T4 · 05-report.json exposure and training.
AdapterDifficult rowsFamiliar rowsSupervised response tokens
Direct answers646414,102
Target-only traces128021,739
Mixed traces646418,029

Here's the part of the notebook’s batch builder that decides which tokens carry loss. The completion mask retains the response token as its label. Positions from the invoice prompt and the padding get the trainer’s ignore index.

# Keep response labels and ignore prompt and padding positions.
labels.append([token if mask else -100 for token, mask in zip(
    example.input_ids, example.completion_mask, strict=True,
)] + [-100] * n_pad)

Comparing Target-only traces with Mixed traces answers a budget question for a team choosing what to fit next. Adding a familiar example spends a training position that could have held a difficult invoice. It changes the number of examples from each group and the token exposure. Comparing Direct answers with Mixed traces holds the ordered input list fixed and changes what the student has to produce. The target length and the presence of the calculation still move together. I’d keep those comparisons separate when deciding whether to collect a different mix or change the target format. The disabled Equal-target option provides a starting point for investigating the displacement question.

Together reported that on the same 965 Lao translations, adding 989 Thai translations moved the student from 44.3 to 47.4 Thai chrF++ and from 41.8 to 41.9 Lao chrF++. That comparison also used more training steps. Here the updates are fixed and the mix displaces difficult examples. Hsieh and colleagues report that supervising rationales and labels as separate tasks beat concatenation on ANLI-R1. This invoice lab tests a concatenated trace, so its Direct answers control matters. Together AI, results table and appendix · Distilling Step-by-Step, Table 2

Inspect the changes invoice by invoice

On familiar invoices, both mixed-data fits achieved 25/25 exact. On difficult invoices Mixed traces scored 14/45 and Direct answers scored 16/45. That difference is −4.4 percentage points, with a paired 95% interval of −10.2 to 0.0. On the same 45 invoices, Target-only traces correctly copied the printed total 31 times, against 25 for Mixed traces and 26 for Direct answers. Those are field-level counts out of the whole slice, including invalid outputs. A correct total alone cannot pass exact-record scoring.

A familiar gain and a difficult trade-off moved different invoices

Counts of paired outcomes for Mixed traces

4
Difficult

versus Target-only traces

2 fixed · 6 regressed · 12 both exact · 25 both wrong

versus Direct answers

3 fixed · 5 regressed · 11 both exact · 26 both wrong

Familiar

versus Target-only traces

25 fixed · 0 regressed · 0 both exact · 0 both wrong

versus Direct answers

0 fixed · 0 regressed · 25 both exact · 0 both wrong

Source · Lab 05, Tesla T4 · 05-report.json, paired outcomes on fixed rosters.

Compare the recorded responses on SF-269212. Prompted base returned decimal dollars in fields that require integer cents. Target-only traces put the totals inside the line-item list. Mixed traces and Direct answers both extracted the one visible row and copied the correct payable total.

Supplier: Sample Supplier 1597
Invoice: SF-269212
Issued: 2026-07-21
Currency: USD
Description | Quantity | Unit price
Cooling filter | 6 | 12.26
Subtotal: 73.56
Tax: 5.15
Amount due: 78.71

SF-269212 · held-out familiar invoice

Expected record
{ "invoice_id": "SF-269212", "issued_on": "2026-07-21", "supplier": "Sample Supplier 1597", "currency": "USD", "line_items": [ { "description": "Cooling filter", "quantity": 6, "unit_minor": 1226 } ], "subtotal_minor": 7356, "tax_minor": 515, "total_minor": 7871 }
Prompted base
```json { "invoice_id": "SF-269212", "issued_on": "2026-07-21", "supplier": "Sample Supplier 1597", "currency": "USD", "line_items": [ { "description": "Cooling filter", "quantity": 6, "unit_minor": 12.26 } ], "subtotal_minor": 73.56, "tax_minor": 5.15, "total_minor": 78.71 } ```
Direct answers
{"invoice_id":"SF-269212","issued_on":"2026-07-21","supplier":"Sample Supplier 1597","currency":"USD","line_items":[{"description":"Cooling filter","quantity":6,"unit_minor":1226}],"subtotal_minor":7356,"tax_minor":515,"total_minor":7871}
Target-only traces
CALC 6 * 1226 + 6 * 1226 + 7356 = 7356 RECORD {"invoice_id":"SF-269212","issued_on":"2026-07-21","supplier":"Sample Supplier 1597","currency":"USD","line_items":[{"description":"Cooling filter","quantity":6,"unit_minor":1226},{"subtotal_minor":7356,"tax_minor":515,"total_minor":7871}]}
Mixed traces
CALC 6 * 1226 = 7356 RECORD {"invoice_id":"SF-269212","issued_on":"2026-07-21","supplier":"Sample Supplier 1597","currency":"USD","line_items":[{"description":"Cooling filter","quantity":6,"unit_minor":1226}],"subtotal_minor":7356,"tax_minor":515,"total_minor":7871}

The familiar example is useful because the checkpoints break the contract in different ways. Decimal dollar values need a currency-aware conversion before ingestion. Totals inside line_items need the model or a parser to recover the record hierarchy. Treat both as invalid at the scoring boundary. A system that repairs either problem should record the repair explicitly and score the final accepted record separately. Counting repaired records as clean model outputs would obscure which checkpoint actually learnt the target representation.

The difficult examples expose a related choice. Target-only traces returned valid records for 44 of 45 invoices and exact ones for 18. Mixed traces returned valid records for 38 and exact ones for 14. Direct answers returned valid records for 30 and exact ones for 16. On a desk that routes invalid JSON for immediate review, validity changes the shape of the queue. Plausible records with wrong fields need their own verification step, because syntactic checks will let them through. Keep a row-level or field-level diagnosis alongside exact extraction when a checkpoint appears to reduce the review workload.

Separate stopping from correctness

For Mixed traces, raising the cap from 128 to 256 new tokens restored eight natural stops on the same 16 invoices. Exact extraction gained one record, from 8/16 to 9/16. On SF-779662, the shorter answer was cut off mid-row. The longer answer parsed and retained the correct amount, but stored the label Biller as part of the supplier name.

A longer cap restored stopping more often than exact extraction

Same adapter and 16 invoices at each generation cap

5
CapValidExactNatural stopMean tokens
1288/168/168/16119.1
25616/169/1616/16141.4
Source · Lab 05, Tesla T4 · 05-report.json and 05-cap-predictions.json.
Document SF-779662
Biller Sample Supplier 8167 / As of 2026-05-13 / EUR
3 x Meter label @ 53,29 per unit
5 x Cable sleeve @ 33,11 per unit
2 x Carrier adjustment @ 172,40 per unit
Gross 757,35
Breakdown: net 670,22 and taxes 87,13.

SF-779662 · Mixed traces at two caps

Expected record
{ "invoice_id": "SF-779662", "issued_on": "2026-05-13", "supplier": "Sample Supplier 8167", "currency": "EUR", "line_items": [ { "description": "Meter label", "quantity": 3, "unit_minor": 5329 }, { "description": "Cable sleeve", "quantity": 5, "unit_minor": 3311 }, { "description": "Carrier adjustment", "quantity": 2, "unit_minor": 17240 } ], "subtotal_minor": 67022, "tax_minor": 8713, "total_minor": 75735 }
128 tokens
CALC 3 * 5329 + 5 * 3311 + 2 * 17240 = 67022 RECORD {"invoice_id":"SF-779662","issued_on":"2026-05-13","supplier":"Biller Sample Supplier 8167","currency":"EUR","line_items":[{"description":"Meter label","quantity":3,"unit_minor":5329},{"description":"Cable sleeve","quantity":5,"unit_minor":3311},{"description":"Carrier adjustment","quantity":2
256 tokens
CALC 3 * 5329 + 5 * 3311 + 2 * 17240 = 67022 RECORD {"invoice_id":"SF-779662","issued_on":"2026-05-13","supplier":"Biller Sample Supplier 8167","currency":"EUR","line_items":[{"description":"Meter label","quantity":3,"unit_minor":5329},{"description":"Cable sleeve","quantity":5,"unit_minor":3311},{"description":"Carrier adjustment","quantity":2,"unit_minor":17240}],"subtotal_minor":67022,"tax_minor":8713,"total_minor":75735}

The longer completion changes the next action on SF-779662. A reader who only sees the short generation should investigate the stop condition before retraining the model. The longer output exposes a separate source-field error. Stripping Biller is a possible parsing rule for a known layout, and it would need tests against a broader set of suppliers before use. Applying the rule unconditionally could discard part of a legitimate name. Save the completion and the matched source line whenever you separate response-budget errors from content errors.

Select the student against gold

The separate probability diagnostic uses a three-class classifier over deterministically counted visible lines. It deliberately gives every three-line invoice a teacher distribution of [0.035, 0.93, 0.035] over one, two and three lines. For example, the held-out SF-797533 lists Packing insert, Cooling filter and Rack inspection. Its gold vector is [0, 0, 1]. The teacher chooses two even though the feature exposes all three lines.

The pre-fit audit makes that fault visible. In training, teacher top-1 was 187/187 for one line, 195/195 for two and 0/194 for three. Gold validation recorded 9/9, 9/9 and 0/18, respectively. Novel test has 37, 27 and 32 records in those three classes, so every class has coverage. Fit the student with soft cross-entropy and retain epoch 0, a fixed gold-informed warm start, as a candidate checkpoint.

def soft_cross_entropy(logits, target):
    # Compute log probabilities in FP32 before applying the teacher targets.
    return -(target * torch.log_softmax(logits.float(), -1)).sum(-1).mean()
Lsoft=−1N∑i=1N∑c=13qiclog⁡softmax⁡(zi)c.\mathcal L_{\mathrm{soft}} = -\frac{1}{N}\sum_{i=1}^{N}\sum_{c=1}^{3} q_{ic}\log\operatorname{softmax}(z_i)_c .

Teacher agreement selected epoch 20. It agreed on all 36 validation invoices and missed all 32 novel three-line gold labels. Gold selection kept epoch 0, which got 32/32. The fitted hybrid used gold targets for the blind class and soft targets for the other two. Gold selection chose epoch 20, and that checkpoint also got 32/32. This is an instrumented demonstration of the evaluation trap. The invoice extractor's learned extraction quality is measured separately above. Hinton, Vinyals and Dean, soft-target objective

Agreement chose the checkpoint that copied the teacher’s blind spot

Validation selection by epoch and exact class counts on the novel test split

6
Teacher agreement and gold accuracy, soft-only training
0%50%100%05101520

Teacher agreement · Gold accuracy

SelectionEpoch1 line2 lines3 lines
Scripted teacher–37/3727/270/32
Teacher agreement2037/3727/270/32
Gold validation037/3727/2732/32
Hybrid, gold validation2037/3727/2732/32
Source · Lab 05, Tesla T4 · 05-soft-targets.json. Synthetic scripted teacher, visible row-count classifier.

Fit one positive temperature against gold negative log likelihood on 36 calibration invoices, with supplier families separate from selection and test. Divide logits by temperature, then recompute probabilities. Positive scaling preserves the class ranking. On the novel test set, expected calibration error (ECE) measures the mean absolute confidence–accuracy gap across ten confidence bins, weighted by bin size. The teacher-selected checkpoint's ECE fell from 21.4% to 18.2% and it still missed every three-line case.

Temperature scaling improved confidence calibration without repairing the wrong class

Novel test ECE in percent, using ten bins. Temperature fitted on 36 separate calibration invoices.

7
Selected checkpointTemp.ECE before → afterCalibration NLL before → after
Teacher agreement1.8821.4% → 18.2%0.956 → 0.820
Gold validation0.1054.8% → 1.3%0.794 → 0.013
Hybrid, gold validation0.1012.9% → 0.0%0.141 → 0.000
Source · Lab 05, Tesla T4 · 05-soft-targets.json. ECE displayed as percent.

The checkpoint and temperature each answer a different question. First pick a checkpoint by the action you need it to get right, such as sending a three-line invoice to the right queue. Then fit the confidence scale on a separate split if people or software will act on the score. Recheck the class breakdown after both steps. When the teacher assigns the wrong class in a systematic way, an apparently well-calibrated aggregate can still hide a broken routing decision. Also check the test roster before computing any averages. If a class is absent, mark its accuracy as unmeasured so a high aggregate cannot stand in for evidence about that class.

What to keep

DecisionEvidence to use
Retain familiar examples when coverage mattersMixed traces and Direct answers both got 25/25 familiar records right. Target-only traces got 0/25.
Use Direct answers as the control for a traceIt used the same ordered inputs as Mixed traces and got 16/45 difficult records right versus 14/45.
Select the classifier against goldThe teacher-agreement checkpoint missed all 32 three-line novel labels. Gold selection and the gold-override hybrid got 32/32.
Treat answer length as a separate controlThe longer cap recovered eight natural stops and one exact record on the matched subset.
  • Keep the printed total and checked arithmetic. The opening discrepancy matters to the reviewer, and the extractor should preserve the source amount.
  • Reject unverified targets before fitting. Check that a candidate finishes, that the arithmetic is present and correct, and that the record matches the fixture.
  • Track training exposure by group. A fixed update budget can shift familiar and difficult examples in opposite directions.
  • Grade validity and extraction separately. A parseable response can carry the wrong supplier name, quantity or total.
  • Select on the outcome a user needs. Use class-level gold checks before trusting teacher agreement or confidence calibration.
  • Next to try, not tested here: Enable the Equal-target diagnostic and compare the paired difficult and familiar records before changing the deployment candidate.

How it was built

ItemSetting
Base modelQwen2.5-0.5B-Instruct at revision 7ae557604adf67be50417f59c2c2f167def9a775.
DataSynthetic course-invoice-v1, seed 42. Independent fixture checks grade scripted teacher candidates.
Test45 difficult and 25 familiar invoices. Paired intervals resample supplier families. The release split stays reserved.
MethodDirect answers, Target-only traces and Mixed traces. A separate classifier uses counted lines for the probability diagnostic.
TrainingFrozen FP16 decoder, rank-8 LoRA with alpha 16 on q_proj, v_proj and o_proj. AdamW at 2e-4, 128 rows in batches of four per fit. The probability diagnostic uses SGD with an FP16 forward pass and FP32 loss arithmetic.
DecodingGreedy, up to 256 new tokens, batch size eight. The matched generation-cap check includes a 128-token arm.
HardwareTesla T4, PyTorch 2.14.1+cu130, Transformers 4.51.3, PEFT 0.15.2 and Accelerate 1.6.0.

Time and cost. Direct answers took 11.61 seconds at 5.23 GiB peak allocated, Target-only traces took 12.14 seconds at 5.72 GiB, and Mixed traces took 11.33 seconds at 5.70 GiB. These times cover the optimiser loops. Each saved adapter’s weight file is 3,557,696 bytes. The execution receipt records 432.866 seconds for the full notebook, including evaluation and the probability diagnostic.

Executed notebook · Run report · Candidate ledger and rosters · Raw predictions · Cap predictions · Class audit and calibration

Run it yourself

The saved execution took 432.866 seconds on the T4. Notebook section 2 matches Filter the proposed answers, section 3 matches Select the student against gold, and sections 4 and 5 match Count what the student sees. Sections 6 and 7 produce the paired invoice comparison and the generation-cap comparison. Predict the outcome before editing a cell, then inspect the named output.

  1. In section 2, predict which verifier flags a response that keeps the correct calculation but changes the total. Replace the accepted answer’s total_minor for SF-157375 with 115781 and inspect the rejection recorded in the candidate ledger or the assertion if the verified candidate is required.
  2. In section 3, predict which checkpoint the hybrid will select if every class gets teacher targets. Remove the gold override for three-line invoices, then inspect the selected epoch and novel test scores for that class before looking at ECE.
  3. In section 7, predict how a higher short cap affects natural stops and exact records. Change SHORT_CAP from 128 to 160 and check both measures on the matched output rows.

Continue with Lesson 06 · Test the training stack from the course outline.

How is this page?

Last updated on