deep-analysis-research commited on
Commit
f103ea1
·
verified ·
1 Parent(s): e245736

Initial model upload

Browse files
Files changed (4) hide show
  1. __init__.py +27 -0
  2. configuration_qwen3.py +212 -0
  3. modeling_qwen3.py +1016 -0
  4. modular_qwen3.py +191 -0
__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 ...utils import _LazyModule
17
+ from ...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 ...configuration_utils import PretrainedConfig
18
+ from ...modeling_rope_utils import rope_config_validation
19
+ from ...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"]
modeling_qwen3.py ADDED
@@ -0,0 +1,1016 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 ...activations import ACT2FN
28
+ from ...cache_utils import Cache, DynamicCache, SlidingWindowCache, StaticCache
29
+ from ...generation import GenerationMixin
30
+ from ...integrations import use_kernel_forward_from_hub
31
+ from ...modeling_attn_mask_utils import AttentionMaskConverter
32
+ from ...modeling_flash_attention_utils import FlashAttentionKwargs
33
+ from ...modeling_layers import GradientCheckpointingLayer
34
+ from ...modeling_outputs import (
35
+ BaseModelOutputWithPast,
36
+ CausalLMOutputWithPast,
37
+ QuestionAnsweringModelOutput,
38
+ SequenceClassifierOutputWithPast,
39
+ TokenClassifierOutput,
40
+ )
41
+ from ...modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update
42
+ from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
43
+ from ...processing_utils import Unpack
44
+ from ...utils import LossKwargs, auto_docstring, can_return_tuple, is_torch_flex_attn_available, logging
45
+ from .configuration_qwen3 import Qwen3Config
46
+
47
+
48
+ if is_torch_flex_attn_available():
49
+ from torch.nn.attention.flex_attention import BlockMask
50
+
51
+ from ...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 = DynamicCache()
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
+ cnt = 0
460
+
461
+ for decoder_layer in self.layers[: self.config.num_hidden_layers]:
462
+ if output_hidden_states:
463
+ all_hidden_states += (hidden_states,)
464
+
465
+ # if decoder_layer.self_attn.q_proj.qweight.device != hidden_states.device:
466
+ # # If the layer's weights are on a different device, we need to move the hidden states to that device.
467
+ # hidden_states = hidden_states.to(decoder_layer.self_attn.q_proj.qweight.device)
468
+ # # import pdb
469
+ # # pdb.set_trace()
470
+ # position_embeddings = (position_embeddings[0].to(decoder_layer.self_attn.q_proj.qweight.device),
471
+ # position_embeddings[1].to(decoder_layer.self_attn.q_proj.qweight.device))
472
+ # print(f"layer {cnt} Moving hidden states to device: {decoder_layer.self_attn.q_proj.qweight.device}")
473
+ # cnt += 1
474
+
475
+ layer_outputs = decoder_layer(
476
+ hidden_states,
477
+ attention_mask=causal_mask,
478
+ position_ids=position_ids,
479
+ past_key_value=past_key_values,
480
+ output_attentions=output_attentions,
481
+ use_cache=use_cache,
482
+ cache_position=cache_position,
483
+ position_embeddings=position_embeddings,
484
+ **flash_attn_kwargs,
485
+ )
486
+
487
+ hidden_states = layer_outputs[0]
488
+
489
+ if output_attentions:
490
+ all_self_attns += (layer_outputs[1],)
491
+
492
+ hidden_states = self.norm(hidden_states)
493
+
494
+ # add hidden states from the last decoder layer
495
+ if output_hidden_states:
496
+ all_hidden_states += (hidden_states,)
497
+
498
+ return BaseModelOutputWithPast(
499
+ last_hidden_state=hidden_states,
500
+ past_key_values=past_key_values if use_cache else None,
501
+ hidden_states=all_hidden_states,
502
+ attentions=all_self_attns,
503
+ )
504
+
505
+ def _update_causal_mask(
506
+ self,
507
+ attention_mask: Union[torch.Tensor, "BlockMask"],
508
+ input_tensor: torch.Tensor,
509
+ cache_position: torch.Tensor,
510
+ past_key_values: Cache,
511
+ output_attentions: bool = False,
512
+ ):
513
+ if self.config._attn_implementation == "flash_attention_2":
514
+ if attention_mask is not None and past_key_values is not None:
515
+ is_padding_right = attention_mask[:, -1].sum().item() != input_tensor.size()[0]
516
+ if is_padding_right:
517
+ raise ValueError(
518
+ "You are attempting to perform batched generation with padding_side='right'"
519
+ " this may lead to unexpected behaviour for Flash Attention version of Qwen3. Make sure to "
520
+ " call `tokenizer.padding_side = 'left'` before tokenizing the input. "
521
+ )
522
+ if attention_mask is not None and 0.0 in attention_mask:
523
+ return attention_mask
524
+ return None
525
+ if self.config._attn_implementation == "flex_attention":
526
+ if isinstance(attention_mask, torch.Tensor):
527
+ attention_mask = make_flex_block_causal_mask(attention_mask)
528
+ return attention_mask
529
+
530
+ # For SDPA, when possible, we will rely on its `is_causal` argument instead of its `attn_mask` argument, in
531
+ # order to dispatch on Flash Attention 2. This feature is not compatible with static cache, as SDPA will fail
532
+ # to infer the attention mask.
533
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
534
+ using_static_cache = isinstance(past_key_values, StaticCache)
535
+ using_sliding_window_cache = isinstance(past_key_values, SlidingWindowCache)
536
+
537
+ # When output attentions is True, sdpa implementation's forward method calls the eager implementation's forward
538
+ if (
539
+ self.config._attn_implementation == "sdpa"
540
+ and not (using_static_cache or using_sliding_window_cache)
541
+ and not output_attentions
542
+ ):
543
+ if AttentionMaskConverter._ignore_causal_mask_sdpa(
544
+ attention_mask,
545
+ inputs_embeds=input_tensor,
546
+ past_key_values_length=past_seen_tokens,
547
+ sliding_window=self.config.sliding_window,
548
+ is_training=self.training,
549
+ ):
550
+ return None
551
+
552
+ dtype = input_tensor.dtype
553
+ min_dtype = torch.finfo(dtype).min
554
+ sequence_length = input_tensor.shape[1]
555
+ # SlidingWindowCache or StaticCache
556
+ if using_sliding_window_cache or using_static_cache:
557
+ target_length = past_key_values.get_max_cache_shape()
558
+ # DynamicCache or no cache
559
+ else:
560
+ target_length = (
561
+ attention_mask.shape[-1]
562
+ if isinstance(attention_mask, torch.Tensor)
563
+ else past_seen_tokens + sequence_length + 1
564
+ )
565
+
566
+ # In case the provided `attention` mask is 2D, we generate a causal mask here (4D).
567
+ causal_mask = self._prepare_4d_causal_attention_mask_with_cache_position(
568
+ attention_mask,
569
+ sequence_length=sequence_length,
570
+ target_length=target_length,
571
+ dtype=dtype,
572
+ cache_position=cache_position,
573
+ batch_size=input_tensor.shape[0],
574
+ config=self.config,
575
+ past_key_values=past_key_values,
576
+ )
577
+
578
+ if (
579
+ self.config._attn_implementation == "sdpa"
580
+ and attention_mask is not None
581
+ and attention_mask.device.type in ["cuda", "xpu", "npu"]
582
+ and not output_attentions
583
+ ):
584
+ # Attend to all tokens in fully masked rows in the causal_mask, for example the relevant first rows when
585
+ # using left padding. This is required by F.scaled_dot_product_attention memory-efficient attention path.
586
+ # Details: https://github.com/pytorch/pytorch/issues/110213
587
+ causal_mask = AttentionMaskConverter._unmask_unattended(causal_mask, min_dtype)
588
+
589
+ return causal_mask
590
+
591
+ @staticmethod
592
+ def _prepare_4d_causal_attention_mask_with_cache_position(
593
+ attention_mask: torch.Tensor,
594
+ sequence_length: int,
595
+ target_length: int,
596
+ dtype: torch.dtype,
597
+ cache_position: torch.Tensor,
598
+ batch_size: int,
599
+ config: Qwen3Config,
600
+ past_key_values: Cache,
601
+ ):
602
+ """
603
+ Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape
604
+ `(batch_size, key_value_length)`, or if the input `attention_mask` is already 4D, do nothing.
605
+
606
+ Args:
607
+ attention_mask (`torch.Tensor`):
608
+ 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)`.
609
+ sequence_length (`int`):
610
+ The sequence length being processed.
611
+ target_length (`int`):
612
+ 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.
613
+ dtype (`torch.dtype`):
614
+ The dtype to use for the 4D attention mask.
615
+ cache_position (`torch.Tensor`):
616
+ Indices depicting the position of the input sequence tokens in the sequence.
617
+ batch_size (`torch.Tensor`):
618
+ Batch size.
619
+ config (`Qwen3Config`):
620
+ The model's configuration class
621
+ past_key_values (`Cache`):
622
+ The cache class that is being used currently to generate
623
+ """
624
+ if attention_mask is not None and attention_mask.dim() == 4:
625
+ # In this case we assume that the mask comes already in inverted form and requires no inversion or slicing.
626
+ causal_mask = attention_mask
627
+ else:
628
+ min_dtype = torch.finfo(dtype).min
629
+ causal_mask = torch.full(
630
+ (sequence_length, target_length), fill_value=min_dtype, dtype=dtype, device=cache_position.device
631
+ )
632
+ diagonal_attend_mask = torch.arange(target_length, device=cache_position.device) > cache_position.reshape(
633
+ -1, 1
634
+ )
635
+ text_config = config.get_text_config()
636
+ if getattr(text_config, "use_sliding_window", True) and text_config.sliding_window is not None:
637
+ # if we have sliding window, we should not attend to tokens beyond sliding window length, so we mask them out also
638
+ # the check is needed to verify is current checkpoint was trained with sliding window or not
639
+ if not isinstance(past_key_values, SlidingWindowCache) or sequence_length > target_length:
640
+ sliding_attend_mask = torch.arange(target_length, device=cache_position.device) <= (
641
+ cache_position.reshape(-1, 1) - text_config.sliding_window
642
+ )
643
+ diagonal_attend_mask.bitwise_or_(sliding_attend_mask)
644
+ causal_mask *= diagonal_attend_mask
645
+ causal_mask = causal_mask[None, None, :, :].expand(batch_size, 1, -1, -1)
646
+ if attention_mask is not None:
647
+ causal_mask = causal_mask.clone() # copy to contiguous memory for in-place edit
648
+ if attention_mask.shape[-1] > target_length:
649
+ attention_mask = attention_mask[:, :target_length]
650
+ mask_length = attention_mask.shape[-1]
651
+ padding_mask = causal_mask[:, :, :, :mask_length] + attention_mask[:, None, None, :].to(
652
+ causal_mask.device
653
+ )
654
+ padding_mask = padding_mask == 0
655
+ causal_mask[:, :, :, :mask_length] = causal_mask[:, :, :, :mask_length].masked_fill(
656
+ padding_mask, min_dtype
657
+ )
658
+ return causal_mask
659
+
660
+
661
+ class KwargsForCausalLM(FlashAttentionKwargs, LossKwargs): ...
662
+
663
+
664
+ @auto_docstring
665
+ class Qwen3ForCausalLM(Qwen3PreTrainedModel, GenerationMixin):
666
+ _tied_weights_keys = ["lm_head.weight"]
667
+ _tp_plan = {"lm_head": "colwise_rep"}
668
+ _pp_plan = {"lm_head": (["hidden_states"], ["logits"])}
669
+
670
+ def __init__(self, config):
671
+ super().__init__(config)
672
+ self.model = Qwen3Model(config)
673
+ self.vocab_size = config.vocab_size
674
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
675
+
676
+ # Initialize weights and apply final processing
677
+ self.post_init()
678
+
679
+ def get_input_embeddings(self):
680
+ return self.model.embed_tokens
681
+
682
+ def set_input_embeddings(self, value):
683
+ self.model.embed_tokens = value
684
+
685
+ def get_output_embeddings(self):
686
+ return self.lm_head
687
+
688
+ def set_output_embeddings(self, new_embeddings):
689
+ self.lm_head = new_embeddings
690
+
691
+ def set_decoder(self, decoder):
692
+ self.model = decoder
693
+
694
+ def get_decoder(self):
695
+ return self.model
696
+
697
+ @can_return_tuple
698
+ @auto_docstring
699
+ def forward(
700
+ self,
701
+ input_ids: Optional[torch.LongTensor] = None,
702
+ attention_mask: Optional[torch.Tensor] = None,
703
+ position_ids: Optional[torch.LongTensor] = None,
704
+ past_key_values: Optional[Cache] = None,
705
+ inputs_embeds: Optional[torch.FloatTensor] = None,
706
+ labels: Optional[torch.LongTensor] = None,
707
+ use_cache: Optional[bool] = None,
708
+ output_attentions: Optional[bool] = None,
709
+ output_hidden_states: Optional[bool] = None,
710
+ cache_position: Optional[torch.LongTensor] = None,
711
+ logits_to_keep: Union[int, torch.Tensor] = 0,
712
+ **kwargs: Unpack[KwargsForCausalLM],
713
+ ) -> CausalLMOutputWithPast:
714
+ r"""
715
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
716
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
717
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
718
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
719
+
720
+ Example:
721
+
722
+ ```python
723
+ >>> from transformers import AutoTokenizer, Qwen3ForCausalLM
724
+
725
+ >>> model = Qwen3ForCausalLM.from_pretrained("Qwen/Qwen3-8B")
726
+ >>> tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen3-8B")
727
+
728
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
729
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
730
+
731
+ >>> # Generate
732
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
733
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
734
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
735
+ ```"""
736
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
737
+ output_hidden_states = (
738
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
739
+ )
740
+
741
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
742
+ outputs: BaseModelOutputWithPast = self.model(
743
+ input_ids=input_ids,
744
+ attention_mask=attention_mask,
745
+ position_ids=position_ids,
746
+ past_key_values=past_key_values,
747
+ inputs_embeds=inputs_embeds,
748
+ use_cache=use_cache,
749
+ output_attentions=output_attentions,
750
+ output_hidden_states=output_hidden_states,
751
+ cache_position=cache_position,
752
+ **kwargs,
753
+ )
754
+
755
+ hidden_states = outputs.last_hidden_state
756
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
757
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
758
+ # import pdb
759
+ # pdb.set_trace()
760
+ logits = self.lm_head(hidden_states[:, slice_indices, :])
761
+
762
+ loss = None
763
+ if labels is not None:
764
+ loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs)
765
+
766
+ return CausalLMOutputWithPast(
767
+ loss=loss,
768
+ logits=logits,
769
+ past_key_values=outputs.past_key_values,
770
+ hidden_states=outputs.hidden_states,
771
+ attentions=outputs.attentions,
772
+ )
773
+
774
+
775
+ @auto_docstring(
776
+ custom_intro="""
777
+ The Qwen3 Model transformer with a sequence classification head on top (linear layer).
778
+
779
+ [`Qwen3ForSequenceClassification`] uses the last token in order to do the classification, as other causal models
780
+ (e.g. GPT-2) do.
781
+
782
+ Since it does classification on the last token, it requires to know the position of the last token. If a
783
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
784
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
785
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
786
+ each row of the batch).
787
+ """
788
+ )
789
+ class Qwen3ForSequenceClassification(Qwen3PreTrainedModel):
790
+ def __init__(self, config):
791
+ super().__init__(config)
792
+ self.num_labels = config.num_labels
793
+ self.model = Qwen3Model(config)
794
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
795
+
796
+ # Initialize weights and apply final processing
797
+ self.post_init()
798
+
799
+ def get_input_embeddings(self):
800
+ return self.model.embed_tokens
801
+
802
+ def set_input_embeddings(self, value):
803
+ self.model.embed_tokens = value
804
+
805
+ @can_return_tuple
806
+ @auto_docstring
807
+ def forward(
808
+ self,
809
+ input_ids: Optional[torch.LongTensor] = None,
810
+ attention_mask: Optional[torch.Tensor] = None,
811
+ position_ids: Optional[torch.LongTensor] = None,
812
+ past_key_values: Optional[Cache] = None,
813
+ inputs_embeds: Optional[torch.FloatTensor] = None,
814
+ labels: Optional[torch.LongTensor] = None,
815
+ use_cache: Optional[bool] = None,
816
+ output_attentions: Optional[bool] = None,
817
+ output_hidden_states: Optional[bool] = None,
818
+ ) -> SequenceClassifierOutputWithPast:
819
+ r"""
820
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
821
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
822
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
823
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
824
+ """
825
+
826
+ transformer_outputs: BaseModelOutputWithPast = self.model(
827
+ input_ids,
828
+ attention_mask=attention_mask,
829
+ position_ids=position_ids,
830
+ past_key_values=past_key_values,
831
+ inputs_embeds=inputs_embeds,
832
+ use_cache=use_cache,
833
+ output_attentions=output_attentions,
834
+ output_hidden_states=output_hidden_states,
835
+ )
836
+ hidden_states = transformer_outputs.last_hidden_state
837
+ logits = self.score(hidden_states)
838
+
839
+ if input_ids is not None:
840
+ batch_size = input_ids.shape[0]
841
+ else:
842
+ batch_size = inputs_embeds.shape[0]
843
+
844
+ if self.config.pad_token_id is None and batch_size != 1:
845
+ raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
846
+ if self.config.pad_token_id is None:
847
+ last_non_pad_token = -1
848
+ elif input_ids is not None:
849
+ # To handle both left- and right- padding, we take the rightmost token that is not equal to pad_token_id
850
+ non_pad_mask = (input_ids != self.config.pad_token_id).to(logits.device, torch.int32)
851
+ token_indices = torch.arange(input_ids.shape[-1], device=logits.device, dtype=torch.int32)
852
+ last_non_pad_token = (token_indices * non_pad_mask).argmax(-1)
853
+ else:
854
+ last_non_pad_token = -1
855
+ logger.warning_once(
856
+ f"{self.__class__.__name__} will not detect padding tokens in `inputs_embeds`. Results may be "
857
+ "unexpected if using padding tokens in conjunction with `inputs_embeds.`"
858
+ )
859
+
860
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), last_non_pad_token]
861
+
862
+ loss = None
863
+ if labels is not None:
864
+ loss = self.loss_function(logits=logits, labels=labels, pooled_logits=pooled_logits, config=self.config)
865
+
866
+ return SequenceClassifierOutputWithPast(
867
+ loss=loss,
868
+ logits=pooled_logits,
869
+ past_key_values=transformer_outputs.past_key_values,
870
+ hidden_states=transformer_outputs.hidden_states,
871
+ attentions=transformer_outputs.attentions,
872
+ )
873
+
874
+
875
+ @auto_docstring
876
+ class Qwen3ForTokenClassification(Qwen3PreTrainedModel):
877
+ def __init__(self, config):
878
+ super().__init__(config)
879
+ self.num_labels = config.num_labels
880
+ self.model = Qwen3Model(config)
881
+ if getattr(config, "classifier_dropout", None) is not None:
882
+ classifier_dropout = config.classifier_dropout
883
+ elif getattr(config, "hidden_dropout", None) is not None:
884
+ classifier_dropout = config.hidden_dropout
885
+ else:
886
+ classifier_dropout = 0.1
887
+ self.dropout = nn.Dropout(classifier_dropout)
888
+ self.score = nn.Linear(config.hidden_size, config.num_labels)
889
+
890
+ # Initialize weights and apply final processing
891
+ self.post_init()
892
+
893
+ def get_input_embeddings(self):
894
+ return self.model.embed_tokens
895
+
896
+ def set_input_embeddings(self, value):
897
+ self.model.embed_tokens = value
898
+
899
+ @can_return_tuple
900
+ @auto_docstring
901
+ def forward(
902
+ self,
903
+ input_ids: Optional[torch.LongTensor] = None,
904
+ attention_mask: Optional[torch.Tensor] = None,
905
+ position_ids: Optional[torch.LongTensor] = None,
906
+ past_key_values: Optional[Cache] = None,
907
+ inputs_embeds: Optional[torch.FloatTensor] = None,
908
+ labels: Optional[torch.LongTensor] = None,
909
+ use_cache: Optional[bool] = None,
910
+ output_attentions: Optional[bool] = None,
911
+ output_hidden_states: Optional[bool] = None,
912
+ ) -> TokenClassifierOutput:
913
+ r"""
914
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
915
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
916
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
917
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
918
+ """
919
+
920
+ outputs: BaseModelOutputWithPast = self.model(
921
+ input_ids,
922
+ attention_mask=attention_mask,
923
+ position_ids=position_ids,
924
+ past_key_values=past_key_values,
925
+ inputs_embeds=inputs_embeds,
926
+ use_cache=use_cache,
927
+ output_attentions=output_attentions,
928
+ output_hidden_states=output_hidden_states,
929
+ )
930
+ sequence_output = outputs.last_hidden_state
931
+ sequence_output = self.dropout(sequence_output)
932
+ logits = self.score(sequence_output)
933
+
934
+ loss = None
935
+ if labels is not None:
936
+ loss = self.loss_function(logits, labels, self.config)
937
+
938
+ return TokenClassifierOutput(
939
+ loss=loss,
940
+ logits=logits,
941
+ hidden_states=outputs.hidden_states,
942
+ attentions=outputs.attentions,
943
+ )
944
+
945
+
946
+ @auto_docstring
947
+ class Qwen3ForQuestionAnswering(Qwen3PreTrainedModel):
948
+ base_model_prefix = "transformer"
949
+
950
+ def __init__(self, config):
951
+ super().__init__(config)
952
+ self.transformer = Qwen3Model(config)
953
+ self.qa_outputs = nn.Linear(config.hidden_size, 2)
954
+
955
+ # Initialize weights and apply final processing
956
+ self.post_init()
957
+
958
+ def get_input_embeddings(self):
959
+ return self.transformer.embed_tokens
960
+
961
+ def set_input_embeddings(self, value):
962
+ self.transformer.embed_tokens = value
963
+
964
+ @can_return_tuple
965
+ @auto_docstring
966
+ def forward(
967
+ self,
968
+ input_ids: Optional[torch.LongTensor] = None,
969
+ attention_mask: Optional[torch.Tensor] = None,
970
+ position_ids: Optional[torch.LongTensor] = None,
971
+ past_key_values: Optional[Cache] = None,
972
+ inputs_embeds: Optional[torch.FloatTensor] = None,
973
+ start_positions: Optional[torch.LongTensor] = None,
974
+ end_positions: Optional[torch.LongTensor] = None,
975
+ output_attentions: Optional[bool] = None,
976
+ output_hidden_states: Optional[bool] = None,
977
+ **kwargs,
978
+ ) -> QuestionAnsweringModelOutput:
979
+ outputs: BaseModelOutputWithPast = self.transformer(
980
+ input_ids,
981
+ attention_mask=attention_mask,
982
+ position_ids=position_ids,
983
+ past_key_values=past_key_values,
984
+ inputs_embeds=inputs_embeds,
985
+ output_attentions=output_attentions,
986
+ output_hidden_states=output_hidden_states,
987
+ )
988
+
989
+ sequence_output = outputs.last_hidden_state
990
+
991
+ logits = self.qa_outputs(sequence_output)
992
+ start_logits, end_logits = logits.split(1, dim=-1)
993
+ start_logits = start_logits.squeeze(-1).contiguous()
994
+ end_logits = end_logits.squeeze(-1).contiguous()
995
+
996
+ loss = None
997
+ if start_positions is not None and end_positions is not None:
998
+ loss = self.loss_function(start_logits, end_logits, start_positions, end_positions, **kwargs)
999
+
1000
+ return QuestionAnsweringModelOutput(
1001
+ loss=loss,
1002
+ start_logits=start_logits,
1003
+ end_logits=end_logits,
1004
+ hidden_states=outputs.hidden_states,
1005
+ attentions=outputs.attentions,
1006
+ )
1007
+
1008
+
1009
+ __all__ = [
1010
+ "Qwen3ForCausalLM",
1011
+ "Qwen3ForQuestionAnswering",
1012
+ "Qwen3Model",
1013
+ "Qwen3PreTrainedModel",
1014
+ "Qwen3ForSequenceClassification",
1015
+ "Qwen3ForTokenClassification",
1016
+ ]
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 ...cache_utils import Cache
23
+ from ...modeling_flash_attention_utils import FlashAttentionKwargs
24
+ from ...modeling_outputs import CausalLMOutputWithPast
25
+ from ...modeling_utils import ALL_ATTENTION_FUNCTIONS
26
+ from ...processing_utils import Unpack
27
+ from ...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
+ ]