Skip to Content
Recodocs

01 · LoRA vs QLoRA for invoice extraction

Train two versions of the same invoice parser on one T4. See which invoices each gets right and how much memory each uses.

12 min read
Part 1
Build the data
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’re checking a paid invoice for gazebo weights. The parser got the total right. Check the quantity before you send the record to the ledger.

Would you post this answer?

Read the quantity column on this invoice. Would you trust the parser’s quantity if its price and total both look right?

Original invoice detail showing one pack of gazebo weights, £11.57 before VAT, £2.31 VAT and £13.88 payable.
Line items and VAT from the paid invoice. View larger image or Open the complete invoice on page 19.

From the invoice

Qty 1 · £11.57 before VAT · £13.88 payable

From the locally fitted QLoRA model

Qty 4 · £11.57 before VAT · £13.88 payable

Check the answer

The quantity column says 1 pack. The model returned 4, which appears in the product description. Its total of £13.88 was correct and it returned 1388 pence, as the ledger expects.

An exact match means every field agrees with the answer, including the order of the line items. We use the same rule for the paid invoice and the controlled comparison on a T4. The T4 comparison uses invoices generated for the lab.

Both methods improved accuracy. FP16 LoRA used less memory here.

Familiar covers layouts seen in training. Novel covers four new layouts. Separate covers one more new layout.

1
  • FP16 LoRA
  • NF4 QLoRA

Fully correct invoices before and after training

0%25%50%75%100%Familiarn = 9699.0%95.8%Noveln = 9656.3%1.0%50.0%0.0%Separaten = 4858.3%85.4%

Peak GPU memory during training

Same adapter size, data and updates

FP16 LoRA4.13 GiBNF4 QLoRA4.93 GiB+19%for the full NF4 recipe
Source: Chapter 1 Colab T4 notebook. Hollow marks show scores before training. Solid marks show scores after training. Peak is the memory PyTorch allocated during the update loop.

1. See what prompting can do

A tuned parser should beat a comparable untuned parser supplied with the best reasonable prompt. Otherwise the improvement may be due to a better instruction rather than changed weights.

Before training each version, give it the same instructions, one solved invoice, and a new invoice to read. This gives you a starting score. Without it, you can’t tell what fine-tuning added.

Look at the two item lines on this Packing invoice. The FP16 model finished its answer and returned valid JSON with an empty item list. The four-bit model, labelled NF4, filled its item list with null until it hit the 384-token limit.

Invoice

SF-177277

Billing details / SF-177277

Sold by Sample Supplier 3177

Document date 2025-01-11

Invoice currency USD

Balance payable 1,122.29

Cooling filter: 198.62 each for 5 units

Door seal: 55.77 each for 1 units

Merchandise 1,048.87

Tax 73.42

Complete invoice text for SF-177277

FP16 prompted

Finished with valid JSON, but left out both items

{"invoice_id":"SF-177277","issued_on":"2025-01-11","supplier":"Sample Supplier 3177","currency":"USD","line_items":[],"subtotal_minor":104887,"tax_minor":7342,"total_minor":112229}

NF4 prompted

384 tokens before cutoff · excerpts

