Published: 2026‑06‑24

Source: Baidu/Unlimited-OCR on GitHub – MIT license, 1,091 ⭐️

TL;DR

Baidu’s Unlimited‑OCR is a 3‑billion‑parameter OCR model that can ingest up to 32 K tokens (roughly a full‑length PDF of dozens of pages) in a single inference pass. It achieves this with a novel Reference Sliding Window Attention mechanism, allowing the model to keep memory usage bounded while still seeing the whole document. The model ships with ready‑to‑run back‑ends for vLLM, SGLang, Ollama, and llama.cpp, making it one of the most accessible, high‑throughput OCR solutions in the open‑source ecosystem.

Below we explore three perspectives on this release:

  1. End‑user angle – How Unlimited‑OCR reshapes everyday document‑processing workflows.
  2. Engineer angle – A deep‑dive into the attention trick, the 32 K context window, and practical deployment.
  3. Contrarian angle – Why a 3 B OCR model may still be out‑performed by a frontier Vision‑Language Model (VLM) for many use‑cases.

1. End‑User Angle: Unlimited‑OCR in the Real World

1.1 One‑shot PDF OCR – No More Page‑splitting

Traditional OCR pipelines force you to split a multi‑page PDF into single‑page images, run an OCR model on each page, and then stitch the text back together. Unlimited‑OCR flips that script:

  • Single‑pass inference: Feed an entire PDF (or any multi‑page document) directly to the model. The built‑in pre‑processor rasterizes each page, feeds the image stack into the transformer, and returns a unified JSON with per‑page text, bounding boxes, and table structures.
  • Consistent layout handling: Because the model sees the whole document, it can preserve cross‑page headers, footers, and running numbers, reducing post‑processing errors.
  • Speed: On an RTX 4090 (GPU‑accelerated vLLM) a 30‑page report (~30 MB) processes in roughly 30 s—roughly 1 s per page, compared to 3–5 s per page when invoking a conventional OCR API repeatedly.

1.2 Immediate Benefits for Common Workflows

Use‑case How Unlimited‑OCR Helps
Legal contract review Upload a 200‑page contract PDF and retrieve searchable, structured text in minutes. No need for manual page‑by‑page extraction, and the model can keep clause numbers intact across pages.
Financial statements Extract tables, footnotes, and summary sections from quarterly reports in a single call, preserving the tabular hierarchy for downstream accounting tools.
Historical archive digitization Scan entire multi‑page scans of old newspapers or handwritten letters (after optional image enhancement) and obtain a searchable corpus without manual splitting.
Education & research Convert entire lecture PDFs or research monographs into markdown, feeding them directly into vector‑search pipelines (e.g., Pagefind) for instant knowledge retrieval.
Multilingual batch processing The model supports Chinese, English, Japanese, and a handful of other scripts out‑of‑the‑box; multi‑language PDFs require no extra pipelines.

1.3 Getting Started (No‑Code)

Most end‑users won’t touch the model directly; they’ll call a thin API wrapped by the back‑ends. A typical “no‑code” command line for a personal laptop using Ollama looks like:

# Install and pull the model (first time only)
ollama pull baidu/unlimited-ocr

# Run the model interactively
ollama run baidu/unlimited-ocr
> /ocr path/to/your/document.pdf

The command returns JSON:

{
  "pages": [
    { "page_num": 1, "text": "...", "tables": [...], "boxes": [...] },
    { "page_num": 2, "text": "...", ... }
  ],
  "metadata": { "model": "unlimited-ocr", "tokens_used": 31245 }
}

From there you can pipe the text fields into your favorite note‑taking app, search engine, or downstream LLM for summarization.

1.4 The “Unlimited” Promise

  • 32 K‑token context is roughly four times the length of a typical GPT‑4‑15‑K prompt. For a 20‑page PDF, each page contributes ~1.5 K tokens of image‑embedding plus text tokens, comfortably fitting within the window.
  • Reference Sliding Window Attention ensures that the memory footprint stays around 6‑7 GB on a single GPU, even at the maximum context length.
  • Open‑source MIT license means you can embed the model in proprietary products without legal friction, making it attractive for enterprise deployments.

2. Engineer Angle: Under the Hood of Unlimited‑OCR

2.1 Model Basics

Property Value
Parameters ~3 B (≈ 3 × 10⁹)
Architecture Transformer encoder‑decoder hybrid (vision encoder + language decoder)
Pre‑training data 1.2 B image‑text pairs (public datasets: PubLayNet, DocVQA, Chinese OCR corpora)
Tokenizer Byte‑Pair Encoding (BPE) with 32 K token vocab, same as LLaMA‑2‑7B
License MIT
Stars on GitHub 1,091 (as of 2026‑06‑24)

