Vontra commited on
Commit
c444e5d
·
0 Parent(s):

Clean public model snapshot

Browse files
Files changed (42) hide show
  1. .gitattributes +36 -0
  2. LICENSE +96 -0
  3. OMLX.md +73 -0
  4. README.md +76 -0
  5. chat_template.jinja +235 -0
  6. config.json +70 -0
  7. generation_config.json +9 -0
  8. model-00001-of-00029.safetensors +3 -0
  9. model-00002-of-00029.safetensors +3 -0
  10. model-00003-of-00029.safetensors +3 -0
  11. model-00004-of-00029.safetensors +3 -0
  12. model-00005-of-00029.safetensors +3 -0
  13. model-00006-of-00029.safetensors +3 -0
  14. model-00007-of-00029.safetensors +3 -0
  15. model-00008-of-00029.safetensors +3 -0
  16. model-00009-of-00029.safetensors +3 -0
  17. model-00010-of-00029.safetensors +3 -0
  18. model-00011-of-00029.safetensors +3 -0
  19. model-00012-of-00029.safetensors +3 -0
  20. model-00013-of-00029.safetensors +3 -0
  21. model-00014-of-00029.safetensors +3 -0
  22. model-00015-of-00029.safetensors +3 -0
  23. model-00016-of-00029.safetensors +3 -0
  24. model-00017-of-00029.safetensors +3 -0
  25. model-00018-of-00029.safetensors +3 -0
  26. model-00019-of-00029.safetensors +3 -0
  27. model-00020-of-00029.safetensors +3 -0
  28. model-00021-of-00029.safetensors +3 -0
  29. model-00022-of-00029.safetensors +3 -0
  30. model-00023-of-00029.safetensors +3 -0
  31. model-00024-of-00029.safetensors +3 -0
  32. model-00025-of-00029.safetensors +3 -0
  33. model-00026-of-00029.safetensors +3 -0
  34. model-00027-of-00029.safetensors +3 -0
  35. model-00028-of-00029.safetensors +3 -0
  36. model-00029-of-00029.safetensors +3 -0
  37. model.safetensors.index.json +0 -0
  38. omlx/install_omlx_solar_open2_patch.sh +130 -0
  39. omlx/solar_open2_tool_parser.py +114 -0
  40. solar_open2.py +372 -0
  41. tokenizer.json +3 -0
  42. tokenizer_config.json +14 -0
