wmere commited on
Commit
95df130
·
verified ·
1 Parent(s): 28abd1e

Upload FalconH1MoEForCausalLM

Browse files
README.md ADDED
@@ -0,0 +1,199 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ library_name: transformers
3
+ tags: []
4
+ ---
5
+
6
+ # Model Card for Model ID
7
+
8
+ <!-- Provide a quick summary of what the model is/does. -->
9
+
10
+
11
+
12
+ ## Model Details
13
+
14
+ ### Model Description
15
+
16
+ <!-- Provide a longer summary of what this model is. -->
17
+
18
+ This is the model card of a 🤗 transformers model that has been pushed on the Hub. This model card has been automatically generated.
19
+
20
+ - **Developed by:** [More Information Needed]
21
+ - **Funded by [optional]:** [More Information Needed]
22
+ - **Shared by [optional]:** [More Information Needed]
23
+ - **Model type:** [More Information Needed]
24
+ - **Language(s) (NLP):** [More Information Needed]
25
+ - **License:** [More Information Needed]
26
+ - **Finetuned from model [optional]:** [More Information Needed]
27
+
28
+ ### Model Sources [optional]
29
+
30
+ <!-- Provide the basic links for the model. -->
31
+
32
+ - **Repository:** [More Information Needed]
33
+ - **Paper [optional]:** [More Information Needed]
34
+ - **Demo [optional]:** [More Information Needed]
35
+
36
+ ## Uses
37
+
38
+ <!-- Address questions around how the model is intended to be used, including the foreseeable users of the model and those affected by the model. -->
39
+
40
+ ### Direct Use
41
+
42
+ <!-- This section is for the model use without fine-tuning or plugging into a larger ecosystem/app. -->
43
+
44
+ [More Information Needed]
45
+
46
+ ### Downstream Use [optional]
47
+
48
+ <!-- This section is for the model use when fine-tuned for a task, or when plugged into a larger ecosystem/app -->
49
+
50
+ [More Information Needed]
51
+
52
+ ### Out-of-Scope Use
53
+
54
+ <!-- This section addresses misuse, malicious use, and uses that the model will not work well for. -->
55
+
56
+ [More Information Needed]
57
+
58
+ ## Bias, Risks, and Limitations
59
+
60
+ <!-- This section is meant to convey both technical and sociotechnical limitations. -->
61
+
62
+ [More Information Needed]
63
+
64
+ ### Recommendations
65
+
66
+ <!-- This section is meant to convey recommendations with respect to the bias, risk, and technical limitations. -->
67
+
68
+ Users (both direct and downstream) should be made aware of the risks, biases and limitations of the model. More information needed for further recommendations.
69
+
70
+ ## How to Get Started with the Model
71
+
72
+ Use the code below to get started with the model.
73
+
74
+ [More Information Needed]
75
+
76
+ ## Training Details
77
+
78
+ ### Training Data
79
+
80
+ <!-- This should link to a Dataset Card, perhaps with a short stub of information on what the training data is all about as well as documentation related to data pre-processing or additional filtering. -->
81
+
82
+ [More Information Needed]
83
+
84
+ ### Training Procedure
85
+
86
+ <!-- This relates heavily to the Technical Specifications. Content here should link to that section when it is relevant to the training procedure. -->
87
+
88
+ #### Preprocessing [optional]
89
+
90
+ [More Information Needed]
91
+
92
+
93
+ #### Training Hyperparameters
94
+
95
+ - **Training regime:** [More Information Needed] <!--fp32, fp16 mixed precision, bf16 mixed precision, bf16 non-mixed precision, fp16 non-mixed precision, fp8 mixed precision -->
96
+
97
+ #### Speeds, Sizes, Times [optional]
98
+
99
+ <!-- This section provides information about throughput, start/end time, checkpoint size if relevant, etc. -->
100
+
101
+ [More Information Needed]
102
+
103
+ ## Evaluation
104
+
105
+ <!-- This section describes the evaluation protocols and provides the results. -->
106
+
107
+ ### Testing Data, Factors & Metrics
108
+
109
+ #### Testing Data
110
+
111
+ <!-- This should link to a Dataset Card if possible. -->
112
+
113
+ [More Information Needed]
114
+
115
+ #### Factors
116
+
117
+ <!-- These are the things the evaluation is disaggregating by, e.g., subpopulations or domains. -->
118
+
119
+ [More Information Needed]
120
+
121
+ #### Metrics
122
+
123
+ <!-- These are the evaluation metrics being used, ideally with a description of why. -->
124
+
125
+ [More Information Needed]
126
+
127
+ ### Results
128
+
129
+ [More Information Needed]
130
+
131
+ #### Summary
132
+
133
+
134
+
135
+ ## Model Examination [optional]
136
+
137
+ <!-- Relevant interpretability work for the model goes here -->
138
+
139
+ [More Information Needed]
140
+
141
+ ## Environmental Impact
142
+
143
+ <!-- Total emissions (in grams of CO2eq) and additional considerations, such as electricity usage, go here. Edit the suggested text below accordingly -->
144
+
145
+ Carbon emissions can be estimated using the [Machine Learning Impact calculator](https://mlco2.github.io/impact#compute) presented in [Lacoste et al. (2019)](https://arxiv.org/abs/1910.09700).
146
+
147
+ - **Hardware Type:** [More Information Needed]
148
+ - **Hours used:** [More Information Needed]
149
+ - **Cloud Provider:** [More Information Needed]
150
+ - **Compute Region:** [More Information Needed]
151
+ - **Carbon Emitted:** [More Information Needed]
152
+
153
+ ## Technical Specifications [optional]
154
+
155
+ ### Model Architecture and Objective
156
+
157
+ [More Information Needed]
158
+
159
+ ### Compute Infrastructure
160
+
161
+ [More Information Needed]
162
+
163
+ #### Hardware
164
+
165
+ [More Information Needed]
166
+
167
+ #### Software
168
+
169
+ [More Information Needed]
170
+
171
+ ## Citation [optional]
172
+
173
+ <!-- If there is a paper or blog post introducing the model, the APA and Bibtex information for that should go in this section. -->
174
+
175
+ **BibTeX:**
176
+
177
+ [More Information Needed]
178
+
179
+ **APA:**
180
+
181
+ [More Information Needed]
182
+
183
+ ## Glossary [optional]
184
+
185
+ <!-- If relevant, include terms and calculations in this section that can help readers understand the model or model card. -->
186
+
187
+ [More Information Needed]
188
+
189
+ ## More Information [optional]
190
+
191
+ [More Information Needed]
192
+
193
+ ## Model Card Authors [optional]
194
+
195
+ [More Information Needed]
196
+
197
+ ## Model Card Contact
198
+
199
+ [More Information Needed]
config.json ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "FalconH1MoEForCausalLM"
4
+ ],
5
+ "attention_bias": false,
6
+ "attention_dropout": 0.0,
7
+ "attention_in_multiplier": 1.0,
8
+ "attention_out_multiplier": 0.9375,
9
+ "attn_layer_indices": null,
10
+ "auto_map": {
11
+ "AutoConfig": "configuration_falcon_h1_moe.FalconH1MoEConfig",
12
+ "AutoModel": "modeling_falcon_h1_moe.FalconH1MoEForCausalLM"
13
+ },
14
+ "bos_token_id": 1,
15
+ "embedding_multiplier": 5.656854249492381,
16
+ "eos_token_id": 11,
17
+ "expert_num": 8,
18
+ "head_dim": 64,
19
+ "hidden_act": "silu",
20
+ "hidden_size": 1024,
21
+ "initializer_range": 0.02,
22
+ "intermediate_size": 2048,
23
+ "key_multiplier": 0.39062499999999994,
24
+ "lm_head_multiplier": 0.0390625,
25
+ "mamba_chunk_size": 128,
26
+ "mamba_conv_bias": true,
27
+ "mamba_d_conv": 4,
28
+ "mamba_d_head": 64,
29
+ "mamba_d_ssm": 1536,
30
+ "mamba_d_state": 128,
31
+ "mamba_expand": 2,
32
+ "mamba_n_groups": 1,
33
+ "mamba_n_heads": 24,
34
+ "mamba_norm_before_gate": false,
35
+ "mamba_proj_bias": false,
36
+ "mamba_rms_norm": false,
37
+ "mamba_use_mlp": true,
38
+ "max_position_embeddings": 16384,
39
+ "mlp_bias": false,
40
+ "mlp_expansion_factor": 8,
41
+ "mlp_multipliers": [
42
+ 0.8838834764831844,
43
+ 0.5859375
44
+ ],
45
+ "model_type": "falcon_h1",
46
+ "num_attention_heads": 8,
47
+ "num_hidden_layers": 36,
48
+ "num_key_value_heads": 2,
49
+ "num_logits_to_keep": 1,
50
+ "pad_token_id": 0,
51
+ "projectors_bias": false,
52
+ "rms_norm_eps": 1e-05,
53
+ "rope_scaling": null,
54
+ "rope_theta": 100000000000.0,
55
+ "ssm_in_multiplier": 1.25,
56
+ "ssm_multipliers": [
57
+ 0.3535533905932738,
58
+ 0.25,
59
+ 0.3535533905932738,
60
+ 0.5,
61
+ 0.3535533905932738
62
+ ],
63
+ "ssm_out_multiplier": 0.23570226039551587,
64
+ "tie_word_embeddings": false,
65
+ "topk": 2,
66
+ "torch_dtype": "float32",
67
+ "transformers_version": "4.55.2",
68
+ "use_cache": true,
69
+ "vocab_size": 32784
70
+ }
configuration_falcon_h1_moe.py ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers import FalconH1Config
2
+
3
+
4
+ """FalconH1MoE model configuration"""
5
+ class FalconH1MoEConfig(FalconH1Config):
6
+ def __init__(
7
+ self,
8
+ expert_num=8,
9
+ topk=2,
10
+ **kwargs,
11
+ ):
12
+ super().__init__(**kwargs)
13
+ self.expert_num = expert_num
14
+ self.topk = topk
15
+
16
+
17
+ __all__ = ["FalconH1MoEConfig"]
generation_config.json ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "bos_token_id": 1,
4
+ "eos_token_id": 11,
5
+ "pad_token_id": 0,
6
+ "transformers_version": "4.55.2"
7
+ }
model-00001-of-00002.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8511f8dcbafd15cc0a878e826192af5f50ee1622047e24645027d29cf4157474
3
+ size 4995103432
model-00002-of-00002.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e6a2cf8841920aed4698fd782c5750be0209e2c6d2a82aee56e23a6489f6cac6
3
+ size 3433677328
model.safetensors.index.json ADDED
The diff for this file is too large to render. See raw diff
 
