Master-Shi commited on
Commit
ecb25ed
·
verified ·
1 Parent(s): 1f83130

Add files using upload-large-folder tool

Browse files
HuatuoGPT-Vision-Abla/HuatuoGPT-Vision-7B_medical_multimodel_evaluation_data_result.json ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "OmniMedVQA": 0.7396619920891766,
3
+ "PMC-VQA_test": 0.5405,
4
+ "PathVQA_test": 0.5758477096966091,
5
+ "SLAKE_test": 0.7668269230769231,
6
+ "VQA-RAD_test": 0.5936254980079682,
7
+ "MMMU_Medical_Validation": 0.5448275862068965,
8
+ "The total score for multiple-choice questions": 0.6816973060469419,
9
+ "OmniMedVQA_MR (Mag-netic Resonance Imaging)": 0.725,
10
+ "OmniMedVQA_ultrasound": 0.7799113737075333,
11
+ "OmniMedVQA_OCT (Optical Coherence Tomography": 0.8701754385964913,
12
+ "OmniMedVQA_Dermoscopy": 0.707286432160804,
13
+ "OmniMedVQA_CT(Computed Tomography)": 0.6519337016574586,
14
+ "OmniMedVQA_X-Ray": 0.8007850834151129,
15
+ "OmniMedVQA_Microscopy Images": 0.7623626373626373,
16
+ "OmniMedVQA_Fundus Photography": 0.8226837060702875,
17
+ "MMMU_Medical_Validation_validation_Public_Health": 0.5333333333333333,
18
+ "MMMU_Medical_Validation_validation_Diagnostics_and_Laboratory_Medicine": 0.4,
19
+ "MMMU_Medical_Validation_validation_Pharmacy": 0.5185185185185185,
20
+ "MMMU_Medical_Validation_validation_Basic_Medical_Science": 0.6071428571428571,
21
+ "MMMU_Medical_Validation_validation_Clinical_Medicine": 0.6666666666666666
22
+ }
HuatuoGPT-Vision-Abla/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-Abla/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-Abla/eval.py ADDED
@@ -0,0 +1,183 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ if accelerator.num_processes > 1:
142
+ all_data = [None] * dist.get_world_size()
143
+ dist.all_gather_object(all_data, cache_data)
144
+ all_data = [item for sublist in all_data for item in sublist]
145
+ else:
146
+ # single-process run (accelerate launch --num_processes=1): torch.distributed's
147
+ # default process group is never initialized in this mode, so dist.get_world_size()/
148
+ # dist.all_gather_object would raise "Default process group has not been initialized"
149
+ # -- there is only one rank's data to begin with, so just use it directly.
150
+ all_data = cache_data
151
+
152
+ for d in all_data:
153
+ ress.append(d)
154
+
155
+ if accelerator.is_main_process:
156
+ task_name = os.path.basename(args.model_path) + f'_{os.path.split(args.data_path)[-1].replace(".json","")}'
157
+ out_file = f'./{task_name}.json'
158
+ with open(out_file,'w') as fw:
159
+ json.dump(ress,fw,ensure_ascii=False,indent=2)
160
+ print(f'test results: {out_file}')
161
+ print(f'question num: {len(ress)}')
162
+ val_res = score_mix_llava(ress)
163
+ outstr = json.dumps(val_res,ensure_ascii=False,indent = 2)
164
+ accelerator.print(outstr)
165
+ with open(f'{task_name}_result.json','w') as fw:
166
+ json.dump(val_res,fw,ensure_ascii=False,indent=2)
167
+
168
+ if __name__ == '__main__':
169
+ parser = argparse.ArgumentParser(description='Args of sft')
170
+
171
+ # Model Args
172
+ parser.add_argument('--data_path', default='medical_multimodel_evaluation_data.json', type=str)
173
+ parser.add_argument('--model_path', default='HuatuoGPT-Vision-7B', type=str)
174
+ parser.add_argument('--max_new_tokens', default=256, type=int)
175
+ parser.add_argument('--batch_size', default=2, type=int)
176
+
177
+ # Other Args
178
+ parser.add_argument('--seed', default=42, type=int)
179
+
180
+ args = parser.parse_args()
181
+
182
+ set_seed(args.seed)
183
+ test(args)
HuatuoGPT-Vision-Abla/eval_attnbias_sam.py ADDED
The diff for this file is too large to render. See raw diff
 
