JinaLeejnl commited on
Commit
fe7ffd3
·
verified ·
1 Parent(s): c20b70a
__init__.py ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The Qwen Team and The HuggingFace Inc. team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ from typing import TYPE_CHECKING
15
+
16
+ from transformers.utils import _LazyModule
17
+ from transformers.utils.import_utils import define_import_structure
18
+
19
+
20
+ if TYPE_CHECKING:
21
+ from .configuration_qwen3 import *
22
+ from .modeling_qwen3 import *
23
+ else:
24
+ import sys
25
+
26
+ _file = globals()["__file__"]
27
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
configuration_qwen3.py ADDED
@@ -0,0 +1,212 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 The Qwen team, Alibaba Group and the HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """Qwen3 model configuration"""
16
+
17
+ from transformers.configuration_utils import PretrainedConfig
18
+ from transformers.modeling_rope_utils import rope_config_validation
19
+ from transformers.utils import logging
20
+
21
+
22
+ logger = logging.get_logger(__name__)
23
+
24
+
25
+ class Qwen3Config(PretrainedConfig):
26
+ r"""
27
+ This is the configuration class to store the configuration of a [`Qwen3Model`]. It is used to instantiate a
28
+ Qwen3 model according to the specified arguments, defining the model architecture. Instantiating a configuration
29
+ with the defaults will yield a similar configuration to that of
30
+ Qwen3-8B [Qwen/Qwen3-8B](https://huggingface.co/Qwen/Qwen3-8B).
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 Qwen3 model. Defines the number of different tokens that can be represented by the
39
+ `inputs_ids` passed when calling [`Qwen3Model`]
40
+ hidden_size (`int`, *optional*, defaults to 4096):
41
+ Dimension of the hidden representations.
42
+ intermediate_size (`int`, *optional*, defaults to 22016):
43
+ Dimension of the MLP representations.
44
+ num_hidden_layers (`int`, *optional*, defaults to 32):
45
+ Number of hidden layers in the Transformer encoder.
46
+ num_attention_heads (`int`, *optional*, defaults to 32):
47
+ Number of attention heads for each attention layer in the Transformer encoder.
48
+ num_key_value_heads (`int`, *optional*, defaults to 32):
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
+ head_dim (`int`, *optional*, defaults to 128):
56
+ The attention head dimension.
57
+ hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
58
+ The non-linear activation function (function or string) in the decoder.
59
+ max_position_embeddings (`int`, *optional*, defaults to 32768):
60
+ The maximum sequence length that this model might ever be used with.
61
+ initializer_range (`float`, *optional*, defaults to 0.02):
62
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
63
+ rms_norm_eps (`float`, *optional*, defaults to 1e-06):
64
+ The epsilon used by the rms normalization layers.
65
+ use_cache (`bool`, *optional*, defaults to `True`):
66
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
67
+ relevant if `config.is_decoder=True`.
68
+ tie_word_embeddings (`bool`, *optional*, defaults to `False`):
69
+ Whether the model's input and output word embeddings should be tied.
70
+ rope_theta (`float`, *optional*, defaults to 10000.0):
71
+ The base period of the RoPE embeddings.
72
+ rope_scaling (`Dict`, *optional*):
73
+ Dictionary containing the scaling configuration for the RoPE embeddings. NOTE: if you apply new rope type
74
+ and you expect the model to work on longer `max_position_embeddings`, we recommend you to update this value
75
+ accordingly.
76
+ Expected contents:
77
+ `rope_type` (`str`):
78
+ The sub-variant of RoPE to use. Can be one of ['default', 'linear', 'dynamic', 'yarn', 'longrope',
79
+ 'llama3'], with 'default' being the original RoPE implementation.
80
+ `factor` (`float`, *optional*):
81
+ Used with all rope types except 'default'. The scaling factor to apply to the RoPE embeddings. In
82
+ most scaling types, a `factor` of x will enable the model to handle sequences of length x *
83
+ original maximum pre-trained length.
84
+ `original_max_position_embeddings` (`int`, *optional*):
85
+ Used with 'dynamic', 'longrope' and 'llama3'. The original max position embeddings used during
86
+ pretraining.
87
+ `attention_factor` (`float`, *optional*):
88
+ Used with 'yarn' and 'longrope'. The scaling factor to be applied on the attention
89
+ computation. If unspecified, it defaults to value recommended by the implementation, using the
90
+ `factor` field to infer the suggested value.
91
+ `beta_fast` (`float`, *optional*):
92
+ Only used with 'yarn'. Parameter to set the boundary for extrapolation (only) in the linear
93
+ ramp function. If unspecified, it defaults to 32.
94
+ `beta_slow` (`float`, *optional*):
95
+ Only used with 'yarn'. Parameter to set the boundary for interpolation (only) in the linear
96
+ ramp function. If unspecified, it defaults to 1.
97
+ `short_factor` (`List[float]`, *optional*):
98
+ Only used with 'longrope'. The scaling factor to be applied to short contexts (<
99
+ `original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
100
+ size divided by the number of attention heads divided by 2
101
+ `long_factor` (`List[float]`, *optional*):
102
+ Only used with 'longrope'. The scaling factor to be applied to long contexts (<
103
+ `original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
104
+ size divided by the number of attention heads divided by 2
105
+ `low_freq_factor` (`float`, *optional*):
106
+ Only used with 'llama3'. Scaling factor applied to low frequency components of the RoPE
107
+ `high_freq_factor` (`float`, *optional*):
108
+ Only used with 'llama3'. Scaling factor applied to high frequency components of the RoPE
109
+ attention_bias (`bool`, defaults to `False`, *optional*, defaults to `False`):
110
+ Whether to use a bias in the query, key, value and output projection layers during self-attention.
111
+ use_sliding_window (`bool`, *optional*, defaults to `False`):
112
+ Whether to use sliding window attention.
113
+ sliding_window (`int`, *optional*, defaults to 4096):
114
+ Sliding window attention (SWA) window size. If not specified, will default to `4096`.
115
+ max_window_layers (`int`, *optional*, defaults to 28):
116
+ The number of layers that use SWA (Sliding Window Attention). The bottom layers use SWA while the top use full attention.
117
+ attention_dropout (`float`, *optional*, defaults to 0.0):
118
+ The dropout ratio for the attention probabilities.
119
+
120
+ ```python
121
+ >>> from transformers import Qwen3Model, Qwen3Config
122
+
123
+ >>> # Initializing a Qwen3 style configuration
124
+ >>> configuration = Qwen3Config()
125
+
126
+ >>> # Initializing a model from the Qwen3-8B style configuration
127
+ >>> model = Qwen3Model(configuration)
128
+
129
+ >>> # Accessing the model configuration
130
+ >>> configuration = model.config
131
+ ```"""
132
+
133
+ model_type = "qwen3"
134
+ keys_to_ignore_at_inference = ["past_key_values"]
135
+
136
+ # Default tensor parallel plan for base model `Qwen3`
137
+ base_model_tp_plan = {
138
+ "layers.*.self_attn.q_proj": "colwise",
139
+ "layers.*.self_attn.k_proj": "colwise",
140
+ "layers.*.self_attn.v_proj": "colwise",
141
+ "layers.*.self_attn.o_proj": "rowwise",
142
+ "layers.*.mlp.gate_proj": "colwise",
143
+ "layers.*.mlp.up_proj": "colwise",
144
+ "layers.*.mlp.down_proj": "rowwise",
145
+ }
146
+ base_model_pp_plan = {
147
+ "embed_tokens": (["input_ids"], ["inputs_embeds"]),
148
+ "layers": (["hidden_states", "attention_mask"], ["hidden_states"]),
149
+ "norm": (["hidden_states"], ["hidden_states"]),
150
+ }
151
+
152
+ def __init__(
153
+ self,
154
+ vocab_size=151936,
155
+ hidden_size=4096,
156
+ intermediate_size=22016,
157
+ num_hidden_layers=32,
158
+ num_attention_heads=32,
159
+ num_key_value_heads=32,
160
+ head_dim=128,
161
+ hidden_act="silu",
162
+ max_position_embeddings=32768,
163
+ initializer_range=0.02,
164
+ rms_norm_eps=1e-6,
165
+ use_cache=True,
166
+ tie_word_embeddings=False,
167
+ rope_theta=10000.0,
168
+ rope_scaling=None,
169
+ attention_bias=False,
170
+ use_sliding_window=False,
171
+ sliding_window=4096,
172
+ max_window_layers=28,
173
+ attention_dropout=0.0,
174
+ **kwargs,
175
+ ):
176
+ self.vocab_size = vocab_size
177
+ self.max_position_embeddings = max_position_embeddings
178
+ self.hidden_size = hidden_size
179
+ self.intermediate_size = intermediate_size
180
+ self.num_hidden_layers = num_hidden_layers
181
+ self.num_attention_heads = num_attention_heads
182
+ self.use_sliding_window = use_sliding_window
183
+ self.sliding_window = sliding_window # we check `use_sliding_window` in the modeling code
184
+ self.max_window_layers = max_window_layers
185
+
186
+ # for backward compatibility
187
+ if num_key_value_heads is None:
188
+ num_key_value_heads = num_attention_heads
189
+
190
+ self.num_key_value_heads = num_key_value_heads
191
+ self.head_dim = head_dim
192
+ self.hidden_act = hidden_act
193
+ self.initializer_range = initializer_range
194
+ self.rms_norm_eps = rms_norm_eps
195
+ self.use_cache = use_cache
196
+ self.rope_theta = rope_theta
197
+ self.rope_scaling = rope_scaling
198
+ self.attention_bias = attention_bias
199
+ self.attention_dropout = attention_dropout
200
+ # Validate the correctness of rotary position embeddings parameters
201
+ # BC: if there is a 'type' field, move it to 'rope_type'.
202
+ if self.rope_scaling is not None and "type" in self.rope_scaling:
203
+ self.rope_scaling["rope_type"] = self.rope_scaling["type"]
204
+ rope_config_validation(self)
205
+
206
+ super().__init__(
207
+ tie_word_embeddings=tie_word_embeddings,
208
+ **kwargs,
209
+ )
210
+
211
+
212
+ __all__ = ["Qwen3Config"]
diffusion_cache_utils.py ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from transformers.cache_utils import DynamicCache
3
+ from typing import Optional, List, Tuple, Dict, Any
4
+
5
+ class DiffusionDynamicCache(DynamicCache):
6
+ def __init__(self, num_hidden_layers: Optional[int] = None):
7
+ super().__init__(num_hidden_layers)
8
+
9
+ def full_update(
10
+ self,
11
+ new_kv: Tuple,
12
+ cache_kwargs: Optional[Dict[str, Any]] = None,
13
+ ):
14
+ for i, (key, val) in enumerate(new_kv):
15
+ self.key_cache[i] = torch.cat([self.key_cache[i], key], dim=-2)
16
+ self.value_cache[i] = torch.cat([self.value_cache[i], val], dim=-2)
17
+
18
+ def select_partial(
19
+ self,
20
+ indices: torch.Tensor,
21
+ ):
22
+ for i in range(len(self.key_cache)):
23
+ self.key_cache[i] = self.key_cache[i][:, :, indices, :]
24
+ self.value_cache[i] = self.value_cache[i][:, :, indices, :]
25
+
26
+ def batch_select_minibatch(self, indices: torch.Tensor):
27
+ """Only keep the `indices` in the batch dimension of the cache. Used in contrastive search."""
28
+ for layer_idx in range(len(self)):
29
+ self.key_cache[layer_idx] = self.key_cache[layer_idx][:indices, ...]
30
+ self.value_cache[layer_idx] = self.value_cache[layer_idx][:indices, ...]
modeling_qwen3_refusion.py ADDED
@@ -0,0 +1,1138 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
2
+ # This file was automatically generated from src/transformers/models/qwen3/modular_qwen3.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.py file directly. One of our CI enforces this.
6
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
7
+ # coding=utf-8
8
+ # Copyright 2025 The Qwen team, Alibaba Group and the HuggingFace Inc. team. All rights reserved.
9
+ #
10
+ # Licensed under the Apache License, Version 2.0 (the "License");
11
+ # you may not use this file except in compliance with the License.
12
+ # You may obtain a copy of the License at
13
+ #
14
+ # http://www.apache.org/licenses/LICENSE-2.0
15
+ #
16
+ # Unless required by applicable law or agreed to in writing, software
17
+ # distributed under the License is distributed on an "AS IS" BASIS,
18
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19
+ # See the License for the specific language governing permissions and
20
+ # limitations under the License.
21
+
22
+ from typing import Callable, Optional, Tuple, Union
23
+
24
+ import torch
25
+ from torch import nn
26
+
27
+ from transformers.activations import ACT2FN
28
+ from transformers.cache_utils import Cache, DynamicCache, SlidingWindowCache, StaticCache
29
+ from transformers.generation import GenerationMixin
30
+ from transformers.integrations import use_kernel_forward_from_hub
31
+ from transformers.modeling_attn_mask_utils import AttentionMaskConverter
32
+ from transformers.modeling_flash_attention_utils import FlashAttentionKwargs
33
+ from transformers.modeling_layers import GradientCheckpointingLayer
34
+ from transformers.modeling_outputs import (
35
+ BaseModelOutputWithPast,
36
+ CausalLMOutputWithPast,
37
+ QuestionAnsweringModelOutput,
38
+ SequenceClassifierOutputWithPast,
39
+ TokenClassifierOutput,
40
+ )
41
+ from transformers.modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update
42
+ from transformers.modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
43
+ from transformers.processing_utils import Unpack
44
+ from transformers.utils import LossKwargs, auto_docstring, can_return_tuple, is_torch_flex_attn_available, logging
45
+ from .configuration_qwen3 import Qwen3Config
46
+ from .diffusion_cache_utils import DiffusionDynamicCache
47
+
48
+ if is_torch_flex_attn_available():
49
+ from torch.nn.attention.flex_attention import BlockMask
50
+
51
+ from transformers.integrations.flex_attention import make_flex_block_causal_mask
52
+
53
+
54
+ logger = logging.get_logger(__name__)
55
+
56
+
57
+ @use_kernel_forward_from_hub("RMSNorm")
58
+ class Qwen3RMSNorm(nn.Module):
59
+ def __init__(self, hidden_size, eps=1e-6):
60
+ """
61
+ Qwen3RMSNorm is equivalent to T5LayerNorm
62
+ """
63
+ super().__init__()
64
+ self.weight = nn.Parameter(torch.ones(hidden_size))
65
+ self.variance_epsilon = eps
66
+
67
+ def forward(self, hidden_states):
68
+ input_dtype = hidden_states.dtype
69
+ hidden_states = hidden_states.to(torch.float32)
70
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
71
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
72
+ return self.weight * hidden_states.to(input_dtype)
73
+
74
+ def extra_repr(self):
75
+ return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
76
+
77
+
78
+ class Qwen3MLP(nn.Module):
79
+ def __init__(self, config):
80
+ super().__init__()
81
+ self.config = config
82
+ self.hidden_size = config.hidden_size
83
+ self.intermediate_size = config.intermediate_size
84
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
85
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
86
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
87
+ self.act_fn = ACT2FN[config.hidden_act]
88
+
89
+ def forward(self, x):
90
+ down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
91
+ return down_proj
92
+
93
+
94
+ def rotate_half(x):
95
+ """Rotates half the hidden dims of the input."""
96
+ x1 = x[..., : x.shape[-1] // 2]
97
+ x2 = x[..., x.shape[-1] // 2 :]
98
+ return torch.cat((-x2, x1), dim=-1)
99
+
100
+
101
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
102
+ """Applies Rotary Position Embedding to the query and key tensors.
103
+
104
+ Args:
105
+ q (`torch.Tensor`): The query tensor.
106
+ k (`torch.Tensor`): The key tensor.
107
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
108
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
109
+ position_ids (`torch.Tensor`, *optional*):
110
+ Deprecated and unused.
111
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
112
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
113
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
114
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
115
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
116
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
117
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
118
+ Returns:
119
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
120
+ """
121
+ cos = cos.unsqueeze(unsqueeze_dim)
122
+ sin = sin.unsqueeze(unsqueeze_dim)
123
+ q_embed = (q * cos) + (rotate_half(q) * sin)
124
+ k_embed = (k * cos) + (rotate_half(k) * sin)
125
+ return q_embed, k_embed
126
+
127
+
128
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
129
+ """
130
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
131
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
132
+ """
133
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
134
+ if n_rep == 1:
135
+ return hidden_states
136
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
137
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
138
+
139
+
140
+ def eager_attention_forward(
141
+ module: nn.Module,
142
+ query: torch.Tensor,
143
+ key: torch.Tensor,
144
+ value: torch.Tensor,
145
+ attention_mask: Optional[torch.Tensor],
146
+ scaling: float,
147
+ dropout: float = 0.0,
148
+ **kwargs,
149
+ ):
150
+ key_states = repeat_kv(key, module.num_key_value_groups)
151
+ value_states = repeat_kv(value, module.num_key_value_groups)
152
+
153
+ attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
154
+ if attention_mask is not None:
155
+ causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
156
+ attn_weights = attn_weights + causal_mask
157
+
158
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
159
+ attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
160
+ attn_output = torch.matmul(attn_weights, value_states)
161
+ attn_output = attn_output.transpose(1, 2).contiguous()
162
+
163
+ return attn_output, attn_weights
164
+
165
+
166
+ class Qwen3Attention(nn.Module):
167
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
168
+
169
+ def __init__(self, config: Qwen3Config, layer_idx: int):
170
+ super().__init__()
171
+ self.config = config
172
+ self.layer_idx = layer_idx
173
+ self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
174
+ self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
175
+ self.scaling = self.head_dim**-0.5
176
+ self.attention_dropout = config.attention_dropout
177
+ self.is_causal = True
178
+
179
+ self.q_proj = nn.Linear(
180
+ config.hidden_size, config.num_attention_heads * self.head_dim, bias=config.attention_bias
181
+ )
182
+ self.k_proj = nn.Linear(
183
+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
184
+ )
185
+ self.v_proj = nn.Linear(
186
+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
187
+ )
188
+ self.o_proj = nn.Linear(
189
+ config.num_attention_heads * self.head_dim, config.hidden_size, bias=config.attention_bias
190
+ )
191
+ self.q_norm = Qwen3RMSNorm(self.head_dim, eps=config.rms_norm_eps) # unlike olmo, only on the head dim!
192
+ self.k_norm = Qwen3RMSNorm(self.head_dim, eps=config.rms_norm_eps) # thus post q_norm does not need reshape
193
+ self.sliding_window = config.sliding_window
194
+ if not (
195
+ self.config.use_sliding_window
196
+ and getattr(self.config, "sliding_window", None) is not None
197
+ and self.layer_idx >= self.config.max_window_layers
198
+ ):
199
+ self.sliding_window = None
200
+
201
+ def forward(
202
+ self,
203
+ hidden_states: torch.Tensor,
204
+ position_embeddings: Tuple[torch.Tensor, torch.Tensor],
205
+ attention_mask: Optional[torch.Tensor],
206
+ past_key_value: Optional[Cache] = None,
207
+ cache_position: Optional[torch.LongTensor] = None,
208
+ **kwargs: Unpack[FlashAttentionKwargs],
209
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
210
+ input_shape = hidden_states.shape[:-1]
211
+ hidden_shape = (*input_shape, -1, self.head_dim)
212
+
213
+ query_states = self.q_norm(self.q_proj(hidden_states).view(hidden_shape)).transpose(1, 2)
214
+ key_states = self.k_norm(self.k_proj(hidden_states).view(hidden_shape)).transpose(1, 2)
215
+ value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
216
+
217
+ cos, sin = position_embeddings
218
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
219
+
220
+ if past_key_value is not None:
221
+ # sin and cos are specific to RoPE models; cache_position needed for the static cache
222
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
223
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
224
+
225
+ attention_interface: Callable = eager_attention_forward
226
+ if self.config._attn_implementation != "eager":
227
+ if self.config._attn_implementation == "sdpa" and kwargs.get("output_attentions", False):
228
+ logger.warning_once(
229
+ "`torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to "
230
+ 'eager attention. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.'
231
+ )
232
+ else:
233
+ attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
234
+
235
+ attn_output, attn_weights = attention_interface(
236
+ self,
237
+ query_states,
238
+ key_states,
239
+ value_states,
240
+ attention_mask,
241
+ dropout=0.0 if not self.training else self.attention_dropout,
242
+ scaling=self.scaling,
243
+ sliding_window=self.sliding_window, # diff with Llama
244
+ **kwargs,
245
+ )
246
+
247
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
248
+ attn_output = self.o_proj(attn_output)
249
+ return attn_output, attn_weights
250
+
251
+
252
+ class Qwen3DecoderLayer(GradientCheckpointingLayer):
253
+ def __init__(self, config: Qwen3Config, layer_idx: int):
254
+ super().__init__()
255
+ self.hidden_size = config.hidden_size
256
+ self.self_attn = Qwen3Attention(config=config, layer_idx=layer_idx)
257
+ self.mlp = Qwen3MLP(config)
258
+ self.input_layernorm = Qwen3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
259
+ self.post_attention_layernorm = Qwen3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
260
+ if (
261
+ config.sliding_window and config._attn_implementation != "flash_attention_2"
262
+ ): # diff with Llama is this warning
263
+ logger.warning_once(
264
+ f"Sliding Window Attention is enabled but not implemented for `{config._attn_implementation}`; "
265
+ "unexpected results may be encountered."
266
+ )
267
+
268
+ def forward(
269
+ self,
270
+ hidden_states: torch.Tensor,
271
+ attention_mask: Optional[torch.Tensor] = None,
272
+ position_ids: Optional[torch.LongTensor] = None,
273
+ past_key_value: Optional[Cache] = None,
274
+ output_attentions: Optional[bool] = False,
275
+ use_cache: Optional[bool] = False,
276
+ cache_position: Optional[torch.LongTensor] = None,
277
+ position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, # necessary, but kept here for BC
278
+ **kwargs: Unpack[FlashAttentionKwargs],
279
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
280
+ residual = hidden_states
281
+ hidden_states = self.input_layernorm(hidden_states)
282
+
283
+ # Self Attention
284
+ hidden_states, self_attn_weights = self.self_attn(
285
+ hidden_states=hidden_states,
286
+ attention_mask=attention_mask,
287
+ position_ids=position_ids,
288
+ past_key_value=past_key_value,
289
+ output_attentions=output_attentions,
290
+ use_cache=use_cache,
291
+ cache_position=cache_position,
292
+ position_embeddings=position_embeddings,
293
+ **kwargs,
294
+ )
295
+ hidden_states = residual + hidden_states
296
+
297
+ # Fully Connected
298
+ residual = hidden_states
299
+ hidden_states = self.post_attention_layernorm(hidden_states)
300
+ hidden_states = self.mlp(hidden_states)
301
+ hidden_states = residual + hidden_states
302
+
303
+ outputs = (hidden_states,)
304
+ if output_attentions:
305
+ outputs += (self_attn_weights,)
306
+
307
+ return outputs
308
+
309
+
310
+ @auto_docstring
311
+ class Qwen3PreTrainedModel(PreTrainedModel):
312
+ config_class = Qwen3Config
313
+ base_model_prefix = "model"
314
+ supports_gradient_checkpointing = True
315
+ _no_split_modules = ["Qwen3DecoderLayer"]
316
+ _skip_keys_device_placement = ["past_key_values"]
317
+ _supports_flash_attn_2 = True
318
+ _supports_sdpa = True
319
+ _supports_flex_attn = True
320
+ _supports_cache_class = True
321
+ _supports_quantized_cache = True
322
+ _supports_static_cache = True
323
+ _supports_attention_backend = True
324
+
325
+ def _init_weights(self, module):
326
+ std = self.config.initializer_range
327
+ if isinstance(module, nn.Linear):
328
+ module.weight.data.normal_(mean=0.0, std=std)
329
+ if module.bias is not None:
330
+ module.bias.data.zero_()
331
+ elif isinstance(module, nn.Embedding):
332
+ module.weight.data.normal_(mean=0.0, std=std)
333
+ if module.padding_idx is not None:
334
+ module.weight.data[module.padding_idx].zero_()
335
+ elif isinstance(module, Qwen3RMSNorm):
336
+ module.weight.data.fill_(1.0)
337
+
338
+
339
+ class Qwen3RotaryEmbedding(nn.Module):
340
+ def __init__(self, config: Qwen3Config, device=None):
341
+ super().__init__()
342
+ # BC: "rope_type" was originally "type"
343
+ if hasattr(config, "rope_scaling") and config.rope_scaling is not None:
344
+ self.rope_type = config.rope_scaling.get("rope_type", config.rope_scaling.get("type"))
345
+ else:
346
+ self.rope_type = "default"
347
+ self.max_seq_len_cached = config.max_position_embeddings
348
+ self.original_max_seq_len = config.max_position_embeddings
349
+
350
+ self.config = config
351
+ self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
352
+
353
+ inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device)
354
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
355
+ self.original_inv_freq = self.inv_freq
356
+
357
+ @torch.no_grad()
358
+ @dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope)
359
+ def forward(self, x, position_ids):
360
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device)
361
+ position_ids_expanded = position_ids[:, None, :].float()
362
+
363
+ device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
364
+ with torch.autocast(device_type=device_type, enabled=False): # Force float32
365
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
366
+ emb = torch.cat((freqs, freqs), dim=-1)
367
+ cos = emb.cos() * self.attention_scaling
368
+ sin = emb.sin() * self.attention_scaling
369
+
370
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
371
+
372
+
373
+ @auto_docstring
374
+ class Qwen3Model(Qwen3PreTrainedModel):
375
+ def __init__(self, config: Qwen3Config):
376
+ super().__init__(config)
377
+ self.padding_idx = config.pad_token_id
378
+ self.vocab_size = config.vocab_size
379
+
380
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
381
+ self.layers = nn.ModuleList(
382
+ [Qwen3DecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
383
+ )
384
+ self.norm = Qwen3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
385
+ self.rotary_emb = Qwen3RotaryEmbedding(config=config)
386
+ self.gradient_checkpointing = False
387
+
388
+ # Initialize weights and apply final processing
389
+ self.post_init()
390
+
391
+ def get_input_embeddings(self):
392
+ return self.embed_tokens
393
+
394
+ def set_input_embeddings(self, value):
395
+ self.embed_tokens = value
396
+
397
+ @can_return_tuple
398
+ @auto_docstring
399
+ def forward(
400
+ self,
401
+ input_ids: Optional[torch.LongTensor] = None,
402
+ attention_mask: Optional[torch.Tensor] = None,
403
+ position_ids: Optional[torch.LongTensor] = None,
404
+ past_key_values: Optional[Cache] = None,
405
+ inputs_embeds: Optional[torch.FloatTensor] = None,
406
+ use_cache: Optional[bool] = None,
407
+ output_attentions: Optional[bool] = None,
408
+ output_hidden_states: Optional[bool] = None,
409
+ cache_position: Optional[torch.LongTensor] = None,
410
+ **flash_attn_kwargs: Unpack[FlashAttentionKwargs],
411
+ ) -> BaseModelOutputWithPast:
412
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
413
+ output_hidden_states = (
414
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
415
+ )
416
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
417
+
418
+ if (input_ids is None) ^ (inputs_embeds is not None):
419
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
420
+
421
+ if self.gradient_checkpointing and self.training and use_cache:
422
+ logger.warning_once(
423
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`."
424
+ )
425
+ use_cache = False
426
+
427
+ # TODO (joao): remove this exception in v4.56 -- it exists for users that try to pass a legacy cache
428
+ if not isinstance(past_key_values, (type(None), Cache)):
429
+ raise ValueError("The `past_key_values` should be either a `Cache` object or `None`.")
430
+
431
+ if inputs_embeds is None:
432
+ inputs_embeds = self.embed_tokens(input_ids)
433
+
434
+ if use_cache and past_key_values is None:
435
+ past_key_values = DiffusionDynamicCache()
436
+
437
+ if cache_position is None:
438
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
439
+ cache_position = torch.arange(
440
+ past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
441
+ )
442
+
443
+ if position_ids is None:
444
+ position_ids = cache_position.unsqueeze(0)
445
+
446
+ causal_mask = self._update_causal_mask(
447
+ attention_mask, inputs_embeds, cache_position, past_key_values, output_attentions
448
+ )
449
+
450
+ hidden_states = inputs_embeds
451
+
452
+ # create position embeddings to be shared across the decoder layers
453
+ position_embeddings = self.rotary_emb(hidden_states, position_ids)
454
+
455
+ # decoder layers
456
+ all_hidden_states = () if output_hidden_states else None
457
+ all_self_attns = () if output_attentions else None
458
+
459
+ for decoder_layer in self.layers[: self.config.num_hidden_layers]:
460
+ if output_hidden_states:
461
+ all_hidden_states += (hidden_states,)
462
+
463
+ layer_outputs = decoder_layer(
464
+ hidden_states,
465
+ attention_mask=causal_mask,
466
+ position_ids=position_ids,
467
+ past_key_value=past_key_values,
468
+ output_attentions=output_attentions,
469
+ use_cache=use_cache,
470
+ cache_position=cache_position,
471
+ position_embeddings=position_embeddings,
472
+ **flash_attn_kwargs,
473
+ )
474
+
475
+ hidden_states = layer_outputs[0]
476
+
477
+ if output_attentions:
478
+ all_self_attns += (layer_outputs[1],)
479
+
480
+ hidden_states = self.norm(hidden_states)
481
+
482
+ # add hidden states from the last decoder layer
483
+ if output_hidden_states:
484
+ all_hidden_states += (hidden_states,)
485
+
486
+ return BaseModelOutputWithPast(
487
+ last_hidden_state=hidden_states,
488
+ past_key_values=past_key_values if use_cache else None,
489
+ hidden_states=all_hidden_states,
490
+ attentions=all_self_attns,
491
+ )
492
+
493
+ def _update_causal_mask(
494
+ self,
495
+ attention_mask: Union[torch.Tensor, "BlockMask"],
496
+ input_tensor: torch.Tensor,
497
+ cache_position: torch.Tensor,
498
+ past_key_values: Cache,
499
+ output_attentions: bool = False,
500
+ ):
501
+ if self.config._attn_implementation == "flash_attention_2":
502
+ if attention_mask is not None and past_key_values is not None:
503
+ is_padding_right = attention_mask[:, -1].sum().item() != input_tensor.size()[0]
504
+ if is_padding_right:
505
+ raise ValueError(
506
+ "You are attempting to perform batched generation with padding_side='right'"
507
+ " this may lead to unexpected behaviour for Flash Attention version of Qwen3. Make sure to "
508
+ " call `tokenizer.padding_side = 'left'` before tokenizing the input. "
509
+ )
510
+ if attention_mask is not None and 0.0 in attention_mask:
511
+ return attention_mask
512
+ return None
513
+ if self.config._attn_implementation == "flex_attention":
514
+ if isinstance(attention_mask, torch.Tensor):
515
+ attention_mask = make_flex_block_causal_mask(attention_mask)
516
+ return attention_mask
517
+
518
+ # For SDPA, when possible, we will rely on its `is_causal` argument instead of its `attn_mask` argument, in
519
+ # order to dispatch on Flash Attention 2. This feature is not compatible with static cache, as SDPA will fail
520
+ # to infer the attention mask.
521
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
522
+ using_static_cache = isinstance(past_key_values, StaticCache)
523
+ using_sliding_window_cache = isinstance(past_key_values, SlidingWindowCache)
524
+
525
+ # When output attentions is True, sdpa implementation's forward method calls the eager implementation's forward
526
+ if (
527
+ self.config._attn_implementation == "sdpa"
528
+ and not (using_static_cache or using_sliding_window_cache)
529
+ and not output_attentions
530
+ ):
531
+ if AttentionMaskConverter._ignore_causal_mask_sdpa(
532
+ attention_mask,
533
+ inputs_embeds=input_tensor,
534
+ past_key_values_length=past_seen_tokens,
535
+ sliding_window=self.config.sliding_window,
536
+ is_training=self.training,
537
+ ):
538
+ return None
539
+
540
+ dtype = input_tensor.dtype
541
+ min_dtype = torch.finfo(dtype).min
542
+ sequence_length = input_tensor.shape[1]
543
+ # SlidingWindowCache or StaticCache
544
+ if using_sliding_window_cache or using_static_cache:
545
+ target_length = past_key_values.get_max_cache_shape()
546
+ # DynamicCache or no cache
547
+ else:
548
+ target_length = (
549
+ attention_mask.shape[-1]
550
+ if isinstance(attention_mask, torch.Tensor)
551
+ else past_seen_tokens + sequence_length + 1
552
+ )
553
+
554
+ # In case the provided `attention` mask is 2D, we generate a causal mask here (4D).
555
+ causal_mask = self._prepare_4d_causal_attention_mask_with_cache_position(
556
+ attention_mask,
557
+ sequence_length=sequence_length,
558
+ target_length=target_length,
559
+ dtype=dtype,
560
+ cache_position=cache_position,
561
+ batch_size=input_tensor.shape[0],
562
+ config=self.config,
563
+ past_key_values=past_key_values,
564
+ )
565
+
566
+ if (
567
+ self.config._attn_implementation == "sdpa"
568
+ and attention_mask is not None
569
+ and attention_mask.device.type in ["cuda", "xpu", "npu"]
570
+ and not output_attentions
571
+ ):
572
+ # Attend to all tokens in fully masked rows in the causal_mask, for example the relevant first rows when
573
+ # using left padding. This is required by F.scaled_dot_product_attention memory-efficient attention path.
574
+ # Details: https://github.com/pytorch/pytorch/issues/110213
575
+ causal_mask = AttentionMaskConverter._unmask_unattended(causal_mask, min_dtype)
576
+
577
+ return causal_mask
578
+
579
+ @staticmethod
580
+ def _prepare_4d_causal_attention_mask_with_cache_position(
581
+ attention_mask: torch.Tensor,
582
+ sequence_length: int,
583
+ target_length: int,
584
+ dtype: torch.dtype,
585
+ cache_position: torch.Tensor,
586
+ batch_size: int,
587
+ config: Qwen3Config,
588
+ past_key_values: Cache,
589
+ ):
590
+ """
591
+ Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape
592
+ `(batch_size, key_value_length)`, or if the input `attention_mask` is already 4D, do nothing.
593
+
594
+ Args:
595
+ attention_mask (`torch.Tensor`):
596
+ A 2D attention mask of shape `(batch_size, key_value_length)` or a 4D attention mask of shape `(batch_size, 1, query_length, key_value_length)`.
597
+ sequence_length (`int`):
598
+ The sequence length being processed.
599
+ target_length (`int`):
600
+ The target length: when generating with static cache, the mask should be as long as the static cache, to account for the 0 padding, the part of the cache that is not filled yet.
601
+ dtype (`torch.dtype`):
602
+ The dtype to use for the 4D attention mask.
603
+ cache_position (`torch.Tensor`):
604
+ Indices depicting the position of the input sequence tokens in the sequence.
605
+ batch_size (`torch.Tensor`):
606
+ Batch size.
607
+ config (`Qwen3Config`):
608
+ The model's configuration class
609
+ past_key_values (`Cache`):
610
+ The cache class that is being used currently to generate
611
+ """
612
+ if attention_mask is not None and attention_mask.dim() == 4:
613
+ # In this case we assume that the mask comes already in inverted form and requires no inversion or slicing.
614
+ causal_mask = attention_mask
615
+ else:
616
+ min_dtype = torch.finfo(dtype).min
617
+ causal_mask = torch.full(
618
+ (sequence_length, target_length), fill_value=min_dtype, dtype=dtype, device=cache_position.device
619
+ )
620
+ diagonal_attend_mask = torch.arange(target_length, device=cache_position.device) > cache_position.reshape(
621
+ -1, 1
622
+ )
623
+ text_config = config.get_text_config()
624
+ if getattr(text_config, "use_sliding_window", True) and text_config.sliding_window is not None:
625
+ # if we have sliding window, we should not attend to tokens beyond sliding window length, so we mask them out also
626
+ # the check is needed to verify is current checkpoint was trained with sliding window or not
627
+ if not isinstance(past_key_values, SlidingWindowCache) or sequence_length > target_length:
628
+ sliding_attend_mask = torch.arange(target_length, device=cache_position.device) <= (
629
+ cache_position.reshape(-1, 1) - text_config.sliding_window
630
+ )
631
+ diagonal_attend_mask.bitwise_or_(sliding_attend_mask)
632
+ causal_mask *= diagonal_attend_mask
633
+ causal_mask = causal_mask[None, None, :, :].expand(batch_size, 1, -1, -1)
634
+ if attention_mask is not None:
635
+ causal_mask = causal_mask.clone() # copy to contiguous memory for in-place edit
636
+ if attention_mask.shape[-1] > target_length:
637
+ attention_mask = attention_mask[:, :target_length]
638
+ mask_length = attention_mask.shape[-1]
639
+ padding_mask = causal_mask[:, :, :, :mask_length] + attention_mask[:, None, None, :].to(
640
+ causal_mask.device
641
+ )
642
+ padding_mask = padding_mask == 0
643
+ causal_mask[:, :, :, :mask_length] = causal_mask[:, :, :, :mask_length].masked_fill(
644
+ padding_mask, min_dtype
645
+ )
646
+ return causal_mask
647
+
648
+
649
+ class KwargsForCausalLM(FlashAttentionKwargs, LossKwargs): ...
650
+
651
+
652
+ def forward_process(input_ids, attention_mask, prompt_lengths, mask_token_id, eps=1e-3):
653
+ import random
654
+ IGNORE_INDEX = -100
655
+ slot_size_set = [4, 8, 16, 32]
656
+ device = input_ids.device
657
+
658
+ batch_size, seq_length = input_ids.shape
659
+
660
+ input_ids = input_ids.tolist()
661
+ prompt_lengths = prompt_lengths.squeeze(1).tolist()
662
+ total_lengths = attention_mask.sum(dim=1).tolist()
663
+
664
+ pro_input_ids = []
665
+ pro_labels = []
666
+ pro_masked_indices = []
667
+ pro_p_masks = []
668
+ pro_answer_lengths = []
669
+ pro_position_ids = []
670
+
671
+ for i in range(batch_size):
672
+ slot_size = random.choice(slot_size_set)
673
+ prompt_len = prompt_lengths[i]
674
+ total_len = int(total_lengths[i])
675
+ pad_len = seq_length - total_len
676
+
677
+ input_id = input_ids[i][:prompt_len]
678
+ end_id = input_ids[i][prompt_len:total_len]
679
+
680
+ input_label = [IGNORE_INDEX] * len(input_id)
681
+
682
+ # Split end_id into chunks of size slot_size
683
+ answer_slots = [
684
+ end_id[i:i + slot_size]
685
+ for i in range(0, len(end_id), slot_size)
686
+ ]
687
+
688
+ num_answer_slots = len(answer_slots)
689
+ if num_answer_slots == 0:
690
+ continue
691
+
692
+ # Get position ids for prompt and answer parts
693
+ input_position_id = list(range(len(input_id)))
694
+ end_position_id = list(range(len(input_id), len(input_id) + len(end_id)))
695
+ answer_position_slots = [
696
+ end_position_id[i:i + slot_size]
697
+ for i in range(0, len(end_position_id), slot_size)
698
+ ]
699
+
700
+ # Get masked slot indices
701
+ t = random.random()
702
+ p_mask = (1 - eps) * t + eps
703
+ slot_mask = [random.random() < p_mask for _ in range(num_answer_slots)]
704
+
705
+ # Extract masked and unmasked indices from the answer part
706
+ unmasked_indices = [i for i, masked in enumerate(slot_mask) if not masked]
707
+ masked_indices = [i for i, masked in enumerate(slot_mask) if masked]
708
+
709
+ # Shuffle only the unmasked slots
710
+ random.shuffle(unmasked_indices)
711
+
712
+ # Construct the final answer part
713
+ final_end_id = []
714
+ final_answer_label = []
715
+ final_masked_indice = []
716
+ final_position_id = []
717
+
718
+ answer_length = len(end_id)
719
+
720
+ # Process shuffled, unmasked slots (AR task)
721
+ for slot_idx in unmasked_indices:
722
+ slot_content = answer_slots[slot_idx]
723
+ final_end_id.extend(slot_content)
724
+
725
+ ar_label = slot_content[1:] + [IGNORE_INDEX]
726
+ final_answer_label.extend(ar_label)
727
+
728
+ final_masked_indice.extend([False]*(len(slot_content)))
729
+
730
+ final_position_id.extend(answer_position_slots[slot_idx])
731
+
732
+ # Process original order, masked slots (MDM task)
733
+ for slot_idx in masked_indices:
734
+ slot_content = answer_slots[slot_idx]
735
+ final_end_id.extend([mask_token_id] * len(slot_content))
736
+
737
+ final_answer_label.extend(slot_content)
738
+
739
+ final_masked_indice.extend([True]*len(slot_content))
740
+
741
+ final_position_id.extend(answer_position_slots[slot_idx])
742
+
743
+ final_input = input_id + final_end_id + input_ids[i][total_len:]
744
+ final_label = input_label + final_answer_label + [IGNORE_INDEX] * pad_len
745
+ final_masked_indice = [False] * len(input_id) + final_masked_indice + [False] * pad_len
746
+ final_position_id = input_position_id + final_position_id + list(range(total_len, seq_length))
747
+
748
+ assert len(final_input) == len(final_label), f"{len(final_input)}, {len(final_label)}"
749
+ assert len(final_input) == len(final_masked_indice), f"{len(final_input)}, {len(final_masked_indice)}"
750
+ assert len(final_input) == len(final_position_id), f"{len(final_input)}, {len(final_position_id)}"
751
+
752
+
753
+ pro_input_ids.append(torch.tensor(final_input))
754
+ pro_labels.append(torch.tensor(final_label))
755
+ pro_masked_indices.append(torch.tensor(final_masked_indice))
756
+ pro_p_masks.append(torch.tensor(p_mask))
757
+ pro_answer_lengths.append(torch.tensor(answer_length))
758
+ pro_position_ids.append(torch.tensor(final_position_id))
759
+
760
+ pro_p_masks = torch.stack(pro_p_masks).view(-1, 1).repeat(1, seq_length)
761
+ pro_answer_lengths = torch.stack(pro_answer_lengths).view(-1, 1).repeat(1, seq_length)
762
+
763
+ return torch.stack(pro_input_ids).to(device), torch.stack(pro_labels).to(device), torch.stack(pro_masked_indices).to(device), pro_p_masks.to(device), pro_answer_lengths.to(device), torch.stack(pro_position_ids).to(device)
764
+
765
+ @auto_docstring
766
+ class Qwen3ForCausalLM(Qwen3PreTrainedModel, GenerationMixin):
767
+ _tied_weights_keys = ["lm_head.weight"]
768
+ _tp_plan = {"lm_head": "colwise_rep"}
769
+ _pp_plan = {"lm_head": (["hidden_states"], ["logits"])}
770
+
771
+ def __init__(self, config):
772
+ super().__init__(config)
773
+ self.model = Qwen3Model(config)
774
+ self.vocab_size = config.vocab_size
775
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
776
+
777
+ self.mask_token_id = config.mask_token_id
778
+
779
+ # Initialize weights and apply final processing
780
+ self.post_init()
781
+
782
+ def get_input_embeddings(self):
783
+ return self.model.embed_tokens
784
+
785
+ def set_input_embeddings(self, value):
786
+ self.model.embed_tokens = value
787
+
788
+ def get_output_embeddings(self):
789
+ return self.lm_head
790
+
791
+ def set_output_embeddings(self, new_embeddings):
792
+ self.lm_head = new_embeddings
793
+
794
+ def set_decoder(self, decoder):
795
+ self.model = decoder
796
+
797
+ def get_decoder(self):
798
+ return self.model
799
+
800
+ @can_return_tuple
801
+ @auto_docstring
802
+ def forward(
803
+ self,
804
+ input_ids: Optional[torch.LongTensor] = None,
805
+ attention_mask: Optional[torch.Tensor] = None,
806
+ position_ids: Optional[torch.LongTensor] = None,
807
+ prompt_lengths: Optional[torch.LongTensor] = None,
808
+ past_key_values: Optional[Cache] = None,
809
+ inputs_embeds: Optional[torch.FloatTensor] = None,
810
+ labels: Optional[torch.LongTensor] = None,
811
+ use_cache: Optional[bool] = None,
812
+ output_attentions: Optional[bool] = None,
813
+ output_hidden_states: Optional[bool] = None,
814
+ cache_position: Optional[torch.LongTensor] = None,
815
+ logits_to_keep: Union[int, torch.Tensor] = 0,
816
+ **kwargs: Unpack[KwargsForCausalLM],
817
+ ) -> CausalLMOutputWithPast:
818
+ r"""
819
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
820
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
821
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
822
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
823
+
824
+ Example:
825
+
826
+ ```python
827
+ >>> from transformers import AutoTokenizer, Qwen3ForCausalLM
828
+
829
+ >>> model = Qwen3ForCausalLM.from_pretrained("Qwen/Qwen3-8B")
830
+ >>> tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen3-8B")
831
+
832
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
833
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
834
+
835
+ >>> # Generate
836
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
837
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
838
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
839
+ ```"""
840
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
841
+ output_hidden_states = (
842
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
843
+ )
844
+
845
+ if labels is not None:
846
+ input_ids, labels, masked_indices, p_mask, answer_lengths, position_ids = forward_process(input_ids, attention_mask, prompt_lengths, self.mask_token_id)
847
+
848
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
849
+ outputs: BaseModelOutputWithPast = self.model(
850
+ input_ids=input_ids,
851
+ attention_mask=attention_mask,
852
+ position_ids=position_ids,
853
+ past_key_values=past_key_values,
854
+ inputs_embeds=inputs_embeds,
855
+ use_cache=use_cache,
856
+ output_attentions=output_attentions,
857
+ output_hidden_states=output_hidden_states,
858
+ cache_position=cache_position,
859
+ **kwargs,
860
+ )
861
+
862
+ hidden_states = outputs.last_hidden_state
863
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
864
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
865
+ logits = self.lm_head(hidden_states[:, slice_indices, :])
866
+
867
+ loss = None
868
+ if labels is not None:
869
+ com_logits = logits.float()
870
+ # Flatten the tokens
871
+ com_logits = com_logits.view(-1, self.config.vocab_size)
872
+ labels = labels.view(-1) # labels already shift
873
+ masked_indices = masked_indices.view(-1)
874
+ p_mask = p_mask.view(-1)
875
+ answer_lengths = answer_lengths.view(-1)
876
+ labels = labels.to(com_logits.device)
877
+
878
+ # AR loss
879
+ AR_indices = ~masked_indices
880
+ AR_loss = nn.functional.cross_entropy(com_logits[AR_indices], labels[AR_indices], ignore_index=-100, reduction="mean")
881
+
882
+ # MDM loss
883
+ MDM_token_loss = nn.functional.cross_entropy(com_logits[masked_indices], labels[masked_indices], ignore_index=-100, reduction='none') / p_mask[masked_indices]
884
+ MDM_loss = torch.sum(MDM_token_loss / answer_lengths[masked_indices]) / input_ids.shape[0]
885
+
886
+ loss = AR_loss + MDM_loss
887
+
888
+ return CausalLMOutputWithPast(
889
+ loss=loss,
890
+ logits=logits,
891
+ past_key_values=outputs.past_key_values,
892
+ hidden_states=outputs.hidden_states,
893
+ attentions=outputs.attentions,
894
+ )
895
+
896
+
897
+ @auto_docstring(
898
+ custom_intro="""
899
+ The Qwen3 Model transformer with a sequence classification head on top (linear layer).
900
+
901
+ [`Qwen3ForSequenceClassification`] uses the last token in order to do the classification, as other causal models
902
+ (e.g. GPT-2) do.
903
+
904
+ Since it does classification on the last token, it requires to know the position of the last token. If a
905
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
906
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
907
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
908
+ each row of the batch).
909
+ """
910
+ )
911
+ class Qwen3ForSequenceClassification(Qwen3PreTrainedModel):
912
+ def __init__(self, config):
913
+ super().__init__(config)
914
+ self.num_labels = config.num_labels
915
+ self.model = Qwen3Model(config)
916
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
917
+
918
+ # Initialize weights and apply final processing
919
+ self.post_init()
920
+
921
+ def get_input_embeddings(self):
922
+ return self.model.embed_tokens
923
+
924
+ def set_input_embeddings(self, value):
925
+ self.model.embed_tokens = value
926
+
927
+ @can_return_tuple
928
+ @auto_docstring
929
+ def forward(
930
+ self,
931
+ input_ids: Optional[torch.LongTensor] = None,
932
+ attention_mask: Optional[torch.Tensor] = None,
933
+ position_ids: Optional[torch.LongTensor] = None,
934
+ past_key_values: Optional[Cache] = None,
935
+ inputs_embeds: Optional[torch.FloatTensor] = None,
936
+ labels: Optional[torch.LongTensor] = None,
937
+ use_cache: Optional[bool] = None,
938
+ output_attentions: Optional[bool] = None,
939
+ output_hidden_states: Optional[bool] = None,
940
+ ) -> SequenceClassifierOutputWithPast:
941
+ r"""
942
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
943
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
944
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
945
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
946
+ """
947
+
948
+ transformer_outputs: BaseModelOutputWithPast = self.model(
949
+ input_ids,
950
+ attention_mask=attention_mask,
951
+ position_ids=position_ids,
952
+ past_key_values=past_key_values,
953
+ inputs_embeds=inputs_embeds,
954
+ use_cache=use_cache,
955
+ output_attentions=output_attentions,
956
+ output_hidden_states=output_hidden_states,
957
+ )
958
+ hidden_states = transformer_outputs.last_hidden_state
959
+ logits = self.score(hidden_states)
960
+
961
+ if input_ids is not None:
962
+ batch_size = input_ids.shape[0]
963
+ else:
964
+ batch_size = inputs_embeds.shape[0]
965
+
966
+ if self.config.pad_token_id is None and batch_size != 1:
967
+ raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
968
+ if self.config.pad_token_id is None:
969
+ last_non_pad_token = -1
970
+ elif input_ids is not None:
971
+ # To handle both left- and right- padding, we take the rightmost token that is not equal to pad_token_id
972
+ non_pad_mask = (input_ids != self.config.pad_token_id).to(logits.device, torch.int32)
973
+ token_indices = torch.arange(input_ids.shape[-1], device=logits.device, dtype=torch.int32)
974
+ last_non_pad_token = (token_indices * non_pad_mask).argmax(-1)
975
+ else:
976
+ last_non_pad_token = -1
977
+ logger.warning_once(
978
+ f"{self.__class__.__name__} will not detect padding tokens in `inputs_embeds`. Results may be "
979
+ "unexpected if using padding tokens in conjunction with `inputs_embeds.`"
980
+ )
981
+
982
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), last_non_pad_token]
983
+
984
+ loss = None
985
+ if labels is not None:
986
+ loss = self.loss_function(logits=logits, labels=labels, pooled_logits=pooled_logits, config=self.config)
987
+
988
+ return SequenceClassifierOutputWithPast(
989
+ loss=loss,
990
+ logits=pooled_logits,
991
+ past_key_values=transformer_outputs.past_key_values,
992
+ hidden_states=transformer_outputs.hidden_states,
993
+ attentions=transformer_outputs.attentions,
994
+ )
995
+
996
+
997
+ @auto_docstring
998
+ class Qwen3ForTokenClassification(Qwen3PreTrainedModel):
999
+ def __init__(self, config):
1000
+ super().__init__(config)
1001
+ self.num_labels = config.num_labels
1002
+ self.model = Qwen3Model(config)
1003
+ if getattr(config, "classifier_dropout", None) is not None:
1004
+ classifier_dropout = config.classifier_dropout
1005
+ elif getattr(config, "hidden_dropout", None) is not None:
1006
+ classifier_dropout = config.hidden_dropout
1007
+ else:
1008
+ classifier_dropout = 0.1
1009
+ self.dropout = nn.Dropout(classifier_dropout)
1010
+ self.score = nn.Linear(config.hidden_size, config.num_labels)
1011
+
1012
+ # Initialize weights and apply final processing
1013
+ self.post_init()
1014
+
1015
+ def get_input_embeddings(self):
1016
+ return self.model.embed_tokens
1017
+
1018
+ def set_input_embeddings(self, value):
1019
+ self.model.embed_tokens = value
1020
+
1021
+ @can_return_tuple
1022
+ @auto_docstring
1023
+ def forward(
1024
+ self,
1025
+ input_ids: Optional[torch.LongTensor] = None,
1026
+ attention_mask: Optional[torch.Tensor] = None,
1027
+ position_ids: Optional[torch.LongTensor] = None,
1028
+ past_key_values: Optional[Cache] = None,
1029
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1030
+ labels: Optional[torch.LongTensor] = None,
1031
+ use_cache: Optional[bool] = None,
1032
+ output_attentions: Optional[bool] = None,
1033
+ output_hidden_states: Optional[bool] = None,
1034
+ ) -> TokenClassifierOutput:
1035
+ r"""
1036
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1037
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1038
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1039
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1040
+ """
1041
+
1042
+ outputs: BaseModelOutputWithPast = self.model(
1043
+ input_ids,
1044
+ attention_mask=attention_mask,
1045
+ position_ids=position_ids,
1046
+ past_key_values=past_key_values,
1047
+ inputs_embeds=inputs_embeds,
1048
+ use_cache=use_cache,
1049
+ output_attentions=output_attentions,
1050
+ output_hidden_states=output_hidden_states,
1051
+ )
1052
+ sequence_output = outputs.last_hidden_state
1053
+ sequence_output = self.dropout(sequence_output)
1054
+ logits = self.score(sequence_output)
1055
+
1056
+ loss = None
1057
+ if labels is not None:
1058
+ loss = self.loss_function(logits, labels, self.config)
1059
+
1060
+ return TokenClassifierOutput(
1061
+ loss=loss,
1062
+ logits=logits,
1063
+ hidden_states=outputs.hidden_states,
1064
+ attentions=outputs.attentions,
1065
+ )
1066
+
1067
+
1068
+ @auto_docstring
1069
+ class Qwen3ForQuestionAnswering(Qwen3PreTrainedModel):
1070
+ base_model_prefix = "transformer"
1071
+
1072
+ def __init__(self, config):
1073
+ super().__init__(config)
1074
+ self.transformer = Qwen3Model(config)
1075
+ self.qa_outputs = nn.Linear(config.hidden_size, 2)
1076
+
1077
+ # Initialize weights and apply final processing
1078
+ self.post_init()
1079
+
1080
+ def get_input_embeddings(self):
1081
+ return self.transformer.embed_tokens
1082
+
1083
+ def set_input_embeddings(self, value):
1084
+ self.transformer.embed_tokens = value
1085
+
1086
+ @can_return_tuple
1087
+ @auto_docstring
1088
+ def forward(
1089
+ self,
1090
+ input_ids: Optional[torch.LongTensor] = None,
1091
+ attention_mask: Optional[torch.Tensor] = None,
1092
+ position_ids: Optional[torch.LongTensor] = None,
1093
+ past_key_values: Optional[Cache] = None,
1094
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1095
+ start_positions: Optional[torch.LongTensor] = None,
1096
+ end_positions: Optional[torch.LongTensor] = None,
1097
+ output_attentions: Optional[bool] = None,
1098
+ output_hidden_states: Optional[bool] = None,
1099
+ **kwargs,
1100
+ ) -> QuestionAnsweringModelOutput:
1101
+ outputs: BaseModelOutputWithPast = self.transformer(
1102
+ input_ids,
1103
+ attention_mask=attention_mask,
1104
+ position_ids=position_ids,
1105
+ past_key_values=past_key_values,
1106
+ inputs_embeds=inputs_embeds,
1107
+ output_attentions=output_attentions,
1108
+ output_hidden_states=output_hidden_states,
1109
+ )
1110
+
1111
+ sequence_output = outputs.last_hidden_state
1112
+
1113
+ logits = self.qa_outputs(sequence_output)
1114
+ start_logits, end_logits = logits.split(1, dim=-1)
1115
+ start_logits = start_logits.squeeze(-1).contiguous()
1116
+ end_logits = end_logits.squeeze(-1).contiguous()
1117
+
1118
+ loss = None
1119
+ if start_positions is not None and end_positions is not None:
1120
+ loss = self.loss_function(start_logits, end_logits, start_positions, end_positions, **kwargs)
1121
+
1122
+ return QuestionAnsweringModelOutput(
1123
+ loss=loss,
1124
+ start_logits=start_logits,
1125
+ end_logits=end_logits,
1126
+ hidden_states=outputs.hidden_states,
1127
+ attentions=outputs.attentions,
1128
+ )
1129
+
1130
+
1131
+ __all__ = [
1132
+ "Qwen3ForCausalLM",
1133
+ "Qwen3ForQuestionAnswering",
1134
+ "Qwen3Model",
1135
+ "Qwen3PreTrainedModel",
1136
+ "Qwen3ForSequenceClassification",
1137
+ "Qwen3ForTokenClassification",
1138
+ ]
modular_qwen3.py ADDED
@@ -0,0 +1,191 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ """PyTorch Qwen3 model."""
16
+
17
+ from typing import Callable, Optional, Tuple
18
+
19
+ import torch
20
+ import torch.utils.checkpoint
21
+
22
+ from transformers.cache_utils import Cache
23
+ from transformers.modeling_flash_attention_utils import FlashAttentionKwargs
24
+ from transformers.modeling_outputs import CausalLMOutputWithPast
25
+ from transformers.modeling_utils import ALL_ATTENTION_FUNCTIONS
26
+ from transformers.processing_utils import Unpack
27
+ from transformers.utils import LossKwargs, logging
28
+ from ..gemma.modeling_gemma import GemmaMLP
29
+ from ..llama.modeling_llama import (
30
+ LlamaAttention,
31
+ LlamaDecoderLayer,
32
+ LlamaForCausalLM,
33
+ LlamaForQuestionAnswering,
34
+ LlamaForSequenceClassification,
35
+ LlamaForTokenClassification,
36
+ LlamaRMSNorm,
37
+ apply_rotary_pos_emb,
38
+ eager_attention_forward,
39
+ )
40
+ from ..mistral.modeling_mistral import MistralModel
41
+ from .configuration_qwen3 import Qwen3Config
42
+
43
+
44
+ logger = logging.get_logger(__name__)
45
+
46
+ _CHECKPOINT_FOR_DOC = "Qwen/Qwen3-8B"
47
+
48
+
49
+ class Qwen3RMSNorm(LlamaRMSNorm):
50
+ pass
51
+
52
+
53
+ class Qwen3MLP(GemmaMLP):
54
+ pass
55
+
56
+
57
+ class Qwen3Attention(LlamaAttention):
58
+ def __init__(self, config: Qwen3Config, layer_idx: int):
59
+ super().__init__(config, layer_idx)
60
+ self.q_norm = Qwen3RMSNorm(self.head_dim, eps=config.rms_norm_eps) # unlike olmo, only on the head dim!
61
+ self.k_norm = Qwen3RMSNorm(self.head_dim, eps=config.rms_norm_eps) # thus post q_norm does not need reshape
62
+ self.sliding_window = config.sliding_window
63
+ if not (
64
+ self.config.use_sliding_window
65
+ and getattr(self.config, "sliding_window", None) is not None
66
+ and self.layer_idx >= self.config.max_window_layers
67
+ ):
68
+ self.sliding_window = None
69
+
70
+ def forward(
71
+ self,
72
+ hidden_states: torch.Tensor,
73
+ position_embeddings: Tuple[torch.Tensor, torch.Tensor],
74
+ attention_mask: Optional[torch.Tensor],
75
+ past_key_value: Optional[Cache] = None,
76
+ cache_position: Optional[torch.LongTensor] = None,
77
+ **kwargs: Unpack[FlashAttentionKwargs],
78
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
79
+ input_shape = hidden_states.shape[:-1]
80
+ hidden_shape = (*input_shape, -1, self.head_dim)
81
+
82
+ query_states = self.q_norm(self.q_proj(hidden_states).view(hidden_shape)).transpose(1, 2)
83
+ key_states = self.k_norm(self.k_proj(hidden_states).view(hidden_shape)).transpose(1, 2)
84
+ value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
85
+
86
+ cos, sin = position_embeddings
87
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
88
+
89
+ if past_key_value is not None:
90
+ # sin and cos are specific to RoPE models; cache_position needed for the static cache
91
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
92
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
93
+
94
+ attention_interface: Callable = eager_attention_forward
95
+ if self.config._attn_implementation != "eager":
96
+ if self.config._attn_implementation == "sdpa" and kwargs.get("output_attentions", False):
97
+ logger.warning_once(
98
+ "`torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to "
99
+ 'eager attention. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.'
100
+ )
101
+ else:
102
+ attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
103
+
104
+ attn_output, attn_weights = attention_interface(
105
+ self,
106
+ query_states,
107
+ key_states,
108
+ value_states,
109
+ attention_mask,
110
+ dropout=0.0 if not self.training else self.attention_dropout,
111
+ scaling=self.scaling,
112
+ sliding_window=self.sliding_window, # diff with Llama
113
+ **kwargs,
114
+ )
115
+
116
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
117
+ attn_output = self.o_proj(attn_output)
118
+ return attn_output, attn_weights
119
+
120
+
121
+ class Qwen3DecoderLayer(LlamaDecoderLayer):
122
+ def __init__(self, config: Qwen3Config, layer_idx: int):
123
+ super().__init__()
124
+ self.self_attn = Qwen3Attention(config=config, layer_idx=layer_idx)
125
+ self.mlp = Qwen3MLP(config)
126
+ if (
127
+ config.sliding_window and config._attn_implementation != "flash_attention_2"
128
+ ): # diff with Llama is this warning
129
+ logger.warning_once(
130
+ f"Sliding Window Attention is enabled but not implemented for `{config._attn_implementation}`; "
131
+ "unexpected results may be encountered."
132
+ )
133
+
134
+
135
+ class Qwen3Model(MistralModel): # mistral model creates sliding window
136
+ pass
137
+
138
+
139
+ class KwargsForCausalLM(FlashAttentionKwargs, LossKwargs): ...
140
+
141
+
142
+ class Qwen3ForCausalLM(LlamaForCausalLM):
143
+ def forward(
144
+ self,
145
+ **super_kwargs: Unpack[KwargsForCausalLM],
146
+ ) -> CausalLMOutputWithPast:
147
+ r"""
148
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
149
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
150
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
151
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
152
+
153
+ Example:
154
+
155
+ ```python
156
+ >>> from transformers import AutoTokenizer, Qwen3ForCausalLM
157
+
158
+ >>> model = Qwen3ForCausalLM.from_pretrained("Qwen/Qwen3-8B")
159
+ >>> tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen3-8B")
160
+
161
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
162
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
163
+
164
+ >>> # Generate
165
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
166
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
167
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
168
+ ```"""
169
+ return super().forward(**super_kwargs)
170
+
171
+
172
+ class Qwen3ForSequenceClassification(LlamaForSequenceClassification):
173
+ pass
174
+
175
+
176
+ class Qwen3ForTokenClassification(LlamaForTokenClassification):
177
+ pass
178
+
179
+
180
+ class Qwen3ForQuestionAnswering(LlamaForQuestionAnswering):
181
+ pass
182
+
183
+
184
+ __all__ = [
185
+ "Qwen3ForCausalLM",
186
+ "Qwen3ForQuestionAnswering",
187
+ "Qwen3Model",
188
+ "Qwen3PreTrainedModel", # noqa: F822
189
+ "Qwen3ForSequenceClassification",
190
+ "Qwen3ForTokenClassification",
191
+ ]