OceanLabs
/

roskosmos19 zhou94539 commited on
Commit
ce1eb7d
·
0 Parent(s):

Duplicate from IFM/K2-Horizon-3.7B

Browse files

Co-authored-by: Kevin Zhou <zhou94539@users.noreply.huggingface.co>

Files changed (48) hide show
  1. .gitattributes +38 -0
  2. APPENDIX.md +483 -0
  3. README.md +224 -0
  4. assets/k2-horizon-3.7b-benchmarks.png +3 -0
  5. chat_template.jinja +994 -0
  6. config.json +92 -0
  7. configuration_k2_horizon.py +96 -0
  8. generation_config.json +7 -0
  9. model.safetensors.index.json +334 -0
  10. modeling_k2_horizon.py +1116 -0
  11. pytorch_model-00001-of-00036.safetensors +3 -0
  12. pytorch_model-00002-of-00036.safetensors +3 -0
  13. pytorch_model-00003-of-00036.safetensors +3 -0
  14. pytorch_model-00004-of-00036.safetensors +3 -0
  15. pytorch_model-00005-of-00036.safetensors +3 -0
  16. pytorch_model-00006-of-00036.safetensors +3 -0
  17. pytorch_model-00007-of-00036.safetensors +3 -0
  18. pytorch_model-00008-of-00036.safetensors +3 -0
  19. pytorch_model-00009-of-00036.safetensors +3 -0
  20. pytorch_model-00010-of-00036.safetensors +3 -0
  21. pytorch_model-00011-of-00036.safetensors +3 -0
  22. pytorch_model-00012-of-00036.safetensors +3 -0
  23. pytorch_model-00013-of-00036.safetensors +3 -0
  24. pytorch_model-00014-of-00036.safetensors +3 -0
  25. pytorch_model-00015-of-00036.safetensors +3 -0
  26. pytorch_model-00016-of-00036.safetensors +3 -0
  27. pytorch_model-00017-of-00036.safetensors +3 -0
  28. pytorch_model-00018-of-00036.safetensors +3 -0
  29. pytorch_model-00019-of-00036.safetensors +3 -0
  30. pytorch_model-00020-of-00036.safetensors +3 -0
  31. pytorch_model-00021-of-00036.safetensors +3 -0
  32. pytorch_model-00022-of-00036.safetensors +3 -0
  33. pytorch_model-00023-of-00036.safetensors +3 -0
  34. pytorch_model-00024-of-00036.safetensors +3 -0
  35. pytorch_model-00025-of-00036.safetensors +3 -0
  36. pytorch_model-00026-of-00036.safetensors +3 -0
  37. pytorch_model-00027-of-00036.safetensors +3 -0
  38. pytorch_model-00028-of-00036.safetensors +3 -0
  39. pytorch_model-00029-of-00036.safetensors +3 -0
  40. pytorch_model-00030-of-00036.safetensors +3 -0
  41. pytorch_model-00031-of-00036.safetensors +3 -0
  42. pytorch_model-00032-of-00036.safetensors +3 -0
  43. pytorch_model-00033-of-00036.safetensors +3 -0
  44. pytorch_model-00034-of-00036.safetensors +3 -0
  45. pytorch_model-00035-of-00036.safetensors +3 -0
  46. pytorch_model-00036-of-00036.safetensors +3 -0
  47. tokenizer.json +3 -0
  48. tokenizer_config.json +10 -0
