Skip to Content
Recodocs

09 · Tune visual document retrieval

Find the right invoice from a partial clue and decide whether adapting the visual search is worth the cost.

11 min read
Part 3
Adapt models
Model
vidore/colqwen2-v1.0-hf
Data
Course Invoice v1 question–page pairs, split by supplier and layout family
Hardware
Tesla T4, in Google Colab

Which invoice belongs in the review queue?

You work in accounts payable. A colleague remembers the supplier and the printed amount, but has lost the invoice ID. They ask, “Find the invoice from Sample Supplier 3177 showing 1,122.29 due.” Both synthetic invoices below name the same supplier. Choose one before opening the ranking. Sending the wrong page would put another bill into the review queue.

Two invoices from Sample Supplier 3177

Which page shows 1,122.29 due?

Candidate A

SF-265176, Sample Supplier 3177, balance payable USD 715.50.

Candidate B

SF-177277, Sample Supplier 3177, balance payable USD 1,122.29.
Original synthetic course invoices rendered with the notebook’s fixture code. Open either crop to enlarge it.
Check the payable and the three search results

Candidate B shows a balance payable of USD 1,122.29. Candidate A shows USD 715.50. All three searches returned candidate B first from the full pool of 40 pages.

Find the invoice from Sample Supplier 3177 showing 1,122.29 due.

Expected
SF-177277
OCR BM25
Returned SF-177277 · expected page at rank 1
Frozen ColQwen2
Returned SF-177277 · expected page at rank 1
Query adapter
Returned SF-177277 · expected page at rank 1

The query adapter moved more correct pages to the top

80 queries · 40 candidate pages · percentage or nDCG × 100

1
050100OCR BM25Frozen ColQwen2Query adapter● Recall@1○ nDCG@10
Source · Verified Lab 09 output on one Tesla T4.

1. Keep the pages fixed

To compare retrieval methods, give them the same document pool. Otherwise a method might win simply because the relevant invoice was available to it and absent from the competing index.

A rank of one means you can send the first hit straight to the review queue. Recall@1 counts those hits, giving 62/80 for OCR BM25, 64/80 for frozen ColQwen2 and 75/80 for the query adapter. nDCG@10 gives partial credit deeper in the results. With exactly one relevant page and rank r, each query contributes:

