hermitdave commited on
Commit
bb03345
·
verified ·
1 Parent(s): 5f2c1ae

Add files using upload-large-folder tool

Browse files
.gitattributes CHANGED
@@ -33,3 +33,4 @@ saved_model/**/* 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
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ tokenizer.json filter=lfs diff=lfs merge=lfs -text
README.md ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ base_model: IFM/K2-Horizon-7B-Uno
3
+ tags:
4
+ - mlx
5
+ - apple-silicon
6
+ - text-generation
7
+ - uno
8
+ - oQ
9
+ - oQ4e
10
+ license: apache-2.0
11
+ ---
12
+
13
+ # K2-Horizon-7B-Uno oQ4e
14
+
15
+ oQ4e (imatrix-enhanced mixed-precision ~4.5 BPW) quantization of the merged [IFM/K2-Horizon-7B-Uno](https://huggingface.co/IFM/K2-Horizon-7B-Uno) model — a diffusion-augmented LLM based on K2-Horizon-7B. The LoRA adapter is baked into the base weights, so it runs as a standard autoregressive model.
16
+
17
+ **Upstream model:** [IFM/K2-Horizon-7B-Uno](https://huggingface.co/IFM/K2-Horizon-7B-Uno) by Institute of Foundation Models, released under Apache 2.0.
18
+
19
+ **Conversion:** Merged and quantized to MLX format using [Hermes Agent](https://hermes-agent.nousresearch.com) with `oMLX`.
20
+
21
+ ## Quickstart
22
+
23
+ ```bash
24
+ pip install -U mlx-lm
25
+
26
+ python3 -m mlx_lm.generate \
27
+ --model hermitdave/K2-Horizon-7B-Uno-oQ4e \
28
+ --prompt "Explain step by step." \
29
+ --max-tokens 512 --temp 1.0 --top-p 0.95
30
+ ```
31
+
32
+ ## Reasoning
33
+
34
+ K2-Horizon-7B is a reasoning model. Always use `reasoning_effort="high"`:
35
+
36
+ ```python
37
+ from openai import OpenAI
38
+
39
+ client = OpenAI(base_url="http://localhost:8000/v1", api_key="EMPTY")
40
+ response = client.chat.completions.create(
41
+ model="hermitdave/K2-Horizon-7B-Uno-oQ4e",
42
+ messages=[{"role": "user", "content": "Explain step by step."}],
43
+ extra_body={"chat_template_kwargs": {"reasoning_effort": "high"}},
44
+ )
45
+ print("Reasoning:", getattr(response.choices[0].message, "reasoning_content", None))
46
+ print("Answer:", response.choices[0].message.content)
47
+ ```
48
+
49
+ ## oMLX Patch
50
+
51
+ K2-Horizon requires oMLX v0.6.4+ with the [K2-Horizon support patch](https://github.com/jundot/omlx/pull/3441).
52
+
53
+ ## Citation
54
+
55
+ ```bibtex
56
+ @misc{k2_horizon_7b_uno,
57
+ title = {K2-Horizon-7B-Uno},
58
+ author = {Institute of Foundation Models},
59
+ year = {2026},
60
+ howpublished = {\url{https://huggingface.co/IFM/K2-Horizon-7B-Uno}},
61
+ }
62
+ ```
63
+
64
+ ## License
65
+
66
+ Apache 2.0 (same as upstream).
config.json ADDED
@@ -0,0 +1,712 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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": 4096,
20
+ "initializer_range": 0.02,
21
+ "intermediate_size": 12288,
22
+ "layernorm_num_groups": 4,
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.13.0",
89
+ "use_cache": true,
90
+ "use_sliding_window": false,
91
+ "vocab_size": 250624,
92
+ "quantization": {
93
+ "group_size": 64,
94
+ "bits": 4,
95
+ "mode": "affine",
96
+ "model.layers.0.mlp.down_proj": {
97
+ "bits": 6,
98
+ "group_size": 64,
99
+ "mode": "affine"
100
+ },
101
+ "model.layers.0.self_attn.k_proj": {
102
+ "bits": 5,
103
+ "group_size": 64,
104
+ "mode": "affine"
105
+ },
106
+ "model.layers.0.self_attn.o_proj": {
107
+ "bits": 5,
108
+ "group_size": 64,
109
+ "mode": "affine"
110
+ },
111
+ "model.layers.0.self_attn.q_proj": {
112
+ "bits": 5,
113
+ "group_size": 64,
114
+ "mode": "affine"
115
+ },
116
+ "model.layers.0.self_attn.v_proj": {
117
+ "bits": 6,
118
+ "group_size": 64,
119
+ "mode": "affine"
120
+ },
121
+ "model.layers.1.mlp.down_proj": {
122
+ "bits": 6,
123
+ "group_size": 64,
124
+ "mode": "affine"
125
+ },
126
+ "model.layers.1.self_attn.k_proj": {
127
+ "bits": 5,
128
+ "group_size": 64,
129
+ "mode": "affine"
130
+ },
131
+ "model.layers.1.self_attn.o_proj": {
132
+ "bits": 5,
133
+ "group_size": 64,
134
+ "mode": "affine"
135
+ },
136
+ "model.layers.1.self_attn.q_proj": {
137
+ "bits": 5,
138
+ "group_size": 64,
139
+ "mode": "affine"
140
+ },
141
+ "model.layers.1.self_attn.v_proj": {
142
+ "bits": 6,
143
+ "group_size": 64,
144
+ "mode": "affine"
145
+ },
146
+ "model.layers.2.mlp.down_proj": {
147
+ "bits": 5,
148
+ "group_size": 64,
149
+ "mode": "affine"
150
+ },
151
+ "model.layers.2.self_attn.o_proj": {
152
+ "bits": 5,
153
+ "group_size": 64,
154
+ "mode": "affine"
155
+ },
156
+ "model.layers.3.mlp.down_proj": {
157
+ "bits": 5,
158
+ "group_size": 64,
159
+ "mode": "affine"
160
+ },
161
+ "model.layers.3.self_attn.o_proj": {
162
+ "bits": 5,
163
+ "group_size": 64,
164
+ "mode": "affine"
165
+ },
166
+ "model.layers.4.self_attn.o_proj": {
167
+ "bits": 5,
168
+ "group_size": 64,
169
+ "mode": "affine"
170
+ },
171
+ "model.layers.10.mlp.down_proj": {
172
+ "bits": 5,
173
+ "group_size": 64,
174
+ "mode": "affine"
175
+ },
176
+ "model.layers.10.self_attn.o_proj": {
177
+ "bits": 5,
178
+ "group_size": 64,
179
+ "mode": "affine"
180
+ },
181
+ "model.layers.4.mlp.down_proj": {
182
+ "bits": 5,
183
+ "group_size": 64,
184
+ "mode": "affine"
185
+ },
186
+ "model.layers.5.mlp.down_proj": {
187
+ "bits": 5,
188
+ "group_size": 64,
189
+ "mode": "affine"
190
+ },
191
+ "model.layers.5.self_attn.o_proj": {
192
+ "bits": 5,
193
+ "group_size": 64,
194
+ "mode": "affine"
195
+ },
196
+ "model.layers.6.mlp.down_proj": {
197
+ "bits": 5,
198
+ "group_size": 64,
199
+ "mode": "affine"
200
+ },
201
+ "model.layers.6.self_attn.o_proj": {
202
+ "bits": 5,
203
+ "group_size": 64,
204
+ "mode": "affine"
205
+ },
206
+ "model.layers.7.mlp.down_proj": {
207
+ "bits": 5,
208
+ "group_size": 64,
209
+ "mode": "affine"
210
+ },
211
+ "model.layers.7.self_attn.o_proj": {
212
+ "bits": 5,
213
+ "group_size": 64,
214
+ "mode": "affine"
215
+ },
216
+ "model.layers.8.mlp.down_proj": {
217
+ "bits": 5,
218
+ "group_size": 64,
219
+ "mode": "affine"
220
+ },
221
+ "model.layers.8.self_attn.o_proj": {
222
+ "bits": 5,
223
+ "group_size": 64,
224
+ "mode": "affine"
225
+ },
226
+ "model.layers.9.mlp.down_proj": {
227
+ "bits": 5,
228
+ "group_size": 64,
229
+ "mode": "affine"
230
+ },
231
+ "model.layers.9.self_attn.o_proj": {
232
+ "bits": 5,
233
+ "group_size": 64,
234
+ "mode": "affine"
235
+ },
236
+ "model.layers.11.mlp.down_proj": {
237
+ "bits": 5,
238
+ "group_size": 64,
239
+ "mode": "affine"
240
+ },
241
+ "model.layers.11.self_attn.o_proj": {
242
+ "bits": 5,
243
+ "group_size": 64,
244
+ "mode": "affine"
245
+ },
246
+ "model.layers.12.mlp.down_proj": {
247
+ "bits": 5,
248
+ "group_size": 64,
249
+ "mode": "affine"
250
+ },
251
+ "model.layers.12.self_attn.o_proj": {
252
+ "bits": 5,
253
+ "group_size": 64,
254
+ "mode": "affine"
255
+ },
256
+ "model.layers.13.mlp.down_proj": {
257
+ "bits": 5,
258
+ "group_size": 64,
259
+ "mode": "affine"
260
+ },
261
+ "model.layers.13.self_attn.o_proj": {
262
+ "bits": 5,
263
+ "group_size": 64,
264
+ "mode": "affine"
265
+ },
266
+ "model.layers.14.mlp.down_proj": {
267
+ "bits": 5,
268
+ "group_size": 64,
269
+ "mode": "affine"
270
+ },
271
+ "model.layers.14.self_attn.o_proj": {
272
+ "bits": 5,
273
+ "group_size": 64,
274
+ "mode": "affine"
275
+ },
276
+ "model.layers.15.mlp.down_proj": {
277
+ "bits": 5,
278
+ "group_size": 64,
279
+ "mode": "affine"
280
+ },
281
+ "model.layers.15.self_attn.o_proj": {
282
+ "bits": 5,
283
+ "group_size": 64,
284
+ "mode": "affine"
285
+ },
286
+ "model.layers.16.mlp.down_proj": {
287
+ "bits": 5,
288
+ "group_size": 64,
289
+ "mode": "affine"
290
+ },
291
+ "model.layers.16.self_attn.o_proj": {
292
+ "bits": 5,
293
+ "group_size": 64,
294
+ "mode": "affine"
295
+ },
296
+ "model.layers.17.mlp.down_proj": {
297
+ "bits": 5,
298
+ "group_size": 64,
299
+ "mode": "affine"
300
+ },
301
+ "model.layers.17.self_attn.o_proj": {
302
+ "bits": 5,
303
+ "group_size": 64,
304
+ "mode": "affine"
305
+ },
306
+ "model.layers.18.mlp.down_proj": {
307
+ "bits": 5,
308
+ "group_size": 64,
309
+ "mode": "affine"
310
+ },
311
+ "model.layers.18.self_attn.o_proj": {
312
+ "bits": 5,
313
+ "group_size": 64,
314
+ "mode": "affine"
315
+ },
316
+ "model.layers.19.mlp.down_proj": {
317
+ "bits": 5,
318
+ "group_size": 64,
319
+ "mode": "affine"
320
+ },
321
+ "model.layers.19.self_attn.o_proj": {
322
+ "bits": 5,
323
+ "group_size": 64,
324
+ "mode": "affine"
325
+ },
326
+ "model.layers.20.mlp.down_proj": {
327
+ "bits": 5,
328
+ "group_size": 64,
329
+ "mode": "affine"
330
+ },
331
+ "model.layers.20.self_attn.o_proj": {
332
+ "bits": 5,
333
+ "group_size": 64,
334
+ "mode": "affine"
335
+ },
336
+ "model.layers.21.mlp.down_proj": {
337
+ "bits": 5,
338
+ "group_size": 64,
339
+ "mode": "affine"
340
+ },
341
+ "model.layers.21.self_attn.o_proj": {
342
+ "bits": 5,
343
+ "group_size": 64,
344
+ "mode": "affine"
345
+ },
346
+ "model.layers.22.mlp.down_proj": {
347
+ "bits": 5,
348
+ "group_size": 64,
349
+ "mode": "affine"
350
+ },
351
+ "model.layers.22.self_attn.o_proj": {
352
+ "bits": 5,
353
+ "group_size": 64,
354
+ "mode": "affine"
355
+ },
356
+ "model.layers.23.self_attn.k_proj": {
357
+ "bits": 5,
358
+ "group_size": 64,
359
+ "mode": "affine"
360
+ },
361
+ "model.layers.23.self_attn.o_proj": {
362
+ "bits": 5,
363
+ "group_size": 64,
364
+ "mode": "affine"
365
+ },
366
+ "model.layers.23.self_attn.q_proj": {
367
+ "bits": 5,
368
+ "group_size": 64,
369
+ "mode": "affine"
370
+ },
371
+ "model.layers.23.self_attn.v_proj": {
372
+ "bits": 6,
373
+ "group_size": 64,
374
+ "mode": "affine"
375
+ },
376
+ "model.layers.24.self_attn.k_proj": {
377
+ "bits": 5,
378
+ "group_size": 64,
379
+ "mode": "affine"
380
+ },
381
+ "model.layers.24.self_attn.o_proj": {
382
+ "bits": 5,
383
+ "group_size": 64,
384
+ "mode": "affine"
385
+ },
386
+ "model.layers.24.self_attn.q_proj": {
387
+ "bits": 5,
388
+ "group_size": 64,
389
+ "mode": "affine"
390
+ },
391
+ "model.layers.24.self_attn.v_proj": {
392
+ "bits": 6,
393
+ "group_size": 64,
394
+ "mode": "affine"
395
+ },
396
+ "model.layers.25.self_attn.k_proj": {
397
+ "bits": 5,
398
+ "group_size": 64,
399
+ "mode": "affine"
400
+ }
401
+ },
402
+ "quantization_config": {
403
+ "group_size": 64,
404
+ "bits": 4,
405
+ "mode": "affine",
406
+ "model.layers.0.mlp.down_proj": {
407
+ "bits": 6,
408
+ "group_size": 64,
409
+ "mode": "affine"
410
+ },
411
+ "model.layers.0.self_attn.k_proj": {
412
+ "bits": 5,
413
+ "group_size": 64,
414
+ "mode": "affine"
415
+ },
416
+ "model.layers.0.self_attn.o_proj": {
417
+ "bits": 5,
418
+ "group_size": 64,
419
+ "mode": "affine"
420
+ },
421
+ "model.layers.0.self_attn.q_proj": {
422
+ "bits": 5,
423
+ "group_size": 64,
424
+ "mode": "affine"
425
+ },
426
+ "model.layers.0.self_attn.v_proj": {
427
+ "bits": 6,
428
+ "group_size": 64,
429
+ "mode": "affine"
430
+ },
431
+ "model.layers.1.mlp.down_proj": {
432
+ "bits": 6,
433
+ "group_size": 64,
434
+ "mode": "affine"
435
+ },
436
+ "model.layers.1.self_attn.k_proj": {
437
+ "bits": 5,
438
+ "group_size": 64,
439
+ "mode": "affine"
440
+ },
441
+ "model.layers.1.self_attn.o_proj": {
442
+ "bits": 5,
443
+ "group_size": 64,
444
+ "mode": "affine"
445
+ },
446
+ "model.layers.1.self_attn.q_proj": {
447
+ "bits": 5,
448
+ "group_size": 64,
449
+ "mode": "affine"
450
+ },
451
+ "model.layers.1.self_attn.v_proj": {
452
+ "bits": 6,
453
+ "group_size": 64,
454
+ "mode": "affine"
455
+ },
456
+ "model.layers.2.mlp.down_proj": {
457
+ "bits": 5,
458
+ "group_size": 64,
459
+ "mode": "affine"
460
+ },
461
+ "model.layers.2.self_attn.o_proj": {
462
+ "bits": 5,
463
+ "group_size": 64,
464
+ "mode": "affine"
465
+ },
466
+ "model.layers.3.mlp.down_proj": {
467
+ "bits": 5,
468
+ "group_size": 64,
469
+ "mode": "affine"
470
+ },
471
+ "model.layers.3.self_attn.o_proj": {
472
+ "bits": 5,
473
+ "group_size": 64,
474
+ "mode": "affine"
475
+ },
476
+ "model.layers.4.self_attn.o_proj": {
477
+ "bits": 5,
478
+ "group_size": 64,
479
+ "mode": "affine"
480
+ },
481
+ "model.layers.10.mlp.down_proj": {
482
+ "bits": 5,
483
+ "group_size": 64,
484
+ "mode": "affine"
485
+ },
486
+ "model.layers.10.self_attn.o_proj": {
487
+ "bits": 5,
488
+ "group_size": 64,
489
+ "mode": "affine"
490
+ },
491
+ "model.layers.4.mlp.down_proj": {
492
+ "bits": 5,
493
+ "group_size": 64,
494
+ "mode": "affine"
495
+ },
496
+ "model.layers.5.mlp.down_proj": {
497
+ "bits": 5,
498
+ "group_size": 64,
499
+ "mode": "affine"
500
+ },
501
+ "model.layers.5.self_attn.o_proj": {
502
+ "bits": 5,
503
+ "group_size": 64,
504
+ "mode": "affine"
505
+ },
506
+ "model.layers.6.mlp.down_proj": {
507
+ "bits": 5,
508
+ "group_size": 64,
509
+ "mode": "affine"
510
+ },
511
+ "model.layers.6.self_attn.o_proj": {
512
+ "bits": 5,
513
+ "group_size": 64,
514
+ "mode": "affine"
515
+ },
516
+ "model.layers.7.mlp.down_proj": {
517
+ "bits": 5,
518
+ "group_size": 64,
519
+ "mode": "affine"
520
+ },
521
+ "model.layers.7.self_attn.o_proj": {
522
+ "bits": 5,
523
+ "group_size": 64,
524
+ "mode": "affine"
525
+ },
526
+ "model.layers.8.mlp.down_proj": {
527
+ "bits": 5,
528
+ "group_size": 64,
529
+ "mode": "affine"
530
+ },
531
+ "model.layers.8.self_attn.o_proj": {
532
+ "bits": 5,
533
+ "group_size": 64,
534
+ "mode": "affine"
535
+ },
536
+ "model.layers.9.mlp.down_proj": {
537
+ "bits": 5,
538
+ "group_size": 64,
539
+ "mode": "affine"
540
+ },
541
+ "model.layers.9.self_attn.o_proj": {
542
+ "bits": 5,
543
+ "group_size": 64,
544
+ "mode": "affine"
545
+ },
546
+ "model.layers.11.mlp.down_proj": {
547
+ "bits": 5,
548
+ "group_size": 64,
549
+ "mode": "affine"
550
+ },
551
+ "model.layers.11.self_attn.o_proj": {
552
+ "bits": 5,
553
+ "group_size": 64,
554
+ "mode": "affine"
555
+ },
556
+ "model.layers.12.mlp.down_proj": {
557
+ "bits": 5,
558
+ "group_size": 64,
559
+ "mode": "affine"
560
+ },
561
+ "model.layers.12.self_attn.o_proj": {
562
+ "bits": 5,
563
+ "group_size": 64,
564
+ "mode": "affine"
565
+ },
566
+ "model.layers.13.mlp.down_proj": {
567
+ "bits": 5,
568
+ "group_size": 64,
569
+ "mode": "affine"
570
+ },
571
+ "model.layers.13.self_attn.o_proj": {
572
+ "bits": 5,
573
+ "group_size": 64,
574
+ "mode": "affine"
575
+ },
576
+ "model.layers.14.mlp.down_proj": {
577
+ "bits": 5,
578
+ "group_size": 64,
579
+ "mode": "affine"
580
+ },
581
+ "model.layers.14.self_attn.o_proj": {
582
+ "bits": 5,
583
+ "group_size": 64,
584
+ "mode": "affine"
585
+ },
586
+ "model.layers.15.mlp.down_proj": {
587
+ "bits": 5,
588
+ "group_size": 64,
589
+ "mode": "affine"
590
+ },
591
+ "model.layers.15.self_attn.o_proj": {
592
+ "bits": 5,
593
+ "group_size": 64,
594
+ "mode": "affine"
595
+ },
596
+ "model.layers.16.mlp.down_proj": {
597
+ "bits": 5,
598
+ "group_size": 64,
599
+ "mode": "affine"
600
+ },
601
+ "model.layers.16.self_attn.o_proj": {
602
+ "bits": 5,
603
+ "group_size": 64,
604
+ "mode": "affine"
605
+ },
606
+ "model.layers.17.mlp.down_proj": {
607
+ "bits": 5,
608
+ "group_size": 64,
609
+ "mode": "affine"
610
+ },
611
+ "model.layers.17.self_attn.o_proj": {
612
+ "bits": 5,
613
+ "group_size": 64,
614
+ "mode": "affine"
615
+ },
616
+ "model.layers.18.mlp.down_proj": {
617
+ "bits": 5,
618
+ "group_size": 64,
619
+ "mode": "affine"
620
+ },
621
+ "model.layers.18.self_attn.o_proj": {
622
+ "bits": 5,
623
+ "group_size": 64,
624
+ "mode": "affine"
625
+ },
626
+ "model.layers.19.mlp.down_proj": {
627
+ "bits": 5,
628
+ "group_size": 64,
629
+ "mode": "affine"
630
+ },
631
+ "model.layers.19.self_attn.o_proj": {
632
+ "bits": 5,
633
+ "group_size": 64,
634
+ "mode": "affine"
635
+ },
636
+ "model.layers.20.mlp.down_proj": {
637
+ "bits": 5,
638
+ "group_size": 64,
639
+ "mode": "affine"
640
+ },
641
+ "model.layers.20.self_attn.o_proj": {
642
+ "bits": 5,
643
+ "group_size": 64,
644
+ "mode": "affine"
645
+ },
646
+ "model.layers.21.mlp.down_proj": {
647
+ "bits": 5,
648
+ "group_size": 64,
649
+ "mode": "affine"
650
+ },
651
+ "model.layers.21.self_attn.o_proj": {
652
+ "bits": 5,
653
+ "group_size": 64,
654
+ "mode": "affine"
655
+ },
656
+ "model.layers.22.mlp.down_proj": {
657
+ "bits": 5,
658
+ "group_size": 64,
659
+ "mode": "affine"
660
+ },
661
+ "model.layers.22.self_attn.o_proj": {
662
+ "bits": 5,
663
+ "group_size": 64,
664
+ "mode": "affine"
665
+ },
666
+ "model.layers.23.self_attn.k_proj": {
667
+ "bits": 5,
668
+ "group_size": 64,
669
+ "mode": "affine"
670
+ },
671
+ "model.layers.23.self_attn.o_proj": {
672
+ "bits": 5,
673
+ "group_size": 64,
674
+ "mode": "affine"
675
+ },
676
+ "model.layers.23.self_attn.q_proj": {
677
+ "bits": 5,
678
+ "group_size": 64,
679
+ "mode": "affine"
680
+ },
681
+ "model.layers.23.self_attn.v_proj": {
682
+ "bits": 6,
683
+ "group_size": 64,
684
+ "mode": "affine"
685
+ },
686
+ "model.layers.24.self_attn.k_proj": {
687
+ "bits": 5,
688
+ "group_size": 64,
689
+ "mode": "affine"
690
+ },
691
+ "model.layers.24.self_attn.o_proj": {
692
+ "bits": 5,
693
+ "group_size": 64,
694
+ "mode": "affine"
695
+ },
696
+ "model.layers.24.self_attn.q_proj": {
697
+ "bits": 5,
698
+ "group_size": 64,
699
+ "mode": "affine"
700
+ },
701
+ "model.layers.24.self_attn.v_proj": {
702
+ "bits": 6,
703
+ "group_size": 64,
704
+ "mode": "affine"
705
+ },
706
+ "model.layers.25.self_attn.k_proj": {
707
+ "bits": 5,
708
+ "group_size": 64,
709
+ "mode": "affine"
710
+ }
711
+ }
712
+ }
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"]
model-00001-of-PLACEHOLDER.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:39886a6724d9f346dbeb1b36c0f7349cf2f46a4f732ed658c9954ae16907484f
3
+ size 5287482670
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
+ ]
oq_imatrix_report.json ADDED
@@ -0,0 +1,364 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "enabled": true,
3
+ "cache_path": "/Users/hermit.dave/Projects/ml/models/.oqe_imatrix/K2-Horizon-7B-Uno-merged-bf16-oQe-s128-l512.npz",
4
+ "cache_reused": false,
5
+ "entry_count": 252,
6
+ "calib_dataset": "oqe_code_multilingual",
7
+ "collection": {
8
+ "dataset": "oqe_code_multilingual",
9
+ "requested_samples": 128,
10
+ "seq_length": 512,
11
+ "adaptive": true,
12
+ "adaptive_step_samples": 128,
13
+ "adaptive_max_samples": 1024,
14
+ "available_samples": 1024,
15
+ "micro_batch_size": 32,
16
+ "micro_batches": 4,
17
+ "batch_plan": {
18
+ "micro_batch_size": 32,
19
+ "estimated_sample_bytes": 8388608,
20
+ "capture_budget_bytes": 306620116,
21
+ "system_available_bytes": 35724574720,
22
+ "metal_available_bytes": 62272646860,
23
+ "live_available_bytes": 35724574720,
24
+ "model_bytes": 5062563118,
25
+ "remaining_available_bytes": 30662011602,
26
+ "fits_one_sample": true,
27
+ "hidden_size": 4096,
28
+ "num_experts": 0,
29
+ "top_k": 0,
30
+ "gemma4_state_bytes": 0,
31
+ "num_hidden_layers": 36,
32
+ "num_kv_shared_layers": 0,
33
+ "per_layer_input_size": 0
34
+ },
35
+ "processed_samples": 128,
36
+ "model_class": "k2_horizon.Model",
37
+ "layer_model_class": "k2_horizon.K2HorizonModel",
38
+ "layer_model_type": "k2_horizon",
39
+ "layer_count": 36,
40
+ "layer_state_kind": "generic",
41
+ "successful_layer_forwards": 144,
42
+ "skipped_layer_forwards": 0,
43
+ "mtp_head_forwards": 0,
44
+ "installed_modules": 253,
45
+ "capture_module_classes": {
46
+ "QuantizedLinear": 253
47
+ },
48
+ "switch_capture_modules": 0,
49
+ "requires_expert_counts": false,
50
+ "coverage_sufficient": true,
51
+ "collection_sufficient": true,
52
+ "coverage": {
53
+ "has_expert_counts": false,
54
+ "expert_modules": 0,
55
+ "total_experts": 0,
56
+ "active_experts": 0,
57
+ "zero_count_experts": 0,
58
+ "active_ratio": 1.0,
59
+ "min_count": 0,
60
+ "p05_count": 0.0,
61
+ "p10_count": 0.0,
62
+ "median_count": 0.0,
63
+ "max_count": 0,
64
+ "min_required_count": 16,
65
+ "required_percentile": 5
66
+ },
67
+ "rounds": [
68
+ {
69
+ "processed_samples": 128,
70
+ "coverage_sufficient": true,
71
+ "collection_sufficient": true,
72
+ "coverage": {
73
+ "has_expert_counts": false,
74
+ "expert_modules": 0,
75
+ "total_experts": 0,
76
+ "active_experts": 0,
77
+ "zero_count_experts": 0,
78
+ "active_ratio": 1.0,
79
+ "min_count": 0,
80
+ "p05_count": 0.0,
81
+ "p10_count": 0.0,
82
+ "median_count": 0.0,
83
+ "max_count": 0,
84
+ "min_required_count": 16,
85
+ "required_percentile": 5
86
+ }
87
+ }
88
+ ]
89
+ },
90
+ "expert_coverage": {
91
+ "has_expert_counts": false,
92
+ "expert_modules": 0,
93
+ "total_experts": 0,
94
+ "active_experts": 0,
95
+ "zero_count_experts": 0,
96
+ "active_ratio": 1.0,
97
+ "min_count": 0,
98
+ "p05_count": 0.0,
99
+ "p10_count": 0.0,
100
+ "median_count": 0.0,
101
+ "max_count": 0,
102
+ "min_required_count": 16,
103
+ "required_percentile": 5
104
+ },
105
+ "applied": [
106
+ "model.layers.0.mlp.down_proj",
107
+ "model.layers.0.mlp.gate_proj",
108
+ "model.layers.0.mlp.up_proj",
109
+ "model.layers.0.self_attn.k_proj",
110
+ "model.layers.0.self_attn.o_proj",
111
+ "model.layers.0.self_attn.q_proj",
112
+ "model.layers.0.self_attn.v_proj",
113
+ "model.layers.1.mlp.down_proj",
114
+ "model.layers.1.mlp.gate_proj",
115
+ "model.layers.1.mlp.up_proj",
116
+ "model.layers.1.self_attn.k_proj",
117
+ "model.layers.1.self_attn.o_proj",
118
+ "model.layers.1.self_attn.q_proj",
119
+ "model.layers.1.self_attn.v_proj",
120
+ "model.layers.10.mlp.down_proj",
121
+ "model.layers.10.mlp.gate_proj",
122
+ "model.layers.10.mlp.up_proj",
123
+ "model.layers.10.self_attn.k_proj",
124
+ "model.layers.10.self_attn.o_proj",
125
+ "model.layers.10.self_attn.q_proj",
126
+ "model.layers.10.self_attn.v_proj",
127
+ "model.layers.11.mlp.down_proj",
128
+ "model.layers.11.mlp.gate_proj",
129
+ "model.layers.11.mlp.up_proj",
130
+ "model.layers.11.self_attn.k_proj",
131
+ "model.layers.11.self_attn.o_proj",
132
+ "model.layers.11.self_attn.q_proj",
133
+ "model.layers.11.self_attn.v_proj",
134
+ "model.layers.12.mlp.down_proj",
135
+ "model.layers.12.mlp.gate_proj",
136
+ "model.layers.12.mlp.up_proj",
137
+ "model.layers.12.self_attn.k_proj",
138
+ "model.layers.12.self_attn.o_proj",
139
+ "model.layers.12.self_attn.q_proj",
140
+ "model.layers.12.self_attn.v_proj",
141
+ "model.layers.13.mlp.down_proj",
142
+ "model.layers.13.mlp.gate_proj",
143
+ "model.layers.13.mlp.up_proj",
144
+ "model.layers.13.self_attn.k_proj",
145
+ "model.layers.13.self_attn.o_proj",
146
+ "model.layers.13.self_attn.q_proj",
147
+ "model.layers.13.self_attn.v_proj",
148
+ "model.layers.14.mlp.down_proj",
149
+ "model.layers.14.mlp.gate_proj",
150
+ "model.layers.14.mlp.up_proj",
151
+ "model.layers.14.self_attn.k_proj",
152
+ "model.layers.14.self_attn.o_proj",
153
+ "model.layers.14.self_attn.q_proj",
154
+ "model.layers.14.self_attn.v_proj",
155
+ "model.layers.15.mlp.down_proj",
156
+ "model.layers.15.mlp.gate_proj",
157
+ "model.layers.15.mlp.up_proj",
158
+ "model.layers.15.self_attn.k_proj",
159
+ "model.layers.15.self_attn.o_proj",
160
+ "model.layers.15.self_attn.q_proj",
161
+ "model.layers.15.self_attn.v_proj",
162
+ "model.layers.16.mlp.down_proj",
163
+ "model.layers.16.mlp.gate_proj",
164
+ "model.layers.16.mlp.up_proj",
165
+ "model.layers.16.self_attn.k_proj",
166
+ "model.layers.16.self_attn.o_proj",
167
+ "model.layers.16.self_attn.q_proj",
168
+ "model.layers.16.self_attn.v_proj",
169
+ "model.layers.17.mlp.down_proj",
170
+ "model.layers.17.mlp.gate_proj",
171
+ "model.layers.17.mlp.up_proj",
172
+ "model.layers.17.self_attn.k_proj",
173
+ "model.layers.17.self_attn.o_proj",
174
+ "model.layers.17.self_attn.q_proj",
175
+ "model.layers.17.self_attn.v_proj",
176
+ "model.layers.18.mlp.down_proj",
177
+ "model.layers.18.mlp.gate_proj",
178
+ "model.layers.18.mlp.up_proj",
179
+ "model.layers.18.self_attn.k_proj",
180
+ "model.layers.18.self_attn.o_proj",
181
+ "model.layers.18.self_attn.q_proj",
182
+ "model.layers.18.self_attn.v_proj",
183
+ "model.layers.19.mlp.down_proj",
184
+ "model.layers.19.mlp.gate_proj",
185
+ "model.layers.19.mlp.up_proj",
186
+ "model.layers.19.self_attn.k_proj",
187
+ "model.layers.19.self_attn.o_proj",
188
+ "model.layers.19.self_attn.q_proj",
189
+ "model.layers.19.self_attn.v_proj",
190
+ "model.layers.2.mlp.down_proj",
191
+ "model.layers.2.mlp.gate_proj",
192
+ "model.layers.2.mlp.up_proj",
193
+ "model.layers.2.self_attn.k_proj",
194
+ "model.layers.2.self_attn.o_proj",
195
+ "model.layers.2.self_attn.q_proj",
196
+ "model.layers.2.self_attn.v_proj",
197
+ "model.layers.20.mlp.down_proj",
198
+ "model.layers.20.mlp.gate_proj",
199
+ "model.layers.20.mlp.up_proj",
200
+ "model.layers.20.self_attn.k_proj",
201
+ "model.layers.20.self_attn.o_proj",
202
+ "model.layers.20.self_attn.q_proj",
203
+ "model.layers.20.self_attn.v_proj",
204
+ "model.layers.21.mlp.down_proj",
205
+ "model.layers.21.mlp.gate_proj",
206
+ "model.layers.21.mlp.up_proj",
207
+ "model.layers.21.self_attn.k_proj",
208
+ "model.layers.21.self_attn.o_proj",
209
+ "model.layers.21.self_attn.q_proj",
210
+ "model.layers.21.self_attn.v_proj",
211
+ "model.layers.22.mlp.down_proj",
212
+ "model.layers.22.mlp.gate_proj",
213
+ "model.layers.22.mlp.up_proj",
214
+ "model.layers.22.self_attn.k_proj",
215
+ "model.layers.22.self_attn.o_proj",
216
+ "model.layers.22.self_attn.q_proj",
217
+ "model.layers.22.self_attn.v_proj",
218
+ "model.layers.23.mlp.down_proj",
219
+ "model.layers.23.mlp.gate_proj",
220
+ "model.layers.23.mlp.up_proj",
221
+ "model.layers.23.self_attn.k_proj",
222
+ "model.layers.23.self_attn.o_proj",
223
+ "model.layers.23.self_attn.q_proj",
224
+ "model.layers.23.self_attn.v_proj",
225
+ "model.layers.24.mlp.down_proj",
226
+ "model.layers.24.mlp.gate_proj",
227
+ "model.layers.24.mlp.up_proj",
228
+ "model.layers.24.self_attn.k_proj",
229
+ "model.layers.24.self_attn.o_proj",
230
+ "model.layers.24.self_attn.q_proj",
231
+ "model.layers.24.self_attn.v_proj",
232
+ "model.layers.25.mlp.down_proj",
233
+ "model.layers.25.mlp.gate_proj",
234
+ "model.layers.25.mlp.up_proj",
235
+ "model.layers.25.self_attn.k_proj",
236
+ "model.layers.25.self_attn.o_proj",
237
+ "model.layers.25.self_attn.q_proj",
238
+ "model.layers.25.self_attn.v_proj",
239
+ "model.layers.26.mlp.down_proj",
240
+ "model.layers.26.mlp.gate_proj",
241
+ "model.layers.26.mlp.up_proj",
242
+ "model.layers.26.self_attn.k_proj",
243
+ "model.layers.26.self_attn.o_proj",
244
+ "model.layers.26.self_attn.q_proj",
245
+ "model.layers.26.self_attn.v_proj",
246
+ "model.layers.27.mlp.down_proj",
247
+ "model.layers.27.mlp.gate_proj",
248
+ "model.layers.27.mlp.up_proj",
249
+ "model.layers.27.self_attn.k_proj",
250
+ "model.layers.27.self_attn.o_proj",
251
+ "model.layers.27.self_attn.q_proj",
252
+ "model.layers.27.self_attn.v_proj",
253
+ "model.layers.28.mlp.down_proj",
254
+ "model.layers.28.mlp.gate_proj",
255
+ "model.layers.28.mlp.up_proj",
256
+ "model.layers.28.self_attn.k_proj",
257
+ "model.layers.28.self_attn.o_proj",
258
+ "model.layers.28.self_attn.q_proj",
259
+ "model.layers.28.self_attn.v_proj",
260
+ "model.layers.29.mlp.down_proj",
261
+ "model.layers.29.mlp.gate_proj",
262
+ "model.layers.29.mlp.up_proj",
263
+ "model.layers.29.self_attn.k_proj",
264
+ "model.layers.29.self_attn.o_proj",
265
+ "model.layers.29.self_attn.q_proj",
266
+ "model.layers.29.self_attn.v_proj",
267
+ "model.layers.3.mlp.down_proj",
268
+ "model.layers.3.mlp.gate_proj",
269
+ "model.layers.3.mlp.up_proj",
270
+ "model.layers.3.self_attn.k_proj",
271
+ "model.layers.3.self_attn.o_proj",
272
+ "model.layers.3.self_attn.q_proj",
273
+ "model.layers.3.self_attn.v_proj",
274
+ "model.layers.30.mlp.down_proj",
275
+ "model.layers.30.mlp.gate_proj",
276
+ "model.layers.30.mlp.up_proj",
277
+ "model.layers.30.self_attn.k_proj",
278
+ "model.layers.30.self_attn.o_proj",
279
+ "model.layers.30.self_attn.q_proj",
280
+ "model.layers.30.self_attn.v_proj",
281
+ "model.layers.31.mlp.down_proj",
282
+ "model.layers.31.mlp.gate_proj",
283
+ "model.layers.31.mlp.up_proj",
284
+ "model.layers.31.self_attn.k_proj",
285
+ "model.layers.31.self_attn.o_proj",
286
+ "model.layers.31.self_attn.q_proj",
287
+ "model.layers.31.self_attn.v_proj",
288
+ "model.layers.32.mlp.down_proj",
289
+ "model.layers.32.mlp.gate_proj",
290
+ "model.layers.32.mlp.up_proj",
291
+ "model.layers.32.self_attn.k_proj",
292
+ "model.layers.32.self_attn.o_proj",
293
+ "model.layers.32.self_attn.q_proj",
294
+ "model.layers.32.self_attn.v_proj",
295
+ "model.layers.33.mlp.down_proj",
296
+ "model.layers.33.mlp.gate_proj",
297
+ "model.layers.33.mlp.up_proj",
298
+ "model.layers.33.self_attn.k_proj",
299
+ "model.layers.33.self_attn.o_proj",
300
+ "model.layers.33.self_attn.q_proj",
301
+ "model.layers.33.self_attn.v_proj",
302
+ "model.layers.34.mlp.down_proj",
303
+ "model.layers.34.mlp.gate_proj",
304
+ "model.layers.34.mlp.up_proj",
305
+ "model.layers.34.self_attn.k_proj",
306
+ "model.layers.34.self_attn.o_proj",
307
+ "model.layers.34.self_attn.q_proj",
308
+ "model.layers.34.self_attn.v_proj",
309
+ "model.layers.35.mlp.down_proj",
310
+ "model.layers.35.mlp.gate_proj",
311
+ "model.layers.35.mlp.up_proj",
312
+ "model.layers.35.self_attn.k_proj",
313
+ "model.layers.35.self_attn.o_proj",
314
+ "model.layers.35.self_attn.q_proj",
315
+ "model.layers.35.self_attn.v_proj",
316
+ "model.layers.4.mlp.down_proj",
317
+ "model.layers.4.mlp.gate_proj",
318
+ "model.layers.4.mlp.up_proj",
319
+ "model.layers.4.self_attn.k_proj",
320
+ "model.layers.4.self_attn.o_proj",
321
+ "model.layers.4.self_attn.q_proj",
322
+ "model.layers.4.self_attn.v_proj",
323
+ "model.layers.5.mlp.down_proj",
324
+ "model.layers.5.mlp.gate_proj",
325
+ "model.layers.5.mlp.up_proj",
326
+ "model.layers.5.self_attn.k_proj",
327
+ "model.layers.5.self_attn.o_proj",
328
+ "model.layers.5.self_attn.q_proj",
329
+ "model.layers.5.self_attn.v_proj",
330
+ "model.layers.6.mlp.down_proj",
331
+ "model.layers.6.mlp.gate_proj",
332
+ "model.layers.6.mlp.up_proj",
333
+ "model.layers.6.self_attn.k_proj",
334
+ "model.layers.6.self_attn.o_proj",
335
+ "model.layers.6.self_attn.q_proj",
336
+ "model.layers.6.self_attn.v_proj",
337
+ "model.layers.7.mlp.down_proj",
338
+ "model.layers.7.mlp.gate_proj",
339
+ "model.layers.7.mlp.up_proj",
340
+ "model.layers.7.self_attn.k_proj",
341
+ "model.layers.7.self_attn.o_proj",
342
+ "model.layers.7.self_attn.q_proj",
343
+ "model.layers.7.self_attn.v_proj",
344
+ "model.layers.8.mlp.down_proj",
345
+ "model.layers.8.mlp.gate_proj",
346
+ "model.layers.8.mlp.up_proj",
347
+ "model.layers.8.self_attn.k_proj",
348
+ "model.layers.8.self_attn.o_proj",
349
+ "model.layers.8.self_attn.q_proj",
350
+ "model.layers.8.self_attn.v_proj",
351
+ "model.layers.9.mlp.down_proj",
352
+ "model.layers.9.mlp.gate_proj",
353
+ "model.layers.9.mlp.up_proj",
354
+ "model.layers.9.self_attn.k_proj",
355
+ "model.layers.9.self_attn.o_proj",
356
+ "model.layers.9.self_attn.q_proj",
357
+ "model.layers.9.self_attn.v_proj"
358
+ ],
359
+ "missing": [
360
+ "lm_head"
361
+ ],
362
+ "mismatched": [],
363
+ "zero_count_experts": 0
364
+ }
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
+ }