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