GabrielPimenta99 commited on
Commit
1dd8850
Β·
verified Β·
1 Parent(s): d220277

Update README.md

Browse files
Files changed (1) hide show
  1. README.md +148 -75
README.md CHANGED
@@ -2,123 +2,196 @@
2
  license: other
3
  language:
4
  - pt
5
- task_categories:
6
- - image-text-to-text
 
 
7
  tags:
8
  - ocr
9
- - benchmark
10
  - document-understanding
 
 
 
 
 
11
  - brazilian-portuguese
12
- - text-recognition
13
- - handwriting-recognition
14
- - legal-documents
15
- size_categories:
16
- - n<1K
17
  ---
18
 
19
- # DharmaOCR-Benchmark
20
 
21
  <p align="center">
22
  <img src="dharma_logo.png" width="200" alt="Dharma-AI Logo"/>
23
  </p>
24
 
25
- ## Overview
26
 
27
- **DharmaOCR-Benchmark** is a 496-instance evaluation suite for OCR models, focused on text extraction in **Brazilian Portuguese**. It covers printed text, handwritten text, and legal/administrative documents β€” domains that are underrepresented in existing large-scale OCR benchmarks such as OCRBench and olmOCR-Bench.
28
 
29
- This benchmark was introduced alongside the [DharmaOCR](https://huggingface.co/dharma-ai/DharmaOCR-Lite) family of models. It is designed to evaluate not only transcription quality, but also **text degeneration rate** and **unit inference cost** as first-class metrics.
30
 
31
- ## Motivation
32
 
33
- Existing OCR benchmarks are not designed to reflect the constraints of Brazilian Portuguese document OCR. In preliminary analyses, performance on general-purpose benchmarks did not reliably predict performance in this setting, where language-specific orthography, domain vocabulary, and document formatting can shift the error profile and amplify text degeneration.
 
 
 
 
 
34
 
35
- DharmaOCR-Benchmark addresses this gap by providing a dedicated evaluation protocol for this domain.
36
 
37
- ## Dataset Composition
 
 
 
 
 
 
 
 
 
 
38
 
39
- | Subset | Samples | Source | Description |
40
- |---|---|---|---|
41
- | **ESTER-Pt** | 363 | [Santos et al., 2023](https://link.springer.com/chapter/10.1007/978-3-031-41679-8_21) | Public benchmark for text recognition in Brazilian Portuguese |
42
- | **Legal** | 83 | Internal curation | Legal and administrative documents from publicly available sources |
43
- | **BRESSAY** | 50 | [Neto et al., 2024](https://link.springer.com/chapter/10.1007/978-3-031-70543-4_18) | Handwritten text recognition in Brazilian Portuguese |
44
- | **Total** | **496** | | |
45
 
46
- ### Labeling
47
 
48
- - **ESTER-Pt** and **BRESSAY**: Labels from their original published benchmarks.
49
- - **Legal**: Two-stage labeling pipeline inspired by olmOCR-Bench methodology β€” labels produced by multiple LLMs, followed by a **complete manual audit** of all 83 instances.
 
 
 
 
 
 
 
 
 
 
50
 
51
- ## Evaluation Protocol
52
 
53
- ### Score
54
 
55
- The **DharmaOCR-Benchmark Score** is defined as:
56
 
57
  ```
58
  score = (LevenshteinRatio + BLEU) / 2
59
  ```
60
 
61
- | Component | What it captures |
62
- |---|---|
63
- | `LevenshteinRatio` | Character-level fidelity (misspellings, missing accents, punctuation errors) |
64
- | `BLEU` | N-gram sequence preservation (reorderings, dropped spans) |
65
 
66
- ### Additional Metrics
67
 
68
- Beyond transcription quality, the benchmark tracks:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
69
 
70
- - **Text degeneration rate (%):** Percentage of requests that hit the output-token limit *and* exhibit repeated text spans (detected via n-gram repetition criterion). This is a critical operational metric β€” degenerate requests inflate cost, increase latency, and reduce throughput for all concurrent requests.
71
 
72
- - **Unit cost per page:** Enables fair comparison between self-hosted models and commercial APIs.
 
 
 
 
 
 
 
73
 
74
- ## Inference Protocol
75
 
76
- To ensure reproducibility, all models are evaluated under a standardized setup:
77
 
78
- | Parameter | Value |
79
- |---|---|
80
- | **GPU** | NVIDIA L40S (48GB GDDR6) |
81
- | **Instance** | AWS g6e.2xlarge |
82
- | **Engine** | vLLM |
83
- | **Max output tokens** | 8,192 |
84
- | **Temperature** | 0 |
85
 
86
- Cost for local models is estimated from average time per page Γ— hourly infrastructure cost. Cost for commercial APIs uses public pricing (March 2026).
87
 
88
- ## Benchmark Results
89
 
90
- | Model | Score | Degeneration (%) | Type |
91
- |---|---|---|---|
92
- | **DharmaOCR Full** (7B) | **0.925** | **0.40** | Open-source (ours) |
93
- | **DharmaOCR Lite** (3B) | **0.911** | **0.20** | Open-source (ours) |
94
- | Claude Opus 4.6 | 0.833 | β€” | Commercial |
95
- | Qwen3-VL-8B | 0.829 | 5.65 | Open-source |
96
- | olmOCR-2-7B | 0.823 | 1.41 | Open-source |
97
- | Gemini 3.1 Pro | 0.820 | β€” | Commercial |
98
- | Nanonets-OCR2-3B | 0.791 | 2.62 | Open-source |
99
- | GPT-5.4 | 0.750 | β€” | Commercial |
100
- | Dots OCR | 0.738 | 6.85 | Open-source |
101
- | GLM-OCR | 0.710 | 11.69 | Open-source |
102
- | Google Vision | 0.686 | β€” | Commercial |
103
- | gemma-3-4b-it | 0.654 | 4.03 | Open-source |
104
- | Google Document AI | 0.640 | β€” | Commercial |
105
- | GPT-4o | 0.635 | β€” | Commercial |
106
- | Amazon Textract | 0.618 | β€” | Commercial |
107
- | Mistral OCR 3 | 0.574 | β€” | Commercial |
108
-
109
- ## Usage
110
 
111
- ```python
112
- from datasets import load_dataset
113
 
114
- dataset = load_dataset("dharma-ai/DharmaOCR-Benchmark")
115
- ```
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
116
 
117
- ## Important Notes
118
 
119
- - This benchmark was **not used** for training, model selection, DPO pair construction, or quantization calibration of any DharmaOCR model.
120
- - The benchmark is primarily designed for **Brazilian Portuguese** document OCR evaluation. Using it to evaluate models on other languages is not recommended.
121
- - Text degeneration detection uses a combined criterion: (1) the request hits the configured output-token limit, and (2) repeated text spans are detected via n-gram analysis.
122
 
123
  ## Citation
124
 
 
2
  license: other
3
  language:
4
  - pt
5
+ - en
6
+ library_name: transformers
7
+ base_model: Nanonets/Nanonets-OCR2-3B
8
+ pipeline_tag: image-text-to-text
9
  tags:
10
  - ocr
 
11
  - document-understanding
12
+ - structured-extraction
13
+ - dpo
14
+ - sft
15
+ - awq
16
+ - specialized-small-language-model
17
  - brazilian-portuguese
18
+ datasets:
19
+ - dharma-ai/DharmaOCR-Benchmark
 
 
 
20
  ---
21
 
22
+ # DharmaOCR Lite
23
 
24
  <p align="center">
25
  <img src="dharma_logo.png" width="200" alt="Dharma-AI Logo"/>
26
  </p>
27
 
28
+ ## Introduction
29
 
30
+ **DharmaOCR Lite** is a 3B-parameter Specialized Small Language Model (SSLM) for structured OCR, developed by [Dharma-AI](https://dharma-ai.com). It is designed to extract text from document images into a structured JSON format with explicit `header`, `text`, `footer`, and `margin` fields.
31
 
32
+ DharmaOCR Lite achieves **state-of-the-art performance** on [DharmaOCR-Benchmark](https://huggingface.co/datasets/dharma-ai/DharmaOCR-Benchmark), outperforming all evaluated open-source and commercial baselines β€” including GPT-4o, GPT-5.4, Claude Opus 4.6, Gemini 3.1 Pro, Google Document AI, Amazon Textract, and olmOCR-2-7B β€” while being significantly cheaper and faster to run.
33
 
34
+ ### Key Highlights
35
 
36
+ - **Score: 0.911** on DharmaOCR-Benchmark (highest among all 3B models, surpasses all commercial APIs evaluated)
37
+ - **Text degeneration rate: 0.20%** β€” the lowest across all models tested
38
+ - **~34% relative cost** compared to olmOCR-2-7B vanilla (reference baseline)
39
+ - **1.464s average time per page** on an NVIDIA L40S GPU
40
+ - Trained with a novel **SFT + DPO** pipeline, where DPO is applied to OCR for the first time to explicitly reduce text degeneration
41
+ - **AWQ-quantized** (FP8) for efficient deployment with negligible quality loss
42
 
43
+ ## Model Details
44
 
45
+ | Attribute | Value |
46
+ |---|---|
47
+ | **Base model** | [Nanonets-OCR2-3B](https://huggingface.co/Nanonets/Nanonets-OCR2-3B) |
48
+ | **Architecture** | Qwen2.5-VL-3B-Instruct (decoder-only VLM) |
49
+ | **Parameters** | ~3B |
50
+ | **Training pipeline** | SFT β†’ DPO β†’ AWQ Quantization (FP8) |
51
+ | **Output format** | Structured JSON (`header`, `text`, `footer`, `margin`) |
52
+ | **Primary language** | Brazilian Portuguese |
53
+ | **Context length** | 8,192 tokens (generation limit) |
54
+ | **Precision** | FP8 (AWQ) |
55
+ | **License** | Apache 2.0 |
56
 
57
+ ## Performance
 
 
 
 
 
58
 
59
+ ### DharmaOCR-Benchmark Results
60
 
61
+ | Model | Score | Degeneration Rate (%) | Time/Page (s) |
62
+ |---|---|---|---|
63
+ | **DharmaOCR Lite (ours)** | **0.911** | **0.20** | **1.464** |
64
+ | DharmaOCR Full (ours, 7B) | 0.925 | 0.40 | 2.132 |
65
+ | olmOCR-2-7B (vanilla) | 0.823 | 1.41 | 4.306 |
66
+ | Nanonets-OCR2-3B (vanilla) | 0.791 | 2.62 | 1.911 |
67
+ | Claude Opus 4.6 | 0.833 | β€” | β€” |
68
+ | Gemini 3.1 Pro | 0.820 | β€” | β€” |
69
+ | GPT-5.4 | 0.750 | β€” | β€” |
70
+ | GPT-4o | 0.635 | β€” | β€” |
71
+ | Google Document AI | 0.640 | β€” | β€” |
72
+ | Amazon Textract | 0.618 | β€” | β€” |
73
 
74
+ > **DharmaOCR Lite (3B) outperforms olmOCR-2-7B (7B)** β€” a model with more than twice as many parameters β€” by ~10% in benchmark score, while being ~3Γ— faster and ~66% cheaper per page.
75
 
76
+ ### Benchmark Score Definition
77
 
78
+ The DharmaOCR-Benchmark Score is defined as:
79
 
80
  ```
81
  score = (LevenshteinRatio + BLEU) / 2
82
  ```
83
 
84
+ where `LevenshteinRatio` captures character-level fidelity and `BLEU` measures n-gram sequence preservation.
 
 
 
85
 
86
+ ## Quickstart
87
 
88
+ ```python
89
+ from transformers import Qwen2_5_VLForConditionalGeneration, AutoProcessor
90
+ from qwen_vl_utils import process_vision_info
91
+ from PIL import Image
92
+
93
+ model_name = "dharma-ai/DharmaOCR-Lite"
94
+
95
+ model = Qwen2_5_VLForConditionalGeneration.from_pretrained(
96
+ model_name,
97
+ torch_dtype="auto",
98
+ device_map="auto",
99
+ )
100
+ processor = AutoProcessor.from_pretrained(model_name)
101
+
102
+ # Load your document image
103
+ image_path = "document.png"
104
+
105
+ messages = [
106
+ {
107
+ "role": "user",
108
+ "content": [
109
+ {"type": "image", "image": image_path},
110
+ {"type": "text", "text": "Extract the text from this image."},
111
+ ],
112
+ }
113
+ ]
114
+
115
+ text = processor.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
116
+ image_inputs, video_inputs = process_vision_info(messages)
117
+ inputs = processor(
118
+ text=[text],
119
+ images=image_inputs,
120
+ videos=video_inputs,
121
+ padding=True,
122
+ return_tensors="pt",
123
+ ).to(model.device)
124
+
125
+ generated_ids = model.generate(**inputs, max_new_tokens=8192)
126
+ generated_ids_trimmed = [
127
+ out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
128
+ ]
129
+ output_text = processor.batch_decode(
130
+ generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
131
+ )[0]
132
+
133
+ print(output_text)
134
+ ```
135
 
136
+ ### Expected Output Format
137
 
138
+ ```json
139
+ {
140
+ "header": "DOCUMENT TITLE | Page 1",
141
+ "margin": null,
142
+ "footer": "Journal Name, Vol. X, pp. 1-10, 2025.",
143
+ "text": "Full main body text extracted from the document..."
144
+ }
145
+ ```
146
 
147
+ Fields that are not present in the original document are returned as `null`.
148
 
149
+ ## Serving with vLLM
150
 
151
+ ```bash
152
+ vllm serve dharma-ai/DharmaOCR-Lite \
153
+ --gpu-memory-utilization 0.90 \
154
+ --max-model-len 65536 \
155
+ --max-num-batched-tokens 32000
156
+ ```
 
157
 
158
+ ## Training Details
159
 
160
+ ### Pipeline
161
 
162
+ 1. **Supervised Fine-Tuning (SFT):** Full fine-tuning on ~39,680 pages of diverse document types (printed, handwritten, tables, forms, mixed layouts) predominantly in Brazilian Portuguese. Labels were generated by large LLMs (Claude Sonnet 4, Llama 4 Maverick, Gemini 2.5 Pro) and validated by human reviewers.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
163
 
164
+ 2. **Direct Preference Optimization (DPO):** A novel application of DPO to OCR β€” degenerate model outputs were explicitly used as *rejected* examples to penalize looping/repetitive behavior. Preference pairs were constructed from 5 candidate responses per document, scored by Qwen3-VL-235B as judge, and filtered through a multi-stage policy combining Selective-DPO principles and reward-margin analysis. Final dataset: 49,170 preference pairs.
 
165
 
166
+ 3. **AWQ Quantization (FP8):** Activation-aware weight quantization preserving visual encoder and output layer in full precision. Reduces cost by ~12% with minimal quality degradation (score: 0.921 β†’ 0.911).
167
+
168
+ ### Infrastructure
169
+
170
+ - **SFT:** 1Γ— NVIDIA H200, 24 CPU cores, 256 GB RAM
171
+ - **DPO:** 4Γ— NVIDIA H200, 96 CPU cores, 1024 GB RAM
172
+ - **Hyperparameters:** Effective batch size 32, AdamW optimizer, cosine LR schedule
173
+
174
+ ## Why DPO for OCR?
175
+
176
+ Text degeneration β€” where models get stuck in repetitive loops β€” is a critical but underreported problem in OCR systems. It's not just a quality issue: degenerate requests consume disproportionate GPU time, reduce throughput for *all* concurrent requests, and inflate costs.
177
+
178
+ DharmaOCR Lite applies DPO to reduce degeneration by **87.6%** relative to SFT-only training (from 1.61% β†’ 0.20%), the largest reduction observed across all model families tested.
179
+
180
+ ## DharmaOCR-Benchmark
181
+
182
+ We release [DharmaOCR-Benchmark](https://huggingface.co/datasets/dharma-ai/DharmaOCR-Benchmark), a 496-instance evaluation suite for OCR in Brazilian Portuguese covering:
183
+
184
+ - **ESTER-Pt** (363 samples): Printed text recognition
185
+ - **Legal** (83 samples): Legal and administrative documents
186
+ - **BRESSAY** (50 samples): Handwritten text recognition
187
+
188
+ The benchmark evaluates transcription quality, text degeneration rate, and unit inference cost under a unified protocol.
189
 
190
+ ## Limitations
191
 
192
+ - **Language focus:** Primarily optimized for Brazilian Portuguese documents. Performance on other languages may vary.
193
+ - **Field repetition:** The model may occasionally repeat header/footer content within the `text` field. A post-processing step checking exact matches resolves >80% of occurrences.
194
+ - **Domain scope:** Best results on printed, handwritten, and legal/administrative documents. Highly specialized layouts (e.g., complex engineering drawings) are not covered.
195
 
196
  ## Citation
197