Master-Shi commited on
Commit
b62803b
·
verified ·
1 Parent(s): 46a291e

Add files using upload-large-folder tool

Browse files
Files changed (20) hide show
  1. 之前的代码版本/第一版-全部代码/HuatuoGPT-Vision-v1-fullcode/cli.py +388 -0
  2. 之前的代码版本/第一版-全部代码/HuatuoGPT-Vision-v1-fullcode/eval.py +179 -0
  3. 之前的代码版本/第一版-全部代码/HuatuoGPT-Vision-v1-fullcode/run_all_attnbias_sam.sh +23 -0
  4. 之前的代码版本/第一版-全部代码/HuatuoGPT-Vision-v1-fullcode/run_eval_attnbias_sam_both.sh +57 -0
  5. 之前的代码版本/第一版-全部代码/HuatuoGPT-Vision-v1-fullcode/run_eval_attnbias_sam_text.sh +57 -0
  6. 之前的代码版本/第一版-全部代码/HuatuoGPT-Vision-v1-fullcode/scorer.py +195 -0
  7. 之前的代码版本/第一版-全部代码/HuatuoGPT-Vision-v1-fullcode/train_vl.py +496 -0
  8. 之前的代码版本/第一版-全部代码/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/docs/LLaVA-NeXT-Video.md +81 -0
  9. 之前的代码版本/第一版-全部代码/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/docs/LLaVA_OneVision.md +121 -0
  10. 之前的代码版本/第一版-全部代码/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/docs/LLaVA_OneVision_Tutorials.ipynb +397 -0
  11. 之前的代码版本/第一版-全部代码/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/docs/README.md +18 -0
  12. 之前的代码版本/第一版-全部代码/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/docs/onevision_trial.py +111 -0
  13. 之前的代码版本/第一版-全部代码/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/playground/2d_hist.py +132 -0
  14. 之前的代码版本/第一版-全部代码/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/playground/data_checker.py +364 -0
  15. 之前的代码版本/第一版-全部代码/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/playground/demo/video_demo.py +335 -0
  16. 之前的代码版本/第一版-全部代码/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/playground/equal_splitter.py +38 -0
  17. 之前的代码版本/第一版-全部代码/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/playground/llava_ov_plot.ipynb +0 -0
  18. 之前的代码版本/第一版-全部代码/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/playground/remove_mid_ckpt.py +35 -0
  19. 之前的代码版本/第一版-全部代码/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/playground/sgl_llava_inference_multinode.py +125 -0
  20. 之前的代码版本/第一版-全部代码/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/playground/upload_data.py +217 -0
