lucataco commited on
Commit
e0a23bd
·
verified ·
1 Parent(s): 460b5d6

Add MLX 4-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,90 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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-4bit
19
+
20
+ [Cloudflare/clef](https://huggingface.co/Cloudflare/clef) converted to MLX (4-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-4bit")
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 4 --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.037 |
84
+ | Images + video (5 records, 9 questions) | 9/9 | 0.097 |
85
+
86
+ Measured on an M5 Max (128 GB). Small spot-check, not a full benchmark run.
87
+
88
+ ## License
89
+
90
+ Apache-2.0, following [Cloudflare/clef](https://huggingface.co/Cloudflare/clef).
__pycache__/clef_mlx.cpython-312.pyc ADDED
Binary file (38.5 kB). View file
 
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,542 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ # --------------------------------------------------------------------------- encoding
32
+ # Mirrors joint_schema_model.encode_record (text-only path) exactly.
33
+
34
+
35
+ def render(value: Any) -> str:
36
+ if isinstance(value, str):
37
+ return value
38
+ return json.dumps(value, ensure_ascii=False, separators=(",", ":"), sort_keys=True)
39
+
40
+
41
+ def question_options(question: dict[str, Any]) -> list[tuple[str, Any]]:
42
+ question_type = str(question["type"])
43
+ if question_type == "noul":
44
+ criteria = {
45
+ "true": "The proposition is true or the answer is yes.",
46
+ "false": "The proposition is false or the answer is no.",
47
+ }
48
+ criteria.update(question.get("criteria") or {})
49
+ return [(key, criteria[key]) for key in ("true", "false")]
50
+ if question_type == "choice":
51
+ return sorted((str(key), value) for key, value in question["criteria"].items())
52
+ return [(str(index), value) for index, value in enumerate(question["criteria"])]
53
+
54
+
55
+ @dataclass(frozen=True)
56
+ class EncodedQuestion:
57
+ question_id: str
58
+ question_type: int
59
+ question_span: tuple[int, int]
60
+ option_spans: tuple[tuple[int, int], ...]
61
+ option_ids: tuple[str, ...]
62
+
63
+
64
+ @dataclass(frozen=True)
65
+ class EncodedRecord:
66
+ input_ids: tuple[int, ...]
67
+ questions: tuple[EncodedQuestion, ...]
68
+ media: dict[str, Any] | None = field(default=None, compare=False, repr=False)
69
+
70
+
71
+ def _tokens(tokenizer: Any, text: str) -> list[int]:
72
+ return tokenizer(text, add_special_tokens=False).input_ids
73
+
74
+
75
+ def sample_frames(video, fps=2.0, source_fps=24.0, min_frames=4, max_frames=768):
76
+ """Uniform frame sampling matching transformers' Qwen3VLVideoProcessor.
77
+
78
+ Frame arrays carry no metadata, so (like transformers) assume a 24 fps source.
79
+ Returns (frames, source frame indices).
80
+ """
81
+ import numpy as np
82
+
83
+ video = np.asarray(video)
84
+ total = len(video)
85
+ n = int(total / source_fps * fps)
86
+ n = min(max(n, min_frames), max_frames, total)
87
+ indices = np.linspace(0, total - 1, n).round().astype(int)
88
+ return video[indices], indices.tolist()
89
+
90
+
91
+ def _timestamps(indices: list[int], source_fps: float, temporal_patch: int) -> list[float]:
92
+ indices = list(indices)
93
+ if len(indices) % temporal_patch:
94
+ indices.extend(indices[-1] for _ in range(temporal_patch - len(indices) % temporal_patch))
95
+ seconds = [i / source_fps for i in indices]
96
+ return [(seconds[i] + seconds[i + temporal_patch - 1]) / 2 for i in range(0, len(seconds), temporal_patch)]
97
+
98
+
99
+ def _encode_media(processor: Any, record: dict[str, Any]) -> tuple[list[int], dict[str, Any] | None]:
100
+ """Pixel preprocessing via the (torch-free) mlx-vlm processor; the token layout is
101
+ built here to match the transformers Qwen3-VL processor the model was trained with."""
102
+ import numpy as np
103
+
104
+ images = list(record.get("images") or [])
105
+ videos = list(record.get("videos") or [])
106
+ if not images and not videos:
107
+ return [], None
108
+ if processor is None:
109
+ raise ValueError("records with images or videos require a processor")
110
+ kwargs = dict(record.get("media_kwargs") or {})
111
+ sample = {k: kwargs.pop(k) for k in ("fps", "source_fps", "min_frames", "max_frames") if k in kwargs}
112
+ source_fps = sample.get("source_fps", 24.0)
113
+ do_sample = kwargs.pop("do_sample_frames", True)
114
+
115
+ media: dict[str, Any] = {}
116
+ text = ""
117
+ if images:
118
+ out = processor.image_processor(images=images, **kwargs)
119
+ media["pixel_values"] = mx.array(np.asarray(out["pixel_values"]))
120
+ grids = np.asarray(out["image_grid_thw"])
121
+ media["image_grid_thw"] = mx.array(grids)
122
+ merge = processor.image_processor.merge_size**2
123
+ for grid in grids:
124
+ text += "<|vision_start|>" + "<|image_pad|>" * (int(np.prod(grid)) // merge) + "<|vision_end|>"
125
+ if videos:
126
+ vp = processor.video_processor
127
+ frames, frame_indices = [], []
128
+ for v in videos:
129
+ f, idx = sample_frames(v, **sample) if do_sample else (np.asarray(v), list(range(len(v))))
130
+ frames.append(f)
131
+ frame_indices.append(idx)
132
+ out = vp(videos=frames, **kwargs)
133
+ media["pixel_values_videos"] = mx.array(np.asarray(out["pixel_values_videos"]))
134
+ grids = np.asarray(out["video_grid_thw"])
135
+ media["video_grid_thw"] = mx.array(grids)
136
+ for grid, idx in zip(grids, frame_indices):
137
+ per_frame = int(grid[1] * grid[2]) // vp.merge_size**2
138
+ stamps = _timestamps(idx, source_fps, vp.temporal_patch_size)
139
+ text += "<|vision_start|>"
140
+ for t in range(int(grid[0])):
141
+ text += f"<{stamps[t]:.1f} seconds><|vision_start|>" + "<|video_pad|>" * per_frame + "<|vision_end|>"
142
+ text += "<|vision_end|>"
143
+ text += "\n"
144
+ return _tokens(processor.tokenizer, text), media
145
+
146
+
147
+ def encode_record(
148
+ tokenizer: Any,
149
+ record: dict[str, Any],
150
+ max_length: int = 16384,
151
+ max_state_tokens: int | None = None,
152
+ processor: Any | None = None,
153
+ ) -> EncodedRecord:
154
+ schema_ids = _tokens(tokenizer, "\n\nSCHEMA FIELDS:\n")
155
+ questions: list[EncodedQuestion] = []
156
+ for qi, (question_id, question) in enumerate(record["questions"].items()):
157
+ schema_ids.extend(
158
+ _tokens(
159
+ tokenizer,
160
+ f"\nFIELD {qi + 1}\nID: {question_id}\nTYPE: {question['type']}\nINSTRUCTION: ",
161
+ )
162
+ )
163
+ q_start = len(schema_ids)
164
+ instructions = question.get("instructions") or str(question_id)
165
+ schema_ids.extend(_tokens(tokenizer, render(instructions)))
166
+ q_end = len(schema_ids)
167
+ schema_ids.extend(_tokens(tokenizer, "\nALLOWED OPTIONS:\n"))
168
+ option_spans, option_ids = [], []
169
+ for oi, (option_id, description) in enumerate(question_options(question)):
170
+ schema_ids.extend(_tokens(tokenizer, f"OPTION {oi + 1}: "))
171
+ o_start = len(schema_ids)
172
+ semantics = {"option_id": option_id}
173
+ if description is not None:
174
+ semantics["description"] = description
175
+ schema_ids.extend(_tokens(tokenizer, render(semantics)))
176
+ option_spans.append((o_start, len(schema_ids)))
177
+ option_ids.append(option_id)
178
+ schema_ids.extend(_tokens(tokenizer, "\n"))
179
+ schema_ids.extend(_tokens(tokenizer, "END FIELD\n"))
180
+ questions.append(
181
+ EncodedQuestion(
182
+ str(question_id),
183
+ QUESTION_TYPES[str(question["type"])],
184
+ (q_start, q_end),
185
+ tuple(option_spans),
186
+ tuple(option_ids),
187
+ )
188
+ )
189
+
190
+ prefix_ids = _tokens(
191
+ tokenizer, f"<|im_start|>system\n{SYSTEM_PROMPT}<|im_end|>\n<|im_start|>user\nSTATE:\n"
192
+ )
193
+ suffix_ids = _tokens(
194
+ tokenizer,
195
+ "\n<|im_end|>\n<|im_start|>assistant\n<think>\n\n</think>\n\nJOINT SCHEMA DECISIONS:",
196
+ )
197
+ media_ids, media = _encode_media(processor, record)
198
+ prefix_ids = prefix_ids + media_ids
199
+ state_ids = _tokens(tokenizer, render(record["state"]))
200
+ if max_state_tokens is not None:
201
+ state_ids = state_ids[:max_state_tokens]
202
+ fixed = len(prefix_ids) + len(schema_ids) + len(suffix_ids)
203
+ if fixed > max_length:
204
+ raise ValueError(f"schema requires {fixed} tokens before state; maximum is {max_length}")
205
+ state_ids = state_ids[: max_length - fixed]
206
+ off = len(prefix_ids) + len(state_ids)
207
+ shifted = tuple(
208
+ EncodedQuestion(
209
+ q.question_id,
210
+ q.question_type,
211
+ (q.question_span[0] + off, q.question_span[1] + off),
212
+ tuple((s + off, e + off) for s, e in q.option_spans),
213
+ q.option_ids,
214
+ )
215
+ for q in questions
216
+ )
217
+ return EncodedRecord(tuple(prefix_ids + state_ids + schema_ids + suffix_ids), shifted, media)
218
+
219
+
220
+ # --------------------------------------------------------------------------- head
221
+
222
+
223
+ class MultiheadAttention(nn.Module):
224
+ """torch.nn.MultiheadAttention (batch_first, packed in_proj) in MLX."""
225
+
226
+ def __init__(self, width: int, heads: int):
227
+ super().__init__()
228
+ self.heads = heads
229
+ self.in_proj_weight = mx.zeros((3 * width, width))
230
+ self.in_proj_bias = mx.zeros((3 * width,))
231
+ self.out_proj = nn.Linear(width, width)
232
+
233
+ def __call__(self, q: mx.array, k: mx.array, v: mx.array) -> mx.array:
234
+ w = self.in_proj_weight
235
+ b = self.in_proj_bias
236
+ d = w.shape[1]
237
+ q = q @ w[:d].T + b[:d]
238
+ k = k @ w[d : 2 * d].T + b[d : 2 * d]
239
+ v = v @ w[2 * d :].T + b[2 * d :]
240
+ B, Lq, _ = q.shape
241
+ Lk = k.shape[1]
242
+ hd = d // self.heads
243
+ q = q.reshape(B, Lq, self.heads, hd).transpose(0, 2, 1, 3)
244
+ k = k.reshape(B, Lk, self.heads, hd).transpose(0, 2, 1, 3)
245
+ v = v.reshape(B, Lk, self.heads, hd).transpose(0, 2, 1, 3)
246
+ o = mx.fast.scaled_dot_product_attention(q, k, v, scale=hd**-0.5)
247
+ return self.out_proj(o.transpose(0, 2, 1, 3).reshape(B, Lq, d))
248
+
249
+
250
+ class FeedForward(nn.Module):
251
+ def __init__(self, width: int, feedforward: int):
252
+ super().__init__()
253
+ self.fc1 = nn.Linear(width, feedforward)
254
+ self.fc2 = nn.Linear(feedforward, width)
255
+
256
+ def __call__(self, x):
257
+ return self.fc2(nn.gelu(self.fc1(x)))
258
+
259
+
260
+ class EvidenceRoutingLayer(nn.Module):
261
+ def __init__(self, width: int, heads: int, feedforward: int):
262
+ super().__init__()
263
+ self.query_norm = nn.LayerNorm(width)
264
+ self.memory_norm = nn.LayerNorm(width)
265
+ self.attention = MultiheadAttention(width, heads)
266
+ self.feedforward_norm = nn.LayerNorm(width)
267
+ self.feedforward = FeedForward(width, feedforward)
268
+
269
+ def __call__(self, queries, memory):
270
+ m = self.memory_norm(memory)
271
+ queries = queries + self.attention(self.query_norm(queries), m, m)
272
+ return queries + self.feedforward(self.feedforward_norm(queries))
273
+
274
+
275
+ class TransformerDecoderLayer(nn.Module):
276
+ """torch.nn.TransformerDecoderLayer(norm_first=True, activation='gelu')."""
277
+
278
+ def __init__(self, width: int, heads: int, feedforward: int):
279
+ super().__init__()
280
+ self.self_attn = MultiheadAttention(width, heads)
281
+ self.multihead_attn = MultiheadAttention(width, heads)
282
+ self.linear1 = nn.Linear(width, feedforward)
283
+ self.linear2 = nn.Linear(feedforward, width)
284
+ self.norm1 = nn.LayerNorm(width)
285
+ self.norm2 = nn.LayerNorm(width)
286
+ self.norm3 = nn.LayerNorm(width)
287
+
288
+ def __call__(self, x, memory):
289
+ h = self.norm1(x)
290
+ x = x + self.self_attn(h, h, h)
291
+ x = x + self.multihead_attn(self.norm2(x), memory, memory)
292
+ return x + self.linear2(nn.gelu(self.linear1(self.norm3(x))))
293
+
294
+
295
+ def _l2norm(x, eps=1e-12):
296
+ return x / mx.maximum(mx.linalg.norm(x, axis=-1, keepdims=True), eps)
297
+
298
+
299
+ class JointSchemaHead(nn.Module):
300
+ def __init__(self, hidden_size, width, routing_layers, layers, heads, feedforward):
301
+ super().__init__()
302
+ self.hidden_norm = nn.LayerNorm(hidden_size)
303
+ self.memory_projection = nn.Linear(hidden_size, width, bias=False)
304
+ self.question_projection = nn.Linear(hidden_size, width, bias=False)
305
+ self.option_question_projection = nn.Linear(hidden_size, width, bias=False)
306
+ self.global_projection = nn.Linear(hidden_size, width, bias=False)
307
+ self.option_context_projection = nn.Linear(hidden_size, width, bias=False)
308
+ self.option_lexical_projection = nn.Linear(hidden_size, width, bias=False)
309
+ self.type_embedding = nn.Embedding(3, width)
310
+ self.evidence_layers = [
311
+ EvidenceRoutingLayer(width, heads, feedforward) for _ in range(routing_layers)
312
+ ]
313
+ self.option_summary_norm = nn.LayerNorm(width)
314
+ self.layers = [TransformerDecoderLayer(width, heads, feedforward) for _ in range(layers)]
315
+ self.field_norm = nn.LayerNorm(width)
316
+ self.option_norm = nn.LayerNorm(width)
317
+ self.scorer1 = nn.Linear(width * 4, width)
318
+ self.scorer2 = nn.Linear(width, 1)
319
+ self.prior_logit_scale = mx.zeros(())
320
+ self.joint_logit_scale = mx.zeros(())
321
+ self.residual_gate = mx.zeros(())
322
+
323
+ @staticmethod
324
+ def sanitize(weights: dict[str, mx.array]) -> dict[str, mx.array]:
325
+ out = {}
326
+ for k, v in weights.items():
327
+ k = k.replace(".feedforward.0.", ".feedforward.fc1.")
328
+ k = k.replace(".feedforward.3.", ".feedforward.fc2.")
329
+ k = k.replace("residual_scorer.0.", "scorer1.").replace("residual_scorer.3.", "scorer2.")
330
+ out[k] = v
331
+ return out
332
+
333
+ def __call__(self, hidden, input_ids, record: EncodedRecord, lexical_lookup):
334
+ """hidden: (L, H) final backbone states for one record. Returns list of (n_opts,)."""
335
+ h = self.hidden_norm(hidden)
336
+ memory = self.memory_projection(h)[None]
337
+ global_vector = h[-1]
338
+ qs = record.questions
339
+ question_vectors = mx.stack([h[s:e].mean(0) for s, e in (q.question_span for q in qs)])
340
+ type_ids = mx.array([q.question_type for q in qs])
341
+
342
+ option_contexts, lexical_options, counts = [], [], []
343
+ for q in qs:
344
+ option_contexts.append(mx.stack([h[s:e].mean(0) for s, e in q.option_spans]))
345
+ lexical_options.append(
346
+ mx.stack([lexical_lookup(input_ids[s:e]).mean(0) for s, e in q.option_spans])
347
+ )
348
+ counts.append(len(q.option_spans))
349
+
350
+ option_queries = [
351
+ self.option_context_projection(c)
352
+ + self.option_lexical_projection(lx)
353
+ + self.option_question_projection(question_vectors[i])[None]
354
+ for i, (c, lx) in enumerate(zip(option_contexts, lexical_options))
355
+ ]
356
+ routed = mx.concatenate(option_queries, axis=0)[None]
357
+ for layer in self.evidence_layers:
358
+ routed = layer(routed, memory)
359
+ routed = routed[0]
360
+ splits = [int(x) for x in mx.cumsum(mx.array(counts))[:-1].tolist()]
361
+ split_options = mx.split(routed, splits, axis=0) if splits else [routed]
362
+
363
+ base_fields = self.question_projection(question_vectors)
364
+ summaries = []
365
+ for field, options in zip(base_fields, split_options):
366
+ w = mx.softmax((options @ field) / math.sqrt(options.shape[-1]), axis=0)
367
+ summaries.append((w[:, None] * options).sum(0))
368
+ fields = (
369
+ base_fields
370
+ + self.option_summary_norm(mx.stack(summaries))
371
+ + self.global_projection(global_vector)[None]
372
+ + self.type_embedding(type_ids)
373
+ )[None]
374
+ for layer in self.layers:
375
+ fields = layer(fields, memory)
376
+ fields = self.field_norm(fields[0])
377
+
378
+ prior_scale = mx.exp(mx.minimum(self.prior_logit_scale, math.log(100.0)))
379
+ joint_scale = mx.exp(mx.minimum(self.joint_logit_scale, math.log(100.0)))
380
+ gate = mx.sigmoid(self.residual_gate)
381
+ logits = []
382
+ for i, (field, lexical, routed_opts) in enumerate(zip(fields, lexical_options, split_options)):
383
+ anchor = _l2norm(question_vectors[i] + global_vector)
384
+ prior = prior_scale * (_l2norm(lexical) @ anchor)
385
+ options = self.option_norm(routed_opts)
386
+ rf = mx.broadcast_to(field[None], options.shape)
387
+ cosine = (rf * options).sum(-1) / mx.maximum(
388
+ mx.linalg.norm(rf, axis=-1) * mx.linalg.norm(options, axis=-1), 1e-8
389
+ )
390
+ feats = mx.concatenate([rf, options, rf * options, mx.abs(rf - options)], axis=-1)
391
+ residual = self.scorer2(nn.gelu(self.scorer1(feats)))[:, 0]
392
+ logits.append(prior + gate * (joint_scale * cosine + residual))
393
+ return logits
394
+
395
+
396
+ # --------------------------------------------------------------------------- model
397
+
398
+
399
+ class ClefMLX:
400
+ def __init__(self, backbone, tokenizer, head: JointSchemaHead, processor=None):
401
+ self.backbone = backbone
402
+ if type(tokenizer).__name__ == "TokenizerWrapper": # mlx-lm wrapper
403
+ tokenizer = tokenizer._tokenizer
404
+ self.tokenizer = tokenizer
405
+ self.processor = processor
406
+ self.head = head
407
+ self.vision = hasattr(backbone, "vision_tower")
408
+ lm = backbone.language_model
409
+ self._text_model = lm.model
410
+ self._out = lm.lm_head if hasattr(lm, "lm_head") else lm.model.embed_tokens
411
+
412
+ def _lexical(self, ids: mx.array) -> mx.array:
413
+ """Rows of the output-embedding matrix, dequantized if needed."""
414
+ m = self._out
415
+ if isinstance(m, (nn.QuantizedLinear, nn.QuantizedEmbedding)):
416
+ return mx.dequantize(
417
+ m.weight[ids], m.scales[ids], m.get("biases")[ids] if "biases" in m else None,
418
+ group_size=m.group_size, bits=m.bits, mode=getattr(m, "mode", "affine"),
419
+ )
420
+ return m.weight[ids]
421
+
422
+ def _hidden(self, ids: mx.array, media: dict[str, Any] | None) -> mx.array:
423
+ if not self.vision:
424
+ if media:
425
+ raise ValueError("this checkpoint has no vision tower; convert with mlx_vlm")
426
+ return self._text_model(ids[None])[0]
427
+ media = media or {}
428
+ if "pixel_values" in media and "pixel_values_videos" in media:
429
+ raise NotImplementedError("mixing images and videos in one record is not supported")
430
+ pixel_values = media.get("pixel_values", media.get("pixel_values_videos"))
431
+ feats = self.backbone.get_input_embeddings(
432
+ ids[None],
433
+ pixel_values=pixel_values,
434
+ image_grid_thw=media.get("image_grid_thw"),
435
+ video_grid_thw=media.get("video_grid_thw"),
436
+ )
437
+ return self._text_model(
438
+ ids[None], inputs_embeds=feats.inputs_embeds, position_ids=feats.position_ids
439
+ )[0]
440
+
441
+ def logits(self, record: dict[str, Any], **encode_kwargs) -> tuple[EncodedRecord, list[mx.array]]:
442
+ enc = encode_record(self.tokenizer, record, processor=self.processor, **encode_kwargs)
443
+ ids = mx.array(enc.input_ids)
444
+ hidden = self._hidden(ids, enc.media)
445
+ out = self.head(hidden, ids, enc, self._lexical)
446
+ mx.eval(out)
447
+ return enc, out
448
+
449
+ def predict(self, record: dict[str, Any], **kw) -> dict[str, dict[str, float]]:
450
+ enc, logits = self.logits(record, **kw)
451
+ return {
452
+ q.question_id: dict(zip(q.option_ids, mx.softmax(lg.astype(mx.float32)).tolist()))
453
+ for q, lg in zip(enc.questions, logits)
454
+ }
455
+
456
+ def systemone(self, request: dict[str, Any], max_length: int = 16384) -> dict[str, Any]:
457
+ """Answer a Jev/SystemOne ``POST /v1/systemone`` request body (same response body)."""
458
+ questions = request.get("questions")
459
+ if not isinstance(request.get("model"), str) or "state" not in request:
460
+ raise ValueError("model and state are required")
461
+ if not isinstance(questions, dict) or not questions:
462
+ raise ValueError("at least one question is required")
463
+ for qid, q in questions.items():
464
+ if q.get("type") not in QUESTION_TYPES:
465
+ raise ValueError(f"{qid}: type must be noul, choice, or score")
466
+ if q["type"] != "noul" and not q.get("criteria"):
467
+ raise ValueError(f"{qid}: criteria must not be empty")
468
+ enc, logits = self.logits(request, max_length=max_length)
469
+ answers = {
470
+ q.question_id: systemone_answer(
471
+ questions[q.question_id],
472
+ dict(zip(q.option_ids, mx.softmax(lg.astype(mx.float32)).tolist())),
473
+ )
474
+ for q, lg in zip(enc.questions, logits)
475
+ }
476
+ return {
477
+ "model": request["model"],
478
+ "answers": answers,
479
+ "usage": {"input_tokens": len(enc.input_ids), "output_tokens": 0},
480
+ }
481
+
482
+
483
+ def systemone_answer(question: dict[str, Any], probabilities: dict[str, float]) -> dict[str, Any]:
484
+ if question["type"] == "noul":
485
+ return {"type": "noul", "noul": round(probabilities["true"], 4)}
486
+ if question["type"] == "choice":
487
+ options = [str(o) for o in question["criteria"]]
488
+ choice = max(options, key=probabilities.__getitem__)
489
+ return {
490
+ "type": "choice",
491
+ "choice": choice,
492
+ "confidence": round(probabilities[choice], 4),
493
+ "probabilities": {o: round(probabilities[o], 4) for o in options},
494
+ }
495
+ levels = [str(i) for i in range(len(question["criteria"]))]
496
+ return {
497
+ "type": "score",
498
+ "score": round(sum(i * probabilities[lv] for i, lv in enumerate(levels)), 4),
499
+ "confidence": round(max(probabilities[lv] for lv in levels), 4),
500
+ "legend": dict(zip(levels, question["criteria"])),
501
+ "probabilities": {lv: round(probabilities[lv], 4) for lv in levels},
502
+ }
503
+
504
+
505
+ def _has_vision_weights(path: Path) -> bool:
506
+ index = path / "model.safetensors.index.json"
507
+ if index.exists():
508
+ keys = json.loads(index.read_text())["weight_map"]
509
+ else:
510
+ keys = mx.load(str(next(path.glob("*.safetensors"))))
511
+ return any(k.startswith(("vision_tower", "model.visual")) for k in keys)
512
+
513
+
514
+ def load(path: str | Path, head_dtype=mx.bfloat16, backend: str = "auto") -> ClefMLX:
515
+ """Load an MLX Clef checkpoint (local dir or HF repo id).
516
+
517
+ backend: "vlm" (mlx-vlm, text + images/video), "lm" (mlx-lm, text only), or "auto".
518
+ """
519
+ path = Path(path)
520
+ if not path.is_dir():
521
+ from huggingface_hub import snapshot_download
522
+
523
+ path = Path(snapshot_download(str(path)))
524
+ if backend == "auto":
525
+ backend = "vlm" if _has_vision_weights(path) else "lm"
526
+ processor = None
527
+ if backend == "vlm":
528
+ from mlx_vlm import load as vlm_load
529
+
530
+ backbone, processor = vlm_load(str(path))
531
+ tokenizer = processor.tokenizer
532
+ else:
533
+ from mlx_lm import load as lm_load
534
+
535
+ backbone, tokenizer = lm_load(str(path))
536
+ cfg = json.loads((path / "joint_head_config.json").read_text())
537
+ head = JointSchemaHead(**cfg)
538
+ weights = JointSchemaHead.sanitize(mx.load(str(path / "joint_head.safetensors")))
539
+ head.load_weights(list(weights.items()), strict=True)
540
+ head.set_dtype(head_dtype)
541
+ mx.eval(head.parameters())
542
+ 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": 4,
30
+ "mode": "affine"
31
+ },
32
+ "quantization_config": {
33
+ "group_size": 64,
34
+ "bits": 4,
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-00003.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6cc1508e96fb5d0865dfd5753a79f4ec60651bf3e2a82844a7e8ae9c60528c0d
3
+ size 5343268662
model-00002-of-00003.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6b0933f831ddcfacd2ae4d4d1dc326db0578fddc5fcf48319eed20b202f9c962
3
+ size 5354185130
model-00003-of-00003.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f97fd037229334ce55a1d74f401546279a43113fe8d01adf4213f0c98a546585
3
+ size 5357087557
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
+ }