Skip to Content
Recodocs

08 · Extract tables and charts

Check whether a vision adapter copies line items, chart labels and printed totals accurately enough for a payable review.

12 min read
Part 3
Adapt models
Model
Qwen/Qwen2-VL-2B-Instruct
Data
Course Invoice v1, page images with separately stored gold records. Original spend-chart renders are a separate transfer set.
Hardware
Tesla T4, in Google Colab

Can you post this payable?

You are checking a synthetic invoice before entering it into the payables queue. The printed balance says USD 1,219.65. The two amounts above it add to USD 1,218.64. Which value belongs in the extraction record? Which value would you authorise for payment? Then read the spend chart from top to bottom and check whether it follows the invoice’s row order.

The printed balance and the reversed spend chart

SF-862677 · original synthetic course fixture

Invoice text and balance

Invoice SF-862677 showing subtotal 1,138.92, tax 79.72 and a printed payable of 1,219.65.

Spending before tax

Grounding clip at 273.72 appears above Bench calibration at 865.20.
Invoice rerendered from the notebook’s fixture code. The chart is cropped to its labels and bars. Open either image to inspect it.
Check the expected records and both model outputs

Copy the printed total_minor: 121965 into the extraction record and flag the USD 1.01 discrepancy for review before payment. The chart starts with Grounding clip at USD 273.72, then shows Bench calibration at USD 865.20.

SF-862677 · novel invoice

Expected
{ "invoice_id": "SF-862677", "issued_on": "2025-08-20", "supplier": "Sample Supplier 3177", "currency": "USD", "line_items": [ { "description": "Bench calibration", "quantity": 6, "unit_minor": 14420 }, { "description": "Grounding clip", "quantity": 3, "unit_minor": 9124 } ], "subtotal_minor": 113892, "tax_minor": 7972, "total_minor": 121965 }
Rules · verified text
null
Frozen Qwen
```json { "invoice_id": 123456, "issued_on": "2022-04-15", "supplier": "ABC Company", "currency": "USD", "line_items": [ { "description": "Item 1", "quantity": 10, "unit_price": 10.50, "unit_price": 10.50, "total_price": 105.00, "tax": 1.00, "total": 106.00 }, { "description": "Item 2", "quantity": 5, "unit_price": 15.00, "unit_price": 15.00, "total_price": 75.00, "tax": 1.00, "total": 76.00 } ] } ```
LoRA Qwen
{"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": 500000, "tax_minor": 50000, "total_minor": 500000}

SF-862677 · reversed spend chart

Expected
{ "currency": "USD", "rows": [ { "description": "Grounding clip", "line_total_minor": 27372 }, { "description": "Bench calibration", "line_total_minor": 86520 } ] }
Frozen Qwen
```json [ { "description": "Total before tax per line item", "line_total_minor": 100 }, { "description": "Tax", "line_total_minor": 10 }, { "description": "Total after tax per line item", "line_total_minor": 110 } ] ```
LoRA Qwen
{"currency": "USD", "rows": [{"description": "Total before tax per line item", "line_total_minor": 1000000000000000000}]}

Neither pixel model recovered a complete invoice

Exact records per layout slice · 24 invoices per slice

1

familiar

Rules · verified text6/24
Frozen Qwen0/24
LoRA Qwen0/24

novel

Rules · verified text0/24
Frozen Qwen0/24
LoRA Qwen0/24

independent

Rules · verified text0/24
Frozen Qwen0/24
LoRA Qwen0/24
Source · Saved Lab 08 outputs from one Tesla T4. The paired family bootstrap returned 0 pp [0, 0] on each slice because both pixel models missed every record.

1. Compare inputs before you compare systems

The rules receive verified text from the fixture engine, so they do not pay an OCR penalty. Both Qwen variants get the same rendered pixels and extraction instruction. The familiar slice uses known layout types with held-out supplier families. Novel and independent refer to other layout groups within the same synthetic catalogue. The independent slice prints its rows as quantity-first descriptions and its payable as “Gross”. The novel slice uses packing and remittance layouts.

These two documents demonstrate the spread. On the familiar invoice, the verified-text rules get the complete record right. On the independent invoice, the same rules emit no record. Both Qwen variants miss both records. Open the images to read the row labels and compare the raw responses with each expected record.

Held-out familiar-layout invoice SF-228794, payable 1,782.53.Independently formatted invoice SF-830444 with a printed gross of 1,517.14.

