cpatonn commited on
Commit
5236027
·
verified ·
1 Parent(s): 146002d

Add files using upload-large-folder tool

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 +2 -0
  2. chat_template.jinja +159 -0
  3. config.json +409 -0
  4. configuration_afmoe.py +133 -0
  5. generation_config.json +10 -0
  6. model-00001-of-00046.safetensors +3 -0
  7. model-00002-of-00046.safetensors +3 -0
  8. model-00003-of-00046.safetensors +3 -0
  9. model-00004-of-00046.safetensors +3 -0
  10. model-00005-of-00046.safetensors +3 -0
  11. model-00006-of-00046.safetensors +3 -0
  12. model-00007-of-00046.safetensors +3 -0
  13. model-00008-of-00046.safetensors +3 -0
  14. model-00011-of-00046.safetensors +3 -0
  15. model-00013-of-00046.safetensors +3 -0
  16. model-00014-of-00046.safetensors +3 -0
  17. model-00015-of-00046.safetensors +3 -0
  18. model-00017-of-00046.safetensors +3 -0
  19. model-00018-of-00046.safetensors +3 -0
  20. model-00019-of-00046.safetensors +3 -0
  21. model-00021-of-00046.safetensors +3 -0
  22. model-00022-of-00046.safetensors +3 -0
  23. model-00023-of-00046.safetensors +3 -0
  24. model-00024-of-00046.safetensors +3 -0
  25. model-00025-of-00046.safetensors +3 -0
  26. model-00026-of-00046.safetensors +3 -0
  27. model-00027-of-00046.safetensors +3 -0
  28. model-00028-of-00046.safetensors +3 -0
  29. model-00029-of-00046.safetensors +3 -0
  30. model-00030-of-00046.safetensors +3 -0
  31. model-00031-of-00046.safetensors +3 -0
  32. model-00032-of-00046.safetensors +3 -0
  33. model-00033-of-00046.safetensors +3 -0
  34. model-00034-of-00046.safetensors +3 -0
  35. model-00035-of-00046.safetensors +3 -0
  36. model-00037-of-00046.safetensors +3 -0
  37. model-00038-of-00046.safetensors +3 -0
  38. model-00039-of-00046.safetensors +3 -0
  39. model-00040-of-00046.safetensors +3 -0
  40. model-00041-of-00046.safetensors +3 -0
  41. model-00042-of-00046.safetensors +3 -0
  42. model-00043-of-00046.safetensors +3 -0
  43. model-00044-of-00046.safetensors +3 -0
  44. model-00045-of-00046.safetensors +3 -0
  45. model-00046-of-00046.safetensors +3 -0
  46. model.safetensors.index.json +3 -0
  47. modeling_afmoe.py +680 -0
  48. recipe.yaml +45 -0
  49. special_tokens_map.json +23 -0
  50. tokenizer.json +3 -0
