Raincleared commited on
Commit
8563fb4
·
verified ·
1 Parent(s): 7758f0a

Upload folder using huggingface_hub

Browse files
c4_validation.json ADDED
The diff for this file is too large to render. See raw diff
 
config.json ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "BlockFFNForCausalLM"
4
+ ],
5
+ "auto_map": {
6
+ "AutoConfig": "configuration_blockffn.BlockFFNConfig",
7
+ "AutoModel": "modeling_blockffn.BlockFFNModel",
8
+ "AutoModelForCausalLM": "modeling_blockffn.BlockFFNForCausalLM"
9
+ },
10
+ "bos_token_id": 1,
11
+ "eos_token_id": [
12
+ 2,
13
+ 73440
14
+ ],
15
+ "pad_token_id": 2,
16
+ "hidden_act": "silu",
17
+ "hidden_size": 1792,
18
+ "initializer_range": 0.1,
19
+ "intermediate_size": 10240,
20
+ "head_dim": 128,
21
+ "max_position_embeddings": 4096,
22
+ "model_type": "blockffn",
23
+ "num_attention_heads": 14,
24
+ "num_hidden_layers": 32,
25
+ "num_key_value_heads": 2,
26
+ "rms_norm_eps": 1e-05,
27
+ "rope_scaling": null,
28
+ "rope_theta": 10000.0,
29
+ "torch_dtype": "bfloat16",
30
+ "transformers_version": "4.36.0",
31
+ "use_cache": true,
32
+ "vocab_size": 73448,
33
+ "use_mup": false,
34
+ "num_experts": 102,
35
+ "moe_ffn_hidden_size": 64,
36
+ "moe_shared_expert_intermediate_size": 128,
37
+ "moe_layer_freq": [
38
+ 0,
39
+ 1,
40
+ 1,
41
+ 1,
42
+ 1,
43
+ 1,
44
+ 1,
45
+ 1,
46
+ 1,
47
+ 1,
48
+ 1,
49
+ 1,
50
+ 1,
51
+ 1,
52
+ 1,
53
+ 1,
54
+ 1,
55
+ 1,
56
+ 1,
57
+ 1,
58
+ 1,
59
+ 1,
60
+ 1,
61
+ 1,
62
+ 1,
63
+ 1,
64
+ 1,
65
+ 1,
66
+ 1,
67
+ 1,
68
+ 1,
69
+ 1
70
+ ],
71
+ "moe_router_dtype": "fp32",
72
+ "router_act_func": "relu",
73
+ "router_norm_type": "simple",
74
+ "expert_act_func": "norm_silu",
75
+ "expert_act_norm_type": "normal",
76
+ "num_layers": 32,
77
+ "ffn_hidden_size": 4480,
78
+ "num_query_groups": 14,
79
+ "norm_epsilon": 1e-05,
80
+ "router_norm_fixed": false,
81
+ "router_norm_scalar": false,
82
+ "router_norm_init_var": 0.1,
83
+ "moe_expert_bias_apply_method": "rms",
84
+ "use_blockffn": true,
85
+ "router_type": "topk",
86
+ "moe_router_enable_expert_bias": false,
87
+ "expert_not_gated": true,
88
+ "moe_router_pre_softmax": false,
89
+ "moe_router_topk": 2,
90
+ "moe_router_topp": 0.5,
91
+ "moe_router_score_function": "softmax",
92
+ "moe_router_topk_scaling_factor": null
93
+ }
configuration_blockffn.py ADDED
@@ -0,0 +1,169 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
5
+ # and OPT implementations in this library. It has been modified from its
6
+ # original forms to accommodate minor architectural differences compared
7
+ # to GPT-NeoX and OPT used by the Meta AI team that trained the model.
8
+ #
9
+ # Licensed under the Apache License, Version 2.0 (the "License");
10
+ # you may not use this file except in compliance with the License.
11
+ # You may obtain a copy of the License at
12
+ #
13
+ # http://www.apache.org/licenses/LICENSE-2.0
14
+ #
15
+ # Unless required by applicable law or agreed to in writing, software
16
+ # distributed under the License is distributed on an "AS IS" BASIS,
17
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18
+ # See the License for the specific language governing permissions and
19
+ # limitations under the License.
20
+ """BlockFFN model configuration"""
21
+
22
+ from transformers import PretrainedConfig
23
+ from transformers.modeling_rope_utils import rope_config_validation
24
+
25
+
26
+ class BlockFFNConfig(PretrainedConfig):
27
+
28
+ model_type = "blockffn"
29
+ keys_to_ignore_at_inference = ["past_key_values"]
30
+ # Default tensor parallel plan for base model `BlockFFNModel`
31
+ base_model_tp_plan = {
32
+ "layers.*.self_attn.q_proj": "colwise",
33
+ "layers.*.self_attn.k_proj": "colwise",
34
+ "layers.*.self_attn.v_proj": "colwise",
35
+ "layers.*.self_attn.o_proj": "rowwise",
36
+ "layers.*.mlp.gate_proj": "colwise",
37
+ "layers.*.mlp.up_proj": "colwise",
38
+ "layers.*.mlp.down_proj": "rowwise",
39
+ }
40
+ base_model_pp_plan = {
41
+ "embed_tokens": (["input_ids"], ["inputs_embeds"]),
42
+ "layers": (["hidden_states", "attention_mask"], ["hidden_states"]),
43
+ "norm": (["hidden_states"], ["hidden_states"]),
44
+ }
45
+
46
+ def __init__(
47
+ self,
48
+ vocab_size=32000,
49
+ hidden_size=4096,
50
+ ffn_hidden_size=11008,
51
+ num_layers=32,
52
+ num_attention_heads=32,
53
+ num_query_groups=None,
54
+ hidden_act="silu",
55
+ max_position_embeddings=2048,
56
+ initializer_range=0.02,
57
+ norm_epsilon=1e-6,
58
+ use_cache=True,
59
+ pad_token_id=None,
60
+ bos_token_id=1,
61
+ eos_token_id=2,
62
+ pretraining_tp=1,
63
+ tie_word_embeddings=False,
64
+ rope_theta=10000.0,
65
+ rope_scaling=None,
66
+ attention_bias=False,
67
+ attention_dropout=0.0,
68
+ mlp_bias=False,
69
+ head_dim=None,
70
+ use_mup=True,
71
+ mup_emb_scale=12,
72
+ mup_depth_scale=1.4,
73
+ mup_base_hidden_size=256,
74
+ num_experts=180,
75
+ moe_ffn_hidden_size=128,
76
+ moe_shared_expert_intermediate_size=128,
77
+ moe_layer_freq="([0]*3+[1]*29)",
78
+ moe_router_dtype="fp32",
79
+ router_act_func="relu",
80
+ router_norm_type="simple",
81
+ router_norm_fixed=False,
82
+ router_norm_scalar=False,
83
+ router_norm_init_var=0.1,
84
+ expert_act_func="norm_silu",
85
+ expert_act_norm_type="normal",
86
+ use_blockffn=False,
87
+ router_type="topk",
88
+ moe_router_topk=0,
89
+ moe_router_topp=0,
90
+ moe_router_enable_expert_bias=False,
91
+ moe_expert_bias_apply_method="base",
92
+ moe_router_score_function="sigmoid",
93
+ moe_router_topk_scaling_factor=2.5,
94
+ expert_not_gated=False,
95
+ moe_router_pre_softmax=False,
96
+ **kwargs,
97
+ ):
98
+ self.vocab_size = vocab_size
99
+ self.max_position_embeddings = max_position_embeddings
100
+ self.hidden_size = hidden_size
101
+ self.ffn_hidden_size = ffn_hidden_size
102
+ self.num_layers = num_layers
103
+ self.num_attention_heads = num_attention_heads
104
+
105
+ # for backward compatibility
106
+ if num_query_groups is None:
107
+ num_query_groups = num_attention_heads
108
+
109
+ self.num_query_groups = num_query_groups
110
+ self.hidden_act = hidden_act
111
+ self.initializer_range = initializer_range
112
+ self.norm_epsilon = norm_epsilon
113
+ self.pretraining_tp = pretraining_tp
114
+ self.use_cache = use_cache
115
+ self.rope_theta = rope_theta
116
+ self.rope_scaling = rope_scaling
117
+ self.attention_bias = attention_bias
118
+ self.attention_dropout = attention_dropout
119
+ self.mlp_bias = mlp_bias
120
+ self.head_dim = head_dim if head_dim is not None else self.hidden_size // self.num_attention_heads
121
+ self.use_mup = use_mup
122
+ self.mup_emb_scale = mup_emb_scale
123
+ self.mup_depth_scale = mup_depth_scale
124
+ self.mup_base_hidden_size = mup_base_hidden_size
125
+
126
+ self.num_experts = num_experts
127
+ self.moe_ffn_hidden_size = moe_ffn_hidden_size
128
+ self.moe_shared_expert_intermediate_size = moe_shared_expert_intermediate_size
129
+ self.moe_layer_freq = moe_layer_freq if isinstance(moe_layer_freq, (str, list)) else ([0] * num_layers)
130
+ self.moe_router_dtype = moe_router_dtype
131
+ self.router_act_func = router_act_func
132
+ self.router_norm_type = router_norm_type
133
+ self.router_norm_fixed = router_norm_fixed
134
+ self.router_norm_scalar = router_norm_scalar
135
+ self.router_norm_init_var = router_norm_init_var
136
+ self.expert_act_func = expert_act_func
137
+ self.expert_act_norm_type = expert_act_norm_type
138
+
139
+ self.use_blockffn = use_blockffn
140
+ self.router_type = router_type
141
+ self.moe_router_topk = moe_router_topk
142
+ self.moe_router_topp = moe_router_topp
143
+ self.moe_router_enable_expert_bias = moe_router_enable_expert_bias
144
+ self.moe_expert_bias_apply_method = moe_expert_bias_apply_method
145
+ self.moe_router_score_function = moe_router_score_function
146
+ self.moe_router_topk_scaling_factor = moe_router_topk_scaling_factor
147
+ self.expert_not_gated = expert_not_gated
148
+ self.moe_router_pre_softmax = moe_router_pre_softmax
149
+
150
+ # Validate the correctness of rotary position embeddings parameters
151
+ # BC: if there is a 'type' field, copy it it to 'rope_type'.
152
+ if self.rope_scaling is not None and "type" in self.rope_scaling:
153
+ self.rope_scaling["rope_type"] = self.rope_scaling["type"]
154
+ rope_config_validation(self)
155
+
156
+ super().__init__(
157
+ pad_token_id=pad_token_id,
158
+ bos_token_id=bos_token_id,
159
+ eos_token_id=eos_token_id,
160
+ tie_word_embeddings=tie_word_embeddings,
161
+ **kwargs,
162
+ )
163
+
164
+ @property
165
+ def mup_width_scale(self):
166
+ return (self.hidden_size / self.mup_base_hidden_size) if (self.use_mup and self.mup_base_hidden_size > 0) else 1
167
+
168
+
169
+ __all__ = ["BlockFFNConfig"]
evaluation.log ADDED
The diff for this file is too large to render. See raw diff
 