g(r)={1/log⁡2(r+1),r≤100,r>10g(r) = \begin{cases} 1 / \log_2(r+1), & r \le 10 \\ 0, & r > 10 \end{cases}

The opening invoice scores 1.0 under all three arms. The replay below ends at rank six for the adapted model, so the formula gives partial credit while the shortlist test records a miss. Frozen visual search gained 1.74 nDCG points over BM25, with a 95% interval of −3.61 to +7.04 points. The notebook bootstraps supplier families together, so related queries stay paired during resampling.

ViDoRe evaluates page retrieval over larger pools. Its practical tasks use 1,000 pages and 100 vetted queries per topic. Its reported ColPali ablation compared 81.3 mean nDCG@5 for multi-vector scoring with 58.8 for BiPali. This notebook uses a different model, task and cutoff. Retain the fixed candidate pool if you want to attribute a change to the query path. ColPali paper, sections 3 and 5

SearchCorrect at rank oneCorrect in the first fivenDCG@10
OCR BM2562/8080/8089.16%
Frozen ColQwen264/8080/8090.90%
Query-adapted ColQwen275/8079/8097.19%

The scores are rounded from the saved report. A system serving a single suggested invoice needs the first column. A reviewer working through a shortlist needs the second. nDCG helps when the location within that shortlist affects their time. Choose the output shape first and use the score that reflects the workflow. The saved result is a better match for the single suggestion, yet it contains a real regression if the correct page has to appear in the first five.

The notebook turns scores into a deterministic order before recording rank and first result. Sorting by invoice key for tied scores gives the replay an explicit tie rule. A different tie rule can move a page with the same score across a cutoff and should be held fixed during the comparison.

# Use the document key to break ties between equal scores.
def rank_of(scores, keys, gold):
    ranks = sorted(zip(keys, scores, strict=True), key=lambda item: (-item[1], item[0]))
    return next(i for i, (key, _) in enumerate(ranks, 1) if key == gold), ranks[0][0]

Both visual arms search one fixed index

What changes at query time

2

OCR and lexical search

Page pixels → Tesseract text → BM25 index. The query uses word tokens.

Frozen and adapted visual search

Page pixels → ColQwen2 tokens → shared index. An optional projection transforms the query tokens before scoring.

Source · Lab 09 notebook scoring and index construction.

Each query in the notebook has one adjudicated answer. Candidate pages with ambiguous clue combinations can still distract the retriever. The pooled test pages include familiar, novel and independent layouts, with suppliers and families held out from the training roster. The two visual arms share an immutable index, while BM25 ranks OCR text produced from the same pixels. ColQwen2 model card

2. Match the method to the clue

For the opening pair, Tesseract retained both the supplier string and the payable. Its index contains “Sold by Sample Supplier 3177” and “Balance payable 1,122.29” for candidate B. The first string is identical for candidate A, whose index instead contains “Balance payable 715.50.” Check OCR text before tuning the retrieval model. The notebook runs English OCR in page segmentation mode 11, which treats the page as sparse text. Full indexed OCR text · Tesseract segmentation documentation

Exact printed amounts already suited lexical search

Recall@1 · 40 queries per clue type

3

Supplier and balance

OCR BM25100.0%
Frozen ColQwen287.5%
Query adapter92.5%

Date, currency and service

OCR BM2555.0%
Frozen ColQwen272.5%
Query adapter95.0%
Source · Verified Lab 09 output on one Tesla T4.

Lexical search found the right page first on all 40 supplier-and-balance queries. The query adapter’s largest gain over its frozen visual control was on date-and-service queries, from 29/40 to 38/40. The service example below shows how a single wrong date can still defeat that comparison.

Query cluesOCR BM25 firstFrozen ColQwen2 firstQuery adapter first
Supplier and balance40/4035/4037/40
Date and service22/4029/4038/40

The two clue groups expose a decision that the aggregate hides. If a clerk gives you a supplier and a literal amount, exact strings can get the right page to the top without the query encoder. When the clue is a service described in the document, the page vector may help rank a relevant line among similar amounts and suppliers. The adapter changed the relative ranking of these groups. The fact that it helped date-and-service queries here doesn't guarantee that it recovers a date missing from another scan.

In an accounts-payable product, the caller might be able to declare which clue they have. That gives you a way to compare a fast primary path and an optional visual search without forcing all queries through the same model. If the caller writes freely, work out how the router will identify an actual amount and an unambiguous currency. A query containing a number might refer to a date, an invoice suffix or a payable. Keep a record of misrouted queries so you can distinguish a poor route from a poor rank within the right route.

3. Learn a change on the query side

A visual page has a collection of token vectors. Late interaction scores each query token against every real page token, then sums the best match per query token. Each query token gets its own maximum. That lets the supplier cue and amount cue take evidence from different parts of a page. Masking padding matters because a padding score of zero could wrongly beat a real negative similarity.

# Exclude padded page tokens before taking the maximum.
def maxsim(query, documents, mask):
    similarities = torch.einsum("qd,nkd->nqk", query.float(), documents)
    return similarities.masked_fill(
        ~mask[:, None, :], -torch.inf
    ).amax(dim=-1).sum(dim=-1)

The adapter starts with a zero residual and applies a learned matrix to each query token before normalisation. The page tokens remain fixed.

qi′=normalize⁡(qi+Wqi)q'_i = \operatorname{normalize}(q_i + Wq_i)

At each update, put the gold page first in the scoring batch, then add six distractors. The notebook prioritises same-supplier pages and lexical overlap for three hard negatives, then samples three from the remaining training pages. Cross-entropy uses target index zero. For the first recorded update, the search requested Sample Supplier 8288 and a balance of 1,213.99 on SF-537040. The positive page and all six selected distractors are listed below. All 32 updates

One positive page competes with six negatives

First of 32 projection updates

4

Sample Supplier 8288 billing memo / 2025-10-21 Account invoice SF-537040 [GBP] 6 x Door seal @ 134.27 per unit 2 x Grounding clip @ 116.39 per unit 1 x Cooling filter @ 35.93 per unit Total due 1,213.99 including tax 139.66; net amount 1,074.33.

Positive
SF-537040
Three ranked negatives, then three sampled negatives
SF-280550 · SF-531542 · SF-231446 · SF-851512 · SF-231789 · SF-649982
Cross-entropy loss
0.738
Source · Verified Lab 09 output on one Tesla T4.

The hard negatives make the positive compete on a meaningful detail. A same-supplier page can carry the same name in the same visual position and still show a different payable. If easy random negatives dominate the fit, the adapter could score supplier cues well while failing on the opening pair. Adding more hard negatives is a plausible next step, but the saved experiment doesn't compare different mixes. Inspect the selected IDs before changing the mix and check if any negative would also satisfy the search request.

Both visual arms read the same page embeddings and use identical candidate identifiers. The notebook records a rank and first-result ID together with preparation and scoring time. It adds encoding time explicitly, which guards against reporting only the fast matrix operation while excluding the work that produced the query vectors.

# Keep query preparation time in the recorded result.
def add_result(query, arm, scores, started, encoding_seconds=0.0):
    rank, first = rank_of(scores, test_keys, query["gold"])
    seconds = encoding_seconds + perf_counter() - started
    results.append({**query, "arm": arm, "rank": rank, "top1": first, "seconds": seconds})

4. Inspect a rank regression

The query asks for the GBP bill dated 2025-12-21 that charges for Cable sleeve. The adapter put a different GBP invoice first. Compare the date on both pages before checking the ranks.

The returned page matches the service and currency, but misses the date

Find the GBP bill from 2025-12-21 that charges for Cable sleeve.

5

Expected · SF-526862

Expected invoice SF-526862, GBP, dated 2025-12-21, listing Cable sleeve.

Service fee notice, 2025-12-21 · Unit 152.61/ 1 times/ Cable sleeve

Adapter’s first result · SF-576379

Adapter’s top invoice SF-576379, GBP, dated 2025-01-22, also listing Cable sleeve.

Sample Supplier 7823 billing memo/ 2025-01-22 · 9x Cable sleeve @ 169.60 per unit

Source · Verified Lab 09 output on one Tesla T4.

Find the GBP bill issued on 2025-12-21 that charges for Cable sleeve.

Expected
SF-526862
OCR BM25
Returned SF-548824 · expected page at rank 3
Frozen ColQwen2
Returned SF-181336 · expected page at rank 5
Query adapter
Returned SF-576379 · expected page at rank 6

The correct invoice fell from rank five to six after adaptation. That one query accounts for the drop in Recall@5 from 80/80 to 79/80. The returned page has the right item description, but it is dated 2025-01-22. The raw OCR contains both dates and the shared service. That rules out a missing OCR date as an explanation for this replay, while the rank logs alone cannot tell which cues the visual model weighted. Raw per-query ranks

If a reviewer only sees the first suggestion, the GBP service regression has a specific cost. The first page shows the correct service text, so a skim might miss the date mismatch. Keep the query date visible beside the result and compare it against the invoice issue date before the page moves into the review queue. If matching is ambiguous, the reviewer can ask for the invoice ID or widen the candidate list. The ranking alone doesn't tell you how the reviewer responded, so measure that step separately if you want to estimate time saved.

The positional failure also illustrates why we keep different cutoffs in the report. An improvement in first positions across the collection can coexist with a page dropping just beyond the reviewer’s search window. Inspect rank changes in both directions when replacing the search, particularly for any request that loses a result at the cutoff. With only a few supplier families in a group, a local layout convention can drive a cluster of such changes. Preserving the family grouping in the bootstrap keeps that dependency visible.

What to keep

OptionWhere it fitsCheck before adopting
OCR BM25Fast path for explicit supplier and balance queriesInspect what OCR retained for the actual amount.
Frozen ColQwen2Visual baseline with a reusable page indexTrack the ranking by clue group and cutoff.
Query-adapted ColQwen2Candidate for mixed date-and-service cluesVerify the date and check dropped shortlist hits.
  • Choose the cutoff from the review workflow. A single suggested invoice and a five-page shortlist have different failure modes.
  • Inspect the indexed OCR. A repeated supplier name may still be distinguishable by the exact printed balance.
  • Hold the pages fixed. Point both visual arms at the same page tokens to isolate the query projection.
  • Check the full clue. A result with the right service but wrong date should stay out of payment review.
  • Budget for query encoding. Include it in latency measurements even when you reuse the visual page index.
  • Next to try, not tested here: compare routes by clue group on a larger, mixed-quality invoice collection with adjudicated relevant pages.

How it was built

ItemSetting
Base modelColQwen2 revision ddc07d2317c80f75fc742b7362ee9ad1912908f9, FP16.
Data48 synthetic invoice training pages.
Test40 held-out pages with 80 queries.
MethodOCR BM25, frozen visual late interaction and a learned query-only residual.
Training32 AdamW steps, learning rate 0.001 and seed 409.
DecodingNo generated answer. Rank scores descending, then invoice key ascending for ties.
HardwareTesla T4, CUDA 13.0, PyTorch 2.14.1+cu130.

The visual query took about 94 ms in either arm

Single-query search in a warm notebook · milliseconds

6

Median and 95th percentile

OCR BM25
0.41 ms median · 0.67 ms p95
Frozen ColQwen2
94.45 ms median · 98.30 ms p95
Query adapter
94.49 ms median · 98.30 ms p95

Persisted inputs to search

OCR text by page
12,274 bytes · 43.16 s to build
Shared visual token index
7,333,951 bytes · 52.23 s to build
Source · Verified Lab 09 output on one Tesla T4.

One Tesla T4 ran the default profile with CUDA 13.0, PyTorch 2.14.1+cu130, Transformers 4.57.1, rank-bm25 0.2.2, pytesseract 0.3.13 and Tesseract 5.3.4. ColQwen2 uses revision ddc07d2317c80f75fc742b7362ee9ad1912908f9 with FP16 weights. The 32 AdamW steps use a learning rate of 0.001 and seed 409. The one-page, one-query and backward preflight took 7.03 seconds and reserved 4.65 GiB. Peak allocation across the run was 4.27 GiB.

Time and cost. The receipt records 239.15 seconds. With embeddings ready, projection fitting took 0.26 seconds. The saved OCR text occupied 12,274 bytes and the visual token index occupied 7,333,951 bytes. The saved query projection occupies 67,304 bytes. Query timings include query processing and scoring. The visual encoder cost is charged to both visual arms. Index times are separate, and the stored OCR JSON represents text used to build BM25 in memory. The payload comparison measures those stored inputs and visual token vectors. Run report and candidate roster · Execution receipt

Run it yourself

Open the notebook in the facts box or download the exact notebook used for the run. Allow 239.15 seconds on the measured T4 setup. The notebook’s query-definition and index sections map to the fixed pool and clues. Its projection section maps to query training and the retrieval section writes the records used for the regression replay.

  1. Predict how OCR BM25 will rank the opening pair when the query omits the balance. Change only that query, then inspect rank and top1 in ranks.jsonl alongside the stored OCR text.
  2. Predict which result a required date match would reject for SF-526862/date-and-service. Apply only that check to the saved first hits, then inspect which results still qualify for review.
  3. Predict how changing the hard-negative allocation from three to four at the same total negative count will affect the shortlist. Keep the seed, updates and held-out pool fixed. Inspect paired nDCG@10, Recall@5 and the saved regression’s rank.

Back to the course

How is this page?

Last updated on