Raincleared commited on
Commit
c4c9ae1
·
verified ·
1 Parent(s): 41fb858

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,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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": 1280,
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": 10,
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": 77,
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
+ ],
66
+ "moe_router_dtype": "fp32",
67
+ "router_act_func": "relu",
68
+ "router_norm_type": "simple",
69
+ "expert_act_func": "norm_silu",
70
+ "expert_act_norm_type": "normal",
71
+ "num_layers": 27,
72
+ "ffn_hidden_size": 3360,
73
+ "num_query_groups": 10,
74
+ "norm_epsilon": 1e-05,
75
+ "router_norm_fixed": false,
76
+ "router_norm_scalar": false,
77
+ "router_norm_init_var": 0.1,
78
+ "use_blockffn": true,
79
+ "router_type": "topk",
80
+ "moe_router_enable_expert_bias": false,
81
+ "expert_not_gated": true,
82
+ "moe_router_pre_softmax": false,
83
+ "moe_router_topk": 2,
84
+ "moe_router_topp": 0.5,
85
+ "moe_router_score_function": "softmax",
86
+ "moe_router_topk_scaling_factor": null
87
+ }
configuration_blockffn.py ADDED
@@ -0,0 +1,167 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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_router_score_function="sigmoid",
92
+ moe_router_topk_scaling_factor=2.5,
93
+ expert_not_gated=False,
94
+ moe_router_pre_softmax=False,
95
+ **kwargs,
96
+ ):
97
+ self.vocab_size = vocab_size
98
+ self.max_position_embeddings = max_position_embeddings
99
+ self.hidden_size = hidden_size
100
+ self.ffn_hidden_size = ffn_hidden_size
101
+ self.num_layers = num_layers
102
+ self.num_attention_heads = num_attention_heads
103
+
104
+ # for backward compatibility
105
+ if num_query_groups is None:
106
+ num_query_groups = num_attention_heads
107
+
108
+ self.num_query_groups = num_query_groups
109
+ self.hidden_act = hidden_act
110
+ self.initializer_range = initializer_range
111
+ self.norm_epsilon = norm_epsilon
112
+ self.pretraining_tp = pretraining_tp
113
+ self.use_cache = use_cache
114
+ self.rope_theta = rope_theta
115
+ self.rope_scaling = rope_scaling
116
+ self.attention_bias = attention_bias
117
+ self.attention_dropout = attention_dropout
118
+ self.mlp_bias = mlp_bias
119
+ self.head_dim = head_dim if head_dim is not None else self.hidden_size // self.num_attention_heads
120
+ self.use_mup = use_mup
121
+ self.mup_emb_scale = mup_emb_scale
122
+ self.mup_depth_scale = mup_depth_scale
123
+ self.mup_base_hidden_size = mup_base_hidden_size
124
+
125
+ self.num_experts = num_experts
126
+ self.moe_ffn_hidden_size = moe_ffn_hidden_size
127
+ self.moe_shared_expert_intermediate_size = moe_shared_expert_intermediate_size
128
+ self.moe_layer_freq = moe_layer_freq if isinstance(moe_layer_freq, (str, list)) else ([0] * num_layers)
129
+ self.moe_router_dtype = moe_router_dtype
130
+ self.router_act_func = router_act_func
131
+ self.router_norm_type = router_norm_type
132
+ self.router_norm_fixed = router_norm_fixed
133
+ self.router_norm_scalar = router_norm_scalar
134
+ self.router_norm_init_var = router_norm_init_var
135
+ self.expert_act_func = expert_act_func
136
+ self.expert_act_norm_type = expert_act_norm_type
137
+
138
+ self.use_blockffn = use_blockffn
139
+ self.router_type = router_type
140
+ self.moe_router_topk = moe_router_topk
141
+ self.moe_router_topp = moe_router_topp
142
+ self.moe_router_enable_expert_bias = moe_router_enable_expert_bias
143
+ self.moe_router_score_function = moe_router_score_function
144
+ self.moe_router_topk_scaling_factor = moe_router_topk_scaling_factor
145
+ self.expert_not_gated = expert_not_gated
146
+ self.moe_router_pre_softmax = moe_router_pre_softmax
147
+
148
+ # Validate the correctness of rotary position embeddings parameters
149
+ # BC: if there is a 'type' field, copy it it to 'rope_type'.
150
+ if self.rope_scaling is not None and "type" in self.rope_scaling:
151
+ self.rope_scaling["rope_type"] = self.rope_scaling["type"]
152
+ rope_config_validation(self)
153
+
154
+ super().__init__(
155
+ pad_token_id=pad_token_id,
156
+ bos_token_id=bos_token_id,
157
+ eos_token_id=eos_token_id,
158
+ tie_word_embeddings=tie_word_embeddings,
159
+ **kwargs,
160
+ )
161
+
162
+ @property
163
+ def mup_width_scale(self):
164
+ return (self.hidden_size / self.mup_base_hidden_size) if (self.use_mup and self.mup_base_hidden_size > 0) else 1
165
+
166
+
167
+ __all__ = ["BlockFFNConfig"]
evaluation.log ADDED
The diff for this file is too large to render. See raw diff
 
