Update to new model interface.
Browse files- config.json +11 -6
- configuration_phi.py +62 -0
- modeling_phi.py +907 -0
- pytorch_model.bin +2 -2
config.json
CHANGED
@@ -1,19 +1,24 @@
|
|
1 |
{
|
2 |
-
"_name_or_path": "phi-1
|
3 |
"activation_function": "gelu_new",
|
4 |
"architectures": [
|
5 |
-
"
|
6 |
],
|
|
|
7 |
"auto_map": {
|
8 |
-
"AutoConfig": "
|
9 |
-
"AutoModelForCausalLM": "
|
10 |
},
|
11 |
"embd_pdrop": 0.0,
|
|
|
|
|
|
|
12 |
"initializer_range": 0.02,
|
13 |
"layer_norm_epsilon": 1e-05,
|
14 |
-
"model_type": "
|
15 |
"n_embd": 2048,
|
16 |
"n_head": 32,
|
|
|
17 |
"n_inner": null,
|
18 |
"n_layer": 24,
|
19 |
"n_positions": 2048,
|
@@ -21,6 +26,6 @@
|
|
21 |
"rotary_dim": 32,
|
22 |
"tie_word_embeddings": false,
|
23 |
"torch_dtype": "float16",
|
24 |
-
"transformers_version": "4.
|
25 |
"vocab_size": 51200
|
26 |
}
|
|
|
1 |
{
|
2 |
+
"_name_or_path": "microsoft/phi-1",
|
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": null,
|
23 |
"n_layer": 24,
|
24 |
"n_positions": 2048,
|
|
|
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)
|
modeling_phi.py
ADDED
@@ -0,0 +1,907 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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, seqlen: int, device: Optional[str] = None, dtype: Optional[torch.dtype] = None
|
222 |
+
) -> None:
|
223 |
+
self._seq_len_cached = seqlen
|
224 |
+
|
225 |
+
# fp32 is preferred since the output of `torch.arange` can be quite large
|
226 |
+
# and bf16 would lose a lot of precision
|
227 |
+
if self.pos_idx_in_fp32:
|
228 |
+
t = torch.arange(seqlen, device=device, dtype=torch.float32)
|
229 |
+
if self.inv_freq.dtype != torch.float32:
|
230 |
+
inv_freq = self._compute_inv_freq(device=device)
|
231 |
+
else:
|
232 |
+
inv_freq = self.inv_freq
|
233 |
+
else:
|
234 |
+
t = torch.arange(seqlen, device=device, dtype=self.inv_freq.dtype)
|
235 |
+
inv_freq = self.inv_freq
|
236 |
+
|
237 |
+
# `torch.outer` is preferred since `torch.einsum` converts from fp32 to fp16 if used with AMP
|
238 |
+
freqs = torch.outer(t, inv_freq)
|
239 |
+
if self.scale is None:
|
240 |
+
self._cos_cached = torch.cos(freqs).to(dtype)
|
241 |
+
self._sin_cached = torch.sin(freqs).to(dtype)
|
242 |
+
else:
|
243 |
+
power = (
|
244 |
+
torch.arange(seqlen, dtype=self.scale.dtype, device=self.scale.device) - seqlen // 2
|
245 |
+
) / self.scale_base
|
246 |
+
scale = self.scale.to(device=power.device) ** rearrange(power, "s -> s 1")
|
247 |
+
|
248 |
+
# Force the scale multiplication to happen in fp32
|
249 |
+
self._cos_cached = (torch.cos(freqs) * scale).to(dtype)
|
250 |
+
self._sin_cached = (torch.sin(freqs) * scale).to(dtype)
|
251 |
+
self._cos_k_cached = (torch.cos(freqs) / scale).to(dtype)
|
252 |
+
self._sin_k_cached = (torch.sin(freqs) / scale).to(dtype)
|
253 |
+
|
254 |
+
def forward(
|
255 |
+
self,
|
256 |
+
qkv: torch.Tensor,
|
257 |
+
kv: Optional[torch.Tensor] = None,
|
258 |
+
seqlen_offset: int = 0,
|
259 |
+
**kwargs,
|
260 |
+
) -> Tuple[torch.Tensor, torch.Tensor]:
|
261 |
+
seq_start = seqlen_offset
|
262 |
+
seq_end = seq_start + qkv.shape[1]
|
263 |
+
|
264 |
+
if self._cos_cached.device != qkv.device or self._cos_cached.dtype != qkv.dtype or (self.training and self._cos_cached.is_inference()):
|
265 |
+
self._update_cos_sin_cache(self.max_position_embeddings, device=qkv.device, dtype=qkv.dtype)
|
266 |
+
|
267 |
+
if kv is None:
|
268 |
+
return _apply_rotary_emb_qkv(qkv, self._cos_cached[seq_start:seq_end], self._sin_cached[seq_start:seq_end])
|
269 |
+
else:
|
270 |
+
q = _apply_rotary_emb(qkv, self._cos_cached[seq_start:seq_end], self._sin_cached[seq_start:seq_end])
|
271 |
+
kv = _apply_rotary_emb_kv(kv, self._cos_cached[seq_start:seq_end], self._sin_cached[seq_start:seq_end])
|
272 |
+
|
273 |
+
return q, kv
|
274 |
+
|
275 |
+
|
276 |
+
class MLP(nn.Module):
|
277 |
+
"""Multi-Layer Perceptron.
|
278 |
+
|
279 |
+
Reference:
|
280 |
+
Attention Is All You Need.
|
281 |
+
https://arxiv.org/pdf/1706.03762.pdf.
|
282 |
+
|
283 |
+
"""
|
284 |
+
|
285 |
+
def __init__(
|
286 |
+
self,
|
287 |
+
config: PretrainedConfig,
|
288 |
+
n_inner: Optional[int] = None,
|
289 |
+
act_fn: Optional[str] = None,
|
290 |
+
) -> None:
|
291 |
+
super().__init__()
|
292 |
+
|
293 |
+
act_fn = config.activation_function if act_fn is None else act_fn
|
294 |
+
|
295 |
+
n_inner = getattr(config, "n_inner", None) if n_inner is None else n_inner
|
296 |
+
n_inner = n_inner if n_inner is not None else 4 * config.n_embd
|
297 |
+
|
298 |
+
self.fc1 = nn.Linear(config.n_embd, n_inner)
|
299 |
+
self.fc2 = nn.Linear(n_inner, config.n_embd)
|
300 |
+
self.act = ACT2FN[act_fn]
|
301 |
+
|
302 |
+
def forward(self, hidden_states: torch.FloatTensor) -> torch.FloatTensor:
|
303 |
+
hidden_states = self.fc1(hidden_states)
|
304 |
+
hidden_states = self.act(hidden_states)
|
305 |
+
hidden_states = self.fc2(hidden_states)
|
306 |
+
|
307 |
+
return hidden_states
|
308 |
+
|
309 |
+
|
310 |
+
class SelfAttention(nn.Module):
|
311 |
+
"""Self-attention layer (compatible with PyTorch).
|
312 |
+
|
313 |
+
Reference:
|
314 |
+
https://github.com/Dao-AILab/flash-attention/blob/main/flash_attn/modules/mha.py.
|
315 |
+
|
316 |
+
"""
|
317 |
+
|
318 |
+
def __init__(
|
319 |
+
self,
|
320 |
+
causal: bool = True,
|
321 |
+
softmax_scale: Optional[float] = None,
|
322 |
+
attention_dropout: float = 0.0,
|
323 |
+
) -> None:
|
324 |
+
super().__init__()
|
325 |
+
|
326 |
+
self.causal = causal
|
327 |
+
self.softmax_scale = softmax_scale
|
328 |
+
self.drop = nn.Dropout(attention_dropout)
|
329 |
+
|
330 |
+
def forward(
|
331 |
+
self,
|
332 |
+
qkv: torch.FloatTensor,
|
333 |
+
causal: bool = None,
|
334 |
+
key_padding_mask: Optional[torch.BoolTensor] = None,
|
335 |
+
**kwargs,
|
336 |
+
) -> torch.FloatTensor:
|
337 |
+
batch_size, seqlen = qkv.shape[0], qkv.shape[1]
|
338 |
+
q, k, v = qkv.unbind(dim=2)
|
339 |
+
|
340 |
+
causal = self.causal if causal is None else causal
|
341 |
+
softmax_scale = self.softmax_scale or 1.0 / math.sqrt(q.shape[-1])
|
342 |
+
|
343 |
+
scores = torch.einsum("bthd,bshd->bhts", q, k * softmax_scale)
|
344 |
+
|
345 |
+
if key_padding_mask is not None:
|
346 |
+
padding_mask = torch.full((batch_size, seqlen), -10000.0, dtype=scores.dtype, device=scores.device)
|
347 |
+
padding_mask.masked_fill_(key_padding_mask, 0.0)
|
348 |
+
|
349 |
+
scores = scores + rearrange(padding_mask, "b s -> b 1 1 s")
|
350 |
+
|
351 |
+
if causal:
|
352 |
+
causal_mask = torch.triu(torch.full((seqlen, seqlen), -10000.0, device=scores.device), 1)
|
353 |
+
scores = scores + causal_mask.to(dtype=scores.dtype)
|
354 |
+
|
355 |
+
attention = torch.softmax(scores, dim=-1, dtype=v.dtype)
|
356 |
+
attention = self.drop(attention)
|
357 |
+
|
358 |
+
output = torch.einsum("bhts,bshd->bthd", attention, v)
|
359 |
+
|
360 |
+
return output
|
361 |
+
|
362 |
+
|
363 |
+
class CrossAttention(nn.Module):
|
364 |
+
"""Cross-attention layer (compatible with PyTorch).
|
365 |
+
|
366 |
+
Reference:
|
367 |
+
https://github.com/Dao-AILab/flash-attention/blob/main/flash_attn/modules/mha.py.
|
368 |
+
|
369 |
+
"""
|
370 |
+
|
371 |
+
def __init__(
|
372 |
+
self,
|
373 |
+
causal: bool = True,
|
374 |
+
softmax_scale: Optional[float] = None,
|
375 |
+
attention_dropout: float = 0.0,
|
376 |
+
) -> None:
|
377 |
+
super().__init__()
|
378 |
+
|
379 |
+
self.causal = causal
|
380 |
+
self.softmax_scale = softmax_scale
|
381 |
+
self.drop = nn.Dropout(attention_dropout)
|
382 |
+
|
383 |
+
def forward(
|
384 |
+
self,
|
385 |
+
q: torch.FloatTensor,
|
386 |
+
kv: torch.FloatTensor,
|
387 |
+
causal: bool = None,
|
388 |
+
key_padding_mask: Optional[torch.BoolTensor] = None,
|
389 |
+
**kwargs,
|
390 |
+
) -> torch.FloatTensor:
|
391 |
+
batch_size, seqlen_q = q.shape[0], q.shape[1]
|
392 |
+
seqlen_k = kv.shape[1]
|
393 |
+
|
394 |
+
if kv.shape[3] != q.shape[2]:
|
395 |
+
kv = repeat(kv, "... hkv d -> ... (hkv g) d", g=q.shape[2] // kv.shape[3])
|
396 |
+
k, v = kv.unbind(dim=2)
|
397 |
+
|
398 |
+
causal = self.causal if causal is None else causal
|
399 |
+
softmax_scale = self.softmax_scale or 1.0 / math.sqrt(q.shape[-1])
|
400 |
+
|
401 |
+
scores = torch.einsum("bthd,bshd->bhts", q, k * softmax_scale)
|
402 |
+
|
403 |
+
if key_padding_mask is not None:
|
404 |
+
padding_mask = torch.full(
|
405 |
+
(batch_size, seqlen_k),
|
406 |
+
-10000.0,
|
407 |
+
dtype=scores.dtype,
|
408 |
+
device=scores.device,
|
409 |
+
)
|
410 |
+
padding_mask.masked_fill_(key_padding_mask, 0.0)
|
411 |
+
|
412 |
+
scores = scores + rearrange(padding_mask, "b s -> b 1 1 s")
|
413 |
+
|
414 |
+
if causal:
|
415 |
+
rows = rearrange(torch.arange(seqlen_q, device=q.device, dtype=torch.long), "s -> s 1")
|
416 |
+
cols = torch.arange(seqlen_k, device=k.device, dtype=torch.long)
|
417 |
+
causal_mask = cols > rows + seqlen_k - seqlen_q
|
418 |
+
|
419 |
+
scores = scores.masked_fill(causal_mask, -10000.0)
|
420 |
+
|
421 |
+
attention = torch.softmax(scores, dim=-1, dtype=v.dtype)
|
422 |
+
attention = self.drop(attention)
|
423 |
+
|
424 |
+
output = torch.einsum("bhts,bshd->bthd", attention, v)
|
425 |
+
|
426 |
+
return output
|
427 |
+
|
428 |
+
|
429 |
+
def _find_mha_dims(
|
430 |
+
config: PretrainedConfig,
|
431 |
+
n_head: Optional[int] = None,
|
432 |
+
n_head_kv: Optional[int] = None,
|
433 |
+
head_dim: Optional[int] = None,
|
434 |
+
) -> Tuple[int, int]:
|
435 |
+
if n_head is None and head_dim is None:
|
436 |
+
head_dim = config.n_embd // config.n_head
|
437 |
+
n_head = config.n_head
|
438 |
+
elif n_head is None or head_dim is None:
|
439 |
+
raise ValueError("`n_head` and `head_dim` must be both specified or `None`.")
|
440 |
+
|
441 |
+
if n_head_kv is None:
|
442 |
+
n_head_kv = getattr(config, "n_head_kv", None) or n_head
|
443 |
+
|
444 |
+
return n_head, n_head_kv, head_dim
|
445 |
+
|
446 |
+
|
447 |
+
def _update_kv_cache(kv: torch.FloatTensor, inference_params: InferenceParams, layer_idx: int) -> torch.FloatTensor:
|
448 |
+
num_heads, head_dim = kv.shape[-2:]
|
449 |
+
|
450 |
+
if layer_idx not in inference_params.key_value_memory_dict:
|
451 |
+
kv_cache = torch.empty(
|
452 |
+
inference_params.max_batch_size,
|
453 |
+
inference_params.max_seqlen,
|
454 |
+
2,
|
455 |
+
num_heads,
|
456 |
+
head_dim,
|
457 |
+
dtype=kv.dtype,
|
458 |
+
device=kv.device,
|
459 |
+
)
|
460 |
+
inference_params.key_value_memory_dict[layer_idx] = kv_cache
|
461 |
+
else:
|
462 |
+
kv_cache = inference_params.key_value_memory_dict[layer_idx]
|
463 |
+
|
464 |
+
batch_start = inference_params.batch_size_offset
|
465 |
+
batch_end = batch_start + kv.shape[0]
|
466 |
+
|
467 |
+
sequence_start = inference_params.seqlen_offset
|
468 |
+
sequence_end = sequence_start + kv.shape[1]
|
469 |
+
|
470 |
+
kv_cache[batch_start:batch_end, sequence_start:sequence_end, ...] = kv
|
471 |
+
kv = kv_cache[batch_start:batch_end, :sequence_end, ...]
|
472 |
+
|
473 |
+
return kv
|
474 |
+
|
475 |
+
|
476 |
+
class MHA(nn.Module):
|
477 |
+
"""Multi-head attention layer."""
|
478 |
+
|
479 |
+
def __init__(
|
480 |
+
self,
|
481 |
+
config: PretrainedConfig,
|
482 |
+
dtype: Optional[torch.dtype] = None,
|
483 |
+
device: Optional[str] = None,
|
484 |
+
rotary_dim: Optional[int] = None,
|
485 |
+
rotary_base: float = 10000.0,
|
486 |
+
rotary_scale_base: Optional[float] = None,
|
487 |
+
n_head: Optional[int] = None,
|
488 |
+
n_head_kv: Optional[int] = None,
|
489 |
+
head_dim: Optional[int] = None,
|
490 |
+
bias: bool = True,
|
491 |
+
causal: bool = True,
|
492 |
+
softmax_scale: Optional[float] = None,
|
493 |
+
layer_idx: Optional[int] = None,
|
494 |
+
return_residual: bool = False,
|
495 |
+
checkpointing: bool = False,
|
496 |
+
) -> None:
|
497 |
+
super().__init__()
|
498 |
+
|
499 |
+
# Rotary embedding
|
500 |
+
self.rotary_dim = rotary_dim if rotary_dim is not None else getattr(config, "rotary_dim", 0)
|
501 |
+
if self.rotary_dim > 0:
|
502 |
+
rotary_cls = FlashRotaryEmbedding if config.flash_rotary else RotaryEmbedding
|
503 |
+
if rotary_cls is None:
|
504 |
+
rotary_cls = RotaryEmbedding
|
505 |
+
|
506 |
+
rotary_kwargs = {}
|
507 |
+
if rotary_cls is RotaryEmbedding:
|
508 |
+
rotary_kwargs["max_position_embeddings"] = config.n_positions
|
509 |
+
|
510 |
+
self.rotary_emb = rotary_cls(self.rotary_dim, base=rotary_base, scale_base=rotary_scale_base, device=device, **rotary_kwargs)
|
511 |
+
|
512 |
+
# MLP
|
513 |
+
self.n_head, self.n_head_kv, self.head_dim = _find_mha_dims(
|
514 |
+
config, n_head=n_head, n_head_kv=n_head_kv, head_dim=head_dim
|
515 |
+
)
|
516 |
+
op_size = self.head_dim * (self.n_head + 2 * self.n_head_kv)
|
517 |
+
hidden_size = config.n_embd
|
518 |
+
|
519 |
+
linear_cls = FusedDense if config.fused_dense else nn.Linear
|
520 |
+
if linear_cls is None:
|
521 |
+
linear_cls = nn.Linear
|
522 |
+
|
523 |
+
self.Wqkv = linear_cls(hidden_size, op_size, bias=bias, device=device, dtype=dtype)
|
524 |
+
self.out_proj = linear_cls(hidden_size, hidden_size, bias=bias, device=device, dtype=dtype)
|
525 |
+
|
526 |
+
# Attention
|
527 |
+
attn_cls = FlashSelfAttention if config.flash_attn else SelfAttention
|
528 |
+
if attn_cls is None:
|
529 |
+
attn_cls = SelfAttention
|
530 |
+
|
531 |
+
cross_attn_cls = FlashCrossAttention if config.flash_attn else CrossAttention
|
532 |
+
if cross_attn_cls is None:
|
533 |
+
cross_attn_cls = CrossAttention
|
534 |
+
|
535 |
+
self.inner_attn = attn_cls(causal=causal, softmax_scale=softmax_scale, attention_dropout=config.attn_pdrop)
|
536 |
+
self.inner_cross_attn = cross_attn_cls(
|
537 |
+
causal=causal, softmax_scale=softmax_scale, attention_dropout=config.attn_pdrop
|
538 |
+
)
|
539 |
+
|
540 |
+
self.flash_attn = config.flash_attn and attn_cls is FlashSelfAttention
|
541 |
+
self.layer_idx = layer_idx
|
542 |
+
self.return_residual = return_residual
|
543 |
+
self.checkpointing = checkpointing
|
544 |
+
|
545 |
+
def _forward_self_attn(
|
546 |
+
self, x: torch.FloatTensor, key_padding_mask: Optional[torch.BoolTensor]
|
547 |
+
) -> torch.FloatTensor:
|
548 |
+
qkv = self.Wqkv(x)
|
549 |
+
qkv = rearrange(qkv, "... (three h d) -> ... three h d", three=3, d=self.head_dim)
|
550 |
+
|
551 |
+
if self.rotary_dim > 0:
|
552 |
+
qkv = self.rotary_emb(qkv)
|
553 |
+
|
554 |
+
if self.flash_attn:
|
555 |
+
batch_size, seqlen = qkv.shape[0], qkv.shape[1]
|
556 |
+
|
557 |
+
cu_seqlens, max_seqlen = None, None
|
558 |
+
if key_padding_mask is not None:
|
559 |
+
# If `key_padding_mask` is supplied, we need to unpad the input and retrieve
|
560 |
+
# the `cu_seqlens` and `max_seqlen` to be used by `flash-attn`
|
561 |
+
qkv, indices, cu_seqlens, max_seqlen = unpad_input(qkv, key_padding_mask)
|
562 |
+
|
563 |
+
if self.checkpointing:
|
564 |
+
attn_output = torch.utils.checkpoint.checkpoint(
|
565 |
+
self.inner_attn, qkv, cu_seqlens=cu_seqlens, max_seqlen=max_seqlen
|
566 |
+
)
|
567 |
+
else:
|
568 |
+
attn_output = self.inner_attn(qkv, cu_seqlens=cu_seqlens, max_seqlen=max_seqlen).to(qkv.device)
|
569 |
+
|
570 |
+
# If `key_padding_mask` is supplied, we need to pad the output back to the original shape
|
571 |
+
return pad_input(attn_output, indices, batch_size, seqlen) if key_padding_mask is not None else attn_output
|
572 |
+
|
573 |
+
if self.checkpointing:
|
574 |
+
return torch.utils.checkpoint.checkpoint(self.inner_attn, qkv, key_padding_mask=key_padding_mask)
|
575 |
+
|
576 |
+
return self.inner_attn(qkv, key_padding_mask=key_padding_mask)
|
577 |
+
|
578 |
+
def _forward_cross_attn(
|
579 |
+
self,
|
580 |
+
x: torch.FloatTensor,
|
581 |
+
past_key_values: Optional[InferenceParams],
|
582 |
+
key_padding_mask: Optional[torch.BoolTensor],
|
583 |
+
) -> torch.FloatTensor:
|
584 |
+
batch_size = x.shape[0]
|
585 |
+
|
586 |
+
qkv = self.Wqkv(x)
|
587 |
+
|
588 |
+
q = qkv[..., : self.n_head * self.head_dim]
|
589 |
+
q = rearrange(q, "... (h d) -> ... h d", d=self.head_dim)
|
590 |
+
|
591 |
+
kv = qkv[..., self.n_head * self.head_dim :]
|
592 |
+
kv = rearrange(kv, "... (two hkv d) -> ... two hkv d", two=2, d=self.head_dim)
|
593 |
+
|
594 |
+
seqlen_offset = past_key_values.seqlen_offset if past_key_values is not None else 0
|
595 |
+
causal = None if seqlen_offset == 0 else False
|
596 |
+
if self.rotary_dim > 0:
|
597 |
+
q, kv = self.rotary_emb(q, kv=kv, seqlen_offset=seqlen_offset)
|
598 |
+
|
599 |
+
if past_key_values is not None:
|
600 |
+
kv = _update_kv_cache(kv, past_key_values, self.layer_idx)
|
601 |
+
|
602 |
+
if self.flash_attn:
|
603 |
+
batch_size, seqlen_q = q.shape[0], q.shape[1]
|
604 |
+
seqlen_k = kv.shape[1]
|
605 |
+
|
606 |
+
cu_seqlens_q, cu_seqlens_k, max_seqlen_q, max_seqlen_k = None, None, None, None
|
607 |
+
if key_padding_mask is not None:
|
608 |
+
kv, _, cu_seqlens_k, max_seqlen_k = unpad_input(kv, key_padding_mask)
|
609 |
+
|
610 |
+
if seqlen_q == 1:
|
611 |
+
key_padding_mask = torch.ones(batch_size, 1, device=q.device)
|
612 |
+
elif seqlen_q != seqlen_k:
|
613 |
+
key_padding_mask = key_padding_mask[:, -seqlen_q:]
|
614 |
+
|
615 |
+
q, indices_q, cu_seqlens_q, max_seqlen_q = unpad_input(q, key_padding_mask)
|
616 |
+
|
617 |
+
if self.checkpointing:
|
618 |
+
attn_output = torch.utils.checkpoint.checkpoint(
|
619 |
+
self.inner_cross_attn,
|
620 |
+
q,
|
621 |
+
kv,
|
622 |
+
causal=causal,
|
623 |
+
cu_seqlens=cu_seqlens_q,
|
624 |
+
max_seqlen=max_seqlen_q,
|
625 |
+
cu_seqlens_k=cu_seqlens_k,
|
626 |
+
max_seqlen_k=max_seqlen_k,
|
627 |
+
)
|
628 |
+
else:
|
629 |
+
attn_output = self.inner_cross_attn(
|
630 |
+
q,
|
631 |
+
kv,
|
632 |
+
causal=causal,
|
633 |
+
cu_seqlens=cu_seqlens_q,
|
634 |
+
max_seqlen=max_seqlen_q,
|
635 |
+
cu_seqlens_k=cu_seqlens_k,
|
636 |
+
max_seqlen_k=max_seqlen_k,
|
637 |
+
)
|
638 |
+
|
639 |
+
return (
|
640 |
+
pad_input(attn_output, indices_q, batch_size, max_seqlen_q)
|
641 |
+
if key_padding_mask is not None
|
642 |
+
else attn_output
|
643 |
+
)
|
644 |
+
|
645 |
+
if self.checkpointing:
|
646 |
+
return torch.utils.checkpoint.checkpoint(
|
647 |
+
self.inner_cross_attn, q, kv, key_padding_mask=key_padding_mask, causal=causal
|
648 |
+
)
|
649 |
+
|
650 |
+
return self.inner_cross_attn(q, kv, key_padding_mask=key_padding_mask, causal=causal)
|
651 |
+
|
652 |
+
def forward(
|
653 |
+
self,
|
654 |
+
x: torch.FloatTensor,
|
655 |
+
past_key_values: Optional[InferenceParams] = None,
|
656 |
+
attention_mask: Optional[Union[torch.LongTensor, torch.BoolTensor]] = None,
|
657 |
+
**kwargs,
|
658 |
+
) -> Tuple[torch.FloatTensor, torch.FloatTensor]:
|
659 |
+
# TODO: Need an alternative way for dynamic control flow: torch.any(~attention_mask.bool())
|
660 |
+
if attention_mask is not None:
|
661 |
+
attention_mask = attention_mask.bool()
|
662 |
+
else:
|
663 |
+
attention_mask = None
|
664 |
+
|
665 |
+
# MHA
|
666 |
+
if self.n_head == self.n_head_kv:
|
667 |
+
if past_key_values is None:
|
668 |
+
# If `past_key_values` are not supplied, we run self-attention
|
669 |
+
attn_output = self._forward_self_attn(x, attention_mask)
|
670 |
+
else:
|
671 |
+
# If `past_key_values` are supplied, it means that we might have cached values and
|
672 |
+
# could take advantage of cross-attention
|
673 |
+
attn_output = self._forward_cross_attn(x, past_key_values, attention_mask)
|
674 |
+
# MQA / GQA
|
675 |
+
else:
|
676 |
+
# Regardless of `past_key_values` being supplied or not, it always use cross-attention
|
677 |
+
# because `q` and `kv` lengths might be different
|
678 |
+
attn_output = self._forward_cross_attn(x, past_key_values, attention_mask)
|
679 |
+
|
680 |
+
output = rearrange(attn_output, "... h d -> ... (h d)")
|
681 |
+
output = self.out_proj(output)
|
682 |
+
|
683 |
+
return output if not self.return_residual else (output, x)
|
684 |
+
|
685 |
+
|
686 |
+
class ParallelBlock(nn.Module):
|
687 |
+
"""Parallel block.
|
688 |
+
|
689 |
+
This block applies parallel mixer and MLP layers to the input (used in GPT-J and CodeGen).
|
690 |
+
|
691 |
+
"""
|
692 |
+
|
693 |
+
def __init__(
|
694 |
+
self,
|
695 |
+
config: PretrainedConfig,
|
696 |
+
block_idx: Optional[int] = None,
|
697 |
+
) -> None:
|
698 |
+
super().__init__()
|
699 |
+
|
700 |
+
self.ln = nn.LayerNorm(config.n_embd, eps=config.layer_norm_epsilon)
|
701 |
+
self.resid_dropout = nn.Dropout(config.resid_pdrop)
|
702 |
+
self.block_idx = block_idx
|
703 |
+
|
704 |
+
self.mixer = MHA(config, layer_idx=block_idx)
|
705 |
+
self.mlp = MLP(config)
|
706 |
+
|
707 |
+
def forward(
|
708 |
+
self,
|
709 |
+
hidden_states: torch.FloatTensor,
|
710 |
+
past_key_values: Optional[Union[torch.FloatTensor, InferenceParams]] = None,
|
711 |
+
attention_mask: Optional[torch.BoolTensor] = None,
|
712 |
+
**kwargs,
|
713 |
+
) -> torch.FloatTensor:
|
714 |
+
residual = hidden_states
|
715 |
+
hidden_states = self.ln(hidden_states)
|
716 |
+
|
717 |
+
attn_outputs = self.mixer(
|
718 |
+
hidden_states,
|
719 |
+
past_key_values=past_key_values,
|
720 |
+
attention_mask=attention_mask,
|
721 |
+
)
|
722 |
+
if isinstance(attn_outputs, tuple):
|
723 |
+
attn_outputs = attn_outputs[0]
|
724 |
+
|
725 |
+
attn_outputs = self.resid_dropout(attn_outputs)
|
726 |
+
feed_forward_hidden_states = self.resid_dropout(self.mlp(hidden_states))
|
727 |
+
|
728 |
+
hidden_states = attn_outputs + feed_forward_hidden_states + residual
|
729 |
+
|
730 |
+
return hidden_states
|
731 |
+
|
732 |
+
|
733 |
+
class CausalLMHead(nn.Module):
|
734 |
+
"""Causal Language Modeling head.
|
735 |
+
|
736 |
+
Reference:
|
737 |
+
Improving Language Understanding by Generative Pre-Training.
|
738 |
+
https://cdn.openai.com/research-covers/language-unsupervised/language_understanding_paper.pdf.
|
739 |
+
|
740 |
+
"""
|
741 |
+
|
742 |
+
def __init__(self, config: PretrainedConfig) -> None:
|
743 |
+
super().__init__()
|
744 |
+
|
745 |
+
self.ln = nn.LayerNorm(config.n_embd, eps=config.layer_norm_epsilon)
|
746 |
+
self.linear = nn.Linear(config.n_embd, config.vocab_size)
|
747 |
+
|
748 |
+
def forward(self, hidden_states: torch.FloatTensor) -> torch.FloatTensor:
|
749 |
+
hidden_states = self.ln(hidden_states)
|
750 |
+
logits = self.linear(hidden_states).to(torch.float32)
|
751 |
+
|
752 |
+
return logits
|
753 |
+
|
754 |
+
|
755 |
+
class CausalLMLoss(nn.Module):
|
756 |
+
"""Causal Language Modeling loss.
|
757 |
+
|
758 |
+
Reference:
|
759 |
+
Improving Language Understanding by Generative Pre-Training.
|
760 |
+
https://cdn.openai.com/research-covers/language-unsupervised/language_understanding_paper.pdf.
|
761 |
+
|
762 |
+
"""
|
763 |
+
|
764 |
+
def __init__(self, shift_labels: bool = True) -> None:
|
765 |
+
super().__init__()
|
766 |
+
|
767 |
+
self.shift_labels = shift_labels
|
768 |
+
self.loss_fct = nn.CrossEntropyLoss()
|
769 |
+
|
770 |
+
def forward(self, logits: torch.FloatTensor, labels: torch.LongTensor) -> torch.FloatTensor:
|
771 |
+
if self.shift_labels:
|
772 |
+
logits = logits[..., :-1, :].contiguous()
|
773 |
+
labels = labels[..., 1:].contiguous()
|
774 |
+
|
775 |
+
loss = self.loss_fct(logits.view(-1, logits.size(-1)), labels.view(-1))
|
776 |
+
|
777 |
+
return loss
|
778 |
+
|
779 |
+
|
780 |
+
class PhiPreTrainedModel(PreTrainedModel):
|
781 |
+
"""Phi pre-trained model."""
|
782 |
+
|
783 |
+
config_class = PhiConfig
|
784 |
+
base_model_prefix = "transformer"
|
785 |
+
supports_gradient_checkpointing = False
|
786 |
+
_no_split_modules = ["ParallelBlock"]
|
787 |
+
|
788 |
+
def __init__(self, *inputs, **kwargs) -> None:
|
789 |
+
super().__init__(*inputs, **kwargs)
|
790 |
+
|
791 |
+
def _init_weights(self, module: nn.Module) -> None:
|
792 |
+
if isinstance(module, (nn.Linear,)):
|
793 |
+
module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
|
794 |
+
if module.bias is not None:
|
795 |
+
module.bias.data.zero_()
|
796 |
+
elif isinstance(module, nn.Embedding):
|
797 |
+
module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
|
798 |
+
if module.padding_idx is not None:
|
799 |
+
module.weight.data[module.padding_idx].zero_()
|
800 |
+
elif isinstance(module, nn.LayerNorm):
|
801 |
+
if module.bias is not None:
|
802 |
+
module.bias.data.zero_()
|
803 |
+
module.weight.data.fill_(1.0)
|
804 |
+
|
805 |
+
def prepare_inputs_for_generation(
|
806 |
+
self,
|
807 |
+
input_ids: torch.LongTensor,
|
808 |
+
past_key_values: Optional[Union[torch.FloatTensor, InferenceParams]] = None,
|
809 |
+
attention_mask: Optional[Union[torch.LongTensor, torch.BoolTensor]] = None,
|
810 |
+
**kwargs,
|
811 |
+
) -> Dict[str, Any]:
|
812 |
+
if past_key_values is None or not (isinstance(past_key_values, InferenceParams)):
|
813 |
+
past_key_values = InferenceParams(
|
814 |
+
max_seqlen=self.config.n_positions,
|
815 |
+
max_batch_size=input_ids.shape[0],
|
816 |
+
seqlen_offset=0,
|
817 |
+
batch_size_offset=0,
|
818 |
+
key_value_memory_dict={},
|
819 |
+
lengths_per_sample=None,
|
820 |
+
)
|
821 |
+
else:
|
822 |
+
# Assume that `past_key_values` has cached all tokens up to the last token in `input_ids`
|
823 |
+
past_key_values.seqlen_offset = len(input_ids[0]) - 1
|
824 |
+
input_ids = input_ids[:, -1].unsqueeze(-1)
|
825 |
+
|
826 |
+
return {
|
827 |
+
"input_ids": input_ids,
|
828 |
+
"past_key_values": past_key_values,
|
829 |
+
"attention_mask": attention_mask,
|
830 |
+
}
|
831 |
+
|
832 |
+
|
833 |
+
class PhiModel(PhiPreTrainedModel):
|
834 |
+
"""Phi model."""
|
835 |
+
|
836 |
+
_keys_to_ignore_on_load_missing = [""]
|
837 |
+
_keys_to_ignore_on_load_unexpected = [r"h\.\d+\.mlp.(fc_in|fc_out)\.(weight|bias)"]
|
838 |
+
|
839 |
+
def __init__(self, config: PhiConfig) -> None:
|
840 |
+
super().__init__(config)
|
841 |
+
|
842 |
+
self.embd = Embedding(config)
|
843 |
+
self.h = nn.ModuleList([ParallelBlock(config, block_idx=i) for i in range(config.n_layer)])
|
844 |
+
self.gradient_checkpointing = False
|
845 |
+
self.post_init()
|
846 |
+
|
847 |
+
def get_input_embeddings(self) -> nn.Embedding:
|
848 |
+
return self.embd.wte
|
849 |
+
|
850 |
+
def set_input_embeddings(self, new_embeddings: nn.Embedding) -> None:
|
851 |
+
self.embd.wte = new_embeddings
|
852 |
+
|
853 |
+
def forward(
|
854 |
+
self,
|
855 |
+
input_ids: torch.LongTensor,
|
856 |
+
past_key_values: Optional[Union[torch.FloatTensor, InferenceParams]] = None,
|
857 |
+
attention_mask: Optional[torch.BoolTensor] = None,
|
858 |
+
) -> torch.FloatTensor:
|
859 |
+
hidden_states = self.embd(input_ids)
|
860 |
+
|
861 |
+
for layer in self.h:
|
862 |
+
hidden_states = layer(
|
863 |
+
hidden_states,
|
864 |
+
past_key_values=past_key_values,
|
865 |
+
attention_mask=attention_mask,
|
866 |
+
)
|
867 |
+
|
868 |
+
return hidden_states
|
869 |
+
|
870 |
+
|
871 |
+
class PhiForCausalLM(PhiPreTrainedModel):
|
872 |
+
"""Phi for Causal Language Modeling."""
|
873 |
+
|
874 |
+
_keys_to_ignore_on_load_missing = [""]
|
875 |
+
_keys_to_ignore_on_load_unexpected = [r"transformer\.h\.\d+\.mlp.(fc_in|fc_out)\.(weight|bias)"]
|
876 |
+
|
877 |
+
def __init__(self, config: PhiConfig) -> None:
|
878 |
+
super().__init__(config)
|
879 |
+
|
880 |
+
self.transformer = PhiModel(config)
|
881 |
+
self.lm_head = CausalLMHead(config)
|
882 |
+
self.loss = CausalLMLoss()
|
883 |
+
|
884 |
+
self.post_init()
|
885 |
+
|
886 |
+
def get_output_embeddings(self) -> nn.Linear:
|
887 |
+
return self.lm_head.linear
|
888 |
+
|
889 |
+
def set_output_embeddings(self, new_embeddings: nn.Linear) -> None:
|
890 |
+
self.lm_head.linear = new_embeddings
|
891 |
+
|
892 |
+
def forward(
|
893 |
+
self,
|
894 |
+
input_ids: torch.LongTensor,
|
895 |
+
past_key_values: Optional[Union[torch.FloatTensor, InferenceParams]] = None,
|
896 |
+
attention_mask: Optional[torch.BoolTensor] = None,
|
897 |
+
labels: Optional[torch.LongTensor] = None,
|
898 |
+
**kwargs,
|
899 |
+
) -> CausalLMOutputWithPast:
|
900 |
+
hidden_states = self.transformer(input_ids, past_key_values=past_key_values, attention_mask=attention_mask)
|
901 |
+
lm_logits = self.lm_head(hidden_states)
|
902 |
+
|
903 |
+
loss = None
|
904 |
+
if labels is not None:
|
905 |
+
loss = self.loss(lm_logits, labels)
|
906 |
+
|
907 |
+
return CausalLMOutputWithPast(loss=loss, logits=lm_logits, past_key_values=past_key_values)
|
pytorch_model.bin
CHANGED
@@ -1,3 +1,3 @@
|
|
1 |
version https://git-lfs.github.com/spec/v1
|
2 |
-
oid sha256:
|
3 |
-
size
|
|
|
1 |
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:e5cbf1ddf999b35f41a2a25ec4b4402e5f858702537c85b884705a810628c5ef
|
3 |
+
size 5673163926
|