Fixed the incompatibility with transformers-4.43.3
#6
by
iamdanialkamali
- opened
- modeling_cogvlm.py +835 -834
modeling_cogvlm.py
CHANGED
@@ -1,834 +1,835 @@
|
|
1 |
-
"""largely copy from llama and adapt for cogvlm"""
|
2 |
-
import warnings
|
3 |
-
from typing import TYPE_CHECKING, Optional, Tuple, List, Union, Literal, Dict, Any
|
4 |
-
|
5 |
-
import math
|
6 |
-
import torch
|
7 |
-
from torch import nn
|
8 |
-
from torch.nn import functional as F
|
9 |
-
from torch.nn import CrossEntropyLoss
|
10 |
-
from torchvision import transforms
|
11 |
-
from einops import rearrange
|
12 |
-
|
13 |
-
from transformers import PreTrainedModel, PreTrainedTokenizer
|
14 |
-
from transformers.utils.logging import get_logger
|
15 |
-
from transformers.activations import ACT2FN
|
16 |
-
from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast
|
17 |
-
|
18 |
-
from .configuration_cogvlm import CogVLMConfig
|
19 |
-
from .visual import EVA2CLIPModel
|
20 |
-
|
21 |
-
if TYPE_CHECKING:
|
22 |
-
from transformers.utils import ModelOutput
|
23 |
-
|
24 |
-
logger = get_logger(__name__)
|
25 |
-
|
26 |
-
LANGUAGE_TOKEN_TYPE = 0
|
27 |
-
VISION_TOKEN_TYPE = 1
|
28 |
-
|
29 |
-
|
30 |
-
# Copied from transformers.models.bart.modeling_bart._make_causal_mask
|
31 |
-
def _make_causal_mask(
|
32 |
-
input_ids_shape: torch.Size, dtype: torch.dtype, device: torch.device, past_key_values_length: int = 0
|
33 |
-
):
|
34 |
-
"""
|
35 |
-
Make causal mask used for bi-directional self-attention.
|
36 |
-
"""
|
37 |
-
bsz, tgt_len = input_ids_shape
|
38 |
-
mask = torch.full((tgt_len, tgt_len), torch.finfo(dtype).min, device=device)
|
39 |
-
mask_cond = torch.arange(mask.size(-1), device=device)
|
40 |
-
mask.masked_fill_(mask_cond < (mask_cond + 1).view(mask.size(-1), 1), 0)
|
41 |
-
mask = mask.to(dtype)
|
42 |
-
|
43 |
-
if past_key_values_length > 0:
|
44 |
-
mask = torch.cat([torch.zeros(tgt_len, past_key_values_length, dtype=dtype, device=device), mask], dim=-1)
|
45 |
-
return mask[None, None, :, :].expand(bsz, 1, tgt_len, tgt_len + past_key_values_length)
|
46 |
-
|
47 |
-
|
48 |
-
# Copied from transformers.models.bart.modeling_bart._expand_mask
|
49 |
-
def _expand_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None):
|
50 |
-
"""
|
51 |
-
Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`.
|
52 |
-
"""
|
53 |
-
bsz, src_len = mask.size()
|
54 |
-
tgt_len = tgt_len if tgt_len is not None else src_len
|
55 |
-
|
56 |
-
expanded_mask = mask[:, None, None, :].expand(bsz, 1, tgt_len, src_len).to(dtype)
|
57 |
-
|
58 |
-
inverted_mask = 1.0 - expanded_mask
|
59 |
-
|
60 |
-
return inverted_mask.masked_fill(inverted_mask.to(torch.bool), torch.finfo(dtype).min)
|
61 |
-
|
62 |
-
|
63 |
-
class RMSNorm(nn.Module):
|
64 |
-
def __init__(self, hidden_size, eps=1e-6):
|
65 |
-
super().__init__()
|
66 |
-
self.weight = nn.Parameter(torch.ones(hidden_size))
|
67 |
-
self.variance_epsilon = eps
|
68 |
-
|
69 |
-
def forward(self, hidden_states):
|
70 |
-
input_dtype = hidden_states.dtype
|
71 |
-
hidden_states = hidden_states.to(torch.float32)
|
72 |
-
variance = hidden_states.pow(2).mean(-1, keepdim=True)
|
73 |
-
hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
|
74 |
-
return (self.weight * hidden_states).to(input_dtype)
|
75 |
-
|
76 |
-
|
77 |
-
class MLP(nn.Module):
|
78 |
-
def __init__(self, config):
|
79 |
-
super().__init__()
|
80 |
-
self.hidden_size = config.hidden_size
|
81 |
-
self.intermediate_size = config.intermediate_size
|
82 |
-
self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
|
83 |
-
self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
|
84 |
-
self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
|
85 |
-
self.act_fn = ACT2FN[config.hidden_act]
|
86 |
-
|
87 |
-
def forward(self, x):
|
88 |
-
down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
|
89 |
-
return down_proj
|
90 |
-
|
91 |
-
|
92 |
-
def get_expert_mask(token_type_ids: "torch.LongTensor(B, L)") -> "[torch.BoolTensor(B, L), torch.BoolTensor(B, L)]":
|
93 |
-
vision_token_mask = torch.zeros_like(token_type_ids, dtype=torch.bool)
|
94 |
-
vision_token_mask[:, :-1] = (token_type_ids[:, :-1] == VISION_TOKEN_TYPE) & (token_type_ids[:, 1:] == VISION_TOKEN_TYPE)
|
95 |
-
language_token_mask = ~vision_token_mask
|
96 |
-
return vision_token_mask, language_token_mask
|
97 |
-
|
98 |
-
|
99 |
-
class VisionExpertMLP(nn.Module):
|
100 |
-
def __init__(self, config):
|
101 |
-
super().__init__()
|
102 |
-
self.language_mlp = MLP(config)
|
103 |
-
self.vision_mlp = MLP(config)
|
104 |
-
|
105 |
-
def forward(self, hidden_states: "torch.Tensor(B, L, D)", token_type_ids: "torch.LongTensor(B, L)"):
|
106 |
-
output = torch.empty(hidden_states.shape, dtype=hidden_states.dtype, device=hidden_states.device)
|
107 |
-
vision_token_mask, language_token_mask = get_expert_mask(token_type_ids)
|
108 |
-
output[vision_token_mask] = self.vision_mlp(hidden_states[vision_token_mask])
|
109 |
-
output[language_token_mask] = self.language_mlp(hidden_states[language_token_mask])
|
110 |
-
return output
|
111 |
-
|
112 |
-
|
113 |
-
def attention_fn(
|
114 |
-
query_layer: "torch.tensor(B, H, L, HD)",
|
115 |
-
key_layer: "torch.tensor(B, H, L, HD)",
|
116 |
-
value_layer: "torch.tensor(B, H, L, HD)",
|
117 |
-
attention_mask: "torch.tensor(B, H, L, HD)",
|
118 |
-
*,
|
119 |
-
scaling_attention_score: bool = True,
|
120 |
-
attention_dropout: nn.Module = None
|
121 |
-
):
|
122 |
-
attention_mask_bool = (attention_mask == 0)
|
123 |
-
is_low_triangle = (attention_mask_bool == torch.ones_like(attention_mask_bool, dtype=torch.float).tril()).all()
|
124 |
-
is_full = (attention_mask_bool > 0).all()
|
125 |
-
if not (int(torch.__version__.split('.')[0]) >= 2):
|
126 |
-
warnings.warn("It's recommended to use torch2.0 or higher.")
|
127 |
-
if int(torch.__version__.split('.')[0]) >= 2 and scaling_attention_score and (is_full or is_low_triangle):
|
128 |
-
dropout_p = 0. if attention_dropout is None or not attention_dropout.training else attention_dropout.p
|
129 |
-
return torch.nn.functional.scaled_dot_product_attention(
|
130 |
-
query_layer, key_layer, value_layer,
|
131 |
-
attn_mask=None,
|
132 |
-
dropout_p=dropout_p,
|
133 |
-
is_causal=not is_full
|
134 |
-
)
|
135 |
-
else:
|
136 |
-
if scaling_attention_score:
|
137 |
-
query_layer = query_layer / math.sqrt(query_layer.shape[-1])
|
138 |
-
attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2))
|
139 |
-
attention_scores = attention_scores + attention_mask
|
140 |
-
attention_scores = nn.functional.softmax(attention_scores, dim=-1, dtype=torch.float32).to(query_layer.dtype)
|
141 |
-
if attention_dropout is not None:
|
142 |
-
attention_scores = attention_dropout(attention_scores)
|
143 |
-
context_layer = torch.matmul(attention_scores, value_layer)
|
144 |
-
return context_layer
|
145 |
-
|
146 |
-
|
147 |
-
class RotaryEmbedding(torch.nn.Module):
|
148 |
-
def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
|
149 |
-
super().__init__()
|
150 |
-
|
151 |
-
self.dim = dim
|
152 |
-
self.max_position_embeddings = max_position_embeddings
|
153 |
-
self.base = base
|
154 |
-
inv_freq = self._compute_inv_freq(device)
|
155 |
-
self.register_buffer("inv_freq", inv_freq)
|
156 |
-
self.max_seq_len_cached = 0
|
157 |
-
|
158 |
-
def _compute_inv_freq(self, device=None):
|
159 |
-
return 1.0 / (
|
160 |
-
self.base
|
161 |
-
** (torch.arange(0, self.dim, 2, device=device) / self.dim)
|
162 |
-
)
|
163 |
-
|
164 |
-
def _set_cos_sin_cache(self, seq_len, device, dtype):
|
165 |
-
self.max_seq_len_cached = seq_len
|
166 |
-
t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
|
167 |
-
|
168 |
-
freqs = torch.einsum("i,j->ij", t, self.inv_freq)
|
169 |
-
# Different from paper, but it uses a different permutation in order to obtain the same calculation
|
170 |
-
emb = torch.cat((freqs, freqs), dim=-1)
|
171 |
-
self.register_buffer("cos_cached", emb.cos()[:, None, :].to(dtype), persistent=False)
|
172 |
-
self.register_buffer("sin_cached", emb.sin()[:, None, :].to(dtype), persistent=False)
|
173 |
-
|
174 |
-
def forward(self, x, seq_len):
|
175 |
-
# x: [bs, num_attention_heads, seq_len, head_size]
|
176 |
-
if seq_len > self.max_seq_len_cached:
|
177 |
-
self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=x.dtype)
|
178 |
-
|
179 |
-
return (
|
180 |
-
self.cos_cached[:seq_len, ...].to(dtype=x.dtype),
|
181 |
-
self.sin_cached[:seq_len, ...].to(dtype=x.dtype),
|
182 |
-
)
|
183 |
-
|
184 |
-
|
185 |
-
def rotate_half(x):
|
186 |
-
x1, x2 = x[..., :x.shape[-1] // 2], x[..., x.shape[-1] // 2:]
|
187 |
-
return torch.cat((-x2, x1), dim=x1.ndim - 1)
|
188 |
-
|
189 |
-
|
190 |
-
def apply_rotary_pos_emb_index_bhs(q, k, cos, sin, position_id):
|
191 |
-
# batch_size, num_head, seq_len, hidden_size
|
192 |
-
cos, sin = F.embedding(position_id, cos.squeeze(1)).unsqueeze(1), \
|
193 |
-
F.embedding(position_id, sin.squeeze(1)).unsqueeze(1)
|
194 |
-
q, k = (q * cos) + (rotate_half(q) * sin), (k * cos) + (rotate_half(k) * sin)
|
195 |
-
return q, k
|
196 |
-
|
197 |
-
|
198 |
-
class VisionExpertAttention(nn.Module):
|
199 |
-
def __init__(self, config):
|
200 |
-
super().__init__()
|
201 |
-
self.config = config
|
202 |
-
self.hidden_size = config.hidden_size
|
203 |
-
self.num_heads = config.num_attention_heads
|
204 |
-
self.head_dim = self.hidden_size // self.num_heads
|
205 |
-
self.max_position_embeddings = config.max_position_embeddings
|
206 |
-
|
207 |
-
self.rotary_emb = RotaryEmbedding(self.head_dim)
|
208 |
-
self.vision_expert_query_key_value = nn.Linear(self.hidden_size, self.hidden_size * 3, bias=False)
|
209 |
-
self.vision_expert_dense = nn.Linear(self.hidden_size, self.hidden_size, bias=False)
|
210 |
-
self.language_expert_query_key_value = nn.Linear(self.hidden_size, self.hidden_size * 3, bias=False)
|
211 |
-
self.language_expert_dense = nn.Linear(self.hidden_size, self.hidden_size, bias=False)
|
212 |
-
|
213 |
-
def _transpose_for_scores(self, tensor):
|
214 |
-
"""Transpose a 3D tensor [B, L, H*HD] into a 4D tensor with size [B H L HD]."""
|
215 |
-
new_tensor_shape = tensor.size()[:-1] + (self.num_heads, self.head_dim)
|
216 |
-
tensor = tensor.view(*new_tensor_shape)
|
217 |
-
return tensor.permute(0, 2, 1, 3)
|
218 |
-
|
219 |
-
def forward(
|
220 |
-
self,
|
221 |
-
hidden_states: torch.Tensor,
|
222 |
-
token_type_ids: torch.LongTensor,
|
223 |
-
position_ids: torch.LongTensor,
|
224 |
-
attention_mask: Optional[torch.Tensor] = None,
|
225 |
-
past_key_value: Optional[Tuple[torch.Tensor]] = None,
|
226 |
-
output_attentions: bool = False,
|
227 |
-
use_cache: bool = False,
|
228 |
-
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
229 |
-
bsz, q_len, _ = hidden_states.size()
|
230 |
-
vision_token_mask, language_token_mask = get_expert_mask(token_type_ids)
|
231 |
-
|
232 |
-
shape = list(hidden_states.shape)
|
233 |
-
shape[-1] = shape[-1] * 3
|
234 |
-
mixed_raw_layer = torch.empty(shape, dtype=hidden_states.dtype, device=hidden_states.device)
|
235 |
-
mixed_raw_layer[vision_token_mask] = self.vision_expert_query_key_value(hidden_states[vision_token_mask])
|
236 |
-
mixed_raw_layer[language_token_mask] = self.language_expert_query_key_value(hidden_states[language_token_mask])
|
237 |
-
|
238 |
-
query_states, key_states, value_states = torch.split(mixed_raw_layer, self.hidden_size, dim=-1)
|
239 |
-
query_states = self._transpose_for_scores(query_states) # B, H, L, HD
|
240 |
-
key_states = self._transpose_for_scores(key_states) # B, H, L, HD
|
241 |
-
value_states = self._transpose_for_scores(value_states) # B, H, L, HD
|
242 |
-
|
243 |
-
kv_seq_len = key_states.shape[-2]
|
244 |
-
if past_key_value is not None:
|
245 |
-
kv_seq_len += past_key_value[0].shape[-2]
|
246 |
-
cos, sin = self.rotary_emb(value_states, seq_len=position_ids.max() + 1)
|
247 |
-
query_states, key_states = apply_rotary_pos_emb_index_bhs(query_states, key_states, cos, sin, position_ids)
|
248 |
-
|
249 |
-
if past_key_value is not None:
|
250 |
-
key_states = torch.cat([past_key_value[0], key_states], dim=2)
|
251 |
-
value_states = torch.cat([past_key_value[1], value_states], dim=2)
|
252 |
-
|
253 |
-
past_key_value = (key_states, value_states) if use_cache else None
|
254 |
-
|
255 |
-
context_layer = attention_fn(
|
256 |
-
query_layer=query_states, key_layer=key_states, value_layer=value_states, attention_mask=attention_mask,
|
257 |
-
scaling_attention_score=True, attention_dropout=None)
|
258 |
-
if context_layer.size() != (bsz, self.num_heads, q_len, self.head_dim):
|
259 |
-
raise ValueError(
|
260 |
-
f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
|
261 |
-
f" {context_layer.size()}"
|
262 |
-
)
|
263 |
-
context_layer = context_layer.transpose(1, 2).contiguous().reshape(bsz, q_len, self.hidden_size)
|
264 |
-
|
265 |
-
attn_output = torch.empty(context_layer.shape, dtype=hidden_states.dtype, device=hidden_states.device)
|
266 |
-
attn_output[vision_token_mask] = self.vision_expert_dense(context_layer[vision_token_mask])
|
267 |
-
attn_output[language_token_mask] = self.language_expert_dense(context_layer[language_token_mask])
|
268 |
-
|
269 |
-
if output_attentions:
|
270 |
-
warnings.warn("output_attentions is not implemented.")
|
271 |
-
|
272 |
-
return attn_output, None, past_key_value
|
273 |
-
|
274 |
-
|
275 |
-
class CogVLMDecoderLayer(nn.Module):
|
276 |
-
def __init__(self, config):
|
277 |
-
super().__init__()
|
278 |
-
self.hidden_size = config.hidden_size
|
279 |
-
self.self_attn = VisionExpertAttention(config=config)
|
280 |
-
self.mlp = VisionExpertMLP(config)
|
281 |
-
self.input_layernorm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
282 |
-
self.post_attention_layernorm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
283 |
-
|
284 |
-
def forward(
|
285 |
-
self,
|
286 |
-
hidden_states: torch.Tensor,
|
287 |
-
token_type_ids: torch.LongTensor,
|
288 |
-
position_ids: torch.LongTensor,
|
289 |
-
attention_mask: Optional[torch.Tensor] = None,
|
290 |
-
past_key_value: Optional[Tuple[torch.Tensor]] = None,
|
291 |
-
output_attentions: Optional[bool] = False,
|
292 |
-
use_cache: Optional[bool] = False,
|
293 |
-
) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
|
294 |
-
residual = hidden_states
|
295 |
-
|
296 |
-
hidden_states = self.input_layernorm(hidden_states)
|
297 |
-
|
298 |
-
# Self Attention
|
299 |
-
hidden_states, self_attn_weights, present_key_value = self.self_attn(
|
300 |
-
hidden_states=hidden_states,
|
301 |
-
token_type_ids=token_type_ids,
|
302 |
-
position_ids=position_ids,
|
303 |
-
attention_mask=attention_mask,
|
304 |
-
past_key_value=past_key_value,
|
305 |
-
output_attentions=output_attentions,
|
306 |
-
use_cache=use_cache,
|
307 |
-
)
|
308 |
-
hidden_states = residual + hidden_states
|
309 |
-
|
310 |
-
# Fully Connected
|
311 |
-
residual = hidden_states
|
312 |
-
hidden_states = self.post_attention_layernorm(hidden_states)
|
313 |
-
hidden_states = self.mlp(hidden_states, token_type_ids=token_type_ids)
|
314 |
-
hidden_states = residual + hidden_states
|
315 |
-
|
316 |
-
outputs = (hidden_states,)
|
317 |
-
|
318 |
-
if output_attentions:
|
319 |
-
outputs += (self_attn_weights,)
|
320 |
-
|
321 |
-
if use_cache:
|
322 |
-
outputs += (present_key_value,)
|
323 |
-
|
324 |
-
return outputs # type: ignore
|
325 |
-
|
326 |
-
|
327 |
-
class CogVLMPreTrainedModel(PreTrainedModel):
|
328 |
-
config_class = CogVLMConfig
|
329 |
-
base_model_prefix = "model"
|
330 |
-
supports_gradient_checkpointing = False
|
331 |
-
_no_split_modules = ["CogVLMDecoderLayer", "TransformerLayer"]
|
332 |
-
_skip_keys_device_placement = "past_key_values"
|
333 |
-
|
334 |
-
def _init_weights(self, module):
|
335 |
-
std = self.config.initializer_range
|
336 |
-
if isinstance(module, nn.Linear):
|
337 |
-
module.weight.data.normal_(mean=0.0, std=std)
|
338 |
-
if module.bias is not None:
|
339 |
-
module.bias.data.zero_()
|
340 |
-
elif isinstance(module, nn.Embedding):
|
341 |
-
module.weight.data.normal_(mean=0.0, std=std)
|
342 |
-
if module.padding_idx is not None:
|
343 |
-
module.weight.data[module.padding_idx].zero_()
|
344 |
-
|
345 |
-
|
346 |
-
def is_empty(images_list: Optional[List[List[torch.Tensor]]]):
|
347 |
-
if images_list is None or len(images_list) == 0:
|
348 |
-
return True
|
349 |
-
for image_list in images_list:
|
350 |
-
if len(image_list):
|
351 |
-
return False
|
352 |
-
return True
|
353 |
-
|
354 |
-
|
355 |
-
def build_position_ids(x: "torch.BoolTensor(B, L)", attention_mask: Optional["torch.BoolTensor(B, L)"] = None) -> "torch.LongTensor(B, L)":
|
356 |
-
if attention_mask is not None:
|
357 |
-
tmp = x.clone()
|
358 |
-
tmp[~(attention_mask.bool())] = -1
|
359 |
-
else:
|
360 |
-
tmp = x.clone()
|
361 |
-
# image boi eoi token as LANGUAGE_TOKEN_TYPE
|
362 |
-
is_boi_eoi = torch.zeros_like(x, dtype=torch.bool)
|
363 |
-
is_boi_eoi[:, 1:] |= (tmp[:, 1:] == VISION_TOKEN_TYPE) & (tmp[:, :-1] == LANGUAGE_TOKEN_TYPE)
|
364 |
-
is_boi_eoi[:, 0] |= (tmp[:, 0] == VISION_TOKEN_TYPE)
|
365 |
-
is_boi_eoi[:, :-1] |= (tmp[:, :-1] == VISION_TOKEN_TYPE) & (tmp[:, 1:] == LANGUAGE_TOKEN_TYPE)
|
366 |
-
is_boi_eoi[:, -1] |= (tmp[:, -1] == VISION_TOKEN_TYPE)
|
367 |
-
tmp[is_boi_eoi] = LANGUAGE_TOKEN_TYPE
|
368 |
-
# final position ids
|
369 |
-
y = torch.zeros_like(x, dtype=torch.long)
|
370 |
-
y[:, 1:] = (tmp[:, 1:] == LANGUAGE_TOKEN_TYPE) | ((tmp[:, 1:] == VISION_TOKEN_TYPE) & (tmp[:, :-1] == LANGUAGE_TOKEN_TYPE))
|
371 |
-
y = y.cumsum(dim=-1)
|
372 |
-
return y
|
373 |
-
|
374 |
-
|
375 |
-
class CogVLMModel(CogVLMPreTrainedModel):
|
376 |
-
def __init__(self, config):
|
377 |
-
super().__init__(config)
|
378 |
-
self.padding_idx = config.pad_token_id
|
379 |
-
self.vocab_size = config.vocab_size
|
380 |
-
|
381 |
-
self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
|
382 |
-
self.layers = nn.ModuleList([CogVLMDecoderLayer(config) for _ in range(config.num_hidden_layers)])
|
383 |
-
self.norm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
384 |
-
|
385 |
-
self.vision = EVA2CLIPModel(config)
|
386 |
-
|
387 |
-
self.gradient_checkpointing = False
|
388 |
-
# Initialize weights and apply final processing
|
389 |
-
self.post_init()
|
390 |
-
|
391 |
-
def encode_images(self, images: List[List[torch.Tensor]]) -> torch.Tensor:
|
392 |
-
images_list, images = images, []
|
393 |
-
|
394 |
-
images = []
|
395 |
-
for image_list in images_list:
|
396 |
-
for image in image_list:
|
397 |
-
images.append(image)
|
398 |
-
|
399 |
-
images = torch.stack(images)
|
400 |
-
images_features = self.vision(images)
|
401 |
-
return images_features
|
402 |
-
|
403 |
-
def forward(
|
404 |
-
self,
|
405 |
-
input_ids: torch.LongTensor = None,
|
406 |
-
images: List[List[torch.Tensor]] = None,
|
407 |
-
token_type_ids: Optional[torch.LongTensor] = None,
|
408 |
-
attention_mask: Optional[torch.Tensor] = None,
|
409 |
-
position_ids: Optional[torch.LongTensor] = None,
|
410 |
-
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
411 |
-
inputs_embeds: Optional[torch.FloatTensor] = None,
|
412 |
-
use_cache: Optional[bool] = None,
|
413 |
-
output_attentions: Optional[bool] = None,
|
414 |
-
output_hidden_states: Optional[bool] = None,
|
415 |
-
return_dict: Optional[bool] = None,
|
416 |
-
) -> Union[Tuple, BaseModelOutputWithPast]:
|
417 |
-
"""take care of image_encode, token_type_ids, position_ids and (attention_mask = None is fine)"""
|
418 |
-
|
419 |
-
if past_key_values is not None:
|
420 |
-
pass # generate mode with past_key_values. the image features are already mapped
|
421 |
-
else:
|
422 |
-
# not allow for inputs_embeds, because we want to process image feature
|
423 |
-
assert input_ids is not None and inputs_embeds is None, f"{input_ids} {inputs_embeds}"
|
424 |
-
if not is_empty(images): # multi-modality
|
425 |
-
assert token_type_ids is not None, f"multi-modality requires `token_type_ids`!"
|
426 |
-
assert len(input_ids) == len(images), f"{len(input_ids)} {len(images)}"
|
427 |
-
inputs_embeds = self.embed_tokens(input_ids)
|
428 |
-
images_features = self.encode_images(images)
|
429 |
-
images_features = rearrange(images_features, 'b n d -> (b n) d')
|
430 |
-
images_features = images_features.to(dtype=inputs_embeds.dtype, device=inputs_embeds.device)
|
431 |
-
inputs_embeds = inputs_embeds.index_put([token_type_ids == VISION_TOKEN_TYPE], images_features)
|
432 |
-
else: # single-modality
|
433 |
-
if token_type_ids is None:
|
434 |
-
token_type_ids = torch.ones_like(input_ids, dtype=torch.long, device=input_ids.device) * LANGUAGE_TOKEN_TYPE
|
435 |
-
assert not (token_type_ids == VISION_TOKEN_TYPE).any(), f"{(token_type_ids == VISION_TOKEN_TYPE).sum()}"
|
436 |
-
inputs_embeds = self.embed_tokens(input_ids)
|
437 |
-
|
438 |
-
if position_ids is None:
|
439 |
-
position_ids = build_position_ids(token_type_ids, attention_mask)
|
440 |
-
input_ids = None
|
441 |
-
|
442 |
-
return self.llm_forward(
|
443 |
-
input_ids=input_ids,
|
444 |
-
token_type_ids=token_type_ids,
|
445 |
-
attention_mask=attention_mask,
|
446 |
-
position_ids=position_ids,
|
447 |
-
past_key_values=past_key_values,
|
448 |
-
inputs_embeds=inputs_embeds,
|
449 |
-
use_cache=use_cache,
|
450 |
-
output_attentions=output_attentions,
|
451 |
-
output_hidden_states=output_hidden_states,
|
452 |
-
return_dict=return_dict,
|
453 |
-
)
|
454 |
-
|
455 |
-
def llm_forward(
|
456 |
-
self,
|
457 |
-
input_ids: torch.LongTensor = None,
|
458 |
-
token_type_ids: torch.LongTensor = None,
|
459 |
-
attention_mask: Optional[torch.Tensor] = None,
|
460 |
-
position_ids: Optional[torch.LongTensor] = None,
|
461 |
-
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
462 |
-
inputs_embeds: Optional[torch.FloatTensor] = None,
|
463 |
-
use_cache: Optional[bool] = None,
|
464 |
-
output_attentions: Optional[bool] = None,
|
465 |
-
output_hidden_states: Optional[bool] = None,
|
466 |
-
return_dict: Optional[bool] = None,
|
467 |
-
) -> Union[Tuple, BaseModelOutputWithPast]:
|
468 |
-
"""largely copy from llama forward and adapt for cogvlm with `token_type_ids`"""
|
469 |
-
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
470 |
-
output_hidden_states = (
|
471 |
-
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
472 |
-
)
|
473 |
-
use_cache = use_cache if use_cache is not None else self.config.use_cache
|
474 |
-
|
475 |
-
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
476 |
-
|
477 |
-
# retrieve input_ids and inputs_embeds
|
478 |
-
if input_ids is not None and inputs_embeds is not None:
|
479 |
-
raise ValueError("You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time")
|
480 |
-
elif input_ids is not None:
|
481 |
-
batch_size, seq_length = input_ids.shape
|
482 |
-
elif inputs_embeds is not None:
|
483 |
-
batch_size, seq_length, _ = inputs_embeds.shape
|
484 |
-
else:
|
485 |
-
raise ValueError("You have to specify either decoder_input_ids or decoder_inputs_embeds")
|
486 |
-
|
487 |
-
seq_length_with_past = seq_length
|
488 |
-
past_key_values_length = 0
|
489 |
-
|
490 |
-
if past_key_values is not None:
|
491 |
-
past_key_values_length = past_key_values[0][0].shape[2]
|
492 |
-
|
493 |
-
|
494 |
-
|
495 |
-
|
496 |
-
|
497 |
-
|
498 |
-
|
499 |
-
|
500 |
-
|
501 |
-
|
502 |
-
|
503 |
-
|
504 |
-
|
505 |
-
|
506 |
-
|
507 |
-
|
508 |
-
|
509 |
-
|
510 |
-
|
511 |
-
|
512 |
-
|
513 |
-
|
514 |
-
|
515 |
-
|
516 |
-
|
517 |
-
|
518 |
-
|
519 |
-
|
520 |
-
|
521 |
-
|
522 |
-
|
523 |
-
|
524 |
-
|
525 |
-
|
526 |
-
|
527 |
-
|
528 |
-
|
529 |
-
|
530 |
-
|
531 |
-
|
532 |
-
|
533 |
-
|
534 |
-
|
535 |
-
|
536 |
-
|
537 |
-
|
538 |
-
|
539 |
-
|
540 |
-
|
541 |
-
|
542 |
-
|
543 |
-
|
544 |
-
|
545 |
-
|
546 |
-
|
547 |
-
|
548 |
-
|
549 |
-
|
550 |
-
if
|
551 |
-
|
552 |
-
|
553 |
-
|
554 |
-
|
555 |
-
|
556 |
-
|
557 |
-
|
558 |
-
|
559 |
-
|
560 |
-
|
561 |
-
|
562 |
-
|
563 |
-
|
564 |
-
|
565 |
-
|
566 |
-
#
|
567 |
-
|
568 |
-
|
569 |
-
#
|
570 |
-
|
571 |
-
|
572 |
-
|
573 |
-
|
574 |
-
|
575 |
-
|
576 |
-
|
577 |
-
|
578 |
-
|
579 |
-
|
580 |
-
|
581 |
-
|
582 |
-
|
583 |
-
|
584 |
-
|
585 |
-
|
586 |
-
|
587 |
-
|
588 |
-
|
589 |
-
|
590 |
-
|
591 |
-
|
592 |
-
|
593 |
-
|
594 |
-
|
595 |
-
|
596 |
-
|
597 |
-
|
598 |
-
|
599 |
-
|
600 |
-
|
601 |
-
|
602 |
-
|
603 |
-
|
604 |
-
|
605 |
-
|
606 |
-
|
607 |
-
|
608 |
-
|
609 |
-
|
610 |
-
|
611 |
-
|
612 |
-
|
613 |
-
|
614 |
-
self.
|
615 |
-
self.
|
616 |
-
|
617 |
-
|
618 |
-
|
619 |
-
|
620 |
-
|
621 |
-
|
622 |
-
|
623 |
-
|
624 |
-
|
625 |
-
|
626 |
-
|
627 |
-
|
628 |
-
|
629 |
-
|
630 |
-
|
631 |
-
|
632 |
-
|
633 |
-
|
634 |
-
|
635 |
-
|
636 |
-
|
637 |
-
|
638 |
-
|
639 |
-
|
640 |
-
|
641 |
-
|
642 |
-
|
643 |
-
|
644 |
-
|
645 |
-
|
646 |
-
|
647 |
-
|
648 |
-
|
649 |
-
|
650 |
-
|
651 |
-
|
652 |
-
|
653 |
-
|
654 |
-
|
655 |
-
|
656 |
-
|
657 |
-
|
658 |
-
|
659 |
-
|
660 |
-
outputs
|
661 |
-
|
662 |
-
|
663 |
-
|
664 |
-
|
665 |
-
|
666 |
-
|
667 |
-
|
668 |
-
|
669 |
-
|
670 |
-
|
671 |
-
|
672 |
-
|
673 |
-
|
674 |
-
|
675 |
-
|
676 |
-
logits =
|
677 |
-
|
678 |
-
|
679 |
-
|
680 |
-
|
681 |
-
|
682 |
-
|
683 |
-
|
684 |
-
|
685 |
-
|
686 |
-
|
687 |
-
|
688 |
-
|
689 |
-
|
690 |
-
|
691 |
-
|
692 |
-
|
693 |
-
|
694 |
-
|
695 |
-
|
696 |
-
|
697 |
-
|
698 |
-
|
699 |
-
|
700 |
-
|
701 |
-
|
702 |
-
|
703 |
-
|
704 |
-
|
705 |
-
|
706 |
-
|
707 |
-
|
708 |
-
|
709 |
-
|
710 |
-
|
711 |
-
|
712 |
-
|
713 |
-
|
714 |
-
|
715 |
-
|
716 |
-
|
717 |
-
|
718 |
-
|
719 |
-
|
720 |
-
|
721 |
-
|
722 |
-
|
723 |
-
|
724 |
-
|
725 |
-
if inputs_embeds
|
726 |
-
|
727 |
-
|
728 |
-
|
729 |
-
|
730 |
-
|
731 |
-
|
732 |
-
|
733 |
-
"
|
734 |
-
"
|
735 |
-
"
|
736 |
-
"
|
737 |
-
"
|
738 |
-
|
739 |
-
|
740 |
-
|
741 |
-
|
742 |
-
|
743 |
-
|
744 |
-
|
745 |
-
|
746 |
-
|
747 |
-
|
748 |
-
|
749 |
-
|
750 |
-
|
751 |
-
|
752 |
-
|
753 |
-
|
754 |
-
|
755 |
-
|
756 |
-
|
757 |
-
|
758 |
-
|
759 |
-
|
760 |
-
|
761 |
-
|
762 |
-
|
763 |
-
|
764 |
-
|
765 |
-
|
766 |
-
|
767 |
-
model_kwargs["attention_mask"]
|
768 |
-
|
769 |
-
|
770 |
-
|
771 |
-
|
772 |
-
|
773 |
-
|
774 |
-
model_kwargs["decoder_attention_mask"]
|
775 |
-
|
776 |
-
|
777 |
-
|
778 |
-
|
779 |
-
|
780 |
-
|
781 |
-
|
782 |
-
|
783 |
-
|
784 |
-
|
785 |
-
|
786 |
-
|
787 |
-
|
788 |
-
|
789 |
-
|
790 |
-
|
791 |
-
|
792 |
-
|
793 |
-
|
794 |
-
|
795 |
-
|
796 |
-
|
797 |
-
|
798 |
-
|
799 |
-
|
800 |
-
|
801 |
-
|
802 |
-
|
803 |
-
|
804 |
-
|
805 |
-
|
806 |
-
|
807 |
-
|
808 |
-
|
809 |
-
|
810 |
-
|
811 |
-
|
812 |
-
|
813 |
-
|
814 |
-
|
815 |
-
transforms.
|
816 |
-
|
817 |
-
|
818 |
-
|
819 |
-
|
820 |
-
|
821 |
-
|
822 |
-
|
823 |
-
|
824 |
-
|
825 |
-
|
826 |
-
|
827 |
-
|
828 |
-
|
829 |
-
|
830 |
-
|
831 |
-
'
|
832 |
-
'
|
833 |
-
'
|
834 |
-
|
|
|
|
1 |
+
"""largely copy from llama and adapt for cogvlm"""
|
2 |
+
import warnings
|
3 |
+
from typing import TYPE_CHECKING, Optional, Tuple, List, Union, Literal, Dict, Any
|
4 |
+
|
5 |
+
import math
|
6 |
+
import torch
|
7 |
+
from torch import nn
|
8 |
+
from torch.nn import functional as F
|
9 |
+
from torch.nn import CrossEntropyLoss
|
10 |
+
from torchvision import transforms
|
11 |
+
from einops import rearrange
|
12 |
+
|
13 |
+
from transformers import PreTrainedModel, PreTrainedTokenizer
|
14 |
+
from transformers.utils.logging import get_logger
|
15 |
+
from transformers.activations import ACT2FN
|
16 |
+
from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast
|
17 |
+
|
18 |
+
from .configuration_cogvlm import CogVLMConfig
|
19 |
+
from .visual import EVA2CLIPModel
|
20 |
+
|
21 |
+
if TYPE_CHECKING:
|
22 |
+
from transformers.utils import ModelOutput
|
23 |
+
|
24 |
+
logger = get_logger(__name__)
|
25 |
+
|
26 |
+
LANGUAGE_TOKEN_TYPE = 0
|
27 |
+
VISION_TOKEN_TYPE = 1
|
28 |
+
|
29 |
+
|
30 |
+
# Copied from transformers.models.bart.modeling_bart._make_causal_mask
|
31 |
+
def _make_causal_mask(
|
32 |
+
input_ids_shape: torch.Size, dtype: torch.dtype, device: torch.device, past_key_values_length: int = 0
|
33 |
+
):
|
34 |
+
"""
|
35 |
+
Make causal mask used for bi-directional self-attention.
|
36 |
+
"""
|
37 |
+
bsz, tgt_len = input_ids_shape
|
38 |
+
mask = torch.full((tgt_len, tgt_len), torch.finfo(dtype).min, device=device)
|
39 |
+
mask_cond = torch.arange(mask.size(-1), device=device)
|
40 |
+
mask.masked_fill_(mask_cond < (mask_cond + 1).view(mask.size(-1), 1), 0)
|
41 |
+
mask = mask.to(dtype)
|
42 |
+
|
43 |
+
if past_key_values_length > 0:
|
44 |
+
mask = torch.cat([torch.zeros(tgt_len, past_key_values_length, dtype=dtype, device=device), mask], dim=-1)
|
45 |
+
return mask[None, None, :, :].expand(bsz, 1, tgt_len, tgt_len + past_key_values_length)
|
46 |
+
|
47 |
+
|
48 |
+
# Copied from transformers.models.bart.modeling_bart._expand_mask
|
49 |
+
def _expand_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None):
|
50 |
+
"""
|
51 |
+
Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`.
|
52 |
+
"""
|
53 |
+
bsz, src_len = mask.size()
|
54 |
+
tgt_len = tgt_len if tgt_len is not None else src_len
|
55 |
+
|
56 |
+
expanded_mask = mask[:, None, None, :].expand(bsz, 1, tgt_len, src_len).to(dtype)
|
57 |
+
|
58 |
+
inverted_mask = 1.0 - expanded_mask
|
59 |
+
|
60 |
+
return inverted_mask.masked_fill(inverted_mask.to(torch.bool), torch.finfo(dtype).min)
|
61 |
+
|
62 |
+
|
63 |
+
class RMSNorm(nn.Module):
|
64 |
+
def __init__(self, hidden_size, eps=1e-6):
|
65 |
+
super().__init__()
|
66 |
+
self.weight = nn.Parameter(torch.ones(hidden_size))
|
67 |
+
self.variance_epsilon = eps
|
68 |
+
|
69 |
+
def forward(self, hidden_states):
|
70 |
+
input_dtype = hidden_states.dtype
|
71 |
+
hidden_states = hidden_states.to(torch.float32)
|
72 |
+
variance = hidden_states.pow(2).mean(-1, keepdim=True)
|
73 |
+
hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
|
74 |
+
return (self.weight * hidden_states).to(input_dtype)
|
75 |
+
|
76 |
+
|
77 |
+
class MLP(nn.Module):
|
78 |
+
def __init__(self, config):
|
79 |
+
super().__init__()
|
80 |
+
self.hidden_size = config.hidden_size
|
81 |
+
self.intermediate_size = config.intermediate_size
|
82 |
+
self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
|
83 |
+
self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
|
84 |
+
self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
|
85 |
+
self.act_fn = ACT2FN[config.hidden_act]
|
86 |
+
|
87 |
+
def forward(self, x):
|
88 |
+
down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
|
89 |
+
return down_proj
|
90 |
+
|
91 |
+
|
92 |
+
def get_expert_mask(token_type_ids: "torch.LongTensor(B, L)") -> "[torch.BoolTensor(B, L), torch.BoolTensor(B, L)]":
|
93 |
+
vision_token_mask = torch.zeros_like(token_type_ids, dtype=torch.bool)
|
94 |
+
vision_token_mask[:, :-1] = (token_type_ids[:, :-1] == VISION_TOKEN_TYPE) & (token_type_ids[:, 1:] == VISION_TOKEN_TYPE)
|
95 |
+
language_token_mask = ~vision_token_mask
|
96 |
+
return vision_token_mask, language_token_mask
|
97 |
+
|
98 |
+
|
99 |
+
class VisionExpertMLP(nn.Module):
|
100 |
+
def __init__(self, config):
|
101 |
+
super().__init__()
|
102 |
+
self.language_mlp = MLP(config)
|
103 |
+
self.vision_mlp = MLP(config)
|
104 |
+
|
105 |
+
def forward(self, hidden_states: "torch.Tensor(B, L, D)", token_type_ids: "torch.LongTensor(B, L)"):
|
106 |
+
output = torch.empty(hidden_states.shape, dtype=hidden_states.dtype, device=hidden_states.device)
|
107 |
+
vision_token_mask, language_token_mask = get_expert_mask(token_type_ids)
|
108 |
+
output[vision_token_mask] = self.vision_mlp(hidden_states[vision_token_mask])
|
109 |
+
output[language_token_mask] = self.language_mlp(hidden_states[language_token_mask])
|
110 |
+
return output
|
111 |
+
|
112 |
+
|
113 |
+
def attention_fn(
|
114 |
+
query_layer: "torch.tensor(B, H, L, HD)",
|
115 |
+
key_layer: "torch.tensor(B, H, L, HD)",
|
116 |
+
value_layer: "torch.tensor(B, H, L, HD)",
|
117 |
+
attention_mask: "torch.tensor(B, H, L, HD)",
|
118 |
+
*,
|
119 |
+
scaling_attention_score: bool = True,
|
120 |
+
attention_dropout: nn.Module = None
|
121 |
+
):
|
122 |
+
attention_mask_bool = (attention_mask == 0)
|
123 |
+
is_low_triangle = (attention_mask_bool == torch.ones_like(attention_mask_bool, dtype=torch.float).tril()).all()
|
124 |
+
is_full = (attention_mask_bool > 0).all()
|
125 |
+
if not (int(torch.__version__.split('.')[0]) >= 2):
|
126 |
+
warnings.warn("It's recommended to use torch2.0 or higher.")
|
127 |
+
if int(torch.__version__.split('.')[0]) >= 2 and scaling_attention_score and (is_full or is_low_triangle):
|
128 |
+
dropout_p = 0. if attention_dropout is None or not attention_dropout.training else attention_dropout.p
|
129 |
+
return torch.nn.functional.scaled_dot_product_attention(
|
130 |
+
query_layer, key_layer, value_layer,
|
131 |
+
attn_mask=None,
|
132 |
+
dropout_p=dropout_p,
|
133 |
+
is_causal=not is_full
|
134 |
+
)
|
135 |
+
else:
|
136 |
+
if scaling_attention_score:
|
137 |
+
query_layer = query_layer / math.sqrt(query_layer.shape[-1])
|
138 |
+
attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2))
|
139 |
+
attention_scores = attention_scores + attention_mask
|
140 |
+
attention_scores = nn.functional.softmax(attention_scores, dim=-1, dtype=torch.float32).to(query_layer.dtype)
|
141 |
+
if attention_dropout is not None:
|
142 |
+
attention_scores = attention_dropout(attention_scores)
|
143 |
+
context_layer = torch.matmul(attention_scores, value_layer)
|
144 |
+
return context_layer
|
145 |
+
|
146 |
+
|
147 |
+
class RotaryEmbedding(torch.nn.Module):
|
148 |
+
def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
|
149 |
+
super().__init__()
|
150 |
+
|
151 |
+
self.dim = dim
|
152 |
+
self.max_position_embeddings = max_position_embeddings
|
153 |
+
self.base = base
|
154 |
+
inv_freq = self._compute_inv_freq(device)
|
155 |
+
self.register_buffer("inv_freq", inv_freq)
|
156 |
+
self.max_seq_len_cached = 0
|
157 |
+
|
158 |
+
def _compute_inv_freq(self, device=None):
|
159 |
+
return 1.0 / (
|
160 |
+
self.base
|
161 |
+
** (torch.arange(0, self.dim, 2, device=device) / self.dim)
|
162 |
+
)
|
163 |
+
|
164 |
+
def _set_cos_sin_cache(self, seq_len, device, dtype):
|
165 |
+
self.max_seq_len_cached = seq_len
|
166 |
+
t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
|
167 |
+
|
168 |
+
freqs = torch.einsum("i,j->ij", t, self.inv_freq)
|
169 |
+
# Different from paper, but it uses a different permutation in order to obtain the same calculation
|
170 |
+
emb = torch.cat((freqs, freqs), dim=-1)
|
171 |
+
self.register_buffer("cos_cached", emb.cos()[:, None, :].to(dtype), persistent=False)
|
172 |
+
self.register_buffer("sin_cached", emb.sin()[:, None, :].to(dtype), persistent=False)
|
173 |
+
|
174 |
+
def forward(self, x, seq_len):
|
175 |
+
# x: [bs, num_attention_heads, seq_len, head_size]
|
176 |
+
if seq_len > self.max_seq_len_cached:
|
177 |
+
self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=x.dtype)
|
178 |
+
|
179 |
+
return (
|
180 |
+
self.cos_cached[:seq_len, ...].to(dtype=x.dtype),
|
181 |
+
self.sin_cached[:seq_len, ...].to(dtype=x.dtype),
|
182 |
+
)
|
183 |
+
|
184 |
+
|
185 |
+
def rotate_half(x):
|
186 |
+
x1, x2 = x[..., :x.shape[-1] // 2], x[..., x.shape[-1] // 2:]
|
187 |
+
return torch.cat((-x2, x1), dim=x1.ndim - 1)
|
188 |
+
|
189 |
+
|
190 |
+
def apply_rotary_pos_emb_index_bhs(q, k, cos, sin, position_id):
|
191 |
+
# batch_size, num_head, seq_len, hidden_size
|
192 |
+
cos, sin = F.embedding(position_id, cos.squeeze(1)).unsqueeze(1), \
|
193 |
+
F.embedding(position_id, sin.squeeze(1)).unsqueeze(1)
|
194 |
+
q, k = (q * cos) + (rotate_half(q) * sin), (k * cos) + (rotate_half(k) * sin)
|
195 |
+
return q, k
|
196 |
+
|
197 |
+
|
198 |
+
class VisionExpertAttention(nn.Module):
|
199 |
+
def __init__(self, config):
|
200 |
+
super().__init__()
|
201 |
+
self.config = config
|
202 |
+
self.hidden_size = config.hidden_size
|
203 |
+
self.num_heads = config.num_attention_heads
|
204 |
+
self.head_dim = self.hidden_size // self.num_heads
|
205 |
+
self.max_position_embeddings = config.max_position_embeddings
|
206 |
+
|
207 |
+
self.rotary_emb = RotaryEmbedding(self.head_dim)
|
208 |
+
self.vision_expert_query_key_value = nn.Linear(self.hidden_size, self.hidden_size * 3, bias=False)
|
209 |
+
self.vision_expert_dense = nn.Linear(self.hidden_size, self.hidden_size, bias=False)
|
210 |
+
self.language_expert_query_key_value = nn.Linear(self.hidden_size, self.hidden_size * 3, bias=False)
|
211 |
+
self.language_expert_dense = nn.Linear(self.hidden_size, self.hidden_size, bias=False)
|
212 |
+
|
213 |
+
def _transpose_for_scores(self, tensor):
|
214 |
+
"""Transpose a 3D tensor [B, L, H*HD] into a 4D tensor with size [B H L HD]."""
|
215 |
+
new_tensor_shape = tensor.size()[:-1] + (self.num_heads, self.head_dim)
|
216 |
+
tensor = tensor.view(*new_tensor_shape)
|
217 |
+
return tensor.permute(0, 2, 1, 3)
|
218 |
+
|
219 |
+
def forward(
|
220 |
+
self,
|
221 |
+
hidden_states: torch.Tensor,
|
222 |
+
token_type_ids: torch.LongTensor,
|
223 |
+
position_ids: torch.LongTensor,
|
224 |
+
attention_mask: Optional[torch.Tensor] = None,
|
225 |
+
past_key_value: Optional[Tuple[torch.Tensor]] = None,
|
226 |
+
output_attentions: bool = False,
|
227 |
+
use_cache: bool = False,
|
228 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
229 |
+
bsz, q_len, _ = hidden_states.size()
|
230 |
+
vision_token_mask, language_token_mask = get_expert_mask(token_type_ids)
|
231 |
+
|
232 |
+
shape = list(hidden_states.shape)
|
233 |
+
shape[-1] = shape[-1] * 3
|
234 |
+
mixed_raw_layer = torch.empty(shape, dtype=hidden_states.dtype, device=hidden_states.device)
|
235 |
+
mixed_raw_layer[vision_token_mask] = self.vision_expert_query_key_value(hidden_states[vision_token_mask])
|
236 |
+
mixed_raw_layer[language_token_mask] = self.language_expert_query_key_value(hidden_states[language_token_mask])
|
237 |
+
|
238 |
+
query_states, key_states, value_states = torch.split(mixed_raw_layer, self.hidden_size, dim=-1)
|
239 |
+
query_states = self._transpose_for_scores(query_states) # B, H, L, HD
|
240 |
+
key_states = self._transpose_for_scores(key_states) # B, H, L, HD
|
241 |
+
value_states = self._transpose_for_scores(value_states) # B, H, L, HD
|
242 |
+
|
243 |
+
kv_seq_len = key_states.shape[-2]
|
244 |
+
if past_key_value is not None:
|
245 |
+
kv_seq_len += past_key_value[0].shape[-2]
|
246 |
+
cos, sin = self.rotary_emb(value_states, seq_len=position_ids.max() + 1)
|
247 |
+
query_states, key_states = apply_rotary_pos_emb_index_bhs(query_states, key_states, cos, sin, position_ids)
|
248 |
+
|
249 |
+
if past_key_value is not None:
|
250 |
+
key_states = torch.cat([past_key_value[0], key_states], dim=2)
|
251 |
+
value_states = torch.cat([past_key_value[1], value_states], dim=2)
|
252 |
+
|
253 |
+
past_key_value = (key_states, value_states) if use_cache else None
|
254 |
+
|
255 |
+
context_layer = attention_fn(
|
256 |
+
query_layer=query_states, key_layer=key_states, value_layer=value_states, attention_mask=attention_mask,
|
257 |
+
scaling_attention_score=True, attention_dropout=None)
|
258 |
+
if context_layer.size() != (bsz, self.num_heads, q_len, self.head_dim):
|
259 |
+
raise ValueError(
|
260 |
+
f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
|
261 |
+
f" {context_layer.size()}"
|
262 |
+
)
|
263 |
+
context_layer = context_layer.transpose(1, 2).contiguous().reshape(bsz, q_len, self.hidden_size)
|
264 |
+
|
265 |
+
attn_output = torch.empty(context_layer.shape, dtype=hidden_states.dtype, device=hidden_states.device)
|
266 |
+
attn_output[vision_token_mask] = self.vision_expert_dense(context_layer[vision_token_mask])
|
267 |
+
attn_output[language_token_mask] = self.language_expert_dense(context_layer[language_token_mask])
|
268 |
+
|
269 |
+
if output_attentions:
|
270 |
+
warnings.warn("output_attentions is not implemented.")
|
271 |
+
|
272 |
+
return attn_output, None, past_key_value
|
273 |
+
|
274 |
+
|
275 |
+
class CogVLMDecoderLayer(nn.Module):
|
276 |
+
def __init__(self, config):
|
277 |
+
super().__init__()
|
278 |
+
self.hidden_size = config.hidden_size
|
279 |
+
self.self_attn = VisionExpertAttention(config=config)
|
280 |
+
self.mlp = VisionExpertMLP(config)
|
281 |
+
self.input_layernorm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
282 |
+
self.post_attention_layernorm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
283 |
+
|
284 |
+
def forward(
|
285 |
+
self,
|
286 |
+
hidden_states: torch.Tensor,
|
287 |
+
token_type_ids: torch.LongTensor,
|
288 |
+
position_ids: torch.LongTensor,
|
289 |
+
attention_mask: Optional[torch.Tensor] = None,
|
290 |
+
past_key_value: Optional[Tuple[torch.Tensor]] = None,
|
291 |
+
output_attentions: Optional[bool] = False,
|
292 |
+
use_cache: Optional[bool] = False,
|
293 |
+
) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
|
294 |
+
residual = hidden_states
|
295 |
+
|
296 |
+
hidden_states = self.input_layernorm(hidden_states)
|
297 |
+
|
298 |
+
# Self Attention
|
299 |
+
hidden_states, self_attn_weights, present_key_value = self.self_attn(
|
300 |
+
hidden_states=hidden_states,
|
301 |
+
token_type_ids=token_type_ids,
|
302 |
+
position_ids=position_ids,
|
303 |
+
attention_mask=attention_mask,
|
304 |
+
past_key_value=past_key_value,
|
305 |
+
output_attentions=output_attentions,
|
306 |
+
use_cache=use_cache,
|
307 |
+
)
|
308 |
+
hidden_states = residual + hidden_states
|
309 |
+
|
310 |
+
# Fully Connected
|
311 |
+
residual = hidden_states
|
312 |
+
hidden_states = self.post_attention_layernorm(hidden_states)
|
313 |
+
hidden_states = self.mlp(hidden_states, token_type_ids=token_type_ids)
|
314 |
+
hidden_states = residual + hidden_states
|
315 |
+
|
316 |
+
outputs = (hidden_states,)
|
317 |
+
|
318 |
+
if output_attentions:
|
319 |
+
outputs += (self_attn_weights,)
|
320 |
+
|
321 |
+
if use_cache:
|
322 |
+
outputs += (present_key_value,)
|
323 |
+
|
324 |
+
return outputs # type: ignore
|
325 |
+
|
326 |
+
|
327 |
+
class CogVLMPreTrainedModel(PreTrainedModel):
|
328 |
+
config_class = CogVLMConfig
|
329 |
+
base_model_prefix = "model"
|
330 |
+
supports_gradient_checkpointing = False
|
331 |
+
_no_split_modules = ["CogVLMDecoderLayer", "TransformerLayer"]
|
332 |
+
_skip_keys_device_placement = "past_key_values"
|
333 |
+
|
334 |
+
def _init_weights(self, module):
|
335 |
+
std = self.config.initializer_range
|
336 |
+
if isinstance(module, nn.Linear):
|
337 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
338 |
+
if module.bias is not None:
|
339 |
+
module.bias.data.zero_()
|
340 |
+
elif isinstance(module, nn.Embedding):
|
341 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
342 |
+
if module.padding_idx is not None:
|
343 |
+
module.weight.data[module.padding_idx].zero_()
|
344 |
+
|
345 |
+
|
346 |
+
def is_empty(images_list: Optional[List[List[torch.Tensor]]]):
|
347 |
+
if images_list is None or len(images_list) == 0:
|
348 |
+
return True
|
349 |
+
for image_list in images_list:
|
350 |
+
if len(image_list):
|
351 |
+
return False
|
352 |
+
return True
|
353 |
+
|
354 |
+
|
355 |
+
def build_position_ids(x: "torch.BoolTensor(B, L)", attention_mask: Optional["torch.BoolTensor(B, L)"] = None) -> "torch.LongTensor(B, L)":
|
356 |
+
if attention_mask is not None:
|
357 |
+
tmp = x.clone()
|
358 |
+
tmp[~(attention_mask.bool())] = -1
|
359 |
+
else:
|
360 |
+
tmp = x.clone()
|
361 |
+
# image boi eoi token as LANGUAGE_TOKEN_TYPE
|
362 |
+
is_boi_eoi = torch.zeros_like(x, dtype=torch.bool)
|
363 |
+
is_boi_eoi[:, 1:] |= (tmp[:, 1:] == VISION_TOKEN_TYPE) & (tmp[:, :-1] == LANGUAGE_TOKEN_TYPE)
|
364 |
+
is_boi_eoi[:, 0] |= (tmp[:, 0] == VISION_TOKEN_TYPE)
|
365 |
+
is_boi_eoi[:, :-1] |= (tmp[:, :-1] == VISION_TOKEN_TYPE) & (tmp[:, 1:] == LANGUAGE_TOKEN_TYPE)
|
366 |
+
is_boi_eoi[:, -1] |= (tmp[:, -1] == VISION_TOKEN_TYPE)
|
367 |
+
tmp[is_boi_eoi] = LANGUAGE_TOKEN_TYPE
|
368 |
+
# final position ids
|
369 |
+
y = torch.zeros_like(x, dtype=torch.long)
|
370 |
+
y[:, 1:] = (tmp[:, 1:] == LANGUAGE_TOKEN_TYPE) | ((tmp[:, 1:] == VISION_TOKEN_TYPE) & (tmp[:, :-1] == LANGUAGE_TOKEN_TYPE))
|
371 |
+
y = y.cumsum(dim=-1)
|
372 |
+
return y
|
373 |
+
|
374 |
+
|
375 |
+
class CogVLMModel(CogVLMPreTrainedModel):
|
376 |
+
def __init__(self, config):
|
377 |
+
super().__init__(config)
|
378 |
+
self.padding_idx = config.pad_token_id
|
379 |
+
self.vocab_size = config.vocab_size
|
380 |
+
|
381 |
+
self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
|
382 |
+
self.layers = nn.ModuleList([CogVLMDecoderLayer(config) for _ in range(config.num_hidden_layers)])
|
383 |
+
self.norm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
384 |
+
|
385 |
+
self.vision = EVA2CLIPModel(config)
|
386 |
+
|
387 |
+
self.gradient_checkpointing = False
|
388 |
+
# Initialize weights and apply final processing
|
389 |
+
self.post_init()
|
390 |
+
|
391 |
+
def encode_images(self, images: List[List[torch.Tensor]]) -> torch.Tensor:
|
392 |
+
images_list, images = images, []
|
393 |
+
|
394 |
+
images = []
|
395 |
+
for image_list in images_list:
|
396 |
+
for image in image_list:
|
397 |
+
images.append(image)
|
398 |
+
|
399 |
+
images = torch.stack(images)
|
400 |
+
images_features = self.vision(images)
|
401 |
+
return images_features
|
402 |
+
|
403 |
+
def forward(
|
404 |
+
self,
|
405 |
+
input_ids: torch.LongTensor = None,
|
406 |
+
images: List[List[torch.Tensor]] = None,
|
407 |
+
token_type_ids: Optional[torch.LongTensor] = None,
|
408 |
+
attention_mask: Optional[torch.Tensor] = None,
|
409 |
+
position_ids: Optional[torch.LongTensor] = None,
|
410 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
411 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
412 |
+
use_cache: Optional[bool] = None,
|
413 |
+
output_attentions: Optional[bool] = None,
|
414 |
+
output_hidden_states: Optional[bool] = None,
|
415 |
+
return_dict: Optional[bool] = None,
|
416 |
+
) -> Union[Tuple, BaseModelOutputWithPast]:
|
417 |
+
"""take care of image_encode, token_type_ids, position_ids and (attention_mask = None is fine)"""
|
418 |
+
|
419 |
+
if past_key_values is not None:
|
420 |
+
pass # generate mode with past_key_values. the image features are already mapped
|
421 |
+
else:
|
422 |
+
# not allow for inputs_embeds, because we want to process image feature
|
423 |
+
assert input_ids is not None and inputs_embeds is None, f"{input_ids} {inputs_embeds}"
|
424 |
+
if not is_empty(images): # multi-modality
|
425 |
+
assert token_type_ids is not None, f"multi-modality requires `token_type_ids`!"
|
426 |
+
assert len(input_ids) == len(images), f"{len(input_ids)} {len(images)}"
|
427 |
+
inputs_embeds = self.embed_tokens(input_ids)
|
428 |
+
images_features = self.encode_images(images)
|
429 |
+
images_features = rearrange(images_features, 'b n d -> (b n) d')
|
430 |
+
images_features = images_features.to(dtype=inputs_embeds.dtype, device=inputs_embeds.device)
|
431 |
+
inputs_embeds = inputs_embeds.index_put([token_type_ids == VISION_TOKEN_TYPE], images_features)
|
432 |
+
else: # single-modality
|
433 |
+
if token_type_ids is None:
|
434 |
+
token_type_ids = torch.ones_like(input_ids, dtype=torch.long, device=input_ids.device) * LANGUAGE_TOKEN_TYPE
|
435 |
+
assert not (token_type_ids == VISION_TOKEN_TYPE).any(), f"{(token_type_ids == VISION_TOKEN_TYPE).sum()}"
|
436 |
+
inputs_embeds = self.embed_tokens(input_ids)
|
437 |
+
|
438 |
+
if position_ids is None:
|
439 |
+
position_ids = build_position_ids(token_type_ids, attention_mask)
|
440 |
+
input_ids = None
|
441 |
+
|
442 |
+
return self.llm_forward(
|
443 |
+
input_ids=input_ids,
|
444 |
+
token_type_ids=token_type_ids,
|
445 |
+
attention_mask=attention_mask,
|
446 |
+
position_ids=position_ids,
|
447 |
+
past_key_values=past_key_values,
|
448 |
+
inputs_embeds=inputs_embeds,
|
449 |
+
use_cache=use_cache,
|
450 |
+
output_attentions=output_attentions,
|
451 |
+
output_hidden_states=output_hidden_states,
|
452 |
+
return_dict=return_dict,
|
453 |
+
)
|
454 |
+
|
455 |
+
def llm_forward(
|
456 |
+
self,
|
457 |
+
input_ids: torch.LongTensor = None,
|
458 |
+
token_type_ids: torch.LongTensor = None,
|
459 |
+
attention_mask: Optional[torch.Tensor] = None,
|
460 |
+
position_ids: Optional[torch.LongTensor] = None,
|
461 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
462 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
463 |
+
use_cache: Optional[bool] = None,
|
464 |
+
output_attentions: Optional[bool] = None,
|
465 |
+
output_hidden_states: Optional[bool] = None,
|
466 |
+
return_dict: Optional[bool] = None,
|
467 |
+
) -> Union[Tuple, BaseModelOutputWithPast]:
|
468 |
+
"""largely copy from llama forward and adapt for cogvlm with `token_type_ids`"""
|
469 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
470 |
+
output_hidden_states = (
|
471 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
472 |
+
)
|
473 |
+
use_cache = use_cache if use_cache is not None else self.config.use_cache
|
474 |
+
|
475 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
476 |
+
|
477 |
+
# retrieve input_ids and inputs_embeds
|
478 |
+
if input_ids is not None and inputs_embeds is not None:
|
479 |
+
raise ValueError("You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time")
|
480 |
+
elif input_ids is not None:
|
481 |
+
batch_size, seq_length = input_ids.shape
|
482 |
+
elif inputs_embeds is not None:
|
483 |
+
batch_size, seq_length, _ = inputs_embeds.shape
|
484 |
+
else:
|
485 |
+
raise ValueError("You have to specify either decoder_input_ids or decoder_inputs_embeds")
|
486 |
+
|
487 |
+
seq_length_with_past = seq_length
|
488 |
+
past_key_values_length = 0
|
489 |
+
|
490 |
+
if past_key_values is not None:
|
491 |
+
past_key_values_length = past_key_values[1][0][0].shape[2]
|
492 |
+
|
493 |
+
seq_length_with_past = seq_length_with_past + past_key_values_length
|
494 |
+
|
495 |
+
if position_ids is None:
|
496 |
+
device = input_ids.device if input_ids is not None else inputs_embeds.device
|
497 |
+
position_ids = torch.arange(
|
498 |
+
past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device
|
499 |
+
)
|
500 |
+
position_ids = position_ids.unsqueeze(0).view(-1, seq_length)
|
501 |
+
else:
|
502 |
+
position_ids = position_ids.view(-1, seq_length).long()
|
503 |
+
|
504 |
+
if inputs_embeds is None:
|
505 |
+
inputs_embeds = self.embed_tokens(input_ids)
|
506 |
+
# embed positions
|
507 |
+
if attention_mask is None:
|
508 |
+
attention_mask = torch.ones(
|
509 |
+
(batch_size, seq_length_with_past), dtype=torch.bool, device=inputs_embeds.device
|
510 |
+
)
|
511 |
+
attention_mask = self._prepare_decoder_attention_mask(
|
512 |
+
attention_mask, (batch_size, seq_length), inputs_embeds, past_key_values_length
|
513 |
+
)
|
514 |
+
|
515 |
+
hidden_states = inputs_embeds
|
516 |
+
|
517 |
+
# decoder layers
|
518 |
+
all_hidden_states = () if output_hidden_states else None
|
519 |
+
all_self_attns = () if output_attentions else None
|
520 |
+
next_decoder_cache = () if use_cache else None
|
521 |
+
|
522 |
+
for idx, decoder_layer in enumerate(self.layers):
|
523 |
+
if output_hidden_states:
|
524 |
+
all_hidden_states += (hidden_states,)
|
525 |
+
|
526 |
+
past_key_value = past_key_values[1][idx] if past_key_values is not None else None
|
527 |
+
layer_outputs = decoder_layer(
|
528 |
+
hidden_states,
|
529 |
+
token_type_ids=token_type_ids,
|
530 |
+
attention_mask=attention_mask,
|
531 |
+
position_ids=position_ids,
|
532 |
+
past_key_value=past_key_value,
|
533 |
+
output_attentions=output_attentions,
|
534 |
+
use_cache=use_cache,
|
535 |
+
)
|
536 |
+
hidden_states = layer_outputs[0]
|
537 |
+
|
538 |
+
if use_cache:
|
539 |
+
next_decoder_cache += (layer_outputs[2 if output_attentions else 1],)
|
540 |
+
|
541 |
+
if output_attentions:
|
542 |
+
all_self_attns += (layer_outputs[1],)
|
543 |
+
|
544 |
+
hidden_states = self.norm(hidden_states)
|
545 |
+
|
546 |
+
# add hidden states from the last decoder layer
|
547 |
+
if output_hidden_states:
|
548 |
+
all_hidden_states += (hidden_states,)
|
549 |
+
|
550 |
+
next_cache = next_decoder_cache if use_cache else None
|
551 |
+
if not return_dict:
|
552 |
+
return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
|
553 |
+
return BaseModelOutputWithPast(
|
554 |
+
last_hidden_state=hidden_states,
|
555 |
+
past_key_values=next_cache,
|
556 |
+
hidden_states=all_hidden_states,
|
557 |
+
attentions=all_self_attns,
|
558 |
+
)
|
559 |
+
|
560 |
+
def get_input_embeddings(self):
|
561 |
+
return self.embed_tokens
|
562 |
+
|
563 |
+
def set_input_embeddings(self, value):
|
564 |
+
self.embed_tokens = value
|
565 |
+
|
566 |
+
# noinspection PyMethodMayBeStatic
|
567 |
+
# Copied from transformers.models.bart.modeling_bart.BartDecoder._prepare_decoder_attention_mask
|
568 |
+
def _prepare_decoder_attention_mask(self, attention_mask, input_shape, inputs_embeds, past_key_values_length):
|
569 |
+
# create causal mask
|
570 |
+
# [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
|
571 |
+
combined_attention_mask = None
|
572 |
+
if input_shape[-1] > 1:
|
573 |
+
combined_attention_mask = _make_causal_mask(
|
574 |
+
input_shape,
|
575 |
+
inputs_embeds.dtype,
|
576 |
+
device=inputs_embeds.device,
|
577 |
+
past_key_values_length=past_key_values_length,
|
578 |
+
)
|
579 |
+
|
580 |
+
if attention_mask is not None:
|
581 |
+
# [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
|
582 |
+
expanded_attn_mask = _expand_mask(attention_mask, inputs_embeds.dtype, tgt_len=input_shape[-1]).to(
|
583 |
+
inputs_embeds.device
|
584 |
+
)
|
585 |
+
combined_attention_mask = (
|
586 |
+
expanded_attn_mask if combined_attention_mask is None else expanded_attn_mask + combined_attention_mask
|
587 |
+
)
|
588 |
+
|
589 |
+
return combined_attention_mask
|
590 |
+
|
591 |
+
|
592 |
+
def _history_to_prompt(signal_type, history, query):
|
593 |
+
if signal_type == 'base':
|
594 |
+
return query
|
595 |
+
elif signal_type == 'vqa':
|
596 |
+
answer_format = 'Short answer:'
|
597 |
+
elif signal_type == 'chat':
|
598 |
+
answer_format = 'Answer:'
|
599 |
+
else:
|
600 |
+
assert False, f"Unknown signal type {signal_type}"
|
601 |
+
|
602 |
+
prompt = ''
|
603 |
+
for i, (old_query, response) in enumerate(history):
|
604 |
+
prompt += 'Question: ' + old_query + " {} ".format(answer_format) + response + "\n"
|
605 |
+
prompt += 'Question: {} {}'.format(query, answer_format)
|
606 |
+
return prompt
|
607 |
+
|
608 |
+
|
609 |
+
class CogVLMForCausalLM(CogVLMPreTrainedModel):
|
610 |
+
_auto_class = "AutoModelForCausalLM"
|
611 |
+
|
612 |
+
def __init__(self, config):
|
613 |
+
super().__init__(config)
|
614 |
+
self.model = CogVLMModel(config)
|
615 |
+
self.vocab_size = config.vocab_size
|
616 |
+
self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
|
617 |
+
|
618 |
+
# Initialize weights and apply final processing
|
619 |
+
self.post_init()
|
620 |
+
|
621 |
+
def get_input_embeddings(self):
|
622 |
+
return self.model.embed_tokens
|
623 |
+
|
624 |
+
def set_input_embeddings(self, value):
|
625 |
+
self.model.embed_tokens = value
|
626 |
+
|
627 |
+
def get_output_embeddings(self):
|
628 |
+
return self.lm_head
|
629 |
+
|
630 |
+
def set_output_embeddings(self, new_embeddings):
|
631 |
+
self.lm_head = new_embeddings
|
632 |
+
|
633 |
+
def set_decoder(self, decoder):
|
634 |
+
self.model = decoder
|
635 |
+
|
636 |
+
def get_decoder(self):
|
637 |
+
return self.model
|
638 |
+
|
639 |
+
def forward(
|
640 |
+
self,
|
641 |
+
input_ids: torch.LongTensor = None,
|
642 |
+
images: List[List[torch.Tensor]] = None,
|
643 |
+
token_type_ids: Optional[torch.LongTensor] = None,
|
644 |
+
attention_mask: Optional[torch.Tensor] = None,
|
645 |
+
position_ids: Optional[torch.LongTensor] = None,
|
646 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
647 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
648 |
+
use_cache: Optional[bool] = None,
|
649 |
+
output_attentions: Optional[bool] = None,
|
650 |
+
output_hidden_states: Optional[bool] = None,
|
651 |
+
return_dict: Optional[bool] = None,
|
652 |
+
labels: Optional[torch.LongTensor] = None,
|
653 |
+
) -> Union[Tuple, CausalLMOutputWithPast]:
|
654 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
655 |
+
output_hidden_states = (
|
656 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
657 |
+
)
|
658 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
659 |
+
|
660 |
+
# decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
|
661 |
+
outputs = self.model(
|
662 |
+
input_ids=input_ids,
|
663 |
+
images=images,
|
664 |
+
token_type_ids=token_type_ids,
|
665 |
+
attention_mask=attention_mask,
|
666 |
+
position_ids=position_ids,
|
667 |
+
past_key_values=past_key_values,
|
668 |
+
inputs_embeds=inputs_embeds,
|
669 |
+
use_cache=use_cache,
|
670 |
+
output_attentions=output_attentions,
|
671 |
+
output_hidden_states=output_hidden_states,
|
672 |
+
return_dict=return_dict,
|
673 |
+
)
|
674 |
+
|
675 |
+
hidden_states = outputs[0]
|
676 |
+
logits = self.lm_head(hidden_states)
|
677 |
+
logits = logits.float()
|
678 |
+
|
679 |
+
loss = None
|
680 |
+
if labels is not None:
|
681 |
+
# Shift so that tokens < n predict n
|
682 |
+
shift_logits = logits[..., :-1, :].contiguous()
|
683 |
+
shift_labels = labels[..., 1:].contiguous()
|
684 |
+
# Flatten the tokens
|
685 |
+
loss_fct = CrossEntropyLoss()
|
686 |
+
shift_logits = shift_logits.view(-1, self.config.vocab_size)
|
687 |
+
shift_labels = shift_labels.view(-1)
|
688 |
+
# Enable model parallelism
|
689 |
+
shift_labels = shift_labels.to(shift_logits.device)
|
690 |
+
loss = loss_fct(shift_logits, shift_labels)
|
691 |
+
|
692 |
+
if not return_dict:
|
693 |
+
output = (logits,) + outputs[1:]
|
694 |
+
return (loss,) + output if loss is not None else output
|
695 |
+
|
696 |
+
return CausalLMOutputWithPast(
|
697 |
+
loss=loss,
|
698 |
+
logits=logits,
|
699 |
+
past_key_values=outputs.past_key_values,
|
700 |
+
hidden_states=outputs.hidden_states,
|
701 |
+
attentions=outputs.attentions,
|
702 |
+
)
|
703 |
+
|
704 |
+
def _prepare_attention_mask_for_generation(
|
705 |
+
self,
|
706 |
+
inputs: torch.Tensor,
|
707 |
+
pad_token_id: Optional[int],
|
708 |
+
eos_token_id: Optional[Union[int, List[int]]],
|
709 |
+
) -> torch.LongTensor:
|
710 |
+
return torch.ones(inputs.shape[:2], dtype=torch.long, device=inputs.device) # type: ignore
|
711 |
+
|
712 |
+
def prepare_inputs_for_generation(
|
713 |
+
self, input_ids, token_type_ids, images=None, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs
|
714 |
+
):
|
715 |
+
# build position_ids if needed
|
716 |
+
position_ids = kwargs.get("position_ids", None)
|
717 |
+
if position_ids is None:
|
718 |
+
position_ids = build_position_ids(token_type_ids, attention_mask)
|
719 |
+
|
720 |
+
if past_key_values:
|
721 |
+
input_ids = input_ids[:, -1:]
|
722 |
+
token_type_ids = token_type_ids[:, -1:]
|
723 |
+
position_ids = position_ids[:, -1:]
|
724 |
+
|
725 |
+
# if `inputs_embeds` are passed, we only want to use them in the 1st generation step
|
726 |
+
if inputs_embeds is not None and past_key_values is None:
|
727 |
+
model_inputs = {"inputs_embeds": inputs_embeds}
|
728 |
+
else:
|
729 |
+
model_inputs = {"input_ids": input_ids}
|
730 |
+
|
731 |
+
model_inputs.update(
|
732 |
+
{
|
733 |
+
"token_type_ids": token_type_ids,
|
734 |
+
"images": images,
|
735 |
+
"position_ids": position_ids,
|
736 |
+
"past_key_values": past_key_values,
|
737 |
+
"use_cache": kwargs.get("use_cache"),
|
738 |
+
"attention_mask": attention_mask,
|
739 |
+
}
|
740 |
+
)
|
741 |
+
return model_inputs
|
742 |
+
|
743 |
+
def _update_model_kwargs_for_generation(
|
744 |
+
self,
|
745 |
+
outputs: "ModelOutput",
|
746 |
+
model_kwargs: Dict[str, Any],
|
747 |
+
is_encoder_decoder: bool = False,
|
748 |
+
standardize_cache_format: bool = False,
|
749 |
+
) -> Dict[str, Any]:
|
750 |
+
# update past_key_values
|
751 |
+
model_kwargs["past_key_values"] = self._extract_past_from_model_output(
|
752 |
+
outputs, standardize_cache_format=standardize_cache_format
|
753 |
+
)
|
754 |
+
if getattr(outputs, "state", None) is not None:
|
755 |
+
model_kwargs["state"] = outputs.state
|
756 |
+
|
757 |
+
# update token_type_ids with last value
|
758 |
+
if "token_type_ids" in model_kwargs:
|
759 |
+
token_type_ids = model_kwargs["token_type_ids"]
|
760 |
+
new_token_type_ids = torch.ones(size=(token_type_ids.shape[0], 1), dtype=token_type_ids.dtype,
|
761 |
+
device=token_type_ids.device) * LANGUAGE_TOKEN_TYPE
|
762 |
+
model_kwargs["token_type_ids"] = torch.cat([token_type_ids, new_token_type_ids], dim=-1)
|
763 |
+
|
764 |
+
if not is_encoder_decoder:
|
765 |
+
# update attention mask
|
766 |
+
if "attention_mask" in model_kwargs:
|
767 |
+
attention_mask = model_kwargs["attention_mask"]
|
768 |
+
model_kwargs["attention_mask"] = torch.cat(
|
769 |
+
[attention_mask, attention_mask.new_ones((attention_mask.shape[0], 1))], dim=-1
|
770 |
+
)
|
771 |
+
else:
|
772 |
+
# update decoder attention mask
|
773 |
+
if "decoder_attention_mask" in model_kwargs:
|
774 |
+
decoder_attention_mask = model_kwargs["decoder_attention_mask"]
|
775 |
+
model_kwargs["decoder_attention_mask"] = torch.cat(
|
776 |
+
[decoder_attention_mask, decoder_attention_mask.new_ones((decoder_attention_mask.shape[0], 1))],
|
777 |
+
dim=-1,
|
778 |
+
)
|
779 |
+
|
780 |
+
return model_kwargs
|
781 |
+
|
782 |
+
def _reorder_cache(self, past_key_values, beam_idx):
|
783 |
+
reordered_past = ()
|
784 |
+
for layer_past in past_key_values:
|
785 |
+
reordered_past += (
|
786 |
+
tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
|
787 |
+
)
|
788 |
+
return reordered_past
|
789 |
+
|
790 |
+
def build_conversation_input_ids(
|
791 |
+
self,
|
792 |
+
tokenizer: "PreTrainedTokenizer",
|
793 |
+
*,
|
794 |
+
query: str,
|
795 |
+
history: Optional[List[Tuple[str, str]]] = None,
|
796 |
+
images: Optional[List["PIL.Image"]] = None,
|
797 |
+
template_version: Optional[Literal["base", "chat", "vqa"]] = None,
|
798 |
+
):
|
799 |
+
image_size: int = self.config.vision_config['image_size']
|
800 |
+
patch_size: int = self.config.vision_config['patch_size']
|
801 |
+
template_version = template_version or self.config.template_version
|
802 |
+
assert images is None or len(images) <= 1, f"not support multi images by now."
|
803 |
+
history = history or []
|
804 |
+
text = _history_to_prompt(template_version, history, query)
|
805 |
+
|
806 |
+
input_ids = [tokenizer.bos_token_id]
|
807 |
+
token_type_ids = [LANGUAGE_TOKEN_TYPE]
|
808 |
+
if images is not None and len(images) == 1:
|
809 |
+
# vision
|
810 |
+
transform = transforms.Compose(
|
811 |
+
[
|
812 |
+
transforms.Resize(
|
813 |
+
(image_size, image_size), interpolation=transforms.InterpolationMode.BICUBIC
|
814 |
+
),
|
815 |
+
transforms.ToTensor(),
|
816 |
+
transforms.Normalize((0.48145466, 0.4578275, 0.40821073), (0.26862954, 0.26130258, 0.27577711)),
|
817 |
+
]
|
818 |
+
)
|
819 |
+
images = [transform(images[0])]
|
820 |
+
# language
|
821 |
+
vision_token_num = (image_size // patch_size) * (image_size // patch_size) + 2
|
822 |
+
input_ids += [tokenizer.pad_token_id] * vision_token_num
|
823 |
+
token_type_ids += [VISION_TOKEN_TYPE] * vision_token_num
|
824 |
+
text_ids = tokenizer.encode(text, add_special_tokens=False)
|
825 |
+
|
826 |
+
input_ids += text_ids
|
827 |
+
token_type_ids += [LANGUAGE_TOKEN_TYPE] * len(text_ids)
|
828 |
+
attention_mask = [1] * len(input_ids)
|
829 |
+
|
830 |
+
return {
|
831 |
+
'input_ids': torch.tensor(input_ids, dtype=torch.long),
|
832 |
+
'token_type_ids': torch.tensor(token_type_ids, dtype=torch.long),
|
833 |
+
'attention_mask': torch.tensor(attention_mask, dtype=torch.long),
|
834 |
+
'images': images,
|
835 |
+
}
|