zRzRzRzRzRzRzR commited on
Commit
d88b352
1 Parent(s): a809fc4

Update modeling_cogvlm.py

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