leeloolee commited on
Commit
966662a
1 Parent(s): 7e7255d

Create modeling_boost.py

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