cpatonn commited on
Commit
fafd8e9
·
0 Parent(s):

Super-squash branch 'main' using huggingface_hub

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +37 -0
  2. .ipynb_checkpoints/config-checkpoint.json +294 -0
  3. README.md +372 -0
  4. added_tokens.json +28 -0
  5. chat_template.jinja +143 -0
  6. config.json +294 -0
  7. configuration_mimo_v2_flash.py +109 -0
  8. generation_config.json +4 -0
  9. merges.txt +0 -0
  10. model-00001-of-00036.safetensors +3 -0
  11. model-00002-of-00036.safetensors +3 -0
  12. model-00003-of-00036.safetensors +3 -0
  13. model-00004-of-00036.safetensors +3 -0
  14. model-00005-of-00036.safetensors +3 -0
  15. model-00006-of-00036.safetensors +3 -0
  16. model-00007-of-00036.safetensors +3 -0
  17. model-00008-of-00036.safetensors +3 -0
  18. model-00009-of-00036.safetensors +3 -0
  19. model-00010-of-00036.safetensors +3 -0
  20. model-00011-of-00036.safetensors +3 -0
  21. model-00012-of-00036.safetensors +3 -0
  22. model-00013-of-00036.safetensors +3 -0
  23. model-00014-of-00036.safetensors +3 -0
  24. model-00015-of-00036.safetensors +3 -0
  25. model-00016-of-00036.safetensors +3 -0
  26. model-00017-of-00036.safetensors +3 -0
  27. model-00018-of-00036.safetensors +3 -0
  28. model-00019-of-00036.safetensors +3 -0
  29. model-00020-of-00036.safetensors +3 -0
  30. model-00021-of-00036.safetensors +3 -0
  31. model-00022-of-00036.safetensors +3 -0
  32. model-00023-of-00036.safetensors +3 -0
  33. model-00024-of-00036.safetensors +3 -0
  34. model-00025-of-00036.safetensors +3 -0
  35. model-00026-of-00036.safetensors +3 -0
  36. model-00027-of-00036.safetensors +3 -0
  37. model-00028-of-00036.safetensors +3 -0
  38. model-00029-of-00036.safetensors +3 -0
  39. model-00030-of-00036.safetensors +3 -0
  40. model-00031-of-00036.safetensors +3 -0
  41. model-00032-of-00036.safetensors +3 -0
  42. model-00033-of-00036.safetensors +3 -0
  43. model-00034-of-00036.safetensors +3 -0
  44. model-00035-of-00036.safetensors +3 -0
  45. model-00036-of-00036.safetensors +3 -0
  46. model.safetensors.index.json +3 -0
  47. modeling_mimo_v2_flash.py +663 -0
  48. recipe.yaml +35 -0
  49. special_tokens_map.json +31 -0
  50. tokenizer.json +3 -0
