mikasenghaas commited on
Commit
436e7ab
·
verified ·
1 Parent(s): 24c25eb

Upload folder using huggingface_hub

Browse files
.gitattributes CHANGED
@@ -33,3 +33,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ tokenizer.json filter=lfs diff=lfs merge=lfs -text
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]
added_tokens.json ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "</think>": 151668,
3
+ "</tool_call>": 151658,
4
+ "</tool_response>": 151666,
5
+ "<think>": 151667,
6
+ "<tool_call>": 151657,
7
+ "<tool_response>": 151665,
8
+ "<|box_end|>": 151649,
9
+ "<|box_start|>": 151648,
10
+ "<|endoftext|>": 151643,
11
+ "<|file_sep|>": 151664,
12
+ "<|fim_middle|>": 151660,
13
+ "<|fim_pad|>": 151662,
14
+ "<|fim_prefix|>": 151659,
15
+ "<|fim_suffix|>": 151661,
16
+ "<|im_end|>": 151645,
17
+ "<|im_start|>": 151644,
18
+ "<|image_pad|>": 151655,
19
+ "<|object_ref_end|>": 151647,
20
+ "<|object_ref_start|>": 151646,
21
+ "<|quad_end|>": 151651,
22
+ "<|quad_start|>": 151650,
23
+ "<|repo_name|>": 151663,
24
+ "<|video_pad|>": 151656,
25
+ "<|vision_end|>": 151653,
26
+ "<|vision_pad|>": 151654,
27
+ "<|vision_start|>": 151652
28
+ }
chat_template.jinja ADDED
@@ -0,0 +1,130 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {% macro render_extra_keys(json_dict, handled_keys) %}
2
+ {%- if json_dict is mapping %}
3
+ {%- for json_key in json_dict if json_key not in handled_keys %}
4
+ {%- if json_dict[json_key] is mapping or (json_dict[json_key] is sequence and json_dict[json_key] is not string) %}
5
+ {{- '\n<' ~ json_key ~ '>' ~ (json_dict[json_key] | tojson | safe) ~ '</' ~ json_key ~ '>' }}
6
+ {%- else %}
7
+ {{-'\n<' ~ json_key ~ '>' ~ (json_dict[json_key] | string) ~ '</' ~ json_key ~ '>' }}
8
+ {%- endif %}
9
+ {%- endfor %}
10
+ {%- endif %}
11
+ {% endmacro %}
12
+
13
+ {%- if messages[0]["role"] == "system" %}
14
+ {%- set system_message = messages[0]["content"] %}
15
+ {%- set loop_messages = messages[1:] %}
16
+ {%- else %}
17
+ {%- set loop_messages = messages %}
18
+ {%- endif %}
19
+
20
+ {%- if not tools is defined %}
21
+ {%- set tools = [] %}
22
+ {%- endif %}
23
+
24
+ {%- if system_message is defined %}
25
+ {{- "<|im_start|>system\n" + system_message }}
26
+ {%- else %}
27
+ {%- if tools is iterable and tools | length > 0 %}
28
+ {{- "<|im_start|>system\nYou are Qwen, a helpful AI assistant that can interact with a computer to solve tasks." }}
29
+ {%- endif %}
30
+ {%- endif %}
31
+ {%- if tools is iterable and tools | length > 0 %}
32
+ {{- "\n\n# Tools\n\nYou have access to the following functions:\n\n" }}
33
+ {{- "<tools>" }}
34
+ {%- for tool in tools %}
35
+ {%- if tool.function is defined %}
36
+ {%- set tool = tool.function %}
37
+ {%- endif %}
38
+ {{- "\n<function>\n<name>" ~ tool.name ~ "</name>" }}
39
+ {%- if tool.description is defined %}
40
+ {{- '\n<description>' ~ (tool.description | trim) ~ '</description>' }}
41
+ {%- endif %}
42
+ {{- '\n<parameters>' }}
43
+ {%- if tool.parameters is defined and tool.parameters is mapping and tool.parameters.properties is defined and tool.parameters.properties is mapping %}
44
+ {%- for param_name, param_fields in tool.parameters.properties|items %}
45
+ {{- '\n<parameter>' }}
46
+ {{- '\n<name>' ~ param_name ~ '</name>' }}
47
+ {%- if param_fields.type is defined %}
48
+ {{- '\n<type>' ~ (param_fields.type | string) ~ '</type>' }}
49
+ {%- endif %}
50
+ {%- if param_fields.description is defined %}
51
+ {{- '\n<description>' ~ (param_fields.description | trim) ~ '</description>' }}
52
+ {%- endif %}
53
+ {%- set handled_keys = ['name', 'type', 'description'] %}
54
+ {{- render_extra_keys(param_fields, handled_keys) }}
55
+ {{- '\n</parameter>' }}
56
+ {%- endfor %}
57
+ {%- endif %}
58
+ {% set handled_keys = ['type', 'properties'] %}
59
+ {{- render_extra_keys(tool.parameters, handled_keys) }}
60
+ {{- '\n</parameters>' }}
61
+ {%- set handled_keys = ['type', 'name', 'description', 'parameters'] %}
62
+ {{- render_extra_keys(tool, handled_keys) }}
63
+ {{- '\n</function>' }}
64
+ {%- endfor %}
65
+ {{- "\n</tools>" }}
66
+ {{- '\n\nIf you choose to call a function ONLY reply in the following format with NO suffix:\n\n<tool_call>\n<function=example_function_name>\n<parameter=example_parameter_1>\nvalue_1\n</parameter>\n<parameter=example_parameter_2>\nThis is the value for the second parameter\nthat can span\nmultiple lines\n</parameter>\n</function>\n</tool_call>\n\n<IMPORTANT>\nReminder:\n- Function calls MUST follow the specified format: an inner <function=...></function> block must be nested within <tool_call></tool_call> XML tags\n- Required parameters MUST be specified\n- You may provide optional reasoning for your function call in natural language BEFORE the function call, but NOT after\n- If there is no function call available, answer the question like normal with your current knowledge and do not tell the user about function calls\n</IMPORTANT>' }}
67
+ {%- endif %}
68
+ {%- if system_message is defined %}
69
+ {{- '<|im_end|>\n' }}
70
+ {%- else %}
71
+ {%- if tools is iterable and tools | length > 0 %}
72
+ {{- '<|im_end|>\n' }}
73
+ {%- endif %}
74
+ {%- endif %}
75
+ {%- for message in loop_messages %}
76
+ {%- if message.role == "assistant" and message.tool_calls is defined and message.tool_calls is iterable and message.tool_calls | length > 0 %}
77
+ {{- '<|im_start|>' + message.role }}
78
+ {%- if message.content is defined and message.content is string and message.content | trim | length > 0 %}
79
+ {{- '\n' + message.content | trim + '\n' }}
80
+ {%- endif %}
81
+ {%- for tool_call in message.tool_calls %}
82
+ {%- if tool_call.function is defined %}
83
+ {%- set tool_call = tool_call.function %}
84
+ {%- endif %}
85
+ {{- '\n<tool_call>\n<function=' + tool_call.name + '>\n' }}
86
+ {%- if tool_call.arguments is defined %}
87
+ {%- for args_name, args_value in tool_call.arguments|items %}
88
+ {{- '<parameter=' + args_name + '>\n' }}
89
+ {%- set args_value = args_value | tojson | safe if args_value is mapping or (args_value is sequence and args_value is not string) else args_value | string %}
90
+ {{- args_value }}
91
+ {{- '\n</parameter>\n' }}
92
+ {%- endfor %}
93
+ {%- endif %}
94
+ {{- '</function>\n</tool_call>' }}
95
+ {%- endfor %}
96
+ {{- '<|im_end|>\n' }}
97
+ {%- elif message.role == "user" or message.role == "system" or message.role == "assistant" %}
98
+ {{- '<|im_start|>' + message.role }}
99
+ {%- if message.role == "assistant" and message.reasoning_content is defined %}
100
+ {%- if message.reasoning_content -%}
101
+ {{ '\n<think>' + message.reasoning_content.strip() + '</think>' }}
102
+ {%- else -%}
103
+ {{ '\n<think></think>' }}
104
+ {%- endif -%}
105
+ {%- if message.content.strip() -%}
106
+ {{ '\n' + message.content.strip() }}
107
+ {%- endif -%}
108
+ {%- else %}
109
+ {{- '\n' + message.content }}
110
+ {%- endif %}
111
+ {{- '<|im_end|>' + '\n' }}
112
+ {%- elif message.role == "tool" %}
113
+ {%- if loop.previtem and loop.previtem.role != "tool" %}
114
+ {{- '<|im_start|>user\n' }}
115
+ {%- endif %}
116
+ {{- '<tool_response>\n' }}
117
+ {{- message.content }}
118
+ {{- '\n</tool_response>\n' }}
119
+ {%- if not loop.last and loop.nextitem.role != "tool" %}
120
+ {{- '<|im_end|>\n' }}
121
+ {%- elif loop.last %}
122
+ {{- '<|im_end|>\n' }}
123
+ {%- endif %}
124
+ {%- else %}
125
+ {{- '<|im_start|>' + message.role + '\n' + message.content + '<|im_end|>\n' }}
126
+ {%- endif %}
127
+ {%- endfor %}
128
+ {%- if add_generation_prompt %}
129
+ {{- '<|im_start|>assistant\n' }}
130
+ {%- endif %}
config.json ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "Qwen3MoeForCausalLM"
4
+ ],
5
+ "auto_map": {
6
+ "AutoConfig": "configuration_qwen3_moe.Qwen3MoeConfig",
7
+ "AutoModelForCausalLM": "modeling_qwen3_moe.Qwen3MoeForCausalLM",
8
+ "AutoModel": "modeling_qwen3_moe.Qwen3MoeModel"
9
+ },
10
+ "attention_bias": false,
11
+ "attention_dropout": 0.0,
12
+ "bos_token_id": 151643,
13
+ "decoder_sparse_step": 1,
14
+ "eos_token_id": 151645,
15
+ "head_dim": 128,
16
+ "hidden_act": "silu",
17
+ "hidden_size": 2048,
18
+ "initializer_range": 0.02,
19
+ "intermediate_size": 6144,
20
+ "max_position_embeddings": 40960,
21
+ "max_window_layers": 48,
22
+ "mlp_only_layers": [],
23
+ "model_type": "qwen3_moe",
24
+ "moe_intermediate_size": 768,
25
+ "norm_topk_prob": true,
26
+ "num_attention_heads": 32,
27
+ "num_experts": 128,
28
+ "num_experts_per_tok": 8,
29
+ "num_hidden_layers": 48,
30
+ "num_key_value_heads": 4,
31
+ "output_router_logits": false,
32
+ "rms_norm_eps": 1e-06,
33
+ "rope_scaling": null,
34
+ "rope_theta": 1000000.0,
35
+ "router_aux_loss_coef": 0.001,
36
+ "sliding_window": null,
37
+ "tie_word_embeddings": false,
38
+ "torch_dtype": "bfloat16",
39
+ "transformers_version": "4.51.0",
40
+ "use_cache": true,
41
+ "use_sliding_window": false,
42
+ "vocab_size": 151936
43
+ }
configuration_qwen3_moe.py ADDED
@@ -0,0 +1,243 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 The Qwen team, Alibaba Group and the HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """Qwen3MoE model configuration"""
16
+
17
+ from transformers.configuration_utils import PretrainedConfig
18
+ from transformers.modeling_rope_utils import rope_config_validation
19
+ from transformers.utils import logging
20
+
21
+
22
+ logger = logging.get_logger(__name__)
23
+
24
+
25
+ class Qwen3MoeConfig(PretrainedConfig):
26
+ r"""
27
+ This is the configuration class to store the configuration of a [`Qwen3MoeModel`]. It is used to instantiate a
28
+ Qwen3MoE model according to the specified arguments, defining the model architecture. Instantiating a configuration
29
+ with the defaults will yield a similar configuration to that of [Qwen/Qwen3-15B-A2B](https://huggingface.co/Qwen/Qwen3-15B-A2B).
30
+
31
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
32
+ documentation from [`PretrainedConfig`] for more information.
33
+
34
+
35
+ Args:
36
+ vocab_size (`int`, *optional*, defaults to 151936):
37
+ Vocabulary size of the Qwen3MoE model. Defines the number of different tokens that can be represented by the
38
+ `inputs_ids` passed when calling [`Qwen3MoeModel`]
39
+ hidden_size (`int`, *optional*, defaults to 2048):
40
+ Dimension of the hidden representations.
41
+ intermediate_size (`int`, *optional*, defaults to 6144):
42
+ Dimension of the MLP representations.
43
+ num_hidden_layers (`int`, *optional*, defaults to 24):
44
+ Number of hidden layers in the Transformer encoder.
45
+ num_attention_heads (`int`, *optional*, defaults to 32):
46
+ Number of attention heads for each attention layer in the Transformer encoder.
47
+ num_key_value_heads (`int`, *optional*, defaults to 4):
48
+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If
49
+ `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
50
+ `num_key_value_heads=1` the model will use Multi Query Attention (MQA) otherwise GQA is used. When
51
+ converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
52
+ by meanpooling all the original heads within that group. For more details, check out [this
53
+ paper](https://huggingface.co/papers/2305.13245). If it is not specified, will default to `32`.
54
+
55
+ hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
56
+ The non-linear activation function (function or string) in the decoder.
57
+ max_position_embeddings (`int`, *optional*, defaults to 32768):
58
+ The maximum sequence length that this model might ever be used with.
59
+ initializer_range (`float`, *optional*, defaults to 0.02):
60
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
61
+ rms_norm_eps (`float`, *optional*, defaults to 1e-06):
62
+ The epsilon used by the rms normalization layers.
63
+ use_cache (`bool`, *optional*, defaults to `True`):
64
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
65
+ relevant if `config.is_decoder=True`.
66
+ tie_word_embeddings (`bool`, *optional*, defaults to `False`):
67
+ Whether the model's input and output word embeddings should be tied.
68
+ rope_theta (`float`, *optional*, defaults to 10000.0):
69
+ The base period of the RoPE embeddings.
70
+ rope_scaling (`Dict`, *optional*):
71
+ Dictionary containing the scaling configuration for the RoPE embeddings. NOTE: if you apply new rope type
72
+ and you expect the model to work on longer `max_position_embeddings`, we recommend you to update this value
73
+ accordingly.
74
+ Expected contents:
75
+ `rope_type` (`str`):
76
+ The sub-variant of RoPE to use. Can be one of ['default', 'linear', 'dynamic', 'yarn', 'longrope',
77
+ 'llama3'], with 'default' being the original RoPE implementation.
78
+ `factor` (`float`, *optional*):
79
+ Used with all rope types except 'default'. The scaling factor to apply to the RoPE embeddings. In
80
+ most scaling types, a `factor` of x will enable the model to handle sequences of length x *
81
+ original maximum pre-trained length.
82
+ `original_max_position_embeddings` (`int`, *optional*):
83
+ Used with 'dynamic', 'longrope' and 'llama3'. The original max position embeddings used during
84
+ pretraining.
85
+ `attention_factor` (`float`, *optional*):
86
+ Used with 'yarn' and 'longrope'. The scaling factor to be applied on the attention
87
+ computation. If unspecified, it defaults to value recommended by the implementation, using the
88
+ `factor` field to infer the suggested value.
89
+ `beta_fast` (`float`, *optional*):
90
+ Only used with 'yarn'. Parameter to set the boundary for extrapolation (only) in the linear
91
+ ramp function. If unspecified, it defaults to 32.
92
+ `beta_slow` (`float`, *optional*):
93
+ Only used with 'yarn'. Parameter to set the boundary for interpolation (only) in the linear
94
+ ramp function. If unspecified, it defaults to 1.
95
+ `short_factor` (`list[float]`, *optional*):
96
+ Only used with 'longrope'. The scaling factor to be applied to short contexts (<
97
+ `original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
98
+ size divided by the number of attention heads divided by 2
99
+ `long_factor` (`list[float]`, *optional*):
100
+ Only used with 'longrope'. The scaling factor to be applied to long contexts (<
101
+ `original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
102
+ size divided by the number of attention heads divided by 2
103
+ `low_freq_factor` (`float`, *optional*):
104
+ Only used with 'llama3'. Scaling factor applied to low frequency components of the RoPE
105
+ `high_freq_factor` (`float`, *optional*):
106
+ Only used with 'llama3'. Scaling factor applied to high frequency components of the RoPE
107
+ attention_bias (`bool`, defaults to `False`, *optional*, defaults to `False`):
108
+ Whether to use a bias in the query, key, value and output projection layers during self-attention.
109
+ use_sliding_window (`bool`, *optional*, defaults to `False`):
110
+ Whether to use sliding window attention.
111
+ sliding_window (`int`, *optional*, defaults to 4096):
112
+ Sliding window attention (SWA) window size. If not specified, will default to `4096`.
113
+ attention_dropout (`float`, *optional*, defaults to 0.0):
114
+ The dropout ratio for the attention probabilities.
115
+ decoder_sparse_step (`int`, *optional*, defaults to 1):
116
+ The frequency of the MoE layer.
117
+ moe_intermediate_size (`int`, *optional*, defaults to 768):
118
+ Intermediate size of the routed expert.
119
+ num_experts_per_tok (`int`, *optional*, defaults to 8):
120
+ Number of selected experts.
121
+ num_experts (`int`, *optional*, defaults to 128):
122
+ Number of routed experts.
123
+ norm_topk_prob (`bool`, *optional*, defaults to `False`):
124
+ Whether to normalize the topk probabilities.
125
+ output_router_logits (`bool`, *optional*, defaults to `False`):
126
+ Whether or not the router logits should be returned by the model. Enabling this will also
127
+ allow the model to output the auxiliary loss, including load balancing loss and router z-loss.
128
+ router_aux_loss_coef (`float`, *optional*, defaults to 0.001):
129
+ The aux loss factor for the total loss.
130
+ mlp_only_layers (`list[int]`, *optional*, defaults to `[]`):
131
+ Indicate which layers use Qwen3MoeMLP rather than Qwen3MoeSparseMoeBlock
132
+ The list contains layer index, from 0 to num_layers-1 if we have num_layers layers
133
+ If `mlp_only_layers` is empty, `decoder_sparse_step` is used to determine the sparsity.
134
+
135
+ ```python
136
+ >>> from transformers import Qwen3MoeModel, Qwen3MoeConfig
137
+
138
+ >>> # Initializing a Qwen3MoE style configuration
139
+ >>> configuration = Qwen3MoeConfig()
140
+
141
+ >>> # Initializing a model from the Qwen3-15B-A2B" style configuration
142
+ >>> model = Qwen3MoeModel(configuration)
143
+
144
+ >>> # Accessing the model configuration
145
+ >>> configuration = model.config
146
+ ```"""
147
+
148
+ model_type = "qwen3_moe"
149
+ keys_to_ignore_at_inference = ["past_key_values"]
150
+
151
+ # Default tensor parallel plan for base model `Qwen3Moe`
152
+ base_model_tp_plan = {
153
+ "layers.*.self_attn.q_proj": "colwise",
154
+ "layers.*.self_attn.k_proj": "colwise",
155
+ "layers.*.self_attn.v_proj": "colwise",
156
+ "layers.*.self_attn.o_proj": "rowwise",
157
+ "layers.*.mlp.experts.*.gate_proj": "colwise",
158
+ "layers.*.mlp.experts.*.up_proj": "colwise",
159
+ "layers.*.mlp.experts.*.down_proj": "rowwise",
160
+ "layers.*.mlp.gate_proj": "colwise",
161
+ "layers.*.mlp.up_proj": "colwise",
162
+ "layers.*.mlp.down_proj": "rowwise",
163
+ }
164
+ base_model_pp_plan = {
165
+ "embed_tokens": (["input_ids"], ["inputs_embeds"]),
166
+ "layers": (["hidden_states", "attention_mask"], ["hidden_states"]),
167
+ "norm": (["hidden_states"], ["hidden_states"]),
168
+ }
169
+
170
+ def __init__(
171
+ self,
172
+ vocab_size=151936,
173
+ hidden_size=2048,
174
+ intermediate_size=6144,
175
+ num_hidden_layers=24,
176
+ num_attention_heads=32,
177
+ num_key_value_heads=4,
178
+ hidden_act="silu",
179
+ max_position_embeddings=32768,
180
+ initializer_range=0.02,
181
+ rms_norm_eps=1e-6,
182
+ use_cache=True,
183
+ tie_word_embeddings=False,
184
+ rope_theta=10000.0,
185
+ rope_scaling=None,
186
+ attention_bias=False,
187
+ use_sliding_window=False,
188
+ sliding_window=4096,
189
+ attention_dropout=0.0,
190
+ decoder_sparse_step=1,
191
+ moe_intermediate_size=768,
192
+ num_experts_per_tok=8,
193
+ num_experts=128,
194
+ norm_topk_prob=False,
195
+ output_router_logits=False,
196
+ router_aux_loss_coef=0.001,
197
+ mlp_only_layers=None,
198
+ load_balance_coeff=1e-3,
199
+ **kwargs,
200
+ ):
201
+ self.vocab_size = vocab_size
202
+ self.max_position_embeddings = max_position_embeddings
203
+ self.hidden_size = hidden_size
204
+ self.intermediate_size = intermediate_size
205
+ self.num_hidden_layers = num_hidden_layers
206
+ self.num_attention_heads = num_attention_heads
207
+ self.use_sliding_window = use_sliding_window
208
+ self.sliding_window = sliding_window if use_sliding_window else None
209
+
210
+ self.num_key_value_heads = num_key_value_heads
211
+ self.hidden_act = hidden_act
212
+ self.initializer_range = initializer_range
213
+ self.rms_norm_eps = rms_norm_eps
214
+ self.use_cache = use_cache
215
+ self.rope_theta = rope_theta
216
+ self.rope_scaling = rope_scaling
217
+ self.attention_bias = attention_bias
218
+ self.attention_dropout = attention_dropout
219
+ # Validate the correctness of rotary position embeddings parameters
220
+ # BC: if there is a 'type' field, move it to 'rope_type'.
221
+ if self.rope_scaling is not None and "type" in self.rope_scaling:
222
+ self.rope_scaling["rope_type"] = self.rope_scaling["type"]
223
+ rope_config_validation(self)
224
+
225
+ # MoE arguments
226
+ self.decoder_sparse_step = decoder_sparse_step
227
+ self.moe_intermediate_size = moe_intermediate_size
228
+ self.num_experts_per_tok = num_experts_per_tok
229
+ self.num_experts = num_experts
230
+ self.norm_topk_prob = norm_topk_prob
231
+ self.output_router_logits = output_router_logits
232
+ self.router_aux_loss_coef = router_aux_loss_coef
233
+ self.mlp_only_layers = [] if mlp_only_layers is None else mlp_only_layers
234
+ self.load_balance_coeff = load_balance_coeff
235
+
236
+ super().__init__(
237
+ tie_word_embeddings=tie_word_embeddings,
238
+ **kwargs,
239
+ )
240
+
241
+
242
+ __all__ = ["Qwen3MoeConfig"]
243
+
generation_config.json ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "bos_token_id": 151643,
3
+ "do_sample": true,
4
+ "eos_token_id": [
5
+ 151645,
6
+ 151643
7
+ ],
8
+ "pad_token_id": 151643,
9
+ "temperature": 0.6,
10
+ "top_k": 20,
11
+ "top_p": 0.95,
12
+ "transformers_version": "4.53.0"
13
+ }
merges.txt ADDED
The diff for this file is too large to render. See raw diff
 
