jadechoghari commited on
Commit
c9bbdac
·
verified ·
1 Parent(s): 93ae000

Create model_UI.py

Browse files
Files changed (1) hide show
  1. model_UI.py +256 -0
model_UI.py ADDED
@@ -0,0 +1,256 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import torch
3
+ import os
4
+ import json
5
+ from tqdm import tqdm
6
+
7
+ from constants import IMAGE_TOKEN_INDEX, DEFAULT_IMAGE_TOKEN, DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN, DEFAULT_REGION_FEA_TOKEN, VOCAB_IMAGE_W, VOCAB_IMAGE_H
8
+ from conversation import conv_templates, SeparatorStyle
9
+ from builder import load_pretrained_model
10
+ from utils import disable_torch_init
11
+ from mm_utils import tokenizer_image_token, process_images
12
+
13
+ from PIL import Image
14
+ import math
15
+ import pdb
16
+ import numpy as np
17
+ from copy import deepcopy
18
+ from functools import partial
19
+
20
+
21
+ def split_list(lst, n):
22
+ """Split a list into n (roughly) equal-sized chunks"""
23
+ chunk_size = math.ceil(len(lst) / n) # integer division
24
+ return [lst[i:i+chunk_size] for i in range(0, len(lst), chunk_size)]
25
+
26
+ def get_chunk(lst, n, k):
27
+ chunks = split_list(lst, n)
28
+ return chunks[k]
29
+
30
+ def generate_mask_for_feature(coor, raw_w, raw_h, mask=None):
31
+ if mask is not None:
32
+ assert mask.shape[0] == raw_w and mask.shape[1] == raw_h
33
+ coor_mask = np.zeros((raw_w, raw_h))
34
+ # Assume it samples a point.
35
+ if len(coor) == 2:
36
+ # Define window size
37
+ span = 5
38
+ # Make sure the window does not exceed array bounds
39
+ x_min = max(0, coor[0] - span)
40
+ x_max = min(raw_w, coor[0] + span + 1)
41
+ y_min = max(0, coor[1] - span)
42
+ y_max = min(raw_h, coor[1] + span + 1)
43
+ coor_mask[int(x_min):int(x_max), int(y_min):int(y_max)] = 1
44
+ assert (coor_mask==1).any(), f"coor: {coor}, raw_w: {raw_w}, raw_h: {raw_h}"
45
+ elif len(coor) == 4:
46
+ # Box input or Sketch input.
47
+ coor_mask[coor[0]:coor[2]+1, coor[1]:coor[3]+1] = 1
48
+ if mask is not None:
49
+ coor_mask = coor_mask * mask
50
+ coor_mask = torch.from_numpy(coor_mask)
51
+ try:
52
+ assert len(coor_mask.nonzero()) != 0
53
+ except:
54
+ pdb.set_trace()
55
+ return coor_mask
56
+
57
+ def get_task_from_file(file):
58
+ box_in_tasks = ['widgetcaptions', 'taperception', 'ocr', 'icon_recognition', 'widget_classification', 'example_0']
59
+ # box_out_tasks = ['widget_listing', 'find_text', 'find_icons', 'find_widget', 'conversation_interaction']
60
+ # no_box = ['screen2words', 'detailed_description', 'conversation_perception', 'gpt4']
61
+ if any(task in file for task in box_in_tasks):
62
+ return 'box_in'
63
+ else:
64
+ return 'no_box_in'
65
+ # elif any(task in file for task in box_out_tasks):
66
+ # return 'box_out'
67
+ # elif any(task in file for task in no_box):
68
+ # return 'no_box'
69
+
70
+ def get_bbox_coor(box, ratio_w, ratio_h):
71
+ return box[0] * ratio_w, box[1] * ratio_h, box[2] * ratio_w, box[3] * ratio_h
72
+
73
+ def get_model_name_from_path(model_path):
74
+ if 'gemma' in model_path:
75
+ return 'ferret_gemma'
76
+ elif 'llama' or 'vicuna' in model_path:
77
+ return 'ferret_llama'
78
+ else:
79
+ raise ValueError(f"No model matched for {model_path}")
80
+
81
+ class UIData:
82
+ def __init__(self, data_path, image_path, args) -> None:
83
+ self.obj_list = json.load(open(data_path, 'r'))
84
+ self.image_path = image_path
85
+ self.args = args
86
+ self._ids = range(len(self.obj_list))
87
+ self.task = get_task_from_file(data_path)
88
+
89
+ @property
90
+ def ids(self):
91
+ return deepcopy(self._ids)
92
+
93
+ def __getitem__(self, idx):
94
+ i = self.obj_list[idx]
95
+
96
+ # image stuff
97
+ image_path_i = os.path.join(self.image_path, i['image'].split('/')[-1])
98
+ image = Image.open(image_path_i).convert('RGB')
99
+
100
+ q_turn = i['conversations'][0]['value']
101
+ if "<image>" in q_turn:
102
+ prompt = q_turn.split('\n')[1]
103
+ else:
104
+ prompt = q_turn
105
+ i['question'] = prompt
106
+ i['region_masks'] = None
107
+
108
+ if self.task == 'box_in':
109
+ ratio_w = VOCAB_IMAGE_W * 1.0 / i['image_w']
110
+ ratio_h = VOCAB_IMAGE_H * 1.0 / i['image_h']
111
+
112
+ box = i['box_x1y1x2y2'][0][0]
113
+ box_x1, box_y1, box_x2, box_y2 = box
114
+ box_x1_textvocab, box_y1_textvocab, box_x2_textvocab, box_y2_textvocab = get_bbox_coor(box=box, ratio_h=ratio_h, ratio_w=ratio_w)
115
+
116
+ if self.args.region_format == 'box':
117
+ region_coordinate_raw = [box_x1, box_y1, box_x2, box_y2]
118
+ if args.add_region_feature:
119
+ i['question'] = prompt.replace('<bbox_location0>', '[{}, {}, {}, {}] {}'.format(int(box_x1_textvocab), int(box_y1_textvocab), int(box_x2_textvocab), int(box_y2_textvocab), DEFAULT_REGION_FEA_TOKEN))
120
+ generated_mask = generate_mask_for_feature(region_coordinate_raw, raw_w=i['image_w'], raw_h=i['image_h'], mask=None)
121
+ i['region_masks'] = [generated_mask]
122
+ else:
123
+ i['question'] = prompt.replace('<bbox_location0>', '[{}, {}, {}, {}]'.format(int(box_x1_textvocab), int(box_y1_textvocab), int(box_x2_textvocab), int(box_y2_textvocab)))
124
+ else:
125
+ raise NotImplementedError(f'{self.args.region_format} is not supported.')
126
+
127
+ return image, i, image.size
128
+
129
+ def eval_model(args):
130
+ # Data
131
+ dataset = UIData(data_path=args.data_path, image_path=args.image_path, args=args)
132
+ data_ids = dataset.ids
133
+
134
+ # Model
135
+ disable_torch_init()
136
+ model_path = os.path.expanduser(args.model_path)
137
+ model_name = get_model_name_from_path(model_path)
138
+ tokenizer, model, image_processor, context_len = \
139
+ load_pretrained_model(model_path, args.model_base, model_name)
140
+
141
+ chunk_data_ids = get_chunk(data_ids, args.num_chunks, args.chunk_idx)
142
+ answers_folder = os.path.expanduser(args.answers_file)
143
+ os.makedirs(answers_folder, exist_ok=True)
144
+ answers_file = os.path.join(answers_folder, f'{args.chunk_idx}_of_{args.num_chunks}.jsonl')
145
+ ans_file = open(answers_file, "w")
146
+
147
+ for i, id in enumerate(tqdm(chunk_data_ids)):
148
+ img, ann, image_size = dataset[id]
149
+ image_path = ann['image']
150
+ qs = ann["question"]
151
+ cur_prompt = qs
152
+
153
+ if "<image>" in qs:
154
+ qs = qs.split('\n')[1]
155
+
156
+ if model.config.mm_use_im_start_end:
157
+ qs = DEFAULT_IM_START_TOKEN + DEFAULT_IMAGE_TOKEN + DEFAULT_IM_END_TOKEN + '\n' + qs
158
+ else:
159
+ qs = DEFAULT_IMAGE_TOKEN + '\n' + qs
160
+
161
+ conv = conv_templates[args.conv_mode].copy()
162
+ conv.append_message(conv.roles[0], qs)
163
+ conv.append_message(conv.roles[1], None)
164
+ prompt = conv.get_prompt()
165
+
166
+ input_ids = tokenizer_image_token(prompt, tokenizer, IMAGE_TOKEN_INDEX, return_tensors='pt').unsqueeze(0).cuda()
167
+
168
+ if model.config.image_aspect_ratio == "square_nocrop":
169
+ image_tensor = image_processor.preprocess(img, return_tensors='pt', do_resize=True,
170
+ do_center_crop=False, size=[args.image_h, args.image_w])['pixel_values'][0]
171
+ elif model.config.image_aspect_ratio == "anyres":
172
+ image_process_func = partial(image_processor.preprocess, return_tensors='pt', do_resize=True, do_center_crop=False, size=[args.image_h, args.image_w])
173
+ image_tensor = process_images([img], image_processor, model.config, image_process_func=image_process_func)[0]
174
+ else:
175
+ image_tensor = process_images([img], image_processor, model.config)[0]
176
+
177
+ images = image_tensor.unsqueeze(0).to(args.data_type).cuda()
178
+
179
+ region_masks = ann['region_masks']
180
+
181
+ if region_masks is not None:
182
+ region_masks = [[region_mask_i.cuda().half() for region_mask_i in region_masks]]
183
+ else:
184
+ region_masks = None
185
+
186
+ with torch.inference_mode():
187
+ model.orig_forward = model.forward
188
+ model.forward = partial(
189
+ model.orig_forward,
190
+ region_masks=region_masks
191
+ )
192
+ output_ids = model.generate(
193
+ input_ids,
194
+ images=images,
195
+ region_masks=region_masks,
196
+ image_sizes=[image_size],
197
+ do_sample=True if args.temperature > 0 else False,
198
+ temperature=args.temperature,
199
+ top_p=args.top_p,
200
+ num_beams=args.num_beams,
201
+ max_new_tokens=args.max_new_tokens,
202
+ use_cache=True)
203
+ model.forward = model.orig_forward
204
+
205
+ outputs = tokenizer.batch_decode(output_ids, skip_special_tokens=True)[0]
206
+ outputs = outputs.strip()
207
+
208
+ if 'label' in ann:
209
+ label = ann['label']
210
+ elif len(ann['conversations']) > 1:
211
+ label = ann['conversations'][1]['value']
212
+ else:
213
+ label = None
214
+
215
+ ans_file.write(json.dumps({"id":ann['id'], # +1 offset
216
+ "image_path":image_path,
217
+ "prompt": cur_prompt,
218
+ "text": outputs,
219
+ "label": label,
220
+ }) + "\n")
221
+ ans_file.flush()
222
+ ans_file.close()
223
+
224
+
225
+ if __name__ == "__main__":
226
+ parser = argparse.ArgumentParser()
227
+ parser.add_argument("--model_path", type=str, default="facebook/opt-350m")
228
+ parser.add_argument("--vision_model_path", type=str, default=None)
229
+ parser.add_argument("--model_base", type=str, default=None)
230
+ parser.add_argument("--image_path", type=str, default="")
231
+ parser.add_argument("--data_path", type=str, default="")
232
+ parser.add_argument("--answers_file", type=str, default="")
233
+ parser.add_argument("--conv_mode", type=str, default="ferret_gemma_instruct",
234
+ help="[ferret_gemma_instruct,ferret_llama_3,ferret_vicuna_v1]")
235
+ parser.add_argument("--num_chunks", type=int, default=1)
236
+ parser.add_argument("--chunk_idx", type=int, default=0)
237
+ parser.add_argument("--image_w", type=int, default=336) # 224
238
+ parser.add_argument("--image_h", type=int, default=336) # 224
239
+ parser.add_argument("--add_region_feature", action="store_true")
240
+ parser.add_argument("--region_format", type=str, default="point", choices=["point", "box", "segment", "free_shape"])
241
+ parser.add_argument("--no_coor", action="store_true")
242
+ parser.add_argument("--temperature", type=float, default=0.001)
243
+ parser.add_argument("--top_p", type=float, default=None)
244
+ parser.add_argument("--num_beams", type=int, default=1)
245
+ parser.add_argument("--max_new_tokens", type=int, default=1024)
246
+ parser.add_argument("--data_type", type=str, default='fp16', choices=['fp16', 'bf16', 'fp32'])
247
+ args = parser.parse_args()
248
+
249
+ if args.data_type == 'fp16':
250
+ args.data_type = torch.float16
251
+ elif args.data_type == 'bf16':
252
+ args.data_type = torch.bfloat16
253
+ else:
254
+ args.data_type = torch.float32
255
+
256
+ eval_model(args)