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