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License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ #
16
+ # This code is based off the following work:
17
+ # https://github.com/huggingface/transformers/blob/main/src/transformers/models/llama/modeling_llama.py
18
+ # https://github.com/huggingface/transformers/blob/main/src/transformers/models/gpt_neox/modeling_gpt_neox.py
19
+ """ PyTorch StableLM Epoch model. """
20
+ from typing import Optional, Tuple, Union
21
+ import math
22
+ import warnings
23
+
24
+ import torch
25
+ import torch.nn.functional as F
26
+ import torch.utils.checkpoint
27
+ from torch import nn
28
+ from torch.nn import CrossEntropyLoss
29
+
30
+ from transformers.cache_utils import Cache
31
+ from transformers.modeling_outputs import (
32
+ BaseModelOutputWithPast,
33
+ CausalLMOutputWithPast,
34
+ )
35
+ from transformers.modeling_utils import PreTrainedModel
36
+ from transformers.utils import logging, is_flash_attn_greater_or_equal_2_10
37
+
38
+ try:
39
+ from .configuration_stablelm_epoch import StableLMEpochConfig
40
+ except:
41
+ from configuration_stablelm_epoch import StableLMEpochConfig
42
+
43
+ try:
44
+ from flash_attn import flash_attn_func, flash_attn_varlen_func
45
+ from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input
46
+ except:
47
+ flash_attn_func, flash_attn_varlen_func = None, None
48
+ index_first_axis, pad_input, unpad_input = None, None, None
49
+
50
+
51
+ logger = logging.get_logger(__name__)
52
+
53
+
54
+ # Copied from transformers.models.llama.modeling_llama._get_unpad_data
55
+ def _get_unpad_data(attention_mask):
56
+ seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
57
+ indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
58
+ max_seqlen_in_batch = seqlens_in_batch.max().item()
59
+ cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.torch.int32), (1, 0))
60
+ return (
61
+ indices,
62
+ cu_seqlens,
63
+ max_seqlen_in_batch,
64
+ )
65
+
66
+
67
+ # Copied from transformers.models.bart.modeling_bart._make_causal_mask
68
+ def _make_causal_mask(
69
+ input_ids_shape: torch.Size,
70
+ dtype: torch.dtype,
71
+ device: torch.device,
72
+ past_key_values_length: int = 0,
73
+ ):
74
+ """Make causal mask used for bi-directional self-attention."""
75
+ batch_size, tgt_len = input_ids_shape
76
+ mask = torch.full((tgt_len, tgt_len), torch.finfo(torch.float16).min, device=device)
77
+ mask_cond = torch.arange(mask.size(-1), device=device)
78
+ mask.masked_fill_(mask_cond < (mask_cond + 1).view(mask.size(-1), 1), 0)
79
+ mask = mask.to(dtype)
80
+ if past_key_values_length > 0:
81
+ mask = torch.cat([torch.zeros(tgt_len, past_key_values_length, dtype=dtype, device=device), mask], dim=-1)
82
+ return mask[None, None, :, :].expand(batch_size, 1, tgt_len, tgt_len + past_key_values_length)
83
+
84
+
85
+ # Copied from transformers.models.bart.modeling_bart._expand_mask
86
+ def _expand_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None):
87
+ """Expands attention_mask from `[batch_size, seq_len]` to `[batch_size, 1, tgt_seq_len, src_seq_len]`."""
88
+ batch_size, src_len = mask.size()
89
+ tgt_len = tgt_len if tgt_len is not None else src_len
90
+
91
+ expanded_mask = mask[:, None, None, :].expand(batch_size, 1, tgt_len, src_len).to(dtype)
92
+ inverted_mask = 1.0 - expanded_mask
93
+
94
+ return inverted_mask.masked_fill(
95
+ inverted_mask.to(torch.bool), torch.finfo(dtype).min
96
+ )
97
+
98
+
99
+ class RotaryEmbedding(nn.Module):
100
+ def __init__(
101
+ self,
102
+ dim: int,
103
+ max_position_embeddings: int,
104
+ base: int = 10_000,
105
+ device: Optional[torch.device] = None,
106
+ ):
107
+ super().__init__()
108
+
109
+ self.dim = dim
110
+ self.max_position_embeddings = max_position_embeddings
111
+ self.base = base
112
+ inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2, device=device, dtype=torch.float32) / self.dim))
113
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
114
+
115
+ # Build here to make `torch.jit.trace` work.
116
+ self._set_cos_sin_cache(
117
+ seq_len=max_position_embeddings, device=self.inv_freq.device, dtype=torch.get_default_dtype(),
118
+ )
119
+
120
+ def _set_cos_sin_cache(self, seq_len: int, device: torch.device, dtype: torch.dtype):
121
+ self.max_seq_len_cached = seq_len
122
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=torch.float32)
123
+
124
+ # Don't do einsum, it converts fp32 to fp16 under AMP
125
+ # freqs = torch.einsum("i,j->ij", t, self.inv_freq)
126
+ freqs = torch.outer(t, self.inv_freq)
127
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
128
+ emb = torch.cat((freqs, freqs), dim=-1)
129
+ self.register_buffer("cos_cached", emb.cos()[None, None, :, :].to(dtype), persistent=False)
130
+ self.register_buffer("sin_cached", emb.sin()[None, None, :, :].to(dtype), persistent=False)
131
+
132
+ def forward(self, x: torch.Tensor, seq_len: Optional[int] = None):
133
+ # x: [batch_size, num_heads, seq_len, head_size]
134
+ if seq_len > self.max_seq_len_cached:
135
+ self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=torch.get_default_dtype())
136
+ return (
137
+ self.cos_cached[:, :, :seq_len, ...].to(dtype=x.dtype),
138
+ self.sin_cached[:, :, :seq_len, ...].to(dtype=x.dtype),
139
+ )
140
+
141
+
142
+ def rotate_half(x: torch.Tensor):
143
+ """Rotates half the hidden dims of the input."""
144
+ x1, x2 = torch.chunk(x, 2, dim=-1)
145
+ return torch.cat((-x2, x1), dim=-1)
146
+
147
+
148
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids):
149
+ # The first two dimensions of cos and sin are always 1, so we can `squeeze` them.
150
+ cos = cos.squeeze(1).squeeze(0) # [seq_len, dim]
151
+ sin = sin.squeeze(1).squeeze(0) # [seq_len, dim]
152
+ cos = cos[position_ids].unsqueeze(1) # [batch_size, 1, seq_len, dim]
153
+ sin = sin[position_ids].unsqueeze(1) # [batch_size, 1, seq_len, dim]
154
+ q_embed = (q * cos) + (rotate_half(q) * sin)
155
+ k_embed = (k * cos) + (rotate_half(k) * sin)
156
+ return q_embed, k_embed
157
+
158
+
159
+ class MLP(nn.Module):
160
+ def __init__(self, config: StableLMEpochConfig):
161
+ super().__init__()
162
+ self.config = config
163
+ self.hidden_size = config.hidden_size
164
+ self.intermediate_size = config.intermediate_size
165
+ self.gate_proj = nn.Linear(config.hidden_size, config.intermediate_size, bias=False)
166
+ self.up_proj = nn.Linear(config.hidden_size, config.intermediate_size, bias=False)
167
+ self.down_proj = nn.Linear(config.intermediate_size, config.hidden_size, bias=False)
168
+ self.act_fn = nn.SiLU()
169
+
170
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
171
+ return self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
172
+
173
+
174
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
175
+ """
176
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
177
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
178
+ """
179
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
180
+ if n_rep == 1:
181
+ return hidden_states
182
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
183
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
184
+
185
+
186
+ class Attention(nn.Module):
187
+ def __init__(self, config: StableLMEpochConfig):
188
+ super().__init__()
189
+ self.config = config
190
+ self.hidden_size = config.hidden_size
191
+ self.num_heads = config.num_attention_heads
192
+ self.head_dim = self.hidden_size // self.num_heads
193
+ self.num_key_value_heads = config.num_key_value_heads
194
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
195
+ self.max_position_embeddings = config.max_position_embeddings
196
+ self.is_causal = True
197
+ self.attention_dropout = 0.0 # dbg: added
198
+
199
+ if (self.head_dim * self.num_heads) != self.hidden_size:
200
+ raise ValueError(
201
+ f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
202
+ f" and `num_heads`: {self.num_heads})."
203
+ )
204
+
205
+ self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=config.use_qkv_bias)
206
+ self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.use_qkv_bias)
207
+ self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.use_qkv_bias)
208
+ self.o_proj = nn.Linear(self.hidden_size, self.hidden_size, bias=False)
209
+
210
+ self._init_rope()
211
+
212
+ def _init_rope(self):
213
+ self.rotary_ndims = int(self.head_dim * self.config.rope_pct)
214
+ self.rotary_emb = RotaryEmbedding(
215
+ self.rotary_ndims,
216
+ max_position_embeddings=self.config.max_position_embeddings,
217
+ base=self.config.rope_theta,
218
+ )
219
+
220
+ def forward(
221
+ self,
222
+ hidden_states: torch.FloatTensor,
223
+ attention_mask: torch.FloatTensor,
224
+ position_ids: torch.LongTensor,
225
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
226
+ output_attentions: Optional[bool] = False,
227
+ use_cache: Optional[bool] = False,
228
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
229
+ bsz, q_len, _ = hidden_states.size()
230
+
231
+ query_states = self.q_proj(hidden_states)
232
+ key_states = self.k_proj(hidden_states)
233
+ value_states = self.v_proj(hidden_states)
234
+
235
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
236
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
237
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
238
+
239
+ query_rot = query_states[..., : self.rotary_ndims]
240
+ query_pass = query_states[..., self.rotary_ndims :]
241
+ key_rot = key_states[..., : self.rotary_ndims]
242
+ key_pass = key_states[..., self.rotary_ndims :]
243
+
244
+ kv_seq_len = key_states.shape[-2]
245
+ if past_key_value is not None:
246
+ kv_seq_len += past_key_value[0].shape[-2]
247
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
248
+ query_states, key_states = apply_rotary_pos_emb(query_rot, key_rot, cos, sin, position_ids)
249
+
250
+ # [batch_size, num_heads, seq_len, head_dim]
251
+ query_states = torch.cat((query_states, query_pass), dim=-1)
252
+ key_states = torch.cat((key_states, key_pass), dim=-1)
253
+
254
+ if past_key_value is not None:
255
+ # Reuse k, v, self_attention
256
+ key_states = torch.cat((past_key_value[0], key_states), dim=2)
257
+ value_states = torch.cat((past_key_value[1], value_states), dim=2)
258
+
259
+ past_key_value = (key_states, value_states) if use_cache else None
260
+
261
+ # Repeat k/v heads if n_kv_heads < n_heads
262
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
263
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
264
+
265
+ attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
266
+
267
+ if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
268
+ raise ValueError(
269
+ f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is"
270
+ f" {attn_weights.size()}"
271
+ )
272
+
273
+ if attention_mask is not None:
274
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
275
+ raise ValueError(
276
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
277
+ )
278
+ attn_weights = attn_weights + attention_mask
279
+
280
+ # Upcast attention to fp32
281
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
282
+ attn_output = torch.matmul(attn_weights, value_states)
283
+
284
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
285
+ raise ValueError(
286
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
287
+ f" {attn_output.size()}"
288
+ )
289
+
290
+ # Merge heads
291
+ attn_output = attn_output.transpose(1, 2).contiguous()
292
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
293
+
294
+ # Final linear projection
295
+ attn_output = self.o_proj(attn_output)
296
+
297
+ if not output_attentions:
298
+ attn_weights = None
299
+
300
+ return attn_output, attn_weights, past_key_value
301
+
302
+
303
+ class FlashAttention2(Attention):
304
+ """
305
+ Reference: https://github.com/huggingface/transformers/blob/5d36025ca13d05151b7a0c761e90d429c4644a30/src/transformers/models/llama/modeling_llama.py#L456
306
+ """
307
+
308
+ def __init__(self, *args, **kwargs):
309
+ super().__init__(*args, **kwargs)
310
+
311
+ # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
312
+ # 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.
313
+ # 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).
314
+ self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
315
+
316
+ def forward(
317
+ self,
318
+ hidden_states: torch.Tensor,
319
+ attention_mask: Optional[torch.LongTensor] = None,
320
+ position_ids: Optional[torch.LongTensor] = None,
321
+ past_key_value: Optional[Cache] = None,
322
+ output_attentions: bool = False,
323
+ use_cache: bool = False,
324
+ **kwargs,
325
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
326
+ # FlashAttention2 attention does not support output_attentions
327
+ if "padding_mask" in kwargs:
328
+ warnings.warn(
329
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
330
+ )
331
+
332
+ # overwrite attention_mask with padding_mask
333
+ attention_mask = kwargs.pop("padding_mask")
334
+
335
+ output_attentions = False
336
+
337
+ bsz, q_len, _ = hidden_states.size()
338
+
339
+ query_states = self.q_proj(hidden_states)
340
+ key_states = self.k_proj(hidden_states)
341
+ value_states = self.v_proj(hidden_states)
342
+
343
+ # Flash attention requires the input to have the shape
344
+ # batch_size x seq_length x head_dim x hidden_dim
345
+ # therefore we just need to keep the original shape
346
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
347
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
348
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
349
+
350
+ query_rot = query_states[..., : self.rotary_ndims]
351
+ query_pass = query_states[..., self.rotary_ndims :]
352
+ key_rot = key_states[..., : self.rotary_ndims]
353
+ key_pass = key_states[..., self.rotary_ndims :]
354
+
355
+ kv_seq_len = key_states.shape[-2]
356
+ if past_key_value is not None:
357
+ kv_seq_len += past_key_value[0].shape[-2]
358
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
359
+ query_states, key_states = apply_rotary_pos_emb(query_rot, key_rot, cos, sin, position_ids)
360
+
361
+ # [batch_size, num_heads, seq_len, head_dim]
362
+ query_states = torch.cat((query_states, query_pass), dim=-1)
363
+ key_states = torch.cat((key_states, key_pass), dim=-1)
364
+
365
+ if past_key_value is not None:
366
+ # Reuse k, v, self_attention
367
+ key_states = torch.cat((past_key_value[0], key_states), dim=2)
368
+ value_states = torch.cat((past_key_value[1], value_states), dim=2)
369
+
370
+ past_key_value = (key_states, value_states) if use_cache else None
371
+
372
+ # TODO: These transpose are quite inefficient but Flash Attention requires the layout [batch_size, sequence_length, num_heads, head_dim]. We would need to refactor the KV cache
373
+ # to be able to avoid many of these transpose/reshape/view.
374
+ query_states = query_states.transpose(1, 2)
375
+ key_states = key_states.transpose(1, 2)
376
+ value_states = value_states.transpose(1, 2)
377
+
378
+ dropout_rate = self.attention_dropout if self.training else 0.0
379
+
380
+ attn_output = self._flash_attention_forward(
381
+ query_states, key_states, value_states, attention_mask, q_len, dropout=dropout_rate
382
+ )
383
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size).contiguous()
384
+ attn_output = self.o_proj(attn_output)
385
+
386
+ if not output_attentions:
387
+ attn_weights = None
388
+
389
+ return attn_output, attn_weights, past_key_value
390
+
391
+ def _flash_attention_forward(
392
+ self, query_states, key_states, value_states, attention_mask, query_length, dropout=0.0, softmax_scale=None
393
+ ):
394
+ """
395
+ Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
396
+ first unpad the input, then computes the attention scores and pad the final attention scores.
397
+
398
+ Args:
399
+ query_states (`torch.Tensor`):
400
+ Input query states to be passed to Flash Attention API
401
+ key_states (`torch.Tensor`):
402
+ Input key states to be passed to Flash Attention API
403
+ value_states (`torch.Tensor`):
404
+ Input value states to be passed to Flash Attention API
405
+ attention_mask (`torch.Tensor`):
406
+ The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
407
+ position of padding tokens and 1 for the position of non-padding tokens.
408
+ dropout (`int`, *optional*):
409
+ Attention dropout
410
+ softmax_scale (`float`, *optional*):
411
+ The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
412
+ """
413
+ if not self._flash_attn_uses_top_left_mask:
414
+ causal = self.is_causal
415
+ else:
416
+ # TODO: Remove the `query_length != 1` check once Flash Attention for RoCm is bumped to 2.1. For details, please see the comment in FlashAttention2 __init__.
417
+ causal = self.is_causal and query_length != 1
418
+
419
+ # Contains at least one padding token in the sequence
420
+ if attention_mask is not None:
421
+ batch_size = query_states.shape[0]
422
+ query_states, key_states, value_states, indices_q, cu_seq_lens, max_seq_lens = self._upad_input(
423
+ query_states, key_states, value_states, attention_mask, query_length
424
+ )
425
+
426
+ cu_seqlens_q, cu_seqlens_k = cu_seq_lens
427
+ max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
428
+
429
+ attn_output_unpad = flash_attn_varlen_func(
430
+ query_states,
431
+ key_states,
432
+ value_states,
433
+ cu_seqlens_q=cu_seqlens_q,
434
+ cu_seqlens_k=cu_seqlens_k,
435
+ max_seqlen_q=max_seqlen_in_batch_q,
436
+ max_seqlen_k=max_seqlen_in_batch_k,
437
+ dropout_p=dropout,
438
+ softmax_scale=softmax_scale,
439
+ causal=causal,
440
+ )
441
+
442
+ attn_output = pad_input(attn_output_unpad, indices_q, batch_size, query_length)
443
+ else:
444
+ attn_output = flash_attn_func(
445
+ query_states, key_states, value_states, dropout, softmax_scale=softmax_scale, causal=causal
446
+ )
447
+
448
+ return attn_output
449
+
450
+ def _upad_input(self, query_layer, key_layer, value_layer, attention_mask, query_length):
451
+ indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
452
+ batch_size, kv_seq_len, num_key_value_heads, head_dim = key_layer.shape
453
+
454
+ key_layer = index_first_axis(
455
+ key_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
456
+ )
457
+ value_layer = index_first_axis(
458
+ value_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
459
+ )
460
+ if query_length == kv_seq_len:
461
+ query_layer = index_first_axis(
462
+ query_layer.reshape(batch_size * kv_seq_len, self.num_heads, head_dim), indices_k
463
+ )
464
+ cu_seqlens_q = cu_seqlens_k
465
+ max_seqlen_in_batch_q = max_seqlen_in_batch_k
466
+ indices_q = indices_k
467
+ elif query_length == 1:
468
+ max_seqlen_in_batch_q = 1
469
+ cu_seqlens_q = torch.arange(
470
+ batch_size + 1, dtype=torch.int32, device=query_layer.device
471
+ ) # There is a memcpy here, that is very bad.
472
+ indices_q = cu_seqlens_q[:-1]
473
+ query_layer = query_layer.squeeze(1)
474
+ else:
475
+ # The -q_len: slice assumes left padding.
476
+ attention_mask = attention_mask[:, -query_length:]
477
+ query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(query_layer, attention_mask)
478
+
479
+ return (
480
+ query_layer,
481
+ key_layer,
482
+ value_layer,
483
+ indices_q,
484
+ (cu_seqlens_q, cu_seqlens_k),
485
+ (max_seqlen_in_batch_q, max_seqlen_in_batch_k),
486
+ )
487
+
488
+
489
+ ATTENTION_CLASSES = {
490
+ "eager": Attention,
491
+ "flash_attention_2": FlashAttention2,
492
+ }
493
+
494
+
495
+ class DecoderLayer(nn.Module):
496
+ def __init__(self, config: StableLMEpochConfig):
497
+ super().__init__()
498
+ self.self_attn = ATTENTION_CLASSES[config._attn_implementation](config=config)
499
+ self.mlp = MLP(config)
500
+ self.input_layernorm = nn.LayerNorm(config.hidden_size, eps=config.norm_eps)
501
+ self.post_attention_layernorm = nn.LayerNorm(config.hidden_size, eps=config.norm_eps)
502
+
503
+ def forward(
504
+ self,
505
+ hidden_states: Optional[torch.FloatTensor],
506
+ attention_mask: Optional[torch.FloatTensor] = None,
507
+ position_ids: Optional[torch.LongTensor] = None,
508
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
509
+ output_attentions: Optional[bool] = False,
510
+ use_cache: Optional[bool] = False,
511
+ ) -> Union[Tuple[torch.Tensor], Optional[Tuple[torch.Tensor, Tuple[torch.FloatTensor, ...]]]]:
512
+ residual = hidden_states
513
+
514
+ hidden_states = self.input_layernorm(hidden_states)
515
+
516
+ # Self Attention
517
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
518
+ hidden_states=hidden_states,
519
+ attention_mask=attention_mask,
520
+ position_ids=position_ids,
521
+ past_key_value=past_key_value,
522
+ output_attentions=output_attentions,
523
+ use_cache=use_cache,
524
+ )
525
+ hidden_states = residual + hidden_states
526
+
527
+ # Fully Connected
528
+ residual = hidden_states
529
+ hidden_states = self.post_attention_layernorm(hidden_states)
530
+ hidden_states = self.mlp(hidden_states)
531
+ hidden_states = residual + hidden_states
532
+
533
+ outputs = (hidden_states,)
534
+
535
+ if output_attentions:
536
+ outputs += (self_attn_weights,)
537
+
538
+ if use_cache:
539
+ outputs += (present_key_value,)
540
+
541
+ return outputs
542
+
543
+
544
+ class StableLMEpochPreTrainedModel(PreTrainedModel):
545
+ """An abstract class to handle weights initialization and a simple interface
546
+ for downloading and loading pretrained models.
547
+ """
548
+
549
+ config_class = StableLMEpochConfig
550
+ base_model_prefix = "transformer"
551
+ supports_gradient_checkpointing = True
552
+ _no_split_modules = ["DecoderLayer"]
553
+ _skip_keys_device_placement = "past_key_values"
554
+ _supports_flash_attn_2 = True
555
+
556
+ def _init_weights(self, module: nn.Module):
557
+ """Initialize the weights"""
558
+ if isinstance(module, nn.Linear):
559
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
560
+ if module.bias is not None:
561
+ module.bias.data.zero_()
562
+ elif isinstance(module, nn.Embedding):
563
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
564
+ if module.padding_idx is not None:
565
+ module.weight.data[module.padding_idx].zero_()
566
+ elif isinstance(module, nn.LayerNorm):
567
+ module.bias.data.zero_()
568
+ module.weight.data.fill_(1.0)
569
+
570
+ def _set_gradient_checkpointing(self, module: nn.Module, value=False):
571
+ if isinstance(module, StableLMEpochModel):
572
+ module.gradient_checkpointing = value
573
+
574
+
575
+ class StableLMEpochModel(StableLMEpochPreTrainedModel):
576
+ def __init__(self, config: StableLMEpochConfig):
577
+ super().__init__(config)
578
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, config.pad_token_id)
579
+ self.layers = nn.ModuleList([DecoderLayer(config) for _ in range(config.num_hidden_layers)])
580
+ self.norm = nn.LayerNorm(config.hidden_size, eps=config.norm_eps)
581
+
582
+ self._use_flash_attention_2 = config._attn_implementation == "flash_attention_2"
583
+ self.gradient_checkpointing = False
584
+ # Initialize weights and apply final processing
585
+ self.post_init()
586
+
587
+ def get_input_embeddings(self):
588
+ return self.embed_tokens
589
+
590
+ def set_input_embeddings(self, value: nn.Module):
591
+ self.embed_tokens = value
592
+
593
+ # Copied from transformers.models.bart.modeling_bart.BartDecoder._prepare_decoder_attention_mask
594
+ def _prepare_decoder_attention_mask(
595
+ self,
596
+ attention_mask: torch.Tensor,
597
+ input_shape: torch.Size,
598
+ inputs_embeds: torch.Tensor,
599
+ past_key_values_length: int,
600
+ ):
601
+ # Create causal mask
602
+ # [batch_size, seq_len] -> [batch_size, 1, tgt_seq_len, src_seq_len]
603
+ combined_attention_mask = None
604
+ if input_shape[-1] > 1:
605
+ combined_attention_mask = _make_causal_mask(
606
+ input_shape,
607
+ inputs_embeds.dtype,
608
+ device=inputs_embeds.device,
609
+ past_key_values_length=past_key_values_length,
610
+ )
611
+
612
+ if attention_mask is not None:
613
+ # [batch_size, seq_len] -> [batch_size, 1, tgt_seq_len, src_seq_len]
614
+ expanded_attn_mask = _expand_mask(
615
+ attention_mask, inputs_embeds.dtype, tgt_len=input_shape[-1]
616
+ ).to(inputs_embeds.device)
617
+ combined_attention_mask = expanded_attn_mask if combined_attention_mask is None else expanded_attn_mask + combined_attention_mask
618
+
619
+ return combined_attention_mask
620
+
621
+ def forward(
622
+ self,
623
+ input_ids: Optional[torch.LongTensor] = None,
624
+ attention_mask: Optional[torch.FloatTensor] = None,
625
+ position_ids: Optional[torch.LongTensor] = None,
626
+ past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
627
+ inputs_embeds: Optional[torch.FloatTensor] = None,
628
+ use_cache: Optional[bool] = None,
629
+ output_attentions: Optional[bool] = None,
630
+ output_hidden_states: Optional[bool] = None,
631
+ return_dict: Optional[bool] = None,
632
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
633
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
634
+ output_hidden_states = output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
635
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
636
+
637
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
638
+
639
+ # Retrieve input_ids and inputs_embeds
640
+ if input_ids is not None and inputs_embeds is not None:
641
+ raise ValueError(
642
+ "You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time"
643
+ )
644
+ elif input_ids is not None:
645
+ batch_size, seq_length = input_ids.shape
646
+ elif inputs_embeds is not None:
647
+ batch_size, seq_length, _ = inputs_embeds.shape
648
+ else:
649
+ raise ValueError(
650
+ "You have to specify either decoder_input_ids or decoder_inputs_embeds"
651
+ )
652
+
653
+ seq_length_with_past = seq_length
654
+ past_key_values_length = 0
655
+
656
+ if position_ids is None:
657
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
658
+ position_ids = torch.arange(
659
+ past_key_values_length,
660
+ seq_length + past_key_values_length,
661
+ dtype=torch.long,
662
+ device=device,
663
+ )
664
+ position_ids = position_ids.unsqueeze(0).view(-1, seq_length)
665
+ else:
666
+ position_ids = position_ids.view(-1, seq_length).long()
667
+
668
+ if inputs_embeds is None:
669
+ inputs_embeds = self.embed_tokens(input_ids)
670
+ # Embed positions
671
+ if self._use_flash_attention_2:
672
+ # 2d mask is passed through the layers
673
+ attention_mask = attention_mask if (attention_mask is not None and 0 in attention_mask) else None
674
+ else:
675
+ if attention_mask is None:
676
+ attention_mask = torch.ones(
677
+ (batch_size, seq_length_with_past),
678
+ dtype=torch.bool,
679
+ device=inputs_embeds.device,
680
+ )
681
+ attention_mask = self._prepare_decoder_attention_mask(
682
+ attention_mask,
683
+ (batch_size, seq_length),
684
+ inputs_embeds,
685
+ past_key_values_length,
686
+ )
687
+
688
+ hidden_states = inputs_embeds
689
+
690
+ if self.gradient_checkpointing and self.training:
691
+ if use_cache:
692
+ logger.warning(
693
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
694
+ )
695
+ use_cache = False
696
+
697
+ # Decoder layers
698
+ all_hidden_states = () if output_hidden_states else None
699
+ all_self_attns = () if output_attentions else None
700
+ next_decoder_cache = () if use_cache else None
701
+
702
+ for idx, decoder_layer in enumerate(self.layers):
703
+ if output_hidden_states:
704
+ all_hidden_states += (hidden_states,)
705
+
706
+ past_key_value = (
707
+ past_key_values[idx] if past_key_values is not None else None
708
+ )
709
+
710
+ if self.gradient_checkpointing and self.training:
711
+
712
+ def create_custom_forward(module):
713
+ def custom_forward(*inputs):
714
+ # None for past_key_value
715
+ return module(*inputs, past_key_value, output_attentions)
716
+
717
+ return custom_forward
718
+
719
+ layer_outputs = torch.utils.checkpoint.checkpoint(
720
+ create_custom_forward(decoder_layer),
721
+ hidden_states,
722
+ attention_mask,
723
+ position_ids,
724
+ )
725
+ else:
726
+ layer_outputs = decoder_layer(
727
+ hidden_states,
728
+ attention_mask=attention_mask,
729
+ position_ids=position_ids,
730
+ past_key_value=past_key_value,
731
+ output_attentions=output_attentions,
732
+ use_cache=use_cache,
733
+ )
734
+
735
+ hidden_states = layer_outputs[0]
736
+
737
+ if use_cache:
738
+ next_decoder_cache += (layer_outputs[2 if output_attentions else 1],)
739
+
740
+ if output_attentions:
741
+ all_self_attns += (layer_outputs[1],)
742
+
743
+ hidden_states = self.norm(hidden_states)
744
+
745
+ # Add hidden states from the last decoder layer
746
+ if output_hidden_states:
747
+ all_hidden_states += (hidden_states,)
748
+
749
+ next_cache = next_decoder_cache if use_cache else None
750
+ if not return_dict:
751
+ return tuple(
752
+ v
753
+ for v in [hidden_states, next_cache, all_hidden_states, all_self_attns]
754
+ if v is not None
755
+ )
756
+ return BaseModelOutputWithPast(
757
+ last_hidden_state=hidden_states,
758
+ past_key_values=next_cache,
759
+ hidden_states=all_hidden_states,
760
+ attentions=all_self_attns,
761
+ )
762
+
763
+
764
+ class StableLMEpochForCausalLM(StableLMEpochPreTrainedModel):
765
+ _tied_weights_keys = ["lm_head.weight"]
766
+
767
+ def __init__(self, config: StableLMEpochConfig):
768
+ super().__init__(config)
769
+
770
+ self.model = StableLMEpochModel(config)
771
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
772
+
773
+ # Initialize weights and apply final processing
774
+ self.post_init()
775
+
776
+ def get_input_embeddings(self):
777
+ return self.model.embed_tokens
778
+
779
+ def set_input_embeddings(self, value):
780
+ self.model.embed_tokens = value
781
+
782
+ def get_output_embeddings(self):
783
+ return self.lm_head
784
+
785
+ def set_output_embeddings(self, new_embeddings: nn.Module):
786
+ self.lm_head = new_embeddings
787
+
788
+ def get_decoder(self):
789
+ return self.model
790
+
791
+ def set_decoder(self, decoder):
792
+ self.model = decoder
793
+
794
+ def forward(
795
+ self,
796
+ input_ids: Optional[torch.LongTensor] = None,
797
+ attention_mask: Optional[torch.FloatTensor] = None,
798
+ position_ids: Optional[torch.LongTensor] = None,
799
+ past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
800
+ inputs_embeds: Optional[torch.FloatTensor] = None,
801
+ labels: Optional[torch.LongTensor] = None,
802
+ use_cache: Optional[bool] = None,
803
+ output_attentions: Optional[bool] = None,
804
+ output_hidden_states: Optional[bool] = None,
805
+ return_dict: Optional[bool] = None,
806
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
807
+ output_attentions = (
808
+ output_attentions
809
+ if output_attentions is not None
810
+ else self.config.output_attentions
811
+ )
812
+ output_hidden_states = (
813
+ output_hidden_states
814
+ if output_hidden_states is not None
815
+ else self.config.output_hidden_states
816
+ )
817
+ return_dict = (
818
+ return_dict if return_dict is not None else self.config.use_return_dict
819
+ )
820
+
821
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
822
+ outputs = self.model(
823
+ input_ids,
824
+ attention_mask=attention_mask,
825
+ position_ids=position_ids,
826
+ past_key_values=past_key_values,
827
+ inputs_embeds=inputs_embeds,
828
+ use_cache=use_cache,
829
+ output_attentions=output_attentions,
830
+ output_hidden_states=output_hidden_states,
831
+ return_dict=return_dict,
832
+ )
833
+
834
+ hidden_states = outputs[0]
835
+ logits = self.lm_head(hidden_states).float()
836
+
837
+ loss = None
838
+ if labels is not None:
839
+ # Shift so that tokens < n predict n
840
+ shift_logits = logits[..., :-1, :].contiguous()
841
+ shift_labels = labels[..., 1:].contiguous()
842
+ # Flatten the tokens
843
+ loss_fct = CrossEntropyLoss()
844
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
845
+ shift_labels = shift_labels.view(-1)
846
+ # Enable model parallelism
847
+ shift_labels = shift_labels.to(shift_logits.device)
848
+ loss = loss_fct(shift_logits, shift_labels)
849
+
850
+ if not return_dict:
851
+ output = (logits,) + outputs[1:]
852
+ return (loss,) + output if loss is not None else output
853
+
854
+ return CausalLMOutputWithPast(
855
+ loss=loss,
856
+ logits=logits,
857
+ past_key_values=outputs.past_key_values,
858
+ hidden_states=outputs.hidden_states,
859
+ attentions=outputs.attentions,
860
+ )
861
+
862
+ def prepare_inputs_for_generation(
863
+ self,
864
+ input_ids,
865
+ past_key_values: Optional[torch.Tensor] = None,
866
+ attention_mask: Optional[torch.Tensor] = None,
867
+ inputs_embeds: Optional[torch.Tensor] = None,
868
+ **kwargs,
869
+ ):
870
+ # Trim decoder_input_ids if past is used
871
+ if past_key_values is not None:
872
+ past_length = past_key_values[0][0].shape[2]
873
+
874
+ # Some generation methods already pass only the last input ID
875
+ if input_ids.shape[1] > past_length:
876
+ remove_prefix_length = past_length
877
+ else:
878
+ # Default to old behavior: keep only final ID
879
+ remove_prefix_length = input_ids.shape[1] - 1
880
+
881
+ input_ids = input_ids[:, remove_prefix_length:]
882
+
883
+ position_ids = kwargs.get("position_ids", None)
884
+ if attention_mask is not None and position_ids is None:
885
+ # Create position_ids on the fly for batch generation
886
+ position_ids = attention_mask.long().cumsum(-1) - 1
887
+ position_ids.masked_fill_(attention_mask == 0, 1)
888
+ if past_key_values:
889
+ position_ids = position_ids[:, -1].unsqueeze(-1)
890
+
891
+ # If `inputs_embeds` are passed, we only want to use them in the 1st generation step
892
+ if inputs_embeds is not None and past_key_values is None:
893
+ model_inputs = {"inputs_embeds": inputs_embeds}
894
+ else:
895
+ model_inputs = {"input_ids": input_ids}
896
+
897
+ model_inputs.update(
898
+ {
899
+ "attention_mask": attention_mask,
900
+ "past_key_values": past_key_values,
901
+ "use_cache": kwargs.get("use_cache"),
902
+ "position_ids": position_ids,
903
+ }
904
+ )
905
+ return model_inputs
906
+
907
+ @staticmethod
908
+ def _reorder_cache(past_key_values, beam_idx):
909
+ reordered_past = ()
910
+ for layer_past in past_key_values:
911
+ reordered_past += (
912
+ tuple(
913
+ past_state.index_select(0, beam_idx.to(past_state.device))
914
+ for past_state in layer_past
915
+ ),
916
+ )
917
+ return reordered_past
918
+
919
+
920
+ StableLMEpochConfig.register_for_auto_class()
921
+ StableLMEpochForCausalLM.register_for_auto_class("AutoModelForCausalLM")