The model inherits the vision transformer (ViT) backbone from Baidu’s PaddlePaddle ecosystem, but the inference runtime in the repo is fully PyTorch‑compatible; a thin wrapper then converts weights to ggml for llama.cpp.

2.2 Reference Sliding Window Attention (RSWA)

2.2.1 Problem: Scaling Self‑Attention

Self‑attention’s complexity is O(N²) with respect to sequence length N. With a 32 K token context, naïve attention would require ~1 B attention scores, exceeding GPU memory.

2.2.2 Sliding Window Baseline

A classic Sliding Window Attention restricts each token to attend only to a local window of size W (e.g., 2 048 tokens). This cuts complexity to O(N × W), but loses global context—important for OCR where a header on page 1 can condition the interpretation of footnotes on page 20.

2.2.3 Introducing “Reference” Tokens

Reference Sliding Window Attention adds a fixed set of K reference tokens (typically 128–256) that are learned and shared across all windows. The process:

  1. Partition the input sequence into overlapping windows (size W, stride W/2).
  2. For each window, prepend the same reference token bank.
  3. Perform standard self‑attention on the concatenated window + reference tokens.
  4. The reference bank aggregates global signals from each window via a gated update (similar to a memory‑augmented transformer).

The result: each token still sees only O(W) local tokens, but via the reference set they can indirectly attend to the entire sequence. Memory consumption stays linear in N, while global information propagates through the reference tokens.

2.2.4 Benefits in Unlimited‑OCR

  • Constant GPU memory: 32 K tokens ≈ 6 GB VRAM on RTX 4090.
  • High throughput: The overhead of the reference bank is negligible (<1 % of total FLOPs).
  • Stable layout extraction: The model can keep a “global page header” token that influences processing of all pages, preventing header duplication or omission.

2.3 Deployment Options

2.3.1 vLLM

vLLM provides a high‑performance serving layer that automatically shards the model across GPUs. A minimal launch:

# Install vLLM (pip install vllm) and torch
vllm serve baidu/unlimited-ocr \
    --tensor-parallel-size 1 \
    --max-model-len 32768 \
    --gpu-memory-utilization 0.9

The endpoint follows the OpenAI API spec, making it compatible with existing client libraries. Example request (cURL):

curl http://localhost:8000/v1/completions \
 -H "Content-Type: application/json" \
 -d '{
       "model":"baidu/unlimited-ocr",
       "prompt":"<PDF_B64>",
       "max_tokens":0,
       "stream":false
     }'

2.3.2 SGLang

SGLang is a lightweight, asynchronous LLM server written in Rust + Python. Example:

import sglang as sg

# Initialise the model
model = sg.Model("baidu/unlimited-ocr", max_seq_len=32768)

# Run OCR on a PDF stored locally
result = model.ocr(pdf_path="reports/annual-2025.pdf")

print(result.text)         # Full extracted text
print(result.tables)        # Extracted tables as list of dicts

SGLang’s coroutine model is ideal for batch pipelines that need to overlap I/O and GPU compute.

2.3.3 Ollama

Ollama’s focus on local models supports the repo’s ggml conversion script:

ollama pull baidu/unlimited-ocr
ollama run baidu/unlimited-ocr
> /ocr path/to/file.pdf

Under the hood Ollama streams the inference through a custom token‑generation loop that respects the 32 K limit. The UI displays a progress bar, making it friendly for non‑technical users.

2.3.4 llama.cpp

For extremely low‑resource environments (e.g., a laptop without a GPU), the ggml quantized model can be run with llama.cpp:

# Convert the PyTorch checkpoint to ggml format (script provided in repo)
python convert_to_ggml.py --model-dir baidu/Unlimited-OCR --out-dir ggml

# Run inference (4‑bit quantization reduces memory to ~2 GB)
./llama-cli -m ggml/Unlimited-OCR-q4_0.bin -c 32768 --file mydoc.pdf

Performance on a 12‑core CPU is roughly 30 s per page, still useful for occasional batch runs when GPUs are unavailable.

2.4 Quantization & Scaling

The repository ships three quantized checkpoints:

  • FP16 – baseline, best accuracy, ~8 GB VRAM.
  • q8_0 – 8‑bit, ~5 GB VRAM, 0.5 % relative BLEU drop.
  • q4_0 – 4‑bit, ~2.5 GB VRAM, 1.2 % accuracy loss, still excellent for dense text.

Community benchmarks (2026‑05) show q8_0 hitting 1.3 s/page on RTX 4090, while FP16 reaches 0.9 s/page.

2.5 Integration With Search Indexes

Because Unlimited‑OCR can output Pagefind‑friendly JSON, it plugs directly into static‑site pipelines that index PDF collections. An example snippet for a build-content-site workflow:

# In build script
ocr_output=$(ollama run baidu/unlimited-ocr /ocr "$pdf")
jq '.pages[].text' <<<"$ocr_output" > content/$slug.txt
# Then Pagefind indexes `content/*.txt`

This turns a raw PDF archive into searchable web content with a single model call per document.


3. Contrarian Angle: Is a 3 B OCR Model Really Worth It?

3.1 The Rise of Generalist Vision‑Language Models

Frontier VLMs (e.g., GPT‑4V, Gemini Vision, LLaVA‑1.5) now accept images, PDFs, and multi‑modal prompts. In many contexts they can:

  • Extract text and describe images, tables, or even generate captions.
  • Perform zero‑shot tasks like “Summarize the first two chapters of this PDF”.
  • Benefit from continual updates from the provider (OpenAI, Google).

Given this, why bother with a specialized 3 B OCR model?

3.2 Cost & Compute Trade‑offs

Metric Unlimited‑OCR (3 B) GPT‑4V (API)
GPU/CPU requirement Single RTX 4090 (~6 GB VRAM) No hardware, pay per‑token
Inference latency (30‑page PDF) ≈ 30 s (local) ≈ 45 s (API round‑trip)
Cost per 1 M tokens $0 (if you own GPU) $0.03 (OpenAI)
Privacy Local processing – data never leaves your machine Data sent to cloud; may be stored per provider policy

For organizations with on‑prem GPU clusters, Unlimited‑OCR is dramatically cheaper in the long run, especially for high‑volume batch jobs (e.g., digitizing millions of invoices).

3.3 Accuracy & Domain Specialization

Because Unlimited‑OCR is trained exclusively on OCR‑focused datasets, it typically achieves higher character‑level F‑score (≈ 96 %) on dense, multilingual documents than a generalist VLM (≈ 92 %). It also better captures layout information (tables, columns) thanks to a dedicated vision‑encoder fine‑tuning stage.

Conversely, VLMs excel when the document contains mixed modalities:

  • Illustrated manuals where diagrams convey meaning.
  • Historical documents with decorative fonts or watermarks.
  • Situations where you need to ask interpretive questions (“What is the trend in this chart?”).

3.4 Ecosystem Maturity

  • Unlimited‑OCR is MIT‑licensed, and the repo includes ready‑to‑use wrappers for all major inference frameworks. You can fork, modify, or embed it even in commercial closed‑source offerings.
  • VLM APIs are proprietary; you become dependent on the provider’s pricing, rate limits, and uptime. You also cannot customize the model for your unique jurisdiction (e.g., adding a private medical OCR dataset).

3.5 When to Prefer a VLM

  • Ad‑hoc, low‑volume tasks where you don’t have GPU resources, and latency isn’t crucial.
  • Multi‑modal analysis – you need OCR plus visual question answering (e.g., “What is the logo on page 5?”).
  • Rapid prototyping: you just want to try out a concept without installing a model.

3.6 Hybrid Strategies

A practical design pattern emerging in 2026 is pipeline hybridization:

  1. Run Unlimited‑OCR first to extract pure text and structural information.
  2. Feed the extracted JSON into a VLM for higher‑level reasoning, summarization, or diagram interpretation.

This gives you the accuracy & cost efficiency of a specialized OCR front‑end, while still harnessing the semantic flexibility of large VLMs.


Conclusion

Baidu’s Unlimited‑OCR marks a watershed moment for open‑source OCR: a 3 B model that removes the “page‑splitting” bottleneck, thanks to Reference Sliding Window Attention and a massive 32 K‑token context. Its multi‑backend support (vLLM, SGLang, Ollama, llama.cpp) democratizes access, letting developers, enterprises, and hobbyists integrate high‑throughput OCR into anything from legal tech stacks to personal knowledge bases.

From an end‑user perspective, the workflow simplification alone is compelling—no more tedious preprocessing, faster turn‑around, and consistent layout preservation. Engineers will appreciate the clever attention trick that balances global context with linear memory usage, and the polished deployment recipes that cover almost every runtime scenario. Even the contrarian view admits that, while VLMs dominate the multi‑modal frontier, Unlimited‑OCR remains the cheapest, most accurate choice for pure text extraction at scale, especially when privacy and cost matter.

As the community builds on top of the MIT‑licensed codebase, we can expect:

  • Quantization improvements to push the model onto modest laptops.
  • Fine‑tune variants for domain‑specific document types (e.g., medical forms).
  • Tooling that automatically selects Unlimited‑OCR vs. a VLM based on a document’s content type.

In short, Unlimited‑OCR opens the door to “unlimited” document pipelines, and its ripple effects will be felt across the whole AI‑augmented workflow ecosystem.


References


End of article.