SF-228794 · familiar invoice

Expected
{ "invoice_id": "SF-228794", "issued_on": "2026-03-21", "supplier": "Sample Supplier 1597", "currency": "USD", "line_items": [ { "description": "Mounting plate", "quantity": 8, "unit_minor": 1195 }, { "description": "Packing insert", "quantity": 6, "unit_minor": 21634 }, { "description": "Cooling filter", "quantity": 4, "unit_minor": 6807 } ], "subtotal_minor": 166592, "tax_minor": 11661, "total_minor": 178253 }
Rules · verified text
{ "invoice_id": "SF-228794", "issued_on": "2026-03-21", "supplier": "Sample Supplier 1597", "currency": "USD", "line_items": [ { "description": "Mounting plate", "quantity": 8, "unit_minor": 1195 }, { "description": "Packing insert", "quantity": 6, "unit_minor": 21634 }, { "description": "Cooling filter", "quantity": 4, "unit_minor": 6807 } ], "subtotal_minor": 166592, "tax_minor": 11661, "total_minor": 178253 }
Frozen Qwen
```json { "invoice_id": 123456, "issued_on": "2022-04-15", "supplier": "ABC Company", "currency": "USD", "line_items": [ { "description": "Item 1", "quantity": 10, "unit_minor": "EA", "subtotal_minor": 100, "tax_minor": 10, "total_minor": 110 }, { "description": "Item 2", "quantity": 5, "unit_minor": "EA", "subtotal_minor": 50, "tax_minor": 5, "total_minor": 55 } ] } ```
LoRA Qwen
{"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": 500000, "total_minor": 5000000}

SF-830444 · independent invoice

Expected
{ "invoice_id": "SF-830444", "issued_on": "2025-12-23", "supplier": "Sample Supplier 8052", "currency": "USD", "line_items": [ { "description": "Meter label", "quantity": 2, "unit_minor": 7999 }, { "description": "Cable sleeve", "quantity": 8, "unit_minor": 15712 } ], "subtotal_minor": 141694, "tax_minor": 9919, "total_minor": 151714 }
Rules · verified text
null
Frozen Qwen
```json { "invoice_id": 123456, "issued_on": "2022-04-15", "supplier": "ABC Company", "currency": "USD", "line_items": [ { "description": "Item A", "quantity": 10, "unit_minor": "EA", "subtotal_minor": 100, "tax_minor": 10, "total_minor": 110 }, { "description": "Item B", "quantity": 5, "unit_minor": "EA", "subtotal_minor": 50, "tax_minor": 5, "total_minor": 55 } ] } ```
LoRA Qwen
{"invoice_id": "Original synthetic course fixture", "issued_on": "2023-04-15", "supplier": "Syllable", "currency": "EUR", "line_items": [{"description": "Original synthetic course fixture", "quantity": 1, "unit_minor": 1000000}], "subtotal_minor": 1000000, "tax_minor": 1000000, "total_minor": 2000000}

Keep the input boundary visible when you present the comparison to a team that already pays for OCR. If the rule engine receives approved text from a separate system, the measured rule scores help you reason about parsing after that system. They leave its upstream errors outside the measurement. If all you have is an image, a realistic comparison needs the rule engine to consume transcripts from a fixed recogniser. A line break in the wrong place could change the rule result even when the underlying invoice layout is familiar.

The rendered independent invoice shows the other dependency. Changing the order of quantity and description, or moving the marker to “Gross”, can break rules with a perfect transcript. Build an exception queue with the original page and the specific field the parser could not recover. A system that emits no valid record leaves a clear opportunity for such a review path. A model that emits a plausible but fabricated record needs verification at the field level before it can take the same route.

2. Grade the field, row and position separately

An amount can be transcribed correctly but attached to the wrong line item. Keep field accuracy, row identity and position separate so the result reflects the record a person would actually use.

Schema validity checks the keys and data types. Exact extraction also requires the correct printed fields and correctly ordered rows. Whole-row F1 matches complete rows regardless of order. Positional cell F1 compares each description, quantity and unit amount with its counterpart at the same row position. With M aligned cells matching, G expected cells and P predicted cells, the notebook scores:

F1,cell=2MG+PF_{1,\mathrm{cell}}=\frac{2M}{G+P}

