WaveSpeedAI

How to Run Unlimited-OCR on Multi-Page PDFs

Run Unlimited-OCR on images and multi-page PDFs with Transformers, SGLang serving, validation and production failure controls.

By Dora12 min read
How to Run Unlimited-OCR on Multi-Page PDFs

I searched “​how to use Unlimited-OCR​” because I wanted one thing: a repeatable PDF OCR path that does not turn a 40-page scan into 40 unrelated text files with mystery gaps between them.

This is a work note for teams doing document parsing, scanned PDF cleanup, archive conversion, or OCR evaluation before wiring the model into a product. The commands below follow the official Unlimited OCR 2 path checked on November 23, 2026. The repository switched to this model after the original July draft. I have not run a GPU inference for this revision, so the commands are a setup and acceptance path, not a reported benchmark. The 32K output limit used in the local example is a test setting, not a promise that every GPU will run it cleanly.

Prerequisites and Safety Checks

Start from the official Unlimited-OCR GitHub repository. Do not copy commands from random blog snippets first. Its release notes now include the October 27, 2026 release of Unlimited OCR 2.

Clone the repo, then inspect the files that matter:

git clone https://github.com/baidu/Unlimited-OCR.git
cd Unlimited-OCR
git rev-parse HEAD
ls

The working surfaces are:

  • README.md for the official examples and current dependency versions.
  • infer.py for the repository’s SGLang benchmark client.
  • wheel/ for the custom SGLang wheel.
  • utils/process_unlimitedOCR2.py for converting raw layout output to Markdown.
  • LICENSE for the repository’s MIT license.
  • The model ID baidu/Unlimited-OCR-2 for weight loading.

The Unlimited OCR 2 model card lists the model as Image-Text-to-Text, multilingual, MIT licensed, and custom code, with 3B parameters and BF16 weights. That is enough to plan the environment, not enough to skip a local smoke test.

The uncomfortable bit is trust_remote_code=True. Unlimited OCR 2 uses custom model code. Hugging Face’s Transformers documentation says this setting executes code from the model repository locally, so I treat it like running a downloaded program. Review the modeling files and pin a model revision before production.

I paused here.

Temporary files matter too. A PDF-to-image OCR run creates page images on disk. If the source PDF contains contracts, IDs, medical files, invoices, or customer records, the temp directory is part of the data boundary. Put it somewhere controlled. Do not leave page PNGs in /tmp on a shared machine and call the job private.

Run a Single-Image Test

The single-image path is the fastest way to find environment errors before touching a PDF. It tests weight loading, custom code, CUDA, output writing, and OCR tags.

  1. Create and activate an isolated environment. The current README reports a Transformers test with Python 3.10 and specific package versions on an NVIDIA A800-80GB. That is a documented test environment, not a minimum GPU specification.
python3.10 -m venv .venv
source .venv/bin/activate
python -m pip install --upgrade pip
  1. Install​ the packages from the current README. Start with its versions, then change one dependency at a time if your environment requires it.
pip install torch==2.13.0 torchvision pillow transformers==4.52.1 \
  huggingface-hub==0.36.0 tokenizers==0.21.4 \
  addict==2.4.0 einops==0.8.2 easydict==1.13 \
  pymupdf==1.27.2.2
  1. Put ​one page​​ image in the ​repo​​ folder. Use a page with visible headings, a table, and a line near the margin. A perfect sample hides layout bugs. The small PDF fixture in the next section also creates page_0001.png for this step.
  2. Run the Transformers ​OCR​​ smoke test.
from pathlib import Path
import torch
from transformers import AutoModel, AutoTokenizer

model_name = "baidu/Unlimited-OCR-2"
Path("outputs").mkdir(exist_ok=True)

tokenizer = AutoTokenizer.from_pretrained(
    model_name, trust_remote_code=True
)
model = AutoModel.from_pretrained(
    model_name,
    trust_remote_code=True,
    use_safetensors=True,
    torch_dtype=torch.bfloat16,
).eval().cuda()

text = model.infer(
    tokenizer,
    image_file="page_0001.png",
    output_path="outputs/smoke",
    save_results=True,
)
print(text[:500])
  1. Validate the output before moving on. I check five things: text exists, reading order is plausible, headings are not repeated, table cells have not become one long sentence, and no footer line appears five times. Repetition is the first failure mode I would look for.

