adalbertojunior commited on
Commit
7dfb5ab
·
verified ·
1 Parent(s): 33ee032

Create modeling_compac.py

Browse files
Files changed (1) hide show
  1. modeling_compac.py +1650 -0
modeling_compac.py ADDED
@@ -0,0 +1,1650 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 The Qwen team, Alibaba Group and the HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
5
+ # and OPT implementations in this library. It has been modified from its
6
+ # original forms to accommodate minor architectural differences compared
7
+ # to GPT-NeoX and OPT used by the Meta AI team that trained the model.
8
+ #
9
+ # Licensed under the Apache License, Version 2.0 (the "License");
10
+ # you may not use this file except in compliance with the License.
11
+ # You may obtain a copy of the License at
12
+ #
13
+ # http://www.apache.org/licenses/LICENSE-2.0
14
+ #
15
+ # Unless required by applicable law or agreed to in writing, software
16
+ # distributed under the License is distributed on an "AS IS" BASIS,
17
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18
+ # See the License for the specific language governing permissions and
19
+ # limitations under the License.
20
+ """PyTorch Qwen2 model."""
21
+
22
+ import math
23
+ from typing import List, Optional, Tuple, Union
24
+
25
+ import torch
26
+ import torch.utils.checkpoint
27
+ from torch import nn
28
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
29
+
30
+ from transformers.activations import ACT2FN
31
+ from transformers.cache_utils import Cache, DynamicCache, SlidingWindowCache, StaticCache
32
+ from transformers.generation import GenerationMixin
33
+ from transformers.modeling_attn_mask_utils import AttentionMaskConverter
34
+ from transformers.modeling_outputs import (
35
+ BaseModelOutputWithPast,
36
+ CausalLMOutputWithPast,
37
+ QuestionAnsweringModelOutput,
38
+ SequenceClassifierOutputWithPast,
39
+ TokenClassifierOutput,
40
+ )
41
+ from transformers.modeling_rope_utils import ROPE_INIT_FUNCTIONS
42
+ from transformers.modeling_utils import PreTrainedModel
43
+ from transformers.utils import (
44
+ add_code_sample_docstrings,
45
+ add_start_docstrings,
46
+ add_start_docstrings_to_model_forward,
47
+ is_flash_attn_2_available,
48
+ is_flash_attn_greater_or_equal_2_10,
49
+ logging,
50
+ replace_return_docstrings,
51
+ )
52
+ from .configuration_compac import CompacQwen2Config
53
+
54
+
55
+ if is_flash_attn_2_available():
56
+ from transformers.modeling_flash_attention_utils import _flash_attention_forward
57
+
58
+
59
+ logger = logging.get_logger(__name__)
60
+
61
+
62
+ _CHECKPOINT_FOR_DOC = "Qwen/Qwen2-7B"
63
+ _CONFIG_FOR_DOC = "CompacQwen2Config"
64
+
65
+
66
+ # Copied from transformers.models.llama.modeling_llama.LlamaRMSNorm with Llama->Qwen2
67
+ class Qwen2RMSNorm(nn.Module):
68
+ def __init__(self, hidden_size, eps=1e-6):
69
+ """
70
+ Qwen2RMSNorm is equivalent to T5LayerNorm
71
+ """
72
+ super().__init__()
73
+ self.weight = nn.Parameter(torch.ones(hidden_size))
74
+ self.variance_epsilon = eps
75
+
76
+ def forward(self, hidden_states):
77
+ input_dtype = hidden_states.dtype
78
+ hidden_states = hidden_states.to(torch.float32)
79
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
80
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
81
+ return self.weight * hidden_states.to(input_dtype)
82
+
83
+ def extra_repr(self):
84
+ return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
85
+
86
+
87
+ # Copied from transformers.models.llama.modeling_llama.LlamaRotaryEmbedding with Llama->Qwen2
88
+ class Qwen2RotaryEmbedding(nn.Module):
89
+ def __init__(
90
+ self,
91
+ dim=None,
92
+ max_position_embeddings=2048,
93
+ base=10000,
94
+ device=None,
95
+ scaling_factor=1.0,
96
+ rope_type="default",
97
+ config: Optional[CompacQwen2Config] = None,
98
+ ):
99
+ super().__init__()
100
+ # TODO (joao): remove the `if` below, only used for BC
101
+ self.rope_kwargs = {}
102
+ if config is None:
103
+ logger.warning_once(
104
+ "`Qwen2RotaryEmbedding` can now be fully parameterized by passing the model config through the "
105
+ "`config` argument. All other arguments will be removed in v4.46"
106
+ )
107
+ self.rope_kwargs = {
108
+ "rope_type": rope_type,
109
+ "factor": scaling_factor,
110
+ "dim": dim,
111
+ "base": base,
112
+ "max_position_embeddings": max_position_embeddings,
113
+ }
114
+ self.rope_type = rope_type
115
+ self.max_seq_len_cached = max_position_embeddings
116
+ self.original_max_seq_len = max_position_embeddings
117
+ else:
118
+ # BC: "rope_type" was originally "type"
119
+ if config.rope_scaling is not None:
120
+ self.rope_type = config.rope_scaling.get("rope_type", config.rope_scaling.get("type"))
121
+ else:
122
+ self.rope_type = "default"
123
+ self.max_seq_len_cached = config.max_position_embeddings
124
+ self.original_max_seq_len = config.max_position_embeddings
125
+
126
+ self.config = config
127
+ self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
128
+
129
+ inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device, **self.rope_kwargs)
130
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
131
+ self.original_inv_freq = self.inv_freq
132
+
133
+ def _dynamic_frequency_update(self, position_ids, device):
134
+ """
135
+ dynamic RoPE layers should recompute `inv_freq` in the following situations:
136
+ 1 - growing beyond the cached sequence length (allow scaling)
137
+ 2 - the current sequence length is in the original scale (avoid losing precision with small sequences)
138
+ """
139
+ seq_len = torch.max(position_ids) + 1
140
+ if seq_len > self.max_seq_len_cached: # growth
141
+ inv_freq, self.attention_scaling = self.rope_init_fn(
142
+ self.config, device, seq_len=seq_len, **self.rope_kwargs
143
+ )
144
+ self.register_buffer("inv_freq", inv_freq, persistent=False) # TODO joao: may break with compilation
145
+ self.max_seq_len_cached = seq_len
146
+
147
+ if seq_len < self.original_max_seq_len and self.max_seq_len_cached > self.original_max_seq_len: # reset
148
+ self.register_buffer("inv_freq", self.original_inv_freq, persistent=False)
149
+ self.max_seq_len_cached = self.original_max_seq_len
150
+
151
+ @torch.no_grad()
152
+ def forward(self, x, position_ids):
153
+ if "dynamic" in self.rope_type:
154
+ self._dynamic_frequency_update(position_ids, device=x.device)
155
+
156
+ # Core RoPE block
157
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
158
+ position_ids_expanded = position_ids[:, None, :].float()
159
+ # Force float32 (see https://github.com/huggingface/transformers/pull/29285)
160
+ device_type = x.device.type
161
+ device_type = device_type if isinstance(device_type, str) and device_type != "mps" else "cpu"
162
+ with torch.autocast(device_type=device_type, enabled=False):
163
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
164
+ emb = torch.cat((freqs, freqs), dim=-1)
165
+ cos = emb.cos()
166
+ sin = emb.sin()
167
+
168
+ # Advanced RoPE types (e.g. yarn) apply a post-processing scaling factor, equivalent to scaling attention
169
+ cos = cos * self.attention_scaling
170
+ sin = sin * self.attention_scaling
171
+
172
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
173
+
174
+
175
+ # Copied from transformers.models.llama.modeling_llama.rotate_half
176
+ def rotate_half(x):
177
+ """Rotates half the hidden dims of the input."""
178
+ x1 = x[..., : x.shape[-1] // 2]
179
+ x2 = x[..., x.shape[-1] // 2 :]
180
+ return torch.cat((-x2, x1), dim=-1)
181
+
182
+
183
+ # Copied from transformers.models.llama.modeling_llama.apply_rotary_pos_emb
184
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
185
+ """Applies Rotary Position Embedding to the query and key tensors.
186
+
187
+ Args:
188
+ q (`torch.Tensor`): The query tensor.
189
+ k (`torch.Tensor`): The key tensor.
190
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
191
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
192
+ position_ids (`torch.Tensor`, *optional*):
193
+ Deprecated and unused.
194
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
195
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
196
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
197
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
198
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
199
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
200
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
201
+ Returns:
202
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
203
+ """
204
+ cos = cos.unsqueeze(unsqueeze_dim)
205
+ sin = sin.unsqueeze(unsqueeze_dim)
206
+ q_embed = (q * cos) + (rotate_half(q) * sin)
207
+ k_embed = (k * cos) + (rotate_half(k) * sin)
208
+ return q_embed, k_embed
209
+
210
+
211
+ # Copied from transformers.models.mistral.modeling_mistral.MistralMLP with Mistral->Qwen2
212
+ class Qwen2MLP(nn.Module):
213
+ def __init__(self, config):
214
+ super().__init__()
215
+ self.hidden_size = config.hidden_size
216
+ self.intermediate_size = config.intermediate_size
217
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
218
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
219
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
220
+ self.act_fn = ACT2FN[config.hidden_act]
221
+
222
+ def forward(self, hidden_state):
223
+ return self.down_proj(self.act_fn(self.gate_proj(hidden_state)) * self.up_proj(hidden_state))
224
+
225
+
226
+ # Copied from transformers.models.llama.modeling_llama.repeat_kv
227
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
228
+ """
229
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
230
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
231
+ """
232
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
233
+ if n_rep == 1:
234
+ return hidden_states
235
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
236
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
237
+
238
+
239
+ class Qwen2Attention(nn.Module):
240
+ """
241
+ Multi-headed attention from 'Attention Is All You Need' paper. Modified to use sliding window attention: Longformer
242
+ and "Generating Long Sequences with Sparse Transformers".
243
+ """
244
+
245
+ def __init__(self, config: CompacQwen2Config, layer_idx: Optional[int] = None):
246
+ super().__init__()
247
+ self.config = config
248
+ self.layer_idx = layer_idx
249
+ if layer_idx is None:
250
+ logger.warning_once(
251
+ f"Instantiating {self.__class__.__name__} without passing `layer_idx` is not recommended and will "
252
+ "to errors during the forward call, if caching is used. Please make sure to provide a `layer_idx` "
253
+ "when creating this class."
254
+ )
255
+
256
+ self.hidden_size = config.hidden_size
257
+ self.num_heads = config.num_attention_heads
258
+ self.head_dim = self.hidden_size // self.num_heads
259
+ self.num_key_value_heads = config.num_key_value_heads
260
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
261
+ self.max_position_embeddings = config.max_position_embeddings
262
+ self.rope_theta = config.rope_theta
263
+ self.is_causal = True
264
+ self.attention_dropout = config.attention_dropout
265
+
266
+ if (self.head_dim * self.num_heads) != self.hidden_size:
267
+ raise ValueError(
268
+ f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
269
+ f" and `num_heads`: {self.num_heads})."
270
+ )
271
+ self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=True)
272
+ self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=True)
273
+ self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=True)
274
+ self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=False)
275
+
276
+ self.rotary_emb = Qwen2RotaryEmbedding(config=self.config)
277
+
278
+ def forward(
279
+ self,
280
+ hidden_states: torch.Tensor,
281
+ attention_mask: Optional[torch.Tensor] = None,
282
+ position_ids: Optional[torch.LongTensor] = None,
283
+ past_key_value: Optional[Cache] = None,
284
+ output_attentions: bool = False,
285
+ use_cache: bool = False,
286
+ cache_position: Optional[torch.LongTensor] = None,
287
+ position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, # will become mandatory in v4.46
288
+ layer_idx: Optional[int] = None,
289
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
290
+
291
+ if layer_idx:
292
+ self.layer_idx = layer_idx
293
+
294
+ bsz, q_len, _ = hidden_states.size()
295
+
296
+ query_states = self.q_proj(hidden_states)
297
+ key_states = self.k_proj(hidden_states)
298
+ value_states = self.v_proj(hidden_states)
299
+
300
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
301
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
302
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
303
+
304
+ if position_embeddings is None:
305
+ logger.warning_once(
306
+ "The attention layers in this model are transitioning from computing the RoPE embeddings internally "
307
+ "through `position_ids` (2D tensor with the indexes of the tokens), to using externally computed "
308
+ "`position_embeddings` (Tuple of tensors, containing cos and sin). In v4.46 `position_ids` will be "
309
+ "removed and `position_embeddings` will be mandatory."
310
+ )
311
+ cos, sin = self.rotary_emb(value_states, position_ids)
312
+ else:
313
+ cos, sin = position_embeddings
314
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
315
+
316
+ if past_key_value is not None:
317
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position} # Specific to RoPE models
318
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
319
+
320
+ # repeat k/v heads if n_kv_heads < n_heads
321
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
322
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
323
+
324
+ attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
325
+ if attention_mask is not None: # no matter the length, we just slice it
326
+ causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
327
+ attn_weights = attn_weights + causal_mask
328
+
329
+ # upcast attention to fp32
330
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
331
+ attn_weights = nn.functional.dropout(attn_weights, p=self.attention_dropout, training=self.training)
332
+ attn_output = torch.matmul(attn_weights, value_states)
333
+
334
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
335
+ raise ValueError(
336
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
337
+ f" {attn_output.size()}"
338
+ )
339
+
340
+ attn_output = attn_output.transpose(1, 2).contiguous()
341
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
342
+
343
+ attn_output = self.o_proj(attn_output)
344
+
345
+ if not output_attentions:
346
+ attn_weights = None
347
+
348
+ return attn_output, attn_weights, past_key_value
349
+
350
+
351
+ class Qwen2FlashAttention2(Qwen2Attention):
352
+ """
353
+ Qwen2 flash attention module, following Qwen2 attention module. This module inherits from `Qwen2Attention`
354
+ as the weights of the module stays untouched. The only required change would be on the forward pass
355
+ where it needs to correctly call the public API of flash attention and deal with padding tokens
356
+ in case the input contains any of them. Additionally, for sliding window attention, we apply SWA only to the bottom
357
+ config.max_window_layers layers.
358
+ """
359
+
360
+ # Copied from transformers.models.llama.modeling_llama.LlamaFlashAttention2.__init__
361
+ def __init__(self, *args, **kwargs):
362
+ super().__init__(*args, **kwargs)
363
+
364
+ # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
365
+ # 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.
366
+ # 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).
367
+ self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
368
+
369
+ def forward(
370
+ self,
371
+ hidden_states: torch.Tensor,
372
+ attention_mask: Optional[torch.Tensor] = None,
373
+ position_ids: Optional[torch.LongTensor] = None,
374
+ past_key_value: Optional[Cache] = None,
375
+ output_attentions: bool = False,
376
+ use_cache: bool = False,
377
+ cache_position: Optional[torch.LongTensor] = None,
378
+ position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, # will become mandatory in v4.46
379
+ layer_idx: Optional[int] = None,
380
+ ):
381
+
382
+ if layer_idx:
383
+ self.layer_idx = layer_idx
384
+
385
+ bsz, q_len, _ = hidden_states.size()
386
+
387
+ query_states = self.q_proj(hidden_states)
388
+ key_states = self.k_proj(hidden_states)
389
+ value_states = self.v_proj(hidden_states)
390
+
391
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
392
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
393
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
394
+
395
+ if position_embeddings is None:
396
+ logger.warning_once(
397
+ "The attention layers in this model are transitioning from computing the RoPE embeddings internally "
398
+ "through `position_ids` (2D tensor with the indexes of the tokens), to using externally computed "
399
+ "`position_embeddings` (Tuple of tensors, containing cos and sin). In v4.46 `position_ids` will be "
400
+ "removed and `position_embeddings` will be mandatory."
401
+ )
402
+ cos, sin = self.rotary_emb(value_states, position_ids)
403
+ else:
404
+ cos, sin = position_embeddings
405
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
406
+
407
+ if past_key_value is not None:
408
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position} # Specific to RoPE models
409
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
410
+
411
+ # repeat k/v heads if n_kv_heads < n_heads
412
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
413
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
414
+ dropout_rate = 0.0 if not self.training else self.attention_dropout
415
+
416
+ # In PEFT, usually we cast the layer norms in float32 for training stability reasons
417
+ # therefore the input hidden states gets silently casted in float32. Hence, we need
418
+ # cast them back in float16 just to be sure everything works as expected.
419
+ input_dtype = query_states.dtype
420
+ if input_dtype == torch.float32:
421
+ if torch.is_autocast_enabled():
422
+ target_dtype = torch.get_autocast_gpu_dtype()
423
+ # Handle the case where the model is quantized
424
+ elif hasattr(self.config, "_pre_quantization_dtype"):
425
+ target_dtype = self.config._pre_quantization_dtype
426
+ else:
427
+ target_dtype = self.q_proj.weight.dtype
428
+
429
+ logger.warning_once(
430
+ f"The input hidden states seems to be silently casted in float32, this might be related to"
431
+ f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
432
+ f" {target_dtype}."
433
+ )
434
+
435
+ query_states = query_states.to(target_dtype)
436
+ key_states = key_states.to(target_dtype)
437
+ value_states = value_states.to(target_dtype)
438
+
439
+ # Reashape to the expected shape for Flash Attention
440
+ query_states = query_states.transpose(1, 2)
441
+ key_states = key_states.transpose(1, 2)
442
+ value_states = value_states.transpose(1, 2)
443
+
444
+ if (
445
+ self.config.use_sliding_window
446
+ and getattr(self.config, "sliding_window", None) is not None
447
+ and self.layer_idx >= self.config.max_window_layers
448
+ ):
449
+ sliding_window = self.config.sliding_window
450
+ else:
451
+ sliding_window = None
452
+
453
+ attn_output = _flash_attention_forward(
454
+ query_states,
455
+ key_states,
456
+ value_states,
457
+ attention_mask,
458
+ q_len,
459
+ position_ids=position_ids,
460
+ dropout=dropout_rate,
461
+ sliding_window=sliding_window,
462
+ is_causal=self.is_causal,
463
+ use_top_left_mask=self._flash_attn_uses_top_left_mask,
464
+ )
465
+
466
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size).contiguous()
467
+ attn_output = self.o_proj(attn_output)
468
+
469
+ if not output_attentions:
470
+ attn_weights = None
471
+
472
+ return attn_output, attn_weights, past_key_value
473
+
474
+
475
+ class Qwen2SdpaAttention(Qwen2Attention):
476
+ """
477
+ Qwen2 attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from
478
+ `Qwen2Attention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to
479
+ SDPA API.
480
+ """
481
+
482
+ # Adapted from Qwen2Attention.forward
483
+ def forward(
484
+ self,
485
+ hidden_states: torch.Tensor,
486
+ attention_mask: Optional[torch.Tensor] = None,
487
+ position_ids: Optional[torch.LongTensor] = None,
488
+ past_key_value: Optional[Cache] = None,
489
+ output_attentions: bool = False,
490
+ use_cache: bool = False,
491
+ cache_position: Optional[torch.LongTensor] = None,
492
+ position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, # will become mandatory in v4.46
493
+ layer_idx: Optional[int] = None,
494
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
495
+ if layer_idx:
496
+ self.layer_idx = layer_idx
497
+ if output_attentions:
498
+ # TODO: Improve this warning with e.g. `model.config.attn_implementation = "manual"` once this is implemented.
499
+ logger.warning_once(
500
+ "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, "
501
+ '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.'
502
+ )
503
+ return super().forward(
504
+ hidden_states=hidden_states,
505
+ attention_mask=attention_mask,
506
+ position_ids=position_ids,
507
+ past_key_value=past_key_value,
508
+ output_attentions=output_attentions,
509
+ use_cache=use_cache,
510
+ )
511
+
512
+ bsz, q_len, _ = hidden_states.size()
513
+
514
+ query_states = self.q_proj(hidden_states)
515
+ key_states = self.k_proj(hidden_states)
516
+ value_states = self.v_proj(hidden_states)
517
+
518
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
519
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
520
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
521
+
522
+ if position_embeddings is None:
523
+ logger.warning_once(
524
+ "The attention layers in this model are transitioning from computing the RoPE embeddings internally "
525
+ "through `position_ids` (2D tensor with the indexes of the tokens), to using externally computed "
526
+ "`position_embeddings` (Tuple of tensors, containing cos and sin). In v4.46 `position_ids` will be "
527
+ "removed and `position_embeddings` will be mandatory."
528
+ )
529
+ cos, sin = self.rotary_emb(value_states, position_ids)
530
+ else:
531
+ cos, sin = position_embeddings
532
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
533
+
534
+ if past_key_value is not None:
535
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position} # Specific to RoPE models
536
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
537
+
538
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
539
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
540
+
541
+ causal_mask = attention_mask
542
+ if attention_mask is not None: # no matter the length, we just slice it
543
+ causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
544
+
545
+ # SDPA with memory-efficient backend is currently (torch==2.1.2) bugged with non-contiguous inputs with custom attn_mask,
546
+ # Reference: https://github.com/pytorch/pytorch/issues/112577.
547
+ if query_states.device.type == "cuda" and attention_mask is not None:
548
+ query_states = query_states.contiguous()
549
+ key_states = key_states.contiguous()
550
+ value_states = value_states.contiguous()
551
+
552
+ # We dispatch to SDPA's Flash Attention or Efficient kernels via this `is_causal` if statement instead of an inline conditional assignment
553
+ # in SDPA to support both torch.compile's dynamic shapes and full graph options. An inline conditional prevents dynamic shapes from compiling.
554
+ # 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.
555
+ is_causal = True if causal_mask is None and q_len > 1 else False
556
+
557
+ attn_output = torch.nn.functional.scaled_dot_product_attention(
558
+ query_states,
559
+ key_states,
560
+ value_states,
561
+ attn_mask=causal_mask,
562
+ dropout_p=self.attention_dropout if self.training else 0.0,
563
+ is_causal=is_causal,
564
+ )
565
+
566
+ attn_output = attn_output.transpose(1, 2).contiguous()
567
+ attn_output = attn_output.view(bsz, q_len, self.hidden_size)
568
+
569
+ attn_output = self.o_proj(attn_output)
570
+
571
+ return attn_output, None, past_key_value
572
+
573
+
574
+ QWEN2_ATTENTION_CLASSES = {
575
+ "eager": Qwen2Attention,
576
+ "flash_attention_2": Qwen2FlashAttention2,
577
+ "sdpa": Qwen2SdpaAttention,
578
+ }
579
+
580
+
581
+ class Qwen2DecoderLayer(nn.Module):
582
+ def __init__(self, config: CompacQwen2Config, layer_idx: int):
583
+ super().__init__()
584
+ self.hidden_size = config.hidden_size
585
+
586
+ if config.sliding_window and config._attn_implementation != "flash_attention_2":
587
+ logger.warning_once(
588
+ f"Sliding Window Attention is enabled but not implemented for `{config._attn_implementation}`; "
589
+ "unexpected results may be encountered."
590
+ )
591
+ self.self_attn = QWEN2_ATTENTION_CLASSES[config._attn_implementation](config, layer_idx)
592
+
593
+ self.mlp = Qwen2MLP(config)
594
+ self.input_layernorm = Qwen2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
595
+ self.post_attention_layernorm = Qwen2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
596
+
597
+ def forward(
598
+ self,
599
+ hidden_states: torch.Tensor,
600
+ attention_mask: Optional[torch.Tensor] = None,
601
+ position_ids: Optional[torch.LongTensor] = None,
602
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
603
+ output_attentions: Optional[bool] = False,
604
+ use_cache: Optional[bool] = False,
605
+ cache_position: Optional[torch.LongTensor] = None,
606
+ position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, # will become mandatory in v4.46,
607
+ layer_idx: Optional[int] = None,
608
+ **kwargs,
609
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
610
+ """
611
+ Args:
612
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
613
+ attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
614
+ `(batch, sequence_length)` where padding elements are indicated by 0.
615
+ output_attentions (`bool`, *optional*):
616
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
617
+ returned tensors for more detail.
618
+ use_cache (`bool`, *optional*):
619
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
620
+ (see `past_key_values`).
621
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
622
+ cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
623
+ Indices depicting the position of the input sequence tokens in the sequence.
624
+ position_embeddings (`Tuple[torch.FloatTensor, torch.FloatTensor]`, *optional*):
625
+ Tuple containing the cosine and sine positional embeddings of shape `(batch_size, seq_len, head_dim)`,
626
+ with `head_dim` being the embedding dimension of each attention head.
627
+ kwargs (`dict`, *optional*):
628
+ Arbitrary kwargs to be ignored, used for FSDP and other methods that injects code
629
+ into the model
630
+ """
631
+
632
+ residual = hidden_states
633
+
634
+ hidden_states = self.input_layernorm(hidden_states)
635
+
636
+ # Self Attention
637
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
638
+ hidden_states=hidden_states,
639
+ attention_mask=attention_mask,
640
+ position_ids=position_ids,
641
+ past_key_value=past_key_value,
642
+ output_attentions=output_attentions,
643
+ use_cache=use_cache,
644
+ cache_position=cache_position,
645
+ position_embeddings=position_embeddings,
646
+ layer_idx=layer_idx
647
+ )
648
+ hidden_states = residual + hidden_states
649
+
650
+ # Fully Connected
651
+ residual = hidden_states
652
+ hidden_states = self.post_attention_layernorm(hidden_states)
653
+ hidden_states = self.mlp(hidden_states)
654
+ hidden_states = residual + hidden_states
655
+
656
+ outputs = (hidden_states,)
657
+
658
+ if output_attentions:
659
+ outputs += (self_attn_weights,)
660
+
661
+ if use_cache:
662
+ outputs += (present_key_value,)
663
+
664
+ return outputs
665
+
666
+
667
+
668
+
669
+
670
+ QWEN2_START_DOCSTRING = r"""
671
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
672
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
673
+ etc.)
674
+
675
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
676
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
677
+ and behavior.
678
+
679
+ Parameters:
680
+ config ([`CompacQwen2Config`]):
681
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
682
+ load the weights associated with the model, only the configuration. Check out the
683
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
684
+ """
685
+
686
+
687
+ @add_start_docstrings(
688
+ "The bare Qwen2 Model outputting raw hidden-states without any specific head on top.",
689
+ QWEN2_START_DOCSTRING,
690
+ )
691
+ class Qwen2PreTrainedModel(PreTrainedModel):
692
+ config_class = CompacQwen2Config
693
+ base_model_prefix = "model"
694
+ supports_gradient_checkpointing = True
695
+ _no_split_modules = ["Qwen2DecoderLayer"]
696
+ _skip_keys_device_placement = "past_key_values"
697
+ _supports_flash_attn_2 = True
698
+ _supports_sdpa = True
699
+ _supports_cache_class = True
700
+ _supports_quantized_cache = True
701
+ _supports_static_cache = True
702
+
703
+ def _init_weights(self, module):
704
+ std = self.config.initializer_range
705
+ if isinstance(module, nn.Linear):
706
+ module.weight.data.normal_(mean=0.0, std=std)
707
+ if module.bias is not None:
708
+ module.bias.data.zero_()
709
+ elif isinstance(module, nn.Embedding):
710
+ module.weight.data.normal_(mean=0.0, std=std)
711
+ if module.padding_idx is not None:
712
+ module.weight.data[module.padding_idx].zero_()
713
+
714
+
715
+ QWEN2_INPUTS_DOCSTRING = r"""
716
+ Args:
717
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
718
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
719
+ it.
720
+
721
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
722
+ [`PreTrainedTokenizer.__call__`] for details.
723
+
724
+ [What are input IDs?](../glossary#input-ids)
725
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
726
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
727
+
728
+ - 1 for tokens that are **not masked**,
729
+ - 0 for tokens that are **masked**.
730
+
731
+ [What are attention masks?](../glossary#attention-mask)
732
+
733
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
734
+ [`PreTrainedTokenizer.__call__`] for details.
735
+
736
+ If `past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see
737
+ `past_key_values`).
738
+
739
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
740
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
741
+ information on the default strategy.
742
+
743
+ - 1 indicates the head is **not masked**,
744
+ - 0 indicates the head is **masked**.
745
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
746
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
747
+ config.n_positions - 1]`.
748
+
749
+ [What are position IDs?](../glossary#position-ids)
750
+ past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
751
+ Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
752
+ blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
753
+ returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
754
+
755
+ Two formats are allowed:
756
+ - a [`~cache_utils.Cache`] instance, see our
757
+ [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache);
758
+ - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
759
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
760
+ cache format.
761
+
762
+ The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
763
+ legacy cache format will be returned.
764
+
765
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
766
+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
767
+ of shape `(batch_size, sequence_length)`.
768
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
769
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
770
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
771
+ model's internal embedding lookup matrix.
772
+ use_cache (`bool`, *optional*):
773
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
774
+ `past_key_values`).
775
+ output_attentions (`bool`, *optional*):
776
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
777
+ tensors for more detail.
778
+ output_hidden_states (`bool`, *optional*):
779
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
780
+ more detail.
781
+ return_dict (`bool`, *optional*):
782
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
783
+ cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
784
+ Indices depicting the position of the input sequence tokens in the sequence. Contrarily to `position_ids`,
785
+ this tensor is not affected by padding. It is used to update the cache in the correct position and to infer
786
+ the complete sequence length.
787
+ """
788
+
789
+
790
+ @add_start_docstrings(
791
+ "The bare Qwen2 Model outputting raw hidden-states without any specific head on top.",
792
+ QWEN2_START_DOCSTRING,
793
+ )
794
+ class Qwen2Model(Qwen2PreTrainedModel):
795
+ """
796
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`Qwen2DecoderLayer`]
797
+
798
+ Args:
799
+ config: CompacQwen2Config
800
+ """
801
+
802
+ def __init__(self, config: CompacQwen2Config):
803
+ super().__init__(config)
804
+ self.padding_idx = config.pad_token_id
805
+ self.vocab_size = config.vocab_size
806
+
807
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
808
+
809
+
810
+ self.first_layer = Qwen2DecoderLayer(config, 0)
811
+
812
+ # self.shared_layer = Qwen2DecoderLayer(config, 1)
813
+
814
+ self.num_shared_groups = config.num_shared_groups # New config parameter for K
815
+ iterations_per_group = (config.num_hidden_layers - 2) // self.num_shared_groups
816
+ self.iterations_per_group = iterations_per_group
817
+
818
+ self.shared_layers = nn.ModuleList([
819
+ Qwen2DecoderLayer(config, i + 1)
820
+ for i in range(self.num_shared_groups)
821
+ ])
822
+
823
+ self.last_layer = Qwen2DecoderLayer(config, config.num_hidden_layers - 1)
824
+
825
+ # self.layers = nn.ModuleList(
826
+ # [Qwen2DecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
827
+ # )
828
+
829
+ self._attn_implementation = config._attn_implementation
830
+ self.norm = Qwen2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
831
+ self.rotary_emb = Qwen2RotaryEmbedding(config=config)
832
+
833
+ self.gradient_checkpointing = False
834
+ # Initialize weights and apply final processing
835
+ self.post_init()
836
+
837
+ def get_input_embeddings(self):
838
+ return self.embed_tokens
839
+
840
+ def set_input_embeddings(self, value):
841
+ self.embed_tokens = value
842
+
843
+ @add_start_docstrings_to_model_forward(QWEN2_INPUTS_DOCSTRING)
844
+ def forward(
845
+ self,
846
+ input_ids: torch.LongTensor = None,
847
+ attention_mask: Optional[torch.Tensor] = None,
848
+ position_ids: Optional[torch.LongTensor] = None,
849
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
850
+ inputs_embeds: Optional[torch.FloatTensor] = None,
851
+ use_cache: Optional[bool] = None,
852
+ output_attentions: Optional[bool] = None,
853
+ output_hidden_states: Optional[bool] = None,
854
+ return_dict: Optional[bool] = None,
855
+ cache_position: Optional[torch.LongTensor] = None,
856
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
857
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
858
+ output_hidden_states = (
859
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
860
+ )
861
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
862
+
863
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
864
+
865
+ if (input_ids is None) ^ (inputs_embeds is not None):
866
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
867
+
868
+ if self.gradient_checkpointing and self.training:
869
+ if use_cache:
870
+ logger.warning_once(
871
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
872
+ )
873
+ use_cache = False
874
+
875
+ # kept for BC (non `Cache` `past_key_values` inputs)
876
+ return_legacy_cache = False
877
+ if use_cache and not isinstance(past_key_values, Cache):
878
+ return_legacy_cache = True
879
+ if past_key_values is None:
880
+ past_key_values = DynamicCache()
881
+ else:
882
+ past_key_values = DynamicCache.from_legacy_cache(past_key_values)
883
+ logger.warning_once(
884
+ "We detected that you are passing `past_key_values` as a tuple of tuples. This is deprecated and "
885
+ "will be removed in v4.47. Please convert your cache or use an appropriate `Cache` class "
886
+ "(https://huggingface.co/docs/transformers/kv_cache#legacy-cache-format)"
887
+ )
888
+
889
+ if inputs_embeds is None:
890
+ inputs_embeds = self.embed_tokens(input_ids)
891
+
892
+ if cache_position is None:
893
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
894
+ cache_position = torch.arange(
895
+ past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
896
+ )
897
+ if position_ids is None:
898
+ position_ids = cache_position.unsqueeze(0)
899
+
900
+ causal_mask = self._update_causal_mask(
901
+ attention_mask, inputs_embeds, cache_position, past_key_values, output_attentions
902
+ )
903
+
904
+ hidden_states = inputs_embeds
905
+
906
+ # create position embeddings to be shared across the decoder layers
907
+ position_embeddings = self.rotary_emb(hidden_states, position_ids)
908
+
909
+ # decoder layers
910
+ all_hidden_states = () if output_hidden_states else None
911
+ all_self_attns = () if output_attentions else None
912
+ next_decoder_cache = None
913
+
914
+ # First layer
915
+ if output_hidden_states:
916
+ all_hidden_states += (hidden_states,)
917
+
918
+ layer_outputs = self._process_layer(
919
+ self.first_layer,
920
+ hidden_states,
921
+ causal_mask,
922
+ position_ids,
923
+ past_key_values,
924
+ output_attentions,
925
+ use_cache,
926
+ cache_position,
927
+ position_embeddings,
928
+ layer_idx=0
929
+ )
930
+
931
+ hidden_states = layer_outputs[0]
932
+ if use_cache:
933
+ next_decoder_cache = layer_outputs[2 if output_attentions else 1]
934
+ if output_attentions:
935
+ all_self_attns += (layer_outputs[1],)
936
+
937
+ # Process through K shared layers
938
+ current_layer_idx = 1
939
+ for group_idx in range(self.num_shared_groups):
940
+ shared_layer = self.shared_layers[group_idx]
941
+
942
+ # Each shared layer repeats iterations_per_group times
943
+ for iteration in range(self.iterations_per_group):
944
+ if output_hidden_states:
945
+ all_hidden_states += (hidden_states,)
946
+
947
+ layer_outputs = self._process_layer(
948
+ shared_layer,
949
+ hidden_states,
950
+ causal_mask,
951
+ position_ids,
952
+ past_key_values,
953
+ output_attentions,
954
+ use_cache,
955
+ cache_position,
956
+ position_embeddings,
957
+ layer_idx=current_layer_idx
958
+ )
959
+
960
+ hidden_states = layer_outputs[0]
961
+ if use_cache:
962
+ next_decoder_cache = layer_outputs[2 if output_attentions else 1]
963
+ if output_attentions:
964
+ all_self_attns += (layer_outputs[1],)
965
+
966
+ current_layer_idx += 1
967
+
968
+ # Last layer
969
+ if output_hidden_states:
970
+ all_hidden_states += (hidden_states,)
971
+
972
+ layer_outputs = self._process_layer(
973
+ self.last_layer,
974
+ hidden_states,
975
+ causal_mask,
976
+ position_ids,
977
+ past_key_values,
978
+ output_attentions,
979
+ use_cache,
980
+ cache_position,
981
+ position_embeddings,
982
+ layer_idx=self.config.num_hidden_layers - 1
983
+ )
984
+
985
+ hidden_states = layer_outputs[0]
986
+ if use_cache:
987
+ next_decoder_cache = layer_outputs[2 if output_attentions else 1]
988
+ if output_attentions:
989
+ all_self_attns += (layer_outputs[1],)
990
+
991
+ #Pass through last layer
992
+ if output_hidden_states:
993
+ all_hidden_states += (hidden_states,)
994
+
995
+ if self.gradient_checkpointing and self.training:
996
+ layer_outputs = self._gradient_checkpointing_func(
997
+ self.last_layer.__call__,
998
+ hidden_states,
999
+ causal_mask,
1000
+ position_ids,
1001
+ past_key_values,
1002
+ output_attentions,
1003
+ use_cache,
1004
+ cache_position,
1005
+ position_embeddings,
1006
+ )
1007
+ else:
1008
+ layer_outputs = self.last_layer(
1009
+ hidden_states,
1010
+ attention_mask=causal_mask,
1011
+ position_ids=position_ids,
1012
+ past_key_value=past_key_values,
1013
+ output_attentions=output_attentions,
1014
+ use_cache=use_cache,
1015
+ cache_position=cache_position,
1016
+ position_embeddings=position_embeddings,
1017
+ )
1018
+
1019
+ hidden_states = layer_outputs[0]
1020
+
1021
+ if use_cache:
1022
+ next_decoder_cache = layer_outputs[2 if output_attentions else 1]
1023
+
1024
+ if output_attentions:
1025
+ all_self_attns += (layer_outputs[1],)
1026
+
1027
+ #continue normally
1028
+
1029
+ hidden_states = self.norm(hidden_states)
1030
+
1031
+ # add hidden states from the last decoder layer
1032
+ if output_hidden_states:
1033
+ all_hidden_states += (hidden_states,)
1034
+
1035
+ next_cache = next_decoder_cache if use_cache else None
1036
+ if return_legacy_cache:
1037
+ next_cache = next_cache.to_legacy_cache()
1038
+
1039
+ if not return_dict:
1040
+ return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
1041
+ return BaseModelOutputWithPast(
1042
+ last_hidden_state=hidden_states,
1043
+ past_key_values=next_cache,
1044
+ hidden_states=all_hidden_states,
1045
+ attentions=all_self_attns,
1046
+ )
1047
+
1048
+ def _process_layer(
1049
+ self,
1050
+ layer,
1051
+ hidden_states,
1052
+ causal_mask,
1053
+ position_ids,
1054
+ past_key_values,
1055
+ output_attentions,
1056
+ use_cache,
1057
+ cache_position,
1058
+ position_embeddings,
1059
+ layer_idx
1060
+ ):
1061
+ """Helper method to process a single layer with gradient checkpointing if needed"""
1062
+ if self.gradient_checkpointing and self.training:
1063
+ layer_outputs = self._gradient_checkpointing_func(
1064
+ layer.__call__,
1065
+ hidden_states,
1066
+ causal_mask,
1067
+ position_ids,
1068
+ past_key_values,
1069
+ output_attentions,
1070
+ use_cache,
1071
+ cache_position,
1072
+ position_embeddings,
1073
+ layer_idx
1074
+ )
1075
+ else:
1076
+ layer_outputs = layer(
1077
+ hidden_states,
1078
+ attention_mask=causal_mask,
1079
+ position_ids=position_ids,
1080
+ past_key_value=past_key_values,
1081
+ output_attentions=output_attentions,
1082
+ use_cache=use_cache,
1083
+ cache_position=cache_position,
1084
+ position_embeddings=position_embeddings,
1085
+ layer_idx=layer_idx
1086
+ )
1087
+ return layer_outputs
1088
+ # Copied from transformers.models.phi3.modeling_phi3.Phi3Model._update_causal_mask
1089
+ def _update_causal_mask(
1090
+ self,
1091
+ attention_mask: torch.Tensor,
1092
+ input_tensor: torch.Tensor,
1093
+ cache_position: torch.Tensor,
1094
+ past_key_values: Cache,
1095
+ output_attentions: bool,
1096
+ ):
1097
+ if self.config._attn_implementation == "flash_attention_2":
1098
+ if attention_mask is not None and 0.0 in attention_mask:
1099
+ return attention_mask
1100
+ return None
1101
+
1102
+ # For SDPA, when possible, we will rely on its `is_causal` argument instead of its `attn_mask` argument, in
1103
+ # order to dispatch on Flash Attention 2. This feature is not compatible with static cache, as SDPA will fail
1104
+ # to infer the attention mask.
1105
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
1106
+ using_static_cache = isinstance(past_key_values, StaticCache)
1107
+ using_sliding_window_cache = isinstance(past_key_values, SlidingWindowCache)
1108
+
1109
+ # When output attentions is True, sdpa implementation's forward method calls the eager implementation's forward
1110
+ if (
1111
+ self.config._attn_implementation == "sdpa"
1112
+ and not (using_static_cache or using_sliding_window_cache)
1113
+ and not output_attentions
1114
+ ):
1115
+ if AttentionMaskConverter._ignore_causal_mask_sdpa(
1116
+ attention_mask,
1117
+ inputs_embeds=input_tensor,
1118
+ past_key_values_length=past_seen_tokens,
1119
+ sliding_window=self.config.sliding_window,
1120
+ is_training=self.training,
1121
+ ):
1122
+ return None
1123
+
1124
+ dtype, device = input_tensor.dtype, input_tensor.device
1125
+ min_dtype = torch.finfo(dtype).min
1126
+ sequence_length = input_tensor.shape[1]
1127
+ # SlidingWindowCache or StaticCache
1128
+ if using_sliding_window_cache or using_static_cache:
1129
+ target_length = past_key_values.get_max_cache_shape()
1130
+ # DynamicCache or no cache
1131
+ else:
1132
+ target_length = (
1133
+ attention_mask.shape[-1]
1134
+ if isinstance(attention_mask, torch.Tensor)
1135
+ else past_seen_tokens + sequence_length + 1
1136
+ )
1137
+
1138
+ # In case the provided `attention` mask is 2D, we generate a causal mask here (4D).
1139
+ causal_mask = self._prepare_4d_causal_attention_mask_with_cache_position(
1140
+ attention_mask,
1141
+ sequence_length=sequence_length,
1142
+ target_length=target_length,
1143
+ dtype=dtype,
1144
+ device=device,
1145
+ cache_position=cache_position,
1146
+ batch_size=input_tensor.shape[0],
1147
+ config=self.config,
1148
+ past_key_values=past_key_values,
1149
+ )
1150
+
1151
+ if (
1152
+ self.config._attn_implementation == "sdpa"
1153
+ and attention_mask is not None
1154
+ and attention_mask.device.type == "cuda"
1155
+ and not output_attentions
1156
+ ):
1157
+ # Attend to all tokens in fully masked rows in the causal_mask, for example the relevant first rows when
1158
+ # using left padding. This is required by F.scaled_dot_product_attention memory-efficient attention path.
1159
+ # Details: https://github.com/pytorch/pytorch/issues/110213
1160
+ causal_mask = AttentionMaskConverter._unmask_unattended(causal_mask, min_dtype)
1161
+
1162
+ return causal_mask
1163
+
1164
+ @staticmethod
1165
+ # Copied from transformers.models.mistral.modeling_mistral.MistralModel._prepare_4d_causal_attention_mask_with_cache_position with Mistral->Qwen2
1166
+ def _prepare_4d_causal_attention_mask_with_cache_position(
1167
+ attention_mask: torch.Tensor,
1168
+ sequence_length: int,
1169
+ target_length: int,
1170
+ dtype: torch.dtype,
1171
+ device: torch.device,
1172
+ cache_position: torch.Tensor,
1173
+ batch_size: int,
1174
+ config: CompacQwen2Config,
1175
+ past_key_values: Cache,
1176
+ ):
1177
+ """
1178
+ Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape
1179
+ `(batch_size, key_value_length)`, or if the input `attention_mask` is already 4D, do nothing.
1180
+
1181
+ Args:
1182
+ attention_mask (`torch.Tensor`):
1183
+ A 2D attention mask of shape `(batch_size, key_value_length)` or a 4D attention mask of shape `(batch_size, 1, query_length, key_value_length)`.
1184
+ sequence_length (`int`):
1185
+ The sequence length being processed.
1186
+ target_length (`int`):
1187
+ The target length: when generating with static cache, the mask should be as long as the static cache, to account for the 0 padding, the part of the cache that is not filled yet.
1188
+ dtype (`torch.dtype`):
1189
+ The dtype to use for the 4D attention mask.
1190
+ device (`torch.device`):
1191
+ The device to plcae the 4D attention mask on.
1192
+ cache_position (`torch.Tensor`):
1193
+ Indices depicting the position of the input sequence tokens in the sequence.
1194
+ batch_size (`torch.Tensor`):
1195
+ Batch size.
1196
+ config (`CompacQwen2Config`):
1197
+ The model's configuration class
1198
+ past_key_values (`Cache`):
1199
+ The cache class that is being used currently to generate
1200
+ """
1201
+ if attention_mask is not None and attention_mask.dim() == 4:
1202
+ # In this case we assume that the mask comes already in inverted form and requires no inversion or slicing.
1203
+ causal_mask = attention_mask
1204
+ else:
1205
+ min_dtype = torch.finfo(dtype).min
1206
+ causal_mask = torch.full(
1207
+ (sequence_length, target_length), fill_value=min_dtype, dtype=dtype, device=device
1208
+ )
1209
+ diagonal_attend_mask = torch.arange(target_length, device=device) > cache_position.reshape(-1, 1)
1210
+ if config.sliding_window is not None:
1211
+ # if we have sliding window, we should not attend to tokens beyond sliding window length, so we mask them out also
1212
+ # the check is needed to verify is current checkpoint was trained with sliding window or not
1213
+ if not isinstance(past_key_values, SlidingWindowCache) or sequence_length > target_length:
1214
+ sliding_attend_mask = torch.arange(target_length, device=device) <= (
1215
+ cache_position.reshape(-1, 1) - config.sliding_window
1216
+ )
1217
+ diagonal_attend_mask.bitwise_or_(sliding_attend_mask)
1218
+ causal_mask *= diagonal_attend_mask
1219
+ causal_mask = causal_mask[None, None, :, :].expand(batch_size, 1, -1, -1)
1220
+ if attention_mask is not None:
1221
+ causal_mask = causal_mask.clone() # copy to contiguous memory for in-place edit
1222
+ if attention_mask.shape[-1] > target_length:
1223
+ attention_mask = attention_mask[:, :target_length]
1224
+ mask_length = attention_mask.shape[-1]
1225
+ padding_mask = causal_mask[:, :, :, :mask_length] + attention_mask[:, None, None, :]
1226
+ padding_mask = padding_mask == 0
1227
+ causal_mask[:, :, :, :mask_length] = causal_mask[:, :, :, :mask_length].masked_fill(
1228
+ padding_mask, min_dtype
1229
+ )
1230
+ return causal_mask
1231
+
1232
+
1233
+ class Qwen2ForCausalLM(Qwen2PreTrainedModel, GenerationMixin):
1234
+ _tied_weights_keys = ["lm_head.weight"]
1235
+
1236
+ def __init__(self, config):
1237
+ super().__init__(config)
1238
+ self.model = Qwen2Model(config)
1239
+ self.vocab_size = config.vocab_size
1240
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1241
+
1242
+ # Initialize weights and apply final processing
1243
+ self.post_init()
1244
+
1245
+ def get_input_embeddings(self):
1246
+ return self.model.embed_tokens
1247
+
1248
+ def set_input_embeddings(self, value):
1249
+ self.model.embed_tokens = value
1250
+
1251
+ def get_output_embeddings(self):
1252
+ return self.lm_head
1253
+
1254
+ def set_output_embeddings(self, new_embeddings):
1255
+ self.lm_head = new_embeddings
1256
+
1257
+ def set_decoder(self, decoder):
1258
+ self.model = decoder
1259
+
1260
+ def get_decoder(self):
1261
+ return self.model
1262
+
1263
+ @add_start_docstrings_to_model_forward(QWEN2_INPUTS_DOCSTRING)
1264
+ @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
1265
+ def forward(
1266
+ self,
1267
+ input_ids: torch.LongTensor = None,
1268
+ attention_mask: Optional[torch.Tensor] = None,
1269
+ position_ids: Optional[torch.LongTensor] = None,
1270
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1271
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1272
+ labels: Optional[torch.LongTensor] = None,
1273
+ use_cache: Optional[bool] = None,
1274
+ output_attentions: Optional[bool] = None,
1275
+ output_hidden_states: Optional[bool] = None,
1276
+ return_dict: Optional[bool] = None,
1277
+ cache_position: Optional[torch.LongTensor] = None,
1278
+ num_logits_to_keep: int = 0,
1279
+ **loss_kwargs,
1280
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
1281
+ r"""
1282
+ Args:
1283
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1284
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1285
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1286
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1287
+
1288
+ num_logits_to_keep (`int`, *optional*):
1289
+ Calculate logits for the last `num_logits_to_keep` tokens. If `0`, calculate logits for all
1290
+ `input_ids` (special case). Only last token logits are needed for generation, and calculating them only for that
1291
+ token can save memory, which becomes pretty significant for long sequences or large vocabulary size.
1292
+
1293
+ Returns:
1294
+
1295
+ Example:
1296
+
1297
+ ```python
1298
+ >>> from transformers import AutoTokenizer, Qwen2ForCausalLM
1299
+
1300
+ >>> model = Qwen2ForCausalLM.from_pretrained(PATH_TO_CONVERTED_WEIGHTS)
1301
+ >>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER)
1302
+
1303
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
1304
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
1305
+
1306
+ >>> # Generate
1307
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
1308
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1309
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
1310
+ ```"""
1311
+
1312
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1313
+ output_hidden_states = (
1314
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1315
+ )
1316
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1317
+
1318
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1319
+ outputs = self.model(
1320
+ input_ids=input_ids,
1321
+ attention_mask=attention_mask,
1322
+ position_ids=position_ids,
1323
+ past_key_values=past_key_values,
1324
+ inputs_embeds=inputs_embeds,
1325
+ use_cache=use_cache,
1326
+ output_attentions=output_attentions,
1327
+ output_hidden_states=output_hidden_states,
1328
+ return_dict=return_dict,
1329
+ cache_position=cache_position,
1330
+ )
1331
+
1332
+ hidden_states = outputs[0]
1333
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
1334
+ logits = self.lm_head(hidden_states[:, -num_logits_to_keep:, :])
1335
+
1336
+ loss = None
1337
+ if labels is not None:
1338
+ loss = self.loss_function(logits, labels, self.vocab_size, **loss_kwargs)
1339
+
1340
+ if not return_dict:
1341
+ output = (logits,) + outputs[1:]
1342
+ return (loss,) + output if loss is not None else output
1343
+
1344
+ return CausalLMOutputWithPast(
1345
+ loss=loss,
1346
+ logits=logits,
1347
+ past_key_values=outputs.past_key_values,
1348
+ hidden_states=outputs.hidden_states,
1349
+ attentions=outputs.attentions,
1350
+ )
1351
+
1352
+
1353
+ @add_start_docstrings(
1354
+ """
1355
+ The Qwen2 Model transformer with a sequence classification head on top (linear layer).
1356
+
1357
+ [`Qwen2ForSequenceClassification`] uses the last token in order to do the classification, as other causal models
1358
+ (e.g. GPT-2) do.
1359
+
1360
+ Since it does classification on the last token, it requires to know the position of the last token. If a
1361
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
1362
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
1363
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
1364
+ each row of the batch).
1365
+ """,
1366
+ QWEN2_START_DOCSTRING,
1367
+ )
1368
+ class Qwen2ForSequenceClassification(Qwen2PreTrainedModel):
1369
+ def __init__(self, config):
1370
+ super().__init__(config)
1371
+ self.num_labels = config.num_labels
1372
+ self.model = Qwen2Model(config)
1373
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
1374
+
1375
+ # Initialize weights and apply final processing
1376
+ self.post_init()
1377
+
1378
+ def get_input_embeddings(self):
1379
+ return self.model.embed_tokens
1380
+
1381
+ def set_input_embeddings(self, value):
1382
+ self.model.embed_tokens = value
1383
+
1384
+ @add_start_docstrings_to_model_forward(QWEN2_INPUTS_DOCSTRING)
1385
+ def forward(
1386
+ self,
1387
+ input_ids: torch.LongTensor = None,
1388
+ attention_mask: Optional[torch.Tensor] = None,
1389
+ position_ids: Optional[torch.LongTensor] = None,
1390
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1391
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1392
+ labels: Optional[torch.LongTensor] = None,
1393
+ use_cache: Optional[bool] = None,
1394
+ output_attentions: Optional[bool] = None,
1395
+ output_hidden_states: Optional[bool] = None,
1396
+ return_dict: Optional[bool] = None,
1397
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
1398
+ r"""
1399
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1400
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1401
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1402
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1403
+ """
1404
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1405
+
1406
+ transformer_outputs = self.model(
1407
+ input_ids,
1408
+ attention_mask=attention_mask,
1409
+ position_ids=position_ids,
1410
+ past_key_values=past_key_values,
1411
+ inputs_embeds=inputs_embeds,
1412
+ use_cache=use_cache,
1413
+ output_attentions=output_attentions,
1414
+ output_hidden_states=output_hidden_states,
1415
+ return_dict=return_dict,
1416
+ )
1417
+ hidden_states = transformer_outputs[0]
1418
+ logits = self.score(hidden_states)
1419
+
1420
+ if input_ids is not None:
1421
+ batch_size = input_ids.shape[0]
1422
+ else:
1423
+ batch_size = inputs_embeds.shape[0]
1424
+
1425
+ if self.config.pad_token_id is None and batch_size != 1:
1426
+ raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
1427
+ if self.config.pad_token_id is None:
1428
+ sequence_lengths = -1
1429
+ else:
1430
+ if input_ids is not None:
1431
+ # if no pad token found, use modulo instead of reverse indexing for ONNX compatibility
1432
+ sequence_lengths = torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1
1433
+ sequence_lengths = sequence_lengths % input_ids.shape[-1]
1434
+ sequence_lengths = sequence_lengths.to(logits.device)
1435
+ else:
1436
+ sequence_lengths = -1
1437
+
1438
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
1439
+
1440
+ loss = None
1441
+ if labels is not None:
1442
+ labels = labels.to(logits.device)
1443
+ if self.config.problem_type is None:
1444
+ if self.num_labels == 1:
1445
+ self.config.problem_type = "regression"
1446
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
1447
+ self.config.problem_type = "single_label_classification"
1448
+ else:
1449
+ self.config.problem_type = "multi_label_classification"
1450
+
1451
+ if self.config.problem_type == "regression":
1452
+ loss_fct = MSELoss()
1453
+ if self.num_labels == 1:
1454
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
1455
+ else:
1456
+ loss = loss_fct(pooled_logits, labels)
1457
+ elif self.config.problem_type == "single_label_classification":
1458
+ loss_fct = CrossEntropyLoss()
1459
+ loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
1460
+ elif self.config.problem_type == "multi_label_classification":
1461
+ loss_fct = BCEWithLogitsLoss()
1462
+ loss = loss_fct(pooled_logits, labels)
1463
+ if not return_dict:
1464
+ output = (pooled_logits,) + transformer_outputs[1:]
1465
+ return ((loss,) + output) if loss is not None else output
1466
+
1467
+ return SequenceClassifierOutputWithPast(
1468
+ loss=loss,
1469
+ logits=pooled_logits,
1470
+ past_key_values=transformer_outputs.past_key_values,
1471
+ hidden_states=transformer_outputs.hidden_states,
1472
+ attentions=transformer_outputs.attentions,
1473
+ )
1474
+
1475
+
1476
+ @add_start_docstrings(
1477
+ """
1478
+ The Qwen2 Model transformer with a token classification head on top (a linear layer on top of the hidden-states
1479
+ output) e.g. for Named-Entity-Recognition (NER) tasks.
1480
+ """,
1481
+ QWEN2_START_DOCSTRING,
1482
+ )
1483
+ # Copied from transformers.models.llama.modeling_llama.LlamaForTokenClassification with Llama->Qwen2, LLAMA->QWEN2
1484
+ class Qwen2ForTokenClassification(Qwen2PreTrainedModel):
1485
+ def __init__(self, config):
1486
+ super().__init__(config)
1487
+ self.num_labels = config.num_labels
1488
+ self.model = Qwen2Model(config)
1489
+ if getattr(config, "classifier_dropout", None) is not None:
1490
+ classifier_dropout = config.classifier_dropout
1491
+ elif getattr(config, "hidden_dropout", None) is not None:
1492
+ classifier_dropout = config.hidden_dropout
1493
+ else:
1494
+ classifier_dropout = 0.1
1495
+ self.dropout = nn.Dropout(classifier_dropout)
1496
+ self.score = nn.Linear(config.hidden_size, config.num_labels)
1497
+
1498
+ # Initialize weights and apply final processing
1499
+ self.post_init()
1500
+
1501
+ def get_input_embeddings(self):
1502
+ return self.model.embed_tokens
1503
+
1504
+ def set_input_embeddings(self, value):
1505
+ self.model.embed_tokens = value
1506
+
1507
+ @add_start_docstrings_to_model_forward(QWEN2_INPUTS_DOCSTRING)
1508
+ @add_code_sample_docstrings(
1509
+ checkpoint=_CHECKPOINT_FOR_DOC,
1510
+ output_type=TokenClassifierOutput,
1511
+ config_class=_CONFIG_FOR_DOC,
1512
+ )
1513
+ def forward(
1514
+ self,
1515
+ input_ids: Optional[torch.LongTensor] = None,
1516
+ attention_mask: Optional[torch.Tensor] = None,
1517
+ position_ids: Optional[torch.LongTensor] = None,
1518
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1519
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1520
+ labels: Optional[torch.LongTensor] = None,
1521
+ use_cache: Optional[bool] = None,
1522
+ output_attentions: Optional[bool] = None,
1523
+ output_hidden_states: Optional[bool] = None,
1524
+ return_dict: Optional[bool] = None,
1525
+ ) -> Union[Tuple, TokenClassifierOutput]:
1526
+ r"""
1527
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1528
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1529
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1530
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1531
+ """
1532
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1533
+
1534
+ outputs = self.model(
1535
+ input_ids,
1536
+ attention_mask=attention_mask,
1537
+ position_ids=position_ids,
1538
+ past_key_values=past_key_values,
1539
+ inputs_embeds=inputs_embeds,
1540
+ use_cache=use_cache,
1541
+ output_attentions=output_attentions,
1542
+ output_hidden_states=output_hidden_states,
1543
+ return_dict=return_dict,
1544
+ )
1545
+ sequence_output = outputs[0]
1546
+ sequence_output = self.dropout(sequence_output)
1547
+ logits = self.score(sequence_output)
1548
+
1549
+ loss = None
1550
+ if labels is not None:
1551
+ loss = self.loss_function(logits, labels, self.config)
1552
+
1553
+ if not return_dict:
1554
+ output = (logits,) + outputs[2:]
1555
+ return ((loss,) + output) if loss is not None else output
1556
+
1557
+ return TokenClassifierOutput(
1558
+ loss=loss,
1559
+ logits=logits,
1560
+ hidden_states=outputs.hidden_states,
1561
+ attentions=outputs.attentions,
1562
+ )
1563
+
1564
+
1565
+ @add_start_docstrings(
1566
+ """
1567
+ The Qwen2 Model transformer with a span classification head on top for extractive question-answering tasks like
1568
+ SQuAD (a linear layer on top of the hidden-states output to compute `span start logits` and `span end logits`).
1569
+ """,
1570
+ QWEN2_START_DOCSTRING,
1571
+ )
1572
+ # Copied from transformers.models.mistral.modeling_mistral.MistralForQuestionAnswering with Mistral->Qwen2, MISTRAL->QWEN2
1573
+ class Qwen2ForQuestionAnswering(Qwen2PreTrainedModel):
1574
+ base_model_prefix = "model"
1575
+
1576
+ # Copied from models.models.bloom.modeling_bloom.BloomForQuestionAnswering.__init__ with Bloom->Qwen2
1577
+ def __init__(self, config):
1578
+ super().__init__(config)
1579
+ self.model = Qwen2Model(config)
1580
+ self.qa_outputs = nn.Linear(config.hidden_size, 2)
1581
+
1582
+ # Initialize weights and apply final processing
1583
+ self.post_init()
1584
+
1585
+ def get_input_embeddings(self):
1586
+ return self.model.embed_tokens
1587
+
1588
+ def set_input_embeddings(self, value):
1589
+ self.model.embed_tokens = value
1590
+
1591
+ @add_start_docstrings_to_model_forward(QWEN2_INPUTS_DOCSTRING)
1592
+ def forward(
1593
+ self,
1594
+ input_ids: Optional[torch.LongTensor] = None,
1595
+ attention_mask: Optional[torch.FloatTensor] = None,
1596
+ position_ids: Optional[torch.LongTensor] = None,
1597
+ past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
1598
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1599
+ start_positions: Optional[torch.LongTensor] = None,
1600
+ end_positions: Optional[torch.LongTensor] = None,
1601
+ output_attentions: Optional[bool] = None,
1602
+ output_hidden_states: Optional[bool] = None,
1603
+ return_dict: Optional[bool] = None,
1604
+ **kwargs,
1605
+ ) -> Union[Tuple, QuestionAnsweringModelOutput]:
1606
+ r"""
1607
+ start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1608
+ Labels for position (index) of the start of the labelled span for computing the token classification loss.
1609
+ Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
1610
+ are not taken into account for computing the loss.
1611
+ end_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1612
+ Labels for position (index) of the end of the labelled span for computing the token classification loss.
1613
+ Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
1614
+ are not taken into account for computing the loss.
1615
+ """
1616
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1617
+
1618
+ outputs = self.model(
1619
+ input_ids,
1620
+ attention_mask=attention_mask,
1621
+ position_ids=position_ids,
1622
+ past_key_values=past_key_values,
1623
+ inputs_embeds=inputs_embeds,
1624
+ output_attentions=output_attentions,
1625
+ output_hidden_states=output_hidden_states,
1626
+ return_dict=return_dict,
1627
+ )
1628
+
1629
+ sequence_output = outputs[0]
1630
+
1631
+ logits = self.qa_outputs(sequence_output)
1632
+ start_logits, end_logits = logits.split(1, dim=-1)
1633
+ start_logits = start_logits.squeeze(-1).contiguous()
1634
+ end_logits = end_logits.squeeze(-1).contiguous()
1635
+
1636
+ loss = None
1637
+ if start_positions is not None and end_positions is not None:
1638
+ loss = self.loss_function(start_logits, end_logits, start_positions, end_positions, **kwargs)
1639
+
1640
+ if not return_dict:
1641
+ output = (start_logits, end_logits) + outputs[2:]
1642
+ return ((loss,) + output) if loss is not None else output
1643
+
1644
+ return QuestionAnsweringModelOutput(
1645
+ loss=loss,
1646
+ start_logits=start_logits,
1647
+ end_logits=end_logits,
1648
+ hidden_states=outputs.hidden_states,
1649
+ attentions=outputs.attentions,
1650
+ )