15 · Release a document parser
Apply a locked release gate, test decoding speed and verify that you can restore the previous parser.
- Part 4
- Release
- Model
Qwen/Qwen2-VL-2B-Instruct- Data
- Course Invoice v1, page images with separately stored gold records. Separate locked release holdout and an independent synthetic invoice set at 446bab08662790cb39457792243bff5704373b95 (CC BY 4.0).
- Hardware
- Tesla T4, in Google Colab
Would you switch the parser today?
You approve invoice records before they go to accounts payable. Check the three printed rows, including one Meter label at USD 73.88, and the USD 992.85 balance. The candidate returns a JSON record with the right currency. Would you let that record through if the rows and payable still need checking?
Three lines on the source invoice
SF-750705 · synthetic release fixture

Compare the expected record with both adapter responses
Both adapters returned Item 1 and Item 2, omitted the Meter label and claimed USD 50,500.00 payable. The reward adapter completed generation and returned valid JSON with the expected shape. A payment-ready record would still be wrong.
SF-750705 · copy the printed fields and rows
- Expected record
- { "invoice_id": "SF-750705", "issued_on": "2025-09-01", "supplier": "Sample Supplier 1009", "currency": "USD", "line_items": [ { "description": "Grounding clip", "quantity": 4, "unit_minor": 10808 }, { "description": "Carrier adjustment", "quantity": 5, "unit_minor": 8434 }, { "description": "Meter label", "quantity": 1, "unit_minor": 7388 } ], "subtotal_minor": 92790, "tax_minor": 6495, "total_minor": 99285 }
- Supervised adapter
- {"invoice_id": "1234567890", "issued_on": "2022-04-15", "supplier": "ABC Company", "currency": "USD", "line_items": [{"description": "Item 1", "quantity": 10, "unit_minor": 1000000}, {"description": "Item 2", "quantity": 5, "unit_minor": 500000}], "subtotal_minor": 5000000, "tax_minor": 50000, "total_minor": 5050000}
- Reward adapter
- {"invoice_id": "1234567890", "issued_on": "2022-04-15", "supplier": "ABC Company", "currency": "USD", "line_items": [{"description": "Item 1", "quantity": 10, "unit_minor": 1000000}, {"description": "Item 2", "quantity": 5, "unit_minor": 500000}], "subtotal_minor": 5000000, "tax_minor": 50000, "total_minor": 5050000}
1. Freeze the release rules
Decide what would make a payment record safe to accept before comparing parser versions. Average field accuracy should not erase a failure on required rows, totals or other mandatory constraints.
Require at least 98% schema validity, 98% complete generations and 90% exact-and-complete records. A generation counts as complete when its last generated token is an end-of-sequence token. The generation limit is 220 tokens. An exact record must preserve the printed values and ordered rows. The two image adapters delivered valid and complete responses on 83 of 84 invoices, yet neither extracted a single exact record.
Both adapters passed the format gate and failed the accuracy gate
84 locked invoices per arm · count passing each check
1Release minimums · 98% valid · 98% stopped · 90% exact and complete
| Comparison | Schema-valid | Complete | Exact and complete |
|---|---|---|---|
| Text rules | 0/84 | No token generation | 0/84 |
| Prompted image model | 0/84 | 83/84 | 0/84 |
| Supervised incumbent | 83/84 | 83/84 | 0/84 |
| Reward candidate | 83/84 | 83/84 | 0/84 |
The opening invoice shows why this is a conjunctive gate. For payment, we'd need the payable and the rows on the same correct record. Counting a correct currency as a partial success is helpful when locating a fault. Counting it towards the release criterion would let a large amount error through. The completion check asks a different question. It can tell whether the model reached its end marker within budget, but a model can put its end marker immediately after a confidently wrong payable. Inspect the flags beside the raw record when you investigate an incident.
The rules baseline received fixture-generated verified text, while Qwen2-VL received pixels. The fixed text extractor looks for the literal header Description | Quantity | Unit price. The opening source text uses lines such as Meter label: 73.88 each for 1 units. The extractor produced no schema-valid records on the 84 fixtures. That result measures this extractor on the locked roster, with no generated-token completion check.
2. Give rows their own reward
The capstone gives a valid record a weighted reward for scalar-field accuracy, whole-row F1 and completion. Repeating or dropping a line changes the row multiset. The release guard separately compares the currency and row descriptions against verified fixture text. Its three rejection controls included a format-valid mutation that dropped the last row from SF-750705 while keeping the total. The guard rejected that control and all 84 recorded reward-adapter outputs. Production use would require a trusted source-text path.
# Count matching scalar fields and matching row tuples separately.
def training_reward(text, expected, complete):
observed=parse_record(text)
if observed is None:
return -0.5
scalar_fields=("invoice_id","issued_on","supplier","currency","subtotal_minor","tax_minor","total_minor")
field_score=sum(observed[k]==expected[k] for k in scalar_fields)/len(scalar_fields)
keys=("description","quantity","unit_minor")
rows=lambda r:Counter(tuple(item[k] for k in keys) for item in r["line_items"])
predicted,target=rows(observed),rows(expected)
f1=2*(predicted&target).total()/max(1,predicted.total()+target.total())
return 0.30*field_score+0.55*f1+0.15*int(complete)Centre and scale each reward using the mean and population standard deviation of its three-response group.
Skip a group when the reward spread is at most 10⁻⁸, including when all rewards tie. For example, SF-252566 produced 124, 102 and 158 tokens and rewards about 0.15, 0.19 and −0.50. The notebook used two clipped-policy updates for this group.
Five reward groups could distinguish the samples
Three sampled completions per development invoice · two updates for every non-tied group
2The scorer gives partial credit on a row multiset. If an output repeats a description with an incorrect quantity, the tuple for that row changes. The repeated row contributes fewer matches against the printed list, and it still counts in the size of the prediction. However, a multiset ignores order, while the release metric requires it. Imagine two exactly copied items in the reverse order. The reward can still credit their content. A procurement system that reconciles against ordered line positions will still reject the record. This is a concrete way to make a training signal easier to learn while keeping the operational decision stricter.
Check the saved reward groups before proposing a longer fit. In the resource probe, all three forced-width responses scored −0.50. To test the cost of an update at that width, the notebook supplied diagnostic advantages independently of the actual rewards. The reported preflight therefore tells you the longest chosen update path fit on the device. It doesn't tell you that a model got any learning signal from those three completions. The subsequent scored fit uses the real invoice rewards. Keep its skip rule and metrics when you compare changes to the objective, because a recipe can become more selective while producing fewer updates.
DeepSeekMath uses group-relative advantages in a clipped objective that includes a reference penalty. This capstone uses the group-relative idea with a reference-free objective and invoice-specific scores. DeepSeekMath §4.1
Ai2’s Tülu 3 405B recipe starts with curated data, applies supervised fine-tuning and preference optimisation, then trains selected skills against verifiable rewards and runs a standardised evaluation. Here the locked invoice roster, the supervised checkpoint and the field-and-row verifier play analogous roles. The earlier training-stack lesson tests preference optimisation separately. In its document-specific recipe, NVIDIA describes supervised training for text, tables and charts, followed by verifier-based reward training and a separate DFlash2 decoding comparison. The invoice release follows that separation with its own strict extraction gate and prompt lookup parity check. Training-stack experiment · Ai2’s Tülu 3 405B release · NVIDIA’s Nemotron 3.5 Parse recipe
3. Check slices and transfer
Before computing a paired pass@1 difference, record whether each rollout produced a response that could be graded. A response that hits the configured token cap or returns invalid JSON is a model outcome under that budget. A lost connection, failed notebook process or missing fixture is an infrastructure fault. Keep that fault visible and replay the affected pair with identical input, seed and budget. If a pair remains unresolved, report the missing coverage and hold the release. For a partial comparison, give the denominator of pairs that completed in both arms.
The supervised and reward adapters both scored 0/84 exact, a paired difference of 0 percentage points with a 95% family-bootstrap interval of [0, 0] across 10 families. Every pair failed the exact check, so resampling those families still yields zero difference. The release rule also capped per-slice regressions at three points where a slice had at least 30 records.
Only the two locale slices were large enough for the regression gate
Reward adapter minus supervised adapter · slice minimum n = 30
3The decimal-comma and decimal-point groups had 34 and 50 invoices respectively, so both reached the slice gate's minimum. Their change in exactness was zero points. An equal score can be useful for a regression guard when the incumbent is already strong. Here zero is a hard floor. This result cannot reassure you about either locale. To find where the format breaks, inspect the parsed money fields and their raw source strings separately for each locale. Review differences such as a thousands separator read as a decimal separator before deciding whether to change encoding, preprocessing or the training examples.
A scanned purchase invoice can also be legible to a reviewer while its layout differs sharply from the training catalogue. The external comparison treats those documents as a separate check on the common fields. If a benchmark omits quantity labels, scoring the model against guessed quantities would confound parser quality with label quality. On the other hand, passing common headers would still leave line-item extraction untested. Keep a dedicated test with reliable row annotations if a later release decision depends on stock or project coding.
The four external benchmark PDFs provide a separate header-only transfer check. Both corpora label currency and totals, but the full course record also requires quantities and unit prices. The raw US response starts with invoice ID 123456 and uses USD, but a stray closing bracket in the first row makes the JSON invalid, so the strict scorer gives no credit for the currency mention. The source answer is ACM-100145 and USD 372.49, or 37,249 cents. Pinned benchmark label
The candidate missed the total on all four external invoices
Strict parsed header matches on four pinned PDFs
4
clean-us-clean-simple · four scored headers
- Expected headers
- { "invoice_id": "ACM-100145", "supplier": "Acme Industrial Supply Co", "currency": "USD", "total_minor": 37249 }
- Raw reward adapter
- {"invoice_id": "123456", "issued_on": "2022-04-15", "supplier": "Acme Industrial", "currency": "USD", "line_items": [{"description": "Heavy-duty steel washers (pack of 200)", "quantity": 2, "unit_minor": 320000]}, {"description": "Threaslide adhesive, blue, 10ml", "quantity": 6, "unit_minor": 130000}], "subtotal_minor": 320000, "tax_minor": 640000, "total_minor": 960000}
4. Test speed on the same weights
Prompt lookup proposes continuations from matching token sequences already present in the prompt. The notebook alternated greedy and lookup order over six requests, kept the checkpoint fixed and required identical generated token IDs and a complete response on both paths. Median latency fell by 2.34 seconds. With only six observations, nearest-rank p95 selects the slowest request in each arm.
Prompt lookup preserved every token in six complete responses
Same checkpoint · alternating run order · seconds per page
510.80 s median
12.82 s nearest-rank p95
0.089 pages per GPU-second
8.46 s median
10.57 s nearest-rank p95
0.113 pages per GPU-second
# Synchronise the device around generation and compare the whole token sequence.
def latency_report(model):
jobs=[cap_item(row) for row in Q]
if rl_record["steps"]==0:
disposition="no policy gradient signal"
else:
disposition="completed"
try:
generate_vision(model,processor,jobs[0],max_new_tokens=MAX_TOKENS)
generate_vision(model,processor,jobs[0],max_new_tokens=MAX_TOKENS,prompt_lookup_num_tokens=4)
except (AttributeError, TypeError, ValueError, NotImplementedError) as exc:
return {"status":"unsupported","reason":str(exc),"training":disposition}
trial=[]
for index,item in enumerate(jobs):
results={}
settings=[("greedy",{}),("lookup",{"prompt_lookup_num_tokens":4})]
if index%2:
settings.reverse()
for label,kwargs in settings:
torch.cuda.synchronize()
started=perf_counter()
output=generate_vision(model,processor,item,max_new_tokens=MAX_TOKENS,**kwargs)
torch.cuda.synchronize()
results[label]={"seconds":perf_counter()-started,"tokens":output["tokens"],
"complete":output["complete"]}
trial.append({"key":item.key,"matches":results["greedy"]["tokens"]==results["lookup"]["tokens"],"results":results})
if not all(r["matches"] for r in trial):
return {"status":"parity_failed","pairs":trial}
if not all(out["complete"] for row in trial for out in row["results"].values()):
return {"status":"incomplete_output","pairs":trial}
durations={name: sorted(row["results"][name]["seconds"] for row in trial) for name in ("greedy","lookup")}
return {"status":"parity_passed","cases":len(trial),"pairs":trial,
"p50_seconds":{k:statistics.median(a) for k,a in durations.items()},
"p95_nearest_rank_seconds":{k:a[-1] for k,a in durations.items()},
"pages_per_gpu_second":{k:len(a)/sum(a) for k,a in durations.items()}}| Serving measure | Greedy | Prompt lookup |
|---|---|---|
| Median seconds per request | 10.80 | 8.46 |
| Nearest-rank p95 seconds per request | 12.82 | 10.57 |
The paired design answers a narrow question about decoder substitution. If you changed the image resolution as well, fewer prompt tokens might reduce latency and make small text harder to read. Token equality would then be a different test. Keep resolution, weights and stop settings fixed when measuring the decoder. Load testing would need its own queueing and concurrency boundary. The timed loop measures one request at a time and calls device synchronisation around each decode.
Leviathan and colleagues used a separate draft model for speculative decoding. Transformers prompt lookup instead proposes from the existing prompt. The parity check here establishes an equivalent response for the six measured requests. The quality gate still holds the candidate. Speculative decoding paper · Transformers prompt lookup
5. Rehearse the rollback
The notebook verified the Lab 08 input and executed notebook hashes, the ordered training feature manifest and the adapter weight hash. It compared the regenerated greedy tokens for SF-228794 with Lab 08's saved tokens before training. After benchmarking, a fresh base plus the saved incumbent adapter and greedy configuration reproduced the earlier response for SF-750705. This check proves the saved checkpoint can be restored on that fixture. The incumbent response still fails the extraction gate.
The restored supervised checkpoint reproduced the saved response
Two token checks on two recorded requests
6Lab 08 → capstone · anchor SF-228794 · token match
Fresh reload of saved incumbent · SF-750705 · token match
Incumbent adapter SHA-256 592bbf3309b83409b446f8a0d5bcadff086a6d77eabd3f08a7b23c47565ad71c
# Check the restored weights and settings before repeating the incumbent fixture.
restored=PeftModel.from_pretrained(load_vision_base(trainable=True),incumbent,is_trainable=False).eval()
restored_config=json.loads(Path("15_incumbent_serving.json").read_text())
assert restored_config["model"]==VISION_MODEL and restored_config["revision"]==VISION_REV
assert restored_config["max_pixels"]==VISION_MAX_PIXELS and restored_config["decoding"]=="greedy"
assert hashlib.sha256((incumbent/"adapter_model.safetensors").read_bytes()).hexdigest()==restored_config["adapter_sha256"]
restored_tokens=generate_vision(restored,processor,fixture,max_new_tokens=restored_config["max_new_tokens"])["tokens"]
require_token_parity(fixture,fixture.key,incumbent_tokens,restored_tokens)Save the complete serving configuration with the weights. If you roll back the adapter but keep a later image pixel budget or generation cap, you may still serve a different token sequence. Use a known replay with an expected sequence to catch that case. At a payment desk, rollback stops the release from changing the parser further. It doesn't establish that the restored parser is accurate enough to write payments automatically. Retain the earlier review route for any record that cannot be verified.
What to keep
| Option | Evidence | Release decision |
|---|---|---|
| Supervised incumbent | Weights and token output were restored, but exact extraction was at the floor. | Keep the artefact and its review route available. |
| Reward candidate | Passed validity and completion, failed exact-and-complete extraction. | Hold the candidate. |
| Prompt lookup | Matched greedy token IDs on all six timed requests. | Consider it as a separate serving change once the parser meets its quality gate. |
- Lock the scoring roster. Keep release invoices out of adapter training and separate from development examples.
- Require complete, correct records. Keep a printed payable and its ordered rows together in the exactness check.
- Track reward spread. Distinguish the cost of an update from the availability of a learning signal.
- Review the locale slices. Inspect raw money fields when exact accuracy is at the floor.
- Gate decoding changes separately. Check full token equality and end-of-sequence completion before attributing a speed gain.
- Rehearse configuration rollback. Check the adapter digest, pixel budget and token cap along with the replay output.
- Next to try, not tested here: prepare a development set annotated for confusion between subtotal and payable, then test whether training on it improves those fields on a separate roster.
How it was built
| Item | Setting |
|---|---|
| Base model | Qwen2-VL-2B-Instruct, revision 1860c46f12b7449d0f5b426a7474ab715342bc65 |
| Data | Lab 08's 72 generated invoices and 24 charts for supervised tuning, eight distinct development invoices for reward training |
| Test | 84 locked release invoices over 10 families, four external PDFs for a header-only check |
| Method | NF4 weights with FP16 compute, then group-relative clipped policy updates on the verified Lab 08 handoff |
| Training | Seed 42, 32 supervised updates in the handoff and 10 reward updates in the capstone |
| Decoding | Greedy with 220 new tokens. Serving probe used four prompt-lookup proposal tokens. |
| Hardware | One Tesla T4, Torch 2.14.1+cu130, Transformers 4.51.3, PEFT 0.15.2 and bitsandbytes 0.50.2 |
Time and cost. The execution receipt reports 3,774.353 seconds, about 62.91 minutes. The one-update preflight took 68.76 seconds and reserved 3.28 GiB. The reward fit took 359.21 seconds and peaked at 2.69 GiB allocated. Each adapter's saved weights occupy 4,372,840 bytes in the verified export. Full release report · Run receipt · Saved serving configuration
Run it yourself
Open the notebook from the facts box or download the exact T4 input. The recorded notebook took 62.91 minutes on a T4. To reproduce the Lab 08 comparison, download and extract the verified Lab 08 handoff ZIP in the notebook environment, then point LAB08_HANDOFF_DIR at the directory containing the receipt, executed notebook and adapter. For an independent fit, LAB15_STANDALONE_REFIT=1 rebuilds the supervised adapter. That mode cannot reproduce the paired Lab 08 handoff.
Read What would warrant a release? for the locked gates, then Which outputs fool a usable-looking verifier? and Does an image-based reward help? for the reward. Will speculative decoding preserve the answer? runs the serving comparison. Can the earlier parser be restored? produces the rollback proof and release report.
- Predict which checks will still pass if you remove the last item from the saved correct SF-750705 record but keep the payable. Change only that row and examine the score from
training_rewardand the decision fromverified_source_guard. - Predict whether changing only the proposal width from four to one alters the response. In
latency_report, change the prompt lookup proposal width and inspect the token comparisons, completion flags and paired latency fields. - Predict what the rollback check will report if you change the saved token cap while reusing the exact adapter. Change that cap in the restored configuration for a copy of the fixture replay and compare the generated token sequence with the saved incumbent tokens.
How is this page?
Last updated on