.gitattributes CHANGED
@@ -33,3 +33,5 @@ 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
37
+ model.safetensors.index.json filter=lfs diff=lfs merge=lfs -text
chat_template.jinja ADDED
@@ -0,0 +1,159 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <|begin_of_text|>{%- macro render_extra_keys(json_dict, handled_keys) -%}
2
+ {%- if json_dict is mapping %}
3
+ {%- for json_key in json_dict if json_key not in handled_keys %}
4
+ {%- if json_dict[json_key] is mapping or (json_dict[json_key] is sequence and json_dict[json_key] is not string) %}
5
+ {{- '\n<' ~ json_key ~ '>' ~ (json_dict[json_key] | tojson | safe) ~ '</' ~ json_key ~ '>' }}
6
+ {%- else %}
7
+ {{- '\n<' ~ json_key ~ '>' ~ (json_dict[json_key] | string) ~ '</' ~ json_key ~ '>' }}
8
+ {%- endif %}
9
+ {%- endfor %}
10
+ {%- endif %}
11
+ {%- endmacro -%}
12
+
13
+ {%- macro render_tool_call(raw_tool_call) -%}
14
+ {%- if raw_tool_call.function is defined and raw_tool_call.function is mapping %}
15
+ {%- set tool_call = raw_tool_call.function %}
16
+ {%- else %}
17
+ {%- set tool_call = raw_tool_call %}
18
+ {%- endif %}
19
+ {{- '<tool_call>\n<function=' + (tool_call.name | default('') | string) + '>\n' }}
20
+ {%- if tool_call.arguments is defined and tool_call.arguments is mapping %}
21
+ {%- for args_name, args_value in tool_call.arguments.items() %}
22
+ {{- '<parameter=' + (args_name | string) + '>\n' }}
23
+ {%- if args_value is mapping or (args_value is sequence and args_value is not string) %}
24
+ {{- args_value | tojson | safe }}
25
+ {%- else %}
26
+ {{- args_value | string }}
27
+ {%- endif %}
28
+ {{- '\n</parameter>\n' }}
29
+ {%- endfor %}
30
+ {%- endif %}
31
+ {{- '</function>\n</tool_call>' }}
32
+ {%- endmacro -%}
33
+
34
+ {%- set system_message = none %}
35
+ {%- if messages and messages[0]["role"] == "system" %}
36
+ {%- set system_message = messages[0]["content"] %}
37
+ {%- set loop_messages = messages[1:] %}
38
+ {%- else %}
39
+ {%- set loop_messages = messages %}
40
+ {%- endif %}
41
+
42
+ {%- if not tools is defined %}
43
+ {%- set tools = [] %}
44
+ {%- endif %}
45
+ {%- set has_tools = tools is iterable and tools is not string and tools | length > 0 %}
46
+
47
+ {%- if system_message is not none or has_tools %}
48
+ {{- '<|im_start|>system\n' }}
49
+ {%- if system_message is not none %}
50
+ {{- system_message }}
51
+ {%- else %}
52
+ {{- "You are Trinity Large, a helpful assistant developed by Arcee AI, that can interact with a computer to solve tasks." }}
53
+ {%- endif %}
54
+ {%- if has_tools %}
55
+ {{- "\n\n# Tools\n\nYou have access to the following functions:\n\n<tools>" }}
56
+ {%- for tool in tools %}
57
+ {%- if tool.function is defined and tool.function is mapping %}
58
+ {%- set tool = tool.function %}
59
+ {%- endif %}
60
+ {{- '\n<function>\n<name>' ~ (tool.name | default('') | string) ~ '</name>' }}
61
+ {%- if tool.description is defined and tool.description is not none %}
62
+ {{- '\n<description>' ~ (tool.description | string | trim) ~ '</description>' }}
63
+ {%- endif %}
64
+ {{- '\n<parameters>' }}
65
+ {%- if tool.parameters is defined and tool.parameters is mapping and tool.parameters.properties is defined and tool.parameters.properties is mapping %}
66
+ {%- for param_name, param_fields in tool.parameters.properties.items() %}
67
+ {{- '\n<parameter>\n<name>' ~ (param_name | string) ~ '</name>' }}
68
+ {%- if param_fields is mapping and param_fields.type is defined and param_fields.type is not none %}
69
+ {{- '\n<type>' ~ (param_fields.type | string) ~ '</type>' }}
70
+ {%- endif %}
71
+ {%- if param_fields is mapping and param_fields.description is defined and param_fields.description is not none %}
72
+ {{- '\n<description>' ~ (param_fields.description | string | trim) ~ '</description>' }}
73
+ {%- endif %}
74
+ {%- if param_fields is mapping %}
75
+ {%- set handled_keys = ['name', 'type', 'description'] %}
76
+ {{- render_extra_keys(param_fields, handled_keys) }}
77
+ {%- endif %}
78
+ {{- '\n</parameter>' }}
79
+ {%- endfor %}
80
+ {%- endif %}
81
+ {%- if tool.parameters is defined %}
82
+ {%- set handled_keys = ['type', 'properties'] %}
83
+ {{- render_extra_keys(tool.parameters, handled_keys) }}
84
+ {%- endif %}
85
+ {{- '\n</parameters>' }}
86
+ {%- set handled_keys = ['type', 'name', 'description', 'parameters'] %}
87
+ {{- render_extra_keys(tool, handled_keys) }}
88
+ {{- '\n</function>' }}
89
+ {%- endfor %}
90
+ {{- "\n</tools>" }}
91
+ {{- '\n\nIf you choose to call a function ONLY reply in the following format with NO suffix:\n\n<tool_call>\n<function=example_function_name>\n<parameter=example_parameter_1>\nvalue_1\n</parameter>\n<parameter=example_parameter_2>\nThis is the value for the second parameter\nthat can span\nmultiple lines\n</parameter>\n</function>\n</tool_call>\n\n<IMPORTANT>\nReminder:\n- Function calls MUST follow the specified format: an inner <function=...></function> block must be nested within <tool_call></tool_call> XML tags\n- Required parameters MUST be specified\n- You may provide optional reasoning for your function call in natural language BEFORE the function call, but NOT after\n- If there is no function call available, answer the question like normal with your current knowledge and do not tell the user about function calls\n</IMPORTANT>' }}
92
+ {%- endif %}
93
+ {{- '<|im_end|>\n' }}
94
+ {%- endif %}
95
+
96
+ {%- for message in loop_messages %}
97
+ {%- set role = message.role | default('') %}
98
+ {%- if role == "assistant" %}
99
+ {%- set content_str = '' if message.content is none else (message.content | string) %}
100
+ {%- set trimmed_content = content_str | trim %}
101
+
102
+ {%- set has_reasoning_content = message.reasoning_content is defined %}
103
+ {%- set has_reasoning = has_reasoning_content or (message.reasoning is defined) %}
104
+
105
+ {%- if has_reasoning_content %}
106
+ {%- set reasoning_value = message.reasoning_content %}
107
+ {%- elif message.reasoning is defined %}
108
+ {%- set reasoning_value = message.reasoning %}
109
+ {%- else %}
110
+ {%- set reasoning_value = none %}
111
+ {%- endif %}
112
+
113
+ {%- set has_tool_calls = message.tool_calls is defined and message.tool_calls is iterable and message.tool_calls is not string and message.tool_calls | length > 0 %}
114
+
115
+ {{- '<|im_start|>assistant\n' }}
116
+ {%- if has_reasoning %}
117
+ {%- if reasoning_value %}
118
+ {{- '<think>' + (reasoning_value | string | trim) + '</think>' }}
119
+ {%- else %}
120
+ {{- '<think></think>' }}
121
+ {%- endif %}
122
+ {%- if trimmed_content %}
123
+ {{- '\n' + trimmed_content }}
124
+ {%- endif %}
125
+ {%- elif has_tool_calls %}
126
+ {%- if trimmed_content %}
127
+ {{- trimmed_content }}
128
+ {%- endif %}
129
+ {%- else %}
130
+ {{- content_str }}
131
+ {%- endif %}
132
+
133
+ {%- if has_tool_calls %}
134
+ {%- for tool_call in message.tool_calls %}
135
+ {%- set separator = '\n' if ((loop.first and (has_reasoning or trimmed_content)) or (not loop.first)) else '' -%}
136
+ {{- separator + render_tool_call(tool_call) }}
137
+ {%- endfor %}
138
+ {%- endif %}
139
+ {{- '<|im_end|>\n' }}
140
+ {%- elif role == "tool" or role == "observation" or role == "function" %}
141
+ {%- if loop.first or loop.previtem.role not in ["tool", "observation", "function"] %}
142
+ {{- '<|im_start|>user\n' }}
143
+ {%- endif %}
144
+ {{- '<tool_response>\n' }}
145
+ {{- '' if message.content is none else (message.content | string) }}
146
+ {{- '\n</tool_response>\n' }}
147
+ {%- if loop.last or loop.nextitem.role not in ["tool", "observation", "function"] %}
148
+ {{- '<|im_end|>\n' }}
149
+ {%- endif %}
150
+ {%- else %}
151
+ {{- '<|im_start|>' + (role | string) }}
152
+ {{- '\n' + ('' if message.content is none else (message.content | string)) }}
153
+ {{- '<|im_end|>\n' }}
154
+ {%- endif %}
155
+ {%- endfor %}
156
+
157
+ {%- if add_generation_prompt %}
158
+ {{- '<|im_start|>assistant\n<think>' }}
159
+ {%- endif %}
config.json ADDED
@@ -0,0 +1,409 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "AfmoeForCausalLM"
4
+ ],
5
+ "attention_dropout": 0.0,
6
+ "auto_map": {
7
+ "AutoConfig": "configuration_afmoe.AfmoeConfig",
8
+ "AutoModel": "modeling_afmoe.AfmoeModel",
9
+ "AutoModelForCausalLM": "modeling_afmoe.AfmoeForCausalLM"
10
+ },
11
+ "dtype": "bfloat16",
12
+ "global_attn_every_n_layers": 4,
13
+ "head_dim": 128,
14
+ "hidden_act": "silu",
15
+ "hidden_size": 3072,
16
+ "initializer_range": 0.02,
17
+ "intermediate_size": 12288,
18
+ "layer_types": [
19
+ "sliding_attention",
20
+ "sliding_attention",
21
+ "sliding_attention",
22
+ "full_attention",
23
+ "sliding_attention",
24
+ "sliding_attention",
25
+ "sliding_attention",
26
+ "full_attention",
27
+ "sliding_attention",
28
+ "sliding_attention",
29
+ "sliding_attention",
30
+ "full_attention",
31
+ "sliding_attention",
32
+ "sliding_attention",
33
+ "sliding_attention",
34
+ "full_attention",
35
+ "sliding_attention",
36
+ "sliding_attention",
37
+ "sliding_attention",
38
+ "full_attention",
39
+ "sliding_attention",
40
+ "sliding_attention",
41
+ "sliding_attention",
42
+ "full_attention",
43
+ "sliding_attention",
44
+ "sliding_attention",
45
+ "sliding_attention",
46
+ "full_attention",
47
+ "sliding_attention",
48
+ "sliding_attention",
49
+ "sliding_attention",
50
+ "full_attention",
51
+ "sliding_attention",
52
+ "sliding_attention",
53
+ "sliding_attention",
54
+ "full_attention",
55
+ "sliding_attention",
56
+ "sliding_attention",
57
+ "sliding_attention",
58
+ "full_attention",
59
+ "sliding_attention",
60
+ "sliding_attention",
61
+ "sliding_attention",
62
+ "full_attention",
63
+ "sliding_attention",
64
+ "sliding_attention",
65
+ "sliding_attention",
66
+ "full_attention",
67
+ "sliding_attention",
68
+ "sliding_attention",
69
+ "sliding_attention",
70
+ "full_attention",
71
+ "sliding_attention",
72
+ "sliding_attention",
73
+ "sliding_attention",
74
+ "full_attention",
75
+ "sliding_attention",
76
+ "sliding_attention",
77
+ "sliding_attention",
78
+ "full_attention"
79
+ ],
80
+ "load_balance_coeff": 5e-05,
81
+ "max_position_embeddings": 262144,
82
+ "model_type": "afmoe",
83
+ "moe_intermediate_size": 3072,
84
+ "mup_enabled": true,
85
+ "n_group": 1,
86
+ "num_attention_heads": 48,
87
+ "num_dense_layers": 6,
88
+ "num_expert_groups": 1,
89
+ "num_experts": 256,
90
+ "num_experts_per_tok": 4,
91
+ "num_hidden_layers": 60,
92
+ "num_key_value_heads": 8,
93
+ "num_limited_groups": 1,
94
+ "num_shared_experts": 1,
95
+ "quantization_config": {
96
+ "config_groups": {
97
+ "group_0": {
98
+ "format": "pack-quantized",
99
+ "input_activations": null,
100
+ "output_activations": null,
101
+ "targets": [
102
+ "Linear"
103
+ ],
104
+ "weights": {
105
+ "actorder": null,
106
+ "block_structure": null,
107
+ "dynamic": false,
108
+ "group_size": 32,
109
+ "num_bits": 4,
110
+ "observer": "mse",
111
+ "observer_kwargs": {},
112
+ "scale_dtype": null,
113
+ "strategy": "group",
114
+ "symmetric": true,
115
+ "type": "int",
116
+ "zp_dtype": null
117
+ }
118
+ }
119
+ },
120
+ "format": "pack-quantized",
121
+ "global_compression_ratio": null,
122
+ "ignore": [
123
+ "model.layers.0.self_attn.q_proj",
124
+ "model.layers.0.self_attn.k_proj",
125
+ "model.layers.0.self_attn.v_proj",
126
+ "model.layers.0.self_attn.o_proj",
127
+ "model.layers.0.self_attn.gate_proj",
128
+ "model.layers.0.mlp.gate_proj",
129
+ "model.layers.0.mlp.up_proj",
130
+ "model.layers.0.mlp.down_proj",
131
+ "model.layers.1.self_attn.q_proj",
132
+ "model.layers.1.self_attn.k_proj",
133
+ "model.layers.1.self_attn.v_proj",
134
+ "model.layers.1.self_attn.o_proj",
135
+ "model.layers.1.self_attn.gate_proj",
136
+ "model.layers.1.mlp.gate_proj",
137
+ "model.layers.1.mlp.up_proj",
138
+ "model.layers.1.mlp.down_proj",
139
+ "model.layers.2.self_attn.q_proj",
140
+ "model.layers.2.self_attn.k_proj",
141
+ "model.layers.2.self_attn.v_proj",
142
+ "model.layers.2.self_attn.o_proj",
143
+ "model.layers.2.self_attn.gate_proj",
144
+ "model.layers.2.mlp.gate_proj",
145
+ "model.layers.2.mlp.up_proj",
146
+ "model.layers.2.mlp.down_proj",
147
+ "model.layers.3.self_attn.q_proj",
148
+ "model.layers.3.self_attn.k_proj",
149
+ "model.layers.3.self_attn.v_proj",
150
+ "model.layers.3.self_attn.o_proj",
151
+ "model.layers.3.self_attn.gate_proj",
152
+ "model.layers.3.mlp.gate_proj",
153
+ "model.layers.3.mlp.up_proj",
154
+ "model.layers.3.mlp.down_proj",
155
+ "model.layers.4.self_attn.q_proj",
156
+ "model.layers.4.self_attn.k_proj",
157
+ "model.layers.4.self_attn.v_proj",
158
+ "model.layers.4.self_attn.o_proj",
159
+ "model.layers.4.self_attn.gate_proj",
160
+ "model.layers.4.mlp.gate_proj",
161
+ "model.layers.4.mlp.up_proj",
162
+ "model.layers.4.mlp.down_proj",
163
+ "model.layers.5.self_attn.q_proj",
164
+ "model.layers.5.self_attn.k_proj",
165
+ "model.layers.5.self_attn.v_proj",
166
+ "model.layers.5.self_attn.o_proj",
167
+ "model.layers.5.self_attn.gate_proj",
168
+ "model.layers.5.mlp.gate_proj",
169
+ "model.layers.5.mlp.up_proj",
170
+ "model.layers.5.mlp.down_proj",
171
+ "model.layers.6.mlp.router.gate",
172
+ "model.layers.6.mlp.shared_experts.gate_proj",
173
+ "model.layers.6.mlp.shared_experts.up_proj",
174
+ "model.layers.6.mlp.shared_experts.down_proj",
175
+ "model.layers.7.mlp.router.gate",
176
+ "model.layers.7.mlp.shared_experts.gate_proj",
177
+ "model.layers.7.mlp.shared_experts.up_proj",
178
+ "model.layers.7.mlp.shared_experts.down_proj",
179
+ "model.layers.8.mlp.router.gate",
180
+ "model.layers.8.mlp.shared_experts.gate_proj",
181
+ "model.layers.8.mlp.shared_experts.up_proj",
182
+ "model.layers.8.mlp.shared_experts.down_proj",
183
+ "model.layers.9.mlp.router.gate",
184
+ "model.layers.9.mlp.shared_experts.gate_proj",
185
+ "model.layers.9.mlp.shared_experts.up_proj",
186
+ "model.layers.9.mlp.shared_experts.down_proj",
187
+ "model.layers.10.mlp.router.gate",
188
+ "model.layers.10.mlp.shared_experts.gate_proj",
189
+ "model.layers.10.mlp.shared_experts.up_proj",
190
+ "model.layers.10.mlp.shared_experts.down_proj",
191
+ "model.layers.11.mlp.router.gate",
192
+ "model.layers.11.mlp.shared_experts.gate_proj",
193
+ "model.layers.11.mlp.shared_experts.up_proj",
194
+ "model.layers.11.mlp.shared_experts.down_proj",
195
+ "model.layers.12.mlp.router.gate",
196
+ "model.layers.12.mlp.shared_experts.gate_proj",
197
+ "model.layers.12.mlp.shared_experts.up_proj",
198
+ "model.layers.12.mlp.shared_experts.down_proj",
199
+ "model.layers.13.mlp.router.gate",
200
+ "model.layers.13.mlp.shared_experts.gate_proj",
201
+ "model.layers.13.mlp.shared_experts.up_proj",
202
+ "model.layers.13.mlp.shared_experts.down_proj",
203
+ "model.layers.14.mlp.router.gate",
204
+ "model.layers.14.mlp.shared_experts.gate_proj",
205
+ "model.layers.14.mlp.shared_experts.up_proj",
206
+ "model.layers.14.mlp.shared_experts.down_proj",
207
+ "model.layers.15.mlp.router.gate",
208
+ "model.layers.15.mlp.shared_experts.gate_proj",
209
+ "model.layers.15.mlp.shared_experts.up_proj",
210
+ "model.layers.15.mlp.shared_experts.down_proj",
211
+ "model.layers.16.mlp.router.gate",
212
+ "model.layers.16.mlp.shared_experts.gate_proj",
213
+ "model.layers.16.mlp.shared_experts.up_proj",
214
+ "model.layers.16.mlp.shared_experts.down_proj",
215
+ "model.layers.17.mlp.router.gate",
216
+ "model.layers.17.mlp.shared_experts.gate_proj",
217
+ "model.layers.17.mlp.shared_experts.up_proj",
218
+ "model.layers.17.mlp.shared_experts.down_proj",
219
+ "model.layers.18.mlp.router.gate",
220
+ "model.layers.18.mlp.shared_experts.gate_proj",
221
+ "model.layers.18.mlp.shared_experts.up_proj",
222
+ "model.layers.18.mlp.shared_experts.down_proj",
223
+ "model.layers.19.mlp.router.gate",
224
+ "model.layers.19.mlp.shared_experts.gate_proj",
225
+ "model.layers.19.mlp.shared_experts.up_proj",
226
+ "model.layers.19.mlp.shared_experts.down_proj",
227
+ "model.layers.20.mlp.router.gate",
228
+ "model.layers.20.mlp.shared_experts.gate_proj",
229
+ "model.layers.20.mlp.shared_experts.up_proj",
230
+ "model.layers.20.mlp.shared_experts.down_proj",
231
+ "model.layers.21.mlp.router.gate",
232
+ "model.layers.21.mlp.shared_experts.gate_proj",
233
+ "model.layers.21.mlp.shared_experts.up_proj",
234
+ "model.layers.21.mlp.shared_experts.down_proj",
235
+ "model.layers.22.mlp.router.gate",
236
+ "model.layers.22.mlp.shared_experts.gate_proj",
237
+ "model.layers.22.mlp.shared_experts.up_proj",
238
+ "model.layers.22.mlp.shared_experts.down_proj",
239
+ "model.layers.23.mlp.router.gate",
240
+ "model.layers.23.mlp.shared_experts.gate_proj",
241
+ "model.layers.23.mlp.shared_experts.up_proj",
242
+ "model.layers.23.mlp.shared_experts.down_proj",
243
+ "model.layers.24.mlp.router.gate",
244
+ "model.layers.24.mlp.shared_experts.gate_proj",
245
+ "model.layers.24.mlp.shared_experts.up_proj",
246
+ "model.layers.24.mlp.shared_experts.down_proj",
247
+ "model.layers.25.mlp.router.gate",
248
+ "model.layers.25.mlp.shared_experts.gate_proj",
249
+ "model.layers.25.mlp.shared_experts.up_proj",
250
+ "model.layers.25.mlp.shared_experts.down_proj",
251
+ "model.layers.26.mlp.router.gate",
252
+ "model.layers.26.mlp.shared_experts.gate_proj",
253
+ "model.layers.26.mlp.shared_experts.up_proj",
254
+ "model.layers.26.mlp.shared_experts.down_proj",
255
+ "model.layers.27.mlp.router.gate",
256
+ "model.layers.27.mlp.shared_experts.gate_proj",
257
+ "model.layers.27.mlp.shared_experts.up_proj",
258
+ "model.layers.27.mlp.shared_experts.down_proj",
259
+ "model.layers.28.mlp.router.gate",
260
+ "model.layers.28.mlp.shared_experts.gate_proj",
261
+ "model.layers.28.mlp.shared_experts.up_proj",
262
+ "model.layers.28.mlp.shared_experts.down_proj",
263
+ "model.layers.29.mlp.router.gate",
264
+ "model.layers.29.mlp.shared_experts.gate_proj",
265
+ "model.layers.29.mlp.shared_experts.up_proj",
266
+ "model.layers.29.mlp.shared_experts.down_proj",
267
+ "model.layers.30.mlp.router.gate",
268
+ "model.layers.30.mlp.shared_experts.gate_proj",
269
+ "model.layers.30.mlp.shared_experts.up_proj",
270
+ "model.layers.30.mlp.shared_experts.down_proj",
271
+ "model.layers.31.mlp.router.gate",
272
+ "model.layers.31.mlp.shared_experts.gate_proj",
273
+ "model.layers.31.mlp.shared_experts.up_proj",
274
+ "model.layers.31.mlp.shared_experts.down_proj",
275
+ "model.layers.32.mlp.router.gate",
276
+ "model.layers.32.mlp.shared_experts.gate_proj",
277
+ "model.layers.32.mlp.shared_experts.up_proj",
278
+ "model.layers.32.mlp.shared_experts.down_proj",
279
+ "model.layers.33.mlp.router.gate",
280
+ "model.layers.33.mlp.shared_experts.gate_proj",
281
+ "model.layers.33.mlp.shared_experts.up_proj",
282
+ "model.layers.33.mlp.shared_experts.down_proj",
283
+ "model.layers.34.mlp.router.gate",
284
+ "model.layers.34.mlp.shared_experts.gate_proj",
285
+ "model.layers.34.mlp.shared_experts.up_proj",
286
+ "model.layers.34.mlp.shared_experts.down_proj",
287
+ "model.layers.35.mlp.router.gate",
288
+ "model.layers.35.mlp.shared_experts.gate_proj",
289
+ "model.layers.35.mlp.shared_experts.up_proj",
290
+ "model.layers.35.mlp.shared_experts.down_proj",
291
+ "model.layers.36.mlp.router.gate",
292
+ "model.layers.36.mlp.shared_experts.gate_proj",
293
+ "model.layers.36.mlp.shared_experts.up_proj",
294
+ "model.layers.36.mlp.shared_experts.down_proj",
295
+ "model.layers.37.mlp.router.gate",
296
+ "model.layers.37.mlp.shared_experts.gate_proj",
297
+ "model.layers.37.mlp.shared_experts.up_proj",
298
+ "model.layers.37.mlp.shared_experts.down_proj",
299
+ "model.layers.38.mlp.router.gate",
300
+ "model.layers.38.mlp.shared_experts.gate_proj",
301
+ "model.layers.38.mlp.shared_experts.up_proj",
302
+ "model.layers.38.mlp.shared_experts.down_proj",
303
+ "model.layers.39.mlp.router.gate",
304
+ "model.layers.39.mlp.shared_experts.gate_proj",
305
+ "model.layers.39.mlp.shared_experts.up_proj",
306
+ "model.layers.39.mlp.shared_experts.down_proj",
307
+ "model.layers.40.mlp.router.gate",
308
+ "model.layers.40.mlp.shared_experts.gate_proj",
309
+ "model.layers.40.mlp.shared_experts.up_proj",
310
+ "model.layers.40.mlp.shared_experts.down_proj",
311
+ "model.layers.41.mlp.router.gate",
312
+ "model.layers.41.mlp.shared_experts.gate_proj",
313
+ "model.layers.41.mlp.shared_experts.up_proj",
314
+ "model.layers.41.mlp.shared_experts.down_proj",
315
+ "model.layers.42.mlp.router.gate",
316
+ "model.layers.42.mlp.shared_experts.gate_proj",
317
+ "model.layers.42.mlp.shared_experts.up_proj",
318
+ "model.layers.42.mlp.shared_experts.down_proj",
319
+ "model.layers.43.mlp.router.gate",
320
+ "model.layers.43.mlp.shared_experts.gate_proj",
321
+ "model.layers.43.mlp.shared_experts.up_proj",
322
+ "model.layers.43.mlp.shared_experts.down_proj",
323
+ "model.layers.44.mlp.router.gate",
324
+ "model.layers.44.mlp.shared_experts.gate_proj",
325
+ "model.layers.44.mlp.shared_experts.up_proj",
326
+ "model.layers.44.mlp.shared_experts.down_proj",
327
+ "model.layers.45.mlp.router.gate",
328
+ "model.layers.45.mlp.shared_experts.gate_proj",
329
+ "model.layers.45.mlp.shared_experts.up_proj",
330
+ "model.layers.45.mlp.shared_experts.down_proj",
331
+ "model.layers.46.mlp.router.gate",
332
+ "model.layers.46.mlp.shared_experts.gate_proj",
333
+ "model.layers.46.mlp.shared_experts.up_proj",
334
+ "model.layers.46.mlp.shared_experts.down_proj",
335
+ "model.layers.47.mlp.router.gate",
336
+ "model.layers.47.mlp.shared_experts.gate_proj",
337
+ "model.layers.47.mlp.shared_experts.up_proj",
338
+ "model.layers.47.mlp.shared_experts.down_proj",
339
+ "model.layers.48.mlp.router.gate",
340
+ "model.layers.48.mlp.shared_experts.gate_proj",
341
+ "model.layers.48.mlp.shared_experts.up_proj",
342
+ "model.layers.48.mlp.shared_experts.down_proj",
343
+ "model.layers.49.mlp.router.gate",
344
+ "model.layers.49.mlp.shared_experts.gate_proj",
345
+ "model.layers.49.mlp.shared_experts.up_proj",
346
+ "model.layers.49.mlp.shared_experts.down_proj",
347
+ "model.layers.50.mlp.router.gate",
348
+ "model.layers.50.mlp.shared_experts.gate_proj",
349
+ "model.layers.50.mlp.shared_experts.up_proj",
350
+ "model.layers.50.mlp.shared_experts.down_proj",
351
+ "model.layers.51.mlp.router.gate",
352
+ "model.layers.51.mlp.shared_experts.gate_proj",
353
+ "model.layers.51.mlp.shared_experts.up_proj",
354
+ "model.layers.51.mlp.shared_experts.down_proj",
355
+ "model.layers.52.mlp.router.gate",
356
+ "model.layers.52.mlp.shared_experts.gate_proj",
357
+ "model.layers.52.mlp.shared_experts.up_proj",
358
+ "model.layers.52.mlp.shared_experts.down_proj",
359
+ "model.layers.53.mlp.router.gate",
360
+ "model.layers.53.mlp.shared_experts.gate_proj",
361
+ "model.layers.53.mlp.shared_experts.up_proj",
362
+ "model.layers.53.mlp.shared_experts.down_proj",
363
+ "model.layers.54.mlp.router.gate",
364
+ "model.layers.54.mlp.shared_experts.gate_proj",
365
+ "model.layers.54.mlp.shared_experts.up_proj",
366
+ "model.layers.54.mlp.shared_experts.down_proj",
367
+ "model.layers.55.mlp.router.gate",
368
+ "model.layers.55.mlp.shared_experts.gate_proj",
369
+ "model.layers.55.mlp.shared_experts.up_proj",
370
+ "model.layers.55.mlp.shared_experts.down_proj",
371
+ "model.layers.56.mlp.router.gate",
372
+ "model.layers.56.mlp.shared_experts.gate_proj",
373
+ "model.layers.56.mlp.shared_experts.up_proj",
374
+ "model.layers.56.mlp.shared_experts.down_proj",
375
+ "model.layers.57.mlp.router.gate",
376
+ "model.layers.57.mlp.shared_experts.gate_proj",
377
+ "model.layers.57.mlp.shared_experts.up_proj",
378
+ "model.layers.57.mlp.shared_experts.down_proj",
379
+ "model.layers.58.mlp.router.gate",
380
+ "model.layers.58.mlp.shared_experts.gate_proj",
381
+ "model.layers.58.mlp.shared_experts.up_proj",
382
+ "model.layers.58.mlp.shared_experts.down_proj",
383
+ "model.layers.59.mlp.router.gate",
384
+ "model.layers.59.mlp.shared_experts.gate_proj",
385
+ "model.layers.59.mlp.shared_experts.up_proj",
386
+ "model.layers.59.mlp.shared_experts.down_proj",
387
+ "lm_head"
388
+ ],
389
+ "kv_cache_scheme": null,
390
+ "quant_method": "compressed-tensors",
391
+ "quantization_status": "compressed",
392
+ "sparsity_config": {},
393
+ "transform_config": {},
394
+ "version": "0.14.1.a20260326"
395
+ },
396
+ "rms_norm_eps": 1e-05,
397
+ "rope_scaling": null,
398
+ "rope_theta": 10000,
399
+ "route_norm": true,
400
+ "route_scale": 2.448,
401
+ "score_func": "sigmoid",
402
+ "sliding_window": 4096,
403
+ "tie_word_embeddings": false,
404
+ "topk_group": 1,
405
+ "transformers_version": "4.57.6",
406
+ "use_cache": true,
407
+ "use_grouped_mm": true,
408
+ "vocab_size": 200192
409
+ }
configuration_afmoe.py ADDED
@@ -0,0 +1,133 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ from transformers.configuration_utils import PretrainedConfig
16
+ from transformers.modeling_rope_utils import rope_config_validation
17
+ from transformers.configuration_utils import layer_type_validation
18
+ from transformers.utils import logging
19
+
20
+ logger = logging.get_logger(__name__)
21
+
22
+ class AfmoeConfig(PretrainedConfig):
23
+ """
24
+ n_group (`int`, *optional*, defaults to 1):
25
+ Number of groups for routed experts.
26
+ topk_group (`int`, *optional*, defaults to 1):
27
+ Number of selected groups for each token(for each token, ensuring the selected experts is only within `topk_group` groups).
28
+ """
29
+ model_type = "afmoe"
30
+ base_model_pp_plan = {
31
+ "embed_tokens": (["input_ids"], ["inputs_embeds"]),
32
+ "layers": (["hidden_states", "attention_mask"], ["hidden_states"]),
33
+ "norm": (["hidden_states"], ["hidden_states"]),
34
+ }
35
+
36
+ def __init__(
37
+ self,
38
+ num_hidden_layers: int = 32,
39
+ vocab_size: int = 200192,
40
+ hidden_size: int = 2048,
41
+ intermediate_size: int = 6144,
42
+ moe_intermediate_size=1408,
43
+ num_dense_layers=1,
44
+ num_attention_heads=16,
45
+ num_key_value_heads=None,
46
+ head_dim=128,
47
+ hidden_act="silu",
48
+ max_position_embeddings=16384,
49
+ initializer_range=0.02,
50
+ rms_norm_eps=1e-5,
51
+ use_cache=True,
52
+ tie_word_embeddings=False,
53
+ rope_theta=10000.0,
54
+ rope_scaling=None,
55
+ num_experts=64,
56
+ num_experts_per_tok=6,
57
+ num_shared_experts=2,
58
+ num_expert_groups=1,
59
+ num_limited_groups=1,
60
+ score_func="sigmoid",
61
+ route_norm=True,
62
+ route_scale=1.0,
63
+ global_attn_every_n_layers=4,
64
+ sliding_window=1024,
65
+ mup_enabled=False,
66
+ layer_types=None,
67
+ attention_dropout: float = 0.0,
68
+ n_group: int = 1,
69
+ topk_group: int = 1,
70
+ **kwargs,
71
+ ):
72
+ self.vocab_size = vocab_size
73
+ self.max_position_embeddings = max_position_embeddings
74
+ self.hidden_size = hidden_size
75
+ self.intermediate_size = intermediate_size
76
+ self.num_hidden_layers = num_hidden_layers
77
+ self.num_dense_layers = num_dense_layers
78
+ self.num_attention_heads = num_attention_heads
79
+ self.head_dim = head_dim
80
+ self.hidden_act = hidden_act
81
+ self.initializer_range = initializer_range
82
+ self.rms_norm_eps = rms_norm_eps
83
+ self.use_cache = use_cache
84
+ self.rope_theta = rope_theta
85
+ self.rope_scaling = rope_scaling
86
+
87
+
88
+ # MoE specific
89
+ self.moe_intermediate_size = moe_intermediate_size
90
+ self.num_experts_per_tok = num_experts_per_tok
91
+ self.n_group = n_group
92
+ self.topk_group = topk_group
93
+ self.num_experts = num_experts
94
+ self.num_shared_experts = num_shared_experts
95
+ self.num_expert_groups = num_expert_groups
96
+ self.num_limited_groups = num_limited_groups
97
+ self.score_func = score_func
98
+ self.route_norm = route_norm
99
+ self.route_scale = route_scale
100
+
101
+
102
+ # Attention specific
103
+ self.attention_dropout = attention_dropout
104
+ self.global_attn_every_n_layers = global_attn_every_n_layers
105
+ self.sliding_window = sliding_window
106
+ self.layer_types = layer_types
107
+ if self.layer_types is None:
108
+ self.layer_types = [
109
+ "sliding_attention" if bool((i + 1) % global_attn_every_n_layers) else "full_attention" for i in range(self.num_hidden_layers)
110
+ ]
111
+ layer_type_validation(self.layer_types)
112
+
113
+ # muP specific
114
+ self.mup_enabled = mup_enabled
115
+
116
+ if num_key_value_heads is None:
117
+ num_key_value_heads = num_attention_heads
118
+
119
+ self.num_key_value_heads = num_key_value_heads
120
+
121
+
122
+ # Validate rope configs
123
+ if self.rope_scaling is not None and "type" in self.rope_scaling:
124
+ self.rope_scaling["rope_type"] = self.rope_scaling["type"]
125
+ rope_config_validation(self)
126
+
127
+ super().__init__(
128
+ tie_word_embeddings=tie_word_embeddings,
129
+ **kwargs,
130
+ )
131
+
132
+
133
+ __all__ = ["AfmoeConfig"]
generation_config.json ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "bos_token_id": 0,
4
+ "do_sample": true,
5
+ "eos_token_id": 3,
6
+ "pad_token_id": 12,
7
+ "temperature": 0.8,
8
+ "top_p": 0.8,
9
+ "transformers_version": "4.57.6"
10
+ }
model-00001-of-00046.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:34aef3d4b81b7026849e8077579ef301f61e91743dd4cf003791ed05b11b79a3
3
+ size 4999059968
model-00002-of-00046.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:33f2e07db3ded6967c8e875179ea8fc6d6d13b69549a05edbe9e212ef0c5d62c
3
+ size 4998946688
model-00003-of-00046.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9b9bd079f4fd6929f14558ac22f523ba90596915e77bb32914235229218cd4fb
3
+ size 4998946704
model-00004-of-00046.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6e97bdd62a072586abcda4df2f10ec60f48d9cd21d6604fa7e99fdfbb3f0c96a
3
+ size 4998946704
model-00005-of-00046.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d29ebcf9553c4da332fe876073dd504abe3e646535722e10c0edfd67904e985f
3
+ size 4997005120
model-00006-of-00046.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3a7ae1f4885feaeeac8781187d2b5c620e45678cc87850e800e82932a4bdc2a9
3
+ size 4998949032
model-00007-of-00046.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:39d0e8eb5e43b52cca1ee434b8e73805ea9b94ea29a12b2c3f826f647c0945c2
3
+ size 4998949472
model-00008-of-00046.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2b1a807a24ee40654bfbd47fe8322511548bafe52742ae89b9dba4fff285c3aa
3
+ size 4998949504
model-00011-of-00046.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7957ae1d4961fd09eb7eb71e4be94cbb36ade6e722d37058cf71d601a67ae194
3
+ size 4998949032
model-00013-of-00046.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:abaf778583ab3faa3f6f4361aaa9e29b3daaca776624492be40ec84e9d633e31
3
+ size 4998949504
model-00014-of-00046.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5c7c723e8ef7b361aa8b1d81c98631e8962e478324442cc51065e8ca785c796d
3
+ size 4998949504
model-00015-of-00046.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:481557f90424890bc95b469a649de0986acef8d6d6c17e4bbf0237f6740d8f37
3
+ size 4997005168
model-00017-of-00046.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:388fb52f60bfc9ca7cf63119d1a2de94527abed51d097eff05e0b141e2472e37
3
+ size 4998949432
model-00018-of-00046.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c9326ac5f4f15f53928bf106ed6c3e03d365195f2fc05d8baf0256b24e0f0b23
3
+ size 4998949504
model-00019-of-00046.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:97e36e455186e8153ccae536648eafde437df509bebcebc993a878d4aba21edc
3
+ size 4998949504
model-00021-of-00046.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:582db04c5b3ea1051e0e99bd090c464cace58f05f78f0c1f43e8ce8416c54d5c
3
+ size 4998949032
model-00022-of-00046.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e38a4399d140bd1e25584935b2d8783c5554acc7a9bed0d4b5356c6f27d91528
3
+ size 4998949416
model-00023-of-00046.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e6bff642d544bd49710813e6b29d1691b99dc0cd377bb44cd1def79bcd78c528
3
+ size 4998949504
model-00024-of-00046.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:34c5d901a06b0d1e09edcc2bf1a98c2ffca439b54c399fb269eea77d99869cc2
3
+ size 4998949504
model-00025-of-00046.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:97cd343220ab732aefe21bb582ce5b5bad8f1e2a8245f92ced2b6650f5cf7a46
3
+ size 4997005208
model-00026-of-00046.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a0eefd0933c0793a75f5964c331ed1273272c5d1d0000f0cb341996d84d916ce
3
+ size 4998949032
model-00027-of-00046.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:352cab91ac067d183b74058a64cf7748ae9547c972d99adcc12b17a54d24cc2d
3
+ size 4998949400
model-00028-of-00046.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:74c9b01f67aba4421a6e1bfc214dff8724d4a9b00203cf2e13d7223d1ddfec82
3
+ size 4998949504
model-00029-of-00046.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e393104e058d93d6aebd7dc0bdd152d7ec63c6197423497299fb958839c1a61a
3
+ size 4998949504
model-00030-of-00046.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:957db25537bba8925f8fb8f07fa9a36068d63cb1d73d0e6ad32a5e842801089c
3
+ size 4997005224
model-00031-of-00046.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a3e3b6d8bb82fedc80cfd2bec8321f2a3960fa7834e53ab6832ff27734c7c882
3
+ size 4998949032
model-00032-of-00046.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:667e173f53b268fb35e34c4d47c1416e1634ef899ad9a2438459581a387a0f1d
3
+ size 4998949376
model-00033-of-00046.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:26b8db94acf64a533d51d5a223d7e8c88027a4b9d07ddc05afe7eb7482c7a660
3
+ size 4998949504
model-00034-of-00046.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:56c93cc8e9ecffc2df9327e8923b7490519ee5eb9992149ed023559209ca5841
3
+ size 4998949504
model-00035-of-00046.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5df2023afb0909107918a3022721304e8af1b116c8797b68174323cc28567d97
3
+ size 4997005240
model-00037-of-00046.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:34e1f19ed22edd5abdfed8625cc237b86a8ac96ac5c2734b6b88224d3fb5e761
3
+ size 4998949360
model-00038-of-00046.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:34484512e4f536e2d69b7dda4151733f7a746dd2fbee2fd42376f607bc46fb45
3
+ size 4998949504
model-00039-of-00046.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0b5cfcf72132d481d81b5826425c9c608e9daede879cf8e8eb73e36873c63d4c
3
+ size 4998949504
model-00040-of-00046.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:502416244e0b502486052d8f4bd2b738b7e2cb1b674cd65f9b2d8c6c568ffcb4
3
+ size 4997005256
model-00041-of-00046.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3935fbee44225983ea4e0751990f83b5739c152cc406c4ed5a54df760b53ea62
3
+ size 4998949032
model-00042-of-00046.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b27ab584813a90b9b8ad82a3cd6b1e15e8d8bcd8e388807a7093f20a6ab6a47c
3
+ size 4998949344
model-00043-of-00046.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d237c5f3c2507e829f332bb3f1d929a1c30a0b09a3962c2178568fb6b8a31be4
3
+ size 4998949504
model-00044-of-00046.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b3848447eaaab40a6583d2ac960c5bc15e30f241c6f0c62c87e110b9e8667c5b
3
+ size 4998949504
model-00045-of-00046.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8c8006f1aae4f389a7a19593cdff0b89babbc9252c7eac0bf1ef3d9645d14bbc
3
+ size 4997005280
model-00046-of-00046.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ddcc79d7a5aab4d30858ad6b6abc9698136539f3e1f237b8a4d5db0e8c690718
3
+ size 4860617544
model.safetensors.index.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f72f1c080f4fe8f7c6f71e726046dd001e9c5047fb65c69feeabc52aef4807f0
3
+ size 12219756
modeling_afmoe.py ADDED
@@ -0,0 +1,680 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Callable, Optional, Tuple, Union
2
+
3
+ import torch
4
+ import torch.nn.functional as F
5
+ from torch import nn
6
+
7
+ from transformers.activations import ACT2FN
8
+ from transformers.generation import GenerationMixin
9
+ from transformers.modeling_outputs import (
10
+ MoeCausalLMOutputWithPast,
11
+ MoeModelOutputWithPast,
12
+ )
13
+ from transformers.modeling_utils import PreTrainedModel, ALL_ATTENTION_FUNCTIONS
14
+ from transformers.modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update
15
+ from transformers.masking_utils import (
16
+ create_causal_mask,
17
+ create_sliding_window_causal_mask,
18
+ )
19
+ from transformers.modeling_layers import GradientCheckpointingLayer
20
+ from transformers.processing_utils import Unpack
21
+ from transformers.utils import TransformersKwargs
22
+ from transformers.cache_utils import Cache, DynamicCache
23
+ from transformers.integrations import use_kernel_forward_from_hub
24
+
25
+
26
+ try:
27
+ from .configuration_afmoe import AfmoeConfig
28
+ except:
29
+ from configuration_afmoe import AfmoeConfig
30
+
31
+ class AfmoeRotaryEmbedding(nn.Module):
32
+
33
+ def __init__(self, config: AfmoeConfig, device=None):
34
+ super().__init__()
35
+ # BC: "rope_type" was originally "type"
36
+ if hasattr(config, "rope_scaling") and config.rope_scaling is not None:
37
+ self.rope_type = config.rope_scaling.get("rope_type", config.rope_scaling.get("type"))
38
+ else:
39
+ self.rope_type = "default"
40
+ self.max_seq_len_cached = config.max_position_embeddings
41
+ self.original_max_seq_len = config.max_position_embeddings
42
+
43
+ self.config = config
44
+ self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
45
+
46
+ inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device)
47
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
48
+ self.original_inv_freq = self.inv_freq
49
+
50
+ def _dynamic_frequency_update(self, position_ids, device):
51
+ """
52
+ dynamic RoPE layers should recompute `inv_freq` in the following situations:
53
+ 1 - growing beyond the cached sequence length (allow scaling)
54
+ 2 - the current sequence length is in the original scale (avoid losing precision with small sequences)
55
+ """
56
+ seq_len = torch.max(position_ids) + 1
57
+ if seq_len > self.max_seq_len_cached: # growth
58
+ inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device, seq_len=seq_len)
59
+ self.register_buffer("inv_freq", inv_freq, persistent=False) # TODO joao: may break with compilation
60
+ self.max_seq_len_cached = seq_len
61
+
62
+ if seq_len < self.original_max_seq_len and self.max_seq_len_cached > self.original_max_seq_len: # reset
63
+ # This .to() is needed if the model has been moved to a device after being initialized (because
64
+ # the buffer is automatically moved, but not the original copy)
65
+ self.original_inv_freq = self.original_inv_freq.to(device)
66
+ self.register_buffer("inv_freq", self.original_inv_freq, persistent=False)
67
+ self.max_seq_len_cached = self.original_max_seq_len
68
+
69
+ @torch.no_grad()
70
+ def forward(self, x, position_ids):
71
+ if "dynamic" in self.rope_type:
72
+ self._dynamic_frequency_update(position_ids, device=x.device)
73
+
74
+ # Core RoPE block
75
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
76
+ position_ids_expanded = position_ids[:, None, :].float()
77
+ # Force float32 (see https://github.com/huggingface/transformers/pull/29285)
78
+ device_type = x.device.type
79
+ device_type = device_type if isinstance(device_type, str) and device_type != "mps" else "cpu"
80
+ with torch.autocast(device_type=device_type, enabled=False):
81
+ freqs = (inv_freq_expanded.float().to(x.device) @ position_ids_expanded.float()).transpose(1, 2)
82
+ emb = torch.cat((freqs, freqs), dim=-1)
83
+ cos = emb.cos()
84
+ sin = emb.sin()
85
+
86
+ # Advanced RoPE types (e.g. yarn) apply a post-processing scaling factor, equivalent to scaling attention
87
+ cos = cos * self.attention_scaling
88
+ sin = sin * self.attention_scaling
89
+
90
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
91
+
92
+
93
+ def rotate_half(x):
94
+ """Rotates half the hidden dims of the input."""
95
+ x1 = x[..., : x.shape[-1] // 2]
96
+ x2 = x[..., x.shape[-1] // 2 :]
97
+ return torch.cat((-x2, x1), dim=-1)
98
+
99
+
100
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
101
+ """Applies Rotary Position Embedding to the query and key tensors.
102
+
103
+ Args:
104
+ q (`torch.Tensor`): The query tensor.
105
+ k (`torch.Tensor`): The key tensor.
106
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
107
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
108
+ position_ids (`torch.Tensor`, *optional*):
109
+ Deprecated and unused.
110
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
111
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
112
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
113
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
114
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
115
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
116
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
117
+ Returns:
118
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
119
+ """
120
+ cos = cos.unsqueeze(unsqueeze_dim)
121
+ sin = sin.unsqueeze(unsqueeze_dim)
122
+ q_embed = (q * cos) + (rotate_half(q) * sin)
123
+ k_embed = (k * cos) + (rotate_half(k) * sin)
124
+ return q_embed, k_embed
125
+
126
+
127
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
128
+ """
129
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
130
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
131
+ """
132
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
133
+ if n_rep == 1:
134
+ return hidden_states
135
+ hidden_states = hidden_states[:, :, None, :, :].expand(
136
+ batch, num_key_value_heads, n_rep, slen, head_dim
137
+ )
138
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
139
+
140
+ @use_kernel_forward_from_hub("RMSNorm")
141
+ class AfmoeRMSNorm(nn.Module):
142
+ def __init__(self, hidden_size: int, eps: float):
143
+ """
144
+ AfmoeRMSNorm is equivalent to T5LayerNorm
145
+ """
146
+ super().__init__()
147
+ self.weight = nn.Parameter(torch.ones(hidden_size))
148
+ self.variance_epsilon = eps
149
+
150
+ def forward(self, hidden_states):
151
+ input_dtype = hidden_states.dtype
152
+ hidden_states = hidden_states.to(torch.float32)
153
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
154
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
155
+ return self.weight * hidden_states.to(input_dtype)
156
+
157
+ def extra_repr(self):
158
+ return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
159
+
160
+
161
+
162
+ def eager_attention_forward(
163
+ module: nn.Module,
164
+ query: torch.Tensor,
165
+ key: torch.Tensor,
166
+ value: torch.Tensor,
167
+ attention_mask: Optional[torch.Tensor],
168
+ scaling: float,
169
+ dropout: float = 0.0,
170
+ **kwargs,
171
+ ):
172
+ key_states = repeat_kv(key, module.num_key_value_groups)
173
+ value_states = repeat_kv(value, module.num_key_value_groups)
174
+
175
+ attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
176
+ if attention_mask is not None:
177
+ causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
178
+ attn_weights = attn_weights + causal_mask
179
+
180
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(
181
+ query.dtype
182
+ )
183
+ attn_weights = nn.functional.dropout(
184
+ attn_weights, p=dropout, training=module.training
185
+ )
186
+ attn_output = torch.matmul(attn_weights, value_states)
187
+ attn_output = attn_output.transpose(1, 2).contiguous()
188
+
189
+ return attn_output, attn_weights
190
+
191
+
192
+ class AfmoeMLP(nn.Module):
193
+ def __init__(self, config, intermediate_size=None):
194
+ super().__init__()
195
+ self.config = config
196
+ self.hidden_size = config.hidden_size
197
+ self.intermediate_size = intermediate_size or config.intermediate_size
198
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
199
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
200
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
201
+ self.act_fn = ACT2FN[config.hidden_act]
202
+
203
+ def forward(self, x):
204
+ return self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
205
+
206
+
207
+ class AfmoeTokenChoiceRouter(nn.Module):
208
+ """Token-choice top-K router for MoE routing."""
209
+
210
+ def __init__(self, config):
211
+ super().__init__()
212
+ self.config = config
213
+ self.top_k = config.num_experts_per_tok
214
+ self.num_experts = config.num_experts
215
+ self.score_func = config.score_func
216
+ self.route_norm = config.route_norm
217
+ self.route_scale = config.route_scale
218
+ self.gate = nn.Linear(config.hidden_size, config.num_experts, bias=False)
219
+
220
+ def forward(self, hidden_states, expert_bias: torch.Tensor | None):
221
+ _, _, hidden_dim = hidden_states.shape
222
+ hidden_states = hidden_states.view(-1, hidden_dim)
223
+
224
+ scores = self.gate(hidden_states)
225
+
226
+ # Apply scoring function in float32 for stability
227
+ if self.score_func == "sigmoid":
228
+ scores = torch.sigmoid(scores.to(torch.float32))
229
+ else:
230
+ scores = F.softmax(scores.to(torch.float32), dim=-1)
231
+
232
+ if expert_bias is not None:
233
+ _, selected_experts = torch.topk(scores + expert_bias, k=self.top_k, dim=1)
234
+ top_scores = scores.gather(dim=1, index=selected_experts)
235
+ else:
236
+ top_scores, selected_experts = torch.topk(scores, k=self.top_k, dim=1)
237
+
238
+ # Normalize weights if using sigmoid
239
+ if self.score_func == "sigmoid" and self.route_norm:
240
+ denominator = top_scores.sum(dim=-1, keepdim=True) + 1e-20
241
+ top_scores = top_scores / denominator
242
+
243
+ top_scores = top_scores * self.route_scale
244
+ return top_scores, selected_experts
245
+
246
+ class AfmoeMoE(nn.Module):
247
+ def __init__(self, config):
248
+ super().__init__()
249
+ self.config = config
250
+ self.router = AfmoeTokenChoiceRouter(config)
251
+
252
+ self.shared_experts = None
253
+ if config.num_shared_experts > 0:
254
+ self.shared_experts = AfmoeMLP(
255
+ config, config.moe_intermediate_size * config.num_shared_experts
256
+ )
257
+ self.experts = nn.ModuleList(
258
+ [AfmoeMLP(
259
+ config, intermediate_size=config.moe_intermediate_size
260
+ ) for _ in range(config.num_experts)]
261
+ )
262
+ self.expert_bias = nn.Parameter(torch.zeros(config.num_experts, dtype=torch.float32), requires_grad=False)
263
+
264
+
265
+ def forward(self, hidden_states):
266
+ batch_size, seq_len, hidden_dim = hidden_states.shape
267
+ hidden_states_flat = hidden_states.view(-1, hidden_dim)
268
+
269
+ # Get routing decisions
270
+ top_scores, selected_experts = self.router(hidden_states, self.expert_bias)
271
+
272
+ # Process through shared experts
273
+ if self.shared_experts is not None:
274
+ shared_output = self.shared_experts(hidden_states_flat)
275
+ else:
276
+ shared_output = torch.zeros_like(hidden_states_flat)
277
+
278
+ # Reorder tokens by expert for efficient processing
279
+ token_indices_sorted = torch.argsort(selected_experts.view(-1), stable=True)
280
+ top_scores_sorted = top_scores.view(-1)[token_indices_sorted]
281
+ token_to_expert = selected_experts.view(-1)[token_indices_sorted]
282
+ token_indices_sorted = token_indices_sorted // self.config.num_experts_per_tok
283
+
284
+ # Gather input tokens
285
+ token_indices_expanded = token_indices_sorted.unsqueeze(-1).expand(
286
+ -1, hidden_dim
287
+ )
288
+ routed_input = torch.gather(
289
+ hidden_states_flat, dim=0, index=token_indices_expanded
290
+ )
291
+
292
+ routed_output = torch.zeros_like(routed_input)
293
+ for expert_id in range(self.config.num_experts):
294
+ mask = token_to_expert == expert_id
295
+ if mask.any():
296
+ expert_input = routed_input[mask]
297
+ expert_out = self.experts[expert_id](expert_input)
298
+ routed_output[mask] = expert_out
299
+
300
+ routed_output = (
301
+ routed_output.to(torch.float32) * top_scores_sorted.unsqueeze(-1)
302
+ ).to(hidden_states.dtype)
303
+
304
+ # Scatter back to original positions
305
+ output = shared_output.scatter_add(
306
+ dim=0, index=token_indices_expanded, src=routed_output
307
+ )
308
+
309
+ return output.view(batch_size, seq_len, hidden_dim)
310
+
311
+
312
+ class AfmoeAttention(nn.Module):
313
+ """Multi-headed attention with local/global pattern and gating."""
314
+
315
+ def __init__(self, config: AfmoeConfig, layer_idx: int):
316
+ super().__init__()
317
+ self.config = config
318
+ self.layer_idx = layer_idx
319
+ self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
320
+ self.num_heads = config.num_attention_heads
321
+ self.num_key_value_heads = config.num_key_value_heads
322
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
323
+
324
+ self.scaling = self.head_dim**-0.5
325
+ self.attention_dropout = config.attention_dropout
326
+ self.is_local_attention = config.layer_types[layer_idx] == "sliding_attention"
327
+ self.sliding_window = config.sliding_window if self.is_local_attention else None
328
+
329
+ self.q_proj = nn.Linear(
330
+ config.hidden_size, self.num_heads * self.head_dim, bias=False
331
+ )
332
+ self.k_proj = nn.Linear(
333
+ config.hidden_size, self.num_key_value_heads * self.head_dim, bias=False
334
+ )
335
+ self.v_proj = nn.Linear(
336
+ config.hidden_size, self.num_key_value_heads * self.head_dim, bias=False
337
+ )
338
+ self.o_proj = nn.Linear(
339
+ self.num_heads * self.head_dim, config.hidden_size, bias=False
340
+ )
341
+
342
+ self.q_norm = AfmoeRMSNorm(self.head_dim, eps=config.rms_norm_eps)
343
+ self.k_norm = AfmoeRMSNorm(self.head_dim, eps=config.rms_norm_eps)
344
+
345
+ self.gate_proj = nn.Linear(
346
+ config.hidden_size, self.num_heads * self.head_dim, bias=False
347
+ )
348
+
349
+ def forward(
350
+ self,
351
+ hidden_states: torch.Tensor,
352
+ position_embeddings: tuple[torch.Tensor, torch.Tensor],
353
+ attention_mask: Optional[torch.Tensor],
354
+ past_key_value: Optional[Cache] = None,
355
+ cache_position: Optional[torch.LongTensor] = None,
356
+ **kwargs: Unpack[TransformersKwargs],
357
+ ) -> torch.Tensor:
358
+
359
+ input_shape = hidden_states.shape[:-1]
360
+ hidden_shape = (*input_shape, -1, self.head_dim)
361
+
362
+ query_states = self.q_proj(hidden_states).view(hidden_shape)
363
+ key_states = self.k_proj(hidden_states).view(hidden_shape)
364
+ value_states = self.v_proj(hidden_states).view(hidden_shape)
365
+ gate_states = self.gate_proj(hidden_states)
366
+
367
+ query_states = self.q_norm(query_states)
368
+ key_states = self.k_norm(key_states)
369
+
370
+ query_states = query_states.transpose(1, 2)
371
+ key_states = key_states.transpose(1, 2)
372
+ value_states = value_states.transpose(1, 2)
373
+
374
+ if self.is_local_attention:
375
+ cos, sin = position_embeddings
376
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
377
+
378
+ if past_key_value is not None:
379
+ cache_kwargs = {"cache_position": cache_position}
380
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
381
+
382
+ attention_interface: Callable = eager_attention_forward
383
+ if self.config._attn_implementation != "eager":
384
+ attention_interface = ALL_ATTENTION_FUNCTIONS[
385
+ self.config._attn_implementation
386
+ ]
387
+
388
+ output, _ = attention_interface(
389
+ self,
390
+ query_states,
391
+ key_states,
392
+ value_states,
393
+ attention_mask=attention_mask,
394
+ dropout=0.0 if not self.training else self.attention_dropout,
395
+ scaling=self.scaling,
396
+ sliding_window=self.sliding_window,
397
+ **kwargs,
398
+ )
399
+
400
+ output = output.view(*input_shape, -1).contiguous()
401
+ output = output * F.sigmoid(gate_states)
402
+ return self.o_proj(output)
403
+
404
+
405
+ class AfmoeDecoderLayer(GradientCheckpointingLayer):
406
+ def __init__(self, config: AfmoeConfig, layer_idx: int):
407
+ super().__init__()
408
+ self.hidden_size = config.hidden_size
409
+ self.layer_idx = layer_idx
410
+
411
+ self.self_attn = AfmoeAttention(config=config, layer_idx=layer_idx)
412
+ self.attention_type = config.layer_types[layer_idx]
413
+
414
+ # Dual normalization for attention
415
+ self.input_layernorm = AfmoeRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
416
+ self.post_attention_layernorm = AfmoeRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
417
+
418
+ # Dual normalization for FFN
419
+ self.pre_mlp_layernorm = AfmoeRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
420
+ self.post_mlp_layernorm = AfmoeRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
421
+
422
+ # MoE or dense FFN
423
+ self.moe_enabled = layer_idx >= config.num_dense_layers
424
+ if self.moe_enabled:
425
+ self.mlp = AfmoeMoE(config)
426
+ else:
427
+ self.mlp = AfmoeMLP(config)
428
+
429
+ def forward(
430
+ self,
431
+ hidden_states: torch.Tensor,
432
+ attention_mask: Optional[torch.Tensor] = None,
433
+ position_ids: Optional[torch.LongTensor] = None,
434
+ past_key_value: Optional[Cache] = None,
435
+ use_cache: Optional[bool] = None,
436
+ cache_position: Optional[torch.LongTensor] = None,
437
+ position_embeddings: Optional[tuple[torch.Tensor, torch.Tensor]] = None,
438
+ **kwargs: Unpack[TransformersKwargs],
439
+ ) -> torch.FloatTensor:
440
+ residual = hidden_states
441
+
442
+ # Self Attention with dual normalization
443
+ hidden_states = self.input_layernorm(hidden_states)
444
+ hidden_states = self.self_attn(
445
+ hidden_states=hidden_states,
446
+ attention_mask=attention_mask,
447
+ position_ids=position_ids,
448
+ past_key_value=past_key_value,
449
+ use_cache=use_cache,
450
+ cache_position=cache_position,
451
+ position_embeddings=position_embeddings,
452
+ **kwargs,
453
+ )
454
+ hidden_states = self.post_attention_layernorm(hidden_states)
455
+ hidden_states = residual + hidden_states
456
+
457
+ # FFN with dual normalization
458
+ residual = hidden_states
459
+ hidden_states = self.pre_mlp_layernorm(hidden_states)
460
+
461
+ if self.moe_enabled:
462
+ hidden_states = self.mlp(hidden_states)
463
+ else:
464
+ hidden_states = self.mlp(hidden_states)
465
+
466
+ hidden_states = self.post_mlp_layernorm(hidden_states)
467
+ hidden_states = residual + hidden_states
468
+ return hidden_states
469
+
470
+
471
+ class AfmoePreTrainedModel(PreTrainedModel):
472
+ config_class = AfmoeConfig
473
+ base_model_prefix = "model"
474
+ _no_split_modules = ["AfmoeDecoderLayer"]
475
+ _skip_keys_device_placement = ["past_key_values"]
476
+ _keep_in_fp32_modules = [
477
+ "input_layernorm",
478
+ "post_attention_layernorm",
479
+ "pre_mlp_layernorm",
480
+ "post_mlp_layernorm",
481
+ "q_norm",
482
+ "k_norm",
483
+ "norm",
484
+ ]
485
+ _supports_sdpa = True
486
+ _supports_attention_backend = True
487
+ supports_gradient_checkpointing = True
488
+
489
+
490
+ class AfmoeModel(AfmoePreTrainedModel):
491
+ _no_split_modules = ["AfmoeDecoderLayer"]
492
+
493
+ def __init__(self, config: AfmoeConfig):
494
+ super().__init__(config)
495
+ self.padding_idx = config.pad_token_id
496
+ self.vocab_size = config.vocab_size
497
+
498
+ self.embed_tokens = nn.Embedding(
499
+ config.vocab_size, config.hidden_size, self.padding_idx
500
+ )
501
+ self.layers = nn.ModuleList(
502
+ [
503
+ AfmoeDecoderLayer(config, layer_idx)
504
+ for layer_idx in range(config.num_hidden_layers)
505
+ ]
506
+ )
507
+ self.norm = AfmoeRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
508
+ self.rotary_emb = AfmoeRotaryEmbedding(config=config)
509
+ self.gradient_checkpointing = False
510
+
511
+ self.post_init()
512
+
513
+ def get_input_embeddings(self):
514
+ return self.embed_tokens
515
+
516
+ def set_input_embeddings(self, value):
517
+ self.embed_tokens = value
518
+
519
+
520
+ def forward(
521
+ self,
522
+ input_ids: torch.LongTensor,
523
+ attention_mask: Optional[torch.Tensor] = None,
524
+ position_ids: Optional[torch.LongTensor] = None,
525
+ past_key_values: Optional[list[torch.FloatTensor]] = None,
526
+ inputs_embeds: Optional[torch.FloatTensor] = None,
527
+ use_cache: Optional[bool] = None,
528
+ cache_position: Optional[torch.LongTensor] = None,
529
+ **kwargs: Unpack[TransformersKwargs],
530
+ ) -> MoeModelOutputWithPast:
531
+ if (input_ids is None) ^ (inputs_embeds is not None):
532
+ raise ValueError(
533
+ "You must specify exactly one of input_ids or inputs_embeds"
534
+ )
535
+
536
+ if use_cache and past_key_values is None:
537
+ past_key_values = DynamicCache()
538
+
539
+ if inputs_embeds is None:
540
+ inputs_embeds = self.embed_tokens(input_ids)
541
+
542
+ if cache_position is None:
543
+ past_seen_tokens = (
544
+ past_key_values.get_seq_length() if past_key_values is not None else 0
545
+ )
546
+ cache_position = torch.arange(
547
+ past_seen_tokens,
548
+ past_seen_tokens + inputs_embeds.shape[1],
549
+ device=inputs_embeds.device,
550
+ )
551
+ if position_ids is None:
552
+ position_ids = cache_position.unsqueeze(0)
553
+
554
+ # It may already have been prepared by e.g. `generate`
555
+ if not isinstance(causal_mask_mapping := attention_mask, dict):
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
+ }
563
+ causal_mask_mapping = {
564
+ "full_attention": create_causal_mask(**mask_kwargs),
565
+ "sliding_attention": create_sliding_window_causal_mask(**mask_kwargs),
566
+ }
567
+
568
+ hidden_states = inputs_embeds
569
+
570
+ # Apply muP input scaling if enabled
571
+ if self.config.mup_enabled:
572
+ hidden_states = hidden_states * (self.config.hidden_size**0.5)
573
+
574
+ position_embeddings = self.rotary_emb(hidden_states, position_ids)
575
+
576
+ for decoder_layer in self.layers:
577
+ hidden_states = decoder_layer(
578
+ hidden_states,
579
+ attention_mask=causal_mask_mapping[decoder_layer.attention_type],
580
+ position_ids=position_ids,
581
+ past_key_value=past_key_values,
582
+ use_cache=use_cache,
583
+ cache_position=cache_position,
584
+ position_embeddings=position_embeddings,
585
+ **kwargs,
586
+ )
587
+
588
+ hidden_states = self.norm(hidden_states)
589
+ return MoeModelOutputWithPast(
590
+ last_hidden_state=hidden_states,
591
+ past_key_values=past_key_values,
592
+ )
593
+
594
+
595
+ class AfmoeForCausalLM(AfmoePreTrainedModel, GenerationMixin):
596
+ _tied_weights_keys = ["lm_head.weight"]
597
+ _tp_plan = {"lm_head": "colwise_rep"}
598
+ _pp_plan = {"lm_head": (["hidden_states"], ["logits"])}
599
+
600
+ def __init__(self, config):
601
+ super().__init__(config)
602
+ self.model = AfmoeModel(config)
603
+ self.vocab_size = config.vocab_size
604
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
605
+
606
+ # Initialize weights and apply final processing
607
+ self.post_init()
608
+
609
+ def get_input_embeddings(self):
610
+ return self.model.embed_tokens
611
+
612
+ def set_input_embeddings(self, value):
613
+ self.model.embed_tokens = value
614
+
615
+ def get_output_embeddings(self):
616
+ return self.lm_head
617
+
618
+ def set_output_embeddings(self, new_embeddings):
619
+ self.lm_head = new_embeddings
620
+
621
+ def set_decoder(self, decoder):
622
+ self.model = decoder
623
+
624
+ def get_decoder(self):
625
+ return self.model
626
+
627
+ def forward(
628
+ self,
629
+ input_ids: torch.LongTensor,
630
+ attention_mask: Optional[torch.Tensor] = None,
631
+ position_ids: Optional[torch.LongTensor] = None,
632
+ past_key_values: Optional[Cache] = None,
633
+ inputs_embeds: Optional[torch.FloatTensor] = None,
634
+ labels: Optional[torch.LongTensor] = None,
635
+ use_cache: Optional[bool] = None,
636
+ cache_position: Optional[torch.LongTensor] = None,
637
+ logits_to_keep: Union[int, torch.Tensor] = 0,
638
+ token_type_ids: Optional[torch.Tensor] = None, # will be ignored
639
+ **kwargs: Unpack[TransformersKwargs],
640
+ ) -> Union[Tuple, MoeCausalLMOutputWithPast]:
641
+ outputs: MoeModelOutputWithPast = self.model(
642
+ input_ids=input_ids,
643
+ attention_mask=attention_mask,
644
+ position_ids=position_ids,
645
+ past_key_values=past_key_values,
646
+ inputs_embeds=inputs_embeds,
647
+ use_cache=use_cache,
648
+ cache_position=cache_position,
649
+ **kwargs,
650
+ )
651
+
652
+ hidden_states = outputs.last_hidden_state
653
+ # Only compute necessary logits
654
+ slice_indices = (
655
+ slice(-logits_to_keep, None)
656
+ if isinstance(logits_to_keep, int)
657
+ else logits_to_keep
658
+ )
659
+ logits = self.lm_head(hidden_states[:, slice_indices, :])
660
+
661
+ loss = None
662
+ if labels is not None:
663
+ loss = self.loss_function(logits, labels, self.vocab_size, **kwargs)
664
+
665
+
666
+ return MoeCausalLMOutputWithPast(
667
+ loss=loss,
668
+ logits=logits,
669
+ past_key_values=outputs.past_key_values,
670
+ hidden_states=outputs.hidden_states,
671
+ attentions=outputs.attentions,
672
+ router_logits=outputs.router_logits,
673
+ )
674
+
675
+
676
+ __all__ = [
677
+ "AfmoeForCausalLM",
678
+ "AfmoeModel",
679
+ "AfmoePreTrainedModel",
680
+ ]
recipe.yaml ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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: mse
19
+ observer_kwargs: {}
20
+ input_activations: null
21
+ output_activations: null
22
+ format: null
23
+ targets: [Linear]
24
+ ignore: ['re:model[.]layers[.]0[.].*', 're:model[.]layers[.]1[.].*', 're:model[.]layers[.]2[.].*',
25
+ 're:model[.]layers[.]3[.].*', 're:model[.]layers[.]4[.].*', 're:model[.]layers[.]5[.].*',
26
+ 're:.*shared_experts.*', 're:.*router[.]gate$', lm_head]
27
+ bypass_divisibility_checks: false
28
+ mappings:
29
+ - smooth_layer: re:.*[.]([6-9]|[1-5][0-9])[.].*input_layernorm
30
+ balance_layers: ['re:.*[.]([6-9]|[1-5][0-9])[.].*self_attn[.]q_proj', 're:.*[.]([6-9]|[1-5][0-9])[.].*self_attn[.]k_proj',
31
+ 're:.*[.]([6-9]|[1-5][0-9])[.].*self_attn[.]v_proj', 're:.*[.]([6-9]|[1-5][0-9])[.].*self_attn[.]gate_proj']
32
+ activation_hook_target: null
33
+ balance_exponent: 1
34
+ - smooth_layer: re:.*[.]([6-9]|[1-5][0-9])[.].*pre_mlp_layernorm
35
+ balance_layers: ['re:.*[.]([6-9]|[1-5][0-9])[.].*mlp[.]router[.]gate$', 're:.*[.]([6-9]|[1-5][0-9])[.].*mlp[.].*gate_proj',
36
+ 're:.*[.]([6-9]|[1-5][0-9])[.].*mlp[.].*up_proj']
37
+ activation_hook_target: router.gate
38
+ balance_exponent: 1
39
+ - smooth_layer: re:.*[.]([6-9]|[1-5][0-9])[.].*mlp[.]experts.*up_proj
40
+ balance_layers: ['re:.*[.]([6-9]|[1-5][0-9])[.].*mlp[.]experts.*down_proj']
41
+ activation_hook_target: null
42
+ balance_exponent: 1
43
+ offload_device: !!python/object/apply:torch.device [cpu]
44
+ duo_scaling: true
45
+ n_grid: 20
special_tokens_map.json ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "bos_token": {
3
+ "content": "<|begin_of_text|>",
4
+ "lstrip": false,
5
+ "normalized": false,
6
+ "rstrip": false,
7
+ "single_word": false
8
+ },
9
+ "eos_token": {
10
+ "content": "<|im_end|>",
11
+ "lstrip": false,
12
+ "normalized": false,
13
+ "rstrip": false,
14
+ "single_word": false
15
+ },
16
+ "pad_token": {
17
+ "content": "<|pad|>",
18
+ "lstrip": false,
19
+ "normalized": false,
20
+ "rstrip": false,
21
+ "single_word": false
22
+ }
23
+ }
tokenizer.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c5a93d847b4d3a1da95e9527c30ec10144f63a823e9feec98570274980754897
3
+ size 14614487