Upload modeling_intern_vit.py with huggingface_hub
Browse files- modeling_intern_vit.py +434 -0
modeling_intern_vit.py
ADDED
@@ -0,0 +1,434 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
+
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 |
+
config_class = InternVisionConfig
|
372 |
+
_no_split_modules = ['InternVisionEncoderLayer']
|
373 |
+
|
374 |
+
def __init__(self, config: InternVisionConfig):
|
375 |
+
super().__init__(config)
|
376 |
+
self.config = config
|
377 |
+
|
378 |
+
self.embeddings = InternVisionEmbeddings(config)
|
379 |
+
self.encoder = InternVisionEncoder(config)
|
380 |
+
|
381 |
+
def resize_pos_embeddings(self, old_size, new_size, patch_size):
|
382 |
+
pos_emb = self.embeddings.position_embedding
|
383 |
+
_, num_positions, embed_dim = pos_emb.shape
|
384 |
+
cls_emb = pos_emb[:, :1, :]
|
385 |
+
pos_emb = pos_emb[:, 1:, :].reshape(1, old_size // patch_size, old_size // patch_size, -1).permute(0, 3, 1, 2)
|
386 |
+
pos_emb = F.interpolate(pos_emb.float(), size=new_size // patch_size, mode='bicubic', align_corners=False)
|
387 |
+
pos_emb = pos_emb.to(cls_emb.dtype).reshape(1, embed_dim, -1).permute(0, 2, 1)
|
388 |
+
pos_emb = torch.cat([cls_emb, pos_emb], dim=1)
|
389 |
+
self.embeddings.position_embedding = nn.Parameter(pos_emb)
|
390 |
+
self.embeddings.image_size = new_size
|
391 |
+
logger.info('Resized position embeddings from {} to {}'.format(old_size, new_size))
|
392 |
+
|
393 |
+
def get_input_embeddings(self):
|
394 |
+
return self.embeddings
|
395 |
+
|
396 |
+
def forward(
|
397 |
+
self,
|
398 |
+
pixel_values: Optional[torch.FloatTensor] = None,
|
399 |
+
output_hidden_states: Optional[bool] = None,
|
400 |
+
return_dict: Optional[bool] = None,
|
401 |
+
pixel_embeds: Optional[torch.FloatTensor] = None,
|
402 |
+
) -> Union[Tuple, BaseModelOutputWithPooling]:
|
403 |
+
output_hidden_states = (
|
404 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
405 |
+
)
|
406 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
407 |
+
|
408 |
+
if pixel_values is None and pixel_embeds is None:
|
409 |
+
raise ValueError('You have to specify pixel_values or pixel_embeds')
|
410 |
+
|
411 |
+
if pixel_embeds is not None:
|
412 |
+
hidden_states = pixel_embeds
|
413 |
+
else:
|
414 |
+
if len(pixel_values.shape) == 4:
|
415 |
+
hidden_states = self.embeddings(pixel_values)
|
416 |
+
else:
|
417 |
+
raise ValueError(f'wrong pixel_values size: {pixel_values.shape}')
|
418 |
+
encoder_outputs = self.encoder(
|
419 |
+
inputs_embeds=hidden_states,
|
420 |
+
output_hidden_states=output_hidden_states,
|
421 |
+
return_dict=return_dict,
|
422 |
+
)
|
423 |
+
last_hidden_state = encoder_outputs.last_hidden_state
|
424 |
+
pooled_output = last_hidden_state[:, 0, :]
|
425 |
+
|
426 |
+
if not return_dict:
|
427 |
+
return (last_hidden_state, pooled_output) + encoder_outputs[1:]
|
428 |
+
|
429 |
+
return BaseModelOutputWithPooling(
|
430 |
+
last_hidden_state=last_hidden_state,
|
431 |
+
pooler_output=pooled_output,
|
432 |
+
hidden_states=encoder_outputs.hidden_states,
|
433 |
+
attentions=encoder_outputs.attentions,
|
434 |
+
)
|