T8RIN commited on
Commit
cb16f2e
·
verified ·
1 Parent(s): 48fef12

Add Qwen3.5 Vision Lite and Vision Max for ImageToolbox

Browse files

CPU INT8 multimodal packages with pinned source provenance, original licenses, SHA-256 manifests, visual encoder parity reports and reproducible export recipes. Existing assistant packages are retained.

Files changed (50) hide show
  1. .gitattributes +8 -0
  2. assistant/v1/vision_lite/LICENSE +202 -0
  3. assistant/v1/vision_lite/README.md +9 -0
  4. assistant/v1/vision_lite/chat_template.jinja +154 -0
  5. assistant/v1/vision_lite/config.json +96 -0
  6. assistant/v1/vision_lite/embedding.onnx +3 -0
  7. assistant/v1/vision_lite/embedding.onnx.data +3 -0
  8. assistant/v1/vision_lite/genai_config.json +105 -0
  9. assistant/v1/vision_lite/manifest.json +56 -0
  10. assistant/v1/vision_lite/processor_config.json +76 -0
  11. assistant/v1/vision_lite/provenance.json +93 -0
  12. assistant/v1/vision_lite/text.onnx +3 -0
  13. assistant/v1/vision_lite/text.onnx.data +3 -0
  14. assistant/v1/vision_lite/tokenizer.json +3 -0
  15. assistant/v1/vision_lite/tokenizer_config.json +48 -0
  16. assistant/v1/vision_lite/vision-parity.json +44 -0
  17. assistant/v1/vision_lite/vision.onnx +3 -0
  18. assistant/v1/vision_lite/vision.onnx.data +3 -0
  19. assistant/v1/vision_max/LICENSE +202 -0
  20. assistant/v1/vision_max/README.md +9 -0
  21. assistant/v1/vision_max/chat_template.jinja +154 -0
  22. assistant/v1/vision_max/config.json +96 -0
  23. assistant/v1/vision_max/embedding.onnx +3 -0
  24. assistant/v1/vision_max/embedding.onnx.data +3 -0
  25. assistant/v1/vision_max/genai_config.json +105 -0
  26. assistant/v1/vision_max/manifest.json +56 -0
  27. assistant/v1/vision_max/processor_config.json +76 -0
  28. assistant/v1/vision_max/provenance.json +93 -0
  29. assistant/v1/vision_max/text.onnx +3 -0
  30. assistant/v1/vision_max/text.onnx.data +3 -0
  31. assistant/v1/vision_max/tokenizer.json +3 -0
  32. assistant/v1/vision_max/tokenizer_config.json +48 -0
  33. assistant/v1/vision_max/vision-parity.json +44 -0
  34. assistant/v1/vision_max/vision.onnx +3 -0
  35. assistant/v1/vision_max/vision.onnx.data +3 -0
  36. assistant/vision-export/v1/LICENSE-Microsoft +21 -0
  37. assistant/vision-export/v1/LICENSE-Qwen +202 -0
  38. assistant/vision-export/v1/README.md +23 -0
  39. assistant/vision-export/v1/check_tokenizer.py +26 -0
  40. assistant/vision-export/v1/codes/__init__.py +0 -0
  41. assistant/vision-export/v1/codes/modeling_qwen3_5.py +489 -0
  42. assistant/vision-export/v1/compare_precision.py +52 -0
  43. assistant/vision-export/v1/configure_package.py +54 -0
  44. assistant/vision-export/v1/export_models.py +35 -0
  45. assistant/vision-export/v1/prepare_export.py +48 -0
  46. assistant/vision-export/v1/requirements.txt +10 -0
  47. assistant/vision-export/v1/smoke.py +50 -0
  48. assistant/vision-export/v1/trim_rope.py +45 -0
  49. assistant/vision-export/v1/user_script.py +93 -0
  50. assistant/vision-export/v1/verify_vision.py +66 -0
.gitattributes CHANGED
@@ -40,3 +40,11 @@ assistant/v1/advanced/model.onnx.data filter=lfs diff=lfs merge=lfs -text
40
  assistant/v1/advanced/tokenizer.json filter=lfs diff=lfs merge=lfs -text
41
  assistant/v1/max/model.onnx.data filter=lfs diff=lfs merge=lfs -text
42
  assistant/v1/max/tokenizer.json filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
 
 
40
  assistant/v1/advanced/tokenizer.json filter=lfs diff=lfs merge=lfs -text
41
  assistant/v1/max/model.onnx.data filter=lfs diff=lfs merge=lfs -text
42
  assistant/v1/max/tokenizer.json filter=lfs diff=lfs merge=lfs -text
