07 · Adapt OCR
Read the same invoice line before and after scan damage, then test whether a vision adapter earns its place.
- Part 3
- Adapt models
- Model
Qwen/Qwen2-VL-2B-Instruct- Data
- Licensed render fonts and Course Invoice v1 crops. CORD-v2 at 7f0115a4b758a71d6473b8d085751692da2fef98 (CC BY 4.0) is an external annotated-line slice.
- Hardware
- Tesla T4, in Google Colab
Can you read the balance?
A scanner blurs the last digit in an invoice balance. Your OCR system has to transcribe the cents and return the line exactly. Read both crops before comparing the four outputs.
Same balance, different pixels
Read the cents digit in both crops from invoice SF-177277.
1Check the last digit against the four OCR outputs
Clean crop · SF-177277
- Expected
- Balance payable 1,122.29
- Tesseract
- Balance payable 1,122.29
- Frozen Qwen
- (13,13),(987,987)
- Clean adapter
- The single line in the image is: "The quick brown fox jumps over the lazy dog."
- Varied adapter
- The single line in the image is: "Transcribe the single line in this image exactly."
Degraded crop · SF-177277
- Expected
- Balance payable 1,122.29
- Tesseract
- Balance payable 1,122.29
- Frozen Qwen
- Balance payable 1,122.29
- Clean adapter
- Balance payable 1,122.29
- Varied adapter
- Balance payable 1,122.29
The expected line ends in .29. Tesseract copied it from both crops. All three Qwen methods copied it from the degraded crop. On the clean one, frozen Qwen returned coordinates, the clean adapter returned a pangram, and the varied adapter echoed the instruction. This example gives you two checks for a transcription system. Measure whether it reads the characters and whether it follows the output instruction.
1. Change the pixels and keep the transcript
OCR reads visible characters. To test whether image degradation matters, preserve the underlying text and vary the image. That creates a comparison where recognition, rather than document content, is the changing condition.
The notebook selects one line of catalogue text per synthetic invoice and uses its row position to crop the rendered page. The notebook creates a clean and degraded image of that line under the same invoice key. Both branches train from the same 72 invoice lines in the same seeded order, with 48 examples processed by each fit. The 32 test invoices come from eight supplier families held out from both fits. Both renders of a given test invoice carry the same transcript.
# Tie each degraded render to its invoice key.
def degrade(image, key):
rng = random.Random(key)
return ImageEnhance.Contrast(
image.rotate(rng.choice((-1.5, -0.8, 0.8, 1.5)), fillcolor="white")
.filter(ImageFilter.GaussianBlur(rng.uniform(0.5, 1.2)))
).enhance(rng.uniform(0.58, 0.85))Rotation simulates a tilted scan. The Gaussian filter softens the strokes, and the contrast multiplier reduces the difference between dark ink and light paper. The fixture text follows the crop through all three changes. Oxford’s SynthText applies related supervision to scene text. The authors compose text onto photographs and supply word and character boxes, reporting roughly 800,000 images and eight million word instances. Oxford VGG SynthText
For a fixed OCR baseline, run the same Tesseract configuration on all three slices. The maintainers document skew as a cause of segmentation failures and mode 7 as the single-line setting. That setting fits these crops. The baseline uses Indonesian and English language packs throughout. Tesseract image quality and segmentation guide
# Run the fixed OCR baseline on exactly the saved line crop.
def tesseract_text(item):
with tempfile.TemporaryDirectory() as location:
path = Path(location) / "crop.png"
item.image.save(path)
return {"text": subprocess.check_output(
["tesseract", str(path), "stdout", "--psm", "7", "-l", "ind+eng"],
stderr=subprocess.DEVNULL, text=True,
).strip(), "complete": None}2. Put the loss on the transcript
Qwen2-VL receives an image and the instruction Transcribe the single line in this image exactly. Output the line only. The model’s chat template adds vision markers. The processor expands the image placeholder into visual tokens. Encode the prompt and the prompt-plus-answer from the same pixels, then check that the expanded prefix agrees token for token before masking it. The masked prefix still supplies context to the model. Transformers 4.51.3 Qwen2-VL documentation · Pinned Qwen2-VL chat template
# Check the expanded prefix before masking it.
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] = -100The loss starts with “Balance”
Label mask for the clean opening crop
2Masked prefix · 64 tokens
28 image tokens · 36 other tokens
First supervised token
BalanceThe loss averages the negative log probabilities at the supervised positions. The symbols below denote the prompt and image context, the target token, and the set of supervised positions. The -100 label keeps a position out of that average.
The opening mask record makes the boundary inspectable. It counts 28 image tokens and 64 masked prefix tokens. The first supervised token decodes to Balance. Those counts describe different parts of the encoded sequence. The image tokens sit inside the masked prefix, and still participate in attention. Check the decoded boundary if you change the processor or chat template. A training loss can look healthy even if the replay has quietly started scoring the wrong completion span.
There is a second boundary at inference. We want the continuation returned by the decoder, stripped of the chat prompt, compared with the printed transcript. Check both token slicing and the decoded text when a model echoes instructions. The opening example gives three materially different failure shapes on the clean crop. Coordinates suggest a localisation-style answer. The pangram is fluent text unrelated to the line. The instruction echo repeats the task wording. Those failures all require rejection at the payment desk. Increasing sharpness on the input is a weak response to any of them until the raw output is understood.
3. Score each slice separately
Exact match asks whether any character differed after whitespace normalisation. Character error rate (CER) and word error rate (WER) count partial errors. Pool insertions I, deletions D, substitutions S and reference length N across the slice. Use characters for CER and whitespace-delimited words for WER.
The notebook preserves case, punctuation and digits. A one-character mistake can change the amount while barely moving CER. Excess insertions can push a rate above 100%. The varied adapter’s clean-crop instruction echo needed 74 character edits to become the 24-character reference.
Varied training helped on degraded invoices. The clean crops tell a different story.
Character and word error rates by slice. Both measures use the same 0–500% scale.
3Character error rate
Word error rate
| Method | Clean invoices, exact /32 | Degraded invoices, exact /32 | CORD crops, exact /20 |
|---|---|---|---|
| Tesseract | 23 | 17 | 8 |
| Frozen Qwen | 0 | 21 | 1 |
| Clean adapter | 0 | 15 | 0 |
| Varied adapter | 0 | 27 | 0 |
| Method | Clean invoice CER | Degraded invoice CER | CORD CER |
|---|---|---|---|
| Tesseract | 1.1% | 2.2% | 23.0% |
| Frozen Qwen | 97.2% | 16.1% | 102.2% |
| Clean adapter | 215.9% | 23.4% | 420.4% |
| Varied adapter | 184.4% | 0.8% | 353.3% |
These are rounded readings of the saved slice scores. The numerator comes from the edit counter and the denominator from the reference, as shown in the notebook.
# Measure the edits against the reference length.
def error_counts(process, truth, prediction):
counts = process(truth, prediction)
edits = counts.substitutions + counts.deletions + counts.insertions
reference_length = counts.hits + counts.substitutions + counts.deletions
return edits, reference_lengthDegraded invoices. The varied adapter had 0.8% CER and 6.2% WER. Tesseract had 2.2% CER and 15.4% WER. The comparison with Tesseract is descriptive. The paired intervals below compare the two adapters.
Clean invoices. Tesseract had 1.1% CER and 23 exact matches. Frozen Qwen returned coordinates, including (13,13),(987,987) on the opening crop. The varied adapter had 184.4% CER and zero exact matches. Review the actual strings before deciding to train more steps. Line-by-line predictions
4. Test receipt transfer on annotated lines
CORD v2 supplies word quadrilaterals and a line order for Indonesian receipts. The notebook took one eligible annotated line from each of 20 official test receipts. It joined the annotated words in order, cropped around their quadrilaterals, and padded any dimension under 28 pixels with white. All four methods saw the same padded crops. NAVER CLOVA CORD data specification
Read the line the CORD annotators marked
CORD test receipt 0 · annotation-derived crop
4
CORD · cord-0
- Annotation
- -TICKET CP
- Tesseract
- -TICKET CP
- Frozen Qwen
- (131,101),(869,907)
- Clean adapter · hit the decode cap
- The line in the image is: "The line in the image is: "The line in the image is: "The line in the image is: "The line in the image is: "The line in the image is: "The line in the image is: "The line in the image is: "
- Varied adapter · hit the decode cap
- The line in the image is: "The line in the image is: "The line in the image is: "The line in the image is: "The line in the image is: "The line in the image is: "The line in the image is: "The line in the image is: "
Both adapters repeated a phrase and reached the 64-token decode cap on this crop. Their output still counted in CER and WER. Across 20 crops the varied adapter scored 353.3% CER and zero exact matches. Tesseract scored 23.0% CER and got eight lines exactly right. The experiment measures transcription with the line locations already supplied.
If a scanner produces a mixture of clean and degraded lines, resist the temptation to route based on the model’s own confidence alone. The opening clean outputs are confidently formed strings with the wrong contract. A routing test needs an independent label for scan condition, backed by the image itself. Then check cases around the boundary, including a clean-looking image with a clipped right edge and a blurred image with still-readable cents. These are proposed acceptance cases for a real scanner. The measured evidence here comes from the controlled rotations, blur and contrast changes.
A receipt-processing team should split localisation and transcription when it measures a replacement. CORD gives the notebook an oracle for line location. In a deployed pipeline, a detector may cut off the start of a price or join two adjacent lines before the transcription stage sees them. The supplied crop puts that source of error outside this score. Keep a manually checked crop set for diagnosing the recogniser and a separate end-to-end receipt set for measuring the impact of localisation errors on posting.
When a line is capped, keep its entire returned text for review and mark the event in the evaluation. A caller may otherwise trim repeated words, count a shorter output and record an apparent CER gain without recovering the missing information. The paired receipt result gives a concrete reason to keep both exact and edit-based scores. Even if a replacement removes many excess characters, a line with the wrong amount or a missing product still goes to exception handling. In a payable workflow, splitting mismatches by consequence is more useful than routing everything through a single CER threshold. A garbled description needs a reviewer to identify the line, while a plausible wrong balance should stop the posting step.
How stable was the difference between the two fits?
Pair predictions on the same crop and keep references fixed. The bootstrap draws supplier families with replacement for the invoices and receipts with replacement for CORD. It keeps matched predictions together, then recomputes the relative edit counts over the sampled groups.
The varied fit reduced both error rates on all three slices
Varied minus clean adapter in percentage points, with paired 95% bootstrap intervals
5Character error rate
Clean invoices · −31.6 pp
−53.0 to −11.2 pp · 8 groups
Degraded invoices · −22.6 pp
−34.3 to −12.9 pp · 8 groups
CORD receipt lines · −67.0 pp
−148.9 to −12.8 pp · 20 groups
Word error rate
Clean invoices · −72.2 pp
−102.3 to −39.9 pp · 8 groups
Degraded invoices · −22.8 pp
−35.0 to −13.1 pp · 8 groups
CORD receipt lines · −79.6 pp
−161.1 to −20.0 pp · 20 groups
On degraded invoices, the clean-to-varied CER change was −22.6 points with a 95% interval of −34.3 to −12.9. On CORD the change was −67.0 points, with zero exact transcripts for both fits. The intervals use eight invoice families or 20 receipts, with one seed per fit.
What to keep
| Option | Where to use it | Check before routing |
|---|---|---|
| Tesseract | Starting point for clean invoices and supplied CORD line crops | Inspect the source line when payment fields disagree. |
| Frozen Qwen | Reference for the effect of adapting the checkpoint | Reject coordinates and other non-transcript output. |
| Clean adapter | Control for the varied training images | Treat clean and degraded scores separately. |
| Varied adapter | Candidate for representative degraded invoices | Check clean inputs, instruction echoes and cap hits before allowing automatic entry. |
- Preserve the reference. Use the exact same line and target when testing an input transformation.
- Grade payment fields exactly. A wrong cent digit can be material even when nearly every other character agrees.
- Hold out supplier families. Keep lookalike layouts and repeated supplier names from making the test easier than production.
- Check the output contract. Review coordinates, instruction echoes and output at the decode cap as well as spelling errors.
- Separate localisation from transcription. Annotated boxes answer a different question from a full-page receipt trial.
- Next to try, not tested here: evaluate clean, skewed and low-contrast samples from a production scanner and set review rules per slice.
How it was built
| Item | Setting |
|---|---|
| Base model | Qwen2-VL-2B-Instruct at 1860c46f12b7449d0f5b426a7474ab715342bc65. NF4 double quantisation, FP16 weights and compute, and SDPA. |
| Method | Language-backbone LoRA on q_proj and v_proj, rank 8, alpha 16, dropout 0, AdamW at 1e-4, gradient clip 1.0, seed 42. |
| Training | 24 updates per fit, accumulation 2, 48 examples processed. |
| Decoding | Greedy with a 64-new-token cap for all three Qwen variants. |
| Test | 32 invoices per render and 20 annotated CORD lines. |
| Data | course-invoice-v1 paired clean and degraded crops. CORD v2 at 7f0115a4b758a71d6473b8d085751692da2fef98, official test split. |
| Hardware | One Tesla T4. PyTorch 2.14.1+cu130, Transformers 4.51.3, PEFT 0.15.2, Accelerate 1.6.0, bitsandbytes 0.50.2, Pillow 11.3.0, datasets 3.6.0, jiwer 4.0.0, Tesseract 5.3.4. |
The notebook profiles the longest training candidate before comparing the full checkpoint, Tesseract and both fits. That candidate was SF-540371, with 99 prompt-plus-answer tokens. The profile took 3.92 seconds for one update.
Both 24-update fits stayed near 2.06 GiB allocated
Synchronised update-loop time and peak PyTorch allocated memory on the T4
6Training loop time
Peak allocated memory
Time and cost. The timer inside the experiment logged 438.41 seconds. The enclosing execution receipt recorded 475.79 seconds, including setup. The fit chart clocks the update loops after model and optimiser setup. PyTorch’s reserved memory includes cached allocator blocks and can exceed actively allocated tensor memory.
Run it yourself
Download the executed notebook · Download scores and exact outputs · Download the T4 profile
Allow 475.79 seconds on the measured T4 setup. The notebook’s input-variation cells match the crop pairs, the loss section matches the label mask, and the final results cell saves the outputs for slice scoring and receipt transfer. Save the original scores before changing a single setting.
- Remove rotation. Predict whether removing rotation from the varied training render improves or worsens exact match on the original degraded slice. Hold all evaluation pixels fixed. Compare exact match and inspect three changed predictions.
- Segmentation. Predict which slice is most sensitive to using Tesseract mode 6 in place of line mode 7. Change that flag on the same files and compare the full strings before reading CER.
- Decode cap. Predict whether reducing the cap lowers CORD CER for the varied adapter and whether it truncates any otherwise correct invoice lines. Keep the trained weights fixed. Report how many generations reach the cap alongside exact match.
Check the saved files
| Record | SHA-256 |
|---|---|
| Executed notebook | 2c01990d79f865e518d4c2a6c6cb79aca75a782d4e6394846153ab951e280d5c |
| Scores and line outputs | 67f7e032f7c9e48ad9ca253410af1c35dfdf2a3bd23638e9ecf2eb2fe6f5853f |
| T4 profile | e822caf38f9dafb1cbdf2ef8eeac0595cd030353bcdea819e0bf7eca1967c5d0 |
How is this page?
Last updated on

