DmitryInd commited on
Commit
e34cd13
·
verified ·
1 Parent(s): 119df23

Update modeling_cogvlm.py

Browse files

Update of modeling_cogvlm.py for Transformers newer version (copy of the similar commit in THUDM/cogvlm2-llama3-chat-19B)

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