HuatuoGPT-Vision-Abla/full_pipeline_gpu0.log ADDED
@@ -0,0 +1 @@
 
 
1
+ nohup: ignoring input
HuatuoGPT-Vision-Abla/llava/model/__pycache__/llava_arch.cpython-310.pyc ADDED
Binary file (13.9 kB). View file
 
HuatuoGPT-Vision-Abla/llava/model/language_model/__pycache__/llava_qwen2.cpython-310.pyc ADDED
Binary file (3.95 kB). View file
 
HuatuoGPT-Vision-Abla/llava/model/language_model/llava_qwen2.py ADDED
@@ -0,0 +1,168 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023 Haotian Liu
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ # import sys
16
+ # sys.path.insert(0, '/opt/conda/lib/python3.10')
17
+ # print(sys.path)
18
+ from typing import List, Optional, Tuple, Union
19
+
20
+ import torch
21
+ import torch.nn as nn
22
+
23
+ from transformers import AutoConfig, AutoModelForCausalLM, AutoTokenizer, \
24
+ Qwen2ForCausalLM, Qwen2Config, Qwen2Model \
25
+
26
+ from transformers.modeling_outputs import CausalLMOutputWithPast
27
+
28
+ from ..llava_arch import LlavaMetaModel, LlavaMetaForCausalLM
29
+
30
+
31
+ class LlavaQwenConfig(Qwen2Config):
32
+ model_type = "llava_qwen2"
33
+
34
+
35
+ class LlavaQwen2Model(LlavaMetaModel, Qwen2Model):
36
+ config_class = LlavaQwenConfig
37
+
38
+ def __init__(self, config: Qwen2Config):
39
+ super(LlavaQwen2Model, self).__init__(config)
40
+
41
+
42
+ class LlavaQwen2ForCausalLM(Qwen2ForCausalLM, LlavaMetaForCausalLM):
43
+ config_class = LlavaQwenConfig
44
+
45
+ def __init__(self, config, init_vision_encoder_from_ckpt=False):
46
+ # config._attn_implementation = "flash_attention_2"
47
+ # config._flash_attn_2_enabled = True
48
+ super(Qwen2ForCausalLM, self).__init__(config)
49
+ self.model = LlavaQwen2Model(config)
50
+ # assert self.model._use_flash_attention_2 == True
51
+ # self.tokenizer = AutoTokenizer.from_pretrained(config._name_or_path,padding_side="left")
52
+ self.tokenizer = None
53
+ # self.pretraining_tp = config.pretraining_tp
54
+ self.vocab_size = config.vocab_size
55
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
56
+
57
+ # if getattr(config, 'init_vision_encoder_from_ckpt', True):
58
+ if init_vision_encoder_from_ckpt:
59
+ vision_tower = self.get_vision_tower()
60
+ print(f'loading from CLIP first. This should only be used at inference!!!')
61
+ vision_tower.load_model() #
62
+
63
+ # Initialize weights and apply final processing
64
+ self.post_init()
65
+
66
+ def get_model(self):
67
+ return self.model
68
+
69
+ def get_tokenizer(self):
70
+ return self.tokenizer
71
+
72
+ def forward(
73
+ self,
74
+ input_ids: torch.LongTensor = None,
75
+ attention_mask: Optional[torch.Tensor] = None,
76
+ position_ids: Optional[torch.LongTensor] = None,
77
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
78
+ inputs_embeds: Optional[torch.FloatTensor] = None,
79
+ labels: Optional[torch.LongTensor] = None,
80
+ use_cache: Optional[bool] = None,
81
+ output_attentions: Optional[bool] = None,
82
+ output_hidden_states: Optional[bool] = None,
83
+ images: Optional[torch.FloatTensor] = None,
84
+ return_dict: Optional[bool] = None,
85
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
86
+
87
+ if inputs_embeds is None:
88
+ (
89
+ input_ids,
90
+ position_ids,
91
+ attention_mask,
92
+ past_key_values,
93
+ inputs_embeds,
94
+ labels
95
+ # ) = self.prepare_inputs_labels_for_multimodal(
96
+ ) = self.prepare_inputs_labels_for_multimodal_new(
97
+ input_ids,
98
+ position_ids,
99
+ attention_mask,
100
+ past_key_values,
101
+ labels,
102
+ images
103
+ )
104
+
105
+ return super().forward(
106
+ input_ids=input_ids,
107
+ attention_mask=attention_mask,
108
+ position_ids=position_ids,
109
+ past_key_values=past_key_values,
110
+ inputs_embeds=inputs_embeds,
111
+ labels=labels,
112
+ use_cache=use_cache,
113
+ output_attentions=output_attentions,
114
+ output_hidden_states=output_hidden_states,
115
+ return_dict=return_dict
116
+ )
117
+
118
+ @torch.no_grad()
119
+ def generate(
120
+ self,
121
+ inputs: Optional[torch.Tensor] = None,
122
+ images: Optional[torch.Tensor] = None,
123
+ **kwargs,
124
+ ) :
125
+ position_ids = kwargs.pop("position_ids", None)
126
+ attention_mask = kwargs.pop("attention_mask", None)
127
+ if "inputs_embeds" in kwargs:
128
+ raise NotImplementedError("`inputs_embeds` is not supported")
129
+
130
+ if images is not None:
131
+ (
132
+ inputs,
133
+ position_ids,
134
+ attention_mask,
135
+ _,
136
+ inputs_embeds,
137
+ _
138
+ ) = self.prepare_inputs_labels_for_multimodal_new(
139
+ inputs,
140
+ position_ids,
141
+ attention_mask,
142
+ None,
143
+ None,
144
+ images
145
+ )
146
+ else:
147
+ inputs_embeds = self.get_model().embed_tokens(inputs)
148
+
149
+ # print(inputs_embeds.shape)
150
+ return super().generate(
151
+ position_ids=None,
152
+ attention_mask=None,
153
+ inputs_embeds=inputs_embeds,
154
+ **kwargs
155
+ )
156
+
157
+ def prepare_inputs_for_generation(self, input_ids, past_key_values=None, inputs_embeds=None, **kwargs):
158
+ images = kwargs.pop("images", None)
159
+ _inputs = super().prepare_inputs_for_generation(
160
+ input_ids, past_key_values=past_key_values, inputs_embeds=inputs_embeds, **kwargs
161
+ )
162
+ if images is not None:
163
+ _inputs['images'] = images
164
+ return _inputs
165
+
166
+ # AutoConfig.register("llava", LlavaQwenConfig)
167
+ AutoConfig.register("llava_qwen2", LlavaQwenConfig)
168
+ AutoModelForCausalLM.register(LlavaQwenConfig, LlavaQwen2ForCausalLM)
HuatuoGPT-Vision-Abla/llava/model/multimodal_projector/__pycache__/builder.cpython-310.pyc ADDED
Binary file (2.04 kB). View file
 
HuatuoGPT-Vision-Abla/llava/model/multimodal_projector/builder.py ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ import re
4
+
5
+
6
+ class IdentityMap(nn.Module):
7
+ def __init__(self):
8
+ super().__init__()
9
+
10
+ def forward(self, x, *args, **kwargs):
11
+ return x
12
+
13
+ @property
14
+ def config(self):
15
+ return {"mm_projector_type": 'identity'}
16
+
17
+
18
+ class SimpleResBlock(nn.Module):
19
+ def __init__(self, channels):
20
+ super().__init__()
21
+ self.pre_norm = nn.LayerNorm(channels)
22
+
23
+ self.proj = nn.Sequential(
24
+ nn.Linear(channels, channels),
25
+ nn.GELU(),
26
+ nn.Linear(channels, channels)
27
+ )
28
+ def forward(self, x):
29
+ x = self.pre_norm(x)
30
+ return x + self.proj(x)
31
+
32
+
33
+ def build_vision_projector(config, delay_load=False, **kwargs):
34
+ projector_type = getattr(config, 'mm_projector_type', 'linear')
35
+
36
+ if projector_type == 'linear':
37
+ return nn.Linear(config.mm_hidden_size, config.hidden_size)
38
+
39
+ mlp_gelu_match = re.match(r'^mlp(\d+)x_gelu$', projector_type)
40
+ if mlp_gelu_match:
41
+ mlp_depth = int(mlp_gelu_match.group(1))
42
+ modules = [nn.Linear(config.mm_hidden_size, config.hidden_size)]
43
+ for _ in range(1, mlp_depth):
44
+ modules.append(nn.GELU())
45
+ modules.append(nn.Linear(config.hidden_size, config.hidden_size))
46
+ return nn.Sequential(*modules)
47
+
48
+ if projector_type == 'identity':
49
+ return IdentityMap()
50
+
51
+ raise ValueError(f'Unknown projector type: {projector_type}')
HuatuoGPT-Vision-Abla/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-Abla/results_attnbias/HuatuoGPT-Vision-7B/sam_vis/HuatuoGPT-Vision-7B_medical_multimodel_evaluation_data_vis_Lt17_kt0.0_nt0.0_Lv17_kv1.0_nv0.0_result.json ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "OmniMedVQA": 0.7444264653002517,
3
+ "PMC-VQA_test": 0.5475,
4
+ "PathVQA_test": 0.5847709696609161,
5
+ "SLAKE_test": 0.7475961538461539,
6
+ "VQA-RAD_test": 0.6135458167330677,
7
+ "MMMU_Medical_Validation": 0.5241379310344828,
8
+ "The total score for multiple-choice questions": 0.6869580298300382,
9
+ "OmniMedVQA_MR (Mag-netic Resonance Imaging)": 0.7309405940594059,
10
+ "OmniMedVQA_ultrasound": 0.7740029542097489,
11
+ "OmniMedVQA_OCT (Optical Coherence Tomography": 0.8614035087719298,
12
+ "OmniMedVQA_Dermoscopy": 0.7185929648241206,
13
+ "OmniMedVQA_CT(Computed Tomography)": 0.6569563033651431,
14
+ "OmniMedVQA_X-Ray": 0.8056918547595682,
15
+ "OmniMedVQA_Microscopy Images": 0.7802197802197802,
16
+ "OmniMedVQA_Fundus Photography": 0.8306709265175719,
17
+ "MMMU_Medical_Validation_validation_Public_Health": 0.4666666666666667,
18
+ "MMMU_Medical_Validation_validation_Diagnostics_and_Laboratory_Medicine": 0.36666666666666664,
19
+ "MMMU_Medical_Validation_validation_Pharmacy": 0.48148148148148145,
20
+ "MMMU_Medical_Validation_validation_Basic_Medical_Science": 0.5714285714285714,
21
+ "MMMU_Medical_Validation_validation_Clinical_Medicine": 0.7333333333333333
22
+ }
HuatuoGPT-Vision-Abla/results_attnbias/HuatuoGPT-Vision-7B/sam_vis/_snapshot/run_ablation_grid_pick.sh ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ cd "$(dirname "$0")"
3
+
4
+ # Picks the best (strength_text, strength_vis) across the full grid and syncs
5
+ # it into every run_eval_attnbias_sam_*.sh via sync_attn_params.py. Run this
6
+ # ONCE, by hand, after every run_ablation_grid_worker.sh slice (on every GPU
7
+ # you split the grid across) has finished -- it requires *all* combos'
8
+ # *_result.json to be present, since the "best" choice isn't meaningful until
9
+ # the whole grid has been scored.
10
+ #
11
+ # FINAL METHOD = run_eval_attnbias_sam_both.sh: nonkey_bias is
12
+ # pinned at 0 (amplify_only -- boost key regions only, no suppression) AND the
13
+ # grid was searched with the auction mechanism OFF (see
14
+ # run_ablation_grid_worker.sh), matching the final method exactly.
15
+ # run_eval_attnbias_sam_both_suppress_only.sh has been dropped from
16
+ # run_all_attnbias_sam.sh's comparison set (no longer a live ablation arm), so
17
+ # there's no risk of this sync corrupting it.
18
+ set -e
19
+
20
+ source /home/jinhua/miniconda3/etc/profile.d/conda.sh
21
+ conda activate huatuovision
22
+
23
+ LAYER=17
24
+ # must stay identical to run_ablation_grid_worker.sh's copy of these arrays.
25
+ STRENGTHS_TEXT=(1.0 2.0 3.0 4.0 5.0)
26
+ STRENGTHS_VIS=(1.0 2.0 3.0 4.0 5.0)
27
+
28
+ # ── pick the best (s_text, s_vis) across the full grid, layer fixed at 17.
29
+ # Each combo's output dir holds exactly one *_result.json (eval_attnbias_sam.py's hparam_tag
30
+ # already makes the filename unique per layer/strength/auction config, so
31
+ # no risk of stale files from a previous combo lingering in the same dir),
32
+ # so glob for it directly instead of hand-reconstructing the filename --
33
+ # that reconstruction is what broke last time hparam_tag's format changed.
34
+ BEST_S_TEXT=""
35
+ BEST_S_VIS=""
36
+ BEST_SCORE=""
37
+ for S_TEXT in "${STRENGTHS_TEXT[@]}"; do
38
+ for S_VIS in "${STRENGTHS_VIS[@]}"; do
39
+ OUTPUT_PATH="results_attnbias_ablation/HuatuoGPT-Vision-7B/sam_both_amplify_noauction_layer${LAYER}_stext${S_TEXT}_svis${S_VIS}"
40
+ RESULT_F=$(ls "$OUTPUT_PATH"/*_result.json 2>/dev/null | head -n1)
41
+ if [ -z "$RESULT_F" ]; then
42
+ echo "[ablation-grid-pick] missing *_result.json under $OUTPUT_PATH -- cannot pick best (s_text, s_vis). Did every run_ablation_grid_worker.sh slice finish?" >&2
43
+ exit 1
44
+ fi
45
+ SCORE=$(python -c "
46
+ import json
47
+ with open('$RESULT_F') as f:
48
+ d = json.load(f)
49
+ print(d['The total score for multiple-choice questions'])
50
+ ")
51
+ echo "[ablation-grid-pick] s_text=$S_TEXT s_vis=$S_VIS score=$SCORE"
52
+ if [ -z "$BEST_SCORE" ] || python -c "exit(0 if $SCORE > $BEST_SCORE else 1)"; then
53
+ BEST_SCORE="$SCORE"
54
+ BEST_S_TEXT="$S_TEXT"
55
+ BEST_S_VIS="$S_VIS"
56
+ fi
57
+ done
58
+ done
59
+
60
+ echo "[ablation-grid-pick] best overall: layer=$LAYER s_text=$BEST_S_TEXT s_vis=$BEST_S_VIS (score=$BEST_SCORE)"
61
+ echo "[ablation-grid-pick] syncing into every run_eval_attnbias_sam_*.sh via sync_attn_params.py"
62
+
63
+ python sync_attn_params.py \
64
+ --layers_text "$LAYER" --key_bias_text "$BEST_S_TEXT" --nonkey_bias_text "0" \
65
+ --layers_vis "$LAYER" --key_bias_vis "$BEST_S_VIS" --nonkey_bias_vis "0"
66
+
67
+ echo "[ablation-grid-pick] done. All run_eval_attnbias_sam_*.sh now use the ablation-selected layer/strength (nonkey_bias=0, amplify_only style)"
68
+ echo "[ablation-grid-pick] (amplify_only keeps its pinned-zero side; text.sh/vis.sh keep their single-modality side -- see sync_attn_params.py)."
HuatuoGPT-Vision-Abla/results_attnbias/HuatuoGPT-Vision-7B/sam_vis/_snapshot/run_eval_attnbias_sam_both.sh ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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-Abla/MedSAM3/configs/full_lora_config.yaml"
12
+ MEDSAM3_DIR="/home/jinhua/ExplainableVQA/HuatuoGPT-Vision-Abla/MedSAM3"
13
+
14
+ # FINAL METHOD: both mode, amplify-only (nonkey_bias pinned at 0 -- boost key
15
+ # regions, don't suppress anything else) and auction OFF -- every Stage1/SAM-
16
+ # detected key position gets boosted directly, not just an auction-selected
17
+ # subset (ablation found the auction mechanism doesn't help over this simpler
18
+ # design; see run_eval_attnbias_sam_both_noauction.sh, kept around for
19
+ # reference but no longer part of the active comparison set).
20
+ INTERVENTION="both"
21
+ ATTN_LAYERS_TEXT=17
22
+ ATTN_KEY_BIAS_TEXT=5.0
23
+ ATTN_NONKEY_BIAS_TEXT=0
24
+ ATTN_LAYERS_VIS=17
25
+ ATTN_KEY_BIAS_VIS=1.0
26
+ ATTN_NONKEY_BIAS_VIS=0
27
+
28
+ MAX_SAMPLES=""
29
+
30
+ accelerate launch --num_processes=1 eval_attnbias_sam.py \
31
+ --data_path "$DATA_PATH" \
32
+ --model_path "$MODEL_PATH" \
33
+ --seed "$SEED" \
34
+ --max_new_tokens "$MAX_NEW_TOKENS" \
35
+ --output_path "$OUTPUT_PATH" \
36
+ --intervention "$INTERVENTION" \
37
+ --attn_layers_text "$ATTN_LAYERS_TEXT" \
38
+ --attn_key_bias_text "$ATTN_KEY_BIAS_TEXT" \
39
+ --attn_nonkey_bias_text "$ATTN_NONKEY_BIAS_TEXT" \
40
+ --attn_layers_vis "$ATTN_LAYERS_VIS" \
41
+ --attn_key_bias_vis "$ATTN_KEY_BIAS_VIS" \
42
+ --attn_nonkey_bias_vis "$ATTN_NONKEY_BIAS_VIS" \
43
+ --medsam3_config "$MEDSAM3_CONFIG" \
44
+ --medsam3_dir "$MEDSAM3_DIR" \
45
+ ${MAX_SAMPLES:+--max_samples "$MAX_SAMPLES"}
HuatuoGPT-Vision-Abla/run_ablation_grid.sh ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ cd "$(dirname "$0")"
3
+
4
+ # Full grid search over (strength_text, strength_vis) for the "both"
5
+ # intervention mode WITH Budgeted Token Auction enabled, split across GPU 0
6
+ # and GPU 2 and run concurrently via run_ablation_grid_worker.sh (GPU 1/3 are
7
+ # occupied by other people's jobs on this workstation, so 0/2 are used
8
+ # instead of the usual 0/1 -- see run_eval.sh for the same reasoning). The bias
9
+ # layer is fixed at 17 for both modalities; text and vis each get their own
10
+ # strength sweep and every (strength_text, strength_vis) combination is run --
11
+ # kbt=nbt=-s_text, kbv=nbv=-s_vis for s_text in STRENGTHS_TEXT, s_vis in
12
+ # STRENGTHS_VIS. Stage1/SAM results are cached in eval_attnbias_sam.py (keyed
13
+ # on data_path/model_path/seed, see HuatuoGPT-Vision/cache/sam_stage1_cache/)
14
+ # and are independent of the bias layer/strength/auction args, so re-running
15
+ # a combo only re-pays the much cheaper bias-intervention generation pass.
16
+ # Auction budgets/alpha/beta are fixed at their defaults here -- this script
17
+ # only sweeps bias strength, not the auction hyperparameters themselves.
18
+ # Each combo writes to its own output dir under results_attnbias_ablation/, so
19
+ # this never touches results_attnbias/HuatuoGPT-Vision-7B/sam_both or any other
20
+ # previously saved result.
21
+ #
22
+ # NOTE: picking the best (s_text, s_vis) and syncing it into every
23
+ # run_eval_attnbias_sam_*.sh needs the WHOLE grid scored first, so it is
24
+ # NOT done here -- run ./run_ablation_grid_pick.sh by hand once this script
25
+ # (both GPU workers) finishes. STRENGTHS_TEXT/STRENGTHS_VIS/LAYER are defined
26
+ # independently in run_ablation_grid_worker.sh and run_ablation_grid_pick.sh;
27
+ # keep all three in sync if you change the grid.
28
+ #
29
+ # Pass 0 (keyword/Stage1/SAM extraction) in eval_attnbias_sam.py caches its
30
+ # output keyed only on (data_path, model_path, seed) -- every combo in this
31
+ # grid shares the exact same key, so both GPU workers would hit the *same*
32
+ # cache file. accelerator.wait_for_everyone() only synchronizes ranks within
33
+ # one `accelerate launch` process group; GPU0's and GPU2's workers are two
34
+ # fully independent processes with no cross-process coordination, so if both
35
+ # ran Pass 0 concurrently on a cold cache they'd race to read-modify-write the
36
+ # same JSON file (worst case: interleaved writes corrupt it; typical case:
37
+ # whichever finishes last silently clobbers the other's freshly-computed
38
+ # entries with the stale snapshot it read at startup) and both would
39
+ # redundantly re-run the expensive Stage1+SAM pass over the whole dataset.
40
+ # Fix: run ONE combo alone first (GPU 0, combo index 0) to fully populate the
41
+ # cache -- Pass 0 always covers the whole dataset regardless of which combo is
42
+ # running, so after this single warmup run every subsequent Pass 0 (on either
43
+ # GPU) is a pure cache hit and never writes to the file, making the parallel
44
+ # phase below race-free.
45
+ set -e
46
+
47
+ echo "[ablation-grid] warmup: running combo 0 alone on GPU 0 to populate the Pass0 cache before parallelizing"
48
+ ./run_ablation_grid_worker.sh 0 0 1 > ablation_grid_warmup.log 2>&1
49
+ echo "[ablation-grid] warmup done (log: ablation_grid_warmup.log)"
50
+
51
+ TOTAL=25 # len(STRENGTHS_TEXT) * len(STRENGTHS_VIS), see run_ablation_grid_worker.sh
52
+ SPLIT=13 # combos [1, SPLIT) -> GPU 0, combos [SPLIT, TOTAL) -> GPU 2
53
+ # combo 0 already ran during warmup above -- GPU0's parallel slice starts at
54
+ # index 1 (not 0) so it isn't touched again at all, not even via the
55
+ # OUTPUT_PATH-exists skip check.
56
+
57
+ echo "[ablation-grid] launching GPU 0 on combos [1, $SPLIT) and GPU 2 on combos [$SPLIT, $TOTAL) in parallel"
58
+
59
+ ./run_ablation_grid_worker.sh 0 1 $((SPLIT - 1)) > ablation_grid_gpu0.log 2>&1 &
60
+ PID0=$!
61
+ ./run_ablation_grid_worker.sh 2 "$SPLIT" $((TOTAL - SPLIT)) > ablation_grid_gpu2.log 2>&1 &
62
+ PID1=$!
63
+
64
+ echo "[ablation-grid] gpu0 worker pid=$PID0 (log: ablation_grid_gpu0.log), gpu2 worker pid=$PID1 (log: ablation_grid_gpu2.log)"
65
+
66
+ wait "$PID0"
67
+ STATUS0=$?
68
+ wait "$PID1"
69
+ STATUS1=$?
70
+
71
+ if [ "$STATUS0" -ne 0 ] || [ "$STATUS1" -ne 0 ]; then
72
+ echo "[ablation-grid] a worker failed (gpu0 exit=$STATUS0, gpu2 exit=$STATUS1) -- check ablation_grid_gpu{0,2}.log before running run_ablation_grid_pick.sh" >&2
73
+ exit 1
74
+ fi
75
+
76
+ echo "[ablation-grid] both workers finished, all $TOTAL combinations done"
77
+ echo "[ablation-grid] now run: ./run_ablation_grid_pick.sh"
HuatuoGPT-Vision-Abla/run_eval.sh ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ # 单卡跑,卡1/卡3被其他任务占用(其他人的进程),显式锁定卡0(确认空闲的卡)。
11
+ # Single GPU -- pin to GPU 0 explicitly (confirmed free; GPU 1/3 are occupied
12
+ # by other jobs on this workstation).
13
+ export CUDA_VISIBLE_DEVICES=0
14
+
15
+ accelerate launch --num_processes=1 eval.py \
16
+ --data_path "$DATA_PATH" \
17
+ --model_path "$MODEL_PATH" \
18
+ --seed "$SEED" \
19
+ --max_new_tokens "$MAX_NEW_TOKENS"
HuatuoGPT-Vision-Abla/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-Abla/MedSAM3/configs/full_lora_config.yaml"
12
+ MEDSAM3_DIR="/home/jinhua/ExplainableVQA/HuatuoGPT-Vision-Abla/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=0
26
+ ATTN_LAYERS_VIS=17
27
+ ATTN_KEY_BIAS_VIS=0.0
28
+ ATTN_NONKEY_BIAS_VIS=0
29
+
30
+ AUCTION_TOTAL_RATIO=0.8
31
+ AUCTION_NEG_RATIO=0.8
32
+
33
+ MAX_SAMPLES=""
34
+
35
+ accelerate launch --num_processes=1 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-Abla/run_eval_attnbias_sam_vis.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_vis"
7
+
8
+ SEED=42
9
+ MAX_NEW_TOKENS=256
10
+
11
+ MEDSAM3_CONFIG="/home/jinhua/ExplainableVQA/HuatuoGPT-Vision-Abla/MedSAM3/configs/full_lora_config.yaml"
12
+ MEDSAM3_DIR="/home/jinhua/ExplainableVQA/HuatuoGPT-Vision-Abla/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"). Matches run_eval_attnbias_sam_both.sh's
18
+ # mechanism (amplify-only, auction OFF) so this differs from the final method
19
+ # by exactly one factor (modality restricted to vis); compare against
20
+ # run_eval_attnbias_sam_text.sh and run_eval_attnbias_sam_both.sh.
21
+ INTERVENTION="vis"
22
+ ATTN_LAYERS_TEXT=17
23
+ ATTN_LAYERS_VIS=17
24
+ ATTN_KEY_BIAS_VIS=1.0
25
+ ATTN_NONKEY_BIAS_VIS=0
26
+
27
+ MAX_SAMPLES=""
28
+
29
+ accelerate launch --num_processes=1 eval_attnbias_sam.py \
30
+ --data_path "$DATA_PATH" \
31
+ --model_path "$MODEL_PATH" \
32
+ --seed "$SEED" \
33
+ --max_new_tokens "$MAX_NEW_TOKENS" \
34
+ --output_path "$OUTPUT_PATH" \
35
+ --intervention "$INTERVENTION" \
36
+ --attn_layers_text "$ATTN_LAYERS_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-Abla/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)