之前的代码版本/第一版-全部代码/HuatuoGPT-Vision-v1-fullcode/cli.py ADDED
@@ -0,0 +1,388 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+ import os
3
+ file_path = os.path.abspath(__file__)
4
+ dir_path = os.path.dirname(file_path)
5
+ print(dir_path)
6
+ sys.path.insert(0, dir_path)
7
+ from llava.constants import IMAGE_TOKEN_INDEX, DEFAULT_IMAGE_TOKEN, DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN
8
+ from llava.model import *
9
+
10
+ from transformers import AutoTokenizer
11
+ from transformers import TextIteratorStreamer
12
+ from threading import Thread
13
+ import torch
14
+
15
+ from PIL import Image
16
+
17
+ class HuatuoChatbot():
18
+ def __init__(self, model_dir, device = 'cuda'):
19
+ self.model_dir = model_dir
20
+
21
+ self.gen_kwargs = {
22
+ 'do_sample': True,
23
+ 'max_new_tokens': 512,
24
+ 'min_new_tokens': 1,
25
+ 'temperature': .2,
26
+ 'repetition_penalty': 1.2
27
+ }
28
+ self.device = device
29
+ self.init_components()
30
+ self.history = []
31
+ self.images = []
32
+ self.debug = True
33
+ self.max_image_num = 6
34
+
35
+
36
+ def init_components(self):
37
+
38
+ d = self.model_dir
39
+ if 'huatuogpt-vision-7b' in d.lower():
40
+ print(f'loading from {self.model_dir}')
41
+ from llava.model.language_model.llava_qwen2 import LlavaQwen2ForCausalLM
42
+ model, loading_info = LlavaQwen2ForCausalLM.from_pretrained(self.model_dir, init_vision_encoder_from_ckpt=True, output_loading_info=True, torch_dtype=torch.bfloat16)
43
+ missing_keys = loading_info['missing_keys'] # keys exists in model architecture but does not exist in ckpt
44
+ unexpected_keys = loading_info['unexpected_keys'] # keys exists in ckpt but are not loaded by the model
45
+ assert all(['vision_tower' in k for k in unexpected_keys])
46
+
47
+ tokenizer = AutoTokenizer.from_pretrained(self.model_dir)
48
+ tokenizer.pad_token_id = tokenizer.eos_token_id
49
+ self.gen_kwargs['eos_token_id'] = tokenizer.eos_token_id
50
+ self.gen_kwargs['pad_token_id'] = tokenizer.pad_token_id if tokenizer.pad_token_id else tokenizer.eos_token_id
51
+ vision_tower = model.get_vision_tower()
52
+ if not vision_tower.is_loaded:
53
+ vision_tower.load_model()
54
+ vision_tower.vision_tower = vision_tower.vision_tower.from_pretrained(self.model_dir)
55
+ vision_tower.to(dtype=torch.bfloat16, device=model.device)
56
+ image_processor = vision_tower.image_processor
57
+
58
+ elif 'huatuogpt' in d.lower():
59
+ print(f'loading from {self.model_dir}')
60
+ from llava.model.language_model.llava_llama import LlavaLlamaForCausalLM
61
+ model, loading_info = LlavaLlamaForCausalLM.from_pretrained(self.model_dir, init_vision_encoder_from_ckpt=True, output_loading_info=True, torch_dtype=torch.bfloat16)
62
+ missing_keys = loading_info['missing_keys'] # keys exists in model architecture but does not exist in ckpt
63
+ unexpected_keys = loading_info['unexpected_keys'] # keys exists in ckpt but are not loaded by the model
64
+ assert all(['vision_tower' in k for k in unexpected_keys])
65
+
66
+ tokenizer = AutoTokenizer.from_pretrained(self.model_dir)
67
+ tokenizer.pad_token_id = tokenizer.eos_token_id
68
+ self.gen_kwargs['eos_token_id'] = tokenizer.eos_token_id
69
+ self.gen_kwargs['pad_token_id'] = tokenizer.pad_token_id if tokenizer.pad_token_id else tokenizer.eos_token_id
70
+ vision_tower = model.get_vision_tower()
71
+ if not vision_tower.is_loaded:
72
+ vision_tower.load_model()
73
+ vision_tower.vision_tower = vision_tower.vision_tower.from_pretrained(self.model_dir)
74
+ vision_tower.to(dtype=torch.bfloat16, device=model.device)
75
+ image_processor = vision_tower.image_processor
76
+
77
+ else:
78
+ raise NotImplementedError
79
+
80
+ model.eval()
81
+ self.model = model.to(self.device)
82
+ self.model.config.tokenizer_padding_side = 'left'
83
+ self.tokenizer = tokenizer
84
+ self.processor = image_processor
85
+
86
+
87
+ def clear_history(self,):
88
+ self.images = []
89
+ self.history = []
90
+
91
+ def tokenizer_image_token(self, prompt, image_token_index=IMAGE_TOKEN_INDEX, return_tensors=None): # copied from llava
92
+ prompt_chunks = [self.tokenizer(chunk, add_special_tokens=False).input_ids for chunk in prompt.split('<image>')]
93
+
94
+ def insert_separator(X, sep):
95
+ return [ele for sublist in zip(X, [sep]*len(X)) for ele in sublist][:-1]
96
+
97
+ input_ids = []
98
+ offset = 0
99
+ if len(prompt_chunks) > 0 and len(prompt_chunks[0]) > 0 and prompt_chunks[0][0] == self.tokenizer.bos_token_id:
100
+ offset = 1
101
+ input_ids.append(prompt_chunks[0][0])
102
+
103
+ for x in insert_separator(prompt_chunks, [image_token_index] * (offset + 1)):
104
+ input_ids.extend(x[offset:])
105
+
106
+ if return_tensors is not None:
107
+ if return_tensors == 'pt':
108
+ return torch.tensor(input_ids, dtype=torch.long)
109
+ raise ValueError(f'Unsupported tensor type: {return_tensors}')
110
+ return input_ids
111
+
112
+ def preprocess(self, data: list, return_tensors='pt'):
113
+ '''
114
+ [
115
+ {
116
+ 'from': 'human',
117
+ 'value': xxx,
118
+ },
119
+ {
120
+ 'from': 'gpt',
121
+ 'value': xxx
122
+ }
123
+ ]
124
+ '''
125
+ if not isinstance(data, list):
126
+ raise ValueError('must be a list')
127
+ return self.preprocess_huatuo(data, return_tensors=return_tensors)
128
+
129
+ def preprocess_huatuo(self, convs: list, return_tensors) -> list: # tokenize and concat the coversations
130
+ input_ids = None
131
+ convs = [ conv for conv in convs if conv['value'] is not None]
132
+ round_num = len(convs)//2
133
+
134
+ for ind in range(round_num):
135
+ h = convs[ind*2]['value'].strip()
136
+ h = f"<|user|>\n{h}\n"
137
+
138
+ g = convs[ind*2+1]['value']
139
+ g = f"<|assistant|>\n{g} \n"
140
+
141
+ cur_input_ids = self.tokenizer_image_token(prompt=h, return_tensors=return_tensors)
142
+
143
+ if input_ids is None:
144
+ input_ids = cur_input_ids
145
+ else:
146
+ input_ids = torch.cat([input_ids, cur_input_ids])
147
+
148
+ cur_input_ids = self.tokenizer(g, add_special_tokens= False, truncation=True, return_tensors='pt').input_ids[0]
149
+ input_ids = torch.cat([input_ids, cur_input_ids])
150
+
151
+ h = convs[-1]['value'].strip()
152
+ h = f"<|user|>\n{h}\n<|assistant|>\n"
153
+ cur_input_ids = self.tokenizer_image_token(prompt=h, return_tensors=return_tensors)
154
+
155
+ if input_ids is None:
156
+ input_ids = cur_input_ids
157
+ else:
158
+ input_ids = torch.cat([input_ids, cur_input_ids])
159
+
160
+ if self.debug:
161
+ self.debug = False
162
+
163
+ return input_ids
164
+
165
+
166
+ def input_moderation(self, t: str):
167
+ blacklist = ['<image>', '<s>', '</s>']
168
+ for b in blacklist:
169
+ t = t.replace(b, '')
170
+ return t
171
+
172
+ def insert_image_placeholder(self, t, num_images, placeholder='<image>', sep='\n'):
173
+ for _ in range(num_images):
174
+ t = f"{placeholder}{sep}" + t
175
+
176
+ return t
177
+
178
+ def get_conv(self, text):
179
+ ret = []
180
+ if self.history is None:
181
+ self.history = []
182
+
183
+ for conv in self.history:
184
+ ret.append({'from': 'human', 'value': conv[0]})
185
+ ret.append({'from': 'gpt', 'value': conv[1]})
186
+
187
+ ret.append({'from': 'human', 'value': text})
188
+ ret.append({'from': 'gpt', 'value': None})
189
+
190
+ return ret
191
+
192
+ def get_conv_without_history(self, text):
193
+ ret = []
194
+
195
+ ret.append({'from': 'human', 'value': text})
196
+ ret.append({'from': 'gpt', 'value': None})
197
+
198
+ return ret
199
+
200
+ def get_image_tensors(self, images):
201
+ list_image_tensors = []
202
+ crop_size = self.processor.crop_size
203
+ processor = self.processor
204
+ for fp in images:
205
+ if fp is None: # None is used as a placeholder
206
+ continue
207
+ elif isinstance(fp, str):
208
+ image = Image.open(fp).convert('RGB')
209
+ elif isinstance(fp, Image.Image):
210
+ image = fp # already an image
211
+ else:
212
+ raise TypeError(f'Unsupported type {type(fp)}')
213
+
214
+ if True or self.data_args.image_aspect_ratio == 'pad':
215
+ def expand2square(pil_img, background_color):
216
+ width, height = pil_img.size
217
+ if width == height:
218
+ return pil_img
219
+ elif width > height:
220
+ result = Image.new(pil_img.mode, (width, width), background_color)
221
+ result.paste(pil_img, (0, (width - height) // 2))
222
+ return result
223
+ else:
224
+ result = Image.new(pil_img.mode, (height, height), background_color)
225
+ result.paste(pil_img, ((height - width) // 2, 0))
226
+ return result
227
+ image = expand2square(image, tuple(int(x*255) for x in processor.image_mean))
228
+ image = processor.preprocess(image, return_tensors='pt')['pixel_values'][0]
229
+ else:
230
+ image = processor.preprocess(image, return_tensors='pt')['pixel_values'][0] # a tensor
231
+ list_image_tensors.append(image.to(self.device))
232
+ if len(list_image_tensors) == 0:
233
+ list_image_tensors.append(torch.zeros(3, crop_size['height'], crop_size['width']).to(self.device))
234
+ return list_image_tensors
235
+
236
+ def inference(self, text, images=None):
237
+ '''
238
+ text: str
239
+ images: list[str]
240
+ '''
241
+
242
+ # image
243
+ if images is None:
244
+ images = []
245
+
246
+ if isinstance(images,str):
247
+ images = [images]
248
+
249
+ valid_images = []
250
+ for img in images:
251
+ try:
252
+ if isinstance(img, str):
253
+ Image.open(img).convert('RGB') # make sure that the path exists
254
+ valid_images.append(img)
255
+ except:
256
+ print(f'{img} This image is wrong.')
257
+ continue
258
+ images = valid_images
259
+ if len(valid_images) > self.max_image_num:
260
+ images = images[:self.max_image_num]
261
+
262
+ # text
263
+ text = self.input_moderation(text)
264
+ text = self.insert_image_placeholder(text, len(images) if None not in images else 0)
265
+
266
+ conv = self.get_conv_without_history(text)
267
+ input_ids = self.preprocess(conv, return_tensors='pt').unsqueeze(0).to(self.device)
268
+
269
+ if len(images) > 0:
270
+ list_image_tensors = self.get_image_tensors(images)
271
+ image_tensors = torch.stack(list_image_tensors).to(dtype=torch.bfloat16).to(self.device)
272
+ else:
273
+ image_tensors = None
274
+
275
+ with torch.inference_mode():
276
+ output_ids = self.model.generate(
277
+ input_ids,
278
+ images=image_tensors,
279
+ use_cache=True,
280
+ **self.gen_kwargs)
281
+ answers = []
282
+ for output_id in output_ids:
283
+ answers.append(self.tokenizer.decode(output_id, skip_special_tokens=True).strip())
284
+ return answers
285
+
286
+ def chat(self, text: str, images: list[str]=None, ):
287
+ '''
288
+ images: list[str], images for this round
289
+ text: str
290
+ '''
291
+ text = self.input_moderation(text)
292
+ if text == '':
293
+ return 'Please type in something'
294
+
295
+ if isinstance(images, str) or isinstance(images, Image.Image):
296
+ images = [images]
297
+
298
+ valid_images = []
299
+ if images is None:
300
+ images = []
301
+
302
+ for img in images:
303
+ try:
304
+ if isinstance(img, str):
305
+ Image.open(img).convert('RGB') # make sure that the path exists
306
+ valid_images.append(img)
307
+ except:
308
+ continue
309
+
310
+ images = valid_images
311
+
312
+ self.images.extend(images)
313
+
314
+
315
+ assert len(images) < self.max_image_num, f'at most {self.max_image_num} images'
316
+
317
+ text = self.insert_image_placeholder(text, len(images) if None not in images else 0)
318
+ # make conv
319
+ conv = self.get_conv(text)
320
+ # make input ids
321
+ input_ids = self.preprocess(conv, return_tensors='pt').unsqueeze(0).to(self.device)
322
+
323
+ if len(self.images) > 0:
324
+ list_image_tensors = self.get_image_tensors(self.images)
325
+ image_tensors = torch.stack(list_image_tensors)
326
+ else:
327
+ image_tensors = None
328
+
329
+ streamer = TextIteratorStreamer(self.tokenizer,skip_prompt=True, skip_special_tokens=True)
330
+ generation_kwargs = dict(inputs=input_ids,images=image_tensors.to(dtype=torch.bfloat16) if image_tensors is not None else image_tensors, streamer=streamer,use_cache=True,**self.gen_kwargs)
331
+
332
+
333
+ with torch.inference_mode():
334
+ thread = Thread(target=self.model.generate, kwargs=generation_kwargs)
335
+ thread.start()
336
+ generated_text = ''
337
+ sep = self.tokenizer.convert_ids_to_tokens(self.tokenizer.eos_token_id)
338
+ for new_text in streamer:
339
+ if sep in new_text:
340
+ new_text = self.remove_overlap(generated_text,new_text[:-len(sep)])
341
+ for char in new_text:
342
+ generated_text += char
343
+ print(char,end='',flush = True)
344
+ break
345
+ for char in new_text:
346
+ generated_text += char
347
+ print(char,end='',flush = True)
348
+ answer = generated_text
349
+
350
+ self.history.append([text, answer])
351
+
352
+ return answer
353
+
354
+
355
+ if __name__ =="__main__":
356
+
357
+ import argparse
358
+ parser = argparse.ArgumentParser(description='Args of Data Preprocess')
359
+
360
+ parser.add_argument('--model_dir', default='', type=str)
361
+ parser.add_argument('--device', default='cuda:0', type=str)
362
+ args = parser.parse_args()
363
+
364
+ bot = HuatuoChatbot(args.model_dir, args.device)
365
+
366
+ # test
367
+ # print(bot.inference('what show in this picture?',['./output.png']))
368
+ # print(bot.inference('hi'))
369
+
370
+ while True:
371
+ images = input('images, split by ",": ')
372
+ images = [i.strip() for i in images.split(',') if len(i.strip()) > 1 ]
373
+ text = input('USER ("clear" to clear history, "q" to exit): ')
374
+ if text.lower() in ['q', 'quit']:
375
+ exit()
376
+
377
+ if text.lower() == 'clear':
378
+ bot.history = []
379
+ bot.images = []
380
+ continue
381
+
382
+ answer = bot.chat(images=images, text=text)
383
+
384
+ images = None # already in the history
385
+
386
+ print()
387
+ print(f'GPT: {answer}')
388
+ print()
之前的代码版本/第一版-全部代码/HuatuoGPT-Vision-v1-fullcode/eval.py ADDED
@@ -0,0 +1,179 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Code for finetune_huatuo"""
2
+
3
+ import os
4
+ import copy
5
+ import json
6
+ import torch
7
+ import logging
8
+ import argparse
9
+ from transformers.generation.utils import LogitsProcessorList
10
+ from transformers.generation.logits_process import LogitsProcessor
11
+ import sys
12
+ import ast
13
+
14
+ from tqdm import tqdm
15
+ import torch.distributed as dist
16
+ from torch.utils.data import Dataset, DataLoader
17
+ from accelerate import Accelerator, DeepSpeedPlugin
18
+ from transformers import set_seed
19
+ import datasets
20
+ import shutil
21
+ import json
22
+ import random
23
+ from scorer import score_mix_llava
24
+ from cli import HuatuoChatbot
25
+
26
+
27
+ from transformers import AutoModelForCausalLM, AutoTokenizer, AutoModel, AutoModelWithLMHead
28
+ os.umask(0)
29
+
30
+
31
+ logger = logging.getLogger(__name__)
32
+ logging.basicConfig(level='INFO')
33
+
34
+
35
+ class TestDataset(torch.utils.data.Dataset):
36
+ def __init__(self, config, data_path):
37
+ self.config = config
38
+ self.dataset = {}
39
+ with open(data_path) as f:
40
+ self.dataset = json.load(f)
41
+ self.datas = []
42
+
43
+ test_id = 1
44
+ for da in self.dataset:
45
+ da['query'] = self.llava_prompt(da)
46
+ da['test_id'] = test_id
47
+ test_id += 1
48
+ self.datas.append(da)
49
+
50
+ def mmmu_prompt(self,da):
51
+ self.query_prompt = "Please answer the multiple-choice questions below.\n{}\n{}"
52
+ opt_title = ['A','B','C','D','E','F','G']
53
+ if isinstance(da['options'],str):
54
+ da['options'] = ast.literal_eval(da['options'])
55
+ option_str = '\n'.join(f'{opt}. {ops}' for opt,ops in zip(opt_title,da['options']))
56
+ return self.query_prompt.format(da['question'],option_str)
57
+
58
+ def OmniMedVQA_prompt(self,entity):
59
+ q_str = entity['question'] + f'Here are {len(entity["options"])} candidate answers:' + str(entity["options"])+' Only return what you think is the correct answer from the candidate answers, do not return any other irrelevant text!'
60
+ return q_str
61
+
62
+ def llava_prompt(self,da):
63
+ self.query_prompt = "{}\n{}\nAnswer with the option's letter from the given choices directly."
64
+ opt_title = ['A','B','C','D','E','F','G','H','I','J','K']
65
+ if isinstance(da['options'],str):
66
+ da['options'] = ast.literal_eval(da['options'])
67
+ option_str = '\n'.join(f'{opt}. {ops}' for opt,ops in zip(opt_title,da['options']))
68
+ return self.query_prompt.format(da['question'],option_str)
69
+
70
+ def __getitem__(self, index):
71
+ da = self.datas[index]
72
+ return {
73
+ 'data': da,
74
+ 'query': da['query'],
75
+ 'image': da['image']
76
+ }
77
+
78
+ def __len__(self):
79
+ return len(self.datas)
80
+
81
+ def collate_fn(self, batch):
82
+ out_batch = {}
83
+ out_batch['query'] = [x['query'] for x in batch]
84
+ out_batch['data'] = [x['data'] for x in batch]
85
+ out_batch['image'] = [x['image'] for x in batch]
86
+ return out_batch
87
+
88
+
89
+ def get_response(inputs,outputs,tokenizer,num_return):
90
+ responses_list=[]
91
+ batch_return=[]
92
+ for i, output in enumerate(outputs):
93
+ input_len = len(inputs[0])
94
+ generated_output = output[input_len:]
95
+ batch_return.append(tokenizer.decode(generated_output, skip_special_tokens=True))
96
+ if i%num_return==num_return-1:
97
+ responses_list.append(batch_return)
98
+ batch_return=[]
99
+ return responses_list
100
+
101
+ def table_to_csv_string(table):
102
+ rows = [",".join(table.columns)]
103
+ for row in table.data:
104
+ rows.append(",".join(map(str, row)))
105
+ return "\n".join(rows)
106
+
107
+ def test(args):
108
+ accelerator = Accelerator()
109
+ torch.cuda.set_device(accelerator.process_index)
110
+ accelerator.print(f'args:\n{args}')
111
+
112
+ bot = HuatuoChatbot(args.model_path)
113
+ accelerator.print(f'load_finish')
114
+
115
+ bot.gen_kwargs['max_new_tokens'] = args.max_new_tokens
116
+
117
+ dataset = TestDataset(args, args.data_path)
118
+
119
+ val_dataloader = DataLoader(dataset, batch_size=1, shuffle=False, drop_last=False, collate_fn=dataset.collate_fn)
120
+
121
+ val_dataloader = accelerator.prepare(val_dataloader)
122
+ accelerator.wait_for_everyone()
123
+ cache_data = []
124
+
125
+ with torch.no_grad():
126
+ ress = []
127
+
128
+ dataloader_iterator = tqdm(val_dataloader, total=len(val_dataloader)) if accelerator.is_main_process else val_dataloader
129
+
130
+ for batch in dataloader_iterator:
131
+ for da,query,image in zip(batch["data"],batch['query'],batch['image']):
132
+ response = bot.inference(query,[os.path.join(os.path.dirname(args.data_path),x) for x in image])
133
+ for img in [os.path.join(os.path.dirname(args.data_path),x) for x in image]:
134
+ assert os.path.exists(img),f'{img} not exists'
135
+ da['model_output'] = response[0]
136
+ cache_data.append(da)
137
+
138
+ torch.cuda.empty_cache()
139
+ accelerator.wait_for_everyone()
140
+
141
+ all_data = [None] * dist.get_world_size()
142
+ all_response = [None] * dist.get_world_size()
143
+
144
+ dist.all_gather_object(all_data,cache_data)
145
+
146
+ all_data = [item for sublist in all_data for item in sublist]
147
+
148
+ for d in all_data:
149
+ ress.append(d)
150
+
151
+ if accelerator.is_main_process:
152
+ task_name = os.path.basename(args.model_path) + f'_{os.path.split(args.data_path)[-1].replace(".json","")}'
153
+ out_file = f'./{task_name}.json'
154
+ with open(out_file,'w') as fw:
155
+ json.dump(ress,fw,ensure_ascii=False,indent=2)
156
+ print(f'test results: {out_file}')
157
+ print(f'question num: {len(ress)}')
158
+ val_res = score_mix_llava(ress)
159
+ outstr = json.dumps(val_res,ensure_ascii=False,indent = 2)
160
+ accelerator.print(outstr)
161
+ with open(f'{task_name}_result.json','w') as fw:
162
+ json.dump(val_res,fw,ensure_ascii=False,indent=2)
163
+
164
+ if __name__ == '__main__':
165
+ parser = argparse.ArgumentParser(description='Args of sft')
166
+
167
+ # Model Args
168
+ parser.add_argument('--data_path', default='medical_multimodel_evaluation_data.json', type=str)
169
+ parser.add_argument('--model_path', default='HuatuoGPT-Vision-7B', type=str)
170
+ parser.add_argument('--max_new_tokens', default=256, type=int)
171
+ parser.add_argument('--batch_size', default=2, type=int)
172
+
173
+ # Other Args
174
+ parser.add_argument('--seed', default=42, type=int)
175
+
176
+ args = parser.parse_args()
177
+
178
+ set_seed(args.seed)
179
+ test(args)
之前的代码版本/第一版-全部代码/HuatuoGPT-Vision-v1-fullcode/run_all_attnbias_sam.sh ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ cd "$(dirname "$0")"
3
+
4
+ # 依次跑完 none / text / vis / both 四种干预模式
5
+ # 任意一个失败就停止,避免在错误的环境下继续浪费时间
6
+ set -e
7
+
8
+ SCRIPTS=(
9
+ "run_eval_attnbias_sam_none.sh"
10
+ "run_eval_attnbias_sam_text.sh"
11
+ "run_eval_attnbias_sam_vis.sh"
12
+ "run_eval_attnbias_sam_both.sh"
13
+ )
14
+
15
+ for script in "${SCRIPTS[@]}"; do
16
+ echo "=================================================="
17
+ echo "[run_all] 开始运行 $script"
18
+ echo "=================================================="
19
+ bash "$script"
20
+ echo "[run_all] $script 运行完成"
21
+ done
22
+
23
+ echo "[run_all] 全部干预模式运行完成"
之前的代码版本/第一版-全部代码/HuatuoGPT-Vision-v1-fullcode/run_eval_attnbias_sam_both.sh ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ cd "$(dirname "$0")"
3
+
4
+ DATA_PATH="/home/jinhua/ExplainableVQA/benchmarks/Medical_Multimodal_Evaluation_Data/medical_multimodel_evaluation_data.json"
5
+ MODEL_PATH="FreedomIntelligence/HuatuoGPT-Vision-7B"
6
+ OUTPUT_PATH="results_attnbias/HuatuoGPT-Vision-7B/sam_both"
7
+
8
+ SEED=42
9
+ MAX_NEW_TOKENS=256
10
+
11
+ PT_PATH="grounding_results/HuatuoGPT-V-7B/HuatuoGPT-Vision-7B/mask_region/COCO_localization_mean_divergence_per_layer.pt"
12
+ PT_PATH_RANDOM="grounding_results/HuatuoGPT-V-7B/HuatuoGPT-Vision-7B/mask_region_random/COCO_localization_mean_divergence_per_layer.pt"
13
+ PT_PATH_TEXT="grounding_results/HuatuoGPT-V-7B/HuatuoGPT-Vision-7B/mask_text/COCO_localization_mean_divergence_per_layer.pt"
14
+ PT_PATH_TEXT_RANDOM="grounding_results/HuatuoGPT-V-7B/HuatuoGPT-Vision-7B/mask_text_random/COCO_localization_mean_divergence_per_layer.pt"
15
+
16
+ MEDSAM3_CONFIG="/home/jinhua/ExplainableVQA/HuatuoGPT-Vision/MedSAM3/configs/full_lora_config.yaml"
17
+ MEDSAM3_DIR="/home/jinhua/ExplainableVQA/HuatuoGPT-Vision/MedSAM3"
18
+
19
+ # both mode: amplify scispaCy keyword tokens + SAM-bbox patches via pre-softmax bias
20
+ INTERVENTION="both"
21
+ ATTN_LAYERS_TEXT="17"
22
+ ATTN_KEY_SCALE_TEXT=1
23
+ ATTN_NONKEY_SCALE_TEXT=1
24
+ ATTN_KEY_BIAS_TEXT=4.0
25
+ ATTN_NONKEY_BIAS_TEXT=-4.0
26
+ ATTN_LAYERS_VIS="17"
27
+ ATTN_KEY_SCALE_VIS=1
28
+ ATTN_NONKEY_SCALE_VIS=1
29
+ ATTN_KEY_BIAS_VIS=1.0
30
+ ATTN_NONKEY_BIAS_VIS=-1.0
31
+
32
+ MAX_SAMPLES=""
33
+
34
+ accelerate launch eval_attnbias_sam.py \
35
+ --data_path "$DATA_PATH" \
36
+ --model_path "$MODEL_PATH" \
37
+ --seed "$SEED" \
38
+ --max_new_tokens "$MAX_NEW_TOKENS" \
39
+ --pt_path "$PT_PATH" \
40
+ --pt_path_random "$PT_PATH_RANDOM" \
41
+ --pt_path_text "$PT_PATH_TEXT" \
42
+ --pt_path_text_random "$PT_PATH_TEXT_RANDOM" \
43
+ --output_path "$OUTPUT_PATH" \
44
+ --intervention "$INTERVENTION" \
45
+ --attn_layers_text "$ATTN_LAYERS_TEXT" \
46
+ --attn_key_scale_text "$ATTN_KEY_SCALE_TEXT" \
47
+ --attn_nonkey_scale_text "$ATTN_NONKEY_SCALE_TEXT" \
48
+ --attn_key_bias_text "$ATTN_KEY_BIAS_TEXT" \
49
+ --attn_nonkey_bias_text "$ATTN_NONKEY_BIAS_TEXT" \
50
+ --attn_layers_vis "$ATTN_LAYERS_VIS" \
51
+ --attn_key_scale_vis "$ATTN_KEY_SCALE_VIS" \
52
+ --attn_nonkey_scale_vis "$ATTN_NONKEY_SCALE_VIS" \
53
+ --attn_key_bias_vis "$ATTN_KEY_BIAS_VIS" \
54
+ --attn_nonkey_bias_vis "$ATTN_NONKEY_BIAS_VIS" \
55
+ --medsam3_config "$MEDSAM3_CONFIG" \
56
+ --medsam3_dir "$MEDSAM3_DIR" \
57
+ ${MAX_SAMPLES:-}
之前的代码版本/第一版-全部代码/HuatuoGPT-Vision-v1-fullcode/run_eval_attnbias_sam_text.sh ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ cd "$(dirname "$0")"
3
+
4
+ DATA_PATH="/home/jinhua/ExplainableVQA/benchmarks/Medical_Multimodal_Evaluation_Data/medical_multimodel_evaluation_data.json"
5
+ MODEL_PATH="FreedomIntelligence/HuatuoGPT-Vision-7B"
6
+ OUTPUT_PATH="results_attnbias/HuatuoGPT-Vision-7B/sam_text"
7
+
8
+ SEED=42
9
+ MAX_NEW_TOKENS=256
10
+
11
+ PT_PATH="grounding_results/HuatuoGPT-V-7B/HuatuoGPT-Vision-7B/mask_region/COCO_localization_mean_divergence_per_layer.pt"
12
+ PT_PATH_RANDOM="grounding_results/HuatuoGPT-V-7B/HuatuoGPT-Vision-7B/mask_region_random/COCO_localization_mean_divergence_per_layer.pt"
13
+ PT_PATH_TEXT="grounding_results/HuatuoGPT-V-7B/HuatuoGPT-Vision-7B/mask_text/COCO_localization_mean_divergence_per_layer.pt"
14
+ PT_PATH_TEXT_RANDOM="grounding_results/HuatuoGPT-V-7B/HuatuoGPT-Vision-7B/mask_text_random/COCO_localization_mean_divergence_per_layer.pt"
15
+
16
+ MEDSAM3_CONFIG="/home/jinhua/ExplainableVQA/HuatuoGPT-Vision/MedSAM3/configs/full_lora_config.yaml"
17
+ MEDSAM3_DIR="/home/jinhua/ExplainableVQA/HuatuoGPT-Vision/MedSAM3"
18
+
19
+ # text mode: amplify scispaCy keyword tokens only via pre-softmax bias
20
+ INTERVENTION="text"
21
+ ATTN_LAYERS_TEXT="17"
22
+ ATTN_KEY_SCALE_TEXT=1
23
+ ATTN_NONKEY_SCALE_TEXT=1
24
+ ATTN_KEY_BIAS_TEXT=4.0
25
+ ATTN_NONKEY_BIAS_TEXT=-4.0
26
+ ATTN_LAYERS_VIS="17"
27
+ ATTN_KEY_SCALE_VIS=1
28
+ ATTN_NONKEY_SCALE_VIS=1
29
+ ATTN_KEY_BIAS_VIS=1.0
30
+ ATTN_NONKEY_BIAS_VIS=-1.0
31
+
32
+ MAX_SAMPLES=""
33
+
34
+ accelerate launch eval_attnbias_sam.py \
35
+ --data_path "$DATA_PATH" \
36
+ --model_path "$MODEL_PATH" \
37
+ --seed "$SEED" \
38
+ --max_new_tokens "$MAX_NEW_TOKENS" \
39
+ --pt_path "$PT_PATH" \
40
+ --pt_path_random "$PT_PATH_RANDOM" \
41
+ --pt_path_text "$PT_PATH_TEXT" \
42
+ --pt_path_text_random "$PT_PATH_TEXT_RANDOM" \
43
+ --output_path "$OUTPUT_PATH" \
44
+ --intervention "$INTERVENTION" \
45
+ --attn_layers_text "$ATTN_LAYERS_TEXT" \
46
+ --attn_key_scale_text "$ATTN_KEY_SCALE_TEXT" \
47
+ --attn_nonkey_scale_text "$ATTN_NONKEY_SCALE_TEXT" \
48
+ --attn_key_bias_text "$ATTN_KEY_BIAS_TEXT" \
49
+ --attn_nonkey_bias_text "$ATTN_NONKEY_BIAS_TEXT" \
50
+ --attn_layers_vis "$ATTN_LAYERS_VIS" \
51
+ --attn_key_scale_vis "$ATTN_KEY_SCALE_VIS" \
52
+ --attn_nonkey_scale_vis "$ATTN_NONKEY_SCALE_VIS" \
53
+ --attn_key_bias_vis "$ATTN_KEY_BIAS_VIS" \
54
+ --attn_nonkey_bias_vis "$ATTN_NONKEY_BIAS_VIS" \
55
+ --medsam3_config "$MEDSAM3_CONFIG" \
56
+ --medsam3_dir "$MEDSAM3_DIR" \
57
+ ${MAX_SAMPLES:-}
之前的代码版本/第一版-全部代码/HuatuoGPT-Vision-v1-fullcode/scorer.py ADDED
@@ -0,0 +1,195 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #%%
2
+ import re
3
+ import json,os
4
+ from collections import defaultdict
5
+ import random
6
+ import ast
7
+ import wandb
8
+ # import argparse
9
+ import traceback
10
+
11
+ import difflib
12
+
13
+ def str_similarity(str1, str2):
14
+ seq = difflib.SequenceMatcher(None, str1, str2)
15
+ return seq.ratio()
16
+
17
+ def find_most_similar_index(str_list, target_str):
18
+ """
19
+ Given a list of strings and a target string, returns the index of the most similar string in the list.
20
+ """
21
+ # Initialize variables to keep track of the most similar string and its index
22
+ most_similar_str = None
23
+ most_similar_index = None
24
+ highest_similarity = 0
25
+
26
+ # Iterate through each string in the list
27
+ for i, str in enumerate(str_list):
28
+ # Calculate the similarity between the current string and the target string
29
+ similarity = str_similarity(str, target_str)
30
+
31
+ # If the current string is more similar than the previous most similar string, update the variables
32
+ if similarity >= highest_similarity:
33
+ most_similar_str = str
34
+ most_similar_index = i
35
+ highest_similarity = similarity
36
+
37
+ # Return the index of the most similar string
38
+ return most_similar_index
39
+
40
+ def match_choice3(text,options):
41
+ matches = list(re.finditer(r"(is |是|\*|\W|\ |\(|为|^|'|\"|#)(?![aA] )([abcdefghijklmnABCDEFGHIJKLMN])(\W|$)", text, re.S))
42
+ if matches:
43
+ ans = matches[0].group(2)
44
+ return ans,1
45
+
46
+ text = text.lower()
47
+
48
+ opsindex = [(opt,text.rindex(options[opt].lower())) for opt in options if options[opt].lower() in text]
49
+ if len(opsindex) > 0:
50
+ return sorted(opsindex,key=lambda x:x[1],reverse=True)[0][0],2
51
+
52
+ oplabels = [x for x in options]
53
+ opans = [options[x].lower() for x in options]
54
+ ansindex = find_most_similar_index(opans,text.lower())
55
+ return oplabels[ansindex], 3
56
+
57
+ def test_OmniMedVQA(da):
58
+ a,b,c,d = da.get('option_A'), da.get('option_B'), da.get('option_C'), da.get('option_D')
59
+ answer_list = [a, b]
60
+ if c is not None:
61
+ answer_list.append(c)
62
+ if d is not None:
63
+ answer_list.append(d)
64
+ # print(f'answer_list {answer_list}')
65
+ # print(f"answer_list {answer_list[find_most_similar_index(answer_list, da['model_output'])] == da['gt_answer']}")
66
+ return answer_list[find_most_similar_index(answer_list, da['model_output'])] == da['gt_answer']
67
+
68
+ def test_OmniMedVQA_new(da):
69
+ answer_list = da['options']
70
+ choice = find_most_similar_index(answer_list, da['model_output'])
71
+ label = answer_list[choice] == da['answer']
72
+ return label,choice
73
+
74
+ def test_choice_simple(da):
75
+ choice = ['A','B','C','D','E','F','G'].index(da['model_output'][0])
76
+ answer_list = da['options']
77
+ label = answer_list[choice] == da['answer']
78
+ return label,choice
79
+
80
+
81
+ wrong_ans = []
82
+ def test_mmlu(da):
83
+ global wrong_ans
84
+ ans = match_choice3(da['model_output'],da)
85
+ # ans = match_choice3(da['huatuo_answer'],da)
86
+ if len(ans) == 0:
87
+ wrong_ans.append(da)
88
+ ans = 'A'
89
+ return ans[0] == da['answer']
90
+
91
+
92
+ wrong_data = []
93
+ sample_num = 5
94
+ wrong_ans_num = 0
95
+ def test_choice_llava(input_data):
96
+ global wrong_ans_num
97
+ type2score = {}
98
+ sub_type2score = {}
99
+ sample_data = {}
100
+ ty_set = set()
101
+ res = {}
102
+
103
+ miss_match_num = 0
104
+
105
+ if len(input_data) == 0:
106
+ return sample_data,res
107
+
108
+ for da in input_data:
109
+ ty = da['dataset']
110
+
111
+ if ty not in type2score:
112
+ type2score[ty] = [0,0]
113
+
114
+ type2score[ty][1] += 1
115
+
116
+ try:
117
+ opt_title = ['A','B','C','D','E','F','G','H','I','J','K']
118
+ if da['answer'] == '?':
119
+ da['is_correct'] = False
120
+ else:
121
+ answer_label = opt_title[da['options'].index(da['answer'])]
122
+ da['answer'] = answer_label
123
+ da['is_correct'] = test_mmlu(da)
124
+ except Exception as e:
125
+ print(da)
126
+ traceback.print_exc()
127
+ assert False,da
128
+
129
+ if da['is_correct']:
130
+ type2score[ty][0] += 1
131
+ else:
132
+ wrong_data.append(da)
133
+
134
+ def update_sub_record(sub_type2score,type_name,iscorrect):
135
+ if type_name not in sub_type2score:
136
+ sub_type2score[type_name] = [0,0]
137
+ sub_type2score[type_name][1] += 1
138
+ if iscorrect:
139
+ sub_type2score[type_name][0] += 1
140
+ if 'subset' in da and da['subset']!= '':
141
+ update_sub_record(sub_type2score, f'{ty}_{da["subset"]}',da['is_correct'])
142
+
143
+
144
+ for k,v in type2score.items():
145
+ print(f'【{k}】Accuracy:{(v[0]/v[1] if v[0] > 0 else 0) :.4f} question number:{v[1]}')
146
+ res[k] = (v[0]/v[1] if v[0] > 0 else 0)
147
+
148
+ print(f'The total score for multiple-choice questions:{sum([sc[0] for k,sc in type2score.items() if "___" not in k ])/len(input_data) :.3f} question number: {len(input_data)}')
149
+ res['The total score for multiple-choice questions'] = sum([sc[0] for k,sc in type2score.items() if "___" not in k ])/len(input_data)
150
+
151
+ print('\n'+f'-------'*4)
152
+ for k,v in sub_type2score.items():
153
+ print(f'【{k}】Accuracy:{(v[0]/v[1] if v[0] > 0 else 0) :.4f} question number:{v[1]}')
154
+ res[k] = (v[0]/v[1] if v[0] > 0 else 0)
155
+
156
+ sample_data = [{'Input':x['query'],'Output':x['model_output'],'Answer': x['answer'], 'Dataset':x['dataset']} for x in random.sample(input_data,5)]
157
+ print(f'\n wrong_ans_num {wrong_ans_num}')
158
+ return sample_data,res
159
+
160
+ def test_chat(chat_data,sample_data):
161
+ for da in chat_data:
162
+ ty = da['dataset']
163
+ da['answer'] = da['output']
164
+ if sample_data is not None:
165
+ sample_data[ty] = []
166
+ if len(sample_data[ty]) < sample_num:
167
+ sample_data[ty].append(da)
168
+ return sample_data
169
+
170
+
171
+ def score_mix_llava(datas, iswandb = False):
172
+ global test_func
173
+ test_func = match_choice3
174
+ filted_data = []
175
+ test_id_set = set()
176
+ for da in datas:
177
+ if 'question_type' in da and da['question_type'] == 'open':
178
+ continue
179
+ if da['test_id'] in test_id_set:
180
+ continue
181
+ if len(da['options']) == 0:
182
+ continue
183
+ test_id_set.add(da['test_id'])
184
+ filted_data.append(da)
185
+ print(f'filted_data: {len(filted_data)} datas:{len(datas)}')
186
+
187
+ sample_data,res = test_choice_llava(filted_data)
188
+
189
+ if iswandb:
190
+ table = wandb.Table(columns=["Input", "Output","Answer","Dataset"])
191
+ for da in sample_data:
192
+ table.add_data(da['Input'],da['Output'],da['Answer'],da['Dataset'])
193
+ res['InputOutputTable'] = table
194
+ return res
195
+
之前的代码版本/第一版-全部代码/HuatuoGPT-Vision-v1-fullcode/train_vl.py ADDED
@@ -0,0 +1,496 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import copy
3
+ import json
4
+ import torch
5
+ import logging
6
+ import argparse
7
+ import random
8
+ import shutil
9
+ from typing import List, Dict, Any
10
+ from dataclasses import dataclass
11
+
12
+ import wandb
13
+ import datasets
14
+ from tqdm import tqdm
15
+ import gc
16
+ from jinja2 import Template
17
+ import torch.nn.functional as F
18
+ import torch.distributed as dist
19
+ from torch.utils.data import Dataset, DataLoader
20
+ from accelerate import Accelerator
21
+ from transformers import (
22
+ Qwen2_5_VLForConditionalGeneration,
23
+ Qwen2_5_VLProcessor,
24
+ set_seed,
25
+ get_cosine_schedule_with_warmup
26
+ )
27
+ from torch.optim.lr_scheduler import LambdaLR
28
+ import math
29
+ from qwen_vl_utils import fetch_image
30
+
31
+ # Set environment variables
32
+ os.environ['WANDB_DISABLE_CODE'] = 'true'
33
+ os.environ["WANDB_API_KEY"] = ''
34
+ os.umask(0)
35
+
36
+ # Set up logging
37
+ logger = logging.getLogger(__name__)
38
+ logging.basicConfig(level='INFO')
39
+
40
+ def get_custom_cosine_schedule_with_warmup(
41
+ optimizer,
42
+ num_warmup_steps,
43
+ num_training_steps,
44
+ min_lr_ratio=0.0,
45
+ num_cycles=0.5
46
+ ):
47
+ """
48
+ Custom cosine scheduler supporting minimum learning rate ratio
49
+ """
50
+ def lr_lambda(current_step):
51
+ if current_step < num_warmup_steps:
52
+ return float(current_step) / float(max(1, num_warmup_steps))
53
+ progress = float(current_step - num_warmup_steps) / float(max(1, num_training_steps - num_warmup_steps))
54
+ cosine_factor = 0.5 * (1.0 + math.cos(math.pi * 2 * num_cycles * progress))
55
+ scaled_factor = (1 - min_lr_ratio) * cosine_factor + min_lr_ratio
56
+ return scaled_factor
57
+
58
+ return LambdaLR(optimizer, lr_lambda, last_epoch=-1)
59
+
60
+ def get_learning_rate(step, initial_lr, num_warmup_steps, num_training_steps, min_lr_ratio, num_cycles=0.5):
61
+ if step < num_warmup_steps:
62
+ return float(step) / float(max(1, num_warmup_steps)) * initial_lr
63
+ progress = float(step - num_warmup_steps) / float(max(1, num_training_steps - num_warmup_steps))
64
+ cosine_factor = 0.5 * (1.0 + math.cos(math.pi * 2 * num_cycles * progress))
65
+ scaled_factor = (1 - min_lr_ratio) * cosine_factor + min_lr_ratio
66
+ return scaled_factor * initial_lr
67
+
68
+ class TrainingMetrics:
69
+ def __init__(self, device):
70
+ self.n_step = 0
71
+ self.right = torch.Tensor([0]).to(device=device)
72
+ self.total = torch.Tensor([0]).to(device=device)
73
+ self.total_loss = torch.Tensor([0]).to(device=device)
74
+ self.world_size = dist.get_world_size()
75
+
76
+ def __call__(self, logits, labels, loss):
77
+ return self.update(logits, labels, loss)
78
+
79
+ def update(self, logits, labels, loss):
80
+ self.n_step += 1
81
+ with torch.no_grad():
82
+ shift_preds = logits[..., :-1, :].argmax(dim=-1)
83
+ shift_labels = labels[..., 1:]
84
+ self.right += (shift_preds == shift_labels).masked_fill(shift_labels.eq(-100), 0).sum().item()
85
+ self.total += (shift_labels != -100).sum().item()
86
+ self.total_loss += loss.item()
87
+
88
+ def get_metric(self, reset=True):
89
+ dist.all_reduce(self.right, op=torch.distributed.ReduceOp.SUM)
90
+ dist.all_reduce(self.total, op=torch.distributed.ReduceOp.SUM)
91
+ dist.all_reduce(self.total_loss, op=torch.distributed.ReduceOp.SUM)
92
+
93
+ acc = (self.right / self.total).item()
94
+ loss = self.total_loss.item() / (self.world_size * self.n_step)
95
+
96
+ if reset:
97
+ self.n_step = 0
98
+ self.right.fill_(0)
99
+ self.total.fill_(0)
100
+ self.total_loss.fill_(0)
101
+ return acc, loss
102
+
103
+ class SftDataset(Dataset):
104
+ """Pretraining dataset class"""
105
+ def __init__(self, config, processor, accelerator):
106
+ self.config = config
107
+ self.processor = processor
108
+ self.accelerator = accelerator
109
+
110
+ # Load pretraining data (supports multiple sources)
111
+ self.data = []
112
+ with open(config.data_path,'r') as f:
113
+ data = json.load(f)
114
+ self.data = data
115
+
116
+ # Convert conversation format
117
+ role_map = {'system': 'system', 'human': 'user', 'gpt': 'assistant'}
118
+ if 'value' in data[0]['conversations'][0]:
119
+ for da in data:
120
+ conv = []
121
+ for x in da['conversations']:
122
+ conv.append({
123
+ 'role': role_map[x['from']],
124
+ 'content': x['value']
125
+ })
126
+ da['conversations'] = conv
127
+
128
+ # Filter long samples and ensure assistant response is valid
129
+ tmp_data = []
130
+ for da in self.data:
131
+ if len(da['image']) > 8:
132
+ continue
133
+ if da['conversations'][-1]['role'] != 'assistant' or len(da['conversations'][-1]['content'].strip()) == 0:
134
+ continue
135
+ tmp_data.append(da)
136
+ self.data = tmp_data
137
+ accelerator.print(f'Training data size: {len(self.data)} samples')
138
+
139
+ self.assistant_token_id = self.processor.tokenizer.convert_tokens_to_ids("<|im_start|>")
140
+ self.assistant_prefix_ids = self.processor.tokenizer.encode("<|im_start|>assistant\n", add_special_tokens=False, return_tensors="pt")[0]
141
+ self.eos_token_id = self.processor.tokenizer.convert_tokens_to_ids("<|im_end|>")
142
+
143
+ self.image_sizes = (config.max_width, config.max_height)
144
+ accelerator.print(f'Total dataset size: {len(self.data)}')
145
+
146
+ # Padding
147
+ self.image_padding = {'pixel_values': torch.zeros(24, 1176), 'image_grid_thw': torch.tensor([[1, 4, 6]])}
148
+
149
+ def __len__(self) -> int:
150
+ return len(self.data)
151
+
152
+ def __getitem__(self, index: int) -> Dict[str, torch.Tensor]:
153
+ return self.data[index]
154
+
155
+ def collate_fn(self, batch: List[Dict[str, torch.Tensor]]) -> Dict[str, torch.Tensor]:
156
+ texts = []
157
+ images = []
158
+
159
+ for item in batch:
160
+ img_num = 0
161
+
162
+ if len(item['image']) > 0 and '<image>' not in ''.join([x['content'] for x in item['conversations']]):
163
+ item["conversations"][0]['content'] = '\n'.join(['<image>']*len(item['image']))+'\n'+item["conversations"][0]['content']
164
+
165
+ if len(item['image']) > 0:
166
+ for k in item["conversations"]:
167
+ img_num += k['content'].count('<image>')
168
+ k['content'] = k['content'].replace("<image>", "<|vision_start|><|image_pad|><|vision_end|>")
169
+ assert img_num == len(item['image']), f"Image count mismatch: {img_num} != {len(item['image'])}\n{item['conversations']}"
170
+ input_text = self.processor.apply_chat_template(item["conversations"], add_generation_prompt=False, tokenize=False)
171
+ texts.append(input_text)
172
+ images.extend(item["image"])
173
+
174
+ img_list = [fetch_image({"type": "image", "image": img_path,"max_pixels": self.image_sizes[0] * self.image_sizes[1]}) for img_path in images]
175
+
176
+ if len(img_list) > 0:
177
+ inputs = self.processor(text=texts, images=img_list, return_tensors="pt", padding=True)
178
+ pixel_values = inputs['pixel_values']
179
+ image_grid_thw = inputs['image_grid_thw']
180
+ assert inputs['input_ids'].shape[0] <= self.config.max_seq_len, f"input_ids length exceeds max_seq_len: {inputs['input_ids'].shape[0]} > {self.config.max_seq_len}, may cause errors!!"
181
+ else:
182
+ inputs = self.processor.tokenizer(text=texts, return_tensors="pt", add_special_tokens=False, truncation=True, padding=True, max_length=self.config.max_seq_len)
183
+ pixel_values = self.image_padding['pixel_values']
184
+ image_grid_thw = self.image_padding['image_grid_thw']
185
+
186
+ labels = torch.full_like(inputs['input_ids'], -100)
187
+ for batch_idx in range(inputs['input_ids'].size(0)):
188
+ input_ids = inputs['input_ids'][batch_idx]
189
+ assistant_indices = (input_ids == self.assistant_token_id).nonzero(as_tuple=True)[0]
190
+
191
+ stop_flag = False
192
+
193
+ for idx in reversed(assistant_indices):
194
+ if not torch.equal(input_ids[idx:idx+len(self.assistant_prefix_ids)], self.assistant_prefix_ids):
195
+ continue
196
+
197
+ for j in range(idx + len(self.assistant_prefix_ids), len(input_ids)):
198
+ labels[batch_idx, j] = input_ids[j]
199
+ if input_ids[j] == self.eos_token_id:
200
+ stop_flag = True
201
+ break
202
+
203
+ if stop_flag:
204
+ break
205
+
206
+ assert inputs['attention_mask'].shape[0] <= self.config.max_seq_len, f"attention_mask length exceeds max_seq_len: {inputs['attention_mask'].shape[0]} > {self.config.max_seq_len}"
207
+
208
+ return {
209
+ "input_ids": inputs['input_ids'][:, :self.config.max_seq_len],
210
+ "labels": labels[:, :self.config.max_seq_len],
211
+ "attention_mask": inputs['attention_mask'][:, :self.config.max_seq_len],
212
+ "pixel_values": pixel_values,
213
+ "image_grid_thw": image_grid_thw
214
+ }
215
+
216
+ def save_checkpoint(
217
+ model,
218
+ processor,
219
+ accelerator: Accelerator,
220
+ args: argparse.Namespace,
221
+ epoch: int,
222
+ step: int,
223
+ global_step: int,
224
+ is_last: bool = False
225
+ ) -> None:
226
+ save_dir = os.path.join(args.output_dir, f"checkpoint-{epoch}-{global_step}")
227
+
228
+ if accelerator.is_main_process:
229
+ # Manage number of checkpoints
230
+ checkpoint_files = [f for f in os.listdir(args.output_dir) if f.startswith("checkpoint-")]
231
+ if args.max_ckpts > 0 and len(checkpoint_files) >= args.max_ckpts:
232
+ oldest_ckpt = min(checkpoint_files, key=lambda x: os.path.getctime(os.path.join(args.output_dir, x)))
233
+ shutil.rmtree(os.path.join(args.output_dir, oldest_ckpt))
234
+
235
+ os.makedirs(save_dir, exist_ok=True)
236
+ output_dir = os.path.join(save_dir, 'tfmr')
237
+
238
+ # Save model and tokenizer
239
+ if accelerator.state.deepspeed_plugin.zero_stage != 3:
240
+ model.save_pretrained(output_dir, state_dict=accelerator.get_state_dict(model))
241
+ processor.save_pretrained(output_dir)
242
+
243
+ logger.info(f'Model saved in {output_dir}')
244
+
245
+ # Handle DeepSpeed stage 3
246
+ if accelerator.state.deepspeed_plugin.zero_stage == 3:
247
+ unwrap_model = accelerator.unwrap_model(model)
248
+ unwrap_model.save_pretrained(
249
+ os.path.join(save_dir, 'tfmr'),
250
+ is_main_process=accelerator.is_main_process,
251
+ save_function=accelerator.save,
252
+ state_dict=accelerator.get_state_dict(model)
253
+ )
254
+
255
+ accelerator.wait_for_everyone()
256
+ logger.info(f'Checkpoint {epoch}-{global_step} saved successfully')
257
+
258
+ if args.save_state:
259
+ try:
260
+ accelerator.save_state(save_dir)
261
+ except Exception as e:
262
+ logger.info(f"Failed to save state: {e}")
263
+
264
+
265
+ def train(args: argparse.Namespace) -> None:
266
+ """Main training function"""
267
+ accelerator = Accelerator(
268
+ mixed_precision='bf16',
269
+ gradient_accumulation_steps=args.gradient_accumulation_steps
270
+ )
271
+
272
+ if accelerator.is_main_process:
273
+ wandb.init(
274
+ project=args.experiment_name,
275
+ name=args.run_name,
276
+ config=args,
277
+ dir=args.log_dir,
278
+ mode="offline"
279
+ )
280
+
281
+ accelerator.state.deepspeed_plugin.deepspeed_config['train_micro_batch_size_per_gpu'] = args.train_bsz_per_gpu
282
+ accelerator.state.deepspeed_plugin.deepspeed_config['train_batch_size'] = (
283
+ args.train_bsz_per_gpu *
284
+ dist.get_world_size() *
285
+ accelerator.gradient_accumulation_steps
286
+ )
287
+
288
+ processor = Qwen2_5_VLProcessor.from_pretrained(args.model_path, trust_remote_code=True)
289
+ model = Qwen2_5_VLForConditionalGeneration.from_pretrained(
290
+ args.model_path,
291
+ trust_remote_code=True,
292
+ attn_implementation='flash_attention_2',
293
+ torch_dtype=torch.bfloat16
294
+ )
295
+
296
+ if args.gradient_checkpointing:
297
+ model.gradient_checkpointing_enable()
298
+
299
+ # Freeze components if required
300
+ if args.freeze_vision_tower:
301
+ logger.info("Freezing vision tower parameters")
302
+ for param in model.visual.parameters():
303
+ param.requires_grad = False
304
+ for param in model.visual.merger.parameters():
305
+ param.requires_grad = True
306
+
307
+ if args.freeze_multi_modal_projector:
308
+ logger.info("Freezing multi-modal projector parameters")
309
+ for param in model.visual.merger.parameters():
310
+ param.requires_grad = False
311
+
312
+ if args.freeze_language_model:
313
+ logger.info("Freezing language model parameters")
314
+ for param in model.model.parameters():
315
+ param.requires_grad = False
316
+
317
+ # Display parameter statistics
318
+ if args.freeze_vision_tower or args.freeze_language_model or args.freeze_multi_modal_projector:
319
+ trainable_params, all_params = 0, 0
320
+ param_status = {}
321
+ for name, param in model.named_parameters():
322
+ all_params += param.numel()
323
+ if param.requires_grad:
324
+ trainable_params += param.numel()
325
+ module_name = name.split('.')[0] if '.' in name else name
326
+ if module_name not in param_status:
327
+ param_status[module_name] = {'trainable': 0, 'frozen': 0}
328
+ param_status[module_name]['trainable'] += param.numel()
329
+ else:
330
+ module_name = name.split('.')[0] if '.' in name else name
331
+ if module_name not in param_status:
332
+ param_status[module_name] = {'trainable': 0, 'frozen': 0}
333
+ param_status[module_name]['frozen'] += param.numel()
334
+
335
+ accelerator.print(f"Total model params: {all_params/1e6:.2f}M, Trainable: {trainable_params/1e6:.2f}M ({trainable_params/all_params*100:.2f}%)")
336
+ accelerator.print("Module-wise parameter status:")
337
+ for module, stats in param_status.items():
338
+ total = stats['trainable'] + stats['frozen']
339
+ if total > 0:
340
+ accelerator.print(f" - {module}: Total {total/1e6:.2f}M, Trainable {stats['trainable']/1e6:.2f}M ({stats['trainable']/total*100:.2f}%), Frozen {stats['frozen']/1e6:.2f}M ({stats['frozen']/total*100:.2f}%)")
341
+
342
+ # Optimizer setup
343
+ no_decay = ["bias", "LayerNorm.weight"]
344
+ optimizer_grouped_parameters = [
345
+ {"params": [p for n, p in model.named_parameters() if not any(nd in n for nd in no_decay)], "weight_decay": args.weight_decay},
346
+ {"params": [p for n, p in model.named_parameters() if any(nd in n for nd in no_decay)], "weight_decay": 0.0},
347
+ ]
348
+ optimizer = torch.optim.AdamW(optimizer_grouped_parameters, lr=args.learning_rate)
349
+
350
+ train_dataset = SftDataset(args, processor, accelerator)
351
+ train_dataloader = DataLoader(
352
+ train_dataset,
353
+ batch_size=args.train_bsz_per_gpu,
354
+ shuffle=True,
355
+ drop_last=True,
356
+ collate_fn=train_dataset.collate_fn,
357
+ num_workers=4
358
+ )
359
+
360
+ num_training_steps = int(len(train_dataloader) * args.n_epochs) // accelerator.gradient_accumulation_steps // dist.get_world_size()
361
+ lr_scheduler = get_custom_cosine_schedule_with_warmup(
362
+ optimizer,
363
+ num_warmup_steps=int(args.warmup_rates * num_training_steps),
364
+ num_training_steps=num_training_steps,
365
+ min_lr_ratio=args.min_lr_ratio
366
+ )
367
+
368
+ model, optimizer, train_dataloader = accelerator.prepare(model, optimizer, train_dataloader)
369
+ metric = TrainingMetrics(device=torch.cuda.current_device())
370
+ model.train()
371
+
372
+ global_step = 0
373
+ inepoch_step = 0
374
+ start_epoch = 0
375
+
376
+ for epoch in range(start_epoch, args.n_epochs):
377
+ train_iter = tqdm(train_dataloader, total=len(train_dataloader)) if accelerator.is_main_process else train_dataloader
378
+
379
+ for batch in train_iter:
380
+ if inepoch_step > 0:
381
+ inepoch_step -= 1
382
+ continue
383
+
384
+ outputs = model(
385
+ input_ids=batch['input_ids'],
386
+ labels=batch['labels'],
387
+ attention_mask=batch['attention_mask'],
388
+ pixel_values=batch['pixel_values'],
389
+ image_grid_thw=batch['image_grid_thw'],
390
+ return_dict=True,
391
+ use_cache=False
392
+ )
393
+ loss = outputs.loss
394
+ metric(outputs.logits, batch['labels'], loss)
395
+
396
+ accelerator.backward(loss)
397
+
398
+ if args.max_grad_norm > 0:
399
+ accelerator.clip_grad_norm_(model.parameters(), args.max_grad_norm)
400
+
401
+ if (global_step + 1) % accelerator.gradient_accumulation_steps == 0:
402
+ optimizer.step()
403
+ lr_scheduler.step()
404
+ optimizer.zero_grad()
405
+
406
+ if (global_step + 1) % (accelerator.gradient_accumulation_steps * 2) == 0:
407
+ torch.cuda.empty_cache()
408
+
409
+ global_step += 1
410
+
411
+ if (global_step + 1) % accelerator.gradient_accumulation_steps == 0:
412
+ acc, train_loss = metric.get_metric()
413
+ if accelerator.is_main_process:
414
+ train_iter.set_postfix(
415
+ epoch=epoch,
416
+ step=global_step - 1,
417
+ total_steps=len(train_dataloader),
418
+ skip=accelerator.optimizer_step_was_skipped,
419
+ length=len(batch["input_ids"][0]),
420
+ loss=f"{train_loss:.3f}",
421
+ acc=f"{acc:.3f}",
422
+ lr=f"{lr_scheduler.get_last_lr()[0]:.2e}"
423
+ )
424
+
425
+ wandb.log({
426
+ 'loss': train_loss,
427
+ 'acc': acc,
428
+ 'lr': lr_scheduler.get_last_lr()[0]
429
+ }, step=global_step)
430
+
431
+ accelerator.wait_for_everyone()
432
+ save_checkpoint(
433
+ model=model,
434
+ processor=processor,
435
+ accelerator=accelerator,
436
+ args=args,
437
+ epoch=epoch,
438
+ step=global_step - 1,
439
+ global_step=global_step,
440
+ is_last=True
441
+ )
442
+
443
+
444
+ if __name__ == '__main__':
445
+ parser = argparse.ArgumentParser(description='Pretraining Configuration')
446
+
447
+ # Experiment
448
+ parser.add_argument('--experiment_name', type=str, help='Experiment name')
449
+ parser.add_argument('--run_name', type=str, default=None, help='Run name')
450
+ parser.add_argument('--model_path', type=str, default='', help='Pretrained model path')
451
+
452
+ # Data
453
+ parser.add_argument('--data_path', type=str, required=True, help='Training data path')
454
+ parser.add_argument('--output_dir', type=str, default='./', help='Model save path')
455
+ parser.add_argument('--max_ckpts', type=int, default=3, help='Max number of checkpoints')
456
+ parser.add_argument('--log_dir', type=str, default='./', help='Log directory')
457
+
458
+ # Training
459
+ parser.add_argument('--max_seq_len', type=int, default=4096, help='Max sequence length')
460
+ parser.add_argument('--gradient_checkpointing', action='store_true', help='Enable gradient checkpointing')
461
+ parser.add_argument('--gradient_accumulation_steps', type=int, default=16, help='Gradient accumulation steps')
462
+ parser.add_argument('--max_grad_norm', type=float, default=1.0, help='Gradient clipping threshold')
463
+ parser.add_argument('--train_bsz_per_gpu', type=int, default=1, help='Batch size per GPU')
464
+ parser.add_argument('--weight_decay', type=float, default=0.1, help='Weight decay')
465
+ parser.add_argument('--learning_rate', type=float, default=5e-6, help='Learning rate')
466
+ parser.add_argument('--min_lr_ratio', type=float, default=0.15, help='Min learning rate ratio')
467
+ parser.add_argument('--warmup_rates', type=float, default=0.05, help='Warmup rate')
468
+ parser.add_argument('--n_epochs', type=int, default=2, help='Number of training epochs')
469
+ parser.add_argument('--save_steps', type=int, default=2000, help='Checkpoint saving interval')
470
+ parser.add_argument('--save_state', action='store_true', help='Save accelerator state')
471
+ parser.add_argument('--resume_from_checkpoint', action='store_true', help='Resume from checkpoint')
472
+
473
+ parser.add_argument('--freeze_vision_tower', action='store_true', help='Freeze vision tower')
474
+ parser.add_argument('--freeze_language_model', action='store_true', help='Freeze language model')
475
+ parser.add_argument('--freeze_multi_modal_projector', action='store_true', help='Freeze multi-modal projector')
476
+
477
+ # Image
478
+ parser.add_argument('--max_width', type=int, default=420, help='Max image width')
479
+ parser.add_argument('--max_height', type=int, default=360, help='Max image height')
480
+
481
+ # Misc
482
+ parser.add_argument('--seed', type=int, default=42, help='Random seed')
483
+
484
+ args = parser.parse_args()
485
+
486
+ # Set paths
487
+ args.log_dir = os.path.join(args.log_dir, args.experiment_name)
488
+ args.output_dir = os.path.join(args.output_dir, args.experiment_name)
489
+ if args.run_name:
490
+ args.output_dir = os.path.join(args.output_dir, args.run_name)
491
+
492
+ os.makedirs(args.log_dir, exist_ok=True)
493
+ os.makedirs(args.output_dir, exist_ok=True)
494
+
495
+ set_seed(args.seed)
496
+ train(args)
之前的代码版本/第一版-全部代码/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/docs/LLaVA-NeXT-Video.md ADDED
@@ -0,0 +1,81 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ # LLaVA-NeXT: A Strong Zero-shot Video Understanding Model
3
+
4
+ ## Contents
5
+ - [Demo](#demo)
6
+ - [Evaluation](#evaluation)
7
+
8
+ ## Demo
9
+
10
+ > make sure you installed the LLaVA-NeXT model files via outside REAME.md
11
+
12
+ 1. **Example model:** `lmms-lab/LLaVA-NeXT-Video-7B-DPO`
13
+
14
+ 2. **Prompt mode:** `vicuna_v1` (use `mistral_direct` for `lmms-lab/LLaVA-NeXT-Video-34B-DPO`)
15
+
16
+ 3. **Sampled frames:** `32` (Defines how many frames to sample from the video.)
17
+
18
+ 4. **Spatial pooling stride:** `2` (With original tokens for one frame at 24x24, if stride=2, then the tokens for one frame are 12x12.)
19
+
20
+ 5. **Spatial pooling mode:** `average` (Options: `average`, `max`.)
21
+
22
+ 6. **Local video path:** `./data/llava_video/video-chatgpt/evaluation/Test_Videos/v_Lf_7RurLgp0.mp4`
23
+
24
+ To run a demo, execute:
25
+ ```bash
26
+ bash scripts/video/demo/video_demo.sh ${Example model} ${Prompt mode} ${Sampled frames} ${Spatial pooling stride} ${Spatial pooling mode} grid True ${Video path at local}
27
+ ```
28
+ Example:
29
+ ```bash
30
+ bash scripts/video/demo/video_demo.sh lmms-lab/LLaVA-NeXT-Video-7B-DPO vicuna_v1 32 2 average no_token True playground/demo/xU25MMA2N4aVtYay.mp4
31
+ ```
32
+
33
+ **IMPORTANT** Please refer to [Latest video model](https://github.com/LLaVA-VL/LLaVA-NeXT/blob/inference/docs/LLaVA-NeXT-Video_0716.md) for the runnning of the latest model.
34
+
35
+ ## Evaluation
36
+
37
+ ### Preparation
38
+
39
+ Please download the evaluation data and its metadata from the following links:
40
+
41
+ 1. **video-chatgpt:** [here](https://github.com/mbzuai-oryx/Video-ChatGPT/blob/main/quantitative_evaluation/README.md#video-based-generative-performance-benchmarking).
42
+ 2. **video_detail_description:** [here](https://mbzuaiac-my.sharepoint.com/personal/hanoona_bangalath_mbzuai_ac_ae/_layouts/15/onedrive.aspx?id=%2Fpersonal%2Fhanoona%5Fbangalath%5Fmbzuai%5Fac%5Fae%2FDocuments%2FVideo%2DChatGPT%2FData%5FCode%5FModel%5FRelease%2FQuantitative%5FEvaluation%2Fbenchamarking%2FTest%5FHuman%5FAnnotated%5FCaptions%2Ezip&parent=%2Fpersonal%2Fhanoona%5Fbangalath%5Fmbzuai%5Fac%5Fae%2FDocuments%2FVideo%2DChatGPT%2FData%5FCode%5FModel%5FRelease%2FQuantitative%5FEvaluation%2Fbenchamarking&ga=1).
43
+ 3. **activity_qa:** [here](https://mbzuaiac-my.sharepoint.com/personal/hanoona_bangalath_mbzuai_ac_ae/_layouts/15/onedrive.aspx?id=%2Fpersonal%2Fhanoona%5Fbangalath%5Fmbzuai%5Fac%5Fae%2FDocuments%2FVideo%2DChatGPT%2FData%5FCode%5FModel%5FRelease%2FData%2FActivityNet%5FTest%2D1%2D3%5Fvideos%2Ezip&parent=%2Fpersonal%2Fhanoona%5Fbangalath%5Fmbzuai%5Fac%5Fae%2FDocuments%2FVideo%2DChatGPT%2FData%5FCode%5FModel%5FRelease%2FData&ga=1) and [here](https://github.com/MILVLG/activitynet-qa/tree/master/dataset).
44
+
45
+ Organize the downloaded data into the following structure:
46
+ ```
47
+ LLaVA-NeXT
48
+ ├── llava
49
+ ├── scripts
50
+ └── data
51
+ └── llava_video
52
+ ├── video-chatgpt
53
+ │ ├── Test_Videos
54
+ │ ├── consistency_qa.json
55
+ │ ├── consistency_qa_test.json
56
+ │ ├── consistency_qa_train.json
57
+ ├── video_detail_description
58
+ │ └── Test_Human_Annotated_Captions
59
+ └── ActivityNet-QA
60
+ ├── all_test
61
+ ├── test_a.json
62
+ └── test_b.json
63
+ ```
64
+
65
+ ### Inference and Evaluation
66
+
67
+ Example for video detail description evaluation (additional scripts are available in `scripts/eval`):
68
+ ```bash
69
+ bash scripts/video/eval/video_detail_description_eval_shard.sh ${Example model} ${Prompt mode} ${Sampled frames} ${Spatial pooling stride} True 8
70
+ ```
71
+ Example:
72
+ ```bash
73
+ bash scripts/eval/video_detail_description_eval_shard.sh liuhaotian/llava-v1.6-vicuna-7b vicuna_v1 32 2 True 8
74
+ ```
75
+
76
+ ### GPT Evaluation Example (Optional if the above step is completed)
77
+
78
+ Assuming you have `pred.json` (model-generated predictions) for model `llava-v1.6-vicuna-7b` at `./work_dirs/eval_video_detail_description/llava-v1.6-vicuna-7b_vicuna_v1_frames_32_stride_2`:
79
+ ```bash
80
+ bash scripts/video/eval/video_description_eval_only.sh llava-v1.6-vicuna-7b_vicuna_v1_frames_32_stride_2
81
+ ```
之前的代码版本/第一版-全部代码/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/docs/LLaVA_OneVision.md ADDED
@@ -0,0 +1,121 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # LLaVA OneVision
2
+
3
+ ## Model Details
4
+
5
+ LLaVA OneVision is a multi-modal model capable of processing images, text, image-text interleaved inputs, and videos. The model is trained in multiple stages:
6
+
7
+ 1. Stage-1: Initial training on 558K samples from the LCS dataset.
8
+ 2. Stage-1.5: Training on 4M high-quality samples with detailed captions, OCR and knowledge data.
9
+ 3. Stage-2:
10
+ - Single-Image: Training on 3.2M instruction-following image samples.
11
+ - OneVision: Training on 1.6M single-image, multi-image and video samples with instructions.
12
+
13
+ Key features:
14
+ - Supports various input resolutions up to 2304 * 2304 pixels.
15
+ - Single image input is represented by 729 * (9+1) tokens at most under `anyres_max_9` mode.
16
+ - Supports multi-image and video inputs. Multi-image input is represented by 729 token for each image, and video input is represented by 196 token for each frame.
17
+ - Available in three sizes: 0.5B, 7B and 72B parameter versions, fit for different memory and inference latency requirements.
18
+
19
+ Some Implementation Details:
20
+ - Trained using a combination of vision-specific (AdamW, 2e-6) and language model (AdamW, 1e-5) learning rates.
21
+ - Each stage is trained for 1 epoch.
22
+
23
+ The model uses [SO400M](https://huggingface.co/collections/google/siglip-659d5e62f0ae1a57ae0e83ba) as the vision encoder and [Qwen-2.0](https://huggingface.co/docs/transformers/model_doc/qwen2) as the language model, with trainable components including a projector and the full model in later stages.
24
+
25
+ We recommend to use the scripts in [training](../scripts/) to get the details of the training process.
26
+
27
+ ## Inference Guidance
28
+
29
+ We recommend to follow the [tutorial](./LLaVA_OneVision_Tutorials.ipynb) to get started on using our most basic 0.5B model for image, text, image-text interleaved, and video input. We use our 0.5B version as an example. This could be running on a GPU with 4GB memory. And with the following examples, you could see it's surprisingly have promising performance on understanding the image, interleaved image-text, and video. Tiny but mighty!
30
+
31
+ ## Evaluation Guidance
32
+
33
+ We use the [lmms-eval](https://github.com/EvolvingLMMs-Lab/lmms-eval) toolkit to evaluate our models. Ensure you have installed the LLaVA-NeXT model files as per the instructions in the main README.md.
34
+
35
+ Install lmms-eval:
36
+
37
+ > pip install git+https://github.com/EvolvingLMMs-Lab/lmms-eval.git
38
+
39
+ ### Reproducing Evaluation Results
40
+
41
+ Our models' evaluation results can be fully reproduced using the lmms-eval toolkit. After installing lmms-eval and llava, you can run the evaluation using the following commands.
42
+
43
+ Note: These commands require flash-attn. If you prefer not to install it, disable flash-attn by adding `attn_implementation=None` to the `--model_args` parameter.
44
+
45
+ Important: Different torch versions may cause slight variations in results. By default in `lmms-eval`, the requirement for torch version is set to the latest version. In `llava` repo, the torch version is set to `2.1.2`. Torch version `2.1.2` would be stable for both `llava` and `lmms-eval`
46
+
47
+ ### Evaluating LLaVA-OneVision on multiple datasets
48
+
49
+ We recommend the developers and researchers to thoroughly evaluate the models on more datasets to get a comprehensive understanding of their performance in different scenarios. So we provide a comprehensive list of datasets for evaluation, and welcome to incoporate more evaluation tasks. Please refer to the [lmms-eval](https://github.com/EvolvingLMMs-Lab/lmms-eval) for more details.
50
+
51
+
52
+ Task: single-image tasks.
53
+
54
+ ```bash
55
+ # image tasks
56
+ accelerate launch --num_processes=8 \
57
+ -m lmms_eval \
58
+ --model llava_onevision \
59
+ --model_args pretrained=lmms-lab/llava-onevision-qwen2-0.5b-si,conv_template=qwen_1_5,model_name=llava_qwen \
60
+ --tasks ai2d,chartqa,docvqa_val,infovqa_val,mme,realworldqa,mathvista_testmini,llava_in_the_wild,mmvet,mmbench_en_dev,ocrbench,mmmu,mathverse_testmini_vision_intensive,mathverse_testmini_vision_only,seedbench,scienceqa_img,mmstar \
61
+ --batch_size 1 \
62
+ --log_samples \
63
+ --log_samples_suffix llava_onevision \
64
+ --output_path ./logs/
65
+ ```
66
+
67
+ ## Data Visualization
68
+
69
+ We provide visualization scripts to analyze the training data distribution in the notebook [llava_ov_plot.ipynb](../llava_ov_plot.ipynb). The notebook includes:
70
+
71
+ - **Training Data Distribution by Category**: Visualizes data across Doc/Chart/Screen, General, Pure Language, Math/Reasoning, and General OCR categories with nested pie charts showing detailed dataset contributions.
72
+ - **Training Data Distribution by Modality**: Shows the breakdown of single-image, multi-image, and video data with percentage calculations.
73
+ - **Polar/Radar Charts**: Advanced visualizations for comparing model performance across different benchmarks.
74
+ - **Timeline Visualizations**: Tracks the evolution of model capabilities over time.
75
+
76
+ Task: video tasks. The video tasks are more computationally expensive. We recommend running them on a machine with a GPU with at least 16GB memory.
77
+
78
+ ```bash
79
+ # video tasks
80
+ accelerate launch --num_processes=8 \
81
+ -m lmms_eval \
82
+ --model llava_onevision \
83
+ --model_args pretrained=lmms-lab/llava-onevision-qwen2-0.5b-ov,conv_template=qwen_1_5,model_name=llava_qwen \
84
+ --tasks activitynetqa,videochatgpt,nextqa_mc_test,egoschema,video_dc499,videmme,videomme_w_subtitle,perceptiontest_val_mc \
85
+ --batch_size 1 \
86
+ --log_samples \
87
+ --log_samples_suffix llava_onevision \
88
+ --output_path ./logs/
89
+ ```
90
+
91
+ ## Data Visualization
92
+
93
+ We provide visualization scripts to analyze the training data distribution in the notebook [llava_ov_plot.ipynb](../playground/llava_ov_plot.ipynb). The notebook includes:
94
+
95
+ - **Training Data Distribution by Category**: Visualizes data across Doc/Chart/Screen, General, Pure Language, Math/Reasoning, and General OCR categories with nested pie charts showing detailed dataset contributions.
96
+ - **Training Data Distribution by Modality**: Shows the breakdown of single-image, multi-image, and video data with percentage calculations.
97
+ - **Polar/Radar Charts**: Advanced visualizations for comparing model performance across different benchmarks.
98
+ - **Timeline Visualizations**: Tracks the evolution of model capabilities over time.
99
+
100
+ Task: interleave tasks (`llava-interleave-bench` already contains most of existing image-text tasks). `mmmu_test` contains single image and multiple images as input, we run the model to obtain a submission file and you need to submit it to the [leaderboard](https://eval.ai/web/challenges/challenge-page/1700/overview) to get the accuracy for MMMU (multi-image) result.
101
+
102
+ ```bash
103
+ accelerate launch --num_processes=8 \
104
+ -m lmms_eval \
105
+ --model llava_onevision \
106
+ --model_args pretrained=lmms-lab/llava-onevision-qwen2-0.5b-ov,conv_template=qwen_1_5,model_name=llava_qwen \
107
+ --tasks llava-interleave-bench,muirbench,mmmu_test \
108
+ --batch_size 1 \
109
+ --log_samples \
110
+ --log_samples_suffix llava_onevision \
111
+ --output_path ./logs/
112
+ ```
113
+
114
+ ## Data Visualization
115
+
116
+ We provide visualization scripts to analyze the training data distribution in the notebook [llava_ov_plot.ipynb](../playground/llava_ov_plot.ipynb). The notebook includes:
117
+
118
+ - **Training Data Distribution by Category**: Visualizes data across Doc/Chart/Screen, General, Pure Language, Math/Reasoning, and General OCR categories with nested pie charts showing detailed dataset contributions.
119
+ - **Training Data Distribution by Modality**: Shows the breakdown of single-image, multi-image, and video data with percentage calculations.
120
+ - **Polar/Radar Charts**: Advanced visualizations for comparing model performance across different benchmarks.
121
+ - **Timeline Visualizations**: Tracks the evolution of model capabilities over time.
之前的代码版本/第一版-全部代码/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/docs/LLaVA_OneVision_Tutorials.ipynb ADDED
@@ -0,0 +1,397 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "markdown",
5
+ "metadata": {},
6
+ "source": [
7
+ "# (Frustratingly Easy) LLaVA OneVision Tutorial\n",
8
+ "\n",
9
+ "We know that it's always beneficial to have a unified interface for different tasks. So we are trying to unify the interface for image, text, image-text interleaved, and video input. And in this tutorial, we aim to provide the most straightforward way to use our model. \n",
10
+ "\n",
11
+ "We use our 0.5B version as an example. This could be running on a GPU with 4GB memory. And with the following examples, you could see it's surprisingly have promising performance on understanding the image, interleaved image-text, and video. Tiny but mighty!\n",
12
+ "\n",
13
+ "The same code could be used for 7B model as well.\n",
14
+ "\n",
15
+ "## Inference Guidance\n",
16
+ "\n",
17
+ "First please install our repo with code and environments: pip install git+https://github.com/LLaVA-VL/LLaVA-NeXT.git\n",
18
+ "\n",
19
+ "Here is a quick inference code using [lmms-lab/qwen2-0.5b-si](https://huggingface.co/lmms-lab/llava-onevision-qwen2-0.5b-si) as an example. You will need to install `flash-attn` to use this code snippet. If you don't want to install it, you can set `attn_implementation=None` when load_pretrained_model\n",
20
+ "\n",
21
+ "### Image Input\n",
22
+ "Tackling the single image input with LLaVA OneVision is pretty straightforward."
23
+ ]
24
+ },
25
+ {
26
+ "cell_type": "code",
27
+ "execution_count": null,
28
+ "metadata": {},
29
+ "outputs": [],
30
+ "source": [
31
+ "from llava.model.builder import load_pretrained_model\n",
32
+ "from llava.mm_utils import get_model_name_from_path, process_images, tokenizer_image_token\n",
33
+ "from llava.constants import IMAGE_TOKEN_INDEX, DEFAULT_IMAGE_TOKEN, DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN, IGNORE_INDEX\n",
34
+ "from llava.conversation import conv_templates, SeparatorStyle\n",
35
+ "\n",
36
+ "from PIL import Image\n",
37
+ "import requests\n",
38
+ "import copy\n",
39
+ "import torch\n",
40
+ "\n",
41
+ "import sys\n",
42
+ "import warnings\n",
43
+ "\n",
44
+ "warnings.filterwarnings(\"ignore\")\n",
45
+ "pretrained = \"lmms-lab/llava-onevision-qwen2-0.5b-si\"\n",
46
+ "model_name = \"llava_qwen\"\n",
47
+ "device = \"cuda\"\n",
48
+ "device_map = \"auto\"\n",
49
+ "llava_model_args = {\n",
50
+ " \"multimodal\": True,\n",
51
+ " \"attn_implementation\": \"sdpa\",\n",
52
+ "}\n",
53
+ "tokenizer, model, image_processor, max_length = load_pretrained_model(pretrained, None, model_name, device_map=device_map, **llava_model_args) # Add any other thing you want to pass in llava_model_args\n",
54
+ "\n",
55
+ "model.eval()\n",
56
+ "\n",
57
+ "url = \"https://github.com/haotian-liu/LLaVA/blob/1a91fc274d7c35a9b50b3cb29c4247ae5837ce39/images/llava_v1_5_radar.jpg?raw=true\"\n",
58
+ "image = Image.open(requests.get(url, stream=True).raw)\n",
59
+ "image_tensor = process_images([image], image_processor, model.config)\n",
60
+ "image_tensor = [_image.to(dtype=torch.float16, device=device) for _image in image_tensor]\n",
61
+ "\n",
62
+ "conv_template = \"qwen_1_5\" # Make sure you use correct chat template for different models\n",
63
+ "question = DEFAULT_IMAGE_TOKEN + \"\\nWhat is shown in this image?\"\n",
64
+ "conv = copy.deepcopy(conv_templates[conv_template])\n",
65
+ "conv.append_message(conv.roles[0], question)\n",
66
+ "conv.append_message(conv.roles[1], None)\n",
67
+ "prompt_question = conv.get_prompt()\n",
68
+ "\n",
69
+ "input_ids = tokenizer_image_token(prompt_question, tokenizer, IMAGE_TOKEN_INDEX, return_tensors=\"pt\").unsqueeze(0).to(device)\n",
70
+ "image_sizes = [image.size]\n",
71
+ "\n",
72
+ "\n",
73
+ "cont = model.generate(\n",
74
+ " input_ids,\n",
75
+ " images=image_tensor,\n",
76
+ " image_sizes=image_sizes,\n",
77
+ " do_sample=False,\n",
78
+ " temperature=0,\n",
79
+ " max_new_tokens=4096,\n",
80
+ ")\n",
81
+ "text_outputs = tokenizer.batch_decode(cont, skip_special_tokens=True)\n",
82
+ "print(text_outputs)"
83
+ ]
84
+ },
85
+ {
86
+ "cell_type": "markdown",
87
+ "metadata": {},
88
+ "source": [
89
+ "You could use the following code to make it streaming in terminal, this would be pretty useful when creating a chatbot."
90
+ ]
91
+ },
92
+ {
93
+ "cell_type": "code",
94
+ "execution_count": null,
95
+ "metadata": {},
96
+ "outputs": [],
97
+ "source": [
98
+ "from threading import Thread\n",
99
+ "from transformers import TextIteratorStreamer\n",
100
+ "import json\n",
101
+ "\n",
102
+ "url = \"https://github.com/haotian-liu/LLaVA/blob/1a91fc274d7c35a9b50b3cb29c4247ae5837ce39/images/llava_v1_5_radar.jpg?raw=true\"\n",
103
+ "image = Image.open(requests.get(url, stream=True).raw)\n",
104
+ "image_tensor = process_images([image], image_processor, model.config)\n",
105
+ "image_tensor = [_image.to(dtype=torch.float16, device=device) for _image in image_tensor]\n",
106
+ "\n",
107
+ "conv_template = \"qwen_1_5\"\n",
108
+ "question = DEFAULT_IMAGE_TOKEN + \"\\nWhat is shown in this image?\"\n",
109
+ "conv = copy.deepcopy(conv_templates[conv_template])\n",
110
+ "conv.append_message(conv.roles[0], question)\n",
111
+ "conv.append_message(conv.roles[1], None)\n",
112
+ "prompt_question = conv.get_prompt()\n",
113
+ "\n",
114
+ "input_ids = tokenizer_image_token(prompt_question, tokenizer, IMAGE_TOKEN_INDEX, return_tensors=\"pt\").unsqueeze(0).to(device)\n",
115
+ "image_sizes = [image.size]\n",
116
+ "\n",
117
+ "max_context_length = getattr(model.config, \"max_position_embeddings\", 2048)\n",
118
+ "num_image_tokens = question.count(DEFAULT_IMAGE_TOKEN) * model.get_vision_tower().num_patches\n",
119
+ "\n",
120
+ "streamer = TextIteratorStreamer(tokenizer, skip_prompt=True, skip_special_tokens=True, timeout=15)\n",
121
+ "\n",
122
+ "max_new_tokens = min(4096, max_context_length - input_ids.shape[-1] - num_image_tokens)\n",
123
+ "\n",
124
+ "if max_new_tokens < 1:\n",
125
+ " print(\n",
126
+ " json.dumps(\n",
127
+ " {\n",
128
+ " \"text\": question + \"Exceeds max token length. Please start a new conversation, thanks.\",\n",
129
+ " \"error_code\": 0,\n",
130
+ " }\n",
131
+ " )\n",
132
+ " )\n",
133
+ "else:\n",
134
+ " gen_kwargs = {\n",
135
+ " \"do_sample\": False,\n",
136
+ " \"temperature\": 0,\n",
137
+ " \"max_new_tokens\": max_new_tokens,\n",
138
+ " \"images\": image_tensor,\n",
139
+ " \"image_sizes\": image_sizes,\n",
140
+ " }\n",
141
+ "\n",
142
+ " thread = Thread(\n",
143
+ " target=model.generate,\n",
144
+ " kwargs=dict(\n",
145
+ " inputs=input_ids,\n",
146
+ " streamer=streamer,\n",
147
+ " **gen_kwargs,\n",
148
+ " ),\n",
149
+ " )\n",
150
+ " thread.start()\n",
151
+ "\n",
152
+ " generated_text = \"\"\n",
153
+ " for new_text in streamer:\n",
154
+ " generated_text += new_text\n",
155
+ " print(generated_text, flush=True)\n",
156
+ " # print(json.dumps({\"text\": generated_text, \"error_code\": 0}), flush=True)\n",
157
+ "\n",
158
+ " print(\"Final output:\", generated_text)"
159
+ ]
160
+ },
161
+ {
162
+ "cell_type": "markdown",
163
+ "metadata": {},
164
+ "source": [
165
+ "### Image-Text Interleaved Input\n",
166
+ "\n",
167
+ "Now switching to our onevision model for more complex tasks. You should start to use `llava-onevision-qwen2-0.5b-ov` for image-text interleaved input and video input.\n",
168
+ "\n",
169
+ "Processing image-text interleaved input is a bit more complicated. But following the code below should work."
170
+ ]
171
+ },
172
+ {
173
+ "cell_type": "code",
174
+ "execution_count": null,
175
+ "metadata": {},
176
+ "outputs": [],
177
+ "source": [
178
+ "# Load model\n",
179
+ "pretrained = \"lmms-lab/llava-onevision-qwen2-0.5b-ov\"\n",
180
+ "model_name = \"llava_qwen\"\n",
181
+ "device = \"cuda\"\n",
182
+ "device_map = \"auto\"\n",
183
+ "llava_model_args = {\n",
184
+ " \"multimodal\": True,\n",
185
+ " }\n",
186
+ "overwrite_config = {}\n",
187
+ "overwrite_config[\"image_aspect_ratio\"] = \"pad\"\n",
188
+ "llava_model_args[\"overwrite_config\"] = overwrite_config\n",
189
+ "tokenizer, model, image_processor, max_length = load_pretrained_model(pretrained, None, model_name, device_map=device_map, **llava_model_args)\n",
190
+ "\n",
191
+ "model.eval()\n",
192
+ "\n",
193
+ "# Load two images\n",
194
+ "url1 = \"https://github.com/haotian-liu/LLaVA/blob/1a91fc274d7c35a9b50b3cb29c4247ae5837ce39/images/llava_v1_5_radar.jpg?raw=true\"\n",
195
+ "url2 = \"https://raw.githubusercontent.com/haotian-liu/LLaVA/main/images/llava_logo.png\"\n",
196
+ "\n",
197
+ "image1 = Image.open(requests.get(url1, stream=True).raw)\n",
198
+ "image2 = Image.open(requests.get(url2, stream=True).raw)\n",
199
+ "\n",
200
+ "images = [image1, image2]\n",
201
+ "image_tensors = process_images(images, image_processor, model.config)\n",
202
+ "image_tensors = [_image.to(dtype=torch.float16, device=device) for _image in image_tensors]\n",
203
+ "\n",
204
+ "# Prepare interleaved text-image input\n",
205
+ "conv_template = \"qwen_1_5\"\n",
206
+ "question = f\"{DEFAULT_IMAGE_TOKEN} This is the first image. Can you describe what you see?\\n\\nNow, let's look at another image: {DEFAULT_IMAGE_TOKEN}\\nWhat's the difference between these two images?\"\n",
207
+ "\n",
208
+ "conv = copy.deepcopy(conv_templates[conv_template])\n",
209
+ "conv.append_message(conv.roles[0], question)\n",
210
+ "conv.append_message(conv.roles[1], None)\n",
211
+ "prompt_question = conv.get_prompt()\n",
212
+ "\n",
213
+ "input_ids = tokenizer_image_token(prompt_question, tokenizer, IMAGE_TOKEN_INDEX, return_tensors=\"pt\").unsqueeze(0).to(device)\n",
214
+ "image_sizes = [image.size for image in images]\n",
215
+ "\n",
216
+ "# Generate response\n",
217
+ "cont = model.generate(\n",
218
+ " input_ids,\n",
219
+ " images=image_tensors,\n",
220
+ " image_sizes=image_sizes,\n",
221
+ " do_sample=False,\n",
222
+ " temperature=0,\n",
223
+ " max_new_tokens=4096,\n",
224
+ ")\n",
225
+ "text_outputs = tokenizer.batch_decode(cont, skip_special_tokens=True)\n",
226
+ "print(text_outputs[0])"
227
+ ]
228
+ },
229
+ {
230
+ "cell_type": "markdown",
231
+ "metadata": {},
232
+ "source": [
233
+ "### Video Input\n",
234
+ "\n",
235
+ "Now let's try video input. It's the same as image input, but you need to pass in a list of video frames. And remember to set the `<image>` token only once in the prompt, e.g. \"<image>\\nWhat is shown in this video?\", not \"<image>\\n<image>\\n<image>\\nWhat is shown in this video?\". Since we trained on this format, it's important to keep the format consistent."
236
+ ]
237
+ },
238
+ {
239
+ "cell_type": "code",
240
+ "execution_count": 1,
241
+ "metadata": {},
242
+ "outputs": [
243
+ {
244
+ "name": "stderr",
245
+ "output_type": "stream",
246
+ "text": [
247
+ "/home/tiger/miniconda3/envs/public_llava/lib/python3.10/site-packages/tqdm/auto.py:21: TqdmWarning: IProgress not found. Please update jupyter and ipywidgets. See https://ipywidgets.readthedocs.io/en/stable/user_install.html\n",
248
+ " from .autonotebook import tqdm as notebook_tqdm\n",
249
+ "/home/tiger/miniconda3/envs/public_llava/lib/python3.10/site-packages/huggingface_hub/file_download.py:1150: FutureWarning: `resume_download` is deprecated and will be removed in version 1.0.0. Downloads always resume when possible. If you want to force a new download, use `force_download=True`.\n",
250
+ " warnings.warn(\n",
251
+ "Special tokens have been added in the vocabulary, make sure the associated word embeddings are fine-tuned or trained.\n"
252
+ ]
253
+ },
254
+ {
255
+ "name": "stdout",
256
+ "output_type": "stream",
257
+ "text": [
258
+ "Loaded LLaVA model: lmms-lab/llava-onevision-qwen2-7b-ov\n"
259
+ ]
260
+ },
261
+ {
262
+ "name": "stderr",
263
+ "output_type": "stream",
264
+ "text": [
265
+ "Special tokens have been added in the vocabulary, make sure the associated word embeddings are fine-tuned or trained.\n",
266
+ "You are using a model of type llava to instantiate a model of type llava_qwen. This is not supported for all configurations of models and can yield errors.\n"
267
+ ]
268
+ },
269
+ {
270
+ "name": "stdout",
271
+ "output_type": "stream",
272
+ "text": [
273
+ "Loading vision tower: google/siglip-so400m-patch14-384\n"
274
+ ]
275
+ },
276
+ {
277
+ "name": "stderr",
278
+ "output_type": "stream",
279
+ "text": [
280
+ "Loading checkpoint shards: 100%|██████████| 4/4 [00:08<00:00, 2.07s/it]\n"
281
+ ]
282
+ },
283
+ {
284
+ "name": "stdout",
285
+ "output_type": "stream",
286
+ "text": [
287
+ "Model Class: LlavaQwenForCausalLM\n",
288
+ "(16, 1024, 576, 3)\n",
289
+ "The video features a person standing on a stage, dressed in a black shirt and dark pants. A large hand appears from the background, reaching towards the person's pocket. The text 'Source: Joshua AG' is displayed at the top left corner of the frames, and 'EVAN CARMICHAEL' is shown in the top right corner. The text 'Anyone know what this pocket is for?' appears as the hand continues to reach into the pocket. The person then looks down at their pocket, and the text 'I've always wondered that' appears. The hand finally pulls out a small white device labeled 'iPod Nano'. The person holds up the iPod Nano, and the text 'is the new iPod Nano' appears. The video concludes with a close-up of the person holding the iPod Nano, showing it from different angles.\n"
290
+ ]
291
+ }
292
+ ],
293
+ "source": [
294
+ "from operator import attrgetter\n",
295
+ "from llava.model.builder import load_pretrained_model\n",
296
+ "from llava.mm_utils import get_model_name_from_path, process_images, tokenizer_image_token\n",
297
+ "from llava.constants import IMAGE_TOKEN_INDEX, DEFAULT_IMAGE_TOKEN, DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN, IGNORE_INDEX\n",
298
+ "from llava.conversation import conv_templates, SeparatorStyle\n",
299
+ "\n",
300
+ "import torch\n",
301
+ "import cv2\n",
302
+ "import numpy as np\n",
303
+ "from PIL import Image\n",
304
+ "import requests\n",
305
+ "import copy\n",
306
+ "import warnings\n",
307
+ "from decord import VideoReader, cpu\n",
308
+ "\n",
309
+ "warnings.filterwarnings(\"ignore\")\n",
310
+ "# Load the OneVision model\n",
311
+ "pretrained = \"lmms-lab/llava-onevision-qwen2-7b-ov\"\n",
312
+ "model_name = \"llava_qwen\"\n",
313
+ "device = \"cuda\"\n",
314
+ "device_map = \"auto\"\n",
315
+ "llava_model_args = {\n",
316
+ " \"multimodal\": True,\n",
317
+ "}\n",
318
+ "tokenizer, model, image_processor, max_length = load_pretrained_model(pretrained, None, model_name, device_map=device_map, attn_implementation=\"sdpa\", **llava_model_args)\n",
319
+ "\n",
320
+ "model.eval()\n",
321
+ "\n",
322
+ "\n",
323
+ "# Function to extract frames from video\n",
324
+ "def load_video(video_path, max_frames_num):\n",
325
+ " if type(video_path) == str:\n",
326
+ " vr = VideoReader(video_path, ctx=cpu(0))\n",
327
+ " else:\n",
328
+ " vr = VideoReader(video_path[0], ctx=cpu(0))\n",
329
+ " total_frame_num = len(vr)\n",
330
+ " uniform_sampled_frames = np.linspace(0, total_frame_num - 1, max_frames_num, dtype=int)\n",
331
+ " frame_idx = uniform_sampled_frames.tolist()\n",
332
+ " spare_frames = vr.get_batch(frame_idx).asnumpy()\n",
333
+ " return spare_frames # (frames, height, width, channels)\n",
334
+ "\n",
335
+ "\n",
336
+ "# Load and process video\n",
337
+ "video_path = \"jobs.mp4\"\n",
338
+ "video_frames = load_video(video_path, 16)\n",
339
+ "print(video_frames.shape) # (16, 1024, 576, 3)\n",
340
+ "image_tensors = []\n",
341
+ "frames = image_processor.preprocess(video_frames, return_tensors=\"pt\")[\"pixel_values\"].half().cuda()\n",
342
+ "image_tensors.append(frames)\n",
343
+ "\n",
344
+ "# Prepare conversation input\n",
345
+ "conv_template = \"qwen_1_5\"\n",
346
+ "question = f\"{DEFAULT_IMAGE_TOKEN}\\nDescribe what's happening in this video.\"\n",
347
+ "\n",
348
+ "conv = copy.deepcopy(conv_templates[conv_template])\n",
349
+ "conv.append_message(conv.roles[0], question)\n",
350
+ "conv.append_message(conv.roles[1], None)\n",
351
+ "prompt_question = conv.get_prompt()\n",
352
+ "\n",
353
+ "input_ids = tokenizer_image_token(prompt_question, tokenizer, IMAGE_TOKEN_INDEX, return_tensors=\"pt\").unsqueeze(0).to(device)\n",
354
+ "image_sizes = [frame.size for frame in video_frames]\n",
355
+ "\n",
356
+ "# Generate response\n",
357
+ "cont = model.generate(\n",
358
+ " input_ids,\n",
359
+ " images=image_tensors,\n",
360
+ " image_sizes=image_sizes,\n",
361
+ " do_sample=False,\n",
362
+ " temperature=0,\n",
363
+ " max_new_tokens=4096,\n",
364
+ " modalities=[\"video\"],\n",
365
+ ")\n",
366
+ "text_outputs = tokenizer.batch_decode(cont, skip_special_tokens=True)\n",
367
+ "print(text_outputs[0])"
368
+ ]
369
+ }
370
+ ],
371
+ "metadata": {
372
+ "kernelspec": {
373
+ "display_name": "Python 3.9.2 64-bit",
374
+ "language": "python",
375
+ "name": "python3"
376
+ },
377
+ "language_info": {
378
+ "codemirror_mode": {
379
+ "name": "ipython",
380
+ "version": 3
381
+ },
382
+ "file_extension": ".py",
383
+ "mimetype": "text/x-python",
384
+ "name": "python",
385
+ "nbconvert_exporter": "python",
386
+ "pygments_lexer": "ipython3",
387
+ "version": "3.10.14"
388
+ },
389
+ "vscode": {
390
+ "interpreter": {
391
+ "hash": "31f2aee4e71d21fbe5cf8b01ff0e069b9275f58929596ceb00d14d90e3e16cd6"
392
+ }
393
+ }
394
+ },
395
+ "nbformat": 4,
396
+ "nbformat_minor": 2
397
+ }
之前的代码版本/第一版-全部代码/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/docs/README.md ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # LLaVA-NeXT Documentation
2
+
3
+ Welcome to the LLaVA-NeXT documentation. This guide provides an overview of the different components and features of LLaVA-NeXT. Please refer to the following documents for detailed information on specific topics:
4
+
5
+ 1. [LLaVA OneVision](LLaVA_OneVision.md): Learn about the most advanced and unified version: LLaVA OneVision.
6
+ - [LLaVA OneVision: Inference Tutorials](LLaVA_OneVision_Tutorials.ipynb): Learn how to use LLaVA OneVision for inference.
7
+ - [LLaVA OneVision: Data Visualization](../llava_ov_plot.ipynb): Visualization scripts for analyzing training data distribution and model performance.
8
+ - [LLaVA Onevision Chat](LLaVA_OneVision_Chat.md): Improving Chat with Preference Learning
9
+
10
+ 2. [LLaVA-NeXT Interleave](LLaVA-NeXT-Interleave.md): Explore the interleaved training approach used in LLaVA-NeXT.
11
+
12
+ 3. [LLaVA-NeXT Video (0716)](LLaVA-NeXT-Video_0716.md): Discover the video processing capabilities of LLaVA-NeXT (version 0716).
13
+
14
+ 4. [LLaVA-NeXT Video](LLaVA-NeXT-Video.md): Get information about the latest video processing features in LLaVA-NeXT.
15
+
16
+ 5. [LLaVA-NeXT Overview](LLaVA-NeXT.md): Read a comprehensive overview of the LLaVA-NeXT project, including its architecture, features, and capabilities.
17
+
18
+ These documents provide in-depth information on various aspects of LLaVA-NeXT. Please refer to them for detailed explanations, implementation details, and usage instructions.
之前的代码版本/第一版-全部代码/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/docs/onevision_trial.py ADDED
@@ -0,0 +1,111 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from llava.model.builder import load_pretrained_model
2
+ from llava.mm_utils import get_model_name_from_path, process_images, tokenizer_image_token
3
+ from llava.constants import IMAGE_TOKEN_INDEX, DEFAULT_IMAGE_TOKEN, DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN, IGNORE_INDEX
4
+ from llava.conversation import conv_templates, SeparatorStyle
5
+
6
+ from PIL import Image
7
+ import requests
8
+ import copy
9
+ import torch
10
+
11
+ import sys
12
+ import warnings
13
+
14
+ warnings.filterwarnings("ignore")
15
+
16
+ pretrained = "lmms-lab/llava-onevision-qwen2-0.5b-si"
17
+ model_name = "llava_qwen"
18
+ device = "cuda"
19
+ device_map = "auto"
20
+ tokenizer, model, image_processor, max_length = load_pretrained_model(pretrained, None, model_name, device_map=device_map) # Add any other thing you want to pass in llava_model_args
21
+
22
+ model.eval()
23
+
24
+ url = "https://github.com/haotian-liu/LLaVA/blob/1a91fc274d7c35a9b50b3cb29c4247ae5837ce39/images/llava_v1_5_radar.jpg?raw=true"
25
+ image = Image.open(requests.get(url, stream=True).raw)
26
+ image_tensor = process_images([image], image_processor, model.config)
27
+ image_tensor = [_image.to(dtype=torch.float16, device=device) for _image in image_tensor]
28
+
29
+ conv_template = "qwen_1_5" # Make sure you use correct chat template for different models
30
+ question = DEFAULT_IMAGE_TOKEN + "\nWhat is shown in this image?"
31
+ conv = copy.deepcopy(conv_templates[conv_template])
32
+ conv.append_message(conv.roles[0], question)
33
+ conv.append_message(conv.roles[1], None)
34
+ prompt_question = conv.get_prompt()
35
+
36
+ input_ids = tokenizer_image_token(prompt_question, tokenizer, IMAGE_TOKEN_INDEX, return_tensors="pt").unsqueeze(0).to(device)
37
+ image_sizes = [image.size]
38
+
39
+
40
+ cont = model.generate(
41
+ input_ids,
42
+ images=image_tensor,
43
+ image_sizes=image_sizes,
44
+ do_sample=False,
45
+ temperature=0,
46
+ max_new_tokens=4096,
47
+ )
48
+ text_outputs = tokenizer.batch_decode(cont, skip_special_tokens=True)
49
+ print(text_outputs)
50
+
51
+ from threading import Thread
52
+ from transformers import TextIteratorStreamer
53
+ import json
54
+
55
+ url = "https://github.com/haotian-liu/LLaVA/blob/1a91fc274d7c35a9b50b3cb29c4247ae5837ce39/images/llava_v1_5_radar.jpg?raw=true"
56
+ image = Image.open(requests.get(url, stream=True).raw)
57
+ image_tensor = process_images([image], image_processor, model.config)
58
+ image_tensor = [_image.to(dtype=torch.float16, device=device) for _image in image_tensor]
59
+
60
+ conv_template = "qwen_1_5"
61
+ question = DEFAULT_IMAGE_TOKEN + "\nWhat is shown in this image?"
62
+ conv = copy.deepcopy(conv_templates[conv_template])
63
+ conv.append_message(conv.roles[0], question)
64
+ conv.append_message(conv.roles[1], None)
65
+ prompt_question = conv.get_prompt()
66
+
67
+ input_ids = tokenizer_image_token(prompt_question, tokenizer, IMAGE_TOKEN_INDEX, return_tensors="pt").unsqueeze(0).to(device)
68
+ image_sizes = [image.size]
69
+
70
+ max_context_length = getattr(model.config, "max_position_embeddings", 2048)
71
+ num_image_tokens = question.count(DEFAULT_IMAGE_TOKEN) * model.get_vision_tower().num_patches
72
+
73
+ streamer = TextIteratorStreamer(tokenizer, skip_prompt=True, skip_special_tokens=True, timeout=15)
74
+
75
+ max_new_tokens = min(4096, max_context_length - input_ids.shape[-1] - num_image_tokens)
76
+
77
+ if max_new_tokens < 1:
78
+ print(
79
+ json.dumps(
80
+ {
81
+ "text": question + "Exceeds max token length. Please start a new conversation, thanks.",
82
+ "error_code": 0,
83
+ }
84
+ )
85
+ )
86
+ else:
87
+ gen_kwargs = {
88
+ "do_sample": False,
89
+ "temperature": 0,
90
+ "max_new_tokens": max_new_tokens,
91
+ "images": image_tensor,
92
+ "image_sizes": image_sizes,
93
+ }
94
+
95
+ thread = Thread(
96
+ target=model.generate,
97
+ kwargs=dict(
98
+ inputs=input_ids,
99
+ streamer=streamer,
100
+ **gen_kwargs,
101
+ ),
102
+ )
103
+ thread.start()
104
+
105
+ generated_text = ""
106
+ for new_text in streamer:
107
+ generated_text += new_text
108
+ sys.stdout.write(new_text)
109
+ sys.stdout.flush()
110
+
111
+ print("\nFinal output:", generated_text)
之前的代码版本/第一版-全部代码/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/playground/2d_hist.py ADDED
@@ -0,0 +1,132 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import os
3
+ from PIL import Image
4
+ from tqdm import tqdm
5
+ import matplotlib.pyplot as plt
6
+ import numpy as np
7
+ from multiprocessing import Pool
8
+ import functools
9
+ import argparse
10
+
11
+
12
+ def load_data(json_path):
13
+ with open(json_path, "r") as f:
14
+ return json.load(f)
15
+
16
+
17
+ def filter_data(data):
18
+ filtered_data = [item for item in data if "image" in item]
19
+ return filtered_data
20
+
21
+
22
+ def calculate_image_dimension(image_path, images_folder):
23
+ full_path = os.path.join(images_folder, image_path)
24
+ try:
25
+ with Image.open(full_path) as img:
26
+ width, height = img.size
27
+ return width, height
28
+ except Exception as e:
29
+ print(f"Error opening {full_path}: {e}")
30
+ return None, None
31
+
32
+
33
+ def calculate_image_dimensions_multiprocess(filtered_data, images_folder, num_processes=256):
34
+ image_paths = []
35
+ for item in filtered_data:
36
+ if isinstance(item["image"], list):
37
+ image_paths.extend(item["image"])
38
+ else:
39
+ image_paths.append(item["image"])
40
+
41
+ with Pool(num_processes) as p:
42
+ dimensions = list(
43
+ tqdm(
44
+ p.imap(functools.partial(calculate_image_dimension, images_folder=images_folder), image_paths),
45
+ total=len(image_paths),
46
+ desc="Calculating image dimensions",
47
+ )
48
+ )
49
+ widths, heights = zip(*[dim for dim in dimensions if dim[0] is not None])
50
+ return list(widths), list(heights)
51
+
52
+
53
+ def tokenize(text):
54
+ return text.split()
55
+
56
+
57
+ def calculate_tokenized_lengths(data):
58
+ lengths = []
59
+ for item in tqdm(data, desc="Tokenizing conversations"):
60
+ for conversation in item["conversations"]:
61
+ tokenized_value = tokenize(conversation["value"])
62
+ lengths.append(len(tokenized_value))
63
+ return lengths
64
+
65
+
66
+ def main():
67
+ parser = argparse.ArgumentParser(description="Process data for LLaVA_Next project.")
68
+ parser.add_argument(
69
+ "--json_path",
70
+ type=str,
71
+ help="Path to the JSON file containing data.",
72
+ default="/mnt/bn/vl-research/data/llava_instruct/real_vision_flan/llava_ofa_DEMON-FULL.json",
73
+ )
74
+ parser.add_argument(
75
+ "--images_folder",
76
+ type=str,
77
+ default="/mnt/bn/vl-research/data/llava_data",
78
+ help="Path to the folder containing images.",
79
+ )
80
+ args = parser.parse_args()
81
+
82
+ llava_instruct_name = os.path.basename(args.json_path).replace(".json", "")
83
+ images_folder = args.images_folder
84
+
85
+ data = load_data(args.json_path)
86
+ filtered_data = filter_data(data)
87
+
88
+ print(f"Total data items: {len(data)}, Filtered data items: {len(filtered_data)}")
89
+ widths, heights = calculate_image_dimensions_multiprocess(filtered_data, images_folder)
90
+ max_width, max_height = max(widths), max(heights)
91
+ print(f"Max width: {max_width}, Max height: {max_height}")
92
+
93
+ tokenized_lengths = calculate_tokenized_lengths(filtered_data)
94
+
95
+ fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(24, 12))
96
+
97
+ # Plot 2D histogram
98
+ widths_bins = [min(widths), max(widths) + 1] if min(widths) == max(widths) else np.arange(min(widths), max(widths) + 100, 100)
99
+ heights_bins = [min(heights), max(heights) + 1] if min(heights) == max(heights) else np.arange(min(heights), max(heights) + 100, 100)
100
+
101
+ h, xedges, yedges, image = ax1.hist2d(widths, heights, bins=[widths_bins, heights_bins], cmap=plt.cm.jet, density=True)
102
+ fig.colorbar(image, ax=ax1)
103
+ ax1.set_xlabel("Width")
104
+ ax1.set_ylabel("Height")
105
+ ax1.set_title(
106
+ f"dist_{llava_instruct_name}_2d_w_h\nMax width: {max(widths)}, Max height: {max(heights)}",
107
+ fontsize=10,
108
+ )
109
+
110
+ # Plot histogram
111
+ hist, bin_edges = np.histogram(tokenized_lengths, bins=np.arange(0, max(tokenized_lengths) + 10, 10))
112
+ bins = np.arange(0, max(tokenized_lengths) + 10, 10)
113
+ ax2.bar(bin_edges[:-1], hist, width=7, edgecolor="black", log=True)
114
+
115
+ # Display every nth label on the x-axis
116
+ n = 8 # Adjust this value to control the number of labels displayed
117
+ ticks = bins[::n]
118
+ tick_labels = [int(tick) for tick in ticks]
119
+ ax2.set_xticks(ticks)
120
+ ax2.set_xticklabels(tick_labels, rotation=90, fontsize=8)
121
+
122
+ ax2.set_xlim(min(bin_edges), max(bin_edges))
123
+ ax2.set_xlabel("Tokenized Length")
124
+ ax2.set_ylabel("Count (log scale)")
125
+ ax2.set_title(f"dist_{llava_instruct_name}_tokenized_length", fontsize=8)
126
+
127
+ plt.tight_layout()
128
+ plt.savefig(f"./dist_{llava_instruct_name}_combined.png")
129
+
130
+
131
+ if __name__ == "__main__":
132
+ main()
之前的代码版本/第一版-全部代码/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/playground/data_checker.py ADDED
@@ -0,0 +1,364 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import os
3
+ from tqdm import tqdm
4
+ from multiprocessing import Pool, cpu_count
5
+ import yaml
6
+
7
+
8
+ class DataProcessor:
9
+ def __init__(self, file_path, image_root, video_root):
10
+ self.file_path = file_path
11
+ self.image_root = image_root
12
+ self.data = None
13
+ self.video_root = video_root
14
+ self.load_data()
15
+
16
+ def load_data(self):
17
+ if self.file_path.endswith(".json"):
18
+ with open(self.file_path, "r") as f:
19
+ self.data = json.load(f)
20
+ elif self.file_path.endswith(".yaml"):
21
+ with open(self.file_path, "r") as f:
22
+ self.data = yaml.safe_load(f)
23
+ elif self.file_path.endswith(".jsonl"):
24
+ with open(self.file_path, "r") as f:
25
+ self.data = [json.loads(line) for line in f.readlines()]
26
+ else:
27
+ raise ValueError("Unsupported file format")
28
+
29
+ def load_json_data(self, json_path):
30
+ if json_path.endswith(".jsonl"):
31
+ cur_data_dict = []
32
+ with open(json_path, "r") as json_file:
33
+ for line in json_file:
34
+ cur_data_dict.append(json.loads(line.strip()))
35
+ return cur_data_dict
36
+ elif json_path.endswith(".json"):
37
+ with open(json_path, "r") as f:
38
+ return json.load(f)
39
+ else:
40
+ raise ValueError("Unsupported file format")
41
+
42
+ def check_image_existence(self, data):
43
+ if "image" in data:
44
+ if type(data["image"]) == list:
45
+ images = data["image"]
46
+ else:
47
+ images = [data["image"]]
48
+
49
+ for image in images:
50
+ full_image_path = os.path.join(self.image_root, image)
51
+ if not os.path.exists(full_image_path):
52
+ print(f"WARNING!!! {full_image_path} not exists !!!")
53
+
54
+ if "video" in data:
55
+ full_video_path = os.path.join(self.video_root, data["video"])
56
+ if not os.path.exists(full_video_path):
57
+ print(f"WARNING!!! {full_video_path} not exists !!!")
58
+
59
+ # if data["conversations"][0]["value"].count("<image>") > 1:
60
+ # print(f"WARNING!!! {data['conversations'][0]['value']} has more than one <image> !!!")
61
+
62
+ def check_item_structure(self, item):
63
+ if not all(key in item for key in ["conversations"]):
64
+ print(f"WARNING!!! Item {item.get('id', 'unknown')} is missing required fields!")
65
+ return False
66
+
67
+ conversations = item["conversations"]
68
+ if not isinstance(conversations, list) or len(conversations) < 2 or len(conversations) % 2 != 0:
69
+ print(f"WARNING!!! Item {item['id']} has invalid conversations structure!")
70
+ return False
71
+
72
+ for i, conv in enumerate(conversations):
73
+ if not all(key in conv for key in ["from", "value"]):
74
+ print(f"WARNING!!! Item {item['id']} has invalid conversation format!")
75
+ return False
76
+
77
+ expected_from = "human" if i % 2 == 0 else "gpt"
78
+ if conv["from"] != expected_from:
79
+ print(f"WARNING!!! Item {item['id']} has incorrect conversation order!")
80
+ return False
81
+
82
+ return True
83
+
84
+ def check_image_and_structure(self, item):
85
+ if not self.check_item_structure(item):
86
+ return
87
+
88
+ # self.check_image_existence(item)
89
+
90
+ def process_images(self):
91
+ if isinstance(self.data, list):
92
+ args = [d for d in self.data]
93
+ with Pool(processes=cpu_count()) as pool:
94
+ list(tqdm(pool.imap(self.check_image_and_structure, args), total=len(self.data)))
95
+ elif isinstance(self.data, dict):
96
+ for d in self.data["datasets"]:
97
+ dd_json_path = d["json_path"]
98
+ data = self.load_json_data(dd_json_path)
99
+ args = [d for d in data]
100
+ with Pool(processes=cpu_count()) as pool:
101
+ list(tqdm(pool.imap(self.check_image_and_structure, args), total=len(data), desc=f"Processing {dd_json_path}"))
102
+
103
+ def count_items(self):
104
+ if isinstance(self.data, list): # Assuming JSON data loaded directly
105
+ return len(self.data)
106
+ elif isinstance(self.data, dict): # Assuming YAML data loaded
107
+ total_items_count = 0
108
+ for d in self.data["datasets"]:
109
+ dd_json_path = d["json_path"]
110
+ data = self.load_json_data(dd_json_path)
111
+ current_items_count = len(data)
112
+
113
+ sampling_strategy = d["sampling_strategy"]
114
+ try:
115
+ if sampling_strategy != "all":
116
+ percentage = float(sampling_strategy.split(":")[-1].replace("%", "")) / 100.0
117
+ else:
118
+ percentage = 1.0
119
+ except Exception as e:
120
+ print(f"Error: {e}")
121
+ percentage = 1.0
122
+
123
+ sampling_count = int(current_items_count * percentage)
124
+ total_items_count += sampling_count
125
+ print(f"{dd_json_path}: {sampling_count}")
126
+ return total_items_count
127
+
128
+ def stat_data(self):
129
+ if isinstance(self.data, dict):
130
+ cur_lens_list = []
131
+ single_image_count = 0
132
+ multiple_image_count = 0
133
+ video_count = 0
134
+ total_count = 0
135
+ text_count = 0
136
+ max_tokens_item = None
137
+ max_tokens = 0
138
+
139
+ for d in self.data["datasets"]:
140
+ dd_json_path = d["json_path"]
141
+ data = self.load_json_data(dd_json_path)
142
+ sampling_strategy = d["sampling_strategy"]
143
+
144
+ try:
145
+ if sampling_strategy != "all":
146
+ percentage = float(sampling_strategy.split(":")[-1].replace("%", "")) / 100.0
147
+ else:
148
+ percentage = 1.0
149
+ except Exception as e:
150
+ print(f"Error parsing sampling strategy: {e}")
151
+ percentage = 1.0
152
+
153
+ sampled_count = int(len(data) * percentage)
154
+ print(f"{dd_json_path}: {sampled_count} (sampled from {len(data)})")
155
+
156
+ for item in data[:sampled_count]:
157
+ conversations = item["conversations"]
158
+ cur_len = sum([len(conv["value"].split()) for conv in conversations])
159
+ cur_lens_list.append(cur_len)
160
+
161
+ if cur_len > max_tokens:
162
+ max_tokens = cur_len
163
+ max_tokens_item = item
164
+
165
+ total_count += 1
166
+ if "image" in item:
167
+ if isinstance(item["image"], list):
168
+ if len(item["image"]) > 1:
169
+ multiple_image_count += 1
170
+ else:
171
+ single_image_count += 1
172
+ else:
173
+ single_image_count += 1
174
+ elif "video" in item:
175
+ video_count += 1
176
+ else:
177
+ text_count += 1
178
+
179
+ print(f"Max length: {max(cur_lens_list)}, Min length: {min(cur_lens_list)}, Average length: {sum(cur_lens_list) / len(cur_lens_list)}")
180
+ print(f"Total items: {total_count}")
181
+ print(f"Text items: {text_count} ({text_count/total_count*100:.2f}%)")
182
+ print(f"Single image items: {single_image_count} ({single_image_count/total_count*100:.2f}%)")
183
+ print(f"Multiple image items: {multiple_image_count} ({multiple_image_count/total_count*100:.2f}%)")
184
+ print(f"Video items: {video_count} ({video_count/total_count*100:.2f}%)")
185
+
186
+ print("\nItem with the largest number of tokens:")
187
+ print(f"Token count: {max_tokens}")
188
+ print("Item content:")
189
+ print(json.dumps(max_tokens_item, indent=2))
190
+
191
+ def filter_data(self):
192
+ if isinstance(self.data, dict):
193
+ for d in self.data["datasets"]:
194
+ dd_json_path = d["json_path"]
195
+ print(f"Processing {dd_json_path}")
196
+ data = self.load_json_data(dd_json_path)
197
+
198
+ filtered_data = []
199
+ mismatch_data = []
200
+ mismatch_flag = False
201
+ for item in data:
202
+ try:
203
+ if "image" in item:
204
+ num_image = len(item["image"]) if isinstance(item["image"], list) else 1
205
+ else:
206
+ num_image = 0
207
+
208
+ if "video" in item:
209
+ num_video = len(item["video"]) if isinstance(item["video"], list) else 1
210
+ else:
211
+ num_video = 0
212
+
213
+ num_visuals = num_image + num_video
214
+ conv_text = ""
215
+ for conv in item["conversations"]:
216
+ conv_text += conv["value"]
217
+
218
+ num_img_token_appearance = conv_text.count("<image>")
219
+ if len(conv_text) == 0:
220
+ print(f"Conversation text is empty for {item}")
221
+
222
+ if num_img_token_appearance == num_visuals or num_img_token_appearance < num_visuals and len(conv_text) > 0:
223
+ filtered_data.append(item)
224
+ elif num_img_token_appearance > num_visuals:
225
+ item["num_img_token_appearance"] = num_img_token_appearance
226
+ item["num_visuals"] = num_visuals
227
+ mismatch_data.append(item)
228
+
229
+ if not mismatch_flag:
230
+ print(f"Data mismatch for {item}")
231
+
232
+ mismatch_flag = True
233
+ except Exception as e:
234
+ print(f"Error: {e}")
235
+ print()
236
+
237
+ if mismatch_flag:
238
+ print(f"Data mismatch for {dd_json_path}")
239
+
240
+ if len(filtered_data) < len(data):
241
+ saving_dd_json_path = dd_json_path.replace(".jsonl", f"fltd_{len(filtered_data)}.json").replace(".json", f"fltd_{len(filtered_data)}.json")
242
+ with open(saving_dd_json_path, "w") as f:
243
+ json.dump(filtered_data, f, indent=2)
244
+ print(f"Filtered data count: {len(filtered_data)}")
245
+ else:
246
+ pass
247
+
248
+ def stat_and_filter_data(self, threshold):
249
+ if isinstance(self.data, dict):
250
+ cur_lens_list = []
251
+ single_image_count = 0
252
+ multiple_image_count = 0
253
+ video_count = 0
254
+ total_count = 0
255
+ text_count = 0
256
+
257
+ for d in self.data["datasets"]:
258
+ dd_json_path = d["json_path"]
259
+ data = self.load_json_data(dd_json_path)
260
+ sampling_strategy = d["sampling_strategy"]
261
+ filtered_data = []
262
+
263
+ try:
264
+ if sampling_strategy != "all":
265
+ percentage = float(sampling_strategy.split(":")[-1].replace("%", "")) / 100.0
266
+ else:
267
+ percentage = 1.0
268
+ except Exception as e:
269
+ print(f"Error parsing sampling strategy: {e}")
270
+ percentage = 1.0
271
+
272
+ sampled_count = int(len(data) * percentage)
273
+ print(f"{dd_json_path}: {sampled_count} (sampled from {len(data)})")
274
+
275
+ save_flag = False
276
+ for item in data:
277
+ total_count += 1
278
+ conversations = item["conversations"]
279
+ filtered_conversations = []
280
+ current_token_count = 0
281
+
282
+ for i in range(0, len(conversations), 2):
283
+ if i + 1 < len(conversations):
284
+ human_conv = conversations[i]
285
+ gpt_conv = conversations[i + 1]
286
+ pair_tokens = len(human_conv["value"].split()) + len(gpt_conv["value"].split())
287
+
288
+ if current_token_count + pair_tokens <= threshold:
289
+ filtered_conversations.extend([human_conv, gpt_conv])
290
+ current_token_count += pair_tokens
291
+ else:
292
+ save_flag = True
293
+ break
294
+
295
+ if filtered_conversations:
296
+ item["conversations"] = filtered_conversations
297
+ cur_len = sum([len(conv["value"].split()) for conv in filtered_conversations])
298
+ cur_lens_list.append(cur_len)
299
+ filtered_data.append(item)
300
+
301
+ if "image" in item:
302
+ if isinstance(item["image"], list):
303
+ if len(item["image"]) > 1:
304
+ multiple_image_count += 1
305
+ else:
306
+ single_image_count += 1
307
+ else:
308
+ single_image_count += 1
309
+ elif "video" in item:
310
+ video_count += 1
311
+ else:
312
+ text_count += 1
313
+
314
+ # Save filtered data for each dataset
315
+ if filtered_data and save_flag:
316
+ if dd_json_path.endswith(".jsonl"):
317
+ output_file = dd_json_path.replace(".jsonl", f"_filtered_{threshold}tokens_{len(filtered_data)}.jsonl")
318
+ with open(output_file, "w") as f:
319
+ for item in filtered_data:
320
+ f.write(json.dumps(item) + "\n")
321
+ else:
322
+ output_file = dd_json_path.replace(".json", f"_filtered_{threshold}tokens_{len(filtered_data)}.json")
323
+ with open(output_file, "w") as f:
324
+ json.dump(filtered_data, f, indent=2)
325
+ print(f"Filtered data for {dd_json_path} saved to: {output_file}")
326
+
327
+ print(f"Max length: {max(cur_lens_list)}, Min length: {min(cur_lens_list)}, Average length: {sum(cur_lens_list) / len(cur_lens_list)}")
328
+ print(f"Total items: {total_count}")
329
+ print(f"Text items: {text_count} ({text_count/total_count*100:.2f}%)")
330
+ print(f"Single image items: {single_image_count} ({single_image_count/total_count*100:.2f}%)")
331
+ print(f"Multiple image items: {multiple_image_count} ({multiple_image_count/total_count*100:.2f}%)")
332
+ print(f"Video items: {video_count} ({video_count/total_count*100:.2f}%)")
333
+
334
+
335
+ def main(file_path, image_root, operation, video_root, threshold=None):
336
+ processor = DataProcessor(file_path, image_root, video_root)
337
+ if operation == "check":
338
+ processor.process_images()
339
+ elif operation == "count":
340
+ total_items = processor.count_items()
341
+ print(f"Total items: {total_items}")
342
+ elif operation == "filter":
343
+ processor.filter_data()
344
+ elif operation == "stat":
345
+ processor.stat_data()
346
+ elif operation == "stat_and_filter":
347
+ if threshold is None:
348
+ raise ValueError("Threshold must be provided for stat_and_filter operation")
349
+ processor.stat_and_filter_data(threshold)
350
+ else:
351
+ raise ValueError("Unsupported operation")
352
+
353
+
354
+ if __name__ == "__main__":
355
+ import argparse
356
+
357
+ parser = argparse.ArgumentParser()
358
+ parser.add_argument("--file_path", type=str, default="/mnt/bn/vl-research/workspace/boli01/projects/LLaVA_Next/scripts/i18n/scale_llms/next_continual.yaml")
359
+ parser.add_argument("--image_root", type=str, default="/mnt/bn/vl-research/data/llava_data")
360
+ parser.add_argument("--video_root", type=str, default="/mnt/bn/vl-research/data/llava_video")
361
+ parser.add_argument("--operation", type=str, default="filter")
362
+ parser.add_argument("--threshold", type=int, default=None, help="Threshold for stat_and_filter operation")
363
+ args = parser.parse_args()
364
+ main(args.file_path, args.image_root, args.operation, args.video_root, args.threshold)
之前的代码版本/第一版-全部代码/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/playground/demo/video_demo.py ADDED
@@ -0,0 +1,335 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import torch
3
+
4
+ from llava.constants import IMAGE_TOKEN_INDEX, DEFAULT_IMAGE_TOKEN, DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN
5
+ from llava.conversation import conv_templates, SeparatorStyle
6
+ from llava.model.builder import load_pretrained_model
7
+ from llava.utils import disable_torch_init
8
+ from llava.mm_utils import process_anyres_image,tokenizer_image_token, get_model_name_from_path, KeywordsStoppingCriteria
9
+
10
+ import json
11
+ import os
12
+ import math
13
+ from tqdm import tqdm
14
+ from decord import VideoReader, cpu
15
+
16
+ from transformers import AutoConfig
17
+
18
+ import cv2
19
+ import base64
20
+ import openai
21
+
22
+ from PIL import Image
23
+
24
+
25
+
26
+ import numpy as np
27
+
28
+ def split_list(lst, n):
29
+ """Split a list into n (roughly) equal-sized chunks"""
30
+ chunk_size = math.ceil(len(lst) / n) # integer division
31
+ return [lst[i : i + chunk_size] for i in range(0, len(lst), chunk_size)]
32
+
33
+
34
+ def get_chunk(lst, n, k):
35
+ chunks = split_list(lst, n)
36
+ return chunks[k]
37
+
38
+
39
+ def parse_args():
40
+ """
41
+ Parse command-line arguments.
42
+ """
43
+ parser = argparse.ArgumentParser()
44
+
45
+ # Define the command-line arguments
46
+ parser.add_argument("--video_path", help="Path to the video files.", required=True)
47
+ parser.add_argument("--output_dir", help="Directory to save the model results JSON.", required=True)
48
+ parser.add_argument("--output_name", help="Name of the file for storing results JSON.", required=True)
49
+ parser.add_argument("--model-path", type=str, default="facebook/opt-350m")
50
+ parser.add_argument("--model-base", type=str, default=None)
51
+ parser.add_argument("--conv-mode", type=str, default=None)
52
+ parser.add_argument("--chunk-idx", type=int, default=0)
53
+ parser.add_argument("--mm_resampler_type", type=str, default="spatial_pool")
54
+ parser.add_argument("--mm_spatial_pool_stride", type=int, default=4)
55
+ parser.add_argument("--mm_spatial_pool_out_channels", type=int, default=1024)
56
+ parser.add_argument("--mm_spatial_pool_mode", type=str, default="average")
57
+ parser.add_argument("--image_aspect_ratio", type=str, default="anyres")
58
+ parser.add_argument("--image_grid_pinpoints", type=str, default="[(224, 448), (224, 672), (224, 896), (448, 448), (448, 224), (672, 224), (896, 224)]")
59
+ parser.add_argument("--mm_patch_merge_type", type=str, default="spatial_unpad")
60
+ parser.add_argument("--overwrite", type=lambda x: (str(x).lower() == 'true'), default=True)
61
+ parser.add_argument("--for_get_frames_num", type=int, default=4)
62
+ parser.add_argument("--load_8bit", type=lambda x: (str(x).lower() == 'true'), default=False)
63
+ parser.add_argument("--prompt", type=str, default=None)
64
+ parser.add_argument("--api_key", type=str, help="OpenAI API key")
65
+ parser.add_argument("--mm_newline_position", type=str, default="no_token")
66
+ parser.add_argument("--force_sample", type=lambda x: (str(x).lower() == 'true'), default=False)
67
+ parser.add_argument("--add_time_instruction", type=str, default=False)
68
+ return parser.parse_args()
69
+
70
+ def load_video(video_path,args):
71
+ if args.for_get_frames_num == 0:
72
+ return np.zeros((1, 336, 336, 3))
73
+ vr = VideoReader(video_path, ctx=cpu(0),num_threads=1)
74
+ total_frame_num = len(vr)
75
+ video_time = total_frame_num / vr.get_avg_fps()
76
+ fps = round(vr.get_avg_fps())
77
+ frame_idx = [i for i in range(0, len(vr), fps)]
78
+ frame_time = [i/fps for i in frame_idx]
79
+ if len(frame_idx) > args.for_get_frames_num or args.force_sample:
80
+ sample_fps = args.for_get_frames_num
81
+ uniform_sampled_frames = np.linspace(0, total_frame_num - 1, sample_fps, dtype=int)
82
+ frame_idx = uniform_sampled_frames.tolist()
83
+ frame_time = [i/vr.get_avg_fps() for i in frame_idx]
84
+ frame_time = ",".join([f"{i:.2f}s" for i in frame_time])
85
+ spare_frames = vr.get_batch(frame_idx).asnumpy()
86
+ # import pdb;pdb.set_trace()
87
+
88
+ return spare_frames,frame_time,video_time
89
+
90
+
91
+
92
+
93
+ def load_video_base64(path):
94
+ video = cv2.VideoCapture(path)
95
+
96
+ base64Frames = []
97
+ while video.isOpened():
98
+ success, frame = video.read()
99
+ if not success:
100
+ break
101
+ _, buffer = cv2.imencode(".jpg", frame)
102
+ base64Frames.append(base64.b64encode(buffer).decode("utf-8"))
103
+
104
+ video.release()
105
+ # print(len(base64Frames), "frames read.")
106
+ return base64Frames
107
+
108
+
109
+ def run_inference(args):
110
+ """
111
+ Run inference on ActivityNet QA DataSet using the Video-ChatGPT model.
112
+
113
+ Args:
114
+ args: Command-line arguments.
115
+ """
116
+ # Initialize the model
117
+ if "gpt4v" != args.model_path:
118
+ model_name = get_model_name_from_path(args.model_path)
119
+ # Set model configuration parameters if they exist
120
+ if args.overwrite == True:
121
+ overwrite_config = {}
122
+ overwrite_config["mm_spatial_pool_mode"] = args.mm_spatial_pool_mode
123
+ overwrite_config["mm_spatial_pool_stride"] = args.mm_spatial_pool_stride
124
+ overwrite_config["mm_newline_position"] = args.mm_newline_position
125
+
126
+ cfg_pretrained = AutoConfig.from_pretrained(args.model_path)
127
+
128
+ # import pdb;pdb.set_trace()
129
+ if "qwen" not in args.model_path.lower():
130
+ if "224" in cfg_pretrained.mm_vision_tower:
131
+ # suppose the length of text tokens is around 1000, from bo's report
132
+ least_token_number = args.for_get_frames_num*(16//args.mm_spatial_pool_stride)**2 + 1000
133
+ else:
134
+ least_token_number = args.for_get_frames_num*(24//args.mm_spatial_pool_stride)**2 + 1000
135
+
136
+ scaling_factor = math.ceil(least_token_number/4096)
137
+ if scaling_factor >= 2:
138
+ if "vicuna" in cfg_pretrained._name_or_path.lower():
139
+ print(float(scaling_factor))
140
+ overwrite_config["rope_scaling"] = {"factor": float(scaling_factor), "type": "linear"}
141
+ overwrite_config["max_sequence_length"] = 4096 * scaling_factor
142
+ overwrite_config["tokenizer_model_max_length"] = 4096 * scaling_factor
143
+
144
+ tokenizer, model, image_processor, context_len = load_pretrained_model(args.model_path, args.model_base, model_name, load_8bit=args.load_8bit, overwrite_config=overwrite_config)
145
+ else:
146
+ tokenizer, model, image_processor, context_len = load_pretrained_model(args.model_path, args.model_base, model_name)
147
+ else:
148
+ pass
149
+
150
+ # import pdb;pdb.set_trace()
151
+ if getattr(model.config, "force_sample", None) is not None:
152
+ args.force_sample = model.config.force_sample
153
+ else:
154
+ args.force_sample = False
155
+
156
+ # import pdb;pdb.set_trace()
157
+
158
+ if getattr(model.config, "add_time_instruction", None) is not None:
159
+ args.add_time_instruction = model.config.add_time_instruction
160
+ else:
161
+ args.add_time_instruction = False
162
+
163
+ # Create the output directory if it doesn't exist
164
+ if not os.path.exists(args.output_dir):
165
+ os.makedirs(args.output_dir)
166
+
167
+ output_name = args.output_name
168
+ answers_file = os.path.join(args.output_dir, f"{output_name}.json")
169
+ ans_file = open(answers_file, "w")
170
+
171
+ video_path = args.video_path
172
+
173
+ all_video_pathes = []
174
+
175
+ # Check if the video_path is a directory or a file
176
+ if os.path.isdir(video_path):
177
+ # If it's a directory, loop over all files in the directory
178
+ for filename in os.listdir(video_path):
179
+ # Load the video file
180
+ cur_video_path = os.path.join(video_path, f"{filename}")
181
+ all_video_pathes.append(os.path.join(video_path, cur_video_path))
182
+ else:
183
+ # If it's a file, just process the video
184
+ all_video_pathes.append(video_path)
185
+
186
+ # import pdb;pdb.set_trace()
187
+ for video_path in all_video_pathes:
188
+
189
+ sample_set = {}
190
+ question = args.prompt
191
+ sample_set["Q"] = question
192
+ sample_set["video_name"] = video_path
193
+
194
+
195
+ # Check if the video exists
196
+ if os.path.exists(video_path):
197
+ if "gpt4v" != args.model_path:
198
+ video,frame_time,video_time = load_video(video_path, args)
199
+ video = image_processor.preprocess(video, return_tensors="pt")["pixel_values"].half().cuda()
200
+ video = [video]
201
+ else:
202
+ spare_frames,frame_time,video_time = load_video_base64(video_path)
203
+ interval = int(len(video) / args.for_get_frames_num)
204
+
205
+ # try:
206
+ # Run inference on the video and add the output to the list
207
+ if "gpt4v" != args.model_path:
208
+ qs = question
209
+ if args.add_time_instruction:
210
+ time_instruciton = f"The video lasts for {video_time:.2f} seconds, and {len(video[0])} frames are uniformly sampled from it. These frames are located at {frame_time}.Please answer the following questions related to this video."
211
+ qs = f'{time_instruciton}\n{qs}'
212
+ if model.config.mm_use_im_start_end:
213
+ qs = DEFAULT_IM_START_TOKEN + DEFAULT_IMAGE_TOKEN + DEFAULT_IM_END_TOKEN + "\n" + qs
214
+ else:
215
+ qs = DEFAULT_IMAGE_TOKEN + "\n" + qs
216
+
217
+ conv = conv_templates[args.conv_mode].copy()
218
+ conv.append_message(conv.roles[0], qs)
219
+ conv.append_message(conv.roles[1], None)
220
+ prompt = conv.get_prompt()
221
+
222
+ input_ids = tokenizer_image_token(prompt, tokenizer, IMAGE_TOKEN_INDEX, return_tensors="pt").unsqueeze(0).cuda()
223
+ if tokenizer.pad_token_id is None:
224
+ if "qwen" in tokenizer.name_or_path.lower():
225
+ print("Setting pad token to bos token for qwen model.")
226
+ tokenizer.pad_token_id = 151643
227
+
228
+ attention_masks = input_ids.ne(tokenizer.pad_token_id).long().cuda()
229
+
230
+ stop_str = conv.sep if conv.sep_style != SeparatorStyle.TWO else conv.sep2
231
+ keywords = [stop_str]
232
+ stopping_criteria = KeywordsStoppingCriteria(keywords, tokenizer, input_ids)
233
+
234
+ cur_prompt = question
235
+ else:
236
+ prompt = question
237
+
238
+ system_error = ""
239
+
240
+ if "gpt4v" != args.model_path:
241
+
242
+
243
+ with torch.inference_mode():
244
+ # model.update_prompt([[cur_prompt]])
245
+ # import pdb;pdb.set_trace()
246
+ # output_ids = model.generate(inputs=input_ids, images=video, attention_mask=attention_masks, modalities="video", do_sample=True, temperature=0.2, max_new_tokens=1024, use_cache=True, stopping_criteria=[stopping_criteria])
247
+ if "mistral" not in cfg_pretrained._name_or_path.lower():
248
+ output_ids = model.generate(inputs=input_ids, images=video, attention_mask=attention_masks, modalities="video", do_sample=False, temperature=0.0, max_new_tokens=1024, top_p=0.1,num_beams=1,use_cache=True, stopping_criteria=[stopping_criteria])
249
+ # output_ids = model.generate(inputs=input_ids, images=video, attention_mask=attention_masks, modalities="video", do_sample=True, temperature=0.2, max_new_tokens=1024, use_cache=True, stopping_criteria=[stopping_criteria])
250
+ else:
251
+ output_ids = model.generate(inputs=input_ids, images=video, attention_mask=attention_masks, modalities="video", do_sample=False, temperature=0.0, max_new_tokens=1024, top_p=0.1, num_beams=1, use_cache=True)
252
+ # output_ids = model.generate(inputs=input_ids, images=video, attention_mask=attention_masks, modalities="video", do_sample=True, temperature=0.2, max_new_tokens=1024, use_cache=True)
253
+ else:
254
+ openai.api_key = args.api_key # Your API key here
255
+
256
+ max_num_retries = 0
257
+ retry = 5
258
+ PROMPT_MESSAGES = [
259
+ {
260
+ "role": "user",
261
+ "content": [
262
+ f"These are frames from a video that I want to upload. Answer me one question of this video: {prompt}",
263
+ *map(lambda x: {"image": x, "resize": 336}, video[0::interval]),
264
+ ],
265
+ },
266
+ ]
267
+ params = {
268
+ "model": "gpt-4-vision-preview", #gpt-4-1106-vision-preview
269
+ "messages": PROMPT_MESSAGES,
270
+ "max_tokens": 1024,
271
+ }
272
+ sucess_flag=False
273
+ while max_num_retries < retry:
274
+ try:
275
+ result = openai.ChatCompletion.create(**params)
276
+ outputs = result.choices[0].message.content
277
+ sucess_flag = True
278
+ break
279
+ except Exception as inst :
280
+ if 'error' in dir(inst):
281
+ # import pdb;pdb.set_trace()
282
+ if inst.error.code == 'rate_limit_exceeded':
283
+ if "TPM" in inst.error.message:
284
+ time.sleep(30)
285
+ continue
286
+ else:
287
+ import pdb;pdb.set_trace()
288
+ elif inst.error.code == 'insufficient_quota':
289
+ print(f'insufficient_quota key')
290
+ exit()
291
+ elif inst.error.code == 'content_policy_violation':
292
+ print(f'content_policy_violation')
293
+ system_error = "content_policy_violation"
294
+
295
+ break
296
+ print('Find error message in response: ',str(inst.error.message), 'error code: ', str(inst.error.code))
297
+
298
+ continue
299
+ if not sucess_flag:
300
+ print(f'Calling OpenAI failed after retrying for {max_num_retries} times. Check the logs for details.')
301
+ exit()
302
+
303
+ if "gpt4v" != args.model_path:
304
+ outputs = tokenizer.batch_decode(output_ids, skip_special_tokens=True)[0].strip()
305
+ else:
306
+ print(len(video[0::interval]))
307
+
308
+ print(f"Question: {prompt}\n")
309
+ print(f"Response: {outputs}\n")
310
+
311
+ if "gpt4v" == args.model_path:
312
+ if system_error == 'content_policy_violation':
313
+ continue
314
+ elif system_error == "":
315
+ continue
316
+ else:
317
+ import pdb;pdb.set_trace()
318
+
319
+ # import pdb;pdb.set_trace()
320
+ if "mistral" not in cfg_pretrained._name_or_path.lower():
321
+ if outputs.endswith(stop_str):
322
+ outputs = outputs[: -len(stop_str)]
323
+
324
+ outputs = outputs.strip()
325
+
326
+ sample_set["pred"] = outputs
327
+ ans_file.write(json.dumps(sample_set, ensure_ascii=False) + "\n")
328
+ ans_file.flush()
329
+
330
+ ans_file.close()
331
+
332
+
333
+ if __name__ == "__main__":
334
+ args = parse_args()
335
+ run_inference(args)
之前的代码版本/第一版-全部代码/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/playground/equal_splitter.py ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ from math import ceil
3
+
4
+
5
+ def split_json_file(input_file, n_splits):
6
+ # Read the JSON file
7
+ with open(input_file, "r") as file:
8
+ data = json.load(file)
9
+
10
+ # Calculate the size of each split
11
+ total_items = len(data)
12
+ items_per_split = ceil(total_items / n_splits)
13
+
14
+ # Split the data and save into separate files
15
+ for i in range(n_splits):
16
+ start_index = i * items_per_split
17
+ end_index = min((i + 1) * items_per_split, total_items)
18
+ split_data = data[start_index:end_index]
19
+
20
+ # Write the split data to a new JSON file
21
+ with open(f"{input_file.split('.')[0]}_split_{i}.json", "w") as split_file:
22
+ json.dump(split_data, split_file, indent=4)
23
+
24
+
25
+ def main():
26
+ import argparse
27
+
28
+ parser = argparse.ArgumentParser(description="Split a JSON file into multiple parts.")
29
+ parser.add_argument("--input_file", type=str, help="The JSON file to split")
30
+ parser.add_argument("--n_splits", type=int, help="The number of splits")
31
+
32
+ args = parser.parse_args()
33
+
34
+ split_json_file(args.input_file, args.n_splits)
35
+
36
+
37
+ if __name__ == "__main__":
38
+ main()
之前的代码版本/第一版-全部代码/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/playground/llava_ov_plot.ipynb ADDED
The diff for this file is too large to render. See raw diff
 
之前的代码版本/第一版-全部代码/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/playground/remove_mid_ckpt.py ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import shutil
3
+ import glob
4
+
5
+
6
+ def remove_checkpoints(directory, pattern):
7
+ # Walk through the directory
8
+ for root, dirs, files in os.walk(directory):
9
+ # Use glob to find paths matching the pattern
10
+ for file_path in glob.glob(os.path.join(root, pattern)):
11
+ # Check if it is a directory
12
+ if "llava-1.6-mistral-7b" in file_path:
13
+ continue
14
+ if os.path.isdir(file_path):
15
+ # Remove the directory
16
+ print(f"Removing {file_path}")
17
+ input("Press Enter to continue...")
18
+ shutil.rmtree(file_path)
19
+ print(f"Removed directory: {file_path}")
20
+ else:
21
+ print(f"Removing {file_path}")
22
+ input("Press Enter to continue...")
23
+ # Remove the file
24
+ os.remove(file_path)
25
+ print(f"Removed file: {file_path}")
26
+
27
+
28
+ # Directory containing the checkpoints
29
+ directory = "/mnt/bn/vl-research/checkpoints/feng/"
30
+
31
+ # Pattern to match in the file names
32
+ pattern = "global_step*"
33
+
34
+ # Call the function
35
+ remove_checkpoints(directory, pattern)
之前的代码版本/第一版-全部代码/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/playground/sgl_llava_inference_multinode.py ADDED
@@ -0,0 +1,125 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import json
3
+ import time
4
+ import os
5
+ import tqdm
6
+ import sglang as sgl
7
+ from sglang.test.test_utils import select_sglang_backend
8
+ from sglang.utils import dump_state_text
9
+
10
+
11
+ @sgl.function
12
+ def image_description(s, image_file):
13
+ prompt = "Please generate detailed descriptions of the given image."
14
+ s += sgl.user(sgl.image(image_file) + prompt)
15
+ s += sgl.assistant(sgl.gen("answer", max_tokens=1024, temperature=0.0))
16
+
17
+
18
+ def load_progress(progress_file):
19
+ print(f"Load progress from {progress_file}")
20
+ if os.path.exists(progress_file):
21
+ with open(progress_file, "r") as f:
22
+ return json.load(f)
23
+ return {"last_index": -1, "last_chunk": -1, "results": [], "annotations": []}
24
+
25
+
26
+ def save_progress(progress_file, progress_data):
27
+ with open(progress_file, "w") as f:
28
+ json.dump(progress_data, f, indent=2)
29
+
30
+
31
+ def find_images_in_subfolders(folder_path):
32
+ image_extensions = (".png", ".jpg", ".jpeg", ".gif", ".bmp")
33
+ image_files = []
34
+ for root, dirs, files in os.walk(folder_path):
35
+ for file in files:
36
+ if file.endswith(image_extensions):
37
+ image_files.append(os.path.join(root, file))
38
+ return image_files
39
+
40
+
41
+ def main(args):
42
+ dist_rank = args.dist
43
+ dist_size = args.total_dist
44
+
45
+ base_dir = os.path.dirname(args.result_file)
46
+ os.makedirs(base_dir, exist_ok=True) # Ensure the base directory exists
47
+ progress_file = f"{base_dir}/progress_{dist_rank}_or_{dist_size}.json"
48
+ progress_data = load_progress(progress_file)
49
+
50
+ with open(args.json_path, "r") as fp:
51
+ data = json.load(fp)
52
+
53
+ image_files = [os.path.join(args.images_root, item["image"]) for item in data]
54
+ image_files = image_files[: args.limit] if args.limit > 0 else image_files
55
+
56
+ # Shard the data
57
+ shard_size = len(image_files) // dist_size
58
+ start_index = shard_size * dist_rank
59
+ end_index = start_index + shard_size if dist_rank < dist_size - 1 else len(image_files)
60
+ shard_files = image_files[start_index:end_index]
61
+
62
+ print(f"Querying {len(shard_files)} images from index {start_index} to {end_index - 1}")
63
+
64
+ # Select backend
65
+ backend = select_sglang_backend(args)
66
+ sgl.set_default_backend(backend)
67
+
68
+ tic = time.time()
69
+ batch_size = args.parallel
70
+ for batch_start in tqdm.tqdm(range(0, len(shard_files), batch_size)):
71
+ batch_end = min(batch_start + batch_size, len(shard_files))
72
+ if batch_start <= progress_data.get("last_index", -1):
73
+ print(f"Skipping already processed batch starting at {batch_start}")
74
+ continue
75
+ batch_arguments = [{"image_file": image_file} for image_file in shard_files[batch_start:batch_end]]
76
+ try:
77
+ batch_states = image_description.run_batch(batch_arguments, temperature=0, num_threads=args.parallel, progress_bar=False)
78
+ for i, ret in enumerate(batch_states):
79
+ image_file = batch_arguments[i]["image_file"]
80
+ caption = ret.text().split("ASSISTANT:")[-1].strip()
81
+ progress_data["annotations"].append({"image_file": image_file, "caption": caption})
82
+ progress_data["last_index"] = batch_start + i # Update last_index relative to this rank's shard
83
+
84
+ save_progress(progress_file, progress_data)
85
+ except Exception as e:
86
+ print(f"Error during batch processing: {e}")
87
+ save_progress(progress_file, progress_data)
88
+ break
89
+
90
+ latency = time.time() - tic
91
+ print(f"Latency: {latency:.3f}")
92
+
93
+ value = {
94
+ "task": "image_captioning",
95
+ "backend": args.backend,
96
+ "num_gpus": 1,
97
+ "latency": round(latency, 3),
98
+ "num_requests": len(shard_files),
99
+ "parallel": args.parallel,
100
+ "results": progress_data["annotations"],
101
+ }
102
+
103
+ result_file = args.result_file.replace(".json", f"_shard_{dist_rank}_or_{dist_size}.json")
104
+ print(f"Write output to {result_file}")
105
+ with open(result_file, "w") as fout:
106
+ json.dump(value, fout, indent=2)
107
+
108
+ save_progress(progress_file, progress_data)
109
+
110
+
111
+ if __name__ == "__main__":
112
+ parser = argparse.ArgumentParser()
113
+ parser.add_argument("--images_root", type=str, default="/mnt/bn/vl-research/data/llava_data/cc3m")
114
+ parser.add_argument("--json_path", type=str, default="/mnt/bn/vl-research/data/llava_instruct/cc3m_recap_requery_363707.json")
115
+ parser.add_argument("--max_tokens", type=int, default=1024)
116
+ parser.add_argument("--parallel", type=int, default=32)
117
+ parser.add_argument("--backend", type=str, default="srt")
118
+ parser.add_argument("--host", type=str, default="http://127.0.0.1")
119
+ parser.add_argument("--port", type=int, default=30000)
120
+ parser.add_argument("--result_file", type=str, default="/mnt/bn/vl-research/workspace/boli01/projects/LLaVA_Next/playground/sgl_llava_inference.json")
121
+ parser.add_argument("--limit", type=int, default=-1)
122
+ parser.add_argument("--dist", type=int, default=0, help="The rank of the distributed machine")
123
+ parser.add_argument("--total_dist", type=int, default=6, help="Total number of distributed machines")
124
+ args = parser.parse_args()
125
+ main(args)
之前的代码版本/第一版-全部代码/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/playground/upload_data.py ADDED
@@ -0,0 +1,217 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from datasets import Dataset, Features, Value, ClassLabel, Sequence, Image
2
+ import json
3
+ import PIL.Image as pil_image
4
+ from io import BytesIO
5
+ from tqdm import tqdm
6
+
7
+ json_paths = [
8
+ # "/mnt/bn/vl-research/data/llava_instruct/real_vision_flan/mavis_math_metagen_87358.json",
9
+ # "/mnt/bn/vl-research/data/llava_instruct/real_vision_flan/mavis_math_rule_geo_100000.json",
10
+ # "/mnt/bn/vl-research/data/llava_instruct/real_vision_flan/k12_printing_train_256646.json",
11
+ # "/mnt/bn/vl-research/data/llava_instruct/real_vision_flan/iiit5k_annotations_2000.json",
12
+ # "/mnt/bn/vl-research/data/llava_instruct/real_vision_flan/hme100k_train_clean_74502.json",
13
+ # "/mnt/bn/vl-research/data/llava_instruct/real_vision_flan/ai2d_azuregpt_detailed_understanding_4874.json",
14
+ # "/mnt/bn/vl-research/data/llava_instruct/real_vision_flan/infographic_vqa_4404.json",
15
+ # "/mnt/bn/vl-research/data/llava_instruct/real_vision_flan/infographic_azuregpt4v_1992.json",
16
+ # "/mnt/bn/vl-research/data/llava_instruct/real_vision_flan/lrv_chart_1787.json",
17
+ # "/mnt/bn/vl-research/data/llava_instruct/real_vision_flan/lrv_normal_gpt4v_filtered_10500.json",
18
+ # "/mnt/bn/vl-research/data/llava_instruct/real_vision_flan/scienceqa_nona_context_19218.json",
19
+ # "/mnt/bn/vl-research/data/llava_instruct/real_vision_flan/allava_instruct_vflan4v_20000.json",
20
+ # "/mnt/bn/vl-research/data/llava_instruct/real_vision_flan/allava_instruct_laion4v_50000.json",
21
+ # "/mnt/bn/vl-research/data/llava_instruct/real_vision_flan/textocr_gpt4v_train_converted_25114.json",
22
+ # "/mnt/bn/vl-research/data/llava_instruct/real_vision_flan/ai2d_train_internvl_single_12413.json",
23
+ # "/mnt/bn/vl-research/data/llava_instruct/real_vision_flan/textcaps_train_21952.json",
24
+ # "/mnt/bn/vl-research/data/llava_instruct/ureader_new/ureader_qa_sft.json",
25
+ # "/mnt/bn/vl-research/data/llava_instruct/ureader_new/ureader_cap_sft.json",
26
+ # "/mnt/bn/vl-research/data/llava_instruct/ureader_new/ureader_ie_sft.json",
27
+ # "/mnt/bn/vl-research/data/llava_instruct/ureader_new/ureader_kg_sft.json",
28
+ # "/mnt/bn/vl-research/data/llava_instruct/real_vision_flan/vision_flan_filtered_186070.json",
29
+ # "/mnt/bn/vl-research/data/llava_instruct/real_vision_flan/mathqa_29837.json",
30
+ # "/mnt/bn/vl-research/data/llava_instruct/real_vision_flan/geo3k_2101.json",
31
+ # "/mnt/bn/vl-research/data/llava_instruct/real_vision_flan/geo170k_qa_converted_67833.json",
32
+ # "/mnt/bn/vl-research/data/llava_instruct/real_vision_flan/geo170k_align_converted_60252.json",
33
+ # "/mnt/bn/vl-research/data/llava_instruct/real_vision_flan/sharegpt4v-coco-50k.json",
34
+ # "/mnt/bn/vl-research/data/llava_instruct/real_vision_flan/sharegpt4v-knowledge-2k.json",
35
+ # "/mnt/bn/vl-research/data/llava_instruct/real_vision_flan/sharegpt4v-llava-30k.json",
36
+ # "/mnt/bn/vl-research/data/llava_instruct/real_vision_flan/sharegpt4v-sam-20k.json",
37
+ # "/mnt/bn/vl-research/data/llava_instruct/real_vision_flan/MathV360K_CLEVR-Math_5290.json",
38
+ # "/mnt/bn/vl-research/data/llava_instruct/real_vision_flan/MathV360K_FigureQA_17597.json",
39
+ # "/mnt/bn/vl-research/data/llava_instruct/real_vision_flan/MathV360K_Geometry3K_9734.json",
40
+ # "/mnt/bn/vl-research/data/llava_instruct/real_vision_flan/MathV360K_GeoQA+_17172.json",
41
+ # "/mnt/bn/vl-research/data/llava_instruct/real_vision_flan/MathV360K_GEOS_508.json",
42
+ # "/mnt/bn/vl-research/data/llava_instruct/real_vision_flan/MathV360K_IconQA_22599.json",
43
+ # "/mnt/bn/vl-research/data/llava_instruct/real_vision_flan/MathV360K_MapQA_5235.json",
44
+ # "/mnt/bn/vl-research/data/llava_instruct/real_vision_flan/MathV360K_PMC-VQA_35958.json",
45
+ # "/mnt/bn/vl-research/data/llava_instruct/real_vision_flan/MathV360K_Super-CLEVR_8652.json",
46
+ # "/mnt/bn/vl-research/data/llava_instruct/real_vision_flan/MathV360K_TabMWP_22462.json",
47
+ # "/mnt/bn/vl-research/data/llava_instruct/real_vision_flan/MathV360K_UniGeo_11959.json",
48
+ # "/mnt/bn/vl-research/data/llava_instruct/real_vision_flan/MathV360K_VizWiz_6614.json",
49
+ # "/mnt/bn/vl-research/data/llava_instruct/real_vision_flan/magpie_pro_qwen2_72b_st_300000_sp_token_fltd_299992.json",
50
+ # "/mnt/bn/vl-research/data/llava_instruct/real_vision_flan/magpie_pro_l3_80b_st_300000.json",
51
+ # "/mnt/bn/vl-research/data/llava_instruct/real_vision_flan/magpie_pro_l3_80b_mt_300000_sp_token_fltd_299998.json",
52
+ # "/mnt/bn/vl-research/data/llava_instruct/real_vision_flan/image_textualization_dataset_filtered.json",
53
+ # "/mnt/bn/vl-research/data/llava_instruct/real_vision_flan/cambrian_filtered_gpt4vo_sp_token_fltd_max10k.json",
54
+ "/mnt/bn/vl-research/data/llava_instruct/real_vision_flan/sharegpt4o_dataset.jsonl",
55
+ "/mnt/bn/vl-research/data/llava_instruct/cauldron/ai2d_llava_format_2434.json",
56
+ "/mnt/bn/vl-research/data/llava_instruct/cauldron/aokvqa_16539_llava_format.json",
57
+ "/mnt/bn/vl-research/data/llava_instruct/cauldron/chart2text_26961.json",
58
+ "/mnt/bn/vl-research/data/llava_instruct/cauldron/chartqa_18265_llava_format.json",
59
+ "/mnt/bn/vl-research/data/llava_instruct/cauldron/clevr_70000_llava_format.json",
60
+ "/mnt/bn/vl-research/data/llava_instruct/cauldron/diagram_image_to_text_300.json",
61
+ "/mnt/bn/vl-research/data/llava_instruct/cauldron/dvqa_200000_llava_format.json",
62
+ "/mnt/bn/vl-research/data/llava_instruct/cauldron/figureqa_100000_llava_format.json",
63
+ "/mnt/bn/vl-research/data/llava_instruct/cauldron/geomverse_9303.json",
64
+ "/mnt/bn/vl-research/data/llava_instruct/cauldron/hateful_memes_8500_llava_format.json",
65
+ "/mnt/bn/vl-research/data/llava_instruct/cauldron/hitab_2500_llava_format.json",
66
+ "/mnt/bn/vl-research/data/llava_instruct/cauldron/iam_5663.json",
67
+ "/mnt/bn/vl-research/data/llava_instruct/cauldron/raven_42000.json",
68
+ "/mnt/bn/vl-research/data/llava_instruct/cauldron/iconqa_llava_format_27307.json",
69
+ "/mnt/bn/vl-research/data/llava_instruct/cauldron/infographic_vqa_2118_llava_format.json",
70
+ "/mnt/bn/vl-research/data/llava_instruct/cauldron/intergps_1280_llava_format.json",
71
+ "/mnt/bn/vl-research/data/llava_instruct/cauldron/mapqa_37417_llava_format.json",
72
+ "/mnt/bn/vl-research/data/llava_instruct/cauldron/multihiertt_7619.json",
73
+ "/mnt/bn/vl-research/data/llava_instruct/cauldron/rendered_text_10000.json",
74
+ "/mnt/bn/vl-research/data/llava_instruct/cauldron/robut_sqa_8514.json",
75
+ "/mnt/bn/vl-research/data/llava_instruct/cauldron/robut_wikisql_74989.json",
76
+ "/mnt/bn/vl-research/data/llava_instruct/cauldron/robut_wtq_38246_llava_format.json",
77
+ "/mnt/bn/vl-research/data/llava_instruct/cauldron/screen2words_15730.json",
78
+ "/mnt/bn/vl-research/data/llava_instruct/cauldron/scienceqa_llava_format_4976.json",
79
+ "/mnt/bn/vl-research/data/llava_instruct/cauldron/tabmwp_22722.json",
80
+ "/mnt/bn/vl-research/data/llava_instruct/cauldron/tallyqa_98680_llava_format.json",
81
+ "/mnt/bn/vl-research/data/llava_instruct/cauldron/st_vqa_17247_llava_format.json",
82
+ "/mnt/bn/vl-research/data/llava_instruct/cauldron/tqa_llava_format_27307.json",
83
+ "/mnt/bn/vl-research/data/llava_instruct/cauldron/visual7w_llava_format_14366.json",
84
+ "/mnt/bn/vl-research/data/llava_instruct/cauldron/visualmrc_3027.json",
85
+ "/mnt/bn/vl-research/data/llava_instruct/cauldron/vqarad_313_llava_format.json",
86
+ "/mnt/bn/vl-research/data/llava_instruct/cauldron/vsr_2157_llava_format.json",
87
+ "/mnt/bn/vl-research/data/llava_instruct/cauldron/vistext_9969.json",
88
+ "/mnt/bn/vl-research/data/llava_instruct/cauldron/websight_10000.json"
89
+ ]
90
+
91
+ short_names = [
92
+ # "mavis_math_metagen",
93
+ # "mavis_math_rule_geo",
94
+ # "k12_printing",
95
+ # "iiit5k",
96
+ # "hme100k",
97
+ # "ai2d(gpt4v)",
98
+ # "infographic_vqa",
99
+ # "infographic(gpt4v)",
100
+ # "lrv_chart",
101
+ # "lrv_normal(filtered)",
102
+ # "scienceqa(nona_context)",
103
+ # "allava_instruct_vflan4v",
104
+ # "allava_instruct_laion4v",
105
+ # "textocr(gpt4v)",
106
+ # "ai2d(internvl)",
107
+ # "textcaps",
108
+ # "ureader_qa", # need to re-upload
109
+ # "ureader_cap", # need to re-upload
110
+ # "ureader_ie", # need to re-upload
111
+ # "ureader_kg", # need to re-upload
112
+ # "vision_flan(filtered)",
113
+ # "mathqa",
114
+ # "geo3k",
115
+ # "geo170k(qa)",
116
+ # "geo170k(align)",
117
+ # "sharegpt4v(coco)",
118
+ # "sharegpt4v(knowledge)",
119
+ # "sharegpt4v(llava)",
120
+ # "sharegpt4v(sam)",
121
+ # "CLEVR-Math(MathV360K)",
122
+ # "FigureQA(MathV360K)",
123
+ # "Geometry3K(MathV360K)",
124
+ # "GeoQA+(MathV360K)",
125
+ # "GEOS(MathV360K)",
126
+ # "IconQA(MathV360K)",
127
+ # "MapQA(MathV360K)",
128
+ # "PMC-VQA(MathV360K)",
129
+ # "Super-CLEVR(MathV360K)",
130
+ # "TabMWP(MathV360K)",
131
+ # "UniGeo(MathV360K)",
132
+ # "VizWiz(MathV360K)",
133
+ # "magpie_pro(qwen2_72b_st)",
134
+ # "magpie_pro(l3_80b_st)",
135
+ # "magpie_pro(l3_80b_mt)",
136
+ # "image_textualization(filtered)",
137
+ # "cambrian(filtered_gpt4vo)", # need to re-upload
138
+ "sharegpt4o",
139
+ "ai2d(cauldron,llava_format)",
140
+ "aokvqa(cauldron,llava_format)",
141
+ "chart2text(cauldron)",
142
+ "chartqa(cauldron,llava_format)",
143
+ "clevr(cauldron,llava_format)",
144
+ "diagram_image_to_text(cauldron)",
145
+ "dvqa(cauldron,llava_format)",
146
+ "figureqa(cauldron,llava_format)",
147
+ "geomverse(cauldron)",
148
+ "hateful_memes(cauldron,llava_format)",
149
+ "hitab(cauldron,llava_format)",
150
+ "iam(cauldron)",
151
+ "raven(cauldron)",
152
+ "iconqa(cauldron,llava_format)",
153
+ "infographic_vqa_llava_format",
154
+ "intergps(cauldron,llava_format)",
155
+ "mapqa(cauldron,llava_format)",
156
+ "multihiertt(cauldron)",
157
+ "rendered_text(cauldron)",
158
+ "robut_sqa(cauldron)",
159
+ "robut_wikisql(cauldron)",
160
+ "robut_wtq(cauldron,llava_format)",
161
+ "screen2words(cauldron)",
162
+ "scienceqa(cauldron,llava_format)",
163
+ "tabmwp(cauldron)",
164
+ "tallyqa(cauldron,llava_format)",
165
+ "st_vqa(cauldron,llava_format)",
166
+ "tqa(cauldron,llava_format)",
167
+ "visual7w(cauldron,llava_format)",
168
+ "visualmrc(cauldron)",
169
+ "vqarad(cauldron,llava_format)",
170
+ "vsr(cauldron,llava_format)",
171
+ "vistext(cauldron)",
172
+ "websight(cauldron)"
173
+ ]
174
+
175
+ def upload_data(json_path, short_name):
176
+ def gen():
177
+ if json_path.endswith(".jsonl"):
178
+ with open(json_path, "r") as f:
179
+ data = [json.loads(line) for line in f]
180
+ else:
181
+ with open(json_path, "r") as f:
182
+ data = json.load(f)
183
+
184
+ preview_index = 5
185
+ idx = 0
186
+ for item in tqdm(data):
187
+ if preview_index > 0:
188
+ preview_index -= 1
189
+ print(item)
190
+ continue
191
+
192
+ try:
193
+ if "image" in item:
194
+ image_path = f"/mnt/bn/vl-research/data/llava_data/{item['image']}"
195
+ try:
196
+ with open(image_path, "rb") as img_file:
197
+ image = pil_image.open(BytesIO(img_file.read()))
198
+ except:
199
+ print(f"Failed to load image {item['image']}")
200
+ continue
201
+ else:
202
+ image = None
203
+
204
+ item_id = item["id"] if "id" in item else f"{idx:06d}"
205
+ yield {"id": item_id, "image": image, "conversations": item["conversations"], "data_source": short_name}
206
+ idx += 1
207
+
208
+ except Exception as e:
209
+ print(e)
210
+ continue
211
+
212
+
213
+ hf_dataset = Dataset.from_generator(generator=gen, num_proc=32)
214
+ hf_dataset.push_to_hub("lmms-lab/LLaVA-OneVision-Data", config_name=short_name, split="train")
215
+
216
+ for json_path, short_name in zip(json_paths, short_names):
217
+ upload_data(json_path, short_name)