Master-Shi commited on
Commit
e7dd411
·
verified ·
1 Parent(s): b5f54c0

Add files using upload-large-folder tool

Browse files
Files changed (20) hide show
  1. 之前的代码版本/HuatuoGPT-Vision/cli.py +388 -0
  2. 之前的代码版本/HuatuoGPT-Vision/convert_llm_to_vl.py +82 -0
  3. 之前的代码版本/HuatuoGPT-Vision/eval.py +179 -0
  4. 之前的代码版本/HuatuoGPT-Vision/eval_attnbias_sam.py +0 -0
  5. 之前的代码版本/HuatuoGPT-Vision/medsam3_wrapper.py +112 -0
  6. 之前的代码版本/HuatuoGPT-Vision/run_ablation_grid.sh +122 -0
  7. 之前的代码版本/HuatuoGPT-Vision/run_all_attnbias_sam.sh +33 -0
  8. 之前的代码版本/HuatuoGPT-Vision/run_eval.sh +14 -0
  9. 之前的代码版本/HuatuoGPT-Vision/run_eval_attnbias_sam_both.sh +49 -0
  10. 之前的代码版本/HuatuoGPT-Vision/run_eval_attnbias_sam_both_noauction.sh +42 -0
  11. 之前的代码版本/HuatuoGPT-Vision/run_eval_attnbias_sam_both_random.sh +57 -0
  12. 之前的代码版本/HuatuoGPT-Vision/run_eval_attnbias_sam_both_suppress_only.sh +53 -0
  13. 之前的代码版本/HuatuoGPT-Vision/run_eval_attnbias_sam_none.sh +40 -0
  14. 之前的代码版本/HuatuoGPT-Vision/run_eval_attnbias_sam_text.sh +46 -0
  15. 之前的代码版本/HuatuoGPT-Vision/run_eval_attnbias_sam_vis.sh +50 -0
  16. 之前的代码版本/HuatuoGPT-Vision/scorer.py +195 -0
  17. 之前的代码版本/HuatuoGPT-Vision/sync_attn_params.py +116 -0
  18. 之前的代码版本/HuatuoGPT-Vision/train_vl.py +496 -0
  19. 之前的代码版本/注意力关键词用于sam的/MedEvalKit/LLaVA-NeXT/playground/demo/video_demo.py +335 -0
  20. 之前的代码版本/注意力关键词用于sam的/MedEvalKit/LLaVA-NeXT/playground/remove_mid_ckpt.py +35 -0
之前的代码版本/HuatuoGPT-Vision/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/convert_llm_to_vl.py ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #%%
2
+ import torch
3
+ import argparse
4
+ from transformers import (
5
+ Qwen2_5_VLForConditionalGeneration,
6
+ AutoProcessor,
7
+ Qwen2ForCausalLM,
8
+ )
9
+
10
+ #%%
11
+ def parse_args():
12
+ parser = argparse.ArgumentParser(description="Convert Qwen2.5-LLM weights into Qwen2.5-VL")
13
+ parser.add_argument("--vl_model_path", type=str, required=True, help="Path to the pretrained Qwen2.5-VL model")
14
+ parser.add_argument("--llm_model_path", type=str, required=True, help="Path to the pretrained Qwen2.5-LLM model")
15
+ parser.add_argument("--save_path", type=str, required=True, help="Path to save the converted Qwen2.5-VL model")
16
+ return parser.parse_args()
17
+
18
+ #%%
19
+ def main():
20
+ args = parse_args()
21
+
22
+ # Load models
23
+ print("Loading VL model from:", args.vl_model_path)
24
+ model_vl = Qwen2_5_VLForConditionalGeneration.from_pretrained(
25
+ args.vl_model_path, torch_dtype="auto"
26
+ )
27
+
28
+ print("Loading LLM model from:", args.llm_model_path)
29
+ model_lm = Qwen2ForCausalLM.from_pretrained(
30
+ args.llm_model_path, torch_dtype="auto"
31
+ )
32
+
33
+ # Print model parameter info
34
+ print("==== Parameters of model_vl ====")
35
+ vl_params = list(model_vl.named_parameters())
36
+ print(f"Total number of VL model parameters: {len(vl_params)}")
37
+ print("Sample parameters:")
38
+ for i, (name, _) in enumerate(vl_params[:10]):
39
+ print(f" {name}")
40
+
41
+ print("\n==== Parameters of model_lm ====")
42
+ lm_params = list(model_lm.named_parameters())
43
+ print(f"Total number of LLM model parameters: {len(lm_params)}")
44
+ print("Sample parameters:")
45
+ for i, (name, _) in enumerate(lm_params[:10]):
46
+ print(f" {name}")
47
+
48
+ # Parameter replacement
49
+ print("\n==== Starting parameter replacement ====")
50
+ lm_state_dict = model_lm.state_dict()
51
+ vl_model_state_dict = model_vl.state_dict()
52
+ new_vl_model_state_dict = {}
53
+
54
+ replaced_count = 0
55
+ skipped_count = 0
56
+
57
+ for key in vl_model_state_dict.keys():
58
+ if key in lm_state_dict and vl_model_state_dict[key].shape == lm_state_dict[key].shape:
59
+ new_vl_model_state_dict[key] = lm_state_dict[key]
60
+ replaced_count += 1
61
+ else:
62
+ new_vl_model_state_dict[key] = vl_model_state_dict[key]
63
+ skipped_count += 1
64
+ if key not in lm_state_dict:
65
+ print(f"Parameter not found in LLM model: {key}")
66
+ else:
67
+ print(f"Shape mismatch - skipping: {key}, VL shape: {vl_model_state_dict[key].shape}, LLM shape: {lm_state_dict[key].shape}")
68
+
69
+ model_vl.load_state_dict(new_vl_model_state_dict)
70
+ print(f"\nParameter replacement completed! Replaced: {replaced_count}, Skipped: {skipped_count}")
71
+
72
+ # Save model
73
+ print(f"\nSaving converted VL model to: {args.save_path}")
74
+ model_vl.save_pretrained(args.save_path)
75
+
76
+ processor = AutoProcessor.from_pretrained(args.vl_model_path)
77
+ processor.save_pretrained(args.save_path)
78
+ print("Processor saved successfully.")
79
+
80
+ #%%
81
+ if __name__ == "__main__":
82
+ main()
之前的代码版本/HuatuoGPT-Vision/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/eval_attnbias_sam.py ADDED
The diff for this file is too large to render. See raw diff
 
