NobodyExistsOnTheInternet commited on
Commit
a2f1254
1 Parent(s): 67e342a

Delete modeling_mixformer_sequential.py

Browse files
Files changed (1) hide show
  1. modeling_mixformer_sequential.py +0 -935
modeling_mixformer_sequential.py DELETED
@@ -1,935 +0,0 @@
1
- # Copyright (c) Microsoft Corporation.
2
- # Licensed under the MIT license.
3
- #
4
- # BSD 3-Clause License
5
- #
6
- # Copyright (c) 2022, Tri Dao, trid@cs.stanford.edu.
7
- # All rights reserved.
8
- #
9
- # Redistribution and use in source and binary forms, with or without
10
- # modification, are permitted provided that the following conditions are met:
11
- #
12
- # * Redistributions of source code must retain the above copyright notice, this
13
- # list of conditions and the following disclaimer.
14
- #
15
- # * Redistributions in binary form must reproduce the above copyright notice,
16
- # this list of conditions and the following disclaimer in the documentation
17
- # and/or other materials provided with the distribution.
18
- #
19
- # * Neither the name of the copyright holder nor the names of its
20
- # contributors may be used to endorse or promote products derived from
21
- # this software without specific prior written permission.
22
- #
23
- # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
24
- # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
25
- # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
26
- # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
27
- # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
28
- # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
29
- # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
30
- # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
31
- # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
32
- # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
33
-
34
- from __future__ import annotations
35
-
36
- import math
37
- from typing import Any, Dict, Optional, Tuple, Union
38
- from dataclasses import dataclass, field
39
-
40
- import torch
41
- import torch.nn as nn
42
-
43
- from einops import rearrange, repeat
44
- from transformers.activations import ACT2FN
45
- from transformers import PretrainedConfig, PreTrainedModel
46
- from transformers.modeling_outputs import CausalLMOutputWithPast
47
-
48
- from .configuration_mixformer_sequential import MixFormerSequentialConfig
49
-
50
-
51
- try:
52
- from flash_attn.bert_padding import pad_input, unpad_input
53
- from flash_attn.layers.rotary import RotaryEmbedding as FlashRotaryEmbedding
54
- from flash_attn.modules.mha import FlashCrossAttention, FlashSelfAttention
55
- from flash_attn.ops.fused_dense import FusedDense
56
- except:
57
- pad_input, unpad_input = None, None
58
- FlashRotaryEmbedding = None
59
- FlashSelfAttention, FlashCrossAttention = None, None
60
- FusedDense = None
61
-
62
-
63
- @dataclass
64
- class InferenceParams:
65
- """Inference parameters passed to model to efficiently calculate
66
- and store context during inference.
67
-
68
- Reference:
69
- https://github.com/Dao-AILab/flash-attention/blob/main/flash_attn/utils/generation.py.
70
-
71
- Args:
72
- max_seqlen: Maximum sequence length.
73
- max_batch_size: Maximum batch size.
74
- seqlen_offset: Sequence length offset.
75
- batch_size_offset: Batch size offset.
76
- key_value_memory_dict: Key value memory dictionary.
77
- lengths_per_sample: Lengths per sample.
78
-
79
- """
80
-
81
- max_seqlen: int = field(metadata={"help": "Maximum sequence length."})
82
-
83
- max_batch_size: int = field(metadata={"help": "Maximum batch size."})
84
-
85
- seqlen_offset: int = field(default=0, metadata={"help": "Sequence length offset."})
86
-
87
- batch_size_offset: int = field(default=0, metadata={"help": "Batch size offset."})
88
-
89
- key_value_memory_dict: Dict[str, Any] = field(
90
- default_factory=dict, metadata={"help": "Key value memory dictionary."}
91
- )
92
-
93
- lengths_per_sample: torch.Tensor = field(default=None, metadata={"help": "Lengths per sample."})
94
-
95
-
96
- class Embedding(nn.Module):
97
- """Token embedding with dropout."""
98
-
99
- def __init__(self, config: PretrainedConfig) -> None:
100
- super().__init__()
101
-
102
- self.wte = nn.Embedding(config.vocab_size, config.n_embd)
103
- self.drop = nn.Dropout(config.embd_pdrop)
104
-
105
- def forward(self, input_ids: torch.LongTensor) -> torch.FloatTensor:
106
- input_shape = input_ids.size()
107
- input_ids = input_ids.view(-1, input_shape[-1])
108
-
109
- hidden_states = self.wte(input_ids)
110
- hidden_states = self.drop(hidden_states)
111
-
112
- return hidden_states
113
-
114
-
115
- def _apply_rotary_emb(
116
- x: torch.FloatTensor,
117
- cos: torch.FloatTensor,
118
- sin: torch.FloatTensor,
119
- ) -> torch.FloatTensor:
120
- _, seqlen, _, head_dim = x.shape
121
- rotary_seqlen, rotary_dim = cos.shape
122
- rotary_dim *= 2
123
-
124
- assert rotary_dim <= head_dim
125
- assert seqlen <= rotary_seqlen
126
- assert cos.shape == sin.shape == (rotary_seqlen, rotary_dim // 2)
127
-
128
- x_rot = x[:, :, :, :rotary_dim]
129
- x_pass = x[:, :, :, rotary_dim:]
130
-
131
- x1, x2 = x_rot.chunk(2, dim=-1)
132
- c, s = rearrange(cos[:seqlen], "s d -> s 1 d"), rearrange(sin[:seqlen], "s d -> s 1 d")
133
- x1, x2, c, s = [t.to(dtype=torch.float32) for t in [x1, x2, c, s]]
134
-
135
- x_rot = torch.cat([x1 * c - x2 * s, x1 * s + x2 * c], axis=-1).to(x.dtype)
136
-
137
- return torch.cat([x_rot, x_pass], axis=-1)
138
-
139
-
140
- def _apply_rotary_emb_kv(
141
- kv: torch.FloatTensor,
142
- cos: torch.FloatTensor,
143
- sin: torch.FloatTensor,
144
- cos_k: Optional[torch.FloatTensor] = None,
145
- sin_k: Optional[torch.FloatTensor] = None,
146
- ) -> torch.FloatTensor:
147
- _, seqlen, two, _, head_dim = kv.shape
148
- assert two == 2
149
-
150
- rotary_seqlen, rotary_dim = cos.shape
151
- rotary_dim *= 2
152
- assert rotary_dim <= head_dim
153
- assert seqlen <= rotary_seqlen
154
- assert cos.shape == sin.shape == (rotary_seqlen, rotary_dim // 2)
155
-
156
- k_rot = kv[:, :, 0, :, :rotary_dim]
157
- k_pass = kv[:, :, 0, :, rotary_dim:]
158
-
159
- k1, k2 = k_rot.chunk(2, dim=-1)
160
- c, s = rearrange(cos[:seqlen], "s d -> s 1 d"), rearrange(sin[:seqlen], "s d -> s 1 d")
161
- k1, k2, c, s = [t.to(dtype=torch.float32) for t in [k1, k2, c, s]]
162
-
163
- k_rot = torch.cat([k1 * c - k2 * s, k1 * s + k2 * c], axis=-1).to(kv.dtype)
164
-
165
- return torch.cat(
166
- [
167
- torch.cat([k_rot, k_pass], axis=-1).unsqueeze(2),
168
- kv[:, :, 1:2, :, :],
169
- ],
170
- axis=2,
171
- )
172
-
173
-
174
- def _apply_rotary_emb_qkv(
175
- qkv: torch.FloatTensor,
176
- cos: torch.FloatTensor,
177
- sin: torch.FloatTensor,
178
- cos_k: Optional[torch.FloatTensor] = None,
179
- sin_k: Optional[torch.FloatTensor] = None,
180
- ) -> torch.FloatTensor:
181
- _, seqlen, three, _, head_dim = qkv.shape
182
- assert three == 3
183
-
184
- rotary_seqlen, rotary_dim = cos.shape
185
- rotary_dim *= 2
186
- assert rotary_dim <= head_dim
187
- assert seqlen <= rotary_seqlen
188
- assert cos.shape == sin.shape == (rotary_seqlen, rotary_dim // 2)
189
-
190
- q_rot = qkv[:, :, 0, :, :rotary_dim]
191
- q_pass = qkv[:, :, 0, :, rotary_dim:]
192
-
193
- k_rot = qkv[:, :, 1, :, :rotary_dim]
194
- k_pass = qkv[:, :, 1, :, rotary_dim:]
195
-
196
- q1, q2 = q_rot.chunk(2, dim=-1)
197
- k1, k2 = k_rot.chunk(2, dim=-1)
198
- c, s = rearrange(cos[:seqlen], "s d -> s 1 d"), rearrange(sin[:seqlen], "s d -> s 1 d")
199
- q1, q2, k1, k2, c, s = [t.to(dtype=torch.float32) for t in [q1, q2, k1, k2, c, s]]
200
-
201
- q_rot = torch.cat([q1 * c - q2 * s, q1 * s + q2 * c], axis=-1).to(qkv.dtype)
202
- k_rot = torch.cat([k1 * c - k2 * s, k1 * s + k2 * c], axis=-1).to(qkv.dtype)
203
-
204
- return torch.cat(
205
- [
206
- torch.cat([q_rot, q_pass], axis=-1).unsqueeze(2),
207
- torch.cat([k_rot, k_pass], axis=-1).unsqueeze(2),
208
- qkv[:, :, 2:3, :, :],
209
- ],
210
- axis=2,
211
- )
212
-
213
-
214
- class RotaryEmbedding(nn.Module):
215
- """Rotary positional embedding (RoPE).
216
-
217
- Reference:
218
- RoFormer: Enhanced Transformer with Rotary Position Embedding.
219
- https://arxiv.org/pdf/2104.09864.pdf.
220
-
221
- """
222
-
223
- def __init__(
224
- self,
225
- dim: int,
226
- base: int = 10000,
227
- scale_base: Optional[float] = None,
228
- pos_idx_in_fp32: bool = True,
229
- device: Optional[str] = None,
230
- **kwargs,
231
- ) -> None:
232
- super().__init__()
233
-
234
- if scale_base is not None:
235
- raise NotImplementedError
236
-
237
- self.dim = dim
238
- self.base = float(base)
239
- self.scale_base = scale_base
240
- self.pos_idx_in_fp32 = pos_idx_in_fp32
241
- self.device = device
242
-
243
- # Generate and save the inverse frequency buffer (non-trainable)
244
- inv_freq = self._compute_inv_freq(device)
245
- self.register_buffer("inv_freq", inv_freq, persistent=False)
246
-
247
- # Generate and save the scale buffer (non-trainable)
248
- scale = (
249
- (torch.arange(0, dim, 2, device=device, dtype=torch.float32) + 0.4 * dim) / (1.4 * dim)
250
- if scale_base is not None
251
- else None
252
- )
253
- self.register_buffer("scale", scale, persistent=False)
254
-
255
- self._seq_len_cached = 0
256
- self._cos_cached = None
257
- self._sin_cached = None
258
- self._cos_k_cached = None
259
- self._sin_k_cached = None
260
-
261
- def _compute_inv_freq(self, device: Optional[str] = None) -> torch.FloatTensor:
262
- return 1.0 / (self.base ** (torch.arange(0, self.dim, 2, device=device, dtype=torch.float32) / self.dim))
263
-
264
- def _update_cos_sin_cache(
265
- self, seqlen: int, device: Optional[str] = None, dtype: Optional[torch.dtype] = None
266
- ) -> None:
267
- # Reset the tables if sequence length has been chaned, if we are on a
268
- # new device or if we are switching from inference mode to training
269
- if (
270
- seqlen > self._seq_len_cached
271
- or self._cos_cached is None
272
- or self._cos_cached.device != device
273
- or self._cos_cached.dtype != dtype
274
- or (self.training and self._cos_cached.is_inference())
275
- ):
276
- self._seq_len_cached = seqlen
277
-
278
- # fp32 is preferred since the output of `torch.arange` can be quite large
279
- # and bf16 would lose a lot of precision
280
- if self.pos_idx_in_fp32:
281
- t = torch.arange(seqlen, device=device, dtype=torch.float32)
282
- if self.inv_freq.dtype != torch.float32:
283
- inv_freq = self._compute_inv_freq(device=device)
284
- else:
285
- inv_freq = self.inv_freq
286
- else:
287
- t = torch.arange(seqlen, device=device, dtype=self.inv_freq.dtype)
288
- inv_freq = self.inv_freq
289
-
290
- # `torch.outer` is preferred since `torch.einsum` converts from fp32 to fp16 if used with AMP
291
- freqs = torch.outer(t, inv_freq)
292
- if self.scale is None:
293
- self._cos_cached = torch.cos(freqs).to(dtype)
294
- self._sin_cached = torch.sin(freqs).to(dtype)
295
- else:
296
- power = (
297
- torch.arange(seqlen, dtype=self.scale.dtype, device=self.scale.device) - seqlen // 2
298
- ) / self.scale_base
299
- scale = self.scale.to(device=power.device) ** rearrange(power, "s -> s 1")
300
-
301
- # Force the scale multiplication to happen in fp32
302
- self._cos_cached = (torch.cos(freqs) * scale).to(dtype)
303
- self._sin_cached = (torch.sin(freqs) * scale).to(dtype)
304
- self._cos_k_cached = (torch.cos(freqs) / scale).to(dtype)
305
- self._sin_k_cached = (torch.sin(freqs) / scale).to(dtype)
306
-
307
- def forward(
308
- self,
309
- qkv: torch.Tensor,
310
- kv: Optional[torch.Tensor] = None,
311
- seqlen_offset: int = 0,
312
- max_seqlen: Optional[int] = None,
313
- ) -> Tuple[torch.Tensor, torch.Tensor]:
314
- seqlen = qkv.shape[1]
315
-
316
- if max_seqlen is not None:
317
- self._update_cos_sin_cache(max_seqlen, device=qkv.device, dtype=qkv.dtype)
318
- else:
319
- self._update_cos_sin_cache(seqlen + seqlen_offset, device=qkv.device, dtype=qkv.dtype)
320
-
321
- if kv is None:
322
- return _apply_rotary_emb_qkv(qkv, self._cos_cached[seqlen_offset:], self._sin_cached[seqlen_offset:])
323
- else:
324
- q = _apply_rotary_emb(qkv, self._cos_cached[seqlen_offset:], self._sin_cached[seqlen_offset:])
325
- kv = _apply_rotary_emb_kv(kv, self._cos_cached[seqlen_offset:], self._sin_cached[seqlen_offset:])
326
-
327
- return q, kv
328
-
329
-
330
- class MLP(nn.Module):
331
- """Multi-Layer Perceptron.
332
-
333
- Reference:
334
- Attention Is All You Need.
335
- https://arxiv.org/pdf/1706.03762.pdf.
336
-
337
- """
338
-
339
- def __init__(self, config: PretrainedConfig, n_inner: Optional[int] = None, act_fn: Optional[str] = None) -> None:
340
- super().__init__()
341
-
342
- act_fn = config.activation_function if act_fn is None else act_fn
343
- assert act_fn in ACT2FN.keys(), f"`act_fn` must be one of: {ACT2FN.keys()}."
344
-
345
- n_inner = getattr(config, "n_inner", None) if n_inner is None else n_inner
346
- n_inner = n_inner if n_inner is not None else 4 * config.n_embd
347
-
348
- self.fc1 = nn.Linear(config.n_embd, n_inner)
349
- self.fc2 = nn.Linear(n_inner, config.n_embd)
350
- self.act = ACT2FN[act_fn]
351
-
352
- def forward(self, hidden_states: torch.FloatTensor) -> torch.FloatTensor:
353
- hidden_states = self.fc1(hidden_states)
354
- hidden_states = self.act(hidden_states)
355
- hidden_states = self.fc2(hidden_states)
356
-
357
- return hidden_states
358
-
359
-
360
- class SelfAttention(nn.Module):
361
- """Self-attention layer (compatible with PyTorch).
362
- Reference:
363
- https://github.com/Dao-AILab/flash-attention/blob/main/flash_attn/modules/mha.py.
364
- """
365
-
366
- def __init__(
367
- self,
368
- causal: bool = True,
369
- softmax_scale: Optional[float] = None,
370
- attention_dropout: float = 0.0,
371
- ) -> None:
372
- super().__init__()
373
-
374
- self.causal = causal
375
- self.softmax_scale = softmax_scale
376
- self.drop = nn.Dropout(attention_dropout)
377
-
378
- def forward(
379
- self,
380
- qkv: torch.FloatTensor,
381
- causal: bool = None,
382
- key_padding_mask: Optional[torch.BoolTensor] = None,
383
- **kwargs,
384
- ) -> torch.FloatTensor:
385
- batch_size, seqlen = qkv.shape[0], qkv.shape[1]
386
- q, k, v = qkv.unbind(dim=2)
387
-
388
- causal = self.causal if causal is None else causal
389
- softmax_scale = self.softmax_scale or 1.0 / math.sqrt(q.shape[-1])
390
-
391
- scores = torch.einsum("bthd,bshd->bhts", q, k * softmax_scale)
392
-
393
- if key_padding_mask is not None:
394
- padding_mask = torch.full((batch_size, seqlen), -10000.0, dtype=scores.dtype, device=scores.device)
395
- padding_mask.masked_fill_(key_padding_mask, 0.0)
396
-
397
- scores = scores + rearrange(padding_mask, "b s -> b 1 1 s")
398
-
399
- if causal:
400
- causal_mask = torch.triu(torch.full((seqlen, seqlen), -10000.0, device=scores.device), 1)
401
- scores = scores + causal_mask.to(dtype=scores.dtype)
402
-
403
- attention = torch.softmax(scores, dim=-1, dtype=v.dtype)
404
- attention = self.drop(attention)
405
-
406
- output = torch.einsum("bhts,bshd->bthd", attention, v)
407
-
408
- return output
409
-
410
-
411
- class CrossAttention(nn.Module):
412
- """Cross-attention layer (compatible with PyTorch).
413
- Reference:
414
- https://github.com/Dao-AILab/flash-attention/blob/main/flash_attn/modules/mha.py.
415
- """
416
-
417
- def __init__(
418
- self,
419
- causal: bool = True,
420
- softmax_scale: Optional[float] = None,
421
- attention_dropout: float = 0.0,
422
- ) -> None:
423
- super().__init__()
424
-
425
- self.causal = causal
426
- self.softmax_scale = softmax_scale
427
- self.drop = nn.Dropout(attention_dropout)
428
-
429
- def forward(
430
- self,
431
- q: torch.FloatTensor,
432
- kv: torch.FloatTensor,
433
- causal: bool = None,
434
- key_padding_mask: Optional[torch.BoolTensor] = None,
435
- **kwargs,
436
- ) -> torch.FloatTensor:
437
- batch_size, seqlen_q = q.shape[0], q.shape[1]
438
- seqlen_k = kv.shape[1]
439
-
440
- if kv.shape[3] != q.shape[2]:
441
- kv = repeat(kv, "... hkv d -> ... (hkv g) d", g=q.shape[2] // kv.shape[3])
442
- k, v = kv.unbind(dim=2)
443
-
444
- causal = self.causal if causal is None else causal
445
- softmax_scale = self.softmax_scale or 1.0 / math.sqrt(q.shape[-1])
446
-
447
- scores = torch.einsum("bthd,bshd->bhts", q, k * softmax_scale)
448
-
449
- if key_padding_mask is not None:
450
- padding_mask = torch.full(
451
- (batch_size, seqlen_k),
452
- -10000.0,
453
- dtype=scores.dtype,
454
- device=scores.device,
455
- )
456
- padding_mask.masked_fill_(key_padding_mask, 0.0)
457
-
458
- scores = scores + rearrange(padding_mask, "b s -> b 1 1 s")
459
-
460
- if causal:
461
- rows = rearrange(torch.arange(seqlen_q, device=q.device, dtype=torch.long), "s -> s 1")
462
- cols = torch.arange(seqlen_k, device=k.device, dtype=torch.long)
463
- causal_mask = cols > rows + seqlen_k - seqlen_q
464
-
465
- scores = scores.masked_fill(causal_mask, -10000.0)
466
-
467
- attention = torch.softmax(scores, dim=-1, dtype=v.dtype)
468
- attention = self.drop(attention)
469
-
470
- output = torch.einsum("bhts,bshd->bthd", attention, v)
471
-
472
- return output
473
-
474
-
475
- def _find_mha_dims(
476
- config: PretrainedConfig,
477
- n_head: Optional[int] = None,
478
- n_head_kv: Optional[int] = None,
479
- head_dim: Optional[int] = None,
480
- ) -> Tuple[int, int]:
481
- assert all(
482
- hasattr(config, attr) for attr in ["n_embd", "n_head"]
483
- ), "`config` must have `n_embd` and `n_head` attributes."
484
-
485
- if head_dim is None:
486
- assert (
487
- config.n_embd % config.n_head == 0
488
- ), f"Hidden size ({config.n_embd}) must be divisible by the number of heads ({config.n_head})."
489
-
490
- if n_head is None and head_dim is None:
491
- head_dim = config.n_embd // config.n_head
492
- n_head = config.n_head
493
- elif n_head is None or head_dim is None:
494
- raise ValueError("`n_head` and `head_dim` must be both specified or `None`.")
495
-
496
- if n_head_kv is None:
497
- n_head_kv = getattr(config, "n_head_kv", None) or n_head
498
- assert n_head % n_head_kv == 0, "`n_head` must be divisible by `n_head_kv`."
499
-
500
- return n_head, n_head_kv, head_dim
501
-
502
-
503
- def _update_kv_cache(kv: torch.FloatTensor, inference_params: InferenceParams, layer_idx: int) -> torch.FloatTensor:
504
- num_heads, head_dim = kv.shape[-2:]
505
-
506
- if layer_idx not in inference_params.key_value_memory_dict:
507
- kv_cache = torch.empty(
508
- inference_params.max_batch_size,
509
- inference_params.max_seqlen,
510
- 2,
511
- num_heads,
512
- head_dim,
513
- dtype=kv.dtype,
514
- device=kv.device,
515
- )
516
- inference_params.key_value_memory_dict[layer_idx] = kv_cache
517
- else:
518
- kv_cache = inference_params.key_value_memory_dict[layer_idx]
519
-
520
- batch_start = inference_params.batch_size_offset
521
- batch_end = batch_start + kv.shape[0]
522
- assert batch_end <= kv_cache.shape[0]
523
-
524
- sequence_start = inference_params.seqlen_offset
525
- sequence_end = sequence_start + kv.shape[1]
526
- assert sequence_end <= kv_cache.shape[1]
527
-
528
- assert kv_cache is not None
529
- kv_cache[batch_start:batch_end, sequence_start:sequence_end, ...] = kv
530
- kv = kv_cache[batch_start:batch_end, :sequence_end, ...]
531
-
532
- return kv
533
-
534
-
535
- class MHA(nn.Module):
536
- """Multi-head attention layer."""
537
-
538
- def __init__(
539
- self,
540
- config: PretrainedConfig,
541
- dtype: Optional[torch.dtype] = None,
542
- device: Optional[str] = None,
543
- rotary_dim: Optional[int] = None,
544
- rotary_scale_base: Optional[float] = None,
545
- n_head: Optional[int] = None,
546
- n_head_kv: Optional[int] = None,
547
- head_dim: Optional[int] = None,
548
- bias: bool = True,
549
- causal: bool = True,
550
- softmax_scale: Optional[float] = None,
551
- layer_idx: Optional[int] = None,
552
- return_residual: bool = False,
553
- checkpointing: bool = False,
554
- ) -> None:
555
- super().__init__()
556
-
557
- # Rotary embedding
558
- self.rotary_dim = rotary_dim if rotary_dim is not None else getattr(config, "rotary_dim", 0)
559
- if self.rotary_dim > 0:
560
- rotary_kwargs = {"device": device}
561
- if rotary_scale_base is not None and rotary_scale_base > 0.0:
562
- rotary_kwargs["scale_base"] = rotary_scale_base
563
-
564
- rotary_cls = FlashRotaryEmbedding if config.flash_rotary else RotaryEmbedding
565
- if rotary_cls is None:
566
- rotary_cls = RotaryEmbedding
567
- self.rotary_emb = rotary_cls(self.rotary_dim, **rotary_kwargs)
568
-
569
- # MLP
570
- self.n_head, self.n_head_kv, self.head_dim = _find_mha_dims(config, n_head=n_head, n_head_kv=n_head_kv, head_dim=head_dim)
571
- op_size = self.head_dim * (self.n_head + 2 * self.n_head_kv)
572
- hidden_size = config.n_embd
573
-
574
- linear_cls = FusedDense if config.fused_dense else nn.Linear
575
- if linear_cls is None:
576
- linear_cls = nn.Linear
577
-
578
- self.Wqkv = linear_cls(hidden_size, op_size, bias=bias, device=device, dtype=dtype)
579
- self.out_proj = linear_cls(hidden_size, hidden_size, bias=bias, device=device, dtype=dtype)
580
-
581
- # Attention
582
- attn_cls = FlashSelfAttention if config.flash_attn else SelfAttention
583
- if attn_cls is None:
584
- attn_cls = SelfAttention
585
-
586
- cross_attn_cls = FlashCrossAttention if config.flash_attn else CrossAttention
587
- if cross_attn_cls is None:
588
- cross_attn_cls = CrossAttention
589
-
590
- self.inner_attn = attn_cls(causal=causal, softmax_scale=softmax_scale, attention_dropout=config.attn_pdrop)
591
- self.inner_cross_attn = cross_attn_cls(
592
- causal=causal, softmax_scale=softmax_scale, attention_dropout=config.attn_pdrop
593
- )
594
-
595
- self.flash_attn = config.flash_attn and attn_cls is FlashSelfAttention
596
- self.layer_idx = layer_idx
597
- self.return_residual = return_residual
598
- self.checkpointing = checkpointing
599
-
600
- def _forward_self_attn(
601
- self, x: torch.FloatTensor, key_padding_mask: Optional[torch.BoolTensor]
602
- ) -> torch.FloatTensor:
603
- qkv = self.Wqkv(x)
604
- qkv = rearrange(qkv, "... (three h d) -> ... three h d", three=3, d=self.head_dim)
605
-
606
- if self.rotary_dim > 0:
607
- qkv = self.rotary_emb(qkv)
608
-
609
- if self.flash_attn:
610
- batch_size, seqlen = qkv.shape[0], qkv.shape[1]
611
-
612
- cu_seqlens, max_seqlen = None, None
613
- if key_padding_mask is not None:
614
- # If `key_padding_mask` is supplied, we need to unpad the input and retrieve
615
- # the `cu_seqlens` and `max_seqlen` to be used by `flash-attn`
616
- qkv, indices, cu_seqlens, max_seqlen = unpad_input(qkv, key_padding_mask)
617
-
618
- if self.checkpointing:
619
- attn_output = torch.utils.checkpoint.checkpoint(
620
- self.inner_attn, qkv, cu_seqlens=cu_seqlens, max_seqlen=max_seqlen
621
- )
622
- else:
623
- attn_output = self.inner_attn(qkv, cu_seqlens=cu_seqlens, max_seqlen=max_seqlen).to(qkv.device)
624
-
625
- # If `key_padding_mask` is supplied, we need to pad the output back to the original shape
626
- return pad_input(attn_output, indices, batch_size, seqlen) if key_padding_mask is not None else attn_output
627
-
628
- if self.checkpointing:
629
- return torch.utils.checkpoint.checkpoint(self.inner_attn, qkv, key_padding_mask=key_padding_mask)
630
-
631
- return self.inner_attn(qkv, key_padding_mask=key_padding_mask)
632
-
633
- def _forward_cross_attn(
634
- self,
635
- x: torch.FloatTensor,
636
- past_key_values: Optional[InferenceParams],
637
- key_padding_mask: Optional[torch.BoolTensor],
638
- ) -> torch.FloatTensor:
639
- batch_size = x.shape[0]
640
-
641
- qkv = self.Wqkv(x)
642
-
643
- q = qkv[..., : self.n_head * self.head_dim]
644
- q = rearrange(q, "... (h d) -> ... h d", d=self.head_dim)
645
-
646
- kv = qkv[..., self.n_head * self.head_dim :]
647
- kv = rearrange(kv, "... (two hkv d) -> ... two hkv d", two=2, d=self.head_dim)
648
-
649
- seqlen_offset = past_key_values.seqlen_offset if past_key_values is not None else 0
650
- causal = None if seqlen_offset == 0 else False
651
- if self.rotary_dim > 0:
652
- q, kv = self.rotary_emb(q, kv=kv, seqlen_offset=seqlen_offset)
653
-
654
- if past_key_values is not None:
655
- kv = _update_kv_cache(kv, past_key_values, self.layer_idx)
656
-
657
- if self.flash_attn:
658
- batch_size, seqlen_q = q.shape[0], q.shape[1]
659
- seqlen_k = kv.shape[1]
660
-
661
- cu_seqlens_q, cu_seqlens_k, max_seqlen_q, max_seqlen_k = None, None, None, None
662
- if key_padding_mask is not None:
663
- kv, _, cu_seqlens_k, max_seqlen_k = unpad_input(kv, key_padding_mask)
664
-
665
- if seqlen_q == 1:
666
- key_padding_mask = torch.ones(batch_size, 1, device=q.device)
667
- elif seqlen_q != seqlen_k:
668
- key_padding_mask = key_padding_mask[:, -seqlen_q:]
669
-
670
- q, indices_q, cu_seqlens_q, max_seqlen_q = unpad_input(q, key_padding_mask)
671
-
672
- if self.checkpointing:
673
- attn_output = torch.utils.checkpoint.checkpoint(
674
- self.inner_cross_attn,
675
- q,
676
- kv,
677
- causal=causal,
678
- cu_seqlens=cu_seqlens_q,
679
- max_seqlen=max_seqlen_q,
680
- cu_seqlens_k=cu_seqlens_k,
681
- max_seqlen_k=max_seqlen_k,
682
- )
683
- else:
684
- attn_output = self.inner_cross_attn(
685
- q,
686
- kv,
687
- causal=causal,
688
- cu_seqlens=cu_seqlens_q,
689
- max_seqlen=max_seqlen_q,
690
- cu_seqlens_k=cu_seqlens_k,
691
- max_seqlen_k=max_seqlen_k,
692
- )
693
-
694
- return (
695
- pad_input(attn_output, indices_q, batch_size, max_seqlen_q)
696
- if key_padding_mask is not None
697
- else attn_output
698
- )
699
-
700
- if self.checkpointing:
701
- return torch.utils.checkpoint.checkpoint(
702
- self.inner_cross_attn, q, kv, key_padding_mask=key_padding_mask, causal=causal
703
- )
704
-
705
- return self.inner_cross_attn(q, kv, key_padding_mask=key_padding_mask, causal=causal)
706
-
707
- def forward(
708
- self,
709
- x: torch.FloatTensor,
710
- past_key_values: Optional[InferenceParams] = None,
711
- attention_mask: Optional[Union[torch.LongTensor, torch.BoolTensor]] = None,
712
- **kwargs,
713
- ) -> Tuple[torch.FloatTensor, torch.FloatTensor]:
714
- # TODO: Need an alternative way for dynamic control flow: torch.any(~attention_mask.bool())
715
- if attention_mask is not None:
716
- attention_mask = attention_mask.bool()
717
- else:
718
- attention_mask = None
719
-
720
- # MHA
721
- if self.n_head == self.n_head_kv:
722
- if past_key_values is None:
723
- # If `past_key_values` are not supplied, we run self-attention
724
- attn_output = self._forward_self_attn(x, attention_mask)
725
- else:
726
- # If `past_key_values` are supplied, it means that we might have cached values and
727
- # could take advantage of cross-attention
728
- attn_output = self._forward_cross_attn(x, past_key_values, attention_mask)
729
- # MQA / GQA
730
- else:
731
- # Regardless of `past_key_values` being supplied or not, it always use cross-attention
732
- # because `q` and `kv` lengths might be different
733
- attn_output = self._forward_cross_attn(x, past_key_values, attention_mask)
734
-
735
- output = rearrange(attn_output, "... h d -> ... (h d)")
736
- output = self.out_proj(output)
737
-
738
- return output if not self.return_residual else (output, x)
739
-
740
-
741
- class ParallelBlock(nn.Module):
742
- """Parallel block.
743
-
744
- This block applies parallel mixer and MLP layers to the input (used in GPT-J and CodeGen).
745
-
746
- """
747
-
748
- def __init__(
749
- self,
750
- config: PretrainedConfig,
751
- block_idx: Optional[int] = None,
752
- ) -> None:
753
- super().__init__()
754
-
755
- self.ln = nn.LayerNorm(config.n_embd, eps=config.layer_norm_epsilon)
756
- self.resid_dropout = nn.Dropout(config.resid_pdrop)
757
- self.block_idx = block_idx
758
-
759
- self.mixer = MHA(config, layer_idx=block_idx)
760
- self.mlp = MLP(config)
761
-
762
- def forward(
763
- self,
764
- hidden_states: torch.FloatTensor,
765
- past_key_values: Optional[Union[torch.FloatTensor, InferenceParams]] = None,
766
- attention_mask: Optional[torch.BoolTensor] = None,
767
- **kwargs,
768
- ) -> torch.FloatTensor:
769
- residual = hidden_states
770
- hidden_states = self.ln(hidden_states)
771
-
772
- attn_outputs = self.mixer(hidden_states, past_key_values=past_key_values, attention_mask=attention_mask)
773
- if isinstance(attn_outputs, tuple):
774
- attn_outputs = attn_outputs[0]
775
-
776
- attn_outputs = self.resid_dropout(attn_outputs)
777
- feed_forward_hidden_states = self.resid_dropout(self.mlp(hidden_states))
778
-
779
- hidden_states = attn_outputs + feed_forward_hidden_states + residual
780
-
781
- return hidden_states
782
-
783
-
784
- class CausalLMHead(nn.Module):
785
- """Causal Language Modeling head.
786
-
787
- Reference:
788
- Improving Language Understanding by Generative Pre-Training.
789
- https://cdn.openai.com/research-covers/language-unsupervised/language_understanding_paper.pdf.
790
-
791
- """
792
-
793
- def __init__(self, config: PretrainedConfig) -> None:
794
- super().__init__()
795
-
796
- self.ln = nn.LayerNorm(config.n_embd, eps=config.layer_norm_epsilon)
797
- self.linear = nn.Linear(config.n_embd, config.vocab_size)
798
-
799
- def forward(self, hidden_states: torch.FloatTensor) -> torch.FloatTensor:
800
- hidden_states = self.ln(hidden_states)
801
- logits = self.linear(hidden_states).to(torch.float32)
802
-
803
- return logits
804
-
805
-
806
- class CausalLMLoss(nn.Module):
807
- """Causal Language Modeling loss.
808
-
809
- Reference:
810
- Improving Language Understanding by Generative Pre-Training.
811
- https://cdn.openai.com/research-covers/language-unsupervised/language_understanding_paper.pdf.
812
-
813
- """
814
-
815
- def __init__(self, shift_labels: bool = True) -> None:
816
- super().__init__()
817
-
818
- self.shift_labels = shift_labels
819
- self.loss_fct = nn.CrossEntropyLoss()
820
-
821
- def forward(self, logits: torch.FloatTensor, labels: torch.LongTensor) -> torch.FloatTensor:
822
- if self.shift_labels:
823
- logits = logits[..., :-1, :].contiguous()
824
- labels = labels[..., 1:].contiguous()
825
-
826
- loss = self.loss_fct(logits.view(-1, logits.size(-1)), labels.view(-1))
827
-
828
- return loss
829
-
830
-
831
- class MixFormerSequentialPreTrainedModel(PreTrainedModel):
832
- """MixFormer (sequential for DeepSpeed) pre-trained model."""
833
-
834
- config_class = MixFormerSequentialConfig
835
- base_model_prefix = "transformer"
836
- supports_gradient_checkpointing = True
837
-
838
- def __init__(self, *inputs, **kwargs) -> None:
839
- super().__init__(*inputs, **kwargs)
840
-
841
- def _init_weights(self, module: nn.Module) -> None:
842
- if isinstance(module, (nn.Linear,)):
843
- module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
844
- if module.bias is not None:
845
- module.bias.data.zero_()
846
- elif isinstance(module, nn.Embedding):
847
- module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
848
- if module.padding_idx is not None:
849
- module.weight.data[module.padding_idx].zero_()
850
- elif isinstance(module, nn.LayerNorm):
851
- if module.bias is not None:
852
- module.bias.data.zero_()
853
- module.weight.data.fill_(1.0)
854
-
855
- def prepare_inputs_for_generation(
856
- self,
857
- input_ids: torch.LongTensor,
858
- past_key_values: Optional[Union[torch.FloatTensor, InferenceParams]] = None,
859
- attention_mask: Optional[Union[torch.LongTensor, torch.BoolTensor]] = None,
860
- **kwargs,
861
- ) -> Dict[str, Any]:
862
- if past_key_values is None or not (isinstance(past_key_values, InferenceParams)):
863
- past_key_values = InferenceParams(
864
- max_seqlen=self.config.n_positions,
865
- max_batch_size=input_ids.shape[0],
866
- seqlen_offset=0,
867
- batch_size_offset=0,
868
- key_value_memory_dict={},
869
- lengths_per_sample=None,
870
- )
871
- else:
872
- # Assume that `past_key_values` has cached all tokens up to the last token in `input_ids`
873
- past_key_values.seqlen_offset = len(input_ids[0]) - 1
874
- input_ids = input_ids[:, -1].unsqueeze(-1)
875
-
876
- return {
877
- "input_ids": input_ids,
878
- "past_key_values": past_key_values,
879
- "attention_mask": attention_mask,
880
- }
881
-
882
- def _set_gradient_checkpointing(self, module: nn.Module, value: bool = False) -> None:
883
- if isinstance(module, MixFormerSequentialPreTrainedModel):
884
- module.gradient_checkpointing = value
885
-
886
-
887
- class MixFormerSequentialForCausalLM(MixFormerSequentialPreTrainedModel):
888
- """MixFormer (sequential for DeepSpeed) for Causal Language Modeling."""
889
-
890
- _keys_to_ignore_on_load_missing = [""]
891
- _keys_to_ignore_on_load_unexpected = [r"layers\.\d+\.mlp.(fc_in|fc_out)\.(weight|bias)"]
892
- _no_split_modules = ["ParallelBlock"]
893
-
894
- def __init__(self, config: MixFormerSequentialConfig) -> None:
895
- super().__init__(config)
896
-
897
- modules = [Embedding(config)]
898
- modules += [ParallelBlock(config, block_idx=i) for i in range(config.n_layer)]
899
- modules.append(CausalLMHead(config))
900
-
901
- self.layers = nn.Sequential(*modules)
902
- self.loss = CausalLMLoss()
903
-
904
- self.post_init()
905
-
906
- def get_input_embeddings(self) -> nn.Embedding:
907
- return self.layers[0].wte
908
-
909
- def set_input_embeddings(self, new_embeddings: nn.Embedding) -> None:
910
- self.layers[0].wte = new_embeddings
911
-
912
- def get_output_embeddings(self) -> nn.Linear:
913
- return self.layers[-1].linear
914
-
915
- def set_output_embeddings(self, new_embeddings: nn.Linear) -> None:
916
- self.layers[-1].linear = new_embeddings
917
-
918
- def forward(
919
- self,
920
- input_ids: torch.LongTensor,
921
- past_key_values: Optional[Union[torch.FloatTensor, InferenceParams]] = None,
922
- attention_mask: Optional[torch.BoolTensor] = None,
923
- labels: Optional[torch.LongTensor] = None,
924
- **kwargs,
925
- ) -> CausalLMOutputWithPast:
926
- hidden_layer = self.layers[0](input_ids)
927
- for module in self.layers[1:-1]:
928
- hidden_layer = module(hidden_layer, past_key_values=past_key_values, attention_mask=attention_mask)
929
- lm_logits = self.layers[-1](hidden_layer)
930
-
931
- loss = None
932
- if labels is not None:
933
- loss = self.loss(lm_logits, labels)
934
-
935
- return CausalLMOutputWithPast(loss=loss, logits=lm_logits, past_key_values=past_key_values)