Text Generation
MLX
Safetensors
spark2_5
apple-silicon
decision-making
agents
agent-safety
on-device
laplace
conversational
custom_code
Run this model with HF Jobs
Run netprojects/Laplace-1-Vector-MLX-bf16 on Hugging Face's managed compute, monitor its progress, and retrieve the results when it's done.
Paste one of these prompts into your coding agent:
Fine-tune on my dataset
Use HF Jobs to fine-tune https://huggingface.co/netprojects/Laplace-1-Vector-MLX-bf16. Ask me which dataset to train on, then push the fine-tuned model to a new model repo. Run `hf jobs --help` first to learn the CLI.
Run batch inference
Use HF Jobs to run batch inference with https://huggingface.co/netprojects/Laplace-1-Vector-MLX-bf16 on the inputs in a mounted HF Bucket. Ask me which Bucket to use, then write the outputs back to it and keep each input ID. Run `hf jobs --help` first to learn the CLI.
Evaluate on a benchmark
Use HF Jobs to evaluate https://huggingface.co/netprojects/Laplace-1-Vector-MLX-bf16. Ask me which benchmark to run, then save the scores and the per-example results to a new dataset repo. Run `hf jobs --help` first to learn the CLI.
Instructions to use netprojects/Laplace-1-Vector-MLX-bf16 with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- MLX
How to use netprojects/Laplace-1-Vector-MLX-bf16 with MLX:
# Make sure mlx-lm is installed # pip install --upgrade mlx-lm # Generate text with mlx-lm from mlx_lm import load, generate model, tokenizer = load("netprojects/Laplace-1-Vector-MLX-bf16") prompt = "Write a story about Einstein" messages = [{"role": "user", "content": prompt}] prompt = tokenizer.apply_chat_template( messages, add_generation_prompt=True ) text = generate(model, tokenizer, prompt=prompt, verbose=True) - Notebooks
- Google Colab
- Kaggle
- Local Apps Settings
- LM Studio
- Pi
How to use netprojects/Laplace-1-Vector-MLX-bf16 with Pi:
Start the MLX server
# Install MLX LM: uv tool install mlx-lm # Start a local OpenAI-compatible server: mlx_lm.server --model "netprojects/Laplace-1-Vector-MLX-bf16"
Configure the model in Pi
# Install Pi: npm install -g @earendil-works/pi-coding-agent # Add to ~/.pi/agent/models.json: { "providers": { "mlx-lm": { "baseUrl": "http://localhost:8080/v1", "api": "openai-completions", "apiKey": "none", "models": [ { "id": "netprojects/Laplace-1-Vector-MLX-bf16" } ] } } }Run Pi
# Start Pi in your project directory: pi
- MLX LM
How to use netprojects/Laplace-1-Vector-MLX-bf16 with MLX LM:
Generate or start a chat session
# Install MLX LM uv tool install mlx-lm # Interactive chat REPL mlx_lm.chat --model "netprojects/Laplace-1-Vector-MLX-bf16"
Run an OpenAI-compatible server
# Install MLX LM uv tool install mlx-lm # Start the server mlx_lm.server --model "netprojects/Laplace-1-Vector-MLX-bf16" # Calling the OpenAI-compatible server with curl curl -X POST "http://localhost:8080/v1/chat/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "netprojects/Laplace-1-Vector-MLX-bf16", "messages": [ {"role": "user", "content": "Hello"} ] }' - Hermes Agent
How to use netprojects/Laplace-1-Vector-MLX-bf16 with Hermes Agent:
Start the MLX server
# Install MLX LM: uv tool install mlx-lm # Start a local OpenAI-compatible server: mlx_lm.server --model "netprojects/Laplace-1-Vector-MLX-bf16"
Configure Hermes
# Install Hermes: curl -fsSL https://hermes-agent.nousresearch.com/install.sh | bash hermes setup # Point Hermes at the local server: hermes config set model.provider custom hermes config set model.base_url http://127.0.0.1:8080/v1 hermes config set model.default netprojects/Laplace-1-Vector-MLX-bf16
Run Hermes
hermes
- Atomic Chat
- OpenClaw
How to use netprojects/Laplace-1-Vector-MLX-bf16 with OpenClaw:
Start the MLX server
# Install MLX LM: uv tool install mlx-lm # Start a local OpenAI-compatible server: mlx_lm.server --model "netprojects/Laplace-1-Vector-MLX-bf16"
Configure OpenClaw
# Install OpenClaw: npm install -g openclaw@latest # Register the local server and set it as the default model: openclaw onboard --non-interactive --mode local \ --auth-choice custom-api-key \ --custom-base-url http://127.0.0.1:8080/v1 \ --custom-model-id "netprojects/Laplace-1-Vector-MLX-bf16" \ --custom-provider-id mlx-lm \ --custom-compatibility openai \ --custom-text-input \ --accept-risk \ --skip-health
Run OpenClaw
openclaw agent --local --agent main --message "Hello from Hugging Face"
Laplace-1-Vector (06cea7d) MLX bf16: weights, card, Apache-2.0 LICENSE and NOTICE
Browse filesFiles changed (13)
- LICENSEAdded+202
- NOTICEAdded+12
- README.mdAdded+162
- chat_template.jinjaAdded+121
- config.jsonAdded+83
- configuration_spark.pyAdded+118
- generation_config.jsonAdded+12
- model-00001-of-00002.safetensorsAdded+3
- model-00002-of-00002.safetensorsAdded+3
- model.safetensors.index.jsonAdded+298
- modeling_spark.pyAdded+483
- tokenizer.jsonAdded
- tokenizer_config.jsonAdded+15
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202
Apache License Version 2.0, January 2004 http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
"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.
"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
"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.
"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).
"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.
"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."
"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.
2. Grant of Copyright License. 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.
3. Grant of Patent License. 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.
4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
(a) You must give any other recipients of the Work or Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices stating that You changed the files; and
(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
(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.
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.
5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
6. Trademarks. 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 and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache 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.
Copyright 2026 XHToken
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.123456789101112Laplace-1-Vector, MLX conversion
This conversion is derived from JuneoAI/Laplace-1-Vector (revision 06cea7d0d2bf3b26bb111d3ef6077051d4e3f7dc) byJuneo Lab, released under the Apache License, Version 2.0 (see LICENSE). That model is a fine-tune ofXHToken/Spark-X2.6-4B, Copyright XHToken, Apache License 2.0.
Changes made here: the weights were converted to MLX format and, in the quantised builds, the linear layers werequantised (affine, group size 64; the attention output gate g_proj is kept unquantised). No weights were otherwisechanged.
Conversion by NetProjects (Internet Projects Ltd), https://netprojects.com.Not affiliated with Juneo Lab (JuneoAI) or XHToken.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162---license: apache-2.0base_model: JuneoAI/Laplace-1-Vectorpipeline_tag: text-generationlibrary_name: mlxtags: - mlx - apple-silicon - decision-making - agents - agent-safety - on-device - laplace---
# Laplace-1-Vector for Apple Silicon (MLX, bf16)
An MLX conversion of [JuneoAI/Laplace-1-Vector](https://huggingface.co/JuneoAI/Laplace-1-Vector) (revision `06cea7d`),Juneo Lab's 4B decision model built on Spark-X2.6-4B. Hand it a state, a question and a set of candidates, and itreturns a probability for each candidate from one forward pass: who should own a task, who may see what, whether toact or ask first, whether a result meets the standard. It can also predict the next state of an environment youdescribe. At 4B parameters it runs comfortably on a Mac, next to the agent, so the data stays on your machine.This build keeps the full bf16 weights (the reference for the other builds). Size: 8.2 GB.
Published by [NetProjects](https://netprojects.com) (Internet Projects Ltd). Not affiliated with Juneo Lab or XHToken.
| Build | Size | JevBench (231 public items) | Same top answer as bf16 ||---|---|---|---|| [netprojects/Laplace-1-Vector-MLX-6bit](https://huggingface.co/netprojects/Laplace-1-Vector-MLX-6bit) (recommended) | 3.3 GB | 79.2% | 222 / 231 || [netprojects/Laplace-1-Vector-MLX-8bit](https://huggingface.co/netprojects/Laplace-1-Vector-MLX-8bit) | 4.4 GB | 79.7% | 229 / 231 || [netprojects/Laplace-1-Vector-MLX-4bit](https://huggingface.co/netprojects/Laplace-1-Vector-MLX-4bit) | 2.3 GB | 78.4% | 210 / 231 || [netprojects/Laplace-1-Vector-MLX-bf16](https://huggingface.co/netprojects/Laplace-1-Vector-MLX-bf16) | 8.2 GB | 78.8% | reference |
For scoring and ranking work, use the 6-bit (recommended) or 8-bit build: both track bf16 closely. The 4-bit build isthe smallest option; its accuracy holds, but it changes the top answer on about 9% of JevBench items compared with bf16.
## Score candidates
A decision is one forward pass: the model reads the candidates as letters and the next-token logits of those lettersgive the distribution. This is Juneo's `score_candidates` helper, ported to mlx-lm with the same prompt.
```bashpip install -U "mlx-lm>=0.32"```
```pythonimport json, stringimport mlx.core as mxfrom mlx_lm import load
model, tokenizer = load("netprojects/Laplace-1-Vector-MLX-bf16")SYSTEM = ("Choose the supported answer from the supplied candidates. Output only its letter.\n" "Return exactly one supplied candidate label.")
def score_candidates(state, question, choices): """choices maps your own keys to candidate descriptions (up to 26).""" keys, letters, ids = list(choices), [], [] for name in string.ascii_uppercase: t = tokenizer.encode(name, add_special_tokens=False) if len(t) == 1 and t[0] not in ids: letters.append(name); ids.append(t[0]) if len(letters) == len(keys): break payload = {"state": state, "question": question, "candidates": [{"letter": l, "description": choices[k]} for l, k in zip(letters, keys)]} messages = [{"role": "system", "content": SYSTEM}, {"role": "user", "content": json.dumps(payload, ensure_ascii=False)}] prompt = tokenizer.apply_chat_template(messages, add_generation_prompt=True, enable_thinking=False, tokenize=False) tokens = mx.array(tokenizer.encode(prompt, add_special_tokens=False))[None] logits = model(tokens)[0, -1].astype(mx.float32) probs = mx.softmax(logits[mx.array(ids)]).tolist() best = max(range(len(keys)), key=probs.__getitem__) return {"choice": keys[best], "probabilities": dict(zip(keys, probs))}
print(score_candidates( state={"permissions": ["read_records"], "request": "Delete a record."}, question="Which decision is supported by the supplied permissions?", choices={"allow": "Allow the request.", "deny": "Deny the request."},))```
The probabilities are relative to the candidates you supply, not a calibrated chance of being correct. Put the rulesthat govern the decision in the state, and include a hand-back or request-more-information option when the stakes callfor one.
## Predict the next observation
For outcome prediction, give the environment rules as the system message and the state and action as JSON, withthinking off:
```bashmlx_lm.generate --model netprojects/Laplace-1-Vector-MLX-bf16 --max-tokens 256 \ --chat-template-config '{"enable_thinking": false}' \ --system-prompt 'Predict the next environment observation after the supplied action. Return only JSON.' \ --prompt '{"state": {"owner": "operator", "open": true}, "history": [], "action": {"kind": "resolve"}}'```
Or from Python:
```pythonfrom mlx_lm import load, generate
model, tokenizer = load("netprojects/Laplace-1-Vector-MLX-bf16")messages = [{"role": "user", "content": "In one sentence, when should an agent hand a decision back to a person?"}]prompt = tokenizer.apply_chat_template(messages, add_generation_prompt=True, enable_thinking=False, tokenize=False)print(generate(model, tokenizer, prompt=prompt, max_tokens=200))```
`mlx_lm.server` serves the model with an OpenAI-compatible API. mlx-lm 0.32 and newer support this architecture(`spark2_5`) natively, so no `trust_remote_code` is needed; Python 3.11 or newer. Tested with mlx 0.32.4 andmlx-lm 0.32.2.
## What was checked
On a MacBook Pro M5 Max (128 GB), 16 November 2026.
- **Parity with the original model.** Each build was compared with Juneo's own model code running in float32 on CPU (Transformers 4.57.1) on 11 prompts, including one of 3,313 tokens. Teacher-forced, the builds pick the same next token as the original on 99.6% (bf16), 98.9% (8-bit), 98.1% (6-bit) and 90.4% (4-bit) of 753 positions; cached decoding agrees with the full forward pass in every build. On 16 candidate-scoring cases, every build picks the same candidate as the original.- **JevBench.** The 231 public items of [JevBench](https://github.com/fstandhartinger/jevbench) (easy, original and hard tiers; MIT). Each item is one candidate-scoring pass with thinking off, using the system prompt above; the highest-probability candidate is compared with the expected answer:
| Build | Accuracy | easy | original | hard | Same top answer as bf16 | |---|---|---|---|---|---| | bf16 | 78.8% | 48 / 48 | 68 / 72 | 66 / 111 | reference | | 8-bit | 79.7% | 48 / 48 | 69 / 72 | 67 / 111 | 229 / 231 | | 6-bit | 79.2% | 48 / 48 | 69 / 72 | 66 / 111 | 222 / 231 | | 4-bit | 78.4% | 48 / 48 | 67 / 72 | 66 / 111 | 210 / 231 |
These figures come from our own candidate-scoring harness and are not directly comparable with the JevBench score in Juneo's model card, which uses Juneo's evaluation setup.- **Source files.** All weight files of the upstream revision match the Hub's SHA-256 hashes.
## Intended use
Laplace advises; your system decides. As Juneo's card says, keep deterministic permission checks, authentication andaudit logging in place, calibrate thresholds on your own held-out decisions before automating on them, and keep aperson on the final decision for irreversible, safety-critical, financial, medical or legal actions. See the[original model card](https://huggingface.co/JuneoAI/Laplace-1-Vector) for the training data (Decision Forge), thefull evaluation and the limitations.
## License
Apache-2.0, as the original model and Spark-X2.6-4B. `LICENSE` is the Apache-2.0 text from the upstream repository and`NOTICE` describes the conversion and credits Juneo Lab and XHToken. If you use the model, please cite Juneo Lab:
```bibtex@misc{juneo2026laplace1, title = {Laplace-1: Causal-Interventional Decision Models for Trustworthy Agent Delegation}, author = {{Juneo Lab}}, year = {2026}, howpublished = {\url{https://huggingface.co/JuneoAI/Laplace-1-Vector}}, note = {Model family: Laplace-1-Atlas (27B), Laplace-1-Vector (4B)}}```
More MLX builds from NetProjects: [huggingface.co/netprojects](https://huggingface.co/netprojects) ·[netprojects.com](https://netprojects.com)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121{%- if not messages %} {{- raise_exception('No messages provided.') }}{%- endif %}{%- set enable_thinking = enable_thinking | default(true) %}{%- set reasoning_instructions = '' %}{%- if enable_thinking is true %} {%- set resolved_reasoning_effort = reasoning_effort|default('high') %} {%- if resolved_reasoning_effort not in ('high', 'low') %} {{- raise_exception('Unexpected reasoning effort ' ~ reasoning_effort ~ '. Supported types are high (default) and low.') }} {%- endif %} {%- if resolved_reasoning_effort == 'high' %} {%- set reasoning_instructions = '\n`thinking_effort` guides on how much to think in your thinking channel (not including the response channel), supported values include `low` and `high`.\nNow the system is invoked with `thinking_effort=high`.' %} {%- elif resolved_reasoning_effort == 'low' %} {%- set reasoning_instructions = '\n`thinking_effort` guides on how much to think in your thinking channel (not including the response channel), supported values include `low` and `high`.\nNow the system is invoked with `thinking_effort=low`.' %} {%- endif %}{%- endif %}
{#- Render a string or a list of text blocks. -#}{%- macro render_content(content, context_name) %} {%- if content is string %} {{- content }} {%- elif content is none or content is undefined %} {{- '' }} {%- elif content is iterable and content is not mapping %} {%- for block in content %} {%- if block.type == 'text' %} {{- block.text }} {%- else %} {{- raise_exception('Unsupported ' ~ context_name ~ ' content block type: ' ~ (block.type | string)) }} {%- endif %} {%- endfor %} {%- else %} {{- raise_exception(context_name ~ ' content must be a string or a list of text blocks') }} {%- endif %}{%- endmacro %}
{#- Default system prompt -#}{%- set default_system = "you are a helpful assistant." + reasoning_instructions %}
{#- The first message-level system is placed in the initial system block. -#}{%- set ns = namespace(initial_system='') %}{%- if messages[0].role == "system" %} {%- set ns.initial_system = render_content(messages[0].content, 'system') %}{%- endif %}
{#- System block -#}{{- '<|start▁of▁sentence|><|System|>' + '\n' + default_system }}{%- if tools %} {{- '\n\n' + '## Tools' + '\n' + 'You have access to the following functions:' + '\n' + '<tools>' }} {%- for tool in tools %} {{- '\n' + (tool.function | tojson(separators=(',', ':'))) }} {%- endfor %} {{- '\n' + '</tools>' }}{%- endif %}{%- if ns.initial_system %} {{- '\n\n' + ns.initial_system }}{%- endif %}{{- '<|end▁of▁sentence|>'}}
{#- Conversation turns -#}{%- for message in messages %} {%- if message.role == "system" %} {#- The first system message was consumed by the initial block. -#} {%- if not loop.first %} {{- '<|start▁of▁sentence|><|System|>\n' + render_content(message.content, 'system') + '<|end▁of▁sentence|>' }} {%- endif %} {%- elif message.role == "user" %} {{- '<|start▁of▁sentence|><|User|>' + render_content(message.content, 'user') + '<|end▁of▁sentence|>' }} {%- elif message.role == "assistant" %} {%- set assistant_content = render_content(message.content, 'assistant') %} {%- if message.reasoning_content is defined and message.reasoning_content %} {%- set reasoning_content = message.reasoning_content %} {%- else %} {%- set reasoning_content = '' %} {%- endif %} {{- '<|start▁of▁sentence|><|Bot|>'}} {%- if reasoning_content %} {{- '<think>' + reasoning_content + '</think>'}} {%- else %} {{- '</think>' }} {%- endif %} {%- if assistant_content %} {{- assistant_content }} {%- endif %} {%- if message.tool_calls is defined and message.tool_calls is not none %} {%- for tool_call in message.tool_calls %} {%- if tool_call.function.arguments is not mapping %} {{- raise_exception('tool_call.function.arguments must be a dictionary; normalize JSON strings before apply_chat_template') }} {%- endif %} {%- set args = tool_call.function.arguments %} {{- '<tool_call>' + tool_call.function.name }} {%- for k, v in args.items() %} {{- '<arg_key>' ~ k ~ '</arg_key><arg_value>' ~ (v if v is string else v | tojson(separators=(', ', ': '))) ~ '</arg_value>' }} {%- endfor %} {{- '</tool_call>' }} {%- endfor %} {%- endif %} {{- '<|end▁of▁sentence|>' }} {%- elif message.role == "tool" %} {%- if loop.previtem is undefined or loop.previtem.role != "tool" %} {{- '<|start▁of▁sentence|><|Tool|>' }} {%- endif %} {{- '<tool_response>' ~ message.content ~ '</tool_response>' }} {%- if loop.nextitem is undefined or loop.nextitem.role != "tool" %} {{- '<|end▁of▁sentence|>' }} {%- endif %} {%- else %} {{- raise_exception('Unsupported message role: ' ~ message.role) }} {%- endif %}{%- endfor %}
{#- Generation prompt -#}{%- if add_generation_prompt %} {{- '<|start▁of▁sentence|><|Bot|>' }} {%- if enable_thinking is defined and enable_thinking %} {{- '<think>' }} {%- endif %} {%- if enable_thinking is defined and not enable_thinking %} {{- '</think>' }} {%- endif %}{%- endif %}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283{ "architectures": [ "Spark2_5ForCausalLM" ], "attention_bias": false, "attention_dropout": 0.0, "auto_map": { "AutoConfig": "configuration_spark.Spark2_5Config", "AutoModel": "modeling_spark.Spark2_5Model", "AutoModelForCausalLM": "modeling_spark.Spark2_5ForCausalLM" }, "bos_token_id": 0, "dtype": "bfloat16", "eos_token_id": 1, "gate_attn_act_mode": "sigmoid", "head_dim": 256, "headwise_attn_output_gate": true, "hidden_act": "gelu", "hidden_size": 2560, "initializer_range": 0.01976, "intermediate_size": 10240, "layer_types": [ "sliding_attention", "sliding_attention", "sliding_attention", "full_attention", "sliding_attention", "sliding_attention", "sliding_attention", "full_attention", "sliding_attention", "sliding_attention", "sliding_attention", "full_attention", "sliding_attention", "sliding_attention", "sliding_attention", "full_attention", "sliding_attention", "sliding_attention", "sliding_attention", "full_attention", "sliding_attention", "sliding_attention", "sliding_attention", "full_attention", "sliding_attention", "sliding_attention", "sliding_attention", "full_attention", "sliding_attention", "sliding_attention", "sliding_attention", "full_attention", "sliding_attention", "sliding_attention", "sliding_attention", "full_attention" ], "max_position_embeddings": 1048576, "mlp_bias": false, "model_type": "spark2_5", "num_attention_heads": 16, "num_hidden_layers": 36, "num_key_value_heads": 4, "pad_token_id": 2, "rms_norm_eps": 1e-06, "rope_parameters": { "full_attention": { "partial_rotary_factor": 0.25, "rope_theta": 5000000 }, "sliding_attention": { "partial_rotary_factor": 1.0, "rope_theta": 10000 } }, "sliding_window": 512, "tie_word_embeddings": true, "transformers_version": "4.57.1", "use_cache": true, "vocab_size": 131072}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118# coding=utf-8# Copyright 2026 The XHToken team and the HuggingFace Inc. team. All rights reserved.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.
from transformers import PretrainedConfig
class Spark2_5Config(PretrainedConfig): model_type = "spark2_5" keys_to_ignore_at_inference = ["past_key_values"]
base_model_tp_plan = { "layers.*.self_attn.q_k_v_proj": "colwise", "layers.*.self_attn.g_proj": "colwise", "layers.*.self_attn.out_proj": "rowwise", "layers.*.mlp.gate_proj": "colwise", "layers.*.mlp.up_proj": "colwise", "layers.*.mlp.down_proj": "rowwise", } base_model_pp_plan = { "embedding": (["input_ids"], ["inputs_embeds"]), "layers": (["hidden_states", "attention_mask"], ["hidden_states"]), "norm": (["hidden_states"], ["hidden_states"]), }
def __init__( self, vocab_size=32000, hidden_size=4096, intermediate_size=11008, num_hidden_layers=32, num_attention_heads=32, num_key_value_heads=None, hidden_act="gelu", max_position_embeddings=2048, initializer_range=0.02, rms_norm_eps=1e-6, use_cache=True, pad_token_id=None, bos_token_id=1, eos_token_id=2, tie_word_embeddings=False, rope_parameters=None, attention_bias=False, attention_dropout=0.0, mlp_bias=False, head_dim=None, headwise_attn_output_gate=False, gate_attn_act_mode="sigmoid", sliding_window=None, layer_types=None, **kwargs, ): self.vocab_size = vocab_size self.max_position_embeddings = max_position_embeddings self.hidden_size = hidden_size self.intermediate_size = intermediate_size self.num_hidden_layers = num_hidden_layers self.num_attention_heads = num_attention_heads
if num_key_value_heads is None: num_key_value_heads = num_attention_heads if num_attention_heads % num_key_value_heads != 0: raise ValueError( f"num_attention_heads ({num_attention_heads}) must be divisible by num_key_value_heads ({num_key_value_heads})" ) self.num_key_value_heads = num_key_value_heads
self.hidden_act = hidden_act self.initializer_range = initializer_range self.rms_norm_eps = rms_norm_eps self.use_cache = use_cache self.attention_bias = attention_bias self.attention_dropout = attention_dropout self.mlp_bias = mlp_bias self.head_dim = head_dim if head_dim is not None else self.hidden_size // self.num_attention_heads self.headwise_attn_output_gate = headwise_attn_output_gate self.gate_attn_act_mode = gate_attn_act_mode self.sliding_window = sliding_window self.rope_parameters = rope_parameters
if layer_types is None: layer_types = ["full_attention"] * num_hidden_layers if len(layer_types) != num_hidden_layers: raise ValueError( f"layer_types length ({len(layer_types)}) must match num_hidden_layers ({num_hidden_layers})" ) self.layer_types = layer_types
super().__init__( pad_token_id=pad_token_id, bos_token_id=bos_token_id, eos_token_id=eos_token_id, tie_word_embeddings=tie_word_embeddings, **kwargs, )
def get_rope_theta(self, layer_type): params = self.rope_parameters.get(layer_type, {}) return params.get("rope_theta", 10000)
def get_partial_rotary_factor(self, layer_type): params = self.rope_parameters.get(layer_type, {}) return params.get("partial_rotary_factor", 1.0)
__all__ = ["Spark2_5Config"]123456789101112{ "bos_token_id": 0, "do_sample": true, "eos_token_id": 1, "frequency_penalty": 0, "max_tokens": 1048576, "pad_token_id": 2, "presence_penalty": 0, "top_k": -1, "top_p": 0.95, "transformers_version": "4.57.1"}123version https://git-lfs.github.com/spec/v1oid sha256:47ec1a88cae0e73add4c226ea8652feed8b473d90b780a402a9d9427b42915d1size 5339382235123version https://git-lfs.github.com/spec/v1oid sha256:c8f476839220cb0432c797cfcfdc37676d008b03fc1eefa72d0de25dea6807absize 2884810243123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298{ "metadata": { "total_size": 8224158720, "total_parameters": 4112079360 }, "weight_map": { "model.embedding.weight": "model-00001-of-00002.safetensors", "model.layers.0.input_layernorm.weight": "model-00001-of-00002.safetensors", "model.layers.0.mlp.down_proj.weight": "model-00001-of-00002.safetensors", "model.layers.0.mlp.gate_proj.weight": "model-00001-of-00002.safetensors", "model.layers.0.mlp.up_proj.weight": "model-00001-of-00002.safetensors", "model.layers.0.post_attention_layernorm.weight": "model-00001-of-00002.safetensors", "model.layers.0.self_attn.g_proj.weight": "model-00001-of-00002.safetensors", "model.layers.0.self_attn.out_proj.weight": "model-00001-of-00002.safetensors", "model.layers.0.self_attn.q_k_v_proj.weight": "model-00001-of-00002.safetensors", "model.layers.1.input_layernorm.weight": "model-00001-of-00002.safetensors", "model.layers.1.mlp.down_proj.weight": "model-00001-of-00002.safetensors", "model.layers.1.mlp.gate_proj.weight": "model-00001-of-00002.safetensors", "model.layers.1.mlp.up_proj.weight": "model-00001-of-00002.safetensors", "model.layers.1.post_attention_layernorm.weight": "model-00001-of-00002.safetensors", "model.layers.1.self_attn.g_proj.weight": "model-00001-of-00002.safetensors", "model.layers.1.self_attn.out_proj.weight": "model-00001-of-00002.safetensors", "model.layers.1.self_attn.q_k_v_proj.weight": "model-00001-of-00002.safetensors", "model.layers.10.input_layernorm.weight": "model-00001-of-00002.safetensors", "model.layers.10.mlp.down_proj.weight": "model-00001-of-00002.safetensors", "model.layers.10.mlp.gate_proj.weight": "model-00001-of-00002.safetensors", "model.layers.10.mlp.up_proj.weight": "model-00001-of-00002.safetensors", "model.layers.10.post_attention_layernorm.weight": "model-00001-of-00002.safetensors", "model.layers.10.self_attn.g_proj.weight": "model-00001-of-00002.safetensors", "model.layers.10.self_attn.out_proj.weight": "model-00001-of-00002.safetensors", "model.layers.10.self_attn.q_k_v_proj.weight": "model-00001-of-00002.safetensors", "model.layers.11.input_layernorm.weight": "model-00001-of-00002.safetensors", "model.layers.11.mlp.down_proj.weight": "model-00001-of-00002.safetensors", "model.layers.11.mlp.gate_proj.weight": "model-00001-of-00002.safetensors", "model.layers.11.mlp.up_proj.weight": "model-00001-of-00002.safetensors", "model.layers.11.post_attention_layernorm.weight": "model-00001-of-00002.safetensors", "model.layers.11.self_attn.g_proj.weight": "model-00001-of-00002.safetensors", "model.layers.11.self_attn.out_proj.weight": "model-00001-of-00002.safetensors", "model.layers.11.self_attn.q_k_v_proj.weight": "model-00001-of-00002.safetensors", "model.layers.12.input_layernorm.weight": "model-00001-of-00002.safetensors", "model.layers.12.mlp.down_proj.weight": "model-00001-of-00002.safetensors", "model.layers.12.mlp.gate_proj.weight": "model-00001-of-00002.safetensors", "model.layers.12.mlp.up_proj.weight": "model-00001-of-00002.safetensors", "model.layers.12.post_attention_layernorm.weight": "model-00001-of-00002.safetensors", "model.layers.12.self_attn.g_proj.weight": "model-00001-of-00002.safetensors", "model.layers.12.self_attn.out_proj.weight": "model-00001-of-00002.safetensors", "model.layers.12.self_attn.q_k_v_proj.weight": "model-00001-of-00002.safetensors", "model.layers.13.input_layernorm.weight": "model-00001-of-00002.safetensors", "model.layers.13.mlp.down_proj.weight": "model-00001-of-00002.safetensors", "model.layers.13.mlp.gate_proj.weight": "model-00001-of-00002.safetensors", "model.layers.13.mlp.up_proj.weight": "model-00001-of-00002.safetensors", "model.layers.13.post_attention_layernorm.weight": "model-00001-of-00002.safetensors", "model.layers.13.self_attn.g_proj.weight": "model-00001-of-00002.safetensors", "model.layers.13.self_attn.out_proj.weight": "model-00001-of-00002.safetensors", "model.layers.13.self_attn.q_k_v_proj.weight": "model-00001-of-00002.safetensors", "model.layers.14.input_layernorm.weight": "model-00001-of-00002.safetensors", "model.layers.14.mlp.down_proj.weight": "model-00001-of-00002.safetensors", "model.layers.14.mlp.gate_proj.weight": "model-00001-of-00002.safetensors", "model.layers.14.mlp.up_proj.weight": "model-00001-of-00002.safetensors", "model.layers.14.post_attention_layernorm.weight": "model-00001-of-00002.safetensors", "model.layers.14.self_attn.g_proj.weight": "model-00001-of-00002.safetensors", "model.layers.14.self_attn.out_proj.weight": "model-00001-of-00002.safetensors", "model.layers.14.self_attn.q_k_v_proj.weight": "model-00001-of-00002.safetensors", "model.layers.15.input_layernorm.weight": "model-00001-of-00002.safetensors", "model.layers.15.mlp.down_proj.weight": "model-00001-of-00002.safetensors", "model.layers.15.mlp.gate_proj.weight": "model-00001-of-00002.safetensors", "model.layers.15.mlp.up_proj.weight": "model-00001-of-00002.safetensors", "model.layers.15.post_attention_layernorm.weight": "model-00001-of-00002.safetensors", "model.layers.15.self_attn.g_proj.weight": "model-00001-of-00002.safetensors", "model.layers.15.self_attn.out_proj.weight": "model-00001-of-00002.safetensors", "model.layers.15.self_attn.q_k_v_proj.weight": "model-00001-of-00002.safetensors", "model.layers.16.input_layernorm.weight": "model-00001-of-00002.safetensors", "model.layers.16.mlp.down_proj.weight": "model-00001-of-00002.safetensors", "model.layers.16.mlp.gate_proj.weight": "model-00001-of-00002.safetensors", "model.layers.16.mlp.up_proj.weight": "model-00001-of-00002.safetensors", "model.layers.16.post_attention_layernorm.weight": "model-00001-of-00002.safetensors", "model.layers.16.self_attn.g_proj.weight": "model-00001-of-00002.safetensors", "model.layers.16.self_attn.out_proj.weight": "model-00001-of-00002.safetensors", "model.layers.16.self_attn.q_k_v_proj.weight": "model-00001-of-00002.safetensors", "model.layers.17.input_layernorm.weight": "model-00001-of-00002.safetensors", "model.layers.17.mlp.down_proj.weight": "model-00001-of-00002.safetensors", "model.layers.17.mlp.gate_proj.weight": "model-00001-of-00002.safetensors", "model.layers.17.mlp.up_proj.weight": "model-00001-of-00002.safetensors", "model.layers.17.post_attention_layernorm.weight": "model-00001-of-00002.safetensors", "model.layers.17.self_attn.g_proj.weight": "model-00001-of-00002.safetensors", "model.layers.17.self_attn.out_proj.weight": "model-00001-of-00002.safetensors", "model.layers.17.self_attn.q_k_v_proj.weight": "model-00001-of-00002.safetensors", "model.layers.18.input_layernorm.weight": "model-00001-of-00002.safetensors", "model.layers.18.mlp.down_proj.weight": "model-00001-of-00002.safetensors", "model.layers.18.mlp.gate_proj.weight": "model-00001-of-00002.safetensors", "model.layers.18.mlp.up_proj.weight": "model-00001-of-00002.safetensors", "model.layers.18.post_attention_layernorm.weight": "model-00001-of-00002.safetensors", "model.layers.18.self_attn.g_proj.weight": "model-00001-of-00002.safetensors", "model.layers.18.self_attn.out_proj.weight": "model-00001-of-00002.safetensors", "model.layers.18.self_attn.q_k_v_proj.weight": "model-00001-of-00002.safetensors", "model.layers.19.input_layernorm.weight": "model-00001-of-00002.safetensors", "model.layers.19.mlp.down_proj.weight": "model-00001-of-00002.safetensors", "model.layers.19.mlp.gate_proj.weight": "model-00001-of-00002.safetensors", "model.layers.19.mlp.up_proj.weight": "model-00001-of-00002.safetensors", "model.layers.19.post_attention_layernorm.weight": "model-00001-of-00002.safetensors", "model.layers.19.self_attn.g_proj.weight": "model-00001-of-00002.safetensors", "model.layers.19.self_attn.out_proj.weight": "model-00001-of-00002.safetensors", "model.layers.19.self_attn.q_k_v_proj.weight": "model-00001-of-00002.safetensors", "model.layers.2.input_layernorm.weight": "model-00001-of-00002.safetensors", "model.layers.2.mlp.down_proj.weight": "model-00001-of-00002.safetensors", "model.layers.2.mlp.gate_proj.weight": "model-00001-of-00002.safetensors", "model.layers.2.mlp.up_proj.weight": "model-00001-of-00002.safetensors", "model.layers.2.post_attention_layernorm.weight": "model-00001-of-00002.safetensors", "model.layers.2.self_attn.g_proj.weight": "model-00001-of-00002.safetensors", "model.layers.2.self_attn.out_proj.weight": "model-00001-of-00002.safetensors", "model.layers.2.self_attn.q_k_v_proj.weight": "model-00001-of-00002.safetensors", "model.layers.20.input_layernorm.weight": "model-00001-of-00002.safetensors", "model.layers.20.mlp.down_proj.weight": "model-00001-of-00002.safetensors", "model.layers.20.mlp.gate_proj.weight": "model-00001-of-00002.safetensors", "model.layers.20.mlp.up_proj.weight": "model-00001-of-00002.safetensors", "model.layers.20.post_attention_layernorm.weight": "model-00001-of-00002.safetensors", "model.layers.20.self_attn.g_proj.weight": "model-00001-of-00002.safetensors", "model.layers.20.self_attn.out_proj.weight": "model-00001-of-00002.safetensors", "model.layers.20.self_attn.q_k_v_proj.weight": "model-00001-of-00002.safetensors", "model.layers.21.input_layernorm.weight": "model-00001-of-00002.safetensors", "model.layers.21.mlp.down_proj.weight": "model-00001-of-00002.safetensors", "model.layers.21.mlp.gate_proj.weight": "model-00001-of-00002.safetensors", "model.layers.21.mlp.up_proj.weight": "model-00001-of-00002.safetensors", "model.layers.21.post_attention_layernorm.weight": "model-00001-of-00002.safetensors", "model.layers.21.self_attn.g_proj.weight": "model-00001-of-00002.safetensors", "model.layers.21.self_attn.out_proj.weight": "model-00001-of-00002.safetensors", "model.layers.21.self_attn.q_k_v_proj.weight": "model-00001-of-00002.safetensors", "model.layers.22.input_layernorm.weight": "model-00002-of-00002.safetensors", "model.layers.22.mlp.down_proj.weight": "model-00002-of-00002.safetensors", "model.layers.22.mlp.gate_proj.weight": "model-00002-of-00002.safetensors", "model.layers.22.mlp.up_proj.weight": "model-00002-of-00002.safetensors", "model.layers.22.post_attention_layernorm.weight": "model-00002-of-00002.safetensors", "model.layers.22.self_attn.g_proj.weight": "model-00001-of-00002.safetensors", "model.layers.22.self_attn.out_proj.weight": "model-00001-of-00002.safetensors", "model.layers.22.self_attn.q_k_v_proj.weight": "model-00001-of-00002.safetensors", "model.layers.23.input_layernorm.weight": "model-00002-of-00002.safetensors", "model.layers.23.mlp.down_proj.weight": "model-00002-of-00002.safetensors", "model.layers.23.mlp.gate_proj.weight": "model-00002-of-00002.safetensors", "model.layers.23.mlp.up_proj.weight": "model-00002-of-00002.safetensors", "model.layers.23.post_attention_layernorm.weight": "model-00002-of-00002.safetensors", "model.layers.23.self_attn.g_proj.weight": "model-00002-of-00002.safetensors", "model.layers.23.self_attn.out_proj.weight": "model-00002-of-00002.safetensors", "model.layers.23.self_attn.q_k_v_proj.weight": "model-00002-of-00002.safetensors", "model.layers.24.input_layernorm.weight": "model-00002-of-00002.safetensors", "model.layers.24.mlp.down_proj.weight": "model-00002-of-00002.safetensors", "model.layers.24.mlp.gate_proj.weight": "model-00002-of-00002.safetensors", "model.layers.24.mlp.up_proj.weight": "model-00002-of-00002.safetensors", "model.layers.24.post_attention_layernorm.weight": "model-00002-of-00002.safetensors", "model.layers.24.self_attn.g_proj.weight": "model-00002-of-00002.safetensors", "model.layers.24.self_attn.out_proj.weight": "model-00002-of-00002.safetensors", "model.layers.24.self_attn.q_k_v_proj.weight": "model-00002-of-00002.safetensors", "model.layers.25.input_layernorm.weight": "model-00002-of-00002.safetensors", "model.layers.25.mlp.down_proj.weight": "model-00002-of-00002.safetensors", "model.layers.25.mlp.gate_proj.weight": "model-00002-of-00002.safetensors", "model.layers.25.mlp.up_proj.weight": "model-00002-of-00002.safetensors", "model.layers.25.post_attention_layernorm.weight": "model-00002-of-00002.safetensors", "model.layers.25.self_attn.g_proj.weight": "model-00002-of-00002.safetensors", "model.layers.25.self_attn.out_proj.weight": "model-00002-of-00002.safetensors", "model.layers.25.self_attn.q_k_v_proj.weight": "model-00002-of-00002.safetensors", "model.layers.26.input_layernorm.weight": "model-00002-of-00002.safetensors", "model.layers.26.mlp.down_proj.weight": "model-00002-of-00002.safetensors", "model.layers.26.mlp.gate_proj.weight": "model-00002-of-00002.safetensors", "model.layers.26.mlp.up_proj.weight": "model-00002-of-00002.safetensors", "model.layers.26.post_attention_layernorm.weight": "model-00002-of-00002.safetensors", "model.layers.26.self_attn.g_proj.weight": "model-00002-of-00002.safetensors", "model.layers.26.self_attn.out_proj.weight": "model-00002-of-00002.safetensors", "model.layers.26.self_attn.q_k_v_proj.weight": "model-00002-of-00002.safetensors", "model.layers.27.input_layernorm.weight": "model-00002-of-00002.safetensors", "model.layers.27.mlp.down_proj.weight": "model-00002-of-00002.safetensors", "model.layers.27.mlp.gate_proj.weight": "model-00002-of-00002.safetensors", "model.layers.27.mlp.up_proj.weight": "model-00002-of-00002.safetensors", "model.layers.27.post_attention_layernorm.weight": "model-00002-of-00002.safetensors", "model.layers.27.self_attn.g_proj.weight": "model-00002-of-00002.safetensors", "model.layers.27.self_attn.out_proj.weight": "model-00002-of-00002.safetensors", "model.layers.27.self_attn.q_k_v_proj.weight": "model-00002-of-00002.safetensors", "model.layers.28.input_layernorm.weight": "model-00002-of-00002.safetensors", "model.layers.28.mlp.down_proj.weight": "model-00002-of-00002.safetensors", "model.layers.28.mlp.gate_proj.weight": "model-00002-of-00002.safetensors", "model.layers.28.mlp.up_proj.weight": "model-00002-of-00002.safetensors", "model.layers.28.post_attention_layernorm.weight": "model-00002-of-00002.safetensors", "model.layers.28.self_attn.g_proj.weight": "model-00002-of-00002.safetensors", "model.layers.28.self_attn.out_proj.weight": "model-00002-of-00002.safetensors", "model.layers.28.self_attn.q_k_v_proj.weight": "model-00002-of-00002.safetensors", "model.layers.29.input_layernorm.weight": "model-00002-of-00002.safetensors", "model.layers.29.mlp.down_proj.weight": "model-00002-of-00002.safetensors", "model.layers.29.mlp.gate_proj.weight": "model-00002-of-00002.safetensors", "model.layers.29.mlp.up_proj.weight": "model-00002-of-00002.safetensors", "model.layers.29.post_attention_layernorm.weight": "model-00002-of-00002.safetensors", "model.layers.29.self_attn.g_proj.weight": "model-00002-of-00002.safetensors", "model.layers.29.self_attn.out_proj.weight": "model-00002-of-00002.safetensors", "model.layers.29.self_attn.q_k_v_proj.weight": "model-00002-of-00002.safetensors", "model.layers.3.input_layernorm.weight": "model-00001-of-00002.safetensors", "model.layers.3.mlp.down_proj.weight": "model-00001-of-00002.safetensors", "model.layers.3.mlp.gate_proj.weight": "model-00001-of-00002.safetensors", "model.layers.3.mlp.up_proj.weight": "model-00001-of-00002.safetensors", "model.layers.3.post_attention_layernorm.weight": "model-00001-of-00002.safetensors", "model.layers.3.self_attn.g_proj.weight": "model-00001-of-00002.safetensors", "model.layers.3.self_attn.out_proj.weight": "model-00001-of-00002.safetensors", "model.layers.3.self_attn.q_k_v_proj.weight": "model-00001-of-00002.safetensors", "model.layers.30.input_layernorm.weight": "model-00002-of-00002.safetensors", "model.layers.30.mlp.down_proj.weight": "model-00002-of-00002.safetensors", "model.layers.30.mlp.gate_proj.weight": "model-00002-of-00002.safetensors", "model.layers.30.mlp.up_proj.weight": "model-00002-of-00002.safetensors", "model.layers.30.post_attention_layernorm.weight": "model-00002-of-00002.safetensors", "model.layers.30.self_attn.g_proj.weight": "model-00002-of-00002.safetensors", "model.layers.30.self_attn.out_proj.weight": "model-00002-of-00002.safetensors", "model.layers.30.self_attn.q_k_v_proj.weight": "model-00002-of-00002.safetensors", "model.layers.31.input_layernorm.weight": "model-00002-of-00002.safetensors", "model.layers.31.mlp.down_proj.weight": "model-00002-of-00002.safetensors", "model.layers.31.mlp.gate_proj.weight": "model-00002-of-00002.safetensors", "model.layers.31.mlp.up_proj.weight": "model-00002-of-00002.safetensors", "model.layers.31.post_attention_layernorm.weight": "model-00002-of-00002.safetensors", "model.layers.31.self_attn.g_proj.weight": "model-00002-of-00002.safetensors", "model.layers.31.self_attn.out_proj.weight": "model-00002-of-00002.safetensors", "model.layers.31.self_attn.q_k_v_proj.weight": "model-00002-of-00002.safetensors", "model.layers.32.input_layernorm.weight": "model-00002-of-00002.safetensors", "model.layers.32.mlp.down_proj.weight": "model-00002-of-00002.safetensors", "model.layers.32.mlp.gate_proj.weight": "model-00002-of-00002.safetensors", "model.layers.32.mlp.up_proj.weight": "model-00002-of-00002.safetensors", "model.layers.32.post_attention_layernorm.weight": "model-00002-of-00002.safetensors", "model.layers.32.self_attn.g_proj.weight": "model-00002-of-00002.safetensors", "model.layers.32.self_attn.out_proj.weight": "model-00002-of-00002.safetensors", "model.layers.32.self_attn.q_k_v_proj.weight": "model-00002-of-00002.safetensors", "model.layers.33.input_layernorm.weight": "model-00002-of-00002.safetensors", "model.layers.33.mlp.down_proj.weight": "model-00002-of-00002.safetensors", "model.layers.33.mlp.gate_proj.weight": "model-00002-of-00002.safetensors", "model.layers.33.mlp.up_proj.weight": "model-00002-of-00002.safetensors", "model.layers.33.post_attention_layernorm.weight": "model-00002-of-00002.safetensors", "model.layers.33.self_attn.g_proj.weight": "model-00002-of-00002.safetensors", "model.layers.33.self_attn.out_proj.weight": "model-00002-of-00002.safetensors", "model.layers.33.self_attn.q_k_v_proj.weight": "model-00002-of-00002.safetensors", "model.layers.34.input_layernorm.weight": "model-00002-of-00002.safetensors", "model.layers.34.mlp.down_proj.weight": "model-00002-of-00002.safetensors", "model.layers.34.mlp.gate_proj.weight": "model-00002-of-00002.safetensors", "model.layers.34.mlp.up_proj.weight": "model-00002-of-00002.safetensors", "model.layers.34.post_attention_layernorm.weight": "model-00002-of-00002.safetensors", "model.layers.34.self_attn.g_proj.weight": "model-00002-of-00002.safetensors", "model.layers.34.self_attn.out_proj.weight": "model-00002-of-00002.safetensors", "model.layers.34.self_attn.q_k_v_proj.weight": "model-00002-of-00002.safetensors", "model.layers.35.input_layernorm.weight": "model-00002-of-00002.safetensors", "model.layers.35.mlp.down_proj.weight": "model-00002-of-00002.safetensors", "model.layers.35.mlp.gate_proj.weight": "model-00002-of-00002.safetensors", "model.layers.35.mlp.up_proj.weight": "model-00002-of-00002.safetensors", "model.layers.35.post_attention_layernorm.weight": "model-00002-of-00002.safetensors", "model.layers.35.self_attn.g_proj.weight": "model-00002-of-00002.safetensors", "model.layers.35.self_attn.out_proj.weight": "model-00002-of-00002.safetensors", "model.layers.35.self_attn.q_k_v_proj.weight": "model-00002-of-00002.safetensors", "model.layers.4.input_layernorm.weight": "model-00001-of-00002.safetensors", "model.layers.4.mlp.down_proj.weight": "model-00001-of-00002.safetensors", "model.layers.4.mlp.gate_proj.weight": "model-00001-of-00002.safetensors", "model.layers.4.mlp.up_proj.weight": "model-00001-of-00002.safetensors", "model.layers.4.post_attention_layernorm.weight": "model-00001-of-00002.safetensors", "model.layers.4.self_attn.g_proj.weight": "model-00001-of-00002.safetensors", "model.layers.4.self_attn.out_proj.weight": "model-00001-of-00002.safetensors", "model.layers.4.self_attn.q_k_v_proj.weight": "model-00001-of-00002.safetensors", "model.layers.5.input_layernorm.weight": "model-00001-of-00002.safetensors", "model.layers.5.mlp.down_proj.weight": "model-00001-of-00002.safetensors", "model.layers.5.mlp.gate_proj.weight": "model-00001-of-00002.safetensors", "model.layers.5.mlp.up_proj.weight": "model-00001-of-00002.safetensors", "model.layers.5.post_attention_layernorm.weight": "model-00001-of-00002.safetensors", "model.layers.5.self_attn.g_proj.weight": "model-00001-of-00002.safetensors", "model.layers.5.self_attn.out_proj.weight": "model-00001-of-00002.safetensors", "model.layers.5.self_attn.q_k_v_proj.weight": "model-00001-of-00002.safetensors", "model.layers.6.input_layernorm.weight": "model-00001-of-00002.safetensors", "model.layers.6.mlp.down_proj.weight": "model-00001-of-00002.safetensors", "model.layers.6.mlp.gate_proj.weight": "model-00001-of-00002.safetensors", "model.layers.6.mlp.up_proj.weight": "model-00001-of-00002.safetensors", "model.layers.6.post_attention_layernorm.weight": "model-00001-of-00002.safetensors", "model.layers.6.self_attn.g_proj.weight": "model-00001-of-00002.safetensors", "model.layers.6.self_attn.out_proj.weight": "model-00001-of-00002.safetensors", "model.layers.6.self_attn.q_k_v_proj.weight": "model-00001-of-00002.safetensors", "model.layers.7.input_layernorm.weight": "model-00001-of-00002.safetensors", "model.layers.7.mlp.down_proj.weight": "model-00001-of-00002.safetensors", "model.layers.7.mlp.gate_proj.weight": "model-00001-of-00002.safetensors", "model.layers.7.mlp.up_proj.weight": "model-00001-of-00002.safetensors", "model.layers.7.post_attention_layernorm.weight": "model-00001-of-00002.safetensors", "model.layers.7.self_attn.g_proj.weight": "model-00001-of-00002.safetensors", "model.layers.7.self_attn.out_proj.weight": "model-00001-of-00002.safetensors", "model.layers.7.self_attn.q_k_v_proj.weight": "model-00001-of-00002.safetensors", "model.layers.8.input_layernorm.weight": "model-00001-of-00002.safetensors", "model.layers.8.mlp.down_proj.weight": "model-00001-of-00002.safetensors", "model.layers.8.mlp.gate_proj.weight": "model-00001-of-00002.safetensors", "model.layers.8.mlp.up_proj.weight": "model-00001-of-00002.safetensors", "model.layers.8.post_attention_layernorm.weight": "model-00001-of-00002.safetensors", "model.layers.8.self_attn.g_proj.weight": "model-00001-of-00002.safetensors", "model.layers.8.self_attn.out_proj.weight": "model-00001-of-00002.safetensors", "model.layers.8.self_attn.q_k_v_proj.weight": "model-00001-of-00002.safetensors", "model.layers.9.input_layernorm.weight": "model-00001-of-00002.safetensors", "model.layers.9.mlp.down_proj.weight": "model-00001-of-00002.safetensors", "model.layers.9.mlp.gate_proj.weight": "model-00001-of-00002.safetensors", "model.layers.9.mlp.up_proj.weight": "model-00001-of-00002.safetensors", "model.layers.9.post_attention_layernorm.weight": "model-00001-of-00002.safetensors", "model.layers.9.self_attn.g_proj.weight": "model-00001-of-00002.safetensors", "model.layers.9.self_attn.out_proj.weight": "model-00001-of-00002.safetensors", "model.layers.9.self_attn.q_k_v_proj.weight": "model-00001-of-00002.safetensors", "model.norm.weight": "model-00002-of-00002.safetensors" }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483import math
import torchimport torch.nn.functional as Ffrom torch import nnfrom transformers.activations import ACT2FNfrom transformers.cache_utils import Cache, DynamicCachefrom transformers.generation import GenerationMixinfrom transformers.masking_utils import create_causal_mask, create_sliding_window_causal_maskfrom transformers.modeling_outputs import ( BaseModelOutputWithPast, CausalLMOutputWithPast,)from transformers.modeling_utils import PreTrainedModelfrom transformers.processing_utils import Unpackfrom transformers.pytorch_utils import ALL_LAYERNORM_LAYERSfrom transformers.utils import TransformersKwargs, can_return_tuple, logging
from .configuration_spark import Spark2_5Config
logger = logging.get_logger(__name__)
_CONFIG_FOR_DOC = "Spark2_5Config"
def rotate_half(x): x1 = x[..., : x.shape[-1] // 2] x2 = x[..., x.shape[-1] // 2 :] return torch.cat((-x2, x1), dim=-1)
def compute_rope_cos_sin(positions, head_dim, rope_theta, partial_rotary_factor=1.0, device="cpu"): rope_head_dim = int(head_dim * partial_rotary_factor) inv_freq = 1.0 / (rope_theta ** (torch.arange(0, rope_head_dim, 2, dtype=torch.int64).to(device="cpu", dtype=torch.float) / rope_head_dim)) inv_freq = inv_freq.to(device) t = positions.to(device=device, dtype=torch.float32) freqs = torch.outer(t, inv_freq) freqs = torch.cat([freqs, freqs], dim=-1) cos = freqs.cos() sin = freqs.sin() return cos, sin
def apply_rotary_pos_emb(x, cos, sin): rope_head_dim = cos.shape[-1] x_f32 = x.float() if x_f32.shape[-1] > rope_head_dim: x_rot = x_f32[..., :rope_head_dim] x_pass = x_f32[..., rope_head_dim:] c = cos.unsqueeze(0).unsqueeze(0) s = sin.unsqueeze(0).unsqueeze(0) x_rot = x_rot * c + rotate_half(x_rot) * s result = torch.cat([x_rot, x_pass], dim=-1) else: c = cos.unsqueeze(0).unsqueeze(0) s = sin.unsqueeze(0).unsqueeze(0) result = x_f32 * c + rotate_half(x_f32) * s return result.to(x.dtype)
def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor: batch, num_key_value_heads, slen, head_dim = hidden_states.shape if n_rep == 1: return hidden_states hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim) return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
def eager_attention_forward( module: nn.Module, query: torch.Tensor, key: torch.Tensor, value: torch.Tensor, attention_mask: torch.Tensor | None = None, scaling: float | None = None, dropout: float = 0.0, **kwargs: Unpack[TransformersKwargs],): key = repeat_kv(key, module.num_key_value_groups) value = repeat_kv(value, module.num_key_value_groups)
if scaling is None: scaling = 1.0 / math.sqrt(query.shape[-1])
attn_weights = torch.matmul(query, key.transpose(2, 3)) * scaling if attention_mask is not None: causal_mask = attention_mask[:, :, :, : key.shape[-2]] attn_weights = attn_weights + causal_mask
attn_weights = attn_weights - attn_weights.max(dim=-1, keepdim=True).values attn_weights = F.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype) attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training) attn_output = torch.matmul(attn_weights, value) return attn_output, attn_weights
class Spark2_5RMSNorm(nn.Module): def __init__(self, hidden_size, eps=1e-6): super().__init__() self.weight = nn.Parameter(torch.ones(hidden_size)) self.variance_epsilon = eps
def forward(self, hidden_states): input_dtype = hidden_states.dtype hidden_states = hidden_states.to(torch.float32) variance = hidden_states.pow(2).mean(-1, keepdim=True) hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon) return (self.weight.float() * hidden_states).to(input_dtype)
def extra_repr(self): return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
ALL_LAYERNORM_LAYERS.append(Spark2_5RMSNorm)
class Spark2_5MLP(nn.Module): def __init__(self, config): super().__init__() self.config = config self.hidden_size = config.hidden_size self.intermediate_size = config.intermediate_size self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.mlp_bias) self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.mlp_bias) self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=config.mlp_bias)
if config.hidden_act != "gelu": raise ValueError(f"只支持hidden_act='gelu',当前传入:{config.hidden_act}") self.act_fn = ACT2FN[config.hidden_act]
def forward(self, x): return self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
class Spark2_5Attention(nn.Module): def __init__(self, config: Spark2_5Config, layer_idx: int | None = None): super().__init__() self.config = config self.layer_idx = layer_idx self.attention_dropout = config.attention_dropout self.hidden_size = config.hidden_size self.num_heads = config.num_attention_heads self.head_dim = config.head_dim self.num_key_value_heads = config.num_key_value_heads self.num_key_value_groups = self.num_heads // self.num_key_value_heads self.scaling = 1.0 / math.sqrt(self.head_dim) self.headwise_attn_output_gate = config.headwise_attn_output_gate self.gate_attn_act_mode = config.gate_attn_act_mode self.q_dim = self.num_heads * self.head_dim self.kv_dim = self.num_key_value_heads * self.head_dim
qkv_out_dim = self.q_dim + 2 * self.kv_dim self.q_k_v_proj = nn.Linear(self.hidden_size, qkv_out_dim, bias=config.attention_bias) self.g_proj = nn.Linear(self.hidden_size, self.num_heads, bias=config.attention_bias) if self.headwise_attn_output_gate else None self.out_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=config.attention_bias) self.sliding_window = None
def forward( self, hidden_states: torch.Tensor, position_embeddings: tuple[torch.Tensor, torch.Tensor], attention_mask: torch.Tensor | None = None, past_key_values: Cache | None = None, cache_position: torch.LongTensor | None = None, **kwargs: Unpack[TransformersKwargs], ) -> tuple[torch.Tensor, torch.Tensor]: input_shape = hidden_states.shape[:-1] bsz, seq_len = input_shape
qkv = self.q_k_v_proj(hidden_states) q = qkv[..., :self.q_dim] k = qkv[..., self.q_dim:self.q_dim + self.kv_dim] v = qkv[..., self.q_dim + self.kv_dim:] gate_score = self.g_proj(hidden_states) if self.g_proj is not None else None
q = q.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2) k = k.view(bsz, seq_len, self.num_key_value_heads, self.head_dim).transpose(1, 2) v = v.view(bsz, seq_len, self.num_key_value_heads, self.head_dim).transpose(1, 2) if gate_score is not None: gate_score = gate_score.view(bsz, seq_len, self.num_heads, 1).transpose(1, 2)
cos, sin = position_embeddings q = apply_rotary_pos_emb(q, cos, sin) k = apply_rotary_pos_emb(k, cos, sin)
if past_key_values is not None: cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position} k, v = past_key_values.update(k, v, self.layer_idx, cache_kwargs)
attn_output, attn_weights = eager_attention_forward( self, q, k, v, attention_mask=attention_mask, scaling=self.scaling, dropout=self.attention_dropout if self.training else 0.0, )
if gate_score is not None: if self.gate_attn_act_mode == "sigmoid": gate = torch.sigmoid(gate_score.float()) elif self.gate_attn_act_mode == "silu": gate = F.silu(gate_score.float()) else: raise ValueError(f"Unsupported gate_attn_act_mode: {self.gate_attn_act_mode}") gate = gate.to(attn_output.dtype) attn_output = attn_output * gate
attn_output = attn_output.transpose(1, 2).contiguous().view(bsz, seq_len, -1) attn_output = self.out_proj(attn_output)
return attn_output, attn_weights
class Spark2_5DecoderLayer(nn.Module): def __init__(self, config: Spark2_5Config, layer_idx: int): super().__init__() self.hidden_size = config.hidden_size
self.self_attn = Spark2_5Attention(config=config, layer_idx=layer_idx) self.mlp = Spark2_5MLP(config) self.input_layernorm = Spark2_5RMSNorm(config.hidden_size, eps=config.rms_norm_eps) self.post_attention_layernorm = Spark2_5RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
self.layer_type = config.layer_types[layer_idx] if layer_idx < len(config.layer_types) else "full_attention" if self.layer_type == "sliding_attention" and config.sliding_window is not None: self.self_attn.sliding_window = config.sliding_window else: self.self_attn.sliding_window = None self.self_attn.partial_rotary_factor = config.get_partial_rotary_factor(self.layer_type) def forward( self, hidden_states: torch.Tensor, position_embeddings: tuple[torch.Tensor, torch.Tensor], attention_mask: torch.Tensor | None = None, past_key_values: Cache | None = None, cache_position: torch.LongTensor | None = None, position_ids: torch.LongTensor | None = None, **kwargs: Unpack[TransformersKwargs] ) -> torch.Tensor:
residual = hidden_states hidden_states = self.input_layernorm(hidden_states) hidden_states = hidden_states.to(self.mlp.gate_proj.weight.dtype)
hidden_states, _ = self.self_attn( hidden_states=hidden_states, position_embeddings=position_embeddings, attention_mask=attention_mask, past_key_values=past_key_values, cache_position=cache_position, position_ids=position_ids, ) hidden_states = residual + hidden_states
residual = hidden_states hidden_states = self.post_attention_layernorm(hidden_states) hidden_states = hidden_states.to(self.mlp.gate_proj.weight.dtype)
hidden_states = self.mlp(hidden_states) hidden_states = residual + hidden_states
return hidden_states
class Spark2_5PreTrainedModel(PreTrainedModel): config_class = Spark2_5Config base_model_prefix = "model" supports_gradient_checkpointing = True _no_split_modules = ["Spark2_5DecoderLayer"] # noqa: RUF012 _skip_keys_device_placement = ["past_key_values"] # noqa: RUF012
def _init_weights(self, module): std = self.config.initializer_range if isinstance(module, nn.Linear): module.weight.data.normal_(mean=0.0, std=std) if module.bias is not None: module.bias.data.zero_() elif isinstance(module, nn.Embedding): module.weight.data.normal_(mean=0.0, std=std) if module.padding_idx is not None: module.weight.data[module.padding_idx].zero_()
class Spark2_5Model(Spark2_5PreTrainedModel): def __init__(self, config: Spark2_5Config): super().__init__(config) self.padding_idx = config.pad_token_id self.vocab_size = config.vocab_size
self.embedding = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx) self.layers = nn.ModuleList( [Spark2_5DecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)] ) self.norm = Spark2_5RMSNorm(config.hidden_size, eps=config.rms_norm_eps) self.gradient_checkpointing = False self.has_sliding_layers = "sliding_attention" in config.layer_types
self.post_init()
def get_input_embeddings(self): return self.embedding
def set_input_embeddings(self, value): self.embedding = value def forward( self, input_ids: torch.LongTensor = None, attention_mask: torch.Tensor | None = None, position_ids: torch.LongTensor | None = None, past_key_values: Cache | list[torch.FloatTensor] | None = None, inputs_embeds: torch.FloatTensor | None = None, use_cache: bool | None = None, cache_position: torch.LongTensor | None = None, token_type_ids: torch.LongTensor | None = None, **kwargs: Unpack[TransformersKwargs], ) -> BaseModelOutputWithPast: use_cache = use_cache if use_cache is not None else self.config.use_cache if (input_ids is None) ^ (inputs_embeds is not None): raise ValueError( "You cannot specify both input_ids and inputs_embeds at the same time, and must specify either one" )
if self.gradient_checkpointing and self.training and use_cache: logger.warning_once( "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`." ) use_cache = False
if inputs_embeds is None: inputs_embeds = self.embedding(input_ids)
if use_cache and past_key_values is None: past_key_values = DynamicCache(config=self.config)
if cache_position is None: past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0 cache_position = torch.arange( past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device )
if position_ids is None: position_ids = cache_position.unsqueeze(0)
if not isinstance(attention_mask, dict): mask_kwargs = { "config": self.config, "input_embeds": inputs_embeds, "attention_mask": attention_mask, "cache_position": cache_position, "past_key_values": past_key_values, "position_ids": position_ids, } causal_mask_mapping = { "full_attention": create_causal_mask(**mask_kwargs), } if self.has_sliding_layers: causal_mask_mapping["sliding_attention"] = create_sliding_window_causal_mask(**mask_kwargs) else: causal_mask_mapping = attention_mask
hidden_states = inputs_embeds.float()
device = hidden_states.device dtype = self.embedding.weight.dtype
head_dim = self.config.head_dim rope_cache = {} for lt in set(self.config.layer_types): rope_theta = self.config.get_rope_theta(lt) prf = self.config.get_partial_rotary_factor(lt) cos, sin = compute_rope_cos_sin(cache_position, head_dim, rope_theta, partial_rotary_factor=prf, device=device) rope_cache[lt] = (cos, sin)
for decoder_layer in self.layers: layer_type = decoder_layer.layer_type position_embeddings = rope_cache.get(layer_type, rope_cache.get("full_attention")) layer_attention_mask = causal_mask_mapping.get(layer_type, causal_mask_mapping.get("full_attention"))
if self.gradient_checkpointing and self.training: layer_outputs = self._gradient_checkpointing_func( decoder_layer.__call__, hidden_states, position_embeddings, layer_attention_mask, ) hidden_states = layer_outputs[0] if isinstance(layer_outputs, tuple) else layer_outputs else: hidden_states = decoder_layer( hidden_states, position_embeddings=position_embeddings, attention_mask=layer_attention_mask, past_key_values=past_key_values, cache_position=cache_position, position_ids=position_ids, )
hidden_states = self.norm(hidden_states) hidden_states = hidden_states.to(dtype)
return BaseModelOutputWithPast( last_hidden_state=hidden_states, past_key_values=past_key_values if use_cache else None, )
class Spark2_5ForCausalLM(Spark2_5PreTrainedModel, GenerationMixin): _tied_weights_keys = ["lm_head.weight"] # noqa: RUF012
def __init__(self, config): super().__init__(config) self.model = Spark2_5Model(config) self.vocab_size = config.vocab_size self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False) self.post_init()
def get_input_embeddings(self): return self.model.embedding
def set_input_embeddings(self, value): self.model.embedding = value
def get_output_embeddings(self): return self.lm_head
def set_output_embeddings(self, new_embeddings): self.lm_head = new_embeddings
def set_decoder(self, decoder): self.model = decoder
def get_decoder(self): return self.model
@can_return_tuple def forward( self, input_ids: torch.LongTensor = None, attention_mask: torch.Tensor | None = None, position_ids: torch.LongTensor | None = None, past_key_values: Cache | list[torch.FloatTensor] | None = None, inputs_embeds: torch.FloatTensor | None = None, labels: torch.LongTensor | None = None, use_cache: bool | None = None, cache_position: torch.LongTensor | None = None, logits_to_keep: int = 0, token_type_ids: torch.LongTensor | None = None, **kwargs: Unpack[TransformersKwargs], ) -> CausalLMOutputWithPast: outputs: BaseModelOutputWithPast = self.model( input_ids=input_ids, attention_mask=attention_mask, position_ids=position_ids, past_key_values=past_key_values, inputs_embeds=inputs_embeds, use_cache=use_cache, cache_position=cache_position, )
hidden_states = outputs.last_hidden_state slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep hidden_states = hidden_states[:, slice_indices, :]
if self.config.tie_word_embeddings: embed_weight = self.model.embedding.weight logits = F.linear(hidden_states, embed_weight) else: logits = self.lm_head(hidden_states)
loss = None if labels is not None: loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs)
return CausalLMOutputWithPast( loss=loss, logits=logits, past_key_values=outputs.past_key_values, hidden_states=outputs.hidden_states, attentions=outputs.attentions, )
__all__ = ["Spark2_5Config", "Spark2_5ForCausalLM", "Spark2_5Model"]123456789101112131415{ "backend": "tokenizers", "bos_token": "<|start▁of▁sentence|>", "clean_up_tokenization_spaces": false, "eos_token": "<|end▁of▁sentence|>", "is_local": true, "legacy": true, "local_files_only": false, "model_max_length": 131072, "pad_token": "<|▁pad▁|>", "sp_model_kwargs": {}, "tokenizer_class": "TokenizersBackend", "tool_parser_type": "glm47", "unk_token": "<unk>"}LICENSEAdded+202
NOTICEAdded+12
README.mdAdded+162
chat_template.jinjaAdded+121
config.jsonAdded+83
configuration_spark.pyAdded+118
generation_config.jsonAdded+12
model-00001-of-00002.safetensorsAdded+3
model-00002-of-00002.safetensorsAdded+3
model.safetensors.index.jsonAdded+298
modeling_spark.pyAdded+483
tokenizer.jsonAdded
tokenizer_config.jsonAdded+15