evaluation/results__hf_ckpts__blockffn_12b_mul1001_withmean_d64_s128_lr654e4_b512__/results_2026-03-09T14-06-28.603901.json ADDED
@@ -0,0 +1,609 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "results": {
3
+ "arc_challenge": {
4
+ "alias": "arc_challenge",
5
+ "acc,none": 0.29692832764505117,
6
+ "acc_stderr,none": 0.013352025976725228,
7
+ "acc_norm,none": 0.30802047781569963,
8
+ "acc_norm_stderr,none": 0.01349142951729204
9
+ },
10
+ "arc_easy": {
11
+ "alias": "arc_easy",
12
+ "acc,none": 0.6296296296296297,
13
+ "acc_stderr,none": 0.009908978578665757,
14
+ "acc_norm,none": 0.577020202020202,
15
+ "acc_norm_stderr,none": 0.010137328382209107
16
+ },
17
+ "boolq": {
18
+ "alias": "boolq",
19
+ "acc,none": 0.6256880733944954,
20
+ "acc_stderr,none": 0.008464246656443236
21
+ },
22
+ "hellaswag": {
23
+ "alias": "hellaswag",
24
+ "acc,none": 0.37422824138617805,
25
+ "acc_stderr,none": 0.004829339926388328,
26
+ "acc_norm,none": 0.4738099980083649,
27
+ "acc_norm_stderr,none": 0.004982931565945946
28
+ },
29
+ "lambada_openai": {
30
+ "alias": "lambada_openai",
31
+ "perplexity,none": 16.99295013502752,
32
+ "perplexity_stderr,none": 0.5693576969205276,
33
+ "acc,none": 0.443042887638269,
34
+ "acc_stderr,none": 0.0069206332420079265
35
+ },
36
+ "lambada_standard": {
37
+ "alias": "lambada_standard",
38
+ "perplexity,none": 27.533257711233524,
39
+ "perplexity_stderr,none": 0.9519324571988527,
40
+ "acc,none": 0.35532699398408696,
41
+ "acc_stderr,none": 0.006668004996315348
42
+ },
43
+ "piqa": {
44
+ "alias": "piqa",
45
+ "acc,none": 0.7023939064200218,
46
+ "acc_stderr,none": 0.01066735379238821,
47
+ "acc_norm,none": 0.6980413492927094,
48
+ "acc_norm_stderr,none": 0.010711732891588352
49
+ },
50
+ "social_iqa": {
51
+ "alias": "social_iqa",
52
+ "acc,none": 0.40890481064483114,
53
+ "acc_stderr,none": 0.011124710055682845
54
+ },
55
+ "wikitext": {
56
+ "alias": "wikitext",
57
+ "word_perplexity,none": 21.603753499994546,
58
+ "word_perplexity_stderr,none": "N/A",
59
+ "byte_perplexity,none": 1.7764935452161108,
60
+ "byte_perplexity_stderr,none": "N/A",
61
+ "bits_per_byte,none": 0.8290324467318287,
62
+ "bits_per_byte_stderr,none": "N/A"
63
+ },
64
+ "winogrande": {
65
+ "alias": "winogrande",
66
+ "acc,none": 0.5493291239147593,
67
+ "acc_stderr,none": 0.013983928869040235
68
+ }
69
+ },
70
+ "group_subtasks": {
71
+ "arc_challenge": [],
72
+ "arc_easy": [],
73
+ "boolq": [],
74
+ "hellaswag": [],
75
+ "lambada_openai": [],
76
+ "lambada_standard": [],
77
+ "piqa": [],
78
+ "social_iqa": [],
79
+ "wikitext": [],
80
+ "winogrande": []
81
+ },
82
+ "configs": {
83
+ "arc_challenge": {
84
+ "task": "arc_challenge",
85
+ "tag": [
86
+ "ai2_arc"
87
+ ],
88
+ "dataset_path": "allenai/ai2_arc",
89
+ "dataset_name": "ARC-Challenge",
90
+ "training_split": "train",
91
+ "validation_split": "validation",
92
+ "test_split": "test",
93
+ "doc_to_text": "Question: {{question}}\nAnswer:",
94
+ "doc_to_target": "{{choices.label.index(answerKey)}}",
95
+ "unsafe_code": false,
96
+ "doc_to_choice": "{{choices.text}}",
97
+ "description": "",
98
+ "target_delimiter": " ",
99
+ "fewshot_delimiter": "\n\n",
100
+ "num_fewshot": 0,
101
+ "metric_list": [
102
+ {
103
+ "metric": "acc",
104
+ "aggregation": "mean",
105
+ "higher_is_better": true
106
+ },
107
+ {
108
+ "metric": "acc_norm",
109
+ "aggregation": "mean",
110
+ "higher_is_better": true
111
+ }
112
+ ],
113
+ "output_type": "multiple_choice",
114
+ "repeats": 1,
115
+ "should_decontaminate": true,
116
+ "doc_to_decontamination_query": "Question: {{question}}\nAnswer:",
117
+ "metadata": {
118
+ "version": 1.0,
119
+ "pretrained": "results/hf_ckpts/blockffn_12b_mul1001_withmean_d64_s128_lr654e4_b512/",
120
+ "dtype": "bfloat16",
121
+ "trust_remote_code": true
122
+ }
123
+ },
124
+ "arc_easy": {
125
+ "task": "arc_easy",
126
+ "tag": [
127
+ "ai2_arc"
128
+ ],
129
+ "dataset_path": "allenai/ai2_arc",
130
+ "dataset_name": "ARC-Easy",
131
+ "training_split": "train",
132
+ "validation_split": "validation",
133
+ "test_split": "test",
134
+ "doc_to_text": "Question: {{question}}\nAnswer:",
135
+ "doc_to_target": "{{choices.label.index(answerKey)}}",
136
+ "unsafe_code": false,
137
+ "doc_to_choice": "{{choices.text}}",
138
+ "description": "",
139
+ "target_delimiter": " ",
140
+ "fewshot_delimiter": "\n\n",
141
+ "num_fewshot": 0,
142
+ "metric_list": [
143
+ {
144
+ "metric": "acc",
145
+ "aggregation": "mean",
146
+ "higher_is_better": true
147
+ },
148
+ {
149
+ "metric": "acc_norm",
150
+ "aggregation": "mean",
151
+ "higher_is_better": true
152
+ }
153
+ ],
154
+ "output_type": "multiple_choice",
155
+ "repeats": 1,
156
+ "should_decontaminate": true,
157
+ "doc_to_decontamination_query": "Question: {{question}}\nAnswer:",
158
+ "metadata": {
159
+ "version": 1.0,
160
+ "pretrained": "results/hf_ckpts/blockffn_12b_mul1001_withmean_d64_s128_lr654e4_b512/",
161
+ "dtype": "bfloat16",
162
+ "trust_remote_code": true
163
+ }
164
+ },
165
+ "boolq": {
166
+ "task": "boolq",
167
+ "tag": [
168
+ "super-glue-lm-eval-v1"
169
+ ],
170
+ "dataset_path": "super_glue",
171
+ "dataset_name": "boolq",
172
+ "training_split": "train",
173
+ "validation_split": "validation",
174
+ "doc_to_text": "{{passage}}\nQuestion: {{question}}?\nAnswer:",
175
+ "doc_to_target": "label",
176
+ "unsafe_code": false,
177
+ "doc_to_choice": [
178
+ "no",
179
+ "yes"
180
+ ],
181
+ "description": "",
182
+ "target_delimiter": " ",
183
+ "fewshot_delimiter": "\n\n",
184
+ "num_fewshot": 0,
185
+ "metric_list": [
186
+ {
187
+ "metric": "acc"
188
+ }
189
+ ],
190
+ "output_type": "multiple_choice",
191
+ "repeats": 1,
192
+ "should_decontaminate": true,
193
+ "doc_to_decontamination_query": "passage",
194
+ "metadata": {
195
+ "version": 2.0,
196
+ "pretrained": "results/hf_ckpts/blockffn_12b_mul1001_withmean_d64_s128_lr654e4_b512/",
197
+ "dtype": "bfloat16",
198
+ "trust_remote_code": true
199
+ }
200
+ },
201
+ "hellaswag": {
202
+ "task": "hellaswag",
203
+ "tag": [
204
+ "multiple_choice"
205
+ ],
206
+ "dataset_path": "Rowan/hellaswag",
207
+ "training_split": "train",
208
+ "validation_split": "validation",
209
+ "process_docs": "def process_docs(dataset: datasets.Dataset) -> datasets.Dataset:\n def _process_doc(doc):\n ctx = doc[\"ctx_a\"] + \" \" + doc[\"ctx_b\"].capitalize()\n out_doc = {\n \"query\": preprocess(doc[\"activity_label\"] + \": \" + ctx),\n \"choices\": [preprocess(ending) for ending in doc[\"endings\"]],\n \"gold\": int(doc[\"label\"]),\n }\n return out_doc\n\n return dataset.map(_process_doc)\n",
210
+ "doc_to_text": "{{query}}",
211
+ "doc_to_target": "{{label}}",
212
+ "unsafe_code": false,
213
+ "doc_to_choice": "choices",
214
+ "description": "",
215
+ "target_delimiter": " ",
216
+ "fewshot_delimiter": "\n\n",
217
+ "num_fewshot": 0,
218
+ "metric_list": [
219
+ {
220
+ "metric": "acc",
221
+ "aggregation": "mean",
222
+ "higher_is_better": true
223
+ },
224
+ {
225
+ "metric": "acc_norm",
226
+ "aggregation": "mean",
227
+ "higher_is_better": true
228
+ }
229
+ ],
230
+ "output_type": "multiple_choice",
231
+ "repeats": 1,
232
+ "should_decontaminate": false,
233
+ "metadata": {
234
+ "version": 1.0,
235
+ "pretrained": "results/hf_ckpts/blockffn_12b_mul1001_withmean_d64_s128_lr654e4_b512/",
236
+ "dtype": "bfloat16",
237
+ "trust_remote_code": true
238
+ }
239
+ },
240
+ "lambada_openai": {
241
+ "task": "lambada_openai",
242
+ "tag": [
243
+ "lambada"
244
+ ],
245
+ "dataset_path": "EleutherAI/lambada_openai",
246
+ "dataset_name": "default",
247
+ "test_split": "test",
248
+ "doc_to_text": "{{text.split(' ')[:-1]|join(' ')}}",
249
+ "doc_to_target": "{{' '+text.split(' ')[-1]}}",
250
+ "unsafe_code": false,
251
+ "description": "",
252
+ "target_delimiter": " ",
253
+ "fewshot_delimiter": "\n\n",
254
+ "num_fewshot": 0,
255
+ "metric_list": [
256
+ {
257
+ "metric": "perplexity",
258
+ "aggregation": "perplexity",
259
+ "higher_is_better": false
260
+ },
261
+ {
262
+ "metric": "acc",
263
+ "aggregation": "mean",
264
+ "higher_is_better": true
265
+ }
266
+ ],
267
+ "output_type": "loglikelihood",
268
+ "repeats": 1,
269
+ "should_decontaminate": true,
270
+ "doc_to_decontamination_query": "{{text}}",
271
+ "metadata": {
272
+ "version": 1.0,
273
+ "pretrained": "results/hf_ckpts/blockffn_12b_mul1001_withmean_d64_s128_lr654e4_b512/",
274
+ "dtype": "bfloat16",
275
+ "trust_remote_code": true
276
+ }
277
+ },
278
+ "lambada_standard": {
279
+ "task": "lambada_standard",
280
+ "tag": [
281
+ "lambada"
282
+ ],
283
+ "dataset_path": "lambada",
284
+ "validation_split": "validation",
285
+ "test_split": "test",
286
+ "doc_to_text": "{{text.split(' ')[:-1]|join(' ')}}",
287
+ "doc_to_target": "{{' '+text.split(' ')[-1]}}",
288
+ "unsafe_code": false,
289
+ "description": "",
290
+ "target_delimiter": " ",
291
+ "fewshot_delimiter": "\n\n",
292
+ "num_fewshot": 0,
293
+ "metric_list": [
294
+ {
295
+ "metric": "perplexity",
296
+ "aggregation": "perplexity",
297
+ "higher_is_better": false
298
+ },
299
+ {
300
+ "metric": "acc",
301
+ "aggregation": "mean",
302
+ "higher_is_better": true
303
+ }
304
+ ],
305
+ "output_type": "loglikelihood",
306
+ "repeats": 1,
307
+ "should_decontaminate": true,
308
+ "doc_to_decontamination_query": "{{text}}",
309
+ "metadata": {
310
+ "version": 1.0,
311
+ "pretrained": "results/hf_ckpts/blockffn_12b_mul1001_withmean_d64_s128_lr654e4_b512/",
312
+ "dtype": "bfloat16",
313
+ "trust_remote_code": true
314
+ }
315
+ },
316
+ "piqa": {
317
+ "task": "piqa",
318
+ "dataset_path": "baber/piqa",
319
+ "training_split": "train",
320
+ "validation_split": "validation",
321
+ "doc_to_text": "Question: {{goal}}\nAnswer:",
322
+ "doc_to_target": "label",
323
+ "unsafe_code": false,
324
+ "doc_to_choice": "{{[sol1, sol2]}}",
325
+ "description": "",
326
+ "target_delimiter": " ",
327
+ "fewshot_delimiter": "\n\n",
328
+ "num_fewshot": 0,
329
+ "metric_list": [
330
+ {
331
+ "metric": "acc",
332
+ "aggregation": "mean",
333
+ "higher_is_better": true
334
+ },
335
+ {
336
+ "metric": "acc_norm",
337
+ "aggregation": "mean",
338
+ "higher_is_better": true
339
+ }
340
+ ],
341
+ "output_type": "multiple_choice",
342
+ "repeats": 1,
343
+ "should_decontaminate": true,
344
+ "doc_to_decontamination_query": "goal",
345
+ "metadata": {
346
+ "version": 1.0,
347
+ "pretrained": "results/hf_ckpts/blockffn_12b_mul1001_withmean_d64_s128_lr654e4_b512/",
348
+ "dtype": "bfloat16",
349
+ "trust_remote_code": true
350
+ }
351
+ },
352
+ "social_iqa": {
353
+ "task": "social_iqa",
354
+ "dataset_path": "social_i_qa",
355
+ "training_split": "train",
356
+ "validation_split": "validation",
357
+ "doc_to_text": "Q: {{context}} {{question}}\nA:",
358
+ "doc_to_target": "{{ (label|int) - 1 }}",
359
+ "unsafe_code": false,
360
+ "doc_to_choice": "{{[answerA, answerB, answerC]}}",
361
+ "description": "",
362
+ "target_delimiter": " ",
363
+ "fewshot_delimiter": "\n\n",
364
+ "num_fewshot": 0,
365
+ "metric_list": [
366
+ {
367
+ "metric": "acc",
368
+ "aggregation": "mean",
369
+ "higher_is_better": true
370
+ }
371
+ ],
372
+ "output_type": "multiple_choice",
373
+ "repeats": 1,
374
+ "should_decontaminate": false,
375
+ "metadata": {
376
+ "version": 0.0,
377
+ "pretrained": "results/hf_ckpts/blockffn_12b_mul1001_withmean_d64_s128_lr654e4_b512/",
378
+ "dtype": "bfloat16",
379
+ "trust_remote_code": true
380
+ }
381
+ },
382
+ "wikitext": {
383
+ "task": "wikitext",
384
+ "dataset_path": "EleutherAI/wikitext_document_level",
385
+ "dataset_name": "wikitext-2-raw-v1",
386
+ "training_split": "train",
387
+ "validation_split": "validation",
388
+ "test_split": "test",
389
+ "doc_to_text": "",
390
+ "doc_to_target": "def wikitext_detokenizer(doc):\n string = doc[\"page\"]\n # contractions\n string = string.replace(\"s '\", \"s'\")\n string = re.sub(r\"/' [0-9]/\", r\"/'[0-9]/\", string)\n # number separators\n string = string.replace(\" @-@ \", \"-\")\n string = string.replace(\" @,@ \", \",\")\n string = string.replace(\" @.@ \", \".\")\n # punctuation\n string = string.replace(\" : \", \": \")\n string = string.replace(\" ; \", \"; \")\n string = string.replace(\" . \", \". \")\n string = string.replace(\" ! \", \"! \")\n string = string.replace(\" ? \", \"? \")\n string = string.replace(\" , \", \", \")\n # double brackets\n string = re.sub(r\"\\(\\s*([^\\)]*?)\\s*\\)\", r\"(\\1)\", string)\n string = re.sub(r\"\\[\\s*([^\\]]*?)\\s*\\]\", r\"[\\1]\", string)\n string = re.sub(r\"{\\s*([^}]*?)\\s*}\", r\"{\\1}\", string)\n string = re.sub(r\"\\\"\\s*([^\\\"]*?)\\s*\\\"\", r'\"\\1\"', string)\n string = re.sub(r\"'\\s*([^']*?)\\s*'\", r\"'\\1'\", string)\n # miscellaneous\n string = string.replace(\"= = = =\", \"====\")\n string = string.replace(\"= = =\", \"===\")\n string = string.replace(\"= =\", \"==\")\n string = string.replace(\" \" + chr(176) + \" \", chr(176))\n string = string.replace(\" \\n\", \"\\n\")\n string = string.replace(\"\\n \", \"\\n\")\n string = string.replace(\" N \", \" 1 \")\n string = string.replace(\" 's\", \"'s\")\n\n return string\n",
391
+ "unsafe_code": false,
392
+ "process_results": "def process_results(doc, results):\n (loglikelihood,) = results\n # IMPORTANT: wikitext counts number of words in *original doc before detokenization*\n _words = len(re.split(r\"\\s+\", doc[\"page\"]))\n _bytes = len(doc[\"page\"].encode(\"utf-8\"))\n return {\n \"word_perplexity\": (loglikelihood, _words),\n \"byte_perplexity\": (loglikelihood, _bytes),\n \"bits_per_byte\": (loglikelihood, _bytes),\n }\n",
393
+ "description": "",
394
+ "target_delimiter": " ",
395
+ "fewshot_delimiter": "\n\n",
396
+ "num_fewshot": 0,
397
+ "metric_list": [
398
+ {
399
+ "metric": "word_perplexity"
400
+ },
401
+ {
402
+ "metric": "byte_perplexity"
403
+ },
404
+ {
405
+ "metric": "bits_per_byte"
406
+ }
407
+ ],
408
+ "output_type": "loglikelihood_rolling",
409
+ "repeats": 1,
410
+ "should_decontaminate": true,
411
+ "doc_to_decontamination_query": "{{page}}",
412
+ "metadata": {
413
+ "version": 2.0,
414
+ "pretrained": "results/hf_ckpts/blockffn_12b_mul1001_withmean_d64_s128_lr654e4_b512/",
415
+ "dtype": "bfloat16",
416
+ "trust_remote_code": true
417
+ }
418
+ },
419
+ "winogrande": {
420
+ "task": "winogrande",
421
+ "dataset_path": "winogrande",
422
+ "dataset_name": "winogrande_xl",
423
+ "training_split": "train",
424
+ "validation_split": "validation",
425
+ "doc_to_text": "def doc_to_text(doc):\n answer_to_num = {\"1\": 0, \"2\": 1}\n return answer_to_num[doc[\"answer\"]]\n",
426
+ "doc_to_target": "def doc_to_target(doc):\n idx = doc[\"sentence\"].index(\"_\") + 1\n return doc[\"sentence\"][idx:].strip()\n",
427
+ "unsafe_code": false,
428
+ "doc_to_choice": "def doc_to_choice(doc):\n idx = doc[\"sentence\"].index(\"_\")\n options = [doc[\"option1\"], doc[\"option2\"]]\n return [doc[\"sentence\"][:idx] + opt for opt in options]\n",
429
+ "description": "",
430
+ "target_delimiter": " ",
431
+ "fewshot_delimiter": "\n\n",
432
+ "num_fewshot": 0,
433
+ "metric_list": [
434
+ {
435
+ "metric": "acc",
436
+ "aggregation": "mean",
437
+ "higher_is_better": true
438
+ }
439
+ ],
440
+ "output_type": "multiple_choice",
441
+ "repeats": 1,
442
+ "should_decontaminate": true,
443
+ "doc_to_decontamination_query": "sentence",
444
+ "metadata": {
445
+ "version": 1.0,
446
+ "pretrained": "results/hf_ckpts/blockffn_12b_mul1001_withmean_d64_s128_lr654e4_b512/",
447
+ "dtype": "bfloat16",
448
+ "trust_remote_code": true
449
+ }
450
+ }
451
+ },
452
+ "versions": {
453
+ "arc_challenge": 1.0,
454
+ "arc_easy": 1.0,
455
+ "boolq": 2.0,
456
+ "hellaswag": 1.0,
457
+ "lambada_openai": 1.0,
458
+ "lambada_standard": 1.0,
459
+ "piqa": 1.0,
460
+ "social_iqa": 0.0,
461
+ "wikitext": 2.0,
462
+ "winogrande": 1.0
463
+ },
464
+ "n-shot": {
465
+ "arc_challenge": 0,
466
+ "arc_easy": 0,
467
+ "boolq": 0,
468
+ "hellaswag": 0,
469
+ "lambada_openai": 0,
470
+ "lambada_standard": 0,
471
+ "piqa": 0,
472
+ "social_iqa": 0,
473
+ "wikitext": 0,
474
+ "winogrande": 0
475
+ },
476
+ "higher_is_better": {
477
+ "arc_challenge": {
478
+ "acc": true,
479
+ "acc_norm": true
480
+ },
481
+ "arc_easy": {
482
+ "acc": true,
483
+ "acc_norm": true
484
+ },
485
+ "boolq": {
486
+ "acc": true
487
+ },
488
+ "hellaswag": {
489
+ "acc": true,
490
+ "acc_norm": true
491
+ },
492
+ "lambada_openai": {
493
+ "perplexity": false,
494
+ "acc": true
495
+ },
496
+ "lambada_standard": {
497
+ "perplexity": false,
498
+ "acc": true
499
+ },
500
+ "piqa": {
501
+ "acc": true,
502
+ "acc_norm": true
503
+ },
504
+ "social_iqa": {
505
+ "acc": true
506
+ },
507
+ "wikitext": {
508
+ "word_perplexity": false,
509
+ "byte_perplexity": false,
510
+ "bits_per_byte": false
511
+ },
512
+ "winogrande": {
513
+ "acc": true
514
+ }
515
+ },
516
+ "n-samples": {
517
+ "winogrande": {
518
+ "original": 1267,
519
+ "effective": 1267
520
+ },
521
+ "wikitext": {
522
+ "original": 62,
523
+ "effective": 62
524
+ },
525
+ "social_iqa": {
526
+ "original": 1954,
527
+ "effective": 1954
528
+ },
529
+ "piqa": {
530
+ "original": 1838,
531
+ "effective": 1838
532
+ },
533
+ "lambada_standard": {
534
+ "original": 5153,
535
+ "effective": 5153
536
+ },
537
+ "lambada_openai": {
538
+ "original": 5153,
539
+ "effective": 5153
540
+ },
541
+ "hellaswag": {
542
+ "original": 10042,
543
+ "effective": 10042
544
+ },
545
+ "boolq": {
546
+ "original": 3270,
547
+ "effective": 3270
548
+ },
549
+ "arc_easy": {
550
+ "original": 2376,
551
+ "effective": 2376
552
+ },
553
+ "arc_challenge": {
554
+ "original": 1172,
555
+ "effective": 1172
556
+ }
557
+ },
558
+ "config": {
559
+ "model": "hf",
560
+ "model_args": "pretrained=results/hf_ckpts/blockffn_12b_mul1001_withmean_d64_s128_lr654e4_b512/,dtype=bfloat16,trust_remote_code=True,trust_remote_code=True",
561
+ "model_num_parameters": 1450770714,
562
+ "model_dtype": "torch.bfloat16",
563
+ "model_revision": "main",
564
+ "model_sha": "",
565
+ "batch_size": "8",
566
+ "batch_sizes": [],
567
+ "device": "cuda:0",
568
+ "use_cache": null,
569
+ "limit": null,
570
+ "bootstrap_iters": 100000,
571
+ "gen_kwargs": null,
572
+ "random_seed": 0,
573
+ "numpy_seed": 1234,
574
+ "torch_seed": 1234,
575
+ "fewshot_seed": 1234
576
+ },
577
+ "git_hash": "core_v0.12.0-135-g7f33517",
578
+ "date": 1773035718.973999,
579
+ "pretty_env_info": "PyTorch version: 2.6.0+cu124\nIs debug build: False\nCUDA used to build PyTorch: 12.4\nROCM used to build PyTorch: N/A\n\nOS: CentOS Linux 7 (Core) (x86_64)\nGCC version: (conda-forge gcc 9.5.0-19) 9.5.0\nClang version: Could not collect\nCMake version: version 3.30.1\nLibc version: glibc-2.17\n\nPython version: 3.10.14 (main, May 6 2024, 19:42:50) [GCC 11.2.0] (64-bit runtime)\nPython platform: Linux-3.10.0-1160.el7.x86_64-x86_64-with-glibc2.17\nIs CUDA available: True\nCUDA runtime version: 12.4.131\nCUDA_MODULE_LOADING set to: LAZY\nGPU models and configuration: \nGPU 0: NVIDIA A800-SXM4-80GB\nGPU 1: NVIDIA A800-SXM4-80GB\nGPU 2: NVIDIA A800-SXM4-80GB\nGPU 3: NVIDIA A800-SXM4-80GB\nGPU 4: NVIDIA A800-SXM4-80GB\nGPU 5: NVIDIA A800-SXM4-80GB\nGPU 6: NVIDIA A800-SXM4-80GB\nGPU 7: NVIDIA A800-SXM4-80GB\n\nNvidia driver version: 535.183.06\ncuDNN version: Could not collect\nHIP runtime version: N/A\nMIOpen runtime version: N/A\nIs XNNPACK available: True\n\nCPU:\nArchitecture: x86_64\nCPU op-mode(s): 32-bit, 64-bit\nByte Order: Little Endian\nCPU(s): 104\nOn-line CPU(s) list: 0-103\nThread(s) per core: 1\nCore(s) per socket: 52\nSocket(s): 2\nNUMA node(s): 2\nVendor ID: GenuineIntel\nCPU family: 6\nModel: 143\nModel name: Intel(R) Xeon(R) Platinum 8470\nStepping: 8\nCPU MHz: 800.048\nCPU max MHz: 3800.0000\nCPU min MHz: 800.0000\nBogoMIPS: 4000.00\nVirtualization: VT-x\nL1d cache: 48K\nL1i cache: 32K\nL2 cache: 2048K\nL3 cache: 107520K\nNUMA node0 CPU(s): 0-51\nNUMA node1 CPU(s): 52-103\nFlags: fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx pdpe1gb rdtscp lm constant_tsc art arch_perfmon pebs bts rep_good nopl xtopology nonstop_tsc aperfmperf eagerfpu pni pclmulqdq dtes64 monitor ds_cpl vmx smx est tm2 ssse3 sdbg fma cx16 xtpr pdcm pcid dca sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm abm 3dnowprefetch epb cat_l3 cat_l2 cdp_l3 invpcid_single intel_pt cdp_l2 ssbd mba ibrs ibpb stibp ibrs_enhanced tpr_shadow vnmi flexpriority ept vpid fsgsbase tsc_adjust bmi1 hle avx2 smep bmi2 erms invpcid rtm cqm rdt_a avx512f avx512dq rdseed adx smap avx512ifma clflushopt clwb avx512cd sha_ni avx512bw avx512vl xsaveopt xsavec xgetbv1 cqm_llc cqm_occup_llc cqm_mbm_total cqm_mbm_local dtherm ida arat pln pts hwp hwp_act_window hwp_epp hwp_pkg_req avx512vbmi umip pku ospke avx512_vbmi2 gfni vaes vpclmulqdq avx512_vnni avx512_bitalg avx512_vpopcntdq cldemote movdiri movdir64b md_clear pconfig spec_ctrl intel_stibp flush_l1d arch_capabilities\n\nVersions of relevant libraries:\n[pip3] numpy==1.26.4\n[pip3] nvidia-cublas-cu12==12.4.5.8\n[pip3] nvidia-cuda-cupti-cu12==12.4.127\n[pip3] nvidia-cuda-nvrtc-cu12==12.4.127\n[pip3] nvidia-cuda-runtime-cu12==12.4.127\n[pip3] nvidia-cudnn-cu12==9.1.0.70\n[pip3] nvidia-cufft-cu12==11.2.1.3\n[pip3] nvidia-curand-cu12==10.3.5.147\n[pip3] nvidia-cusolver-cu12==11.6.1.9\n[pip3] nvidia-cusparse-cu12==12.3.1.170\n[pip3] nvidia-cusparselt-cu12==0.6.2\n[pip3] nvidia-nccl-cu11==2.21.5\n[pip3] nvidia-nccl-cu12==2.21.5\n[pip3] nvidia-nvjitlink-cu12==12.4.127\n[pip3] nvidia-nvtx-cu12==12.4.127\n[pip3] torch==2.6.0\n[pip3] torchaudio==2.6.0\n[pip3] torchdata==0.11.0\n[pip3] torchvision==0.21.0\n[pip3] triton==3.2.0\n[conda] cuda-cudart 12.4.99 hd3aeb46_0 conda-forge\n[conda] cuda-cudart_linux-64 12.4.99 h59595ed_0 conda-forge\n[conda] cuda-cupti 12.4.127 he02047a_2 conda-forge\n[conda] cuda-libraries 12.4.0 ha770c72_0 conda-forge\n[conda] cuda-nvrtc 12.4.99 hd3aeb46_0 conda-forge\n[conda] cuda-nvtx 12.4.127 he02047a_2 conda-forge\n[conda] cuda-opencl 12.4.99 h59595ed_0 conda-forge\n[conda] cuda-runtime 12.4.0 ha804496_0 conda-forge\n[conda] ffmpeg 4.3 hf484d3e_0 pytorch\n[conda] libcublas 12.4.2.65 hd3aeb46_0 conda-forge\n[conda] libcufft 11.2.0.44 hd3aeb46_0 conda-forge\n[conda] libcurand 10.3.5.119 hd3aeb46_0 conda-forge\n[conda] libcusolver 11.6.0.99 hd3aeb46_0 conda-forge\n[conda] libcusparse 12.3.0.142 hd3aeb46_0 conda-forge\n[conda] libjpeg-turbo 2.0.0 h9bf148f_0 pytorch\n[conda] libnvjitlink 12.4.99 hd3aeb46_0 conda-forge\n[conda] mkl 2023.1.0 h213fc3f_46344 defaults\n[conda] numpy 1.26.4 pypi_0 pypi\n[conda] nvidia-cublas-cu12 12.4.5.8 pypi_0 pypi\n[conda] nvidia-cuda-cupti-cu12 12.4.127 pypi_0 pypi\n[conda] nvidia-cuda-nvrtc-cu12 12.4.127 pypi_0 pypi\n[conda] nvidia-cuda-runtime-cu12 12.4.127 pypi_0 pypi\n[conda] nvidia-cudnn-cu12 9.1.0.70 pypi_0 pypi\n[conda] nvidia-cufft-cu12 11.2.1.3 pypi_0 pypi\n[conda] nvidia-curand-cu12 10.3.5.147 pypi_0 pypi\n[conda] nvidia-cusolver-cu12 11.6.1.9 pypi_0 pypi\n[conda] nvidia-cusparse-cu12 12.3.1.170 pypi_0 pypi\n[conda] nvidia-cusparselt-cu12 0.6.2 pypi_0 pypi\n[conda] nvidia-nccl-cu11 2.21.5 pypi_0 pypi\n[conda] nvidia-nccl-cu12 2.21.5 pypi_0 pypi\n[conda] nvidia-nvjitlink-cu12 12.4.127 pypi_0 pypi\n[conda] nvidia-nvtx-cu12 12.4.127 pypi_0 pypi\n[conda] pytorch-cuda 12.4 hc786d27_6 pytorch\n[conda] pytorch-mutex 1.0 cuda pytorch\n[conda] torch 2.6.0 pypi_0 pypi\n[conda] torchaudio 2.6.0 pypi_0 pypi\n[conda] torchdata 0.11.0 pypi_0 pypi\n[conda] torchvision 0.21.0 pypi_0 pypi\n[conda] triton 3.2.0 pypi_0 pypi",
580
+ "transformers_version": "4.55.2",
581
+ "lm_eval_version": "0.4.9.1",
582
+ "upper_git_hash": null,
583
+ "tokenizer_pad_token": [
584
+ "<unk>",
585
+ "0"
586
+ ],
587
+ "tokenizer_eos_token": [
588
+ "<|im_end|>",
589
+ "73440"
590
+ ],
591
+ "tokenizer_bos_token": [
592
+ "<s>",
593
+ "1"
594
+ ],
595
+ "eot_token_id": 73440,
596
+ "max_length": 4096,
597
+ "task_hashes": {},
598
+ "model_source": "hf",
599
+ "model_name": "results/hf_ckpts/blockffn_12b_mul1001_withmean_d64_s128_lr654e4_b512/",
600
+ "model_name_sanitized": "results__hf_ckpts__blockffn_12b_mul1001_withmean_d64_s128_lr654e4_b512__",
601
+ "system_instruction": null,
602
+ "system_instruction_sha": null,
603
+ "fewshot_as_multiturn": false,
604
+ "chat_template": null,
605
+ "chat_template_sha": null,
606
+ "start_time": 11591492.163990611,
607
+ "end_time": 11592289.97671808,
608
+ "total_evaluation_time_seconds": "797.8127274680883"
609
+ }
generation_config.json ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "do_sample": true,
3
+ "top_p": 0.8,
4
+ "temperature": 0.8,
5
+ "bos_token_id": 1,
6
+ "eos_token_id": [2,73440],
7
+ "pad_token_id": 2
8
+ }
modeling_blockffn.py ADDED
@@ -0,0 +1,1040 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
5
+ # and OPT implementations in this library. It has been modified from its
6
+ # original forms to accommodate minor architectural differences compared
7
+ # to GPT-NeoX and OPT used by the Meta AI team that trained the model.
8
+ #
9
+ # Licensed under the Apache License, Version 2.0 (the "License");
10
+ # you may not use this file except in compliance with the License.
11
+ # You may obtain a copy of the License at
12
+ #
13
+ # http://www.apache.org/licenses/LICENSE-2.0
14
+ #
15
+ # Unless required by applicable law or agreed to in writing, software
16
+ # distributed under the License is distributed on an "AS IS" BASIS,
17
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18
+ # See the License for the specific language governing permissions and
19
+ # limitations under the License.
20
+ from typing import Callable, Optional, Union
21
+
22
+ import math
23
+ import torch
24
+ from torch import nn
25
+
26
+ import tree
27
+ from abc import ABC, abstractmethod
28
+ from fmoe.linear import MOELinear
29
+ from fmoe.functions import prepare_forward, MOEScatter, MOEGather
30
+
31
+ from transformers.activations import ACT2FN
32
+ from transformers.cache_utils import Cache, DynamicCache
33
+ from transformers.generation import GenerationMixin
34
+ from transformers.integrations import use_kernel_forward_from_hub
35
+ from transformers.masking_utils import create_causal_mask
36
+ from transformers.modeling_layers import GradientCheckpointingLayer
37
+ from transformers.modeling_outputs import (
38
+ BaseModelOutputWithPast,
39
+ CausalLMOutputWithPast,
40
+ )
41
+ from transformers.modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update
42
+ from transformers.modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
43
+ from transformers.processing_utils import Unpack
44
+ from transformers.utils import TransformersKwargs, auto_docstring, can_return_tuple, logging
45
+ from transformers.utils.generic import check_model_inputs
46
+ from .configuration_blockffn import BlockFFNConfig
47
+
48
+
49
+ logger = logging.get_logger(__name__)
50
+
51
+
52
+ @use_kernel_forward_from_hub("RMSNorm")
53
+ class BlockFFNRMSNorm(nn.Module):
54
+ def __init__(self, hidden_size, eps=1e-6):
55
+ super().__init__()
56
+ self.weight = nn.Parameter(torch.ones(hidden_size))
57
+ self.variance_epsilon = eps
58
+
59
+ def forward(self, hidden_states):
60
+ input_dtype = hidden_states.dtype
61
+ hidden_states = hidden_states.to(torch.float32)
62
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
63
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
64
+ return self.weight * hidden_states.to(input_dtype)
65
+
66
+ def extra_repr(self):
67
+ return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
68
+
69
+
70
+ class BlockFFNRotaryEmbedding(nn.Module):
71
+ def __init__(self, config: BlockFFNConfig, device=None):
72
+ super().__init__()
73
+ # BC: "rope_type" was originally "type"
74
+ if hasattr(config, "rope_scaling") and isinstance(config.rope_scaling, dict):
75
+ self.rope_type = config.rope_scaling.get("rope_type", config.rope_scaling.get("type"))
76
+ else:
77
+ self.rope_type = "default"
78
+ self.max_seq_len_cached = config.max_position_embeddings
79
+ self.original_max_seq_len = config.max_position_embeddings
80
+
81
+ self.config = config
82
+ self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
83
+
84
+ inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device)
85
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
86
+ self.original_inv_freq = self.inv_freq
87
+
88
+ @torch.no_grad()
89
+ @dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope)
90
+ def forward(self, x, position_ids):
91
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device)
92
+ position_ids_expanded = position_ids[:, None, :].float()
93
+
94
+ device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
95
+ with torch.autocast(device_type=device_type, enabled=False): # Force float32
96
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
97
+ emb = torch.cat((freqs, freqs), dim=-1)
98
+ cos = emb.cos() * self.attention_scaling
99
+ sin = emb.sin() * self.attention_scaling
100
+
101
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
102
+
103
+
104
+ def rotate_half(x):
105
+ """Rotates half the hidden dims of the input."""
106
+ x1 = x[..., : x.shape[-1] // 2]
107
+ x2 = x[..., x.shape[-1] // 2 :]
108
+ return torch.cat((-x2, x1), dim=-1)
109
+
110
+
111
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
112
+ """Applies Rotary Position Embedding to the query and key tensors.
113
+
114
+ Args:
115
+ q (`torch.Tensor`): The query tensor.
116
+ k (`torch.Tensor`): The key tensor.
117
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
118
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
119
+ position_ids (`torch.Tensor`, *optional*):
120
+ Deprecated and unused.
121
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
122
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
123
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
124
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
125
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
126
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
127
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
128
+ Returns:
129
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
130
+ """
131
+ cos = cos.unsqueeze(unsqueeze_dim)
132
+ sin = sin.unsqueeze(unsqueeze_dim)
133
+ q_embed = (q * cos) + (rotate_half(q) * sin)
134
+ k_embed = (k * cos) + (rotate_half(k) * sin)
135
+ return q_embed, k_embed
136
+
137
+
138
+ class SimpleLayerNorm(nn.Module):
139
+ def __init__(self, dim_norm: int, fixed: bool = False, init_var: float = 1.0):
140
+ super().__init__()
141
+ self.dim_norm = dim_norm
142
+ self.fixed = fixed
143
+ if self.fixed:
144
+ self.weight = init_var
145
+ else:
146
+ self.weight = torch.nn.Parameter(torch.full((self.dim_norm,), init_var))
147
+
148
+ @torch.compile
149
+ def forward(self, x: torch.Tensor):
150
+ return x * self.weight
151
+
152
+
153
+ class BlockFFNMLP(nn.Module):
154
+ def __init__(self, config: BlockFFNConfig, intermediate_size: int = None):
155
+ super().__init__()
156
+ self.config = config
157
+ self.hidden_size = config.hidden_size
158
+ self.intermediate_size = config.ffn_hidden_size if intermediate_size is None else intermediate_size
159
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.mlp_bias)
160
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.mlp_bias)
161
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=config.mlp_bias)
162
+ self.act_fn = ACT2FN[config.hidden_act]
163
+
164
+ def forward(self, x):
165
+ down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
166
+ return down_proj
167
+
168
+
169
+ class BlockFFNRouter(nn.Module):
170
+ def __init__(self, config: BlockFFNConfig):
171
+ super().__init__()
172
+ self.config = config
173
+ self.num_experts = self.config.num_experts
174
+
175
+ if self.config.moe_router_dtype == "fp32":
176
+ self.router_dtype = torch.float32
177
+ elif self.config.moe_router_dtype == "fp64":
178
+ self.router_dtype = torch.float64
179
+ elif self.config.moe_router_dtype == "bf16":
180
+ self.router_dtype = torch.bfloat16
181
+ else:
182
+ raise NotImplementedError(f"{self.config.moe_router_dtype} is not supported.")
183
+
184
+ self.weight = torch.nn.Parameter(
185
+ torch.empty((self.config.num_experts, self.config.hidden_size), dtype=self.router_dtype)
186
+ )
187
+
188
+ def forward(self, x: torch.Tensor):
189
+ return nn.functional.linear(x.to(self.router_dtype), self.weight)
190
+
191
+
192
+ class NormSiLU(nn.Module):
193
+ def __init__(self, config: BlockFFNConfig):
194
+ super().__init__()
195
+ self.num_blocks, self.block_size = config.num_experts, config.moe_ffn_hidden_size
196
+ self.activate_fn_type = config.expert_act_func
197
+ assert self.activate_fn_type in ["norm_silu", "norm_silu_norms", "norm_silu_nomean", "silu"]
198
+
199
+ self.rms_norm = None
200
+ if self.activate_fn_type not in ["norm_silu_norms", "silu"]:
201
+ self.rms_norm = BlockFFNRMSNorm(config.moe_ffn_hidden_size, eps=config.norm_epsilon)
202
+ self.silu = torch.nn.SiLU()
203
+
204
+ @torch.compile
205
+ def forward(self, hidden: torch.Tensor) -> torch.Tensor:
206
+ assert hidden.ndim == 2
207
+ if self.activate_fn_type not in ["norm_silu_nomean", "silu"]:
208
+ hidden = hidden - torch.mean(hidden, dim=-1, keepdim=True)
209
+ if self.activate_fn_type not in ["norm_silu_norms", "silu"]:
210
+ return self.silu(self.rms_norm(hidden.view(hidden.shape[0], self.num_blocks, self.block_size)))
211
+ else:
212
+ return self.silu(hidden)
213
+
214
+
215
+ class BlockFFNLayer(nn.Module):
216
+ def __init__(self, config: BlockFFNConfig):
217
+ super(BlockFFNLayer, self).__init__()
218
+ self.config = config
219
+ self.num_experts, self.dim_expert, self.hidden_size = \
220
+ config.num_experts, config.moe_ffn_hidden_size, config.hidden_size
221
+ self.dim_shared_expert = config.moe_shared_expert_intermediate_size
222
+ self.router_norm_type = config.router_norm_type
223
+
224
+ self.moe_router = BlockFFNRouter(self.config)
225
+ assert config.router_act_func == "relu"
226
+ self.router_act = nn.ReLU()
227
+ if config.router_norm_type == "simple":
228
+ self.router_norm = SimpleLayerNorm(
229
+ dim_norm=(1 if self.config.router_norm_scalar else config.num_experts),
230
+ fixed=config.router_norm_fixed,
231
+ init_var=config.router_norm_init_var,
232
+ )
233
+ elif config.router_norm_type == "rms":
234
+ self.router_norm = BlockFFNRMSNorm(self.config.num_experts, eps=config.norm_epsilon)
235
+ else:
236
+ raise NotImplementedError
237
+
238
+ self.expert_gated = not config.expert_not_gated
239
+ if self.expert_gated:
240
+ self.expert_gate_proj = nn.Linear(self.hidden_size, self.num_experts * self.dim_expert, bias=config.mlp_bias)
241
+
242
+ self.expert_up_proj = nn.Linear(self.hidden_size, self.num_experts * self.dim_expert, bias=config.mlp_bias)
243
+ assert config.expert_act_norm_type == "normal"
244
+ self.expert_act = NormSiLU(self.config)
245
+ self.expert_down_proj = nn.Linear(self.num_experts * self.dim_expert, self.hidden_size, bias=config.mlp_bias)
246
+
247
+ self.use_shared_expert = self.dim_shared_expert is not None and self.dim_shared_expert > 0
248
+ if self.use_shared_expert:
249
+ self.shared_experts = BlockFFNMLP(self.config, intermediate_size=self.dim_shared_expert)
250
+
251
+ self.enable_expert_bias = config.moe_router_enable_expert_bias
252
+ if self.enable_expert_bias:
253
+ self.expert_bias = torch.nn.Parameter(torch.zeros(self.num_experts, dtype=torch.float32))
254
+ self.expert_bias_apply_method = config.moe_expert_bias_apply_method
255
+
256
+ def apply_expert_bias(self, router_scores: torch.Tensor) -> torch.Tensor:
257
+ if self.expert_bias_apply_method == "base":
258
+ scores_for_routing = router_scores + self.expert_bias
259
+ elif self.expert_bias_apply_method == "rms":
260
+ variance = router_scores.to(torch.float32).pow(2).mean(dim=-1, keepdim=True)
261
+ scores_for_routing = router_scores + self.expert_bias.unsqueeze(0) * torch.sqrt(variance)
262
+ else:
263
+ raise NotImplementedError(f"invalid apply method: {self.expert_bias_apply_method}")
264
+ return scores_for_routing
265
+
266
+ def forward(self, hidden_states: torch.Tensor):
267
+ ori_shape = hidden_states.shape
268
+ hidden_states = hidden_states.view(-1, self.hidden_size)
269
+ seq_len = hidden_states.shape[0]
270
+
271
+ # router module forward
272
+ raw_router_score = self.moe_router(hidden_states) # [seq_len, num_experts]
273
+ if self.enable_expert_bias:
274
+ scores_for_routing = self.apply_expert_bias(raw_router_score)
275
+ router_score = self.router_act(raw_router_score) * torch.gt(scores_for_routing, 0).type_as(raw_router_score)
276
+ else:
277
+ router_score = self.router_act(raw_router_score)
278
+
279
+ router_score = self.router_norm(router_score)
280
+
281
+ # expert module forward
282
+ x_in = self.expert_up_proj(hidden_states) # [seq_len, num_experts * dim_expert]
283
+ if self.expert_gated:
284
+ x_gate = self.expert_gate_proj(hidden_states)
285
+ x_gate = self.expert_act(x_gate)
286
+ if x_gate.ndim == 3:
287
+ x_in = x_in.view(seq_len, self.num_experts, self.dim_expert)
288
+ x_in = x_in * x_gate
289
+ else:
290
+ x_in = self.expert_act(x_in)
291
+ if x_in.ndim == 3:
292
+ scored_x_in = x_in * router_score.type_as(hidden_states).unsqueeze(-1)
293
+ else:
294
+ scored_x_in = x_in.view(seq_len, self.num_experts, self.dim_expert) * router_score.type_as(hidden_states).unsqueeze(-1)
295
+ output = self.expert_down_proj(scored_x_in.view(seq_len, self.num_experts * self.dim_expert))
296
+
297
+ if self.use_shared_expert:
298
+ output = output + self.shared_experts(hidden_states)
299
+ return output.view(*ori_shape)
300
+
301
+
302
+ class BaseRouter(ABC, nn.Module):
303
+ """Base Router class"""
304
+ def __init__(self, config: BlockFFNConfig) -> None:
305
+ super().__init__()
306
+ self.config = config
307
+ self.num_experts = self.config.num_experts
308
+
309
+ if self.config.moe_router_dtype == "fp32":
310
+ self.router_dtype = torch.float32
311
+ elif self.config.moe_router_dtype == "fp64":
312
+ self.router_dtype = torch.float64
313
+ elif self.config.moe_router_dtype == "bf16":
314
+ self.router_dtype = torch.bfloat16
315
+ else:
316
+ raise NotImplementedError(f"{self.config.moe_router_dtype} is not supported.")
317
+
318
+ self.weight = torch.nn.Parameter(
319
+ torch.empty((self.num_experts, self.config.hidden_size), dtype=self.router_dtype)
320
+ )
321
+
322
+ def gating(self, input: torch.Tensor):
323
+ return torch.nn.functional.linear(input.to(self.router_dtype), self.weight.to(self.router_dtype))
324
+
325
+ @abstractmethod
326
+ def routing(self, logits: torch.Tensor):
327
+ """Routing function.
328
+
329
+ Args:
330
+ logits (torch.Tensor): Logits tensor.
331
+
332
+ Returns:
333
+ Tuple[torch.Tensor, torch.Tensor]: A tuple containing token assignment
334
+ probabilities and mapping.
335
+ """
336
+ raise NotImplementedError("Routing function not implemented.")
337
+
338
+ @abstractmethod
339
+ def forward(self, input: torch.Tensor):
340
+ """
341
+ Forward pass of the router.
342
+
343
+ Args:
344
+ input (torch.Tensor): Input tensor.
345
+ """
346
+ raise NotImplementedError("Forward function not implemented.")
347
+
348
+
349
+ class TopKRouter(BaseRouter):
350
+ """Route each token to the top-k experts."""
351
+
352
+ def __init__(self, config: BlockFFNConfig) -> None:
353
+ super().__init__(config)
354
+ self.config = config
355
+ self.topk = self.config.moe_router_topk
356
+ self.score_function = self.config.moe_router_score_function
357
+ self.use_pre_softmax = self.config.moe_router_pre_softmax
358
+ self.scaling_factor = self.config.moe_router_topk_scaling_factor
359
+
360
+ self.enable_expert_bias = self.config.moe_router_enable_expert_bias
361
+ if self.enable_expert_bias:
362
+ self.expert_bias = torch.nn.Parameter(torch.zeros(self.num_experts, dtype=torch.float32))
363
+ else:
364
+ self.expert_bias = None
365
+
366
+ def _maintain_float32_expert_bias(self):
367
+ """
368
+ Maintain the expert bias in float32.
369
+
370
+ When using bf16/fp16, the expert bias gets converted to lower precision in Float16Module.
371
+ We keep it in float32 to avoid routing errors when updating the expert_bias.
372
+ """
373
+ if hasattr(self, 'expert_bias') and self.expert_bias is not None:
374
+ if self.expert_bias.dtype != torch.float32:
375
+ self.expert_bias.data = self.expert_bias.data.to(torch.float32)
376
+
377
+ def routing(self, logits: torch.Tensor):
378
+ """Top-k routing function
379
+
380
+ Args:
381
+ logits (torch.Tensor): Logits tensor after gating.
382
+
383
+ Returns:
384
+ probs (torch.Tensor): The probabilities of token to experts assignment.
385
+ routing_map (torch.Tensor): The mapping of token to experts assignment,
386
+ with shape [num_tokens, num_experts].
387
+ """
388
+ logits = logits.view(-1, self.num_experts)
389
+
390
+ if self.score_function == "softmax":
391
+ if self.use_pre_softmax:
392
+ scores = torch.softmax(logits, dim=-1, dtype=torch.float32).type_as(logits)
393
+ probs, top_indices = torch.topk(scores, k=self.topk, dim=1)
394
+ else:
395
+ scores, top_indices = torch.topk(logits, k=self.topk, dim=1)
396
+ probs = torch.softmax(scores, dim=-1, dtype=torch.float32).type_as(logits)
397
+ elif self.score_function == "sigmoid":
398
+ scores = torch.sigmoid(logits.float()).type_as(logits)
399
+ if self.expert_bias is not None:
400
+ scores_for_routing = scores + self.expert_bias
401
+ _, top_indices = torch.topk(scores_for_routing, k=self.topk, dim=1)
402
+ scores = torch.gather(scores, dim=1, index=top_indices).type_as(logits)
403
+ else:
404
+ scores, top_indices = torch.topk(scores, k=self.topk, dim=1)
405
+ probs = scores / (scores.sum(dim=-1, keepdim=True) + 1e-20) if self.topk > 1 else scores
406
+ else:
407
+ raise ValueError(f"Invalid score_function: {self.score_function}")
408
+
409
+ if self.scaling_factor:
410
+ probs = probs * self.scaling_factor
411
+
412
+ return probs, top_indices
413
+
414
+ def forward(self, input: torch.Tensor):
415
+ """
416
+ Forward pass of the router.
417
+
418
+ Args:
419
+ input (torch.Tensor): Input tensor.
420
+ """
421
+ self._maintain_float32_expert_bias()
422
+ logits = self.gating(input)
423
+ top_scores, top_indices = self.routing(logits)
424
+ return top_scores, top_indices
425
+
426
+
427
+ class ReMoERouter(BaseRouter):
428
+ def __init__(self, config: BlockFFNConfig) -> None:
429
+ super().__init__(config)
430
+ self.config = config
431
+ self.router_act = torch.nn.ReLU()
432
+
433
+ def routing(self, logits: torch.Tensor):
434
+ """Top-k routing function
435
+
436
+ Args:
437
+ logits (torch.Tensor): Logits tensor after gating.
438
+
439
+ Returns:
440
+ probs (torch.Tensor): The probabilities of token to experts assignment.
441
+ routing_map (torch.Tensor): The mapping of token to experts assignment,
442
+ with shape [num_tokens, num_experts].
443
+ """
444
+ logits = logits.view(-1, self.num_experts)
445
+
446
+ router_score = self.router_act(logits)
447
+ routing_map = router_score > 0
448
+
449
+ sorted_probs, sorted_indices = torch.sort(router_score, descending=True, dim=-1)
450
+ sorted_map = sorted_probs <= 0
451
+ sorted_indices = torch.where(sorted_map, -1, sorted_indices)
452
+ max_valid_num = max(sorted_probs.size(-1) - torch.min(torch.sum(sorted_map, dim=-1)).item(), 1)
453
+ assert torch.all(sorted_map[:, max_valid_num:])
454
+ sorted_probs = sorted_probs[:, :max_valid_num]
455
+ sorted_indices = sorted_indices[:, :max_valid_num]
456
+ assert torch.sum(routing_map) == torch.sum(sorted_indices != -1)
457
+ return sorted_probs, sorted_indices
458
+
459
+ def forward(self, input: torch.Tensor):
460
+ """
461
+ Forward pass of the router.
462
+
463
+ Args:
464
+ input (torch.Tensor): Input tensor.
465
+ """
466
+ logits = self.gating(input)
467
+ top_scores, top_indices = self.routing(logits)
468
+ return top_scores, top_indices
469
+
470
+
471
+ class TopPRouter(BaseRouter):
472
+ def __init__(self, config: BlockFFNConfig) -> None:
473
+ super().__init__(config)
474
+ self.config = config
475
+ self.top_p = config.moe_router_topp
476
+
477
+ def routing(self, logits: torch.Tensor):
478
+ """Top-k routing function
479
+
480
+ Args:
481
+ logits (torch.Tensor): Logits tensor after gating.
482
+
483
+ Returns:
484
+ probs (torch.Tensor): The probabilities of token to experts assignment.
485
+ routing_map (torch.Tensor): The mapping of token to experts assignment,
486
+ with shape [num_tokens, num_experts].
487
+ """
488
+ logits = logits.view(-1, self.num_experts)
489
+
490
+ router_score = torch.abs(logits)
491
+ router_score = router_score / (router_score.sum(dim=-1, keepdim=True) + 1e-20)
492
+
493
+ sorted_probs, sorted_indices = torch.sort(router_score, descending=True, dim=-1)
494
+ cumulative_probs = torch.cumsum(sorted_probs, dim=-1)
495
+ mask = cumulative_probs > self.top_p
496
+
497
+ threshold_indices = mask.long().argmax(dim=-1)
498
+ threshold_mask = torch.nn.functional.one_hot(threshold_indices, num_classes=sorted_indices.size(-1)).bool()
499
+
500
+ mask = mask & ~threshold_mask
501
+ sorted_indices = torch.where(mask, -1, sorted_indices)
502
+ sorted_probs = torch.where(mask, 0.0, sorted_probs)
503
+
504
+ max_valid_num = max(mask.size(-1) - torch.min(torch.sum(mask, dim=-1)).item(), 1)
505
+ assert torch.all(mask[:, max_valid_num:])
506
+
507
+ sorted_indices = sorted_indices[:, :max_valid_num]
508
+ sorted_probs = sorted_probs[:, :max_valid_num]
509
+ sorted_probs = sorted_probs / sorted_probs.sum(dim=-1, keepdim=True)
510
+ return sorted_probs, sorted_indices
511
+
512
+ def forward(self, input: torch.Tensor):
513
+ """
514
+ Forward pass of the router.
515
+
516
+ Args:
517
+ input (torch.Tensor): Input tensor.
518
+ """
519
+ logits = self.gating(input)
520
+ top_scores, top_indices = self.routing(logits)
521
+ return top_scores, top_indices
522
+
523
+
524
+ class FastTopKCalculator:
525
+ def __init__(self, num_experts: int):
526
+ self.num_experts = num_experts
527
+
528
+ def fmoe_sparse_topk_forward(self, hidden_states: torch.Tensor, topk_indices: torch.Tensor, experts: torch.nn.Module):
529
+ (
530
+ pos,
531
+ local_expert_count,
532
+ global_expert_count,
533
+ fwd_expert_count,
534
+ fwd_batch_size,
535
+ ) = prepare_forward(topk_indices, self.num_experts, 1)
536
+ topk = 1
537
+ if len(topk_indices.shape) == 2:
538
+ topk = topk_indices.shape[1]
539
+
540
+ def scatter_func(tensor):
541
+ return MOEScatter.apply(
542
+ tensor,
543
+ torch.div(pos, topk, rounding_mode='floor'),
544
+ local_expert_count,
545
+ global_expert_count,
546
+ fwd_batch_size,
547
+ 1,
548
+ )
549
+
550
+ x = tree.map_structure(scatter_func, hidden_states)
551
+ x = experts(x, fwd_expert_count, topk_indices=topk_indices)
552
+
553
+ out_batch_size = tree.flatten(hidden_states)[0].shape[0]
554
+ if len(topk_indices.shape) == 2:
555
+ out_batch_size *= topk_indices.shape[1]
556
+
557
+ def gather_func(tensor):
558
+ return MOEGather.apply(
559
+ tensor,
560
+ pos,
561
+ local_expert_count,
562
+ global_expert_count,
563
+ out_batch_size,
564
+ 1,
565
+ )
566
+
567
+ outp = tree.map_structure(gather_func, x)
568
+ return outp
569
+
570
+ def forward(self, hidden_states, topk_indices, topk_weights, experts):
571
+ assert topk_indices.shape == topk_weights.shape
572
+ top_k = topk_indices.shape[-1]
573
+ dim3 = hidden_states.ndim == 3
574
+ if dim3:
575
+ batch_size, seq_len, dim = hidden_states.shape
576
+ hidden_states = hidden_states.view(batch_size * seq_len, dim)
577
+ else:
578
+ assert hidden_states.ndim == 2
579
+ batch_size, (seq_len, dim) = -1, hidden_states.shape
580
+ fwd = self.fmoe_sparse_topk_forward(hidden_states, topk_indices, experts)
581
+
582
+ def view_func(tensor):
583
+ n_dim = tensor.shape[-1]
584
+ tensor = tensor.view(-1, top_k, n_dim)
585
+ return tensor
586
+
587
+ moe_output = tree.map_structure(view_func, fwd)
588
+ topk_weights = topk_weights.unsqueeze(1)
589
+
590
+ def bmm_func(tensor):
591
+ n_dim = tensor.shape[-1]
592
+ tensor = torch.bmm(topk_weights, tensor).reshape(-1, n_dim)
593
+ return tensor
594
+
595
+ moe_output = tree.map_structure(bmm_func, moe_output)
596
+ if dim3:
597
+ moe_output = moe_output.view(batch_size, seq_len, -1)
598
+ return moe_output
599
+
600
+
601
+ class MoELinearExperts(nn.Module):
602
+ def __init__(
603
+ self,
604
+ dim_in: int,
605
+ dim_out: int,
606
+ num_experts: int,
607
+ ffn_bias: bool,
608
+ ):
609
+ super().__init__()
610
+ self.dim_in = self.in_features = dim_in
611
+ self.dim_out = self.out_features = dim_out
612
+ self.weight = torch.nn.Parameter(torch.empty(num_experts, dim_out, dim_in))
613
+ self.bias = None
614
+ if ffn_bias:
615
+ self.bias = torch.nn.Parameter(torch.empty(num_experts, dim_out))
616
+
617
+ def forward(self, x: torch.Tensor, fwd_expert_count: torch.Tensor):
618
+ x = MOELinear.apply(x, fwd_expert_count, self.weight, self.bias)
619
+ return x
620
+
621
+
622
+ class MoEGatedExperts(nn.Module):
623
+ def __init__(
624
+ self,
625
+ dim_in: int,
626
+ dim_ff: int,
627
+ is_gated: bool,
628
+ act_name: str,
629
+ num_experts: int,
630
+ ffn_bias: bool = False,
631
+ ):
632
+ super().__init__()
633
+ self.is_gated = is_gated
634
+ self.dim_in, self.dim_ff, self.num_experts = dim_in, dim_ff, num_experts
635
+ if self.is_gated:
636
+ self.gate_proj = MoELinearExperts(dim_in, dim_ff, num_experts, ffn_bias)
637
+ self.up_proj = MoELinearExperts(dim_in, dim_ff, num_experts, ffn_bias)
638
+ self.down_proj = MoELinearExperts(dim_ff, dim_in, num_experts, ffn_bias)
639
+
640
+ self.act_fn = ACT2FN[act_name]
641
+
642
+ def forward(self, x: torch.Tensor, fwd_expert_count: torch.Tensor, **kwargs) -> torch.Tensor:
643
+ if self.is_gated:
644
+ gate_score = self.gate_proj(x, fwd_expert_count)
645
+ up_proj = self.up_proj(x, fwd_expert_count)
646
+ x = up_proj * self.act_fn(gate_score)
647
+ else:
648
+ up_score = self.up_proj(x, fwd_expert_count)
649
+ x = self.act_fn(up_score)
650
+ x = self.down_proj(x, fwd_expert_count)
651
+ return x
652
+
653
+
654
+ class VanillaMoELayer(nn.Module):
655
+ def __init__(self, config: BlockFFNConfig):
656
+ super(VanillaMoELayer, self).__init__()
657
+ self.config = config
658
+
659
+ # Initialize router
660
+ if config.router_type == "topk":
661
+ self.router = TopKRouter(config=self.config)
662
+ elif config.router_type == "remoe":
663
+ self.router = ReMoERouter(config=self.config)
664
+ elif config.router_type == "topp":
665
+ self.router = TopPRouter(config=self.config)
666
+ else:
667
+ raise NotImplementedError(f"Router type {config.router_type} not implemented.")
668
+
669
+ self.mix_calculator = FastTopKCalculator(num_experts=self.config.num_experts)
670
+
671
+ # Initialize experts
672
+ self.experts = MoEGatedExperts(
673
+ dim_in=self.config.hidden_size,
674
+ dim_ff=self.config.moe_ffn_hidden_size,
675
+ is_gated=not self.config.expert_not_gated,
676
+ act_name="silu",
677
+ num_experts=self.config.num_experts,
678
+ )
679
+
680
+ self.dim_shared_expert = self.config.moe_shared_expert_intermediate_size
681
+ self.use_shared_expert = self.dim_shared_expert is not None and self.dim_shared_expert > 0
682
+ if self.use_shared_expert:
683
+ self.shared_experts = BlockFFNMLP(self.config, intermediate_size=self.dim_shared_expert)
684
+
685
+ def forward(self, hidden_states: torch.Tensor):
686
+ top_scores, top_indices = self.router(hidden_states)
687
+ y = self.mix_calculator.forward(
688
+ hidden_states=hidden_states,
689
+ topk_indices=top_indices.contiguous(),
690
+ topk_weights=top_scores.type_as(hidden_states),
691
+ experts=self.experts,
692
+ )
693
+ if self.shared_experts is not None:
694
+ y = y + self.shared_experts(hidden_states)
695
+ return y
696
+
697
+
698
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
699
+ """
700
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
701
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
702
+ """
703
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
704
+ if n_rep == 1:
705
+ return hidden_states
706
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
707
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
708
+
709
+
710
+ def eager_attention_forward(
711
+ module: nn.Module,
712
+ query: torch.Tensor,
713
+ key: torch.Tensor,
714
+ value: torch.Tensor,
715
+ attention_mask: Optional[torch.Tensor],
716
+ scaling: float,
717
+ dropout: float = 0.0,
718
+ ):
719
+ key_states = repeat_kv(key, module.num_key_value_groups)
720
+ value_states = repeat_kv(value, module.num_key_value_groups)
721
+
722
+ attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
723
+ if attention_mask is not None:
724
+ causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
725
+ attn_weights = attn_weights + causal_mask
726
+
727
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
728
+ attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
729
+ attn_output = torch.matmul(attn_weights, value_states)
730
+ attn_output = attn_output.transpose(1, 2).contiguous()
731
+
732
+ return attn_output, attn_weights
733
+
734
+
735
+ class BlockFFNAttention(nn.Module):
736
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
737
+
738
+ def __init__(self, config: BlockFFNConfig, layer_idx: int):
739
+ super().__init__()
740
+ self.config = config
741
+ self.layer_idx = layer_idx
742
+ self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
743
+ self.num_key_value_groups = config.num_attention_heads // config.num_query_groups
744
+ self.scaling = self.head_dim**-0.5
745
+ self.attention_dropout = config.attention_dropout
746
+ self.is_causal = True
747
+
748
+ self.q_proj = nn.Linear(
749
+ config.hidden_size, config.num_attention_heads * self.head_dim, bias=config.attention_bias
750
+ )
751
+ self.k_proj = nn.Linear(
752
+ config.hidden_size, config.num_query_groups * self.head_dim, bias=config.attention_bias
753
+ )
754
+ self.v_proj = nn.Linear(
755
+ config.hidden_size, config.num_query_groups * self.head_dim, bias=config.attention_bias
756
+ )
757
+ self.o_proj = nn.Linear(
758
+ config.num_attention_heads * self.head_dim, config.hidden_size, bias=config.attention_bias
759
+ )
760
+
761
+ def forward(
762
+ self,
763
+ hidden_states: torch.Tensor,
764
+ position_embeddings: tuple[torch.Tensor, torch.Tensor],
765
+ attention_mask: Optional[torch.Tensor],
766
+ past_key_value: Optional[Cache] = None,
767
+ cache_position: Optional[torch.LongTensor] = None,
768
+ **kwargs: Unpack[TransformersKwargs],
769
+ ) -> tuple[torch.Tensor, torch.Tensor]:
770
+ input_shape = hidden_states.shape[:-1]
771
+ hidden_shape = (*input_shape, -1, self.head_dim)
772
+
773
+ query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2)
774
+ key_states = self.k_proj(hidden_states).view(hidden_shape).transpose(1, 2)
775
+ value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
776
+
777
+ cos, sin = position_embeddings
778
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
779
+
780
+ if past_key_value is not None:
781
+ # sin and cos are specific to RoPE models; cache_position needed for the static cache
782
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
783
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
784
+
785
+ attention_interface: Callable = eager_attention_forward
786
+ if self.config._attn_implementation != "eager":
787
+ attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
788
+
789
+ attn_output, attn_weights = attention_interface(
790
+ self,
791
+ query_states,
792
+ key_states,
793
+ value_states,
794
+ attention_mask,
795
+ dropout=0.0 if not self.training else self.attention_dropout,
796
+ scaling=self.scaling,
797
+ **kwargs,
798
+ )
799
+
800
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
801
+ attn_output = self.o_proj(attn_output)
802
+ return attn_output, attn_weights
803
+
804
+
805
+ class BlockFFNDecoderLayer(GradientCheckpointingLayer):
806
+ def __init__(self, config: BlockFFNConfig, layer_idx: int, is_moe_layer: bool):
807
+ super().__init__()
808
+ self.config = config
809
+ self.hidden_size = config.hidden_size
810
+
811
+ self.self_attn = BlockFFNAttention(config=config, layer_idx=layer_idx)
812
+
813
+ if is_moe_layer:
814
+ if config.use_blockffn:
815
+ self.mlp = BlockFFNLayer(config)
816
+ elif config.router_type in ["topk", "remoe", "topp"]:
817
+ self.mlp = VanillaMoELayer(config)
818
+ else:
819
+ raise NotImplementedError
820
+ else:
821
+ self.mlp = BlockFFNMLP(config)
822
+ self.input_layernorm = BlockFFNRMSNorm(config.hidden_size, eps=config.norm_epsilon)
823
+ self.post_attention_layernorm = BlockFFNRMSNorm(config.hidden_size, eps=config.norm_epsilon)
824
+
825
+ def forward(
826
+ self,
827
+ hidden_states: torch.Tensor,
828
+ attention_mask: Optional[torch.Tensor] = None,
829
+ position_ids: Optional[torch.LongTensor] = None,
830
+ past_key_value: Optional[Cache] = None,
831
+ use_cache: Optional[bool] = False,
832
+ cache_position: Optional[torch.LongTensor] = None,
833
+ position_embeddings: Optional[tuple[torch.Tensor, torch.Tensor]] = None, # necessary, but kept here for BC
834
+ **kwargs: Unpack[TransformersKwargs],
835
+ ) -> tuple[torch.Tensor]:
836
+ residual = hidden_states
837
+ hidden_states = self.input_layernorm(hidden_states)
838
+ # Self Attention
839
+ hidden_states, _ = self.self_attn(
840
+ hidden_states=hidden_states,
841
+ attention_mask=attention_mask,
842
+ position_ids=position_ids,
843
+ past_key_value=past_key_value,
844
+ use_cache=use_cache,
845
+ cache_position=cache_position,
846
+ position_embeddings=position_embeddings,
847
+ **kwargs,
848
+ )
849
+ if self.config.use_mup:
850
+ hidden_states = residual + hidden_states * (self.config.mup_depth_scale / math.sqrt(self.config.num_layers))
851
+ else:
852
+ hidden_states = residual + hidden_states
853
+
854
+ # Fully Connected
855
+ residual = hidden_states
856
+ hidden_states = self.post_attention_layernorm(hidden_states)
857
+ hidden_states = self.mlp(hidden_states)
858
+ if self.config.use_mup:
859
+ hidden_states = residual + hidden_states * (self.config.mup_depth_scale / math.sqrt(self.config.num_layers))
860
+ else:
861
+ hidden_states = residual + hidden_states
862
+ return hidden_states
863
+
864
+
865
+ @auto_docstring
866
+ class BlockFFNPreTrainedModel(PreTrainedModel):
867
+ config: BlockFFNConfig
868
+ base_model_prefix = "model"
869
+ supports_gradient_checkpointing = True
870
+ _no_split_modules = ["BlockFFNDecoderLayer"]
871
+ _skip_keys_device_placement = ["past_key_values"]
872
+ _supports_flash_attn = True
873
+ _supports_sdpa = True
874
+ _supports_flex_attn = True
875
+
876
+ _can_compile_fullgraph = True
877
+ _supports_attention_backend = True
878
+ _can_record_outputs = {
879
+ "hidden_states": BlockFFNDecoderLayer,
880
+ "attentions": BlockFFNAttention,
881
+ }
882
+
883
+
884
+ @auto_docstring
885
+ class BlockFFNModel(BlockFFNPreTrainedModel):
886
+ def __init__(self, config: BlockFFNConfig):
887
+ super().__init__(config)
888
+ self.config = config
889
+ self.padding_idx = config.pad_token_id
890
+ self.vocab_size = config.vocab_size
891
+
892
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
893
+ self.moe_layer_freq = eval(config.moe_layer_freq) if isinstance(config.moe_layer_freq, str) else config.moe_layer_freq
894
+ assert len(self.moe_layer_freq) == config.num_layers
895
+ self.layers = nn.ModuleList(
896
+ [BlockFFNDecoderLayer(config, layer_idx, bool(self.moe_layer_freq[layer_idx])) for layer_idx in range(config.num_layers)]
897
+ )
898
+ self.norm = BlockFFNRMSNorm(config.hidden_size, eps=config.norm_epsilon)
899
+ self.rotary_emb = BlockFFNRotaryEmbedding(config=config)
900
+ self.gradient_checkpointing = False
901
+
902
+ # Initialize weights and apply final processing
903
+ self.post_init()
904
+
905
+ @check_model_inputs
906
+ @auto_docstring
907
+ def forward(
908
+ self,
909
+ input_ids: Optional[torch.LongTensor] = None,
910
+ attention_mask: Optional[torch.Tensor] = None,
911
+ position_ids: Optional[torch.LongTensor] = None,
912
+ past_key_values: Optional[Cache] = None,
913
+ inputs_embeds: Optional[torch.FloatTensor] = None,
914
+ cache_position: Optional[torch.LongTensor] = None,
915
+ use_cache: Optional[bool] = None,
916
+ **kwargs: Unpack[TransformersKwargs],
917
+ ) -> BaseModelOutputWithPast:
918
+ if (input_ids is None) ^ (inputs_embeds is not None):
919
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
920
+
921
+ if inputs_embeds is None:
922
+ inputs_embeds: torch.Tensor = self.embed_tokens(input_ids)
923
+ if self.config.use_mup:
924
+ inputs_embeds = inputs_embeds * self.config.mup_emb_scale
925
+
926
+ if use_cache and past_key_values is None:
927
+ past_key_values = DynamicCache()
928
+
929
+ if cache_position is None:
930
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
931
+ cache_position: torch.Tensor = torch.arange(
932
+ past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
933
+ )
934
+
935
+ if position_ids is None:
936
+ position_ids = cache_position.unsqueeze(0)
937
+
938
+ causal_mask = create_causal_mask(
939
+ config=self.config,
940
+ input_embeds=inputs_embeds,
941
+ attention_mask=attention_mask,
942
+ cache_position=cache_position,
943
+ past_key_values=past_key_values,
944
+ position_ids=position_ids,
945
+ )
946
+
947
+ hidden_states = inputs_embeds
948
+ position_embeddings = self.rotary_emb(hidden_states, position_ids)
949
+
950
+ for decoder_layer in self.layers[: self.config.num_layers]:
951
+ hidden_states = decoder_layer(
952
+ hidden_states,
953
+ attention_mask=causal_mask,
954
+ position_ids=position_ids,
955
+ past_key_value=past_key_values,
956
+ cache_position=cache_position,
957
+ position_embeddings=position_embeddings,
958
+ **kwargs,
959
+ )
960
+
961
+ hidden_states = self.norm(hidden_states)
962
+ return BaseModelOutputWithPast(
963
+ last_hidden_state=hidden_states,
964
+ past_key_values=past_key_values,
965
+ )
966
+
967
+
968
+ @auto_docstring
969
+ class BlockFFNForCausalLM(BlockFFNPreTrainedModel, GenerationMixin):
970
+ _tied_weights_keys = ["lm_head.weight"]
971
+ _tp_plan = {"lm_head": "colwise_rep"}
972
+ _pp_plan = {"lm_head": (["hidden_states"], ["logits"])}
973
+
974
+ def __init__(self, config: BlockFFNConfig):
975
+ super().__init__(config)
976
+ self.config = config
977
+ self.model = BlockFFNModel(config)
978
+ self.vocab_size = config.vocab_size
979
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
980
+
981
+ # Initialize weights and apply final processing
982
+ self.post_init()
983
+
984
+ def set_decoder(self, decoder):
985
+ self.model = decoder
986
+
987
+ def get_decoder(self):
988
+ return self.model
989
+
990
+ @can_return_tuple
991
+ @auto_docstring
992
+ def forward(
993
+ self,
994
+ input_ids: Optional[torch.LongTensor] = None,
995
+ attention_mask: Optional[torch.Tensor] = None,
996
+ position_ids: Optional[torch.LongTensor] = None,
997
+ past_key_values: Optional[Cache] = None,
998
+ inputs_embeds: Optional[torch.FloatTensor] = None,
999
+ labels: Optional[torch.LongTensor] = None,
1000
+ use_cache: Optional[bool] = None,
1001
+ cache_position: Optional[torch.LongTensor] = None,
1002
+ logits_to_keep: Union[int, torch.Tensor] = 0,
1003
+ **kwargs: Unpack[TransformersKwargs],
1004
+ ) -> CausalLMOutputWithPast:
1005
+ outputs: BaseModelOutputWithPast = self.model(
1006
+ input_ids=input_ids,
1007
+ attention_mask=attention_mask,
1008
+ position_ids=position_ids,
1009
+ past_key_values=past_key_values,
1010
+ inputs_embeds=inputs_embeds,
1011
+ use_cache=use_cache,
1012
+ cache_position=cache_position,
1013
+ **kwargs,
1014
+ )
1015
+
1016
+ hidden_states = outputs.last_hidden_state
1017
+ if self.config.use_mup:
1018
+ hidden_states = hidden_states / self.config.mup_width_scale
1019
+
1020
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
1021
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
1022
+ logits = self.lm_head(hidden_states[:, slice_indices, :])
1023
+
1024
+ loss = None
1025
+ if labels is not None:
1026
+ loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs)
1027
+
1028
+ return CausalLMOutputWithPast(
1029
+ loss=loss,
1030
+ logits=logits,
1031
+ past_key_values=outputs.past_key_values,
1032
+ hidden_states=outputs.hidden_states,
1033
+ attentions=outputs.attentions,
1034
+ )
1035
+
1036
+ __all__ = [
1037
+ "BlockFFNForCausalLM",
1038
+ "BlockFFNModel",
1039
+ "BlockFFNPreTrainedModel",
1040
+ ]
pytorch_model.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:21d500ba074f2d0d0e202a56c2869c13f554f4fa1348148c22cbb5c012d5b2a3
3
+ size 2901693453
special_tokens_map.json ADDED
@@ -0,0 +1,81 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "additional_special_tokens": [
3
+ {
4
+ "content": "<|im_end|>",
5
+ "lstrip": false,
6
+ "normalized": false,
7
+ "rstrip": false,
8
+ "single_word": false
9
+ },
10
+ {
11
+ "content": "<|im_start|>",
12
+ "lstrip": false,
13
+ "normalized": false,
14
+ "rstrip": false,
15
+ "single_word": false
16
+ },
17
+ {
18
+ "content": "<|tool_call|>",
19
+ "lstrip": false,
20
+ "normalized": false,
21
+ "rstrip": false,
22
+ "single_word": false
23
+ },
24
+ {
25
+ "content": "<|execute_start|>",
26
+ "lstrip": false,
27
+ "normalized": false,
28
+ "rstrip": false,
29
+ "single_word": false
30
+ },
31
+ {
32
+ "content": "<|execute_end|>",
33
+ "lstrip": false,
34
+ "normalized": false,
35
+ "rstrip": false,
36
+ "single_word": false
37
+ },
38
+ {
39
+ "content": "<|fim_prefix|>",
40
+ "lstrip": false,
41
+ "normalized": false,
42
+ "rstrip": false,
43
+ "single_word": false
44
+ },
45
+ {
46
+ "content": "<|fim_middle|>",
47
+ "lstrip": false,
48
+ "normalized": false,
49
+ "rstrip": false,
50
+ "single_word": false
51
+ },
52
+ {
53
+ "content": "<|fim_suffix|>",
54
+ "lstrip": false,
55
+ "normalized": false,
56
+ "rstrip": false,
57
+ "single_word": false
58
+ }
59
+ ],
60
+ "bos_token": {
61
+ "content": "<s>",
62
+ "lstrip": false,
63
+ "normalized": false,
64
+ "rstrip": false,
65
+ "single_word": false
66
+ },
67
+ "eos_token": {
68
+ "content": "</s>",
69
+ "lstrip": false,
70
+ "normalized": false,
71
+ "rstrip": false,
72
+ "single_word": false
73
+ },
74
+ "unk_token": {
75
+ "content": "<unk>",
76
+ "lstrip": false,
77
+ "normalized": false,
78
+ "rstrip": false,
79
+ "single_word": false
80
+ }
81
+ }
tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
tokenizer.model ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:bb74d51116831c3bf65db812c553f94ab0c88dcf97a5bbb37e3504f6d359c530
3
+ size 1181204
tokenizer_config.json ADDED
@@ -0,0 +1,116 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_bos_token": true,
3
+ "add_eos_token": false,
4
+ "added_tokens_decoder": {
5
+ "0": {
6
+ "content": "<unk>",
7
+ "lstrip": false,
8
+ "normalized": false,
9
+ "rstrip": false,
10
+ "single_word": false,
11
+ "special": true
12
+ },
13
+ "1": {
14
+ "content": "<s>",
15
+ "lstrip": false,
16
+ "normalized": false,
17
+ "rstrip": false,
18
+ "single_word": false,
19
+ "special": true
20
+ },
21
+ "2": {
22
+ "content": "</s>",
23
+ "lstrip": false,
24
+ "normalized": false,
25
+ "rstrip": false,
26
+ "single_word": false,
27
+ "special": true
28
+ },
29
+ "73440": {
30
+ "content": "<|im_end|>",
31
+ "lstrip": false,
32
+ "normalized": false,
33
+ "rstrip": false,
34
+ "single_word": false,
35
+ "special": true
36
+ },
37
+ "73441": {
38
+ "content": "<|im_start|>",
39
+ "lstrip": false,
40
+ "normalized": false,
41
+ "rstrip": false,
42
+ "single_word": false,
43
+ "special": true
44
+ },
45
+ "73442": {
46
+ "content": "<|tool_call|>",
47
+ "lstrip": false,
48
+ "normalized": false,
49
+ "rstrip": false,
50
+ "single_word": false,
51
+ "special": true
52
+ },
53
+ "73443": {
54
+ "content": "<|execute_start|>",
55
+ "lstrip": false,
56
+ "normalized": false,
57
+ "rstrip": false,
58
+ "single_word": false,
59
+ "special": true
60
+ },
61
+ "73444": {
62
+ "content": "<|execute_end|>",
63
+ "lstrip": false,
64
+ "normalized": false,
65
+ "rstrip": false,
66
+ "single_word": false,
67
+ "special": true
68
+ },
69
+ "73445": {
70
+ "content": "<|fim_prefix|>",
71
+ "lstrip": false,
72
+ "normalized": false,
73
+ "rstrip": false,
74
+ "single_word": false,
75
+ "special": true
76
+ },
77
+ "73446": {
78
+ "content": "<|fim_middle|>",
79
+ "lstrip": false,
80
+ "normalized": false,
81
+ "rstrip": false,
82
+ "single_word": false,
83
+ "special": true
84
+ },
85
+ "73447": {
86
+ "content": "<|fim_suffix|>",
87
+ "lstrip": false,
88
+ "normalized": false,
89
+ "rstrip": false,
90
+ "single_word": false,
91
+ "special": true
92
+ }
93
+ },
94
+ "additional_special_tokens": [
95
+ "<|im_end|>",
96
+ "<|im_start|>",
97
+ "<|tool_call|>",
98
+ "<|execute_start|>",
99
+ "<|execute_end|>",
100
+ "<|fim_prefix|>",
101
+ "<|fim_middle|>",
102
+ "<|fim_suffix|>"
103
+ ],
104
+ "bos_token": "<s>",
105
+ "clean_up_tokenization_spaces": false,
106
+ "eos_token": "<|im_end|>",
107
+ "legacy": true,
108
+ "model_max_length": 1000000000000000019884624838656,
109
+ "pad_token": null,
110
+ "sp_model_kwargs": {},
111
+ "spaces_between_special_tokens": false,
112
+ "tokenizer_class": "LlamaTokenizer",
113
+ "unk_token": "<unk>",
114
+ "use_default_system_prompt": false,
115
+ "chat_template": "{% for message in messages %}{{'<|im_start|>' + message['role'] + '\n' + message['content'] + '<|im_end|>' + '\n'}}{% endfor %}{% if add_generation_prompt %}{{ '<|im_start|>assistant\n' }}{% endif %}"
116
+ }