davanstrien HF Staff commited on
Commit
97fecee
·
verified ·
1 Parent(s): 3a5d7ed

Sync from GitHub via hub-sync

Browse files
Files changed (4) hide show
  1. CLAUDE.md +93 -0
  2. README.md +4 -2
  3. serving-unlimited-ocr.md +83 -11
  4. unlimited-ocr-vllm.py +544 -0
CLAUDE.md CHANGED
@@ -196,6 +196,99 @@ hf jobs uv run --flavor l4x1 \
196
 
197
  ## Other OCR Scripts
198
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
199
  ### Nanonets OCR (`nanonets-ocr.py`, `nanonets-ocr2.py`)
200
  ✅ Both versions working
201
 
 
196
 
197
  ## Other OCR Scripts
198
 
199
+ ### Unlimited-OCR (`unlimited-ocr-vllm.py`)
200
+ ✅ **Production Ready — single-image** (added + validated 2026-06-28)
201
+
202
+ Baidu's `baidu/Unlimited-OCR` (3.3B, MIT, DeepSeek-OCR / DeepSeek-OCR-2 descendant). Offline vLLM
203
+ batch recipe adapted from `deepseek-ocr-vllm.py` — `llm.generate()` with PIL images +
204
+ `NGramPerReqLogitsProcessor` (imported from `vllm.model_executor.models.unlimited_ocr`), prompt
205
+ `<image>document parsing.`, `SamplingParams(temperature=0, skip_special_tokens=False,
206
+ extra_args=dict(ngram_size=35, window_size=128))`, `limit_mm_per_prompt={"image": 1}`. One image per
207
+ row → one markdown. `--strip-grounding` drops `<|det|>`/`<|ref|>` tags (verified locally on real
208
+ output: removes boxes, keeps inner text + LaTeX).
209
+
210
+ **⚠️ Dedicated image, not the standard one.** The arch is NOT in any stable vLLM pip wheel — must run
211
+ on Baidu's `vllm/vllm-openai:unlimited-ocr` (CUDA 13.0; `:unlimited-ocr-cu129` on Hopper). So `vllm`
212
+ and `torch` are **omitted from the PEP 723 deps** and come from the image via `PYTHONPATH`. The image
213
+ uses the **standard** layout: `--python /usr/bin/python3 -e PYTHONPATH=/usr/local/lib/python3.12/dist-packages`
214
+ (vLLM `0.23.1rc1.dev541` lives there; probed 2026-06-28). The `unlimited_ocr` module re-exports
215
+ `deepseek_ocr.NGramPerReqLogitsProcessor`. Recipe: https://recipes.vllm.ai/baidu/Unlimited-OCR
216
+
217
+ **Smoke tests (2026-06-28):**
218
+ - **ufo-ColPali** (5, l4x1): 5/5 OK, 2.3 min, ~200 tok/s. Clean layout-grounded markdown — accurate
219
+ text, `<|det|>` bboxes (0–1000), multilingual (Spanish), LaTeX. Output `davanstrien/unlimited-ocr-smoke`.
220
+ - **encyclopaedia-britannica-1771** (8, l4x1, `--strip-grounding`): 6/6 content pages produced clean
221
+ text matching the dataset's own `ocr_text` length almost exactly (e.g. row 1: md 5811 vs ocr_text
222
+ 5752), period-accurate 1771 OCR (long-ſ, archaic spelling). The 2 "empty" rows are genuinely blank
223
+ pages (ground-truth `ocr_text` 3–24 chars). Output `davanstrien/unlimited-ocr-britannica-smoke`.
224
+
225
+ **Multi-page: BOTH engines work on clean docs; robustness differs on hard scans. (Corrected
226
+ 2026-06-29 — earlier "vLLM multi-page is broken" was an input-difficulty artifact.)**
227
+ - **Control test that overturned the first read:** ran the SAME clean synthetic 2-page doc through the
228
+ **vLLM server** that SGLang had aced. vLLM returned **`<PAGE>=2`, both pages, real text** (`Chapter
229
+ One The Harbor` + lines / `Chapter Two The Market` + lines), with minor body-OCR slips ("early oakh",
230
+ "Guile covered") — i.e. the model *misreading*, not the engine hallucinating. Worked with both 1×
231
+ and 2× `<image>` prompt forms + `vllm_xargs.window_size=1024`. So **vLLM multi-page works**.
232
+ - **What the earlier garbling actually was:** my first vLLM multi-page tests used **hard** inputs —
233
+ `unlimited-ocr-pdf-test` (blank + dense 1771 Britannica) and ufo newspaper clippings. On those, vLLM
234
+ multi-page degraded to hallucination (counting garbage "SIGILLUM. 17. 96…", `2017年1月1日` loops,
235
+ content in neither input). SGLang read the *same* hard ufo input as real content → **SGLang is more
236
+ robust on hard/degraded scans**, but neither engine is "broken."
237
+ - **Offline `LLM().generate()`** still needs one `<image>` per image (single placeholder → assertion);
238
+ offline multi-page was only tested on the hard Britannica PDF (garbled) — not re-tested on clean, so
239
+ the recipe stays single-image (multi-page belongs to serving).
240
+ - `images_config`/`image_mode` are **SGLang-only** params (vLLM ignores them); on vLLM use one
241
+ `<image>` per page + `window_size=1024` in `vllm_xargs`.
242
+ - **Upstream check (vllm-project/vllm#46564, "Support Unlimited OCR", merged 2026-06-28):** confirms
243
+ this. Multi-image IS implemented (crop/gundam auto-disabled → base mode; one `<image>` placeholder
244
+ per image). R-SWA needs the **FlexAttention** backend (auto on non-FA4 GPUs like L4) or FA4 on
245
+ H20/H100 — our run correctly used FlexAttention. BUT: the PR's only benchmark is **single-page
246
+ OmniDocBench** (FA4 92.12 / Flex 92.38); there is **no multi-page test, no `examples/`, no canonical
247
+ multi-page prompt** in the merged code. PR-author comment: multi-page needs **V1 + NGramPerReq-
248
+ LogitsProcessor** (V2 lacks custom logits processors), and their "14-page PDF merge" smoke test only
249
+ confirmed "**R-SWA itself works**" (mechanism runs on long seqs) — *not* OCR quality. So nobody
250
+ upstream has shown multi-page OCR quality; the tweet's "40+ pages, low edit distance" is ahead of the
251
+ merged evidence. (Our own clean-doc control test later showed vLLM multi-page DOES read correctly —
252
+ see the corrected block above; the earlier garbling was hard-input degradation, not an engine break.)
253
+ - **Conclusion:** the **batch recipe stays single-image** (offline multi-page is finicky and untested
254
+ on clean; `--pdf-column` removed). For multi-page, **serve** the model — both engines read clean
255
+ multi-page docs; route hard/degraded scans to **SGLang** (more robust; authors' `images_config` path;
256
+ serving-unlimited-ocr.md Option B + §3). Image probed: `vllm 0.23.1rc1.dev541` (docs say "0.25.0+").
257
+ - **SGLang multi-page — ✅ FIXED + validated working (2026-06-28).** Multi-page is the model's headline
258
+ feature and **SGLang delivers it robustly** (vLLM multi-page also works on clean docs but hallucinated
259
+ on hard scans — see corrected block above). Two pins were needed:
260
+ 1. **Image `lmsysorg/sglang:v0.5.10.post1`** (not `:latest`). `:latest` drifted to sglang 0.5.14 /
261
+ torch 2.11 / cu130; the wheel (`dev11416`) needs torch 2.9.1 / cuda-python 12.9 / flashinfer 0.6.7 /
262
+ xgrammar 0.1.32 / transformers 5.3.0. Found v0.5.10.post1 by bisecting sglang release pyproject
263
+ pins — the **last** release before the torch-2.11 bump; matches the wheel exactly.
264
+ 2. **`a100-large` + `--attention-backend flashinfer`** (not `h200`/`fa3`). `fa3` needs Hopper, but
265
+ HF's `h200` nodes **fail GPU init with `CUDA error 802: system not yet initialized`, 3/3** (infra /
266
+ Fabric-Manager — *all* working jobs this session were l4x1/a100, never h200). The version pin alone
267
+ did NOT fix 802; the 802 is purely the h200 node. a100+flashinfer dodges it.
268
+ - **Result:** server up; clean 2-page synthetic doc → **both pages read verbatim, `<PAGE>`-separated**
269
+ (`Chapter One: The Harbor…` / `Chapter Two: The Market…`); ufo pages → **real content**
270
+ (`OUT OF THIS WORLD / UFO FlyBys…`), *not* vLLM's hallucinated garbage. Client: OpenAI API,
271
+ `images_config:{image_mode:base}` + `Multi page parsing.`; no per-request NGram processor (so harder
272
+ scans show minor page-merge/OCR slips — fa3 + the custom logit processor would tighten quality; the
273
+ mechanism works). Working command lives in `serving-unlimited-ocr.md` Option B; switch back to
274
+ `fa3`/`h200` for exact R-SWA once the h200 802 infra issue clears.
275
+
276
+ **Example usage:**
277
+ ```bash
278
+ hf jobs uv run --flavor l4x1 -s HF_TOKEN \
279
+ --image vllm/vllm-openai:unlimited-ocr --python /usr/bin/python3 \
280
+ -e PYTHONPATH=/usr/local/lib/python3.12/dist-packages \
281
+ ./ocr/unlimited-ocr-vllm.py davanstrien/ufo-ColPali output-dataset --max-samples 10 --shuffle
282
+ ```
283
+
284
+ **Deferred follow-up (captured, not built):** a *multi-page batch* recipe that drives the **SGLang
285
+ server** in-job (server lifecycle + `ThreadPoolExecutor` over multi-page docs, like Baidu's `infer.py`,
286
+ → Hub) — the only way to get robust multi-page at corpus scale, since SGLang offline-Engine is
287
+ non-viable (server-only, custom-logit-processor/R-SWA are server-side, `fa3` Hopper-only) and vLLM
288
+ offline needs one `<image>` per page and degrades on hard scans. Gate: a real corpus-scale multi-page
289
+ need **+** the h200/`fa3` infra fix (for exact R-SWA quality). Single-image vLLM (this recipe) stays
290
+ the batch default.
291
+
292
  ### Nanonets OCR (`nanonets-ocr.py`, `nanonets-ocr2.py`)
