BN7002 commited on
Commit
2a68387
1 Parent(s): 177ff31

Create modeling_qwen.py

Browse files
Files changed (1) hide show
  1. modeling_qwen.py +1430 -0
modeling_qwen.py ADDED
@@ -0,0 +1,1430 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # --- This file is to make quantized repo good to go. ---
3
+ # Copyright 2024 The Qwen team, Alibaba Group and the HuggingFace Inc. team. All rights reserved.
4
+ #
5
+ # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
6
+ # and OPT implementations in this library. It has been modified from its
7
+ # original forms to accommodate minor architectural differences compared
8
+ # to GPT-NeoX and OPT used by the Meta AI team that trained the model.
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
+ """ PyTorch Qwen2 model."""
22
+ from transformers import Qwen2Config
23
+ import inspect
24
+ import math
25
+ import os
26
+ import warnings
27
+ from typing import List, Optional, Tuple, Union
28
+
29
+ import torch
30
+ import torch.nn.functional as F
31
+ import torch.utils.checkpoint
32
+ from torch import nn
33
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
34
+
35
+ from transformers.activations import ACT2FN
36
+ from transformers.cache_utils import Cache, DynamicCache
37
+ from transformers.modeling_attn_mask_utils import _prepare_4d_causal_attention_mask, _prepare_4d_causal_attention_mask_for_sdpa, _prepare_4d_attention_mask, _prepare_4d_attention_mask_for_sdpa
38
+ from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast, SequenceClassifierOutputWithPast
39
+ from transformers.modeling_utils import PreTrainedModel
40
+ from transformers.utils import (
41
+ add_start_docstrings,
42
+ add_start_docstrings_to_model_forward,
43
+ is_flash_attn_2_available,
44
+ is_flash_attn_greater_or_equal_2_10,
45
+ logging,
46
+ replace_return_docstrings,
47
+ )
48
+
49
+
50
+ if is_flash_attn_2_available():
51
+ from flash_attn import flash_attn_func, flash_attn_varlen_func
52
+ from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input # noqa
53
+
54
+ _flash_supports_window_size = "window_size" in list(inspect.signature(flash_attn_func).parameters)
55
+
56
+
57
+ logger = logging.get_logger(__name__)
58
+
59
+
60
+ _CHECKPOINT_FOR_DOC = "Qwen/Qwen2-7B-beta"
61
+ _CONFIG_FOR_DOC = "Qwen2Config"
62
+
63
+ QWEN2_PRETRAINED_MODEL_ARCHIVE_LIST = [
64
+ "Qwen/Qwen2-7B-beta",
65
+ # See all Qwen2 models at https://huggingface.co/models?filter=qwen2
66
+ ]
67
+
68
+
69
+ # Copied from transformers.models.llama.modeling_llama._get_unpad_data
70
+ def _get_unpad_data(attention_mask):
71
+ seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
72
+ indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
73
+ max_seqlen_in_batch = seqlens_in_batch.max().item()
74
+ cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.int32), (1, 0))
75
+ return (
76
+ indices,
77
+ cu_seqlens,
78
+ max_seqlen_in_batch,
79
+ )
80
+
81
+
82
+ # Copied from transformers.models.llama.modeling_llama.LlamaRMSNorm with Llama->Qwen2
83
+ class Qwen2RMSNorm(nn.Module):
84
+ def __init__(self, hidden_size, eps=1e-6):
85
+ """
86
+ Qwen2RMSNorm is equivalent to T5LayerNorm
87
+ """
88
+ super().__init__()
89
+ self.weight = nn.Parameter(torch.ones(hidden_size))
90
+ self.variance_epsilon = eps
91
+
92
+ def forward(self, hidden_states):
93
+ input_dtype = hidden_states.dtype
94
+ hidden_states = hidden_states.to(torch.float32)
95
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
96
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
97
+ return self.weight * hidden_states.to(input_dtype)
98
+
99
+
100
+ # Copied from transformers.models.mistral.modeling_mistral.MistralRotaryEmbedding with Mistral->Qwen2
101
+ class Qwen2RotaryEmbedding(nn.Module):
102
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
103
+ super().__init__()
104
+
105
+ self.dim = dim
106
+ self.max_position_embeddings = max_position_embeddings
107
+ self.base = base
108
+ inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2, dtype=torch.int64).float().to(device) / self.dim))
109
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
110
+
111
+ # Build here to make `torch.jit.trace` work.
112
+ self._set_cos_sin_cache(
113
+ seq_len=max_position_embeddings, device=self.inv_freq.device, dtype=torch.get_default_dtype()
114
+ )
115
+
116
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
117
+ self.max_seq_len_cached = seq_len
118
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=torch.int64).type_as(self.inv_freq)
119
+
120
+ freqs = torch.outer(t, self.inv_freq)
121
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
122
+ emb = torch.cat((freqs, freqs), dim=-1)
123
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
124
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
125
+
126
+ def forward(self, x, seq_len=None):
127
+ # x: [bs, num_attention_heads, seq_len, head_size]
128
+ if seq_len > self.max_seq_len_cached:
129
+ self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=x.dtype)
130
+
131
+ return (
132
+ self.cos_cached[:seq_len].to(dtype=x.dtype),
133
+ self.sin_cached[:seq_len].to(dtype=x.dtype),
134
+ )
135
+
136
+
137
+ # Copied from transformers.models.llama.modeling_llama.rotate_half
138
+ def rotate_half(x):
139
+ """Rotates half the hidden dims of the input."""
140
+ x1 = x[..., : x.shape[-1] // 2]
141
+ x2 = x[..., x.shape[-1] // 2 :]
142
+ return torch.cat((-x2, x1), dim=-1)
143
+
144
+
145
+ # Copied from transformers.models.mistral.modeling_mistral.apply_rotary_pos_emb
146
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids, unsqueeze_dim=1):
147
+ """Applies Rotary Position Embedding to the query and key tensors.
148
+
149
+ Args:
150
+ q (`torch.Tensor`): The query tensor.
151
+ k (`torch.Tensor`): The key tensor.
152
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
153
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
154
+ position_ids (`torch.Tensor`):
155
+ The position indices of the tokens corresponding to the query and key tensors. For example, this can be
156
+ used to pass offsetted position ids when working with a KV-cache.
157
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
158
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
159
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
160
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
161
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
162
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
163
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
164
+ Returns:
165
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
166
+ """
167
+ cos = cos[position_ids].unsqueeze(unsqueeze_dim)
168
+ sin = sin[position_ids].unsqueeze(unsqueeze_dim)
169
+ q_embed = (q * cos) + (rotate_half(q) * sin)
170
+ k_embed = (k * cos) + (rotate_half(k) * sin)
171
+ return q_embed, k_embed
172
+
173
+
174
+ # Copied from transformers.models.mistral.modeling_mistral.MistralMLP with Mistral->Qwen2
175
+ class Qwen2MLP(nn.Module):
176
+ def __init__(self, config):
177
+ super().__init__()
178
+ self.config = config
179
+ self.hidden_size = config.hidden_size
180
+ self.intermediate_size = config.intermediate_size
181
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
182
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
183
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
184
+ self.act_fn = ACT2FN[config.hidden_act]
185
+
186
+ def forward(self, x):
187
+ return self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
188
+
189
+
190
+ # Copied from transformers.models.llama.modeling_llama.repeat_kv
191
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
192
+ """
193
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
194
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
195
+ """
196
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
197
+ if n_rep == 1:
198
+ return hidden_states
199
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
200
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
201
+
202
+
203
+ class Qwen2Attention(nn.Module):
204
+ """
205
+ Multi-headed attention from 'Attention Is All You Need' paper. Modified to use sliding window attention: Longformer
206
+ and "Generating Long Sequences with Sparse Transformers".
207
+ """
208
+
209
+ def __init__(self, config: Qwen2Config, layer_idx: Optional[int] = None):
210
+ super().__init__()
211
+ self.config = config
212
+ self.layer_idx = layer_idx
213
+ if layer_idx is None:
214
+ logger.warning_once(
215
+ f"Instantiating {self.__class__.__name__} without passing `layer_idx` is not recommended and will "
216
+ "to errors during the forward call, if caching is used. Please make sure to provide a `layer_idx` "
217
+ "when creating this class."
218
+ )
219
+
220
+ self.hidden_size = config.hidden_size
221
+ self.num_heads = config.num_attention_heads
222
+ self.head_dim = self.hidden_size // self.num_heads
223
+ self.num_key_value_heads = config.num_key_value_heads
224
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
225
+ self.max_position_embeddings = config.max_position_embeddings
226
+ self.rope_theta = config.rope_theta
227
+ self.is_causal = True
228
+ self.attention_dropout = config.attention_dropout
229
+
230
+ if (self.head_dim * self.num_heads) != self.hidden_size:
231
+ raise ValueError(
232
+ f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
233
+ f" and `num_heads`: {self.num_heads})."
234
+ )
235
+ self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=True)
236
+ self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=True)
237
+ self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=True)
238
+ self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=False)
239
+
240
+ self.rotary_emb = Qwen2RotaryEmbedding(
241
+ self.head_dim,
242
+ max_position_embeddings=self.max_position_embeddings,
243
+ base=self.rope_theta,
244
+ )
245
+
246
+ def forward(
247
+ self,
248
+ hidden_states: torch.Tensor,
249
+ attention_mask: Optional[torch.Tensor] = None,
250
+ position_ids: Optional[torch.LongTensor] = None,
251
+ past_key_value: Optional[Cache] = None,
252
+ output_attentions: bool = False,
253
+ use_cache: bool = False,
254
+ **kwargs,
255
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
256
+ if "padding_mask" in kwargs:
257
+ warnings.warn(
258
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
259
+ )
260
+ bsz, q_len, _ = hidden_states.size()
261
+
262
+ query_states = self.q_proj(hidden_states)
263
+ key_states = self.k_proj(hidden_states)
264
+ value_states = self.v_proj(hidden_states)
265
+
266
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
267
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
268
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
269
+
270
+ kv_seq_len = key_states.shape[-2]
271
+ if past_key_value is not None:
272
+ if self.layer_idx is None:
273
+ raise ValueError(
274
+ f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
275
+ "for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
276
+ "with a layer index."
277
+ )
278
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
279
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
280
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
281
+
282
+ if past_key_value is not None:
283
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
284
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
285
+
286
+ # repeat k/v heads if n_kv_heads < n_heads
287
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
288
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
289
+
290
+ attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
291
+
292
+ if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
293
+ raise ValueError(
294
+ f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is"
295
+ f" {attn_weights.size()}"
296
+ )
297
+
298
+ if attention_mask is not None:
299
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
300
+ raise ValueError(
301
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
302
+ )
303
+
304
+ attn_weights = attn_weights + attention_mask
305
+
306
+ # upcast attention to fp32
307
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
308
+ attn_weights = nn.functional.dropout(attn_weights, p=self.attention_dropout, training=self.training)
309
+ attn_output = torch.matmul(attn_weights, value_states)
310
+
311
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
312
+ raise ValueError(
313
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
314
+ f" {attn_output.size()}"
315
+ )
316
+
317
+ attn_output = attn_output.transpose(1, 2).contiguous()
318
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
319
+
320
+ attn_output = self.o_proj(attn_output)
321
+
322
+ if not output_attentions:
323
+ attn_weights = None
324
+
325
+ return attn_output, attn_weights, past_key_value
326
+
327
+
328
+ class Qwen2FlashAttention2(Qwen2Attention):
329
+ """
330
+ Qwen2 flash attention module, following Qwen2 attention module. This module inherits from `Qwen2Attention`
331
+ as the weights of the module stays untouched. The only required change would be on the forward pass
332
+ where it needs to correctly call the public API of flash attention and deal with padding tokens
333
+ in case the input contains any of them. Additionally, for sliding window attention, we apply SWA only to the bottom
334
+ config.max_window_layers layers.
335
+ """
336
+
337
+ # Copied from transformers.models.llama.modeling_llama.LlamaFlashAttention2.__init__
338
+ def __init__(self, *args, **kwargs):
339
+ super().__init__(*args, **kwargs)
340
+
341
+ # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
342
+ # flash_attn<2.1 generates top-left aligned causal mask, while what is needed here is bottom-right alignement, that was made default for flash_attn>=2.1. This attribute is used to handle this difference. Reference: https://github.com/Dao-AILab/flash-attention/releases/tag/v2.1.0.
343
+ # Beware that with flash_attn<2.1, using q_seqlen != k_seqlen (except for the case q_seqlen == 1) produces a wrong mask (top-left).
344
+ self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
345
+
346
+ def forward(
347
+ self,
348
+ hidden_states: torch.Tensor,
349
+ attention_mask: Optional[torch.Tensor] = None,
350
+ position_ids: Optional[torch.LongTensor] = None,
351
+ past_key_value: Optional[Cache] = None,
352
+ output_attentions: bool = False,
353
+ use_cache: bool = False,
354
+ is_causal: bool = False,
355
+ **kwargs,
356
+ ):
357
+ if "padding_mask" in kwargs:
358
+ warnings.warn(
359
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
360
+ )
361
+
362
+ # overwrite attention_mask with padding_mask
363
+ attention_mask = kwargs.pop("padding_mask")
364
+ bsz, q_len, _ = hidden_states.size()
365
+
366
+ query_states = self.q_proj(hidden_states)
367
+ key_states = self.k_proj(hidden_states)
368
+ value_states = self.v_proj(hidden_states)
369
+
370
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
371
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
372
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
373
+
374
+ kv_seq_len = key_states.shape[-2]
375
+ if past_key_value is not None:
376
+ if self.layer_idx is None:
377
+ raise ValueError(
378
+ f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
379
+ "for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
380
+ "with a layer index."
381
+ )
382
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
383
+
384
+ # Because the input can be padded, the absolute sequence length depends on the max position id.
385
+ rotary_seq_len = max(kv_seq_len, position_ids[:, -1].max().item()) + 1
386
+ cos, sin = self.rotary_emb(value_states, seq_len=rotary_seq_len)
387
+
388
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
389
+
390
+ use_sliding_windows = (
391
+ _flash_supports_window_size
392
+ and getattr(self.config, "sliding_window", None) is not None
393
+ and kv_seq_len > self.config.sliding_window
394
+ and self.config.use_sliding_window
395
+ )
396
+
397
+ if not _flash_supports_window_size:
398
+ logger.warning_once(
399
+ "The current flash attention version does not support sliding window attention, for a more memory efficient implementation"
400
+ " make sure to upgrade flash-attn library."
401
+ )
402
+
403
+ if past_key_value is not None:
404
+ # Activate slicing cache only if the config has a value `sliding_windows` attribute
405
+ cache_has_contents = past_key_value.get_seq_length(self.layer_idx) > 0
406
+ if (
407
+ getattr(self.config, "sliding_window", None) is not None
408
+ and kv_seq_len > self.config.sliding_window
409
+ and cache_has_contents
410
+ ):
411
+ slicing_tokens = 1 - self.config.sliding_window
412
+
413
+ past_key = past_key_value[self.layer_idx][0]
414
+ past_value = past_key_value[self.layer_idx][1]
415
+
416
+ past_key = past_key[:, :, slicing_tokens:, :].contiguous()
417
+ past_value = past_value[:, :, slicing_tokens:, :].contiguous()
418
+
419
+ if past_key.shape[-2] != self.config.sliding_window - 1:
420
+ raise ValueError(
421
+ f"past key must have a shape of (`batch_size, num_heads, self.config.sliding_window-1, head_dim`), got"
422
+ f" {past_key.shape}"
423
+ )
424
+
425
+ if attention_mask is not None:
426
+ attention_mask = attention_mask[:, slicing_tokens:]
427
+ attention_mask = torch.cat([attention_mask, torch.ones_like(attention_mask[:, -1:])], dim=-1)
428
+
429
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
430
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
431
+
432
+ # repeat k/v heads if n_kv_heads < n_heads
433
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
434
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
435
+ dropout_rate = 0.0 if not self.training else self.attention_dropout
436
+
437
+ # In PEFT, usually we cast the layer norms in float32 for training stability reasons
438
+ # therefore the input hidden states gets silently casted in float32. Hence, we need
439
+ # cast them back in float16 just to be sure everything works as expected.
440
+ input_dtype = query_states.dtype
441
+ if input_dtype == torch.float32:
442
+ if torch.is_autocast_enabled():
443
+ target_dtype = torch.get_autocast_gpu_dtype()
444
+ # Handle the case where the model is quantized
445
+ elif hasattr(self.config, "_pre_quantization_dtype"):
446
+ target_dtype = self.config._pre_quantization_dtype
447
+ else:
448
+ target_dtype = self.q_proj.weight.dtype
449
+
450
+ logger.warning_once(
451
+ f"The input hidden states seems to be silently casted in float32, this might be related to"
452
+ f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
453
+ f" {target_dtype}."
454
+ )
455
+
456
+ query_states = query_states.to(target_dtype)
457
+ key_states = key_states.to(target_dtype)
458
+ value_states = value_states.to(target_dtype)
459
+
460
+ # Reashape to the expected shape for Flash Attention
461
+ query_states = query_states.transpose(1, 2)
462
+ key_states = key_states.transpose(1, 2)
463
+ value_states = value_states.transpose(1, 2)
464
+
465
+ attn_output = self._flash_attention_forward(
466
+ query_states,
467
+ key_states,
468
+ value_states,
469
+ attention_mask,
470
+ q_len,
471
+ dropout=dropout_rate,
472
+ use_sliding_windows=use_sliding_windows,
473
+ is_causal=is_causal
474
+ )
475
+
476
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size).contiguous()
477
+ attn_output = self.o_proj(attn_output)
478
+
479
+ if not output_attentions:
480
+ attn_weights = None
481
+
482
+ return attn_output, attn_weights, past_key_value
483
+
484
+ def _flash_attention_forward(
485
+ self,
486
+ query_states,
487
+ key_states,
488
+ value_states,
489
+ attention_mask,
490
+ query_length,
491
+ dropout=0.0,
492
+ softmax_scale=None,
493
+ use_sliding_windows=False,
494
+ is_causal=True,
495
+ ):
496
+ """
497
+ Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
498
+ first unpad the input, then computes the attention scores and pad the final attention scores.
499
+
500
+ Args:
501
+ query_states (`torch.Tensor`):
502
+ Input query states to be passed to Flash Attention API
503
+ key_states (`torch.Tensor`):
504
+ Input key states to be passed to Flash Attention API
505
+ value_states (`torch.Tensor`):
506
+ Input value states to be passed to Flash Attention API
507
+ attention_mask (`torch.Tensor`):
508
+ The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
509
+ position of padding tokens and 1 for the position of non-padding tokens.
510
+ dropout (`int`, *optional*):
511
+ Attention dropout
512
+ softmax_scale (`float`, *optional*):
513
+ The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
514
+ use_sliding_windows (`bool`, *optional*):
515
+ Whether to activate sliding window attention.
516
+ """
517
+ if not self._flash_attn_uses_top_left_mask:
518
+ causal = is_causal
519
+ else:
520
+ # TODO: Remove the `query_length != 1` check once Flash Attention for RoCm is bumped to 2.1. For details, please see the comment in LlamaFlashAttention2 __init__.
521
+ causal = is_causal and query_length != 1
522
+
523
+ # Decide whether to use SWA or not by layer index.
524
+ if use_sliding_windows and self.layer_idx >= self.config.max_window_layers:
525
+ use_sliding_windows = False
526
+
527
+ # Contains at least one padding token in the sequence
528
+ if attention_mask is not None:
529
+ batch_size = query_states.shape[0]
530
+ query_states, key_states, value_states, indices_q, cu_seq_lens, max_seq_lens = self._upad_input(
531
+ query_states, key_states, value_states, attention_mask, query_length
532
+ )
533
+
534
+ cu_seqlens_q, cu_seqlens_k = cu_seq_lens
535
+ max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
536
+
537
+ if not use_sliding_windows:
538
+ attn_output_unpad = flash_attn_varlen_func(
539
+ query_states,
540
+ key_states,
541
+ value_states,
542
+ cu_seqlens_q=cu_seqlens_q,
543
+ cu_seqlens_k=cu_seqlens_k,
544
+ max_seqlen_q=max_seqlen_in_batch_q,
545
+ max_seqlen_k=max_seqlen_in_batch_k,
546
+ dropout_p=dropout,
547
+ softmax_scale=softmax_scale,
548
+ causal=causal,
549
+ )
550
+ else:
551
+ attn_output_unpad = flash_attn_varlen_func(
552
+ query_states,
553
+ key_states,
554
+ value_states,
555
+ cu_seqlens_q=cu_seqlens_q,
556
+ cu_seqlens_k=cu_seqlens_k,
557
+ max_seqlen_q=max_seqlen_in_batch_q,
558
+ max_seqlen_k=max_seqlen_in_batch_k,
559
+ dropout_p=dropout,
560
+ softmax_scale=softmax_scale,
561
+ causal=causal,
562
+ window_size=(self.config.sliding_window, self.config.sliding_window),
563
+ )
564
+
565
+ attn_output = pad_input(attn_output_unpad, indices_q, batch_size, query_length)
566
+ else:
567
+ if not use_sliding_windows:
568
+ attn_output = flash_attn_func(
569
+ query_states,
570
+ key_states,
571
+ value_states,
572
+ dropout,
573
+ softmax_scale=softmax_scale,
574
+ causal=causal,
575
+ )
576
+ else:
577
+ attn_output = flash_attn_func(
578
+ query_states,
579
+ key_states,
580
+ value_states,
581
+ dropout,
582
+ softmax_scale=softmax_scale,
583
+ causal=causal,
584
+ window_size=(self.config.sliding_window, self.config.sliding_window),
585
+ )
586
+
587
+ return attn_output
588
+
589
+ # Copied from transformers.models.mistral.modeling_mistral.MistralFlashAttention2._upad_input
590
+ def _upad_input(self, query_layer, key_layer, value_layer, attention_mask, query_length):
591
+ batch_size, kv_seq_len, num_heads, head_dim = key_layer.shape
592
+
593
+ # On the first iteration we need to properly re-create the padding mask
594
+ # by slicing it on the proper place
595
+ if kv_seq_len != attention_mask.shape[-1]:
596
+ attention_mask_num_tokens = attention_mask.shape[-1]
597
+ attention_mask = attention_mask[:, attention_mask_num_tokens - kv_seq_len :]
598
+
599
+ indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
600
+
601
+ key_layer = index_first_axis(key_layer.reshape(batch_size * kv_seq_len, num_heads, head_dim), indices_k)
602
+ value_layer = index_first_axis(value_layer.reshape(batch_size * kv_seq_len, num_heads, head_dim), indices_k)
603
+
604
+ if query_length == kv_seq_len:
605
+ query_layer = index_first_axis(
606
+ query_layer.reshape(batch_size * kv_seq_len, num_heads, head_dim), indices_k
607
+ )
608
+ cu_seqlens_q = cu_seqlens_k
609
+ max_seqlen_in_batch_q = max_seqlen_in_batch_k
610
+ indices_q = indices_k
611
+ elif query_length == 1:
612
+ max_seqlen_in_batch_q = 1
613
+ cu_seqlens_q = torch.arange(
614
+ batch_size + 1, dtype=torch.int32, device=query_layer.device
615
+ ) # There is a memcpy here, that is very bad.
616
+ indices_q = cu_seqlens_q[:-1]
617
+ query_layer = query_layer.squeeze(1)
618
+ else:
619
+ # The -q_len: slice assumes left padding.
620
+ attention_mask = attention_mask[:, -query_length:]
621
+ query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(query_layer, attention_mask)
622
+
623
+ return (
624
+ query_layer,
625
+ key_layer,
626
+ value_layer,
627
+ indices_q,
628
+ (cu_seqlens_q, cu_seqlens_k),
629
+ (max_seqlen_in_batch_q, max_seqlen_in_batch_k),
630
+ )
631
+
632
+
633
+ # Copied from transformers.models.mistral.modeling_mistral.MistralSdpaAttention with Mistral->Qwen2
634
+ class Qwen2SdpaAttention(Qwen2Attention):
635
+ """
636
+ Qwen2 attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from
637
+ `Qwen2Attention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to
638
+ SDPA API.
639
+ """
640
+
641
+ # Adapted from Qwen2Attention.forward
642
+ def forward(
643
+ self,
644
+ hidden_states: torch.Tensor,
645
+ attention_mask: Optional[torch.Tensor] = None,
646
+ position_ids: Optional[torch.LongTensor] = None,
647
+ past_key_value: Optional[Cache] = None,
648
+ output_attentions: bool = False,
649
+ use_cache: bool = False,
650
+ is_causal: bool = True,
651
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
652
+ if output_attentions:
653
+ # TODO: Improve this warning with e.g. `model.config.attn_implementation = "manual"` once this is implemented.
654
+ logger.warning_once(
655
+ "Qwen2Model is using Qwen2SdpaAttention, but `torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to the manual attention implementation, "
656
+ 'but specifying the manual implementation will be required from Transformers version v5.0.0 onwards. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.'
657
+ )
658
+ return super().forward(
659
+ hidden_states=hidden_states,
660
+ attention_mask=attention_mask,
661
+ position_ids=position_ids,
662
+ past_key_value=past_key_value,
663
+ output_attentions=output_attentions,
664
+ use_cache=use_cache,
665
+ is_causal=is_causal
666
+ )
667
+
668
+ bsz, q_len, _ = hidden_states.size()
669
+
670
+ query_states = self.q_proj(hidden_states)
671
+ key_states = self.k_proj(hidden_states)
672
+ value_states = self.v_proj(hidden_states)
673
+
674
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
675
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
676
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
677
+
678
+ kv_seq_len = key_states.shape[-2]
679
+ if past_key_value is not None:
680
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
681
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
682
+
683
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
684
+
685
+ if past_key_value is not None:
686
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
687
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
688
+
689
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
690
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
691
+
692
+ if attention_mask is not None:
693
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
694
+ raise ValueError(
695
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
696
+ )
697
+
698
+ # SDPA with memory-efficient backend is currently (torch==2.1.2) bugged with non-contiguous inputs with custom attn_mask,
699
+ # Reference: https://github.com/pytorch/pytorch/issues/112577.
700
+ if query_states.device.type == "cuda" and attention_mask is not None:
701
+ query_states = query_states.contiguous()
702
+ key_states = key_states.contiguous()
703
+ value_states = value_states.contiguous()
704
+
705
+ attn_output = torch.nn.functional.scaled_dot_product_attention(
706
+ query_states,
707
+ key_states,
708
+ value_states,
709
+ attn_mask=attention_mask,
710
+ dropout_p=self.attention_dropout if self.training else 0.0,
711
+ # The q_len > 1 is necessary to match with AttentionMaskConverter.to_causal_4d that does not create a causal mask in case q_len == 1.
712
+ is_causal=is_causal and attention_mask is None and q_len > 1,
713
+ )
714
+
715
+ attn_output = attn_output.transpose(1, 2).contiguous()
716
+ attn_output = attn_output.view(bsz, q_len, self.hidden_size)
717
+
718
+ attn_output = self.o_proj(attn_output)
719
+
720
+ return attn_output, None, past_key_value
721
+
722
+
723
+ QWEN2_ATTENTION_CLASSES = {
724
+ "eager": Qwen2Attention,
725
+ "flash_attention_2": Qwen2FlashAttention2,
726
+ "sdpa": Qwen2SdpaAttention,
727
+ }
728
+
729
+
730
+ class Qwen2DecoderLayer(nn.Module):
731
+ def __init__(self, config: Qwen2Config, layer_idx: int):
732
+ super().__init__()
733
+ self.hidden_size = config.hidden_size
734
+
735
+ if config.use_sliding_window and config._attn_implementation != "flash_attention_2":
736
+ logger.warning_once(
737
+ f"Sliding Window Attention is enabled but not implemented for `{config._attn_implementation}`; "
738
+ "unexpected results may be encountered."
739
+ )
740
+ self.self_attn = QWEN2_ATTENTION_CLASSES[config._attn_implementation](config, layer_idx)
741
+
742
+ self.mlp = Qwen2MLP(config)
743
+ self.input_layernorm = Qwen2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
744
+ self.post_attention_layernorm = Qwen2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
745
+
746
+ def forward(
747
+ self,
748
+ hidden_states: torch.Tensor,
749
+ attention_mask: Optional[torch.Tensor] = None,
750
+ position_ids: Optional[torch.LongTensor] = None,
751
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
752
+ output_attentions: Optional[bool] = False,
753
+ use_cache: Optional[bool] = False,
754
+ is_causal: Optional[bool] = True,
755
+ **kwargs,
756
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
757
+ if "padding_mask" in kwargs:
758
+ warnings.warn(
759
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. "
760
+ "Please make sure use `attention_mask` instead.`"
761
+ )
762
+ """
763
+ Args:
764
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
765
+ attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
766
+ `(batch, sequence_length)` where padding elements are indicated by 0.
767
+ output_attentions (`bool`, *optional*):
768
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
769
+ returned tensors for more detail.
770
+ use_cache (`bool`, *optional*):
771
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
772
+ (see `past_key_values`).
773
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
774
+ """
775
+
776
+ residual = hidden_states
777
+
778
+ hidden_states = self.input_layernorm(hidden_states)
779
+
780
+ # Self Attention
781
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
782
+ hidden_states=hidden_states,
783
+ attention_mask=attention_mask,
784
+ position_ids=position_ids,
785
+ past_key_value=past_key_value,
786
+ output_attentions=output_attentions,
787
+ use_cache=use_cache,
788
+ is_causal=is_causal,
789
+ )
790
+ hidden_states = residual + hidden_states
791
+
792
+ # Fully Connected
793
+ residual = hidden_states
794
+ hidden_states = self.post_attention_layernorm(hidden_states)
795
+ hidden_states = self.mlp(hidden_states)
796
+ hidden_states = residual + hidden_states
797
+
798
+ outputs = (hidden_states,)
799
+
800
+ if output_attentions:
801
+ outputs += (self_attn_weights,)
802
+
803
+ if use_cache:
804
+ outputs += (present_key_value,)
805
+
806
+ return outputs
807
+
808
+
809
+ QWEN2_START_DOCSTRING = r"""
810
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
811
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
812
+ etc.)
813
+
814
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
815
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
816
+ and behavior.
817
+
818
+ Parameters:
819
+ config ([`Qwen2Config`]):
820
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
821
+ load the weights associated with the model, only the configuration. Check out the
822
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
823
+ """
824
+
825
+
826
+ @add_start_docstrings(
827
+ "The bare Qwen2 Model outputting raw hidden-states without any specific head on top.",
828
+ QWEN2_START_DOCSTRING,
829
+ )
830
+ class Qwen2PreTrainedModel(PreTrainedModel):
831
+ config_class = Qwen2Config
832
+ base_model_prefix = "model"
833
+ supports_gradient_checkpointing = True
834
+ _no_split_modules = ["Qwen2DecoderLayer"]
835
+ _skip_keys_device_placement = "past_key_values"
836
+ _supports_flash_attn_2 = True
837
+ _supports_sdpa = True
838
+ _supports_cache_class = True
839
+
840
+ def _init_weights(self, module):
841
+ std = self.config.initializer_range
842
+ if isinstance(module, nn.Linear):
843
+ module.weight.data.normal_(mean=0.0, std=std)
844
+ if module.bias is not None:
845
+ module.bias.data.zero_()
846
+ elif isinstance(module, nn.Embedding):
847
+ module.weight.data.normal_(mean=0.0, std=std)
848
+ if module.padding_idx is not None:
849
+ module.weight.data[module.padding_idx].zero_()
850
+
851
+
852
+ QWEN2_INPUTS_DOCSTRING = r"""
853
+ Args:
854
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
855
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
856
+ it.
857
+
858
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
859
+ [`PreTrainedTokenizer.__call__`] for details.
860
+
861
+ [What are input IDs?](../glossary#input-ids)
862
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
863
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
864
+
865
+ - 1 for tokens that are **not masked**,
866
+ - 0 for tokens that are **masked**.
867
+
868
+ [What are attention masks?](../glossary#attention-mask)
869
+
870
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
871
+ [`PreTrainedTokenizer.__call__`] for details.
872
+
873
+ If `past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see
874
+ `past_key_values`).
875
+
876
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
877
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
878
+ information on the default strategy.
879
+
880
+ - 1 indicates the head is **not masked**,
881
+ - 0 indicates the head is **masked**.
882
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
883
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
884
+ config.n_positions - 1]`.
885
+
886
+ [What are position IDs?](../glossary#position-ids)
887
+ past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
888
+ Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
889
+ blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
890
+ returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
891
+
892
+ Two formats are allowed:
893
+ - a [`~cache_utils.Cache`] instance;
894
+ - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
895
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
896
+ cache format.
897
+
898
+ The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
899
+ legacy cache format will be returned.
900
+
901
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
902
+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
903
+ of shape `(batch_size, sequence_length)`.
904
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
905
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
906
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
907
+ model's internal embedding lookup matrix.
908
+ use_cache (`bool`, *optional*):
909
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
910
+ `past_key_values`).
911
+ output_attentions (`bool`, *optional*):
912
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
913
+ tensors for more detail.
914
+ output_hidden_states (`bool`, *optional*):
915
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
916
+ more detail.
917
+ return_dict (`bool`, *optional*):
918
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
919
+ """
920
+
921
+
922
+ @add_start_docstrings(
923
+ "The bare Qwen2 Model outputting raw hidden-states without any specific head on top.",
924
+ QWEN2_START_DOCSTRING,
925
+ )
926
+ class Qwen2Model(Qwen2PreTrainedModel):
927
+ """
928
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`Qwen2DecoderLayer`]
929
+
930
+ Args:
931
+ config: Qwen2Config
932
+ """
933
+
934
+ def __init__(self, config: Qwen2Config):
935
+ super().__init__(config)
936
+ self.padding_idx = config.pad_token_id
937
+ self.vocab_size = config.vocab_size
938
+
939
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
940
+ self.layers = nn.ModuleList(
941
+ [Qwen2DecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
942
+ )
943
+ self._attn_implementation = config._attn_implementation
944
+ self.norm = Qwen2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
945
+
946
+ self.gradient_checkpointing = False
947
+ # Initialize weights and apply final processing
948
+ self.post_init()
949
+
950
+ def get_input_embeddings(self):
951
+ return self.embed_tokens
952
+
953
+ def set_input_embeddings(self, value):
954
+ self.embed_tokens = value
955
+
956
+ @add_start_docstrings_to_model_forward(QWEN2_INPUTS_DOCSTRING)
957
+ def forward(
958
+ self,
959
+ input_ids: torch.LongTensor = None,
960
+ attention_mask: Optional[torch.Tensor] = None,
961
+ position_ids: Optional[torch.LongTensor] = None,
962
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
963
+ inputs_embeds: Optional[torch.FloatTensor] = None,
964
+ use_cache: Optional[bool] = None,
965
+ output_attentions: Optional[bool] = None,
966
+ output_hidden_states: Optional[bool] = None,
967
+ return_dict: Optional[bool] = None,
968
+ labels: Optional[torch.LongTensor] = None,
969
+ is_causal: Optional[bool] = False,
970
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
971
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
972
+ output_hidden_states = (
973
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
974
+ )
975
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
976
+
977
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
978
+
979
+ # retrieve input_ids and inputs_embeds
980
+ if input_ids is not None and inputs_embeds is not None:
981
+ raise ValueError("You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time")
982
+ elif input_ids is not None:
983
+ batch_size, seq_length = input_ids.shape
984
+ elif inputs_embeds is not None:
985
+ batch_size, seq_length, _ = inputs_embeds.shape
986
+ else:
987
+ raise ValueError("You have to specify either decoder_input_ids or decoder_inputs_embeds")
988
+
989
+ if self.gradient_checkpointing and self.training:
990
+ if use_cache:
991
+ logger.warning_once(
992
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
993
+ )
994
+ use_cache = False
995
+
996
+ past_key_values_length = 0
997
+
998
+ if use_cache:
999
+ use_legacy_cache = not isinstance(past_key_values, Cache)
1000
+ if use_legacy_cache:
1001
+ past_key_values = DynamicCache.from_legacy_cache(past_key_values)
1002
+ past_key_values_length = past_key_values.get_usable_length(seq_length)
1003
+
1004
+ if position_ids is None:
1005
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
1006
+ position_ids = torch.arange(
1007
+ past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device
1008
+ )
1009
+ position_ids = position_ids.unsqueeze(0).view(-1, seq_length)
1010
+ else:
1011
+ position_ids = position_ids.view(-1, seq_length).long()
1012
+
1013
+ if inputs_embeds is None:
1014
+ inputs_embeds = self.embed_tokens(input_ids)
1015
+
1016
+ if attention_mask is not None and self._attn_implementation == "flash_attention_2" and use_cache:
1017
+ is_padding_right = attention_mask[:, -1].sum().item() != batch_size
1018
+ if is_padding_right:
1019
+ raise ValueError(
1020
+ "You are attempting to perform batched generation with padding_side='right'"
1021
+ " this may lead to unexpected behaviour for Flash Attention version of Qwen2. Make sure to "
1022
+ " call `tokenizer.padding_side = 'left'` before tokenizing the input. "
1023
+ )
1024
+
1025
+ if self._attn_implementation == "flash_attention_2":
1026
+ # 2d mask is passed through the layers
1027
+ attention_mask = attention_mask if (attention_mask is not None and 0 in attention_mask) else None
1028
+ elif self._attn_implementation == "sdpa" and not output_attentions:
1029
+ # output_attentions=True can not be supported when using SDPA, and we fall back on
1030
+ # the manual implementation that requires a 4D causal mask in all cases.
1031
+ if is_causal:
1032
+ attention_mask = _prepare_4d_causal_attention_mask_for_sdpa(
1033
+ attention_mask,
1034
+ (batch_size, seq_length),
1035
+ inputs_embeds,
1036
+ past_key_values_length,
1037
+ )
1038
+ else:
1039
+ attention_mask = _prepare_4d_attention_mask_for_sdpa(
1040
+ attention_mask, inputs_embeds.dtype
1041
+ )
1042
+ else:
1043
+ # 4d mask is passed through the layers
1044
+ if is_causal:
1045
+ # Causal mask with -3.3895e+38 where no attention should be
1046
+ attention_mask = _prepare_4d_causal_attention_mask(
1047
+ attention_mask,
1048
+ (batch_size, seq_length),
1049
+ inputs_embeds,
1050
+ past_key_values_length,
1051
+ sliding_window=self.config.sliding_window,
1052
+ )
1053
+ else:
1054
+ # Shape: batch_size, 1, query_length, key_value_length
1055
+ attention_mask = _prepare_4d_attention_mask(
1056
+ attention_mask, inputs_embeds.dtype
1057
+ )
1058
+
1059
+ hidden_states = inputs_embeds
1060
+
1061
+ # decoder layers
1062
+ all_hidden_states = () if output_hidden_states else None
1063
+ all_self_attns = () if output_attentions else None
1064
+ next_decoder_cache = None
1065
+
1066
+ for decoder_layer in self.layers:
1067
+ if output_hidden_states:
1068
+ all_hidden_states += (hidden_states,)
1069
+
1070
+ if self.gradient_checkpointing and self.training:
1071
+ layer_outputs = self._gradient_checkpointing_func(
1072
+ decoder_layer.__call__,
1073
+ hidden_states,
1074
+ attention_mask,
1075
+ position_ids,
1076
+ past_key_values,
1077
+ output_attentions,
1078
+ use_cache,
1079
+ is_causal,
1080
+ )
1081
+ else:
1082
+ layer_outputs = decoder_layer(
1083
+ hidden_states,
1084
+ attention_mask=attention_mask,
1085
+ position_ids=position_ids,
1086
+ past_key_value=past_key_values,
1087
+ output_attentions=output_attentions,
1088
+ use_cache=use_cache,
1089
+ is_causal=is_causal,
1090
+ )
1091
+
1092
+ hidden_states = layer_outputs[0]
1093
+
1094
+ if use_cache:
1095
+ next_decoder_cache = layer_outputs[2 if output_attentions else 1]
1096
+
1097
+ if output_attentions:
1098
+ all_self_attns += (layer_outputs[1],)
1099
+
1100
+ hidden_states = self.norm(hidden_states)
1101
+
1102
+ # add hidden states from the last decoder layer
1103
+ if output_hidden_states:
1104
+ all_hidden_states += (hidden_states,)
1105
+
1106
+ next_cache = None
1107
+ if use_cache:
1108
+ next_cache = next_decoder_cache.to_legacy_cache() if use_legacy_cache else next_decoder_cache
1109
+
1110
+ if not return_dict:
1111
+ return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
1112
+ return BaseModelOutputWithPast(
1113
+ last_hidden_state=hidden_states,
1114
+ past_key_values=next_cache,
1115
+ hidden_states=all_hidden_states,
1116
+ attentions=all_self_attns,
1117
+ )
1118
+
1119
+
1120
+ class Qwen2ForCausalLM(Qwen2PreTrainedModel):
1121
+ _tied_weights_keys = ["lm_head.weight"]
1122
+
1123
+ def __init__(self, config):
1124
+ super().__init__(config)
1125
+ self.model = Qwen2Model(config)
1126
+ self.vocab_size = config.vocab_size
1127
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1128
+
1129
+ # Initialize weights and apply final processing
1130
+ self.post_init()
1131
+
1132
+ def get_input_embeddings(self):
1133
+ return self.model.embed_tokens
1134
+
1135
+ def set_input_embeddings(self, value):
1136
+ self.model.embed_tokens = value
1137
+
1138
+ def get_output_embeddings(self):
1139
+ return self.lm_head
1140
+
1141
+ def set_output_embeddings(self, new_embeddings):
1142
+ self.lm_head = new_embeddings
1143
+
1144
+ def set_decoder(self, decoder):
1145
+ self.model = decoder
1146
+
1147
+ def get_decoder(self):
1148
+ return self.model
1149
+
1150
+ @add_start_docstrings_to_model_forward(QWEN2_INPUTS_DOCSTRING)
1151
+ @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
1152
+ def forward(
1153
+ self,
1154
+ input_ids: torch.LongTensor = None,
1155
+ attention_mask: Optional[torch.Tensor] = None,
1156
+ position_ids: Optional[torch.LongTensor] = None,
1157
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1158
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1159
+ labels: Optional[torch.LongTensor] = None,
1160
+ use_cache: Optional[bool] = None,
1161
+ output_attentions: Optional[bool] = None,
1162
+ output_hidden_states: Optional[bool] = None,
1163
+ return_dict: Optional[bool] = None,
1164
+ is_causal: Optional[bool] = False,
1165
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
1166
+ r"""
1167
+ Args:
1168
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1169
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1170
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1171
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1172
+
1173
+ Returns:
1174
+
1175
+ Example:
1176
+
1177
+ ```python
1178
+ >>> from transformers import AutoTokenizer, Qwen2ForCausalLM
1179
+
1180
+ >>> model = Qwen2ForCausalLM.from_pretrained(PATH_TO_CONVERTED_WEIGHTS)
1181
+ >>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER)
1182
+
1183
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
1184
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
1185
+
1186
+ >>> # Generate
1187
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
1188
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1189
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
1190
+ ```"""
1191
+
1192
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1193
+ output_hidden_states = (
1194
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1195
+ )
1196
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1197
+
1198
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1199
+ outputs = self.model(
1200
+ input_ids=input_ids,
1201
+ attention_mask=attention_mask,
1202
+ position_ids=position_ids,
1203
+ past_key_values=past_key_values,
1204
+ inputs_embeds=inputs_embeds,
1205
+ use_cache=use_cache,
1206
+ output_attentions=output_attentions,
1207
+ output_hidden_states=output_hidden_states,
1208
+ return_dict=return_dict,
1209
+ is_causal=is_causal,
1210
+ )
1211
+
1212
+ hidden_states = outputs[0]
1213
+ logits = self.lm_head(hidden_states)
1214
+ logits = logits.float()
1215
+
1216
+ loss = None
1217
+ if labels is not None:
1218
+ # Shift so that tokens < n predict n
1219
+ shift_logits = logits[..., :-1, :].contiguous()
1220
+ shift_labels = labels[..., 1:].contiguous()
1221
+ # Flatten the tokens
1222
+ loss_fct = CrossEntropyLoss()
1223
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
1224
+ shift_labels = shift_labels.view(-1)
1225
+ # Enable model parallelism
1226
+ shift_labels = shift_labels.to(shift_logits.device)
1227
+ loss = loss_fct(shift_logits, shift_labels)
1228
+
1229
+ if not return_dict:
1230
+ output = (logits,) + outputs[1:]
1231
+ return (loss,) + output if loss is not None else output
1232
+
1233
+ return CausalLMOutputWithPast(
1234
+ loss=loss,
1235
+ logits=logits,
1236
+ past_key_values=outputs.past_key_values,
1237
+ hidden_states=outputs.hidden_states,
1238
+ attentions=outputs.attentions,
1239
+ )
1240
+
1241
+ def prepare_inputs_for_generation(
1242
+ self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs
1243
+ ):
1244
+ # Omit tokens covered by past_key_values
1245
+ if past_key_values is not None:
1246
+ if isinstance(past_key_values, Cache):
1247
+ cache_length = past_key_values.get_seq_length()
1248
+ past_length = past_key_values.seen_tokens
1249
+ max_cache_length = past_key_values.get_max_length()
1250
+ else:
1251
+ cache_length = past_length = past_key_values[0][0].shape[2]
1252
+ max_cache_length = None
1253
+
1254
+ # Keep only the unprocessed tokens:
1255
+ # 1 - If the length of the attention_mask exceeds the length of input_ids, then we are in a setting where
1256
+ # some of the inputs are exclusively passed as part of the cache (e.g. when passing input_embeds as
1257
+ # input)
1258
+ if attention_mask is not None and attention_mask.shape[1] > input_ids.shape[1]:
1259
+ input_ids = input_ids[:, -(attention_mask.shape[1] - past_length) :]
1260
+ # 2 - If the past_length is smaller than input_ids', then input_ids holds all input tokens. We can discard
1261
+ # input_ids based on the past_length.
1262
+ elif past_length < input_ids.shape[1]:
1263
+ input_ids = input_ids[:, past_length:]
1264
+ # 3 - Otherwise (past_length >= input_ids.shape[1]), let's assume input_ids only has unprocessed tokens.
1265
+
1266
+ # If we are about to go beyond the maximum cache length, we need to crop the input attention mask.
1267
+ if (
1268
+ max_cache_length is not None
1269
+ and attention_mask is not None
1270
+ and cache_length + input_ids.shape[1] > max_cache_length
1271
+ ):
1272
+ attention_mask = attention_mask[:, -max_cache_length:]
1273
+
1274
+ position_ids = kwargs.get("position_ids", None)
1275
+ if attention_mask is not None and position_ids is None:
1276
+ # create position_ids on the fly for batch generation
1277
+ position_ids = attention_mask.long().cumsum(-1) - 1
1278
+ position_ids.masked_fill_(attention_mask == 0, 1)
1279
+ if past_key_values:
1280
+ position_ids = position_ids[:, -input_ids.shape[1] :]
1281
+
1282
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
1283
+ if inputs_embeds is not None and past_key_values is None:
1284
+ model_inputs = {"inputs_embeds": inputs_embeds}
1285
+ else:
1286
+ model_inputs = {"input_ids": input_ids}
1287
+
1288
+ model_inputs.update(
1289
+ {
1290
+ "position_ids": position_ids,
1291
+ "past_key_values": past_key_values,
1292
+ "use_cache": kwargs.get("use_cache"),
1293
+ "attention_mask": attention_mask,
1294
+ }
1295
+ )
1296
+ return model_inputs
1297
+
1298
+ @staticmethod
1299
+ def _reorder_cache(past_key_values, beam_idx):
1300
+ reordered_past = ()
1301
+ for layer_past in past_key_values:
1302
+ reordered_past += (
1303
+ tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
1304
+ )
1305
+ return reordered_past
1306
+
1307
+
1308
+ @add_start_docstrings(
1309
+ """
1310
+ The Qwen2 Model transformer with a sequence classification head on top (linear layer).
1311
+
1312
+ [`Qwen2ForSequenceClassification`] uses the last token in order to do the classification, as other causal models
1313
+ (e.g. GPT-2) do.
1314
+
1315
+ Since it does classification on the last token, it requires to know the position of the last token. If a
1316
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
1317
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
1318
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
1319
+ each row of the batch).
1320
+ """,
1321
+ QWEN2_START_DOCSTRING,
1322
+ )
1323
+ class Qwen2ForSequenceClassification(Qwen2PreTrainedModel):
1324
+ def __init__(self, config):
1325
+ super().__init__(config)
1326
+ self.num_labels = config.num_labels
1327
+ self.model = Qwen2Model(config)
1328
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
1329
+
1330
+ # Initialize weights and apply final processing
1331
+ self.post_init()
1332
+
1333
+ def get_input_embeddings(self):
1334
+ return self.model.embed_tokens
1335
+
1336
+ def set_input_embeddings(self, value):
1337
+ self.model.embed_tokens = value
1338
+
1339
+ @add_start_docstrings_to_model_forward(QWEN2_INPUTS_DOCSTRING)
1340
+ def forward(
1341
+ self,
1342
+ input_ids: torch.LongTensor = None,
1343
+ attention_mask: Optional[torch.Tensor] = None,
1344
+ position_ids: Optional[torch.LongTensor] = None,
1345
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1346
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1347
+ labels: Optional[torch.LongTensor] = None,
1348
+ use_cache: Optional[bool] = None,
1349
+ output_attentions: Optional[bool] = None,
1350
+ output_hidden_states: Optional[bool] = None,
1351
+ return_dict: Optional[bool] = None,
1352
+ is_causal: Optional[bool] = True,
1353
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
1354
+ r"""
1355
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1356
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1357
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1358
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1359
+ """
1360
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1361
+
1362
+ transformer_outputs = self.model(
1363
+ input_ids,
1364
+ attention_mask=attention_mask,
1365
+ position_ids=position_ids,
1366
+ past_key_values=past_key_values,
1367
+ inputs_embeds=inputs_embeds,
1368
+ use_cache=use_cache,
1369
+ output_attentions=output_attentions,
1370
+ output_hidden_states=output_hidden_states,
1371
+ return_dict=return_dict,
1372
+ is_causal=is_causal,
1373
+ )
1374
+ hidden_states = transformer_outputs[0]
1375
+ logits = self.score(hidden_states)
1376
+
1377
+ if input_ids is not None:
1378
+ batch_size = input_ids.shape[0]
1379
+ else:
1380
+ batch_size = inputs_embeds.shape[0]
1381
+
1382
+ if self.config.pad_token_id is None and batch_size != 1:
1383
+ raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
1384
+ if self.config.pad_token_id is None:
1385
+ sequence_lengths = -1
1386
+ else:
1387
+ if input_ids is not None:
1388
+ # if no pad token found, use modulo instead of reverse indexing for ONNX compatibility
1389
+ sequence_lengths = torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1
1390
+ sequence_lengths = sequence_lengths % input_ids.shape[-1]
1391
+ sequence_lengths = sequence_lengths.to(logits.device)
1392
+ else:
1393
+ sequence_lengths = -1
1394
+
1395
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
1396
+
1397
+ loss = None
1398
+ if labels is not None:
1399
+ labels = labels.to(logits.device)
1400
+ if self.config.problem_type is None:
1401
+ if self.num_labels == 1:
1402
+ self.config.problem_type = "regression"
1403
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
1404
+ self.config.problem_type = "single_label_classification"
1405
+ else:
1406
+ self.config.problem_type = "multi_label_classification"
1407
+
1408
+ if self.config.problem_type == "regression":
1409
+ loss_fct = MSELoss()
1410
+ if self.num_labels == 1:
1411
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
1412
+ else:
1413
+ loss = loss_fct(pooled_logits, labels)
1414
+ elif self.config.problem_type == "single_label_classification":
1415
+ loss_fct = CrossEntropyLoss()
1416
+ loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
1417
+ elif self.config.problem_type == "multi_label_classification":
1418
+ loss_fct = BCEWithLogitsLoss()
1419
+ loss = loss_fct(pooled_logits, labels)
1420
+ if not return_dict:
1421
+ output = (pooled_logits,) + transformer_outputs[1:]
1422
+ return ((loss,) + output) if loss is not None else output
1423
+
1424
+ return SequenceClassifierOutputWithPast(
1425
+ loss=loss,
1426
+ logits=pooled_logits,
1427
+ past_key_values=transformer_outputs.past_key_values,
1428
+ hidden_states=transformer_outputs.hidden_states,
1429
+ attentions=transformer_outputs.attentions,
1430
+ )