之前的代码版本/HuatuoGPT-Vision/medsam3_wrapper.py ADDED
@@ -0,0 +1,112 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ medsam3_wrapper.py
3
+ ===================
4
+ MedSAM3Wrapper: lazy-loads MedSAM3's LoRA inference model and runs
5
+ text-query-driven bbox/mask prediction for a single (image, keyword) pair.
6
+
7
+ Migrated from the earlier eval_textquery_medsam3_attnbias_both.py prototype
8
+ (see F:\\文本提示的分割\\数据集\\之前尝试版本-关于关键区域和关键文本\\HuatuoGPT-Vision\\),
9
+ so eval_attnbias_sam.py's `--intervention vis`/`--intervention both` modes can
10
+ import a real implementation instead of degrading to the full-image fallback.
11
+
12
+ Requires MedSAM3 to be installed (see _lazy_load below) and --medsam3_config /
13
+ --medsam3_dir to point at a valid SAM3LoRAInference config and repo checkout.
14
+ """
15
+
16
+ import os
17
+
18
+ import numpy as np
19
+ from PIL import Image
20
+
21
+
22
+ class MedSAM3Wrapper:
23
+ def __init__(self, config_path, device="cuda", threshold=0.3, nms_iou=0.5,
24
+ medsam3_dir=None):
25
+ self.threshold = threshold
26
+ self.nms_iou = nms_iou
27
+ self.device = device
28
+ self._inferencer = None
29
+ self._config_path = config_path
30
+ self._medsam3_dir = medsam3_dir or os.path.dirname(
31
+ os.path.dirname(os.path.abspath(config_path))
32
+ )
33
+
34
+ def _lazy_load(self):
35
+ if self._inferencer is not None:
36
+ return
37
+ import sys
38
+ if self._medsam3_dir not in sys.path:
39
+ sys.path.insert(0, self._medsam3_dir)
40
+ try:
41
+ from infer_sam import SAM3LoRAInference
42
+ except ImportError:
43
+ raise ImportError(
44
+ "找不到 MedSAM3。请先安装:\n"
45
+ " git clone https://github.com/Joey-S-Liu/MedSAM3.git\n"
46
+ " cd MedSAM3 && pip install -e ."
47
+ )
48
+ print("[MedSAM3] 加载模型...")
49
+ _orig_dir = os.getcwd()
50
+ try:
51
+ os.chdir(self._medsam3_dir)
52
+ self._inferencer = SAM3LoRAInference(
53
+ config_path=self._config_path, device=self.device,
54
+ )
55
+ finally:
56
+ os.chdir(_orig_dir)
57
+ print("[MedSAM3] 加载完成")
58
+
59
+ def predict_bbox(self, image: Image.Image, keyword: str):
60
+ self._lazy_load()
61
+ import tempfile
62
+ try:
63
+ with tempfile.NamedTemporaryFile(suffix=".png", delete=False) as tmp:
64
+ tmp_path = tmp.name
65
+ image.convert("RGB").save(tmp_path)
66
+ _tmp_size = os.path.getsize(tmp_path)
67
+ print(f"[MedSAM3-debug] wrote {tmp_path} size={_tmp_size} bytes "
68
+ f"image.size={image.size} keyword='{keyword}'")
69
+ if _tmp_size == 0:
70
+ print(f"[MedSAM3-debug] WARNING: {tmp_path} is empty after save()!")
71
+ _orig_dir = os.getcwd()
72
+ os.chdir(self._medsam3_dir)
73
+ try:
74
+ result = self._inferencer.predict(tmp_path, [keyword])
75
+ finally:
76
+ os.chdir(_orig_dir)
77
+ os.unlink(tmp_path)
78
+ except Exception as e:
79
+ import traceback; traceback.print_exc()
80
+ return [], None, f"MedSAM3 推理失败('{keyword}'): {e}"
81
+
82
+ pred = result.get(0, None)
83
+ if pred is None or pred.get("num_detections", 0) == 0:
84
+ return [], None, f"MedSAM3 未检测到 '{keyword}'"
85
+ n = pred.get("num_detections", 0)
86
+ boxes = pred.get("boxes", None)
87
+ masks = pred.get("masks", None)
88
+
89
+ combined_mask = None
90
+ if masks is not None:
91
+ for m in masks[:n]:
92
+ m_f = m.astype(np.float32)
93
+ combined_mask = m_f if combined_mask is None else np.maximum(combined_mask, m_f)
94
+
95
+ if boxes is not None and len(boxes) > 0:
96
+ bbox_list = [[int(v) for v in b] for b in boxes[:n]]
97
+ info = f"MedSAM3('{keyword}') {len(bbox_list)}个box→{bbox_list}"
98
+ return bbox_list, combined_mask, info
99
+
100
+ if masks is not None and len(masks) > 0:
101
+ bbox_list = []
102
+ for mask in masks[:n]:
103
+ if not mask.any():
104
+ continue
105
+ ys = np.where(np.any(mask, axis=1))[0]
106
+ xs = np.where(np.any(mask, axis=0))[0]
107
+ bbox_list.append([int(xs[0]), int(ys[0]), int(xs[-1]), int(ys[-1])])
108
+ if bbox_list:
109
+ info = f"MedSAM3('{keyword}') {len(bbox_list)}个mask→bbox"
110
+ return bbox_list, combined_mask, info
111
+
112
+ return [], None, f"MedSAM3 无有效结果: '{keyword}'"
之前的代码版本/HuatuoGPT-Vision/run_ablation_grid.sh ADDED
@@ -0,0 +1,122 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ cd "$(dirname "$0")"
3
+
4
+ # Full grid search over (layer, strength) for the "both" intervention mode WITH
5
+ # Budgeted Token Auction enabled. Previously this was a 2-stage greedy search
6
+ # (fix layer, sweep strength; then fix the best strength, sweep layer) to avoid
7
+ # the cost of re-running Stage1 (model generation) + SAM for every one of the
8
+ # 5 layers x 4 strengths = 20 combinations. Stage1/SAM results are now cached
9
+ # in eval_attnbias_sam.py (keyed on data_path/model_path/seed, see
10
+ # HuatuoGPT-Vision/cache/sam_stage1_cache/) and are independent of the bias
11
+ # layer/strength/auction args, so re-running this file for a new (layer,
12
+ # strength) combo only re-pays the much cheaper bias-intervention generation
13
+ # pass -- a full grid is no longer prohibitively expensive.
14
+ # kbt=kbv=s, nbt=nbv=-s for s in {0.5, 1.0, 2.0, 4.0}; layer in {3, 10, 17, 24, 27}.
15
+ # Auction budgets/alpha/beta are fixed at their defaults here -- this script
16
+ # only sweeps bias layer/strength, not the auction hyperparameters themselves.
17
+ # Each combo writes to its own output dir under results_attnbias_ablation/, so
18
+ # this never touches results_attnbias/HuatuoGPT-Vision-7B/sam_both or any other
19
+ # previously saved result.
20
+ set -e
21
+
22
+ source "$(conda info --base)/etc/profile.d/conda.sh"
23
+ conda activate huatuovision
24
+
25
+ DATA_PATH="/home/jinhua/ExplainableVQA/benchmarks/Medical_Multimodal_Evaluation_Data/medical_multimodel_evaluation_data.json"
26
+ MODEL_PATH="FreedomIntelligence/HuatuoGPT-Vision-7B"
27
+
28
+ SEED=42
29
+ MAX_NEW_TOKENS=256
30
+
31
+ MEDSAM3_CONFIG="/home/jinhua/ExplainableVQA/HuatuoGPT-Vision/MedSAM3/configs/full_lora_config.yaml"
32
+ MEDSAM3_DIR="/home/jinhua/ExplainableVQA/HuatuoGPT-Vision/MedSAM3"
33
+
34
+ INTERVENTION="both"
35
+ LAYERS=(3 10 17 24 27)
36
+ STRENGTHS=(0.5 1.0 2.0 4.0)
37
+
38
+ AUCTION_TOTAL_RATIO=0.7
39
+ AUCTION_NEG_RATIO=0.7
40
+
41
+ MAX_SAMPLES=""
42
+
43
+ for LAYER in "${LAYERS[@]}"; do
44
+ for S in "${STRENGTHS[@]}"; do
45
+ OUTPUT_PATH="results_attnbias_ablation/HuatuoGPT-Vision-7B/sam_both_auction_layer${LAYER}_s${S}"
46
+ if [ -d "$OUTPUT_PATH" ]; then
47
+ echo "[ablation-grid] $OUTPUT_PATH already exists, skipping layer=$LAYER s=$S (delete the dir manually to re-run)"
48
+ continue
49
+ fi
50
+
51
+ echo "=================================================="
52
+ echo "[ablation-grid] layer=$LAYER strength=$S -> $OUTPUT_PATH"
53
+ echo "=================================================="
54
+
55
+ accelerate launch eval_attnbias_sam.py \
56
+ --data_path "$DATA_PATH" \
57
+ --model_path "$MODEL_PATH" \
58
+ --seed "$SEED" \
59
+ --max_new_tokens "$MAX_NEW_TOKENS" \
60
+ --output_path "$OUTPUT_PATH" \
61
+ --intervention "$INTERVENTION" \
62
+ --attn_layers_text "$LAYER" \
63
+ --attn_key_bias_text "$S" \
64
+ --attn_nonkey_bias_text "-$S" \
65
+ --attn_layers_vis "$LAYER" \
66
+ --attn_key_bias_vis "$S" \
67
+ --attn_nonkey_bias_vis "-$S" \
68
+ --medsam3_config "$MEDSAM3_CONFIG" \
69
+ --medsam3_dir "$MEDSAM3_DIR" \
70
+ --auction_enable \
71
+ --auction_total_ratio "$AUCTION_TOTAL_RATIO" \
72
+ --auction_neg_ratio "$AUCTION_NEG_RATIO" \
73
+ ${MAX_SAMPLES:+--max_samples "$MAX_SAMPLES"}
74
+
75
+ echo "[ablation-grid] layer=$LAYER s=$S finished"
76
+ done
77
+ done
78
+
79
+ echo "[ablation-grid] all ${#LAYERS[@]}x${#STRENGTHS[@]} combinations finished"
80
+
81
+ # ── pick the best (layer, strength) across the full grid. Each combo's output
82
+ # dir holds exactly one *_result.json (eval_attnbias_sam.py's hparam_tag
83
+ # already makes the filename unique per layer/strength/auction config, so
84
+ # no risk of stale files from a previous combo lingering in the same dir),
85
+ # so glob for it directly instead of hand-reconstructing the filename --
86
+ # that reconstruction is what broke last time hparam_tag's format changed.
87
+ BEST_LAYER=""
88
+ BEST_STRENGTH=""
89
+ BEST_SCORE=""
90
+ for LAYER in "${LAYERS[@]}"; do
91
+ for S in "${STRENGTHS[@]}"; do
92
+ OUTPUT_PATH="results_attnbias_ablation/HuatuoGPT-Vision-7B/sam_both_auction_layer${LAYER}_s${S}"
93
+ RESULT_F=$(ls "$OUTPUT_PATH"/*_result.json 2>/dev/null | head -n1)
94
+ if [ -z "$RESULT_F" ]; then
95
+ echo "[ablation-grid] missing *_result.json under $OUTPUT_PATH -- cannot pick best (layer, strength)" >&2
96
+ exit 1
97
+ fi
98
+ SCORE=$(python -c "
99
+ import json
100
+ with open('$RESULT_F') as f:
101
+ d = json.load(f)
102
+ print(d['The total score for multiple-choice questions'])
103
+ ")
104
+ echo "[ablation-grid] layer=$LAYER s=$S score=$SCORE"
105
+ if [ -z "$BEST_SCORE" ] || python -c "exit(0 if $SCORE > $BEST_SCORE else 1)"; then
106
+ BEST_SCORE="$SCORE"
107
+ BEST_LAYER="$LAYER"
108
+ BEST_STRENGTH="$S"
109
+ fi
110
+ done
111
+ done
112
+
113
+ echo "[ablation-grid] best overall: layer=$BEST_LAYER strength=$BEST_STRENGTH (score=$BEST_SCORE)"
114
+ echo "[ablation-grid] syncing into every run_eval_attnbias_sam_*.sh via sync_attn_params.py"
115
+
116
+ NONKEY_STRENGTH="-$BEST_STRENGTH"
117
+ python sync_attn_params.py \
118
+ --layers_text "$BEST_LAYER" --key_bias_text "$BEST_STRENGTH" --nonkey_bias_text "$NONKEY_STRENGTH" \
119
+ --layers_vis "$BEST_LAYER" --key_bias_vis "$BEST_STRENGTH" --nonkey_bias_vis "$NONKEY_STRENGTH"
120
+
121
+ echo "[ablation-grid] done. All run_eval_attnbias_sam_*.sh now use the ablation-selected layer/strength"
122
+ echo "[ablation-grid] (amplify_only/suppress_only keep their pinned-zero side; text.sh/vis.sh keep their single-modality side -- see sync_attn_params.py)."
之前的代码版本/HuatuoGPT-Vision/run_all_attnbias_sam.sh ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ cd "$(dirname "$0")"
3
+
4
+ # 先跑 baseline(无干预的 eval.py),再依次跑完主干对比三组:
5
+ # none(无attention干预)/ both_noauction(传统全有全无)/ both(auction精选,正式配置)
6
+ # 任意一个失败就停止,避免在错误的环境下继续浪费时间
7
+ set -e
8
+
9
+ # 默认使用 huatuovision conda 环境,不依赖调用者当前激活的环境
10
+ source "$(conda info --base)/etc/profile.d/conda.sh"
11
+ conda activate huatuovision
12
+
13
+ SCRIPTS=(
14
+ "run_eval.sh"
15
+ "run_eval_attnbias_sam_none.sh"
16
+ "run_eval_attnbias_sam_both_noauction.sh"
17
+ "run_eval_attnbias_sam_both.sh"
18
+ "run_eval_attnbias_sam_text.sh"
19
+ "run_eval_attnbias_sam_vis.sh"
20
+ "run_eval_attnbias_sam_both_amplify_only.sh"
21
+ "run_eval_attnbias_sam_both_suppress_only.sh"
22
+ "run_eval_attnbias_sam_both_random.sh"
23
+ )
24
+
25
+ for script in "${SCRIPTS[@]}"; do
26
+ echo "=================================================="
27
+ echo "[run_all] 开始运行 $script"
28
+ echo "=================================================="
29
+ bash "$script"
30
+ echo "[run_all] $script 运行完成"
31
+ done
32
+
33
+ echo "[run_all] 全部干预模式运行完成"
之前的代码版本/HuatuoGPT-Vision/run_eval.sh ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
7
+ SEED=42
8
+ MAX_NEW_TOKENS=256
9
+
10
+ accelerate launch eval.py \
11
+ --data_path "$DATA_PATH" \
12
+ --model_path "$MODEL_PATH" \
13
+ --seed "$SEED" \
14
+ --max_new_tokens "$MAX_NEW_TOKENS"
之前的代码版本/HuatuoGPT-Vision/run_eval_attnbias_sam_both.sh ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ MEDSAM3_CONFIG="/home/jinhua/ExplainableVQA/HuatuoGPT-Vision/MedSAM3/configs/full_lora_config.yaml"
12
+ MEDSAM3_DIR="/home/jinhua/ExplainableVQA/HuatuoGPT-Vision/MedSAM3"
13
+
14
+ # both mode + Budgeted Token Auction: instead of amplifying every SAM patch /
15
+ # scispaCy keyword and suppressing everything else, score every candidate by its
16
+ # original attention and select only top-k under a fixed budget (see
17
+ # BudgetedTokenAuction in eval_attnbias_sam.py).
18
+ INTERVENTION="both"
19
+ ATTN_LAYERS_TEXT=17
20
+ ATTN_KEY_BIAS_TEXT=3.0
21
+ ATTN_NONKEY_BIAS_TEXT=-3.0
22
+ ATTN_LAYERS_VIS=17
23
+ ATTN_KEY_BIAS_VIS=3.0
24
+ ATTN_NONKEY_BIAS_VIS=-3.0
25
+
26
+ AUCTION_TOTAL_RATIO=0.7
27
+ AUCTION_NEG_RATIO=0.7
28
+
29
+ MAX_SAMPLES=""
30
+
31
+ accelerate launch eval_attnbias_sam.py \
32
+ --data_path "$DATA_PATH" \
33
+ --model_path "$MODEL_PATH" \
34
+ --seed "$SEED" \
35
+ --max_new_tokens "$MAX_NEW_TOKENS" \
36
+ --output_path "$OUTPUT_PATH" \
37
+ --intervention "$INTERVENTION" \
38
+ --attn_layers_text "$ATTN_LAYERS_TEXT" \
39
+ --attn_key_bias_text "$ATTN_KEY_BIAS_TEXT" \
40
+ --attn_nonkey_bias_text "$ATTN_NONKEY_BIAS_TEXT" \
41
+ --attn_layers_vis "$ATTN_LAYERS_VIS" \
42
+ --attn_key_bias_vis "$ATTN_KEY_BIAS_VIS" \
43
+ --attn_nonkey_bias_vis "$ATTN_NONKEY_BIAS_VIS" \
44
+ --medsam3_config "$MEDSAM3_CONFIG" \
45
+ --medsam3_dir "$MEDSAM3_DIR" \
46
+ --auction_enable \
47
+ --auction_total_ratio "$AUCTION_TOTAL_RATIO" \
48
+ --auction_neg_ratio "$AUCTION_NEG_RATIO" \
49
+ ${MAX_SAMPLES:+--max_samples "$MAX_SAMPLES"}
之前的代码版本/HuatuoGPT-Vision/run_eval_attnbias_sam_both_noauction.sh ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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_noauction"
7
+
8
+ SEED=42
9
+ MAX_NEW_TOKENS=256
10
+
11
+ MEDSAM3_CONFIG="/home/jinhua/ExplainableVQA/HuatuoGPT-Vision/MedSAM3/configs/full_lora_config.yaml"
12
+ MEDSAM3_DIR="/home/jinhua/ExplainableVQA/HuatuoGPT-Vision/MedSAM3"
13
+
14
+ # both mode, auction OFF (legacy behavior): every SAM patch / scispaCy keyword
15
+ # gets amplified, everything else gets suppressed -- no scoring, no budget. This
16
+ # is the "before" half of the main ablation: none vs both-noauction vs both+auction.
17
+ INTERVENTION="both"
18
+ ATTN_LAYERS_TEXT=17
19
+ ATTN_KEY_BIAS_TEXT=3.0
20
+ ATTN_NONKEY_BIAS_TEXT=-3.0
21
+ ATTN_LAYERS_VIS=17
22
+ ATTN_KEY_BIAS_VIS=3.0
23
+ ATTN_NONKEY_BIAS_VIS=-3.0
24
+
25
+ MAX_SAMPLES=""
26
+
27
+ accelerate launch eval_attnbias_sam.py \
28
+ --data_path "$DATA_PATH" \
29
+ --model_path "$MODEL_PATH" \
30
+ --seed "$SEED" \
31
+ --max_new_tokens "$MAX_NEW_TOKENS" \
32
+ --output_path "$OUTPUT_PATH" \
33
+ --intervention "$INTERVENTION" \
34
+ --attn_layers_text "$ATTN_LAYERS_TEXT" \
35
+ --attn_key_bias_text "$ATTN_KEY_BIAS_TEXT" \
36
+ --attn_nonkey_bias_text "$ATTN_NONKEY_BIAS_TEXT" \
37
+ --attn_layers_vis "$ATTN_LAYERS_VIS" \
38
+ --attn_key_bias_vis "$ATTN_KEY_BIAS_VIS" \
39
+ --attn_nonkey_bias_vis "$ATTN_NONKEY_BIAS_VIS" \
40
+ --medsam3_config "$MEDSAM3_CONFIG" \
41
+ --medsam3_dir "$MEDSAM3_DIR" \
42
+ ${MAX_SAMPLES:+--max_samples "$MAX_SAMPLES"}
之前的代码版本/HuatuoGPT-Vision/run_eval_attnbias_sam_both_random.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_random"
7
+
8
+ SEED=42
9
+ MAX_NEW_TOKENS=256
10
+
11
+ MEDSAM3_CONFIG="/home/jinhua/ExplainableVQA/HuatuoGPT-Vision/MedSAM3/configs/full_lora_config.yaml"
12
+ MEDSAM3_DIR="/home/jinhua/ExplainableVQA/HuatuoGPT-Vision/MedSAM3"
13
+
14
+ # Ablation control: same "both" bias strengths/layers/auction params as
15
+ # run_eval_attnbias_sam_both.sh, but the scispaCy keyword positions and SAM
16
+ # bbox patches are each replaced (--ablation_random_text/--ablation_random_vis)
17
+ # with an equal-count RANDOM sample from the same candidate pool (all question
18
+ # text tokens / full 24x24 visual grid, excluding the true key positions),
19
+ # seeded by $SEED for reproducibility. Auction stays ON so this differs from
20
+ # "both" by exactly one factor (random vs real key positions feeding the
21
+ # auction's bidding) -- tests whether gains come from biasing the
22
+ # *semantically correct* tokens, or merely from biasing *some* tokens of the
23
+ # same count. Compare this run's accuracy against run_eval_attnbias_sam_both.sh.
24
+ INTERVENTION="both"
25
+ ATTN_LAYERS_TEXT=17
26
+ ATTN_KEY_BIAS_TEXT=3.0
27
+ ATTN_NONKEY_BIAS_TEXT=-3.0
28
+ ATTN_LAYERS_VIS=17
29
+ ATTN_KEY_BIAS_VIS=3.0
30
+ ATTN_NONKEY_BIAS_VIS=-3.0
31
+
32
+ AUCTION_TOTAL_RATIO=0.7
33
+ AUCTION_NEG_RATIO=0.7
34
+
35
+ MAX_SAMPLES=""
36
+
37
+ accelerate launch eval_attnbias_sam.py \
38
+ --data_path "$DATA_PATH" \
39
+ --model_path "$MODEL_PATH" \
40
+ --seed "$SEED" \
41
+ --max_new_tokens "$MAX_NEW_TOKENS" \
42
+ --output_path "$OUTPUT_PATH" \
43
+ --intervention "$INTERVENTION" \
44
+ --attn_layers_text "$ATTN_LAYERS_TEXT" \
45
+ --attn_key_bias_text "$ATTN_KEY_BIAS_TEXT" \
46
+ --attn_nonkey_bias_text "$ATTN_NONKEY_BIAS_TEXT" \
47
+ --attn_layers_vis "$ATTN_LAYERS_VIS" \
48
+ --attn_key_bias_vis "$ATTN_KEY_BIAS_VIS" \
49
+ --attn_nonkey_bias_vis "$ATTN_NONKEY_BIAS_VIS" \
50
+ --medsam3_config "$MEDSAM3_CONFIG" \
51
+ --medsam3_dir "$MEDSAM3_DIR" \
52
+ --auction_enable \
53
+ --auction_total_ratio "$AUCTION_TOTAL_RATIO" \
54
+ --auction_neg_ratio "$AUCTION_NEG_RATIO" \
55
+ --ablation_random_text \
56
+ --ablation_random_vis \
57
+ ${MAX_SAMPLES:+--max_samples "$MAX_SAMPLES"}
之前的代码版本/HuatuoGPT-Vision/run_eval_attnbias_sam_both_suppress_only.sh ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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_suppress_only"
7
+
8
+ SEED=42
9
+ MAX_NEW_TOKENS=256
10
+
11
+ MEDSAM3_CONFIG="/home/jinhua/ExplainableVQA/HuatuoGPT-Vision/MedSAM3/configs/full_lora_config.yaml"
12
+ MEDSAM3_DIR="/home/jinhua/ExplainableVQA/HuatuoGPT-Vision/MedSAM3"
13
+
14
+ # Ablation: suppress-only. nonkey_bias_* keeps the negative bias (distractors
15
+ # suppressed), but key_bias_* is 0 instead of positive -- isolates how much of
16
+ # the "both" result comes from suppressing non-keyword text / non-SAM visual
17
+ # patches, with no amplification of the key set. Auction stays ON with the
18
+ # same ratio/alpha/beta as run_eval_attnbias_sam_both.sh, so this differs from
19
+ # "both" by exactly one factor (key_bias_*); compare against
20
+ # run_eval_attnbias_sam_both_amplify_only.sh (same setup, opposite side
21
+ # zeroed) and run_eval_attnbias_sam_both.sh.
22
+ INTERVENTION="both"
23
+ ATTN_LAYERS_TEXT=17
24
+ ATTN_KEY_BIAS_TEXT=0.0
25
+ ATTN_NONKEY_BIAS_TEXT=-3.0
26
+ ATTN_LAYERS_VIS=17
27
+ ATTN_KEY_BIAS_VIS=0.0
28
+ ATTN_NONKEY_BIAS_VIS=-3.0
29
+
30
+ AUCTION_TOTAL_RATIO=0.7
31
+ AUCTION_NEG_RATIO=0.7
32
+
33
+ MAX_SAMPLES=""
34
+
35
+ accelerate launch eval_attnbias_sam.py \
36
+ --data_path "$DATA_PATH" \
37
+ --model_path "$MODEL_PATH" \
38
+ --seed "$SEED" \
39
+ --max_new_tokens "$MAX_NEW_TOKENS" \
40
+ --output_path "$OUTPUT_PATH" \
41
+ --intervention "$INTERVENTION" \
42
+ --attn_layers_text "$ATTN_LAYERS_TEXT" \
43
+ --attn_key_bias_text "$ATTN_KEY_BIAS_TEXT" \
44
+ --attn_nonkey_bias_text "$ATTN_NONKEY_BIAS_TEXT" \
45
+ --attn_layers_vis "$ATTN_LAYERS_VIS" \
46
+ --attn_key_bias_vis "$ATTN_KEY_BIAS_VIS" \
47
+ --attn_nonkey_bias_vis "$ATTN_NONKEY_BIAS_VIS" \
48
+ --medsam3_config "$MEDSAM3_CONFIG" \
49
+ --medsam3_dir "$MEDSAM3_DIR" \
50
+ --auction_enable \
51
+ --auction_total_ratio "$AUCTION_TOTAL_RATIO" \
52
+ --auction_neg_ratio "$AUCTION_NEG_RATIO" \
53
+ ${MAX_SAMPLES:+--max_samples "$MAX_SAMPLES"}
之前的代码版本/HuatuoGPT-Vision/run_eval_attnbias_sam_none.sh ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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_none"
7
+
8
+ SEED=42
9
+ MAX_NEW_TOKENS=256
10
+
11
+ MEDSAM3_CONFIG="/home/jinhua/ExplainableVQA/HuatuoGPT-Vision/MedSAM3/configs/full_lora_config.yaml"
12
+ MEDSAM3_DIR="/home/jinhua/ExplainableVQA/HuatuoGPT-Vision/MedSAM3"
13
+
14
+ # none: no attention intervention (model_output reuses plain inference result)
15
+ INTERVENTION="none"
16
+ ATTN_LAYERS_TEXT="17"
17
+ ATTN_KEY_BIAS_TEXT=3.0
18
+ ATTN_NONKEY_BIAS_TEXT=-3.0
19
+ ATTN_LAYERS_VIS="17"
20
+ ATTN_KEY_BIAS_VIS=3.0
21
+ ATTN_NONKEY_BIAS_VIS=-3.0
22
+
23
+ MAX_SAMPLES=""
24
+
25
+ accelerate launch eval_attnbias_sam.py \
26
+ --data_path "$DATA_PATH" \
27
+ --model_path "$MODEL_PATH" \
28
+ --seed "$SEED" \
29
+ --max_new_tokens "$MAX_NEW_TOKENS" \
30
+ --output_path "$OUTPUT_PATH" \
31
+ --intervention "$INTERVENTION" \
32
+ --attn_layers_text "$ATTN_LAYERS_TEXT" \
33
+ --attn_key_bias_text "$ATTN_KEY_BIAS_TEXT" \
34
+ --attn_nonkey_bias_text "$ATTN_NONKEY_BIAS_TEXT" \
35
+ --attn_layers_vis "$ATTN_LAYERS_VIS" \
36
+ --attn_key_bias_vis "$ATTN_KEY_BIAS_VIS" \
37
+ --attn_nonkey_bias_vis "$ATTN_NONKEY_BIAS_VIS" \
38
+ --medsam3_config "$MEDSAM3_CONFIG" \
39
+ --medsam3_dir "$MEDSAM3_DIR" \
40
+ ${MAX_SAMPLES:+--max_samples "$MAX_SAMPLES"}
之前的代码版本/HuatuoGPT-Vision/run_eval_attnbias_sam_text.sh ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ # Modality ablation: text-only. Only the scispaCy keyword text positions get
12
+ # biased (key_bias_text / nonkey_bias_text); the vis side is forced to 0 bias
13
+ # inside _make_attn_ctx regardless of what's passed here. SAM/MedSAM3 is
14
+ # skipped entirely (_needs_sam is False for "text"), so no medsam3_* args.
15
+ # Auction stays ON with the same ratio/alpha/beta as run_eval_attnbias_sam_both.sh
16
+ # (clear_market sizes its budget off only the text-side candidate pool here,
17
+ # since vis_enabled=False when intervention=="text" -- see clear_market's
18
+ # text_enabled/vis_enabled params), so this differs from "both" by exactly one
19
+ # factor (modality); compare against run_eval_attnbias_sam_vis.sh and
20
+ # run_eval_attnbias_sam_both.sh.
21
+ INTERVENTION="text"
22
+ ATTN_LAYERS_TEXT=17
23
+ ATTN_KEY_BIAS_TEXT=3.0
24
+ ATTN_NONKEY_BIAS_TEXT=-3.0
25
+ ATTN_LAYERS_VIS="17"
26
+
27
+ AUCTION_TOTAL_RATIO=0.7
28
+ AUCTION_NEG_RATIO=0.7
29
+
30
+ MAX_SAMPLES=""
31
+
32
+ accelerate launch eval_attnbias_sam.py \
33
+ --data_path "$DATA_PATH" \
34
+ --model_path "$MODEL_PATH" \
35
+ --seed "$SEED" \
36
+ --max_new_tokens "$MAX_NEW_TOKENS" \
37
+ --output_path "$OUTPUT_PATH" \
38
+ --intervention "$INTERVENTION" \
39
+ --attn_layers_text "$ATTN_LAYERS_TEXT" \
40
+ --attn_key_bias_text "$ATTN_KEY_BIAS_TEXT" \
41
+ --attn_nonkey_bias_text "$ATTN_NONKEY_BIAS_TEXT" \
42
+ --attn_layers_vis "$ATTN_LAYERS_VIS" \
43
+ --auction_enable \
44
+ --auction_total_ratio "$AUCTION_TOTAL_RATIO" \
45
+ --auction_neg_ratio "$AUCTION_NEG_RATIO" \
46
+ ${MAX_SAMPLES:+--max_samples "$MAX_SAMPLES"}
之前的代码版本/HuatuoGPT-Vision/run_eval_attnbias_sam_vis.sh ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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_vis"
7
+
8
+ SEED=42
9
+ MAX_NEW_TOKENS=256
10
+
11
+ MEDSAM3_CONFIG="/home/jinhua/ExplainableVQA/HuatuoGPT-Vision/MedSAM3/configs/full_lora_config.yaml"
12
+ MEDSAM3_DIR="/home/jinhua/ExplainableVQA/HuatuoGPT-Vision/MedSAM3"
13
+
14
+ # Modality ablation: vis-only. Only the SAM bbox patches get biased
15
+ # (key_bias_vis / nonkey_bias_vis); the text side is forced to 0 bias inside
16
+ # _make_attn_ctx regardless of what's passed here. SAM/MedSAM3 still runs
17
+ # (_needs_sam is True for "vis"). Auction stays ON with the same
18
+ # ratio/alpha/beta as run_eval_attnbias_sam_both.sh (clear_market sizes its
19
+ # budget off only the vis-side candidate pool here, since text_enabled=False
20
+ # when intervention=="vis" -- see clear_market's text_enabled/vis_enabled
21
+ # params), so this differs from "both" by exactly one factor (modality);
22
+ # compare against run_eval_attnbias_sam_text.sh and run_eval_attnbias_sam_both.sh.
23
+ INTERVENTION="vis"
24
+ ATTN_LAYERS_TEXT=17
25
+ ATTN_LAYERS_VIS=17
26
+ ATTN_KEY_BIAS_VIS=3.0
27
+ ATTN_NONKEY_BIAS_VIS=-3.0
28
+
29
+ AUCTION_TOTAL_RATIO=0.7
30
+ AUCTION_NEG_RATIO=0.7
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
+ --output_path "$OUTPUT_PATH" \
40
+ --intervention "$INTERVENTION" \
41
+ --attn_layers_text "$ATTN_LAYERS_TEXT" \
42
+ --attn_layers_vis "$ATTN_LAYERS_VIS" \
43
+ --attn_key_bias_vis "$ATTN_KEY_BIAS_VIS" \
44
+ --attn_nonkey_bias_vis "$ATTN_NONKEY_BIAS_VIS" \
45
+ --medsam3_config "$MEDSAM3_CONFIG" \
46
+ --medsam3_dir "$MEDSAM3_DIR" \
47
+ --auction_enable \
48
+ --auction_total_ratio "$AUCTION_TOTAL_RATIO" \
49
+ --auction_neg_ratio "$AUCTION_NEG_RATIO" \
50
+ ${MAX_SAMPLES:+--max_samples "$MAX_SAMPLES"}
之前的代码版本/HuatuoGPT-Vision/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/sync_attn_params.py ADDED
@@ -0,0 +1,116 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Sync the best attention-bias hyperparameters (layers + key/nonkey bias for
3
+ text and vis) across all run_eval_attnbias_sam_*.sh ablation scripts, so a
4
+ single grid-search result doesn't have to be hand-copied into 8 files.
5
+
6
+ Two scripts intentionally keep one side pinned at 0 as part of what they're
7
+ ablating, and must NOT be overwritten on that side:
8
+ - run_eval_attnbias_sam_both_amplify_only.sh : ATTN_NONKEY_BIAS_{TEXT,VIS} stay 0
9
+ - run_eval_attnbias_sam_both_suppress_only.sh: ATTN_KEY_BIAS_{TEXT,VIS} stay 0
10
+ run_eval_attnbias_sam_none.sh has no attention-bias variables and is skipped.
11
+
12
+ Usage:
13
+ python sync_attn_params.py --layers_text 17 --key_bias_text 4.0 --nonkey_bias_text -4.0 \\
14
+ --layers_vis 17 --key_bias_vis 1.0 --nonkey_bias_vis -1.0
15
+ python sync_attn_params.py --layers_text 17 --key_bias_text 4.0 --nonkey_bias_text -4.0 \\
16
+ --layers_vis 17 --key_bias_vis 1.0 --nonkey_bias_vis -1.0 --dry_run
17
+ """
18
+ import argparse
19
+ import glob
20
+ import os
21
+ import re
22
+
23
+ SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
24
+
25
+ # variable name -> argparse dest
26
+ VARS = {
27
+ "ATTN_LAYERS_TEXT": "layers_text",
28
+ "ATTN_KEY_BIAS_TEXT": "key_bias_text",
29
+ "ATTN_NONKEY_BIAS_TEXT": "nonkey_bias_text",
30
+ "ATTN_LAYERS_VIS": "layers_vis",
31
+ "ATTN_KEY_BIAS_VIS": "key_bias_vis",
32
+ "ATTN_NONKEY_BIAS_VIS": "nonkey_bias_vis",
33
+ }
34
+
35
+ # files where one side must stay pinned at 0 -- those variables are skipped
36
+ PINNED_ZERO = {
37
+ "run_eval_attnbias_sam_both_amplify_only.sh": {"ATTN_NONKEY_BIAS_TEXT", "ATTN_NONKEY_BIAS_VIS"},
38
+ "run_eval_attnbias_sam_both_suppress_only.sh": {"ATTN_KEY_BIAS_TEXT", "ATTN_KEY_BIAS_VIS"},
39
+ }
40
+
41
+ SKIP_FILES = {"run_eval_attnbias_sam_none.sh"}
42
+
43
+ # text-only / vis-only scripts don't set the other side's bias vars at all
44
+ # (they're forced to 0 inside eval_attnbias_sam.py regardless) -- only sync
45
+ # the side that's actually present in the file.
46
+ ONE_SIDED_FILES = {
47
+ "run_eval_attnbias_sam_text.sh": {"ATTN_LAYERS_VIS", "ATTN_KEY_BIAS_VIS", "ATTN_NONKEY_BIAS_VIS"},
48
+ "run_eval_attnbias_sam_vis.sh": {"ATTN_KEY_BIAS_TEXT", "ATTN_NONKEY_BIAS_TEXT"},
49
+ }
50
+
51
+
52
+ def sync_file(path, values, dry_run):
53
+ fname = os.path.basename(path)
54
+ if fname in SKIP_FILES:
55
+ return 0
56
+
57
+ with open(path, "r", encoding="utf-8") as f:
58
+ content = f.read()
59
+
60
+ skip_vars = PINNED_ZERO.get(fname, set()) | ONE_SIDED_FILES.get(fname, set())
61
+
62
+ n_changed = 0
63
+ for var, dest in VARS.items():
64
+ if var not in content or var in skip_vars or dest not in values:
65
+ continue
66
+ new_val = values[dest]
67
+ pattern = re.compile(rf'^({re.escape(var)}=)(.*)$', re.MULTILINE)
68
+
69
+ def _replace(m, new_val=new_val):
70
+ return f"{m.group(1)}{new_val}"
71
+
72
+ new_content, count = pattern.subn(_replace, content)
73
+ if count:
74
+ content = new_content
75
+ n_changed += count
76
+
77
+ if n_changed and not dry_run:
78
+ with open(path, "w", encoding="utf-8") as f:
79
+ f.write(content)
80
+ return n_changed
81
+
82
+
83
+ def main():
84
+ p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
85
+ p.add_argument("--layers_text", type=str, default=None)
86
+ p.add_argument("--key_bias_text", type=str, default=None)
87
+ p.add_argument("--nonkey_bias_text", type=str, default=None)
88
+ p.add_argument("--layers_vis", type=str, default=None)
89
+ p.add_argument("--key_bias_vis", type=str, default=None)
90
+ p.add_argument("--nonkey_bias_vis", type=str, default=None)
91
+ p.add_argument("--dry_run", action="store_true", default=False,
92
+ help="print what would change, without writing files")
93
+ args = p.parse_args()
94
+
95
+ values = {k: v for k, v in vars(args).items() if k != "dry_run" and v is not None}
96
+ if not values:
97
+ p.error("provide at least one of --layers_text/--key_bias_text/... to sync")
98
+
99
+ sh_files = sorted(glob.glob(os.path.join(SCRIPT_DIR, "run_eval_attnbias_sam_*.sh")))
100
+ total = 0
101
+ for path in sh_files:
102
+ fname = os.path.basename(path)
103
+ n = sync_file(path, values, args.dry_run)
104
+ total += n
105
+ if n:
106
+ tag = " (dry-run)" if args.dry_run else ""
107
+ print(f"[sync]{tag} {fname}: updated {n} variable(s)")
108
+ elif fname not in SKIP_FILES:
109
+ print(f"[sync] {fname}: no matching variables (skipped/pinned)")
110
+
111
+ print(f"[sync] done, {total} variable assignment(s) {'would be ' if args.dry_run else ''}updated "
112
+ f"across {len(sh_files)} file(s)")
113
+
114
+
115
+ if __name__ == "__main__":
116
+ main()
之前的代码版本/HuatuoGPT-Vision/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)
之前的代码版本/注意力关键词用于sam的/MedEvalKit/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)
之前的代码版本/注意力关键词用于sam的/MedEvalKit/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)