293
  ✅ Both versions working
294
 
README.md CHANGED
@@ -33,7 +33,7 @@ This will:
33
 
34
  ## Serve a model as a live endpoint
35
 
36
- The recipes here run as batch jobs. To call a model interactively, from an agent, or with concurrent ad-hoc requests, you can instead run it as a temporary endpoint: [HF Jobs serving](https://huggingface.co/docs/hub/jobs-serving) exposes a port on a GPU Job, giving an OpenAI-compatible endpoint that runs until the job is cancelled or its `--timeout` is reached. See [serving-unlimited-ocr.md](serving-unlimited-ocr.md) for a worked example serving Baidu's [Unlimited-OCR](https://huggingface.co/baidu/Unlimited-OCR) with SGLang.
37
 
38
  ## Models at a glance
39
 
@@ -69,6 +69,7 @@ _Sorted by model size:_
69
  | `deepseek-ocr-vllm.py` | [DeepSeek-OCR](https://huggingface.co/deepseek-ai/DeepSeek-OCR) | 4B | vLLM | 5 resolution + 5 prompt modes |
70
  | `deepseek-ocr.py` | [DeepSeek-OCR](https://huggingface.co/deepseek-ai/DeepSeek-OCR) | 4B | Transformers | Same model, Transformers backend |
71
  | `deepseek-ocr2-vllm.py` | [DeepSeek-OCR-2](https://huggingface.co/deepseek-ai/DeepSeek-OCR-2) | 3B | vLLM | Newer; needs nightly vLLM **+ the `vllm/vllm-openai` image** ([why](#if-a-vllm-script-crashes-at-startup-the-nvcc--nvrtc-error)) |
 
72
  | `nuextract3.py` | [NuExtract3](https://huggingface.co/numind/NuExtract3) | 4B | vLLM | Markdown OCR **+ schema-guided JSON extraction** (template/Pydantic). Needs `vllm/vllm-openai` image |
73
  | `qianfan-ocr.py` | [Qianfan-OCR](https://huggingface.co/baidu/Qianfan-OCR) | 4.7B | vLLM | #1 OmniDocBench v1.5 (93.12), Layout-as-Thought, 192 languages |
74
  | `olmocr2-vllm.py` | [olmOCR-2-7B](https://huggingface.co/allenai/olmOCR-2-7B-1025-FP8) | 7B | vLLM | 82.4% olmOCR-Bench |
@@ -213,10 +214,11 @@ Beyond the shared flags, some models add their own. Run `--help` on any script f
213
  | `dots-ocr.py` | `--prompt-mode ocr\|layout-all\|layout-only` |
214
  | `dots-mocr.py` | `--prompt-mode` (8: ocr, layout-all, layout-only, web-parsing, scene-spotting, grounding-ocr, svg, general); SVG: `--model rednote-hilab/dots.mocr-svg --prompt-mode svg` |
215
  | `qianfan-ocr.py` | `--prompt-mode ocr\|table\|formula\|chart\|scene\|kie`, `--think` (Layout-as-Thought); `kie` needs `--custom-prompt` |
 
216
  | `numarkdown-ocr.py` | `--include-thinking` (store the reasoning trace) |
217
  | `nuextract3.py` | `--template` / `--schema` / `--enable-thinking` — see the NuExtract3 section above |
218
 
219
- **Image-mode models** — `abot-ocr.py` and `nuextract3.py` (Qwen3.5 architecture) need the `vllm/vllm-openai` image because the default uv-script image lacks `nvcc`. Add `--image vllm/vllm-openai:latest --python /usr/bin/python3 -e PYTHONPATH=/usr/local/lib/python3.12/dist-packages` (see the NuExtract3 example above for the full command).
220
 
221
  ## Output & features
222
 
 
33
 
34
  ## Serve a model as a live endpoint
35
 
36
+ The recipes here run as batch jobs. To call a model interactively, from an agent, or with concurrent ad-hoc requests, you can instead run it as a temporary endpoint: [HF Jobs serving](https://huggingface.co/docs/hub/jobs-serving) exposes a port on a GPU Job, giving an OpenAI-compatible endpoint that runs until the job is cancelled or its `--timeout` is reached. See [serving-unlimited-ocr.md](serving-unlimited-ocr.md) for a worked example serving Baidu's [Unlimited-OCR](https://huggingface.co/baidu/Unlimited-OCR) with vLLM (official image) or SGLang. To OCR a whole corpus of single-page images instead, the batch recipe `unlimited-ocr-vllm.py` is the better fit (it's single-image only). **Multi-page** documents need a server: both vLLM and SGLang read clean multi-page docs, but **SGLang is the more robust** — on hard/degraded scans vLLM multi-page hallucinated in our tests while SGLang held up.
37
 
38
  ## Models at a glance
39
 
 
69
  | `deepseek-ocr-vllm.py` | [DeepSeek-OCR](https://huggingface.co/deepseek-ai/DeepSeek-OCR) | 4B | vLLM | 5 resolution + 5 prompt modes |
70
  | `deepseek-ocr.py` | [DeepSeek-OCR](https://huggingface.co/deepseek-ai/DeepSeek-OCR) | 4B | Transformers | Same model, Transformers backend |
71
  | `deepseek-ocr2-vllm.py` | [DeepSeek-OCR-2](https://huggingface.co/deepseek-ai/DeepSeek-OCR-2) | 3B | vLLM | Newer; needs nightly vLLM **+ the `vllm/vllm-openai` image** ([why](#if-a-vllm-script-crashes-at-startup-the-nvcc--nvrtc-error)) |
72
+ | `unlimited-ocr-vllm.py` | [Unlimited-OCR](https://huggingface.co/baidu/Unlimited-OCR) | 3.3B | vLLM | DeepSeek-OCR-based; layout-grounded markdown (`--strip-grounding` for clean text). Single-image batch — needs Baidu's **dedicated `vllm/vllm-openai:unlimited-ocr` image** (`-cu129` on Hopper). Multi-page "long-horizon" parsing → serve it ([doc](serving-unlimited-ocr.md)); both engines do clean docs, **SGLang more robust** on hard scans. MIT |
73
  | `nuextract3.py` | [NuExtract3](https://huggingface.co/numind/NuExtract3) | 4B | vLLM | Markdown OCR **+ schema-guided JSON extraction** (template/Pydantic). Needs `vllm/vllm-openai` image |
74
  | `qianfan-ocr.py` | [Qianfan-OCR](https://huggingface.co/baidu/Qianfan-OCR) | 4.7B | vLLM | #1 OmniDocBench v1.5 (93.12), Layout-as-Thought, 192 languages |
75
  | `olmocr2-vllm.py` | [olmOCR-2-7B](https://huggingface.co/allenai/olmOCR-2-7B-1025-FP8) | 7B | vLLM | 82.4% olmOCR-Bench |
 
214
  | `dots-ocr.py` | `--prompt-mode ocr\|layout-all\|layout-only` |
215
  | `dots-mocr.py` | `--prompt-mode` (8: ocr, layout-all, layout-only, web-parsing, scene-spotting, grounding-ocr, svg, general); SVG: `--model rednote-hilab/dots.mocr-svg --prompt-mode svg` |
216
  | `qianfan-ocr.py` | `--prompt-mode ocr\|table\|formula\|chart\|scene\|kie`, `--think` (Layout-as-Thought); `kie` needs `--custom-prompt` |
217
+ | `unlimited-ocr-vllm.py` | `--strip-grounding` (drop `<\|det\|>`/`<\|ref\|>` grounding tags); needs the **`vllm/vllm-openai:unlimited-ocr`** image |
218
  | `numarkdown-ocr.py` | `--include-thinking` (store the reasoning trace) |
219
  | `nuextract3.py` | `--template` / `--schema` / `--enable-thinking` — see the NuExtract3 section above |
220
 
221
+ **Image-mode models** — `abot-ocr.py` and `nuextract3.py` (Qwen3.5 architecture) need the `vllm/vllm-openai` image because the default uv-script image lacks `nvcc`. Add `--image vllm/vllm-openai:latest --python /usr/bin/python3 -e PYTHONPATH=/usr/local/lib/python3.12/dist-packages` (see the NuExtract3 example above for the full command). `unlimited-ocr-vllm.py` is a special case — its architecture isn't in any stable vLLM wheel, so it needs Baidu's **dedicated** `vllm/vllm-openai:unlimited-ocr` image (tag `:unlimited-ocr-cu129` on Hopper), e.g. `--image vllm/vllm-openai:unlimited-ocr --python /usr/bin/python3 -e PYTHONPATH=/usr/local/lib/python3.12/dist-packages` (its docstring has the full command).
222
 
223
  ## Output & features
224
 
serving-unlimited-ocr.md CHANGED
@@ -7,19 +7,77 @@ port on a GPU Job, giving an OpenAI-compatible endpoint that runs until the job
7
  `--timeout` is reached.
8
 
9
  This is a worked example for [baidu/Unlimited-OCR](https://huggingface.co/baidu/Unlimited-OCR)
10
- (3B, MIT, based on DeepSeek-OCR; supports multi-page parsing in a single request). The model ships
11
- its own SGLang build, so it runs on the stock `lmsysorg/sglang` image with the 12 MB wheel
12
- installed at startup; no custom image is required.
 
 
 
 
 
 
 
 
 
 
 
 
13
 
14
  ## 1. Start the server
15
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16
  ```bash
17
- hf jobs run --detach --expose 10000 --flavor h200 -s HF_TOKEN --timeout 30m \
18
- lmsysorg/sglang:latest -- \
19
  bash -lc 'pip install --no-deps https://github.com/baidu/Unlimited-OCR/raw/main/wheel/sglang-0.0.0.dev11416+g92e8bb79e-py3-none-any.whl \
20
  && pip install -q kernels==0.11.7 \
21
  && python -m sglang.launch_server --model baidu/Unlimited-OCR --served-model-name Unlimited-OCR \
22
- --attention-backend fa3 --page-size 1 --mem-fraction-static 0.8 --context-length 32768 \
23
  --enable-custom-logit-processor --disable-overlap-schedule --skip-server-warmup \
24
  --host 0.0.0.0 --port 10000'
25
  ```
@@ -27,10 +85,16 @@ hf jobs run --detach --expose 10000 --flavor h200 -s HF_TOKEN --timeout 30m \
27
  Notes:
28
  - `--` before `bash` is required, or the CLI parses `-lc` as its own flags.
29
  - `--timeout` stops the endpoint (and billing) at the deadline; `hf jobs cancel <id>` stops it earlier.
30
- - `fa3` requires a Hopper GPU (e.g. `h200`). The model is small, so the attention backend, not GPU
31
- memory, determines the flavor. Run `hf jobs hardware` for available flavors.
32
- - Follow startup with `hf jobs logs -f <id>`; the server is ready at `Application startup complete`
33
- (about 3 minutes from a cold start).
 
 
 
 
 
 
34
 
35
  ## 2. Call it (OpenAI client; HF token as the API key)
36
 
@@ -59,7 +123,15 @@ Output is layout-grounded markdown: each block is tagged `<|det|>type [x1,y1,x2,
59
  with coordinates normalized to 0–1000. Remove the tags for plain text
60
  (`re.sub(r'<\|det\|>.*?<\|/det\|>', '', text)`) or keep them for structure.
61
 
62
- ## 3. Multi-page / PDF
 
 
 
 
 
 
 
 
63
 
64
  Send multiple page images in one request with the `Multi page parsing.` prompt and `image_mode="base"`:
65
 
 
7
  `--timeout` is reached.
8
 
9
  This is a worked example for [baidu/Unlimited-OCR](https://huggingface.co/baidu/Unlimited-OCR)
10
+ (3B, MIT, based on DeepSeek-OCR; supports multi-page parsing in a single request). Two server
11
+ options below: **vLLM** on Baidu's official image (the newer official path, OpenAI-compatible), or
12
+ **SGLang** on the stock image with the model's own wheel. Either gives an OpenAI-compatible endpoint.
13
+
14
+ > **Single-image vs multi-page — pick the engine by task:**
15
+ > - **Single-page** OCR (one image → markdown): both engines work. For a whole corpus, the batch
16
+ > recipe [`unlimited-ocr-vllm.py`](unlimited-ocr-vllm.py) (offline vLLM, resumable, no network) is
17
+ > the better fit than a client loop; for interactive/agent use, serve with **vLLM (Option A)**.
18
+ > - **Multi-page / long-horizon** parsing (the model's headline feature): **both engines do it**
19
+ > (validated 2026-06-28 — a clean 2-page doc read back both pages, `<PAGE>`-separated, on *both* vLLM
20
+ > and SGLang). The difference is **robustness on hard inputs**: on degraded historical scans / newspaper
21
+ > clippings, vLLM multi-page degraded to hallucination in our tests while **SGLang (Option B)** read
22
+ > real content — so SGLang is the **more robust** multi-page path (it's also the authors' documented
23
+ > one, via `images_config`). Use vLLM multi-page for clean docs; reach for SGLang for hard scans.
24
+ > (vLLM's upstream PR [#46564](https://github.com/vllm-project/vllm/pull/46564) benchmarks single-page only.)
25
 
26
  ## 1. Start the server
27
 
28
+ ### Option A — vLLM (official image)
29
+
30
+ vLLM support landed upstream; Baidu ships a dedicated image (the architecture isn't in a stable pip
31
+ wheel yet). Use the default `:unlimited-ocr` tag on L4/A100, or `:unlimited-ocr-cu129` on Hopper.
32
+ Runs on `l4x1`, no fa3/Hopper requirement. **Single-image is validated**; **multi-page also works on
33
+ clean docs** (both pages, `<PAGE>`-separated) but degraded to hallucination on hard scans in our tests
34
+ — for hard/degraded inputs prefer Option B (SGLang). For multi-page on vLLM, the request takes one
35
+ `<image>` per page in the text and `window_size=1024` in `vllm_xargs` (it has no `images_config`).
36
+
37
+ ```bash
38
+ hf jobs run --detach --expose 8000 --flavor l4x1 -s HF_TOKEN --timeout 30m \
39
+ vllm/vllm-openai:unlimited-ocr -- \
40
+ vllm serve baidu/Unlimited-OCR --served-model-name Unlimited-OCR \
41
+ --trust-remote-code --max-model-len 32768 --host 0.0.0.0 --port 8000 \
42
+ --logits_processors vllm.model_executor.models.unlimited_ocr:NGramPerReqLogitsProcessor \
43
+ --no-enable-prefix-caching --mm-processor-cache-gb 0
44
+ ```
45
+
46
+ Per-request, vLLM takes the no-repeat n-gram knobs via `vllm_xargs` and needs `skip_special_tokens`
47
+ off (it has no `images_config` — that's an SGLang param):
48
+
49
+ ```python
50
+ r = client.chat.completions.create(
51
+ model="Unlimited-OCR",
52
+ messages=[{"role": "user", "content": [
53
+ {"type": "text", "text": "<image>document parsing."}, # literal <image> prefix is required
54
+ {"type": "image_url", "image_url": {"url": f"data:image/jpeg;base64,{img}"}},
55
+ ]}],
56
+ temperature=0,
57
+ extra_body={"skip_special_tokens": False, "vllm_xargs": {"ngram_size": 35, "window_size": 128}},
58
+ )
59
+ ```
60
+
61
+ ### Option B — SGLang (model's own build) · supports multi-page
62
+
63
+ The model also ships its own SGLang build, installed at startup from a 12 MB wheel. **This is the
64
+ more robust path for multi-page / long-horizon parsing** (§3) — the model authors' documented route
65
+ (`images_config`), and the one that held up on hard scans where vLLM multi-page hallucinated. Two
66
+ pins matter (both learned the hard way, 2026-06-28):
67
+ - **Pin the image to `lmsysorg/sglang:v0.5.10.post1`** — *not* `:latest`. `:latest` drifted to torch
68
+ 2.11 / cu130, incompatible with the wheel (torch 2.9.1 / cuda-python 12.9); v0.5.10.post1 is the last
69
+ release that matches the wheel exactly.
70
+ - **Run on `a100-large` with `--attention-backend flashinfer`, not `h200`/`fa3`.** `fa3` needs a Hopper
71
+ GPU, but HF's `h200` nodes currently fail GPU init with `CUDA error 802: system not yet initialized`
72
+ (3/3 attempts) — an infra issue, not the model. `a100` + `flashinfer` sidesteps it and works.
73
+
74
  ```bash
75
+ hf jobs run --detach --expose 10000 --flavor a100-large -s HF_TOKEN --timeout 30m \
76
+ lmsysorg/sglang:v0.5.10.post1 -- \
77
  bash -lc 'pip install --no-deps https://github.com/baidu/Unlimited-OCR/raw/main/wheel/sglang-0.0.0.dev11416+g92e8bb79e-py3-none-any.whl \
78
  && pip install -q kernels==0.11.7 \
79
  && python -m sglang.launch_server --model baidu/Unlimited-OCR --served-model-name Unlimited-OCR \
80
+ --attention-backend flashinfer --page-size 1 --mem-fraction-static 0.85 --context-length 32768 \
81
  --enable-custom-logit-processor --disable-overlap-schedule --skip-server-warmup \
82
  --host 0.0.0.0 --port 10000'
83
  ```
 
85
  Notes:
86
  - `--` before `bash` is required, or the CLI parses `-lc` as its own flags.
87
  - `--timeout` stops the endpoint (and billing) at the deadline; `hf jobs cancel <id>` stops it earlier.
88
+ - **Validated 2026-06-28** on `a100-large`: server came up, single-image and multi-page both read
89
+ correctly (a clean 2-page doc returned both pages verbatim, `<PAGE>`-separated). The model card's
90
+ "official" backend is `fa3` on Hopper for exact R-SWA switch back to `--attention-backend fa3
91
+ --flavor h200` once the h200 `802` infra issue clears; `flashinfer` on `a100` is the working fallback.
92
+ - Follow startup with `hf jobs logs -f <id>`; ready at `The server is fired up` / `Application startup
93
+ complete` (a few minutes cold; the wheel + model download dominate).
94
+
95
+ The client examples below use the **SGLang** request format (`images_config` in `extra_body`,
96
+ port 10000). The single-image call (§2) also works on the vLLM server — just use the Option A
97
+ `extra_body` and your exposed port. **Multi-page (§3) is SGLang-only.**
98
 
99
  ## 2. Call it (OpenAI client; HF token as the API key)
100
 
 
123
  with coordinates normalized to 0–1000. Remove the tags for plain text
124
  (`re.sub(r'<\|det\|>.*?<\|/det\|>', '', text)`) or keep them for structure.
125
 
126
+ ## 3. Multi-page / PDF (SGLang shown; vLLM also works on clean docs)
127
+
128
+ > ✅ This **SGLang** flow (Option B) is **validated working 2026-06-28** (a clean 2-page doc read back
129
+ > both pages verbatim, `<PAGE>`-separated) and follows the model card's multi-page example. The
130
+ > `images_config`/`image_mode` param is SGLang-specific — **vLLM ignores it**; on vLLM, do multi-page
131
+ > with one `<image>` per page in the text + `window_size=1024` in `vllm_xargs` (no `images_config`).
132
+ > Both engines read clean multi-page docs; **SGLang was the more robust on hard/degraded scans**, where
133
+ > vLLM multi-page hallucinated in our tests. (vLLM's upstream
134
+ > [PR #46564](https://github.com/vllm-project/vllm/pull/46564) benchmarks single-page only.)
135
 
136
  Send multiple page images in one request with the `Multi page parsing.` prompt and `image_mode="base"`:
137
 
unlimited-ocr-vllm.py ADDED
@@ -0,0 +1,544 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # /// script
2
+ # requires-python = ">=3.11"
3
+ # dependencies = [
4
+ # "datasets>=4.0.0",
5
+ # "huggingface-hub",
6
+ # "pillow",
7
+ # "tqdm",
8
+ # "toolz",
9
+ # ]
10
+ # ///
11
+
12
+ """
13
+ Convert document images to markdown using Baidu Unlimited-OCR with vLLM.
14
+
15
+ Unlimited-OCR (baidu/Unlimited-OCR, 3.3B, MIT) is a DeepSeek-OCR / DeepSeek-OCR-2 descendant. This
16
+ recipe runs it as an offline vLLM batch job (dataset in -> markdown out), mirroring the proven
17
+ deepseek-ocr-vllm.py pattern: llm.generate() with PIL images and the model's
18
+ NGramPerReqLogitsProcessor to stop coordinate-token loops on long documents.
19
+
20
+ One image per row -> one markdown. Output is layout-grounded markdown: text spans are tagged
21
+ <|ref|>...<|/ref|> with <|det|>...<|/det|> coordinate boxes (coords normalized 0-1000); tables come
22
+ back as HTML and equations as LaTeX. Pass --strip-grounding to drop the tags and keep clean text;
23
+ add --grounding-column to keep the raw grounded output (with bboxes) in a second column too.
24
+
25
+ Multi-page / "long-horizon" parsing (the model's headline feature) is not in this single-image batch
26
+ recipe — for multi-page, serve the model and send all pages in one request (see serving-unlimited-ocr.md).
27
+ Multi-page *does* work via vLLM serving: on a clean 2-page doc it returned both pages, <PAGE>-separated.
28
+ But on hard/degraded scans (dense historical pages, newspaper clippings) vLLM multi-page degraded to
29
+ hallucination in our tests, where the model's own SGLang build held up better — so SGLang is the more
30
+ robust multi-page path. (vLLM's upstream PR, vllm-project/vllm#46564, benchmarks single-page only.)
31
+
32
+ IMPORTANT: Unlimited-OCR's architecture is not in a stable vLLM pip wheel, so this script MUST run on
33
+ Baidu's dedicated vLLM image (vllm and torch come from the image, not the PEP 723 deps):
34
+
35
+ hf jobs uv run --flavor l4x1 -s HF_TOKEN \\
36
+ --image vllm/vllm-openai:unlimited-ocr --python /usr/bin/python3 \\
37
+ -e PYTHONPATH=/usr/local/lib/python3.12/dist-packages \\
38
+ https://huggingface.co/datasets/uv-scripts/ocr/raw/main/unlimited-ocr-vllm.py \\
39
+ your-input-dataset your-output-dataset --max-samples 10
40
+
41
+ Use the vllm/vllm-openai:unlimited-ocr-cu129 tag on Hopper GPUs (h100/h200).
42
+
43
+ Model card: https://huggingface.co/baidu/Unlimited-OCR
44
+ vLLM recipe: https://recipes.vllm.ai/baidu/Unlimited-OCR
45
+ """
46
+
47
+ import argparse
48
+ import io
49
+ import json
50
+ import logging
51
+ import os
52
+ import re
53
+ import sys
54
+ import time
55
+ from datetime import datetime
56
+ from typing import Any, Dict, List, Optional, Union
57
+
58
+ import torch
59
+ from datasets import load_dataset
60
+ from huggingface_hub import DatasetCard, login
61
+ from PIL import Image
62
+ from toolz import partition_all
63
+ from tqdm.auto import tqdm
64
+
65
+ # Disable vLLM's FlashInfer sampler: it JIT-compiles a CUDA kernel needing nvcc. Greedy OCR doesn't
66
+ # use it; on the dedicated vllm/vllm-openai image it's a harmless no-op.
67
+ os.environ.setdefault("VLLM_USE_FLASHINFER_SAMPLER", "0")
68
+ from vllm import LLM, SamplingParams
69
+ from vllm.model_executor.models.unlimited_ocr import NGramPerReqLogitsProcessor
70
+
71
+ logging.basicConfig(level=logging.INFO)
72
+ logger = logging.getLogger(__name__)
73
+
74
+ MODEL = "baidu/Unlimited-OCR"
75
+
76
+ # Prompt and no-repeat-ngram knobs straight from the model card / vLLM recipe (single image).
77
+ PROMPT = "<image>document parsing."
78
+ NGRAM_SIZE = 35
79
+ WINDOW_SIZE = 128
80
+
81
+ # Strip the model's grounding markup to recover clean text:
82
+ # drop the <|det|>...<|/det|> coordinate boxes, then unwrap the <|ref|>...<|/ref|> spans.
83
+ _DET_RE = re.compile(r"<\|det\|>.*?<\|/det\|>", re.DOTALL)
84
+ _REF_RE = re.compile(r"<\|/?ref\|>")
85
+
86
+
87
+ def strip_grounding(text: str) -> str:
88
+ """Remove <|det|> boxes and <|ref|> wrappers, keeping the inner text."""
89
+ text = _DET_RE.sub("", text)
90
+ text = _REF_RE.sub("", text)
91
+ # collapse the blank lines left behind by removed boxes
92
+ return re.sub(r"\n{3,}", "\n\n", text).strip()
93
+
94
+
95
+ def check_cuda_availability():
96
+ """Check if CUDA is available and exit if not."""
97
+ if not torch.cuda.is_available():
98
+ logger.error("CUDA is not available. This script requires a GPU.")
99
+ sys.exit(1)
100
+ logger.info(f"CUDA is available. GPU: {torch.cuda.get_device_name(0)}")
101
+
102
+
103
+ def to_pil(image: Union[Image.Image, Dict[str, Any], str]) -> Image.Image:
104
+ """Convert various dataset image cell formats to an RGB PIL image."""
105
+ if isinstance(image, Image.Image):
106
+ return image.convert("RGB")
107
+ if isinstance(image, dict) and "bytes" in image:
108
+ return Image.open(io.BytesIO(image["bytes"])).convert("RGB")
109
+ if isinstance(image, str):
110
+ return Image.open(image).convert("RGB")
111
+ raise ValueError(f"Unsupported image type: {type(image)}")
112
+
113
+
114
+ def create_dataset_card(
115
+ source_dataset: str,
116
+ output_dataset: str,
117
+ model: str,
118
+ num_samples: int,
119
+ processing_time: str,
120
+ output_column: str,
121
+ strip_grounding_enabled: bool,
122
+ split: str,
123
+ ) -> str:
124
+ """Create a dataset card documenting the OCR run."""
125
+ if strip_grounding_enabled:
126
+ grounding = "Grounding markup was stripped (`--strip-grounding`); the column holds clean text."
127
+ else:
128
+ grounding = (
129
+ "The column holds the model's raw layout-grounded markdown: text spans tagged "
130
+ "`<|ref|>...<|/ref|>` with `<|det|>...<|/det|>` coordinate boxes (coords 0-1000). "
131
+ "Strip them with "
132
+ "`re.sub(r'<\\|det\\|>.*?<\\|/det\\|>', '', t)` then `re.sub(r'<\\|/?ref\\|>', '', t)`."
133
+ )
134
+ return f"""---
135
+ tags:
136
+ - ocr
137
+ - document-processing
138
+ - unlimited-ocr
139
+ - baidu
140
+ - markdown
141
+ - uv-script
142
+ - generated
143
+ ---
144
+
145
+ # Document OCR using Unlimited-OCR
146
+
147
+ This dataset contains OCR results for [{source_dataset}](https://huggingface.co/datasets/{source_dataset})
148
+ produced by [{model}](https://huggingface.co/{model}) with vLLM.
149
+
150
+ ## Processing Details
151
+
152
+ - **Source Dataset**: [{source_dataset}](https://huggingface.co/datasets/{source_dataset})
153
+ - **Model**: [{model}](https://huggingface.co/{model})
154
+ - **Number of Samples**: {num_samples:,}
155
+ - **Processing Time**: {processing_time}
156
+ - **Processing Date**: {datetime.now().strftime("%Y-%m-%d %H:%M UTC")}
157
+ - **Output Column**: `{output_column}`
158
+ - **Split**: `{split}`
159
+
160
+ ## Output
161
+
162
+ {grounding}
163
+
164
+ Tables are returned as HTML and equations as LaTeX.
165
+
166
+ ## Usage
167
+
168
+ ```python
169
+ from datasets import load_dataset
170
+
171
+ ds = load_dataset("{output_dataset}", split="{split}")
172
+ print(ds[0]["{output_column}"])
173
+ ```
174
+
175
+ ## Reproduction
176
+
177
+ Generated with the [uv-scripts/ocr](https://huggingface.co/datasets/uv-scripts/ocr) Unlimited-OCR
178
+ vLLM recipe. Unlimited-OCR needs Baidu's dedicated vLLM image:
179
+
180
+ ```bash
181
+ hf jobs uv run --flavor l4x1 -s HF_TOKEN \\
182
+ --image vllm/vllm-openai:unlimited-ocr --python /usr/bin/python3 \\
183
+ -e PYTHONPATH=/usr/local/lib/python3.12/dist-packages \\
184
+ https://huggingface.co/datasets/uv-scripts/ocr/raw/main/unlimited-ocr-vllm.py \\
185
+ {source_dataset} <output-dataset>
186
+ ```
187
+
188
+ Generated with [UV Scripts](https://huggingface.co/uv-scripts)
189
+ """
190
+
191
+
192
+ def main(
193
+ input_dataset: str,
194
+ output_dataset: str,
195
+ model: str = MODEL,
196
+ image_column: str = "image",
197
+ output_column: str = "markdown",
198
+ grounding_column: Optional[str] = None,
199
+ batch_size: int = 8,
200
+ max_model_len: int = 32768,
201
+ max_tokens: int = 8192,
202
+ gpu_memory_utilization: float = 0.8,
203
+ strip_grounding_enabled: bool = False,
204
+ hf_token: Optional[str] = None,
205
+ split: str = "train",
206
+ max_samples: Optional[int] = None,
207
+ private: bool = False,
208
+ shuffle: bool = False,
209
+ seed: int = 42,
210
+ config: Optional[str] = None,
211
+ create_pr: bool = False,
212
+ verbose: bool = False,
213
+ ):
214
+ """Process images from an HF dataset through Unlimited-OCR with vLLM."""
215
+ if grounding_column and grounding_column == output_column:
216
+ raise ValueError("--grounding-column must differ from --output-column")
217
+ check_cuda_availability()
218
+ start_time = datetime.now()
219
+
220
+ HF_TOKEN = hf_token or os.environ.get("HF_TOKEN")
221
+ if HF_TOKEN:
222
+ login(token=HF_TOKEN)
223
+
224
+ logger.info(f"Loading dataset: {input_dataset}")
225
+ dataset = load_dataset(input_dataset, split=split)
226
+ if image_column not in dataset.column_names:
227
+ raise ValueError(
228
+ f"Column '{image_column}' not found. Available: {dataset.column_names}"
229
+ )
230
+
231
+ if shuffle:
232
+ logger.info(f"Shuffling dataset with seed {seed}")
233
+ dataset = dataset.shuffle(seed=seed)
234
+ if max_samples:
235
+ dataset = dataset.select(range(min(max_samples, len(dataset))))
236
+ logger.info(f"Limited to {len(dataset)} samples")
237
+
238
+ logger.info(f"Initializing vLLM with model: {model}")
239
+ logger.info("This may take a few minutes on first run...")
240
+
241
+ llm = LLM(
242
+ model=model,
243
+ trust_remote_code=True,
244
+ max_model_len=max_model_len,
245
+ gpu_memory_utilization=gpu_memory_utilization,
246
+ enable_prefix_caching=False,
247
+ mm_processor_cache_gb=0,
248
+ limit_mm_per_prompt={"image": 1},
249
+ logits_processors=[NGramPerReqLogitsProcessor],
250
+ )
251
+
252
+ sampling_params = SamplingParams(
253
+ temperature=0.0,
254
+ max_tokens=max_tokens,
255
+ skip_special_tokens=False,
256
+ extra_args=dict(ngram_size=NGRAM_SIZE, window_size=WINDOW_SIZE),
257
+ )
258
+
259
+ logger.info(f"Processing {len(dataset)} images in batches of {batch_size}")
260
+ all_outputs: List[str] = []
261
+ all_grounded: List[
262
+ str
263
+ ] = [] # raw grounded text, only when --grounding-column is set
264
+ for batch_indices in tqdm(
265
+ partition_all(batch_size, range(len(dataset))),
266
+ total=(len(dataset) + batch_size - 1) // batch_size,
267
+ desc="Unlimited-OCR",
268
+ ):
269
+ batch_indices = list(batch_indices)
270
+ try:
271
+ model_inputs = [
272
+ {
273
+ "prompt": PROMPT,
274
+ "multi_modal_data": {"image": to_pil(dataset[i][image_column])},
275
+ }
276
+ for i in batch_indices
277
+ ]
278
+ outputs = llm.generate(model_inputs, sampling_params)
279
+ for output in outputs:
280
+ raw = output.outputs[0].text.strip()
281
+ all_outputs.append(
282
+ strip_grounding(raw) if strip_grounding_enabled else raw
283
+ )
284
+ if grounding_column:
285
+ all_grounded.append(raw)
286
+ except Exception as e:
287
+ logger.error(f"Error processing batch: {e}")
288
+ all_outputs.extend(["[OCR FAILED]"] * len(batch_indices))
289
+ if grounding_column:
290
+ all_grounded.extend(["[OCR FAILED]"] * len(batch_indices))
291
+
292
+ processing_time_str = (
293
+ f"{(datetime.now() - start_time).total_seconds() / 60:.1f} min"
294
+ )
295
+
296
+ logger.info(f"Adding '{output_column}' column to dataset")
297
+ if output_column in dataset.column_names:
298
+ logger.warning(f"Column '{output_column}' already exists, replacing it")
299
+ dataset = dataset.remove_columns([output_column])
300
+ dataset = dataset.add_column(output_column, all_outputs)
301
+ if grounding_column:
302
+ logger.info(f"Adding '{grounding_column}' column (raw grounded output)")
303
+ if grounding_column in dataset.column_names:
304
+ logger.warning(f"Column '{grounding_column}' already exists, replacing it")
305
+ dataset = dataset.remove_columns([grounding_column])
306
+ dataset = dataset.add_column(grounding_column, all_grounded)
307
+
308
+ # inference_info: append-only log so several models can write into one dataset and be compared.
309
+ inference_entry = {
310
+ "model_id": model,
311
+ "model_name": "Unlimited-OCR",
312
+ "column_name": output_column,
313
+ "timestamp": datetime.now().isoformat(),
314
+ "batch_size": batch_size,
315
+ "max_tokens": max_tokens,
316
+ "max_model_len": max_model_len,
317
+ "gpu_memory_utilization": gpu_memory_utilization,
318
+ "strip_grounding": strip_grounding_enabled,
319
+ "grounding_column": grounding_column,
320
+ "script": "unlimited-ocr-vllm.py",
321
+ "script_url": "https://huggingface.co/datasets/uv-scripts/ocr/raw/main/unlimited-ocr-vllm.py",
322
+ }
323
+ if "inference_info" in dataset.column_names:
324
+ logger.info("Updating existing inference_info column")
325
+
326
+ def update_inference_info(example):
327
+ try:
328
+ existing = (
329
+ json.loads(example["inference_info"])
330
+ if example["inference_info"]
331
+ else []
332
+ )
333
+ except (json.JSONDecodeError, TypeError):
334
+ existing = []
335
+ existing.append(inference_entry)
336
+ return {"inference_info": json.dumps(existing)}
337
+
338
+ dataset = dataset.map(update_inference_info)
339
+ else:
340
+ logger.info("Creating new inference_info column")
341
+ dataset = dataset.add_column(
342
+ "inference_info", [json.dumps([inference_entry])] * len(dataset)
343
+ )
344
+
345
+ logger.info(f"Pushing to {output_dataset}")
346
+ max_retries = 3
347
+ for attempt in range(1, max_retries + 1):
348
+ try:
349
+ if attempt > 1:
350
+ logger.warning("Disabling XET (fallback to HTTP upload)")
351
+ os.environ["HF_HUB_DISABLE_XET"] = "1"
352
+ dataset.push_to_hub(
353
+ output_dataset,
354
+ private=private,
355
+ token=HF_TOKEN,
356
+ max_shard_size="500MB",
357
+ **({"config_name": config} if config else {}),
358
+ create_pr=create_pr,
359
+ commit_message=f"Add {model} OCR results ({len(dataset)} samples)"
360
+ + (f" [{config}]" if config else ""),
361
+ )
362
+ break
363
+ except Exception as e:
364
+ logger.error(f"Upload attempt {attempt}/{max_retries} failed: {e}")
365
+ if attempt < max_retries:
366
+ delay = 30 * (2 ** (attempt - 1))
367
+ logger.info(f"Retrying in {delay}s...")
368
+ time.sleep(delay)
369
+ else:
370
+ logger.error("All upload attempts failed. OCR results are lost.")
371
+ sys.exit(1)
372
+
373
+ logger.info("Creating dataset card...")
374
+ card = DatasetCard(
375
+ create_dataset_card(
376
+ source_dataset=input_dataset,
377
+ output_dataset=output_dataset,
378
+ model=model,
379
+ num_samples=len(dataset),
380
+ processing_time=processing_time_str,
381
+ output_column=output_column,
382
+ strip_grounding_enabled=strip_grounding_enabled,
383
+ split=split,
384
+ )
385
+ )
386
+ card.push_to_hub(output_dataset, token=HF_TOKEN)
387
+
388
+ logger.info("✅ OCR conversion complete!")
389
+ logger.info(f"Dataset: https://huggingface.co/datasets/{output_dataset}")
390
+ logger.info(f"Processing time: {processing_time_str}")
391
+
392
+ if verbose:
393
+ import importlib.metadata
394
+
395
+ logger.info("--- Resolved package versions ---")
396
+ for pkg in ["vllm", "transformers", "torch", "datasets", "pillow"]:
397
+ try:
398
+ logger.info(f" {pkg}=={importlib.metadata.version(pkg)}")
399
+ except importlib.metadata.PackageNotFoundError:
400
+ logger.info(f" {pkg}: not installed")
401
+ logger.info("--- End versions ---")
402
+
403
+
404
+ if __name__ == "__main__":
405
+ if len(sys.argv) == 1:
406
+ print("=" * 80)
407
+ print("Unlimited-OCR to Markdown Converter (vLLM)")
408
+ print("=" * 80)
409
+ print("\nBaidu Unlimited-OCR (3.3B, MIT) — one image per row -> markdown.")
410
+ print("\nMUST run on the dedicated image: vllm/vllm-openai:unlimited-ocr")
411
+ print("(use the -cu129 tag on Hopper GPUs).")
412
+ print("\nExample:")
413
+ print(" hf jobs uv run --flavor l4x1 -s HF_TOKEN \\")
414
+ print(
415
+ " --image vllm/vllm-openai:unlimited-ocr --python /usr/bin/python3 \\"
416
+ )
417
+ print(" -e PYTHONPATH=/usr/local/lib/python3.12/dist-packages \\")
418
+ print(" unlimited-ocr-vllm.py my-images my-markdown --max-samples 10")
419
+ print(
420
+ "\nMulti-page documents: serve the model instead (see serving-unlimited-ocr.md)."
421
+ )
422
+ print("\nFor full help, run with --help")
423
+ sys.exit(0)
424
+
425
+ parser = argparse.ArgumentParser(
426
+ description="OCR images to markdown using Unlimited-OCR (vLLM)",
427
+ formatter_class=argparse.RawDescriptionHelpFormatter,
428
+ epilog="""
429
+ Examples:
430
+ # Basic usage
431
+ uv run unlimited-ocr-vllm.py my-images ocr-results
432
+
433
+ # Clean text (strip grounding tags)
434
+ uv run unlimited-ocr-vllm.py my-images ocr-results --strip-grounding
435
+
436
+ # On HF Jobs (dedicated image required)
437
+ hf jobs uv run --flavor l4x1 -s HF_TOKEN \\
438
+ --image vllm/vllm-openai:unlimited-ocr --python /usr/bin/python3 \\
439
+ -e PYTHONPATH=/usr/local/lib/python3.12/dist-packages \\
440
+ https://huggingface.co/datasets/uv-scripts/ocr/raw/main/unlimited-ocr-vllm.py \\
441
+ my-dataset my-output --max-samples 10
442
+ """,
443
+ )
444
+ parser.add_argument("input_dataset", help="Input dataset ID from Hugging Face Hub")
445
+ parser.add_argument("output_dataset", help="Output dataset ID for Hugging Face Hub")
446
+ parser.add_argument(
447
+ "--model",
448
+ default=MODEL,
449
+ help=f"Model to use (default: {MODEL}). Override only for a same-architecture mirror.",
450
+ )
451
+ parser.add_argument(
452
+ "--image-column", default="image", help="Column with images (default: image)"
453
+ )
454
+ parser.add_argument(
455
+ "--output-column",
456
+ default="markdown",
457
+ help="Output column name (default: markdown)",
458
+ )
459
+ parser.add_argument(
460
+ "--strip-grounding",
461
+ action="store_true",
462
+ help="Drop <|det|>/<|ref|> grounding tags from the output column, keeping clean text",
463
+ )
464
+ parser.add_argument(
465
+ "--grounding-column",
466
+ help="Also store the RAW grounded output (boxes + tags) in this extra column "
467
+ "(pair with --strip-grounding to keep clean text AND the layout/bboxes)",
468
+ )
469
+ parser.add_argument(
470
+ "--batch-size", type=int, default=8, help="Images per batch (default: 8)"
471
+ )
472
+ parser.add_argument(
473
+ "--max-model-len",
474
+ type=int,
475
+ default=32768,
476
+ help="Max context length (default: 32768)",
477
+ )
478
+ parser.add_argument(
479
+ "--max-tokens",
480
+ type=int,
481
+ default=8192,
482
+ help="Max output tokens (default: 8192)",
483
+ )
484
+ parser.add_argument(
485
+ "--gpu-memory-utilization",
486
+ type=float,
487
+ default=0.8,
488
+ help="GPU memory fraction (default: 0.8)",
489
+ )
490
+ parser.add_argument("--hf-token", help="Hugging Face API token")
491
+ parser.add_argument(
492
+ "--split", default="train", help="Dataset split (default: train)"
493
+ )
494
+ parser.add_argument(
495
+ "--max-samples", type=int, help="Max samples to process (for testing)"
496
+ )
497
+ parser.add_argument(
498
+ "--private", action="store_true", help="Make output dataset private"
499
+ )
500
+ parser.add_argument(
501
+ "--shuffle", action="store_true", help="Shuffle before processing"
502
+ )
503
+ parser.add_argument(
504
+ "--seed", type=int, default=42, help="Shuffle seed (default: 42)"
505
+ )
506
+ parser.add_argument(
507
+ "--config",
508
+ help="Config/subset name when pushing (for benchmarking multiple models)",
509
+ )
510
+ parser.add_argument(
511
+ "--create-pr",
512
+ action="store_true",
513
+ help="Push as a PR instead of a direct commit",
514
+ )
515
+ parser.add_argument(
516
+ "--verbose",
517
+ action="store_true",
518
+ help="Log resolved package versions after the run",
519
+ )
520
+
521
+ args = parser.parse_args()
522
+
523
+ main(
524
+ input_dataset=args.input_dataset,
525
+ output_dataset=args.output_dataset,
526
+ model=args.model,
527
+ image_column=args.image_column,
528
+ output_column=args.output_column,
529
+ grounding_column=args.grounding_column,
530
+ batch_size=args.batch_size,
531
+ max_model_len=args.max_model_len,
532
+ max_tokens=args.max_tokens,
533
+ gpu_memory_utilization=args.gpu_memory_utilization,
534
+ strip_grounding_enabled=args.strip_grounding,
535
+ hf_token=args.hf_token,
536
+ split=args.split,
537
+ max_samples=args.max_samples,
538
+ private=args.private,
539
+ shuffle=args.shuffle,
540
+ seed=args.seed,
541
+ config=args.config,
542
+ create_pr=args.create_pr,
543
+ verbose=args.verbose,
544
+ )