IvanHU commited on
Commit
faddcb8
·
verified ·
1 Parent(s): ab2996a

Upload v3_1_ear_moehybrid_bailing_e256_top8_swiglu7_finallogit30_eprobe (iter 11920)

Browse files
v3_1_ear_moehybrid_bailing_e256_top8_swiglu7_finallogit30_eprobe/config.json ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "Qwen3NextForCausalLM"
4
+ ],
5
+ "attention_bias": false,
6
+ "attention_dropout": 0.0,
7
+ "attn_output_gate": false,
8
+ "auto_map": {
9
+ "AutoConfig": "configuration_qwen3_next.Qwen3NextConfig",
10
+ "AutoModel": "modeling_qwen3_next.Qwen3NextForCausalLM",
11
+ "AutoModelForCausalLM": "modeling_qwen3_next.Qwen3NextForCausalLM"
12
+ },
13
+ "bos_token_id": 1,
14
+ "decoder_sparse_step": 1,
15
+ "dtype": "float32",
16
+ "enable_qk_norm": true,
17
+ "eos_token_id": 2,
18
+ "full_attention_interval": 0,
19
+ "head_dim": 128,
20
+ "hidden_act": "silu",
21
+ "hidden_size": 2048,
22
+ "initializer_range": 0.02,
23
+ "intermediate_size": 5120,
24
+ "layer_types": ["full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention"],
25
+ "linear_conv_kernel_dim": 4,
26
+ "linear_key_head_dim": 128,
27
+ "linear_num_key_heads": 4,
28
+ "linear_num_value_heads": 16,
29
+ "linear_value_head_dim": 128,
30
+ "max_position_embeddings": 32768,
31
+ "mlp_only_layers": [0],
32
+ "num_experts_per_tok": 8,
33
+ "num_experts": 256,
34
+ "model_type": "qwen3_next",
35
+ "moe_intermediate_size": 512,
36
+ "norm_topk_prob": true,
37
+ "moe_router_pre_softmax": false,
38
+ "num_attention_heads": 16,
39
+ "num_hidden_layers": 20,
40
+ "num_key_value_heads": 4,
41
+ "output_router_logits": false,
42
+ "partial_rotary_factor": 1.0,
43
+ "rms_norm_eps": 1e-06,
44
+ "rope_scaling": null,
45
+ "rope_theta": 640000,
46
+ "router_aux_loss_coef": 0.001,
47
+ "router_bias": false,
48
+ "moe_router_score_function": "softmax",
49
+ "moe_router_use_topk_scores_as_probs": false,
50
+ "use_weight_aware_router": true,
51
+ "moe_router_add_static_router": true,
52
+ "moe_router_add_static_weight": true,
53
+ "moe_router_gate_up_interaction": false,
54
+ "moe_router_per_expert_probe": true,
55
+ "moe_router_ear_normalize": false,
56
+ "moe_router_ear_normalize_tau": 1.0,
57
+ "moe_router_use_channel_beta": false,
58
+ "moe_router_grad_mode": "end2end",
59
+ "moe_router_probe_init": "mean",
60
+ "moe_expert_output_norm": false,
61
+ "shared_expert_intermediate_size": 512,
62
+ "use_shared_expert_gate": false,
63
+ "tie_word_embeddings": false,
64
+ "transformers_version": "4.57.1",
65
+ "use_cache": true,
66
+ "use_sliding_window": false,
67
+ "ffn_token_shift": null,
68
+ "ffn_intermediate_token_shift": null,
69
+ "attn_token_shift": null,
70
+ "attn_q_token_shift": null,
71
+ "attn_k_token_shift": null,
72
+ "attn_v_token_shift": null,
73
+ "token_shift_conv_size": 4,
74
+ "token_shift_conv_init": "default",
75
+ "attn_position_embedding_type": "rope",
76
+ "rnn_position_embedding_type": "nope",
77
+ "attn_logits_scaling": null,
78
+ "vocab_size": 99000
79
+ }
v3_1_ear_moehybrid_bailing_e256_top8_swiglu7_finallogit30_eprobe/configuration_qwen3_next.py ADDED
@@ -0,0 +1,347 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2025 The Qwen team, Alibaba Group and the HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """Qwen3-Next model configuration"""
16
+
17
+ from transformers.configuration_utils import PretrainedConfig, layer_type_validation
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 Qwen3NextConfig(PretrainedConfig):
26
+ r"""
27
+ This is the configuration class to store the configuration of a [`Qwen3NextModel`]. It is used to instantiate a
28
+ Qwen3-Next model according to the specified arguments, defining the model architecture.
29
+ Instantiating a configuration with the defaults will yield a similar configuration to that of
30
+ Qwen3-Next-80B-A3B-Instruct [Qwen/Qwen3-Next-80B-A3B-Instruct](https://huggingface.co/Qwen/Qwen3-Next-80B-A3B-Instruct).
31
+
32
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
33
+ documentation from [`PretrainedConfig`] for more information.
34
+
35
+
36
+ Args:
37
+ vocab_size (`int`, *optional*, defaults to 151936):
38
+ Vocabulary size of the model. Defines the number of different tokens that can be represented by the
39
+ `inputs_ids`.
40
+ hidden_size (`int`, *optional*, defaults to 2048):
41
+ Dimension of the hidden representations.
42
+ intermediate_size (`int`, *optional*, defaults to 5632):
43
+ Dimension of the MLP representations.
44
+ num_hidden_layers (`int`, *optional*, defaults to 48):
45
+ Number of hidden layers in the Transformer encoder.
46
+ num_attention_heads (`int`, *optional*, defaults to 16):
47
+ Number of attention heads for each attention layer in the Transformer encoder.
48
+ num_key_value_heads (`int`, *optional*, defaults to 2):
49
+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If
50
+ `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
51
+ `num_key_value_heads=1` the model will use Multi Query Attention (MQA) otherwise GQA is used. When
52
+ converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
53
+ by meanpooling all the original heads within that group. For more details checkout [this
54
+ paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to `32`.
55
+ hidden_act (`str`, *optional*, defaults to `"silu"`):
56
+ The non-linear activation function in the decoder.
57
+ max_position_embeddings (`int`, *optional*, defaults to 32768):
58
+ The maximum sequence length that this model might ever be used with.
59
+ initializer_range (`float`, *optional*, defaults to 0.02):
60
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
61
+ rms_norm_eps (`float`, *optional*, defaults to 1e-06):
62
+ The epsilon used by the rms normalization layers.
63
+ use_cache (`bool`, *optional*, defaults to `True`):
64
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
65
+ relevant if `config.is_decoder=True`.
66
+ tie_word_embeddings (`bool`, *optional*, defaults to `False`):
67
+ Whether the model's input and output word embeddings should be tied.
68
+ rope_theta (`float`, *optional*, defaults to 10000.0):
69
+ The base period of the RoPE embeddings.
70
+ rope_scaling (`Dict`, *optional*):
71
+ Dictionary containing the scaling configuration for the RoPE embeddings. NOTE: if you apply new rope type
72
+ and you expect the model to work on longer `max_position_embeddings`, we recommend you to update this value
73
+ accordingly.
74
+ Expected contents:
75
+ `rope_type` (`str`):
76
+ The sub-variant of RoPE to use. Can be one of ['default', 'linear', 'dynamic', 'yarn', 'longrope',
77
+ 'llama3'], with 'default' being the original RoPE implementation.
78
+ `factor` (`float`, *optional*):
79
+ Used with all rope types except 'default'. The scaling factor to apply to the RoPE embeddings. In
80
+ most scaling types, a `factor` of x will enable the model to handle sequences of length x *
81
+ original maximum pre-trained length.
82
+ `original_max_position_embeddings` (`int`, *optional*):
83
+ Used with 'dynamic', 'longrope' and 'llama3'. The original max position embeddings used during
84
+ pretraining.
85
+ `attention_factor` (`float`, *optional*):
86
+ Used with 'yarn' and 'longrope'. The scaling factor to be applied on the attention
87
+ computation. If unspecified, it defaults to value recommended by the implementation, using the
88
+ `factor` field to infer the suggested value.
89
+ `beta_fast` (`float`, *optional*):
90
+ Only used with 'yarn'. Parameter to set the boundary for extrapolation (only) in the linear
91
+ ramp function. If unspecified, it defaults to 32.
92
+ `beta_slow` (`float`, *optional*):
93
+ Only used with 'yarn'. Parameter to set the boundary for interpolation (only) in the linear
94
+ ramp function. If unspecified, it defaults to 1.
95
+ `short_factor` (`List[float]`, *optional*):
96
+ Only used with 'longrope'. The scaling factor to be applied to short contexts (<
97
+ `original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
98
+ size divided by the number of attention heads divided by 2
99
+ `long_factor` (`List[float]`, *optional*):
100
+ Only used with 'longrope'. The scaling factor to be applied to long contexts (<
101
+ `original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
102
+ size divided by the number of attention heads divided by 2
103
+ `low_freq_factor` (`float`, *optional*):
104
+ Only used with 'llama3'. Scaling factor applied to low frequency components of the RoPE
105
+ `high_freq_factor` (`float`, *optional*):
106
+ Only used with 'llama3'. Scaling factor applied to high frequency components of the RoPE
107
+ partial_rotary_factor (`float`, *optional*, defaults to 0.25):
108
+ Percentage of the query and keys which will have rotary embedding.
109
+ attention_bias (`bool`, *optional*, defaults to `False`):
110
+ Whether to use a bias in the query, key, value and output projection layers during self-attention.
111
+ attention_dropout (`float`, *optional*, defaults to 0.0):
112
+ The dropout ratio for the attention probabilities.
113
+ head_dim (`int`, *optional*, defaults to 256):
114
+ Projection weights dimension in multi-head attention.
115
+ linear_conv_kernel_dim (`int`, *optional*, defaults to 4):
116
+ Kernel size of the convolution used in linear attention layers.
117
+ linear_key_head_dim (`int`, *optional*, defaults to 128):
118
+ Dimension of each key head in linear attention.
119
+ linear_value_head_dim (`int`, *optional*, defaults to 128):
120
+ Dimension of each value head in linear attention.
121
+ linear_num_key_heads (`int`, *optional*, defaults to 16):
122
+ Number of key heads used in linear attention layers.
123
+ linear_num_value_heads (`int`, *optional*, defaults to 32):
124
+ Number of value heads used in linear attention layers.
125
+ decoder_sparse_step (`int`, *optional*, defaults to 1):
126
+ The frequency of the MoE layer.
127
+ moe_intermediate_size (`int`, *optional*, defaults to 512):
128
+ Intermediate size of the routed expert.
129
+ shared_expert_intermediate_size (`int`, *optional*, defaults to 512):
130
+ Intermediate size of the shared expert.
131
+ num_experts_per_tok (`int`, *optional*, defaults to 10):
132
+ Number of selected experts.
133
+ num_experts (`int`, *optional*, defaults to 512):
134
+ Number of routed experts.
135
+ norm_topk_prob (`bool`, *optional*, defaults to `True`):
136
+ Whether to normalize the topk probabilities.
137
+ output_router_logits (`bool`, *optional*, defaults to `False`):
138
+ Whether or not the router logits should be returned by the model. Enabling this will also
139
+ allow the model to output the auxiliary loss, including load balancing loss and router z-loss.
140
+ router_aux_loss_coef (`float`, *optional*, defaults to 0.001):
141
+ The aux loss factor for the total loss.
142
+ mlp_only_layers (`list[int]`, *optional*, defaults to `[]`):
143
+ Indicate which layers use Qwen3NextMLP rather than Qwen3NextSparseMoeBlock
144
+ The list contains layer index, from 0 to num_layers-1 if we have num_layers layers
145
+ If `mlp_only_layers` is empty, `decoder_sparse_step` is used to determine the sparsity.
146
+ layer_types (`list[str]`, *optional*):
147
+ Types of each layer (attention or linear).
148
+ enable_qk_norm (`bool`, *optional*, defaults to `False`):
149
+ Whether to apply L2 normalization to the query and key embeddings.
150
+ router_bias (`bool`, *optional*, defaults to `False`):
151
+ Whether to use a bias in the router logits.
152
+ moe_router_score_function (`str`, *optional*, defaults to `"softmax"`):
153
+ The score function used in the MoE router.
154
+ moe_router_pre_softmax (`bool`, *optional*, defaults to `False`):
155
+ Whether to apply the router score function before top-k expert selection.
156
+ ffn_token_shift (`str`, *optional*): Token shift before FFN/MoE. `None`, `"cat"`, or `"conv"`.
157
+ ffn_intermediate_token_shift (`str`, *optional*): Token shift in MLP before down_proj. `None`, `"cat"`, or `"conv"`.
158
+ attn_token_shift (`str`, *optional*): Token shift before attention. `None`, `"cat"`, or `"conv"`.
159
+ attn_q_token_shift (`str`, *optional*): Token shift on query after projection. `None`, `"cat"`, or `"conv"`.
160
+ attn_k_token_shift (`str`, *optional*): Token shift on key after projection. `None`, `"cat"`, or `"conv"`.
161
+ attn_v_token_shift (`str`, *optional*): Token shift on value after projection. `None`, `"cat"`, or `"conv"`.
162
+ token_shift_conv_size (`int`, *optional*, defaults to 4): Kernel size for token-shift Conv1d.
163
+ token_shift_conv_init (`str`, *optional*, defaults to `"default"`): Init for token-shift Conv1d; `"identity"` for causal identity.
164
+ ```python
165
+ >>> from transformers import Qwen3NextModel, Qwen3NextConfig
166
+
167
+ >>> # Initializing a Qwen3Next style configuration
168
+ >>> configuration = Qwen3NextConfig()
169
+
170
+ >>> # Initializing a model from the Qwen3-Next-80B-A3B style configuration
171
+ >>> model = Qwen3NextModel(configuration)
172
+
173
+ >>> # Accessing the model configuration
174
+ >>> configuration = model.config
175
+ ```
176
+ """
177
+
178
+ model_type = "qwen3_next"
179
+ keys_to_ignore_at_inference = ["past_key_values"]
180
+
181
+ base_model_tp_plan = {
182
+ "layers.*.self_attn.q_proj": "colwise",
183
+ "layers.*.self_attn.k_proj": "colwise",
184
+ "layers.*.self_attn.v_proj": "colwise",
185
+ "layers.*.self_attn.o_proj": "rowwise",
186
+ "layers.*.mlp.experts.*.gate_proj": "colwise",
187
+ "layers.*.mlp.experts.*.up_proj": "colwise",
188
+ "layers.*.mlp.experts.*.down_proj": "rowwise",
189
+ "layers.*.mlp.shared_experts.gate_proj": "colwise",
190
+ "layers.*.mlp.shared_experts.up_proj": "colwise",
191
+ "layers.*.mlp.shared_experts.down_proj": "rowwise",
192
+ "layers.*.mlp.gate_proj": "colwise",
193
+ "layers.*.mlp.up_proj": "colwise",
194
+ "layers.*.mlp.down_proj": "rowwise",
195
+ }
196
+ base_model_pp_plan = {
197
+ "embed_tokens": (["input_ids"], ["inputs_embeds"]),
198
+ "layers": (["hidden_states", "attention_mask"], ["hidden_states"]),
199
+ "norm": (["hidden_states"], ["hidden_states"]),
200
+ }
201
+
202
+ def __init__(
203
+ self,
204
+ vocab_size=151936,
205
+ hidden_size=2048,
206
+ intermediate_size=5632,
207
+ num_hidden_layers=48,
208
+ num_attention_heads=16,
209
+ num_key_value_heads=2,
210
+ hidden_act="silu",
211
+ max_position_embeddings=32768,
212
+ initializer_range=0.02,
213
+ rms_norm_eps=1e-6,
214
+ use_cache=True,
215
+ tie_word_embeddings=False,
216
+ rope_theta=10000.0,
217
+ rope_scaling=None,
218
+ partial_rotary_factor=0.25,
219
+ attention_bias=False,
220
+ attention_dropout=0.0,
221
+ head_dim=256,
222
+ linear_conv_kernel_dim=4,
223
+ linear_key_head_dim=128,
224
+ linear_value_head_dim=128,
225
+ linear_num_key_heads=16,
226
+ linear_num_value_heads=32,
227
+ decoder_sparse_step=1,
228
+ moe_intermediate_size=512,
229
+ shared_expert_intermediate_size=512,
230
+ num_experts_per_tok=10,
231
+ num_experts=512,
232
+ norm_topk_prob=True,
233
+ output_router_logits=False,
234
+ router_aux_loss_coef=0.001,
235
+ mlp_only_layers=[],
236
+ layer_types=None,
237
+ pad_token_id=None,
238
+ bos_token_id=None,
239
+ eos_token_id=None,
240
+ enable_qk_norm=False, # @o2iginal
241
+ router_bias=False, # @o2iginal
242
+ attn_output_gate=False, # @o2iginal
243
+ moe_router_score_function="softmax", # @xcx
244
+ moe_router_pre_softmax=False,
245
+ # Cannon layer / token shifting (align with Megatron) @o2iginal
246
+ ffn_token_shift=None,
247
+ ffn_intermediate_token_shift=None,
248
+ attn_token_shift=None,
249
+ attn_q_token_shift=None,
250
+ attn_k_token_shift=None,
251
+ attn_v_token_shift=None,
252
+ token_shift_conv_size=4,
253
+ token_shift_conv_init="default",
254
+ # Separate RoPE for attention vs linear/RNN (GDN): "rope" or "nope"
255
+ attn_position_embedding_type="rope",
256
+ rnn_position_embedding_type="nope",
257
+ # Optional logits scaling for length extrapolation (attention only): None, float, or "log" / "log <a>"
258
+ attn_logits_scaling=None,
259
+ **kwargs,
260
+ ):
261
+ self.pad_token_id = pad_token_id
262
+ self.bos_token_id = bos_token_id
263
+ self.eos_token_id = eos_token_id
264
+ self.tie_word_embeddings = tie_word_embeddings
265
+ super().__init__(
266
+ pad_token_id=pad_token_id,
267
+ bos_token_id=bos_token_id,
268
+ eos_token_id=eos_token_id,
269
+ tie_word_embeddings=tie_word_embeddings,
270
+ **kwargs,
271
+ )
272
+ assert attn_position_embedding_type in ("rope", "nope"), (
273
+ f"attn_position_embedding_type must be 'rope' or 'nope', got {attn_position_embedding_type}"
274
+ )
275
+ assert rnn_position_embedding_type in ("rope", "nope"), (
276
+ f"rnn_position_embedding_type must be 'rope' or 'nope', got {rnn_position_embedding_type}"
277
+ )
278
+ self.attn_position_embedding_type = attn_position_embedding_type
279
+ self.rnn_position_embedding_type = rnn_position_embedding_type
280
+ self.attn_logits_scaling = attn_logits_scaling
281
+ self.vocab_size = vocab_size
282
+ self.max_position_embeddings = max_position_embeddings
283
+ self.hidden_size = hidden_size
284
+ self.intermediate_size = intermediate_size
285
+ self.num_hidden_layers = num_hidden_layers
286
+ self.num_attention_heads = num_attention_heads
287
+ self.num_key_value_heads = num_key_value_heads
288
+ self.hidden_act = hidden_act
289
+ self.initializer_range = initializer_range
290
+ self.rms_norm_eps = rms_norm_eps
291
+ self.use_cache = use_cache
292
+ self.rope_theta = rope_theta
293
+ self.rope_scaling = rope_scaling
294
+ self.partial_rotary_factor = partial_rotary_factor
295
+ self.attention_bias = attention_bias
296
+ self.attention_dropout = attention_dropout
297
+ self.head_dim = head_dim
298
+ self.rope_parameters = self.standardize_rope_params() if hasattr(self, "standardize_rope_params") else {"rope_type": "default", "rope_theta": rope_theta}
299
+ rope_config_validation(self)
300
+
301
+ self.layer_types = layer_types
302
+ if self.layer_types is None:
303
+ interval_pattern = kwargs.get("full_attention_interval", 4)
304
+ self.layer_types = [
305
+ "linear_attention" if bool((i + 1) % interval_pattern) else "full_attention"
306
+ for i in range(self.num_hidden_layers)
307
+ ]
308
+ layer_type_validation(self.layer_types)
309
+
310
+ # linear attention part
311
+ self.linear_conv_kernel_dim = linear_conv_kernel_dim
312
+ self.linear_key_head_dim = linear_key_head_dim
313
+ self.linear_value_head_dim = linear_value_head_dim
314
+ self.linear_num_key_heads = linear_num_key_heads
315
+ self.linear_num_value_heads = linear_num_value_heads
316
+
317
+ # MoE arguments
318
+ self.decoder_sparse_step = decoder_sparse_step
319
+ self.moe_intermediate_size = moe_intermediate_size
320
+ self.shared_expert_intermediate_size = shared_expert_intermediate_size
321
+ self.num_experts_per_tok = num_experts_per_tok
322
+ self.num_experts = num_experts
323
+ self.norm_topk_prob = norm_topk_prob
324
+ self.output_router_logits = output_router_logits
325
+ self.router_aux_loss_coef = router_aux_loss_coef
326
+ self.mlp_only_layers = mlp_only_layers
327
+ self.enable_qk_norm = enable_qk_norm
328
+ self.router_bias = router_bias
329
+ self.attn_output_gate = attn_output_gate
330
+ self.moe_router_score_function = moe_router_score_function
331
+ self.moe_router_pre_softmax = moe_router_pre_softmax
332
+ self.enable_qk_norm = enable_qk_norm
333
+ self.router_bias = router_bias
334
+ self.attn_output_gate = attn_output_gate
335
+ self.moe_router_score_function = moe_router_score_function
336
+
337
+ # Token shifting (cannon layer): None | "cat" | "conv"
338
+ self.ffn_token_shift = ffn_token_shift
339
+ self.ffn_intermediate_token_shift = ffn_intermediate_token_shift
340
+ self.attn_token_shift = attn_token_shift
341
+ self.attn_q_token_shift = attn_q_token_shift
342
+ self.attn_k_token_shift = attn_k_token_shift
343
+ self.attn_v_token_shift = attn_v_token_shift
344
+ self.token_shift_conv_size = token_shift_conv_size
345
+ self.token_shift_conv_init = token_shift_conv_init
346
+
347
+ __all__ = ["Qwen3NextConfig"]
v3_1_ear_moehybrid_bailing_e256_top8_swiglu7_finallogit30_eprobe/model-00001-of-00004.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ad268e0aa895a764f57a62a7bcc9aea7f37ae62053a8fcaba18999859fcdc6e1
3
+ size 9998490744
v3_1_ear_moehybrid_bailing_e256_top8_swiglu7_finallogit30_eprobe/model-00002-of-00004.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3c809cd0fbdde9f2c9e5675e9b9a3de47ebc7bb6b73c1907408195ba42aaeceb
3
+ size 9999863392
v3_1_ear_moehybrid_bailing_e256_top8_swiglu7_finallogit30_eprobe/model-00003-of-00004.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a7028f89b1bea89128c7c03f0cbd587288744a7b27b27cd4e53add62dc6a6f9c
3
+ size 9993582488
v3_1_ear_moehybrid_bailing_e256_top8_swiglu7_finallogit30_eprobe/model-00004-of-00004.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:798109a14bcb1e3b3eade527a965af0bd96ef713e25fcff761d28698b8437106
3
+ size 2044538080
v3_1_ear_moehybrid_bailing_e256_top8_swiglu7_finallogit30_eprobe/model.safetensors.index.json ADDED
The diff for this file is too large to render. See raw diff
 
