intervitens commited on
Commit
b97dc84
·
verified ·
1 Parent(s): e34315b

Upload folder using huggingface_hub

Browse files
.gitattributes CHANGED
@@ -33,3 +33,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ tokenizer.json filter=lfs diff=lfs merge=lfs -text
chat_template.jinja ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {%- if tools %}
2
+ {{- '<|im_start|>system\n' }}
3
+ {%- if messages[0].role == 'system' %}
4
+ {{- messages[0].content + '\n\n' }}
5
+ {%- endif %}
6
+ {{- "# Tools\n\nYou may call one or more functions to assist with the user query.\n\nYou are provided with function signatures within <tools></tools> XML tags:\n<tools>" }}
7
+ {%- for tool in tools %}
8
+ {{- "\n" }}
9
+ {{- tool | tojson }}
10
+ {%- endfor %}
11
+ {{- "\n</tools>\n\nFor each function call, return a json object with function name and arguments within <tool_call></tool_call> XML tags:\n<tool_call>\n{\"name\": <function-name>, \"arguments\": <args-json-object>}\n</tool_call><|im_end|>\n" }}
12
+ {%- else %}
13
+ {%- if messages[0].role == 'system' %}
14
+ {{- '<|im_start|>system\n' + messages[0].content + '<|im_end|>\n' }}
15
+ {%- endif %}
16
+ {%- endif %}
17
+ {%- for message in messages %}
18
+ {%- if message.content is string %}
19
+ {%- set content = message.content %}
20
+ {%- else %}
21
+ {%- set content = '' %}
22
+ {%- endif %}
23
+ {%- if (message.role == "user") or (message.role == "system" and not loop.first) %}
24
+ {{- '<|im_start|>' + message.role + '\n' + content + '<|im_end|>' + '\n' }}
25
+ {%- elif message.role == "assistant" %}
26
+ {%- if '</think>' in content %}
27
+ {%- set content = content.split('</think>')[-1].lstrip('\n') %}
28
+ {%- endif %}
29
+ {{- '<|im_start|>' + message.role + '\n' }}
30
+ {% generation %}
31
+ {{- content }}
32
+ {%- if message.tool_calls %}
33
+ {%- for tool_call in message.tool_calls %}
34
+ {%- if (loop.first and content) or (not loop.first) %}
35
+ {{- '\n' }}
36
+ {%- endif %}
37
+ {%- if tool_call.function %}
38
+ {%- set tool_call = tool_call.function %}
39
+ {%- endif %}
40
+ {{- '<tool_call>\n{"name": "' }}
41
+ {{- tool_call.name }}
42
+ {{- '", "arguments": ' }}
43
+ {%- if tool_call.arguments is string %}
44
+ {{- tool_call.arguments }}
45
+ {%- else %}
46
+ {{- tool_call.arguments | tojson }}
47
+ {%- endif %}
48
+ {{- '}\n</tool_call>' }}
49
+ {%- endfor %}
50
+ {%- endif %}
51
+ {{- '<|im_end|>' }}
52
+ {% endgeneration %}
53
+ {{- '\n' }}
54
+ {%- elif message.role == "tool" %}
55
+ {%- if loop.first or (messages[loop.index0 - 1].role != "tool") %}
56
+ {{- '<|im_start|>user' }}
57
+ {%- endif %}
58
+ {{- '\n<tool_response>\n' }}
59
+ {{- content }}
60
+ {{- '\n</tool_response>' }}
61
+ {%- if loop.last or (messages[loop.index0 + 1].role != "tool") %}
62
+ {{- '<|im_end|>\n' }}
63
+ {%- endif %}
64
+ {%- endif %}
65
+ {%- endfor %}
66
+ {%- if add_generation_prompt %}
67
+ {{- '<|im_start|>assistant\n<think>\n' }}
68
+ {%- endif %}
config.json ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "AfmoeSCMForCausalLM"
4
+ ],
5
+ "attention_dropout": 0.0,
6
+ "auto_map": {
7
+ "AutoConfig": "configuration_afmoe_scm.AfmoeSCMConfig",
8
+ "AutoModel": "modeling_afmoe_scm.AfmoeSCMModel",
9
+ "AutoModelForCausalLM": "modeling_afmoe_scm.AfmoeSCMForCausalLM"
10
+ },
11
+ "dtype": "bfloat16",
12
+ "global_attn_every_n_layers": 4,
13
+ "head_dim": 128,
14
+ "hidden_act": "silu",
15
+ "hidden_size": 2048,
16
+ "initializer_range": 0.02,
17
+ "intermediate_size": 6144,
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
+ ],
52
+ "load_balance_coeff": 0.001,
53
+ "max_position_embeddings": 131072,
54
+ "model_type": "afmoe",
55
+ "moe_intermediate_size": 1024,
56
+ "mup_enabled": true,
57
+ "n_group": 1,
58
+ "num_attention_heads": 32,
59
+ "num_dense_layers": 2,
60
+ "num_expert_groups": 1,
61
+ "num_experts": 128,
62
+ "num_experts_per_tok": 8,
63
+ "num_hidden_layers": 32,
64
+ "num_key_value_heads": 4,
65
+ "num_limited_groups": 1,
66
+ "num_shared_experts": 1,
67
+ "rms_norm_eps": 1e-05,
68
+ "rope_scaling": null,
69
+ "rope_theta": 10000,
70
+ "route_norm": true,
71
+ "route_scale": 2.826,
72
+ "score_func": "sigmoid",
73
+ "sliding_window": 2048,
74
+ "tie_word_embeddings": false,
75
+ "topk_group": 1,
76
+ "transformers_version": "4.57.3",
77
+ "use_cache": true,
78
+ "vocab_size": 200192
79
+ }
configuration_afmoe_scm.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 AfmoeSCMConfig(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__ = ["AfmoeSCMConfig"]
convert_hf_to_scm.py ADDED
@@ -0,0 +1,128 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import glob
2
+ import re
3
+ import shutil
4
+ import sys
5
+
6
+ import accelerate
7
+ import torch
8
+ from configuration_afmoe_scm import AfmoeSCMConfig
9
+ from modeling_afmoe_scm import AfmoeSCMForCausalLM
10
+ from configuration_afmoe import AfmoeConfig
11
+ from safetensors import safe_open
12
+
13
+ input_model = sys.argv[1]
14
+ output_model_path = sys.argv[2]
15
+
16
+ auto_map = {
17
+ "AutoConfig": "configuration_afmoe_scm.AfmoeSCMConfig",
18
+ "AutoModel": "modeling_afmoe_scm.AfmoeSCMModel",
19
+ "AutoModelForCausalLM": "modeling_afmoe_scm.AfmoeSCMForCausalLM"
20
+ }
21
+
22
+ cfg_standard_moe = AfmoeConfig.from_pretrained(input_model)
23
+ cfg_shared_moe = AfmoeSCMConfig(
24
+ auto_map=auto_map,
25
+ layer_types=cfg_standard_moe.layer_types,
26
+ global_attn_every_n_layers=cfg_standard_moe.global_attn_every_n_layers,
27
+ load_balance_coeff=cfg_standard_moe.load_balance_coeff,
28
+ mup_enabled=cfg_standard_moe.mup_enabled,
29
+ num_dense_layers=cfg_standard_moe.num_dense_layers,
30
+ num_expert_groups=cfg_standard_moe.num_expert_groups,
31
+ num_limited_groups=cfg_standard_moe.num_limited_groups,
32
+ route_norm=cfg_standard_moe.route_norm,
33
+ route_scale=cfg_standard_moe.route_scale,
34
+ score_func=cfg_standard_moe.score_func,
35
+ topk_group=cfg_standard_moe.topk_group,
36
+ num_shared_experts=cfg_standard_moe.num_shared_experts,
37
+ vocab_size=cfg_standard_moe.vocab_size,
38
+ hidden_size=cfg_standard_moe.hidden_size,
39
+ intermediate_size=cfg_standard_moe.intermediate_size,
40
+ num_hidden_layers=cfg_standard_moe.num_hidden_layers,
41
+ num_attention_heads=cfg_standard_moe.num_attention_heads,
42
+ num_key_value_heads=cfg_standard_moe.num_key_value_heads,
43
+ hidden_act=cfg_standard_moe.hidden_act,
44
+ max_position_embeddings=cfg_standard_moe.max_position_embeddings,
45
+ initializer_range=cfg_standard_moe.initializer_range,
46
+ rms_norm_eps=cfg_standard_moe.rms_norm_eps,
47
+ use_cache=cfg_standard_moe.use_cache,
48
+ tie_word_embeddings=cfg_standard_moe.tie_word_embeddings,
49
+ rope_theta=cfg_standard_moe.rope_theta,
50
+ rope_scaling=cfg_standard_moe.rope_scaling,
51
+ sliding_window=cfg_standard_moe.sliding_window,
52
+ attention_dropout=cfg_standard_moe.attention_dropout,
53
+ moe_intermediate_size=cfg_standard_moe.moe_intermediate_size,
54
+ num_experts_per_tok=cfg_standard_moe.num_experts_per_tok,
55
+ num_experts=cfg_standard_moe.num_experts,
56
+ head_dim=cfg_standard_moe.head_dim,
57
+ eos_token_id=cfg_standard_moe.eos_token_id,
58
+ pad_token_id=cfg_standard_moe.pad_token_id,
59
+ torch_dtype=cfg_standard_moe.torch_dtype,
60
+ )
61
+
62
+ num_experts = cfg_standard_moe.num_experts
63
+
64
+ with accelerate.init_empty_weights():
65
+ model_shared_moe = AfmoeSCMForCausalLM(cfg_shared_moe)
66
+
67
+ model_shared_moe = model_shared_moe.to(torch.bfloat16)
68
+ new_state_dict = {}
69
+ pattern = f"{input_model}/model-*-of-*.safetensors"
70
+ files = sorted(glob.glob(pattern))
71
+
72
+ if len(files) == 0:
73
+ raise FileNotFoundError
74
+ tensors = {}
75
+
76
+ for file_path in files:
77
+ print(f"processing {file_path}")
78
+ with safe_open(file_path, framework="pt", device="cpu") as f:
79
+ for key in f.keys():
80
+ tensor = f.get_tensor(key)
81
+ tensors[key] = tensor
82
+
83
+ for key in tensors:
84
+ if "experts" not in key or "shared_experts" in key:
85
+ new_state_dict[key] = tensors[key]
86
+ elif "experts.0" in key:
87
+ layer_num = int(re.search(r"\d+", key).group())
88
+ new_state_dict[
89
+ f"model.layers.{layer_num}.mlp.moe_mlp.output_experts.weight"
90
+ ] = torch.stack(
91
+ [
92
+ tensors[f"model.layers.{layer_num}.mlp.experts.{i}.down_proj.weight"]
93
+ for i in range(num_experts)
94
+ ]
95
+ )
96
+ new_state_dict[f"model.layers.{layer_num}.mlp.moe_mlp.experts.weight"] = (
97
+ torch.stack(
98
+ [
99
+ torch.cat(
100
+ [
101
+ tensors[
102
+ f"model.layers.{layer_num}.mlp.experts.{i}.up_proj.weight"
103
+ ],
104
+ tensors[
105
+ f"model.layers.{layer_num}.mlp.experts.{i}.gate_proj.weight"
106
+ ],
107
+ ],
108
+ dim=0,
109
+ )
110
+ for i in range(num_experts)
111
+ ]
112
+ )
113
+ )
114
+ model_shared_moe.load_state_dict(new_state_dict, strict=True, assign=True)
115
+ model_shared_moe.save_pretrained(output_model_path)
116
+ cfg_shared_moe.save_pretrained(output_model_path)
117
+
118
+
119
+ shutil.copy(
120
+ "modeling_afmoe_scm.py",
121
+ output_model_path + "/" + "modeling_afmoe_scm.py",
122
+ )
123
+ shutil.copy(
124
+ "configuration_afmoe_scm.py",
125
+ output_model_path + "/" + "configuration_afmoe_scm.py",
126
+ )
127
+ for i in ["special_tokens_map.json", "tokenizer_config.json", "tokenizer.json", "chat_template.jinja"]:
128
+ shutil.copy(input_model + "/" + i, output_model_path + "/" + i)
convert_scm_to_hf.py ADDED
@@ -0,0 +1,117 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import glob
2
+ import re
3
+ import shutil
4
+ import sys
5
+
6
+ import accelerate
7
+ import torch
8
+ from safetensors import safe_open
9
+ from configuration_afmoe_scm import AfmoeSCMConfig
10
+ from modeling_afmoe import AfmoeForCausalLM
11
+ from configuration_afmoe import AfmoeConfig
12
+
13
+ input_model = sys.argv[1]
14
+ output_model_path = sys.argv[2]
15
+
16
+ auto_map = {
17
+ "AutoConfig": "configuration_afmoe.AfmoeConfig",
18
+ "AutoModel": "modeling_afmoe.AfmoeModel",
19
+ "AutoModelForCausalLM": "modeling_afmoe.AfmoeForCausalLM"
20
+ }
21
+ cfg_shared_moe = AfmoeSCMConfig.from_pretrained(input_model)
22
+ cfg_standard_moe = AfmoeConfig(
23
+ auto_map=auto_map,
24
+ layer_types=cfg_shared_moe.layer_types,
25
+ global_attn_every_n_layers=cfg_shared_moe.global_attn_every_n_layers,
26
+ load_balance_coeff=cfg_shared_moe.load_balance_coeff,
27
+ mup_enabled=cfg_shared_moe.mup_enabled,
28
+ num_dense_layers=cfg_shared_moe.num_dense_layers,
29
+ num_expert_groups=cfg_shared_moe.num_expert_groups,
30
+ num_limited_groups=cfg_shared_moe.num_limited_groups,
31
+ route_norm=cfg_shared_moe.route_norm,
32
+ route_scale=cfg_shared_moe.route_scale,
33
+ score_func=cfg_shared_moe.score_func,
34
+ topk_group=cfg_shared_moe.topk_group,
35
+ num_shared_experts=cfg_shared_moe.num_shared_experts,
36
+ vocab_size=cfg_shared_moe.vocab_size,
37
+ hidden_size=cfg_shared_moe.hidden_size,
38
+ intermediate_size=cfg_shared_moe.intermediate_size,
39
+ num_hidden_layers=cfg_shared_moe.num_hidden_layers,
40
+ num_attention_heads=cfg_shared_moe.num_attention_heads,
41
+ num_key_value_heads=cfg_shared_moe.num_key_value_heads,
42
+ hidden_act=cfg_shared_moe.hidden_act,
43
+ max_position_embeddings=cfg_shared_moe.max_position_embeddings,
44
+ initializer_range=cfg_shared_moe.initializer_range,
45
+ rms_norm_eps=cfg_shared_moe.rms_norm_eps,
46
+ use_cache=cfg_shared_moe.use_cache,
47
+ tie_word_embeddings=cfg_shared_moe.tie_word_embeddings,
48
+ rope_theta=cfg_shared_moe.rope_theta,
49
+ rope_scaling=cfg_shared_moe.rope_scaling,
50
+ sliding_window=cfg_shared_moe.sliding_window,
51
+ attention_dropout=cfg_shared_moe.attention_dropout,
52
+ moe_intermediate_size=cfg_shared_moe.moe_intermediate_size,
53
+ num_experts_per_tok=cfg_shared_moe.num_experts_per_tok,
54
+ num_experts=cfg_shared_moe.num_experts,
55
+ head_dim=cfg_shared_moe.head_dim,
56
+ eos_token_id=cfg_shared_moe.eos_token_id,
57
+ pad_token_id=cfg_shared_moe.pad_token_id,
58
+ torch_dtype=cfg_shared_moe.torch_dtype,
59
+ )
60
+ num_experts = cfg_shared_moe.num_experts
61
+
62
+ with accelerate.init_empty_weights():
63
+ model_standard_moe = AfmoeForCausalLM(cfg_standard_moe)
64
+
65
+ model_standard_moe = model_standard_moe.to(torch.bfloat16)
66
+ new_state_dict = {}
67
+ pattern = f"{input_model}/model-*-of-*.safetensors"
68
+ files = sorted(glob.glob(pattern))
69
+
70
+ if len(files) == 0:
71
+ raise FileNotFoundError
72
+ tensors = {}
73
+
74
+ for file_path in files:
75
+ print(f"processing {file_path}")
76
+ with safe_open(file_path, framework="pt", device="cpu") as f:
77
+ for key in f.keys():
78
+ tensor = f.get_tensor(key)
79
+ tensors[key] = tensor
80
+
81
+ for key in tensors:
82
+ if "moe_mlp" not in key:
83
+ new_state_dict[key] = tensors[key]
84
+ elif "moe_mlp.output_experts" in key:
85
+ layer_num = int(re.search(r"\d+", key).group())
86
+ for i, tensor in enumerate(torch.unbind(tensors[key])):
87
+ new_state_dict[
88
+ f"model.layers.{layer_num}.mlp.experts.{i}.down_proj.weight"
89
+ ] = tensor.contiguous()
90
+ elif "moe_mlp.experts" in key:
91
+ layer_num = int(re.search(r"\d+", key).group())
92
+ for i, tensor in enumerate(torch.unbind(tensors[key])):
93
+ (
94
+ new_state_dict[
95
+ f"model.layers.{layer_num}.mlp.experts.{i}.up_proj.weight"
96
+ ],
97
+ new_state_dict[
98
+ f"model.layers.{layer_num}.mlp.experts.{i}.gate_proj.weight"
99
+ ],
100
+ ) = torch.chunk(tensor, 2, dim=0)
101
+
102
+ model_standard_moe.load_state_dict(new_state_dict, strict=True, assign=True)
103
+ model_standard_moe.save_pretrained(output_model_path)
104
+ cfg_standard_moe.save_pretrained(output_model_path)
105
+
106
+ shutil.copy(
107
+ "modeling_afmoe.py",
108
+ output_model_path + "/" + "modeling_afmoe.py",
109
+ )
110
+ shutil.copy(
111
+ "configuration_afmoe.py",
112
+ output_model_path + "/" + "configuration_afmoe.py",
113
+ )
114
+
115
+ for i in ["special_tokens_map.json", "tokenizer_config.json", "tokenizer.json", "chat_template.jinja"]:
116
+ shutil.copy(input_model + "/" + i, output_model_path + "/" + i)
117
+
generation_config.json ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "transformers_version": "4.57.3"
4
+ }
model-00001-of-00012.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c6e76bc7093ed7b73fca644c785e14eca4d7f6297018b8fab5004c36bd512182
3
+ size 4504252888
model-00002-of-00012.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7ea06032723cbc8909ce6eb47f26852316f288570933262287292410bd029007
3
+ size 4988115224
model-00003-of-00012.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:940e643ea5a42d83fcea1eccd458908d675862f92d8c56ebdb3a687c54cbbf47
3
+ size 4476952592
model-00004-of-00012.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e5ba37cbf9942002c7a0ac95237771d8bf549f9eb555c9e95800fdbeb3ee9d39
3
+ size 3961053608
model-00005-of-00012.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:702192634903333bf135612a0a11ac04d916e2b4bec44b26fbdf0169184583b9
3
+ size 4988115264
model-00006-of-00012.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4b8dba99959db39cb05970a5aec1e0c849f9847a8f01c136096a5a101d313ecc
3
+ size 4476952640
model-00007-of-00012.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a79061db20e5ee5b92f1aa79fb94e7065aef1d663e18abe2209375940fd42993
3
+ size 3961053624
model-00008-of-00012.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:539a15a7c3e16efe21767557dd55de0ef848e2dbc46dc27c33505a1746240e5f
3
+ size 4988115264
model-00009-of-00012.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:79cc9fcefee2a2d72cdb5b2fc7e46c65483883a9a41bf8c063caa8bcdda5bd10
3
+ size 4476952640
model-00010-of-00012.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:654643950d9f4373bd130d163e7ed2ae19651f4154a2d901b8409b0b507f38e0
3
+ size 3961053624
model-00011-of-00012.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:906da265ef65fc9087d9e1bb192df384a9827170b600019f2b1ec2c3dcd6eae3
3
+ size 4988115264
model-00012-of-00012.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:776c52063a0936746fa9bf67d82edbb4395399699e8fadbaee88fbae0004c572
3
+ size 2477284056
model.safetensors.index.json ADDED
@@ -0,0 +1,579 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "metadata": {
3
+ "total_parameters": 26123974400,
4
+ "total_size": 52247948800
5
+ },
6
+ "weight_map": {
7
+ "lm_head.weight": "model-00012-of-00012.safetensors",
8
+ "model.embed_tokens.weight": "model-00001-of-00012.safetensors",
9
+ "model.layers.0.input_layernorm.weight": "model-00001-of-00012.safetensors",
10
+ "model.layers.0.mlp.down_proj.weight": "model-00001-of-00012.safetensors",
11
+ "model.layers.0.mlp.gate_proj.weight": "model-00001-of-00012.safetensors",
12
+ "model.layers.0.mlp.up_proj.weight": "model-00001-of-00012.safetensors",
13
+ "model.layers.0.post_attention_layernorm.weight": "model-00001-of-00012.safetensors",
14
+ "model.layers.0.post_mlp_layernorm.weight": "model-00001-of-00012.safetensors",
15
+ "model.layers.0.pre_mlp_layernorm.weight": "model-00001-of-00012.safetensors",
16
+ "model.layers.0.self_attn.gate_proj.weight": "model-00001-of-00012.safetensors",
17
+ "model.layers.0.self_attn.k_norm.weight": "model-00001-of-00012.safetensors",
18
+ "model.layers.0.self_attn.k_proj.weight": "model-00001-of-00012.safetensors",
19
+ "model.layers.0.self_attn.o_proj.weight": "model-00001-of-00012.safetensors",
20
+ "model.layers.0.self_attn.q_norm.weight": "model-00001-of-00012.safetensors",
21
+ "model.layers.0.self_attn.q_proj.weight": "model-00001-of-00012.safetensors",
22
+ "model.layers.0.self_attn.v_proj.weight": "model-00001-of-00012.safetensors",
23
+ "model.layers.1.input_layernorm.weight": "model-00001-of-00012.safetensors",
24
+ "model.layers.1.mlp.down_proj.weight": "model-00001-of-00012.safetensors",
25
+ "model.layers.1.mlp.gate_proj.weight": "model-00001-of-00012.safetensors",
26
+ "model.layers.1.mlp.up_proj.weight": "model-00001-of-00012.safetensors",
27
+ "model.layers.1.post_attention_layernorm.weight": "model-00001-of-00012.safetensors",
28
+ "model.layers.1.post_mlp_layernorm.weight": "model-00001-of-00012.safetensors",
29
+ "model.layers.1.pre_mlp_layernorm.weight": "model-00001-of-00012.safetensors",
30
+ "model.layers.1.self_attn.gate_proj.weight": "model-00001-of-00012.safetensors",
31
+ "model.layers.1.self_attn.k_norm.weight": "model-00001-of-00012.safetensors",
32
+ "model.layers.1.self_attn.k_proj.weight": "model-00001-of-00012.safetensors",
33
+ "model.layers.1.self_attn.o_proj.weight": "model-00001-of-00012.safetensors",
34
+ "model.layers.1.self_attn.q_norm.weight": "model-00001-of-00012.safetensors",
35
+ "model.layers.1.self_attn.q_proj.weight": "model-00001-of-00012.safetensors",
36
+ "model.layers.1.self_attn.v_proj.weight": "model-00001-of-00012.safetensors",
37
+ "model.layers.10.input_layernorm.weight": "model-00004-of-00012.safetensors",
38
+ "model.layers.10.mlp.expert_bias": "model-00004-of-00012.safetensors",
39
+ "model.layers.10.mlp.moe_mlp.experts.weight": "model-00004-of-00012.safetensors",
40
+ "model.layers.10.mlp.moe_mlp.output_experts.weight": "model-00004-of-00012.safetensors",
41
+ "model.layers.10.mlp.router.gate.weight": "model-00004-of-00012.safetensors",
42
+ "model.layers.10.mlp.shared_experts.down_proj.weight": "model-00004-of-00012.safetensors",
43
+ "model.layers.10.mlp.shared_experts.gate_proj.weight": "model-00004-of-00012.safetensors",
44
+ "model.layers.10.mlp.shared_experts.up_proj.weight": "model-00004-of-00012.safetensors",
45
+ "model.layers.10.post_attention_layernorm.weight": "model-00004-of-00012.safetensors",
46
+ "model.layers.10.post_mlp_layernorm.weight": "model-00004-of-00012.safetensors",
47
+ "model.layers.10.pre_mlp_layernorm.weight": "model-00004-of-00012.safetensors",
48
+ "model.layers.10.self_attn.gate_proj.weight": "model-00004-of-00012.safetensors",
49
+ "model.layers.10.self_attn.k_norm.weight": "model-00004-of-00012.safetensors",
50
+ "model.layers.10.self_attn.k_proj.weight": "model-00004-of-00012.safetensors",
51
+ "model.layers.10.self_attn.o_proj.weight": "model-00004-of-00012.safetensors",
52
+ "model.layers.10.self_attn.q_norm.weight": "model-00004-of-00012.safetensors",
53
+ "model.layers.10.self_attn.q_proj.weight": "model-00004-of-00012.safetensors",
54
+ "model.layers.10.self_attn.v_proj.weight": "model-00004-of-00012.safetensors",
55
+ "model.layers.11.input_layernorm.weight": "model-00004-of-00012.safetensors",
56
+ "model.layers.11.mlp.expert_bias": "model-00004-of-00012.safetensors",
57
+ "model.layers.11.mlp.moe_mlp.experts.weight": "model-00004-of-00012.safetensors",
58
+ "model.layers.11.mlp.moe_mlp.output_experts.weight": "model-00004-of-00012.safetensors",
59
+ "model.layers.11.mlp.router.gate.weight": "model-00004-of-00012.safetensors",
60
+ "model.layers.11.mlp.shared_experts.down_proj.weight": "model-00004-of-00012.safetensors",
61
+ "model.layers.11.mlp.shared_experts.gate_proj.weight": "model-00004-of-00012.safetensors",
62
+ "model.layers.11.mlp.shared_experts.up_proj.weight": "model-00004-of-00012.safetensors",
63
+ "model.layers.11.post_attention_layernorm.weight": "model-00004-of-00012.safetensors",
64
+ "model.layers.11.post_mlp_layernorm.weight": "model-00004-of-00012.safetensors",
65
+ "model.layers.11.pre_mlp_layernorm.weight": "model-00004-of-00012.safetensors",
66
+ "model.layers.11.self_attn.gate_proj.weight": "model-00004-of-00012.safetensors",
67
+ "model.layers.11.self_attn.k_norm.weight": "model-00004-of-00012.safetensors",
68
+ "model.layers.11.self_attn.k_proj.weight": "model-00004-of-00012.safetensors",
69
+ "model.layers.11.self_attn.o_proj.weight": "model-00004-of-00012.safetensors",
70
+ "model.layers.11.self_attn.q_norm.weight": "model-00004-of-00012.safetensors",
71
+ "model.layers.11.self_attn.q_proj.weight": "model-00004-of-00012.safetensors",
72
+ "model.layers.11.self_attn.v_proj.weight": "model-00004-of-00012.safetensors",
73
+ "model.layers.12.input_layernorm.weight": "model-00004-of-00012.safetensors",
74
+ "model.layers.12.mlp.expert_bias": "model-00004-of-00012.safetensors",
75
+ "model.layers.12.mlp.moe_mlp.experts.weight": "model-00005-of-00012.safetensors",
76
+ "model.layers.12.mlp.moe_mlp.output_experts.weight": "model-00005-of-00012.safetensors",
77
+ "model.layers.12.mlp.router.gate.weight": "model-00004-of-00012.safetensors",
78
+ "model.layers.12.mlp.shared_experts.down_proj.weight": "model-00004-of-00012.safetensors",
79
+ "model.layers.12.mlp.shared_experts.gate_proj.weight": "model-00004-of-00012.safetensors",
80
+ "model.layers.12.mlp.shared_experts.up_proj.weight": "model-00004-of-00012.safetensors",
81
+ "model.layers.12.post_attention_layernorm.weight": "model-00004-of-00012.safetensors",
82
+ "model.layers.12.post_mlp_layernorm.weight": "model-00004-of-00012.safetensors",
83
+ "model.layers.12.pre_mlp_layernorm.weight": "model-00004-of-00012.safetensors",
84
+ "model.layers.12.self_attn.gate_proj.weight": "model-00004-of-00012.safetensors",
85
+ "model.layers.12.self_attn.k_norm.weight": "model-00004-of-00012.safetensors",
86
+ "model.layers.12.self_attn.k_proj.weight": "model-00004-of-00012.safetensors",
87
+ "model.layers.12.self_attn.o_proj.weight": "model-00004-of-00012.safetensors",
88
+ "model.layers.12.self_attn.q_norm.weight": "model-00004-of-00012.safetensors",
89
+ "model.layers.12.self_attn.q_proj.weight": "model-00004-of-00012.safetensors",
90
+ "model.layers.12.self_attn.v_proj.weight": "model-00004-of-00012.safetensors",
91
+ "model.layers.13.input_layernorm.weight": "model-00005-of-00012.safetensors",
92
+ "model.layers.13.mlp.expert_bias": "model-00005-of-00012.safetensors",
93
+ "model.layers.13.mlp.moe_mlp.experts.weight": "model-00005-of-00012.safetensors",
94
+ "model.layers.13.mlp.moe_mlp.output_experts.weight": "model-00005-of-00012.safetensors",
95
+ "model.layers.13.mlp.router.gate.weight": "model-00005-of-00012.safetensors",
96
+ "model.layers.13.mlp.shared_experts.down_proj.weight": "model-00005-of-00012.safetensors",
97
+ "model.layers.13.mlp.shared_experts.gate_proj.weight": "model-00005-of-00012.safetensors",
98
+ "model.layers.13.mlp.shared_experts.up_proj.weight": "model-00005-of-00012.safetensors",
99
+ "model.layers.13.post_attention_layernorm.weight": "model-00005-of-00012.safetensors",
100
+ "model.layers.13.post_mlp_layernorm.weight": "model-00005-of-00012.safetensors",
101
+ "model.layers.13.pre_mlp_layernorm.weight": "model-00005-of-00012.safetensors",
102
+ "model.layers.13.self_attn.gate_proj.weight": "model-00005-of-00012.safetensors",
103
+ "model.layers.13.self_attn.k_norm.weight": "model-00005-of-00012.safetensors",
104
+ "model.layers.13.self_attn.k_proj.weight": "model-00005-of-00012.safetensors",
105
+ "model.layers.13.self_attn.o_proj.weight": "model-00005-of-00012.safetensors",
106
+ "model.layers.13.self_attn.q_norm.weight": "model-00005-of-00012.safetensors",
107
+ "model.layers.13.self_attn.q_proj.weight": "model-00005-of-00012.safetensors",
108
+ "model.layers.13.self_attn.v_proj.weight": "model-00005-of-00012.safetensors",
109
+ "model.layers.14.input_layernorm.weight": "model-00005-of-00012.safetensors",
110
+ "model.layers.14.mlp.expert_bias": "model-00005-of-00012.safetensors",
111
+ "model.layers.14.mlp.moe_mlp.experts.weight": "model-00005-of-00012.safetensors",
112
+ "model.layers.14.mlp.moe_mlp.output_experts.weight": "model-00005-of-00012.safetensors",
113
+ "model.layers.14.mlp.router.gate.weight": "model-00005-of-00012.safetensors",
114
+ "model.layers.14.mlp.shared_experts.down_proj.weight": "model-00005-of-00012.safetensors",
115
+ "model.layers.14.mlp.shared_experts.gate_proj.weight": "model-00005-of-00012.safetensors",
116
+ "model.layers.14.mlp.shared_experts.up_proj.weight": "model-00005-of-00012.safetensors",
117
+ "model.layers.14.post_attention_layernorm.weight": "model-00005-of-00012.safetensors",
118
+ "model.layers.14.post_mlp_layernorm.weight": "model-00005-of-00012.safetensors",
119
+ "model.layers.14.pre_mlp_layernorm.weight": "model-00005-of-00012.safetensors",
120
+ "model.layers.14.self_attn.gate_proj.weight": "model-00005-of-00012.safetensors",
121
+ "model.layers.14.self_attn.k_norm.weight": "model-00005-of-00012.safetensors",
122
+ "model.layers.14.self_attn.k_proj.weight": "model-00005-of-00012.safetensors",
123
+ "model.layers.14.self_attn.o_proj.weight": "model-00005-of-00012.safetensors",
124
+ "model.layers.14.self_attn.q_norm.weight": "model-00005-of-00012.safetensors",
125
+ "model.layers.14.self_attn.q_proj.weight": "model-00005-of-00012.safetensors",
126
+ "model.layers.14.self_attn.v_proj.weight": "model-00005-of-00012.safetensors",
127
+ "model.layers.15.input_layernorm.weight": "model-00006-of-00012.safetensors",
128
+ "model.layers.15.mlp.expert_bias": "model-00006-of-00012.safetensors",
129
+ "model.layers.15.mlp.moe_mlp.experts.weight": "model-00006-of-00012.safetensors",
130
+ "model.layers.15.mlp.moe_mlp.output_experts.weight": "model-00006-of-00012.safetensors",
131
+ "model.layers.15.mlp.router.gate.weight": "model-00006-of-00012.safetensors",
132
+ "model.layers.15.mlp.shared_experts.down_proj.weight": "model-00006-of-00012.safetensors",
133
+ "model.layers.15.mlp.shared_experts.gate_proj.weight": "model-00006-of-00012.safetensors",
134
+ "model.layers.15.mlp.shared_experts.up_proj.weight": "model-00006-of-00012.safetensors",
135
+ "model.layers.15.post_attention_layernorm.weight": "model-00006-of-00012.safetensors",
136
+ "model.layers.15.post_mlp_layernorm.weight": "model-00006-of-00012.safetensors",
137
+ "model.layers.15.pre_mlp_layernorm.weight": "model-00006-of-00012.safetensors",
138
+ "model.layers.15.self_attn.gate_proj.weight": "model-00006-of-00012.safetensors",
139
+ "model.layers.15.self_attn.k_norm.weight": "model-00006-of-00012.safetensors",
140
+ "model.layers.15.self_attn.k_proj.weight": "model-00005-of-00012.safetensors",
141
+ "model.layers.15.self_attn.o_proj.weight": "model-00006-of-00012.safetensors",
142
+ "model.layers.15.self_attn.q_norm.weight": "model-00006-of-00012.safetensors",
143
+ "model.layers.15.self_attn.q_proj.weight": "model-00005-of-00012.safetensors",
144
+ "model.layers.15.self_attn.v_proj.weight": "model-00005-of-00012.safetensors",
145
+ "model.layers.16.input_layernorm.weight": "model-00006-of-00012.safetensors",
146
+ "model.layers.16.mlp.expert_bias": "model-00006-of-00012.safetensors",
147
+ "model.layers.16.mlp.moe_mlp.experts.weight": "model-00006-of-00012.safetensors",
148
+ "model.layers.16.mlp.moe_mlp.output_experts.weight": "model-00006-of-00012.safetensors",
149
+ "model.layers.16.mlp.router.gate.weight": "model-00006-of-00012.safetensors",
150
+ "model.layers.16.mlp.shared_experts.down_proj.weight": "model-00006-of-00012.safetensors",
151
+ "model.layers.16.mlp.shared_experts.gate_proj.weight": "model-00006-of-00012.safetensors",
152
+ "model.layers.16.mlp.shared_experts.up_proj.weight": "model-00006-of-00012.safetensors",
153
+ "model.layers.16.post_attention_layernorm.weight": "model-00006-of-00012.safetensors",
154
+ "model.layers.16.post_mlp_layernorm.weight": "model-00006-of-00012.safetensors",
155
+ "model.layers.16.pre_mlp_layernorm.weight": "model-00006-of-00012.safetensors",
156
+ "model.layers.16.self_attn.gate_proj.weight": "model-00006-of-00012.safetensors",
157
+ "model.layers.16.self_attn.k_norm.weight": "model-00006-of-00012.safetensors",
158
+ "model.layers.16.self_attn.k_proj.weight": "model-00006-of-00012.safetensors",
159
+ "model.layers.16.self_attn.o_proj.weight": "model-00006-of-00012.safetensors",
160
+ "model.layers.16.self_attn.q_norm.weight": "model-00006-of-00012.safetensors",
161
+ "model.layers.16.self_attn.q_proj.weight": "model-00006-of-00012.safetensors",
162
+ "model.layers.16.self_attn.v_proj.weight": "model-00006-of-00012.safetensors",
163
+ "model.layers.17.input_layernorm.weight": "model-00006-of-00012.safetensors",
164
+ "model.layers.17.mlp.expert_bias": "model-00006-of-00012.safetensors",
165
+ "model.layers.17.mlp.moe_mlp.experts.weight": "model-00006-of-00012.safetensors",
166
+ "model.layers.17.mlp.moe_mlp.output_experts.weight": "model-00007-of-00012.safetensors",
167
+ "model.layers.17.mlp.router.gate.weight": "model-00006-of-00012.safetensors",
168
+ "model.layers.17.mlp.shared_experts.down_proj.weight": "model-00006-of-00012.safetensors",
169
+ "model.layers.17.mlp.shared_experts.gate_proj.weight": "model-00006-of-00012.safetensors",
170
+ "model.layers.17.mlp.shared_experts.up_proj.weight": "model-00006-of-00012.safetensors",
171
+ "model.layers.17.post_attention_layernorm.weight": "model-00006-of-00012.safetensors",
172
+ "model.layers.17.post_mlp_layernorm.weight": "model-00006-of-00012.safetensors",
173
+ "model.layers.17.pre_mlp_layernorm.weight": "model-00006-of-00012.safetensors",
174
+ "model.layers.17.self_attn.gate_proj.weight": "model-00006-of-00012.safetensors",
175
+ "model.layers.17.self_attn.k_norm.weight": "model-00006-of-00012.safetensors",
176
+ "model.layers.17.self_attn.k_proj.weight": "model-00006-of-00012.safetensors",
177
+ "model.layers.17.self_attn.o_proj.weight": "model-00006-of-00012.safetensors",
178
+ "model.layers.17.self_attn.q_norm.weight": "model-00006-of-00012.safetensors",
179
+ "model.layers.17.self_attn.q_proj.weight": "model-00006-of-00012.safetensors",
180
+ "model.layers.17.self_attn.v_proj.weight": "model-00006-of-00012.safetensors",
181
+ "model.layers.18.input_layernorm.weight": "model-00007-of-00012.safetensors",
182
+ "model.layers.18.mlp.expert_bias": "model-00007-of-00012.safetensors",
183
+ "model.layers.18.mlp.moe_mlp.experts.weight": "model-00007-of-00012.safetensors",
184
+ "model.layers.18.mlp.moe_mlp.output_experts.weight": "model-00007-of-00012.safetensors",
185
+ "model.layers.18.mlp.router.gate.weight": "model-00007-of-00012.safetensors",
186
+ "model.layers.18.mlp.shared_experts.down_proj.weight": "model-00007-of-00012.safetensors",
187
+ "model.layers.18.mlp.shared_experts.gate_proj.weight": "model-00007-of-00012.safetensors",
188
+ "model.layers.18.mlp.shared_experts.up_proj.weight": "model-00007-of-00012.safetensors",
189
+ "model.layers.18.post_attention_layernorm.weight": "model-00007-of-00012.safetensors",
190
+ "model.layers.18.post_mlp_layernorm.weight": "model-00007-of-00012.safetensors",
191
+ "model.layers.18.pre_mlp_layernorm.weight": "model-00007-of-00012.safetensors",
192
+ "model.layers.18.self_attn.gate_proj.weight": "model-00007-of-00012.safetensors",
193
+ "model.layers.18.self_attn.k_norm.weight": "model-00007-of-00012.safetensors",
194
+ "model.layers.18.self_attn.k_proj.weight": "model-00007-of-00012.safetensors",
195
+ "model.layers.18.self_attn.o_proj.weight": "model-00007-of-00012.safetensors",
196
+ "model.layers.18.self_attn.q_norm.weight": "model-00007-of-00012.safetensors",
197
+ "model.layers.18.self_attn.q_proj.weight": "model-00007-of-00012.safetensors",
198
+ "model.layers.18.self_attn.v_proj.weight": "model-00007-of-00012.safetensors",
199
+ "model.layers.19.input_layernorm.weight": "model-00007-of-00012.safetensors",
200
+ "model.layers.19.mlp.expert_bias": "model-00007-of-00012.safetensors",
201
+ "model.layers.19.mlp.moe_mlp.experts.weight": "model-00007-of-00012.safetensors",
202
+ "model.layers.19.mlp.moe_mlp.output_experts.weight": "model-00007-of-00012.safetensors",
203
+ "model.layers.19.mlp.router.gate.weight": "model-00007-of-00012.safetensors",
204
+ "model.layers.19.mlp.shared_experts.down_proj.weight": "model-00007-of-00012.safetensors",
205
+ "model.layers.19.mlp.shared_experts.gate_proj.weight": "model-00007-of-00012.safetensors",
206
+ "model.layers.19.mlp.shared_experts.up_proj.weight": "model-00007-of-00012.safetensors",
207
+ "model.layers.19.post_attention_layernorm.weight": "model-00007-of-00012.safetensors",
208
+ "model.layers.19.post_mlp_layernorm.weight": "model-00007-of-00012.safetensors",
209
+ "model.layers.19.pre_mlp_layernorm.weight": "model-00007-of-00012.safetensors",
210
+ "model.layers.19.self_attn.gate_proj.weight": "model-00007-of-00012.safetensors",
211
+ "model.layers.19.self_attn.k_norm.weight": "model-00007-of-00012.safetensors",
212
+ "model.layers.19.self_attn.k_proj.weight": "model-00007-of-00012.safetensors",
213
+ "model.layers.19.self_attn.o_proj.weight": "model-00007-of-00012.safetensors",
214
+ "model.layers.19.self_attn.q_norm.weight": "model-00007-of-00012.safetensors",
215
+ "model.layers.19.self_attn.q_proj.weight": "model-00007-of-00012.safetensors",
216
+ "model.layers.19.self_attn.v_proj.weight": "model-00007-of-00012.safetensors",
217
+ "model.layers.2.input_layernorm.weight": "model-00001-of-00012.safetensors",
218
+ "model.layers.2.mlp.expert_bias": "model-00001-of-00012.safetensors",
219
+ "model.layers.2.mlp.moe_mlp.experts.weight": "model-00001-of-00012.safetensors",
220
+ "model.layers.2.mlp.moe_mlp.output_experts.weight": "model-00001-of-00012.safetensors",
221
+ "model.layers.2.mlp.router.gate.weight": "model-00001-of-00012.safetensors",
222
+ "model.layers.2.mlp.shared_experts.down_proj.weight": "model-00001-of-00012.safetensors",
223
+ "model.layers.2.mlp.shared_experts.gate_proj.weight": "model-00001-of-00012.safetensors",
224
+ "model.layers.2.mlp.shared_experts.up_proj.weight": "model-00001-of-00012.safetensors",
225
+ "model.layers.2.post_attention_layernorm.weight": "model-00001-of-00012.safetensors",
226
+ "model.layers.2.post_mlp_layernorm.weight": "model-00001-of-00012.safetensors",
227
+ "model.layers.2.pre_mlp_layernorm.weight": "model-00001-of-00012.safetensors",
228
+ "model.layers.2.self_attn.gate_proj.weight": "model-00001-of-00012.safetensors",
229
+ "model.layers.2.self_attn.k_norm.weight": "model-00001-of-00012.safetensors",
230
+ "model.layers.2.self_attn.k_proj.weight": "model-00001-of-00012.safetensors",
231
+ "model.layers.2.self_attn.o_proj.weight": "model-00001-of-00012.safetensors",
232
+ "model.layers.2.self_attn.q_norm.weight": "model-00001-of-00012.safetensors",
233
+ "model.layers.2.self_attn.q_proj.weight": "model-00001-of-00012.safetensors",
234
+ "model.layers.2.self_attn.v_proj.weight": "model-00001-of-00012.safetensors",
235
+ "model.layers.20.input_layernorm.weight": "model-00007-of-00012.safetensors",
236
+ "model.layers.20.mlp.expert_bias": "model-00007-of-00012.safetensors",
237
+ "model.layers.20.mlp.moe_mlp.experts.weight": "model-00008-of-00012.safetensors",
238
+ "model.layers.20.mlp.moe_mlp.output_experts.weight": "model-00008-of-00012.safetensors",
239
+ "model.layers.20.mlp.router.gate.weight": "model-00007-of-00012.safetensors",
240
+ "model.layers.20.mlp.shared_experts.down_proj.weight": "model-00007-of-00012.safetensors",
241
+ "model.layers.20.mlp.shared_experts.gate_proj.weight": "model-00007-of-00012.safetensors",
242
+ "model.layers.20.mlp.shared_experts.up_proj.weight": "model-00007-of-00012.safetensors",
243
+ "model.layers.20.post_attention_layernorm.weight": "model-00007-of-00012.safetensors",
244
+ "model.layers.20.post_mlp_layernorm.weight": "model-00007-of-00012.safetensors",
245
+ "model.layers.20.pre_mlp_layernorm.weight": "model-00007-of-00012.safetensors",
246
+ "model.layers.20.self_attn.gate_proj.weight": "model-00007-of-00012.safetensors",
247
+ "model.layers.20.self_attn.k_norm.weight": "model-00007-of-00012.safetensors",
248
+ "model.layers.20.self_attn.k_proj.weight": "model-00007-of-00012.safetensors",
249
+ "model.layers.20.self_attn.o_proj.weight": "model-00007-of-00012.safetensors",
250
+ "model.layers.20.self_attn.q_norm.weight": "model-00007-of-00012.safetensors",
251
+ "model.layers.20.self_attn.q_proj.weight": "model-00007-of-00012.safetensors",
252
+ "model.layers.20.self_attn.v_proj.weight": "model-00007-of-00012.safetensors",
253
+ "model.layers.21.input_layernorm.weight": "model-00008-of-00012.safetensors",
254
+ "model.layers.21.mlp.expert_bias": "model-00008-of-00012.safetensors",
255
+ "model.layers.21.mlp.moe_mlp.experts.weight": "model-00008-of-00012.safetensors",
256
+ "model.layers.21.mlp.moe_mlp.output_experts.weight": "model-00008-of-00012.safetensors",
257
+ "model.layers.21.mlp.router.gate.weight": "model-00008-of-00012.safetensors",
258
+ "model.layers.21.mlp.shared_experts.down_proj.weight": "model-00008-of-00012.safetensors",
259
+ "model.layers.21.mlp.shared_experts.gate_proj.weight": "model-00008-of-00012.safetensors",
260
+ "model.layers.21.mlp.shared_experts.up_proj.weight": "model-00008-of-00012.safetensors",
261
+ "model.layers.21.post_attention_layernorm.weight": "model-00008-of-00012.safetensors",
262
+ "model.layers.21.post_mlp_layernorm.weight": "model-00008-of-00012.safetensors",
263
+ "model.layers.21.pre_mlp_layernorm.weight": "model-00008-of-00012.safetensors",
264
+ "model.layers.21.self_attn.gate_proj.weight": "model-00008-of-00012.safetensors",
265
+ "model.layers.21.self_attn.k_norm.weight": "model-00008-of-00012.safetensors",
266
+ "model.layers.21.self_attn.k_proj.weight": "model-00008-of-00012.safetensors",
267
+ "model.layers.21.self_attn.o_proj.weight": "model-00008-of-00012.safetensors",
268
+ "model.layers.21.self_attn.q_norm.weight": "model-00008-of-00012.safetensors",
269
+ "model.layers.21.self_attn.q_proj.weight": "model-00008-of-00012.safetensors",
270
+ "model.layers.21.self_attn.v_proj.weight": "model-00008-of-00012.safetensors",
271
+ "model.layers.22.input_layernorm.weight": "model-00008-of-00012.safetensors",
272
+ "model.layers.22.mlp.expert_bias": "model-00008-of-00012.safetensors",
273
+ "model.layers.22.mlp.moe_mlp.experts.weight": "model-00008-of-00012.safetensors",
274
+ "model.layers.22.mlp.moe_mlp.output_experts.weight": "model-00008-of-00012.safetensors",
275
+ "model.layers.22.mlp.router.gate.weight": "model-00008-of-00012.safetensors",
276
+ "model.layers.22.mlp.shared_experts.down_proj.weight": "model-00008-of-00012.safetensors",
277
+ "model.layers.22.mlp.shared_experts.gate_proj.weight": "model-00008-of-00012.safetensors",
278
+ "model.layers.22.mlp.shared_experts.up_proj.weight": "model-00008-of-00012.safetensors",
279
+ "model.layers.22.post_attention_layernorm.weight": "model-00008-of-00012.safetensors",
280
+ "model.layers.22.post_mlp_layernorm.weight": "model-00008-of-00012.safetensors",
281
+ "model.layers.22.pre_mlp_layernorm.weight": "model-00008-of-00012.safetensors",
282
+ "model.layers.22.self_attn.gate_proj.weight": "model-00008-of-00012.safetensors",
283
+ "model.layers.22.self_attn.k_norm.weight": "model-00008-of-00012.safetensors",
284
+ "model.layers.22.self_attn.k_proj.weight": "model-00008-of-00012.safetensors",
285
+ "model.layers.22.self_attn.o_proj.weight": "model-00008-of-00012.safetensors",
286
+ "model.layers.22.self_attn.q_norm.weight": "model-00008-of-00012.safetensors",
287
+ "model.layers.22.self_attn.q_proj.weight": "model-00008-of-00012.safetensors",
288
+ "model.layers.22.self_attn.v_proj.weight": "model-00008-of-00012.safetensors",
289
+ "model.layers.23.input_layernorm.weight": "model-00009-of-00012.safetensors",
290
+ "model.layers.23.mlp.expert_bias": "model-00009-of-00012.safetensors",
291
+ "model.layers.23.mlp.moe_mlp.experts.weight": "model-00009-of-00012.safetensors",
292
+ "model.layers.23.mlp.moe_mlp.output_experts.weight": "model-00009-of-00012.safetensors",
293
+ "model.layers.23.mlp.router.gate.weight": "model-00009-of-00012.safetensors",
294
+ "model.layers.23.mlp.shared_experts.down_proj.weight": "model-00009-of-00012.safetensors",
295
+ "model.layers.23.mlp.shared_experts.gate_proj.weight": "model-00009-of-00012.safetensors",
296
+ "model.layers.23.mlp.shared_experts.up_proj.weight": "model-00009-of-00012.safetensors",
297
+ "model.layers.23.post_attention_layernorm.weight": "model-00009-of-00012.safetensors",
298
+ "model.layers.23.post_mlp_layernorm.weight": "model-00009-of-00012.safetensors",
299
+ "model.layers.23.pre_mlp_layernorm.weight": "model-00009-of-00012.safetensors",
300
+ "model.layers.23.self_attn.gate_proj.weight": "model-00009-of-00012.safetensors",
301
+ "model.layers.23.self_attn.k_norm.weight": "model-00009-of-00012.safetensors",
302
+ "model.layers.23.self_attn.k_proj.weight": "model-00008-of-00012.safetensors",
303
+ "model.layers.23.self_attn.o_proj.weight": "model-00009-of-00012.safetensors",
304
+ "model.layers.23.self_attn.q_norm.weight": "model-00009-of-00012.safetensors",
305
+ "model.layers.23.self_attn.q_proj.weight": "model-00008-of-00012.safetensors",
306
+ "model.layers.23.self_attn.v_proj.weight": "model-00008-of-00012.safetensors",
307
+ "model.layers.24.input_layernorm.weight": "model-00009-of-00012.safetensors",
308
+ "model.layers.24.mlp.expert_bias": "model-00009-of-00012.safetensors",
309
+ "model.layers.24.mlp.moe_mlp.experts.weight": "model-00009-of-00012.safetensors",
310
+ "model.layers.24.mlp.moe_mlp.output_experts.weight": "model-00009-of-00012.safetensors",
311
+ "model.layers.24.mlp.router.gate.weight": "model-00009-of-00012.safetensors",
312
+ "model.layers.24.mlp.shared_experts.down_proj.weight": "model-00009-of-00012.safetensors",
313
+ "model.layers.24.mlp.shared_experts.gate_proj.weight": "model-00009-of-00012.safetensors",
314
+ "model.layers.24.mlp.shared_experts.up_proj.weight": "model-00009-of-00012.safetensors",
315
+ "model.layers.24.post_attention_layernorm.weight": "model-00009-of-00012.safetensors",
316
+ "model.layers.24.post_mlp_layernorm.weight": "model-00009-of-00012.safetensors",
317
+ "model.layers.24.pre_mlp_layernorm.weight": "model-00009-of-00012.safetensors",
318
+ "model.layers.24.self_attn.gate_proj.weight": "model-00009-of-00012.safetensors",
319
+ "model.layers.24.self_attn.k_norm.weight": "model-00009-of-00012.safetensors",
320
+ "model.layers.24.self_attn.k_proj.weight": "model-00009-of-00012.safetensors",
321
+ "model.layers.24.self_attn.o_proj.weight": "model-00009-of-00012.safetensors",
322
+ "model.layers.24.self_attn.q_norm.weight": "model-00009-of-00012.safetensors",
323
+ "model.layers.24.self_attn.q_proj.weight": "model-00009-of-00012.safetensors",
324
+ "model.layers.24.self_attn.v_proj.weight": "model-00009-of-00012.safetensors",
325
+ "model.layers.25.input_layernorm.weight": "model-00009-of-00012.safetensors",
326
+ "model.layers.25.mlp.expert_bias": "model-00009-of-00012.safetensors",
327
+ "model.layers.25.mlp.moe_mlp.experts.weight": "model-00009-of-00012.safetensors",
328
+ "model.layers.25.mlp.moe_mlp.output_experts.weight": "model-00010-of-00012.safetensors",
329
+ "model.layers.25.mlp.router.gate.weight": "model-00009-of-00012.safetensors",
330
+ "model.layers.25.mlp.shared_experts.down_proj.weight": "model-00009-of-00012.safetensors",
331
+ "model.layers.25.mlp.shared_experts.gate_proj.weight": "model-00009-of-00012.safetensors",
332
+ "model.layers.25.mlp.shared_experts.up_proj.weight": "model-00009-of-00012.safetensors",
333
+ "model.layers.25.post_attention_layernorm.weight": "model-00009-of-00012.safetensors",
334
+ "model.layers.25.post_mlp_layernorm.weight": "model-00009-of-00012.safetensors",
335
+ "model.layers.25.pre_mlp_layernorm.weight": "model-00009-of-00012.safetensors",
336
+ "model.layers.25.self_attn.gate_proj.weight": "model-00009-of-00012.safetensors",
337
+ "model.layers.25.self_attn.k_norm.weight": "model-00009-of-00012.safetensors",
338
+ "model.layers.25.self_attn.k_proj.weight": "model-00009-of-00012.safetensors",
339
+ "model.layers.25.self_attn.o_proj.weight": "model-00009-of-00012.safetensors",
340
+ "model.layers.25.self_attn.q_norm.weight": "model-00009-of-00012.safetensors",
341
+ "model.layers.25.self_attn.q_proj.weight": "model-00009-of-00012.safetensors",
342
+ "model.layers.25.self_attn.v_proj.weight": "model-00009-of-00012.safetensors",
343
+ "model.layers.26.input_layernorm.weight": "model-00010-of-00012.safetensors",
344
+ "model.layers.26.mlp.expert_bias": "model-00010-of-00012.safetensors",
345
+ "model.layers.26.mlp.moe_mlp.experts.weight": "model-00010-of-00012.safetensors",
346
+ "model.layers.26.mlp.moe_mlp.output_experts.weight": "model-00010-of-00012.safetensors",
347
+ "model.layers.26.mlp.router.gate.weight": "model-00010-of-00012.safetensors",
348
+ "model.layers.26.mlp.shared_experts.down_proj.weight": "model-00010-of-00012.safetensors",
349
+ "model.layers.26.mlp.shared_experts.gate_proj.weight": "model-00010-of-00012.safetensors",
350
+ "model.layers.26.mlp.shared_experts.up_proj.weight": "model-00010-of-00012.safetensors",
351
+ "model.layers.26.post_attention_layernorm.weight": "model-00010-of-00012.safetensors",
352
+ "model.layers.26.post_mlp_layernorm.weight": "model-00010-of-00012.safetensors",
353
+ "model.layers.26.pre_mlp_layernorm.weight": "model-00010-of-00012.safetensors",
354
+ "model.layers.26.self_attn.gate_proj.weight": "model-00010-of-00012.safetensors",
355
+ "model.layers.26.self_attn.k_norm.weight": "model-00010-of-00012.safetensors",
356
+ "model.layers.26.self_attn.k_proj.weight": "model-00010-of-00012.safetensors",
357
+ "model.layers.26.self_attn.o_proj.weight": "model-00010-of-00012.safetensors",
358
+ "model.layers.26.self_attn.q_norm.weight": "model-00010-of-00012.safetensors",
359
+ "model.layers.26.self_attn.q_proj.weight": "model-00010-of-00012.safetensors",
360
+ "model.layers.26.self_attn.v_proj.weight": "model-00010-of-00012.safetensors",
361
+ "model.layers.27.input_layernorm.weight": "model-00010-of-00012.safetensors",
362
+ "model.layers.27.mlp.expert_bias": "model-00010-of-00012.safetensors",
363
+ "model.layers.27.mlp.moe_mlp.experts.weight": "model-00010-of-00012.safetensors",
364
+ "model.layers.27.mlp.moe_mlp.output_experts.weight": "model-00010-of-00012.safetensors",
365
+ "model.layers.27.mlp.router.gate.weight": "model-00010-of-00012.safetensors",
366
+ "model.layers.27.mlp.shared_experts.down_proj.weight": "model-00010-of-00012.safetensors",
367
+ "model.layers.27.mlp.shared_experts.gate_proj.weight": "model-00010-of-00012.safetensors",
368
+ "model.layers.27.mlp.shared_experts.up_proj.weight": "model-00010-of-00012.safetensors",
369
+ "model.layers.27.post_attention_layernorm.weight": "model-00010-of-00012.safetensors",
370
+ "model.layers.27.post_mlp_layernorm.weight": "model-00010-of-00012.safetensors",
371
+ "model.layers.27.pre_mlp_layernorm.weight": "model-00010-of-00012.safetensors",
372
+ "model.layers.27.self_attn.gate_proj.weight": "model-00010-of-00012.safetensors",
373
+ "model.layers.27.self_attn.k_norm.weight": "model-00010-of-00012.safetensors",
374
+ "model.layers.27.self_attn.k_proj.weight": "model-00010-of-00012.safetensors",
375
+ "model.layers.27.self_attn.o_proj.weight": "model-00010-of-00012.safetensors",
376
+ "model.layers.27.self_attn.q_norm.weight": "model-00010-of-00012.safetensors",
377
+ "model.layers.27.self_attn.q_proj.weight": "model-00010-of-00012.safetensors",
378
+ "model.layers.27.self_attn.v_proj.weight": "model-00010-of-00012.safetensors",
379
+ "model.layers.28.input_layernorm.weight": "model-00010-of-00012.safetensors",
380
+ "model.layers.28.mlp.expert_bias": "model-00010-of-00012.safetensors",
381
+ "model.layers.28.mlp.moe_mlp.experts.weight": "model-00011-of-00012.safetensors",
382
+ "model.layers.28.mlp.moe_mlp.output_experts.weight": "model-00011-of-00012.safetensors",
383
+ "model.layers.28.mlp.router.gate.weight": "model-00010-of-00012.safetensors",
384
+ "model.layers.28.mlp.shared_experts.down_proj.weight": "model-00010-of-00012.safetensors",
385
+ "model.layers.28.mlp.shared_experts.gate_proj.weight": "model-00010-of-00012.safetensors",
386
+ "model.layers.28.mlp.shared_experts.up_proj.weight": "model-00010-of-00012.safetensors",
387
+ "model.layers.28.post_attention_layernorm.weight": "model-00010-of-00012.safetensors",
388
+ "model.layers.28.post_mlp_layernorm.weight": "model-00010-of-00012.safetensors",
389
+ "model.layers.28.pre_mlp_layernorm.weight": "model-00010-of-00012.safetensors",
390
+ "model.layers.28.self_attn.gate_proj.weight": "model-00010-of-00012.safetensors",
391
+ "model.layers.28.self_attn.k_norm.weight": "model-00010-of-00012.safetensors",
392
+ "model.layers.28.self_attn.k_proj.weight": "model-00010-of-00012.safetensors",
393
+ "model.layers.28.self_attn.o_proj.weight": "model-00010-of-00012.safetensors",
394
+ "model.layers.28.self_attn.q_norm.weight": "model-00010-of-00012.safetensors",
395
+ "model.layers.28.self_attn.q_proj.weight": "model-00010-of-00012.safetensors",
396
+ "model.layers.28.self_attn.v_proj.weight": "model-00010-of-00012.safetensors",
397
+ "model.layers.29.input_layernorm.weight": "model-00011-of-00012.safetensors",
398
+ "model.layers.29.mlp.expert_bias": "model-00011-of-00012.safetensors",
399
+ "model.layers.29.mlp.moe_mlp.experts.weight": "model-00011-of-00012.safetensors",
400
+ "model.layers.29.mlp.moe_mlp.output_experts.weight": "model-00011-of-00012.safetensors",
401
+ "model.layers.29.mlp.router.gate.weight": "model-00011-of-00012.safetensors",
402
+ "model.layers.29.mlp.shared_experts.down_proj.weight": "model-00011-of-00012.safetensors",
403
+ "model.layers.29.mlp.shared_experts.gate_proj.weight": "model-00011-of-00012.safetensors",
404
+ "model.layers.29.mlp.shared_experts.up_proj.weight": "model-00011-of-00012.safetensors",
405
+ "model.layers.29.post_attention_layernorm.weight": "model-00011-of-00012.safetensors",
406
+ "model.layers.29.post_mlp_layernorm.weight": "model-00011-of-00012.safetensors",
407
+ "model.layers.29.pre_mlp_layernorm.weight": "model-00011-of-00012.safetensors",
408
+ "model.layers.29.self_attn.gate_proj.weight": "model-00011-of-00012.safetensors",
409
+ "model.layers.29.self_attn.k_norm.weight": "model-00011-of-00012.safetensors",
410
+ "model.layers.29.self_attn.k_proj.weight": "model-00011-of-00012.safetensors",
411
+ "model.layers.29.self_attn.o_proj.weight": "model-00011-of-00012.safetensors",
412
+ "model.layers.29.self_attn.q_norm.weight": "model-00011-of-00012.safetensors",
413
+ "model.layers.29.self_attn.q_proj.weight": "model-00011-of-00012.safetensors",
414
+ "model.layers.29.self_attn.v_proj.weight": "model-00011-of-00012.safetensors",
415
+ "model.layers.3.input_layernorm.weight": "model-00001-of-00012.safetensors",
416
+ "model.layers.3.mlp.expert_bias": "model-00001-of-00012.safetensors",
417
+ "model.layers.3.mlp.moe_mlp.experts.weight": "model-00001-of-00012.safetensors",
418
+ "model.layers.3.mlp.moe_mlp.output_experts.weight": "model-00001-of-00012.safetensors",
419
+ "model.layers.3.mlp.router.gate.weight": "model-00001-of-00012.safetensors",
420
+ "model.layers.3.mlp.shared_experts.down_proj.weight": "model-00001-of-00012.safetensors",
421
+ "model.layers.3.mlp.shared_experts.gate_proj.weight": "model-00001-of-00012.safetensors",
422
+ "model.layers.3.mlp.shared_experts.up_proj.weight": "model-00001-of-00012.safetensors",
423
+ "model.layers.3.post_attention_layernorm.weight": "model-00001-of-00012.safetensors",
424
+ "model.layers.3.post_mlp_layernorm.weight": "model-00001-of-00012.safetensors",
425
+ "model.layers.3.pre_mlp_layernorm.weight": "model-00001-of-00012.safetensors",
426
+ "model.layers.3.self_attn.gate_proj.weight": "model-00001-of-00012.safetensors",
427
+ "model.layers.3.self_attn.k_norm.weight": "model-00001-of-00012.safetensors",
428
+ "model.layers.3.self_attn.k_proj.weight": "model-00001-of-00012.safetensors",
429
+ "model.layers.3.self_attn.o_proj.weight": "model-00001-of-00012.safetensors",
430
+ "model.layers.3.self_attn.q_norm.weight": "model-00001-of-00012.safetensors",
431
+ "model.layers.3.self_attn.q_proj.weight": "model-00001-of-00012.safetensors",
432
+ "model.layers.3.self_attn.v_proj.weight": "model-00001-of-00012.safetensors",
433
+ "model.layers.30.input_layernorm.weight": "model-00011-of-00012.safetensors",
434
+ "model.layers.30.mlp.expert_bias": "model-00011-of-00012.safetensors",
435
+ "model.layers.30.mlp.moe_mlp.experts.weight": "model-00011-of-00012.safetensors",
436
+ "model.layers.30.mlp.moe_mlp.output_experts.weight": "model-00011-of-00012.safetensors",
437
+ "model.layers.30.mlp.router.gate.weight": "model-00011-of-00012.safetensors",
438
+ "model.layers.30.mlp.shared_experts.down_proj.weight": "model-00011-of-00012.safetensors",
439
+ "model.layers.30.mlp.shared_experts.gate_proj.weight": "model-00011-of-00012.safetensors",
440
+ "model.layers.30.mlp.shared_experts.up_proj.weight": "model-00011-of-00012.safetensors",
441
+ "model.layers.30.post_attention_layernorm.weight": "model-00011-of-00012.safetensors",
442
+ "model.layers.30.post_mlp_layernorm.weight": "model-00011-of-00012.safetensors",
443
+ "model.layers.30.pre_mlp_layernorm.weight": "model-00011-of-00012.safetensors",
444
+ "model.layers.30.self_attn.gate_proj.weight": "model-00011-of-00012.safetensors",
445
+ "model.layers.30.self_attn.k_norm.weight": "model-00011-of-00012.safetensors",
446
+ "model.layers.30.self_attn.k_proj.weight": "model-00011-of-00012.safetensors",
447
+ "model.layers.30.self_attn.o_proj.weight": "model-00011-of-00012.safetensors",
448
+ "model.layers.30.self_attn.q_norm.weight": "model-00011-of-00012.safetensors",
449
+ "model.layers.30.self_attn.q_proj.weight": "model-00011-of-00012.safetensors",
450
+ "model.layers.30.self_attn.v_proj.weight": "model-00011-of-00012.safetensors",
451
+ "model.layers.31.input_layernorm.weight": "model-00012-of-00012.safetensors",
452
+ "model.layers.31.mlp.expert_bias": "model-00012-of-00012.safetensors",
453
+ "model.layers.31.mlp.moe_mlp.experts.weight": "model-00012-of-00012.safetensors",
454
+ "model.layers.31.mlp.moe_mlp.output_experts.weight": "model-00012-of-00012.safetensors",
455
+ "model.layers.31.mlp.router.gate.weight": "model-00012-of-00012.safetensors",
456
+ "model.layers.31.mlp.shared_experts.down_proj.weight": "model-00012-of-00012.safetensors",
457
+ "model.layers.31.mlp.shared_experts.gate_proj.weight": "model-00012-of-00012.safetensors",
458
+ "model.layers.31.mlp.shared_experts.up_proj.weight": "model-00012-of-00012.safetensors",
459
+ "model.layers.31.post_attention_layernorm.weight": "model-00012-of-00012.safetensors",
460
+ "model.layers.31.post_mlp_layernorm.weight": "model-00012-of-00012.safetensors",
461
+ "model.layers.31.pre_mlp_layernorm.weight": "model-00012-of-00012.safetensors",
462
+ "model.layers.31.self_attn.gate_proj.weight": "model-00012-of-00012.safetensors",
463
+ "model.layers.31.self_attn.k_norm.weight": "model-00012-of-00012.safetensors",
464
+ "model.layers.31.self_attn.k_proj.weight": "model-00011-of-00012.safetensors",
465
+ "model.layers.31.self_attn.o_proj.weight": "model-00012-of-00012.safetensors",
466
+ "model.layers.31.self_attn.q_norm.weight": "model-00012-of-00012.safetensors",
467
+ "model.layers.31.self_attn.q_proj.weight": "model-00011-of-00012.safetensors",
468
+ "model.layers.31.self_attn.v_proj.weight": "model-00011-of-00012.safetensors",
469
+ "model.layers.4.input_layernorm.weight": "model-00001-of-00012.safetensors",
470
+ "model.layers.4.mlp.expert_bias": "model-00001-of-00012.safetensors",
471
+ "model.layers.4.mlp.moe_mlp.experts.weight": "model-00002-of-00012.safetensors",
472
+ "model.layers.4.mlp.moe_mlp.output_experts.weight": "model-00002-of-00012.safetensors",
473
+ "model.layers.4.mlp.router.gate.weight": "model-00001-of-00012.safetensors",
474
+ "model.layers.4.mlp.shared_experts.down_proj.weight": "model-00001-of-00012.safetensors",
475
+ "model.layers.4.mlp.shared_experts.gate_proj.weight": "model-00001-of-00012.safetensors",
476
+ "model.layers.4.mlp.shared_experts.up_proj.weight": "model-00001-of-00012.safetensors",
477
+ "model.layers.4.post_attention_layernorm.weight": "model-00001-of-00012.safetensors",
478
+ "model.layers.4.post_mlp_layernorm.weight": "model-00001-of-00012.safetensors",
479
+ "model.layers.4.pre_mlp_layernorm.weight": "model-00001-of-00012.safetensors",
480
+ "model.layers.4.self_attn.gate_proj.weight": "model-00001-of-00012.safetensors",
481
+ "model.layers.4.self_attn.k_norm.weight": "model-00001-of-00012.safetensors",
482
+ "model.layers.4.self_attn.k_proj.weight": "model-00001-of-00012.safetensors",
483
+ "model.layers.4.self_attn.o_proj.weight": "model-00001-of-00012.safetensors",
484
+ "model.layers.4.self_attn.q_norm.weight": "model-00001-of-00012.safetensors",
485
+ "model.layers.4.self_attn.q_proj.weight": "model-00001-of-00012.safetensors",
486
+ "model.layers.4.self_attn.v_proj.weight": "model-00001-of-00012.safetensors",
487
+ "model.layers.5.input_layernorm.weight": "model-00002-of-00012.safetensors",
488
+ "model.layers.5.mlp.expert_bias": "model-00002-of-00012.safetensors",
489
+ "model.layers.5.mlp.moe_mlp.experts.weight": "model-00002-of-00012.safetensors",
490
+ "model.layers.5.mlp.moe_mlp.output_experts.weight": "model-00002-of-00012.safetensors",
491
+ "model.layers.5.mlp.router.gate.weight": "model-00002-of-00012.safetensors",
492
+ "model.layers.5.mlp.shared_experts.down_proj.weight": "model-00002-of-00012.safetensors",
493
+ "model.layers.5.mlp.shared_experts.gate_proj.weight": "model-00002-of-00012.safetensors",
494
+ "model.layers.5.mlp.shared_experts.up_proj.weight": "model-00002-of-00012.safetensors",
495
+ "model.layers.5.post_attention_layernorm.weight": "model-00002-of-00012.safetensors",
496
+ "model.layers.5.post_mlp_layernorm.weight": "model-00002-of-00012.safetensors",
497
+ "model.layers.5.pre_mlp_layernorm.weight": "model-00002-of-00012.safetensors",
498
+ "model.layers.5.self_attn.gate_proj.weight": "model-00002-of-00012.safetensors",
499
+ "model.layers.5.self_attn.k_norm.weight": "model-00002-of-00012.safetensors",
500
+ "model.layers.5.self_attn.k_proj.weight": "model-00002-of-00012.safetensors",
501
+ "model.layers.5.self_attn.o_proj.weight": "model-00002-of-00012.safetensors",
502
+ "model.layers.5.self_attn.q_norm.weight": "model-00002-of-00012.safetensors",
503
+ "model.layers.5.self_attn.q_proj.weight": "model-00002-of-00012.safetensors",
504
+ "model.layers.5.self_attn.v_proj.weight": "model-00002-of-00012.safetensors",
505
+ "model.layers.6.input_layernorm.weight": "model-00002-of-00012.safetensors",
506
+ "model.layers.6.mlp.expert_bias": "model-00002-of-00012.safetensors",
507
+ "model.layers.6.mlp.moe_mlp.experts.weight": "model-00002-of-00012.safetensors",
508
+ "model.layers.6.mlp.moe_mlp.output_experts.weight": "model-00002-of-00012.safetensors",
509
+ "model.layers.6.mlp.router.gate.weight": "model-00002-of-00012.safetensors",
510
+ "model.layers.6.mlp.shared_experts.down_proj.weight": "model-00002-of-00012.safetensors",
511
+ "model.layers.6.mlp.shared_experts.gate_proj.weight": "model-00002-of-00012.safetensors",
512
+ "model.layers.6.mlp.shared_experts.up_proj.weight": "model-00002-of-00012.safetensors",
513
+ "model.layers.6.post_attention_layernorm.weight": "model-00002-of-00012.safetensors",
514
+ "model.layers.6.post_mlp_layernorm.weight": "model-00002-of-00012.safetensors",
515
+ "model.layers.6.pre_mlp_layernorm.weight": "model-00002-of-00012.safetensors",
516
+ "model.layers.6.self_attn.gate_proj.weight": "model-00002-of-00012.safetensors",
517
+ "model.layers.6.self_attn.k_norm.weight": "model-00002-of-00012.safetensors",
518
+ "model.layers.6.self_attn.k_proj.weight": "model-00002-of-00012.safetensors",
519
+ "model.layers.6.self_attn.o_proj.weight": "model-00002-of-00012.safetensors",
520
+ "model.layers.6.self_attn.q_norm.weight": "model-00002-of-00012.safetensors",
521
+ "model.layers.6.self_attn.q_proj.weight": "model-00002-of-00012.safetensors",
522
+ "model.layers.6.self_attn.v_proj.weight": "model-00002-of-00012.safetensors",
523
+ "model.layers.7.input_layernorm.weight": "model-00003-of-00012.safetensors",
524
+ "model.layers.7.mlp.expert_bias": "model-00003-of-00012.safetensors",
525
+ "model.layers.7.mlp.moe_mlp.experts.weight": "model-00003-of-00012.safetensors",
526
+ "model.layers.7.mlp.moe_mlp.output_experts.weight": "model-00003-of-00012.safetensors",
527
+ "model.layers.7.mlp.router.gate.weight": "model-00003-of-00012.safetensors",
528
+ "model.layers.7.mlp.shared_experts.down_proj.weight": "model-00003-of-00012.safetensors",
529
+ "model.layers.7.mlp.shared_experts.gate_proj.weight": "model-00003-of-00012.safetensors",
530
+ "model.layers.7.mlp.shared_experts.up_proj.weight": "model-00003-of-00012.safetensors",
531
+ "model.layers.7.post_attention_layernorm.weight": "model-00003-of-00012.safetensors",
532
+ "model.layers.7.post_mlp_layernorm.weight": "model-00003-of-00012.safetensors",
533
+ "model.layers.7.pre_mlp_layernorm.weight": "model-00003-of-00012.safetensors",
534
+ "model.layers.7.self_attn.gate_proj.weight": "model-00003-of-00012.safetensors",
535
+ "model.layers.7.self_attn.k_norm.weight": "model-00003-of-00012.safetensors",
536
+ "model.layers.7.self_attn.k_proj.weight": "model-00002-of-00012.safetensors",
537
+ "model.layers.7.self_attn.o_proj.weight": "model-00003-of-00012.safetensors",
538
+ "model.layers.7.self_attn.q_norm.weight": "model-00003-of-00012.safetensors",
539
+ "model.layers.7.self_attn.q_proj.weight": "model-00002-of-00012.safetensors",
540
+ "model.layers.7.self_attn.v_proj.weight": "model-00002-of-00012.safetensors",
541
+ "model.layers.8.input_layernorm.weight": "model-00003-of-00012.safetensors",
542
+ "model.layers.8.mlp.expert_bias": "model-00003-of-00012.safetensors",
543
+ "model.layers.8.mlp.moe_mlp.experts.weight": "model-00003-of-00012.safetensors",
544
+ "model.layers.8.mlp.moe_mlp.output_experts.weight": "model-00003-of-00012.safetensors",
545
+ "model.layers.8.mlp.router.gate.weight": "model-00003-of-00012.safetensors",
546
+ "model.layers.8.mlp.shared_experts.down_proj.weight": "model-00003-of-00012.safetensors",
547
+ "model.layers.8.mlp.shared_experts.gate_proj.weight": "model-00003-of-00012.safetensors",
548
+ "model.layers.8.mlp.shared_experts.up_proj.weight": "model-00003-of-00012.safetensors",
549
+ "model.layers.8.post_attention_layernorm.weight": "model-00003-of-00012.safetensors",
550
+ "model.layers.8.post_mlp_layernorm.weight": "model-00003-of-00012.safetensors",
551
+ "model.layers.8.pre_mlp_layernorm.weight": "model-00003-of-00012.safetensors",
552
+ "model.layers.8.self_attn.gate_proj.weight": "model-00003-of-00012.safetensors",
553
+ "model.layers.8.self_attn.k_norm.weight": "model-00003-of-00012.safetensors",
554
+ "model.layers.8.self_attn.k_proj.weight": "model-00003-of-00012.safetensors",
555
+ "model.layers.8.self_attn.o_proj.weight": "model-00003-of-00012.safetensors",
556
+ "model.layers.8.self_attn.q_norm.weight": "model-00003-of-00012.safetensors",
557
+ "model.layers.8.self_attn.q_proj.weight": "model-00003-of-00012.safetensors",
558
+ "model.layers.8.self_attn.v_proj.weight": "model-00003-of-00012.safetensors",
559
+ "model.layers.9.input_layernorm.weight": "model-00003-of-00012.safetensors",
560
+ "model.layers.9.mlp.expert_bias": "model-00003-of-00012.safetensors",
561
+ "model.layers.9.mlp.moe_mlp.experts.weight": "model-00003-of-00012.safetensors",
562
+ "model.layers.9.mlp.moe_mlp.output_experts.weight": "model-00004-of-00012.safetensors",
563
+ "model.layers.9.mlp.router.gate.weight": "model-00003-of-00012.safetensors",
564
+ "model.layers.9.mlp.shared_experts.down_proj.weight": "model-00003-of-00012.safetensors",
565
+ "model.layers.9.mlp.shared_experts.gate_proj.weight": "model-00003-of-00012.safetensors",
566
+ "model.layers.9.mlp.shared_experts.up_proj.weight": "model-00003-of-00012.safetensors",
567
+ "model.layers.9.post_attention_layernorm.weight": "model-00003-of-00012.safetensors",
568
+ "model.layers.9.post_mlp_layernorm.weight": "model-00003-of-00012.safetensors",
569
+ "model.layers.9.pre_mlp_layernorm.weight": "model-00003-of-00012.safetensors",
570
+ "model.layers.9.self_attn.gate_proj.weight": "model-00003-of-00012.safetensors",
571
+ "model.layers.9.self_attn.k_norm.weight": "model-00003-of-00012.safetensors",
572
+ "model.layers.9.self_attn.k_proj.weight": "model-00003-of-00012.safetensors",
573
+ "model.layers.9.self_attn.o_proj.weight": "model-00003-of-00012.safetensors",
574
+ "model.layers.9.self_attn.q_norm.weight": "model-00003-of-00012.safetensors",
575
+ "model.layers.9.self_attn.q_proj.weight": "model-00003-of-00012.safetensors",
576
+ "model.layers.9.self_attn.v_proj.weight": "model-00003-of-00012.safetensors",
577
+ "model.norm.weight": "model-00012-of-00012.safetensors"
578
+ }
579
+ }
modeling_afmoe_scm.py ADDED
@@ -0,0 +1,661 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ import scattermoe
26
+
27
+ try:
28
+ from .configuration_afmoe_scm import AfmoeSCMConfig
29
+ except:
30
+ from configuration_afmoe_scm import AfmoeSCMConfig
31
+
32
+ class AfmoeSCMRotaryEmbedding(nn.Module):
33
+
34
+ def __init__(self, config: AfmoeSCMConfig, device=None):
35
+ super().__init__()
36
+ # BC: "rope_type" was originally "type"
37
+ if hasattr(config, "rope_scaling") and config.rope_scaling is not None:
38
+ self.rope_type = config.rope_scaling.get("rope_type", config.rope_scaling.get("type"))
39
+ else:
40
+ self.rope_type = "default"
41
+ self.max_seq_len_cached = config.max_position_embeddings
42
+ self.original_max_seq_len = config.max_position_embeddings
43
+
44
+ self.config = config
45
+ self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
46
+
47
+ inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device)
48
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
49
+ self.original_inv_freq = self.inv_freq
50
+
51
+ def _dynamic_frequency_update(self, position_ids, device):
52
+ """
53
+ dynamic RoPE layers should recompute `inv_freq` in the following situations:
54
+ 1 - growing beyond the cached sequence length (allow scaling)
55
+ 2 - the current sequence length is in the original scale (avoid losing precision with small sequences)
56
+ """
57
+ seq_len = torch.max(position_ids) + 1
58
+ if seq_len > self.max_seq_len_cached: # growth
59
+ inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device, seq_len=seq_len)
60
+ self.register_buffer("inv_freq", inv_freq, persistent=False) # TODO joao: may break with compilation
61
+ self.max_seq_len_cached = seq_len
62
+
63
+ if seq_len < self.original_max_seq_len and self.max_seq_len_cached > self.original_max_seq_len: # reset
64
+ # This .to() is needed if the model has been moved to a device after being initialized (because
65
+ # the buffer is automatically moved, but not the original copy)
66
+ self.original_inv_freq = self.original_inv_freq.to(device)
67
+ self.register_buffer("inv_freq", self.original_inv_freq, persistent=False)
68
+ self.max_seq_len_cached = self.original_max_seq_len
69
+
70
+ @torch.no_grad()
71
+ def forward(self, x, position_ids):
72
+ if "dynamic" in self.rope_type:
73
+ self._dynamic_frequency_update(position_ids, device=x.device)
74
+
75
+ # Core RoPE block
76
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
77
+ position_ids_expanded = position_ids[:, None, :].float()
78
+ # Force float32 (see https://github.com/huggingface/transformers/pull/29285)
79
+ device_type = x.device.type
80
+ device_type = device_type if isinstance(device_type, str) and device_type != "mps" else "cpu"
81
+ with torch.autocast(device_type=device_type, enabled=False):
82
+ freqs = (inv_freq_expanded.float().to(x.device) @ position_ids_expanded.float()).transpose(1, 2)
83
+ emb = torch.cat((freqs, freqs), dim=-1)
84
+ cos = emb.cos()
85
+ sin = emb.sin()
86
+
87
+ # Advanced RoPE types (e.g. yarn) apply a post-processing scaling factor, equivalent to scaling attention
88
+ cos = cos * self.attention_scaling
89
+ sin = sin * self.attention_scaling
90
+
91
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
92
+
93
+
94
+ def rotate_half(x):
95
+ """Rotates half the hidden dims of the input."""
96
+ x1 = x[..., : x.shape[-1] // 2]
97
+ x2 = x[..., x.shape[-1] // 2 :]
98
+ return torch.cat((-x2, x1), dim=-1)
99
+
100
+
101
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
102
+ """Applies Rotary Position Embedding to the query and key tensors.
103
+
104
+ Args:
105
+ q (`torch.Tensor`): The query tensor.
106
+ k (`torch.Tensor`): The key tensor.
107
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
108
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
109
+ position_ids (`torch.Tensor`, *optional*):
110
+ Deprecated and unused.
111
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
112
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
113
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
114
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
115
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
116
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
117
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
118
+ Returns:
119
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
120
+ """
121
+ cos = cos.unsqueeze(unsqueeze_dim)
122
+ sin = sin.unsqueeze(unsqueeze_dim)
123
+ q_embed = (q * cos) + (rotate_half(q) * sin)
124
+ k_embed = (k * cos) + (rotate_half(k) * sin)
125
+ return q_embed, k_embed
126
+
127
+
128
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
129
+ """
130
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
131
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
132
+ """
133
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
134
+ if n_rep == 1:
135
+ return hidden_states
136
+ hidden_states = hidden_states[:, :, None, :, :].expand(
137
+ batch, num_key_value_heads, n_rep, slen, head_dim
138
+ )
139
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
140
+
141
+ @use_kernel_forward_from_hub("RMSNorm")
142
+ class AfmoeSCMRMSNorm(nn.Module):
143
+ def __init__(self, hidden_size: int, eps: float):
144
+ """
145
+ AfmoeSCMRMSNorm is equivalent to T5LayerNorm
146
+ """
147
+ super().__init__()
148
+ self.weight = nn.Parameter(torch.ones(hidden_size))
149
+ self.variance_epsilon = eps
150
+
151
+ def forward(self, hidden_states):
152
+ input_dtype = hidden_states.dtype
153
+ hidden_states = hidden_states.to(torch.float32)
154
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
155
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
156
+ return self.weight * hidden_states.to(input_dtype)
157
+
158
+ def extra_repr(self):
159
+ return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
160
+
161
+
162
+
163
+ def eager_attention_forward(
164
+ module: nn.Module,
165
+ query: torch.Tensor,
166
+ key: torch.Tensor,
167
+ value: torch.Tensor,
168
+ attention_mask: Optional[torch.Tensor],
169
+ scaling: float,
170
+ dropout: float = 0.0,
171
+ **kwargs,
172
+ ):
173
+ key_states = repeat_kv(key, module.num_key_value_groups)
174
+ value_states = repeat_kv(value, module.num_key_value_groups)
175
+
176
+ attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
177
+ if attention_mask is not None:
178
+ causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
179
+ attn_weights = attn_weights + causal_mask
180
+
181
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(
182
+ query.dtype
183
+ )
184
+ attn_weights = nn.functional.dropout(
185
+ attn_weights, p=dropout, training=module.training
186
+ )
187
+ attn_output = torch.matmul(attn_weights, value_states)
188
+ attn_output = attn_output.transpose(1, 2).contiguous()
189
+
190
+ return attn_output, attn_weights
191
+
192
+
193
+ class AfmoeSCMMLP(nn.Module):
194
+ def __init__(self, config, intermediate_size=None):
195
+ super().__init__()
196
+ self.config = config
197
+ self.hidden_size = config.hidden_size
198
+ self.intermediate_size = intermediate_size or config.intermediate_size
199
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
200
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
201
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
202
+ self.act_fn = ACT2FN[config.hidden_act]
203
+
204
+ def forward(self, x):
205
+ return self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
206
+
207
+
208
+ class AfmoeSCMTokenChoiceRouter(nn.Module):
209
+ """Token-choice top-K router for MoE routing."""
210
+
211
+ def __init__(self, config):
212
+ super().__init__()
213
+ self.config = config
214
+ self.top_k = config.num_experts_per_tok
215
+ self.num_experts = config.num_experts
216
+ self.score_func = config.score_func
217
+ self.route_norm = config.route_norm
218
+ self.route_scale = config.route_scale
219
+ self.gate = nn.Linear(config.hidden_size, config.num_experts, bias=False)
220
+
221
+ def forward(self, hidden_states, expert_bias: torch.Tensor | None):
222
+ _, _, hidden_dim = hidden_states.shape
223
+ hidden_states = hidden_states.view(-1, hidden_dim)
224
+
225
+ scores = self.gate(hidden_states)
226
+
227
+ # Apply scoring function in float32 for stability
228
+ if self.score_func == "sigmoid":
229
+ scores = torch.sigmoid(scores.to(torch.float32))
230
+ else:
231
+ scores = F.softmax(scores.to(torch.float32), dim=-1)
232
+
233
+ if expert_bias is not None:
234
+ _, selected_experts = torch.topk(scores + expert_bias, k=self.top_k, dim=1)
235
+ top_scores = scores.gather(dim=1, index=selected_experts)
236
+ else:
237
+ top_scores, selected_experts = torch.topk(scores, k=self.top_k, dim=1)
238
+
239
+ # Normalize weights if using sigmoid
240
+ if self.score_func == "sigmoid" and self.route_norm:
241
+ denominator = top_scores.sum(dim=-1, keepdim=True) + 1e-20
242
+ top_scores = top_scores / denominator
243
+
244
+ top_scores = top_scores * self.route_scale
245
+ return top_scores, selected_experts
246
+
247
+ class AfmoeSCMMoE(nn.Module):
248
+ def __init__(self, config):
249
+ super().__init__()
250
+ self.config = config
251
+ self.router = AfmoeSCMTokenChoiceRouter(config)
252
+
253
+ self.shared_experts = None
254
+ if config.num_shared_experts > 0:
255
+ self.shared_experts = AfmoeSCMMLP(
256
+ config, config.moe_intermediate_size * config.num_shared_experts
257
+ )
258
+ self.moe_mlp = scattermoe.mlp.GLUMLP(
259
+ input_size=self.config.hidden_size,
260
+ hidden_size=self.config.moe_intermediate_size,
261
+ num_experts=self.config.num_experts,
262
+ top_k=self.config.num_experts_per_tok,
263
+ activation=ACT2FN[config.hidden_act],
264
+ )
265
+
266
+ #self.experts = nn.ModuleList(
267
+ # [AfmoeSCMMLP(
268
+ # config, intermediate_size=config.moe_intermediate_size
269
+ # ) for _ in range(config.num_experts)]
270
+ #)
271
+ self.expert_bias = nn.Parameter(torch.zeros(config.num_experts, dtype=torch.float32), requires_grad=False)
272
+
273
+
274
+ def forward(self, hidden_states):
275
+ batch_size, seq_len, hidden_dim = hidden_states.shape
276
+ hidden_states_flat = hidden_states.view(-1, hidden_dim)
277
+
278
+ # Get routing decisions
279
+ top_scores, selected_experts = self.router(hidden_states, self.expert_bias)
280
+
281
+ # Process through shared experts
282
+ if self.shared_experts is not None:
283
+ shared_output = self.shared_experts(hidden_states_flat)
284
+ else:
285
+ shared_output = torch.zeros_like(hidden_states_flat)
286
+
287
+ hs_0 = self.moe_mlp(hidden_states_flat, top_scores.to(torch.bfloat16), selected_experts)
288
+ output = hs_0 + shared_output
289
+
290
+ return output.view(batch_size, seq_len, hidden_dim)
291
+
292
+
293
+ class AfmoeSCMAttention(nn.Module):
294
+ """Multi-headed attention with local/global pattern and gating."""
295
+
296
+ def __init__(self, config: AfmoeSCMConfig, layer_idx: int):
297
+ super().__init__()
298
+ self.config = config
299
+ self.layer_idx = layer_idx
300
+ self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
301
+ self.num_heads = config.num_attention_heads
302
+ self.num_key_value_heads = config.num_key_value_heads
303
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
304
+
305
+ self.scaling = self.head_dim**-0.5
306
+ self.attention_dropout = config.attention_dropout
307
+ self.is_local_attention = config.layer_types[layer_idx] == "sliding_attention"
308
+ self.sliding_window = config.sliding_window if self.is_local_attention else None
309
+
310
+ self.q_proj = nn.Linear(
311
+ config.hidden_size, self.num_heads * self.head_dim, bias=False
312
+ )
313
+ self.k_proj = nn.Linear(
314
+ config.hidden_size, self.num_key_value_heads * self.head_dim, bias=False
315
+ )
316
+ self.v_proj = nn.Linear(
317
+ config.hidden_size, self.num_key_value_heads * self.head_dim, bias=False
318
+ )
319
+ self.o_proj = nn.Linear(
320
+ self.num_heads * self.head_dim, config.hidden_size, bias=False
321
+ )
322
+
323
+ self.q_norm = AfmoeSCMRMSNorm(self.head_dim, eps=config.rms_norm_eps)
324
+ self.k_norm = AfmoeSCMRMSNorm(self.head_dim, eps=config.rms_norm_eps)
325
+
326
+ self.gate_proj = nn.Linear(
327
+ config.hidden_size, self.num_heads * self.head_dim, bias=False
328
+ )
329
+
330
+ def forward(
331
+ self,
332
+ hidden_states: torch.Tensor,
333
+ position_embeddings: tuple[torch.Tensor, torch.Tensor],
334
+ attention_mask: Optional[torch.Tensor],
335
+ past_key_value: Optional[Cache] = None,
336
+ cache_position: Optional[torch.LongTensor] = None,
337
+ **kwargs: Unpack[TransformersKwargs],
338
+ ) -> torch.Tensor:
339
+
340
+ input_shape = hidden_states.shape[:-1]
341
+ hidden_shape = (*input_shape, -1, self.head_dim)
342
+
343
+ query_states = self.q_proj(hidden_states).view(hidden_shape)
344
+ key_states = self.k_proj(hidden_states).view(hidden_shape)
345
+ value_states = self.v_proj(hidden_states).view(hidden_shape)
346
+ gate_states = self.gate_proj(hidden_states)
347
+
348
+ query_states = self.q_norm(query_states)
349
+ key_states = self.k_norm(key_states)
350
+
351
+ query_states = query_states.transpose(1, 2)
352
+ key_states = key_states.transpose(1, 2)
353
+ value_states = value_states.transpose(1, 2)
354
+
355
+ if self.is_local_attention:
356
+ cos, sin = position_embeddings
357
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
358
+
359
+ if past_key_value is not None:
360
+ cache_kwargs = {"cache_position": cache_position}
361
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
362
+
363
+ attention_interface: Callable = eager_attention_forward
364
+ if self.config._attn_implementation != "eager":
365
+ attention_interface = ALL_ATTENTION_FUNCTIONS[
366
+ self.config._attn_implementation
367
+ ]
368
+
369
+ output, _ = attention_interface(
370
+ self,
371
+ query_states,
372
+ key_states,
373
+ value_states,
374
+ attention_mask=attention_mask,
375
+ dropout=0.0 if not self.training else self.attention_dropout,
376
+ scaling=self.scaling,
377
+ sliding_window=self.sliding_window,
378
+ **kwargs,
379
+ )
380
+
381
+ output = output.view(*input_shape, -1).contiguous()
382
+ output = output * F.sigmoid(gate_states)
383
+ return self.o_proj(output)
384
+
385
+
386
+ class AfmoeSCMDecoderLayer(GradientCheckpointingLayer):
387
+ def __init__(self, config: AfmoeSCMConfig, layer_idx: int):
388
+ super().__init__()
389
+ self.hidden_size = config.hidden_size
390
+ self.layer_idx = layer_idx
391
+
392
+ self.self_attn = AfmoeSCMAttention(config=config, layer_idx=layer_idx)
393
+ self.attention_type = config.layer_types[layer_idx]
394
+
395
+ # Dual normalization for attention
396
+ self.input_layernorm = AfmoeSCMRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
397
+ self.post_attention_layernorm = AfmoeSCMRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
398
+
399
+ # Dual normalization for FFN
400
+ self.pre_mlp_layernorm = AfmoeSCMRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
401
+ self.post_mlp_layernorm = AfmoeSCMRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
402
+
403
+ # MoE or dense FFN
404
+ self.moe_enabled = layer_idx >= config.num_dense_layers
405
+ if self.moe_enabled:
406
+ self.mlp = AfmoeSCMMoE(config)
407
+ else:
408
+ self.mlp = AfmoeSCMMLP(config)
409
+
410
+ def forward(
411
+ self,
412
+ hidden_states: torch.Tensor,
413
+ attention_mask: Optional[torch.Tensor] = None,
414
+ position_ids: Optional[torch.LongTensor] = None,
415
+ past_key_value: Optional[Cache] = None,
416
+ use_cache: Optional[bool] = None,
417
+ cache_position: Optional[torch.LongTensor] = None,
418
+ position_embeddings: Optional[tuple[torch.Tensor, torch.Tensor]] = None,
419
+ **kwargs: Unpack[TransformersKwargs],
420
+ ) -> torch.FloatTensor:
421
+ residual = hidden_states
422
+
423
+ # Self Attention with dual normalization
424
+ hidden_states = self.input_layernorm(hidden_states)
425
+ hidden_states = self.self_attn(
426
+ hidden_states=hidden_states,
427
+ attention_mask=attention_mask,
428
+ position_ids=position_ids,
429
+ past_key_value=past_key_value,
430
+ use_cache=use_cache,
431
+ cache_position=cache_position,
432
+ position_embeddings=position_embeddings,
433
+ **kwargs,
434
+ )
435
+ hidden_states = self.post_attention_layernorm(hidden_states)
436
+ hidden_states = residual + hidden_states
437
+
438
+ # FFN with dual normalization
439
+ residual = hidden_states
440
+ hidden_states = self.pre_mlp_layernorm(hidden_states)
441
+
442
+ if self.moe_enabled:
443
+ hidden_states = self.mlp(hidden_states)
444
+ else:
445
+ hidden_states = self.mlp(hidden_states)
446
+
447
+ hidden_states = self.post_mlp_layernorm(hidden_states)
448
+ hidden_states = residual + hidden_states
449
+ return hidden_states
450
+
451
+
452
+ class AfmoeSCMPreTrainedModel(PreTrainedModel):
453
+ config_class = AfmoeSCMConfig
454
+ base_model_prefix = "model"
455
+ _no_split_modules = ["AfmoeSCMDecoderLayer"]
456
+ _skip_keys_device_placement = ["past_key_values"]
457
+ _keep_in_fp32_modules = [
458
+ "input_layernorm",
459
+ "post_attention_layernorm",
460
+ "pre_mlp_layernorm",
461
+ "post_mlp_layernorm",
462
+ "q_norm",
463
+ "k_norm",
464
+ "norm",
465
+ ]
466
+ _supports_sdpa = True
467
+ _supports_attention_backend = True
468
+ supports_gradient_checkpointing = True
469
+
470
+
471
+ class AfmoeSCMModel(AfmoeSCMPreTrainedModel):
472
+ _no_split_modules = ["AfmoeSCMDecoderLayer"]
473
+
474
+ def __init__(self, config: AfmoeSCMConfig):
475
+ super().__init__(config)
476
+ self.padding_idx = config.pad_token_id
477
+ self.vocab_size = config.vocab_size
478
+
479
+ self.embed_tokens = nn.Embedding(
480
+ config.vocab_size, config.hidden_size, self.padding_idx
481
+ )
482
+ self.layers = nn.ModuleList(
483
+ [
484
+ AfmoeSCMDecoderLayer(config, layer_idx)
485
+ for layer_idx in range(config.num_hidden_layers)
486
+ ]
487
+ )
488
+ self.norm = AfmoeSCMRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
489
+ self.rotary_emb = AfmoeSCMRotaryEmbedding(config=config)
490
+ self.gradient_checkpointing = False
491
+
492
+ self.post_init()
493
+
494
+ def get_input_embeddings(self):
495
+ return self.embed_tokens
496
+
497
+ def set_input_embeddings(self, value):
498
+ self.embed_tokens = value
499
+
500
+
501
+ def forward(
502
+ self,
503
+ input_ids: torch.LongTensor,
504
+ attention_mask: Optional[torch.Tensor] = None,
505
+ position_ids: Optional[torch.LongTensor] = None,
506
+ past_key_values: Optional[list[torch.FloatTensor]] = None,
507
+ inputs_embeds: Optional[torch.FloatTensor] = None,
508
+ use_cache: Optional[bool] = None,
509
+ cache_position: Optional[torch.LongTensor] = None,
510
+ **kwargs: Unpack[TransformersKwargs],
511
+ ) -> MoeModelOutputWithPast:
512
+ if (input_ids is None) ^ (inputs_embeds is not None):
513
+ raise ValueError(
514
+ "You must specify exactly one of input_ids or inputs_embeds"
515
+ )
516
+
517
+ if use_cache and past_key_values is None:
518
+ past_key_values = DynamicCache()
519
+
520
+ if inputs_embeds is None:
521
+ inputs_embeds = self.embed_tokens(input_ids)
522
+
523
+ if cache_position is None:
524
+ past_seen_tokens = (
525
+ past_key_values.get_seq_length() if past_key_values is not None else 0
526
+ )
527
+ cache_position = torch.arange(
528
+ past_seen_tokens,
529
+ past_seen_tokens + inputs_embeds.shape[1],
530
+ device=inputs_embeds.device,
531
+ )
532
+ if position_ids is None:
533
+ position_ids = cache_position.unsqueeze(0)
534
+
535
+ # It may already have been prepared by e.g. `generate`
536
+ if not isinstance(causal_mask_mapping := attention_mask, dict):
537
+ mask_kwargs = {
538
+ "config": self.config,
539
+ "input_embeds": inputs_embeds,
540
+ "attention_mask": attention_mask,
541
+ "cache_position": cache_position,
542
+ "past_key_values": past_key_values,
543
+ }
544
+ causal_mask_mapping = {
545
+ "full_attention": create_causal_mask(**mask_kwargs),
546
+ "sliding_attention": create_sliding_window_causal_mask(**mask_kwargs),
547
+ }
548
+
549
+ hidden_states = inputs_embeds
550
+
551
+ # Apply muP input scaling if enabled
552
+ if self.config.mup_enabled:
553
+ hidden_states = hidden_states * (self.config.hidden_size**0.5)
554
+
555
+ position_embeddings = self.rotary_emb(hidden_states, position_ids)
556
+
557
+ for decoder_layer in self.layers:
558
+ hidden_states = decoder_layer(
559
+ hidden_states,
560
+ attention_mask=causal_mask_mapping[decoder_layer.attention_type],
561
+ position_ids=position_ids,
562
+ past_key_value=past_key_values,
563
+ use_cache=use_cache,
564
+ cache_position=cache_position,
565
+ position_embeddings=position_embeddings,
566
+ **kwargs,
567
+ )
568
+
569
+ hidden_states = self.norm(hidden_states)
570
+ return MoeModelOutputWithPast(
571
+ last_hidden_state=hidden_states,
572
+ past_key_values=past_key_values,
573
+ )
574
+
575
+
576
+ class AfmoeSCMForCausalLM(AfmoeSCMPreTrainedModel, GenerationMixin):
577
+ _tied_weights_keys = ["lm_head.weight"]
578
+ _tp_plan = {"lm_head": "colwise_rep"}
579
+ _pp_plan = {"lm_head": (["hidden_states"], ["logits"])}
580
+
581
+ def __init__(self, config):
582
+ super().__init__(config)
583
+ self.model = AfmoeSCMModel(config)
584
+ self.vocab_size = config.vocab_size
585
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
586
+
587
+ # Initialize weights and apply final processing
588
+ self.post_init()
589
+
590
+ def get_input_embeddings(self):
591
+ return self.model.embed_tokens
592
+
593
+ def set_input_embeddings(self, value):
594
+ self.model.embed_tokens = value
595
+
596
+ def get_output_embeddings(self):
597
+ return self.lm_head
598
+
599
+ def set_output_embeddings(self, new_embeddings):
600
+ self.lm_head = new_embeddings
601
+
602
+ def set_decoder(self, decoder):
603
+ self.model = decoder
604
+
605
+ def get_decoder(self):
606
+ return self.model
607
+
608
+ def forward(
609
+ self,
610
+ input_ids: torch.LongTensor,
611
+ attention_mask: Optional[torch.Tensor] = None,
612
+ position_ids: Optional[torch.LongTensor] = None,
613
+ past_key_values: Optional[Cache] = None,
614
+ inputs_embeds: Optional[torch.FloatTensor] = None,
615
+ labels: Optional[torch.LongTensor] = None,
616
+ use_cache: Optional[bool] = None,
617
+ cache_position: Optional[torch.LongTensor] = None,
618
+ logits_to_keep: Union[int, torch.Tensor] = 0,
619
+ token_type_ids: Optional[torch.Tensor] = None, # will be ignored
620
+ **kwargs: Unpack[TransformersKwargs],
621
+ ) -> Union[Tuple, MoeCausalLMOutputWithPast]:
622
+ outputs: MoeModelOutputWithPast = self.model(
623
+ input_ids=input_ids,
624
+ attention_mask=attention_mask,
625
+ position_ids=position_ids,
626
+ past_key_values=past_key_values,
627
+ inputs_embeds=inputs_embeds,
628
+ use_cache=use_cache,
629
+ cache_position=cache_position,
630
+ **kwargs,
631
+ )
632
+
633
+ hidden_states = outputs.last_hidden_state
634
+ # Only compute necessary logits
635
+ slice_indices = (
636
+ slice(-logits_to_keep, None)
637
+ if isinstance(logits_to_keep, int)
638
+ else logits_to_keep
639
+ )
640
+ logits = self.lm_head(hidden_states[:, slice_indices, :])
641
+
642
+ loss = None
643
+ if labels is not None:
644
+ loss = self.loss_function(logits, labels, self.vocab_size, **kwargs)
645
+
646
+
647
+ return MoeCausalLMOutputWithPast(
648
+ loss=loss,
649
+ logits=logits,
650
+ past_key_values=outputs.past_key_values,
651
+ hidden_states=outputs.hidden_states,
652
+ attentions=outputs.attentions,
653
+ router_logits=outputs.router_logits,
654
+ )
655
+
656
+
657
+ __all__ = [
658
+ "AfmoeSCMForCausalLM",
659
+ "AfmoeSCMModel",
660
+ "AfmoeSCMPreTrainedModel",
661
+ ]
modeling_afmoe_scm_liger.py ADDED
@@ -0,0 +1,675 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ import scattermoe
26
+
27
+ from liger_kernel.transformers.model.loss_utils import LigerForCausalLMLoss
28
+ from liger_kernel.transformers.rms_norm import LigerRMSNorm as AfmoeSCMRMSNorm
29
+
30
+ try:
31
+ from .configuration_afmoe_scm import AfmoeSCMConfig
32
+ except:
33
+ from configuration_afmoe_scm import AfmoeSCMConfig
34
+
35
+ class AfmoeSCMRotaryEmbedding(nn.Module):
36
+
37
+ def __init__(self, config: AfmoeSCMConfig, device=None):
38
+ super().__init__()
39
+ # BC: "rope_type" was originally "type"
40
+ if hasattr(config, "rope_scaling") and config.rope_scaling is not None:
41
+ self.rope_type = config.rope_scaling.get("rope_type", config.rope_scaling.get("type"))
42
+ else:
43
+ self.rope_type = "default"
44
+ self.max_seq_len_cached = config.max_position_embeddings
45
+ self.original_max_seq_len = config.max_position_embeddings
46
+
47
+ self.config = config
48
+ self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
49
+
50
+ inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device)
51
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
52
+ self.original_inv_freq = self.inv_freq
53
+
54
+ def _dynamic_frequency_update(self, position_ids, device):
55
+ """
56
+ dynamic RoPE layers should recompute `inv_freq` in the following situations:
57
+ 1 - growing beyond the cached sequence length (allow scaling)
58
+ 2 - the current sequence length is in the original scale (avoid losing precision with small sequences)
59
+ """
60
+ seq_len = torch.max(position_ids) + 1
61
+ if seq_len > self.max_seq_len_cached: # growth
62
+ inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device, seq_len=seq_len)
63
+ self.register_buffer("inv_freq", inv_freq, persistent=False) # TODO joao: may break with compilation
64
+ self.max_seq_len_cached = seq_len
65
+
66
+ if seq_len < self.original_max_seq_len and self.max_seq_len_cached > self.original_max_seq_len: # reset
67
+ # This .to() is needed if the model has been moved to a device after being initialized (because
68
+ # the buffer is automatically moved, but not the original copy)
69
+ self.original_inv_freq = self.original_inv_freq.to(device)
70
+ self.register_buffer("inv_freq", self.original_inv_freq, persistent=False)
71
+ self.max_seq_len_cached = self.original_max_seq_len
72
+
73
+ @torch.no_grad()
74
+ def forward(self, x, position_ids):
75
+ if "dynamic" in self.rope_type:
76
+ self._dynamic_frequency_update(position_ids, device=x.device)
77
+
78
+ # Core RoPE block
79
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
80
+ position_ids_expanded = position_ids[:, None, :].float()
81
+ # Force float32 (see https://github.com/huggingface/transformers/pull/29285)
82
+ device_type = x.device.type
83
+ device_type = device_type if isinstance(device_type, str) and device_type != "mps" else "cpu"
84
+ with torch.autocast(device_type=device_type, enabled=False):
85
+ freqs = (inv_freq_expanded.float().to(x.device) @ position_ids_expanded.float()).transpose(1, 2)
86
+ emb = torch.cat((freqs, freqs), dim=-1)
87
+ cos = emb.cos()
88
+ sin = emb.sin()
89
+
90
+ # Advanced RoPE types (e.g. yarn) apply a post-processing scaling factor, equivalent to scaling attention
91
+ cos = cos * self.attention_scaling
92
+ sin = sin * self.attention_scaling
93
+
94
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
95
+
96
+
97
+ def rotate_half(x):
98
+ """Rotates half the hidden dims of the input."""
99
+ x1 = x[..., : x.shape[-1] // 2]
100
+ x2 = x[..., x.shape[-1] // 2 :]
101
+ return torch.cat((-x2, x1), dim=-1)
102
+
103
+
104
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
105
+ """Applies Rotary Position Embedding to the query and key tensors.
106
+
107
+ Args:
108
+ q (`torch.Tensor`): The query tensor.
109
+ k (`torch.Tensor`): The key tensor.
110
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
111
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
112
+ position_ids (`torch.Tensor`, *optional*):
113
+ Deprecated and unused.
114
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
115
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
116
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
117
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
118
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
119
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
120
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
121
+ Returns:
122
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
123
+ """
124
+ cos = cos.unsqueeze(unsqueeze_dim)
125
+ sin = sin.unsqueeze(unsqueeze_dim)
126
+ q_embed = (q * cos) + (rotate_half(q) * sin)
127
+ k_embed = (k * cos) + (rotate_half(k) * sin)
128
+ return q_embed, k_embed
129
+
130
+
131
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
132
+ """
133
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
134
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
135
+ """
136
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
137
+ if n_rep == 1:
138
+ return hidden_states
139
+ hidden_states = hidden_states[:, :, None, :, :].expand(
140
+ batch, num_key_value_heads, n_rep, slen, head_dim
141
+ )
142
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
143
+
144
+ #@use_kernel_forward_from_hub("RMSNorm")
145
+ class _AfmoeSCMRMSNorm(nn.Module):
146
+ def __init__(self, hidden_size: int, eps: float):
147
+ """
148
+ AfmoeSCMRMSNorm is equivalent to T5LayerNorm
149
+ """
150
+ super().__init__()
151
+ self.weight = nn.Parameter(torch.ones(hidden_size))
152
+ self.variance_epsilon = eps
153
+
154
+ def forward(self, hidden_states):
155
+ input_dtype = hidden_states.dtype
156
+ hidden_states = hidden_states.to(torch.float32)
157
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
158
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
159
+ return self.weight * hidden_states.to(input_dtype)
160
+
161
+ def extra_repr(self):
162
+ return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
163
+
164
+
165
+
166
+ def eager_attention_forward(
167
+ module: nn.Module,
168
+ query: torch.Tensor,
169
+ key: torch.Tensor,
170
+ value: torch.Tensor,
171
+ attention_mask: Optional[torch.Tensor],
172
+ scaling: float,
173
+ dropout: float = 0.0,
174
+ **kwargs,
175
+ ):
176
+ key_states = repeat_kv(key, module.num_key_value_groups)
177
+ value_states = repeat_kv(value, module.num_key_value_groups)
178
+
179
+ attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
180
+ if attention_mask is not None:
181
+ causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
182
+ attn_weights = attn_weights + causal_mask
183
+
184
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(
185
+ query.dtype
186
+ )
187
+ attn_weights = nn.functional.dropout(
188
+ attn_weights, p=dropout, training=module.training
189
+ )
190
+ attn_output = torch.matmul(attn_weights, value_states)
191
+ attn_output = attn_output.transpose(1, 2).contiguous()
192
+
193
+ return attn_output, attn_weights
194
+
195
+
196
+ class AfmoeSCMMLP(nn.Module):
197
+ def __init__(self, config, intermediate_size=None):
198
+ super().__init__()
199
+ self.config = config
200
+ self.hidden_size = config.hidden_size
201
+ self.intermediate_size = intermediate_size or config.intermediate_size
202
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
203
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
204
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
205
+ self.act_fn = ACT2FN[config.hidden_act]
206
+
207
+ def forward(self, x):
208
+ return self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
209
+
210
+
211
+ class AfmoeSCMTokenChoiceRouter(nn.Module):
212
+ """Token-choice top-K router for MoE routing."""
213
+
214
+ def __init__(self, config):
215
+ super().__init__()
216
+ self.config = config
217
+ self.top_k = config.num_experts_per_tok
218
+ self.num_experts = config.num_experts
219
+ self.score_func = config.score_func
220
+ self.route_norm = config.route_norm
221
+ self.route_scale = config.route_scale
222
+ self.gate = nn.Linear(config.hidden_size, config.num_experts, bias=False)
223
+
224
+ def forward(self, hidden_states, expert_bias: torch.Tensor | None):
225
+ _, _, hidden_dim = hidden_states.shape
226
+ hidden_states = hidden_states.view(-1, hidden_dim)
227
+
228
+ scores = self.gate(hidden_states)
229
+
230
+ # Apply scoring function in float32 for stability
231
+ if self.score_func == "sigmoid":
232
+ scores = torch.sigmoid(scores.to(torch.float32))
233
+ else:
234
+ scores = F.softmax(scores.to(torch.float32), dim=-1)
235
+
236
+ if expert_bias is not None:
237
+ _, selected_experts = torch.topk(scores + expert_bias, k=self.top_k, dim=1)
238
+ top_scores = scores.gather(dim=1, index=selected_experts)
239
+ else:
240
+ top_scores, selected_experts = torch.topk(scores, k=self.top_k, dim=1)
241
+
242
+ # Normalize weights if using sigmoid
243
+ if self.score_func == "sigmoid" and self.route_norm:
244
+ denominator = top_scores.sum(dim=-1, keepdim=True) + 1e-20
245
+ top_scores = top_scores / denominator
246
+
247
+ top_scores = top_scores * self.route_scale
248
+ return top_scores, selected_experts
249
+
250
+ class AfmoeSCMMoE(nn.Module):
251
+ def __init__(self, config):
252
+ super().__init__()
253
+ self.config = config
254
+ self.router = AfmoeSCMTokenChoiceRouter(config)
255
+
256
+ self.shared_experts = None
257
+ if config.num_shared_experts > 0:
258
+ self.shared_experts = AfmoeSCMMLP(
259
+ config, config.moe_intermediate_size * config.num_shared_experts
260
+ )
261
+ self.moe_mlp = scattermoe.mlp.GLUMLP(
262
+ input_size=self.config.hidden_size,
263
+ hidden_size=self.config.moe_intermediate_size,
264
+ num_experts=self.config.num_experts,
265
+ top_k=self.config.num_experts_per_tok,
266
+ activation=ACT2FN[config.hidden_act],
267
+ )
268
+
269
+ self.expert_bias = nn.Parameter(torch.zeros(config.num_experts, dtype=torch.float32), requires_grad=False)
270
+
271
+
272
+ def forward(self, hidden_states):
273
+ batch_size, seq_len, hidden_dim = hidden_states.shape
274
+ hidden_states_flat = hidden_states.view(-1, hidden_dim)
275
+
276
+ # Get routing decisions
277
+ top_scores, selected_experts = self.router(hidden_states, self.expert_bias)
278
+
279
+ # Process through shared experts
280
+ if self.shared_experts is not None:
281
+ shared_output = self.shared_experts(hidden_states_flat)
282
+ else:
283
+ shared_output = torch.zeros_like(hidden_states_flat)
284
+
285
+ hs_0 = self.moe_mlp(hidden_states_flat, top_scores.to(torch.bfloat16), selected_experts)
286
+ output = hs_0 + shared_output
287
+
288
+ return output.view(batch_size, seq_len, hidden_dim)
289
+
290
+
291
+ class AfmoeSCMAttention(nn.Module):
292
+ """Multi-headed attention with local/global pattern and gating."""
293
+
294
+ def __init__(self, config: AfmoeSCMConfig, layer_idx: int):
295
+ super().__init__()
296
+ self.config = config
297
+ self.layer_idx = layer_idx
298
+ self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
299
+ self.num_heads = config.num_attention_heads
300
+ self.num_key_value_heads = config.num_key_value_heads
301
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
302
+
303
+ self.scaling = self.head_dim**-0.5
304
+ self.attention_dropout = config.attention_dropout
305
+ self.is_local_attention = config.layer_types[layer_idx] == "sliding_attention"
306
+ self.sliding_window = config.sliding_window if self.is_local_attention else None
307
+
308
+ self.q_proj = nn.Linear(
309
+ config.hidden_size, self.num_heads * self.head_dim, bias=False
310
+ )
311
+ self.k_proj = nn.Linear(
312
+ config.hidden_size, self.num_key_value_heads * self.head_dim, bias=False
313
+ )
314
+ self.v_proj = nn.Linear(
315
+ config.hidden_size, self.num_key_value_heads * self.head_dim, bias=False
316
+ )
317
+ self.o_proj = nn.Linear(
318
+ self.num_heads * self.head_dim, config.hidden_size, bias=False
319
+ )
320
+
321
+ self.q_norm = AfmoeSCMRMSNorm(self.head_dim, eps=config.rms_norm_eps)
322
+ self.k_norm = AfmoeSCMRMSNorm(self.head_dim, eps=config.rms_norm_eps)
323
+
324
+ self.gate_proj = nn.Linear(
325
+ config.hidden_size, self.num_heads * self.head_dim, bias=False
326
+ )
327
+
328
+ def forward(
329
+ self,
330
+ hidden_states: torch.Tensor,
331
+ position_embeddings: tuple[torch.Tensor, torch.Tensor],
332
+ attention_mask: Optional[torch.Tensor],
333
+ past_key_value: Optional[Cache] = None,
334
+ cache_position: Optional[torch.LongTensor] = None,
335
+ **kwargs: Unpack[TransformersKwargs],
336
+ ) -> torch.Tensor:
337
+
338
+ input_shape = hidden_states.shape[:-1]
339
+ hidden_shape = (*input_shape, -1, self.head_dim)
340
+
341
+ query_states = self.q_proj(hidden_states).view(hidden_shape)
342
+ key_states = self.k_proj(hidden_states).view(hidden_shape)
343
+ value_states = self.v_proj(hidden_states).view(hidden_shape)
344
+ gate_states = self.gate_proj(hidden_states)
345
+
346
+ query_states = self.q_norm(query_states)
347
+ key_states = self.k_norm(key_states)
348
+
349
+ query_states = query_states.transpose(1, 2)
350
+ key_states = key_states.transpose(1, 2)
351
+ value_states = value_states.transpose(1, 2)
352
+
353
+ if self.is_local_attention:
354
+ cos, sin = position_embeddings
355
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
356
+
357
+ if past_key_value is not None:
358
+ cache_kwargs = {"cache_position": cache_position}
359
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
360
+
361
+ attention_interface: Callable = eager_attention_forward
362
+ if self.config._attn_implementation != "eager":
363
+ attention_interface = ALL_ATTENTION_FUNCTIONS[
364
+ self.config._attn_implementation
365
+ ]
366
+
367
+ output, _ = attention_interface(
368
+ self,
369
+ query_states,
370
+ key_states,
371
+ value_states,
372
+ attention_mask=attention_mask,
373
+ dropout=0.0 if not self.training else self.attention_dropout,
374
+ scaling=self.scaling,
375
+ sliding_window=self.sliding_window,
376
+ **kwargs,
377
+ )
378
+
379
+ output = output.view(*input_shape, -1).contiguous()
380
+ output = output * F.sigmoid(gate_states)
381
+ return self.o_proj(output)
382
+
383
+
384
+ class AfmoeSCMDecoderLayer(GradientCheckpointingLayer):
385
+ def __init__(self, config: AfmoeSCMConfig, layer_idx: int):
386
+ super().__init__()
387
+ self.hidden_size = config.hidden_size
388
+ self.layer_idx = layer_idx
389
+
390
+ self.self_attn = AfmoeSCMAttention(config=config, layer_idx=layer_idx)
391
+ self.attention_type = config.layer_types[layer_idx]
392
+
393
+ # Dual normalization for attention
394
+ self.input_layernorm = AfmoeSCMRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
395
+ self.post_attention_layernorm = AfmoeSCMRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
396
+
397
+ # Dual normalization for FFN
398
+ self.pre_mlp_layernorm = AfmoeSCMRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
399
+ self.post_mlp_layernorm = AfmoeSCMRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
400
+
401
+ # MoE or dense FFN
402
+ self.moe_enabled = layer_idx >= config.num_dense_layers
403
+ if self.moe_enabled:
404
+ self.mlp = AfmoeSCMMoE(config)
405
+ else:
406
+ self.mlp = AfmoeSCMMLP(config)
407
+
408
+ def forward(
409
+ self,
410
+ hidden_states: torch.Tensor,
411
+ attention_mask: Optional[torch.Tensor] = None,
412
+ position_ids: Optional[torch.LongTensor] = None,
413
+ past_key_value: Optional[Cache] = None,
414
+ use_cache: Optional[bool] = None,
415
+ cache_position: Optional[torch.LongTensor] = None,
416
+ position_embeddings: Optional[tuple[torch.Tensor, torch.Tensor]] = None,
417
+ **kwargs: Unpack[TransformersKwargs],
418
+ ) -> torch.FloatTensor:
419
+ residual = hidden_states
420
+
421
+ # Self Attention with dual normalization
422
+ hidden_states = self.input_layernorm(hidden_states)
423
+ hidden_states = self.self_attn(
424
+ hidden_states=hidden_states,
425
+ attention_mask=attention_mask,
426
+ position_ids=position_ids,
427
+ past_key_value=past_key_value,
428
+ use_cache=use_cache,
429
+ cache_position=cache_position,
430
+ position_embeddings=position_embeddings,
431
+ **kwargs,
432
+ )
433
+ hidden_states = self.post_attention_layernorm(hidden_states)
434
+ hidden_states = residual + hidden_states
435
+
436
+ # FFN with dual normalization
437
+ residual = hidden_states
438
+ hidden_states = self.pre_mlp_layernorm(hidden_states)
439
+
440
+ if self.moe_enabled:
441
+ hidden_states = self.mlp(hidden_states)
442
+ else:
443
+ hidden_states = self.mlp(hidden_states)
444
+
445
+ hidden_states = self.post_mlp_layernorm(hidden_states)
446
+ hidden_states = residual + hidden_states
447
+ return hidden_states
448
+
449
+
450
+ class AfmoeSCMPreTrainedModel(PreTrainedModel):
451
+ config_class = AfmoeSCMConfig
452
+ base_model_prefix = "model"
453
+ _no_split_modules = ["AfmoeSCMDecoderLayer"]
454
+ _skip_keys_device_placement = ["past_key_values"]
455
+ _keep_in_fp32_modules = [
456
+ "input_layernorm",
457
+ "post_attention_layernorm",
458
+ "pre_mlp_layernorm",
459
+ "post_mlp_layernorm",
460
+ "q_norm",
461
+ "k_norm",
462
+ "norm",
463
+ ]
464
+ _supports_sdpa = True
465
+ _supports_attention_backend = True
466
+ supports_gradient_checkpointing = True
467
+
468
+
469
+ class AfmoeSCMModel(AfmoeSCMPreTrainedModel):
470
+ _no_split_modules = ["AfmoeSCMDecoderLayer"]
471
+
472
+ def __init__(self, config: AfmoeSCMConfig):
473
+ super().__init__(config)
474
+ self.padding_idx = config.pad_token_id
475
+ self.vocab_size = config.vocab_size
476
+
477
+ self.embed_tokens = nn.Embedding(
478
+ config.vocab_size, config.hidden_size, self.padding_idx
479
+ )
480
+ self.layers = nn.ModuleList(
481
+ [
482
+ AfmoeSCMDecoderLayer(config, layer_idx)
483
+ for layer_idx in range(config.num_hidden_layers)
484
+ ]
485
+ )
486
+ self.norm = AfmoeSCMRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
487
+ self.rotary_emb = AfmoeSCMRotaryEmbedding(config=config)
488
+ self.gradient_checkpointing = False
489
+
490
+ self.post_init()
491
+
492
+ def get_input_embeddings(self):
493
+ return self.embed_tokens
494
+
495
+ def set_input_embeddings(self, value):
496
+ self.embed_tokens = value
497
+
498
+
499
+ def forward(
500
+ self,
501
+ input_ids: torch.LongTensor,
502
+ attention_mask: Optional[torch.Tensor] = None,
503
+ position_ids: Optional[torch.LongTensor] = None,
504
+ past_key_values: Optional[list[torch.FloatTensor]] = None,
505
+ inputs_embeds: Optional[torch.FloatTensor] = None,
506
+ use_cache: Optional[bool] = None,
507
+ cache_position: Optional[torch.LongTensor] = None,
508
+ **kwargs: Unpack[TransformersKwargs],
509
+ ) -> MoeModelOutputWithPast:
510
+ if (input_ids is None) ^ (inputs_embeds is not None):
511
+ raise ValueError(
512
+ "You must specify exactly one of input_ids or inputs_embeds"
513
+ )
514
+
515
+ if use_cache and past_key_values is None:
516
+ past_key_values = DynamicCache()
517
+
518
+ if inputs_embeds is None:
519
+ inputs_embeds = self.embed_tokens(input_ids)
520
+
521
+ if cache_position is None:
522
+ past_seen_tokens = (
523
+ past_key_values.get_seq_length() if past_key_values is not None else 0
524
+ )
525
+ cache_position = torch.arange(
526
+ past_seen_tokens,
527
+ past_seen_tokens + inputs_embeds.shape[1],
528
+ device=inputs_embeds.device,
529
+ )
530
+ if position_ids is None:
531
+ position_ids = cache_position.unsqueeze(0)
532
+
533
+ # It may already have been prepared by e.g. `generate`
534
+ if not isinstance(causal_mask_mapping := attention_mask, dict):
535
+ mask_kwargs = {
536
+ "config": self.config,
537
+ "input_embeds": inputs_embeds,
538
+ "attention_mask": attention_mask,
539
+ "cache_position": cache_position,
540
+ "past_key_values": past_key_values,
541
+ }
542
+ causal_mask_mapping = {
543
+ "full_attention": create_causal_mask(**mask_kwargs),
544
+ "sliding_attention": create_sliding_window_causal_mask(**mask_kwargs),
545
+ }
546
+
547
+ hidden_states = inputs_embeds
548
+
549
+ # Apply muP input scaling if enabled
550
+ if self.config.mup_enabled:
551
+ hidden_states = hidden_states * (self.config.hidden_size**0.5)
552
+
553
+ position_embeddings = self.rotary_emb(hidden_states, position_ids)
554
+
555
+ for decoder_layer in self.layers:
556
+ hidden_states = decoder_layer(
557
+ hidden_states,
558
+ attention_mask=causal_mask_mapping[decoder_layer.attention_type],
559
+ position_ids=position_ids,
560
+ past_key_value=past_key_values,
561
+ use_cache=use_cache,
562
+ cache_position=cache_position,
563
+ position_embeddings=position_embeddings,
564
+ **kwargs,
565
+ )
566
+
567
+ hidden_states = self.norm(hidden_states)
568
+ return MoeModelOutputWithPast(
569
+ last_hidden_state=hidden_states,
570
+ past_key_values=past_key_values,
571
+ )
572
+
573
+
574
+ class AfmoeSCMForCausalLM(AfmoeSCMPreTrainedModel, GenerationMixin):
575
+ _tied_weights_keys = ["lm_head.weight"]
576
+ _tp_plan = {"lm_head": "colwise_rep"}
577
+ _pp_plan = {"lm_head": (["hidden_states"], ["logits"])}
578
+
579
+ def __init__(self, config):
580
+ super().__init__(config)
581
+ self.model = AfmoeSCMModel(config)
582
+ self.vocab_size = config.vocab_size
583
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
584
+
585
+ # Initialize weights and apply final processing
586
+ self.post_init()
587
+
588
+ def get_input_embeddings(self):
589
+ return self.model.embed_tokens
590
+
591
+ def set_input_embeddings(self, value):
592
+ self.model.embed_tokens = value
593
+
594
+ def get_output_embeddings(self):
595
+ return self.lm_head
596
+
597
+ def set_output_embeddings(self, new_embeddings):
598
+ self.lm_head = new_embeddings
599
+
600
+ def set_decoder(self, decoder):
601
+ self.model = decoder
602
+
603
+ def get_decoder(self):
604
+ return self.model
605
+
606
+ def forward(
607
+ self,
608
+ input_ids: torch.LongTensor,
609
+ attention_mask: Optional[torch.Tensor] = None,
610
+ position_ids: Optional[torch.LongTensor] = None,
611
+ past_key_values: Optional[Cache] = None,
612
+ inputs_embeds: Optional[torch.FloatTensor] = None,
613
+ labels: Optional[torch.LongTensor] = None,
614
+ use_cache: Optional[bool] = None,
615
+ cache_position: Optional[torch.LongTensor] = None,
616
+ logits_to_keep: Union[int, torch.Tensor] = 0,
617
+ token_type_ids: Optional[torch.Tensor] = None, # will be ignored
618
+ **kwargs: Unpack[TransformersKwargs],
619
+ ) -> Union[Tuple, MoeCausalLMOutputWithPast]:
620
+ outputs: MoeModelOutputWithPast = self.model(
621
+ input_ids=input_ids,
622
+ attention_mask=attention_mask,
623
+ position_ids=position_ids,
624
+ past_key_values=past_key_values,
625
+ inputs_embeds=inputs_embeds,
626
+ use_cache=use_cache,
627
+ cache_position=cache_position,
628
+ **kwargs,
629
+ )
630
+
631
+ hidden_states = outputs.last_hidden_state
632
+ loss = None
633
+ # Only compute necessary logits
634
+ slice_indices = (
635
+ slice(-logits_to_keep, None)
636
+ if isinstance(logits_to_keep, int)
637
+ else logits_to_keep
638
+ )
639
+ kept_hidden_states = hidden_states[:, slice_indices, :]
640
+ shift_labels = kwargs.pop("shift_labels", None)
641
+ logits = None
642
+ loss = None
643
+
644
+ skip_logits = self.training and (labels is not None or shift_labels is not None)
645
+ if skip_logits:
646
+ loss = LigerForCausalLMLoss(
647
+ hidden_states=kept_hidden_states,
648
+ lm_head_weight=self.lm_head.weight,
649
+ labels=labels,
650
+ shift_labels=shift_labels,
651
+ hidden_size=self.config.hidden_size,
652
+ **kwargs,
653
+ )
654
+ else:
655
+ logits = self.lm_head(hidden_states[:, slice_indices, :])
656
+
657
+ if labels is not None:
658
+ loss = self.loss_function(logits, labels, self.vocab_size, **kwargs)
659
+
660
+
661
+ return MoeCausalLMOutputWithPast(
662
+ loss=loss,
663
+ logits=logits,
664
+ past_key_values=outputs.past_key_values,
665
+ hidden_states=outputs.hidden_states,
666
+ attentions=outputs.attentions,
667
+ router_logits=outputs.router_logits,
668
+ )
669
+
670
+
671
+ __all__ = [
672
+ "AfmoeSCMForCausalLM",
673
+ "AfmoeSCMModel",
674
+ "AfmoeSCMPreTrainedModel",
675
+ ]
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:0058acf26a6e7228298b0c9fed2a87fcb3f6cb5f84752cfde101b9e68b380918
3
+ size 14614841
tokenizer_config.json ADDED
@@ -0,0 +1,271 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_bos_token": false,
3
+ "add_eos_token": false,
4
+ "add_prefix_space": null,
5
+ "added_tokens_decoder": {
6
+ "0": {
7
+ "content": "<|begin_of_text|>",
8
+ "lstrip": false,
9
+ "normalized": false,
10
+ "rstrip": false,
11
+ "single_word": false,
12
+ "special": true
13
+ },
14
+ "1": {
15
+ "content": "<|end_of_text|>",
16
+ "lstrip": false,
17
+ "normalized": false,
18
+ "rstrip": false,
19
+ "single_word": false,
20
+ "special": true
21
+ },
22
+ "2": {
23
+ "content": "<|im_start|>",
24
+ "lstrip": false,
25
+ "normalized": false,
26
+ "rstrip": false,
27
+ "single_word": false,
28
+ "special": true
29
+ },
30
+ "3": {
31
+ "content": "<|im_end|>",
32
+ "lstrip": false,
33
+ "normalized": false,
34
+ "rstrip": false,
35
+ "single_word": false,
36
+ "special": true
37
+ },
38
+ "4": {
39
+ "content": "<|eot_id|>",
40
+ "lstrip": false,
41
+ "normalized": false,
42
+ "rstrip": false,
43
+ "single_word": false,
44
+ "special": true
45
+ },
46
+ "5": {
47
+ "content": "<|start|>",
48
+ "lstrip": false,
49
+ "normalized": false,
50
+ "rstrip": false,
51
+ "single_word": false,
52
+ "special": true
53
+ },
54
+ "6": {
55
+ "content": "<|channel|>",
56
+ "lstrip": false,
57
+ "normalized": false,
58
+ "rstrip": false,
59
+ "single_word": false,
60
+ "special": true
61
+ },
62
+ "7": {
63
+ "content": "<|message|>",
64
+ "lstrip": false,
65
+ "normalized": false,
66
+ "rstrip": false,
67
+ "single_word": false,
68
+ "special": true
69
+ },
70
+ "8": {
71
+ "content": "<|end|>",
72
+ "lstrip": false,
73
+ "normalized": false,
74
+ "rstrip": false,
75
+ "single_word": false,
76
+ "special": true
77
+ },
78
+ "9": {
79
+ "content": "<|fitm_start|>",
80
+ "lstrip": false,
81
+ "normalized": false,
82
+ "rstrip": false,
83
+ "single_word": false,
84
+ "special": true
85
+ },
86
+ "10": {
87
+ "content": "<|fitm_end|>",
88
+ "lstrip": false,
89
+ "normalized": false,
90
+ "rstrip": false,
91
+ "single_word": false,
92
+ "special": true
93
+ },
94
+ "11": {
95
+ "content": "<|fitm_hole|>",
96
+ "lstrip": false,
97
+ "normalized": false,
98
+ "rstrip": false,
99
+ "single_word": false,
100
+ "special": true
101
+ },
102
+ "12": {
103
+ "content": "<|pad|>",
104
+ "lstrip": false,
105
+ "normalized": false,
106
+ "rstrip": false,
107
+ "single_word": false,
108
+ "special": true
109
+ },
110
+ "13": {
111
+ "content": "<think>",
112
+ "lstrip": false,
113
+ "normalized": false,
114
+ "rstrip": false,
115
+ "single_word": false,
116
+ "special": false
117
+ },
118
+ "14": {
119
+ "content": "</think>",
120
+ "lstrip": false,
121
+ "normalized": false,
122
+ "rstrip": false,
123
+ "single_word": false,
124
+ "special": false
125
+ },
126
+ "15": {
127
+ "content": "<|reserved_special_2|>",
128
+ "lstrip": false,
129
+ "normalized": false,
130
+ "rstrip": false,
131
+ "single_word": false,
132
+ "special": true
133
+ },
134
+ "16": {
135
+ "content": "<|reserved_special_3|>",
136
+ "lstrip": false,
137
+ "normalized": false,
138
+ "rstrip": false,
139
+ "single_word": false,
140
+ "special": true
141
+ },
142
+ "17": {
143
+ "content": "<|reserved_special_4|>",
144
+ "lstrip": false,
145
+ "normalized": false,
146
+ "rstrip": false,
147
+ "single_word": false,
148
+ "special": true
149
+ },
150
+ "18": {
151
+ "content": "<|reserved_special_5|>",
152
+ "lstrip": false,
153
+ "normalized": false,
154
+ "rstrip": false,
155
+ "single_word": false,
156
+ "special": true
157
+ },
158
+ "19": {
159
+ "content": "<|reserved_special_6|>",
160
+ "lstrip": false,
161
+ "normalized": false,
162
+ "rstrip": false,
163
+ "single_word": false,
164
+ "special": true
165
+ },
166
+ "20": {
167
+ "content": "<|reserved_special_7|>",
168
+ "lstrip": false,
169
+ "normalized": false,
170
+ "rstrip": false,
171
+ "single_word": false,
172
+ "special": true
173
+ },
174
+ "21": {
175
+ "content": "<|reserved_special_8|>",
176
+ "lstrip": false,
177
+ "normalized": false,
178
+ "rstrip": false,
179
+ "single_word": false,
180
+ "special": true
181
+ },
182
+ "22": {
183
+ "content": "<|reserved_special_9|>",
184
+ "lstrip": false,
185
+ "normalized": false,
186
+ "rstrip": false,
187
+ "single_word": false,
188
+ "special": true
189
+ },
190
+ "23": {
191
+ "content": "<|reserved_special_10|>",
192
+ "lstrip": false,
193
+ "normalized": false,
194
+ "rstrip": false,
195
+ "single_word": false,
196
+ "special": true
197
+ },
198
+ "24": {
199
+ "content": "<|reserved_special_11|>",
200
+ "lstrip": false,
201
+ "normalized": false,
202
+ "rstrip": false,
203
+ "single_word": false,
204
+ "special": true
205
+ },
206
+ "25": {
207
+ "content": "<|reserved_special_12|>",
208
+ "lstrip": false,
209
+ "normalized": false,
210
+ "rstrip": false,
211
+ "single_word": false,
212
+ "special": true
213
+ },
214
+ "26": {
215
+ "content": "<|reserved_special_13|>",
216
+ "lstrip": false,
217
+ "normalized": false,
218
+ "rstrip": false,
219
+ "single_word": false,
220
+ "special": true
221
+ },
222
+ "27": {
223
+ "content": "<|reserved_special_14|>",
224
+ "lstrip": false,
225
+ "normalized": false,
226
+ "rstrip": false,
227
+ "single_word": false,
228
+ "special": true
229
+ },
230
+ "28": {
231
+ "content": "<|reserved_special_15|>",
232
+ "lstrip": false,
233
+ "normalized": false,
234
+ "rstrip": false,
235
+ "single_word": false,
236
+ "special": true
237
+ },
238
+ "29": {
239
+ "content": "<|reserved_special_16|>",
240
+ "lstrip": false,
241
+ "normalized": false,
242
+ "rstrip": false,
243
+ "single_word": false,
244
+ "special": true
245
+ },
246
+ "30": {
247
+ "content": "<|reserved_special_17|>",
248
+ "lstrip": false,
249
+ "normalized": false,
250
+ "rstrip": false,
251
+ "single_word": false,
252
+ "special": true
253
+ },
254
+ "31": {
255
+ "content": "<|reserved_special_18|>",
256
+ "lstrip": false,
257
+ "normalized": false,
258
+ "rstrip": false,
259
+ "single_word": false,
260
+ "special": true
261
+ }
262
+ },
263
+ "bos_token": "<|begin_of_text|>",
264
+ "clean_up_tokenization_spaces": false,
265
+ "eos_token": "<|im_end|>",
266
+ "extra_special_tokens": {},
267
+ "model_max_length": 65536,
268
+ "pad_token": "<|pad|>",
269
+ "tokenizer_class": "PreTrainedTokenizerFast",
270
+ "use_default_system_prompt": false
271
+ }