lll2343 commited on
Commit
171cd7a
·
verified ·
1 Parent(s): 2a1a5dc

Upload modeling_sdlm.py with huggingface_hub

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