aziz9788's picture
Initial commit
cf8c8d4
|
Raw History Blame Contribute Delete
12.7 kB

OCR Architectures Toolkit

One folder per leading open-source OCR architecture, each with the same building blocks: weights download, official code pinned to a commit, data conversion to that framework's format, and training / inference entry points for Windows (PowerShell) and Linux (bash).

The goal is to compare architectures on equal terms: same data, same prompts, same scoring. For how the architectures differ and how to choose between them, read docs/architectures.md.


Architectures at a glance

# Architecture Family Params Vision tokens / page Official training code Fine-tune here with
01 OvisOCR2 / OvisOCR3 A · autoregressive VLM 0.85B ~200–8,100 (32×32 px each) No common.vlm_sft (LoRA fits 8 GB)
02 FD-RL A · autoregressive VLM + RL recipe 4.4B 32×32 px each SFT command only LLaMA-Factory config, common.vlm_sft
03 olmOCR 2 A · autoregressive VLM 8.3B 28×28 px each Yes (SFT + GRPO) Official trainer
04 Qwen-VL official trainer Base models for 01–03, 08 0.8–7B 28 or 32 px Yes qwen-vl-finetune
05 GOT-OCR 2.0 A · compressed encoder + small LLM 0.56B fixed 256 per 1024² Yes Official DeepSpeed, ms-swift
06 Nougat A · encoder–decoder, no LLM 0.35B fixed 896×672 input Yes Official Lightning trainer
07 MinerU-Diffusion B · block-diffusion VLM 2.5B 4–2,048 No Inference only
08 DODO B · AR → diffusion conversion 3B 28×28 px each No (no weights) Base model only
09 PP-OCRv6 C · detector + recognizer 1–19M n/a (line crops) Yes Official PaddleOCR trainer
10 PaddleOCR-VL A + layout detector 0.96B native resolution Not verified Inference
11 dots.ocr A · layout + text in one pass 3.0B native resolution No Inference
12 DeepSeek-OCR A · optical token compression 3.3B 64–400+ by mode No Inference
13 Consensus Entropy D · multi-model wrapper — — n/a Data-quality filter

Families: A autoregressive end-to-end vision-language model · B block-diffusion vision-language model · C text detector + line recognizer · D training-free wrapper around other models.


Repository layout

common/                    shared, framework-independent code
  paths.py                 folder layout (all outputs under ./data by default, git-ignored)
  data_prep.py             datasets -> canonical JSONL -> qwenvl | llamafactory | swift | olmocr | nougat | paddle_rec
  vlm_sft.py               full / LoRA fine-tuning for every Qwen-family OCR model (transformers + peft)
  vlm_infer.py             crash-safe, resumable inference (one page at a time)
  score.py                 character error rate, strict and folded, plus loop / truncation counts
  selfplay.py              discrepancy-aware self-play after SFT (trains on the tokens still wrong)
  self_distill.py          on-policy self-distillation: BlinkOPD (sharper view, eyes-closed contrast) or GT teacher
  grpo.py, rewards.py      GRPO / GRPD with verifiable OCR rewards (CER, tag closure, tables, LaTeX, loops)
  credit.py                per-line credit: align a reading to the ground truth, score each line
  select_data.py           sieve broken labels, balance sources, pick hard or uncertain records
  merge_adapter.py         merge one or more LoRA updates at chosen strengths (grafting / task arithmetic)
  vlm_utils.py             shared helpers for the recipes above
  mdpbench.py              MDPBench: page subsets, prediction, official scorer (own uv env), collapse checks
  replay.py                replay pages in other languages (real + synthetic), optionally self-labelled
  photo_aug.py             make clean pages look photographed (perspective, light, shadow, blur, JPEG)
  experiment.py            YAML-driven, resumable experiments: data -> baseline -> runs -> leaderboard
run_mdpbench.py            reproduce a paper's MDPBench row (like run_omnidocbench_ocr.py for OmniDocBench)
experiments/
  arabic_mdpbench/         improve Arabic on MDPBench without losing other languages (quick.yaml, full.yaml)
  download.py              Hugging Face weight download with a --dry-run size check
  upstream.py              clone official repositories at the commits in upstream.lock.json
  render_config.py         fills ${OCR_*} folder placeholders in upstream configs
  env.ps1, env.sh          shared setup sourced by every script
architectures/NN_name/     one folder per architecture
  README.md                architecture, training recipe, strengths, limitations, scripts
  download.py              weights for this architecture
  train*.ps1 / train*.sh   training entry points (+ upstream config templates)
  infer*.ps1 / infer*.sh   inference + scoring, where applicable
recipes/
  data_efficient.ps1/.sh   sieve -> balance -> SFT -> hard cases -> self-play -> GRPO -> merge sweep
configs/
  sources.example.yaml     template describing your datasets for data_prep
docs/
  architectures.md         how the architectures differ and how to choose
  finetuning_recipes.md    data-efficient fine-tuning recipes, the evidence behind them, how to run them
upstream.lock.json         official repositories and pinned commits
requirements.txt           dependencies of common/

Quick start

Requires uv, Git, and an NVIDIA GPU. Commands run from the repository root. All installs use uv (no pip).

1. Install the shared dependencies

uv venv .venv-arch --python 3.12
.venv-arch\Scripts\activate            # Linux: source .venv-arch/bin/activate
uv pip install torch torchvision --index-url https://download.pytorch.org/whl/cu128
uv pip install -r requirements.txt

Framework-specific packages (LLaMA-Factory, PaddleOCR, Nougat, olmOCR, ms-swift) are installed with uv pip by the training script that needs them, from the pinned upstream checkout.

2. Describe your data