evaluation/results__hf_ckpts__blockffn_05b_mul1001_withmean_d64_s128_lr78e4_b256__/results_2026-01-25T01-55-39.634755.json ADDED
@@ -0,0 +1,609 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "results": {
3
+ "arc_challenge": {
4
+ "alias": "arc_challenge",
5
+ "acc,none": 0.25426621160409557,
6
+ "acc_stderr,none": 0.012724999945157755,
7
+ "acc_norm,none": 0.2764505119453925,
8
+ "acc_norm_stderr,none": 0.013069662474252427
9
+ },
10
+ "arc_easy": {
11
+ "alias": "arc_easy",
12
+ "acc,none": 0.5711279461279462,
13
+ "acc_stderr,none": 0.010155440652900152,
14
+ "acc_norm,none": 0.5008417508417509,
15
+ "acc_norm_stderr,none": 0.01025976898181524
16
+ },
17
+ "boolq": {
18
+ "alias": "boolq",
19
+ "acc,none": 0.5892966360856269,
20
+ "acc_stderr,none": 0.008604460608471415
21
+ },
22
+ "hellaswag": {
23
+ "alias": "hellaswag",
24
+ "acc,none": 0.327823142800239,
25
+ "acc_stderr,none": 0.0046846063106423365,
26
+ "acc_norm,none": 0.39026090420235016,
27
+ "acc_norm_stderr,none": 0.004868117598481953
28
+ },
29
+ "lambada_openai": {
30
+ "alias": "lambada_openai",
31
+ "perplexity,none": 33.34233644657029,
32
+ "perplexity_stderr,none": 1.2310484101964607,
33
+ "acc,none": 0.3407723656122647,
34
+ "acc_stderr,none": 0.0066033141566029605
35
+ },
36
+ "lambada_standard": {
37
+ "alias": "lambada_standard",
38
+ "perplexity,none": 80.75969362338128,
39
+ "perplexity_stderr,none": 3.2201488781306558,
40
+ "acc,none": 0.2549970890743256,
41
+ "acc_stderr,none": 0.006072376194465698
42
+ },
43
+ "piqa": {
44
+ "alias": "piqa",
45
+ "acc,none": 0.6594124047878128,
46
+ "acc_stderr,none": 0.011057027540404739,
47
+ "acc_norm,none": 0.6610446137105549,
48
+ "acc_norm_stderr,none": 0.011044144419710637
49
+ },
50
+ "social_iqa": {
51
+ "alias": "social_iqa",
52
+ "acc,none": 0.3961105424769703,
53
+ "acc_stderr,none": 0.011067150171168508
54
+ },
55
+ "wikitext": {
56
+ "alias": "wikitext",
57
+ "word_perplexity,none": 28.10252377406155,
58
+ "word_perplexity_stderr,none": "N/A",
59
+ "byte_perplexity,none": 1.8660471691374998,
60
+ "byte_perplexity_stderr,none": "N/A",
61
+ "bits_per_byte,none": 0.899985454475132,
62
+ "bits_per_byte_stderr,none": "N/A"
63
+ },
64
+ "winogrande": {
65
+ "alias": "winogrande",
66
+ "acc,none": 0.5327545382794001,
67
+ "acc_stderr,none": 0.014022300570434139
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_05b_mul1001_withmean_d64_s128_lr78e4_b256/",
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_05b_mul1001_withmean_d64_s128_lr78e4_b256/",
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_05b_mul1001_withmean_d64_s128_lr78e4_b256/",
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_05b_mul1001_withmean_d64_s128_lr78e4_b256/",
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_05b_mul1001_withmean_d64_s128_lr78e4_b256/",
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_05b_mul1001_withmean_d64_s128_lr78e4_b256/",
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_05b_mul1001_withmean_d64_s128_lr78e4_b256/",
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_05b_mul1001_withmean_d64_s128_lr78e4_b256/",
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_05b_mul1001_withmean_d64_s128_lr78e4_b256/",
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_05b_mul1001_withmean_d64_s128_lr78e4_b256/",
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_05b_mul1001_withmean_d64_s128_lr78e4_b256/,dtype=bfloat16,trust_remote_code=True,trust_remote_code=True",
561
+ "model_num_parameters": 721300306,
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-112-g2361e6340",
578
+ "date": 1769276962.57087,
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: Ubuntu 22.04.4 LTS (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.35\n\nPython version: 3.10.14 (main, May 6 2024, 19:42:50) [GCC 11.2.0] (64-bit runtime)\nPython platform: Linux-6.5.0-18-generic-x86_64-with-glibc2.35\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: 550.54.15\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\nAddress sizes: 52 bits physical, 57 bits virtual\nByte Order: Little Endian\nCPU(s): 104\nOn-line CPU(s) list: 0-103\nVendor ID: GenuineIntel\nModel name: Intel(R) Xeon(R) Platinum 8470\nCPU family: 6\nModel: 143\nThread(s) per core: 1\nCore(s) per socket: 52\nSocket(s): 2\nStepping: 8\nCPU max MHz: 3800.0000\nCPU min MHz: 800.0000\nBogoMIPS: 4000.00\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 cpuid aperfmperf tsc_known_freq 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 cpuid_fault epb cat_l3 cat_l2 cdp_l3 invpcid_single intel_ppin cdp_l2 ssbd mba ibrs ibpb stibp ibrs_enhanced tpr_shadow flexpriority ept vpid ept_ad fsgsbase tsc_adjust bmi1 avx2 smep bmi2 erms invpcid cqm rdt_a avx512f avx512dq rdseed adx smap avx512ifma clflushopt clwb intel_pt avx512cd sha_ni avx512bw avx512vl xsaveopt xsavec xgetbv1 xsaves cqm_llc cqm_occup_llc cqm_mbm_total cqm_mbm_local split_lock_detect avx_vnni avx512_bf16 wbnoinvd dtherm ida arat pln pts hwp hwp_act_window hwp_epp hwp_pkg_req vnmi avx512vbmi umip pku ospke waitpkg avx512_vbmi2 gfni vaes vpclmulqdq avx512_vnni avx512_bitalg tme avx512_vpopcntdq la57 rdpid bus_lock_detect cldemote movdiri movdir64b enqcmd fsrm md_clear serialize tsxldtrk pconfig arch_lbr ibt amx_bf16 avx512_fp16 amx_tile amx_int8 flush_l1d arch_capabilities\nVirtualization: VT-x\nL1d cache: 4.9 MiB (104 instances)\nL1i cache: 3.3 MiB (104 instances)\nL2 cache: 208 MiB (104 instances)\nL3 cache: 210 MiB (2 instances)\nNUMA node(s): 2\nNUMA node0 CPU(s): 0-51\nNUMA node1 CPU(s): 52-103\nVulnerability Gather data sampling: Not affected\nVulnerability Itlb multihit: Not affected\nVulnerability L1tf: Not affected\nVulnerability Mds: Not affected\nVulnerability Meltdown: Not affected\nVulnerability Mmio stale data: Not affected\nVulnerability Retbleed: Not affected\nVulnerability Spec rstack overflow: Not affected\nVulnerability Spec store bypass: Mitigation; Speculative Store Bypass disabled via prctl\nVulnerability Spectre v1: Mitigation; usercopy/swapgs barriers and __user pointer sanitization\nVulnerability Spectre v2: Mitigation; Enhanced / Automatic IBRS, IBPB conditional, RSB filling, PBRSB-eIBRS SW sequence\nVulnerability Srbds: Not affected\nVulnerability Tsx async abort: Not affected\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_05b_mul1001_withmean_d64_s128_lr78e4_b256/",
600
+ "model_name_sanitized": "results__hf_ckpts__blockffn_05b_mul1001_withmean_d64_s128_lr78e4_b256__",
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": 117422.270613087,
607
+ "end_time": 117903.896989432,
608
+ "total_evaluation_time_seconds": "481.62637634499697"
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,1020 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ def forward(self, hidden_states: torch.Tensor):
252
+ ori_shape = hidden_states.shape
253
+ hidden_states = hidden_states.view(-1, self.hidden_size)
254
+ seq_len = hidden_states.shape[0]
255
+
256
+ # router module forward
257
+ raw_router_score = self.moe_router(hidden_states) # [seq_len, num_experts]
258
+ router_score = self.router_act(raw_router_score)
259
+ router_score = self.router_norm(router_score)
260
+
261
+ # expert module forward
262
+ x_in = self.expert_up_proj(hidden_states) # [seq_len, num_experts * dim_expert]
263
+ if self.expert_gated:
264
+ x_gate = self.expert_gate_proj(hidden_states)
265
+ x_gate = self.expert_act(x_gate)
266
+ if x_gate.ndim == 3:
267
+ x_in = x_in.view(seq_len, self.num_experts, self.dim_expert)
268
+ x_in = x_in * x_gate
269
+ else:
270
+ x_in = self.expert_act(x_in)
271
+ if x_in.ndim == 3:
272
+ scored_x_in = x_in * router_score.type_as(hidden_states).unsqueeze(-1)
273
+ else:
274
+ scored_x_in = x_in.view(seq_len, self.num_experts, self.dim_expert) * router_score.type_as(hidden_states).unsqueeze(-1)
275
+ output = self.expert_down_proj(scored_x_in.view(seq_len, self.num_experts * self.dim_expert))
276
+
277
+ if self.use_shared_expert:
278
+ output = output + self.shared_experts(hidden_states)
279
+ return output.view(*ori_shape)
280
+
281
+
282
+ class BaseRouter(ABC, nn.Module):
283
+ """Base Router class"""
284
+ def __init__(self, config: BlockFFNConfig) -> None:
285
+ super().__init__()
286
+ self.config = config
287
+ self.num_experts = self.config.num_experts
288
+
289
+ if self.config.moe_router_dtype == "fp32":
290
+ self.router_dtype = torch.float32
291
+ elif self.config.moe_router_dtype == "fp64":
292
+ self.router_dtype = torch.float64
293
+ elif self.config.moe_router_dtype == "bf16":
294
+ self.router_dtype = torch.bfloat16
295
+ else:
296
+ raise NotImplementedError(f"{self.config.moe_router_dtype} is not supported.")
297
+
298
+ self.weight = torch.nn.Parameter(
299
+ torch.empty((self.num_experts, self.config.hidden_size), dtype=self.router_dtype)
300
+ )
301
+
302
+ def gating(self, input: torch.Tensor):
303
+ return torch.nn.functional.linear(input.to(self.router_dtype), self.weight.to(self.router_dtype))
304
+
305
+ @abstractmethod
306
+ def routing(self, logits: torch.Tensor):
307
+ """Routing function.
308
+
309
+ Args:
310
+ logits (torch.Tensor): Logits tensor.
311
+
312
+ Returns:
313
+ Tuple[torch.Tensor, torch.Tensor]: A tuple containing token assignment
314
+ probabilities and mapping.
315
+ """
316
+ raise NotImplementedError("Routing function not implemented.")
317
+
318
+ @abstractmethod
319
+ def forward(self, input: torch.Tensor):
320
+ """
321
+ Forward pass of the router.
322
+
323
+ Args:
324
+ input (torch.Tensor): Input tensor.
325
+ """
326
+ raise NotImplementedError("Forward function not implemented.")
327
+
328
+
329
+ class TopKRouter(BaseRouter):
330
+ """Route each token to the top-k experts."""
331
+
332
+ def __init__(self, config: BlockFFNConfig) -> None:
333
+ super().__init__(config)
334
+ self.config = config
335
+ self.topk = self.config.moe_router_topk
336
+ self.score_function = self.config.moe_router_score_function
337
+ self.use_pre_softmax = self.config.moe_router_pre_softmax
338
+ self.scaling_factor = self.config.moe_router_topk_scaling_factor
339
+
340
+ self.enable_expert_bias = self.config.moe_router_enable_expert_bias
341
+ if self.enable_expert_bias:
342
+ self.expert_bias = torch.nn.Parameter(torch.zeros(self.num_experts, dtype=torch.float32))
343
+ else:
344
+ self.expert_bias = None
345
+
346
+ def _maintain_float32_expert_bias(self):
347
+ """
348
+ Maintain the expert bias in float32.
349
+
350
+ When using bf16/fp16, the expert bias gets converted to lower precision in Float16Module.
351
+ We keep it in float32 to avoid routing errors when updating the expert_bias.
352
+ """
353
+ if hasattr(self, 'expert_bias') and self.expert_bias is not None:
354
+ if self.expert_bias.dtype != torch.float32:
355
+ self.expert_bias.data = self.expert_bias.data.to(torch.float32)
356
+
357
+ def routing(self, logits: torch.Tensor):
358
+ """Top-k routing function
359
+
360
+ Args:
361
+ logits (torch.Tensor): Logits tensor after gating.
362
+
363
+ Returns:
364
+ probs (torch.Tensor): The probabilities of token to experts assignment.
365
+ routing_map (torch.Tensor): The mapping of token to experts assignment,
366
+ with shape [num_tokens, num_experts].
367
+ """
368
+ logits = logits.view(-1, self.num_experts)
369
+
370
+ if self.score_function == "softmax":
371
+ if self.use_pre_softmax:
372
+ scores = torch.softmax(logits, dim=-1, dtype=torch.float32).type_as(logits)
373
+ probs, top_indices = torch.topk(scores, k=self.topk, dim=1)
374
+ else:
375
+ scores, top_indices = torch.topk(logits, k=self.topk, dim=1)
376
+ probs = torch.softmax(scores, dim=-1, dtype=torch.float32).type_as(logits)
377
+ elif self.score_function == "sigmoid":
378
+ scores = torch.sigmoid(logits.float()).type_as(logits)
379
+ if self.expert_bias is not None:
380
+ scores_for_routing = scores + self.expert_bias
381
+ _, top_indices = torch.topk(scores_for_routing, k=self.topk, dim=1)
382
+ scores = torch.gather(scores, dim=1, index=top_indices).type_as(logits)
383
+ else:
384
+ scores, top_indices = torch.topk(scores, k=self.topk, dim=1)
385
+ probs = scores / (scores.sum(dim=-1, keepdim=True) + 1e-20) if self.topk > 1 else scores
386
+ else:
387
+ raise ValueError(f"Invalid score_function: {self.score_function}")
388
+
389
+ if self.scaling_factor:
390
+ probs = probs * self.scaling_factor
391
+
392
+ return probs, top_indices
393
+
394
+ def forward(self, input: torch.Tensor):
395
+ """
396
+ Forward pass of the router.
397
+
398
+ Args:
399
+ input (torch.Tensor): Input tensor.
400
+ """
401
+ self._maintain_float32_expert_bias()
402
+ logits = self.gating(input)
403
+ top_scores, top_indices = self.routing(logits)
404
+ return top_scores, top_indices
405
+
406
+
407
+ class ReMoERouter(BaseRouter):
408
+ def __init__(self, config: BlockFFNConfig) -> None:
409
+ super().__init__(config)
410
+ self.config = config
411
+ self.router_act = torch.nn.ReLU()
412
+
413
+ def routing(self, logits: torch.Tensor):
414
+ """Top-k routing function
415
+
416
+ Args:
417
+ logits (torch.Tensor): Logits tensor after gating.
418
+
419
+ Returns:
420
+ probs (torch.Tensor): The probabilities of token to experts assignment.
421
+ routing_map (torch.Tensor): The mapping of token to experts assignment,
422
+ with shape [num_tokens, num_experts].
423
+ """
424
+ logits = logits.view(-1, self.num_experts)
425
+
426
+ router_score = self.router_act(logits)
427
+ routing_map = router_score > 0
428
+
429
+ sorted_probs, sorted_indices = torch.sort(router_score, descending=True, dim=-1)
430
+ sorted_map = sorted_probs <= 0
431
+ sorted_indices = torch.where(sorted_map, -1, sorted_indices)
432
+ max_valid_num = max(sorted_probs.size(-1) - torch.min(torch.sum(sorted_map, dim=-1)).item(), 1)
433
+ assert torch.all(sorted_map[:, max_valid_num:])
434
+ sorted_probs = sorted_probs[:, :max_valid_num]
435
+ sorted_indices = sorted_indices[:, :max_valid_num]
436
+ assert torch.sum(routing_map) == torch.sum(sorted_indices != -1)
437
+ return sorted_probs, sorted_indices
438
+
439
+ def forward(self, input: torch.Tensor):
440
+ """
441
+ Forward pass of the router.
442
+
443
+ Args:
444
+ input (torch.Tensor): Input tensor.
445
+ """
446
+ logits = self.gating(input)
447
+ top_scores, top_indices = self.routing(logits)
448
+ return top_scores, top_indices
449
+
450
+
451
+ class TopPRouter(BaseRouter):
452
+ def __init__(self, config: BlockFFNConfig) -> None:
453
+ super().__init__(config)
454
+ self.config = config
455
+ self.top_p = config.moe_router_topp
456
+
457
+ def routing(self, logits: torch.Tensor):
458
+ """Top-k routing function
459
+
460
+ Args:
461
+ logits (torch.Tensor): Logits tensor after gating.
462
+
463
+ Returns:
464
+ probs (torch.Tensor): The probabilities of token to experts assignment.
465
+ routing_map (torch.Tensor): The mapping of token to experts assignment,
466
+ with shape [num_tokens, num_experts].
467
+ """
468
+ logits = logits.view(-1, self.num_experts)
469
+
470
+ router_score = torch.abs(logits)
471
+ router_score = router_score / (router_score.sum(dim=-1, keepdim=True) + 1e-20)
472
+
473
+ sorted_probs, sorted_indices = torch.sort(router_score, descending=True, dim=-1)
474
+ cumulative_probs = torch.cumsum(sorted_probs, dim=-1)
475
+ mask = cumulative_probs > self.top_p
476
+
477
+ threshold_indices = mask.long().argmax(dim=-1)
478
+ threshold_mask = torch.nn.functional.one_hot(threshold_indices, num_classes=sorted_indices.size(-1)).bool()
479
+
480
+ mask = mask & ~threshold_mask
481
+ sorted_indices = torch.where(mask, -1, sorted_indices)
482
+ sorted_probs = torch.where(mask, 0.0, sorted_probs)
483
+
484
+ max_valid_num = max(mask.size(-1) - torch.min(torch.sum(mask, dim=-1)).item(), 1)
485
+ assert torch.all(mask[:, max_valid_num:])
486
+
487
+ sorted_indices = sorted_indices[:, :max_valid_num]
488
+ sorted_probs = sorted_probs[:, :max_valid_num]
489
+ sorted_probs = sorted_probs / sorted_probs.sum(dim=-1, keepdim=True)
490
+ return sorted_probs, sorted_indices
491
+
492
+ def forward(self, input: torch.Tensor):
493
+ """
494
+ Forward pass of the router.
495
+
496
+ Args:
497
+ input (torch.Tensor): Input tensor.
498
+ """
499
+ logits = self.gating(input)
500
+ top_scores, top_indices = self.routing(logits)
501
+ return top_scores, top_indices
502
+
503
+
504
+ class FastTopKCalculator:
505
+ def __init__(self, num_experts: int):
506
+ self.num_experts = num_experts
507
+
508
+ def fmoe_sparse_topk_forward(self, hidden_states: torch.Tensor, topk_indices: torch.Tensor, experts: torch.nn.Module):
509
+ (
510
+ pos,
511
+ local_expert_count,
512
+ global_expert_count,
513
+ fwd_expert_count,
514
+ fwd_batch_size,
515
+ ) = prepare_forward(topk_indices, self.num_experts, 1)
516
+ topk = 1
517
+ if len(topk_indices.shape) == 2:
518
+ topk = topk_indices.shape[1]
519
+
520
+ def scatter_func(tensor):
521
+ return MOEScatter.apply(
522
+ tensor,
523
+ torch.div(pos, topk, rounding_mode='floor'),
524
+ local_expert_count,
525
+ global_expert_count,
526
+ fwd_batch_size,
527
+ 1,
528
+ )
529
+
530
+ x = tree.map_structure(scatter_func, hidden_states)
531
+ x = experts(x, fwd_expert_count, topk_indices=topk_indices)
532
+
533
+ out_batch_size = tree.flatten(hidden_states)[0].shape[0]
534
+ if len(topk_indices.shape) == 2:
535
+ out_batch_size *= topk_indices.shape[1]
536
+
537
+ def gather_func(tensor):
538
+ return MOEGather.apply(
539
+ tensor,
540
+ pos,
541
+ local_expert_count,
542
+ global_expert_count,
543
+ out_batch_size,
544
+ 1,
545
+ )
546
+
547
+ outp = tree.map_structure(gather_func, x)
548
+ return outp
549
+
550
+ def forward(self, hidden_states, topk_indices, topk_weights, experts):
551
+ assert topk_indices.shape == topk_weights.shape
552
+ top_k = topk_indices.shape[-1]
553
+ dim3 = hidden_states.ndim == 3
554
+ if dim3:
555
+ batch_size, seq_len, dim = hidden_states.shape
556
+ hidden_states = hidden_states.view(batch_size * seq_len, dim)
557
+ else:
558
+ assert hidden_states.ndim == 2
559
+ batch_size, (seq_len, dim) = -1, hidden_states.shape
560
+ fwd = self.fmoe_sparse_topk_forward(hidden_states, topk_indices, experts)
561
+
562
+ def view_func(tensor):
563
+ n_dim = tensor.shape[-1]
564
+ tensor = tensor.view(-1, top_k, n_dim)
565
+ return tensor
566
+
567
+ moe_output = tree.map_structure(view_func, fwd)
568
+ topk_weights = topk_weights.unsqueeze(1)
569
+
570
+ def bmm_func(tensor):
571
+ n_dim = tensor.shape[-1]
572
+ tensor = torch.bmm(topk_weights, tensor).reshape(-1, n_dim)
573
+ return tensor
574
+
575
+ moe_output = tree.map_structure(bmm_func, moe_output)
576
+ if dim3:
577
+ moe_output = moe_output.view(batch_size, seq_len, -1)
578
+ return moe_output
579
+
580
+
581
+ class MoELinearExperts(nn.Module):
582
+ def __init__(
583
+ self,
584
+ dim_in: int,
585
+ dim_out: int,
586
+ num_experts: int,
587
+ ffn_bias: bool,
588
+ ):
589
+ super().__init__()
590
+ self.dim_in = self.in_features = dim_in
591
+ self.dim_out = self.out_features = dim_out
592
+ self.weight = torch.nn.Parameter(torch.empty(num_experts, dim_out, dim_in))
593
+ self.bias = None
594
+ if ffn_bias:
595
+ self.bias = torch.nn.Parameter(torch.empty(num_experts, dim_out))
596
+
597
+ def forward(self, x: torch.Tensor, fwd_expert_count: torch.Tensor):
598
+ x = MOELinear.apply(x, fwd_expert_count, self.weight, self.bias)
599
+ return x
600
+
601
+
602
+ class MoEGatedExperts(nn.Module):
603
+ def __init__(
604
+ self,
605
+ dim_in: int,
606
+ dim_ff: int,
607
+ is_gated: bool,
608
+ act_name: str,
609
+ num_experts: int,
610
+ ffn_bias: bool = False,
611
+ ):
612
+ super().__init__()
613
+ self.is_gated = is_gated
614
+ self.dim_in, self.dim_ff, self.num_experts = dim_in, dim_ff, num_experts
615
+ if self.is_gated:
616
+ self.gate_proj = MoELinearExperts(dim_in, dim_ff, num_experts, ffn_bias)
617
+ self.up_proj = MoELinearExperts(dim_in, dim_ff, num_experts, ffn_bias)
618
+ self.down_proj = MoELinearExperts(dim_ff, dim_in, num_experts, ffn_bias)
619
+
620
+ self.act_fn = ACT2FN[act_name]
621
+
622
+ def forward(self, x: torch.Tensor, fwd_expert_count: torch.Tensor, **kwargs) -> torch.Tensor:
623
+ if self.is_gated:
624
+ gate_score = self.gate_proj(x, fwd_expert_count)
625
+ up_proj = self.up_proj(x, fwd_expert_count)
626
+ x = up_proj * self.act_fn(gate_score)
627
+ else:
628
+ up_score = self.up_proj(x, fwd_expert_count)
629
+ x = self.act_fn(up_score)
630
+ x = self.down_proj(x, fwd_expert_count)
631
+ return x
632
+
633
+
634
+ class VanillaMoELayer(nn.Module):
635
+ def __init__(self, config: BlockFFNConfig):
636
+ super(VanillaMoELayer, self).__init__()
637
+ self.config = config
638
+
639
+ # Initialize router
640
+ if config.router_type == "topk":
641
+ self.router = TopKRouter(config=self.config)
642
+ elif config.router_type == "remoe":
643
+ self.router = ReMoERouter(config=self.config)
644
+ elif config.router_type == "topp":
645
+ self.router = TopPRouter(config=self.config)
646
+ else:
647
+ raise NotImplementedError(f"Router type {config.router_type} not implemented.")
648
+
649
+ self.mix_calculator = FastTopKCalculator(num_experts=self.config.num_experts)
650
+
651
+ # Initialize experts
652
+ self.experts = MoEGatedExperts(
653
+ dim_in=self.config.hidden_size,
654
+ dim_ff=self.config.moe_ffn_hidden_size,
655
+ is_gated=not self.config.expert_not_gated,
656
+ act_name="silu",
657
+ num_experts=self.config.num_experts,
658
+ )
659
+
660
+ self.dim_shared_expert = self.config.moe_shared_expert_intermediate_size
661
+ self.use_shared_expert = self.dim_shared_expert is not None and self.dim_shared_expert > 0
662
+ if self.use_shared_expert:
663
+ self.shared_experts = BlockFFNMLP(self.config, intermediate_size=self.dim_shared_expert)
664
+
665
+ def forward(self, hidden_states: torch.Tensor):
666
+ top_scores, top_indices = self.router(hidden_states)
667
+ y = self.mix_calculator.forward(
668
+ hidden_states=hidden_states,
669
+ topk_indices=top_indices.contiguous(),
670
+ topk_weights=top_scores.type_as(hidden_states),
671
+ experts=self.experts,
672
+ )
673
+ if self.shared_experts is not None:
674
+ y = y + self.shared_experts(hidden_states)
675
+ return y
676
+
677
+
678
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
679
+ """
680
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
681
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
682
+ """
683
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
684
+ if n_rep == 1:
685
+ return hidden_states
686
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
687
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
688
+
689
+
690
+ def eager_attention_forward(
691
+ module: nn.Module,
692
+ query: torch.Tensor,
693
+ key: torch.Tensor,
694
+ value: torch.Tensor,
695
+ attention_mask: Optional[torch.Tensor],
696
+ scaling: float,
697
+ dropout: float = 0.0,
698
+ ):
699
+ key_states = repeat_kv(key, module.num_key_value_groups)
700
+ value_states = repeat_kv(value, module.num_key_value_groups)
701
+
702
+ attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
703
+ if attention_mask is not None:
704
+ causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
705
+ attn_weights = attn_weights + causal_mask
706
+
707
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
708
+ attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
709
+ attn_output = torch.matmul(attn_weights, value_states)
710
+ attn_output = attn_output.transpose(1, 2).contiguous()
711
+
712
+ return attn_output, attn_weights
713
+
714
+
715
+ class BlockFFNAttention(nn.Module):
716
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
717
+
718
+ def __init__(self, config: BlockFFNConfig, layer_idx: int):
719
+ super().__init__()
720
+ self.config = config
721
+ self.layer_idx = layer_idx
722
+ self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
723
+ self.num_key_value_groups = config.num_attention_heads // config.num_query_groups
724
+ self.scaling = self.head_dim**-0.5
725
+ self.attention_dropout = config.attention_dropout
726
+ self.is_causal = True
727
+
728
+ self.q_proj = nn.Linear(
729
+ config.hidden_size, config.num_attention_heads * self.head_dim, bias=config.attention_bias
730
+ )
731
+ self.k_proj = nn.Linear(
732
+ config.hidden_size, config.num_query_groups * self.head_dim, bias=config.attention_bias
733
+ )
734
+ self.v_proj = nn.Linear(
735
+ config.hidden_size, config.num_query_groups * self.head_dim, bias=config.attention_bias
736
+ )
737
+ self.o_proj = nn.Linear(
738
+ config.num_attention_heads * self.head_dim, config.hidden_size, bias=config.attention_bias
739
+ )
740
+
741
+ def forward(
742
+ self,
743
+ hidden_states: torch.Tensor,
744
+ position_embeddings: tuple[torch.Tensor, torch.Tensor],
745
+ attention_mask: Optional[torch.Tensor],
746
+ past_key_value: Optional[Cache] = None,
747
+ cache_position: Optional[torch.LongTensor] = None,
748
+ **kwargs: Unpack[TransformersKwargs],
749
+ ) -> tuple[torch.Tensor, torch.Tensor]:
750
+ input_shape = hidden_states.shape[:-1]
751
+ hidden_shape = (*input_shape, -1, self.head_dim)
752
+
753
+ query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2)
754
+ key_states = self.k_proj(hidden_states).view(hidden_shape).transpose(1, 2)
755
+ value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
756
+
757
+ cos, sin = position_embeddings
758
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
759
+
760
+ if past_key_value is not None:
761
+ # sin and cos are specific to RoPE models; cache_position needed for the static cache
762
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
763
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
764
+
765
+ attention_interface: Callable = eager_attention_forward
766
+ if self.config._attn_implementation != "eager":
767
+ attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
768
+
769
+ attn_output, attn_weights = attention_interface(
770
+ self,
771
+ query_states,
772
+ key_states,
773
+ value_states,
774
+ attention_mask,
775
+ dropout=0.0 if not self.training else self.attention_dropout,
776
+ scaling=self.scaling,
777
+ **kwargs,
778
+ )
779
+
780
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
781
+ attn_output = self.o_proj(attn_output)
782
+ return attn_output, attn_weights
783
+
784
+
785
+ class BlockFFNDecoderLayer(GradientCheckpointingLayer):
786
+ def __init__(self, config: BlockFFNConfig, layer_idx: int, is_moe_layer: bool):
787
+ super().__init__()
788
+ self.config = config
789
+ self.hidden_size = config.hidden_size
790
+
791
+ self.self_attn = BlockFFNAttention(config=config, layer_idx=layer_idx)
792
+
793
+ if is_moe_layer:
794
+ if config.use_blockffn:
795
+ self.mlp = BlockFFNLayer(config)
796
+ elif config.router_type in ["topk", "remoe", "topp"]:
797
+ self.mlp = VanillaMoELayer(config)
798
+ else:
799
+ raise NotImplementedError
800
+ else:
801
+ self.mlp = BlockFFNMLP(config)
802
+ self.input_layernorm = BlockFFNRMSNorm(config.hidden_size, eps=config.norm_epsilon)
803
+ self.post_attention_layernorm = BlockFFNRMSNorm(config.hidden_size, eps=config.norm_epsilon)
804
+
805
+ def forward(
806
+ self,
807
+ hidden_states: torch.Tensor,
808
+ attention_mask: Optional[torch.Tensor] = None,
809
+ position_ids: Optional[torch.LongTensor] = None,
810
+ past_key_value: Optional[Cache] = None,
811
+ use_cache: Optional[bool] = False,
812
+ cache_position: Optional[torch.LongTensor] = None,
813
+ position_embeddings: Optional[tuple[torch.Tensor, torch.Tensor]] = None, # necessary, but kept here for BC
814
+ **kwargs: Unpack[TransformersKwargs],
815
+ ) -> tuple[torch.Tensor]:
816
+ residual = hidden_states
817
+ hidden_states = self.input_layernorm(hidden_states)
818
+ # Self Attention
819
+ hidden_states, _ = self.self_attn(
820
+ hidden_states=hidden_states,
821
+ attention_mask=attention_mask,
822
+ position_ids=position_ids,
823
+ past_key_value=past_key_value,
824
+ use_cache=use_cache,
825
+ cache_position=cache_position,
826
+ position_embeddings=position_embeddings,
827
+ **kwargs,
828
+ )
829
+ if self.config.use_mup:
830
+ hidden_states = residual + hidden_states * (self.config.mup_depth_scale / math.sqrt(self.config.num_layers))
831
+ else:
832
+ hidden_states = residual + hidden_states
833
+
834
+ # Fully Connected
835
+ residual = hidden_states
836
+ hidden_states = self.post_attention_layernorm(hidden_states)
837
+ hidden_states = self.mlp(hidden_states)
838
+ if self.config.use_mup:
839
+ hidden_states = residual + hidden_states * (self.config.mup_depth_scale / math.sqrt(self.config.num_layers))
840
+ else:
841
+ hidden_states = residual + hidden_states
842
+ return hidden_states
843
+
844
+
845
+ @auto_docstring
846
+ class BlockFFNPreTrainedModel(PreTrainedModel):
847
+ config: BlockFFNConfig
848
+ base_model_prefix = "model"
849
+ supports_gradient_checkpointing = True
850
+ _no_split_modules = ["BlockFFNDecoderLayer"]
851
+ _skip_keys_device_placement = ["past_key_values"]
852
+ _supports_flash_attn = True
853
+ _supports_sdpa = True
854
+ _supports_flex_attn = True
855
+
856
+ _can_compile_fullgraph = True
857
+ _supports_attention_backend = True
858
+ _can_record_outputs = {
859
+ "hidden_states": BlockFFNDecoderLayer,
860
+ "attentions": BlockFFNAttention,
861
+ }
862
+
863
+
864
+ @auto_docstring
865
+ class BlockFFNModel(BlockFFNPreTrainedModel):
866
+ def __init__(self, config: BlockFFNConfig):
867
+ super().__init__(config)
868
+ self.config = config
869
+ self.padding_idx = config.pad_token_id
870
+ self.vocab_size = config.vocab_size
871
+
872
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
873
+ self.moe_layer_freq = eval(config.moe_layer_freq) if isinstance(config.moe_layer_freq, str) else config.moe_layer_freq
874
+ assert len(self.moe_layer_freq) == config.num_layers
875
+ self.layers = nn.ModuleList(
876
+ [BlockFFNDecoderLayer(config, layer_idx, bool(self.moe_layer_freq[layer_idx])) for layer_idx in range(config.num_layers)]
877
+ )
878
+ self.norm = BlockFFNRMSNorm(config.hidden_size, eps=config.norm_epsilon)
879
+ self.rotary_emb = BlockFFNRotaryEmbedding(config=config)
880
+ self.gradient_checkpointing = False
881
+
882
+ # Initialize weights and apply final processing
883
+ self.post_init()
884
+
885
+ @check_model_inputs
886
+ @auto_docstring
887
+ def forward(
888
+ self,
889
+ input_ids: Optional[torch.LongTensor] = None,
890
+ attention_mask: Optional[torch.Tensor] = None,
891
+ position_ids: Optional[torch.LongTensor] = None,
892
+ past_key_values: Optional[Cache] = None,
893
+ inputs_embeds: Optional[torch.FloatTensor] = None,
894
+ cache_position: Optional[torch.LongTensor] = None,
895
+ use_cache: Optional[bool] = None,
896
+ **kwargs: Unpack[TransformersKwargs],
897
+ ) -> BaseModelOutputWithPast:
898
+ if (input_ids is None) ^ (inputs_embeds is not None):
899
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
900
+
901
+ if inputs_embeds is None:
902
+ inputs_embeds: torch.Tensor = self.embed_tokens(input_ids)
903
+ if self.config.use_mup:
904
+ inputs_embeds = inputs_embeds * self.config.mup_emb_scale
905
+
906
+ if use_cache and past_key_values is None:
907
+ past_key_values = DynamicCache()
908
+
909
+ if cache_position is None:
910
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
911
+ cache_position: torch.Tensor = torch.arange(
912
+ past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
913
+ )
914
+
915
+ if position_ids is None:
916
+ position_ids = cache_position.unsqueeze(0)
917
+
918
+ causal_mask = create_causal_mask(
919
+ config=self.config,
920
+ input_embeds=inputs_embeds,
921
+ attention_mask=attention_mask,
922
+ cache_position=cache_position,
923
+ past_key_values=past_key_values,
924
+ position_ids=position_ids,
925
+ )
926
+
927
+ hidden_states = inputs_embeds
928
+ position_embeddings = self.rotary_emb(hidden_states, position_ids)
929
+
930
+ for decoder_layer in self.layers[: self.config.num_layers]:
931
+ hidden_states = decoder_layer(
932
+ hidden_states,
933
+ attention_mask=causal_mask,
934
+ position_ids=position_ids,
935
+ past_key_value=past_key_values,
936
+ cache_position=cache_position,
937
+ position_embeddings=position_embeddings,
938
+ **kwargs,
939
+ )
940
+
941
+ hidden_states = self.norm(hidden_states)
942
+ return BaseModelOutputWithPast(
943
+ last_hidden_state=hidden_states,
944
+ past_key_values=past_key_values,
945
+ )
946
+
947
+
948
+ @auto_docstring
949
+ class BlockFFNForCausalLM(BlockFFNPreTrainedModel, GenerationMixin):
950
+ _tied_weights_keys = ["lm_head.weight"]
951
+ _tp_plan = {"lm_head": "colwise_rep"}
952
+ _pp_plan = {"lm_head": (["hidden_states"], ["logits"])}
953
+
954
+ def __init__(self, config: BlockFFNConfig):
955
+ super().__init__(config)
956
+ self.config = config
957
+ self.model = BlockFFNModel(config)
958
+ self.vocab_size = config.vocab_size
959
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
960
+
961
+ # Initialize weights and apply final processing
962
+ self.post_init()
963
+
964
+ def set_decoder(self, decoder):
965
+ self.model = decoder
966
+
967
+ def get_decoder(self):
968
+ return self.model
969
+
970
+ @can_return_tuple
971
+ @auto_docstring
972
+ def forward(
973
+ self,
974
+ input_ids: Optional[torch.LongTensor] = None,
975
+ attention_mask: Optional[torch.Tensor] = None,
976
+ position_ids: Optional[torch.LongTensor] = None,
977
+ past_key_values: Optional[Cache] = None,
978
+ inputs_embeds: Optional[torch.FloatTensor] = None,
979
+ labels: Optional[torch.LongTensor] = None,
980
+ use_cache: Optional[bool] = None,
981
+ cache_position: Optional[torch.LongTensor] = None,
982
+ logits_to_keep: Union[int, torch.Tensor] = 0,
983
+ **kwargs: Unpack[TransformersKwargs],
984
+ ) -> CausalLMOutputWithPast:
985
+ outputs: BaseModelOutputWithPast = self.model(
986
+ input_ids=input_ids,
987
+ attention_mask=attention_mask,
988
+ position_ids=position_ids,
989
+ past_key_values=past_key_values,
990
+ inputs_embeds=inputs_embeds,
991
+ use_cache=use_cache,
992
+ cache_position=cache_position,
993
+ **kwargs,
994
+ )
995
+
996
+ hidden_states = outputs.last_hidden_state
997
+ if self.config.use_mup:
998
+ hidden_states = hidden_states / self.config.mup_width_scale
999
+
1000
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
1001
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
1002
+ logits = self.lm_head(hidden_states[:, slice_indices, :])
1003
+
1004
+ loss = None
1005
+ if labels is not None:
1006
+ loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs)
1007
+
1008
+ return CausalLMOutputWithPast(
1009
+ loss=loss,
1010
+ logits=logits,
1011
+ past_key_values=outputs.past_key_values,
1012
+ hidden_states=outputs.hidden_states,
1013
+ attentions=outputs.attentions,
1014
+ )
1015
+
1016
+ __all__ = [
1017
+ "BlockFFNForCausalLM",
1018
+ "BlockFFNModel",
1019
+ "BlockFFNPreTrainedModel",
1020
+ ]
pytorch_model.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:77bd28f57761994db8a474357cc7a738ae262e3051030761e0cb6eae64e28278
3
+ size 1442728373
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
+ }