In the current README, single-page infer uses dynamic tiling by default. Multi-page infer_multi uses base mode and returns page markers in order. Keep those two paths separate while testing.

Process a Multi-Page PDF

For PDF OCR, render the pages to images first, then pass those images to infer_multi in page order. This keeps the input order explicit and gives you a way to inspect a bad page render.

  1. Make a small test PDF. The following PyMuPDF fixture has a table on page 1 and a rasterized, scanned-style page 2. It also writes page_0001.png for the single-image test above. This is a proposed fixture script; I have not claimed an OCR result from it.
import fitz

doc = fitz.open()
page = doc.new_page()
page.insert_text((50, 80), "OCR TEST PAGE 1", fontsize=18)

for x in (50, 300, 400):
    page.draw_line((x, 130), (x, 210))
for y in (130, 170, 210):
    page.draw_line((50, y), (400, y))
page.insert_text((60, 155), "Item")
page.insert_text((310, 155), "Qty")
page.insert_text((60, 195), "Widget A")
page.insert_text((310, 195), "2")

scan_source = fitz.open()
scan_page = scan_source.new_page()
scan_page.insert_text((50, 80), "SCANNED PAGE 2", fontsize=18)
scan_page.insert_text((50, 120), "Invoice 0042")
scan_pixels = scan_page.get_pixmap(matrix=fitz.Matrix(2, 2))

scanned_page = doc.new_page()
scanned_page.insert_image(scanned_page.rect, pixmap=scan_pixels)
doc.save("ocr_fixture.pdf")
doc[0].get_pixmap(matrix=fitz.Matrix(2, 2)).save("page_0001.png")

with fitz.open("ocr_fixture.pdf") as check:
    assert len(check) == 2
    assert check[0].get_text().strip()
    assert not check[1].get_text().strip()

scan_source.close()
doc.close()
  1. Render the PDF to numbered page images. The repository uses PyMuPDF through fitz. PyMuPDF’s page-rendering documentation also shows Page.get_pixmap() for this job.
import os
import shutil
import tempfile
import fitz

def pdf_to_images(pdf_path, dpi=300, temp_root=None):
    if temp_root is not None:
        os.makedirs(temp_root, exist_ok=True)

    tmp_dir = tempfile.mkdtemp(prefix="pdf_ocr_", dir=temp_root)
    doc = None

    try:
        doc = fitz.open(pdf_path)
        mat = fitz.Matrix(dpi / 72, dpi / 72)
        paths = []

        for i, page in enumerate(doc):
            out = os.path.join(tmp_dir, f"page_{i + 1:04d}.png")
            page.get_pixmap(matrix=mat).save(out)
            paths.append(out)

        return paths, tmp_dir
    except Exception:
        shutil.rmtree(tmp_dir, ignore_errors=True)
        raise
    finally:
        if doc is not None:
            doc.close()
  1. Send those images to ​infer_multi​​ in the same order. Run this in the same Python session as the model-loading code above.
from pathlib import Path

page_images, tmp_dir = pdf_to_images(
    "ocr_fixture.pdf",
    dpi=300,
    temp_root="./controlled_tmp",
)

try:
    raw_text, token_count = model.infer_multi(
        tokenizer,
        image_files=page_images,
        output_path="./outputs/pdf_run",
        max_length=32768,
        save_results=True,
    )
    Path("outputs/pdf_run.txt").write_text(raw_text, encoding="utf-8")
finally:
    shutil.rmtree(tmp_dir, ignore_errors=True)
  1. Check page boundaries and expected content. Unlimited OCR 2 returns raw layout text with <PAGE> markers; that text is ​not yet ​Markdown​. For the two-page fixture, this check should either pass or tell you exactly what needs review:
from pathlib import Path

raw = Path("outputs/pdf_run.txt").read_text(encoding="utf-8")
assert raw.count("<PAGE>") == 2, "Missing or extra page marker"
assert "Widget A" in raw, "Table item needs review"
assert "SCANNED PAGE 2" in raw, "Scanned page needs review"
print("Review passed for page count and test text.")

Those exact-text checks are intentionally strict. An OCR miss should fail the check, not be quietly described as a successful run. To produce Markdown, follow the repository’s post-processing instructions; keep the raw file for comparison.

  1. Split long documents when needed. infer_multi can use context across pages in one request. If memory or output limits force smaller ranges, record the page range for each output and merge only after every range passes review:
from pathlib import Path

Path("raw_ranges").mkdir(exist_ok=True)

for start in range(0, len(page_images), 8):
    batch = page_images[start:start + 8]
    raw, _ = model.infer_multi(
        tokenizer,
        image_files=batch,
        max_length=32768,
        save_results=False,
    )
    name = f"pages_{start + 1:04d}_{start + len(batch):04d}.txt"
    Path("raw_ranges", name).write_text(raw, encoding="utf-8")

Run that range loop before deleting ​tmp_dir in a real script. A range boundary can interrupt a table or paragraph that continues onto the next page, so compare boundary pages before joining the output. The 32K setting here is a chosen test limit; inspect truncation and memory use on your own hardware.

Serve Unlimited-OCR with SGLang

SGLang is the path I would use when OCR needs a service boundary instead of a notebook. The current README uses a custom SGLang wheel and an OpenAI-compatible /v1/chat/completions endpoint.

  1. Create the SGLang environment from the ​repo​​ checkout. The old wheel and kernels pin in the July draft no longer match the current README.
uv venv --python 3.10
source .venv/bin/activate

uv pip install wheel/sglang-0.5.20.dev13+g75b9b06b02-py3-none-any.whl
uv pip install pymupdf==1.27.2.2 fastokens==0.3.2 requests
  1. Start the server. These are the current README’s Unlimited OCR 2 settings. Bind to 127.0.0.1 for a local test; add an approved access boundary before exposing a document-processing service to other machines.
export SGLANG_UOCR_EANABLE_DOC_LIMIT=1
export SGLANG_UOCR_DOC_GUNDAM_PAGE_WINDOW=10
export SGLANG_UOCR_DOC_BASE_PAGE_WINDOW=10
export SGLANG_UOCR_MAX_PAGE_TOKENS=20000
export SGLANG_OPT_UOCR_SAM_REL_POS_BIAS_MB=64
export SGLANG_UOCR_SHM_WRAP_MODEL_DATA=1
export SGLANG_UOCR_SHM_WRAP_MIN_MB=1
export SGLANG_VLM_CACHE_SIZE_MB=0
export PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True

python -m sglang.launch_server \
  --model-path baidu/Unlimited-OCR-2 \
  --served-model-name Unlimited-OCR-2 \
  --chat-template unlimited-ocr \
  --tokenizer-backend fastokens \
  --tokenizer-worker-num 8 \
  --mem-fraction-static 0.7 \
  --max-running-requests 64 \
  --max-prefill-tokens 2048 \
  --enable-custom-logit-processor \
  --enable-streaming-session \
  --allow-auto-truncate \
  --disable-radix-cache \
  --mm-preprocess-cache-size-mb 0 \
  --cuda-graph-backend-decode full --cuda-graph-max-bs-decode 64 \
  --cuda-graph-backend-prefill full \
  --cuda-graph-max-bs-prefill 16384 \
  --cuda-graph-bs-prefill 1024 2048 \
  --cuda-graph-config '{"prefill": {"backend": "full", "full_prefill_max_req": 64}}' \
  --host 127.0.0.1 \
  --port 10000

The environment variable really is spelled EANABLE in the current README. Keep the repo revision in your run log so a later correction does not silently change this setup.

  1. ​Submit a two-page request to ​/v1/chat/completions​. This retains the original streaming approach but uses the current model ID, page prompt, positive output budget, and Unlimited OCR 2 fields.
import base64
import json
from pathlib import Path
import requests
from sglang.srt.sampling.custom_logit_processor import (
    DeepseekOCRNoRepeatNGramLogitProcessor,
)

server_url = "http://127.0.0.1:10000"

def encode_image(path):
    with open(path, "rb") as file:
        data = base64.b64encode(file.read()).decode("utf-8")
    return {
        "type": "image_url",
        "image_url": {"url": f"data:image/png;base64,{data}"},
    }

page_paths = ["page_0001.png", "page_0002.png"]
content = [encode_image(path) for path in page_paths]
content.append({
    "type": "text",
    "text": "<PAGE><image>" * len(page_paths) + "Multi page parsing.",
})

