13 · Adapt a model to a domain
Choose the current remittance source, test three adaptation objectives on the same records, and check invoice extraction before routing traffic.
- Part 3
- Adapt models
- Model
Qwen/Qwen2.5-0.5B-Instruct- Data
- Original vendor notes and policies linked to Course Invoice v1, with plausible distractors and missing-evidence cases
- Hardware
- Tesla T4, in Google Colab
Which code can you put on the payment instruction?
You handle vendor payments. A colleague asks for the current authorised remittance code for SF-781239. Three records show plausible codes. Choose the code and the record that authorises it. Picking the superseded code or the other invoice’s code could send the payment down the wrong route.
Policy records for SF-781239
Records in the order shown to the model
- P-952d16Superseded remittance entry for SF-781239. Old code REMIT-5E312D.
- P-4af262Current authorised remittance code for SF-781239 is REMIT-33C167.
- P-1c63bcCurrent remittance code for another invoice is REMIT-F80A8C.
Check the code, source and four recorded answers
The current entry for SF-781239 is REMIT-33C167 from P-4af262. The prompted checkpoint included the correct code inside a Markdown fence but left its source null. Only the RAFT-style adapter returned the complete answer in the required format on this question.
What is the current authorised remittance code for SF-781239?
- Expected
- {"answer":"REMIT-33C167","source_id":"P-4af262"}
- Prompted
- ```json { "answer": "REMIT-33C167", "source_id": null } ```
- Continued pretraining
- {"answer":"P-1C63BC"}
- Reading SFT
- {"answer":null,"source_id":null}
- RAFT-style SFT
- {"answer":"REMIT-33C167","source_id":"P-4af262"}
Distractor training improved exact answers when the record was present
Exact JSON answer and source ID · counts by evidence availability
1Current record present
Current record missing
1. Hold the evidence pack fixed
The question and all retrieved text stay fixed at evaluation time. Each arm gets the same current entry, superseded entry and unrelated entry when the answer is present. When the current entry is missing, the pack keeps the two distractors. The 48 questions cover 32 cases with current evidence and 16 without. The 96 training invoices, 48 policy cases and 24 extraction cases have disjoint invoice IDs, suppliers and layout families.
The setup isolates what the model does once evidence arrives. It says how well each checkpoint reads these prepared packs with greedy decoding and a 96-token cap. It leaves the quality of an upstream search system unmeasured. All 48 evaluation packs
Look at the two ways the opening case can go wrong. You can pick a code from the obsolete entry for SF-781239. The invoice matches, but the status makes the record unusable. Or you can pick the unrelated invoice's current code. The status matches, but the invoice doesn't. A useful verifier joins all the relevant facts in the same record. It doesn't search the pack for a correct identifier in one line and a plausible code in another.
The missing-record version keeps both ways to make that mistake available. That's a stronger test than an empty retrieval result. If the pack were empty, a model could learn to abstain whenever the input lacks documents. Here it must inspect evidence and decide whether any entry meets the request. For the payment desk, that distinction determines what happens next. An empty pack can go back to search for another attempt. A pack full of convincing but inadmissible records can need a policy or permissions check. The model's two nulls are the signal to stop normal processing in either situation.
We used disjoint suppliers and layout families because an invoice ID alone is too easy a holdout. A model can otherwise see a highly similar record at training time and reuse its layout or supplier cue. Follow the same idea if a support desk trains a model to cite the current version of an entitlement policy. Hold out policy families and the organisations that share a template. In each comparison, record the text handed to the model. If search changes as well, an improved answer can come from a better document pack or from greater care in reading it. A fixed pack lets you investigate the second effect.
2. Give each adapter a different job
A changing policy belongs in a current evidence source. Training can change the model's ability to read or apply that source, but should not be treated as a guarantee that its internal facts stay current.
The continued-pretraining adapter predicts the next token in raw policy text. Reading-comprehension SFT teaches a structured answer using the current entry when available. RAFT-style SFT teaches the same answer from a pack that also includes a superseded record and another invoice’s code. When evidence is missing, both supervised arms see distractors and learn the same two-null target.
Here is the notebook’s response construction. Only tokens in the response contribute to the supervised loss in the two SFT arms.
# Put the canonical answer and its end marker in the supervised span.
def domain_row(case):
prefix=domain_prompt(case)
response=tokenizer.encode(canonical_json(case.target),add_special_tokens=False)+[tokenizer.eos_token_id]
return split_turns([Turn(prefix,response)])[0]# Score the policy text itself rather than an answer to a lookup.
def cpt_row(invoice):
case=evidence_case(invoice,conflicts=True)
raw_text="\\n".join(content for _,content in case.documents)
sequence=tokenizer.encode(raw_text,add_special_tokens=False)+[tokenizer.eos_token_id]
if len(sequence)<2:
raise ValueError("Expected more than one token in a policy continuation.")
return MaskedSequence(sequence,[1]*len(sequence))For a token sequence, the mask identifies the positions scored by the objective. For policy continuation it covers all available next-token targets. For SFT it covers the response.
The two supervised adapters predicted the same number of tokens
48 completed optimiser updates per adapter
2| Training objective | Input tokens | Scored tokens |
|---|---|---|
| Continued pretraining | 6,862 | 6,766 |
| Reading SFT | 12,999 | 2,015 |
| RAFT-style SFT | 17,356 | 2,015 |
| Objective | Unpadded input tokens | Prediction targets | Updates completed |
|---|---|---|---|
| Continued pretraining | 6,862 | 6,766 | 48 |
| Reading SFT | 12,999 | 2,015 | 48 |
| RAFT-style SFT | 17,356 | 2,015 | 48 |
Think about what a wrong completion costs each arm. A continuation error occurs when the model assigns low probability to the next observed token. The loss has no special term for selecting an obsolete entry. In a reading example the model receives a different signal. It has to emit the answer and source that belong to the named invoice, with the evidence already present in the input. In the packed version, changing that answer to a distractor raises the loss on the output we care about. This is why the table shows both context and targets. Longer packs change what the model has to read, even when the supervised answer has exactly the same tokens.
The two SFT arms scored the same 2,015 tokens. RAFT-style prompts were longer, so they consumed 17,356 input tokens against 12,999 for reading SFT. The policy continuation arm used 6,766 prediction targets and is a different objective, even though all three arms ran 48 updates.
AdaptLLM’s finance prompting ablation reports better scores for reading-comprehension reformulations than for raw domain text. This lab tracks both held-out policy loss and task accuracy to see where improvement lands. The RAFT paper trains with useful and distracting documents and varies the distractor count. Here the answer contract uses a source ID and teaches an explicit null when the source is absent. AdaptLLM, Table 5 · RAFT, sections 4–5
BioMistral illustrates continued pretraining. The paper reports adapting Mistral on PubMed Central and evaluating medical question answering. It lists further supervised fine-tuning and direct preference optimisation for multilingual and chat behaviour as future work. FinGPT illustrates a different objective. Its authors derive sentiment labels from price changes following news and use those labels for a LoRA fit. For the payment desk, choose text pretraining when the problem is unfamiliar terminology. When the problem is selecting the current policy record, give the model examples that tie an answer to its source. BioMistral, §§3 and 6 · FinGPT, §3.3.1
3. Score the code and the source separately
The scorer requires bare JSON with exactly two unique keys, answer and source_id. Each value must be a string or null. On the 32 answered questions, continued pretraining found the code 5 times and the source 0 times. Reading SFT found the code 15 times and the source 5 times, giving 5 exact matches. RAFT-style SFT found both on 31. Its exact-match gain over the prompted checkpoint on that slice was 96.9 percentage points, with a 95% paired family-bootstrap interval of +90.6 to +100 points. That interval reflects resampling the held-out families, with a single training seed.
# Reject malformed or ambiguous objects before comparing fields.
def evidence_score(text, case):
def unique_object(pairs):
out = {}
for key, value in pairs:
if key in out:
raise ValueError("duplicate keys")
out[key] = value
return out
try:
value = json.loads(text, object_pairs_hook=unique_object)
except (ValueError, TypeError):
return {"valid": False, "answer": False, "evidence": False, "exact": False, "abstained": False}
valid = isinstance(value, dict) and set(value) == {"answer", "source_id"} and all(
item is None or isinstance(item, str) for item in value.values()
)
if not valid:
return {"valid": False, "answer": False, "evidence": False, "exact": False, "abstained": False}
return {"valid": True, "answer": value["answer"] == case.target["answer"],
"evidence": value["source_id"] == case.target["source_id"],
"exact": value == case.target, "abstained": value["answer"] is None and value["source_id"] is None}One useful adjudication question is whether you really want the fence around the answer to count as a failure. A person may read through it. A strict parser stops. Both are reasonable, provided the exact same rule is applied to every candidate and written down before comparing them. If your existing system strips fences, put that normaliser in the fixed evaluation path, record how often it intervenes and keep source verification after it. Look again at the opening prompted response. Removing the fence would still leave its source null. Format repair and evidence grounding solve different problems.
| Arm | Exact with current evidence | Abstained with current evidence | Exact when current evidence was missing |
|---|---|---|---|
| Prompted | 0/32 | 0/32 | 0/16 |
| Continued pretraining | 0/32 | 0/32 | 0/16 |
| Reading SFT | 5/32 | 14/32 | 16/16 |
| RAFT-style SFT | 31/32 | 1/32 | 16/16 |
The middle column explains why looking only at missing cases can mislead you. Reading SFT learned a useful response when the source was truly absent, and also withheld an answer on many questions that had the current record. Our comparison gives credit for both answering with evidence and stopping without it. A team that audits only its blocked payments would miss missed opportunities among payments with usable evidence. A team that audits only payments that went through would miss whether the model silently overlooked authorisation. Report both cohorts and, where you're testing the cost of a refusal, keep a record of which requests were passed to a person.
Continued pretraining lowered policy loss but solved no lookups
Mean negative log-likelihood · nats per held-out policy token
3Continued pretraining lowered held-out policy NLL from 3.65 to 2.05 nats per token. It still found zero complete answers with supporting evidence. RAFT-style SFT scored 3.67 nats on the same policy text and handled the structured lookup well. The two tests answer different questions.
Now try SF-177277. You still have a record for the right invoice and a current code. Check what each record authorises before returning either field.
Policy records for SF-177277
Records in the order shown to the model
4- P-97a33cSuperseded remittance entry for SF-177277. Old code REMIT-023C42.
- P-adc908Current remittance code for another invoice is REMIT-C51527.
Check the missing-record result
The correct response is null for both fields. The continued-pretraining adapter got the source field right by returning null, but treated the unrelated record ID as the answer. Across all 16 missing cases it matched the null source field 15 times and abstained zero times. Both supervised adapters abstained on all 16.
What is the current authorised remittance code for SF-177277?
- Expected
- {"answer":null,"source_id":null}
- Prompted
- ```json { "answer": "P-adc908", "source_id": null } ```
- Continued pretraining
- {"answer": "P-adc908", "source_id": null}
- Reading SFT
- {"answer":null,"source_id":null}
- RAFT-style SFT
- {"answer":null,"source_id":null}
Raw policy predictions and per-field scoring
4. Check the work the model already does
The existing task extracts an invoice record directly from ledger text. The prompted checkpoint matched 4 of 24 invoices exactly. Continued pretraining matched 3, reading SFT matched 1 and RAFT-style SFT matched 2. RAFT-style SFT lost 8.3 percentage points, with a 95% paired family-bootstrap interval of −20.8 to 0. The interval reaches zero, and all observed changes point to a retention risk worth replaying.
Every adapter lost exact matches on familiar invoice extraction
Exact records · same 24 held-out invoices across all arms
5The ledger still contains three charge lines
The direct extraction input for SF-173476
Sample Supplier 1460 | issued 2025-07-19 | invoice SF-173476 Ledger in EUR Service | Count | Per unit Carrier adjustment | 7 | 174,06 Rack inspection | 2 | 165,73 Packing insert | 2 | 215,76 Before tax 1 981,40 Tax charged 257,58 Balance 2 238,98
Extract SF-173476 as an invoice record
- Expected
- {"invoice_id":"SF-173476","issued_on":"2025-07-19","supplier":"Sample Supplier 1460","currency":"EUR","line_items":[{"description":"Carrier adjustment","quantity":7,"unit_minor":17406},{"description":"Rack inspection","quantity":2,"unit_minor":16573},{"description":"Packing insert","quantity":2,"unit_minor":21576}],"subtotal_minor":198140,"tax_minor":25758,"total_minor":223898}
- Prompted
- {"invoice_id":"SF-173476","issued_on":"2025-07-19","supplier":"Sample Supplier 1460","currency":"EUR","line_items":[{"description":"Carrier adjustment","quantity":7,"unit_minor":17406},{"description":"Rack inspection","quantity":2,"unit_minor":16573},{"description":"Packing insert","quantity":2,"unit_minor":21576}],"subtotal_minor":198140,"tax_minor":25758,"total_minor":223898}
- RAFT-style SFT
- {"invoice_id":"SF-173476","issued_on":"2025-07-19","supplier":"Sample Supplier 1460","currency":"EUR","line_items":[{"description":"Carrier adjustment","quantity":7,"unit_minor":17406},{"description":"Rack inspection","quantity":2,"unit_minor":16573}],"subtotal_minor":198140,"tax_minor":25758,"total_minor":223898}
For SF-173476, the adapted result retained the total and dropped the Packing insert row. An exact record check spots the omission even though the header and amount fields are correct. Together’s Kimi-to-Qwen case reports losing Thai performance during an initial Lao adaptation and evaluates both languages while tuning the recipe. That example motivates a separate extraction test here. Together experiment · Raw extraction predictions
Look at the expected row in the extraction example before deciding which score should determine release. Correct totals can coexist with incomplete line items. If a downstream reconciliation uses the rows, it may accept the overall invoice amount and still assign the wrong spend to a stock record or a cost centre. The right field-level diagnostic depends on that downstream consumer. Keep exact record accuracy as the gate for an automated write and use per-field and row scores to find the fault. Here the separate retention roster already demonstrates that lookup accuracy cannot stand in for row fidelity.
There are two reasonable ways to use the result. A routing layer can send lookup-only requests to a checkpoint with compact evidence packs while direct record extraction keeps its own parser and validation checks. Or a team can keep one checkpoint and train for both tasks. The first option makes the gate simple to enforce, although the router becomes part of what you need to test. The second is simpler to deploy, but it needs paired proof that the policy examples haven't damaged extraction. The saved experiment compares policy adapters with a fixed extraction benchmark. It doesn't test a combined training mixture or either production routing design.
What to keep
| Choice | What the saved results support | Decision at the payment desk |
|---|---|---|
| Prompted | The opening code was visible in the answer but the response was unusable under the schema. | Keep it as the starting comparison. |
| Continued pretraining | Policy-token NLL fell while exact supported lookup stayed at 0/32. | Use language loss to diagnose domain familiarity. |
| Reading SFT | Learnt the response contract and scored 16/16 on missing records. | Use it as a control for abstention and output format. |
| RAFT-style SFT | Reached 31/32 with current evidence, while direct extraction reached 2/24. | Consider it for lookup behind source validation. |
- Validate the citation. Check that the returned source ID authorises the returned code for this invoice.
- Keep hard distractors. Include an old entry for the right invoice and a current entry for the wrong invoice when you prepare an evidence pack.
- Count false refusals. Review abstentions where the current record was available and separate them from correct stops.
- Lock the retrieval output. Reuse the same evidence text and case roster whenever you compare checkpoints.
- Protect line-item extraction. Replay complete records even when the headline change affects only policy questions.
- Next to try, not tested here: compare paired evidence packs with more than one plausible source and require human reviewers to adjudicate authorisation.
How it was built
Fitting took about 20 seconds across the three adapters
Fit time and peak allocated GPU memory by training arm
6- Continued pretraining
- 6.26 s · 1.37 GiB
- Reading SFT
- 6.87 s · 1.79 GiB
- RAFT-style SFT
- 7.18 s · 2.05 GiB
| Item | Setting |
|---|---|
| Base model | Qwen2.5-0.5B-Instruct, revision 7ae557604adf67be50417f59c2c2f167def9a775 |
| Data | 96 generated training invoices |
| Test | 48 policy questions and 24 extraction invoices with disjoint keys, suppliers and families |
| Method | Continued pretraining on raw policy text, reading SFT on cleaner packs and RAFT-style SFT with distractors |
| Training | 48 completed updates per arm, seed 42, learning rate 0.0001, 540,672 trainable parameters per arm |
| Decoding | Greedy policy answers, up to 96 generated tokens |
| Hardware | Tesla T4 with FP16, Transformers 4.51.3 and PEFT 0.15.2 |
Time and cost. The full notebook took 275.40 seconds. Continued pretraining, reading SFT and RAFT-style SFT took 6.26, 6.87 and 7.18 seconds, with 1.37, 1.79 and 2.05 GiB peak allocated respectively. Each saved adapter's weights occupy 2,175,168 bytes in the verified export. The report records the full evidence pack digest, beginning ab5809f0ce58. Run report · Execution receipt
Run it yourself
Open the notebook in the facts box or download the exact notebook used on the T4. The notebook took 275.40 seconds on the recorded T4. Start with How do we keep retrieval fixed? for the evidence pack. How does task supervision differ from continued pretraining? builds the training rows. How should we read the evidence scores? exports the lookup breakdown and the separate extraction comparison.
- Predict how the scorer will grade the opening prompted response if you strip only the Markdown fence. Make that edit to the saved SF-781239 output and inspect
valid,answerandevidenceinevidence_score. - Predict whether the same adapter will still cite the right source when a different invoice's current code is listed first. Reorder just that record in the fixed pack and examine the paired prediction and exact source score.
- Predict whether restoring the omitted Packing insert row in the saved SF-173476 response is enough for an exact match. Insert only that row and inspect the extraction scorer's exact record and row scores.
How is this page?
Last updated on