Yuki131 commited on
Commit
b783a8a
·
verified ·
1 Parent(s): 7bcdf9b

Upload 12 files

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