.gitattributes ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
5
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
6
+ *.ftz filter=lfs diff=lfs merge=lfs -text
7
+ *.gz filter=lfs diff=lfs merge=lfs -text
8
+ *.h5 filter=lfs diff=lfs merge=lfs -text
9
+ *.joblib filter=lfs diff=lfs merge=lfs -text
10
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
+ *.model filter=lfs diff=lfs merge=lfs -text
13
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
14
+ *.npy filter=lfs diff=lfs merge=lfs -text
15
+ *.npz filter=lfs diff=lfs merge=lfs -text
16
+ *.onnx filter=lfs diff=lfs merge=lfs -text
17
+ *.ot filter=lfs diff=lfs merge=lfs -text
18
+ *.parquet filter=lfs diff=lfs merge=lfs -text
19
+ *.pb filter=lfs diff=lfs merge=lfs -text
20
+ *.pickle filter=lfs diff=lfs merge=lfs -text
21
+ *.pkl filter=lfs diff=lfs merge=lfs -text
22
+ *.pt filter=lfs diff=lfs merge=lfs -text
23
+ *.pth filter=lfs diff=lfs merge=lfs -text
24
+ *.rar filter=lfs diff=lfs merge=lfs -text
25
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
26
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
28
+ *.tar filter=lfs diff=lfs merge=lfs -text
29
+ *.tflite filter=lfs diff=lfs merge=lfs -text
30
+ *.tgz filter=lfs diff=lfs merge=lfs -text
31
+ *.wasm filter=lfs diff=lfs merge=lfs -text
32
+ *.xz filter=lfs diff=lfs merge=lfs -text
33
+ *.zip filter=lfs diff=lfs merge=lfs -text
34
+ *.zst filter=lfs diff=lfs merge=lfs -text
35
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ tokenizer.json filter=lfs diff=lfs merge=lfs -text
LICENSE ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Upstage Solar License
2
+
3
+ # Preamble
4
+
5
+ The 'Upstage Solar License' (hereinafter referred to as "this License") was established by Upstage Co., Ltd., incorporated under the laws of the Republic of Korea, to encourage the development of open-source software using Solar AI models, and is not affiliated with the Apache Software Foundation.
6
+
7
+ This License basically adopts all provisions of the Apache License, Version 2.0 (hereinafter referred to as "Apache License 2.0"), including the principle of allowing commercial use, but prescribes minimum strategic conditions for the global expansion of AI technology and the sustainable development of the AI ecosystem.
8
+
9
+ The key additional condition, as specified in Section 4(e), is that if you distribute a "Derivative AI Model" based on the "Work", you must specify the 'Solar' brand. This applies as an exception to Section 6 (Trademarks) of the Apache License 2.0.
10
+
11
+ # TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
12
+
13
+ 1\. Definitions.
14
+
15
+ "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
16
+
17
+ "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
18
+
19
+ "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
20
+
21
+ "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
22
+
23
+ "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
24
+
25
+ "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
26
+
27
+ "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
28
+
29
+ "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
30
+
31
+ "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
32
+
33
+ "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
34
+
35
+ 2\. Grant of Copyright License.
36
+ Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
37
+
38
+ 3\. Grant of Patent License.
39
+ Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
40
+
41
+ 4\. Redistribution.
42
+ You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
43
+
44
+ (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and
45
+ (b) You must cause any modified files to carry prominent notices stating that You changed the files; and
46
+ (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
47
+ (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
48
+ (e) If You distribute or make available a Derivative Work that is an artificial intelligence model created, trained, fine-tuned, or otherwise improved using the Work (the "Derivative AI Model"), You must adhere to the following conditions:
49
+ (i) The name of such Derivative AI Model must begin with "Solar" (e.g., "Solar-MyModel-v1"); and
50
+ (ii) You must prominently display the phrase "Built with Solar" in any related websites, user interfaces, or documentation associated with the Derivative AI Model; and
51
+ (iii) You must provide a copy of this License, including the original copyright notice and NOTICE file as included in the distribution of the Works, alongside the Derivative AI Model.
52
+
53
+ You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
54
+
55
+ 5\. Submission of Contributions.
56
+ Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
57
+
58
+ 6\. Trademarks.
59
+ This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work, reproducing the content of the NOTICE file, and as explicitly required for attribution in Section 4(e) of this License.
60
+ Any use of the “Solar” name under this License must not imply any sponsorship, endorsement, certification, or official relationship with the Licensor, nor mislead users into believing that a Derivative AI Model is an official product of the Licensor.
61
+
62
+ 7\. Disclaimer of Warranty.
63
+ Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
64
+
65
+ 8\. Limitation of Liability.
66
+ In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
67
+
68
+ 9\. Accepting Warranty or Additional Liability.
69
+ While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
70
+
71
+ END OF TERMS AND CONDITIONS
72
+
73
+ # APPENDIX: How to apply the Upstage Solar License to your work.
74
+
75
+ To apply the Upstage Solar License to your work, attach the following boilerplate notice, with the fields enclosed by brackets replaced with your own identifying information. (Don't include the brackets\!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives.
76
+
77
+ Copyright \[yyyy\] \[Upstage AI (or other copyright owner)\]
78
+
79
+ Licensed under the Upstage Solar License (the "License");
80
+ you may not use this file except in compliance with the License.
81
+ You may obtain a copy of the License at
82
+
83
+ https://huggingface.co/Upstage/Solar-Open-100B/blob/main/LICENSE
84
+
85
+ Unless required by applicable law or agreed to in writing, software
86
+ distributed under the License is distributed on an "AS IS" BASIS,
87
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
88
+ See the License for the specific language governing permissions and
89
+ limitations under the License.
90
+
91
+ This work is based on or derived from materials licensed under the
92
+ Upstage Solar License.
93
+ If you distribute or make available a Derivative AI Model (as defined
94
+ in Section 4(e) of the License), your model name must begin with "Solar"
95
+ and you must prominently display "Built with Solar" in associated
96
+ documentation or interfaces.
OMLX.md ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Using This Quant With OMLX
2
+
3
+ Some OMLX builds may not yet include native Solar Open2 support in their bundled
4
+ `mlx_lm` runtime. This repo includes a small compatibility patch that installs:
5
+
6
+ - `solar_open2.py`, the MLX loader for the Solar Open2 architecture.
7
+ - `solar_open2_tool_parser.py`, a parser for Solar Open2 tool-call markup.
8
+ - Tokenizer runtime detection for Solar Open2 thinking and tool-call markers.
9
+ - Four-state recurrent-cache restoration for reliable multi-turn tool loops.
10
+
11
+ ## Install
12
+
13
+ Clone this model repo locally, then run the installer from the repo root:
14
+
15
+ ```bash
16
+ sudo zsh omlx/install_omlx_solar_open2_patch.sh
17
+ ```
18
+
19
+ The installer patches the OMLX app bundle and creates timestamped backups of any
20
+ files it changes. If your OMLX installation uses a non-default location, set:
21
+
22
+ ```bash
23
+ export OMLX_MLX_LM_DIR="/path/to/mlx_lm"
24
+ export OMLX_PYTHON="/path/to/python"
25
+ export OMLX_RESOURCES="/path/to/oMLX.app/Contents/Resources"
26
+ sudo -E zsh omlx/install_omlx_solar_open2_patch.sh
27
+ ```
28
+
29
+ Reload OMLX after installing the patch.
30
+
31
+ ## Tool Calling
32
+
33
+ Solar Open2 emits tool calls using this marker format:
34
+
35
+ ```text
36
+ <|tool_call:start|>tool_name
37
+ <|tool_arg:start|>argument_name<|tool_arg:value|>argument_value<|tool_arg:end|>
38
+ <|tool_call:end|>
39
+ ```
40
+
41
+ The included parser converts that format into OpenAI-compatible tool-call
42
+ arguments where the serving runtime supports tool parsing.
43
+
44
+ ## Thinking Toggle
45
+
46
+ This quant defaults to clean direct responses. To enable or disable thinking in
47
+ clients that pass chat-template arguments:
48
+
49
+ ```json
50
+ {"enable_thinking": false}
51
+ ```
52
+
53
+ ```json
54
+ {"enable_thinking": true}
55
+ ```
56
+
57
+ Advanced clients can also pass Solar's native option directly:
58
+
59
+ ```json
60
+ {"reasoning_effort": "none"}
61
+ ```
62
+
63
+ ```json
64
+ {"reasoning_effort": "high"}
65
+ ```
66
+
67
+ If the serving runtime does not hide reasoning channels, enabled thinking may
68
+ show `<|think:start|>` and `<|think:end|>` markers in generated text.
69
+
70
+ ## Notes
71
+
72
+ OMLX updates can replace bundled runtime files. Re-run the installer after an
73
+ OMLX update if the model stops loading or tool-call parsing disappears.
README.md ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ language:
3
+ - en
4
+ - ko
5
+ - ja
6
+ library_name: mlx
7
+ pipeline_tag: text-generation
8
+ license: other
9
+ license_name: upstage-solar-license
10
+ license_link: LICENSE
11
+ base_model: upstage/Solar-Open2-250B
12
+ tags:
13
+ - mlx
14
+ - solar
15
+ - solar-open2
16
+ - moe
17
+ - text-generation
18
+ - quantized
19
+ - 4bit
20
+ ---
21
+
22
+ # Solar-Open2-250B-MLX-4bit
23
+
24
+ Built with Solar. This is an MLX 4-bit affine quantization of [upstage/Solar-Open2-250B](https://huggingface.co/upstage/Solar-Open2-250B), converted for Apple Silicon / MLX workflows.
25
+
26
+ ## Details
27
+
28
+ - Source model: `upstage/Solar-Open2-250B`
29
+ - Quantization: 4-bit affine, group size 64
30
+ - Local size: 131G
31
+ - Weight shards: 29
32
+ - Architecture: Solar Open 2 hybrid-attention MoE, 250B total / ~15B active parameters
33
+ - Context: source model advertises 1M-token context; practical MLX context depends on memory and runtime settings
34
+
35
+ ## Important runtime notes
36
+
37
+ Solar Open2 is not yet a stock `mlx-lm` architecture in many installs. This repo includes `solar_open2.py`; launch with `--trust-remote-code` when serving or loading from Hugging Face.
38
+
39
+ ```bash
40
+ mlx_lm.server \
41
+ --model Vontra/Solar-Open2-250B-MLX-4bit \
42
+ --host 0.0.0.0 \
43
+ --port 8021 \
44
+ --trust-remote-code \
45
+ --temp 0.2 \
46
+ --top-p 0.9 \
47
+ --max-tokens 32768
48
+ ```
49
+
50
+ You may see a `transformers` warning that mentions loading `model_type=solar_open2` into a blank model type. With the included custom MLX loader this warning is expected; the important check is that the model actually loads.
51
+
52
+ The tokenizer template uses Solar/Whale-style tool markers such as `<|tool_call:start|>` and `<|tool_arg:start|>`. For OpenAI-compatible tool calling, your serving runtime must parse those markers into structured `tool_calls`. Plain text generation does not need this parser.
53
+
54
+ ## Use with MLX
55
+
56
+ This repo includes a small `solar_open2.py` MLX loader because upstream `mlx-lm` does not yet ship native Solar Open 2 support.
57
+
58
+ ```bash
59
+ pip install -U mlx-lm
60
+ ```
61
+
62
+ ```python
63
+ from mlx_lm import load, generate
64
+
65
+ model, tokenizer = load("Vontra/Solar-Open2-250B-MLX-4bit")
66
+ prompt = "Write a short Python function that validates an IPv4 CIDR string."
67
+ print(generate(model, tokenizer, prompt=prompt, max_tokens=256, verbose=True))
68
+ ```
69
+
70
+ ## Notes
71
+
72
+ This is an independent community conversion under the Vontra organization. It is not an official Upstage release.
73
+
74
+ ## License
75
+
76
+ The source model is released under the Upstage Solar License. A copy is included in `LICENSE`. Please review the upstream model card and license before use or redistribution.
chat_template.jinja ADDED
@@ -0,0 +1,235 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {#- ======== Template Parameters ======== #}
2
+ {%- set add_generation_prompt = add_generation_prompt if add_generation_prompt is defined else true %}
3
+ {%- set provider_system_prompt = provider_system_prompt if provider_system_prompt else false %}
4
+ {%- set enable_thinking = enable_thinking if enable_thinking is defined else false %}
5
+ {%- set reasoning_effort = reasoning_effort if reasoning_effort is defined else ("high" if enable_thinking else "none") %}
6
+ {%- set think_render_option = think_render_option if think_render_option is defined else "interleaved" %}
7
+
8
+ {#- ======== System Block State ======== #}
9
+ {%- set sys_ns = namespace(is_first_block=true) -%}
10
+
11
+ {#- ======== Find last user message index ======== #}
12
+ {%- set last_user_idx = namespace(value=-1) -%}
13
+ {%- for message in messages -%}
14
+ {%- if message.role == 'user' -%}
15
+ {%- set last_user_idx.value = loop.index0 -%}
16
+ {%- endif -%}
17
+ {%- endfor -%}
18
+
19
+ {#- ======== System messages renderers ======== #}
20
+ {%- macro render_system_message(user_system_messages) %}
21
+ {%- if provider_system_prompt %}
22
+ {%- if not sys_ns.is_first_block %}{{- "\n\n" }}{%- endif %}
23
+ {%- set sys_ns.is_first_block = false %}
24
+ {{- "## Provider System Prompt\n\nYou are Solar Open2 250B, a large language model trained by Upstage AI, a Korean startup. Your knowledge cutoff is 2026-02. The current date is " + strftime_now("%Y-%m-%d") + "." }}
25
+ {%- endif -%}
26
+ {%- if user_system_messages %}
27
+ {%- if not sys_ns.is_first_block %}{{- "\n\n" }}{%- endif %}
28
+ {%- set sys_ns.is_first_block = false %}
29
+ {{- "## System Prompt" }}
30
+ {%- for system_message in user_system_messages %}
31
+ {{- "\n\n" }}
32
+ {{- system_message }}
33
+ {%- endfor %}
34
+ {%- endif -%}
35
+ {%- endmacro %}
36
+
37
+ {%- macro render_tool_instruction(tools, is_last_block) %}
38
+ {%- if not sys_ns.is_first_block %}{{- "\n\n" }}{%- endif %}
39
+ {%- set sys_ns.is_first_block = false %}
40
+ {{- "## Tools\n- You may invoke one or more tools to assist with the user's query." }}
41
+ {{- "\n\n### Available Tools\n" }}
42
+ {%- for tool in tools %}
43
+ {{- "<|tool:start|>" }}
44
+ {{- tool.function | tojson }}
45
+ {{- "<|tool:end|>\n" }}
46
+ {%- endfor %}
47
+ {{- "\n### Tool Call Instruction\n" }}
48
+ {{- "- If using a tool, any reasoning must strictly precede the call. Do not append any text after the tool call.\n" }}
49
+ {{- "- If no tool is required, answer directly from your knowledge without ever mentioning the availability or absence of tools.\n" }}
50
+ {{- "- Each tool call MUST use this following format: <|tool_call:start|>{example-tool-name}\n<|tool_arg:start|>{example-key-name-1}<|tool_arg:value|>{example-value-1}<|tool_arg:end|>\n<|tool_arg:start|>{example-key-name-2}<|tool_arg:value|>{example-value-2}<|tool_arg:end|>\n<|tool_call:end|>\n" }}
51
+ {%- endmacro %}
52
+
53
+ {#-
54
+ Input convention for `response_format`:
55
+ - Per the OpenAI Chat Completions API, `response_format` is an object of one of:
56
+ {"type": "json_schema", "json_schema": {"name": ..., "schema": {...}, "strict": ...}}
57
+ {"type": "json_object"}
58
+ - Only `response_format.json_schema.schema` (the inner JSON Schema) is injected
59
+ into the prompt; the OpenAI wrapper fields (`name`, `strict`, ...) are dropped.
60
+ - For `json_object`, no schema exists, so we emit a generic JSON-only instruction.
61
+ - vLLM does NOT pass `response_format` to chat templates by default; it routes it
62
+ to guided decoding instead. This template/whale opts into prompt injection,
63
+ so callers serving the model directly via vLLM must opt in via
64
+ `chat_template_kwargs` (or rely on whale's normalization).
65
+ -#}
66
+ {%- macro render_json_response_format_instruction(response_format) %}
67
+ {%- if not sys_ns.is_first_block %}{{- "\n\n" }}{%- endif %}
68
+ {%- set sys_ns.is_first_block = false %}
69
+ {{- "## Output Format Constraint" }}
70
+ {%- if response_format.type == "json_schema" %}
71
+ {{- "\n\n- Your final response should follow the JSON schema:\n```json\n" }}
72
+ {{- response_format.json_schema.schema | tojson }}
73
+ {{- "\n```\n- Please ensure your answers adhere to this format and do not contain any unnecessary text." }}
74
+ {%- elif response_format.type == "json_object" %}
75
+ {{- "\n\n- Your final response must be a valid JSON object." }}
76
+ {{- "\n- Do not include any text outside the JSON object." }}
77
+ {%- endif %}
78
+ {%- endmacro %}
79
+
80
+ {#-
81
+ Input convention for `tool_arguments`:
82
+ - Must be a mapping (dict), NOT a JSON-encoded string.
83
+ - The OpenAI API spec defines `tool_calls[].function.arguments` as a JSON string,
84
+ but vLLM, HuggingFace transformers tool-use templates (Qwen, Hermes, Llama, ...),
85
+ and this template all expect the value to be parsed into a dict before rendering.
86
+ - vLLM normalizes this in `_postprocess_messages()` (vllm/entrypoints/chat_utils.py).
87
+ - Callers (whale, training pipelines that call `tokenizer.apply_chat_template`
88
+ directly, ...) are responsible for parsing the JSON string into a dict before
89
+ invoking the template.
90
+ -#}
91
+ {%- macro render_tool_arguments(tool_arguments) %}
92
+ {%- for args_name, args_value in tool_arguments|items %}
93
+ {{- "<|tool_arg:start|>"+ args_name + "<|tool_arg:value|>"}}
94
+ {%- set args_value = args_value if args_value is string else (args_value | tojson | safe) %}
95
+ {{- args_value }}
96
+ {{- "<|tool_arg:end|>\n" }}
97
+ {%- endfor %}
98
+ {%- endmacro %}
99
+
100
+ {#- ======== Render system message ======== #}
101
+ {%- set ns = namespace(system_messages=[]) -%}
102
+ {%- for message in messages -%}
103
+ {%- if message.role == 'system' -%}
104
+ {%- set ns.system_messages = ns.system_messages + [message.content] -%}
105
+ {%- endif -%}
106
+ {%- endfor -%}
107
+
108
+ {%- if ns.system_messages or provider_system_prompt or tools or response_format -%}
109
+ {{- "<|im:start|>system<|im:content|>" }}
110
+ {{- render_system_message(ns.system_messages) }}
111
+ {%- if tools -%}
112
+ {{- render_tool_instruction(tools, not response_format) }}
113
+ {%- endif %}
114
+ {%- if response_format -%}
115
+ {{- render_json_response_format_instruction(response_format) }}
116
+ {%- endif %}
117
+ {{- "<|im:end|>\n" }}
118
+ {%- endif -%}
119
+
120
+ {#- ======== Render main messages ======== #}
121
+ {%- for message in messages -%}
122
+ {%- if message.role == 'user' -%}
123
+ {{- "<|im:start|>user<|im:content|>" + message.content + "<|im:end|>\n" }}
124
+ {%- elif message.role == 'tool' -%}
125
+ {%- if not message.tool_call_id -%}
126
+ {{- raise_exception("tool message is missing required 'tool_call_id' field") -}}
127
+ {%- endif -%}
128
+ {%- set prev_is_tool = loop.index0 > 0 and messages[loop.index0 - 1].role == 'tool' -%}
129
+ {#- Only render at the start of a contiguous tool block; subsequent tool messages -#}
130
+ {#- are already emitted (reordered) within the first one. -#}
131
+ {%- if not prev_is_tool -%}
132
+ {%- set start_idx = loop.index0 -%}
133
+ {#- Collect contiguous tool messages starting at start_idx -#}
134
+ {%- set tool_ns = namespace(items=[], scanning=true) -%}
135
+ {%- for j in range(start_idx, messages | length) -%}
136
+ {%- if tool_ns.scanning -%}
137
+ {%- if messages[j].role == 'tool' -%}
138
+ {%- set tool_ns.items = tool_ns.items + [messages[j]] -%}
139
+ {%- else -%}
140
+ {%- set tool_ns.scanning = false -%}
141
+ {%- endif -%}
142
+ {%- endif -%}
143
+ {%- endfor -%}
144
+
145
+ {{- "<|im:start|>tool<|im:content|>" }}
146
+
147
+ {%- set prev_msg = messages[start_idx - 1] if start_idx > 0 else none -%}
148
+ {%- if prev_msg and prev_msg.role == 'assistant' and prev_msg.tool_calls -%}
149
+ {#- Render tool responses in the order of the preceding assistant's tool_calls ids. -#}
150
+ {%- set sep_ns = namespace(first=true, rendered_ids=[]) -%}
151
+ {%- for tool_call in prev_msg.tool_calls -%}
152
+ {%- for tool_msg in tool_ns.items -%}
153
+ {%- if tool_msg.tool_call_id == tool_call.id -%}
154
+ {%- if not sep_ns.first -%}{{- "\n" }}{%- endif -%}
155
+ {%- set sep_ns.first = false -%}
156
+ {%- set sep_ns.rendered_ids = sep_ns.rendered_ids + [tool_msg.tool_call_id] -%}
157
+ {{- "<|tool_response:start|>" + tool_msg.content + "<|tool_response:end|>" }}
158
+ {%- endif -%}
159
+ {%- endfor -%}
160
+ {%- endfor -%}
161
+ {#- Append any orphan tool messages (no matching id) in their original order. -#}
162
+ {%- for tool_msg in tool_ns.items -%}
163
+ {%- if tool_msg.tool_call_id not in sep_ns.rendered_ids -%}
164
+ {%- if not sep_ns.first -%}{{- "\n" }}{%- endif -%}
165
+ {%- set sep_ns.first = false -%}
166
+ {{- "<|tool_response:start|>" + tool_msg.content + "<|tool_response:end|>" }}
167
+ {%- endif -%}
168
+ {%- endfor -%}
169
+ {%- else -%}
170
+ {%- for tool_msg in tool_ns.items -%}
171
+ {%- if not loop.first -%}{{- "\n" }}{%- endif -%}
172
+ {{- "<|tool_response:start|>" + tool_msg.content + "<|tool_response:end|>" }}
173
+ {%- endfor -%}
174
+ {%- endif -%}
175
+
176
+ {{- "\n<|im:end|>\n" }}
177
+ {%- endif -%}
178
+ {%- elif message.role == 'assistant' -%}
179
+ {{- "<|im:start|>assistant<|im:content|>" }}
180
+
181
+ {#- ======== Resolve reasoning field (reasoning or reasoning_content) ======== #}
182
+ {%- if message.reasoning is defined -%}
183
+ {%- set reasoning = message.reasoning -%}
184
+ {%- elif message.reasoning_content is defined -%}
185
+ {%- set reasoning = message.reasoning_content -%}
186
+ {%- else -%}
187
+ {%- set reasoning = none -%}
188
+ {%- endif -%}
189
+
190
+ {#- ======== Assistant Thinking ======== #}
191
+ {%- if think_render_option == "preserved" -%}
192
+ {%- if reasoning -%}
193
+ {{- "<|think:start|>" + reasoning + "<|think:end|>" }}
194
+ {%- else -%}
195
+ {{- "<|think:start|><|think:end|>" }}
196
+ {%- endif -%}
197
+ {%- elif think_render_option == "interleaved" -%}
198
+ {%- if reasoning and loop.index0 > last_user_idx.value -%}
199
+ {{- "<|think:start|>" + reasoning + "<|think:end|>" }}
200
+ {%- else -%}
201
+ {{- "<|think:start|><|think:end|>" }}
202
+ {%- endif -%}
203
+ {%- endif -%}
204
+
205
+ {#- ======== Assistant Messages ======== #}
206
+ {%- if message.content -%}
207
+ {{- message.content }}
208
+ {%- endif -%}
209
+
210
+ {#- ======== Assistant Tool calls ======== #}
211
+ {%- if message.tool_calls -%}
212
+ {%- for tool_call in message.tool_calls -%}
213
+ {%- if not tool_call.id -%}
214
+ {{- raise_exception("assistant tool_call is missing required 'id' field") -}}
215
+ {%- endif -%}
216
+ {%- if not loop.first -%}{{- "\n" }}{%- endif -%}
217
+ {{- "<|tool_call:start|>" + tool_call.function.name + "\n" }}
218
+ {%- if tool_call.function.arguments is defined %}
219
+ {{- render_tool_arguments(tool_call.function.arguments) }}
220
+ {%- endif %}
221
+ {{- "<|tool_call:end|>" }}
222
+ {%- endfor -%}
223
+ {{- "\n" }}
224
+ {%- endif -%}
225
+ {{- "<|im:end|>\n" }}
226
+ {%- endif -%}
227
+ {%- endfor -%}
228
+
229
+ {%- if add_generation_prompt -%}
230
+ {%- if reasoning_effort in ["medium", "high", "xhigh"] -%}
231
+ {{- "<|im:start|>assistant<|im:content|><|think:start|>" }}
232
+ {%- else -%}
233
+ {{- "<|im:start|>assistant<|im:content|><|think:start|><|think:end|>" }}
234
+ {%- endif -%}
235
+ {%- endif -%}
config.json ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "SolarOpen2ForCausalLM"
4
+ ],
5
+ "bos_token_id": 1,
6
+ "eos_token_id": [
7
+ 2,
8
+ 129
9
+ ],
10
+ "first_k_dense_replace": 0,
11
+ "gqa_interval": 3,
12
+ "gqa_layers": [
13
+ 0,
14
+ 4,
15
+ 8,
16
+ 12,
17
+ 16,
18
+ 20,
19
+ 24,
20
+ 28,
21
+ 32,
22
+ 36,
23
+ 40,
24
+ 44
25
+ ],
26
+ "head_dim": 128,
27
+ "hidden_size": 4096,
28
+ "intermediate_size": 10240,
29
+ "kda_allow_neg_eigval": true,
30
+ "kda_use_full_proj": false,
31
+ "linear_attn_config": {
32
+ "short_conv_kernel_size": 4,
33
+ "head_dim": 128,
34
+ "num_heads": 64,
35
+ "num_kv_heads": null
36
+ },
37
+ "max_position_embeddings": 1048576,
38
+ "model_type": "solar_open2",
39
+ "moe_intermediate_size": 1280,
40
+ "n_routed_experts": 320,
41
+ "n_shared_experts": 1,
42
+ "norm_topk_prob": true,
43
+ "num_attention_heads": 64,
44
+ "num_experts_per_tok": 8,
45
+ "num_hidden_layers": 48,
46
+ "num_key_value_heads": 8,
47
+ "pad_token_id": 2,
48
+ "partial_rotary_factor": 1.0,
49
+ "quantization": {
50
+ "group_size": 64,
51
+ "bits": 4,
52
+ "mode": "affine"
53
+ },
54
+ "quantization_config": {
55
+ "group_size": 64,
56
+ "bits": 4,
57
+ "mode": "affine"
58
+ },
59
+ "rms_norm_eps": 1e-05,
60
+ "rope_theta": 10000,
61
+ "routed_scaling_factor": 1.0,
62
+ "tie_word_embeddings": false,
63
+ "torch_dtype": "bfloat16",
64
+ "transformers_version": "5.5.4",
65
+ "use_gqa_gate": true,
66
+ "use_rope": false,
67
+ "vocab_size": 196608,
68
+ "model_file": "solar_open2.py",
69
+ "library_name": "mlx"
70
+ }
generation_config.json ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "bos_token_id": 1,
3
+ "do_sample": true,
4
+ "eos_token_id": [
5
+ 2,
6
+ 129
7
+ ],
8
+ "transformers_version": "4.57.6"
9
+ }
model-00001-of-00029.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:87d4b556464a5e06f76f5d30c7fa4842c39fba2d7405294ff642dad7a7a87cd5
3
+ size 5322042118
model-00002-of-00029.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:de1eafb59e2c9d7da92258838ced1b4e4a961b80270484a97237563fa0e0c9ff
3
+ size 4896833183
model-00003-of-00029.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e888aad95347abbd7645e0e2b195b38e55dd6da6780d3ea064f09366badecad0
3
+ size 4880544949
model-00004-of-00029.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:aad46e6c3fa8a3c666a10a0b08aebe35253a003b83867cd6e7eb680ed68419a5
3
+ size 4807713494
model-00005-of-00029.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1f87cb3d73333e67fa4393d26c228d083d1b804e2be4260e4401b6d567af605f
3
+ size 4880545009
model-00006-of-00029.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5f995bc22d861675b3881f5015d1fbc3ac8d2750943c0c7853907d6abec34944
3
+ size 4896833092
model-00007-of-00029.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:23952b7c18c6cca89281ebd8dd748e81caafa2645fbce3997099d164704f8712
3
+ size 4807713611
model-00008-of-00029.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:609b21e01deab09da030c748738a2181ef1241f5f1aef4b57d83d7219bb66487
3
+ size 4880544924
model-00009-of-00029.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a324481c197b003f9cb83f45686cab94ad7acc32ee049384eceda93d641930d1
3
+ size 4896833210
model-00010-of-00029.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:58a811fe7891241a6e7cb9ca43d33ce134189f43a4223408890d872c78b329cd
3
+ size 4791425403
model-00011-of-00029.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:48a7898c34a7b7564d7c87f700b613dc93354bd471ee860f473858b4194afe79
3
+ size 4896833246
model-00012-of-00029.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:116fdea94e11982a75a7ced5ec8bff704d28a53d85cc2e4ba5fc1560d1f5aca0
3
+ size 4880545060
model-00013-of-00029.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:49d7ea21ac76a93be0cfe54823620de2cbba9f48b7c8f8774dbdebba4600099d
3
+ size 4807713617
model-00014-of-00029.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b8cbd2ea91cb987d5383c943683b6f01545d9dc0cc990ce685ec6f7f12067d59
3
+ size 4896833244
model-00015-of-00029.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:390eee0ff3925595dccb4c35b1e419338408a9b85bba7576b8ab729cd2c91242
3
+ size 4880544958
model-00016-of-00029.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:41bd1760c66275c52de54a156f68f04a6d14169790cf8af961ef21e42c4d4848
3
+ size 4807713609
model-00017-of-00029.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:45e502754a2a3581ac5a53d1ea1a52b4085fb514d2f06b1d1d74ee6cfe98a28b
3
+ size 4880545066
model-00018-of-00029.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:47c68c8ff4aefb22bdc2ac921d625040c57d040e73ab99dda72018a18068f789
3
+ size 4896833148
model-00019-of-00029.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:545c3b6892b5af22e213bfcc9570745cad7f7d775616d118a3c32d7edae5bafc
3
+ size 4807713601
model-00020-of-00029.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5a6128bcc1234ab294e50b625abc04f7850a2c8ffb7ee52ebb45e756ddada4a1
3
+ size 4880544970
model-00021-of-00029.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b01eb8d3df14546c6e5e7216aa3e908654ae115e1d902d5c2a25a58b18e02ba5
3
+ size 4896833188
model-00022-of-00029.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7643178461976584e5ea1e556771bcf823b52ad2421a0ac814ce18c9d0f2e434
3
+ size 4791425401
model-00023-of-00029.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d4355ff13aa776dced78d36ae88f6517c64f282668ae3ce0191aa1ca1de307c0
3
+ size 4896833246
model-00024-of-00029.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:237e7fcbc8166d8b802c69dd9e69f9cae9d92e03f8e069016434e1e984488e1d
3
+ size 4880545042
model-00025-of-00029.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8616949f9684ac6422702555dd4ce152de4d7a239cc7cf0e6c8983327f645b36
3
+ size 4807713601
model-00026-of-00029.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:137ee328f6d34ff90b3aebd5f2d8fb6795b6d83ba2c2e0d1dd43593663e4c44a
3
+ size 4896833190
model-00027-of-00029.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:289e3dd664702e770131c250e1320df84b4262f87dbdc8a11d9b9e58f4f82c46
3
+ size 4880545022
model-00028-of-00029.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ac85d4f7603af874fbb0ccda710a7cc067b895ed84385fa0fe3bfa736fa0b908
3
+ size 4807713617
model-00029-of-00029.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:179c3fc9f9d73ce4f9870ba05384f11361a6776d89e0f5e60584b6332f65a136
3
+ size 4328476277
model.safetensors.index.json ADDED
The diff for this file is too large to render. See raw diff
 
omlx/install_omlx_solar_open2_patch.sh ADDED
@@ -0,0 +1,130 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/zsh
2
+ set -euo pipefail
3
+
4
+ SCRIPT_DIR="${0:A:h}"
5
+ REPO_DIR="${SCRIPT_DIR:h}"
6
+ BASE="${OMLX_MLX_LM_DIR:-/Applications/oMLX.app/Contents/Resources/Python/framework-mlx-base/lib/python3.11/site-packages/mlx_lm}"
7
+ PY="${OMLX_PYTHON:-/Applications/oMLX.app/Contents/Resources/Python/cpython-3.11/bin/python3.11}"
8
+ OMLX_RESOURCES="${OMLX_RESOURCES:-/Applications/oMLX.app/Contents/Resources}"
9
+ PREFIX_CACHE="$OMLX_RESOURCES/omlx/cache/prefix_cache.py"
10
+ STAMP="$(date +%Y%m%d-%H%M%S)"
11
+
12
+ if [[ "$(id -u)" -ne 0 ]]; then
13
+ echo "Run this installer with sudo so it can patch the OMLX app bundle."
14
+ exit 1
15
+ fi
16
+
17
+ test -f "$REPO_DIR/solar_open2.py"
18
+ test -f "$SCRIPT_DIR/solar_open2_tool_parser.py"
19
+ test -f "$BASE/tokenizer_utils.py"
20
+ test -f "$PREFIX_CACHE"
21
+
22
+ mkdir -p "$BASE/models" "$BASE/tool_parsers"
23
+
24
+ cp "$BASE/tokenizer_utils.py" "$BASE/tokenizer_utils.py.bak-$STAMP"
25
+ cp "$PREFIX_CACHE" "$PREFIX_CACHE.bak-$STAMP"
26
+ if [[ -f "$BASE/models/solar_open2.py" ]]; then
27
+ cp "$BASE/models/solar_open2.py" "$BASE/models/solar_open2.py.bak-$STAMP"
28
+ fi
29
+ if [[ -f "$BASE/tool_parsers/solar_open2.py" ]]; then
30
+ cp "$BASE/tool_parsers/solar_open2.py" "$BASE/tool_parsers/solar_open2.py.bak-$STAMP"
31
+ fi
32
+
33
+ install -m 0644 "$REPO_DIR/solar_open2.py" "$BASE/models/solar_open2.py"
34
+ install -m 0644 "$SCRIPT_DIR/solar_open2_tool_parser.py" "$BASE/tool_parsers/solar_open2.py"
35
+
36
+ TOKENIZER_UTILS="$BASE/tokenizer_utils.py" "$PY" - <<'PY'
37
+ import os
38
+ from pathlib import Path
39
+
40
+ path = Path(os.environ["TOKENIZER_UTILS"])
41
+ text = path.read_text(encoding="utf-8")
42
+
43
+ think_marker = ' ("<|think:start|>", "<|think:end|>"),\n'
44
+ if think_marker not in text:
45
+ anchor = ' ("<longcat_think>", "</longcat_think>"),\n'
46
+ if anchor not in text:
47
+ raise SystemExit("Could not find the thinking-token list in tokenizer_utils.py")
48
+ text = text.replace(anchor, anchor + think_marker, 1)
49
+
50
+ parser_marker = ' return "solar_open2"\n'
51
+ if parser_marker not in text:
52
+ anchor = (
53
+ ' elif "<|tool_list_start|>" in chat_template:\n'
54
+ ' return "pythonic"\n'
55
+ )
56
+ insert = (
57
+ ' elif "<|tool_call:start|>" in chat_template and "<|tool_arg:start|>" in chat_template:\n'
58
+ ' return "solar_open2"\n'
59
+ )
60
+ if anchor not in text:
61
+ raise SystemExit("Could not find the tool-parser inference block in tokenizer_utils.py")
62
+ text = text.replace(anchor, anchor + insert, 1)
63
+
64
+ solar_apply_marker = 'is_solar_open2 = "<|tool_call:start|>" in template and "<|tool_arg:start|>" in template and "<|think:start|>" in template\n'
65
+ if solar_apply_marker not in text:
66
+ old = (
67
+ ' def apply_chat_template(self, *args, tokenize=True, **kwargs):\n'
68
+ ' if "enable_thinking" not in kwargs:\n'
69
+ ' kwargs["enable_thinking"] = self.has_thinking\n'
70
+ )
71
+ new = (
72
+ ' def apply_chat_template(self, *args, tokenize=True, **kwargs):\n'
73
+ ' template = self._chat_template or getattr(self._tokenizer, "chat_template", None) or ""\n'
74
+ ' is_solar_open2 = "<|tool_call:start|>" in template and "<|tool_arg:start|>" in template and "<|think:start|>" in template\n'
75
+ ' if is_solar_open2 and "reasoning_effort" not in kwargs:\n'
76
+ ' enable_thinking = kwargs.pop("enable_thinking", False)\n'
77
+ ' kwargs["reasoning_effort"] = "high" if enable_thinking else "none"\n'
78
+ ' elif "enable_thinking" not in kwargs:\n'
79
+ ' kwargs["enable_thinking"] = self.has_thinking\n'
80
+ )
81
+ if old not in text:
82
+ raise SystemExit("Could not patch TokenizerWrapper.apply_chat_template in tokenizer_utils.py")
83
+ text = text.replace(old, new, 1)
84
+
85
+ path.write_text(text, encoding="utf-8")
86
+ PY
87
+
88
+ PREFIX_CACHE="$PREFIX_CACHE" "$PY" - <<'PY'
89
+ import os
90
+ from pathlib import Path
91
+
92
+ path = Path(os.environ["PREFIX_CACHE"])
93
+ text = path.read_text(encoding="utf-8")
94
+
95
+ marker = "Solar Open2 variable ArraysCache compatibility"
96
+ if marker not in text:
97
+ old = """ cache = marker_handler.deserialize_state(
98
+ tuple(elements), meta_state
99
+ )
100
+ """
101
+ new = """ # Solar Open2 variable ArraysCache compatibility:
102
+ # preserve all recurrent-state tensors and their token count.
103
+ if marker_handler.is_variable_length_state():
104
+ cache = marker_handler.reconstruct_cache(
105
+ {
106
+ \"states\": list(elements),
107
+ \"cache_type\": marker_class,
108
+ },
109
+ meta_state,
110
+ token_count=valid_token_count,
111
+ )
112
+ else:
113
+ cache = marker_handler.deserialize_state(
114
+ tuple(elements), meta_state
115
+ )
116
+ """
117
+ if old not in text:
118
+ raise SystemExit("Could not patch variable ArraysCache reconstruction in prefix_cache.py")
119
+ text = text.replace(old, new, 1)
120
+
121
+ path.write_text(text, encoding="utf-8")
122
+ PY
123
+
124
+ "$PY" -m py_compile \
125
+ "$BASE/models/solar_open2.py" \
126
+ "$BASE/tool_parsers/solar_open2.py" \
127
+ "$BASE/tokenizer_utils.py" \
128
+ "$PREFIX_CACHE"
129
+
130
+ echo "Installed Solar Open2 OMLX compatibility patch. Backups use stamp $STAMP."
omlx/solar_open2_tool_parser.py ADDED
@@ -0,0 +1,114 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import ast
2
+ import json
3
+ import re
4
+ from typing import Any
5
+
6
+
7
+ tool_call_start = "<|tool_call:start|>"
8
+ tool_call_end = "<|tool_call:end|>"
9
+
10
+ _ARG_RE = re.compile(
11
+ r"<\|tool_arg:start\|>(.*?)<\|tool_arg:value\|>(.*?)<\|tool_arg:end\|>",
12
+ re.DOTALL,
13
+ )
14
+
15
+ _STRING_TYPES = {"string", "str", "text", "varchar", "char", "enum"}
16
+ _BOOL_TYPES = {"boolean", "bool", "binary"}
17
+ _INT_PREFIXES = ("int", "uint", "long", "short", "unsigned")
18
+ _FLOAT_PREFIXES = ("num", "float", "double", "decimal")
19
+ _JSON_TYPES = {"object", "array", "arr", "dict", "list"}
20
+
21
+
22
+ def _tool_properties(name: str, tools: Any | None) -> dict[str, Any]:
23
+ if not tools:
24
+ return {}
25
+ for tool in tools:
26
+ function = tool.get("function") if isinstance(tool, dict) else None
27
+ if function and function.get("name") == name:
28
+ params = function.get("parameters") or {}
29
+ return params.get("properties") or {}
30
+ return {}
31
+
32
+
33
+ def _schema_type(properties: dict[str, Any], key: str) -> str:
34
+ schema = properties.get(key) or {}
35
+ typ = schema.get("type", "string")
36
+ if isinstance(typ, list):
37
+ typ = next((item for item in typ if item != "null"), typ[0] if typ else "string")
38
+ return str(typ).lower()
39
+
40
+
41
+ def _coerce(value: str, key: str, properties: dict[str, Any]) -> Any:
42
+ value = value.strip()
43
+ typ = _schema_type(properties, key)
44
+
45
+ if value.lower() == "null":
46
+ return None
47
+ if typ in _STRING_TYPES:
48
+ return value
49
+ if typ in _BOOL_TYPES:
50
+ normalized = value.lower()
51
+ if normalized in {"1", "true", "yes"}:
52
+ return True
53
+ if normalized in {"0", "false", "no"}:
54
+ return False
55
+ return value
56
+ if typ.startswith(_INT_PREFIXES):
57
+ try:
58
+ return int(value)
59
+ except (TypeError, ValueError):
60
+ return value
61
+ if typ.startswith(_FLOAT_PREFIXES):
62
+ try:
63
+ number = float(value)
64
+ return int(number) if number.is_integer() else number
65
+ except (TypeError, ValueError):
66
+ return value
67
+ if typ in _JSON_TYPES or typ.startswith(("dict", "list")):
68
+ try:
69
+ return json.loads(value)
70
+ except (TypeError, ValueError, json.JSONDecodeError):
71
+ try:
72
+ return ast.literal_eval(value)
73
+ except (SyntaxError, ValueError):
74
+ return value
75
+
76
+ try:
77
+ return json.loads(value)
78
+ except (TypeError, json.JSONDecodeError):
79
+ return value
80
+
81
+
82
+ def parse_tool_call(text: str, tools: Any | None = None) -> dict[str, Any]:
83
+ body = text.strip()
84
+ if body.startswith(tool_call_start):
85
+ body = body[len(tool_call_start) :].strip()
86
+ if body.endswith(tool_call_end):
87
+ body = body[: -len(tool_call_end)].strip()
88
+
89
+ first_arg = body.find("<|tool_arg:start|>")
90
+ if first_arg == -1:
91
+ try:
92
+ payload = json.loads(body)
93
+ except json.JSONDecodeError as exc:
94
+ raise ValueError(f"No Solar tool arguments found in: {text!r}") from exc
95
+ name = payload.get("name") or payload.get("tool") or payload.get("function")
96
+ args = payload.get("arguments") or payload.get("args") or {}
97
+ if not name:
98
+ raise ValueError(f"No Solar tool name found in: {text!r}")
99
+ if isinstance(args, str):
100
+ args = json.loads(args)
101
+ return {"name": name, "arguments": args}
102
+
103
+ name = body[:first_arg].strip().splitlines()[0].strip()
104
+ if not name:
105
+ raise ValueError(f"No Solar tool name found in: {text!r}")
106
+
107
+ properties = _tool_properties(name, tools)
108
+ arguments: dict[str, Any] = {}
109
+ for key, value in _ARG_RE.findall(body[first_arg:]):
110
+ key = key.strip()
111
+ if key:
112
+ arguments[key] = _coerce(value, key, properties)
113
+
114
+ return {"name": name, "arguments": arguments}
solar_open2.py ADDED
@@ -0,0 +1,372 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2026
2
+ #
3
+ # Local MLX-LM compatibility loader for upstage/Solar-Open2-250B.
4
+ #
5
+ # Solar Open 2 uses a hybrid stack: GQA/full attention every fourth layer and
6
+ # Kimi-style gated delta attention in the other layers, with a GLM/Solar MoE.
7
+
8
+ from dataclasses import dataclass, field
9
+ from typing import Any, Dict, List, Optional, Tuple
10
+
11
+ import mlx.core as mx
12
+ import mlx.nn as nn
13
+
14
+ from mlx_lm.models.base import (
15
+ BaseModelArgs,
16
+ create_attention_mask,
17
+ create_ssm_mask,
18
+ scaled_dot_product_attention,
19
+ )
20
+ from mlx_lm.models.cache import ArraysCache, KVCache
21
+ from mlx_lm.models.gated_delta import gated_delta_kernel, gated_delta_ops
22
+ from mlx_lm.models.glm4_moe import MLP, MoE
23
+ from mlx_lm.models.kimi_linear import KimiDeltaAttention
24
+ from mlx_lm.models.pipeline import PipelineMixin
25
+
26
+
27
+ @dataclass
28
+ class ModelArgs(BaseModelArgs):
29
+ model_type: str
30
+ vocab_size: int
31
+ hidden_size: int
32
+ intermediate_size: int
33
+ moe_intermediate_size: int
34
+ num_hidden_layers: int
35
+ num_attention_heads: int
36
+ num_key_value_heads: int
37
+ head_dim: int
38
+ n_shared_experts: int
39
+ n_routed_experts: int
40
+ routed_scaling_factor: float
41
+ num_experts_per_tok: int
42
+ first_k_dense_replace: int
43
+ norm_topk_prob: bool
44
+ max_position_embeddings: int
45
+ rms_norm_eps: float
46
+ rope_theta: float = 10000.0
47
+ tie_word_embeddings: bool = False
48
+ partial_rotary_factor: float = 1.0
49
+ linear_attn_config: Dict[str, Any] = field(default_factory=dict)
50
+ gqa_layers: List[int] = field(default_factory=list)
51
+ gqa_interval: int = 3
52
+ use_gqa_gate: bool = True
53
+ use_gqa_gate_bias: bool = False
54
+ use_rope: bool = False
55
+ attention_bias: bool = False
56
+ use_qk_norm: bool = False
57
+ kda_use_full_proj: bool = False
58
+ kda_gate_lower_bound: Optional[float] = -5.0
59
+ kda_allow_neg_eigval: bool = True
60
+ n_group: int = 1
61
+ topk_group: int = 1
62
+ scoring_func: str = "sigmoid"
63
+ topk_method: str = "noaux_tc"
64
+
65
+
66
+ @mx.compile
67
+ def _solar_kda_decay(A_log, a, dt_bias, lower_bound: Optional[float]):
68
+ num_heads = A_log.size
69
+ head_dim = dt_bias.size // num_heads
70
+ A = mx.reshape(A_log.astype(mx.float32), (num_heads, 1))
71
+ dt = mx.reshape(dt_bias.astype(mx.float32), (num_heads, head_dim))
72
+ log_decay = -mx.exp(A) * nn.softplus(a.astype(mx.float32) + dt)
73
+ if lower_bound is not None:
74
+ log_decay = mx.maximum(log_decay, mx.array(lower_bound, dtype=log_decay.dtype))
75
+ return mx.exp(log_decay)
76
+
77
+
78
+ def _solar_gated_delta_update(
79
+ q: mx.array,
80
+ k: mx.array,
81
+ v: mx.array,
82
+ a: mx.array,
83
+ b: mx.array,
84
+ A_log: mx.array,
85
+ dt_bias: mx.array,
86
+ state: Optional[mx.array] = None,
87
+ mask: Optional[mx.array] = None,
88
+ use_kernel: bool = True,
89
+ lower_bound: Optional[float] = -5.0,
90
+ allow_neg_eigval: bool = True,
91
+ ) -> Tuple[mx.array, mx.array]:
92
+ beta = mx.sigmoid(b)
93
+ if allow_neg_eigval:
94
+ beta = beta * 2.0
95
+ g = _solar_kda_decay(A_log, a, dt_bias, lower_bound)
96
+ if state is None:
97
+ B, _, Hk, Dk = q.shape
98
+ Hv, Dv = v.shape[-2:]
99
+ state = mx.zeros((B, Hv, Dv, Dk), dtype=mx.float32)
100
+
101
+ if not use_kernel or mx.default_device() != mx.gpu or not mx.metal.is_available():
102
+ return gated_delta_ops(q, k, v, g, beta, state, mask)
103
+ return gated_delta_kernel(q, k, v, g, beta, state, mask)
104
+
105
+
106
+ class SolarOpen2Attention(nn.Module):
107
+ def __init__(self, args: ModelArgs):
108
+ super().__init__()
109
+ dim = args.hidden_size
110
+ self.n_heads = args.num_attention_heads
111
+ self.n_kv_heads = args.num_key_value_heads
112
+ self.head_dim = args.head_dim
113
+ self.scale = self.head_dim**-0.5
114
+ self.use_gqa_gate = args.use_gqa_gate
115
+
116
+ self.q_proj = nn.Linear(dim, self.n_heads * self.head_dim, bias=args.attention_bias)
117
+ self.k_proj = nn.Linear(dim, self.n_kv_heads * self.head_dim, bias=args.attention_bias)
118
+ self.v_proj = nn.Linear(dim, self.n_kv_heads * self.head_dim, bias=args.attention_bias)
119
+ self.o_proj = nn.Linear(self.n_heads * self.head_dim, dim, bias=False)
120
+ self.use_qk_norm = args.use_qk_norm
121
+ if self.use_qk_norm:
122
+ self.q_norm = nn.RMSNorm(self.head_dim, eps=args.rms_norm_eps)
123
+ self.k_norm = nn.RMSNorm(self.head_dim, eps=args.rms_norm_eps)
124
+ if self.use_gqa_gate:
125
+ self.g_proj = nn.Linear(dim, self.n_heads * self.head_dim, bias=args.use_gqa_gate_bias)
126
+
127
+ def __call__(
128
+ self,
129
+ x: mx.array,
130
+ mask: Optional[mx.array] = None,
131
+ cache: Optional[Any] = None,
132
+ ) -> mx.array:
133
+ B, L, _ = x.shape
134
+
135
+ queries = self.q_proj(x).reshape(B, L, self.n_heads, self.head_dim).transpose(0, 2, 1, 3)
136
+ keys = self.k_proj(x).reshape(B, L, self.n_kv_heads, self.head_dim).transpose(0, 2, 1, 3)
137
+ values = self.v_proj(x).reshape(B, L, self.n_kv_heads, self.head_dim).transpose(0, 2, 1, 3)
138
+
139
+ if self.use_qk_norm:
140
+ queries = self.q_norm(queries)
141
+ keys = self.k_norm(keys)
142
+
143
+ if cache is not None:
144
+ keys, values = cache.update_and_fetch(keys, values)
145
+
146
+ output = scaled_dot_product_attention(
147
+ queries, keys, values, cache=cache, scale=self.scale, mask=mask
148
+ )
149
+ output = output.transpose(0, 2, 1, 3).reshape(B, L, -1)
150
+ if self.use_gqa_gate:
151
+ output = output * mx.sigmoid(self.g_proj(x))
152
+ return self.o_proj(output)
153
+
154
+
155
+ class SolarOpen2LinearAttention(KimiDeltaAttention):
156
+ def __init__(self, args: ModelArgs, layer_idx: int):
157
+ if args.kda_use_full_proj:
158
+ raise NotImplementedError("Solar Open2 full KDA projections are not supported by this MLX loader.")
159
+ super().__init__(args, layer_idx)
160
+ self.kda_gate_lower_bound = args.kda_gate_lower_bound
161
+ self.kda_allow_neg_eigval = args.kda_allow_neg_eigval
162
+
163
+ def __call__(
164
+ self,
165
+ x: mx.array,
166
+ mask: Optional[mx.array] = None,
167
+ cache: Optional[Any] = None,
168
+ ) -> mx.array:
169
+ B, T, _ = x.shape
170
+ dtype = x.dtype
171
+
172
+ if cache is not None:
173
+ q_state, k_state, v_state, ssm_state = cache
174
+ lengths = cache.lengths
175
+ else:
176
+ q_state = None
177
+ k_state = None
178
+ v_state = None
179
+ ssm_state = None
180
+ lengths = None
181
+
182
+ if q_state is None:
183
+ s = mx.zeros((B, self.conv_kernel - 1, self.projection_dim), dtype=dtype)
184
+ q_state = s
185
+ k_state = s
186
+ v_state = s
187
+
188
+ q_conv, q_state = self.q_conv(self.q_proj(x), q_state, mask, lengths)
189
+ k_conv, k_state = self.k_conv(self.k_proj(x), k_state, mask, lengths)
190
+ v_conv, v_state = self.v_conv(self.v_proj(x), v_state, mask, lengths)
191
+
192
+ if cache is not None:
193
+ cache[0] = q_state
194
+ cache[1] = k_state
195
+ cache[2] = v_state
196
+
197
+ q = q_conv.reshape(B, T, self.num_heads, self.head_dim)
198
+ k = k_conv.reshape(B, T, self.num_heads, self.head_dim)
199
+ v = v_conv.reshape(B, T, self.num_heads, self.head_dim)
200
+
201
+ inv_scale = self.scale
202
+ q = (inv_scale**2) * mx.fast.rms_norm(q, None, 1e-6)
203
+ k = inv_scale * mx.fast.rms_norm(k, None, 1e-6)
204
+
205
+ a_logits = self.f_b_proj(self.f_a_proj(x)).reshape(B, T, self.num_heads, self.head_dim)
206
+ b_logits = self.b_proj(x).reshape(B, T, self.num_heads)
207
+
208
+ out, ssm_state = _solar_gated_delta_update(
209
+ q,
210
+ k,
211
+ v,
212
+ a_logits,
213
+ b_logits,
214
+ self.A_log.reshape(self.num_heads, 1),
215
+ self.dt_bias.reshape(self.num_heads, self.head_dim),
216
+ state=ssm_state,
217
+ mask=mask,
218
+ use_kernel=not self.training,
219
+ lower_bound=self.kda_gate_lower_bound,
220
+ allow_neg_eigval=self.kda_allow_neg_eigval,
221
+ )
222
+
223
+ if cache is not None:
224
+ cache[3] = ssm_state
225
+ cache.advance(T)
226
+
227
+ gate = self.g_b_proj(self.g_a_proj(x)).reshape(B, T, self.num_heads, self.head_dim)
228
+ out = (self.o_norm(out.reshape(B, T, self.num_heads, self.head_dim)) * mx.sigmoid(gate)).reshape(B, T, -1)
229
+ return self.o_proj(out)
230
+
231
+
232
+ class SolarOpen2DecoderLayer(nn.Module):
233
+ def __init__(self, args: ModelArgs, layer_idx: int):
234
+ super().__init__()
235
+ gqa_layers = set(args.gqa_layers or list(range(0, args.num_hidden_layers, args.gqa_interval + 1)))
236
+ self.is_linear = layer_idx not in gqa_layers
237
+ self.self_attn = (
238
+ SolarOpen2LinearAttention(args, layer_idx)
239
+ if self.is_linear
240
+ else SolarOpen2Attention(args)
241
+ )
242
+ self.mlp = (
243
+ MoE(args)
244
+ if args.n_routed_experts is not None and layer_idx >= args.first_k_dense_replace
245
+ else MLP(args)
246
+ )
247
+ self.input_layernorm = nn.RMSNorm(args.hidden_size, eps=args.rms_norm_eps)
248
+ self.post_attention_layernorm = nn.RMSNorm(args.hidden_size, eps=args.rms_norm_eps)
249
+
250
+ def __call__(
251
+ self,
252
+ x: mx.array,
253
+ mask: Optional[mx.array] = None,
254
+ cache: Optional[Any] = None,
255
+ ) -> mx.array:
256
+ h = x + self.self_attn(self.input_layernorm(x), mask=mask, cache=cache)
257
+ return h + self.mlp(self.post_attention_layernorm(h))
258
+
259
+
260
+ class SolarOpen2Model(PipelineMixin, nn.Module):
261
+ def __init__(self, args: ModelArgs):
262
+ super().__init__()
263
+ self.embed_tokens = nn.Embedding(args.vocab_size, args.hidden_size)
264
+ self.layers = [SolarOpen2DecoderLayer(args, i) for i in range(args.num_hidden_layers)]
265
+ self.norm = nn.RMSNorm(args.hidden_size, eps=args.rms_norm_eps)
266
+ self.linear_idx = next((i for i, layer in enumerate(self.layers) if layer.is_linear), 0)
267
+ self.attn_idx = next((i for i, layer in enumerate(self.layers) if not layer.is_linear), 0)
268
+
269
+ def __call__(
270
+ self,
271
+ inputs: mx.array,
272
+ cache: Optional[List[Any]] = None,
273
+ ) -> mx.array:
274
+ h = self.embed_tokens(inputs)
275
+ if cache is None:
276
+ cache = [None] * len(self.layers)
277
+
278
+ ssm_mask = create_ssm_mask(h, cache[self.linear_idx])
279
+ attn_mask = create_attention_mask(h, cache[self.attn_idx], return_array=True)
280
+
281
+ for layer, layer_cache in zip(self.layers, cache):
282
+ mask = ssm_mask if layer.is_linear else attn_mask
283
+ h = layer(h, mask=mask, cache=layer_cache)
284
+
285
+ return self.norm(h)
286
+
287
+
288
+ class Model(nn.Module):
289
+ def __init__(self, args: ModelArgs):
290
+ super().__init__()
291
+ self.args = args
292
+ self.model_type = args.model_type
293
+ self.model = SolarOpen2Model(args)
294
+ if args.tie_word_embeddings:
295
+ self.lm_head = None
296
+ else:
297
+ self.lm_head = nn.Linear(args.hidden_size, args.vocab_size, bias=False)
298
+
299
+ def __call__(
300
+ self,
301
+ inputs: mx.array,
302
+ cache: Optional[List[Any]] = None,
303
+ ) -> mx.array:
304
+ out = self.model(inputs, cache)
305
+ if self.lm_head is None:
306
+ return self.model.embed_tokens.as_linear(out)
307
+ return self.lm_head(out)
308
+
309
+ @property
310
+ def layers(self):
311
+ return self.model.layers
312
+
313
+ def make_cache(self):
314
+ caches: List[Any] = []
315
+ for layer in self.layers:
316
+ caches.append(ArraysCache(size=4) if layer.is_linear else KVCache())
317
+ return caches
318
+
319
+ def sanitize(self, weights: Dict[str, mx.array]) -> Dict[str, mx.array]:
320
+ # Stack per-expert HF tensors into MLX SwitchGLU tensors.
321
+ for layer_idx in range(self.args.num_hidden_layers):
322
+ prefix = f"model.layers.{layer_idx}"
323
+ for dst, src in (("gate_proj", "gate_proj"), ("down_proj", "down_proj"), ("up_proj", "up_proj")):
324
+ for suffix in ("weight", "scales", "biases"):
325
+ first = f"{prefix}.mlp.experts.0.{src}.{suffix}"
326
+ if first in weights:
327
+ weights[f"{prefix}.mlp.switch_mlp.{dst}.{suffix}"] = mx.stack(
328
+ [
329
+ weights.pop(f"{prefix}.mlp.experts.{expert}.{src}.{suffix}")
330
+ for expert in range(self.args.n_routed_experts)
331
+ ]
332
+ )
333
+
334
+ layer = self.layers[layer_idx]
335
+ if layer.is_linear:
336
+ attn_prefix = f"{prefix}.self_attn"
337
+ for src_name, dst_name in (
338
+ ("q_conv1d", "q_conv"),
339
+ ("k_conv1d", "k_conv"),
340
+ ("v_conv1d", "v_conv"),
341
+ ):
342
+ src_key = f"{attn_prefix}.{src_name}.weight"
343
+ if src_key in weights:
344
+ w = weights.pop(src_key)
345
+ if w.ndim == 3:
346
+ w = w.moveaxis(2, 1)
347
+ weights[f"{attn_prefix}.{dst_name}.conv.weight"] = w
348
+ dt_key = f"{attn_prefix}.dt_bias"
349
+ if dt_key in weights and weights[dt_key].ndim > 1:
350
+ weights[dt_key] = mx.reshape(weights[dt_key], (-1,))
351
+
352
+ return weights
353
+
354
+ @property
355
+ def cast_predicate(self):
356
+ def predicate(path: str):
357
+ if "e_score_correction_bias" in path:
358
+ return False
359
+ if path.endswith("A_log") or path.endswith("dt_bias"):
360
+ return False
361
+ return True
362
+
363
+ return predicate
364
+
365
+ @property
366
+ def quant_predicate(self):
367
+ def predicate(path, _):
368
+ if path.endswith("mlp.gate"):
369
+ return {"group_size": 64, "bits": 8}
370
+ return True
371
+
372
+ return predicate
tokenizer.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c7b7cb72447bbe1f8d856adaf34933acfdedfa89c7fe1d95d0fdabedf9d19a94
3
+ size 16473585
tokenizer_config.json ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "backend": "tokenizers",
3
+ "bos_token": "<|startoftext|>",
4
+ "clean_up_tokenization_spaces": false,
5
+ "eos_token": "<|endoftext|>",
6
+ "is_local": true,
7
+ "local_files_only": false,
8
+ "model_max_length": 1048576,
9
+ "pad_token": "<|endoftext|>",
10
+ "padding_side": "left",
11
+ "split_special_tokens": false,
12
+ "tokenizer_class": "TokenizersBackend",
13
+ "unk_token": "<unk>"
14
+ }