.gitattributes ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
5
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
6
+ *.ftz filter=lfs diff=lfs merge=lfs -text
7
+ *.gz filter=lfs diff=lfs merge=lfs -text
8
+ *.h5 filter=lfs diff=lfs merge=lfs -text
9
+ *.joblib filter=lfs diff=lfs merge=lfs -text
10
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
+ *.model filter=lfs diff=lfs merge=lfs -text
13
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
14
+ *.npy filter=lfs diff=lfs merge=lfs -text
15
+ *.npz filter=lfs diff=lfs merge=lfs -text
16
+ *.onnx filter=lfs diff=lfs merge=lfs -text
17
+ *.ot filter=lfs diff=lfs merge=lfs -text
18
+ *.parquet filter=lfs diff=lfs merge=lfs -text
19
+ *.pb filter=lfs diff=lfs merge=lfs -text
20
+ *.pickle filter=lfs diff=lfs merge=lfs -text
21
+ *.pkl filter=lfs diff=lfs merge=lfs -text
22
+ *.pt filter=lfs diff=lfs merge=lfs -text
23
+ *.pth filter=lfs diff=lfs merge=lfs -text
24
+ *.rar filter=lfs diff=lfs merge=lfs -text
25
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
26
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
28
+ *.tar filter=lfs diff=lfs merge=lfs -text
29
+ *.tflite filter=lfs diff=lfs merge=lfs -text
30
+ *.tgz filter=lfs diff=lfs merge=lfs -text
31
+ *.wasm filter=lfs diff=lfs merge=lfs -text
32
+ *.xz filter=lfs diff=lfs merge=lfs -text
33
+ *.zip filter=lfs diff=lfs merge=lfs -text
34
+ *.zst filter=lfs diff=lfs merge=lfs -text
35
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ assets/k2-horizon-3-7b-training-loss-vs-tokens.png filter=lfs diff=lfs merge=lfs -text
37
+ tokenizer.json filter=lfs diff=lfs merge=lfs -text
38
+ k2-horizon-3.7b-benchmarks.png filter=lfs diff=lfs merge=lfs -text
APPENDIX.md ADDED
@@ -0,0 +1,483 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # K2-Horizon-3.7B Technical Appendix
2
+
3
+ This appendix contains the detailed architecture, checkpoint, training, deployment, hardware, evaluation, dataset, source-code, intended-use, and safety material moved from the full model card. The short [README](README.md) follows the common K2-Horizon release format.
4
+
5
+ ## Model Series Overview
6
+
7
+ K2-Horizon is released as a family of checkpoints that share the same post-training recipe, release process, and user-facing deployment guidance while covering dense, MoE, and MoVA configurations. The table below summarizes the public family view; individual repositories contain the files and branches for one model size.
8
+
9
+ | Model | Architecture | Stored parameters | Active parameters/token | Context length | Vocab size | Intended use |
10
+ | --- | --- | --- | --- | --- | --- | --- |
11
+ | K2-Horizon-0.9B | K2HorizonForCausalLM; dense decoder-only | 0.9B | 0.9B | 8,192 | 64,256 | Lightweight experimentation, local development, evaluation dry runs |
12
+ | K2-Horizon-3.7B | XllmForCausalLM; dense decoder-only | 5.06B | 5.06B | 524,288 | 250,624 | Efficient research, evaluation, and single-node serving |
13
+ | K2-Horizon-7B | XllmForCausalLM; dense decoder-only | 9.00B | 9.00B | 524,288 | 250,624 | General research, fine-tuning, and cost-conscious deployment |
14
+ | K2-Horizon-32B | K2HorizonForCausalLM; dense decoder-only | 34.78B | 34.78B | 524,288 | 250,624 | Stronger long-context and reasoning experiments |
15
+ | K2-Horizon-36B | K2HorizonForCausalLM; MoVA + MoE | 37.44B | 5.95B | 524,288 | 250,624 | Multistage research and production-style serving experiments |
16
+ | K2-Horizon-375B | XllmForCausalLM; sparse MoE | 379.17B | 26.67B | 524,288 | 250,624 | Frontier-scale open research, long-context evaluation, and high-capacity serving |
17
+
18
+ Tokenizer files are distributed with each model repository. The compact K2-Horizon-0.9B model comes from the IFM Mobile line and uses a 64,256-token vocabulary. The 3.7B, 7B, 32B, 36B, and 375B models use a 250,624-token vocabulary.
19
+
20
+ The native 0.9B `main`, 32B `mid_4`, and 36B `main`/`mid_4` revisions publish `K2HorizonForCausalLM`, `model_type: k2_horizon`, and matching `configuration_k2_horizon.py` and `modeling_k2_horizon.py` modules. The deployment preflights below validate that public contract before loading weights.
21
+
22
+ ## This Repository
23
+
24
+ | Field | Value |
25
+ | --- | --- |
26
+ | Model name | K2-Horizon-3.7B |
27
+ | Repository | IFM/K2-Horizon-3.7B |
28
+ | Model family | K2-Horizon |
29
+ | Architecture class | XllmForCausalLM |
30
+ | Classification | Dense |
31
+ | Stored parameters | 3.78B core; 5.06B including embeddings |
32
+ | Active parameters per token | 3.78B core; 5.06B including embeddings |
33
+ | Context length | 512K tokens |
34
+ | Transformer layers | 36 |
35
+ | Hidden size | 2,560 |
36
+ | Dense / expert intermediate size | 10,240 / 0 |
37
+ | Attention heads / KV heads | 32 / 8 |
38
+ | Dense attention / sparse attention blocks | 36 / 0 |
39
+ | Dense FFN / sparse FFN blocks | 36 / 0 |
40
+ | MoE experts / active experts | 0 / 0 |
41
+ | MoVA count / active values | 0 / 0 |
42
+ | Vocab size | 250,624 |
43
+ | Tokenizer metadata | Hugging Face tokenizer files; vocab size 250,624 |
44
+ | Checkpoint storage dtype | float32 (FP32) |
45
+ | Checkpoint config dtype metadata | float32 |
46
+ | Evaluation and sample dtype | bfloat16 (BF16) |
47
+ | Shard/index summary | 36 shards |
48
+
49
+ ## Checkpoint Revisions
50
+
51
+ Each repository uses branches for model stages and stable tags for specific checkpoints. Pin a revision tag when reproducibility matters; use `main` for the default model checkpoint.
52
+
53
+ | Stage | Branch | Revision tag | Max context | Description |
54
+ | --- | --- | --- | --- | --- |
55
+ | Base / pretraining | `pretrain` | `base_final` | 8K tokens | Base model checkpoint |
56
+ | Midtraining 1 | `mid_1` | `mid_1_final` | 32K tokens | Midtraining 1 checkpoint |
57
+ | Midtraining 2 | `mid_2` | `mid_2_final` | 128K tokens | Midtraining 2 checkpoint |
58
+ | Midtraining 3 | `mid_3` | `mid_3_final` | 512K tokens | Midtraining 3 checkpoint |
59
+ | Midtraining 4 | `mid_4` | `mid_4_final` | 512K tokens | Midtraining 4 checkpoint |
60
+ | Default | `main` | `main` | 512K tokens | Default release view of `mid_4_final` |
61
+
62
+ Example revision pinning:
63
+
64
+ <details>
65
+ <summary>Show revision pinning example</summary>
66
+
67
+ ```python
68
+ # Validated with Python 3.14,
69
+ # Transformers 4.57.6, and
70
+ # Safetensors 0.8.0.
71
+ from transformers import AutoModelForCausalLM, AutoTokenizer
72
+
73
+ model_id = "IFM/K2-Horizon-3.7B"
74
+ revision = "mid_4_final"
75
+
76
+ tokenizer = AutoTokenizer.from_pretrained(model_id, revision=revision, trust_remote_code=True)
77
+ model = AutoModelForCausalLM.from_pretrained(
78
+ model_id,
79
+ revision=revision,
80
+ device_map="auto",
81
+ dtype="bfloat16",
82
+ low_cpu_mem_usage=True,
83
+ trust_remote_code=True,
84
+ )
85
+ ```
86
+
87
+ </details>
88
+
89
+
90
+
91
+ ## Training Provenance
92
+
93
+ Each row identifies the last W&B process record associated with the selected checkpoint, together with its Slurm job and exact xLLM source revision. A training stage can span multiple W&B process records when checkpointed training is resumed.
94
+
95
+ | Stage | Revision | Checkpoint context | xLLM source | W&B last run | Slurm job | Training nodes |
96
+ | --- | --- | --- | --- | --- | --- | --- |
97
+ | Base / pretraining | `base_final` | 8K tokens | [`ad6dac16`](https://github.com/LLM360/xllm/commit/ad6dac16031ae74d3e02c10bf3f37384815503a2) | [`k2v3-4b/aici7hvs`](https://wandb.ai/mbzuai-llm/k2v3-4b/runs/aici7hvs) | `423852` | 38 |
98
+ | Midtraining 1 | `mid_1_final` | 32K tokens | [`b69a6b2e`](https://github.com/LLM360/xllm/commit/b69a6b2ed17091dfee8af68a570f78816f765bad) | [`k2v3_midtrain/um64dwov`](https://wandb.ai/mbzuai-llm/k2v3_midtrain/runs/um64dwov) | `498823` | 38 |
99
+ | Midtraining 2 | `mid_2_final` | 128K tokens | [`b69a6b2e`](https://github.com/LLM360/xllm/commit/b69a6b2ed17091dfee8af68a570f78816f765bad) | [`k2v3_midtrain/axxd0ylh`](https://wandb.ai/mbzuai-llm/k2v3_midtrain/runs/axxd0ylh) | `504283` | 38 |
100
+ | Midtraining 3 | `mid_3_final` | 512K tokens | [`198c2fb6`](https://github.com/LLM360/xllm/commit/198c2fb61457529d7d790550acd0f937da931112) | [`k2v3_midtrain/9qm67nzz`](https://wandb.ai/mbzuai-llm/k2v3_midtrain/runs/9qm67nzz) | `966354` | 38 |
101
+ | Midtraining 4 | `mid_4_final` | 512K tokens | [`5494c84c`](https://github.com/LLM360/xllm/commit/5494c84cc7a2a66e5d6439bf9aa07454097ce9be) | [`k2v3_midtrain/0fhhm8wn`](https://wandb.ai/mbzuai-llm/k2v3_midtrain/runs/0fhhm8wn) | `980739` | 38 |
102
+
103
+
104
+
105
+ ## Training Loss
106
+
107
+ The chart reconstructs the release checkpoint lineage for Pretraining, Midtraining 1, Midtraining 2, Midtraining 3, Midtraining 4. Training loss is the next-token prediction objective; lower values indicate that the model assigns greater probability to the observed next token. Training loss is not a validation score and should not be compared across different tokenizers or data mixtures without additional controls.
108
+
109
+ ![K2-Horizon-3.7B training loss versus cumulative training tokens](./assets/k2-horizon-3-7b-training-loss-vs-tokens.png)
110
+
111
+ Each panel combines the W&B process records that contribute to the release checkpoint. Faint lines show sampled raw training loss; bold lines show an unpadded centered moving average with a raised-cosine taper over the final half-window. The final sample retains 20% of its base weight, limiting right-edge bias without hiding the raw tail. Checkpoint restart overlap is replaced by the later process record.
112
+
113
+
114
+ ## Deployment Guide
115
+
116
+ These are base checkpoints. They can be served for research, evaluation, retrieval-augmented generation experiments, tool-use research, and downstream adaptation. They are not instruction-aligned assistants by default, so production deployments should add application-level safety filters, system prompting, and task-specific validation.
117
+
118
+ All reported K2-Horizon evaluation used BF16. Some released checkpoint shards and configuration metadata remain FP32; the examples below explicitly load or serve them as BF16 to match the evaluation runtime and reduce accelerator memory usage.
119
+
120
+ ### Validated Independent Dependency Versions
121
+
122
+ Use a separate Python environment for every workflow. Direct Transformers loading, xLLM conversion, vLLM, and the pinned SGLang production revision have independent dependency contracts. Do not install one row into another row's environment. Versions intentionally differ when a framework or remote-model contract requires them.
123
+
124
+ | Workflow | Python | PyTorch | CUDA | Transformers | Safetensors | Attention kernel | Framework revision |
125
+ | --- | --- | --- | --- | --- | --- | --- | --- |
126
+ | Direct Transformers loading | 3.14 | 2.13.0 | 12.6 | 4.57.6 | 0.8.0 | PyTorch SDPA 2.13.0 | Transformers 4.57.6 remote code |
127
+ | xLLM checkpoint conversion | 3.12 | 2.8.0 | 12.8 | 4.57.3 | 0.8.0 | FlashAttention 2.8.3.post1 | xLLM `7cfa3b2c` |
128
+ | vLLM serving | 3.12 | 2.13.0 | 12.9 | 5.16.1 | 0.8.0 | FlashInfer 0.6.17 | vLLM 0.26.1rc1.dev1212 source `d9fd5f11` (PR #53806) |
129
+ | SGLang serving | 3.12 | 2.9.1 | 12.8 (CUDA Python 12.9) | 5.3.0 | 0.8.0 | FA3 (sglang-kernel 0.4.1); FlashInfer 0.6.7.post2 available | SGLang `ffb41d77` (stable-only metadata) |
130
+
131
+ ### Inference Parameter Starting Points
132
+
133
+ K2-Horizon does not use one family-wide sampling preset. The values below are operational baselines: temperature 0 is the validated deterministic serving comparison, while sampled settings are conservative starting points that should be tuned on application prompts. Benchmark reproduction must use the decoding configuration attached to that benchmark.
134
+
135
+ | Use case | Temperature | Top-p | Max new tokens | Notes |
136
+ | --- | --- | --- | --- | --- |
137
+ | Checkpoint smoke test and deterministic evaluation | 0.0 | 1.0 | 512-4,096 | Greedy decoding is the reproducible baseline used by serving comparisons. |
138
+ | Base-model continuation | 0.6 | 0.95 | 1,024-4,096 | A conservative sampling baseline; tune on a held-out prompt set. |
139
+ | Long-context continuation or summarization | 0.2 | 0.9 | 2,048-8,192 | Start with one request and increase context only after KV-cache capacity checks. |
140
+ | Reasoning and tool-call validation | 0.0 | 1.0 | 4,096 | Use a compatible chat template and the K2Horizon parser stack below. |
141
+
142
+ ### Transformers
143
+
144
+ The selected default checkpoint is loaded with Transformers 4.57.6 and PyTorch 2.13.0 on CUDA 12.6. Select the corresponding PyTorch build for your accelerator when that CUDA runtime is unavailable. The selected checkpoint uses the self-contained legacy `XllmForCausalLM` remote implementation. Its saved Transformers 4.57.3 contract is compatible with stable 4.57.6, PyTorch SDPA, and no external xLLM or FlashAttention package. xLLM conversion remains isolated below because its native build has a different runtime contract.
145
+
146
+ <details>
147
+ <summary>Show Transformers installation commands</summary>
148
+
149
+ ```bash
150
+ python -m pip install "torch==2.13.0" \
151
+ --index-url "https://download.pytorch.org/whl/cu126"
152
+ python -m pip install \
153
+ "transformers==4.57.6" \
154
+ "safetensors==0.8.0" \
155
+ "accelerate==1.14.0"
156
+ ```
157
+
158
+ </details>
159
+
160
+ <details>
161
+ <summary>Show Transformers inference example</summary>
162
+
163
+ ```python
164
+ from transformers import AutoModelForCausalLM, AutoTokenizer
165
+
166
+ MODEL_ID = "IFM/K2-Horizon-3.7B"
167
+ REVISION = "mid_4"
168
+
169
+ tokenizer = AutoTokenizer.from_pretrained(
170
+ MODEL_ID,
171
+ revision=REVISION,
172
+ trust_remote_code=True,
173
+ )
174
+ model = AutoModelForCausalLM.from_pretrained(
175
+ MODEL_ID,
176
+ revision=REVISION,
177
+ device_map="auto",
178
+ dtype="bfloat16",
179
+ low_cpu_mem_usage=True,
180
+ trust_remote_code=True,
181
+ )
182
+
183
+ prompt = "Explain why long-context evaluation is difficult."
184
+ inputs = tokenizer(prompt, return_tensors="pt").to(model.device)
185
+ inputs.pop("token_type_ids", None)
186
+ outputs = model.generate(
187
+ **inputs,
188
+ max_new_tokens=512,
189
+ temperature=0.7,
190
+ top_p=0.9,
191
+ do_sample=True,
192
+ )
193
+ print(tokenizer.decode(outputs[0], skip_special_tokens=True))
194
+ ```
195
+
196
+ </details>
197
+
198
+ ### xLLM
199
+
200
+ xLLM provides the training framework, checkpoint converter, serving bridges, and runtime kernels used by the XLLM-based K2-Horizon repositories. For checkpoint conversion, parity work, or loading a legacy 36B `XllmForCausalLM` stage that imports xLLM MoVA kernels, use the isolated legacy contract and reviewed bridge revision [`7cfa3b2c`](https://github.com/LLM360/xllm/commit/7cfa3b2c61fad3b2ef48f7f7b497ef360087c72f):
201
+
202
+ <details>
203
+ <summary>Show xLLM setup and conversion commands</summary>
204
+
205
+ ```bash
206
+ git clone https://github.com/LLM360/xllm.git
207
+ cd xllm
208
+ git checkout 7cfa3b2c61fad3b2ef48f7f7b497ef360087c72f
209
+
210
+ python -m pip install "torch==2.8.0" \
211
+ --index-url "https://download.pytorch.org/whl/cu128"
212
+ export XLLM_BUILD_ROOT="${XLLM_BUILD_ROOT:-$PWD/.xllm-build}"
213
+ export TMPDIR="$XLLM_BUILD_ROOT/tmp"
214
+ export PIP_CACHE_DIR="$XLLM_BUILD_ROOT/pip-cache"
215
+ mkdir -p "$TMPDIR" "$PIP_CACHE_DIR"
216
+ python -m pip install packaging ninja
217
+ python -m pip install "https://github.com/Dao-AILab/flash-attention/releases/download/v2.8.3.post1/flash_attn-2.8.3.post1+cu12torch2.8cxx11abiTRUE-cp312-cp312-linux_x86_64.whl"
218
+ python -m pip install -r requirements.txt
219
+ python -m pip install -e . --no-build-isolation \
220
+ --config-settings editable_mode=compat
221
+ python -m pip install \
222
+ "transformers==4.57.3" \
223
+ "safetensors==0.8.0" \
224
+ accelerate fire
225
+
226
+ python xllm_bridges/huggingface/xllm_to_hf_main.py --help
227
+ ```
228
+
229
+ </details>
230
+
231
+ The converter requires an original xLLM distributed checkpoint and tokenizer. Released Hugging Face revisions are already converted and use the pure direct Transformers/SDPA contract above. Install xLLM only for conversion, parity work, or a model-specific native-kernel dependency. Pinning a revision does not make runtime contracts interchangeable.
232
+
233
+ ### vLLM
234
+
235
+ The example pins [vLLM PR #53806](https://github.com/vllm-project/vllm/pull/53806) at [`d9fd5f11`](https://github.com/vllm-project/vllm/commit/d9fd5f11423a1a5628fe29e7296ceb9de91aac3c). That source registers `K2HorizonForCausalLM` plus the built-in `k2_horizon` reasoning and tool parsers. The command uses vLLM's `transformers` model implementation for this checkpoint contract.
236
+
237
+ <details>
238
+ <summary>Show vLLM setup and serving commands</summary>
239
+
240
+ ```bash
241
+ git clone --filter=blob:none --no-checkout \
242
+ https://github.com/vllm-project/vllm.git
243
+ cd vllm
244
+ git fetch origin \
245
+ pull/53806/head:refs/remotes/origin/pr-53806
246
+ git checkout --detach d9fd5f11423a1a5628fe29e7296ceb9de91aac3c
247
+ test "$(git rev-parse HEAD)" = "d9fd5f11423a1a5628fe29e7296ceb9de91aac3c"
248
+
249
+ python3.12 -m venv .venv
250
+ source .venv/bin/activate
251
+ python -m pip install --upgrade pip uv
252
+ export UV_LINK_MODE=copy
253
+ VLLM_USE_PRECOMPILED=1 uv pip install --upgrade --editable . \
254
+ --torch-backend=auto
255
+ uv pip install \
256
+ "transformers==5.16.1" \
257
+ "safetensors==0.8.0"
258
+ python -m pip check
259
+
260
+ python - <<'PY'
261
+ from vllm import ModelRegistry
262
+ from vllm.reasoning import ReasoningParserManager
263
+ from vllm.tool_parsers import ToolParserManager
264
+
265
+ assert "K2HorizonForCausalLM" in ModelRegistry.get_supported_archs()
266
+ assert ReasoningParserManager.get_reasoning_parser("k2_horizon") is not None
267
+ assert ToolParserManager.get_tool_parser("k2_horizon") is not None
268
+ PY
269
+
270
+ export MODEL_ID="IFM/K2-Horizon-3.7B"
271
+ export MODEL_REVISION="mid_4"
272
+ export TENSOR_PARALLEL_SIZE=1
273
+ export MAX_MODEL_LEN=131072
274
+
275
+ vllm serve "$MODEL_ID" \
276
+ --revision "$MODEL_REVISION" \
277
+ --model-impl transformers \
278
+ --tensor-parallel-size "$TENSOR_PARALLEL_SIZE" \
279
+ --trust-remote-code \
280
+ --dtype bfloat16 \
281
+ --served-model-name "$MODEL_ID" \
282
+ --max-model-len "$MAX_MODEL_LEN" \
283
+ --reasoning-parser k2_horizon \
284
+ --enable-auto-tool-choice \
285
+ --tool-call-parser k2_horizon
286
+ ```
287
+
288
+ </details>
289
+
290
+ The source checkout is immutable at `d9fd5f11423a1a5628fe29e7296ceb9de91aac3c`. The command serves `mid_4`; the repository's longest checkpoint configuration reports 524,288 tokens, while this example starts at 131,072 tokens. Increase context and concurrency only after measuring KV-cache capacity. The preflight fails immediately if the native architecture or either Horizon parser registration is absent.
291
+
292
+ ### SGLang
293
+
294
+ Native K2 Horizon support is provided by
295
+ [sgl-project/sglang#37654](https://github.com/sgl-project/sglang/pull/37654).
296
+ Use a `lmsysorg/sglang:dev` image built after that PR is merged. Once support is
297
+ included in a tagged SGLang release, use the corresponding versioned image.
298
+
299
+ <details>
300
+ <summary>Show the SGLang serving command</summary>
301
+
302
+ ```bash
303
+ docker run --gpus all \
304
+ --shm-size 32g \
305
+ -p 30000:30000 \
306
+ -v ~/.cache/huggingface:/root/.cache/huggingface \
307
+ --ipc=host \
308
+ lmsysorg/sglang:dev \
309
+ python3 -m sglang.launch_server \
310
+ --model-path "IFM/K2-Horizon-3.7B" \
311
+ --revision main \
312
+ --tp 1 \
313
+ --dtype bfloat16 \
314
+ --context-length 131072 \
315
+ --attention-backend fa3 \
316
+ --reasoning-parser k2_horizon \
317
+ --tool-call-parser k2_horizon \
318
+ --mem-fraction-static 0.85 \
319
+ --host 0.0.0.0 \
320
+ --port 30000
321
+ ```
322
+
323
+ </details>
324
+
325
+ This uses SGLang's native `K2HorizonForCausalLM` implementation; no
326
+ `--trust-remote-code`, source patch, or external parser plugin is required. The
327
+ 131,072-token limit is a conservative starting point; increase it only after
328
+ measuring KV-cache capacity.
329
+
330
+ ### Reasoning and Tool Parsers
331
+
332
+ Parser configuration is part of the deployment contract. The canonical K2-Horizon format uses `<ifm|...>` reasoning and tool tokens; test streaming and non-streaming responses before exposing an OpenAI-compatible endpoint.
333
+
334
+ | Goal | vLLM guidance | SGLang guidance | When to use |
335
+ | --- | --- | --- | --- |
336
+ | Plain text generation | Do not enable a reasoning or tool parser. | Do not enable a reasoning or tool parser. | Base-model evaluation, completion-style generation, and checkpoint smoke tests. |
337
+ | Canonical K2-Horizon reasoning | Use the built-in `--reasoning-parser k2_horizon`. | Use `--reasoning-parser k2_horizon`. | Checkpoints and chat templates using `<ifm|think>`, `<ifm|think_fast>`, or `<ifm|think_faster>`. |
338
+ | Canonical K2-Horizon tool calls | Use `--enable-auto-tool-choice --tool-call-parser k2_horizon`. | Use `--tool-call-parser k2_horizon`. | XML, typed-XML, or JSON calls wrapped in `<ifm|tool_call>`. |
339
+ | Legacy K2 reasoning traces | Use the legacy parser only in a compatibility image that registers it. | Use `--reasoning-parser k2_horizon_legacy`. | Older traces using `<think>`, `<think_fast>`, or `<think_faster>` instead of canonical IFM tokens. |
340
+ | Mixed tool-call corpora | Use `multi_format` only in a build that includes and tests that parser. | Use `--tool-call-parser multi_format`. | Evaluation corpora that intentionally mix K2, GLM, or JSON tool-call dialects. |
341
+
342
+ PR #53806 registers both Horizon parsers in-tree; no external parser plugin is required.
343
+
344
+ For OpenAI-compatible requests, select reasoning effort through chat-template kwargs:
345
+
346
+ <details>
347
+ <summary>Show OpenAI-compatible request example</summary>
348
+
349
+ ```python
350
+ from openai import OpenAI
351
+
352
+ client = OpenAI(base_url="http://localhost:8000/v1", api_key="unused")
353
+ response = client.chat.completions.create(
354
+ model="IFM/K2-Horizon-3.7B",
355
+ messages=[{"role": "user", "content": "Explain the result step by step."}],
356
+ temperature=0,
357
+ max_tokens=4096,
358
+ extra_body={"chat_template_kwargs": {"reasoning_effort": "high"}},
359
+ )
360
+ print(response.choices[0].message)
361
+ ```
362
+
363
+ </details>
364
+
365
+ ### Other Serving Frameworks
366
+
367
+ Text Generation Inference, TensorRT-LLM, llama.cpp, Ollama, and LM Studio may require model-specific conversion, quantization, or custom architecture support. Validate tokenizer behavior, remote-code requirements, attention implementation, and long-context behavior before publishing service results.
368
+
369
+
370
+ ## Hardware Planning
371
+
372
+ The table below gives capacity-planning starting points for self-hosted inference. Weight memory uses the parameter count including input and output embeddings. On-disk FP32 shards and dtype conversion can require substantially more host RAM during loading than the final BF16 GPU footprint. KV-cache estimates use BF16 keys and values for one request at the smaller of the model maximum and 128K tokens; batching, allocator overhead, activations, CUDA graphs, and framework workspaces require additional memory.
373
+
374
+ | Model | Stored params | Active params/token | BF16 weight memory | FP32 weight memory | BF16 KV cache / request | Starting TP | Recommended starting point |
375
+ | --- | --- | --- | --- | --- | --- | --- | --- |
376
+ | K2-Horizon-0.9B | 0.9B | 0.9B | 2.0 GiB | 4.0 GiB | 0.4 GiB @ 8K tokens | 1 | 1 GPU with 16 GiB is a practical starting point for the model's 8K context; allow additional memory for batching. |
377
+ | K2-Horizon-3.7B | 5.06B | 5.06B | 9.4 GiB | 18.8 GiB | 18.0 GiB @ 128K tokens | 1 | 1 GPU with 24 GiB can serve short contexts in BF16; use 48-80 GiB for larger KV caches and 128K-class requests. |
378
+ | K2-Horizon-7B | 9.00B | 9.00B | 16.8 GiB | 33.5 GiB | 18.0 GiB @ 128K tokens | 1 | 1 GPU with 40-48 GiB is suitable for short-context BF16 serving; 80 GiB is the practical starting point for 128K-class requests. |
379
+ | K2-Horizon-32B | 34.78B | 34.78B | 64.8 GiB | 129.6 GiB | 32.0 GiB @ 128K tokens | 2-4 | 1x 80 GiB fits BF16 weights only at short context; start with 2x 80 GiB for 128K requests and 4x 80 GiB for larger context or throughput. |
380
+ | K2-Horizon-36B | 37.44B | 5.95B | 69.7 GiB | 139.5 GiB | 24.0 GiB @ 128K tokens | 2-4 | Use at least 256 GiB of host RAM to load the current 139.5 GiB FP32 shard set. Start with 2x 80 GiB GPUs for BF16 weight sharding, or 1x H200 141 GiB for short single-request validation; use 4x 80 GiB for 128K-class requests. |
381
+ | K2-Horizon-375B | 379.17B | 26.67B | 706.3 GiB | 1.38 TiB | 30.5 GiB @ 128K tokens | 8 H200 or 16x 80 GiB | The full 512K profile is validated on 8x H200 141 GiB GPUs at TP=8 and 0.92 memory utilization; use at least 16x 80 GiB GPUs on lower-memory hardware. |
382
+
383
+ ## Evaluation
384
+
385
+ Benchmark values are reported as percentages unless otherwise noted. A dash means the metric was not reported for that model or revision in the release evaluation records. The family tables below use each model's latest listed midtraining release checkpoint.
386
+
387
+ ### Family Evaluation: Knowledge and Instruction Following
388
+
389
+ | Model | Revision | IFEval | MMLU-Pro | MMLU | BBH |
390
+ | --- | --- | --- | --- | --- | --- |
391
+ | K2-Horizon-0.9B | `mid_2_final` | 43.1 | 40.3 | 44.4 | 43.8 |
392
+ | K2-Horizon-3.7B | `mid_4_final` | 85.7 | 73.0 | 80.7 | 84.4 |
393
+ | K2-Horizon-7B | `mid_4_final` | 89.9 | 75.7 | 83.3 | 87.8 |
394
+ | K2-Horizon-32B | `mid_4_final` | 88.0 | 79.5 | 87.5 | 89.1 |
395
+ | K2-Horizon-36B | `mid_4_final` | 89.6 | 79.2 | 87.3 | 88.6 |
396
+ | K2-Horizon-375B | `mid_4_final` | 92.1 | 82.6 | 89.5 | 87.5 |
397
+
398
+ ### Family Evaluation: STEM, Reasoning, and Coding
399
+
400
+ | Model | Revision | AIME26 | GPQA-Diamond | GSM8K | MBPP |
401
+ | --- | --- | --- | --- | --- | --- |
402
+ | K2-Horizon-0.9B | `mid_2_final` | 12.3 | 27.8 | 53.1 | 53.2 |
403
+ | K2-Horizon-3.7B | `mid_4_final` | 88.2 | 73.3 | 92.3 | 86.4 |
404
+ | K2-Horizon-7B | `mid_4_final` | 87.6 | 73.9 | 95.1 | 91.0 |
405
+ | K2-Horizon-32B | `mid_4_final` | 91.7 | 75.4 | 95.5 | 87.8 |
406
+ | K2-Horizon-36B | `mid_4_final` | 92.7 | 75.4 | 95.2 | 87.2 |
407
+ | K2-Horizon-375B | `mid_4_final` | 92.5 | 84.9 | 95.1 | 93.8 |
408
+
409
+ ### Family Evaluation: Agentic and Long-Context Tasks
410
+
411
+ | Model | Revision | SWE-Bench Verified (avg@3) | Terminal-Bench 2.1 (avg@3) | GDPval (acc@75%) | Tau3 Banking | BrowseComp+ (acc@1) | Apex Agents (pass@1) | WildClawBench | LCR |
412
+ | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
413
+ | K2-Horizon-7B | `mid_4_final` | 57.5 | 28.1 | 34.5 | 10.4 | 52.2 | 6.0 | 23.9 | - |
414
+ | K2-Horizon-375B | `mid_4_final` | 67.8 | 38.2 | 39.6 | 11.4 | 58.1 | 13.8 | 34.8 | 56.0 |
415
+
416
+ Agentic results are joined only to exact selected release checkpoints. SWE-Bench Verified and Terminal-Bench 2.1 report three-run averages where available; GDPval reports accuracy at 75 percent; BrowseComp+ reports accuracy at one; Apex Agents reports pass at one. Fractional workbook values are converted to percentages. When a source cell contains multiple reported aggregates, the first aggregate is shown unless the cell contains only three slash-separated trial values, in which case their mean is reported. A dash means the exact release checkpoint has no reported result for that benchmark.
417
+
418
+ ### Family Evaluation: Advanced Research Benchmarks
419
+
420
+ | Model | Revision | MCP Atlas | HLE | SciCode | OmniScience Accuracy | OmniScience Non-Hallucination | CritPT |
421
+ | --- | --- | --- | --- | --- | --- | --- | --- |
422
+ | K2-Horizon-7B | `mid_4_final` | 53.6 | 13.8 | - | - | 43.7 | - |
423
+ | K2-Horizon-375B | `mid_4_final` | 59.0 | 21.2 | 40.3 | 20.6 | 49.2 | 5.1 |
424
+
425
+ These results use exact final-stage checkpoint records. Benchmark availability differs by model, so unreported cells remain `-`.
426
+
427
+ ### This Repository: Base / Pretraining Snapshot
428
+
429
+ | Revision | ArabicMMLU | ARC-C | BBH | GPQA-Diamond-CoT | GSM8K | MMLU | MMLU-Pro | HumanEval | MBPP | IFEval |
430
+ | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
431
+ | `base_final` | 61.4 | 60.8 | 71.4 | 13.6 | 70.8 | 66.4 | 41.1 | 51.8 | 48.6 | 23.8 |
432
+
433
+ ### This Repository: Midtraining Snapshot
434
+
435
+ | Revision | IFEval avg | MMLU-Pro | GSM8K | MMLU | BBH | MBPP | AIME26 | GPQA-Diamond | LongBench-v2 | LCR | SWE-Bench Verified | Terminal Bench 2 |
436
+ | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
437
+ | `mid_1_final` | 84.6 | 72.2 | 95.2 | 80.7 | 84.9 | 88.8 | 71.5 | 52.0 | - | - | - | - |
438
+ | `mid_2_final` | 85.9 | 71.9 | 93.7 | 80.9 | 84.5 | 84.6 | 87.8 | 60.1 | - | - | - | - |
439
+ | `mid_3_final` | 83.3 | 71.9 | 93.9 | 81.0 | 84.5 | 84.6 | 87.9 | 61.9 | - | - | - | - |
440
+ | `mid_4_final` | 85.7 | 73.0 | 92.3 | 80.7 | 84.4 | 86.4 | 88.2 | 73.3 | - | - | - | - |
441
+
442
+
443
+
444
+ ### This Repository: RULER Long-Context Results
445
+
446
+ | Revision | 4K | 8K | 16K | 32K | 64K | 128K |
447
+ | --- | --- | --- | --- | --- | --- | --- |
448
+ | `mid_1_final` | 94.5 (13) | 92.7 (13) | 92.7 (13) | - | - | - |
449
+
450
+ RULER scores are macro-averages over the non-empty task columns in the exact checkpoint row. The number of contributing tasks is shown in parentheses.
451
+
452
+
453
+ ## Datasets and Mixtures
454
+
455
+ K2-Horizon training is organized around transparent data releases:
456
+
457
+ - Pretraining data: [IFM/K2-Horizon-Pretrain-Data](https://huggingface.co/datasets/IFM/K2-Horizon-Pretrain-Data), derived from the TxT360 lineage.
458
+ - Midtraining data: [IFM/K2-Horizon-Midtrain-Data](https://huggingface.co/datasets/IFM/K2-Horizon-Midtrain-Data), following the TxT360-Midas reasoning and long-context release pattern.
459
+ - The public data-preparation lineage is maintained in [LLM360/TxT360](https://github.com/LLM360/TxT360).
460
+
461
+ ## Source Code
462
+
463
+ - [LLM360/xllm](https://github.com/LLM360/xllm) - Training framework and Hugging Face/vLLM bridges. Per-stage training commits are linked in the provenance table.
464
+ - [LLM360/Eval360-V2 at `f5081bfb`](https://github.com/LLM360/Eval360-V2/commit/f5081bfba9ef8e7b380f5bd85ed1cf61a91f90b0) - Evaluation harness revision reviewed against the release benchmark workbooks.
465
+ - [LLM360/agent-evals at `f3788399`](https://github.com/LLM360/agent-evals/commit/f3788399a974e49121984f11556138f23f907cee) - Agentic benchmark harness, Slurm launchers, and serving profiles used to reconcile the agentic release results.
466
+ - [vLLM PR #53806 at `d9fd5f11`](https://github.com/vllm-project/vllm/commit/d9fd5f11423a1a5628fe29e7296ceb9de91aac3c) - Native K2-Horizon architecture plus built-in reasoning and tool parsers used by the serving example.
467
+ - [LLM360/Inference360 at `a7ee94f9`](https://github.com/LLM360/Inference360/commit/a7ee94f9ad9a561e65a67ede22d4e7a2c8428b57) - Serving-image and deployment-validation references.
468
+ - [LLM360/sglang at `ffb41d77`](https://github.com/LLM360/sglang/commit/ffb41d77d8b96b8a953351cb4d66d6bf4ed061a7) - SGLang serving base used by the hash-guarded K2-Horizon namespace migration.
469
+ - [LLM360/TxT360](https://github.com/LLM360/TxT360) - Public data-preparation and source-data lineage reference.
470
+
471
+ ## Intended Use
472
+
473
+ K2-Horizon-3.7B is intended for open research on foundation models, transparent evaluation, staged checkpoint analysis, downstream fine-tuning, and reproducibility studies. It is suitable for researchers and developers who want to inspect training-stage behavior, serve a model privately, compare model sizes, or build downstream adaptations.
474
+
475
+ ## Limitations and Safety
476
+
477
+ - This is a base checkpoint family and may produce inaccurate, biased, unsafe, or hallucinated content.
478
+ - The model is not optimized for moderation, refusal behavior, or production assistant safety.
479
+ - Long-context behavior depends on serving stack, prompt construction, retrieval quality, and KV-cache configuration.
480
+ - Tool-use and agentic results depend heavily on parser format, prompt template, tool schema, and execution harness.
481
+ - The model family is documented primarily with English-language evaluations; additional multilingual evaluation should be performed before broad multilingual claims.
482
+ - Users are responsible for complying with the model license and for validating deployments in their own risk domain.
483
+
README.md ADDED
@@ -0,0 +1,224 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ pipeline_tag: text-generation
3
+ library_name: transformers
4
+ model_name: K2-Horizon-3.7B
5
+ language:
6
+ - en
7
+ license: apache-2.0
8
+ datasets:
9
+ - IFM/K2-Horizon-Pretrain-Data
10
+ - IFM/K2-Horizon-Midtrain-Data
11
+ tags:
12
+ - k2-horizon
13
+ - 3.7b
14
+ - dense
15
+ - open-weights
16
+ - ifm
17
+ ---
18
+
19
+ # K2-Horizon-3.7B
20
+
21
+
22
+ K2-Horizon-3.7B is the small dense member of the K2-Horizon family: a 3.7B-core decoder-only model with a 512K context window.
23
+
24
+ <p align="center">
25
+ <img src="assets/k2-horizon-3.7b-benchmarks.png" alt="K2-Horizon-3.7B benchmark results" width="100%">
26
+ </p>
27
+
28
+ ## K2-Horizon-3.7B Highlights
29
+
30
+ - **Strong small-model baseline.** A dense model evaluated on the same agentic, coding, and reasoning benchmarks as the rest of the family.
31
+ - **512K context.** Native 524,288-token context from the midtraining stages onward.
32
+ - **Intermediate checkpoints.** Intermediate checkpoints are released so capability changes can be studied across training rather than at a single checkpoint.
33
+ - **Fully open.** Training data and recipe, training code, and evaluation resources are public.
34
+
35
+ ## Benchmark Results
36
+
37
+ The chart at the top of this card shows K2-Horizon-3.7B against selected reference models. The table below lists every comparison model used in the figure.
38
+
39
+ ### Full Results
40
+
41
+ <!-- TABLE:START -->
42
+ <div style="font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,sans-serif;margin:0 auto;padding:8px 0 16px;overflow-x:auto"><table style="display:table;width:100%;table-layout:fixed;border-collapse:collapse;font-size:12px;margin:0"><thead><tr><th style="width:30%;border-bottom:none"></th><th colspan="5" style="padding:6px 4px 2px;text-align:center;font-size:11px;font-weight:600;letter-spacing:0.04em;text-transform:uppercase;opacity:0.65;border-bottom:1px solid rgba(128,128,128,0.25)">Open-weight dense models</th></tr><tr><th style="padding:10px 6px;text-align:left;border-bottom:2px solid #2450D6"></th><th style="padding:10px 3px;text-align:center;font-weight:600;border-bottom:2px solid #2450D6;color:#2450D6;font-size:12.5px;line-height:1.2;width:14%;overflow-wrap:anywhere;background:rgba(36,80,214,0.08);">K2-Horizon-3.7B</th><th style="padding:10px 3px;text-align:center;font-weight:600;border-bottom:2px solid #2450D6;color:#2450D6;font-size:12.5px;line-height:1.2;width:14%;overflow-wrap:anywhere;">Qwen3.5-4B</th><th style="padding:10px 3px;text-align:center;font-weight:600;border-bottom:2px solid #2450D6;color:#2450D6;font-size:12.5px;line-height:1.2;width:14%;overflow-wrap:anywhere;">G9v3-3B</th><th style="padding:10px 3px;text-align:center;font-weight:600;border-bottom:2px solid #2450D6;color:#2450D6;font-size:12.5px;line-height:1.2;width:14%;overflow-wrap:anywhere;">Granite 4.2-3B</th><th style="padding:10px 3px;text-align:center;font-weight:600;border-bottom:2px solid #2450D6;color:#2450D6;font-size:12.5px;line-height:1.2;width:14%;overflow-wrap:anywhere;">Nemotron 3 Nano-4B</th></tr></thead><tbody><tr><td style="padding:7px 4px 7px 10px;border-bottom:1px solid rgba(128,128,128,0.15);vertical-align:middle;font-size:12.5px;font-weight:600"># Params</td><td style="padding:6px 2px;text-align:center;border-bottom:1px solid rgba(128,128,128,0.15);vertical-align:middle;font-size:12.5px;line-height:1.2;background:rgba(36,80,214,0.08);">3.7B</td><td style="padding:6px 2px;text-align:center;border-bottom:1px solid rgba(128,128,128,0.15);vertical-align:middle;font-size:12.5px;line-height:1.2;">4B</td><td style="padding:6px 2px;text-align:center;border-bottom:1px solid rgba(128,128,128,0.15);vertical-align:middle;font-size:12.5px;line-height:1.2;">3B</td><td style="padding:6px 2px;text-align:center;border-bottom:1px solid rgba(128,128,128,0.15);vertical-align:middle;font-size:12.5px;line-height:1.2;">3B</td><td style="padding:6px 2px;text-align:center;border-bottom:1px solid rgba(128,128,128,0.15);vertical-align:middle;font-size:12.5px;line-height:1.2;">4B</td></tr><tr><td style="padding:7px 4px 7px 10px;border-bottom:1px solid rgba(128,128,128,0.15);vertical-align:middle;font-size:12.5px;font-weight:600"># Activated params</td><td style="padding:6px 2px;text-align:center;border-bottom:1px solid rgba(128,128,128,0.15);vertical-align:middle;font-size:12.5px;line-height:1.2;background:rgba(36,80,214,0.08);">3.7B</td><td style="padding:6px 2px;text-align:center;border-bottom:1px solid rgba(128,128,128,0.15);vertical-align:middle;font-size:12.5px;line-height:1.2;">4B</td><td style="padding:6px 2px;text-align:center;border-bottom:1px solid rgba(128,128,128,0.15);vertical-align:middle;font-size:12.5px;line-height:1.2;">3B</td><td style="padding:6px 2px;text-align:center;border-bottom:1px solid rgba(128,128,128,0.15);vertical-align:middle;font-size:12.5px;line-height:1.2;">3B</td><td style="padding:6px 2px;text-align:center;border-bottom:1px solid rgba(128,128,128,0.15);vertical-align:middle;font-size:12.5px;line-height:1.2;">4B</td></tr><tr><td style="padding:7px 4px 7px 10px;border-bottom:1px solid rgba(128,128,128,0.15);vertical-align:middle;font-size:12.5px;font-weight:600">Architecture</td><td style="padding:6px 2px;text-align:center;border-bottom:1px solid rgba(128,128,128,0.15);vertical-align:middle;font-size:12.5px;line-height:1.2;background:rgba(36,80,214,0.08);">Dense</td><td style="padding:6px 2px;text-align:center;border-bottom:1px solid rgba(128,128,128,0.15);vertical-align:middle;font-size:12.5px;line-height:1.2;">Dense</td><td style="padding:6px 2px;text-align:center;border-bottom:1px solid rgba(128,128,128,0.15);vertical-align:middle;font-size:12.5px;line-height:1.2;">Dense</td><td style="padding:6px 2px;text-align:center;border-bottom:1px solid rgba(128,128,128,0.15);vertical-align:middle;font-size:12.5px;line-height:1.2;">Dense</td><td style="padding:6px 2px;text-align:center;border-bottom:1px solid rgba(128,128,128,0.15);vertical-align:middle;font-size:12.5px;line-height:1.2;">Dense</td></tr><tr><td colspan="6" style="padding:6px 10px;font-weight:600;font-size:12.5px;color:#2450D6;border-bottom:1px solid rgba(36,80,214,0.25);background:rgba(36,80,214,0.12)">Math</td></tr><tr><td style="padding:6px 4px 6px 10px;border-bottom:1px solid rgba(128,128,128,0.15);vertical-align:middle"><div style="font-size:12.5px;font-weight:600;line-height:1.2">HMMT Feb 2026</div><div style="margin-top:2px;font-size:10px;opacity:0.65">Competition mathematics</div></td><td style="padding:6px 2px;text-align:center;border-bottom:1px solid rgba(128,128,128,0.15);vertical-align:middle;font-size:12.5px;line-height:1.2;background:rgba(36,80,214,0.08);"><strong>70.5</strong></td><td style="padding:6px 2px;text-align:center;border-bottom:1px solid rgba(128,128,128,0.15);vertical-align:middle;font-size:12.5px;line-height:1.2;">61.6</td><td style="padding:6px 2px;text-align:center;border-bottom:1px solid rgba(128,128,128,0.15);vertical-align:middle;font-size:12.5px;line-height:1.2;">34.1</td><td style="padding:6px 2px;text-align:center;border-bottom:1px solid rgba(128,128,128,0.15);vertical-align:middle;font-size:12.5px;line-height:1.2;">57.2</td><td style="padding:6px 2px;text-align:center;border-bottom:1px solid rgba(128,128,128,0.15);vertical-align:middle;font-size:12.5px;line-height:1.2;">34.7</td></tr><tr><td colspan="6" style="padding:6px 10px;font-weight:600;font-size:12.5px;color:#2450D6;border-bottom:1px solid rgba(36,80,214,0.25);background:rgba(36,80,214,0.12)">Coding</td></tr><tr><td style="padding:6px 4px 6px 10px;border-bottom:1px solid rgba(128,128,128,0.15);vertical-align:middle"><div style="font-size:12.5px;font-weight:600;line-height:1.2">SWE-bench Verified</div><div style="margin-top:2px;font-size:10px;opacity:0.65">Software engineering</div></td><td style="padding:6px 2px;text-align:center;border-bottom:1px solid rgba(128,128,128,0.15);vertical-align:middle;font-size:12.5px;line-height:1.2;background:rgba(36,80,214,0.08);"><strong>68.6</strong></td><td style="padding:6px 2px;text-align:center;border-bottom:1px solid rgba(128,128,128,0.15);vertical-align:middle;font-size:12.5px;line-height:1.2;">41.2</td><td style="padding:6px 2px;text-align:center;border-bottom:1px solid rgba(128,128,128,0.15);vertical-align:middle;font-size:12.5px;line-height:1.2;">16.4</td><td style="padding:6px 2px;text-align:center;border-bottom:1px solid rgba(128,128,128,0.15);vertical-align:middle;font-size:12.5px;line-height:1.2;">32.2</td><td style="padding:6px 2px;text-align:center;border-bottom:1px solid rgba(128,128,128,0.15);vertical-align:middle;font-size:12.5px;line-height:1.2;">1.8</td></tr><tr><td colspan="6" style="padding:6px 10px;font-weight:600;font-size:12.5px;color:#2450D6;border-bottom:1px solid rgba(36,80,214,0.25);background:rgba(36,80,214,0.12)">Scientific Reasoning</td></tr><tr><td style="padding:6px 4px 6px 10px;border-bottom:1px solid rgba(128,128,128,0.15);vertical-align:middle"><div style="font-size:12.5px;font-weight:600;line-height:1.2">GPQA Diamond</div><div style="margin-top:2px;font-size:10px;opacity:0.65">Graduate-level science QA</div></td><td style="padding:6px 2px;text-align:center;border-bottom:1px solid rgba(128,128,128,0.15);vertical-align:middle;font-size:12.5px;line-height:1.2;background:rgba(36,80,214,0.08);"><strong>65.4</strong></td><td style="padding:6px 2px;text-align:center;border-bottom:1px solid rgba(128,128,128,0.15);vertical-align:middle;font-size:12.5px;line-height:1.2;">77.1</td><td style="padding:6px 2px;text-align:center;border-bottom:1px solid rgba(128,128,128,0.15);vertical-align:middle;font-size:12.5px;line-height:1.2;">43.8</td><td style="padding:6px 2px;text-align:center;border-bottom:1px solid rgba(128,128,128,0.15);vertical-align:middle;font-size:12.5px;line-height:1.2;">55.9</td><td style="padding:6px 2px;text-align:center;border-bottom:1px solid rgba(128,128,128,0.15);vertical-align:middle;font-size:12.5px;line-height:1.2;">51.3</td></tr><tr><td style="padding:6px 4px 6px 10px;border-bottom:1px solid rgba(128,128,128,0.15);vertical-align:middle"><div style="font-size:12.5px;font-weight:600;line-height:1.2">HLE</div><div style="margin-top:2px;font-size:10px;opacity:0.65">Expert-level reasoning</div></td><td style="padding:6px 2px;text-align:center;border-bottom:1px solid rgba(128,128,128,0.15);vertical-align:middle;font-size:12.5px;line-height:1.2;background:rgba(36,80,214,0.08);"><strong>12.9</strong></td><td style="padding:6px 2px;text-align:center;border-bottom:1px solid rgba(128,128,128,0.15);vertical-align:middle;font-size:12.5px;line-height:1.2;">9.9</td><td style="padding:6px 2px;text-align:center;border-bottom:1px solid rgba(128,128,128,0.15);vertical-align:middle;font-size:12.5px;line-height:1.2;">4.5</td><td style="padding:6px 2px;text-align:center;border-bottom:1px solid rgba(128,128,128,0.15);vertical-align:middle;font-size:12.5px;line-height:1.2;">6.6</td><td style="padding:6px 2px;text-align:center;border-bottom:1px solid rgba(128,128,128,0.15);vertical-align:middle;font-size:12.5px;line-height:1.2;">4.9</td></tr><tr><td colspan="6" style="padding:6px 10px;font-weight:600;font-size:12.5px;color:#2450D6;border-bottom:1px solid rgba(36,80,214,0.25);background:rgba(36,80,214,0.12)">Coding</td></tr><tr><td style="padding:6px 4px 6px 10px;border-bottom:1px solid rgba(128,128,128,0.15);vertical-align:middle"><div style="font-size:12.5px;font-weight:600;line-height:1.2">SciCode</div><div style="margin-top:2px;font-size:10px;opacity:0.65">Scientific coding</div></td><td style="padding:6px 2px;text-align:center;border-bottom:1px solid rgba(128,128,128,0.15);vertical-align:middle;font-size:12.5px;line-height:1.2;background:rgba(36,80,214,0.08);"><strong>25.9</strong></td><td style="padding:6px 2px;text-align:center;border-bottom:1px solid rgba(128,128,128,0.15);vertical-align:middle;font-size:12.5px;line-height:1.2;">16.1</td><td style="padding:6px 2px;text-align:center;border-bottom:1px solid rgba(128,128,128,0.15);vertical-align:middle;font-size:12.5px;line-height:1.2;">17.7</td><td style="padding:6px 2px;text-align:center;border-bottom:1px solid rgba(128,128,128,0.15);vertical-align:middle;font-size:12.5px;line-height:1.2;">24.9</td><td style="padding:6px 2px;text-align:center;border-bottom:1px solid rgba(128,128,128,0.15);vertical-align:middle;font-size:12.5px;line-height:1.2;">16.4</td></tr><tr><td style="padding:6px 4px 6px 10px;border-bottom:1px solid rgba(128,128,128,0.15);vertical-align:middle"><div style="font-size:12.5px;font-weight:600;line-height:1.2">Terminal-Bench 2.1</div><div style="margin-top:2px;font-size:10px;opacity:0.65">Agentic terminal use</div></td><td style="padding:6px 2px;text-align:center;border-bottom:1px solid rgba(128,128,128,0.15);vertical-align:middle;font-size:12.5px;line-height:1.2;background:rgba(36,80,214,0.08);"><strong>25.1</strong></td><td style="padding:6px 2px;text-align:center;border-bottom:1px solid rgba(128,128,128,0.15);vertical-align:middle;font-size:12.5px;line-height:1.2;">25.8</td><td style="padding:6px 2px;text-align:center;border-bottom:1px solid rgba(128,128,128,0.15);vertical-align:middle;font-size:12.5px;line-height:1.2;">6.0</td><td style="padding:6px 2px;text-align:center;border-bottom:1px solid rgba(128,128,128,0.15);vertical-align:middle;font-size:12.5px;line-height:1.2;">13.9</td><td style="padding:6px 2px;text-align:center;border-bottom:1px solid rgba(128,128,128,0.15);vertical-align:middle;font-size:12.5px;line-height:1.2;">3.7</td></tr><tr><td colspan="6" style="padding:6px 10px;font-weight:600;font-size:12.5px;color:#2450D6;border-bottom:1px solid rgba(36,80,214,0.25);background:rgba(36,80,214,0.12)">Agents</td></tr><tr><td style="padding:6px 4px 6px 10px;border-bottom:1px solid rgba(128,128,128,0.15);vertical-align:middle"><div style="font-size:12.5px;font-weight:600;line-height:1.2">tau3-Banking</div><div style="margin-top:2px;font-size:10px;opacity:0.65">Agentic tool use</div></td><td style="padding:6px 2px;text-align:center;border-bottom:1px solid rgba(128,128,128,0.15);vertical-align:middle;font-size:12.5px;line-height:1.2;background:rgba(36,80,214,0.08);"><strong>17.7</strong></td><td style="padding:6px 2px;text-align:center;border-bottom:1px solid rgba(128,128,128,0.15);vertical-align:middle;font-size:12.5px;line-height:1.2;">6.8</td><td style="padding:6px 2px;text-align:center;border-bottom:1px solid rgba(128,128,128,0.15);vertical-align:middle;font-size:12.5px;line-height:1.2;">—</td><td style="padding:6px 2px;text-align:center;border-bottom:1px solid rgba(128,128,128,0.15);vertical-align:middle;font-size:12.5px;line-height:1.2;">5.6</td><td style="padding:6px 2px;text-align:center;border-bottom:1px solid rgba(128,128,128,0.15);vertical-align:middle;font-size:12.5px;line-height:1.2;">—</td></tr><tr><td style="padding:6px 4px 6px 10px;border-bottom:1px solid rgba(128,128,128,0.15);vertical-align:middle"><div style="font-size:12.5px;font-weight:600;line-height:1.2">BFCL v4</div><div style="margin-top:2px;font-size:10px;opacity:0.65">Function calling</div></td><td style="padding:6px 2px;text-align:center;border-bottom:1px solid rgba(128,128,128,0.15);vertical-align:middle;font-size:12.5px;line-height:1.2;background:rgba(36,80,214,0.08);"><strong>50.9</strong></td><td style="padding:6px 2px;text-align:center;border-bottom:1px solid rgba(128,128,128,0.15);vertical-align:middle;font-size:12.5px;line-height:1.2;">55.7</td><td style="padding:6px 2px;text-align:center;border-bottom:1px solid rgba(128,128,128,0.15);vertical-align:middle;font-size:12.5px;line-height:1.2;">47.9</td><td style="padding:6px 2px;text-align:center;border-bottom:1px solid rgba(128,128,128,0.15);vertical-align:middle;font-size:12.5px;line-height:1.2;">50.8</td><td style="padding:6px 2px;text-align:center;border-bottom:1px solid rgba(128,128,128,0.15);vertical-align:middle;font-size:12.5px;line-height:1.2;">36.8</td></tr></tbody></table></div>
43
+ <!-- TABLE:END -->
44
+
45
+ Scores in %. Bold marks the best score in each row. Baseline protocols may differ;
46
+
47
+ ## Quickstart
48
+
49
+ ### Serving
50
+
51
+ vLLM, recipe at [recipes.vllm.ai/IFM](https://recipes.vllm.ai/IFM):
52
+
53
+ ```shell
54
+ vllm serve IFM/K2-Horizon-3.7B \
55
+ --trust-remote-code \
56
+ --dtype bfloat16 \
57
+ --tensor-parallel-size 1 \
58
+ --reasoning-parser k2_horizon \
59
+ --enable-auto-tool-choice \
60
+ --tool-call-parser k2_horizon
61
+ ```
62
+
63
+ Use an exact branch name from the inventory with vLLM's `--revision` option. For example, `--revision pretrain_1100000` selects the final checkpoint of Pretraining, at step 1,100,000.
64
+
65
+ SGLang, this is the recipe validated in the [SGLang K2 Horizon cookbook](https://docs.sglang.io/cookbook/autoregressive/IFM/K2-Horizon):
66
+
67
+ ```shell
68
+ sglang serve \
69
+ --model-path IFM/K2-Horizon-3.7B \
70
+ --revision 09568bab0d7ee4152a12ee13c21902ca910d15b2 \
71
+ --tp 1 \
72
+ --dtype bfloat16 \
73
+ --attention-backend fa3 \
74
+ --reasoning-parser k2_horizon \
75
+ --host 0.0.0.0 \
76
+ --port 30000
77
+ ```
78
+
79
+ ### API Usage
80
+
81
+ > [!Tip]
82
+ > Recommended settings: `reasoning_effort="high"`, `temperature=1.0`, `top_p=0.95`, and at least 32,768 output tokens.
83
+ > Reasoning depth is selected per request through `chat_template_kwargs`. Thinking is returned in `reasoning_content` and the answer in `content`.
84
+
85
+ ```python
86
+ from openai import OpenAI
87
+
88
+ client = OpenAI(base_url="http://localhost:30000/v1", api_key="EMPTY")
89
+ response = client.chat.completions.create(
90
+ model="IFM/K2-Horizon-3.7B",
91
+ messages=[{"role": "user", "content": "Explain the result step by step."}],
92
+ temperature=1.0,
93
+ top_p=0.95,
94
+ max_tokens=32768,
95
+ extra_body={"chat_template_kwargs": {"reasoning_effort": "high"}},
96
+ )
97
+ message = response.choices[0].message
98
+ print("Reasoning:", getattr(message, "reasoning_content", None))
99
+ print("Answer:", message.content)
100
+ ```
101
+
102
+ ### Transformers
103
+
104
+ Validated with Transformers 5.15.0, PyTorch 2.13.0, Safetensors 0.8.0.
105
+
106
+ ```python
107
+ from transformers import AutoModelForCausalLM, AutoTokenizer
108
+
109
+ model_id = "IFM/K2-Horizon-3.7B"
110
+ tokenizer = AutoTokenizer.from_pretrained(model_id, trust_remote_code=True)
111
+ model = AutoModelForCausalLM.from_pretrained(
112
+ model_id, device_map="auto", dtype="bfloat16", low_cpu_mem_usage=True, trust_remote_code=True
113
+ )
114
+
115
+ inputs = tokenizer("Explain why long-context evaluation is difficult.", return_tensors="pt").to(model.device)
116
+ inputs.pop("token_type_ids", None)
117
+ outputs = model.generate(**inputs, max_new_tokens=32768, temperature=1.0, top_p=0.95, do_sample=True)
118
+ print(tokenizer.decode(outputs[0], skip_special_tokens=True))
119
+ ```
120
+
121
+ ## Training Overview
122
+
123
+ The table below lists the training stages in order and the purpose of each stage.
124
+
125
+ Training steps are counted within each stage or phase. Token budgets cover only the additional training in that stage or phase. For example, the 50B tokens listed for SFT Phase 2 are additional to the 219B tokens in Phase 1, bringing the cumulative budget to 269B tokens by the end of Phase 2. Here, B and T denote billion and trillion tokens, respectively.
126
+
127
+ Each stage or phase continues from the final checkpoint of the preceding stage or phase.
128
+
129
+ Some stages, such as SFT, have multiple phases with slight changes to the data mix while retaining the same overall purpose. During RL, training branches into multiple expert models, which are then merged, as described below.
130
+
131
+ | Training stage | Training steps | Training tokens | Sequence length | Purpose |
132
+ | --- | --- | --- | --- | --- |
133
+ | Pretraining | 1100000 | 22.9T | 8K | Pretraining. |
134
+ | Midtraining — Stage 1 | 55000 | 1.1T | 32K | Context extension. |
135
+ | Midtraining — Stage 2 | 25000 | 498B | 128K | Context extension. |
136
+ | Midtraining — Stage 3 | 5500 | 110B | 512K | Context extension. |
137
+ | Midtraining — Stage 4 | 10000 | 199B | 512K | Continued context extension from Stage 3, with the data mix shifted toward agentic and reasoning SFT data. |
138
+ | RL — Math expert | 2549 | 28.9B | 64K | Math RL from Midtraining Stage 4; common ancestor of the Code and STEM-Code experts. |
139
+ | RL — Code expert | 949 | 15.5B | 64K | Code RL from the Math expert. |
140
+ | RL — STEM-Code expert | 451 | 1.3B | 64K | STEM and code RL from the Math expert. |
141
+ | RL — Merge | — | — | — | ISO merge on self-attention, RAM on the remaining weights; inputs: Midtraining Stage 4 base + Math, Code, STEM-Code experts. |
142
+ | SFT — Phase 1 | 10000 | 199B | 512K | SFT for better domain coverage, starting from the merged RL checkpoint. |
143
+ | SFT — Phase 2 | 2500 | 50B | 512K | SFT on a high-quality subset of the data used in Phase 1, with learning rate decay. |
144
+
145
+ ## Release Artifacts
146
+
147
+ The tables below list the release artifacts for **K2-Horizon-3.7B**, their availability, and the expected release dates for remaining items.
148
+
149
+ **Last updated:** 2026-09-11
150
+
151
+ **Status:**
152
+
153
+ - **Available** — fully released for the scope listed;
154
+ - **Partial** — some items are available, with remaining items listed in the notes;
155
+ - **In Progress** — being prepared for release but not yet available.
156
+
157
+ ### Artifact Index
158
+
159
+ | Artifact | Link | Status | Remaining items / expected availability |
160
+ | --- | --- | --- | --- |
161
+ | Model card | [Hugging Face](https://huggingface.co/IFM/K2-Horizon-3.7B) | Available | N/A |
162
+ | Training logs | [W&B](https://wandb.ai/llm360/K2-Horizon-3.7B) | Available | N/A |
163
+ | Blog post | [Blog post](https://ifm.ai/blog/k2/) | Available | N/A |
164
+ | Checkpoints | [Checkpoint inventory](#checkpoint-inventory) | Available | N/A |
165
+ | Technical report | Not yet available | In Progress | End of September 2026 |
166
+ | Code repository | [GitHub](https://github.com/ifm-ai/xllm) | In Progress | End of September 2026 |
167
+
168
+ ### Checkpoint Inventory
169
+
170
+ **Model repository:** [IFM/K2-Horizon-3.7B](https://huggingface.co/IFM/K2-Horizon-3.7B)
171
+
172
+ Branch names below refer to this repository. Patterns containing `*` group branches by training stage or phase. The `*` is a placeholder for a training-step number, not a literal branch name. Intermediate checkpoint groups exclude the final checkpoint listed separately; a pattern does not imply that a checkpoint is available at every step.
173
+
174
+ For example, `sft_1_10000` is the checkpoint saved at training step 11,000 within SFT Phase 1, and is the final checkpoint of that phase. The numeric suffix is the step within the named stage or phase, not the cumulative step across all training. Thus, `sft_2_2500` refers to step 2,500 within SFT Phase 2.
175
+
176
+ For a partially released group, the available checkpoints and the remaining checkpoints are listed in the notes.
177
+
178
+ | Checkpoint | Branch / repository | Status | Remaining items / expected availability |
179
+ | --- | --- | --- | --- |
180
+ | Pretrain Intermediate Checkpoints | `pretrain_*` | Available | N/A |
181
+ | Pretrain Final Checkpoint | `pretrain_1100000` | Available | N/A |
182
+ | Midtrain Stage 1 Intermediate Checkpoints | `mid_1_*` | Available | N/A |
183
+ | Midtrain Stage 1 Final Checkpoint | `mid_1_55000` | Available | N/A |
184
+ | Midtrain Stage 2 Intermediate Checkpoints | `mid_2_*` | Available | N/A |
185
+ | Midtrain Stage 2 Final Checkpoint | `mid_2_25000` | Available | N/A |
186
+ | Midtrain Stage 3 Intermediate Checkpoints | `mid_3_*` | Available | N/A |
187
+ | Midtrain Stage 3 Final Checkpoint | `mid_3_5500` | Available | N/A |
188
+ | Midtrain Stage 4 Intermediate Checkpoints | `mid_4_*` | Available | N/A |
189
+ | Midtrain Stage 4 Final Checkpoint | `mid_4_10000` | Available | N/A |
190
+ | RL Math Expert Checkpoint | `rl_math` | Available | N/A |
191
+ | RL Code Expert Checkpoint | `rl_code` | Available | N/A |
192
+ | RL Stem Code Expert Checkpoint | `rl_stemcode` | Available | N/A |
193
+ | RL Merged Final Checkpoint | `rl_merged` | Available | N/A |
194
+ | SFT Phase 1 Intermediate Checkpoints | `sft_1_*` | Available | N/A |
195
+ | SFT Phase 1 Final Checkpoint | `sft_1_10000` | Available | N/A |
196
+ | SFT Phase 2 Intermediate Checkpoints | `sft_2_*` | Available | N/A |
197
+ | SFT Phase 2 Final Checkpoint | `sft_2_2500` | Available | N/A |
198
+
199
+ > [!IMPORTANT]
200
+ > Note:
201
+ > - Released K2-Horizon Hugging Face checkpoints (e.g. [Huggingface](https://huggingface.co/IFM/K2-Horizon-375B-A23B/tree/main)) can be used for inference, evaluation, and downstream fine-tuning (including SFT).
202
+ > Training behavior in the bundled Hugging Face implementation may differ from native xLLM, including the auxiliary load-balancing loss.
203
+ > To continue the original pretraining with xLLM's training behavior, use the native xLLM checkpoint and XLLM runtime.
204
+
205
+ ## Best Practices
206
+
207
+ 1. **Reasoning effort: always `high`.** All reported results use high reasoning effort. Pass `{"chat_template_kwargs": {"reasoning_effort": "high"}}` on every request; `medium` and `low` trade accuracy for speed and are not recommended for evaluation.
208
+ 2. **Sampling parameters.** `temperature=1.0`, `top_p=0.95`.
209
+ 3. **Output length.** Allow at least 32,768 output tokens so reasoning is never cut off. Truncated reasoning is a failed response, not a shorter one.
210
+ 4. **Serving.** Use the validated SGLang recipe above: BF16, TP=1, FlashAttention-3. Full recipes for every K2-Horizon size, with measured H200 latency and throughput, are in the [SGLang cookbook](https://docs.sglang.io/cookbook/autoregressive/IFM/K2-Horizon).
211
+ 5. **Parsers.** Enable the `k2_horizon` reasoning parser for chat, and add the `k2_horizon` tool-call parser for agent use. Leave both off for plain completion-style generation.
212
+ 6. **Revisions.** Pin a revision tag when reproducibility matters. `main` is the default checkpoint; `base_final` and the `mid_*_final` tags identify training stages.
213
+
214
+ ## Citation
215
+
216
+ ```bibtex
217
+ @misc{k2horizon2026,
218
+ title = {Introducing K2 Horizon: Frontier Performance, Radically Open},
219
+ author = {{IFM Team}},
220
+ year = {2026},
221
+ url = {https://ifm.ai/blog/k2/},
222
+ }
223
+ ```
224
+
assets/k2-horizon-3.7b-benchmarks.png ADDED

Git LFS Details

  • SHA256: e256eb826b0eb3eae5784bf37afae91684eb298960ab09645b060b42544647be
  • Pointer size: 132 Bytes
  • Size of remote file: 1.16 MB
chat_template.jinja ADDED
@@ -0,0 +1,994 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {{- bos_token }}
2
+ {%- if tool_presentation is defined -%}
3
+ {{- raise_exception("Unsupported argument: tool_presentation. Use tool_presentation_format with one of: json, xml, markdown.") -}}
4
+ {%- endif -%}
5
+ {%- if tool_calling_format is defined -%}
6
+ {{- raise_exception("Unsupported argument: tool_calling_format. Use tool_call_format with one of: json, xml, xml_typed.") -}}
7
+ {%- endif -%}
8
+ {%- if tool_format is defined -%}
9
+ {{- raise_exception("Unsupported argument: tool_format. Use tool_call_format with one of: json, xml, xml_typed.") -}}
10
+ {%- endif -%}
11
+ {%- set tool_presentation_fmt = tool_presentation_format | default('markdown') -%}
12
+ {%- set tool_call_fmt = tool_call_format | default('xml') -%}
13
+ {%- if tool_presentation_fmt != 'json' and tool_presentation_fmt != 'xml' and tool_presentation_fmt != 'markdown' -%}
14
+ {{- raise_exception("Unsupported tool_presentation_format: '" ~ tool_presentation_fmt ~ "'. Supported formats: json, xml, markdown.") -}}
15
+ {%- endif -%}
16
+ {%- if tool_call_fmt != 'json' and tool_call_fmt != 'xml' and tool_call_fmt != 'xml_typed' -%}
17
+ {{- raise_exception("Unsupported tool_call_format: '" ~ tool_call_fmt ~ "'. Supported formats: json, xml, xml_typed.") -}}
18
+ {%- endif -%}
19
+
20
+ {#- Renderability state, computed during validate_tools (single walk, no extra -#}
21
+ {#- traversal at render time): ok = working flag for the tool being validated; -#}
22
+ {#- bad = pipe-delimited indices of tools that must render as verbatim JSON. -#}
23
+ {%- set RB = namespace(ok=true, bad='|') -%}
24
+
25
+ {%- macro value_contains_mapping(v) -%}
26
+ {%- if v is mapping -%}
27
+ true
28
+ {%- elif v is sequence and v is not string -%}
29
+ {%- set f = namespace(x='false') -%}
30
+ {%- for c in v -%}{%- if value_contains_mapping(c) == 'true' -%}{%- set f.x = 'true' -%}{%- endif -%}{%- endfor -%}
31
+ {{- f.x -}}
32
+ {%- else -%}
33
+ false
34
+ {%- endif -%}
35
+ {%- endmacro -%}
36
+
37
+ {#- $ref inlining state: defs = local $defs of the tool being rendered; seen = -#}
38
+ {#- pipe-delimited names already expanded for this tool (each def inlines at most -#}
39
+ {#- once; later references render by def name; cycles terminate immediately). -#}
40
+ {#- $ref-sibling annotations (description/default/...) merge OVER the def at -#}
41
+ {#- the inline site, so use-site annotations win and are never dropped. -#}
42
+ {%- set REFS = namespace(defs={}, seen='|') -%}
43
+
44
+ {%- macro render_compact_type_name(type_name, spec) -%}
45
+ {%- if type_name == "array" -%}
46
+ array[{%- if 'items' in spec -%}{{ render_compact_type(spec['items']) }}{%- else -%}any{%- endif -%}]
47
+ {%- elif type_name -%}
48
+ {{- type_name -}}
49
+ {%- else -%}
50
+ any
51
+ {%- endif -%}
52
+ {%- endmacro -%}
53
+
54
+ {%- macro render_compact_type(spec) -%}
55
+ {%- if spec is not mapping -%}
56
+ any
57
+ {%- elif spec.type is defined and spec.type is sequence and spec.type is not string and spec.type | length > 0 -%}
58
+ {%- for type_name in spec.type -%}{{ render_compact_type_name(type_name, spec) }}{%- if not loop.last -%}|{%- endif -%}{%- endfor -%}
59
+ {%- elif spec.type is defined and spec.type is sequence and spec.type is not string -%}
60
+ any
61
+ {%- elif spec.type -%}
62
+ {{- render_compact_type_name(spec.type, spec) -}}
63
+ {%- elif spec['$ref'] is string -%}
64
+ {{- spec['$ref'].split('/') | last -}}
65
+ {%- elif spec.oneOf -%}
66
+ oneOf[{%- for variant in spec.oneOf -%}{{ render_compact_type(variant) }}{%- if not loop.last -%}|{%- endif -%}{%- endfor -%}]
67
+ {%- elif spec.anyOf -%}
68
+ anyOf[{%- for variant in spec.anyOf -%}{{ render_compact_type(variant) }}{%- if not loop.last -%}|{%- endif -%}{%- endfor -%}]
69
+ {%- elif spec.properties -%}
70
+ object
71
+ {%- elif 'items' in spec -%}
72
+ array[{{ render_compact_type(spec['items']) }}]
73
+ {%- else -%}
74
+ any
75
+ {%- endif -%}
76
+ {%- endmacro -%}
77
+
78
+ {%- macro render_markdown_type_name(type_name, spec) -%}
79
+ {%- if type_name == "array" -%}
80
+ array of {% if 'items' in spec %}{{ render_markdown_type(spec['items']) }}{% else %}any{% endif %}
81
+ {%- elif type_name -%}
82
+ {{- type_name -}}
83
+ {%- else -%}
84
+ any
85
+ {%- endif -%}
86
+ {%- endmacro -%}
87
+
88
+ {%- macro render_markdown_type(spec) -%}
89
+ {%- if spec is sameas true -%}
90
+ True
91
+ {%- elif spec is sameas false -%}
92
+ False
93
+ {%- elif spec is not mapping -%}
94
+ any
95
+ {%- elif spec.type is defined and spec.type is sequence and spec.type is not string and spec.type | length > 0 -%}
96
+ {%- for type_name in spec.type -%}{{ render_markdown_type_name(type_name, spec) }}{% if not loop.last %} or {% endif %}{%- endfor -%}
97
+ {%- elif spec.type is defined and spec.type is sequence and spec.type is not string -%}
98
+ any
99
+ {%- elif spec.type -%}
100
+ {{- render_markdown_type_name(spec.type, spec) -}}
101
+ {%- elif spec['$ref'] is string -%}
102
+ {{- spec['$ref'].split('/') | last -}}
103
+ {%- elif spec.oneOf -%}
104
+ oneOf[{%- for variant in spec.oneOf -%}{{ render_markdown_type(variant) }}{% if not loop.last %} or {% endif %}{%- endfor -%}]
105
+ {%- elif spec.anyOf -%}
106
+ anyOf[{%- for variant in spec.anyOf -%}{{ render_markdown_type(variant) }}{% if not loop.last %} or {% endif %}{%- endfor -%}]
107
+ {%- elif spec.properties -%}
108
+ object
109
+ {%- elif 'items' in spec -%}
110
+ array of {{ render_markdown_type(spec['items']) }}
111
+ {%- else -%}
112
+ any
113
+ {%- endif -%}
114
+ {%- endmacro -%}
115
+
116
+ {%- macro render_xml_text(value) -%}
117
+ {{- value.split() | join(" ") -}}
118
+ {%- endmacro -%}
119
+
120
+ {%- macro render_python_string(value) -%}
121
+ '{{- value.split() | join(" ") | replace("\\", "\\\\") | replace("'", "\\'") -}}'
122
+ {%- endmacro -%}
123
+
124
+ {%- macro render_python_repr(value) -%}
125
+ {%- if value is string -%}
126
+ {{ render_python_string(value) }}
127
+ {%- elif value is sameas true -%}
128
+ True
129
+ {%- elif value is sameas false -%}
130
+ False
131
+ {%- elif value is none -%}
132
+ None
133
+ {%- elif value is mapping -%}
134
+ {{- "{" -}}
135
+ {%- for key, child in value | items -%}
136
+ {{ render_python_repr(key) }}: {{ render_python_repr(child) }}{%- if not loop.last -%}, {% endif -%}
137
+ {%- endfor -%}
138
+ {{- "}" -}}
139
+ {%- elif value is sequence -%}
140
+ {{- "[" -}}
141
+ {%- for child in value -%}
142
+ {{ render_python_repr(child) }}{%- if not loop.last -%}, {% endif -%}
143
+ {%- endfor -%}
144
+ {{- "]" -}}
145
+ {%- else -%}
146
+ {{- value -}}
147
+ {%- endif -%}
148
+ {%- endmacro -%}
149
+
150
+ {%- macro render_xml_value(value) -%}
151
+ {%- if value is string -%}{{ render_xml_text(value) }}{%- else -%}{{ render_python_repr(value) }}{%- endif -%}
152
+ {%- endmacro -%}
153
+
154
+ {%- macro render_xml_enum_value(value) -%}
155
+ {%- if value is string -%}"{{- value | replace("\\", "\\\\") | replace("\"", "\\\"") -}}"{%- else -%}"{{- render_python_repr(value) | replace("\\", "\\\\") | replace("\"", "\\\"") -}}"{%- endif -%}
156
+ {%- endmacro -%}
157
+
158
+ {%- macro render_xml_enum(values) -%}
159
+ {%- for value in values -%}{{ render_xml_enum_value(value) }}{%- if not loop.last -%}|{%- endif -%}{%- endfor -%}
160
+ {%- endmacro -%}
161
+
162
+ {%- macro render_xml_default_attr(value) -%}
163
+ {{- " default=" }}{%- if value is string -%}"{{- value | replace("\\", "\\\\") | replace("\"", "\\\"") -}}"{%- else -%}{{ render_xml_value(value) }}{%- endif -%}
164
+ {%- endmacro -%}
165
+
166
+ {%- macro render_xml_attr(name, value) -%}
167
+ {{- " " + name + "=" }}{%- if value == "" -%}""{%- else -%}{{ render_xml_value(value) }}{%- endif -%}
168
+ {%- endmacro -%}
169
+
170
+ {%- macro validate_schema(spec, path, lenient=false, classify=true, in_variant=false) -%}
171
+ {%- if spec is mapping -%}
172
+ {%- if not lenient -%}
173
+ {%- if spec.required is defined -%}
174
+ {%- if spec.required is string or spec.required is not sequence -%}
175
+ {{- raise_exception("Schema '" + path + "' has 'required' but it is not a list.") -}}
176
+ {%- endif -%}
177
+ {%- if spec.required | length > 0 and not spec.properties and not in_variant -%}
178
+ {{- raise_exception("Schema '" + path + "' has required fields but no properties object to define them.") -}}
179
+ {%- endif -%}
180
+ {%- if spec.properties -%}
181
+ {%- for required_name in spec.required -%}
182
+ {%- if required_name not in spec.properties -%}
183
+ {{- raise_exception("Schema '" + path + "' marks '" + required_name + "' as required, but that property is not defined in properties.") -}}
184
+ {%- endif -%}
185
+ {%- endfor -%}
186
+ {%- endif -%}
187
+ {%- endif -%}
188
+ {%- endif -%}
189
+ {#- renderability classification, piggybacking on this walk (no raises here): -#}
190
+ {#- constructs the pretty renderer does not fully handle flip RB.ok so the -#}
191
+ {#- tool falls back to verbatim JSON. Skipped entirely for json presentation. -#}
192
+ {%- if classify -%}
193
+ {%- for key, value in spec | items -%}
194
+ {%- if key == '$ref' -%}
195
+ {%- if value is not string -%}{%- set RB.ok = false -%}
196
+ {%- elif not (value.startswith('#/$defs/') or value.startswith('#/definitions/')) -%}{%- set RB.ok = false -%}{%- endif -%}
197
+ {%- elif key == '$defs' or key == 'definitions' -%}
198
+ {%- if value is mapping -%}
199
+ {%- for dk, dv in value | items -%}
200
+ {{- validate_schema(dv, path + ".$defs." + dk, true) -}}
201
+ {%- endfor -%}
202
+ {%- else -%}{%- set RB.ok = false -%}{%- endif -%}
203
+ {%- elif key == 'type' -%}
204
+ {%- if value is mapping -%}{%- set RB.ok = false -%}{%- endif -%}
205
+ {%- elif key == 'enum' -%}
206
+ {%- if value is string or value is mapping or value is not sequence -%}{%- set RB.ok = false -%}{%- endif -%}
207
+ {%- elif key == 'items' -%}
208
+ {#- any items shape renders: mapping structurally, others via repr detail -#}
209
+ {%- elif key == 'oneOf' or key == 'anyOf' -%}
210
+ {%- if value is mapping or value is string or value is not sequence -%}{%- set RB.ok = false -%}{%- endif -%}
211
+ {%- elif key == 'required' -%}
212
+ {%- if value and not spec.properties -%}{%- set RB.ok = false -%}{%- endif -%}
213
+ {%- elif ('|' ~ key ~ '|') in '|description|default|title|examples|properties|patternProperties|additionalProperties|returns|' -%}
214
+ {%- elif value is mapping -%}
215
+ {%- for uk, uv in value | items -%}
216
+ {%- if value_contains_mapping(uv) == 'true' -%}{%- set RB.ok = false -%}{%- endif -%}
217
+ {%- endfor -%}
218
+ {%- elif value is sequence and value is not string -%}
219
+ {%- if value_contains_mapping(value) == 'true' -%}{%- set RB.ok = false -%}{%- endif -%}
220
+ {%- endif -%}
221
+ {%- endfor -%}
222
+ {%- endif -%}
223
+ {%- if spec.properties -%}
224
+ {%- for child_name, child_spec in spec.properties | items -%}
225
+ {{- validate_schema(child_spec, path + "." + child_name, lenient, classify) -}}
226
+ {%- endfor -%}
227
+ {%- endif -%}
228
+ {%- if 'items' in spec -%}{{- validate_schema(spec['items'], path + "[]", lenient, classify) -}}{%- endif -%}
229
+ {%- if spec.oneOf -%}
230
+ {%- for variant in spec.oneOf -%}{{- validate_schema(variant, path + ".oneOf[" + (loop.index0 | string) + "]", lenient, classify, true) -}}{%- endfor -%}
231
+ {%- endif -%}
232
+ {%- if spec.anyOf -%}
233
+ {%- for variant in spec.anyOf -%}{{- validate_schema(variant, path + ".anyOf[" + (loop.index0 | string) + "]", lenient, classify, true) -}}{%- endfor -%}
234
+ {%- endif -%}
235
+ {%- if spec.additionalProperties is mapping -%}{{- validate_schema(spec.additionalProperties, path + ".additionalProperties", lenient, classify) -}}{%- endif -%}
236
+ {%- if spec.patternProperties is mapping -%}
237
+ {%- for pattern, pattern_spec in spec.patternProperties | items -%}
238
+ {{- validate_schema(pattern_spec, path + ".patternProperties[" + pattern + "]", lenient, classify) -}}
239
+ {%- endfor -%}
240
+ {%- endif -%}
241
+ {%- if spec.returns is mapping -%}{{- validate_schema(spec.returns, path + ".returns", lenient, classify) -}}{%- endif -%}
242
+ {%- endif -%}
243
+ {%- endmacro -%}
244
+
245
+ {%- macro validate_tools(tools_list, classify=true) -%}
246
+ {%- set RB.bad = '|' -%}
247
+ {%- for tool in tools_list -%}
248
+ {%- set fn = tool.function if tool.function is defined else tool -%}
249
+ {%- set RB.ok = true -%}
250
+ {%- if fn.parameters is defined and fn.parameters is string -%}
251
+ {{- raise_exception("tool.function.parameters must be a dict, not a JSON string. Parse it before passing to the template.") -}}
252
+ {%- endif -%}
253
+ {%- if fn.parameters is not defined or fn.parameters is none -%}
254
+ {%- if fn.arguments is defined -%}
255
+ {{- raise_exception("Tool '" + fn.name + "' has 'arguments' instead of 'parameters'. Rename 'arguments' to 'parameters'.") -}}
256
+ {%- else -%}
257
+ {{- raise_exception("Tool '" + fn.name + "' is missing required 'parameters' field. Each tool must have a 'parameters' dict with 'type', 'properties', and 'required' keys.") -}}
258
+ {%- endif -%}
259
+ {%- endif -%}
260
+ {{- validate_schema(fn.parameters, "tool." + fn.name + ".parameters", false, classify) -}}
261
+ {%- if classify -%}
262
+ {%- if fn.parameters is mapping -%}
263
+ {#- unknown container-valued keys at the parameters ROOT are never rendered -#}
264
+ {#- by the pretty path (root extras are dropped) -> verbatim fallback. -#}
265
+ {%- for rk, rv in fn.parameters | items -%}
266
+ {%- if rk not in ['type', 'description', 'enum', 'default', 'properties', 'required', 'optional', 'title', 'items', 'oneOf', 'anyOf', 'additionalProperties', 'patternProperties', 'returns', 'examples', '$defs', 'definitions', '$ref'] -%}
267
+ {%- if rv is mapping or (rv is sequence and rv is not string) -%}{%- set RB.ok = false -%}{%- endif -%}
268
+ {%- endif -%}
269
+ {%- endfor -%}
270
+ {%- else -%}
271
+ {%- set RB.ok = false -%}
272
+ {%- endif -%}
273
+ {%- endif -%}
274
+ {%- if fn.returns is mapping -%}{{- validate_schema(fn.returns, "tool." + fn.name + ".returns", false, classify) -}}{%- endif -%}
275
+ {%- if classify and fn.returns is not defined and fn.response is mapping -%}{{- validate_schema(fn.response, "tool." + fn.name + ".response", true) -}}{%- endif -%}
276
+ {#- unknown container-valued keys at the FUNCTION level are never rendered -> fallback. -#}
277
+ {%- if classify -%}
278
+ {%- for fk, fv in fn | items -%}
279
+ {%- if fk not in ['name', 'description', 'parameters', 'returns', 'response', 'type', 'function'] -%}
280
+ {%- if fv is mapping or (fv is sequence and fv is not string) -%}{%- set RB.ok = false -%}{%- endif -%}
281
+ {%- endif -%}
282
+ {%- endfor -%}
283
+ {%- endif -%}
284
+ {%- if not RB.ok -%}{%- set RB.bad = RB.bad ~ loop.index0 ~ '|' -%}{%- endif -%}
285
+ {%- endfor -%}
286
+ {%- endmacro -%}
287
+
288
+ {%- macro render_tools_json(tools_list) -%}
289
+ {{- "<ifm|tools>" }}
290
+ {%- for tool in tools_list %}
291
+ {{- "\n" }}
292
+ {{- tool | tojson }}
293
+ {%- endfor %}
294
+ {{- "\n</ifm|tools>" }}
295
+ {%- endmacro -%}
296
+
297
+ {%- macro render_xml_schema_attrs(spec, include_value_attrs) -%}
298
+ {%- if spec is mapping -%}
299
+ {%- set structural_keys = ["type", "description", "enum", "default", "properties", "required", "items", "oneOf", "anyOf", "additionalProperties", "patternProperties", "returns"] -%}
300
+ {%- if include_value_attrs and spec.enum -%}{{- " enum=" }}{{ render_xml_enum(spec.enum) }}{%- endif -%}
301
+ {%- if include_value_attrs and spec.default is defined -%}{{ render_xml_default_attr(spec.default) }}{%- endif -%}
302
+ {%- if spec.additionalProperties is defined and spec.additionalProperties is not mapping -%}{{ render_xml_attr("additionalProperties", spec.additionalProperties) }}{%- endif -%}
303
+ {%- if spec.patternProperties is defined and spec.patternProperties is not mapping -%}{{ render_xml_attr("patternProperties", spec.patternProperties) }}{%- endif -%}
304
+ {%- for key, value in spec | items -%}
305
+ {%- if key not in structural_keys -%}
306
+ {{ render_xml_attr(key, value) }}
307
+ {%- endif -%}
308
+ {%- endfor -%}
309
+ {%- endif -%}
310
+ {%- endmacro -%}
311
+
312
+ {%- macro xml_schema_has_children(spec, include_properties, include_description) -%}
313
+ {%- if spec is not mapping -%}
314
+ false
315
+ {%- elif (include_description and spec.description is defined) or (include_properties and spec.properties) or 'items' in spec or spec.oneOf or spec.anyOf or spec.additionalProperties is mapping or spec.patternProperties is mapping or spec.returns is defined -%}
316
+ true
317
+ {%- else -%}
318
+ false
319
+ {%- endif -%}
320
+ {%- endmacro -%}
321
+
322
+ {%- macro render_xml_schema_node(tag, spec, include_properties) -%}
323
+ {%- if spec is mapping and spec['$ref'] is string -%}
324
+ {%- set _r = spec['$ref'] -%}
325
+ {%- set _k = _r[8:] if _r.startswith('#/$defs/') else (_r[14:] if _r.startswith('#/definitions/') else none) -%}
326
+ {%- if _k is not none and ('|' + _k + '|') not in REFS.seen and REFS.defs[_k] is mapping -%}
327
+ {%- set spec = dict((REFS.defs[_k] | items | list) + (spec | items | rejectattr('0', 'equalto', '$ref') | list)) -%}
328
+ {%- set REFS.seen = REFS.seen + _k + '|' -%}
329
+ {%- if spec['$ref'] is string -%}
330
+ {%- set _r2 = spec['$ref'] -%}
331
+ {%- set _k2 = _r2[8:] if _r2.startswith('#/$defs/') else (_r2[14:] if _r2.startswith('#/definitions/') else none) -%}
332
+ {%- if _k2 is not none and REFS.defs[_k2] is mapping -%}
333
+ {%- set spec = dict((REFS.defs[_k2] | items | list) + (spec | items | rejectattr('0', 'equalto', '$ref') | list)) -%}
334
+ {%- set REFS.seen = REFS.seen + _k2 + '|' -%}
335
+ {%- endif -%}
336
+ {%- endif -%}
337
+ {%- endif -%}
338
+ {%- endif -%}
339
+ {%- if spec is mapping -%}
340
+ {{- "<" + tag + " type=" + render_compact_type(spec) }}{{ render_xml_schema_attrs(spec, true) }}
341
+ {%- if xml_schema_has_children(spec, include_properties, true) == 'true' -%}
342
+ {{- ">" }}{{ render_xml_schema_children(spec, include_properties, true) }}{{- "</" + tag + ">" }}
343
+ {%- else -%}
344
+ {{- "/>" }}
345
+ {%- endif -%}
346
+ {%- else -%}
347
+ {{- "<" + tag + ">" }}{{ render_xml_value(spec) }}{{- "</" + tag + ">" }}
348
+ {%- endif -%}
349
+ {%- endmacro -%}
350
+
351
+ {%- macro render_xml_pattern_property(pattern, spec) -%}
352
+ {%- if spec is mapping and spec['$ref'] is string -%}
353
+ {%- set _r = spec['$ref'] -%}
354
+ {%- set _k = _r[8:] if _r.startswith('#/$defs/') else (_r[14:] if _r.startswith('#/definitions/') else none) -%}
355
+ {%- if _k is not none and ('|' + _k + '|') not in REFS.seen and REFS.defs[_k] is mapping -%}
356
+ {%- set spec = dict((REFS.defs[_k] | items | list) + (spec | items | rejectattr('0', 'equalto', '$ref') | list)) -%}
357
+ {%- set REFS.seen = REFS.seen + _k + '|' -%}
358
+ {%- if spec['$ref'] is string -%}
359
+ {%- set _r2 = spec['$ref'] -%}
360
+ {%- set _k2 = _r2[8:] if _r2.startswith('#/$defs/') else (_r2[14:] if _r2.startswith('#/definitions/') else none) -%}
361
+ {%- if _k2 is not none and REFS.defs[_k2] is mapping -%}
362
+ {%- set spec = dict((REFS.defs[_k2] | items | list) + (spec | items | rejectattr('0', 'equalto', '$ref') | list)) -%}
363
+ {%- set REFS.seen = REFS.seen + _k2 + '|' -%}
364
+ {%- endif -%}
365
+ {%- endif -%}
366
+ {%- endif -%}
367
+ {%- endif -%}
368
+ {%- if spec is mapping -%}
369
+ {{- "<patternProperty" }}{{ render_xml_attr("pattern", pattern) }}{{- " type=" + render_compact_type(spec) }}{{ render_xml_schema_attrs(spec, true) }}
370
+ {%- if xml_schema_has_children(spec, true, true) == 'true' -%}
371
+ {{- ">" }}{{ render_xml_schema_children(spec, true, true) }}{{- "</patternProperty>" }}
372
+ {%- else -%}
373
+ {{- "/>" }}
374
+ {%- endif -%}
375
+ {%- else -%}
376
+ {{- "<patternProperty" }}{{ render_xml_attr("pattern", pattern) }}{{- ">" }}{{ render_xml_value(spec) }}{{- "</patternProperty>" }}
377
+ {%- endif -%}
378
+ {%- endmacro -%}
379
+
380
+ {%- macro render_xml_schema_children(spec, include_properties, include_description) -%}
381
+ {%- if include_description and spec.description is defined -%}{{- "<description>" }}{{ spec.description }}{{- "</description>" }}{%- endif -%}
382
+ {%- if include_properties and spec.properties -%}
383
+ {%- for child_name, child_spec in spec.properties | items -%}
384
+ {{- render_xml_param(child_name, child_spec, spec.required or []) }}
385
+ {%- endfor -%}
386
+ {%- endif -%}
387
+ {%- if 'items' in spec -%}{{ render_xml_schema_node("items", spec['items'], true) }}{%- endif -%}
388
+ {%- if spec.oneOf -%}
389
+ {{- "<oneOf>" }}
390
+ {%- for variant in spec.oneOf -%}{{ render_xml_schema_node("variant", variant, true) }}{%- endfor -%}
391
+ {{- "</oneOf>" }}
392
+ {%- endif -%}
393
+ {%- if spec.anyOf -%}
394
+ {{- "<anyOf>" }}
395
+ {%- for variant in spec.anyOf -%}{{ render_xml_schema_node("variant", variant, true) }}{%- endfor -%}
396
+ {{- "</anyOf>" }}
397
+ {%- endif -%}
398
+ {%- if spec.additionalProperties is mapping -%}{{ render_xml_schema_node("additionalProperties", spec.additionalProperties, true) }}{%- endif -%}
399
+ {%- if spec.patternProperties is mapping -%}
400
+ {{- "<patternProperties>" }}
401
+ {%- for pattern, pattern_spec in spec.patternProperties | items -%}{{ render_xml_pattern_property(pattern, pattern_spec) }}{%- endfor -%}
402
+ {{- "</patternProperties>" }}
403
+ {%- elif spec.patternProperties is defined -%}<patternProperties>{{ render_xml_value(spec.patternProperties) }}</patternProperties>{%- endif -%}
404
+ {%- if spec.returns is mapping -%}{{ render_xml_schema_node("returns", spec.returns, true) }}{%- elif spec.returns is defined -%}<returns>{{ render_xml_value(spec.returns) }}</returns>{%- endif -%}
405
+ {%- endmacro -%}
406
+
407
+ {%- macro render_xml_param(name, spec, required_list) -%}
408
+ {%- if spec is mapping and spec['$ref'] is string -%}
409
+ {%- set _r = spec['$ref'] -%}
410
+ {%- set _k = _r[8:] if _r.startswith('#/$defs/') else (_r[14:] if _r.startswith('#/definitions/') else none) -%}
411
+ {%- if _k is not none and ('|' + _k + '|') not in REFS.seen and REFS.defs[_k] is mapping -%}
412
+ {%- set spec = dict((REFS.defs[_k] | items | list) + (spec | items | rejectattr('0', 'equalto', '$ref') | list)) -%}
413
+ {%- set REFS.seen = REFS.seen + _k + '|' -%}
414
+ {%- if spec['$ref'] is string -%}
415
+ {%- set _r2 = spec['$ref'] -%}
416
+ {%- set _k2 = _r2[8:] if _r2.startswith('#/$defs/') else (_r2[14:] if _r2.startswith('#/definitions/') else none) -%}
417
+ {%- if _k2 is not none and REFS.defs[_k2] is mapping -%}
418
+ {%- set spec = dict((REFS.defs[_k2] | items | list) + (spec | items | rejectattr('0', 'equalto', '$ref') | list)) -%}
419
+ {%- set REFS.seen = REFS.seen + _k2 + '|' -%}
420
+ {%- endif -%}
421
+ {%- endif -%}
422
+ {%- endif -%}
423
+ {%- endif -%}
424
+ {{- "<param name=" + name + " type=" + render_compact_type(spec) }}
425
+ {%- if name in (required_list or []) -%}{{- " required=true" }}{%- endif -%}
426
+ {%- if spec.enum -%}{{- " enum=" }}{{ render_xml_enum(spec.enum) }}{%- endif -%}
427
+ {%- if spec.default is defined -%}{{ render_xml_default_attr(spec.default) }}{%- endif -%}
428
+ {{- render_xml_schema_attrs(spec, false) }}
429
+ {%- if spec.description or xml_schema_has_children(spec, true, false) == 'true' -%}
430
+ {{- ">" }}
431
+ {%- if spec.description -%}{{ spec.description }}{%- endif -%}
432
+ {{- render_xml_schema_children(spec, true, false) }}
433
+ {{- "</param>" }}
434
+ {%- else -%}
435
+ {{- "/>" }}
436
+ {%- endif -%}
437
+ {%- endmacro -%}
438
+
439
+ {%- macro render_tools_xml(tools_list) -%}
440
+ {{- "<ifm|tools>" }}
441
+ {%- for tool in tools_list -%}
442
+ {%- set fn = tool.function if tool.function is defined else tool -%}
443
+ {%- set REFS.defs = fn.parameters['$defs'] if (fn.parameters is mapping and fn.parameters['$defs'] is mapping) else (fn.parameters['definitions'] if (fn.parameters is mapping and fn.parameters['definitions'] is mapping) else {}) -%}
444
+ {%- set REFS.seen = '|' -%}
445
+ {%- set fnp = namespace(p=fn.parameters) -%}
446
+ {%- if fnp.p is mapping and fnp.p['$ref'] is string -%}
447
+ {%- set _r = fnp.p['$ref'] -%}
448
+ {%- set _k = _r[8:] if _r.startswith('#/$defs/') else (_r[14:] if _r.startswith('#/definitions/') else none) -%}
449
+ {%- if _k is not none and REFS.defs[_k] is mapping -%}
450
+ {%- set fnp.p = dict((REFS.defs[_k] | items | list) + (fnp.p | items | rejectattr('0', 'equalto', '$ref') | list)) -%}
451
+ {%- set REFS.seen = REFS.seen + _k + '|' -%}
452
+ {%- endif -%}
453
+ {%- endif -%}
454
+ {{- "\n<function name=" + fn.name + ">" }}
455
+ {%- if fn.description -%}
456
+ {{- "<description>" }}{{ fn.description }}{{- "</description>" }}
457
+ {%- endif -%}
458
+ {{- "<parameters>" }}
459
+ {%- if fnp.p and fnp.p.properties -%}
460
+ {%- for pname, pspec in fnp.p.properties | items -%}
461
+ {{- render_xml_param(pname, pspec, fnp.p.required or []) }}
462
+ {%- endfor -%}
463
+ {%- elif fnp.p is mapping and (fnp.p.oneOf or fnp.p.anyOf or 'items' in fnp.p) -%}
464
+ {{- render_xml_schema_children(fnp.p, true, false) }}
465
+ {%- endif -%}
466
+ {{- "</parameters>" }}
467
+ {%- set fn_ret = fn.returns if fn.returns is defined else fn.response -%}
468
+ {%- if fn_ret is mapping -%}{{ render_xml_schema_node("returns", fn_ret, true) }}{%- elif fn_ret is defined -%}<returns>{{ render_xml_value(fn_ret) }}</returns>{%- endif -%}
469
+ {{- "</function>" }}
470
+ {%- endfor -%}
471
+ {{- "\n</ifm|tools>" }}
472
+ {%- endmacro -%}
473
+
474
+ {%- macro render_markdown_literal(value) -%}
475
+ {%- if value is string and value == "" -%}""
476
+ {%- elif value is string -%}`{{ value | replace("\n", "\\n") }}`
477
+ {%- else -%}`{{ render_python_repr(value) }}`
478
+ {%- endif -%}
479
+ {%- endmacro -%}
480
+
481
+ {%- macro render_allowed_values(values) -%}
482
+ {%- for value in values -%}{{ render_markdown_literal(value) }}{% if not loop.last %}, {% endif %}{%- endfor -%}
483
+ {%- endmacro -%}
484
+
485
+ {%- macro render_markdown_value(value) -%}
486
+ {%- if value is string and value == "" -%}""{%- elif value is string -%}{{ value }}{%- else -%}{{ render_python_repr(value) }}{%- endif -%}
487
+ {%- endmacro -%}
488
+
489
+ {%- macro render_markdown_detail(indent, label, value) -%}
490
+ {{- "\n" + indent + " - " + label + ": " }}{{ render_markdown_value(value) }}
491
+ {%- endmacro -%}
492
+
493
+ {%- macro render_markdown_metadata_detail(label, value) -%}
494
+ {{- "\n- " + label + ": " }}{{ render_markdown_value(value) }}
495
+ {%- endmacro -%}
496
+
497
+ {%- macro render_markdown_schema_annotations(spec, indent, include_value_details) -%}
498
+ {%- if include_value_details and spec.description is defined -%}{{ render_markdown_detail(indent, "Description", spec.description | replace("\n", "\n" + indent + " ")) }}{%- endif -%}
499
+ {%- if include_value_details and spec.enum is defined -%}{{- "\n" + indent + " - Allowed values: " }}{{ render_allowed_values(spec.enum) }}{%- endif -%}
500
+ {%- if include_value_details and spec.default is defined -%}{{- "\n" + indent + " - Default: " }}{{ render_markdown_literal(spec.default) }}{%- endif -%}
501
+ {%- if spec.additionalProperties is defined -%}
502
+ {%- if spec.additionalProperties is mapping -%}
503
+ {{- "\n" + indent + " - Additional properties *(" + render_markdown_type(spec.additionalProperties) + ")*" }}
504
+ {{- render_markdown_schema_details(spec.additionalProperties, indent + " ", true) }}
505
+ {%- else -%}
506
+ {{ render_markdown_detail(indent, "Additional properties", spec.additionalProperties) }}
507
+ {%- endif -%}
508
+ {%- endif -%}
509
+ {%- endmacro -%}
510
+
511
+ {%- macro render_markdown_metadata_annotations(spec) -%}
512
+ {%- if spec.description is defined -%}{{ render_markdown_metadata_detail("Description", spec.description | replace("\n", "\n ")) }}{%- endif -%}
513
+ {%- if spec.enum is defined -%}{{- "\n- Allowed values: " }}{{ render_allowed_values(spec.enum) }}{%- endif -%}
514
+ {%- if spec.default is defined -%}{{- "\n- Default: " }}{{ render_markdown_literal(spec.default) }}{%- endif -%}
515
+ {%- if spec.additionalProperties is defined -%}
516
+ {%- if spec.additionalProperties is mapping -%}
517
+ {{- "\n- Additional properties *(" + render_markdown_type(spec.additionalProperties) + ")*" }}
518
+ {{- render_markdown_schema_details(spec.additionalProperties, "", true) }}
519
+ {%- else -%}
520
+ {{ render_markdown_metadata_detail("Additional properties", spec.additionalProperties) }}
521
+ {%- endif -%}
522
+ {%- endif -%}
523
+ {%- endmacro -%}
524
+
525
+ {%- macro render_markdown_schema_extras(spec, indent) -%}
526
+ {%- set rendered_keys = ["type", "description", "enum", "default", "properties", "required", "items", "oneOf", "anyOf", "additionalProperties", "patternProperties", "returns"] -%}
527
+ {%- for key, value in spec | items -%}
528
+ {%- if key not in rendered_keys -%}
529
+ {{- "\n" + indent + " - " + key + ": " }}{{ render_markdown_value(value) }}
530
+ {%- endif -%}
531
+ {%- endfor -%}
532
+ {%- endmacro -%}
533
+
534
+ {%- macro render_markdown_metadata_extras(spec) -%}
535
+ {%- set rendered_keys = ["type", "description", "enum", "default", "properties", "required", "items", "oneOf", "anyOf", "additionalProperties", "patternProperties", "returns"] -%}
536
+ {%- for key, value in spec | items -%}
537
+ {%- if key not in rendered_keys -%}
538
+ {{- "\n- " + key + ": " }}{{ render_markdown_value(value) }}
539
+ {%- endif -%}
540
+ {%- endfor -%}
541
+ {%- endmacro -%}
542
+
543
+ {%- macro markdown_schema_has_extra(spec) -%}
544
+ {%- set rendered_keys = ["type", "description", "enum", "default", "properties", "required", "items", "oneOf", "anyOf", "additionalProperties", "patternProperties", "returns"] -%}
545
+ {%- set found = namespace(value='false') -%}
546
+ {%- for key, value in spec | items -%}
547
+ {%- if key not in rendered_keys -%}{%- set found.value = 'true' -%}{%- endif -%}
548
+ {%- endfor -%}
549
+ {{- found.value -}}
550
+ {%- endmacro -%}
551
+
552
+ {%- macro markdown_parameter_schema_has_details(spec) -%}
553
+ {%- if spec.description is defined or spec.enum is defined or spec.default is defined or spec.additionalProperties is defined or spec.patternProperties is defined or 'items' in spec or spec.oneOf or spec.anyOf or spec.returns is defined or markdown_schema_has_extra(spec) == 'true' -%}
554
+ true
555
+ {%- else -%}
556
+ false
557
+ {%- endif -%}
558
+ {%- endmacro -%}
559
+
560
+ {%- macro render_markdown_schema_structure(spec, indent, include_properties) -%}
561
+ {%- if include_properties and spec.properties -%}
562
+ {%- for child_name, child_spec in spec.properties | items -%}
563
+ {{- render_markdown_param(child_name, child_spec, spec.required or [], indent + " ") }}
564
+ {%- endfor -%}
565
+ {%- endif -%}
566
+ {%- if 'items' in spec and spec['items'] is mapping -%}
567
+ {{- "\n" + indent + " - Items *(" + render_markdown_type(spec['items']) + ")*" }}
568
+ {{- render_markdown_schema_details(spec['items'], indent + " ", true) }}
569
+ {%- elif 'items' in spec -%}
570
+ {{ render_markdown_detail(indent, "Items", spec['items']) }}
571
+ {%- endif -%}
572
+ {%- if spec.oneOf -%}
573
+ {{- "\n" + indent + " - oneOf:" }}
574
+ {%- for variant in spec.oneOf -%}
575
+ {{- "\n" + indent + " - Variant " }}{{ loop.index }}{{- " *(" + render_markdown_type(variant) + ")*" }}
576
+ {{- render_markdown_schema_details(variant, indent + " ", true) }}
577
+ {%- endfor -%}
578
+ {%- endif -%}
579
+ {%- if spec.anyOf -%}
580
+ {{- "\n" + indent + " - anyOf:" }}
581
+ {%- for variant in spec.anyOf -%}
582
+ {{- "\n" + indent + " - Variant " }}{{ loop.index }}{{- " *(" + render_markdown_type(variant) + ")*" }}
583
+ {{- render_markdown_schema_details(variant, indent + " ", true) }}
584
+ {%- endfor -%}
585
+ {%- endif -%}
586
+ {%- if spec.patternProperties is mapping -%}
587
+ {{- "\n" + indent + " - Pattern properties:" }}
588
+ {%- for pattern, pattern_spec in spec.patternProperties | items -%}
589
+ {%- if pattern_spec is mapping -%}
590
+ {{- "\n" + indent + " - `" + pattern + "` *(" + render_markdown_type(pattern_spec) + ")*" }}
591
+ {{- render_markdown_schema_details(pattern_spec, indent + " ", true) }}
592
+ {%- else -%}
593
+ {{- "\n" + indent + " - `" + pattern + "`: " }}{{ render_markdown_value(pattern_spec) }}
594
+ {%- endif -%}
595
+ {%- endfor -%}
596
+ {%- elif spec.patternProperties is defined -%}
597
+ {{ render_markdown_detail(indent, "Pattern properties", spec.patternProperties) }}
598
+ {%- endif -%}
599
+ {%- if spec.returns is mapping -%}
600
+ {{- "\n" + indent + " - Returns *(" + render_markdown_type(spec.returns) + ")*" }}
601
+ {{- render_markdown_schema_details(spec.returns, indent + " ", true) }}
602
+ {%- elif spec.returns is defined -%}
603
+ {{ render_markdown_detail(indent, "Returns", spec.returns) }}
604
+ {%- endif -%}
605
+ {%- endmacro -%}
606
+
607
+ {%- macro render_markdown_schema_details(spec, indent, include_value_details) -%}
608
+ {%- if spec is mapping and spec['$ref'] is string -%}
609
+ {%- set _r = spec['$ref'] -%}
610
+ {%- set _k = _r[8:] if _r.startswith('#/$defs/') else (_r[14:] if _r.startswith('#/definitions/') else none) -%}
611
+ {%- if _k is not none and ('|' + _k + '|') not in REFS.seen and REFS.defs[_k] is mapping -%}
612
+ {%- set spec = dict((REFS.defs[_k] | items | list) + (spec | items | rejectattr('0', 'equalto', '$ref') | list)) -%}
613
+ {%- set REFS.seen = REFS.seen + _k + '|' -%}
614
+ {%- if spec['$ref'] is string -%}
615
+ {%- set _r2 = spec['$ref'] -%}
616
+ {%- set _k2 = _r2[8:] if _r2.startswith('#/$defs/') else (_r2[14:] if _r2.startswith('#/definitions/') else none) -%}
617
+ {%- if _k2 is not none and REFS.defs[_k2] is mapping -%}
618
+ {%- set spec = dict((REFS.defs[_k2] | items | list) + (spec | items | rejectattr('0', 'equalto', '$ref') | list)) -%}
619
+ {%- set REFS.seen = REFS.seen + _k2 + '|' -%}
620
+ {%- endif -%}
621
+ {%- endif -%}
622
+ {%- endif -%}
623
+ {%- endif -%}
624
+ {%- if spec is mapping -%}
625
+ {{- render_markdown_schema_annotations(spec, indent, include_value_details) }}
626
+ {{- render_markdown_schema_structure(spec, indent, true) }}
627
+ {{- render_markdown_schema_extras(spec, indent) }}
628
+ {%- elif spec is not sameas true and spec is not sameas false -%}
629
+ {{- "\n" + indent + " - Value: " }}{{ render_markdown_literal(spec) }}
630
+ {%- endif -%}
631
+ {%- endmacro -%}
632
+
633
+ {%- macro render_markdown_parameter_schema(spec) -%}
634
+ {%- if spec is mapping and spec['$ref'] is string -%}
635
+ {%- set _r = spec['$ref'] -%}
636
+ {%- set _k = _r[8:] if _r.startswith('#/$defs/') else (_r[14:] if _r.startswith('#/definitions/') else none) -%}
637
+ {%- if _k is not none and ('|' + _k + '|') not in REFS.seen and REFS.defs[_k] is mapping -%}
638
+ {%- set spec = dict((REFS.defs[_k] | items | list) + (spec | items | rejectattr('0', 'equalto', '$ref') | list)) -%}
639
+ {%- set REFS.seen = REFS.seen + _k + '|' -%}
640
+ {%- if spec['$ref'] is string -%}
641
+ {%- set _r2 = spec['$ref'] -%}
642
+ {%- set _k2 = _r2[8:] if _r2.startswith('#/$defs/') else (_r2[14:] if _r2.startswith('#/definitions/') else none) -%}
643
+ {%- if _k2 is not none and REFS.defs[_k2] is mapping -%}
644
+ {%- set spec = dict((REFS.defs[_k2] | items | list) + (spec | items | rejectattr('0', 'equalto', '$ref') | list)) -%}
645
+ {%- set REFS.seen = REFS.seen + _k2 + '|' -%}
646
+ {%- endif -%}
647
+ {%- endif -%}
648
+ {%- endif -%}
649
+ {%- endif -%}
650
+ {%- if spec is mapping -%}
651
+ {{- render_markdown_metadata_annotations(spec) }}
652
+ {%- if 'items' in spec and spec['items'] is mapping -%}
653
+ {{- "\n- Items *(" + render_markdown_type(spec['items']) + ")*" }}
654
+ {{- render_markdown_schema_details(spec['items'], "", true) }}
655
+ {%- elif 'items' in spec -%}
656
+ {{ render_markdown_metadata_detail("Items", spec['items']) }}
657
+ {%- endif -%}
658
+ {%- if spec.oneOf -%}
659
+ {{- "\n- oneOf:" }}
660
+ {%- for variant in spec.oneOf -%}
661
+ {{- "\n - Variant " }}{{ loop.index }}{{- " *(" + render_markdown_type(variant) + ")*" }}
662
+ {{- render_markdown_schema_details(variant, " ", true) }}
663
+ {%- endfor -%}
664
+ {%- endif -%}
665
+ {%- if spec.anyOf -%}
666
+ {{- "\n- anyOf:" }}
667
+ {%- for variant in spec.anyOf -%}
668
+ {{- "\n - Variant " }}{{ loop.index }}{{- " *(" + render_markdown_type(variant) + ")*" }}
669
+ {{- render_markdown_schema_details(variant, " ", true) }}
670
+ {%- endfor -%}
671
+ {%- endif -%}
672
+ {%- if spec.patternProperties is mapping -%}
673
+ {{- "\n- Pattern properties:" }}
674
+ {%- for pattern, pattern_spec in spec.patternProperties | items -%}
675
+ {%- if pattern_spec is mapping -%}
676
+ {{- "\n - `" + pattern + "` *(" + render_markdown_type(pattern_spec) + ")*" }}
677
+ {{- render_markdown_schema_details(pattern_spec, " ", true) }}
678
+ {%- else -%}
679
+ {{- "\n - `" + pattern + "`: " }}{{ render_markdown_value(pattern_spec) }}
680
+ {%- endif -%}
681
+ {%- endfor -%}
682
+ {%- elif spec.patternProperties is defined -%}
683
+ {{ render_markdown_metadata_detail("Pattern properties", spec.patternProperties) }}
684
+ {%- endif -%}
685
+ {%- if spec.returns is mapping -%}
686
+ {{- "\n- Returns *(" + render_markdown_type(spec.returns) + ")*" }}
687
+ {{- render_markdown_schema_details(spec.returns, "", true) }}
688
+ {%- elif spec.returns is defined -%}
689
+ {{ render_markdown_metadata_detail("Returns", spec.returns) }}
690
+ {%- endif -%}
691
+ {{- render_markdown_metadata_extras(spec) }}
692
+ {%- endif -%}
693
+ {%- endmacro -%}
694
+
695
+ {%- macro render_markdown_param(name, spec, required_list, indent) -%}
696
+ {%- if spec is mapping and spec['$ref'] is string -%}
697
+ {%- set _r = spec['$ref'] -%}
698
+ {%- set _k = _r[8:] if _r.startswith('#/$defs/') else (_r[14:] if _r.startswith('#/definitions/') else none) -%}
699
+ {%- if _k is not none and ('|' + _k + '|') not in REFS.seen and REFS.defs[_k] is mapping -%}
700
+ {%- set spec = dict((REFS.defs[_k] | items | list) + (spec | items | rejectattr('0', 'equalto', '$ref') | list)) -%}
701
+ {%- set REFS.seen = REFS.seen + _k + '|' -%}
702
+ {%- if spec['$ref'] is string -%}
703
+ {%- set _r2 = spec['$ref'] -%}
704
+ {%- set _k2 = _r2[8:] if _r2.startswith('#/$defs/') else (_r2[14:] if _r2.startswith('#/definitions/') else none) -%}
705
+ {%- if _k2 is not none and REFS.defs[_k2] is mapping -%}
706
+ {%- set spec = dict((REFS.defs[_k2] | items | list) + (spec | items | rejectattr('0', 'equalto', '$ref') | list)) -%}
707
+ {%- set REFS.seen = REFS.seen + _k2 + '|' -%}
708
+ {%- endif -%}
709
+ {%- endif -%}
710
+ {%- endif -%}
711
+ {%- endif -%}
712
+ {{- "\n" + indent + "- `" + name + "` *(" + render_markdown_type(spec) }}
713
+ {%- if name in (required_list or []) -%}{{- ", required" }}{%- endif -%}
714
+ {{- ")*" }}
715
+ {%- if spec.description -%}{{- " - " + spec.description | replace("\n", "\n" + indent + " ") }}{%- endif -%}
716
+ {%- if spec.enum -%}
717
+ {{- "\n" + indent + " - Allowed values: " }}{{ render_allowed_values(spec.enum) }}
718
+ {%- endif -%}
719
+ {%- if spec.default is defined -%}
720
+ {{- "\n" + indent + " - Default: " }}{{ render_markdown_literal(spec.default) }}
721
+ {%- endif -%}
722
+ {{- render_markdown_schema_details(spec, indent, false) }}
723
+ {%- endmacro -%}
724
+
725
+ {%- macro render_tools_markdown(tools_list) -%}
726
+ {{- "<ifm|tools>" }}
727
+ {%- for tool in tools_list -%}
728
+ {%- set fn = tool.function if tool.function is defined else tool -%}
729
+ {%- set REFS.defs = fn.parameters['$defs'] if (fn.parameters is mapping and fn.parameters['$defs'] is mapping) else (fn.parameters['definitions'] if (fn.parameters is mapping and fn.parameters['definitions'] is mapping) else {}) -%}
730
+ {%- set REFS.seen = '|' -%}
731
+ {%- set fnp = namespace(p=fn.parameters) -%}
732
+ {%- if fnp.p is mapping and fnp.p['$ref'] is string -%}
733
+ {%- set _r = fnp.p['$ref'] -%}
734
+ {%- set _k = _r[8:] if _r.startswith('#/$defs/') else (_r[14:] if _r.startswith('#/definitions/') else none) -%}
735
+ {%- if _k is not none and REFS.defs[_k] is mapping -%}
736
+ {%- set fnp.p = dict((REFS.defs[_k] | items | list) + (fnp.p | items | rejectattr('0', 'equalto', '$ref') | list)) -%}
737
+ {%- set REFS.seen = REFS.seen + _k + '|' -%}
738
+ {%- endif -%}
739
+ {%- endif -%}
740
+ {{- "\n## " + fn.name }}
741
+ {%- if fn.description -%}
742
+ {{- "\n" + fn.description }}
743
+ {%- endif -%}
744
+ {{- "\n\n**Parameters**" }}
745
+ {%- if fnp.p and fnp.p.properties -%}
746
+ {%- for pname, pspec in fnp.p.properties | items -%}
747
+ {{- render_markdown_param(pname, pspec, fnp.p.required or [], "") }}
748
+ {%- endfor -%}
749
+ {%- elif fnp.p is mapping and (fnp.p.oneOf or fnp.p.anyOf or 'items' in fnp.p) -%}
750
+ {{- render_markdown_parameter_schema(fnp.p) }}
751
+ {%- else -%}
752
+ {{- "\n- None" }}
753
+ {%- endif -%}
754
+ {%- set fn_ret = fn.returns if fn.returns is defined else fn.response -%}
755
+ {%- if fn_ret is mapping -%}
756
+ {{- "\n\n**Returns**" }}
757
+ {{- "\n- Return *(" + render_markdown_type(fn_ret) + ")*" }}
758
+ {{- render_markdown_schema_details(fn_ret, "", true) }}
759
+ {%- elif fn_ret is defined -%}
760
+ {{- "\n\n**Returns**\n- " }}{{ render_markdown_value(fn_ret) }}
761
+ {%- endif -%}
762
+ {%- if not loop.last -%}{{- "\n" }}{%- endif -%}
763
+ {%- endfor -%}
764
+ {{- "\n</ifm|tools>" }}
765
+ {%- endmacro -%}
766
+
767
+ {%- macro render_tool_presentation(tools_list, fmt) -%}
768
+ {%- if fmt == 'json' -%}
769
+ {{- render_tools_json(tools_list) }}
770
+ {%- elif RB.bad != '|' -%}
771
+ {#- some tool uses constructs the pretty renderers cannot represent (verdicts -#}
772
+ {#- computed during validate_tools): render the WHOLE toolset exactly as the -#}
773
+ {#- json presentation would, so the block stays uniform and model-familiar. -#}
774
+ {{- render_tools_json(tools_list) }}
775
+ {%- elif fmt == 'xml' -%}
776
+ {{- render_tools_xml(tools_list) }}
777
+ {%- elif fmt == 'markdown' -%}
778
+ {{- render_tools_markdown(tools_list) }}
779
+ {%- else -%}
780
+ {{- raise_exception("Unsupported tool_presentation_format: '" + fmt + "'. Supported formats: json, xml, markdown.") }}
781
+ {%- endif -%}
782
+ {%- endmacro -%}
783
+
784
+ {%- macro render_call_instructions(fmt) -%}
785
+ {%- if fmt == 'json' -%}
786
+ {{- "Wrap all tool calls in a single <ifm|tool_calls></ifm|tool_calls> block. For each call, emit one JSON object with the function name and arguments on the same line inside <ifm|tool_call></ifm|tool_call> tags:\n\n<ifm|tool_calls>\n<ifm|tool_call>{\"name\": <function-name>, \"arguments\": <args-json-object>}</ifm|tool_call>\n</ifm|tool_calls>" }}
787
+ {%- elif fmt == 'xml' -%}
788
+ {{- "Wrap all tool calls in a single <ifm|tool_calls></ifm|tool_calls> block. For each call, write the function name at the start of <ifm|tool_call>, followed by paired <ifm|arg_key> and <ifm|arg_value> tags for each argument:\n\n<ifm|tool_calls>\n<ifm|tool_call>$FUNCTION_NAME\n<ifm|arg_key>$PARAMETER_NAME</ifm|arg_key>\n<ifm|arg_value>$PARAMETER_VALUE</ifm|arg_value>\n...\n</ifm|tool_call>\n</ifm|tool_calls>\n\nString and scalar parameters should be written as plain text. Array and object parameters should be written as JSON literals." }}
789
+ {%- elif fmt == 'xml_typed' -%}
790
+ {{- "Wrap all tool calls in a single <ifm|tool_calls></ifm|tool_calls> block. For each call, write the function name at the start of <ifm|tool_call>, followed by <ifm|arg_key>, <ifm|arg_type>, and <ifm|arg_value> tags for each argument:\n\n<ifm|tool_calls>\n<ifm|tool_call>$FUNCTION_NAME\n<ifm|arg_key>$PARAMETER_NAME</ifm|arg_key>\n<ifm|arg_type>$ARGUMENT_TYPE</ifm|arg_type>\n<ifm|arg_value>$PARAMETER_VALUE</ifm|arg_value>\n...\n</ifm|tool_call>\n</ifm|tool_calls>\n\nUse the parameter type shown in the tool definition. If that type contains anyOf or oneOf, use the actual argument value type instead. String and scalar parameters should be written as plain text. Array and object parameters should be written as JSON literals." }}
791
+ {%- else -%}
792
+ {{- raise_exception("Unsupported tool_call_format: '" + fmt + "'. Supported formats: json, xml, xml_typed.") }}
793
+ {%- endif -%}
794
+ {%- endmacro -%}
795
+
796
+ {%- macro render_system_with_tools(tools_list, system_content, presentation_fmt, call_fmt) -%}
797
+ {{- "<|ifm|im_start|>system\n# Tools\nYou may call one or more tools to assist with the user query.\n\nAvailable tools are:\n\n" }}
798
+ {{- render_tool_presentation(tools_list, presentation_fmt) }}
799
+ {{- "\n\nWhen calling tools, you MUST follow the tool-call format below:\n\n" }}
800
+ {{- render_call_instructions(call_fmt) }}
801
+ {%- if system_content -%}
802
+ {{- "\n\n" + system_content }}
803
+ {%- endif -%}
804
+ {{- "<|ifm|im_end|>" }}
805
+ {%- endmacro -%}
806
+
807
+ {%- macro render_argument_value(value) -%}
808
+ {%- if value is string -%}{{- value -}}{%- else -%}{{- value | tojson -}}{%- endif -%}
809
+ {%- endmacro -%}
810
+
811
+ {%- macro render_value_type(value) -%}
812
+ {%- if value is none -%}null
813
+ {%- elif value is boolean -%}boolean
814
+ {%- elif value is integer -%}integer
815
+ {%- elif value is number -%}number
816
+ {%- elif value is string -%}string
817
+ {%- elif value is mapping -%}object
818
+ {%- elif value is sequence -%}array
819
+ {%- else -%}any
820
+ {%- endif -%}
821
+ {%- endmacro -%}
822
+
823
+ {%- macro schema_has_combinator(spec) -%}
824
+ {%- if spec.oneOf or spec.anyOf -%}
825
+ true
826
+ {%- elif spec.type is defined and spec.type is sequence and spec.type is not string and spec.type | length > 1 -%}
827
+ true
828
+ {%- elif spec.type == "array" and 'items' in spec -%}
829
+ {{- schema_has_combinator(spec['items']) -}}
830
+ {%- elif spec.properties -%}
831
+ {%- set found = namespace(value='false') -%}
832
+ {%- for child_name, child_spec in spec.properties | items -%}
833
+ {%- if schema_has_combinator(child_spec) == 'true' -%}
834
+ {%- set found.value = 'true' -%}
835
+ {%- endif -%}
836
+ {%- endfor -%}
837
+ {{- found.value -}}
838
+ {%- else -%}
839
+ false
840
+ {%- endif -%}
841
+ {%- endmacro -%}
842
+
843
+ {%- macro render_arg_type(tools_list, tool_name, arg_name, value) -%}
844
+ {%- set found = namespace(type='any') -%}
845
+ {%- for tool in tools_list -%}
846
+ {%- set fn = tool.function if tool.function is defined else tool -%}
847
+ {%- if fn.name == tool_name and fn.parameters and fn.parameters.properties and arg_name in fn.parameters.properties -%}
848
+ {%- set spec = fn.parameters.properties[arg_name] -%}
849
+ {%- if spec is mapping and spec['$ref'] is string -%}
850
+ {%- set _r = spec['$ref'] -%}
851
+ {%- set _k = _r[8:] if _r.startswith('#/$defs/') else (_r[14:] if _r.startswith('#/definitions/') else none) -%}
852
+ {%- set _d = fn.parameters['$defs'] if fn.parameters['$defs'] is mapping else fn.parameters['definitions'] -%}
853
+ {%- set spec = dict((_d[_k] | items | list) + (spec | items | rejectattr('0', 'equalto', '$ref') | list)) if (_k is not none and _d is mapping and _d[_k] is mapping) else spec -%}
854
+ {%- endif -%}
855
+ {%- if schema_has_combinator(spec) == 'true' -%}
856
+ {%- set found.type = render_value_type(value) -%}
857
+ {%- else -%}
858
+ {%- set found.type = render_compact_type(spec) -%}
859
+ {%- endif -%}
860
+ {%- endif -%}
861
+ {%- endfor -%}
862
+ {{- found.type -}}
863
+ {%- endmacro -%}
864
+
865
+ {%- macro render_tool_calls_block(tool_calls, fmt, tools_list) -%}
866
+ {{- "<ifm|tool_calls>" }}
867
+ {%- for raw_tool_call in tool_calls -%}
868
+ {%- set tool_call = raw_tool_call.function if raw_tool_call.function else raw_tool_call -%}
869
+ {%- if tool_call.arguments is string -%}
870
+ {{- raise_exception("tool_call.arguments must be a dict, not a JSON string. Parse it before passing to the template.") -}}
871
+ {%- endif -%}
872
+ {%- if fmt == 'json' -%}
873
+ {{- "\n<ifm|tool_call>{\"name\": \"" + tool_call.name + "\", \"arguments\": " }}{{ tool_call.arguments | tojson }}{{- "}</ifm|tool_call>" }}
874
+ {%- elif fmt == 'xml' or fmt == 'xml_typed' -%}
875
+ {{- "\n<ifm|tool_call>" + tool_call.name + "\n" }}
876
+ {%- for key, value in tool_call.arguments | items -%}
877
+ {{- "<ifm|arg_key>" + key + "</ifm|arg_key>\n" }}
878
+ {%- if fmt == 'xml_typed' -%}
879
+ {{- "<ifm|arg_type>" + render_arg_type(tools_list, tool_call.name, key, value) + "</ifm|arg_type>\n" }}
880
+ {%- endif -%}
881
+ {{- "<ifm|arg_value>" }}{{ render_argument_value(value) }}{{- "</ifm|arg_value>\n" }}
882
+ {%- endfor -%}
883
+ {{- "</ifm|tool_call>" }}
884
+ {%- else -%}
885
+ {{- raise_exception("Unsupported tool_call_format: '" + fmt + "'. Supported formats: json, xml, xml_typed.") -}}
886
+ {%- endif -%}
887
+ {%- endfor -%}
888
+ {{- "\n</ifm|tool_calls>" }}
889
+ {%- endmacro -%}
890
+
891
+ {%- macro render_tool_response_messages(raw_content) -%}
892
+ {%- if raw_content is string -%}
893
+ {{- '<|ifm|im_start|>tool\n' + raw_content + '<|ifm|im_end|>' }}
894
+ {%- elif raw_content is sequence and raw_content is not string and raw_content is not mapping -%}
895
+ {%- if raw_content | length == 0 -%}
896
+ {{- raise_exception("tool message content list must not be empty.") -}}
897
+ {%- endif -%}
898
+ {{- '<|ifm|im_start|>tool\n' -}}
899
+ {%- for item in raw_content -%}
900
+ {%- if not loop.first -%}{{- '\n' -}}{%- endif -%}
901
+ {%- if item is string -%}
902
+ {{- item -}}
903
+ {%- elif item is mapping and item.text is string -%}
904
+ {{- item.text -}}
905
+ {%- else -%}
906
+ {{- (item | tojson) -}}
907
+ {%- endif -%}
908
+ {%- endfor -%}
909
+ {{- '<|ifm|im_end|>' -}}
910
+ {%- else -%}
911
+ {{- '<|ifm|im_start|>tool\n' }}{{ raw_content | tojson }}{{- '<|ifm|im_end|>' }}
912
+ {%- endif -%}
913
+ {%- endmacro -%}
914
+
915
+ {%- set available_tools = tools if tools else [] -%}
916
+ {%- if (not available_tools) and messages[0].role == 'system' and messages[0].get('tools') -%}
917
+ {%- set available_tools = messages[0]['tools'] -%}
918
+ {%- endif -%}
919
+ {%- if available_tools -%}
920
+ {{- validate_tools(available_tools, tool_presentation_fmt != 'json') }}
921
+ {%- set system_content = '' -%}
922
+ {%- if messages[0].role == 'system' and messages[0].content -%}
923
+ {%- set system_content = messages[0].content -%}
924
+ {%- endif -%}
925
+ {{- render_system_with_tools(available_tools, system_content, tool_presentation_fmt, tool_call_fmt) }}
926
+ {%- else -%}
927
+ {%- if messages[0].role == 'system' -%}
928
+ {{- '<|ifm|im_start|>system\n' + messages[0].content + '<|ifm|im_end|>' }}
929
+ {%- endif -%}
930
+ {%- endif -%}
931
+
932
+ {%- for message in messages -%}
933
+ {%- if message.content is string -%}
934
+ {%- set content = message.content -%}
935
+ {%- else -%}
936
+ {%- set content = '' -%}
937
+ {%- endif -%}
938
+ {%- if (message.role == "user") or (message.role == "system" and not loop.first) -%}
939
+ {{- '<|ifm|im_start|>' + message.role + '\n' + content + '<|ifm|im_end|>' }}
940
+ {%- elif message.role == "assistant" -%}
941
+ {%- set thinking_content = '' -%}
942
+ {%- set think_tag = 'ifm|think' -%}
943
+ {%- if message.think is defined and message.think is string -%}
944
+ {%- set thinking_content = message.think -%}
945
+ {%- set think_tag = 'ifm|think' -%}
946
+ {%- elif message.think_fast is defined and message.think_fast is string -%}
947
+ {%- set thinking_content = message.think_fast -%}
948
+ {%- set think_tag = 'ifm|think_fast' -%}
949
+ {%- elif message.think_faster is defined and message.think_faster is string -%}
950
+ {%- set thinking_content = message.think_faster -%}
951
+ {%- set think_tag = 'ifm|think_faster' -%}
952
+ {%- elif message.reasoning_content is defined and message.reasoning_content is string -%}
953
+ {%- set thinking_content = message.reasoning_content -%}
954
+ {%- set think_tag = 'ifm|think' -%}
955
+ {%- elif message.reasoning is defined and message.reasoning is string -%}
956
+ {%- set thinking_content = message.reasoning -%}
957
+ {%- set think_tag = 'ifm|think' -%}
958
+ {%- elif message.think is not defined and message.reasoning is not defined and message.reasoning_content is not defined and message.think_fast is not defined and message.think_faster is not defined -%}
959
+ {{- raise_exception("Assistant message is missing a thinking field. Provide one of: think, reasoning, reasoning_content, think_fast, think_faster.") -}}
960
+ {%- else -%}
961
+ {{- raise_exception("Assistant thinking fields must be strings. Provide one of: think, reasoning, reasoning_content, think_fast, think_faster as a string.") -}}
962
+ {%- endif -%}
963
+ {{- '<|ifm|im_start|>' + message.role }}
964
+ {% generation %}
965
+ {%- if think_tag -%}
966
+ {%- if thinking_content -%}
967
+ {{- '<' + think_tag + '>\n' + thinking_content + '</' + think_tag + '>' + content }}
968
+ {%- else -%}
969
+ {{- '<' + think_tag + '>\n</' + think_tag + '>' + content }}
970
+ {%- endif -%}
971
+ {%- else -%}
972
+ {{- content }}
973
+ {%- endif -%}
974
+ {%- if message.tool_calls -%}
975
+ {{- render_tool_calls_block(message.tool_calls, tool_call_fmt, available_tools) }}
976
+ {%- endif -%}
977
+ {{- '<|ifm|im_end|>' -}}
978
+ {%- endgeneration -%}
979
+ {%- elif message.role == "tool" -%}
980
+ {{- render_tool_response_messages(message.content) }}
981
+ {%- endif -%}
982
+ {%- endfor -%}
983
+ {%- if add_generation_prompt -%}
984
+ {%- set effort = reasoning_effort | default('high') -%}
985
+ {%- if effort == 'high' -%}
986
+ {{- '<|ifm|im_start|>assistant\n<ifm|think>\n' }}
987
+ {%- elif effort == 'medium' -%}
988
+ {{- '<|ifm|im_start|>assistant\n<ifm|think_fast>\n' }}
989
+ {%- elif effort == 'low' -%}
990
+ {{- '<|ifm|im_start|>assistant\n<ifm|think_faster>\n' }}
991
+ {%- else -%}
992
+ {{- raise_exception("Unsupported reasoning_effort: '" + effort + "'. Supported values: high, medium, low.") -}}
993
+ {%- endif -%}
994
+ {%- endif -%}
config.json ADDED
@@ -0,0 +1,92 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "K2HorizonForCausalLM"
4
+ ],
5
+ "attention_bias": false,
6
+ "attention_dropout": 0.0,
7
+ "attention_gate_func": null,
8
+ "auto_map": {
9
+ "AutoConfig": "configuration_k2_horizon.K2HorizonConfig",
10
+ "AutoModel": "modeling_k2_horizon.K2HorizonModel",
11
+ "AutoModelForCausalLM": "modeling_k2_horizon.K2HorizonForCausalLM"
12
+ },
13
+ "bos_token_id": 0,
14
+ "decoder_sparse_step": 1,
15
+ "dtype": "bfloat16",
16
+ "eos_token_id": 1,
17
+ "head_dim": 128,
18
+ "hidden_act": "silu",
19
+ "hidden_size": 2560,
20
+ "initializer_range": 0.02,
21
+ "intermediate_size": 10240,
22
+ "layernorm_num_groups": 2,
23
+ "max_position_embeddings": 524288,
24
+ "mlp_only_layers": [
25
+ 0,
26
+ 1,
27
+ 2,
28
+ 3,
29
+ 4,
30
+ 5,
31
+ 6,
32
+ 7,
33
+ 8,
34
+ 9,
35
+ 10,
36
+ 11,
37
+ 12,
38
+ 13,
39
+ 14,
40
+ 15,
41
+ 16,
42
+ 17,
43
+ 18,
44
+ 19,
45
+ 20,
46
+ 21,
47
+ 22,
48
+ 23,
49
+ 24,
50
+ 25,
51
+ 26,
52
+ 27,
53
+ 28,
54
+ 29,
55
+ 30,
56
+ 31,
57
+ 32,
58
+ 33,
59
+ 34,
60
+ 35
61
+ ],
62
+ "model_type": "k2_horizon",
63
+ "moe_gate_bias": false,
64
+ "moe_intermediate_size": 0,
65
+ "mova_num_experts": 0,
66
+ "mova_num_experts_per_tok": 0,
67
+ "norm_topk_prob": true,
68
+ "num_attention_heads": 32,
69
+ "num_experts": 0,
70
+ "num_experts_per_tok": 0,
71
+ "num_hidden_layers": 36,
72
+ "num_key_value_heads": 8,
73
+ "num_shared_experts": 0,
74
+ "output_router_logits": false,
75
+ "pad_token_id": null,
76
+ "query_key_norm": false,
77
+ "rms_norm_eps": 1e-06,
78
+ "rope_head_dim": 128,
79
+ "rope_parameters": {
80
+ "rope_theta": 10000000.0,
81
+ "rope_type": "default"
82
+ },
83
+ "router_aux_loss_coef": 0.001,
84
+ "router_scaling_factor": 1.0,
85
+ "router_score_func": "sigmoid",
86
+ "sliding_window": null,
87
+ "tie_word_embeddings": false,
88
+ "transformers_version": "5.17.0",
89
+ "use_cache": true,
90
+ "use_sliding_window": false,
91
+ "vocab_size": 250624
92
+ }
configuration_k2_horizon.py ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The Qwen team, Alibaba Group and the HuggingFace Inc. team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """K2Horizon model configuration"""
15
+
16
+ from huggingface_hub.dataclasses import strict
17
+
18
+ from transformers.configuration_utils import PreTrainedConfig
19
+ from transformers.modeling_rope_utils import RopeParameters
20
+
21
+
22
+ @strict
23
+ class K2HorizonConfig(PreTrainedConfig):
24
+ r"""
25
+ decoder_sparse_step (`int`, *optional*, defaults to 1):
26
+ The frequency of the MoE layer.
27
+ mlp_only_layers (`list[int]`, *optional*, defaults to `[]`):
28
+ Indicate which layers use K2HorizonMLP rather than K2HorizonSparseMoeBlock
29
+ The list contains layer index, from 0 to num_layers-1 if we have num_layers layers
30
+ If `mlp_only_layers` is empty, `decoder_sparse_step` is used to determine the sparsity.
31
+
32
+ ```python
33
+ >>> from transformers import K2HorizonModel, K2HorizonConfig
34
+
35
+ >>> # Initializing a K2Horizon style configuration
36
+ >>> configuration = K2HorizonConfig()
37
+ >>> model = K2HorizonModel(configuration)
38
+
39
+ >>> # Accessing the model configuration
40
+ >>> configuration = model.config
41
+ ```
42
+ """
43
+
44
+ model_type = "k2_horizon"
45
+ keys_to_ignore_at_inference = ["past_key_values"]
46
+
47
+ vocab_size: int = 151936
48
+ hidden_size: int = 2048
49
+ intermediate_size: int = 6144
50
+ num_hidden_layers: int = 24
51
+ num_attention_heads: int = 32
52
+ num_key_value_heads: int = 4
53
+ hidden_act: str = "silu"
54
+ max_position_embeddings: int = 32768
55
+ initializer_range: float = 0.02
56
+ rms_norm_eps: float = 1e-6
57
+ use_cache: bool = True
58
+ tie_word_embeddings: bool = False
59
+ rope_parameters: RopeParameters | dict | None = None
60
+ attention_bias: bool = False
61
+ use_sliding_window: bool = False
62
+ sliding_window: int | None = 4096
63
+ attention_dropout: float | int = 0.0
64
+ decoder_sparse_step: int = 1
65
+ moe_intermediate_size: int = 768
66
+ num_experts_per_tok: int = 8
67
+ num_experts: int = 128
68
+ norm_topk_prob: bool = False
69
+ output_router_logits: bool = False
70
+ router_aux_loss_coef: float = 0.001
71
+ mlp_only_layers: list[int] | None = None
72
+ pad_token_id: int | None = None
73
+ bos_token_id: int | None = None
74
+ eos_token_id: int | list[int] | None = None
75
+
76
+ head_dim: int = 128
77
+ query_key_norm: bool = True
78
+ moe_gate_bias: bool = False
79
+ layernorm_num_groups: int = 1
80
+ num_shared_experts: int = 0
81
+ router_score_func: str = "softmax"
82
+ router_scaling_factor: float | None = 1.0
83
+ rope_head_dim: int | None = None
84
+ attention_gate_func: str | None = None
85
+ mova_num_experts: int = 0
86
+ mova_num_experts_per_tok: int = 0
87
+
88
+ def __post_init__(self, **kwargs):
89
+ self.sliding_window = self.sliding_window if self.use_sliding_window else None
90
+ self.mlp_only_layers = [] if self.mlp_only_layers is None else self.mlp_only_layers
91
+ if self.router_scaling_factor is None:
92
+ self.router_scaling_factor = 1.0
93
+ super().__post_init__(**kwargs)
94
+
95
+
96
+ __all__ = ["K2HorizonConfig"]
generation_config.json ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ {
2
+ "bos_token_id": 0,
3
+ "eos_token_id": [
4
+ 1,
5
+ 250019
6
+ ]
7
+ }
model.safetensors.index.json ADDED
@@ -0,0 +1,334 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "metadata": {
3
+ "total_size": 10116510720
4
+ },
5
+ "weight_map": {
6
+ "model.layers.0.self_attn.q_proj.weight": "pytorch_model-00001-of-00036.safetensors",
7
+ "model.layers.0.self_attn.k_proj.weight": "pytorch_model-00001-of-00036.safetensors",
8
+ "model.layers.0.self_attn.v_proj.weight": "pytorch_model-00001-of-00036.safetensors",
9
+ "model.layers.0.self_attn.o_proj.weight": "pytorch_model-00001-of-00036.safetensors",
10
+ "model.layers.0.input_layernorm.weight": "pytorch_model-00001-of-00036.safetensors",
11
+ "model.layers.0.post_attention_layernorm.weight": "pytorch_model-00001-of-00036.safetensors",
12
+ "model.layers.0.mlp.gate_proj.weight": "pytorch_model-00001-of-00036.safetensors",
13
+ "model.layers.0.mlp.down_proj.weight": "pytorch_model-00001-of-00036.safetensors",
14
+ "model.layers.0.mlp.up_proj.weight": "pytorch_model-00001-of-00036.safetensors",
15
+ "model.layers.1.self_attn.q_proj.weight": "pytorch_model-00002-of-00036.safetensors",
16
+ "model.layers.1.self_attn.k_proj.weight": "pytorch_model-00002-of-00036.safetensors",
17
+ "model.layers.1.self_attn.v_proj.weight": "pytorch_model-00002-of-00036.safetensors",
18
+ "model.layers.1.self_attn.o_proj.weight": "pytorch_model-00002-of-00036.safetensors",
19
+ "model.layers.1.input_layernorm.weight": "pytorch_model-00002-of-00036.safetensors",
20
+ "model.layers.1.post_attention_layernorm.weight": "pytorch_model-00002-of-00036.safetensors",
21
+ "model.layers.1.mlp.gate_proj.weight": "pytorch_model-00002-of-00036.safetensors",
22
+ "model.layers.1.mlp.down_proj.weight": "pytorch_model-00002-of-00036.safetensors",
23
+ "model.layers.1.mlp.up_proj.weight": "pytorch_model-00002-of-00036.safetensors",
24
+ "model.layers.2.self_attn.q_proj.weight": "pytorch_model-00003-of-00036.safetensors",
25
+ "model.layers.2.self_attn.k_proj.weight": "pytorch_model-00003-of-00036.safetensors",
26
+ "model.layers.2.self_attn.v_proj.weight": "pytorch_model-00003-of-00036.safetensors",
27
+ "model.layers.2.self_attn.o_proj.weight": "pytorch_model-00003-of-00036.safetensors",
28
+ "model.layers.2.input_layernorm.weight": "pytorch_model-00003-of-00036.safetensors",
29
+ "model.layers.2.post_attention_layernorm.weight": "pytorch_model-00003-of-00036.safetensors",
30
+ "model.layers.2.mlp.gate_proj.weight": "pytorch_model-00003-of-00036.safetensors",
31
+ "model.layers.2.mlp.down_proj.weight": "pytorch_model-00003-of-00036.safetensors",
32
+ "model.layers.2.mlp.up_proj.weight": "pytorch_model-00003-of-00036.safetensors",
33
+ "model.layers.3.self_attn.q_proj.weight": "pytorch_model-00004-of-00036.safetensors",
34
+ "model.layers.3.self_attn.k_proj.weight": "pytorch_model-00004-of-00036.safetensors",
35
+ "model.layers.3.self_attn.v_proj.weight": "pytorch_model-00004-of-00036.safetensors",
36
+ "model.layers.3.self_attn.o_proj.weight": "pytorch_model-00004-of-00036.safetensors",
37
+ "model.layers.3.input_layernorm.weight": "pytorch_model-00004-of-00036.safetensors",
38
+ "model.layers.3.post_attention_layernorm.weight": "pytorch_model-00004-of-00036.safetensors",
39
+ "model.layers.3.mlp.gate_proj.weight": "pytorch_model-00004-of-00036.safetensors",
40
+ "model.layers.3.mlp.down_proj.weight": "pytorch_model-00004-of-00036.safetensors",
41
+ "model.layers.3.mlp.up_proj.weight": "pytorch_model-00004-of-00036.safetensors",
42
+ "model.layers.4.self_attn.q_proj.weight": "pytorch_model-00005-of-00036.safetensors",
43
+ "model.layers.4.self_attn.k_proj.weight": "pytorch_model-00005-of-00036.safetensors",
44
+ "model.layers.4.self_attn.v_proj.weight": "pytorch_model-00005-of-00036.safetensors",
45
+ "model.layers.4.self_attn.o_proj.weight": "pytorch_model-00005-of-00036.safetensors",
46
+ "model.layers.4.input_layernorm.weight": "pytorch_model-00005-of-00036.safetensors",
47
+ "model.layers.4.post_attention_layernorm.weight": "pytorch_model-00005-of-00036.safetensors",
48
+ "model.layers.4.mlp.gate_proj.weight": "pytorch_model-00005-of-00036.safetensors",
49
+ "model.layers.4.mlp.down_proj.weight": "pytorch_model-00005-of-00036.safetensors",
50
+ "model.layers.4.mlp.up_proj.weight": "pytorch_model-00005-of-00036.safetensors",
51
+ "model.layers.5.self_attn.q_proj.weight": "pytorch_model-00006-of-00036.safetensors",
52
+ "model.layers.5.self_attn.k_proj.weight": "pytorch_model-00006-of-00036.safetensors",
53
+ "model.layers.5.self_attn.v_proj.weight": "pytorch_model-00006-of-00036.safetensors",
54
+ "model.layers.5.self_attn.o_proj.weight": "pytorch_model-00006-of-00036.safetensors",
55
+ "model.layers.5.input_layernorm.weight": "pytorch_model-00006-of-00036.safetensors",
56
+ "model.layers.5.post_attention_layernorm.weight": "pytorch_model-00006-of-00036.safetensors",
57
+ "model.layers.5.mlp.gate_proj.weight": "pytorch_model-00006-of-00036.safetensors",
58
+ "model.layers.5.mlp.down_proj.weight": "pytorch_model-00006-of-00036.safetensors",
59
+ "model.layers.5.mlp.up_proj.weight": "pytorch_model-00006-of-00036.safetensors",
60
+ "model.layers.6.self_attn.q_proj.weight": "pytorch_model-00007-of-00036.safetensors",
61
+ "model.layers.6.self_attn.k_proj.weight": "pytorch_model-00007-of-00036.safetensors",
62
+ "model.layers.6.self_attn.v_proj.weight": "pytorch_model-00007-of-00036.safetensors",
63
+ "model.layers.6.self_attn.o_proj.weight": "pytorch_model-00007-of-00036.safetensors",
64
+ "model.layers.6.input_layernorm.weight": "pytorch_model-00007-of-00036.safetensors",
65
+ "model.layers.6.post_attention_layernorm.weight": "pytorch_model-00007-of-00036.safetensors",
66
+ "model.layers.6.mlp.gate_proj.weight": "pytorch_model-00007-of-00036.safetensors",
67
+ "model.layers.6.mlp.down_proj.weight": "pytorch_model-00007-of-00036.safetensors",
68
+ "model.layers.6.mlp.up_proj.weight": "pytorch_model-00007-of-00036.safetensors",
69
+ "model.layers.7.self_attn.q_proj.weight": "pytorch_model-00008-of-00036.safetensors",
70
+ "model.layers.7.self_attn.k_proj.weight": "pytorch_model-00008-of-00036.safetensors",
71
+ "model.layers.7.self_attn.v_proj.weight": "pytorch_model-00008-of-00036.safetensors",
72
+ "model.layers.7.self_attn.o_proj.weight": "pytorch_model-00008-of-00036.safetensors",
73
+ "model.layers.7.input_layernorm.weight": "pytorch_model-00008-of-00036.safetensors",
74
+ "model.layers.7.post_attention_layernorm.weight": "pytorch_model-00008-of-00036.safetensors",
75
+ "model.layers.7.mlp.gate_proj.weight": "pytorch_model-00008-of-00036.safetensors",
76
+ "model.layers.7.mlp.down_proj.weight": "pytorch_model-00008-of-00036.safetensors",
77
+ "model.layers.7.mlp.up_proj.weight": "pytorch_model-00008-of-00036.safetensors",
78
+ "model.layers.8.self_attn.q_proj.weight": "pytorch_model-00009-of-00036.safetensors",
79
+ "model.layers.8.self_attn.k_proj.weight": "pytorch_model-00009-of-00036.safetensors",
80
+ "model.layers.8.self_attn.v_proj.weight": "pytorch_model-00009-of-00036.safetensors",
81
+ "model.layers.8.self_attn.o_proj.weight": "pytorch_model-00009-of-00036.safetensors",
82
+ "model.layers.8.input_layernorm.weight": "pytorch_model-00009-of-00036.safetensors",
83
+ "model.layers.8.post_attention_layernorm.weight": "pytorch_model-00009-of-00036.safetensors",
84
+ "model.layers.8.mlp.gate_proj.weight": "pytorch_model-00009-of-00036.safetensors",
85
+ "model.layers.8.mlp.down_proj.weight": "pytorch_model-00009-of-00036.safetensors",
86
+ "model.layers.8.mlp.up_proj.weight": "pytorch_model-00009-of-00036.safetensors",
87
+ "model.layers.9.self_attn.q_proj.weight": "pytorch_model-00010-of-00036.safetensors",
88
+ "model.layers.9.self_attn.k_proj.weight": "pytorch_model-00010-of-00036.safetensors",
89
+ "model.layers.9.self_attn.v_proj.weight": "pytorch_model-00010-of-00036.safetensors",
90
+ "model.layers.9.self_attn.o_proj.weight": "pytorch_model-00010-of-00036.safetensors",
91
+ "model.layers.9.input_layernorm.weight": "pytorch_model-00010-of-00036.safetensors",
92
+ "model.layers.9.post_attention_layernorm.weight": "pytorch_model-00010-of-00036.safetensors",
93
+ "model.layers.9.mlp.gate_proj.weight": "pytorch_model-00010-of-00036.safetensors",
94
+ "model.layers.9.mlp.down_proj.weight": "pytorch_model-00010-of-00036.safetensors",
95
+ "model.layers.9.mlp.up_proj.weight": "pytorch_model-00010-of-00036.safetensors",
96
+ "model.layers.10.self_attn.q_proj.weight": "pytorch_model-00011-of-00036.safetensors",
97
+ "model.layers.10.self_attn.k_proj.weight": "pytorch_model-00011-of-00036.safetensors",
98
+ "model.layers.10.self_attn.v_proj.weight": "pytorch_model-00011-of-00036.safetensors",
99
+ "model.layers.10.self_attn.o_proj.weight": "pytorch_model-00011-of-00036.safetensors",
100
+ "model.layers.10.input_layernorm.weight": "pytorch_model-00011-of-00036.safetensors",
101
+ "model.layers.10.post_attention_layernorm.weight": "pytorch_model-00011-of-00036.safetensors",
102
+ "model.layers.10.mlp.gate_proj.weight": "pytorch_model-00011-of-00036.safetensors",
103
+ "model.layers.10.mlp.down_proj.weight": "pytorch_model-00011-of-00036.safetensors",
104
+ "model.layers.10.mlp.up_proj.weight": "pytorch_model-00011-of-00036.safetensors",
105
+ "model.layers.11.self_attn.q_proj.weight": "pytorch_model-00012-of-00036.safetensors",
106
+ "model.layers.11.self_attn.k_proj.weight": "pytorch_model-00012-of-00036.safetensors",
107
+ "model.layers.11.self_attn.v_proj.weight": "pytorch_model-00012-of-00036.safetensors",
108
+ "model.layers.11.self_attn.o_proj.weight": "pytorch_model-00012-of-00036.safetensors",
109
+ "model.layers.11.input_layernorm.weight": "pytorch_model-00012-of-00036.safetensors",
110
+ "model.layers.11.post_attention_layernorm.weight": "pytorch_model-00012-of-00036.safetensors",
111
+ "model.layers.11.mlp.gate_proj.weight": "pytorch_model-00012-of-00036.safetensors",
112
+ "model.layers.11.mlp.down_proj.weight": "pytorch_model-00012-of-00036.safetensors",
113
+ "model.layers.11.mlp.up_proj.weight": "pytorch_model-00012-of-00036.safetensors",
114
+ "model.layers.12.self_attn.q_proj.weight": "pytorch_model-00013-of-00036.safetensors",
115
+ "model.layers.12.self_attn.k_proj.weight": "pytorch_model-00013-of-00036.safetensors",
116
+ "model.layers.12.self_attn.v_proj.weight": "pytorch_model-00013-of-00036.safetensors",
117
+ "model.layers.12.self_attn.o_proj.weight": "pytorch_model-00013-of-00036.safetensors",
118
+ "model.layers.12.input_layernorm.weight": "pytorch_model-00013-of-00036.safetensors",
119
+ "model.layers.12.post_attention_layernorm.weight": "pytorch_model-00013-of-00036.safetensors",
120
+ "model.layers.12.mlp.gate_proj.weight": "pytorch_model-00013-of-00036.safetensors",
121
+ "model.layers.12.mlp.down_proj.weight": "pytorch_model-00013-of-00036.safetensors",
122
+ "model.layers.12.mlp.up_proj.weight": "pytorch_model-00013-of-00036.safetensors",
123
+ "model.layers.13.self_attn.q_proj.weight": "pytorch_model-00014-of-00036.safetensors",
124
+ "model.layers.13.self_attn.k_proj.weight": "pytorch_model-00014-of-00036.safetensors",
125
+ "model.layers.13.self_attn.v_proj.weight": "pytorch_model-00014-of-00036.safetensors",
126
+ "model.layers.13.self_attn.o_proj.weight": "pytorch_model-00014-of-00036.safetensors",
127
+ "model.layers.13.input_layernorm.weight": "pytorch_model-00014-of-00036.safetensors",
128
+ "model.layers.13.post_attention_layernorm.weight": "pytorch_model-00014-of-00036.safetensors",
129
+ "model.layers.13.mlp.gate_proj.weight": "pytorch_model-00014-of-00036.safetensors",
130
+ "model.layers.13.mlp.down_proj.weight": "pytorch_model-00014-of-00036.safetensors",
131
+ "model.layers.13.mlp.up_proj.weight": "pytorch_model-00014-of-00036.safetensors",
132
+ "model.layers.14.self_attn.q_proj.weight": "pytorch_model-00015-of-00036.safetensors",
133
+ "model.layers.14.self_attn.k_proj.weight": "pytorch_model-00015-of-00036.safetensors",
134
+ "model.layers.14.self_attn.v_proj.weight": "pytorch_model-00015-of-00036.safetensors",
135
+ "model.layers.14.self_attn.o_proj.weight": "pytorch_model-00015-of-00036.safetensors",
136
+ "model.layers.14.input_layernorm.weight": "pytorch_model-00015-of-00036.safetensors",
137
+ "model.layers.14.post_attention_layernorm.weight": "pytorch_model-00015-of-00036.safetensors",
138
+ "model.layers.14.mlp.gate_proj.weight": "pytorch_model-00015-of-00036.safetensors",
139
+ "model.layers.14.mlp.down_proj.weight": "pytorch_model-00015-of-00036.safetensors",
140
+ "model.layers.14.mlp.up_proj.weight": "pytorch_model-00015-of-00036.safetensors",
141
+ "model.layers.15.self_attn.q_proj.weight": "pytorch_model-00016-of-00036.safetensors",
142
+ "model.layers.15.self_attn.k_proj.weight": "pytorch_model-00016-of-00036.safetensors",
143
+ "model.layers.15.self_attn.v_proj.weight": "pytorch_model-00016-of-00036.safetensors",
144
+ "model.layers.15.self_attn.o_proj.weight": "pytorch_model-00016-of-00036.safetensors",
145
+ "model.layers.15.input_layernorm.weight": "pytorch_model-00016-of-00036.safetensors",
146
+ "model.layers.15.post_attention_layernorm.weight": "pytorch_model-00016-of-00036.safetensors",
147
+ "model.layers.15.mlp.gate_proj.weight": "pytorch_model-00016-of-00036.safetensors",
148
+ "model.layers.15.mlp.down_proj.weight": "pytorch_model-00016-of-00036.safetensors",
149
+ "model.layers.15.mlp.up_proj.weight": "pytorch_model-00016-of-00036.safetensors",
150
+ "model.layers.16.self_attn.q_proj.weight": "pytorch_model-00017-of-00036.safetensors",
151
+ "model.layers.16.self_attn.k_proj.weight": "pytorch_model-00017-of-00036.safetensors",
152
+ "model.layers.16.self_attn.v_proj.weight": "pytorch_model-00017-of-00036.safetensors",
153
+ "model.layers.16.self_attn.o_proj.weight": "pytorch_model-00017-of-00036.safetensors",
154
+ "model.layers.16.input_layernorm.weight": "pytorch_model-00017-of-00036.safetensors",
155
+ "model.layers.16.post_attention_layernorm.weight": "pytorch_model-00017-of-00036.safetensors",
156
+ "model.layers.16.mlp.gate_proj.weight": "pytorch_model-00017-of-00036.safetensors",
157
+ "model.layers.16.mlp.down_proj.weight": "pytorch_model-00017-of-00036.safetensors",
158
+ "model.layers.16.mlp.up_proj.weight": "pytorch_model-00017-of-00036.safetensors",
159
+ "model.layers.17.self_attn.q_proj.weight": "pytorch_model-00018-of-00036.safetensors",
160
+ "model.layers.17.self_attn.k_proj.weight": "pytorch_model-00018-of-00036.safetensors",
161
+ "model.layers.17.self_attn.v_proj.weight": "pytorch_model-00018-of-00036.safetensors",
162
+ "model.layers.17.self_attn.o_proj.weight": "pytorch_model-00018-of-00036.safetensors",
163
+ "model.layers.17.input_layernorm.weight": "pytorch_model-00018-of-00036.safetensors",
164
+ "model.layers.17.post_attention_layernorm.weight": "pytorch_model-00018-of-00036.safetensors",
165
+ "model.layers.17.mlp.gate_proj.weight": "pytorch_model-00018-of-00036.safetensors",
166
+ "model.layers.17.mlp.down_proj.weight": "pytorch_model-00018-of-00036.safetensors",
167
+ "model.layers.17.mlp.up_proj.weight": "pytorch_model-00018-of-00036.safetensors",
168
+ "model.layers.18.self_attn.q_proj.weight": "pytorch_model-00019-of-00036.safetensors",
169
+ "model.layers.18.self_attn.k_proj.weight": "pytorch_model-00019-of-00036.safetensors",
170
+ "model.layers.18.self_attn.v_proj.weight": "pytorch_model-00019-of-00036.safetensors",
171
+ "model.layers.18.self_attn.o_proj.weight": "pytorch_model-00019-of-00036.safetensors",
172
+ "model.layers.18.input_layernorm.weight": "pytorch_model-00019-of-00036.safetensors",
173
+ "model.layers.18.post_attention_layernorm.weight": "pytorch_model-00019-of-00036.safetensors",
174
+ "model.layers.18.mlp.gate_proj.weight": "pytorch_model-00019-of-00036.safetensors",
175
+ "model.layers.18.mlp.down_proj.weight": "pytorch_model-00019-of-00036.safetensors",
176
+ "model.layers.18.mlp.up_proj.weight": "pytorch_model-00019-of-00036.safetensors",
177
+ "model.layers.19.self_attn.q_proj.weight": "pytorch_model-00020-of-00036.safetensors",
178
+ "model.layers.19.self_attn.k_proj.weight": "pytorch_model-00020-of-00036.safetensors",
179
+ "model.layers.19.self_attn.v_proj.weight": "pytorch_model-00020-of-00036.safetensors",
180
+ "model.layers.19.self_attn.o_proj.weight": "pytorch_model-00020-of-00036.safetensors",
181
+ "model.layers.19.input_layernorm.weight": "pytorch_model-00020-of-00036.safetensors",
182
+ "model.layers.19.post_attention_layernorm.weight": "pytorch_model-00020-of-00036.safetensors",
183
+ "model.layers.19.mlp.gate_proj.weight": "pytorch_model-00020-of-00036.safetensors",
184
+ "model.layers.19.mlp.down_proj.weight": "pytorch_model-00020-of-00036.safetensors",
185
+ "model.layers.19.mlp.up_proj.weight": "pytorch_model-00020-of-00036.safetensors",
186
+ "model.layers.20.self_attn.q_proj.weight": "pytorch_model-00021-of-00036.safetensors",
187
+ "model.layers.20.self_attn.k_proj.weight": "pytorch_model-00021-of-00036.safetensors",
188
+ "model.layers.20.self_attn.v_proj.weight": "pytorch_model-00021-of-00036.safetensors",
189
+ "model.layers.20.self_attn.o_proj.weight": "pytorch_model-00021-of-00036.safetensors",
190
+ "model.layers.20.input_layernorm.weight": "pytorch_model-00021-of-00036.safetensors",
191
+ "model.layers.20.post_attention_layernorm.weight": "pytorch_model-00021-of-00036.safetensors",
192
+ "model.layers.20.mlp.gate_proj.weight": "pytorch_model-00021-of-00036.safetensors",
193
+ "model.layers.20.mlp.down_proj.weight": "pytorch_model-00021-of-00036.safetensors",
194
+ "model.layers.20.mlp.up_proj.weight": "pytorch_model-00021-of-00036.safetensors",
195
+ "model.layers.21.self_attn.q_proj.weight": "pytorch_model-00022-of-00036.safetensors",
196
+ "model.layers.21.self_attn.k_proj.weight": "pytorch_model-00022-of-00036.safetensors",
197
+ "model.layers.21.self_attn.v_proj.weight": "pytorch_model-00022-of-00036.safetensors",
198
+ "model.layers.21.self_attn.o_proj.weight": "pytorch_model-00022-of-00036.safetensors",
199
+ "model.layers.21.input_layernorm.weight": "pytorch_model-00022-of-00036.safetensors",
200
+ "model.layers.21.post_attention_layernorm.weight": "pytorch_model-00022-of-00036.safetensors",
201
+ "model.layers.21.mlp.gate_proj.weight": "pytorch_model-00022-of-00036.safetensors",
202
+ "model.layers.21.mlp.down_proj.weight": "pytorch_model-00022-of-00036.safetensors",
203
+ "model.layers.21.mlp.up_proj.weight": "pytorch_model-00022-of-00036.safetensors",
204
+ "model.layers.22.self_attn.q_proj.weight": "pytorch_model-00023-of-00036.safetensors",
205
+ "model.layers.22.self_attn.k_proj.weight": "pytorch_model-00023-of-00036.safetensors",
206
+ "model.layers.22.self_attn.v_proj.weight": "pytorch_model-00023-of-00036.safetensors",
207
+ "model.layers.22.self_attn.o_proj.weight": "pytorch_model-00023-of-00036.safetensors",
208
+ "model.layers.22.input_layernorm.weight": "pytorch_model-00023-of-00036.safetensors",
209
+ "model.layers.22.post_attention_layernorm.weight": "pytorch_model-00023-of-00036.safetensors",
210
+ "model.layers.22.mlp.gate_proj.weight": "pytorch_model-00023-of-00036.safetensors",
211
+ "model.layers.22.mlp.down_proj.weight": "pytorch_model-00023-of-00036.safetensors",
212
+ "model.layers.22.mlp.up_proj.weight": "pytorch_model-00023-of-00036.safetensors",
213
+ "model.layers.23.self_attn.q_proj.weight": "pytorch_model-00024-of-00036.safetensors",
214
+ "model.layers.23.self_attn.k_proj.weight": "pytorch_model-00024-of-00036.safetensors",
215
+ "model.layers.23.self_attn.v_proj.weight": "pytorch_model-00024-of-00036.safetensors",
216
+ "model.layers.23.self_attn.o_proj.weight": "pytorch_model-00024-of-00036.safetensors",
217
+ "model.layers.23.input_layernorm.weight": "pytorch_model-00024-of-00036.safetensors",
218
+ "model.layers.23.post_attention_layernorm.weight": "pytorch_model-00024-of-00036.safetensors",
219
+ "model.layers.23.mlp.gate_proj.weight": "pytorch_model-00024-of-00036.safetensors",
220
+ "model.layers.23.mlp.down_proj.weight": "pytorch_model-00024-of-00036.safetensors",
221
+ "model.layers.23.mlp.up_proj.weight": "pytorch_model-00024-of-00036.safetensors",
222
+ "model.layers.24.self_attn.q_proj.weight": "pytorch_model-00025-of-00036.safetensors",
223
+ "model.layers.24.self_attn.k_proj.weight": "pytorch_model-00025-of-00036.safetensors",
224
+ "model.layers.24.self_attn.v_proj.weight": "pytorch_model-00025-of-00036.safetensors",
225
+ "model.layers.24.self_attn.o_proj.weight": "pytorch_model-00025-of-00036.safetensors",
226
+ "model.layers.24.input_layernorm.weight": "pytorch_model-00025-of-00036.safetensors",
227
+ "model.layers.24.post_attention_layernorm.weight": "pytorch_model-00025-of-00036.safetensors",
228
+ "model.layers.24.mlp.gate_proj.weight": "pytorch_model-00025-of-00036.safetensors",
229
+ "model.layers.24.mlp.down_proj.weight": "pytorch_model-00025-of-00036.safetensors",
230
+ "model.layers.24.mlp.up_proj.weight": "pytorch_model-00025-of-00036.safetensors",
231
+ "model.layers.25.self_attn.q_proj.weight": "pytorch_model-00026-of-00036.safetensors",
232
+ "model.layers.25.self_attn.k_proj.weight": "pytorch_model-00026-of-00036.safetensors",
233
+ "model.layers.25.self_attn.v_proj.weight": "pytorch_model-00026-of-00036.safetensors",
234
+ "model.layers.25.self_attn.o_proj.weight": "pytorch_model-00026-of-00036.safetensors",
235
+ "model.layers.25.input_layernorm.weight": "pytorch_model-00026-of-00036.safetensors",
236
+ "model.layers.25.post_attention_layernorm.weight": "pytorch_model-00026-of-00036.safetensors",
237
+ "model.layers.25.mlp.gate_proj.weight": "pytorch_model-00026-of-00036.safetensors",
238
+ "model.layers.25.mlp.down_proj.weight": "pytorch_model-00026-of-00036.safetensors",
239
+ "model.layers.25.mlp.up_proj.weight": "pytorch_model-00026-of-00036.safetensors",
240
+ "model.layers.26.self_attn.q_proj.weight": "pytorch_model-00027-of-00036.safetensors",
241
+ "model.layers.26.self_attn.k_proj.weight": "pytorch_model-00027-of-00036.safetensors",
242
+ "model.layers.26.self_attn.v_proj.weight": "pytorch_model-00027-of-00036.safetensors",
243
+ "model.layers.26.self_attn.o_proj.weight": "pytorch_model-00027-of-00036.safetensors",
244
+ "model.layers.26.input_layernorm.weight": "pytorch_model-00027-of-00036.safetensors",
245
+ "model.layers.26.post_attention_layernorm.weight": "pytorch_model-00027-of-00036.safetensors",
246
+ "model.layers.26.mlp.gate_proj.weight": "pytorch_model-00027-of-00036.safetensors",
247
+ "model.layers.26.mlp.down_proj.weight": "pytorch_model-00027-of-00036.safetensors",
248
+ "model.layers.26.mlp.up_proj.weight": "pytorch_model-00027-of-00036.safetensors",
249
+ "model.layers.27.self_attn.q_proj.weight": "pytorch_model-00028-of-00036.safetensors",
250
+ "model.layers.27.self_attn.k_proj.weight": "pytorch_model-00028-of-00036.safetensors",
251
+ "model.layers.27.self_attn.v_proj.weight": "pytorch_model-00028-of-00036.safetensors",
252
+ "model.layers.27.self_attn.o_proj.weight": "pytorch_model-00028-of-00036.safetensors",
253
+ "model.layers.27.input_layernorm.weight": "pytorch_model-00028-of-00036.safetensors",
254
+ "model.layers.27.post_attention_layernorm.weight": "pytorch_model-00028-of-00036.safetensors",
255
+ "model.layers.27.mlp.gate_proj.weight": "pytorch_model-00028-of-00036.safetensors",
256
+ "model.layers.27.mlp.down_proj.weight": "pytorch_model-00028-of-00036.safetensors",
257
+ "model.layers.27.mlp.up_proj.weight": "pytorch_model-00028-of-00036.safetensors",
258
+ "model.layers.28.self_attn.q_proj.weight": "pytorch_model-00029-of-00036.safetensors",
259
+ "model.layers.28.self_attn.k_proj.weight": "pytorch_model-00029-of-00036.safetensors",
260
+ "model.layers.28.self_attn.v_proj.weight": "pytorch_model-00029-of-00036.safetensors",
261
+ "model.layers.28.self_attn.o_proj.weight": "pytorch_model-00029-of-00036.safetensors",
262
+ "model.layers.28.input_layernorm.weight": "pytorch_model-00029-of-00036.safetensors",
263
+ "model.layers.28.post_attention_layernorm.weight": "pytorch_model-00029-of-00036.safetensors",
264
+ "model.layers.28.mlp.gate_proj.weight": "pytorch_model-00029-of-00036.safetensors",
265
+ "model.layers.28.mlp.down_proj.weight": "pytorch_model-00029-of-00036.safetensors",
266
+ "model.layers.28.mlp.up_proj.weight": "pytorch_model-00029-of-00036.safetensors",
267
+ "model.layers.29.self_attn.q_proj.weight": "pytorch_model-00030-of-00036.safetensors",
268
+ "model.layers.29.self_attn.k_proj.weight": "pytorch_model-00030-of-00036.safetensors",
269
+ "model.layers.29.self_attn.v_proj.weight": "pytorch_model-00030-of-00036.safetensors",
270
+ "model.layers.29.self_attn.o_proj.weight": "pytorch_model-00030-of-00036.safetensors",
271
+ "model.layers.29.input_layernorm.weight": "pytorch_model-00030-of-00036.safetensors",
272
+ "model.layers.29.post_attention_layernorm.weight": "pytorch_model-00030-of-00036.safetensors",
273
+ "model.layers.29.mlp.gate_proj.weight": "pytorch_model-00030-of-00036.safetensors",
274
+ "model.layers.29.mlp.down_proj.weight": "pytorch_model-00030-of-00036.safetensors",
275
+ "model.layers.29.mlp.up_proj.weight": "pytorch_model-00030-of-00036.safetensors",
276
+ "model.layers.30.self_attn.q_proj.weight": "pytorch_model-00031-of-00036.safetensors",
277
+ "model.layers.30.self_attn.k_proj.weight": "pytorch_model-00031-of-00036.safetensors",
278
+ "model.layers.30.self_attn.v_proj.weight": "pytorch_model-00031-of-00036.safetensors",
279
+ "model.layers.30.self_attn.o_proj.weight": "pytorch_model-00031-of-00036.safetensors",
280
+ "model.layers.30.input_layernorm.weight": "pytorch_model-00031-of-00036.safetensors",
281
+ "model.layers.30.post_attention_layernorm.weight": "pytorch_model-00031-of-00036.safetensors",
282
+ "model.layers.30.mlp.gate_proj.weight": "pytorch_model-00031-of-00036.safetensors",
283
+ "model.layers.30.mlp.down_proj.weight": "pytorch_model-00031-of-00036.safetensors",
284
+ "model.layers.30.mlp.up_proj.weight": "pytorch_model-00031-of-00036.safetensors",
285
+ "model.layers.31.self_attn.q_proj.weight": "pytorch_model-00032-of-00036.safetensors",
286
+ "model.layers.31.self_attn.k_proj.weight": "pytorch_model-00032-of-00036.safetensors",
287
+ "model.layers.31.self_attn.v_proj.weight": "pytorch_model-00032-of-00036.safetensors",
288
+ "model.layers.31.self_attn.o_proj.weight": "pytorch_model-00032-of-00036.safetensors",
289
+ "model.layers.31.input_layernorm.weight": "pytorch_model-00032-of-00036.safetensors",
290
+ "model.layers.31.post_attention_layernorm.weight": "pytorch_model-00032-of-00036.safetensors",
291
+ "model.layers.31.mlp.gate_proj.weight": "pytorch_model-00032-of-00036.safetensors",
292
+ "model.layers.31.mlp.down_proj.weight": "pytorch_model-00032-of-00036.safetensors",
293
+ "model.layers.31.mlp.up_proj.weight": "pytorch_model-00032-of-00036.safetensors",
294
+ "model.layers.32.self_attn.q_proj.weight": "pytorch_model-00033-of-00036.safetensors",
295
+ "model.layers.32.self_attn.k_proj.weight": "pytorch_model-00033-of-00036.safetensors",
296
+ "model.layers.32.self_attn.v_proj.weight": "pytorch_model-00033-of-00036.safetensors",
297
+ "model.layers.32.self_attn.o_proj.weight": "pytorch_model-00033-of-00036.safetensors",
298
+ "model.layers.32.input_layernorm.weight": "pytorch_model-00033-of-00036.safetensors",
299
+ "model.layers.32.post_attention_layernorm.weight": "pytorch_model-00033-of-00036.safetensors",
300
+ "model.layers.32.mlp.gate_proj.weight": "pytorch_model-00033-of-00036.safetensors",
301
+ "model.layers.32.mlp.down_proj.weight": "pytorch_model-00033-of-00036.safetensors",
302
+ "model.layers.32.mlp.up_proj.weight": "pytorch_model-00033-of-00036.safetensors",
303
+ "model.layers.33.self_attn.q_proj.weight": "pytorch_model-00034-of-00036.safetensors",
304
+ "model.layers.33.self_attn.k_proj.weight": "pytorch_model-00034-of-00036.safetensors",
305
+ "model.layers.33.self_attn.v_proj.weight": "pytorch_model-00034-of-00036.safetensors",
306
+ "model.layers.33.self_attn.o_proj.weight": "pytorch_model-00034-of-00036.safetensors",
307
+ "model.layers.33.input_layernorm.weight": "pytorch_model-00034-of-00036.safetensors",
308
+ "model.layers.33.post_attention_layernorm.weight": "pytorch_model-00034-of-00036.safetensors",
309
+ "model.layers.33.mlp.gate_proj.weight": "pytorch_model-00034-of-00036.safetensors",
310
+ "model.layers.33.mlp.down_proj.weight": "pytorch_model-00034-of-00036.safetensors",
311
+ "model.layers.33.mlp.up_proj.weight": "pytorch_model-00034-of-00036.safetensors",
312
+ "model.layers.34.self_attn.q_proj.weight": "pytorch_model-00035-of-00036.safetensors",
313
+ "model.layers.34.self_attn.k_proj.weight": "pytorch_model-00035-of-00036.safetensors",
314
+ "model.layers.34.self_attn.v_proj.weight": "pytorch_model-00035-of-00036.safetensors",
315
+ "model.layers.34.self_attn.o_proj.weight": "pytorch_model-00035-of-00036.safetensors",
316
+ "model.layers.34.input_layernorm.weight": "pytorch_model-00035-of-00036.safetensors",
317
+ "model.layers.34.post_attention_layernorm.weight": "pytorch_model-00035-of-00036.safetensors",
318
+ "model.layers.34.mlp.gate_proj.weight": "pytorch_model-00035-of-00036.safetensors",
319
+ "model.layers.34.mlp.down_proj.weight": "pytorch_model-00035-of-00036.safetensors",
320
+ "model.layers.34.mlp.up_proj.weight": "pytorch_model-00035-of-00036.safetensors",
321
+ "model.layers.35.self_attn.q_proj.weight": "pytorch_model-00036-of-00036.safetensors",
322
+ "model.layers.35.self_attn.k_proj.weight": "pytorch_model-00036-of-00036.safetensors",
323
+ "model.layers.35.self_attn.v_proj.weight": "pytorch_model-00036-of-00036.safetensors",
324
+ "model.layers.35.self_attn.o_proj.weight": "pytorch_model-00036-of-00036.safetensors",
325
+ "model.layers.35.input_layernorm.weight": "pytorch_model-00036-of-00036.safetensors",
326
+ "model.layers.35.post_attention_layernorm.weight": "pytorch_model-00036-of-00036.safetensors",
327
+ "model.layers.35.mlp.gate_proj.weight": "pytorch_model-00036-of-00036.safetensors",
328
+ "model.layers.35.mlp.down_proj.weight": "pytorch_model-00036-of-00036.safetensors",
329
+ "model.layers.35.mlp.up_proj.weight": "pytorch_model-00036-of-00036.safetensors",
330
+ "model.embed_tokens.weight": "pytorch_model-00036-of-00036.safetensors",
331
+ "model.norm.weight": "pytorch_model-00036-of-00036.safetensors",
332
+ "lm_head.weight": "pytorch_model-00036-of-00036.safetensors"
333
+ }
334
+ }
modeling_k2_horizon.py ADDED
@@ -0,0 +1,1116 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
2
+ # This file was automatically generated from src/transformers/models/qwen3_moe/modular_qwen3_moe.py.
3
+ # Do NOT edit this file manually as any edits will be overwritten by the generation of
4
+ # the file from the modular. If any change should be done, please apply the change to the
5
+ # modular_qwen3_moe.py file directly. One of our CI enforces this.
6
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
7
+ # coding=utf-8
8
+ # Copyright 2025 The Qwen team, Alibaba Group and the HuggingFace Inc. team. All rights reserved.
9
+ #
10
+ # Licensed under the Apache License, Version 2.0 (the "License");
11
+ # you may not use this file except in compliance with the License.
12
+ # You may obtain a copy of the License at
13
+ #
14
+ # http://www.apache.org/licenses/LICENSE-2.0
15
+ #
16
+ # Unless required by applicable law or agreed to in writing, software
17
+ # distributed under the License is distributed on an "AS IS" BASIS,
18
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19
+ # See the License for the specific language governing permissions and
20
+ # limitations under the License.
21
+
22
+ from typing import Callable, Optional, Union
23
+
24
+ import math
25
+ import torch
26
+ import torch.nn.functional as F
27
+ from torch import nn
28
+
29
+ from transformers.activations import ACT2FN
30
+ from transformers.cache_utils import Cache, DynamicCache
31
+ from transformers.generation import GenerationMixin
32
+ from transformers.masking_utils import create_causal_mask, create_sliding_window_causal_mask
33
+ from transformers.modeling_flash_attention_utils import FlashAttentionKwargs
34
+ from transformers.modeling_layers import (
35
+ GenericForQuestionAnswering,
36
+ GenericForSequenceClassification,
37
+ GenericForTokenClassification,
38
+ GradientCheckpointingLayer,
39
+ )
40
+ from transformers.modeling_outputs import MoeCausalLMOutputWithPast, MoeModelOutputWithPast
41
+ from transformers.modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update
42
+ from transformers.modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
43
+ from transformers.processing_utils import Unpack
44
+ from transformers.utils import TransformersKwargs, auto_docstring, can_return_tuple
45
+ from transformers.utils.generic import maybe_autocast
46
+ from transformers.utils.deprecation import deprecate_kwarg
47
+ from transformers.utils.output_capturing import OutputRecorder
48
+
49
+ from .configuration_k2_horizon import K2HorizonConfig
50
+
51
+
52
+ def rotate_half(x):
53
+ """Rotates half the hidden dims of the input."""
54
+ x1 = x[..., : x.shape[-1] // 2]
55
+ x2 = x[..., x.shape[-1] // 2:]
56
+ return torch.cat((-x2, x1), dim=-1)
57
+
58
+
59
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
60
+ """Applies Rotary Position Embedding to the query and key tensors.
61
+
62
+ Args:
63
+ q (`torch.Tensor`): The query tensor.
64
+ k (`torch.Tensor`): The key tensor.
65
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
66
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
67
+ position_ids (`torch.Tensor`, *optional*):
68
+ Deprecated and unused.
69
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
70
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
71
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
72
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
73
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
74
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
75
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
76
+ Returns:
77
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
78
+ """
79
+ cos = cos.unsqueeze(unsqueeze_dim)
80
+ sin = sin.unsqueeze(unsqueeze_dim)
81
+ q_embed = (q * cos) + (rotate_half(q) * sin)
82
+ k_embed = (k * cos) + (rotate_half(k) * sin)
83
+ return q_embed, k_embed
84
+
85
+
86
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
87
+ """
88
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
89
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
90
+ """
91
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
92
+ if n_rep == 1:
93
+ return hidden_states
94
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
95
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
96
+
97
+
98
+ def split_to_interleaved(x):
99
+ # Split halves: x0 x1 x2 x3 ... y0 y1 y2 y3 ...
100
+ # Interleaved: x0 y0 x1 y1 x2 y2 x3 y3 ...
101
+ return x.reshape(*x.shape[:-1], 2, -1).transpose(-1, -2).reshape(*x.shape[:-1], -1)
102
+
103
+
104
+ def interleaved_to_split(x):
105
+ # Interleaved: x0 y0 x1 y1 x2 y2 x3 y3 ...
106
+ # Split halves: x0 x1 x2 x3 ... y0 y1 y2 y3 ...
107
+ return x.reshape(*x.shape[:-1], -1, 2).transpose(-1, -2).reshape(*x.shape[:-1], -1)
108
+
109
+
110
+ def eager_attention_forward(
111
+ module: nn.Module,
112
+ query: torch.Tensor,
113
+ key: torch.Tensor,
114
+ value: torch.Tensor,
115
+ attention_mask: Optional[torch.Tensor],
116
+ scaling: float,
117
+ dropout: float = 0.0,
118
+ **kwargs: Unpack[TransformersKwargs],
119
+ ):
120
+ key_states = repeat_kv(key, module.num_key_value_groups)
121
+ value_states = repeat_kv(value, module.num_key_value_groups)
122
+
123
+ attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
124
+ if attention_mask is not None:
125
+ causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
126
+ attn_weights = attn_weights + causal_mask
127
+
128
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
129
+ attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
130
+ attn_output = torch.matmul(attn_weights, value_states)
131
+ attn_output = attn_output.transpose(1, 2).contiguous()
132
+
133
+ return attn_output, attn_weights
134
+
135
+
136
+ def calc_router_weights(
137
+ router_logits: torch.Tensor,
138
+ router_bias: Optional[torch.Tensor],
139
+ score_func: str,
140
+ top_k: int,
141
+ scaling_factor: Optional[float],
142
+ ) -> tuple[torch.Tensor, torch.Tensor]:
143
+ """Return native-XLLM-compatible routing weights and selected experts.
144
+
145
+ XLLM applies router bias only to the values used for top-k selection. The
146
+ selected routes are still weighted by the original router probabilities,
147
+ then optionally normalized and scaled.
148
+ """
149
+ if score_func == "softmax":
150
+ routing_scores = F.softmax(router_logits, dim=-1, dtype=torch.float32)
151
+ elif score_func == "sigmoid":
152
+ routing_scores = torch.sigmoid(router_logits.to(torch.float32))
153
+ else:
154
+ raise ValueError(f"Unsupported router score function: {score_func}")
155
+
156
+ selection_scores = routing_scores
157
+ if router_bias is not None:
158
+ selection_scores = selection_scores + router_bias.to(selection_scores)
159
+
160
+ selected_indices = torch.topk(selection_scores, top_k, dim=-1).indices
161
+ routing_weights = torch.gather(routing_scores, dim=-1, index=selected_indices)
162
+ if top_k > 1:
163
+ routing_weights = routing_weights / routing_weights.sum(dim=-1, keepdim=True)
164
+ if scaling_factor is not None:
165
+ routing_weights = routing_weights * scaling_factor
166
+ return routing_weights, selected_indices
167
+
168
+
169
+ def combine_routed_experts(
170
+ hidden_states: torch.Tensor,
171
+ routing_weights: torch.Tensor,
172
+ selected_indices: torch.Tensor,
173
+ experts: nn.ModuleList,
174
+ activation: Optional[Callable[[torch.Tensor], torch.Tensor]] = None,
175
+ ) -> torch.Tensor:
176
+ num_tokens, hidden_dim = hidden_states.shape
177
+ final_hidden_states = torch.zeros(
178
+ (num_tokens, experts[0].out_features),
179
+ dtype=hidden_states.dtype,
180
+ device=hidden_states.device,
181
+ )
182
+ expert_mask = torch.nn.functional.one_hot(
183
+ selected_indices, num_classes=len(experts)
184
+ ).permute(2, 1, 0)
185
+
186
+ for expert_idx in torch.nonzero(expert_mask.sum(dim=(-1, -2)), as_tuple=False).flatten():
187
+ topk_positions, token_positions = torch.where(expert_mask[int(expert_idx)])
188
+ expert_states = experts[int(expert_idx)](hidden_states[token_positions])
189
+ if activation is not None:
190
+ expert_states = activation(expert_states)
191
+ expert_states = expert_states * routing_weights[token_positions, topk_positions, None].to(expert_states.dtype)
192
+ final_hidden_states.index_add_(0, token_positions, expert_states.to(hidden_states.dtype))
193
+
194
+ return final_hidden_states
195
+
196
+
197
+ class K2HorizonAttention(nn.Module):
198
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
199
+
200
+ def __init__(self, config: K2HorizonConfig, layer_idx: int):
201
+ super().__init__()
202
+ self.config = config
203
+ self.layer_idx = layer_idx
204
+ self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
205
+ self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
206
+ self.scaling = self.head_dim ** -0.5
207
+ self.attention_dropout = config.attention_dropout
208
+ self.is_causal = True
209
+
210
+ self.rope_head_dim = self.head_dim if config.rope_head_dim is None else config.rope_head_dim
211
+
212
+ self.q_proj = nn.Linear(
213
+ config.hidden_size, config.num_attention_heads * self.head_dim, bias=config.attention_bias
214
+ )
215
+ self.k_proj = nn.Linear(
216
+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
217
+ )
218
+ self.v_proj = nn.Linear(
219
+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
220
+ )
221
+ self.o_proj = nn.Linear(
222
+ config.num_attention_heads * self.head_dim, config.hidden_size, bias=config.attention_bias
223
+ )
224
+
225
+ self.gate_func = config.attention_gate_func
226
+ if self.gate_func is not None:
227
+ self.gate_proj = nn.Linear(
228
+ config.hidden_size,
229
+ config.num_attention_heads * self.head_dim,
230
+ bias=False)
231
+
232
+ if config.query_key_norm:
233
+ self.q_norm = K2HorizonRMSNorm(
234
+ hidden_size=config.num_attention_heads * self.head_dim,
235
+ n_groups=config.num_attention_heads,
236
+ eps=config.rms_norm_eps)
237
+ self.k_norm = K2HorizonRMSNorm(
238
+ hidden_size=config.num_key_value_heads * self.head_dim,
239
+ n_groups=config.num_key_value_heads,
240
+ eps=config.rms_norm_eps)
241
+
242
+ self.sliding_window = getattr(config, "sliding_window", None)
243
+
244
+ @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
245
+ def forward(
246
+ self,
247
+ hidden_states: torch.Tensor,
248
+ position_embeddings: tuple[torch.Tensor, torch.Tensor],
249
+ attention_mask: Optional[torch.Tensor],
250
+ past_key_values: Optional[Cache] = None,
251
+ cache_position: Optional[torch.LongTensor] = None,
252
+ **kwargs: Unpack[FlashAttentionKwargs],
253
+ ) -> tuple[torch.Tensor, Optional[torch.Tensor]]:
254
+ input_shape = hidden_states.shape[:-1]
255
+ hidden_shape = (*input_shape, -1, self.head_dim)
256
+
257
+ if self.config.query_key_norm:
258
+ query_states = self.q_norm(self.q_proj(hidden_states)).view(hidden_shape).transpose(1, 2)
259
+ key_states = self.k_norm(self.k_proj(hidden_states)).view(hidden_shape).transpose(1, 2)
260
+ else:
261
+ query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2)
262
+ key_states = self.k_proj(hidden_states).view(hidden_shape).transpose(1, 2)
263
+
264
+ value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
265
+
266
+ cos, sin = position_embeddings
267
+ if self.rope_head_dim == self.head_dim:
268
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
269
+ else:
270
+ query_states, query_states_ = torch.split(
271
+ split_to_interleaved(query_states),
272
+ split_size_or_sections=[self.rope_head_dim, self.head_dim - self.rope_head_dim],
273
+ dim=-1)
274
+
275
+ key_states, key_states_ = torch.split(
276
+ split_to_interleaved(key_states),
277
+ split_size_or_sections=[self.rope_head_dim, self.head_dim - self.rope_head_dim],
278
+ dim=-1)
279
+
280
+ query_states, key_states = apply_rotary_pos_emb(
281
+ interleaved_to_split(query_states),
282
+ interleaved_to_split(key_states),
283
+ cos,
284
+ sin)
285
+
286
+ query_states = interleaved_to_split(torch.cat(
287
+ [split_to_interleaved(query_states), query_states_], dim=-1))
288
+ key_states = interleaved_to_split(torch.cat(
289
+ [split_to_interleaved(key_states), key_states_], dim=-1))
290
+
291
+ if past_key_values is not None:
292
+ # sin and cos are specific to RoPE models; cache_position needed for the static cache
293
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
294
+ key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx, cache_kwargs)
295
+
296
+ attention_interface: Callable = eager_attention_forward
297
+ if self.config._attn_implementation != "eager":
298
+ attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
299
+
300
+ attn_output, attn_weights = attention_interface(
301
+ self,
302
+ query_states,
303
+ key_states,
304
+ value_states,
305
+ attention_mask,
306
+ dropout=0.0 if not self.training else self.attention_dropout,
307
+ scaling=self.scaling,
308
+ sliding_window=self.sliding_window, # diff with Llama
309
+ **kwargs,
310
+ )
311
+
312
+ if self.gate_func is not None:
313
+ gate = self.gate_proj(hidden_states).view(
314
+ input_shape + (-1, self.head_dim))
315
+ if self.gate_func == 'silu':
316
+ gate = F.silu(gate)
317
+ else:
318
+ assert self.gate_func == 'softplus'
319
+ gate = F.softplus(gate, beta=math.log(2))
320
+
321
+ attn_output = attn_output * gate
322
+
323
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
324
+ attn_output = self.o_proj(attn_output)
325
+ return attn_output, attn_weights
326
+
327
+
328
+ def apply_rotary_pos_emb_xllm(q, k, freqs_cis):
329
+ if q.shape[-1] % 2 != 0 or k.shape[-1] % 2 != 0:
330
+ raise ValueError(f"RoPE dimensions must be even, got q={q.shape[-1]} and k={k.shape[-1]}")
331
+ q_ = torch.view_as_complex(q.float().reshape(*q.shape[:-1], -1, 2))
332
+ k_ = torch.view_as_complex(k.float().reshape(*k.shape[:-1], -1, 2))
333
+ if freqs_cis.ndim == 2:
334
+ freqs_cis = freqs_cis.unsqueeze(1)
335
+ elif freqs_cis.ndim == 3:
336
+ freqs_cis = freqs_cis.unsqueeze(2)
337
+ else:
338
+ raise ValueError(f"Unsupported freqs_cis shape: {tuple(freqs_cis.shape)}")
339
+ if freqs_cis.shape[-1] != q_.shape[-1] or freqs_cis.shape[-1] != k_.shape[-1]:
340
+ raise ValueError(
341
+ "RoPE frequency dimension mismatch: "
342
+ f"q_rope_dim={q.shape[-1]}, k_rope_dim={k.shape[-1]}, "
343
+ f"q_complex_dim={q_.shape[-1]}, k_complex_dim={k_.shape[-1]}, "
344
+ f"freqs_complex_dim={freqs_cis.shape[-1]}, freqs_shape={tuple(freqs_cis.shape)}"
345
+ )
346
+ q_embed = torch.view_as_real(q_ * freqs_cis).flatten(-2).to(q.dtype)
347
+ k_embed = torch.view_as_real(k_ * freqs_cis).flatten(-2).to(k.dtype)
348
+ return q_embed, k_embed
349
+
350
+
351
+ class K2HorizonMoVAAttention(nn.Module):
352
+ """MoVA attention with routed value experts and optional post-attention gate."""
353
+
354
+ def __init__(self, config: K2HorizonConfig, layer_idx: int):
355
+ super().__init__()
356
+ self.config = config
357
+ self.layer_idx = layer_idx
358
+ self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
359
+ self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
360
+ self.scaling = self.head_dim**-0.5
361
+ self.attention_dropout = config.attention_dropout
362
+ self.is_causal = True
363
+
364
+ self.num_experts_per_tok = config.mova_num_experts_per_tok
365
+ self.router_score_func = config.router_score_func
366
+ self.router_scaling_factor = config.router_scaling_factor
367
+ self.gate_func = config.attention_gate_func
368
+
369
+ self.rope_head_dim = self.head_dim if config.rope_head_dim is None else config.rope_head_dim
370
+
371
+ self.q_proj = nn.Linear(
372
+ config.hidden_size, config.num_attention_heads * self.head_dim, bias=config.attention_bias
373
+ )
374
+ self.k_proj = nn.Linear(
375
+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
376
+ )
377
+ self.o_proj = nn.Linear(
378
+ config.num_attention_heads * self.head_dim, config.hidden_size, bias=config.attention_bias
379
+ )
380
+ self.v_router = nn.Linear(
381
+ config.hidden_size,
382
+ config.mova_num_experts,
383
+ bias=config.moe_gate_bias)
384
+ self.v_experts = nn.ModuleList([
385
+ nn.Linear(
386
+ config.hidden_size,
387
+ config.num_key_value_heads * self.head_dim,
388
+ bias=False
389
+ ) for _ in range(config.mova_num_experts)
390
+ ])
391
+
392
+ if self.gate_func is not None:
393
+ self.gate_proj = nn.Linear(
394
+ config.hidden_size,
395
+ config.num_attention_heads * self.head_dim,
396
+ bias=False)
397
+
398
+ if config.query_key_norm:
399
+ self.q_norm = K2HorizonRMSNorm(
400
+ hidden_size=config.num_attention_heads * self.head_dim,
401
+ n_groups=config.num_attention_heads,
402
+ eps=config.rms_norm_eps,
403
+ )
404
+ self.k_norm = K2HorizonRMSNorm(
405
+ hidden_size=config.num_key_value_heads * self.head_dim,
406
+ n_groups=config.num_key_value_heads,
407
+ eps=config.rms_norm_eps,
408
+ )
409
+
410
+ self.sliding_window = getattr(config, "sliding_window", None)
411
+
412
+ @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
413
+ def forward(
414
+ self,
415
+ hidden_states: torch.Tensor,
416
+ position_embeddings: torch.Tensor,
417
+ attention_mask: Optional[torch.Tensor],
418
+ past_key_values: Optional[Cache] = None,
419
+ cache_position: Optional[torch.LongTensor] = None,
420
+ **kwargs: Unpack[FlashAttentionKwargs],
421
+ ) -> tuple[torch.Tensor, Optional[torch.Tensor]]:
422
+ input_shape = hidden_states.shape[:-1]
423
+ hidden_shape = (*input_shape, -1, self.head_dim)
424
+ flat_hidden_states = hidden_states.reshape(-1, hidden_states.shape[-1])
425
+
426
+ # Match native MOVAttention router semantics exactly: compute logits with
427
+ # the weight-only linear and apply router bias only to selection scores.
428
+ router_logits = F.linear(flat_hidden_states, self.v_router.weight)
429
+ routing_weights, selected_values = calc_router_weights(
430
+ router_logits=router_logits,
431
+ router_bias=self.v_router.bias,
432
+ score_func=self.router_score_func,
433
+ top_k=self.num_experts_per_tok,
434
+ scaling_factor=self.router_scaling_factor,
435
+ )
436
+
437
+ mixed_value_states = combine_routed_experts(
438
+ hidden_states=flat_hidden_states,
439
+ routing_weights=routing_weights,
440
+ selected_indices=selected_values,
441
+ experts=self.v_experts,
442
+ activation=F.silu)
443
+
444
+ value_states = mixed_value_states.view(hidden_shape).transpose(1, 2)
445
+
446
+ if self.config.query_key_norm:
447
+ query_states = self.q_norm(self.q_proj(hidden_states)).view(hidden_shape).transpose(1, 2)
448
+ key_states = self.k_norm(self.k_proj(hidden_states)).view(hidden_shape).transpose(1, 2)
449
+ else:
450
+ query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2)
451
+ key_states = self.k_proj(hidden_states).view(hidden_shape).transpose(1, 2)
452
+
453
+ cos, sin = position_embeddings
454
+ if self.rope_head_dim == self.head_dim:
455
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
456
+ else:
457
+ query_states, query_states_ = torch.split(
458
+ split_to_interleaved(query_states),
459
+ split_size_or_sections=[self.rope_head_dim, self.head_dim - self.rope_head_dim],
460
+ dim=-1)
461
+
462
+ key_states, key_states_ = torch.split(
463
+ split_to_interleaved(key_states),
464
+ split_size_or_sections=[self.rope_head_dim, self.head_dim - self.rope_head_dim],
465
+ dim=-1)
466
+
467
+ query_states, key_states = apply_rotary_pos_emb(
468
+ interleaved_to_split(query_states),
469
+ interleaved_to_split(key_states),
470
+ cos,
471
+ sin)
472
+
473
+ query_states = interleaved_to_split(torch.cat(
474
+ [split_to_interleaved(query_states), query_states_], dim=-1))
475
+ key_states = interleaved_to_split(torch.cat(
476
+ [split_to_interleaved(key_states), key_states_], dim=-1))
477
+
478
+ if past_key_values is not None:
479
+ cache_kwargs = {"cache_position": cache_position}
480
+ key_states, value_states = past_key_values.update(
481
+ key_states, value_states, self.layer_idx, cache_kwargs
482
+ )
483
+
484
+ attention_interface: Callable = eager_attention_forward
485
+ if self.config._attn_implementation != "eager":
486
+ attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
487
+
488
+ attn_output, attn_weights = attention_interface(
489
+ self,
490
+ query_states,
491
+ key_states,
492
+ value_states,
493
+ attention_mask,
494
+ dropout=0.0 if not self.training else self.attention_dropout,
495
+ scaling=self.scaling,
496
+ sliding_window=self.sliding_window,
497
+ **kwargs,
498
+ )
499
+
500
+ if self.gate_func is not None:
501
+ gate = self.gate_proj(hidden_states).view(input_shape + (-1, self.head_dim))
502
+ if self.gate_func == 'silu':
503
+ gate = F.silu(gate)
504
+ else:
505
+ assert self.gate_func == 'softplus'
506
+ gate = F.softplus(gate, beta=math.log(2))
507
+
508
+ attn_output = attn_output * gate
509
+
510
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
511
+ attn_output = self.o_proj(attn_output)
512
+ return attn_output, attn_weights
513
+
514
+
515
+ class K2HorizonMLP(nn.Module):
516
+ def __init__(self, config, intermediate_size=None):
517
+ super().__init__()
518
+ self.config = config
519
+ self.hidden_size = config.hidden_size
520
+ self.intermediate_size = intermediate_size if intermediate_size is not None else config.intermediate_size
521
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
522
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
523
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
524
+ self.act_fn = ACT2FN[config.hidden_act]
525
+
526
+ def forward(self, x):
527
+ down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
528
+ return down_proj
529
+
530
+
531
+ class K2HorizonSparseMoeBlock(nn.Module):
532
+ def __init__(self, config):
533
+ super().__init__()
534
+ self.num_experts = config.num_experts
535
+ self.top_k = config.num_experts_per_tok
536
+ self.norm_topk_prob = config.norm_topk_prob
537
+ self.num_shared_experts = config.num_shared_experts
538
+ self.router_score_func = config.router_score_func
539
+ self.router_scaling_factor = config.router_scaling_factor
540
+
541
+ # gating
542
+ self.gate = nn.Linear(config.hidden_size, config.num_experts, bias=config.moe_gate_bias)
543
+ self.experts = nn.ModuleList(
544
+ [K2HorizonMLP(config, intermediate_size=config.moe_intermediate_size) for _ in range(self.num_experts)]
545
+ )
546
+
547
+ if config.num_shared_experts > 0:
548
+ self.shared_experts = K2HorizonMLP(
549
+ config=config,
550
+ intermediate_size=config.moe_intermediate_size * config.num_shared_experts)
551
+
552
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
553
+ """ """
554
+ residuals = hidden_states
555
+
556
+ batch_size, sequence_length, hidden_dim = hidden_states.shape
557
+ hidden_states = hidden_states.view(-1, hidden_dim)
558
+ # router_logits: (batch * sequence_length, n_experts)
559
+ # router_logits = self.gate(hidden_states)
560
+ router_logits = F.linear(hidden_states, self.gate.weight)
561
+
562
+ if self.router_score_func == "softmax":
563
+ routing_weights = F.softmax(router_logits, dim=1, dtype=torch.float)
564
+ else:
565
+ assert self.router_score_func == "sigmoid"
566
+ routing_weights = F.sigmoid(router_logits.to(torch.float32))
567
+
568
+ routing_weights_for_choice = routing_weights
569
+ if self.gate.bias is not None:
570
+ routing_weights_for_choice = routing_weights + self.gate.bias.to(routing_weights.dtype)
571
+
572
+ _, selected_experts = torch.topk(routing_weights_for_choice, self.top_k, dim=-1)
573
+ routing_weights = torch.gather(routing_weights, dim=-1, index=selected_experts)
574
+
575
+ if self.norm_topk_prob: # only diff with mixtral sparse moe block!
576
+ routing_weights /= routing_weights.sum(dim=-1, keepdim=True)
577
+ routing_weights = routing_weights * self.router_scaling_factor
578
+ # we cast back to the input dtype
579
+ routing_weights = routing_weights.to(hidden_states.dtype)
580
+
581
+ final_hidden_states = torch.zeros(
582
+ (batch_size * sequence_length, hidden_dim), dtype=hidden_states.dtype, device=hidden_states.device
583
+ )
584
+
585
+ # One hot encode the selected experts to create an expert mask
586
+ # this will be used to easily index which expert is going to be sollicitated
587
+ expert_mask = torch.nn.functional.one_hot(selected_experts, num_classes=self.num_experts).permute(2, 1, 0)
588
+
589
+ # Loop over all available experts in the model and perform the computation on each expert
590
+ expert_hit = torch.greater(expert_mask.sum(dim=(-1, -2)), 0).nonzero()
591
+ for expert_idx in expert_hit:
592
+ expert_layer = self.experts[expert_idx]
593
+ idx, top_x = torch.where(expert_mask[expert_idx].squeeze(0))
594
+
595
+ # Index the correct hidden states and compute the expert hidden state for
596
+ # the current expert. We need to make sure to multiply the output hidden
597
+ # states by `routing_weights` on the corresponding tokens (top-1 and top-2)
598
+ current_state = hidden_states[None, top_x].reshape(-1, hidden_dim)
599
+ current_hidden_states = expert_layer(current_state) * routing_weights[top_x, idx, None]
600
+
601
+ # However `index_add_` only support torch tensors for indexing so we'll use
602
+ # the `top_x` tensor here.
603
+ final_hidden_states.index_add_(0, top_x, current_hidden_states.to(hidden_states.dtype))
604
+ final_hidden_states = final_hidden_states.reshape(batch_size, sequence_length, hidden_dim)
605
+
606
+ if self.num_shared_experts > 0:
607
+ final_hidden_states = final_hidden_states + self.shared_experts(residuals)
608
+
609
+ return final_hidden_states, router_logits
610
+
611
+
612
+ # @use_kernel_forward_from_hub("RMSNorm")
613
+ class K2HorizonRMSNorm(nn.Module):
614
+ def __init__(self, hidden_size: int, n_groups: int, eps=1e-6):
615
+ """
616
+ K2HorizonRMSNorm is equivalent to T5LayerNorm
617
+ """
618
+ super().__init__()
619
+ self.n_groups = n_groups
620
+ self.hidden_size = hidden_size
621
+ assert hidden_size % n_groups == 0
622
+ self.weight = nn.Parameter(torch.ones(hidden_size))
623
+ self.variance_epsilon = eps
624
+
625
+ def forward(self, hidden_states):
626
+ input_dtype = hidden_states.dtype
627
+ hidden_states = hidden_states.to(torch.float32)
628
+
629
+ hidden_states = hidden_states.reshape(*hidden_states.shape[:-1], self.n_groups, -1)
630
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
631
+
632
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
633
+ hidden_states = hidden_states.reshape(*hidden_states.shape[:-2], -1)
634
+ hidden_states = self.weight * hidden_states
635
+
636
+ return hidden_states.to(input_dtype)
637
+
638
+ def extra_repr(self):
639
+ return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
640
+
641
+
642
+ class K2HorizonDecoderLayer(GradientCheckpointingLayer):
643
+ def __init__(self, config: K2HorizonConfig, layer_idx: int):
644
+ super().__init__()
645
+ self.hidden_size = config.hidden_size
646
+
647
+ is_sparse_layer = (layer_idx not in config.mlp_only_layers) and (
648
+ config.num_experts > 0 and (layer_idx + 1) % config.decoder_sparse_step == 0)
649
+
650
+ if is_sparse_layer and config.mova_num_experts > 0:
651
+ self.self_attn = K2HorizonMoVAAttention(config=config, layer_idx=layer_idx)
652
+ else:
653
+ self.self_attn = K2HorizonAttention(config, layer_idx)
654
+
655
+ if is_sparse_layer:
656
+ self.mlp = K2HorizonSparseMoeBlock(config)
657
+ else:
658
+ self.mlp = K2HorizonMLP(config, intermediate_size=config.intermediate_size)
659
+
660
+ assert config.hidden_size % config.layernorm_num_groups == 0
661
+ self.input_layernorm = K2HorizonRMSNorm(
662
+ hidden_size=config.hidden_size,
663
+ n_groups=config.layernorm_num_groups,
664
+ eps=config.rms_norm_eps)
665
+ self.post_attention_layernorm = K2HorizonRMSNorm(
666
+ hidden_size=config.hidden_size,
667
+ n_groups=config.layernorm_num_groups,
668
+ eps=config.rms_norm_eps)
669
+
670
+ @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
671
+ def forward(
672
+ self,
673
+ hidden_states: torch.Tensor,
674
+ position_embeddings: tuple[torch.Tensor, torch.Tensor],
675
+ attention_mask: Optional[torch.Tensor] = None,
676
+ position_ids: Optional[torch.LongTensor] = None,
677
+ past_key_values: Optional[Cache] = None,
678
+ cache_position: Optional[torch.LongTensor] = None,
679
+ **kwargs: Unpack[FlashAttentionKwargs],
680
+ ) -> torch.FloatTensor:
681
+ """
682
+ Args:
683
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
684
+ attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
685
+ `(batch, sequence_length)` where padding elements are indicated by 0.
686
+ output_attentions (`bool`, *optional*):
687
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
688
+ returned tensors for more detail.
689
+ output_router_logits (`bool`, *optional*):
690
+ Whether or not to return the logits of all the routers. They are useful for computing the router loss,
691
+ and should not be returned during inference.
692
+ use_cache (`bool`, *optional*):
693
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
694
+ (see `past_key_values`).
695
+ past_key_values (`Cache`, *optional*): cached past key and value projection states
696
+ cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
697
+ Indices depicting the position of the input sequence tokens in the sequence.
698
+ position_embeddings (`tuple[torch.FloatTensor, torch.FloatTensor]`, *optional*):
699
+ Tuple containing the cosine and sine positional embeddings of shape `(batch_size, seq_len, head_dim)`,
700
+ with `head_dim` being the embedding dimension of each attention head.
701
+ kwargs (`dict`, *optional*):
702
+ Arbitrary kwargs to be ignored, used for FSDP and other methods that injects code
703
+ into the model
704
+ """
705
+ residual = hidden_states
706
+ hidden_states = self.input_layernorm(hidden_states)
707
+
708
+ # Self Attention
709
+ hidden_states, _ = self.self_attn(
710
+ hidden_states=hidden_states,
711
+ position_embeddings=position_embeddings,
712
+ attention_mask=attention_mask,
713
+ position_ids=position_ids,
714
+ past_key_values=past_key_values,
715
+ cache_position=cache_position,
716
+ **kwargs,
717
+ )
718
+
719
+ hidden_states = residual + hidden_states
720
+
721
+ # Fully Connected
722
+ residual = hidden_states
723
+ hidden_states = self.post_attention_layernorm(hidden_states)
724
+ hidden_states = self.mlp(hidden_states)
725
+ # For the MoE layers, we need to unpack
726
+ if isinstance(hidden_states, tuple):
727
+ hidden_states, _ = hidden_states
728
+ hidden_states = residual + hidden_states
729
+
730
+ return hidden_states
731
+
732
+
733
+ class K2HorizonRotaryEmbedding(nn.Module):
734
+ inv_freq: torch.Tensor # fix linting for `register_buffer`
735
+
736
+ def __init__(self, config: K2HorizonConfig, device=None):
737
+ super().__init__()
738
+ self.max_seq_len_cached = config.max_position_embeddings
739
+ self.original_max_seq_len = config.max_position_embeddings
740
+
741
+ self.config = config
742
+
743
+ self.rope_type = self.config.rope_parameters["rope_type"]
744
+ rope_init_fn: Callable = self.compute_default_rope_parameters
745
+ if self.rope_type != "default":
746
+ rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
747
+ inv_freq, self.attention_scaling = rope_init_fn(self.config, device)
748
+
749
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
750
+ self.register_buffer("original_inv_freq", inv_freq.clone(), persistent=False)
751
+
752
+ @staticmethod
753
+ def compute_default_rope_parameters(
754
+ config: K2HorizonConfig | None = None,
755
+ device: Optional["torch.device"] = None,
756
+ seq_len: int | None = None,
757
+ ) -> tuple["torch.Tensor", float]:
758
+ """
759
+ Computes the inverse frequencies according to the original RoPE implementation
760
+ Args:
761
+ config ([`~transformers.PreTrainedConfig`]):
762
+ The model configuration.
763
+ device (`torch.device`):
764
+ The device to use for initialization of the inverse frequencies.
765
+ seq_len (`int`, *optional*):
766
+ The current sequence length. Unused for this type of RoPE.
767
+ Returns:
768
+ Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the
769
+ post-processing scaling factor applied to the computed cos/sin (unused in this type of RoPE).
770
+ """
771
+ base = config.rope_parameters["rope_theta"]
772
+ # dim = getattr(config, "head_dim", None) or config.hidden_size // config.num_attention_heads
773
+ dim = (
774
+ config.rope_head_dim
775
+ if config.rope_head_dim is not None
776
+ else getattr(config, "head_dim", None) or config.hidden_size // config.num_attention_heads
777
+ )
778
+
779
+ attention_factor = 1.0 # Unused in this type of RoPE
780
+
781
+ # Compute the inverse frequencies
782
+ inv_freq = 1.0 / (
783
+ base ** (torch.arange(0, dim, 2, dtype=torch.int64).to(device=device, dtype=torch.float) / dim)
784
+ )
785
+ return inv_freq, attention_factor
786
+
787
+ @torch.no_grad()
788
+ @dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope)
789
+ def forward(self, x, position_ids):
790
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device)
791
+ position_ids_expanded = position_ids[:, None, :].float()
792
+
793
+ device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
794
+ with maybe_autocast(device_type=device_type, enabled=False): # Force float32
795
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
796
+ emb = torch.cat((freqs, freqs), dim=-1)
797
+ cos = emb.cos() * self.attention_scaling
798
+ sin = emb.sin() * self.attention_scaling
799
+
800
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
801
+
802
+
803
+ @auto_docstring
804
+ class K2HorizonPreTrainedModel(PreTrainedModel):
805
+ config: K2HorizonConfig
806
+ base_model_prefix = "model"
807
+ supports_gradient_checkpointing = True
808
+ _no_split_modules = ["K2HorizonDecoderLayer"]
809
+ _skip_keys_device_placement = ["past_key_values"]
810
+ _supports_flash_attn = True
811
+ _supports_sdpa = True
812
+ _supports_flex_attn = True
813
+ _can_compile_fullgraph = False # MoE models don't work with torch.compile (`torch.where(condition)` not supported)
814
+ _supports_attention_backend = True
815
+ _can_record_outputs = {
816
+ "router_logits": OutputRecorder(K2HorizonSparseMoeBlock, index=1),
817
+ "hidden_states": K2HorizonDecoderLayer,
818
+ "attentions": K2HorizonAttention,
819
+ }
820
+
821
+
822
+ @auto_docstring
823
+ class K2HorizonModel(K2HorizonPreTrainedModel):
824
+ def __init__(self, config: K2HorizonConfig):
825
+ super().__init__(config)
826
+ # self.padding_idx = config.pad_token_id
827
+ self.padding_idx = getattr(config, "padding_idx", None)
828
+ self.vocab_size = config.vocab_size
829
+
830
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
831
+ self.layers = nn.ModuleList(
832
+ [K2HorizonDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
833
+ )
834
+
835
+ assert config.hidden_size % config.layernorm_num_groups == 0
836
+ self.norm = K2HorizonRMSNorm(
837
+ hidden_size=config.hidden_size,
838
+ n_groups=config.layernorm_num_groups,
839
+ eps=config.rms_norm_eps)
840
+
841
+ self.rotary_emb = K2HorizonRotaryEmbedding(config=config)
842
+ self.gradient_checkpointing = False
843
+
844
+ # Initialize weights and apply final processing
845
+ self.post_init()
846
+
847
+ @auto_docstring
848
+ def forward(
849
+ self,
850
+ input_ids: Optional[torch.LongTensor] = None,
851
+ attention_mask: Optional[torch.Tensor] = None,
852
+ position_ids: Optional[torch.LongTensor] = None,
853
+ past_key_values: Optional[Cache] = None,
854
+ inputs_embeds: Optional[torch.FloatTensor] = None,
855
+ use_cache: Optional[bool] = None,
856
+ cache_position: Optional[torch.LongTensor] = None,
857
+ **kwargs: Unpack[TransformersKwargs],
858
+ ) -> MoeModelOutputWithPast:
859
+ if (input_ids is None) ^ (inputs_embeds is not None):
860
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
861
+
862
+ if use_cache and past_key_values is None:
863
+ past_key_values = DynamicCache(config=self.config)
864
+
865
+ if inputs_embeds is None:
866
+ inputs_embeds = self.embed_tokens(input_ids)
867
+
868
+ if cache_position is None:
869
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
870
+ cache_position = torch.arange(
871
+ past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
872
+ )
873
+ if position_ids is None:
874
+ position_ids = cache_position.unsqueeze(0)
875
+
876
+ mask_function = create_causal_mask if self.config.sliding_window is None else create_sliding_window_causal_mask
877
+ causal_mask = mask_function(
878
+ config=self.config,
879
+ inputs_embeds=inputs_embeds,
880
+ attention_mask=attention_mask,
881
+ past_key_values=past_key_values,
882
+ position_ids=position_ids,
883
+ )
884
+
885
+ hidden_states = inputs_embeds
886
+
887
+ # create position embeddings to be shared across the decoder layers
888
+ position_embeddings = self.rotary_emb(hidden_states, position_ids)
889
+
890
+ for layer_idx, decoder_layer in enumerate(self.layers[: self.config.num_hidden_layers]):
891
+ hidden_states = decoder_layer(
892
+ hidden_states,
893
+ position_embeddings=position_embeddings,
894
+ attention_mask=causal_mask,
895
+ position_ids=position_ids,
896
+ past_key_values=past_key_values,
897
+ use_cache=use_cache,
898
+ cache_position=cache_position,
899
+ **kwargs,
900
+ )
901
+
902
+ hidden_states = self.norm(hidden_states)
903
+
904
+ return MoeModelOutputWithPast( # only diff with Mistral is the output type, we need MoE
905
+ last_hidden_state=hidden_states,
906
+ past_key_values=past_key_values,
907
+ )
908
+
909
+
910
+ def load_balancing_loss_func(
911
+ gate_logits: Union[torch.Tensor, tuple[torch.Tensor], None],
912
+ num_experts: Optional[int] = None,
913
+ top_k=2,
914
+ attention_mask: Optional[torch.Tensor] = None,
915
+ ) -> Union[torch.Tensor, int]:
916
+ r"""
917
+ Computes auxiliary load balancing loss as in Switch Transformer - implemented in Pytorch.
918
+
919
+ See Switch Transformer (https://huggingface.co/papers/2101.03961) for more details. This function implements the loss
920
+ function presented in equations (4) - (6) of the paper. It aims at penalizing cases where the routing between
921
+ experts is too unbalanced.
922
+
923
+ Args:
924
+ gate_logits:
925
+ Logits from the `gate`, should be a tuple of model.config.num_hidden_layers tensors of
926
+ shape [batch_size X sequence_length, num_experts].
927
+ num_experts:
928
+ Number of experts
929
+ top_k:
930
+ The number of experts to route per-token, can be also interpreted as the `top-k` routing
931
+ parameter.
932
+ attention_mask (`torch.Tensor`, *optional*):
933
+ The attention_mask used in forward function
934
+ shape [batch_size X sequence_length] if not None.
935
+
936
+ Returns:
937
+ The auxiliary loss.
938
+ """
939
+ if gate_logits is None or not isinstance(gate_logits, tuple):
940
+ return 0
941
+
942
+ if isinstance(gate_logits, tuple):
943
+ compute_device = gate_logits[0].device
944
+ concatenated_gate_logits = torch.cat([layer_gate.to(compute_device) for layer_gate in gate_logits], dim=0)
945
+
946
+ routing_weights = torch.nn.functional.softmax(concatenated_gate_logits, dim=-1)
947
+
948
+ _, selected_experts = torch.topk(routing_weights, top_k, dim=-1)
949
+
950
+ expert_mask = torch.nn.functional.one_hot(selected_experts, num_experts)
951
+
952
+ if attention_mask is None:
953
+ # Compute the percentage of tokens routed to each experts
954
+ tokens_per_expert = torch.mean(expert_mask.float(), dim=0)
955
+
956
+ # Compute the average probability of routing to these experts
957
+ router_prob_per_expert = torch.mean(routing_weights, dim=0)
958
+ else:
959
+ batch_size, sequence_length = attention_mask.shape
960
+ num_hidden_layers = concatenated_gate_logits.shape[0] // (batch_size * sequence_length)
961
+
962
+ # Compute the mask that masks all padding tokens as 0 with the same shape of expert_mask
963
+ expert_attention_mask = (
964
+ attention_mask[None, :, :, None, None]
965
+ .expand((num_hidden_layers, batch_size, sequence_length, top_k, num_experts))
966
+ .reshape(-1, top_k, num_experts)
967
+ .to(compute_device)
968
+ )
969
+
970
+ # Compute the percentage of tokens routed to each experts
971
+ tokens_per_expert = torch.sum(expert_mask.float() * expert_attention_mask, dim=0) / torch.sum(
972
+ expert_attention_mask, dim=0
973
+ )
974
+
975
+ # Compute the mask that masks all padding tokens as 0 with the same shape of tokens_per_expert
976
+ router_per_expert_attention_mask = (
977
+ attention_mask[None, :, :, None]
978
+ .expand((num_hidden_layers, batch_size, sequence_length, num_experts))
979
+ .reshape(-1, num_experts)
980
+ .to(compute_device)
981
+ )
982
+
983
+ # Compute the average probability of routing to these experts
984
+ router_prob_per_expert = torch.sum(routing_weights * router_per_expert_attention_mask, dim=0) / torch.sum(
985
+ router_per_expert_attention_mask, dim=0
986
+ )
987
+
988
+ overall_loss = torch.sum(tokens_per_expert * router_prob_per_expert.unsqueeze(0))
989
+ return overall_loss * num_experts
990
+
991
+
992
+ @auto_docstring
993
+ class K2HorizonForCausalLM(K2HorizonPreTrainedModel, GenerationMixin):
994
+ # _tied_weights_keys = ["lm_head.weight"]
995
+ # _tp_plan = {"lm_head": "colwise_rep"}
996
+ # _pp_plan = {"lm_head": (["hidden_states"], ["logits"])}
997
+
998
+ def __init__(self, config):
999
+ super().__init__(config)
1000
+ self.model = K2HorizonModel(config)
1001
+ self.vocab_size = config.vocab_size
1002
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1003
+ self.router_aux_loss_coef = config.router_aux_loss_coef
1004
+ self.num_experts = config.num_experts
1005
+ self.num_experts_per_tok = config.num_experts_per_tok
1006
+
1007
+ # Initialize weights and apply final processing
1008
+ self.post_init()
1009
+
1010
+ @can_return_tuple
1011
+ @auto_docstring
1012
+ def forward(
1013
+ self,
1014
+ input_ids: Optional[torch.LongTensor] = None,
1015
+ attention_mask: Optional[torch.Tensor] = None,
1016
+ position_ids: Optional[torch.LongTensor] = None,
1017
+ past_key_values: Optional[Cache] = None,
1018
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1019
+ labels: Optional[torch.LongTensor] = None,
1020
+ use_cache: Optional[bool] = None,
1021
+ output_router_logits: Optional[bool] = None,
1022
+ cache_position: Optional[torch.LongTensor] = None,
1023
+ logits_to_keep: Union[int, torch.Tensor] = 0,
1024
+ **kwargs: Unpack[TransformersKwargs],
1025
+ ) -> MoeCausalLMOutputWithPast:
1026
+ r"""
1027
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1028
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1029
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1030
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1031
+
1032
+ Example:
1033
+
1034
+ ```python
1035
+ >>> from transformers import AutoTokenizer, K2HorizonForCausalLM
1036
+
1037
+ >>> model = K2HorizonForCausalLM.from_pretrained("Qwen/Qwen3-MoE-15B-A2B")
1038
+ >>> tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen3-MoE-15B-A2B")
1039
+
1040
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
1041
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
1042
+
1043
+ >>> # Generate
1044
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
1045
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1046
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
1047
+ ```"""
1048
+
1049
+ output_router_logits = (
1050
+ output_router_logits if output_router_logits is not None else self.config.output_router_logits
1051
+ )
1052
+
1053
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1054
+ outputs: MoeModelOutputWithPast = self.model(
1055
+ input_ids=input_ids,
1056
+ attention_mask=attention_mask,
1057
+ position_ids=position_ids,
1058
+ past_key_values=past_key_values,
1059
+ inputs_embeds=inputs_embeds,
1060
+ use_cache=use_cache,
1061
+ output_router_logits=output_router_logits,
1062
+ cache_position=cache_position,
1063
+ **kwargs,
1064
+ )
1065
+
1066
+ hidden_states = outputs.last_hidden_state
1067
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
1068
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
1069
+ logits = self.lm_head(hidden_states[:, slice_indices, :])
1070
+
1071
+ loss = None
1072
+ if labels is not None:
1073
+ loss = self.loss_function(logits, labels, self.vocab_size, **kwargs)
1074
+
1075
+ aux_loss = None
1076
+ if output_router_logits:
1077
+ aux_loss = load_balancing_loss_func(
1078
+ outputs.router_logits,
1079
+ self.num_experts,
1080
+ self.num_experts_per_tok,
1081
+ attention_mask,
1082
+ )
1083
+ if labels is not None:
1084
+ loss += self.router_aux_loss_coef * aux_loss.to(loss.device) # make sure to reside in the same device
1085
+
1086
+ return MoeCausalLMOutputWithPast(
1087
+ loss=loss,
1088
+ aux_loss=aux_loss,
1089
+ logits=logits,
1090
+ past_key_values=outputs.past_key_values,
1091
+ hidden_states=outputs.hidden_states,
1092
+ attentions=outputs.attentions,
1093
+ router_logits=outputs.router_logits,
1094
+ )
1095
+
1096
+
1097
+ class K2HorizonForSequenceClassification(GenericForSequenceClassification, K2HorizonPreTrainedModel):
1098
+ pass
1099
+
1100
+
1101
+ class K2HorizonForTokenClassification(GenericForTokenClassification, K2HorizonPreTrainedModel):
1102
+ pass
1103
+
1104
+
1105
+ class K2HorizonForQuestionAnswering(GenericForQuestionAnswering, K2HorizonPreTrainedModel):
1106
+ base_model_prefix = "transformer" # For BC, where `transformer` was used instead of `model`
1107
+
1108
+
1109
+ __all__ = [
1110
+ "K2HorizonForCausalLM",
1111
+ "K2HorizonForQuestionAnswering",
1112
+ "K2HorizonModel",
1113
+ "K2HorizonPreTrainedModel",
1114
+ "K2HorizonForSequenceClassification",
1115
+ "K2HorizonForTokenClassification",
1116
+ ]
pytorch_model-00001-of-00036.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d110e6762cf85f674fafa94cadbf3fb07b970fff3d2253eeddcfd9fa679c9b10
3
+ size 209726456
pytorch_model-00002-of-00036.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:219394d503b95ea4973c92b97afb24ab76dcb18911edccf824fd84bd166657fe
3
+ size 209726456
pytorch_model-00003-of-00036.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b1ddbe4ff8c50178a50babf808a662e2b5062161e368d1fcd6445814de0dcbc4
3
+ size 209726456
pytorch_model-00004-of-00036.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ef32e974a0a8ac08c2e42dd729a29a539fcedbcd54fc3b5d20ec8016c061fcd1
3
+ size 209726456
pytorch_model-00005-of-00036.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ab173ae7f0e15552083a4357337b6db221c8b39368896cf87954a6ca8112834e
3
+ size 209726456
pytorch_model-00006-of-00036.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:04800ffb44ae333db31acebabbd3b6479d922e70815d2a980095c692802bfd3b
3
+ size 209726456
pytorch_model-00007-of-00036.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:58283718bb60434d34558195aaf8a500102ea8b6900313a526bb2000e39fec5a
3
+ size 209726456
pytorch_model-00008-of-00036.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:07ea6dcc528a1c8aa40629b1ac82f1f4709af27c7bfbba463e09322ac54ffbbd
3
+ size 209726456
pytorch_model-00009-of-00036.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1c7ca45ab209e907cd0870434ce250a45d2f2fcabee172863acb7f4347d591f7
3
+ size 209726456
pytorch_model-00010-of-00036.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:72630d27e7473b133a4d0bfd06698c38d3e59e91d966ff33faf0ee0dfed45aac
3
+ size 209726456
pytorch_model-00011-of-00036.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b79b48f5cb1ba86dab068c136b6bdba5a89227ea8da77efd9b11cefee4daa042
3
+ size 209726464
pytorch_model-00012-of-00036.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:555adf66a051ed26ff2f62b7225e66c66e337d8d17883215467c50b3067a01c0
3
+ size 209726464
pytorch_model-00013-of-00036.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:88c0309e67230e0b46969c03ef1d38f7c5a1c64338618c948a03cb88f5fc1125
3
+ size 209726464
pytorch_model-00014-of-00036.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:741024e7349d3f7da3830daaba44652b29bc376d5a1b798e544251ce08f750b6
3
+ size 209726464
pytorch_model-00015-of-00036.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:109a4b90c9196f1efc85a6c37ca493b51417af36fbf5c04435a8efb1caeb0721
3
+ size 209726464
pytorch_model-00016-of-00036.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:233aba62372d793e5fe0049c8bafb5e84030a177e90db7c7870dd49c523ed55a
3
+ size 209726464
pytorch_model-00017-of-00036.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1c7a72eb7ab4ec07fb50a1f39e6ed1699ed9d4d8eee1a97fef67f915cb860a6c
3
+ size 209726464
pytorch_model-00018-of-00036.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a6f037b8abb77be356c85c84135c35dd6e638c92d1cf6b99851301d44dc5b266
3
+ size 209726464
pytorch_model-00019-of-00036.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c93b7417584fe5f0df966a7e35c2d81eee2c3bd3a2211a3581fdd9330ece1033
3
+ size 209726464
pytorch_model-00020-of-00036.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:42f887f37c4568d975d84d64d15ecf8b811c3e06fd4c5642ab083b77c6079400
3
+ size 209726464
pytorch_model-00021-of-00036.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9180c84c2765b1195a93fcbf2b91842c3aa48b5a93d9c21a5f5186743e84b85c
3
+ size 209726464
pytorch_model-00022-of-00036.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:779922fd3ddd1d521637897f989b896fe088da27e84f8de41cbadfabc45559bf
3
+ size 209726464
pytorch_model-00023-of-00036.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7ec024d9567112f7c678176f6a7ff096d7e6adc680dcb9943c719ca1c40d0697
3
+ size 209726464
pytorch_model-00024-of-00036.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c1f47068a96f74316ad78d1f61a747af075fc551e46affd4565e32735649018f
3
+ size 209726464
pytorch_model-00025-of-00036.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:69cb586f3870597d9b9406813d3b114bb597139ed7e4290ca4727d385f308ae8
3
+ size 209726464
pytorch_model-00026-of-00036.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:db3c9ca402ce5641a0931f54e2708310b4def9b5339fc9f2498731ba49f90559
3
+ size 209726464
pytorch_model-00027-of-00036.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a213216658c5f60061b05f68c28ef2c2ad8b707e512d2ca59dcc83cbebd6c855
3
+ size 209726464
pytorch_model-00028-of-00036.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ca2eecbadf94ef6823166cb5621c016f6924c132d038feda2f98603dc43c64a9
3
+ size 209726464
pytorch_model-00029-of-00036.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:18014f073dfffc8778dee79ebdb4a10fe6a17e19ac5ce165f42ee6d9a7241422
3
+ size 209726464
pytorch_model-00030-of-00036.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:52017c4e7a7622caf41b5638c9f5670cdbe683ca158c650c102dee7db77a21a0
3
+ size 209726464
pytorch_model-00031-of-00036.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:595d6832ae7c0bc602f09db5085d1ffb6d3d0eefde5334b038174d9a679e14c6
3
+ size 209726464
pytorch_model-00032-of-00036.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ce282ec1948eae29b6766b717b5ef61f9e70ce67b4f3eb941f801b2a59526b65
3
+ size 209726464
pytorch_model-00033-of-00036.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d54819763862df5da76be25d1e25a8366407add31bf749a098ca9265c0a6e4bc
3
+ size 209726464
pytorch_model-00034-of-00036.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5db1fc8429dd8b14759068c0026ea84e3476ce44f2d7f715792f28da4a4e59d7
3
+ size 209726464
pytorch_model-00035-of-00036.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9e151f279a2b3fcfc13dd8a5b52609dbbb3d35c454b1371d044ed7df08d3bef7
3
+ size 209726464
pytorch_model-00036-of-00036.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:80ed9da7581f3f6226e9dfd701210b6d61fd7461343b45883eeb0271d39eca06
3
+ size 2776121664
tokenizer.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:838d767b7c9925ff257feb20eaa4299a8e3cc35bb3d805589c373f51d2cc3cb6
3
+ size 20637260
tokenizer_config.json ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "backend": "tokenizers",
3
+ "bos_token": "<|ifm|begin_of_text|>",
4
+ "clean_up_tokenization_spaces": false,
5
+ "eos_token": "<|ifm|endoftext|>",
6
+ "is_local": true,
7
+ "local_files_only": false,
8
+ "model_max_length": 1000000000000000019884624838656,
9
+ "tokenizer_class": "TokenizersBackend"
10
+ }