rewardhacker00 commited on
Commit
9810314
·
verified ·
1 Parent(s): 35b8ac4

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
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,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {%- if tools %}
2
+ {{- '<|im_start|>system\n' }}
3
+ {%- if messages[0]['role'] == 'system' %}
4
+ {{- messages[0]['content'] }}
5
+ {%- else %}
6
+ {{- 'You are Qwen, created by Alibaba Cloud. You are a helpful assistant.' }}
7
+ {%- endif %}
8
+ {{- "\n\n# Tools\n\nYou may call one or more functions to assist with the user query.\n\nYou are provided with function signatures within <tools></tools> XML tags:\n<tools>" }}
9
+ {%- for tool in tools %}
10
+ {{- "\n" }}
11
+ {{- tool | tojson }}
12
+ {%- endfor %}
13
+ {{- "\n</tools>\n\nFor each function call, return a json object with function name and arguments within <tool_call></tool_call> XML tags:\n<tool_call>\n{\"name\": <function-name>, \"arguments\": <args-json-object>}\n</tool_call><|im_end|>\n" }}
14
+ {%- else %}
15
+ {%- if messages[0]['role'] == 'system' %}
16
+ {{- '<|im_start|>system\n' + messages[0]['content'] + '<|im_end|>\n' }}
17
+ {%- else %}
18
+ {{- '<|im_start|>system\nYou are Qwen, created by Alibaba Cloud. You are a helpful assistant.<|im_end|>\n' }}
19
+ {%- endif %}
20
+ {%- endif %}
21
+ {%- for message in messages %}
22
+ {%- if (message.role == "user") or (message.role == "system" and not loop.first) or (message.role == "assistant" and not message.tool_calls) %}
23
+ {{- '<|im_start|>' + message.role + '\n' + message.content + '<|im_end|>' + '\n' }}
24
+ {%- elif message.role == "assistant" %}
25
+ {{- '<|im_start|>' + message.role }}
26
+ {%- if message.content %}
27
+ {{- '\n' + message.content }}
28
+ {%- endif %}
29
+ {%- for tool_call in message.tool_calls %}
30
+ {%- if tool_call.function is defined %}
31
+ {%- set tool_call = tool_call.function %}
32
+ {%- endif %}
33
+ {{- '\n<tool_call>\n{"name": "' }}
34
+ {{- tool_call.name }}
35
+ {{- '", "arguments": ' }}
36
+ {{- tool_call.arguments | tojson }}
37
+ {{- '}\n</tool_call>' }}
38
+ {%- endfor %}
39
+ {{- '<|im_end|>\n' }}
40
+ {%- elif message.role == "tool" %}
41
+ {%- if (loop.index0 == 0) or (messages[loop.index0 - 1].role != "tool") %}
42
+ {{- '<|im_start|>user' }}
43
+ {%- endif %}
44
+ {{- '\n<tool_response>\n' }}
45
+ {{- message.content }}
46
+ {{- '\n</tool_response>' }}
47
+ {%- if loop.last or (messages[loop.index0 + 1].role != "tool") %}
48
+ {{- '<|im_end|>\n' }}
49
+ {%- endif %}
50
+ {%- endif %}
51
+ {%- endfor %}
52
+ {%- if add_generation_prompt %}
53
+ {{- '<|im_start|>assistant\n' }}
54
+ {%- endif %}
config.json ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "Qwen3MoeForCausalLM"
4
+ ],
5
+ "attention_bias": false,
6
+ "attention_dropout": 0.0,
7
+ "auto_map": {
8
+ "AutoConfig": "configuration_qwen3_moe.Qwen3MoeConfig",
9
+ "AutoModel": "modeling_qwen3_moe.Qwen3MoeModel",
10
+ "AutoModelForCausalLM": "modeling_qwen3_moe.Qwen3MoeForCausalLM"
11
+ },
12
+ "bos_token_id": 151643,
13
+ "decoder_sparse_step": 1,
14
+ "dtype": "bfloat16",
15
+ "eos_token_id": 151645,
16
+ "head_dim": 128,
17
+ "hidden_act": "silu",
18
+ "hidden_size": 1024,
19
+ "initializer_range": 0.02,
20
+ "intermediate_size": 6144,
21
+ "load_balance_coeff": 0.001,
22
+ "max_position_embeddings": 4096,
23
+ "max_window_layers": 48,
24
+ "mlp_only_layers": [],
25
+ "model_type": "qwen3_moe",
26
+ "moe_intermediate_size": 256,
27
+ "norm_topk_prob": true,
28
+ "num_attention_heads": 16,
29
+ "num_experts": 16,
30
+ "num_experts_per_tok": 4,
31
+ "num_hidden_layers": 12,
32
+ "num_key_value_heads": 4,
33
+ "output_router_logits": false,
34
+ "rms_norm_eps": 1e-06,
35
+ "rope_scaling": null,
36
+ "rope_theta": 1000000.0,
37
+ "router_aux_loss_coef": 0.001,
38
+ "sliding_window": null,
39
+ "tie_word_embeddings": false,
40
+ "transformers_version": "4.56.1",
41
+ "use_cache": false,
42
+ "use_grouped_mm": true,
43
+ "use_sliding_window": false,
44
+ "vocab_size": 151936
45
+ }
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=None,
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,6 @@
 
 
 
 
 
 
 
