gabrielmbmb HF staff commited on
Commit
f1a1ba7
·
verified ·
1 Parent(s): eb758a2

Upload Qwen2MoeForCausalLM

Browse files
README.md CHANGED
@@ -1,109 +1,199 @@
1
- # Upcycled-Qwen1.5-MoE2.7B
2
-
3
- This an attemp (probably too naive) to reproduce the upcycling process used to initialize [Qwen1.5-MoE-A2.7B](https://huggingface.co/Qwen/Qwen1.5-MoE-A2.7B) using [Qwen1.5-1.8B](Qwen/Qwen1.5-1.8B).
4
-
5
- ## Upcycling script
6
-
7
- ```python
8
- from torch import nn
9
- from transformers import AutoModelForCausalLM
10
- from dataclasses import dataclass
11
- from transformers import AutoModel
12
- from typing_extensions import Self
13
- from copy import deepcopy
14
-
15
- @dataclass
16
- class UpcyclingConfig:
17
- finegrained_experts: int
18
- partitions_from_mlp: int
19
-
20
- @property
21
- def upcycling_factor(self) -> int:
22
- return self.finegrained_experts // self.partitions_from_mlp
23
-
24
-
25
- def iterate_in_chunks(list1, list2, chunk_size1, chunk_size2):
26
- iterations = max(len(list1) // chunk_size1, len(list2) // chunk_size2)
27
- for i in range(iterations):
28
- start_idx1 = i * chunk_size1
29
- end_idx1 = start_idx1 + chunk_size1
30
- start_idx2 = i * chunk_size2
31
- end_idx2 = start_idx2 + chunk_size2
32
- yield (list1[start_idx1:end_idx1], list2[start_idx2:end_idx2])
33
-
34
-
35
- def chunk_linear(linear: nn.Linear, chunks: int, down_proj: bool = False) -> tuple[nn.Linear, ...]:
36
- if not down_proj:
37
- in_features = linear.in_features
38
- out_features = linear.out_features // chunks
39
- else:
40
- in_features = linear.in_features // chunks
41
- out_features = linear.out_features
42
-
43
- weights = linear.weight.chunk(chunks)
44
- biases = linear.bias.chunk(chunks) if linear.bias is not None else [None] * chunks
45
- linear_layers = []
46
- for weight, bias in zip(weights, biases):
47
- new_linear = nn.Linear(
48
- in_features=in_features, out_features=out_features, bias=bias is not None
49
- )
50
- new_linear.weight = nn.Parameter(weight.clone()) # Clone weights to ensure they are not shared
51
- if bias is not None:
52
- new_linear.bias = nn.Parameter(bias.clone()) # Clone bias if it exists
53
- linear_layers.append(new_linear)
54
- return tuple(linear_layers)
55
-
56
-
57
- class UpcycledModelMixin:
58
- sparse_moe_block_cls: type
59
-
60
- @classmethod
61
- def upcycled_from(cls, source_model, config: UpcyclingConfig) -> Self:
62
- upcycled_model_config = cls.config_class(**source_model.config.to_dict())
63
- if hasattr(upcycled_model_config, "shared_expert_intermediate_size"):
64
- upcycled_model_config.shared_expert_intermediate_size = source_model.config.intermediate_size
65
-
66
- upcycled_model = cls(upcycled_model_config)
67
- upcycled_model.model.embed_tokens = source_model.model.embed_tokens
68
-
69
- for upcycled_layer, layer in zip(upcycled_model.model.layers, source_model.model.layers):
70
- upcycled_layer.self_attn = layer.self_attn
71
- upcycled_mlp_layers = [deepcopy(layer.mlp) for _ in range(config.upcycling_factor)]
72
-
73
- if hasattr(upcycled_layer.mlp, "shared_expert"):
74
- upcycled_layer.mlp.shared_expert = upcycled_mlp_layers.pop(-1)
75
-
76
- for experts, mlp in iterate_in_chunks(upcycled_layer.mlp.experts, upcycled_mlp_layers, 4, 1):
77
- gate_projs = chunk_linear(mlp[0].gate_proj, 4, down_proj=False)
78
- up_projs = chunk_linear(mlp[0].up_proj, 4, down_proj=False)
79
- down_projs = chunk_linear(mlp[0].down_proj, 4, down_proj=True)
80
- for i, expert in enumerate(experts):
81
- expert.gate_proj = gate_projs[i]
82
- expert.up_proj = up_projs[i]
83
- expert.down_proj = down_projs[i]
84
- expert.act_fn = deepcopy(mlp[0].act_fn)
85
-
86
- upcycled_layer.input_layernorm = layer.input_layernorm
87
- upcycled_layer.post_attention_layernorm = layer.post_attention_layernorm
88
-
89
- upcycled_model.lm_head = source_model.lm_head
90
- return upcycled_model
91
-
92
-
93
- from transformers import Qwen2MoeForCausalLM as _Qwen2MoeForCausalLM
94
- from transformers.models.qwen2.modeling_qwen2 import Qwen2MLP
95
- from transformers.models.qwen2_moe.modeling_qwen2_moe import Qwen2MoeSparseMoeBlock
96
-
97
- class Qwen2MoeForCausalLM(UpcycledModelMixin, _Qwen2MoeForCausalLM):
98
- sparse_moe_block_cls = Qwen2MoeSparseMoeBlock
99
-
100
-
101
- source_model = AutoModelForCausalLM.from_pretrained("Qwen/Qwen1.5-1.8B")
102
- model = Qwen2MoeForCausalLM.upcycled_from(
103
- source_model,
104
- UpcyclingConfig(
105
- finegrained_experts=64,
106
- partitions_from_mlp=4,
107
- ),
108
- )
109
- ```
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "Qwen/Qwen1.5-1.8B",
3
+ "architectures": [
4
+ "Qwen2MoeForCausalLM"
5
+ ],
6
+ "attention_dropout": 0.0,
7
+ "bos_token_id": 151643,
8
+ "decoder_sparse_step": 1,
9
+ "eos_token_id": 151643,
10
+ "hidden_act": "silu",
11
+ "hidden_size": 2048,
12
+ "initializer_range": 0.02,
13
+ "intermediate_size": 5504,
14
+ "max_position_embeddings": 32768,
15
+ "max_window_layers": 21,
16
+ "model_type": "qwen2_moe",
17
+ "moe_intermediate_size": 1408,
18
+ "norm_topk_prob": false,
19
+ "num_attention_heads": 16,
20
+ "num_experts": 60,
21
+ "num_experts_per_tok": 4,
22
+ "num_hidden_layers": 24,
23
+ "num_key_value_heads": 16,
24
+ "output_router_logits": false,
25
+ "rms_norm_eps": 1e-06,
26
+ "rope_theta": 1000000.0,
27
+ "router_aux_loss_coef": 0.001,
28
+ "shared_expert_intermediate_size": 5504,
29
+ "sliding_window": 32768,
30
+ "tie_word_embeddings": false,
31
+ "torch_dtype": "float32",
32
+ "transformers_version": "4.40.0.dev0",
33
+ "use_cache": true,
34
+ "use_sliding_window": false,
35
+ "vocab_size": 151936
36
+ }
generation_config.json ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "bos_token_id": 151643,
4
+ "eos_token_id": 151643,
5
+ "transformers_version": "4.40.0.dev0"
6
+ }
model-00001-of-00012.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:fa08aff3e4dd7f4cb7c97a995bf20b945151e67caaec1ffa21fcad963aaa3238
3
+ size 4998348448
model-00002-of-00012.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c60629f8099a4c2ced043ce3486ffdbd9b2fc05b1d21b6038480a8ea012ee61e
3
+ size 4993666912
model-00003-of-00012.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5d627b48b981e327555ea52ddd7f9f6fef09ef37663a2a0fc1e127a9623207eb
3
+ size 4993682688
model-00004-of-00012.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2ed0aaa105d9b4cfeb5211b81ee683797ba45683c0850a23206b20645b70240e
3
+ size 4993666896
model-00005-of-00012.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c7257218ff3dbb12354489ed83e67de74fe619c15a44e9e57e4cf32e9e131e33
3
+ size 4993667040
model-00006-of-00012.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:133b38b85c3c71a3973672ed65fb6081ee573c16b815d238e96ef3f6d348e976
3
+ size 4993667352
model-00007-of-00012.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ffc2aae38b11b0908340821b73ba5912052ac8f764db648b02f8901c5b3faa28
3
+ size 4993683128
model-00008-of-00012.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:20c5550838172649d89c8fc6548878997b269146ded7ff7674523adab07be815
3
+ size 4993667320
model-00009-of-00012.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b73be2628ff33a392edadc788d2abf0e7efebb1e640d9a22e01b8ebf14dea0ea
3
+ size 4993667336
model-00010-of-00012.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:959fcfbd31660a38ed5f90234def80e6d22929516ffd442faa5f63efe074dcd1
3
+ size 4993667352
model-00011-of-00012.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:defe36cc3621d7f982a32aa23899937d007220bdc8db87fd06ead4760a036c41
3
+ size 4869703976
model-00012-of-00012.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0e6e8547b8884ccba68b2f4a275e6a2b08bb94d8f25c9235b02617d2d6842ac3
3
+ size 1244659840
model.safetensors.index.json ADDED
The diff for this file is too large to render. See raw diff