Ramji commited on
Commit
8afaec4
1 Parent(s): 13b1534

Upload modeling_internvl_chat.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. modeling_internvl_chat.py +349 -0
modeling_internvl_chat.py ADDED
@@ -0,0 +1,349 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # --------------------------------------------------------
2
+ # InternVL
3
+ # Copyright (c) 2024 OpenGVLab
4
+ # Licensed under The MIT License [see LICENSE for details]
5
+ # --------------------------------------------------------
6
+ import warnings
7
+ from typing import Any, List, Optional, Tuple, Union
8
+
9
+ import torch.utils.checkpoint
10
+ import transformers
11
+ from torch import nn
12
+ from torch.nn import CrossEntropyLoss
13
+ from transformers import (AutoModel, GenerationConfig, LlamaForCausalLM,
14
+ Qwen2ForCausalLM)
15
+ from transformers.modeling_outputs import CausalLMOutputWithPast
16
+ from transformers.modeling_utils import PreTrainedModel
17
+ from transformers.utils import ModelOutput, logging
18
+
19
+ from .configuration_internvl_chat import InternVLChatConfig
20
+ from .conversation import get_conv_template
21
+ from .modeling_intern_vit import InternVisionModel, has_flash_attn
22
+
23
+ logger = logging.get_logger(__name__)
24
+
25
+
26
+ def version_cmp(v1, v2, op='eq'):
27
+ import operator
28
+
29
+ from packaging import version
30
+ op_func = getattr(operator, op)
31
+ return op_func(version.parse(v1), version.parse(v2))
32
+
33
+
34
+ class InternVLChatModel(PreTrainedModel):
35
+ config_class = InternVLChatConfig
36
+ main_input_name = 'pixel_values'
37
+ base_model_prefix = 'language_model'
38
+ _supports_flash_attn_2 = True
39
+ _no_split_modules = ['InternVisionModel', 'LlamaDecoderLayer', 'Qwen2DecoderLayer']
40
+
41
+ def __init__(self, config: InternVLChatConfig, vision_model=None, language_model=None, use_flash_attn=True):
42
+ super().__init__(config)
43
+
44
+ assert version_cmp(transformers.__version__, '4.37.0', 'ge')
45
+ image_size = config.force_image_size or config.vision_config.image_size
46
+ patch_size = config.vision_config.patch_size
47
+ self.patch_size = patch_size
48
+ self.select_layer = config.select_layer
49
+ self.template = config.template
50
+ self.num_image_token = int((image_size // patch_size) ** 2 * (config.downsample_ratio ** 2))
51
+ self.downsample_ratio = config.downsample_ratio
52
+ self.ps_version = config.ps_version
53
+ use_flash_attn = use_flash_attn if has_flash_attn else False
54
+ config.vision_config.use_flash_attn = True if use_flash_attn else False
55
+ config.llm_config._attn_implementation = 'flash_attention_2' if use_flash_attn else 'eager'
56
+
57
+ logger.info(f'num_image_token: {self.num_image_token}')
58
+ logger.info(f'ps_version: {self.ps_version}')
59
+ if vision_model is not None:
60
+ self.vision_model = vision_model
61
+ else:
62
+ self.vision_model = InternVisionModel(config.vision_config)
63
+ if language_model is not None:
64
+ self.language_model = language_model
65
+ else:
66
+ if config.llm_config.architectures[0] == 'LlamaForCausalLM':
67
+ self.language_model = LlamaForCausalLM(config.llm_config)
68
+ elif config.llm_config.architectures[0] == 'Qwen2ForCausalLM':
69
+ self.language_model = Qwen2ForCausalLM(config.llm_config)
70
+ else:
71
+ raise NotImplementedError(f'{config.llm_config.architectures[0]} is not implemented.')
72
+
73
+ vit_hidden_size = config.vision_config.hidden_size
74
+ llm_hidden_size = config.llm_config.hidden_size
75
+
76
+ self.mlp1 = nn.Sequential(
77
+ nn.LayerNorm(vit_hidden_size * int(1 / self.downsample_ratio) ** 2),
78
+ nn.Linear(vit_hidden_size * int(1 / self.downsample_ratio) ** 2, llm_hidden_size),
79
+ nn.GELU(),
80
+ nn.Linear(llm_hidden_size, llm_hidden_size)
81
+ )
82
+
83
+ self.img_context_token_id = None
84
+ self.conv_template = get_conv_template(self.template)
85
+ self.system_message = self.conv_template.system_message
86
+
87
+ def forward(
88
+ self,
89
+ pixel_values: torch.FloatTensor,
90
+ input_ids: torch.LongTensor = None,
91
+ attention_mask: Optional[torch.Tensor] = None,
92
+ position_ids: Optional[torch.LongTensor] = None,
93
+ image_flags: Optional[torch.LongTensor] = None,
94
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
95
+ labels: Optional[torch.LongTensor] = None,
96
+ use_cache: Optional[bool] = None,
97
+ output_attentions: Optional[bool] = None,
98
+ output_hidden_states: Optional[bool] = None,
99
+ return_dict: Optional[bool] = None,
100
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
101
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
102
+
103
+ image_flags = image_flags.squeeze(-1)
104
+ input_embeds = self.language_model.get_input_embeddings()(input_ids).clone()
105
+
106
+ vit_embeds = self.extract_feature(pixel_values)
107
+ vit_embeds = vit_embeds[image_flags == 1]
108
+ vit_batch_size = pixel_values.shape[0]
109
+
110
+ B, N, C = input_embeds.shape
111
+ input_embeds = input_embeds.reshape(B * N, C)
112
+
113
+ if torch.distributed.get_rank() == 0:
114
+ print(f'dynamic ViT batch size: {vit_batch_size}, images per sample: {vit_batch_size / B}, dynamic token length: {N}')
115
+
116
+ input_ids = input_ids.reshape(B * N)
117
+ selected = (input_ids == self.img_context_token_id)
118
+ try:
119
+ input_embeds[selected] = input_embeds[selected] * 0.0 + vit_embeds.reshape(-1, C)
120
+ except Exception as e:
121
+ vit_embeds = vit_embeds.reshape(-1, C)
122
+ print(f'warning: {e}, input_embeds[selected].shape={input_embeds[selected].shape}, '
123
+ f'vit_embeds.shape={vit_embeds.shape}')
124
+ n_token = selected.sum()
125
+ input_embeds[selected] = input_embeds[selected] * 0.0 + vit_embeds[:n_token]
126
+
127
+ input_embeds = input_embeds.reshape(B, N, C)
128
+
129
+ outputs = self.language_model(
130
+ inputs_embeds=input_embeds,
131
+ attention_mask=attention_mask,
132
+ position_ids=position_ids,
133
+ past_key_values=past_key_values,
134
+ use_cache=use_cache,
135
+ output_attentions=output_attentions,
136
+ output_hidden_states=output_hidden_states,
137
+ return_dict=return_dict,
138
+ )
139
+ logits = outputs.logits
140
+
141
+ loss = None
142
+ if labels is not None:
143
+ # Shift so that tokens < n predict n
144
+ shift_logits = logits[..., :-1, :].contiguous()
145
+ shift_labels = labels[..., 1:].contiguous()
146
+ # Flatten the tokens
147
+ loss_fct = CrossEntropyLoss()
148
+ shift_logits = shift_logits.view(-1, self.language_model.config.vocab_size)
149
+ shift_labels = shift_labels.view(-1)
150
+ # Enable model parallelism
151
+ shift_labels = shift_labels.to(shift_logits.device)
152
+ loss = loss_fct(shift_logits, shift_labels)
153
+
154
+ if not return_dict:
155
+ output = (logits,) + outputs[1:]
156
+ return (loss,) + output if loss is not None else output
157
+
158
+ return CausalLMOutputWithPast(
159
+ loss=loss,
160
+ logits=logits,
161
+ past_key_values=outputs.past_key_values,
162
+ hidden_states=outputs.hidden_states,
163
+ attentions=outputs.attentions,
164
+ )
165
+
166
+ def pixel_shuffle(self, x, scale_factor=0.5):
167
+ n, w, h, c = x.size()
168
+ # N, W, H, C --> N, W, H * scale, C // scale
169
+ x = x.view(n, w, int(h * scale_factor), int(c / scale_factor))
170
+ # N, W, H * scale, C // scale --> N, H * scale, W, C // scale
171
+ x = x.permute(0, 2, 1, 3).contiguous()
172
+ # N, H * scale, W, C // scale --> N, H * scale, W * scale, C // (scale ** 2)
173
+ x = x.view(n, int(h * scale_factor), int(w * scale_factor),
174
+ int(c / (scale_factor * scale_factor)))
175
+ if self.ps_version == 'v1':
176
+ warnings.warn("In ps_version 'v1', the height and width have not been swapped back, "
177
+ 'which results in a transposed image.')
178
+ else:
179
+ x = x.permute(0, 2, 1, 3).contiguous()
180
+ return x
181
+
182
+ def extract_feature(self, pixel_values):
183
+ if self.select_layer == -1:
184
+ vit_embeds = self.vision_model(
185
+ pixel_values=pixel_values,
186
+ output_hidden_states=False,
187
+ return_dict=True).last_hidden_state
188
+ else:
189
+ vit_embeds = self.vision_model(
190
+ pixel_values=pixel_values,
191
+ output_hidden_states=True,
192
+ return_dict=True).hidden_states[self.select_layer]
193
+ vit_embeds = vit_embeds[:, 1:, :]
194
+
195
+ h = w = int(vit_embeds.shape[1] ** 0.5)
196
+ vit_embeds = vit_embeds.reshape(vit_embeds.shape[0], h, w, -1)
197
+ vit_embeds = self.pixel_shuffle(vit_embeds, scale_factor=self.downsample_ratio)
198
+ vit_embeds = vit_embeds.reshape(vit_embeds.shape[0], -1, vit_embeds.shape[-1])
199
+ vit_embeds = self.mlp1(vit_embeds)
200
+ return vit_embeds
201
+
202
+ def batch_chat(self, tokenizer, pixel_values, questions, generation_config, num_patches_list=None,
203
+ history=None, return_history=False, IMG_START_TOKEN='<img>', IMG_END_TOKEN='</img>',
204
+ IMG_CONTEXT_TOKEN='<IMG_CONTEXT>', verbose=False, image_counts=None):
205
+ if history is not None or return_history:
206
+ print('Now multi-turn chat is not supported in batch_chat.')
207
+ raise NotImplementedError
208
+
209
+ if image_counts is not None:
210
+ num_patches_list = image_counts
211
+ print('Warning: `image_counts` is deprecated. Please use `num_patches_list` instead.')
212
+
213
+ img_context_token_id = tokenizer.convert_tokens_to_ids(IMG_CONTEXT_TOKEN)
214
+ self.img_context_token_id = img_context_token_id
215
+
216
+ if verbose and pixel_values is not None:
217
+ image_bs = pixel_values.shape[0]
218
+ print(f'dynamic ViT batch size: {image_bs}')
219
+
220
+ queries = []
221
+ for idx, num_patches in enumerate(num_patches_list):
222
+ question = questions[idx]
223
+ if pixel_values is not None and '<image>' not in question:
224
+ question = '<image>\n' + question
225
+ template = get_conv_template(self.template)
226
+ template.system_message = self.system_message
227
+ template.append_message(template.roles[0], question)
228
+ template.append_message(template.roles[1], None)
229
+ query = template.get_prompt()
230
+
231
+ image_tokens = IMG_START_TOKEN + IMG_CONTEXT_TOKEN * self.num_image_token * num_patches + IMG_END_TOKEN
232
+ query = query.replace('<image>', image_tokens, 1)
233
+ queries.append(query)
234
+
235
+ tokenizer.padding_side = 'left'
236
+ model_inputs = tokenizer(queries, return_tensors='pt', padding=True)
237
+ input_ids = model_inputs['input_ids'].to(self.device)
238
+ attention_mask = model_inputs['attention_mask'].to(self.device)
239
+ eos_token_id = tokenizer.convert_tokens_to_ids(template.sep)
240
+ generation_config['eos_token_id'] = eos_token_id
241
+ generation_output = self.generate(
242
+ pixel_values=pixel_values,
243
+ input_ids=input_ids,
244
+ attention_mask=attention_mask,
245
+ **generation_config
246
+ )
247
+ responses = tokenizer.batch_decode(generation_output, skip_special_tokens=True)
248
+ responses = [response.split(template.sep)[0].strip() for response in responses]
249
+ return responses
250
+
251
+ def chat(self, tokenizer, pixel_values, question, generation_config, history=None, return_history=False,
252
+ num_patches_list=None, IMG_START_TOKEN='<img>', IMG_END_TOKEN='</img>', IMG_CONTEXT_TOKEN='<IMG_CONTEXT>',
253
+ verbose=False):
254
+
255
+ if history is None and pixel_values is not None and '<image>' not in question:
256
+ question = '<image>\n' + question
257
+
258
+ if num_patches_list is None:
259
+ num_patches_list = [pixel_values.shape[0]] if pixel_values is not None else []
260
+ assert pixel_values is None or len(pixel_values) == sum(num_patches_list)
261
+
262
+ img_context_token_id = tokenizer.convert_tokens_to_ids(IMG_CONTEXT_TOKEN)
263
+ self.img_context_token_id = img_context_token_id
264
+
265
+ template = get_conv_template(self.template)
266
+ template.system_message = self.system_message
267
+ eos_token_id = tokenizer.convert_tokens_to_ids(template.sep)
268
+
269
+ history = [] if history is None else history
270
+ for (old_question, old_answer) in history:
271
+ template.append_message(template.roles[0], old_question)
272
+ template.append_message(template.roles[1], old_answer)
273
+ template.append_message(template.roles[0], question)
274
+ template.append_message(template.roles[1], None)
275
+ query = template.get_prompt()
276
+
277
+ if verbose and pixel_values is not None:
278
+ image_bs = pixel_values.shape[0]
279
+ print(f'dynamic ViT batch size: {image_bs}')
280
+
281
+ for num_patches in num_patches_list:
282
+ image_tokens = IMG_START_TOKEN + IMG_CONTEXT_TOKEN * self.num_image_token * num_patches + IMG_END_TOKEN
283
+ query = query.replace('<image>', image_tokens, 1)
284
+
285
+ model_inputs = tokenizer(query, return_tensors='pt')
286
+ input_ids = model_inputs['input_ids'].to(self.device)
287
+ attention_mask = model_inputs['attention_mask'].to(self.device)
288
+ generation_config['eos_token_id'] = eos_token_id
289
+ generation_output = self.generate(
290
+ pixel_values=pixel_values,
291
+ input_ids=input_ids,
292
+ attention_mask=attention_mask,
293
+ **generation_config
294
+ )
295
+ response = tokenizer.batch_decode(generation_output, skip_special_tokens=True)[0]
296
+ response = response.split(template.sep)[0].strip()
297
+ history.append((question, response))
298
+ if return_history:
299
+ return response, history
300
+ else:
301
+ query_to_print = query.replace(IMG_CONTEXT_TOKEN, '')
302
+ query_to_print = query_to_print.replace(f'{IMG_START_TOKEN}{IMG_END_TOKEN}', '<image>')
303
+ if verbose:
304
+ print(query_to_print, response)
305
+ return response
306
+
307
+ @torch.no_grad()
308
+ def generate(
309
+ self,
310
+ pixel_values: Optional[torch.FloatTensor] = None,
311
+ input_ids: Optional[torch.FloatTensor] = None,
312
+ attention_mask: Optional[torch.LongTensor] = None,
313
+ visual_features: Optional[torch.FloatTensor] = None,
314
+ generation_config: Optional[GenerationConfig] = None,
315
+ output_hidden_states: Optional[bool] = None,
316
+ return_dict: Optional[bool] = None,
317
+ **generate_kwargs,
318
+ ) -> torch.LongTensor:
319
+
320
+ assert self.img_context_token_id is not None
321
+ if pixel_values is not None:
322
+ if visual_features is not None:
323
+ vit_embeds = visual_features
324
+ else:
325
+ vit_embeds = self.extract_feature(pixel_values)
326
+ input_embeds = self.language_model.get_input_embeddings()(input_ids)
327
+ B, N, C = input_embeds.shape
328
+ input_embeds = input_embeds.reshape(B * N, C)
329
+
330
+ input_ids = input_ids.reshape(B * N)
331
+ selected = (input_ids == self.img_context_token_id)
332
+ assert selected.sum() != 0
333
+ input_embeds[selected] = vit_embeds.reshape(-1, C).to(input_embeds.device)
334
+
335
+ input_embeds = input_embeds.reshape(B, N, C)
336
+ else:
337
+ input_embeds = self.language_model.get_input_embeddings()(input_ids)
338
+
339
+ outputs = self.language_model.generate(
340
+ inputs_embeds=input_embeds,
341
+ attention_mask=attention_mask,
342
+ generation_config=generation_config,
343
+ output_hidden_states=output_hidden_states,
344
+ return_dict=return_dict,
345
+ use_cache=True,
346
+ **generate_kwargs,
347
+ )
348
+
349
+ return outputs