In the opening invoice, the adapter returned two rows, just as the expected record does. One says “Item 1”, quantity 10, with a unit amount of 1,000,000 cents. The first printed row is “Bench calibration”, quantity 6, at 14,420 cents. The adapter scored zero both for row F1 and for positional cell F1 on that invoice, despite returning valid JSON for the contract.

The format improved. The rows still failed.

LoRA Qwen · 24 invoices per slice · percentages or F1 × 100

2

familiar

Schema validity95.8%

Whole-row F10.0

Positional cell F11.4

novel

Schema validity100.0%

Whole-row F10.0

Positional cell F12.1

independent

Schema validity95.8%

Whole-row F10.0

Positional cell F13.1

Source · Saved Lab 08 outputs from one Tesla T4. Derived means from the saved per-invoice scores. Frozen Qwen scored zero on every measure shown.
Invoice comparisonValid recordsExact records
Frozen Qwen with pixels0/720/72
LoRA Qwen with pixels70/720/72

The table is a pairing of schema checks and complete-record checks on the same held-out inputs. It helps a reviewer decide whether the problem is integration or extraction. The masked fit mostly cleared the structural gate. It didn't clear the gate for values. The following function shows where a correctly copied value can still lose positional credit.

# Compare each field with the field in the same row position.
def invoice_metrics(text, invoice):
    metrics = score_record(text, invoice)
    observed = parse_record(text)
    expected = invoice_record(invoice)["line_items"]
    predicted = observed["line_items"] if observed else []
    columns = ("description","quantity","unit_minor")
    matches = sum(gold[name] == guess[name]
                  for gold, guess in zip(expected, predicted) for name in columns)
    metrics["cell_f1"] = 2 * matches / (len(columns) * (len(expected) + len(predicted)))
    return metrics

Keep a cell-level diagnostic even if your ledger accepts an unordered collection of rows. A row match can survive a reorder and may therefore be sufficient for a downstream total. Positional cells help diagnose a parser that assigns a quantity to an adjacent item or follows its usual order instead of the current layout. For a human reviewer, the two views help distinguish a simple reorder from an amount being detached from its description. Returning both counts to the reviewer gives them a clue about where to look on the page.

The PubTables-1M paper distinguishes locating a table, recognising its rows and columns, and identifying which cells act as keys or values. It also standardises how ambiguous spanning cells are represented in the target. In this lab, explicit row order and separate row and cell scores make it possible to identify the same kind of ambiguity before a misplaced value reaches a ledger. PubTables-1M, primary paper

3. Train on the response tokens

Generate each target from the underlying invoice record. A table row uses description, quantity and unit amount. The chart uses the line total before tax, computed from the same quantity and unit amount, in the rendered order. The notebook builds a pool of 72 invoice examples and 24 chart examples, then shuffles it once with seed 42. The scored fit takes the first 64 examples in that order.

NVIDIA reports releasing 9.98 million synthetic chart examples and one million rendered HTML table examples used to train Nemotron 3.5 Parse. These image-and-target pairs illustrate the same supervision pattern at a different scale. The release covers a broader set of visual tasks and uses a different evaluation. NVIDIA training-data and recipe report

The image and the extraction instruction are inputs to every training example. The notebook encodes the input again with the expected response appended and checks that the expanded prompt is the same. The prefix stays visible to the model, while only the response contributes targets to the loss.

# Keep the image and instruction visible while supervising the answer.
prompt = encode_image(processor, item)
full = encode_image(processor, item, item.answer)
labels = full["input_ids"].clone()
prefix = prompt["input_ids"]
width = prefix.shape[1]

if width >= labels.shape[1] or not torch.equal(labels[:, :width], prefix):
    raise ValueError(f"Chat template changed its expanded image prefix for {item.key}.")
labels[:, :width] = -100
if not torch.any(labels[:, width:] != -100):
    raise ValueError("The prompt mask removed the entire target.")

Training loss fell while held-out exact scores stayed at zero

Mean supervised loss per optimiser update · 32 updates · two examples per update

3
1.01.21.41.618162432
Source · Saved Lab 08 outputs from one Tesla T4. Shown on the training examples only. The separate preflight update is excluded.

Loss starts at 1.51 and ends at 1.22 on the training examples. The held-out invoice scores in Figure 1 show what the loss cannot tell you. The format changed, but the parser still missed every complete record.

4. Read the chart in the order it appears

The chart renderer reverses the displayed rows and changes the bar colour for the held-out variant. On SF-862677, Grounding clip moves above Bench calibration, with its amount still attached. The opening comparison shows that the adapter instead writes a chart subtitle as a row label and assigns it an amount of 1000000000000000000 cents.

