davanstrien HF Staff commited on
Commit
54444e7
·
verified ·
1 Parent(s): 74f97dc

Sync from GitHub via hub-sync

Browse files
Files changed (5) hide show
  1. README.md +3 -3
  2. SERVING.md +12 -0
  3. lighton-ocr3-saturate.py +475 -0
  4. lighton-ocr3.py +4 -0
  5. models.json +23 -0
README.md CHANGED
@@ -104,7 +104,7 @@ These are the maintained recipes. Each one has a tested `[tool.hf-jobs]` header,
104
 
105
  Start with a model under 2B. Use a larger model only if the output of a small one is not good enough. Check the licence before you use a model: Surya and lift use a modified OpenRAIL-M licence (free for research, personal use and startups under $5M; no competitive use against Datalab's API), and the Hunyuan licence excludes the EU, the UK and South Korea.
106
 
107
- **Variants and tools:** `glm-ocr-bucket.py`, `surya-ocr-bucket.py` and `lighton-ocr3-bucket.py` read images and PDFs from a Bucket and write one `.md` per page. `lighton-ocr3-bucket.py` also takes `hf://buckets/...` URLs for input and output directly, so it reads large buckets in batches through the Hub API without mounting them. It reads `.jp2`, skips pages that already have output (so a re-run resumes), and in `--mode grounding` writes a `.json` sidecar with the layout blocks. `surya-ocr-bucket.py` also writes a `.json` sidecar with the layout blocks, resumes from existing JSON, and can mount or copy its input (`--io-mode mount|copy`); the dataset version, `surya-ocr.py`, keeps the blocks in a `surya_blocks` column. `lighton-ocr2-saturate.py`, `ovis-ocr2-saturate.py` and `xiaomi-ocr-0-saturate.py` are for large runs, and `ocr-vllm-judge.py` compares outputs ([Scaling up](#scaling-up)). `pp-doclayout.py` and `lfm2-extract.py` are described in [Structured extraction and layout](#structured-extraction-and-layout).
108
 
109
  Which model is best depends on your documents. The public olmOCR-Bench leaderboard is one command away:
110
 
@@ -230,7 +230,7 @@ The image is about 11 GB, so a cold start takes several minutes. On dense pages
230
 
231
  ## Scaling up
232
 
233
- **Large datasets:** `lighton-ocr2-saturate.py`, `ovis-ocr2-saturate.py` and `xiaomi-ocr-0-saturate.py` start a vLLM server in the Job (the Xiaomi recipe can use SGLang instead) and send pages to it with adaptive concurrency. They stream results to the output repo as parquet parts. If a run stops, run the same command again and it skips the rows that are done. A failed page is stored as an error row, and `--retry-errors` tries those rows again. The output layout is different from the other recipes; the script header explains how to read it. [SERVING.md](SERVING.md) compares server mode with offline batches (measured throughput and output parity).
234
 
235
  **Whole books and long documents:** `unlimited-ocr2.py` runs [Unlimited-OCR-2](https://huggingface.co/baidu/Unlimited-OCR-2) on Baidu's own SGLang build. It groups page images into documents and sends 16 consecutive pages per request, so a paragraph that runs over a page break comes back joined. Point it at a folder of pages, for example a Bucket:
236
 
@@ -245,7 +245,7 @@ The header picks `rtx-pro-6000` (the fastest per dollar in our tests; 24 GB GPUs
245
 
246
  ```bash
247
  hf jobs uv run --detach --timeout 4h \
248
- https://huggingface.co/datasets/uv-scripts/ocr/raw/main/lighton-ocr2-saturate.py \
249
  your-dataset your-output
250
  ```
251
 
 
104
 
105
  Start with a model under 2B. Use a larger model only if the output of a small one is not good enough. Check the licence before you use a model: Surya and lift use a modified OpenRAIL-M licence (free for research, personal use and startups under $5M; no competitive use against Datalab's API), and the Hunyuan licence excludes the EU, the UK and South Korea.
106
 
107
+ **Variants and tools:** `glm-ocr-bucket.py`, `surya-ocr-bucket.py` and `lighton-ocr3-bucket.py` read images and PDFs from a Bucket and write one `.md` per page. `lighton-ocr3-bucket.py` also takes `hf://buckets/...` URLs for input and output directly, so it reads large buckets in batches through the Hub API without mounting them. It reads `.jp2`, skips pages that already have output (so a re-run resumes), and in `--mode grounding` writes a `.json` sidecar with the layout blocks. `surya-ocr-bucket.py` also writes a `.json` sidecar with the layout blocks, resumes from existing JSON, and can mount or copy its input (`--io-mode mount|copy`); the dataset version, `surya-ocr.py`, keeps the blocks in a `surya_blocks` column. `lighton-ocr3-saturate.py`, `lighton-ocr2-saturate.py`, `ovis-ocr2-saturate.py` and `xiaomi-ocr-0-saturate.py` are for large runs, and `ocr-vllm-judge.py` compares outputs ([Scaling up](#scaling-up)). `pp-doclayout.py` and `lfm2-extract.py` are described in [Structured extraction and layout](#structured-extraction-and-layout).
108
 
109
  Which model is best depends on your documents. The public olmOCR-Bench leaderboard is one command away:
110
 
 
230
 
231
  ## Scaling up
232
 
233
+ **Large datasets:** `lighton-ocr3-saturate.py`, `lighton-ocr2-saturate.py`, `ovis-ocr2-saturate.py` and `xiaomi-ocr-0-saturate.py` start a vLLM server in the Job (the Xiaomi recipe can use SGLang instead) and send pages to it with adaptive concurrency. They stream results to the output repo as parquet parts. If a run stops, run the same command again and it skips the rows that are done. A failed page is stored as an error row, and `--retry-errors` tries those rows again. The output layout is different from the other recipes; the script header explains how to read it. [SERVING.md](SERVING.md) compares server mode with offline batches (measured throughput and output parity). For LightOnOCR-3-0.8B, `lighton-ocr3-saturate.py` measured 2.2 pages/s on `a10g-small` and 10.0 pages/s on `rtx-pro-6000` (about $0.08 per 1,000 pages), against 0.90 and 1.27 pages/s for `lighton-ocr3.py` on `a10g-small` and `a100-large`.
234
 
235
  **Whole books and long documents:** `unlimited-ocr2.py` runs [Unlimited-OCR-2](https://huggingface.co/baidu/Unlimited-OCR-2) on Baidu's own SGLang build. It groups page images into documents and sends 16 consecutive pages per request, so a paragraph that runs over a page break comes back joined. Point it at a folder of pages, for example a Bucket:
236
 
 
245
 
246
  ```bash
247
  hf jobs uv run --detach --timeout 4h \
248
+ https://huggingface.co/datasets/uv-scripts/ocr/raw/main/lighton-ocr3-saturate.py \
249
  your-dataset your-output
250
  ```
251
 
SERVING.md CHANGED
@@ -26,6 +26,18 @@ same data, same sampling, driver concurrency 32):
26
  image cells were empty, the offline recipe produced 0 usable outputs and the server
27
  recipe produced all of the valid ones.
28
 
 
 
 
 
 
 
 
 
 
 
 
 
29
  The job command stays the standard `hf jobs uv run` shape: the driver spawns
30
  `vllm serve` itself as a subprocess when no server is reachable (flags live in the
31
  script's `SERVE_ARGS`, taken from the model's own card where they exist), so the only
 
26
  image cells were empty, the offline recipe produced 0 usable outputs and the server
27
  recipe produced all of the valid ones.
28
 
29
+ **LightOnOCR-3-0.8B** (`lighton-ocr3.py` against `lighton-ocr3-saturate.py`, 600 pages: 350
30
+ book pages from finebooks/bhl-impact-gt and 250 typed industry documents, 2026-11-05, steady
31
+ state): `a10g-small` 0.90 → 2.2 pages/s, `a100-large` 1.27 → 7.2 pages/s. Most of the gain is
32
+ pages in flight (the offline recipe sends batches of 16 and waits for the slowest page); on
33
+ small flavors the window is capped by host memory, because each page in flight holds about
34
+ 0.1 GiB of image data. On fast GPUs one vLLM API server cannot preprocess images quickly
35
+ enough (128-256 pages in flight, 36-60 running in the engine, none waiting); 4 API servers
36
+ (`--api-server-count 4`) gave +16% on `a100-large`, +9% on `rtx-pro-6000`, +10% on `a10g-large`. At temperature 0.2 the outputs of two server runs differ on about 40%
37
+ of pages; the offline recipe differs from a server run by the same amount. The character
38
+ error rate on the 282 book pages with at least 20 characters of ground truth (IMPACT) was
39
+ 0.077 to 0.083 mean and 0.020 median in every 0.8B run, offline or server.
40
+
41
  The job command stays the standard `hf jobs uv run` shape: the driver spawns
42
  `vllm serve` itself as a subprocess when no server is reachable (flags live in the
43
  script's `SERVE_ARGS`, taken from the model's own card where they exist), so the only
lighton-ocr3-saturate.py ADDED
@@ -0,0 +1,475 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # /// script
2
+ # requires-python = ">=3.11"
3
+ # dependencies = [
4
+ # "saturate[hf]==0.3.0",
5
+ # "pillow>=10",
6
+ # # LightOn's official client, pinned to a commit (not on PyPI). Used for its page
7
+ # # resize, grounding parser and dollar-delimiter repair so outputs match upstream.
8
+ # "lightonocr @ https://github.com/lightonai/LightOnOCR/archive/36755d461be079737860a5f03ae0c803501269e9.tar.gz",
9
+ # ]
10
+ #
11
+ # [tool.hf-jobs]
12
+ # image = "vllm/vllm-openai:v0.30.0"
13
+ # flavor = "a10g-small"
14
+ # timeout = "4h"
15
+ # secrets = ["HF_TOKEN"]
16
+ # ///
17
+ """
18
+ Convert document images to markdown (or layout blocks) using LightOnOCR-3 via saturate.
19
+
20
+ Same model, prompt modes, sampling and page preparation as `lighton-ocr3.py`, but the
21
+ script starts `vllm serve` in the Job and the `saturate` library sends the pages to it:
22
+ many pages in flight, resumable parquet output and durable error rows. Use this recipe
23
+ for large runs.
24
+
25
+ Run on HF Jobs. The script starts the server itself; its [tool.hf-jobs] header declares
26
+ the image that provides `vllm`, the hardware and the HF_TOKEN secret (`hf` CLI 1.32+).
27
+ Flags on the command line override the header:
28
+
29
+ hf jobs uv run --detach \\
30
+ https://huggingface.co/datasets/uv-scripts/ocr/raw/main/lighton-ocr3-saturate.py \\
31
+ <input-dataset> <output-dataset>
32
+
33
+ Smoke test first with --max-samples 10. Layout blocks with labels and boxes:
34
+
35
+ hf jobs uv run --detach \\
36
+ https://huggingface.co/datasets/uv-scripts/ocr/raw/main/lighton-ocr3-saturate.py \\
37
+ <input-dataset> <output-dataset> --mode grounding
38
+
39
+ Output: the output repo holds `data/part-*.parquet` with rows
40
+ `{id, markdown, raw, finish_reason, layout_blocks, model, prompt_tokens, completion_tokens,
41
+ error}` keyed by the input row id (`--id-column`, or `<repo>:<config>:<split>:<000000000>`
42
+ by default). Read it with `saturate.read_output`, which keeps one row per id (a success
43
+ over an earlier error). `datasets.load_dataset(<output>, data_dir="data")` returns every
44
+ record, so after a --retry-errors run it also holds the old error rows: drop rows with an
45
+ `error` before you join back to the input on id. Re-running the same command skips
46
+ finished rows; --retry-errors re-admits failed ones.
47
+
48
+ `finish_reason` = "length" marks a page that hit --max-tokens (long tables, or the model
49
+ repeating a line). --repair-max-tokens N sends those pages once more, at the end of the
50
+ run, with a cap of N tokens and temperature 0.1, and writes the results to `repair/`
51
+ (`load_dataset(<output>, data_dir="repair")`); join on id and prefer the repair row where
52
+ its finish_reason is "stop". A restarted run also repairs the pages that an earlier,
53
+ interrupted run saved as truncated.
54
+
55
+ Models (Apache-2.0):
56
+ lightonai/LightOnOCR-3-0.8B (default) 85.5 olmOCR-Bench, 74.6 ParseBench
57
+ lightonai/LightOnOCR-3-4B 86.3 olmOCR-Bench, 75.1 ParseBench
58
+ LightOnOCR-3-1B is not supported: it keeps the LightOnOCR-2 (Pixtral) architecture, and
59
+ LightOn reports that transformers 5.17 (the version in the vLLM 0.30.0 image) breaks it.
60
+
61
+ Upstream settings kept:
62
+ - Serve flags: the LightOnOCR README's flags for the 0.8B and 4B (`--max-model-len 18000`,
63
+ thinking off, `--mm-processor-cache-gb 0`, `--no-enable-prefix-caching`,
64
+ `--limit-mm-per-prompt '{"image": 1}'`). vLLM 0.30.0, the version LightOn tests.
65
+ - Prompt modes: plain sends the image alone; grounding adds the text "grounding". The card
66
+ says other instructions are out of distribution.
67
+ - Sampling: the model card's vLLM example (temperature 0.2, top_p 0.9, max_tokens 4096).
68
+ - Pages: downscaled to 2048 px on the longest edge with LightOn's own resize (never
69
+ upscaled), sent as PNG, as the official client does. The PNG uses a fast compression
70
+ level; PNG is lossless, so the server decodes the same pixels.
71
+ - Escaped dollar delimiters are repaired (`\\$x\\$` -> `$x$`) as the client does; `raw`
72
+ keeps the model's text.
73
+
74
+ Speed settings: pages are prepared in `--prepare-workers` threads (default: the CPU_CORES
75
+ that HF Jobs sets), and saturate's adaptive window sets how many pages are in flight, up to
76
+ a cap that fits the Job's memory (window_cap below). `--window N` pins it instead. The
77
+ server also gets `--max-num-batched-tokens 16384`, and 4 API server processes on flavors
78
+ with 12 or more CPU cores (see SERVING). Pass --serve-args "--api-server-count N" to choose.
79
+
80
+ Measured speed, LightOnOCR-3-0.8B (2026-11-05, vLLM 0.30.0). 600 pages: 350 book pages from
81
+ finebooks/bhl-impact-gt and 250 pages of typed industry documents, all fitted to 2048 px.
82
+ Steady state, excluding the server start (about 4 min, also paid by lighton-ocr3.py):
83
+
84
+ flavor pages/s $ per 1,000 pages lighton-ocr3.py (offline batches)
85
+ a10g-small 2.2 0.12 0.90 pages/s, $0.31
86
+ l4x1 1.6 0.14
87
+ a10g-large 2.7 0.15
88
+ a100-large 7.2 0.10 1.27 pages/s, $0.55
89
+ rtx-pro-6000 10.0 0.08
90
+
91
+ The 4B on a100-large (one API server): 2.7 pages/s, $0.26 per 1,000 pages; on these book
92
+ pages its character error rate was higher than the 0.8B's (0.10 mean, 0.023 median, one
93
+ run), so check a sample before paying for it. The header's a10g-small is a good default
94
+ for small and medium runs; for large runs add --flavor rtx-pro-6000 (or a100-large). In
95
+ every run the outputs differed from lighton-ocr3.py's no more than two runs of this recipe
96
+ differ from each other (sampling at temperature 0.2). The character error rate on the 282
97
+ book pages with at least 20 characters of ground truth was 0.077 to 0.083 mean and 0.020
98
+ median in every 0.8B run.
99
+
100
+ Truncation and repair: 9 to 12 of the 600 pages stopped at max_tokens 4096 in each run,
101
+ most of them typed tables. With --repair-max-tokens 12000, 8 of 12 such pages finished:
102
+ 3 in fewer than 4,096 tokens on the second try, and 5 long pages that needed 4,900 to
103
+ 6,100 tokens. The other 4 hit the cap again. The pass added 22% to the run's output
104
+ tokens. With --repair-max-tokens 8192 (suggested), 5 of 9 such pages finished, the same 4
105
+ hit the cap again, and the pass added 16%. Pages that hit the cap on both tries keep
106
+ their first output in data/.
107
+
108
+ The SERVING dict below is the per-model tuning prior. Agents can `ast.literal_eval` it
109
+ without running the script; the script itself consumes it.
110
+ """
111
+
112
+ import argparse
113
+ import base64
114
+ import hashlib
115
+ import io
116
+ import json
117
+ import os
118
+ import shlex
119
+ import sys
120
+ import tempfile
121
+
122
+ # Serving starting values for LightOnOCR-3 (0.8B and 4B). Per-value provenance:
123
+ # - image: vLLM 0.30.0, the version LightOn's client pins and tests (0.27.1 makes the
124
+ # models loop, per the LightOnOCR README).
125
+ # - context 18000 and serve_args: the LightOnOCR README "Models" table for the 0.8B and 4B,
126
+ # plus its `--limit-mm-per-prompt '{"image": 1}'`.
127
+ # - max_tokens/temperature/top_p: the model card's vLLM example, verbatim.
128
+ # - longest_edge 2048: the card's rendering tip and the client's page size for these models.
129
+ # - patch 32: 16 px patches with a 2x2 merge, so a 2048x2048 page is at most 64x64 = 4,096
130
+ # image tokens (used for the context check).
131
+ # - --max-num-batched-tokens 16384: speed only. vLLM 0.30 serves with 2048 on A10G, L4 and
132
+ # A100 (8192 on other GPUs of 70 GB or more), less than one page's image tokens. Measured on a100-large:
133
+ # 6.20 and 6.30 pages/s against 5.83 without it, outputs within the run-to-run noise.
134
+ # - pages_per_gib: see window_cap().
135
+ # - api_servers 4 when CPU_CORES >= 12: speed only. With one vLLM API server, a100-large and
136
+ # rtx-pro-6000 had 128-256 pages in flight but only 36-60 running in the engine and none
137
+ # waiting: the rest queued for image preprocessing in the API process. Measured, 4 API
138
+ # servers against one: a100-large 7.29 and 7.18 against 6.20 and 6.30 pages/s,
139
+ # rtx-pro-6000 10.0 against 9.15, a10g-large 2.74 against 2.49; outputs within the
140
+ # run-to-run noise. Small flavors (a10g-small 3 cores, l4x1 8) keep one, to leave CPU
141
+ # for page preparation.
142
+ SERVING = {
143
+ "models": ["lightonai/LightOnOCR-3-0.8B", "lightonai/LightOnOCR-3-4B"],
144
+ "image": "vllm/vllm-openai:v0.30.0",
145
+ "context": 18000,
146
+ "serve_args": [
147
+ "--default-chat-template-kwargs", '{"enable_thinking": false}',
148
+ "--limit-mm-per-prompt", '{"image": 1}',
149
+ "--mm-processor-cache-gb", "0",
150
+ "--no-enable-prefix-caching",
151
+ "--max-num-batched-tokens", "16384",
152
+ ],
153
+ "pages_per_gib": 6,
154
+ "api_servers": 4,
155
+ "api_servers_min_cores": 12,
156
+ "max_tokens": 4096,
157
+ "temperature": 0.2,
158
+ "top_p": 0.9,
159
+ "repair_temperature": 0.1,
160
+ "longest_edge": 2048,
161
+ "patch": 32,
162
+ }
163
+
164
+
165
+ def window_cap() -> int:
166
+ """Most pages in flight that this machine's memory allows.
167
+
168
+ Every page in flight holds about 0.1 GiB of image data on the host (the client's copy and
169
+ the server's preprocessed image), on top of 7 to 9 GiB for the engine itself. On
170
+ a10g-small (14.9 GiB limit), 64 pages in flight reached the limit and the Job stopped
171
+ making progress; 32 peaked at 12.0 GiB, and up to 39 peaked at 13.0 and 14.8 GiB on two
172
+ runs. So the window may grow by SERVING "pages_per_gib" pages per GiB above 10 GiB: 29 on
173
+ a10g-small (which is GPU-bound from about 20 pages in flight), about 100 on l4x1, the full
174
+ 512 on a100-large. The limit is read from the container (cgroup v2), then from the MEMORY
175
+ variable that HF Jobs sets.
176
+ """
177
+ limit_gib = None
178
+ try:
179
+ with open("/sys/fs/cgroup/memory.max") as handle:
180
+ value = handle.read().strip()
181
+ if value != "max":
182
+ limit_gib = int(value) / 2**30
183
+ except (OSError, ValueError):
184
+ pass
185
+ if limit_gib is None and os.environ.get("MEMORY"):
186
+ try: # e.g. "16.0G" (decimal gigabytes)
187
+ limit_gib = float(os.environ["MEMORY"].upper().rstrip("GIB ")) * 1e9 / 2**30
188
+ except ValueError:
189
+ pass
190
+ if limit_gib is None:
191
+ return 512
192
+ return max(8, min(512, int((limit_gib - 10) * SERVING["pages_per_gib"])))
193
+
194
+
195
+ def flag_value(tokens: list[str], name: str):
196
+ """Last value given for `name` in a `vllm serve` argument list (`--x v` or `--x=v`), else None."""
197
+ value = None
198
+ for index, token in enumerate(tokens):
199
+ if token == name and index + 1 < len(tokens):
200
+ value = tokens[index + 1]
201
+ elif token.startswith(name + "="):
202
+ value = token.split("=", 1)[1]
203
+ return value
204
+
205
+
206
+ def saved_truncations(output_dataset: str) -> set:
207
+ """Ids whose saved result in data/ stopped at max_tokens and that have no saved repair.
208
+
209
+ A restarted run skips rows already in data/, so without this the pages truncated
210
+ before the restart would never reach the repair pass. Reads only three columns.
211
+ """
212
+ import fsspec
213
+ import pyarrow.parquet as pq
214
+
215
+ def records(subdir, columns):
216
+ fs, root = fsspec.core.url_to_fs(f"hf://datasets/{output_dataset}/{subdir}")
217
+ if not fs.exists(root):
218
+ return
219
+ for path in fs.glob(f"{root}/part-*.parquet"):
220
+ with fs.open(path, "rb") as handle:
221
+ yield from pq.read_table(handle, columns=columns).to_pylist()
222
+
223
+ finish = {}
224
+ for record in records("data", ["id", "error", "finish_reason"]):
225
+ if record["error"] is None:
226
+ finish[record["id"]] = record["finish_reason"]
227
+ repaired = {r["id"] for r in records("repair", ["id", "error"]) if r["error"] is None}
228
+ return {row_id for row_id, reason in finish.items() if reason == "length" and row_id not in repaired}
229
+
230
+
231
+ def max_image_tokens(longest_edge: int) -> int:
232
+ """Upper bound on the image tokens of a page fitted to longest_edge (square page)."""
233
+ side = -(-longest_edge // SERVING["patch"])
234
+ return side * side
235
+
236
+
237
+ def to_pil(value):
238
+ from PIL import Image
239
+
240
+ if isinstance(value, Image.Image):
241
+ return value
242
+ if isinstance(value, dict) and value.get("bytes"):
243
+ return Image.open(io.BytesIO(value["bytes"]))
244
+ if isinstance(value, dict) and value.get("path"):
245
+ return Image.open(value["path"])
246
+ if isinstance(value, (bytes, bytearray)):
247
+ return Image.open(io.BytesIO(value))
248
+ raise ValueError(f"unsupported image value: {type(value)}")
249
+
250
+
251
+ def page_png(value, longest_edge: int) -> bytes:
252
+ """RGB page fitted to longest_edge with LightOn's resize, as PNG bytes.
253
+
254
+ compress_level=1 instead of Pillow's default 6: PNG is lossless at every level, so the
255
+ pixels are identical, and level 1 encodes several times faster (CPU is the limit on
256
+ small flavors).
257
+ """
258
+ from lightonocr import fit
259
+
260
+ image = fit(to_pil(value).convert("RGB"), longest_edge)
261
+ buffer = io.BytesIO()
262
+ image.save(buffer, format="PNG", compress_level=1)
263
+ return buffer.getvalue()
264
+
265
+
266
+ def chat_request(model: str, png: bytes, mode: str, max_tokens: int, temperature: float, top_p: float) -> dict:
267
+ """One page as the client sends it: the image, plus the word "grounding" in grounding mode."""
268
+ from lightonocr import GROUNDING_PROMPT
269
+
270
+ url = "data:image/png;base64," + base64.b64encode(png).decode()
271
+ content = [{"type": "image_url", "image_url": {"url": url}}]
272
+ if mode == "grounding":
273
+ content.append({"type": "text", "text": GROUNDING_PROMPT})
274
+ return {
275
+ "model": model,
276
+ "messages": [{"role": "user", "content": content}],
277
+ "max_tokens": max_tokens,
278
+ "temperature": temperature,
279
+ "top_p": top_p,
280
+ "chat_template_kwargs": {"enable_thinking": False},
281
+ }
282
+
283
+
284
+ def postprocess(raw: str, mode: str, fix_dollars: bool):
285
+ """Return (markdown, layout_blocks JSON or None) for one model output, as lighton-ocr3.py."""
286
+ from lightonocr import fix_escaped_dollars, parse_blocks, to_markdown
287
+
288
+ text = fix_escaped_dollars(raw) if fix_dollars else raw
289
+ if mode != "grounding":
290
+ return text, None
291
+ blocks = parse_blocks(text)
292
+ if not blocks:
293
+ return text, json.dumps([]) # no markers parsed: keep the text so nothing is lost
294
+ return to_markdown(blocks), json.dumps([b.to_dict() for b in blocks], ensure_ascii=False)
295
+
296
+
297
+ def main():
298
+ ap = argparse.ArgumentParser(description="LightOnOCR-3 batch OCR via saturate")
299
+ ap.add_argument("input_dataset", help="Input dataset repo id (rows with an image column)")
300
+ ap.add_argument("output_dataset", help="Output dataset repo id (created private if missing)")
301
+ ap.add_argument("--model", default=SERVING["models"][0], choices=SERVING["models"])
302
+ ap.add_argument("--mode", default="plain", choices=["plain", "grounding"],
303
+ help="plain = markdown; grounding = labelled layout blocks with 0-1000 boxes")
304
+ ap.add_argument("--image-column", default="image")
305
+ ap.add_argument("--config", default=None, help="Dataset config name")
306
+ ap.add_argument("--split", default="train")
307
+ ap.add_argument("--id-column", default=None,
308
+ help="Column to use as row id (default: split-index ids)")
309
+ ap.add_argument("--max-samples", "--limit", dest="limit", type=int, default=None,
310
+ help="Process only the first N rows (smoke test)")
311
+ ap.add_argument("--max-tokens", type=int, default=SERVING["max_tokens"],
312
+ help="Output cap per page (default 4096, the model card's)")
313
+ ap.add_argument("--temperature", type=float, default=SERVING["temperature"])
314
+ ap.add_argument("--top-p", type=float, default=SERVING["top_p"],
315
+ help="Default 0.9, the model card's; LightOn's client uses 1.0")
316
+ ap.add_argument("--longest-edge", type=int, default=SERVING["longest_edge"],
317
+ help="Downscale pages to at most this many pixels on the longest edge")
318
+ ap.add_argument("--no-fix-dollars", action="store_true",
319
+ help="Keep the model's text in `markdown` without repairing escaped dollars")
320
+ ap.add_argument("--repair-max-tokens", type=int, default=0,
321
+ help="Re-send pages that hit --max-tokens once, with this cap and "
322
+ "temperature 0.1, into repair/ (default 0: off; 8192 suggested)")
323
+ ap.add_argument("--window", default="auto",
324
+ help="Pages in flight: 'auto' (saturate adapts it) or a fixed number")
325
+ ap.add_argument("--prepare-workers", type=int, default=None,
326
+ help="Threads that decode, resize and encode pages (default: CPU_CORES)")
327
+ ap.add_argument("--serve-args", default="",
328
+ help="Extra `vllm serve` flags, one quoted string, e.g. "
329
+ "\"--max-num-batched-tokens 16384\"")
330
+ ap.add_argument("--retry-errors", action="store_true",
331
+ help="Re-admit rows whose only record is an error row")
332
+ args = ap.parse_args()
333
+
334
+ user_serve_args = shlex.split(args.serve_args)
335
+ if args.longest_edge < 1:
336
+ ap.error("--longest-edge must be at least 1")
337
+ try: # --serve-args may set its own --max-model-len; vLLM uses the last one given
338
+ context = int(flag_value(user_serve_args, "--max-model-len") or SERVING["context"])
339
+ except ValueError:
340
+ ap.error("--max-model-len in --serve-args must be a whole number of tokens")
341
+ room = context - max_image_tokens(args.longest_edge) - 64
342
+ for flag, value in (("--max-tokens", args.max_tokens), ("--repair-max-tokens", args.repair_max_tokens)):
343
+ if value > room:
344
+ ap.error(f"{flag} {value} can overflow the {context}-token context with a "
345
+ f"{args.longest_edge} px page; use at most {room}")
346
+ if args.max_tokens < 1:
347
+ ap.error("--max-tokens must be at least 1")
348
+ if args.repair_max_tokens and args.repair_max_tokens <= args.max_tokens:
349
+ ap.error("--repair-max-tokens must be larger than --max-tokens")
350
+ if args.window != "auto" and not (args.window.isdigit() and int(args.window) >= 1):
351
+ ap.error("--window must be 'auto' or a number of at least 1")
352
+
353
+ import pyarrow as pa
354
+ from saturate import Auto, Engine, Fixed, dataset_rows, pump
355
+
356
+ if args.id_column is None:
357
+ ids = "index"
358
+ elif args.id_column in ("index", "content"):
359
+ # saturate reads these two names as id strategies, so a column with one of them
360
+ # needs a callable. It returns the raw value, so saturate still refuses a null id.
361
+ def ids(example):
362
+ return example[args.id_column]
363
+ else:
364
+ ids = args.id_column
365
+
366
+ rows = dataset_rows(
367
+ args.input_dataset, config=args.config, split=args.split,
368
+ columns=[args.image_column], ids=ids, limit=args.limit,
369
+ )
370
+
371
+ # Declared, so a part holding only error rows has the same columns as the rest
372
+ # (datasets.load_dataset reads every part with one schema).
373
+ schema = pa.schema([
374
+ ("id", pa.string()), ("error", pa.string()), ("markdown", pa.string()), ("raw", pa.string()),
375
+ ("finish_reason", pa.string()), ("layout_blocks", pa.string()), ("model", pa.string()),
376
+ ("prompt_tokens", pa.int64()), ("completion_tokens", pa.int64()),
377
+ ]) # fmt: skip
378
+
379
+ # Pages that hit --max-tokens, kept on local disk for the repair pass: those truncated
380
+ # in this run (stashed in parse) and those saved as truncated by an earlier, interrupted
381
+ # run (stashed as the stream passes them; the main pass skips them).
382
+ repair_dir = tempfile.mkdtemp(prefix="lighton-ocr3-repair-") if args.repair_max_tokens else None
383
+ earlier = saved_truncations(args.output_dataset) if repair_dir else set()
384
+ truncated = []
385
+
386
+ def stash(row_id, image):
387
+ path = os.path.join(repair_dir, hashlib.sha1(row_id.encode()).hexdigest() + ".png")
388
+ with open(path, "wb") as handle:
389
+ handle.write(page_png(image, args.longest_edge))
390
+ truncated.append((row_id, path))
391
+
392
+ def to_request(row):
393
+ png = page_png(row[args.image_column], args.longest_edge)
394
+ return chat_request(args.model, png, args.mode, args.max_tokens, args.temperature, args.top_p)
395
+
396
+ def make_parse(stash_truncated: bool):
397
+ def parse(row, body):
398
+ choice = body["choices"][0]
399
+ raw = (choice["message"].get("content") or "").strip()
400
+ markdown, blocks = postprocess(raw, args.mode, fix_dollars=not args.no_fix_dollars)
401
+ usage = body.get("usage") or {}
402
+ if stash_truncated and choice.get("finish_reason") == "length":
403
+ stash(row["__id"], row[args.image_column])
404
+ return {
405
+ "markdown": markdown,
406
+ "raw": raw,
407
+ "finish_reason": choice.get("finish_reason"),
408
+ "layout_blocks": blocks,
409
+ "model": args.model,
410
+ "prompt_tokens": usage.get("prompt_tokens"),
411
+ "completion_tokens": usage.get("completion_tokens"),
412
+ }
413
+ return parse
414
+
415
+ def with_ids(source):
416
+ # Keep each row's id on the row, so parse can name the page it stashes for repair.
417
+ for row_id, row in source:
418
+ if row_id in earlier:
419
+ stash(row_id, row[args.image_column])
420
+ yield row_id, {**row, "__id": row_id}
421
+
422
+ cap = window_cap()
423
+ if args.window == "auto":
424
+ window = Auto(initial=min(64, cap), max_limit=cap)
425
+ print(f"window: auto, at most {cap} pages in flight (host memory)", file=sys.stderr)
426
+ else:
427
+ window = Fixed(int(args.window))
428
+ if int(args.window) > cap:
429
+ print(f"warning: --window {args.window} is above the {cap} pages this machine's "
430
+ "memory allows; the Job may run out of memory", file=sys.stderr)
431
+ cores = max(1, int(float(os.environ.get("CPU_CORES") or "4")))
432
+ workers = args.prepare_workers if args.prepare_workers is not None else cores
433
+ extra = [
434
+ "--max-model-len", str(SERVING["context"]),
435
+ *SERVING["serve_args"],
436
+ *user_serve_args,
437
+ ]
438
+ # Several API server processes share the image decoding and preprocessing, which one
439
+ # process cannot keep up with on a fast GPU. Only where there are cores to spare.
440
+ if cores >= SERVING["api_servers_min_cores"] and flag_value(extra, "--api-server-count") is None:
441
+ extra += ["--api-server-count", str(SERVING["api_servers"])]
442
+ print(f"server: --api-server-count {SERVING['api_servers']} ({cores} CPU cores)", file=sys.stderr)
443
+
444
+ output = f"hf://datasets/{args.output_dataset}/data"
445
+ with Engine(args.model, engine="vllm", extra_args=extra) as endpoint:
446
+ stats = pump(with_ids(rows) if repair_dir else rows, to_request, make_parse(bool(repair_dir)),
447
+ endpoint, output, window=window, prepare_workers=workers,
448
+ retry_errors=args.retry_errors, schema=schema)
449
+ print("LIGHTON_OCR3_SATURATE " + stats.to_json(), flush=True)
450
+
451
+ if repair_dir and truncated:
452
+ print(f"repair: re-sending {len(truncated)} pages that hit --max-tokens "
453
+ f"with a cap of {args.repair_max_tokens}", file=sys.stderr, flush=True)
454
+
455
+ def repair_rows():
456
+ for row_id, path in truncated:
457
+ with open(path, "rb") as handle:
458
+ yield row_id, {"png": handle.read()}
459
+
460
+ def repair_request(row):
461
+ return chat_request(args.model, row["png"], args.mode, args.repair_max_tokens,
462
+ SERVING["repair_temperature"], args.top_p)
463
+
464
+ repair_stats = pump(repair_rows(), repair_request, make_parse(False), endpoint,
465
+ f"hf://datasets/{args.output_dataset}/repair", window=window,
466
+ retry_errors=args.retry_errors, schema=schema)
467
+ print("LIGHTON_OCR3_SATURATE_REPAIR " + repair_stats.to_json(), flush=True)
468
+
469
+ print(f"https://huggingface.co/datasets/{args.output_dataset} "
470
+ f"({stats.rows_processed} ok, {stats.rows_failed} error rows, "
471
+ f"{len(truncated) if repair_dir else 'n/a'} truncated pages re-sent to repair/)", file=sys.stderr)
472
+
473
+
474
+ if __name__ == "__main__":
475
+ main()
lighton-ocr3.py CHANGED
@@ -49,6 +49,10 @@ Run on your own GPU (vLLM and torch come from the image on Jobs, so add them her
49
 
50
  For large scans with very small type, try a higher --longest-edge and --max-tokens.
51
 
 
 
 
 
52
  The image is pinned to vLLM 0.30.0 because LightOn's client reports that vLLM 0.27.1
53
  makes the models loop and 0.30.0 is the version they test. Loosen the pin once a newer
54
  vLLM is checked against the same outputs.
 
49
 
50
  For large scans with very small type, try a higher --longest-edge and --max-tokens.
51
 
52
+ For large runs use lighton-ocr3-saturate.py: same model, prompts and sampling, served by
53
+ vLLM with many pages in flight (measured 2.4x the pages per second on a10g-small, 5.7x on
54
+ a100-large), with resumable output.
55
+
56
  The image is pinned to vLLM 0.30.0 because LightOn's client reports that vLLM 0.27.1
57
  makes the models loop and 0.30.0 is the version they test. Loosen the pin once a newer
58
  vLLM is checked against the same outputs.
models.json CHANGED
@@ -390,6 +390,29 @@
390
  "image": "vllm/vllm-openai:v0.30.0",
391
  "notes": "Bucket sibling of lighton-ocr3.py (same model, prompt, sampling). Input/output: hf://buckets/... URLs via bucketbag v0.3.1 (no mount) or directories. Reads .jp2; resume-by-skip."
392
  },
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
393
  "lighton-ocr2-server.py": {
394
  "model_id": "lightonai/LightOnOCR-2-1B",
395
  "params": "1B",
 
390
  "image": "vllm/vllm-openai:v0.30.0",
391
  "notes": "Bucket sibling of lighton-ocr3.py (same model, prompt, sampling). Input/output: hf://buckets/... URLs via bucketbag v0.3.1 (no mount) or directories. Reads .jp2; resume-by-skip."
392
  },
393
+ "lighton-ocr3-saturate.py": {
394
+ "model_id": "lightonai/LightOnOCR-3-0.8B",
395
+ "params": "0.8B (or 4B via --model)",
396
+ "backend": "saturate (in-job vllm serve + saturate pump)",
397
+ "image": "vllm/vllm-openai:v0.30.0",
398
+ "task": "ocr",
399
+ "output": "markdown; --mode grounding adds labelled layout blocks with 0-1000 boxes (layout_blocks JSON column)",
400
+ "license": "apache-2.0",
401
+ "notes": "Large-run sibling of lighton-ocr3.py: same prompt modes, sampling and page resize; LightOn's serve flags (--max-model-len 18000) plus --max-num-batched-tokens 16384, and 4 vLLM API servers when CPU_CORES >= 12. Window capped by host memory. Measured 2026-11-05 (0.8B, 600 pages, steady state): a10g-small 2.2 pages/s, a100-large 7.2, rtx-pro-6000 10.0 (about $0.08 per 1,000 pages); lighton-ocr3.py: 0.90 and 1.27. Not LightOnOCR-3-1B.",
402
+ "languages": {
403
+ "evidence": "not-stated",
404
+ "notes": "LightOnOCR-3 cards give no language list (LightOnOCR-2 named 11)."
405
+ },
406
+ "support": "core",
407
+ "jobs": {
408
+ "image": "vllm/vllm-openai:v0.30.0",
409
+ "flavor": "a10g-small",
410
+ "timeout": "4h",
411
+ "secrets": [
412
+ "HF_TOKEN"
413
+ ]
414
+ }
415
+ },
416
  "lighton-ocr2-server.py": {
417
  "model_id": "lightonai/LightOnOCR-2-1B",
418
  "params": "1B",