.gitattributes ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
5
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
6
+ *.ftz filter=lfs diff=lfs merge=lfs -text
7
+ *.gz filter=lfs diff=lfs merge=lfs -text
8
+ *.h5 filter=lfs diff=lfs merge=lfs -text
9
+ *.joblib filter=lfs diff=lfs merge=lfs -text
10
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
+ *.model filter=lfs diff=lfs merge=lfs -text
13
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
14
+ *.npy filter=lfs diff=lfs merge=lfs -text
15
+ *.npz filter=lfs diff=lfs merge=lfs -text
16
+ *.onnx filter=lfs diff=lfs merge=lfs -text
17
+ *.ot filter=lfs diff=lfs merge=lfs -text
18
+ *.parquet filter=lfs diff=lfs merge=lfs -text
19
+ *.pb filter=lfs diff=lfs merge=lfs -text
20
+ *.pickle filter=lfs diff=lfs merge=lfs -text
21
+ *.pkl filter=lfs diff=lfs merge=lfs -text
22
+ *.pt filter=lfs diff=lfs merge=lfs -text
23
+ *.pth filter=lfs diff=lfs merge=lfs -text
24
+ *.rar filter=lfs diff=lfs merge=lfs -text
25
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
26
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
28
+ *.tar filter=lfs diff=lfs merge=lfs -text
29
+ *.tflite filter=lfs diff=lfs merge=lfs -text
30
+ *.tgz filter=lfs diff=lfs merge=lfs -text
31
+ *.wasm filter=lfs diff=lfs merge=lfs -text
32
+ *.xz filter=lfs diff=lfs merge=lfs -text
33
+ *.zip filter=lfs diff=lfs merge=lfs -text
34
+ *.zst filter=lfs diff=lfs merge=lfs -text
35
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ tokenizer.json filter=lfs diff=lfs merge=lfs -text
37
+ model.safetensors.index.json filter=lfs diff=lfs merge=lfs -text
.ipynb_checkpoints/config-checkpoint.json ADDED
@@ -0,0 +1,294 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_full_attention_sink_bias": false,
3
+ "add_swa_attention_sink_bias": true,
4
+ "architectures": [
5
+ "MiMoV2FlashForCausalLM"
6
+ ],
7
+ "attention_bias": false,
8
+ "attention_chunk_size": 128,
9
+ "attention_dropout": 0.0,
10
+ "attention_value_scale": 0.707,
11
+ "auto_map": {
12
+ "AutoConfig": "configuration_mimo_v2_flash.MiMoV2FlashConfig",
13
+ "AutoModel": "modeling_mimo_v2_flash.MiMoV2Model",
14
+ "AutoModelForCausalLM": "modeling_mimo_v2_flash.MiMoV2FlashForCausalLM"
15
+ },
16
+ "dtype": "bfloat16",
17
+ "head_dim": 192,
18
+ "hidden_act": "silu",
19
+ "hidden_size": 4096,
20
+ "hybrid_block_size": null,
21
+ "hybrid_layer_pattern": [
22
+ 0,
23
+ 1,
24
+ 1,
25
+ 1,
26
+ 1,
27
+ 0,
28
+ 1,
29
+ 1,
30
+ 1,
31
+ 1,
32
+ 1,
33
+ 0,
34
+ 1,
35
+ 1,
36
+ 1,
37
+ 1,
38
+ 1,
39
+ 0,
40
+ 1,
41
+ 1,
42
+ 1,
43
+ 1,
44
+ 1,
45
+ 0,
46
+ 1,
47
+ 1,
48
+ 1,
49
+ 1,
50
+ 1,
51
+ 0,
52
+ 1,
53
+ 1,
54
+ 1,
55
+ 1,
56
+ 1,
57
+ 0,
58
+ 1,
59
+ 1,
60
+ 1,
61
+ 1,
62
+ 1,
63
+ 0,
64
+ 1,
65
+ 1,
66
+ 1,
67
+ 1,
68
+ 1,
69
+ 0
70
+ ],
71
+ "initializer_range": 0.02,
72
+ "intermediate_size": 16384,
73
+ "layer_types": [
74
+ "full_attention",
75
+ "sliding_attention",
76
+ "sliding_attention",
77
+ "sliding_attention",
78
+ "sliding_attention",
79
+ "full_attention",
80
+ "sliding_attention",
81
+ "sliding_attention",
82
+ "sliding_attention",
83
+ "sliding_attention",
84
+ "sliding_attention",
85
+ "full_attention",
86
+ "sliding_attention",
87
+ "sliding_attention",
88
+ "sliding_attention",
89
+ "sliding_attention",
90
+ "sliding_attention",
91
+ "full_attention",
92
+ "sliding_attention",
93
+ "sliding_attention",
94
+ "sliding_attention",
95
+ "sliding_attention",
96
+ "sliding_attention",
97
+ "full_attention",
98
+ "sliding_attention",
99
+ "sliding_attention",
100
+ "sliding_attention",
101
+ "sliding_attention",
102
+ "sliding_attention",
103
+ "full_attention",
104
+ "sliding_attention",
105
+ "sliding_attention",
106
+ "sliding_attention",
107
+ "sliding_attention",
108
+ "sliding_attention",
109
+ "full_attention",
110
+ "sliding_attention",
111
+ "sliding_attention",
112
+ "sliding_attention",
113
+ "sliding_attention",
114
+ "sliding_attention",
115
+ "full_attention",
116
+ "sliding_attention",
117
+ "sliding_attention",
118
+ "sliding_attention",
119
+ "sliding_attention",
120
+ "sliding_attention",
121
+ "full_attention"
122
+ ],
123
+ "layernorm_epsilon": 1e-05,
124
+ "max_position_embeddings": 262144,
125
+ "moe_intermediate_size": 2048,
126
+ "moe_layer_freq": [
127
+ 0,
128
+ 1,
129
+ 1,
130
+ 1,
131
+ 1,
132
+ 1,
133
+ 1,
134
+ 1,
135
+ 1,
136
+ 1,
137
+ 1,
138
+ 1,
139
+ 1,
140
+ 1,
141
+ 1,
142
+ 1,
143
+ 1,
144
+ 1,
145
+ 1,
146
+ 1,
147
+ 1,
148
+ 1,
149
+ 1,
150
+ 1,
151
+ 1,
152
+ 1,
153
+ 1,
154
+ 1,
155
+ 1,
156
+ 1,
157
+ 1,
158
+ 1,
159
+ 1,
160
+ 1,
161
+ 1,
162
+ 1,
163
+ 1,
164
+ 1,
165
+ 1,
166
+ 1,
167
+ 1,
168
+ 1,
169
+ 1,
170
+ 1,
171
+ 1,
172
+ 1,
173
+ 1,
174
+ 1
175
+ ],
176
+ "n_group": 1,
177
+ "n_routed_experts": 256,
178
+ "n_shared_experts": null,
179
+ "norm_topk_prob": true,
180
+ "num_attention_heads": 64,
181
+ "num_experts_per_tok": 8,
182
+ "num_hidden_layers": 48,
183
+ "num_key_value_heads": 4,
184
+ "partial_rotary_factor": 0.334,
185
+ "quantization_config": {
186
+ "config_groups": {
187
+ "group_0": {
188
+ "format": "pack-quantized",
189
+ "input_activations": null,
190
+ "output_activations": null,
191
+ "targets": [
192
+ "Linear"
193
+ ],
194
+ "weights": {
195
+ "actorder": null,
196
+ "block_structure": null,
197
+ "dynamic": false,
198
+ "group_size": 32,
199
+ "num_bits": 4,
200
+ "observer": "minmax",
201
+ "observer_kwargs": {},
202
+ "strategy": "group",
203
+ "symmetric": true,
204
+ "type": "int"
205
+ }
206
+ }
207
+ },
208
+ "format": "pack-quantized",
209
+ "global_compression_ratio": null,
210
+ "ignore": [
211
+ "model.layers.0.self_attn.q_proj",
212
+ "model.layers.0.self_attn.k_proj",
213
+ "model.layers.0.self_attn.v_proj",
214
+ "model.layers.0.self_attn.o_proj",
215
+ "model.layers.0.self_attn.qkv_proj",
216
+ "model.layers.0.mlp.gate_up_proj",
217
+ "model.layers.0.mlp.gate_proj",
218
+ "model.layers.0.mlp.up_proj",
219
+ "model.layers.0.mlp.down_proj",
220
+ "model.layers.1.self_attn.o_proj",
221
+ "model.layers.2.self_attn.o_proj",
222
+ "model.layers.3.self_attn.o_proj",
223
+ "model.layers.4.self_attn.o_proj",
224
+ "model.layers.5.self_attn.o_proj",
225
+ "model.layers.6.self_attn.o_proj",
226
+ "model.layers.7.self_attn.o_proj",
227
+ "model.layers.8.self_attn.o_proj",
228
+ "model.layers.9.self_attn.o_proj",
229
+ "model.layers.10.self_attn.o_proj",
230
+ "model.layers.11.self_attn.o_proj",
231
+ "model.layers.12.self_attn.o_proj",
232
+ "model.layers.13.self_attn.o_proj",
233
+ "model.layers.14.self_attn.o_proj",
234
+ "model.layers.15.self_attn.o_proj",
235
+ "model.layers.16.self_attn.o_proj",
236
+ "model.layers.17.self_attn.o_proj",
237
+ "model.layers.18.self_attn.o_proj",
238
+ "model.layers.19.self_attn.o_proj",
239
+ "model.layers.20.self_attn.o_proj",
240
+ "model.layers.21.self_attn.o_proj",
241
+ "model.layers.22.self_attn.o_proj",
242
+ "model.layers.23.self_attn.o_proj",
243
+ "model.layers.24.self_attn.o_proj",
244
+ "model.layers.25.self_attn.o_proj",
245
+ "model.layers.26.self_attn.o_proj",
246
+ "model.layers.27.self_attn.o_proj",
247
+ "model.layers.28.self_attn.o_proj",
248
+ "model.layers.29.self_attn.o_proj",
249
+ "model.layers.30.self_attn.o_proj",
250
+ "model.layers.31.self_attn.o_proj",
251
+ "model.layers.32.self_attn.o_proj",
252
+ "model.layers.33.self_attn.o_proj",
253
+ "model.layers.34.self_attn.o_proj",
254
+ "model.layers.35.self_attn.o_proj",
255
+ "model.layers.36.self_attn.o_proj",
256
+ "model.layers.37.self_attn.o_proj",
257
+ "model.layers.38.self_attn.o_proj",
258
+ "model.layers.39.self_attn.o_proj",
259
+ "model.layers.40.self_attn.o_proj",
260
+ "model.layers.41.self_attn.o_proj",
261
+ "model.layers.42.self_attn.o_proj",
262
+ "model.layers.43.self_attn.o_proj",
263
+ "model.layers.44.self_attn.o_proj",
264
+ "model.layers.45.self_attn.o_proj",
265
+ "model.layers.46.self_attn.o_proj",
266
+ "model.layers.47.self_attn.o_proj",
267
+ "lm_head"
268
+ ],
269
+ "kv_cache_scheme": null,
270
+ "quant_method": "compressed-tensors",
271
+ "quantization_status": "compressed",
272
+ "sparsity_config": {},
273
+ "transform_config": {},
274
+ "version": "0.13.1.a20251215"
275
+ },
276
+ "rope_scaling": null,
277
+ "rope_theta": 10000,
278
+ "routed_scaling_factor": null,
279
+ "scoring_func": "sigmoid",
280
+ "sliding_window": 128,
281
+ "sliding_window_size": 128,
282
+ "swa_head_dim": 192,
283
+ "swa_num_attention_heads": 64,
284
+ "swa_num_key_value_heads": 8,
285
+ "swa_rope_theta": 10000,
286
+ "swa_v_head_dim": 128,
287
+ "tie_word_embeddings": false,
288
+ "topk_group": 1,
289
+ "topk_method": "noaux_tc",
290
+ "transformers_version": "4.57.3",
291
+ "use_cache": true,
292
+ "v_head_dim": 128,
293
+ "vocab_size": 152576
294
+ }
README.md ADDED
@@ -0,0 +1,372 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: mit
3
+ library_name: transformers
4
+ base_model: XiaomiMiMo/MiMo-V2-Flash
5
+ ---
6
+
7
+ # MiMo-V2-Flash AWQ - INT4
8
+
9
+ ## Model Details
10
+
11
+ ### Quantization Details
12
+
13
+ - **Quantization Method:** cyankiwi AWQ v1.0
14
+ - **Bits:** 4
15
+ - **Group Size:** 32
16
+ - **Calibration Dataset:** [nvidia/Llama-Nemotron-Post-Training-Dataset](https://huggingface.co/datasets/nvidia/Llama-Nemotron-Post-Training-Dataset)
17
+ - **Quantization Tool:** [llm-compressor](https://github.com/vllm-project/llm-compressor)
18
+
19
+ ### Memory Usage
20
+
21
+ | **Type** | **MiMo-V2-Flash** | **MiMo-V2-Flash-AWQ-4bit** |
22
+ |:---------------:|:----------------:|:----------------:|
23
+ | **Memory Size** | 291.6 GB | 166.0 GB |
24
+
25
+ ## Inference
26
+
27
+ ### Prerequisite
28
+
29
+ ```bash
30
+ git clone https://github.com/sgl-project/sglang.git
31
+ cd sglang
32
+ git fetch origin pull/15207/head:pr-15207
33
+ git checkout pr-15207
34
+ pip install -e "python"
35
+ ```
36
+
37
+ ### Basic Usage
38
+
39
+ ```bash
40
+ python3 -m sglang.launch_server \
41
+ --model-path cyankiwi/MiMo-V2-Flash-AWQ-4bit \
42
+ --trust-remote-code \
43
+ --reasoning-parser qwen3 \
44
+ --tool-call-parser mimo
45
+ ```
46
+
47
+ ## Additional Information
48
+
49
+ ### Known Issues
50
+
51
+ - No MTP implementation
52
+
53
+ ### Changelog
54
+
55
+ - **v0.9.0** - Initial quantized release without MTP implementation
56
+
57
+ ### Authors
58
+
59
+ - **Name:** Ton Cao
60
+ - **Contacts:** ton@cyan.kiwi
61
+
62
+ <br/><br/>
63
+
64
+ <div align="center">
65
+ <picture>
66
+ <source srcset="https://github.com/XiaomiMiMo/MiMo-V2-Flash/raw/main/figures/Xiaomi_MiMo_darkmode.png?raw=true" media="(prefers-color-scheme: dark)">
67
+ <img src="https://github.com/XiaomiMiMo/MiMo-V2-Flash/raw/main/figures/Xiaomi_MiMo.png?raw=true" width="60%" alt="Xiaomi-MiMo" />
68
+ </picture>
69
+ </div>
70
+
71
+ <br/>
72
+
73
+ <div align="center" style="line-height: 1;">
74
+ |
75
+ <a href="https://huggingface.co/XiaomiMiMo/MiMo-V2-Flash" target="_blank">🤗 HuggingFace</a>
76
+ &nbsp;|
77
+ <a href="https://github.com/XiaomiMiMo/MiMo-V2-Flash/blob/main/paper.pdf" target="_blank">📔 Technical Report </a>
78
+ &nbsp;|
79
+ <a href="https://mimo.xiaomi.com/blog/mimo-v2-flash" target="_blank">📰 Blog </a>
80
+ &nbsp;|
81
+ <br/><br/>
82
+ <strong>Play around!</strong> &nbsp;
83
+ <a href="https://aistudio.xiaomimimo.com" target="_blank">🗨️ Xiaomi MiMo Studio </a>
84
+ &nbsp;
85
+ <a href="https://platform.xiaomimimo.com/" target="_blank">🎨 Xiaomi MiMo API Platform </a>
86
+ </div>
87
+ <br/>
88
+
89
+ # MiMo-V2-Flash
90
+
91
+ **MiMo-V2-Flash** is a Mixture-of-Experts (MoE) language model with **309B total parameters** and **15B active parameters**. Designed for high-speed reasoning and agentic workflows, it utilizes a novel hybrid attention architecture and Multi-Token Prediction (MTP) to achieve state-of-the-art performance while significantly reducing inference costs.
92
+
93
+ <p align="center">
94
+ <img width="80%" src="https://github.com/XiaomiMiMo/MiMo-V2-Flash/raw/main/figures/MiMo-v2-flash-performance.jpg?raw=true">
95
+ </p>
96
+
97
+ -----
98
+
99
+ ## 1. Introduction
100
+
101
+ MiMo-V2-Flash creates a new balance between long-context modeling capability and inference efficiency. Key features include:
102
+
103
+ * **Hybrid Attention Architecture**: Interleaves Sliding Window Attention (SWA) and Global Attention (GA) with a 5:1 ratio and an aggressive 128-token window. This reduces KV-cache storage by nearly 6x while maintaining long-context performance via learnable **attention sink bias**.
104
+ * **Multi-Token Prediction (MTP)**: Equipped with a lightweight MTP module (0.33B params/block) using dense FFNs. This triples output speed during inference and will be good to accelerates rollout in RL training.
105
+ * **Efficient Pre-Training**: Trained on 27T tokens using FP8 mixed precision and native 32k seq length. The context window supports up to 256k length.
106
+ * **Agentic Capabilities**: Post-training utilizes Multi-Teacher On-Policy Distillation (MOPD) and large-scale agentic RL, achieving superior performance on **SWE-Bench** and complex reasoning tasks.
107
+
108
+ -----
109
+
110
+ ## 2. Model Downloads
111
+
112
+ | Model | Total Params | Active Params | Context Length | Download |
113
+ | :--------------------- | :----------: | :-----------: | :------------: | :-------------------------------------------------------------------: |
114
+ | **MiMo-V2-Flash-Base** | 309B | 15B | 256k | [🤗 HuggingFace](https://huggingface.co/XiaomiMiMo/MiMo-V2-Flash-Base) |
115
+ | **MiMo-V2-Flash** | 309B | 15B | 256k | [🤗 HuggingFace](https://huggingface.co/XiaomiMiMo/MiMo-V2-Flash) |
116
+
117
+ > [!IMPORTANT]
118
+ > We also open-source the 3-layer MTP weights to foster community research.
119
+
120
+ -----
121
+
122
+ ## 3. Evaluation Results
123
+
124
+ ### Base Model Evaluation
125
+
126
+ MiMo-V2-Flash-Base demonstrates strong performance across standard benchmarks, surpassing models with significantly larger parameter counts.
127
+
128
+ | Category | Benchmark | Setting/Length | MiMo-V2-Flash Base | Kimi-K2 Base | DeepSeek-V3.1 Base | DeepSeek-V3.2 Exp Base |
129
+ | :--------------- | :---------------------- | :------------- | :----------------: | :-------------: | :----------------: | :--------------------: |
130
+ | **Params** | **#Activated / #Total** | - | **15B / 309B** | **32B / 1043B** | **37B / 671B** | **37B / 671B** |
131
+ | **General** | BBH | 3-shot | 88.5 | 88.7 | 88.2 | 88.7 |
132
+ | | MMLU | 5-shot | 86.7 | 87.8 | 87.4 | 87.8 |
133
+ | | MMLU-Redux | 5-shot | 90.6 | 90.2 | 90.0 | 90.4 |
134
+ | | MMLU-Pro | 5-shot | 73.2 | 69.2 | 58.8 | 62.1 |
135
+ | | DROP | 3-shot | 84.7 | 83.6 | 86.3 | 86.6 |
136
+ | | ARC-Challenge | 25-shot | 95.9 | 96.2 | 95.6 | 95.5 |
137
+ | | HellaSwag | 10-shot | 88.5 | 94.6 | 89.2 | 89.4 |
138
+ | | WinoGrande | 5-shot | 83.8 | 85.3 | 85.9 | 85.6 |
139
+ | | TriviaQA | 5-shot | 80.3 | 85.1 | 83.5 | 83.9 |
140
+ | | GPQA-Diamond | 5-shot | 55.1 | 48.1 | 51.0 | 52.0 |
141
+ | | SuperGPQA | 5-shot | 41.1 | 44.7 | 42.3 | 43.6 |
142
+ | | SimpleQA | 5-shot | 20.6 | 35.3 | 26.3 | 27.0 |
143
+ | **Math** | GSM8K | 8-shot | 92.3 | 92.1 | 91.4 | 91.1 |
144
+ | | MATH | 4-shot | 71.0 | 70.2 | 62.6 | 62.5 |
145
+ | | AIME 24&25 | 2-shot | 35.3 | 31.6 | 21.6 | 24.8 |
146
+ | **Code** | HumanEval+ | 1-shot | 70.7 | 84.8 | 64.6 | 67.7 |
147
+ | | MBPP+ | 3-shot | 71.4 | 73.8 | 72.2 | 69.8 |
148
+ | | CRUXEval-I | 1-shot | 67.5 | 74.0 | 62.1 | 63.9 |
149
+ | | CRUXEval-O | 1-shot | 79.1 | 83.5 | 76.4 | 74.9 |
150
+ | | MultiPL-E HumanEval | 0-shot | 59.5 | 60.5 | 45.9 | 45.7 |
151
+ | | MultiPL-E MBPP | 0-shot | 56.7 | 58.8 | 52.5 | 50.6 |
152
+ | | BigCodeBench | 0-shot | 70.1 | 61.7 | 63.0 | 62.9 |
153
+ | | LiveCodeBench v6 | 1-shot | 30.8 | 26.3 | 24.8 | 24.9 |
154
+ | | SWE-Bench (AgentLess) | 3-shot | 30.8 | 28.2 | 24.8 | 9.4* |
155
+ | **Chinese** | C-Eval | 5-shot | 87.9 | 92.5 | 90.0 | 91.0 |
156
+ | | CMMLU | 5-shot | 87.4 | 90.9 | 88.8 | 88.9 |
157
+ | | C-SimpleQA | 5-shot | 61.5 | 77.6 | 70.9 | 68.0 |
158
+ | **Multilingual** | GlobalMMLU | 5-shot | 76.6 | 80.7 | 81.9 | 82.0 |
159
+ | | INCLUDE | 5-shot | 71.4 | 75.3 | 77.2 | 77.2 |
160
+ | **Long Context** | NIAH-Multi | 32K | 99.3 | 99.8 | 99.7 | 85.6* |
161
+ | | | 64K | 99.9 | 100.0 | 98.6 | 85.9* |
162
+ | | | 128K | 98.6 | 99.5 | 97.2 | 94.3* |
163
+ | | | 256K | 96.7 | - | - | - |
164
+ | | GSM-Infinite Hard | 16K | 37.7 | 34.6 | 41.5 | 50.4 |
165
+ | | | 32K | 33.7 | 26.1 | 38.8 | 45.2 |
166
+ | | | 64K | 31.5 | 16.0 | 34.7 | 32.6 |
167
+ | | | 128K | 29.0 | 8.8 | 28.7 | 25.7 |
168
+
169
+ > \* indicates the model may fail to follow the prompt or format.
170
+
171
+ ### Post-training Model Evaluation
172
+
173
+ Following our Post-Training Paradigm with MOPD and Agentic RL, the model achieves SOTA reasoning and agentic performance.
174
+
175
+
176
+
177
+ | Benchmark | MiMo-V2 Flash | Kimi-K2 Thinking | DeepSeek-V3.2 Thinking | Gemini-3.0 Pro | Claude Sonnet 4.5 | GPT-5 High |
178
+ | :----------------------------- | :-----------: | :--------------: | :--------------------: | :------------: | :---------------: | :--------: |
179
+ | **Reasoning** | | | | | | |
180
+ | MMLU-Pro | 84.9 | 84.6 | 85.0 | 90.1 | 88.2 | 87.5 |
181
+ | GPQA-Diamond | 83.7 | 84.5 | 82.4 | 91.9 | 83.4 | 85.7 |
182
+ | HLE (no tools) | 22.1 | 23.9 | 25.1 | 37.5 | 13.7 | 26.3 |
183
+ | AIME 2025 | 94.1 | 94.5 | 93.1 | 95.0 | 87.0 | 94.6 |
184
+ | HMMT Feb. 2025 | 84.4 | 89.4 | 92.5 | 97.5 | 79.2 | 88.3 |
185
+ | LiveCodeBench-v6 | 80.6 | 83.1 | 83.3 | 90.7 | 64.0 | 84.5 |
186
+ | **General Writing** | | | | | | |
187
+ | Arena-Hard (Hard Prompt) | 54.1 | 71.9 | 53.4 | 72.6 | 63.3 | 71.9 |
188
+ | Arena-Hard (Creative Writing) | 86.2 | 80.1 | 88.8 | 93.6 | 76.7 | 92.2 |
189
+ | **Long Context** | | | | | | |
190
+ | LongBench V2 | 60.6 | 45.1 | 58.4 | 65.6 | 61.8 | - |
191
+ | MRCR | 45.7 | 44.2 | 55.5 | 89.7 | 55.4 | - |
192
+ | **Code Agent** | | | | | | |
193
+ | SWE-Bench Verified | 73.4 | 71.3 | 73.1 | 76.2 | 77.2 | 74.9 |
194
+ | SWE-Bench Multilingual | 71.7 | 61.1 | 70.2 | - | 68.0 | 55.3 |
195
+ | Terminal-Bench Hard | 30.5 | 30.6 | 35.4 | 39.0 | 33.3 | 30.5 |
196
+ | Terminal-Bench 2.0 | 38.5 | 35.7 | 46.4 | 54.2 | 42.8 | 35.2 |
197
+ | **General Agent** | | | | | | |
198
+ | BrowseComp | 45.4 | - | 51.4 | - | 24.1 | 54.9 |
199
+ | BrowseComp (w/ Context Manage) | 58.3 | 60.2 | 67.6 | 59.2 | - | - |
200
+ | \\(\tau^2\\)-Bench | 80.3 | 74.3 | 80.3 | 85.4 | 84.7 | 80.2 |
201
+
202
+ -----
203
+
204
+ ## 4. Model Architecture
205
+
206
+ <p align="center">
207
+ <img width="80%" src="https://github.com/XiaomiMiMo/MiMo-V2-Flash/raw/main/figures/MiMo-v2-flash-arch.png?raw=true">
208
+ </p>
209
+
210
+ ### Hybrid Sliding Window Attention
211
+
212
+ MiMo-V2-Flash addresses the quadratic complexity of long contexts by interleaving Local Sliding Window Attention (SWA) and Global Attention (GA).
213
+
214
+ * **Configuration**: Stacks of \\(M=8\\) hybrid blocks. Each block contains \\(N=5\\) SWA layers followed by 1 GA layer.
215
+ * **Efficiency**: SWA layers use a window size of 128 tokens, reducing KV cache significantly.
216
+ * **Sink Bias**: Learnable attention sink bias is applied to maintain performance despite the aggressive window size.
217
+
218
+ ### Lightweight Multi-Token Prediction (MTP)
219
+
220
+ Unlike traditional speculative decoding, our MTP module is natively integrated for training and inference.
221
+
222
+ * **Structure**: Uses a dense FFN (instead of MoE) and SWA (instead of GA) to keep the parameter count low (0.33B per block).
223
+ * **Performance**: Facilitates self-speculative decoding, tripling generation speed and mitigating GPU idleness during small-batch RL training.
224
+
225
+ -----
226
+
227
+ ## 5. Post-Training Technical Highlights
228
+
229
+ MiMo-V2-Flash leverages a post-training pipeline designed to maximize reasoning and agentic capabilities through innovative distillation and reinforcement learning strategies.
230
+
231
+ ### 5.1 Multi-Teacher On-Policy Distillation (MOPD)
232
+
233
+ We introduce **Multi-Teacher On-Policy Distillation (MOPD)**, a new paradigm that formulates knowledge distillation as a reinforcement learning process.
234
+ * **Dense Token-Level Guidance**: Unlike methods relying on sparse sequence-level feedback, MOPD utilizes domain-specific expert models (teachers) to provide supervision at every token position.
235
+ * **On-Policy Optimization**: The student model learns from its own generated responses rather than a fixed dataset. This eliminates exposure bias and ensures smaller, more stable gradient updates.
236
+ * **Inherent Reward Robustness**: Rewards are derived from the distribution divergence between student and teacher, making the process naturally resistant to reward hacking.
237
+
238
+ ### 5.2 Scaling Agentic RL
239
+
240
+ We significantly scale up the agentic training environments to improve intelligence and generalization.
241
+ * **Massive Code Agent Environments**: We utilize real-world GitHub issues to create over 100,000 verifiable tasks. Our automated pipeline maintains a Kubernetes cluster capable of running over 10,000 concurrent pods with a 70% environment setup success rate.
242
+ * **Multimodal Verifier for WebDev**: For web development tasks, we employ a vision-based verifier that evaluates code execution via recorded videos rather than static screenshots. This reduces visual hallucination and ensures functional correctness.
243
+ * **Cross-Domain Generalization**: Our experiments show that large-scale RL training on code agents effectively generalizes to other domains, boosting performance in Math and General Agent tasks.
244
+
245
+ ### 5.3 Advanced RL Infrastructure
246
+
247
+ To support high-throughput RL training for large-scale MoE models, we implemented several infrastructure optimizations on top of SGLang and Megatron-LM.
248
+ * **Rollout Routing Replay (R3)**: Addresses numerical precision inconsistencies in MoE routing between inference and training. R3 reuses the exact routed experts from rollout during the training pass, ensuring consistency with negligible overhead.
249
+ * **Request-Level Prefix Cache**: In multi-turn agent training, this cache stores KV states and routed experts from prior turns. It avoids re-computation and ensures sampling consistency across turns.
250
+ * **Fine-Grained Data Scheduler**: We extend the rollout engine to schedule fine-grained sequences instead of micro-batches. Combined with partial rollout, this significantly reduces GPU idleness caused by long-tail stragglers.
251
+ * **Toolbox & Tool Manager**: A two-layer design using Ray actor pools to handle resource contention. It eliminates cold-start delays for tool execution and isolates task logic from system policies.
252
+
253
+ -----
254
+
255
+ ## 6. Inference & Deployment
256
+
257
+ MiMo-V2-Flash supports FP8 mixed precision inference. We recommend using **SGLang** for optimal performance.
258
+
259
+ ### Quick Start with SGLang
260
+
261
+ ```bash
262
+ pip install sglang
263
+
264
+ # Launch server
265
+ python3 -m sglang.launch_server \
266
+ --model-path XiaomiMiMo/MiMo-V2-Flash \
267
+ --served-model-name mimo-v2-flash \
268
+ --pp-size 1 \
269
+ --dp-size 2 \
270
+ --enable-dp-attention \
271
+ --tp-size 8 \
272
+ --moe-a2a-backend deepep \
273
+ --page-size 1 \
274
+ --host 0.0.0.0 \
275
+ --port 9001 \
276
+ --trust-remote-code \
277
+ --mem-fraction-static 0.75 \
278
+ --max-running-requests 128 \
279
+ --chunked-prefill-size 16384 \
280
+ --reasoning-parser qwen3 \
281
+ --tool-call-parser mimo \
282
+ --context-length 262144 \
283
+ --attention-backend fa3 \
284
+ --speculative-algorithm EAGLE \
285
+ --speculative-num-steps 3 \
286
+ --speculative-eagle-topk 1 \
287
+ --speculative-num-draft-tokens 4 \
288
+ --enable-mtp
289
+
290
+ # Send request
291
+ curl -i http://localhost:9001/v1/chat/completions \
292
+ -H 'Content-Type:application/json' \
293
+ -d '{
294
+ "messages" : [{
295
+ "role": "user",
296
+ "content": "Nice to meet you MiMo"
297
+ }],
298
+ "model": "mimo-v2-flash",
299
+ "max_tokens": 4096,
300
+ "temperature": 0.8,
301
+ "top_p": 0.95,
302
+ "stream": true,
303
+ "chat_template_kwargs": {
304
+ "enable_thinking": true
305
+ }
306
+ }'
307
+ ```
308
+
309
+ ### Notifications
310
+
311
+ #### 1. System prompt
312
+
313
+ > [!IMPORTANT]
314
+ > The following system prompts are **HIGHLY** recommended, please choose from English and Chinese version.
315
+
316
+ English
317
+
318
+ ```plaintext
319
+ You are MiMo, an AI assistant developed by Xiaomi.
320
+
321
+ Today's date: {date} {week}. Your knowledge cutoff date is December 2024.
322
+ ```
323
+
324
+ Chinese
325
+
326
+ ```plaintext
327
+ 你是MiMo(中文名称也是MiMo),是小米公司研发的AI智能助手。
328
+
329
+ 今天的日期:{date} {week},你的知识截止日期是2024年12月。
330
+ ```
331
+
332
+ #### 2. Sampling parameters
333
+
334
+ > [!IMPORTANT]
335
+ > Recommended sampling parameters:
336
+ >
337
+ > `top_p=0.95`
338
+ >
339
+ > `temperature=0.8` for math, writing, web-dev
340
+ >
341
+ > `temperature=0.3` for agentic taks (e.g., vibe-coding, tool-use)
342
+
343
+ #### 3. Tool-use practice
344
+
345
+ > [!IMPORTANT]
346
+ > In the thinking mode with multi-turn tool calls, the model returns a `reasoning_content` field alongside `tool_calls`. To continue the conversation, the user must persist all history `reasoning_content` in the `messages` array of each subsequent request.
347
+
348
+ -----
349
+
350
+ ## 7. Citation
351
+
352
+ If you find our work helpful, please cite our technical report:
353
+
354
+ ```bibtex
355
+ @misc{mimo2025flash,
356
+ title={MiMo-V2-Flash Technical Report},
357
+ author={LLM-Core Xiaomi},
358
+ year={2025},
359
+ url={https://github.com/XiaomiMiMo/MiMo-V2-Flash/paper.pdf}
360
+ }
361
+ ```
362
+
363
+ ## 8. Contact
364
+
365
+ Please contact us at [mimo@xiaomi.com](mailto:mimo@xiaomi.com), join our WeChat group below or open an issue if you have any questions.
366
+
367
+ <p align="center">
368
+ <img src="https://github.com/XiaomiMiMo/MiMo-V2-Flash/raw/main/figures/wechat_group/wechat1.jpg?raw=true" width="20%" />
369
+ <img src="https://github.com/XiaomiMiMo/MiMo-V2-Flash/raw/main/figures/wechat_group/wechat2.jpg?raw=true" width="20%" />
370
+ <img src="https://github.com/XiaomiMiMo/MiMo-V2-Flash/raw/main/figures/wechat_group/wechat3.jpg?raw=true" width="20%" />
371
+ <img src="https://github.com/XiaomiMiMo/MiMo-V2-Flash/raw/main/figures/wechat_group/wechat4.jpg?raw=true" width="20%" />
372
+ </p>
added_tokens.json ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "</think>": 151668,
3
+ "</tool_call>": 151658,
4
+ "</tool_response>": 151666,
5
+ "<think>": 151667,
6
+ "<tool_call>": 151657,
7
+ "<tool_response>": 151665,
8
+ "<|box_end|>": 151649,
9
+ "<|box_start|>": 151648,
10
+ "<|endoftext|>": 151643,
11
+ "<|file_sep|>": 151664,
12
+ "<|fim_middle|>": 151660,
13
+ "<|fim_pad|>": 151662,
14
+ "<|fim_prefix|>": 151659,
15
+ "<|fim_suffix|>": 151661,
16
+ "<|im_end|>": 151645,
17
+ "<|im_start|>": 151644,
18
+ "<|image_pad|>": 151655,
19
+ "<|object_ref_end|>": 151647,
20
+ "<|object_ref_start|>": 151646,
21
+ "<|quad_end|>": 151651,
22
+ "<|quad_start|>": 151650,
23
+ "<|repo_name|>": 151663,
24
+ "<|video_pad|>": 151656,
25
+ "<|vision_end|>": 151653,
26
+ "<|vision_pad|>": 151654,
27
+ "<|vision_start|>": 151652
28
+ }
chat_template.jinja ADDED
@@ -0,0 +1,143 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {%- if not add_generation_prompt is defined -%}
2
+ {%- set add_generation_prompt = false -%}
3
+ {%- endif -%}
4
+ {%- if not enable_thinking is defined -%}
5
+ {%- set enable_thinking = false -%}
6
+ {%- endif -%}
7
+ {%- if not keep_all_reasoning is defined -%}
8
+ {%- set keep_all_reasoning = false -%}
9
+ {%- endif -%}
10
+ {%- macro render_extra_keys(json_dict, handled_keys) -%}
11
+ {%- if json_dict is mapping %}
12
+ {%- for json_key in json_dict if json_key not in handled_keys %}
13
+ {%- if json_dict[json_key] is mapping or (json_dict[json_key] is sequence and json_dict[json_key] is not string) %}
14
+ {{- '\n<' ~ json_key ~ '>' ~ (json_dict[json_key] | tojson | safe) ~ '</' ~ json_key ~ '>' }}
15
+ {%- else %}
16
+ {{-'\n<' ~ json_key ~ '>' ~ (json_dict[json_key] | string) ~ '</' ~ json_key ~ '>' }}
17
+ {%- endif %}
18
+ {%- endfor %}
19
+ {%- endif %}
20
+ {%- endmacro -%}
21
+ {%- if messages[0]["role"] == "system" %}
22
+ {%- set system_message = messages[0]["content"] %}
23
+ {%- set loop_messages = messages[1:] %}
24
+ {%- else %}
25
+ {%- set loop_messages = messages %}
26
+ {%- endif %}
27
+ {%- set ns = namespace(last_user_index=-1) %}
28
+ {%- for m in loop_messages %}
29
+ {%- if m.role == 'user' %}
30
+ {%- set ns.last_user_index = loop.index0 -%}
31
+ {%- endif %}
32
+ {%- endfor %}
33
+ {%- if not tools is defined %}
34
+ {%- set tools = [] %}
35
+ {%- endif %}
36
+ {%- if system_message is defined %}
37
+ {{- "<|im_start|>system\n" + system_message }}
38
+ {%- else %}
39
+ {{- "<|im_start|>system\nYou are MiMo, a helpful AI assistant engineered by Xiaomi." }}
40
+ {%- endif %}
41
+ {%- if tools is iterable and tools | length > 0 %}
42
+ {{- "\n\n# Tools\n\nYou may call one or more functions to assist with the user query.\n\nYou have access to the following functions:\n\n" }}
43
+ {{- "<tools>" }}
44
+ {%- for tool in tools %}
45
+ {%- if tool.function is defined %}
46
+ {%- set tool = tool.function %}
47
+ {%- endif %}
48
+ {{- "\n<function>\n<name>" ~ tool.name ~ "</name>" }}
49
+ {%- if tool.description is defined %}
50
+ {{- '\n<description>' ~ (tool.description | trim) ~ '</description>' }}
51
+ {%- endif %}
52
+ {{- '\n<parameters>' }}
53
+ {%- if tool.parameters is defined and tool.parameters is mapping and tool.parameters.properties is defined and tool.parameters.properties is mapping %}
54
+ {%- for param_name, param_fields in tool.parameters.properties|items %}
55
+ {{- '\n<parameter>' }}
56
+ {{- '\n<name>' ~ param_name ~ '</name>' }}
57
+ {%- if param_fields.type is defined %}
58
+ {{- '\n<type>' ~ (param_fields.type | string) ~ '</type>' }}
59
+ {%- endif %}
60
+ {%- if param_fields.description is defined %}
61
+ {{- '\n<description>' ~ (param_fields.description | trim) ~ '</description>' }}
62
+ {%- endif %}
63
+ {%- set handled_keys = ['name', 'type', 'description'] %}
64
+ {{- render_extra_keys(param_fields, handled_keys) }}
65
+ {{- '\n</parameter>' }}
66
+ {%- endfor %}
67
+ {%- endif %}
68
+ {%- set handled_keys = ['type', 'properties'] %}
69
+ {{- render_extra_keys(tool.parameters, handled_keys) }}
70
+ {{- '\n</parameters>' }}
71
+ {%- set handled_keys = ['type', 'name', 'description', 'parameters'] %}
72
+ {{- render_extra_keys(tool, handled_keys) }}
73
+ {{- '\n</function>' }}
74
+ {%- endfor %}
75
+ {{- "\n</tools>" }}
76
+ {{- '\n\nFor each function call, output the function name and arguments in the following format:\n<tool_call>\n<function=example_function_name>\n<parameter=example_parameter_1>value_1</parameter>\n<parameter=example_parameter_2>This is the value for the second parameter\nthat can span\nmultiple lines</parameter>\n</function>\n</tool_call>\n\n<IMPORTANT>\n- Function calls MUST follow the specified format: an inner <function=...></function> block must be nested within <tool_call></tool_call> XML tags\n- DO NOT use function calls inside <think></think> tags.\n- The value enclosed between parameter tags is preserved exactly as-is, including newlines and spaces.\n</IMPORTANT>' }}
77
+ {%- endif %}
78
+ {{- '<|im_end|>' }}
79
+ {%- for message in loop_messages %}
80
+ {%- if message.content is string %}
81
+ {%- set content = message.content %}
82
+ {%- else %}
83
+ {%- set content = '' %}
84
+ {%- endif %}
85
+ {%- if message.role == "assistant" %}
86
+ {%- if message.reasoning_content is string %}
87
+ {%- set reasoning_content = message.reasoning_content %}
88
+ {%- else %}
89
+ {%- set reasoning_content = '' %}
90
+ {%- if '</think>' in content %}
91
+ {%- set reasoning_content = content.split('</think>')[0].split('<think>')[-1] %}
92
+ {%- set content = content.split('</think>')[-1] %}
93
+ {%- endif %}
94
+ {%- endif %}
95
+ {%- if (keep_all_reasoning or loop.index0 > ns.last_user_index) and reasoning_content -%}
96
+ {{- '<|im_start|>' + message.role + '\n<think>' + reasoning_content + '</think>' + content }}
97
+ {%- else %}
98
+ {{- '<|im_start|>' + message.role + '\n<think></think>' + content }}
99
+ {%- endif %}
100
+ {%- if message.tool_calls is defined and message.tool_calls is iterable and message.tool_calls | length > 0 %}
101
+ {%- for tool_call in message.tool_calls %}
102
+ {%- if tool_call.function is defined %}
103
+ {%- set tool_call = tool_call.function %}
104
+ {%- endif %}
105
+ {{- '<tool_call>\n<function=' + tool_call.name + '>\n' }}
106
+ {%- if tool_call.arguments is defined %}
107
+ {%- for args_name, args_value in tool_call.arguments|items %}
108
+ {{- '<parameter=' + args_name + '>' }}
109
+ {%- set args_value = args_value | tojson | safe if args_value is mapping or (args_value is sequence and args_value is not string) else args_value | string %}
110
+ {{- args_value }}
111
+ {{- '</parameter>\n' }}
112
+ {%- endfor %}
113
+ {%- endif %}
114
+ {{- '</function>\n</tool_call>' }}
115
+ {%- endfor %}
116
+ {%- endif %}
117
+ {{- '<|im_end|>' }}
118
+ {%- elif message.role == "user" or message.role == "system"%}
119
+ {{- '<|im_start|>' + message.role + '\n' + message.content + '<|im_end|>' }}
120
+ {%- elif message.role == "tool" %}
121
+ {%- if loop.previtem and loop.previtem.role != "tool" %}
122
+ {{- '<|im_start|>tool\n' }}
123
+ {%- endif %}
124
+ {{- '<tool_response>\n' }}
125
+ {{- message.content }}
126
+ {{- '\n</tool_response>\n' }}
127
+ {%- if not loop.last and loop.nextitem.role != "tool" %}
128
+ {{- '<|im_end|>' }}
129
+ {%- elif loop.last %}
130
+ {{- '<|im_end|>' }}
131
+ {%- endif %}
132
+ {%- else %}
133
+ {{- '<|im_start|>' + message.role + '\n' + message.content + '<|im_end|>' }}
134
+ {%- endif %}
135
+ {%- endfor %}
136
+ {%- if add_generation_prompt %}
137
+ {{- '<|im_start|>assistant\n' }}
138
+ {%- if not enable_thinking -%}
139
+ {{- '<think></think>' -}}
140
+ {%- else -%}
141
+ {{- '' -}}
142
+ {%- endif -%}
143
+ {%- endif %}
config.json ADDED
@@ -0,0 +1,294 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_full_attention_sink_bias": false,
3
+ "add_swa_attention_sink_bias": true,
4
+ "architectures": [
5
+ "MiMoV2FlashForCausalLM"
6
+ ],
7
+ "attention_bias": false,
8
+ "attention_chunk_size": 128,
9
+ "attention_dropout": 0.0,
10
+ "attention_value_scale": 0.707,
11
+ "auto_map": {
12
+ "AutoConfig": "configuration_mimo_v2_flash.MiMoV2FlashConfig",
13
+ "AutoModel": "modeling_mimo_v2_flash.MiMoV2Model",
14
+ "AutoModelForCausalLM": "modeling_mimo_v2_flash.MiMoV2FlashForCausalLM"
15
+ },
16
+ "dtype": "bfloat16",
17
+ "head_dim": 192,
18
+ "hidden_act": "silu",
19
+ "hidden_size": 4096,
20
+ "hybrid_block_size": null,
21
+ "hybrid_layer_pattern": [
22
+ 0,
23
+ 1,
24
+ 1,
25
+ 1,
26
+ 1,
27
+ 0,
28
+ 1,
29
+ 1,
30
+ 1,
31
+ 1,
32
+ 1,
33
+ 0,
34
+ 1,
35
+ 1,
36
+ 1,
37
+ 1,
38
+ 1,
39
+ 0,
40
+ 1,
41
+ 1,
42
+ 1,
43
+ 1,
44
+ 1,
45
+ 0,
46
+ 1,
47
+ 1,
48
+ 1,
49
+ 1,
50
+ 1,
51
+ 0,
52
+ 1,
53
+ 1,
54
+ 1,
55
+ 1,
56
+ 1,
57
+ 0,
58
+ 1,
59
+ 1,
60
+ 1,
61
+ 1,
62
+ 1,
63
+ 0,
64
+ 1,
65
+ 1,
66
+ 1,
67
+ 1,
68
+ 1,
69
+ 0
70
+ ],
71
+ "initializer_range": 0.02,
72
+ "intermediate_size": 16384,
73
+ "layer_types": [
74
+ "full_attention",
75
+ "sliding_attention",
76
+ "sliding_attention",
77
+ "sliding_attention",
78
+ "sliding_attention",
79
+ "full_attention",
80
+ "sliding_attention",
81
+ "sliding_attention",
82
+ "sliding_attention",
83
+ "sliding_attention",
84
+ "sliding_attention",
85
+ "full_attention",
86
+ "sliding_attention",
87
+ "sliding_attention",
88
+ "sliding_attention",
89
+ "sliding_attention",
90
+ "sliding_attention",
91
+ "full_attention",
92
+ "sliding_attention",
93
+ "sliding_attention",
94
+ "sliding_attention",
95
+ "sliding_attention",
96
+ "sliding_attention",
97
+ "full_attention",
98
+ "sliding_attention",
99
+ "sliding_attention",
100
+ "sliding_attention",
101
+ "sliding_attention",
102
+ "sliding_attention",
103
+ "full_attention",
104
+ "sliding_attention",
105
+ "sliding_attention",
106
+ "sliding_attention",
107
+ "sliding_attention",
108
+ "sliding_attention",
109
+ "full_attention",
110
+ "sliding_attention",
111
+ "sliding_attention",
112
+ "sliding_attention",
113
+ "sliding_attention",
114
+ "sliding_attention",
115
+ "full_attention",
116
+ "sliding_attention",
117
+ "sliding_attention",
118
+ "sliding_attention",
119
+ "sliding_attention",
120
+ "sliding_attention",
121
+ "full_attention"
122
+ ],
123
+ "layernorm_epsilon": 1e-05,
124
+ "max_position_embeddings": 262144,
125
+ "moe_intermediate_size": 2048,
126
+ "moe_layer_freq": [
127
+ 0,
128
+ 1,
129
+ 1,
130
+ 1,
131
+ 1,
132
+ 1,
133
+ 1,
134
+ 1,
135
+ 1,
136
+ 1,
137
+ 1,
138
+ 1,
139
+ 1,
140
+ 1,
141
+ 1,
142
+ 1,
143
+ 1,
144
+ 1,
145
+ 1,
146
+ 1,
147
+ 1,
148
+ 1,
149
+ 1,
150
+ 1,
151
+ 1,
152
+ 1,
153
+ 1,
154
+ 1,
155
+ 1,
156
+ 1,
157
+ 1,
158
+ 1,
159
+ 1,
160
+ 1,
161
+ 1,
162
+ 1,
163
+ 1,
164
+ 1,
165
+ 1,
166
+ 1,
167
+ 1,
168
+ 1,
169
+ 1,
170
+ 1,
171
+ 1,
172
+ 1,
173
+ 1,
174
+ 1
175
+ ],
176
+ "n_group": 1,
177
+ "n_routed_experts": 256,
178
+ "n_shared_experts": null,
179
+ "norm_topk_prob": true,
180
+ "num_attention_heads": 64,
181
+ "num_experts_per_tok": 8,
182
+ "num_hidden_layers": 48,
183
+ "num_key_value_heads": 4,
184
+ "partial_rotary_factor": 0.334,
185
+ "quantization_config": {
186
+ "config_groups": {
187
+ "group_0": {
188
+ "format": "pack-quantized",
189
+ "input_activations": null,
190
+ "output_activations": null,
191
+ "targets": [
192
+ "Linear"
193
+ ],
194
+ "weights": {
195
+ "actorder": null,
196
+ "block_structure": null,
197
+ "dynamic": false,
198
+ "group_size": 32,
199
+ "num_bits": 4,
200
+ "observer": "minmax",
201
+ "observer_kwargs": {},
202
+ "strategy": "group",
203
+ "symmetric": true,
204
+ "type": "int"
205
+ }
206
+ }
207
+ },
208
+ "format": "pack-quantized",
209
+ "global_compression_ratio": null,
210
+ "ignore": [
211
+ "model.layers.0.self_attn.q_proj",
212
+ "model.layers.0.self_attn.k_proj",
213
+ "model.layers.0.self_attn.v_proj",
214
+ "model.layers.0.self_attn.o_proj",
215
+ "model.layers.0.self_attn.qkv_proj",
216
+ "model.layers.0.mlp.gate_up_proj",
217
+ "model.layers.0.mlp.gate_proj",
218
+ "model.layers.0.mlp.up_proj",
219
+ "model.layers.0.mlp.down_proj",
220
+ "model.layers.1.self_attn.o_proj",
221
+ "model.layers.2.self_attn.o_proj",
222
+ "model.layers.3.self_attn.o_proj",
223
+ "model.layers.4.self_attn.o_proj",
224
+ "model.layers.5.self_attn.o_proj",
225
+ "model.layers.6.self_attn.o_proj",
226
+ "model.layers.7.self_attn.o_proj",
227
+ "model.layers.8.self_attn.o_proj",
228
+ "model.layers.9.self_attn.o_proj",
229
+ "model.layers.10.self_attn.o_proj",
230
+ "model.layers.11.self_attn.o_proj",
231
+ "model.layers.12.self_attn.o_proj",
232
+ "model.layers.13.self_attn.o_proj",
233
+ "model.layers.14.self_attn.o_proj",
234
+ "model.layers.15.self_attn.o_proj",
235
+ "model.layers.16.self_attn.o_proj",
236
+ "model.layers.17.self_attn.o_proj",
237
+ "model.layers.18.self_attn.o_proj",
238
+ "model.layers.19.self_attn.o_proj",
239
+ "model.layers.20.self_attn.o_proj",
240
+ "model.layers.21.self_attn.o_proj",
241
+ "model.layers.22.self_attn.o_proj",
242
+ "model.layers.23.self_attn.o_proj",
243
+ "model.layers.24.self_attn.o_proj",
244
+ "model.layers.25.self_attn.o_proj",
245
+ "model.layers.26.self_attn.o_proj",
246
+ "model.layers.27.self_attn.o_proj",
247
+ "model.layers.28.self_attn.o_proj",
248
+ "model.layers.29.self_attn.o_proj",
249
+ "model.layers.30.self_attn.o_proj",
250
+ "model.layers.31.self_attn.o_proj",
251
+ "model.layers.32.self_attn.o_proj",
252
+ "model.layers.33.self_attn.o_proj",
253
+ "model.layers.34.self_attn.o_proj",
254
+ "model.layers.35.self_attn.o_proj",
255
+ "model.layers.36.self_attn.o_proj",
256
+ "model.layers.37.self_attn.o_proj",
257
+ "model.layers.38.self_attn.o_proj",
258
+ "model.layers.39.self_attn.o_proj",
259
+ "model.layers.40.self_attn.o_proj",
260
+ "model.layers.41.self_attn.o_proj",
261
+ "model.layers.42.self_attn.o_proj",
262
+ "model.layers.43.self_attn.o_proj",
263
+ "model.layers.44.self_attn.o_proj",
264
+ "model.layers.45.self_attn.o_proj",
265
+ "model.layers.46.self_attn.o_proj",
266
+ "model.layers.47.self_attn.o_proj",
267
+ "lm_head"
268
+ ],
269
+ "kv_cache_scheme": null,
270
+ "quant_method": "compressed-tensors",
271
+ "quantization_status": "compressed",
272
+ "sparsity_config": {},
273
+ "transform_config": {},
274
+ "version": "0.13.1.a20251215"
275
+ },
276
+ "rope_scaling": null,
277
+ "rope_theta": 10000,
278
+ "routed_scaling_factor": null,
279
+ "scoring_func": "sigmoid",
280
+ "sliding_window": 128,
281
+ "sliding_window_size": 128,
282
+ "swa_head_dim": 192,
283
+ "swa_num_attention_heads": 64,
284
+ "swa_num_key_value_heads": 8,
285
+ "swa_rope_theta": 10000,
286
+ "swa_v_head_dim": 128,
287
+ "tie_word_embeddings": false,
288
+ "topk_group": 1,
289
+ "topk_method": "noaux_tc",
290
+ "transformers_version": "4.57.3",
291
+ "use_cache": true,
292
+ "v_head_dim": 128,
293
+ "vocab_size": 152576
294
+ }
configuration_mimo_v2_flash.py ADDED
@@ -0,0 +1,109 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ #
3
+ # Copyright 2025 Xiaomi Corporation.
4
+ # Copyright 2025 The HuggingFace Inc. team.
5
+ #
6
+ # Licensed under the Apache License, Version 2.0 (the "License");
7
+ # you may not use this file except in compliance with the License.
8
+ # You may obtain a copy of the License at
9
+ #
10
+ # http://www.apache.org/licenses/LICENSE-2.0
11
+ #
12
+ # Unless required by applicable law or agreed to in writing, software
13
+ # distributed under the License is distributed on an "AS IS" BASIS,
14
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ # See the License for the specific language governing permissions and
16
+ # limitations under the License.
17
+
18
+ from transformers.configuration_utils import PretrainedConfig
19
+ from transformers.modeling_rope_utils import rope_config_validation
20
+ from transformers.utils import logging
21
+
22
+
23
+ logger = logging.get_logger(__name__)
24
+
25
+
26
+ class MiMoV2FlashConfig(PretrainedConfig):
27
+
28
+ model_type = ""
29
+ keys_to_ignore_at_inference = ["past_key_values"]
30
+
31
+ # Default tensor parallel plan for base model `Hybrid`
32
+ base_model_tp_plan = {
33
+ "layers.*.self_attn.q_proj": "colwise",
34
+ "layers.*.self_attn.k_proj": "colwise",
35
+ "layers.*.self_attn.v_proj": "colwise",
36
+ "layers.*.self_attn.o_proj": "rowwise",
37
+ "layers.*.mlp.gate_proj": "colwise",
38
+ "layers.*.mlp.up_proj": "colwise",
39
+ "layers.*.mlp.down_proj": "rowwise",
40
+ }
41
+ base_model_pp_plan = {
42
+ "embed_tokens": (["input_ids"], ["inputs_embeds"]),
43
+ "layers": (["hidden_states", "attention_mask"], ["hidden_states"]),
44
+ "norm": (["hidden_states"], ["hidden_states"]),
45
+ }
46
+
47
+ attribute_map = {
48
+ "num_local_experts": "n_routed_experts",
49
+ }
50
+
51
+ def __init__(
52
+ self,
53
+ vocab_size=151936,
54
+ hidden_size=4096,
55
+ intermediate_size=22016,
56
+ num_hidden_layers=32,
57
+ num_attention_heads=32,
58
+ num_key_value_heads=32,
59
+ hidden_act="silu",
60
+ max_position_embeddings=32768,
61
+ initializer_range=0.02,
62
+ layernorm_epsilon=1e-6,
63
+ use_cache=True,
64
+ tie_word_embeddings=False,
65
+ rope_theta=10000.0,
66
+ rope_scaling=None,
67
+ attention_dropout=0.0,
68
+ hybrid_block_size=None,
69
+ hybrid_layer_pattern=None,
70
+ partial_rotary_factor=1.0,
71
+ **kwargs,
72
+ ):
73
+ self.vocab_size = vocab_size
74
+ self.max_position_embeddings = max_position_embeddings
75
+ self.hidden_size = hidden_size
76
+ self.intermediate_size = intermediate_size
77
+ self.num_hidden_layers = num_hidden_layers
78
+ self.num_attention_heads = num_attention_heads
79
+
80
+ # for backward compatibility
81
+ if num_key_value_heads is None:
82
+ num_key_value_heads = num_attention_heads
83
+
84
+ self.num_key_value_heads = num_key_value_heads
85
+ self.hidden_act = hidden_act
86
+ self.initializer_range = initializer_range
87
+ self.layernorm_epsilon = layernorm_epsilon
88
+ self.use_cache = use_cache
89
+ self.rope_theta = rope_theta
90
+ self.rope_scaling = rope_scaling
91
+ self.attention_dropout = attention_dropout
92
+
93
+ if hybrid_block_size is not None and hybrid_layer_pattern is None:
94
+ hybrid_layer_pattern = [0 if ((i + 1) % hybrid_block_size == 0) else 1 for i in range(num_hidden_layers)]
95
+ self.hybrid_block_size = hybrid_block_size
96
+ self.hybrid_layer_pattern = hybrid_layer_pattern
97
+
98
+ self.partial_rotary_factor = partial_rotary_factor
99
+
100
+ # Validate the correctness of rotary position embeddings parameters
101
+ # BC: if there is a 'type' field, move it to 'rope_type'.
102
+ if self.rope_scaling is not None and "type" in self.rope_scaling:
103
+ self.rope_scaling["rope_type"] = self.rope_scaling["type"]
104
+ rope_config_validation(self)
105
+
106
+ super().__init__(
107
+ tie_word_embeddings=tie_word_embeddings,
108
+ **kwargs,
109
+ )
generation_config.json ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "transformers_version": "4.57.3"
4
+ }
merges.txt ADDED
The diff for this file is too large to render. See raw diff
 
model-00001-of-00036.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1b72fe3306423aaa2547f1cce1f948e6b24e7952ac264216522d5ec0e5f70afa
3
+ size 4996864944
model-00002-of-00036.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:32370938d270ca3a7b67d7b6d6291123dad139fa820d2203a3082b7b2ce6f0b7
3
+ size 4996631272
model-00003-of-00036.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1c968af56b53a55fe26e58fa3634ab1d7da749efdf85a592e99b8be6777ba88d
3
+ size 4997014192
model-00004-of-00036.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c8f057de876273611e661f2e55a1e07e3cafa5e130d591003e98c4503aac2bff
3
+ size 4998784320
model-00005-of-00036.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:70a8d5b2f650f12b60cbbf86f107bf082779a67d1897247445d7496d2e7235d3
3
+ size 4996631216
model-00006-of-00036.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:cfdeb11803545c1197f0d6851843d331e62ee7a57f71d182bb3156f0755e6be0
3
+ size 4997014248
model-00007-of-00036.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7147a77aebdc931ca77137dc9088f61ff3746216fa902ebc7330e23498d4f36c
3
+ size 4997014704
model-00008-of-00036.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6113df2d0f84feb76ada86d6fcc59adf267bdff46b6c909c9f1711a5aee6fe63
3
+ size 4998403600
model-00009-of-00036.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:bab63a66c83c6ee2d671b1cb17f0c540fd6477f2a23c77297792bb4541ee42b5
3
+ size 4997017424
model-00010-of-00036.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2275411b1a4b18220897a1c431cfc498416d6e51b7e5bcd293606e17b75aaaa7
3
+ size 4997017832
model-00011-of-00036.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5866ef7f23657d59c613d853d09f279a0a9bd65b26a1780937a17a8fac7b114d
3
+ size 4996634192
model-00012-of-00036.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8b5b32971eb1a9ec55ea1ecb0ca168bfbc35a61cf217a0b3abaa51e0f9d794d4
3
+ size 4997017472
model-00013-of-00036.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1fe306dac375b60a856bff52ebfa528c3bd58fd3ce40b8623c70e85342fef22e
3
+ size 4998787448
model-00014-of-00036.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2c1e904229e6ccb1ab1621fb66f6208536dc93dee61c7ecc9d9466f11792b58a
3
+ size 4996634136
model-00015-of-00036.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7324c758422c30a65323e75981c091bd07b3775e7b6977d453b0b45c32240f42
3
+ size 4997017528
model-00016-of-00036.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:09d5bbb4645ca735ac2cca7e8b3843bb08671e34e7e727e3dc5edc60ad3d475c
3
+ size 4997017832
model-00017-of-00036.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:994cfabb33ecaacbb9a5683de49ec20b355bd3025e29ba80ba374b4263b86dcd
3
+ size 4998403696
model-00018-of-00036.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:bdeeb3c6cb94601501f2ede6a919d66f156a583f9aaa979c3efd381d7ab7e5a1
3
+ size 4997017584
model-00019-of-00036.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1285eea168d994d02c84a325ec6dbe67b73d269de00981840d2a9370b75ddfeb
3
+ size 4997017832
model-00020-of-00036.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:dc5204e061786f03be2ee0f4910599f14370df8e0094943d59c40f06ef814899
3
+ size 4996634032
model-00021-of-00036.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:622c27bf3422bccd5fbb161064ea764408a149e7362679f1841b84be873f2fe1
3
+ size 4997017632
model-00022-of-00036.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d3ad420476981a8a4b5a8a55d6162c234bd60a9829548aa6a1a30c978815fe06
3
+ size 5000375328
model-00023-of-00036.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6af977bd10700578417a3e53a475ef4331ae49dca7ceae10012f7c0631c40772
3
+ size 4999765072
model-00024-of-00036.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a087d3c3f6a369a66e5cf2f8164f557625c5e69da67411b5e83fbe16000a0956
3
+ size 4997017688
model-00025-of-00036.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:14248f62cce116af70f7f0707e803bda83a4b8e4c41fa48ba01aed45aa6db30c
3
+ size 4996634816
model-00026-of-00036.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8d61529ce02c0a5792ad53cf697a4ba3bd8cda22ca484f1817261bbacc589af1
3
+ size 4998786552
model-00027-of-00036.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:eb63626f046290f63c83413b5d951767ddc6a383bc98011093c99a30c764db71
3
+ size 4997017744
model-00028-of-00036.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b70cdecd1507f8fc5bb8814f862182d24d2cc30370bde495271d5cc801e202ab
3
+ size 4996634704
model-00029-of-00036.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ac3b061dfa4404d4328519bb2640a23358e67cb4f723e72e80fdcec704eb7ab9
3
+ size 4997016992
model-00030-of-00036.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ec6643ca0e400ddd1ca6c7b2d74ef3e98b10e2da5e778d9061bc16b54b18229f
3
+ size 4997017792
model-00031-of-00036.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:45369c15e787001f14d96a3aee344e50b6d850c2a15cf7539348752f3bcfa704
3
+ size 4998404240
model-00032-of-00036.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0d8f860620bca4dea514efd03c3602f9cb6ea0f15c55c3bdcf96a8cc3e43709f
3
+ size 4997017040
model-00033-of-00036.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:71279c7fe6aaf06382f0b4933dc542aa04b5ec58c3eb69af416ef3f55f7a26a4
3
+ size 4997017832
model-00034-of-00036.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:33cb0b845bfe841c2d9f33a73aedc1b4b4008a879289231f830f48ea1c116ccb
3
+ size 4996634568
model-00035-of-00036.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:24626b14fd36cffaeb00af7dc8b13fa6a729b7d7698b9c6a26d291c1f7d75434
3
+ size 4998786704
model-00036-of-00036.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:25a1daf9240e653e5189c199511a485d613f473e076c8b225610aedaa5762a74
3
+ size 3345154688
model.safetensors.index.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8e51e5f33c35c8976f892eb95a9acc66206c7f7ae8244a345c0b950003dde3a3
3
+ size 10570904
modeling_mimo_v2_flash.py ADDED
@@ -0,0 +1,663 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ #
3
+ # Copyright 2025 Xiaomi Corporation.
4
+ # Copyright 2025 The HuggingFace Inc. team.
5
+ #
6
+ # Licensed under the Apache License, Version 2.0 (the "License");
7
+ # you may not use this file except in compliance with the License.
8
+ # You may obtain a copy of the License at
9
+ #
10
+ # http://www.apache.org/licenses/LICENSE-2.0
11
+ #
12
+ # Unless required by applicable law or agreed to in writing, software
13
+ # distributed under the License is distributed on an "AS IS" BASIS,
14
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ # See the License for the specific language governing permissions and
16
+ # limitations under the License.
17
+
18
+ from typing import Callable, Optional, Tuple, Union
19
+
20
+ import torch
21
+ import torch.nn as nn
22
+ import torch.nn.functional as F
23
+
24
+ from transformers.generation import GenerationMixin
25
+ from transformers.activations import ACT2FN
26
+ from transformers.cache_utils import Cache, DynamicCache
27
+ from transformers.integrations import use_kernel_forward_from_hub
28
+
29
+ from transformers.modeling_outputs import (
30
+ BaseModelOutputWithPast,
31
+ CausalLMOutputWithPast,
32
+ )
33
+
34
+ from transformers.masking_utils import create_causal_mask, create_sliding_window_causal_mask
35
+ from transformers.modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update
36
+ from transformers.modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
37
+ from transformers.processing_utils import Unpack
38
+ from transformers.utils import (
39
+ logging,
40
+ )
41
+
42
+ from transformers.modeling_outputs import MoeModelOutputWithPast
43
+ from transformers.utils import TransformersKwargs, auto_docstring, can_return_tuple
44
+ from .configuration_mimo_v2_flash import MiMoV2FlashConfig
45
+
46
+ logger = logging.get_logger(__name__)
47
+
48
+
49
+ def rotate_half(x):
50
+ """Rotates half the hidden dims of the input."""
51
+ x1 = x[..., : x.shape[-1] // 2]
52
+ x2 = x[..., x.shape[-1] // 2:]
53
+ return torch.cat((-x2, x1), dim=-1)
54
+
55
+
56
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
57
+ """Applies Rotary Position Embedding to the query and key tensors.
58
+
59
+ Args:
60
+ q (`torch.Tensor`): The query tensor.
61
+ k (`torch.Tensor`): The key tensor.
62
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
63
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
64
+ position_ids (`torch.Tensor`, *optional*):
65
+ Deprecated and unused.
66
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
67
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
68
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
69
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
70
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
71
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
72
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
73
+ Returns:
74
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
75
+ """
76
+ cos = cos.unsqueeze(unsqueeze_dim)
77
+ sin = sin.unsqueeze(unsqueeze_dim)
78
+ q_embed = (q * cos) + (rotate_half(q) * sin)
79
+ k_embed = (k * cos) + (rotate_half(k) * sin)
80
+ return q_embed, k_embed
81
+
82
+
83
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
84
+ """
85
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
86
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
87
+ """
88
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
89
+ if n_rep == 1:
90
+ return hidden_states
91
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
92
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
93
+
94
+
95
+ def eager_attention_forward(
96
+ module: nn.Module,
97
+ query: torch.Tensor,
98
+ key: torch.Tensor,
99
+ value: torch.Tensor,
100
+ attention_mask: Optional[torch.Tensor],
101
+ scaling: float,
102
+ dropout: float = 0.0,
103
+ sinks: Optional[torch.Tensor] = None,
104
+ ):
105
+ key_states = repeat_kv(key, module.num_key_value_groups)
106
+ value_states = repeat_kv(value, module.num_key_value_groups)
107
+ attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
108
+ if attention_mask is not None:
109
+ causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
110
+ attn_weights = attn_weights + causal_mask
111
+
112
+ if sinks is not None:
113
+ sinks = module.attention_sink_bias.reshape(1, -1, 1, 1).expand(query.shape[0], -1, query.shape[-2], -1)
114
+ attn_weights = torch.cat([attn_weights, sinks], dim=-1)
115
+
116
+ attn_weights = attn_weights - attn_weights.max(dim=-1, keepdim=True).values
117
+ probs = F.softmax(attn_weights, dim=-1, dtype=attn_weights.dtype)
118
+
119
+ if sinks is not None:
120
+ probs = probs[..., :-1] # we drop the sink here
121
+
122
+ attn_weights = nn.functional.dropout(probs, p=dropout, training=module.training)
123
+ attn_output = torch.matmul(attn_weights, value_states)
124
+ attn_output = attn_output.transpose(1, 2).contiguous()
125
+ return attn_output, attn_weights
126
+
127
+
128
+ @use_kernel_forward_from_hub("RMSNorm")
129
+ class MiMoV2RMSNorm(nn.Module):
130
+ def __init__(self, hidden_size, eps=1e-6):
131
+ """
132
+ MiMoV2RMSNorm is equivalent to T5LayerNorm
133
+ """
134
+ super().__init__()
135
+ self.weight = nn.Parameter(torch.ones(hidden_size))
136
+ self.variance_epsilon = eps
137
+
138
+ def forward(self, hidden_states):
139
+ input_dtype = hidden_states.dtype
140
+ hidden_states = hidden_states.to(torch.float32)
141
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
142
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
143
+ return self.weight * hidden_states.to(input_dtype)
144
+
145
+
146
+ class MiMoV2MLP(nn.Module):
147
+ """MiMoV2MLP matching the gate, up, and down projection layers."""
148
+
149
+ def __init__(self, config: MiMoV2FlashConfig, intermediate_size=None):
150
+ super().__init__()
151
+ self.config = config
152
+ self.hidden_size = config.hidden_size
153
+ self.intermediate_size = config.intermediate_size if intermediate_size is None else intermediate_size
154
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
155
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
156
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
157
+ self.act_fn = ACT2FN[config.hidden_act]
158
+
159
+ def forward(self, hidden_states):
160
+ down_proj = self.down_proj(self.act_fn(self.gate_proj(hidden_states)) * self.up_proj(hidden_states))
161
+ return down_proj
162
+
163
+
164
+ class MiMoV2MoEGate(nn.Module):
165
+ def __init__(self, config):
166
+ super().__init__()
167
+ self.config = config
168
+ self.top_k = config.num_experts_per_tok
169
+ self.n_routed_experts = config.n_routed_experts
170
+ self.routed_scaling_factor = (
171
+ config.routed_scaling_factor
172
+ if config.routed_scaling_factor is not None
173
+ else 1.0
174
+ )
175
+ self.scoring_func = config.scoring_func
176
+ self.topk_method = config.topk_method
177
+ self.n_group = config.n_group
178
+ self.topk_group = config.topk_group
179
+
180
+ # topk selection algorithm
181
+ self.norm_topk_prob = config.norm_topk_prob
182
+ self.gating_dim = config.hidden_size
183
+ self.weight = nn.Parameter(
184
+ torch.empty((self.n_routed_experts, self.gating_dim))
185
+ )
186
+ if self.topk_method == "noaux_tc":
187
+ self.e_score_correction_bias = nn.Parameter(
188
+ torch.empty((self.n_routed_experts))
189
+ )
190
+
191
+ def forward(self, hidden_states):
192
+ bsz, seq_len, h = hidden_states.shape
193
+ ### compute gating score
194
+ hidden_states = hidden_states.view(-1, h)
195
+ logits = F.linear(
196
+ hidden_states.type(torch.float32), self.weight.type(torch.float32), None
197
+ )
198
+ if self.scoring_func == "sigmoid":
199
+ scores = logits.sigmoid()
200
+ else:
201
+ raise NotImplementedError(
202
+ f"insupportable scoring function for MoE gating: {self.scoring_func}"
203
+ )
204
+
205
+ ### select top-k experts
206
+ if self.topk_method == "noaux_tc":
207
+ assert not self.training
208
+ scores_for_choice = scores.view(bsz * seq_len, -1) + self.e_score_correction_bias.unsqueeze(0)
209
+ group_scores = (
210
+ scores_for_choice.view(bsz * seq_len, self.n_group, -1).topk(2, dim=-1)[0].sum(dim = -1)
211
+ ) # [n, n_group]
212
+ group_idx = torch.topk(
213
+ group_scores, k=self.topk_group, dim=-1, sorted=False
214
+ )[
215
+ 1
216
+ ] # [n, top_k_group]
217
+ group_mask = torch.zeros_like(group_scores) # [n, n_group]
218
+ group_mask.scatter_(1, group_idx, 1) # [n, n_group]
219
+ score_mask = (
220
+ group_mask.unsqueeze(-1)
221
+ .expand(
222
+ bsz * seq_len, self.n_group, self.n_routed_experts // self.n_group
223
+ )
224
+ .reshape(bsz * seq_len, -1)
225
+ ) # [n, e]
226
+ tmp_scores = scores_for_choice.masked_fill(~score_mask.bool(), float("-inf")) # [n, e]
227
+ _, topk_idx = torch.topk(
228
+ tmp_scores, k=self.top_k, dim=-1, sorted=False
229
+ )
230
+ topk_weight = scores.gather(1, topk_idx)
231
+ else:
232
+ raise NotImplementedError(
233
+ f"insupportable TopK function for MoE gating: {self.topk_method}"
234
+ )
235
+
236
+ ### norm gate to sum 1
237
+ if self.top_k > 1 and self.norm_topk_prob:
238
+ denominator = topk_weight.sum(dim=-1, keepdim=True) + 1e-20
239
+ topk_weight = topk_weight / denominator
240
+ topk_weight = topk_weight * self.routed_scaling_factor # must multiply the scaling factor
241
+
242
+ return topk_idx, topk_weight
243
+
244
+
245
+ class MiMoV2MoE(nn.Module):
246
+ """
247
+ A mixed expert module containing shared experts.
248
+ """
249
+
250
+ def __init__(self, config):
251
+ super().__init__()
252
+ self.config = config
253
+ self.experts = nn.ModuleList(
254
+ [
255
+ MiMoV2MLP(config, intermediate_size=config.moe_intermediate_size)
256
+ for _ in range(config.n_routed_experts)
257
+ ]
258
+ )
259
+ self.gate = MiMoV2MoEGate(config)
260
+
261
+ def moe(self, hidden_states: torch.Tensor, topk_indices: torch.Tensor, topk_weights: torch.Tensor):
262
+ r"""
263
+ CALL FOR CONTRIBUTION! I don't have time to optimise this right now, but expert weights need to be fused
264
+ to not have to do a loop here (deepseek has 256 experts soooo yeah).
265
+ """
266
+ final_hidden_states = torch.zeros_like(hidden_states, dtype=topk_weights.dtype)
267
+ expert_mask = torch.nn.functional.one_hot(topk_indices, num_classes=len(self.experts))
268
+ expert_mask = expert_mask.permute(2, 0, 1)
269
+
270
+ for expert_idx in range(len(self.experts)):
271
+ expert = self.experts[expert_idx]
272
+ mask = expert_mask[expert_idx]
273
+ token_indices, weight_indices = torch.where(mask)
274
+
275
+ if token_indices.numel() > 0:
276
+ expert_weights = topk_weights[token_indices, weight_indices]
277
+ expert_input = hidden_states[token_indices]
278
+ expert_output = expert(expert_input)
279
+ weighted_output = expert_output * expert_weights.unsqueeze(-1)
280
+ final_hidden_states.index_add_(0, token_indices, weighted_output)
281
+
282
+ # in original deepseek, the output of the experts are gathered once we leave this module
283
+ # thus the moe module is itelsf an IsolatedParallel module
284
+ # and all expert are "local" meaning we shard but we don't gather
285
+ return final_hidden_states.type(hidden_states.dtype)
286
+
287
+
288
+ def forward(self, hidden_states: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
289
+ orig_shape = hidden_states.shape
290
+ topk_indices, topk_weights = self.gate(hidden_states)
291
+ hidden_states = hidden_states.view(-1, hidden_states.shape[-1])
292
+ hidden_states = self.moe(hidden_states, topk_indices, topk_weights).view(*orig_shape)
293
+
294
+ return hidden_states
295
+
296
+
297
+ class MiMoV2Attention(nn.Module):
298
+ """MiMoV2 Global Attention (pattern == 0) and Sliding Window Attention (pattern == 1)."""
299
+
300
+ def __init__(self, config: MiMoV2FlashConfig, is_swa: bool, layer_idx: int):
301
+ super().__init__()
302
+ self.config = config
303
+ self.layer_idx = layer_idx
304
+
305
+ if is_swa:
306
+ self.head_dim = config.swa_head_dim
307
+ self.v_head_dim = config.swa_v_head_dim
308
+ self.num_attention_heads = config.swa_num_attention_heads
309
+ self.num_key_value_heads = config.swa_num_key_value_heads
310
+ else:
311
+ self.head_dim = config.head_dim
312
+ self.v_head_dim = config.v_head_dim
313
+ self.num_attention_heads = config.num_attention_heads
314
+ self.num_key_value_heads = config.num_key_value_heads
315
+
316
+ self.rope_dim = int(self.head_dim * config.partial_rotary_factor)
317
+ self.num_key_value_groups = self.num_attention_heads // self.num_key_value_heads
318
+ self.attention_bias = config.attention_bias
319
+ self.attention_dropout: float = config.attention_dropout
320
+ self.scaling = self.head_dim ** -0.5
321
+
322
+ # These dimensions are for the attention layers
323
+ q_hidden_size = self.num_attention_heads * self.head_dim
324
+ k_hidden_size = self.num_key_value_heads * self.head_dim
325
+ v_hidden_size = self.num_key_value_heads * self.v_head_dim
326
+ o_hidden_size = self.num_attention_heads * self.v_head_dim
327
+
328
+ self.q_proj = nn.Linear(config.hidden_size, q_hidden_size, bias=self.attention_bias)
329
+ self.k_proj = nn.Linear(config.hidden_size, k_hidden_size, bias=self.attention_bias)
330
+ self.v_proj = nn.Linear(config.hidden_size, v_hidden_size, bias=self.attention_bias)
331
+ self.o_proj = nn.Linear(o_hidden_size, config.hidden_size, bias=False)
332
+
333
+ self.attention_sink_bias = (
334
+ torch.nn.Parameter(torch.empty(config.num_attention_heads), requires_grad=False)
335
+ if (config.add_full_attention_sink_bias and not is_swa) or (config.add_swa_attention_sink_bias and is_swa)
336
+ else None
337
+ )
338
+
339
+ def forward(
340
+ self,
341
+ hidden_states: torch.Tensor,
342
+ position_embeddings: tuple[torch.Tensor, torch.Tensor],
343
+ attention_mask: Optional[torch.Tensor],
344
+ past_key_values: Optional[Cache] = None,
345
+ cache_position: Optional[torch.LongTensor] = None,
346
+ position_ids: Optional[torch.LongTensor] = None,
347
+ **kwargs: Unpack[TransformersKwargs],
348
+ ) -> tuple[torch.Tensor, torch.Tensor]:
349
+ input_shape = hidden_states.shape[:-1]
350
+ qk_hidden_shape = (*input_shape, -1, self.head_dim)
351
+ v_hidden_shape = (*input_shape, -1, self.v_head_dim)
352
+
353
+ query_states = self.q_proj(hidden_states).view(qk_hidden_shape).transpose(1, 2)
354
+ key_states = self.k_proj(hidden_states).view(qk_hidden_shape).transpose(1, 2)
355
+ value_states = self.v_proj(hidden_states).view(v_hidden_shape).transpose(1, 2)
356
+
357
+ cos, sin = position_embeddings
358
+
359
+ query_rope, query_nope = query_states.split([self.rope_dim, self.head_dim - self.rope_dim], dim=-1)
360
+ key_rope, key_nope = key_states.split([self.rope_dim, self.head_dim - self.rope_dim], dim=-1)
361
+
362
+ query_rope, key_rope = apply_rotary_pos_emb(query_rope, key_rope, cos, sin)
363
+
364
+ query_states = torch.cat([query_rope, query_nope], dim=-1)
365
+ key_states = torch.cat([key_rope, key_nope], dim=-1)
366
+
367
+ if past_key_values is not None:
368
+ # sin and cos are specific to RoPE models; cache_position needed for the static cache
369
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
370
+ key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx, cache_kwargs)
371
+
372
+ attention_interface: Callable = eager_attention_forward
373
+ if self.config._attn_implementation != "eager":
374
+ attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
375
+
376
+ attn_output, attn_weights = attention_interface(
377
+ self,
378
+ query_states,
379
+ key_states,
380
+ value_states,
381
+ attention_mask,
382
+ dropout=0.0 if not self.training else self.attention_dropout,
383
+ scaling=self.scaling,
384
+ sinks=self.attention_sink_bias,
385
+ )
386
+
387
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
388
+ attn_output = self.o_proj(attn_output)
389
+ return attn_output, attn_weights
390
+
391
+
392
+ class MiMoV2DecoderLayer(nn.Module):
393
+ """
394
+ MiMoV2 Decoder Layer. It dynamically chooses the correct attention
395
+ module based on the layer index and the `hybrid_layer_pattern`.
396
+ """
397
+
398
+ def __init__(self, config: MiMoV2FlashConfig, layer_idx: int):
399
+ super().__init__()
400
+
401
+ # This is the key logic: choose the module based on the pattern
402
+ is_swa_layer = config.hybrid_layer_pattern[layer_idx] == 1
403
+ if is_swa_layer:
404
+ self.attention_type = "sliding_window_attention"
405
+ self.self_attn = MiMoV2Attention(config, True, layer_idx)
406
+ else:
407
+ self.attention_type = "full_attention"
408
+ self.self_attn = MiMoV2Attention(config, False, layer_idx)
409
+
410
+ self.mlp = (
411
+ MiMoV2MoE(config)
412
+ if (
413
+ getattr(config, 'n_routed_experts', None) is not None
414
+ and config.moe_layer_freq[layer_idx]
415
+ )
416
+ else MiMoV2MLP(config)
417
+ )
418
+
419
+ self.input_layernorm = MiMoV2RMSNorm(config.hidden_size, eps=config.layernorm_epsilon)
420
+ self.post_attention_layernorm = MiMoV2RMSNorm(config.hidden_size, eps=config.layernorm_epsilon)
421
+ self.hidden_size = config.hidden_size
422
+
423
+ def forward(
424
+ self,
425
+ hidden_states: torch.Tensor,
426
+ attention_mask: Optional[torch.Tensor] = None,
427
+ position_ids: Optional[torch.LongTensor] = None,
428
+ past_key_values: Optional[Cache] = None,
429
+ use_cache: Optional[bool] = False,
430
+ cache_position: Optional[torch.LongTensor] = None,
431
+ position_embeddings: Optional[tuple[torch.Tensor, torch.Tensor]] = None,
432
+ **kwargs: Unpack[TransformersKwargs],
433
+ ) -> torch.Tensor:
434
+ residual = hidden_states
435
+ hidden_states = self.input_layernorm(hidden_states)
436
+ # Self Attention
437
+ hidden_states, _ = self.self_attn(
438
+ hidden_states=hidden_states,
439
+ attention_mask=attention_mask,
440
+ position_ids=position_ids,
441
+ past_key_values=past_key_values,
442
+ use_cache=use_cache,
443
+ cache_position=cache_position,
444
+ position_embeddings=position_embeddings,
445
+ **kwargs,
446
+ )
447
+ hidden_states = residual + hidden_states
448
+
449
+ # MLP or MOE
450
+ residual = hidden_states
451
+ hidden_states = self.post_attention_layernorm(hidden_states)
452
+ hidden_states = self.mlp(hidden_states)
453
+ hidden_states = residual + hidden_states
454
+ return hidden_states
455
+
456
+ class MiMoV2FlashRotaryEmbedding(nn.Module):
457
+ inv_freq: torch.Tensor # fix linting for `register_buffer`
458
+
459
+ def __init__(self, config: MiMoV2FlashConfig, is_swa, device=None):
460
+ super().__init__()
461
+ # BC: "rope_type" was originally "type"
462
+ if hasattr(config, "rope_scaling") and isinstance(config.rope_scaling, dict):
463
+ self.rope_type = config.rope_scaling.get("rope_type", config.rope_scaling.get("type"))
464
+ else:
465
+ self.rope_type = "default"
466
+ self.max_seq_len_cached = config.max_position_embeddings
467
+ self.original_max_seq_len = config.max_position_embeddings
468
+
469
+ self.config = config
470
+ self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
471
+
472
+ if is_swa:
473
+ self.config.rope_theta = config.swa_rope_theta
474
+ self.config.head_dim = config.swa_head_dim
475
+
476
+ inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device)
477
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
478
+ self.original_inv_freq = self.inv_freq
479
+
480
+ @torch.no_grad()
481
+ @dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope)
482
+ def forward(self, x, position_ids):
483
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device)
484
+ position_ids_expanded = position_ids[:, None, :].float()
485
+
486
+ device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
487
+ with torch.autocast(device_type=device_type, enabled=False): # Force float32
488
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
489
+ emb = torch.cat((freqs, freqs), dim=-1)
490
+ cos = emb.cos() * self.attention_scaling
491
+ sin = emb.sin() * self.attention_scaling
492
+
493
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
494
+
495
+
496
+ @auto_docstring
497
+ class MiMoV2Model(PreTrainedModel):
498
+ """The main 'model' block, corresponding to `model.` in the weight map."""
499
+ config_class = MiMoV2FlashConfig
500
+
501
+ def __init__(self, config: MiMoV2FlashConfig):
502
+ super().__init__(config)
503
+ self.vocab_size = config.vocab_size
504
+
505
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size)
506
+ self.layers = nn.ModuleList(
507
+ [MiMoV2DecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
508
+ )
509
+ self.norm = MiMoV2RMSNorm(config.hidden_size, eps=config.layernorm_epsilon)
510
+ self.rotary_emb = MiMoV2FlashRotaryEmbedding(config=config, is_swa=False)
511
+ self.swa_rotary_emb = MiMoV2FlashRotaryEmbedding(config=config, is_swa=True)
512
+
513
+ self.has_sliding_layers = any(
514
+ pattern == 1 for pattern in config.hybrid_layer_pattern
515
+ )
516
+
517
+ # For Huggingface DynamicCache compatibility
518
+ self.config.layer_types = [
519
+ "sliding_attention" if config.hybrid_layer_pattern[i] == 1 else "full_attention"
520
+ for i in range(config.num_hidden_layers)
521
+ ]
522
+
523
+ @auto_docstring
524
+ def forward(
525
+ self,
526
+ input_ids: Optional[torch.LongTensor] = None,
527
+ attention_mask: Optional[torch.Tensor] = None,
528
+ position_ids: Optional[torch.LongTensor] = None,
529
+ past_key_values: Optional[Cache] = None,
530
+ inputs_embeds: Optional[torch.FloatTensor] = None,
531
+ use_cache: Optional[bool] = None,
532
+ cache_position: Optional[torch.LongTensor] = None,
533
+ **kwargs: Unpack[TransformersKwargs],
534
+ ) -> MoeModelOutputWithPast:
535
+ if (input_ids is None) ^ (inputs_embeds is not None):
536
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
537
+
538
+ if inputs_embeds is None:
539
+ inputs_embeds = self.embed_tokens(input_ids)
540
+
541
+ if use_cache and past_key_values is None:
542
+ past_key_values = DynamicCache(config=self.config)
543
+
544
+ if cache_position is None:
545
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
546
+ cache_position = torch.arange(
547
+ past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
548
+ )
549
+
550
+ if position_ids is None:
551
+ position_ids = cache_position.unsqueeze(0)
552
+
553
+ # It may already have been prepared by e.g. `generate`
554
+ if not isinstance(causal_mask_mapping := attention_mask, dict):
555
+ # Prepare mask arguments
556
+ mask_kwargs = {
557
+ "config": self.config,
558
+ "input_embeds": inputs_embeds,
559
+ "attention_mask": attention_mask,
560
+ "cache_position": cache_position,
561
+ "past_key_values": past_key_values,
562
+ "position_ids": position_ids,
563
+ }
564
+ # Create the masks
565
+ causal_mask_mapping = {
566
+ "full_attention": create_causal_mask(**mask_kwargs),
567
+ }
568
+ # The sliding window alternating layers are not always activated depending on the config
569
+ if self.has_sliding_layers:
570
+ causal_mask_mapping["sliding_window_attention"] = create_sliding_window_causal_mask(**mask_kwargs)
571
+
572
+ hidden_states = inputs_embeds
573
+ position_embeddings = self.rotary_emb(hidden_states, position_ids)
574
+ swa_position_embeddings = self.swa_rotary_emb(hidden_states, position_ids)
575
+
576
+ for decoder_layer in self.layers[: self.config.num_hidden_layers]:
577
+ hidden_states = decoder_layer(
578
+ hidden_states,
579
+ attention_mask=causal_mask_mapping[decoder_layer.attention_type],
580
+ position_embeddings=(
581
+ position_embeddings
582
+ if decoder_layer.attention_type == "full_attention"
583
+ else swa_position_embeddings
584
+ ),
585
+ position_ids=position_ids,
586
+ past_key_values=past_key_values,
587
+ use_cache=use_cache,
588
+ cache_position=cache_position,
589
+ **kwargs,
590
+ )
591
+
592
+ hidden_states = self.norm(hidden_states)
593
+ return BaseModelOutputWithPast(
594
+ last_hidden_state=hidden_states,
595
+ past_key_values=past_key_values if use_cache else None,
596
+ )
597
+
598
+
599
+ @auto_docstring
600
+ class MiMoV2FlashForCausalLM(PreTrainedModel,GenerationMixin):
601
+ _tied_weights_keys = {"lm_head.weight": "model.embed_tokens.weight"}
602
+ _tp_plan = {"lm_head": "colwise_rep"}
603
+ _pp_plan = {"lm_head": (["hidden_states"], ["logits"])}
604
+
605
+ config_class = MiMoV2FlashConfig
606
+ _keys_to_ignore_on_load_unexpected = [r"model.layers\.\d+\.self_attn\.rotary_emb\.inv_freq"]
607
+
608
+ def __init__(self, config: MiMoV2FlashConfig):
609
+ super().__init__(config)
610
+ self.model = MiMoV2Model(config)
611
+ self.vocab_size = config.vocab_size
612
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
613
+
614
+ # Initialize weights and apply final processing
615
+ self.post_init()
616
+
617
+ @can_return_tuple
618
+ @auto_docstring
619
+ def forward(
620
+ self,
621
+ input_ids: Optional[torch.LongTensor] = None,
622
+ attention_mask: Optional[torch.Tensor] = None,
623
+ position_ids: Optional[torch.LongTensor] = None,
624
+ past_key_values: Optional[Cache] = None,
625
+ inputs_embeds: Optional[torch.FloatTensor] = None,
626
+ labels: Optional[torch.LongTensor] = None,
627
+ use_cache: Optional[bool] = None,
628
+ cache_position: Optional[torch.LongTensor] = None,
629
+ logits_to_keep: Union[int, torch.Tensor] = 0,
630
+ **kwargs: Unpack[TransformersKwargs],
631
+ ) -> CausalLMOutputWithPast:
632
+
633
+ outputs: BaseModelOutputWithPast = self.model(
634
+ input_ids=input_ids,
635
+ attention_mask=attention_mask,
636
+ position_ids=position_ids,
637
+ past_key_values=past_key_values,
638
+ inputs_embeds=inputs_embeds,
639
+ use_cache=use_cache,
640
+ cache_position=cache_position,
641
+ **kwargs,
642
+ )
643
+
644
+ hidden_states = outputs.last_hidden_state
645
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
646
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
647
+ logits = self.lm_head(hidden_states[:, slice_indices, :])
648
+
649
+ loss = None
650
+ if labels is not None:
651
+ loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs)
652
+
653
+ return CausalLMOutputWithPast(
654
+ loss=loss,
655
+ logits=logits,
656
+ past_key_values=outputs.past_key_values,
657
+ hidden_states=outputs.hidden_states,
658
+ attentions=outputs.attentions,
659
+ )
660
+
661
+ __all__ = [
662
+ "MiMoV2FlashForCausalLM"
663
+ ]
recipe.yaml ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ default_stage:
2
+ default_modifiers:
3
+ AWQModifier:
4
+ config_groups:
5
+ group_0:
6
+ targets: [Linear]
7
+ weights:
8
+ num_bits: 4
9
+ type: int
10
+ symmetric: true
11
+ group_size: 32
12
+ strategy: group
13
+ block_structure: null
14
+ dynamic: false
15
+ actorder: null
16
+ scale_dtype: null
17
+ zp_dtype: null
18
+ observer: minmax
19
+ observer_kwargs: {}
20
+ input_activations: null
21
+ output_activations: null
22
+ format: null
23
+ targets: [Linear]
24
+ ignore: [model.embed_tokens, 're:model[.]layers[.]0.*', 're:.*mlp[.]gate$', 're:.*self_attn[.]o_proj$',
25
+ model.norm, lm_head]
26
+ mappings:
27
+ - smooth_layer: re:.*input_layernorm$
28
+ balance_layers: ['re:.*q_proj$', 're:.*k_proj$', 're:.*v_proj$']
29
+ - smooth_layer: re:.*post_attention_layernorm$
30
+ balance_layers: ['re:.*gate_proj$', 're:.*up_proj$']
31
+ - smooth_layer: re:.*up_proj$
32
+ balance_layers: ['re:.*down_proj$']
33
+ offload_device: !!python/object/apply:torch.device [cpu]
34
+ duo_scaling: true
35
+ n_grid: 20
special_tokens_map.json ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "additional_special_tokens": [
3
+ "<|im_start|>",
4
+ "<|im_end|>",
5
+ "<|object_ref_start|>",
6
+ "<|object_ref_end|>",
7
+ "<|box_start|>",
8
+ "<|box_end|>",
9
+ "<|quad_start|>",
10
+ "<|quad_end|>",
11
+ "<|vision_start|>",
12
+ "<|vision_end|>",
13
+ "<|vision_pad|>",
14
+ "<|image_pad|>",
15
+ "<|video_pad|>"
16
+ ],
17
+ "eos_token": {
18
+ "content": "<|im_end|>",
19
+ "lstrip": false,
20
+ "normalized": false,
21
+ "rstrip": false,
22
+ "single_word": false
23
+ },
24
+ "pad_token": {
25
+ "content": "<|endoftext|>",
26
+ "lstrip": false,
27
+ "normalized": false,
28
+ "rstrip": false,
29
+ "single_word": false
30
+ }
31
+ }
tokenizer.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:aeb13307a71acd8fe81861d94ad54ab689df773318809eed3cbe794b4492dae4
3
+ size 11422654