Reversed charts produced 18 valid records and no exact reads

24 held-out labelled charts · 8 supplier families

4

Frozen Qwen

0/24 valid · 0/24 exact

0 matched labels · 22 completions below the limit

LoRA Qwen

18/24 valid · 0/24 exact

0 matched labels · 22 completions below the limit

Source · Saved Lab 08 outputs from one Tesla T4. No expected label matched either system’s predictions. Mean amount error is undefined.

The grader averages amount error only where a predicted label matches an expected one. Neither system matched any of the labels on the 24 charts, so this metric is unavailable for both. All 24 charts still count in the exact score. The paired difference was 0 points with a 95% interval of [0, 0] because every pair was a miss. These results describe the reversed-render slice under the tested recipe. The lab did not run a same-chart original-order control.

Reordered chart comparisonExact chartsCharts with a matched label
Frozen Qwen0/240/24
LoRA Qwen0/240/24

An amount-only aggregate would conceal the coverage problem. The notebook checks the response shape, rejects duplicate labels and only charges an amount error against a matching label. Keep the coverage column beside error summaries if you use the same method for another document collection.

# Score each amount only when its printed label has a counterpart.
def chart_score(text, target):
    gold=json.loads(target)
    try:
        value=json.loads(text,object_pairs_hook=_strict_dict)
    except (TypeError,ValueError):
        return {"valid":False,"exact":False,"amount_error_minor":None}
    if (not isinstance(value,dict) or set(value)!={"currency","rows"}
            or type(value["currency"]) is not str or not isinstance(value["rows"],list)):
        return {"valid":False,"exact":False,"amount_error_minor":None}
    if any(not isinstance(row,dict) or set(row)!={"description","line_total_minor"} or
           type(row["line_total_minor"]) is not int or type(row["description"]) is not str for row in value["rows"]):
        return {"valid":False,"exact":False,"amount_error_minor":None}
    descriptions = [row["description"] for row in value["rows"]]
    if len(descriptions) != len(set(descriptions)):
        return {"valid":False,"exact":False,"amount_error_minor":None}
    by_name={row["description"]:row["line_total_minor"] for row in value["rows"]}
    errors=[abs(by_name[row["description"]]-row["line_total_minor"])
            for row in gold["rows"] if row["description"] in by_name]
    return {"valid":True,"exact":value==gold,"matched_labels":len(errors),"amount_error_minor":sum(errors)/len(errors) if errors else None}

That scoring decision matters in a spend report. If the output contains a rounded amount that coincidentally appears on another bar, numerical proximity gives the reviewer false reassurance. Match the label first, then check the attached figure and displayed order. If the label never appears, report the missing match explicitly. Reverse rendering is useful for checking position dependence, but the saved evaluation changed the bar colour as well. A follow-up should vary only the order if the team wants to isolate that mechanism.

ChartQA uses human-written and generated questions to test both reading chart values and reasoning over them, such as computing a difference across plotted series. The notebook’s chart task asks for labelled amounts in order. A reasoning test needs its own questions and reference answers. ChartQA, primary paper

5. Preserve the printed payable

The opening invoice illustrates two separate checks. First, extract the printed amount accurately. Then reconcile the extracted fields and route discrepancies for review. The rules returned no valid record for this layout. Frozen Qwen returned an example-shaped response without a top-level payable. LoRA Qwen returned total_minor: 500000, which would enter USD 5,000.00 if schema validity alone allowed the record through.

The printed payable and the arithmetic differ by USD 1.01

SF-862677 · amounts in USD

5

Printed payable

1,219.65

Subtotal + tax

1,218.64

LoRA Qwen output

5,000.00

Source · Saved Lab 08 outputs from one Tesla T4. Printed fields from the independent reference record. The arithmetic is derived. The LoRA total is from its saved completion.

A reconciliation rule can compare cents directly after validating the record. It would flag the genuine USD 1.01 difference in the expected record. A fabricated record can still balance, so reconciliation cannot substitute for checking the extracted fields against the source.

A payables form gives the extraction model a narrow job. It copies the visible value and keeps the source available. A separate check interprets whether the result should post, be corrected by a reviewer, or go back to the supplier. Treat the discrepancy in the opening invoice as part of the input rather than an inconsistency to repair while copying. A parser that silently repairs the arithmetic removes the evidence the reviewer needs. Conversely, an arithmetically balanced model output can pass a reconciliation check despite containing values that are nowhere on the page.

