davanstrien HF Staff commited on
Commit
02f715f
·
verified ·
1 Parent(s): 5bbe409

Sync from GitHub via hub-sync

Browse files
Files changed (2) hide show
  1. CLAUDE.md +216 -913
  2. OCR-BENCHMARK.md +93 -0
CLAUDE.md CHANGED
@@ -1,949 +1,252 @@
1
- # OCR Scripts - Development Notes
2
-
3
- ## Large full-page scan fixes (2026-07-01)
4
-
5
- A batch of scripts run over a **large**-page historical book-scan corpus (WebP, ~2000–4000px /
6
- 7–9 MP) exposed 5 failures. Root-caused + fixed + verified on Jobs (l4x1, `--max-samples 4–16` on
7
- that corpus). `deepseek-ocr-vllm.py` / `paddleocr-vl-1.6.py` were unaffected.
8
-
9
- > ⚠️ **Gotcha for testing on such corpora:** some eval sets already ship `text`, `markdown`,
10
- > `docling`, `xml` columns, so **every** default `--output-column` collides — pass a distinct one
11
- > (e.g. `--output-column ocr_md`) on *all* the markdown-default scripts, not just pp-ocrv6.
12
-
13
- - **`surya-ocr.py` — silent per-row `[SURYA GENERATE ERROR]`, log `No module named 'vllm'`.**
14
- Working as designed (deps omit `vllm`; needs `--image vllm/vllm-openai:v0.20.1` — see its own section
15
- below); the batch run just dropped the image flags. **Fix:** added a `check_vllm_available()` preflight
16
- that `sys.exit(1)`s with the exact required flags **before** processing, instead of writing 400 silent
17
- sentinels. `--max-model-len` was already 18000. Verified: bare-image run now fails fast.
18
- - **`dots-ocr.py` — `[OCR ERROR]` on large pages (small pages OK).** No image resize; a 7–9 MP page →
19
- up to ~14k image tokens (model's 11.29M-px processor cap) > the old `--max-model-len 8192` → vLLM
20
- rejects → sentinel. **Fix:** default `--max-model-len` 8192→**32768** + new optional `--max-pixels`
21
- (mm_processor cap). Verified 4/4 real OCR (matches GT; v1 works with the auto-detected `openai` chat
22
- format — the dots-1.5 `content_format="string"` fix does **not** apply to v1).
23
- - **`lighton-ocr2.py` — `[OCR ERROR]` on large pages.** Its 1540px resize is correct, but ~6k image
24
- tokens **+ `--max-tokens 4096`** > `--max-model-len 8192` at admission. **Fix:** default
25
- `--max-model-len` 8192→**16384**. Verified 4/4 real OCR on l4x1.
26
- - **`glm-ocr.py` — whole JOB ERROR.** The *current* blocker was **not** OOM: glm pinned
27
- `pyarrow>=17.0.0,<18.0.0`, but `datasets>=5.0.0` (which understands this dataset's `Json` feature
28
- type) needs `pyarrow>=21`, so uv resolved `datasets 4.0.0` and `load_dataset` threw
29
- `ValueError: Feature type 'Json' not found` (this is the 3-second startup ERROR seen in job history;
30
- dots/lighton don't pin pyarrow, so they loaded fine). **Fix:** dropped the pyarrow pin. Also added
31
- `VLLM_USE_DEEP_GEMM=0` (silences the non-fatal deep_gemm assertion on the nvcc-less nightly image) and
32
- an **optional** `--max-pixels` cap. Verified: loads + completes 16/16 large pages, and **did NOT OOM
33
- at defaults** (batch 16, no cap) — so `--max-pixels` stays an opt-in memory safety-valve, not a
34
- default (the original "30-min OOM" didn't reproduce on 16 pages; it likely needed a specific
35
- page/batch deep in a 400-row run). glm is chatty on blank pages / can emit degenerate repeats, but
36
- that's model quality, not the crash.
37
- - **`pp-ocrv6.py` — crash on SAVE: duplicated column `['text']`.** Hardcoded output to `text` with **no**
38
- `--output-column` flag; the corpus already has a `text` column. **Fix:** added `--output-column`
39
- (default `markdown`, matching siblings) threaded through the sink + card + inference_info, plus a
40
- **fast-fail startup guard** (`sys.exit(1)` before inference) if the chosen output column — or
41
- `pp_ocr_blocks` — already exists in the input, so it never silently overwrites ground truth. Verified:
42
- guard fires on the colliding default; `--output-column ocr_md` pushes cleanly.
43
-
44
- ### Cross-cutting notes
45
- - **Output-column collision guard (rolled out to ALL ~31 output-writing scripts, 2026-07-01):**
46
- generalises the pp-ocrv6 fix. A shared `ensure_output_columns_free(dataset, columns, overwrite=False)`
47
- helper (copied into each standalone script — no shared lib in this repo) fails fast at startup if an
48
- output column already exists in the input, instead of silently building a duplicate that crashes on
49
- push *after* inference (or clobbering a ground-truth column). New `--overwrite` flag opts in to
50
- replacing it. surya guards both `output_column` + `blocks_column`; the sink scripts (pp-ocrv6,
51
- pp-doclayout) carry the equivalent guard inline. The 5 scripts that hardcoded `"markdown"`
52
- (nanonets-ocr/-ocr2, abot-ocr, deepseek-ocr/-ocr-vllm) also gained a configurable `--output-column`.
53
- Static-verified (ruff + AST + wiring) on all; the pattern is Jobs-proven via pp-ocrv6.
54
- - **Error signalling (#6 — documented, NOT implemented this pass):** ~39 sentinel-string sites
55
- (`[OCR ERROR]`, `[SURYA GENERATE ERROR]`, …) across ~20 scripts write the sentinel *into* the OCR
56
- column, so partial failures are silent and pollute downstream metrics. **Proposed follow-up:** leave
57
- the OCR cell null/empty on failure and record the truncated exception in a companion `ocr_error`
58
- column, so "model read nothing" is distinguishable from "the run errored." Deferred — would touch all
59
- ~20 standalone scripts (no shared lib).
60
- - **`--max-model-len` policy:** the durable fix is to **bound the input** (image cap) and size context
61
- to that bound + output — what the working `paddleocr-vl-1.6.py` (~1M-px smart resize) and `surya-ocr.py`
62
- (max_pixels + 18000) already do. The per-script default bumps above are the minimal version. Don't
63
- auto-size `max_model_len` from images (it's fixed at engine init, before images are seen).
64
- - **Context-length invariant (must hold for every vLLM recipe):**
65
- `--max-tokens` ≤ `--max-model-len` ≤ the model's real max context. The real max is the language
66
- model's `max_position_embeddings` in `config.json` (VLMs: usually under `text_config`/`language_config`,
67
- adjusted by any `rope_scaling`). If `max_model_len` > that, vLLM refuses to start (we don't set
68
- `VLLM_ALLOW_LONG_MAX_MODEL_LEN`); if `max_tokens` > `max_model_len`, the output alone can't fit.
69
- Quick check: `curl -s https://huggingface.co/<model>/raw/main/config.json | python -c "import json,sys;c=json.load(sys.stdin);t=c.get('text_config',c);print(t.get('max_position_embeddings'),t.get('rope_scaling'))"`.
70
- Audited 2026-07-01 across all vLLM recipes: none exceed their window (dots-ocr 32768/131072 ✓,
71
- lighton-ocr2 16384/16384 = at cap/zero headroom ✓); fixed `nanonets-ocr.py` (had `max_tokens 15000`
72
- > `max_model_len 8192` → raised default to 32768).
73
-
74
- ### Future: "self-review a new/changed OCR recipe" skill (spark, 2026-07-01)
75
- A **dev-only skill** (sibling to `bump-vllm-pins`) that reviews an OCR recipe (a given script or the
76
- current diff / `--all`) against the invariants this repo keeps re-learning, so a new recipe or a bumped
77
- default is caught **before** it ships. Mostly a **static** check (fast, no compute); each maps to a
78
- concrete failure we've hit:
79
-
80
- 1. **Context-length** — `--max-tokens` ≤ `--max-model-len` ≤ model `config.json` `max_position_embeddings`
81
- (fetch the config; VLMs → `text_config`, mind `rope_scaling`). Catches vLLM-won't-start and
82
- output-can't-fit (found `nanonets-ocr.py`).
83
- 2. **Output-column collision guard** — has `ensure_output_columns_free` (or the inline sink guard) +
84
- `--overwrite`, and `--output-column` default isn't a bare hardcoded name that clobbers input.
85
- 3. **vLLM image / preflight** — if the arch isn't in a stable wheel, deps omit `vllm`/`torch` AND there's
86
- a fail-fast preflight naming the required `--image`/`--python`/`PYTHONPATH` (surya-class).
87
- 4. **Env guards on the bare image** — `VLLM_USE_FLASHINFER_SAMPLER=0` (and `VLLM_USE_DEEP_GEMM=0` for
88
- nightly vLLM) set before importing vllm.
89
- 5. **Dep sanity** — no stale caps that drag a transitive lib back (e.g. `pyarrow<18` → old `datasets`
90
- lacking the `Json` feature → `load_dataset` crash, the glm-ocr bug).
91
- 6. **Large-image bounding** — full-page recipes cap input pixels / resize, or size `max_model_len` to fit.
92
- 7. **(optional) Jobs smoke** — only after the static checks pass, run on a tiny hard-input set (the
93
- smoke-test dataset **+** a large 7–9 MP page) on l4x1, poll to terminal, and classify any failure
94
- into the catalogued buckets (missing-vllm/wrong-image, collision, context-overflow `[OCR ERROR]`,
95
- encoder OOM, dep-drift) with remedies.
96
-
97
- Pairs with the "OCR Smoke Test Dataset" idea below. Build after the current fixes land.
98
-
99
- ## Active Scripts
100
-
101
- ### DeepSeek-OCR v1 (`deepseek-ocr-vllm.py`)
102
- ✅ **Production Ready** (Fixed 2026-02-12)
103
- - Uses official vLLM offline pattern: `llm.generate()` with PIL images
104
- - `NGramPerReqLogitsProcessor` prevents repetition on complex documents
105
- - Resolution modes removed (handled by vLLM's multimodal processor)
106
- - See: https://docs.vllm.ai/projects/recipes/en/latest/DeepSeek/DeepSeek-OCR.html
107
-
108
- **Known issue (vLLM nightly, 2026-02-12):** Some images trigger a crop dimension validation error:
109
- ```
110
- ValueError: images_crop dim[2] expected 1024, got 640. Expected shape: ('bnp', 3, 1024, 1024), but got torch.Size([0, 3, 640, 640])
111
- ```
112
- This is a vLLM bug: the preprocessor defaults to gundam mode (image_size=640), but the tensor validator expects 1024x1024 even when the crop batch is empty (dim 0). Hit 2/10 on `davanstrien/ufo-ColPali`, 0/10 on NLS Medical History. Likely depends on image aspect ratios. No upstream issue filed yet. Related feature request: [vllm#28160](https://github.com/vllm-project/vllm/issues/28160) (no way to control resolution mode via mm-processor-kwargs).
113
-
114
- ### LightOnOCR-2-1B (`lighton-ocr2.py`)
115
- ✅ **Production Ready** (Fixed 2026-01-29)
116
-
117
- **Status:** Working with vLLM nightly
118
-
119
- **What was fixed:**
120
- - Root cause was NOT vLLM - it was the deprecated `HF_HUB_ENABLE_HF_TRANSFER=1` env var
121
- - The script was setting this env var but `hf_transfer` package no longer exists
122
- - This caused download failures that manifested as "Can't load image processor" errors
123
- - Fix: Removed the `HF_HUB_ENABLE_HF_TRANSFER=1` setting from the script
124
-
125
- **Test results (2026-01-29):**
126
- - 10/10 samples processed successfully
127
- - Clean markdown output with proper headers and paragraphs
128
- - Output dataset: `davanstrien/lighton-ocr2-test-v4`
129
-
130
- **Example usage:**
131
- ```bash
132
- hf jobs uv run --flavor a100-large \
133
- -s HF_TOKEN \
134
- https://huggingface.co/datasets/uv-scripts/ocr/raw/main/lighton-ocr2.py \
135
- davanstrien/ufo-ColPali output-dataset \
136
- --max-samples 10 --shuffle --seed 42
137
- ```
138
 
139
- **Model Info:**
140
- - Model: `lightonai/LightOnOCR-2-1B`
141
- - Architecture: Pixtral ViT encoder + Qwen3 LLM
142
- - Training: RLVR (Reinforcement Learning with Verifiable Rewards)
143
- - Performance: 83.2% on OlmOCR-Bench, 42.8 pages/sec on H100
144
 
145
- ### PaddleOCR-VL-1.5 (`paddleocr-vl-1.5.py`)
146
- **Production Ready** (Added 2026-01-30)
 
147
 
148
- **Status:** Working with transformers
149
-
150
- **Note:** Uses transformers backend (not vLLM) because PaddleOCR-VL only supports vLLM in server mode, which doesn't fit the single-command UV script pattern. Images are processed one at a time for stability.
151
-
152
- **Test results (2026-01-30):**
153
- - 10/10 samples processed successfully
154
- - Processing time: ~50s per image on L4 GPU
155
- - Output dataset: `davanstrien/paddleocr-vl15-final-test`
156
-
157
- **Example usage:**
158
- ```bash
159
- hf jobs uv run --flavor l4x1 \
160
- -s HF_TOKEN \
161
- https://huggingface.co/datasets/uv-scripts/ocr/raw/main/paddleocr-vl-1.5.py \
162
- davanstrien/ufo-ColPali output-dataset \
163
- --max-samples 10 --shuffle --seed 42
164
- ```
165
-
166
- **Task modes:**
167
- - `ocr` (default): General text extraction to markdown
168
- - `table`: Table extraction to HTML format
169
- - `formula`: Mathematical formula recognition to LaTeX
170
- - `chart`: Chart and diagram analysis
171
- - `spotting`: Text spotting with localization (uses higher resolution)
172
- - `seal`: Seal and stamp recognition
173
-
174
- **Model Info:**
175
- - Model: `PaddlePaddle/PaddleOCR-VL-1.5`
176
- - Size: 0.9B parameters (ultra-compact)
177
- - Performance: 94.5% SOTA on OmniDocBench v1.5
178
- - Backend: Transformers (single image processing)
179
- - Requires: `transformers>=5.0.0`
180
 
181
- ### DoTS.ocr-1.5 (`dots-ocr-1.5.py`)
182
- ✅ **Production Ready** (Fixed 2026-03-14)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
183
 
184
- **Status:** Working with vLLM 0.17.1 stable
185
 
186
- **Model availability:** The v1.5 model is NOT on HF from the original authors. We mirrored it from ModelScope to `davanstrien/dots.ocr-1.5`. Original: https://modelscope.cn/models/rednote-hilab/dots.ocr-1.5. License: MIT-based (with supplementary terms for responsible use).
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
187
 
188
- **Key fix (2026-03-14):** Must pass `chat_template_content_format="string"` to `llm.chat()`. The model's `tokenizer_config.json` chat template expects string content (not openai-format lists). Without this, the model generates empty output (~1 token then EOS). The separate `chat_template.json` file handles multimodal content but vLLM uses the tokenizer_config template by default.
189
 
190
- **Bbox coordinate system (layout modes):**
191
- Bounding boxes from `layout-all` and `layout-only` modes are in the **resized image coordinate space**, not original image coordinates. The model uses `Qwen2VLImageProcessor` which resizes images via `smart_resize()`:
192
- - `max_pixels=11,289,600`, `factor=28` (patch_size=14 × merge_size=2)
193
- - Images are scaled down so `w×h ≤ max_pixels`, dims rounded to multiples of 28
194
- - To map bboxes back to original image coordinates:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
195
  ```python
196
  import math
197
-
198
- def smart_resize(height, width, factor=28, min_pixels=3136, max_pixels=11289600):
199
- h_bar = max(factor, round(height / factor) * factor)
200
- w_bar = max(factor, round(width / factor) * factor)
201
- if h_bar * w_bar > max_pixels:
202
- beta = math.sqrt((height * width) / max_pixels)
203
- h_bar = math.floor(height / beta / factor) * factor
204
- w_bar = math.floor(width / beta / factor) * factor
205
- elif h_bar * w_bar < min_pixels:
206
- beta = math.sqrt(min_pixels / (height * width))
207
- h_bar = math.ceil(height * beta / factor) * factor
208
- w_bar = math.ceil(width * beta / factor) * factor
209
  return h_bar, w_bar
210
-
211
- resized_h, resized_w = smart_resize(orig_h, orig_w)
212
- scale_x = orig_w / resized_w
213
- scale_y = orig_h / resized_h
214
- # Then: orig_x = bbox_x * scale_x, orig_y = bbox_y * scale_y
215
  ```
216
-
217
- **Test results (2026-03-14):**
218
- - 3/3 samples on L4: OCR mode working, ~147 toks/s output
219
- - 3/3 samples on L4: layout-all mode working, structured JSON with bboxes
220
- - 10/10 samples on A100: layout-only mode on NLS Highland News, ~670 toks/s output
221
- - Output datasets: `davanstrien/dots-ocr-1.5-smoke-test-v3`, `davanstrien/dots-ocr-1.5-layout-test`, `davanstrien/dots-ocr-1.5-nls-layout-test`
222
-
223
- **Prompt modes:**
224
- - `ocr` text extraction (default)
225
- - `layout-all`layout + bboxes + categories + text (JSON)
226
- - `layout-only` layout + bboxes + categories only (JSON)
227
- - `web-parsing` webpage layout analysis (JSON) [new in v1.5]
228
- - `scene-spotting` — scene text detection [new in v1.5]
229
- - `grounding-ocr` — text from bounding box region [new in v1.5]
230
- - `general` free-form (use with `--custom-prompt`) [new in v1.5]
231
-
232
- **Example usage:**
233
- ```bash
234
- hf jobs uv run --flavor l4x1 \
235
- -s HF_TOKEN \
236
- /path/to/dots-ocr-1.5.py \
237
- davanstrien/ufo-ColPali output-dataset \
238
- --model davanstrien/dots.ocr-1.5 \
239
- --max-samples 10 --shuffle --seed 42
240
- ```
241
-
242
- **Model Info:**
243
- - Original: `rednote-hilab/dots.ocr-1.5` (ModelScope only)
244
- - Mirror: `davanstrien/dots.ocr-1.5` (HF)
245
- - Parameters: 3B (1.2B vision encoder + 1.7B language model)
246
- - Architecture: DotsOCRForCausalLM (custom code, trust_remote_code required)
247
- - Precision: BF16
248
- - GitHub: https://github.com/rednote-hilab/dots.ocr
 
 
 
 
 
 
249
 
250
  ---
251
 
252
- ## Pending Development
253
 
254
- ### DeepSeek-OCR-2 (`deepseek-ocr2-vllm.py`)
255
- ✅ **Production Ready** (2026-02-12)
256
 
257
- **Status:** Working with vLLM nightly (requires nightly for `DeepseekOCR2ForCausalLM` support, not yet in stable 0.15.1)
258
-
259
- **What was done:**
260
- - Rewrote the broken draft script (which used base64/llm.chat/resolution modes)
261
- - Uses the same proven pattern as v1: `llm.generate()` with PIL images + `NGramPerReqLogitsProcessor`
262
- - Key v2 addition: `limit_mm_per_prompt={"image": 1}` in LLM init
263
- - Added `addict` and `matplotlib` as dependencies (required by model's HF custom code)
264
-
265
- **Test results (2026-02-12):**
266
- - 10/10 samples processed successfully on L4 GPU
267
- - Processing time: 6.4 min (includes model download + warmup)
268
- - Model: 6.33 GiB, ~475 toks/s input, ~246 toks/s output
269
- - Output dataset: `davanstrien/deepseek-ocr2-nls-test`
270
-
271
- **Example usage:**
272
- ```bash
273
- hf jobs uv run --flavor l4x1 \
274
- -s HF_TOKEN \
275
- https://huggingface.co/datasets/uv-scripts/ocr/raw/main/deepseek-ocr2-vllm.py \
276
- NationalLibraryOfScotland/medical-history-of-british-india output-dataset \
277
- --max-samples 10 --shuffle --seed 42
278
- ```
279
-
280
- **Important notes:**
281
- - Requires vLLM **nightly** (stable 0.15.1 does NOT include DeepSeek-OCR-2 support)
282
- - The nightly index (`https://wheels.vllm.ai/nightly`) occasionally has transient build issues (e.g., only ARM wheels). If this happens, wait and retry.
283
- - Uses same API pattern as v1: `NGramPerReqLogitsProcessor`, `SamplingParams(temperature=0, skip_special_tokens=False)`, `extra_args` for ngram settings
284
-
285
- **Model Information:**
286
- - Model ID: `deepseek-ai/DeepSeek-OCR-2`
287
- - Model Card: https://huggingface.co/deepseek-ai/DeepSeek-OCR-2
288
- - GitHub: https://github.com/deepseek-ai/DeepSeek-OCR-2
289
- - Parameters: 3B
290
- - Architecture: Visual Causal Flow
291
- - Resolution: (0-6)x768x768 + 1x1024x1024 patches
292
-
293
- ## Other OCR Scripts
294
-
295
- ### Unlimited-OCR (`unlimited-ocr-vllm.py`)
296
- ✅ **Production Ready — single-image** (added + validated 2026-06-28)
297
-
298
- Baidu's `baidu/Unlimited-OCR` (3.3B, MIT, DeepSeek-OCR / DeepSeek-OCR-2 descendant). Offline vLLM
299
- batch recipe adapted from `deepseek-ocr-vllm.py` — `llm.generate()` with PIL images +
300
- `NGramPerReqLogitsProcessor` (imported from `vllm.model_executor.models.unlimited_ocr`), prompt
301
- `<image>document parsing.`, `SamplingParams(temperature=0, skip_special_tokens=False,
302
- extra_args=dict(ngram_size=35, window_size=128))`, `limit_mm_per_prompt={"image": 1}`. One image per
303
- row → one markdown. `--strip-grounding` drops `<|det|>`/`<|ref|>` tags (verified locally on real
304
- output: removes boxes, keeps inner text + LaTeX).
305
-
306
- **⚠️ Dedicated image, not the standard one.** The arch is NOT in any stable vLLM pip wheel — must run
307
- on Baidu's `vllm/vllm-openai:unlimited-ocr` (CUDA 13.0; `:unlimited-ocr-cu129` on Hopper). So `vllm`
308
- and `torch` are **omitted from the PEP 723 deps** and come from the image via `PYTHONPATH`. The image
309
- uses the **standard** layout: `--python /usr/bin/python3 -e PYTHONPATH=/usr/local/lib/python3.12/dist-packages`
310
- (vLLM `0.23.1rc1.dev541` lives there; probed 2026-06-28). The `unlimited_ocr` module re-exports
311
- `deepseek_ocr.NGramPerReqLogitsProcessor`. Recipe: https://recipes.vllm.ai/baidu/Unlimited-OCR
312
-
313
- **Smoke tests (2026-06-28):**
314
- - **ufo-ColPali** (5, l4x1): 5/5 OK, 2.3 min, ~200 tok/s. Clean layout-grounded markdown — accurate
315
- text, `<|det|>` bboxes (0–1000), multilingual (Spanish), LaTeX. Output `davanstrien/unlimited-ocr-smoke`.
316
- - **encyclopaedia-britannica-1771** (8, l4x1, `--strip-grounding`): 6/6 content pages produced clean
317
- text matching the dataset's own `ocr_text` length almost exactly (e.g. row 1: md 5811 vs ocr_text
318
- 5752), period-accurate 1771 OCR (long-ſ, archaic spelling). The 2 "empty" rows are genuinely blank
319
- pages (ground-truth `ocr_text` 3–24 chars). Output `davanstrien/unlimited-ocr-britannica-smoke`.
320
-
321
- **Multi-page: BOTH engines work on clean docs; robustness differs on hard scans. (Corrected
322
- 2026-06-29 — earlier "vLLM multi-page is broken" was an input-difficulty artifact.)**
323
- - **Control test that overturned the first read:** ran the SAME clean synthetic 2-page doc through the
324
- **vLLM server** that SGLang had aced. vLLM returned **`<PAGE>=2`, both pages, real text** (`Chapter
325
- One The Harbor` + lines / `Chapter Two The Market` + lines), with minor body-OCR slips ("early oakh",
326
- "Guile covered") — i.e. the model *misreading*, not the engine hallucinating. Worked with both 1×
327
- and 2× `<image>` prompt forms + `vllm_xargs.window_size=1024`. So **vLLM multi-page works**.
328
- - **What the earlier garbling actually was:** my first vLLM multi-page tests used **hard** inputs —
329
- `unlimited-ocr-pdf-test` (blank + dense 1771 Britannica) and ufo newspaper clippings. On those, vLLM
330
- multi-page degraded to hallucination (counting garbage "SIGILLUM. 17. 96…", `2017年1月1日` loops,
331
- content in neither input). SGLang read the *same* hard ufo input as real content → **SGLang is more
332
- robust on hard/degraded scans**, but neither engine is "broken."
333
- - **Offline `LLM().generate()`** still needs one `<image>` per image (single placeholder → assertion);
334
- offline multi-page was only tested on the hard Britannica PDF (garbled) — not re-tested on clean, so
335
- the recipe stays single-image (multi-page belongs to serving).
336
- - `images_config`/`image_mode` are **SGLang-only** params (vLLM ignores them); on vLLM use one
337
- `<image>` per page + `window_size=1024` in `vllm_xargs`.
338
- - **Upstream check (vllm-project/vllm#46564, "Support Unlimited OCR", merged 2026-06-28):** confirms
339
- this. Multi-image IS implemented (crop/gundam auto-disabled → base mode; one `<image>` placeholder
340
- per image). R-SWA needs the **FlexAttention** backend (auto on non-FA4 GPUs like L4) or FA4 on
341
- H20/H100 — our run correctly used FlexAttention. BUT: the PR's only benchmark is **single-page
342
- OmniDocBench** (FA4 92.12 / Flex 92.38); there is **no multi-page test, no `examples/`, no canonical
343
- multi-page prompt** in the merged code. PR-author comment: multi-page needs **V1 + NGramPerReq-
344
- LogitsProcessor** (V2 lacks custom logits processors), and their "14-page PDF merge" smoke test only
345
- confirmed "**R-SWA itself works**" (mechanism runs on long seqs) — *not* OCR quality. So nobody
346
- upstream has shown multi-page OCR quality; the tweet's "40+ pages, low edit distance" is ahead of the
347
- merged evidence. (Our own clean-doc control test later showed vLLM multi-page DOES read correctly —
348
- see the corrected block above; the earlier garbling was hard-input degradation, not an engine break.)
349
- - **Conclusion:** the **batch recipe stays single-image** (offline multi-page is finicky and untested
350
- on clean; `--pdf-column` removed). For multi-page, **serve** the model — both engines read clean
351
- multi-page docs; route hard/degraded scans to **SGLang** (more robust; authors' `images_config` path;
352
- serving-unlimited-ocr.md Option B + §3). Image probed: `vllm 0.23.1rc1.dev541` (docs say "0.25.0+").
353
- - **SGLang multi-page — ✅ FIXED + validated working (2026-06-28).** Multi-page is the model's headline
354
- feature and **SGLang delivers it robustly** (vLLM multi-page also works on clean docs but hallucinated
355
- on hard scans — see corrected block above). Two pins were needed:
356
- 1. **Image `lmsysorg/sglang:v0.5.10.post1`** (not `:latest`). `:latest` drifted to sglang 0.5.14 /
357
- torch 2.11 / cu130; the wheel (`dev11416`) needs torch 2.9.1 / cuda-python 12.9 / flashinfer 0.6.7 /
358
- xgrammar 0.1.32 / transformers 5.3.0. Found v0.5.10.post1 by bisecting sglang release pyproject
359
- pins — the **last** release before the torch-2.11 bump; matches the wheel exactly.
360
- 2. **`a100-large` + `--attention-backend flashinfer`** (not `h200`/`fa3`). `fa3` needs Hopper, but
361
- HF's `h200` nodes **fail GPU init with `CUDA error 802: system not yet initialized`, 3/3** (infra /
362
- Fabric-Manager — *all* working jobs this session were l4x1/a100, never h200). The version pin alone
363
- did NOT fix 802; the 802 is purely the h200 node. a100+flashinfer dodges it.
364
- - **Result:** server up; clean 2-page synthetic doc → **both pages read verbatim, `<PAGE>`-separated**
365
- (`Chapter One: The Harbor…` / `Chapter Two: The Market…`); ufo pages → **real content**
366
- (`OUT OF THIS WORLD / UFO FlyBys…`), *not* vLLM's hallucinated garbage. Client: OpenAI API,
367
- `images_config:{image_mode:base}` + `Multi page parsing.`; no per-request NGram processor (so harder
368
- scans show minor page-merge/OCR slips — fa3 + the custom logit processor would tighten quality; the
369
- mechanism works). Working command lives in `serving-unlimited-ocr.md` Option B; switch back to
370
- `fa3`/`h200` for exact R-SWA once the h200 802 infra issue clears.
371
-
372
- **Example usage:**
373
  ```bash
374
- hf jobs uv run --flavor l4x1 -s HF_TOKEN \
375
- --image vllm/vllm-openai:unlimited-ocr --python /usr/bin/python3 \
376
- -e PYTHONPATH=/usr/local/lib/python3.12/dist-packages \
377
- ./ocr/unlimited-ocr-vllm.py davanstrien/ufo-ColPali output-dataset --max-samples 10 --shuffle
378
- ```
379
-
380
- **Deferred follow-up (captured, not built):** a *multi-page batch* recipe that drives the **SGLang
381
- server** in-job (server lifecycle + `ThreadPoolExecutor` over multi-page docs, like Baidu's `infer.py`,
382
- → Hub) — the only way to get robust multi-page at corpus scale, since SGLang offline-Engine is
383
- non-viable (server-only, custom-logit-processor/R-SWA are server-side, `fa3` Hopper-only) and vLLM
384
- offline needs one `<image>` per page and degrades on hard scans. Gate: a real corpus-scale multi-page
385
- need **+** the h200/`fa3` infra fix (for exact R-SWA quality). Single-image vLLM (this recipe) stays
386
- the batch default.
387
-
388
- ### Nanonets OCR (`nanonets-ocr.py`, `nanonets-ocr2.py`)
389
- ✅ `nanonets-ocr.py` working.
390
-
391
- **`nanonets-ocr2.py` — ⚠️ requires pinned vLLM image `vllm/vllm-openai:v0.10.2` (fixed 2026-06-30).**
392
- Nanonets-OCR2-3B is a **Qwen2.5-VL** model. On a floating `vllm` pin (resolved to **0.24.0**) it
393
- decoded **pure `!` on every page** — the documented vLLM **>=0.11 Qwen2.5-VL regression**
394
- ([vllm#27775](https://github.com/vllm-project/vllm/issues/27775),
395
- [#14126](https://github.com/vllm-project/vllm/issues/14126); 0.9.2/0.10.1/**0.10.2** are the
396
- known-good builds). Ruled out along the way: it is **not** context length (still `!` at
397
- `max_model_len=32768`) and **not** torch.compile (still `!` with `enforce_eager=True`). Pip-pinning
398
- `vllm==0.10.2` alone fails — its old tokenizer API (`Qwen2Tokenizer.all_special_tokens_extended`)
399
- clashes with modern `transformers` 5.x. **Fix:** run on the **`vllm/vllm-openai:v0.10.2` image**
400
- (ships a consistent vLLM 0.10.2 + transformers 4.56.1); `vllm` and `torch` are omitted from the PEP
401
- 723 deps and come from the image via `PYTHONPATH`. Also bumped the `--max-model-len` default
402
- 8192→32768 (the script's `--max-tokens` default is 15000 per the model card, which an 8192 context
403
- can't hold). Standard `/usr/bin/python3` + `dist-packages` image layout (probed). Re-test the pin
404
- when a newer vLLM ships a Qwen2.5-VL decode fix → it can move back to the default image.
405
-
406
- **Smoke test (2026-06-30, `davanstrien/ufo-ColPali`, 5 samples, a10g-small):** 5/5 clean markdown
407
- (English + Spanish, `<header>`/`<img>` semantic tags), 0 degenerate rows. Output
408
- `davanstrien/nanonets-ocr2-img0102-test`.
409
-
410
- ```bash
411
- hf jobs uv run --flavor a10g-small -s HF_TOKEN \
412
- --image vllm/vllm-openai:v0.10.2 --python /usr/bin/python3 \
413
- -e PYTHONPATH=/usr/local/lib/python3.12/dist-packages \
414
- ./ocr/nanonets-ocr2.py INPUT_DATASET OUTPUT_DATASET --max-samples 10 --shuffle --seed 42
415
- ```
416
-
417
- ### PaddleOCR-VL (`paddleocr-vl.py`)
418
- ✅ Working
419
-
420
- ### lift (`lift-extract.py`)
421
- ✅ **Both backends validated on Jobs** (added 2026-06-22)
422
-
423
- Datalab's `lift` (9B, Qwen3.5-based) for **schema-constrained** structured extraction:
424
- image *or* multi-page PDF + JSON Schema → JSON. Sits alongside `nuextract3.py` /
425
- `lfm2-vl-extract.py` in the structured-extraction group, but it's the only one that
426
- ingests PDFs directly (one row = one document, multi-page collapsed into one extraction).
427
-
428
- **Shared rendering** comes from lift: we reuse `lift.input.load_file` (auto-detects PDF vs
429
- image by content; `pypdfium2`, DPI/min-dim, `--page-range`) via a temp file per row. Each row
430
- → a list of page images → one extraction. Both backends share this.
431
-
432
- **Backends (`--method`)** — both **in-process, single command** (no server):
433
- - `hf` (default): drives the `lift-pdf` package directly — `InferenceManager(method="hf")` →
434
- `AutoModelForImageTextToText`, bf16, batches a list of `BatchInputItem` conversations with
435
- left padding. **No** constrained decoding (plain `model.generate`); trusts lift's training.
436
- Runs on the **default** uv image. Simplest path; best for small jobs.
437
- - `vllm`: vLLM's **offline `LLM()` engine** + `llm.chat()` with structured outputs — the
438
- repo's standard fast-batch pattern. We reproduce lift's *own* vLLM recipe (their `generate_vllm`)
439
- rather than calling the package: `PROMPT_MAPPING["direct"]`, `scale_to_fit`,
440
- `mm_processor_kwargs={min_pixels:3136,max_pixels:861696}`, and the guided JSON schema
441
- (`json_schema_to_pydantic.create_model` → `make_properties_nullable` → `StructuredOutputsParams`,
442
- with the version shim from `ocr-vllm-judge.py`). Sampling matches lift exactly: `temperature=0.0,
443
- top_p=0.1, max_tokens=12384`. Needs the `vllm/vllm-openai` image (vLLM not in our deps; reused
444
- from the image via `PYTHONPATH`, which also wins the torch version → no clash). **Not mirrored:**
445
- lift's repeat-token retry loop (re-runs looped items at higher temp) — less critical here since
446
- the grammar constraint already prevents runaway repetition.
447
-
448
- > **History:** the first `--method vllm` used the package's path, which is an OpenAI *client* →
449
- > server (lift's `lift_vllm` shells out to `sudo docker run`, unusable in a Job). We built+validated
450
- > an auto-launched `vllm serve` subprocess for it, then replaced the whole thing with the offline
451
- > `LLM()` engine — cleaner single command, no HTTP, and the repo's established pattern.
452
-
453
- **Model id:** card repo is `datalab-to/lift` (9.65B, license `openrail`, not gated). The
454
- installed package's internal default was `datalab-to/lift-extract`; we pin `--model
455
- datalab-to/lift` via the `MODEL_CHECKPOINT` env (set *before* importing lift, since settings
456
- read env at import). Confirmed in the smoke test: `datalab-to/lift` (commit `3129597…`) loads.
457
-
458
- **Naming gotcha:** the script must NOT be named `lift.py` — that shadows the installed `lift`
459
- package (`import lift` resolves to the script itself → `ImportError: cannot import name
460
- 'resolve_schema'`). Hence `lift-extract.py`. Hit this on the first Jobs run.
461
-
462
- **License:** code Apache-2.0, **weights modified OpenRAIL-M** (research/personal/<$5M, no
463
- competitive use vs Datalab API). Surfaced in the docstring, the README entry, and the output
464
- dataset card.
465
-
466
- **Benchmark both backends:** `--config hf --create-pr` vs `--config vllm --create-pr` into one
467
- repo (same multi-config pattern as the other OCR scripts).
468
-
469
- **Smoke-test results (2026-06-22, `davanstrien/ufo-ColPali`, 3 samples, a100-large):**
470
- - **HF backend** (default image): 3/3 valid JSON, batched (1 chunk of 3 at `--batch-size 8`, no
471
- padding/image-count issues), 1.8 min. Output `davanstrien/lift-smoke-hf`. Resolved
472
- `lift-pdf==0.1.1, transformers==5.12.1, torch==2.12.1, datasets==5.0.0`.
473
- - **vLLM offline backend** (`vllm/vllm-openai` image): `LLM()` engine loaded (weights 18 GiB /
474
- 59s via Xet high-perf), `llm.chat` batched all 3 prompts in one call (538 tok/s in), 3/3 valid
475
- JSON via `StructuredOutputsParams`, clean engine shutdown, 5.2 min (engine init + torch.compile
476
- warmup dominates at 3 samples; wins at scale). `vllm==0.23.0`, image's `torch==2.11.0+cu130` (no
477
- clash). Output `davanstrien/lift-smoke-vllm-offline`.
478
- - (The earlier server-subprocess vLLM also passed — `davanstrien/lift-smoke-vllm`, 5.3 min — but
479
- was replaced by the offline engine; see History above.)
480
- - **All paths produce valid schema-shaped JSON**, e.g.
481
- `{"title": "OUT OF THIS WORLD UFO FlyBys in Middle Tennessee", "date": "Oct. 26, 1995"}`;
482
- absent fields → `null` (nullable-leaf transform). `parse_error_rate: 0.0`. Outputs agree across
483
- backends except minor low-temp content drift (offline-vLLM recovered a Spanish title hf left null).
484
-
485
- **Still untested (lower risk — reuses lift's `load_file`, exercised on the image path):**
486
- - PDF column path (`--pdf-column`, `--page-range`) on a real PDF-bytes dataset.
487
- - `l4x1` for the hf backend (9B bf16 ≈ 19GB; default `a100-large` confirmed comfortable).
488
-
489
- Requires Python ≥3.12 (lift-pdf constraint) — fine on the standard images.
490
-
491
- ### Surya OCR 2 (`surya-ocr.py`)
492
- ✅ **OCR + layout + table validated on Jobs** (added 2026-06-22)
493
-
494
- Datalab's **Surya OCR 2** (`datalab-to/surya-ocr-2`, 650M, Qwen3.5-style) for **structured** OCR.
495
- Unlike the flat-markdown scripts, it returns per-block HTML + bounding boxes + reading order. The
496
- recipe writes **two columns**: `--output-column` (default `markdown`, flattened reading-order text)
497
- **and** `surya_blocks` (the full structured result as JSON, one entry per page). `--task` switches
498
- between `ocr` (RecognitionPredictor, full-page), `layout` (LayoutPredictor), and `table`
499
- (TableRecPredictor; `--table-mode full` → HTML, `simple` → rows/cols/cells).
500
-
501
- **Engine — offline vLLM batch, NO server (the whole trick).** Surya normally runs its VLM through a
502
- **spawned server**: on GPU it `docker run`s `vllm/vllm-openai`, on CPU a `llama-server` subprocess
503
- (`surya/inference/backends/{vllm,llamacpp}.py`). Docker-in-Docker isn't available inside a Job, so
504
- the default path can't work. Instead we subclass Surya's `Backend` ABC
505
- (`surya/inference/backends/base.py`: `start`/`stop`/`generate(batch)->List[BatchOutputItem]`) with an
506
- in-process `OfflineVLLMBackend` that runs vLLM's offline `LLM().chat()` and inject it via
507
- `manager.backend = ...` (bypassing `SuryaInferenceManager.__init__`'s autodetect). **Surya still owns
508
- everything else** — prompts (`PROMPT_MAPPING`), image scaling (`scale_to_fit`), HTML/bbox parsing, the
509
- repeat-loop fallback, the 0–1000→pixel bbox rescale, and the layout/table predictors — so we only swap
510
- the transport. We reuse Surya's own `_build_messages`/`scale_to_fit`/`PROMPT_MAPPING` so the offline
511
- path matches the server byte-for-byte. `mm_processor_kwargs={min_pixels:3136,max_pixels:6291456}`,
512
- `dtype=bfloat16`, `max_model_len=18000`, sampling `temperature=0.0/top_p=0.1`, `logprobs=1` →
513
- `mean_token_prob` → Surya's per-block `confidence`. Guided JSON (layout's `LAYOUT_JSON_SCHEMA`) maps to
514
- `StructuredOutputsParams`/`GuidedDecodingParams` (same shim as `ocr-vllm-judge.py`). **Not mirrored:**
515
- Surya's per-item repeat-token retry — its recognition layer already detects loops and falls back to
516
- layout+block OCR, so the backend stays simple (like lift).
517
-
518
- **⚠️ Image gotcha — pin `vllm/vllm-openai:v0.20.1` AND use the `site-packages` path.** Surya-2 is the
519
- recent, **version-sensitive, hybrid (linear-attention) `qwen3_5`** architecture; v0.20.1 is Surya's
520
- known-good vLLM. Unlike the other vLLM recipes (which use the unversioned image at
521
- `/usr/bin/python3` + `dist-packages`), the **`:v0.20.1`** image puts python at `/usr/local/bin/python3`
522
- and vLLM/torch at **`/usr/local/lib/python3.12/site-packages`**. The first smoke run used the old
523
- `dist-packages` path → `No module named 'vllm'` → 0/5. Correct flags:
524
- ```bash
525
- hf jobs uv run --flavor l4x1 -s HF_TOKEN \
526
- --image vllm/vllm-openai:v0.20.1 --python /usr/local/bin/python3 \
527
- -e PYTHONPATH=/usr/local/lib/python3.12/site-packages \
528
- ./ocr/surya-ocr.py davanstrien/ufo-ColPali OUTPUT --max-samples 5
529
- ```
530
- `PYTHONPATH` is prepended ahead of the uv venv, so the **image's** torch 2.11.0+cu130 / transformers /
531
- vLLM 0.20.1 win at import even though `surya-ocr` pulls its own torch into the venv (harmless, just a
532
- wasted download). Confirmed via a probe job: vLLM at `…/site-packages/vllm`, python 3.12.13.
533
-
534
- **Naming gotcha:** must be `surya-ocr.py`, never `surya.py` (would shadow the `surya` package on
535
- import). Checked: no other `surya*` file in the repo.
536
-
537
- **Smoke-test results (2026-06-22, `davanstrien/ufo-ColPali`, l4x1, `vllm/vllm-openai:v0.20.1`):**
538
- - **ocr** (5 samples): 5/5 OK, 3.7 min (vLLM engine init ~113s incl. 34s compile + CUDA-graph capture,
539
- then inference). `markdown` clean reading-order text; `surya_blocks` valid JSON with **pixel-space**
540
- bboxes (e.g. `[21.6,65.5,30.9,343.4]` within `image_bbox=[0,0,618,1007]`), sequential `reading_order`,
541
- canonical labels (PageHeader/SectionHeader/Text/…), `confidence` ~0.94 (logprobs path works), per-block
542
- HTML (`<h1>`, `<sup>`, `<br/>`). Output `davanstrien/surya-smoke-ocr`. Resolved `vllm==0.20.1,
543
- torch==2.11.0+cu130, transformers==5.7.0, surya-ocr==0.20.0`.
544
- - **layout** (3 samples): 3/3 OK; `surya_blocks` = `LayoutResult` per page (bboxes with `label`/
545
- `position`/`count`/`confidence`, guided-JSON enforced). Output `davanstrien/surya-smoke-layout`.
546
- - **table** `--table-mode full` (3 samples): 3/3 OK; `TableResult` with `html` populated (rows/cols/cells
547
- empty in full mode, by design). ufo-ColPali has no real tables, so use a table dataset for meaningful
548
- output — the code path is what's validated. Output `davanstrien/surya-smoke-table`.
549
-
550
- - **pdf** (`--pdf-column`/`--page-range`, real 14.8MB arXiv PDF, pages 0–2): 1/1 OK. Text
551
- concatenates the 3 pages (title/authors/abstract of arXiv:2606.17162 extracted in reading order);
552
- `surya_blocks` has **3 page entries** (`image_bbox=[0,0,1632,2112]` at 192 DPI) with sensible labels
553
- (PageHeader/SectionHeader/Text/Picture/Diagram/Caption/ListGroup/…). Source built by wrapping the PDF
554
- bytes into a `Value("binary")` column. Output `davanstrien/surya-smoke-pdf`.
555
-
556
- **Still untested (low risk):** `--table-mode simple` (rows/cols/cells). Larger GPUs (l4x1 confirmed
557
- comfortable for 650M).
558
-
559
- ### Bucket variant (`surya-ocr-bucket.py`) — issue #55 ✅
560
- ✅ **OCR a bucket of files directly, no dataset round-trip** (added 2026-06-22). Reuses the parent's
561
- `OfflineVLLMBackend` / predictor dispatch / `serialize_pages` **verbatim**; grafts on the bucket I/O
562
- from `pp-doclayout.py`. Two input strategies via `--io-mode {auto,mount,copy}`: **mount** reads off a
563
- FUSE-mounted `/in` (`-v hf://buckets/<id>:/in:ro`); **copy** uses `huggingface_hub`
564
- `list_bucket_tree` + `download_bucket_files` to batch-fetch each `--batch-size` chunk to temp, OCR, then
565
- `shutil.rmtree` (peak disk = one batch — sidesteps the FUSE bulk-read stall). Two sinks (≥1, both
566
- allowed): `--output-bucket` writes per-page `<rel>.md` + `<rel>.json` (`surya_blocks`) to a mounted dir
567
- or `hf://buckets/...` URL (`batch_bucket_files`), **resume-by-skip keyed on the `.json`** (the parent
568
- bucket recipes have no resume); `--output-dataset` buffers one row per file and `push_to_hub`. `.jp2` is
569
- first-class (LoC/Chronicling America) with an `imagecodecs` fallback when the image's Pillow lacks
570
- OpenJPEG.
571
-
572
- **⚠️ Dependency gotcha (cost one job):** must pin **`surya-ocr==0.20.0`** in the PEP 723 header. Adding
573
- `huggingface-hub>=1.6.0` (for the buckets API) loosened the resolve and uv backtracked to an ancient
574
- surya without the `surya.inference` engine layout → `ModuleNotFoundError: No module named 'surya.inference'`.
575
- Fix: pin surya, leave `huggingface-hub` unpinned — at runtime `PYTHONPATH` puts the pinned image's hub
576
- (buckets API present) ahead of the venv, so there's no version tension.
577
-
578
- **Smoke-tested on Jobs (2026-06-22, `davanstrien/chronicling-america-mirror-demo`, 1901 *The Commoner*
579
- `.jp2`, l4x1):** copy→dataset, mount→mounted-bucket-files, copy→API-bucket-files, and resume re-run
580
- (skip-all, no model load) all 8/8 OK with clean masthead/body OCR + valid pixel-space `surya_blocks`.
581
- Mount-vs-copy benchmark (32-page seed-42 slice, l4x1, inference identical ~745s — confirms the I/O
582
- split): **copy wins decisively** — listing **5.1s vs mount 134.2s** (FUSE `rglob` stats all 38k bucket
583
- files; ~26×), batch-download I/O **57.6s vs FUSE-read 74.6s**. Mount *also* hit a transient
584
- `Volume mount failed: init container exhausted retries` on the first attempt (needed a cold retry;
585
- documented fresh-node CSI flake) — copy never mounts. → `auto` defaulting `hf://buckets/...` inputs to
586
- **copy** is the right call (already the implemented default); mount stays for when the bucket is already
587
- mounted or zero ephemeral disk is wanted.
588
-
589
- **TODO(alto):** ALTO XML export from `surya_blocks` is its own follow-up issue (block-level
590
- bbox→`HPOS/VPOS/WIDTH/HEIGHT`, label→`TextBlock`/`Illustration`, reading_order→order; line-level needs
591
- Surya's `DetectionPredictor`; word-level out of scope). The test bucket ships CA's own ALTO `.xml` next
592
- to each `.jp2` as a ready-made diff target.
593
-
594
- **License:** code Apache-2.0, **weights modified OpenRAIL-M** (research/personal/<$5M, no competitive use
595
- vs Datalab's API). Surfaced in the docstring, README entry, and output dataset card.
596
-
597
- **Benchmark/compare:** `--config`/`--create-pr` push the same multi-config pattern as the other scripts.
598
-
599
- ---
600
-
601
- ## Future: OCR Smoke Test Dataset
602
-
603
- **Status:** Idea (noted 2026-02-12)
604
-
605
- Build a small curated dataset (`uv-scripts/ocr-smoke-test`?) with ~2-5 samples from diverse sources. Purpose: fast CI-style verification that scripts still work after dep updates, without downloading full datasets.
606
-
607
- **Design goals:**
608
- - Tiny (~20-30 images total) so download is seconds not minutes
609
- - Covers the axes that break things: document type, image quality, language, layout complexity
610
- - Has ground truth text where possible for quality regression checks
611
- - All permissively licensed (CC0/CC-BY preferred)
612
-
613
- **Candidate sources:**
614
-
615
- | Source | What it covers | Why |
616
- |--------|---------------|-----|
617
- | `NationalLibraryOfScotland/medical-history-of-british-india` | Historical English, degraded scans | Has hand-corrected `text` column for comparison. CC0. Already tested with GLM-OCR. |
618
- | `davanstrien/ufo-ColPali` | Mixed modern documents | Already used as our go-to test set. Varied layouts. |
619
- | Something with **tables** | Structured data extraction | Tests `--task table` modes. Maybe a financial report or census page. |
620
- | Something with **formulas/LaTeX** | Math notation | Tests `--task formula`. arXiv pages or textbook scans. |
621
- | Something **multilingual** (CJK, Arabic, etc.) | Non-Latin scripts | GLM-OCR claims zh/ja/ko support. Good to verify. |
622
- | Something **handwritten** | Handwriting recognition | Edge case that reveals model limits. |
623
-
624
- **How it would work:**
625
- ```bash
626
- # Quick smoke test for any script
627
- uv run glm-ocr.py uv-scripts/ocr-smoke-test smoke-out --max-samples 5
628
- # Or a dedicated test runner that checks all scripts against it
629
- ```
630
-
631
- **Open questions:**
632
- - Build as a proper HF dataset, or just a folder of images in the repo?
633
- - Should we include expected output for regression testing (fragile if models change)?
634
- - Could we add a `--smoke-test` flag to each script that auto-uses this dataset?
635
- - Worth adding to HF Jobs scheduled runs for ongoing monitoring?
636
-
637
- ---
638
-
639
- ## OCR Benchmark Coordinator (`ocr-bench-run.py`)
640
-
641
- **Status:** Working end-to-end (2026-02-14)
642
-
643
- Launches N OCR models on the same dataset via `run_uv_job()`, each pushing to a shared repo as a separate config via `--config/--create-pr`. Eval done separately with `ocr-elo-bench.py`.
644
-
645
- ### Model Registry (4 models)
646
-
647
- | Slug | Model ID | Size | Default GPU | Notes |
648
- |------|----------|------|-------------|-------|
649
- | `glm-ocr` | `zai-org/GLM-OCR` | 0.9B | l4x1 | |
650
- | `deepseek-ocr` | `deepseek-ai/DeepSeek-OCR` | 4B | l4x1 | Auto-passes `--prompt-mode free` (no grounding tags) |
651
- | `lighton-ocr-2` | `lightonai/LightOnOCR-2-1B` | 1B | a100-large | |
652
- | `dots-ocr` | `rednote-hilab/dots.ocr` | 1.7B | l4x1 | Stable vLLM (>=0.9.1) |
653
-
654
- Each model entry has a `default_args` list for model-specific flags (e.g., DeepSeek uses `["--prompt-mode", "free"]`).
655
-
656
- ### Workflow
657
- ```bash
658
- # Launch all 4 models on same data
659
  uv run ocr-bench-run.py source-dataset --output my-bench --max-samples 50
660
-
661
- # Evaluate directly from PRs (no merge needed)
662
- uv run ocr-elo-bench.py my-bench --from-prs --mode both
663
-
664
- # Or merge + evaluate
665
- uv run ocr-elo-bench.py my-bench --from-prs --merge-prs --mode both
666
-
667
- # Other useful flags
668
- uv run ocr-bench-run.py --list-models # Show registry table
669
- uv run ocr-bench-run.py ... --dry-run # Preview without launching
670
- uv run ocr-bench-run.py ... --wait # Poll until complete
671
- uv run ocr-bench-run.py ... --models glm-ocr dots-ocr # Subset of models
672
  ```
673
 
674
- ### Eval script features (`ocr-elo-bench.py`)
675
- - `--from-prs`: Auto-discovers open PRs on the dataset repo, extracts config names from PR title `[config-name]` suffix, loads data from `refs/pr/N` without merging
676
- - `--merge-prs`: Auto-merges discovered PRs via `api.merge_pull_request()` before loading
677
- - `--configs`: Manually specify which configs to load (for merged repos)
678
- - `--mode both`: Runs pairwise ELO + pointwise scoring
679
- - Flat mode (original behavior) still works when `--configs`/`--from-prs` not used
680
-
681
- ### Scripts pushed to Hub
682
- All 4 scripts have been pushed to `uv-scripts/ocr` on the Hub with `--config`/`--create-pr` support:
683
- - `glm-ocr.py` ✅
684
- - `deepseek-ocr-vllm.py` ✅
685
- - `lighton-ocr2.py` ✅
686
- - `dots-ocr.py` ✅
687
-
688
- ### Benchmark Results
689
-
690
- #### Run 1: NLS Medical History (2026-02-14) — Pilot
691
-
692
- **Dataset:** `NationalLibraryOfScotland/medical-history-of-british-india` (10 samples, shuffled, seed 42)
693
- **Output repo:** `davanstrien/ocr-bench-test` (4 open PRs)
694
- **Judge:** `Qwen/Qwen2.5-VL-72B-Instruct` via HF Inference Providers
695
- **Content:** Historical English, degraded scans of medical texts
696
-
697
- **ELO (pairwise, 5 samples evaluated):**
698
- 1. DoTS.ocr — 1540 (67% win rate)
699
- 2. DeepSeek-OCR — 1539 (57%)
700
- 3. LightOnOCR-2 — 1486 (50%)
701
- 4. GLM-OCR — 1436 (29%)
702
-
703
- **Pointwise (5 samples):**
704
- 1. DeepSeek-OCR — 5.0/5.0
705
- 2. GLM-OCR — 4.6
706
- 3. LightOnOCR-2 — 4.4
707
- 4. DoTS.ocr — 4.2
708
-
709
- **Key finding:** DeepSeek-OCR's `--prompt-mode document` produces grounding tags (`<|ref|>`, `<|det|>`) that the judge penalizes heavily. Switching to `--prompt-mode free` (now the default in the registry) made it jump from last place to top 2.
710
-
711
- **Caveat:** 5 samples is far too few for stable rankings. The judge VLM is called once per comparison (pairwise) or once per model-sample (pointwise) via HF Inference Providers API.
712
-
713
- #### Run 2: Rubenstein Manuscript Catalog (2026-02-15) — First Full Benchmark
714
-
715
- **Dataset:** `biglam/rubenstein-manuscript-catalog` (50 samples, shuffled, seed 42)
716
- **Output repo:** `davanstrien/ocr-bench-rubenstein` (4 PRs)
717
- **Judge:** Jury of 2 via `ocr-vllm-judge.py` — `Qwen/Qwen2.5-VL-7B-Instruct` + `Qwen/Qwen3-VL-8B-Instruct` on A100
718
- **Content:** ~48K typewritten + handwritten manuscript catalog cards from Duke University (CC0)
719
-
720
- **ELO (pairwise, 50 samples, 300 comparisons, 0 parse failures):**
721
-
722
- | Rank | Model | ELO | W | L | T | Win% |
723
- |------|-------|-----|---|---|---|------|
724
- | 1 | LightOnOCR-2-1B | 1595 | 100 | 50 | 0 | 67% |
725
- | 2 | DeepSeek-OCR | 1497 | 73 | 77 | 0 | 49% |
726
- | 3 | GLM-OCR | 1471 | 57 | 93 | 0 | 38% |
727
- | 4 | dots.ocr | 1437 | 70 | 80 | 0 | 47% |
728
-
729
- **OCR job times** (all 50 samples each):
730
- - dots-ocr: 5.3 min (L4)
731
- - deepseek-ocr: 5.6 min (L4)
732
- - glm-ocr: 5.7 min (L4)
733
- - lighton-ocr-2: 6.4 min (A100)
734
-
735
- **Key findings:**
736
- - **LightOnOCR-2-1B dominates** on manuscript catalog cards (67% win rate, 100-point ELO gap over 2nd place) — a very different result from the NLS pilot where it placed 3rd
737
- - **Rankings are dataset-dependent**: NLS historical medical texts favored DoTS.ocr and DeepSeek-OCR; Rubenstein typewritten/handwritten cards favor LightOnOCR-2
738
- - **Jury of small models works well**: 0 parse failures on 300 comparisons thanks to vLLM structured output (xgrammar). Majority voting between 2 judges provides robustness
739
- - **50 samples gives meaningful separation**: Clear ELO gaps (1595 → 1497 → 1471 → 1437) unlike the noisy 5-sample pilot
740
- - This validates the multi-dataset benchmark approach — no single dataset tells the whole story
741
-
742
- #### Run 3: UFO-ColPali (2026-02-15) — Cross-Dataset Validation
743
-
744
- **Dataset:** `davanstrien/ufo-ColPali` (50 samples, shuffled, seed 42)
745
- **Output repo:** `davanstrien/ocr-bench-ufo` (4 PRs)
746
- **Judge:** `Qwen/Qwen3-VL-30B-A3B-Instruct` via `ocr-vllm-judge.py` on A100 (updated prompt)
747
- **Content:** Mixed modern documents (invoices, reports, forms, etc.)
748
-
749
- **ELO (pairwise, 50 samples, 294 comparisons):**
750
-
751
- | Rank | Model | ELO | W | L | T | Win% |
752
- |------|-------|-----|---|---|---|------|
753
- | 1 | DeepSeek-OCR | 1827 | 130 | 17 | 0 | 88% |
754
- | 2 | dots.ocr | 1510 | 64 | 83 | 0 | 44% |
755
- | 3 | LightOnOCR-2-1B | 1368 | 77 | 70 | 0 | 52% |
756
- | 4 | GLM-OCR | 1294 | 23 | 124 | 0 | 16% |
757
-
758
- **Human validation (30 comparisons):** DeepSeek-OCR #1 (same as judge), LightOnOCR-2 #3 (same). Middle pack (GLM-OCR #2 human / #4 judge, dots.ocr #4 human / #2 judge) shuffled.
759
-
760
- #### Cross-Dataset Comparison (Human-Validated)
761
-
762
- | Model | Rubenstein Human | Rubenstein Kimi | UFO Human | UFO 30B |
763
- |-------|:---------------:|:---------------:|:---------:|:-------:|
764
- | DeepSeek-OCR | **#1** | **#1** | **#1** | **#1** |
765
- | GLM-OCR | #2 | #3 | #2 | #4 |
766
- | LightOnOCR-2 | #4 | #2 | #3 | #3 |
767
- | dots.ocr | #3 | #4 | #4 | #2 |
768
-
769
- **Conclusion:** DeepSeek-OCR is consistently #1 across datasets and evaluation methods. Middle-pack rankings are dataset-dependent. Updated prompt fixed the LightOnOCR-2 overrating seen with old prompt/small judges.
770
-
771
- *Note: NLS pilot results (5 samples, 72B API judge) omitted — not comparable with newer methodology.*
772
-
773
- ### Known Issues / Next Steps
774
-
775
- 1. ✅ **More samples needed** — Done. Rubenstein run (2026-02-15) used 50 samples and produced clear ELO separation across all 4 models.
776
- 2. ✅ **Smaller judge model** — Tested with Qwen VL 7B + Qwen3 VL 8B via `ocr-vllm-judge.py`. Works well with structured output (0 parse failures). Jury of small models compensates for individual model weakness. See "Offline vLLM Judge" section below.
777
- 3. **Auto-merge in coordinator** — `--wait` could auto-merge PRs after successful jobs. Not yet implemented.
778
- 4. **Adding more models** — `rolm-ocr.py` exists but needs `--config`/`--create-pr` added. `deepseek-ocr2-vllm.py`, `paddleocr-vl-1.5.py`, etc. could also be added to the registry.
779
- 5. **Leaderboard Space** — See future section below.
780
- 6. ✅ **Result persistence** — `ocr-vllm-judge.py` now has `--save-results REPO_ID` flag. First dataset: `davanstrien/ocr-bench-rubenstein-judge`.
781
- 7. **More diverse datasets** — Rankings are dataset-dependent (LightOnOCR-2 wins on Rubenstein, DoTS.ocr won pilot on NLS). Need benchmarks on tables, formulas, multilingual, and modern documents for a complete picture.
782
- 8. ✅ **Human validation** — `ocr-human-eval.py` completed on Rubenstein (30/30). Tested 3 judge configs. **Kimi K2.5 (170B) via Novita + updated prompt = best human agreement** (only judge to match human's #1). Now default in `ocr-jury-bench.py`. See `OCR-BENCHMARK.md` for full comparison.
783
-
784
- ---
785
-
786
- ## Offline vLLM Judge (`ocr-vllm-judge.py`)
787
-
788
- **Status:** Working end-to-end (2026-02-15)
789
-
790
- Runs pairwise OCR quality comparisons using a local VLM judge via vLLM's offline `LLM()` pattern. Supports jury mode (multiple models vote sequentially on the same GPU) with majority voting.
791
-
792
- ### Why use this over the API judge (`ocr-jury-bench.py`)?
793
-
794
- | | API judge (`ocr-jury-bench.py`) | Offline judge (`ocr-vllm-judge.py`) |
795
- |---|---|---|
796
- | Parse failures | Needs retries for malformed JSON | 0 failures — vLLM structured output guarantees valid JSON |
797
- | Network | Rate limits, timeouts, transient errors | Zero network calls |
798
- | Cost | Per-token API pricing | Just GPU time |
799
- | Judge models | Limited to Inference Providers catalog | Any vLLM-supported VLM |
800
- | Jury mode | Sequential API calls per judge | Sequential model loading, batch inference per judge |
801
- | Best for | Quick spot-checks, access to 72B models | Batch evaluation (50+ samples), reproducibility |
802
-
803
- **Pushed to Hub:** `uv-scripts/ocr` as `ocr-vllm-judge.py` (2026-02-15)
804
-
805
- ### Test Results (2026-02-15)
806
-
807
- **Test 1 — Single judge, 1 sample, L4:**
808
- - Qwen2.5-VL-7B-Instruct, 6/6 comparisons, 0 parse failures
809
- - Total time: ~3 min (including model download + warmup)
810
-
811
- **Test 2 — Jury of 2, 3 samples, A100:**
812
- - Qwen2.5-VL-7B + Qwen3-VL-8B, 15/15 comparisons, 0 parse failures
813
- - GPU cleanup between models: successful (nanobind warnings are cosmetic)
814
- - Majority vote aggregation working (`[2/2]` unanimous, `[1/2]` split)
815
- - Total time: ~4 min (including both model downloads)
816
-
817
- **Test 3 — Full benchmark, 50 samples, A100 (Rubenstein Manuscript Catalog):**
818
- - Qwen2.5-VL-7B + Qwen3-VL-8B jury, 300/300 comparisons, 0 parse failures
819
- - Input: `davanstrien/ocr-bench-rubenstein` (4 PRs from `ocr-bench-run.py`)
820
- - Produced clear ELO rankings with meaningful separation
821
- - See "Benchmark Results → Run 2" in the OCR Benchmark Coordinator section above
822
-
823
- ### Usage
824
-
825
  ```bash
826
- # Single judge on L4
827
- hf jobs uv run --flavor l4x1 -s HF_TOKEN \
828
- ocr-vllm-judge.py davanstrien/ocr-bench-nls-50 --from-prs \
829
- --judge-model Qwen/Qwen2.5-VL-7B-Instruct --max-samples 10
830
-
831
- # Jury of 2 on A100 (recommended for jury mode)
832
- hf jobs uv run --flavor a100-large -s HF_TOKEN \
833
- ocr-vllm-judge.py davanstrien/ocr-bench-nls-50 --from-prs \
834
- --judge-model Qwen/Qwen2.5-VL-7B-Instruct \
835
- --judge-model Qwen/Qwen3-VL-8B-Instruct \
836
- --max-samples 50
837
  ```
838
 
839
- ### Implementation Notes
840
- - Comparisons built upfront on CPU as `NamedTuple`s, then batched to vLLM in single `llm.chat()` call
841
- - Structured output via compatibility shim: `StructuredOutputsParams` (vLLM >= 0.12) `GuidedDecodingParams` (older) prompt-based fallback
842
- - GPU cleanup between jury models: `destroy_model_parallel()` + `gc.collect()` + `torch.cuda.empty_cache()`
843
- - Position bias mitigation: A/B order randomized per comparison
844
- - A100 recommended for jury mode; L4 works for single 7B judge
845
-
846
- ### Next Steps
847
- 1. ✅ **Scale test** — Completed on Rubenstein Manuscript Catalog (50 samples, 300 comparisons, 0 parse failures). Rankings differ from API-based pilot (different dataset + judge), validating multi-dataset approach.
848
- 2. ✅ **Result persistence** — Added `--save-results REPO_ID` flag. Pushes 3 configs to HF Hub: `comparisons` (one row per pairwise comparison), `leaderboard` (ELO + win/loss/tie per model), `metadata` (source dataset, judge models, seed, timestamp). First dataset: `davanstrien/ocr-bench-rubenstein-judge`.
849
- 3. **Integrate into `ocr-bench-run.py`** — Add `--eval` flag that auto-runs vLLM judge after OCR jobs complete
850
-
851
- ---
852
-
853
- ## Blind Human Eval (`ocr-human-eval.py`)
854
-
855
- **Status:** Working (2026-02-15)
856
-
857
- Gradio app for blind A/B comparison of OCR outputs. Shows document image + two anonymized OCR outputs, human picks winner or tie. Computes ELO rankings from human annotations and optionally compares against automated judge results.
858
-
859
- ### Usage
860
-
861
  ```bash
862
- # Basic — blind human eval only
863
- uv run ocr-human-eval.py davanstrien/ocr-bench-rubenstein --from-prs --max-samples 5
864
-
865
- # With judge comparison — loads automated judge results for agreement analysis
866
  uv run ocr-human-eval.py davanstrien/ocr-bench-rubenstein --from-prs \
867
  --judge-results davanstrien/ocr-bench-rubenstein-judge --max-samples 5
868
  ```
869
 
870
- ### Features
871
- - **Blind evaluation**: Two-tab design Evaluate tab never shows model names, Results tab reveals rankings
872
- - **Position bias mitigation**: A/B order randomly swapped per comparison
873
- - **Resume support**: JSON annotations saved atomically after each vote; restart app to resume where you left off
874
- - **Live agreement tracking**: Per-vote feedback shows running agreement with automated judge (when `--judge-results` provided)
875
- - **Split-jury prioritization**: Comparisons where automated judges disagreed ("1/2" agreement) shown first — highest annotation value per vote
876
- - **Image variety**: Round-robin interleaving by sample so you don't see the same document image repeatedly
877
- - **Soft/hard disagreement analysis**: Distinguishes between harmless ties-vs-winner disagreements and genuine opposite-winner errors
878
-
879
- ### First Validation Results (Rubenstein, 30 annotations)
880
-
881
- Tested 3 judge configs against 30 human annotations. **Kimi K2.5 (170B) via Novita** is the only judge to match human's #1 pick (DeepSeek-OCR). Small models (7B/8B/30B) all overrate LightOnOCR-2 due to bias toward its commentary style. Updated prompt (prioritized faithfulness > completeness > accuracy) helps but model size is the bigger factor.
882
-
883
- Full results and analysis in `OCR-BENCHMARK.md` → "Human Validation" section.
884
-
885
- ### Next Steps
886
- 1. **Second dataset** — Run on NLS Medical History for cross-dataset human validation
887
- 2. **Multiple annotators** — Currently single-user; could support annotator ID for inter-annotator agreement
888
- 3. **Remaining LightOnOCR-2 gap** — Still #2 (Kimi) vs #4 (human). May need to investigate on more samples or strip commentary in preprocessing
889
 
890
  ---
891
 
892
- ## Future: Leaderboard HF Space
893
-
894
- **Status:** Idea (noted 2026-02-14)
895
-
896
- Build a Hugging Face Space with a persistent leaderboard that gets updated after each benchmark run. This would give a public-facing view of OCR model quality.
897
-
898
- **Design ideas:**
899
- - Gradio or static Space displaying ELO ratings + pointwise scores
900
- - `ocr-elo-bench.py` could push results to a dataset that the Space reads
901
- - Or the Space itself could run evaluation on demand
902
- - Show per-document comparisons (image + side-by-side OCR outputs)
903
- - Historical tracking how scores change across model versions
904
- - Filter by document type (historical, modern, tables, formulas, multilingual)
905
-
906
- **Open questions:**
907
- - Should the eval script push structured results to a dataset (e.g., `uv-scripts/ocr-leaderboard-data`)?
908
- - Static leaderboard (updated by CI/scheduled job) vs interactive (evaluate on demand)?
909
- - Include sample outputs for qualitative comparison?
910
- - How to handle different eval datasets (NLS medical history vs UFO vs others)?
 
 
 
 
 
911
 
912
  ---
913
 
914
- ## Incremental Uploads / Checkpoint Strategy — ON HOLD
915
-
916
- **Status:** Waiting on HF Hub Buckets (noted 2026-02-20)
917
-
918
- **Current state:**
919
- - `glm-ocr.py` (v1): Simple batch-then-push. Works fine for most jobs.
920
- - `glm-ocr-v2.py`: Adds CommitScheduler-based incremental uploads + checkpoint/resume. ~400 extra lines. Works but has tradeoffs (commit noise, `--create-pr` incompatible, complex resume metadata).
921
-
922
- **Decision: Do NOT port v2 pattern to other scripts.** Wait for HF Hub Buckets instead.
923
-
924
- **Why:** Two open PRs will likely make the v2 CommitScheduler approach obsolete:
925
- - [huggingface_hub#3673](https://github.com/huggingface/huggingface_hub/pull/3673) — Buckets API: S3-like mutable object storage on HF, no git versioning overhead
926
- - [huggingface_hub#3807](https://github.com/huggingface/huggingface_hub/pull/3807) — HfFileSystem support for buckets: fsspec-compatible, so pyarrow/pandas/datasets can read/write `hf://buckets/` paths directly
927
-
928
- **What Buckets would replace:** Once landed, incremental saves become one line per batch:
929
- ```python
930
- batch_ds.to_parquet(f"hf://buckets/{user}/ocr-scratch/shard-{batch_num:05d}.parquet")
931
- ```
932
- No CommitScheduler, no CleanupScheduler, no resume metadata, no completed batch scanning. Just write to the bucket path via fsspec. Final step: read back from bucket, `push_to_hub` to a clean dataset repo (compatible with `--create-pr`).
933
-
934
- **Action items when Buckets ships:**
935
- 1. Test `hf://buckets/` fsspec writes on one script (glm-ocr is the guinea pig)
936
- 2. Verify: write performance, atomicity (partial writes visible?), auth propagation in HF Jobs
937
- 3. If it works, adopt as the standard pattern for all scripts — simple enough to inline (~20 lines)
938
- 4. Retire `glm-ocr-v2.py` CommitScheduler approach
939
-
940
- **Until then:** v1 scripts stay as-is. `glm-ocr-v2.py` exists if someone needs resume on a very large job today.
941
-
942
- ---
943
 
944
- **Last Updated:** 2026-02-20
945
- **Watch PRs:**
946
- - **HF Hub Buckets API** ([#3673](https://github.com/huggingface/huggingface_hub/pull/3673)): Core buckets support. Will enable simpler incremental upload pattern for all scripts.
947
- - **HfFileSystem Buckets** ([#3807](https://github.com/huggingface/huggingface_hub/pull/3807)): fsspec support for `hf://buckets/` paths. Key for zero-boilerplate writes from scripts.
948
- - DeepSeek-OCR-2 stable vLLM release: Currently only in nightly. Watch for vLLM 0.16.0 stable release on PyPI to remove nightly dependency.
949
- - nanobind leak warnings in vLLM structured output (xgrammar): Cosmetic only, does not affect results. May be fixed in future xgrammar release.
 
1
+ # OCR Scripts Development Notes
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2
 
3
+ Dev notes for the `ocr/` recipes: the **conventions** to follow, the **per-script gotchas** (the
4
+ "why" behind each script's quirks), and the **internal tooling**. Runnable examples live in each
5
+ script's docstring and `README.md`; benchmark result tables live in `OCR-BENCHMARK.md`.
 
 
6
 
7
+ - [Conventions & invariants](#conventions--invariants) — read before adding/changing a recipe
8
+ - [Script status](#script-status) · [Per-script gotchas](#per-script-gotchas)
9
+ - [Internal tooling](#internal-tooling) · [Deferred / tracked](#deferred--tracked) · [Change log](#change-log)
10
 
11
+ ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
12
 
13
+ ## Conventions & invariants
14
+
15
+ Read this before adding or changing a recipe. Each rule maps to a failure we've actually hit; the
16
+ planned **self-review skill** (see [Deferred](#deferred--tracked)) just enforces this list.
17
+
18
+ - **Self-contained single file.** Each recipe is one PEP 723 UV script runnable from a raw URL
19
+ (`hf jobs uv run <url>`). No shared *importable local* module (the job env only gets the one file).
20
+ Extra pip deps are fine — **pin them**. A heavy/stable/shared subsystem may become an opt-in *package*
21
+ dep (e.g. bucket I/O → `bucketbag`, [#67](https://github.com/davanstrien/uv-scripts-for-ai/issues/67)),
22
+ never a local import. Recipes = inline; internal tooling may share freely.
23
+ - **GPU + output.** Check `torch.cuda.is_available()` and exit clearly if absent. Write to the Hub
24
+ (`push_to_hub`) or a bucket (`-v hf://…`), never local paths (Jobs disk is ephemeral).
25
+ - **vLLM image + fail-fast preflight.** If the model's arch isn't in a stable vLLM wheel, **omit
26
+ `vllm`/`torch` from deps** and run on the pinned `vllm/vllm-openai` image via
27
+ `--image … --python … -e PYTHONPATH=…`; add a preflight that `sys.exit(1)`s naming the exact flags
28
+ (surya-class — see gotchas). Pinned-image scripts: `surya-ocr` (`:v0.20.1`, **site-packages**),
29
+ `nanonets-ocr2` (`:v0.10.2`), `unlimited-ocr` (`:unlimited-ocr`), `deepseek-ocr2`/`glm-ocr` (nightly).
30
+ - **Pins are temporary.** An image/version pin (`:v0.10.2`, `:v0.20.1`, a nightly, `surya-ocr==0.20.0`,
31
+ …) is a workaround for a *current* ecosystem gap — a decode regression, an arch not yet in a stable
32
+ wheel, a resolver backtrack. In the recipe, record **why** the pin exists and **what would loosen it**
33
+ (e.g. "move back to the default image when a newer vLLM ships a Qwen2.5-VL decode fix"; "drop the
34
+ nightly once the arch lands in a stable release"). Re-test periodically and relax when the gap closes —
35
+ that's what the `bump-vllm-pins` skill is for; prefer floors over exact pins once you can.
36
+ - **Env guards on the bare image.** Set `VLLM_USE_FLASHINFER_SAMPLER=0` (and `VLLM_USE_DEEP_GEMM=0`
37
+ for nightly vLLM) **before** importing `vllm` — both JIT paths need `nvcc`, which the bare uv image lacks.
38
+ - **Context-length invariant.** `--max-tokens` ≤ `--max-model-len` ≤ the model's real max context
39
+ (`config.json` `max_position_embeddings`; VLMs → `text_config`, mind `rope_scaling`). vLLM refuses to
40
+ start if `max_model_len` is over (we don't set `VLLM_ALLOW_LONG_MAX_MODEL_LEN`); output can't fit if
41
+ `max_tokens` > `max_model_len`. Check:
42
+ `curl -s https://huggingface.co/<model>/raw/main/config.json | python -c "import json,sys;c=json.load(sys.stdin);t=c.get('text_config',c);print(t.get('max_position_embeddings'),t.get('rope_scaling'))"`.
43
+ - **Output-column collision guard.** Every recipe that adds an output column calls
44
+ `ensure_output_columns_free(dataset, [cols], overwrite)` (or the inline sink guard for pp-*) so it
45
+ fails fast instead of duplicating/clobbering an input column; `--overwrite` opts into replacing it.
46
+ Default `--output-column` is `markdown` (never a bare `text`). ([#66](https://github.com/davanstrien/uv-scripts-for-ai/pull/66))
47
+ - **Bound large images.** Full-page recipes cap input pixels / resize, or size `max_model_len` to fit —
48
+ a 7–9 MP page is ~14k image tokens. Prefer bounding the input (deterministic) over a giant context;
49
+ don't auto-size `max_model_len` from images (it's fixed at engine init, before images are seen).
50
+ - **Dep sanity.** No stale version *caps* that drag a transitive lib back — e.g. `pyarrow<18` forced an
51
+ old `datasets` lacking the `Json` feature → `load_dataset` crashed (the glm-ocr bug). Use floors, not ceilings.
52
+ - **Error signalling (known gap).** Scripts currently write sentinels (`[OCR ERROR]`, `[SURYA GENERATE
53
+ ERROR]`) *into* the output column, so partial failures are silent. A companion `ocr_error` status
54
+ column is the deferred fix (see [Deferred](#deferred--tracked)).
55
 
56
+ ---
57
 
58
+ ## Script status
59
+
60
+ Legend: ✅ production-ready · ⚠️ works only with a required pinned image · 🧪 experimental/on-hold.
61
+ "+image" = needs a `--image vllm/vllm-openai:<tag>` override (not the default uv image).
62
+
63
+ | Script | | Backend | Flavor | Note |
64
+ |--------|--|---------|--------|------|
65
+ | `deepseek-ocr-vllm.py` | ✅ | vLLM (stable) | l4x1 | `NGramPerReqLogitsProcessor` anti-repeat |
66
+ | `deepseek-ocr2-vllm.py` | ✅ | vLLM (nightly) | l4x1 | arch needs nightly; `addict`+`matplotlib` deps |
67
+ | `lighton-ocr2.py` | ✅ | vLLM | a100-large / l4x1 | resize 1540px; `--max-model-len` 16384 |
68
+ | `paddleocr-vl-1.5.py` | ✅ | transformers | l4x1 | not vLLM (server-only upstream); single-image |
69
+ | `paddleocr-vl-1.6.py` | ✅ | vLLM | l4x1 | smart-resize ~1M px; SOTA OmniDocBench |
70
+ | `paddleocr-vl.py` | ✅ | vLLM | l4x1 | |
71
+ | `dots-ocr.py` | ✅ | vLLM (stable) | l4x1 | `--max-model-len` 32768; no internal resize |
72
+ | `dots-ocr-1.5.py` | ✅ | vLLM 0.17.1 | l4x1 | see gotcha (`content_format`, mirror, bbox space) |
73
+ | `glm-ocr.py` | ✅ | vLLM (nightly) | l4x1 | `VLLM_USE_DEEP_GEMM=0`; no pyarrow cap |
74
+ | `glm-ocr-v2.py` | 🧪 | vLLM (nightly) | l4x1 | CommitScheduler incremental — on hold (see Deferred) |
75
+ | `nanonets-ocr.py` | ✅ | vLLM | a10g-small | `--max-model-len` 32768 (`--max-tokens` 15000) |
76
+ | `nanonets-ocr2.py` | ⚠️+image | vLLM `:v0.10.2` | a10g-small | Qwen2.5-VL ≥0.11 regression → pure `!` |
77
+ | `unlimited-ocr-vllm.py` | ✅+image | vLLM `:unlimited-ocr` | l4x1 | single-image; multi-page → serve |
78
+ | `surya-ocr.py` | ✅+image | vLLM `:v0.20.1` | l4x1 | offline backend inject; site-packages PYTHONPATH |
79
+ | `surya-ocr-bucket.py` | ✅+image | vLLM `:v0.20.1` | l4x1 | bucket I/O; pin `surya-ocr==0.20.0` |
80
+ | `lift-extract.py` | ✅ | hf / vLLM | a100-large | schema-constrained extraction; naming gotcha |
81
+ | `nuextract3.py`, `lfm2-extract.py`, `lfm2-vl-extract.py` | ✅ | vLLM | l4x1 | structured extraction |
82
+ | `rolm-ocr.py`, `smoldocling-ocr.py`, `numarkdown-ocr.py`, `hunyuan-ocr.py`, `qianfan-ocr.py`, `firered-ocr.py`, `abot-ocr.py`, `falcon-ocr.py`, `olmocr2-vllm.py`, `dots-mocr.py` | ✅ | vLLM | varies | see `README.md` for flags |
83
+ | `pp-ocrv6.py`, `pp-doclayout.py` | ✅ | PaddleOCR / PaddleX | l4x1 | classical det+rec; dataset **or** bucket I/O |
84
+
85
+ **License note:** Surya and `lift` ship code as Apache-2.0 but **weights under a modified OpenRAIL-M**
86
+ (research/personal/<$5M, no competitive use vs Datalab's API) — surfaced in each docstring + card.
87
 
88
+ ---
89
 
90
+ ## Per-script gotchas
91
+
92
+ Only the scripts with load-bearing quirks; the rest are unremarkable (`README.md` covers flags).
93
+
94
+ ### `surya-ocr.py` / `surya-ocr-bucket.py` pinned image + site-packages path
95
+ Surya-2 (`datalab-to/surya-ocr-2`, 650M, `qwen3_5`) needs its **known-good** vLLM build, and the
96
+ `:v0.20.1` image puts python at `/usr/local/bin/python3` and libs at
97
+ **`/usr/local/lib/python3.12/site-packages`** (not the usual `dist-packages`) — wrong path →
98
+ `No module named 'vllm'` → 0/5. It can't Docker-in-Docker Surya's normal server, so it **injects an
99
+ in-process `OfflineVLLMBackend`** into `SuryaInferenceManager` (subclassing Surya's `Backend` ABC) and
100
+ reuses Surya's own prompts/`scale_to_fit`/HTML+bbox parsing so the offline path matches the server.
101
+ `mm_processor_kwargs={min_pixels:3136, max_pixels:6291456}`, `max_model_len=18000`, `logprobs=1` →
102
+ per-block `confidence`. Writes two columns (`--output-column` markdown + `surya_blocks` JSON). Never
103
+ name the file `surya.py` (shadows the package). The recipe now **fails fast** if `vllm` isn't importable,
104
+ naming the required flags. **Bucket variant:** pin `surya-ocr==0.20.0` (loosening it, or adding
105
+ `huggingface-hub>=1.6.0`, lets uv backtrack to a surya without `surya.inference`); **copy beats mount**
106
+ for bucket reads (FUSE `rglob` is ~26× slower on a 38k-file bucket; mount also hit a transient CSI flake);
107
+ `.jp2` via an `imagecodecs` fallback (Pillow lacks OpenJPEG); resume-by-skip on the output `.json`.
108
+
109
+ ### `nanonets-ocr2.py` — pinned `:v0.10.2` image
110
+ Nanonets-OCR2-3B is **Qwen2.5-VL**, which has a vLLM **≥0.11 decode regression** (outputs pure `!` on
111
+ every page) — [vllm#27775](https://github.com/vllm-project/vllm/issues/27775). 0.9.2/0.10.1/**0.10.2**
112
+ are known-good. Not context length (still `!` at 32768) and not torch.compile. Pip-pinning `vllm==0.10.2`
113
+ clashes with modern `transformers` (old tokenizer API), so run on the **`:v0.10.2` image** (ships a
114
+ consistent vLLM 0.10.2 + transformers 4.56.1); `vllm`/`torch` omitted from deps. `--max-model-len` 32768
115
+ (the 15000 `--max-tokens` can't fit 8192). Re-test the default image when a newer vLLM ships a Qwen2.5-VL
116
+ decode fix.
117
+
118
+ ### `dots-ocr-1.5.py` — `content_format="string"` + resized-bbox space
119
+ Must pass `chat_template_content_format="string"` to `llm.chat()` — the model's `tokenizer_config.json`
120
+ template expects string content; without it you get ~1 token then EOS (empty output). The v1.5 weights
121
+ aren't on HF from the authors — **mirrored to `davanstrien/dots.ocr-1.5`** from ModelScope (MIT-based).
122
+ Layout bboxes are in the **resized** image space (`Qwen2VLImageProcessor.smart_resize`,
123
+ `max_pixels=11,289,600`, `factor=28`); map back with:
124
  ```python
125
  import math
126
+ def smart_resize(h, w, factor=28, min_pixels=3136, max_pixels=11289600):
127
+ h_bar, w_bar = max(factor, round(h/factor)*factor), max(factor, round(w/factor)*factor)
128
+ if h_bar*w_bar > max_pixels:
129
+ beta = math.sqrt((h*w)/max_pixels); h_bar, w_bar = math.floor(h/beta/factor)*factor, math.floor(w/beta/factor)*factor
130
+ elif h_bar*w_bar < min_pixels:
131
+ beta = math.sqrt(min_pixels/(h*w)); h_bar, w_bar = math.ceil(h*beta/factor)*factor, math.ceil(w*beta/factor)*factor
 
 
 
 
 
 
132
  return h_bar, w_bar
133
+ # orig_x = bbox_x * (orig_w / w_bar); orig_y = bbox_y * (orig_h / h_bar)
 
 
 
 
134
  ```
135
+ (Same `smart_resize`/`max_pixels=11.29M` applies to `dots-ocr.py` v1's processor cap — but the
136
+ `content_format="string"` fix does **not**: v1 works with the auto-detected `openai` chat format.)
137
+
138
+ ### `unlimited-ocr-vllm.py` dedicated image, single-image batch
139
+ Baidu `baidu/Unlimited-OCR` (3.3B, DeepSeek-OCR descendant); arch is in **no stable vLLM wheel**, so it
140
+ runs on **`vllm/vllm-openai:unlimited-ocr`** (`:unlimited-ocr-cu129` on Hopper), standard `/usr/bin/python3`
141
+ + `dist-packages`. `NGramPerReqLogitsProcessor` (re-exported via `unlimited_ocr`), prompt
142
+ `<image>document parsing.`, `limit_mm_per_prompt={"image":1}`, `--strip-grounding` drops `<|det|>`/`<|ref|>`.
143
+ **Batch recipe stays single-image**; multi-page is finicky offline (one `<image>` per page; degrades on
144
+ hard scans) and belongs to **serving** both engines read clean multi-page docs, but **SGLang is more
145
+ robust on hard/degraded scans**. Serving setup (SGLang pin `lmsysorg/sglang:v0.5.10.post1`, a100+flashinfer
146
+ HF `h200` nodes fail with `CUDA error 802`) is in `serving-unlimited-ocr.md`.
147
+
148
+ ### `lift-extract.py` — naming + backends
149
+ Datalab `lift` (9B, Qwen3.5), schema-constrained image/PDF JSON; the only recipe ingesting PDFs directly.
150
+ **Must not be named `lift.py`** (shadows the installed `lift` package → ImportError). Two in-process backends
151
+ via `--method`: `hf` (default image, plain `model.generate`) and `vllm` (needs the `vllm/vllm-openai` image;
152
+ reproduces lift's own recipe: `mm_processor_kwargs={min_pixels:3136,max_pixels:861696}`, guided JSON schema,
153
+ `temperature=0.0,top_p=0.1,max_tokens=12384`). Pin `--model datalab-to/lift` via the `MODEL_CHECKPOINT` env
154
+ (settings read env at import).
155
+
156
+ ### `deepseek-ocr-vllm.py` / `deepseek-ocr2-vllm.py`
157
+ v1 uses the official offline pattern (`llm.generate()` + `NGramPerReqLogitsProcessor` for repetition).
158
+ **Known bug** (hit on vLLM *nightly*, 2026-02-12; unverified on the stable wheels v1 now resolves):
159
+ some aspect ratios trip `images_crop dim[2] expected 1024, got 640` (gundam-mode
160
+ default vs a validator expecting 1024²) — hit 2/10 on `ufo-ColPali`, aspect-ratio dependent, no upstream
161
+ issue filed ([vllm#28160](https://github.com/vllm-project/vllm/issues/28160) is the related request). v2
162
+ needs **nightly** vLLM (`DeepseekOCR2ForCausalLM` not in stable) + `addict`/`matplotlib` (its HF custom
163
+ code), plus `limit_mm_per_prompt={"image":1}`.
164
+
165
+ ### `glm-ocr.py`
166
+ Chatty on blank pages / can emit degenerate repeats — that's **model quality, not a crash**; don't
167
+ re-debug it as a recipe bug. (The actual historical crash was the `pyarrow<18` cap — see Conventions.)
168
+
169
+ ### `lighton-ocr2.py`
170
+ The original breakage was **not** vLLM — it was a dead `HF_HUB_ENABLE_HF_TRANSFER=1` (the `hf_transfer`
171
+ package is gone), which surfaced as "Can't load image processor". Removed. Pixtral ViT + Qwen3, RLVR-trained,
172
+ resize 1540px @200 DPI, `--max-model-len` 16384. `paddleocr-vl-1.5.py` uses the **transformers** backend
173
+ (single-image) because PaddleOCR-VL only supports vLLM in server mode.
174
 
175
  ---
176
 
177
+ ## Internal tooling
178
 
179
+ Not user recipes — benchmark/eval infra. **Result tables + validation history → `OCR-BENCHMARK.md`.**
 
180
 
181
+ ### `ocr-bench-run.py` coordinator
182
+ Launches N OCR models on the same dataset, each pushing to a shared repo as a separate config via
183
+ `--config/--create-pr`. Eval separately with `ocr-vllm-judge.py` / `ocr-elo-bench.py`. Registry (4 models):
184
+ `glm-ocr`, `deepseek-ocr` (auto `--prompt-mode free`), `lighton-ocr-2`, `dots-ocr`; each has a `default_args`.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
185
  ```bash
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
186
  uv run ocr-bench-run.py source-dataset --output my-bench --max-samples 50
187
+ uv run ocr-bench-run.py --list-models # registry table
188
+ uv run ocr-bench-run.py ... --models glm-ocr dots-ocr --dry-run
189
+ uv run ocr-elo-bench.py my-bench --from-prs --mode both # eval from PRs, no merge
 
 
 
 
 
 
 
 
 
190
  ```
191
 
192
+ ### `ocr-vllm-judge.py` — offline vLLM jury judge
193
+ Pairwise OCR-quality comparisons via vLLM offline `LLM()`; jury mode (multiple models vote, majority
194
+ aggregation) with **0 parse failures** (structured output via the `StructuredOutputsParams` `GuidedDecodingParams`
195
+ prompt shim). Prefer over the API judge (`ocr-jury-bench.py`) for batch eval no rate limits, reproducible.
196
+ `--from-prs` loads configs from open PRs without merging; `--save-results REPO` persists comparisons/leaderboard/metadata.
197
+ A100 recommended for jury mode; L4 works for a single 7B judge.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
198
  ```bash
199
+ hf jobs uv run --flavor a100-large -s HF_TOKEN ocr-vllm-judge.py davanstrien/ocr-bench-nls-50 --from-prs \
200
+ --judge-model Qwen/Qwen2.5-VL-7B-Instruct --judge-model Qwen/Qwen3-VL-8B-Instruct --max-samples 50
 
 
 
 
 
 
 
 
 
201
  ```
202
 
203
+ ### `ocr-human-eval.py` — blind human A/B
204
+ Gradio app for blind A/B with ELO + optional agreement-vs-judge analysis (split-jury comparisons shown
205
+ first; round-robin image variety). Resume-safe (atomic JSON per vote).
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
206
  ```bash
 
 
 
 
207
  uv run ocr-human-eval.py davanstrien/ocr-bench-rubenstein --from-prs \
208
  --judge-results davanstrien/ocr-bench-rubenstein-judge --max-samples 5
209
  ```
210
 
211
+ **Validation headline** (full tables in `OCR-BENCHMARK.md`): DeepSeek-OCR is consistently #1 across
212
+ datasets and eval methods; middle-pack rankings are dataset-dependent; a jury of small models gives 0
213
+ parse failures; **Kimi K2.5 (170B)** is the only judge matching the human's #1 (small judges overrate
214
+ LightOnOCR-2's commentary style).
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
215
 
216
  ---
217
 
218
+ ## Deferred / tracked
219
+
220
+ - **bucketbag adoption** evaluate adopting `bucketbag` for the bucket recipes (slim recipes / harden
221
+ bucketbag / find other beneficiaries) → [#67](https://github.com/davanstrien/uv-scripts-for-ai/issues/67).
222
+ - **Self-review skill** (spark) a dev-only skill (sibling to `bump-vllm-pins`) that reviews a recipe/diff
223
+ against the [Conventions](#conventions--invariants) block: context-length, collision guard, vLLM-image +
224
+ preflight, env guards, dep sanity, image bounding, optional Jobs smoke. Enforces that list; build after
225
+ the current work.
226
+ - **Error-signalling** companion `ocr_error` status column (null cell + truncated exception) instead of
227
+ sentinels in the output column, so "read nothing" ≠ "run errored". Touches ~all recipes; deferred.
228
+ - **OCR smoke-test dataset** a tiny curated set (~20–30 images across doc-type/quality/language/layout,
229
+ ground truth where possible) for fast CI-style regression checks after dep bumps. Pairs with the skill.
230
+ - **Multi-page batch (Unlimited-OCR)** an SGLang-server-in-job recipe for robust multi-page at scale
231
+ (single-image vLLM stays the batch default). Gated on a real corpus-scale need + the `h200`/`fa3` infra
232
+ fix; see `serving-unlimited-ocr.md`.
233
+ - **ALTO XML export** from `surya_blocks` (block-level bbox→`HPOS/VPOS/…`, label→`TextBlock`/`Illustration`);
234
+ the surya-ocr-bucket test bucket ships CA's own ALTO `.xml` as a diff target.
235
+ - **Incremental uploads** superseded by HF Buckets / `bucketbag` ([#67](https://github.com/davanstrien/uv-scripts-for-ai/issues/67));
236
+ `glm-ocr-v2.py` keeps the older CommitScheduler resume path for very large jobs today (do not port it on hold).
237
+ - **Leaderboard Space** — public ELO/pointwise view fed by the benchmark datasets. Idea only.
238
+
239
+ **Watch:** `deepseek-ocr2` / `glm-ocr` stay on nightly vLLM until their arch lands in a stable release.
240
+ The nightly index (`https://wheels.vllm.ai/nightly`) occasionally has transient build issues (e.g. only
241
+ ARM wheels) — if a nightly-recipe install fails on resolution, wait and retry before debugging the recipe.
242
 
243
  ---
244
 
245
+ ## Change log
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
246
 
247
+ - **2026-07-01** — large full-page scan fixes ([#65](https://github.com/davanstrien/uv-scripts-for-ai/pull/65)):
248
+ surya vLLM-missing preflight; `dots` 8192→32768 + `--max-pixels`; `lighton-ocr2` 8192→16384; `glm` dropped
249
+ `pyarrow<18` (→ `datasets` `Json` load crash) + `VLLM_USE_DEEP_GEMM=0` + `--max-pixels`; `pp-ocrv6`
250
+ `--output-column` + collision guard. Then the output-column collision-guard + `--overwrite` sweep across
251
+ the recipes ([#66](https://github.com/davanstrien/uv-scripts-for-ai/pull/66)); `nanonets-ocr` 8192→32768.
252
+ - **Earlier** per-script fixes are recorded in git history + the gotchas above; benchmark runs in `OCR-BENCHMARK.md`.
OCR-BENCHMARK.md ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # OCR Benchmark — results & history
2
+
3
+ Result tables and validation history for the OCR benchmark tooling. **How to *run* the tools**
4
+ (`ocr-bench-run.py`, `ocr-vllm-judge.py`, `ocr-human-eval.py`) lives in `CLAUDE.md` → "Internal
5
+ tooling"; this file is the accumulated *evidence*.
6
+
7
+ ## Model registry (as benchmarked)
8
+
9
+ | Slug | Model | Size | GPU | Notes |
10
+ |------|-------|------|-----|-------|
11
+ | `glm-ocr` | `zai-org/GLM-OCR` | 0.9B | l4x1 | |
12
+ | `deepseek-ocr` | `deepseek-ai/DeepSeek-OCR` | 4B | l4x1 | auto `--prompt-mode free` (no grounding tags) |
13
+ | `lighton-ocr-2` | `lightonai/LightOnOCR-2-1B` | 1B | a100-large | |
14
+ | `dots-ocr` | `rednote-hilab/dots.ocr` | 1.7B | l4x1 | stable vLLM (>=0.9.1) |
15
+
16
+ ## Run 1 — NLS Medical History (2026-02-14, pilot)
17
+
18
+ `NationalLibraryOfScotland/medical-history-of-british-india`, 10 samples, seed 42. Judge:
19
+ `Qwen2.5-VL-72B` via Inference Providers. Historical English, degraded scans.
20
+
21
+ - **ELO (pairwise, 5 samples):** DoTS 1540 (67%) · DeepSeek 1539 (57%) · LightOnOCR-2 1486 (50%) · GLM 1436 (29%)
22
+ - **Pointwise (5):** DeepSeek 5.0 · GLM 4.6 · LightOnOCR-2 4.4 · DoTS 4.2
23
+ - **Key finding:** DeepSeek's `--prompt-mode document` emits grounding tags (`<|ref|>`/`<|det|>`) the
24
+ judge penalises heavily; switching to `--prompt-mode free` moved it last→top-2 (now the registry default).
25
+ - **Caveat:** 5 samples is far too few for stable rankings.
26
+
27
+ ## Run 2 — Rubenstein Manuscript Catalog (2026-02-15, first full run)
28
+
29
+ `biglam/rubenstein-manuscript-catalog`, 50 samples, seed 42. Judge: jury of `Qwen2.5-VL-7B` +
30
+ `Qwen3-VL-8B` on A100 (`ocr-vllm-judge.py`). ~48K typewritten + handwritten cards (Duke, CC0).
31
+
32
+ **ELO (50 samples, 300 comparisons, 0 parse failures):**
33
+
34
+ | Rank | Model | ELO | W | L | T | Win% |
35
+ |------|-------|-----|---|---|---|------|
36
+ | 1 | LightOnOCR-2-1B | 1595 | 100 | 50 | 0 | 67% |
37
+ | 2 | DeepSeek-OCR | 1497 | 73 | 77 | 0 | 49% |
38
+ | 3 | GLM-OCR | 1471 | 57 | 93 | 0 | 38% |
39
+ | 4 | dots.ocr | 1437 | 70 | 80 | 0 | 47% |
40
+
41
+ Job times (50 samples): dots 5.3 min (L4) · deepseek 5.6 (L4) · glm 5.7 (L4) · lighton 6.4 (A100).
42
+
43
+ **Findings:** LightOnOCR-2 dominates on manuscript cards (very different from the NLS pilot) — rankings
44
+ are **dataset-dependent**; a jury of small models works well (0 parse failures via vLLM structured output);
45
+ 50 samples gives meaningful separation.
46
+
47
+ ## Run 3 — UFO-ColPali (2026-02-15, cross-dataset validation)
48
+
49
+ `davanstrien/ufo-ColPali`, 50 samples, seed 42. Judge: `Qwen3-VL-30B-A3B` on A100 (updated prompt).
50
+ Mixed modern documents.
51
+
52
+ **ELO (50 samples, 294 comparisons):**
53
+
54
+ | Rank | Model | ELO | W | L | T | Win% |
55
+ |------|-------|-----|---|---|---|------|
56
+ | 1 | DeepSeek-OCR | 1827 | 130 | 17 | 0 | 88% |
57
+ | 2 | dots.ocr | 1510 | 64 | 83 | 0 | 44% |
58
+ | 3 | LightOnOCR-2-1B | 1368 | 77 | 70 | 0 | 52% |
59
+ | 4 | GLM-OCR | 1294 | 23 | 124 | 0 | 16% |
60
+
61
+ **Human validation (30 comparisons):** DeepSeek #1 (matches judge), LightOnOCR-2 #3 (matches). Middle
62
+ pack (GLM, dots) shuffled between human and judge.
63
+
64
+ ## Cross-dataset comparison (human-validated)
65
+
66
+ | Model | Rubenstein Human | Rubenstein Kimi | UFO Human | UFO 30B |
67
+ |-------|:---:|:---:|:---:|:---:|
68
+ | DeepSeek-OCR | **#1** | **#1** | **#1** | **#1** |
69
+ | GLM-OCR | #2 | #3 | #2 | #4 |
70
+ | LightOnOCR-2 | #4 | #2 | #3 | #3 |
71
+ | dots.ocr | #3 | #4 | #4 | #2 |
72
+
73
+ **Conclusion:** DeepSeek-OCR is consistently #1 across datasets and eval methods; middle-pack rankings
74
+ are dataset-dependent. (NLS pilot omitted — 5 samples / 72B API judge, not comparable with the newer
75
+ methodology.)
76
+
77
+ ## Judge validation — `ocr-vllm-judge.py` (2026-02-15)
78
+
79
+ - **Test 1** (single judge, 1 sample, L4): `Qwen2.5-VL-7B`, 6/6 comparisons, 0 parse failures, ~3 min.
80
+ - **Test 2** (jury of 2, 3 samples, A100): `Qwen2.5-VL-7B` + `Qwen3-VL-8B`, 15/15, 0 failures; GPU cleanup
81
+ between models OK; majority-vote aggregation working (`[2/2]` unanimous, `[1/2]` split).
82
+ - **Test 3** (full, 50 samples, A100, Rubenstein): 300/300 comparisons, 0 parse failures; clear ELO
83
+ separation. First saved dataset: `davanstrien/ocr-bench-rubenstein-judge`.
84
+
85
+ Structured output via a compatibility shim: `StructuredOutputsParams` (vLLM ≥0.12) → `GuidedDecodingParams`
86
+ (older) → prompt-based fallback. Position bias mitigated by A/B randomisation. A100 recommended for jury mode.
87
+
88
+ ## Human eval — `ocr-human-eval.py` first validation (Rubenstein, 30 annotations)
89
+
90
+ Tested 3 judge configs against 30 human annotations. **Kimi K2.5 (170B) via Novita + the updated prompt**
91
+ is the only judge to match the human's #1 (DeepSeek-OCR); it's now the default in `ocr-jury-bench.py`.
92
+ Small models (7B/8B/30B) overrate LightOnOCR-2 (bias toward its commentary style); the updated prompt
93
+ (faithfulness > completeness > accuracy) helps, but model size is the bigger factor.