43
+ assistant/v1/vision_lite/embedding.onnx.data filter=lfs diff=lfs merge=lfs -text
44
+ assistant/v1/vision_lite/text.onnx.data filter=lfs diff=lfs merge=lfs -text
45
+ assistant/v1/vision_lite/tokenizer.json filter=lfs diff=lfs merge=lfs -text
46
+ assistant/v1/vision_lite/vision.onnx.data filter=lfs diff=lfs merge=lfs -text
47
+ assistant/v1/vision_max/embedding.onnx.data filter=lfs diff=lfs merge=lfs -text
48
+ assistant/v1/vision_max/text.onnx.data filter=lfs diff=lfs merge=lfs -text
49
+ assistant/v1/vision_max/tokenizer.json filter=lfs diff=lfs merge=lfs -text
50
+ assistant/v1/vision_max/vision.onnx.data filter=lfs diff=lfs merge=lfs -text
assistant/v1/vision_lite/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.
assistant/v1/vision_lite/README.md ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ # Vision Lite
2
+
3
+ Local image understanding for ImageToolbox, based on [Qwen/Qwen3.5-0.8B](https://huggingface.co/Qwen/Qwen3.5-0.8B/tree/2fc06364715b967f1860aea9cf38778875588b17).
4
+
5
+ This package contains the complete vision encoder, image/text embedding fusion and recurrent text decoder for ONNX Runtime GenAI 0.17.0 on CPU. All three components use INT8 weights with FP32 input/output tensors. It supports image descriptions, captions, content questions and editing suggestions, plus text-only app assistance.
6
+
7
+ The application downloads 1,276,010,062 bytes. `manifest.json` lists the exact runtime files, sizes and SHA-256 digests. The supported application context is 4,096 tokens; a single image occupies at most 576 tokens. Input text must be NFC-normalized. Greedy generation with repetition penalty 1.1 was selected over sampling for more stable short responses.
8
+
9
+ See [the export recipe](../../vision-export/v1/README.md), `provenance.json`, the original Apache 2.0 `LICENSE`, and the visual encoder parity report. This is a conversion of the source model without fine-tuning. Small models can make factual and language mistakes; image content and generated editing advice should remain reviewable by the user.
assistant/v1/vision_lite/chat_template.jinja ADDED
@@ -0,0 +1,154 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ {%- if tools and tools is iterable and tools is not mapping %}
46
+ {{- '<|im_start|>system\n' }}
47
+ {{- "# Tools\n\nYou have access to the following functions:\n\n<tools>" }}
48
+ {%- for tool in tools %}
49
+ {{- "\n" }}
50
+ {{- tool | tojson }}
51
+ {%- endfor %}
52
+ {{- "\n</tools>" }}
53
+ {{- '\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>' }}
54
+ {%- if messages[0].role == 'system' %}
55
+ {%- set content = render_content(messages[0].content, false, true)|trim %}
56
+ {%- if content %}
57
+ {{- '\n\n' + content }}
58
+ {%- endif %}
59
+ {%- endif %}
60
+ {{- '<|im_end|>\n' }}
61
+ {%- else %}
62
+ {%- if messages[0].role == 'system' %}
63
+ {%- set content = render_content(messages[0].content, false, true)|trim %}
64
+ {{- '<|im_start|>system\n' + content + '<|im_end|>\n' }}
65
+ {%- endif %}
66
+ {%- endif %}
67
+ {%- set ns = namespace(multi_step_tool=true, last_query_index=messages|length - 1) %}
68
+ {%- for message in messages[::-1] %}
69
+ {%- set index = (messages|length - 1) - loop.index0 %}
70
+ {%- if ns.multi_step_tool and message.role == "user" %}
71
+ {%- set content = render_content(message.content, false)|trim %}
72
+ {%- if not(content.startswith('<tool_response>') and content.endswith('</tool_response>')) %}
73
+ {%- set ns.multi_step_tool = false %}
74
+ {%- set ns.last_query_index = index %}
75
+ {%- endif %}
76
+ {%- endif %}
77
+ {%- endfor %}
78
+ {%- if ns.multi_step_tool %}
79
+ {{- raise_exception('No user query found in messages.') }}
80
+ {%- endif %}
81
+ {%- for message in messages %}
82
+ {%- set content = render_content(message.content, true)|trim %}
83
+ {%- if message.role == "system" %}
84
+ {%- if not loop.first %}
85
+ {{- raise_exception('System message must be at the beginning.') }}
86
+ {%- endif %}
87
+ {%- elif message.role == "user" %}
88
+ {{- '<|im_start|>' + message.role + '\n' + content + '<|im_end|>' + '\n' }}
89
+ {%- elif message.role == "assistant" %}
90
+ {%- set reasoning_content = '' %}
91
+ {%- if message.reasoning_content is string %}
92
+ {%- set reasoning_content = message.reasoning_content %}
93
+ {%- else %}
94
+ {%- if '</think>' in content %}
95
+ {%- set reasoning_content = content.split('</think>')[0].rstrip('\n').split('<think>')[-1].lstrip('\n') %}
96
+ {%- set content = content.split('</think>')[-1].lstrip('\n') %}
97
+ {%- endif %}
98
+ {%- endif %}
99
+ {%- set reasoning_content = reasoning_content|trim %}
100
+ {%- if loop.index0 > ns.last_query_index %}
101
+ {{- '<|im_start|>' + message.role + '\n<think>\n' + reasoning_content + '\n</think>\n\n' + content }}
102
+ {%- else %}
103
+ {{- '<|im_start|>' + message.role + '\n' + content }}
104
+ {%- endif %}
105
+ {%- if message.tool_calls and message.tool_calls is iterable and message.tool_calls is not mapping %}
106
+ {%- for tool_call in message.tool_calls %}
107
+ {%- if tool_call.function is defined %}
108
+ {%- set tool_call = tool_call.function %}
109
+ {%- endif %}
110
+ {%- if loop.first %}
111
+ {%- if content|trim %}
112
+ {{- '\n\n<tool_call>\n<function=' + tool_call.name + '>\n' }}
113
+ {%- else %}
114
+ {{- '<tool_call>\n<function=' + tool_call.name + '>\n' }}
115
+ {%- endif %}
116
+ {%- else %}
117
+ {{- '\n<tool_call>\n<function=' + tool_call.name + '>\n' }}
118
+ {%- endif %}
119
+ {%- if tool_call.arguments is defined %}
120
+ {%- for args_name, args_value in tool_call.arguments|items %}
121
+ {{- '<parameter=' + args_name + '>\n' }}
122
+ {%- set args_value = args_value | tojson | safe if args_value is mapping or (args_value is sequence and args_value is not string) else args_value | string %}
123
+ {{- args_value }}
124
+ {{- '\n</parameter>\n' }}
125
+ {%- endfor %}
126
+ {%- endif %}
127
+ {{- '</function>\n</tool_call>' }}
128
+ {%- endfor %}
129
+ {%- endif %}
130
+ {{- '<|im_end|>\n' }}
131
+ {%- elif message.role == "tool" %}
132
+ {%- if loop.previtem and loop.previtem.role != "tool" %}
133
+ {{- '<|im_start|>user' }}
134
+ {%- endif %}
135
+ {{- '\n<tool_response>\n' }}
136
+ {{- content }}
137
+ {{- '\n</tool_response>' }}
138
+ {%- if not loop.last and loop.nextitem.role != "tool" %}
139
+ {{- '<|im_end|>\n' }}
140
+ {%- elif loop.last %}
141
+ {{- '<|im_end|>\n' }}
142
+ {%- endif %}
143
+ {%- else %}
144
+ {{- raise_exception('Unexpected message role.') }}
145
+ {%- endif %}
146
+ {%- endfor %}
147
+ {%- if add_generation_prompt %}
148
+ {{- '<|im_start|>assistant\n' }}
149
+ {%- if enable_thinking is defined and enable_thinking is true %}
150
+ {{- '<think>\n' }}
151
+ {%- else %}
152
+ {{- '<think>\n\n</think>\n\n' }}
153
+ {%- endif %}
154
+ {%- endif %}
assistant/v1/vision_lite/config.json ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "Qwen3_5ForConditionalGeneration"
4
+ ],
5
+ "image_token_id": 248056,
6
+ "model_type": "qwen3_5",
7
+ "text_config": {
8
+ "attention_bias": false,
9
+ "attention_dropout": 0.0,
10
+ "attn_output_gate": true,
11
+ "dtype": "bfloat16",
12
+ "eos_token_id": 248044,
13
+ "full_attention_interval": 4,
14
+ "head_dim": 256,
15
+ "hidden_act": "silu",
16
+ "hidden_size": 1024,
17
+ "initializer_range": 0.02,
18
+ "intermediate_size": 3584,
19
+ "layer_types": [
20
+ "linear_attention",
21
+ "linear_attention",
22
+ "linear_attention",
23
+ "full_attention",
24
+ "linear_attention",
25
+ "linear_attention",
26
+ "linear_attention",
27
+ "full_attention",
28
+ "linear_attention",
29
+ "linear_attention",
30
+ "linear_attention",
31
+ "full_attention",
32
+ "linear_attention",
33
+ "linear_attention",
34
+ "linear_attention",
35
+ "full_attention",
36
+ "linear_attention",
37
+ "linear_attention",
38
+ "linear_attention",
39
+ "full_attention",
40
+ "linear_attention",
41
+ "linear_attention",
42
+ "linear_attention",
43
+ "full_attention"
44
+ ],
45
+ "linear_conv_kernel_dim": 4,
46
+ "linear_key_head_dim": 128,
47
+ "linear_num_key_heads": 16,
48
+ "linear_num_value_heads": 16,
49
+ "linear_value_head_dim": 128,
50
+ "max_position_embeddings": 262144,
51
+ "mlp_only_layers": [],
52
+ "model_type": "qwen3_5_text",
53
+ "mtp_num_hidden_layers": 1,
54
+ "mtp_use_dedicated_embeddings": false,
55
+ "num_attention_heads": 8,
56
+ "num_hidden_layers": 24,
57
+ "num_key_value_heads": 2,
58
+ "rms_norm_eps": 1e-06,
59
+ "tie_word_embeddings": true,
60
+ "use_cache": true,
61
+ "vocab_size": 248320,
62
+ "mamba_ssm_dtype": "float32",
63
+ "rope_parameters": {
64
+ "mrope_interleaved": true,
65
+ "mrope_section": [
66
+ 11,
67
+ 11,
68
+ 10
69
+ ],
70
+ "rope_type": "default",
71
+ "rope_theta": 10000000,
72
+ "partial_rotary_factor": 0.25
73
+ }
74
+ },
75
+ "tie_word_embeddings": true,
76
+ "transformers_version": "4.57.0.dev0",
77
+ "video_token_id": 248057,
78
+ "vision_config": {
79
+ "deepstack_visual_indexes": [],
80
+ "depth": 12,
81
+ "hidden_act": "gelu_pytorch_tanh",
82
+ "hidden_size": 768,
83
+ "in_channels": 3,
84
+ "initializer_range": 0.02,
85
+ "intermediate_size": 3072,
86
+ "model_type": "qwen3_5",
87
+ "num_heads": 12,
88
+ "num_position_embeddings": 2304,
89
+ "out_hidden_size": 1024,
90
+ "patch_size": 16,
91
+ "spatial_merge_size": 2,
92
+ "temporal_patch_size": 2
93
+ },
94
+ "vision_end_token_id": 248054,
95
+ "vision_start_token_id": 248053
96
+ }
assistant/v1/vision_lite/embedding.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a90615fb71379f3a730d72adbf2def710b4f50b46f2470daf6bad8e8054dbdc5
3
+ size 2745
assistant/v1/vision_lite/embedding.onnx.data ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:80668d32e2bc7570fc97573263f4a21aa9c142e9d313397c79800b7846caef60
3
+ size 286064640
assistant/v1/vision_lite/genai_config.json ADDED
@@ -0,0 +1,105 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "model": {
3
+ "bos_token_id": 248044,
4
+ "context_length": 4096,
5
+ "decoder": {
6
+ "session_options": {
7
+ "log_id": "onnxruntime-genai",
8
+ "provider_options": [],
9
+ "intra_op_num_threads": 2,
10
+ "inter_op_num_threads": 1,
11
+ "mlas.disable_kleidiai": "1"
12
+ },
13
+ "filename": "text.onnx",
14
+ "head_size": 256,
15
+ "hidden_size": 1024,
16
+ "inputs": {
17
+ "inputs_embeds": "inputs_embeds",
18
+ "attention_mask": "attention_mask",
19
+ "position_ids": "position_ids",
20
+ "past_key_names": "past_key_values.%d.key",
21
+ "past_value_names": "past_key_values.%d.value",
22
+ "past_conv_names": "past.%d.conv",
23
+ "past_recurrent_names": "past.%d.recurrent"
24
+ },
25
+ "outputs": {
26
+ "logits": "logits",
27
+ "present_key_names": "present.%d.key",
28
+ "present_value_names": "present.%d.value",
29
+ "present_conv_names": "present.%d.conv",
30
+ "present_recurrent_names": "present.%d.recurrent"
31
+ },
32
+ "num_attention_heads": 8,
33
+ "num_hidden_layers": 24,
34
+ "num_key_value_heads": 2
35
+ },
36
+ "eos_token_id": [
37
+ 248046,
38
+ 248044
39
+ ],
40
+ "pad_token_id": 248044,
41
+ "type": "qwen3_5",
42
+ "vocab_size": 248320,
43
+ "bot_token_id": 248058,
44
+ "eot_token_id": 248059,
45
+ "bor_token_id": 248068,
46
+ "eor_token_id": 248069,
47
+ "embedding": {
48
+ "filename": "embedding.onnx",
49
+ "inputs": {
50
+ "input_ids": "input_ids",
51
+ "image_features": "image_features"
52
+ },
53
+ "outputs": {
54
+ "inputs_embeds": "inputs_embeds"
55
+ },
56
+ "session_options": {
57
+ "log_id": "onnxruntime-genai",
58
+ "provider_options": [],
59
+ "intra_op_num_threads": 2,
60
+ "inter_op_num_threads": 1,
61
+ "mlas.disable_kleidiai": "1"
62
+ }
63
+ },
64
+ "vision": {
65
+ "filename": "vision.onnx",
66
+ "config_filename": "processor_config.json",
67
+ "spatial_merge_size": 2,
68
+ "patch_size": 16,
69
+ "tokens_per_second": 2.0,
70
+ "inputs": {
71
+ "pixel_values": "pixel_values",
72
+ "image_grid_thw": "image_grid_thw"
73
+ },
74
+ "outputs": {
75
+ "image_features": "image_features"
76
+ },
77
+ "session_options": {
78
+ "log_id": "onnxruntime-genai",
79
+ "provider_options": [],
80
+ "intra_op_num_threads": 2,
81
+ "inter_op_num_threads": 1,
82
+ "mlas.disable_kleidiai": "1"
83
+ }
84
+ },
85
+ "image_token_id": 248056,
86
+ "video_token_id": 248057,
87
+ "vision_start_token_id": 248053
88
+ },
89
+ "search": {
90
+ "diversity_penalty": 0.0,
91
+ "do_sample": false,
92
+ "early_stopping": true,
93
+ "length_penalty": 1.0,
94
+ "max_length": 4096,
95
+ "min_length": 0,
96
+ "no_repeat_ngram_size": 0,
97
+ "num_beams": 1,
98
+ "num_return_sequences": 1,
99
+ "past_present_share_buffer": false,
100
+ "repetition_penalty": 1.1,
101
+ "temperature": 1.0,
102
+ "top_k": 1,
103
+ "top_p": 1.0
104
+ }
105
+ }
assistant/v1/vision_lite/manifest.json ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "variant": "vision_lite",
3
+ "runtime": "onnxruntime-genai 0.17.0",
4
+ "files": [
5
+ {
6
+ "name": "genai_config.json",
7
+ "size": 2866,
8
+ "sha256": "639443e319c3cfc4f2df9f65f50f1cffa2dadb402bb47d4e051ce3f1e4247235"
9
+ },
10
+ {
11
+ "name": "processor_config.json",
12
+ "size": 1528,
13
+ "sha256": "ceb4f9c08b4fb66a7dbba921d2da1074f57ddf58f12ccaa2052b0f0cf2f27caa"
14
+ },
15
+ {
16
+ "name": "tokenizer.json",
17
+ "size": 19989339,
18
+ "sha256": "a5cd9732badce41de57e6efce8302930ded1c1188c5f81feb2bd6c24c4a1941f"
19
+ },
20
+ {
21
+ "name": "tokenizer_config.json",
22
+ "size": 1462,
23
+ "sha256": "6bcfdefdea3da31bacc5741005cd5523a6a5bffcb5af4596f6b4641643450ee1"
24
+ },
25
+ {
26
+ "name": "embedding.onnx",
27
+ "size": 2745,
28
+ "sha256": "a90615fb71379f3a730d72adbf2def710b4f50b46f2470daf6bad8e8054dbdc5"
29
+ },
30
+ {
31
+ "name": "embedding.onnx.data",
32
+ "size": 286064640,
33
+ "sha256": "80668d32e2bc7570fc97573263f4a21aa9c142e9d313397c79800b7846caef60"
34
+ },
35
+ {
36
+ "name": "text.onnx",
37
+ "size": 363968,
38
+ "sha256": "51c0df5309939ce108fe4af71088ff67cc56fa7ce8e25d7f1be3b005bf89b514"
39
+ },
40
+ {
41
+ "name": "text.onnx.data",
42
+ "size": 851062016,
43
+ "sha256": "e78ac9a769e99996e9c3410a33fa68b67625f9a12297b73fb6b4389eeac29c88"
44
+ },
45
+ {
46
+ "name": "vision.onnx",
47
+ "size": 1539738,
48
+ "sha256": "c7e2a3ba4cb0ff56cf721b20210ea30366bddc462a8a2ae6b12783501f6e3cff"
49
+ },
50
+ {
51
+ "name": "vision.onnx.data",
52
+ "size": 116981760,
53
+ "sha256": "7ffa58330aa3907db3b0869792ebc721f752d2c86ef083d7ab113bd5af3ca966"
54
+ }
55
+ ]
56
+ }
assistant/v1/vision_lite/processor_config.json ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "processor": {
3
+ "name": "qwen2_5_image_processor",
4
+ "transforms": [
5
+ {
6
+ "operation": {
7
+ "name": "decode_image",
8
+ "type": "DecodeImage",
9
+ "attrs": {
10
+ "color_space": "RGB"
11
+ }
12
+ }
13
+ },
14
+ {
15
+ "operation": {
16
+ "name": "convert_to_rgb",
17
+ "type": "ConvertRGB"
18
+ }
19
+ },
20
+ {
21
+ "operation": {
22
+ "name": "resize",
23
+ "type": "Resize",
24
+ "attrs": {
25
+ "width": 768,
26
+ "height": 768,
27
+ "smart_resize": 1,
28
+ "min_pixels": 1024,
29
+ "max_pixels": 589824,
30
+ "patch_size": 16,
31
+ "merge_size": 2
32
+ }
33
+ }
34
+ },
35
+ {
36
+ "operation": {
37
+ "name": "rescale",
38
+ "type": "Rescale",
39
+ "attrs": {
40
+ "rescale_factor": 0.00392156862745098
41
+ }
42
+ }
43
+ },
44
+ {
45
+ "operation": {
46
+ "name": "normalize",
47
+ "type": "Normalize",
48
+ "attrs": {
49
+ "mean": [
50
+ 0.5,
51
+ 0.5,
52
+ 0.5
53
+ ],
54
+ "std": [
55
+ 0.5,
56
+ 0.5,
57
+ 0.5
58
+ ],
59
+ "qwen2_5_vl": 1
60
+ }
61
+ }
62
+ },
63
+ {
64
+ "operation": {
65
+ "name": "patch_image",
66
+ "type": "PatchImage",
67
+ "attrs": {
68
+ "patch_size": 16,
69
+ "temporal_patch_size": 2,
70
+ "merge_size": 2
71
+ }
72
+ }
73
+ }
74
+ ]
75
+ }
76
+ }
assistant/v1/vision_lite/provenance.json ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "source": {
3
+ "repository": "Qwen/Qwen3.5-0.8B",
4
+ "revision": "2fc06364715b967f1860aea9cf38778875588b17",
5
+ "license": "Apache-2.0"
6
+ },
7
+ "export": {
8
+ "runtime": "onnxruntime-genai",
9
+ "runtimeVersion": "0.17.0",
10
+ "executionProvider": "CPU",
11
+ "weightPrecision": "INT8",
12
+ "ioPrecision": "FP32",
13
+ "blockSize": 32,
14
+ "contextLength": 4096,
15
+ "maxImages": 1,
16
+ "maxImagePixels": 589824,
17
+ "maxImageTokens": 576,
18
+ "decoderAccuracyLevel": 4,
19
+ "visionAccuracyLevel": 1,
20
+ "embeddingAccuracyLevel": 1
21
+ },
22
+ "tokenizer": {
23
+ "nativeClass": "Qwen2Tokenizer",
24
+ "inputNormalization": "NFC",
25
+ "vocabularyAndMerges": "original",
26
+ "splitPreTokenizer": "original",
27
+ "thinking": false
28
+ },
29
+ "recipe": "../../vision-export/v1/export_models.py",
30
+ "libraries": {
31
+ "onnxruntime-genai": "0.17.0",
32
+ "onnxruntime": "1.31.0",
33
+ "torch": "2.14.1",
34
+ "transformers": "5.20.2",
35
+ "onnx": "1.23.2",
36
+ "onnx-ir": "1.0.0",
37
+ "onnxscript": "0.7.2",
38
+ "huggingface-hub": "2.2.0",
39
+ "Pillow": "13.0.0"
40
+ },
41
+ "sourceFiles": [
42
+ {
43
+ "name": "LICENSE",
44
+ "size": 11544,
45
+ "sha256": "bbedc3fda3305820b977265f01b8619d87570a6739de3a5582c3464840f1e57a"
46
+ },
47
+ {
48
+ "name": "chat_template.jinja",
49
+ "size": 7755,
50
+ "sha256": "273d8e0e683b885071fb17e08d71e5f2a5ddfb5309756181681de4f5a1822d80"
51
+ },
52
+ {
53
+ "name": "config.json",
54
+ "size": 2907,
55
+ "sha256": "b90b86f35c8e6925ef74ee04d0e758f0a845c83a42089ad82bbaa948de9b4204"
56
+ },
57
+ {
58
+ "name": "model.safetensors-00001-of-00001.safetensors",
59
+ "size": 1746942600,
60
+ "sha256": "04b1c301231dd422b8860db31311ab2721511346a32cb1e079c4c4e5f1fe4696"
61
+ },
62
+ {
63
+ "name": "model.safetensors.index.json",
64
+ "size": 50900,
65
+ "sha256": "d8a08838a613b025eb7952ed9db11696213e57e76a375661ef5c12f9dd5dcf4e"
66
+ },
67
+ {
68
+ "name": "preprocessor_config.json",
69
+ "size": 390,
70
+ "sha256": "27225450ac9c6529872ee1924fcb0962ff5634834f817040f444118116f4e516"
71
+ },
72
+ {
73
+ "name": "tokenizer.json",
74
+ "size": 12807982,
75
+ "sha256": "5f9e4d4901a92b997e463c1f46055088b6cca5ca61a6522d1b9f64c4bb81cb42"
76
+ },
77
+ {
78
+ "name": "tokenizer_config.json",
79
+ "size": 16709,
80
+ "sha256": "49e2b6e395f959f077f1e992b338919c0d4a9732fc6e613995e06557f843500c"
81
+ },
82
+ {
83
+ "name": "video_preprocessor_config.json",
84
+ "size": 385,
85
+ "sha256": "7768af27c1fafa9cc9011c1dc20067e03f8915e03b63504550e11d5066986d13"
86
+ },
87
+ {
88
+ "name": "vocab.json",
89
+ "size": 6722759,
90
+ "sha256": "ce99b4cb2983d118806ce0a8b777a35b093e2000a503ebde25853284c9dfa003"
91
+ }
92
+ ]
93
+ }
assistant/v1/vision_lite/text.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:51c0df5309939ce108fe4af71088ff67cc56fa7ce8e25d7f1be3b005bf89b514
3
+ size 363968
assistant/v1/vision_lite/text.onnx.data ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e78ac9a769e99996e9c3410a33fa68b67625f9a12297b73fb6b4389eeac29c88
3
+ size 851062016
assistant/v1/vision_lite/tokenizer.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a5cd9732badce41de57e6efce8302930ded1c1188c5f81feb2bd6c24c4a1941f
3
+ size 19989339
assistant/v1/vision_lite/tokenizer_config.json ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ "extra_special_tokens": [
12
+ "<|im_start|>",
13
+ "<|im_end|>",
14
+ "<|object_ref_start|>",
15
+ "<|object_ref_end|>",
16
+ "<|box_start|>",
17
+ "<|box_end|>",
18
+ "<|quad_start|>",
19
+ "<|quad_end|>",
20
+ "<|vision_start|>",
21
+ "<|vision_end|>",
22
+ "<|vision_pad|>",
23
+ "<|image_pad|>",
24
+ "<|video_pad|>"
25
+ ],
26
+ "image_token": "<|image_pad|>",
27
+ "is_local": true,
28
+ "local_files_only": false,
29
+ "merges_file": null,
30
+ "model_max_length": 262144,
31
+ "model_specific_special_tokens": {
32
+ "audio_bos_token": "<|audio_start|>",
33
+ "audio_eos_token": "<|audio_end|>",
34
+ "audio_token": "<|audio_pad|>",
35
+ "image_token": "<|image_pad|>",
36
+ "video_token": "<|video_pad|>",
37
+ "vision_bos_token": "<|vision_start|>",
38
+ "vision_eos_token": "<|vision_end|>"
39
+ },
40
+ "pad_token": "<|endoftext|>",
41
+ "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+",
42
+ "split_special_tokens": false,
43
+ "tokenizer_class": "Qwen2Tokenizer",
44
+ "unk_token": null,
45
+ "video_token": "<|video_pad|>",
46
+ "vision_bos_token": "<|vision_start|>",
47
+ "vision_eos_token": "<|vision_end|>"
48
+ }
assistant/v1/vision_lite/vision-parity.json ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [
2
+ {
3
+ "grid": [
4
+ 16,
5
+ 16
6
+ ],
7
+ "shape": [
8
+ 64,
9
+ 1024
10
+ ],
11
+ "float_max_abs": 6.008148193359375e-05,
12
+ "quantized_cosine": 0.9992821216583252,
13
+ "quantized_rmse": 0.005015345755964518,
14
+ "float_rms": 0.1290646493434906
15
+ },
16
+ {
17
+ "grid": [
18
+ 12,
19
+ 20
20
+ ],
21
+ "shape": [
22
+ 60,
23
+ 1024
24
+ ],
25
+ "float_max_abs": 1.9788742065429688e-05,
26
+ "quantized_cosine": 0.9988245368003845,
27
+ "quantized_rmse": 0.006604430265724659,
28
+ "float_rms": 0.13357654213905334
29
+ },
30
+ {
31
+ "grid": [
32
+ 48,
33
+ 48
34
+ ],
35
+ "shape": [
36
+ 576,
37
+ 1024
38
+ ],
39
+ "float_max_abs": 0.00015461444854736328,
40
+ "quantized_cosine": 0.997759222984314,
41
+ "quantized_rmse": 0.008364256471395493,
42
+ "float_rms": 0.12419654428958893
43
+ }
44
+ ]
assistant/v1/vision_lite/vision.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c7e2a3ba4cb0ff56cf721b20210ea30366bddc462a8a2ae6b12783501f6e3cff
3
+ size 1539738
assistant/v1/vision_lite/vision.onnx.data ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7ffa58330aa3907db3b0869792ebc721f752d2c86ef083d7ab113bd5af3ca966
3
+ size 116981760
assistant/v1/vision_max/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.
assistant/v1/vision_max/README.md ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ # Vision Max
2
+
3
+ Local image understanding for ImageToolbox, based on [Qwen/Qwen3.5-2B](https://huggingface.co/Qwen/Qwen3.5-2B/tree/15852e8c16360a2fea060d615a32b45270f8a8fc).
4
+
5
+ This package contains the complete vision encoder, image/text embedding fusion and recurrent text decoder for ONNX Runtime GenAI 0.17.0 on CPU. All three components use INT8 weights with FP32 input/output tensors. It supports image descriptions, captions, content questions and editing suggestions, plus text-only app assistance.
6
+
7
+ The application downloads 3,097,467,800 bytes. `manifest.json` lists the exact runtime files, sizes and SHA-256 digests. The supported application context is 4,096 tokens; a single image occupies at most 576 tokens. Input text must be NFC-normalized. Greedy generation with repetition penalty 1.1 was selected over sampling for more stable short responses.
8
+
9
+ See [the export recipe](../../vision-export/v1/README.md), `provenance.json`, the original Apache 2.0 `LICENSE`, and the visual encoder parity report. This is a conversion of the source model without fine-tuning. Small models can make factual and language mistakes; image content and generated editing advice should remain reviewable by the user.
assistant/v1/vision_max/chat_template.jinja ADDED
@@ -0,0 +1,154 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ {%- if tools and tools is iterable and tools is not mapping %}
46
+ {{- '<|im_start|>system\n' }}
47
+ {{- "# Tools\n\nYou have access to the following functions:\n\n<tools>" }}
48
+ {%- for tool in tools %}
49
+ {{- "\n" }}
50
+ {{- tool | tojson }}
51
+ {%- endfor %}
52
+ {{- "\n</tools>" }}
53
+ {{- '\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>' }}
54
+ {%- if messages[0].role == 'system' %}
55
+ {%- set content = render_content(messages[0].content, false, true)|trim %}
56
+ {%- if content %}
57
+ {{- '\n\n' + content }}
58
+ {%- endif %}
59
+ {%- endif %}
60
+ {{- '<|im_end|>\n' }}
61
+ {%- else %}
62
+ {%- if messages[0].role == 'system' %}
63
+ {%- set content = render_content(messages[0].content, false, true)|trim %}
64
+ {{- '<|im_start|>system\n' + content + '<|im_end|>\n' }}
65
+ {%- endif %}
66
+ {%- endif %}
67
+ {%- set ns = namespace(multi_step_tool=true, last_query_index=messages|length - 1) %}
68
+ {%- for message in messages[::-1] %}
69
+ {%- set index = (messages|length - 1) - loop.index0 %}
70
+ {%- if ns.multi_step_tool and message.role == "user" %}
71
+ {%- set content = render_content(message.content, false)|trim %}
72
+ {%- if not(content.startswith('<tool_response>') and content.endswith('</tool_response>')) %}
73
+ {%- set ns.multi_step_tool = false %}
74
+ {%- set ns.last_query_index = index %}
75
+ {%- endif %}
76
+ {%- endif %}
77
+ {%- endfor %}
78
+ {%- if ns.multi_step_tool %}
79
+ {{- raise_exception('No user query found in messages.') }}
80
+ {%- endif %}
81
+ {%- for message in messages %}
82
+ {%- set content = render_content(message.content, true)|trim %}
83
+ {%- if message.role == "system" %}
84
+ {%- if not loop.first %}
85
+ {{- raise_exception('System message must be at the beginning.') }}
86
+ {%- endif %}
87
+ {%- elif message.role == "user" %}
88
+ {{- '<|im_start|>' + message.role + '\n' + content + '<|im_end|>' + '\n' }}
89
+ {%- elif message.role == "assistant" %}
90
+ {%- set reasoning_content = '' %}
91
+ {%- if message.reasoning_content is string %}
92
+ {%- set reasoning_content = message.reasoning_content %}
93
+ {%- else %}
94
+ {%- if '</think>' in content %}
95
+ {%- set reasoning_content = content.split('</think>')[0].rstrip('\n').split('<think>')[-1].lstrip('\n') %}
96
+ {%- set content = content.split('</think>')[-1].lstrip('\n') %}
97
+ {%- endif %}
98
+ {%- endif %}
99
+ {%- set reasoning_content = reasoning_content|trim %}
100
+ {%- if loop.index0 > ns.last_query_index %}
101
+ {{- '<|im_start|>' + message.role + '\n<think>\n' + reasoning_content + '\n</think>\n\n' + content }}
102
+ {%- else %}
103
+ {{- '<|im_start|>' + message.role + '\n' + content }}
104
+ {%- endif %}
105
+ {%- if message.tool_calls and message.tool_calls is iterable and message.tool_calls is not mapping %}
106
+ {%- for tool_call in message.tool_calls %}
107
+ {%- if tool_call.function is defined %}
108
+ {%- set tool_call = tool_call.function %}
109
+ {%- endif %}
110
+ {%- if loop.first %}
111
+ {%- if content|trim %}
112
+ {{- '\n\n<tool_call>\n<function=' + tool_call.name + '>\n' }}
113
+ {%- else %}
114
+ {{- '<tool_call>\n<function=' + tool_call.name + '>\n' }}
115
+ {%- endif %}
116
+ {%- else %}
117
+ {{- '\n<tool_call>\n<function=' + tool_call.name + '>\n' }}
118
+ {%- endif %}
119
+ {%- if tool_call.arguments is defined %}
120
+ {%- for args_name, args_value in tool_call.arguments|items %}
121
+ {{- '<parameter=' + args_name + '>\n' }}
122
+ {%- set args_value = args_value | tojson | safe if args_value is mapping or (args_value is sequence and args_value is not string) else args_value | string %}
123
+ {{- args_value }}
124
+ {{- '\n</parameter>\n' }}
125
+ {%- endfor %}
126
+ {%- endif %}
127
+ {{- '</function>\n</tool_call>' }}
128
+ {%- endfor %}
129
+ {%- endif %}
130
+ {{- '<|im_end|>\n' }}
131
+ {%- elif message.role == "tool" %}
132
+ {%- if loop.previtem and loop.previtem.role != "tool" %}
133
+ {{- '<|im_start|>user' }}
134
+ {%- endif %}
135
+ {{- '\n<tool_response>\n' }}
136
+ {{- content }}
137
+ {{- '\n</tool_response>' }}
138
+ {%- if not loop.last and loop.nextitem.role != "tool" %}
139
+ {{- '<|im_end|>\n' }}
140
+ {%- elif loop.last %}
141
+ {{- '<|im_end|>\n' }}
142
+ {%- endif %}
143
+ {%- else %}
144
+ {{- raise_exception('Unexpected message role.') }}
145
+ {%- endif %}
146
+ {%- endfor %}
147
+ {%- if add_generation_prompt %}
148
+ {{- '<|im_start|>assistant\n' }}
149
+ {%- if enable_thinking is defined and enable_thinking is true %}
150
+ {{- '<think>\n' }}
151
+ {%- else %}
152
+ {{- '<think>\n\n</think>\n\n' }}
153
+ {%- endif %}
154
+ {%- endif %}
assistant/v1/vision_max/config.json ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "Qwen3_5ForConditionalGeneration"
4
+ ],
5
+ "image_token_id": 248056,
6
+ "model_type": "qwen3_5",
7
+ "text_config": {
8
+ "attention_bias": false,
9
+ "attention_dropout": 0.0,
10
+ "attn_output_gate": true,
11
+ "dtype": "bfloat16",
12
+ "eos_token_id": 248044,
13
+ "full_attention_interval": 4,
14
+ "head_dim": 256,
15
+ "hidden_act": "silu",
16
+ "hidden_size": 2048,
17
+ "initializer_range": 0.02,
18
+ "intermediate_size": 6144,
19
+ "layer_types": [
20
+ "linear_attention",
21
+ "linear_attention",
22
+ "linear_attention",
23
+ "full_attention",
24
+ "linear_attention",
25
+ "linear_attention",
26
+ "linear_attention",
27
+ "full_attention",
28
+ "linear_attention",
29
+ "linear_attention",
30
+ "linear_attention",
31
+ "full_attention",
32
+ "linear_attention",
33
+ "linear_attention",
34
+ "linear_attention",
35
+ "full_attention",
36
+ "linear_attention",
37
+ "linear_attention",
38
+ "linear_attention",
39
+ "full_attention",
40
+ "linear_attention",
41
+ "linear_attention",
42
+ "linear_attention",
43
+ "full_attention"
44
+ ],
45
+ "linear_conv_kernel_dim": 4,
46
+ "linear_key_head_dim": 128,
47
+ "linear_num_key_heads": 16,
48
+ "linear_num_value_heads": 16,
49
+ "linear_value_head_dim": 128,
50
+ "max_position_embeddings": 262144,
51
+ "mlp_only_layers": [],
52
+ "model_type": "qwen3_5_text",
53
+ "mtp_num_hidden_layers": 1,
54
+ "mtp_use_dedicated_embeddings": false,
55
+ "num_attention_heads": 8,
56
+ "num_hidden_layers": 24,
57
+ "num_key_value_heads": 2,
58
+ "rms_norm_eps": 1e-06,
59
+ "tie_word_embeddings": true,
60
+ "use_cache": true,
61
+ "vocab_size": 248320,
62
+ "mamba_ssm_dtype": "float32",
63
+ "rope_parameters": {
64
+ "mrope_interleaved": true,
65
+ "mrope_section": [
66
+ 11,
67
+ 11,
68
+ 10
69
+ ],
70
+ "rope_type": "default",
71
+ "rope_theta": 10000000,
72
+ "partial_rotary_factor": 0.25
73
+ }
74
+ },
75
+ "tie_word_embeddings": true,
76
+ "transformers_version": "4.57.0.dev0",
77
+ "video_token_id": 248057,
78
+ "vision_config": {
79
+ "deepstack_visual_indexes": [],
80
+ "depth": 24,
81
+ "hidden_act": "gelu_pytorch_tanh",
82
+ "hidden_size": 1024,
83
+ "in_channels": 3,
84
+ "initializer_range": 0.02,
85
+ "intermediate_size": 4096,
86
+ "model_type": "qwen3_5",
87
+ "num_heads": 16,
88
+ "num_position_embeddings": 2304,
89
+ "out_hidden_size": 2048,
90
+ "patch_size": 16,
91
+ "spatial_merge_size": 2,
92
+ "temporal_patch_size": 2
93
+ },
94
+ "vision_end_token_id": 248054,
95
+ "vision_start_token_id": 248053
96
+ }
assistant/v1/vision_max/embedding.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0158757c64317e9915e31bcab906f6a44ca47831f3c5e225c2a3b460285c9526
3
+ size 2745
assistant/v1/vision_max/embedding.onnx.data ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:58a35460276a890fec4b4a3dd8b61b8d1e5b50d85afa1ad6881012bed34635ce
3
+ size 572129280
assistant/v1/vision_max/genai_config.json ADDED
@@ -0,0 +1,105 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "model": {
3
+ "bos_token_id": 248044,
4
+ "context_length": 4096,
5
+ "decoder": {
6
+ "session_options": {
7
+ "log_id": "onnxruntime-genai",
8
+ "provider_options": [],
9
+ "intra_op_num_threads": 2,
10
+ "inter_op_num_threads": 1,
11
+ "mlas.disable_kleidiai": "1"
12
+ },
13
+ "filename": "text.onnx",
14
+ "head_size": 256,
15
+ "hidden_size": 2048,
16
+ "inputs": {
17
+ "inputs_embeds": "inputs_embeds",
18
+ "attention_mask": "attention_mask",
19
+ "position_ids": "position_ids",
20
+ "past_key_names": "past_key_values.%d.key",
21
+ "past_value_names": "past_key_values.%d.value",
22
+ "past_conv_names": "past.%d.conv",
23
+ "past_recurrent_names": "past.%d.recurrent"
24
+ },
25
+ "outputs": {
26
+ "logits": "logits",
27
+ "present_key_names": "present.%d.key",
28
+ "present_value_names": "present.%d.value",
29
+ "present_conv_names": "present.%d.conv",
30
+ "present_recurrent_names": "present.%d.recurrent"
31
+ },
32
+ "num_attention_heads": 8,
33
+ "num_hidden_layers": 24,
34
+ "num_key_value_heads": 2
35
+ },
36
+ "eos_token_id": [
37
+ 248046,
38
+ 248044
39
+ ],
40
+ "pad_token_id": 248044,
41
+ "type": "qwen3_5",
42
+ "vocab_size": 248320,
43
+ "bot_token_id": 248058,
44
+ "eot_token_id": 248059,
45
+ "bor_token_id": 248068,
46
+ "eor_token_id": 248069,
47
+ "embedding": {
48
+ "filename": "embedding.onnx",
49
+ "inputs": {
50
+ "input_ids": "input_ids",
51
+ "image_features": "image_features"
52
+ },
53
+ "outputs": {
54
+ "inputs_embeds": "inputs_embeds"
55
+ },
56
+ "session_options": {
57
+ "log_id": "onnxruntime-genai",
58
+ "provider_options": [],
59
+ "intra_op_num_threads": 2,
60
+ "inter_op_num_threads": 1,
61
+ "mlas.disable_kleidiai": "1"
62
+ }
63
+ },
64
+ "vision": {
65
+ "filename": "vision.onnx",
66
+ "config_filename": "processor_config.json",
67
+ "spatial_merge_size": 2,
68
+ "patch_size": 16,
69
+ "tokens_per_second": 2.0,
70
+ "inputs": {
71
+ "pixel_values": "pixel_values",
72
+ "image_grid_thw": "image_grid_thw"
73
+ },
74
+ "outputs": {
75
+ "image_features": "image_features"
76
+ },
77
+ "session_options": {
78
+ "log_id": "onnxruntime-genai",
79
+ "provider_options": [],
80
+ "intra_op_num_threads": 2,
81
+ "inter_op_num_threads": 1,
82
+ "mlas.disable_kleidiai": "1"
83
+ }
84
+ },
85
+ "image_token_id": 248056,
86
+ "video_token_id": 248057,
87
+ "vision_start_token_id": 248053
88
+ },
89
+ "search": {
90
+ "diversity_penalty": 0.0,
91
+ "do_sample": false,
92
+ "early_stopping": true,
93
+ "length_penalty": 1.0,
94
+ "max_length": 4096,
95
+ "min_length": 0,
96
+ "no_repeat_ngram_size": 0,
97
+ "num_beams": 1,
98
+ "num_return_sequences": 1,
99
+ "past_present_share_buffer": false,
100
+ "repetition_penalty": 1.1,
101
+ "temperature": 1.0,
102
+ "top_k": 1,
103
+ "top_p": 1.0
104
+ }
105
+ }
assistant/v1/vision_max/manifest.json ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "variant": "vision_max",
3
+ "runtime": "onnxruntime-genai 0.17.0",
4
+ "files": [
5
+ {
6
+ "name": "genai_config.json",
7
+ "size": 2866,
8
+ "sha256": "ffa0090f4f9e4c025aafd4b9f31a13e972a8abeef451c9c95e7b5204092aced4"
9
+ },
10
+ {
11
+ "name": "processor_config.json",
12
+ "size": 1528,
13
+ "sha256": "ceb4f9c08b4fb66a7dbba921d2da1074f57ddf58f12ccaa2052b0f0cf2f27caa"
14
+ },
15
+ {
16
+ "name": "tokenizer.json",
17
+ "size": 19989339,
18
+ "sha256": "a5cd9732badce41de57e6efce8302930ded1c1188c5f81feb2bd6c24c4a1941f"
19
+ },
20
+ {
21
+ "name": "tokenizer_config.json",
22
+ "size": 1462,
23
+ "sha256": "6bcfdefdea3da31bacc5741005cd5523a6a5bffcb5af4596f6b4641643450ee1"
24
+ },
25
+ {
26
+ "name": "embedding.onnx",
27
+ "size": 2745,
28
+ "sha256": "0158757c64317e9915e31bcab906f6a44ca47831f3c5e225c2a3b460285c9526"
29
+ },
30
+ {
31
+ "name": "embedding.onnx.data",
32
+ "size": 572129280,
33
+ "sha256": "58a35460276a890fec4b4a3dd8b61b8d1e5b50d85afa1ad6881012bed34635ce"
34
+ },
35
+ {
36
+ "name": "text.onnx",
37
+ "size": 364527,
38
+ "sha256": "21a03b0df4859c8b178b6effd1294f13b99776f6d69224de66a39ea189fe48f1"
39
+ },
40
+ {
41
+ "name": "text.onnx.data",
42
+ "size": 2123513088,
43
+ "sha256": "f306874b0c48b773364d889453cb6051fe6dfe013c5a66c3d100ea337f39224e"
44
+ },
45
+ {
46
+ "name": "vision.onnx",
47
+ "size": 3123637,
48
+ "sha256": "3b89180d42d93dd410f56b63f977635ca7e1b7448367b22b9e3cada99d5b29ec"
49
+ },
50
+ {
51
+ "name": "vision.onnx.data",
52
+ "size": 378339328,
53
+ "sha256": "45740b760bc963207548c86e282064403acf486cc690cea898961d9cc85e4dba"
54
+ }
55
+ ]
56
+ }
assistant/v1/vision_max/processor_config.json ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "processor": {
3
+ "name": "qwen2_5_image_processor",
4
+ "transforms": [
5
+ {
6
+ "operation": {
7
+ "name": "decode_image",
8
+ "type": "DecodeImage",
9
+ "attrs": {
10
+ "color_space": "RGB"
11
+ }
12
+ }
13
+ },
14
+ {
15
+ "operation": {
16
+ "name": "convert_to_rgb",
17
+ "type": "ConvertRGB"
18
+ }
19
+ },
20
+ {
21
+ "operation": {
22
+ "name": "resize",
23
+ "type": "Resize",
24
+ "attrs": {
25
+ "width": 768,
26
+ "height": 768,
27
+ "smart_resize": 1,
28
+ "min_pixels": 1024,
29
+ "max_pixels": 589824,
30
+ "patch_size": 16,
31
+ "merge_size": 2
32
+ }
33
+ }
34
+ },
35
+ {
36
+ "operation": {
37
+ "name": "rescale",
38
+ "type": "Rescale",
39
+ "attrs": {
40
+ "rescale_factor": 0.00392156862745098
41
+ }
42
+ }
43
+ },
44
+ {
45
+ "operation": {
46
+ "name": "normalize",
47
+ "type": "Normalize",
48
+ "attrs": {
49
+ "mean": [
50
+ 0.5,
51
+ 0.5,
52
+ 0.5
53
+ ],
54
+ "std": [
55
+ 0.5,
56
+ 0.5,
57
+ 0.5
58
+ ],
59
+ "qwen2_5_vl": 1
60
+ }
61
+ }
62
+ },
63
+ {
64
+ "operation": {
65
+ "name": "patch_image",
66
+ "type": "PatchImage",
67
+ "attrs": {
68
+ "patch_size": 16,
69
+ "temporal_patch_size": 2,
70
+ "merge_size": 2
71
+ }
72
+ }
73
+ }
74
+ ]
75
+ }
76
+ }
assistant/v1/vision_max/provenance.json ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "source": {
3
+ "repository": "Qwen/Qwen3.5-2B",
4
+ "revision": "15852e8c16360a2fea060d615a32b45270f8a8fc",
5
+ "license": "Apache-2.0"
6
+ },
7
+ "export": {
8
+ "runtime": "onnxruntime-genai",
9
+ "runtimeVersion": "0.17.0",
10
+ "executionProvider": "CPU",
11
+ "weightPrecision": "INT8",
12
+ "ioPrecision": "FP32",
13
+ "blockSize": 32,
14
+ "contextLength": 4096,
15
+ "maxImages": 1,
16
+ "maxImagePixels": 589824,
17
+ "maxImageTokens": 576,
18
+ "decoderAccuracyLevel": 4,
19
+ "visionAccuracyLevel": 1,
20
+ "embeddingAccuracyLevel": 1
21
+ },
22
+ "tokenizer": {
23
+ "nativeClass": "Qwen2Tokenizer",
24
+ "inputNormalization": "NFC",
25
+ "vocabularyAndMerges": "original",
26
+ "splitPreTokenizer": "original",
27
+ "thinking": false
28
+ },
29
+ "recipe": "../../vision-export/v1/export_models.py",
30
+ "libraries": {
31
+ "onnxruntime-genai": "0.17.0",
32
+ "onnxruntime": "1.31.0",
33
+ "torch": "2.14.1",
34
+ "transformers": "5.20.2",
35
+ "onnx": "1.23.2",
36
+ "onnx-ir": "1.0.0",
37
+ "onnxscript": "0.7.2",
38
+ "huggingface-hub": "2.2.0",
39
+ "Pillow": "13.0.0"
40
+ },
41
+ "sourceFiles": [
42
+ {
43
+ "name": "LICENSE",
44
+ "size": 11544,
45
+ "sha256": "bbedc3fda3305820b977265f01b8619d87570a6739de3a5582c3464840f1e57a"
46
+ },
47
+ {
48
+ "name": "chat_template.jinja",
49
+ "size": 7755,
50
+ "sha256": "273d8e0e683b885071fb17e08d71e5f2a5ddfb5309756181681de4f5a1822d80"
51
+ },
52
+ {
53
+ "name": "config.json",
54
+ "size": 2908,
55
+ "sha256": "ed1c1723241f23f7f4e23430759cbd7dcfb4103cbdfe052bfe7626b57c2615b4"
56
+ },
57
+ {
58
+ "name": "model.safetensors-00001-of-00001.safetensors",
59
+ "size": 4548221488,
60
+ "sha256": "aa33250c4fc64891ddfaba3a314fd9542ea371843c387178b425fbcc5ed680b1"
61
+ },
62
+ {
63
+ "name": "model.safetensors.index.json",
64
+ "size": 64460,
65
+ "sha256": "aca8afed9da75b0f050b408d270766fd77627f1af401e240f61c3b47d0db02f9"
66
+ },
67
+ {
68
+ "name": "preprocessor_config.json",
69
+ "size": 390,
70
+ "sha256": "27225450ac9c6529872ee1924fcb0962ff5634834f817040f444118116f4e516"
71
+ },
72
+ {
73
+ "name": "tokenizer.json",
74
+ "size": 12807982,
75
+ "sha256": "5f9e4d4901a92b997e463c1f46055088b6cca5ca61a6522d1b9f64c4bb81cb42"
76
+ },
77
+ {
78
+ "name": "tokenizer_config.json",
79
+ "size": 16709,
80
+ "sha256": "49e2b6e395f959f077f1e992b338919c0d4a9732fc6e613995e06557f843500c"
81
+ },
82
+ {
83
+ "name": "video_preprocessor_config.json",
84
+ "size": 385,
85
+ "sha256": "7768af27c1fafa9cc9011c1dc20067e03f8915e03b63504550e11d5066986d13"
86
+ },
87
+ {
88
+ "name": "vocab.json",
89
+ "size": 6722759,
90
+ "sha256": "ce99b4cb2983d118806ce0a8b777a35b093e2000a503ebde25853284c9dfa003"
91
+ }
92
+ ]
93
+ }
assistant/v1/vision_max/text.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:21a03b0df4859c8b178b6effd1294f13b99776f6d69224de66a39ea189fe48f1
3
+ size 364527
assistant/v1/vision_max/text.onnx.data ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f306874b0c48b773364d889453cb6051fe6dfe013c5a66c3d100ea337f39224e
3
+ size 2123513088
assistant/v1/vision_max/tokenizer.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a5cd9732badce41de57e6efce8302930ded1c1188c5f81feb2bd6c24c4a1941f
3
+ size 19989339
assistant/v1/vision_max/tokenizer_config.json ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ "extra_special_tokens": [
12
+ "<|im_start|>",
13
+ "<|im_end|>",
14
+ "<|object_ref_start|>",
15
+ "<|object_ref_end|>",
16
+ "<|box_start|>",
17
+ "<|box_end|>",
18
+ "<|quad_start|>",
19
+ "<|quad_end|>",
20
+ "<|vision_start|>",
21
+ "<|vision_end|>",
22
+ "<|vision_pad|>",
23
+ "<|image_pad|>",
24
+ "<|video_pad|>"
25
+ ],
26
+ "image_token": "<|image_pad|>",
27
+ "is_local": true,
28
+ "local_files_only": false,
29
+ "merges_file": null,
30
+ "model_max_length": 262144,
31
+ "model_specific_special_tokens": {
32
+ "audio_bos_token": "<|audio_start|>",
33
+ "audio_eos_token": "<|audio_end|>",
34
+ "audio_token": "<|audio_pad|>",
35
+ "image_token": "<|image_pad|>",
36
+ "video_token": "<|video_pad|>",
37
+ "vision_bos_token": "<|vision_start|>",
38
+ "vision_eos_token": "<|vision_end|>"
39
+ },
40
+ "pad_token": "<|endoftext|>",
41
+ "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+",
42
+ "split_special_tokens": false,
43
+ "tokenizer_class": "Qwen2Tokenizer",
44
+ "unk_token": null,
45
+ "video_token": "<|video_pad|>",
46
+ "vision_bos_token": "<|vision_start|>",
47
+ "vision_eos_token": "<|vision_end|>"
48
+ }
assistant/v1/vision_max/vision-parity.json ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [
2
+ {
3
+ "grid": [
4
+ 16,
5
+ 16
6
+ ],
7
+ "shape": [
8
+ 64,
9
+ 2048
10
+ ],
11
+ "float_max_abs": 0.00014495849609375,
12
+ "quantized_cosine": 0.9970054626464844,
13
+ "quantized_rmse": 0.00972276646643877,
14
+ "float_rms": 0.12565015256404877
15
+ },
16
+ {
17
+ "grid": [
18
+ 12,
19
+ 20
20
+ ],
21
+ "shape": [
22
+ 60,
23
+ 2048
24
+ ],
25
+ "float_max_abs": 7.402896881103516e-05,
26
+ "quantized_cosine": 0.9988663196563721,
27
+ "quantized_rmse": 0.0060358801856637,
28
+ "float_rms": 0.12655341625213623
29
+ },
30
+ {
31
+ "grid": [
32
+ 48,
33
+ 48
34
+ ],
35
+ "shape": [
36
+ 576,
37
+ 2048
38
+ ],
39
+ "float_max_abs": 0.00017273426055908203,
40
+ "quantized_cosine": 0.9974403381347656,
41
+ "quantized_rmse": 0.0077403574250638485,
42
+ "float_rms": 0.10822044312953949
43
+ }
44
+ ]
assistant/v1/vision_max/vision.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3b89180d42d93dd410f56b63f977635ca7e1b7448367b22b9e3cada99d5b29ec
3
+ size 3123637
assistant/v1/vision_max/vision.onnx.data ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:45740b760bc963207548c86e282064403acf486cc690cea898961d9cc85e4dba
3
+ size 378339328
assistant/vision-export/v1/LICENSE-Microsoft ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Microsoft
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
assistant/vision-export/v1/LICENSE-Qwen 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.
assistant/vision-export/v1/README.md ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ImageToolbox Vision export
2
+
3
+ Reproducible CPU ONNX packages for Vision Lite and Vision Max.
4
+
5
+ Install `requirements.txt` in a Python 3.12 environment, then run:
6
+
7
+ ```sh
8
+ python export_models.py vision_lite vision_max
9
+ ```
10
+
11
+ The exporter downloads pinned Qwen source revisions and writes packages to `packages/assistant/v1/`. Export one model at a time on machines with limited memory. Intermediate Olive caches may take several times the final package size.
12
+
13
+ The vision and embedding code adapts [Microsoft Olive's Qwen3.5 recipe](https://github.com/microsoft/olive-recipes/tree/main/Qwen-Qwen3.5-9B/builtin). The retained vision modeling code carries the Qwen Apache 2.0 notice; the Microsoft recipe's MIT license is included separately. The ONNX Runtime GenAI 0.17.0 builder exports the recurrent text decoder. No model training or fine-tuning is performed.
14
+
15
+ The text decoder, input embeddings and vision projections use symmetric INT8 weights, block size 32, and FP32 inputs/outputs. Decoder MatMulNBits accuracy level is 4; vision/embedding quantization accuracy level is 1. The decoder keeps only final-position logits. Rotary lookup caches are trimmed to the 4,096-position application context without changing any retained values.
16
+
17
+ The original tokenizer vocabulary, merges and Split pre-tokenizer are preserved. `tokenizer_class` is aliased to `Qwen2Tokenizer` for the native runtime. Normalize input text to NFC before tokenization, as the original Hugging Face tokenizer does. The package uses the original non-thinking chat template.
18
+
19
+ The processor accepts one image with a maximum of 589,824 pixels, patch size 16, merge size 2, temporal patch size 2, and at most 576 image tokens. The application preserves aspect ratio, applies EXIF orientation and limits the longest side to 768 pixels before calling the processor. Native input token limits include the expanded image tokens.
20
+
21
+ `verify_vision.py` compares the quantized visual encoder against the original Hugging Face implementation at three image grids, including the maximum 768-pixel square. The published parity reports record the results. `check_tokenizer.py` compares English, Russian, mixed Unicode, numeric and image/chat marker token IDs after NFC normalization.
22
+
23
+ For the optional real-photo comparison, download the public [Hugging Face COCO sample](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/coco_sample.png) to `fixtures/cats.png`, then run `compare_precision.py PACKAGE_PATH REPORT_NAME --penalty 1.1 --localized`. This small smoke test is not an accuracy benchmark. Small vision models can misidentify details and make language errors; the application should keep image context and model choice explicit.
assistant/vision-export/v1/check_tokenizer.py ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import unicodedata
3
+ from pathlib import Path
4
+ import onnxruntime_genai as og
5
+ from tokenizers import Tokenizer
6
+
7
+ root=Path(__file__).parent
8
+ sentences=[
9
+ 'Привет, что изображено на фото?',
10
+ 'Как улучшить это фото? Дай 3 конкретных совета по цвету, кадрированию и свету.',
11
+ 'Describe this photograph. Do not invent details.',
12
+ "It's a colourful picture: 12345, 3.14, café, йога, e\u0301, 中文, 한국어 😊",
13
+ ' Первый\n\nВторой\tтретий ',
14
+ '<|im_start|>user\n<|vision_start|><|image_pad|><|vision_end|>Что здесь?<|im_end|>\n<|im_start|>assistant\n<think>\n\n</think>\n\n',
15
+ ]
16
+ reference=Tokenizer.from_file(str(root/'sources/vision_lite/tokenizer.json'))
17
+ native=og.Tokenizer(str(root/'packages/assistant/v1/vision_lite'))
18
+ report=[]
19
+ for text in sentences:
20
+ expected=reference.encode(text,add_special_tokens=False).ids
21
+ actual=native.encode(unicodedata.normalize("NFC",text)).tolist()
22
+ report.append(dict(text=text,expected=expected,actual=actual,exact=expected==actual,roundtrip=native.decode(actual)))
23
+ path=root/'reports';path.mkdir(exist_ok=True)
24
+ (path/'tokenizer-parity.json').write_text(json.dumps(report,ensure_ascii=False,indent=2))
25
+ print([(r['exact'],r['text'][:45]) for r in report])
26
+ assert all(r['exact'] for r in report)
assistant/vision-export/v1/codes/__init__.py ADDED
File without changes
assistant/vision-export/v1/codes/modeling_qwen3_5.py ADDED
@@ -0,0 +1,489 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 The Qwen Team and The HuggingFace Inc. team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from typing import Optional
16
+
17
+ import torch
18
+ import torch.nn as nn
19
+ import torch.nn.functional as F
20
+
21
+ from transformers.activations import ACT2FN
22
+ from transformers.modeling_layers import GradientCheckpointingLayer
23
+ from transformers.modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
24
+ from transformers.utils import auto_docstring, logging
25
+ from transformers.models.qwen3_5.configuration_qwen3_5 import Qwen3_5Config, Qwen3_5VisionConfig
26
+
27
+ logger = logging.get_logger(__name__)
28
+
29
+
30
+ # ═══════════════════════════════════════════════════════════════
31
+ # Vision encoder components (identical architecture to Qwen3-VL)
32
+ # ═══════════════════════════════════════════════════════════════
33
+
34
+
35
+ class VisionMLP(nn.Module):
36
+ def __init__(self, config):
37
+ super().__init__()
38
+ self.hidden_size = config.hidden_size
39
+ self.intermediate_size = config.intermediate_size
40
+ self.linear_fc1 = nn.Linear(self.hidden_size, self.intermediate_size, bias=True)
41
+ self.linear_fc2 = nn.Linear(self.intermediate_size, self.hidden_size, bias=True)
42
+ self.act_fn = ACT2FN[config.hidden_act]
43
+
44
+ def forward(self, hidden_state):
45
+ return self.linear_fc2(self.act_fn(self.linear_fc1(hidden_state)))
46
+
47
+
48
+ class VisionPatchEmbed(nn.Module):
49
+ def __init__(self, config) -> None:
50
+ super().__init__()
51
+ self.patch_size = config.patch_size
52
+ self.temporal_patch_size = config.temporal_patch_size
53
+ self.in_channels = config.in_channels
54
+ self.embed_dim = config.hidden_size
55
+
56
+ kernel_size = [self.temporal_patch_size, self.patch_size, self.patch_size]
57
+ self.proj = nn.Conv3d(self.in_channels, self.embed_dim, kernel_size=kernel_size, stride=kernel_size, bias=True)
58
+
59
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
60
+ target_dtype = self.proj.weight.dtype
61
+ hidden_states = hidden_states.view(
62
+ -1, self.in_channels, self.temporal_patch_size, self.patch_size, self.patch_size
63
+ )
64
+ hidden_states = self.proj(hidden_states.to(dtype=target_dtype)).view(-1, self.embed_dim)
65
+ return hidden_states
66
+
67
+
68
+ class VisionRotaryEmbedding(nn.Module):
69
+ inv_freq: torch.Tensor
70
+
71
+ def __init__(self, dim: int, theta: float = 10000.0) -> None:
72
+ super().__init__()
73
+ inv_freq = 1.0 / (theta ** (torch.arange(0, dim, 2, dtype=torch.float) / dim))
74
+ self.register_buffer("inv_freq", inv_freq, persistent=True)
75
+
76
+ def forward(self, seqlen) -> torch.Tensor:
77
+ seq = torch.arange(seqlen, device=self.inv_freq.device, dtype=self.inv_freq.dtype)
78
+ freqs = torch.outer(seq, self.inv_freq)
79
+ return freqs
80
+
81
+
82
+ class VisionPatchMerger(nn.Module):
83
+ def __init__(self, config: Qwen3_5VisionConfig, use_postshuffle_norm=False) -> None:
84
+ super().__init__()
85
+ self.hidden_size = config.hidden_size * (config.spatial_merge_size**2)
86
+ self.use_postshuffle_norm = use_postshuffle_norm
87
+ self.norm = nn.LayerNorm(self.hidden_size if use_postshuffle_norm else config.hidden_size, eps=1e-6)
88
+ self.linear_fc1 = nn.Linear(self.hidden_size, self.hidden_size)
89
+ self.act_fn = nn.GELU()
90
+ self.linear_fc2 = nn.Linear(self.hidden_size, config.out_hidden_size)
91
+
92
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
93
+ x = self.norm(x.view(-1, self.hidden_size) if self.use_postshuffle_norm else x).view(-1, self.hidden_size)
94
+ x = self.linear_fc2(self.act_fn(self.linear_fc1(x)))
95
+ return x
96
+
97
+
98
+ def rotate_half(x):
99
+ x1 = x[..., : x.shape[-1] // 2]
100
+ x2 = x[..., x.shape[-1] // 2 :]
101
+ return torch.cat((-x2, x1), dim=-1)
102
+
103
+
104
+ def apply_rotary_pos_emb_vision(
105
+ q: torch.Tensor, k: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor
106
+ ) -> tuple[torch.Tensor, torch.Tensor]:
107
+ orig_q_dtype = q.dtype
108
+ orig_k_dtype = k.dtype
109
+ q, k = q.float(), k.float()
110
+ cos, sin = cos.unsqueeze(-2).float(), sin.unsqueeze(-2).float()
111
+ q_embed = (q * cos) + (rotate_half(q) * sin)
112
+ k_embed = (k * cos) + (rotate_half(k) * sin)
113
+ return q_embed.to(orig_q_dtype), k_embed.to(orig_k_dtype)
114
+
115
+
116
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
117
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
118
+ if n_rep == 1:
119
+ return hidden_states
120
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
121
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
122
+
123
+
124
+ def eager_attention_forward(module, query, key, value, attention_mask, scaling, dropout=0.0, **kwargs):
125
+ key_states = repeat_kv(key, module.num_key_value_groups)
126
+ value_states = repeat_kv(value, module.num_key_value_groups)
127
+
128
+ attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
129
+ if attention_mask is not None:
130
+ causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
131
+ attn_weights = attn_weights + causal_mask
132
+
133
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
134
+ attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
135
+ attn_output = torch.matmul(attn_weights, value_states)
136
+ attn_output = attn_output.transpose(1, 2).contiguous()
137
+ return attn_output, attn_weights
138
+
139
+
140
+ class VisionAttention(nn.Module):
141
+ def __init__(self, config: Qwen3_5VisionConfig) -> None:
142
+ super().__init__()
143
+ self.dim = config.hidden_size
144
+ self.num_heads = config.num_heads
145
+ self.head_dim = self.dim // self.num_heads
146
+ self.num_key_value_groups = 1
147
+ self.qkv = nn.Linear(self.dim, self.dim * 3, bias=True)
148
+ self.proj = nn.Linear(self.dim, self.dim)
149
+ self.scaling = self.head_dim**-0.5
150
+ self.config = config
151
+ self.attention_dropout = 0.0
152
+ self.is_causal = False
153
+
154
+ def forward(
155
+ self,
156
+ hidden_states: torch.Tensor,
157
+ cu_seqlens: torch.Tensor,
158
+ rotary_pos_emb: Optional[torch.Tensor] = None,
159
+ position_embeddings: Optional[tuple[torch.Tensor, torch.Tensor]] = None,
160
+ **kwargs,
161
+ ) -> torch.Tensor:
162
+ seq_length = hidden_states.shape[0]
163
+ query_states, key_states, value_states = (
164
+ self.qkv(hidden_states).reshape(seq_length, 3, self.num_heads, -1).permute(1, 0, 2, 3).unbind(0)
165
+ )
166
+ cos, sin = position_embeddings
167
+ query_states, key_states = apply_rotary_pos_emb_vision(query_states, key_states, cos, sin)
168
+
169
+ query_states = query_states.transpose(0, 1).unsqueeze(0)
170
+ key_states = key_states.transpose(0, 1).unsqueeze(0)
171
+ value_states = value_states.transpose(0, 1).unsqueeze(0)
172
+
173
+ attention_interface = eager_attention_forward
174
+ if self.config._attn_implementation != "eager":
175
+ attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
176
+
177
+ if self.config._attn_implementation == "flash_attention_2":
178
+ max_seqlen = (cu_seqlens[1:] - cu_seqlens[:-1]).max()
179
+ attn_output, _ = attention_interface(
180
+ self, query_states, key_states, value_states,
181
+ attention_mask=None, scaling=self.scaling,
182
+ dropout=0.0 if not self.training else self.attention_dropout,
183
+ cu_seq_lens_q=cu_seqlens, cu_seq_lens_k=cu_seqlens,
184
+ max_length_q=max_seqlen, max_length_k=max_seqlen,
185
+ is_causal=False, **kwargs,
186
+ )
187
+ elif getattr(torch.compiler, "is_exporting", lambda: False)():
188
+ # ONNX export: use PackedAttention custom op
189
+ attn_output = torch.onnx.ops.symbolic(
190
+ "custom::PackedAttention",
191
+ (query_states, key_states, value_states, cu_seqlens),
192
+ dict(scale=self.scaling, num_heads=self.num_heads),
193
+ dtype=query_states.dtype,
194
+ shape=(
195
+ query_states.shape[0],
196
+ query_states.shape[2],
197
+ query_states.shape[1],
198
+ query_states.shape[3],
199
+ ),
200
+ version=1,
201
+ )
202
+ attn_output = attn_output.to(self.proj.weight.device)
203
+ else:
204
+ # SDPA fallback: process each chunk separately
205
+ lengths = cu_seqlens[1:] - cu_seqlens[:-1]
206
+ splits = [
207
+ torch.split(tensor, lengths.tolist(), dim=2)
208
+ for tensor in (query_states, key_states, value_states)
209
+ ]
210
+ attn_outputs = []
211
+ for q, k, v in zip(*splits):
212
+ out = torch.nn.functional.scaled_dot_product_attention(
213
+ q, k, v, attn_mask=None,
214
+ dropout_p=0.0 if not self.training else self.attention_dropout,
215
+ scale=self.scaling, is_causal=False,
216
+ )
217
+ attn_outputs.append(out.transpose(1, 2))
218
+ attn_output = torch.cat(attn_outputs, dim=1)
219
+
220
+ attn_output = attn_output.reshape(seq_length, -1).contiguous()
221
+ attn_output = self.proj(attn_output)
222
+ return attn_output
223
+
224
+
225
+ class VisionBlock(GradientCheckpointingLayer):
226
+ def __init__(self, config, attn_implementation: str = "sdpa") -> None:
227
+ super().__init__()
228
+ self.norm1 = nn.LayerNorm(config.hidden_size, eps=1e-6)
229
+ self.norm2 = nn.LayerNorm(config.hidden_size, eps=1e-6)
230
+ self.attn = VisionAttention(config=config)
231
+ self.mlp = VisionMLP(config=config)
232
+
233
+ def forward(self, hidden_states, cu_seqlens, rotary_pos_emb=None, position_embeddings=None, **kwargs):
234
+ hidden_states = hidden_states + self.attn(
235
+ self.norm1(hidden_states), cu_seqlens=cu_seqlens,
236
+ rotary_pos_emb=rotary_pos_emb, position_embeddings=position_embeddings, **kwargs,
237
+ )
238
+ hidden_states = hidden_states + self.mlp(self.norm2(hidden_states))
239
+ return hidden_states
240
+
241
+
242
+ # ═══════════════════════════════════════════════════════════════
243
+ # Vision model (PreTrainedModel wrapper)
244
+ # ═══════════════════════════════════════════════════════════════
245
+
246
+
247
+ @auto_docstring
248
+ class Qwen3_5PreTrainedModel(PreTrainedModel):
249
+ config: Qwen3_5Config
250
+ base_model_prefix = "model"
251
+ supports_gradient_checkpointing = True
252
+ _no_split_modules = ["VisionBlock"]
253
+ _skip_keys_device_placement = "past_key_values"
254
+ _supports_sdpa = True
255
+ _supports_attention_backend = True
256
+
257
+
258
+ class Qwen3_5VisionModel(Qwen3_5PreTrainedModel):
259
+ config: Qwen3_5VisionConfig
260
+ _no_split_modules = ["VisionBlock"]
261
+
262
+ def __init__(self, config, *inputs, **kwargs) -> None:
263
+ super().__init__(config, *inputs, **kwargs)
264
+ self.spatial_merge_size = config.spatial_merge_size
265
+ self.patch_size = config.patch_size
266
+ self.spatial_merge_unit = self.spatial_merge_size * self.spatial_merge_size
267
+
268
+ self.patch_embed = VisionPatchEmbed(config=config)
269
+
270
+ self.pos_embed = nn.Embedding(config.num_position_embeddings, config.hidden_size)
271
+ self.num_grid_per_side = int(config.num_position_embeddings**0.5)
272
+
273
+ head_dim = config.hidden_size // config.num_heads
274
+ self.rotary_pos_emb = VisionRotaryEmbedding(head_dim // 2)
275
+
276
+ self.blocks = nn.ModuleList([VisionBlock(config) for _ in range(config.depth)])
277
+ self.merger = VisionPatchMerger(config=config, use_postshuffle_norm=False)
278
+
279
+ self.deepstack_visual_indexes = config.deepstack_visual_indexes
280
+ self.deepstack_merger_list = nn.ModuleList(
281
+ [VisionPatchMerger(config=config, use_postshuffle_norm=True) for _ in range(len(config.deepstack_visual_indexes))]
282
+ )
283
+
284
+ self.gradient_checkpointing = False
285
+
286
+ def rot_pos_emb(self, grid_thw: torch.Tensor) -> torch.Tensor:
287
+ merge_size = self.spatial_merge_size
288
+ max_hw = grid_thw[:, 1:].max()
289
+ freq_table = self.rotary_pos_emb(max_hw)
290
+ device = freq_table.device
291
+
292
+ all_embeddings = []
293
+ for num_frames, height, width in grid_thw:
294
+ merged_h, merged_w = height // merge_size, width // merge_size
295
+
296
+ torch._check(merged_h.item() >= 1)
297
+ torch._check(merged_w.item() >= 1)
298
+ torch._check(num_frames.item() >= 1)
299
+
300
+ block_rows = torch.arange(merged_h, device=device)
301
+ block_cols = torch.arange(merged_w, device=device)
302
+ intra_row = torch.arange(merge_size, device=device)
303
+ intra_col = torch.arange(merge_size, device=device)
304
+
305
+ row_idx = (
306
+ block_rows[:, None, None, None] * merge_size + intra_row[None, None, :, None]
307
+ ).expand(merged_h, merged_w, merge_size, merge_size).reshape(-1)
308
+ col_idx = (
309
+ block_cols[None, :, None, None] * merge_size + intra_col[None, None, None, :]
310
+ ).expand(merged_h, merged_w, merge_size, merge_size).reshape(-1)
311
+
312
+ coords = torch.stack((row_idx, col_idx), dim=-1)
313
+ coords = coords.repeat(num_frames, 1)
314
+ all_embeddings.append(freq_table[coords].flatten(1))
315
+
316
+ return torch.cat(all_embeddings, dim=0)
317
+
318
+ def fast_pos_embed_interpolate(self, grid_thw):
319
+ """Bilinear interpolation of learnable 2D position embeddings."""
320
+ merge_size = self.config.spatial_merge_size
321
+ dev = self.pos_embed.weight.device
322
+ dtype = self.pos_embed.weight.dtype
323
+ n = self.num_grid_per_side
324
+
325
+ all_pos_embeds = []
326
+ for t, h, w in zip(grid_thw[:, 0], grid_thw[:, 1], grid_thw[:, 2]):
327
+ torch._check(t.item() >= 1)
328
+ torch._check(h.item() >= 2)
329
+ torch._check(w.item() >= 2)
330
+
331
+ h_idxs = torch.arange(h, dtype=torch.float32, device=dev) * ((n - 1) / (h - 1))
332
+ w_idxs = torch.arange(w, dtype=torch.float32, device=dev) * ((n - 1) / (w - 1))
333
+
334
+ h_floor = h_idxs.int()
335
+ w_floor = w_idxs.int()
336
+ h_ceil = (h_floor + 1).clamp(max=n - 1)
337
+ w_ceil = (w_floor + 1).clamp(max=n - 1)
338
+
339
+ dh = (h_idxs - h_floor.float()).to(dtype)
340
+ dw = (w_idxs - w_floor.float()).to(dtype)
341
+
342
+ base_h = h_floor.long() * n
343
+ base_hc = h_ceil.long() * n
344
+
345
+ idx_00 = (base_h[:, None] + w_floor.long()[None]).reshape(-1)
346
+ idx_01 = (base_h[:, None] + w_ceil.long()[None]).reshape(-1)
347
+ idx_10 = (base_hc[:, None] + w_floor.long()[None]).reshape(-1)
348
+ idx_11 = (base_hc[:, None] + w_ceil.long()[None]).reshape(-1)
349
+
350
+ wt_00 = ((1.0 - dh)[:, None] * (1.0 - dw)[None]).reshape(-1)
351
+ wt_01 = ((1.0 - dh)[:, None] * dw[None]).reshape(-1)
352
+ wt_10 = (dh[:, None] * (1.0 - dw)[None]).reshape(-1)
353
+ wt_11 = (dh[:, None] * dw[None]).reshape(-1)
354
+
355
+ pos = (
356
+ self.pos_embed(idx_00.to(dev)) * wt_00[:, None]
357
+ + self.pos_embed(idx_01.to(dev)) * wt_01[:, None]
358
+ + self.pos_embed(idx_10.to(dev)) * wt_10[:, None]
359
+ + self.pos_embed(idx_11.to(dev)) * wt_11[:, None]
360
+ )
361
+
362
+ pos = pos.repeat(t, 1)
363
+ pos = (
364
+ pos.reshape(t, h // merge_size, merge_size, w // merge_size, merge_size, -1)
365
+ .permute(0, 1, 3, 2, 4, 5)
366
+ .flatten(0, 4)
367
+ )
368
+ all_pos_embeds.append(pos)
369
+
370
+ return torch.cat(all_pos_embeds)
371
+
372
+ def forward(self, hidden_states: torch.Tensor, grid_thw: torch.Tensor, **kwargs) -> torch.Tensor:
373
+ hidden_states = self.patch_embed(hidden_states)
374
+ pos_embeds = self.fast_pos_embed_interpolate(grid_thw)
375
+ hidden_states = hidden_states + pos_embeds
376
+
377
+ rotary_pos_emb = self.rot_pos_emb(grid_thw)
378
+ seq_len, _ = hidden_states.size()
379
+ hidden_states = hidden_states.reshape(seq_len, -1)
380
+ rotary_pos_emb = rotary_pos_emb.reshape(seq_len, -1)
381
+ emb = torch.cat((rotary_pos_emb, rotary_pos_emb), dim=-1)
382
+ position_embeddings = (emb.cos(), emb.sin())
383
+
384
+ cu_seqlens = torch.repeat_interleave(grid_thw[:, 1] * grid_thw[:, 2], grid_thw[:, 0]).cumsum(
385
+ dim=0, dtype=grid_thw.dtype if torch.jit.is_tracing() else torch.int32,
386
+ )
387
+ cu_seqlens = F.pad(cu_seqlens, (1, 0), value=0)
388
+
389
+ for blk in self.blocks:
390
+ hidden_states = blk(hidden_states, cu_seqlens=cu_seqlens, position_embeddings=position_embeddings, **kwargs)
391
+
392
+ hidden_states = self.merger(hidden_states)
393
+ return hidden_states
394
+
395
+
396
+ # ═══════════════════════════════════════════════════════════════
397
+ # Top-level Qwen3.5 model (vision + text embedding shell)
398
+ # ═══════════════════════════════════════════════════════════════
399
+
400
+
401
+ class Qwen3_5Model(Qwen3_5PreTrainedModel):
402
+ """Qwen3.5 composite model for vision + embedding ONNX export.
403
+
404
+ The text decoder is exported separately via ModelBuilder.
405
+ This class provides:
406
+ - get_image_features(): vision encoder export
407
+ - get_fused_input_embeddings(): embedding fusion export
408
+ """
409
+ base_model_prefix = ""
410
+ _checkpoint_conversion_mapping = {}
411
+ config: Qwen3_5Config
412
+ _no_split_modules = ["VisionBlock"]
413
+
414
+ def __init__(self, config):
415
+ super().__init__(config)
416
+ self.visual = Qwen3_5VisionModel._from_config(config.vision_config)
417
+ # Minimal text model: only need embed_tokens for embedding export
418
+ text_config = config.text_config
419
+ self.embed_tokens = nn.Embedding(text_config.vocab_size, text_config.hidden_size)
420
+ self.post_init()
421
+
422
+ def get_input_embeddings(self):
423
+ return self.embed_tokens
424
+
425
+ def get_image_features(self, pixel_values: torch.FloatTensor, image_grid_thw: Optional[torch.LongTensor] = None):
426
+ """Vision encoder: pixel_values + grid_thw -> image features.
427
+
428
+ Returns list of per-image feature tensors (split by grid sizes).
429
+ """
430
+ pixel_values = pixel_values.type(self.visual.dtype)
431
+ image_embeds = self.visual(pixel_values, grid_thw=image_grid_thw)
432
+ split_sizes = (image_grid_thw.prod(-1) // self.visual.spatial_merge_size**2).tolist()
433
+ image_embeds = torch.split(image_embeds, split_sizes)
434
+ return image_embeds
435
+
436
+ def get_fused_input_embeddings(self, input_ids, image_features=None):
437
+ """Embedding fusion: input_ids + image_features -> inputs_embeds.
438
+
439
+ Scatters image features at image_token_id positions in the text embedding.
440
+ """
441
+ def true_fn_for_input_ids(input_ids):
442
+ special_image_mask = input_ids == self.config.image_token_id
443
+ llm_input_ids = input_ids.clone()
444
+ llm_input_ids[special_image_mask] = 0
445
+ return llm_input_ids
446
+
447
+ def false_fn_for_input_ids(input_ids):
448
+ return input_ids
449
+
450
+ llm_input_ids = torch.cond(
451
+ input_ids is not None and self.config.image_token_id >= self.config.text_config.vocab_size,
452
+ true_fn_for_input_ids,
453
+ false_fn_for_input_ids,
454
+ (input_ids,),
455
+ )
456
+
457
+ inputs_embeds = self.embed_tokens(llm_input_ids)
458
+
459
+ def image_features_is_none(inputs_embeds, image_features=None):
460
+ return inputs_embeds
461
+
462
+ def image_features_is_not_none(inputs_embeds, image_features=None):
463
+ special_image_mask = (llm_input_ids == self.config.image_token_id).unsqueeze(-1)
464
+ special_image_mask = special_image_mask.expand_as(inputs_embeds).to(inputs_embeds.device)
465
+ image_features = image_features.to(inputs_embeds.device, inputs_embeds.dtype)
466
+ inputs_embeds = inputs_embeds.masked_scatter(special_image_mask, image_features)
467
+ return inputs_embeds
468
+
469
+ inputs_embeds = torch.cond(
470
+ image_features is None,
471
+ image_features_is_none,
472
+ image_features_is_not_none,
473
+ (inputs_embeds, image_features),
474
+ )
475
+
476
+ return inputs_embeds
477
+
478
+ def forward(self, *args, **kwargs):
479
+ raise NotImplementedError(
480
+ "Qwen3_5Model.forward() should not be called directly. "
481
+ "Use get_image_features() or get_fused_input_embeddings() via method swap."
482
+ )
483
+
484
+
485
+ __all__ = [
486
+ "Qwen3_5Model",
487
+ "Qwen3_5PreTrainedModel",
488
+ "Qwen3_5VisionModel",
489
+ ]
assistant/vision-export/v1/compare_precision.py ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import gc
3
+ import json
4
+ import time
5
+ import unicodedata
6
+ from pathlib import Path
7
+ import onnxruntime_genai as og
8
+
9
+ root=Path(__file__).parent
10
+ parser=argparse.ArgumentParser()
11
+ parser.add_argument('package')
12
+ parser.add_argument('report')
13
+ parser.add_argument('--penalty',type=float,default=1.0)
14
+ parser.add_argument('--localized',action='store_true')
15
+ args=parser.parse_args()
16
+ model=og.Model(args.package)
17
+ tokenizer=og.Tokenizer(model)
18
+ processor=model.create_multimodal_processor()
19
+ questions=[
20
+ 'Describe this photo in one short sentence. How many animals are visible?',
21
+ 'Что видно на фотографии? Опиши по-русски в двух коротких предложениях.',
22
+ 'Придумай одну короткую подпись к этой фотографии по-русски.',
23
+ 'Предложи три конкретных улучшения этой фотографии: кадрирование, свет и цвет. Отвечай по-русски.',
24
+ ]
25
+ report=[]
26
+ for q in questions:
27
+ prompt='<|im_start|>system\nYou are an image assistant. Use the actual image to answer. Be specific, concise and do not invent details. Answer in the language requested by the user.<|im_end|>\n<|im_start|>user\n<|vision_start|><|image_pad|><|vision_end|>'+q+'<|im_end|>\n<|im_start|>assistant\n<think>\n\n</think>\n\n'
28
+ if args.localized and any('А' <= c <= 'я' for c in q):
29
+ prompt=prompt.replace('You are an image assistant. Use the actual image to answer. Be specific, concise and do not invent details. Answer in the language requested by the user.', 'Ты помогаешь работать с изображениями. Отвечай только по-русски, кратко и конкретно. Используй только видимые детали. Не выдумывай объекты и не повторяй советы. Если просят три улучшения, дай ровно три пункта, по одному предложению на пункт.')
30
+ prompt=unicodedata.normalize('NFC',prompt)
31
+ images=og.Images.open(str(root/'fixtures/cats.png'))
32
+ start=time.monotonic()
33
+ inputs=processor(prompt,images=images)
34
+ input_count=inputs['input_ids'].shape()[-1]
35
+ params=og.GeneratorParams(model)
36
+ params.set_search_options(max_length=input_count+192,do_sample=False,repetition_penalty=args.penalty)
37
+ generator=og.Generator(model,params)
38
+ generator.set_inputs(inputs)
39
+ stream=tokenizer.create_stream()
40
+ answer='';ttft=None;n=0
41
+ while not generator.is_done():
42
+ generator.generate_next_token()
43
+ if ttft is None:ttft=time.monotonic()-start
44
+ token=generator.get_next_tokens()[0];n+=1
45
+ answer+=stream.decode(token)
46
+ elapsed=time.monotonic()-start
47
+ result=dict(prompt=q,answer=answer,inputTokens=input_count,outputTokens=n,seconds=elapsed,ttft=ttft,tokensPerSecond=(n-1)/max(.001,elapsed-ttft))
48
+ report.append(result)
49
+ print(json.dumps(result,ensure_ascii=False),flush=True)
50
+ del generator,params,inputs,images,stream
51
+ gc.collect()
52
+ (root/'reports'/args.report).write_text(json.dumps(report,indent=2,ensure_ascii=False))
assistant/vision-export/v1/configure_package.py ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import json
3
+ import shutil
4
+ from pathlib import Path
5
+
6
+ root=Path(__file__).resolve().parent
7
+ parser=argparse.ArgumentParser()
8
+ parser.add_argument('variant',choices=['vision_lite','vision_max'])
9
+ args=parser.parse_args()
10
+ source=root/'sources'/args.variant
11
+ output=root/'packages/assistant/v1'/args.variant
12
+ config_path=output/'genai_config.json'
13
+ config=json.loads(config_path.read_text())
14
+ source_config=json.loads((source/'config.json').read_text())
15
+ session={'log_id':'onnxruntime-genai','provider_options':[], 'intra_op_num_threads':2,'inter_op_num_threads':1,'mlas.disable_kleidiai':'1'}
16
+ config['model']['decoder']['session_options']=session
17
+ config['model']['context_length']=4096
18
+ config['model']['bos_token_id']=248044
19
+ config['model']['pad_token_id']=248044
20
+ config['model']['eos_token_id']=[248046,248044]
21
+ config['model']['embedding']={
22
+ 'filename':'embedding.onnx',
23
+ 'inputs':{'input_ids':'input_ids','image_features':'image_features'},
24
+ 'outputs':{'inputs_embeds':'inputs_embeds'},
25
+ 'session_options':session,
26
+ }
27
+ config['model']['vision']={
28
+ 'filename':'vision.onnx','config_filename':'processor_config.json',
29
+ 'spatial_merge_size':2,'patch_size':16,'tokens_per_second':2.0,
30
+ 'inputs':{'pixel_values':'pixel_values','image_grid_thw':'image_grid_thw'},
31
+ 'outputs':{'image_features':'image_features'},
32
+ 'session_options':session,
33
+ }
34
+ for key in ['image_token_id','video_token_id','vision_start_token_id']:
35
+ config['model'][key]=source_config[key]
36
+ config['search'].update(max_length=4096,do_sample=False,top_k=1,top_p=1.0,past_present_share_buffer=False,repetition_penalty=1.1)
37
+ config_path.write_text(json.dumps(config,indent=2))
38
+ processor={'processor':{'name':'qwen2_5_image_processor','transforms':[
39
+ {'operation':{'name':'decode_image','type':'DecodeImage','attrs':{'color_space':'RGB'}}},
40
+ {'operation':{'name':'convert_to_rgb','type':'ConvertRGB'}},
41
+ {'operation':{'name':'resize','type':'Resize','attrs':{'width':768,'height':768,'smart_resize':1,'min_pixels':1024,'max_pixels':589824,'patch_size':16,'merge_size':2}}},
42
+ {'operation':{'name':'rescale','type':'Rescale','attrs':{'rescale_factor':1/255}}},
43
+ {'operation':{'name':'normalize','type':'Normalize','attrs':{'mean':[0.5]*3,'std':[0.5]*3,'qwen2_5_vl':1}}},
44
+ {'operation':{'name':'patch_image','type':'PatchImage','attrs':{'patch_size':16,'temporal_patch_size':2,'merge_size':2}}},
45
+ ]}}
46
+ (output/'processor_config.json').write_text(json.dumps(processor,indent=2))
47
+ config_path=output/'tokenizer_config.json'
48
+ config=json.loads(config_path.read_text())
49
+ config['tokenizer_class']='Qwen2Tokenizer'
50
+ config_path.write_text(json.dumps(config,indent=2,ensure_ascii=False))
51
+ for name in ['LICENSE','config.json']:
52
+ shutil.copyfile(source/name,output/name)
53
+ for name in ['model_config.json']:
54
+ (output/name).unlink(missing_ok=True)
assistant/vision-export/v1/export_models.py ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Reproduce ImageToolbox Vision packages with the pinned source weights."""
2
+ import argparse
3
+ import json
4
+ import subprocess
5
+ import sys
6
+ from pathlib import Path
7
+ from huggingface_hub import snapshot_download
8
+
9
+ SOURCES = {
10
+ 'vision_lite': ('Qwen/Qwen3.5-0.8B', '2fc06364715b967f1860aea9cf38778875588b17'),
11
+ 'vision_max': ('Qwen/Qwen3.5-2B', '15852e8c16360a2fea060d615a32b45270f8a8fc'),
12
+ }
13
+ root=Path(__file__).resolve().parent
14
+ parser=argparse.ArgumentParser()
15
+ parser.add_argument('variants',nargs='*',choices=list(SOURCES),default=list(SOURCES))
16
+ args=parser.parse_args()
17
+ for variant in args.variants:
18
+ repository,revision=SOURCES[variant]
19
+ snapshot_download(repository,revision=revision,local_dir=root/'sources'/variant,
20
+ allow_patterns=['*.json','*.safetensors','*.jinja','LICENSE'])
21
+ subprocess.run([sys.executable,str(root/'prepare_export.py')],check=True)
22
+ for variant in args.variants:
23
+ subprocess.run([
24
+ sys.executable,'-m','onnxruntime_genai.models.builder',
25
+ '-i',str(root/'sources'/variant),'-o',str(root/'packages/assistant/v1'/variant),
26
+ '-p','int8','-e','cpu','-c',str(root/'export-cache'/variant),
27
+ '--extra_options','filename=text.onnx','exclude_embeds=true','exclude_mtp=true',
28
+ 'shared_embeddings=false','prune_lm_head=true','block_size=32','accuracy_level=4',
29
+ ],check=True)
30
+ for component in ('embedding','vision'):
31
+ subprocess.run([sys.executable,'-c',
32
+ 'from olive import run; run('+repr(str(root/'recipes'/variant/(component+'.json')))+')'],
33
+ check=True,cwd=root)
34
+ subprocess.run([sys.executable,str(root/'configure_package.py'),variant],check=True)
35
+ subprocess.run([sys.executable,str(root/'trim_rope.py'),variant],check=True)
assistant/vision-export/v1/prepare_export.py ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ from pathlib import Path
3
+
4
+ root = Path(__file__).resolve().parent
5
+ for variant in ('vision_lite', 'vision_max'):
6
+ source = root / 'sources' / variant
7
+ output = root / 'packages' / 'assistant' / 'v1' / variant
8
+ folder = root / 'recipes' / variant
9
+ folder.mkdir(parents=True, exist_ok=True)
10
+ output.mkdir(parents=True, exist_ok=True)
11
+ model = {
12
+ 'type': 'PyTorchModel',
13
+ 'model_path': str(source),
14
+ 'model_script': str(root / 'user_script.py'),
15
+ }
16
+ common = {
17
+ 'cast': {
18
+ 'type': 'OnnxPeepholeOptimizer', 'onnxscript_optimize': False,
19
+ 'onnxoptimizer_optimize': False, 'fuse_reshape_operations': False,
20
+ 'fix_com_microsoft_opset': True, 'cast_chain_elimination': True,
21
+ },
22
+ 'gemm': {'type': 'GraphSurgeries', 'surgeries': [{'surgeon': 'GemmToMatMulAdd'}]},
23
+ }
24
+ vision = {
25
+ 'input_model': dict(model, model_loader='get_vision_model', io_config='get_vision_io_config', dummy_inputs_func='get_vision_dummy_inputs'),
26
+ 'passes': {
27
+ 'convert': {'type': 'OnnxConversion', 'use_dynamo_exporter': True},
28
+ 'packed': {'type': 'GraphSurgeries', 'surgeries': [{'surgeon': 'PackedAttentionToLoopMHA'}, {'surgeon': 'RenameOutputDims', 'output_idx': 0, 'dim_idx': 0, 'dim_name': 'num_logical_patches'}]},
29
+ **common,
30
+ 'quantize': {'type': 'OnnxBlockWiseRtnQuantization', 'bits': 8, 'block_size': 32, 'is_symmetric': True, 'accuracy_level': 1, 'save_as_external_data': True, 'external_data_name': 'vision.onnx.data'},
31
+ },
32
+ 'no_artifacts': True,
33
+ 'cache_dir': str(root / 'olive-cache' / variant / 'vision'),
34
+ 'output_dir': str(output / 'vision.onnx'),
35
+ }
36
+ embedding = {
37
+ 'input_model': dict(model, model_loader='get_embedding_model', io_config='get_embedding_io_config', dummy_inputs_func='get_embedding_dummy_inputs'),
38
+ 'passes': {
39
+ 'convert': {'type': 'OnnxConversion', 'use_dynamo_exporter': False},
40
+ **common,
41
+ 'quantize': {'type': 'OnnxBlockWiseRtnQuantization', 'bits': 8, 'block_size': 32, 'is_symmetric': True, 'accuracy_level': 1, 'axis': 1, 'save_as_external_data': True, 'external_data_name': 'embedding.onnx.data'},
42
+ },
43
+ 'no_artifacts': True,
44
+ 'cache_dir': str(root / 'olive-cache' / variant / 'embedding'),
45
+ 'output_dir': str(output / 'embedding.onnx'),
46
+ }
47
+ for name, data in [('vision', vision), ('embedding', embedding)]:
48
+ (folder / f'{name}.json').write_text(json.dumps(data, indent=2))
assistant/vision-export/v1/requirements.txt ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ onnxruntime-genai==0.17.0
2
+ onnxruntime==1.31.0
3
+ torch==2.14.1
4
+ transformers==5.20.2
5
+ onnx==1.23.2
6
+ onnx-ir==1.0.0
7
+ onnxscript==0.7.2
8
+ huggingface-hub==2.2.0
9
+ Pillow==13.0.0
10
+ olive-ai @ git+https://github.com/microsoft/Olive.git@4acb072117138433d0c89bbae2cd6851b610e265
assistant/vision-export/v1/smoke.py ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import gc
3
+ import json
4
+ import time
5
+ import unicodedata
6
+ from pathlib import Path
7
+ import onnxruntime_genai as og
8
+ from PIL import Image,ImageDraw
9
+
10
+ root=Path(__file__).parent
11
+ parser=argparse.ArgumentParser()
12
+ parser.add_argument('variant',choices=['vision_lite','vision_max'])
13
+ parser.add_argument('--image')
14
+ parser.add_argument('--prompt',default='Describe the main shape and its color. Answer in one short sentence.')
15
+ args=parser.parse_args()
16
+ fixtures=root/'fixtures';fixtures.mkdir(exist_ok=True)
17
+ for name,color,shape in [('red-square','red','rectangle'),('blue-circle','blue','ellipse')]:
18
+ im=Image.new('RGB',(384,384),'white')
19
+ getattr(ImageDraw.Draw(im),shape)((64,64,320,320),fill=color)
20
+ im.save(fixtures/f'{name}.png')
21
+ model=og.Model(str(root/'packages/assistant/v1'/args.variant))
22
+ tokenizer=og.Tokenizer(model)
23
+ processor=model.create_multimodal_processor()
24
+ reports=[]
25
+ for path in ([Path(args.image)] if args.image else sorted(fixtures.glob('*.png'))):
26
+ prompt='<|im_start|>system\nYou help users understand images. Describe only what is visible.<|im_end|>\n<|im_start|>user\n<|vision_start|><|image_pad|><|vision_end|>'+args.prompt+'<|im_end|>\n<|im_start|>assistant\n<think>\n\n</think>\n\n'
27
+ prompt=unicodedata.normalize('NFC',prompt)
28
+ images=og.Images.open(str(path))
29
+ start=time.monotonic()
30
+ inputs=processor(prompt,images=images)
31
+ ids=inputs['input_ids']
32
+ print('INPUT',path.name,ids.shape(),flush=True)
33
+ params=og.GeneratorParams(model)
34
+ params.set_search_options(max_length=int(ids.shape()[-1])+128,do_sample=False)
35
+ generator=og.Generator(model,params)
36
+ generator.set_inputs(inputs)
37
+ stream=tokenizer.create_stream()
38
+ answer=''
39
+ while not generator.is_done():
40
+ generator.generate_next_token()
41
+ token=generator.get_next_tokens()[0]
42
+ chunk=stream.decode(token)
43
+ answer+=chunk
44
+ print(chunk,end='',flush=True)
45
+ print(flush=True)
46
+ reports.append(dict(image=path.name,prompt=args.prompt,text=answer,seconds=time.monotonic()-start,input_tokens=int(ids.shape()[-1])))
47
+ del generator,params,inputs,images,stream
48
+ gc.collect()
49
+ (root/'reports'/f'{args.variant}-smoke.json').write_text(json.dumps(reports,indent=2,ensure_ascii=False))
50
+ print(json.dumps(reports,ensure_ascii=False,indent=2),flush=True)
assistant/vision-export/v1/trim_rope.py ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import os
3
+ from pathlib import Path
4
+ import onnx
5
+
6
+ root=Path(__file__).parent
7
+ parser=argparse.ArgumentParser()
8
+ parser.add_argument('variant',choices=['vision_lite','vision_max'])
9
+ parser.add_argument('--folder')
10
+ args=parser.parse_args()
11
+ folder=Path(args.folder) if args.folder else root/'packages/assistant/v1'/args.variant
12
+ model=onnx.load(folder/'text.onnx',load_external_data=False)
13
+ weights=folder/'text.onnx.data'
14
+ temp=folder/'text.onnx.data.trimmed'
15
+ changed=False
16
+ with weights.open('rb') as source, temp.open('wb') as target:
17
+ for tensor in model.graph.initializer:
18
+ if tensor.data_location != onnx.TensorProto.EXTERNAL:
19
+ continue
20
+ external={e.key:e.value for e in tensor.external_data}
21
+ assert external['location']=='text.onnx.data'
22
+ start=int(external['offset']);length=int(external['length'])
23
+ if tensor.name in ('cos_cache','sin_cache'):
24
+ assert tensor.dims[0] in (4096,262144), tensor.dims
25
+ if tensor.dims[0] != 4096:
26
+ length=4096*tensor.dims[1]*4
27
+ tensor.dims[0]=4096
28
+ changed=True
29
+ source.seek(start)
30
+ offset=target.tell()
31
+ remaining=length
32
+ while remaining:
33
+ chunk=source.read(min(8*1024*1024,remaining))
34
+ assert chunk
35
+ target.write(chunk); remaining-=len(chunk)
36
+ for entry in tensor.external_data:
37
+ if entry.key=='offset':entry.value=str(offset)
38
+ if entry.key=='length':entry.value=str(length)
39
+ if changed:
40
+ os.replace(temp,weights)
41
+ onnx.save(model,folder/'text.onnx')
42
+ print(args.variant,'limited rotary cache to4096',weights.stat().st_size)
43
+ else:
44
+ temp.unlink()
45
+ print(args.variant,'already limited')
assistant/vision-export/v1/user_script.py ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from pathlib import Path
2
+ import torch
3
+ from safetensors import safe_open
4
+ from transformers import Qwen3_5Config
5
+ from codes.modeling_qwen3_5 import Qwen3_5Model, Qwen3_5VisionModel
6
+
7
+
8
+ def _load_base_model(model_path):
9
+ source = Path(model_path)
10
+ config = Qwen3_5Config.from_pretrained(source, local_files_only=True)
11
+ model = Qwen3_5Model(config)
12
+ state = {}
13
+ for file in sorted(source.glob('*.safetensors')):
14
+ with safe_open(file, framework='pt', device='cpu') as weights:
15
+ for key in weights.keys():
16
+ if key.startswith('model.visual.'):
17
+ state[key[len('model.'):]] = weights.get_tensor(key).float()
18
+ elif key == 'model.language_model.embed_tokens.weight':
19
+ state['embed_tokens.weight'] = weights.get_tensor(key).float()
20
+ result = model.load_state_dict(state, strict=False)
21
+ missing = [key for key in result.missing_keys if key != 'visual.rotary_pos_emb.inv_freq']
22
+ if missing or result.unexpected_keys:
23
+ raise RuntimeError(f'Invalid weights: {missing=}, {result.unexpected_keys=}')
24
+ model.eval()
25
+ return model
26
+
27
+
28
+ def get_embedding_model(model_path=None):
29
+ model = _load_base_model(model_path)
30
+ model.forward = model.get_fused_input_embeddings
31
+ return model
32
+
33
+
34
+ def get_embedding_io_config(model_path=None):
35
+ return {
36
+ 'input_names': ['input_ids', 'image_features'],
37
+ 'output_names': ['inputs_embeds'],
38
+ 'dynamic_axes': {
39
+ 'input_ids': {0: 'batch_size', 1: 'sequence_length'},
40
+ 'image_features': {0: 'num_logical_patches'},
41
+ 'inputs_embeds': {0: 'batch_size', 1: 'sequence_length'},
42
+ },
43
+ }
44
+
45
+
46
+ def get_embedding_dummy_inputs(model=None):
47
+ config = Qwen3_5Config.from_pretrained(model.model_path, local_files_only=True)
48
+ input_ids = torch.randint(0, 10000, (1, 20), dtype=torch.int64)
49
+ input_ids[0, 2] = config.vision_start_token_id
50
+ input_ids[0, 3:19] = config.image_token_id
51
+ input_ids[0, 19] = config.vision_end_token_id
52
+ return {'input_ids': input_ids, 'image_features': torch.randn(16, config.text_config.hidden_size)}
53
+
54
+
55
+ class VisionEncoder(torch.nn.Module):
56
+ def __init__(self, config):
57
+ super().__init__()
58
+ self.visual = Qwen3_5VisionModel._from_config(config.vision_config)
59
+
60
+ def forward(self, pixel_values, image_grid_thw):
61
+ return self.visual(pixel_values, grid_thw=image_grid_thw)
62
+
63
+
64
+ def get_vision_model(model_path=None):
65
+ source = Path(model_path)
66
+ config = Qwen3_5Config.from_pretrained(source, local_files_only=True)
67
+ model = VisionEncoder(config)
68
+ state = {}
69
+ for file in sorted(source.glob('*.safetensors')):
70
+ with safe_open(file, framework='pt', device='cpu') as weights:
71
+ for key in weights.keys():
72
+ if key.startswith('model.visual.'):
73
+ state[key[len('model.'):]] = weights.get_tensor(key).float()
74
+ result = model.load_state_dict(state, strict=False)
75
+ missing = [key for key in result.missing_keys if key != 'visual.rotary_pos_emb.inv_freq']
76
+ if missing or result.unexpected_keys:
77
+ raise RuntimeError(f'Invalid vision weights: {missing=}, {result.unexpected_keys=}')
78
+ return model.eval()
79
+
80
+
81
+ def get_vision_io_config(model_path=None):
82
+ return {
83
+ 'input_names': ['pixel_values', 'image_grid_thw'],
84
+ 'output_names': ['image_features'],
85
+ 'dynamic_shapes': {'pixel_values': {0: 'num_patches'}, 'image_grid_thw': None},
86
+ }
87
+
88
+
89
+ def get_vision_dummy_inputs(model=None):
90
+ return {
91
+ 'pixel_values': torch.randn(16 * 16, 1536),
92
+ 'image_grid_thw': torch.tensor([[1, 16, 16]], dtype=torch.int64),
93
+ }
assistant/vision-export/v1/verify_vision.py ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import gc
3
+ import json
4
+ from pathlib import Path
5
+
6
+ import numpy as np
7
+ import onnxruntime as ort
8
+ import torch
9
+ from safetensors import safe_open
10
+ from transformers import Qwen3_5Config
11
+ from transformers.models.qwen3_5.modeling_qwen3_5 import Qwen3_5VisionModel as OriginalVisionModel
12
+ from codes.modeling_qwen3_5 import Qwen3_5VisionModel
13
+
14
+ parser = argparse.ArgumentParser()
15
+ parser.add_argument('variant')
16
+ parser.add_argument('--model')
17
+ parser.add_argument('--threshold', type=float, default=0.97)
18
+ args = parser.parse_args()
19
+ root = Path(__file__).parent
20
+ source = root / 'sources' / args.variant
21
+ config = Qwen3_5Config.from_pretrained(source, local_files_only=True).vision_config
22
+ config._attn_implementation = 'sdpa'
23
+ torch.set_num_threads(4)
24
+ state = {}
25
+ for file in source.glob('*.safetensors'):
26
+ with safe_open(file, framework='pt', device='cpu') as weights:
27
+ for key in weights.keys():
28
+ if key.startswith('model.visual.'):
29
+ state[key[len('model.visual.'):]] = weights.get_tensor(key).float()
30
+ model = Qwen3_5VisionModel(config).eval()
31
+ missing, unexpected = model.load_state_dict(state, strict=False)
32
+ assert missing == ['rotary_pos_emb.inv_freq'], (missing, unexpected)
33
+ assert not unexpected
34
+ original = OriginalVisionModel(config).eval()
35
+ missing, unexpected = original.load_state_dict(state, strict=False)
36
+ assert not missing and not unexpected, (missing, unexpected)
37
+ del state
38
+ options = ort.SessionOptions()
39
+ options.intra_op_num_threads = 4
40
+ options.inter_op_num_threads = 1
41
+ ort.disable_telemetry_events()
42
+ onnx_path = Path(args.model) if args.model else root / 'packages' / 'assistant' / 'v1' / args.variant / 'vision.onnx'
43
+ if onnx_path.is_dir():
44
+ onnx_path = onnx_path / 'model.onnx'
45
+ session = ort.InferenceSession(str(onnx_path), options, providers=['CPUExecutionProvider'])
46
+ report = []
47
+ for h, w in [(16,16), (12,20), (48,48)]:
48
+ torch.manual_seed(2026)
49
+ pixels = torch.randn(h*w, 1536)
50
+ grid = torch.tensor([[1,h,w]], dtype=torch.int64)
51
+ with torch.inference_mode():
52
+ expected = original(pixels, grid_thw=grid).pooler_output.numpy()
53
+ adapted = model(pixels, grid_thw=grid).numpy()
54
+ actual = session.run(None, {'pixel_values':pixels.numpy(), 'image_grid_thw':grid.numpy()})[0]
55
+ assert expected.shape == actual.shape == adapted.shape
56
+ assert np.isfinite(actual).all()
57
+ float_diff = float(np.max(np.abs(expected-adapted)))
58
+ np.testing.assert_allclose(adapted, expected, rtol=1e-4, atol=1e-4)
59
+ flat_expected = expected.reshape(-1)
60
+ flat_actual = actual.reshape(-1)
61
+ cosine = float(np.dot(flat_expected,flat_actual)/(np.linalg.norm(flat_expected)*np.linalg.norm(flat_actual)))
62
+ result = {'grid':[h,w], 'shape':list(actual.shape), 'float_max_abs':float_diff,'quantized_cosine':cosine,'quantized_rmse':float(np.sqrt(np.mean((actual-expected)**2))), 'float_rms':float(np.sqrt(np.mean(expected**2)))}
63
+ report.append(result)
64
+ print(json.dumps(result), flush=True)
65
+ assert cosine > args.threshold, result
66
+ (root / 'logs' / f'{args.variant}-vision-parity.json').write_text(json.dumps(report, indent=2))