lucataco commited on
Commit
08bc7a7
·
verified ·
1 Parent(s): 3532d71

Add MLX 8-bit conversion of Cloudflare/clef with joint schema head and clef_mlx.py loader

Browse files
.gitattributes CHANGED
@@ -33,3 +33,4 @@ saved_model/**/* 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
 
 
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
+ tokenizer.json filter=lfs diff=lfs merge=lfs -text
LICENSE ADDED
@@ -0,0 +1,202 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright 2026 Alibaba Cloud
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
README.md ADDED
@@ -0,0 +1,108 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: apache-2.0
3
+ library_name: mlx
4
+ base_model: Cloudflare/clef
5
+ base_model_relation: quantized
6
+ pipeline_tag: image-text-to-text
7
+ tags:
8
+ - mlx
9
+ - clef
10
+ - cloudflare
11
+ - systemone
12
+ - structured-output
13
+ - classification
14
+ - multimodal
15
+ - custom-code
16
+ ---
17
+
18
+ # mlx-community/clef-8bit
19
+
20
+ [Cloudflare/clef](https://huggingface.co/Cloudflare/clef) converted to MLX (8-bit) for Apple Silicon.
21
+
22
+ Clef turns a state (text, JSON, images, or video) plus a schema of typed questions into a
23
+ probability for every allowed option, in a single forward pass. **It is not a chat model** —
24
+ `mlx_vlm.generate`, `mlx_lm.generate`, and LM Studio will load the backbone but produce
25
+ meaningless text. Use the bundled `clef_mlx.py` loader, which runs the backbone and the
26
+ joint schema head.
27
+
28
+ ## Usage
29
+
30
+ ```bash
31
+ pip install mlx-vlm huggingface_hub # no torch needed
32
+ ```
33
+
34
+ ```python
35
+ import sys
36
+ from huggingface_hub import snapshot_download
37
+
38
+ path = snapshot_download("mlx-community/clef-8bit")
39
+ sys.path.insert(0, path)
40
+ import clef_mlx
41
+
42
+ model = clef_mlx.load(path)
43
+ response = model.systemone({
44
+ "model": "clef",
45
+ "state": "Our checkout started returning errors and orders are blocked.",
46
+ "questions": {
47
+ "department": {
48
+ "type": "choice",
49
+ "instructions": "Which team should handle the message?",
50
+ "criteria": {"billing": "Payments or invoices", "technical": "Bugs or outages"},
51
+ },
52
+ "urgency": {"type": "score", "criteria": ["Can wait", "This week", "Today"]},
53
+ "outage": {"type": "noul", "instructions": "Is a service down?"},
54
+ },
55
+ })
56
+ print(response["answers"])
57
+ ```
58
+
59
+ Images (PIL) and videos (frame arrays) go in `images` / `videos`, as in the original:
60
+
61
+ ```python
62
+ from PIL import Image
63
+ model.predict({
64
+ "state": {"task": "Review the attached receipt."},
65
+ "images": [Image.open("receipt.jpg")],
66
+ "questions": {"legible": {"type": "noul", "instructions": "Is the receipt total legible?"}},
67
+ })
68
+ ```
69
+
70
+ See the [original model card](https://huggingface.co/Cloudflare/clef) for the input format, question types, and benchmarks.
71
+
72
+ ## Conversion
73
+
74
+ - Backbone: `mlx_vlm.convert -q --q-bits 8 --q-group-size 64` (vision tower kept in bf16).
75
+ - Joint schema head: `joint_head.safetensors` copied unchanged (bf16) and run by `clef_mlx.py`.
76
+ - `processor_config.json` is the original from Cloudflare/clef; prompt/token layout matches the reference
77
+ `joint_schema_model.py` exactly (images and video).
78
+
79
+ ## Parity vs. official PyTorch implementation (bf16)
80
+
81
+ | Inputs | Top answer agrees | Max abs Δprob |
82
+ |---|---|---|
83
+ | Text (4 records, 10 questions) | 10/10 | 0.007 |
84
+ | Images + video (5 records, 9 questions) | 9/9 | 0.032 |
85
+
86
+ Measured on an M5 Max (128 GB). Small spot-check, not a full benchmark run.
87
+
88
+ ## Quality check: Decision Index (sampled)
89
+
90
+ | | Decision Index (sample) | Median latency |
91
+ |---|---|---|
92
+ | **This model (8-bit)** | **57.96** | 1.13 s |
93
+ | MLX 4-bit ([mlx-community/clef-4bit](https://huggingface.co/mlx-community/clef-4bit)), same rows | 57.02 (98.1% same top answer) | 1.03 s |
94
+ | Cloudflare published (full suite) | 61.21 | |
95
+
96
+ 8-bit tracks the PyTorch reference within 0.007 probability on spot checks. The gap to the published score is
97
+ mostly sample noise and harness differences (Arts & Human Taste in particular), not quantization.
98
+
99
+ Method: [Decision Index](https://github.com/apolinario/decision-index) 0.2.1 kit (suite rebuilt byte-identical), stratified
100
+ 2,000-request sample across all 44 benchmarks (`suite sample --n 2000`), engine = `clef_mlx.py` with
101
+ `max_length=16384` and **no truncation** (over-length requests are refused and count as wrong; 15 of 2,000,
102
+ mostly BRIGHT). The index is computed from each benchmark's native metric on the sampled rows with the kit's
103
+ chance correction and weights; HLE and iSarcasmEval are set to 0 to match how Cloudflare's published run is
104
+ scored. With ~40 rows per benchmark, per-benchmark numbers are noisy (±10+ pts) — only the index is meaningful.
105
+
106
+ ## License
107
+
108
+ Apache-2.0, following [Cloudflare/clef](https://huggingface.co/Cloudflare/clef).
chat_template.jinja ADDED
@@ -0,0 +1,170 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {%- set image_count = namespace(value=0) %}
2
+ {%- set video_count = namespace(value=0) %}
3
+ {%- macro render_content(content, do_vision_count, is_system_content=false) %}
4
+ {%- if content is string %}
5
+ {{- content }}
6
+ {%- elif content is iterable and content is not mapping %}
7
+ {%- for item in content %}
8
+ {%- if 'image' in item or 'image_url' in item or item.type == 'image' %}
9
+ {%- if is_system_content %}
10
+ {{- raise_exception('System message cannot contain images.') }}
11
+ {%- endif %}
12
+ {%- if do_vision_count %}
13
+ {%- set image_count.value = image_count.value + 1 %}
14
+ {%- endif %}
15
+ {%- if add_vision_id %}
16
+ {{- 'Picture ' ~ image_count.value ~ ': ' }}
17
+ {%- endif %}
18
+ {{- '<|vision_start|><|image_pad|><|vision_end|>' }}
19
+ {%- elif 'video' in item or item.type == 'video' %}
20
+ {%- if is_system_content %}
21
+ {{- raise_exception('System message cannot contain videos.') }}
22
+ {%- endif %}
23
+ {%- if do_vision_count %}
24
+ {%- set video_count.value = video_count.value + 1 %}
25
+ {%- endif %}
26
+ {%- if add_vision_id %}
27
+ {{- 'Video ' ~ video_count.value ~ ': ' }}
28
+ {%- endif %}
29
+ {{- '<|vision_start|><|video_pad|><|vision_end|>' }}
30
+ {%- elif 'text' in item %}
31
+ {{- item.text }}
32
+ {%- else %}
33
+ {{- raise_exception('Unexpected item type in content.') }}
34
+ {%- endif %}
35
+ {%- endfor %}
36
+ {%- elif content is none or content is undefined %}
37
+ {{- '' }}
38
+ {%- else %}
39
+ {{- raise_exception('Unexpected content type.') }}
40
+ {%- endif %}
41
+ {%- endmacro %}
42
+ {%- if not messages %}
43
+ {{- raise_exception('No messages provided.') }}
44
+ {%- endif %}
45
+ {%- set reasoning_instructions = '' %}
46
+ {%- if enable_thinking is undefined or enable_thinking is true %}
47
+ {%- set resolved_reasoning_effort = reasoning_effort|default('xhigh') %}
48
+ {%- if resolved_reasoning_effort not in ('xhigh', 'medium', 'low') %}
49
+ {{- raise_exception('Unexpected reasoning effort ' ~ reasoning_effort ~ '. Supported types are xhigh (default), medium, and low.') }}
50
+ {%- endif %}
51
+ {%- if resolved_reasoning_effort == 'xhigh' %}
52
+ {%- set reasoning_instructions = 'Reasoning effort is set to xhigh. Please think carefully through the task, validate key assumptions, consider plausible alternatives, and prioritize correctness, consistency, and clarity in the final answer.' %}
53
+ {%- elif resolved_reasoning_effort == 'low' %}
54
+ {%- set reasoning_instructions = 'Reasoning effort is set to low. Keep your thinking brief and focused, moving directly to the conclusion without unnecessary elaboration.' %}
55
+ {%- endif %}
56
+ {%- endif %}
57
+ {%- if tools and tools is iterable and tools is not mapping %}
58
+ {{- '<|im_start|>system\n' }}
59
+ {%- if reasoning_instructions %}
60
+ {{- reasoning_instructions + '\n\n' }}
61
+ {%- endif %}
62
+ {{- "# Tools\n\nYou have access to the following functions:\n\n<tools>" }}
63
+ {%- for tool in tools %}
64
+ {{- "\n" }}
65
+ {{- tool | tojson }}
66
+ {%- endfor %}
67
+ {{- "\n</tools>" }}
68
+ {{- '\n\nIf you choose to call a function ONLY reply in the following format with NO suffix:\n\n<tool_call>\n<function=example_function_name>\n<parameter=example_parameter_1>\nvalue_1\n</parameter>\n<parameter=example_parameter_2>\nThis is the value for the second parameter\nthat can span\nmultiple lines\n</parameter>\n</function>\n</tool_call>\n\n<IMPORTANT>\nReminder:\n- Function calls MUST follow the specified format: an inner <function=...></function> block must be nested within <tool_call></tool_call> XML tags\n- Required parameters MUST be specified\n- You may provide optional reasoning for your function call in natural language BEFORE the function call, but NOT after\n- If there is no function call available, answer the question like normal with your current knowledge and do not tell the user about function calls\n</IMPORTANT>' }}
69
+ {%- if messages[0].role == 'system' %}
70
+ {%- set content = render_content(messages[0].content, false, true)|trim %}
71
+ {%- if content %}
72
+ {{- '\n\n' + content }}
73
+ {%- endif %}
74
+ {%- endif %}
75
+ {{- '<|im_end|>\n' }}
76
+ {%- else %}
77
+ {%- if messages[0].role == 'system' %}
78
+ {%- set content = render_content(messages[0].content, false, true)|trim %}
79
+ {%- if content %}
80
+ {{- '<|im_start|>system\n' + (reasoning_instructions + '\n\n' if reasoning_instructions else '') + content + '<|im_end|>\n' }}
81
+ {%- elif reasoning_instructions %}
82
+ {{- '<|im_start|>system\n' + reasoning_instructions + '<|im_end|>\n' }}
83
+ {%- endif %}
84
+ {%- elif reasoning_instructions %}
85
+ {{- '<|im_start|>system\n' + reasoning_instructions + '<|im_end|>\n' }}
86
+ {%- endif %}
87
+ {%- endif %}
88
+ {%- set ns = namespace(multi_step_tool=true, last_query_index=messages|length - 1) %}
89
+ {%- for message in messages[::-1] %}
90
+ {%- set index = (messages|length - 1) - loop.index0 %}
91
+ {%- if ns.multi_step_tool and message.role == "user" %}
92
+ {%- set content = render_content(message.content, false)|trim %}
93
+ {%- if not(content.startswith('<tool_response>') and content.endswith('</tool_response>')) %}
94
+ {%- set ns.multi_step_tool = false %}
95
+ {%- set ns.last_query_index = index %}
96
+ {%- endif %}
97
+ {%- endif %}
98
+ {%- endfor %}
99
+ {%- if ns.multi_step_tool %}
100
+ {{- raise_exception('No user query found in messages.') }}
101
+ {%- endif %}
102
+ {%- for message in messages %}
103
+ {%- set content = render_content(message.content, true)|trim %}
104
+ {%- if message.role == "system" %}
105
+ {%- if not loop.first %}
106
+ {{- raise_exception('System message must be at the beginning.') }}
107
+ {%- endif %}
108
+ {%- elif message.role == "user" %}
109
+ {{- '<|im_start|>' + message.role + '\n' + content + '<|im_end|>' + '\n' }}
110
+ {%- elif message.role == "assistant" %}
111
+ {%- set reasoning_content = '' %}
112
+ {%- if message.reasoning_content is string %}
113
+ {%- set reasoning_content = message.reasoning_content %}
114
+ {%- endif %}
115
+ {%- set reasoning_content = reasoning_content|trim %}
116
+ {%- if preserve_thinking is undefined or preserve_thinking is true or loop.index0 > ns.last_query_index %}
117
+ {{- '<|im_start|>' + message.role + '\n<think>\n' + reasoning_content + '\n</think>\n\n' + content }}
118
+ {%- else %}
119
+ {{- '<|im_start|>' + message.role + '\n' + content }}
120
+ {%- endif %}
121
+ {%- if message.tool_calls and message.tool_calls is iterable and message.tool_calls is not mapping %}
122
+ {%- for tool_call in message.tool_calls %}
123
+ {%- if tool_call.function is defined %}
124
+ {%- set tool_call = tool_call.function %}
125
+ {%- endif %}
126
+ {%- if loop.first %}
127
+ {%- if content|trim %}
128
+ {{- '\n\n<tool_call>\n<function=' + tool_call.name + '>\n' }}
129
+ {%- else %}
130
+ {{- '<tool_call>\n<function=' + tool_call.name + '>\n' }}
131
+ {%- endif %}
132
+ {%- else %}
133
+ {{- '\n<tool_call>\n<function=' + tool_call.name + '>\n' }}
134
+ {%- endif %}
135
+ {%- if tool_call.arguments is defined and tool_call.arguments != '' %}
136
+ {%- for args_name, args_value in tool_call.arguments|items %}
137
+ {{- '<parameter=' + args_name + '>\n' }}
138
+ {%- set args_value = args_value | string if args_value is string else args_value | tojson | safe %}
139
+ {{- args_value }}
140
+ {{- '\n</parameter>\n' }}
141
+ {%- endfor %}
142
+ {%- endif %}
143
+ {{- '</function>\n</tool_call>' }}
144
+ {%- endfor %}
145
+ {%- endif %}
146
+ {{- '<|im_end|>\n' }}
147
+ {%- elif message.role == "tool" %}
148
+ {%- if loop.previtem and loop.previtem.role != "tool" %}
149
+ {{- '<|im_start|>user' }}
150
+ {%- endif %}
151
+ {{- '\n<tool_response>\n' }}
152
+ {{- content }}
153
+ {{- '\n</tool_response>' }}
154
+ {%- if not loop.last and loop.nextitem.role != "tool" %}
155
+ {{- '<|im_end|>\n' }}
156
+ {%- elif loop.last %}
157
+ {{- '<|im_end|>\n' }}
158
+ {%- endif %}
159
+ {%- else %}
160
+ {{- raise_exception('Unexpected message role.') }}
161
+ {%- endif %}
162
+ {%- endfor %}
163
+ {%- if add_generation_prompt %}
164
+ {{- '<|im_start|>assistant\n' }}
165
+ {%- if enable_thinking is defined and enable_thinking is false %}
166
+ {{- '<think>\n\n</think>\n\n' }}
167
+ {%- else %}
168
+ {{- '<think>\n' }}
169
+ {%- endif %}
170
+ {%- endif %}
clef_mlx.py ADDED
@@ -0,0 +1,551 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """MLX port of Cloudflare Clef / Clef-Flash (Qwen3.5 backbone + joint schema head).
2
+
3
+ Torch-free. The backbone is loaded with mlx-vlm (text + images/video) or mlx-lm
4
+ (text only), bf16 or quantized. The joint head is loaded from the original
5
+ ``joint_head.safetensors`` / ``joint_head_config.json`` with no conversion.
6
+
7
+ import clef_mlx
8
+ model = clef_mlx.load("mlx-community/clef-flash-4bit")
9
+ model.predict(record) # {question_id: {option_id: probability}}
10
+ model.systemone(request) # Jev/SystemOne /v1/systemone response body
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import json
16
+ import math
17
+ from dataclasses import dataclass, field
18
+ from pathlib import Path
19
+ from typing import Any
20
+
21
+ import mlx.core as mx
22
+ import mlx.nn as nn
23
+
24
+ SYSTEM_PROMPT = (
25
+ "Read the complete state and schema. Decide every field jointly. Each answer "
26
+ "must be exactly one of that field's allowed options."
27
+ )
28
+ QUESTION_TYPES = {"noul": 0, "choice": 1, "score": 2}
29
+
30
+
31
+ class ContextTooLong(ValueError):
32
+ pass
33
+
34
+
35
+ # --------------------------------------------------------------------------- encoding
36
+ # Mirrors joint_schema_model.encode_record (text-only path) exactly.
37
+
38
+
39
+ def render(value: Any) -> str:
40
+ if isinstance(value, str):
41
+ return value
42
+ return json.dumps(value, ensure_ascii=False, separators=(",", ":"), sort_keys=True)
43
+
44
+
45
+ def question_options(question: dict[str, Any]) -> list[tuple[str, Any]]:
46
+ question_type = str(question["type"])
47
+ if question_type == "noul":
48
+ criteria = {
49
+ "true": "The proposition is true or the answer is yes.",
50
+ "false": "The proposition is false or the answer is no.",
51
+ }
52
+ criteria.update(question.get("criteria") or {})
53
+ return [(key, criteria[key]) for key in ("true", "false")]
54
+ if question_type == "choice":
55
+ return sorted((str(key), value) for key, value in question["criteria"].items())
56
+ return [(str(index), value) for index, value in enumerate(question["criteria"])]
57
+
58
+
59
+ @dataclass(frozen=True)
60
+ class EncodedQuestion:
61
+ question_id: str
62
+ question_type: int
63
+ question_span: tuple[int, int]
64
+ option_spans: tuple[tuple[int, int], ...]
65
+ option_ids: tuple[str, ...]
66
+
67
+
68
+ @dataclass(frozen=True)
69
+ class EncodedRecord:
70
+ input_ids: tuple[int, ...]
71
+ questions: tuple[EncodedQuestion, ...]
72
+ media: dict[str, Any] | None = field(default=None, compare=False, repr=False)
73
+
74
+
75
+ def _tokens(tokenizer: Any, text: str) -> list[int]:
76
+ return tokenizer(text, add_special_tokens=False).input_ids
77
+
78
+
79
+ def sample_frames(video, fps=2.0, source_fps=24.0, min_frames=4, max_frames=768):
80
+ """Uniform frame sampling matching transformers' Qwen3VLVideoProcessor.
81
+
82
+ Frame arrays carry no metadata, so (like transformers) assume a 24 fps source.
83
+ Returns (frames, source frame indices).
84
+ """
85
+ import numpy as np
86
+
87
+ video = np.asarray(video)
88
+ total = len(video)
89
+ n = int(total / source_fps * fps)
90
+ n = min(max(n, min_frames), max_frames, total)
91
+ indices = np.linspace(0, total - 1, n).round().astype(int)
92
+ return video[indices], indices.tolist()
93
+
94
+
95
+ def _timestamps(indices: list[int], source_fps: float, temporal_patch: int) -> list[float]:
96
+ indices = list(indices)
97
+ if len(indices) % temporal_patch:
98
+ indices.extend(indices[-1] for _ in range(temporal_patch - len(indices) % temporal_patch))
99
+ seconds = [i / source_fps for i in indices]
100
+ return [(seconds[i] + seconds[i + temporal_patch - 1]) / 2 for i in range(0, len(seconds), temporal_patch)]
101
+
102
+
103
+ def _encode_media(processor: Any, record: dict[str, Any]) -> tuple[list[int], dict[str, Any] | None]:
104
+ """Pixel preprocessing via the (torch-free) mlx-vlm processor; the token layout is
105
+ built here to match the transformers Qwen3-VL processor the model was trained with."""
106
+ import numpy as np
107
+
108
+ images = list(record.get("images") or [])
109
+ videos = list(record.get("videos") or [])
110
+ if not images and not videos:
111
+ return [], None
112
+ if processor is None:
113
+ raise ValueError("records with images or videos require a processor")
114
+ kwargs = dict(record.get("media_kwargs") or {})
115
+ sample = {k: kwargs.pop(k) for k in ("fps", "source_fps", "min_frames", "max_frames") if k in kwargs}
116
+ source_fps = sample.get("source_fps", 24.0)
117
+ do_sample = kwargs.pop("do_sample_frames", True)
118
+
119
+ media: dict[str, Any] = {}
120
+ text = ""
121
+ if images:
122
+ out = processor.image_processor(images=images, **kwargs)
123
+ media["pixel_values"] = mx.array(np.asarray(out["pixel_values"]))
124
+ grids = np.asarray(out["image_grid_thw"])
125
+ media["image_grid_thw"] = mx.array(grids)
126
+ merge = processor.image_processor.merge_size**2
127
+ for grid in grids:
128
+ text += "<|vision_start|>" + "<|image_pad|>" * (int(np.prod(grid)) // merge) + "<|vision_end|>"
129
+ if videos:
130
+ vp = processor.video_processor
131
+ frames, frame_indices = [], []
132
+ for v in videos:
133
+ f, idx = sample_frames(v, **sample) if do_sample else (np.asarray(v), list(range(len(v))))
134
+ frames.append(f)
135
+ frame_indices.append(idx)
136
+ out = vp(videos=frames, **kwargs)
137
+ media["pixel_values_videos"] = mx.array(np.asarray(out["pixel_values_videos"]))
138
+ grids = np.asarray(out["video_grid_thw"])
139
+ media["video_grid_thw"] = mx.array(grids)
140
+ for grid, idx in zip(grids, frame_indices):
141
+ per_frame = int(grid[1] * grid[2]) // vp.merge_size**2
142
+ stamps = _timestamps(idx, source_fps, vp.temporal_patch_size)
143
+ text += "<|vision_start|>"
144
+ for t in range(int(grid[0])):
145
+ text += f"<{stamps[t]:.1f} seconds><|vision_start|>" + "<|video_pad|>" * per_frame + "<|vision_end|>"
146
+ text += "<|vision_end|>"
147
+ text += "\n"
148
+ return _tokens(processor.tokenizer, text), media
149
+
150
+
151
+ def encode_record(
152
+ tokenizer: Any,
153
+ record: dict[str, Any],
154
+ max_length: int = 16384,
155
+ max_state_tokens: int | None = None,
156
+ processor: Any | None = None,
157
+ truncate: bool = True,
158
+ ) -> EncodedRecord:
159
+ """Encode a record. Like the reference, the state is truncated to fit ``max_length``
160
+ unless ``truncate=False``, in which case ``ContextTooLong`` is raised instead."""
161
+ schema_ids = _tokens(tokenizer, "\n\nSCHEMA FIELDS:\n")
162
+ questions: list[EncodedQuestion] = []
163
+ for qi, (question_id, question) in enumerate(record["questions"].items()):
164
+ schema_ids.extend(
165
+ _tokens(
166
+ tokenizer,
167
+ f"\nFIELD {qi + 1}\nID: {question_id}\nTYPE: {question['type']}\nINSTRUCTION: ",
168
+ )
169
+ )
170
+ q_start = len(schema_ids)
171
+ instructions = question.get("instructions") or str(question_id)
172
+ schema_ids.extend(_tokens(tokenizer, render(instructions)))
173
+ q_end = len(schema_ids)
174
+ schema_ids.extend(_tokens(tokenizer, "\nALLOWED OPTIONS:\n"))
175
+ option_spans, option_ids = [], []
176
+ for oi, (option_id, description) in enumerate(question_options(question)):
177
+ schema_ids.extend(_tokens(tokenizer, f"OPTION {oi + 1}: "))
178
+ o_start = len(schema_ids)
179
+ semantics = {"option_id": option_id}
180
+ if description is not None:
181
+ semantics["description"] = description
182
+ schema_ids.extend(_tokens(tokenizer, render(semantics)))
183
+ option_spans.append((o_start, len(schema_ids)))
184
+ option_ids.append(option_id)
185
+ schema_ids.extend(_tokens(tokenizer, "\n"))
186
+ schema_ids.extend(_tokens(tokenizer, "END FIELD\n"))
187
+ questions.append(
188
+ EncodedQuestion(
189
+ str(question_id),
190
+ QUESTION_TYPES[str(question["type"])],
191
+ (q_start, q_end),
192
+ tuple(option_spans),
193
+ tuple(option_ids),
194
+ )
195
+ )
196
+
197
+ prefix_ids = _tokens(
198
+ tokenizer, f"<|im_start|>system\n{SYSTEM_PROMPT}<|im_end|>\n<|im_start|>user\nSTATE:\n"
199
+ )
200
+ suffix_ids = _tokens(
201
+ tokenizer,
202
+ "\n<|im_end|>\n<|im_start|>assistant\n<think>\n\n</think>\n\nJOINT SCHEMA DECISIONS:",
203
+ )
204
+ media_ids, media = _encode_media(processor, record)
205
+ prefix_ids = prefix_ids + media_ids
206
+ state_ids = _tokens(tokenizer, render(record["state"]))
207
+ if max_state_tokens is not None:
208
+ state_ids = state_ids[:max_state_tokens]
209
+ fixed = len(prefix_ids) + len(schema_ids) + len(suffix_ids)
210
+ if fixed > max_length:
211
+ raise ContextTooLong(f"schema requires {fixed} tokens before state; maximum is {max_length}")
212
+ if not truncate and fixed + len(state_ids) > max_length:
213
+ raise ContextTooLong(f"request needs {fixed + len(state_ids)} tokens; maximum is {max_length}")
214
+ state_ids = state_ids[: max_length - fixed]
215
+ off = len(prefix_ids) + len(state_ids)
216
+ shifted = tuple(
217
+ EncodedQuestion(
218
+ q.question_id,
219
+ q.question_type,
220
+ (q.question_span[0] + off, q.question_span[1] + off),
221
+ tuple((s + off, e + off) for s, e in q.option_spans),
222
+ q.option_ids,
223
+ )
224
+ for q in questions
225
+ )
226
+ return EncodedRecord(tuple(prefix_ids + state_ids + schema_ids + suffix_ids), shifted, media)
227
+
228
+
229
+ # --------------------------------------------------------------------------- head
230
+
231
+
232
+ class MultiheadAttention(nn.Module):
233
+ """torch.nn.MultiheadAttention (batch_first, packed in_proj) in MLX."""
234
+
235
+ def __init__(self, width: int, heads: int):
236
+ super().__init__()
237
+ self.heads = heads
238
+ self.in_proj_weight = mx.zeros((3 * width, width))
239
+ self.in_proj_bias = mx.zeros((3 * width,))
240
+ self.out_proj = nn.Linear(width, width)
241
+
242
+ def __call__(self, q: mx.array, k: mx.array, v: mx.array) -> mx.array:
243
+ w = self.in_proj_weight
244
+ b = self.in_proj_bias
245
+ d = w.shape[1]
246
+ q = q @ w[:d].T + b[:d]
247
+ k = k @ w[d : 2 * d].T + b[d : 2 * d]
248
+ v = v @ w[2 * d :].T + b[2 * d :]
249
+ B, Lq, _ = q.shape
250
+ Lk = k.shape[1]
251
+ hd = d // self.heads
252
+ q = q.reshape(B, Lq, self.heads, hd).transpose(0, 2, 1, 3)
253
+ k = k.reshape(B, Lk, self.heads, hd).transpose(0, 2, 1, 3)
254
+ v = v.reshape(B, Lk, self.heads, hd).transpose(0, 2, 1, 3)
255
+ o = mx.fast.scaled_dot_product_attention(q, k, v, scale=hd**-0.5)
256
+ return self.out_proj(o.transpose(0, 2, 1, 3).reshape(B, Lq, d))
257
+
258
+
259
+ class FeedForward(nn.Module):
260
+ def __init__(self, width: int, feedforward: int):
261
+ super().__init__()
262
+ self.fc1 = nn.Linear(width, feedforward)
263
+ self.fc2 = nn.Linear(feedforward, width)
264
+
265
+ def __call__(self, x):
266
+ return self.fc2(nn.gelu(self.fc1(x)))
267
+
268
+
269
+ class EvidenceRoutingLayer(nn.Module):
270
+ def __init__(self, width: int, heads: int, feedforward: int):
271
+ super().__init__()
272
+ self.query_norm = nn.LayerNorm(width)
273
+ self.memory_norm = nn.LayerNorm(width)
274
+ self.attention = MultiheadAttention(width, heads)
275
+ self.feedforward_norm = nn.LayerNorm(width)
276
+ self.feedforward = FeedForward(width, feedforward)
277
+
278
+ def __call__(self, queries, memory):
279
+ m = self.memory_norm(memory)
280
+ queries = queries + self.attention(self.query_norm(queries), m, m)
281
+ return queries + self.feedforward(self.feedforward_norm(queries))
282
+
283
+
284
+ class TransformerDecoderLayer(nn.Module):
285
+ """torch.nn.TransformerDecoderLayer(norm_first=True, activation='gelu')."""
286
+
287
+ def __init__(self, width: int, heads: int, feedforward: int):
288
+ super().__init__()
289
+ self.self_attn = MultiheadAttention(width, heads)
290
+ self.multihead_attn = MultiheadAttention(width, heads)
291
+ self.linear1 = nn.Linear(width, feedforward)
292
+ self.linear2 = nn.Linear(feedforward, width)
293
+ self.norm1 = nn.LayerNorm(width)
294
+ self.norm2 = nn.LayerNorm(width)
295
+ self.norm3 = nn.LayerNorm(width)
296
+
297
+ def __call__(self, x, memory):
298
+ h = self.norm1(x)
299
+ x = x + self.self_attn(h, h, h)
300
+ x = x + self.multihead_attn(self.norm2(x), memory, memory)
301
+ return x + self.linear2(nn.gelu(self.linear1(self.norm3(x))))
302
+
303
+
304
+ def _l2norm(x, eps=1e-12):
305
+ return x / mx.maximum(mx.linalg.norm(x, axis=-1, keepdims=True), eps)
306
+
307
+
308
+ class JointSchemaHead(nn.Module):
309
+ def __init__(self, hidden_size, width, routing_layers, layers, heads, feedforward):
310
+ super().__init__()
311
+ self.hidden_norm = nn.LayerNorm(hidden_size)
312
+ self.memory_projection = nn.Linear(hidden_size, width, bias=False)
313
+ self.question_projection = nn.Linear(hidden_size, width, bias=False)
314
+ self.option_question_projection = nn.Linear(hidden_size, width, bias=False)
315
+ self.global_projection = nn.Linear(hidden_size, width, bias=False)
316
+ self.option_context_projection = nn.Linear(hidden_size, width, bias=False)
317
+ self.option_lexical_projection = nn.Linear(hidden_size, width, bias=False)
318
+ self.type_embedding = nn.Embedding(3, width)
319
+ self.evidence_layers = [
320
+ EvidenceRoutingLayer(width, heads, feedforward) for _ in range(routing_layers)
321
+ ]
322
+ self.option_summary_norm = nn.LayerNorm(width)
323
+ self.layers = [TransformerDecoderLayer(width, heads, feedforward) for _ in range(layers)]
324
+ self.field_norm = nn.LayerNorm(width)
325
+ self.option_norm = nn.LayerNorm(width)
326
+ self.scorer1 = nn.Linear(width * 4, width)
327
+ self.scorer2 = nn.Linear(width, 1)
328
+ self.prior_logit_scale = mx.zeros(())
329
+ self.joint_logit_scale = mx.zeros(())
330
+ self.residual_gate = mx.zeros(())
331
+
332
+ @staticmethod
333
+ def sanitize(weights: dict[str, mx.array]) -> dict[str, mx.array]:
334
+ out = {}
335
+ for k, v in weights.items():
336
+ k = k.replace(".feedforward.0.", ".feedforward.fc1.")
337
+ k = k.replace(".feedforward.3.", ".feedforward.fc2.")
338
+ k = k.replace("residual_scorer.0.", "scorer1.").replace("residual_scorer.3.", "scorer2.")
339
+ out[k] = v
340
+ return out
341
+
342
+ def __call__(self, hidden, input_ids, record: EncodedRecord, lexical_lookup):
343
+ """hidden: (L, H) final backbone states for one record. Returns list of (n_opts,)."""
344
+ h = self.hidden_norm(hidden)
345
+ memory = self.memory_projection(h)[None]
346
+ global_vector = h[-1]
347
+ qs = record.questions
348
+ question_vectors = mx.stack([h[s:e].mean(0) for s, e in (q.question_span for q in qs)])
349
+ type_ids = mx.array([q.question_type for q in qs])
350
+
351
+ option_contexts, lexical_options, counts = [], [], []
352
+ for q in qs:
353
+ option_contexts.append(mx.stack([h[s:e].mean(0) for s, e in q.option_spans]))
354
+ lexical_options.append(
355
+ mx.stack([lexical_lookup(input_ids[s:e]).mean(0) for s, e in q.option_spans])
356
+ )
357
+ counts.append(len(q.option_spans))
358
+
359
+ option_queries = [
360
+ self.option_context_projection(c)
361
+ + self.option_lexical_projection(lx)
362
+ + self.option_question_projection(question_vectors[i])[None]
363
+ for i, (c, lx) in enumerate(zip(option_contexts, lexical_options))
364
+ ]
365
+ routed = mx.concatenate(option_queries, axis=0)[None]
366
+ for layer in self.evidence_layers:
367
+ routed = layer(routed, memory)
368
+ routed = routed[0]
369
+ splits = [int(x) for x in mx.cumsum(mx.array(counts))[:-1].tolist()]
370
+ split_options = mx.split(routed, splits, axis=0) if splits else [routed]
371
+
372
+ base_fields = self.question_projection(question_vectors)
373
+ summaries = []
374
+ for field, options in zip(base_fields, split_options):
375
+ w = mx.softmax((options @ field) / math.sqrt(options.shape[-1]), axis=0)
376
+ summaries.append((w[:, None] * options).sum(0))
377
+ fields = (
378
+ base_fields
379
+ + self.option_summary_norm(mx.stack(summaries))
380
+ + self.global_projection(global_vector)[None]
381
+ + self.type_embedding(type_ids)
382
+ )[None]
383
+ for layer in self.layers:
384
+ fields = layer(fields, memory)
385
+ fields = self.field_norm(fields[0])
386
+
387
+ prior_scale = mx.exp(mx.minimum(self.prior_logit_scale, math.log(100.0)))
388
+ joint_scale = mx.exp(mx.minimum(self.joint_logit_scale, math.log(100.0)))
389
+ gate = mx.sigmoid(self.residual_gate)
390
+ logits = []
391
+ for i, (field, lexical, routed_opts) in enumerate(zip(fields, lexical_options, split_options)):
392
+ anchor = _l2norm(question_vectors[i] + global_vector)
393
+ prior = prior_scale * (_l2norm(lexical) @ anchor)
394
+ options = self.option_norm(routed_opts)
395
+ rf = mx.broadcast_to(field[None], options.shape)
396
+ cosine = (rf * options).sum(-1) / mx.maximum(
397
+ mx.linalg.norm(rf, axis=-1) * mx.linalg.norm(options, axis=-1), 1e-8
398
+ )
399
+ feats = mx.concatenate([rf, options, rf * options, mx.abs(rf - options)], axis=-1)
400
+ residual = self.scorer2(nn.gelu(self.scorer1(feats)))[:, 0]
401
+ logits.append(prior + gate * (joint_scale * cosine + residual))
402
+ return logits
403
+
404
+
405
+ # --------------------------------------------------------------------------- model
406
+
407
+
408
+ class ClefMLX:
409
+ def __init__(self, backbone, tokenizer, head: JointSchemaHead, processor=None):
410
+ self.backbone = backbone
411
+ if type(tokenizer).__name__ == "TokenizerWrapper": # mlx-lm wrapper
412
+ tokenizer = tokenizer._tokenizer
413
+ self.tokenizer = tokenizer
414
+ self.processor = processor
415
+ self.head = head
416
+ self.vision = hasattr(backbone, "vision_tower")
417
+ lm = backbone.language_model
418
+ self._text_model = lm.model
419
+ self._out = lm.lm_head if hasattr(lm, "lm_head") else lm.model.embed_tokens
420
+
421
+ def _lexical(self, ids: mx.array) -> mx.array:
422
+ """Rows of the output-embedding matrix, dequantized if needed."""
423
+ m = self._out
424
+ if isinstance(m, (nn.QuantizedLinear, nn.QuantizedEmbedding)):
425
+ return mx.dequantize(
426
+ m.weight[ids], m.scales[ids], m.get("biases")[ids] if "biases" in m else None,
427
+ group_size=m.group_size, bits=m.bits, mode=getattr(m, "mode", "affine"),
428
+ )
429
+ return m.weight[ids]
430
+
431
+ def _hidden(self, ids: mx.array, media: dict[str, Any] | None) -> mx.array:
432
+ if not self.vision:
433
+ if media:
434
+ raise ValueError("this checkpoint has no vision tower; convert with mlx_vlm")
435
+ return self._text_model(ids[None])[0]
436
+ media = media or {}
437
+ if "pixel_values" in media and "pixel_values_videos" in media:
438
+ raise NotImplementedError("mixing images and videos in one record is not supported")
439
+ pixel_values = media.get("pixel_values", media.get("pixel_values_videos"))
440
+ feats = self.backbone.get_input_embeddings(
441
+ ids[None],
442
+ pixel_values=pixel_values,
443
+ image_grid_thw=media.get("image_grid_thw"),
444
+ video_grid_thw=media.get("video_grid_thw"),
445
+ )
446
+ return self._text_model(
447
+ ids[None], inputs_embeds=feats.inputs_embeds, position_ids=feats.position_ids
448
+ )[0]
449
+
450
+ def logits(self, record: dict[str, Any], **encode_kwargs) -> tuple[EncodedRecord, list[mx.array]]:
451
+ enc = encode_record(self.tokenizer, record, processor=self.processor, **encode_kwargs)
452
+ ids = mx.array(enc.input_ids)
453
+ hidden = self._hidden(ids, enc.media)
454
+ out = self.head(hidden, ids, enc, self._lexical)
455
+ mx.eval(out)
456
+ return enc, out
457
+
458
+ def predict(self, record: dict[str, Any], **kw) -> dict[str, dict[str, float]]:
459
+ enc, logits = self.logits(record, **kw)
460
+ return {
461
+ q.question_id: dict(zip(q.option_ids, mx.softmax(lg.astype(mx.float32)).tolist()))
462
+ for q, lg in zip(enc.questions, logits)
463
+ }
464
+
465
+ def systemone(self, request: dict[str, Any], max_length: int = 16384, truncate: bool = True) -> dict[str, Any]:
466
+ """Answer a Jev/SystemOne ``POST /v1/systemone`` request body (same response body)."""
467
+ questions = request.get("questions")
468
+ if not isinstance(request.get("model"), str) or "state" not in request:
469
+ raise ValueError("model and state are required")
470
+ if not isinstance(questions, dict) or not questions:
471
+ raise ValueError("at least one question is required")
472
+ for qid, q in questions.items():
473
+ if q.get("type") not in QUESTION_TYPES:
474
+ raise ValueError(f"{qid}: type must be noul, choice, or score")
475
+ if q["type"] != "noul" and not q.get("criteria"):
476
+ raise ValueError(f"{qid}: criteria must not be empty")
477
+ enc, logits = self.logits(request, max_length=max_length, truncate=truncate)
478
+ answers = {
479
+ q.question_id: systemone_answer(
480
+ questions[q.question_id],
481
+ dict(zip(q.option_ids, mx.softmax(lg.astype(mx.float32)).tolist())),
482
+ )
483
+ for q, lg in zip(enc.questions, logits)
484
+ }
485
+ return {
486
+ "model": request["model"],
487
+ "answers": answers,
488
+ "usage": {"input_tokens": len(enc.input_ids), "output_tokens": 0},
489
+ }
490
+
491
+
492
+ def systemone_answer(question: dict[str, Any], probabilities: dict[str, float]) -> dict[str, Any]:
493
+ if question["type"] == "noul":
494
+ return {"type": "noul", "noul": round(probabilities["true"], 4)}
495
+ if question["type"] == "choice":
496
+ options = [str(o) for o in question["criteria"]]
497
+ choice = max(options, key=probabilities.__getitem__)
498
+ return {
499
+ "type": "choice",
500
+ "choice": choice,
501
+ "confidence": round(probabilities[choice], 4),
502
+ "probabilities": {o: round(probabilities[o], 4) for o in options},
503
+ }
504
+ levels = [str(i) for i in range(len(question["criteria"]))]
505
+ return {
506
+ "type": "score",
507
+ "score": round(sum(i * probabilities[lv] for i, lv in enumerate(levels)), 4),
508
+ "confidence": round(max(probabilities[lv] for lv in levels), 4),
509
+ "legend": dict(zip(levels, question["criteria"])),
510
+ "probabilities": {lv: round(probabilities[lv], 4) for lv in levels},
511
+ }
512
+
513
+
514
+ def _has_vision_weights(path: Path) -> bool:
515
+ index = path / "model.safetensors.index.json"
516
+ if index.exists():
517
+ keys = json.loads(index.read_text())["weight_map"]
518
+ else:
519
+ keys = mx.load(str(next(path.glob("*.safetensors"))))
520
+ return any(k.startswith(("vision_tower", "model.visual")) for k in keys)
521
+
522
+
523
+ def load(path: str | Path, head_dtype=mx.bfloat16, backend: str = "auto") -> ClefMLX:
524
+ """Load an MLX Clef checkpoint (local dir or HF repo id).
525
+
526
+ backend: "vlm" (mlx-vlm, text + images/video), "lm" (mlx-lm, text only), or "auto".
527
+ """
528
+ path = Path(path)
529
+ if not path.is_dir():
530
+ from huggingface_hub import snapshot_download
531
+
532
+ path = Path(snapshot_download(str(path)))
533
+ if backend == "auto":
534
+ backend = "vlm" if _has_vision_weights(path) else "lm"
535
+ processor = None
536
+ if backend == "vlm":
537
+ from mlx_vlm import load as vlm_load
538
+
539
+ backbone, processor = vlm_load(str(path))
540
+ tokenizer = processor.tokenizer
541
+ else:
542
+ from mlx_lm import load as lm_load
543
+
544
+ backbone, tokenizer = lm_load(str(path))
545
+ cfg = json.loads((path / "joint_head_config.json").read_text())
546
+ head = JointSchemaHead(**cfg)
547
+ weights = JointSchemaHead.sanitize(mx.load(str(path / "joint_head.safetensors")))
548
+ head.load_weights(list(weights.items()), strict=True)
549
+ head.set_dtype(head_dtype)
550
+ mx.eval(head.parameters())
551
+ return ClefMLX(backbone, tokenizer, head, processor)
config.json ADDED
@@ -0,0 +1,173 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "Qwen3_5ForConditionalGeneration"
4
+ ],
5
+ "do_sample": true,
6
+ "dtype": "bfloat16",
7
+ "eos_token_id": [
8
+ 248046,
9
+ 248044
10
+ ],
11
+ "generation_config": {
12
+ "bos_token_id": 248044,
13
+ "do_sample": true,
14
+ "eos_token_id": [
15
+ 248046,
16
+ 248044
17
+ ],
18
+ "pad_token_id": 248044,
19
+ "temperature": 1.0,
20
+ "top_k": 20,
21
+ "top_p": 0.95,
22
+ "transformers_version": "5.10.2"
23
+ },
24
+ "image_token_id": 248056,
25
+ "language_model_only": false,
26
+ "model_type": "qwen3_5",
27
+ "quantization": {
28
+ "group_size": 64,
29
+ "bits": 8,
30
+ "mode": "affine"
31
+ },
32
+ "quantization_config": {
33
+ "group_size": 64,
34
+ "bits": 8,
35
+ "mode": "affine"
36
+ },
37
+ "temperature": 1.0,
38
+ "text_config": {
39
+ "attention_bias": false,
40
+ "attention_dropout": 0.0,
41
+ "attn_output_gate": true,
42
+ "bos_token_id": 248044,
43
+ "dtype": "bfloat16",
44
+ "eos_token_id": 248044,
45
+ "full_attention_interval": 4,
46
+ "head_dim": 256,
47
+ "hidden_act": "silu",
48
+ "hidden_size": 5120,
49
+ "initializer_range": 0.02,
50
+ "intermediate_size": 17408,
51
+ "layer_types": [
52
+ "linear_attention",
53
+ "linear_attention",
54
+ "linear_attention",
55
+ "full_attention",
56
+ "linear_attention",
57
+ "linear_attention",
58
+ "linear_attention",
59
+ "full_attention",
60
+ "linear_attention",
61
+ "linear_attention",
62
+ "linear_attention",
63
+ "full_attention",
64
+ "linear_attention",
65
+ "linear_attention",
66
+ "linear_attention",
67
+ "full_attention",
68
+ "linear_attention",
69
+ "linear_attention",
70
+ "linear_attention",
71
+ "full_attention",
72
+ "linear_attention",
73
+ "linear_attention",
74
+ "linear_attention",
75
+ "full_attention",
76
+ "linear_attention",
77
+ "linear_attention",
78
+ "linear_attention",
79
+ "full_attention",
80
+ "linear_attention",
81
+ "linear_attention",
82
+ "linear_attention",
83
+ "full_attention",
84
+ "linear_attention",
85
+ "linear_attention",
86
+ "linear_attention",
87
+ "full_attention",
88
+ "linear_attention",
89
+ "linear_attention",
90
+ "linear_attention",
91
+ "full_attention",
92
+ "linear_attention",
93
+ "linear_attention",
94
+ "linear_attention",
95
+ "full_attention",
96
+ "linear_attention",
97
+ "linear_attention",
98
+ "linear_attention",
99
+ "full_attention",
100
+ "linear_attention",
101
+ "linear_attention",
102
+ "linear_attention",
103
+ "full_attention",
104
+ "linear_attention",
105
+ "linear_attention",
106
+ "linear_attention",
107
+ "full_attention",
108
+ "linear_attention",
109
+ "linear_attention",
110
+ "linear_attention",
111
+ "full_attention",
112
+ "linear_attention",
113
+ "linear_attention",
114
+ "linear_attention",
115
+ "full_attention"
116
+ ],
117
+ "linear_conv_kernel_dim": 4,
118
+ "linear_key_head_dim": 128,
119
+ "linear_num_key_heads": 16,
120
+ "linear_num_value_heads": 48,
121
+ "linear_value_head_dim": 128,
122
+ "mamba_ssm_dtype": "float32",
123
+ "max_position_embeddings": 262144,
124
+ "model_type": "qwen3_5_text",
125
+ "mtp_num_hidden_layers": 0,
126
+ "mtp_use_dedicated_embeddings": false,
127
+ "num_attention_heads": 24,
128
+ "num_hidden_layers": 64,
129
+ "num_key_value_heads": 4,
130
+ "output_gate_type": "swish",
131
+ "pad_token_id": null,
132
+ "partial_rotary_factor": 0.25,
133
+ "rms_norm_eps": 1e-06,
134
+ "rope_parameters": {
135
+ "mrope_interleaved": true,
136
+ "mrope_section": [
137
+ 11,
138
+ 11,
139
+ 10
140
+ ],
141
+ "partial_rotary_factor": 0.25,
142
+ "rope_theta": 10000000,
143
+ "rope_type": "default"
144
+ },
145
+ "tie_word_embeddings": false,
146
+ "use_cache": true,
147
+ "vocab_size": 248320
148
+ },
149
+ "tie_word_embeddings": false,
150
+ "top_k": 20,
151
+ "top_p": 0.95,
152
+ "transformers_version": "5.10.2",
153
+ "video_token_id": 248057,
154
+ "vision_config": {
155
+ "deepstack_visual_indexes": [],
156
+ "depth": 27,
157
+ "dtype": "bfloat16",
158
+ "hidden_act": "gelu_pytorch_tanh",
159
+ "hidden_size": 1152,
160
+ "in_channels": 3,
161
+ "initializer_range": 0.02,
162
+ "intermediate_size": 4304,
163
+ "model_type": "qwen3_5_vision",
164
+ "num_heads": 16,
165
+ "num_position_embeddings": 2304,
166
+ "out_hidden_size": 5120,
167
+ "patch_size": 16,
168
+ "spatial_merge_size": 2,
169
+ "temporal_patch_size": 2
170
+ },
171
+ "vision_end_token_id": 248054,
172
+ "vision_start_token_id": 248053
173
+ }
generation_config.json ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "bos_token_id": 248044,
3
+ "do_sample": true,
4
+ "eos_token_id": [
5
+ 248046,
6
+ 248044
7
+ ],
8
+ "pad_token_id": 248044,
9
+ "temperature": 1.0,
10
+ "top_k": 20,
11
+ "top_p": 0.95,
12
+ "transformers_version": "5.10.2"
13
+ }
joint_head.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a010ac04f078e699988e4049cbea5e62c962393f59fec366640b64e8d69a4953
3
+ size 256125024
joint_head_config.json ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "hidden_size": 5120,
3
+ "width": 1024,
4
+ "routing_layers": 2,
5
+ "layers": 4,
6
+ "heads": 16,
7
+ "feedforward": 4096
8
+ }
model-00001-of-00006.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c7921fe72af5c961c3c4230ea25068ed6d1e502d5ecb2b4a53b7c9c213effa0c
3
+ size 5317707581
model-00002-of-00006.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e9d93d15495354045da281f102649b99793e5b6ed0e05852c58f46e6616b54a0
3
+ size 5354102610
model-00003-of-00006.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7015f40310c86a18230e28644832b624532333d5dfbf7584e6c62341dbd8975e
3
+ size 5354184694
model-00004-of-00006.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b99b75d269cc037e6501bc7ce951126b66ab8be876e936980bdda045bd76017d
3
+ size 5337309653
model-00005-of-00006.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:83d7b64daac098749889b74307e3c2b41be8c256ac643be8cae40bccdd8778ab
3
+ size 5292848464
model-00006-of-00006.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:17442d87f0ca4d71ae790349b1eccb14b5c82886358b5b45e3e6bd1a0d17f1fc
3
+ size 2845065477
model.safetensors.index.json ADDED
The diff for this file is too large to render. See raw diff
 
processor_config.json ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "image_processor": {
3
+ "do_convert_rgb": true,
4
+ "do_normalize": true,
5
+ "do_rescale": true,
6
+ "do_resize": true,
7
+ "image_mean": [
8
+ 0.5,
9
+ 0.5,
10
+ 0.5
11
+ ],
12
+ "image_processor_type": "Qwen2VLImageProcessor",
13
+ "image_std": [
14
+ 0.5,
15
+ 0.5,
16
+ 0.5
17
+ ],
18
+ "merge_size": 2,
19
+ "patch_size": 16,
20
+ "resample": 3,
21
+ "rescale_factor": 0.00392156862745098,
22
+ "size": {
23
+ "longest_edge": 16777216,
24
+ "shortest_edge": 65536
25
+ },
26
+ "temporal_patch_size": 2
27
+ },
28
+ "processor_class": "Qwen3VLProcessor",
29
+ "video_processor": {
30
+ "do_convert_rgb": true,
31
+ "do_normalize": true,
32
+ "do_rescale": true,
33
+ "do_resize": true,
34
+ "do_sample_frames": true,
35
+ "fps": 2,
36
+ "image_mean": [
37
+ 0.5,
38
+ 0.5,
39
+ 0.5
40
+ ],
41
+ "image_std": [
42
+ 0.5,
43
+ 0.5,
44
+ 0.5
45
+ ],
46
+ "max_frames": 768,
47
+ "merge_size": 2,
48
+ "min_frames": 4,
49
+ "patch_size": 16,
50
+ "resample": 3,
51
+ "rescale_factor": 0.00392156862745098,
52
+ "return_metadata": false,
53
+ "size": {
54
+ "longest_edge": 25165824,
55
+ "shortest_edge": 4096
56
+ },
57
+ "temporal_patch_size": 2,
58
+ "video_processor_type": "Qwen3VLVideoProcessor"
59
+ }
60
+ }
tokenizer.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a5cd9732badce41de57e6efce8302930ded1c1188c5f81feb2bd6c24c4a1941f
3
+ size 19989339
tokenizer_config.json ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_prefix_space": false,
3
+ "audio_bos_token": "<|audio_start|>",
4
+ "audio_eos_token": "<|audio_end|>",
5
+ "audio_token": "<|audio_pad|>",
6
+ "backend": "tokenizers",
7
+ "bos_token": null,
8
+ "clean_up_tokenization_spaces": false,
9
+ "eos_token": "<|im_end|>",
10
+ "errors": "replace",
11
+ "image_token": "<|image_pad|>",
12
+ "is_local": true,
13
+ "local_files_only": false,
14
+ "merges_file": null,
15
+ "model_max_length": 262144,
16
+ "model_specific_special_tokens": {
17
+ "audio_bos_token": "<|audio_start|>",
18
+ "audio_eos_token": "<|audio_end|>",
19
+ "audio_token": "<|audio_pad|>",
20
+ "image_token": "<|image_pad|>",
21
+ "video_token": "<|video_pad|>",
22
+ "vision_bos_token": "<|vision_start|>",
23
+ "vision_eos_token": "<|vision_end|>"
24
+ },
25
+ "pad_token": "<|endoftext|>",
26
+ "pretokenize_regex": "(?i:'s|'t|'re|'ve|'m|'ll|'d)|[^\\r\\n\\p{L}\\p{N}]?[\\p{L}\\p{M}]+|\\p{N}| ?[^\\s\\p{L}\\p{M}\\p{N}]+[\\r\\n]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+",
27
+ "processor_class": "Qwen3VLProcessor",
28
+ "split_special_tokens": false,
29
+ "tokenizer_class": "Qwen3_5Tokenizer",
30
+ "unk_token": null,
31
+ "video_token": "<|video_pad|>",
32
+ "vision_bos_token": "<|vision_start|>",
33
+ "vision_eos_token": "<|vision_end|>"
34
+ }