payload = {
    "model": "Unlimited-OCR-2",
    "messages": [{"role": "user", "content": content}],
    "max_tokens": 16000,
    "temperature": 0,
    "skip_special_tokens": False,
    "images_config": {"crop_mode": False},
    "custom_logit_processor": DeepseekOCRNoRepeatNGramLogitProcessor.to_str(),
    "custom_params": {
        "ngram_size": 35,
        "window_size": 1024,
        "page_token_id": 128827,
        "eos_token_id": 1,
        "max_page_tokens": 20000,
    },
    "stream": True,
}

response = requests.post(
    f"{server_url}/v1/chat/completions",
    headers={"Content-Type": "application/json"},
    data=json.dumps(payload),
    timeout=6000,
    stream=True,
)
response.raise_for_status()

chunks = []
for line in response.iter_lines(decode_unicode=True):
    if not line or not line.startswith("data:"):
        continue

    data = line[len("data:"):].strip()
    if data == "[DONE]":
        break

    event = json.loads(data)
    choices = event.get("choices") or []
    if not choices:
        continue

    delta = (choices[0].get("delta") or {}).get("content") or ""
    if delta:
        chunks.append(delta)

raw_text = "".join(chunks)
Path("raw").mkdir(exist_ok=True)
Path("raw/pdf_run.txt").write_text(raw_text, encoding="utf-8")

The request expects page_0002.png as well as page_0001.png; render both from ocr_fixture.pdf with pdf_to_images and use the returned paths when running it. Then convert the raw output:

python utils/process_unlimitedOCR2.py --infer-dir raw --out-dir outputs
  1. Store outputs outside the request process. For queues, I use a job ID, page range, source checksum, model revision, config hash, output path, and status. The repo’s infer.py is a benchmark client; inspect its assumptions before adapting it into a production queue.

Production Limits and Recovery

Retry and Partial Output Controls

Do not retry the whole PDF by default. Store page images or page ranges as units of work. If page 37 fails in a range, rerun that range with the same neighboring pages when cross-page continuity matters. Reprocessing the full document makes output diffs noisy.

The minimal state record is plain: document_id, source_hash, page_range, image_path, prompt, crop_mode, max_length or max_tokens, ngram_window, model_revision, attempt_count, status, and output_path.

If output repeats, lower the blast radius first. Mark the range failed, save the raw model text, and rerun with the same inputs after checking the image render. Do not silently patch repeated lines unless the downstream system labels them as edited OCR.

Sensitive File and Logging Controls

The risk is not only the original PDF. It is the rendered images, base64 request bodies, streamed chunks, logs, retries, and failed outputs.

For sensitive document parsing, keep temp images in an encrypted workspace or short-lived job directory. Do not log base64 payloads. Do not put raw OCR text into application logs unless the log store is approved for the same data class as the source file.

Audit logs should say what happened without copying the whole document. Store hashes, page numbers, config, error type, and output file references. The actual files belong in controlled storage.

FAQ

How should failed pages resume without reprocessing the full document?

Render the PDF into stable page images and track each page range as a job. Resume the failed range using the same source hash, model revision, settings, and neighboring pages where continuity matters. Keep the original page order and merge only after all ranges pass validation.

Can SGLang clients reuse existing OpenAI-compatible request handling?

Mostly, yes. Existing clients can point at the SGLang base URL and call /v1/chat/completions. The OCR request still needs multimodal content plus Unlimited OCR 2 fields such as images_config and the custom no-repeat parameters shown above. The transport can be reused. The request builder still needs OCR-specific logic.

Where should temporary PDF images be stored securely?

Use a controlled job directory, not a casual shared temp folder. For regulated files, put rendered images on encrypted local disk or an approved object store with short retention. Delete page images after output validation unless audit rules require retention.

What should teams log for reproducible OCR failures?

Log the document hash, page range, rendered image hashes, model ID, model revision, prompt, crop_mode, output budget, n-gram settings, server version, attempt number, error class, and output pointer. Avoid logging full document text or base64 image bodies. This is where my data ends.

Conclusion

That is how to use Unlimited-OCR without turning a PDF run into a loose pile of scripts. Start with a single image. Convert PDF pages with stable names. Use infer_multi for ordered multi-page parsing. Serve with SGLang when the workflow needs queues, retries, and shared access. Keep raw layout output, validate page boundaries, and convert to Markdown only after that check. The 32K setting is a test choice, not a hardware promise.


Previous posts:

Share