GuanshuoXu commited on
Commit
a5d1ed5
1 Parent(s): 0b9eab7

solve flash attn issue

Browse files
configuration_h2ovl_chat.py CHANGED
@@ -4,6 +4,8 @@ from transformers.utils import logging
4
  from transformers import AutoConfig
5
  from transformers.models.auto import CONFIG_MAPPING
6
 
 
 
7
  logger = logging.get_logger(__name__)
8
 
9
  class H2OVLChatConfig(PretrainedConfig):
@@ -30,11 +32,7 @@ class H2OVLChatConfig(PretrainedConfig):
30
  **kwargs):
31
  super().__init__(**kwargs)
32
 
33
- if vision_config["model_type"] in CONFIG_MAPPING:
34
- self.vision_config = CONFIG_MAPPING[vision_config["model_type"]](**vision_config)
35
- else:
36
- self.vision_config = AutoConfig.from_pretrained(vision_config["_name_or_path"], trust_remote_code=True)
37
- self.vision_config.update(vision_config)
38
 
39
  if llm_config["model_type"] in CONFIG_MAPPING:
40
  self.llm_config = CONFIG_MAPPING[llm_config["model_type"]](**llm_config)
 
4
  from transformers import AutoConfig
5
  from transformers.models.auto import CONFIG_MAPPING
6
 
7
+ from .configuration_intern_vit import InternVisionConfig
8
+
9
  logger = logging.get_logger(__name__)
10
 
11
  class H2OVLChatConfig(PretrainedConfig):
 
32
  **kwargs):
33
  super().__init__(**kwargs)
34
 
35
+ self.vision_config = InternVisionConfig(**vision_config)
 
 
 
 
36
 
37
  if llm_config["model_type"] in CONFIG_MAPPING:
