Sync from GitHub via hub-sync
Browse filesFiles changed (4)
- CLAUDE.md+93
- README.md+4-2
- serving-unlimited-ocr.md+83-11
- unlimited-ocr-vllm.pyAdded+544
195 unmodified lines196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294195 unmodified lines
## Other OCR Scripts
### Unlimited-OCR (`unlimited-ocr-vllm.py`)✅ **Production Ready — single-image** (added + validated 2026-06-28)
Baidu's `baidu/Unlimited-OCR` (3.3B, MIT, DeepSeek-OCR / DeepSeek-OCR-2 descendant). Offline vLLMbatch recipe adapted from `deepseek-ocr-vllm.py` — `llm.generate()` with PIL images +`NGramPerReqLogitsProcessor` (imported from `vllm.model_executor.models.unlimited_ocr`), prompt`<image>document parsing.`, `SamplingParams(temperature=0, skip_special_tokens=False,extra_args=dict(ngram_size=35, window_size=128))`, `limit_mm_per_prompt={"image": 1}`. One image perrow → one markdown. `--strip-grounding` drops `<|det|>`/`<|ref|>` tags (verified locally on realoutput: removes boxes, keeps inner text + LaTeX).
**⚠️ Dedicated image, not the standard one.** The arch is NOT in any stable vLLM pip wheel — must runon Baidu's `vllm/vllm-openai:unlimited-ocr` (CUDA 13.0; `:unlimited-ocr-cu129` on Hopper). So `vllm`and `torch` are **omitted from the PEP 723 deps** and come from the image via `PYTHONPATH`. The imageuses the **standard** layout: `--python /usr/bin/python3 -e PYTHONPATH=/usr/local/lib/python3.12/dist-packages`(vLLM `0.23.1rc1.dev541` lives there; probed 2026-06-28). The `unlimited_ocr` module re-exports`deepseek_ocr.NGramPerReqLogitsProcessor`. Recipe: https://recipes.vllm.ai/baidu/Unlimited-OCR
**Smoke tests (2026-06-28):**- **ufo-ColPali** (5, l4x1): 5/5 OK, 2.3 min, ~200 tok/s. Clean layout-grounded markdown — accurate text, `<|det|>` bboxes (0–1000), multilingual (Spanish), LaTeX. Output `davanstrien/unlimited-ocr-smoke`.- **encyclopaedia-britannica-1771** (8, l4x1, `--strip-grounding`): 6/6 content pages produced clean text matching the dataset's own `ocr_text` length almost exactly (e.g. row 1: md 5811 vs ocr_text 5752), period-accurate 1771 OCR (long-ſ, archaic spelling). The 2 "empty" rows are genuinely blank pages (ground-truth `ocr_text` 3–24 chars). Output `davanstrien/unlimited-ocr-britannica-smoke`.
**Multi-page: BOTH engines work on clean docs; robustness differs on hard scans. (Corrected2026-06-29 — earlier "vLLM multi-page is broken" was an input-difficulty artifact.)**- **Control test that overturned the first read:** ran the SAME clean synthetic 2-page doc through the **vLLM server** that SGLang had aced. vLLM returned **`<PAGE>=2`, both pages, real text** (`Chapter One The Harbor` + lines / `Chapter Two The Market` + lines), with minor body-OCR slips ("early oakh", "Guile covered") — i.e. the model *misreading*, not the engine hallucinating. Worked with both 1× and 2× `<image>` prompt forms + `vllm_xargs.window_size=1024`. So **vLLM multi-page works**.- **What the earlier garbling actually was:** my first vLLM multi-page tests used **hard** inputs — `unlimited-ocr-pdf-test` (blank + dense 1771 Britannica) and ufo newspaper clippings. On those, vLLM multi-page degraded to hallucination (counting garbage "SIGILLUM. 17. 96…", `2017年1月1日` loops, content in neither input). SGLang read the *same* hard ufo input as real content → **SGLang is more robust on hard/degraded scans**, but neither engine is "broken."- **Offline `LLM().generate()`** still needs one `<image>` per image (single placeholder → assertion); offline multi-page was only tested on the hard Britannica PDF (garbled) — not re-tested on clean, so the recipe stays single-image (multi-page belongs to serving).- `images_config`/`image_mode` are **SGLang-only** params (vLLM ignores them); on vLLM use one `<image>` per page + `window_size=1024` in `vllm_xargs`.- **Upstream check (vllm-project/vllm#46564, "Support Unlimited OCR", merged 2026-06-28):** confirms this. Multi-image IS implemented (crop/gundam auto-disabled → base mode; one `<image>` placeholder per image). R-SWA needs the **FlexAttention** backend (auto on non-FA4 GPUs like L4) or FA4 on H20/H100 — our run correctly used FlexAttention. BUT: the PR's only benchmark is **single-page OmniDocBench** (FA4 92.12 / Flex 92.38); there is **no multi-page test, no `examples/`, no canonical multi-page prompt** in the merged code. PR-author comment: multi-page needs **V1 + NGramPerReq- LogitsProcessor** (V2 lacks custom logits processors), and their "14-page PDF merge" smoke test only confirmed "**R-SWA itself works**" (mechanism runs on long seqs) — *not* OCR quality. So nobody upstream has shown multi-page OCR quality; the tweet's "40+ pages, low edit distance" is ahead of the merged evidence. (Our own clean-doc control test later showed vLLM multi-page DOES read correctly — see the corrected block above; the earlier garbling was hard-input degradation, not an engine break.)- **Conclusion:** the **batch recipe stays single-image** (offline multi-page is finicky and untested on clean; `--pdf-column` removed). For multi-page, **serve** the model — both engines read clean multi-page docs; route hard/degraded scans to **SGLang** (more robust; authors' `images_config` path; serving-unlimited-ocr.md Option B + §3). Image probed: `vllm 0.23.1rc1.dev541` (docs say "0.25.0+").- **SGLang multi-page — ✅ FIXED + validated working (2026-06-28).** Multi-page is the model's headline feature and **SGLang delivers it robustly** (vLLM multi-page also works on clean docs but hallucinated on hard scans — see corrected block above). Two pins were needed: 1. **Image `lmsysorg/sglang:v0.5.10.post1`** (not `:latest`). `:latest` drifted to sglang 0.5.14 / torch 2.11 / cu130; the wheel (`dev11416`) needs torch 2.9.1 / cuda-python 12.9 / flashinfer 0.6.7 / xgrammar 0.1.32 / transformers 5.3.0. Found v0.5.10.post1 by bisecting sglang release pyproject pins — the **last** release before the torch-2.11 bump; matches the wheel exactly. 2. **`a100-large` + `--attention-backend flashinfer`** (not `h200`/`fa3`). `fa3` needs Hopper, but HF's `h200` nodes **fail GPU init with `CUDA error 802: system not yet initialized`, 3/3** (infra / Fabric-Manager — *all* working jobs this session were l4x1/a100, never h200). The version pin alone did NOT fix 802; the 802 is purely the h200 node. a100+flashinfer dodges it. - **Result:** server up; clean 2-page synthetic doc → **both pages read verbatim, `<PAGE>`-separated** (`Chapter One: The Harbor…` / `Chapter Two: The Market…`); ufo pages → **real content** (`OUT OF THIS WORLD / UFO FlyBys…`), *not* vLLM's hallucinated garbage. Client: OpenAI API, `images_config:{image_mode:base}` + `Multi page parsing.`; no per-request NGram processor (so harder scans show minor page-merge/OCR slips — fa3 + the custom logit processor would tighten quality; the mechanism works). Working command lives in `serving-unlimited-ocr.md` Option B; switch back to `fa3`/`h200` for exact R-SWA once the h200 802 infra issue clears.
**Example usage:**```bashhf jobs uv run --flavor l4x1 -s HF_TOKEN \ --image vllm/vllm-openai:unlimited-ocr --python /usr/bin/python3 \ -e PYTHONPATH=/usr/local/lib/python3.12/dist-packages \ ./ocr/unlimited-ocr-vllm.py davanstrien/ufo-ColPali output-dataset --max-samples 10 --shuffle```
**Deferred follow-up (captured, not built):** a *multi-page batch* recipe that drives the **SGLangserver** in-job (server lifecycle + `ThreadPoolExecutor` over multi-page docs, like Baidu's `infer.py`,→ Hub) — the only way to get robust multi-page at corpus scale, since SGLang offline-Engine isnon-viable (server-only, custom-logit-processor/R-SWA are server-side, `fa3` Hopper-only) and vLLMoffline needs one `<image>` per page and degrades on hard scans. Gate: a real corpus-scale multi-pageneed **+** the h200/`fa3` infra fix (for exact R-SWA quality). Single-image vLLM (this recipe) staysthe batch default.
### Nanonets OCR (`nanonets-ocr.py`, `nanonets-ocr2.py`)✅ Both versions working
32 unmodified lines333435363637383929 unmodified lines69707172737475138 unmodified lines21421521621721821922021922122222322432 unmodified lines
## Serve a model as a live endpoint
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.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.
## Models at a glance
29 unmodified lines| `deepseek-ocr-vllm.py` | [DeepSeek-OCR](https://huggingface.co/deepseek-ai/DeepSeek-OCR) | 4B | vLLM | 5 resolution + 5 prompt modes || `deepseek-ocr.py` | [DeepSeek-OCR](https://huggingface.co/deepseek-ai/DeepSeek-OCR) | 4B | Transformers | Same model, Transformers backend || `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)) || `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 || `nuextract3.py` | [NuExtract3](https://huggingface.co/numind/NuExtract3) | 4B | vLLM | Markdown OCR **+ schema-guided JSON extraction** (template/Pydantic). Needs `vllm/vllm-openai` image || `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 || `olmocr2-vllm.py` | [olmOCR-2-7B](https://huggingface.co/allenai/olmOCR-2-7B-1025-FP8) | 7B | vLLM | 82.4% olmOCR-Bench |138 unmodified lines| `dots-ocr.py` | `--prompt-mode ocr\|layout-all\|layout-only` || `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` || `qianfan-ocr.py` | `--prompt-mode ocr\|table\|formula\|chart\|scene\|kie`, `--think` (Layout-as-Thought); `kie` needs `--custom-prompt` || `unlimited-ocr-vllm.py` | `--strip-grounding` (drop `<\|det\|>`/`<\|ref\|>` grounding tags); needs the **`vllm/vllm-openai:unlimited-ocr`** image || `numarkdown-ocr.py` | `--include-thinking` (store the reasoning trace) || `nuextract3.py` | `--template` / `--schema` / `--enable-thinking` — see the NuExtract3 section above |
**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).**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).
## Output & features
6 unmodified lines78910111210111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273741718757677787922808182831 unmodified line8586873031323388899091929394959697989910022 unmodified lines123124125621261271281291301311321331341351361376 unmodified lines`--timeout` is reached.
This is a worked example for [baidu/Unlimited-OCR](https://huggingface.co/baidu/Unlimited-OCR)(3B, MIT, based on DeepSeek-OCR; supports multi-page parsing in a single request). The model shipsits own SGLang build, so it runs on the stock `lmsysorg/sglang` image with the 12 MB wheelinstalled at startup; no custom image is required.(3B, MIT, based on DeepSeek-OCR; supports multi-page parsing in a single request). Two serveroptions below: **vLLM** on Baidu's official image (the newer official path, OpenAI-compatible), or**SGLang** on the stock image with the model's own wheel. Either gives an OpenAI-compatible endpoint.
> **Single-image vs multi-page — pick the engine by task:**> - **Single-page** OCR (one image → markdown): both engines work. For a whole corpus, the batch> recipe [`unlimited-ocr-vllm.py`](unlimited-ocr-vllm.py) (offline vLLM, resumable, no network) is> the better fit than a client loop; for interactive/agent use, serve with **vLLM (Option A)**.> - **Multi-page / long-horizon** parsing (the model's headline feature): **both engines do it**> (validated 2026-06-28 — a clean 2-page doc read back both pages, `<PAGE>`-separated, on *both* vLLM> and SGLang). The difference is **robustness on hard inputs**: on degraded historical scans / newspaper> clippings, vLLM multi-page degraded to hallucination in our tests while **SGLang (Option B)** read> real content — so SGLang is the **more robust** multi-page path (it's also the authors' documented> one, via `images_config`). Use vLLM multi-page for clean docs; reach for SGLang for hard scans.> (vLLM's upstream PR [#46564](https://github.com/vllm-project/vllm/pull/46564) benchmarks single-page only.)
## 1. Start the server
### Option A — vLLM (official image)
vLLM support landed upstream; Baidu ships a dedicated image (the architecture isn't in a stable pipwheel yet). Use the default `:unlimited-ocr` tag on L4/A100, or `:unlimited-ocr-cu129` on Hopper.Runs on `l4x1`, no fa3/Hopper requirement. **Single-image is validated**; **multi-page also works onclean docs** (both pages, `<PAGE>`-separated) but degraded to hallucination on hard scans in our tests— for hard/degraded inputs prefer Option B (SGLang). For multi-page on vLLM, the request takes one`<image>` per page in the text and `window_size=1024` in `vllm_xargs` (it has no `images_config`).
```bashhf jobs run --detach --expose 8000 --flavor l4x1 -s HF_TOKEN --timeout 30m \ vllm/vllm-openai:unlimited-ocr -- \ vllm serve baidu/Unlimited-OCR --served-model-name Unlimited-OCR \ --trust-remote-code --max-model-len 32768 --host 0.0.0.0 --port 8000 \ --logits_processors vllm.model_executor.models.unlimited_ocr:NGramPerReqLogitsProcessor \ --no-enable-prefix-caching --mm-processor-cache-gb 0```
Per-request, vLLM takes the no-repeat n-gram knobs via `vllm_xargs` and needs `skip_special_tokens`off (it has no `images_config` — that's an SGLang param):
```pythonr = client.chat.completions.create( model="Unlimited-OCR", messages=[{"role": "user", "content": [ {"type": "text", "text": "<image>document parsing."}, # literal <image> prefix is required {"type": "image_url", "image_url": {"url": f"data:image/jpeg;base64,{img}"}}, ]}], temperature=0, extra_body={"skip_special_tokens": False, "vllm_xargs": {"ngram_size": 35, "window_size": 128}},)```
### Option B — SGLang (model's own build) · supports multi-page
The model also ships its own SGLang build, installed at startup from a 12 MB wheel. **This is themore robust path for multi-page / long-horizon parsing** (§3) — the model authors' documented route(`images_config`), and the one that held up on hard scans where vLLM multi-page hallucinated. Twopins matter (both learned the hard way, 2026-06-28):- **Pin the image to `lmsysorg/sglang:v0.5.10.post1`** — *not* `:latest`. `:latest` drifted to torch 2.11 / cu130, incompatible with the wheel (torch 2.9.1 / cuda-python 12.9); v0.5.10.post1 is the last release that matches the wheel exactly.- **Run on `a100-large` with `--attention-backend flashinfer`, not `h200`/`fa3`.** `fa3` needs a Hopper GPU, but HF's `h200` nodes currently fail GPU init with `CUDA error 802: system not yet initialized` (3/3 attempts) — an infra issue, not the model. `a100` + `flashinfer` sidesteps it and works.
```bashhf jobs run --detach --expose 10000 --flavor h200 -s HF_TOKEN --timeout 30m \ lmsysorg/sglang:latest -- \hf jobs run --detach --expose 10000 --flavor a100-large -s HF_TOKEN --timeout 30m \ lmsysorg/sglang:v0.5.10.post1 -- \ 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 \ && pip install -q kernels==0.11.7 \ && python -m sglang.launch_server --model baidu/Unlimited-OCR --served-model-name Unlimited-OCR \ --attention-backend fa3 --page-size 1 --mem-fraction-static 0.8 --context-length 32768 \ --attention-backend flashinfer --page-size 1 --mem-fraction-static 0.85 --context-length 32768 \ --enable-custom-logit-processor --disable-overlap-schedule --skip-server-warmup \ --host 0.0.0.0 --port 10000'```1 unmodified lineNotes:- `--` before `bash` is required, or the CLI parses `-lc` as its own flags.- `--timeout` stops the endpoint (and billing) at the deadline; `hf jobs cancel <id>` stops it earlier.- `fa3` requires a Hopper GPU (e.g. `h200`). The model is small, so the attention backend, not GPU memory, determines the flavor. Run `hf jobs hardware` for available flavors.- Follow startup with `hf jobs logs -f <id>`; the server is ready at `Application startup complete` (about 3 minutes from a cold start).- **Validated 2026-06-28** on `a100-large`: server came up, single-image and multi-page both read correctly (a clean 2-page doc returned both pages verbatim, `<PAGE>`-separated). The model card's "official" backend is `fa3` on Hopper for exact R-SWA — switch back to `--attention-backend fa3 --flavor h200` once the h200 `802` infra issue clears; `flashinfer` on `a100` is the working fallback.- Follow startup with `hf jobs logs -f <id>`; ready at `The server is fired up` / `Application startup complete` (a few minutes cold; the wheel + model download dominate).
The client examples below use the **SGLang** request format (`images_config` in `extra_body`,port 10000). The single-image call (§2) also works on the vLLM server — just use the Option A`extra_body` and your exposed port. **Multi-page (§3) is SGLang-only.**
## 2. Call it (OpenAI client; HF token as the API key)
22 unmodified lineswith coordinates normalized to 0–1000. Remove the tags for plain text(`re.sub(r'<\|det\|>.*?<\|/det\|>', '', text)`) or keep them for structure.
## 3. Multi-page / PDF## 3. Multi-page / PDF (SGLang shown; vLLM also works on clean docs)
> ✅ This **SGLang** flow (Option B) is **validated working 2026-06-28** (a clean 2-page doc read back> both pages verbatim, `<PAGE>`-separated) and follows the model card's multi-page example. The> `images_config`/`image_mode` param is SGLang-specific — **vLLM ignores it**; on vLLM, do multi-page> with one `<image>` per page in the text + `window_size=1024` in `vllm_xargs` (no `images_config`).> Both engines read clean multi-page docs; **SGLang was the more robust on hard/degraded scans**, where> vLLM multi-page hallucinated in our tests. (vLLM's upstream> [PR #46564](https://github.com/vllm-project/vllm/pull/46564) benchmarks single-page only.)
Send multiple page images in one request with the `Multi page parsing.` prompt and `image_mode="base"`:
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544# /// script# requires-python = ">=3.11"# dependencies = [# "datasets>=4.0.0",# "huggingface-hub",# "pillow",# "tqdm",# "toolz",# ]# ///
"""Convert document images to markdown using Baidu Unlimited-OCR with vLLM.
Unlimited-OCR (baidu/Unlimited-OCR, 3.3B, MIT) is a DeepSeek-OCR / DeepSeek-OCR-2 descendant. Thisrecipe runs it as an offline vLLM batch job (dataset in -> markdown out), mirroring the provendeepseek-ocr-vllm.py pattern: llm.generate() with PIL images and the model'sNGramPerReqLogitsProcessor to stop coordinate-token loops on long documents.
One image per row -> one markdown. Output is layout-grounded markdown: text spans are tagged<|ref|>...<|/ref|> with <|det|>...<|/det|> coordinate boxes (coords normalized 0-1000); tables comeback as HTML and equations as LaTeX. Pass --strip-grounding to drop the tags and keep clean text;add --grounding-column to keep the raw grounded output (with bboxes) in a second column too.
Multi-page / "long-horizon" parsing (the model's headline feature) is not in this single-image batchrecipe — for multi-page, serve the model and send all pages in one request (see serving-unlimited-ocr.md).Multi-page *does* work via vLLM serving: on a clean 2-page doc it returned both pages, <PAGE>-separated.But on hard/degraded scans (dense historical pages, newspaper clippings) vLLM multi-page degraded tohallucination in our tests, where the model's own SGLang build held up better — so SGLang is the morerobust multi-page path. (vLLM's upstream PR, vllm-project/vllm#46564, benchmarks single-page only.)
IMPORTANT: Unlimited-OCR's architecture is not in a stable vLLM pip wheel, so this script MUST run onBaidu's dedicated vLLM image (vllm and torch come from the image, not the PEP 723 deps):
hf jobs uv run --flavor l4x1 -s HF_TOKEN \\ --image vllm/vllm-openai:unlimited-ocr --python /usr/bin/python3 \\ -e PYTHONPATH=/usr/local/lib/python3.12/dist-packages \\ https://huggingface.co/datasets/uv-scripts/ocr/raw/main/unlimited-ocr-vllm.py \\ your-input-dataset your-output-dataset --max-samples 10
Use the vllm/vllm-openai:unlimited-ocr-cu129 tag on Hopper GPUs (h100/h200).
Model card: https://huggingface.co/baidu/Unlimited-OCRvLLM recipe: https://recipes.vllm.ai/baidu/Unlimited-OCR"""
import argparseimport ioimport jsonimport loggingimport osimport reimport sysimport timefrom datetime import datetimefrom typing import Any, Dict, List, Optional, Union
import torchfrom datasets import load_datasetfrom huggingface_hub import DatasetCard, loginfrom PIL import Imagefrom toolz import partition_allfrom tqdm.auto import tqdm
# Disable vLLM's FlashInfer sampler: it JIT-compiles a CUDA kernel needing nvcc. Greedy OCR doesn't# use it; on the dedicated vllm/vllm-openai image it's a harmless no-op.os.environ.setdefault("VLLM_USE_FLASHINFER_SAMPLER", "0")from vllm import LLM, SamplingParamsfrom vllm.model_executor.models.unlimited_ocr import NGramPerReqLogitsProcessor
logging.basicConfig(level=logging.INFO)logger = logging.getLogger(__name__)
MODEL = "baidu/Unlimited-OCR"
# Prompt and no-repeat-ngram knobs straight from the model card / vLLM recipe (single image).PROMPT = "<image>document parsing."NGRAM_SIZE = 35WINDOW_SIZE = 128
# Strip the model's grounding markup to recover clean text:# drop the <|det|>...<|/det|> coordinate boxes, then unwrap the <|ref|>...<|/ref|> spans._DET_RE = re.compile(r"<\|det\|>.*?<\|/det\|>", re.DOTALL)_REF_RE = re.compile(r"<\|/?ref\|>")
def strip_grounding(text: str) -> str: """Remove <|det|> boxes and <|ref|> wrappers, keeping the inner text.""" text = _DET_RE.sub("", text) text = _REF_RE.sub("", text) # collapse the blank lines left behind by removed boxes return re.sub(r"\n{3,}", "\n\n", text).strip()
def check_cuda_availability(): """Check if CUDA is available and exit if not.""" if not torch.cuda.is_available(): logger.error("CUDA is not available. This script requires a GPU.") sys.exit(1) logger.info(f"CUDA is available. GPU: {torch.cuda.get_device_name(0)}")
def to_pil(image: Union[Image.Image, Dict[str, Any], str]) -> Image.Image: """Convert various dataset image cell formats to an RGB PIL image.""" if isinstance(image, Image.Image): return image.convert("RGB") if isinstance(image, dict) and "bytes" in image: return Image.open(io.BytesIO(image["bytes"])).convert("RGB") if isinstance(image, str): return Image.open(image).convert("RGB") raise ValueError(f"Unsupported image type: {type(image)}")
def create_dataset_card( source_dataset: str, output_dataset: str, model: str, num_samples: int, processing_time: str, output_column: str, strip_grounding_enabled: bool, split: str,) -> str: """Create a dataset card documenting the OCR run.""" if strip_grounding_enabled: grounding = "Grounding markup was stripped (`--strip-grounding`); the column holds clean text." else: grounding = ( "The column holds the model's raw layout-grounded markdown: text spans tagged " "`<|ref|>...<|/ref|>` with `<|det|>...<|/det|>` coordinate boxes (coords 0-1000). " "Strip them with " "`re.sub(r'<\\|det\\|>.*?<\\|/det\\|>', '', t)` then `re.sub(r'<\\|/?ref\\|>', '', t)`." ) return f"""---tags:- ocr- document-processing- unlimited-ocr- baidu- markdown- uv-script- generated---
# Document OCR using Unlimited-OCR
This dataset contains OCR results for [{source_dataset}](https://huggingface.co/datasets/{source_dataset})produced by [{model}](https://huggingface.co/{model}) with vLLM.
## Processing Details
- **Source Dataset**: [{source_dataset}](https://huggingface.co/datasets/{source_dataset})- **Model**: [{model}](https://huggingface.co/{model})- **Number of Samples**: {num_samples:,}- **Processing Time**: {processing_time}- **Processing Date**: {datetime.now().strftime("%Y-%m-%d %H:%M UTC")}- **Output Column**: `{output_column}`- **Split**: `{split}`
## Output
{grounding}
Tables are returned as HTML and equations as LaTeX.
## Usage
```pythonfrom datasets import load_dataset
ds = load_dataset("{output_dataset}", split="{split}")print(ds[0]["{output_column}"])```
## Reproduction
Generated with the [uv-scripts/ocr](https://huggingface.co/datasets/uv-scripts/ocr) Unlimited-OCRvLLM recipe. Unlimited-OCR needs Baidu's dedicated vLLM image:
```bashhf jobs uv run --flavor l4x1 -s HF_TOKEN \\ --image vllm/vllm-openai:unlimited-ocr --python /usr/bin/python3 \\ -e PYTHONPATH=/usr/local/lib/python3.12/dist-packages \\ https://huggingface.co/datasets/uv-scripts/ocr/raw/main/unlimited-ocr-vllm.py \\ {source_dataset} <output-dataset>```
Generated with [UV Scripts](https://huggingface.co/uv-scripts)"""
def main( input_dataset: str, output_dataset: str, model: str = MODEL, image_column: str = "image", output_column: str = "markdown", grounding_column: Optional[str] = None, batch_size: int = 8, max_model_len: int = 32768, max_tokens: int = 8192, gpu_memory_utilization: float = 0.8, strip_grounding_enabled: bool = False, hf_token: Optional[str] = None, split: str = "train", max_samples: Optional[int] = None, private: bool = False, shuffle: bool = False, seed: int = 42, config: Optional[str] = None, create_pr: bool = False, verbose: bool = False,): """Process images from an HF dataset through Unlimited-OCR with vLLM.""" if grounding_column and grounding_column == output_column: raise ValueError("--grounding-column must differ from --output-column") check_cuda_availability() start_time = datetime.now()
HF_TOKEN = hf_token or os.environ.get("HF_TOKEN") if HF_TOKEN: login(token=HF_TOKEN)
logger.info(f"Loading dataset: {input_dataset}") dataset = load_dataset(input_dataset, split=split) if image_column not in dataset.column_names: raise ValueError( f"Column '{image_column}' not found. Available: {dataset.column_names}" )
if shuffle: logger.info(f"Shuffling dataset with seed {seed}") dataset = dataset.shuffle(seed=seed) if max_samples: dataset = dataset.select(range(min(max_samples, len(dataset)))) logger.info(f"Limited to {len(dataset)} samples")
logger.info(f"Initializing vLLM with model: {model}") logger.info("This may take a few minutes on first run...")
llm = LLM( model=model, trust_remote_code=True, max_model_len=max_model_len, gpu_memory_utilization=gpu_memory_utilization, enable_prefix_caching=False, mm_processor_cache_gb=0, limit_mm_per_prompt={"image": 1}, logits_processors=[NGramPerReqLogitsProcessor], )
sampling_params = SamplingParams( temperature=0.0, max_tokens=max_tokens, skip_special_tokens=False, extra_args=dict(ngram_size=NGRAM_SIZE, window_size=WINDOW_SIZE), )
logger.info(f"Processing {len(dataset)} images in batches of {batch_size}") all_outputs: List[str] = [] all_grounded: List[ str ] = [] # raw grounded text, only when --grounding-column is set for batch_indices in tqdm( partition_all(batch_size, range(len(dataset))), total=(len(dataset) + batch_size - 1) // batch_size, desc="Unlimited-OCR", ): batch_indices = list(batch_indices) try: model_inputs = [ { "prompt": PROMPT, "multi_modal_data": {"image": to_pil(dataset[i][image_column])}, } for i in batch_indices ] outputs = llm.generate(model_inputs, sampling_params) for output in outputs: raw = output.outputs[0].text.strip() all_outputs.append( strip_grounding(raw) if strip_grounding_enabled else raw ) if grounding_column: all_grounded.append(raw) except Exception as e: logger.error(f"Error processing batch: {e}") all_outputs.extend(["[OCR FAILED]"] * len(batch_indices)) if grounding_column: all_grounded.extend(["[OCR FAILED]"] * len(batch_indices))
processing_time_str = ( f"{(datetime.now() - start_time).total_seconds() / 60:.1f} min" )
logger.info(f"Adding '{output_column}' column to dataset") if output_column in dataset.column_names: logger.warning(f"Column '{output_column}' already exists, replacing it") dataset = dataset.remove_columns([output_column]) dataset = dataset.add_column(output_column, all_outputs) if grounding_column: logger.info(f"Adding '{grounding_column}' column (raw grounded output)") if grounding_column in dataset.column_names: logger.warning(f"Column '{grounding_column}' already exists, replacing it") dataset = dataset.remove_columns([grounding_column]) dataset = dataset.add_column(grounding_column, all_grounded)
# inference_info: append-only log so several models can write into one dataset and be compared. inference_entry = { "model_id": model, "model_name": "Unlimited-OCR", "column_name": output_column, "timestamp": datetime.now().isoformat(), "batch_size": batch_size, "max_tokens": max_tokens, "max_model_len": max_model_len, "gpu_memory_utilization": gpu_memory_utilization, "strip_grounding": strip_grounding_enabled, "grounding_column": grounding_column, "script": "unlimited-ocr-vllm.py", "script_url": "https://huggingface.co/datasets/uv-scripts/ocr/raw/main/unlimited-ocr-vllm.py", } if "inference_info" in dataset.column_names: logger.info("Updating existing inference_info column")
def update_inference_info(example): try: existing = ( json.loads(example["inference_info"]) if example["inference_info"] else [] ) except (json.JSONDecodeError, TypeError): existing = [] existing.append(inference_entry) return {"inference_info": json.dumps(existing)}
dataset = dataset.map(update_inference_info) else: logger.info("Creating new inference_info column") dataset = dataset.add_column( "inference_info", [json.dumps([inference_entry])] * len(dataset) )
logger.info(f"Pushing to {output_dataset}") max_retries = 3 for attempt in range(1, max_retries + 1): try: if attempt > 1: logger.warning("Disabling XET (fallback to HTTP upload)") os.environ["HF_HUB_DISABLE_XET"] = "1" dataset.push_to_hub( output_dataset, private=private, token=HF_TOKEN, max_shard_size="500MB", **({"config_name": config} if config else {}), create_pr=create_pr, commit_message=f"Add {model} OCR results ({len(dataset)} samples)" + (f" [{config}]" if config else ""), ) break except Exception as e: logger.error(f"Upload attempt {attempt}/{max_retries} failed: {e}") if attempt < max_retries: delay = 30 * (2 ** (attempt - 1)) logger.info(f"Retrying in {delay}s...") time.sleep(delay) else: logger.error("All upload attempts failed. OCR results are lost.") sys.exit(1)
logger.info("Creating dataset card...") card = DatasetCard( create_dataset_card( source_dataset=input_dataset, output_dataset=output_dataset, model=model, num_samples=len(dataset), processing_time=processing_time_str, output_column=output_column, strip_grounding_enabled=strip_grounding_enabled, split=split, ) ) card.push_to_hub(output_dataset, token=HF_TOKEN)
logger.info("✅ OCR conversion complete!") logger.info(f"Dataset: https://huggingface.co/datasets/{output_dataset}") logger.info(f"Processing time: {processing_time_str}")
if verbose: import importlib.metadata
logger.info("--- Resolved package versions ---") for pkg in ["vllm", "transformers", "torch", "datasets", "pillow"]: try: logger.info(f" {pkg}=={importlib.metadata.version(pkg)}") except importlib.metadata.PackageNotFoundError: logger.info(f" {pkg}: not installed") logger.info("--- End versions ---")
if __name__ == "__main__": if len(sys.argv) == 1: print("=" * 80) print("Unlimited-OCR to Markdown Converter (vLLM)") print("=" * 80) print("\nBaidu Unlimited-OCR (3.3B, MIT) — one image per row -> markdown.") print("\nMUST run on the dedicated image: vllm/vllm-openai:unlimited-ocr") print("(use the -cu129 tag on Hopper GPUs).") print("\nExample:") print(" hf jobs uv run --flavor l4x1 -s HF_TOKEN \\") print( " --image vllm/vllm-openai:unlimited-ocr --python /usr/bin/python3 \\" ) print(" -e PYTHONPATH=/usr/local/lib/python3.12/dist-packages \\") print(" unlimited-ocr-vllm.py my-images my-markdown --max-samples 10") print( "\nMulti-page documents: serve the model instead (see serving-unlimited-ocr.md)." ) print("\nFor full help, run with --help") sys.exit(0)
parser = argparse.ArgumentParser( description="OCR images to markdown using Unlimited-OCR (vLLM)", formatter_class=argparse.RawDescriptionHelpFormatter, epilog="""Examples: # Basic usage uv run unlimited-ocr-vllm.py my-images ocr-results
# Clean text (strip grounding tags) uv run unlimited-ocr-vllm.py my-images ocr-results --strip-grounding
# On HF Jobs (dedicated image required) hf jobs uv run --flavor l4x1 -s HF_TOKEN \\ --image vllm/vllm-openai:unlimited-ocr --python /usr/bin/python3 \\ -e PYTHONPATH=/usr/local/lib/python3.12/dist-packages \\ https://huggingface.co/datasets/uv-scripts/ocr/raw/main/unlimited-ocr-vllm.py \\ my-dataset my-output --max-samples 10 """, ) parser.add_argument("input_dataset", help="Input dataset ID from Hugging Face Hub") parser.add_argument("output_dataset", help="Output dataset ID for Hugging Face Hub") parser.add_argument( "--model", default=MODEL, help=f"Model to use (default: {MODEL}). Override only for a same-architecture mirror.", ) parser.add_argument( "--image-column", default="image", help="Column with images (default: image)" ) parser.add_argument( "--output-column", default="markdown", help="Output column name (default: markdown)", ) parser.add_argument( "--strip-grounding", action="store_true", help="Drop <|det|>/<|ref|> grounding tags from the output column, keeping clean text", ) parser.add_argument( "--grounding-column", help="Also store the RAW grounded output (boxes + tags) in this extra column " "(pair with --strip-grounding to keep clean text AND the layout/bboxes)", ) parser.add_argument( "--batch-size", type=int, default=8, help="Images per batch (default: 8)" ) parser.add_argument( "--max-model-len", type=int, default=32768, help="Max context length (default: 32768)", ) parser.add_argument( "--max-tokens", type=int, default=8192, help="Max output tokens (default: 8192)", ) parser.add_argument( "--gpu-memory-utilization", type=float, default=0.8, help="GPU memory fraction (default: 0.8)", ) parser.add_argument("--hf-token", help="Hugging Face API token") parser.add_argument( "--split", default="train", help="Dataset split (default: train)" ) parser.add_argument( "--max-samples", type=int, help="Max samples to process (for testing)" ) parser.add_argument( "--private", action="store_true", help="Make output dataset private" ) parser.add_argument( "--shuffle", action="store_true", help="Shuffle before processing" ) parser.add_argument( "--seed", type=int, default=42, help="Shuffle seed (default: 42)" ) parser.add_argument( "--config", help="Config/subset name when pushing (for benchmarking multiple models)", ) parser.add_argument( "--create-pr", action="store_true", help="Push as a PR instead of a direct commit", ) parser.add_argument( "--verbose", action="store_true", help="Log resolved package versions after the run", )
args = parser.parse_args()
main( input_dataset=args.input_dataset, output_dataset=args.output_dataset, model=args.model, image_column=args.image_column, output_column=args.output_column, grounding_column=args.grounding_column, batch_size=args.batch_size, max_model_len=args.max_model_len, max_tokens=args.max_tokens, gpu_memory_utilization=args.gpu_memory_utilization, strip_grounding_enabled=args.strip_grounding, hf_token=args.hf_token, split=args.split, max_samples=args.max_samples, private=args.private, shuffle=args.shuffle, seed=args.seed, config=args.config, create_pr=args.create_pr, verbose=args.verbose, )CLAUDE.md+93
README.md+4-2
serving-unlimited-ocr.md+83-11
unlimited-ocr-vllm.pyAdded+544