HaoxingChen commited on
Commit
7ae75f8
·
verified ·
1 Parent(s): 2eb384c

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
config.json ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "modeling_grove_moe.GroveMoeForCausalLM"
4
+ ],
5
+ "auto_map": {
6
+ "AutoConfig": "configuration_qwen3_moe.Qwen3MoeConfig",
7
+ "AutoModel": "modeling_grove_moe.GroveMoeModel",
8
+ "AutoModelForCausalLM": "modeling_grove_moe.GroveMoeForCausalLM"
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,240 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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-MoE-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 checkout [this
53
+ paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to `32`.
54
+ hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
55
+ The non-linear activation function (function or string) in the decoder.
56
+ max_position_embeddings (`int`, *optional*, defaults to 32768):
57
+ The maximum sequence length that this model might ever be used with.
58
+ initializer_range (`float`, *optional*, defaults to 0.02):
59
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
60
+ rms_norm_eps (`float`, *optional*, defaults to 1e-06):
61
+ The epsilon used by the rms normalization layers.
62
+ use_cache (`bool`, *optional*, defaults to `True`):
63
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
64
+ relevant if `config.is_decoder=True`.
65
+ tie_word_embeddings (`bool`, *optional*, defaults to `False`):
66
+ Whether the model's input and output word embeddings should be tied.
67
+ rope_theta (`float`, *optional*, defaults to 10000.0):
68
+ The base period of the RoPE embeddings.
69
+ rope_scaling (`Dict`, *optional*):
70
+ Dictionary containing the scaling configuration for the RoPE embeddings. NOTE: if you apply new rope type
71
+ and you expect the model to work on longer `max_position_embeddings`, we recommend you to update this value
72
+ accordingly.
73
+ Expected contents:
74
+ `rope_type` (`str`):
75
+ The sub-variant of RoPE to use. Can be one of ['default', 'linear', 'dynamic', 'yarn', 'longrope',
76
+ 'llama3'], with 'default' being the original RoPE implementation.
77
+ `factor` (`float`, *optional*):
78
+ Used with all rope types except 'default'. The scaling factor to apply to the RoPE embeddings. In
79
+ most scaling types, a `factor` of x will enable the model to handle sequences of length x *
80
+ original maximum pre-trained length.
81
+ `original_max_position_embeddings` (`int`, *optional*):
82
+ Used with 'dynamic', 'longrope' and 'llama3'. The original max position embeddings used during
83
+ pretraining.
84
+ `attention_factor` (`float`, *optional*):
85
+ Used with 'yarn' and 'longrope'. The scaling factor to be applied on the attention
86
+ computation. If unspecified, it defaults to value recommended by the implementation, using the
87
+ `factor` field to infer the suggested value.
88
+ `beta_fast` (`float`, *optional*):
89
+ Only used with 'yarn'. Parameter to set the boundary for extrapolation (only) in the linear
90
+ ramp function. If unspecified, it defaults to 32.
91
+ `beta_slow` (`float`, *optional*):
92
+ Only used with 'yarn'. Parameter to set the boundary for interpolation (only) in the linear
93
+ ramp function. If unspecified, it defaults to 1.
94
+ `short_factor` (`List[float]`, *optional*):
95
+ Only used with 'longrope'. The scaling factor to be applied to short contexts (<
96
+ `original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
97
+ size divided by the number of attention heads divided by 2
98
+ `long_factor` (`List[float]`, *optional*):
99
+ Only used with 'longrope'. The scaling factor to be applied to long contexts (<
100
+ `original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
101
+ size divided by the number of attention heads divided by 2
102
+ `low_freq_factor` (`float`, *optional*):
103
+ Only used with 'llama3'. Scaling factor applied to low frequency components of the RoPE
104
+ `high_freq_factor` (`float`, *optional*):
105
+ Only used with 'llama3'. Scaling factor applied to high frequency components of the RoPE
106
+ attention_bias (`bool`, defaults to `False`, *optional*, defaults to `False`):
107
+ Whether to use a bias in the query, key, value and output projection layers during self-attention.
108
+ use_sliding_window (`bool`, *optional*, defaults to `False`):
109
+ Whether to use sliding window attention.
110
+ sliding_window (`int`, *optional*, defaults to 4096):
111
+ Sliding window attention (SWA) window size. If not specified, will default to `4096`.
112
+ max_window_layers (`int`, *optional*, defaults to 28):
113
+ The number of layers that use SWA (Sliding Window Attention). The bottom layers use SWA while the top use full attention.
114
+ attention_dropout (`float`, *optional*, defaults to 0.0):
115
+ The dropout ratio for the attention probabilities.
116
+ decoder_sparse_step (`int`, *optional*, defaults to 1):
117
+ The frequency of the MoE layer.
118
+ moe_intermediate_size (`int`, *optional*, defaults to 768):
119
+ Intermediate size of the routed expert.
120
+ num_experts_per_tok (`int`, *optional*, defaults to 8):
121
+ Number of selected experts.
122
+ num_experts (`int`, *optional*, defaults to 128):
123
+ Number of routed experts.
124
+ norm_topk_prob (`bool`, *optional*, defaults to `False`):
125
+ Whether to normalize the topk probabilities.
126
+ output_router_logits (`bool`, *optional*, defaults to `False`):
127
+ Whether or not the router logits should be returned by the model. Enabeling this will also
128
+ allow the model to output the auxiliary loss, including load balancing loss and router z-loss.
129
+ router_aux_loss_coef (`float`, *optional*, defaults to 0.001):
130
+ The aux loss factor for the total loss.
131
+ mlp_only_layers (`List[int]`, *optional*, defaults to `[]`):
132
+ Indicate which layers use Qwen3MoeMLP rather than Qwen3MoeSparseMoeBlock
133
+ The list contains layer index, from 0 to num_layers-1 if we have num_layers layers
134
+ If `mlp_only_layers` is empty, `decoder_sparse_step` is used to determine the sparsity.
135
+
136
+ ```python
137
+ >>> from transformers import Qwen3MoeModel, Qwen3MoeConfig
138
+
139
+ >>> # Initializing a Qwen3MoE style configuration
140
+ >>> configuration = Qwen3MoeConfig()
141
+
142
+ >>> # Initializing a model from the Qwen3-15B-A2B" style configuration
143
+ >>> model = Qwen3MoeModel(configuration)
144
+
145
+ >>> # Accessing the model configuration
146
+ >>> configuration = model.config
147
+ ```"""
148
+
149
+ model_type = "qwen3_moe"
150
+ keys_to_ignore_at_inference = ["past_key_values"]
151
+
152
+ # Default tensor parallel plan for base model `Qwen3Moe`
153
+ base_model_tp_plan = {
154
+ "layers.*.self_attn.q_proj": "colwise",
155
+ "layers.*.self_attn.k_proj": "colwise",
156
+ "layers.*.self_attn.v_proj": "colwise",
157
+ "layers.*.self_attn.o_proj": "rowwise",
158
+ "layers.*.mlp.gate_proj": "colwise",
159
+ "layers.*.mlp.up_proj": "colwise",
160
+ "layers.*.mlp.down_proj": "rowwise",
161
+ }
162
+ base_model_pp_plan = {
163
+ "embed_tokens": (["input_ids"], ["inputs_embeds"]),
164
+ "layers": (["hidden_states", "attention_mask"], ["hidden_states"]),
165
+ "norm": (["hidden_states"], ["hidden_states"]),
166
+ }
167
+
168
+ def __init__(
169
+ self,
170
+ vocab_size=151936,
171
+ hidden_size=2048,
172
+ intermediate_size=6144,
173
+ num_hidden_layers=24,
174
+ num_attention_heads=32,
175
+ num_key_value_heads=4,
176
+ hidden_act="silu",
177
+ max_position_embeddings=32768,
178
+ initializer_range=0.02,
179
+ rms_norm_eps=1e-6,
180
+ use_cache=True,
181
+ tie_word_embeddings=False,
182
+ rope_theta=10000.0,
183
+ rope_scaling=None,
184
+ attention_bias=False,
185
+ use_sliding_window=False,
186
+ sliding_window=4096,
187
+ max_window_layers=28,
188
+ attention_dropout=0.0,
189
+ decoder_sparse_step=1,
190
+ moe_intermediate_size=768,
191
+ num_experts_per_tok=8,
192
+ num_experts=128,
193
+ norm_topk_prob=False,
194
+ output_router_logits=False,
195
+ router_aux_loss_coef=0.001,
196
+ mlp_only_layers=None,
197
+ **kwargs,
198
+ ):
199
+ self.vocab_size = vocab_size
200
+ self.max_position_embeddings = max_position_embeddings
201
+ self.hidden_size = hidden_size
202
+ self.intermediate_size = intermediate_size
203
+ self.num_hidden_layers = num_hidden_layers
204
+ self.num_attention_heads = num_attention_heads
205
+ self.use_sliding_window = use_sliding_window
206
+ self.sliding_window = sliding_window if use_sliding_window else None
207
+ self.max_window_layers = max_window_layers
208
+
209
+ self.num_key_value_heads = num_key_value_heads
210
+ self.hidden_act = hidden_act
211
+ self.initializer_range = initializer_range
212
+ self.rms_norm_eps = rms_norm_eps
213
+ self.use_cache = use_cache
214
+ self.rope_theta = rope_theta
215
+ self.rope_scaling = rope_scaling
216
+ self.attention_bias = attention_bias
217
+ self.attention_dropout = attention_dropout
218
+ # Validate the correctness of rotary position embeddings parameters
219
+ # BC: if there is a 'type' field, move it to 'rope_type'.
220
+ if self.rope_scaling is not None and "type" in self.rope_scaling:
221
+ self.rope_scaling["rope_type"] = self.rope_scaling["type"]
222
+ rope_config_validation(self)
223
+
224
+ # MoE arguments
225
+ self.decoder_sparse_step = decoder_sparse_step
226
+ self.moe_intermediate_size = moe_intermediate_size
227
+ self.num_experts_per_tok = num_experts_per_tok
228
+ self.num_experts = num_experts
229
+ self.norm_topk_prob = norm_topk_prob
230
+ self.output_router_logits = output_router_logits
231
+ self.router_aux_loss_coef = router_aux_loss_coef
232
+ self.mlp_only_layers = [] if mlp_only_layers is None else mlp_only_layers
233
+
234
+ super().__init__(
235
+ tie_word_embeddings=tie_word_embeddings,
236
+ **kwargs,
237
+ )
238
+
239
+
240
+ __all__ = ["Qwen3MoeConfig"]
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.7,
10
+ "top_k": 20,
11
+ "top_p": 0.8,
12
+ "transformers_version": "4.51.0"
13
+ }
merges.txt ADDED
The diff for this file is too large to render. See raw diff
 
model-00001-of-00016.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:105905a3029e1c760a6e647eeea9c3bf9d599caaf9f5b7b90d50140c46d610d6
3
+ size 4293406800
model-00002-of-00016.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:de1b6efb02eaffc3c864e384656497c58bc81cc868ef9c0199603b77bb1b5b3d
3
+ size 4294086536
model-00003-of-00016.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:82826f66ca584a3bfaa0470a0bc2afd8439aae23e0d72bbcc9f058a3c9ef1649
3
+ size 4294086616
model-00004-of-00016.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2e404d77d0a7ff64b5b2d5d4ea27f42d41f249e442446bd7b9fff314b20d06b0
3
+ size 4294087208
model-00005-of-00016.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:856e235b48da5f2b4c200a23690463553f146529294445aa4533c5db7f380d0f
3
+ size 4294087984
model-00006-of-00016.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:01b16f6b978406b72942be836add7e3e403086efdeb5108107fab93a798d40fe
3
+ size 4294087928
model-00007-of-00016.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d33575f875461376e8f136abe69cdba0f514d631018b45116721eb14fb1a1e37
3
+ size 4294087984
model-00008-of-00016.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a8aa0d7cf6cab9abd2cc74273f0c14c6669c9d9796555df4b84d49610c1910c5
3
+ size 4294087968
model-00009-of-00016.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:cd546c56d7e5ad4ea8a270db2e950dc5cc1ffd1a12bcbdadad05b4151835b461
3
+ size 4294087944
model-00010-of-00016.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:fec80f5ddccdd2ea1f85308610d1eee1f0ecaee92d760b80d5b5124140dbc2cc
3
+ size 4294088008
model-00011-of-00016.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:168297f175585d39e459f6634ed78c6329aaf8e5ad0598329005106cdded1b62
3
+ size 4294087904
model-00012-of-00016.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4d8a26b5b2f669c4c6dcc32490fbb1d757a25156d110191333665fe2807241de
3
+ size 4294087984
model-00013-of-00016.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:fff5881f94ffc5ab1f8c5bda2cfbf1be502158df95ebef468181f88dfd5975d7
3
+ size 4294087928
model-00014-of-00016.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6c9caecb93fcbdcf74b70529a9ee20058aba6211f9b7ad67b12039ad12fdf2ed
3
+ size 4294087984
model-00015-of-00016.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9d1a73cf9fc10593276e659ad0d018f5df1a065a511fe4b6785b103306e5bb1c
3
+ size 4295829312
model-00016-of-00016.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:613d83b0b0ea9bd8607b3574b2c96f9010bdc8c45c901f7923da92853b3cbcf3
3
+ size 1487245776
model.safetensors.index.json ADDED
The diff for this file is too large to render. See raw diff
 
modeling_grove_moe.py ADDED
@@ -0,0 +1,2023 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
2
+ # This file was automatically generated from src/transformers/models/qwen3_moe/modular_qwen3_moe.py.
3
+ # Do NOT edit this file manually as any edits will be overwritten by the generation of
4
+ # the file from the modular. If any change should be done, please apply the change to the
5
+ # modular_qwen3_moe.py file directly. One of our CI enforces this.
6
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
7
+ # coding=utf-8
8
+ # Copyright 2025 The Qwen team, Alibaba Group and the HuggingFace Inc. team. All rights reserved.
9
+ #
10
+ # Licensed under the Apache License, Version 2.0 (the "License");
11
+ # you may not use this file except in compliance with the License.
12
+ # You may obtain a copy of the License at
13
+ #
14
+ # http://www.apache.org/licenses/LICENSE-2.0
15
+ #
16
+ # Unless required by applicable law or agreed to in writing, software
17
+ # distributed under the License is distributed on an "AS IS" BASIS,
18
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19
+ # See the License for the specific language governing permissions and
20
+ # limitations under the License.
21
+
22
+ from functools import partial
23
+ from typing import Callable, List, Optional, Tuple, Union
24
+
25
+ import torch
26
+ import torch.nn.functional as F
27
+ from torch import nn
28
+
29
+ from transformers.activations import ACT2FN
30
+ from transformers.cache_utils import Cache, DynamicCache, SlidingWindowCache, StaticCache
31
+ from transformers.generation import GenerationMixin
32
+ from transformers.modeling_attn_mask_utils import AttentionMaskConverter
33
+ from transformers.modeling_flash_attention_utils import FlashAttentionKwargs
34
+ from transformers.modeling_outputs import (
35
+ BaseModelOutputWithPast,
36
+ CausalLMOutputWithPast,
37
+ MoeCausalLMOutputWithPast,
38
+ MoeModelOutputWithPast,
39
+ QuestionAnsweringModelOutput,
40
+ SequenceClassifierOutputWithPast,
41
+ TokenClassifierOutput,
42
+ )
43
+ from transformers.modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update
44
+ from transformers.modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
45
+ from transformers.processing_utils import Unpack
46
+ from transformers.utils import (
47
+ LossKwargs,
48
+ add_code_sample_docstrings,
49
+ add_start_docstrings,
50
+ add_start_docstrings_to_model_forward,
51
+ can_return_tuple,
52
+ logging,
53
+ replace_return_docstrings,
54
+ )
55
+ from transformers.utils.deprecation import deprecate_kwarg
56
+ from .configuration_qwen3_moe import Qwen3MoeConfig
57
+
58
+
59
+ logger = logging.get_logger(__name__)
60
+
61
+ _CHECKPOINT_FOR_DOC = "Qwen/Qwen3-MoE-15B-A2B"
62
+ _CONFIG_FOR_DOC = "Qwen3MoeConfig"
63
+
64
+
65
+ def rotate_half(x):
66
+ """Rotates half the hidden dims of the input."""
67
+ x1 = x[..., : x.shape[-1] // 2]
68
+ x2 = x[..., x.shape[-1] // 2 :]
69
+ return torch.cat((-x2, x1), dim=-1)
70
+
71
+
72
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
73
+ """Applies Rotary Position Embedding to the query and key tensors.
74
+
75
+ Args:
76
+ q (`torch.Tensor`): The query tensor.
77
+ k (`torch.Tensor`): The key tensor.
78
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
79
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
80
+ position_ids (`torch.Tensor`, *optional*):
81
+ Deprecated and unused.
82
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
83
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
84
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
85
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
86
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
87
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
88
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
89
+ Returns:
90
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
91
+ """
92
+ cos = cos.unsqueeze(unsqueeze_dim)
93
+ sin = sin.unsqueeze(unsqueeze_dim)
94
+ q_embed = (q * cos) + (rotate_half(q) * sin)
95
+ k_embed = (k * cos) + (rotate_half(k) * sin)
96
+ return q_embed, k_embed
97
+
98
+
99
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
100
+ """
101
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
102
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
103
+ """
104
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
105
+ if n_rep == 1:
106
+ return hidden_states
107
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
108
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
109
+
110
+
111
+ def eager_attention_forward(
112
+ module: nn.Module,
113
+ query: torch.Tensor,
114
+ key: torch.Tensor,
115
+ value: torch.Tensor,
116
+ attention_mask: Optional[torch.Tensor],
117
+ scaling: float,
118
+ dropout: float = 0.0,
119
+ **kwargs,
120
+ ):
121
+ key_states = repeat_kv(key, module.num_key_value_groups)
122
+ value_states = repeat_kv(value, module.num_key_value_groups)
123
+
124
+ attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
125
+ if attention_mask is not None:
126
+ causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
127
+ attn_weights = attn_weights + causal_mask
128
+
129
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
130
+ attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
131
+ attn_output = torch.matmul(attn_weights, value_states)
132
+ attn_output = attn_output.transpose(1, 2).contiguous()
133
+
134
+ return attn_output, attn_weights
135
+
136
+
137
+ class Qwen3MoeAttention(nn.Module):
138
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
139
+
140
+ def __init__(self, config: Qwen3MoeConfig, layer_idx: int):
141
+ super().__init__()
142
+ self.config = config
143
+ self.layer_idx = layer_idx
144
+ self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
145
+ self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
146
+ self.scaling = self.head_dim**-0.5
147
+ self.attention_dropout = config.attention_dropout
148
+ self.is_causal = True
149
+
150
+ self.q_proj = nn.Linear(
151
+ config.hidden_size, config.num_attention_heads * self.head_dim, bias=config.attention_bias
152
+ )
153
+ self.k_proj = nn.Linear(
154
+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
155
+ )
156
+ self.v_proj = nn.Linear(
157
+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
158
+ )
159
+ self.o_proj = nn.Linear(
160
+ config.num_attention_heads * self.head_dim, config.hidden_size, bias=config.attention_bias
161
+ )
162
+ self.q_norm = Qwen3MoeRMSNorm(self.head_dim, eps=config.rms_norm_eps) # unlike olmo, only on the head dim!
163
+ self.k_norm = Qwen3MoeRMSNorm(self.head_dim, eps=config.rms_norm_eps) # thus post q_norm does not need reshape
164
+ self.sliding_window = config.sliding_window
165
+ if not (
166
+ self.config.use_sliding_window
167
+ and getattr(self.config, "sliding_window", None) is not None
168
+ and self.layer_idx >= self.config.max_window_layers
169
+ ):
170
+ self.sliding_window = None
171
+
172
+ def forward(
173
+ self,
174
+ hidden_states: torch.Tensor,
175
+ position_embeddings: Tuple[torch.Tensor, torch.Tensor],
176
+ attention_mask: Optional[torch.Tensor],
177
+ past_key_value: Optional[Cache] = None,
178
+ cache_position: Optional[torch.LongTensor] = None,
179
+ **kwargs: Unpack[FlashAttentionKwargs],
180
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
181
+ input_shape = hidden_states.shape[:-1]
182
+ hidden_shape = (*input_shape, -1, self.head_dim)
183
+
184
+ query_states = self.q_norm(self.q_proj(hidden_states).view(hidden_shape)).transpose(1, 2)
185
+ key_states = self.k_norm(self.k_proj(hidden_states).view(hidden_shape)).transpose(1, 2)
186
+ value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
187
+
188
+ cos, sin = position_embeddings
189
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
190
+
191
+ if past_key_value is not None:
192
+ # sin and cos are specific to RoPE models; cache_position needed for the static cache
193
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
194
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
195
+
196
+ attention_interface: Callable = eager_attention_forward
197
+ if self.config._attn_implementation != "eager":
198
+ if self.config._attn_implementation == "sdpa" and kwargs.get("output_attentions", False):
199
+ logger.warning_once(
200
+ "`torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to "
201
+ 'eager attention. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.'
202
+ )
203
+ else:
204
+ attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
205
+
206
+ attn_output, attn_weights = attention_interface(
207
+ self,
208
+ query_states,
209
+ key_states,
210
+ value_states,
211
+ attention_mask,
212
+ dropout=0.0 if not self.training else self.attention_dropout,
213
+ scaling=self.scaling,
214
+ sliding_window=self.sliding_window, # diff with Llama
215
+ **kwargs,
216
+ )
217
+
218
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
219
+ attn_output = self.o_proj(attn_output)
220
+ return attn_output, attn_weights
221
+
222
+
223
+ class Qwen3MoeMLP(nn.Module):
224
+ def __init__(self, config, intermediate_size=None):
225
+ super().__init__()
226
+ self.config = config
227
+ self.hidden_size = config.hidden_size
228
+ self.intermediate_size = intermediate_size if intermediate_size is not None else config.intermediate_size
229
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
230
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
231
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
232
+ self.act_fn = ACT2FN[config.hidden_act]
233
+
234
+ def forward(self, x):
235
+ down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
236
+ return down_proj
237
+
238
+
239
+ class Qwen3MoeSparseMoeBlock(nn.Module):
240
+ def __init__(self, config):
241
+ super().__init__()
242
+ self.num_experts = config.num_experts
243
+ self.top_k = config.num_experts_per_tok
244
+ self.norm_topk_prob = config.norm_topk_prob
245
+
246
+ # gating
247
+ self.gate = nn.Linear(config.hidden_size, config.num_experts, bias=False)
248
+ self.experts = nn.ModuleList(
249
+ [Qwen3MoeMLP(config, intermediate_size=config.moe_intermediate_size) for _ in range(self.num_experts)]
250
+ )
251
+
252
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
253
+ """ """
254
+ batch_size, sequence_length, hidden_dim = hidden_states.shape
255
+ hidden_states = hidden_states.view(-1, hidden_dim)
256
+ # router_logits: (batch * sequence_length, n_experts)
257
+ router_logits = self.gate(hidden_states)
258
+
259
+ routing_weights = F.softmax(router_logits, dim=1, dtype=torch.float)
260
+ routing_weights, selected_experts = torch.topk(routing_weights, self.top_k, dim=-1)
261
+ if self.norm_topk_prob: # only diff with mixtral sparse moe block!
262
+ routing_weights /= routing_weights.sum(dim=-1, keepdim=True)
263
+ # we cast back to the input dtype
264
+ routing_weights = routing_weights.to(hidden_states.dtype)
265
+
266
+ final_hidden_states = torch.zeros(
267
+ (batch_size * sequence_length, hidden_dim), dtype=hidden_states.dtype, device=hidden_states.device
268
+ )
269
+
270
+ # One hot encode the selected experts to create an expert mask
271
+ # this will be used to easily index which expert is going to be sollicitated
272
+ expert_mask = torch.nn.functional.one_hot(selected_experts, num_classes=self.num_experts).permute(2, 1, 0)
273
+
274
+ # Loop over all available experts in the model and perform the computation on each expert
275
+ for expert_idx in range(self.num_experts):
276
+ expert_layer = self.experts[expert_idx]
277
+ idx, top_x = torch.where(expert_mask[expert_idx])
278
+
279
+ # Index the correct hidden states and compute the expert hidden state for
280
+ # the current expert. We need to make sure to multiply the output hidden
281
+ # states by `routing_weights` on the corresponding tokens (top-1 and top-2)
282
+ current_state = hidden_states[None, top_x].reshape(-1, hidden_dim)
283
+ current_hidden_states = expert_layer(current_state) * routing_weights[top_x, idx, None]
284
+
285
+ # However `index_add_` only support torch tensors for indexing so we'll use
286
+ # the `top_x` tensor here.
287
+ final_hidden_states.index_add_(0, top_x, current_hidden_states.to(hidden_states.dtype))
288
+ final_hidden_states = final_hidden_states.reshape(batch_size, sequence_length, hidden_dim)
289
+ return final_hidden_states, router_logits
290
+
291
+
292
+ class GroveMoeSparseMoeBlock(nn.Module):
293
+ def __init__(self, config):
294
+ super().__init__()
295
+ self.num_experts = config.num_experts
296
+ self.top_k = config.num_experts_per_tok
297
+ self.norm_topk_prob = config.norm_topk_prob
298
+ self.num_experts_per_group = 2
299
+ self.parallel_expert_intermediate_size = 128
300
+
301
+ # gating
302
+ self.gate = nn.Linear(config.hidden_size, config.num_experts, bias=False)
303
+ self.register_buffer('expert_bias', torch.zeros(self.num_experts))
304
+
305
+ self.experts = nn.ModuleList(
306
+ [Qwen3MoeMLP(config, intermediate_size=config.moe_intermediate_size) for _ in range(self.num_experts)]
307
+ )
308
+ self.chunk_experts = nn.ModuleList(
309
+ [Qwen3MoeMLP(config, intermediate_size=self.parallel_expert_intermediate_size) for _ in range(self.num_experts // self.num_experts_per_group)]
310
+ )
311
+
312
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
313
+ """ """
314
+ batch_size, sequence_length, hidden_dim = hidden_states.shape
315
+ hidden_states = hidden_states.view(-1, hidden_dim)
316
+
317
+ router_logits = self.gate(hidden_states)
318
+ routing_weights = F.softmax(router_logits, dim=-1, dtype=torch.float)
319
+ bias_routing_weights = torch.sigmoid(router_logits).to(torch.float)
320
+
321
+ _, selected_experts = torch.topk(bias_routing_weights, self.top_k, dim=-1)
322
+ group_selected_experts = selected_experts // self.num_experts_per_group
323
+
324
+ routing_weights = routing_weights.gather(-1, selected_experts)
325
+ routing_weights /= routing_weights.sum(dim=-1, keepdim=True)
326
+ routing_weights = routing_weights.to(hidden_states.dtype)
327
+
328
+ # forward large
329
+ large_experts_hidden_states = torch.zeros(
330
+ (batch_size * sequence_length, hidden_dim), dtype=hidden_states.dtype, device=hidden_states.device
331
+ )
332
+
333
+ # One hot encode the selected experts to create an expert mask
334
+ # this will be used to easily index which expert is going to be sollicitated
335
+ expert_mask = torch.nn.functional.one_hot(selected_experts, num_classes=self.num_experts).permute(2, 1, 0)
336
+
337
+ # Loop over all available experts in the model and perform the computation on each expert
338
+ for expert_idx in range(self.num_experts):
339
+ expert_layer = self.experts[expert_idx]
340
+ idx, top_x = torch.where(expert_mask[expert_idx])
341
+
342
+ # Index the correct hidden states and compute the expert hidden state for
343
+ # the current expert. We need to make sure to multiply the output hidden
344
+ # states by `routing_weights` on the corresponding tokens (top-1 and top-2)
345
+ current_state = hidden_states[None, top_x].reshape(-1, hidden_dim)
346
+ current_hidden_states = expert_layer(current_state) * routing_weights[top_x, idx, None]
347
+
348
+ # However `index_add_` only support torch tensors for indexing so we'll use
349
+ # the `top_x` tensor here.
350
+ large_experts_hidden_states.index_add_(0, top_x, current_hidden_states.to(hidden_states.dtype))
351
+
352
+ # forward small
353
+ small_experts_hidden_states = torch.zeros(
354
+ (batch_size * sequence_length, hidden_dim), dtype=hidden_states.dtype, device=hidden_states.device
355
+ )
356
+
357
+ # One hot encode the selected experts to create an expert mask
358
+ # this will be used to easily index which expert is going to be sollicitated
359
+ expert_mask = torch.nn.functional.one_hot(group_selected_experts, num_classes=self.num_experts // self.num_experts_per_group).permute(2, 1, 0)
360
+
361
+ # Loop over all available experts in the model and perform the computation on each expert
362
+ for expert_idx in range(self.num_experts // self.num_experts_per_group):
363
+ expert_layer = self.chunk_experts[expert_idx]
364
+ idx, top_x = torch.where(expert_mask[expert_idx])
365
+
366
+ # Index the correct hidden states and compute the expert hidden state for
367
+ # the current expert. We need to make sure to multiply the output hidden
368
+ # states by `routing_weights` on the corresponding tokens (top-1 and top-2)
369
+ current_state = hidden_states[None, top_x].reshape(-1, hidden_dim)
370
+ current_hidden_states = expert_layer(current_state) * routing_weights[top_x, idx, None]
371
+
372
+ # However `index_add_` only support torch tensors for indexing so we'll use
373
+ # the `top_x` tensor here.
374
+ small_experts_hidden_states.index_add_(0, top_x, current_hidden_states.to(hidden_states.dtype))
375
+
376
+ final_hidden_states = 0.05 * small_experts_hidden_states + large_experts_hidden_states
377
+ final_hidden_states = final_hidden_states.reshape(batch_size, sequence_length, hidden_dim)
378
+
379
+ return final_hidden_states, router_logits
380
+
381
+ class Qwen3MoeRMSNorm(nn.Module):
382
+ def __init__(self, hidden_size, eps=1e-6):
383
+ """
384
+ Qwen3MoeRMSNorm is equivalent to T5LayerNorm
385
+ """
386
+ super().__init__()
387
+ self.weight = nn.Parameter(torch.ones(hidden_size))
388
+ self.variance_epsilon = eps
389
+
390
+ def forward(self, hidden_states):
391
+ input_dtype = hidden_states.dtype
392
+ hidden_states = hidden_states.to(torch.float32)
393
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
394
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
395
+ return self.weight * hidden_states.to(input_dtype)
396
+
397
+ def extra_repr(self):
398
+ return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
399
+
400
+
401
+ class Qwen3MoeDecoderLayer(nn.Module):
402
+ def __init__(self, config: Qwen3MoeConfig, layer_idx: int):
403
+ super().__init__()
404
+ self.hidden_size = config.hidden_size
405
+
406
+ self.self_attn = Qwen3MoeAttention(config, layer_idx)
407
+ self.mlp = Qwen3MoeMLP(config)
408
+
409
+ self.self_attn = Qwen3MoeAttention(config, layer_idx)
410
+
411
+ if (layer_idx not in config.mlp_only_layers) and (
412
+ config.num_experts > 0 and (layer_idx + 1) % config.decoder_sparse_step == 0
413
+ ):
414
+ self.mlp = Qwen3MoeSparseMoeBlock(config)
415
+ else:
416
+ self.mlp = Qwen3MoeMLP(config, intermediate_size=config.intermediate_size)
417
+
418
+ self.input_layernorm = Qwen3MoeRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
419
+ self.post_attention_layernorm = Qwen3MoeRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
420
+
421
+ def forward(
422
+ self,
423
+ hidden_states: torch.Tensor,
424
+ attention_mask: Optional[torch.Tensor] = None,
425
+ position_ids: Optional[torch.LongTensor] = None,
426
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
427
+ output_attentions: Optional[bool] = False,
428
+ output_router_logits: Optional[bool] = False,
429
+ use_cache: Optional[bool] = False,
430
+ cache_position: Optional[torch.LongTensor] = None,
431
+ position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, # necessary, but kept here for BC
432
+ **kwargs: Unpack[FlashAttentionKwargs],
433
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
434
+ """
435
+ Args:
436
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
437
+ attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
438
+ `(batch, sequence_length)` where padding elements are indicated by 0.
439
+ output_attentions (`bool`, *optional*):
440
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
441
+ returned tensors for more detail.
442
+ output_router_logits (`bool`, *optional*):
443
+ Whether or not to return the logits of all the routers. They are useful for computing the router loss,
444
+ and should not be returned during inference.
445
+ use_cache (`bool`, *optional*):
446
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
447
+ (see `past_key_values`).
448
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
449
+ cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
450
+ Indices depicting the position of the input sequence tokens in the sequence.
451
+ position_embeddings (`Tuple[torch.FloatTensor, torch.FloatTensor]`, *optional*):
452
+ Tuple containing the cosine and sine positional embeddings of shape `(batch_size, seq_len, head_dim)`,
453
+ with `head_dim` being the embedding dimension of each attention head.
454
+ kwargs (`dict`, *optional*):
455
+ Arbitrary kwargs to be ignored, used for FSDP and other methods that injects code
456
+ into the model
457
+ """
458
+
459
+ residual = hidden_states
460
+
461
+ hidden_states = self.input_layernorm(hidden_states)
462
+
463
+ # Self Attention
464
+ hidden_states, self_attn_weights = self.self_attn(
465
+ hidden_states=hidden_states,
466
+ attention_mask=attention_mask,
467
+ position_ids=position_ids,
468
+ past_key_value=past_key_value,
469
+ output_attentions=output_attentions,
470
+ use_cache=use_cache,
471
+ cache_position=cache_position,
472
+ position_embeddings=position_embeddings,
473
+ )
474
+ hidden_states = residual + hidden_states
475
+
476
+ # Fully Connected
477
+ residual = hidden_states
478
+ hidden_states = self.post_attention_layernorm(hidden_states)
479
+
480
+ hidden_states = self.mlp(hidden_states)
481
+ if isinstance(hidden_states, tuple):
482
+ hidden_states, router_logits = hidden_states
483
+ else:
484
+ router_logits = None
485
+
486
+ hidden_states = residual + hidden_states
487
+
488
+ outputs = (hidden_states,)
489
+
490
+ if output_attentions:
491
+ outputs += (self_attn_weights,)
492
+
493
+ if output_router_logits:
494
+ outputs += (router_logits,)
495
+
496
+ return outputs
497
+
498
+
499
+ class GroveMoeDecoderLayer(nn.Module):
500
+ def __init__(self, config: Qwen3MoeConfig, layer_idx: int):
501
+ super().__init__()
502
+ self.hidden_size = config.hidden_size
503
+
504
+ self.self_attn = Qwen3MoeAttention(config, layer_idx)
505
+ self.mlp = Qwen3MoeMLP(config)
506
+
507
+ self.self_attn = Qwen3MoeAttention(config, layer_idx)
508
+
509
+ if (layer_idx not in config.mlp_only_layers) and (
510
+ config.num_experts > 0 and (layer_idx + 1) % config.decoder_sparse_step == 0
511
+ ):
512
+ self.mlp = GroveMoeSparseMoeBlock(config)
513
+ else:
514
+ self.mlp = Qwen3MoeMLP(config, intermediate_size=config.intermediate_size)
515
+
516
+ self.input_layernorm = Qwen3MoeRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
517
+ self.post_attention_layernorm = Qwen3MoeRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
518
+
519
+ def forward(
520
+ self,
521
+ hidden_states: torch.Tensor,
522
+ attention_mask: Optional[torch.Tensor] = None,
523
+ position_ids: Optional[torch.LongTensor] = None,
524
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
525
+ output_attentions: Optional[bool] = False,
526
+ output_router_logits: Optional[bool] = False,
527
+ use_cache: Optional[bool] = False,
528
+ cache_position: Optional[torch.LongTensor] = None,
529
+ position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, # necessary, but kept here for BC
530
+ **kwargs: Unpack[FlashAttentionKwargs],
531
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
532
+ """
533
+ Args:
534
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
535
+ attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
536
+ `(batch, sequence_length)` where padding elements are indicated by 0.
537
+ output_attentions (`bool`, *optional*):
538
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
539
+ returned tensors for more detail.
540
+ output_router_logits (`bool`, *optional*):
541
+ Whether or not to return the logits of all the routers. They are useful for computing the router loss,
542
+ and should not be returned during inference.
543
+ use_cache (`bool`, *optional*):
544
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
545
+ (see `past_key_values`).
546
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
547
+ cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
548
+ Indices depicting the position of the input sequence tokens in the sequence.
549
+ position_embeddings (`Tuple[torch.FloatTensor, torch.FloatTensor]`, *optional*):
550
+ Tuple containing the cosine and sine positional embeddings of shape `(batch_size, seq_len, head_dim)`,
551
+ with `head_dim` being the embedding dimension of each attention head.
552
+ kwargs (`dict`, *optional*):
553
+ Arbitrary kwargs to be ignored, used for FSDP and other methods that injects code
554
+ into the model
555
+ """
556
+
557
+ residual = hidden_states
558
+
559
+ hidden_states = self.input_layernorm(hidden_states)
560
+
561
+ # Self Attention
562
+ hidden_states, self_attn_weights = self.self_attn(
563
+ hidden_states=hidden_states,
564
+ attention_mask=attention_mask,
565
+ position_ids=position_ids,
566
+ past_key_value=past_key_value,
567
+ output_attentions=output_attentions,
568
+ use_cache=use_cache,
569
+ cache_position=cache_position,
570
+ position_embeddings=position_embeddings,
571
+ )
572
+ hidden_states = residual + hidden_states
573
+
574
+ # Fully Connected
575
+ residual = hidden_states
576
+ hidden_states = self.post_attention_layernorm(hidden_states)
577
+
578
+ hidden_states = self.mlp(hidden_states)
579
+ if isinstance(hidden_states, tuple):
580
+ hidden_states, router_logits = hidden_states
581
+ else:
582
+ router_logits = None
583
+
584
+ hidden_states = residual + hidden_states
585
+
586
+ outputs = (hidden_states,)
587
+
588
+ if output_attentions:
589
+ outputs += (self_attn_weights,)
590
+
591
+ if output_router_logits:
592
+ outputs += (router_logits,)
593
+
594
+ return outputs
595
+
596
+
597
+ class Qwen3MoeRotaryEmbedding(nn.Module):
598
+ def __init__(self, config: Qwen3MoeConfig, device=None):
599
+ super().__init__()
600
+ # BC: "rope_type" was originally "type"
601
+ if hasattr(config, "rope_scaling") and config.rope_scaling is not None:
602
+ self.rope_type = config.rope_scaling.get("rope_type", config.rope_scaling.get("type"))
603
+ else:
604
+ self.rope_type = "default"
605
+ self.max_seq_len_cached = config.max_position_embeddings
606
+ self.original_max_seq_len = config.max_position_embeddings
607
+
608
+ self.config = config
609
+ self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
610
+
611
+ inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device)
612
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
613
+ self.original_inv_freq = self.inv_freq
614
+
615
+ @torch.no_grad()
616
+ @dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope)
617
+ def forward(self, x, position_ids):
618
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device)
619
+ position_ids_expanded = position_ids[:, None, :].float()
620
+
621
+ device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
622
+ with torch.autocast(device_type=device_type, enabled=False): # Force float32
623
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
624
+ emb = torch.cat((freqs, freqs), dim=-1)
625
+ cos = emb.cos() * self.attention_scaling
626
+ sin = emb.sin() * self.attention_scaling
627
+
628
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
629
+
630
+
631
+ QWEN3_MOE_START_DOCSTRING = r"""
632
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
633
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
634
+ etc.)
635
+
636
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
637
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
638
+ and behavior.
639
+
640
+ Parameters:
641
+ config ([`Qwen3MoeConfig`]):
642
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
643
+ load the weights associated with the model, only the configuration. Check out the
644
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
645
+ """
646
+
647
+
648
+ @add_start_docstrings(
649
+ "The bare Qwen3Moe Model outputting raw hidden-states without any specific head on top.",
650
+ QWEN3_MOE_START_DOCSTRING,
651
+ )
652
+ class Qwen3MoePreTrainedModel(PreTrainedModel):
653
+ config_class = Qwen3MoeConfig
654
+ base_model_prefix = "model"
655
+ supports_gradient_checkpointing = True
656
+ _no_split_modules = ["Qwen3MoeDecoderLayer"]
657
+ _skip_keys_device_placement = ["past_key_values"]
658
+ _supports_flash_attn_2 = True
659
+ _supports_sdpa = True
660
+ _supports_flex_attn = True
661
+ _supports_cache_class = True
662
+ _supports_quantized_cache = True
663
+ _supports_static_cache = False # MoE models don't work with torch.compile (`torch.where(condition)` not supported)
664
+ _supports_attention_backend = True
665
+
666
+ def _init_weights(self, module):
667
+ std = self.config.initializer_range
668
+ if isinstance(module, nn.Linear):
669
+ module.weight.data.normal_(mean=0.0, std=std)
670
+ if module.bias is not None:
671
+ module.bias.data.zero_()
672
+ elif isinstance(module, nn.Embedding):
673
+ module.weight.data.normal_(mean=0.0, std=std)
674
+ if module.padding_idx is not None:
675
+ module.weight.data[module.padding_idx].zero_()
676
+
677
+
678
+ @add_start_docstrings(
679
+ "The bare Qwen3Moe Model outputting raw hidden-states without any specific head on top.",
680
+ QWEN3_MOE_START_DOCSTRING,
681
+ )
682
+ class GroveMoePreTrainedModel(PreTrainedModel):
683
+ config_class = Qwen3MoeConfig
684
+ base_model_prefix = "model"
685
+ supports_gradient_checkpointing = True
686
+ _no_split_modules = ["GroveMoeDecoderLayer"]
687
+ _skip_keys_device_placement = ["past_key_values"]
688
+ _supports_flash_attn_2 = True
689
+ _supports_sdpa = True
690
+ _supports_flex_attn = True
691
+ _supports_cache_class = True
692
+ _supports_quantized_cache = True
693
+ _supports_static_cache = False # MoE models don't work with torch.compile (`torch.where(condition)` not supported)
694
+ _supports_attention_backend = True
695
+
696
+ def _init_weights(self, module):
697
+ std = self.config.initializer_range
698
+ if isinstance(module, nn.Linear):
699
+ module.weight.data.normal_(mean=0.0, std=std)
700
+ if module.bias is not None:
701
+ module.bias.data.zero_()
702
+ elif isinstance(module, nn.Embedding):
703
+ module.weight.data.normal_(mean=0.0, std=std)
704
+ if module.padding_idx is not None:
705
+ module.weight.data[module.padding_idx].zero_()
706
+
707
+
708
+ QWEN3_MOE_INPUTS_DOCSTRING = r"""
709
+ Args:
710
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
711
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
712
+ it.
713
+
714
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
715
+ [`PreTrainedTokenizer.__call__`] for details.
716
+
717
+ [What are input IDs?](../glossary#input-ids)
718
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
719
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
720
+
721
+ - 1 for tokens that are **not masked**,
722
+ - 0 for tokens that are **masked**.
723
+
724
+ [What are attention masks?](../glossary#attention-mask)
725
+
726
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
727
+ [`PreTrainedTokenizer.__call__`] for details.
728
+
729
+ If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
730
+ `past_key_values`).
731
+
732
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
733
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
734
+ information on the default strategy.
735
+
736
+ - 1 indicates the head is **not masked**,
737
+ - 0 indicates the head is **masked**.
738
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
739
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
740
+ config.n_positions - 1]`.
741
+
742
+ [What are position IDs?](../glossary#position-ids)
743
+ past_key_values (`Cache`, *optional*):
744
+ Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
745
+ blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
746
+ returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
747
+
748
+ It is a [`~cache_utils.Cache`] instance. For more details, see our [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache).
749
+
750
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
751
+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
752
+ of shape `(batch_size, sequence_length)`.
753
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
754
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
755
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
756
+ model's internal embedding lookup matrix.
757
+ use_cache (`bool`, *optional*):
758
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
759
+ `past_key_values`).
760
+ output_attentions (`bool`, *optional*):
761
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
762
+ tensors for more detail.
763
+ output_hidden_states (`bool`, *optional*):
764
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
765
+ more detail.
766
+ return_dict (`bool`, *optional*):
767
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
768
+ cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
769
+ Indices depicting the position of the input sequence tokens in the sequence. Contrarily to `position_ids`,
770
+ this tensor is not affected by padding. It is used to update the cache in the correct position and to infer
771
+ the complete sequence length.
772
+ """
773
+
774
+
775
+ @add_start_docstrings(
776
+ "The bare Qwen3Moe Model outputting raw hidden-states without any specific head on top.",
777
+ QWEN3_MOE_START_DOCSTRING,
778
+ )
779
+ class Qwen3MoeModel(Qwen3MoePreTrainedModel):
780
+ """
781
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`Qwen3MoeDecoderLayer`]
782
+
783
+ Args:
784
+ config: Qwen3MoeConfig
785
+ """
786
+
787
+ def __init__(self, config: Qwen3MoeConfig):
788
+ super().__init__(config)
789
+ self.padding_idx = config.pad_token_id
790
+ self.vocab_size = config.vocab_size
791
+
792
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
793
+ self.layers = nn.ModuleList(
794
+ [Qwen3MoeDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
795
+ )
796
+ self.norm = Qwen3MoeRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
797
+ self.rotary_emb = Qwen3MoeRotaryEmbedding(config=config)
798
+ self.gradient_checkpointing = False
799
+
800
+ # Initialize weights and apply final processing
801
+ self.post_init()
802
+
803
+ def get_input_embeddings(self):
804
+ return self.embed_tokens
805
+
806
+ def set_input_embeddings(self, value):
807
+ self.embed_tokens = value
808
+
809
+ @can_return_tuple
810
+ @add_start_docstrings_to_model_forward(QWEN3_MOE_INPUTS_DOCSTRING)
811
+ def forward(
812
+ self,
813
+ input_ids: Optional[torch.LongTensor] = None,
814
+ attention_mask: Optional[torch.Tensor] = None,
815
+ position_ids: Optional[torch.LongTensor] = None,
816
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
817
+ inputs_embeds: Optional[torch.FloatTensor] = None,
818
+ use_cache: Optional[bool] = None,
819
+ output_attentions: Optional[bool] = None,
820
+ output_hidden_states: Optional[bool] = None,
821
+ output_router_logits: Optional[bool] = None,
822
+ cache_position: Optional[torch.LongTensor] = None,
823
+ **flash_attn_kwargs: Unpack[FlashAttentionKwargs],
824
+ ) -> MoeModelOutputWithPast:
825
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
826
+ output_router_logits = (
827
+ output_router_logits if output_router_logits is not None else self.config.output_router_logits
828
+ )
829
+ output_hidden_states = (
830
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
831
+ )
832
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
833
+
834
+ if (input_ids is None) ^ (inputs_embeds is not None):
835
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
836
+
837
+ if self.gradient_checkpointing and self.training:
838
+ if use_cache:
839
+ logger.warning_once(
840
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
841
+ )
842
+ use_cache = False
843
+
844
+ if use_cache and past_key_values is None:
845
+ past_key_values = DynamicCache()
846
+
847
+ if inputs_embeds is None:
848
+ inputs_embeds = self.embed_tokens(input_ids)
849
+
850
+ if cache_position is None:
851
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
852
+ cache_position = torch.arange(
853
+ past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
854
+ )
855
+ if position_ids is None:
856
+ position_ids = cache_position.unsqueeze(0)
857
+
858
+ causal_mask = self._update_causal_mask(
859
+ attention_mask, inputs_embeds, cache_position, past_key_values, output_attentions
860
+ )
861
+
862
+ hidden_states = inputs_embeds
863
+
864
+ # create position embeddings to be shared across the decoder layers
865
+ position_embeddings = self.rotary_emb(hidden_states, position_ids)
866
+
867
+ # decoder layers
868
+ all_hidden_states = () if output_hidden_states else None
869
+ all_self_attns = () if output_attentions else None
870
+ all_router_logits = () if output_router_logits else None
871
+
872
+ for decoder_layer in self.layers:
873
+ if output_hidden_states:
874
+ all_hidden_states += (hidden_states,)
875
+
876
+ if self.gradient_checkpointing and self.training:
877
+ layer_outputs = self._gradient_checkpointing_func(
878
+ partial(decoder_layer.__call__, **flash_attn_kwargs),
879
+ hidden_states,
880
+ causal_mask,
881
+ position_ids,
882
+ past_key_values,
883
+ output_attentions,
884
+ output_router_logits,
885
+ use_cache,
886
+ cache_position,
887
+ position_embeddings,
888
+ )
889
+ else:
890
+ layer_outputs = decoder_layer(
891
+ hidden_states,
892
+ attention_mask=causal_mask,
893
+ position_ids=position_ids,
894
+ past_key_value=past_key_values,
895
+ output_attentions=output_attentions,
896
+ output_router_logits=output_router_logits,
897
+ use_cache=use_cache,
898
+ cache_position=cache_position,
899
+ position_embeddings=position_embeddings,
900
+ **flash_attn_kwargs,
901
+ )
902
+
903
+ hidden_states = layer_outputs[0]
904
+
905
+ if output_attentions:
906
+ all_self_attns += (layer_outputs[1],)
907
+
908
+ if output_router_logits:
909
+ all_router_logits += (layer_outputs[-1],)
910
+
911
+ hidden_states = self.norm(hidden_states)
912
+
913
+ # add hidden states from the last decoder layer
914
+ if output_hidden_states:
915
+ all_hidden_states += (hidden_states,)
916
+
917
+ return MoeModelOutputWithPast(
918
+ last_hidden_state=hidden_states,
919
+ past_key_values=past_key_values,
920
+ hidden_states=all_hidden_states,
921
+ attentions=all_self_attns,
922
+ router_logits=all_router_logits,
923
+ )
924
+
925
+ def _update_causal_mask(
926
+ self,
927
+ attention_mask: torch.Tensor,
928
+ input_tensor: torch.Tensor,
929
+ cache_position: torch.Tensor,
930
+ past_key_values: Cache,
931
+ output_attentions: bool = False,
932
+ ):
933
+ if self.config._attn_implementation == "flash_attention_2":
934
+ if attention_mask is not None and past_key_values is not None:
935
+ is_padding_right = attention_mask[:, -1].sum().item() != input_tensor.size()[0]
936
+ if is_padding_right:
937
+ raise ValueError(
938
+ "You are attempting to perform batched generation with padding_side='right'"
939
+ " this may lead to unexpected behaviour for Flash Attention version of Qwen3Moe. Make sure to "
940
+ " call `tokenizer.padding_side = 'left'` before tokenizing the input. "
941
+ )
942
+ if attention_mask is not None and 0.0 in attention_mask:
943
+ return attention_mask
944
+ return None
945
+
946
+ # For SDPA, when possible, we will rely on its `is_causal` argument instead of its `attn_mask` argument, in
947
+ # order to dispatch on Flash Attention 2. This feature is not compatible with static cache, as SDPA will fail
948
+ # to infer the attention mask.
949
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
950
+ using_static_cache = isinstance(past_key_values, StaticCache)
951
+ using_sliding_window_cache = isinstance(past_key_values, SlidingWindowCache)
952
+
953
+ # When output attentions is True, sdpa implementation's forward method calls the eager implementation's forward
954
+ if (
955
+ self.config._attn_implementation == "sdpa"
956
+ and not (using_static_cache or using_sliding_window_cache)
957
+ and not output_attentions
958
+ ):
959
+ if AttentionMaskConverter._ignore_causal_mask_sdpa(
960
+ attention_mask,
961
+ inputs_embeds=input_tensor,
962
+ past_key_values_length=past_seen_tokens,
963
+ sliding_window=self.config.sliding_window,
964
+ is_training=self.training,
965
+ ):
966
+ return None
967
+
968
+ dtype, device = input_tensor.dtype, input_tensor.device
969
+ min_dtype = torch.finfo(dtype).min
970
+ sequence_length = input_tensor.shape[1]
971
+ # SlidingWindowCache or StaticCache
972
+ if using_sliding_window_cache or using_static_cache:
973
+ target_length = past_key_values.get_max_cache_shape()
974
+ # DynamicCache or no cache
975
+ else:
976
+ target_length = (
977
+ attention_mask.shape[-1]
978
+ if isinstance(attention_mask, torch.Tensor)
979
+ else past_seen_tokens + sequence_length + 1
980
+ )
981
+
982
+ # In case the provided `attention` mask is 2D, we generate a causal mask here (4D).
983
+ causal_mask = self._prepare_4d_causal_attention_mask_with_cache_position(
984
+ attention_mask,
985
+ sequence_length=sequence_length,
986
+ target_length=target_length,
987
+ dtype=dtype,
988
+ device=device,
989
+ cache_position=cache_position,
990
+ batch_size=input_tensor.shape[0],
991
+ config=self.config,
992
+ past_key_values=past_key_values,
993
+ )
994
+
995
+ if (
996
+ self.config._attn_implementation == "sdpa"
997
+ and attention_mask is not None
998
+ and attention_mask.device.type in ["cuda", "xpu"]
999
+ and not output_attentions
1000
+ ):
1001
+ # Attend to all tokens in fully masked rows in the causal_mask, for example the relevant first rows when
1002
+ # using left padding. This is required by F.scaled_dot_product_attention memory-efficient attention path.
1003
+ # Details: https://github.com/pytorch/pytorch/issues/110213
1004
+ causal_mask = AttentionMaskConverter._unmask_unattended(causal_mask, min_dtype)
1005
+
1006
+ return causal_mask
1007
+
1008
+ @staticmethod
1009
+ def _prepare_4d_causal_attention_mask_with_cache_position(
1010
+ attention_mask: torch.Tensor,
1011
+ sequence_length: int,
1012
+ target_length: int,
1013
+ dtype: torch.dtype,
1014
+ device: torch.device,
1015
+ cache_position: torch.Tensor,
1016
+ batch_size: int,
1017
+ config: Qwen3MoeConfig,
1018
+ past_key_values: Cache,
1019
+ ):
1020
+ """
1021
+ Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape
1022
+ `(batch_size, key_value_length)`, or if the input `attention_mask` is already 4D, do nothing.
1023
+
1024
+ Args:
1025
+ attention_mask (`torch.Tensor`):
1026
+ A 2D attention mask of shape `(batch_size, key_value_length)` or a 4D attention mask of shape `(batch_size, 1, query_length, key_value_length)`.
1027
+ sequence_length (`int`):
1028
+ The sequence length being processed.
1029
+ target_length (`int`):
1030
+ The target length: when generating with static cache, the mask should be as long as the static cache, to account for the 0 padding, the part of the cache that is not filled yet.
1031
+ dtype (`torch.dtype`):
1032
+ The dtype to use for the 4D attention mask.
1033
+ device (`torch.device`):
1034
+ The device to place the 4D attention mask on.
1035
+ cache_position (`torch.Tensor`):
1036
+ Indices depicting the position of the input sequence tokens in the sequence.
1037
+ batch_size (`torch.Tensor`):
1038
+ Batch size.
1039
+ config (`Qwen3MoeConfig`):
1040
+ The model's configuration class
1041
+ past_key_values (`Cache`):
1042
+ The cache class that is being used currently to generate
1043
+ """
1044
+ if attention_mask is not None and attention_mask.dim() == 4:
1045
+ # In this case we assume that the mask comes already in inverted form and requires no inversion or slicing.
1046
+ causal_mask = attention_mask
1047
+ else:
1048
+ min_dtype = torch.finfo(dtype).min
1049
+ causal_mask = torch.full(
1050
+ (sequence_length, target_length), fill_value=min_dtype, dtype=dtype, device=device
1051
+ )
1052
+ diagonal_attend_mask = torch.arange(target_length, device=device) > cache_position.reshape(-1, 1)
1053
+ if config.sliding_window is not None:
1054
+ # if we have sliding window, we should not attend to tokens beyond sliding window length, so we mask them out also
1055
+ # the check is needed to verify is current checkpoint was trained with sliding window or not
1056
+ if not isinstance(past_key_values, SlidingWindowCache) or sequence_length > target_length:
1057
+ sliding_attend_mask = torch.arange(target_length, device=device) <= (
1058
+ cache_position.reshape(-1, 1) - config.sliding_window
1059
+ )
1060
+ diagonal_attend_mask.bitwise_or_(sliding_attend_mask)
1061
+ causal_mask *= diagonal_attend_mask
1062
+ causal_mask = causal_mask[None, None, :, :].expand(batch_size, 1, -1, -1)
1063
+ if attention_mask is not None:
1064
+ causal_mask = causal_mask.clone() # copy to contiguous memory for in-place edit
1065
+ if attention_mask.shape[-1] > target_length:
1066
+ attention_mask = attention_mask[:, :target_length]
1067
+ mask_length = attention_mask.shape[-1]
1068
+ padding_mask = causal_mask[:, :, :, :mask_length] + attention_mask[:, None, None, :].to(
1069
+ causal_mask.device
1070
+ )
1071
+ padding_mask = padding_mask == 0
1072
+ causal_mask[:, :, :, :mask_length] = causal_mask[:, :, :, :mask_length].masked_fill(
1073
+ padding_mask, min_dtype
1074
+ )
1075
+ return causal_mask
1076
+
1077
+
1078
+
1079
+ @add_start_docstrings(
1080
+ "The bare Qwen3Moe Model outputting raw hidden-states without any specific head on top.",
1081
+ QWEN3_MOE_START_DOCSTRING,
1082
+ )
1083
+ class GroveMoeModel(GroveMoePreTrainedModel):
1084
+ """
1085
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`Qwen3MoeDecoderLayer`]
1086
+
1087
+ Args:
1088
+ config: Qwen3MoeConfig
1089
+ """
1090
+
1091
+ def __init__(self, config: Qwen3MoeConfig):
1092
+ super().__init__(config)
1093
+ self.padding_idx = config.pad_token_id
1094
+ self.vocab_size = config.vocab_size
1095
+
1096
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
1097
+ self.layers = nn.ModuleList(
1098
+ [GroveMoeDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
1099
+ )
1100
+ self.norm = Qwen3MoeRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
1101
+ self.rotary_emb = Qwen3MoeRotaryEmbedding(config=config)
1102
+ self.gradient_checkpointing = False
1103
+
1104
+ # Initialize weights and apply final processing
1105
+ self.post_init()
1106
+
1107
+ def get_input_embeddings(self):
1108
+ return self.embed_tokens
1109
+
1110
+ def set_input_embeddings(self, value):
1111
+ self.embed_tokens = value
1112
+
1113
+ @can_return_tuple
1114
+ @add_start_docstrings_to_model_forward(QWEN3_MOE_INPUTS_DOCSTRING)
1115
+ def forward(
1116
+ self,
1117
+ input_ids: Optional[torch.LongTensor] = None,
1118
+ attention_mask: Optional[torch.Tensor] = None,
1119
+ position_ids: Optional[torch.LongTensor] = None,
1120
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1121
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1122
+ use_cache: Optional[bool] = None,
1123
+ output_attentions: Optional[bool] = None,
1124
+ output_hidden_states: Optional[bool] = None,
1125
+ output_router_logits: Optional[bool] = None,
1126
+ cache_position: Optional[torch.LongTensor] = None,
1127
+ **flash_attn_kwargs: Unpack[FlashAttentionKwargs],
1128
+ ) -> MoeModelOutputWithPast:
1129
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1130
+ output_router_logits = (
1131
+ output_router_logits if output_router_logits is not None else self.config.output_router_logits
1132
+ )
1133
+ output_hidden_states = (
1134
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1135
+ )
1136
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
1137
+
1138
+ if (input_ids is None) ^ (inputs_embeds is not None):
1139
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
1140
+
1141
+ if self.gradient_checkpointing and self.training:
1142
+ if use_cache:
1143
+ logger.warning_once(
1144
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
1145
+ )
1146
+ use_cache = False
1147
+
1148
+ if use_cache and past_key_values is None:
1149
+ past_key_values = DynamicCache()
1150
+
1151
+ if inputs_embeds is None:
1152
+ inputs_embeds = self.embed_tokens(input_ids)
1153
+
1154
+ if cache_position is None:
1155
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
1156
+ cache_position = torch.arange(
1157
+ past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
1158
+ )
1159
+ if position_ids is None:
1160
+ position_ids = cache_position.unsqueeze(0)
1161
+
1162
+ causal_mask = self._update_causal_mask(
1163
+ attention_mask, inputs_embeds, cache_position, past_key_values, output_attentions
1164
+ )
1165
+
1166
+ hidden_states = inputs_embeds
1167
+
1168
+ # create position embeddings to be shared across the decoder layers
1169
+ position_embeddings = self.rotary_emb(hidden_states, position_ids)
1170
+
1171
+ # decoder layers
1172
+ all_hidden_states = () if output_hidden_states else None
1173
+ all_self_attns = () if output_attentions else None
1174
+ all_router_logits = () if output_router_logits else None
1175
+
1176
+ for decoder_layer in self.layers:
1177
+ if output_hidden_states:
1178
+ all_hidden_states += (hidden_states,)
1179
+
1180
+ if self.gradient_checkpointing and self.training:
1181
+ layer_outputs = self._gradient_checkpointing_func(
1182
+ partial(decoder_layer.__call__, **flash_attn_kwargs),
1183
+ hidden_states,
1184
+ causal_mask,
1185
+ position_ids,
1186
+ past_key_values,
1187
+ output_attentions,
1188
+ output_router_logits,
1189
+ use_cache,
1190
+ cache_position,
1191
+ position_embeddings,
1192
+ )
1193
+ else:
1194
+ layer_outputs = decoder_layer(
1195
+ hidden_states,
1196
+ attention_mask=causal_mask,
1197
+ position_ids=position_ids,
1198
+ past_key_value=past_key_values,
1199
+ output_attentions=output_attentions,
1200
+ output_router_logits=output_router_logits,
1201
+ use_cache=use_cache,
1202
+ cache_position=cache_position,
1203
+ position_embeddings=position_embeddings,
1204
+ **flash_attn_kwargs,
1205
+ )
1206
+
1207
+ hidden_states = layer_outputs[0]
1208
+
1209
+ if output_attentions:
1210
+ all_self_attns += (layer_outputs[1],)
1211
+
1212
+ if output_router_logits:
1213
+ all_router_logits += (layer_outputs[-1],)
1214
+
1215
+ hidden_states = self.norm(hidden_states)
1216
+
1217
+ # add hidden states from the last decoder layer
1218
+ if output_hidden_states:
1219
+ all_hidden_states += (hidden_states,)
1220
+
1221
+ return MoeModelOutputWithPast(
1222
+ last_hidden_state=hidden_states,
1223
+ past_key_values=past_key_values,
1224
+ hidden_states=all_hidden_states,
1225
+ attentions=all_self_attns,
1226
+ router_logits=all_router_logits,
1227
+ )
1228
+
1229
+ def _update_causal_mask(
1230
+ self,
1231
+ attention_mask: torch.Tensor,
1232
+ input_tensor: torch.Tensor,
1233
+ cache_position: torch.Tensor,
1234
+ past_key_values: Cache,
1235
+ output_attentions: bool = False,
1236
+ ):
1237
+ if self.config._attn_implementation == "flash_attention_2":
1238
+ if attention_mask is not None and past_key_values is not None:
1239
+ is_padding_right = attention_mask[:, -1].sum().item() != input_tensor.size()[0]
1240
+ if is_padding_right:
1241
+ raise ValueError(
1242
+ "You are attempting to perform batched generation with padding_side='right'"
1243
+ " this may lead to unexpected behaviour for Flash Attention version of Qwen3Moe. Make sure to "
1244
+ " call `tokenizer.padding_side = 'left'` before tokenizing the input. "
1245
+ )
1246
+ if attention_mask is not None and 0.0 in attention_mask:
1247
+ return attention_mask
1248
+ return None
1249
+
1250
+ # For SDPA, when possible, we will rely on its `is_causal` argument instead of its `attn_mask` argument, in
1251
+ # order to dispatch on Flash Attention 2. This feature is not compatible with static cache, as SDPA will fail
1252
+ # to infer the attention mask.
1253
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
1254
+ using_static_cache = isinstance(past_key_values, StaticCache)
1255
+ using_sliding_window_cache = isinstance(past_key_values, SlidingWindowCache)
1256
+
1257
+ # When output attentions is True, sdpa implementation's forward method calls the eager implementation's forward
1258
+ if (
1259
+ self.config._attn_implementation == "sdpa"
1260
+ and not (using_static_cache or using_sliding_window_cache)
1261
+ and not output_attentions
1262
+ ):
1263
+ if AttentionMaskConverter._ignore_causal_mask_sdpa(
1264
+ attention_mask,
1265
+ inputs_embeds=input_tensor,
1266
+ past_key_values_length=past_seen_tokens,
1267
+ sliding_window=self.config.sliding_window,
1268
+ is_training=self.training,
1269
+ ):
1270
+ return None
1271
+
1272
+ dtype, device = input_tensor.dtype, input_tensor.device
1273
+ min_dtype = torch.finfo(dtype).min
1274
+ sequence_length = input_tensor.shape[1]
1275
+ # SlidingWindowCache or StaticCache
1276
+ if using_sliding_window_cache or using_static_cache:
1277
+ target_length = past_key_values.get_max_cache_shape()
1278
+ # DynamicCache or no cache
1279
+ else:
1280
+ target_length = (
1281
+ attention_mask.shape[-1]
1282
+ if isinstance(attention_mask, torch.Tensor)
1283
+ else past_seen_tokens + sequence_length + 1
1284
+ )
1285
+
1286
+ # In case the provided `attention` mask is 2D, we generate a causal mask here (4D).
1287
+ causal_mask = self._prepare_4d_causal_attention_mask_with_cache_position(
1288
+ attention_mask,
1289
+ sequence_length=sequence_length,
1290
+ target_length=target_length,
1291
+ dtype=dtype,
1292
+ device=device,
1293
+ cache_position=cache_position,
1294
+ batch_size=input_tensor.shape[0],
1295
+ config=self.config,
1296
+ past_key_values=past_key_values,
1297
+ )
1298
+
1299
+ if (
1300
+ self.config._attn_implementation == "sdpa"
1301
+ and attention_mask is not None
1302
+ and attention_mask.device.type in ["cuda", "xpu"]
1303
+ and not output_attentions
1304
+ ):
1305
+ # Attend to all tokens in fully masked rows in the causal_mask, for example the relevant first rows when
1306
+ # using left padding. This is required by F.scaled_dot_product_attention memory-efficient attention path.
1307
+ # Details: https://github.com/pytorch/pytorch/issues/110213
1308
+ causal_mask = AttentionMaskConverter._unmask_unattended(causal_mask, min_dtype)
1309
+
1310
+ return causal_mask
1311
+
1312
+ @staticmethod
1313
+ def _prepare_4d_causal_attention_mask_with_cache_position(
1314
+ attention_mask: torch.Tensor,
1315
+ sequence_length: int,
1316
+ target_length: int,
1317
+ dtype: torch.dtype,
1318
+ device: torch.device,
1319
+ cache_position: torch.Tensor,
1320
+ batch_size: int,
1321
+ config: Qwen3MoeConfig,
1322
+ past_key_values: Cache,
1323
+ ):
1324
+ """
1325
+ Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape
1326
+ `(batch_size, key_value_length)`, or if the input `attention_mask` is already 4D, do nothing.
1327
+
1328
+ Args:
1329
+ attention_mask (`torch.Tensor`):
1330
+ A 2D attention mask of shape `(batch_size, key_value_length)` or a 4D attention mask of shape `(batch_size, 1, query_length, key_value_length)`.
1331
+ sequence_length (`int`):
1332
+ The sequence length being processed.
1333
+ target_length (`int`):
1334
+ The target length: when generating with static cache, the mask should be as long as the static cache, to account for the 0 padding, the part of the cache that is not filled yet.
1335
+ dtype (`torch.dtype`):
1336
+ The dtype to use for the 4D attention mask.
1337
+ device (`torch.device`):
1338
+ The device to place the 4D attention mask on.
1339
+ cache_position (`torch.Tensor`):
1340
+ Indices depicting the position of the input sequence tokens in the sequence.
1341
+ batch_size (`torch.Tensor`):
1342
+ Batch size.
1343
+ config (`Qwen3MoeConfig`):
1344
+ The model's configuration class
1345
+ past_key_values (`Cache`):
1346
+ The cache class that is being used currently to generate
1347
+ """
1348
+ if attention_mask is not None and attention_mask.dim() == 4:
1349
+ # In this case we assume that the mask comes already in inverted form and requires no inversion or slicing.
1350
+ causal_mask = attention_mask
1351
+ else:
1352
+ min_dtype = torch.finfo(dtype).min
1353
+ causal_mask = torch.full(
1354
+ (sequence_length, target_length), fill_value=min_dtype, dtype=dtype, device=device
1355
+ )
1356
+ diagonal_attend_mask = torch.arange(target_length, device=device) > cache_position.reshape(-1, 1)
1357
+ if config.sliding_window is not None:
1358
+ # if we have sliding window, we should not attend to tokens beyond sliding window length, so we mask them out also
1359
+ # the check is needed to verify is current checkpoint was trained with sliding window or not
1360
+ if not isinstance(past_key_values, SlidingWindowCache) or sequence_length > target_length:
1361
+ sliding_attend_mask = torch.arange(target_length, device=device) <= (
1362
+ cache_position.reshape(-1, 1) - config.sliding_window
1363
+ )
1364
+ diagonal_attend_mask.bitwise_or_(sliding_attend_mask)
1365
+ causal_mask *= diagonal_attend_mask
1366
+ causal_mask = causal_mask[None, None, :, :].expand(batch_size, 1, -1, -1)
1367
+ if attention_mask is not None:
1368
+ causal_mask = causal_mask.clone() # copy to contiguous memory for in-place edit
1369
+ if attention_mask.shape[-1] > target_length:
1370
+ attention_mask = attention_mask[:, :target_length]
1371
+ mask_length = attention_mask.shape[-1]
1372
+ padding_mask = causal_mask[:, :, :, :mask_length] + attention_mask[:, None, None, :].to(
1373
+ causal_mask.device
1374
+ )
1375
+ padding_mask = padding_mask == 0
1376
+ causal_mask[:, :, :, :mask_length] = causal_mask[:, :, :, :mask_length].masked_fill(
1377
+ padding_mask, min_dtype
1378
+ )
1379
+ return causal_mask
1380
+
1381
+ class KwargsForCausalLM(FlashAttentionKwargs, LossKwargs): ...
1382
+
1383
+
1384
+ def load_balancing_loss_func(
1385
+ gate_logits: Union[torch.Tensor, Tuple[torch.Tensor], None],
1386
+ num_experts: Optional[int] = None,
1387
+ top_k=2,
1388
+ attention_mask: Optional[torch.Tensor] = None,
1389
+ ) -> Union[torch.Tensor, int]:
1390
+ r"""
1391
+ Computes auxiliary load balancing loss as in Switch Transformer - implemented in Pytorch.
1392
+
1393
+ See Switch Transformer (https://arxiv.org/abs/2101.03961) for more details. This function implements the loss
1394
+ function presented in equations (4) - (6) of the paper. It aims at penalizing cases where the routing between
1395
+ experts is too unbalanced.
1396
+
1397
+ Args:
1398
+ gate_logits:
1399
+ Logits from the `gate`, should be a tuple of model.config.num_hidden_layers tensors of
1400
+ shape [batch_size X sequence_length, num_experts].
1401
+ num_experts:
1402
+ Number of experts
1403
+ top_k:
1404
+ The number of experts to route per-token, can be also interpreted as the `top-k` routing
1405
+ parameter.
1406
+ attention_mask (`torch.Tensor`, *optional*):
1407
+ The attention_mask used in forward function
1408
+ shape [batch_size X sequence_length] if not None.
1409
+
1410
+ Returns:
1411
+ The auxiliary loss.
1412
+ """
1413
+ if gate_logits is None or not isinstance(gate_logits, tuple):
1414
+ return 0
1415
+
1416
+ if isinstance(gate_logits, tuple):
1417
+ compute_device = gate_logits[0].device
1418
+ concatenated_gate_logits = torch.cat([layer_gate.to(compute_device) for layer_gate in gate_logits], dim=0)
1419
+
1420
+ routing_weights = torch.nn.functional.softmax(concatenated_gate_logits, dim=-1)
1421
+
1422
+ _, selected_experts = torch.topk(routing_weights, top_k, dim=-1)
1423
+
1424
+ expert_mask = torch.nn.functional.one_hot(selected_experts, num_experts)
1425
+
1426
+ if attention_mask is None:
1427
+ # Compute the percentage of tokens routed to each experts
1428
+ tokens_per_expert = torch.mean(expert_mask.float(), dim=0)
1429
+
1430
+ # Compute the average probability of routing to these experts
1431
+ router_prob_per_expert = torch.mean(routing_weights, dim=0)
1432
+ else:
1433
+ batch_size, sequence_length = attention_mask.shape
1434
+ num_hidden_layers = concatenated_gate_logits.shape[0] // (batch_size * sequence_length)
1435
+
1436
+ # Compute the mask that masks all padding tokens as 0 with the same shape of expert_mask
1437
+ expert_attention_mask = (
1438
+ attention_mask[None, :, :, None, None]
1439
+ .expand((num_hidden_layers, batch_size, sequence_length, top_k, num_experts))
1440
+ .reshape(-1, top_k, num_experts)
1441
+ .to(compute_device)
1442
+ )
1443
+
1444
+ # Compute the percentage of tokens routed to each experts
1445
+ tokens_per_expert = torch.sum(expert_mask.float() * expert_attention_mask, dim=0) / torch.sum(
1446
+ expert_attention_mask, dim=0
1447
+ )
1448
+
1449
+ # Compute the mask that masks all padding tokens as 0 with the same shape of tokens_per_expert
1450
+ router_per_expert_attention_mask = (
1451
+ attention_mask[None, :, :, None]
1452
+ .expand((num_hidden_layers, batch_size, sequence_length, num_experts))
1453
+ .reshape(-1, num_experts)
1454
+ .to(compute_device)
1455
+ )
1456
+
1457
+ # Compute the average probability of routing to these experts
1458
+ router_prob_per_expert = torch.sum(routing_weights * router_per_expert_attention_mask, dim=0) / torch.sum(
1459
+ router_per_expert_attention_mask, dim=0
1460
+ )
1461
+
1462
+ overall_loss = torch.sum(tokens_per_expert * router_prob_per_expert.unsqueeze(0))
1463
+ return overall_loss * num_experts
1464
+
1465
+
1466
+ class Qwen3MoeForCausalLM(Qwen3MoePreTrainedModel, GenerationMixin):
1467
+ _tied_weights_keys = ["lm_head.weight"]
1468
+ _tp_plan = {"lm_head": "colwise_rep"}
1469
+ _pp_plan = {"lm_head": (["hidden_states"], ["logits"])}
1470
+
1471
+ def __init__(self, config):
1472
+ super().__init__(config)
1473
+ self.model = Qwen3MoeModel(config)
1474
+ self.vocab_size = config.vocab_size
1475
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1476
+ self.router_aux_loss_coef = config.router_aux_loss_coef
1477
+ self.num_experts = config.num_experts
1478
+ self.num_experts_per_tok = config.num_experts_per_tok
1479
+
1480
+ # Initialize weights and apply final processing
1481
+ self.post_init()
1482
+
1483
+ def get_input_embeddings(self):
1484
+ return self.model.embed_tokens
1485
+
1486
+ def set_input_embeddings(self, value):
1487
+ self.model.embed_tokens = value
1488
+
1489
+ def get_output_embeddings(self):
1490
+ return self.lm_head
1491
+
1492
+ def set_output_embeddings(self, new_embeddings):
1493
+ self.lm_head = new_embeddings
1494
+
1495
+ def set_decoder(self, decoder):
1496
+ self.model = decoder
1497
+
1498
+ def get_decoder(self):
1499
+ return self.model
1500
+
1501
+ @can_return_tuple
1502
+ @deprecate_kwarg("num_logits_to_keep", version="4.50", new_name="logits_to_keep")
1503
+ @add_start_docstrings_to_model_forward(QWEN3_MOE_INPUTS_DOCSTRING)
1504
+ @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
1505
+ def forward(
1506
+ self,
1507
+ input_ids: Optional[torch.LongTensor] = None,
1508
+ attention_mask: Optional[torch.Tensor] = None,
1509
+ position_ids: Optional[torch.LongTensor] = None,
1510
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1511
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1512
+ labels: Optional[torch.LongTensor] = None,
1513
+ use_cache: Optional[bool] = None,
1514
+ output_attentions: Optional[bool] = None,
1515
+ output_hidden_states: Optional[bool] = None,
1516
+ output_router_logits: Optional[bool] = None,
1517
+ cache_position: Optional[torch.LongTensor] = None,
1518
+ logits_to_keep: Union[int, torch.Tensor] = 0,
1519
+ **kwargs: Unpack[KwargsForCausalLM],
1520
+ ) -> MoeCausalLMOutputWithPast:
1521
+ r"""
1522
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1523
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1524
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1525
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1526
+
1527
+ logits_to_keep (`int` or `torch.Tensor`, *optional*):
1528
+ If an `int`, compute logits for the last `logits_to_keep` tokens. If `0`, calculate logits for all
1529
+ `input_ids` (special case). Only last token logits are needed for generation, and calculating them only for that
1530
+ token can save memory, which becomes pretty significant for long sequences or large vocabulary size.
1531
+ If a `torch.Tensor`, must be 1D corresponding to the indices to keep in the sequence length dimension.
1532
+ This is useful when using packed tensor format (single dimension for batch and sequence length).
1533
+
1534
+ Returns:
1535
+
1536
+ Example:
1537
+
1538
+ ```python
1539
+ >>> from transformers import AutoTokenizer, Qwen3MoeForCausalLM
1540
+
1541
+ >>> model = Qwen3MoeForCausalLM.from_pretrained("Qwen/Qwen3-MoE-15B-A2B")
1542
+ >>> tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen3-MoE-15B-A2B")
1543
+
1544
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
1545
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
1546
+
1547
+ >>> # Generate
1548
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
1549
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1550
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
1551
+ ```"""
1552
+
1553
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1554
+ output_router_logits = (
1555
+ output_router_logits if output_router_logits is not None else self.config.output_router_logits
1556
+ )
1557
+
1558
+ output_hidden_states = (
1559
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1560
+ )
1561
+
1562
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1563
+ outputs: MoeModelOutputWithPast = self.model(
1564
+ input_ids=input_ids,
1565
+ attention_mask=attention_mask,
1566
+ position_ids=position_ids,
1567
+ past_key_values=past_key_values,
1568
+ inputs_embeds=inputs_embeds,
1569
+ use_cache=use_cache,
1570
+ output_attentions=output_attentions,
1571
+ output_hidden_states=output_hidden_states,
1572
+ output_router_logits=output_router_logits,
1573
+ cache_position=cache_position,
1574
+ **kwargs,
1575
+ )
1576
+
1577
+ hidden_states = outputs.last_hidden_state
1578
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
1579
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
1580
+ logits = self.lm_head(hidden_states[:, slice_indices, :])
1581
+
1582
+ loss = None
1583
+ if labels is not None:
1584
+ loss = self.loss_function(logits, labels, self.vocab_size, **kwargs)
1585
+
1586
+ aux_loss = None
1587
+ if output_router_logits:
1588
+ aux_loss = load_balancing_loss_func(
1589
+ outputs.router_logits,
1590
+ self.num_experts,
1591
+ self.num_experts_per_tok,
1592
+ attention_mask,
1593
+ )
1594
+ if labels is not None:
1595
+ loss += self.router_aux_loss_coef * aux_loss.to(loss.device) # make sure to reside in the same device
1596
+
1597
+ return MoeCausalLMOutputWithPast(
1598
+ loss=loss,
1599
+ aux_loss=aux_loss,
1600
+ logits=logits,
1601
+ past_key_values=outputs.past_key_values,
1602
+ hidden_states=outputs.hidden_states,
1603
+ attentions=outputs.attentions,
1604
+ router_logits=outputs.router_logits,
1605
+ )
1606
+
1607
+
1608
+
1609
+ class GroveMoeForCausalLM(GroveMoePreTrainedModel, GenerationMixin):
1610
+ _tied_weights_keys = ["lm_head.weight"]
1611
+ _tp_plan = {"lm_head": "colwise_rep"}
1612
+ _pp_plan = {"lm_head": (["hidden_states"], ["logits"])}
1613
+
1614
+ def __init__(self, config):
1615
+ super().__init__(config)
1616
+ self.model = Qwen3MoeModel(config)
1617
+ self.vocab_size = config.vocab_size
1618
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1619
+ self.router_aux_loss_coef = config.router_aux_loss_coef
1620
+ self.num_experts = config.num_experts
1621
+ self.num_experts_per_tok = config.num_experts_per_tok
1622
+
1623
+ # Initialize weights and apply final processing
1624
+ self.post_init()
1625
+
1626
+ def get_input_embeddings(self):
1627
+ return self.model.embed_tokens
1628
+
1629
+ def set_input_embeddings(self, value):
1630
+ self.model.embed_tokens = value
1631
+
1632
+ def get_output_embeddings(self):
1633
+ return self.lm_head
1634
+
1635
+ def set_output_embeddings(self, new_embeddings):
1636
+ self.lm_head = new_embeddings
1637
+
1638
+ def set_decoder(self, decoder):
1639
+ self.model = decoder
1640
+
1641
+ def get_decoder(self):
1642
+ return self.model
1643
+
1644
+ @can_return_tuple
1645
+ @deprecate_kwarg("num_logits_to_keep", version="4.50", new_name="logits_to_keep")
1646
+ @add_start_docstrings_to_model_forward(QWEN3_MOE_INPUTS_DOCSTRING)
1647
+ @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
1648
+ def forward(
1649
+ self,
1650
+ input_ids: Optional[torch.LongTensor] = None,
1651
+ attention_mask: Optional[torch.Tensor] = None,
1652
+ position_ids: Optional[torch.LongTensor] = None,
1653
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1654
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1655
+ labels: Optional[torch.LongTensor] = None,
1656
+ use_cache: Optional[bool] = None,
1657
+ output_attentions: Optional[bool] = None,
1658
+ output_hidden_states: Optional[bool] = None,
1659
+ output_router_logits: Optional[bool] = None,
1660
+ cache_position: Optional[torch.LongTensor] = None,
1661
+ logits_to_keep: Union[int, torch.Tensor] = 0,
1662
+ **kwargs: Unpack[KwargsForCausalLM],
1663
+ ) -> MoeCausalLMOutputWithPast:
1664
+ r"""
1665
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1666
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1667
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1668
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1669
+
1670
+ logits_to_keep (`int` or `torch.Tensor`, *optional*):
1671
+ If an `int`, compute logits for the last `logits_to_keep` tokens. If `0`, calculate logits for all
1672
+ `input_ids` (special case). Only last token logits are needed for generation, and calculating them only for that
1673
+ token can save memory, which becomes pretty significant for long sequences or large vocabulary size.
1674
+ If a `torch.Tensor`, must be 1D corresponding to the indices to keep in the sequence length dimension.
1675
+ This is useful when using packed tensor format (single dimension for batch and sequence length).
1676
+
1677
+ Returns:
1678
+
1679
+ Example:
1680
+
1681
+ ```python
1682
+ >>> from transformers import AutoTokenizer, Qwen3MoeForCausalLM
1683
+
1684
+ >>> model = Qwen3MoeForCausalLM.from_pretrained("Qwen/Qwen3-MoE-15B-A2B")
1685
+ >>> tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen3-MoE-15B-A2B")
1686
+
1687
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
1688
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
1689
+
1690
+ >>> # Generate
1691
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
1692
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1693
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
1694
+ ```"""
1695
+
1696
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1697
+ output_router_logits = (
1698
+ output_router_logits if output_router_logits is not None else self.config.output_router_logits
1699
+ )
1700
+
1701
+ output_hidden_states = (
1702
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1703
+ )
1704
+
1705
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1706
+ outputs: MoeModelOutputWithPast = self.model(
1707
+ input_ids=input_ids,
1708
+ attention_mask=attention_mask,
1709
+ position_ids=position_ids,
1710
+ past_key_values=past_key_values,
1711
+ inputs_embeds=inputs_embeds,
1712
+ use_cache=use_cache,
1713
+ output_attentions=output_attentions,
1714
+ output_hidden_states=output_hidden_states,
1715
+ output_router_logits=output_router_logits,
1716
+ cache_position=cache_position,
1717
+ **kwargs,
1718
+ )
1719
+
1720
+ hidden_states = outputs.last_hidden_state
1721
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
1722
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
1723
+ logits = self.lm_head(hidden_states[:, slice_indices, :])
1724
+
1725
+ loss = None
1726
+ if labels is not None:
1727
+ loss = self.loss_function(logits, labels, self.vocab_size, **kwargs)
1728
+
1729
+ aux_loss = None
1730
+ if output_router_logits:
1731
+ aux_loss = load_balancing_loss_func(
1732
+ outputs.router_logits,
1733
+ self.num_experts,
1734
+ self.num_experts_per_tok,
1735
+ attention_mask,
1736
+ )
1737
+ if labels is not None:
1738
+ loss += self.router_aux_loss_coef * aux_loss.to(loss.device) # make sure to reside in the same device
1739
+
1740
+ return MoeCausalLMOutputWithPast(
1741
+ loss=loss,
1742
+ aux_loss=aux_loss,
1743
+ logits=logits,
1744
+ past_key_values=outputs.past_key_values,
1745
+ hidden_states=outputs.hidden_states,
1746
+ attentions=outputs.attentions,
1747
+ router_logits=outputs.router_logits,
1748
+ )
1749
+
1750
+
1751
+ @add_start_docstrings(
1752
+ """
1753
+ The Qwen3Moe Model transformer with a sequence classification head on top (linear layer).
1754
+
1755
+ [`Qwen3MoeForSequenceClassification`] uses the last token in order to do the classification, as other causal models
1756
+ (e.g. GPT-2) do.
1757
+
1758
+ Since it does classification on the last token, it requires to know the position of the last token. If a
1759
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
1760
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
1761
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
1762
+ each row of the batch).
1763
+ """,
1764
+ QWEN3_MOE_START_DOCSTRING,
1765
+ )
1766
+ class Qwen3MoeForSequenceClassification(Qwen3MoePreTrainedModel):
1767
+ def __init__(self, config):
1768
+ super().__init__(config)
1769
+ self.num_labels = config.num_labels
1770
+ self.model = Qwen3MoeModel(config)
1771
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
1772
+
1773
+ # Initialize weights and apply final processing
1774
+ self.post_init()
1775
+
1776
+ def get_input_embeddings(self):
1777
+ return self.model.embed_tokens
1778
+
1779
+ def set_input_embeddings(self, value):
1780
+ self.model.embed_tokens = value
1781
+
1782
+ @can_return_tuple
1783
+ @add_start_docstrings_to_model_forward(QWEN3_MOE_INPUTS_DOCSTRING)
1784
+ def forward(
1785
+ self,
1786
+ input_ids: Optional[torch.LongTensor] = None,
1787
+ attention_mask: Optional[torch.Tensor] = None,
1788
+ position_ids: Optional[torch.LongTensor] = None,
1789
+ past_key_values: Optional[Cache] = None,
1790
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1791
+ labels: Optional[torch.LongTensor] = None,
1792
+ use_cache: Optional[bool] = None,
1793
+ output_attentions: Optional[bool] = None,
1794
+ output_hidden_states: Optional[bool] = None,
1795
+ ) -> SequenceClassifierOutputWithPast:
1796
+ r"""
1797
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1798
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1799
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1800
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1801
+ """
1802
+
1803
+ transformer_outputs: BaseModelOutputWithPast = self.model(
1804
+ input_ids,
1805
+ attention_mask=attention_mask,
1806
+ position_ids=position_ids,
1807
+ past_key_values=past_key_values,
1808
+ inputs_embeds=inputs_embeds,
1809
+ use_cache=use_cache,
1810
+ output_attentions=output_attentions,
1811
+ output_hidden_states=output_hidden_states,
1812
+ )
1813
+ hidden_states = transformer_outputs.last_hidden_state
1814
+ logits = self.score(hidden_states)
1815
+
1816
+ if input_ids is not None:
1817
+ batch_size = input_ids.shape[0]
1818
+ else:
1819
+ batch_size = inputs_embeds.shape[0]
1820
+
1821
+ if self.config.pad_token_id is None and batch_size != 1:
1822
+ raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
1823
+ if self.config.pad_token_id is None:
1824
+ last_non_pad_token = -1
1825
+ elif input_ids is not None:
1826
+ # To handle both left- and right- padding, we take the rightmost token that is not equal to pad_token_id
1827
+ non_pad_mask = (input_ids != self.config.pad_token_id).to(logits.device, torch.int32)
1828
+ token_indices = torch.arange(input_ids.shape[-1], device=logits.device, dtype=torch.int32)
1829
+ last_non_pad_token = (token_indices * non_pad_mask).argmax(-1)
1830
+ else:
1831
+ last_non_pad_token = -1
1832
+ logger.warning_once(
1833
+ f"{self.__class__.__name__} will not detect padding tokens in `inputs_embeds`. Results may be "
1834
+ "unexpected if using padding tokens in conjunction with `inputs_embeds.`"
1835
+ )
1836
+
1837
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), last_non_pad_token]
1838
+
1839
+ loss = None
1840
+ if labels is not None:
1841
+ loss = self.loss_function(logits=logits, labels=labels, pooled_logits=pooled_logits, config=self.config)
1842
+
1843
+ return SequenceClassifierOutputWithPast(
1844
+ loss=loss,
1845
+ logits=pooled_logits,
1846
+ past_key_values=transformer_outputs.past_key_values,
1847
+ hidden_states=transformer_outputs.hidden_states,
1848
+ attentions=transformer_outputs.attentions,
1849
+ )
1850
+
1851
+
1852
+ @add_start_docstrings(
1853
+ """
1854
+ The Qwen3Moe Model transformer with a token classification head on top (a linear layer on top of the hidden-states
1855
+ output) e.g. for Named-Entity-Recognition (NER) tasks.
1856
+ """,
1857
+ QWEN3_MOE_START_DOCSTRING,
1858
+ )
1859
+ class Qwen3MoeForTokenClassification(Qwen3MoePreTrainedModel):
1860
+ def __init__(self, config):
1861
+ super().__init__(config)
1862
+ self.num_labels = config.num_labels
1863
+ self.model = Qwen3MoeModel(config)
1864
+ if getattr(config, "classifier_dropout", None) is not None:
1865
+ classifier_dropout = config.classifier_dropout
1866
+ elif getattr(config, "hidden_dropout", None) is not None:
1867
+ classifier_dropout = config.hidden_dropout
1868
+ else:
1869
+ classifier_dropout = 0.1
1870
+ self.dropout = nn.Dropout(classifier_dropout)
1871
+ self.score = nn.Linear(config.hidden_size, config.num_labels)
1872
+
1873
+ # Initialize weights and apply final processing
1874
+ self.post_init()
1875
+
1876
+ def get_input_embeddings(self):
1877
+ return self.model.embed_tokens
1878
+
1879
+ def set_input_embeddings(self, value):
1880
+ self.model.embed_tokens = value
1881
+
1882
+ @can_return_tuple
1883
+ @add_start_docstrings_to_model_forward(QWEN3_MOE_INPUTS_DOCSTRING)
1884
+ @add_code_sample_docstrings(
1885
+ checkpoint=_CHECKPOINT_FOR_DOC,
1886
+ output_type=TokenClassifierOutput,
1887
+ config_class=_CONFIG_FOR_DOC,
1888
+ )
1889
+ def forward(
1890
+ self,
1891
+ input_ids: Optional[torch.LongTensor] = None,
1892
+ attention_mask: Optional[torch.Tensor] = None,
1893
+ position_ids: Optional[torch.LongTensor] = None,
1894
+ past_key_values: Optional[Cache] = None,
1895
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1896
+ labels: Optional[torch.LongTensor] = None,
1897
+ use_cache: Optional[bool] = None,
1898
+ output_attentions: Optional[bool] = None,
1899
+ output_hidden_states: Optional[bool] = None,
1900
+ ) -> TokenClassifierOutput:
1901
+ r"""
1902
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1903
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1904
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1905
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1906
+ """
1907
+
1908
+ outputs: BaseModelOutputWithPast = self.model(
1909
+ input_ids,
1910
+ attention_mask=attention_mask,
1911
+ position_ids=position_ids,
1912
+ past_key_values=past_key_values,
1913
+ inputs_embeds=inputs_embeds,
1914
+ use_cache=use_cache,
1915
+ output_attentions=output_attentions,
1916
+ output_hidden_states=output_hidden_states,
1917
+ )
1918
+ sequence_output = outputs.last_hidden_state
1919
+ sequence_output = self.dropout(sequence_output)
1920
+ logits = self.score(sequence_output)
1921
+
1922
+ loss = None
1923
+ if labels is not None:
1924
+ loss = self.loss_function(logits, labels, self.config)
1925
+
1926
+ return TokenClassifierOutput(
1927
+ loss=loss,
1928
+ logits=logits,
1929
+ hidden_states=outputs.hidden_states,
1930
+ attentions=outputs.attentions,
1931
+ )
1932
+
1933
+
1934
+ @add_start_docstrings(
1935
+ """
1936
+ The Qwen3Moe Model transformer with a span classification head on top for extractive question-answering tasks like
1937
+ SQuAD (a linear layer on top of the hidden-states output to compute `span start logits` and `span end logits`).
1938
+ """,
1939
+ QWEN3_MOE_START_DOCSTRING,
1940
+ )
1941
+ class Qwen3MoeForQuestionAnswering(Qwen3MoePreTrainedModel):
1942
+ base_model_prefix = "transformer"
1943
+
1944
+ def __init__(self, config):
1945
+ super().__init__(config)
1946
+ self.transformer = Qwen3MoeModel(config)
1947
+ self.qa_outputs = nn.Linear(config.hidden_size, 2)
1948
+
1949
+ # Initialize weights and apply final processing
1950
+ self.post_init()
1951
+
1952
+ def get_input_embeddings(self):
1953
+ return self.transformer.embed_tokens
1954
+
1955
+ def set_input_embeddings(self, value):
1956
+ self.transformer.embed_tokens = value
1957
+
1958
+ @can_return_tuple
1959
+ @add_start_docstrings_to_model_forward(QWEN3_MOE_INPUTS_DOCSTRING)
1960
+ def forward(
1961
+ self,
1962
+ input_ids: Optional[torch.LongTensor] = None,
1963
+ attention_mask: Optional[torch.FloatTensor] = None,
1964
+ position_ids: Optional[torch.LongTensor] = None,
1965
+ past_key_values: Optional[Cache] = None,
1966
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1967
+ start_positions: Optional[torch.LongTensor] = None,
1968
+ end_positions: Optional[torch.LongTensor] = None,
1969
+ output_attentions: Optional[bool] = None,
1970
+ output_hidden_states: Optional[bool] = None,
1971
+ **kwargs,
1972
+ ) -> QuestionAnsweringModelOutput:
1973
+ r"""
1974
+ start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1975
+ Labels for position (index) of the start of the labelled span for computing the token classification loss.
1976
+ Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
1977
+ are not taken into account for computing the loss.
1978
+ end_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1979
+ Labels for position (index) of the end of the labelled span for computing the token classification loss.
1980
+ Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
1981
+ are not taken into account for computing the loss.
1982
+ """
1983
+
1984
+ outputs: BaseModelOutputWithPast = self.transformer(
1985
+ input_ids,
1986
+ attention_mask=attention_mask,
1987
+ position_ids=position_ids,
1988
+ past_key_values=past_key_values,
1989
+ inputs_embeds=inputs_embeds,
1990
+ output_attentions=output_attentions,
1991
+ output_hidden_states=output_hidden_states,
1992
+ )
1993
+
1994
+ sequence_output = outputs.last_hidden_state
1995
+
1996
+ logits = self.qa_outputs(sequence_output)
1997
+ start_logits, end_logits = logits.split(1, dim=-1)
1998
+ start_logits = start_logits.squeeze(-1).contiguous()
1999
+ end_logits = end_logits.squeeze(-1).contiguous()
2000
+
2001
+ loss = None
2002
+ if start_positions is not None and end_positions is not None:
2003
+ loss = self.loss_function(start_logits, end_logits, start_positions, end_positions, **kwargs)
2004
+
2005
+ return QuestionAnsweringModelOutput(
2006
+ loss=loss,
2007
+ start_logits=start_logits,
2008
+ end_logits=end_logits,
2009
+ hidden_states=outputs.hidden_states,
2010
+ attentions=outputs.attentions,
2011
+ )
2012
+
2013
+
2014
+ __all__ = [
2015
+ "GroveMoeForCausalLM",
2016
+ "Qwen3MoeForCausalLM",
2017
+ "Qwen3MoeForQuestionAnswering",
2018
+ "GroveMoeModel",
2019
+ "Qwen3MoeModel",
2020
+ "Qwen3MoePreTrainedModel",
2021
+ "Qwen3MoeForSequenceClassification",
2022
+ "Qwen3MoeForTokenClassification",
2023
+ ]
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_prefix_space": false,
3
+ "added_tokens_decoder": {
4
+ "151643": {
5
+ "content": "<|endoftext|>",
6
+ "lstrip": false,
7
+ "normalized": false,
8
+ "rstrip": false,
9
+ "single_word": false,
10
+ "special": true
11
+ },
12
+ "151644": {
13
+ "content": "<|im_start|>",
14
+ "lstrip": false,
15
+ "normalized": false,
16
+ "rstrip": false,
17
+ "single_word": false,
18
+ "special": true
19
+ },
20
+ "151645": {
21
+ "content": "<|im_end|>",
22
+ "lstrip": false,
23
+ "normalized": false,
24
+ "rstrip": false,
25
+ "single_word": false,
26
+ "special": true
27
+ },
28
+ "151646": {
29
+ "content": "<|object_ref_start|>",
30
+ "lstrip": false,
31
+ "normalized": false,
32
+ "rstrip": false,
33
+ "single_word": false,
34
+ "special": true
35
+ },
36
+ "151647": {
37
+ "content": "<|object_ref_end|>",
38
+ "lstrip": false,
39
+ "normalized": false,
40
+ "rstrip": false,
41
+ "single_word": false,
42
+ "special": true
43
+ },
44
+ "151648": {
45
+ "content": "<|box_start|>",
46
+ "lstrip": false,
47
+ "normalized": false,
48
+ "rstrip": false,
49
+ "single_word": false,
50
+ "special": true
51
+ },
52
+ "151649": {
53
+ "content": "<|box_end|>",
54
+ "lstrip": false,
55
+ "normalized": false,
56
+ "rstrip": false,
57
+ "single_word": false,
58
+ "special": true
59
+ },
60
+ "151650": {
61
+ "content": "<|quad_start|>",
62
+ "lstrip": false,
63
+ "normalized": false,
64
+ "rstrip": false,
65
+ "single_word": false,
66
+ "special": true
67
+ },
68
+ "151651": {
69
+ "content": "<|quad_end|>",
70
+ "lstrip": false,
71
+ "normalized": false,
72
+ "rstrip": false,
73
+ "single_word": false,
74
+ "special": true
75
+ },
76
+ "151652": {
77
+ "content": "<|vision_start|>",
78
+ "lstrip": false,
79
+ "normalized": false,
80
+ "rstrip": false,
81
+ "single_word": false,
82
+ "special": true
83
+ },
84
+ "151653": {
85
+ "content": "<|vision_end|>",
86
+ "lstrip": false,
87
+ "normalized": false,
88
+ "rstrip": false,
89
+ "single_word": false,
90
+ "special": true
91
+ },
92
+ "151654": {
93
+ "content": "<|vision_pad|>",
94
+ "lstrip": false,
95
+ "normalized": false,
96
+ "rstrip": false,
97
+ "single_word": false,
98
+ "special": true
99
+ },
100
+ "151655": {
101
+ "content": "<|image_pad|>",
102
+ "lstrip": false,
103
+ "normalized": false,
104
+ "rstrip": false,
105
+ "single_word": false,
106
+ "special": true
107
+ },
108
+ "151656": {
109
+ "content": "<|video_pad|>",
110
+ "lstrip": false,
111
+ "normalized": false,
112
+ "rstrip": false,
113
+ "single_word": false,
114
+ "special": true
115
+ },
116
+ "151657": {
117
+ "content": "<tool_call>",
118
+ "lstrip": false,
119
+ "normalized": false,
120
+ "rstrip": false,
121
+ "single_word": false,
122
+ "special": false
123
+ },
124
+ "151658": {
125
+ "content": "</tool_call>",
126
+ "lstrip": false,
127
+ "normalized": false,
128
+ "rstrip": false,
129
+ "single_word": false,
130
+ "special": false
131
+ },
132
+ "151659": {
133
+ "content": "<|fim_prefix|>",
134
+ "lstrip": false,
135
+ "normalized": false,
136
+ "rstrip": false,
137
+ "single_word": false,
138
+ "special": false
139
+ },
140
+ "151660": {
141
+ "content": "<|fim_middle|>",
142
+ "lstrip": false,
143
+ "normalized": false,
144
+ "rstrip": false,
145
+ "single_word": false,
146
+ "special": false
147
+ },
148
+ "151661": {
149
+ "content": "<|fim_suffix|>",
150
+ "lstrip": false,
151
+ "normalized": false,
152
+ "rstrip": false,
153
+ "single_word": false,
154
+ "special": false
155
+ },
156
+ "151662": {
157
+ "content": "<|fim_pad|>",
158
+ "lstrip": false,
159
+ "normalized": false,
160
+ "rstrip": false,
161
+ "single_word": false,
162
+ "special": false
163
+ },
164
+ "151663": {
165
+ "content": "<|repo_name|>",
166
+ "lstrip": false,
167
+ "normalized": false,
168
+ "rstrip": false,
169
+ "single_word": false,
170
+ "special": false
171
+ },
172
+ "151664": {
173
+ "content": "<|file_sep|>",
174
+ "lstrip": false,
175
+ "normalized": false,
176
+ "rstrip": false,
177
+ "single_word": false,
178
+ "special": false
179
+ },
180
+ "151665": {
181
+ "content": "<tool_response>",
182
+ "lstrip": false,
183
+ "normalized": false,
184
+ "rstrip": false,
185
+ "single_word": false,
186
+ "special": false
187
+ },
188
+ "151666": {
189
+ "content": "</tool_response>",
190
+ "lstrip": false,
191
+ "normalized": false,
192
+ "rstrip": false,
193
+ "single_word": false,
194
+ "special": false
195
+ },
196
+ "151667": {
197
+ "content": "<think>",
198
+ "lstrip": false,
199
+ "normalized": false,
200
+ "rstrip": false,
201
+ "single_word": false,
202
+ "special": false
203
+ },
204
+ "151668": {
205
+ "content": "</think>",
206
+ "lstrip": false,
207
+ "normalized": false,
208
+ "rstrip": false,
209
+ "single_word": false,
210
+ "special": false
211
+ }
212
+ },
213
+ "additional_special_tokens": [
214
+ "<|im_start|>",
215
+ "<|im_end|>",
216
+ "<|object_ref_start|>",
217
+ "<|object_ref_end|>",
218
+ "<|box_start|>",
219
+ "<|box_end|>",
220
+ "<|quad_start|>",
221
+ "<|quad_end|>",
222
+ "<|vision_start|>",
223
+ "<|vision_end|>",
224
+ "<|vision_pad|>",
225
+ "<|image_pad|>",
226
+ "<|video_pad|>"
227
+ ],
228
+ "bos_token": null,
229
+ "chat_template": "{%- if tools %}\n {{- '<|im_start|>system\\n' }}\n {%- if messages[0].role == 'system' %}\n {{- messages[0].content + '\\n\\n' }}\n {%- endif %}\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>\" }}\n {%- for tool in tools %}\n {{- \"\\n\" }}\n {{- tool | tojson }}\n {%- endfor %}\n {{- \"\\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\" }}\n{%- else %}\n {%- if messages[0].role == 'system' %}\n {{- '<|im_start|>system\\n' + messages[0].content + '<|im_end|>\\n' }}\n {%- endif %}\n{%- endif %}\n{%- set ns = namespace(multi_step_tool=true, last_query_index=messages|length - 1) %}\n{%- for message in messages[::-1] %}\n {%- set index = (messages|length - 1) - loop.index0 %}\n {%- if ns.multi_step_tool and message.role == \"user\" and message.content is string and not(message.content.startswith('<tool_response>') and message.content.endswith('</tool_response>')) %}\n {%- set ns.multi_step_tool = false %}\n {%- set ns.last_query_index = index %}\n {%- endif %}\n{%- endfor %}\n{%- for message in messages %}\n {%- if message.content is string %}\n {%- set content = message.content %}\n {%- else %}\n {%- set content = '' %}\n {%- endif %}\n {%- if (message.role == \"user\") or (message.role == \"system\" and not loop.first) %}\n {{- '<|im_start|>' + message.role + '\\n' + content + '<|im_end|>' + '\\n' }}\n {%- elif message.role == \"assistant\" %}\n {%- set reasoning_content = '' %}\n {%- if message.reasoning_content is string %}\n {%- set reasoning_content = message.reasoning_content %}\n {%- else %}\n {%- if '</think>' in content %}\n {%- set reasoning_content = content.split('</think>')[0].rstrip('\\n').split('<think>')[-1].lstrip('\\n') %}\n {%- set content = content.split('</think>')[-1].lstrip('\\n') %}\n {%- endif %}\n {%- endif %}\n {%- if loop.index0 > ns.last_query_index %}\n {%- if loop.last or (not loop.last and reasoning_content) %}\n {{- '<|im_start|>' + message.role + '\\n<think>\\n' + reasoning_content.strip('\\n') + '\\n</think>\\n\\n' + content.lstrip('\\n') }}\n {%- else %}\n {{- '<|im_start|>' + message.role + '\\n' + content }}\n {%- endif %}\n {%- else %}\n {{- '<|im_start|>' + message.role + '\\n' + content }}\n {%- endif %}\n {%- if message.tool_calls %}\n {%- for tool_call in message.tool_calls %}\n {%- if (loop.first and content) or (not loop.first) %}\n {{- '\\n' }}\n {%- endif %}\n {%- if tool_call.function %}\n {%- set tool_call = tool_call.function %}\n {%- endif %}\n {{- '<tool_call>\\n{\"name\": \"' }}\n {{- tool_call.name }}\n {{- '\", \"arguments\": ' }}\n {%- if tool_call.arguments is string %}\n {{- tool_call.arguments }}\n {%- else %}\n {{- tool_call.arguments | tojson }}\n {%- endif %}\n {{- '}\\n</tool_call>' }}\n {%- endfor %}\n {%- endif %}\n {{- '<|im_end|>\\n' }}\n {%- elif message.role == \"tool\" %}\n {%- if loop.first or (messages[loop.index0 - 1].role != \"tool\") %}\n {{- '<|im_start|>user' }}\n {%- endif %}\n {{- '\\n<tool_response>\\n' }}\n {{- content }}\n {{- '\\n</tool_response>' }}\n {%- if loop.last or (messages[loop.index0 + 1].role != \"tool\") %}\n {{- '<|im_end|>\\n' }}\n {%- endif %}\n {%- endif %}\n{%- endfor %}\n{%- if add_generation_prompt %}\n {{- '<|im_start|>assistant\\n' }}\n{%- endif %}",
230
+ "clean_up_tokenization_spaces": false,
231
+ "eos_token": "<|im_end|>",
232
+ "errors": "replace",
233
+ "model_max_length": 1010000,
234
+ "pad_token": "<|endoftext|>",
235
+ "split_special_tokens": false,
236
+ "tokenizer_class": "Qwen2Tokenizer",
237
+ "unk_token": null,
238
+ "add_bos_token": false
239
+ }
vocab.json ADDED
The diff for this file is too large to render. See raw diff