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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright 2023 Haotian Liu
|
2 |
+
#
|
3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
4 |
+
# you may not use this file except in compliance with the License.
|
5 |
+
# You may obtain a copy of the License at
|
6 |
+
#
|
7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
8 |
+
#
|
9 |
+
# Unless required by applicable law or agreed to in writing, software
|
10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
12 |
+
# See the License for the specific language governing permissions and
|
13 |
+
# limitations under the License.
|
14 |
+
|
15 |
+
|
16 |
+
from abc import ABC, abstractmethod
|
17 |
+
import math
|
18 |
+
|
19 |
+
|
20 |
+
import torch
|
21 |
+
import torch.nn as nn
|
22 |
+
import torch.nn.functional as F
|
23 |
+
import torch.distributed as dist
|
24 |
+
|
25 |
+
from .multimodal_encoder.builder import build_vision_tower
|
26 |
+
from .multimodal_projector.builder import build_vision_projector
|
27 |
+
|
28 |
+
#This has been modified for hf implementation
|
29 |
+
from .constants import (IGNORE_INDEX, IMAGE_TOKEN_INDEX,
|
30 |
+
DEFAULT_IMAGE_PATCH_TOKEN, DEFAULT_IM_START_TOKEN,
|
31 |
+
DEFAULT_IM_END_TOKEN, DEFAULT_REGION_FEA_TOKEN)
|
32 |
+
|
33 |
+
#This has been modified for hf implementation
|
34 |
+
from .mm_utils import get_anyres_image_grid_shape
|
35 |
+
|
36 |
+
import os
|
37 |
+
|
38 |
+
def rand_sample(x, max_len):
|
39 |
+
if x.shape[0] <= max_len:
|
40 |
+
return x
|
41 |
+
else:
|
42 |
+
rand_idx = torch.randperm(x.shape[0])[:max_len]
|
43 |
+
return x[rand_idx, :]
|
44 |
+
|
45 |
+
|
46 |
+
def rand_sample_repeat(x, max_len):
|
47 |
+
if x.shape[0] < max_len:
|
48 |
+
indices = torch.randint(0, x.shape[0], (max_len-x.shape[0],))
|
49 |
+
# pdb.set_trace()
|
50 |
+
return torch.cat((x, x[indices]), dim=0)
|
51 |
+
elif x.shape[0] == max_len:
|
52 |
+
return x
|
53 |
+
else:
|
54 |
+
rand_idx = torch.randperm(x.shape[0])[:max_len]
|
55 |
+
return x[rand_idx, :]
|
56 |
+
|
57 |
+
|
58 |
+
def point_sample(input, point_coords, return_dtype, **kwargs):
|
59 |
+
"""
|
60 |
+
A wrapper around :function:`torch.nn.functional.grid_sample` to support 3D point_coords tensors.
|
61 |
+
Unlike :function:`torch.nn.functional.grid_sample` it assumes `point_coords` to lie inside
|
62 |
+
[0, 1] x [0, 1] square.
|
63 |
+
Args:
|
64 |
+
input (Tensor): A tensor of shape (N, C, H, W) that contains features map on a H x W grid.
|
65 |
+
point_coords (Tensor): A tensor of shape (N, P, 2) or (N, Hgrid, Wgrid, 2) that contains
|
66 |
+
[0, 1] x [0, 1] normalized point coordinates.
|
67 |
+
Returns:
|
68 |
+
output (Tensor): A tensor of shape (N, C, P) or (N, C, Hgrid, Wgrid) that contains
|
69 |
+
features for points in `point_coords`. The features are obtained via bilinear
|
70 |
+
interplation from `input` the same way as :function:`torch.nn.functional.grid_sample`.
|
71 |
+
"""
|
72 |
+
add_dim = False
|
73 |
+
if point_coords.dim() == 3:
|
74 |
+
add_dim = True
|
75 |
+
point_coords = point_coords.unsqueeze(2)
|
76 |
+
# output = F.grid_sample(input, 2.0 * point_coords - 1.0, **kwargs)
|
77 |
+
output = F.grid_sample(input.float(), (2.0 * point_coords - 1.0).float(), **kwargs)
|
78 |
+
output = output.to(return_dtype)
|
79 |
+
if add_dim:
|
80 |
+
output = output.squeeze(3)
|
81 |
+
return output
|
82 |
+
|
83 |
+
|
84 |
+
def farthest_point_sample(xyz, npoint):
|
85 |
+
"""
|
86 |
+
Input:
|
87 |
+
xyz: pointcloud data, [B, N, 2]
|
88 |
+
npoint: number of samples
|
89 |
+
Return:
|
90 |
+
centroids: sampled pointcloud index, [B, npoint]
|
91 |
+
"""
|
92 |
+
device = xyz.device
|
93 |
+
B, N, C = xyz.shape
|
94 |
+
centroids = torch.zeros(B, npoint, dtype=torch.long).to(device)
|
95 |
+
distance = torch.ones(B, N).to(device) * 1e10
|
96 |
+
farthest = torch.randint(0, N, (B,), dtype=torch.long).to(device)
|
97 |
+
batch_indices = torch.arange(B, dtype=torch.long).to(device)
|
98 |
+
for i in range(npoint):
|
99 |
+
centroids[:, i] = farthest
|
100 |
+
centroid = xyz[batch_indices, farthest, :].view(B, 1, 2)
|
101 |
+
dist = torch.sum((xyz - centroid) ** 2, -1)
|
102 |
+
distance = torch.min(distance, dist)
|
103 |
+
farthest = torch.max(distance, -1)[1]
|
104 |
+
return centroids
|
105 |
+
|
106 |
+
|
107 |
+
def index_points(points, idx):
|
108 |
+
"""
|
109 |
+
Input:
|
110 |
+
points: input points data, [B, N, C]
|
111 |
+
idx: sample index data, [B, S]
|
112 |
+
Return:
|
113 |
+
new_points:, indexed points data, [B, S, C]
|
114 |
+
"""
|
115 |
+
device = points.device
|
116 |
+
B = points.shape[0]
|
117 |
+
view_shape = list(idx.shape)
|
118 |
+
view_shape[1:] = [1] * (len(view_shape) - 1)
|
119 |
+
repeat_shape = list(idx.shape)
|
120 |
+
repeat_shape[0] = 1
|
121 |
+
batch_indices = torch.arange(B, dtype=torch.long).to(device).view(view_shape).repeat(repeat_shape)
|
122 |
+
new_points = points[batch_indices, idx, :]
|
123 |
+
return new_points
|
124 |
+
|
125 |
+
|
126 |
+
def square_distance(src, dst):
|
127 |
+
"""
|
128 |
+
Calculate Euclid distance between each two points.
|
129 |
+
src^T * dst = xn * xm + yn * ym + zn * zm;
|
130 |
+
sum(src^2, dim=-1) = xn*xn + yn*yn + zn*zn;
|
131 |
+
sum(dst^2, dim=-1) = xm*xm + ym*ym + zm*zm;
|
132 |
+
dist = (xn - xm)^2 + (yn - ym)^2 + (zn - zm)^2
|
133 |
+
= sum(src**2,dim=-1)+sum(dst**2,dim=-1)-2*src^T*dst
|
134 |
+
Input:
|
135 |
+
src: source points, [B, N, C]
|
136 |
+
dst: target points, [B, M, C]
|
137 |
+
Output:
|
138 |
+
dist: per-point square distance, [B, N, M]
|
139 |
+
"""
|
140 |
+
B, N, _ = src.shape
|
141 |
+
_, M, _ = dst.shape
|
142 |
+
dist = -2 * torch.matmul(src, dst.permute(0, 2, 1))
|
143 |
+
dist += torch.sum(src ** 2, -1).view(B, N, 1)
|
144 |
+
dist += torch.sum(dst ** 2, -1).view(B, 1, M)
|
145 |
+
return dist
|
146 |
+
|
147 |
+
|
148 |
+
def knn_point(nsample, xyz, new_xyz):
|
149 |
+
"""
|
150 |
+
Input:
|
151 |
+
nsample: max sample number in local region
|
152 |
+
xyz: all points, [B, N, C]
|
153 |
+
new_xyz: query points, [B, S, C]
|
154 |
+
Return:
|
155 |
+
group_idx: grouped points index, [B, S, nsample]
|
156 |
+
"""
|
157 |
+
sqrdists = square_distance(new_xyz, xyz)
|
158 |
+
_, group_idx = torch.topk(sqrdists, nsample, dim=-1, largest=False, sorted=False)
|
159 |
+
return group_idx
|
160 |
+
|
161 |
+
|
162 |
+
class ConvReLULN1D(nn.Module):
|
163 |
+
def __init__(self, in_channels, out_channels, kernel_size=1, bias=True):
|
164 |
+
super(ConvReLULN1D, self).__init__()
|
165 |
+
self.act = nn.ReLU(inplace=True)
|
166 |
+
self.net = nn.Sequential(
|
167 |
+
nn.Conv1d(in_channels=in_channels, out_channels=out_channels, kernel_size=kernel_size, bias=bias),
|
168 |
+
self.act
|
169 |
+
)
|
170 |
+
self.norm = nn.LayerNorm(out_channels)
|
171 |
+
|
172 |
+
def forward(self, x):
|
173 |
+
# (B, C, N) -> (B, C_1, N)
|
174 |
+
x = self.net(x)
|
175 |
+
x = x.permute(0, 2, 1)
|
176 |
+
x = self.norm(x)
|
177 |
+
x = x.permute(0, 2, 1)
|
178 |
+
|
179 |
+
return x
|
180 |
+
|
181 |
+
|
182 |
+
def normal_init(module, mean=0, std=1, bias=0):
|
183 |
+
if hasattr(module, 'weight') and module.weight is not None:
|
184 |
+
nn.init.normal_(module.weight, mean, std)
|
185 |
+
if hasattr(module, 'bias') and module.bias is not None:
|
186 |
+
nn.init.constant_(module.bias, bias)
|
187 |
+
|
188 |
+
|
189 |
+
class GeoRegionSampler(nn.Module):
|
190 |
+
def __init__(self,
|
191 |
+
input_dim,
|
192 |
+
output_dim,
|
193 |
+
num_init_point,
|
194 |
+
num_sub_point,
|
195 |
+
num_neighbor,
|
196 |
+
pooler_mode='mean'):
|
197 |
+
super(GeoRegionSampler, self).__init__()
|
198 |
+
self.input_dim = input_dim
|
199 |
+
self.output_dim = output_dim
|
200 |
+
self.num_init_point = num_init_point
|
201 |
+
self.num_sub_point = num_sub_point
|
202 |
+
self.num_neighbor = num_neighbor
|
203 |
+
|
204 |
+
self.diff_projector_list = nn.ModuleList()
|
205 |
+
self.agg_projector_list = nn.ModuleList()
|
206 |
+
self.pooler_list = nn.ModuleList()
|
207 |
+
|
208 |
+
for ii in range(len(num_sub_point)):
|
209 |
+
self.diff_projector_list.append(nn.Linear(self.input_dim + 2, self.input_dim + 2))
|
210 |
+
self.agg_projector_list.append(ConvReLULN1D(in_channels=2*(self.input_dim + 2),
|
211 |
+
out_channels=self.input_dim,
|
212 |
+
))
|
213 |
+
if pooler_mode == 'mean':
|
214 |
+
self.pooler_list.append(nn.AvgPool1d(kernel_size=num_neighbor[ii]))
|
215 |
+
elif pooler_mode =='max':
|
216 |
+
self.pooler_list.append(nn.AdaptiveMaxPool1d(output_size=1))
|
217 |
+
else:
|
218 |
+
raise NotImplementedError(f'{self.pooler_mode} is not supported.')
|
219 |
+
|
220 |
+
self.flatten_projector = nn.Linear(self.input_dim * num_sub_point[-1], self.input_dim)
|
221 |
+
self.dim_projector = nn.Linear(self.input_dim, self.output_dim)
|
222 |
+
# self.dim_projector = nn.Sequential(*[
|
223 |
+
# nn.Linear(self.input_dim, self.output_dim),
|
224 |
+
# nn.GELU(),
|
225 |
+
# nn.Linear(self.output_dim, self.output_dim)
|
226 |
+
# ])
|
227 |
+
|
228 |
+
self.norm_init_weights()
|
229 |
+
|
230 |
+
# self.dtype = torch.float32
|
231 |
+
def norm_init_weights(self):
|
232 |
+
for m in self.modules():
|
233 |
+
if isinstance(m, nn.Conv2d):
|
234 |
+
normal_init(m, 0, 0.01)
|
235 |
+
|
236 |
+
|
237 |
+
def forward(self,
|
238 |
+
feature_map,
|
239 |
+
region_masks,
|
240 |
+
original_dtype,
|
241 |
+
return_dtype):
|
242 |
+
|
243 |
+
assert len(feature_map) == len(region_masks)
|
244 |
+
|
245 |
+
all_points = []
|
246 |
+
all_points_fea = []
|
247 |
+
all_points_img_ids = []
|
248 |
+
|
249 |
+
# Sample points and their features
|
250 |
+
for img_idx, (region_feature_map_i, region_masks_list_i) in enumerate(zip(feature_map, region_masks)):
|
251 |
+
if len(region_masks_list_i) != 0:
|
252 |
+
# (w, h)
|
253 |
+
ori_image_wh = torch.tensor([region_masks_list_i[0].shape[0], region_masks_list_i[0].shape[1]], device=region_masks_list_i[0].device)[None,]
|
254 |
+
# list of elements of shape [num_sample_point, 2]
|
255 |
+
cur_non_zero_pos = [rand_sample_repeat((m.nonzero()/ori_image_wh), self.num_init_point) for m in region_masks_list_i]
|
256 |
+
# list -> [num_mask, num_sample_point, 2]
|
257 |
+
cur_non_zero_pos = torch.stack(cur_non_zero_pos)
|
258 |
+
# [HxW, C] -> [H, W, C] -> [C, H, W] -> [N, C, H, W]
|
259 |
+
if region_feature_map_i.ndim == 2:
|
260 |
+
h = w = int(math.sqrt(region_feature_map_i.shape[0]))
|
261 |
+
c = region_feature_map_i.shape[-1]
|
262 |
+
region_feature_map_i = region_feature_map_i.reshape(h, w, c)
|
263 |
+
else:
|
264 |
+
assert region_feature_map_i.ndim == 3
|
265 |
+
dup_region_feature_map_i = region_feature_map_i.permute(2, 0, 1)
|
266 |
+
dup_region_feature_map_i = dup_region_feature_map_i.unsqueeze(0).repeat(cur_non_zero_pos.shape[0], 1, 1, 1)
|
267 |
+
# [num_mask, C, H, W] x [num_mask, num_sample_point, 2] -> [num_mask, C, num_sample_point] -> [num_mask, num_sample_point, C]
|
268 |
+
# F.grid_sample doesn't support BF16. Need to tranform into float32 then transform back.
|
269 |
+
dup_region_feature_map_i_ori_type = dup_region_feature_map_i.to(original_dtype)
|
270 |
+
region_feature_i = point_sample(dup_region_feature_map_i_ori_type,
|
271 |
+
cur_non_zero_pos.flip(dims=(2,)).type(original_dtype),
|
272 |
+
return_dtype,
|
273 |
+
align_corners=True,
|
274 |
+
)
|
275 |
+
# region_feature_i = region_feature_i.to(dup_region_feature_map_i.dtype)
|
276 |
+
region_feature_i = region_feature_i.transpose(-2, -1)
|
277 |
+
|
278 |
+
cur_img_ids = [img_idx] * len(cur_non_zero_pos)
|
279 |
+
# save to global list
|
280 |
+
all_points.append(cur_non_zero_pos)
|
281 |
+
all_points_fea.append(region_feature_i)
|
282 |
+
all_points_img_ids.extend(cur_img_ids)
|
283 |
+
|
284 |
+
# No region found, return list of None.
|
285 |
+
if len(all_points) == 0:
|
286 |
+
return [None] * len(region_masks)
|
287 |
+
|
288 |
+
all_points = torch.cat(all_points, dim=0).to(return_dtype) # [B*num_mask, num_sample_point, 2]
|
289 |
+
all_points_fea = torch.cat(all_points_fea, dim=0) # [B*num_mask, num_sample_point, C]
|
290 |
+
all_points_img_ids = torch.tensor(all_points_img_ids, device=all_points_fea.device)
|
291 |
+
|
292 |
+
assert all_points_fea.shape[:-1] == all_points_fea.shape[:-1]
|
293 |
+
|
294 |
+
# Processing.
|
295 |
+
for stage_i in range(len(self.num_sub_point)):
|
296 |
+
cur_num_sub_point = self.num_sub_point[stage_i]
|
297 |
+
cur_num_neighbor = self.num_neighbor[stage_i]
|
298 |
+
|
299 |
+
all_points = all_points.contiguous() # xy [btach, points, xy]
|
300 |
+
fps_idx = farthest_point_sample(all_points, cur_num_sub_point).long()
|
301 |
+
|
302 |
+
new_points = index_points(all_points, fps_idx) # [B, npoint, 2]
|
303 |
+
new_points_fea = index_points(all_points_fea, fps_idx) # [B, npoint, d]
|
304 |
+
|
305 |
+
idx = knn_point(cur_num_neighbor, all_points, new_points)
|
306 |
+
grouped_points = index_points(all_points, idx) # [B, npoint, k, 2]
|
307 |
+
grouped_points_fea = index_points(all_points_fea, idx) # [B, npoint, k, d]
|
308 |
+
|
309 |
+
local_points_fea = torch.cat([grouped_points_fea, grouped_points],dim=-1) # [B, npoint, k, d+2]
|
310 |
+
anchor_points_fea = torch.cat([new_points_fea, new_points],dim=-1).unsqueeze(-2)
|
311 |
+
diff_points_fea = local_points_fea-anchor_points_fea
|
312 |
+
|
313 |
+
diff_points_fea = self.diff_projector_list[stage_i](diff_points_fea)
|
314 |
+
gather_points_fea = torch.cat([diff_points_fea, anchor_points_fea.repeat(1, 1, cur_num_neighbor, 1)], dim=-1) # [B, npoint, k, 2(d+2)]
|
315 |
+
|
316 |
+
b, n, s, d = gather_points_fea.size()
|
317 |
+
gather_points_fea = gather_points_fea.permute(0, 1, 3, 2) # [B, npoint, 2(d+2), k]
|
318 |
+
gather_points_fea = gather_points_fea.reshape(-1, d, s) # [B*npoint, 2(d+2), k]
|
319 |
+
gather_points_fea = self.agg_projector_list[stage_i](gather_points_fea) # [B*npoint, d, k]
|
320 |
+
|
321 |
+
batch_size, new_dim, _ = gather_points_fea.size()
|
322 |
+
gather_points_fea = self.pooler_list[stage_i](gather_points_fea).view(batch_size, new_dim) # [B*npoint, d]
|
323 |
+
|
324 |
+
gather_points_fea = gather_points_fea.reshape(b, n, -1) # [B, npoint, d]
|
325 |
+
|
326 |
+
all_points = new_points
|
327 |
+
all_points_fea = gather_points_fea
|
328 |
+
|
329 |
+
x = all_points_fea.flatten(1, -1) # [B, npoint x d]
|
330 |
+
x = self.flatten_projector(x)
|
331 |
+
all_region_fea = self.dim_projector(x) # [B, d]
|
332 |
+
|
333 |
+
output_region_fea = []
|
334 |
+
for img_idx in range(len(region_masks)):
|
335 |
+
cur_mask = all_points_img_ids == img_idx
|
336 |
+
|
337 |
+
if not cur_mask.any():
|
338 |
+
output_region_fea.append(None)
|
339 |
+
else:
|
340 |
+
output_region_fea.append(all_region_fea[cur_mask])
|
341 |
+
|
342 |
+
return output_region_fea
|
343 |
+
|
344 |
+
|
345 |
+
class FerretMetaModel:
|
346 |
+
|
347 |
+
def __init__(self, config):
|
348 |
+
super(FerretMetaModel, self).__init__(config)
|
349 |
+
self.max_sample_point = 512
|
350 |
+
if hasattr(config, "mm_vision_tower"):
|
351 |
+
self.vision_tower = build_vision_tower(config, delay_load=True)
|
352 |
+
self.mm_projector = build_vision_projector(config)
|
353 |
+
|
354 |
+
if 'unpad' in getattr(config, 'mm_patch_merge_type', ''):
|
355 |
+
self.image_newline = nn.Parameter(
|
356 |
+
torch.empty(config.hidden_size, dtype=self.dtype)
|
357 |
+
)
|
358 |
+
|
359 |
+
if hasattr(config, "region_fea_adapter"):
|
360 |
+
self.region_fea_adapter = nn.Linear(config.mm_hidden_size, config.hidden_size)
|
361 |
+
|
362 |
+
if hasattr(config, "region_geo_sampler"):
|
363 |
+
if getattr(config, 'mm_patch_merge_type', 'flat').startswith('spatial'):
|
364 |
+
self.region_geo_sampler = GeoRegionSampler(input_dim=config.mm_hidden_size,
|
365 |
+
output_dim=config.hidden_size,
|
366 |
+
num_init_point=self.max_sample_point,
|
367 |
+
num_sub_point=[128, 32],
|
368 |
+
num_neighbor=[24, 24],
|
369 |
+
pooler_mode=config.sampler_pooler_mode
|
370 |
+
)
|
371 |
+
else:
|
372 |
+
self.region_geo_sampler = GeoRegionSampler(input_dim=config.mm_hidden_size,
|
373 |
+
output_dim=config.hidden_size,
|
374 |
+
num_init_point=self.max_sample_point,
|
375 |
+
num_sub_point=[128, 32],
|
376 |
+
num_neighbor=[24, 24],
|
377 |
+
pooler_mode=config.sampler_pooler_mode
|
378 |
+
)
|
379 |
+
|
380 |
+
def get_vision_tower(self):
|
381 |
+
vision_tower = getattr(self, 'vision_tower', None)
|
382 |
+
if type(vision_tower) is list:
|
383 |
+
vision_tower = vision_tower[0]
|
384 |
+
return vision_tower
|
385 |
+
|
386 |
+
def initialize_vision_modules(self, model_args, fsdp=None,
|
387 |
+
add_region_feature=False,
|
388 |
+
region_geo_sampler=False,
|
389 |
+
sampler_pooler_mode='mean',
|
390 |
+
):
|
391 |
+
vision_tower = model_args.vision_tower
|
392 |
+
mm_vision_select_layer = model_args.mm_vision_select_layer
|
393 |
+
mm_vision_select_feature = model_args.mm_vision_select_feature
|
394 |
+
pretrain_mm_mlp_adapter = model_args.pretrain_mm_mlp_adapter
|
395 |
+
mm_patch_merge_type = model_args.mm_patch_merge_type
|
396 |
+
|
397 |
+
self.config.mm_vision_tower = vision_tower
|
398 |
+
|
399 |
+
if self.get_vision_tower() is None:
|
400 |
+
vision_tower = build_vision_tower(model_args)
|
401 |
+
|
402 |
+
if fsdp is not None and len(fsdp) > 0:
|
403 |
+
self.vision_tower = [vision_tower]
|
404 |
+
else:
|
405 |
+
self.vision_tower = vision_tower
|
406 |
+
else:
|
407 |
+
if fsdp is not None and len(fsdp) > 0:
|
408 |
+
vision_tower = self.vision_tower[0]
|
409 |
+
else:
|
410 |
+
vision_tower = self.vision_tower
|
411 |
+
vision_tower.load_model()
|
412 |
+
|
413 |
+
self.config.use_mm_proj = True
|
414 |
+
self.config.mm_projector_type = getattr(model_args, 'mm_projector_type', 'linear')
|
415 |
+
self.config.mm_hidden_size = vision_tower.hidden_size
|
416 |
+
self.config.mm_vision_select_layer = mm_vision_select_layer
|
417 |
+
self.config.mm_vision_select_feature = mm_vision_select_feature
|
418 |
+
self.config.mm_patch_merge_type = mm_patch_merge_type
|
419 |
+
|
420 |
+
if getattr(self, 'mm_projector', None) is None:
|
421 |
+
self.mm_projector = build_vision_projector(self.config)
|
422 |
+
|
423 |
+
if 'unpad' in mm_patch_merge_type:
|
424 |
+
embed_std = 1 / torch.sqrt(torch.tensor(self.config.hidden_size, dtype=self.dtype))
|
425 |
+
self.image_newline = nn.Parameter(
|
426 |
+
torch.randn(self.config.hidden_size, dtype=self.dtype) * embed_std
|
427 |
+
)
|
428 |
+
|
429 |
+
if add_region_feature:
|
430 |
+
if region_geo_sampler:
|
431 |
+
self.config.region_geo_sampler = True
|
432 |
+
self.config.sampler_pooler_mode = sampler_pooler_mode
|
433 |
+
|
434 |
+
if not hasattr(self, 'region_geo_sampler'):
|
435 |
+
if mm_patch_merge_type.startswith('spatial'):
|
436 |
+
# === if feature is concated ===
|
437 |
+
# self.region_geo_sampler = GeoRegionSampler(input_dim=self.config.mm_hidden_size * 2,
|
438 |
+
# output_dim=self.config.hidden_size,
|
439 |
+
# num_init_point=self.max_sample_point,
|
440 |
+
# num_sub_point=[128, 32],
|
441 |
+
# num_neighbor=[24, 24],
|
442 |
+
# pooler_mode=sampler_pooler_mode
|
443 |
+
# )
|
444 |
+
# === if feature is added ===
|
445 |
+
self.region_geo_sampler = GeoRegionSampler(input_dim=self.config.mm_hidden_size,
|
446 |
+
output_dim=self.config.hidden_size,
|
447 |
+
num_init_point=self.max_sample_point,
|
448 |
+
num_sub_point=[128, 32],
|
449 |
+
num_neighbor=[24, 24],
|
450 |
+
pooler_mode=sampler_pooler_mode
|
451 |
+
)
|
452 |
+
else:
|
453 |
+
self.region_geo_sampler = GeoRegionSampler(input_dim=self.config.mm_hidden_size,
|
454 |
+
output_dim=self.config.hidden_size,
|
455 |
+
num_init_point=self.max_sample_point,
|
456 |
+
num_sub_point=[128, 32],
|
457 |
+
num_neighbor=[24, 24],
|
458 |
+
pooler_mode=sampler_pooler_mode
|
459 |
+
)
|
460 |
+
else:
|
461 |
+
self.config.region_fea_adapter = True
|
462 |
+
if not hasattr(self, 'region_fea_adapter'):
|
463 |
+
self.region_fea_adapter = nn.Linear(self.config.mm_hidden_size, self.config.hidden_size)
|
464 |
+
|
465 |
+
else:
|
466 |
+
# In case it is frozen by LoRA
|
467 |
+
for p in self.mm_projector.parameters():
|
468 |
+
p.requires_grad = True
|
469 |
+
|
470 |
+
# print(f"pretrain mm mlp adapter: {type(pretrain_mm_mlp_adapter)}") # String
|
471 |
+
if pretrain_mm_mlp_adapter is not None and pretrain_mm_mlp_adapter != "None":
|
472 |
+
mm_projector_weights = torch.load(pretrain_mm_mlp_adapter, map_location='cpu')
|
473 |
+
def get_w(weights, keyword):
|
474 |
+
return {k.split(keyword + '.')[1]: v for k, v in weights.items() if keyword in k}
|
475 |
+
|
476 |
+
self.mm_projector.load_state_dict(get_w(mm_projector_weights, 'mm_projector'))
|
477 |
+
|
478 |
+
|
479 |
+
def unpad_image(tensor, original_size):
|
480 |
+
"""
|
481 |
+
Unpads a PyTorch tensor of a padded and resized image.
|
482 |
+
|
483 |
+
Args:
|
484 |
+
tensor (torch.Tensor): The image tensor, assumed to be in CxHxW format.
|
485 |
+
original_size (tuple): The original size of PIL image (width, height).
|
486 |
+
|
487 |
+
Returns:
|
488 |
+
torch.Tensor: The unpadded image tensor.
|
489 |
+
"""
|
490 |
+
original_width, original_height = original_size
|
491 |
+
current_height, current_width = tensor.shape[1:]
|
492 |
+
|
493 |
+
original_aspect_ratio = original_width / original_height
|
494 |
+
current_aspect_ratio = current_width / current_height
|
495 |
+
|
496 |
+
if original_aspect_ratio > current_aspect_ratio:
|
497 |
+
scale_factor = current_width / original_width
|
498 |
+
new_height = int(original_height * scale_factor)
|
499 |
+
padding = (current_height - new_height) // 2
|
500 |
+
unpadded_tensor = tensor[:, padding:current_height - padding, :]
|
501 |
+
else:
|
502 |
+
scale_factor = current_height / original_height
|
503 |
+
new_width = int(original_width * scale_factor)
|
504 |
+
padding = (current_width - new_width) // 2
|
505 |
+
unpadded_tensor = tensor[:, :, padding:current_width - padding]
|
506 |
+
|
507 |
+
return unpadded_tensor
|
508 |
+
|
509 |
+
|
510 |
+
class FerretMetaForCausalLM(ABC):
|
511 |
+
|
512 |
+
@abstractmethod
|
513 |
+
def get_model(self):
|
514 |
+
pass
|
515 |
+
|
516 |
+
def get_vision_tower(self):
|
517 |
+
return self.get_model().get_vision_tower()
|
518 |
+
|
519 |
+
def encode_images(self, images, region_flag=False, region_geo_sampler=False):
|
520 |
+
image_features = self.get_model().get_vision_tower()(images)
|
521 |
+
projected_image_features = self.get_model().mm_projector(image_features)
|
522 |
+
if region_flag:
|
523 |
+
if region_geo_sampler:
|
524 |
+
new_region_feature_map = image_features
|
525 |
+
else:
|
526 |
+
new_region_feature_map = self.get_model().region_fea_adapter(image_features)
|
527 |
+
else:
|
528 |
+
new_region_feature_map = None
|
529 |
+
|
530 |
+
return image_features, projected_image_features, new_region_feature_map
|
531 |
+
|
532 |
+
def extract_region_feature(self, region_feature_map, region_masks, original_dtype, return_dtype):
|
533 |
+
all_region_features = []
|
534 |
+
assert len(region_feature_map) == len(region_masks)
|
535 |
+
for region_feature_map_i, region_masks_list_i in zip(region_feature_map, region_masks):
|
536 |
+
if len(region_masks_list_i) == 0:
|
537 |
+
all_region_features.append(None)
|
538 |
+
else:
|
539 |
+
# (w, h)
|
540 |
+
ori_image_wh = torch.tensor([region_masks_list_i[0].shape[0], region_masks_list_i[0].shape[1]], device=region_masks_list_i[0].device)[None,]
|
541 |
+
# list of elements of shape [num_sample_point, 2]
|
542 |
+
non_zero_pos = [rand_sample((m.nonzero()/ori_image_wh), self.get_model().max_sample_point) for m in region_masks_list_i]
|
543 |
+
# [num_mask, num_sample_point(padded), 2]
|
544 |
+
non_zero_pos = nn.utils.rnn.pad_sequence(non_zero_pos, padding_value=-1, batch_first=True)
|
545 |
+
non_zero_pos_mask = ~(non_zero_pos.sum(dim=-1) < 0)
|
546 |
+
# [HxW, C] -> [H, W, C] -> [C, H, W] -> [N, C, H, W]
|
547 |
+
h = w = int(math.sqrt(region_feature_map_i.shape[0]))
|
548 |
+
c = region_feature_map_i.shape[-1]
|
549 |
+
dup_region_feature_map_i = region_feature_map_i.reshape(h, w, c).permute(2, 0, 1)
|
550 |
+
dup_region_feature_map_i = dup_region_feature_map_i.unsqueeze(0).repeat(non_zero_pos.shape[0], 1, 1, 1)
|
551 |
+
# [num_mask, C, H, W] x [num_mask, num_sample_point(padded), 2] -> [num_mask, C, num_sample_point(padded)]
|
552 |
+
# F.grid_sample doesn't support BF16. Need to tranform into float32 then transform back.
|
553 |
+
dup_region_feature_map_i_ori_type = dup_region_feature_map_i.to(original_dtype)
|
554 |
+
# pdb.set_trace()
|
555 |
+
region_feature_i = point_sample(dup_region_feature_map_i_ori_type,
|
556 |
+
non_zero_pos.flip(dims=(2,)).type(original_dtype),
|
557 |
+
return_dtype,
|
558 |
+
align_corners=True
|
559 |
+
)
|
560 |
+
region_feature_i = region_feature_i.to(dup_region_feature_map_i.dtype)
|
561 |
+
# [num_mask, C]
|
562 |
+
region_feature_i = torch.stack([x[m].mean(dim=0) for x, m in zip(region_feature_i.transpose(1,2), non_zero_pos_mask)]).nan_to_num()
|
563 |
+
all_region_features.append(region_feature_i)
|
564 |
+
|
565 |
+
return all_region_features
|
566 |
+
|
567 |
+
def prepare_inputs_labels_for_multimodal(
|
568 |
+
self, input_ids, position_ids, attention_mask, past_key_values, labels,
|
569 |
+
images, image_sizes=None, region_masks=None
|
570 |
+
):
|
571 |
+
if region_masks is not None:
|
572 |
+
region_flag = True
|
573 |
+
else:
|
574 |
+
region_flag = False
|
575 |
+
region_geo_sampler = region_flag and getattr(self.config, 'region_geo_sampler', False)
|
576 |
+
|
577 |
+
vision_tower = self.get_vision_tower()
|
578 |
+
if vision_tower is None or images is None or input_ids.shape[1] == 1:
|
579 |
+
return input_ids, position_ids, attention_mask, past_key_values, None, labels
|
580 |
+
|
581 |
+
if type(images) is list or images.ndim == 5:
|
582 |
+
if type(images) is list:
|
583 |
+
images = [x.unsqueeze(0) if x.ndim == 3 else x for x in images]
|
584 |
+
|
585 |
+
concat_images = torch.cat([image for image in images], dim=0)
|
586 |
+
raw_image_features, image_features, region_feature_map = self.encode_images(concat_images, region_flag=region_flag, region_geo_sampler=region_geo_sampler)
|
587 |
+
split_sizes = [image.shape[0] for image in images]
|
588 |
+
image_features = torch.split(image_features, split_sizes, dim=0)
|
589 |
+
|
590 |
+
if region_flag:
|
591 |
+
region_feature_maps = torch.split(region_feature_map, split_sizes, dim=0) # (#images, #patches, h*w, c)
|
592 |
+
# ======== This is for only taking the global image feature map for referring ======
|
593 |
+
# region_feature_map = torch.split(region_feature_map, split_sizes, dim=0)
|
594 |
+
# first_region_feature_map = [x[0:1] for x in region_feature_map]
|
595 |
+
# region_feature_map = torch.cat(first_region_feature_map, dim=0)
|
596 |
+
|
597 |
+
mm_patch_merge_type = getattr(self.config, 'mm_patch_merge_type', 'flat')
|
598 |
+
image_aspect_ratio = getattr(self.config, 'image_aspect_ratio', 'square_nocrop')
|
599 |
+
|
600 |
+
if mm_patch_merge_type == 'flat':
|
601 |
+
image_features = [x.flatten(0, 1) for x in image_features]
|
602 |
+
# TODO: here we use the first feature map default for each batch (global feaure map) for referring
|
603 |
+
first_region_feature_map = [x[0:1] for x in region_feature_map]
|
604 |
+
region_feature_map = torch.cat(first_region_feature_map, dim=0) # (#images, h, w, c)
|
605 |
+
elif mm_patch_merge_type.startswith('spatial'):
|
606 |
+
new_image_features = []
|
607 |
+
new_region_features = []
|
608 |
+
for image_idx, image_feature in enumerate(image_features):
|
609 |
+
if image_feature.shape[0] > 1:
|
610 |
+
base_image_feature = image_feature[0]
|
611 |
+
image_feature = image_feature[1:]
|
612 |
+
height = width = self.get_vision_tower().num_patches_per_side
|
613 |
+
assert height * width == base_image_feature.shape[0]
|
614 |
+
if region_flag:
|
615 |
+
cur_region_feature_map = region_feature_maps[image_idx] # (#patches, h*w, c)
|
616 |
+
cur_region_feature_map = cur_region_feature_map.view(cur_region_feature_map.shape[0], height, width, cur_region_feature_map.shape[-1]) # (#patches, h, w, c)
|
617 |
+
base_region_feature = cur_region_feature_map[0]
|
618 |
+
region_feature = cur_region_feature_map[1:]
|
619 |
+
# pdb.set_trace()
|
620 |
+
if image_aspect_ratio == 'anyres':
|
621 |
+
num_patch_width, num_patch_height = get_anyres_image_grid_shape(image_sizes[image_idx], self.config.image_grid_pinpoints, self.get_vision_tower().config.image_size)
|
622 |
+
image_feature = image_feature.view(num_patch_height, num_patch_width, height, width, -1)
|
623 |
+
if region_flag:
|
624 |
+
region_feature = region_feature.view(num_patch_height, num_patch_width, height, width, -1)
|
625 |
+
else:
|
626 |
+
raise NotImplementedError
|
627 |
+
|
628 |
+
if 'unpad' in mm_patch_merge_type:
|
629 |
+
image_feature = image_feature.permute(4, 0, 2, 1, 3).contiguous()
|
630 |
+
image_feature = image_feature.flatten(1, 2).flatten(2, 3)
|
631 |
+
image_feature = unpad_image(image_feature, image_sizes[image_idx])
|
632 |
+
image_feature = torch.cat((
|
633 |
+
image_feature,
|
634 |
+
self.model.image_newline[:, None, None].expand(*image_feature.shape[:-1], 1).to(image_feature.device)
|
635 |
+
), dim=-1)
|
636 |
+
image_feature = image_feature.flatten(1, 2).transpose(0, 1)
|
637 |
+
else:
|
638 |
+
image_feature = image_feature.permute(0, 2, 1, 3, 4).contiguous()
|
639 |
+
image_feature = image_feature.flatten(0, 3)
|
640 |
+
image_feature = torch.cat((base_image_feature, image_feature), dim=0)
|
641 |
+
if region_flag:
|
642 |
+
region_feature = region_feature.permute(0, 2, 1, 3, 4).contiguous() # (patch_h, patch_w, h, w, c) -> (patch_h, h, patch_w, w, c)
|
643 |
+
region_feature = region_feature.flatten(0, 1).flatten(1, 2) # (patch_h, h, patch_w, w, c) -> (all_h, all_w, c)
|
644 |
+
# Tranform dtype, if using pytorch2.1+, no need to do this.
|
645 |
+
base_region_feature = base_region_feature.to(dtype=torch.float32)
|
646 |
+
base_region_feature_resized = F.interpolate(base_region_feature.unsqueeze(0).permute(0, 3, 1, 2), (region_feature.shape[0], region_feature.shape[1])) # (1, c, all_h, all_w)
|
647 |
+
base_region_feature_resized = base_region_feature_resized.to(region_feature.dtype)
|
648 |
+
base_region_feature_resized = base_region_feature_resized.squeeze(0).permute(1, 2, 0) # (all_h, all_w, c)
|
649 |
+
# === Add:
|
650 |
+
new_region_feature = base_region_feature_resized + region_feature
|
651 |
+
# === Concat: A bit lower, 1/3 more GPU memory consumption.
|
652 |
+
# new_region_feature = torch.cat((base_region_feature_resized, region_feature), dim=2) # (all_h, all_w, 2c)
|
653 |
+
else:
|
654 |
+
image_feature = image_feature[0]
|
655 |
+
if 'unpad' in mm_patch_merge_type:
|
656 |
+
image_feature = torch.cat((
|
657 |
+
image_feature,
|
658 |
+
self.model.image_newline[None].to(image_feature.device)
|
659 |
+
), dim=0)
|
660 |
+
if region_flag:
|
661 |
+
new_region_feature = region_feature_maps[image_idx][0] # (h, w, c)
|
662 |
+
new_image_features.append(image_feature)
|
663 |
+
if region_flag:
|
664 |
+
new_region_features.append(new_region_feature)
|
665 |
+
# pdb.set_trace()
|
666 |
+
image_features = new_image_features
|
667 |
+
if region_flag:
|
668 |
+
# region_feature_map = torch.stack(new_region_features, dim=0) # (#images, h, w, c or 2c)
|
669 |
+
region_feature_map = new_region_features
|
670 |
+
# pdb.set_trace()
|
671 |
+
else:
|
672 |
+
raise ValueError(f"Unexpected mm_patch_merge_type: {self.config.mm_patch_merge_type}")
|
673 |
+
else:
|
674 |
+
raw_image_features, image_features, region_feature_map = self.encode_images(images, region_flag=region_flag, region_geo_sampler=region_geo_sampler)
|
675 |
+
|
676 |
+
if region_flag:
|
677 |
+
assert len(region_masks) == len(input_ids)
|
678 |
+
for img_idx, (cur_input_id, cur_region_mask) in enumerate(zip(input_ids, region_masks)):
|
679 |
+
cur_region_token_num = (cur_input_id == self.config.im_region_fea_token).sum()
|
680 |
+
if cur_region_token_num != len(cur_region_mask):
|
681 |
+
print('Found regions cropped because of text beyond max_len, removed them.')
|
682 |
+
region_masks[img_idx] = cur_region_mask[:cur_region_token_num]
|
683 |
+
|
684 |
+
# dump_region_mask = torch.zeros(100, 100).to(device='cuda')
|
685 |
+
dump_region_mask = torch.zeros(100, 100, device='cuda')
|
686 |
+
dump_region_mask[10:20, 10:20] = 1
|
687 |
+
dump_region_masks = [[dump_region_mask.clone()]]
|
688 |
+
for _ in range(len(region_feature_map)-1):
|
689 |
+
dump_region_masks.append([])
|
690 |
+
|
691 |
+
if region_geo_sampler:
|
692 |
+
if type(image_features) is list:
|
693 |
+
region_features = self.get_model().region_geo_sampler(region_feature_map, region_masks,
|
694 |
+
original_dtype=raw_image_features.dtype,
|
695 |
+
return_dtype=image_features[0].dtype)
|
696 |
+
dump_region_features = self.get_model().region_geo_sampler(region_feature_map, dump_region_masks,
|
697 |
+
original_dtype=raw_image_features.dtype,
|
698 |
+
return_dtype=image_features[0].dtype)
|
699 |
+
else:
|
700 |
+
region_features = self.get_model().region_geo_sampler(region_feature_map, region_masks,
|
701 |
+
original_dtype=raw_image_features.dtype,
|
702 |
+
return_dtype=image_features.dtype)
|
703 |
+
dump_region_features = self.get_model().region_geo_sampler(region_feature_map, dump_region_masks,
|
704 |
+
original_dtype=raw_image_features.dtype,
|
705 |
+
return_dtype=image_features.dtype)
|
706 |
+
else:
|
707 |
+
if type(image_features) is list:
|
708 |
+
region_features = self.extract_region_feature(region_feature_map, region_masks,
|
709 |
+
original_dtype=raw_image_features.dtype,
|
710 |
+
return_dtype=image_features[0].dtype)
|
711 |
+
dump_region_features = self.extract_region_feature(region_feature_map, dump_region_masks,
|
712 |
+
original_dtype=raw_image_features.dtype,
|
713 |
+
return_dtype=image_features[0].dtype)
|
714 |
+
else:
|
715 |
+
region_features = self.extract_region_feature(region_feature_map, region_masks,
|
716 |
+
original_dtype=raw_image_features.dtype,
|
717 |
+
return_dtype=image_features.dtype)
|
718 |
+
dump_region_features = self.extract_region_feature(region_feature_map, dump_region_masks,
|
719 |
+
original_dtype=raw_image_features.dtype,
|
720 |
+
return_dtype=image_features.dtype)
|
721 |
+
# assert len(dump_region_features) == 1
|
722 |
+
assert len([df for df in dump_region_features if df is not None]) == 1
|
723 |
+
assert len(dump_region_features[0]) == 1
|
724 |
+
assert len(region_features) == len(input_ids)
|
725 |
+
|
726 |
+
# TODO: image start / end is not implemented here to support pretraining.
|
727 |
+
if getattr(self.config, 'tune_mm_mlp_adapter', False) and getattr(self.config, 'mm_use_im_start_end', False):
|
728 |
+
raise NotImplementedError
|
729 |
+
|
730 |
+
# Let's just add dummy tensors if they do not exist,
|
731 |
+
# it is a headache to deal with None all the time.
|
732 |
+
# But it is not ideal, and if you have a better idea,
|
733 |
+
# please open an issue / submit a PR, thanks.
|
734 |
+
_labels = labels
|
735 |
+
_position_ids = position_ids
|
736 |
+
_attention_mask = attention_mask
|
737 |
+
if attention_mask is None:
|
738 |
+
attention_mask = torch.ones_like(input_ids, dtype=torch.bool)
|
739 |
+
else:
|
740 |
+
attention_mask = attention_mask.bool()
|
741 |
+
if position_ids is None:
|
742 |
+
position_ids = torch.arange(0, input_ids.shape[1], dtype=torch.long, device=input_ids.device)
|
743 |
+
if labels is None:
|
744 |
+
labels = torch.full_like(input_ids, IGNORE_INDEX)
|
745 |
+
|
746 |
+
# remove the padding using attention_mask -- FIXME
|
747 |
+
_input_ids = input_ids
|
748 |
+
input_ids = [cur_input_ids[cur_attention_mask] for cur_input_ids, cur_attention_mask in zip(input_ids, attention_mask)]
|
749 |
+
labels = [cur_labels[cur_attention_mask] for cur_labels, cur_attention_mask in zip(labels, attention_mask)]
|
750 |
+
|
751 |
+
new_input_embeds = []
|
752 |
+
new_labels = []
|
753 |
+
cur_image_idx = 0
|
754 |
+
for batch_idx, cur_input_ids in enumerate(input_ids):
|
755 |
+
num_images = (cur_input_ids == IMAGE_TOKEN_INDEX).sum()
|
756 |
+
if num_images == 0:
|
757 |
+
cur_image_features = image_features[cur_image_idx]
|
758 |
+
cur_input_embeds_1 = self.get_model().embed_tokens(cur_input_ids)
|
759 |
+
cur_input_embeds = torch.cat([cur_input_embeds_1, cur_image_features[0:0]], dim=0)
|
760 |
+
new_input_embeds.append(cur_input_embeds)
|
761 |
+
new_labels.append(labels[batch_idx])
|
762 |
+
cur_image_idx += 1
|
763 |
+
continue
|
764 |
+
|
765 |
+
image_token_indices = [-1] + torch.where(cur_input_ids == IMAGE_TOKEN_INDEX)[0].tolist() + [cur_input_ids.shape[0]]
|
766 |
+
cur_input_id_with_im = []
|
767 |
+
cur_input_ids_noim = []
|
768 |
+
cur_labels = labels[batch_idx]
|
769 |
+
cur_labels_noim = []
|
770 |
+
for i in range(len(image_token_indices) - 1):
|
771 |
+
cur_input_ids_noim.append(cur_input_ids[image_token_indices[i]+1:image_token_indices[i+1]])
|
772 |
+
cur_labels_noim.append(cur_labels[image_token_indices[i]+1:image_token_indices[i+1]])
|
773 |
+
split_sizes = [x.shape[0] for x in cur_labels_noim]
|
774 |
+
cur_input_embeds = self.get_model().embed_tokens(torch.cat(cur_input_ids_noim))
|
775 |
+
cur_input_embeds_no_im = torch.split(cur_input_embeds, split_sizes, dim=0)
|
776 |
+
cur_new_input_embeds = []
|
777 |
+
cur_new_labels = []
|
778 |
+
assert len(cur_input_ids_noim) == len(cur_input_embeds_no_im)
|
779 |
+
for i in range(num_images + 1):
|
780 |
+
cur_input_id_with_im.append(cur_input_ids_noim[i])
|
781 |
+
cur_new_input_embeds.append(cur_input_embeds_no_im[i])
|
782 |
+
cur_new_labels.append(cur_labels_noim[i])
|
783 |
+
if i < num_images:
|
784 |
+
cur_image_features = image_features[cur_image_idx]
|
785 |
+
cur_image_idx += 1
|
786 |
+
cur_input_id_with_im.append(torch.full((cur_image_features.shape[0],), IMAGE_TOKEN_INDEX, device=cur_labels.device, dtype=cur_labels.dtype))
|
787 |
+
cur_new_input_embeds.append(cur_image_features)
|
788 |
+
cur_new_labels.append(torch.full((cur_image_features.shape[0],), IGNORE_INDEX, device=cur_labels.device, dtype=cur_labels.dtype))
|
789 |
+
|
790 |
+
cur_new_input_embeds = [x.to(self.device) for x in cur_new_input_embeds]
|
791 |
+
|
792 |
+
cur_new_input_embeds = torch.cat(cur_new_input_embeds)
|
793 |
+
cur_new_labels = torch.cat(cur_new_labels)
|
794 |
+
cur_input_id_with_im = torch.cat(cur_input_id_with_im)
|
795 |
+
|
796 |
+
assert len(cur_input_id_with_im) == len(cur_new_input_embeds)
|
797 |
+
# Add region feature into text feature embeddings.
|
798 |
+
# Currently only support one image in each input.
|
799 |
+
assert batch_idx+1 == cur_image_idx
|
800 |
+
if region_flag and region_features[batch_idx] is not None:
|
801 |
+
region_embs = torch.zeros_like(cur_new_input_embeds)
|
802 |
+
region_replace_mask = (cur_input_id_with_im == self.config.im_region_fea_token)
|
803 |
+
# region_embs[region_replace_mask] = region_features[batch_idx].to(cur_new_input_embeds.dtype)
|
804 |
+
if len(region_embs[region_replace_mask]) != len(region_features[batch_idx]):
|
805 |
+
# ("Found a region cropped in text")
|
806 |
+
region_embs[region_replace_mask] = region_features[batch_idx][:len(region_embs[region_replace_mask])].to(cur_new_input_embeds.dtype)
|
807 |
+
else:
|
808 |
+
region_embs[region_replace_mask] = region_features[batch_idx].to(cur_new_input_embeds.dtype)
|
809 |
+
cur_new_input_embeds = cur_new_input_embeds * (~region_replace_mask).to(cur_new_input_embeds.dtype)[:, None] + region_embs
|
810 |
+
else:
|
811 |
+
if hasattr(self.config, 'im_region_fea_token'):
|
812 |
+
assert (cur_input_id_with_im == self.config.im_region_fea_token).sum() == 0
|
813 |
+
|
814 |
+
# Add dump region feature to input embedding, to make sure the gradient for region sampler always exist when open region_flag.
|
815 |
+
if region_flag:
|
816 |
+
# cur_new_input_embeds[0] = cur_new_input_embeds[0] + 0 * dump_region_features[0, 0].to(cur_new_input_embeds.dtype)
|
817 |
+
cur_new_input_embeds[0] = cur_new_input_embeds[0] + 0.0 * dump_region_features[0][0].to(cur_new_input_embeds.dtype)
|
818 |
+
|
819 |
+
new_input_embeds.append(cur_new_input_embeds)
|
820 |
+
new_labels.append(cur_new_labels)
|
821 |
+
|
822 |
+
# Truncate sequences to max length as image embeddings can make the sequence longer
|
823 |
+
tokenizer_model_max_length = getattr(self.config, 'tokenizer_model_max_length', None)
|
824 |
+
if tokenizer_model_max_length is not None:
|
825 |
+
new_input_embeds = [x[:tokenizer_model_max_length] for x in new_input_embeds]
|
826 |
+
new_labels = [x[:tokenizer_model_max_length] for x in new_labels]
|
827 |
+
|
828 |
+
# Combine them
|
829 |
+
max_len = max(x.shape[0] for x in new_input_embeds)
|
830 |
+
batch_size = len(new_input_embeds)
|
831 |
+
|
832 |
+
new_input_embeds_padded = []
|
833 |
+
new_labels_padded = torch.full((batch_size, max_len), IGNORE_INDEX, dtype=new_labels[0].dtype, device=new_labels[0].device)
|
834 |
+
attention_mask = torch.zeros((batch_size, max_len), dtype=attention_mask.dtype, device=attention_mask.device)
|
835 |
+
position_ids = torch.zeros((batch_size, max_len), dtype=position_ids.dtype, device=position_ids.device)
|
836 |
+
|
837 |
+
for i, (cur_new_embed, cur_new_labels) in enumerate(zip(new_input_embeds, new_labels)):
|
838 |
+
cur_len = cur_new_embed.shape[0]
|
839 |
+
if getattr(self.config, 'tokenizer_padding_side', 'right') == "left":
|
840 |
+
new_input_embeds_padded.append(torch.cat((
|
841 |
+
torch.zeros((max_len - cur_len, cur_new_embed.shape[1]), dtype=cur_new_embed.dtype, device=cur_new_embed.device),
|
842 |
+
cur_new_embed
|
843 |
+
), dim=0))
|
844 |
+
if cur_len > 0:
|
845 |
+
new_labels_padded[i, -cur_len:] = cur_new_labels
|
846 |
+
attention_mask[i, -cur_len:] = True
|
847 |
+
position_ids[i, -cur_len:] = torch.arange(0, cur_len, dtype=position_ids.dtype, device=position_ids.device)
|
848 |
+
else:
|
849 |
+
new_input_embeds_padded.append(torch.cat((
|
850 |
+
cur_new_embed,
|
851 |
+
torch.zeros((max_len - cur_len, cur_new_embed.shape[1]), dtype=cur_new_embed.dtype, device=cur_new_embed.device)
|
852 |
+
), dim=0))
|
853 |
+
if cur_len > 0:
|
854 |
+
new_labels_padded[i, :cur_len] = cur_new_labels
|
855 |
+
attention_mask[i, :cur_len] = True
|
856 |
+
position_ids[i, :cur_len] = torch.arange(0, cur_len, dtype=position_ids.dtype, device=position_ids.device)
|
857 |
+
|
858 |
+
new_input_embeds = torch.stack(new_input_embeds_padded, dim=0)
|
859 |
+
|
860 |
+
if _labels is None:
|
861 |
+
new_labels = None
|
862 |
+
else:
|
863 |
+
new_labels = new_labels_padded
|
864 |
+
|
865 |
+
if _attention_mask is None:
|
866 |
+
attention_mask = None
|
867 |
+
else:
|
868 |
+
attention_mask = attention_mask.to(dtype=_attention_mask.dtype)
|
869 |
+
|
870 |
+
if _position_ids is None:
|
871 |
+
position_ids = None
|
872 |
+
|
873 |
+
return None, position_ids, attention_mask, past_key_values, new_input_embeds, new_labels
|
874 |
+
|
875 |
+
def initialize_vision_tokenizer(self, model_args, tokenizer, add_region_feature=False):
|
876 |
+
if model_args.mm_use_im_patch_token:
|
877 |
+
tokenizer.add_tokens([DEFAULT_IMAGE_PATCH_TOKEN], special_tokens=True)
|
878 |
+
self.resize_token_embeddings(len(tokenizer))
|
879 |
+
|
880 |
+
if add_region_feature:
|
881 |
+
region_token_id = tokenizer.convert_tokens_to_ids([DEFAULT_REGION_FEA_TOKEN])[0]
|
882 |
+
# If region_token doesn't exist, add it.
|
883 |
+
if region_token_id == tokenizer.unk_token_id:
|
884 |
+
num_region_fea_tokens = tokenizer.add_tokens([DEFAULT_REGION_FEA_TOKEN], special_tokens=True)
|
885 |
+
self.config.im_region_fea_token = tokenizer.convert_tokens_to_ids([DEFAULT_REGION_FEA_TOKEN])[0]
|
886 |
+
self.resize_token_embeddings(len(tokenizer))
|
887 |
+
|
888 |
+
if model_args.mm_use_im_start_end:
|
889 |
+
num_new_tokens = tokenizer.add_tokens([DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN], special_tokens=True)
|
890 |
+
self.resize_token_embeddings(len(tokenizer))
|
891 |
+
|
892 |
+
if add_region_feature:
|
893 |
+
num_new_tokens = num_new_tokens + num_region_fea_tokens
|
894 |
+
|
895 |
+
if num_new_tokens > 0:
|
896 |
+
input_embeddings = self.get_input_embeddings().weight.data
|
897 |
+
output_embeddings = self.get_output_embeddings().weight.data
|
898 |
+
|
899 |
+
input_embeddings_avg = input_embeddings[:-num_new_tokens].mean(
|
900 |
+
dim=0, keepdim=True)
|
901 |
+
output_embeddings_avg = output_embeddings[:-num_new_tokens].mean(
|
902 |
+
dim=0, keepdim=True)
|
903 |
+
|
904 |
+
input_embeddings[-num_new_tokens:] = input_embeddings_avg
|
905 |
+
output_embeddings[-num_new_tokens:] = output_embeddings_avg
|
906 |
+
|
907 |
+
if model_args.tune_mm_mlp_adapter:
|
908 |
+
for p in self.get_input_embeddings().parameters():
|
909 |
+
p.requires_grad = True
|
910 |
+
for p in self.get_output_embeddings().parameters():
|
911 |
+
p.requires_grad = False
|
912 |
+
|
913 |
+
if model_args.pretrain_mm_mlp_adapter:
|
914 |
+
mm_projector_weights = torch.load(model_args.pretrain_mm_mlp_adapter, map_location='cpu')
|
915 |
+
embed_tokens_weight = mm_projector_weights['model.embed_tokens.weight']
|
916 |
+
assert num_new_tokens == 2
|
917 |
+
if input_embeddings.shape == embed_tokens_weight.shape:
|
918 |
+
input_embeddings[-num_new_tokens:] = embed_tokens_weight[-num_new_tokens:]
|
919 |
+
elif embed_tokens_weight.shape[0] == num_new_tokens:
|
920 |
+
input_embeddings[-num_new_tokens:] = embed_tokens_weight
|
921 |
+
else:
|
922 |
+
raise ValueError(f"Unexpected embed_tokens_weight shape. Pretrained: {embed_tokens_weight.shape}. Current: {input_embeddings.shape}. Numer of new tokens: {num_new_tokens}.")
|
923 |
+
elif model_args.mm_use_im_patch_token:
|
924 |
+
if model_args.tune_mm_mlp_adapter:
|
925 |
+
for p in self.get_input_embeddings().parameters():
|
926 |
+
p.requires_grad = False
|
927 |
+
for p in self.get_output_embeddings().parameters():
|
928 |
+
p.requires_grad = False
|