Instructions to use tiny-random/spark-x2.6 with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use tiny-random/spark-x2.6 with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("text-generation", model="tiny-random/spark-x2.6", trust_remote_code=True) messages = [ {"role": "user", "content": "Who are you?"}, ] pipe(messages)# pip install -U transformers accelerate # Load model directly from transformers import AutoModelForCausalLM model = AutoModelForCausalLM.from_pretrained("tiny-random/spark-x2.6", trust_remote_code=True, device_map="auto") - Notebooks
- Google Colab
- Kaggle
- Local Apps Settings
- vLLM
How to use tiny-random/spark-x2.6 with vLLM:
Install from pip and serve model
# Install vLLM from pip: pip install vllm # Start the vLLM server: vllm serve "tiny-random/spark-x2.6" # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:8000/v1/chat/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "tiny-random/spark-x2.6", "messages": [ { "role": "user", "content": "What is the capital of France?" } ] }'Use Docker
docker model run hf.co/tiny-random/spark-x2.6
- SGLang
How to use tiny-random/spark-x2.6 with SGLang:
Install from pip and serve model
# Install SGLang from pip: pip install sglang # Start the SGLang server: python3 -m sglang.launch_server \ --model-path "tiny-random/spark-x2.6" \ --host 0.0.0.0 \ --port 30000 # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:30000/v1/chat/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "tiny-random/spark-x2.6", "messages": [ { "role": "user", "content": "What is the capital of France?" } ] }'Use Docker images
docker run --gpus all \ --shm-size 32g \ -p 30000:30000 \ -v ~/.cache/huggingface:/root/.cache/huggingface \ --env "HF_TOKEN=<secret>" \ --ipc=host \ lmsysorg/sglang:latest \ python3 -m sglang.launch_server \ --model-path "tiny-random/spark-x2.6" \ --host 0.0.0.0 \ --port 30000 # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:30000/v1/chat/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "tiny-random/spark-x2.6", "messages": [ { "role": "user", "content": "What is the capital of France?" } ] }' - Docker Model Runner
How to use tiny-random/spark-x2.6 with Docker Model Runner:
docker model run hf.co/tiny-random/spark-x2.6
Upload folder using huggingface_hub
Browse files- .meta.json +17 -0
- README.md +157 -0
- chat_template.jinja +121 -0
- config.json +61 -0
- configuration_spark.py +118 -0
- generation_config.json +14 -0
- merges.txt +0 -0
- model.safetensors +3 -0
- modeling_spark.py +482 -0
- special_tokens_map.json +6 -0
- tokenizer.json +0 -0
- tokenizer_config.json +42 -0
- vocab.json +0 -0
.meta.json
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"source_model": {
|
| 3 |
+
"name": "XHToken/Spark-X2.6-4B",
|
| 4 |
+
"commit_id": "66e3ae7bee54e0a523d692cb8ef841f35409807b"
|
| 5 |
+
},
|
| 6 |
+
"env": {
|
| 7 |
+
"python": "3.12.13",
|
| 8 |
+
"packages": {
|
| 9 |
+
"huggingface_hub": "2.3.0",
|
| 10 |
+
"safetensors": "0.8.0",
|
| 11 |
+
"tokenizers": "0.23.3",
|
| 12 |
+
"torch": "2.13.0",
|
| 13 |
+
"transformers": "5.19.0"
|
| 14 |
+
},
|
| 15 |
+
"cuda": "13.0"
|
| 16 |
+
}
|
| 17 |
+
}
|
README.md
ADDED
|
@@ -0,0 +1,157 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
library_name: transformers
|
| 3 |
+
base_model:
|
| 4 |
+
- XHToken/Spark-X2.6-4B
|
| 5 |
+
---
|
| 6 |
+
|
| 7 |
+
This tiny model is intended for debugging. It is randomly initialized using the configuration adapted from [XHToken/Spark-X2.6-4B](https://huggingface.co/XHToken/Spark-X2.6-4B).
|
| 8 |
+
|
| 9 |
+
Structural comparison with `XHToken/Spark-X2.6-4B`:
|
| 10 |
+
|
| 11 |
+
| Feature | Source | Tiny |
|
| 12 |
+
|---|---:|---:|
|
| 13 |
+
| Vocabulary / tied embeddings | 131,072 / yes | same |
|
| 14 |
+
| Layers | 36 | 12; three 3-sliding + 1-full cycles |
|
| 15 |
+
| Hidden size / head dimension | 2,560 / 256 | 16 / 32 |
|
| 16 |
+
| Query / KV heads | 16 / 4 | 1 / 1 |
|
| 17 |
+
| MLP width | 10,240 | 64 |
|
| 18 |
+
| Sliding window | 512 | same |
|
| 19 |
+
| Per-head output gate | sigmoid | same |
|
| 20 |
+
| Stored precision | BF16 | BF16 |
|
| 21 |
+
|
| 22 |
+
The source implementation invokes eager attention directly. The tiny definition
|
| 23 |
+
retains that source behavior rather than falsely advertising an optimized
|
| 24 |
+
attention backend.
|
| 25 |
+
|
| 26 |
+
| File path | Size |
|
| 27 |
+
|------|------|
|
| 28 |
+
| model.safetensors | 4.3MB |
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
### Example usage:
|
| 32 |
+
|
| 33 |
+
- Transformers (✅ verified)
|
| 34 |
+
|
| 35 |
+
```python
|
| 36 |
+
import torch
|
| 37 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
| 38 |
+
|
| 39 |
+
model_id = "tiny-random/spark-x2.6"
|
| 40 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 41 |
+
dtype = torch.bfloat16 if device == "cuda" else torch.float32
|
| 42 |
+
# The pinned Spark implementation calls eager_attention_forward directly;
|
| 43 |
+
# it exposes no SDPA/FlashAttention dispatch path to select instead.
|
| 44 |
+
model = AutoModelForCausalLM.from_pretrained(model_id, dtype=dtype, trust_remote_code=True).to(device).eval()
|
| 45 |
+
tokenizer = AutoTokenizer.from_pretrained(model_id, trust_remote_code=True)
|
| 46 |
+
inputs = tokenizer("Hello", return_tensors="pt").to(device)
|
| 47 |
+
output = model.generate(**inputs, do_sample=False, min_new_tokens=10, max_new_tokens=10)
|
| 48 |
+
print(tokenizer.decode(output[0, inputs["input_ids"].shape[1]:], skip_special_tokens=True))
|
| 49 |
+
```
|
| 50 |
+
|
| 51 |
+
### Codes to create this repo (✅ verified):
|
| 52 |
+
|
| 53 |
+
<details><summary>Click to expand</summary>
|
| 54 |
+
|
| 55 |
+
```python
|
| 56 |
+
import json
|
| 57 |
+
from pathlib import Path
|
| 58 |
+
from shutil import copyfile
|
| 59 |
+
|
| 60 |
+
import torch
|
| 61 |
+
from huggingface_hub import hf_hub_download, list_repo_files
|
| 62 |
+
from transformers import AutoConfig, AutoModelForCausalLM, set_seed
|
| 63 |
+
|
| 64 |
+
source_model_id = "XHToken/Spark-X2.6-4B"
|
| 65 |
+
save_folder = "/tmp/tiny-random/spark-x26"
|
| 66 |
+
source_revision = "66e3ae7bee54e0a523d692cb8ef841f35409807b"
|
| 67 |
+
set_seed(42)
|
| 68 |
+
folder = Path(save_folder)
|
| 69 |
+
folder.mkdir(parents=True, exist_ok=True)
|
| 70 |
+
raw = json.loads(Path(hf_hub_download(source_model_id, "config.json", revision=source_revision)).read_text())
|
| 71 |
+
raw.update(
|
| 72 |
+
hidden_size=16, head_dim=32, num_attention_heads=1, num_key_value_heads=1,
|
| 73 |
+
intermediate_size=64, num_hidden_layers=12,
|
| 74 |
+
layer_types=(["sliding_attention"] * 3 + ["full_attention"]) * 3,
|
| 75 |
+
)
|
| 76 |
+
(folder / "config.json").write_text(json.dumps(raw, indent=2), encoding="utf-8")
|
| 77 |
+
for filename in ("configuration_spark.py", "modeling_spark.py"):
|
| 78 |
+
source = Path(hf_hub_download(source_model_id, filename, revision=source_revision)).read_text(encoding="utf-8")
|
| 79 |
+
if filename == "modeling_spark.py":
|
| 80 |
+
# Spark's pinned remote implementation targets Transformers 4.57.
|
| 81 |
+
# These are API compatibility adaptations for Transformers 5.19;
|
| 82 |
+
# the attention, state-dict names, and tied-embedding semantics stay unchanged.
|
| 83 |
+
source = source.replace(
|
| 84 |
+
'_tied_weights_keys = ["lm_head.weight"]',
|
| 85 |
+
'_tied_weights_keys = {"lm_head.weight": "model.embedding.weight"}',
|
| 86 |
+
)
|
| 87 |
+
source = source.replace(
|
| 88 |
+
'"input_embeds": inputs_embeds,\n "attention_mask"',
|
| 89 |
+
'"inputs_embeds": inputs_embeds,\n "attention_mask"',
|
| 90 |
+
)
|
| 91 |
+
source = source.replace(
|
| 92 |
+
' "cache_position": cache_position,\n "past_key_values"',
|
| 93 |
+
' "past_key_values"',
|
| 94 |
+
)
|
| 95 |
+
(folder / filename).write_text(source, encoding="utf-8")
|
| 96 |
+
config = AutoConfig.from_pretrained(folder, trust_remote_code=True)
|
| 97 |
+
model = AutoModelForCausalLM.from_config(config, dtype=torch.bfloat16, trust_remote_code=True)
|
| 98 |
+
with torch.no_grad():
|
| 99 |
+
for name, parameter in sorted(model.named_parameters()):
|
| 100 |
+
if name.endswith("weight") and "norm" in name:
|
| 101 |
+
parameter.fill_(1)
|
| 102 |
+
else:
|
| 103 |
+
torch.nn.init.normal_(parameter, mean=0, std=0.02)
|
| 104 |
+
model.save_pretrained(folder, safe_serialization=True)
|
| 105 |
+
assets = {"chat_template.jinja", "generation_config.json", "merges.txt", "special_tokens_map.json", "tokenizer.json", "tokenizer_config.json", "vocab.json"}
|
| 106 |
+
for filename in sorted(set(list_repo_files(source_model_id, revision=source_revision)) & assets):
|
| 107 |
+
copyfile(hf_hub_download(source_model_id, filename, revision=source_revision), folder / filename)
|
| 108 |
+
```
|
| 109 |
+
|
| 110 |
+
</details>
|
| 111 |
+
|
| 112 |
+
### Printing the model:
|
| 113 |
+
|
| 114 |
+
<details><summary>Click to expand</summary>
|
| 115 |
+
|
| 116 |
+
```text
|
| 117 |
+
Spark2_5ForCausalLM(
|
| 118 |
+
(model): Spark2_5Model(
|
| 119 |
+
(embedding): Embedding(131072, 16, padding_idx=2)
|
| 120 |
+
(layers): ModuleList(
|
| 121 |
+
(0-11): 12 x Spark2_5DecoderLayer(
|
| 122 |
+
(self_attn): Spark2_5Attention(
|
| 123 |
+
(q_k_v_proj): Linear(in_features=16, out_features=96, bias=False)
|
| 124 |
+
(g_proj): Linear(in_features=16, out_features=1, bias=False)
|
| 125 |
+
(out_proj): Linear(in_features=32, out_features=16, bias=False)
|
| 126 |
+
)
|
| 127 |
+
(mlp): Spark2_5MLP(
|
| 128 |
+
(gate_proj): Linear(in_features=16, out_features=64, bias=False)
|
| 129 |
+
(up_proj): Linear(in_features=16, out_features=64, bias=False)
|
| 130 |
+
(down_proj): Linear(in_features=64, out_features=16, bias=False)
|
| 131 |
+
(act_fn): GELUActivation()
|
| 132 |
+
)
|
| 133 |
+
(input_layernorm): Spark2_5RMSNorm((16,), eps=1e-06)
|
| 134 |
+
(post_attention_layernorm): Spark2_5RMSNorm((16,), eps=1e-06)
|
| 135 |
+
)
|
| 136 |
+
)
|
| 137 |
+
(norm): Spark2_5RMSNorm((16,), eps=1e-06)
|
| 138 |
+
)
|
| 139 |
+
(lm_head): Linear(in_features=16, out_features=131072, bias=False)
|
| 140 |
+
)
|
| 141 |
+
```
|
| 142 |
+
|
| 143 |
+
</details>
|
| 144 |
+
|
| 145 |
+
### Test environment:
|
| 146 |
+
|
| 147 |
+
- huggingface_hub: 2.3.0
|
| 148 |
+
- safetensors: 0.8.0
|
| 149 |
+
- tokenizers: 0.23.3
|
| 150 |
+
- torch: 2.13.0
|
| 151 |
+
- transformers: 5.19.0
|
| 152 |
+
|
| 153 |
+
### Change log:
|
| 154 |
+
|
| 155 |
+
- 2026-10-23: Initial version.
|
| 156 |
+
|
| 157 |
+
This repo is generated by GPT-6.1-Sol
|
chat_template.jinja
ADDED
|
@@ -0,0 +1,121 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{%- if not messages %}
|
| 2 |
+
{{- raise_exception('No messages provided.') }}
|
| 3 |
+
{%- endif %}
|
| 4 |
+
{%- set enable_thinking = enable_thinking | default(true) %}
|
| 5 |
+
{%- set reasoning_instructions = '' %}
|
| 6 |
+
{%- if enable_thinking is true %}
|
| 7 |
+
{%- set resolved_reasoning_effort = reasoning_effort|default('high') %}
|
| 8 |
+
{%- if resolved_reasoning_effort not in ('high', 'low') %}
|
| 9 |
+
{{- raise_exception('Unexpected reasoning effort ' ~ reasoning_effort ~ '. Supported types are high (default) and low.') }}
|
| 10 |
+
{%- endif %}
|
| 11 |
+
{%- if resolved_reasoning_effort == 'high' %}
|
| 12 |
+
{%- 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`.' %}
|
| 13 |
+
{%- elif resolved_reasoning_effort == 'low' %}
|
| 14 |
+
{%- 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`.' %}
|
| 15 |
+
{%- endif %}
|
| 16 |
+
{%- endif %}
|
| 17 |
+
|
| 18 |
+
{#- Render a string or a list of text blocks. -#}
|
| 19 |
+
{%- macro render_content(content, context_name) %}
|
| 20 |
+
{%- if content is string %}
|
| 21 |
+
{{- content }}
|
| 22 |
+
{%- elif content is none or content is undefined %}
|
| 23 |
+
{{- '' }}
|
| 24 |
+
{%- elif content is iterable and content is not mapping %}
|
| 25 |
+
{%- for block in content %}
|
| 26 |
+
{%- if block.type == 'text' %}
|
| 27 |
+
{{- block.text }}
|
| 28 |
+
{%- else %}
|
| 29 |
+
{{- raise_exception('Unsupported ' ~ context_name ~ ' content block type: ' ~ (block.type | string)) }}
|
| 30 |
+
{%- endif %}
|
| 31 |
+
{%- endfor %}
|
| 32 |
+
{%- else %}
|
| 33 |
+
{{- raise_exception(context_name ~ ' content must be a string or a list of text blocks') }}
|
| 34 |
+
{%- endif %}
|
| 35 |
+
{%- endmacro %}
|
| 36 |
+
|
| 37 |
+
{#- Default system prompt -#}
|
| 38 |
+
{%- set default_system = "you are a helpful assistant." + reasoning_instructions %}
|
| 39 |
+
|
| 40 |
+
{#- The first message-level system is placed in the initial system block. -#}
|
| 41 |
+
{%- set ns = namespace(initial_system='') %}
|
| 42 |
+
{%- if messages[0].role == "system" %}
|
| 43 |
+
{%- set ns.initial_system = render_content(messages[0].content, 'system') %}
|
| 44 |
+
{%- endif %}
|
| 45 |
+
|
| 46 |
+
{#- System block -#}
|
| 47 |
+
{{- '<|start▁of▁sentence|><|System|>' + '\n' + default_system }}
|
| 48 |
+
{%- if tools %}
|
| 49 |
+
{{- '\n\n' + '## Tools' + '\n' + 'You have access to the following functions:' + '\n' + '<tools>' }}
|
| 50 |
+
{%- for tool in tools %}
|
| 51 |
+
{{- '\n' + (tool.function | tojson(separators=(',', ':'))) }}
|
| 52 |
+
{%- endfor %}
|
| 53 |
+
{{- '\n' + '</tools>' }}
|
| 54 |
+
{%- endif %}
|
| 55 |
+
{%- if ns.initial_system %}
|
| 56 |
+
{{- '\n\n' + ns.initial_system }}
|
| 57 |
+
{%- endif %}
|
| 58 |
+
{{- '<|end▁of▁sentence|>'}}
|
| 59 |
+
|
| 60 |
+
{#- Conversation turns -#}
|
| 61 |
+
{%- for message in messages %}
|
| 62 |
+
{%- if message.role == "system" %}
|
| 63 |
+
{#- The first system message was consumed by the initial block. -#}
|
| 64 |
+
{%- if not loop.first %}
|
| 65 |
+
{{- '<|start▁of▁sentence|><|System|>\n' + render_content(message.content, 'system') + '<|end▁of▁sentence|>' }}
|
| 66 |
+
{%- endif %}
|
| 67 |
+
{%- elif message.role == "user" %}
|
| 68 |
+
{{- '<|start▁of▁sentence|><|User|>' + render_content(message.content, 'user') + '<|end▁of▁sentence|>' }}
|
| 69 |
+
{%- elif message.role == "assistant" %}
|
| 70 |
+
{%- set assistant_content = render_content(message.content, 'assistant') %}
|
| 71 |
+
{%- if message.reasoning_content is defined and message.reasoning_content %}
|
| 72 |
+
{%- set reasoning_content = message.reasoning_content %}
|
| 73 |
+
{%- else %}
|
| 74 |
+
{%- set reasoning_content = '' %}
|
| 75 |
+
{%- endif %}
|
| 76 |
+
{{- '<|start▁of▁sentence|><|Bot|>'}}
|
| 77 |
+
{%- if reasoning_content %}
|
| 78 |
+
{{- '<think>' + reasoning_content + '</think>'}}
|
| 79 |
+
{%- else %}
|
| 80 |
+
{{- '</think>' }}
|
| 81 |
+
{%- endif %}
|
| 82 |
+
{%- if assistant_content %}
|
| 83 |
+
{{- assistant_content }}
|
| 84 |
+
{%- endif %}
|
| 85 |
+
{%- if message.tool_calls is defined and message.tool_calls is not none %}
|
| 86 |
+
{%- for tool_call in message.tool_calls %}
|
| 87 |
+
{%- if tool_call.function.arguments is not mapping %}
|
| 88 |
+
{{- raise_exception('tool_call.function.arguments must be a dictionary; normalize JSON strings before apply_chat_template') }}
|
| 89 |
+
{%- endif %}
|
| 90 |
+
{%- set args = tool_call.function.arguments %}
|
| 91 |
+
{{- '<tool_call>' + tool_call.function.name }}
|
| 92 |
+
{%- for k, v in args.items() %}
|
| 93 |
+
{{- '<arg_key>' ~ k ~ '</arg_key><arg_value>' ~ (v if v is string else v | tojson(separators=(', ', ': '))) ~ '</arg_value>' }}
|
| 94 |
+
{%- endfor %}
|
| 95 |
+
{{- '</tool_call>' }}
|
| 96 |
+
{%- endfor %}
|
| 97 |
+
{%- endif %}
|
| 98 |
+
{{- '<|end▁of▁sentence|>' }}
|
| 99 |
+
{%- elif message.role == "tool" %}
|
| 100 |
+
{%- if loop.previtem is undefined or loop.previtem.role != "tool" %}
|
| 101 |
+
{{- '<|start▁of▁sentence|><|Tool|>' }}
|
| 102 |
+
{%- endif %}
|
| 103 |
+
{{- '<tool_response>' ~ message.content ~ '</tool_response>' }}
|
| 104 |
+
{%- if loop.nextitem is undefined or loop.nextitem.role != "tool" %}
|
| 105 |
+
{{- '<|end▁of▁sentence|>' }}
|
| 106 |
+
{%- endif %}
|
| 107 |
+
{%- else %}
|
| 108 |
+
{{- raise_exception('Unsupported message role: ' ~ message.role) }}
|
| 109 |
+
{%- endif %}
|
| 110 |
+
{%- endfor %}
|
| 111 |
+
|
| 112 |
+
{#- Generation prompt -#}
|
| 113 |
+
{%- if add_generation_prompt %}
|
| 114 |
+
{{- '<|start▁of▁sentence|><|Bot|>' }}
|
| 115 |
+
{%- if enable_thinking is defined and enable_thinking %}
|
| 116 |
+
{{- '<think>' }}
|
| 117 |
+
{%- endif %}
|
| 118 |
+
{%- if enable_thinking is defined and not enable_thinking %}
|
| 119 |
+
{{- '</think>' }}
|
| 120 |
+
{%- endif %}
|
| 121 |
+
{%- endif %}
|
config.json
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"architectures": [
|
| 3 |
+
"Spark2_5ForCausalLM"
|
| 4 |
+
],
|
| 5 |
+
"attention_bias": false,
|
| 6 |
+
"attention_dropout": 0.0,
|
| 7 |
+
"auto_map": {
|
| 8 |
+
"AutoConfig": "configuration_spark.Spark2_5Config",
|
| 9 |
+
"AutoModel": "modeling_spark.Spark2_5Model",
|
| 10 |
+
"AutoModelForCausalLM": "modeling_spark.Spark2_5ForCausalLM"
|
| 11 |
+
},
|
| 12 |
+
"bos_token_id": 0,
|
| 13 |
+
"dtype": "bfloat16",
|
| 14 |
+
"eos_token_id": 1,
|
| 15 |
+
"gate_attn_act_mode": "sigmoid",
|
| 16 |
+
"head_dim": 32,
|
| 17 |
+
"headwise_attn_output_gate": true,
|
| 18 |
+
"hidden_act": "gelu",
|
| 19 |
+
"hidden_size": 16,
|
| 20 |
+
"initializer_range": 0.01976,
|
| 21 |
+
"intermediate_size": 64,
|
| 22 |
+
"layer_types": [
|
| 23 |
+
"sliding_attention",
|
| 24 |
+
"sliding_attention",
|
| 25 |
+
"sliding_attention",
|
| 26 |
+
"full_attention",
|
| 27 |
+
"sliding_attention",
|
| 28 |
+
"sliding_attention",
|
| 29 |
+
"sliding_attention",
|
| 30 |
+
"full_attention",
|
| 31 |
+
"sliding_attention",
|
| 32 |
+
"sliding_attention",
|
| 33 |
+
"sliding_attention",
|
| 34 |
+
"full_attention"
|
| 35 |
+
],
|
| 36 |
+
"max_position_embeddings": 1048576,
|
| 37 |
+
"mlp_bias": false,
|
| 38 |
+
"model_type": "spark2_5",
|
| 39 |
+
"num_attention_heads": 1,
|
| 40 |
+
"num_hidden_layers": 12,
|
| 41 |
+
"num_key_value_heads": 1,
|
| 42 |
+
"pad_token_id": 2,
|
| 43 |
+
"rms_norm_eps": 1e-06,
|
| 44 |
+
"rope_parameters": {
|
| 45 |
+
"full_attention": {
|
| 46 |
+
"partial_rotary_factor": 0.25,
|
| 47 |
+
"rope_theta": 5000000,
|
| 48 |
+
"rope_type": "default"
|
| 49 |
+
},
|
| 50 |
+
"sliding_attention": {
|
| 51 |
+
"partial_rotary_factor": 1.0,
|
| 52 |
+
"rope_theta": 10000,
|
| 53 |
+
"rope_type": "default"
|
| 54 |
+
}
|
| 55 |
+
},
|
| 56 |
+
"sliding_window": 512,
|
| 57 |
+
"tie_word_embeddings": true,
|
| 58 |
+
"transformers_version": "5.19.0",
|
| 59 |
+
"use_cache": true,
|
| 60 |
+
"vocab_size": 131072
|
| 61 |
+
}
|
configuration_spark.py
ADDED
|
@@ -0,0 +1,118 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2026 The XHToken team and the HuggingFace Inc. team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
|
| 16 |
+
from transformers import PretrainedConfig
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
class Spark2_5Config(PretrainedConfig):
|
| 20 |
+
model_type = "spark2_5"
|
| 21 |
+
keys_to_ignore_at_inference = ["past_key_values"]
|
| 22 |
+
|
| 23 |
+
base_model_tp_plan = {
|
| 24 |
+
"layers.*.self_attn.q_k_v_proj": "colwise",
|
| 25 |
+
"layers.*.self_attn.g_proj": "colwise",
|
| 26 |
+
"layers.*.self_attn.out_proj": "rowwise",
|
| 27 |
+
"layers.*.mlp.gate_proj": "colwise",
|
| 28 |
+
"layers.*.mlp.up_proj": "colwise",
|
| 29 |
+
"layers.*.mlp.down_proj": "rowwise",
|
| 30 |
+
}
|
| 31 |
+
base_model_pp_plan = {
|
| 32 |
+
"embedding": (["input_ids"], ["inputs_embeds"]),
|
| 33 |
+
"layers": (["hidden_states", "attention_mask"], ["hidden_states"]),
|
| 34 |
+
"norm": (["hidden_states"], ["hidden_states"]),
|
| 35 |
+
}
|
| 36 |
+
|
| 37 |
+
def __init__(
|
| 38 |
+
self,
|
| 39 |
+
vocab_size=32000,
|
| 40 |
+
hidden_size=4096,
|
| 41 |
+
intermediate_size=11008,
|
| 42 |
+
num_hidden_layers=32,
|
| 43 |
+
num_attention_heads=32,
|
| 44 |
+
num_key_value_heads=None,
|
| 45 |
+
hidden_act="gelu",
|
| 46 |
+
max_position_embeddings=2048,
|
| 47 |
+
initializer_range=0.02,
|
| 48 |
+
rms_norm_eps=1e-6,
|
| 49 |
+
use_cache=True,
|
| 50 |
+
pad_token_id=None,
|
| 51 |
+
bos_token_id=1,
|
| 52 |
+
eos_token_id=2,
|
| 53 |
+
tie_word_embeddings=False,
|
| 54 |
+
rope_parameters=None,
|
| 55 |
+
attention_bias=False,
|
| 56 |
+
attention_dropout=0.0,
|
| 57 |
+
mlp_bias=False,
|
| 58 |
+
head_dim=None,
|
| 59 |
+
headwise_attn_output_gate=False,
|
| 60 |
+
gate_attn_act_mode="sigmoid",
|
| 61 |
+
sliding_window=None,
|
| 62 |
+
layer_types=None,
|
| 63 |
+
**kwargs,
|
| 64 |
+
):
|
| 65 |
+
self.vocab_size = vocab_size
|
| 66 |
+
self.max_position_embeddings = max_position_embeddings
|
| 67 |
+
self.hidden_size = hidden_size
|
| 68 |
+
self.intermediate_size = intermediate_size
|
| 69 |
+
self.num_hidden_layers = num_hidden_layers
|
| 70 |
+
self.num_attention_heads = num_attention_heads
|
| 71 |
+
|
| 72 |
+
if num_key_value_heads is None:
|
| 73 |
+
num_key_value_heads = num_attention_heads
|
| 74 |
+
if num_attention_heads % num_key_value_heads != 0:
|
| 75 |
+
raise ValueError(
|
| 76 |
+
f"num_attention_heads ({num_attention_heads}) must be divisible by num_key_value_heads ({num_key_value_heads})"
|
| 77 |
+
)
|
| 78 |
+
self.num_key_value_heads = num_key_value_heads
|
| 79 |
+
|
| 80 |
+
self.hidden_act = hidden_act
|
| 81 |
+
self.initializer_range = initializer_range
|
| 82 |
+
self.rms_norm_eps = rms_norm_eps
|
| 83 |
+
self.use_cache = use_cache
|
| 84 |
+
self.attention_bias = attention_bias
|
| 85 |
+
self.attention_dropout = attention_dropout
|
| 86 |
+
self.mlp_bias = mlp_bias
|
| 87 |
+
self.head_dim = head_dim if head_dim is not None else self.hidden_size // self.num_attention_heads
|
| 88 |
+
self.headwise_attn_output_gate = headwise_attn_output_gate
|
| 89 |
+
self.gate_attn_act_mode = gate_attn_act_mode
|
| 90 |
+
self.sliding_window = sliding_window
|
| 91 |
+
self.rope_parameters = rope_parameters
|
| 92 |
+
|
| 93 |
+
if layer_types is None:
|
| 94 |
+
layer_types = ["full_attention"] * num_hidden_layers
|
| 95 |
+
if len(layer_types) != num_hidden_layers:
|
| 96 |
+
raise ValueError(
|
| 97 |
+
f"layer_types length ({len(layer_types)}) must match num_hidden_layers ({num_hidden_layers})"
|
| 98 |
+
)
|
| 99 |
+
self.layer_types = layer_types
|
| 100 |
+
|
| 101 |
+
super().__init__(
|
| 102 |
+
pad_token_id=pad_token_id,
|
| 103 |
+
bos_token_id=bos_token_id,
|
| 104 |
+
eos_token_id=eos_token_id,
|
| 105 |
+
tie_word_embeddings=tie_word_embeddings,
|
| 106 |
+
**kwargs,
|
| 107 |
+
)
|
| 108 |
+
|
| 109 |
+
def get_rope_theta(self, layer_type):
|
| 110 |
+
params = self.rope_parameters.get(layer_type, {})
|
| 111 |
+
return params.get("rope_theta", 10000)
|
| 112 |
+
|
| 113 |
+
def get_partial_rotary_factor(self, layer_type):
|
| 114 |
+
params = self.rope_parameters.get(layer_type, {})
|
| 115 |
+
return params.get("partial_rotary_factor", 1.0)
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
__all__ = ["Spark2_5Config"]
|
generation_config.json
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"bos_token_id": 0,
|
| 3 |
+
"eos_token_id": 1,
|
| 4 |
+
"pad_token_id": 2,
|
| 5 |
+
"max_tokens": 1048576,
|
| 6 |
+
"temperature": 1.0,
|
| 7 |
+
"top_p": 0.95,
|
| 8 |
+
"top_k": -1,
|
| 9 |
+
"repetition_penalty": 1.0,
|
| 10 |
+
"presence_penalty":0,
|
| 11 |
+
"frequency_penalty":0,
|
| 12 |
+
"do_sample": true,
|
| 13 |
+
"transformers_version": "4.57.1"
|
| 14 |
+
}
|
merges.txt
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
model.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:254aecb0c2a75d91b96d368caed3996123e13e782ab142dc83bb02b18a2ff473
|
| 3 |
+
size 4328808
|
modeling_spark.py
ADDED
|
@@ -0,0 +1,482 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import math
|
| 2 |
+
|
| 3 |
+
import torch
|
| 4 |
+
import torch.nn.functional as F
|
| 5 |
+
from torch import nn
|
| 6 |
+
from transformers.activations import ACT2FN
|
| 7 |
+
from transformers.cache_utils import Cache, DynamicCache
|
| 8 |
+
from transformers.generation import GenerationMixin
|
| 9 |
+
from transformers.masking_utils import create_causal_mask, create_sliding_window_causal_mask
|
| 10 |
+
from transformers.modeling_outputs import (
|
| 11 |
+
BaseModelOutputWithPast,
|
| 12 |
+
CausalLMOutputWithPast,
|
| 13 |
+
)
|
| 14 |
+
from transformers.modeling_utils import PreTrainedModel
|
| 15 |
+
from transformers.processing_utils import Unpack
|
| 16 |
+
from transformers.pytorch_utils import ALL_LAYERNORM_LAYERS
|
| 17 |
+
from transformers.utils import TransformersKwargs, can_return_tuple, logging
|
| 18 |
+
|
| 19 |
+
from .configuration_spark import Spark2_5Config
|
| 20 |
+
|
| 21 |
+
logger = logging.get_logger(__name__)
|
| 22 |
+
|
| 23 |
+
_CONFIG_FOR_DOC = "Spark2_5Config"
|
| 24 |
+
|
| 25 |
+
def rotate_half(x):
|
| 26 |
+
x1 = x[..., : x.shape[-1] // 2]
|
| 27 |
+
x2 = x[..., x.shape[-1] // 2 :]
|
| 28 |
+
return torch.cat((-x2, x1), dim=-1)
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def compute_rope_cos_sin(positions, head_dim, rope_theta, partial_rotary_factor=1.0, device="cpu"):
|
| 32 |
+
rope_head_dim = int(head_dim * partial_rotary_factor)
|
| 33 |
+
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))
|
| 34 |
+
inv_freq = inv_freq.to(device)
|
| 35 |
+
t = positions.to(device=device, dtype=torch.float32)
|
| 36 |
+
freqs = torch.outer(t, inv_freq)
|
| 37 |
+
freqs = torch.cat([freqs, freqs], dim=-1)
|
| 38 |
+
cos = freqs.cos()
|
| 39 |
+
sin = freqs.sin()
|
| 40 |
+
return cos, sin
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def apply_rotary_pos_emb(x, cos, sin):
|
| 44 |
+
rope_head_dim = cos.shape[-1]
|
| 45 |
+
x_f32 = x.float()
|
| 46 |
+
if x_f32.shape[-1] > rope_head_dim:
|
| 47 |
+
x_rot = x_f32[..., :rope_head_dim]
|
| 48 |
+
x_pass = x_f32[..., rope_head_dim:]
|
| 49 |
+
c = cos.unsqueeze(0).unsqueeze(0)
|
| 50 |
+
s = sin.unsqueeze(0).unsqueeze(0)
|
| 51 |
+
x_rot = x_rot * c + rotate_half(x_rot) * s
|
| 52 |
+
result = torch.cat([x_rot, x_pass], dim=-1)
|
| 53 |
+
else:
|
| 54 |
+
c = cos.unsqueeze(0).unsqueeze(0)
|
| 55 |
+
s = sin.unsqueeze(0).unsqueeze(0)
|
| 56 |
+
result = x_f32 * c + rotate_half(x_f32) * s
|
| 57 |
+
return result.to(x.dtype)
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
|
| 61 |
+
batch, num_key_value_heads, slen, head_dim = hidden_states.shape
|
| 62 |
+
if n_rep == 1:
|
| 63 |
+
return hidden_states
|
| 64 |
+
hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
|
| 65 |
+
return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def eager_attention_forward(
|
| 69 |
+
module: nn.Module,
|
| 70 |
+
query: torch.Tensor,
|
| 71 |
+
key: torch.Tensor,
|
| 72 |
+
value: torch.Tensor,
|
| 73 |
+
attention_mask: torch.Tensor | None = None,
|
| 74 |
+
scaling: float | None = None,
|
| 75 |
+
dropout: float = 0.0,
|
| 76 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 77 |
+
):
|
| 78 |
+
key = repeat_kv(key, module.num_key_value_groups)
|
| 79 |
+
value = repeat_kv(value, module.num_key_value_groups)
|
| 80 |
+
|
| 81 |
+
if scaling is None:
|
| 82 |
+
scaling = 1.0 / math.sqrt(query.shape[-1])
|
| 83 |
+
|
| 84 |
+
attn_weights = torch.matmul(query, key.transpose(2, 3)) * scaling
|
| 85 |
+
if attention_mask is not None:
|
| 86 |
+
causal_mask = attention_mask[:, :, :, : key.shape[-2]]
|
| 87 |
+
attn_weights = attn_weights + causal_mask
|
| 88 |
+
|
| 89 |
+
attn_weights = attn_weights - attn_weights.max(dim=-1, keepdim=True).values
|
| 90 |
+
attn_weights = F.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
|
| 91 |
+
attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
|
| 92 |
+
attn_output = torch.matmul(attn_weights, value)
|
| 93 |
+
return attn_output, attn_weights
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
class Spark2_5RMSNorm(nn.Module):
|
| 97 |
+
def __init__(self, hidden_size, eps=1e-6):
|
| 98 |
+
super().__init__()
|
| 99 |
+
self.weight = nn.Parameter(torch.ones(hidden_size))
|
| 100 |
+
self.variance_epsilon = eps
|
| 101 |
+
|
| 102 |
+
def forward(self, hidden_states):
|
| 103 |
+
input_dtype = hidden_states.dtype
|
| 104 |
+
hidden_states = hidden_states.to(torch.float32)
|
| 105 |
+
variance = hidden_states.pow(2).mean(-1, keepdim=True)
|
| 106 |
+
hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
|
| 107 |
+
return (self.weight.float() * hidden_states).to(input_dtype)
|
| 108 |
+
|
| 109 |
+
def extra_repr(self):
|
| 110 |
+
return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
ALL_LAYERNORM_LAYERS.append(Spark2_5RMSNorm)
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
class Spark2_5MLP(nn.Module):
|
| 117 |
+
def __init__(self, config):
|
| 118 |
+
super().__init__()
|
| 119 |
+
self.config = config
|
| 120 |
+
self.hidden_size = config.hidden_size
|
| 121 |
+
self.intermediate_size = config.intermediate_size
|
| 122 |
+
self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.mlp_bias)
|
| 123 |
+
self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.mlp_bias)
|
| 124 |
+
self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=config.mlp_bias)
|
| 125 |
+
|
| 126 |
+
if config.hidden_act != "gelu":
|
| 127 |
+
raise ValueError(f"只支持hidden_act='gelu',当前传入:{config.hidden_act}")
|
| 128 |
+
|
| 129 |
+
self.act_fn = ACT2FN[config.hidden_act]
|
| 130 |
+
|
| 131 |
+
def forward(self, x):
|
| 132 |
+
return self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
class Spark2_5Attention(nn.Module):
|
| 136 |
+
def __init__(self, config: Spark2_5Config, layer_idx: int | None = None):
|
| 137 |
+
super().__init__()
|
| 138 |
+
self.config = config
|
| 139 |
+
self.layer_idx = layer_idx
|
| 140 |
+
self.attention_dropout = config.attention_dropout
|
| 141 |
+
self.hidden_size = config.hidden_size
|
| 142 |
+
self.num_heads = config.num_attention_heads
|
| 143 |
+
self.head_dim = config.head_dim
|
| 144 |
+
self.num_key_value_heads = config.num_key_value_heads
|
| 145 |
+
self.num_key_value_groups = self.num_heads // self.num_key_value_heads
|
| 146 |
+
self.scaling = 1.0 / math.sqrt(self.head_dim)
|
| 147 |
+
self.headwise_attn_output_gate = config.headwise_attn_output_gate
|
| 148 |
+
self.gate_attn_act_mode = config.gate_attn_act_mode
|
| 149 |
+
self.q_dim = self.num_heads * self.head_dim
|
| 150 |
+
self.kv_dim = self.num_key_value_heads * self.head_dim
|
| 151 |
+
|
| 152 |
+
qkv_out_dim = self.q_dim + 2 * self.kv_dim
|
| 153 |
+
self.q_k_v_proj = nn.Linear(self.hidden_size, qkv_out_dim, bias=config.attention_bias)
|
| 154 |
+
self.g_proj = nn.Linear(self.hidden_size, self.num_heads, bias=config.attention_bias) if self.headwise_attn_output_gate else None
|
| 155 |
+
self.out_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=config.attention_bias)
|
| 156 |
+
self.sliding_window = None
|
| 157 |
+
|
| 158 |
+
def forward(
|
| 159 |
+
self,
|
| 160 |
+
hidden_states: torch.Tensor,
|
| 161 |
+
position_embeddings: tuple[torch.Tensor, torch.Tensor],
|
| 162 |
+
attention_mask: torch.Tensor | None = None,
|
| 163 |
+
past_key_values: Cache | None = None,
|
| 164 |
+
cache_position: torch.LongTensor | None = None,
|
| 165 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 166 |
+
) -> tuple[torch.Tensor, torch.Tensor]:
|
| 167 |
+
input_shape = hidden_states.shape[:-1]
|
| 168 |
+
bsz, seq_len = input_shape
|
| 169 |
+
|
| 170 |
+
qkv = self.q_k_v_proj(hidden_states)
|
| 171 |
+
q = qkv[..., :self.q_dim]
|
| 172 |
+
k = qkv[..., self.q_dim:self.q_dim + self.kv_dim]
|
| 173 |
+
v = qkv[..., self.q_dim + self.kv_dim:]
|
| 174 |
+
gate_score = self.g_proj(hidden_states) if self.g_proj is not None else None
|
| 175 |
+
|
| 176 |
+
q = q.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2)
|
| 177 |
+
k = k.view(bsz, seq_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
|
| 178 |
+
v = v.view(bsz, seq_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
|
| 179 |
+
if gate_score is not None:
|
| 180 |
+
gate_score = gate_score.view(bsz, seq_len, self.num_heads, 1).transpose(1, 2)
|
| 181 |
+
|
| 182 |
+
cos, sin = position_embeddings
|
| 183 |
+
q = apply_rotary_pos_emb(q, cos, sin)
|
| 184 |
+
k = apply_rotary_pos_emb(k, cos, sin)
|
| 185 |
+
|
| 186 |
+
|
| 187 |
+
if past_key_values is not None:
|
| 188 |
+
cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
|
| 189 |
+
k, v = past_key_values.update(k, v, self.layer_idx, cache_kwargs)
|
| 190 |
+
|
| 191 |
+
attn_output, attn_weights = eager_attention_forward(
|
| 192 |
+
self, q, k, v,
|
| 193 |
+
attention_mask=attention_mask,
|
| 194 |
+
scaling=self.scaling,
|
| 195 |
+
dropout=self.attention_dropout if self.training else 0.0,
|
| 196 |
+
)
|
| 197 |
+
|
| 198 |
+
if gate_score is not None:
|
| 199 |
+
if self.gate_attn_act_mode == "sigmoid":
|
| 200 |
+
gate = torch.sigmoid(gate_score.float())
|
| 201 |
+
elif self.gate_attn_act_mode == "silu":
|
| 202 |
+
gate = F.silu(gate_score.float())
|
| 203 |
+
else:
|
| 204 |
+
raise ValueError(f"Unsupported gate_attn_act_mode: {self.gate_attn_act_mode}")
|
| 205 |
+
gate = gate.to(attn_output.dtype)
|
| 206 |
+
attn_output = attn_output * gate
|
| 207 |
+
|
| 208 |
+
attn_output = attn_output.transpose(1, 2).contiguous().view(bsz, seq_len, -1)
|
| 209 |
+
attn_output = self.out_proj(attn_output)
|
| 210 |
+
|
| 211 |
+
return attn_output, attn_weights
|
| 212 |
+
|
| 213 |
+
|
| 214 |
+
class Spark2_5DecoderLayer(nn.Module):
|
| 215 |
+
def __init__(self, config: Spark2_5Config, layer_idx: int):
|
| 216 |
+
super().__init__()
|
| 217 |
+
self.hidden_size = config.hidden_size
|
| 218 |
+
|
| 219 |
+
self.self_attn = Spark2_5Attention(config=config, layer_idx=layer_idx)
|
| 220 |
+
self.mlp = Spark2_5MLP(config)
|
| 221 |
+
self.input_layernorm = Spark2_5RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
| 222 |
+
self.post_attention_layernorm = Spark2_5RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
| 223 |
+
|
| 224 |
+
self.layer_type = config.layer_types[layer_idx] if layer_idx < len(config.layer_types) else "full_attention"
|
| 225 |
+
if self.layer_type == "sliding_attention" and config.sliding_window is not None:
|
| 226 |
+
self.self_attn.sliding_window = config.sliding_window
|
| 227 |
+
else:
|
| 228 |
+
self.self_attn.sliding_window = None
|
| 229 |
+
self.self_attn.partial_rotary_factor = config.get_partial_rotary_factor(self.layer_type)
|
| 230 |
+
|
| 231 |
+
def forward(
|
| 232 |
+
self,
|
| 233 |
+
hidden_states: torch.Tensor,
|
| 234 |
+
position_embeddings: tuple[torch.Tensor, torch.Tensor],
|
| 235 |
+
attention_mask: torch.Tensor | None = None,
|
| 236 |
+
past_key_values: Cache | None = None,
|
| 237 |
+
cache_position: torch.LongTensor | None = None,
|
| 238 |
+
position_ids: torch.LongTensor | None = None,
|
| 239 |
+
**kwargs: Unpack[TransformersKwargs]
|
| 240 |
+
) -> torch.Tensor:
|
| 241 |
+
|
| 242 |
+
residual = hidden_states
|
| 243 |
+
hidden_states = self.input_layernorm(hidden_states)
|
| 244 |
+
hidden_states = hidden_states.to(self.mlp.gate_proj.weight.dtype)
|
| 245 |
+
|
| 246 |
+
hidden_states, _ = self.self_attn(
|
| 247 |
+
hidden_states=hidden_states,
|
| 248 |
+
position_embeddings=position_embeddings,
|
| 249 |
+
attention_mask=attention_mask,
|
| 250 |
+
past_key_values=past_key_values,
|
| 251 |
+
cache_position=cache_position,
|
| 252 |
+
position_ids=position_ids,
|
| 253 |
+
)
|
| 254 |
+
hidden_states = residual + hidden_states
|
| 255 |
+
|
| 256 |
+
residual = hidden_states
|
| 257 |
+
hidden_states = self.post_attention_layernorm(hidden_states)
|
| 258 |
+
hidden_states = hidden_states.to(self.mlp.gate_proj.weight.dtype)
|
| 259 |
+
|
| 260 |
+
|
| 261 |
+
hidden_states = self.mlp(hidden_states)
|
| 262 |
+
hidden_states = residual + hidden_states
|
| 263 |
+
|
| 264 |
+
return hidden_states
|
| 265 |
+
|
| 266 |
+
|
| 267 |
+
class Spark2_5PreTrainedModel(PreTrainedModel):
|
| 268 |
+
config_class = Spark2_5Config
|
| 269 |
+
base_model_prefix = "model"
|
| 270 |
+
supports_gradient_checkpointing = True
|
| 271 |
+
_no_split_modules = ["Spark2_5DecoderLayer"] # noqa: RUF012
|
| 272 |
+
_skip_keys_device_placement = ["past_key_values"] # noqa: RUF012
|
| 273 |
+
|
| 274 |
+
def _init_weights(self, module):
|
| 275 |
+
std = self.config.initializer_range
|
| 276 |
+
if isinstance(module, nn.Linear):
|
| 277 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
| 278 |
+
if module.bias is not None:
|
| 279 |
+
module.bias.data.zero_()
|
| 280 |
+
elif isinstance(module, nn.Embedding):
|
| 281 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
| 282 |
+
if module.padding_idx is not None:
|
| 283 |
+
module.weight.data[module.padding_idx].zero_()
|
| 284 |
+
|
| 285 |
+
|
| 286 |
+
class Spark2_5Model(Spark2_5PreTrainedModel):
|
| 287 |
+
def __init__(self, config: Spark2_5Config):
|
| 288 |
+
super().__init__(config)
|
| 289 |
+
self.padding_idx = config.pad_token_id
|
| 290 |
+
self.vocab_size = config.vocab_size
|
| 291 |
+
|
| 292 |
+
self.embedding = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
|
| 293 |
+
self.layers = nn.ModuleList(
|
| 294 |
+
[Spark2_5DecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
|
| 295 |
+
)
|
| 296 |
+
self.norm = Spark2_5RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
| 297 |
+
self.gradient_checkpointing = False
|
| 298 |
+
self.has_sliding_layers = "sliding_attention" in config.layer_types
|
| 299 |
+
|
| 300 |
+
self.post_init()
|
| 301 |
+
|
| 302 |
+
def get_input_embeddings(self):
|
| 303 |
+
return self.embedding
|
| 304 |
+
|
| 305 |
+
def set_input_embeddings(self, value):
|
| 306 |
+
self.embedding = value
|
| 307 |
+
def forward(
|
| 308 |
+
self,
|
| 309 |
+
input_ids: torch.LongTensor = None,
|
| 310 |
+
attention_mask: torch.Tensor | None = None,
|
| 311 |
+
position_ids: torch.LongTensor | None = None,
|
| 312 |
+
past_key_values: Cache | list[torch.FloatTensor] | None = None,
|
| 313 |
+
inputs_embeds: torch.FloatTensor | None = None,
|
| 314 |
+
use_cache: bool | None = None,
|
| 315 |
+
cache_position: torch.LongTensor | None = None,
|
| 316 |
+
token_type_ids: torch.LongTensor | None = None,
|
| 317 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 318 |
+
) -> BaseModelOutputWithPast:
|
| 319 |
+
use_cache = use_cache if use_cache is not None else self.config.use_cache
|
| 320 |
+
if (input_ids is None) ^ (inputs_embeds is not None):
|
| 321 |
+
raise ValueError(
|
| 322 |
+
"You cannot specify both input_ids and inputs_embeds at the same time, and must specify either one"
|
| 323 |
+
)
|
| 324 |
+
|
| 325 |
+
if self.gradient_checkpointing and self.training and use_cache:
|
| 326 |
+
logger.warning_once(
|
| 327 |
+
"`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`."
|
| 328 |
+
)
|
| 329 |
+
use_cache = False
|
| 330 |
+
|
| 331 |
+
if inputs_embeds is None:
|
| 332 |
+
inputs_embeds = self.embedding(input_ids)
|
| 333 |
+
|
| 334 |
+
if use_cache and past_key_values is None:
|
| 335 |
+
past_key_values = DynamicCache(config=self.config)
|
| 336 |
+
|
| 337 |
+
if cache_position is None:
|
| 338 |
+
past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
|
| 339 |
+
cache_position = torch.arange(
|
| 340 |
+
past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
|
| 341 |
+
)
|
| 342 |
+
|
| 343 |
+
if position_ids is None:
|
| 344 |
+
position_ids = cache_position.unsqueeze(0)
|
| 345 |
+
|
| 346 |
+
if not isinstance(attention_mask, dict):
|
| 347 |
+
mask_kwargs = {
|
| 348 |
+
"config": self.config,
|
| 349 |
+
"inputs_embeds": inputs_embeds,
|
| 350 |
+
"attention_mask": attention_mask,
|
| 351 |
+
"past_key_values": past_key_values,
|
| 352 |
+
"position_ids": position_ids,
|
| 353 |
+
}
|
| 354 |
+
causal_mask_mapping = {
|
| 355 |
+
"full_attention": create_causal_mask(**mask_kwargs),
|
| 356 |
+
}
|
| 357 |
+
if self.has_sliding_layers:
|
| 358 |
+
causal_mask_mapping["sliding_attention"] = create_sliding_window_causal_mask(**mask_kwargs)
|
| 359 |
+
else:
|
| 360 |
+
causal_mask_mapping = attention_mask
|
| 361 |
+
|
| 362 |
+
hidden_states = inputs_embeds.float()
|
| 363 |
+
|
| 364 |
+
device = hidden_states.device
|
| 365 |
+
dtype = self.embedding.weight.dtype
|
| 366 |
+
|
| 367 |
+
head_dim = self.config.head_dim
|
| 368 |
+
rope_cache = {}
|
| 369 |
+
for lt in set(self.config.layer_types):
|
| 370 |
+
rope_theta = self.config.get_rope_theta(lt)
|
| 371 |
+
prf = self.config.get_partial_rotary_factor(lt)
|
| 372 |
+
cos, sin = compute_rope_cos_sin(cache_position, head_dim, rope_theta, partial_rotary_factor=prf, device=device)
|
| 373 |
+
rope_cache[lt] = (cos, sin)
|
| 374 |
+
|
| 375 |
+
for decoder_layer in self.layers:
|
| 376 |
+
layer_type = decoder_layer.layer_type
|
| 377 |
+
position_embeddings = rope_cache.get(layer_type, rope_cache.get("full_attention"))
|
| 378 |
+
layer_attention_mask = causal_mask_mapping.get(layer_type, causal_mask_mapping.get("full_attention"))
|
| 379 |
+
|
| 380 |
+
if self.gradient_checkpointing and self.training:
|
| 381 |
+
layer_outputs = self._gradient_checkpointing_func(
|
| 382 |
+
decoder_layer.__call__,
|
| 383 |
+
hidden_states,
|
| 384 |
+
position_embeddings,
|
| 385 |
+
layer_attention_mask,
|
| 386 |
+
)
|
| 387 |
+
hidden_states = layer_outputs[0] if isinstance(layer_outputs, tuple) else layer_outputs
|
| 388 |
+
else:
|
| 389 |
+
hidden_states = decoder_layer(
|
| 390 |
+
hidden_states,
|
| 391 |
+
position_embeddings=position_embeddings,
|
| 392 |
+
attention_mask=layer_attention_mask,
|
| 393 |
+
past_key_values=past_key_values,
|
| 394 |
+
cache_position=cache_position,
|
| 395 |
+
position_ids=position_ids,
|
| 396 |
+
)
|
| 397 |
+
|
| 398 |
+
hidden_states = self.norm(hidden_states)
|
| 399 |
+
hidden_states = hidden_states.to(dtype)
|
| 400 |
+
|
| 401 |
+
return BaseModelOutputWithPast(
|
| 402 |
+
last_hidden_state=hidden_states,
|
| 403 |
+
past_key_values=past_key_values if use_cache else None,
|
| 404 |
+
)
|
| 405 |
+
|
| 406 |
+
class Spark2_5ForCausalLM(Spark2_5PreTrainedModel, GenerationMixin):
|
| 407 |
+
_tied_weights_keys = {"lm_head.weight": "model.embedding.weight"} # noqa: RUF012
|
| 408 |
+
|
| 409 |
+
def __init__(self, config):
|
| 410 |
+
super().__init__(config)
|
| 411 |
+
self.model = Spark2_5Model(config)
|
| 412 |
+
self.vocab_size = config.vocab_size
|
| 413 |
+
self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
|
| 414 |
+
self.post_init()
|
| 415 |
+
|
| 416 |
+
def get_input_embeddings(self):
|
| 417 |
+
return self.model.embedding
|
| 418 |
+
|
| 419 |
+
def set_input_embeddings(self, value):
|
| 420 |
+
self.model.embedding = value
|
| 421 |
+
|
| 422 |
+
def get_output_embeddings(self):
|
| 423 |
+
return self.lm_head
|
| 424 |
+
|
| 425 |
+
def set_output_embeddings(self, new_embeddings):
|
| 426 |
+
self.lm_head = new_embeddings
|
| 427 |
+
|
| 428 |
+
def set_decoder(self, decoder):
|
| 429 |
+
self.model = decoder
|
| 430 |
+
|
| 431 |
+
def get_decoder(self):
|
| 432 |
+
return self.model
|
| 433 |
+
|
| 434 |
+
@can_return_tuple
|
| 435 |
+
def forward(
|
| 436 |
+
self,
|
| 437 |
+
input_ids: torch.LongTensor = None,
|
| 438 |
+
attention_mask: torch.Tensor | None = None,
|
| 439 |
+
position_ids: torch.LongTensor | None = None,
|
| 440 |
+
past_key_values: Cache | list[torch.FloatTensor] | None = None,
|
| 441 |
+
inputs_embeds: torch.FloatTensor | None = None,
|
| 442 |
+
labels: torch.LongTensor | None = None,
|
| 443 |
+
use_cache: bool | None = None,
|
| 444 |
+
cache_position: torch.LongTensor | None = None,
|
| 445 |
+
logits_to_keep: int = 0,
|
| 446 |
+
token_type_ids: torch.LongTensor | None = None,
|
| 447 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 448 |
+
) -> CausalLMOutputWithPast:
|
| 449 |
+
outputs: BaseModelOutputWithPast = self.model(
|
| 450 |
+
input_ids=input_ids,
|
| 451 |
+
attention_mask=attention_mask,
|
| 452 |
+
position_ids=position_ids,
|
| 453 |
+
past_key_values=past_key_values,
|
| 454 |
+
inputs_embeds=inputs_embeds,
|
| 455 |
+
use_cache=use_cache,
|
| 456 |
+
cache_position=cache_position,
|
| 457 |
+
)
|
| 458 |
+
|
| 459 |
+
hidden_states = outputs.last_hidden_state
|
| 460 |
+
slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
|
| 461 |
+
hidden_states = hidden_states[:, slice_indices, :]
|
| 462 |
+
|
| 463 |
+
if self.config.tie_word_embeddings:
|
| 464 |
+
embed_weight = self.model.embedding.weight
|
| 465 |
+
logits = F.linear(hidden_states, embed_weight)
|
| 466 |
+
else:
|
| 467 |
+
logits = self.lm_head(hidden_states)
|
| 468 |
+
|
| 469 |
+
loss = None
|
| 470 |
+
if labels is not None:
|
| 471 |
+
loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs)
|
| 472 |
+
|
| 473 |
+
return CausalLMOutputWithPast(
|
| 474 |
+
loss=loss,
|
| 475 |
+
logits=logits,
|
| 476 |
+
past_key_values=outputs.past_key_values,
|
| 477 |
+
hidden_states=outputs.hidden_states,
|
| 478 |
+
attentions=outputs.attentions,
|
| 479 |
+
)
|
| 480 |
+
|
| 481 |
+
|
| 482 |
+
__all__ = ["Spark2_5Config", "Spark2_5ForCausalLM", "Spark2_5Model"]
|
special_tokens_map.json
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"bos_token": "<|start▁of▁sentence|>",
|
| 3 |
+
"eos_token": "<|end▁of▁sentence|>",
|
| 4 |
+
"unk_token": "<unk>",
|
| 5 |
+
"pad_token": "<|▁pad▁|>"
|
| 6 |
+
}
|
tokenizer.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
tokenizer_config.json
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"add_bos_token": false,
|
| 3 |
+
"add_eos_token": false,
|
| 4 |
+
"bos_token": {
|
| 5 |
+
"__type": "AddedToken",
|
| 6 |
+
"content": "<|start▁of▁sentence|>",
|
| 7 |
+
"lstrip": false,
|
| 8 |
+
"normalized": true,
|
| 9 |
+
"rstrip": false,
|
| 10 |
+
"single_word": false
|
| 11 |
+
},
|
| 12 |
+
"clean_up_tokenization_spaces": false,
|
| 13 |
+
"eos_token": {
|
| 14 |
+
"__type": "AddedToken",
|
| 15 |
+
"content": "<|end▁of▁sentence|>",
|
| 16 |
+
"lstrip": false,
|
| 17 |
+
"normalized": true,
|
| 18 |
+
"rstrip": false,
|
| 19 |
+
"single_word": false
|
| 20 |
+
},
|
| 21 |
+
"legacy": true,
|
| 22 |
+
"model_max_length": 131072,
|
| 23 |
+
"pad_token": {
|
| 24 |
+
"__type": "AddedToken",
|
| 25 |
+
"content": "<|▁pad▁|>",
|
| 26 |
+
"lstrip": false,
|
| 27 |
+
"normalized": true,
|
| 28 |
+
"rstrip": false,
|
| 29 |
+
"single_word": false
|
| 30 |
+
},
|
| 31 |
+
"sp_model_kwargs": {},
|
| 32 |
+
"unk_token": {
|
| 33 |
+
"__type": "AddedToken",
|
| 34 |
+
"content": "<unk>",
|
| 35 |
+
"lstrip": false,
|
| 36 |
+
"normalized": true,
|
| 37 |
+
"rstrip": false,
|
| 38 |
+
"single_word": false
|
| 39 |
+
},
|
| 40 |
+
"tokenizer_class": "PreTrainedTokenizerFast",
|
| 41 |
+
"chat_template": "{%- 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 %}"
|
| 42 |
+
}
|
vocab.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|