appleeji commited on
Commit
84ba8af
·
verified ·
1 Parent(s): 160dbc8

Upload modeling_qwen_kv.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. modeling_qwen_kv.py +1534 -0
modeling_qwen_kv.py ADDED
@@ -0,0 +1,1534 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Source: https://github.com/huggingface/transformers/blob/v4.31-release/src/transformers/models/llama/modeling_llama.py
2
+ # Modifications are denoted by the symbol: [MODIFIED]
3
+
4
+
5
+ """ PyTorch Qwen3 model."""
6
+ import math
7
+ from typing import List, Optional, Tuple, Union
8
+
9
+ import torch
10
+ import torch.nn.functional as F
11
+ import torch.utils.checkpoint
12
+ from torch import nn
13
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
14
+
15
+ # [MODIFIED] Import from transformer library
16
+ from transformers.activations import ACT2FN
17
+ from transformers.modeling_outputs import (
18
+ BaseModelOutputWithPast,
19
+ CausalLMOutputWithPast,
20
+ SequenceClassifierOutputWithPast,
21
+ )
22
+ from transformers.modeling_utils import PreTrainedModel
23
+ from transformers.utils import (
24
+ add_start_docstrings,
25
+ add_start_docstrings_to_model_forward,
26
+ logging,
27
+ replace_return_docstrings,
28
+ )
29
+ try:
30
+ from transformers.modeling_rope_utils import ROPE_INIT_FUNCTIONS
31
+ except ImportError:
32
+ ROPE_INIT_FUNCTIONS = None # Fallback for older transformers versions
33
+ from transformers import Qwen2Config
34
+
35
+ logger = logging.get_logger(__name__)
36
+
37
+ _CONFIG_FOR_DOC = "Qwen2Config"
38
+
39
+
40
+ # Copied from transformers.models.bart.modeling_bart._make_causal_mask
41
+ def _make_causal_mask(
42
+ input_ids_shape: torch.Size,
43
+ dtype: torch.dtype,
44
+ device: torch.device,
45
+ past_key_values_length: int = 0,
46
+ ):
47
+ """
48
+ Create a causal mask for bi-directional self-attention.
49
+
50
+ Args:
51
+ input_ids_shape (torch.Size): The shape of input_ids tensor, typically (batch_size, tgt_len).
52
+ dtype (torch.dtype): The data type of the mask.
53
+ device (torch.device): The device on which the mask will be placed.
54
+ past_key_values_length (int, optional): The length of past key values. Default is 0.
55
+
56
+ Returns:
57
+ torch.Tensor: The causal mask tensor.
58
+ """
59
+ bsz, tgt_len = input_ids_shape
60
+ mask = torch.full((tgt_len, tgt_len), torch.finfo(dtype).min, device=device)
61
+ mask_cond = torch.arange(mask.size(-1), device=device)
62
+ mask.masked_fill_(mask_cond < (mask_cond + 1).view(mask.size(-1), 1), 0)
63
+ mask = mask.to(dtype)
64
+
65
+ if past_key_values_length > 0:
66
+ mask = torch.cat(
67
+ [
68
+ torch.zeros(
69
+ tgt_len, past_key_values_length, dtype=dtype, device=device
70
+ ),
71
+ mask,
72
+ ],
73
+ dim=-1,
74
+ )
75
+ return mask[None, None, :, :].expand(
76
+ bsz, 1, tgt_len, tgt_len + past_key_values_length
77
+ )
78
+
79
+
80
+ # Copied from transformers.models.bart.modeling_bart._expand_mask
81
+ def _expand_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None):
82
+ """
83
+ Expand attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`.
84
+
85
+ Args:
86
+ mask (torch.Tensor): The attention mask tensor of shape `[bsz, seq_len]`.
87
+ dtype (torch.dtype): The data type of the mask.
88
+ tgt_len (Optional[int], optional): The target sequence length. If None, it defaults to the source sequence length.
89
+
90
+ Returns:
91
+ torch.Tensor: The expanded mask tensor.
92
+ """
93
+ bsz, src_len = mask.size()
94
+ tgt_len = tgt_len if tgt_len is not None else src_len
95
+
96
+ expanded_mask = mask[:, None, None, :].expand(bsz, 1, tgt_len, src_len).to(dtype)
97
+
98
+ inverted_mask = 1.0 - expanded_mask
99
+
100
+ return inverted_mask.masked_fill(
101
+ inverted_mask.to(torch.bool), torch.finfo(dtype).min
102
+ )
103
+
104
+
105
+
106
+
107
+ class Qwen3RMSNorm(nn.Module):
108
+ """
109
+ Qwen3RMSNorm is equivalent to T5LayerNorm.
110
+
111
+ Args:
112
+ hidden_size (int): The size of the hidden states.
113
+ eps (float, optional): A small value to prevent division by zero. Default is 1e-6.
114
+ """
115
+
116
+ def __init__(self, hidden_size, eps=1e-6):
117
+ super().__init__()
118
+ self.weight = nn.Parameter(torch.ones(hidden_size))
119
+ self.variance_epsilon = eps
120
+
121
+ def forward(self, hidden_states):
122
+ """
123
+ Apply Qwen3RMSNorm to the input hidden states.
124
+
125
+ Args:
126
+ hidden_states (torch.Tensor): Input hidden states.
127
+
128
+ Returns:
129
+ torch.Tensor: The normalized and scaled hidden states.
130
+ """
131
+ input_dtype = hidden_states.dtype
132
+ hidden_states = hidden_states.to(torch.float32)
133
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
134
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
135
+ return self.weight * hidden_states.to(input_dtype)
136
+
137
+
138
+ class Qwen3RotaryEmbedding(nn.Module):
139
+ """
140
+ Qwen3 Rotary Positional Embedding Module.
141
+
142
+ Args:
143
+ dim (int): The dimension of the embedding.
144
+ max_position_embeddings (int, optional): The maximum position for embeddings. Default is 2048.
145
+ base (int, optional): The base value for rotational encoding. Default is 10000.
146
+ device (str, optional): The device on which the computation will be performed. Default is None.
147
+ """
148
+
149
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
150
+ super().__init__()
151
+
152
+ self.dim = dim
153
+ self.max_position_embeddings = max_position_embeddings
154
+ self.base = base
155
+ inv_freq = 1.0 / (
156
+ self.base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim)
157
+ )
158
+ self.register_buffer("inv_freq", inv_freq)
159
+
160
+ # Build here to make `torch.jit.trace` work.
161
+ self._set_cos_sin_cache(
162
+ seq_len=max_position_embeddings,
163
+ device=self.inv_freq.device,
164
+ dtype=torch.get_default_dtype(),
165
+ )
166
+
167
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
168
+ """
169
+ Set the cosine and sine cache for positional embeddings.
170
+
171
+ Args:
172
+ seq_len (int): The sequence length.
173
+ device (str): The device on which the cache tensors will be stored.
174
+ dtype: The data type of the cache tensors.
175
+ """
176
+ self.max_seq_len_cached = seq_len
177
+ t = torch.arange(
178
+ self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype
179
+ )
180
+
181
+ freqs = torch.einsum("i,j->ij", t, self.inv_freq)
182
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
183
+ emb = torch.cat((freqs, freqs), dim=-1)
184
+ self.register_buffer(
185
+ "cos_cached", emb.cos()[None, None, :, :].to(dtype), persistent=False
186
+ )
187
+ self.register_buffer(
188
+ "sin_cached", emb.sin()[None, None, :, :].to(dtype), persistent=False
189
+ )
190
+
191
+ def forward(self, x, seq_len=None):
192
+ """
193
+ Forward pass of the Qwen3RotaryEmbedding module.
194
+
195
+ Args:
196
+ x (torch.Tensor): Input tensor of shape [bs, num_attention_heads, seq_len, head_size].
197
+ seq_len (int): The sequence length. If greater than the cached length, the cache will be updated.
198
+
199
+ Returns:
200
+ tuple: A tuple containing two tensors, the cosine and sine embeddings, both of shape [1, 1, seq_len, dim].
201
+ """
202
+ if seq_len > self.max_seq_len_cached:
203
+ self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=x.dtype)
204
+
205
+ return (
206
+ self.cos_cached[:, :, :seq_len, ...].to(dtype=x.dtype),
207
+ self.sin_cached[:, :, :seq_len, ...].to(dtype=x.dtype),
208
+ )
209
+
210
+
211
+ class Qwen3RotaryEmbedding_L31(nn.Module):
212
+ def __init__(
213
+ self,
214
+ dim=None,
215
+ max_position_embeddings=2048,
216
+ base=10000,
217
+ device=None,
218
+ scaling_factor=1.0,
219
+ rope_type="default",
220
+ config: Optional[Qwen2Config] = None,
221
+ ):
222
+ super().__init__()
223
+ # TODO (joao): remove the `if` below, only used for BC
224
+ self.rope_kwargs = {}
225
+ if config is None:
226
+ logger.warning_once(
227
+ "`Qwen3RotaryEmbedding` can now be fully parameterized by passing the model config through the "
228
+ "`config` argument. All other arguments will be removed in v4.46"
229
+ )
230
+ self.rope_kwargs = {
231
+ "rope_type": rope_type,
232
+ "factor": scaling_factor,
233
+ "dim": dim,
234
+ "base": base,
235
+ "max_position_embeddings": max_position_embeddings,
236
+ }
237
+ self.rope_type = rope_type
238
+ self.max_seq_len_cached = max_position_embeddings
239
+ self.original_max_seq_len = max_position_embeddings
240
+ else:
241
+ # BC: "rope_type" was originally "type"
242
+ if config.rope_scaling is not None:
243
+ self.rope_type = config.rope_scaling.get("rope_type", config.rope_scaling.get("type"))
244
+ else:
245
+ self.rope_type = "default"
246
+ self.max_seq_len_cached = config.max_position_embeddings
247
+ self.original_max_seq_len = config.max_position_embeddings
248
+
249
+ self.config = config
250
+ self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
251
+
252
+ inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device, **self.rope_kwargs)
253
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
254
+ self.original_inv_freq = self.inv_freq
255
+
256
+ def _dynamic_frequency_update(self, position_ids, device):
257
+ """
258
+ dynamic RoPE layers should recompute `inv_freq` in the following situations:
259
+ 1 - growing beyond the cached sequence length (allow scaling)
260
+ 2 - the current sequence length is in the original scale (avoid losing precision with small sequences)
261
+ """
262
+ seq_len = torch.max(position_ids) + 1
263
+ if seq_len > self.max_seq_len_cached: # growth
264
+ inv_freq, self.attention_scaling = self.rope_init_fn(
265
+ self.config, device, seq_len=seq_len, **self.rope_kwargs
266
+ )
267
+ self.register_buffer("inv_freq", inv_freq, persistent=False) # TODO joao: may break with compilation
268
+ self.max_seq_len_cached = seq_len
269
+
270
+ if seq_len < self.original_max_seq_len and self.max_seq_len_cached > self.original_max_seq_len: # reset
271
+ self.register_buffer("inv_freq", self.original_inv_freq, persistent=False)
272
+ self.max_seq_len_cached = self.original_max_seq_len
273
+
274
+ @torch.no_grad()
275
+ def forward(self, x, position_ids):
276
+ if "dynamic" in self.rope_type:
277
+ self._dynamic_frequency_update(position_ids, device=x.device)
278
+
279
+ # Core RoPE block
280
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
281
+ position_ids_expanded = position_ids[:, None, :].float()
282
+ # Force float32 (see https://github.com/huggingface/transformers/pull/29285)
283
+ device_type = x.device.type
284
+ device_type = device_type if isinstance(device_type, str) and device_type != "mps" else "cpu"
285
+ with torch.autocast(device_type=device_type, enabled=False):
286
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
287
+ emb = torch.cat((freqs, freqs), dim=-1)
288
+ cos = emb.cos()
289
+ sin = emb.sin()
290
+
291
+ # Advanced RoPE types (e.g. yarn) apply a post-processing scaling factor, equivalent to scaling attention
292
+ cos = cos * self.attention_scaling
293
+ sin = sin * self.attention_scaling
294
+
295
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
296
+
297
+ class Qwen3LinearScalingRotaryEmbedding(Qwen3RotaryEmbedding):
298
+ """
299
+ Qwen3RotaryEmbedding extended with linear scaling.
300
+
301
+ This class adds linear scaling to Qwen3RotaryEmbedding. Credits to the Reddit user /u/kaiokendev.
302
+
303
+ Args:
304
+ dim (int): The dimension of the embedding.
305
+ max_position_embeddings (int, optional): The maximum number of position embeddings. Default is 2048.
306
+ base (int, optional): The base value for the rotational embeddings. Default is 10000.
307
+ device (str or torch.device, optional): The device where the embeddings should be stored. Default is None.
308
+ scaling_factor (float, optional): The scaling factor for the embeddings. Default is 1.0.
309
+ """
310
+
311
+ def __init__(
312
+ self,
313
+ dim,
314
+ max_position_embeddings=2048,
315
+ base=10000,
316
+ device=None,
317
+ scaling_factor=1.0,
318
+ ):
319
+ self.scaling_factor = scaling_factor
320
+ super().__init__(dim, max_position_embeddings, base, device)
321
+
322
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
323
+ """
324
+ Set the cosine and sine cache for the rotary embeddings.
325
+
326
+ Args:
327
+ seq_len (int): The sequence length.
328
+ device (str or torch.device): The device where the cache should be stored.
329
+ dtype: The data type for the cache.
330
+ """
331
+ self.max_seq_len_cached = seq_len
332
+ t = torch.arange(
333
+ self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype
334
+ )
335
+ t = t / self.scaling_factor
336
+
337
+ freqs = torch.einsum("i,j->ij", t, self.inv_freq)
338
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
339
+ emb = torch.cat((freqs, freqs), dim=-1)
340
+ self.register_buffer(
341
+ "cos_cached", emb.cos()[None, None, :, :].to(dtype), persistent=False
342
+ )
343
+ self.register_buffer(
344
+ "sin_cached", emb.sin()[None, None, :, :].to(dtype), persistent=False
345
+ )
346
+
347
+
348
+ class Qwen3DynamicNTKScalingRotaryEmbedding(Qwen3RotaryEmbedding):
349
+ """
350
+ Qwen3RotaryEmbedding extended with Dynamic NTK scaling.
351
+
352
+ Credits to the Reddit users /u/bloc97 and /u/emozilla.
353
+ """
354
+
355
+ def __init__(
356
+ self,
357
+ dim,
358
+ max_position_embeddings=2048,
359
+ base=10000,
360
+ device=None,
361
+ scaling_factor=1.0,
362
+ ):
363
+ """
364
+ Initialize the Qwen3DynamicNTKScalingRotaryEmbedding.
365
+
366
+ Args:
367
+ dim (int): The dimensionality of the embedding.
368
+ max_position_embeddings (int, optional): Maximum number of position embeddings. Default is 2048.
369
+ base (int, optional): Base value for scaling calculations. Default is 10000.
370
+ device: The device to place tensors on. If None, uses the default device.
371
+ scaling_factor (float, optional): Scaling factor for NTK scaling. Default is 1.0.
372
+ """
373
+ self.scaling_factor = scaling_factor
374
+ super().__init__(dim, max_position_embeddings, base, device)
375
+
376
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
377
+ """
378
+ Set the cached values for cosine and sine.
379
+
380
+ Args:
381
+ seq_len (int): The sequence length.
382
+ device: The device to place tensors on.
383
+ dtype: The data type of tensors.
384
+ """
385
+ self.max_seq_len_cached = seq_len
386
+
387
+ if seq_len > self.max_position_embeddings:
388
+ base = self.base * (
389
+ (self.scaling_factor * seq_len / self.max_position_embeddings)
390
+ - (self.scaling_factor - 1)
391
+ ) ** (self.dim / (self.dim - 2))
392
+ inv_freq = 1.0 / (
393
+ base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim)
394
+ )
395
+ self.register_buffer("inv_freq", inv_freq)
396
+
397
+ t = torch.arange(
398
+ self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype
399
+ )
400
+
401
+ freqs = torch.einsum("i,j->ij", t, self.inv_freq)
402
+ emb = torch.cat((freqs, freqs), dim=-1)
403
+ self.register_buffer(
404
+ "cos_cached", emb.cos()[None, None, :, :].to(dtype), persistent=False
405
+ )
406
+ self.register_buffer(
407
+ "sin_cached", emb.sin()[None, None, :, :].to(dtype), persistent=False
408
+ )
409
+
410
+
411
+ def rotate_half(x):
412
+ """
413
+ Rotates half the hidden dimensions of the input.
414
+
415
+ Args:
416
+ x (torch.Tensor): Input tensor.
417
+
418
+ Returns:
419
+ torch.Tensor: Tensor with half of its hidden dimensions rotated.
420
+ """
421
+ x1 = x[..., : x.shape[-1] // 2]
422
+ x2 = x[..., x.shape[-1] // 2:]
423
+ return torch.cat((-x2, x1), dim=-1)
424
+
425
+
426
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids):
427
+ """
428
+ Apply rotary position embeddings to query and key tensors.
429
+
430
+ Args:
431
+ q (torch.Tensor): Query tensor.
432
+ k (torch.Tensor): Key tensor.
433
+ cos (torch.Tensor): Cosine values.
434
+ sin (torch.Tensor): Sine values.
435
+ position_ids (torch.Tensor): Position IDs.
436
+
437
+ Returns:
438
+ torch.Tensor: Query and key tensors with rotary position embeddings applied.
439
+ """
440
+ cos = cos.squeeze(1).squeeze(0)
441
+ sin = sin.squeeze(1).squeeze(0)
442
+ cos = cos[position_ids].unsqueeze(1)
443
+ sin = sin[position_ids].unsqueeze(1)
444
+ q_embed = (q * cos) + (rotate_half(q) * sin)
445
+ k_embed = (k * cos) + (rotate_half(k) * sin)
446
+ return q_embed, k_embed
447
+
448
+
449
+ def apply_rotary_pos_emb_L31(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
450
+ """Applies Rotary Position Embedding to the query and key tensors.
451
+
452
+ Args:
453
+ q (`torch.Tensor`): The query tensor.
454
+ k (`torch.Tensor`): The key tensor.
455
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
456
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
457
+ position_ids (`torch.Tensor`, *optional*):
458
+ Deprecated and unused.
459
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
460
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
461
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
462
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
463
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
464
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
465
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
466
+ Returns:
467
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
468
+ """
469
+ cos = cos.unsqueeze(unsqueeze_dim)
470
+ sin = sin.unsqueeze(unsqueeze_dim)
471
+ q_embed = (q * cos) + (rotate_half(q) * sin)
472
+ k_embed = (k * cos) + (rotate_half(k) * sin)
473
+ return q_embed, k_embed
474
+
475
+
476
+ class Qwen3MLP(nn.Module):
477
+ """
478
+ Qwen3MLP is a multi-layer perceptron module used in the Qwen3 model.
479
+
480
+ Args:
481
+ config: The configuration for the MLP.
482
+
483
+ Attributes:
484
+ pretraining_tp (int): The pretraining time periods.
485
+ hidden_size (int): The size of the hidden layer.
486
+ intermediate_size (int): The size of the intermediate layer.
487
+ gate_proj (nn.Linear): The linear projection for gating.
488
+ up_proj (nn.Linear): The linear projection for the up projection.
489
+ down_proj (nn.Linear): The linear projection for the down projection.
490
+ act_fn: The activation function.
491
+
492
+ """
493
+
494
+ def __init__(self, config):
495
+ super().__init__()
496
+ self.pretraining_tp = getattr(config, 'pretraining_tp', 1)
497
+ self.hidden_size = config.hidden_size
498
+ self.intermediate_size = config.intermediate_size
499
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
500
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
501
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
502
+ self.act_fn = ACT2FN[config.hidden_act]
503
+
504
+ def forward(self, x):
505
+ """
506
+ Forward pass of the MLP.
507
+
508
+ Args:
509
+ x: Input tensor.
510
+
511
+ Returns:
512
+ torch.Tensor: Output tensor.
513
+ """
514
+ if self.pretraining_tp > 1:
515
+ slice = self.intermediate_size // self.pretraining_tp
516
+ gate_proj_slices = self.gate_proj.weight.split(slice, dim=0)
517
+ up_proj_slices = self.up_proj.weight.split(slice, dim=0)
518
+ down_proj_slices = self.down_proj.weight.split(slice, dim=1)
519
+
520
+ gate_proj = torch.cat(
521
+ [F.linear(x, gate_proj_slices[i]) for i in range(self.pretraining_tp)],
522
+ dim=-1,
523
+ )
524
+ up_proj = torch.cat(
525
+ [F.linear(x, up_proj_slices[i]) for i in range(self.pretraining_tp)],
526
+ dim=-1,
527
+ )
528
+
529
+ intermediate_states = (self.act_fn(gate_proj) * up_proj).split(slice, dim=2)
530
+ down_proj = [
531
+ F.linear(intermediate_states[i], down_proj_slices[i])
532
+ for i in range(self.pretraining_tp)
533
+ ]
534
+ down_proj = sum(down_proj)
535
+ else:
536
+ down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
537
+
538
+ return down_proj
539
+
540
+
541
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
542
+ """
543
+ Repeat key and value tensors n times along the specified dimension.
544
+
545
+ Args:
546
+ hidden_states (torch.Tensor): Input tensor with shape (batch, num_key_value_heads, seqlen, head_dim).
547
+ n_rep (int): Number of times to repeat.
548
+
549
+ Returns:
550
+ torch.Tensor: Repeated tensor with shape (batch, num_key_value_heads * n_rep, seqlen, head_dim).
551
+ """
552
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
553
+ if n_rep == 1:
554
+ return hidden_states
555
+ hidden_states = hidden_states[:, :, None, :, :].expand(
556
+ batch, num_key_value_heads, n_rep, slen, head_dim
557
+ )
558
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
559
+
560
+
561
+ class Qwen3Attention(nn.Module):
562
+ """
563
+ Qwen3Attention is a multi-headed attention module based on the 'Attention Is All You Need' paper.
564
+
565
+ Args:
566
+ config (Qwen2Config): Configuration for the attention module.
567
+
568
+ Attributes:
569
+ config (Qwen2Config): Configuration for the attention module.
570
+ hidden_size (int): The size of the hidden layer.
571
+ num_heads (int): The number of attention heads.
572
+ head_dim (int): The dimension of each attention head.
573
+ num_key_value_heads (int): The number of key-value attention heads.
574
+ num_key_value_groups (int): The number of key-value groups.
575
+ pretraining_tp (int): The pretraining time periods.
576
+ max_position_embeddings (int): The maximum position embeddings.
577
+
578
+ """
579
+
580
+ def __init__(self, config: Qwen2Config):
581
+ super().__init__()
582
+ self.config = config
583
+ self.hidden_size = config.hidden_size
584
+ self.num_heads = config.num_attention_heads
585
+ self.head_dim = getattr(config, 'head_dim', self.hidden_size // self.num_heads)
586
+ self.num_key_value_heads = config.num_key_value_heads
587
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
588
+ self.pretraining_tp = getattr(config, 'pretraining_tp', 1)
589
+ self.max_position_embeddings = config.max_position_embeddings
590
+
591
+ if (self.head_dim * self.num_heads) != self.hidden_size:
592
+ raise ValueError(
593
+ f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
594
+ f" and `num_heads`: {self.num_heads})."
595
+ )
596
+ self.q_proj = nn.Linear(
597
+ self.hidden_size, self.num_heads * self.head_dim, bias=False
598
+ )
599
+ self.k_proj = nn.Linear(
600
+ self.hidden_size, self.num_key_value_heads * self.head_dim, bias=False
601
+ )
602
+ self.v_proj = nn.Linear(
603
+ self.hidden_size, self.num_key_value_heads * self.head_dim, bias=False
604
+ )
605
+ self.o_proj = nn.Linear(
606
+ self.num_heads * self.head_dim, self.hidden_size, bias=False
607
+ )
608
+
609
+ # Qwen3 uses RMSNorm for Q and K projections
610
+ self.q_norm = Qwen3RMSNorm(self.head_dim, eps=config.rms_norm_eps)
611
+ self.k_norm = Qwen3RMSNorm(self.head_dim, eps=config.rms_norm_eps)
612
+
613
+ self._init_rope()
614
+
615
+ def _init_rope(self):
616
+ rope_theta = getattr(self.config, 'rope_theta', 10000)
617
+ if self.config.rope_scaling is None:
618
+ self.rotary_emb = Qwen3RotaryEmbedding(
619
+ self.head_dim, max_position_embeddings=self.max_position_embeddings, base=rope_theta
620
+ )
621
+ else:
622
+ try:
623
+ scaling_type = self.config.rope_scaling["type"]
624
+ scaling_factor = self.config.rope_scaling["factor"]
625
+ if scaling_type == "linear":
626
+ self.rotary_emb = Qwen3LinearScalingRotaryEmbedding(
627
+ self.head_dim,
628
+ max_position_embeddings=self.max_position_embeddings,
629
+ scaling_factor=scaling_factor,
630
+ base=rope_theta,
631
+ )
632
+ elif scaling_type == "dynamic":
633
+ self.rotary_emb = Qwen3DynamicNTKScalingRotaryEmbedding(
634
+ self.head_dim,
635
+ max_position_embeddings=self.max_position_embeddings,
636
+ scaling_factor=scaling_factor,
637
+ base=rope_theta,
638
+ )
639
+ else:
640
+ raise ValueError(f"Unknown RoPE scaling type {scaling_type}")
641
+ except:
642
+ print("For Qwen3 with advanced RoPE")
643
+ self.rotary_emb = Qwen3RotaryEmbedding_L31(config=self.config)
644
+
645
+ def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
646
+ return (
647
+ tensor.view(bsz, seq_len, self.num_heads, self.head_dim)
648
+ .transpose(1, 2)
649
+ .contiguous()
650
+ )
651
+
652
+ def forward(
653
+ self,
654
+ hidden_states: torch.Tensor,
655
+ attention_mask: Optional[torch.Tensor] = None,
656
+ position_ids: Optional[torch.LongTensor] = None,
657
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
658
+ output_attentions: bool = False,
659
+ use_cache: bool = False,
660
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
661
+ bsz, q_len, _ = hidden_states.size()
662
+
663
+ if self.pretraining_tp > 1:
664
+ key_value_slicing = (
665
+ self.num_key_value_heads * self.head_dim
666
+ ) // self.pretraining_tp
667
+ query_slices = self.q_proj.weight.split(
668
+ (self.num_heads * self.head_dim) // self.pretraining_tp, dim=0
669
+ )
670
+ key_slices = self.k_proj.weight.split(key_value_slicing, dim=0)
671
+ value_slices = self.v_proj.weight.split(key_value_slicing, dim=0)
672
+
673
+ query_states = [
674
+ F.linear(hidden_states, query_slices[i])
675
+ for i in range(self.pretraining_tp)
676
+ ]
677
+ query_states = torch.cat(query_states, dim=-1)
678
+
679
+ key_states = [
680
+ F.linear(hidden_states, key_slices[i])
681
+ for i in range(self.pretraining_tp)
682
+ ]
683
+ key_states = torch.cat(key_states, dim=-1)
684
+
685
+ value_states = [
686
+ F.linear(hidden_states, value_slices[i])
687
+ for i in range(self.pretraining_tp)
688
+ ]
689
+ value_states = torch.cat(value_states, dim=-1)
690
+
691
+ else:
692
+ query_states = self.q_proj(hidden_states)
693
+ key_states = self.k_proj(hidden_states)
694
+ value_states = self.v_proj(hidden_states)
695
+
696
+ query_states = query_states.view(
697
+ bsz, q_len, self.num_heads, self.head_dim
698
+ ).transpose(1, 2)
699
+ key_states = key_states.view(
700
+ bsz, q_len, self.num_key_value_heads, self.head_dim
701
+ ).transpose(1, 2)
702
+ value_states = value_states.view(
703
+ bsz, q_len, self.num_key_value_heads, self.head_dim
704
+ ).transpose(1, 2)
705
+
706
+ # Apply RMSNorm to Q and K (Qwen3 specific)
707
+ query_states = self.q_norm(query_states)
708
+ key_states = self.k_norm(key_states)
709
+
710
+ kv_seq_len = key_states.shape[-2]
711
+ if past_key_value is not None:
712
+ kv_seq_len += past_key_value[0].shape[-2]
713
+ if isinstance(self.rotary_emb, Qwen3RotaryEmbedding_L31):
714
+ cos, sin = self.rotary_emb(query_states,position_ids)
715
+ query_states, key_states = apply_rotary_pos_emb_L31(query_states, key_states, cos, sin)
716
+ else:
717
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
718
+ query_states, key_states = apply_rotary_pos_emb(
719
+ query_states, key_states, cos, sin, position_ids
720
+ )
721
+
722
+ # [MODIFIED] Using KVCache mechanism for preallocated GPU memory optimization
723
+ # past_key_value is utilized to leverage previously computed key and value states.
724
+ # If past_key_value is available, reuse the states for k, v, and self_attention.
725
+ if past_key_value is not None:
726
+ key_states = past_key_value[0].cat(key_states, dim=2)
727
+ value_states = past_key_value[1].cat(value_states, dim=2)
728
+ # Reset past_key_value to avoid return past_key_value.
729
+ past_key_value = None
730
+
731
+ # repeat k/v heads if n_kv_heads < n_heads
732
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
733
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
734
+
735
+ attn_weights = torch.matmul(
736
+ query_states, key_states.transpose(2, 3)
737
+ ) / math.sqrt(self.head_dim)
738
+
739
+ if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
740
+ raise ValueError(
741
+ f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is"
742
+ f" {attn_weights.size()}"
743
+ )
744
+
745
+ if attention_mask is not None:
746
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
747
+ raise ValueError(
748
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
749
+ )
750
+ attn_weights = attn_weights + attention_mask
751
+
752
+ # upcast attention to fp32
753
+ attn_weights = nn.functional.softmax(
754
+ attn_weights, dim=-1, dtype=torch.float32
755
+ ).to(query_states.dtype)
756
+ attn_output = torch.matmul(attn_weights, value_states)
757
+
758
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
759
+ raise ValueError(
760
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
761
+ f" {attn_output.size()}"
762
+ )
763
+
764
+ attn_output = attn_output.transpose(1, 2).contiguous()
765
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
766
+
767
+ if self.pretraining_tp > 1:
768
+ attn_output = attn_output.split(
769
+ self.hidden_size // self.pretraining_tp, dim=2
770
+ )
771
+ o_proj_slices = self.o_proj.weight.split(
772
+ self.hidden_size // self.pretraining_tp, dim=1
773
+ )
774
+ attn_output = sum(
775
+ [
776
+ F.linear(attn_output[i], o_proj_slices[i])
777
+ for i in range(self.pretraining_tp)
778
+ ]
779
+ )
780
+ else:
781
+ attn_output = self.o_proj(attn_output)
782
+
783
+ if not output_attentions:
784
+ attn_weights = None
785
+
786
+ return attn_output, attn_weights, past_key_value
787
+
788
+
789
+ class Qwen3DecoderLayer(nn.Module):
790
+ """
791
+ Qwen3DecoderLayer represents a single layer of the Qwen3 decoder.
792
+
793
+ Args:
794
+ config (Qwen2Config): Configuration for the decoder layer.
795
+
796
+ Attributes:
797
+ hidden_size (int): The size of the hidden layer.
798
+ self_attn (Qwen3Attention): Multi-headed self-attention module.
799
+ mlp (Qwen3MLP): Multi-layer perceptron module.
800
+ input_layernorm (Qwen3RMSNorm): Layer normalization for input.
801
+ post_attention_layernorm (Qwen3RMSNorm): Layer normalization after self-attention.
802
+ """
803
+
804
+ def __init__(self, config: Qwen2Config):
805
+ super().__init__()
806
+ self.hidden_size = config.hidden_size
807
+ self.self_attn = Qwen3Attention(config=config)
808
+ self.mlp = Qwen3MLP(config)
809
+ self.input_layernorm = Qwen3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
810
+ self.post_attention_layernorm = Qwen3RMSNorm(
811
+ config.hidden_size, eps=config.rms_norm_eps
812
+ )
813
+
814
+ def forward(
815
+ self,
816
+ hidden_states: torch.Tensor,
817
+ attention_mask: Optional[torch.Tensor] = None,
818
+ position_ids: Optional[torch.LongTensor] = None,
819
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
820
+ output_attentions: Optional[bool] = False,
821
+ use_cache: Optional[bool] = False,
822
+ ) -> Tuple[
823
+ torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]
824
+ ]:
825
+ """
826
+ Forward pass for the Qwen3DecoderLayer.
827
+
828
+ Args:
829
+ hidden_states (torch.FloatTensor): Input tensor of shape `(batch, seq_len, embed_dim)`.
830
+ attention_mask (torch.FloatTensor, optional): Attention mask of size
831
+ `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
832
+ position_ids (torch.LongTensor, optional): Positional IDs tensor.
833
+ past_key_value (Tuple[torch.FloatTensor], optional): Cached past key and value projection states.
834
+ output_attentions (bool, optional): Whether or not to return the attentions tensors of all attention layers.
835
+ use_cache (bool, optional): If set to `True`, `past_key_values` key-value states are returned and can be
836
+ used to speed up decoding.
837
+
838
+ Returns:
839
+ Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]: Tuple containing:
840
+ - hidden_states (torch.FloatTensor): Output tensor.
841
+ - self_attn_weights (Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]): Self-attention weights if
842
+ `output_attentions` is `True`.
843
+ - present_key_value (Optional[Tuple[torch.FloatTensor]]): Cached key and value projection states if
844
+ `use_cache` is `True`.
845
+ """
846
+
847
+ residual = hidden_states
848
+
849
+ hidden_states = self.input_layernorm(hidden_states)
850
+
851
+ # Self Attention
852
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
853
+ hidden_states=hidden_states,
854
+ attention_mask=attention_mask,
855
+ position_ids=position_ids,
856
+ past_key_value=past_key_value,
857
+ output_attentions=output_attentions,
858
+ use_cache=use_cache,
859
+ )
860
+ hidden_states = residual + hidden_states
861
+
862
+ # Fully Connected
863
+ residual = hidden_states
864
+ hidden_states = self.post_attention_layernorm(hidden_states)
865
+ hidden_states = self.mlp(hidden_states)
866
+ hidden_states = residual + hidden_states
867
+
868
+ outputs = (hidden_states,)
869
+
870
+ if output_attentions:
871
+ outputs += (self_attn_weights,)
872
+
873
+ if use_cache:
874
+ outputs += (present_key_value,)
875
+
876
+ return outputs
877
+
878
+
879
+ QWEN3_START_DOCSTRING = r"""
880
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
881
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
882
+ etc.)
883
+
884
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
885
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
886
+ and behavior.
887
+
888
+ Parameters:
889
+ config ([`Qwen2Config`]):
890
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
891
+ load the weights associated with the model, only the configuration. Check out the
892
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
893
+ """
894
+
895
+
896
+ @add_start_docstrings(
897
+ "The bare Qwen3 Model outputting raw hidden-states without any specific head on top.",
898
+ QWEN3_START_DOCSTRING,
899
+ )
900
+ class Qwen3PreTrainedModel(PreTrainedModel):
901
+ config_class = Qwen2Config
902
+ base_model_prefix = "model"
903
+ supports_gradient_checkpointing = True
904
+ _no_split_modules = ["Qwen3DecoderLayer"]
905
+ _skip_keys_device_placement = "past_key_values"
906
+
907
+ def _init_weights(self, module):
908
+ std = self.config.initializer_range
909
+ if isinstance(module, nn.Linear):
910
+ module.weight.data.normal_(mean=0.0, std=std)
911
+ if module.bias is not None:
912
+ module.bias.data.zero_()
913
+ elif isinstance(module, nn.Embedding):
914
+ module.weight.data.normal_(mean=0.0, std=std)
915
+ if module.padding_idx is not None:
916
+ module.weight.data[module.padding_idx].zero_()
917
+
918
+ def _set_gradient_checkpointing(self, module, value=False):
919
+ if isinstance(module, Qwen3Model):
920
+ module.gradient_checkpointing = value
921
+
922
+
923
+ QWEN3_INPUTS_DOCSTRING = r"""
924
+ Args:
925
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
926
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
927
+ it.
928
+
929
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
930
+ [`PreTrainedTokenizer.__call__`] for details.
931
+
932
+ [What are input IDs?](../glossary#input-ids)
933
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
934
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
935
+
936
+ - 1 for tokens that are **not masked**,
937
+ - 0 for tokens that are **masked**.
938
+
939
+ [What are attention masks?](../glossary#attention-mask)
940
+
941
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
942
+ [`PreTrainedTokenizer.__call__`] for details.
943
+
944
+ If `past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see
945
+ `past_key_values`).
946
+
947
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
948
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
949
+ information on the default strategy.
950
+
951
+ - 1 indicates the head is **not masked**,
952
+ - 0 indicates the head is **masked**.
953
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
954
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
955
+ config.n_positions - 1]`.
956
+
957
+ [What are position IDs?](../glossary#position-ids)
958
+ past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
959
+ Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape
960
+ `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of shape
961
+ `(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`.
962
+
963
+ Contains pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
964
+ blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.
965
+
966
+ If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
967
+ don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
968
+ `decoder_input_ids` of shape `(batch_size, sequence_length)`.
969
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
970
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
971
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
972
+ model's internal embedding lookup matrix.
973
+ use_cache (`bool`, *optional*):
974
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
975
+ `past_key_values`).
976
+ output_attentions (`bool`, *optional*):
977
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
978
+ tensors for more detail.
979
+ output_hidden_states (`bool`, *optional*):
980
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
981
+ more detail.
982
+ return_dict (`bool`, *optional*):
983
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
984
+ """
985
+
986
+
987
+ @add_start_docstrings(
988
+ "The bare Qwen3 Model outputting raw hidden-states without any specific head on top.",
989
+ QWEN3_START_DOCSTRING,
990
+ )
991
+ class Qwen3Model(Qwen3PreTrainedModel):
992
+ """
993
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`Qwen3DecoderLayer`]
994
+
995
+ Args:
996
+ config: Qwen2Config
997
+ """
998
+
999
+ def __init__(self, config: Qwen2Config):
1000
+ super().__init__(config)
1001
+ self.padding_idx = config.pad_token_id
1002
+ self.vocab_size = config.vocab_size
1003
+
1004
+ self.embed_tokens = nn.Embedding(
1005
+ config.vocab_size, config.hidden_size, self.padding_idx
1006
+ )
1007
+ self.layers = nn.ModuleList(
1008
+ [Qwen3DecoderLayer(config) for _ in range(config.num_hidden_layers)]
1009
+ )
1010
+ self.norm = Qwen3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
1011
+
1012
+ self.gradient_checkpointing = False
1013
+ # Initialize weights and apply final processing
1014
+ self.post_init()
1015
+
1016
+ def get_input_embeddings(self):
1017
+ return self.embed_tokens
1018
+
1019
+ def set_input_embeddings(self, value):
1020
+ self.embed_tokens = value
1021
+
1022
+ # Copied from transformers.models.bart.modeling_bart.BartDecoder._prepare_decoder_attention_mask
1023
+ def _prepare_decoder_attention_mask(
1024
+ self, attention_mask, input_shape, inputs_embeds, past_key_values_length
1025
+ ):
1026
+ # create causal mask
1027
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
1028
+ combined_attention_mask = None
1029
+ if input_shape[-1] > 1:
1030
+ combined_attention_mask = _make_causal_mask(
1031
+ input_shape,
1032
+ # inputs_embeds.dtype,
1033
+ torch.float32, # [MODIFIED] force to cast to float32
1034
+ device=inputs_embeds.device,
1035
+ past_key_values_length=past_key_values_length,
1036
+ )
1037
+
1038
+ if attention_mask is not None:
1039
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
1040
+ expanded_attn_mask = _expand_mask(
1041
+ attention_mask, inputs_embeds.dtype, tgt_len=input_shape[-1]
1042
+ ).to(inputs_embeds.device)
1043
+ combined_attention_mask = (
1044
+ expanded_attn_mask
1045
+ if combined_attention_mask is None
1046
+ else expanded_attn_mask + combined_attention_mask
1047
+ )
1048
+
1049
+ if hasattr(self, "tree_mask") and self.tree_mask is not None:
1050
+ tree_mask = self.tree_mask
1051
+ tree_len = tree_mask.size(-1)
1052
+ combined_attention_mask[:, :, -tree_len:, -tree_len:][
1053
+ tree_mask == 0
1054
+ ] = combined_attention_mask.min()
1055
+
1056
+ return combined_attention_mask
1057
+
1058
+ @add_start_docstrings_to_model_forward(QWEN3_INPUTS_DOCSTRING)
1059
+ def forward(
1060
+ self,
1061
+ input_ids: torch.LongTensor = None,
1062
+ attention_mask: Optional[torch.Tensor] = None,
1063
+ position_ids: Optional[torch.LongTensor] = None,
1064
+ past_key_values=None, # [MODIFIED] past_key_value is KVCache class
1065
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1066
+ use_cache: Optional[bool] = None,
1067
+ output_attentions: Optional[bool] = None,
1068
+ output_hidden_states: Optional[bool] = None,
1069
+ return_dict: Optional[bool] = None,
1070
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
1071
+ output_attentions = (
1072
+ output_attentions
1073
+ if output_attentions is not None
1074
+ else self.config.output_attentions
1075
+ )
1076
+ output_hidden_states = (
1077
+ output_hidden_states
1078
+ if output_hidden_states is not None
1079
+ else self.config.output_hidden_states
1080
+ )
1081
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
1082
+
1083
+ return_dict = (
1084
+ return_dict if return_dict is not None else self.config.use_return_dict
1085
+ )
1086
+
1087
+ # retrieve input_ids and inputs_embeds
1088
+ if input_ids is not None and inputs_embeds is not None:
1089
+ raise ValueError(
1090
+ "You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time"
1091
+ )
1092
+ elif input_ids is not None:
1093
+ batch_size, seq_length = input_ids.shape
1094
+ elif inputs_embeds is not None:
1095
+ batch_size, seq_length, _ = inputs_embeds.shape
1096
+ else:
1097
+ raise ValueError(
1098
+ "You have to specify either decoder_input_ids or decoder_inputs_embeds"
1099
+ )
1100
+
1101
+ seq_length_with_past = seq_length
1102
+ past_key_values_length = 0
1103
+
1104
+ if past_key_values is not None:
1105
+ past_key_values_length = past_key_values[0][0].shape[2]
1106
+ seq_length_with_past = seq_length_with_past + past_key_values_length
1107
+
1108
+ if position_ids is None:
1109
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
1110
+ position_ids = torch.arange(
1111
+ past_key_values_length,
1112
+ seq_length + past_key_values_length,
1113
+ dtype=torch.long,
1114
+ device=device,
1115
+ )
1116
+ position_ids = position_ids.unsqueeze(0).view(-1, seq_length)
1117
+ else:
1118
+ position_ids = position_ids.view(-1, seq_length).long()
1119
+
1120
+ if inputs_embeds is None:
1121
+ inputs_embeds = self.embed_tokens(input_ids)
1122
+ # embed positions
1123
+ if attention_mask is None:
1124
+ attention_mask = torch.ones(
1125
+ (batch_size, seq_length_with_past),
1126
+ dtype=torch.bool,
1127
+ device=inputs_embeds.device,
1128
+ )
1129
+ attention_mask = self._prepare_decoder_attention_mask(
1130
+ attention_mask,
1131
+ (batch_size, seq_length),
1132
+ inputs_embeds,
1133
+ past_key_values_length,
1134
+ )
1135
+
1136
+ hidden_states = inputs_embeds
1137
+
1138
+ if self.gradient_checkpointing and self.training:
1139
+ if use_cache:
1140
+ logger.warning_once(
1141
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
1142
+ )
1143
+ use_cache = False
1144
+
1145
+ # decoder layers
1146
+ all_hidden_states = () if 1 else None
1147
+ all_self_attns = () if output_attentions else None
1148
+ next_decoder_cache = () if use_cache else None
1149
+
1150
+ for idx, decoder_layer in enumerate(self.layers):
1151
+
1152
+ if idx==len(self.layers)-3 or idx==len(self.layers)//2 or idx==2:
1153
+ all_hidden_states += (hidden_states,)
1154
+
1155
+ past_key_value = (
1156
+ past_key_values[idx] if past_key_values is not None else None
1157
+ )
1158
+
1159
+ if self.gradient_checkpointing and self.training:
1160
+
1161
+ def create_custom_forward(module):
1162
+ def custom_forward(*inputs):
1163
+ # None for past_key_value
1164
+ return module(*inputs, output_attentions, None)
1165
+
1166
+ return custom_forward
1167
+
1168
+ layer_outputs = torch.utils.checkpoint.checkpoint(
1169
+ create_custom_forward(decoder_layer),
1170
+ hidden_states,
1171
+ attention_mask,
1172
+ position_ids,
1173
+ None,
1174
+ )
1175
+ else:
1176
+ layer_outputs = decoder_layer(
1177
+ hidden_states,
1178
+ attention_mask=attention_mask,
1179
+ position_ids=position_ids,
1180
+ past_key_value=past_key_value,
1181
+ output_attentions=output_attentions,
1182
+ use_cache=use_cache,
1183
+ )
1184
+
1185
+ hidden_states = layer_outputs[0]
1186
+
1187
+ if use_cache:
1188
+ next_decoder_cache += (layer_outputs[2 if output_attentions else 1],)
1189
+
1190
+ if output_attentions:
1191
+ all_self_attns += (layer_outputs[1],)
1192
+
1193
+ hidden_states = self.norm(hidden_states)
1194
+
1195
+ # add hidden states from the last decoder layer
1196
+ if output_hidden_states:
1197
+ all_hidden_states += (hidden_states,)
1198
+
1199
+ # !!!
1200
+ # all_hidden_states += (hidden_states,)
1201
+
1202
+ next_cache = next_decoder_cache if use_cache else None
1203
+ if not return_dict:
1204
+ return tuple(
1205
+ v
1206
+ for v in [hidden_states, next_cache, all_hidden_states, all_self_attns]
1207
+ if v is not None
1208
+ )
1209
+ return BaseModelOutputWithPast(
1210
+ last_hidden_state=hidden_states,
1211
+ past_key_values=next_cache,
1212
+ hidden_states=all_hidden_states,
1213
+ attentions=all_self_attns,
1214
+ )
1215
+
1216
+
1217
+ class Qwen3ForCausalLM(Qwen3PreTrainedModel):
1218
+ _tied_weights_keys = ["lm_head.weight"]
1219
+
1220
+ def __init__(self, config):
1221
+ super().__init__(config)
1222
+ self.model = Qwen3Model(config)
1223
+ self.pretraining_tp = getattr(config, 'pretraining_tp', 1)
1224
+ self.vocab_size = config.vocab_size
1225
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1226
+
1227
+ # Initialize weights and apply final processing
1228
+ self.post_init()
1229
+
1230
+ def get_input_embeddings(self):
1231
+ return self.model.embed_tokens
1232
+
1233
+ def set_input_embeddings(self, value):
1234
+ self.model.embed_tokens = value
1235
+
1236
+ def get_output_embeddings(self):
1237
+ return self.lm_head
1238
+
1239
+ def set_output_embeddings(self, new_embeddings):
1240
+ self.lm_head = new_embeddings
1241
+
1242
+ def set_decoder(self, decoder):
1243
+ self.model = decoder
1244
+
1245
+ def get_decoder(self):
1246
+ return self.model
1247
+
1248
+ @add_start_docstrings_to_model_forward(QWEN3_INPUTS_DOCSTRING)
1249
+ @replace_return_docstrings(
1250
+ output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC
1251
+ )
1252
+ def forward(
1253
+ self,
1254
+ input_ids: torch.LongTensor = None,
1255
+ attention_mask: Optional[torch.Tensor] = None,
1256
+ position_ids: Optional[torch.LongTensor] = None,
1257
+ past_key_values=None, # [MODIFIED] past_key_value is KVCache class
1258
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1259
+ labels: Optional[torch.LongTensor] = None,
1260
+ use_cache: Optional[bool] = None,
1261
+ output_attentions: Optional[bool] = None,
1262
+ output_hidden_states: Optional[bool] = None,
1263
+ return_dict: Optional[bool] = None,
1264
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
1265
+ r"""
1266
+ Args:
1267
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1268
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1269
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1270
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1271
+
1272
+ Returns:
1273
+
1274
+ Example:
1275
+
1276
+ ```python
1277
+ >>> from transformers import AutoTokenizer, Qwen3ForCausalLM
1278
+
1279
+ >>> model = Qwen3ForCausalLM.from_pretrained(PATH_TO_CONVERTED_WEIGHTS)
1280
+ >>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER)
1281
+
1282
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
1283
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
1284
+
1285
+ >>> # Generate
1286
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
1287
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1288
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
1289
+ ```"""
1290
+
1291
+ output_attentions = (
1292
+ output_attentions
1293
+ if output_attentions is not None
1294
+ else self.config.output_attentions
1295
+ )
1296
+ output_hidden_states = (
1297
+ output_hidden_states
1298
+ if output_hidden_states is not None
1299
+ else self.config.output_hidden_states
1300
+ )
1301
+ return_dict = (
1302
+ return_dict if return_dict is not None else self.config.use_return_dict
1303
+ )
1304
+
1305
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1306
+ outputs = self.model(
1307
+ input_ids=input_ids,
1308
+ attention_mask=attention_mask,
1309
+ position_ids=position_ids,
1310
+ past_key_values=past_key_values,
1311
+ inputs_embeds=inputs_embeds,
1312
+ use_cache=use_cache,
1313
+ output_attentions=output_attentions,
1314
+ output_hidden_states=output_hidden_states,
1315
+ return_dict=return_dict,
1316
+ )
1317
+
1318
+ hidden_states = outputs[0]
1319
+ if self.pretraining_tp > 1:
1320
+ lm_head_slices = self.lm_head.weight.split(
1321
+ self.vocab_size // self.pretraining_tp, dim=0
1322
+ )
1323
+ logits = [
1324
+ F.linear(hidden_states, lm_head_slices[i])
1325
+ for i in range(self.pretraining_tp)
1326
+ ]
1327
+ logits = torch.cat(logits, dim=-1)
1328
+ else:
1329
+ logits = self.lm_head(hidden_states)
1330
+ logits = logits.float()
1331
+
1332
+ loss = None
1333
+ if labels is not None:
1334
+ # Shift so that tokens < n predict n
1335
+ shift_logits = logits[..., :-1, :].contiguous()
1336
+ shift_labels = labels[..., 1:].contiguous()
1337
+ # Flatten the tokens
1338
+ loss_fct = CrossEntropyLoss()
1339
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
1340
+ shift_labels = shift_labels.view(-1)
1341
+ # Enable model parallelism
1342
+ shift_labels = shift_labels.to(shift_logits.device)
1343
+ loss = loss_fct(shift_logits, shift_labels)
1344
+
1345
+ if not return_dict:
1346
+ output = (logits,) + outputs[1:]
1347
+ return (loss,) + output if loss is not None else output
1348
+
1349
+ return CausalLMOutputWithPast(
1350
+ loss=loss,
1351
+ logits=logits,
1352
+ past_key_values=outputs.past_key_values,
1353
+ hidden_states=outputs.hidden_states,
1354
+ attentions=outputs.attentions,
1355
+ )
1356
+
1357
+ def prepare_inputs_for_generation(
1358
+ self,
1359
+ input_ids,
1360
+ past_key_values=None,
1361
+ attention_mask=None,
1362
+ inputs_embeds=None,
1363
+ **kwargs,
1364
+ ):
1365
+ if past_key_values:
1366
+ input_ids = input_ids[:, -1:]
1367
+
1368
+ position_ids = kwargs.get("position_ids", None)
1369
+ if attention_mask is not None and position_ids is None:
1370
+ # create position_ids on the fly for batch generation
1371
+ position_ids = attention_mask.long().cumsum(-1) - 1
1372
+ position_ids.masked_fill_(attention_mask == 0, 1)
1373
+ if past_key_values:
1374
+ position_ids = position_ids[:, -1].unsqueeze(-1)
1375
+
1376
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
1377
+ if inputs_embeds is not None and past_key_values is None:
1378
+ model_inputs = {"inputs_embeds": inputs_embeds}
1379
+ else:
1380
+ model_inputs = {"input_ids": input_ids}
1381
+
1382
+ model_inputs.update(
1383
+ {
1384
+ "position_ids": position_ids,
1385
+ "past_key_values": past_key_values,
1386
+ "use_cache": kwargs.get("use_cache"),
1387
+ "attention_mask": attention_mask,
1388
+ }
1389
+ )
1390
+ return model_inputs
1391
+
1392
+ @staticmethod
1393
+ def _reorder_cache(past_key_values, beam_idx):
1394
+ reordered_past = ()
1395
+ for layer_past in past_key_values:
1396
+ reordered_past += (
1397
+ tuple(
1398
+ past_state.index_select(0, beam_idx.to(past_state.device))
1399
+ for past_state in layer_past
1400
+ ),
1401
+ )
1402
+ return reordered_past
1403
+
1404
+
1405
+ @add_start_docstrings(
1406
+ """
1407
+ The LLaMa Model transformer with a sequence classification head on top (linear layer).
1408
+
1409
+ [`Qwen3ForSequenceClassification`] uses the last token in order to do the classification, as other causal models
1410
+ (e.g. GPT-2) do.
1411
+
1412
+ Since it does classification on the last token, it requires to know the position of the last token. If a
1413
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
1414
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
1415
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
1416
+ each row of the batch).
1417
+ """,
1418
+ QWEN3_START_DOCSTRING,
1419
+ )
1420
+ class Qwen3ForSequenceClassification(Qwen3PreTrainedModel):
1421
+ def __init__(self, config):
1422
+ super().__init__(config)
1423
+ self.num_labels = config.num_labels
1424
+ self.model = Qwen3Model(config)
1425
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
1426
+
1427
+ # Initialize weights and apply final processing
1428
+ self.post_init()
1429
+
1430
+ def get_input_embeddings(self):
1431
+ return self.model.embed_tokens
1432
+
1433
+ def set_input_embeddings(self, value):
1434
+ self.model.embed_tokens = value
1435
+
1436
+ @add_start_docstrings_to_model_forward(QWEN3_INPUTS_DOCSTRING)
1437
+ def forward(
1438
+ self,
1439
+ input_ids: torch.LongTensor = None,
1440
+ attention_mask: Optional[torch.Tensor] = None,
1441
+ position_ids: Optional[torch.LongTensor] = None,
1442
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1443
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1444
+ labels: Optional[torch.LongTensor] = None,
1445
+ use_cache: Optional[bool] = None,
1446
+ output_attentions: Optional[bool] = None,
1447
+ output_hidden_states: Optional[bool] = None,
1448
+ return_dict: Optional[bool] = None,
1449
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
1450
+ r"""
1451
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1452
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1453
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1454
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1455
+ """
1456
+ return_dict = (
1457
+ return_dict if return_dict is not None else self.config.use_return_dict
1458
+ )
1459
+
1460
+ transformer_outputs = self.model(
1461
+ input_ids,
1462
+ attention_mask=attention_mask,
1463
+ position_ids=position_ids,
1464
+ past_key_values=past_key_values,
1465
+ inputs_embeds=inputs_embeds,
1466
+ use_cache=use_cache,
1467
+ output_attentions=output_attentions,
1468
+ output_hidden_states=output_hidden_states,
1469
+ return_dict=return_dict,
1470
+ )
1471
+ hidden_states = transformer_outputs[0]
1472
+ logits = self.score(hidden_states)
1473
+
1474
+ if input_ids is not None:
1475
+ batch_size = input_ids.shape[0]
1476
+ else:
1477
+ batch_size = inputs_embeds.shape[0]
1478
+
1479
+ if self.config.pad_token_id is None and batch_size != 1:
1480
+ raise ValueError(
1481
+ "Cannot handle batch sizes > 1 if no padding token is defined."
1482
+ )
1483
+ if self.config.pad_token_id is None:
1484
+ sequence_lengths = -1
1485
+ else:
1486
+ if input_ids is not None:
1487
+ sequence_lengths = (
1488
+ torch.ne(input_ids, self.config.pad_token_id).sum(-1) - 1
1489
+ ).to(logits.device)
1490
+ else:
1491
+ sequence_lengths = -1
1492
+
1493
+ pooled_logits = logits[
1494
+ torch.arange(batch_size, device=logits.device), sequence_lengths
1495
+ ]
1496
+
1497
+ loss = None
1498
+ if labels is not None:
1499
+ labels = labels.to(logits.device)
1500
+ if self.config.problem_type is None:
1501
+ if self.num_labels == 1:
1502
+ self.config.problem_type = "regression"
1503
+ elif self.num_labels > 1 and (
1504
+ labels.dtype == torch.long or labels.dtype == torch.int
1505
+ ):
1506
+ self.config.problem_type = "single_label_classification"
1507
+ else:
1508
+ self.config.problem_type = "multi_label_classification"
1509
+
1510
+ if self.config.problem_type == "regression":
1511
+ loss_fct = MSELoss()
1512
+ if self.num_labels == 1:
1513
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
1514
+ else:
1515
+ loss = loss_fct(pooled_logits, labels)
1516
+ elif self.config.problem_type == "single_label_classification":
1517
+ loss_fct = CrossEntropyLoss()
1518
+ loss = loss_fct(
1519
+ pooled_logits.view(-1, self.num_labels), labels.view(-1)
1520
+ )
1521
+ elif self.config.problem_type == "multi_label_classification":
1522
+ loss_fct = BCEWithLogitsLoss()
1523
+ loss = loss_fct(pooled_logits, labels)
1524
+ if not return_dict:
1525
+ output = (pooled_logits,) + transformer_outputs[1:]
1526
+ return ((loss,) + output) if loss is not None else output
1527
+
1528
+ return SequenceClassifierOutputWithPast(
1529
+ loss=loss,
1530
+ logits=pooled_logits,
1531
+ past_key_values=transformer_outputs.past_key_values,
1532
+ hidden_states=transformer_outputs.hidden_states,
1533
+ attentions=transformer_outputs.attentions,
1534
+ )