nathanrchn commited on
Commit
0d5d7f1
1 Parent(s): 217fc2f

Upload 10 files

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