zhkleciel ruke1ire commited on
Commit
c013d55
·
0 Parent(s):

Super-squash branch 'main' using huggingface_hub

Browse files

Co-authored-by: ruke1ire <ruke1ire@users.noreply.huggingface.co>

.gitattributes ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
5
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
6
+ *.ftz filter=lfs diff=lfs merge=lfs -text
7
+ *.gz filter=lfs diff=lfs merge=lfs -text
8
+ *.h5 filter=lfs diff=lfs merge=lfs -text
9
+ *.joblib filter=lfs diff=lfs merge=lfs -text
10
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
+ *.model filter=lfs diff=lfs merge=lfs -text
13
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
14
+ *.npy filter=lfs diff=lfs merge=lfs -text
15
+ *.npz filter=lfs diff=lfs merge=lfs -text
16
+ *.onnx filter=lfs diff=lfs merge=lfs -text
17
+ *.ot filter=lfs diff=lfs merge=lfs -text
18
+ *.parquet filter=lfs diff=lfs merge=lfs -text
19
+ *.pb filter=lfs diff=lfs merge=lfs -text
20
+ *.pickle filter=lfs diff=lfs merge=lfs -text
21
+ *.pkl filter=lfs diff=lfs merge=lfs -text
22
+ *.pt filter=lfs diff=lfs merge=lfs -text
23
+ *.pth filter=lfs diff=lfs merge=lfs -text
24
+ *.rar filter=lfs diff=lfs merge=lfs -text
25
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
26
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
28
+ *.tar filter=lfs diff=lfs merge=lfs -text
29
+ *.tflite filter=lfs diff=lfs merge=lfs -text
30
+ *.tgz filter=lfs diff=lfs merge=lfs -text
31
+ *.wasm filter=lfs diff=lfs merge=lfs -text
32
+ *.xz filter=lfs diff=lfs merge=lfs -text
33
+ *.zip filter=lfs diff=lfs merge=lfs -text
34
+ *.zst filter=lfs diff=lfs merge=lfs -text
35
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ sample_image.png filter=lfs diff=lfs merge=lfs -text
37
+ lfm2_vl_450m_metrics.png filter=lfs diff=lfs merge=lfs -text
LICENSE ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ LFM Open License v1.0
2
+
3
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
4
+
5
+ 1. Definitions.
6
+
7
+ "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by this document.
8
+
9
+ "Licensor" shall mean Liquid AI, Inc.
10
+
11
+ "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
12
+
13
+ "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
14
+
15
+ "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
16
+
17
+ "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
18
+
19
+ "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work.
20
+
21
+ "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
22
+
23
+ "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
24
+
25
+ "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
26
+
27
+ "Commercial Use" shall mean any use of the Work for direct or indirect commercial advantage or monetary compensation.
28
+
29
+ "Qualified Non-Profit Organization" shall mean a Legal Entity that is organized and operated exclusively for religious, charitable, scientific, testing for public safety, literary, or educational purposes, and which is exempt from federal income tax under Section 501(c)(3) of the United States Internal Revenue Code of 1986, as amended, or any equivalent non-profit or charitable organization in a foreign jurisdiction.
30
+
31
+ "Non-Commercial or Research Purposes" shall mean purposes that do not involve any use of the Work or a Derivative Work for Commercial Use.
32
+
33
+ "Threshold" shall mean annual revenue of 10 million United States dollars ($10,000,000) or more.
34
+
35
+ 2. Grant of Copyright License. Subject to the terms and conditions of this License, including the Commercial Use limitation set forth in Section 5, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
36
+
37
+ 3. Grant of Patent License. Subject to the terms and conditions of this License, including the Commercial Use limitation set forth in Section 5, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
38
+
39
+ 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
40
+
41
+ (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and
42
+
43
+ (b) You must cause any modified files to carry prominent notices stating that You changed the files; and
44
+
45
+ (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
46
+
47
+ (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
48
+
49
+ You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
50
+
51
+ 5. Commercial Use Limitation.
52
+
53
+ (a) The rights granted under this License for Commercial Use are conditioned upon You or Your Legal Entity not exceeding the Threshold.
54
+
55
+ (b) Any Commercial Use of the Work or a Derivative Work by a Legal Entity that exceeds the Threshold is not licensed under this Agreement.
56
+
57
+ (c) The Threshold shall not apply to a Qualified Non-Profit Organization's use of the Work or a Derivative Work for Non-Commercial or Research Purposes.
58
+
59
+ 6. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
60
+
61
+ 7. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except for the reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
62
+
63
+ 8. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
64
+
65
+ 9. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
66
+
67
+ 10. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
68
+
69
+ 11. Termination. This License will terminate automatically and immediately if You fail to comply with any of its terms and conditions. Upon termination, You must cease all use of the Work and any Derivative Works and delete all copies in Your possession.
70
+
71
+ END OF TERMS AND CONDITIONS
README.md ADDED
@@ -0,0 +1,216 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ library_name: transformers
3
+ license: other
4
+ license_name: lfm1.0
5
+ license_link: LICENSE
6
+ language:
7
+ - en
8
+ pipeline_tag: image-text-to-text
9
+ tags:
10
+ - liquid
11
+ - lfm2.5
12
+ - lfm2
13
+ - edge
14
+ - vision
15
+ base_model: LiquidAI/LFM2.5-VL-450M
16
+ ---
17
+ <center>
18
+ <div style="text-align: center;">
19
+ <img
20
+ src="https://cdn-uploads.huggingface.co/production/uploads/61b8e2ba285851687028d395/2b08LKpev0DNEk6DlnWkY.png"
21
+ alt="Liquid AI"
22
+ style="width: 100%; max-width: 100%; height: auto; display: inline-block; margin-bottom: 0.5em; margin-top: 0.5em;"
23
+ />
24
+ </div>
25
+ <div style="display: flex; justify-content: center; gap: 0.5em;">
26
+ <a href="https://playground.liquid.ai/chat?model=lfm2.5-vl-450m"><strong>Try LFM</strong></a> • <a href="https://docs.liquid.ai/lfm/getting-started/welcome"><strong>Docs</strong></a> • <a href="https://leap.liquid.ai/"><strong>LEAP</strong></a> • <a href="https://discord.com/invite/liquid-ai"><strong>Discord</strong></a>
27
+ </div>
28
+ </center>
29
+
30
+ <br>
31
+
32
+ # LFM2.5-VL-450M-Extract
33
+
34
+ **LFM2.5-VL-450M-Extract** extracts user-defined fields from images and returns them as **JSON**. It is Liquid AI's first vision model in the [Liquid Nanos](https://huggingface.co/collections/LiquidAI/liquid-nanos) collection—compact, task-specific models built for production workflows—and extends the Extract family alongside [LFM2-350M-Extract](https://huggingface.co/LiquidAI/LFM2-350M-Extract) for text documents.
35
+
36
+ You specify what to extract as a YAML field list in the system prompt, and the model returns a JSON object with those fields. Structured outputs integrate cleanly with rule-based systems and downstream pipelines. Use it out of the box or fine-tune for domain-specific extraction.
37
+
38
+ ## ⚙️ How it works
39
+
40
+ You specify what to extract as a YAML field list in the system prompt, and the model returns a JSON object with those fields. Structured outputs integrate cleanly with rule-based systems and downstream pipelines. Use it out of the box or fine-tune for domain-specific extraction.
41
+
42
+ - **System prompt**:
43
+
44
+ ```yaml
45
+ wood_color: The overall coloration of the wood surface
46
+ wood_texture: The tactile quality of the wood surface
47
+ wood_pattern: The partern types visible on the wood surface
48
+ ```
49
+
50
+ - **User prompt**:
51
+ <img src="https://huggingface.co/LiquidAI/LFM2.5-VL-450M-Extract/resolve/main/sample_image.png" width="300">
52
+
53
+ - **Output**:
54
+ ```yaml
55
+ {
56
+ "wood_color": "light to medium brown",
57
+ "wood_texture": "smooth with visible grain",
58
+ "wood_pattern": "parallel, irregular, wavy"
59
+ }
60
+ ```
61
+
62
+ Our model supports the enum feature, which lets you provide a list of possible choices alongside the field description as follows, and the model will return one of the listed values as its answer.
63
+
64
+ - **System prompt**:
65
+
66
+ ```yaml
67
+ wood_color: The overall coloration of the wood surface, such as blue, red, or light tan
68
+ wood_texture: The tactile quality of the wood surface, select from smooth, rough, or grainy
69
+ wood_pattern: The partern types visible on the wood surface, e.g., straight, wavy, or curly
70
+ ```
71
+
72
+ ## 🌟 Use cases
73
+
74
+ - Detecting safety-critical events in images (e.g. fallen person, fire, leakage) to trigger automated safety systems.
75
+ - Collecting statistical information about objects across video frames for analytics pipelines.
76
+ - Auto-tag product images with structured attributes for Retail/E-commerce.
77
+
78
+ ## 📄 Model details
79
+
80
+ | Property | Detail |
81
+ |---|---:|
82
+ | **Parameters (LM only)** | 350M |
83
+ | **Vision encoder** | SigLIP2 (~100M, [SigLIP-2 paper](https://arxiv.org/abs/2502.14786)) |
84
+ | **Backbone layers** | hybrid conv+attention |
85
+ | **Image input** | Single image, dynamic resolution |
86
+ | **Context** | 128,000 tokens |
87
+ | **Vocab size** | 65,536 (text) |
88
+ | **Precision** | bfloat16 |
89
+ | **License** | LFM Open License v1.0 |
90
+
91
+ ## 📊 Performance
92
+
93
+ We evaluated LFM2.5-VL-450M-Extract on a 2,000-sample benchmark of
94
+ `(image, schema, JSON)` triples, with reference labels generated by an
95
+ ensemble of frontier multimodal models. Predictions are scored on the
96
+ following three dimensions:
97
+
98
+ - **JSON Validity** — share of samples producing strict-parseable JSON
99
+ - **Schema Consistency F1 Score** — set-level F1 over predicted vs requested field names, macro-averaged across samples
100
+ - **VLM Judge Score** — match against the image directly, judged by a separate vision model ([Qwen/Qwen3.5-35B-A3B](https://huggingface.co/Qwen/Qwen3.5-35B-A3B))
101
+
102
+ <img src="https://huggingface.co/LiquidAI/LFM2.5-VL-450M-Extract/resolve/main/lfm2_vl_450m_metrics.png" width="800">
103
+
104
+ | Model | Params | JSON Validity | F1 Score | VLM Judge Score |
105
+ |---|---:|---:|---:|---:|
106
+ | **LFM2.5-VL-450M-Extract** | **0.45B** | **98.9** | **98.8** | **84.5** |
107
+ | LFM2.5-VL-450M | 0.45B | 97.7 | 93.5 | 73.4 |
108
+ | SmolVLM-500M-Instruct | 0.51B | 33.0 | 26.6 | 12.2 |
109
+ | FastVLM-0.5B | 0.76B | 22.5 | 19.3 | 16.3 |
110
+ | Qwen3.5-0.8B | 0.87B | 96.4 | 96.3 | 82.3 |
111
+ | InternVL3_5-1B | 1.06B | 98.0 | 96.5 | 80.7 |
112
+ | MiniCPM-V-4.6 | 1.30B | 61.8 | 60.4 | 57.5 |
113
+ | *(ref) InternVL3_5-2B* | 2.35B | 99.6 | 99.2 | 87.7 |
114
+ | *(ref) Qwen3.5-2B* | 2.27B | 97.9 | 97.7 | 89.7 |
115
+ | *(ref) gemma-4-E2B-it* | 2.3B | 97.4 | 97.1 | 84.4 |
116
+
117
+ LFM2-VL-450M-Extract outperforms similarly-sized (sub-1B) open-source VLMs on this benchmark and is competitive with models 4× its size.
118
+
119
+ **Reproducing these numbers**: The full evaluation pipeline, which includes extraction, VLM judging, and metric aggregation, is bundled in this repository under `model_eval/`. Setup, configuration, and run instructions are in the folder's [`README`](./model_eval/README.md).
120
+
121
+ **Scope**: These numbers characterize the model on the input/output form it is designed for: a single input image, a YAML field list as the schema, and a flat JSON object as the output. Performance is not expected to transfer to largely different tasks, e.g. multi-image reasoning or free-form VQA.
122
+
123
+ <!-- > Generic instruction-tuned VLMs (SmolVLM, moondream) cannot perform
124
+ > schema-based extraction zero-shot regardless of prompt strategy.
125
+ > Under the most permissive prompt setups, they either:
126
+ > - produce free-form captions ignoring the JSON instruction, or
127
+ > - produce valid-shaped JSON but echo the schema descriptions or
128
+ > few-shot example values as field values (zero faithfulness to
129
+ > the image).
130
+ >
131
+ > LFM2-VL-Extract's task-specific training is what enables strict-JSON
132
+ > output with faithful, image-grounded values in a single zero-shot
133
+ > call — no few-shot examples, no grammar constraints, no inference
134
+ > wrappers. -->
135
+
136
+
137
+ The full evaluation pipeline, which includes extraction, LLM/VLM judging, and
138
+ metric aggregation, is included in this repository under `model_eval/`. Usage details are in the folder's README.
139
+
140
+ ## 🏃 How to run
141
+
142
+ You can run LFM2.5-VL-450M-Extract with Hugging Face [`transformers`](https://github.com/huggingface/transformers) v5.1 or newer:
143
+
144
+ ```bash
145
+ pip install transformers pillow
146
+ ```
147
+
148
+ ```python
149
+ from transformers import AutoProcessor, AutoModelForImageTextToText
150
+ from transformers.image_utils import load_image
151
+
152
+ model_id = "LiquidAI/LFM2.5-VL-450M-Extract"
153
+ model = AutoModelForImageTextToText.from_pretrained(
154
+ model_id,
155
+ device_map="auto",
156
+ dtype="bfloat16",
157
+ trust_remote_code=True,
158
+ )
159
+ processor = AutoProcessor.from_pretrained(model_id, trust_remote_code=True)
160
+
161
+ image = load_image("https://huggingface.co/LiquidAI/LFM2.5-VL-450M-Extract/resolve/main/sample_image.png")
162
+
163
+ fields_yaml = """wood_color: The overall coloration of the wood surface
164
+ wood_texture: The tactile quality of the wood surface
165
+ wood_pattern: The pattern types visible on the wood surface"""
166
+
167
+ system_prompt = f"""Extract the following from the image:
168
+
169
+ {fields_yaml}
170
+
171
+ Respond with only a JSON object. Do not include any text outside the JSON."""
172
+
173
+ conversation = [
174
+ {"role": "system", "content": system_prompt},
175
+ {"role": "user", "content": [{"type": "image", "image": image}]},
176
+ ]
177
+
178
+ inputs = processor.apply_chat_template(
179
+ conversation,
180
+ add_generation_prompt=True,
181
+ return_tensors="pt",
182
+ return_dict=True,
183
+ tokenize=True,
184
+ ).to(model.device)
185
+
186
+ outputs = model.generate(**inputs, max_new_tokens=512, do_sample=False)
187
+ response = processor.batch_decode(
188
+ outputs[:, inputs["input_ids"].shape[1]:],
189
+ skip_special_tokens=True,
190
+ )[0]
191
+ print(response)
192
+ # {
193
+ # "wood_color": "light to medium brown",
194
+ # "wood_texture": "smooth with visible grain",
195
+ # "wood_pattern": "parallel, irregular, wavy"
196
+ # }
197
+ ```
198
+
199
+ > [!WARNING]
200
+ > The model is intended for single-turn conversations. We recommend using greedy decoding (`temperature=0`).
201
+
202
+ ## 📬 Contact
203
+
204
+ - Got questions or want to connect? [Join our Discord community](https://discord.com/invite/liquid-ai)
205
+ - If you are interested in custom solutions with edge deployment, please contact [our sales team](https://www.liquid.ai/contact).
206
+
207
+ ## Citation
208
+
209
+ ```bibtex
210
+ @article{liquidai2025lfm2,
211
+ title={LFM2 Technical Report},
212
+ author={Liquid AI},
213
+ journal={arXiv preprint arXiv:2511.23404},
214
+ year={2025}
215
+ }
216
+ ```
chat_template.jinja ADDED
@@ -0,0 +1,92 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {{- bos_token -}}
2
+ {%- set keep_past_thinking = keep_past_thinking | default(false) -%}
3
+
4
+ {%- macro format_arg_value(arg_value) -%}
5
+ {%- if arg_value is string -%}
6
+ {{- '"' + arg_value + '"' -}}
7
+ {%- elif arg_value is mapping -%}
8
+ {{- arg_value | tojson -}}
9
+ {%- else -%}
10
+ {{- arg_value | string -}}
11
+ {%- endif -%}
12
+ {%- endmacro -%}
13
+
14
+ {%- macro parse_content(content) -%}
15
+ {%- if content is string -%}
16
+ {{- content -}}
17
+ {%- else -%}
18
+ {%- set _ns = namespace(result="") -%}
19
+ {%- for item in content -%}
20
+ {%- if item.type == "image" -%}
21
+ {%- set _ns.result = _ns.result + "<image>" -%}
22
+ {%- elif item.type == "text" -%}
23
+ {%- set _ns.result = _ns.result + item.text -%}
24
+ {%- else -%}
25
+ {%- set _ns.result = _ns.result + item | tojson -%}
26
+ {%- endif -%}
27
+ {%- endfor -%}
28
+ {{- _ns.result -}}
29
+ {%- endif -%}
30
+ {%- endmacro -%}
31
+
32
+ {%- macro render_tool_calls(tool_calls) -%}
33
+ {%- set tool_calls_ns = namespace(tool_calls=[]) -%}
34
+ {%- for tool_call in tool_calls -%}
35
+ {%- set func_name = tool_call.function.name -%}
36
+ {%- set func_args = tool_call.function.arguments -%}
37
+ {%- set args_ns = namespace(arg_strings=[]) -%}
38
+ {%- for arg_name, arg_value in func_args.items() -%}
39
+ {%- set args_ns.arg_strings = args_ns.arg_strings + [arg_name + "=" + format_arg_value(arg_value)] -%}
40
+ {%- endfor -%}
41
+ {%- set tool_calls_ns.tool_calls = tool_calls_ns.tool_calls + [func_name + "(" + (args_ns.arg_strings | join(", ")) + ")"] -%}
42
+ {%- endfor -%}
43
+ {{- "<|tool_call_start|>[" + (tool_calls_ns.tool_calls | join(", ")) + "]<|tool_call_end|>" -}}
44
+ {%- endmacro -%}
45
+
46
+ {%- set ns = namespace(system_prompt="", last_assistant_index=-1) -%}
47
+ {%- if messages[0].role == "system" -%}
48
+ {%- if messages[0].content is defined -%}
49
+ {%- set ns.system_prompt = parse_content(messages[0].content) -%}
50
+ {%- endif -%}
51
+ {%- set messages = messages[1:] -%}
52
+ {%- endif -%}
53
+ {%- if tools -%}
54
+ {%- set ns.system_prompt = ns.system_prompt + ("\n\n" if ns.system_prompt else "") + "Today's date: " + strftime_now("%Y-%m-%d") + "\n\nList of tools: " + (tools | tojson) -%}
55
+ {%- endif -%}
56
+ {%- if ns.system_prompt -%}
57
+ {{- "<|im_start|>system\n" + ns.system_prompt + "<|im_end|>\n" -}}
58
+ {%- endif -%}
59
+ {%- for message in messages -%}
60
+ {%- if message.role == "assistant" -%}
61
+ {%- set ns.last_assistant_index = loop.index0 -%}
62
+ {%- endif -%}
63
+ {%- endfor -%}
64
+ {%- for message in messages -%}
65
+ {{- "<|im_start|>" + message.role + "\n" -}}
66
+ {%- if message.role == "assistant" -%}
67
+ {%- generation -%}
68
+ {%- if message.thinking is defined and (keep_past_thinking or loop.index0 == ns.last_assistant_index) -%}
69
+ {{- "<think>" + message.thinking + "</think>" -}}
70
+ {%- endif -%}
71
+ {%- if message.tool_calls is defined -%}
72
+ {{- render_tool_calls(message.tool_calls) -}}
73
+ {%- endif -%}
74
+ {%- if message.content is defined -%}
75
+ {%- set content = parse_content(message.content) -%}
76
+ {%- if not keep_past_thinking and loop.index0 != ns.last_assistant_index -%}
77
+ {%- if "</think>" in content -%}
78
+ {%- set content = content.split("</think>")[-1] | trim -%}
79
+ {%- endif -%}
80
+ {%- endif -%}
81
+ {{- content + ("" if (continue_final_message and loop.last) else "<|im_end|>\n") -}}
82
+ {%- endif -%}
83
+ {%- endgeneration -%}
84
+ {%- else %}
85
+ {%- if message.content is defined -%}
86
+ {{- parse_content(message.content) + "<|im_end|>\n" -}}
87
+ {%- endif -%}
88
+ {%- endif %}
89
+ {%- endfor -%}
90
+ {%- if add_generation_prompt -%}
91
+ {{- "<|im_start|>assistant\n" -}}
92
+ {%- endif -%}
config.json ADDED
@@ -0,0 +1,104 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "Lfm2VlForConditionalGeneration"
4
+ ],
5
+ "bos_token_id": 1,
6
+ "do_image_splitting": true,
7
+ "downsample_factor": 2,
8
+ "dtype": "bfloat16",
9
+ "encoder_patch_size": 16,
10
+ "eos_token_id": 7,
11
+ "image_token_id": 396,
12
+ "max_image_tokens": 256,
13
+ "max_pixels_tolerance": 2.0,
14
+ "max_tiles": 10,
15
+ "min_image_tokens": 64,
16
+ "min_tiles": 2,
17
+ "model_type": "lfm2_vl",
18
+ "pad_token_id": 0,
19
+ "projector_bias": true,
20
+ "projector_hidden_act": "gelu",
21
+ "projector_hidden_size": 2048,
22
+ "projector_use_layernorm": false,
23
+ "text_config": {
24
+ "_name_or_path": "LiquidAI/LFM2-350M",
25
+ "architectures": [
26
+ "Lfm2ForCausalLM"
27
+ ],
28
+ "block_auto_adjust_ff_dim": true,
29
+ "block_dim": 1024,
30
+ "block_ffn_dim_multiplier": 1.0,
31
+ "block_mlp_init_scale": 1.0,
32
+ "block_multiple_of": 256,
33
+ "block_norm_eps": 1e-05,
34
+ "block_out_init_scale": 1.0,
35
+ "block_use_swiglu": true,
36
+ "block_use_xavier_init": true,
37
+ "bos_token_id": 1,
38
+ "conv_L_cache": 3,
39
+ "conv_bias": false,
40
+ "conv_dim": 1024,
41
+ "conv_dim_out": 1024,
42
+ "conv_use_xavier_init": true,
43
+ "dtype": "bfloat16",
44
+ "eos_token_id": 7,
45
+ "full_attn_idxs": null,
46
+ "hidden_size": 1024,
47
+ "initializer_range": 0.02,
48
+ "intermediate_size": 6656,
49
+ "layer_types": [
50
+ "conv",
51
+ "conv",
52
+ "full_attention",
53
+ "conv",
54
+ "conv",
55
+ "full_attention",
56
+ "conv",
57
+ "conv",
58
+ "full_attention",
59
+ "conv",
60
+ "full_attention",
61
+ "conv",
62
+ "full_attention",
63
+ "conv",
64
+ "full_attention",
65
+ "conv"
66
+ ],
67
+ "max_position_embeddings": 128000,
68
+ "model_type": "lfm2",
69
+ "norm_eps": 1e-05,
70
+ "num_attention_heads": 16,
71
+ "num_heads": 16,
72
+ "num_hidden_layers": 16,
73
+ "num_key_value_heads": 8,
74
+ "pad_token_id": 0,
75
+ "rope_parameters": {
76
+ "rope_theta": 1000000.0,
77
+ "rope_type": "default"
78
+ },
79
+ "tie_word_embeddings": true,
80
+ "use_cache": true,
81
+ "use_pos_enc": true,
82
+ "vocab_size": 65536
83
+ },
84
+ "tie_word_embeddings": true,
85
+ "tile_size": 512,
86
+ "transformers_version": "5.8.1",
87
+ "use_image_special_tokens": true,
88
+ "use_thumbnail": true,
89
+ "vision_config": {
90
+ "attention_dropout": 0.0,
91
+ "dtype": "bfloat16",
92
+ "hidden_act": "gelu_pytorch_tanh",
93
+ "hidden_size": 768,
94
+ "intermediate_size": 3072,
95
+ "layer_norm_eps": 1e-06,
96
+ "model_type": "siglip2_vision_model",
97
+ "num_attention_heads": 12,
98
+ "num_channels": 3,
99
+ "num_hidden_layers": 12,
100
+ "num_patches": 256,
101
+ "patch_size": 16,
102
+ "vision_use_head": false
103
+ }
104
+ }
generation_config.json ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "bos_token_id": 1,
4
+ "eos_token_id": [
5
+ 7,
6
+ 7
7
+ ],
8
+ "pad_token_id": 0,
9
+ "transformers_version": "5.8.1"
10
+ }
lfm2_vl_450m_metrics.png ADDED

Git LFS Details

  • SHA256: 2d7d42e1e5a50dfec52c34b0077d956025bd99ea7b1e0f4a625567cac9a3daf7
  • Pointer size: 131 Bytes
  • Size of remote file: 311 kB
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b7e5694ca9a0ea81985c84822a503b3d583f4dc71fb2540d1bda944c57a16546
3
+ size 897484568
model_eval/README.md ADDED
@@ -0,0 +1,203 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Eval pipeline (OpenRouter judge)
2
+
3
+ A self-contained evaluation pipeline for LFM2.5-VL structured-extraction
4
+ models. Extraction runs on your local GPU (vLLM/HF); the VLM judge runs
5
+ remotely via the [OpenRouter](https://openrouter.ai/) API — no need to
6
+ host a 30+ GB vision judge yourself.
7
+
8
+ ## Pipeline
9
+
10
+ ```
11
+ WDS tars ─▶ Extraction (local GPU) ─▶ predictions
12
+
13
+ structural metrics ◀───────────┤
14
+ (json validity, key P/R/F1) │
15
+
16
+ VLM judge (OpenRouter) ◀───────┘
17
+
18
+
19
+ eval_result.json
20
+ ```
21
+
22
+ Three primary metrics per run: `json_validity_rate`, `key_f1_macro`,
23
+ `vlm_judge_score_avg` (per-key precision / recall also reported as
24
+ diagnostic byproducts of F1).
25
+
26
+ ## Files
27
+
28
+ ```
29
+ .
30
+ ├── README.md
31
+ ├── requirements.txt
32
+ ├── run_eval.sh ← entry script (env vars + python call)
33
+ ├── run_eval.py ← CLI + orchestrator + metrics aggregation
34
+ ├── extract.py ← WDS loader + vLLM/HF extraction + JSON parsing
35
+ ├── judge.py ← OpenRouter async VLM judging
36
+ ├── prompts/ ← 2 prompt templates (.txt)
37
+ └── eval_data/ ← shipped 2000-sample eval set (single WDS tar)
38
+ ```
39
+
40
+ Three Python files total. No nested packages, no `pyproject.toml`,
41
+ no `pip install -e .` — just `pip install -r requirements.txt`.
42
+
43
+ ---
44
+
45
+ ## Setup
46
+
47
+ ### 1. Python environment
48
+
49
+ ```bash
50
+ python -m venv .venv && source .venv/bin/activate
51
+ pip install -r requirements.txt
52
+ ```
53
+
54
+ `pip install` will pull `vllm`, `torch`, `transformers`, `peft`,
55
+ `webdataset`, `pillow`, `openai`, `tqdm`, `numpy` — ~5 GB total, takes
56
+ 5–15 min depending on the network.
57
+
58
+ > **Mac / no NVIDIA GPU?** vLLM won't install. Either drop the `vllm`
59
+ > line from `requirements.txt`, or install everything else manually and
60
+ > run with `--extraction-backend hf` (forces the HF transformers path).
61
+
62
+ ### 2. OpenRouter API key
63
+
64
+ Get a key from https://openrouter.ai/keys, then add it to your `~/.bashrc`:
65
+
66
+ ```bash
67
+ export OPENROUTER_API_KEY=sk-or-v1-...
68
+ ```
69
+
70
+ Then `source ~/.bashrc` (or open a new shell).
71
+
72
+ ---
73
+
74
+ ## Run
75
+
76
+ ### Quick start
77
+
78
+ ```bash
79
+ bash run_eval.sh
80
+ ```
81
+
82
+ Defaults:
83
+ - Evaluates `LiquidAI/LFM2.5-VL-450M-Extract` on `./eval_data/`
84
+ - Runs the full **2000 samples** (~30 min)
85
+ - VLM judge: `qwen/qwen3.5-35b-a3b`
86
+ - Writes results to `./eval_result.json` and log to `./eval_run.log`
87
+
88
+ ### Tweaking knobs
89
+
90
+ Open `run_eval.sh` — every knob is a top-level variable with an inline
91
+ comment. Common changes:
92
+
93
+ ```bash
94
+ NUM_SAMPLES=50 # set 50 for a quick smoke test (~5 min)
95
+ EXTRACTION_BACKEND="hf" # if vLLM init fails on your machine
96
+ EXTRACTION_BATCH=32 # bump for faster extraction (default 8)
97
+ VLM_JUDGE_MODEL="google/gemini-2.5-flash" # any image-capable OpenRouter model id
98
+ JUDGE_CONCURRENCY=8 # lower if you hit OpenRouter rate limits
99
+ ```
100
+
101
+ ### CLI alternative
102
+
103
+ If you'd rather skip the .sh wrapper, drive `run_eval.py` directly:
104
+
105
+ ```bash
106
+ python run_eval.py \
107
+ --checkpoint-path LiquidAI/LFM2.5-VL-450M-Extract \
108
+ --data-path ./eval_data \
109
+ --output-path ./eval_result.json \
110
+ --num-samples 50 \
111
+ --extraction-backend auto \
112
+ --vlm-judge --vlm-judge-model qwen/qwen3.5-35b-a3b
113
+ ```
114
+
115
+ All flags: `python run_eval.py --help`
116
+
117
+ ---
118
+
119
+ ## Eval data
120
+
121
+ ### What ships in `./eval_data/`
122
+
123
+ 2000 `(image, schema, JSON)` samples in a single WebDataset tar
124
+ (`eval_set_n2000.tar`). Reference labels were generated by an ensemble
125
+ of frontier multimodal models and lightly post-processed for consistency.
126
+
127
+ ### Bring your own
128
+
129
+ Drop a `.tar` (or directory of tars) anywhere and pass
130
+ `--data-path /path/to/your/data`.
131
+
132
+ ### Format spec
133
+
134
+ Each sample is a WebDataset group sharing a common `<sample_id>` prefix:
135
+
136
+ ```
137
+ <sample_id>.jpg image bytes
138
+ <sample_id>.key_explanations JSON {key_name: description} (the schema)
139
+ <sample_id>.structured_text JSON {key_name: value} (ground truth)
140
+ ```
141
+
142
+ ---
143
+
144
+ ## Output
145
+
146
+ `./eval_result.json` has three top-level keys:
147
+
148
+ ```jsonc
149
+ {
150
+ "metadata": {
151
+ "checkpoint_path": "LiquidAI/LFM2.5-VL-450M-Extract",
152
+ "num_samples_evaluated": 50,
153
+ "extraction_backend": "auto",
154
+ "vlm_judge_model": "qwen/qwen3.5-35b-a3b",
155
+ "elapsed_s": 215.2,
156
+ "timestamp_utc": "2026-05-29T..."
157
+ },
158
+ "metrics": {
159
+ "json_validity_rate": 0.996, // share of samples with parseable JSON
160
+ "key_precision_macro": 0.996, // pred-keys ∩ gt-keys / pred-keys
161
+ "key_recall_macro": 0.997,
162
+ "key_f1_macro": 0.997, // primary schema-consistency metric
163
+ "vlm_judge_score_avg": 0.922, // 0-1, VLM scoring of all keys vs image
164
+ "samples_evaluated": 50
165
+ },
166
+ "samples": [
167
+ /* per-sample {schema, gt, prediction, per_key scores, raw judge text} */
168
+ ]
169
+ }
170
+ ```
171
+
172
+ The `samples[].vlm_judge_raw` field preserves the judge's verbatim text
173
+ response — useful for debugging unexpected scores.
174
+
175
+ ---
176
+
177
+ ## Costs
178
+
179
+ Default judge on a full 2000-sample run, calculated against per-token
180
+ pricing at the time of writing (check https://openrouter.ai/models for
181
+ current rates):
182
+
183
+ | Stage | Model | Input rate | Output rate | Est. cost |
184
+ |---|---|---|---|---|
185
+ | VLM judge | `qwen/qwen3.5-35b-a3b` | $0.139 / 1M | $1.00 / 1M | ~$1.53 |
186
+
187
+ **Full 2000-sample run: ~$1.50.** Smoke 50-sample: ~$0.04.
188
+
189
+ ---
190
+
191
+ ## Troubleshooting
192
+
193
+ - **vLLM init fails** (e.g. `Ninja build failed` / `__cudaLaunch not declared`)
194
+ → set `EXTRACTION_BACKEND="hf"` in `run_eval.sh` for a slower-but-stable
195
+ fallback.
196
+ - **OpenRouter 429 (rate limit)** → lower `JUDGE_CONCURRENCY` to 4 or 8.
197
+ - **`No usable samples loaded`** → your tars don't have the expected
198
+ `<key>.jpg` / `.key_explanations` / `.structured_text` fields, or the
199
+ `.tar` path is wrong.
200
+ - **A new judge model rejects with `Reasoning is mandatory`** or returns all
201
+ zero scores with `finish_reason=length` → edit the `_VLM_JUDGE_REASONING`
202
+ constant in `judge.py` (the OpenRouter `reasoning` param works differently
203
+ per model).
model_eval/eval_data/eval_set_n2000.tar ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:762bc2e15c5f2636a51ba6d985e8cec31bd0658a11e48a5f6e7e4bbbd5b71923
3
+ size 135168000
model_eval/extract.py ADDED
@@ -0,0 +1,533 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """WDS data loading, schema-aware extraction prompts, local model inference,
2
+ and JSON-from-noise parsing — everything the trained-checkpoint stage needs.
3
+
4
+ Public entry: `run_extraction(samples, model_path, backend, ...)` returns a
5
+ list of records ready for the judge stage.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import base64
11
+ import io
12
+ import json
13
+ import logging
14
+ import re
15
+ import time
16
+ from dataclasses import dataclass
17
+ from pathlib import Path
18
+ from string import Template
19
+ from typing import Any, Iterator, Literal
20
+
21
+ import webdataset as wds
22
+
23
+ logger = logging.getLogger(__name__)
24
+
25
+ _IMAGE_EXTS = ("jpg", "jpeg", "png", "webp")
26
+ _PROMPT_DIR = Path(__file__).resolve().parent / "prompts"
27
+ _EXTRACTION_TPL = Template((_PROMPT_DIR / "extraction_system.txt").read_text(encoding="utf-8"))
28
+
29
+
30
+ # ─── data loading ──────────────────────────────────────────────────────────
31
+
32
+
33
+ @dataclass(frozen=True)
34
+ class EvalSample:
35
+ key: str
36
+ image_bytes: bytes
37
+ schema: dict[str, str]
38
+ ground_truth: dict[str, object]
39
+
40
+
41
+ def discover_tar_files(data_path: str) -> list[str]:
42
+ """Resolve a path/glob/brace-expansion to a sorted list of `.tar` files."""
43
+ if "{" in data_path and ".." in data_path:
44
+ expanded = list(wds.shardlists.expand_urls(data_path))
45
+ if expanded and Path(expanded[0]).is_dir():
46
+ tars: list[str] = []
47
+ for d in expanded:
48
+ if Path(d).is_dir():
49
+ tars.extend(sorted(str(f) for f in Path(d).rglob("*.tar")))
50
+ if not tars:
51
+ raise FileNotFoundError(f"No .tar files found in: {data_path}")
52
+ return tars
53
+ return expanded
54
+
55
+ p = Path(data_path)
56
+ if p.is_file() and p.suffix == ".tar":
57
+ return [str(p)]
58
+ if p.is_dir():
59
+ tars = sorted(str(f) for f in p.rglob("*.tar"))
60
+ if not tars:
61
+ raise FileNotFoundError(f"No .tar files found in {data_path}")
62
+ return tars
63
+ parent = p.parent
64
+ tars = sorted(str(f) for f in parent.glob(p.name))
65
+ if not tars:
66
+ raise FileNotFoundError(f"No files matching pattern: {data_path}")
67
+ return tars
68
+
69
+
70
+ def _first_image(sample: dict) -> bytes | None:
71
+ """Return the first image, preferring `imgN.jpg` order then legacy keys."""
72
+ multi: list[tuple[int, bytes]] = []
73
+ for k, v in sample.items():
74
+ if not isinstance(v, (bytes, bytearray)) or not k.startswith("img"):
75
+ continue
76
+ head, _, ext = k.partition(".")
77
+ if ext.lower() not in _IMAGE_EXTS:
78
+ continue
79
+ idx_str = head[3:]
80
+ if not idx_str.isdigit():
81
+ continue
82
+ multi.append((int(idx_str), bytes(v)))
83
+ if multi:
84
+ multi.sort(key=lambda x: x[0])
85
+ return multi[0][1]
86
+ for k in _IMAGE_EXTS:
87
+ v = sample.get(k)
88
+ if isinstance(v, (bytes, bytearray)):
89
+ return bytes(v)
90
+ return None
91
+
92
+
93
+ def _decode_text(value: object) -> str:
94
+ if value is None:
95
+ return ""
96
+ if isinstance(value, bytes):
97
+ return value.decode("utf-8", errors="replace")
98
+ return str(value)
99
+
100
+
101
+ def iter_eval_samples(
102
+ data_path: str,
103
+ *,
104
+ skip: int = 0,
105
+ limit: int = 0,
106
+ ) -> Iterator[EvalSample]:
107
+ """Yield up to `limit` EvalSamples from WDS tars.
108
+
109
+ Each sample carries `<key>.jpg`, `<key>.key_explanations` (schema with
110
+ descriptions), and `<key>.structured_text` (ground-truth values).
111
+ Samples missing image/schema/labels are silently skipped.
112
+ """
113
+ tar_files = discover_tar_files(data_path)
114
+ logger.info("Discovered %d tar file(s) under %s", len(tar_files), data_path)
115
+
116
+ dataset = wds.WebDataset(
117
+ tar_files,
118
+ shardshuffle=False,
119
+ nodesplitter=None,
120
+ handler=lambda e: logger.warning("WDS skip: %s", e) or True,
121
+ )
122
+ n_seen = 0
123
+ n_yielded = 0
124
+ for sample in dataset:
125
+ img = _first_image(sample)
126
+ ke = sample.get("key_explanations")
127
+ st = sample.get("structured_text")
128
+ if img is None or ke is None or st is None:
129
+ continue
130
+ try:
131
+ schema = json.loads(_decode_text(ke))
132
+ gt = json.loads(_decode_text(st))
133
+ except (json.JSONDecodeError, ValueError) as e:
134
+ logger.warning("Skip %s: bad JSON (%s)", sample.get("__key__", "?"), e)
135
+ continue
136
+ if not isinstance(schema, dict) or not isinstance(gt, dict):
137
+ continue
138
+ n_seen += 1
139
+ if n_seen <= skip:
140
+ continue
141
+ yield EvalSample(
142
+ key=str(sample.get("__key__", f"sample_{n_seen}")),
143
+ image_bytes=img,
144
+ schema=schema,
145
+ ground_truth=gt,
146
+ )
147
+ n_yielded += 1
148
+ if limit and n_yielded >= limit:
149
+ break
150
+ logger.info("Yielded %d eval sample(s) (skipped %d)", n_yielded, skip)
151
+
152
+
153
+ # ─── prompt rendering ──────────────────────────────────────────────────────
154
+
155
+
156
+ def schema_to_yaml(schema: dict[str, str]) -> str:
157
+ return "\n".join(f"{k}: {v}" for k, v in schema.items())
158
+
159
+
160
+ def build_extraction_prompt(schema: dict[str, str]) -> str:
161
+ return _EXTRACTION_TPL.substitute(schema=schema_to_yaml(schema))
162
+
163
+
164
+ # ─── JSON parsing ──────────────────────────────────────────────────────────
165
+
166
+
167
+ def sanitize_output(text: str) -> str:
168
+ """Strip whitespace + markdown fences + bare `json` prefix."""
169
+ if not text:
170
+ return ""
171
+ s = text.strip()
172
+ if s.startswith("```"):
173
+ nl = s.find("\n")
174
+ s = "" if nl == -1 else s[nl + 1 :]
175
+ s = s.rstrip()
176
+ if s.endswith("```"):
177
+ s = s[:-3]
178
+ s = s.strip()
179
+ head = s.split("\n", 1)
180
+ if head and head[0].strip().lower() == "json":
181
+ s = head[1] if len(head) > 1 else ""
182
+ s = s.strip()
183
+ return s
184
+
185
+
186
+ def _first_balanced(text: str, start: int) -> str | None:
187
+ """Return `text[start:i+1]` when braces balance; None if never balances."""
188
+ depth = 0
189
+ in_string = False
190
+ escape = False
191
+ for i in range(start, len(text)):
192
+ ch = text[i]
193
+ if escape:
194
+ escape = False
195
+ continue
196
+ if ch == "\\" and in_string:
197
+ escape = True
198
+ continue
199
+ if ch == '"':
200
+ in_string = not in_string
201
+ continue
202
+ if in_string:
203
+ continue
204
+ if ch == "{":
205
+ depth += 1
206
+ elif ch == "}":
207
+ depth -= 1
208
+ if depth == 0:
209
+ return text[start : i + 1]
210
+ return None
211
+
212
+
213
+ _TRAILING_COMMA_RE = re.compile(r",(\s*[}\]])")
214
+ # Bare empty-string entries inside an object: ` "",` or `\n ""\n}`.
215
+ # Some VLMs emit these as a runaway-collapse pattern.
216
+ _BARE_EMPTY_RE = re.compile(r',\s*""\s*(?=[,}])')
217
+ _BARE_EMPTY_BEFORE_CLOSE_RE = re.compile(r',\s*""\s*(?=\n*\s*})')
218
+
219
+
220
+ def extract_json_strict_first(text: str) -> tuple[dict, bool]:
221
+ """Sanitize + parse. Returns `(dict, was_strict)`.
222
+
223
+ `was_strict=True` if the strict parse succeeded — that's what
224
+ `json_valid` reports. False covers repaired-success and total failure
225
+ (caller distinguishes via `bool(dict)`).
226
+ """
227
+ sanitized = sanitize_output(text)
228
+ if not sanitized:
229
+ return {}, False
230
+ start = sanitized.find("{")
231
+ if start == -1:
232
+ return {}, False
233
+
234
+ candidate = _first_balanced(sanitized, start)
235
+ if candidate is not None:
236
+ try:
237
+ parsed = json.loads(candidate)
238
+ if isinstance(parsed, dict):
239
+ return parsed, True
240
+ except (json.JSONDecodeError, ValueError):
241
+ pass
242
+
243
+ # Second-chance repair (ported from old bundle's `_repair_parse`):
244
+ # try original `bal`, then progressively repaired versions, then the
245
+ # last-`}` truncation with both repairs applied. First dict wins.
246
+ candidates: list[str] = []
247
+ bal = _first_balanced(sanitized[start:], 0)
248
+ if bal is not None:
249
+ candidates.append(bal)
250
+ c2 = _BARE_EMPTY_RE.sub("", bal)
251
+ c2 = _BARE_EMPTY_BEFORE_CLOSE_RE.sub("", c2)
252
+ candidates.append(c2)
253
+ candidates.append(_TRAILING_COMMA_RE.sub(r"\1", c2))
254
+ last_close = sanitized.rfind("}")
255
+ if last_close >= 0:
256
+ tail = sanitized[: last_close + 1]
257
+ candidates.append(tail)
258
+ tail2 = _BARE_EMPTY_RE.sub("", tail)
259
+ tail2 = _BARE_EMPTY_BEFORE_CLOSE_RE.sub("", tail2)
260
+ tail2 = _TRAILING_COMMA_RE.sub(r"\1", tail2)
261
+ candidates.append(tail2)
262
+
263
+ for c in candidates:
264
+ try:
265
+ parsed = json.loads(c)
266
+ except (json.JSONDecodeError, ValueError):
267
+ continue
268
+ if isinstance(parsed, dict):
269
+ return parsed, False
270
+ return {}, False
271
+
272
+
273
+ # ─── extraction backends ───────────────────────────────────────────────────
274
+
275
+
276
+ def _img_to_data_url(img_bytes: bytes) -> str:
277
+ b64 = base64.b64encode(img_bytes).decode("ascii")
278
+ return f"data:image/jpeg;base64,{b64}"
279
+
280
+
281
+ def _build_chat_messages(schema: dict[str, str], img_bytes: bytes) -> list[dict[str, Any]]:
282
+ return [
283
+ {"role": "system", "content": build_extraction_prompt(schema)},
284
+ {
285
+ "role": "user",
286
+ "content": [
287
+ {"type": "image_url", "image_url": {"url": _img_to_data_url(img_bytes)}},
288
+ ],
289
+ },
290
+ ]
291
+
292
+
293
+ def _extract_vllm(
294
+ samples: list[EvalSample],
295
+ *,
296
+ model_path: str,
297
+ max_model_len: int,
298
+ gpu_mem_util: float,
299
+ max_new_tokens: int,
300
+ ) -> list[str]:
301
+ """vLLM offline batch extraction. One shot, no retries — Ctrl+C if hung."""
302
+ from vllm import LLM # type: ignore
303
+
304
+ logger.info("Initializing vLLM for %s …", model_path)
305
+ llm = LLM(
306
+ model=model_path,
307
+ trust_remote_code=True,
308
+ dtype="bfloat16",
309
+ max_model_len=max_model_len,
310
+ gpu_memory_utilization=gpu_mem_util,
311
+ enable_prefix_caching=True,
312
+ disable_log_stats=True,
313
+ limit_mm_per_prompt={"image": 1},
314
+ )
315
+ from vllm import SamplingParams # type: ignore
316
+
317
+ sp = SamplingParams(temperature=0.0, max_tokens=max_new_tokens)
318
+ conversations = [_build_chat_messages(s.schema, s.image_bytes) for s in samples]
319
+ logger.info("vLLM.chat over %d samples …", len(samples))
320
+ # Suppress reasoning for extraction-side reasoning models (Qwen3 family,
321
+ # gpt-oss family). Without this they burn the token budget on internal
322
+ # <think> blocks and emit no JSON. Non-reasoning models silently ignore.
323
+ outputs = llm.chat(
324
+ conversations,
325
+ sampling_params=sp,
326
+ use_tqdm=True,
327
+ chat_template_kwargs={
328
+ "enable_thinking": False,
329
+ "reasoning_effort": "low",
330
+ },
331
+ )
332
+ texts = [o.outputs[0].text if o.outputs else "" for o in outputs]
333
+ return texts
334
+
335
+
336
+ def _extract_hf(
337
+ samples: list[EvalSample],
338
+ *,
339
+ model_path: str,
340
+ max_new_tokens: int,
341
+ batch: int,
342
+ ) -> list[str]:
343
+ """HF transformers fallback. Slower but works without vLLM (e.g. Mac)."""
344
+ import torch # type: ignore
345
+ from PIL import Image # type: ignore
346
+ from transformers import AutoModelForImageTextToText, AutoProcessor # type: ignore
347
+
348
+ logger.info("Loading HF model %s …", model_path)
349
+ processor = AutoProcessor.from_pretrained(model_path, trust_remote_code=True)
350
+ # Decoder-only generation requires left padding so the model never sees
351
+ # padding tokens in the middle of the sequence at decode time.
352
+ if hasattr(processor, "tokenizer") and processor.tokenizer is not None:
353
+ processor.tokenizer.padding_side = "left"
354
+ model = AutoModelForImageTextToText.from_pretrained(
355
+ model_path,
356
+ dtype=torch.bfloat16 if torch.cuda.is_available() else torch.float32,
357
+ trust_remote_code=True,
358
+ device_map="auto" if torch.cuda.is_available() else None,
359
+ )
360
+ model.eval()
361
+
362
+ outputs: list[str] = []
363
+ for start in range(0, len(samples), batch):
364
+ chunk = samples[start : start + batch]
365
+ msgs = [_build_chat_messages(s.schema, s.image_bytes) for s in chunk]
366
+ # The processor strips the image_url data URIs and replaces with PIL.
367
+ for m, s in zip(msgs, chunk):
368
+ m[1]["content"][0] = {"type": "image", "image": Image.open(io.BytesIO(s.image_bytes))}
369
+ inputs = processor.apply_chat_template(
370
+ msgs,
371
+ add_generation_prompt=True,
372
+ tokenize=True,
373
+ return_dict=True,
374
+ return_tensors="pt",
375
+ padding=True,
376
+ # Suppress reasoning blocks (Qwen3 family) — kwarg flows into the
377
+ # model's Jinja chat template. Non-reasoning models ignore it.
378
+ enable_thinking=False,
379
+ ).to(model.device)
380
+ with torch.no_grad():
381
+ gen = model.generate(**inputs, max_new_tokens=max_new_tokens, do_sample=False)
382
+ decoded = processor.batch_decode(
383
+ gen[:, inputs["input_ids"].shape[1] :], skip_special_tokens=True
384
+ )
385
+ outputs.extend(decoded)
386
+ logger.info("HF extraction: %d/%d", min(start + batch, len(samples)), len(samples))
387
+ return outputs
388
+
389
+
390
+ def _extract_smolvlm(
391
+ samples: list[EvalSample],
392
+ *,
393
+ model_path: str,
394
+ max_new_tokens: int,
395
+ max_model_len: int = 8192,
396
+ gpu_mem_util: float = 0.85,
397
+ ) -> list[str]:
398
+ """SmolVLM / Idefics3-family extraction via vLLM with user-prompt format.
399
+
400
+ Why a dedicated path:
401
+ - SmolVLM was trained on user/assistant turns only; system messages
402
+ carry weak signal and trigger generic image-captioning behavior
403
+ rather than schema following. So we put the schema in the *user*
404
+ prompt alongside the image.
405
+ - vLLM natively supports the Idefics3 architecture (SmolVLM v1/v2),
406
+ giving ~20× the throughput of single-sample HF generation. We use
407
+ it directly here instead of going through the generic vLLM path
408
+ (which would also work, but with a system-prompt template).
409
+ """
410
+ from vllm import LLM, SamplingParams # type: ignore
411
+
412
+ logger.info("Initializing vLLM for SmolVLM/Idefics3 model: %s …", model_path)
413
+ llm = LLM(
414
+ model=model_path,
415
+ trust_remote_code=True,
416
+ dtype="bfloat16",
417
+ max_model_len=max_model_len,
418
+ gpu_memory_utilization=gpu_mem_util,
419
+ enable_prefix_caching=True,
420
+ disable_log_stats=True,
421
+ limit_mm_per_prompt={"image": 1},
422
+ )
423
+ sp = SamplingParams(temperature=0.0, max_tokens=max_new_tokens)
424
+
425
+ conversations: list[list[dict[str, Any]]] = []
426
+ for s in samples:
427
+ b64 = base64.b64encode(s.image_bytes).decode("ascii")
428
+ data_url = f"data:image/jpeg;base64,{b64}"
429
+ # User prompt (no system) — schema goes in the user turn alongside
430
+ # the image. This is the format SmolVLM responds to.
431
+ conversations.append([
432
+ {"role": "user", "content": [
433
+ {"type": "image_url", "image_url": {"url": data_url}},
434
+ {"type": "text", "text": build_extraction_prompt(s.schema)},
435
+ ]},
436
+ ])
437
+
438
+ logger.info("vLLM.chat over %d samples (SmolVLM) …", len(samples))
439
+ outputs = llm.chat(conversations, sampling_params=sp, use_tqdm=True)
440
+ return [o.outputs[0].text if o.outputs else "" for o in outputs]
441
+
442
+
443
+ def _is_smolvlm(model_path: str) -> bool:
444
+ """Detect SmolVLM / Idefics3-family models from path."""
445
+ p = model_path.lower()
446
+ return "smolvlm" in p or "idefics" in p
447
+
448
+
449
+ def run_extraction(
450
+ samples: list[EvalSample],
451
+ *,
452
+ model_path: str,
453
+ backend: Literal["auto", "vllm", "hf"] = "auto",
454
+ max_new_tokens: int = 1024,
455
+ max_model_len: int = 8192,
456
+ gpu_mem_util: float = 0.85,
457
+ batch: int = 8,
458
+ ) -> list[dict[str, Any]]:
459
+ """Run extraction; return one prediction record per input sample.
460
+
461
+ `backend="auto"` tries vLLM first and falls back to HF on import error
462
+ or init failure. `"vllm"` / `"hf"` force the choice.
463
+
464
+ Special case: SmolVLM / Idefics3 family always uses a dedicated code
465
+ path regardless of `backend` — vLLM doesn't support them well, and the
466
+ standard `AutoModelForImageTextToText` invocation drops the chat
467
+ template specifics they need.
468
+ """
469
+ if not samples:
470
+ return []
471
+
472
+ t0 = time.perf_counter()
473
+
474
+ # SmolVLM / Idefics: dedicated path, bypass `backend` selection.
475
+ if _is_smolvlm(model_path):
476
+ logger.info("Detected SmolVLM/Idefics-family model — using dedicated extraction path.")
477
+ raw_outputs = _extract_smolvlm(samples, model_path=model_path, max_new_tokens=max_new_tokens)
478
+ backend_used = "smolvlm"
479
+ elif backend == "hf":
480
+ raw_outputs = _extract_hf(samples, model_path=model_path, max_new_tokens=max_new_tokens, batch=batch)
481
+ backend_used = "hf"
482
+ elif backend == "vllm":
483
+ raw_outputs = _extract_vllm(
484
+ samples,
485
+ model_path=model_path,
486
+ max_model_len=max_model_len,
487
+ gpu_mem_util=gpu_mem_util,
488
+ max_new_tokens=max_new_tokens,
489
+ )
490
+ backend_used = "vllm"
491
+ else: # auto
492
+ try:
493
+ raw_outputs = _extract_vllm(
494
+ samples,
495
+ model_path=model_path,
496
+ max_model_len=max_model_len,
497
+ gpu_mem_util=gpu_mem_util,
498
+ max_new_tokens=max_new_tokens,
499
+ )
500
+ backend_used = "vllm"
501
+ except Exception as e:
502
+ logger.warning("vLLM extraction failed (%s); falling back to HF transformers.", e)
503
+ raw_outputs = _extract_hf(samples, model_path=model_path, max_new_tokens=max_new_tokens, batch=batch)
504
+ backend_used = "hf"
505
+
506
+ dt = time.perf_counter() - t0
507
+ logger.info(
508
+ "Extraction over %d samples took %.1fs (%.2f sample/s, backend=%s).",
509
+ len(samples),
510
+ dt,
511
+ len(samples) / max(dt, 1e-9),
512
+ backend_used,
513
+ )
514
+
515
+ if len(raw_outputs) != len(samples):
516
+ raise RuntimeError(
517
+ f"Backend returned {len(raw_outputs)} outputs for {len(samples)} samples"
518
+ )
519
+
520
+ records: list[dict[str, Any]] = []
521
+ for s, raw in zip(samples, raw_outputs):
522
+ parsed, strict = extract_json_strict_first(raw)
523
+ records.append(
524
+ {
525
+ "key": s.key,
526
+ "schema": s.schema,
527
+ "ground_truth": s.ground_truth,
528
+ "prediction_raw": raw,
529
+ "prediction_json": parsed,
530
+ "prediction_strict_valid": strict,
531
+ }
532
+ )
533
+ return records
model_eval/judge.py ADDED
@@ -0,0 +1,296 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """OpenRouter-backed VLM judge.
2
+
3
+ One prompt per sample (batched-over-keys in one JSON answer), run
4
+ concurrently via asyncio. The VLM judge scores every key against the
5
+ image and is the only quality signal we ship.
6
+
7
+ Requires `OPENROUTER_API_KEY` in the environment. OpenRouter is
8
+ OpenAI-compatible, so we point the `openai` SDK's `base_url` at it.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import asyncio
14
+ import base64
15
+ import json
16
+ import logging
17
+ import os
18
+ import re
19
+ from pathlib import Path
20
+ from string import Template
21
+ from typing import Any
22
+
23
+ from openai import AsyncOpenAI
24
+ from tqdm.asyncio import tqdm_asyncio
25
+
26
+ logger = logging.getLogger(__name__)
27
+
28
+ _PROMPT_DIR = Path(__file__).resolve().parent / "prompts"
29
+ _VLM_JUDGE_TPL = Template((_PROMPT_DIR / "vlm_judge_batch.txt").read_text(encoding="utf-8"))
30
+
31
+ OPENROUTER_BASE_URL = "https://openrouter.ai/api/v1"
32
+
33
+ # Reasoning suppression for the VLM judge. Default model
34
+ # (`qwen/qwen3.5-35b-a3b`) requires `enable_thinking=False` to avoid
35
+ # burning the full token budget on internal thought and returning
36
+ # `finish_reason=length` with no visible output. Both layers (top-level
37
+ # `reasoning` + `chat_template_kwargs`) are sent so whichever the
38
+ # underlying provider honors gets used; the other is ignored.
39
+ _VLM_JUDGE_REASONING = {
40
+ "reasoning": {"enabled": False},
41
+ "chat_template_kwargs": {"enable_thinking": False},
42
+ }
43
+
44
+
45
+ # ─── per-key pre-classification ────────────────────────────────────────────
46
+
47
+
48
+ def normalize_bool(gt_val: object, pred_val: object) -> object:
49
+ """If GT is bool and pred is a yes/no/true/false string, coerce."""
50
+ if isinstance(gt_val, bool) and isinstance(pred_val, str):
51
+ lower = pred_val.strip().lower()
52
+ if lower in ("yes", "true"):
53
+ return True
54
+ if lower in ("no", "false"):
55
+ return False
56
+ return pred_val
57
+
58
+
59
+ def initialize_per_key_evals(records: list[dict[str, Any]]) -> None:
60
+ """Build a `per_key` mapping `{key: {gt, pred}}` for the VLM judge to score."""
61
+ for rec in records:
62
+ per_key: dict[str, dict[str, Any]] = {}
63
+ gt = rec["ground_truth"]
64
+ pred = rec["prediction_json"]
65
+ for key, gt_val in gt.items():
66
+ pred_val = pred.get(key)
67
+ if pred_val is not None:
68
+ pred_val = normalize_bool(gt_val, pred_val)
69
+ per_key[key] = {"gt": gt_val, "pred": pred_val}
70
+ rec["per_key"] = per_key
71
+
72
+
73
+ # ─── prompt building ───────────────────────────────────────────────────────
74
+
75
+
76
+ def _vlm_attr_block(entries: list[tuple[str, str, object]]) -> str:
77
+ lines: list[str] = []
78
+ for key, desc, pred in entries:
79
+ lines.append(f'- "{key}": {desc}\n predicted: {json.dumps(pred, ensure_ascii=False)}')
80
+ return "\n".join(lines)
81
+
82
+
83
+ def build_vlm_judge_prompt(entries: list[tuple[str, str, object]]) -> str:
84
+ return _VLM_JUDGE_TPL.substitute(attributes=_vlm_attr_block(entries))
85
+
86
+
87
+ # ─── response parsing ──────────────────────────────────────────────────────
88
+
89
+
90
+ _NUM_RE = re.compile(r"(\d+\.?\d*)")
91
+
92
+
93
+ def _clamp(x: float) -> float:
94
+ return 0.0 if x < 0.0 else (1.0 if x > 1.0 else x)
95
+
96
+
97
+ def parse_score(text: str | None) -> float:
98
+ if not text:
99
+ return 0.0
100
+ text = text.strip()
101
+ try:
102
+ return _clamp(float(text))
103
+ except ValueError:
104
+ m = _NUM_RE.search(text)
105
+ if not m:
106
+ return 0.0
107
+ try:
108
+ return _clamp(float(m.group(1)))
109
+ except ValueError:
110
+ return 0.0
111
+
112
+
113
+ def parse_batch_scores(text: str | None, expected_keys: list[str]) -> dict[str, float]:
114
+ """Parse `{key: score}` from judge output; missing keys default to 0.0."""
115
+ result = {k: 0.0 for k in expected_keys}
116
+ if not text:
117
+ return result
118
+ # Reuse the JSON extractor from extract.py — same logic.
119
+ from extract import extract_json_strict_first
120
+
121
+ parsed, _ = extract_json_strict_first(text)
122
+ if not isinstance(parsed, dict):
123
+ return result
124
+ for k in expected_keys:
125
+ v = parsed.get(k)
126
+ if isinstance(v, bool):
127
+ # Defensive: bool is a subclass of int. Don't accept it as a score.
128
+ continue
129
+ if isinstance(v, (int, float)):
130
+ result[k] = _clamp(float(v))
131
+ elif isinstance(v, str):
132
+ # Judge sometimes returns string-formatted numbers like "0.8";
133
+ # parse_score extracts the leading numeric.
134
+ result[k] = parse_score(v)
135
+ return result
136
+
137
+
138
+ def per_sample_judge_avg(per_key: dict[str, dict[str, Any]], score_field: str) -> float | None:
139
+ """Average a judge score across all keys of one sample. None if no scores."""
140
+ scores = [
141
+ float(v.get(score_field))
142
+ for v in per_key.values()
143
+ if isinstance(v.get(score_field), (int, float)) and not isinstance(v.get(score_field), bool)
144
+ ]
145
+ return sum(scores) / len(scores) if scores else None
146
+
147
+
148
+ # ─── OpenRouter client + concurrent dispatch ───────────────────────────────
149
+
150
+
151
+ def _img_to_data_url(img_bytes: bytes) -> str:
152
+ return f"data:image/jpeg;base64,{base64.b64encode(img_bytes).decode('ascii')}"
153
+
154
+
155
+ def _make_client(api_key: str | None) -> AsyncOpenAI:
156
+ key = api_key or os.environ.get("OPENROUTER_API_KEY")
157
+ if not key:
158
+ raise RuntimeError(
159
+ "OPENROUTER_API_KEY is not set. Get a key at https://openrouter.ai/keys "
160
+ "and `export OPENROUTER_API_KEY=...` before running."
161
+ )
162
+ return AsyncOpenAI(base_url=OPENROUTER_BASE_URL, api_key=key, max_retries=3, timeout=120.0)
163
+
164
+
165
+ async def _one_chat(
166
+ client: AsyncOpenAI,
167
+ *,
168
+ model: str,
169
+ system: str,
170
+ user_text: str,
171
+ image_bytes: bytes | None,
172
+ max_tokens: int,
173
+ semaphore: asyncio.Semaphore,
174
+ extra_body: dict[str, Any] | None = None,
175
+ max_retries_on_empty: int = 3,
176
+ ) -> str:
177
+ """Single OpenRouter chat call, rate-limited by `semaphore`.
178
+
179
+ Some OpenRouter providers occasionally return HTTP 200 with empty content
180
+ (no model output). Treating that as success silently fails the per-key
181
+ JSON parse — so we retry up to `max_retries_on_empty` times before
182
+ giving up.
183
+ """
184
+ user_content: list[dict[str, Any]] = [{"type": "text", "text": user_text}]
185
+ if image_bytes:
186
+ user_content.insert(0, {"type": "image_url", "image_url": {"url": _img_to_data_url(image_bytes)}})
187
+ messages = [
188
+ {"role": "system", "content": system},
189
+ {"role": "user", "content": user_content},
190
+ ]
191
+ kwargs: dict[str, Any] = {
192
+ "model": model,
193
+ "messages": messages,
194
+ "max_tokens": max_tokens,
195
+ "temperature": 0.0,
196
+ }
197
+ if extra_body:
198
+ kwargs["extra_body"] = extra_body
199
+
200
+ async with semaphore:
201
+ for attempt in range(max_retries_on_empty + 1):
202
+ try:
203
+ resp = await client.chat.completions.create(**kwargs)
204
+ text = resp.choices[0].message.content or ""
205
+ if text.strip():
206
+ return text
207
+ finish = getattr(resp.choices[0], "finish_reason", None)
208
+ if attempt < max_retries_on_empty:
209
+ logger.warning(
210
+ "Empty response from %s (finish_reason=%s); retrying %d/%d.",
211
+ model, finish, attempt + 1, max_retries_on_empty,
212
+ )
213
+ continue
214
+ logger.warning(
215
+ "Empty response from %s after %d retries (finish_reason=%s); giving up.",
216
+ model, max_retries_on_empty, finish,
217
+ )
218
+ return ""
219
+ except Exception as e:
220
+ logger.warning("OpenRouter call failed (%s); returning empty string.", e)
221
+ return ""
222
+ return ""
223
+
224
+
225
+ async def _run_concurrent(
226
+ coros: list[Any],
227
+ *,
228
+ desc: str,
229
+ ) -> list[str]:
230
+ """Run coroutines concurrently with a tqdm progress bar."""
231
+ return await tqdm_asyncio.gather(*coros, desc=desc)
232
+
233
+
234
+ # ─── VLM judge ─────────────────────────────────────────────────────────────
235
+
236
+
237
+ def run_vlm_judge(
238
+ records: list[dict[str, Any]],
239
+ *,
240
+ sample_images: dict[str, bytes],
241
+ model: str,
242
+ max_tokens: int = 1024,
243
+ concurrency: int = 16,
244
+ api_key: str | None = None,
245
+ ) -> None:
246
+ """Score every key against the image via an OpenRouter VLM."""
247
+ plans: list[dict[str, Any]] = []
248
+ prompts: list[str] = []
249
+ imgs: list[bytes] = []
250
+ for rec in records:
251
+ per_key = rec.get("per_key", {})
252
+ if not per_key:
253
+ continue
254
+ keys = list(per_key.keys())
255
+ entries = [(k, rec["schema"].get(k, ""), per_key[k].get("pred")) for k in keys]
256
+ img = sample_images.get(rec["key"], b"")
257
+ if not img:
258
+ logger.warning("VLM judge: missing image for sample %s", rec["key"])
259
+ continue
260
+ prompts.append(build_vlm_judge_prompt(entries))
261
+ imgs.append(img)
262
+ plans.append({"record": rec, "keys": keys})
263
+
264
+ if not plans:
265
+ for rec in records:
266
+ rec["vlm_judge_avg"] = None
267
+ return
268
+
269
+ logger.info("VLM judge: scoring %d sample(s) × all keys via %s.", len(plans), model)
270
+
271
+ client = _make_client(api_key)
272
+ sem = asyncio.Semaphore(concurrency)
273
+ coros = [
274
+ _one_chat(
275
+ client,
276
+ model=model,
277
+ system="You are a meticulous visual evaluator.",
278
+ user_text=p,
279
+ image_bytes=img,
280
+ max_tokens=max_tokens,
281
+ semaphore=sem,
282
+ extra_body=_VLM_JUDGE_REASONING,
283
+ )
284
+ for p, img in zip(prompts, imgs)
285
+ ]
286
+ raw_outputs = asyncio.run(_run_concurrent(coros, desc="VLM judge"))
287
+
288
+ for plan, text in zip(plans, raw_outputs):
289
+ scores = parse_batch_scores(text, plan["keys"])
290
+ rec = plan["record"]
291
+ rec["vlm_judge_raw"] = text
292
+ for k in plan["keys"]:
293
+ rec["per_key"][k]["vlm_score"] = scores.get(k, 0.0)
294
+
295
+ for rec in records:
296
+ rec["vlm_judge_avg"] = per_sample_judge_avg(rec["per_key"], "vlm_score")
model_eval/prompts/extraction_system.txt ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ Extract the following from the image:
2
+
3
+ $schema
4
+
5
+ Respond with only a JSON object. Do not include any text outside the JSON.
model_eval/prompts/vlm_judge_batch.txt ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Look at the image and evaluate whether the predicted values are correct for each attribute.
2
+
3
+ Attributes (with descriptions and predictions):
4
+ $attributes
5
+
6
+ Each prediction should be an observation about the image (a word, number, or natural-language phrase like "partly cloudy" or "lying horizontally"), NOT a restatement of the description/question itself.
7
+
8
+ For each attribute, rate how correct the prediction is based on what you see in the image, on a 0.0-1.0 scale:
9
+ - 1.0: Exactly correct or semantically identical
10
+ - 0.7-0.9: Mostly correct with minor differences
11
+ - 0.3-0.6: Partially correct
12
+ - 0.0-0.2: Incorrect, unrelated, or just rephrases the description instead of giving a specific value
13
+
14
+ Respond with ONLY a JSON object mapping each attribute name to its score. Example:
15
+ {"attr1": 0.9, "attr2": 0.3, "attr3": 1.0}
16
+
17
+ No text outside the JSON.
model_eval/requirements.txt ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # --- Extraction (local) ---
2
+ vllm>=0.20.1 # optional but recommended on NVIDIA GPUs; pass
3
+ # --extraction-backend hf to skip if it won't install.
4
+ transformers>=4.45
5
+ torch>=2.4
6
+ peft>=0.10
7
+ webdataset>=0.2
8
+ pillow>=10.0
9
+ num2words>=0.5 # SmolVLM/SmolVLM2 processor requires this for video timestamp formatting
10
+
11
+ # --- OpenRouter judges (remote) ---
12
+ openai>=1.50 # OpenRouter is OpenAI-compatible; just point base_url at it.
13
+
14
+ # --- Tiny helpers ---
15
+ tqdm>=4.66
16
+ numpy>=1.24
model_eval/run_eval.py ADDED
@@ -0,0 +1,209 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ """Eval pipeline driver: extraction → structural metrics → VLM judge → JSON.
3
+
4
+ Extraction runs locally on your GPU (vLLM/HF); the VLM judge runs remotely
5
+ via the OpenRouter API. One process, sequential stages, one JSON file out.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import argparse
11
+ import datetime as _dt
12
+ import json
13
+ import logging
14
+ import sys
15
+ import time
16
+ from pathlib import Path
17
+ from typing import Any
18
+
19
+ from extract import iter_eval_samples, run_extraction
20
+ from judge import initialize_per_key_evals, run_vlm_judge
21
+
22
+
23
+ # ─── metrics aggregation ───────────────────────────────────────────────────
24
+
25
+
26
+ def per_sample_structural(prediction_json: dict, ground_truth: dict, strict_valid: bool) -> dict[str, Any]:
27
+ pred_keys = set(prediction_json.keys())
28
+ gt_keys = set(ground_truth.keys())
29
+ overlap = pred_keys & gt_keys
30
+ p = len(overlap) / len(pred_keys) if pred_keys else 0.0
31
+ r = len(overlap) / len(gt_keys) if gt_keys else 0.0
32
+ f1 = 2 * p * r / (p + r) if (p + r) > 0 else 0.0
33
+ return {
34
+ "json_valid": strict_valid,
35
+ "total_keys": len(gt_keys),
36
+ "total_pred_keys": len(pred_keys),
37
+ "overlap_keys": len(overlap),
38
+ "key_precision": p,
39
+ "key_recall": r,
40
+ "key_f1": f1,
41
+ }
42
+
43
+
44
+ def aggregate(records: list[dict[str, Any]]) -> dict[str, Any]:
45
+ n = len(records)
46
+ if n == 0:
47
+ return {"samples_evaluated": 0}
48
+
49
+ def mean(xs: list[float]) -> float:
50
+ return sum(xs) / len(xs) if xs else 0.0
51
+
52
+ json_valid = sum(1 for r in records if r.get("json_valid"))
53
+ vlm_scores = [r["vlm_judge_avg"] for r in records if r.get("vlm_judge_avg") is not None]
54
+
55
+ return {
56
+ "json_validity_rate": json_valid / n,
57
+ "key_precision_macro": mean([r.get("key_precision", 0.0) for r in records]),
58
+ "key_recall_macro": mean([r.get("key_recall", 0.0) for r in records]),
59
+ "key_f1_macro": mean([r.get("key_f1", 0.0) for r in records]),
60
+ "vlm_judge_score_avg": mean(vlm_scores) if vlm_scores else None,
61
+ "samples_evaluated": n,
62
+ }
63
+
64
+
65
+ def _strip_sample(rec: dict[str, Any]) -> dict[str, Any]:
66
+ """Drop heavy/internal fields before serialising to JSON."""
67
+ return {
68
+ "key": rec["key"],
69
+ "schema": rec["schema"],
70
+ "ground_truth": rec["ground_truth"],
71
+ "prediction_raw": rec["prediction_raw"],
72
+ "prediction_json": rec["prediction_json"],
73
+ "json_valid": rec.get("json_valid", False),
74
+ "total_keys": rec.get("total_keys", 0),
75
+ "total_pred_keys": rec.get("total_pred_keys", 0),
76
+ "key_precision": rec.get("key_precision", 0.0),
77
+ "key_recall": rec.get("key_recall", 0.0),
78
+ "key_f1": rec.get("key_f1", 0.0),
79
+ "vlm_judge_avg": rec.get("vlm_judge_avg"),
80
+ "vlm_judge_raw": rec.get("vlm_judge_raw"),
81
+ "per_key": rec.get("per_key", {}),
82
+ }
83
+
84
+
85
+ # ─── CLI ───────────────────────────────────────────────────────────────────
86
+
87
+
88
+ def main() -> int:
89
+ p = argparse.ArgumentParser(description="OpenRouter-judged structured-extraction eval.")
90
+ p.add_argument("--checkpoint-path", required=True, help="HF id or local merged/LoRA dir.")
91
+ p.add_argument("--data-path", default="./eval_data", help="WDS tar / dir / glob.")
92
+ p.add_argument("--output-path", default="./eval_result.json")
93
+ p.add_argument("--num-samples", type=int, default=0, help="Cap N samples (0 = all).")
94
+ p.add_argument("--skip-samples", type=int, default=0)
95
+ p.add_argument("--extraction-backend", choices=["auto", "vllm", "hf"], default="auto")
96
+ p.add_argument("--extraction-batch", type=int, default=8)
97
+ p.add_argument("--extraction-max-new-tokens", type=int, default=1024)
98
+ p.add_argument("--extraction-gpu-mem-util", type=float, default=0.85)
99
+ p.add_argument("--extraction-max-model-len", type=int, default=8192)
100
+ p.add_argument("--vlm-judge", action=argparse.BooleanOptionalAction, default=True)
101
+ p.add_argument("--vlm-judge-model", default="qwen/qwen3-vl-4b-instruct")
102
+ p.add_argument("--vlm-judge-max-tokens", type=int, default=1024)
103
+ p.add_argument("--judge-concurrency", type=int, default=16, help="Concurrent OpenRouter calls.")
104
+ p.add_argument("--openrouter-api-key", default=None, help="Override $OPENROUTER_API_KEY.")
105
+ p.add_argument("--log-level", default="INFO")
106
+ args = p.parse_args()
107
+
108
+ logging.basicConfig(
109
+ level=args.log_level.upper(),
110
+ format="%(asctime)s [%(levelname)s] %(name)s: %(message)s",
111
+ )
112
+
113
+ t_start = time.perf_counter()
114
+ logger = logging.getLogger("run_eval")
115
+ logger.info("=== OpenRouter-judged eval starting ===")
116
+
117
+ # ── load samples ─────────────────────────────────��───────────────────
118
+ samples = list(
119
+ iter_eval_samples(
120
+ args.data_path,
121
+ skip=args.skip_samples,
122
+ limit=args.num_samples,
123
+ )
124
+ )
125
+ if not samples:
126
+ raise RuntimeError(
127
+ f"No usable samples loaded from {args.data_path} — expected WDS tars "
128
+ "with .jpg, .key_explanations, .structured_text per sample."
129
+ )
130
+ logger.info("Loaded %d sample(s).", len(samples))
131
+ sample_images = {s.key: s.image_bytes for s in samples}
132
+
133
+ # ── extraction ───────────────────────────────────────────────────────
134
+ records = run_extraction(
135
+ samples,
136
+ model_path=args.checkpoint_path,
137
+ backend=args.extraction_backend,
138
+ max_new_tokens=args.extraction_max_new_tokens,
139
+ max_model_len=args.extraction_max_model_len,
140
+ gpu_mem_util=args.extraction_gpu_mem_util,
141
+ batch=args.extraction_batch,
142
+ )
143
+
144
+ # ── structural metrics ───────────────────────────────────────────────
145
+ for rec in records:
146
+ rec.update(
147
+ per_sample_structural(
148
+ rec["prediction_json"],
149
+ rec["ground_truth"],
150
+ rec.get("prediction_strict_valid", bool(rec["prediction_json"])),
151
+ )
152
+ )
153
+
154
+ initialize_per_key_evals(records)
155
+ judge_errors: dict[str, str] = {}
156
+
157
+ # ── VLM judge ────────────────────────────────────────────────────────
158
+ if args.vlm_judge:
159
+ try:
160
+ run_vlm_judge(
161
+ records,
162
+ sample_images=sample_images,
163
+ model=args.vlm_judge_model,
164
+ max_tokens=args.vlm_judge_max_tokens,
165
+ concurrency=args.judge_concurrency,
166
+ api_key=args.openrouter_api_key,
167
+ )
168
+ except Exception as e:
169
+ judge_errors["vlm_judge"] = repr(e)
170
+ logger.warning("VLM judge failed (%s); continuing without VLM scores.", e)
171
+ for rec in records:
172
+ rec.setdefault("vlm_judge_avg", None)
173
+ else:
174
+ for rec in records:
175
+ rec["vlm_judge_avg"] = None
176
+
177
+ # ── write output ─────────────────────────────────────────────────────
178
+ elapsed = time.perf_counter() - t_start
179
+ result = {
180
+ "metadata": {
181
+ "checkpoint_path": args.checkpoint_path,
182
+ "data_path": args.data_path,
183
+ "num_samples_evaluated": len(records),
184
+ "extraction_backend": args.extraction_backend,
185
+ "vlm_judge_model": args.vlm_judge_model if args.vlm_judge else None,
186
+ "judge_errors": judge_errors or None,
187
+ "elapsed_s": round(elapsed, 2),
188
+ "timestamp_utc": _dt.datetime.now(_dt.timezone.utc).isoformat(),
189
+ },
190
+ "metrics": aggregate(records),
191
+ "samples": [_strip_sample(rec) for rec in records],
192
+ }
193
+
194
+ out = Path(args.output_path)
195
+ out.parent.mkdir(parents=True, exist_ok=True)
196
+ out.write_text(json.dumps(result, ensure_ascii=False, indent=2), encoding="utf-8")
197
+
198
+ print()
199
+ print("=== JUDGING SUMMARY ===")
200
+ print(f"output={out}")
201
+ for k, v in result["metrics"].items():
202
+ print(f" {k}={v:.4f}" if isinstance(v, float) else f" {k}={v}")
203
+ print(f" elapsed_s={elapsed:.1f}")
204
+ print("=== JUDGING OK ===")
205
+ return 0
206
+
207
+
208
+ if __name__ == "__main__":
209
+ sys.exit(main())
model_eval/run_eval.sh ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # Example evaluation script — extraction on local GPU, judges via OpenRouter API.
3
+ # bash run_eval.sh
4
+
5
+ set -euo pipefail
6
+
7
+ # --- vLLM env workarounds ----------------------------------------------------
8
+ # Needed when EXTRACTION_BACKEND=vllm or "auto". No-op on systems without
9
+ # vLLM / environment-modules.
10
+ # 1. CUDA toolkit on LD_LIBRARY_PATH so flashinfer's GDN/Mamba kernels can
11
+ # dlopen libcudart.so.12 (LFM2.5-VL is a hybrid arch and uses these).
12
+ # 2. Skip flashinfer's sampling kernel — flashinfer 0.6 + CUDA 12.9 trigger
13
+ # an NVCC stub bug (`__cudaLaunch` not declared). PyTorch-native sampler
14
+ # is ~20% slower but works.
15
+ # 3. Skip vLLM 0.21's DeepGEMM autotune warmup (~18 min for MoE/FP8 models).
16
+ module load cuda12.9/toolkit/12.9.1 2>/dev/null || true
17
+ export VLLM_USE_FLASHINFER_SAMPLER="${VLLM_USE_FLASHINFER_SAMPLER:-0}"
18
+ export VLLM_USE_DEEP_GEMM="${VLLM_USE_DEEP_GEMM:-0}"
19
+
20
+ # --- OpenRouter API key ------------------------------------------------------
21
+ # Required. Get one at https://openrouter.ai/keys, then either:
22
+ # export OPENROUTER_API_KEY=...
23
+ # in your shell, OR uncomment and set it here.
24
+ #OPENROUTER_API_KEY="sk-or-v1-..."
25
+
26
+ # --- Checkpoint --------------------------------------------------------------
27
+ # HF id of the trained model, OR a local merged/LoRA checkpoint dir.
28
+ CHECKPOINT="LiquidAI/LFM2.5-VL-450M-Extract"
29
+
30
+ # --- Eval data ---------------------------------------------------------------
31
+ # WDS tar / dir of tars / brace-glob.
32
+ DATA_PATH="./eval_data"
33
+
34
+ # Output JSON path.
35
+ OUTPUT="./eval_result.json"
36
+
37
+ # --- Sample count ------------------------------------------------------------
38
+ # Number of samples to evaluate. Default 2000 runs the full shipped eval_data
39
+ # (~30 min). Set to 50 for a quick smoke test (~5 min).
40
+ NUM_SAMPLES=2000
41
+
42
+ # --- Extraction (local GPU) --------------------------------------------------
43
+ # "auto" tries vLLM first, falls back to HF transformers on init failure.
44
+ EXTRACTION_BACKEND="auto"
45
+ EXTRACTION_BATCH=8
46
+
47
+ # --- Judge model (OpenRouter) ------------------------------------------------
48
+ # Any image-capable OpenRouter model id works. Pricing:
49
+ # https://openrouter.ai/models
50
+ VLM_JUDGE_MODEL="qwen/qwen3.5-35b-a3b"
51
+
52
+ # Concurrent OpenRouter calls. Lower if you hit rate limits.
53
+ JUDGE_CONCURRENCY=16
54
+
55
+ # --- Run ---------------------------------------------------------------------
56
+ LOG_FILE="${LOG_FILE:-./eval_run.log}"
57
+ echo "Logging to: ${LOG_FILE}"
58
+ python run_eval.py \
59
+ --checkpoint-path "${CHECKPOINT}" \
60
+ --data-path "${DATA_PATH}" \
61
+ --output-path "${OUTPUT}" \
62
+ --num-samples "${NUM_SAMPLES}" \
63
+ --extraction-backend "${EXTRACTION_BACKEND}" \
64
+ --extraction-batch "${EXTRACTION_BATCH}" \
65
+ --vlm-judge --vlm-judge-model "${VLM_JUDGE_MODEL}" \
66
+ --judge-concurrency "${JUDGE_CONCURRENCY}" \
67
+ 2>&1 | tee "${LOG_FILE}"
processor_config.json ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "image_processor": {
3
+ "data_format": "channels_first",
4
+ "do_image_splitting": true,
5
+ "do_normalize": true,
6
+ "do_pad": true,
7
+ "do_rescale": true,
8
+ "do_resize": true,
9
+ "downsample_factor": 2,
10
+ "encoder_patch_size": 16,
11
+ "image_mean": [
12
+ 0.5,
13
+ 0.5,
14
+ 0.5
15
+ ],
16
+ "image_processor_type": "Lfm2VlImageProcessor",
17
+ "image_std": [
18
+ 0.5,
19
+ 0.5,
20
+ 0.5
21
+ ],
22
+ "max_image_tokens": 256,
23
+ "max_num_patches": 1024,
24
+ "max_pixels_tolerance": 2.0,
25
+ "max_tiles": 10,
26
+ "min_image_tokens": 64,
27
+ "min_tiles": 2,
28
+ "resample": 2,
29
+ "rescale_factor": 0.00392156862745098,
30
+ "return_row_col_info": true,
31
+ "size": {
32
+ "height": 512,
33
+ "width": 512
34
+ },
35
+ "tile_size": 512,
36
+ "use_thumbnail": true
37
+ },
38
+ "processor_class": "Lfm2VlProcessor"
39
+ }
sample_image.png ADDED

Git LFS Details

  • SHA256: d7e342c1a492c8da0b13213a4249aaaae7b5b0117e39c513a05def25a7da5c21
  • Pointer size: 131 Bytes
  • Size of remote file: 999 kB
tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
tokenizer_config.json ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "backend": "tokenizers",
3
+ "bos_token": "<|startoftext|>",
4
+ "clean_up_tokenization_spaces": true,
5
+ "do_image_splitting": true,
6
+ "eos_token": "<|im_end|>",
7
+ "extra_special_tokens": [],
8
+ "image_end_token": "<|image_end|>",
9
+ "image_start_token": "<|image_start|>",
10
+ "image_thumbnail": "<|img_thumbnail|>",
11
+ "image_token": "<image>",
12
+ "is_local": true,
13
+ "legacy": false,
14
+ "local_files_only": false,
15
+ "max_length": null,
16
+ "model_max_length": 1000000000000000019884624838656,
17
+ "model_specific_special_tokens": {
18
+ "image_end_token": "<|image_end|>",
19
+ "image_start_token": "<|image_start|>",
20
+ "image_token": "<image>"
21
+ },
22
+ "pad_to_multiple_of": null,
23
+ "pad_token": "<|pad|>",
24
+ "pad_token_type_id": 0,
25
+ "padding_side": "right",
26
+ "processor_class": "Lfm2VlProcessor",
27
+ "return_token_type_ids": false,
28
+ "sp_model_kwargs": {},
29
+ "spaces_between_special_tokens": false,
30
+ "tokenizer_class": "TokenizersBackend",
31
+ "use_default_system_prompt": false,
32
+ "use_fast": true
33
+ }