Luxuriant16 commited on
Commit
fd34a97
·
verified ·
1 Parent(s): 55cc98f
Files changed (2) hide show
  1. modeling_intern_vit.py +356 -0
  2. modeling_internvl_chat.py +385 -0
modeling_intern_vit.py ADDED
@@ -0,0 +1,356 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # --------------------------------------------------------
2
+ # InternVL
3
+ # Copyright (c) 2023 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
+ from .flash_attention import FlashAttention
24
+ has_flash_attn = True
25
+ except:
26
+ print('FlashAttention is not installed.')
27
+ has_flash_attn = False
28
+
29
+
30
+ logger = logging.get_logger(__name__)
31
+
32
+
33
+ class InternRMSNorm(nn.Module):
34
+ def __init__(self, hidden_size, eps=1e-6):
35
+ super().__init__()
36
+ self.weight = nn.Parameter(torch.ones(hidden_size))
37
+ self.variance_epsilon = eps
38
+
39
+ def forward(self, hidden_states):
40
+ input_dtype = hidden_states.dtype
41
+ hidden_states = hidden_states.to(torch.float32)
42
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
43
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
44
+ return self.weight * hidden_states.to(input_dtype)
45
+
46
+
47
+ try:
48
+ from apex.normalization import FusedRMSNorm
49
+
50
+ InternRMSNorm = FusedRMSNorm # noqa
51
+
52
+ logger.info('Discovered apex.normalization.FusedRMSNorm - will use it instead of InternRMSNorm')
53
+ except ImportError:
54
+ # using the normal InternRMSNorm
55
+ pass
56
+ except Exception:
57
+ logger.warning('discovered apex but it failed to load, falling back to InternRMSNorm')
58
+ pass
59
+
60
+
61
+ class InternVisionEmbeddings(nn.Module):
62
+ def __init__(self, config: InternVisionConfig):
63
+ super().__init__()
64
+ self.config = config
65
+ self.embed_dim = config.hidden_size
66
+ self.image_size = config.image_size
67
+ self.patch_size = config.patch_size
68
+
69
+ self.class_embedding = nn.Parameter(
70
+ torch.randn(1, 1, self.embed_dim),
71
+ )
72
+
73
+ self.patch_embedding = nn.Conv2d(
74
+ in_channels=3, out_channels=self.embed_dim, kernel_size=self.patch_size, stride=self.patch_size
75
+ )
76
+
77
+ self.num_patches = (self.image_size // self.patch_size) ** 2
78
+ self.num_positions = self.num_patches + 1
79
+
80
+ self.position_embedding = nn.Parameter(torch.randn(1, self.num_positions, self.embed_dim))
81
+
82
+ def _get_pos_embed(self, pos_embed, H, W):
83
+ target_dtype = pos_embed.dtype
84
+ pos_embed = pos_embed.float().reshape(
85
+ 1, self.image_size // self.patch_size, self.image_size // self.patch_size, -1).permute(0, 3, 1, 2)
86
+ pos_embed = F.interpolate(pos_embed, size=(H, W), mode='bicubic', align_corners=False).\
87
+ reshape(1, -1, H * W).permute(0, 2, 1).to(target_dtype)
88
+ return pos_embed
89
+
90
+ def forward(self, pixel_values: torch.FloatTensor) -> torch.Tensor:
91
+ target_dtype = self.patch_embedding.weight.dtype
92
+ patch_embeds = self.patch_embedding(pixel_values) # shape = [*, channel, width, height]
93
+ batch_size, _, height, width = patch_embeds.shape
94
+ patch_embeds = patch_embeds.flatten(2).transpose(1, 2)
95
+ class_embeds = self.class_embedding.expand(batch_size, 1, -1).to(target_dtype)
96
+ embeddings = torch.cat([class_embeds, patch_embeds], dim=1)
97
+ position_embedding = torch.cat([
98
+ self.position_embedding[:, :1, :],
99
+ self._get_pos_embed(self.position_embedding[:, 1:, :], height, width)
100
+ ], dim=1)
101
+ embeddings = embeddings + position_embedding.to(target_dtype)
102
+ return embeddings
103
+
104
+
105
+ class InternAttention(nn.Module):
106
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
107
+
108
+ def __init__(self, config: InternVisionConfig):
109
+ super().__init__()
110
+ self.config = config
111
+ self.embed_dim = config.hidden_size
112
+ self.num_heads = config.num_attention_heads
113
+ self.use_flash_attn = config.use_flash_attn and has_flash_attn
114
+ if config.use_flash_attn and not has_flash_attn:
115
+ print('Warning: Flash Attention is not available, use_flash_attn is set to False.')
116
+ self.head_dim = self.embed_dim // self.num_heads
117
+ if self.head_dim * self.num_heads != self.embed_dim:
118
+ raise ValueError(
119
+ f'embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim} and `num_heads`:'
120
+ f' {self.num_heads}).'
121
+ )
122
+
123
+ self.scale = self.head_dim ** -0.5
124
+ self.qkv = nn.Linear(self.embed_dim, 3 * self.embed_dim, bias=config.qkv_bias)
125
+ self.attn_drop = nn.Dropout(config.attention_dropout)
126
+ self.proj_drop = nn.Dropout(config.dropout)
127
+
128
+ self.qk_normalization = config.qk_normalization
129
+
130
+ if self.qk_normalization:
131
+ self.q_norm = InternRMSNorm(self.embed_dim, eps=config.layer_norm_eps)
132
+ self.k_norm = InternRMSNorm(self.embed_dim, eps=config.layer_norm_eps)
133
+
134
+ if self.use_flash_attn:
135
+ self.inner_attn = FlashAttention(attention_dropout=config.attention_dropout)
136
+ self.proj = nn.Linear(self.embed_dim, self.embed_dim)
137
+
138
+ def _naive_attn(self, x):
139
+ B, N, C = x.shape
140
+ qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4)
141
+ q, k, v = qkv.unbind(0) # make torchscript happy (cannot use tensor as tuple)
142
+
143
+ if self.qk_normalization:
144
+ B_, H_, N_, D_ = q.shape
145
+ q = self.q_norm(q.transpose(1, 2).flatten(-2, -1)).view(B_, N_, H_, D_).transpose(1, 2)
146
+ k = self.k_norm(k.transpose(1, 2).flatten(-2, -1)).view(B_, N_, H_, D_).transpose(1, 2)
147
+
148
+ attn = ((q * self.scale) @ k.transpose(-2, -1))
149
+ attn = attn.softmax(dim=-1)
150
+ attn = self.attn_drop(attn)
151
+
152
+ x = (attn @ v).transpose(1, 2).reshape(B, N, C)
153
+ x = self.proj(x)
154
+ x = self.proj_drop(x)
155
+ return x
156
+
157
+ def _flash_attn(self, x, key_padding_mask=None, need_weights=False):
158
+ qkv = self.qkv(x)
159
+ qkv = rearrange(qkv, 'b s (three h d) -> b s three h d', three=3, h=self.num_heads)
160
+
161
+ if self.qk_normalization:
162
+ q, k, v = qkv.unbind(2)
163
+ q = self.q_norm(q.flatten(-2, -1)).view(q.shape)
164
+ k = self.k_norm(k.flatten(-2, -1)).view(k.shape)
165
+ qkv = torch.stack([q, k, v], dim=2)
166
+
167
+ context, _ = self.inner_attn(
168
+ qkv, key_padding_mask=key_padding_mask, need_weights=need_weights, causal=False
169
+ )
170
+ outs = self.proj(rearrange(context, 'b s h d -> b s (h d)'))
171
+ outs = self.proj_drop(outs)
172
+ return outs
173
+
174
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
175
+ x = self._naive_attn(hidden_states) if not self.use_flash_attn else self._flash_attn(hidden_states)
176
+ return x
177
+
178
+
179
+ class InternMLP(nn.Module):
180
+ def __init__(self, config: InternVisionConfig):
181
+ super().__init__()
182
+ self.config = config
183
+ self.act = ACT2FN[config.hidden_act]
184
+ self.fc1 = nn.Linear(config.hidden_size, config.intermediate_size)
185
+ self.fc2 = nn.Linear(config.intermediate_size, config.hidden_size)
186
+
187
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
188
+ hidden_states = self.fc1(hidden_states)
189
+ hidden_states = self.act(hidden_states)
190
+ hidden_states = self.fc2(hidden_states)
191
+ return hidden_states
192
+
193
+
194
+ class InternVisionEncoderLayer(nn.Module):
195
+ def __init__(self, config: InternVisionConfig, drop_path_rate: float):
196
+ super().__init__()
197
+ self.embed_dim = config.hidden_size
198
+ self.intermediate_size = config.intermediate_size
199
+
200
+ self.attn = InternAttention(config)
201
+ self.mlp = InternMLP(config)
202
+ self.norm1 = InternRMSNorm(self.embed_dim, eps=config.layer_norm_eps)
203
+ self.norm2 = InternRMSNorm(self.embed_dim, eps=config.layer_norm_eps)
204
+
205
+ self.ls1 = nn.Parameter(config.initializer_factor * torch.ones(self.embed_dim))
206
+ self.ls2 = nn.Parameter(config.initializer_factor * torch.ones(self.embed_dim))
207
+ self.drop_path1 = DropPath(drop_path_rate) if drop_path_rate > 0. else nn.Identity()
208
+ self.drop_path2 = DropPath(drop_path_rate) if drop_path_rate > 0. else nn.Identity()
209
+
210
+ def forward(
211
+ self,
212
+ hidden_states: torch.Tensor,
213
+ ) -> Tuple[torch.FloatTensor, Optional[torch.FloatTensor], Optional[Tuple[torch.FloatTensor]]]:
214
+ """
215
+ Args:
216
+ hidden_states (`Tuple[torch.FloatTensor, Optional[torch.FloatTensor]]`): input to the layer of shape `(batch, seq_len, embed_dim)`
217
+ """
218
+ hidden_states = hidden_states + self.drop_path1(self.attn(self.norm1(hidden_states)) * self.ls1)
219
+
220
+ hidden_states = hidden_states + self.drop_path2(self.mlp(self.norm2(hidden_states)) * self.ls2)
221
+
222
+ return hidden_states
223
+
224
+
225
+ class InternVisionEncoder(nn.Module):
226
+ """
227
+ Transformer encoder consisting of `config.num_hidden_layers` self attention layers. Each layer is a
228
+ [`InternEncoderLayer`].
229
+
230
+ Args:
231
+ config (`InternConfig`):
232
+ The corresponding vision configuration for the `InternEncoder`.
233
+ """
234
+
235
+ def __init__(self, config: InternVisionConfig):
236
+ super().__init__()
237
+ self.config = config
238
+ # stochastic depth decay rule
239
+ dpr = [x.item() for x in torch.linspace(0, config.drop_path_rate, config.num_hidden_layers)]
240
+ self.layers = nn.ModuleList([
241
+ InternVisionEncoderLayer(config, dpr[idx]) for idx in range(config.num_hidden_layers)])
242
+ self.gradient_checkpointing = True
243
+
244
+ def forward(
245
+ self,
246
+ inputs_embeds,
247
+ output_hidden_states: Optional[bool] = None,
248
+ return_dict: Optional[bool] = None,
249
+ ) -> Union[Tuple, BaseModelOutput]:
250
+ r"""
251
+ Args:
252
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
253
+ Embedded representation of the inputs. Should be float, not int tokens.
254
+ output_hidden_states (`bool`, *optional*):
255
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
256
+ for more detail.
257
+ return_dict (`bool`, *optional*):
258
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
259
+ """
260
+ output_hidden_states = (
261
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
262
+ )
263
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
264
+
265
+ encoder_states = () if output_hidden_states else None
266
+ hidden_states = inputs_embeds
267
+
268
+ for idx, encoder_layer in enumerate(self.layers):
269
+ if output_hidden_states:
270
+ encoder_states = encoder_states + (hidden_states,)
271
+ if self.gradient_checkpointing and self.training:
272
+ layer_outputs = torch.utils.checkpoint.checkpoint(
273
+ encoder_layer,
274
+ hidden_states)
275
+ else:
276
+ layer_outputs = encoder_layer(
277
+ hidden_states,
278
+ )
279
+ hidden_states = layer_outputs
280
+
281
+ if output_hidden_states:
282
+ encoder_states = encoder_states + (hidden_states,)
283
+
284
+ if not return_dict:
285
+ return tuple(v for v in [hidden_states, encoder_states] if v is not None)
286
+ return BaseModelOutput(
287
+ last_hidden_state=hidden_states, hidden_states=encoder_states
288
+ )
289
+
290
+
291
+ class InternVisionModel(PreTrainedModel):
292
+ main_input_name = 'pixel_values'
293
+ config_class = InternVisionConfig
294
+ _no_split_modules = ['InternVisionEncoderLayer']
295
+
296
+ def __init__(self, config: InternVisionConfig):
297
+ super().__init__(config)
298
+ self.config = config
299
+
300
+ self.embeddings = InternVisionEmbeddings(config)
301
+ self.encoder = InternVisionEncoder(config)
302
+
303
+ def resize_pos_embeddings(self, old_size, new_size, patch_size):
304
+ pos_emb = self.embeddings.position_embedding
305
+ _, num_positions, embed_dim = pos_emb.shape
306
+ cls_emb = pos_emb[:, :1, :]
307
+ pos_emb = pos_emb[:, 1:, :].reshape(1, old_size // patch_size, old_size // patch_size, -1).permute(0, 3, 1, 2)
308
+ pos_emb = F.interpolate(pos_emb.float(), size=new_size // patch_size, mode='bicubic', align_corners=False)
309
+ pos_emb = pos_emb.to(cls_emb.dtype).reshape(1, embed_dim, -1).permute(0, 2, 1)
310
+ pos_emb = torch.cat([cls_emb, pos_emb], dim=1)
311
+ self.embeddings.position_embedding = nn.Parameter(pos_emb)
312
+ self.embeddings.image_size = new_size
313
+ logger.info('Resized position embeddings from {} to {}'.format(old_size, new_size))
314
+
315
+ def get_input_embeddings(self):
316
+ return self.embeddings
317
+
318
+ def forward(
319
+ self,
320
+ pixel_values: Optional[torch.FloatTensor] = None,
321
+ output_hidden_states: Optional[bool] = None,
322
+ return_dict: Optional[bool] = None,
323
+ pixel_embeds: Optional[torch.FloatTensor] = None,
324
+ ) -> Union[Tuple, BaseModelOutputWithPooling]:
325
+ output_hidden_states = (
326
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
327
+ )
328
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
329
+
330
+ if pixel_values is None and pixel_embeds is None:
331
+ raise ValueError('You have to specify pixel_values or pixel_embeds')
332
+
333
+ if pixel_embeds is not None:
334
+ hidden_states = pixel_embeds
335
+ else:
336
+ if len(pixel_values.shape) == 4:
337
+ hidden_states = self.embeddings(pixel_values)
338
+ else:
339
+ raise ValueError(f'wrong pixel_values size: {pixel_values.shape}')
340
+ encoder_outputs = self.encoder(
341
+ inputs_embeds=hidden_states,
342
+ output_hidden_states=output_hidden_states,
343
+ return_dict=return_dict,
344
+ )
345
+ last_hidden_state = encoder_outputs.last_hidden_state
346
+ pooled_output = last_hidden_state[:, 0, :]
347
+
348
+ if not return_dict:
349
+ return (last_hidden_state, pooled_output) + encoder_outputs[1:]
350
+
351
+ return BaseModelOutputWithPooling(
352
+ last_hidden_state=last_hidden_state,
353
+ pooler_output=pooled_output,
354
+ hidden_states=encoder_outputs.hidden_states,
355
+ attentions=encoder_outputs.attentions,
356
+ )
modeling_internvl_chat.py ADDED
@@ -0,0 +1,385 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # --------------------------------------------------------
2
+ # InternVL
3
+ # Copyright (c) 2023 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
+ from internvl.model.internlm2.modeling_internlm2 import InternLM2ForCausalLM
11
+ from peft import LoraConfig, get_peft_model
12
+ from torch import nn
13
+ from torch.nn import CrossEntropyLoss
14
+ from transformers import (AutoModel, GenerationConfig, LlamaForCausalLM,
15
+ LlamaTokenizer)
16
+ from transformers.modeling_outputs import CausalLMOutputWithPast
17
+ from transformers.modeling_utils import PreTrainedModel
18
+ from transformers.utils import ModelOutput, logging
19
+
20
+ from .configuration_internvl_chat import InternVLChatConfig
21
+ from .modeling_intern_vit import InternVisionModel
22
+ import pdb
23
+
24
+ logger = logging.get_logger(__name__)
25
+
26
+
27
+ class InternVLChatModel(PreTrainedModel):
28
+ config_class = InternVLChatConfig
29
+ main_input_name = 'pixel_values'
30
+ _no_split_modules = ['InternVisionEncoderLayer', 'LlamaDecoderLayer']
31
+
32
+ def __init__(self, config: InternVLChatConfig, vision_model=None, language_model=None):
33
+ super().__init__(config)
34
+
35
+ image_size = config.force_image_size or config.vision_config.image_size
36
+ patch_size = config.vision_config.patch_size
37
+ self.patch_size = patch_size
38
+ self.select_layer = config.select_layer
39
+ self.template = config.template
40
+ self.num_image_token = int((image_size // patch_size) ** 2 * (config.downsample_ratio ** 2))
41
+ self.downsample_ratio = config.downsample_ratio
42
+ self.ps_version = config.ps_version
43
+
44
+ logger.info(f'num_image_token: {self.num_image_token}')
45
+ logger.info(f'ps_version: {self.ps_version}')
46
+ if vision_model is not None:
47
+ self.vision_model = vision_model
48
+ else:
49
+ self.vision_model = InternVisionModel(config.vision_config)
50
+ if language_model is not None:
51
+ self.language_model = language_model
52
+ else:
53
+ if config.llm_config.architectures[0] == 'LlamaForCausalLM':
54
+ self.language_model = LlamaForCausalLM(config.llm_config)
55
+ elif config.llm_config.architectures[0] == 'InternLM2ForCausalLM':
56
+ self.language_model = InternLM2ForCausalLM(config.llm_config)
57
+ else:
58
+ raise NotImplementedError(f'{config.llm_config.architectures[0]} is not implemented.')
59
+
60
+ vit_hidden_size = config.vision_config.hidden_size
61
+ llm_hidden_size = config.llm_config.hidden_size
62
+
63
+ self.mlp1 = nn.Sequential(
64
+ nn.LayerNorm(vit_hidden_size * int(1 / self.downsample_ratio) ** 2),
65
+ nn.Linear(vit_hidden_size * int(1 / self.downsample_ratio) ** 2, llm_hidden_size),
66
+ nn.GELU(),
67
+ nn.Linear(llm_hidden_size, llm_hidden_size)
68
+ )
69
+
70
+ # if config.force_image_size != config.vision_config.image_size:
71
+ # self.vision_model.resize_pos_embeddings(
72
+ # old_size=config.vision_config.image_size,
73
+ # new_size=config.force_image_size,
74
+ # patch_size=config.vision_config.patch_size
75
+ # )
76
+
77
+ self.img_context_token_id = None
78
+ self.neftune_alpha = None
79
+
80
+ if config.use_backbone_lora:
81
+ self.wrap_backbone_lora(r=config.use_backbone_lora, lora_alpha=2 * config.use_backbone_lora)
82
+
83
+ if config.use_llm_lora:
84
+ self.wrap_llm_lora(r=config.use_llm_lora, lora_alpha=2 * config.use_llm_lora)
85
+
86
+ def wrap_backbone_lora(self, r=128, lora_alpha=256, lora_dropout=0.05):
87
+ lora_config = LoraConfig(
88
+ r=r,
89
+ target_modules=['attn.qkv', 'attn.proj', 'mlp.fc1', 'mlp.fc2'],
90
+ lora_alpha=lora_alpha,
91
+ lora_dropout=lora_dropout,
92
+ )
93
+ self.vision_model = get_peft_model(self.vision_model, lora_config)
94
+ self.vision_model.print_trainable_parameters()
95
+
96
+ def wrap_llm_lora(self, r=128, lora_alpha=256, lora_dropout=0.05):
97
+ lora_config = LoraConfig(
98
+ r=r,
99
+ target_modules=['self_attn.q_proj', 'self_attn.k_proj', 'self_attn.v_proj', 'self_attn.o_proj',
100
+ 'mlp.gate_proj', 'mlp.down_proj', 'mlp.up_proj'],
101
+ lora_alpha=lora_alpha,
102
+ lora_dropout=lora_dropout,
103
+ task_type='CAUSAL_LM'
104
+ )
105
+ self.language_model = get_peft_model(self.language_model, lora_config)
106
+ self.language_model.enable_input_require_grads()
107
+ self.language_model.print_trainable_parameters()
108
+
109
+ def forward(
110
+ self,
111
+ pixel_values: torch.FloatTensor,
112
+ input_ids: torch.LongTensor = None,
113
+ attention_mask: Optional[torch.Tensor] = None,
114
+ position_ids: Optional[torch.LongTensor] = None,
115
+ image_flags: Optional[torch.LongTensor] = None,
116
+ loss_reweight: Optional[torch.LongTensor] = None,
117
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
118
+ labels: Optional[torch.LongTensor] = None,
119
+ use_cache: Optional[bool] = None,
120
+ output_attentions: Optional[bool] = None,
121
+ output_hidden_states: Optional[bool] = None,
122
+ return_dict: Optional[bool] = None,
123
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
124
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
125
+
126
+ image_flags = image_flags.squeeze(-1)
127
+ input_embeds = self.language_model.get_input_embeddings()(input_ids).clone()
128
+
129
+ vit_embeds = self.extract_feature(pixel_values)
130
+ vit_embeds = vit_embeds[image_flags == 1]
131
+ vit_batch_size = pixel_values.shape[0]
132
+
133
+ B, N, C = input_embeds.shape
134
+ input_embeds = input_embeds.reshape(B * N, C)
135
+
136
+ # if torch.distributed.get_rank() == 0:
137
+ # print(f'dynamic ViT batch size: {vit_batch_size}, images per sample: {vit_batch_size / B}, dynamic token length: {N}')
138
+
139
+ input_ids = input_ids.reshape(B * N)
140
+ selected = (input_ids == self.img_context_token_id)
141
+
142
+ try:
143
+ input_embeds[selected] = input_embeds[selected] * 0.0 + vit_embeds.reshape(-1, C)
144
+ except Exception as e:
145
+ vit_embeds = vit_embeds.reshape(-1, C)
146
+ print(f'warning: {e}, input_embeds[selected].shape={input_embeds[selected].shape}, '
147
+ f'vit_embeds.shape={vit_embeds.shape}')
148
+ n_token = selected.sum()
149
+ input_embeds[selected] = input_embeds[selected] * 0.0 + vit_embeds[:n_token]
150
+
151
+ input_embeds = input_embeds.reshape(B, N, C)
152
+
153
+ outputs = self.language_model(
154
+ inputs_embeds=input_embeds,
155
+ attention_mask=attention_mask,
156
+ position_ids=position_ids,
157
+ past_key_values=past_key_values,
158
+ use_cache=use_cache,
159
+ output_attentions=output_attentions,
160
+ output_hidden_states=output_hidden_states,
161
+ return_dict=return_dict,
162
+ )
163
+ logits = outputs.logits
164
+
165
+ loss = None
166
+ if labels is not None:
167
+ # Shift so that tokens < n predict n
168
+ shift_logits = logits[..., :-1, :].contiguous()
169
+ shift_labels = labels[..., 1:].contiguous()
170
+ # shift_loss_reweights = loss_reweight[..., 1:].contiguous()
171
+ # Flatten the tokens
172
+ loss_fct = CrossEntropyLoss()
173
+ # loss_fct_reg = CrossEntropyLoss(reduction='none')
174
+ shift_logits = shift_logits.view(-1, self.language_model.config.vocab_size)
175
+ shift_labels = shift_labels.view(-1)
176
+ # shift_loss_reweights = shift_loss_reweights.view(-1)
177
+ # Enable model parallelism
178
+ shift_labels = shift_labels.to(shift_logits.device)
179
+ # shift_loss_reweights = shift_loss_reweights.to(shift_logits.device)
180
+ loss = loss_fct(shift_logits, shift_labels)
181
+ # loss = loss_fct_reg(shift_logits, shift_labels)
182
+ # loss = torch.sum(shift_loss_reweights * loss) / torch.sum(shift_loss_reweights)
183
+
184
+ if not return_dict:
185
+ output = (logits,) + outputs[1:]
186
+ return (loss,) + output if loss is not None else output
187
+
188
+ return CausalLMOutputWithPast(
189
+ loss=loss,
190
+ logits=logits,
191
+ past_key_values=outputs.past_key_values,
192
+ hidden_states=outputs.hidden_states,
193
+ attentions=outputs.attentions,
194
+ )
195
+
196
+ def pixel_shuffle(self, x, scale_factor=0.5):
197
+ n, w, h, c = x.size()
198
+ # N, W, H, C --> N, W, H * scale, C // scale
199
+ x = x.view(n, w, int(h * scale_factor), int(c / scale_factor))
200
+ # N, W, H * scale, C // scale --> N, H * scale, W, C // scale
201
+ x = x.permute(0, 2, 1, 3).contiguous()
202
+ # N, H * scale, W, C // scale --> N, H * scale, W * scale, C // (scale ** 2)
203
+ x = x.view(n, int(h * scale_factor), int(w * scale_factor),
204
+ int(c / (scale_factor * scale_factor)))
205
+ if self.ps_version == 'v1':
206
+ warnings.warn("In ps_version 'v1', the height and width have not been swapped back, "
207
+ 'which results in a transposed image.')
208
+ else:
209
+ x = x.permute(0, 2, 1, 3).contiguous()
210
+ return x
211
+
212
+ def noised_embed(self, vit_embeds, noise_alpha=5):
213
+ dims = torch.tensor(vit_embeds.size(1) * vit_embeds.size(2))
214
+ mag_norm = noise_alpha / torch.sqrt(dims)
215
+ noise = torch.zeros_like(vit_embeds).uniform_(-mag_norm, mag_norm)
216
+ return vit_embeds + noise
217
+
218
+ def extract_feature(self, pixel_values):
219
+ if self.select_layer == -1:
220
+ vit_embeds = self.vision_model(
221
+ pixel_values=pixel_values,
222
+ output_hidden_states=False,
223
+ return_dict=True).last_hidden_state
224
+ else:
225
+ vit_embeds = self.vision_model(
226
+ pixel_values=pixel_values,
227
+ output_hidden_states=True,
228
+ return_dict=True).hidden_states[self.select_layer]
229
+ vit_embeds = vit_embeds[:, 1:, :]
230
+
231
+ if self.training and self.neftune_alpha is not None:
232
+ vit_embeds = self.noised_embed(vit_embeds, self.neftune_alpha)
233
+
234
+ h = w = int(vit_embeds.shape[1] ** 0.5)
235
+ vit_embeds = vit_embeds.reshape(vit_embeds.shape[0], h, w, -1)
236
+ vit_embeds = self.pixel_shuffle(vit_embeds, scale_factor=self.downsample_ratio)
237
+ vit_embeds = vit_embeds.reshape(vit_embeds.shape[0], -1, vit_embeds.shape[-1])
238
+ vit_embeds = self.mlp1(vit_embeds)#.to(pixel_values.device)
239
+ return vit_embeds
240
+
241
+ def chat(self, tokenizer, pixel_values, question, generation_config, history=None, return_history=False,
242
+ IMG_START_TOKEN='<img>', IMG_END_TOKEN='</img>', IMG_CONTEXT_TOKEN='<IMG_CONTEXT>'):
243
+
244
+ img_context_token_id = tokenizer.convert_tokens_to_ids(IMG_CONTEXT_TOKEN)
245
+ self.img_context_token_id = img_context_token_id
246
+ if tokenizer.convert_tokens_to_ids('<|im_end|>') != 0:
247
+ eos_token_id = tokenizer.convert_tokens_to_ids('<|im_end|>') # 92542, InternLM2
248
+ else:
249
+ eos_token_id = tokenizer.eos_token_id
250
+ from internvl.conversation import get_conv_template
251
+ template = get_conv_template(self.template)
252
+ if pixel_values is not None:
253
+ image_bs = pixel_values.shape[0]
254
+ print(f'dynamic ViT batch size: {image_bs}')
255
+ image_tokens = IMG_START_TOKEN + IMG_CONTEXT_TOKEN * self.num_image_token * image_bs + IMG_END_TOKEN
256
+ # question = image_tokens + '\n' + question
257
+ question = question.replace('<image>', image_tokens)
258
+
259
+ if history is None:
260
+ history = []
261
+ else:
262
+ for (old_question, old_answer) in history:
263
+ template.append_message(template.roles[0], old_question)
264
+ template.append_message(template.roles[1], old_answer)
265
+
266
+ template.append_message(template.roles[0], question)
267
+ template.append_message(template.roles[1], None)
268
+ query = template.get_prompt()
269
+ model_inputs = tokenizer(query, return_tensors='pt')
270
+ input_ids = model_inputs['input_ids'].cuda()
271
+ attention_mask = model_inputs['attention_mask'].cuda()
272
+ generation_config['eos_token_id'] = eos_token_id
273
+ generation_output = self.generate(
274
+ pixel_values=pixel_values,
275
+ input_ids=input_ids,
276
+ attention_mask=attention_mask,
277
+ **generation_config
278
+ )
279
+ response = tokenizer.batch_decode(generation_output, skip_special_tokens=True)[0]
280
+ response = response.split('<|im_end|>')[0].strip() # for InternLM2
281
+ history.append((question, response))
282
+ if return_history:
283
+ return response, history
284
+ else:
285
+ # query_to_print = query.replace(image_tokens, '<image>')
286
+ # print(query_to_print, response)
287
+ return response
288
+ return response
289
+
290
+ def multi_image_chat(self, tokenizer, pixel_values, image_counts, question, generation_config, history=None,
291
+ return_history=False, IMG_START_TOKEN='<img>', IMG_END_TOKEN='</img>', IMG_CONTEXT_TOKEN='<IMG_CONTEXT>'):
292
+
293
+ img_context_token_id = tokenizer.convert_tokens_to_ids(IMG_CONTEXT_TOKEN)
294
+ self.img_context_token_id = img_context_token_id
295
+ if tokenizer.convert_tokens_to_ids('<|im_end|>') != 0:
296
+ eos_token_id = tokenizer.convert_tokens_to_ids('<|im_end|>') # 92542, InternLM2
297
+ else:
298
+ eos_token_id = tokenizer.eos_token_id
299
+
300
+ from internvl.conversation import get_conv_template
301
+
302
+ template = get_conv_template(self.template)
303
+
304
+ if history is None:
305
+ history = []
306
+ image_tokens = ''
307
+ image_bs = pixel_values.shape[0]
308
+ print(f'dynamic ViT batch size: {image_bs}, image_counts: {image_counts}')
309
+ for idx, image_count in enumerate(image_counts):
310
+ image_tokens += f'<image {idx+1}> (图{idx+1}):' + IMG_START_TOKEN + IMG_CONTEXT_TOKEN * self.num_image_token * image_count + IMG_END_TOKEN
311
+ question = image_tokens + '\n' + question
312
+ else:
313
+ for (old_question, old_answer) in history:
314
+ template.append_message(template.roles[0], old_question)
315
+ template.append_message(template.roles[1], old_answer)
316
+ template.append_message(template.roles[0], question)
317
+ template.append_message(template.roles[1], None)
318
+ query = template.get_prompt()
319
+ model_inputs = tokenizer(query, return_tensors='pt')
320
+ input_ids = model_inputs['input_ids'].cuda()
321
+ attention_mask = model_inputs['attention_mask'].cuda()
322
+ generation_config['eos_token_id'] = eos_token_id
323
+
324
+ generation_output = self.generate(
325
+ pixel_values=pixel_values,
326
+ input_ids=input_ids,
327
+ attention_mask=attention_mask,
328
+ **generation_config
329
+ )
330
+ response = tokenizer.batch_decode(generation_output, skip_special_tokens=True)[0]
331
+ response = response.split('<|im_end|>')[0].strip() # for InternLM2
332
+ history.append((question, response))
333
+ if return_history:
334
+ return response, history
335
+ else:
336
+ query_to_print = query.replace(image_tokens, '<image>')
337
+ print(query_to_print, response)
338
+ return response
339
+ return response
340
+
341
+ @torch.no_grad()
342
+ def generate(
343
+ self,
344
+ pixel_values: Optional[torch.FloatTensor] = None,
345
+ input_ids: Optional[torch.FloatTensor] = None,
346
+ attention_mask: Optional[torch.LongTensor] = None,
347
+ visual_features: Optional[torch.FloatTensor] = None,
348
+ generation_config: Optional[GenerationConfig] = None,
349
+ output_hidden_states: Optional[bool] = None,
350
+ return_dict: Optional[bool] = None,
351
+ **generate_kwargs,
352
+ ) -> torch.LongTensor:
353
+
354
+ assert self.img_context_token_id is not None
355
+ if pixel_values is not None:
356
+ if visual_features is not None:
357
+ vit_embeds = visual_features
358
+ else:
359
+ vit_embeds = self.extract_feature(pixel_values)
360
+
361
+ input_embeds = self.language_model.get_input_embeddings()(input_ids)
362
+ B, N, C = input_embeds.shape
363
+ input_embeds = input_embeds.reshape(B * N, C)
364
+
365
+ input_ids = input_ids.reshape(B * N)
366
+ selected = (input_ids == self.img_context_token_id)
367
+ assert selected.sum() != 0
368
+ input_embeds[selected] = vit_embeds.reshape(-1, C).to(input_embeds.device)
369
+
370
+ input_embeds = input_embeds.reshape(B, N, C)
371
+ else:
372
+ input_embeds = self.language_model.get_input_embeddings()(input_ids)
373
+
374
+ outputs = self.language_model.generate(
375
+ inputs_embeds=input_embeds,
376
+ attention_mask=attention_mask,
377
+ generation_config=generation_config,
378
+ output_hidden_states=output_hidden_states,
379
+ return_dict=return_dict,
380
+ use_cache=True,
381
+ **generate_kwargs,
382
+ )
383
+
384
+ return outputs
385
+