modeling_falcon_h1_moe.py ADDED
@@ -0,0 +1,186 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ from transformers import AutoConfig, AutoModelForCausalLM, AutoTokenizer
3
+ import torch
4
+ from transformers import FalconH1Config, FalconH1ForCausalLM, FalconH1Model
5
+ from openrlhf.moe_utils import FalconH1MoEConfig
6
+ from transformers.models.falcon_h1.modeling_falcon_h1 import FalconH1DecoderLayer, FalconH1MLP, compute_mup_vector
7
+ from torch import nn
8
+ import random
9
+ import numpy as np
10
+
11
+
12
+ class FalconH1MoEModel(FalconH1Model):
13
+ def __init__(self, config: FalconH1MoEConfig):
14
+ super().__init__(config)
15
+ decoder_layers = []
16
+ for i in range(config.num_hidden_layers):
17
+ decoder_layers.append(FalconH1MoEDecoderLayer(config, layer_idx=i))
18
+ self.layers = nn.ModuleList(decoder_layers)
19
+ mup_vector = compute_mup_vector(config)
20
+ for layer in self.layers:
21
+ layer.mamba.register_buffer("mup_vector", mup_vector, persistent=False)
22
+
23
+
24
+
25
+ class FalconH1MoEMLP(nn.Module):
26
+ def __init__(self, config: FalconH1MoEConfig, layer_idx: int):
27
+ super().__init__()
28
+ self.config = config
29
+ self.layer_idx = layer_idx
30
+ self.entropy = []
31
+ self.num_local_experts = config.expert_num
32
+ self.topk=config.topk
33
+ '''build experts'''
34
+ self.experts = torch.nn.ModuleList()
35
+ for _ in range(self.num_local_experts):
36
+ expert = FalconH1MLP(config)
37
+ self.experts.append(expert)
38
+
39
+
40
+ '''build router'''
41
+ self.weight = torch.nn.Parameter(
42
+ torch.empty((self.num_local_experts, self.config.hidden_size), dtype=torch.float32)
43
+ )
44
+ torch.nn.init.xavier_uniform_(self.weight)
45
+
46
+
47
+
48
+ def forward(self, x):
49
+ log_str = ""
50
+
51
+
52
+ x = x.transpose(0, 1).contiguous() #x: [seq_len, bs, hidden_size]
53
+ '''fixed parameters'''
54
+ inp_shape = x.shape
55
+ num_tokens = inp_shape[0] * inp_shape[1]
56
+ hidden = inp_shape[-1]
57
+ num_experts = self.num_local_experts
58
+ x = x.view(-1, inp_shape[-1]) #x: [token_num, hidden_size]
59
+ restore_shape = x.shape
60
+
61
+
62
+
63
+ """Routing , compute the experts' weight for each token, all following step is on token level.
64
+ Args:
65
+ input (torch.Tensor): Input tensor of shape [bs, seq, hidden].
66
+ weights (torch.Tensor): router's weights, [hidden, expert_num].
67
+ Returns:
68
+ routing_probs, token -> expert_prob
69
+ [[0.0000, 0.0000, 0.4006, 0.5994],
70
+ ...,
71
+ [0.0373, 0.0000, 0.9627, 0.0000]]
72
+ ------------
73
+ routing_map, token -> expert_idx
74
+ [[False, False, True, True],
75
+ ...,
76
+ [ True, False, True, False]])
77
+ """
78
+ y = torch.mm(x, self.weight.to(x.dtype).t()) #y: [token_num, expert_num]
79
+ scores, top_indices = torch.topk(y, k=self.topk, dim=1)
80
+ probs = torch.softmax(scores, dim=-1, dtype=torch.float32).type_as(y)
81
+ routing_probs = torch.zeros_like(y).scatter(1, top_indices, probs)
82
+ routing_map = torch.zeros_like(y).int().scatter(1, top_indices, 1).bool()
83
+
84
+
85
+
86
+ """Dispatch: experts-to-tokens
87
+
88
+ Args:
89
+
90
+
91
+ Returns:
92
+ probs: [expert0{token4_prob, token2_prob,token8_prob}.....expertn]
93
+ x: [expert0{token4_idx, token2_idx, token8_idx}.....]
94
+
95
+ """
96
+ permuted_probs = None
97
+ num_local_tokens_per_expert = routing_map.sum(dim=0).long() # [token_num_e_1, ...., token_num_e_n]
98
+ num_out_tokens = routing_map.size(0) * self.topk
99
+ routing_map = routing_map.bool().T.contiguous() # expert-to-token, [expert_num, token_num]
100
+ '''
101
+ [False, False, False, ..., False, True, True],
102
+ [False, False, False, ..., True, False, False],
103
+ [ True, True, True, ..., True, True, True],
104
+ [ True, True, True, ..., False, False, False]]
105
+ '''
106
+ token_indices = (
107
+ torch.arange(num_tokens, device=routing_map.device).unsqueeze(0).expand(num_experts, -1)
108
+ ) # [expert_num, token_num]
109
+ '''
110
+ [[ 0, 1, 2, ..., 1021, 1022, 1023],
111
+ [ 0, 1, 2, ..., 1021, 1022, 1023],
112
+ [ 0, 1, 2, ..., 1021, 1022, 1023],
113
+ [ 0, 1, 2, ..., 1021, 1022, 1023]]
114
+ '''
115
+
116
+ sorted_indices = token_indices.masked_select(routing_map) # [topk * token_num]
117
+ '''
118
+ [ 8, 9, 12, ..., 1015, 1016, 1017],
119
+ sorted_indices[:idx_1]->expert0
120
+ sorted_indices[idx_1:idx_2]->expert1
121
+ sorted_indices[idx_2:idx_3]->expert2
122
+ sorted_indices[idx_3:idx_4]->expert3
123
+ '''
124
+ probs = routing_probs.T.contiguous().masked_select(routing_map) # [topk * token_num]
125
+ '''
126
+ [0.6458, 0.6458, 0.5577, ..., 0.4983, 0.0520, 0.0520]
127
+ '''
128
+ x = x.index_select(0, sorted_indices) # [token_num * topk, hidden]
129
+
130
+
131
+
132
+
133
+
134
+ """compute:
135
+
136
+ Args:
137
+
138
+
139
+ Returns:
140
+
141
+ """
142
+ tokens_list = torch.split(x, num_local_tokens_per_expert.tolist())
143
+ probs_list = torch.split(probs, num_local_tokens_per_expert.tolist())
144
+
145
+ output_local_list = []
146
+
147
+ self.entropy = []
148
+ for expert, tokens, prob in zip(self.experts, tokens_list, probs_list):
149
+ output = expert(tokens) * prob.unsqueeze(-1)
150
+
151
+ pd = torch.nn.functional.softmax(output, dim=-1)
152
+ entropy = torch.logsumexp(output, dim=-1) - torch.sum(pd * output, dim=-1)
153
+ entropy_mean = entropy.mean(dim=0).item()
154
+ # print(f"*******layer_idx: {str(self.layer_idx)}, entropy_loss: {str(entropy.mean(dim=0).item())}, token_selected: {str(tokens.shape[0])}")
155
+ output_local_list.append(output)
156
+
157
+ self.entropy.append((entropy_mean, tokens.shape[0]))
158
+
159
+ permuted_tokens = torch.cat(output_local_list, dim=0)
160
+
161
+ output_tokens = torch.zeros(
162
+ restore_shape, dtype=permuted_tokens.dtype, device=permuted_tokens.device
163
+ )
164
+ # Scatter add the permuted_input back to the original positions
165
+ output_tokens.scatter_add_(0, sorted_indices.unsqueeze(1).expand(-1, hidden), permuted_tokens)
166
+ output = output_tokens.view(inp_shape).transpose(0, 1)
167
+
168
+ return output
169
+
170
+
171
+
172
+ class FalconH1MoEDecoderLayer(FalconH1DecoderLayer):
173
+ def __init__(self, config: FalconH1MoEConfig, layer_idx: int):
174
+ super().__init__(config, layer_idx)
175
+ self.feed_forward = FalconH1MoEMLP(config, layer_idx)
176
+
177
+
178
+
179
+
180
+
181
+ class FalconH1MoEForCausalLM(FalconH1ForCausalLM):
182
+ def __init__(self, config: FalconH1MoEConfig):
183
+ super().__init__(config)
184
+ self.model = FalconH1MoEModel(config)
185
+
186
+ __all__ = ["FalconH1MoEForCausalLM"]