khang119966 commited on
Commit
6eb49dc
1 Parent(s): 3eed975

Upload 5 files

Browse files
configuration_intern_vit.py ADDED
@@ -0,0 +1,119 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # --------------------------------------------------------
2
+ # InternVL
3
+ # Copyright (c) 2024 OpenGVLab
4
+ # Licensed under The MIT License [see LICENSE for details]
5
+ # --------------------------------------------------------
6
+ import os
7
+ from typing import Union
8
+
9
+ from transformers.configuration_utils import PretrainedConfig
10
+ from transformers.utils import logging
11
+
12
+ logger = logging.get_logger(__name__)
13
+
14
+
15
+ class InternVisionConfig(PretrainedConfig):
16
+ r"""
17
+ This is the configuration class to store the configuration of a [`InternVisionModel`]. It is used to
18
+ instantiate a vision encoder according to the specified arguments, defining the model architecture.
19
+
20
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
21
+ documentation from [`PretrainedConfig`] for more information.
22
+
23
+ Args:
24
+ num_channels (`int`, *optional*, defaults to 3):
25
+ Number of color channels in the input images (e.g., 3 for RGB).
26
+ patch_size (`int`, *optional*, defaults to 14):
27
+ The size (resolution) of each patch.
28
+ image_size (`int`, *optional*, defaults to 224):
29
+ The size (resolution) of each image.
30
+ qkv_bias (`bool`, *optional*, defaults to `False`):
31
+ Whether to add a bias to the queries and values in the self-attention layers.
32
+ hidden_size (`int`, *optional*, defaults to 3200):
33
+ Dimensionality of the encoder layers and the pooler layer.
34
+ num_attention_heads (`int`, *optional*, defaults to 25):
35
+ Number of attention heads for each attention layer in the Transformer encoder.
36
+ intermediate_size (`int`, *optional*, defaults to 12800):
37
+ Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
38
+ qk_normalization (`bool`, *optional*, defaults to `True`):
39
+ Whether to normalize the queries and keys in the self-attention layers.
40
+ num_hidden_layers (`int`, *optional*, defaults to 48):
41
+ Number of hidden layers in the Transformer encoder.
42
+ use_flash_attn (`bool`, *optional*, defaults to `True`):
43
+ Whether to use flash attention mechanism.
44
+ hidden_act (`str` or `function`, *optional*, defaults to `"gelu"`):
45
+ The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
46
+ `"relu"`, `"selu"` and `"gelu_new"` ``"gelu"` are supported.
47
+ layer_norm_eps (`float`, *optional*, defaults to 1e-6):
48
+ The epsilon used by the layer normalization layers.
49
+ dropout (`float`, *optional*, defaults to 0.0):
50
+ The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
51
+ drop_path_rate (`float`, *optional*, defaults to 0.0):
52
+ Dropout rate for stochastic depth.
53
+ attention_dropout (`float`, *optional*, defaults to 0.0):
54
+ The dropout ratio for the attention probabilities.
55
+ initializer_range (`float`, *optional*, defaults to 0.02):
56
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
57
+ initializer_factor (`float`, *optional*, defaults to 0.1):
58
+ A factor for layer scale.
59
+ """
60
+
61
+ model_type = 'intern_vit_6b'
62
+
63
+ def __init__(
64
+ self,
65
+ num_channels=3,
66
+ patch_size=14,
67
+ image_size=224,
68
+ qkv_bias=False,
69
+ hidden_size=3200,
70
+ num_attention_heads=25,
71
+ intermediate_size=12800,
72
+ qk_normalization=True,
73
+ num_hidden_layers=48,
74
+ use_flash_attn=True,
75
+ hidden_act='gelu',
76
+ norm_type='rms_norm',
77
+ layer_norm_eps=1e-6,
78
+ dropout=0.0,
79
+ drop_path_rate=0.0,
80
+ attention_dropout=0.0,
81
+ initializer_range=0.02,
82
+ initializer_factor=0.1,
83
+ **kwargs,
84
+ ):
85
+ super().__init__(**kwargs)
86
+
87
+ self.hidden_size = hidden_size
88
+ self.intermediate_size = intermediate_size
89
+ self.dropout = dropout
90
+ self.drop_path_rate = drop_path_rate
91
+ self.num_hidden_layers = num_hidden_layers
92
+ self.num_attention_heads = num_attention_heads
93
+ self.num_channels = num_channels
94
+ self.patch_size = patch_size
95
+ self.image_size = image_size
96
+ self.initializer_range = initializer_range
97
+ self.initializer_factor = initializer_factor
98
+ self.attention_dropout = attention_dropout
99
+ self.layer_norm_eps = layer_norm_eps
100
+ self.hidden_act = hidden_act
101
+ self.norm_type = norm_type
102
+ self.qkv_bias = qkv_bias
103
+ self.qk_normalization = qk_normalization
104
+ self.use_flash_attn = use_flash_attn
105
+
106
+ @classmethod
107
+ def from_pretrained(cls, pretrained_model_name_or_path: Union[str, os.PathLike], **kwargs) -> 'PretrainedConfig':
108
+ config_dict, kwargs = cls.get_config_dict(pretrained_model_name_or_path, **kwargs)
109
+
110
+ if 'vision_config' in config_dict:
111
+ config_dict = config_dict['vision_config']
112
+
113
+ if 'model_type' in config_dict and hasattr(cls, 'model_type') and config_dict['model_type'] != cls.model_type:
114
+ logger.warning(
115
+ f"You are using a model of type {config_dict['model_type']} to instantiate a model of type "
116
+ f'{cls.model_type}. This is not supported for all configurations of models and can yield errors.'
117
+ )
118
+
119
+ return cls.from_dict(config_dict, **kwargs)
configuration_internvl_chat.py ADDED
@@ -0,0 +1,95 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # --------------------------------------------------------
2
+ # InternVL
3
+ # Copyright (c) 2024 OpenGVLab
4
+ # Licensed under The MIT License [see LICENSE for details]
5
+ # --------------------------------------------------------
6
+
7
+ import copy
8
+
9
+ from transformers import AutoConfig, LlamaConfig, Qwen2Config
10
+ from transformers.configuration_utils import PretrainedConfig
11
+ from transformers.utils import logging
12
+
13
+ from .configuration_intern_vit import InternVisionConfig
14
+
15
+ logger = logging.get_logger(__name__)
16
+
17
+
18
+ class InternVLChatConfig(PretrainedConfig):
19
+ model_type = 'internvl_chat'
20
+ is_composition = True
21
+
22
+ def __init__(
23
+ self,
24
+ vision_config=None,
25
+ llm_config=None,
26
+ use_backbone_lora=0,
27
+ use_llm_lora=0,
28
+ select_layer=-1,
29
+ force_image_size=None,
30
+ downsample_ratio=0.5,
31
+ template=None,
32
+ dynamic_image_size=False,
33
+ use_thumbnail=False,
34
+ ps_version='v1',
35
+ min_dynamic_patch=1,
36
+ max_dynamic_patch=6,
37
+ **kwargs):
38
+ super().__init__(**kwargs)
39
+
40
+ if vision_config is None:
41
+ vision_config = {}
42
+ logger.info('vision_config is None. Initializing the InternVisionConfig with default values.')
43
+
44
+ if llm_config is None:
45
+ llm_config = {}
46
+ logger.info('llm_config is None. Initializing the LlamaConfig config with default values (`LlamaConfig`).')
47
+
48
+ self.vision_config = InternVisionConfig(**vision_config)
49
+ if llm_config['architectures'][0] == 'LlamaForCausalLM':
50
+ self.llm_config = LlamaConfig(**llm_config)
51
+ elif llm_config['architectures'][0] == 'Qwen2ForCausalLM':
52
+ self.llm_config = Qwen2Config(**llm_config)
53
+ else:
54
+ raise ValueError('Unsupported architecture: {}'.format(llm_config['architectures'][0]))
55
+ self.use_backbone_lora = use_backbone_lora
56
+ self.use_llm_lora = use_llm_lora
57
+ self.select_layer = select_layer
58
+ self.force_image_size = force_image_size
59
+ self.downsample_ratio = downsample_ratio
60
+ self.template = template
61
+ self.dynamic_image_size = dynamic_image_size
62
+ self.use_thumbnail = use_thumbnail
63
+ self.ps_version = ps_version # pixel shuffle version
64
+ self.min_dynamic_patch = min_dynamic_patch
65
+ self.max_dynamic_patch = max_dynamic_patch
66
+
67
+ logger.info(f'vision_select_layer: {self.select_layer}')
68
+ logger.info(f'ps_version: {self.ps_version}')
69
+ logger.info(f'min_dynamic_patch: {self.min_dynamic_patch}')
70
+ logger.info(f'max_dynamic_patch: {self.max_dynamic_patch}')
71
+
72
+ def to_dict(self):
73
+ """
74
+ Serializes this instance to a Python dictionary. Override the default [`~PretrainedConfig.to_dict`].
75
+
76
+ Returns:
77
+ `Dict[str, any]`: Dictionary of all the attributes that make up this configuration instance,
78
+ """
79
+ output = copy.deepcopy(self.__dict__)
80
+ output['vision_config'] = self.vision_config.to_dict()
81
+ output['llm_config'] = self.llm_config.to_dict()
82
+ output['model_type'] = self.__class__.model_type
83
+ output['use_backbone_lora'] = self.use_backbone_lora
84
+ output['use_llm_lora'] = self.use_llm_lora
85
+ output['select_layer'] = self.select_layer
86
+ output['force_image_size'] = self.force_image_size
87
+ output['downsample_ratio'] = self.downsample_ratio
88
+ output['template'] = self.template
89
+ output['dynamic_image_size'] = self.dynamic_image_size
90
+ output['use_thumbnail'] = self.use_thumbnail
91
+ output['ps_version'] = self.ps_version
92
+ output['min_dynamic_patch'] = self.min_dynamic_patch
93
+ output['max_dynamic_patch'] = self.max_dynamic_patch
94
+
95
+ return output
conversation.py ADDED
@@ -0,0 +1,396 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Conversation prompt templates.
3
+
4
+ We kindly request that you import fastchat instead of copying this file if you wish to use it.
5
+ If you have changes in mind, please contribute back so the community can benefit collectively and continue to maintain these valuable templates.
6
+ """
7
+
8
+ import dataclasses
9
+ from enum import IntEnum, auto
10
+ from typing import Any, Dict, List, Tuple, Union
11
+
12
+
13
+ class SeparatorStyle(IntEnum):
14
+ """Separator styles."""
15
+
16
+ ADD_COLON_SINGLE = auto()
17
+ ADD_COLON_TWO = auto()
18
+ ADD_COLON_SPACE_SINGLE = auto()
19
+ NO_COLON_SINGLE = auto()
20
+ NO_COLON_TWO = auto()
21
+ ADD_NEW_LINE_SINGLE = auto()
22
+ LLAMA2 = auto()
23
+ CHATGLM = auto()
24
+ CHATML = auto()
25
+ CHATINTERN = auto()
26
+ DOLLY = auto()
27
+ RWKV = auto()
28
+ PHOENIX = auto()
29
+ ROBIN = auto()
30
+ FALCON_CHAT = auto()
31
+ CHATGLM3 = auto()
32
+ INTERNVL_ZH = auto()
33
+ MPT = auto()
34
+
35
+
36
+ @dataclasses.dataclass
37
+ class Conversation:
38
+ """A class that manages prompt templates and keeps all conversation history."""
39
+
40
+ # The name of this template
41
+ name: str
42
+ # The template of the system prompt
43
+ system_template: str = '{system_message}'
44
+ # The system message
45
+ system_message: str = ''
46
+ # The names of two roles
47
+ roles: Tuple[str] = ('USER', 'ASSISTANT')
48
+ # All messages. Each item is (role, message).
49
+ messages: List[List[str]] = ()
50
+ # The number of few shot examples
51
+ offset: int = 0
52
+ # The separator style and configurations
53
+ sep_style: SeparatorStyle = SeparatorStyle.ADD_COLON_SINGLE
54
+ sep: str = '\n'
55
+ sep2: str = None
56
+ # Stop criteria (the default one is EOS token)
57
+ stop_str: Union[str, List[str]] = None
58
+ # Stops generation if meeting any token in this list
59
+ stop_token_ids: List[int] = None
60
+
61
+ def get_prompt(self) -> str:
62
+ """Get the prompt for generation."""
63
+ system_prompt = self.system_template.format(system_message=self.system_message)
64
+ if self.sep_style == SeparatorStyle.ADD_COLON_SINGLE:
65
+ ret = system_prompt + self.sep
66
+ for role, message in self.messages:
67
+ if message:
68
+ ret += role + ': ' + message + self.sep
69
+ else:
70
+ ret += role + ':'
71
+ return ret
72
+ elif self.sep_style == SeparatorStyle.ADD_COLON_TWO:
73
+ seps = [self.sep, self.sep2]
74
+ ret = system_prompt + seps[0]
75
+ for i, (role, message) in enumerate(self.messages):
76
+ if message:
77
+ ret += role + ': ' + message + seps[i % 2]
78
+ else:
79
+ ret += role + ':'
80
+ return ret
81
+ elif self.sep_style == SeparatorStyle.ADD_COLON_SPACE_SINGLE:
82
+ ret = system_prompt + self.sep
83
+ for role, message in self.messages:
84
+ if message:
85
+ ret += role + ': ' + message + self.sep
86
+ else:
87
+ ret += role + ': ' # must be end with a space
88
+ return ret
89
+ elif self.sep_style == SeparatorStyle.ADD_NEW_LINE_SINGLE:
90
+ ret = '' if system_prompt == '' else system_prompt + self.sep
91
+ for role, message in self.messages:
92
+ if message:
93
+ ret += role + '\n' + message + self.sep
94
+ else:
95
+ ret += role + '\n'
96
+ return ret
97
+ elif self.sep_style == SeparatorStyle.NO_COLON_SINGLE:
98
+ ret = system_prompt
99
+ for role, message in self.messages:
100
+ if message:
101
+ ret += role + message + self.sep
102
+ else:
103
+ ret += role
104
+ return ret
105
+ elif self.sep_style == SeparatorStyle.NO_COLON_TWO:
106
+ seps = [self.sep, self.sep2]
107
+ ret = system_prompt
108
+ for i, (role, message) in enumerate(self.messages):
109
+ if message:
110
+ ret += role + message + seps[i % 2]
111
+ else:
112
+ ret += role
113
+ return ret
114
+ elif self.sep_style == SeparatorStyle.RWKV:
115
+ ret = system_prompt
116
+ for i, (role, message) in enumerate(self.messages):
117
+ if message:
118
+ ret += (
119
+ role
120
+ + ': '
121
+ + message.replace('\r\n', '\n').replace('\n\n', '\n')
122
+ )
123
+ ret += '\n\n'
124
+ else:
125
+ ret += role + ':'
126
+ return ret
127
+ elif self.sep_style == SeparatorStyle.LLAMA2:
128
+ seps = [self.sep, self.sep2]
129
+ if self.system_message:
130
+ ret = system_prompt
131
+ else:
132
+ ret = '[INST] '
133
+ for i, (role, message) in enumerate(self.messages):
134
+ tag = self.roles[i % 2]
135
+ if message:
136
+ if i == 0:
137
+ ret += message + ' '
138
+ else:
139
+ ret += tag + ' ' + message + seps[i % 2]
140
+ else:
141
+ ret += tag
142
+ return ret
143
+ elif self.sep_style == SeparatorStyle.CHATGLM:
144
+ # source: https://huggingface.co/THUDM/chatglm-6b/blob/1d240ba371910e9282298d4592532d7f0f3e9f3e/modeling_chatglm.py#L1302-L1308
145
+ # source2: https://huggingface.co/THUDM/chatglm2-6b/blob/e186c891cf64310ac66ef10a87e6635fa6c2a579/modeling_chatglm.py#L926
146
+ round_add_n = 1 if self.name == 'chatglm2' else 0
147
+ if system_prompt:
148
+ ret = system_prompt + self.sep
149
+ else:
150
+ ret = ''
151
+
152
+ for i, (role, message) in enumerate(self.messages):
153
+ if i % 2 == 0:
154
+ ret += f'[Round {i//2 + round_add_n}]{self.sep}'
155
+
156
+ if message:
157
+ ret += f'{role}:{message}{self.sep}'
158
+ else:
159
+ ret += f'{role}:'
160
+ return ret
161
+ elif self.sep_style == SeparatorStyle.CHATML:
162
+ ret = '' if system_prompt == '' else system_prompt + self.sep + '\n'
163
+ for role, message in self.messages:
164
+ if message:
165
+ ret += role + '\n' + message + self.sep + '\n'
166
+ else:
167
+ ret += role + '\n'
168
+ return ret
169
+ elif self.sep_style == SeparatorStyle.CHATGLM3:
170
+ ret = ''
171
+ if self.system_message:
172
+ ret += system_prompt
173
+ for role, message in self.messages:
174
+ if message:
175
+ ret += role + '\n' + ' ' + message
176
+ else:
177
+ ret += role
178
+ return ret
179
+ elif self.sep_style == SeparatorStyle.CHATINTERN:
180
+ # source: https://huggingface.co/internlm/internlm-chat-7b-8k/blob/bd546fa984b4b0b86958f56bf37f94aa75ab8831/modeling_internlm.py#L771
181
+ seps = [self.sep, self.sep2]
182
+ ret = system_prompt
183
+ for i, (role, message) in enumerate(self.messages):
184
+ # if i % 2 == 0:
185
+ # ret += "<s>"
186
+ if message:
187
+ ret += role + ':' + message + seps[i % 2] + '\n'
188
+ else:
189
+ ret += role + ':'
190
+ return ret
191
+ elif self.sep_style == SeparatorStyle.DOLLY:
192
+ seps = [self.sep, self.sep2]
193
+ ret = system_prompt
194
+ for i, (role, message) in enumerate(self.messages):
195
+ if message:
196
+ ret += role + ':\n' + message + seps[i % 2]
197
+ if i % 2 == 1:
198
+ ret += '\n\n'
199
+ else:
200
+ ret += role + ':\n'
201
+ return ret
202
+ elif self.sep_style == SeparatorStyle.PHOENIX:
203
+ ret = system_prompt
204
+ for role, message in self.messages:
205
+ if message:
206
+ ret += role + ': ' + '<s>' + message + '</s>'
207
+ else:
208
+ ret += role + ': ' + '<s>'
209
+ return ret
210
+ elif self.sep_style == SeparatorStyle.ROBIN:
211
+ ret = system_prompt + self.sep
212
+ for role, message in self.messages:
213
+ if message:
214
+ ret += role + ':\n' + message + self.sep
215
+ else:
216
+ ret += role + ':\n'
217
+ return ret
218
+ elif self.sep_style == SeparatorStyle.FALCON_CHAT:
219
+ ret = ''
220
+ if self.system_message:
221
+ ret += system_prompt + self.sep
222
+ for role, message in self.messages:
223
+ if message:
224
+ ret += role + ': ' + message + self.sep
225
+ else:
226
+ ret += role + ':'
227
+
228
+ return ret
229
+ elif self.sep_style == SeparatorStyle.INTERNVL_ZH:
230
+ seps = [self.sep, self.sep2]
231
+ ret = self.system_message + seps[0]
232
+ for i, (role, message) in enumerate(self.messages):
233
+ if message:
234
+ ret += role + ': ' + message + seps[i % 2]
235
+ else:
236
+ ret += role + ':'
237
+ return ret
238
+ elif self.sep_style == SeparatorStyle.MPT:
239
+ ret = system_prompt + self.sep
240
+ for role, message in self.messages:
241
+ if message:
242
+ if type(message) is tuple:
243
+ message, _, _ = message
244
+ ret += role + message + self.sep
245
+ else:
246
+ ret += role
247
+ return ret
248
+ else:
249
+ raise ValueError(f'Invalid style: {self.sep_style}')
250
+
251
+ def set_system_message(self, system_message: str):
252
+ """Set the system message."""
253
+ self.system_message = system_message
254
+
255
+ def append_message(self, role: str, message: str):
256
+ """Append a new message."""
257
+ self.messages.append([role, message])
258
+
259
+ def update_last_message(self, message: str):
260
+ """Update the last output.
261
+
262
+ The last message is typically set to be None when constructing the prompt,
263
+ so we need to update it in-place after getting the response from a model.
264
+ """
265
+ self.messages[-1][1] = message
266
+
267
+ def to_gradio_chatbot(self):
268
+ """Convert the conversation to gradio chatbot format."""
269
+ ret = []
270
+ for i, (role, msg) in enumerate(self.messages[self.offset :]):
271
+ if i % 2 == 0:
272
+ ret.append([msg, None])
273
+ else:
274
+ ret[-1][-1] = msg
275
+ return ret
276
+
277
+ def to_openai_api_messages(self):
278
+ """Convert the conversation to OpenAI chat completion format."""
279
+ ret = [{'role': 'system', 'content': self.system_message}]
280
+
281
+ for i, (_, msg) in enumerate(self.messages[self.offset :]):
282
+ if i % 2 == 0:
283
+ ret.append({'role': 'user', 'content': msg})
284
+ else:
285
+ if msg is not None:
286
+ ret.append({'role': 'assistant', 'content': msg})
287
+ return ret
288
+
289
+ def copy(self):
290
+ return Conversation(
291
+ name=self.name,
292
+ system_template=self.system_template,
293
+ system_message=self.system_message,
294
+ roles=self.roles,
295
+ messages=[[x, y] for x, y in self.messages],
296
+ offset=self.offset,
297
+ sep_style=self.sep_style,
298
+ sep=self.sep,
299
+ sep2=self.sep2,
300
+ stop_str=self.stop_str,
301
+ stop_token_ids=self.stop_token_ids,
302
+ )
303
+
304
+ def dict(self):
305
+ return {
306
+ 'template_name': self.name,
307
+ 'system_message': self.system_message,
308
+ 'roles': self.roles,
309
+ 'messages': self.messages,
310
+ 'offset': self.offset,
311
+ }
312
+
313
+
314
+ # A global registry for all conversation templates
315
+ conv_templates: Dict[str, Conversation] = {}
316
+
317
+
318
+ def register_conv_template(template: Conversation, override: bool = False):
319
+ """Register a new conversation template."""
320
+ if not override:
321
+ assert (
322
+ template.name not in conv_templates
323
+ ), f'{template.name} has been registered.'
324
+
325
+ conv_templates[template.name] = template
326
+
327
+
328
+ def get_conv_template(name: str) -> Conversation:
329
+ """Get a conversation template."""
330
+ return conv_templates[name].copy()
331
+
332
+
333
+ # Both Hermes-2 and internlm2-chat are chatml-format conversation templates. The difference
334
+ # is that during training, the preprocessing function for the Hermes-2 template doesn't add
335
+ # <s> at the beginning of the tokenized sequence, while the internlm2-chat template does.
336
+ # Therefore, they are completely equivalent during inference.
337
+ register_conv_template(
338
+ Conversation(
339
+ name='Hermes-2',
340
+ system_template='<|im_start|>system\n{system_message}',
341
+ # note: The new system prompt was not used here to avoid changes in benchmark performance.
342
+ # system_message='我是书生·万象,英文名是InternVL,是由上海人工智能实验室、清华大学及多家合作单位联合开发的多模态大语言模型。',
343
+ # system_message='你是由上海人工智能实验室联合商汤科技开发的书生多模态大模型,英文名叫InternVL, 是一个有用无害的人工智能助手。',
344
+ system_message='Bạn là một mô hình trí tuệ nhân tạo đa phương thức Tiếng Việt có tên gọi là Vintern, được phát triển bởi người Việt. Bạn là một trợ lý trí tuệ nhân tạo hữu ích và không gây hại.',
345
+ roles=('<|im_start|>user\n', '<|im_start|>assistant\n'),
346
+ sep_style=SeparatorStyle.MPT,
347
+ sep='<|im_end|>',
348
+ stop_token_ids=[
349
+ 2,
350
+ 6,
351
+ 7,
352
+ 8,
353
+ ],
354
+ stop_str='<|endoftext|>',
355
+ )
356
+ )
357
+
358
+
359
+ register_conv_template(
360
+ Conversation(
361
+ name='internlm2-chat',
362
+ system_template='<|im_start|>system\n{system_message}',
363
+ # note: The new system prompt was not used here to avoid changes in benchmark performance.
364
+ # system_message='我是书生·万象,英文名是InternVL,是由上海人工智能实验室、清华大学及多家合作单位联合开发的多模态大语言模型。',
365
+ # system_message='你是由上海人工智能实验室联合商汤科技开发的书生多模态大模型,英文名叫InternVL, 是一个有用无害的人工智能助手。',
366
+ system_message='Bạn là một mô hình trí tuệ nhân tạo đa phương thức Tiếng Việt có tên gọi là Vintern, được phát triển bởi người Việt. Bạn là một trợ lý trí tuệ nhân tạo hữu ích và không gây hại.',
367
+ roles=('<|im_start|>user\n', '<|im_start|>assistant\n'),
368
+ sep_style=SeparatorStyle.MPT,
369
+ sep='<|im_end|>',
370
+ stop_token_ids=[
371
+ 2,
372
+ 92543,
373
+ 92542
374
+ ]
375
+ )
376
+ )
377
+
378
+
379
+ register_conv_template(
380
+ Conversation(
381
+ name='phi3-chat',
382
+ system_template='<|system|>\n{system_message}',
383
+ # note: The new system prompt was not used here to avoid changes in benchmark performance.
384
+ # system_message='我是书生·万象,英文名是InternVL,是由上海人工智能实验室、清华大学及多家合作单位联合开发的多模态大语言模型。',
385
+ # system_message='你是由上海人工智能实验室联合商汤科技开发的书生多模态大模型,英文名叫InternVL, 是一个有用无害的人工智能助手。',
386
+ system_message='Bạn là một mô hình trí tuệ nhân tạo đa phương thức Tiếng Việt có tên gọi là Vintern, được phát triển bởi người Việt. Bạn là một trợ lý trí tuệ nhân tạo hữu ích và không gây hại.',
387
+ roles=('<|user|>\n', '<|assistant|>\n'),
388
+ sep_style=SeparatorStyle.MPT,
389
+ sep='<|end|>',
390
+ stop_token_ids=[
391
+ 2,
392
+ 32000,
393
+ 32007
394
+ ]
395
+ )
396
+ )
modeling_intern_vit.py ADDED
@@ -0,0 +1,435 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # --------------------------------------------------------
2
+ # InternVL
3
+ # Copyright (c) 2024 OpenGVLab
4
+ # Licensed under The MIT License [see LICENSE for details]
5
+ # --------------------------------------------------------
6
+ from typing import Optional, Tuple, Union
7
+
8
+ import torch
9
+ import torch.nn.functional as F
10
+ import torch.utils.checkpoint
11
+ from einops import rearrange
12
+ from timm.models.layers import DropPath
13
+ from torch import nn
14
+ from transformers.activations import ACT2FN
15
+ from transformers.modeling_outputs import (BaseModelOutput,
16
+ BaseModelOutputWithPooling)
17
+ from transformers.modeling_utils import PreTrainedModel
18
+ from transformers.utils import logging
19
+
20
+ from .configuration_intern_vit import InternVisionConfig
21
+
22
+ try:
23
+ try: # v1
24
+ from flash_attn.flash_attn_interface import \
25
+ flash_attn_unpadded_qkvpacked_func
26
+ except: # v2
27
+ from flash_attn.flash_attn_interface import \
28
+ flash_attn_varlen_qkvpacked_func as flash_attn_unpadded_qkvpacked_func
29
+
30
+ from flash_attn.bert_padding import pad_input, unpad_input
31
+
32
+ has_flash_attn = True
33
+ except:
34
+ print('FlashAttention is not installed.')
35
+ has_flash_attn = False
36
+
37
+ logger = logging.get_logger(__name__)
38
+
39
+
40
+ class FlashAttention(nn.Module):
41
+ """Implement the scaled dot product attention with softmax.
42
+ Arguments
43
+ ---------
44
+ softmax_scale: The temperature to use for the softmax attention.
45
+ (default: 1/sqrt(d_keys) where d_keys is computed at
46
+ runtime)
47
+ attention_dropout: The dropout rate to apply to the attention
48
+ (default: 0.0)
49
+ """
50
+
51
+ def __init__(self, softmax_scale=None, attention_dropout=0.0, device=None, dtype=None):
52
+ super().__init__()
53
+ self.softmax_scale = softmax_scale
54
+ self.dropout_p = attention_dropout
55
+
56
+ def forward(self, qkv, key_padding_mask=None, causal=False, cu_seqlens=None,
57
+ max_s=None, need_weights=False):
58
+ """Implements the multihead softmax attention.
59
+ Arguments
60
+ ---------
61
+ qkv: The tensor containing the query, key, and value. (B, S, 3, H, D) if key_padding_mask is None
62
+ if unpadded: (nnz, 3, h, d)
63
+ key_padding_mask: a bool tensor of shape (B, S)
64
+ """
65
+ assert not need_weights
66
+ assert qkv.dtype in [torch.float16, torch.bfloat16]
67
+ assert qkv.is_cuda
68
+
69
+ if cu_seqlens is None:
70
+ batch_size = qkv.shape[0]
71
+ seqlen = qkv.shape[1]
72
+ if key_padding_mask is None:
73
+ qkv = rearrange(qkv, 'b s ... -> (b s) ...')
74
+ max_s = seqlen
75
+ cu_seqlens = torch.arange(0, (batch_size + 1) * seqlen, step=seqlen, dtype=torch.int32,
76
+ device=qkv.device)
77
+ output = flash_attn_unpadded_qkvpacked_func(
78
+ qkv, cu_seqlens, max_s, self.dropout_p if self.training else 0.0,
79
+ softmax_scale=self.softmax_scale, causal=causal
80
+ )
81
+ output = rearrange(output, '(b s) ... -> b s ...', b=batch_size)
82
+ else:
83
+ nheads = qkv.shape[-2]
84
+ x = rearrange(qkv, 'b s three h d -> b s (three h d)')
85
+ x_unpad, indices, cu_seqlens, max_s = unpad_input(x, key_padding_mask)
86
+ x_unpad = rearrange(x_unpad, 'nnz (three h d) -> nnz three h d', three=3, h=nheads)
87
+ output_unpad = flash_attn_unpadded_qkvpacked_func(
88
+ x_unpad, cu_seqlens, max_s, self.dropout_p if self.training else 0.0,
89
+ softmax_scale=self.softmax_scale, causal=causal
90
+ )
91
+ output = rearrange(pad_input(rearrange(output_unpad, 'nnz h d -> nnz (h d)'),
92
+ indices, batch_size, seqlen),
93
+ 'b s (h d) -> b s h d', h=nheads)
94
+ else:
95
+ assert max_s is not None
96
+ output = flash_attn_unpadded_qkvpacked_func(
97
+ qkv, cu_seqlens, max_s, self.dropout_p if self.training else 0.0,
98
+ softmax_scale=self.softmax_scale, causal=causal
99
+ )
100
+
101
+ return output, None
102
+
103
+
104
+ class InternRMSNorm(nn.Module):
105
+ def __init__(self, hidden_size, eps=1e-6):
106
+ super().__init__()
107
+ self.weight = nn.Parameter(torch.ones(hidden_size))
108
+ self.variance_epsilon = eps
109
+
110
+ def forward(self, hidden_states):
111
+ input_dtype = hidden_states.dtype
112
+ hidden_states = hidden_states.to(torch.float32)
113
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
114
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
115
+ return self.weight * hidden_states.to(input_dtype)
116
+
117
+
118
+ try:
119
+ from apex.normalization import FusedRMSNorm
120
+
121
+ InternRMSNorm = FusedRMSNorm # noqa
122
+
123
+ logger.info('Discovered apex.normalization.FusedRMSNorm - will use it instead of InternRMSNorm')
124
+ except ImportError:
125
+ # using the normal InternRMSNorm
126
+ pass
127
+ except Exception:
128
+ logger.warning('discovered apex but it failed to load, falling back to InternRMSNorm')
129
+ pass
130
+
131
+
132
+ NORM2FN = {
133
+ 'rms_norm': InternRMSNorm,
134
+ 'layer_norm': nn.LayerNorm,
135
+ }
136
+
137
+
138
+ class InternVisionEmbeddings(nn.Module):
139
+ def __init__(self, config: InternVisionConfig):
140
+ super().__init__()
141
+ self.config = config
142
+ self.embed_dim = config.hidden_size
143
+ self.image_size = config.image_size
144
+ self.patch_size = config.patch_size
145
+
146
+ self.class_embedding = nn.Parameter(
147
+ torch.randn(1, 1, self.embed_dim),
148
+ )
149
+
150
+ self.patch_embedding = nn.Conv2d(
151
+ in_channels=3, out_channels=self.embed_dim, kernel_size=self.patch_size, stride=self.patch_size
152
+ )
153
+
154
+ self.num_patches = (self.image_size // self.patch_size) ** 2
155
+ self.num_positions = self.num_patches + 1
156
+
157
+ self.position_embedding = nn.Parameter(torch.randn(1, self.num_positions, self.embed_dim))
158
+
159
+ def _get_pos_embed(self, pos_embed, H, W):
160
+ target_dtype = pos_embed.dtype
161
+ pos_embed = pos_embed.float().reshape(
162
+ 1, self.image_size // self.patch_size, self.image_size // self.patch_size, -1).permute(0, 3, 1, 2)
163
+ pos_embed = F.interpolate(pos_embed, size=(H, W), mode='bicubic', align_corners=False). \
164
+ reshape(1, -1, H * W).permute(0, 2, 1).to(target_dtype)
165
+ return pos_embed
166
+
167
+ def forward(self, pixel_values: torch.FloatTensor) -> torch.Tensor:
168
+ target_dtype = self.patch_embedding.weight.dtype
169
+ patch_embeds = self.patch_embedding(pixel_values) # shape = [*, channel, width, height]
170
+ batch_size, _, height, width = patch_embeds.shape
171
+ patch_embeds = patch_embeds.flatten(2).transpose(1, 2)
172
+ class_embeds = self.class_embedding.expand(batch_size, 1, -1).to(target_dtype)
173
+ embeddings = torch.cat([class_embeds, patch_embeds], dim=1)
174
+ position_embedding = torch.cat([
175
+ self.position_embedding[:, :1, :],
176
+ self._get_pos_embed(self.position_embedding[:, 1:, :], height, width)
177
+ ], dim=1)
178
+ embeddings = embeddings + position_embedding.to(target_dtype)
179
+ return embeddings
180
+
181
+
182
+ class InternAttention(nn.Module):
183
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
184
+
185
+ def __init__(self, config: InternVisionConfig):
186
+ super().__init__()
187
+ self.config = config
188
+ self.embed_dim = config.hidden_size
189
+ self.num_heads = config.num_attention_heads
190
+ self.use_flash_attn = config.use_flash_attn and has_flash_attn
191
+ if config.use_flash_attn and not has_flash_attn:
192
+ print('Warning: Flash Attention is not available, use_flash_attn is set to False.')
193
+ self.head_dim = self.embed_dim // self.num_heads
194
+ if self.head_dim * self.num_heads != self.embed_dim:
195
+ raise ValueError(
196
+ f'embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim} and `num_heads`:'
197
+ f' {self.num_heads}).'
198
+ )
199
+
200
+ self.scale = self.head_dim ** -0.5
201
+ self.qkv = nn.Linear(self.embed_dim, 3 * self.embed_dim, bias=config.qkv_bias)
202
+ self.attn_drop = nn.Dropout(config.attention_dropout)
203
+ self.proj_drop = nn.Dropout(config.dropout)
204
+
205
+ self.qk_normalization = config.qk_normalization
206
+
207
+ if self.qk_normalization:
208
+ self.q_norm = InternRMSNorm(self.embed_dim, eps=config.layer_norm_eps)
209
+ self.k_norm = InternRMSNorm(self.embed_dim, eps=config.layer_norm_eps)
210
+
211
+ if self.use_flash_attn:
212
+ self.inner_attn = FlashAttention(attention_dropout=config.attention_dropout)
213
+ self.proj = nn.Linear(self.embed_dim, self.embed_dim)
214
+
215
+ def _naive_attn(self, x):
216
+ B, N, C = x.shape
217
+ qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4)
218
+ q, k, v = qkv.unbind(0) # make torchscript happy (cannot use tensor as tuple)
219
+
220
+ if self.qk_normalization:
221
+ B_, H_, N_, D_ = q.shape
222
+ q = self.q_norm(q.transpose(1, 2).flatten(-2, -1)).view(B_, N_, H_, D_).transpose(1, 2)
223
+ k = self.k_norm(k.transpose(1, 2).flatten(-2, -1)).view(B_, N_, H_, D_).transpose(1, 2)
224
+
225
+ attn = ((q * self.scale) @ k.transpose(-2, -1))
226
+ attn = attn.softmax(dim=-1)
227
+ attn = self.attn_drop(attn)
228
+
229
+ x = (attn @ v).transpose(1, 2).reshape(B, N, C)
230
+ x = self.proj(x)
231
+ x = self.proj_drop(x)
232
+ return x
233
+
234
+ def _flash_attn(self, x, key_padding_mask=None, need_weights=False):
235
+ qkv = self.qkv(x)
236
+ qkv = rearrange(qkv, 'b s (three h d) -> b s three h d', three=3, h=self.num_heads)
237
+
238
+ if self.qk_normalization:
239
+ q, k, v = qkv.unbind(2)
240
+ q = self.q_norm(q.flatten(-2, -1)).view(q.shape)
241
+ k = self.k_norm(k.flatten(-2, -1)).view(k.shape)
242
+ qkv = torch.stack([q, k, v], dim=2)
243
+
244
+ context, _ = self.inner_attn(
245
+ qkv, key_padding_mask=key_padding_mask, need_weights=need_weights, causal=False
246
+ )
247
+ outs = self.proj(rearrange(context, 'b s h d -> b s (h d)'))
248
+ outs = self.proj_drop(outs)
249
+ return outs
250
+
251
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
252
+ x = self._naive_attn(hidden_states) if not self.use_flash_attn else self._flash_attn(hidden_states)
253
+ return x
254
+
255
+
256
+ class InternMLP(nn.Module):
257
+ def __init__(self, config: InternVisionConfig):
258
+ super().__init__()
259
+ self.config = config
260
+ self.act = ACT2FN[config.hidden_act]
261
+ self.fc1 = nn.Linear(config.hidden_size, config.intermediate_size)
262
+ self.fc2 = nn.Linear(config.intermediate_size, config.hidden_size)
263
+
264
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
265
+ hidden_states = self.fc1(hidden_states)
266
+ hidden_states = self.act(hidden_states)
267
+ hidden_states = self.fc2(hidden_states)
268
+ return hidden_states
269
+
270
+
271
+ class InternVisionEncoderLayer(nn.Module):
272
+ def __init__(self, config: InternVisionConfig, drop_path_rate: float):
273
+ super().__init__()
274
+ self.embed_dim = config.hidden_size
275
+ self.intermediate_size = config.intermediate_size
276
+ self.norm_type = config.norm_type
277
+
278
+ self.attn = InternAttention(config)
279
+ self.mlp = InternMLP(config)
280
+ self.norm1 = NORM2FN[self.norm_type](self.embed_dim, eps=config.layer_norm_eps)
281
+ self.norm2 = NORM2FN[self.norm_type](self.embed_dim, eps=config.layer_norm_eps)
282
+
283
+ self.ls1 = nn.Parameter(config.initializer_factor * torch.ones(self.embed_dim))
284
+ self.ls2 = nn.Parameter(config.initializer_factor * torch.ones(self.embed_dim))
285
+ self.drop_path1 = DropPath(drop_path_rate) if drop_path_rate > 0. else nn.Identity()
286
+ self.drop_path2 = DropPath(drop_path_rate) if drop_path_rate > 0. else nn.Identity()
287
+
288
+ def forward(
289
+ self,
290
+ hidden_states: torch.Tensor,
291
+ ) -> Tuple[torch.FloatTensor, Optional[torch.FloatTensor], Optional[Tuple[torch.FloatTensor]]]:
292
+ """
293
+ Args:
294
+ hidden_states (`Tuple[torch.FloatTensor, Optional[torch.FloatTensor]]`): input to the layer of shape `(batch, seq_len, embed_dim)`
295
+ """
296
+ hidden_states = hidden_states + self.drop_path1(self.attn(self.norm1(hidden_states)) * self.ls1)
297
+
298
+ hidden_states = hidden_states + self.drop_path2(self.mlp(self.norm2(hidden_states)) * self.ls2)
299
+
300
+ return hidden_states
301
+
302
+
303
+ class InternVisionEncoder(nn.Module):
304
+ """
305
+ Transformer encoder consisting of `config.num_hidden_layers` self attention layers. Each layer is a
306
+ [`InternEncoderLayer`].
307
+
308
+ Args:
309
+ config (`InternConfig`):
310
+ The corresponding vision configuration for the `InternEncoder`.
311
+ """
312
+
313
+ def __init__(self, config: InternVisionConfig):
314
+ super().__init__()
315
+ self.config = config
316
+ # stochastic depth decay rule
317
+ dpr = [x.item() for x in torch.linspace(0, config.drop_path_rate, config.num_hidden_layers)]
318
+ self.layers = nn.ModuleList([
319
+ InternVisionEncoderLayer(config, dpr[idx]) for idx in range(config.num_hidden_layers)])
320
+ self.gradient_checkpointing = True
321
+
322
+ def forward(
323
+ self,
324
+ inputs_embeds,
325
+ output_hidden_states: Optional[bool] = None,
326
+ return_dict: Optional[bool] = None,
327
+ ) -> Union[Tuple, BaseModelOutput]:
328
+ r"""
329
+ Args:
330
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
331
+ Embedded representation of the inputs. Should be float, not int tokens.
332
+ output_hidden_states (`bool`, *optional*):
333
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
334
+ for more detail.
335
+ return_dict (`bool`, *optional*):
336
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
337
+ """
338
+ output_hidden_states = (
339
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
340
+ )
341
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
342
+
343
+ encoder_states = () if output_hidden_states else None
344
+ hidden_states = inputs_embeds
345
+
346
+ for idx, encoder_layer in enumerate(self.layers):
347
+ if output_hidden_states:
348
+ encoder_states = encoder_states + (hidden_states,)
349
+ if self.gradient_checkpointing and self.training:
350
+ layer_outputs = torch.utils.checkpoint.checkpoint(
351
+ encoder_layer,
352
+ hidden_states)
353
+ else:
354
+ layer_outputs = encoder_layer(
355
+ hidden_states,
356
+ )
357
+ hidden_states = layer_outputs
358
+
359
+ if output_hidden_states:
360
+ encoder_states = encoder_states + (hidden_states,)
361
+
362
+ if not return_dict:
363
+ return tuple(v for v in [hidden_states, encoder_states] if v is not None)
364
+ return BaseModelOutput(
365
+ last_hidden_state=hidden_states, hidden_states=encoder_states
366
+ )
367
+
368
+
369
+ class InternVisionModel(PreTrainedModel):
370
+ main_input_name = 'pixel_values'
371
+ _supports_flash_attn_2 = True
372
+ config_class = InternVisionConfig
373
+ _no_split_modules = ['InternVisionEncoderLayer']
374
+
375
+ def __init__(self, config: InternVisionConfig):
376
+ super().__init__(config)
377
+ self.config = config
378
+
379
+ self.embeddings = InternVisionEmbeddings(config)
380
+ self.encoder = InternVisionEncoder(config)
381
+
382
+ def resize_pos_embeddings(self, old_size, new_size, patch_size):
383
+ pos_emb = self.embeddings.position_embedding
384
+ _, num_positions, embed_dim = pos_emb.shape
385
+ cls_emb = pos_emb[:, :1, :]
386
+ pos_emb = pos_emb[:, 1:, :].reshape(1, old_size // patch_size, old_size // patch_size, -1).permute(0, 3, 1, 2)
387
+ pos_emb = F.interpolate(pos_emb.float(), size=new_size // patch_size, mode='bicubic', align_corners=False)
388
+ pos_emb = pos_emb.to(cls_emb.dtype).reshape(1, embed_dim, -1).permute(0, 2, 1)
389
+ pos_emb = torch.cat([cls_emb, pos_emb], dim=1)
390
+ self.embeddings.position_embedding = nn.Parameter(pos_emb)
391
+ self.embeddings.image_size = new_size
392
+ logger.info('Resized position embeddings from {} to {}'.format(old_size, new_size))
393
+
394
+ def get_input_embeddings(self):
395
+ return self.embeddings
396
+
397
+ def forward(
398
+ self,
399
+ pixel_values: Optional[torch.FloatTensor] = None,
400
+ output_hidden_states: Optional[bool] = None,
401
+ return_dict: Optional[bool] = None,
402
+ pixel_embeds: Optional[torch.FloatTensor] = None,
403
+ ) -> Union[Tuple, BaseModelOutputWithPooling]:
404
+ output_hidden_states = (
405
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
406
+ )
407
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
408
+
409
+ if pixel_values is None and pixel_embeds is None:
410
+ raise ValueError('You have to specify pixel_values or pixel_embeds')
411
+
412
+ if pixel_embeds is not None:
413
+ hidden_states = pixel_embeds
414
+ else:
415
+ if len(pixel_values.shape) == 4:
416
+ hidden_states = self.embeddings(pixel_values)
417
+ else:
418
+ raise ValueError(f'wrong pixel_values size: {pixel_values.shape}')
419
+ encoder_outputs = self.encoder(
420
+ inputs_embeds=hidden_states,
421
+ output_hidden_states=output_hidden_states,
422
+ return_dict=return_dict,
423
+ )
424
+ last_hidden_state = encoder_outputs.last_hidden_state
425
+ pooled_output = last_hidden_state[:, 0, :]
426
+
427
+ if not return_dict:
428
+ return (last_hidden_state, pooled_output) + encoder_outputs[1:]
429
+
430
+ return BaseModelOutputWithPooling(
431
+ last_hidden_state=last_hidden_state,
432
+ pooler_output=pooled_output,
433
+ hidden_states=encoder_outputs.hidden_states,
434
+ attentions=encoder_outputs.attentions,
435
+ )
modeling_internvl_chat.py ADDED
@@ -0,0 +1,344 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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
+ _supports_flash_attn_2 = True
38
+ _no_split_modules = ['InternVisionModel', 'LlamaDecoderLayer', 'Qwen2DecoderLayer']
39
+
40
+ def __init__(self, config: InternVLChatConfig, vision_model=None, language_model=None):
41
+ super().__init__(config)
42
+
43
+ assert version_cmp(transformers.__version__, '4.37.0', 'ge')
44
+ image_size = config.force_image_size or config.vision_config.image_size
45
+ patch_size = config.vision_config.patch_size
46
+ self.patch_size = patch_size
47
+ self.select_layer = config.select_layer
48
+ self.template = config.template
49
+ self.num_image_token = int((image_size // patch_size) ** 2 * (config.downsample_ratio ** 2))
50
+ self.downsample_ratio = config.downsample_ratio
51
+ self.ps_version = config.ps_version
52
+
53
+ logger.info(f'num_image_token: {self.num_image_token}')
54
+ logger.info(f'ps_version: {self.ps_version}')
55
+ if vision_model is not None:
56
+ self.vision_model = vision_model
57
+ else:
58
+ self.vision_model = InternVisionModel(config.vision_config)
59
+ if language_model is not None:
60
+ self.language_model = language_model
61
+ else:
62
+ if config.llm_config.architectures[0] == 'LlamaForCausalLM':
63
+ self.language_model = LlamaForCausalLM(config.llm_config)
64
+ elif config.llm_config.architectures[0] == 'Qwen2ForCausalLM':
65
+ self.language_model = Qwen2ForCausalLM(config.llm_config)
66
+ else:
67
+ raise NotImplementedError(f'{config.llm_config.architectures[0]} is not implemented.')
68
+
69
+ vit_hidden_size = config.vision_config.hidden_size
70
+ llm_hidden_size = config.llm_config.hidden_size
71
+
72
+ self.mlp1 = nn.Sequential(
73
+ nn.LayerNorm(vit_hidden_size * int(1 / self.downsample_ratio) ** 2),
74
+ nn.Linear(vit_hidden_size * int(1 / self.downsample_ratio) ** 2, llm_hidden_size),
75
+ nn.GELU(),
76
+ nn.Linear(llm_hidden_size, llm_hidden_size)
77
+ )
78
+
79
+ self.img_context_token_id = None
80
+ self.conv_template = get_conv_template(self.template)
81
+ self.system_message = self.conv_template.system_message
82
+
83
+ def forward(
84
+ self,
85
+ pixel_values: torch.FloatTensor,
86
+ input_ids: torch.LongTensor = None,
87
+ attention_mask: Optional[torch.Tensor] = None,
88
+ position_ids: Optional[torch.LongTensor] = None,
89
+ image_flags: Optional[torch.LongTensor] = None,
90
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
91
+ labels: Optional[torch.LongTensor] = None,
92
+ use_cache: Optional[bool] = None,
93
+ output_attentions: Optional[bool] = None,
94
+ output_hidden_states: Optional[bool] = None,
95
+ return_dict: Optional[bool] = None,
96
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
97
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
98
+
99
+ image_flags = image_flags.squeeze(-1)
100
+ input_embeds = self.language_model.get_input_embeddings()(input_ids)
101
+
102
+ vit_embeds = self.extract_feature(pixel_values)
103
+ vit_embeds = vit_embeds[image_flags == 1]
104
+ vit_batch_size = pixel_values.shape[0]
105
+
106
+ B, N, C = input_embeds.shape
107
+ input_embeds = input_embeds.reshape(B * N, C)
108
+
109
+ if torch.distributed.get_rank() == 0:
110
+ print(f'dynamic ViT batch size: {vit_batch_size}, images per sample: {vit_batch_size / B}, dynamic token length: {N}')
111
+
112
+ input_ids = input_ids.reshape(B * N)
113
+ selected = (input_ids == self.img_context_token_id)
114
+ try:
115
+ input_embeds[selected] = input_embeds[selected] * 0.0 + vit_embeds.reshape(-1, C)
116
+ except Exception as e:
117
+ vit_embeds = vit_embeds.reshape(-1, C)
118
+ print(f'warning: {e}, input_embeds[selected].shape={input_embeds[selected].shape}, '
119
+ f'vit_embeds.shape={vit_embeds.shape}')
120
+ n_token = selected.sum()
121
+ input_embeds[selected] = input_embeds[selected] * 0.0 + vit_embeds[:n_token]
122
+
123
+ input_embeds = input_embeds.reshape(B, N, C)
124
+
125
+ outputs = self.language_model(
126
+ inputs_embeds=input_embeds,
127
+ attention_mask=attention_mask,
128
+ position_ids=position_ids,
129
+ past_key_values=past_key_values,
130
+ use_cache=use_cache,
131
+ output_attentions=output_attentions,
132
+ output_hidden_states=output_hidden_states,
133
+ return_dict=return_dict,
134
+ )
135
+ logits = outputs.logits
136
+
137
+ loss = None
138
+ if labels is not None:
139
+ # Shift so that tokens < n predict n
140
+ shift_logits = logits[..., :-1, :].contiguous()
141
+ shift_labels = labels[..., 1:].contiguous()
142
+ # Flatten the tokens
143
+ loss_fct = CrossEntropyLoss()
144
+ shift_logits = shift_logits.view(-1, self.language_model.config.vocab_size)
145
+ shift_labels = shift_labels.view(-1)
146
+ # Enable model parallelism
147
+ shift_labels = shift_labels.to(shift_logits.device)
148
+ loss = loss_fct(shift_logits, shift_labels)
149
+
150
+ if not return_dict:
151
+ output = (logits,) + outputs[1:]
152
+ return (loss,) + output if loss is not None else output
153
+
154
+ return CausalLMOutputWithPast(
155
+ loss=loss,
156
+ logits=logits,
157
+ past_key_values=outputs.past_key_values,
158
+ hidden_states=outputs.hidden_states,
159
+ attentions=outputs.attentions,
160
+ )
161
+
162
+ def pixel_shuffle(self, x, scale_factor=0.5):
163
+ n, w, h, c = x.size()
164
+ # N, W, H, C --> N, W, H * scale, C // scale
165
+ x = x.view(n, w, int(h * scale_factor), int(c / scale_factor))
166
+ # N, W, H * scale, C // scale --> N, H * scale, W, C // scale
167
+ x = x.permute(0, 2, 1, 3).contiguous()
168
+ # N, H * scale, W, C // scale --> N, H * scale, W * scale, C // (scale ** 2)
169
+ x = x.view(n, int(h * scale_factor), int(w * scale_factor),
170
+ int(c / (scale_factor * scale_factor)))
171
+ if self.ps_version == 'v1':
172
+ warnings.warn("In ps_version 'v1', the height and width have not been swapped back, "
173
+ 'which results in a transposed image.')
174
+ else:
175
+ x = x.permute(0, 2, 1, 3).contiguous()
176
+ return x
177
+
178
+ def extract_feature(self, pixel_values):
179
+ if self.select_layer == -1:
180
+ vit_embeds = self.vision_model(
181
+ pixel_values=pixel_values,
182
+ output_hidden_states=False,
183
+ return_dict=True).last_hidden_state
184
+ else:
185
+ vit_embeds = self.vision_model(
186
+ pixel_values=pixel_values,
187
+ output_hidden_states=True,
188
+ return_dict=True).hidden_states[self.select_layer]
189
+ vit_embeds = vit_embeds[:, 1:, :]
190
+
191
+ h = w = int(vit_embeds.shape[1] ** 0.5)
192
+ vit_embeds = vit_embeds.reshape(vit_embeds.shape[0], h, w, -1)
193
+ vit_embeds = self.pixel_shuffle(vit_embeds, scale_factor=self.downsample_ratio)
194
+ vit_embeds = vit_embeds.reshape(vit_embeds.shape[0], -1, vit_embeds.shape[-1])
195
+ vit_embeds = self.mlp1(vit_embeds)
196
+ return vit_embeds
197
+
198
+ def batch_chat(self, tokenizer, pixel_values, questions, generation_config, num_patches_list=None,
199
+ history=None, return_history=False, IMG_START_TOKEN='<img>', IMG_END_TOKEN='</img>',
200
+ IMG_CONTEXT_TOKEN='<IMG_CONTEXT>', verbose=False, image_counts=None):
201
+ if history is not None or return_history:
202
+ print('Now multi-turn chat is not supported in batch_chat.')
203
+ raise NotImplementedError
204
+
205
+ if image_counts is not None:
206
+ num_patches_list = image_counts
207
+ print('Warning: `image_counts` is deprecated. Please use `num_patches_list` instead.')
208
+
209
+ img_context_token_id = tokenizer.convert_tokens_to_ids(IMG_CONTEXT_TOKEN)
210
+ self.img_context_token_id = img_context_token_id
211
+
212
+ if verbose and pixel_values is not None:
213
+ image_bs = pixel_values.shape[0]
214
+ print(f'dynamic ViT batch size: {image_bs}')
215
+
216
+ queries = []
217
+ for idx, num_patches in enumerate(num_patches_list):
218
+ question = questions[idx]
219
+ if pixel_values is not None and '<image>' not in question:
220
+ question = '<image>\n' + question
221
+ template = get_conv_template(self.template)
222
+ template.append_message(template.roles[0], question)
223
+ template.append_message(template.roles[1], None)
224
+ query = template.get_prompt()
225
+
226
+ image_tokens = IMG_START_TOKEN + IMG_CONTEXT_TOKEN * self.num_image_token * num_patches + IMG_END_TOKEN
227
+ query = query.replace('<image>', image_tokens, 1)
228
+ queries.append(query)
229
+
230
+ tokenizer.padding_side = 'left'
231
+ model_inputs = tokenizer(queries, return_tensors='pt', padding=True)
232
+ input_ids = model_inputs['input_ids'].cuda()
233
+ attention_mask = model_inputs['attention_mask'].cuda()
234
+ eos_token_id = tokenizer.convert_tokens_to_ids(template.sep)
235
+ generation_config['eos_token_id'] = eos_token_id
236
+ generation_output = self.generate(
237
+ pixel_values=pixel_values,
238
+ input_ids=input_ids,
239
+ attention_mask=attention_mask,
240
+ **generation_config
241
+ )
242
+ responses = tokenizer.batch_decode(generation_output, skip_special_tokens=True)
243
+ responses = [response.split(template.sep)[0].strip() for response in responses]
244
+ return responses
245
+
246
+ def chat(self, tokenizer, pixel_values, question, generation_config, history=None, return_history=False,
247
+ num_patches_list=None, IMG_START_TOKEN='<img>', IMG_END_TOKEN='</img>', IMG_CONTEXT_TOKEN='<IMG_CONTEXT>',
248
+ verbose=False):
249
+
250
+ if history is None and pixel_values is not None and '<image>' not in question:
251
+ question = '<image>\n' + question
252
+
253
+ if num_patches_list is None:
254
+ num_patches_list = [pixel_values.shape[0]] if pixel_values is not None else []
255
+ assert pixel_values is None or len(pixel_values) == sum(num_patches_list)
256
+
257
+ img_context_token_id = tokenizer.convert_tokens_to_ids(IMG_CONTEXT_TOKEN)
258
+ self.img_context_token_id = img_context_token_id
259
+
260
+ template = get_conv_template(self.template)
261
+ template.system_message = self.system_message
262
+ eos_token_id = tokenizer.convert_tokens_to_ids(template.sep)
263
+
264
+ history = [] if history is None else history
265
+ for (old_question, old_answer) in history:
266
+ template.append_message(template.roles[0], old_question)
267
+ template.append_message(template.roles[1], old_answer)
268
+ template.append_message(template.roles[0], question)
269
+ template.append_message(template.roles[1], None)
270
+ query = template.get_prompt()
271
+
272
+ if verbose and pixel_values is not None:
273
+ image_bs = pixel_values.shape[0]
274
+ print(f'dynamic ViT batch size: {image_bs}')
275
+
276
+ for num_patches in num_patches_list:
277
+ image_tokens = IMG_START_TOKEN + IMG_CONTEXT_TOKEN * self.num_image_token * num_patches + IMG_END_TOKEN
278
+ query = query.replace('<image>', image_tokens, 1)
279
+
280
+ model_inputs = tokenizer(query, return_tensors='pt')
281
+ input_ids = model_inputs['input_ids'].cuda()
282
+ attention_mask = model_inputs['attention_mask'].cuda()
283
+ generation_config['eos_token_id'] = eos_token_id
284
+ generation_output = self.generate(
285
+ pixel_values=pixel_values,
286
+ input_ids=input_ids,
287
+ attention_mask=attention_mask,
288
+ **generation_config
289
+ )
290
+ response = tokenizer.batch_decode(generation_output, skip_special_tokens=True)[0]
291
+ response = response.split(template.sep)[0].strip()
292
+ history.append((question, response))
293
+ if return_history:
294
+ return response, history
295
+ else:
296
+ query_to_print = query.replace(IMG_CONTEXT_TOKEN, '')
297
+ query_to_print = query_to_print.replace(f'{IMG_START_TOKEN}{IMG_END_TOKEN}', '<image>')
298
+ if verbose:
299
+ print(query_to_print, response)
300
+ return response
301
+
302
+ @torch.no_grad()
303
+ def generate(
304
+ self,
305
+ pixel_values: Optional[torch.FloatTensor] = None,
306
+ input_ids: Optional[torch.FloatTensor] = None,
307
+ attention_mask: Optional[torch.LongTensor] = None,
308
+ visual_features: Optional[torch.FloatTensor] = None,
309
+ generation_config: Optional[GenerationConfig] = None,
310
+ output_hidden_states: Optional[bool] = None,
311
+ return_dict: Optional[bool] = None,
312
+ **generate_kwargs,
313
+ ) -> torch.LongTensor:
314
+
315
+ assert self.img_context_token_id is not None
316
+ if pixel_values is not None:
317
+ if visual_features is not None:
318
+ vit_embeds = visual_features
319
+ else:
320
+ vit_embeds = self.extract_feature(pixel_values)
321
+ input_embeds = self.language_model.get_input_embeddings()(input_ids)
322
+ B, N, C = input_embeds.shape
323
+ input_embeds = input_embeds.reshape(B * N, C)
324
+
325
+ input_ids = input_ids.reshape(B * N)
326
+ selected = (input_ids == self.img_context_token_id)
327
+ assert selected.sum() != 0
328
+ input_embeds[selected] = vit_embeds.reshape(-1, C).to(input_embeds.device)
329
+
330
+ input_embeds = input_embeds.reshape(B, N, C)
331
+ else:
332
+ input_embeds = self.language_model.get_input_embeddings()(input_ids)
333
+
334
+ outputs = self.language_model.generate(
335
+ inputs_embeds=input_embeds,
336
+ attention_mask=attention_mask,
337
+ generation_config=generation_config,
338
+ output_hidden_states=output_hidden_states,
339
+ return_dict=return_dict,
340
+ use_cache=True,
341
+ **generate_kwargs,
342
+ )
343
+
344
+ return outputs