copy configs\sources.example.yaml configs\sources.yaml     # Linux: cp
# edit configs/sources.yaml: Parquet paths, image/text columns, page or line level, licence
python -m common.data_prep --sources configs/sources.yaml --limit 200 --formats hf   # smoke test
python -m common.data_prep --sources configs/sources.yaml --formats hf               # full conversion

3. Download a model and get a baseline

python architectures/01_ovisocr/download.py --dry-run          # size check, downloads nothing
python architectures/01_ovisocr/download.py --only OvisOCR3
powershell -ExecutionPolicy Bypass -File architectures\01_ovisocr\infer.ps1     # Linux: bash architectures/01_ovisocr/infer.sh

4. Fine-tune and compare

powershell -ExecutionPolicy Bypass -File architectures\01_ovisocr\train_lora.ps1
$env:ADAPTER = "data/runs/ovisocr3-lora-r16"
powershell -ExecutionPolicy Bypass -File architectures\01_ovisocr\infer.ps1

5. Go further with less data

$env:MODEL = "data/models/OvisOCR3"
powershell -ExecutionPolicy Bypass -File recipes\data_efficient.ps1     # Linux: MODEL=... bash recipes/data_efficient.sh

The pipeline adds label checks, hard-case selection, self-play, GRPO with format rewards and a merge sweep after SFT. Each stage, the papers behind it and its memory use are in docs/finetuning_recipes.md.

6. Benchmark and run experiments

python -m common.mdpbench setup                          # official MDPBench scorer, pinned, own uv env
python run_mdpbench.py ovisocr3                          # reproduce the paper's MDPBench row first
python -m common.experiment experiments/arabic_mdpbench/quick.yaml

An experiment trains several techniques from one YAML file, scores each on the same MDPBench pages with the official scorer, and ranks them; see experiments/arabic_mdpbench.

Every download.py accepts --dry-run and --only. python -m common.upstream --list shows every pinned upstream repository.


Windows and Linux support

Every script that can run on Windows ships as a .ps1 next to its .sh. Scripts that exist only as .sh depend on Linux-only components; run them on a Linux server or under WSL2.

Component Windows Linux Why
common/* (data prep, SFT, inference, scoring) ✅ ✅ plain PyTorch + transformers
OvisOCR LoRA / inference, FD-RL LoRA ✅ ✅ common.vlm_sft, common.vlm_infer
GOT-OCR ms-swift, Nougat, PP-OCRv6 ✅ .ps1 ✅ single-GPU upstream trainers
FD-RL LLaMA-Factory, Qwen-VL trainer, GOT official, OvisOCR full FT WSL2 ✅ DeepSpeed / multi-GPU NCCL
olmOCR trainer WSL2 ✅ flash-attn

Notes:

  • On Turing GPUs (RTX 20xx) PyTorch reports bf16 as supported, but it is emulated and several times slower. common.vlm_sft uses bf16 only on compute capability 8.0+ (Ampere and newer) and fp32 otherwise.
  • Qwen3.5-based models (OvisOCR) have no fast linear-attention kernels on Windows; training works but is slower than on Linux.

Data format

Every exporter reads the same canonical record:

Field Meaning
id <source>_<split>_<index>
image absolute path to the image file
text target: Markdown for pages (tables as HTML, formulas as LaTeX), plain text for lines
source, license, language provenance; licences travel with the data
level page or line (selects the prompt and which exporters use the record)
split train, validation, test, or eval (evaluation only, never trained on)

Prompts: pages use the FD-RL prompt ("Extract the main content … tables to HTML."); lines use "Transcribe the text in this image exactly." Both are in common/data_prep.py. Every script accepts --prompt / --prompt-file to replace the page prompt (OvisOCR ships its own in prompts/); line records keep the line prompt (vlm_sft and vlm_infer also take --line-prompt).


Status and testing

Tested How
All weight repositories resolve download.py --dry-run for every folder
All six export formats common.data_prep on page and line datasets
PP-OCRv6 config generation make_config.py against the pinned PaddleOCR configs
LoRA training + inference OvisOCR3, 8 GB GPU, Windows: peak 6.8 GB, loss decreasing, adapter reloaded for inference
Upstream checkouts common.upstream at every pinned commit
Fine-tuning recipes self-play, self-distillation, GRPO, data selection and merging on OvisOCR3, 8 GB GPU, Windows: all train, save and reload; fp32 merges match the scaled adapter exactly

| Core logic | python -m pytest tests -q: 23 CPU tests (token alignment, rewards, CER, benchmark sampling, score parsing, bootstrap, selection) | | MDPBench harness | official scorer (pinned) on real pages, per-language and per-page scores; dev/test split, baseline, four techniques and the leaderboard on a tiny experiment |

Not yet run end to end: the multi-GPU Linux trainers (LLaMA-Factory, Qwen-VL, GOT official, olmOCR), the ms-swift, Nougat and PaddleOCR trainers. Treat their first run as a smoke test and report issues.


Adding an architecture

  1. Create architectures/NN_name/ with a README.md following an existing folder (at-a-glance table, how it works, how it is trained, strengths, limitations, scripts).
  2. Add download.py with a MODELS dict and cli(MODELS).
  3. If official code exists, pin it in upstream.lock.json (URL + full commit hash) and fetch it with common.upstream.
  4. Add train.ps1 + train.sh (source common/env.ps1 / common/env.sh). Put machine paths in configs as ${OCR_*} placeholders.
  5. Add the row to the table above and to docs/architectures.md.

Licences

This toolkit contains only our scripts. Upstream code and model weights keep their own licences, listed in each architecture folder. Check dataset licences (recorded per record) before commercial use.