If you extend the evaluation to a production AP queue, track the exact payable and currency as independent gates before measuring how many reviews automation could save. Record what the reviewers did with bad amounts and with abstentions. A comparison of operational cost needs both, because missing extraction creates manual work and a plausible wrong amount may create a duplicate review or a payment incident. The synthetic comparisons here show where those failures can occur. They give no production incident rate.

What to keep

OptionWhat the comparison supportsWhat still needs review
Verified-text rulesUse as a parser baseline on layouts it knowsEvaluate against the actual OCR input and the layouts outside the template.
Frozen QwenKeep as the pixel controlGuard against example-shaped outputs and missing fields.
LoRA QwenKeep a reproducible checkpoint for structured outputCheck every value against the page before payment.
  • Require exact held-out records before enabling automatic entry. The schema score moved from 0/72 to 70/72 while the exact score stayed at 0/72.
  • Separate transcription from authorisation. Preserve USD 1,219.65 in the opening record and send the discrepancy for review.
  • Keep both row scores. Whole-row and positional-cell scores catch different classes of attachment failures.
  • Report matched-label coverage. An unavailable chart amount error tells the reader that there were no names to align.
  • Carry forward the adapter receipt. Check its pinned source and reference token IDs before repeating the comparison in Lesson 15.
  • Next to try, not tested here: compare the same chart with only its order changed and audit the returned label-to-amount pairs.

How it was built

The adapter fit in memory

One Tesla T4 · separate guard and scored fit

6

Longest-input guard · SF-652885

822 sequence tokens · 2,240 image patches

9.06 s · 3.43 GiB allocated

4.63 GiB reserved

Scored fit

32 optimiser updates · 64 examples seen

111.43 s · 3.43 GiB allocated

4,372,840 bytes saved as adapter weights

Source · Saved Lab 08 outputs from one Tesla T4. Allocated and reserved peaks measure different counters. A reserved peak was recorded for the guard only.
ItemSetting
Base modelQwen/Qwen2-VL-2B-Instruct at revision 1860c46f12b7449d0f5b426a7474ab715342bc65
DataSynthetic catalogue course-invoice-v1. 72 invoice and 24 chart training examples in the pool.
Test24 held-out invoices per slice and 24 charts rendered from the novel slice.
MethodNF4 4-bit base, FP16 compute and LoRA rank 8 with alpha 16.
TrainingAdamW at 0.0001, gradient accumulation 2 and 32 updates.
DecodingGreedy decoding, at most 220 new tokens per example.
Uncertainty2,000 paired supplier-family resamples. Familiar and novel each have eight families, independent has four, and charts have eight. When both systems miss every example the interval collapses to [0, 0].
Hardware and packagesOne Tesla T4. Torch 2.14.1+cu130, Transformers 4.51.3, PEFT 0.15.2, Accelerate 1.6.0, bitsandbytes 0.50.2, Pillow 11.3.0 and datasets 3.6.0.

Time and cost. The fit took 111.43 seconds and peaked at 3.43 GiB allocated. The saved adapter weights occupy 4,372,840 bytes. The results report covers 2,129.52 seconds from the experiment’s internal timer. The external notebook receipt measures 2,162.08 seconds, including setup and notebook overhead. The handoff records the base revision, a SHA-256 over the ordered training examples, the adapter-weight SHA-256, and saved greedy token IDs for familiar invoice SF-228794. Lesson 15 can check those values before reusing the adapter. Full results and locked invoice IDs · Guard profile · Run receipt · Adapter handoff

Run it yourself

Open the notebook from the facts box, or download the exact notebook used for the run. Allow 2,162.08 seconds on the measured T4 setup. The notebook’s extraction checks map to field and row scoring, its supervised fit maps to the response mask, and its last comparison maps to the reordered charts.

  1. Predict which record a discrepancy check will flag. Add only that check after parsing the opening target and adapted prediction, then compare its flag with the payable field score.
  2. Predict whether reversing the opening chart changes exactness. Keep the bar colour and checkpoint fixed, change the order alone, and inspect matched labels and exactness.
  3. Predict whether validity or exact chart rows will change when the fit sees more chart examples. Vary only the chart allocation within the 64 processed examples, then check both outputs.

Back to the course

How is this page?

Last updated on