38
  self.llm_config = CONFIG_MAPPING[llm_config["model_type"]](**llm_config)
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)
modeling_intern_vit.py ADDED
@@ -0,0 +1,433 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ has_flash_attn = False
23
+ try:
24
+ from flash_attn.flash_attn_interface import flash_attn_unpadded_qkvpacked_func
25
+ from flash_attn.bert_padding import pad_input, unpad_input
26
+ has_flash_attn = True
27
+ except ImportError:
28
+ try:
29
+ from flash_attn.flash_attn_interface import flash_attn_varlen_qkvpacked_func as flash_attn_unpadded_qkvpacked_func
30
+ from flash_attn.bert_padding import pad_input, unpad_input
31
+ has_flash_attn = True
32
+ except ImportError:
33
+ print('FlashAttention is not installed.')
34
+
35
+ logger = logging.get_logger(__name__)
36
+
37
+
38
+ class FlashAttention(nn.Module):
39
+ """Implement the scaled dot product attention with softmax.
40
+ Arguments
41
+ ---------
42
+ softmax_scale: The temperature to use for the softmax attention.
43
+ (default: 1/sqrt(d_keys) where d_keys is computed at
44
+ runtime)
45
+ attention_dropout: The dropout rate to apply to the attention
46
+ (default: 0.0)
47
+ """
48
+
49
+ def __init__(self, softmax_scale=None, attention_dropout=0.0, device=None, dtype=None):
50
+ super().__init__()
51
+ self.softmax_scale = softmax_scale
52
+ self.dropout_p = attention_dropout
53
+
54
+ def forward(self, qkv, key_padding_mask=None, causal=False, cu_seqlens=None,
55
+ max_s=None, need_weights=False):
56
+ """Implements the multihead softmax attention.
57
+ Arguments
58
+ ---------
59
+ qkv: The tensor containing the query, key, and value. (B, S, 3, H, D) if key_padding_mask is None
60
+ if unpadded: (nnz, 3, h, d)
61
+ key_padding_mask: a bool tensor of shape (B, S)
62
+ """
63
+ assert not need_weights
64
+ assert qkv.dtype in [torch.float16, torch.bfloat16]
65
+ assert qkv.is_cuda
66
+
67
+ if cu_seqlens is None:
68
+ batch_size = qkv.shape[0]
69
+ seqlen = qkv.shape[1]
70
+ if key_padding_mask is None:
71
+ qkv = rearrange(qkv, 'b s ... -> (b s) ...')
72
+ max_s = seqlen
73
+ cu_seqlens = torch.arange(0, (batch_size + 1) * seqlen, step=seqlen, dtype=torch.int32,
74
+ device=qkv.device)
75
+ output = flash_attn_unpadded_qkvpacked_func(
76
+ qkv, cu_seqlens, max_s, self.dropout_p if self.training else 0.0,
77
+ softmax_scale=self.softmax_scale, causal=causal
78
+ )
79
+ output = rearrange(output, '(b s) ... -> b s ...', b=batch_size)
80
+ else:
81
+ nheads = qkv.shape[-2]
82
+ x = rearrange(qkv, 'b s three h d -> b s (three h d)')
83
+ x_unpad, indices, cu_seqlens, max_s = unpad_input(x, key_padding_mask)
84
+ x_unpad = rearrange(x_unpad, 'nnz (three h d) -> nnz three h d', three=3, h=nheads)
85
+ output_unpad = flash_attn_unpadded_qkvpacked_func(
86
+ x_unpad, cu_seqlens, max_s, self.dropout_p if self.training else 0.0,
87
+ softmax_scale=self.softmax_scale, causal=causal
88
+ )
89
+ output = rearrange(pad_input(rearrange(output_unpad, 'nnz h d -> nnz (h d)'),
90
+ indices, batch_size, seqlen),
91
+ 'b s (h d) -> b s h d', h=nheads)
92
+ else:
93
+ assert max_s is not None
94
+ output = flash_attn_unpadded_qkvpacked_func(
95
+ qkv, cu_seqlens, max_s, self.dropout_p if self.training else 0.0,
96
+ softmax_scale=self.softmax_scale, causal=causal
97
+ )
98
+
99
+ return output, None
100
+
101
+
102
+ class InternRMSNorm(nn.Module):
103
+ def __init__(self, hidden_size, eps=1e-6):
104
+ super().__init__()
105
+ self.weight = nn.Parameter(torch.ones(hidden_size))
106
+ self.variance_epsilon = eps
107
+
108
+ def forward(self, hidden_states):
109
+ input_dtype = hidden_states.dtype
110
+ hidden_states = hidden_states.to(torch.float32)
111
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
112
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
113
+ return self.weight * hidden_states.to(input_dtype)
114
+
115
+
116
+ try:
117
+ from apex.normalization import FusedRMSNorm
118
+
119
+ InternRMSNorm = FusedRMSNorm # noqa
120
+
121
+ logger.info('Discovered apex.normalization.FusedRMSNorm - will use it instead of InternRMSNorm')
122
+ except ImportError:
123
+ # using the normal InternRMSNorm
124
+ pass
125
+ except Exception:
126
+ logger.warning('discovered apex but it failed to load, falling back to InternRMSNorm')
127
+ pass
128
+
129
+
130
+ NORM2FN = {
131
+ 'rms_norm': InternRMSNorm,
132
+ 'layer_norm': nn.LayerNorm,
133
+ }
134
+
135
+
136
+ class InternVisionEmbeddings(nn.Module):
137
+ def __init__(self, config: InternVisionConfig):
138
+ super().__init__()
139
+ self.config = config
140
+ self.embed_dim = config.hidden_size
141
+ self.image_size = config.image_size
142
+ self.patch_size = config.patch_size
143
+
144
+ self.class_embedding = nn.Parameter(
145
+ torch.randn(1, 1, self.embed_dim),
146
+ )
147
+
148
+ self.patch_embedding = nn.Conv2d(
149
+ in_channels=3, out_channels=self.embed_dim, kernel_size=self.patch_size, stride=self.patch_size
150
+ )
151
+
152
+ self.num_patches = (self.image_size // self.patch_size) ** 2
153
+ self.num_positions = self.num_patches + 1
154
+
155
+ self.position_embedding = nn.Parameter(torch.randn(1, self.num_positions, self.embed_dim))
156
+
157
+ def _get_pos_embed(self, pos_embed, H, W):
158
+ target_dtype = pos_embed.dtype
159
+ pos_embed = pos_embed.float().reshape(
160
+ 1, self.image_size // self.patch_size, self.image_size // self.patch_size, -1).permute(0, 3, 1, 2)
161
+ pos_embed = F.interpolate(pos_embed, size=(H, W), mode='bicubic', align_corners=False). \
162
+ reshape(1, -1, H * W).permute(0, 2, 1).to(target_dtype)
163
+ return pos_embed
164
+
165
+ def forward(self, pixel_values: torch.FloatTensor) -> torch.Tensor:
166
+ target_dtype = self.patch_embedding.weight.dtype
167
+ patch_embeds = self.patch_embedding(pixel_values) # shape = [*, channel, width, height]
168
+ batch_size, _, height, width = patch_embeds.shape
169
+ patch_embeds = patch_embeds.flatten(2).transpose(1, 2)
170
+ class_embeds = self.class_embedding.expand(batch_size, 1, -1).to(target_dtype)
171
+ embeddings = torch.cat([class_embeds, patch_embeds], dim=1)
172
+ position_embedding = torch.cat([
173
+ self.position_embedding[:, :1, :],
174
+ self._get_pos_embed(self.position_embedding[:, 1:, :], height, width)
175
+ ], dim=1)
176
+ embeddings = embeddings + position_embedding.to(target_dtype)
177
+ return embeddings
178
+
179
+
180
+ class InternAttention(nn.Module):
181
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
182
+
183
+ def __init__(self, config: InternVisionConfig):
184
+ super().__init__()
185
+ self.config = config
186
+ self.embed_dim = config.hidden_size
187
+ self.num_heads = config.num_attention_heads
188
+ self.use_flash_attn = config.use_flash_attn and has_flash_attn
189
+ if config.use_flash_attn and not has_flash_attn:
190
+ print('Warning: Flash Attention is not available, use_flash_attn is set to False.')
191
+ self.head_dim = self.embed_dim // self.num_heads
192
+ if self.head_dim * self.num_heads != self.embed_dim:
193
+ raise ValueError(
194
+ f'embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim} and `num_heads`:'
195
+ f' {self.num_heads}).'
196
+ )
197
+
198
+ self.scale = self.head_dim ** -0.5
199
+ self.qkv = nn.Linear(self.embed_dim, 3 * self.embed_dim, bias=config.qkv_bias)
200
+ self.attn_drop = nn.Dropout(config.attention_dropout)
201
+ self.proj_drop = nn.Dropout(config.dropout)
202
+
203
+ self.qk_normalization = config.qk_normalization
204
+
205
+ if self.qk_normalization:
206
+ self.q_norm = InternRMSNorm(self.embed_dim, eps=config.layer_norm_eps)
207
+ self.k_norm = InternRMSNorm(self.embed_dim, eps=config.layer_norm_eps)
208
+
209
+ if self.use_flash_attn:
210
+ self.inner_attn = FlashAttention(attention_dropout=config.attention_dropout)
211
+ self.proj = nn.Linear(self.embed_dim, self.embed_dim)
212
+
213
+ def _naive_attn(self, x):
214
+ B, N, C = x.shape
215
+ qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4)
216
+ q, k, v = qkv.unbind(0) # make torchscript happy (cannot use tensor as tuple)
217
+
218
+ if self.qk_normalization:
219
+ B_, H_, N_, D_ = q.shape
220
+ q = self.q_norm(q.transpose(1, 2).flatten(-2, -1)).view(B_, N_, H_, D_).transpose(1, 2)
221
+ k = self.k_norm(k.transpose(1, 2).flatten(-2, -1)).view(B_, N_, H_, D_).transpose(1, 2)
222
+
223
+ attn = ((q * self.scale) @ k.transpose(-2, -1))
224
+ attn = attn.softmax(dim=-1)
225
+ attn = self.attn_drop(attn)
226
+
227
+ x = (attn @ v).transpose(1, 2).reshape(B, N, C)
228
+ x = self.proj(x)
229
+ x = self.proj_drop(x)
230
+ return x
231
+
232
+ def _flash_attn(self, x, key_padding_mask=None, need_weights=False):
233
+ qkv = self.qkv(x)
234
+ qkv = rearrange(qkv, 'b s (three h d) -> b s three h d', three=3, h=self.num_heads)
235
+
236
+ if self.qk_normalization:
237
+ q, k, v = qkv.unbind(2)
238
+ q = self.q_norm(q.flatten(-2, -1)).view(q.shape)
239
+ k = self.k_norm(k.flatten(-2, -1)).view(k.shape)
240
+ qkv = torch.stack([q, k, v], dim=2)
241
+
242
+ context, _ = self.inner_attn(
243
+ qkv, key_padding_mask=key_padding_mask, need_weights=need_weights, causal=False
244
+ )
245
+ outs = self.proj(rearrange(context, 'b s h d -> b s (h d)'))
246
+ outs = self.proj_drop(outs)
247
+ return outs
248
+
249
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
250
+ x = self._naive_attn(hidden_states) if not self.use_flash_attn else self._flash_attn(hidden_states)
251
+ return x
252
+
253
+
254
+ class InternMLP(nn.Module):
255
+ def __init__(self, config: InternVisionConfig):
256
+ super().__init__()
257
+ self.config = config
258
+ self.act = ACT2FN[config.hidden_act]
259
+ self.fc1 = nn.Linear(config.hidden_size, config.intermediate_size)
260
+ self.fc2 = nn.Linear(config.intermediate_size, config.hidden_size)
261
+
262
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
263
+ hidden_states = self.fc1(hidden_states)
264
+ hidden_states = self.act(hidden_states)
265
+ hidden_states = self.fc2(hidden_states)
266
+ return hidden_states
267
+
268
+
269
+ class InternVisionEncoderLayer(nn.Module):
270
+ def __init__(self, config: InternVisionConfig, drop_path_rate: float):
271
+ super().__init__()
272
+ self.embed_dim = config.hidden_size
273
+ self.intermediate_size = config.intermediate_size
274
+ self.norm_type = config.norm_type
275
+
276
+ self.attn = InternAttention(config)
277
+ self.mlp = InternMLP(config)
278
+ self.norm1 = NORM2FN[self.norm_type](self.embed_dim, eps=config.layer_norm_eps)
279
+ self.norm2 = NORM2FN[self.norm_type](self.embed_dim, eps=config.layer_norm_eps)
280
+
281
+ self.ls1 = nn.Parameter(config.initializer_factor * torch.ones(self.embed_dim))
282
+ self.ls2 = nn.Parameter(config.initializer_factor * torch.ones(self.embed_dim))
283
+ self.drop_path1 = DropPath(drop_path_rate) if drop_path_rate > 0. else nn.Identity()
284
+ self.drop_path2 = DropPath(drop_path_rate) if drop_path_rate > 0. else nn.Identity()
285
+
286
+ def forward(
287
+ self,
288
+ hidden_states: torch.Tensor,
289
+ ) -> Tuple[torch.FloatTensor, Optional[torch.FloatTensor], Optional[Tuple[torch.FloatTensor]]]:
290
+ """
291
+ Args:
292
+ hidden_states (`Tuple[torch.FloatTensor, Optional[torch.FloatTensor]]`): input to the layer of shape `(batch, seq_len, embed_dim)`
293
+ """
294
+ hidden_states = hidden_states + self.drop_path1(self.attn(self.norm1(hidden_states)) * self.ls1)
295
+
296
+ hidden_states = hidden_states + self.drop_path2(self.mlp(self.norm2(hidden_states)) * self.ls2)
297
+
298
+ return hidden_states
299
+
300
+
301
+ class InternVisionEncoder(nn.Module):
302
+ """
303
+ Transformer encoder consisting of `config.num_hidden_layers` self attention layers. Each layer is a
304
+ [`InternEncoderLayer`].
305
+
306
+ Args:
307
+ config (`InternConfig`):
308
+ The corresponding vision configuration for the `InternEncoder`.
309
+ """
310
+
311
+ def __init__(self, config: InternVisionConfig):
312
+ super().__init__()
313
+ self.config = config
314
+ # stochastic depth decay rule
315
+ dpr = [x.item() for x in torch.linspace(0, config.drop_path_rate, config.num_hidden_layers)]
316
+ self.layers = nn.ModuleList([
317
+ InternVisionEncoderLayer(config, dpr[idx]) for idx in range(config.num_hidden_layers)])
318
+ self.gradient_checkpointing = True
319
+
320
+ def forward(
321
+ self,
322
+ inputs_embeds,
323
+ output_hidden_states: Optional[bool] = None,
324
+ return_dict: Optional[bool] = None,
325
+ ) -> Union[Tuple, BaseModelOutput]:
326
+ r"""
327
+ Args:
328
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
329
+ Embedded representation of the inputs. Should be float, not int tokens.
330
+ output_hidden_states (`bool`, *optional*):
331
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
332
+ for more detail.
333
+ return_dict (`bool`, *optional*):
334
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
335
+ """
336
+ output_hidden_states = (
337
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
338
+ )
339
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
340
+
341
+ encoder_states = () if output_hidden_states else None
342
+ hidden_states = inputs_embeds
343
+
344
+ for idx, encoder_layer in enumerate(self.layers):
345
+ if output_hidden_states:
346
+ encoder_states = encoder_states + (hidden_states,)
347
+ if self.gradient_checkpointing and self.training:
348
+ layer_outputs = torch.utils.checkpoint.checkpoint(
349
+ encoder_layer,
350
+ hidden_states)
351
+ else:
352
+ layer_outputs = encoder_layer(
353
+ hidden_states,
354
+ )
355
+ hidden_states = layer_outputs
356
+
357
+ if output_hidden_states:
358
+ encoder_states = encoder_states + (hidden_states,)
359
+
360
+ if not return_dict:
361
+ return tuple(v for v in [hidden_states, encoder_states] if v is not None)
362
+ return BaseModelOutput(
363
+ last_hidden_state=hidden_states, hidden_states=encoder_states
364
+ )
365
+
366
+
367
+ class InternVisionModel(PreTrainedModel):
368
+ main_input_name = 'pixel_values'
369
+ _supports_flash_attn_2 = True
370
+ config_class = InternVisionConfig
371
+ _no_split_modules = ['InternVisionEncoderLayer']
372
+
373
+ def __init__(self, config: InternVisionConfig):
374
+ super().__init__(config)
375
+ self.config = config
376
+
377
+ self.embeddings = InternVisionEmbeddings(config)
378
+ self.encoder = InternVisionEncoder(config)
379
+
380
+ def resize_pos_embeddings(self, old_size, new_size, patch_size):
381
+ pos_emb = self.embeddings.position_embedding
382
+ _, num_positions, embed_dim = pos_emb.shape
383
+ cls_emb = pos_emb[:, :1, :]
384
+ pos_emb = pos_emb[:, 1:, :].reshape(1, old_size // patch_size, old_size // patch_size, -1).permute(0, 3, 1, 2)
385
+ pos_emb = F.interpolate(pos_emb.float(), size=new_size // patch_size, mode='bicubic', align_corners=False)
386
+ pos_emb = pos_emb.to(cls_emb.dtype).reshape(1, embed_dim, -1).permute(0, 2, 1)
387
+ pos_emb = torch.cat([cls_emb, pos_emb], dim=1)
388
+ self.embeddings.position_embedding = nn.Parameter(pos_emb)
389
+ self.embeddings.image_size = new_size
390
+ logger.info('Resized position embeddings from {} to {}'.format(old_size, new_size))
391
+
392
+ def get_input_embeddings(self):
393
+ return self.embeddings
394
+
395
+ def forward(
396
+ self,
397
+ pixel_values: Optional[torch.FloatTensor] = None,
398
+ output_hidden_states: Optional[bool] = None,
399
+ return_dict: Optional[bool] = None,
400
+ pixel_embeds: Optional[torch.FloatTensor] = None,
401
+ ) -> Union[Tuple, BaseModelOutputWithPooling]:
402
+ output_hidden_states = (
403
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
404
+ )
405
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
406
+
407
+ if pixel_values is None and pixel_embeds is None:
408
+ raise ValueError('You have to specify pixel_values or pixel_embeds')
409
+
410
+ if pixel_embeds is not None:
411
+ hidden_states = pixel_embeds
412
+ else:
413
+ if len(pixel_values.shape) == 4:
414
+ hidden_states = self.embeddings(pixel_values)
415
+ else:
416
+ raise ValueError(f'wrong pixel_values size: {pixel_values.shape}')
417
+ encoder_outputs = self.encoder(
418
+ inputs_embeds=hidden_states,
419
+ output_hidden_states=output_hidden_states,
420
+ return_dict=return_dict,
421
+ )
422
+ last_hidden_state = encoder_outputs.last_hidden_state
423
+ pooled_output = last_hidden_state[:, 0, :]
424
+
425
+ if not return_dict:
426
+ return (last_hidden_state, pooled_output) + encoder_outputs[1:]
427
+
428
+ return BaseModelOutputWithPooling(
429
+ last_hidden_state=last_hidden_state,
430
+ pooler_output=pooled_output,
431
+ hidden_states=encoder_outputs.hidden_states,
432
+ attentions=encoder_outputs.attentions,
433
+ )
modelling_h2ovl_chat.py CHANGED
@@ -15,6 +15,8 @@ from .configuration_h2ovl_chat import H2OVLChatConfig
15
  from .image_process import load_single_image, load_multi_images
16
  import re
17
 
 
 
18
  logger = logging.get_logger(__name__)
19
 
20
  def version_cmp(v1, v2, op='eq'):
@@ -48,7 +50,7 @@ class H2OVLChatModel(PreTrainedModel):
48
  if vision_model is not None:
49
  self.vision_model = vision_model
50
  else:
51
- self.vision_model = AutoModel.from_config(config.vision_config, trust_remote_code=True)
52
  if language_model is not None:
53
  self.language_model = language_model
54
  else:
 
15
  from .image_process import load_single_image, load_multi_images
16
  import re
17
 
18
+ from .modeling_intern_vit import InternVisionModel
19
+
20
  logger = logging.get_logger(__name__)
21
 
22
  def version_cmp(v1, v2, op='eq'):
 
50
  if vision_model is not None:
51
  self.vision_model = vision_model
52
  else:
53
+ self.vision_model = InternVisionModel(config.vision_config)
54
  if language_model is not None:
55
  self.language_model = language_model
56
  else: