What it does
- Input: receipt text from OCR, lines separated by newlines. It does not read images.
- Output: JSON with
company, date (as printed, without the time), address (all lines
joined with one space) and total (number with two decimals, no currency). A missing field is "".
- Trained on: SROIE (ICDAR 2019 Task 3), scanned receipts in English (https://arxiv.org/abs/2103.10213).
The labelling rules above are written into the prompt (src/llm_document_extraction/prompts.py).
The adapter was trained with exactly that prompt, so use it unchanged.
How to use
Needs a CUDA GPU, plus torch, transformers, peft, bitsandbytes and accelerate. The base is
loaded in 4-bit NF4, the same way it was during training and evaluation
(src/llm_document_extraction/inference.py, scripts/run_val_finetuned.sh).
import torchfrom peft import PeftModelfrom transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig BASE = "Qwen/Qwen3-1.7B"ADAPTER = "saiiexd/qwen3-1.7b-qlora-receipt-extraction" # The exact prompt used in training and evaluation (src/llm_document_extraction/prompts.py).SYSTEM_PROMPT = """You extract key fields from the OCR text of a scanned receipt. Return ONLY a JSON object with exactly these keys:{"company": "...", "date": "...", "address": "...", "total": "..."} Rules:- company: the name of the business that issued the receipt, copied as printed.- date: the receipt date as printed, without the time.- address: the business address, all address lines joined with a single space, copied as printed.- total: the final amount paid, as a number with two decimals and no currency (e.g. "9.00").- If a field is not present, use "".- No explanations, no markdown, only the JSON object.""" tokenizer = AutoTokenizer.from_pretrained(BASE)model = AutoModelForCausalLM.from_pretrained( BASE, dtype=torch.bfloat16, device_map="cuda", quantization_config=BitsAndBytesConfig( load_in_4bit=True, bnb_4bit_quant_type="nf4", bnb_4bit_compute_dtype=torch.bfloat16, bnb_4bit_use_double_quant=True, ),)model = PeftModel.from_pretrained(model, ADAPTER)model.eval() @torch.no_grad()def extract(receipt_text: str) -> str: messages = [ {"role": "system", "content": SYSTEM_PROMPT}, {"role": "user", "content": f"Receipt OCR text:\n{receipt_text}"}, ] prompt = tokenizer.apply_chat_template( messages, tokenize=False, add_generation_prompt=True, enable_thinking=False, ) inputs = tokenizer(prompt, return_tensors="pt").to(model.device) out = model.generate( **inputs, max_new_tokens=256, do_sample=False, # greedy decoding, as in evaluation temperature=None, top_p=None, top_k=None, pad_token_id=tokenizer.eos_token_id, ) return tokenizer.decode(out[0, inputs["input_ids"].shape[1]:], skip_special_tokens=True) print(extract("BOOK TA .K (TAMAN DAYA) SDN BHD\nNO.53 55,57 & 59, JALAN SAGU 18\nTOTAL 9.00"))
The output is a string. Parse it with json.loads, or with parse_output from
src/llm_document_extraction/metrics.py, which also handles stray text around the JSON and
returns None for invalid output. To serve it over HTTP, see src/llm_document_extraction/serve.py
(FastAPI, POST /extract).
Training details
All values from scripts/train_qlora.py and DECISIONS.md unless marked.
Table with columns: Setting, Value| Setting | Value |
|---|
| Method | QLoRA: frozen 4-bit base + trainable LoRA adapters |
| Base quantisation | NF4 4-bit, double quantisation, bf16 compute |
| LoRA | r = 16, alpha = 32, dropout 0.05 |
| LoRA target modules | q_proj, k_proj, v_proj, o_proj, gate_proj, up_proj, down_proj (all 7 linear projections) |
| Trainable parameters | 17,432,576 of 1,738,007,552 (1.0%), from results/logs/train_qwen3-1.7b-qlora.log |
| Optimizer | paged 8-bit AdamW |
| Learning rate | 2e-4, cosine schedule, warmup 5% of steps |
| Batch | 1 per step x gradient accumulation 16 = effective batch 16 |
| Epochs | 3 (script default 3 = 108 optimizer steps; chosen on validation loss, lowest after epoch 3; see DECISIONS.md) |
| Precision | bf16 mixed precision, gradient checkpointing |
| Max sequence length | 1536 tokens; longest training example 1,133 tokens; nothing truncated |
| Seed | 42 |
| Hardware | NVIDIA RTX 3050 Laptop GPU, 6 GB |
| Training time | 33.4 min (training_log.json: train_minutes) |
| Peak VRAM | 4871 MB (training_log.json: peak_vram_mb) |
| Software | transformers 5.24.1, peft 0.22.0, bitsandbytes 0.50.2, torch 2.15.0, accelerate 1.16.0 (uv.lock) |
Training data. 563 SROIE training receipts. 63 more from the official training set are held out
as a validation set (seed 42), and the 347 official test receipts are used only once, for the final
score (scripts/prepare_data.py, results/data_stats.json). OCR text comes from the original SROIE
box files, because one public copy of the dataset cuts every OCR line at its first comma
(DECISIONS.md).
Training format. Each example is the exact inference prompt + the target JSON + the end-of-sequence
token. Loss is computed on the target and end token only; prompt tokens are masked with label -100
(src/llm_document_extraction/training_data.py, tested in tests/test_training_data.py).
Why batch 1. Batch 2 ran out of memory on 6 GB: the output layer produces a score for each of
151,936 vocabulary tokens at every position, in fp32 (DECISIONS.md).
Evaluation
Metric (src/llm_document_extraction/metrics.py, written and tested before any model ran):
per-field exact match after normalisation (case, spaces; currency and thousands commas in total;
spacing around punctuation in address). Field accuracy is the mean of the four fields; "all fields
exact" counts receipts with all four right. Every system gets the same prompt and greedy decoding.
Test set (347 receipts)
Table with columns: System, Field acc %, All fields exact %, Valid JSON %, Company exact %, Date exact %, Address exact %, Total exact %, Median latency s, Peak VRAM MB| System | Field acc % | All fields exact % | Valid JSON % | Company exact % | Date exact % | Address exact % | Total exact % | Median latency s | Peak VRAM MB |
|---|
| qwen3-0.6b-base | 67.4 | 25.1 | 100.0 | 63.4 | 88.5 | 38.9 | 78.7 | 2.69 | 1279 |
| qwen3-1.7b-base | 75.0 | 29.4 | 100.0 | 73.2 | 97.4 | 47.3 | 82.1 | 3.49 | 3449 |
| qwen3-1.7b-qlora | 93.4 | 76.4 | 100.0 | 94.8 | 98.6 | 83.3 | 97.1 | 3.61 | 1566 |
| qwen3-4b-ollama | 80.0 | 39.8 | 100.0 | 63.4 | 98.3 | 63.1 | 95.1 | 5.56 | n/a |
Fine-tuning gain (qwen3-1.7b-qlora minus qwen3-1.7b-base): field accuracy +18.4 pp, all fields exact +47.0 pp. Note: qwen3-1.7b-qlora ran on a 4-bit base and qwen3-1.7b-base in bf16, so this gain also includes the effect of 4-bit loading.
Notes for readers:
- Precision: the baselines ran in bf16 and the fine-tuned model on its 4-bit NF4 base, the base it
was trained on (
load_4bit in each metric file; scripts/run_val_finetuned.sh). So the
fine-tuning gain also includes the effect of 4-bit loading, as the gain line says. The effect of
4-bit loading alone was not measured. The Ollama row is a 4-bit GGUF model even though its metric
file says load_4bit: false (that flag only applies to transformers loading).
- Latency: median 3.61 s per receipt for the fine-tuned model (4-bit base, transformers, batch 1, RTX 3050 Laptop GPU at full memory clock). Only runs with
gpu_mem_clock_mhz_min at full clock are valid;
earlier runs were measured while the GPU memory clock was throttled to 810 MHz and are not reported.
Ollama latency comes from a different engine (4-bit GGUF) and is not comparable with transformers.
Limitations
- Text only. Bounding boxes and the image are not used, so layout cannot help.
- Depends on OCR quality. About 14% of gold addresses do not appear verbatim in the OCR text
(
results/data_stats.json); OCR errors become extraction errors.
- Narrow domain. SROIE receipts only, four fields. Not tested on invoices, other languages
or other layouts.
- Small test set and a single training seed. Differences of a few percentage points between
systems may be noise.
total normalisation treats commas as thousands separators, which suits SROIE but not
formats like "9,00".
- Output is not guaranteed to be valid JSON. Always check, for example with
parse_output.
- Not intended for automated financial decisions without human review.
Citation
SROIE dataset: Huang et al., "ICDAR2019 Competition on Scanned Receipt OCR and Information
Extraction", https://arxiv.org/abs/2103.10213
QLoRA: Dettmers et al., 2023, https://arxiv.org/abs/2305.14314. LoRA: Hu et al., 2021,
https://arxiv.org/abs/2106.09685