{"invoice_id":"SF-177277","issued_on":"2025-01-11","supplier":"Sample Supplier 3177","currency":"USD","line_items":[[null,null

[repeated tokens omitted]

null,null,null,null,null,null,null,null,null,null,null,null,null,null,null
See the exact prompt
  1. System instruction · system

    Extract exactly one JSON object with invoice_id, issued_on (YYYY-MM-DD), supplier, currency (ISO code), line_items (description, quantity, unit_minor), subtotal_minor, tax_minor, and total_minor. Preserve line order and convert currency amounts to integer cents. Use null only for a missing or ambiguous field. Do not rewrite printed amounts, invent fields, or add explanations.
  2. Demonstration invoice · user

    Sample Supplier 7644 | issued 2026-07-15 | invoice SF-898991
    Ledger in USD
    Service | Count | Per unit
    Carrier adjustment | 3 | 188.32
    Rack inspection | 8 | 64.15
    Before tax 1,078.16
    Tax charged 75.47
    Balance 1,153.63
  3. Demonstration answer · assistant

    {"invoice_id":"SF-898991","issued_on":"2026-07-15","supplier":"Sample Supplier 7644","currency":"USD","line_items":[{"description":"Carrier adjustment","quantity":3,"unit_minor":18832},{"description":"Rack inspection","quantity":8,"unit_minor":6415}],"subtotal_minor":107816,"tax_minor":7547,"total_minor":115363}
  4. Current invoice · user

    Billing details / SF-177277
    Sold by Sample Supplier 3177
    Document date 2025-01-11
    Invoice currency USD
    Balance payable 1,122.29
    Cooling filter: 198.62 each for 5 units
    Door seal: 55.77 each for 1 units
    Merchandise 1,048.87
    Tax 73.42
See the full model outputs and answer

SF-177277 · Reference and saved responses

Reference
{"invoice_id":"SF-177277","issued_on":"2025-01-11","supplier":"Sample Supplier 3177","currency":"USD","line_items":[{"description":"Cooling filter","quantity":5,"unit_minor":19862},{"description":"Door seal","quantity":1,"unit_minor":5577}],"subtotal_minor":104887,"tax_minor":7342,"total_minor":112229}
FP16 prompted
{"invoice_id":"SF-177277","issued_on":"2025-01-11","supplier":"Sample Supplier 3177","currency":"USD","line_items":[],"subtotal_minor":104887,"tax_minor":7342,"total_minor":112229}
NF4 prompted
{"invoice_id":"SF-177277","issued_on":"2025-01-11","supplier":"Sample Supplier 3177","currency":"USD","line_items":[[null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null

That difference matters when you decide what to fix. On 96 invoices with new layouts, FP16 returned 79 answers in the required format, but only one was fully correct. NF4 returned 26 in the required format, got none fully right, and hit the token limit 24 times. One problem is getting an answer the software can read. The other is getting the values right.

Prompting alone rarely got the whole invoice right

Same 96 invoices from layouts the models would later be tested on

2

FP16 promptedn = 96

NF4 promptedn = 96

OutcomeFP16 promptedNF4 prompted
Exact record10
Valid schema, wrong record7826
Invalid schema, reached the end token1746
Invalid schema, hit the token cap024
Source: Chapter 1 Colab T4 notebook. Derived from each invoice’s exact-match, schema and end-token flags.
See what a fixed rule can handle

A rule that expects Description | Quantity | Unit price on line five got all 24 Register invoices right. The Memo invoice puts the same information in prose, so the rule returns null. The rule skipped every other invoice. Skips count in the scorecard, because those documents still need processing.

Register · Exact record

Invoice

SF-228794

Supplier: Sample Supplier 1597

Invoice: SF-228794

Issued: 2026-03-21

Currency: USD

Description | Quantity | Unit price

Mounting plate | 8 | 11.95

Packing insert | 6 | 216.34

Cooling filter | 4 | 68.07

Subtotal: 1,665.92

Tax: 116.61

Amount due: 1,782.53

Complete invoice text for SF-228794

Selected fields from the rule output

{"invoice_id":"SF-228794","total_minor":178253}
Complete rule output for SF-228794
{
  "supplier": "Sample Supplier 1597",
  "invoice_id": "SF-228794",
  "issued_on": "2026-03-21",
  "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
}

Memo · Abstained

Invoice

SF-429916

Sample Supplier 7823 billing memo / 2025-05-07

Account invoice SF-429916 [GBP]

2 x Cable sleeve @ 236.17 per unit

8 x Mounting plate @ 116.58 per unit

7 x Meter label @ 96.35 per unit

Total due 2,349.76 including tax 270.33; net amount 2,079.43.

Complete invoice text for SF-429916
null

2. Train both versions on the same invoices

Both methods keep the original model weights frozen and train an adapter, a small set of weights that learns how to change the model’s output. FP16 LoRA keeps the base model in 16-bit precision. NF4 QLoRA stores the frozen linear weights in four bits. In both cases, the adapter learns the same job.

Here’s one of the 192 invoices both versions trained on. Each version completed 96 updates and trained on the same 21,378 answer tokens. Given the invoice, the model learns to write the answer shown beside it.

Invoice

SF-460242

Sample Supplier 6320 billing memo / 2026-03-15

Account invoice SF-460242 [USD]

8 x Door seal @ 232.41 per unit

5 x Grounding clip @ 81.05 per unit

9 x Bench calibration @ 23.19 per unit

Total due 2,646.37 including tax 173.13; net amount 2,473.24.

Complete invoice text for SF-460242

Answer the model learns to write

{
  "invoice_id": "SF-460242",
  "issued_on": "2026-03-15",
  "supplier": "Sample Supplier 6320",
  "currency": "USD",
  "line_items": [
    {"description":"Door seal","quantity":8,"unit_minor":23241},
    {"description":"Grounding clip","quantity":5,"unit_minor":8105},
    {"description":"Bench calibration","quantity":9,"unit_minor":2319}
  ],
  "subtotal_minor": 247324,
  "tax_minor": 17313,
  "total_minor": 264637
}

Load the two bases and add the same adapter

LoRA adds a trainable update to a frozen projection. An adapter of rank r uses r × (input width + output width) trained weights per projection.

h=W0x+αrBAxh = W_0x + \frac{\alpha}{r}BAx

Here rank 8 adapters target the query and value projections. The four-bit path uses NF4 for frozen linear weights, quantises their scale constants, and computes those operations in FP16. The measurements compare both recipes, including the preparation step used by the four-bit path. LoRA paper · QLoRA paper

# NF4 path, from load_model
quant = BitsAndBytesConfig(
    load_in_4bit=True, bnb_4bit_quant_type="nf4",
    bnb_4bit_use_double_quant=True, bnb_4bit_compute_dtype=torch.float16,
)
model = AutoModelForCausalLM.from_pretrained(
    MODEL, revision=REVISION, quantization_config=quant, torch_dtype=torch.float16,
    device_map={"": 0}, attn_implementation="sdpa",
)
# Applied only on the trainable NF4 path.
model = prepare_model_for_kbit_training(model, use_gradient_checkpointing=False)
# FP16 path, then the adapter configuration shared by both training arms
model = AutoModelForCausalLM.from_pretrained(
    MODEL, revision=REVISION, torch_dtype=torch.float16, attn_implementation="sdpa",
).to("cuda")
adapter = LoraConfig(
    r=8, lora_alpha=16, lora_dropout=0.0, bias="none",
    task_type="CAUSAL_LM", target_modules=["q_proj", "v_proj"],
)

Keep the quantised baseline. Dialpad’s paper reports that adding QLoRA to its bitsandbytes 4-bit Qwen2-7B raised Banking77 micro-F1 from 0.8383 to 0.9050. Its experiments trained and evaluated on A100s. The T4 reference in the paper refers to serving. Compare the same frozen encoding before and after adaptation, as the lab does. Dialpad, paper-reported results in Table 3 and §4.2

Which text gets scored during training?

The instruction, solved example, and current invoice tell the model what to do. It’s graded on the answer it’s learning to write, through the end marker. In the first training example, 129 of 552 token positions count towards the loss. You can see which ones count in the second example too.

The prompt supplies context. The correct answer and its end marker are the supervised positions. For supervised indices in the set S, the loss is the mean negative log probability of the next target token:

L=−1∣S∣∑t∈Slog⁡pθ(yt∣x,y<t)\mathcal{L}=-\frac{1}{|S|}\sum_{t\in S}\log p_\theta(y_t\mid x,y_{<t})

The notebook uses Together’s prefix-stable split_turns to keep the prompt/completion boundary aligned. The label builder excludes context and padding from the loss with -100. Pinned Together cookbook helper

prompt = encode_prompt(tokenizer, invoice, exemplar)
completion = tokenizer.encode(answer, add_special_tokens=False) + [tokenizer.eos_token_id]
sequence, = split_turns([Turn(prompt, completion)])

# From right_pad. Convert the completion mask to causal-LM labels.
labels.append([token if mask else -100 for token, mask in zip(
    example.input_ids, example.completion_mask, strict=True,
)] + [-100] * n_pad)

Training scores only the answer and its end marker

Which tokens count towards training loss in the first two examples

3
  • Instructions and example
  • Invoice and role markers
  • Answer and end token
  • Padding
SF-460242129 / 552 tokens carry loss

303 instructions and example · 120 invoice and markers · 128 answer + 1 end token · 0 padding

SF-95777891 / 552 tokens carry loss

303 instructions and example · 89 invoice and markers · 90 answer + 1 end token · 69 padding

Source: Chapter 1 Colab T4 notebook. Token spans reconstructed from the recorded training IDs and revision. Both rows pad to the same batch width.
See both training examples, prompts and token labels

First two training examples

Invoice

SF-460242

Sample Supplier 6320 billing memo / 2026-03-15

Account invoice SF-460242 [USD]

8 x Door seal @ 232.41 per unit

5 x Grounding clip @ 81.05 per unit

9 x Bench calibration @ 23.19 per unit

Total due 2,646.37 including tax 173.13; net amount 2,473.24.

Complete invoice text for SF-460242

Answer the model learns to write

{"invoice_id":"SF-460242","issued_on":"2026-03-15","supplier":"Sample Supplier 6320","currency":"USD","line_items":[{"description":"Door seal","quantity":8,"unit_minor":23241},{"description":"Grounding clip","quantity":5,"unit_minor":8105},{"description":"Bench calibration","quantity":9,"unit_minor":2319}],"subtotal_minor":247324,"tax_minor":17313,"total_minor":264637}
IndexDecoded tokenInput IDAttentionLabel
422"\n"1981-100
423"{\""491314913
424"invoice"22217122217
550"}"92192
551"<|im_end|>"1516451151645

Invoice

SF-957778

SF-957778 / supplier Sample Supplier 7083

Date of issue 2026-07-26 / All amounts EUR

Grounding clip: 151,59 each for 2 units

Net 303,18

Sales tax 39,41

Payable 342,59

Complete invoice text for SF-957778

Answer the model learns to write

{"invoice_id":"SF-957778","issued_on":"2026-07-26","supplier":"Sample Supplier 7083","currency":"EUR","line_items":[{"description":"Grounding clip","quantity":2,"unit_minor":15159}],"subtotal_minor":30318,"tax_minor":3941,"total_minor":34259}
IndexDecoded tokenInput IDAttentionLabel
391"\n"1981-100
392"{\""491314913
393"invoice"22217122217
481"}"92192
482"<|im_end|>"1516451151645
551"<|endoftext|>"1516430-100

These are selected positions from each token sequence, starting at index zero. The last row of the second table is padding.

Exact chat prompt for SF-460242
  1. System instruction · system

    Extract exactly one JSON object with invoice_id, issued_on (YYYY-MM-DD), supplier, currency (ISO code), line_items (description, quantity, unit_minor), subtotal_minor, tax_minor, and total_minor. Preserve line order and convert currency amounts to integer cents. Use null only for a missing or ambiguous field. Do not rewrite printed amounts, invent fields, or add explanations.
  2. Demonstration invoice · user

    Sample Supplier 7644 | issued 2026-07-15 | invoice SF-898991
    Ledger in USD
    Service | Count | Per unit
    Carrier adjustment | 3 | 188.32
    Rack inspection | 8 | 64.15
    Before tax 1,078.16
    Tax charged 75.47
    Balance 1,153.63
  3. Demonstration answer · assistant

    {"invoice_id":"SF-898991","issued_on":"2026-07-15","supplier":"Sample Supplier 7644","currency":"USD","line_items":[{"description":"Carrier adjustment","quantity":3,"unit_minor":18832},{"description":"Rack inspection","quantity":8,"unit_minor":6415}],"subtotal_minor":107816,"tax_minor":7547,"total_minor":115363}
  4. Current invoice · user

    Sample Supplier 6320 billing memo / 2026-03-15
    Account invoice SF-460242 [USD]
    8 x Door seal @ 232.41 per unit
    5 x Grounding clip @ 81.05 per unit
    9 x Bench calibration @ 23.19 per unit
    Total due 2,646.37 including tax 173.13; net amount 2,473.24.
Exact chat prompt for SF-957778
  1. System instruction · system

    Extract exactly one JSON object with invoice_id, issued_on (YYYY-MM-DD), supplier, currency (ISO code), line_items (description, quantity, unit_minor), subtotal_minor, tax_minor, and total_minor. Preserve line order and convert currency amounts to integer cents. Use null only for a missing or ambiguous field. Do not rewrite printed amounts, invent fields, or add explanations.
  2. Demonstration invoice · user

    Sample Supplier 7644 | issued 2026-07-15 | invoice SF-898991
    Ledger in USD
    Service | Count | Per unit
    Carrier adjustment | 3 | 188.32
    Rack inspection | 8 | 64.15
    Before tax 1,078.16
    Tax charged 75.47
    Balance 1,153.63
  3. Demonstration answer · assistant

    {"invoice_id":"SF-898991","issued_on":"2026-07-15","supplier":"Sample Supplier 7644","currency":"USD","line_items":[{"description":"Carrier adjustment","quantity":3,"unit_minor":18832},{"description":"Rack inspection","quantity":8,"unit_minor":6415}],"subtotal_minor":107816,"tax_minor":7547,"total_minor":115363}
  4. Current invoice · user

    SF-957778 / supplier Sample Supplier 7083
    Date of issue 2026-07-26 / All amounts EUR
    Grounding clip: 151,59 each for 2 units
    Net 303,18
    Sales tax 39,41
    Payable 342,59

3. Try invoices the models haven’t seen

Use test invoices from different suppliers. The familiar group uses layouts seen in training. The novel group uses four new layouts. The separate group uses a fifth layout that gets its own score. The same test invoices went to both models.

Compare Packing and Remittance

In Packing, Balance payable appears above the items and Merchandise below them. QLoRA read both items but swapped the subtotal and the total. In Remittance, LoRA read the item but put all three amounts in the wrong fields. Compare the printed values with the model outputs before looking at the scores.

Packing layout

Packing puts the payable amount first

Invoice

SF-177277

Billing details / SF-177277

Sold by Sample Supplier 3177

Document date 2025-01-11

Invoice currency USD

Balance payable 1,122.29

Cooling filter: 198.62 each for 5 units

Door seal: 55.77 each for 1 units

Merchandise 1,048.87

Tax 73.42

Complete invoice text for SF-177277

What the models returned

Amounts in US cents

RecordSubtotalTaxTotal
Reference104,8877,342112,229
FP16 LoRAExact record104,8877,342112,229
NF4 QLoRAValid schema · record differsMismatch. 112,2297,342Mismatch. 104,887

Highlighted values differ from the answer. A dash means the model left the field out.

See the full model outputs and answer

SF-177277 · Reference and saved responses

Reference
{"invoice_id":"SF-177277","issued_on":"2025-01-11","supplier":"Sample Supplier 3177","currency":"USD","line_items":[{"description":"Cooling filter","quantity":5,"unit_minor":19862},{"description":"Door seal","quantity":1,"unit_minor":5577}],"subtotal_minor":104887,"tax_minor":7342,"total_minor":112229}
FP16 LoRA
{"invoice_id":"SF-177277","issued_on":"2025-01-11","supplier":"Sample Supplier 3177","currency":"USD","line_items":[{"description":"Cooling filter","quantity":5,"unit_minor":19862},{"description":"Door seal","quantity":1,"unit_minor":5577}],"subtotal_minor":104887,"tax_minor":7342,"total_minor":112229}
NF4 QLoRA
{"invoice_id":"SF-177277","issued_on":"2025-01-11","supplier":"Sample Supplier 3177","currency":"USD","line_items":[{"description":"Cooling filter","quantity":5,"unit_minor":19862},{"description":"Door seal","quantity":1,"unit_minor":5577}],"subtotal_minor":112229,"tax_minor":7342,"total_minor":104887}

Remittance layout

Remittance puts net and tax on one line

Invoice

SF-781239

Remittance advice for SF-781239 (GBP)

Sample Supplier 3219 / Document issued 2025-11-12

Pay this amount 728.51

5 x Packing insert @ 128.94 per unit

Net charges 644.70 / Tax 83.81

Complete invoice text for SF-781239

What the models returned

Amounts in British pence

RecordSubtotalTaxTotal
Reference64,4708,38172,851
FP16 LoRAValid schema · record differsMismatch. 72,851Mismatch. 64,470Mismatch. 64,470
NF4 QLoRAExact record64,4708,38172,851

Highlighted values differ from the answer. A dash means the model left the field out.

See the full model outputs and answer

SF-781239 · Reference and saved responses

Reference
{"invoice_id":"SF-781239","issued_on":"2025-11-12","supplier":"Sample Supplier 3219","currency":"GBP","line_items":[{"description":"Packing insert","quantity":5,"unit_minor":12894}],"subtotal_minor":64470,"tax_minor":8381,"total_minor":72851}
FP16 LoRA
{"invoice_id":"SF-781239","issued_on":"2025-11-12","supplier":"Sample Supplier 3219","currency":"GBP","line_items":[{"description":"Packing insert","quantity":5,"unit_minor":12894}],"subtotal_minor":72851,"tax_minor":64470,"total_minor":64470}
NF4 QLoRA
{"invoice_id":"SF-781239","issued_on":"2025-11-12","supplier":"Sample Supplier 3219","currency":"GBP","line_items":[{"description":"Packing insert","quantity":5,"unit_minor":12894}],"subtotal_minor":64470,"tax_minor":8381,"total_minor":72851}

The same pattern shows up in the scores. LoRA got 20 of 24 Packing invoices right, versus six for QLoRA. On Remittance it got nine, versus 22 for QLoRA. Across the four novel layouts, the overall gap was uncertain. On the separate layout, QLoRA got 15 invoices right that LoRA missed, and LoRA got two right that QLoRA missed. That’s a net gain of 13 for QLoRA.

FP16 wins on Packing. NF4 wins on Remittance.

Fully correct invoices by layout and test group

4
  • FP16 LoRA
  • NF4 QLoRA

Exact records out of 24 per novel template

06121824Notice2419Packing206Remittance922Service11

NF4 QLoRA minus FP16 LoRA, percentage points

-40-200+20+40Familiar −3.1−6.3 to −1.0Novel −6.3−34.4 to +22.9Separate +27.1+14.6 to +37.5

Which adapter got each invoice right?

Paired outcomeFamiliarNovelSeparate
Both correct923426
Only FP16 correct3202
Only NF4 correct01415
Neither correct1285
Source: Chapter 1 Colab T4 notebook. Left: exact records by template. Right: derived differences and 95% paired supplier-cluster bootstrap intervals, conditional on these layouts and one training seed.

Pair results by invoice so both recipes face the same text. For the 95% intervals, resample whole suppliers, since invoices from one supplier share a layout and locale. On the four novel layouts, the QLoRA gap is −6.3 percentage points (−34.4 to +22.9), so either recipe could lead in a similar test. On the separate layout, QLoRA is +27.1 points (+14.6 to +37.5) for these suppliers. Full test data

Check line items as well as totals

The same problem shows up in the lab data. On this Service invoice, both starting models left out the item. Training got both to return a line item. LoRA still wrote quantity 1. QLoRA wrote 2,939, the unit price in cents, in the quantity field. All four answers got the totals right. Across the 96 novel-layout invoices, line items were the most common reason a complete, readable record was still wrong.

Service layout

Four inspections at €29.39 each

Invoice

SF-357240

Ref SF-357240 / EUR

Service fee notice, 2025-06-22

Sample Supplier 4464

Unit 29,39 / 4 times / Rack inspection

Fee subtotal 117,56

Plus tax 15,28

Amount requested 132,84

Complete invoice text for SF-357240

What the models returned

Unit price in euro cents

RecordDescriptionQtyUnit price
ReferenceRack inspection42,939
FP16 promptedValid schema · record differsMismatch. —Mismatch. —Mismatch. —
FP16 LoRAValid schema · record differsMismatch. Unit 29,39 / 4 times / Rack inspectionMismatch. 12,939
NF4 promptedValid schema · record differsMismatch. —Mismatch. —Mismatch. —
NF4 QLoRAValid schema · record differsMismatch. Unit 29,39 / 4 times / Rack inspectionMismatch. 2,939Mismatch. 11,756

Highlighted values differ from the answer. A dash means the model left the field out.

All four outputs match these amounts, in euro cents

Subtotal
11,756
Tax
1,528
Total
13,284
See the exact prompt
  1. System instruction · system

    Extract exactly one JSON object with invoice_id, issued_on (YYYY-MM-DD), supplier, currency (ISO code), line_items (description, quantity, unit_minor), subtotal_minor, tax_minor, and total_minor. Preserve line order and convert currency amounts to integer cents. Use null only for a missing or ambiguous field. Do not rewrite printed amounts, invent fields, or add explanations.
  2. Demonstration invoice · user

    Sample Supplier 7644 | issued 2026-07-15 | invoice SF-898991
    Ledger in USD
    Service | Count | Per unit
    Carrier adjustment | 3 | 188.32
    Rack inspection | 8 | 64.15
    Before tax 1,078.16
    Tax charged 75.47
    Balance 1,153.63
  3. Demonstration answer · assistant

    {"invoice_id":"SF-898991","issued_on":"2026-07-15","supplier":"Sample Supplier 7644","currency":"USD","line_items":[{"description":"Carrier adjustment","quantity":3,"unit_minor":18832},{"description":"Rack inspection","quantity":8,"unit_minor":6415}],"subtotal_minor":107816,"tax_minor":7547,"total_minor":115363}
  4. Current invoice · user

    Ref SF-357240 / EUR
    Service fee notice, 2025-06-22
    Sample Supplier 4464
    Unit 29,39 / 4 times / Rack inspection
    Fee subtotal 117,56
    Plus tax 15,28
    Amount requested 132,84
See the full model outputs and answer

SF-357240 · Reference and saved responses

Reference
{"invoice_id":"SF-357240","issued_on":"2025-06-22","supplier":"Sample Supplier 4464","currency":"EUR","line_items":[{"description":"Rack inspection","quantity":4,"unit_minor":2939}],"subtotal_minor":11756,"tax_minor":1528,"total_minor":13284}
FP16 prompted
{"invoice_id":"SF-357240","issued_on":"2025-06-22","supplier":"Sample Supplier 4464","currency":"EUR","line_items":[],"subtotal_minor":11756,"tax_minor":1528,"total_minor":13284}
FP16 LoRA
{"invoice_id":"SF-357240","issued_on":"2025-06-22","supplier":"Sample Supplier 4464","currency":"EUR","line_items":[{"description":"Unit 29,39 / 4 times / Rack inspection","quantity":1,"unit_minor":2939}],"subtotal_minor":11756,"tax_minor":1528,"total_minor":13284}
NF4 prompted
{"invoice_id":"SF-357240","issued_on":"2025-06-22","supplier":"Sample Supplier 4464","currency":"EUR","line_items":[],"subtotal_minor":11756,"tax_minor":1528,"total_minor":13284}
NF4 QLoRA
{"invoice_id":"SF-357240","issued_on":"2025-06-22","supplier":"Sample Supplier 4464","currency":"EUR","line_items":[{"description":"Unit 29,39 / 4 times / Rack inspection","quantity":2939,"unit_minor":11756}],"subtotal_minor":11756,"tax_minor":1528,"total_minor":13284}

Line items were the most common error after training

96 test invoices in new layouts, one outcome per invoice

5

FP16 LoRAn = 96

NF4 QLoRAn = 96

OutcomeFP16 LoRANF4 QLoRA
Exact record5448
Line items only2024
Other invoice fields only1514
Line items and other fields37
Invalid schema43
Source: Chapter 1 Colab T4 notebook. Derived from schema validity, scalar-field accuracy and exact row tuple matching. Both fitted models reached the end token on every invoice.

For partial credit, count exact matches of description, quantity and unit price as a multiset. Let m be the number of matching items, p the number predicted and g the number expected. The scorer assigns:

F1,row=2mp+gF_{1,\mathrm{row}} = \frac{2m}{p+g}

The scorer ignores order for row F1 and counts duplicate rows. An invalid record supplies zero predicted rows. Two empty lists score 1. Complete-record exact match also checks item order and every other field.

Grade the structure as well as the format. Apoidea’s company-reported FinTabNet results rose from 23.4 to 81.1 TEDS and 25.3 to 89.7 structure-only TEDS after adapting Qwen2-VL-7B. Their benchmark compares the content and structure of HTML tables. Here, the product code appearing as a second invoice item is a structure error you can see even when the JSON parses. Apoidea report, Results

See three more scoring examples

Correct values, wrong format. On the separate layout, the prompted NF4 model got the amounts right but put the item data in nested arrays. The parser expects an object for each item. QLoRA returned the correct amounts and the item in the required format.

Separate layout

Net and gross on separate lines

Invoice

SF-375561

Document SF-375561

Biller Sample Supplier 8052 / As of 2025-03-27 / USD

4 x Door seal @ 165.43 per unit

Gross 708.04

Breakdown: net 661.72 and taxes 46.32.

Complete invoice text for SF-375561

What the models returned

Amounts in US cents

RecordSubtotalTaxTotal
Reference66,1724,63270,804
FP16 promptedValid schema · record differsMismatch. 70,8044,632Mismatch. 75,485
FP16 LoRAValid schema · record differsMismatch. 70,8044,63270,804
NF4 promptedInvalid schema66,1724,63270,804
NF4 QLoRAExact record66,1724,63270,804

Highlighted values differ from the answer. A dash means the model left the field out.

NF4 prompted · saved line_items

[[1,["Door seal",165.43,1]],[2,["Net",661.72],["Taxes",46.32]]]

NF4 QLoRA · saved line_items

[{"description":"Door seal","quantity":4,"unit_minor":16543}]
See the exact prompt
  1. System instruction · system

    Extract exactly one JSON object with invoice_id, issued_on (YYYY-MM-DD), supplier, currency (ISO code), line_items (description, quantity, unit_minor), subtotal_minor, tax_minor, and total_minor. Preserve line order and convert currency amounts to integer cents. Use null only for a missing or ambiguous field. Do not rewrite printed amounts, invent fields, or add explanations.
  2. Demonstration invoice · user

    Sample Supplier 7644 | issued 2026-07-15 | invoice SF-898991
    Ledger in USD
    Service | Count | Per unit
    Carrier adjustment | 3 | 188.32
    Rack inspection | 8 | 64.15
    Before tax 1,078.16
    Tax charged 75.47
    Balance 1,153.63
  3. Demonstration answer · assistant

    {"invoice_id":"SF-898991","issued_on":"2026-07-15","supplier":"Sample Supplier 7644","currency":"USD","line_items":[{"description":"Carrier adjustment","quantity":3,"unit_minor":18832},{"description":"Rack inspection","quantity":8,"unit_minor":6415}],"subtotal_minor":107816,"tax_minor":7547,"total_minor":115363}
  4. Current invoice · user

    Document SF-375561
    Biller Sample Supplier 8052 / As of 2025-03-27 / USD
    4 x Door seal @ 165.43 per unit
    Gross 708.04
    Breakdown: net 661.72 and taxes 46.32.
See the full model outputs and answer

SF-375561 · Reference and saved responses

Reference
{"invoice_id":"SF-375561","issued_on":"2025-03-27","supplier":"Sample Supplier 8052","currency":"USD","line_items":[{"description":"Door seal","quantity":4,"unit_minor":16543}],"subtotal_minor":66172,"tax_minor":4632,"total_minor":70804}
FP16 prompted
{"invoice_id":"SF-375561","issued_on":"2025-03-27","supplier":"Sample Supplier 8052","currency":"USD","line_items":[{"description":"Door seal","quantity":4,"unit_minor":16543},{"description":"Net","quantity":66172,"unit_minor":66172},{"description":"Taxes","quantity":4632,"unit_minor":4632}],"subtotal_minor":70804,"tax_minor":4632,"total_minor":75485}
FP16 LoRA
{"invoice_id":"SF-375561","issued_on":"2025-03-27","supplier":"Sample Supplier 8052","currency":"USD","line_items":[{"description":"Door seal","quantity":4,"unit_minor":16543}],"subtotal_minor":70804,"tax_minor":4632,"total_minor":70804}
NF4 prompted
{"invoice_id":"SF-375561","issued_on":"2025-03-27","supplier":"Sample Supplier 8052","currency":"USD","line_items":[[1,["Door seal",165.43,1]],[2,["Net",661.72],["Taxes",46.32]]],"subtotal_minor":66172,"tax_minor":4632,"total_minor":70804}
NF4 QLoRA
{"invoice_id":"SF-375561","issued_on":"2025-03-27","supplier":"Sample Supplier 8052","currency":"USD","line_items":[{"description":"Door seal","quantity":4,"unit_minor":16543}],"subtotal_minor":66172,"tax_minor":4632,"total_minor":70804}

One item right, one extra. Apply row F1 to the returned rows below.

A wrong total printed on the invoice. The parser should copy it as printed. A separate arithmetic check can flag it for review.

Invoice

SF-973701

Billing details / SF-973701

Sold by Sample Supplier 3177

Document date 2025-02-11

Invoice currency USD

Balance payable 608.40

Cooling filter: 142.15 each for 4 units

Merchandise 568.60

Tax 39.80

Complete invoice text for SF-973701

One row matches. One was invented.

Line items only · amounts in US cents

Reference
[{"description":"Cooling filter","quantity":4,"unit_minor":14215}]
NF4 QLoRA
[{"description":"Cooling filter","quantity":4,"unit_minor":14215},{"description":"Merchandise","quantity":56860,"unit_minor":56860}]
FP16 LoRA
[{"description":"Cooling filter","quantity":4,"unit_minor":14215},{"description":"Merchandise","quantity":568.6}]

Two predicted rows, one expected row, one match. Row F1 = 2 × 1 / (2 + 1) = 66.7%. The complete record misses. FP16 also returned the Cooling filter, but its second item lacks a unit price and has a non-integer quantity. The schema rejects the response and row F1 is 0.

See the full model outputs and answer

SF-973701 · Reference and saved responses

Reference
{"invoice_id":"SF-973701","issued_on":"2025-02-11","supplier":"Sample Supplier 3177","currency":"USD","line_items":[{"description":"Cooling filter","quantity":4,"unit_minor":14215}],"subtotal_minor":56860,"tax_minor":3980,"total_minor":60840}
NF4 QLoRA
{"invoice_id":"SF-973701","issued_on":"2025-02-11","supplier":"Sample Supplier 3177","currency":"USD","line_items":[{"description":"Cooling filter","quantity":4,"unit_minor":14215},{"description":"Merchandise","quantity":56860,"unit_minor":56860}],"subtotal_minor":60840,"tax_minor":3980,"total_minor":60840}
FP16 LoRA
{"invoice_id":"SF-973701","issued_on":"2025-02-11","supplier":"Sample Supplier 3177","currency":"USD","line_items":[{"description":"Cooling filter","quantity":4,"unit_minor":14215},{"description":"Merchandise","quantity":568.60}],"subtotal_minor":60840,"tax_minor":3980,"total_minor":60840}

Invoice

SF-862677

Billing details / SF-862677

Sold by Sample Supplier 3177

Document date 2025-08-20

Invoice currency USD

Balance payable 1,219.65

Bench calibration: 144.20 each for 6 units

Grounding clip: 91.24 each for 3 units

Merchandise 1,138.92

Tax 79.72

Complete invoice text for SF-862677

The printed total is off by $1.01

What the models returned

Amounts in US cents

RecordSubtotalTaxTotal
Reference113,8927,972121,965
NF4 QLoRAExact record113,8927,972121,965

Highlighted values differ from the answer. A dash means the model left the field out.

113,892 + 7,972 = 121,864. The expected extraction still returns the printed 121,965.

See the full model output and answer

SF-862677 · Reference and saved responses

Reference
{"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}
NF4 QLoRA
{"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}

Full scores and test data

See the five-way decision table for the exact scores and training costs. The invoices and expected answers and the saved model outputs use the same invoice IDs. The input file includes the shared prompt and the training order.

See the test groups, confidence intervals and more examples
SplitInvoices / suppliersLayouts · invoices per layout
Training192 / 24checkout 48 · ledger 48 · memo 48 · register 48
Familiar holdout96 / 8checkout 24 · ledger 24 · memo 24 · register 24
Novel holdout96 / 8notice 24 · packing 24 · remittance 24 · service 24
Separate holdout48 / 4separate 48
Inspect suppliers, layouts and locales

Training

SupplierLayoutLocale · currency · n
Sample Supplier 7083checkoutfr-FR · EUR · 8
Sample Supplier 6653checkouten-US · USD · 8
Sample Supplier 9780checkouten-US · CAD · 8
Sample Supplier 4685checkouten-GB · GBP · 8
Sample Supplier 1519checkoutde-DE · EUR · 8
Sample Supplier 4873checkoutde-DE · EUR · 8
Sample Supplier 2730ledgerfr-FR · EUR · 8
Sample Supplier 5036ledgeren-GB · GBP · 8
Sample Supplier 4347ledgeren-US · CAD · 8
Sample Supplier 5826ledgerde-DE · EUR · 8
Sample Supplier 2327ledgerfr-FR · EUR · 8
Sample Supplier 7644ledgeren-US · USD · 8
Sample Supplier 6320memoen-US · USD · 8
Sample Supplier 3103memofr-FR · EUR · 8
Sample Supplier 7035memode-DE · EUR · 8
Sample Supplier 8288memoen-GB · GBP · 8
Sample Supplier 2228memoen-GB · GBP · 8
Sample Supplier 7686memoen-US · CAD · 8
Sample Supplier 7451registeren-GB · GBP · 8
Sample Supplier 9910registerde-DE · EUR · 8
Sample Supplier 5773registeren-US · CAD · 8
Sample Supplier 2705registerfr-FR · EUR · 8
Sample Supplier 8777registeren-US · USD · 8
Sample Supplier 9083registeren-US · USD · 8

Familiar holdout

SupplierLayoutLocale · currency · n
Sample Supplier 5851checkoutde-DE · EUR · 12
Sample Supplier 6554checkouten-GB · GBP · 12
Sample Supplier 1460ledgerfr-FR · EUR · 12
Sample Supplier 3969ledgerde-DE · EUR · 12
Sample Supplier 7823memoen-GB · GBP · 12
Sample Supplier 8519memoen-US · USD · 12
Sample Supplier 1597registeren-US · USD · 12
Sample Supplier 3900registeren-US · CAD · 12

Novel holdout

SupplierLayoutLocale · currency · n
Sample Supplier 6600noticefr-FR · EUR · 12
Sample Supplier 8417noticede-DE · EUR · 12
Sample Supplier 3177packingen-US · USD · 12
Sample Supplier 8608packingen-US · CAD · 12
Sample Supplier 3219remittanceen-GB · GBP · 12
Sample Supplier 6540remittanceen-US · USD · 12
Sample Supplier 4464servicede-DE · EUR · 12
Sample Supplier 7598serviceen-GB · GBP · 12

Separate holdout

SupplierLayoutLocale · currency · n
Sample Supplier 8052separateen-US · USD · 12
Sample Supplier 2524separateen-GB · GBP · 12
Sample Supplier 8167separatede-DE · EUR · 12
Sample Supplier 9620separatefr-FR · EUR · 12

Novel holdout · paired changes in exact match

ComparisonGain (pp)95% interval (pp)
FP16 LoRA minus FP16 prompted+55.2+28.1 to +79.2
NF4 QLoRA minus NF4 prompted+50.0+25.0 to +74.0
NF4 QLoRA minus FP16 LoRA−6.3−34.4 to +22.9

The supplier bootstrap uses 1,000 draws and seed 42. Each supplier uses one layout and locale, so the comparison does not isolate which one caused the difference.

See four more invoices and their results

Checkout

Invoice

SF-862527

SF-862527 / supplier Sample Supplier 5851

Date of issue 2025-05-22 / All amounts EUR

Meter label: 3,58 each for 5 units

Net 17,90

Sales tax 2,33

Payable 20,23

Complete invoice text for SF-862527

SF-862527 · Reference and saved responses

Reference
{"invoice_id":"SF-862527","issued_on":"2025-05-22","supplier":"Sample Supplier 5851","currency":"EUR","line_items":[{"description":"Meter label","quantity":5,"unit_minor":358}],"subtotal_minor":1790,"tax_minor":233,"total_minor":2023}
FP16 LoRA
{"invoice_id":"SF-862527","issued_on":"2025-05-22","supplier":"Sample Supplier 5851","currency":"EUR","line_items":[{"description":"Meter label","quantity":5,"unit_minor":358}],"subtotal_minor":1790,"tax_minor":233,"total_minor":2023}
NF4 QLoRA
{"invoice_id":"SF-862527","issued_on":"2025-05-22","supplier":"Sample Supplier 5851","currency":"EUR","line_items":[{"description":"Meter label","quantity":3,"unit_minor":5},{"description":"Net","quantity":5,"unit_minor":1790}],"subtotal_minor":1790,"tax_minor":233,"total_minor":2023}

Ledger

Invoice

SF-456433

Sample Supplier 3969 | issued 2025-09-02 | invoice SF-456433

Ledger in EUR

Service | Count | Per unit

Packing insert | 6 | 187,75

Carrier adjustment | 1 | 178,14

Before tax 1.304,64

Tax charged 169,60

Balance 1.474,24

Complete invoice text for SF-456433

SF-456433 · Reference and saved responses

Reference
{"invoice_id":"SF-456433","issued_on":"2025-09-02","supplier":"Sample Supplier 3969","currency":"EUR","line_items":[{"description":"Packing insert","quantity":6,"unit_minor":18775},{"description":"Carrier adjustment","quantity":1,"unit_minor":17814}],"subtotal_minor":130464,"tax_minor":16960,"total_minor":147424}
FP16 LoRA
{"invoice_id":"SF-456433","issued_on":"2025-09-02","supplier":"Sample Supplier 3969","currency":"EUR","line_items":[{"description":"Packing insert","quantity":6,"unit_minor":18775},{"description":"Carrier adjustment","quantity":1,"unit_minor":17814}],"subtotal_minor":130464,"tax_minor":16960,"total_minor":147424}
NF4 QLoRA
{"invoice_id":"SF-456433","issued_on":"2025-09-02","supplier":"Sample Supplier 3969","currency":"EUR","line_items":[{"description":"Packing insert","quantity":6,"unit_minor":17814},{"description":"Carrier adjustment","quantity":1,"unit_minor":18775}],"subtotal_minor":130464,"tax_minor":16960,"total_minor":147424}

Notice

Invoice

SF-931161

Sample Supplier 6600 / statement SF-931161

Issued on 2025-03-07

Invoice denomination EUR

One-off charges

Packing insert: 56,85 each for 6 units

Carrier adjustment: 80,90 each for 6 units

Pre-tax 826,50 / Tax assessment 107,45 / Final bill 933,95

Complete invoice text for SF-931161

SF-931161 · Reference and saved responses

Reference
{"invoice_id":"SF-931161","issued_on":"2025-03-07","supplier":"Sample Supplier 6600","currency":"EUR","line_items":[{"description":"Packing insert","quantity":6,"unit_minor":5685},{"description":"Carrier adjustment","quantity":6,"unit_minor":8090}],"subtotal_minor":82650,"tax_minor":10745,"total_minor":93395}
FP16 LoRA
{"invoice_id":"SF-931161","issued_on":"2025-03-07","supplier":"Sample Supplier 6600","currency":"EUR","line_items":[{"description":"Packing insert","quantity":6,"unit_minor":5685},{"description":"Carrier adjustment","quantity":6,"unit_minor":8090}],"subtotal_minor":82650,"tax_minor":10745,"total_minor":93395}
NF4 QLoRA
{"invoice_id":"SF-931161","issued_on":"2025-03-07","supplier":"Sample Supplier 6600","currency":"EUR","line_items":[{"description":"Packing insert","quantity":6,"unit_minor":5685},{"description":"Carrier adjustment","quantity":8,"unit_minor":8090}],"subtotal_minor":82650,"tax_minor":10745,"total_minor":93395}

Service · both models got this one right

Invoice

SF-526862

Ref SF-526862 / GBP

Service fee notice, 2025-12-21

Sample Supplier 7598

Unit 152.61 / 1 times / Cable sleeve

Unit 200.78 / 6 times / Packing insert

Unit 230.89 / 1 times / Cooling filter

Fee subtotal 1,588.18

Plus tax 206.46

Amount requested 1,794.64

Complete invoice text for SF-526862

SF-526862 · Reference and saved responses

Reference
{"invoice_id":"SF-526862","issued_on":"2025-12-21","supplier":"Sample Supplier 7598","currency":"GBP","line_items":[{"description":"Cable sleeve","quantity":1,"unit_minor":15261},{"description":"Packing insert","quantity":6,"unit_minor":20078},{"description":"Cooling filter","quantity":1,"unit_minor":23089}],"subtotal_minor":158818,"tax_minor":20646,"total_minor":179464}
FP16 LoRA
{"invoice_id":"SF-526862","issued_on":"2025-12-21","supplier":"Sample Supplier 7598","currency":"GBP","line_items":[{"description":"Cable sleeve","quantity":1,"unit_minor":15261},{"description":"Packing insert","quantity":6,"unit_minor":20078},{"description":"Cooling filter","quantity":1,"unit_minor":23089}],"subtotal_minor":158818,"tax_minor":20646,"total_minor":179464}
NF4 QLoRA
{"invoice_id":"SF-526862","issued_on":"2025-12-21","supplier":"Sample Supplier 7598","currency":"GBP","line_items":[{"description":"Cable sleeve","quantity":1,"unit_minor":15261},{"description":"Packing insert","quantity":6,"unit_minor":20078},{"description":"Cooling filter","quantity":1,"unit_minor":23089}],"subtotal_minor":158818,"tax_minor":20646,"total_minor":179464}

Try the recipes on a paid invoice

The invoice at the top was issued for a real purchase and published in a redacted council pack. We fit both adapters afresh on an Apple M3 Max using the same Qwen checkpoint, 192 training invoices and 96 updates per recipe. We gave all four models the same text from the paid invoice. This is a separate test from the T4 measurements.

What the models returned

Money fields should be whole pence. A dash means the expected field could not be read from the answer.

ModelQtyUnit priceVATTotal
ExpectedReference111572311388
FP16 promptedFails format check1Mismatch. 11.57Mismatch. 2.31Mismatch. 13.88
FP16 LoRAFails format check————
NF4 promptedFails format check————
NF4 QLoRAWrong recordMismatch. 411572311388

The extra item returned by QLoRA

{"description":"ASIN:B097TSWV5R","quantity":1,"unit_minor":231}

Download the input, expected answer and saved results

See the exact model input

Text from the invoice with the layout reflowed. Addresses, payment and order references, and boilerplate were omitted. The models received these messages in order.

Instruction · system

Extract exactly one JSON object with invoice_id, issued_on (YYYY-MM-DD), supplier, currency (ISO code), line_items (description, quantity, unit_minor), subtotal_minor, tax_minor, and total_minor. Preserve line order and convert currency amounts to integer cents. Use null only for a missing or ambiguous field. Do not rewrite printed amounts, invent fields, or add explanations.

Worked invoice · user

Sample Supplier 7644 | issued 2026-07-15 | invoice SF-898991
Ledger in USD
Service | Count | Per unit
Carrier adjustment | 3 | 188.32
Rack inspection | 8 | 64.15
Before tax 1,078.16
Tax charged 75.47
Balance 1,153.63

Worked answer · assistant

{"invoice_id":"SF-898991","issued_on":"2026-07-15","supplier":"Sample Supplier 7644","currency":"USD","line_items":[{"description":"Carrier adjustment","quantity":3,"unit_minor":18832},{"description":"Rack inspection","quantity":8,"unit_minor":6415}],"subtotal_minor":107816,"tax_minor":7547,"total_minor":115363}

Paid invoice · user

Invoice
Paid
Sold by Zhengzhouyundanzhinengkejiyouxiangongsi
Invoice date / Delivery date: 04.05.2023
Invoice #: DS-ASE-INV-GB-2023-170747294
Total payable: £13.88
VAT declared by: Amazon Services Europe S.a.r.L.

Invoice details
Description | Qty | Unit price (excl. VAT) | VAT rate | Unit price (incl. VAT) | Item subtotal (incl. VAT)
Dongawin gazebo Weights Bag Leg Weights for Pop up Canopy Tent, Patio Umbrella, Outdoor Furniture. (4large, Black) | B097TSWV5R    1    £11.57    20%    £13.88    £13.88
ASIN: B097TSWV5R
Shipping Charges       £0.00       £0.00    £0.00
Invoice total: £13.88

VAT rate | Item subtotal (excl. VAT) | VAT subtotal
20%    £11.57    £2.31
Total  £11.57    £2.31
See the complete answers

Expected record and raw model responses

Expected
{ "invoice_id": "DS-ASE-INV-GB-2023-170747294", "issued_on": "2023-05-04", "supplier": "Zhengzhouyundanzhinengkejiyouxiangongsi", "currency": "GBP", "line_items": [ { "description": "Dongawin gazebo Weights Bag Leg Weights for Pop up Canopy Tent, Patio Umbrella, Outdoor Furniture. (4large, Black) | B097TSWV5R", "quantity": 1, "unit_minor": 1157 } ], "subtotal_minor": 1157, "tax_minor": 231, "total_minor": 1388 }
FP16 prompted
{ "invoice_id": "DS-ASE-INV-GB-2023-170747294", "issued_on": "04.05.2023", "supplier": "Zhengzhouyundanzhinengkejiyouxiangongsi", "currency": "GBP", "line_items": [ { "description": "Dongawin gazebo Weights Bag Leg Weights for Pop up Canopy Tent, Patio Umbrella, Outdoor Furniture.", "quantity": 1, "unit_minor": 11.57 }, { "description": "ASIN: B097TSWV5R", "quantity": 1, "unit_minor": 2.31 } ], "subtotal_minor": 11.57, "tax_minor": 2.31, "total_minor": 13.88 }
FP16 LoRA
{"invoice_id":"DS-ASE-INV-GB-2023-170747294","issued_on":"04.05.2023","supplier":"Zhengzhouyundanzhinengkejiyouxiangongsi","currency":"GBP","line_items":[{"description":"Dongawin gazebo Weights Bag Leg Weights for Pop up Canopy Tent, Patio Umbrella, Outdoor Furniture.","quantity":B097TSWV5R,"unit_minor":1,"item_subtotal_including_vat":13.88,"subtotal_including_vat":13.88,"vat_rate":"20%"},{"description":"ASIN:B097TSWV5R","quantity":0,"unit_minor":0,"item_subtotal_excluding_vat":0,"subtotal_excluding_vat":0,"vat_rate":"20%"}],"subtotal_including_vat":11.57,"vat_subtotal":2.31,"total_vat":11.57,"total_including_vat":13.88,"total":13.88}
NF4 prompted
{ "invoice_id": "DS-ASE-INV-GB-2023-170747294", "paid_at": "2023-05-04", "sold_by": "Zhengzhouyundanzhinengkejiyouxiangongsi", "invoice_date": "2023-05-04", "total_payable": "$13.88", "vat_declared_by": "Amazon Services Europe S.a.r.L.", "invoice_details": { "description": "Dongawin gazebo Weights Bag Leg Weights for Pop up Canopy Tent, Patio Umbrella, Outdoor Furniture. (4 large, Black)", "quantity": 1, "unit_price_excl_vat": "$11.57", "unit_price_incl_vat": "$13.88", "item_subtotal_excl_vat": "$11.57", "item_subtotal_incl_vat": "$13.88" }, "vat_rate": "$20%", "item_subtotal_incl_vat": "$2.31", "total_vat": "$2.31", "vat_rate": "$20%" }
NF4 QLoRA
{"invoice_id":"DS-ASE-INV-GB-2023-170747294","issued_on":"2023-05-04","supplier":"Zhengzhouyundanzhinengkejiyouxiangongsi","currency":"GBP","line_items":[{"description":"Dongawin gazebo Weights Bag Leg Weights for Pop up Canopy Tent, Patio Umbrella, Outdoor Furniture.","quantity":4,"unit_minor":1157},{"description":"ASIN:B097TSWV5R","quantity":1,"unit_minor":231}],"subtotal_minor":1157,"tax_minor":231,"total_minor":1388}

Only QLoRA returned a record in the required format. Its total and VAT were right, but it entered four packs instead of one and turned the product code into a second item. Its first item also leaves out the product variant and code. None of the four answers matched the full record. The check shows exactly where the parser failed on this purchase.

4. Decide what to run on the T4

Start with the two things you need to know. How much memory did training take? Did the parser get the invoices you care about right? Both losses fell on the training examples. Both models still missed 23 of 24 Service invoices.

Training loss fell for both. FP16 was faster and used less memory.

Training loss averaged over eight updates on a log scale

6
  • FP16 LoRA
  • NF4 QLoRA

Cross-entropy on supervised tokens

0.10.010.0010.00018326496Optimiser update at end of block
FP16 LoRA
Mean loss, final 100.00028
Update time21.3 s
Supervised tokens/s1003
Peak allocated4.13 GiB
Adapter weights2,175,168 B
NF4 QLoRA
Mean loss, final 100.00050
Update time34.8 s
Supervised tokens/s614
Peak allocated4.93 GiB
Adapter weights2,175,168 B
Source: Chapter 1 Colab T4 notebook. Block and final-ten means are derived from the saved loss series. Times cover the synchronized update loops in this Colab session. Adapter sizes come from the saved file-size log.

The four-bit base didn’t lead to a smaller training peak here. FP16 LoRA used 4.13 GiB, compared with 4.93 GiB for NF4 QLoRA. Each adapter file was 2,175,168 bytes. The run report has the full loss curves, timings and memory readings.

Why four-bit storage did not give a lower peak

The adapter and the four-bit linear layers are only part of the memory bill. On the bitsandbytes path, PEFT 0.15.2 freezes the base and casts eligible FP16/BF16 parameters other than Params4bit to FP32. That includes the normalisation parameters and Qwen’s vocabulary embedding. The output head shares that matrix, so count it once. At 151,936 × 896 elements, the cast adds about 0.25 GiB of parameter storage. For comparison, the checkpoint’s 357.8 million layer-projection weights would save up to 0.50 GiB when packed from 16 to 4 bits, before quantisation metadata. These are weight-storage calculations. The cast changes the memory budget without explaining the measured peak by itself. PEFT 0.15.2 source · Pinned Qwen config

The measured 0.80 GiB gap is a whole-loop peak. The benchmark did not log memory after each preparation step or split activation, logits and temporary allocations by dtype. The casting calculation explains one cost. Establishing what accounts for the rest needs a phase-by-phase profile.

Check feasibility at the size you need. Hugging Face reports fitting Falcon-7B on one 16 GB T4 with four-bit QLoRA. That establishes feasibility for a larger checkpoint. On the smaller Qwen model in this lesson, both recipes fit, so compare their complete peaks and scores. Hugging Face, company-reported Falcon experiment

What to keep

Test results and training cost on the T4

Register-layout rules

Familiar exact / 96
24
Novel exact / 96
0
Separate exact / 48
0
Valid F / N / S
24 / 0 / 0
Update time
—
Peak VRAM
—
Adapter weights
—

FP16 prompted

Familiar exact / 96
14
Novel exact / 96
1
Separate exact / 48
6
Valid F / N / S
56 / 79 / 36
Update time
—
Peak VRAM
—
Adapter weights
—

FP16 LoRA

Familiar exact / 96
95
Novel exact / 96
54
Separate exact / 48
28
Valid F / N / S
96 / 92 / 45
Update time
21.3 s
Peak VRAM
4.13 GiB
Adapter weights
2.07 MiB

NF4 prompted

Familiar exact / 96
8
Novel exact / 96
0
Separate exact / 48
3
Valid F / N / S
24 / 26 / 11
Update time
—
Peak VRAM
—
Adapter weights
—

NF4 QLoRA

Familiar exact / 96
92
Novel exact / 96
48
Separate exact / 48
41
Valid F / N / S
95 / 93 / 46
Update time
34.8 s
Peak VRAM
4.93 GiB
Adapter weights
2.07 MiB

Validity counts are in familiar, novel and separate order. A dash marks a path with no measured training updates or saved adapter.

  • Measure the whole training loop on your GPU. Start by testing FP16 LoRA when it fits. Here it used 4.13 GiB and 21.3 seconds, compared with 4.93 GiB and 34.8 seconds for NF4 QLoRA.
  • Choose by layout. Test FP16 first for Packing and QLoRA first for Remittance. With either method, check Service line items before posting.
  • Keep a format check and an accuracy check. Require readable output and verify the quantity, unit price and totals separately. Grade omitted and invented lines explicitly. BMW’s company-reported pilot illustrates the same evaluation principle for root-cause matching. With two candidates, no-match F1 rose from 25% for the same-size prompted model to 70% for the tuned adapter. BMW report, Figure 5

Next to try, not tested here

  • Skip only the PEFT preparation cast in a controlled variant. Verify the adapter weights are still FP32, then compare memory before loading, after preparation and during an update.
  • Profile a 7B checkpoint with the same token budget. Predict which precision fits before training.
  • Add price-first invoices to the same training budget and check a new set of suppliers.
  • Repeat the Packing and Remittance comparison with multiple seeds. Check whether the direction holds on the same test invoices.

How it was built

ItemSetting
BaseQwen/Qwen2.5-0.5B-Instruct, revision 7ae557604adf67be50417f59c2c2f167def9a775
TrainingCourse Invoice v1, 192 training records in the same order, one extra training-only demonstration, batch size 2, one pass, seed 42
OptimiserAdamW, learning rate 0.0002, gradient clipping at 1.0, FP16 autocast and dynamic scaling
DecodingOne fixed demonstration, greedy decoding, batch size 16, up to 384 generated tokens within a 1,536-token budget
RuntimeColab Tesla T4. PyTorch 2.14.1+cu130, Transformers 4.51.3, PEFT 0.15.2, Accelerate 1.6.0 and bitsandbytes 0.50.2

Time and cost. On the Colab T4, the update loops took 21.3 seconds for FP16 LoRA and 34.8 seconds for NF4 QLoRA. Both adapter weights files were 2,175,168 bytes. The T4 peak includes the loaded model and allocations during optimisation. The Saltash test used fresh local fits on Apple M3 Max. Its outputs are separate from the timings, memory and scores in the T4 table.

The notebook constructs one schedule and passes it to both recipes. Compare successful updates and supervised token counts before interpreting an accuracy gap.

# The notebook builds this once and passes schedule to each adapter_train call.
chosen = training_items[:192]
examples = [
    encode_supervision(tokenizer, invoice, canonical_json(invoice_record(invoice)), exemplar)
    for invoice in chosen
]
schedule = make_schedule(examples)

Counters from the completed fits

Recorded counterFP16 LoRANF4 QLoRA
Attempted optimiser updates9696
Successful optimiser updates9696
Supervised response tokens21,37821,378
Unpadded input tokens100,690100,690
Trainable parameters540,672540,672

Synchronise CUDA around the timer to measure completed GPU work. The allocation counter starts just before the update loop. It measures live allocations tracked by PyTorch, including model tensors already in memory. Model loading and evaluation happen outside the timer.

# Excerpts from adapter_train, immediately before and after the update loop.
torch.cuda.synchronize()
torch.cuda.reset_peak_memory_stats()
started = time.perf_counter()

# Forward, backward and optimiser updates run here.

torch.cuda.synchronize()
elapsed = time.perf_counter() - started
peak_gib = torch.cuda.max_memory_allocated() / 2**30

Run it yourself

Open the notebook in Colab, select T4 GPU, and run all cells. You can also download the .ipynb above and use File → Upload notebook in Colab. Start by finding SF-357240 in the predictions and checking the quantity against the Service invoice. The paid invoice check includes its own input and saved results.

Then try one change at a time. These are follow-up experiments.

  1. Investigate the Service errors. Replace some of the 192 training invoices with price-first examples. Predict whether the trained model will read 4 × €29.39 correctly. Score the original test set and add examples from new Service suppliers.
  2. Check what NF4 preparation changes. Score the prepared NF4 model before the first update. Compare what it returns on the Packing invoice with the saved NF4 answer.
  3. Find where memory rises. On an idle T4, record memory after loading, after preparation and during updates. Compare the results with the training peak above.

The next chapter tests what happens when you correct training answers and keep the invoices and training budget fixed.

How is this page?

Last updated on