model-00001-of-00017.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:cab9f07033dcda74dda82884150b1e948cbe637f37ffdcd3a2f2205a66157309
3
+ size 1244664136
model-00002-of-00017.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0d48bb623e635950c267cbebc7c8afbcd275e5ff4e12bc5a97069508d06defc8
3
+ size 3738727960
model-00003-of-00017.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:57ed41214f9ab6b6d2afaa925571f06db521e721495d3d264056502cdff3c493
3
+ size 3738727960
model-00004-of-00017.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:93df7e6c3a4afb30fb0930f44c4f6708c5b3dcd94a591d1b351c2aaaa5df6c0d
3
+ size 3738727960
model-00005-of-00017.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f6d9ec4c54bb8a7ac83e85c815d0811d842b149a988eae7f29a08bacd60a71c4
3
+ size 3738727984
model-00006-of-00017.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:acb7ecc29778fa2dd370ebcffed0dee249866d2ea36f11215a410ba85fa8aa9b
3
+ size 3738727992
model-00007-of-00017.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ec033a07a762a24c23500110817f0b589a0db2526df2d90d91f8dfb825be911c
3
+ size 3738727992
model-00008-of-00017.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7624d0eba94bb1255f382c0adf2091d3683777c23c79b091d102b7808329cb43
3
+ size 3738727992
model-00009-of-00017.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6c562a2b0c71dcdfa9f6ca6e5bdf4321814ba0055093cc90a9d34904ae993b35
3
+ size 3738727992
model-00010-of-00017.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:953b62a923c82023cf675e644266376c43c2b089f31d08809fa780d3ee4b8719
3
+ size 3738727992
model-00011-of-00017.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:26d0b5cefc55533a0f91e71d90e046d2fd3ad1a4a10bd6009257d08ee0f5285d
3
+ size 3738727992
model-00012-of-00017.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:bd036c7d9a50485a61afef1c28f91033e67613b27b7b97955bd89f14e11c634e
3
+ size 3738727992
model-00013-of-00017.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:90d44b839e3c7cc4d38a02c0ece6958027596d125507d6d311ab1b7dfcd1ee74
3
+ size 3738727992
model-00014-of-00017.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:36bba42c89a95001e28caa75c5b578197139d6f220b19d731e343adc600533f9
3
+ size 3738727992
model-00015-of-00017.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:15c63236cd02eff65295d45bcc9aa32d823186773e03561ddd1b92565af32d84
3
+ size 3738727992
model-00016-of-00017.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6fae2ec67887d1b7f55b6941d20aeeebc0888fe9b1f4b6f75c7f582983377ee7
3
+ size 3738727992
model-00017-of-00017.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8ef0d58901646d5eeb86b04958a48d7b5bf802d2d5dd90430fd47f71cb3387d7
3
+ size 3738727992
model.safetensors.index.json ADDED
@@ -0,0 +1 @@
 
 
1
+ {"metadata": {"total_size": 61064245248}, "weight_map": {"lm_head.weight": "model-00001-of-00017.safetensors", "model.embed_tokens.weight": "model-00001-of-00017.safetensors", "model.norm.weight": "model-00001-of-00017.safetensors", "model.layers.0.input_layernorm.weight": "model-00002-of-00017.safetensors", "model.layers.0.post_attention_layernorm.weight": "model-00002-of-00017.safetensors", "model.layers.0.self_attn.k_norm.weight": "model-00002-of-00017.safetensors", "model.layers.0.self_attn.k_proj.weight": "model-00002-of-00017.safetensors", "model.layers.0.self_attn.o_proj.weight": "model-00002-of-00017.safetensors", "model.layers.0.self_attn.q_norm.weight": "model-00002-of-00017.safetensors", "model.layers.0.self_attn.q_proj.weight": "model-00002-of-00017.safetensors", "model.layers.0.self_attn.v_proj.weight": "model-00002-of-00017.safetensors", "model.layers.0.mlp.router.gate.weight": "model-00002-of-00017.safetensors", "model.layers.0.mlp.experts.w1": "model-00002-of-00017.safetensors", "model.layers.0.mlp.experts.w2": "model-00002-of-00017.safetensors", "model.layers.0.mlp.experts.w3": "model-00002-of-00017.safetensors", "model.layers.1.input_layernorm.weight": "model-00002-of-00017.safetensors", "model.layers.1.post_attention_layernorm.weight": "model-00002-of-00017.safetensors", "model.layers.1.self_attn.k_norm.weight": "model-00002-of-00017.safetensors", "model.layers.1.self_attn.k_proj.weight": "model-00002-of-00017.safetensors", "model.layers.1.self_attn.o_proj.weight": "model-00002-of-00017.safetensors", "model.layers.1.self_attn.q_norm.weight": "model-00002-of-00017.safetensors", "model.layers.1.self_attn.q_proj.weight": "model-00002-of-00017.safetensors", "model.layers.1.self_attn.v_proj.weight": "model-00002-of-00017.safetensors", "model.layers.19.input_layernorm.weight": "model-00008-of-00017.safetensors", "model.layers.19.post_attention_layernorm.weight": "model-00008-of-00017.safetensors", "model.layers.10.input_layernorm.weight": "model-00005-of-00017.safetensors", "model.layers.10.post_attention_layernorm.weight": "model-00005-of-00017.safetensors", "model.layers.10.self_attn.k_norm.weight": "model-00005-of-00017.safetensors", "model.layers.10.self_attn.k_proj.weight": "model-00005-of-00017.safetensors", "model.layers.10.self_attn.o_proj.weight": "model-00005-of-00017.safetensors", "model.layers.10.self_attn.q_norm.weight": "model-00005-of-00017.safetensors", "model.layers.10.self_attn.q_proj.weight": "model-00005-of-00017.safetensors", "model.layers.10.self_attn.v_proj.weight": "model-00005-of-00017.safetensors", "model.layers.11.self_attn.k_norm.weight": "model-00005-of-00017.safetensors", "model.layers.11.self_attn.k_proj.weight": "model-00005-of-00017.safetensors", "model.layers.11.self_attn.o_proj.weight": "model-00005-of-00017.safetensors", "model.layers.11.self_attn.q_norm.weight": "model-00005-of-00017.safetensors", "model.layers.11.self_attn.q_proj.weight": "model-00005-of-00017.safetensors", "model.layers.11.self_attn.v_proj.weight": "model-00005-of-00017.safetensors", "model.layers.11.input_layernorm.weight": "model-00005-of-00017.safetensors", "model.layers.11.post_attention_layernorm.weight": "model-00005-of-00017.safetensors", "model.layers.12.input_layernorm.weight": "model-00006-of-00017.safetensors", "model.layers.12.post_attention_layernorm.weight": "model-00006-of-00017.safetensors", "model.layers.12.self_attn.k_norm.weight": "model-00006-of-00017.safetensors", "model.layers.12.self_attn.k_proj.weight": "model-00006-of-00017.safetensors", "model.layers.12.self_attn.o_proj.weight": "model-00006-of-00017.safetensors", "model.layers.12.self_attn.q_norm.weight": "model-00006-of-00017.safetensors", "model.layers.12.self_attn.q_proj.weight": "model-00006-of-00017.safetensors", "model.layers.12.self_attn.v_proj.weight": "model-00006-of-00017.safetensors", "model.layers.13.input_layernorm.weight": "model-00006-of-00017.safetensors", "model.layers.13.post_attention_layernorm.weight": "model-00006-of-00017.safetensors", "model.layers.13.self_attn.k_norm.weight": "model-00006-of-00017.safetensors", "model.layers.13.self_attn.k_proj.weight": "model-00006-of-00017.safetensors", "model.layers.13.self_attn.o_proj.weight": "model-00006-of-00017.safetensors", "model.layers.13.self_attn.q_norm.weight": "model-00006-of-00017.safetensors", "model.layers.13.self_attn.q_proj.weight": "model-00006-of-00017.safetensors", "model.layers.13.self_attn.v_proj.weight": "model-00006-of-00017.safetensors", "model.layers.14.input_layernorm.weight": "model-00006-of-00017.safetensors", "model.layers.14.post_attention_layernorm.weight": "model-00006-of-00017.safetensors", "model.layers.14.self_attn.k_norm.weight": "model-00006-of-00017.safetensors", "model.layers.14.self_attn.k_proj.weight": "model-00006-of-00017.safetensors", "model.layers.14.self_attn.o_proj.weight": "model-00006-of-00017.safetensors", "model.layers.14.self_attn.q_norm.weight": "model-00006-of-00017.safetensors", "model.layers.14.self_attn.q_proj.weight": "model-00006-of-00017.safetensors", "model.layers.14.self_attn.v_proj.weight": "model-00006-of-00017.safetensors", "model.layers.15.self_attn.k_norm.weight": "model-00007-of-00017.safetensors", "model.layers.15.self_attn.k_proj.weight": "model-00007-of-00017.safetensors", "model.layers.15.self_attn.o_proj.weight": "model-00007-of-00017.safetensors", "model.layers.15.self_attn.q_norm.weight": "model-00007-of-00017.safetensors", "model.layers.15.self_attn.q_proj.weight": "model-00007-of-00017.safetensors", "model.layers.15.self_attn.v_proj.weight": "model-00007-of-00017.safetensors", "model.layers.15.input_layernorm.weight": "model-00007-of-00017.safetensors", "model.layers.15.post_attention_layernorm.weight": "model-00007-of-00017.safetensors", "model.layers.16.input_layernorm.weight": "model-00007-of-00017.safetensors", "model.layers.16.post_attention_layernorm.weight": "model-00007-of-00017.safetensors", "model.layers.16.self_attn.k_norm.weight": "model-00007-of-00017.safetensors", "model.layers.16.self_attn.k_proj.weight": "model-00007-of-00017.safetensors", "model.layers.16.self_attn.o_proj.weight": "model-00007-of-00017.safetensors", "model.layers.16.self_attn.q_norm.weight": "model-00007-of-00017.safetensors", "model.layers.16.self_attn.q_proj.weight": "model-00007-of-00017.safetensors", "model.layers.16.self_attn.v_proj.weight": "model-00007-of-00017.safetensors", "model.layers.17.input_layernorm.weight": "model-00007-of-00017.safetensors", "model.layers.17.post_attention_layernorm.weight": "model-00007-of-00017.safetensors", "model.layers.17.self_attn.k_norm.weight": "model-00007-of-00017.safetensors", "model.layers.17.self_attn.k_proj.weight": "model-00007-of-00017.safetensors", "model.layers.17.self_attn.o_proj.weight": "model-00007-of-00017.safetensors", "model.layers.17.self_attn.q_norm.weight": "model-00007-of-00017.safetensors", "model.layers.17.self_attn.q_proj.weight": "model-00007-of-00017.safetensors", "model.layers.17.self_attn.v_proj.weight": "model-00007-of-00017.safetensors", "model.layers.18.input_layernorm.weight": "model-00008-of-00017.safetensors", "model.layers.18.post_attention_layernorm.weight": "model-00008-of-00017.safetensors", "model.layers.18.self_attn.k_norm.weight": "model-00008-of-00017.safetensors", "model.layers.18.self_attn.k_proj.weight": "model-00008-of-00017.safetensors", "model.layers.18.self_attn.o_proj.weight": "model-00008-of-00017.safetensors", "model.layers.18.self_attn.q_norm.weight": "model-00008-of-00017.safetensors", "model.layers.18.self_attn.q_proj.weight": "model-00008-of-00017.safetensors", "model.layers.18.self_attn.v_proj.weight": "model-00008-of-00017.safetensors", "model.layers.19.self_attn.k_norm.weight": "model-00008-of-00017.safetensors", "model.layers.19.self_attn.k_proj.weight": "model-00008-of-00017.safetensors", "model.layers.19.self_attn.o_proj.weight": "model-00008-of-00017.safetensors", "model.layers.19.self_attn.q_norm.weight": "model-00008-of-00017.safetensors", "model.layers.19.self_attn.q_proj.weight": "model-00008-of-00017.safetensors", "model.layers.19.self_attn.v_proj.weight": "model-00008-of-00017.safetensors", "model.layers.1.mlp.router.gate.weight": "model-00002-of-00017.safetensors", "model.layers.1.mlp.experts.w1": "model-00002-of-00017.safetensors", "model.layers.1.mlp.experts.w2": "model-00002-of-00017.safetensors", "model.layers.1.mlp.experts.w3": "model-00002-of-00017.safetensors", "model.layers.10.mlp.router.gate.weight": "model-00005-of-00017.safetensors", "model.layers.10.mlp.experts.w1": "model-00005-of-00017.safetensors", "model.layers.10.mlp.experts.w2": "model-00005-of-00017.safetensors", "model.layers.10.mlp.experts.w3": "model-00005-of-00017.safetensors", "model.layers.11.mlp.router.gate.weight": "model-00005-of-00017.safetensors", "model.layers.11.mlp.experts.w1": "model-00005-of-00017.safetensors", "model.layers.11.mlp.experts.w2": "model-00005-of-00017.safetensors", "model.layers.11.mlp.experts.w3": "model-00005-of-00017.safetensors", "model.layers.12.mlp.router.gate.weight": "model-00006-of-00017.safetensors", "model.layers.12.mlp.experts.w1": "model-00006-of-00017.safetensors", "model.layers.12.mlp.experts.w2": "model-00006-of-00017.safetensors", "model.layers.12.mlp.experts.w3": "model-00006-of-00017.safetensors", "model.layers.13.mlp.router.gate.weight": "model-00006-of-00017.safetensors", "model.layers.13.mlp.experts.w1": "model-00006-of-00017.safetensors", "model.layers.13.mlp.experts.w2": "model-00006-of-00017.safetensors", "model.layers.13.mlp.experts.w3": "model-00006-of-00017.safetensors", "model.layers.14.mlp.router.gate.weight": "model-00006-of-00017.safetensors", "model.layers.14.mlp.experts.w1": "model-00006-of-00017.safetensors", "model.layers.14.mlp.experts.w2": "model-00006-of-00017.safetensors", "model.layers.14.mlp.experts.w3": "model-00006-of-00017.safetensors", "model.layers.15.mlp.router.gate.weight": "model-00007-of-00017.safetensors", "model.layers.15.mlp.experts.w1": "model-00007-of-00017.safetensors", "model.layers.15.mlp.experts.w2": "model-00007-of-00017.safetensors", "model.layers.15.mlp.experts.w3": "model-00007-of-00017.safetensors", "model.layers.16.mlp.router.gate.weight": "model-00007-of-00017.safetensors", "model.layers.16.mlp.experts.w1": "model-00007-of-00017.safetensors", "model.layers.16.mlp.experts.w2": "model-00007-of-00017.safetensors", "model.layers.16.mlp.experts.w3": "model-00007-of-00017.safetensors", "model.layers.17.mlp.router.gate.weight": "model-00007-of-00017.safetensors", "model.layers.17.mlp.experts.w1": "model-00007-of-00017.safetensors", "model.layers.17.mlp.experts.w2": "model-00007-of-00017.safetensors", "model.layers.17.mlp.experts.w3": "model-00007-of-00017.safetensors", "model.layers.18.mlp.router.gate.weight": "model-00008-of-00017.safetensors", "model.layers.18.mlp.experts.w1": "model-00008-of-00017.safetensors", "model.layers.18.mlp.experts.w2": "model-00008-of-00017.safetensors", "model.layers.18.mlp.experts.w3": "model-00008-of-00017.safetensors", "model.layers.19.mlp.router.gate.weight": "model-00008-of-00017.safetensors", "model.layers.19.mlp.experts.w1": "model-00008-of-00017.safetensors", "model.layers.19.mlp.experts.w2": "model-00008-of-00017.safetensors", "model.layers.19.mlp.experts.w3": "model-00008-of-00017.safetensors", "model.layers.2.input_layernorm.weight": "model-00002-of-00017.safetensors", "model.layers.2.post_attention_layernorm.weight": "model-00002-of-00017.safetensors", "model.layers.2.self_attn.k_norm.weight": "model-00002-of-00017.safetensors", "model.layers.2.self_attn.k_proj.weight": "model-00002-of-00017.safetensors", "model.layers.2.self_attn.o_proj.weight": "model-00002-of-00017.safetensors", "model.layers.2.self_attn.q_norm.weight": "model-00002-of-00017.safetensors", "model.layers.2.self_attn.q_proj.weight": "model-00002-of-00017.safetensors", "model.layers.2.self_attn.v_proj.weight": "model-00002-of-00017.safetensors", "model.layers.20.input_layernorm.weight": "model-00008-of-00017.safetensors", "model.layers.20.post_attention_layernorm.weight": "model-00008-of-00017.safetensors", "model.layers.20.self_attn.k_norm.weight": "model-00008-of-00017.safetensors", "model.layers.20.self_attn.k_proj.weight": "model-00008-of-00017.safetensors", "model.layers.20.self_attn.o_proj.weight": "model-00008-of-00017.safetensors", "model.layers.20.self_attn.q_norm.weight": "model-00008-of-00017.safetensors", "model.layers.20.self_attn.q_proj.weight": "model-00008-of-00017.safetensors", "model.layers.20.self_attn.v_proj.weight": "model-00008-of-00017.safetensors", "model.layers.21.input_layernorm.weight": "model-00009-of-00017.safetensors", "model.layers.21.post_attention_layernorm.weight": "model-00009-of-00017.safetensors", "model.layers.21.self_attn.k_norm.weight": "model-00009-of-00017.safetensors", "model.layers.21.self_attn.k_proj.weight": "model-00009-of-00017.safetensors", "model.layers.21.self_attn.o_proj.weight": "model-00009-of-00017.safetensors", "model.layers.21.self_attn.q_norm.weight": "model-00009-of-00017.safetensors", "model.layers.21.self_attn.q_proj.weight": "model-00009-of-00017.safetensors", "model.layers.21.self_attn.v_proj.weight": "model-00009-of-00017.safetensors", "model.layers.22.input_layernorm.weight": "model-00009-of-00017.safetensors", "model.layers.22.post_attention_layernorm.weight": "model-00009-of-00017.safetensors", "model.layers.22.self_attn.k_norm.weight": "model-00009-of-00017.safetensors", "model.layers.22.self_attn.k_proj.weight": "model-00009-of-00017.safetensors", "model.layers.22.self_attn.o_proj.weight": "model-00009-of-00017.safetensors", "model.layers.22.self_attn.q_norm.weight": "model-00009-of-00017.safetensors", "model.layers.22.self_attn.q_proj.weight": "model-00009-of-00017.safetensors", "model.layers.22.self_attn.v_proj.weight": "model-00009-of-00017.safetensors", "model.layers.23.self_attn.k_norm.weight": "model-00009-of-00017.safetensors", "model.layers.23.self_attn.k_proj.weight": "model-00009-of-00017.safetensors", "model.layers.23.self_attn.o_proj.weight": "model-00009-of-00017.safetensors", "model.layers.23.self_attn.q_norm.weight": "model-00009-of-00017.safetensors", "model.layers.23.self_attn.q_proj.weight": "model-00009-of-00017.safetensors", "model.layers.23.self_attn.v_proj.weight": "model-00009-of-00017.safetensors", "model.layers.23.input_layernorm.weight": "model-00009-of-00017.safetensors", "model.layers.23.post_attention_layernorm.weight": "model-00009-of-00017.safetensors", "model.layers.24.input_layernorm.weight": "model-00010-of-00017.safetensors", "model.layers.24.post_attention_layernorm.weight": "model-00010-of-00017.safetensors", "model.layers.24.self_attn.k_norm.weight": "model-00010-of-00017.safetensors", "model.layers.24.self_attn.k_proj.weight": "model-00010-of-00017.safetensors", "model.layers.24.self_attn.o_proj.weight": "model-00010-of-00017.safetensors", "model.layers.24.self_attn.q_norm.weight": "model-00010-of-00017.safetensors", "model.layers.24.self_attn.q_proj.weight": "model-00010-of-00017.safetensors", "model.layers.24.self_attn.v_proj.weight": "model-00010-of-00017.safetensors", "model.layers.25.input_layernorm.weight": "model-00010-of-00017.safetensors", "model.layers.25.post_attention_layernorm.weight": "model-00010-of-00017.safetensors", "model.layers.25.self_attn.k_norm.weight": "model-00010-of-00017.safetensors", "model.layers.25.self_attn.k_proj.weight": "model-00010-of-00017.safetensors", "model.layers.25.self_attn.o_proj.weight": "model-00010-of-00017.safetensors", "model.layers.25.self_attn.q_norm.weight": "model-00010-of-00017.safetensors", "model.layers.25.self_attn.q_proj.weight": "model-00010-of-00017.safetensors", "model.layers.25.self_attn.v_proj.weight": "model-00010-of-00017.safetensors", "model.layers.26.input_layernorm.weight": "model-00010-of-00017.safetensors", "model.layers.26.post_attention_layernorm.weight": "model-00010-of-00017.safetensors", "model.layers.26.self_attn.k_norm.weight": "model-00010-of-00017.safetensors", "model.layers.26.self_attn.k_proj.weight": "model-00010-of-00017.safetensors", "model.layers.26.self_attn.o_proj.weight": "model-00010-of-00017.safetensors", "model.layers.26.self_attn.q_norm.weight": "model-00010-of-00017.safetensors", "model.layers.26.self_attn.q_proj.weight": "model-00010-of-00017.safetensors", "model.layers.26.self_attn.v_proj.weight": "model-00010-of-00017.safetensors", "model.layers.27.self_attn.k_norm.weight": "model-00011-of-00017.safetensors", "model.layers.27.self_attn.k_proj.weight": "model-00011-of-00017.safetensors", "model.layers.27.self_attn.o_proj.weight": "model-00011-of-00017.safetensors", "model.layers.27.self_attn.q_norm.weight": "model-00011-of-00017.safetensors", "model.layers.27.self_attn.q_proj.weight": "model-00011-of-00017.safetensors", "model.layers.27.self_attn.v_proj.weight": "model-00011-of-00017.safetensors", "model.layers.27.input_layernorm.weight": "model-00011-of-00017.safetensors", "model.layers.27.post_attention_layernorm.weight": "model-00011-of-00017.safetensors", "model.layers.28.input_layernorm.weight": "model-00011-of-00017.safetensors", "model.layers.28.post_attention_layernorm.weight": "model-00011-of-00017.safetensors", "model.layers.28.self_attn.k_norm.weight": "model-00011-of-00017.safetensors", "model.layers.28.self_attn.k_proj.weight": "model-00011-of-00017.safetensors", "model.layers.28.self_attn.o_proj.weight": "model-00011-of-00017.safetensors", "model.layers.28.self_attn.q_norm.weight": "model-00011-of-00017.safetensors", "model.layers.28.self_attn.q_proj.weight": "model-00011-of-00017.safetensors", "model.layers.28.self_attn.v_proj.weight": "model-00011-of-00017.safetensors", "model.layers.29.input_layernorm.weight": "model-00011-of-00017.safetensors", "model.layers.29.post_attention_layernorm.weight": "model-00011-of-00017.safetensors", "model.layers.29.self_attn.k_norm.weight": "model-00011-of-00017.safetensors", "model.layers.29.self_attn.k_proj.weight": "model-00011-of-00017.safetensors", "model.layers.29.self_attn.o_proj.weight": "model-00011-of-00017.safetensors", "model.layers.29.self_attn.q_norm.weight": "model-00011-of-00017.safetensors", "model.layers.29.self_attn.q_proj.weight": "model-00011-of-00017.safetensors", "model.layers.29.self_attn.v_proj.weight": "model-00011-of-00017.safetensors", "model.layers.2.mlp.router.gate.weight": "model-00002-of-00017.safetensors", "model.layers.2.mlp.experts.w1": "model-00002-of-00017.safetensors", "model.layers.2.mlp.experts.w2": "model-00002-of-00017.safetensors", "model.layers.2.mlp.experts.w3": "model-00002-of-00017.safetensors", "model.layers.20.mlp.router.gate.weight": "model-00008-of-00017.safetensors", "model.layers.20.mlp.experts.w1": "model-00008-of-00017.safetensors", "model.layers.20.mlp.experts.w2": "model-00008-of-00017.safetensors", "model.layers.20.mlp.experts.w3": "model-00008-of-00017.safetensors", "model.layers.21.mlp.router.gate.weight": "model-00009-of-00017.safetensors", "model.layers.21.mlp.experts.w1": "model-00009-of-00017.safetensors", "model.layers.21.mlp.experts.w2": "model-00009-of-00017.safetensors", "model.layers.21.mlp.experts.w3": "model-00009-of-00017.safetensors", "model.layers.22.mlp.router.gate.weight": "model-00009-of-00017.safetensors", "model.layers.22.mlp.experts.w1": "model-00009-of-00017.safetensors", "model.layers.22.mlp.experts.w2": "model-00009-of-00017.safetensors", "model.layers.22.mlp.experts.w3": "model-00009-of-00017.safetensors", "model.layers.23.mlp.router.gate.weight": "model-00009-of-00017.safetensors", "model.layers.23.mlp.experts.w1": "model-00009-of-00017.safetensors", "model.layers.23.mlp.experts.w2": "model-00009-of-00017.safetensors", "model.layers.23.mlp.experts.w3": "model-00009-of-00017.safetensors", "model.layers.24.mlp.router.gate.weight": "model-00010-of-00017.safetensors", "model.layers.24.mlp.experts.w1": "model-00010-of-00017.safetensors", "model.layers.24.mlp.experts.w2": "model-00010-of-00017.safetensors", "model.layers.24.mlp.experts.w3": "model-00010-of-00017.safetensors", "model.layers.25.mlp.router.gate.weight": "model-00010-of-00017.safetensors", "model.layers.25.mlp.experts.w1": "model-00010-of-00017.safetensors", "model.layers.25.mlp.experts.w2": "model-00010-of-00017.safetensors", "model.layers.25.mlp.experts.w3": "model-00010-of-00017.safetensors", "model.layers.26.mlp.router.gate.weight": "model-00010-of-00017.safetensors", "model.layers.26.mlp.experts.w1": "model-00010-of-00017.safetensors", "model.layers.26.mlp.experts.w2": "model-00010-of-00017.safetensors", "model.layers.26.mlp.experts.w3": "model-00010-of-00017.safetensors", "model.layers.27.mlp.router.gate.weight": "model-00011-of-00017.safetensors", "model.layers.27.mlp.experts.w1": "model-00011-of-00017.safetensors", "model.layers.27.mlp.experts.w2": "model-00011-of-00017.safetensors", "model.layers.27.mlp.experts.w3": "model-00011-of-00017.safetensors", "model.layers.28.mlp.router.gate.weight": "model-00011-of-00017.safetensors", "model.layers.28.mlp.experts.w1": "model-00011-of-00017.safetensors", "model.layers.28.mlp.experts.w2": "model-00011-of-00017.safetensors", "model.layers.28.mlp.experts.w3": "model-00011-of-00017.safetensors", "model.layers.29.mlp.router.gate.weight": "model-00011-of-00017.safetensors", "model.layers.29.mlp.experts.w1": "model-00011-of-00017.safetensors", "model.layers.29.mlp.experts.w2": "model-00011-of-00017.safetensors", "model.layers.29.mlp.experts.w3": "model-00011-of-00017.safetensors", "model.layers.3.self_attn.k_norm.weight": "model-00003-of-00017.safetensors", "model.layers.3.self_attn.k_proj.weight": "model-00003-of-00017.safetensors", "model.layers.3.self_attn.o_proj.weight": "model-00003-of-00017.safetensors", "model.layers.3.self_attn.q_norm.weight": "model-00003-of-00017.safetensors", "model.layers.3.self_attn.q_proj.weight": "model-00003-of-00017.safetensors", "model.layers.3.self_attn.v_proj.weight": "model-00003-of-00017.safetensors", "model.layers.35.input_layernorm.weight": "model-00013-of-00017.safetensors", "model.layers.35.post_attention_layernorm.weight": "model-00013-of-00017.safetensors", "model.layers.36.input_layernorm.weight": "model-00014-of-00017.safetensors", "model.layers.36.post_attention_layernorm.weight": "model-00014-of-00017.safetensors", "model.layers.36.self_attn.k_norm.weight": "model-00014-of-00017.safetensors", "model.layers.36.self_attn.k_proj.weight": "model-00014-of-00017.safetensors", "model.layers.36.self_attn.o_proj.weight": "model-00014-of-00017.safetensors", "model.layers.36.self_attn.q_norm.weight": "model-00014-of-00017.safetensors", "model.layers.36.self_attn.q_proj.weight": "model-00014-of-00017.safetensors", "model.layers.36.self_attn.v_proj.weight": "model-00014-of-00017.safetensors", "model.layers.37.input_layernorm.weight": "model-00014-of-00017.safetensors", "model.layers.37.post_attention_layernorm.weight": "model-00014-of-00017.safetensors", "model.layers.37.self_attn.k_norm.weight": "model-00014-of-00017.safetensors", "model.layers.37.self_attn.k_proj.weight": "model-00014-of-00017.safetensors", "model.layers.37.self_attn.o_proj.weight": "model-00014-of-00017.safetensors", "model.layers.37.self_attn.q_norm.weight": "model-00014-of-00017.safetensors", "model.layers.37.self_attn.q_proj.weight": "model-00014-of-00017.safetensors", "model.layers.37.self_attn.v_proj.weight": "model-00014-of-00017.safetensors", "model.layers.38.input_layernorm.weight": "model-00014-of-00017.safetensors", "model.layers.38.post_attention_layernorm.weight": "model-00014-of-00017.safetensors", "model.layers.38.self_attn.k_norm.weight": "model-00014-of-00017.safetensors", "model.layers.38.self_attn.k_proj.weight": "model-00014-of-00017.safetensors", "model.layers.38.self_attn.o_proj.weight": "model-00014-of-00017.safetensors", "model.layers.38.self_attn.q_norm.weight": "model-00014-of-00017.safetensors", "model.layers.38.self_attn.q_proj.weight": "model-00014-of-00017.safetensors", "model.layers.38.self_attn.v_proj.weight": "model-00014-of-00017.safetensors", "model.layers.39.self_attn.k_norm.weight": "model-00015-of-00017.safetensors", "model.layers.39.self_attn.k_proj.weight": "model-00015-of-00017.safetensors", "model.layers.39.self_attn.o_proj.weight": "model-00015-of-00017.safetensors", "model.layers.39.self_attn.q_norm.weight": "model-00015-of-00017.safetensors", "model.layers.39.self_attn.q_proj.weight": "model-00015-of-00017.safetensors", "model.layers.39.self_attn.v_proj.weight": "model-00015-of-00017.safetensors", "model.layers.31.input_layernorm.weight": "model-00012-of-00017.safetensors", "model.layers.31.post_attention_layernorm.weight": "model-00012-of-00017.safetensors", "model.layers.32.input_layernorm.weight": "model-00012-of-00017.safetensors", "model.layers.32.post_attention_layernorm.weight": "model-00012-of-00017.safetensors", "model.layers.32.self_attn.k_norm.weight": "model-00012-of-00017.safetensors", "model.layers.32.self_attn.k_proj.weight": "model-00012-of-00017.safetensors", "model.layers.32.self_attn.o_proj.weight": "model-00012-of-00017.safetensors", "model.layers.32.self_attn.q_norm.weight": "model-00012-of-00017.safetensors", "model.layers.32.self_attn.q_proj.weight": "model-00012-of-00017.safetensors", "model.layers.32.self_attn.v_proj.weight": "model-00012-of-00017.safetensors", "model.layers.33.input_layernorm.weight": "model-00013-of-00017.safetensors", "model.layers.33.post_attention_layernorm.weight": "model-00013-of-00017.safetensors", "model.layers.33.self_attn.k_norm.weight": "model-00013-of-00017.safetensors", "model.layers.33.self_attn.k_proj.weight": "model-00013-of-00017.safetensors", "model.layers.33.self_attn.o_proj.weight": "model-00013-of-00017.safetensors", "model.layers.33.self_attn.q_norm.weight": "model-00013-of-00017.safetensors", "model.layers.33.self_attn.q_proj.weight": "model-00013-of-00017.safetensors", "model.layers.33.self_attn.v_proj.weight": "model-00013-of-00017.safetensors", "model.layers.34.input_layernorm.weight": "model-00013-of-00017.safetensors", "model.layers.34.post_attention_layernorm.weight": "model-00013-of-00017.safetensors", "model.layers.34.self_attn.k_norm.weight": "model-00013-of-00017.safetensors", "model.layers.34.self_attn.k_proj.weight": "model-00013-of-00017.safetensors", "model.layers.34.self_attn.o_proj.weight": "model-00013-of-00017.safetensors", "model.layers.34.self_attn.q_norm.weight": "model-00013-of-00017.safetensors", "model.layers.34.self_attn.q_proj.weight": "model-00013-of-00017.safetensors", "model.layers.34.self_attn.v_proj.weight": "model-00013-of-00017.safetensors", "model.layers.35.self_attn.k_norm.weight": "model-00013-of-00017.safetensors", "model.layers.35.self_attn.k_proj.weight": "model-00013-of-00017.safetensors", "model.layers.35.self_attn.o_proj.weight": "model-00013-of-00017.safetensors", "model.layers.35.self_attn.q_norm.weight": "model-00013-of-00017.safetensors", "model.layers.35.self_attn.q_proj.weight": "model-00013-of-00017.safetensors", "model.layers.35.self_attn.v_proj.weight": "model-00013-of-00017.safetensors", "model.layers.3.input_layernorm.weight": "model-00003-of-00017.safetensors", "model.layers.3.post_attention_layernorm.weight": "model-00003-of-00017.safetensors", "model.layers.39.input_layernorm.weight": "model-00015-of-00017.safetensors", "model.layers.39.post_attention_layernorm.weight": "model-00015-of-00017.safetensors", "model.layers.30.input_layernorm.weight": "model-00012-of-00017.safetensors", "model.layers.30.post_attention_layernorm.weight": "model-00012-of-00017.safetensors", "model.layers.30.self_attn.k_norm.weight": "model-00012-of-00017.safetensors", "model.layers.30.self_attn.k_proj.weight": "model-00012-of-00017.safetensors", "model.layers.30.self_attn.o_proj.weight": "model-00012-of-00017.safetensors", "model.layers.30.self_attn.q_norm.weight": "model-00012-of-00017.safetensors", "model.layers.30.self_attn.q_proj.weight": "model-00012-of-00017.safetensors", "model.layers.30.self_attn.v_proj.weight": "model-00012-of-00017.safetensors", "model.layers.31.self_attn.k_norm.weight": "model-00012-of-00017.safetensors", "model.layers.31.self_attn.k_proj.weight": "model-00012-of-00017.safetensors", "model.layers.31.self_attn.o_proj.weight": "model-00012-of-00017.safetensors", "model.layers.31.self_attn.q_norm.weight": "model-00012-of-00017.safetensors", "model.layers.31.self_attn.q_proj.weight": "model-00012-of-00017.safetensors", "model.layers.31.self_attn.v_proj.weight": "model-00012-of-00017.safetensors", "model.layers.3.mlp.router.gate.weight": "model-00003-of-00017.safetensors", "model.layers.3.mlp.experts.w1": "model-00003-of-00017.safetensors", "model.layers.3.mlp.experts.w2": "model-00003-of-00017.safetensors", "model.layers.3.mlp.experts.w3": "model-00003-of-00017.safetensors", "model.layers.30.mlp.router.gate.weight": "model-00012-of-00017.safetensors", "model.layers.30.mlp.experts.w1": "model-00012-of-00017.safetensors", "model.layers.30.mlp.experts.w2": "model-00012-of-00017.safetensors", "model.layers.30.mlp.experts.w3": "model-00012-of-00017.safetensors", "model.layers.31.mlp.router.gate.weight": "model-00012-of-00017.safetensors", "model.layers.31.mlp.experts.w1": "model-00012-of-00017.safetensors", "model.layers.31.mlp.experts.w2": "model-00012-of-00017.safetensors", "model.layers.31.mlp.experts.w3": "model-00012-of-00017.safetensors", "model.layers.32.mlp.router.gate.weight": "model-00012-of-00017.safetensors", "model.layers.32.mlp.experts.w1": "model-00012-of-00017.safetensors", "model.layers.32.mlp.experts.w2": "model-00012-of-00017.safetensors", "model.layers.32.mlp.experts.w3": "model-00012-of-00017.safetensors", "model.layers.33.mlp.router.gate.weight": "model-00013-of-00017.safetensors", "model.layers.33.mlp.experts.w1": "model-00013-of-00017.safetensors", "model.layers.33.mlp.experts.w2": "model-00013-of-00017.safetensors", "model.layers.33.mlp.experts.w3": "model-00013-of-00017.safetensors", "model.layers.34.mlp.router.gate.weight": "model-00013-of-00017.safetensors", "model.layers.34.mlp.experts.w1": "model-00013-of-00017.safetensors", "model.layers.34.mlp.experts.w2": "model-00013-of-00017.safetensors", "model.layers.34.mlp.experts.w3": "model-00013-of-00017.safetensors", "model.layers.35.mlp.router.gate.weight": "model-00013-of-00017.safetensors", "model.layers.35.mlp.experts.w1": "model-00013-of-00017.safetensors", "model.layers.35.mlp.experts.w2": "model-00013-of-00017.safetensors", "model.layers.35.mlp.experts.w3": "model-00013-of-00017.safetensors", "model.layers.36.mlp.router.gate.weight": "model-00014-of-00017.safetensors", "model.layers.36.mlp.experts.w1": "model-00014-of-00017.safetensors", "model.layers.36.mlp.experts.w2": "model-00014-of-00017.safetensors", "model.layers.36.mlp.experts.w3": "model-00014-of-00017.safetensors", "model.layers.37.mlp.router.gate.weight": "model-00014-of-00017.safetensors", "model.layers.37.mlp.experts.w1": "model-00014-of-00017.safetensors", "model.layers.37.mlp.experts.w2": "model-00014-of-00017.safetensors", "model.layers.37.mlp.experts.w3": "model-00014-of-00017.safetensors", "model.layers.38.mlp.router.gate.weight": "model-00014-of-00017.safetensors", "model.layers.38.mlp.experts.w1": "model-00014-of-00017.safetensors", "model.layers.38.mlp.experts.w2": "model-00014-of-00017.safetensors", "model.layers.38.mlp.experts.w3": "model-00014-of-00017.safetensors", "model.layers.39.mlp.router.gate.weight": "model-00015-of-00017.safetensors", "model.layers.39.mlp.experts.w1": "model-00015-of-00017.safetensors", "model.layers.39.mlp.experts.w2": "model-00015-of-00017.safetensors", "model.layers.39.mlp.experts.w3": "model-00015-of-00017.safetensors", "model.layers.43.input_layernorm.weight": "model-00016-of-00017.safetensors", "model.layers.43.post_attention_layernorm.weight": "model-00016-of-00017.safetensors", "model.layers.44.input_layernorm.weight": "model-00016-of-00017.safetensors", "model.layers.44.post_attention_layernorm.weight": "model-00016-of-00017.safetensors", "model.layers.44.self_attn.k_norm.weight": "model-00016-of-00017.safetensors", "model.layers.44.self_attn.k_proj.weight": "model-00016-of-00017.safetensors", "model.layers.44.self_attn.o_proj.weight": "model-00016-of-00017.safetensors", "model.layers.44.self_attn.q_norm.weight": "model-00016-of-00017.safetensors", "model.layers.44.self_attn.q_proj.weight": "model-00016-of-00017.safetensors", "model.layers.44.self_attn.v_proj.weight": "model-00016-of-00017.safetensors", "model.layers.45.input_layernorm.weight": "model-00017-of-00017.safetensors", "model.layers.45.post_attention_layernorm.weight": "model-00017-of-00017.safetensors", "model.layers.45.self_attn.k_norm.weight": "model-00017-of-00017.safetensors", "model.layers.45.self_attn.k_proj.weight": "model-00017-of-00017.safetensors", "model.layers.45.self_attn.o_proj.weight": "model-00017-of-00017.safetensors", "model.layers.45.self_attn.q_norm.weight": "model-00017-of-00017.safetensors", "model.layers.45.self_attn.q_proj.weight": "model-00017-of-00017.safetensors", "model.layers.45.self_attn.v_proj.weight": "model-00017-of-00017.safetensors", "model.layers.46.input_layernorm.weight": "model-00017-of-00017.safetensors", "model.layers.46.post_attention_layernorm.weight": "model-00017-of-00017.safetensors", "model.layers.46.self_attn.k_norm.weight": "model-00017-of-00017.safetensors", "model.layers.46.self_attn.k_proj.weight": "model-00017-of-00017.safetensors", "model.layers.46.self_attn.o_proj.weight": "model-00017-of-00017.safetensors", "model.layers.46.self_attn.q_norm.weight": "model-00017-of-00017.safetensors", "model.layers.46.self_attn.q_proj.weight": "model-00017-of-00017.safetensors", "model.layers.46.self_attn.v_proj.weight": "model-00017-of-00017.safetensors", "model.layers.47.self_attn.k_norm.weight": "model-00017-of-00017.safetensors", "model.layers.47.self_attn.k_proj.weight": "model-00017-of-00017.safetensors", "model.layers.47.self_attn.o_proj.weight": "model-00017-of-00017.safetensors", "model.layers.47.self_attn.q_norm.weight": "model-00017-of-00017.safetensors", "model.layers.47.self_attn.q_proj.weight": "model-00017-of-00017.safetensors", "model.layers.47.self_attn.v_proj.weight": "model-00017-of-00017.safetensors", "model.layers.47.input_layernorm.weight": "model-00017-of-00017.safetensors", "model.layers.47.post_attention_layernorm.weight": "model-00017-of-00017.safetensors", "model.layers.4.input_layernorm.weight": "model-00003-of-00017.safetensors", "model.layers.4.post_attention_layernorm.weight": "model-00003-of-00017.safetensors", "model.layers.4.self_attn.k_norm.weight": "model-00003-of-00017.safetensors", "model.layers.4.self_attn.k_proj.weight": "model-00003-of-00017.safetensors", "model.layers.4.self_attn.o_proj.weight": "model-00003-of-00017.safetensors", "model.layers.4.self_attn.q_norm.weight": "model-00003-of-00017.safetensors", "model.layers.4.self_attn.q_proj.weight": "model-00003-of-00017.safetensors", "model.layers.4.self_attn.v_proj.weight": "model-00003-of-00017.safetensors", "model.layers.40.input_layernorm.weight": "model-00015-of-00017.safetensors", "model.layers.40.post_attention_layernorm.weight": "model-00015-of-00017.safetensors", "model.layers.40.self_attn.k_norm.weight": "model-00015-of-00017.safetensors", "model.layers.40.self_attn.k_proj.weight": "model-00015-of-00017.safetensors", "model.layers.40.self_attn.o_proj.weight": "model-00015-of-00017.safetensors", "model.layers.40.self_attn.q_norm.weight": "model-00015-of-00017.safetensors", "model.layers.40.self_attn.q_proj.weight": "model-00015-of-00017.safetensors", "model.layers.40.self_attn.v_proj.weight": "model-00015-of-00017.safetensors", "model.layers.41.input_layernorm.weight": "model-00015-of-00017.safetensors", "model.layers.41.post_attention_layernorm.weight": "model-00015-of-00017.safetensors", "model.layers.41.self_attn.k_norm.weight": "model-00015-of-00017.safetensors", "model.layers.41.self_attn.k_proj.weight": "model-00015-of-00017.safetensors", "model.layers.41.self_attn.o_proj.weight": "model-00015-of-00017.safetensors", "model.layers.41.self_attn.q_norm.weight": "model-00015-of-00017.safetensors", "model.layers.41.self_attn.q_proj.weight": "model-00015-of-00017.safetensors", "model.layers.41.self_attn.v_proj.weight": "model-00015-of-00017.safetensors", "model.layers.42.input_layernorm.weight": "model-00016-of-00017.safetensors", "model.layers.42.post_attention_layernorm.weight": "model-00016-of-00017.safetensors", "model.layers.42.self_attn.k_norm.weight": "model-00016-of-00017.safetensors", "model.layers.42.self_attn.k_proj.weight": "model-00016-of-00017.safetensors", "model.layers.42.self_attn.o_proj.weight": "model-00016-of-00017.safetensors", "model.layers.42.self_attn.q_norm.weight": "model-00016-of-00017.safetensors", "model.layers.42.self_attn.q_proj.weight": "model-00016-of-00017.safetensors", "model.layers.42.self_attn.v_proj.weight": "model-00016-of-00017.safetensors", "model.layers.43.self_attn.k_norm.weight": "model-00016-of-00017.safetensors", "model.layers.43.self_attn.k_proj.weight": "model-00016-of-00017.safetensors", "model.layers.43.self_attn.o_proj.weight": "model-00016-of-00017.safetensors", "model.layers.43.self_attn.q_norm.weight": "model-00016-of-00017.safetensors", "model.layers.43.self_attn.q_proj.weight": "model-00016-of-00017.safetensors", "model.layers.43.self_attn.v_proj.weight": "model-00016-of-00017.safetensors", "model.layers.4.mlp.router.gate.weight": "model-00003-of-00017.safetensors", "model.layers.4.mlp.experts.w1": "model-00003-of-00017.safetensors", "model.layers.4.mlp.experts.w2": "model-00003-of-00017.safetensors", "model.layers.4.mlp.experts.w3": "model-00003-of-00017.safetensors", "model.layers.40.mlp.router.gate.weight": "model-00015-of-00017.safetensors", "model.layers.40.mlp.experts.w1": "model-00015-of-00017.safetensors", "model.layers.40.mlp.experts.w2": "model-00015-of-00017.safetensors", "model.layers.40.mlp.experts.w3": "model-00015-of-00017.safetensors", "model.layers.41.mlp.router.gate.weight": "model-00015-of-00017.safetensors", "model.layers.41.mlp.experts.w1": "model-00015-of-00017.safetensors", "model.layers.41.mlp.experts.w2": "model-00015-of-00017.safetensors", "model.layers.41.mlp.experts.w3": "model-00015-of-00017.safetensors", "model.layers.42.mlp.router.gate.weight": "model-00016-of-00017.safetensors", "model.layers.42.mlp.experts.w1": "model-00016-of-00017.safetensors", "model.layers.42.mlp.experts.w2": "model-00016-of-00017.safetensors", "model.layers.42.mlp.experts.w3": "model-00016-of-00017.safetensors", "model.layers.43.mlp.router.gate.weight": "model-00016-of-00017.safetensors", "model.layers.43.mlp.experts.w1": "model-00016-of-00017.safetensors", "model.layers.43.mlp.experts.w2": "model-00016-of-00017.safetensors", "model.layers.43.mlp.experts.w3": "model-00016-of-00017.safetensors", "model.layers.44.mlp.router.gate.weight": "model-00016-of-00017.safetensors", "model.layers.44.mlp.experts.w1": "model-00016-of-00017.safetensors", "model.layers.44.mlp.experts.w2": "model-00016-of-00017.safetensors", "model.layers.44.mlp.experts.w3": "model-00016-of-00017.safetensors", "model.layers.45.mlp.router.gate.weight": "model-00017-of-00017.safetensors", "model.layers.45.mlp.experts.w1": "model-00017-of-00017.safetensors", "model.layers.45.mlp.experts.w2": "model-00017-of-00017.safetensors", "model.layers.45.mlp.experts.w3": "model-00017-of-00017.safetensors", "model.layers.46.mlp.router.gate.weight": "model-00017-of-00017.safetensors", "model.layers.46.mlp.experts.w1": "model-00017-of-00017.safetensors", "model.layers.46.mlp.experts.w2": "model-00017-of-00017.safetensors", "model.layers.46.mlp.experts.w3": "model-00017-of-00017.safetensors", "model.layers.47.mlp.router.gate.weight": "model-00017-of-00017.safetensors", "model.layers.47.mlp.experts.w1": "model-00017-of-00017.safetensors", "model.layers.47.mlp.experts.w2": "model-00017-of-00017.safetensors", "model.layers.47.mlp.experts.w3": "model-00017-of-00017.safetensors", "model.layers.5.input_layernorm.weight": "model-00003-of-00017.safetensors", "model.layers.5.post_attention_layernorm.weight": "model-00003-of-00017.safetensors", "model.layers.5.self_attn.k_norm.weight": "model-00003-of-00017.safetensors", "model.layers.5.self_attn.k_proj.weight": "model-00003-of-00017.safetensors", "model.layers.5.self_attn.o_proj.weight": "model-00003-of-00017.safetensors", "model.layers.5.self_attn.q_norm.weight": "model-00003-of-00017.safetensors", "model.layers.5.self_attn.q_proj.weight": "model-00003-of-00017.safetensors", "model.layers.5.self_attn.v_proj.weight": "model-00003-of-00017.safetensors", "model.layers.5.mlp.router.gate.weight": "model-00003-of-00017.safetensors", "model.layers.5.mlp.experts.w1": "model-00003-of-00017.safetensors", "model.layers.5.mlp.experts.w2": "model-00003-of-00017.safetensors", "model.layers.5.mlp.experts.w3": "model-00003-of-00017.safetensors", "model.layers.6.input_layernorm.weight": "model-00004-of-00017.safetensors", "model.layers.6.post_attention_layernorm.weight": "model-00004-of-00017.safetensors", "model.layers.6.self_attn.k_norm.weight": "model-00004-of-00017.safetensors", "model.layers.6.self_attn.k_proj.weight": "model-00004-of-00017.safetensors", "model.layers.6.self_attn.o_proj.weight": "model-00004-of-00017.safetensors", "model.layers.6.self_attn.q_norm.weight": "model-00004-of-00017.safetensors", "model.layers.6.self_attn.q_proj.weight": "model-00004-of-00017.safetensors", "model.layers.6.self_attn.v_proj.weight": "model-00004-of-00017.safetensors", "model.layers.6.mlp.router.gate.weight": "model-00004-of-00017.safetensors", "model.layers.6.mlp.experts.w1": "model-00004-of-00017.safetensors", "model.layers.6.mlp.experts.w2": "model-00004-of-00017.safetensors", "model.layers.6.mlp.experts.w3": "model-00004-of-00017.safetensors", "model.layers.7.input_layernorm.weight": "model-00004-of-00017.safetensors", "model.layers.7.post_attention_layernorm.weight": "model-00004-of-00017.safetensors", "model.layers.7.self_attn.k_norm.weight": "model-00004-of-00017.safetensors", "model.layers.7.self_attn.k_proj.weight": "model-00004-of-00017.safetensors", "model.layers.7.self_attn.o_proj.weight": "model-00004-of-00017.safetensors", "model.layers.7.self_attn.q_norm.weight": "model-00004-of-00017.safetensors", "model.layers.7.self_attn.q_proj.weight": "model-00004-of-00017.safetensors", "model.layers.7.self_attn.v_proj.weight": "model-00004-of-00017.safetensors", "model.layers.7.mlp.router.gate.weight": "model-00004-of-00017.safetensors", "model.layers.7.mlp.experts.w1": "model-00004-of-00017.safetensors", "model.layers.7.mlp.experts.w2": "model-00004-of-00017.safetensors", "model.layers.7.mlp.experts.w3": "model-00004-of-00017.safetensors", "model.layers.8.input_layernorm.weight": "model-00004-of-00017.safetensors", "model.layers.8.post_attention_layernorm.weight": "model-00004-of-00017.safetensors", "model.layers.8.self_attn.k_norm.weight": "model-00004-of-00017.safetensors", "model.layers.8.self_attn.k_proj.weight": "model-00004-of-00017.safetensors", "model.layers.8.self_attn.o_proj.weight": "model-00004-of-00017.safetensors", "model.layers.8.self_attn.q_norm.weight": "model-00004-of-00017.safetensors", "model.layers.8.self_attn.q_proj.weight": "model-00004-of-00017.safetensors", "model.layers.8.self_attn.v_proj.weight": "model-00004-of-00017.safetensors", "model.layers.8.mlp.router.gate.weight": "model-00004-of-00017.safetensors", "model.layers.8.mlp.experts.w1": "model-00004-of-00017.safetensors", "model.layers.8.mlp.experts.w2": "model-00004-of-00017.safetensors", "model.layers.8.mlp.experts.w3": "model-00004-of-00017.safetensors", "model.layers.9.input_layernorm.weight": "model-00005-of-00017.safetensors", "model.layers.9.post_attention_layernorm.weight": "model-00005-of-00017.safetensors", "model.layers.9.self_attn.k_norm.weight": "model-00005-of-00017.safetensors", "model.layers.9.self_attn.k_proj.weight": "model-00005-of-00017.safetensors", "model.layers.9.self_attn.o_proj.weight": "model-00005-of-00017.safetensors", "model.layers.9.self_attn.q_norm.weight": "model-00005-of-00017.safetensors", "model.layers.9.self_attn.q_proj.weight": "model-00005-of-00017.safetensors", "model.layers.9.self_attn.v_proj.weight": "model-00005-of-00017.safetensors", "model.layers.9.mlp.router.gate.weight": "model-00005-of-00017.safetensors", "model.layers.9.mlp.experts.w1": "model-00005-of-00017.safetensors", "model.layers.9.mlp.experts.w2": "model-00005-of-00017.safetensors", "model.layers.9.mlp.experts.w3": "model-00005-of-00017.safetensors"}}
modeling_qwen3_moe.py ADDED
@@ -0,0 +1,730 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2025 The Qwen team, Alibaba Group and the HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ from typing import Callable, Optional, Union
17
+
18
+ import torch
19
+ import torch.nn.functional as F
20
+ from torch import nn
21
+
22
+ from transformers.activations import ACT2FN
23
+ from transformers.cache_utils import Cache, DynamicCache
24
+ from transformers.generation import GenerationMixin
25
+ from transformers.integrations import use_kernel_forward_from_hub
26
+ from transformers.masking_utils import create_causal_mask, create_sliding_window_causal_mask
27
+ from transformers.modeling_flash_attention_utils import FlashAttentionKwargs
28
+ from transformers.modeling_layers import (
29
+ GenericForQuestionAnswering,
30
+ GenericForSequenceClassification,
31
+ GenericForTokenClassification,
32
+ GradientCheckpointingLayer,
33
+ )
34
+ from transformers.modeling_outputs import MoeCausalLMOutputWithPast, MoeModelOutputWithPast
35
+ from transformers.modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update
36
+ from transformers.modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
37
+ from transformers.processing_utils import Unpack
38
+ from transformers.utils import TransformersKwargs, auto_docstring, can_return_tuple
39
+ from transformers.utils.generic import OutputRecorder, check_model_inputs
40
+ from .configuration_qwen3_moe import Qwen3MoeConfig
41
+
42
+ from torchtitan.models.moe import MoE, MoEArgs
43
+
44
+
45
+ def rotate_half(x):
46
+ """Rotates half the hidden dims of the input."""
47
+ x1 = x[..., : x.shape[-1] // 2]
48
+ x2 = x[..., x.shape[-1] // 2 :]
49
+ return torch.cat((-x2, x1), dim=-1)
50
+
51
+
52
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
53
+ """Applies Rotary Position Embedding to the query and key tensors.
54
+
55
+ Args:
56
+ q (`torch.Tensor`): The query tensor.
57
+ k (`torch.Tensor`): The key tensor.
58
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
59
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
60
+ position_ids (`torch.Tensor`, *optional*):
61
+ Deprecated and unused.
62
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
63
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
64
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
65
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
66
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
67
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
68
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
69
+ Returns:
70
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
71
+ """
72
+ cos = cos.unsqueeze(unsqueeze_dim)
73
+ sin = sin.unsqueeze(unsqueeze_dim)
74
+ q_embed = (q * cos) + (rotate_half(q) * sin)
75
+ k_embed = (k * cos) + (rotate_half(k) * sin)
76
+ return q_embed, k_embed
77
+
78
+
79
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
80
+ """
81
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
82
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
83
+ """
84
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
85
+ if n_rep == 1:
86
+ return hidden_states
87
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
88
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
89
+
90
+
91
+ def eager_attention_forward(
92
+ module: nn.Module,
93
+ query: torch.Tensor,
94
+ key: torch.Tensor,
95
+ value: torch.Tensor,
96
+ attention_mask: Optional[torch.Tensor],
97
+ scaling: float,
98
+ dropout: float = 0.0,
99
+ **kwargs: Unpack[TransformersKwargs],
100
+ ):
101
+ key_states = repeat_kv(key, module.num_key_value_groups)
102
+ value_states = repeat_kv(value, module.num_key_value_groups)
103
+
104
+ attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
105
+ if attention_mask is not None:
106
+ causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
107
+ attn_weights = attn_weights + causal_mask
108
+
109
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
110
+ attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
111
+ attn_output = torch.matmul(attn_weights, value_states)
112
+ attn_output = attn_output.transpose(1, 2).contiguous()
113
+
114
+ return attn_output, attn_weights
115
+
116
+
117
+ class Qwen3MoeAttention(nn.Module):
118
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
119
+
120
+ def __init__(self, config: Qwen3MoeConfig, layer_idx: int):
121
+ super().__init__()
122
+ self.config = config
123
+ self.layer_idx = layer_idx
124
+ self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
125
+ self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
126
+ self.scaling = self.head_dim**-0.5
127
+ self.attention_dropout = config.attention_dropout
128
+ self.is_causal = True
129
+
130
+ self.q_proj = nn.Linear(
131
+ config.hidden_size, config.num_attention_heads * self.head_dim, bias=config.attention_bias
132
+ )
133
+ self.k_proj = nn.Linear(
134
+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
135
+ )
136
+ self.v_proj = nn.Linear(
137
+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
138
+ )
139
+ self.o_proj = nn.Linear(
140
+ config.num_attention_heads * self.head_dim, config.hidden_size, bias=config.attention_bias
141
+ )
142
+ self.q_norm = Qwen3MoeRMSNorm(self.head_dim, eps=config.rms_norm_eps) # unlike olmo, only on the head dim!
143
+ self.k_norm = Qwen3MoeRMSNorm(self.head_dim, eps=config.rms_norm_eps) # thus post q_norm does not need reshape
144
+ self.sliding_window = getattr(config, "sliding_window", None)
145
+
146
+ def forward(
147
+ self,
148
+ hidden_states: torch.Tensor,
149
+ position_embeddings: tuple[torch.Tensor, torch.Tensor],
150
+ attention_mask: Optional[torch.Tensor],
151
+ past_key_value: Optional[Cache] = None,
152
+ cache_position: Optional[torch.LongTensor] = None,
153
+ **kwargs: Unpack[FlashAttentionKwargs],
154
+ ) -> tuple[torch.Tensor, Optional[torch.Tensor], Optional[tuple[torch.Tensor]]]:
155
+ input_shape = hidden_states.shape[:-1]
156
+ hidden_shape = (*input_shape, -1, self.head_dim)
157
+
158
+ query_states = self.q_norm(self.q_proj(hidden_states).view(hidden_shape)).transpose(1, 2)
159
+ key_states = self.k_norm(self.k_proj(hidden_states).view(hidden_shape)).transpose(1, 2)
160
+ value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
161
+
162
+ cos, sin = position_embeddings
163
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
164
+
165
+ if past_key_value is not None:
166
+ # sin and cos are specific to RoPE models; cache_position needed for the static cache
167
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
168
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
169
+
170
+ if self.config._attn_implementation == "sdpa":
171
+ key_states = key_states.repeat_interleave(self.num_key_value_groups, dim=1)
172
+ value_states = value_states.repeat_interleave(self.num_key_value_groups, dim=1)
173
+ out = F.scaled_dot_product_attention(query_states, key_states, value_states, is_causal=True)
174
+ out = out.transpose(1, 2).contiguous() #.view(out.shape[0], out.shape[1], -1)
175
+ attn_output = out.view(out.shape[0], out.shape[1], -1)
176
+ attn_weights = None
177
+ else:
178
+ attention_interface: Callable = eager_attention_forward
179
+ if self.config._attn_implementation != "eager":
180
+ attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
181
+
182
+ attn_output, attn_weights = attention_interface(
183
+ self,
184
+ query_states,
185
+ key_states,
186
+ value_states,
187
+ attention_mask,
188
+ dropout=0.0 if not self.training else self.attention_dropout,
189
+ scaling=self.scaling,
190
+ sliding_window=self.sliding_window, # diff with Llama
191
+ **kwargs,
192
+ )
193
+
194
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
195
+ attn_output = self.o_proj(attn_output)
196
+ return attn_output, attn_weights
197
+
198
+
199
+ class Qwen3MoeMLP(nn.Module):
200
+ def __init__(self, config, intermediate_size=None):
201
+ super().__init__()
202
+ self.config = config
203
+ self.hidden_size = config.hidden_size
204
+ self.intermediate_size = intermediate_size if intermediate_size is not None else config.intermediate_size
205
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
206
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
207
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
208
+ self.act_fn = ACT2FN[config.hidden_act]
209
+
210
+ def forward(self, x):
211
+ down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
212
+ return down_proj
213
+
214
+
215
+ class Qwen3MoeSparseMoeBlock(nn.Module):
216
+ def __init__(self, config):
217
+ super().__init__()
218
+ self.num_experts = config.num_experts
219
+ self.top_k = config.num_experts_per_tok
220
+ self.norm_topk_prob = config.norm_topk_prob
221
+
222
+ # gating
223
+ self.gate = nn.Linear(config.hidden_size, config.num_experts, bias=False)
224
+ self.experts = nn.ModuleList(
225
+ [Qwen3MoeMLP(config, intermediate_size=config.moe_intermediate_size) for _ in range(self.num_experts)]
226
+ )
227
+
228
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
229
+ """ """
230
+ batch_size, sequence_length, hidden_dim = hidden_states.shape
231
+ hidden_states = hidden_states.view(-1, hidden_dim)
232
+ # router_logits: (batch * sequence_length, n_experts)
233
+ router_logits = self.gate(hidden_states)
234
+
235
+ routing_weights = F.softmax(router_logits, dim=1, dtype=torch.float)
236
+ routing_weights, selected_experts = torch.topk(routing_weights, self.top_k, dim=-1)
237
+ if self.norm_topk_prob: # only diff with mixtral sparse moe block!
238
+ routing_weights /= routing_weights.sum(dim=-1, keepdim=True)
239
+ # we cast back to the input dtype
240
+ routing_weights = routing_weights.to(hidden_states.dtype)
241
+
242
+ final_hidden_states = torch.zeros(
243
+ (batch_size * sequence_length, hidden_dim), dtype=hidden_states.dtype, device=hidden_states.device
244
+ )
245
+
246
+ # One hot encode the selected experts to create an expert mask
247
+ # this will be used to easily index which expert is going to be sollicitated
248
+ expert_mask = torch.nn.functional.one_hot(selected_experts, num_classes=self.num_experts).permute(2, 1, 0)
249
+
250
+ # Loop over all available experts in the model and perform the computation on each expert
251
+ expert_hitted = torch.greater(expert_mask.sum(dim=(-1, -2)), 0).nonzero()
252
+ for expert_idx in expert_hitted:
253
+ expert_layer = self.experts[expert_idx]
254
+ idx, top_x = torch.where(expert_mask[expert_idx].squeeze(0))
255
+
256
+ # Index the correct hidden states and compute the expert hidden state for
257
+ # the current expert. We need to make sure to multiply the output hidden
258
+ # states by `routing_weights` on the corresponding tokens (top-1 and top-2)
259
+ current_state = hidden_states[None, top_x].reshape(-1, hidden_dim)
260
+ current_hidden_states = expert_layer(current_state) * routing_weights[top_x, idx, None]
261
+
262
+ # However `index_add_` only support torch tensors for indexing so we'll use
263
+ # the `top_x` tensor here.
264
+ final_hidden_states.index_add_(0, top_x, current_hidden_states.to(hidden_states.dtype))
265
+ final_hidden_states = final_hidden_states.reshape(batch_size, sequence_length, hidden_dim)
266
+ return final_hidden_states, router_logits
267
+
268
+
269
+ @use_kernel_forward_from_hub("RMSNorm")
270
+ class Qwen3MoeRMSNorm(nn.Module):
271
+ def __init__(self, hidden_size, eps=1e-6):
272
+ """
273
+ Qwen3MoeRMSNorm is equivalent to T5LayerNorm
274
+ """
275
+ super().__init__()
276
+ self.weight = nn.Parameter(torch.ones(hidden_size))
277
+ self.variance_epsilon = eps
278
+
279
+ def forward(self, hidden_states):
280
+ input_dtype = hidden_states.dtype
281
+ hidden_states = hidden_states.to(torch.float32)
282
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
283
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
284
+ return self.weight * hidden_states.to(input_dtype)
285
+
286
+ def extra_repr(self):
287
+ return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
288
+
289
+
290
+ class Qwen3MoeDecoderLayer(GradientCheckpointingLayer):
291
+ def __init__(self, config: Qwen3MoeConfig, layer_idx: int):
292
+ super().__init__()
293
+ self.hidden_size = config.hidden_size
294
+
295
+ self.self_attn = Qwen3MoeAttention(config, layer_idx)
296
+
297
+ moe_args = MoEArgs(
298
+ num_experts=config.num_experts,
299
+ num_shared_experts=0,
300
+ score_func="softmax",
301
+ route_norm=config.norm_topk_prob,
302
+ route_scale=1.0,
303
+ score_before_experts=False,
304
+ top_k=config.num_experts_per_tok,
305
+ use_grouped_mm=True,
306
+ load_balance_coeff=config.load_balance_coeff,
307
+ )
308
+
309
+ if (layer_idx not in config.mlp_only_layers) and (
310
+ config.num_experts > 0 and (layer_idx + 1) % config.decoder_sparse_step == 0
311
+ ):
312
+ self.mlp = MoE(moe_args, dim=config.hidden_size, hidden_dim=config.moe_intermediate_size)
313
+ else:
314
+ self.mlp = Qwen3MoeMLP(config, intermediate_size=config.intermediate_size)
315
+
316
+ self.input_layernorm = Qwen3MoeRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
317
+ self.post_attention_layernorm = Qwen3MoeRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
318
+
319
+ def forward(
320
+ self,
321
+ hidden_states: torch.Tensor,
322
+ position_embeddings: tuple[torch.Tensor, torch.Tensor],
323
+ attention_mask: Optional[torch.Tensor] = None,
324
+ position_ids: Optional[torch.LongTensor] = None,
325
+ past_key_value: Optional[tuple[torch.Tensor]] = None,
326
+ cache_position: Optional[torch.LongTensor] = None,
327
+ **kwargs: Unpack[FlashAttentionKwargs],
328
+ ) -> torch.FloatTensor:
329
+ """
330
+ Args:
331
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
332
+ attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
333
+ `(batch, sequence_length)` where padding elements are indicated by 0.
334
+ output_attentions (`bool`, *optional*):
335
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
336
+ returned tensors for more detail.
337
+ output_router_logits (`bool`, *optional*):
338
+ Whether or not to return the logits of all the routers. They are useful for computing the router loss,
339
+ and should not be returned during inference.
340
+ use_cache (`bool`, *optional*):
341
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
342
+ (see `past_key_values`).
343
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
344
+ cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
345
+ Indices depicting the position of the input sequence tokens in the sequence.
346
+ position_embeddings (`tuple[torch.FloatTensor, torch.FloatTensor]`, *optional*):
347
+ Tuple containing the cosine and sine positional embeddings of shape `(batch_size, seq_len, head_dim)`,
348
+ with `head_dim` being the embedding dimension of each attention head.
349
+ kwargs (`dict`, *optional*):
350
+ Arbitrary kwargs to be ignored, used for FSDP and other methods that injects code
351
+ into the model
352
+ """
353
+ residual = hidden_states
354
+
355
+ hidden_states = self.input_layernorm(hidden_states)
356
+
357
+ # Self Attention
358
+ hidden_states, _ = self.self_attn(
359
+ hidden_states=hidden_states,
360
+ position_embeddings=position_embeddings,
361
+ attention_mask=attention_mask,
362
+ position_ids=position_ids,
363
+ past_key_value=past_key_value,
364
+ cache_position=cache_position,
365
+ **kwargs,
366
+ )
367
+ hidden_states = residual + hidden_states
368
+
369
+ # Fully Connected
370
+ residual = hidden_states
371
+ hidden_states = self.post_attention_layernorm(hidden_states)
372
+ hidden_states = self.mlp(hidden_states)
373
+ # For the MoE layers, we need to unpack
374
+ if isinstance(hidden_states, tuple):
375
+ hidden_states, _ = hidden_states
376
+ hidden_states = residual + hidden_states
377
+
378
+ return hidden_states
379
+
380
+
381
+ class Qwen3MoeRotaryEmbedding(nn.Module):
382
+ def __init__(self, config: Qwen3MoeConfig, device=None):
383
+ super().__init__()
384
+ # BC: "rope_type" was originally "type"
385
+ if hasattr(config, "rope_scaling") and isinstance(config.rope_scaling, dict):
386
+ self.rope_type = config.rope_scaling.get("rope_type", config.rope_scaling.get("type"))
387
+ else:
388
+ self.rope_type = "default"
389
+ self.max_seq_len_cached = config.max_position_embeddings
390
+ self.original_max_seq_len = config.max_position_embeddings
391
+
392
+ self.config = config
393
+ self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
394
+
395
+ inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device)
396
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
397
+ self.original_inv_freq = self.inv_freq
398
+
399
+ @torch.no_grad()
400
+ @dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope)
401
+ def forward(self, x, position_ids):
402
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device)
403
+ position_ids_expanded = position_ids[:, None, :].float()
404
+
405
+ device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
406
+ with torch.autocast(device_type=device_type, enabled=False): # Force float32
407
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
408
+ emb = torch.cat((freqs, freqs), dim=-1)
409
+ cos = emb.cos() * self.attention_scaling
410
+ sin = emb.sin() * self.attention_scaling
411
+
412
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
413
+
414
+
415
+ @auto_docstring
416
+ class Qwen3MoePreTrainedModel(PreTrainedModel):
417
+ config: Qwen3MoeConfig
418
+ base_model_prefix = "model"
419
+ supports_gradient_checkpointing = True
420
+ _no_split_modules = ["Qwen3MoeDecoderLayer"]
421
+ _skip_keys_device_placement = ["past_key_values"]
422
+ _supports_flash_attn = True
423
+ _supports_sdpa = True
424
+ _supports_flex_attn = True
425
+ _can_compile_fullgraph = False # MoE models don't work with torch.compile (`torch.where(condition)` not supported)
426
+ _supports_attention_backend = True
427
+ _can_record_outputs = {
428
+ "router_logits": OutputRecorder(Qwen3MoeSparseMoeBlock, index=1),
429
+ "hidden_states": Qwen3MoeDecoderLayer,
430
+ "attentions": Qwen3MoeAttention,
431
+ }
432
+
433
+
434
+ @auto_docstring
435
+ class Qwen3MoeModel(Qwen3MoePreTrainedModel):
436
+ def __init__(self, config: Qwen3MoeConfig):
437
+ super().__init__(config)
438
+ self.padding_idx = config.pad_token_id
439
+ self.vocab_size = config.vocab_size
440
+
441
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
442
+ self.layers = nn.ModuleList(
443
+ [Qwen3MoeDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
444
+ )
445
+ self.norm = Qwen3MoeRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
446
+ self.rotary_emb = Qwen3MoeRotaryEmbedding(config=config)
447
+ self.gradient_checkpointing = False
448
+
449
+ # Initialize weights and apply final processing
450
+ self.post_init()
451
+
452
+ @check_model_inputs
453
+ @auto_docstring
454
+ def forward(
455
+ self,
456
+ input_ids: Optional[torch.LongTensor] = None,
457
+ attention_mask: Optional[torch.Tensor] = None,
458
+ position_ids: Optional[torch.LongTensor] = None,
459
+ past_key_values: Optional[Cache] = None,
460
+ inputs_embeds: Optional[torch.FloatTensor] = None,
461
+ use_cache: Optional[bool] = None,
462
+ cache_position: Optional[torch.LongTensor] = None,
463
+ **kwargs: Unpack[TransformersKwargs],
464
+ ) -> MoeModelOutputWithPast:
465
+ if (input_ids is None) ^ (inputs_embeds is not None):
466
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
467
+
468
+ if use_cache and past_key_values is None:
469
+ past_key_values = DynamicCache()
470
+
471
+ if inputs_embeds is None:
472
+ inputs_embeds = self.embed_tokens(input_ids)
473
+
474
+ if cache_position is None:
475
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
476
+ cache_position = torch.arange(
477
+ past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
478
+ )
479
+ if position_ids is None:
480
+ position_ids = cache_position.unsqueeze(0)
481
+
482
+ mask_function = create_causal_mask if self.config.sliding_window is None else create_sliding_window_causal_mask
483
+ causal_mask = mask_function(
484
+ config=self.config,
485
+ input_embeds=inputs_embeds,
486
+ attention_mask=attention_mask,
487
+ cache_position=cache_position,
488
+ past_key_values=past_key_values,
489
+ position_ids=position_ids,
490
+ )
491
+
492
+ hidden_states = inputs_embeds
493
+
494
+ # create position embeddings to be shared across the decoder layers
495
+ position_embeddings = self.rotary_emb(hidden_states, position_ids)
496
+
497
+ for decoder_layer in self.layers[: self.config.num_hidden_layers]:
498
+ hidden_states = decoder_layer(
499
+ hidden_states,
500
+ position_embeddings=position_embeddings,
501
+ attention_mask=causal_mask,
502
+ position_ids=position_ids,
503
+ past_key_value=past_key_values,
504
+ use_cache=use_cache,
505
+ cache_position=cache_position,
506
+ **kwargs,
507
+ )
508
+
509
+ hidden_states = self.norm(hidden_states)
510
+
511
+ return MoeModelOutputWithPast( # only diff with Mistral is the output type, we need MoE
512
+ last_hidden_state=hidden_states,
513
+ past_key_values=past_key_values,
514
+ )
515
+
516
+
517
+ def load_balancing_loss_func(
518
+ gate_logits: Union[torch.Tensor, tuple[torch.Tensor], None],
519
+ num_experts: Optional[int] = None,
520
+ top_k=2,
521
+ attention_mask: Optional[torch.Tensor] = None,
522
+ ) -> Union[torch.Tensor, int]:
523
+ r"""
524
+ Computes auxiliary load balancing loss as in Switch Transformer - implemented in Pytorch.
525
+
526
+ See Switch Transformer (https://huggingface.co/papers/2101.03961) for more details. This function implements the loss
527
+ function presented in equations (4) - (6) of the paper. It aims at penalizing cases where the routing between
528
+ experts is too unbalanced.
529
+
530
+ Args:
531
+ gate_logits:
532
+ Logits from the `gate`, should be a tuple of model.config.num_hidden_layers tensors of
533
+ shape [batch_size X sequence_length, num_experts].
534
+ num_experts:
535
+ Number of experts
536
+ top_k:
537
+ The number of experts to route per-token, can be also interpreted as the `top-k` routing
538
+ parameter.
539
+ attention_mask (`torch.Tensor`, *optional*):
540
+ The attention_mask used in forward function
541
+ shape [batch_size X sequence_length] if not None.
542
+
543
+ Returns:
544
+ The auxiliary loss.
545
+ """
546
+ if gate_logits is None or not isinstance(gate_logits, tuple):
547
+ return 0
548
+
549
+ if isinstance(gate_logits, tuple):
550
+ compute_device = gate_logits[0].device
551
+ concatenated_gate_logits = torch.cat([layer_gate.to(compute_device) for layer_gate in gate_logits], dim=0)
552
+
553
+ routing_weights = torch.nn.functional.softmax(concatenated_gate_logits, dim=-1)
554
+
555
+ _, selected_experts = torch.topk(routing_weights, top_k, dim=-1)
556
+
557
+ expert_mask = torch.nn.functional.one_hot(selected_experts, num_experts)
558
+
559
+ if attention_mask is None:
560
+ # Compute the percentage of tokens routed to each experts
561
+ tokens_per_expert = torch.mean(expert_mask.float(), dim=0)
562
+
563
+ # Compute the average probability of routing to these experts
564
+ router_prob_per_expert = torch.mean(routing_weights, dim=0)
565
+ else:
566
+ batch_size, sequence_length = attention_mask.shape
567
+ num_hidden_layers = concatenated_gate_logits.shape[0] // (batch_size * sequence_length)
568
+
569
+ # Compute the mask that masks all padding tokens as 0 with the same shape of expert_mask
570
+ expert_attention_mask = (
571
+ attention_mask[None, :, :, None, None]
572
+ .expand((num_hidden_layers, batch_size, sequence_length, top_k, num_experts))
573
+ .reshape(-1, top_k, num_experts)
574
+ .to(compute_device)
575
+ )
576
+
577
+ # Compute the percentage of tokens routed to each experts
578
+ tokens_per_expert = torch.sum(expert_mask.float() * expert_attention_mask, dim=0) / torch.sum(
579
+ expert_attention_mask, dim=0
580
+ )
581
+
582
+ # Compute the mask that masks all padding tokens as 0 with the same shape of tokens_per_expert
583
+ router_per_expert_attention_mask = (
584
+ attention_mask[None, :, :, None]
585
+ .expand((num_hidden_layers, batch_size, sequence_length, num_experts))
586
+ .reshape(-1, num_experts)
587
+ .to(compute_device)
588
+ )
589
+
590
+ # Compute the average probability of routing to these experts
591
+ router_prob_per_expert = torch.sum(routing_weights * router_per_expert_attention_mask, dim=0) / torch.sum(
592
+ router_per_expert_attention_mask, dim=0
593
+ )
594
+
595
+ overall_loss = torch.sum(tokens_per_expert * router_prob_per_expert.unsqueeze(0))
596
+ return overall_loss * num_experts
597
+
598
+
599
+ @auto_docstring
600
+ class Qwen3MoeForCausalLM(Qwen3MoePreTrainedModel, GenerationMixin):
601
+ _tied_weights_keys = ["lm_head.weight"]
602
+ _tp_plan = {"lm_head": "colwise_rep"}
603
+ _pp_plan = {"lm_head": (["hidden_states"], ["logits"])}
604
+
605
+ def __init__(self, config):
606
+ super().__init__(config)
607
+ self.model = Qwen3MoeModel(config)
608
+ self.vocab_size = config.vocab_size
609
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
610
+ self.router_aux_loss_coef = config.router_aux_loss_coef
611
+ self.num_experts = config.num_experts
612
+ self.num_experts_per_tok = config.num_experts_per_tok
613
+
614
+ # Initialize weights and apply final processing
615
+ self.post_init()
616
+
617
+ def set_decoder(self, decoder):
618
+ self.model = decoder
619
+
620
+ def get_decoder(self):
621
+ return self.model
622
+
623
+ @can_return_tuple
624
+ @auto_docstring
625
+ def forward(
626
+ self,
627
+ input_ids: Optional[torch.LongTensor] = None,
628
+ attention_mask: Optional[torch.Tensor] = None,
629
+ position_ids: Optional[torch.LongTensor] = None,
630
+ past_key_values: Optional[Cache] = None,
631
+ inputs_embeds: Optional[torch.FloatTensor] = None,
632
+ labels: Optional[torch.LongTensor] = None,
633
+ use_cache: Optional[bool] = None,
634
+ output_router_logits: Optional[bool] = None,
635
+ cache_position: Optional[torch.LongTensor] = None,
636
+ logits_to_keep: Union[int, torch.Tensor] = 0,
637
+ **kwargs: Unpack[TransformersKwargs],
638
+ ) -> MoeCausalLMOutputWithPast:
639
+ r"""
640
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
641
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
642
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
643
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
644
+
645
+ Example:
646
+
647
+ ```python
648
+ >>> from transformers import AutoTokenizer, Qwen3MoeForCausalLM
649
+
650
+ >>> model = Qwen3MoeForCausalLM.from_pretrained("Qwen/Qwen3-MoE-15B-A2B")
651
+ >>> tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen3-MoE-15B-A2B")
652
+
653
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
654
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
655
+
656
+ >>> # Generate
657
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
658
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
659
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
660
+ ```"""
661
+
662
+ output_router_logits = (
663
+ output_router_logits if output_router_logits is not None else self.config.output_router_logits
664
+ )
665
+
666
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
667
+ outputs: MoeModelOutputWithPast = self.model(
668
+ input_ids=input_ids,
669
+ attention_mask=attention_mask,
670
+ position_ids=position_ids,
671
+ past_key_values=past_key_values,
672
+ inputs_embeds=inputs_embeds,
673
+ use_cache=use_cache,
674
+ output_router_logits=output_router_logits,
675
+ cache_position=cache_position,
676
+ **kwargs,
677
+ )
678
+
679
+ hidden_states = outputs.last_hidden_state
680
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
681
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
682
+ logits = self.lm_head(hidden_states[:, slice_indices, :])
683
+
684
+ loss = None
685
+ if labels is not None:
686
+ loss = self.loss_function(logits, labels, self.vocab_size, **kwargs)
687
+
688
+ aux_loss = None
689
+ if output_router_logits:
690
+ aux_loss = load_balancing_loss_func(
691
+ outputs.router_logits,
692
+ self.num_experts,
693
+ self.num_experts_per_tok,
694
+ attention_mask,
695
+ )
696
+ if labels is not None:
697
+ loss += self.router_aux_loss_coef * aux_loss.to(loss.device) # make sure to reside in the same device
698
+
699
+ return MoeCausalLMOutputWithPast(
700
+ loss=loss,
701
+ aux_loss=aux_loss,
702
+ logits=logits,
703
+ past_key_values=outputs.past_key_values,
704
+ hidden_states=outputs.hidden_states,
705
+ attentions=outputs.attentions,
706
+ router_logits=outputs.router_logits,
707
+ )
708
+
709
+
710
+ class Qwen3MoeForSequenceClassification(GenericForSequenceClassification, Qwen3MoePreTrainedModel):
711
+ pass
712
+
713
+
714
+ class Qwen3MoeForTokenClassification(GenericForTokenClassification, Qwen3MoePreTrainedModel):
715
+ pass
716
+
717
+
718
+ class Qwen3MoeForQuestionAnswering(GenericForQuestionAnswering, Qwen3MoePreTrainedModel):
719
+ base_model_prefix = "transformer" # For BC, where `transformer` was used instead of `model`
720
+
721
+
722
+ __all__ = [
723
+ "Qwen3MoeForCausalLM",
724
+ "Qwen3MoeForQuestionAnswering",
725
+ "Qwen3MoeModel",
726
+ "Qwen3MoePreTrainedModel",
727
+ "Qwen3MoeForSequenceClassification",
728
+ "Qwen3MoeForTokenClassification",
729
+ ]
730
+
special_tokens_map.json ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "additional_special_tokens": [
3
+ "<|im_start|>",
4
+ "<|im_end|>",
5
+ "<|object_ref_start|>",
6
+ "<|object_ref_end|>",
7
+ "<|box_start|>",
8
+ "<|box_end|>",
9
+ "<|quad_start|>",
10
+ "<|quad_end|>",
11
+ "<|vision_start|>",
12
+ "<|vision_end|>",
13
+ "<|vision_pad|>",
14
+ "<|image_pad|>",
15
+ "<|video_pad|>"
16
+ ],
17
+ "eos_token": {
18
+ "content": "<|endoftext|>",
19
+ "lstrip": false,
20
+ "normalized": false,
21
+ "rstrip": false,
22
+ "single_word": false
23
+ },
24
+ "pad_token": {
25
+ "content": "<|endoftext|>",
26
+ "lstrip": false,
27
+ "normalized": false,
28
+ "rstrip": false,
29
+ "single_word": false
30
+ }
31
+ }
tokenizer.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:aeb13307a71acd8fe81861d94ad54ab689df773318809eed3cbe794b4492dae4
3
+ size 11422654
tokenizer_config.json ADDED
@@ -0,0 +1,239 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_bos_token": false,
3
+ "add_prefix_space": false,
4
+ "added_tokens_decoder": {
5
+ "151643": {
6
+ "content": "<|endoftext|>",
7
+ "lstrip": false,
8
+ "normalized": false,
9
+ "rstrip": false,
10
+ "single_word": false,
11
+ "special": true
12
+ },
13
+ "151644": {
14
+ "content": "<|im_start|>",
15
+ "lstrip": false,
16
+ "normalized": false,
17
+ "rstrip": false,
18
+ "single_word": false,
19
+ "special": true
20
+ },
21
+ "151645": {
22
+ "content": "<|im_end|>",
23
+ "lstrip": false,
24
+ "normalized": false,
25
+ "rstrip": false,
26
+ "single_word": false,
27
+ "special": true
28
+ },
29
+ "151646": {
30
+ "content": "<|object_ref_start|>",
31
+ "lstrip": false,
32
+ "normalized": false,
33
+ "rstrip": false,
34
+ "single_word": false,
35
+ "special": true
36
+ },
37
+ "151647": {
38
+ "content": "<|object_ref_end|>",
39
+ "lstrip": false,
40
+ "normalized": false,
41
+ "rstrip": false,
42
+ "single_word": false,
43
+ "special": true
44
+ },
45
+ "151648": {
46
+ "content": "<|box_start|>",
47
+ "lstrip": false,
48
+ "normalized": false,
49
+ "rstrip": false,
50
+ "single_word": false,
51
+ "special": true
52
+ },
53
+ "151649": {
54
+ "content": "<|box_end|>",
55
+ "lstrip": false,
56
+ "normalized": false,
57
+ "rstrip": false,
58
+ "single_word": false,
59
+ "special": true
60
+ },
61
+ "151650": {
62
+ "content": "<|quad_start|>",
63
+ "lstrip": false,
64
+ "normalized": false,
65
+ "rstrip": false,
66
+ "single_word": false,
67
+ "special": true
68
+ },
69
+ "151651": {
70
+ "content": "<|quad_end|>",
71
+ "lstrip": false,
72
+ "normalized": false,
73
+ "rstrip": false,
74
+ "single_word": false,
75
+ "special": true
76
+ },
77
+ "151652": {
78
+ "content": "<|vision_start|>",
79
+ "lstrip": false,
80
+ "normalized": false,
81
+ "rstrip": false,
82
+ "single_word": false,
83
+ "special": true
84
+ },
85
+ "151653": {
86
+ "content": "<|vision_end|>",
87
+ "lstrip": false,
88
+ "normalized": false,
89
+ "rstrip": false,
90
+ "single_word": false,
91
+ "special": true
92
+ },
93
+ "151654": {
94
+ "content": "<|vision_pad|>",
95
+ "lstrip": false,
96
+ "normalized": false,
97
+ "rstrip": false,
98
+ "single_word": false,
99
+ "special": true
100
+ },
101
+ "151655": {
102
+ "content": "<|image_pad|>",
103
+ "lstrip": false,
104
+ "normalized": false,
105
+ "rstrip": false,
106
+ "single_word": false,
107
+ "special": true
108
+ },
109
+ "151656": {
110
+ "content": "<|video_pad|>",
111
+ "lstrip": false,
112
+ "normalized": false,
113
+ "rstrip": false,
114
+ "single_word": false,
115
+ "special": true
116
+ },
117
+ "151657": {
118
+ "content": "<tool_call>",
119
+ "lstrip": false,
120
+ "normalized": false,
121
+ "rstrip": false,
122
+ "single_word": false,
123
+ "special": false
124
+ },
125
+ "151658": {
126
+ "content": "</tool_call>",
127
+ "lstrip": false,
128
+ "normalized": false,
129
+ "rstrip": false,
130
+ "single_word": false,
131
+ "special": false
132
+ },
133
+ "151659": {
134
+ "content": "<|fim_prefix|>",
135
+ "lstrip": false,
136
+ "normalized": false,
137
+ "rstrip": false,
138
+ "single_word": false,
139
+ "special": false
140
+ },
141
+ "151660": {
142
+ "content": "<|fim_middle|>",
143
+ "lstrip": false,
144
+ "normalized": false,
145
+ "rstrip": false,
146
+ "single_word": false,
147
+ "special": false
148
+ },
149
+ "151661": {
150
+ "content": "<|fim_suffix|>",
151
+ "lstrip": false,
152
+ "normalized": false,
153
+ "rstrip": false,
154
+ "single_word": false,
155
+ "special": false
156
+ },
157
+ "151662": {
158
+ "content": "<|fim_pad|>",
159
+ "lstrip": false,
160
+ "normalized": false,
161
+ "rstrip": false,
162
+ "single_word": false,
163
+ "special": false
164
+ },
165
+ "151663": {
166
+ "content": "<|repo_name|>",
167
+ "lstrip": false,
168
+ "normalized": false,
169
+ "rstrip": false,
170
+ "single_word": false,
171
+ "special": false
172
+ },
173
+ "151664": {
174
+ "content": "<|file_sep|>",
175
+ "lstrip": false,
176
+ "normalized": false,
177
+ "rstrip": false,
178
+ "single_word": false,
179
+ "special": false
180
+ },
181
+ "151665": {
182
+ "content": "<tool_response>",
183
+ "lstrip": false,
184
+ "normalized": false,
185
+ "rstrip": false,
186
+ "single_word": false,
187
+ "special": false
188
+ },
189
+ "151666": {
190
+ "content": "</tool_response>",
191
+ "lstrip": false,
192
+ "normalized": false,
193
+ "rstrip": false,
194
+ "single_word": false,
195
+ "special": false
196
+ },
197
+ "151667": {
198
+ "content": "<think>",
199
+ "lstrip": false,
200
+ "normalized": false,
201
+ "rstrip": false,
202
+ "single_word": false,
203
+ "special": false
204
+ },
205
+ "151668": {
206
+ "content": "</think>",
207
+ "lstrip": false,
208
+ "normalized": false,
209
+ "rstrip": false,
210
+ "single_word": false,
211
+ "special": false
212
+ }
213
+ },
214
+ "additional_special_tokens": [
215
+ "<|im_start|>",
216
+ "<|im_end|>",
217
+ "<|object_ref_start|>",
218
+ "<|object_ref_end|>",
219
+ "<|box_start|>",
220
+ "<|box_end|>",
221
+ "<|quad_start|>",
222
+ "<|quad_end|>",
223
+ "<|vision_start|>",
224
+ "<|vision_end|>",
225
+ "<|vision_pad|>",
226
+ "<|image_pad|>",
227
+ "<|video_pad|>"
228
+ ],
229
+ "bos_token": null,
230
+ "clean_up_tokenization_spaces": false,
231
+ "eos_token": "<|endoftext|>",
232
+ "errors": "replace",
233
+ "extra_special_tokens": {},
234
+ "model_max_length": 131072,
235
+ "pad_token": "<|endoftext|>",
236
+ "split_special_tokens": false,
237
+ "tokenizer_class": "Qwen2Tokenizer",
238
+ "unk_token": null
239
+ }
vocab.json ADDED
The diff for this file is too large to render. See raw diff