Update modeling_cogvlm.py

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