1
+ {
2
+ "bos_token_id": 151643,
3
+ "eos_token_id": 151643,
4
+ "max_new_tokens": 2048,
5
+ "transformers_version": "4.56.1"
6
+ }
merges.txt ADDED
The diff for this file is too large to render. See raw diff
 
modeling_qwen3_moe.py ADDED
@@ -0,0 +1,722 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ attention_interface: Callable = eager_attention_forward
171
+ if self.config._attn_implementation != "eager":
172
+ attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
173
+
174
+ attn_output, attn_weights = attention_interface(
175
+ self,
176
+ query_states,
177
+ key_states,
178
+ value_states,
179
+ attention_mask,
180
+ dropout=0.0 if not self.training else self.attention_dropout,
181
+ scaling=self.scaling,
182
+ sliding_window=self.sliding_window, # diff with Llama
183
+ **kwargs,
184
+ )
185
+
186
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
187
+ attn_output = self.o_proj(attn_output)
188
+ return attn_output, attn_weights
189
+
190
+
191
+ class Qwen3MoeMLP(nn.Module):
192
+ def __init__(self, config, intermediate_size=None):
193
+ super().__init__()
194
+ self.config = config
195
+ self.hidden_size = config.hidden_size
196
+ self.intermediate_size = intermediate_size if intermediate_size is not None else config.intermediate_size
197
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
198
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
199
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
200
+ self.act_fn = ACT2FN[config.hidden_act]
201
+
202
+ def forward(self, x):
203
+ down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
204
+ return down_proj
205
+
206
+
207
+ class Qwen3MoeSparseMoeBlock(nn.Module):
208
+ def __init__(self, config):
209
+ super().__init__()
210
+ self.num_experts = config.num_experts
211
+ self.top_k = config.num_experts_per_tok
212
+ self.norm_topk_prob = config.norm_topk_prob
213
+
214
+ # gating
215
+ self.gate = nn.Linear(config.hidden_size, config.num_experts, bias=False)
216
+ self.experts = nn.ModuleList(
217
+ [Qwen3MoeMLP(config, intermediate_size=config.moe_intermediate_size) for _ in range(self.num_experts)]
218
+ )
219
+
220
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
221
+ """ """
222
+ batch_size, sequence_length, hidden_dim = hidden_states.shape
223
+ hidden_states = hidden_states.view(-1, hidden_dim)
224
+ # router_logits: (batch * sequence_length, n_experts)
225
+ router_logits = self.gate(hidden_states)
226
+
227
+ routing_weights = F.softmax(router_logits, dim=1, dtype=torch.float)
228
+ routing_weights, selected_experts = torch.topk(routing_weights, self.top_k, dim=-1)
229
+ if self.norm_topk_prob: # only diff with mixtral sparse moe block!
230
+ routing_weights /= routing_weights.sum(dim=-1, keepdim=True)
231
+ # we cast back to the input dtype
232
+ routing_weights = routing_weights.to(hidden_states.dtype)
233
+
234
+ final_hidden_states = torch.zeros(
235
+ (batch_size * sequence_length, hidden_dim), dtype=hidden_states.dtype, device=hidden_states.device
236
+ )
237
+
238
+ # One hot encode the selected experts to create an expert mask
239
+ # this will be used to easily index which expert is going to be sollicitated
240
+ expert_mask = torch.nn.functional.one_hot(selected_experts, num_classes=self.num_experts).permute(2, 1, 0)
241
+
242
+ # Loop over all available experts in the model and perform the computation on each expert
243
+ expert_hitted = torch.greater(expert_mask.sum(dim=(-1, -2)), 0).nonzero()
244
+ for expert_idx in expert_hitted:
245
+ expert_layer = self.experts[expert_idx]
246
+ idx, top_x = torch.where(expert_mask[expert_idx].squeeze(0))
247
+
248
+ # Index the correct hidden states and compute the expert hidden state for
249
+ # the current expert. We need to make sure to multiply the output hidden
250
+ # states by `routing_weights` on the corresponding tokens (top-1 and top-2)
251
+ current_state = hidden_states[None, top_x].reshape(-1, hidden_dim)
252
+ current_hidden_states = expert_layer(current_state) * routing_weights[top_x, idx, None]
253
+
254
+ # However `index_add_` only support torch tensors for indexing so we'll use
255
+ # the `top_x` tensor here.
256
+ final_hidden_states.index_add_(0, top_x, current_hidden_states.to(hidden_states.dtype))
257
+ final_hidden_states = final_hidden_states.reshape(batch_size, sequence_length, hidden_dim)
258
+ return final_hidden_states, router_logits
259
+
260
+
261
+ @use_kernel_forward_from_hub("RMSNorm")
262
+ class Qwen3MoeRMSNorm(nn.Module):
263
+ def __init__(self, hidden_size, eps=1e-6):
264
+ """
265
+ Qwen3MoeRMSNorm is equivalent to T5LayerNorm
266
+ """
267
+ super().__init__()
268
+ self.weight = nn.Parameter(torch.ones(hidden_size))
269
+ self.variance_epsilon = eps
270
+
271
+ def forward(self, hidden_states):
272
+ input_dtype = hidden_states.dtype
273
+ hidden_states = hidden_states.to(torch.float32)
274
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
275
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
276
+ return self.weight * hidden_states.to(input_dtype)
277
+
278
+ def extra_repr(self):
279
+ return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
280
+
281
+
282
+ class Qwen3MoeDecoderLayer(GradientCheckpointingLayer):
283
+ def __init__(self, config: Qwen3MoeConfig, layer_idx: int):
284
+ super().__init__()
285
+ self.hidden_size = config.hidden_size
286
+
287
+ self.self_attn = Qwen3MoeAttention(config, layer_idx)
288
+
289
+ moe_args = MoEArgs(
290
+ num_experts=config.num_experts,
291
+ num_shared_experts=0,
292
+ score_func="softmax",
293
+ route_norm=config.norm_topk_prob,
294
+ route_scale=1.0,
295
+ score_before_experts=False,
296
+ top_k=config.num_experts_per_tok,
297
+ use_grouped_mm=True,
298
+ load_balance_coeff=config.load_balance_coeff,
299
+ )
300
+
301
+ if (layer_idx not in config.mlp_only_layers) and (
302
+ config.num_experts > 0 and (layer_idx + 1) % config.decoder_sparse_step == 0
303
+ ):
304
+ self.mlp = MoE(moe_args, dim=config.hidden_size, hidden_dim=config.moe_intermediate_size)
305
+ else:
306
+ self.mlp = Qwen3MoeMLP(config, intermediate_size=config.intermediate_size)
307
+
308
+ self.input_layernorm = Qwen3MoeRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
309
+ self.post_attention_layernorm = Qwen3MoeRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
310
+
311
+ def forward(
312
+ self,
313
+ hidden_states: torch.Tensor,
314
+ position_embeddings: tuple[torch.Tensor, torch.Tensor],
315
+ attention_mask: Optional[torch.Tensor] = None,
316
+ position_ids: Optional[torch.LongTensor] = None,
317
+ past_key_value: Optional[tuple[torch.Tensor]] = None,
318
+ cache_position: Optional[torch.LongTensor] = None,
319
+ **kwargs: Unpack[FlashAttentionKwargs],
320
+ ) -> torch.FloatTensor:
321
+ """
322
+ Args:
323
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
324
+ attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
325
+ `(batch, sequence_length)` where padding elements are indicated by 0.
326
+ output_attentions (`bool`, *optional*):
327
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
328
+ returned tensors for more detail.
329
+ output_router_logits (`bool`, *optional*):
330
+ Whether or not to return the logits of all the routers. They are useful for computing the router loss,
331
+ and should not be returned during inference.
332
+ use_cache (`bool`, *optional*):
333
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
334
+ (see `past_key_values`).
335
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
336
+ cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
337
+ Indices depicting the position of the input sequence tokens in the sequence.
338
+ position_embeddings (`tuple[torch.FloatTensor, torch.FloatTensor]`, *optional*):
339
+ Tuple containing the cosine and sine positional embeddings of shape `(batch_size, seq_len, head_dim)`,
340
+ with `head_dim` being the embedding dimension of each attention head.
341
+ kwargs (`dict`, *optional*):
342
+ Arbitrary kwargs to be ignored, used for FSDP and other methods that injects code
343
+ into the model
344
+ """
345
+ residual = hidden_states
346
+
347
+ hidden_states = self.input_layernorm(hidden_states)
348
+
349
+ # Self Attention
350
+ hidden_states, _ = self.self_attn(
351
+ hidden_states=hidden_states,
352
+ position_embeddings=position_embeddings,
353
+ attention_mask=attention_mask,
354
+ position_ids=position_ids,
355
+ past_key_value=past_key_value,
356
+ cache_position=cache_position,
357
+ **kwargs,
358
+ )
359
+ hidden_states = residual + hidden_states
360
+
361
+ # Fully Connected
362
+ residual = hidden_states
363
+ hidden_states = self.post_attention_layernorm(hidden_states)
364
+ hidden_states = self.mlp(hidden_states)
365
+ # For the MoE layers, we need to unpack
366
+ if isinstance(hidden_states, tuple):
367
+ hidden_states, _ = hidden_states
368
+ hidden_states = residual + hidden_states
369
+
370
+ return hidden_states
371
+
372
+
373
+ class Qwen3MoeRotaryEmbedding(nn.Module):
374
+ def __init__(self, config: Qwen3MoeConfig, device=None):
375
+ super().__init__()
376
+ # BC: "rope_type" was originally "type"
377
+ if hasattr(config, "rope_scaling") and isinstance(config.rope_scaling, dict):
378
+ self.rope_type = config.rope_scaling.get("rope_type", config.rope_scaling.get("type"))
379
+ else:
380
+ self.rope_type = "default"
381
+ self.max_seq_len_cached = config.max_position_embeddings
382
+ self.original_max_seq_len = config.max_position_embeddings
383
+
384
+ self.config = config
385
+ self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
386
+
387
+ inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device)
388
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
389
+ self.original_inv_freq = self.inv_freq
390
+
391
+ @torch.no_grad()
392
+ @dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope)
393
+ def forward(self, x, position_ids):
394
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device)
395
+ position_ids_expanded = position_ids[:, None, :].float()
396
+
397
+ device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
398
+ with torch.autocast(device_type=device_type, enabled=False): # Force float32
399
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
400
+ emb = torch.cat((freqs, freqs), dim=-1)
401
+ cos = emb.cos() * self.attention_scaling
402
+ sin = emb.sin() * self.attention_scaling
403
+
404
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
405
+
406
+
407
+ @auto_docstring
408
+ class Qwen3MoePreTrainedModel(PreTrainedModel):
409
+ config: Qwen3MoeConfig
410
+ base_model_prefix = "model"
411
+ supports_gradient_checkpointing = True
412
+ _no_split_modules = ["Qwen3MoeDecoderLayer"]
413
+ _skip_keys_device_placement = ["past_key_values"]
414
+ _supports_flash_attn = True
415
+ _supports_sdpa = True
416
+ _supports_flex_attn = True
417
+ _can_compile_fullgraph = False # MoE models don't work with torch.compile (`torch.where(condition)` not supported)
418
+ _supports_attention_backend = True
419
+ _can_record_outputs = {
420
+ "router_logits": OutputRecorder(Qwen3MoeSparseMoeBlock, index=1),
421
+ "hidden_states": Qwen3MoeDecoderLayer,
422
+ "attentions": Qwen3MoeAttention,
423
+ }
424
+
425
+
426
+ @auto_docstring
427
+ class Qwen3MoeModel(Qwen3MoePreTrainedModel):
428
+ def __init__(self, config: Qwen3MoeConfig):
429
+ super().__init__(config)
430
+ self.padding_idx = config.pad_token_id
431
+ self.vocab_size = config.vocab_size
432
+
433
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
434
+ self.layers = nn.ModuleList(
435
+ [Qwen3MoeDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
436
+ )
437
+ self.norm = Qwen3MoeRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
438
+ self.rotary_emb = Qwen3MoeRotaryEmbedding(config=config)
439
+ self.gradient_checkpointing = False
440
+
441
+ # Initialize weights and apply final processing
442
+ self.post_init()
443
+
444
+ @check_model_inputs
445
+ @auto_docstring
446
+ def forward(
447
+ self,
448
+ input_ids: Optional[torch.LongTensor] = None,
449
+ attention_mask: Optional[torch.Tensor] = None,
450
+ position_ids: Optional[torch.LongTensor] = None,
451
+ past_key_values: Optional[Cache] = None,
452
+ inputs_embeds: Optional[torch.FloatTensor] = None,
453
+ use_cache: Optional[bool] = None,
454
+ cache_position: Optional[torch.LongTensor] = None,
455
+ **kwargs: Unpack[TransformersKwargs],
456
+ ) -> MoeModelOutputWithPast:
457
+ if (input_ids is None) ^ (inputs_embeds is not None):
458
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
459
+
460
+ if use_cache and past_key_values is None:
461
+ past_key_values = DynamicCache()
462
+
463
+ if inputs_embeds is None:
464
+ inputs_embeds = self.embed_tokens(input_ids)
465
+
466
+ if cache_position is None:
467
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
468
+ cache_position = torch.arange(
469
+ past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
470
+ )
471
+ if position_ids is None:
472
+ position_ids = cache_position.unsqueeze(0)
473
+
474
+ mask_function = create_causal_mask if self.config.sliding_window is None else create_sliding_window_causal_mask
475
+ causal_mask = mask_function(
476
+ config=self.config,
477
+ input_embeds=inputs_embeds,
478
+ attention_mask=attention_mask,
479
+ cache_position=cache_position,
480
+ past_key_values=past_key_values,
481
+ position_ids=position_ids,
482
+ )
483
+
484
+ hidden_states = inputs_embeds
485
+
486
+ # create position embeddings to be shared across the decoder layers
487
+ position_embeddings = self.rotary_emb(hidden_states, position_ids)
488
+
489
+ for decoder_layer in self.layers[: self.config.num_hidden_layers]:
490
+ hidden_states = decoder_layer(
491
+ hidden_states,
492
+ position_embeddings=position_embeddings,
493
+ attention_mask=causal_mask,
494
+ position_ids=position_ids,
495
+ past_key_value=past_key_values,
496
+ use_cache=use_cache,
497
+ cache_position=cache_position,
498
+ **kwargs,
499
+ )
500
+
501
+ hidden_states = self.norm(hidden_states)
502
+
503
+ return MoeModelOutputWithPast( # only diff with Mistral is the output type, we need MoE
504
+ last_hidden_state=hidden_states,
505
+ past_key_values=past_key_values,
506
+ )
507
+
508
+
509
+ def load_balancing_loss_func(
510
+ gate_logits: Union[torch.Tensor, tuple[torch.Tensor], None],
511
+ num_experts: Optional[int] = None,
512
+ top_k=2,
513
+ attention_mask: Optional[torch.Tensor] = None,
514
+ ) -> Union[torch.Tensor, int]:
515
+ r"""
516
+ Computes auxiliary load balancing loss as in Switch Transformer - implemented in Pytorch.
517
+
518
+ See Switch Transformer (https://huggingface.co/papers/2101.03961) for more details. This function implements the loss
519
+ function presented in equations (4) - (6) of the paper. It aims at penalizing cases where the routing between
520
+ experts is too unbalanced.
521
+
522
+ Args:
523
+ gate_logits:
524
+ Logits from the `gate`, should be a tuple of model.config.num_hidden_layers tensors of
525
+ shape [batch_size X sequence_length, num_experts].
526
+ num_experts:
527
+ Number of experts
528
+ top_k:
529
+ The number of experts to route per-token, can be also interpreted as the `top-k` routing
530
+ parameter.
531
+ attention_mask (`torch.Tensor`, *optional*):
532
+ The attention_mask used in forward function
533
+ shape [batch_size X sequence_length] if not None.
534
+
535
+ Returns:
536
+ The auxiliary loss.
537
+ """
538
+ if gate_logits is None or not isinstance(gate_logits, tuple):
539
+ return 0
540
+
541
+ if isinstance(gate_logits, tuple):
542
+ compute_device = gate_logits[0].device
543
+ concatenated_gate_logits = torch.cat([layer_gate.to(compute_device) for layer_gate in gate_logits], dim=0)
544
+
545
+ routing_weights = torch.nn.functional.softmax(concatenated_gate_logits, dim=-1)
546
+
547
+ _, selected_experts = torch.topk(routing_weights, top_k, dim=-1)
548
+
549
+ expert_mask = torch.nn.functional.one_hot(selected_experts, num_experts)
550
+
551
+ if attention_mask is None:
552
+ # Compute the percentage of tokens routed to each experts
553
+ tokens_per_expert = torch.mean(expert_mask.float(), dim=0)
554
+
555
+ # Compute the average probability of routing to these experts
556
+ router_prob_per_expert = torch.mean(routing_weights, dim=0)
557
+ else:
558
+ batch_size, sequence_length = attention_mask.shape
559
+ num_hidden_layers = concatenated_gate_logits.shape[0] // (batch_size * sequence_length)
560
+
561
+ # Compute the mask that masks all padding tokens as 0 with the same shape of expert_mask
562
+ expert_attention_mask = (
563
+ attention_mask[None, :, :, None, None]
564
+ .expand((num_hidden_layers, batch_size, sequence_length, top_k, num_experts))
565
+ .reshape(-1, top_k, num_experts)
566
+ .to(compute_device)
567
+ )
568
+
569
+ # Compute the percentage of tokens routed to each experts
570
+ tokens_per_expert = torch.sum(expert_mask.float() * expert_attention_mask, dim=0) / torch.sum(
571
+ expert_attention_mask, dim=0
572
+ )
573
+
574
+ # Compute the mask that masks all padding tokens as 0 with the same shape of tokens_per_expert
575
+ router_per_expert_attention_mask = (
576
+ attention_mask[None, :, :, None]
577
+ .expand((num_hidden_layers, batch_size, sequence_length, num_experts))
578
+ .reshape(-1, num_experts)
579
+ .to(compute_device)
580
+ )
581
+
582
+ # Compute the average probability of routing to these experts
583
+ router_prob_per_expert = torch.sum(routing_weights * router_per_expert_attention_mask, dim=0) / torch.sum(
584
+ router_per_expert_attention_mask, dim=0
585
+ )
586
+
587
+ overall_loss = torch.sum(tokens_per_expert * router_prob_per_expert.unsqueeze(0))
588
+ return overall_loss * num_experts
589
+
590
+
591
+ @auto_docstring
592
+ class Qwen3MoeForCausalLM(Qwen3MoePreTrainedModel, GenerationMixin):
593
+ _tied_weights_keys = ["lm_head.weight"]
594
+ _tp_plan = {"lm_head": "colwise_rep"}
595
+ _pp_plan = {"lm_head": (["hidden_states"], ["logits"])}
596
+
597
+ def __init__(self, config):
598
+ super().__init__(config)
599
+ self.model = Qwen3MoeModel(config)
600
+ self.vocab_size = config.vocab_size
601
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
602
+ self.router_aux_loss_coef = config.router_aux_loss_coef
603
+ self.num_experts = config.num_experts
604
+ self.num_experts_per_tok = config.num_experts_per_tok
605
+
606
+ # Initialize weights and apply final processing
607
+ self.post_init()
608
+
609
+ def set_decoder(self, decoder):
610
+ self.model = decoder
611
+
612
+ def get_decoder(self):
613
+ return self.model
614
+
615
+ @can_return_tuple
616
+ @auto_docstring
617
+ def forward(
618
+ self,
619
+ input_ids: Optional[torch.LongTensor] = None,
620
+ attention_mask: Optional[torch.Tensor] = None,
621
+ position_ids: Optional[torch.LongTensor] = None,
622
+ past_key_values: Optional[Cache] = None,
623
+ inputs_embeds: Optional[torch.FloatTensor] = None,
624
+ labels: Optional[torch.LongTensor] = None,
625
+ use_cache: Optional[bool] = None,
626
+ output_router_logits: Optional[bool] = None,
627
+ cache_position: Optional[torch.LongTensor] = None,
628
+ logits_to_keep: Union[int, torch.Tensor] = 0,
629
+ **kwargs: Unpack[TransformersKwargs],
630
+ ) -> MoeCausalLMOutputWithPast:
631
+ r"""
632
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
633
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
634
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
635
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
636
+
637
+ Example:
638
+
639
+ ```python
640
+ >>> from transformers import AutoTokenizer, Qwen3MoeForCausalLM
641
+
642
+ >>> model = Qwen3MoeForCausalLM.from_pretrained("Qwen/Qwen3-MoE-15B-A2B")
643
+ >>> tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen3-MoE-15B-A2B")
644
+
645
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
646
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
647
+
648
+ >>> # Generate
649
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
650
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
651
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
652
+ ```"""
653
+
654
+ output_router_logits = (
655
+ output_router_logits if output_router_logits is not None else self.config.output_router_logits
656
+ )
657
+
658
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
659
+ outputs: MoeModelOutputWithPast = self.model(
660
+ input_ids=input_ids,
661
+ attention_mask=attention_mask,
662
+ position_ids=position_ids,
663
+ past_key_values=past_key_values,
664
+ inputs_embeds=inputs_embeds,
665
+ use_cache=use_cache,
666
+ output_router_logits=output_router_logits,
667
+ cache_position=cache_position,
668
+ **kwargs,
669
+ )
670
+
671
+ hidden_states = outputs.last_hidden_state
672
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
673
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
674
+ logits = self.lm_head(hidden_states[:, slice_indices, :])
675
+
676
+ loss = None
677
+ if labels is not None:
678
+ loss = self.loss_function(logits, labels, self.vocab_size, **kwargs)
679
+
680
+ aux_loss = None
681
+ if output_router_logits:
682
+ aux_loss = load_balancing_loss_func(
683
+ outputs.router_logits,
684
+ self.num_experts,
685
+ self.num_experts_per_tok,
686
+ attention_mask,
687
+ )
688
+ if labels is not None:
689
+ loss += self.router_aux_loss_coef * aux_loss.to(loss.device) # make sure to reside in the same device
690
+
691
+ return MoeCausalLMOutputWithPast(
692
+ loss=loss,
693
+ aux_loss=aux_loss,
694
+ logits=logits,
695
+ past_key_values=outputs.past_key_values,
696
+ hidden_states=outputs.hidden_states,
697
+ attentions=outputs.attentions,
698
+ router_logits=outputs.router_logits,
699
+ )
700
+
701
+
702
+ class Qwen3MoeForSequenceClassification(GenericForSequenceClassification, Qwen3MoePreTrainedModel):
703
+ pass
704
+
705
+
706
+ class Qwen3MoeForTokenClassification(GenericForTokenClassification, Qwen3MoePreTrainedModel):
707
+ pass
708
+
709
+
710
+ class Qwen3MoeForQuestionAnswering(GenericForQuestionAnswering, Qwen3MoePreTrainedModel):
711
+ base_model_prefix = "transformer" # For BC, where `transformer` was used instead of `model`
712
+
713
+
714
+ __all__ = [
715
+ "Qwen3MoeForCausalLM",
716
+ "Qwen3MoeForQuestionAnswering",
717
+ "Qwen3MoeModel",
718
+ "Qwen3MoePreTrainedModel",
719
+ "Qwen3MoeForSequenceClassification",
720
+ "Qwen3MoeForTokenClassification",
721
+ ]
722
+
pytorch_model.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:29907f42724ef09eb5475e66ea59ec200802f439fcaa8384080b58ba23c54e98
3
+ size 1050723423
special_tokens_map.json ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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": "<|endoftext|>"
25
+ }
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