v3_1_ear_moehybrid_bailing_e256_top8_swiglu7_finallogit30_eprobe/modeling_qwen3_next.py ADDED
@@ -0,0 +1,1605 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
2
+ # This file was automatically generated from src/transformers/models/qwen3_next/modular_qwen3_next.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_next.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
+ import math
23
+ from typing import Any, Callable, Optional, 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
31
+ from transformers.generation import GenerationMixin
32
+ from transformers.masking_utils import create_causal_mask
33
+ from transformers.modeling_flash_attention_utils import FlashAttentionKwargs
34
+ from transformers.modeling_layers import (
35
+ GradientCheckpointingLayer,
36
+ )
37
+ from transformers.modeling_outputs import MoeCausalLMOutputWithPast, MoeModelOutputWithPast
38
+ from transformers.modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update
39
+ from transformers.modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
40
+ from transformers.processing_utils import Unpack
41
+ from transformers.utils import TransformersKwargs, auto_docstring, can_return_tuple, logging
42
+ from transformers.utils.deprecation import deprecate_kwarg
43
+ try:
44
+ from transformers.utils.output_capturing import OutputRecorder
45
+ except ImportError:
46
+ class OutputRecorder:
47
+ def __init__(self, *args, **kwargs):
48
+ pass
49
+ from transformers.utils.import_utils import (
50
+ is_causal_conv1d_available,
51
+ is_flash_linear_attention_available,
52
+ )
53
+ try:
54
+ from configuration_qwen3_next import Qwen3NextConfig
55
+ except ImportError:
56
+ from .configuration_qwen3_next import Qwen3NextConfig
57
+
58
+ if is_causal_conv1d_available():
59
+ from causal_conv1d import causal_conv1d_fn, causal_conv1d_update
60
+ else:
61
+ causal_conv1d_update, causal_conv1d_fn = None, None
62
+
63
+ if is_flash_linear_attention_available():
64
+ from fla.modules import FusedRMSNormGated
65
+ from fla.ops.gated_delta_rule import chunk_gated_delta_rule, fused_recurrent_gated_delta_rule
66
+ else:
67
+ chunk_gated_delta_rule, fused_recurrent_gated_delta_rule = None, None
68
+ FusedRMSNormGated = None
69
+
70
+ logger = logging.get_logger(__name__)
71
+
72
+ # ANSI colors for console (custom features log)
73
+ _CG = "\033[92m" # green
74
+ _CY = "\033[93m" # yellow
75
+ _CC = "\033[96m" # cyan
76
+ _CR = "\033[0m" # reset
77
+
78
+
79
+ def _log_custom_features(config: Qwen3NextConfig) -> None:
80
+ """Log attn/rnn RoPE and attn_logits_scaling settings (once per model load)."""
81
+ attn_pe = getattr(config, "attn_position_embedding_type", "rope")
82
+ rnn_pe = getattr(config, "rnn_position_embedding_type", "nope")
83
+ logits_scaling = getattr(config, "attn_logits_scaling", None)
84
+ msg = (
85
+ f"{_CG}[Qwen3Next custom]{_CR} "
86
+ f"{_CC}attn_position_embedding_type{_CR}={_CY}{attn_pe}{_CR}, "
87
+ f"{_CC}rnn_position_embedding_type{_CR}={_CY}{rnn_pe}{_CR}, "
88
+ f"{_CC}attn_logits_scaling{_CR}={_CY}{logits_scaling}{_CR}"
89
+ )
90
+ logger.info(msg)
91
+
92
+
93
+ class Qwen3NextRMSNormGated(nn.Module):
94
+ def __init__(self, hidden_size, eps=1e-6, **kwargs):
95
+ super().__init__()
96
+ self.weight = nn.Parameter(torch.ones(hidden_size))
97
+ self.variance_epsilon = eps
98
+
99
+ def forward(self, hidden_states, gate=None):
100
+ input_dtype = hidden_states.dtype
101
+ hidden_states = hidden_states.to(torch.float32)
102
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
103
+ # Norm before gate
104
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
105
+ hidden_states = self.weight * hidden_states.to(input_dtype)
106
+ hidden_states = hidden_states * F.silu(gate.to(torch.float32))
107
+
108
+ return hidden_states.to(input_dtype)
109
+
110
+
111
+ class Qwen3NextDynamicCache:
112
+ """
113
+ A dynamic cache that can handle both the attention cache (which has a seq_len dimension) and the linear attention
114
+ cache (which has a constant shape regardless of seq_len).
115
+
116
+ This cache has two sets of lists of tensors: `key_cache` and `value_cache` for attention cache and `conv_states`
117
+ and `ssm_states` for gated deltanet cache. Each of these lists has `num_layers` tensors. The expected shape for each tensor
118
+ For attention layers, `key_cache` and `value_cache` have a shape of `(batch_size, num_heads, seq_len, head_dim)`,
119
+ while `conv_states` and `ssm_states` have a shape of `(batch_size, 0)` (empty tensors).
120
+ For linear attention layers, `key_cache` and `value_cache` have a shape of `(batch_size, 0)` (empty tensors),
121
+ while `conv_states` represents the convolution state and has a shape of `(batch_size, d_inner, d_conv)`,
122
+ and `recurrent_states` represents the recurrent state and has a shape of `(batch_size, d_inner, d_state)`.
123
+ """
124
+
125
+ is_compileable = False
126
+
127
+ def __init__(self, config: Qwen3NextConfig):
128
+ super().__init__()
129
+ self.layer_types = config.layer_types
130
+ self.transformer_layers = [
131
+ i for i in range(config.num_hidden_layers) if self.layer_types[i] == "full_attention"
132
+ ]
133
+ self.last_linear_layer = len(self.layer_types) - 1 - self.layer_types[::-1].index("linear_attention")
134
+
135
+ # Initialize everything to None -> will be lazy initialized to allow multi-gpu (device_map) inference
136
+ self.conv_states = [None for _ in range(config.num_hidden_layers)]
137
+ self.recurrent_states = [None for _ in range(config.num_hidden_layers)]
138
+ self.key_cache = [None for _ in range(config.num_hidden_layers)]
139
+ self.value_cache = [None for _ in range(config.num_hidden_layers)]
140
+
141
+ def __len__(self):
142
+ return len(self.layer_types)
143
+
144
+ def __getitem__(self, layer_idx: int) -> tuple[torch.Tensor, torch.Tensor]:
145
+ return self.key_cache[layer_idx], self.value_cache[layer_idx]
146
+
147
+ def update(
148
+ self,
149
+ key_states: torch.Tensor,
150
+ value_states: torch.Tensor,
151
+ layer_idx: int,
152
+ cache_kwargs: Optional[dict[str, Any]] = None,
153
+ ) -> tuple[torch.Tensor, torch.Tensor]:
154
+ if self.key_cache[layer_idx] is None:
155
+ self.key_cache[layer_idx] = key_states
156
+ self.value_cache[layer_idx] = value_states
157
+ else:
158
+ self.key_cache[layer_idx] = torch.cat([self.key_cache[layer_idx], key_states], dim=2)
159
+ self.value_cache[layer_idx] = torch.cat([self.value_cache[layer_idx], value_states], dim=2)
160
+
161
+ return self.key_cache[layer_idx], self.value_cache[layer_idx]
162
+
163
+ def reorder_cache(self, beam_idx: torch.LongTensor):
164
+ """Reorders the cache for beam search, given the selected beam indices."""
165
+ for layer_idx in range(len(self.key_cache)):
166
+ if self.key_cache[layer_idx] is not None:
167
+ device = self.key_cache[layer_idx].device
168
+ beam_idx = beam_idx.to(device)
169
+ self.key_cache[layer_idx] = self.key_cache[layer_idx].index_select(0, beam_idx)
170
+ self.value_cache[layer_idx] = self.value_cache[layer_idx].index_select(0, beam_idx)
171
+
172
+ if self.conv_states[layer_idx] is not None:
173
+ device = self.conv_states[layer_idx].device
174
+ beam_idx = beam_idx.to(device)
175
+ self.conv_states[layer_idx] = self.conv_states[layer_idx].index_select(0, beam_idx)
176
+ self.recurrent_states[layer_idx] = self.recurrent_states[layer_idx].index_select(0, beam_idx)
177
+
178
+ def get_seq_length(self, layer_idx: Optional[int] = 0) -> int:
179
+ """Returns the sequence length of the cached states. A layer index can be optionally passed."""
180
+ # take any layer that contains cache and not empty tensor
181
+ layer_idx = self.transformer_layers[0] if layer_idx not in self.transformer_layers else layer_idx
182
+ if len(self.key_cache) <= layer_idx or self.key_cache[layer_idx] is None:
183
+ return 0
184
+ return self.key_cache[layer_idx].shape[-2]
185
+
186
+ def get_mask_sizes(self, cache_position: torch.Tensor, layer_idx: int) -> tuple[int, int]:
187
+ """
188
+ Return a tuple (kv_length, kv_offset) corresponding to the length and offset that will be returned for
189
+ the given layer at `layer_idx`.
190
+ The masks are then prepared according to the given lengths (kv_length, kv_offset) and patterns for each layer.
191
+ """
192
+ kv_offset = 0
193
+ query_length = cache_position.shape[0]
194
+ past_seen_tokens = self.get_seq_length(layer_idx)
195
+ kv_length = query_length + past_seen_tokens
196
+ return kv_length, kv_offset
197
+
198
+ @property
199
+ def has_previous_state(self):
200
+ """We have a previous state if the last linear (conv) layer was already updated."""
201
+ return self.conv_states[self.last_linear_layer] is not None
202
+
203
+
204
+ class Qwen3NextRotaryEmbedding(nn.Module):
205
+ inv_freq: torch.Tensor # fix linting for `register_buffer`
206
+
207
+ def __init__(self, config: Qwen3NextConfig, device=None):
208
+ super().__init__()
209
+ self.max_seq_len_cached = config.max_position_embeddings
210
+ self.original_max_seq_len = config.max_position_embeddings
211
+
212
+ self.config = config
213
+ rope_parameters = getattr(self.config, "rope_parameters", None)
214
+ if rope_parameters is None:
215
+ rope_parameters = self._build_rope_parameters_from_legacy_config(self.config)
216
+ self.rope_type = rope_parameters.get("rope_type", "default")
217
+ rope_init_fn = self.compute_default_rope_parameters
218
+ if self.rope_type != "default":
219
+ rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
220
+
221
+ inv_freq, self.attention_scaling = rope_init_fn(self.config, device)
222
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
223
+ self.original_inv_freq = self.inv_freq
224
+
225
+ @staticmethod
226
+ def _build_rope_parameters_from_legacy_config(config: Qwen3NextConfig) -> dict[str, Any]:
227
+ rope_parameters = {
228
+ "rope_type": "default",
229
+ "rope_theta": getattr(config, "rope_theta", 10000.0),
230
+ "partial_rotary_factor": getattr(config, "partial_rotary_factor", 1.0),
231
+ }
232
+ rope_scaling = getattr(config, "rope_scaling", None)
233
+ if isinstance(rope_scaling, dict):
234
+ rope_parameters.update(rope_scaling)
235
+ rope_parameters["rope_type"] = rope_scaling.get("rope_type", rope_scaling.get("type", "default"))
236
+ return rope_parameters
237
+
238
+ @staticmethod
239
+ def compute_default_rope_parameters(
240
+ config: Optional[Qwen3NextConfig] = None,
241
+ device=None,
242
+ seq_len: Optional[int] = None,
243
+ ):
244
+ del seq_len
245
+ rope_parameters = getattr(config, "rope_parameters", None)
246
+ if rope_parameters is None:
247
+ rope_parameters = Qwen3NextRotaryEmbedding._build_rope_parameters_from_legacy_config(config)
248
+
249
+ base = rope_parameters["rope_theta"]
250
+ partial_rotary_factor = rope_parameters.get("partial_rotary_factor", 1.0)
251
+ head_dim = getattr(config, "head_dim", None) or config.hidden_size // config.num_attention_heads
252
+ dim = int(head_dim * partial_rotary_factor)
253
+ attention_factor = 1.0
254
+
255
+ inv_freq = 1.0 / (
256
+ base ** (torch.arange(0, dim, 2, dtype=torch.int64).to(device=device, dtype=torch.float) / dim)
257
+ )
258
+ return inv_freq, attention_factor
259
+
260
+ @torch.no_grad()
261
+ @dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope)
262
+ def forward(self, x, position_ids):
263
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device)
264
+ position_ids_expanded = position_ids[:, None, :].float()
265
+
266
+ device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
267
+ with torch.autocast(device_type=device_type, enabled=False): # Force float32
268
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
269
+ emb = torch.cat((freqs, freqs), dim=-1)
270
+ cos = emb.cos() * self.attention_scaling
271
+ sin = emb.sin() * self.attention_scaling
272
+
273
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
274
+
275
+
276
+ class Qwen3NextRMSNorm(nn.Module):
277
+ def __init__(self, dim: int, eps: float = 1e-6):
278
+ super().__init__()
279
+ self.eps = eps
280
+ self.weight = nn.Parameter(torch.zeros(dim))
281
+
282
+ def _norm(self, x):
283
+ return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)
284
+
285
+ def forward(self, x):
286
+ output = self._norm(x.float())
287
+ # Llama does x.to(float16) * w whilst Qwen3Next is (x * w).to(float16)
288
+ # See https://github.com/huggingface/transformers/pull/29402
289
+ output = output * (1.0 + self.weight.float())
290
+ return output.type_as(x)
291
+
292
+ def extra_repr(self):
293
+ return f"{tuple(self.weight.shape)}, eps={self.eps}"
294
+
295
+
296
+ class LlamaRMSNorm(nn.Module): # Copy from Llama
297
+ def __init__(self, hidden_size, eps=1e-6):
298
+ super().__init__()
299
+ self.weight = nn.Parameter(torch.ones(hidden_size))
300
+ self.variance_epsilon = eps
301
+
302
+ def forward(self, hidden_states):
303
+ input_dtype = hidden_states.dtype
304
+ hidden_states = hidden_states.to(torch.float32)
305
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
306
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
307
+ return self.weight * hidden_states.to(input_dtype)
308
+
309
+
310
+ def rotate_half(x):
311
+ """Rotates half the hidden dims of the input."""
312
+ x1 = x[..., : x.shape[-1] // 2]
313
+ x2 = x[..., x.shape[-1] // 2 :]
314
+ return torch.cat((-x2, x1), dim=-1)
315
+
316
+
317
+ # Adapted from transformers.models.glm.modular_glm.apply_rotary_pos_emb
318
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
319
+ """Applies Rotary Position Embedding to the query and key tensors.
320
+
321
+ Removes the interleaving of cos and sin from GLM
322
+
323
+ Args:
324
+ q (`torch.Tensor`): The query tensor.
325
+ k (`torch.Tensor`): The key tensor.
326
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
327
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
328
+ position_ids (`torch.Tensor`, *optional*):
329
+ Deprecated and unused.
330
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
331
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
332
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
333
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
334
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
335
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
336
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
337
+ Returns:
338
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
339
+ """
340
+ cos = cos.unsqueeze(unsqueeze_dim)
341
+ sin = sin.unsqueeze(unsqueeze_dim)
342
+
343
+ # Keep half or full tensor for later concatenation
344
+ rotary_dim = cos.shape[-1]
345
+ q_rot, q_pass = q[..., :rotary_dim], q[..., rotary_dim:]
346
+ k_rot, k_pass = k[..., :rotary_dim], k[..., rotary_dim:]
347
+
348
+ # Apply rotary embeddings on the first half or full tensor
349
+ q_embed = (q_rot * cos) + (rotate_half(q_rot) * sin)
350
+ k_embed = (k_rot * cos) + (rotate_half(k_rot) * sin)
351
+
352
+ # Concatenate back to full shape
353
+ q_embed = torch.cat([q_embed, q_pass], dim=-1)
354
+ k_embed = torch.cat([k_embed, k_pass], dim=-1)
355
+ return q_embed, k_embed
356
+
357
+
358
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
359
+ """
360
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
361
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
362
+ """
363
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
364
+ if n_rep == 1:
365
+ return hidden_states
366
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
367
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
368
+
369
+
370
+ def eager_attention_forward(
371
+ module: nn.Module,
372
+ query: torch.Tensor,
373
+ key: torch.Tensor,
374
+ value: torch.Tensor,
375
+ attention_mask: Optional[torch.Tensor],
376
+ scaling: float,
377
+ dropout: float = 0.0,
378
+ **kwargs: Unpack[TransformersKwargs],
379
+ ):
380
+ key_states = repeat_kv(key, module.num_key_value_groups)
381
+ value_states = repeat_kv(value, module.num_key_value_groups)
382
+
383
+ attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
384
+ if attention_mask is not None:
385
+ causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
386
+ attn_weights = attn_weights + causal_mask
387
+
388
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
389
+ attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
390
+ attn_output = torch.matmul(attn_weights, value_states)
391
+ attn_output = attn_output.transpose(1, 2).contiguous()
392
+
393
+ return attn_output, attn_weights
394
+
395
+
396
+ class Qwen3NextAttention(nn.Module):
397
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
398
+
399
+ def __init__(self, config: Qwen3NextConfig, layer_idx: int):
400
+ super().__init__()
401
+ self.config = config
402
+ self.layer_idx = layer_idx
403
+ self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
404
+ self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
405
+ self.scaling = self.head_dim**-0.5
406
+ self.attention_dropout = config.attention_dropout
407
+ self.is_causal = True
408
+ self.attn_output_gate = config.attn_output_gate
409
+ self.q_proj = nn.Linear(
410
+ config.hidden_size, config.num_attention_heads * self.head_dim * (1 + self.attn_output_gate), bias=config.attention_bias
411
+ )
412
+ self.k_proj = nn.Linear(
413
+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
414
+ )
415
+ self.v_proj = nn.Linear(
416
+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
417
+ )
418
+ self.o_proj = nn.Linear(
419
+ config.num_attention_heads * self.head_dim, config.hidden_size, bias=False
420
+ )
421
+ self.enable_qk_norm = config.enable_qk_norm
422
+ if self.enable_qk_norm:
423
+ self.q_norm = Qwen3NextRMSNorm(self.head_dim, eps=config.rms_norm_eps) # unlike olmo, only on the head dim!
424
+ self.k_norm = Qwen3NextRMSNorm(self.head_dim, eps=config.rms_norm_eps) # thus post q_norm does not need reshape
425
+ else:
426
+ self.q_norm = None
427
+ self.k_norm = None
428
+
429
+ # Separate RoPE for attention: "rope" or "nope" (no RoPE)
430
+ self.attn_position_embedding_type = getattr(config, "attn_position_embedding_type", "rope")
431
+ # Optional logits scaling for length extrapolation: None, float, or "log" / "log <a>"
432
+ self.attn_logits_scaling = getattr(config, "attn_logits_scaling", None)
433
+
434
+ # Token shift on Q/K/V after projection (cannon layer, conv mode); per-head conv (head_dim, 1, kernel_size)
435
+ kernel_size = getattr(config, "token_shift_conv_size", 4)
436
+ self.attn_q_token_shift = getattr(config, "attn_q_token_shift", None)
437
+ self.attn_k_token_shift = getattr(config, "attn_k_token_shift", None)
438
+ self.attn_v_token_shift = getattr(config, "attn_v_token_shift", None)
439
+ if self.attn_q_token_shift == "conv":
440
+ self.q_token_shift_conv = nn.Conv1d(
441
+ self.head_dim,
442
+ self.head_dim,
443
+ kernel_size=kernel_size,
444
+ padding=0,
445
+ groups=self.head_dim,
446
+ bias=False,
447
+ )
448
+ else:
449
+ self.q_token_shift_conv = None
450
+ if self.attn_k_token_shift == "conv":
451
+ self.k_token_shift_conv = nn.Conv1d(
452
+ self.head_dim,
453
+ self.head_dim,
454
+ kernel_size=kernel_size,
455
+ padding=0,
456
+ groups=self.head_dim,
457
+ bias=False,
458
+ )
459
+ else:
460
+ self.k_token_shift_conv = None
461
+ if self.attn_v_token_shift == "conv":
462
+ self.v_token_shift_conv = nn.Conv1d(
463
+ self.head_dim,
464
+ self.head_dim,
465
+ kernel_size=kernel_size,
466
+ padding=0,
467
+ groups=self.head_dim,
468
+ bias=False,
469
+ )
470
+ else:
471
+ self.v_token_shift_conv = None
472
+
473
+ @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
474
+ def forward(
475
+ self,
476
+ hidden_states: torch.Tensor,
477
+ position_embeddings: tuple[torch.Tensor, torch.Tensor],
478
+ attention_mask: Optional[torch.Tensor],
479
+ past_key_values: Optional[Cache] = None,
480
+ cache_position: Optional[torch.LongTensor] = None,
481
+ **kwargs: Unpack[FlashAttentionKwargs],
482
+ ) -> tuple[torch.Tensor, Optional[torch.Tensor]]:
483
+ input_shape = hidden_states.shape[:-1]
484
+ hidden_shape = (*input_shape, -1, self.head_dim)
485
+
486
+ if self.attn_output_gate:
487
+ query_states, gate = torch.chunk(
488
+ self.q_proj(hidden_states).view(*input_shape, -1, self.head_dim * 2), 2, dim=-1
489
+ )
490
+ gate = gate.reshape(*input_shape, -1)
491
+ else:
492
+ query_states = self.q_proj(hidden_states).view(*input_shape, -1, self.head_dim)
493
+ gate = None
494
+
495
+ if self.enable_qk_norm:
496
+ query_states = self.q_norm(query_states.view(hidden_shape)).transpose(1, 2)
497
+ key_states = self.k_norm(self.k_proj(hidden_states).view(hidden_shape)).transpose(1, 2)
498
+ else:
499
+ query_states = query_states.view(hidden_shape).transpose(1, 2)
500
+ key_states = self.k_proj(hidden_states).view(hidden_shape).transpose(1, 2)
501
+
502
+ value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
503
+
504
+ # Token shift on Q/K/V (cannon layer, conv mode): [batch, heads, seq, head_dim] -> [batch*heads, head_dim, seq]
505
+ if self.attn_q_token_shift == "conv" and self.q_token_shift_conv is not None:
506
+ b, nh, sq, hn = query_states.shape
507
+ q_bcl = query_states.reshape(b * nh, hn, sq)
508
+ q_bcl = apply_causal_depthwise_conv1d_bcl(q_bcl, self.q_token_shift_conv.weight)
509
+ query_states = q_bcl.reshape(b, nh, hn, sq).permute(0, 1, 3, 2).contiguous()
510
+ if self.attn_k_token_shift == "conv" and self.k_token_shift_conv is not None:
511
+ b, ng, sq, hn = key_states.shape
512
+ k_bcl = key_states.reshape(b * ng, hn, sq)
513
+ k_bcl = apply_causal_depthwise_conv1d_bcl(k_bcl, self.k_token_shift_conv.weight)
514
+ key_states = k_bcl.reshape(b, ng, hn, sq).permute(0, 1, 3, 2).contiguous()
515
+ if self.attn_v_token_shift == "conv" and self.v_token_shift_conv is not None:
516
+ b, ng, sq, hn = value_states.shape
517
+ v_bcl = value_states.reshape(b * ng, hn, sq)
518
+ v_bcl = apply_causal_depthwise_conv1d_bcl(v_bcl, self.v_token_shift_conv.weight)
519
+ value_states = v_bcl.reshape(b, ng, hn, sq).permute(0, 1, 3, 2).contiguous()
520
+
521
+ cos, sin = position_embeddings
522
+ if self.attn_position_embedding_type == "rope":
523
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
524
+ # when "nope", do not apply RoPE
525
+
526
+ if past_key_values is not None:
527
+ # sin and cos are specific to RoPE models; cache_position needed for the static cache
528
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
529
+ key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx, cache_kwargs)
530
+
531
+ # Optional logits scaling for length extrapolation (before attention, same as FLA)
532
+ if self.attn_logits_scaling is not None:
533
+ if isinstance(self.attn_logits_scaling, (int, float)):
534
+ query_states = query_states * float(self.attn_logits_scaling)
535
+ elif isinstance(self.attn_logits_scaling, str):
536
+ position_ids = kwargs.get("position_ids")
537
+ if position_ids is None:
538
+ batch_size, num_heads, seq_len, _ = query_states.shape
539
+ position_ids = torch.arange(
540
+ seq_len, device=query_states.device, dtype=torch.long
541
+ ).unsqueeze(0).expand(batch_size, -1)
542
+ logger.warning_once(
543
+ "attn_logits_scaling uses position-dependent scaling but position_ids was not passed; "
544
+ "using arange(0, seq_len). Pass position_ids for correct behavior with padding."
545
+ )
546
+ parts = self.attn_logits_scaling.split()
547
+ a = float(parts[1]) if len(parts) > 1 else 362.0
548
+ position_ids_f = position_ids.to(device=query_states.device, dtype=torch.float32)
549
+ scale = (torch.log(position_ids_f + a) / math.log(a)).to(query_states.dtype)
550
+ # query_states: (B, H, T, D); scale: (B, T) -> broadcast
551
+ query_states = query_states * scale.unsqueeze(1).unsqueeze(-1)
552
+ else:
553
+ raise TypeError(
554
+ f"attn_logits_scaling must be float, str or None, got {type(self.attn_logits_scaling)}"
555
+ )
556
+
557
+ attention_interface: Callable = eager_attention_forward
558
+ if self.config._attn_implementation != "eager":
559
+ attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
560
+
561
+ attn_output, attn_weights = attention_interface(
562
+ self,
563
+ query_states,
564
+ key_states,
565
+ value_states,
566
+ attention_mask,
567
+ dropout=0.0 if not self.training else self.attention_dropout,
568
+ scaling=self.scaling,
569
+ **kwargs,
570
+ )
571
+
572
+ if self.attn_output_gate:
573
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
574
+ attn_output = attn_output * torch.sigmoid(gate)
575
+ else:
576
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
577
+
578
+ attn_output = self.o_proj(attn_output)
579
+ return attn_output, attn_weights
580
+
581
+
582
+ def apply_mask_to_padding_states(hidden_states, attention_mask):
583
+ """
584
+ Tunes out the hidden states for padding tokens, see https://github.com/state-spaces/mamba/issues/66
585
+ """
586
+ if attention_mask is not None and attention_mask.shape[1] > 1 and attention_mask.shape[0] > 1:
587
+ dtype = hidden_states.dtype
588
+ hidden_states = (hidden_states * attention_mask[:, :, None]).to(dtype)
589
+
590
+ return hidden_states
591
+
592
+
593
+ is_fast_path_available = all(
594
+ (causal_conv1d_fn, causal_conv1d_update, chunk_gated_delta_rule, fused_recurrent_gated_delta_rule)
595
+ )
596
+
597
+
598
+ def torch_causal_conv1d_update(
599
+ hidden_states,
600
+ conv_state,
601
+ weight,
602
+ bias=None,
603
+ activation=None,
604
+ ):
605
+ _, hidden_size, seq_len = hidden_states.shape
606
+ state_len = conv_state.shape[-1]
607
+
608
+ hidden_states_new = torch.cat([conv_state, hidden_states], dim=-1).to(weight.dtype)
609
+ conv_state.copy_(hidden_states_new[:, :, -state_len:])
610
+ out = F.conv1d(hidden_states_new, weight.unsqueeze(1), bias, padding=0, groups=hidden_size)
611
+ out = F.silu(out[:, :, -seq_len:])
612
+ out = out.to(hidden_states.dtype)
613
+ return out
614
+
615
+
616
+ def apply_causal_depthwise_conv1d_bcl(
617
+ x_bcl: torch.Tensor,
618
+ weight_c1w: torch.Tensor,
619
+ ) -> torch.Tensor:
620
+ """Apply causal depthwise Conv1d for token shifting. Aligns with Megatron cannon layer.
621
+
622
+ x_bcl: [B, C, L], weight_c1w: [C, 1, W]. Output: [B, C, L].
623
+ """
624
+ if causal_conv1d_fn is not None:
625
+ return causal_conv1d_fn(
626
+ x=x_bcl,
627
+ weight=weight_c1w.squeeze(1),
628
+ bias=None,
629
+ activation=None,
630
+ )
631
+ w = weight_c1w.shape[-1]
632
+ x_pad = F.pad(x_bcl, (w - 1, 0))
633
+ y = F.conv1d(
634
+ x_pad,
635
+ weight_c1w,
636
+ bias=None,
637
+ stride=1,
638
+ padding=0,
639
+ groups=weight_c1w.shape[0],
640
+ )
641
+ return y[..., : x_bcl.shape[-1]]
642
+
643
+
644
+ def l2norm(x: torch.FloatTensor, dim: int = -1, eps: float = 1e-6):
645
+ """This function is intended to align with the l2norm implementation in the FLA library."""
646
+ inv_norm = 1 / torch.sqrt((x * x).sum(dim=dim, keepdim=True) + eps)
647
+ return x * inv_norm
648
+
649
+
650
+ def torch_chunk_gated_delta_rule(
651
+ query,
652
+ key,
653
+ value,
654
+ g,
655
+ beta,
656
+ chunk_size=64,
657
+ initial_state=None,
658
+ output_final_state=False,
659
+ use_qk_l2norm_in_kernel=False,
660
+ ):
661
+ initial_dtype = query.dtype
662
+ if use_qk_l2norm_in_kernel:
663
+ query = l2norm(query, dim=-1, eps=1e-6)
664
+ key = l2norm(key, dim=-1, eps=1e-6)
665
+ query, key, value, beta, g = [
666
+ x.transpose(1, 2).contiguous().to(torch.float32) for x in (query, key, value, beta, g)
667
+ ]
668
+
669
+ batch_size, sequence_length, num_heads, k_head_dim = key.shape
670
+ v_head_dim = value.shape[-1]
671
+ pad_size = (chunk_size - num_heads % chunk_size) % chunk_size
672
+ query = F.pad(query, (0, 0, 0, pad_size))
673
+ key = F.pad(key, (0, 0, 0, pad_size))
674
+ value = F.pad(value, (0, 0, 0, pad_size))
675
+ beta = F.pad(beta, (0, pad_size))
676
+ g = F.pad(g, (0, pad_size))
677
+ tot_heads = num_heads + pad_size
678
+ scale = 1 / (query.shape[-1] ** 0.5)
679
+ query = query * scale
680
+
681
+ v_beta = value * beta.unsqueeze(-1)
682
+ k_beta = key * beta.unsqueeze(-1)
683
+ # reshape to chunks
684
+ query, key, value, k_beta, v_beta = [
685
+ x.reshape(x.shape[0], x.shape[1], -1, chunk_size, x.shape[-1]) for x in (query, key, value, k_beta, v_beta)
686
+ ]
687
+ g = g.reshape(g.shape[0], g.shape[1], -1, chunk_size)
688
+ mask = torch.triu(torch.ones(chunk_size, chunk_size, dtype=torch.bool, device=query.device), diagonal=0)
689
+
690
+ # chunk decay
691
+ g = g.cumsum(dim=-1)
692
+ decay_mask = ((g.unsqueeze(-1) - g.unsqueeze(-2)).tril().exp().float()).tril()
693
+ attn = -((k_beta @ key.transpose(-1, -2)) * decay_mask).masked_fill(mask, 0)
694
+ for i in range(1, chunk_size):
695
+ row = attn[..., i, :i].clone()
696
+ sub = attn[..., :i, :i].clone()
697
+ attn[..., i, :i] = row + (row.unsqueeze(-1) * sub).sum(-2)
698
+ attn = attn + torch.eye(chunk_size, dtype=attn.dtype, device=attn.device)
699
+ value = attn @ v_beta
700
+ k_cumdecay = attn @ (k_beta * g.exp().unsqueeze(-1))
701
+ last_recurrent_state = (
702
+ torch.zeros(batch_size, sequence_length, k_head_dim, v_head_dim).to(value)
703
+ if initial_state is None
704
+ else initial_state.to(value)
705
+ )
706
+ core_attn_out = torch.zeros_like(value)
707
+ mask = torch.triu(torch.ones(chunk_size, chunk_size, dtype=torch.bool, device=query.device), diagonal=1)
708
+
709
+ # for each chunk
710
+ for i in range(0, tot_heads // chunk_size):
711
+ q_i, k_i, v_i = query[:, :, i], key[:, :, i], value[:, :, i]
712
+ attn = (q_i @ k_i.transpose(-1, -2) * decay_mask[:, :, i]).masked_fill_(mask, 0)
713
+ v_prime = (k_cumdecay[:, :, i]) @ last_recurrent_state
714
+ v_new = v_i - v_prime
715
+ attn_inter = (q_i * g[:, :, i, :, None].exp()) @ last_recurrent_state
716
+ core_attn_out[:, :, i] = attn_inter + attn @ v_new
717
+ last_recurrent_state = (
718
+ last_recurrent_state * g[:, :, i, -1, None, None].exp()
719
+ + (k_i * (g[:, :, i, -1, None] - g[:, :, i]).exp()[..., None]).transpose(-1, -2) @ v_new
720
+ )
721
+
722
+ if not output_final_state:
723
+ last_recurrent_state = None
724
+ core_attn_out = core_attn_out.reshape(core_attn_out.shape[0], core_attn_out.shape[1], -1, core_attn_out.shape[-1])
725
+ core_attn_out = core_attn_out[:, :, :num_heads]
726
+ core_attn_out = core_attn_out.transpose(1, 2).contiguous().to(initial_dtype)
727
+ return core_attn_out, last_recurrent_state
728
+
729
+
730
+ def torch_recurrent_gated_delta_rule(
731
+ query, key, value, g, beta, initial_state, output_final_state, use_qk_l2norm_in_kernel=False
732
+ ):
733
+ initial_dtype = query.dtype
734
+ if use_qk_l2norm_in_kernel:
735
+ query = l2norm(query, dim=-1, eps=1e-6)
736
+ key = l2norm(key, dim=-1, eps=1e-6)
737
+ query, key, value, beta, g = [
738
+ x.transpose(1, 2).contiguous().to(torch.float32) for x in (query, key, value, beta, g)
739
+ ]
740
+
741
+ batch_size, sequence_length, num_heads, k_head_dim = key.shape
742
+ v_head_dim = value.shape[-1]
743
+ scale = 1 / (query.shape[-1] ** 0.5)
744
+ query = query * scale
745
+
746
+ core_attn_out = torch.zeros(batch_size, sequence_length, num_heads, v_head_dim).to(value)
747
+ last_recurrent_state = (
748
+ torch.zeros(batch_size, sequence_length, k_head_dim, v_head_dim).to(value)
749
+ if initial_state is None
750
+ else initial_state.to(value)
751
+ )
752
+
753
+ for i in range(num_heads):
754
+ q_t = query[:, :, i]
755
+ k_t = key[:, :, i]
756
+ v_t = value[:, :, i]
757
+ g_t = g[:, :, i].exp().unsqueeze(-1).unsqueeze(-1)
758
+ beta_t = beta[:, :, i].unsqueeze(-1)
759
+
760
+ last_recurrent_state = last_recurrent_state * g_t
761
+ kv_mem = (last_recurrent_state * k_t.unsqueeze(-1)).sum(dim=-2)
762
+ delta = (v_t - kv_mem) * beta_t
763
+ last_recurrent_state = last_recurrent_state + k_t.unsqueeze(-1) * delta.unsqueeze(-2)
764
+ core_attn_out[:, :, i] = (last_recurrent_state * q_t.unsqueeze(-1)).sum(dim=-2)
765
+
766
+ if not output_final_state:
767
+ last_recurrent_state = None
768
+ core_attn_out = core_attn_out.transpose(1, 2).contiguous().to(initial_dtype)
769
+ return core_attn_out, last_recurrent_state
770
+
771
+
772
+ class Qwen3NextGatedDeltaNet(nn.Module):
773
+ def __init__(self, config: Qwen3NextConfig, layer_idx: int):
774
+ super().__init__()
775
+ self.hidden_size = config.hidden_size
776
+ self.num_v_heads = config.linear_num_value_heads
777
+ self.num_k_heads = config.linear_num_key_heads
778
+ self.head_k_dim = config.linear_key_head_dim
779
+ self.head_v_dim = config.linear_value_head_dim
780
+ self.key_dim = self.head_k_dim * self.num_k_heads
781
+ self.value_dim = self.head_v_dim * self.num_v_heads
782
+
783
+ self.conv_kernel_size = config.linear_conv_kernel_dim
784
+ self.layer_idx = layer_idx
785
+
786
+ # Optional RoPE for linear/RNN path: "rope" or "nope" (same as FLA rnn_position_embedding_type)
787
+ self.rnn_position_embedding_type = getattr(config, "rnn_position_embedding_type", "nope")
788
+ rope_theta = getattr(config, "rope_theta", 10000.0)
789
+ if self.rnn_position_embedding_type == "rope":
790
+ inv_freq = 1.0 / (
791
+ rope_theta ** (torch.arange(0, self.head_k_dim, 2, dtype=torch.float32) / self.head_k_dim)
792
+ )
793
+ self.register_buffer("_inv_freq", inv_freq, persistent=False)
794
+ else:
795
+ self._inv_freq = None
796
+ self.activation = config.hidden_act
797
+ self.act = ACT2FN[config.hidden_act]
798
+ self.layer_norm_epsilon = config.rms_norm_eps
799
+
800
+ # QKV
801
+ self.conv_dim = self.key_dim * 2 + self.value_dim
802
+ self.conv1d = nn.Conv1d(
803
+ in_channels=self.conv_dim,
804
+ out_channels=self.conv_dim,
805
+ bias=False,
806
+ kernel_size=self.conv_kernel_size,
807
+ groups=self.conv_dim,
808
+ padding=self.conv_kernel_size - 1,
809
+ )
810
+
811
+ # projection of the input hidden states
812
+ projection_size_qkvz = self.key_dim * 2 + self.value_dim * 2
813
+ projection_size_ba = self.num_v_heads * 2
814
+ self.in_proj_qkvz = nn.Linear(self.hidden_size, projection_size_qkvz, bias=False)
815
+ self.in_proj_ba = nn.Linear(self.hidden_size, projection_size_ba, bias=False)
816
+
817
+ # time step projection (discretization)
818
+ # instantiate once and copy inv_dt in init_weights of PretrainedModel
819
+ self.dt_bias = nn.Parameter(torch.ones(self.num_v_heads))
820
+
821
+ A = torch.empty(self.num_v_heads).uniform_(0, 16)
822
+ self.A_log = nn.Parameter(torch.log(A))
823
+
824
+ # self.norm = FusedRMSNormGated(self.head_v_dim, eps=self.layer_norm_epsilon)
825
+ self.norm = (
826
+ Qwen3NextRMSNormGated(self.head_v_dim, eps=self.layer_norm_epsilon)
827
+ if FusedRMSNormGated is None
828
+ else FusedRMSNormGated(
829
+ self.head_v_dim,
830
+ eps=self.layer_norm_epsilon,
831
+ activation=self.activation,
832
+ device=torch.cuda.current_device(),
833
+ dtype=config.dtype if config.dtype is not None else torch.get_current_dtype(),
834
+ )
835
+ )
836
+
837
+ self.out_proj = nn.Linear(self.value_dim, self.hidden_size, bias=False)
838
+
839
+ self.causal_conv1d_fn = causal_conv1d_fn
840
+ self.causal_conv1d_update = causal_conv1d_update or torch_causal_conv1d_update
841
+ self.chunk_gated_delta_rule = chunk_gated_delta_rule or torch_chunk_gated_delta_rule
842
+ self.recurrent_gated_delta_rule = fused_recurrent_gated_delta_rule or torch_recurrent_gated_delta_rule
843
+
844
+ if not is_fast_path_available:
845
+ logger.warning_once(
846
+ "The fast path is not available because one of the required library is not installed. Falling back to "
847
+ "torch implementation. To install follow https://github.com/fla-org/flash-linear-attention#installation and"
848
+ " https://github.com/Dao-AILab/causal-conv1d"
849
+ )
850
+
851
+ def fix_query_key_value_ordering(self, mixed_qkvz, mixed_ba):
852
+ """
853
+ Derives `query`, `key` and `value` tensors from `mixed_qkvz` and `mixed_ba`.
854
+ """
855
+ # (b, s, d_model) -> (b, s, num_k_heads, 2 * head_k_dim + 2 * head_v_dim * num_v_heads // num_k_heads)
856
+ new_tensor_shape_qkvz = mixed_qkvz.size()[:-1] + (
857
+ self.num_k_heads,
858
+ 2 * self.head_k_dim + 2 * self.head_v_dim * self.num_v_heads // self.num_k_heads,
859
+ )
860
+ new_tensor_shape_ba = mixed_ba.size()[:-1] + (self.num_k_heads, 2 * self.num_v_heads // self.num_k_heads)
861
+
862
+ mixed_qkvz = mixed_qkvz.view(*new_tensor_shape_qkvz)
863
+ mixed_ba = mixed_ba.view(*new_tensor_shape_ba)
864
+ split_arg_list_qkvz = [
865
+ self.head_k_dim,
866
+ self.head_k_dim,
867
+ (self.num_v_heads // self.num_k_heads * self.head_v_dim),
868
+ (self.num_v_heads // self.num_k_heads * self.head_v_dim),
869
+ ]
870
+ split_arg_list_ba = [self.num_v_heads // self.num_k_heads, self.num_v_heads // self.num_k_heads]
871
+ query, key, value, z = torch.split(mixed_qkvz, split_arg_list_qkvz, dim=3)
872
+ b, a = torch.split(mixed_ba, split_arg_list_ba, dim=3)
873
+ # [b, sq, ng, np/ng * hn] -> [b, sq, np, hn]
874
+ value = value.reshape(value.size(0), value.size(1), -1, self.head_v_dim)
875
+ z = z.reshape(z.size(0), z.size(1), -1, self.head_v_dim)
876
+ b = b.reshape(b.size(0), b.size(1), self.num_v_heads)
877
+ a = a.reshape(a.size(0), a.size(1), self.num_v_heads)
878
+ return query, key, value, z, b, a
879
+
880
+ def forward(
881
+ self,
882
+ hidden_states: torch.Tensor,
883
+ cache_params: Optional[Qwen3NextDynamicCache] = None,
884
+ cache_position: Optional[torch.LongTensor] = None,
885
+ attention_mask: Optional[torch.Tensor] = None,
886
+ position_ids: Optional[torch.LongTensor] = None,
887
+ ):
888
+ hidden_states = apply_mask_to_padding_states(hidden_states, attention_mask)
889
+
890
+ # Set up dimensions for reshapes later
891
+ batch_size, seq_len, _ = hidden_states.shape
892
+
893
+ use_precomputed_states = (
894
+ cache_params is not None
895
+ and cache_params.has_previous_state
896
+ and seq_len == 1
897
+ and cache_position is not None
898
+ )
899
+
900
+ # getting projected states from cache if it exists
901
+ if cache_params is not None:
902
+ conv_state = cache_params.conv_states[self.layer_idx]
903
+ recurrent_state = cache_params.recurrent_states[self.layer_idx]
904
+
905
+ projected_states_qkvz = self.in_proj_qkvz(hidden_states)
906
+ projected_states_ba = self.in_proj_ba(hidden_states)
907
+ query, key, value, z, b, a = self.fix_query_key_value_ordering(projected_states_qkvz, projected_states_ba)
908
+ query, key, value = (x.reshape(x.shape[0], x.shape[1], -1) for x in (query, key, value))
909
+
910
+ mixed_qkv = torch.cat((query, key, value), dim=-1)
911
+ mixed_qkv = mixed_qkv.transpose(1, 2)
912
+
913
+ if use_precomputed_states:
914
+ # 2. Convolution sequence transformation
915
+ # NOTE: the conv state is updated in `causal_conv1d_update`
916
+ mixed_qkv = self.causal_conv1d_update(
917
+ mixed_qkv,
918
+ conv_state,
919
+ self.conv1d.weight.squeeze(1),
920
+ self.conv1d.bias,
921
+ self.activation,
922
+ )
923
+ else:
924
+ if cache_params is not None:
925
+ conv_state = F.pad(mixed_qkv, (self.conv_kernel_size - mixed_qkv.shape[-1], 0))
926
+ cache_params.conv_states[self.layer_idx] = conv_state
927
+ if self.causal_conv1d_fn is not None:
928
+ mixed_qkv = self.causal_conv1d_fn(
929
+ x=mixed_qkv,
930
+ weight=self.conv1d.weight.squeeze(1),
931
+ bias=self.conv1d.bias,
932
+ activation=self.activation,
933
+ seq_idx=None,
934
+ )
935
+ else:
936
+ mixed_qkv = F.silu(self.conv1d(mixed_qkv)[:, :, :seq_len])
937
+
938
+ mixed_qkv = mixed_qkv.transpose(1, 2)
939
+ query, key, value = torch.split(
940
+ mixed_qkv,
941
+ [
942
+ self.key_dim,
943
+ self.key_dim,
944
+ self.value_dim,
945
+ ],
946
+ dim=-1,
947
+ )
948
+ query = query.reshape(query.shape[0], query.shape[1], -1, self.head_k_dim)
949
+ key = key.reshape(key.shape[0], key.shape[1], -1, self.head_k_dim)
950
+ value = value.reshape(value.shape[0], value.shape[1], -1, self.head_v_dim)
951
+
952
+ # Optional RoPE for linear/RNN (same as FLA GatedDeltaNet when rnn_position_embedding_type=="rope")
953
+ if self._inv_freq is not None and position_ids is not None:
954
+ # query, key: (batch, seq, num_k_heads, head_k_dim); need cos, sin (batch, seq, head_k_dim)
955
+ inv_freq = self._inv_freq.to(query.device)
956
+ freqs = position_ids[:, :, None].float() * inv_freq[None, None, :]
957
+ emb = torch.cat([freqs, freqs], dim=-1)
958
+ cos = emb.cos().to(query.dtype)
959
+ sin = emb.sin().to(query.dtype)
960
+ query, key = apply_rotary_pos_emb(query, key, cos, sin, unsqueeze_dim=2)
961
+
962
+ beta = b.sigmoid()
963
+ # If the model is loaded in fp16, without the .float() here, A might be -inf
964
+ g = -self.A_log.float().exp() * F.softplus(a.float() + self.dt_bias)
965
+ if self.num_v_heads // self.num_k_heads > 1:
966
+ query = query.repeat_interleave(self.num_v_heads // self.num_k_heads, dim=2)
967
+ key = key.repeat_interleave(self.num_v_heads // self.num_k_heads, dim=2)
968
+
969
+ if not use_precomputed_states:
970
+ core_attn_out, last_recurrent_state = self.chunk_gated_delta_rule(
971
+ query,
972
+ key,
973
+ value,
974
+ g=g,
975
+ beta=beta,
976
+ initial_state=None,
977
+ output_final_state=cache_params is not None,
978
+ use_qk_l2norm_in_kernel=True,
979
+ )
980
+
981
+ else:
982
+ core_attn_out, last_recurrent_state = self.recurrent_gated_delta_rule(
983
+ query,
984
+ key,
985
+ value,
986
+ g=g,
987
+ beta=beta,
988
+ initial_state=recurrent_state,
989
+ output_final_state=cache_params is not None,
990
+ use_qk_l2norm_in_kernel=True,
991
+ )
992
+ # Update cache
993
+ if cache_params is not None:
994
+ cache_params.recurrent_states[self.layer_idx] = last_recurrent_state
995
+
996
+ z_shape_og = z.shape
997
+ # reshape input data into 2D tensor
998
+ # core_attn_out = core_attn_out.reshape(-1, core_attn_out.shape[-1])
999
+ # z = z.reshape(-1, z.shape[-1])
1000
+ core_attn_out = core_attn_out
1001
+ z = z
1002
+ core_attn_out = self.norm(core_attn_out, z)
1003
+
1004
+ core_attn_out = core_attn_out.reshape(z_shape_og)
1005
+ core_attn_out = core_attn_out.reshape(core_attn_out.shape[0], core_attn_out.shape[1], -1)
1006
+
1007
+ output = self.out_proj(core_attn_out)
1008
+ return output
1009
+
1010
+
1011
+ class Qwen3NextMLP(nn.Module):
1012
+ def __init__(self, config, intermediate_size=None):
1013
+ super().__init__()
1014
+ self.config = config
1015
+ self.hidden_size = config.hidden_size
1016
+ self.intermediate_size = intermediate_size if intermediate_size is not None else config.intermediate_size
1017
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
1018
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
1019
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
1020
+ self.act_fn = ACT2FN[config.hidden_act]
1021
+
1022
+ # Token shifting (cannon layer): conv mode adds depthwise Conv1d
1023
+ self.ffn_token_shift = getattr(config, "ffn_token_shift", None)
1024
+ self.ffn_intermediate_token_shift = getattr(config, "ffn_intermediate_token_shift", None)
1025
+ kernel_size = getattr(config, "token_shift_conv_size", 4)
1026
+ if self.ffn_token_shift == "conv":
1027
+ self.token_shift_conv = nn.Conv1d(
1028
+ self.hidden_size,
1029
+ self.hidden_size,
1030
+ kernel_size=kernel_size,
1031
+ padding=0,
1032
+ groups=self.hidden_size,
1033
+ bias=False,
1034
+ )
1035
+ else:
1036
+ self.token_shift_conv = None
1037
+ if self.ffn_intermediate_token_shift == "conv":
1038
+ self.intermediate_token_shift_conv = nn.Conv1d(
1039
+ self.intermediate_size,
1040
+ self.intermediate_size,
1041
+ kernel_size=kernel_size,
1042
+ padding=0,
1043
+ groups=self.intermediate_size,
1044
+ bias=False,
1045
+ )
1046
+ else:
1047
+ self.intermediate_token_shift_conv = None
1048
+
1049
+ def forward(self, x, per_token_scale=None):
1050
+ # Token shift at MLP entry (conv mode; cat mode is stateless, not implemented here for loading conv checkpoints)
1051
+ if self.ffn_token_shift == "conv" and self.token_shift_conv is not None:
1052
+ # x: [batch, seq, hidden] -> [batch, hidden, seq]
1053
+ x_bcl = x.transpose(1, 2).contiguous()
1054
+ x_bcl = apply_causal_depthwise_conv1d_bcl(x_bcl, self.token_shift_conv.weight)
1055
+ x = x_bcl.transpose(1, 2).contiguous()
1056
+
1057
+ # Compute gate and up projections
1058
+ gate = self.gate_proj(x)
1059
+ up = self.up_proj(x)
1060
+ # Apply activation: act_fn(gate) * up
1061
+ intermediate = self.act_fn(gate) * up
1062
+ # Apply per_token_scale if provided (to align with Megatron's behavior)
1063
+ if per_token_scale is not None:
1064
+ intermediate = intermediate * per_token_scale.unsqueeze(-1)
1065
+
1066
+ # Intermediate token shift before down_proj (conv mode)
1067
+ if self.ffn_intermediate_token_shift == "conv" and self.intermediate_token_shift_conv is not None:
1068
+ inter_bcl = intermediate.transpose(1, 2).contiguous()
1069
+ inter_bcl = apply_causal_depthwise_conv1d_bcl(inter_bcl, self.intermediate_token_shift_conv.weight)
1070
+ intermediate = inter_bcl.transpose(1, 2).contiguous()
1071
+
1072
+ # Apply down projection
1073
+ down_proj = self.down_proj(intermediate)
1074
+ return down_proj
1075
+
1076
+
1077
+ class Qwen3NextSparseMoeBlock(nn.Module):
1078
+ def __init__(self, config):
1079
+ super().__init__()
1080
+ self.num_experts = config.num_experts
1081
+ self.top_k = config.num_experts_per_tok
1082
+ self.norm_topk_prob = config.norm_topk_prob
1083
+ self.config = config
1084
+
1085
+ # Token shift at MoE entry (cannon layer, reuses ffn_token_shift)
1086
+ self.ffn_token_shift = getattr(config, "ffn_token_shift", None)
1087
+ kernel_size = getattr(config, "token_shift_conv_size", 4)
1088
+ if self.ffn_token_shift == "conv":
1089
+ self.token_shift_conv = nn.Conv1d(
1090
+ config.hidden_size,
1091
+ config.hidden_size,
1092
+ kernel_size=kernel_size,
1093
+ padding=0,
1094
+ groups=config.hidden_size,
1095
+ bias=False,
1096
+ )
1097
+ else:
1098
+ self.token_shift_conv = None
1099
+
1100
+ # gating
1101
+ self.gate = nn.Linear(config.hidden_size, config.num_experts, bias=config.router_bias)
1102
+ self.experts = nn.ModuleList(
1103
+ [Qwen3NextMLP(config, intermediate_size=config.moe_intermediate_size) for _ in range(self.num_experts)]
1104
+ )
1105
+ if config.moe_router_score_function == 'softmax':
1106
+ self.score_func = lambda x: F.softmax(x, dim=1, dtype=torch.float)
1107
+ elif config.moe_router_score_function == 'sigmoid':
1108
+ # Sigmoid 不需要 dim,且通常不需要显式指定 dtype (会自动保持)
1109
+ self.score_func = lambda x: F.sigmoid(x)
1110
+
1111
+ if config.shared_expert_intermediate_size > 0:
1112
+ self.shared_expert = Qwen3NextMLP(config, intermediate_size=config.shared_expert_intermediate_size)
1113
+ if getattr(config, "use_shared_expert_gate", True):
1114
+ self.shared_expert_gate = torch.nn.Linear(config.hidden_size, 1, bias=False)
1115
+ else:
1116
+ self.shared_expert_gate = None
1117
+ else:
1118
+ self.shared_expert = None
1119
+ self.shared_expert_gate = None
1120
+
1121
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
1122
+ """ """
1123
+ batch_size, sequence_length, hidden_dim = hidden_states.shape
1124
+
1125
+ # Token shift at MoE entry (cannon layer, conv mode)
1126
+ if self.ffn_token_shift == "conv" and self.token_shift_conv is not None:
1127
+ h_bcl = hidden_states.transpose(1, 2).contiguous()
1128
+ h_bcl = apply_causal_depthwise_conv1d_bcl(h_bcl, self.token_shift_conv.weight)
1129
+ hidden_states = h_bcl.transpose(1, 2).contiguous()
1130
+
1131
+ hidden_states = hidden_states.view(-1, hidden_dim)
1132
+ # router_logits: (batch * sequence_length, n_experts)
1133
+ router_logits = self.gate(hidden_states)
1134
+
1135
+ routing_weights = self.score_func(router_logits)
1136
+ routing_weights, selected_experts = torch.topk(routing_weights, self.top_k, dim=-1)
1137
+ if self.norm_topk_prob:
1138
+ routing_weights /= routing_weights.sum(dim=-1, keepdim=True)
1139
+ # we cast back to the input dtype
1140
+ routing_weights = routing_weights.to(hidden_states.dtype)
1141
+
1142
+ final_hidden_states = torch.zeros(
1143
+ (batch_size * sequence_length, hidden_dim), dtype=hidden_states.dtype, device=hidden_states.device
1144
+ )
1145
+
1146
+ # One hot encode the selected experts to create an expert mask
1147
+ # this will be used to easily index which expert is going to be sollicitated
1148
+ expert_mask = torch.nn.functional.one_hot(selected_experts, num_classes=self.num_experts).permute(2, 1, 0)
1149
+
1150
+ # Loop over all available experts in the model and perform the computation on each expert
1151
+ expert_hit = torch.greater(expert_mask.sum(dim=(-1, -2)), 0).nonzero()
1152
+ for expert_idx in expert_hit:
1153
+ expert_layer = self.experts[expert_idx]
1154
+ idx, top_x = torch.where(expert_mask[expert_idx].squeeze(0))
1155
+
1156
+ # Index the correct hidden states and compute the expert hidden state for
1157
+ # the current expert.
1158
+ # To align with Megatron: apply routing_weights after activation, before down_proj
1159
+ # (instead of after the full expert output)
1160
+ current_state = hidden_states[None, top_x].reshape(-1, hidden_dim)
1161
+ current_routing_weights = routing_weights[top_x, idx] # [M] where M is num tokens for this expert
1162
+ # Pass routing_weights as per_token_scale to apply it after activation, before down_proj
1163
+ current_hidden_states = expert_layer(current_state, per_token_scale=current_routing_weights)
1164
+
1165
+ # However `index_add_` only support torch tensors for indexing so we'll use
1166
+ # the `top_x` tensor here.
1167
+ final_hidden_states.index_add_(0, top_x, current_hidden_states.to(hidden_states.dtype))
1168
+
1169
+ if self.shared_expert is not None:
1170
+ shared_expert_output = self.shared_expert(hidden_states)
1171
+ if self.shared_expert_gate is not None:
1172
+ shared_expert_output = F.sigmoid(self.shared_expert_gate(hidden_states)) * shared_expert_output
1173
+
1174
+ final_hidden_states = final_hidden_states + shared_expert_output
1175
+
1176
+ final_hidden_states = final_hidden_states.reshape(batch_size, sequence_length, hidden_dim)
1177
+ return final_hidden_states, router_logits
1178
+
1179
+
1180
+ class Qwen3NextDecoderLayer(GradientCheckpointingLayer):
1181
+ def __init__(self, config: Qwen3NextConfig, layer_idx: int):
1182
+ super().__init__()
1183
+ self.hidden_size = config.hidden_size
1184
+
1185
+ # token mixer
1186
+ self.layer_type = config.layer_types[layer_idx]
1187
+ if self.layer_type == "linear_attention":
1188
+ self.linear_attn = Qwen3NextGatedDeltaNet(config, layer_idx)
1189
+ elif self.layer_type == "full_attention":
1190
+ self.self_attn = Qwen3NextAttention(config, layer_idx)
1191
+
1192
+ if (layer_idx not in config.mlp_only_layers) and (
1193
+ config.num_experts > 0 and (layer_idx + 1) % config.decoder_sparse_step == 0
1194
+ ):
1195
+ self.mlp = Qwen3NextSparseMoeBlock(config)
1196
+ else:
1197
+ self.mlp = Qwen3NextMLP(config, intermediate_size=config.intermediate_size)
1198
+
1199
+ self.input_layernorm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
1200
+ self.post_attention_layernorm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
1201
+
1202
+ # Token shift before attention (cannon layer, conv mode)
1203
+ self.attn_token_shift = getattr(config, "attn_token_shift", None)
1204
+ kernel_size = getattr(config, "token_shift_conv_size", 4)
1205
+ if self.attn_token_shift == "conv":
1206
+ self.attn_token_shift_conv = nn.Conv1d(
1207
+ config.hidden_size,
1208
+ config.hidden_size,
1209
+ kernel_size=kernel_size,
1210
+ padding=0,
1211
+ groups=config.hidden_size,
1212
+ bias=False,
1213
+ )
1214
+ else:
1215
+ self.attn_token_shift_conv = None
1216
+
1217
+ @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
1218
+ def forward(
1219
+ self,
1220
+ hidden_states: torch.Tensor,
1221
+ position_embeddings: tuple[torch.Tensor, torch.Tensor],
1222
+ attention_mask: Optional[torch.Tensor] = None,
1223
+ position_ids: Optional[torch.LongTensor] = None,
1224
+ past_key_values: Optional[tuple[torch.Tensor]] = None,
1225
+ cache_position: Optional[torch.LongTensor] = None,
1226
+ **kwargs: Unpack[FlashAttentionKwargs],
1227
+ ) -> torch.FloatTensor:
1228
+ """
1229
+ Args:
1230
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
1231
+ attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
1232
+ `(batch, sequence_length)` where padding elements are indicated by 0.
1233
+ output_attentions (`bool`, *optional*):
1234
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
1235
+ returned tensors for more detail.
1236
+ output_router_logits (`bool`, *optional*):
1237
+ Whether or not to return the logits of all the routers. They are useful for computing the router loss,
1238
+ and should not be returned during inference.
1239
+ use_cache (`bool`, *optional*):
1240
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
1241
+ (see `past_key_values`).
1242
+ past_key_values (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
1243
+ cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
1244
+ Indices depicting the position of the input sequence tokens in the sequence.
1245
+ position_embeddings (`tuple[torch.FloatTensor, torch.FloatTensor]`, *optional*):
1246
+ Tuple containing the cosine and sine positional embeddings of shape `(batch_size, seq_len, head_dim)`,
1247
+ with `head_dim` being the embedding dimension of each attention head.
1248
+ kwargs (`dict`, *optional*):
1249
+ Arbitrary kwargs to be ignored, used for FSDP and other methods that injects code
1250
+ into the model
1251
+ """
1252
+ residual = hidden_states
1253
+
1254
+ hidden_states = self.input_layernorm(hidden_states)
1255
+
1256
+ # Token shift before attention (cannon layer, conv mode)
1257
+ if self.attn_token_shift == "conv" and self.attn_token_shift_conv is not None:
1258
+ # [batch, seq, hidden] -> [batch, hidden, seq]
1259
+ h_bcl = hidden_states.transpose(1, 2).contiguous()
1260
+ h_bcl = apply_causal_depthwise_conv1d_bcl(h_bcl, self.attn_token_shift_conv.weight)
1261
+ hidden_states = h_bcl.transpose(1, 2).contiguous()
1262
+
1263
+ # Token Mixer
1264
+ if self.layer_type == "linear_attention":
1265
+ hidden_states = self.linear_attn(
1266
+ hidden_states=hidden_states,
1267
+ cache_params=past_key_values,
1268
+ cache_position=cache_position,
1269
+ attention_mask=attention_mask,
1270
+ position_ids=position_ids,
1271
+ )
1272
+ elif self.layer_type == "full_attention":
1273
+ # Self Attention
1274
+ hidden_states, _ = self.self_attn(
1275
+ hidden_states=hidden_states,
1276
+ attention_mask=attention_mask,
1277
+ position_ids=position_ids,
1278
+ past_key_values=past_key_values,
1279
+ cache_position=cache_position,
1280
+ position_embeddings=position_embeddings,
1281
+ **kwargs,
1282
+ )
1283
+
1284
+ hidden_states = residual + hidden_states
1285
+
1286
+ # Fully Connected
1287
+ residual = hidden_states
1288
+ hidden_states = self.post_attention_layernorm(hidden_states)
1289
+ hidden_states = self.mlp(hidden_states)
1290
+ # For the MoE layers, we need to unpack
1291
+ if isinstance(hidden_states, tuple):
1292
+ hidden_states, _ = hidden_states
1293
+ hidden_states = residual + hidden_states
1294
+
1295
+ return hidden_states
1296
+
1297
+
1298
+ class Qwen3NextPreTrainedModel(PreTrainedModel):
1299
+ config: Qwen3NextConfig
1300
+ base_model_prefix = "model"
1301
+ supports_gradient_checkpointing = True
1302
+ _no_split_modules = ["Qwen3NextDecoderLayer"]
1303
+ _skip_keys_device_placement = "past_key_values"
1304
+ _supports_flash_attn_2 = True
1305
+ _supports_sdpa = True
1306
+ _keys_to_ignore_on_load_unexpected = [r"^mtp.*"]
1307
+ _can_record_outputs = {
1308
+ "router_logits": OutputRecorder(Qwen3NextSparseMoeBlock, index=1),
1309
+ "hidden_states": Qwen3NextDecoderLayer,
1310
+ "attentions": Qwen3NextAttention,
1311
+ }
1312
+ _is_stateful = True
1313
+
1314
+ def _init_weights(self, module):
1315
+ super()._init_weights(module)
1316
+ if isinstance(module, Qwen3NextGatedDeltaNet):
1317
+ module.dt_bias.data.fill_(1.0)
1318
+ module.A_log.data.uniform_(0, 16).log_()
1319
+
1320
+
1321
+ class Qwen3NextModel(Qwen3NextPreTrainedModel):
1322
+ def __init__(self, config: Qwen3NextConfig):
1323
+ super().__init__(config)
1324
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, config.pad_token_id)
1325
+ self.layers = nn.ModuleList(
1326
+ [Qwen3NextDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
1327
+ )
1328
+ self.norm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
1329
+ self.rotary_emb = Qwen3NextRotaryEmbedding(config=config)
1330
+ self.gradient_checkpointing = False
1331
+ # Initialize weights and apply final processing
1332
+ self.post_init()
1333
+ _log_custom_features(config)
1334
+
1335
+ # @check_model_inputs
1336
+ @auto_docstring
1337
+ def forward(
1338
+ self,
1339
+ input_ids: Optional[torch.LongTensor] = None,
1340
+ attention_mask: Optional[torch.Tensor] = None,
1341
+ position_ids: Optional[torch.LongTensor] = None,
1342
+ past_key_values: Optional[Cache] = None,
1343
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1344
+ use_cache: Optional[bool] = None,
1345
+ cache_position: Optional[torch.LongTensor] = None,
1346
+ **kwargs: Unpack[TransformersKwargs],
1347
+ ) -> MoeModelOutputWithPast:
1348
+ if (input_ids is None) ^ (inputs_embeds is not None):
1349
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
1350
+
1351
+ if inputs_embeds is None:
1352
+ inputs_embeds = self.embed_tokens(input_ids)
1353
+
1354
+ if use_cache and past_key_values is None:
1355
+ past_key_values = Qwen3NextDynamicCache(config=self.config)
1356
+
1357
+ if cache_position is None:
1358
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
1359
+ cache_position = torch.arange(
1360
+ past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
1361
+ )
1362
+ if position_ids is None:
1363
+ position_ids = cache_position.unsqueeze(0)
1364
+
1365
+ causal_mask = create_causal_mask(
1366
+ config=self.config,
1367
+ input_embeds=inputs_embeds,
1368
+ attention_mask=attention_mask,
1369
+ cache_position=cache_position,
1370
+ past_key_values=past_key_values,
1371
+ position_ids=position_ids,
1372
+ )
1373
+ linear_attn_mask = self._update_linear_attn_mask(attention_mask, cache_position)
1374
+
1375
+ hidden_states = inputs_embeds
1376
+
1377
+ # create position embeddings to be shared across the decoder layers
1378
+ position_embeddings = self.rotary_emb(hidden_states, position_ids)
1379
+
1380
+ for decoder_layer in self.layers[: self.config.num_hidden_layers]:
1381
+ layer_mask = linear_attn_mask if decoder_layer.layer_type == "linear_attention" else causal_mask
1382
+
1383
+ hidden_states = decoder_layer(
1384
+ hidden_states,
1385
+ position_embeddings=position_embeddings,
1386
+ attention_mask=layer_mask,
1387
+ position_ids=position_ids,
1388
+ past_key_values=past_key_values,
1389
+ use_cache=use_cache,
1390
+ cache_position=cache_position,
1391
+ **kwargs,
1392
+ )
1393
+
1394
+ hidden_states = self.norm(hidden_states)
1395
+
1396
+ return MoeModelOutputWithPast(
1397
+ last_hidden_state=hidden_states,
1398
+ past_key_values=past_key_values,
1399
+ )
1400
+
1401
+ def _update_linear_attn_mask(self, attention_mask, cache_position):
1402
+ """
1403
+ NOTE: Left-padding is used for linear attention mask.
1404
+ No need for zeroing states when
1405
+ 1. Cached forward
1406
+ 2. Attending to all inputs
1407
+ """
1408
+ linear_attn_mask = attention_mask
1409
+ if cache_position[0] > 0 or (attention_mask is not None and torch.all(attention_mask == 1)):
1410
+ linear_attn_mask = None
1411
+ return linear_attn_mask
1412
+
1413
+
1414
+ def load_balancing_loss_func(
1415
+ gate_logits: Union[torch.Tensor, tuple[torch.Tensor], None],
1416
+ num_experts: Optional[int] = None,
1417
+ top_k=2,
1418
+ attention_mask: Optional[torch.Tensor] = None,
1419
+ ) -> Union[torch.Tensor, int]:
1420
+ r"""
1421
+ Computes auxiliary load balancing loss as in Switch Transformer - implemented in Pytorch.
1422
+
1423
+ See Switch Transformer (https://huggingface.co/papers/2101.03961) for more details. This function implements the loss
1424
+ function presented in equations (4) - (6) of the paper. It aims at penalizing cases where the routing between
1425
+ experts is too unbalanced.
1426
+
1427
+ Args:
1428
+ gate_logits:
1429
+ Logits from the `gate`, should be a tuple of model.config.num_hidden_layers tensors of
1430
+ shape [batch_size X sequence_length, num_experts].
1431
+ num_experts:
1432
+ Number of experts
1433
+ top_k:
1434
+ The number of experts to route per-token, can be also interpreted as the `top-k` routing
1435
+ parameter.
1436
+ attention_mask (`torch.Tensor`, *optional*):
1437
+ The attention_mask used in forward function
1438
+ shape [batch_size X sequence_length] if not None.
1439
+
1440
+ Returns:
1441
+ The auxiliary loss.
1442
+ """
1443
+ if gate_logits is None or not isinstance(gate_logits, tuple):
1444
+ return 0
1445
+
1446
+ if isinstance(gate_logits, tuple):
1447
+ compute_device = gate_logits[0].device
1448
+ concatenated_gate_logits = torch.cat([layer_gate.to(compute_device) for layer_gate in gate_logits], dim=0)
1449
+
1450
+ routing_weights = torch.nn.functional.softmax(concatenated_gate_logits, dim=-1)
1451
+
1452
+ _, selected_experts = torch.topk(routing_weights, top_k, dim=-1)
1453
+
1454
+ expert_mask = torch.nn.functional.one_hot(selected_experts, num_experts)
1455
+
1456
+ if attention_mask is None:
1457
+ # Compute the percentage of tokens routed to each experts
1458
+ tokens_per_expert = torch.mean(expert_mask.float(), dim=0)
1459
+
1460
+ # Compute the average probability of routing to these experts
1461
+ router_prob_per_expert = torch.mean(routing_weights, dim=0)
1462
+ else:
1463
+ batch_size, sequence_length = attention_mask.shape
1464
+ num_hidden_layers = concatenated_gate_logits.shape[0] // (batch_size * sequence_length)
1465
+
1466
+ # Compute the mask that masks all padding tokens as 0 with the same shape of expert_mask
1467
+ expert_attention_mask = (
1468
+ attention_mask[None, :, :, None, None]
1469
+ .expand((num_hidden_layers, batch_size, sequence_length, top_k, num_experts))
1470
+ .reshape(-1, top_k, num_experts)
1471
+ .to(compute_device)
1472
+ )
1473
+
1474
+ # Compute the percentage of tokens routed to each experts
1475
+ tokens_per_expert = torch.sum(expert_mask.float() * expert_attention_mask, dim=0) / torch.sum(
1476
+ expert_attention_mask, dim=0
1477
+ )
1478
+
1479
+ # Compute the mask that masks all padding tokens as 0 with the same shape of tokens_per_expert
1480
+ router_per_expert_attention_mask = (
1481
+ attention_mask[None, :, :, None]
1482
+ .expand((num_hidden_layers, batch_size, sequence_length, num_experts))
1483
+ .reshape(-1, num_experts)
1484
+ .to(compute_device)
1485
+ )
1486
+
1487
+ # Compute the average probability of routing to these experts
1488
+ router_prob_per_expert = torch.sum(routing_weights * router_per_expert_attention_mask, dim=0) / torch.sum(
1489
+ router_per_expert_attention_mask, dim=0
1490
+ )
1491
+
1492
+ overall_loss = torch.sum(tokens_per_expert * router_prob_per_expert.unsqueeze(0))
1493
+ return overall_loss * num_experts
1494
+
1495
+
1496
+ @auto_docstring
1497
+ class Qwen3NextForCausalLM(Qwen3NextPreTrainedModel, GenerationMixin):
1498
+ _tied_weights_keys = ["lm_head.weight"]
1499
+ _tp_plan = {"lm_head": "colwise_rep"}
1500
+ _pp_plan = {"lm_head": (["hidden_states"], ["logits"])}
1501
+
1502
+ def __init__(self, config):
1503
+ super().__init__(config)
1504
+ self.model = Qwen3NextModel(config)
1505
+ self.vocab_size = config.vocab_size
1506
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1507
+ self.router_aux_loss_coef = config.router_aux_loss_coef
1508
+ self.num_experts = config.num_experts
1509
+ self.num_experts_per_tok = config.num_experts_per_tok
1510
+
1511
+ # Initialize weights and apply final processing
1512
+ self.post_init()
1513
+
1514
+ @can_return_tuple
1515
+ @auto_docstring
1516
+ def forward(
1517
+ self,
1518
+ input_ids: Optional[torch.LongTensor] = None,
1519
+ attention_mask: Optional[torch.Tensor] = None,
1520
+ position_ids: Optional[torch.LongTensor] = None,
1521
+ past_key_values: Optional[Qwen3NextDynamicCache] = None,
1522
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1523
+ labels: Optional[torch.LongTensor] = None,
1524
+ use_cache: Optional[bool] = None,
1525
+ output_router_logits: Optional[bool] = None,
1526
+ cache_position: Optional[torch.LongTensor] = None,
1527
+ logits_to_keep: Union[int, torch.Tensor] = 0,
1528
+ **kwargs: Unpack[TransformersKwargs],
1529
+ ) -> MoeCausalLMOutputWithPast:
1530
+ r"""
1531
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1532
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1533
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1534
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1535
+
1536
+ Example:
1537
+
1538
+ ```python
1539
+ >>> from transformers import AutoTokenizer, Qwen3NextForCausalLM
1540
+
1541
+ >>> model = Qwen3NextForCausalLM.from_pretrained("Qwen/Qwen3-Next-80B-A3B-Instruct")
1542
+ >>> tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen3-Next-80B-A3B-Instruct")
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_router_logits = (
1554
+ output_router_logits if output_router_logits is not None else self.config.output_router_logits
1555
+ )
1556
+
1557
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1558
+ outputs: MoeModelOutputWithPast = self.model(
1559
+ input_ids=input_ids,
1560
+ attention_mask=attention_mask,
1561
+ position_ids=position_ids,
1562
+ past_key_values=past_key_values,
1563
+ inputs_embeds=inputs_embeds,
1564
+ use_cache=use_cache,
1565
+ output_router_logits=output_router_logits,
1566
+ cache_position=cache_position,
1567
+ **kwargs,
1568
+ )
1569
+
1570
+ hidden_states = outputs.last_hidden_state
1571
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
1572
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
1573
+ logits = self.lm_head(hidden_states[:, slice_indices, :])
1574
+
1575
+ loss = None
1576
+ if labels is not None:
1577
+ loss = self.loss_function(logits, labels, self.vocab_size, **kwargs)
1578
+
1579
+ aux_loss = None
1580
+ if output_router_logits:
1581
+ aux_loss = load_balancing_loss_func(
1582
+ outputs.router_logits,
1583
+ self.num_experts,
1584
+ self.num_experts_per_tok,
1585
+ attention_mask,
1586
+ )
1587
+ if labels is not None:
1588
+ loss += self.router_aux_loss_coef * aux_loss.to(loss.device) # make sure to reside in the same device
1589
+
1590
+ return MoeCausalLMOutputWithPast(
1591
+ loss=loss,
1592
+ aux_loss=aux_loss,
1593
+ logits=logits,
1594
+ past_key_values=outputs.past_key_values,
1595
+ hidden_states=outputs.hidden_states,
1596
+ attentions=outputs.attentions,
1597
+ router_logits=outputs.router_logits,
1598
+ )
1599
+
1600
+
1601
+ __all__ = [
1602
+ "Qwen3NextForCausalLM",
1603
+ "Qwen3NextModel",
1604
+ "Qwen3NextPreTrainedModel",
1605
+ ]
v3_1_ear_moehybrid_bailing_e256_top8_swiglu7_finallogit30_eprobe/tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
v3_1_ear_moehybrid_bailing_e256_top8_swiglu7_finallogit30_eprobe/tokenizer_config.json ADDED
@@ -0,0 +1,436 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_bos_token": false,
3
+ "add_eos_token": false,
4
+ "add_prefix_space": null,
5
+ "added_tokens_decoder": {
6
+ "0": {
7
+ "content": "<unk>",
8
+ "lstrip": false,
9
+ "normalized": false,
10
+ "rstrip": false,
11
+ "single_word": false,
12
+ "special": true
13
+ },
14
+ "1": {
15
+ "content": "<s>",
16
+ "lstrip": false,
17
+ "normalized": false,
18
+ "rstrip": false,
19
+ "single_word": false,
20
+ "special": true
21
+ },
22
+ "2": {
23
+ "content": "<|endoftext|>",
24
+ "lstrip": false,
25
+ "normalized": false,
26
+ "rstrip": false,
27
+ "single_word": false,
28
+ "special": true
29
+ },
30
+ "102": {
31
+ "content": "<pad>",
32
+ "lstrip": false,
33
+ "normalized": false,
34
+ "rstrip": false,
35
+ "single_word": false,
36
+ "special": true
37
+ },
38
+ "103": {
39
+ "content": "<reasoning_step>",
40
+ "lstrip": false,
41
+ "normalized": false,
42
+ "rstrip": false,
43
+ "single_word": false,
44
+ "special": true
45
+ },
46
+ "104": {
47
+ "content": "<|im_start|>",
48
+ "lstrip": false,
49
+ "normalized": false,
50
+ "rstrip": false,
51
+ "single_word": false,
52
+ "special": true
53
+ },
54
+ "105": {
55
+ "content": "<|im_end|>",
56
+ "lstrip": false,
57
+ "normalized": false,
58
+ "rstrip": false,
59
+ "single_word": false,
60
+ "special": true
61
+ },
62
+ "106": {
63
+ "content": "<|object_ref_start|>",
64
+ "lstrip": false,
65
+ "normalized": false,
66
+ "rstrip": false,
67
+ "single_word": false,
68
+ "special": true
69
+ },
70
+ "107": {
71
+ "content": "<|object_ref_end|>",
72
+ "lstrip": false,
73
+ "normalized": false,
74
+ "rstrip": false,
75
+ "single_word": false,
76
+ "special": true
77
+ },
78
+ "108": {
79
+ "content": "<|box_start|>",
80
+ "lstrip": false,
81
+ "normalized": false,
82
+ "rstrip": false,
83
+ "single_word": false,
84
+ "special": true
85
+ },
86
+ "109": {
87
+ "content": "<|box_end|>",
88
+ "lstrip": false,
89
+ "normalized": false,
90
+ "rstrip": false,
91
+ "single_word": false,
92
+ "special": true
93
+ },
94
+ "110": {
95
+ "content": "<|quad_start|>",
96
+ "lstrip": false,
97
+ "normalized": false,
98
+ "rstrip": false,
99
+ "single_word": false,
100
+ "special": true
101
+ },
102
+ "111": {
103
+ "content": "<|quad_end|>",
104
+ "lstrip": false,
105
+ "normalized": false,
106
+ "rstrip": false,
107
+ "single_word": false,
108
+ "special": true
109
+ },
110
+ "112": {
111
+ "content": "<|vision_start|>",
112
+ "lstrip": false,
113
+ "normalized": false,
114
+ "rstrip": false,
115
+ "single_word": false,
116
+ "special": true
117
+ },
118
+ "113": {
119
+ "content": "<|vision_end|>",
120
+ "lstrip": false,
121
+ "normalized": false,
122
+ "rstrip": false,
123
+ "single_word": false,
124
+ "special": true
125
+ },
126
+ "114": {
127
+ "content": "<|vision_pad|>",
128
+ "lstrip": false,
129
+ "normalized": false,
130
+ "rstrip": false,
131
+ "single_word": false,
132
+ "special": true
133
+ },
134
+ "115": {
135
+ "content": "<|image_pad|>",
136
+ "lstrip": false,
137
+ "normalized": false,
138
+ "rstrip": false,
139
+ "single_word": false,
140
+ "special": true
141
+ },
142
+ "116": {
143
+ "content": "<|video_pad|>",
144
+ "lstrip": false,
145
+ "normalized": false,
146
+ "rstrip": false,
147
+ "single_word": false,
148
+ "special": true
149
+ },
150
+ "117": {
151
+ "content": "<tool_call>",
152
+ "lstrip": false,
153
+ "normalized": false,
154
+ "rstrip": false,
155
+ "single_word": false,
156
+ "special": false
157
+ },
158
+ "118": {
159
+ "content": "</tool_call>",
160
+ "lstrip": false,
161
+ "normalized": false,
162
+ "rstrip": false,
163
+ "single_word": false,
164
+ "special": false
165
+ },
166
+ "119": {
167
+ "content": "<|fim_prefix|>",
168
+ "lstrip": false,
169
+ "normalized": false,
170
+ "rstrip": false,
171
+ "single_word": false,
172
+ "special": false
173
+ },
174
+ "120": {
175
+ "content": "<|fim_middle|>",
176
+ "lstrip": false,
177
+ "normalized": false,
178
+ "rstrip": false,
179
+ "single_word": false,
180
+ "special": false
181
+ },
182
+ "121": {
183
+ "content": "<|fim_suffix|>",
184
+ "lstrip": false,
185
+ "normalized": false,
186
+ "rstrip": false,
187
+ "single_word": false,
188
+ "special": false
189
+ },
190
+ "122": {
191
+ "content": "<|fim_pad|>",
192
+ "lstrip": false,
193
+ "normalized": false,
194
+ "rstrip": false,
195
+ "single_word": false,
196
+ "special": false
197
+ },
198
+ "123": {
199
+ "content": "<|repo_name|>",
200
+ "lstrip": false,
201
+ "normalized": false,
202
+ "rstrip": false,
203
+ "single_word": false,
204
+ "special": false
205
+ },
206
+ "124": {
207
+ "content": "<|file_sep|>",
208
+ "lstrip": false,
209
+ "normalized": false,
210
+ "rstrip": false,
211
+ "single_word": false,
212
+ "special": false
213
+ },
214
+ "125": {
215
+ "content": "<tool_response>",
216
+ "lstrip": false,
217
+ "normalized": false,
218
+ "rstrip": false,
219
+ "single_word": false,
220
+ "special": false
221
+ },
222
+ "126": {
223
+ "content": "</tool_response>",
224
+ "lstrip": false,
225
+ "normalized": false,
226
+ "rstrip": false,
227
+ "single_word": false,
228
+ "special": false
229
+ },
230
+ "127": {
231
+ "content": "<think>",
232
+ "lstrip": false,
233
+ "normalized": false,
234
+ "rstrip": false,
235
+ "single_word": false,
236
+ "special": false
237
+ },
238
+ "128": {
239
+ "content": "</think>",
240
+ "lstrip": false,
241
+ "normalized": false,
242
+ "rstrip": false,
243
+ "single_word": false,
244
+ "special": false
245
+ },
246
+ "1071": {
247
+ "content": "<|sequence|>",
248
+ "lstrip": false,
249
+ "normalized": false,
250
+ "rstrip": false,
251
+ "single_word": false,
252
+ "special": true
253
+ },
254
+ "1072": {
255
+ "content": "<|/sequence|>",
256
+ "lstrip": false,
257
+ "normalized": false,
258
+ "rstrip": false,
259
+ "single_word": false,
260
+ "special": true
261
+ },
262
+ "1073": {
263
+ "content": "<|identity|>",
264
+ "lstrip": false,
265
+ "normalized": false,
266
+ "rstrip": false,
267
+ "single_word": false,
268
+ "special": true
269
+ },
270
+ "1074": {
271
+ "content": "<|identity|>",
272
+ "lstrip": false,
273
+ "normalized": false,
274
+ "rstrip": false,
275
+ "single_word": false,
276
+ "special": true
277
+ },
278
+ "1075": {
279
+ "content": "<|tail0|>",
280
+ "lstrip": false,
281
+ "normalized": false,
282
+ "rstrip": false,
283
+ "single_word": false,
284
+ "special": true
285
+ },
286
+ "1076": {
287
+ "content": "<|tail1|>",
288
+ "lstrip": false,
289
+ "normalized": false,
290
+ "rstrip": false,
291
+ "single_word": false,
292
+ "special": true
293
+ },
294
+ "1077": {
295
+ "content": "<|tail2|>",
296
+ "lstrip": false,
297
+ "normalized": false,
298
+ "rstrip": false,
299
+ "single_word": false,
300
+ "special": true
301
+ },
302
+ "1078": {
303
+ "content": "<|tail3|>",
304
+ "lstrip": false,
305
+ "normalized": false,
306
+ "rstrip": false,
307
+ "single_word": false,
308
+ "special": true
309
+ },
310
+ "1079": {
311
+ "content": "<|tail4|>",
312
+ "lstrip": false,
313
+ "normalized": false,
314
+ "rstrip": false,
315
+ "single_word": false,
316
+ "special": true
317
+ },
318
+ "1080": {
319
+ "content": "<|head0|>",
320
+ "lstrip": false,
321
+ "normalized": false,
322
+ "rstrip": false,
323
+ "single_word": false,
324
+ "special": true
325
+ },
326
+ "1081": {
327
+ "content": "<|head1|>",
328
+ "lstrip": false,
329
+ "normalized": false,
330
+ "rstrip": false,
331
+ "single_word": false,
332
+ "special": true
333
+ },
334
+ "1082": {
335
+ "content": "<|head2|>",
336
+ "lstrip": false,
337
+ "normalized": false,
338
+ "rstrip": false,
339
+ "single_word": false,
340
+ "special": true
341
+ },
342
+ "1083": {
343
+ "content": "<|head3|>",
344
+ "lstrip": false,
345
+ "normalized": false,
346
+ "rstrip": false,
347
+ "single_word": false,
348
+ "special": true
349
+ },
350
+ "1084": {
351
+ "content": "<|head4|>",
352
+ "lstrip": false,
353
+ "normalized": false,
354
+ "rstrip": false,
355
+ "single_word": false,
356
+ "special": true
357
+ },
358
+ "1085": {
359
+ "content": "<|chunk_id|>",
360
+ "lstrip": false,
361
+ "normalized": false,
362
+ "rstrip": false,
363
+ "single_word": false,
364
+ "special": true
365
+ },
366
+ "1086": {
367
+ "content": "<|/chunk_id|>",
368
+ "lstrip": false,
369
+ "normalized": false,
370
+ "rstrip": false,
371
+ "single_word": false,
372
+ "special": true
373
+ },
374
+ "1087": {
375
+ "content": "<|last_chunk_id|>",
376
+ "lstrip": false,
377
+ "normalized": false,
378
+ "rstrip": false,
379
+ "single_word": false,
380
+ "special": true
381
+ },
382
+ "1088": {
383
+ "content": "<|/last_chunk_id|>",
384
+ "lstrip": false,
385
+ "normalized": false,
386
+ "rstrip": false,
387
+ "single_word": false,
388
+ "special": true
389
+ }
390
+ },
391
+ "additional_special_tokens": [
392
+ "<|im_start|>",
393
+ "<|im_end|>",
394
+ "<|object_ref_start|>",
395
+ "<|object_ref_end|>",
396
+ "<|box_start|>",
397
+ "<|box_end|>",
398
+ "<|quad_start|>",
399
+ "<|quad_end|>",
400
+ "<|vision_start|>",
401
+ "<|vision_end|>",
402
+ "<|vision_pad|>",
403
+ "<|image_pad|>",
404
+ "<|video_pad|>",
405
+ "<|sequence|>",
406
+ "<|/sequence|>",
407
+ "<|identity|>",
408
+ "<|/identity|>",
409
+ "<|tail0|>",
410
+ "<|tail1|>",
411
+ "<|tail2|>",
412
+ "<|tail3|>",
413
+ "<|tail4|>",
414
+ "<|head0|>",
415
+ "<|head1|>",
416
+ "<|head2|>",
417
+ "<|head3|>",
418
+ "<|head4|>",
419
+ "<|chunk_id|>",
420
+ "<|/chunk_id|>",
421
+ "<|last_chunk_id|>",
422
+ "<|/last_chunk_id|>"
423
+ ],
424
+ "bos_token": null,
425
+ "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<think>\\n' }}\n{%- endif %}",
426
+ "clean_up_tokenization_spaces": false,
427
+ "eos_token": "<|im_end|>",
428
+ "model_max_length": 32768,
429
+ "pad_token": "<|endoftext|>",
430
+ "padding_side": "right",
431
+ "sp_model_kwargs": {},
432
+ "spaces_between_special_tokens": false,
433
+ "tokenizer_class": "LlamaTokenizerFast",
434
+ "unk_token": "<unk>",
435
+ "use_default_system_prompt": false
436
+ }