Master-Shi commited on
Commit
404f7be
·
verified ·
1 Parent(s): 0590cb3

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. 之前的代码版本/注意力关键词用于sam的/MedEvalKit/datas/Radrestruct/test_qa_pairs/1415.json +1 -0
  2. 之前的代码版本/注意力关键词用于sam的/MedEvalKit/datas/Radrestruct/test_qa_pairs/1552.json +1 -0
  3. 之前的代码版本/注意力关键词用于sam的/MedEvalKit/datas/Radrestruct/test_qa_pairs/194.json +1 -0
  4. 之前的代码版本/注意力关键词用于sam的/MedEvalKit/datas/Radrestruct/test_qa_pairs/2555.json +1 -0
  5. 之前的代码版本/注意力关键词用于sam的/MedEvalKit/datas/Radrestruct/test_qa_pairs/2861.json +1 -0
  6. 之前的代码版本/注意力关键词用于sam的/MedEvalKit/datas/Radrestruct/test_qa_pairs/3236.json +1 -0
  7. 之前的代码版本/注意力关键词用于sam的/MedEvalKit/datas/Radrestruct/test_qa_pairs/3465.json +1 -0
  8. 之前的代码版本/注意力关键词用于sam的/MedEvalKit/datas/Radrestruct/test_qa_pairs/3678.json +1 -0
  9. 之前的代码版本/注意力关键词用于sam的/MedEvalKit/datas/Radrestruct/test_qa_pairs/3954.json +1 -0
  10. 之前的代码版本/第一版-全部代码/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/llava/__init__.py +1 -0
  11. 之前的代码版本/第一版-全部代码/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/llava/constants.py +12 -0
  12. 之前的代码版本/第一版-全部代码/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/llava/conversation.py +597 -0
  13. 之前的代码版本/第一版-全部代码/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/llava/mm_utils.py +395 -0
  14. 之前的代码版本/第一版-全部代码/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/llava/model/__init__.py +16 -0
  15. 之前的代码版本/第一版-全部代码/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/llava/model/apply_delta.py +47 -0
  16. 之前的代码版本/第一版-全部代码/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/llava/model/builder.py +305 -0
  17. 之前的代码版本/第一版-全部代码/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/llava/model/consolidate.py +30 -0
  18. 之前的代码版本/第一版-全部代码/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/llava/model/llava_arch.py +597 -0
  19. 之前的代码版本/第一版-全部代码/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/llava/train/llama_flash_attn_monkey_patch.py +87 -0
  20. 之前的代码版本/第一版-全部代码/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/llava/train/llava_trainer.py +1305 -0
  21. 之前的代码版本/第一版-全部代码/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/llava/train/llava_trainer_eval.py +76 -0
  22. 之前的代码版本/第一版-全部代码/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/llava/train/train.py +1770 -0
  23. 之前的代码版本/第一版-全部代码/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/llava/train/train_dpo.py +1828 -0
  24. 之前的代码版本/第一版-全部代码/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/llava/train/train_mem.py +4 -0
  25. 之前的代码版本/第一版-全部代码/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/llava/utils.py +198 -0
  26. 之前的代码版本/第一版-全部代码/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/archived/convert_gqa_for_eval.py +18 -0
  27. 之前的代码版本/第一版-全部代码/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/archived/convert_mmvet_for_eval.py +18 -0
  28. 之前的代码版本/第一版-全部代码/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/archived/convert_sqa_to_llava.py +88 -0
  29. 之前的代码版本/第一版-全部代码/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/archived/convert_sqa_to_llava_base_prompt.py +298 -0
  30. 之前的代码版本/第一版-全部代码/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/archived/convert_vizwiz_for_submission.py +45 -0
  31. 之前的代码版本/第一版-全部代码/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/archived/convert_vqav2_for_submission.py +50 -0
  32. 之前的代码版本/第一版-全部代码/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/archived/data_info.py +124 -0
  33. 之前的代码版本/第一版-全部代码/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/archived/dpo_data_info.py +67 -0
  34. 之前的代码版本/第一版-全部代码/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/archived/entry_cmd.sh +30 -0
  35. 之前的代码版本/第一版-全部代码/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/archived/finetune.sh +95 -0
  36. 之前的代码版本/第一版-全部代码/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/archived/finetune_1.5.sh +99 -0
  37. 之前的代码版本/第一版-全部代码/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/archived/finetune_full_schedule.sh +46 -0
  38. 之前的代码版本/第一版-全部代码/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/archived/finetune_lora.sh +47 -0
  39. 之前的代码版本/第一版-全部代码/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/archived/finetune_mixtral.sh +96 -0
  40. 之前的代码版本/第一版-全部代码/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/archived/finetune_mixtral_1.5.sh +96 -0
  41. 之前的代码版本/第一版-全部代码/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/archived/finetune_mixtral_1.6_336px_anyres.sh +100 -0
  42. 之前的代码版本/第一版-全部代码/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/archived/finetune_mixtral_1.6_336px_anyres_freeze_vision.sh +97 -0
  43. 之前的代码版本/第一版-全部代码/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/archived/finetune_mixtral_1.6_336px_anyres_lmms_eval.sh +78 -0
  44. 之前的代码版本/第一版-全部代码/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/archived/finetune_mixtral_copy.sh +96 -0
  45. 之前的代码版本/第一版-全部代码/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/archived/finetune_qlora.sh +48 -0
  46. 之前的代码版本/第一版-全部代码/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/archived/finetune_sqa.sh +34 -0
  47. 之前的代码版本/第一版-全部代码/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/archived/merge_lora_weights.py +22 -0
  48. 之前的代码版本/第一版-全部代码/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/archived/pretrain.sh +43 -0
  49. 之前的代码版本/第一版-全部代码/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/archived/quick_check.py +57 -0
  50. 之前的代码版本/第一版-全部代码/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/archived/sqa_eval_batch.sh +13 -0
之前的代码版本/注意力关键词用于sam的/MedEvalKit/datas/Radrestruct/test_qa_pairs/1415.json ADDED
@@ -0,0 +1 @@
 
 
1
+ [["Are there any foreign objects?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "foreign objects_objects"}], ["Are there any signs in the lung?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "lung_signs"}], ["Is there anything abnormal in the lung?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "lung_body_regions"}], ["Are there any diseases in the lung?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "lung_diseases"}], ["Are there any signs in the pleura?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "pleura_signs"}], ["Is there anything abnormal in the pleura?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "pleura_body_regions"}], ["Are there any diseases in the pleura?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "pleura_diseases"}], ["Are there any signs in the trachea?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "trachea_signs"}], ["Is there anything abnormal in the trachea?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "trachea_body_regions"}], ["Are there any diseases in the trachea?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "trachea_diseases"}], ["Are there any signs in the cardiovascular system?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "cardiovascular system_signs"}], ["Is there anything abnormal in the cardiovascular system?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "cardiovascular system_body_regions"}], ["Are there any diseases in the cardiovascular system?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "cardiovascular system_diseases"}], ["Are there any signs in the skeletal system?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "skeletal system_signs"}], ["Is there anything abnormal in the skeletal system?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "skeletal system_body_regions"}], ["Are there any diseases in the skeletal system?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "skeletal system_diseases"}], ["Are there any signs in the breast?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "breast_signs"}], ["Are there any diseases in the breast?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "breast_diseases"}], ["Are there any signs in the abdomen?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "abdomen_signs"}], ["Is there anything abnormal in the abdomen?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "abdomen_infos"}], ["Are there any diseases in the abdomen?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "abdomen_diseases"}], ["Are there any signs in the thorax?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "thorax_signs"}], ["Are there any diseases in the thorax?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "thorax_diseases"}], ["Are there any signs in the mediastinum?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "mediastinum_signs"}], ["Is there anything abnormal in the mediastinum?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "mediastinum_infos"}], ["Are there any diseases in the mediastinum?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "mediastinum_diseases"}], ["Is there anything abnormal in the lymph nodes?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "lymph nodes_infos"}], ["Are there any diseases in the lymph nodes?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "lymph nodes_diseases"}]]
之前的代码版本/注意力关键词用于sam的/MedEvalKit/datas/Radrestruct/test_qa_pairs/1552.json ADDED
@@ -0,0 +1 @@
 
 
1
+ [["Are there any foreign objects?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "foreign objects_objects"}], ["Are there any signs in the lung?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "lung_signs"}], ["Is there anything abnormal in the lung?", ["yes"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "lung_body_regions"}], ["Is there anything abnormal in the whole lung?", ["yes"], [["Is there anything abnormal in the lung?", ["yes"]]], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "lung_body_regions"}], ["In which area?", ["unspecified"], [["Is there anything abnormal in the lung?", ["yes"]], ["Is there anything abnormal in the whole lung?", ["yes"]]], {"answer_type": "multi_choice", "options": ["bilateral", "interstitial", "left", "right", "unspecified"], "path": "lung_body_regions_localization"}], ["What are the attributes?", ["no selection"], [["Is there anything abnormal in the lung?", ["yes"]], ["Is there anything abnormal in the whole lung?", ["yes"]], ["In which area?", ["unspecified"]]], {"answer_type": "multi_choice", "options": ["diffuse", "no selection", "obscured", "prominent"], "path": "lung_body_regions_attributes"}], ["What is the degree?", ["hypoinflation"], [["Is there anything abnormal in the lung?", ["yes"]], ["Is there anything abnormal in the whole lung?", ["yes"]], ["In which area?", ["unspecified"]], ["What are the attributes?", ["no selection"]]], {"answer_type": "multi_choice", "options": ["abnormal", "hyperdistention", "hypoinflation", "mild", "moderate", "no selection", "severe"], "path": "lung_body_regions_degree"}], ["Is there anything else abnormal in the whole lung?", ["no"], [["Is there anything abnormal in the lung?", ["yes"]], ["Is there anything abnormal in the whole lung?", ["yes"]], ["In which area?", ["unspecified"]], ["What are the attributes?", ["no selection"]], ["What is the degree?", ["hypoinflation"]]], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "lung_body_regions"}], ["Is there anything abnormal in the diaphragm?", ["no"], [["Is there anything abnormal in the lung?", ["yes"]]], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "lung_body_regions_diaphragm"}], ["Is there anything abnormal in the costophrenic angle?", ["no"], [["Is there anything abnormal in the lung?", ["yes"]]], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "lung_body_regions_costophrenic angle"}], ["Is there anything abnormal in the hilum?", ["no"], [["Is there anything abnormal in the lung?", ["yes"]]], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "lung_body_regions_hilum"}], ["Is there anything abnormal in the apex?", ["no"], [["Is there anything abnormal in the lung?", ["yes"]]], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "lung_body_regions_apex"}], ["Is there anything abnormal in the azygos lobe?", ["no"], [["Is there anything abnormal in the lung?", ["yes"]]], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "lung_body_regions_azygos lobe"}], ["Is there anything abnormal in the blood vessels?", ["no"], [["Is there anything abnormal in the lung?", ["yes"]]], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "lung_body_regions_blood vessels"}], ["Are there any diseases in the lung?", ["yes"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "lung_diseases"}], ["Is there blister in the lung?", ["no"], [["Are there any diseases in the lung?", ["yes"]]], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "lung_diseases_blister"}], ["Is there bronchiectasis in the lung?", ["no"], [["Are there any diseases in the lung?", ["yes"]]], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "lung_diseases_bronchiectasis"}], ["Is there bronchiolitis in the lung?", ["no"], [["Are there any diseases in the lung?", ["yes"]]], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "lung_diseases_bronchiolitis"}], ["Is there bronchitis in the lung?", ["no"], [["Are there any diseases in the lung?", ["yes"]]], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "lung_diseases_bronchitis"}], ["Is there bullous emphysema in the lung?", ["no"], [["Are there any diseases in the lung?", ["yes"]]], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "lung_diseases_bullous emphysema"}], ["Is there calcified granuloma in the lung?", ["no"], [["Are there any diseases in the lung?", ["yes"]]], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "lung_diseases_calcified granuloma"}], ["Is there calcinosis in the lung?", ["no"], [["Are there any diseases in the lung?", ["yes"]]], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "lung_diseases_calcinosis"}], ["Is there cavitation in the lung?", ["no"], [["Are there any diseases in the lung?", ["yes"]]], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "lung_diseases_cavitation"}], ["Is there cicatrix in the lung?", ["no"], [["Are there any diseases in the lung?", ["yes"]]], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "lung_diseases_cicatrix"}], ["Is there cystic fibrosis in the lung?", ["no"], [["Are there any diseases in the lung?", ["yes"]]], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "lung_diseases_cystic fibrosis"}], ["Is there cysts in the lung?", ["no"], [["Are there any diseases in the lung?", ["yes"]]], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "lung_diseases_cysts"}], ["Is there granuloma in the lung?", ["no"], [["Are there any diseases in the lung?", ["yes"]]], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "lung_diseases_granuloma"}], ["Is there hypertension, pulmonary in the lung?", ["no"], [["Are there any diseases in the lung?", ["yes"]]], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "lung_diseases_hypertension, pulmonary"}], ["Is there hypovolemia in the lung?", ["no"], [["Are there any diseases in the lung?", ["yes"]]], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "lung_diseases_hypovolemia"}], ["Is there infiltrate in the lung?", ["no"], [["Are there any diseases in the lung?", ["yes"]]], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "lung_diseases_infiltrate"}], ["Is there lung diseases, interstitial in the lung?", ["no"], [["Are there any diseases in the lung?", ["yes"]]], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "lung_diseases_lung diseases, interstitial"}], ["Is there lung, hyperlucent in the lung?", ["no"], [["Are there any diseases in the lung?", ["yes"]]], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "lung_diseases_lung, hyperlucent"}], ["Is there mass in the lung?", ["no"], [["Are there any diseases in the lung?", ["yes"]]], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "lung_diseases_mass"}], ["Is there nodule in the lung?", ["no"], [["Are there any diseases in the lung?", ["yes"]]], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "lung_diseases_nodule"}], ["Is there pneumonia in the lung?", ["no"], [["Are there any diseases in the lung?", ["yes"]]], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "lung_diseases_pneumonia"}], ["Is there pulmonary atelectasis in the lung?", ["yes"], [["Are there any diseases in the lung?", ["yes"]]], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "lung_diseases_pulmonary atelectasis"}], ["In which part of the body?", ["middle lobe"], [["Are there any diseases in the lung?", ["yes"]], ["Is there pulmonary atelectasis in the lung?", ["yes"]]], {"answer_type": "multi_choice", "options": ["apex", "left costophrenic angle", "left lower lobe", "left upper lobe", "middle lobe", "right costophrenic angle", "right hilum", "right lower lobe", "right upper lobe"], "path": "lung_diseases_pulmonary atelectasis_body_region"}], ["What are the attributes?", ["no selection"], [["Are there any diseases in the lung?", ["yes"]], ["Is there pulmonary atelectasis in the lung?", ["yes"]], ["In which part of the body?", ["middle lobe"]]], {"answer_type": "multi_choice", "options": ["focal", "no selection", "patchy", "round", "scattered", "small", "streaky"], "path": "lung_diseases_pulmonary atelectasis_attributes"}], ["What is the degree?", ["mild"], [["Are there any diseases in the lung?", ["yes"]], ["Is there pulmonary atelectasis in the lung?", ["yes"]], ["In which part of the body?", ["middle lobe"]], ["What are the attributes?", ["no selection"]]], {"answer_type": "single_choice", "options": ["chronic", "mild", "no selection", "severe"], "path": "lung_diseases_pulmonary atelectasis_degree"}], ["Is there another case of pulmonary atelectasis in the lung?", ["no"], [["Are there any diseases in the lung?", ["yes"]], ["Is there pulmonary atelectasis in the lung?", ["yes"]], ["In which part of the body?", ["middle lobe"]], ["What are the attributes?", ["no selection"]], ["What is the degree?", ["mild"]]], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "lung_diseases_pulmonary atelectasis"}], ["Is there pulmonary congestion in the lung?", ["no"], [["Are there any diseases in the lung?", ["yes"]]], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "lung_diseases_pulmonary congestion"}], ["Is there pulmonary disease, chronic obstructive in the lung?", ["no"], [["Are there any diseases in the lung?", ["yes"]]], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "lung_diseases_pulmonary disease, chronic obstructive"}], ["Is there pulmonary edema in the lung?", ["no"], [["Are there any diseases in the lung?", ["yes"]]], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "lung_diseases_pulmonary edema"}], ["Is there pulmonary emphysema in the lung?", ["no"], [["Are there any diseases in the lung?", ["yes"]]], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "lung_diseases_pulmonary emphysema"}], ["Is there pulmonary fibrosis in the lung?", ["no"], [["Are there any diseases in the lung?", ["yes"]]], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "lung_diseases_pulmonary fibrosis"}], ["Is there tuberculosis in the lung?", ["no"], [["Are there any diseases in the lung?", ["yes"]]], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "lung_diseases_tuberculosis"}], ["Are there any signs in the pleura?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "pleura_signs"}], ["Is there anything abnormal in the pleura?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "pleura_body_regions"}], ["Are there any diseases in the pleura?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "pleura_diseases"}], ["Are there any signs in the trachea?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "trachea_signs"}], ["Is there anything abnormal in the trachea?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "trachea_body_regions"}], ["Are there any diseases in the trachea?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "trachea_diseases"}], ["Are there any signs in the cardiovascular system?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "cardiovascular system_signs"}], ["Is there anything abnormal in the cardiovascular system?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "cardiovascular system_body_regions"}], ["Are there any diseases in the cardiovascular system?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "cardiovascular system_diseases"}], ["Are there any signs in the skeletal system?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "skeletal system_signs"}], ["Is there anything abnormal in the skeletal system?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "skeletal system_body_regions"}], ["Are there any diseases in the skeletal system?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "skeletal system_diseases"}], ["Are there any signs in the breast?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "breast_signs"}], ["Are there any diseases in the breast?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "breast_diseases"}], ["Are there any signs in the abdomen?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "abdomen_signs"}], ["Is there anything abnormal in the abdomen?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "abdomen_infos"}], ["Are there any diseases in the abdomen?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "abdomen_diseases"}], ["Are there any signs in the thorax?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "thorax_signs"}], ["Are there any diseases in the thorax?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "thorax_diseases"}], ["Are there any signs in the mediastinum?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "mediastinum_signs"}], ["Is there anything abnormal in the mediastinum?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "mediastinum_infos"}], ["Are there any diseases in the mediastinum?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "mediastinum_diseases"}], ["Is there anything abnormal in the lymph nodes?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "lymph nodes_infos"}], ["Are there any diseases in the lymph nodes?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "lymph nodes_diseases"}]]
之前的代码版本/注意力关键词用于sam的/MedEvalKit/datas/Radrestruct/test_qa_pairs/194.json ADDED
@@ -0,0 +1 @@
 
 
1
+ [["Are there any foreign objects?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "foreign objects_objects"}], ["Are there any signs in the lung?", ["yes"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "lung_signs"}], ["Is there a airspace disease in the lung?", ["yes"], [["Are there any signs in the lung?", ["yes"]]], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "lung_signs_airspace disease"}], ["In which part of the body?", ["left lower lobe"], [["Are there any signs in the lung?", ["yes"]], ["Is there a airspace disease in the lung?", ["yes"]]], {"answer_type": "multi_choice", "options": ["apex", "left lower lobe", "left upper lobe", "middle lobe", "pulmonary alveoli", "right hilum", "right lower lobe", "right upper lobe"], "path": "lung_signs_airspace disease_body_region"}], ["What are the attributes?", ["no selection"], [["Are there any signs in the lung?", ["yes"]], ["Is there a airspace disease in the lung?", ["yes"]], ["In which part of the body?", ["left lower lobe"]]], {"answer_type": "multi_choice", "options": ["diffuse", "focal", "multiple", "no selection", "patchy", "scattered", "streaky"], "path": "lung_signs_airspace disease_attributes"}], ["What is the degree?", ["mild"], [["Are there any signs in the lung?", ["yes"]], ["Is there a airspace disease in the lung?", ["yes"]], ["In which part of the body?", ["left lower lobe"]], ["What are the attributes?", ["no selection"]]], {"answer_type": "single_choice", "options": ["acute", "mild", "no selection", "severe"], "path": "lung_signs_airspace disease_degree"}], ["Is there another airspace disease in the lung?", ["no"], [["Are there any signs in the lung?", ["yes"]], ["Is there a airspace disease in the lung?", ["yes"]], ["In which part of the body?", ["left lower lobe"]], ["What are the attributes?", ["no selection"]], ["What is the degree?", ["mild"]]], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "lung_signs_airspace disease"}], ["Is there an consolidation in the lung?", ["no"], [["Are there any signs in the lung?", ["yes"]]], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "lung_signs_consolidation"}], ["Is there an deformity in the lung?", ["no"], [["Are there any signs in the lung?", ["yes"]]], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "lung_signs_deformity"}], ["Is there an density in the lung?", ["no"], [["Are there any signs in the lung?", ["yes"]]], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "lung_signs_density"}], ["Is there an lucency in the lung?", ["no"], [["Are there any signs in the lung?", ["yes"]]], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "lung_signs_lucency"}], ["Is there an markings in the lung?", ["no"], [["Are there any signs in the lung?", ["yes"]]], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "lung_signs_markings"}], ["Is there an nipple shadow in the lung?", ["no"], [["Are there any signs in the lung?", ["yes"]]], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "lung_signs_nipple shadow"}], ["Is there a opacity in the lung?", ["no"], [["Are there any signs in the lung?", ["yes"]]], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "lung_signs_opacity"}], ["Is there an thickening in the lung?", ["no"], [["Are there any signs in the lung?", ["yes"]]], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "lung_signs_thickening"}], ["Is there an volume loss in the lung?", ["no"], [["Are there any signs in the lung?", ["yes"]]], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "lung_signs_volume loss"}], ["Is there an pneumonectomy in the lung?", ["no"], [["Are there any signs in the lung?", ["yes"]]], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "lung_signs_pneumonectomy"}], ["Is there anything abnormal in the lung?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "lung_body_regions"}], ["Are there any diseases in the lung?", ["yes"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "lung_diseases"}], ["Is there blister in the lung?", ["no"], [["Are there any diseases in the lung?", ["yes"]]], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "lung_diseases_blister"}], ["Is there bronchiectasis in the lung?", ["no"], [["Are there any diseases in the lung?", ["yes"]]], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "lung_diseases_bronchiectasis"}], ["Is there bronchiolitis in the lung?", ["no"], [["Are there any diseases in the lung?", ["yes"]]], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "lung_diseases_bronchiolitis"}], ["Is there bronchitis in the lung?", ["no"], [["Are there any diseases in the lung?", ["yes"]]], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "lung_diseases_bronchitis"}], ["Is there bullous emphysema in the lung?", ["no"], [["Are there any diseases in the lung?", ["yes"]]], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "lung_diseases_bullous emphysema"}], ["Is there calcified granuloma in the lung?", ["no"], [["Are there any diseases in the lung?", ["yes"]]], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "lung_diseases_calcified granuloma"}], ["Is there calcinosis in the lung?", ["no"], [["Are there any diseases in the lung?", ["yes"]]], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "lung_diseases_calcinosis"}], ["Is there cavitation in the lung?", ["no"], [["Are there any diseases in the lung?", ["yes"]]], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "lung_diseases_cavitation"}], ["Is there cicatrix in the lung?", ["no"], [["Are there any diseases in the lung?", ["yes"]]], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "lung_diseases_cicatrix"}], ["Is there cystic fibrosis in the lung?", ["no"], [["Are there any diseases in the lung?", ["yes"]]], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "lung_diseases_cystic fibrosis"}], ["Is there cysts in the lung?", ["no"], [["Are there any diseases in the lung?", ["yes"]]], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "lung_diseases_cysts"}], ["Is there granuloma in the lung?", ["no"], [["Are there any diseases in the lung?", ["yes"]]], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "lung_diseases_granuloma"}], ["Is there hypertension, pulmonary in the lung?", ["no"], [["Are there any diseases in the lung?", ["yes"]]], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "lung_diseases_hypertension, pulmonary"}], ["Is there hypovolemia in the lung?", ["no"], [["Are there any diseases in the lung?", ["yes"]]], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "lung_diseases_hypovolemia"}], ["Is there infiltrate in the lung?", ["yes"], [["Are there any diseases in the lung?", ["yes"]]], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "lung_diseases_infiltrate"}], ["In which part of the body?", ["left lower lobe"], [["Are there any diseases in the lung?", ["yes"]], ["Is there infiltrate in the lung?", ["yes"]]], {"answer_type": "multi_choice", "options": ["interstitial", "left hilum", "left interstitial", "left lower lobe", "left upper lobe", "middle lobe", "pulmonary alveoli", "right hilum", "right interstitial", "right lower lobe", "right upper lobe"], "path": "lung_diseases_infiltrate_body_region"}], ["What are the attributes?", ["no selection"], [["Are there any diseases in the lung?", ["yes"]], ["Is there infiltrate in the lung?", ["yes"]], ["In which part of the body?", ["left lower lobe"]]], {"answer_type": "multi_choice", "options": ["focal", "no selection", "patchy", "round", "small", "streaky"], "path": "lung_diseases_infiltrate_attributes"}], ["What is the degree?", ["no selection"], [["Are there any diseases in the lung?", ["yes"]], ["Is there infiltrate in the lung?", ["yes"]], ["In which part of the body?", ["left lower lobe"]], ["What are the attributes?", ["no selection"]]], {"answer_type": "single_choice", "options": ["mild", "no selection"], "path": "lung_diseases_infiltrate_degree"}], ["Is there another case of infiltrate in the lung?", ["no"], [["Are there any diseases in the lung?", ["yes"]], ["Is there infiltrate in the lung?", ["yes"]], ["In which part of the body?", ["left lower lobe"]], ["What are the attributes?", ["no selection"]], ["What is the degree?", ["no selection"]]], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "lung_diseases_infiltrate"}], ["Is there lung diseases, interstitial in the lung?", ["no"], [["Are there any diseases in the lung?", ["yes"]]], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "lung_diseases_lung diseases, interstitial"}], ["Is there lung, hyperlucent in the lung?", ["no"], [["Are there any diseases in the lung?", ["yes"]]], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "lung_diseases_lung, hyperlucent"}], ["Is there mass in the lung?", ["no"], [["Are there any diseases in the lung?", ["yes"]]], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "lung_diseases_mass"}], ["Is there nodule in the lung?", ["no"], [["Are there any diseases in the lung?", ["yes"]]], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "lung_diseases_nodule"}], ["Is there pneumonia in the lung?", ["no"], [["Are there any diseases in the lung?", ["yes"]]], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "lung_diseases_pneumonia"}], ["Is there pulmonary atelectasis in the lung?", ["yes"], [["Are there any diseases in the lung?", ["yes"]]], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "lung_diseases_pulmonary atelectasis"}], ["In which part of the body?", ["left lower lobe"], [["Are there any diseases in the lung?", ["yes"]], ["Is there pulmonary atelectasis in the lung?", ["yes"]]], {"answer_type": "multi_choice", "options": ["apex", "left costophrenic angle", "left lower lobe", "left upper lobe", "middle lobe", "right costophrenic angle", "right hilum", "right lower lobe", "right upper lobe"], "path": "lung_diseases_pulmonary atelectasis_body_region"}], ["What are the attributes?", ["no selection"], [["Are there any diseases in the lung?", ["yes"]], ["Is there pulmonary atelectasis in the lung?", ["yes"]], ["In which part of the body?", ["left lower lobe"]]], {"answer_type": "multi_choice", "options": ["focal", "no selection", "patchy", "round", "scattered", "small", "streaky"], "path": "lung_diseases_pulmonary atelectasis_attributes"}], ["What is the degree?", ["no selection"], [["Are there any diseases in the lung?", ["yes"]], ["Is there pulmonary atelectasis in the lung?", ["yes"]], ["In which part of the body?", ["left lower lobe"]], ["What are the attributes?", ["no selection"]]], {"answer_type": "single_choice", "options": ["chronic", "mild", "no selection", "severe"], "path": "lung_diseases_pulmonary atelectasis_degree"}], ["Is there another case of pulmonary atelectasis in the lung?", ["no"], [["Are there any diseases in the lung?", ["yes"]], ["Is there pulmonary atelectasis in the lung?", ["yes"]], ["In which part of the body?", ["left lower lobe"]], ["What are the attributes?", ["no selection"]], ["What is the degree?", ["no selection"]]], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "lung_diseases_pulmonary atelectasis"}], ["Is there pulmonary congestion in the lung?", ["no"], [["Are there any diseases in the lung?", ["yes"]]], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "lung_diseases_pulmonary congestion"}], ["Is there pulmonary disease, chronic obstructive in the lung?", ["no"], [["Are there any diseases in the lung?", ["yes"]]], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "lung_diseases_pulmonary disease, chronic obstructive"}], ["Is there pulmonary edema in the lung?", ["no"], [["Are there any diseases in the lung?", ["yes"]]], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "lung_diseases_pulmonary edema"}], ["Is there pulmonary emphysema in the lung?", ["no"], [["Are there any diseases in the lung?", ["yes"]]], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "lung_diseases_pulmonary emphysema"}], ["Is there pulmonary fibrosis in the lung?", ["no"], [["Are there any diseases in the lung?", ["yes"]]], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "lung_diseases_pulmonary fibrosis"}], ["Is there tuberculosis in the lung?", ["no"], [["Are there any diseases in the lung?", ["yes"]]], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "lung_diseases_tuberculosis"}], ["Are there any signs in the pleura?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "pleura_signs"}], ["Is there anything abnormal in the pleura?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "pleura_body_regions"}], ["Are there any diseases in the pleura?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "pleura_diseases"}], ["Are there any signs in the trachea?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "trachea_signs"}], ["Is there anything abnormal in the trachea?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "trachea_body_regions"}], ["Are there any diseases in the trachea?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "trachea_diseases"}], ["Are there any signs in the cardiovascular system?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "cardiovascular system_signs"}], ["Is there anything abnormal in the cardiovascular system?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "cardiovascular system_body_regions"}], ["Are there any diseases in the cardiovascular system?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "cardiovascular system_diseases"}], ["Are there any signs in the skeletal system?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "skeletal system_signs"}], ["Is there anything abnormal in the skeletal system?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "skeletal system_body_regions"}], ["Are there any diseases in the skeletal system?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "skeletal system_diseases"}], ["Are there any signs in the breast?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "breast_signs"}], ["Are there any diseases in the breast?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "breast_diseases"}], ["Are there any signs in the abdomen?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "abdomen_signs"}], ["Is there anything abnormal in the abdomen?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "abdomen_infos"}], ["Are there any diseases in the abdomen?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "abdomen_diseases"}], ["Are there any signs in the thorax?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "thorax_signs"}], ["Are there any diseases in the thorax?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "thorax_diseases"}], ["Are there any signs in the mediastinum?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "mediastinum_signs"}], ["Is there anything abnormal in the mediastinum?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "mediastinum_infos"}], ["Are there any diseases in the mediastinum?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "mediastinum_diseases"}], ["Is there anything abnormal in the lymph nodes?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "lymph nodes_infos"}], ["Are there any diseases in the lymph nodes?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "lymph nodes_diseases"}]]
之前的代码版本/注意力关键词用于sam的/MedEvalKit/datas/Radrestruct/test_qa_pairs/2555.json ADDED
@@ -0,0 +1 @@
 
 
1
+ [["Are there any foreign objects?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "foreign objects_objects"}], ["Are there any signs in the lung?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "lung_signs"}], ["Is there anything abnormal in the lung?", ["yes"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "lung_body_regions"}], ["Is there anything abnormal in the whole lung?", ["yes"], [["Is there anything abnormal in the lung?", ["yes"]]], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "lung_body_regions"}], ["In which area?", ["unspecified"], [["Is there anything abnormal in the lung?", ["yes"]], ["Is there anything abnormal in the whole lung?", ["yes"]]], {"answer_type": "multi_choice", "options": ["bilateral", "interstitial", "left", "right", "unspecified"], "path": "lung_body_regions_localization"}], ["What are the attributes?", ["no selection"], [["Is there anything abnormal in the lung?", ["yes"]], ["Is there anything abnormal in the whole lung?", ["yes"]], ["In which area?", ["unspecified"]]], {"answer_type": "multi_choice", "options": ["diffuse", "no selection", "obscured", "prominent"], "path": "lung_body_regions_attributes"}], ["What is the degree?", ["hyperdistention", "mild"], [["Is there anything abnormal in the lung?", ["yes"]], ["Is there anything abnormal in the whole lung?", ["yes"]], ["In which area?", ["unspecified"]], ["What are the attributes?", ["no selection"]]], {"answer_type": "multi_choice", "options": ["abnormal", "hyperdistention", "hypoinflation", "mild", "moderate", "no selection", "severe"], "path": "lung_body_regions_degree"}], ["Is there anything else abnormal in the whole lung?", ["no"], [["Is there anything abnormal in the lung?", ["yes"]], ["Is there anything abnormal in the whole lung?", ["yes"]], ["In which area?", ["unspecified"]], ["What are the attributes?", ["no selection"]], ["What is the degree?", ["hyperdistention", "mild"]]], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "lung_body_regions"}], ["Is there anything abnormal in the diaphragm?", ["no"], [["Is there anything abnormal in the lung?", ["yes"]]], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "lung_body_regions_diaphragm"}], ["Is there anything abnormal in the costophrenic angle?", ["no"], [["Is there anything abnormal in the lung?", ["yes"]]], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "lung_body_regions_costophrenic angle"}], ["Is there anything abnormal in the hilum?", ["no"], [["Is there anything abnormal in the lung?", ["yes"]]], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "lung_body_regions_hilum"}], ["Is there anything abnormal in the apex?", ["no"], [["Is there anything abnormal in the lung?", ["yes"]]], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "lung_body_regions_apex"}], ["Is there anything abnormal in the azygos lobe?", ["no"], [["Is there anything abnormal in the lung?", ["yes"]]], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "lung_body_regions_azygos lobe"}], ["Is there anything abnormal in the blood vessels?", ["no"], [["Is there anything abnormal in the lung?", ["yes"]]], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "lung_body_regions_blood vessels"}], ["Are there any diseases in the lung?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "lung_diseases"}], ["Are there any signs in the pleura?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "pleura_signs"}], ["Is there anything abnormal in the pleura?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "pleura_body_regions"}], ["Are there any diseases in the pleura?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "pleura_diseases"}], ["Are there any signs in the trachea?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "trachea_signs"}], ["Is there anything abnormal in the trachea?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "trachea_body_regions"}], ["Are there any diseases in the trachea?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "trachea_diseases"}], ["Are there any signs in the cardiovascular system?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "cardiovascular system_signs"}], ["Is there anything abnormal in the cardiovascular system?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "cardiovascular system_body_regions"}], ["Are there any diseases in the cardiovascular system?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "cardiovascular system_diseases"}], ["Are there any signs in the skeletal system?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "skeletal system_signs"}], ["Is there anything abnormal in the skeletal system?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "skeletal system_body_regions"}], ["Are there any diseases in the skeletal system?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "skeletal system_diseases"}], ["Are there any signs in the breast?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "breast_signs"}], ["Are there any diseases in the breast?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "breast_diseases"}], ["Are there any signs in the abdomen?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "abdomen_signs"}], ["Is there anything abnormal in the abdomen?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "abdomen_infos"}], ["Are there any diseases in the abdomen?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "abdomen_diseases"}], ["Are there any signs in the thorax?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "thorax_signs"}], ["Are there any diseases in the thorax?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "thorax_diseases"}], ["Are there any signs in the mediastinum?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "mediastinum_signs"}], ["Is there anything abnormal in the mediastinum?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "mediastinum_infos"}], ["Are there any diseases in the mediastinum?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "mediastinum_diseases"}], ["Is there anything abnormal in the lymph nodes?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "lymph nodes_infos"}], ["Are there any diseases in the lymph nodes?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "lymph nodes_diseases"}]]
之前的代码版本/注意力关键词用于sam的/MedEvalKit/datas/Radrestruct/test_qa_pairs/2861.json ADDED
@@ -0,0 +1 @@
 
 
1
+ [["Are there any foreign objects?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "foreign objects_objects"}], ["Are there any signs in the lung?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "lung_signs"}], ["Is there anything abnormal in the lung?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "lung_body_regions"}], ["Are there any diseases in the lung?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "lung_diseases"}], ["Are there any signs in the pleura?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "pleura_signs"}], ["Is there anything abnormal in the pleura?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "pleura_body_regions"}], ["Are there any diseases in the pleura?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "pleura_diseases"}], ["Are there any signs in the trachea?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "trachea_signs"}], ["Is there anything abnormal in the trachea?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "trachea_body_regions"}], ["Are there any diseases in the trachea?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "trachea_diseases"}], ["Are there any signs in the cardiovascular system?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "cardiovascular system_signs"}], ["Is there anything abnormal in the cardiovascular system?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "cardiovascular system_body_regions"}], ["Are there any diseases in the cardiovascular system?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "cardiovascular system_diseases"}], ["Are there any signs in the skeletal system?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "skeletal system_signs"}], ["Is there anything abnormal in the skeletal system?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "skeletal system_body_regions"}], ["Are there any diseases in the skeletal system?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "skeletal system_diseases"}], ["Are there any signs in the breast?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "breast_signs"}], ["Are there any diseases in the breast?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "breast_diseases"}], ["Are there any signs in the abdomen?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "abdomen_signs"}], ["Is there anything abnormal in the abdomen?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "abdomen_infos"}], ["Are there any diseases in the abdomen?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "abdomen_diseases"}], ["Are there any signs in the thorax?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "thorax_signs"}], ["Are there any diseases in the thorax?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "thorax_diseases"}], ["Are there any signs in the mediastinum?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "mediastinum_signs"}], ["Is there anything abnormal in the mediastinum?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "mediastinum_infos"}], ["Are there any diseases in the mediastinum?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "mediastinum_diseases"}], ["Is there anything abnormal in the lymph nodes?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "lymph nodes_infos"}], ["Are there any diseases in the lymph nodes?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "lymph nodes_diseases"}]]
之前的代码版本/注意力关键词用于sam的/MedEvalKit/datas/Radrestruct/test_qa_pairs/3236.json ADDED
@@ -0,0 +1 @@
 
 
1
+ [["Are there any foreign objects?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "foreign objects_objects"}], ["Are there any signs in the lung?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "lung_signs"}], ["Is there anything abnormal in the lung?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "lung_body_regions"}], ["Are there any diseases in the lung?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "lung_diseases"}], ["Are there any signs in the pleura?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "pleura_signs"}], ["Is there anything abnormal in the pleura?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "pleura_body_regions"}], ["Are there any diseases in the pleura?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "pleura_diseases"}], ["Are there any signs in the trachea?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "trachea_signs"}], ["Is there anything abnormal in the trachea?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "trachea_body_regions"}], ["Are there any diseases in the trachea?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "trachea_diseases"}], ["Are there any signs in the cardiovascular system?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "cardiovascular system_signs"}], ["Is there anything abnormal in the cardiovascular system?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "cardiovascular system_body_regions"}], ["Are there any diseases in the cardiovascular system?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "cardiovascular system_diseases"}], ["Are there any signs in the skeletal system?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "skeletal system_signs"}], ["Is there anything abnormal in the skeletal system?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "skeletal system_body_regions"}], ["Are there any diseases in the skeletal system?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "skeletal system_diseases"}], ["Are there any signs in the breast?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "breast_signs"}], ["Are there any diseases in the breast?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "breast_diseases"}], ["Are there any signs in the abdomen?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "abdomen_signs"}], ["Is there anything abnormal in the abdomen?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "abdomen_infos"}], ["Are there any diseases in the abdomen?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "abdomen_diseases"}], ["Are there any signs in the thorax?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "thorax_signs"}], ["Are there any diseases in the thorax?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "thorax_diseases"}], ["Are there any signs in the mediastinum?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "mediastinum_signs"}], ["Is there anything abnormal in the mediastinum?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "mediastinum_infos"}], ["Are there any diseases in the mediastinum?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "mediastinum_diseases"}], ["Is there anything abnormal in the lymph nodes?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "lymph nodes_infos"}], ["Are there any diseases in the lymph nodes?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "lymph nodes_diseases"}]]
之前的代码版本/注意力关键词用于sam的/MedEvalKit/datas/Radrestruct/test_qa_pairs/3465.json ADDED
@@ -0,0 +1 @@
 
 
1
+ [["Are there any foreign objects?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "foreign objects_objects"}], ["Are there any signs in the lung?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "lung_signs"}], ["Is there anything abnormal in the lung?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "lung_body_regions"}], ["Are there any diseases in the lung?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "lung_diseases"}], ["Are there any signs in the pleura?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "pleura_signs"}], ["Is there anything abnormal in the pleura?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "pleura_body_regions"}], ["Are there any diseases in the pleura?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "pleura_diseases"}], ["Are there any signs in the trachea?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "trachea_signs"}], ["Is there anything abnormal in the trachea?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "trachea_body_regions"}], ["Are there any diseases in the trachea?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "trachea_diseases"}], ["Are there any signs in the cardiovascular system?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "cardiovascular system_signs"}], ["Is there anything abnormal in the cardiovascular system?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "cardiovascular system_body_regions"}], ["Are there any diseases in the cardiovascular system?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "cardiovascular system_diseases"}], ["Are there any signs in the skeletal system?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "skeletal system_signs"}], ["Is there anything abnormal in the skeletal system?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "skeletal system_body_regions"}], ["Are there any diseases in the skeletal system?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "skeletal system_diseases"}], ["Are there any signs in the breast?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "breast_signs"}], ["Are there any diseases in the breast?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "breast_diseases"}], ["Are there any signs in the abdomen?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "abdomen_signs"}], ["Is there anything abnormal in the abdomen?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "abdomen_infos"}], ["Are there any diseases in the abdomen?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "abdomen_diseases"}], ["Are there any signs in the thorax?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "thorax_signs"}], ["Are there any diseases in the thorax?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "thorax_diseases"}], ["Are there any signs in the mediastinum?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "mediastinum_signs"}], ["Is there anything abnormal in the mediastinum?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "mediastinum_infos"}], ["Are there any diseases in the mediastinum?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "mediastinum_diseases"}], ["Is there anything abnormal in the lymph nodes?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "lymph nodes_infos"}], ["Are there any diseases in the lymph nodes?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "lymph nodes_diseases"}]]
之前的代码版本/注意力关键词用于sam的/MedEvalKit/datas/Radrestruct/test_qa_pairs/3678.json ADDED
@@ -0,0 +1 @@
 
 
1
+ [["Are there any foreign objects?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "foreign objects_objects"}], ["Are there any signs in the lung?", ["yes"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "lung_signs"}], ["Is there a airspace disease in the lung?", ["no"], [["Are there any signs in the lung?", ["yes"]]], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "lung_signs_airspace disease"}], ["Is there an consolidation in the lung?", ["no"], [["Are there any signs in the lung?", ["yes"]]], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "lung_signs_consolidation"}], ["Is there an deformity in the lung?", ["no"], [["Are there any signs in the lung?", ["yes"]]], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "lung_signs_deformity"}], ["Is there an density in the lung?", ["no"], [["Are there any signs in the lung?", ["yes"]]], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "lung_signs_density"}], ["Is there an lucency in the lung?", ["no"], [["Are there any signs in the lung?", ["yes"]]], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "lung_signs_lucency"}], ["Is there an markings in the lung?", ["yes"], [["Are there any signs in the lung?", ["yes"]]], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "lung_signs_markings"}], ["In which part of the body?", ["interstitial"], [["Are there any signs in the lung?", ["yes"]], ["Is there an markings in the lung?", ["yes"]]], {"answer_type": "multi_choice", "options": ["apex", "bronchovascular", "interstitial", "left hilum", "left interstitial", "left lower lobe", "left upper lobe", "middle lobe", "right hilum", "right interstitial", "right lower lobe", "right upper lobe"], "path": "lung_signs_markings_body_region"}], ["What are the attributes?", ["prominent"], [["Are there any signs in the lung?", ["yes"]], ["Is there an markings in the lung?", ["yes"]], ["In which part of the body?", ["interstitial"]]], {"answer_type": "multi_choice", "options": ["diffuse", "focal", "irregular", "no selection", "prominent", "reticular", "round", "scattered"], "path": "lung_signs_markings_attributes"}], ["What is the degree?", ["mild"], [["Are there any signs in the lung?", ["yes"]], ["Is there an markings in the lung?", ["yes"]], ["In which part of the body?", ["interstitial"]], ["What are the attributes?", ["prominent"]]], {"answer_type": "single_choice", "options": ["chronic", "mild", "no selection", "severe"], "path": "lung_signs_markings_degree"}], ["Is there another markings in the lung?", ["no"], [["Are there any signs in the lung?", ["yes"]], ["Is there an markings in the lung?", ["yes"]], ["In which part of the body?", ["interstitial"]], ["What are the attributes?", ["prominent"]], ["What is the degree?", ["mild"]]], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "lung_signs_markings"}], ["Is there an nipple shadow in the lung?", ["no"], [["Are there any signs in the lung?", ["yes"]]], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "lung_signs_nipple shadow"}], ["Is there a opacity in the lung?", ["no"], [["Are there any signs in the lung?", ["yes"]]], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "lung_signs_opacity"}], ["Is there an thickening in the lung?", ["no"], [["Are there any signs in the lung?", ["yes"]]], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "lung_signs_thickening"}], ["Is there an volume loss in the lung?", ["no"], [["Are there any signs in the lung?", ["yes"]]], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "lung_signs_volume loss"}], ["Is there an pneumonectomy in the lung?", ["no"], [["Are there any signs in the lung?", ["yes"]]], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "lung_signs_pneumonectomy"}], ["Is there anything abnormal in the lung?", ["yes"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "lung_body_regions"}], ["Is there anything abnormal in the whole lung?", ["no"], [["Is there anything abnormal in the lung?", ["yes"]]], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "lung_body_regions"}], ["Is there anything abnormal in the diaphragm?", ["no"], [["Is there anything abnormal in the lung?", ["yes"]]], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "lung_body_regions_diaphragm"}], ["Is there anything abnormal in the costophrenic angle?", ["yes"], [["Is there anything abnormal in the lung?", ["yes"]]], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "lung_body_regions_costophrenic angle"}], ["In which area?", ["bilateral"], [["Is there anything abnormal in the lung?", ["yes"]], ["Is there anything abnormal in the costophrenic angle?", ["yes"]]], {"answer_type": "single_choice", "options": ["bilateral", "left", "right", "unspecified"], "path": "lung_body_regions_costophrenic angle_localization"}], ["What are the attributes?", ["blunted"], [["Is there anything abnormal in the lung?", ["yes"]], ["Is there anything abnormal in the costophrenic angle?", ["yes"]], ["In which area?", ["bilateral"]]], {"answer_type": "single_choice", "options": ["blunted", "obscured"], "path": "lung_body_regions_costophrenic angle_attributes"}], ["What is the degree?", ["mild"], [["Is there anything abnormal in the lung?", ["yes"]], ["Is there anything abnormal in the costophrenic angle?", ["yes"]], ["In which area?", ["bilateral"]], ["What are the attributes?", ["blunted"]]], {"answer_type": "single_choice", "options": ["chronic", "mild", "no selection"], "path": "lung_body_regions_costophrenic angle_degree"}], ["Is there anything abnormal in the hilum?", ["no"], [["Is there anything abnormal in the lung?", ["yes"]]], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "lung_body_regions_hilum"}], ["Is there anything abnormal in the apex?", ["no"], [["Is there anything abnormal in the lung?", ["yes"]]], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "lung_body_regions_apex"}], ["Is there anything abnormal in the azygos lobe?", ["no"], [["Is there anything abnormal in the lung?", ["yes"]]], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "lung_body_regions_azygos lobe"}], ["Is there anything abnormal in the blood vessels?", ["no"], [["Is there anything abnormal in the lung?", ["yes"]]], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "lung_body_regions_blood vessels"}], ["Are there any diseases in the lung?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "lung_diseases"}], ["Are there any signs in the pleura?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "pleura_signs"}], ["Is there anything abnormal in the pleura?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "pleura_body_regions"}], ["Are there any diseases in the pleura?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "pleura_diseases"}], ["Are there any signs in the trachea?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "trachea_signs"}], ["Is there anything abnormal in the trachea?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "trachea_body_regions"}], ["Are there any diseases in the trachea?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "trachea_diseases"}], ["Are there any signs in the cardiovascular system?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "cardiovascular system_signs"}], ["Is there anything abnormal in the cardiovascular system?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "cardiovascular system_body_regions"}], ["Are there any diseases in the cardiovascular system?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "cardiovascular system_diseases"}], ["Are there any signs in the skeletal system?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "skeletal system_signs"}], ["Is there anything abnormal in the skeletal system?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "skeletal system_body_regions"}], ["Are there any diseases in the skeletal system?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "skeletal system_diseases"}], ["Are there any signs in the breast?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "breast_signs"}], ["Are there any diseases in the breast?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "breast_diseases"}], ["Are there any signs in the abdomen?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "abdomen_signs"}], ["Is there anything abnormal in the abdomen?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "abdomen_infos"}], ["Are there any diseases in the abdomen?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "abdomen_diseases"}], ["Are there any signs in the thorax?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "thorax_signs"}], ["Are there any diseases in the thorax?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "thorax_diseases"}], ["Are there any signs in the mediastinum?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "mediastinum_signs"}], ["Is there anything abnormal in the mediastinum?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "mediastinum_infos"}], ["Are there any diseases in the mediastinum?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "mediastinum_diseases"}], ["Is there anything abnormal in the lymph nodes?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "lymph nodes_infos"}], ["Are there any diseases in the lymph nodes?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "lymph nodes_diseases"}]]
之前的代码版本/注意力关键词用于sam的/MedEvalKit/datas/Radrestruct/test_qa_pairs/3954.json ADDED
@@ -0,0 +1 @@
 
 
1
+ [["Are there any foreign objects?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "foreign objects_objects"}], ["Are there any signs in the lung?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "lung_signs"}], ["Is there anything abnormal in the lung?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "lung_body_regions"}], ["Are there any diseases in the lung?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "lung_diseases"}], ["Are there any signs in the pleura?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "pleura_signs"}], ["Is there anything abnormal in the pleura?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "pleura_body_regions"}], ["Are there any diseases in the pleura?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "pleura_diseases"}], ["Are there any signs in the trachea?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "trachea_signs"}], ["Is there anything abnormal in the trachea?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "trachea_body_regions"}], ["Are there any diseases in the trachea?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "trachea_diseases"}], ["Are there any signs in the cardiovascular system?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "cardiovascular system_signs"}], ["Is there anything abnormal in the cardiovascular system?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "cardiovascular system_body_regions"}], ["Are there any diseases in the cardiovascular system?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "cardiovascular system_diseases"}], ["Are there any signs in the skeletal system?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "skeletal system_signs"}], ["Is there anything abnormal in the skeletal system?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "skeletal system_body_regions"}], ["Are there any diseases in the skeletal system?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "skeletal system_diseases"}], ["Are there any signs in the breast?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "breast_signs"}], ["Are there any diseases in the breast?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "breast_diseases"}], ["Are there any signs in the abdomen?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "abdomen_signs"}], ["Is there anything abnormal in the abdomen?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "abdomen_infos"}], ["Are there any diseases in the abdomen?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "abdomen_diseases"}], ["Are there any signs in the thorax?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "thorax_signs"}], ["Are there any diseases in the thorax?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "thorax_diseases"}], ["Are there any signs in the mediastinum?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "mediastinum_signs"}], ["Is there anything abnormal in the mediastinum?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "mediastinum_infos"}], ["Are there any diseases in the mediastinum?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "mediastinum_diseases"}], ["Is there anything abnormal in the lymph nodes?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "lymph nodes_infos"}], ["Are there any diseases in the lymph nodes?", ["no"], [], {"answer_type": "single_choice", "options": ["yes", "no"], "path": "lymph nodes_diseases"}]]
之前的代码版本/第一版-全部代码/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/llava/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ from .model import LlavaLlamaForCausalLM
之前的代码版本/第一版-全部代码/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/llava/constants.py ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ CONTROLLER_HEART_BEAT_EXPIRATION = 30
2
+ WORKER_HEART_BEAT_INTERVAL = 15
3
+
4
+ LOGDIR = "."
5
+
6
+ # Model Constants
7
+ IGNORE_INDEX = -100
8
+ IMAGE_TOKEN_INDEX = -200
9
+ DEFAULT_IMAGE_TOKEN = "<image>"
10
+ DEFAULT_IMAGE_PATCH_TOKEN = "<im_patch>"
11
+ DEFAULT_IM_START_TOKEN = "<im_start>"
12
+ DEFAULT_IM_END_TOKEN = "<im_end>"
之前的代码版本/第一版-全部代码/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/llava/conversation.py ADDED
@@ -0,0 +1,597 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import dataclasses
2
+ from enum import auto, Enum
3
+ from typing import List, Any, Dict, Union, Tuple
4
+ import re
5
+ import base64
6
+ from io import BytesIO
7
+ from PIL import Image
8
+ from transformers import AutoTokenizer
9
+
10
+
11
+ class SeparatorStyle(Enum):
12
+ """Different separator style."""
13
+
14
+ SINGLE = auto()
15
+ TWO = auto()
16
+ MPT = auto()
17
+ PLAIN = auto()
18
+ CHATML = auto()
19
+ LLAMA_2 = auto()
20
+ LLAMA_3 = auto()
21
+ QWEN = auto()
22
+ GEMMA = auto()
23
+
24
+
25
+ @dataclasses.dataclass
26
+ class Conversation:
27
+ """A class that keeps all conversation history."""
28
+
29
+ system: str
30
+ roles: List[str]
31
+ messages: List[List[str]]
32
+ offset: int
33
+ sep_style: SeparatorStyle = SeparatorStyle.SINGLE
34
+ sep: str = "###"
35
+ sep2: str = None
36
+ version: str = "Unknown"
37
+
38
+ tokenizer_id: str = ""
39
+ tokenizer: Any = None
40
+ # Stop criteria (the default one is EOS token)
41
+ stop_str: Union[str, List[str]] = None
42
+ # Stops generation if meeting any token in this list
43
+ stop_token_ids: List[int] = None
44
+
45
+ skip_next: bool = False
46
+
47
+ def get_prompt(self):
48
+ messages = self.messages
49
+ if len(messages) > 0 and type(messages[0][1]) is tuple:
50
+ messages = self.messages.copy()
51
+ init_role, init_msg = messages[0].copy()
52
+ init_msg = init_msg[0]
53
+ if "mmtag" in self.version:
54
+ init_msg = init_msg.replace("<image>", "").strip()
55
+ messages[0] = (init_role, init_msg)
56
+ messages.insert(0, (self.roles[0], "<Image><image></Image>"))
57
+ messages.insert(1, (self.roles[1], "Received."))
58
+ elif not init_msg.startswith("<image>"):
59
+ init_msg = init_msg.replace("<image>", "").strip()
60
+ messages[0] = (init_role, "<image>\n" + init_msg)
61
+ else:
62
+ messages[0] = (init_role, init_msg)
63
+
64
+ if self.sep_style == SeparatorStyle.SINGLE:
65
+ ret = self.system + self.sep
66
+ for role, message in messages:
67
+ if message:
68
+ if type(message) is tuple:
69
+ message, _, _ = message
70
+ ret += role + ": " + message + self.sep
71
+ else:
72
+ ret += role + ":"
73
+
74
+ elif self.sep_style == SeparatorStyle.TWO:
75
+ seps = [self.sep, self.sep2]
76
+ ret = self.system + seps[0]
77
+ for i, (role, message) in enumerate(messages):
78
+ if message:
79
+ if type(message) is tuple:
80
+ message, _, _ = message
81
+ ret += role + ": " + message + seps[i % 2]
82
+ else:
83
+ ret += role + ":"
84
+
85
+ elif self.sep_style == SeparatorStyle.CHATML:
86
+ ret = "" if self.system == "" else self.system + self.sep + "\n"
87
+ for role, message in messages:
88
+ if message:
89
+ if type(message) is tuple:
90
+ message, images, _ = message
91
+ message = "<image>" * len(images) + message
92
+ ret += role + "\n" + message + self.sep + "\n"
93
+ else:
94
+ ret += role + "\n"
95
+ return ret
96
+
97
+ elif self.sep_style == SeparatorStyle.LLAMA_3:
98
+ if self.tokenizer is None:
99
+ raise ValueError("Llama 3 tokenizer is not available. Make sure you have the necessary permissions.")
100
+ chat_template_messages = [{"role": "system", "content": self.system}]
101
+ for role, message in messages:
102
+ if message:
103
+ if type(message) is tuple:
104
+ message, images = message
105
+ message = "<image>" * len(images) + message
106
+ chat_template_messages.append({"role": role, "content": message})
107
+
108
+ # print(chat_template_messages)
109
+ return self.tokenizer.apply_chat_template(chat_template_messages, tokenize=False, add_generation_prompt=True)
110
+ # ret = "" if self.system == "" else self.system + self.sep + "\n"
111
+ # for role, message in messages:
112
+ # if message:
113
+ # if type(message) is tuple:
114
+ # message, images = message
115
+ # message = "<image>" * len(images) + message
116
+ # ret += role + "\n" + message + self.sep + "\n"
117
+ # else:
118
+ # ret += role + "\n"
119
+ # return ret
120
+
121
+ elif self.sep_style == SeparatorStyle.MPT:
122
+ ret = self.system + self.sep
123
+ for role, message in messages:
124
+ if message:
125
+ if type(message) is tuple:
126
+ message, _, _ = message
127
+ ret += role + message + self.sep
128
+ else:
129
+ ret += role
130
+
131
+ elif self.sep_style == SeparatorStyle.GEMMA:
132
+ ret = ""
133
+ for i, (role, message) in enumerate(messages):
134
+ assert role == self.roles[i % 2], "Conversation should alternate user/assistant/user/assistant/..."
135
+ if message:
136
+ if type(message) is tuple:
137
+ message, _, _ = message
138
+ ret += role + message + self.sep
139
+ else:
140
+ ret += role
141
+
142
+ elif self.sep_style == SeparatorStyle.LLAMA_2:
143
+ wrap_sys = lambda msg: f"<<SYS>>\n{msg}\n<</SYS>>\n\n" if len(msg) > 0 else msg
144
+ wrap_inst = lambda msg: f"[INST] {msg} [/INST]"
145
+ ret = ""
146
+
147
+ for i, (role, message) in enumerate(messages):
148
+ if i == 0:
149
+ assert message, "first message should not be none"
150
+ assert role == self.roles[0], "first message should come from user"
151
+ if message:
152
+ if type(message) is tuple:
153
+ message, _, _ = message
154
+ if i == 0:
155
+ message = wrap_sys(self.system) + message
156
+ if i % 2 == 0:
157
+ message = wrap_inst(message)
158
+ ret += self.sep + message
159
+ else:
160
+ ret += " " + message + " " + self.sep2
161
+ else:
162
+ ret += ""
163
+ ret = ret.lstrip(self.sep)
164
+
165
+ elif self.sep_style == SeparatorStyle.PLAIN:
166
+ seps = [self.sep, self.sep2]
167
+ ret = self.system
168
+ for i, (role, message) in enumerate(messages):
169
+ if message:
170
+ if type(message) is tuple:
171
+ message, _, _ = message
172
+ ret += message + seps[i % 2]
173
+ else:
174
+ ret += ""
175
+ else:
176
+ raise ValueError(f"Invalid style: {self.sep_style}")
177
+
178
+ return ret
179
+
180
+ def append_message(self, role, message):
181
+ self.messages.append([role, message])
182
+
183
+ def process_image(self, image, image_process_mode, return_pil=False, image_format="PNG"):
184
+ if image_process_mode == "Pad":
185
+
186
+ def expand2square(pil_img, background_color=(122, 116, 104)):
187
+ width, height = pil_img.size
188
+ if width == height:
189
+ return pil_img
190
+ elif width > height:
191
+ result = Image.new(pil_img.mode, (width, width), background_color)
192
+ result.paste(pil_img, (0, (width - height) // 2))
193
+ return result
194
+ else:
195
+ result = Image.new(pil_img.mode, (height, height), background_color)
196
+ result.paste(pil_img, ((height - width) // 2, 0))
197
+ return result
198
+
199
+ image = expand2square(image)
200
+ elif image_process_mode in ["Default", "Crop"]:
201
+ pass
202
+ elif image_process_mode == "Resize":
203
+ image = image.resize((336, 336))
204
+ else:
205
+ raise ValueError(f"Invalid image_process_mode: {image_process_mode}")
206
+
207
+ if type(image) is not Image.Image:
208
+ image = Image.open(image).convert("RGB")
209
+
210
+ max_hw, min_hw = max(image.size), min(image.size)
211
+ aspect_ratio = max_hw / min_hw
212
+ max_len, min_len = 672, 448
213
+ shortest_edge = int(min(max_len / aspect_ratio, min_len, min_hw))
214
+ longest_edge = int(shortest_edge * aspect_ratio)
215
+ W, H = image.size
216
+ if H > W:
217
+ H, W = longest_edge, shortest_edge
218
+ else:
219
+ H, W = shortest_edge, longest_edge
220
+ image = image.resize((W, H))
221
+ if return_pil:
222
+ return image
223
+ else:
224
+ buffered = BytesIO()
225
+ image.save(buffered, format=image_format)
226
+ img_b64_str = base64.b64encode(buffered.getvalue()).decode()
227
+ return img_b64_str
228
+
229
+ def get_images(self, return_pil=False, return_path=False):
230
+ images = []
231
+ for i, (role, msg) in enumerate(self.messages[self.offset :]):
232
+ if i % 2 == 0:
233
+ if type(msg) is tuple:
234
+ msg, image, image_process_mode = msg
235
+ if type(image) != list:
236
+ image = [image]
237
+ for img in image:
238
+ if not return_path and self.is_image_file(img):
239
+ img = self.process_image(img, image_process_mode, return_pil=return_pil)
240
+ else:
241
+ images.append(img)
242
+ return images
243
+
244
+ def is_image_file(self, filename):
245
+ image_extensions = [".png", ".jpg", ".jpeg", ".gif", ".bmp", ".tiff", ".webp"]
246
+ return any(filename.lower().endswith(ext) for ext in image_extensions)
247
+
248
+ def is_video_file(self, filename):
249
+ video_extensions = [".mp4", ".mov", ".avi", ".mkv", ".wmv", ".flv", ".mpeg", ".mpg"]
250
+ return any(filename.lower().endswith(ext) for ext in video_extensions)
251
+
252
+ def to_gradio_chatbot(self):
253
+ ret = []
254
+ for i, (role, msg) in enumerate(self.messages[self.offset :]):
255
+ if i % 2 == 0:
256
+ if type(msg) is tuple:
257
+ msg, image, image_process_mode = msg
258
+ if type(image) != list:
259
+ image = [image]
260
+ if len(image) == 1:
261
+ msg = "<image>\n" + msg.replace("<image>", "").strip()
262
+ else:
263
+ msg = re.sub(r"(<image>)\n(?=<image>)", r"\1 ", msg)
264
+
265
+ img_str_list = []
266
+ for img in image:
267
+ if self.is_image_file(img):
268
+ img_b64_str = self.process_image(img, "Default", return_pil=False, image_format="JPEG")
269
+ img_str = f'<img src="data:image/jpeg;base64,{img_b64_str}" style="max-width: 256px; max-height: 256px; width: auto; height: auto; object-fit: contain;"/>'
270
+ img_str_list.append(img_str)
271
+ elif self.is_video_file(img):
272
+ ret.append(((img,), None))
273
+
274
+ msg = msg.strip()
275
+ img_place_holder = ""
276
+ for img_str in img_str_list:
277
+ img_place_holder += f"{img_str}\n\n"
278
+
279
+ if len(img_str_list) > 0:
280
+ msg = f"{img_place_holder}\n\n{msg}"
281
+
282
+ if len(msg) > 0:
283
+ ret.append([msg, None])
284
+ else:
285
+ ret.append([msg, None])
286
+ else:
287
+ ret[-1][-1] = msg
288
+ return ret
289
+
290
+ def copy(self):
291
+ return Conversation(system=self.system, roles=self.roles, messages=[[x, y] for x, y in self.messages], offset=self.offset, sep_style=self.sep_style, sep=self.sep, sep2=self.sep2, version=self.version)
292
+
293
+ def dict(self):
294
+ if len(self.get_images()) > 0:
295
+ return {
296
+ "system": self.system,
297
+ "roles": self.roles,
298
+ "messages": [[x, y[0] if type(y) is tuple else y] for x, y in self.messages],
299
+ "offset": self.offset,
300
+ "sep": self.sep,
301
+ "sep2": self.sep2,
302
+ }
303
+ return {
304
+ "system": self.system,
305
+ "roles": self.roles,
306
+ "messages": self.messages,
307
+ "offset": self.offset,
308
+ "sep": self.sep,
309
+ "sep2": self.sep2,
310
+ }
311
+
312
+
313
+ conv_vicuna_v0 = Conversation(
314
+ system="A chat between a curious human and an artificial intelligence assistant. " "The assistant gives helpful, detailed, and polite answers to the human's questions.",
315
+ roles=("Human", "Assistant"),
316
+ messages=[
317
+ ["Human", "What are the key differences between renewable and non-renewable energy sources?"],
318
+ [
319
+ "Assistant",
320
+ "Renewable energy sources are those that can be replenished naturally in a relatively "
321
+ "short amount of time, such as solar, wind, hydro, geothermal, and biomass. "
322
+ "Non-renewable energy sources, on the other hand, are finite and will eventually be "
323
+ "depleted, such as coal, oil, and natural gas. Here are some key differences between "
324
+ "renewable and non-renewable energy sources:\n"
325
+ "1. Availability: Renewable energy sources are virtually inexhaustible, while non-renewable "
326
+ "energy sources are finite and will eventually run out.\n"
327
+ "2. Environmental impact: Renewable energy sources have a much lower environmental impact "
328
+ "than non-renewable sources, which can lead to air and water pollution, greenhouse gas emissions, "
329
+ "and other negative effects.\n"
330
+ "3. Cost: Renewable energy sources can be more expensive to initially set up, but they typically "
331
+ "have lower operational costs than non-renewable sources.\n"
332
+ "4. Reliability: Renewable energy sources are often more reliable and can be used in more remote "
333
+ "locations than non-renewable sources.\n"
334
+ "5. Flexibility: Renewable energy sources are often more flexible and can be adapted to different "
335
+ "situations and needs, while non-renewable sources are more rigid and inflexible.\n"
336
+ "6. Sustainability: Renewable energy sources are more sustainable over the long term, while "
337
+ "non-renewable sources are not, and their depletion can lead to economic and social instability.\n",
338
+ ],
339
+ ],
340
+ offset=2,
341
+ sep_style=SeparatorStyle.SINGLE,
342
+ sep="###",
343
+ )
344
+
345
+ conv_vicuna_v1 = Conversation(
346
+ system="A chat between a curious user and an artificial intelligence assistant. " "The assistant gives helpful, detailed, and polite answers to the user's questions.",
347
+ roles=("USER", "ASSISTANT"),
348
+ version="v1",
349
+ messages=[],
350
+ offset=0,
351
+ sep_style=SeparatorStyle.TWO,
352
+ sep=" ",
353
+ sep2="</s>",
354
+ )
355
+
356
+ conv_llama_2 = Conversation(
357
+ system="""You are a helpful, respectful and honest assistant. Always answer as helpfully as possible, while being safe. Your answers should not include any harmful, unethical, racist, sexist, toxic, dangerous, or illegal content. Please ensure that your responses are socially unbiased and positive in nature.
358
+
359
+ If a question does not make any sense, or is not factually coherent, explain why instead of answering something not correct. If you don't know the answer to a question, please don't share false information.""",
360
+ roles=("USER", "ASSISTANT"),
361
+ version="llama_v2",
362
+ messages=[],
363
+ offset=0,
364
+ sep_style=SeparatorStyle.LLAMA_2,
365
+ sep="<s>",
366
+ sep2="</s>",
367
+ )
368
+
369
+ conv_llava_llama_2 = Conversation(
370
+ system="You are a helpful language and vision assistant. " "You are able to understand the visual content that the user provides, " "and assist the user with a variety of tasks using natural language.",
371
+ roles=("USER", "ASSISTANT"),
372
+ version="llama_v2",
373
+ messages=[],
374
+ offset=0,
375
+ sep_style=SeparatorStyle.LLAMA_2,
376
+ sep="<s>",
377
+ sep2="</s>",
378
+ )
379
+
380
+ def safe_load_tokenizer(tokenizer_id):
381
+ try:
382
+ return AutoTokenizer.from_pretrained(tokenizer_id)
383
+ except Exception:
384
+ return None
385
+
386
+ conv_llava_llama_3 = Conversation(
387
+ system="You are a helpful language and vision assistant. " "You are able to understand the visual content that the user provides, " "and assist the user with a variety of tasks using natural language.",
388
+ roles=("user", "assistant"),
389
+ version="llama_v3",
390
+ messages=[],
391
+ offset=0,
392
+ sep="<|eot_id|>",
393
+ sep_style=SeparatorStyle.LLAMA_3,
394
+ tokenizer_id="meta-llama/Meta-Llama-3-8B-Instruct",
395
+ tokenizer=safe_load_tokenizer("meta-llama/Meta-Llama-3-8B-Instruct"),
396
+ stop_token_ids=[128009],
397
+ )
398
+
399
+ conv_mistral_instruct = Conversation(
400
+ system="",
401
+ roles=("USER", "ASSISTANT"),
402
+ version="llama_v2",
403
+ messages=[],
404
+ offset=0,
405
+ sep_style=SeparatorStyle.LLAMA_2,
406
+ sep="",
407
+ sep2="</s>",
408
+ )
409
+
410
+ conv_llava_llama_2_simple = Conversation(
411
+ system="Answer the questions about the visual content that the user provides.",
412
+ roles=("USER", "ASSISTANT"),
413
+ version="llama_v2",
414
+ messages=[],
415
+ offset=0,
416
+ sep_style=SeparatorStyle.LLAMA_2,
417
+ sep="<s>",
418
+ sep2="</s>",
419
+ )
420
+
421
+ conv_llava_llama_2_mmtag = Conversation(
422
+ system="Answer the questions about the visual content that the user provides." "The visual content will be provided with the following format: <Image>visual content</Image>.",
423
+ roles=("USER", "ASSISTANT"),
424
+ version="llama_v2_mmtag",
425
+ messages=[],
426
+ offset=0,
427
+ sep_style=SeparatorStyle.LLAMA_2,
428
+ sep="<s>",
429
+ sep2="</s>",
430
+ )
431
+
432
+ conv_mpt = Conversation(
433
+ system="""<|im_start|>system
434
+ A conversation between a user and an LLM-based AI assistant. The assistant gives helpful and honest answers.""",
435
+ roles=("<|im_start|>user\n", "<|im_start|>assistant\n"),
436
+ version="mpt",
437
+ messages=[],
438
+ offset=0,
439
+ sep_style=SeparatorStyle.MPT,
440
+ sep="<|im_end|>",
441
+ )
442
+
443
+ conv_qwen = Conversation(
444
+ system="""<|im_start|>system
445
+ You are a helpful assistant.""",
446
+ roles=("<|im_start|>user", "<|im_start|>assistant"),
447
+ version="qwen",
448
+ messages=[],
449
+ offset=0,
450
+ sep_style=SeparatorStyle.CHATML,
451
+ sep="<|im_end|>",
452
+ )
453
+
454
+ conv_qwen_2_5 = Conversation(
455
+ system="""<|im_start|>system
456
+ You are Qwen, created by Alibaba Cloud. You are a helpful assistant.""",
457
+ roles=("<|im_start|>user", "<|im_start|>assistant"),
458
+ version="qwen",
459
+ messages=[],
460
+ offset=0,
461
+ sep_style=SeparatorStyle.CHATML,
462
+ sep="<|im_end|>",
463
+ )
464
+
465
+ conv_gemma_instruct = Conversation(system="", roles=("<start_of_turn>user\n", "<start_of_turn>model\n"), version="gemma", messages=[], offset=0, sep_style=SeparatorStyle.GEMMA, sep="<end_of_turn>\n")
466
+
467
+ conv_llava_plain = Conversation(
468
+ system="",
469
+ roles=("", ""),
470
+ messages=[],
471
+ offset=0,
472
+ sep_style=SeparatorStyle.PLAIN,
473
+ sep="\n",
474
+ )
475
+
476
+ conv_llava_v0 = Conversation(
477
+ system="A chat between a curious human and an artificial intelligence assistant. " "The assistant gives helpful, detailed, and polite answers to the human's questions.",
478
+ roles=("Human", "Assistant"),
479
+ messages=[],
480
+ offset=0,
481
+ sep_style=SeparatorStyle.SINGLE,
482
+ sep="###",
483
+ )
484
+
485
+ conv_llava_v0_mmtag = Conversation(
486
+ system="A chat between a curious user and an artificial intelligence assistant. "
487
+ "The assistant is able to understand the visual content that the user provides, and assist the user with a variety of tasks using natural language."
488
+ "The visual content will be provided with the following format: <Image>visual content</Image>.",
489
+ roles=("Human", "Assistant"),
490
+ messages=[],
491
+ offset=0,
492
+ sep_style=SeparatorStyle.SINGLE,
493
+ sep="###",
494
+ version="v0_mmtag",
495
+ )
496
+
497
+ conv_llava_v1 = Conversation(
498
+ system="A chat between a curious human and an artificial intelligence assistant. " "The assistant gives helpful, detailed, and polite answers to the human's questions.",
499
+ roles=("USER", "ASSISTANT"),
500
+ version="v1",
501
+ messages=[],
502
+ offset=0,
503
+ sep_style=SeparatorStyle.TWO,
504
+ sep=" ",
505
+ sep2="</s>",
506
+ )
507
+
508
+ conv_llava_v1_mmtag = Conversation(
509
+ system="A chat between a curious user and an artificial intelligence assistant. "
510
+ "The assistant is able to understand the visual content that the user provides, and assist the user with a variety of tasks using natural language."
511
+ "The visual content will be provided with the following format: <Image>visual content</Image>.",
512
+ roles=("USER", "ASSISTANT"),
513
+ messages=[],
514
+ offset=0,
515
+ sep_style=SeparatorStyle.TWO,
516
+ sep=" ",
517
+ sep2="</s>",
518
+ version="v1_mmtag",
519
+ )
520
+
521
+ conv_mistral_orca = Conversation(
522
+ system="""<|im_start|>system
523
+ You are MistralOrca, a large language model trained by Alignment Lab AI. Write out your reasoning step-by-step to be sure you get the right answers!""",
524
+ roles=("<|im_start|>user\n", "<|im_start|>assistant\n"),
525
+ version="mpt",
526
+ messages=[],
527
+ offset=0,
528
+ sep_style=SeparatorStyle.MPT,
529
+ sep="<|im_end|>",
530
+ )
531
+
532
+ conv_mistral_zephyr = Conversation(
533
+ system="""<|system|>
534
+ You are a helpful AI assistant.""",
535
+ roles=("<|user|>\n", "<|assistant|>\n"),
536
+ version="mpt",
537
+ messages=[],
538
+ offset=0,
539
+ sep_style=SeparatorStyle.MPT,
540
+ sep="</s>",
541
+ )
542
+
543
+ conv_mistral_direct = Conversation(
544
+ system="""<|im_start|>system
545
+ Answer the questions.""",
546
+ roles=("<|im_start|>user\n", "<|im_start|>assistant\n"),
547
+ version="mpt",
548
+ messages=[],
549
+ offset=0,
550
+ sep_style=SeparatorStyle.MPT,
551
+ sep="<|im_end|>",
552
+ )
553
+
554
+ conv_chatml_direct = Conversation(
555
+ system="""<|im_start|>system
556
+ Answer the questions.""",
557
+ roles=("<|im_start|>user\n", "<|im_start|>assistant\n"),
558
+ version="mpt",
559
+ messages=[],
560
+ offset=0,
561
+ sep_style=SeparatorStyle.MPT,
562
+ sep="<|im_end|>",
563
+ )
564
+
565
+ default_conversation = conv_vicuna_v0
566
+ conv_templates = {
567
+ "default": conv_vicuna_v0,
568
+ "v0": conv_vicuna_v0,
569
+ "v1": conv_vicuna_v1,
570
+ "vicuna_v1": conv_vicuna_v1,
571
+ "llama_2": conv_llama_2,
572
+ "mistral_instruct": conv_mistral_instruct,
573
+ "mistral_orca": conv_mistral_orca,
574
+ "mistral_zephyr": conv_mistral_zephyr,
575
+ "mistral_direct": conv_mistral_direct,
576
+ "plain": conv_llava_plain,
577
+ "v0_plain": conv_llava_plain,
578
+ "chatml_direct": conv_chatml_direct,
579
+ "llava_v0": conv_llava_v0,
580
+ "llava_v0_mmtag": conv_llava_v0_mmtag,
581
+ "llava_v1": conv_llava_v1,
582
+ "llava_v1_mmtag": conv_llava_v1_mmtag,
583
+ "llava_llama_2": conv_llava_llama_2,
584
+ "llava_llama_3": conv_llava_llama_3,
585
+ "llava_llama_2_simple": conv_llava_llama_2_simple,
586
+ "llava_llama_2_mmtag": conv_llava_llama_2_mmtag,
587
+ "llava_mistral_instruct": conv_mistral_instruct,
588
+ "mpt": conv_mpt,
589
+ "qwen_1_5": conv_qwen,
590
+ "qwen_2": conv_qwen,
591
+ "qwen_2_5": conv_qwen_2_5,
592
+ "gemma_instruct": conv_gemma_instruct,
593
+ }
594
+
595
+
596
+ if __name__ == "__main__":
597
+ print(default_conversation.get_prompt())
之前的代码版本/第一版-全部代码/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/llava/mm_utils.py ADDED
@@ -0,0 +1,395 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from PIL import Image
2
+ from io import BytesIO
3
+ import base64
4
+ import math
5
+ import ast
6
+ import re
7
+ import torch
8
+ from transformers import StoppingCriteria
9
+ from llava.constants import IMAGE_TOKEN_INDEX
10
+
11
+
12
+ def resize_and_center_crop(image, shortest_edge_length):
13
+ # Calculate new dimensions and resize
14
+ aspect_ratio = float(image.width) / float(image.height)
15
+ if aspect_ratio > 1:
16
+ new_width = int(shortest_edge_length * aspect_ratio)
17
+ new_height = shortest_edge_length
18
+ else:
19
+ new_width = shortest_edge_length
20
+ new_height = int(shortest_edge_length / aspect_ratio)
21
+ resized_image = image.resize((new_width, new_height), Image.ANTIALIAS)
22
+
23
+ # Calculate the position and perform the center crop
24
+ left = (new_width - shortest_edge_length) / 2
25
+ top = (new_height - shortest_edge_length) / 2
26
+ right = (new_width + shortest_edge_length) / 2
27
+ bottom = (new_height + shortest_edge_length) / 2
28
+ cropped_image = resized_image.crop((left, top, right, bottom))
29
+
30
+ return cropped_image
31
+
32
+
33
+ def auto_pad_images(image, grid_params):
34
+ assert isinstance(image, Image.Image), "Input should be a Pillow Image"
35
+ assert len(grid_params) > 0, "Grid parameters should not be empty"
36
+
37
+ # Step 1: Calculate and find the closest aspect ratio
38
+ input_width, input_height = image.size
39
+ input_aspect_ratio = input_width / input_height
40
+ candidate_resolutions = [(w / h, w, h) for w in grid_params for h in grid_params]
41
+ closest_aspect_ratio = min(candidate_resolutions, key=lambda x: abs(input_aspect_ratio - x[0]))
42
+
43
+ candidate_resolutions = [(x[1], x[2]) for x in candidate_resolutions if abs(x[0] - closest_aspect_ratio[0]) < 1e-3]
44
+
45
+ target_resolution = min(candidate_resolutions, key=lambda res: abs(max(input_width, input_height) / max(res) - 1))
46
+
47
+ resize_width, resize_height = target_resolution
48
+ if input_width > input_height:
49
+ resize_height = int(resize_width / input_aspect_ratio)
50
+ else:
51
+ resize_width = int(resize_height * input_aspect_ratio)
52
+ resized_image = image.resize((resize_width, resize_height), Image.ANTIALIAS)
53
+
54
+ # Step 5: Pad the resized image if necessary to match the target resolution
55
+ pad_width = target_resolution[0] - resize_width
56
+ pad_height = target_resolution[1] - resize_height
57
+ padded_image = Image.new("RGB", target_resolution, color=(0, 0, 0))
58
+ padded_image.paste(resized_image, (pad_width // 2, pad_height // 2))
59
+
60
+ return padded_image
61
+
62
+
63
+ def extract_patches(image, patch_size, overlap_ratio):
64
+ assert isinstance(image, Image.Image), "Input should be a Pillow Image"
65
+ assert patch_size > 0, "Patch size should be greater than 0"
66
+ assert 0 <= overlap_ratio < 1, "Overlap ratio should be between 0 and 1"
67
+
68
+ W, H = image.size
69
+ patches = []
70
+
71
+ stride = int(patch_size * (1 - overlap_ratio))
72
+
73
+ num_patches_y = (H - patch_size) // stride + 1
74
+ num_patches_x = (W - patch_size) // stride + 1
75
+
76
+ y_start = (H - (num_patches_y - 1) * stride - patch_size) // 2
77
+ x_start = (W - (num_patches_x - 1) * stride - patch_size) // 2
78
+
79
+ for y in range(y_start, y_start + num_patches_y * stride, stride):
80
+ for x in range(x_start, x_start + num_patches_x * stride, stride):
81
+ patch = image.crop((x, y, x + patch_size, y + patch_size))
82
+ patches.append(patch)
83
+
84
+ return patches
85
+
86
+
87
+ def process_highres_image_crop_split(image, data_args, processor=None):
88
+ crop_resolution = data_args.image_crop_resolution
89
+ split_resolution = data_args.image_split_resolution
90
+ if processor is None:
91
+ processor = data_args.image_processor
92
+ image_crop = resize_and_center_crop(image, crop_resolution)
93
+ image_patches = extract_patches(image_crop, patch_size=split_resolution, overlap_ratio=0)
94
+ image_patches = [processor.preprocess(image_patch, return_tensors="pt")["pixel_values"][0] for image_patch in image_patches]
95
+ return torch.stack(image_patches, dim=0)
96
+
97
+
98
+ def process_highres_image(image, processor, grid_pinpoints):
99
+ grid_params = [int(x) for x in grid_pinpoints.split(",")]
100
+ width_height = max(image.size)
101
+ fit_grid_params = [x for x in grid_params if x >= width_height]
102
+ if len(fit_grid_params) == 0:
103
+ select_size = max(grid_params)
104
+ else:
105
+ select_size = min(fit_grid_params)
106
+ # FIXME: always select the 448
107
+ select_size = max(grid_params)
108
+ image_padded = expand2square(image, tuple(int(x * 255) for x in processor.image_mean))
109
+
110
+ # FIXME: this seems to be a bug that it always resizes instead of padding
111
+ image_original_resize = image.resize((processor.size["shortest_edge"], processor.size["shortest_edge"]))
112
+ image_padded = image_padded.resize((select_size, select_size))
113
+ image_patches = extract_patches(image_padded, patch_size=processor.size["shortest_edge"], overlap_ratio=0)
114
+ image_patches = [image_original_resize] + image_patches
115
+ image_patches = [processor.preprocess(image_patch, return_tensors="pt")["pixel_values"][0] for image_patch in image_patches]
116
+ return torch.stack(image_patches, dim=0)
117
+
118
+
119
+ def select_best_resolution(original_size, possible_resolutions):
120
+ """
121
+ Selects the best resolution from a list of possible resolutions based on the original size.
122
+
123
+ Args:
124
+ original_size (tuple): The original size of the image in the format (width, height).
125
+ possible_resolutions (list): A list of possible resolutions in the format [(width1, height1), (width2, height2), ...].
126
+
127
+ Returns:
128
+ tuple: The best fit resolution in the format (width, height).
129
+ """
130
+ original_width, original_height = original_size
131
+ best_fit = None
132
+ max_effective_resolution = 0
133
+ min_wasted_resolution = float("inf")
134
+
135
+ for width, height in possible_resolutions:
136
+ # Calculate the downscaled size to keep the aspect ratio
137
+ scale = min(width / original_width, height / original_height)
138
+ downscaled_width, downscaled_height = int(original_width * scale), int(original_height * scale)
139
+
140
+ # Calculate effective and wasted resolutions
141
+ effective_resolution = min(downscaled_width * downscaled_height, original_width * original_height)
142
+ wasted_resolution = (width * height) - effective_resolution
143
+
144
+ if effective_resolution > max_effective_resolution or (effective_resolution == max_effective_resolution and wasted_resolution < min_wasted_resolution):
145
+ max_effective_resolution = effective_resolution
146
+ min_wasted_resolution = wasted_resolution
147
+ best_fit = (width, height)
148
+
149
+ return best_fit
150
+
151
+
152
+ def resize_and_pad_image(image, target_resolution):
153
+ """
154
+ Resize and pad an image to a target resolution while maintaining aspect ratio.
155
+
156
+ Args:
157
+ image (PIL.Image.Image): The input image.
158
+ target_resolution (tuple): The target resolution (width, height) of the image.
159
+
160
+ Returns:
161
+ PIL.Image.Image: The resized and padded image.
162
+ """
163
+ original_width, original_height = image.size
164
+ target_width, target_height = target_resolution
165
+
166
+ # Determine which dimension (width or height) to fill
167
+ scale_w = target_width / original_width
168
+ scale_h = target_height / original_height
169
+
170
+ if scale_w < scale_h:
171
+ # Width will be filled completely
172
+ new_width = target_width
173
+ new_height = min(math.ceil(original_height * scale_w), target_height)
174
+ else:
175
+ # Height will be filled completely
176
+ new_height = target_height
177
+ new_width = min(math.ceil(original_width * scale_h), target_width)
178
+
179
+ # Resize the image
180
+ resized_image = image.resize((new_width, new_height))
181
+
182
+ # Create a new image with the target size and paste the resized image onto it
183
+ new_image = Image.new("RGB", (target_width, target_height), (0, 0, 0))
184
+ paste_x = (target_width - new_width) // 2
185
+ paste_y = (target_height - new_height) // 2
186
+ new_image.paste(resized_image, (paste_x, paste_y))
187
+
188
+ return new_image
189
+
190
+
191
+ def divide_to_patches(image, patch_size):
192
+ """
193
+ Divides an image into patches of a specified size.
194
+
195
+ Args:
196
+ image (PIL.Image.Image): The input image.
197
+ patch_size (int): The size of each patch.
198
+
199
+ Returns:
200
+ list: A list of PIL.Image.Image objects representing the patches.
201
+ """
202
+ patches = []
203
+ width, height = image.size
204
+ for i in range(0, height, patch_size):
205
+ for j in range(0, width, patch_size):
206
+ box = (j, i, j + patch_size, i + patch_size)
207
+ patch = image.crop(box)
208
+ patches.append(patch)
209
+
210
+ return patches
211
+
212
+
213
+ def get_anyres_image_grid_shape(image_size, grid_pinpoints, patch_size):
214
+ """
215
+ Calculate the shape of the image patch grid after the preprocessing for images of any resolution.
216
+
217
+ Args:
218
+ image_size (tuple): The size of the input image in the format (width, height).
219
+ grid_pinpoints (str): A string representation of a list of possible resolutions.
220
+ patch_size (int): The size of each image patch.
221
+
222
+ Returns:
223
+ tuple: The shape of the image patch grid in the format (width, height).
224
+ """
225
+ if isinstance(grid_pinpoints, str) and "x" in grid_pinpoints:
226
+ assert patch_size in [224, 336, 384, 448, 512], "patch_size should be in [224, 336, 384, 448, 512]"
227
+ # Use regex to extract the range from the input string
228
+ matches = re.findall(r"\((\d+)x(\d+)\)", grid_pinpoints)
229
+ range_start = tuple(map(int, matches[0]))
230
+ range_end = tuple(map(int, matches[-1]))
231
+ # Generate a matrix of tuples from (range_start[0], range_start[1]) to (range_end[0], range_end[1])
232
+ grid_pinpoints = [(i, j) for i in range(range_start[0], range_end[0] + 1) for j in range(range_start[1], range_end[1] + 1)]
233
+ # Multiply all elements by patch_size
234
+ grid_pinpoints = [[dim * patch_size for dim in pair] for pair in grid_pinpoints]
235
+ if type(grid_pinpoints) is list:
236
+ possible_resolutions = grid_pinpoints
237
+ else:
238
+ possible_resolutions = ast.literal_eval(grid_pinpoints)
239
+ width, height = select_best_resolution(image_size, possible_resolutions)
240
+ return width // patch_size, height // patch_size
241
+
242
+
243
+ def process_anyres_image(image, processor, grid_pinpoints):
244
+ """
245
+ Process an image with variable resolutions.
246
+
247
+ Args:
248
+ image (PIL.Image.Image): The input image to be processed.
249
+ processor: The image processor object.
250
+ grid_pinpoints (str): A string representation of a list of possible resolutions.
251
+
252
+ Returns:
253
+ torch.Tensor: A tensor containing the processed image patches.
254
+ """
255
+ # Convert grid_pinpoints from string to list
256
+ if isinstance(grid_pinpoints, str) and "x" in grid_pinpoints:
257
+ try:
258
+ patch_size = processor.size[0]
259
+ except Exception as e:
260
+ patch_size = processor.size["shortest_edge"]
261
+ assert patch_size in [224, 336, 384, 448, 512], "patch_size should be in [224, 336, 384, 448, 512]"
262
+ # Use regex to extract the range from the input string
263
+ matches = re.findall(r"\((\d+)x(\d+)\)", grid_pinpoints)
264
+ range_start = tuple(map(int, matches[0]))
265
+ range_end = tuple(map(int, matches[-1]))
266
+ # Generate a matrix of tuples from (range_start[0], range_start[1]) to (range_end[0], range_end[1])
267
+ grid_pinpoints = [(i, j) for i in range(range_start[0], range_end[0] + 1) for j in range(range_start[1], range_end[1] + 1)]
268
+ # Multiply all elements by patch_size
269
+ grid_pinpoints = [[dim * patch_size for dim in pair] for pair in grid_pinpoints]
270
+
271
+ if type(grid_pinpoints) is list:
272
+ possible_resolutions = grid_pinpoints
273
+ else:
274
+ possible_resolutions = ast.literal_eval(grid_pinpoints)
275
+ best_resolution = select_best_resolution(image.size, possible_resolutions)
276
+ image_padded = resize_and_pad_image(image, best_resolution)
277
+
278
+ patches = divide_to_patches(image_padded, processor.crop_size["height"])
279
+
280
+ # FIXME: this seems to be a bug that it resizes instead of pad.
281
+ # but to keep it consistent with previous, i will keep it as it is
282
+ # TODO: uncomment below to ablate with the padding
283
+ if isinstance(processor.size, dict):
284
+ shortest_edge = processor.size["shortest_edge"]
285
+ else:
286
+ shortest_edge = min(processor.size)
287
+ image_original_resize = image.resize((shortest_edge, shortest_edge))
288
+ # image_padded_square = expand2square(image, tuple(int(x*255) for x in processor.image_mean))
289
+ # image_original_resize = image_padded_square.resize((processor.size['shortest_edge'], processor.size['shortest_edge']))
290
+
291
+ image_patches = [image_original_resize] + patches
292
+ image_patches = [processor.preprocess(image_patch, return_tensors="pt")["pixel_values"][0] for image_patch in image_patches]
293
+ return torch.stack(image_patches, dim=0)
294
+
295
+
296
+ def load_image_from_base64(image):
297
+ return Image.open(BytesIO(base64.b64decode(image)))
298
+
299
+
300
+ def expand2square(pil_img, background_color):
301
+ width, height = pil_img.size
302
+ if width == height:
303
+ return pil_img
304
+ elif width > height:
305
+ result = Image.new(pil_img.mode, (width, width), background_color)
306
+ result.paste(pil_img, (0, (width - height) // 2))
307
+ return result
308
+ else:
309
+ result = Image.new(pil_img.mode, (height, height), background_color)
310
+ result.paste(pil_img, ((height - width) // 2, 0))
311
+ return result
312
+
313
+
314
+ def process_images(images, image_processor, model_cfg):
315
+ image_aspect_ratio = getattr(model_cfg, "image_aspect_ratio", None)
316
+ new_images = []
317
+ if image_aspect_ratio == "highres":
318
+ for image in images:
319
+ image = process_highres_image(image, image_processor, model_cfg.image_grid_pinpoints)
320
+ new_images.append(image)
321
+ elif image_aspect_ratio == "anyres" or "anyres_max" in image_aspect_ratio:
322
+ for image in images:
323
+ image = process_anyres_image(image, image_processor, model_cfg.image_grid_pinpoints)
324
+ new_images.append(image)
325
+ elif image_aspect_ratio == "crop_split":
326
+ for image in images:
327
+ image = process_highres_image_crop_split(image, model_cfg, image_processor)
328
+ new_images.append(image)
329
+ elif image_aspect_ratio == "pad":
330
+ for image in images:
331
+ image = expand2square(image, tuple(int(x * 255) for x in image_processor.image_mean))
332
+ image = image_processor.preprocess(image, return_tensors="pt")["pixel_values"][0]
333
+ new_images.append(image)
334
+ else:
335
+ return image_processor.preprocess(images, return_tensors="pt")["pixel_values"]
336
+ if all(x.shape == new_images[0].shape for x in new_images):
337
+ new_images = torch.stack(new_images, dim=0)
338
+ return new_images
339
+
340
+
341
+ def tokenizer_image_token(prompt, tokenizer, image_token_index=IMAGE_TOKEN_INDEX, return_tensors=None):
342
+ prompt_chunks = [tokenizer(chunk).input_ids for chunk in prompt.split("<image>")]
343
+
344
+ def insert_separator(X, sep):
345
+ return [ele for sublist in zip(X, [sep] * len(X)) for ele in sublist][:-1]
346
+
347
+ input_ids = []
348
+ offset = 0
349
+ if len(prompt_chunks) > 0 and len(prompt_chunks[0]) > 0 and prompt_chunks[0][0] == tokenizer.bos_token_id:
350
+ offset = 1
351
+ input_ids.append(prompt_chunks[0][0])
352
+
353
+ for x in insert_separator(prompt_chunks, [image_token_index] * (offset + 1)):
354
+ input_ids.extend(x[offset:])
355
+
356
+ if return_tensors is not None:
357
+ if return_tensors == "pt":
358
+ return torch.tensor(input_ids, dtype=torch.long)
359
+ raise ValueError(f"Unsupported tensor type: {return_tensors}")
360
+ return input_ids
361
+
362
+
363
+ def get_model_name_from_path(model_path):
364
+ model_path = model_path.strip("/")
365
+ model_paths = model_path.split("/")
366
+ if model_paths[-1].startswith("checkpoint-"):
367
+ return model_paths[-2] + "_" + model_paths[-1]
368
+ else:
369
+ return model_paths[-1]
370
+
371
+
372
+ class KeywordsStoppingCriteria(StoppingCriteria):
373
+ def __init__(self, keywords, tokenizer, input_ids):
374
+ self.keywords = keywords
375
+ self.keyword_ids = []
376
+ for keyword in keywords:
377
+ cur_keyword_ids = tokenizer(keyword).input_ids
378
+ if len(cur_keyword_ids) > 1 and cur_keyword_ids[0] == tokenizer.bos_token_id:
379
+ cur_keyword_ids = cur_keyword_ids[1:]
380
+ self.keyword_ids.append(torch.tensor(cur_keyword_ids))
381
+ self.tokenizer = tokenizer
382
+ self.start_len = input_ids.shape[1]
383
+
384
+ def __call__(self, output_ids: torch.LongTensor, scores: torch.FloatTensor, **kwargs) -> bool:
385
+ assert output_ids.shape[0] == 1, "Only support batch size 1 (yet)" # TODO
386
+ offset = min(output_ids.shape[1] - self.start_len, 3)
387
+ self.keyword_ids = [keyword_id.to(output_ids.device) for keyword_id in self.keyword_ids]
388
+ for keyword_id in self.keyword_ids:
389
+ if output_ids[0, -keyword_id.shape[0] :] == keyword_id:
390
+ return True
391
+ outputs = self.tokenizer.batch_decode(output_ids[:, -offset:], skip_special_tokens=True)[0]
392
+ for keyword in self.keywords:
393
+ if keyword in outputs:
394
+ return True
395
+ return False
之前的代码版本/第一版-全部代码/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/llava/model/__init__.py ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+
3
+ AVAILABLE_MODELS = {
4
+ "llava_llama": "LlavaLlamaForCausalLM, LlavaConfig",
5
+ "llava_qwen": "LlavaQwenForCausalLM, LlavaQwenConfig",
6
+ "llava_mistral": "LlavaMistralForCausalLM, LlavaMistralConfig",
7
+ "llava_mixtral": "LlavaMixtralForCausalLM, LlavaMixtralConfig",
8
+ # "llava_qwen_moe": "LlavaQwenMoeForCausalLM, LlavaQwenMoeConfig",
9
+ # Add other models as needed
10
+ }
11
+
12
+ for model_name, model_classes in AVAILABLE_MODELS.items():
13
+ try:
14
+ exec(f"from .language_model.{model_name} import {model_classes}")
15
+ except Exception as e:
16
+ print(f"Failed to import {model_name} from llava.language_model.{model_name}. Error: {e}")
之前的代码版本/第一版-全部代码/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/llava/model/apply_delta.py ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Usage:
3
+ python3 -m fastchat.model.apply_delta --base ~/model_weights/llama-7b --target ~/model_weights/vicuna-7b --delta lmsys/vicuna-7b-delta
4
+ """
5
+
6
+ import argparse
7
+
8
+ import torch
9
+ from tqdm import tqdm
10
+ from transformers import AutoTokenizer, AutoModelForCausalLM
11
+ from llava import LlavaLlamaForCausalLM
12
+
13
+
14
+ def apply_delta(base_model_path, target_model_path, delta_path):
15
+ print("Loading base model")
16
+ base = AutoModelForCausalLM.from_pretrained(base_model_path, torch_dtype=torch.float16, low_cpu_mem_usage=True)
17
+
18
+ print("Loading delta")
19
+ delta = LlavaLlamaForCausalLM.from_pretrained(delta_path, torch_dtype=torch.float16, low_cpu_mem_usage=True)
20
+ delta_tokenizer = AutoTokenizer.from_pretrained(delta_path)
21
+
22
+ print("Applying delta")
23
+ for name, param in tqdm(delta.state_dict().items(), desc="Applying delta"):
24
+ if name not in base.state_dict():
25
+ assert name in ["model.mm_projector.weight", "model.mm_projector.bias"], f"{name} not in base model"
26
+ continue
27
+ if param.data.shape == base.state_dict()[name].shape:
28
+ param.data += base.state_dict()[name]
29
+ else:
30
+ assert name in ["model.embed_tokens.weight", "lm_head.weight"], f"{name} dimension mismatch: {param.data.shape} vs {base.state_dict()[name].shape}"
31
+ bparam = base.state_dict()[name]
32
+ param.data[: bparam.shape[0], : bparam.shape[1]] += bparam
33
+
34
+ print("Saving target model")
35
+ delta.save_pretrained(target_model_path)
36
+ delta_tokenizer.save_pretrained(target_model_path)
37
+
38
+
39
+ if __name__ == "__main__":
40
+ parser = argparse.ArgumentParser()
41
+ parser.add_argument("--base-model-path", type=str, required=True)
42
+ parser.add_argument("--target-model-path", type=str, required=True)
43
+ parser.add_argument("--delta-path", type=str, required=True)
44
+
45
+ args = parser.parse_args()
46
+
47
+ apply_delta(args.base_model_path, args.target_model_path, args.delta_path)
之前的代码版本/第一版-全部代码/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/llava/model/builder.py ADDED
@@ -0,0 +1,305 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023 Haotian Liu
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+
16
+ import os
17
+ import warnings
18
+ import shutil
19
+
20
+ from transformers import AutoTokenizer, AutoModelForCausalLM, AutoConfig, BitsAndBytesConfig
21
+ import torch
22
+ from llava.model import *
23
+ from llava.constants import DEFAULT_IMAGE_PATCH_TOKEN, DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN
24
+ from llava.utils import rank0_print
25
+
26
+
27
+ def load_pretrained_model(model_path, model_base, model_name, load_8bit=False, load_4bit=False, device_map="auto", torch_dtype="float16",attn_implementation="flash_attention_2", customized_config=None, overwrite_config=None, **kwargs):
28
+ kwargs["device_map"] = device_map
29
+
30
+ if load_8bit:
31
+ kwargs["load_in_8bit"] = True
32
+ elif load_4bit:
33
+ kwargs["load_in_4bit"] = True
34
+ kwargs["quantization_config"] = BitsAndBytesConfig(load_in_4bit=True, bnb_4bit_compute_dtype=torch.float16, bnb_4bit_use_double_quant=True, bnb_4bit_quant_type="nf4")
35
+ elif torch_dtype == "float16":
36
+ kwargs["torch_dtype"] = torch.float16
37
+ elif torch_dtype == "bfloat16":
38
+ kwargs["torch_dtype"] = torch.bfloat16
39
+ else:
40
+ import pdb;pdb.set_trace()
41
+
42
+ if customized_config is not None:
43
+ kwargs["config"] = customized_config
44
+
45
+ if "multimodal" in kwargs:
46
+ if kwargs["multimodal"] is True:
47
+ is_multimodal = True
48
+ kwargs.pop("multimodal")
49
+ else:
50
+ is_multimodal = False
51
+
52
+ if "llava" in model_name.lower() or is_multimodal:
53
+ # Load LLaVA model
54
+ if "lora" in model_name.lower() and model_base is None:
55
+ warnings.warn(
56
+ "There is `lora` in model name but no `model_base` is provided. If you are loading a LoRA model, please provide the `model_base` argument. Detailed instruction: https://github.com/haotian-liu/LLaVA#launch-a-model-worker-lora-weights-unmerged."
57
+ )
58
+ if "lora" in model_name.lower() and model_base is not None:
59
+ lora_cfg_pretrained = AutoConfig.from_pretrained(model_path)
60
+ tokenizer = AutoTokenizer.from_pretrained(model_base, use_fast=False)
61
+ rank0_print("Loading LLaVA from base model...")
62
+ if "mixtral" in model_name.lower():
63
+ from llava.model.language_model.llava_mixtral import LlavaMixtralConfig
64
+
65
+ lora_cfg_pretrained = LlavaMixtralConfig.from_pretrained(model_path)
66
+ tokenizer = AutoTokenizer.from_pretrained(model_base, use_fast=False)
67
+ model = LlavaMixtralForCausalLM.from_pretrained(model_base, low_cpu_mem_usage=True, config=lora_cfg_pretrained, attn_implementation=attn_implementation, **kwargs)
68
+ elif "mistral" in model_name.lower():
69
+ from llava.model.language_model.llava_mistral import LlavaMistralConfig
70
+
71
+ lora_cfg_pretrained = LlavaMistralConfig.from_pretrained(model_path)
72
+ tokenizer = AutoTokenizer.from_pretrained(model_base, use_fast=False)
73
+ model = LlavaMistralForCausalLM.from_pretrained(model_base, low_cpu_mem_usage=True, config=lora_cfg_pretrained, attn_implementation=attn_implementation, **kwargs)
74
+ elif "gemma" in model_name.lower():
75
+ from llava.model.language_model.llava_gemma import LlavaGemmaConfig
76
+
77
+ lora_cfg_pretrained = LlavaGemmaConfig.from_pretrained(model_path)
78
+ tokenizer = AutoTokenizer.from_pretrained(model_base, use_fast=False)
79
+ model = LlavaGemmaForCausalLM.from_pretrained(model_base, low_cpu_mem_usage=True, config=lora_cfg_pretrained, attn_implementation=attn_implementation, **kwargs)
80
+ else:
81
+ from llava.model.language_model.llava_llama import LlavaConfig
82
+
83
+ lora_cfg_pretrained = LlavaConfig.from_pretrained(model_path)
84
+ tokenizer = AutoTokenizer.from_pretrained(model_base, use_fast=False)
85
+ model = LlavaLlamaForCausalLM.from_pretrained(model_base, low_cpu_mem_usage=True, config=lora_cfg_pretrained, attn_implementation=attn_implementation, **kwargs)
86
+
87
+ token_num, tokem_dim = model.lm_head.out_features, model.lm_head.in_features
88
+ if model.lm_head.weight.shape[0] != token_num:
89
+ model.lm_head.weight = torch.nn.Parameter(torch.empty(token_num, tokem_dim, device=model.device, dtype=model.dtype))
90
+ model.model.embed_tokens.weight = torch.nn.Parameter(torch.empty(token_num, tokem_dim, device=model.device, dtype=model.dtype))
91
+
92
+ rank0_print("Loading additional LLaVA weights...")
93
+ if os.path.exists(os.path.join(model_path, "non_lora_trainables.bin")):
94
+ non_lora_trainables = torch.load(os.path.join(model_path, "non_lora_trainables.bin"), map_location="cpu")
95
+ else:
96
+ # this is probably from HF Hub
97
+ from huggingface_hub import hf_hub_download
98
+
99
+ def load_from_hf(repo_id, filename, subfolder=None):
100
+ cache_file = hf_hub_download(repo_id=repo_id, filename=filename, subfolder=subfolder)
101
+ return torch.load(cache_file, map_location="cpu")
102
+
103
+ non_lora_trainables = load_from_hf(model_path, "non_lora_trainables.bin")
104
+ non_lora_trainables = {(k[11:] if k.startswith("base_model.") else k): v for k, v in non_lora_trainables.items()}
105
+ if any(k.startswith("model.model.") for k in non_lora_trainables):
106
+ non_lora_trainables = {(k[6:] if k.startswith("model.") else k): v for k, v in non_lora_trainables.items()}
107
+ model.load_state_dict(non_lora_trainables, strict=False)
108
+
109
+ from peft import PeftModel
110
+
111
+ rank0_print("Loading LoRA weights...")
112
+ model = PeftModel.from_pretrained(model, model_path)
113
+ rank0_print("Merging LoRA weights...")
114
+ model = model.merge_and_unload()
115
+ rank0_print("Model is loaded...")
116
+ elif model_base is not None: # this may be mm projector only, loading projector with preset language mdoel
117
+ rank0_print(f"Loading LLaVA from base model {model_base}...")
118
+ if "mixtral" in model_name.lower():
119
+ tokenizer = AutoTokenizer.from_pretrained(model_base, use_fast=False)
120
+ cfg_pretrained = AutoConfig.from_pretrained(model_path)
121
+ model = LlavaMixtralForCausalLM.from_pretrained(model_base, low_cpu_mem_usage=True, config=cfg_pretrained, attn_implementation=attn_implementation, **kwargs)
122
+ elif "mistral" in model_name.lower() or "zephyr" in model_name.lower():
123
+ tokenizer = AutoTokenizer.from_pretrained(model_base, use_fast=False)
124
+ cfg_pretrained = AutoConfig.from_pretrained(model_path)
125
+ model = LlavaMistralForCausalLM.from_pretrained(model_base, low_cpu_mem_usage=True, config=cfg_pretrained, attn_implementation=attn_implementation, **kwargs)
126
+ elif "gemma" in model_name.lower():
127
+ tokenizer = AutoTokenizer.from_pretrained(model_base, use_fast=False)
128
+ cfg_pretrained = AutoConfig.from_pretrained(model_path)
129
+ model = LlavaGemmaForCausalLM.from_pretrained(model_base, low_cpu_mem_usage=True, config=cfg_pretrained, attn_implementation=attn_implementation, **kwargs)
130
+ elif (
131
+ "wizardlm-2" in model_name.lower()
132
+ and "vicuna" in model_name.lower()
133
+ or "llama" in model_name.lower()
134
+ or "yi" in model_name.lower()
135
+ or "nous-hermes" in model_name.lower()
136
+ or "llava-v1.6-34b" in model_name.lower()
137
+ or "llava-v1.5" in model_name.lower()
138
+ ):
139
+ from llava.model.language_model.llava_llama import LlavaConfig
140
+
141
+ tokenizer = AutoTokenizer.from_pretrained(model_path, use_fast=False)
142
+ if customized_config is None:
143
+ llava_cfg = LlavaConfig.from_pretrained(model_path)
144
+ if "v1.5" in model_name.lower():
145
+ llava_cfg.delay_load = True # a workaround for correctly loading v1.5 models
146
+ else:
147
+ llava_cfg = customized_config
148
+
149
+ tokenizer = AutoTokenizer.from_pretrained(model_base, use_fast=False)
150
+ llava_cfg = LlavaConfig.from_pretrained(model_path)
151
+ model = LlavaLlamaForCausalLM.from_pretrained(model_base, low_cpu_mem_usage=True, config=llava_cfg, **kwargs)
152
+ else:
153
+ raise ValueError(f"Model {model_name} not supported")
154
+
155
+ mm_projector_weights = torch.load(os.path.join(model_path, "mm_projector.bin"), map_location="cpu")
156
+ mm_projector_weights = {k: v.to(torch.float16) for k, v in mm_projector_weights.items()}
157
+ model.load_state_dict(mm_projector_weights, strict=False)
158
+ else:
159
+ rank0_print(f"Loaded LLaVA model: {model_path}")
160
+ if "mixtral" in model_name.lower():
161
+ from llava.model.language_model.llava_mixtral import LlavaMixtralConfig
162
+
163
+ tokenizer = AutoTokenizer.from_pretrained(model_path, use_fast=False)
164
+ if customized_config is None:
165
+ llava_cfg = LlavaMixtralConfig.from_pretrained(model_path)
166
+ else:
167
+ llava_cfg = customized_config
168
+
169
+ if overwrite_config is not None:
170
+ rank0_print(f"Overwriting config with {overwrite_config}")
171
+ for k, v in overwrite_config.items():
172
+ setattr(llava_cfg, k, v)
173
+
174
+ tokenizer = AutoTokenizer.from_pretrained(model_path)
175
+ model = LlavaMixtralForCausalLM.from_pretrained(model_path, low_cpu_mem_usage=True, attn_implementation=attn_implementation, config=llava_cfg, **kwargs)
176
+
177
+ elif "mistral" in model_name.lower() or "zephyr" in model_name.lower():
178
+ tokenizer = AutoTokenizer.from_pretrained(model_path)
179
+ model = LlavaMistralForCausalLM.from_pretrained(model_path, low_cpu_mem_usage=True, attn_implementation=attn_implementation, **kwargs)
180
+ elif (
181
+ "wizardlm-2" in model_name.lower()
182
+ and "vicuna" in model_name.lower()
183
+ or "llama" in model_name.lower()
184
+ or "yi" in model_name.lower()
185
+ or "nous-hermes" in model_name.lower()
186
+ or "llava-v1.6-34b" in model_name.lower()
187
+ or "llava-v1.5" in model_name.lower()
188
+ ):
189
+ from llava.model.language_model.llava_llama import LlavaConfig
190
+
191
+ tokenizer = AutoTokenizer.from_pretrained(model_path, use_fast=False)
192
+ if customized_config is None:
193
+ llava_cfg = LlavaConfig.from_pretrained(model_path)
194
+ if "v1.5" in model_name.lower():
195
+ llava_cfg.delay_load = True # a workaround for correctly loading v1.5 models
196
+ else:
197
+ llava_cfg = customized_config
198
+
199
+ if overwrite_config is not None:
200
+ rank0_print(f"Overwriting config with {overwrite_config}")
201
+ for k, v in overwrite_config.items():
202
+ setattr(llava_cfg, k, v)
203
+
204
+ model = LlavaLlamaForCausalLM.from_pretrained(model_path, low_cpu_mem_usage=True, attn_implementation=attn_implementation, config=llava_cfg, **kwargs)
205
+
206
+ elif "qwen" in model_name.lower() or "quyen" in model_name.lower():
207
+ tokenizer = AutoTokenizer.from_pretrained(model_path)
208
+ if "moe" in model_name.lower() or "A14B" in model_name.lower():
209
+ from llava.model.language_model.llava_qwen_moe import LlavaQwenMoeConfig
210
+ if overwrite_config is not None:
211
+ llava_cfg = LlavaQwenMoeConfig.from_pretrained(model_path)
212
+ rank0_print(f"Overwriting config with {overwrite_config}")
213
+ for k, v in overwrite_config.items():
214
+ setattr(llava_cfg, k, v)
215
+ model = LlavaQwenMoeForCausalLM.from_pretrained(model_path, low_cpu_mem_usage=True, attn_implementation=attn_implementation, config=llava_cfg, **kwargs)
216
+ else:
217
+ model = LlavaQwenMoeForCausalLM.from_pretrained(model_path, low_cpu_mem_usage=True, attn_implementation=attn_implementation, **kwargs)
218
+
219
+ else:
220
+ from llava.model.language_model.llava_qwen import LlavaQwenConfig
221
+ if overwrite_config is not None:
222
+ llava_cfg = LlavaQwenConfig.from_pretrained(model_path)
223
+ rank0_print(f"Overwriting config with {overwrite_config}")
224
+ for k, v in overwrite_config.items():
225
+ setattr(llava_cfg, k, v)
226
+ model = LlavaQwenForCausalLM.from_pretrained(model_path, low_cpu_mem_usage=True, attn_implementation=attn_implementation, config=llava_cfg, **kwargs)
227
+ else:
228
+ model = LlavaQwenForCausalLM.from_pretrained(model_path, low_cpu_mem_usage=True, attn_implementation=attn_implementation, **kwargs)
229
+
230
+ elif "gemma" in model_name.lower():
231
+ tokenizer = AutoTokenizer.from_pretrained(model_path, use_fast=False)
232
+ cfg_pretrained = AutoConfig.from_pretrained(model_path)
233
+ model = LlavaGemmaForCausalLM.from_pretrained(model_path, low_cpu_mem_usage=True, config=cfg_pretrained, attn_implementation=attn_implementation, **kwargs)
234
+ else:
235
+ try:
236
+ from llava.model.language_model.llava_llama import LlavaConfig
237
+
238
+ tokenizer = AutoTokenizer.from_pretrained(model_path, use_fast=False)
239
+ if customized_config is None:
240
+ llava_cfg = LlavaConfig.from_pretrained(model_path)
241
+ if "v1.5" in model_path.lower():
242
+ llava_cfg.delay_load = True # a workaround for correctly loading v1.5 models
243
+ else:
244
+ llava_cfg = customized_config
245
+
246
+ if overwrite_config is not None:
247
+ rank0_print(f"Overwriting config with {overwrite_config}")
248
+ for k, v in overwrite_config.items():
249
+ setattr(llava_cfg, k, v)
250
+ model = LlavaLlamaForCausalLM.from_pretrained(model_path, low_cpu_mem_usage=True, attn_implementation=attn_implementation, config=llava_cfg, **kwargs)
251
+ except:
252
+ raise ValueError(f"Model {model_name} not supported")
253
+
254
+ else:
255
+ # Load language model
256
+ if model_base is not None:
257
+ # PEFT model
258
+ from peft import PeftModel
259
+
260
+ tokenizer = AutoTokenizer.from_pretrained(model_base, use_fast=False)
261
+ model = AutoModelForCausalLM.from_pretrained(model_base, torch_dtype=torch.float16, low_cpu_mem_usage=True, device_map="auto")
262
+ print(f"Loading LoRA weights from {model_path}")
263
+ model = PeftModel.from_pretrained(model, model_path)
264
+ print(f"Merging weights")
265
+ model = model.merge_and_unload()
266
+ print("Convert to FP16...")
267
+ model.to(torch.float16)
268
+ else:
269
+ use_fast = False
270
+ if "mpt" in model_name.lower().replace("prompt", ""):
271
+ tokenizer = AutoTokenizer.from_pretrained(model_path, use_fast=True)
272
+ model = AutoModelForCausalLM.from_pretrained(model_path, low_cpu_mem_usage=True, trust_remote_code=True, **kwargs)
273
+ else:
274
+ tokenizer = AutoTokenizer.from_pretrained(model_path, use_fast=False)
275
+ model = AutoModelForCausalLM.from_pretrained(model_path, low_cpu_mem_usage=True, **kwargs)
276
+
277
+ rank0_print(f"Model Class: {model.__class__.__name__}")
278
+ image_processor = None
279
+
280
+ if "llava" in model_name.lower() or is_multimodal:
281
+ mm_use_im_start_end = getattr(model.config, "mm_use_im_start_end", False)
282
+ mm_use_im_patch_token = getattr(model.config, "mm_use_im_patch_token", True)
283
+ if mm_use_im_patch_token:
284
+ tokenizer.add_tokens([DEFAULT_IMAGE_PATCH_TOKEN], special_tokens=True)
285
+ if mm_use_im_start_end:
286
+ tokenizer.add_tokens([DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN], special_tokens=True)
287
+ model.resize_token_embeddings(len(tokenizer))
288
+
289
+ vision_tower = model.get_vision_tower()
290
+ if not vision_tower.is_loaded:
291
+ vision_tower.load_model(device_map=device_map)
292
+ if device_map != "auto":
293
+ vision_tower.to(device="cuda", dtype=torch.float16)
294
+ image_processor = vision_tower.image_processor
295
+
296
+ if hasattr(model.config, "max_sequence_length"):
297
+ context_len = model.config.max_sequence_length
298
+ elif hasattr(model.config, "max_position_embeddings"):
299
+ context_len = model.config.max_position_embeddings
300
+ elif hasattr(model.config, "tokenizer_model_max_length"):
301
+ context_len = model.config.tokenizer_model_max_length
302
+ else:
303
+ context_len = 2048
304
+
305
+ return tokenizer, model, image_processor, context_len
之前的代码版本/第一版-全部代码/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/llava/model/consolidate.py ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Usage:
3
+ python3 -m llava.model.consolidate --src ~/model_weights/llava-7b --dst ~/model_weights/llava-7b_consolidate
4
+ """
5
+
6
+ import argparse
7
+
8
+ import torch
9
+ from transformers import AutoTokenizer, AutoModelForCausalLM
10
+ from llava.model import *
11
+ from llava.model.utils import auto_upgrade
12
+
13
+
14
+ def consolidate_ckpt(src_path, dst_path):
15
+ print("Loading model")
16
+ auto_upgrade(src_path)
17
+ src_model = AutoModelForCausalLM.from_pretrained(src_path, torch_dtype=torch.float16, low_cpu_mem_usage=True)
18
+ src_tokenizer = AutoTokenizer.from_pretrained(src_path, use_fast=False)
19
+ src_model.save_pretrained(dst_path)
20
+ src_tokenizer.save_pretrained(dst_path)
21
+
22
+
23
+ if __name__ == "__main__":
24
+ parser = argparse.ArgumentParser()
25
+ parser.add_argument("--src", type=str, required=True)
26
+ parser.add_argument("--dst", type=str, required=True)
27
+
28
+ args = parser.parse_args()
29
+
30
+ consolidate_ckpt(args.src, args.dst)
之前的代码版本/第一版-全部代码/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/llava/model/llava_arch.py ADDED
@@ -0,0 +1,597 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023 Haotian Liu
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+
16
+ from abc import ABC, abstractmethod
17
+
18
+ import math
19
+ import re
20
+ import time
21
+ import torch
22
+ import torch.nn as nn
23
+ from .multimodal_encoder.builder import build_vision_tower
24
+ from .multimodal_resampler.builder import build_vision_resampler
25
+ from .multimodal_projector.builder import build_vision_projector
26
+
27
+ from llava.constants import IGNORE_INDEX, IMAGE_TOKEN_INDEX, DEFAULT_IMAGE_PATCH_TOKEN, DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN
28
+
29
+ from llava.mm_utils import get_anyres_image_grid_shape
30
+ from llava.utils import rank0_print, rank_print
31
+ import random
32
+
33
+
34
+ class LlavaMetaModel:
35
+
36
+ def __init__(self, config):
37
+ super(LlavaMetaModel, self).__init__(config)
38
+
39
+ if hasattr(config, "mm_vision_tower"):
40
+ delay_load = getattr(config, "delay_load", False)
41
+ self.vision_tower = build_vision_tower(config, delay_load=delay_load)
42
+ self.vision_resampler = build_vision_resampler(config, vision_tower=self.vision_tower)
43
+ self.mm_projector = build_vision_projector(config, vision_cfg=self.vision_tower.config)
44
+
45
+ if "unpad" in getattr(config, "mm_patch_merge_type", ""):
46
+ self.image_newline = nn.Parameter(torch.empty(config.hidden_size, dtype=self.dtype))
47
+
48
+ def get_vision_tower(self):
49
+ vision_tower = getattr(self, "vision_tower", None)
50
+ if type(vision_tower) is list:
51
+ vision_tower = vision_tower[0]
52
+ return vision_tower
53
+
54
+ def initialize_vision_modules(self, model_args, fsdp=None):
55
+ vision_tower = model_args.vision_tower
56
+ mm_vision_select_layer = model_args.mm_vision_select_layer
57
+ mm_vision_select_feature = model_args.mm_vision_select_feature
58
+ pretrain_mm_mlp_adapter = model_args.pretrain_mm_mlp_adapter
59
+ mm_patch_merge_type = model_args.mm_patch_merge_type
60
+
61
+ self.config.mm_vision_tower = vision_tower
62
+ self.config.vision_tower_pretrained = getattr(model_args, "vision_tower_pretrained", "")
63
+
64
+ if self.get_vision_tower() is None:
65
+ vision_tower = build_vision_tower(model_args)
66
+ vision_resampler = build_vision_resampler(model_args, vision_tower=vision_tower)
67
+ for k, v in vision_resampler.config.items():
68
+ setattr(self.config, k, v)
69
+
70
+ if fsdp is not None and len(fsdp) > 0:
71
+ self.vision_tower = [vision_tower]
72
+ self.vision_resampler = [vision_resampler]
73
+ else:
74
+ self.vision_tower = vision_tower
75
+ self.vision_resampler = vision_resampler
76
+ else:
77
+ if fsdp is not None and len(fsdp) > 0:
78
+ vision_resampler = self.vision_resampler[0]
79
+ vision_tower = self.vision_tower[0]
80
+ else:
81
+ vision_resampler = self.vision_resampler
82
+ vision_tower = self.vision_tower
83
+ vision_tower.load_model()
84
+
85
+ # In case it is frozen by LoRA
86
+ for p in self.vision_resampler.parameters():
87
+ p.requires_grad = True
88
+
89
+ self.config.use_mm_proj = True
90
+ self.config.mm_projector_type = getattr(model_args, "mm_projector_type", "linear")
91
+ self.config.mm_hidden_size = getattr(vision_resampler, "hidden_size", vision_tower.hidden_size)
92
+ self.config.mm_vision_select_layer = mm_vision_select_layer
93
+ self.config.mm_vision_select_feature = mm_vision_select_feature
94
+ self.config.mm_patch_merge_type = mm_patch_merge_type
95
+
96
+
97
+ if not hasattr(self.config, 'add_faster_video'):
98
+ if model_args.add_faster_video:
99
+ embed_std = 1 / torch.sqrt(torch.tensor(self.config.hidden_size, dtype=self.dtype))
100
+ self.faster_token = nn.Parameter(
101
+ torch.randn(self.config.hidden_size, dtype=self.dtype) * embed_std
102
+ )
103
+
104
+ if getattr(self, "mm_projector", None) is None:
105
+ self.mm_projector = build_vision_projector(self.config, vision_cfg=vision_tower.config)
106
+
107
+ if "unpad" in mm_patch_merge_type:
108
+ embed_std = 1 / torch.sqrt(torch.tensor(self.config.hidden_size, dtype=self.dtype))
109
+ self.image_newline = nn.Parameter(torch.randn(self.config.hidden_size, dtype=self.dtype) * embed_std)
110
+ else:
111
+ # In case it is frozen by LoRA
112
+ for p in self.mm_projector.parameters():
113
+ p.requires_grad = True
114
+
115
+ if pretrain_mm_mlp_adapter is not None:
116
+ mm_projector_weights = torch.load(pretrain_mm_mlp_adapter, map_location="cpu")
117
+
118
+ def get_w(weights, keyword):
119
+ return {k.split(keyword + ".")[1]: v for k, v in weights.items() if keyword in k}
120
+
121
+ incompatible_keys = self.mm_projector.load_state_dict(get_w(mm_projector_weights, "mm_projector"))
122
+ rank0_print(f"Loaded mm projector weights from {pretrain_mm_mlp_adapter}. Incompatible keys: {incompatible_keys}")
123
+ incompatible_keys = self.vision_resampler.load_state_dict(get_w(mm_projector_weights, "vision_resampler"), strict=False)
124
+ rank0_print(f"Loaded vision resampler weights from {pretrain_mm_mlp_adapter}. Incompatible keys: {incompatible_keys}")
125
+
126
+
127
+ def unpad_image(tensor, original_size):
128
+ """
129
+ Unpads a PyTorch tensor of a padded and resized image.
130
+
131
+ Args:
132
+ tensor (torch.Tensor): The image tensor, assumed to be in CxHxW format.
133
+ original_size (tuple): The original size of the image (height, width).
134
+
135
+ Returns:
136
+ torch.Tensor: The unpadded image tensor.
137
+ """
138
+ original_width, original_height = original_size
139
+ current_height, current_width = tensor.shape[1:]
140
+
141
+ # Compute aspect ratios
142
+ original_aspect_ratio = original_width / original_height
143
+ current_aspect_ratio = current_width / current_height
144
+
145
+ # Determine padding size and direction
146
+ if original_aspect_ratio > current_aspect_ratio:
147
+ # Padding was added to the height
148
+ scale_factor = current_width / original_width
149
+ new_height = int(original_height * scale_factor)
150
+ padding = (current_height - new_height) // 2
151
+ unpadded_tensor = tensor[:, padding : current_height - padding, :]
152
+ else:
153
+ # Padding was added to the width
154
+ scale_factor = current_height / original_height
155
+ new_width = int(original_width * scale_factor)
156
+ padding = (current_width - new_width) // 2
157
+ unpadded_tensor = tensor[:, :, padding : current_width - padding]
158
+
159
+ return unpadded_tensor
160
+
161
+
162
+ class LlavaMetaForCausalLM(ABC):
163
+
164
+ @abstractmethod
165
+ def get_model(self):
166
+ pass
167
+
168
+ def get_vision_tower(self):
169
+ return self.get_model().get_vision_tower()
170
+
171
+ def get_2dPool(self, image_feature, stride=2):
172
+ height = width = self.get_vision_tower().num_patches_per_side
173
+ num_frames, num_tokens, num_dim = image_feature.shape
174
+ image_feature = image_feature.view(num_frames, height, width, -1)
175
+ image_feature = image_feature.permute(0, 3, 1, 2).contiguous()
176
+ # image_feature = nn.functional.max_pool2d(image_feature, self.config.mm_spatial_pool_stride)
177
+ if self.config.mm_spatial_pool_mode == "average":
178
+ image_feature = nn.functional.avg_pool2d(image_feature, stride)
179
+ elif self.config.mm_spatial_pool_mode == "max":
180
+ image_feature = nn.functional.max_pool2d(image_feature, stride)
181
+ elif self.config.mm_spatial_pool_mode == "bilinear":
182
+ height, width = image_feature.shape[2:]
183
+ scaled_shape = [math.ceil(height / stride), math.ceil(width / stride)]
184
+ image_feature = nn.functional.interpolate(image_feature, size=scaled_shape, mode='bilinear')
185
+
186
+ else:
187
+ raise ValueError(f"Unexpected mm_spatial_pool_mode: {self.config.mm_spatial_pool_mode}")
188
+ image_feature = image_feature.permute(0, 2, 3, 1)
189
+ image_feature = image_feature.view(num_frames, -1, num_dim)
190
+ return image_feature
191
+
192
+ def encode_images(self, images):
193
+ image_features = self.get_model().get_vision_tower()(images)
194
+ # image_features = self.get_model().vision_resampler(image_features, images=images)
195
+ image_features = self.get_model().mm_projector(image_features)
196
+ return image_features
197
+
198
+ def encode_multimodals(self, videos_or_images, video_idx_in_batch, split_sizes=None):
199
+ videos_or_images_features = self.get_model().get_vision_tower()(videos_or_images)
200
+ per_videos_or_images_features = torch.split(videos_or_images_features, split_sizes, dim=0) # tuple, (dim_1, 576, 4096)
201
+ all_videos_or_images_features = []
202
+ all_faster_video_features = []
203
+ cur_mm_spatial_pool_stride = self.config.mm_spatial_pool_stride
204
+
205
+ for idx, feat in enumerate(per_videos_or_images_features):
206
+
207
+ feat = self.get_model().mm_projector(feat)
208
+ faster_video_feature = 0
209
+ slower_img_feat = 0
210
+ if idx in video_idx_in_batch and cur_mm_spatial_pool_stride > 1:
211
+ slower_img_feat = self.get_2dPool(feat,cur_mm_spatial_pool_stride)
212
+ if self.config.add_faster_video:
213
+ cur_mm_spatial_pool_stride = cur_mm_spatial_pool_stride * 2
214
+ faster_video_feature = self.get_2dPool(feat,cur_mm_spatial_pool_stride)
215
+ if slower_img_feat is not 0:
216
+ all_videos_or_images_features.append(slower_img_feat)
217
+ else:
218
+ all_videos_or_images_features.append(feat)
219
+ all_faster_video_features.append(faster_video_feature)
220
+ return all_videos_or_images_features,all_faster_video_features
221
+
222
+ def add_token_per_grid(self, image_feature):
223
+ resize_h = int(math.sqrt(image_feature.shape[1]))
224
+ num_frames = image_feature.shape[0]
225
+ feature_dim = image_feature.shape[-1]
226
+
227
+ image_feature = image_feature.view(num_frames, 1, resize_h, resize_h, -1)
228
+ image_feature = image_feature.permute(4, 0, 2, 1, 3).contiguous()
229
+ image_feature = image_feature.flatten(1, 2).flatten(2, 3)
230
+ image_feature = torch.cat((image_feature, self.model.image_newline[:, None, None].expand(*image_feature.shape[:-1], 1).to(image_feature.device)), dim=-1)
231
+ if getattr(self.config, "add_faster_video", False):
232
+ # import pdb; pdb.set_trace()
233
+ # (3584, 832, 14) -> (3584, 64, 13, 14)
234
+ image_feature = image_feature.view(feature_dim, num_frames,resize_h, -1)
235
+ # (3584, 64, 13, 14) -> (64, 13, 14, 3584)
236
+ image_feature = image_feature.permute(1, 2, 3, 0).contiguous()
237
+ # (64, 13, 14, 3584) -> (64, 13*14, 3584)
238
+ image_feature = image_feature.flatten(1, 2)
239
+ # import pdb; pdb.set_trace()
240
+ return image_feature
241
+ # import pdb; pdb.set_trace()
242
+ image_feature = image_feature.flatten(1, 2).transpose(0, 1)
243
+ return image_feature
244
+
245
+ def add_token_per_frame(self, image_feature):
246
+ image_feature = image_feature.permute(2, 0, 1).contiguous()
247
+ image_feature = torch.cat((image_feature, self.model.image_newline[:, None, None].expand(*image_feature.shape[:-1], 1).to(image_feature.device)), dim=-1)
248
+ image_feature = image_feature.permute(1, 2, 0).contiguous()
249
+ return image_feature
250
+
251
+ def prepare_inputs_labels_for_multimodal(self, input_ids, position_ids, attention_mask, past_key_values, labels, images, modalities=["image"], image_sizes=None):
252
+ vision_tower = self.get_vision_tower()
253
+ # rank_print(modalities)
254
+ if vision_tower is None or images is None or input_ids.shape[1] == 1:
255
+ return input_ids, position_ids, attention_mask, past_key_values, None, labels
256
+
257
+ if isinstance(modalities, str):
258
+ modalities = [modalities]
259
+
260
+ # import pdb; pdb.set_trace()
261
+ if type(images) is list or images.ndim == 5:
262
+ if type(images) is list:
263
+ images = [x.unsqueeze(0) if x.ndim == 3 else x for x in images]
264
+
265
+ video_idx_in_batch = []
266
+ for _ in range(len(modalities)):
267
+ if modalities[_] == "video":
268
+ video_idx_in_batch.append(_)
269
+
270
+ images_list = []
271
+ for image in images:
272
+ if image.ndim == 4:
273
+ images_list.append(image)
274
+ else:
275
+ images_list.append(image.unsqueeze(0))
276
+
277
+ concat_images = torch.cat([image for image in images_list], dim=0)
278
+ split_sizes = [image.shape[0] for image in images_list]
279
+ encoded_image_features = self.encode_images(concat_images)
280
+ # image_features,all_faster_video_features = self.encode_multimodals(concat_images, video_idx_in_batch, split_sizes)
281
+
282
+ # This is a list, each element is [num_images, patch * patch, dim]
283
+ # rank_print(f"Concat images : {concat_images.shape}")
284
+ encoded_image_features = torch.split(encoded_image_features, split_sizes)
285
+ image_features = []
286
+ for idx, image_feat in enumerate(encoded_image_features):
287
+ if idx in video_idx_in_batch:
288
+ image_features.append(self.get_2dPool(image_feat))
289
+ else:
290
+ image_features.append(image_feat)
291
+ # image_features = self.encode_multimodals(concat_images, video_idx_in_batch, split_sizes)
292
+ # rank_print(f"Encoded image feats : {[x.shape for x in image_features]}")
293
+ # image_features = torch.split(image_features, split_sizes, dim=0)
294
+ mm_patch_merge_type = getattr(self.config, "mm_patch_merge_type", "flat")
295
+ image_aspect_ratio = getattr(self.config, "image_aspect_ratio", "square")
296
+ mm_newline_position = getattr(self.config, "mm_newline_position", "one_token")
297
+
298
+ if mm_patch_merge_type == "flat":
299
+ image_features = [x.flatten(0, 1) for x in image_features]
300
+
301
+ elif mm_patch_merge_type.startswith("spatial"):
302
+ new_image_features = []
303
+ for image_idx, image_feature in enumerate(image_features):
304
+ # FIXME: now assume the image is square, and split to 2x2 patches
305
+ # num_patches = h * w, where h = w = sqrt(num_patches)
306
+ # currently image_feature is a tensor of shape (4, num_patches, hidden_size)
307
+ # we want to first unflatten it to (2, 2, h, w, hidden_size)
308
+ # rank0_print("At least we are reaching here")
309
+ # import pdb; pdb.set_trace()
310
+ if image_idx in video_idx_in_batch: # video operations
311
+ # rank0_print("Video")
312
+ if mm_newline_position == "grid":
313
+ # Grid-wise
314
+ image_feature = self.add_token_per_grid(image_feature)
315
+ if getattr(self.config, "add_faster_video", False):
316
+ faster_video_feature = self.add_token_per_grid(all_faster_video_features[image_idx])
317
+ # Add a token for each frame
318
+ concat_slow_fater_token = []
319
+ # import pdb; pdb.set_trace()
320
+ for _ in range(image_feature.shape[0]):
321
+ if _ % self.config.faster_token_stride == 0:
322
+ concat_slow_fater_token.append(torch.cat((image_feature[_], self.model.faster_token[None].to(image_feature.device)), dim=0))
323
+ else:
324
+ concat_slow_fater_token.append(torch.cat((faster_video_feature[_], self.model.faster_token[None].to(image_feature.device)), dim=0))
325
+ # import pdb; pdb.set_trace()
326
+ image_feature = torch.cat(concat_slow_fater_token)
327
+
328
+ # print("!!!!!!!!!!!!")
329
+
330
+ new_image_features.append(image_feature)
331
+ elif mm_newline_position == "frame":
332
+ # Frame-wise
333
+ image_feature = self.add_token_per_frame(image_feature)
334
+
335
+ new_image_features.append(image_feature.flatten(0, 1))
336
+
337
+ elif mm_newline_position == "one_token":
338
+ # one-token
339
+ image_feature = image_feature.flatten(0, 1)
340
+ if 'unpad' in mm_patch_merge_type:
341
+ image_feature = torch.cat((
342
+ image_feature,
343
+ self.model.image_newline[None].to(image_feature.device)
344
+ ), dim=0)
345
+ new_image_features.append(image_feature)
346
+ elif mm_newline_position == "no_token":
347
+ new_image_features.append(image_feature.flatten(0, 1))
348
+ else:
349
+ raise ValueError(f"Unexpected mm_newline_position: {mm_newline_position}")
350
+ elif image_feature.shape[0] > 1: # multi patches and multi images operations
351
+ # rank0_print("Single-images")
352
+ base_image_feature = image_feature[0]
353
+ image_feature = image_feature[1:]
354
+ height = width = self.get_vision_tower().num_patches_per_side
355
+ assert height * width == base_image_feature.shape[0]
356
+
357
+ if "anyres_max" in image_aspect_ratio:
358
+ matched_anyres_max_num_patches = re.match(r"anyres_max_(\d+)", image_aspect_ratio)
359
+ if matched_anyres_max_num_patches:
360
+ max_num_patches = int(matched_anyres_max_num_patches.group(1))
361
+
362
+ if image_aspect_ratio == "anyres" or "anyres_max" in image_aspect_ratio:
363
+ if hasattr(self.get_vision_tower(), "image_size"):
364
+ vision_tower_image_size = self.get_vision_tower().image_size
365
+ else:
366
+ raise ValueError("vision_tower_image_size is not found in the vision tower.")
367
+ try:
368
+ num_patch_width, num_patch_height = get_anyres_image_grid_shape(image_sizes[image_idx], self.config.image_grid_pinpoints, vision_tower_image_size)
369
+ except Exception as e:
370
+ rank0_print(f"Error: {e}")
371
+ num_patch_width, num_patch_height = 2, 2
372
+ image_feature = image_feature.view(num_patch_height, num_patch_width, height, width, -1)
373
+ else:
374
+ image_feature = image_feature.view(2, 2, height, width, -1)
375
+
376
+ if "maxpool2x2" in mm_patch_merge_type:
377
+ image_feature = image_feature.permute(4, 0, 2, 1, 3).contiguous()
378
+ image_feature = image_feature.flatten(1, 2).flatten(2, 3)
379
+ image_feature = nn.functional.max_pool2d(image_feature, 2)
380
+ image_feature = image_feature.flatten(1, 2).transpose(0, 1)
381
+ elif "unpad" in mm_patch_merge_type and "anyres_max" in image_aspect_ratio and matched_anyres_max_num_patches:
382
+ unit = image_feature.shape[2]
383
+ image_feature = image_feature.permute(4, 0, 2, 1, 3).contiguous()
384
+ image_feature = image_feature.flatten(1, 2).flatten(2, 3)
385
+ image_feature = unpad_image(image_feature, image_sizes[image_idx])
386
+ c, h, w = image_feature.shape
387
+ times = math.sqrt(h * w / (max_num_patches * unit**2))
388
+ if times > 1.1:
389
+ image_feature = image_feature[None]
390
+ image_feature = nn.functional.interpolate(image_feature, [int(h // times), int(w // times)], mode="bilinear")[0]
391
+ image_feature = torch.cat((image_feature, self.model.image_newline[:, None, None].expand(*image_feature.shape[:-1], 1).to(image_feature.device)), dim=-1)
392
+ image_feature = image_feature.flatten(1, 2).transpose(0, 1)
393
+ elif "unpad" in mm_patch_merge_type:
394
+ image_feature = image_feature.permute(4, 0, 2, 1, 3).contiguous()
395
+ image_feature = image_feature.flatten(1, 2).flatten(2, 3)
396
+ image_feature = unpad_image(image_feature, image_sizes[image_idx])
397
+ image_feature = torch.cat((image_feature, self.model.image_newline[:, None, None].expand(*image_feature.shape[:-1], 1).to(image_feature.device)), dim=-1)
398
+ image_feature = image_feature.flatten(1, 2).transpose(0, 1)
399
+ else:
400
+ image_feature = image_feature.permute(0, 2, 1, 3, 4).contiguous()
401
+ image_feature = image_feature.flatten(0, 3)
402
+ if "nobase" in mm_patch_merge_type:
403
+ pass
404
+ else:
405
+ image_feature = torch.cat((base_image_feature, image_feature), dim=0)
406
+ new_image_features.append(image_feature)
407
+ else: # single image operations
408
+ image_feature = image_feature[0]
409
+ if "unpad" in mm_patch_merge_type:
410
+ image_feature = torch.cat((image_feature, self.model.image_newline[None]), dim=0)
411
+
412
+ new_image_features.append(image_feature)
413
+ image_features = new_image_features
414
+ else:
415
+ raise ValueError(f"Unexpected mm_patch_merge_type: {self.config.mm_patch_merge_type}")
416
+ else:
417
+ image_features = self.encode_images(images)
418
+
419
+ # TODO: image start / end is not implemented here to support pretraining.
420
+ if getattr(self.config, "tune_mm_mlp_adapter", False) and getattr(self.config, "mm_use_im_start_end", False):
421
+ raise NotImplementedError
422
+ # rank_print(f"Total images : {len(image_features)}")
423
+
424
+ # Let's just add dummy tensors if they do not exist,
425
+ # it is a headache to deal with None all the time.
426
+ # But it is not ideal, and if you have a better idea,
427
+ # please open an issue / submit a PR, thanks.
428
+ _labels = labels
429
+ _position_ids = position_ids
430
+ _attention_mask = attention_mask
431
+ if attention_mask is None:
432
+ attention_mask = torch.ones_like(input_ids, dtype=torch.bool)
433
+ else:
434
+ attention_mask = attention_mask.bool()
435
+ if position_ids is None:
436
+ position_ids = torch.arange(0, input_ids.shape[1], dtype=torch.long, device=input_ids.device)
437
+ if labels is None:
438
+ labels = torch.full_like(input_ids, IGNORE_INDEX)
439
+
440
+ # remove the padding using attention_mask -- FIXME
441
+ _input_ids = input_ids
442
+ input_ids = [cur_input_ids[cur_attention_mask] for cur_input_ids, cur_attention_mask in zip(input_ids, attention_mask)]
443
+ labels = [cur_labels[cur_attention_mask] for cur_labels, cur_attention_mask in zip(labels, attention_mask)]
444
+
445
+ new_input_embeds = []
446
+ new_labels = []
447
+ cur_image_idx = 0
448
+ # rank_print("Inserting Images embedding")
449
+ for batch_idx, cur_input_ids in enumerate(input_ids):
450
+ num_images = (cur_input_ids == IMAGE_TOKEN_INDEX).sum()
451
+ # rank0_print(num_images)
452
+ if num_images == 0:
453
+ cur_image_features = image_features[cur_image_idx]
454
+ cur_input_embeds_1 = self.get_model().embed_tokens(cur_input_ids)
455
+ cur_input_embeds = torch.cat([cur_input_embeds_1, cur_image_features[0:0]], dim=0)
456
+ new_input_embeds.append(cur_input_embeds)
457
+ new_labels.append(labels[batch_idx])
458
+ cur_image_idx += 1
459
+ continue
460
+
461
+ image_token_indices = [-1] + torch.where(cur_input_ids == IMAGE_TOKEN_INDEX)[0].tolist() + [cur_input_ids.shape[0]]
462
+ cur_input_ids_noim = []
463
+ cur_labels = labels[batch_idx]
464
+ cur_labels_noim = []
465
+ for i in range(len(image_token_indices) - 1):
466
+ cur_input_ids_noim.append(cur_input_ids[image_token_indices[i] + 1 : image_token_indices[i + 1]])
467
+ cur_labels_noim.append(cur_labels[image_token_indices[i] + 1 : image_token_indices[i + 1]])
468
+ split_sizes = [x.shape[0] for x in cur_labels_noim]
469
+ cur_input_embeds = self.get_model().embed_tokens(torch.cat(cur_input_ids_noim))
470
+ cur_input_embeds_no_im = torch.split(cur_input_embeds, split_sizes, dim=0)
471
+ cur_new_input_embeds = []
472
+ cur_new_labels = []
473
+
474
+ for i in range(num_images + 1):
475
+ cur_new_input_embeds.append(cur_input_embeds_no_im[i])
476
+ cur_new_labels.append(cur_labels_noim[i])
477
+ if i < num_images:
478
+ try:
479
+ cur_image_features = image_features[cur_image_idx]
480
+ except IndexError:
481
+ cur_image_features = image_features[cur_image_idx - 1]
482
+ cur_image_idx += 1
483
+ cur_new_input_embeds.append(cur_image_features)
484
+ cur_new_labels.append(torch.full((cur_image_features.shape[0],), IGNORE_INDEX, device=cur_labels.device, dtype=cur_labels.dtype))
485
+
486
+ cur_new_input_embeds = [x.to(self.device) for x in cur_new_input_embeds]
487
+
488
+ # import pdb; pdb.set_trace()
489
+ cur_new_input_embeds = torch.cat(cur_new_input_embeds)
490
+ cur_new_labels = torch.cat(cur_new_labels)
491
+
492
+ new_input_embeds.append(cur_new_input_embeds)
493
+ new_labels.append(cur_new_labels)
494
+
495
+ # Truncate sequences to max length as image embeddings can make the sequence longer
496
+ tokenizer_model_max_length = getattr(self.config, "tokenizer_model_max_length", None)
497
+ # rank_print("Finishing Inserting")
498
+
499
+ new_input_embeds = [x[:tokenizer_model_max_length] for x, modality in zip(new_input_embeds, modalities)]
500
+ new_labels = [x[:tokenizer_model_max_length] for x, modality in zip(new_labels, modalities)]
501
+ # TODO: Hard code for control loss spike
502
+ # if tokenizer_model_max_length is not None:
503
+ # new_input_embeds = [x[:4096] if modality != "video" else x[:tokenizer_model_max_length] for x, modality in zip(new_input_embeds, modalities)]
504
+ # new_labels = [x[:4096] if modality != "video" else x[:tokenizer_model_max_length] for x, modality in zip(new_labels, modalities)]
505
+
506
+ # Combine them
507
+ max_len = max(x.shape[0] for x in new_input_embeds)
508
+ batch_size = len(new_input_embeds)
509
+
510
+ new_input_embeds_padded = []
511
+ new_labels_padded = torch.full((batch_size, max_len), IGNORE_INDEX, dtype=new_labels[0].dtype, device=new_labels[0].device)
512
+ attention_mask = torch.zeros((batch_size, max_len), dtype=attention_mask.dtype, device=attention_mask.device)
513
+ position_ids = torch.zeros((batch_size, max_len), dtype=position_ids.dtype, device=position_ids.device)
514
+ # rank0_print("Prepare pos id")
515
+
516
+ for i, (cur_new_embed, cur_new_labels) in enumerate(zip(new_input_embeds, new_labels)):
517
+ cur_len = cur_new_embed.shape[0]
518
+ if getattr(self.config, "tokenizer_padding_side", "right") == "left":
519
+ new_input_embeds_padded.append(torch.cat((torch.zeros((max_len - cur_len, cur_new_embed.shape[1]), dtype=cur_new_embed.dtype, device=cur_new_embed.device), cur_new_embed), dim=0))
520
+ if cur_len > 0:
521
+ new_labels_padded[i, -cur_len:] = cur_new_labels
522
+ attention_mask[i, -cur_len:] = True
523
+ position_ids[i, -cur_len:] = torch.arange(0, cur_len, dtype=position_ids.dtype, device=position_ids.device)
524
+ else:
525
+ new_input_embeds_padded.append(torch.cat((cur_new_embed, torch.zeros((max_len - cur_len, cur_new_embed.shape[1]), dtype=cur_new_embed.dtype, device=cur_new_embed.device)), dim=0))
526
+ if cur_len > 0:
527
+ new_labels_padded[i, :cur_len] = cur_new_labels
528
+ attention_mask[i, :cur_len] = True
529
+ position_ids[i, :cur_len] = torch.arange(0, cur_len, dtype=position_ids.dtype, device=position_ids.device)
530
+
531
+ new_input_embeds = torch.stack(new_input_embeds_padded, dim=0)
532
+ # rank0_print("tokenizer padding")
533
+
534
+ if _labels is None:
535
+ new_labels = None
536
+ else:
537
+ new_labels = new_labels_padded
538
+
539
+ if _attention_mask is None:
540
+ attention_mask = None
541
+ else:
542
+ attention_mask = attention_mask.to(dtype=_attention_mask.dtype)
543
+
544
+ if _position_ids is None:
545
+ position_ids = None
546
+ if getattr(self.config, "use_pos_skipping", False) and self.training:
547
+ position_ids = torch.arange(new_input_embeds.size(1), device=new_input_embeds.device).unsqueeze(0).to(new_input_embeds.device)
548
+ split_position = random.randint(0, new_input_embeds.size(1))
549
+ left_add = random.randint(0, self.config.pos_skipping_range)
550
+ right_add = random.randint(left_add, self.config.pos_skipping_range)
551
+ position_ids[:, :split_position] += left_add
552
+ position_ids[:, split_position:] += right_add
553
+ # import pdb; pdb.set_trace()
554
+ # rank0_print("Finish preparing")
555
+ return None, position_ids, attention_mask, past_key_values, new_input_embeds, new_labels
556
+
557
+ def initialize_vision_tokenizer(self, model_args, tokenizer):
558
+ if model_args.mm_use_im_patch_token:
559
+ tokenizer.add_tokens([DEFAULT_IMAGE_PATCH_TOKEN], special_tokens=True)
560
+ self.resize_token_embeddings(len(tokenizer))
561
+
562
+ if model_args.mm_use_im_start_end:
563
+ num_new_tokens = tokenizer.add_tokens([DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN], special_tokens=True)
564
+ self.resize_token_embeddings(len(tokenizer))
565
+
566
+ if num_new_tokens > 0:
567
+ input_embeddings = self.get_input_embeddings().weight.data
568
+ output_embeddings = self.get_output_embeddings().weight.data
569
+
570
+ input_embeddings_avg = input_embeddings[:-num_new_tokens].mean(dim=0, keepdim=True)
571
+ output_embeddings_avg = output_embeddings[:-num_new_tokens].mean(dim=0, keepdim=True)
572
+
573
+ input_embeddings[-num_new_tokens:] = input_embeddings_avg
574
+ output_embeddings[-num_new_tokens:] = output_embeddings_avg
575
+
576
+ if model_args.tune_mm_mlp_adapter:
577
+ for p in self.get_input_embeddings().parameters():
578
+ p.requires_grad = True
579
+ for p in self.get_output_embeddings().parameters():
580
+ p.requires_grad = False
581
+
582
+ if model_args.pretrain_mm_mlp_adapter:
583
+ mm_projector_weights = torch.load(model_args.pretrain_mm_mlp_adapter, map_location="cpu")
584
+ embed_tokens_weight = mm_projector_weights["model.embed_tokens.weight"]
585
+ assert num_new_tokens == 2
586
+ if input_embeddings.shape == embed_tokens_weight.shape:
587
+ input_embeddings[-num_new_tokens:] = embed_tokens_weight[-num_new_tokens:]
588
+ elif embed_tokens_weight.shape[0] == num_new_tokens:
589
+ input_embeddings[-num_new_tokens:] = embed_tokens_weight
590
+ else:
591
+ raise ValueError(f"Unexpected embed_tokens_weight shape. Pretrained: {embed_tokens_weight.shape}. Current: {input_embeddings.shape}. Numer of new tokens: {num_new_tokens}.")
592
+ elif model_args.mm_use_im_patch_token:
593
+ if model_args.tune_mm_mlp_adapter:
594
+ for p in self.get_input_embeddings().parameters():
595
+ p.requires_grad = False
596
+ for p in self.get_output_embeddings().parameters():
597
+ p.requires_grad = False
之前的代码版本/第一版-全部代码/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/llava/train/llama_flash_attn_monkey_patch.py ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Optional, Tuple
2
+ import warnings
3
+
4
+ import torch
5
+
6
+ import transformers
7
+ from transformers.models.llama.modeling_llama import apply_rotary_pos_emb, repeat_kv
8
+
9
+ try:
10
+ from flash_attn.flash_attn_interface import flash_attn_unpadded_qkvpacked_func
11
+ except ImportError:
12
+ from flash_attn.flash_attn_interface import flash_attn_varlen_qkvpacked_func as flash_attn_unpadded_qkvpacked_func
13
+ from flash_attn.bert_padding import unpad_input, pad_input
14
+
15
+
16
+ def forward(
17
+ self,
18
+ hidden_states: torch.Tensor,
19
+ attention_mask: Optional[torch.Tensor] = None,
20
+ position_ids: Optional[torch.Tensor] = None,
21
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
22
+ output_attentions: bool = False,
23
+ use_cache: bool = False,
24
+ padding_mask: Optional[torch.Tensor] = None,
25
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
26
+ if output_attentions:
27
+ warnings.warn("Output attentions is not supported for patched `LlamaAttention`, returning `None` instead.")
28
+
29
+ bsz, q_len, _ = hidden_states.size()
30
+
31
+ query_states = self.q_proj(hidden_states).view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
32
+ key_states = self.k_proj(hidden_states).view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
33
+ value_states = self.v_proj(hidden_states).view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2) # shape: (b, num_heads, s, head_dim)
34
+
35
+ kv_seq_len = key_states.shape[-2]
36
+ if past_key_value is not None:
37
+ kv_seq_len += past_key_value[0].shape[-2]
38
+
39
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
40
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
41
+
42
+ if past_key_value is not None:
43
+ # reuse k, v
44
+ key_states = torch.cat([past_key_value[0], key_states], dim=2)
45
+ value_states = torch.cat([past_key_value[1], value_states], dim=2)
46
+
47
+ past_key_value = (key_states, value_states) if use_cache else None
48
+
49
+ # repeat k/v heads if n_kv_heads < n_heads
50
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
51
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
52
+
53
+ # Transform the data into the format required by flash attention
54
+ qkv = torch.stack([query_states, key_states, value_states], dim=2)
55
+ qkv = qkv.transpose(1, 3) # shape: [b, s, 3, num_heads, head_dim]
56
+ key_padding_mask = attention_mask
57
+
58
+ if key_padding_mask is None:
59
+ qkv = qkv.reshape(-1, 3, self.num_heads, self.head_dim)
60
+ cu_q_lens = torch.arange(0, (bsz + 1) * q_len, step=q_len, dtype=torch.int32, device=qkv.device)
61
+ max_s = q_len
62
+ output = flash_attn_unpadded_qkvpacked_func(qkv, cu_q_lens, max_s, 0.0, softmax_scale=None, causal=True)
63
+ output = output.view(bsz, q_len, -1)
64
+ else:
65
+ qkv = qkv.reshape(bsz, q_len, -1)
66
+ qkv, indices, cu_q_lens, max_s = unpad_input(qkv, key_padding_mask)
67
+ qkv = qkv.view(-1, 3, self.num_heads, self.head_dim)
68
+ output_unpad = flash_attn_unpadded_qkvpacked_func(qkv, cu_q_lens, max_s, 0.0, softmax_scale=None, causal=True)
69
+ output_unpad = output_unpad.reshape(-1, self.num_heads * self.head_dim)
70
+ output = pad_input(output_unpad, indices, bsz, q_len)
71
+
72
+ return self.o_proj(output), None, past_key_value
73
+
74
+
75
+ # Disable the transformation of the attention mask in LlamaModel as the flash attention
76
+ # requires the attention mask to be the same as the key_padding_mask
77
+ def _prepare_decoder_attention_mask(self, attention_mask, input_shape, inputs_embeds, past_key_values_length):
78
+ # [bsz, seq_len]
79
+ return attention_mask
80
+
81
+
82
+ def replace_llama_attn_with_flash_attn():
83
+ cuda_major, cuda_minor = torch.cuda.get_device_capability()
84
+ if cuda_major < 8:
85
+ warnings.warn("Flash attention is only supported on A100 or H100 GPU during training due to head dim > 64 backward." "ref: https://github.com/HazyResearch/flash-attention/issues/190#issuecomment-1523359593")
86
+ transformers.models.llama.modeling_llama.LlamaModel._prepare_decoder_attention_mask = _prepare_decoder_attention_mask
87
+ transformers.models.llama.modeling_llama.LlamaAttention.forward = forward
之前的代码版本/第一版-全部代码/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/llava/train/llava_trainer.py ADDED
@@ -0,0 +1,1305 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import torch
3
+ import torch.nn as nn
4
+ import datetime
5
+
6
+ from accelerate import Accelerator
7
+ from accelerate.utils import InitProcessGroupKwargs, GradientAccumulationPlugin
8
+ from torch.utils.data import Dataset, Sampler, DataLoader
9
+
10
+ from trl.trainer import DPOTrainer
11
+ from trl.trainer.utils import DPODataCollatorWithPadding
12
+
13
+ from transformers import Trainer
14
+ from transformers.trainer import is_sagemaker_mp_enabled, get_parameter_names, has_length, ALL_LAYERNORM_LAYERS, logger, is_accelerate_available, is_datasets_available, GradientAccumulationPlugin
15
+ from transformers.trainer_utils import seed_worker
16
+ from transformers.trainer_pt_utils import get_length_grouped_indices as get_length_grouped_indices_hf
17
+ from transformers.trainer_pt_utils import AcceleratorConfig
18
+ from typing import List, Optional
19
+ from datetime import timedelta
20
+
21
+ if is_accelerate_available():
22
+ from accelerate import Accelerator, skip_first_batches, InitProcessGroupKwargs
23
+
24
+ if is_datasets_available():
25
+ import datasets
26
+
27
+ from llava.utils import rank0_print
28
+
29
+
30
+ def maybe_zero_3(param, ignore_status=False, name=None):
31
+ from deepspeed import zero
32
+ from deepspeed.runtime.zero.partition_parameters import ZeroParamStatus
33
+
34
+ if hasattr(param, "ds_id"):
35
+ if param.ds_status == ZeroParamStatus.NOT_AVAILABLE:
36
+ if not ignore_status:
37
+ print(name, "no ignore status")
38
+ with zero.GatheredParameters([param]):
39
+ param = param.data.detach().cpu().clone()
40
+ else:
41
+ param = param.detach().cpu().clone()
42
+ return param
43
+
44
+
45
+ def get_mm_adapter_state_maybe_zero_3(named_params, keys_to_match):
46
+ to_return = {k: t for k, t in named_params if any(key_match in k for key_match in keys_to_match)}
47
+ to_return = {k: maybe_zero_3(v, ignore_status=True, name=k).cpu() for k, v in to_return.items()}
48
+ return to_return
49
+
50
+
51
+ def should_only_save_mm_adapter(args) -> bool:
52
+ # LoRA runs need full PEFT checkpoint handling, even when adapters are also trainable.
53
+ if getattr(args, "lora_enable", False):
54
+ return False
55
+
56
+ if getattr(args, "tune_mm_mlp_adapter", False):
57
+ return True
58
+
59
+ mm_tunable_parts = getattr(args, "mm_tunable_parts", None)
60
+ if not mm_tunable_parts:
61
+ return False
62
+
63
+ tunable_parts = [part.strip() for part in mm_tunable_parts.split(",") if part.strip()]
64
+ return len(tunable_parts) == 1 and tunable_parts[0] in {"mm_mlp_adapter", "mm_vision_resampler"}
65
+
66
+
67
+ def split_to_even_chunks(indices, lengths, num_chunks):
68
+ """
69
+ Split a list of indices into `chunks` chunks of roughly equal lengths.
70
+ """
71
+
72
+ if len(indices) % num_chunks != 0:
73
+ return [indices[i::num_chunks] for i in range(num_chunks)]
74
+
75
+ num_indices_per_chunk = len(indices) // num_chunks
76
+
77
+ chunks = [[] for _ in range(num_chunks)]
78
+ chunks_lengths = [0 for _ in range(num_chunks)]
79
+ for index in indices:
80
+ shortest_chunk = chunks_lengths.index(min(chunks_lengths))
81
+ chunks[shortest_chunk].append(index)
82
+ chunks_lengths[shortest_chunk] += lengths[index]
83
+ if len(chunks[shortest_chunk]) == num_indices_per_chunk:
84
+ chunks_lengths[shortest_chunk] = float("inf")
85
+
86
+ return chunks
87
+
88
+
89
+ def get_variable_length_grouped_indices(lengths, batch_size, world_size, megabatch_mult=8, generator=None):
90
+ # We need to use torch for the random part as a distributed sampler will set the random seed for torch.
91
+ indices = torch.randperm(len(lengths), generator=generator)
92
+ sorted_indices = sorted(range(len(lengths)), key=lambda i: lengths[i], reverse=True)
93
+ megabatch_size = world_size * batch_size * megabatch_mult
94
+ megabatches = [sorted_indices[i : i + megabatch_size] for i in range(0, len(lengths), megabatch_size)]
95
+ megabatches = [sorted(megabatch, key=lambda i: indices[i], reverse=True) for megabatch in megabatches]
96
+ shuffled_indices = [i for megabatch in megabatches for i in megabatch]
97
+ world_batch_size = world_size * batch_size
98
+ batches = [shuffled_indices[i : i + world_batch_size] for i in range(0, len(lengths), world_batch_size)]
99
+ batch_indices = torch.randperm(len(batches), generator=generator)
100
+ batches = [batches[i] for i in batch_indices]
101
+
102
+ return [i for batch in batches for i in batch]
103
+
104
+
105
+ def get_modality_length_grouped_indices(lengths, batch_size, world_size, generator=None):
106
+ """
107
+ Return a list of indices so that each slice of `batch_size` consecutive indices correspond to elements of similar
108
+ lengths. To do this, the indices are:
109
+
110
+ - randomly permuted
111
+ - grouped in mega-batches of size `mega_batch_mult * batch_size`
112
+ - reorder by length in each mega-batch
113
+
114
+ The result is the concatenation of all mega-batches, with the batch of `batch_size` containing the element of
115
+ maximum length placed first, so that an OOM happens sooner rather than later.
116
+ """
117
+
118
+ # We need to use torch for the random part as a distributed sampler will set the random seed for torch.
119
+ assert all(l != 0 for l in lengths), "Should not have zero length."
120
+ if all(l > 0 for l in lengths) or all(l < 0 for l in lengths):
121
+ # all samples are in the same modality
122
+ return get_length_grouped_indices(lengths, batch_size, world_size, generator=generator)
123
+ mm_indices, mm_lengths = zip(*[(i, l) for i, l in enumerate(lengths) if l > 0])
124
+ lang_indices, lang_lengths = zip(*[(i, -l) for i, l in enumerate(lengths) if l < 0])
125
+
126
+ mm_shuffle = [mm_indices[i] for i in get_length_grouped_indices(mm_lengths, batch_size, world_size, generator=None)]
127
+ lang_shuffle = [lang_indices[i] for i in get_length_grouped_indices(lang_lengths, batch_size, world_size, generator=None)]
128
+ megabatch_size = world_size * batch_size
129
+ mm_megabatches = [mm_shuffle[i : i + megabatch_size] for i in range(0, len(mm_shuffle), megabatch_size)]
130
+ lang_megabatches = [lang_shuffle[i : i + megabatch_size] for i in range(0, len(lang_shuffle), megabatch_size)]
131
+
132
+ last_mm = mm_megabatches[-1]
133
+ last_lang = lang_megabatches[-1]
134
+ additional_batch = last_mm + last_lang
135
+ megabatches = mm_megabatches[:-1] + lang_megabatches[:-1]
136
+ megabatch_indices = torch.randperm(len(megabatches), generator=generator)
137
+ megabatches = [megabatches[i] for i in megabatch_indices]
138
+
139
+ if len(additional_batch) > 0:
140
+ megabatches.append(sorted(additional_batch))
141
+
142
+ return [i for megabatch in megabatches for i in megabatch]
143
+
144
+
145
+ def get_length_grouped_indices(lengths, batch_size, world_size, generator=None, merge=True):
146
+ """
147
+ Return a list of indices so that each slice of `batch_size` consecutive indices correspond to elements of similar
148
+ lengths. To do this, the indices are:
149
+
150
+ - randomly permuted
151
+ - grouped in mega-batches of size `mega_batch_mult * batch_size`
152
+ - reorder by length in each mega-batch
153
+
154
+ The result is the concatenation of all mega-batches, with the batch of `batch_size` containing the element of
155
+ maximum length placed first, so that an OOM happens sooner rather than later.
156
+ """
157
+
158
+ # We need to use torch for the random part as a distributed sampler will set the random seed for torch.
159
+ indices = torch.randperm(len(lengths), generator=generator)
160
+ megabatch_size = world_size * batch_size
161
+ megabatches = [indices[i : i + megabatch_size].tolist() for i in range(0, len(lengths), megabatch_size)]
162
+ megabatches = [sorted(megabatch, key=lambda i: lengths[i], reverse=True) for megabatch in megabatches]
163
+ megabatches = [split_to_even_chunks(megabatch, lengths, world_size) for megabatch in megabatches]
164
+
165
+ return [i for megabatch in megabatches for batch in megabatch for i in batch]
166
+
167
+
168
+ def get_length_grouped_indices_auto_single(lengths, batch_size, world_size, generator=None):
169
+ indices = get_length_grouped_indices_hf(lengths, batch_size * world_size, generator=generator)
170
+
171
+ megabatch_size = world_size * batch_size
172
+ megabatches = [indices[i : i + megabatch_size] for i in range(0, len(lengths), megabatch_size)]
173
+ megabatches = [sorted(megabatch, key=lambda i: lengths[i], reverse=True) for megabatch in megabatches]
174
+ megabatches = [split_to_even_chunks(megabatch, lengths, world_size) for megabatch in megabatches]
175
+
176
+ # We need to use torch for the random part as a distributed sampler will set the random seed for torch.
177
+ batch_indices = torch.randperm(len(megabatches), generator=generator)
178
+ megabatches = [megabatches[i] for i in batch_indices]
179
+
180
+ return [i for megabatch in megabatches for batch in megabatch for i in batch]
181
+
182
+
183
+ def get_modality_length_grouped_indices_auto(lengths, batch_size, world_size, generator=None):
184
+ # We need to use torch for the random part as a distributed sampler will set the random seed for torch.
185
+ assert all(l != 0 for l in lengths), "Should not have zero length."
186
+ if all(l > 0 for l in lengths) or all(l < 0 for l in lengths):
187
+ # all samples are in the same modality
188
+ return get_length_grouped_indices_auto_single(lengths, batch_size, world_size, generator=generator)
189
+ mm_indices, mm_lengths = zip(*[(i, l) for i, l in enumerate(lengths) if l > 0])
190
+ lang_indices, lang_lengths = zip(*[(i, -l) for i, l in enumerate(lengths) if l < 0])
191
+
192
+ mm_shuffle = [mm_indices[i] for i in get_length_grouped_indices_auto_single(mm_lengths, batch_size, world_size, generator=None)]
193
+ lang_shuffle = [lang_indices[i] for i in get_length_grouped_indices_auto_single(lang_lengths, batch_size, world_size, generator=None)]
194
+ megabatch_size = world_size * batch_size
195
+ mm_megabatches = [mm_shuffle[i : i + megabatch_size] for i in range(0, len(mm_shuffle), megabatch_size)]
196
+ lang_megabatches = [lang_shuffle[i : i + megabatch_size] for i in range(0, len(lang_shuffle), megabatch_size)]
197
+
198
+ last_mm = mm_megabatches[-1]
199
+ last_lang = lang_megabatches[-1]
200
+ additional_batch = last_mm + last_lang
201
+ megabatches = mm_megabatches[:-1] + lang_megabatches[:-1]
202
+ megabatch_indices = torch.randperm(len(megabatches), generator=generator)
203
+ megabatches = [megabatches[i] for i in megabatch_indices]
204
+
205
+ # FIXME: Hard code to avoid last batch mixed with different modalities
206
+ # if len(additional_batch) > 0:
207
+ # megabatches.append(sorted(additional_batch))
208
+
209
+ return [i for megabatch in megabatches for i in megabatch]
210
+
211
+
212
+ class LengthGroupedSampler(Sampler):
213
+ r"""
214
+ Sampler that samples indices in a way that groups together features of the dataset of roughly the same length while
215
+ keeping a bit of randomness.
216
+ """
217
+
218
+ def __init__(
219
+ self,
220
+ batch_size: int,
221
+ world_size: int,
222
+ lengths: Optional[List[int]] = None,
223
+ generator=None,
224
+ variable_length: bool = False,
225
+ group_by_modality: bool = False,
226
+ group_by_modality_auto: bool = False,
227
+ ):
228
+ if lengths is None:
229
+ raise ValueError("Lengths must be provided.")
230
+
231
+ self.batch_size = batch_size
232
+ self.world_size = world_size
233
+ self.lengths = lengths
234
+ self.generator = generator
235
+ self.variable_length = variable_length
236
+ self.group_by_modality = group_by_modality
237
+ self.group_by_modality_auto = group_by_modality_auto
238
+
239
+ def __len__(self):
240
+ return len(self.lengths)
241
+
242
+ def __iter__(self):
243
+ if self.variable_length:
244
+ assert not self.group_by_modality, "Variable length grouping is not supported with modality grouping."
245
+ indices = get_variable_length_grouped_indices(self.lengths, self.batch_size, self.world_size, generator=self.generator)
246
+ else:
247
+ if self.group_by_modality:
248
+ indices = get_modality_length_grouped_indices(self.lengths, self.batch_size, self.world_size, generator=self.generator)
249
+ elif self.group_by_modality_auto:
250
+ indices = get_modality_length_grouped_indices_auto(self.lengths, self.batch_size, self.world_size, generator=self.generator)
251
+ else:
252
+ indices = get_length_grouped_indices_auto_single(self.lengths, self.batch_size, self.world_size, generator=self.generator)
253
+ return iter(indices)
254
+
255
+
256
+ class LLaVATrainer(Trainer):
257
+ def __init__(self, **kwargs):
258
+ """
259
+ Initialize the LLaVATrainer with MeZO support.
260
+
261
+ Args:
262
+ trainer_mode (str): Mode of training (`regular`, `zo`).
263
+ zo_eps (float): MeZO hyperparameter epsilon.
264
+ zo_num_directions (int): Number of directions for zero-order optimization.
265
+ """
266
+ super().__init__(**kwargs)
267
+
268
+ args = self.args
269
+
270
+ self.trainer_mode = getattr(args, "trainer_mode", "regular")
271
+ self.zo_eps = getattr(args, "zo_eps", 1e-3)
272
+ self.zo_num_directions = getattr(args, "zo_num_directions", 1)
273
+
274
+ print(f"MeZOLLaVATrainer initialized with mode: {self.trainer_mode}")
275
+ self.projected_grad = None
276
+ self.zo_random_seed = None
277
+
278
+ self.zo_direction_accumulator = []
279
+ self.zo_accumulation_count = 0
280
+
281
+ self.batch_zo_seeds = None
282
+
283
+ self.trainable_params = [(p[0], p[1]) for p in self.model.named_parameters() if p[1].requires_grad]
284
+
285
+ print(f"Trainable parameters amount: {len(self.trainable_params)}")
286
+
287
+ if not self.trainable_params:
288
+ raise ValueError("No trainable parameters found.")
289
+
290
+ if self.trainer_mode == "zo":
291
+ for param in self.model.parameters():
292
+ param.requires_grad = False # Ensure no accidental gradient computation
293
+
294
+ self.mezo_update_history = []
295
+
296
+ ########################
297
+ # MeZO-specific Methods
298
+ ########################
299
+
300
+ def zo_perturb_parameters(self, scaling_factor=1.0):
301
+ """
302
+ Perturb the model parameters with a random vector z.
303
+
304
+ Args:
305
+ scaling_factor (float): Scaling factor for the perturbation.
306
+ """
307
+ torch.manual_seed(self.zo_random_seed)
308
+ for name, param in self.trainable_params:
309
+ z = torch.normal(
310
+ mean=0, std=1, size=param.data.size(),
311
+ device=param.device, dtype=param.dtype
312
+ )
313
+ param.data += scaling_factor * z * self.zo_eps
314
+
315
+ def zo_forward(self, model, inputs):
316
+ """
317
+ Compute the loss.
318
+
319
+ Args:
320
+ model (nn.Module): The model.
321
+ inputs (Dict): Batch of inputs.
322
+
323
+ Returns:
324
+ torch.Tensor: The computed loss.
325
+ """
326
+ model.eval()
327
+ with torch.inference_mode():
328
+ inputs = self._prepare_inputs(inputs)
329
+ with self.compute_loss_context_manager():
330
+ loss = self.compute_loss(model, inputs)
331
+ if self.args.n_gpu > 1:
332
+ loss = loss.mean()
333
+ return loss.detach()
334
+
335
+ def zo_step(self, model, inputs):
336
+ """
337
+ Estimate the gradient using MeZO by performing multiple directional forward passes.
338
+
339
+ Args:
340
+ model (nn.Module): The model.
341
+ inputs (Dict): Batch of inputs.
342
+
343
+ Returns:
344
+ torch.Tensor: The loss from the first forward pass.
345
+ """
346
+ directions = []
347
+
348
+ if self.batch_zo_seeds is None:
349
+ self.batch_zo_seeds = [np.random.randint(1000000000) for _ in range(self.zo_num_directions)]
350
+ print(f"Sampled batch seeds: {self.batch_zo_seeds}")
351
+
352
+ for seed in self.batch_zo_seeds:
353
+ self.zo_random_seed = seed
354
+
355
+ self.zo_perturb_parameters(scaling_factor=1.0)
356
+ loss_plus = self.zo_forward(model, inputs)
357
+
358
+ self.zo_perturb_parameters(scaling_factor=-2.0)
359
+ loss_minus = self.zo_forward(model, inputs)
360
+ print(f"Seed {seed} loss_plus: {loss_plus} loss_minus: {loss_minus}")
361
+
362
+ self.zo_perturb_parameters(scaling_factor=1.0)
363
+
364
+ grad_estimate = ((loss_plus - loss_minus) / (2 * self.zo_eps)).item()
365
+
366
+ directions.append((seed, grad_estimate))
367
+
368
+ update_entry = {
369
+ "type": "zo_step",
370
+ "global_step": self.state.global_step,
371
+ "zo_eps": self.zo_eps,
372
+ "seed": seed,
373
+ }
374
+
375
+ self.mezo_update_history.append(update_entry)
376
+
377
+ self.zo_direction_accumulator.extend(directions)
378
+ self.zo_accumulation_count += 1
379
+
380
+ return loss_plus / (self.args.gradient_accumulation_steps * self.zo_num_directions)
381
+
382
+ def zo_update(self, learning_rate):
383
+ """
384
+ Update model parameters based on the estimated gradient.
385
+
386
+ Args:
387
+ learning_rate (float): The learning rate used for the update.
388
+ """
389
+ if len(self.zo_direction_accumulator) == 0:
390
+ print("No accumulated directions to update.")
391
+ return
392
+
393
+ seed_group = {}
394
+ for seed, grad_estimate in self.zo_direction_accumulator:
395
+ if seed in seed_group:
396
+ seed_group[seed] += grad_estimate / (self.args.gradient_accumulation_steps * self.zo_num_directions)
397
+ else:
398
+ seed_group[seed] = grad_estimate / (self.args.gradient_accumulation_steps * self.zo_num_directions)
399
+
400
+ for seed, grad_sum in seed_group.items():
401
+ torch.manual_seed(seed)
402
+
403
+ for name, param in self.trainable_params:
404
+ z = torch.normal(
405
+ mean=0, std=1, size=param.data.size(),
406
+ device=param.device, dtype=param.dtype
407
+ )
408
+ if "bias" not in name and "layer_norm" not in name and "layernorm" not in name:
409
+ param.data -= learning_rate * (grad_sum * z + self.args.weight_decay * param.data)
410
+ else:
411
+ param.data -= learning_rate * grad_sum * z
412
+
413
+ print(
414
+ f"Applied MeZO update with aggregated grad estimates "
415
+ f"from {len(self.zo_direction_accumulator)} directions "
416
+ f"(aggregated to {len(seed_group)} unique seeds)."
417
+ f"Seed group: {seed_group}")
418
+
419
+ self.zo_direction_accumulator = []
420
+ self.zo_accumulation_count = 0
421
+ self.batch_zo_seeds = None
422
+
423
+ update_entry = {
424
+ "type": "mezo_update",
425
+ "global_step": self.state.global_step,
426
+ "learning_rate": learning_rate,
427
+ "seed_group": seed_group
428
+ }
429
+
430
+ self.mezo_update_history.append(update_entry)
431
+
432
+ def _save_mezo_state(self, output_dir: str):
433
+ """
434
+ Save the MeZO state checkpoint that includes the noise seeds and the accumulated grad estimates.
435
+ """
436
+ mezo_state = {
437
+ "weight_decay": self.args.weight_decay,
438
+ "zo_eps": self.zo_eps,
439
+ "zo_num_directions": self.zo_num_directions,
440
+ "trainable_params_names": [name for name, _ in self.trainable_params],
441
+ "trainable_params_sizes": {name: param.size() for name, param in self.trainable_params},
442
+ "update_history": self.mezo_update_history
443
+ }
444
+ mezo_checkpoint_path = os.path.join(output_dir, "mezo_state.pt")
445
+ torch.save(mezo_state, mezo_checkpoint_path)
446
+ print(f"MeZO checkpoint saved at {mezo_checkpoint_path}")
447
+
448
+ def save_model(self, output_dir: Optional[str] = None, _internal_call: bool = False):
449
+ """
450
+ Override the save_model method to also store the lightweight MeZO checkpoint.
451
+ """
452
+ ret = super().save_model(output_dir, _internal_call)
453
+
454
+ if self.trainer_mode == "zo":
455
+ output_dir = output_dir if output_dir is not None else self.args.output_dir
456
+ self._save_mezo_state(output_dir)
457
+ return ret
458
+
459
+ ########################
460
+ # MeZO-specific Methods
461
+ ########################
462
+
463
+ def create_accelerator_and_postprocess(self):
464
+ grad_acc_kwargs = {"num_steps": self.args.gradient_accumulation_steps}
465
+ grad_acc_kwargs["sync_with_dataloader"] = False
466
+ gradient_accumulation_plugin = GradientAccumulationPlugin(**grad_acc_kwargs)
467
+
468
+ accelerator_kwargs = InitProcessGroupKwargs(timeout=timedelta(weeks=52))
469
+ rank0_print("Setting NCCL timeout to INF to avoid running errors.")
470
+
471
+ # create accelerator object
472
+ self.accelerator = Accelerator(
473
+ dispatch_batches=self.args.dispatch_batches, split_batches=self.args.split_batches, deepspeed_plugin=self.args.deepspeed_plugin, gradient_accumulation_plugin=gradient_accumulation_plugin, kwargs_handlers=[accelerator_kwargs]
474
+ )
475
+ # some Trainer classes need to use `gather` instead of `gather_for_metrics`, thus we store a flag
476
+ self.gather_function = self.accelerator.gather_for_metrics
477
+
478
+ # deepspeed and accelerate flags covering both trainer args and accelerate launcher
479
+ self.is_deepspeed_enabled = getattr(self.accelerator.state, "deepspeed_plugin", None) is not None
480
+ self.is_fsdp_enabled = getattr(self.accelerator.state, "fsdp_plugin", None) is not None
481
+
482
+ # post accelerator creation setup
483
+ if self.is_fsdp_enabled:
484
+ fsdp_plugin = self.accelerator.state.fsdp_plugin
485
+ fsdp_plugin.limit_all_gathers = self.args.fsdp_config.get("limit_all_gathers", fsdp_plugin.limit_all_gathers)
486
+ if is_accelerate_available("0.23.0"):
487
+ fsdp_plugin.activation_checkpointing = self.args.fsdp_config.get("activation_checkpointing", fsdp_plugin.activation_checkpointing)
488
+ if fsdp_plugin.activation_checkpointing and self.args.gradient_checkpointing:
489
+ raise ValueError("The activation_checkpointing in FSDP config and the gradient_checkpointing in training arg " "can't be set to True simultaneously. Please use FSDP's activation_checkpointing logic " "when using FSDP.")
490
+
491
+ if self.is_deepspeed_enabled and getattr(self.args, "hf_deepspeed_config", None) is None:
492
+ self.propagate_args_to_deepspeed()
493
+
494
+ def _get_train_sampler(self) -> Optional[torch.utils.data.Sampler]:
495
+ if self.train_dataset is None or not has_length(self.train_dataset):
496
+ return None
497
+
498
+ if self.args.group_by_length:
499
+ lengths = self.train_dataset.lengths
500
+ return LengthGroupedSampler(
501
+ # self.args.train_batch_size * self.args.gradient_accumulation_steps, # TODO: seems that we should not have gradient_accumulation_steps
502
+ self.args.train_batch_size,
503
+ # world_size=self.args.world_size,
504
+ world_size=self.args.world_size * self.args.gradient_accumulation_steps, # TODO: seems that this may work?
505
+ lengths=lengths,
506
+ )
507
+ elif self.args.group_by_modality_length:
508
+ lengths = self.train_dataset.modality_lengths
509
+ return LengthGroupedSampler(
510
+ # self.args.train_batch_size * self.args.gradient_accumulation_steps, # TODO: seems that we should not have gradient_accumulation_steps
511
+ self.args.train_batch_size,
512
+ # world_size=self.args.world_size,
513
+ world_size=self.args.world_size * self.args.gradient_accumulation_steps, # TODO: seems that this may work?
514
+ lengths=lengths,
515
+ group_by_modality=True,
516
+ )
517
+ elif self.args.group_by_modality_length_auto:
518
+ lengths = self.train_dataset.modality_lengths
519
+ return LengthGroupedSampler(
520
+ # self.args.train_batch_size * self.args.gradient_accumulation_steps, # TODO: seems that we should not have gradient_accumulation_steps
521
+ self.args.train_batch_size,
522
+ # world_size=self.args.world_size,
523
+ world_size=self.args.world_size * self.args.gradient_accumulation_steps, # TODO: seems that this may work?
524
+ lengths=lengths,
525
+ group_by_modality_auto=True,
526
+ )
527
+ elif self.args.group_by_varlen:
528
+ lengths = self.train_dataset.lengths
529
+ return LengthGroupedSampler(
530
+ self.args.train_batch_size * self.args.gradient_accumulation_steps,
531
+ # self.args.train_batch_size, # TODO: seems that we should have gradient_accumulation_steps
532
+ # world_size=self.args.world_size,
533
+ world_size=self.args.world_size * self.args.gradient_accumulation_steps, # TODO: seems that this may work?
534
+ lengths=lengths,
535
+ variable_length=True,
536
+ )
537
+ else:
538
+ return super()._get_train_sampler()
539
+
540
+ def get_train_dataloader(self) -> DataLoader:
541
+ """
542
+ Returns the training [`~torch.utils.data.DataLoader`].
543
+
544
+ Will use no sampler if `train_dataset` does not implement `__len__`, a random sampler (adapted to distributed
545
+ training if necessary) otherwise.
546
+
547
+ Subclass and override this method if you want to inject some custom behavior.
548
+ """
549
+ if self.train_dataset is None:
550
+ raise ValueError("Trainer: training requires a train_dataset.")
551
+
552
+ train_dataset = self.train_dataset
553
+ data_collator = self.data_collator
554
+ if is_datasets_available() and isinstance(train_dataset, datasets.Dataset):
555
+ train_dataset = self._remove_unused_columns(train_dataset, description="training")
556
+ else:
557
+ data_collator = self._get_collator_with_removed_columns(data_collator, description="training")
558
+
559
+ dataloader_params = {
560
+ "batch_size": self._train_batch_size,
561
+ "collate_fn": data_collator,
562
+ "num_workers": self.args.dataloader_num_workers,
563
+ "pin_memory": self.args.dataloader_pin_memory,
564
+ "persistent_workers": self.args.dataloader_persistent_workers,
565
+ }
566
+
567
+ if not isinstance(train_dataset, torch.utils.data.IterableDataset):
568
+ dataloader_params["sampler"] = self._get_train_sampler()
569
+ dataloader_params["drop_last"] = self.args.dataloader_drop_last
570
+ dataloader_params["worker_init_fn"] = seed_worker
571
+ dataloader_params["prefetch_factor"] = self.args.dataloader_num_workers * 2 if self.args.dataloader_num_workers != 0 else None
572
+
573
+ dataloader = self.accelerator.prepare(DataLoader(train_dataset, **dataloader_params))
574
+
575
+ return dataloader
576
+
577
+ def create_optimizer(self):
578
+ """
579
+ Setup the optimizer.
580
+
581
+ We provide a reasonable default that works well. If you want to use something else, you can pass a tuple in the
582
+ Trainer's init through `optimizers`, or subclass and override this method in a subclass.
583
+ """
584
+ if self.trainer_mode == "zo":
585
+ # Create a dummy optimizer with this dummy parameter.
586
+ # This optimizer will never really be stepped using backprop gradients.
587
+ # We use no optimizer for MeZO. All updates are done in the `zo` methods.
588
+ dummy_param = torch.nn.Parameter(torch.zeros(1, device=self.args.device))
589
+ self.optimizer = torch.optim.AdamW([dummy_param], lr=self.args.learning_rate)
590
+ return self.optimizer
591
+
592
+ if is_sagemaker_mp_enabled():
593
+ return super().create_optimizer()
594
+
595
+ opt_model = self.model
596
+
597
+ if self.optimizer is None:
598
+ decay_parameters = get_parameter_names(opt_model, ALL_LAYERNORM_LAYERS)
599
+ decay_parameters = [name for name in decay_parameters if "bias" not in name]
600
+ lr_mapper = {}
601
+ if self.args.mm_projector_lr is not None:
602
+ lr_mapper["mm_projector"] = self.args.mm_projector_lr
603
+ if self.args.mm_vision_tower_lr is not None:
604
+ lr_mapper["vision_tower"] = self.args.mm_vision_tower_lr
605
+ if len(lr_mapper) > 0:
606
+ special_lr_parameters = [name for name, _ in opt_model.named_parameters() if any(module_keyword in name for module_keyword in lr_mapper)]
607
+ optimizer_grouped_parameters = [
608
+ {
609
+ "params": [p for n, p in opt_model.named_parameters() if (n in decay_parameters and n not in special_lr_parameters and p.requires_grad)],
610
+ "weight_decay": self.args.weight_decay,
611
+ },
612
+ {
613
+ "params": [p for n, p in opt_model.named_parameters() if (n not in decay_parameters and n not in special_lr_parameters and p.requires_grad)],
614
+ "weight_decay": 0.0,
615
+ },
616
+ ]
617
+ for module_keyword, lr in lr_mapper.items():
618
+ module_parameters = [name for name, _ in opt_model.named_parameters() if module_keyword in name]
619
+ optimizer_grouped_parameters.extend(
620
+ [
621
+ {
622
+ "params": [p for n, p in opt_model.named_parameters() if (n in decay_parameters and n in module_parameters and p.requires_grad)],
623
+ "weight_decay": self.args.weight_decay,
624
+ "lr": lr,
625
+ },
626
+ {
627
+ "params": [p for n, p in opt_model.named_parameters() if (n not in decay_parameters and n in module_parameters and p.requires_grad)],
628
+ "weight_decay": 0.0,
629
+ "lr": lr,
630
+ },
631
+ ]
632
+ )
633
+ else:
634
+ optimizer_grouped_parameters = [
635
+ {
636
+ "params": [p for n, p in opt_model.named_parameters() if (n in decay_parameters and p.requires_grad)],
637
+ "weight_decay": self.args.weight_decay,
638
+ },
639
+ {
640
+ "params": [p for n, p in opt_model.named_parameters() if (n not in decay_parameters and p.requires_grad)],
641
+ "weight_decay": 0.0,
642
+ },
643
+ ]
644
+
645
+ optimizer_cls, optimizer_kwargs = Trainer.get_optimizer_cls_and_kwargs(self.args)
646
+
647
+ self.optimizer = optimizer_cls(optimizer_grouped_parameters, **optimizer_kwargs)
648
+ if optimizer_cls.__name__ == "Adam8bit":
649
+ import bitsandbytes
650
+
651
+ manager = bitsandbytes.optim.GlobalOptimManager.get_instance()
652
+
653
+ skipped = 0
654
+ for module in opt_model.modules():
655
+ if isinstance(module, nn.Embedding):
656
+ skipped += sum({p.data_ptr(): p.numel() for p in module.parameters()}.values())
657
+ logger.info(f"skipped {module}: {skipped/2**20}M params")
658
+ manager.register_module_override(module, "weight", {"optim_bits": 32})
659
+ logger.debug(f"bitsandbytes: will optimize {module} in fp32")
660
+ logger.info(f"skipped: {skipped/2**20}M params")
661
+
662
+ return self.optimizer
663
+
664
+ def _save_checkpoint(self, model, trial, metrics=None):
665
+ if should_only_save_mm_adapter(self.args):
666
+ from transformers.trainer_utils import PREFIX_CHECKPOINT_DIR
667
+
668
+ checkpoint_folder = f"{PREFIX_CHECKPOINT_DIR}-{self.state.global_step}"
669
+
670
+ run_dir = self._get_output_dir(trial=trial)
671
+ output_dir = os.path.join(run_dir, checkpoint_folder)
672
+
673
+ # Only save Adapter
674
+ keys_to_match = ["mm_projector", "vision_resampler"]
675
+ if getattr(self.args, "use_im_start_end", False):
676
+ keys_to_match.extend(["embed_tokens", "embed_in"])
677
+
678
+ weight_to_save = get_mm_adapter_state_maybe_zero_3(self.model.named_parameters(), keys_to_match)
679
+
680
+ if self.args.local_rank == 0 or self.args.local_rank == -1:
681
+ self.model.config.save_pretrained(output_dir)
682
+ torch.save(weight_to_save, os.path.join(output_dir, f"mm_projector.bin"))
683
+ else:
684
+ super(LLaVATrainer, self)._save_checkpoint(model, trial, metrics)
685
+
686
+ def _save(self, output_dir: Optional[str] = None, state_dict=None):
687
+ if should_only_save_mm_adapter(self.args):
688
+ pass
689
+ else:
690
+ super(LLaVATrainer, self)._save(output_dir, state_dict)
691
+
692
+ def _inner_training_loop(
693
+ self, batch_size=None, args=None, resume_from_checkpoint=None, trial=None, ignore_keys_for_eval=None
694
+ ):
695
+ if args is None:
696
+ args = self.args
697
+
698
+ # Start of existing training loop setup
699
+ self.accelerator.free_memory()
700
+ self._train_batch_size = batch_size
701
+ if self.args.auto_find_batch_size:
702
+ if self.state.train_batch_size != self._train_batch_size:
703
+ from accelerate.utils import release_memory
704
+
705
+ (self.model_wrapped,) = release_memory(self.model_wrapped)
706
+ self.model_wrapped = self.model
707
+
708
+ # Check for DeepSpeed *after* the initial pass and modify the config
709
+ if self.is_deepspeed_enabled:
710
+ # Temporarily unset `self.args.train_batch_size`
711
+ original_bs = self.args.per_device_train_batch_size
712
+ self.args.per_device_train_batch_size = self._train_batch_size // max(1, self.args.n_gpu)
713
+ self.propagate_args_to_deepspeed(True)
714
+ self.args.per_device_train_batch_size = original_bs
715
+ self.state.train_batch_size = self._train_batch_size
716
+ logger.debug(f"Currently training with a batch size of: {self._train_batch_size}")
717
+ # Data loader and number of training steps
718
+ train_dataloader = self.get_train_dataloader()
719
+ if self.is_fsdp_xla_v2_enabled:
720
+ train_dataloader = tpu_spmd_dataloader(train_dataloader)
721
+
722
+ # Setting up training control variables:
723
+ # number of training epochs: num_train_epochs
724
+ # number of training steps per epoch: num_update_steps_per_epoch
725
+ # total number of training steps to execute: max_steps
726
+ total_train_batch_size = self._train_batch_size * args.gradient_accumulation_steps * args.world_size
727
+
728
+ len_dataloader = None
729
+ num_train_tokens = None
730
+ if has_length(train_dataloader):
731
+ len_dataloader = len(train_dataloader)
732
+ num_update_steps_per_epoch = len_dataloader // args.gradient_accumulation_steps
733
+ num_update_steps_per_epoch = max(num_update_steps_per_epoch, 1)
734
+ num_examples = self.num_examples(train_dataloader)
735
+ if args.max_steps > 0:
736
+ max_steps = args.max_steps
737
+ num_train_epochs = args.max_steps // num_update_steps_per_epoch + int(
738
+ args.max_steps % num_update_steps_per_epoch > 0
739
+ )
740
+ # May be slightly incorrect if the last batch in the training dataloader has a smaller size but it's
741
+ # the best we can do.
742
+ num_train_samples = args.max_steps * total_train_batch_size
743
+ if args.include_tokens_per_second:
744
+ num_train_tokens = (
745
+ self.num_tokens(train_dataloader, args.max_steps) * args.gradient_accumulation_steps
746
+ )
747
+ else:
748
+ max_steps = math.ceil(args.num_train_epochs * num_update_steps_per_epoch)
749
+ num_train_epochs = math.ceil(args.num_train_epochs)
750
+ num_train_samples = self.num_examples(train_dataloader) * args.num_train_epochs
751
+ if args.include_tokens_per_second:
752
+ num_train_tokens = self.num_tokens(train_dataloader) * args.num_train_epochs
753
+ elif args.max_steps > 0: # Rely on max_steps when dataloader does not have a working size
754
+ max_steps = args.max_steps
755
+ # Setting a very large number of epochs so we go as many times as necessary over the iterator.
756
+ num_train_epochs = sys.maxsize
757
+ num_update_steps_per_epoch = max_steps
758
+ num_examples = total_train_batch_size * args.max_steps
759
+ num_train_samples = args.max_steps * total_train_batch_size
760
+ if args.include_tokens_per_second:
761
+ num_train_tokens = self.num_tokens(train_dataloader, args.max_steps) * args.gradient_accumulation_steps
762
+ else:
763
+ raise ValueError(
764
+ "args.max_steps must be set to a positive value if dataloader does not have a length, was"
765
+ f" {args.max_steps}"
766
+ )
767
+
768
+ if DebugOption.UNDERFLOW_OVERFLOW in self.args.debug:
769
+ if self.args.n_gpu > 1:
770
+ # nn.DataParallel(model) replicates the model, creating new variables and module
771
+ # references registered here no longer work on other gpus, breaking the module
772
+ raise ValueError(
773
+ "Currently --debug underflow_overflow is not supported under DP. Please use DDP"
774
+ " (torchrun or torch.distributed.launch (deprecated))."
775
+ )
776
+ else:
777
+ debug_overflow = DebugUnderflowOverflow(self.model) # noqa
778
+
779
+ delay_optimizer_creation = is_sagemaker_mp_enabled() or self.is_fsdp_xla_enabled or self.is_fsdp_enabled
780
+
781
+ # We need to reset the scheduler, as its parameters may be different on subsequent calls
782
+ if self._created_lr_scheduler:
783
+ self.lr_scheduler = None
784
+ self._created_lr_scheduler = False
785
+
786
+ if self.is_deepspeed_enabled:
787
+ ########################
788
+ # Changed Code
789
+ ########################
790
+ if self.trainer_mode == "zo":
791
+ # We need to set the optimizer to dummy optimizer for MeZO
792
+ self.optimizer = self.create_optimizer()
793
+ else:
794
+ self.optimizer, self.lr_scheduler = deepspeed_init(self, num_training_steps=max_steps)
795
+ ########################
796
+ # Changed Code
797
+ ########################
798
+
799
+ if not delay_optimizer_creation:
800
+ self.create_optimizer_and_scheduler(num_training_steps=max_steps)
801
+
802
+ self.state = TrainerState()
803
+ self.state.is_hyper_param_search = trial is not None
804
+ self.state.train_batch_size = self._train_batch_size
805
+
806
+ # Compute absolute values for logging, eval, and save if given as ratio
807
+ if args.logging_steps is not None:
808
+ if args.logging_steps < 1:
809
+ self.state.logging_steps = math.ceil(max_steps * args.logging_steps)
810
+ else:
811
+ self.state.logging_steps = args.logging_steps
812
+ if args.eval_steps is not None:
813
+ if args.eval_steps < 1:
814
+ self.state.eval_steps = math.ceil(max_steps * args.eval_steps)
815
+ else:
816
+ self.state.eval_steps = args.eval_steps
817
+ if args.save_steps is not None:
818
+ if args.save_steps < 1:
819
+ self.state.save_steps = math.ceil(max_steps * args.save_steps)
820
+ else:
821
+ self.state.save_steps = args.save_steps
822
+
823
+ # Activate gradient checkpointing if needed
824
+ if args.gradient_checkpointing:
825
+ if args.gradient_checkpointing_kwargs is None:
826
+ gradient_checkpointing_kwargs = {}
827
+ else:
828
+ gradient_checkpointing_kwargs = args.gradient_checkpointing_kwargs
829
+
830
+ self.model.gradient_checkpointing_enable(gradient_checkpointing_kwargs=gradient_checkpointing_kwargs)
831
+
832
+ model = self._wrap_model(self.model_wrapped)
833
+
834
+ # as the model is wrapped, don't use `accelerator.prepare`
835
+ # this is for unhandled cases such as
836
+ # FSDP-XLA, SageMaker MP/DP, DataParallel, IPEX
837
+ use_accelerator_prepare = True if model is self.model else False
838
+
839
+ if delay_optimizer_creation:
840
+ if use_accelerator_prepare:
841
+ self._fsdp_qlora_plugin_updates()
842
+ self.model = self.accelerator.prepare(self.model)
843
+ self.create_optimizer_and_scheduler(num_training_steps=max_steps)
844
+
845
+ # prepare using `accelerator` prepare
846
+ if use_accelerator_prepare:
847
+ self.model.train()
848
+ if hasattr(self.lr_scheduler, "step"):
849
+ if self.use_apex:
850
+ model = self.accelerator.prepare(self.model)
851
+ else:
852
+ model, self.optimizer = self.accelerator.prepare(self.model, self.optimizer)
853
+ else:
854
+ # to handle cases wherein we pass "DummyScheduler" such as when it is specified in DeepSpeed config.
855
+ model, self.optimizer, self.lr_scheduler = self.accelerator.prepare(
856
+ self.model, self.optimizer, self.lr_scheduler
857
+ )
858
+
859
+ if self.is_fsdp_enabled:
860
+ self.model = self.model_wrapped = model
861
+
862
+ # for the rest of this function `model` is the outside model, whether it was wrapped or not
863
+ if model is not self.model:
864
+ self.model_wrapped = model
865
+
866
+ # backward compatibility
867
+ if self.is_deepspeed_enabled:
868
+ self.deepspeed = self.model_wrapped
869
+
870
+ # ckpt loading
871
+ if resume_from_checkpoint is not None:
872
+ if self.is_deepspeed_enabled:
873
+ deepspeed_load_checkpoint(
874
+ self.model_wrapped, resume_from_checkpoint, load_module_strict=not _is_peft_model(self.model)
875
+ )
876
+ elif is_sagemaker_mp_enabled() or self.is_fsdp_enabled:
877
+ self._load_from_checkpoint(resume_from_checkpoint, self.model_wrapped)
878
+
879
+ # Check if saved optimizer or scheduler states exist
880
+ self._load_optimizer_and_scheduler(resume_from_checkpoint)
881
+
882
+ # important: at this point:
883
+ # self.model is the Transformers Model
884
+ # self.model_wrapped is DDP(Transformers Model), Deepspeed(Transformers Model),
885
+ # FSDP(Transformers Model), Dynamo Optimized Module(Transformers Model) etc.
886
+
887
+ # Train!
888
+ logger.info("***** Running training *****")
889
+ logger.info(f" Num examples = {num_examples:,}")
890
+ logger.info(f" Num Epochs = {num_train_epochs:,}")
891
+ logger.info(f" Instantaneous batch size per device = {self.args.per_device_train_batch_size:,}")
892
+ if self.args.per_device_train_batch_size != self._train_batch_size:
893
+ logger.info(f" Training with DataParallel so batch size has been adjusted to: {self._train_batch_size:,}")
894
+ logger.info(f" Total train batch size (w. parallel, distributed & accumulation) = {total_train_batch_size:,}")
895
+ logger.info(f" Gradient Accumulation steps = {args.gradient_accumulation_steps}")
896
+ logger.info(f" Total optimization steps = {max_steps:,}")
897
+ logger.info(f" Number of trainable parameters = {get_model_param_count(model, trainable_only=True):,}")
898
+
899
+ self.state.epoch = 0
900
+ start_time = time.time()
901
+ epochs_trained = 0
902
+ steps_trained_in_current_epoch = 0
903
+ steps_trained_progress_bar = None
904
+
905
+ # Check if continuing training from a checkpoint
906
+ if resume_from_checkpoint is not None and os.path.isfile(
907
+ os.path.join(resume_from_checkpoint, TRAINER_STATE_NAME)
908
+ ):
909
+ self.state = TrainerState.load_from_json(os.path.join(resume_from_checkpoint, TRAINER_STATE_NAME))
910
+ self.compare_trainer_and_checkpoint_args(self.args, self.state)
911
+ epochs_trained = self.state.global_step // num_update_steps_per_epoch
912
+ if not args.ignore_data_skip:
913
+ steps_trained_in_current_epoch = self.state.global_step % (num_update_steps_per_epoch)
914
+ steps_trained_in_current_epoch *= args.gradient_accumulation_steps
915
+ else:
916
+ steps_trained_in_current_epoch = 0
917
+
918
+ logger.info(" Continuing training from checkpoint, will skip to saved global_step")
919
+ logger.info(f" Continuing training from epoch {epochs_trained}")
920
+ logger.info(f" Continuing training from global step {self.state.global_step}")
921
+ if not args.ignore_data_skip:
922
+ logger.info(
923
+ f" Will skip the first {epochs_trained} epochs then the first"
924
+ f" {steps_trained_in_current_epoch} batches in the first epoch."
925
+ )
926
+
927
+ # Update the references
928
+ self.callback_handler.model = self.model
929
+ self.callback_handler.optimizer = self.optimizer
930
+ self.callback_handler.lr_scheduler = self.lr_scheduler
931
+ self.callback_handler.train_dataloader = train_dataloader
932
+ if self.hp_name is not None and self._trial is not None:
933
+ # use self._trial because the SigOpt/Optuna hpo only call `_hp_search_setup(trial)` instead of passing trial
934
+ # parameter to Train when using DDP.
935
+ self.state.trial_name = self.hp_name(self._trial)
936
+ if trial is not None:
937
+ assignments = trial.assignments if self.hp_search_backend == HPSearchBackend.SIGOPT else trial
938
+ self.state.trial_params = hp_params(assignments)
939
+ else:
940
+ self.state.trial_params = None
941
+ # This should be the same if the state has been saved but in case the training arguments changed, it's safer
942
+ # to set this after the load.
943
+ self.state.max_steps = max_steps
944
+ self.state.num_train_epochs = num_train_epochs
945
+ self.state.is_local_process_zero = self.is_local_process_zero()
946
+ self.state.is_world_process_zero = self.is_world_process_zero()
947
+
948
+ # tr_loss is a tensor to avoid synchronization of TPUs through .item()
949
+ tr_loss = torch.tensor(0.0).to(args.device)
950
+ # _total_loss_scalar is updated everytime .item() has to be called on tr_loss and stores the sum of all losses
951
+ self._total_loss_scalar = 0.0
952
+ self._globalstep_last_logged = self.state.global_step
953
+ model.zero_grad()
954
+ grad_norm: Optional[float] = None
955
+
956
+ self.control = self.callback_handler.on_train_begin(args, self.state, self.control)
957
+
958
+ # Skip the first epochs_trained epochs to get the random state of the dataloader at the right point.
959
+ if not args.ignore_data_skip:
960
+ for epoch in range(epochs_trained):
961
+ sampler = get_dataloader_sampler(train_dataloader)
962
+ sampler_kinds = [RandomSampler]
963
+ if version.parse(accelerate_version) > version.parse("0.23.0"):
964
+ sampler_kinds.append(SeedableRandomSampler)
965
+ is_random_sampler = isinstance(sampler, tuple(sampler_kinds))
966
+ if not is_random_sampler:
967
+ # We just need to begin an iteration to create the randomization of the sampler.
968
+ for _ in train_dataloader:
969
+ break
970
+ else:
971
+ # Otherwise we need to call the whooooole sampler cause there is some random operation added
972
+ # AT THE VERY END!
973
+ sampler = sampler if sampler is not None else []
974
+ _ = list(sampler)
975
+
976
+ total_batched_samples = 0
977
+ for epoch in range(epochs_trained, num_train_epochs):
978
+ epoch_iterator = train_dataloader
979
+ if hasattr(epoch_iterator, "set_epoch"):
980
+ epoch_iterator.set_epoch(epoch)
981
+
982
+ # Reset the past mems state at the beginning of each epoch if necessary.
983
+ if args.past_index >= 0:
984
+ self._past = None
985
+
986
+ steps_in_epoch = (
987
+ len(epoch_iterator)
988
+ if len_dataloader is not None
989
+ else args.max_steps * args.gradient_accumulation_steps
990
+ )
991
+ self.control = self.callback_handler.on_epoch_begin(args, self.state, self.control)
992
+
993
+ if epoch == epochs_trained and resume_from_checkpoint is not None and steps_trained_in_current_epoch == 0:
994
+ self._load_rng_state(resume_from_checkpoint)
995
+
996
+ rng_to_sync = False
997
+ steps_skipped = 0
998
+ if steps_trained_in_current_epoch > 0:
999
+ epoch_iterator = skip_first_batches(epoch_iterator, steps_trained_in_current_epoch)
1000
+ steps_skipped = steps_trained_in_current_epoch
1001
+ steps_trained_in_current_epoch = 0
1002
+ rng_to_sync = True
1003
+
1004
+ step = -1
1005
+ for step, inputs in enumerate(epoch_iterator):
1006
+ total_batched_samples += 1
1007
+
1008
+ if self.args.include_num_input_tokens_seen:
1009
+ main_input_name = getattr(self.model, "main_input_name", "input_ids")
1010
+ if main_input_name not in inputs:
1011
+ logger.warning(
1012
+ "Tried to track the number of tokens seen, however the current model is "
1013
+ "not configured properly to know what item is the input. To fix this, add "
1014
+ "a `main_input_name` attribute to the model class you are using."
1015
+ )
1016
+ else:
1017
+ input_device = inputs[main_input_name].device
1018
+ self.state.num_input_tokens_seen += torch.sum(
1019
+ self.accelerator.gather(
1020
+ torch.tensor(inputs[main_input_name].numel(), device=input_device, dtype=torch.int64)
1021
+ )
1022
+ ).item()
1023
+ if rng_to_sync:
1024
+ self._load_rng_state(resume_from_checkpoint)
1025
+ rng_to_sync = False
1026
+
1027
+ # Skip past any already trained steps if resuming training
1028
+ if steps_trained_in_current_epoch > 0:
1029
+ steps_trained_in_current_epoch -= 1
1030
+ if steps_trained_progress_bar is not None:
1031
+ steps_trained_progress_bar.update(1)
1032
+ if steps_trained_in_current_epoch == 0:
1033
+ self._load_rng_state(resume_from_checkpoint)
1034
+ continue
1035
+ elif steps_trained_progress_bar is not None:
1036
+ steps_trained_progress_bar.close()
1037
+ steps_trained_progress_bar = None
1038
+
1039
+ if step % args.gradient_accumulation_steps == 0:
1040
+ self.control = self.callback_handler.on_step_begin(args, self.state, self.control)
1041
+
1042
+ ########################
1043
+ # MeZO Integration
1044
+ ########################
1045
+ if self.trainer_mode == "zo":
1046
+ # Perform MeZO step
1047
+ tr_loss_step = self.zo_step(model, inputs)
1048
+ else:
1049
+ # Regular training step with gradient accumulation
1050
+ with self.accelerator.accumulate(model):
1051
+ tr_loss_step = self.training_step(model, inputs)
1052
+ print(f"Step {step} loss: {tr_loss_step}")
1053
+
1054
+ torch.cuda.empty_cache() # Releasing reserved memory seems not to work correctly, so do it manually
1055
+ ########################
1056
+ # End of MeZO Integration
1057
+ ########################
1058
+
1059
+ # Accumulate loss
1060
+ if (
1061
+ args.logging_nan_inf_filter
1062
+ and not is_torch_xla_available()
1063
+ and (torch.isnan(tr_loss_step) or torch.isinf(tr_loss_step))
1064
+ ):
1065
+ # if loss is nan or inf simply add the average of previous logged losses
1066
+ tr_loss += tr_loss / (1 + self.state.global_step - self._globalstep_last_logged)
1067
+ else:
1068
+ if tr_loss.device != tr_loss_step.device:
1069
+ raise ValueError(
1070
+ f"Calculated loss must be on the original device: {tr_loss.device} but device in use is {tr_loss_step.device}"
1071
+ )
1072
+ tr_loss += tr_loss_step
1073
+
1074
+ self.current_flos += float(self.floating_point_ops(inputs))
1075
+
1076
+ is_last_step_and_steps_less_than_grad_acc = (
1077
+ steps_in_epoch <= args.gradient_accumulation_steps and (step + 1) == steps_in_epoch
1078
+ )
1079
+
1080
+ if (
1081
+ total_batched_samples % args.gradient_accumulation_steps == 0
1082
+ or
1083
+ # last step in epoch but step is always smaller than gradient_accumulation_steps
1084
+ is_last_step_and_steps_less_than_grad_acc
1085
+ ):
1086
+ ########################
1087
+ # MeZO Integration
1088
+ ########################
1089
+ if self.trainer_mode == "zo":
1090
+ self.zo_update(learning_rate=self._get_learning_rate())
1091
+ self.lr_scheduler.step()
1092
+ ########################
1093
+ # End of MeZO Integration
1094
+ ########################
1095
+ else:
1096
+ # the `or` condition of `is_last_step_and_steps_less_than_grad_acc` is not covered
1097
+ # in accelerate. So, explicitly enable sync gradients to True in that case.
1098
+ if is_last_step_and_steps_less_than_grad_acc:
1099
+ self.accelerator.gradient_state._set_sync_gradients(True)
1100
+
1101
+ # Gradient clipping
1102
+ if args.max_grad_norm is not None and args.max_grad_norm > 0:
1103
+ # deepspeed does its own clipping
1104
+
1105
+ if is_sagemaker_mp_enabled() and args.fp16:
1106
+ _grad_norm = self.optimizer.clip_master_grads(args.max_grad_norm)
1107
+ elif self.use_apex:
1108
+ # Revert to normal clipping otherwise, handling Apex or full precision
1109
+ _grad_norm = nn.utils.clip_grad_norm_(
1110
+ amp.master_params(self.optimizer),
1111
+ args.max_grad_norm,
1112
+ )
1113
+ else:
1114
+ _grad_norm = self.accelerator.clip_grad_norm_(
1115
+ model.parameters(),
1116
+ args.max_grad_norm,
1117
+ )
1118
+
1119
+ if (
1120
+ is_accelerate_available()
1121
+ and self.accelerator.distributed_type == DistributedType.DEEPSPEED
1122
+ ):
1123
+ grad_norm = model.get_global_grad_norm()
1124
+ # In some cases the grad norm may not return a float
1125
+ if hasattr(grad_norm, "item"):
1126
+ grad_norm = grad_norm.item()
1127
+ else:
1128
+ grad_norm = _grad_norm
1129
+
1130
+ # Optimizer step
1131
+ self.optimizer.step()
1132
+ optimizer_was_run = not self.accelerator.optimizer_step_was_skipped
1133
+ if optimizer_was_run:
1134
+ # Delay optimizer scheduling until metrics are generated
1135
+ if not isinstance(self.lr_scheduler, torch.optim.lr_scheduler.ReduceLROnPlateau):
1136
+ self.lr_scheduler.step()
1137
+
1138
+ model.zero_grad()
1139
+
1140
+ self.state.global_step += 1
1141
+ self.state.epoch = epoch + (step + 1 + steps_skipped) / steps_in_epoch
1142
+ self.control = self.callback_handler.on_step_end(args, self.state, self.control)
1143
+
1144
+ self._maybe_log_save_evaluate(tr_loss, grad_norm, model, trial, epoch, ignore_keys_for_eval)
1145
+ else:
1146
+ self.control = self.callback_handler.on_substep_end(args, self.state, self.control)
1147
+
1148
+ if self.control.should_epoch_stop or self.control.should_training_stop:
1149
+ # PyTorch/XLA relies on the data loader to insert the mark_step for
1150
+ # each step. Since we are breaking the loop early, we need to manually
1151
+ # insert the mark_step here.
1152
+ if is_torch_xla_available():
1153
+ xm.mark_step()
1154
+ break
1155
+
1156
+ if step < 0:
1157
+ logger.warning(
1158
+ "There seems to be not a single sample in your epoch_iterator, stopping training at step"
1159
+ f" {self.state.global_step}! This is expected if you're using an IterableDataset and set"
1160
+ f" num_steps ({max_steps}) higher than the number of available samples."
1161
+ )
1162
+ self.control.should_training_stop = True
1163
+
1164
+ self.control = self.callback_handler.on_epoch_end(args, self.state, self.control)
1165
+ self._maybe_log_save_evaluate(tr_loss, grad_norm, model, trial, epoch, ignore_keys_for_eval)
1166
+
1167
+ if DebugOption.TPU_METRICS_DEBUG in self.args.debug:
1168
+ if is_torch_xla_available():
1169
+ # tpu-comment: Logging debug metrics for PyTorch/XLA (compile, execute times, ops, etc.)
1170
+ xm.master_print(met.metrics_report())
1171
+ else:
1172
+ logger.warning(
1173
+ "You enabled PyTorch/XLA debug metrics but you don't have a TPU "
1174
+ "configured. Check your training configuration if this is unexpected."
1175
+ )
1176
+ if self.control.should_training_stop:
1177
+ break
1178
+
1179
+ if args.past_index and hasattr(self, "_past"):
1180
+ # Clean the state at the end of training
1181
+ delattr(self, "_past")
1182
+
1183
+ logger.info("\n\nTraining completed. Do not forget to share your model on huggingface.co/models =)\n\n")
1184
+ if args.load_best_model_at_end and self.state.best_model_checkpoint is not None:
1185
+ # Wait for everyone to get here so we are sure the model has been saved by process 0.
1186
+ if is_torch_xla_available():
1187
+ xm.rendezvous("load_best_model_at_end")
1188
+ elif args.parallel_mode == ParallelMode.DISTRIBUTED:
1189
+ dist.barrier()
1190
+ elif is_sagemaker_mp_enabled():
1191
+ smp.barrier()
1192
+
1193
+ self._load_best_model()
1194
+
1195
+ # add remaining tr_loss
1196
+ self._total_loss_scalar += tr_loss.item()
1197
+ effective_global_step = max(self.state.global_step, 0.001) # Avoid ZeroDivisionError
1198
+ train_loss = self._total_loss_scalar / effective_global_step
1199
+
1200
+ metrics = speed_metrics(
1201
+ "train",
1202
+ start_time,
1203
+ num_samples=num_train_samples,
1204
+ num_steps=self.state.max_steps,
1205
+ num_tokens=num_train_tokens,
1206
+ )
1207
+ self.store_flos()
1208
+ metrics["total_flos"] = self.state.total_flos
1209
+ metrics["train_loss"] = train_loss
1210
+
1211
+ self.is_in_train = False
1212
+
1213
+ self._memory_tracker.stop_and_update_metrics(metrics)
1214
+
1215
+ self.log(metrics)
1216
+
1217
+ run_dir = self._get_output_dir(trial)
1218
+ checkpoints_sorted = self._sorted_checkpoints(use_mtime=False, output_dir=run_dir)
1219
+
1220
+ # Delete the last checkpoint when save_total_limit=1 if it's different from the best checkpoint and process allowed to save.
1221
+ if self.args.should_save and self.state.best_model_checkpoint is not None and self.args.save_total_limit == 1:
1222
+ for checkpoint in checkpoints_sorted:
1223
+ if not os.path.samefile(checkpoint, self.state.best_model_checkpoint):
1224
+ logger.info(f"Deleting older checkpoint [{checkpoint}] due to args.save_total_limit")
1225
+ shutil.rmtree(checkpoint)
1226
+
1227
+ self.control = self.callback_handler.on_train_end(args, self.state, self.control)
1228
+
1229
+ # Wait for the checkpoint to be uploaded.
1230
+ self._finish_current_push()
1231
+
1232
+ # After training we make sure to retrieve back the original forward pass method
1233
+ # for the embedding layer by removing the forward post hook.
1234
+ if self.neftune_noise_alpha is not None:
1235
+ self._deactivate_neftune(self.model)
1236
+
1237
+ plot_graphs_based_on_log_history(
1238
+ log_history=self.state.log_history,
1239
+ output_dir=run_dir,
1240
+ metrics=["train_loss"],
1241
+ )
1242
+
1243
+ return TrainOutput(self.state.global_step, train_loss, metrics)
1244
+
1245
+
1246
+ class LLaVADPOTrainer(DPOTrainer):
1247
+ def _get_train_sampler(self) -> Optional[torch.utils.data.Sampler]:
1248
+ if self.train_dataset is None or not has_length(self.train_dataset):
1249
+ return None
1250
+
1251
+ if self.args.group_by_modality_length:
1252
+ lengths = self.train_dataset.modality_lengths
1253
+ return LengthGroupedSampler(
1254
+ # self.args.train_batch_size * self.args.gradient_accumulation_steps, # TODO: seems that we should not have gradient_accumulation_steps
1255
+ self.args.train_batch_size,
1256
+ world_size=self.args.world_size,
1257
+ lengths=lengths,
1258
+ group_by_modality=True,
1259
+ )
1260
+ else:
1261
+ return super()._get_train_sampler()
1262
+
1263
+ def _save_checkpoint(self, model, trial, metrics=None):
1264
+ if should_only_save_mm_adapter(self.args):
1265
+ from transformers.trainer_utils import PREFIX_CHECKPOINT_DIR
1266
+
1267
+ checkpoint_folder = f"{PREFIX_CHECKPOINT_DIR}-{self.state.global_step}"
1268
+
1269
+ run_dir = self._get_output_dir(trial=trial)
1270
+ output_dir = os.path.join(run_dir, checkpoint_folder)
1271
+
1272
+ # Only save Adapter
1273
+ keys_to_match = ["mm_projector", "vision_resampler"]
1274
+ if getattr(self.args, "use_im_start_end", False):
1275
+ keys_to_match.extend(["embed_tokens", "embed_in"])
1276
+
1277
+ weight_to_save = get_mm_adapter_state_maybe_zero_3(self.model.named_parameters(), keys_to_match)
1278
+
1279
+ if self.args.local_rank == 0 or self.args.local_rank == -1:
1280
+ self.model.config.save_pretrained(output_dir)
1281
+ torch.save(weight_to_save, os.path.join(output_dir, f"mm_projector.bin"))
1282
+ else:
1283
+ # super(LLaVADPOTrainer, self)._save_checkpoint(model, trial, metrics)
1284
+ # print(type(model))
1285
+ # from transformers.modeling_utils import unwrap_model
1286
+ # print(type(unwrap_model(model)))
1287
+ # print(unwrap_model(model).config)
1288
+ if self.args.lora_enable:
1289
+ from transformers.trainer_utils import PREFIX_CHECKPOINT_DIR
1290
+
1291
+ checkpoint_folder = f"{PREFIX_CHECKPOINT_DIR}-{self.state.global_step}"
1292
+ run_dir = self._get_output_dir(trial=trial)
1293
+ output_dir = os.path.join(run_dir, checkpoint_folder)
1294
+ from transformers.modeling_utils import unwrap_model
1295
+
1296
+ unwrapped_model = unwrap_model(model)
1297
+ self.save_my_lora_ckpt(output_dir, self.args, unwrapped_model)
1298
+ else:
1299
+ super(LLaVADPOTrainer, self)._save_checkpoint(model, trial, metrics)
1300
+
1301
+ def _save(self, output_dir: Optional[str] = None, state_dict=None):
1302
+ if should_only_save_mm_adapter(self.args):
1303
+ pass
1304
+ else:
1305
+ super(LLaVADPOTrainer, self)._save(output_dir, state_dict)
之前的代码版本/第一版-全部代码/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/llava/train/llava_trainer_eval.py ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import subprocess
3
+
4
+ from llava.train.llava_trainer import LLaVATrainer
5
+
6
+
7
+ class LLaVAEvalTrainer(LLaVATrainer):
8
+ def evaluate(self, evaluate_args):
9
+ cmd = f"accelerate launch --num_processes {evaluate_args.eval_num_processes} -m lmms_eval \
10
+ --model {evaluate_args.model} \
11
+ --model_args {evaluate_args.model_args} \
12
+ --tasks {evaluate_args.task_names} \
13
+ --batch_size {evaluate_args.batch_size} \
14
+ --log_samples_suffix {evaluate_args.log_samples_suffix} \
15
+ --output_path {evaluate_args.output_path}"
16
+ if evaluate_args.limit:
17
+ cmd += f" --limit {evaluate_args.limit}"
18
+ if evaluate_args.num_fewshot:
19
+ cmd += f" --num_fewshot {evaluate_args.num_fewshot}"
20
+ if evaluate_args.gen_kwargs != "":
21
+ cmd += f" --gen_kwargs {evaluate_args.gen_kwargs}"
22
+ if evaluate_args.log_samples:
23
+ cmd += f" --log_samples"
24
+ else:
25
+ assert False, "Please log samples so that the result can be parsed"
26
+ results = subprocess.run([cmd], shell=True, capture_output=True, text=True)
27
+ try:
28
+ result_file_index_start = results.stdout.index("Saved samples to ")
29
+ result_file_index_end = results.stdout.index(f".json")
30
+ result_file_index_start += len("Saved samples to ")
31
+ file = results.stdout[result_file_index_start:result_file_index_end]
32
+ except:
33
+ result_file_index_start = results.stderr.index("Saved samples to ")
34
+ result_file_index_end = results.stderr.index(f".json")
35
+ result_file_index_start += len("Saved samples to ")
36
+ file = results.stderr[result_file_index_start:result_file_index_end]
37
+ file = file.split("/")[:-1]
38
+ file = "/".join(file) + "/results.json"
39
+ with open(file, "r") as f:
40
+ lmms_eval_results = json.load(f)
41
+ result_dict = {}
42
+ tasks_list = evaluate_args.task_names.split(",")
43
+ for task in tasks_list:
44
+ task_results = lmms_eval_results["results"][task]
45
+ for k, v in task_results.items():
46
+ if k != "alias" and "stderr" not in k:
47
+ metric = k.split(",")[0]
48
+ result_dict[f"{task}_{metric}"] = v
49
+ return result_dict
50
+
51
+ """def evaluate(self, evaluate_args):
52
+ initialize_tasks()
53
+ tasks_list = evaluate_args.task_names.split(",")
54
+ result_dict = {}
55
+ results = evaluator.simple_evaluate(
56
+ model=evaluate_args.model,
57
+ model_args=evaluate_args.model_args,
58
+ tasks=tasks_list,
59
+ num_fewshot=evaluate_args.num_fewshot,
60
+ batch_size=evaluate_args.batch_size,
61
+ device=evaluate_args.device,
62
+ limit=evaluate_args.limit,
63
+ check_integrity=evaluate_args.check_integrity,
64
+ show_task_to_terminal=evaluate_args.show_task_to_terminal,
65
+ log_samples=evaluate_args.log_samples,
66
+ gen_kwargs=evaluate_args.gen_kwargs,
67
+ cli_args=evaluate_args,
68
+ )
69
+ for task in tasks_list:
70
+ task_results = results["results"][task]
71
+ for k,v in task_results.items():
72
+ if k != "alias" and "stderr" not in k:
73
+ metric = k.split(",")[0]
74
+ result_dict[f"{task}_{metric}"] = v
75
+
76
+ return result_dict"""
之前的代码版本/第一版-全部代码/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/llava/train/train.py ADDED
@@ -0,0 +1,1770 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Adopted from https://github.com/lm-sys/FastChat. Below is the original copyright:
2
+ # Adopted from tatsu-lab@stanford_alpaca. Below is the original copyright:
3
+ # Copyright 2023 Rohan Taori, Ishaan Gulrajani, Tianyi Zhang, Yann Dubois, Xuechen Li
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+
17
+ import ast
18
+ import os
19
+ import copy
20
+ from dataclasses import dataclass, field
21
+ import json
22
+ import logging
23
+ import pathlib
24
+ from typing import Dict, Optional, Sequence, List
25
+ from PIL import Image, ImageFile
26
+ from packaging import version
27
+ import numpy as np
28
+
29
+ import time
30
+ import random
31
+ import yaml
32
+ import math
33
+ import re
34
+ import torch
35
+
36
+ import transformers
37
+ import tokenizers
38
+ import deepspeed
39
+
40
+ from transformers import AutoConfig
41
+ from torch.utils.data import Dataset
42
+ from llava.constants import IGNORE_INDEX, DEFAULT_IMAGE_TOKEN, DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN, IMAGE_TOKEN_INDEX
43
+ from llava.train.llava_trainer import LLaVATrainer
44
+
45
+ from llava import conversation as conversation_lib
46
+ from llava.model import *
47
+ from llava.mm_utils import process_highres_image, process_anyres_image, process_highres_image_crop_split, tokenizer_image_token
48
+ from llava.utils import rank0_print, process_video_with_pyav, process_video_with_decord
49
+
50
+ torch.multiprocessing.set_sharing_strategy("file_system")
51
+
52
+ ImageFile.LOAD_TRUNCATED_IMAGES = True
53
+ local_rank = None
54
+
55
+ IS_TOKENIZER_GREATER_THAN_0_14 = version.parse(tokenizers.__version__) >= version.parse("0.14")
56
+
57
+
58
+ @dataclass
59
+ class ModelArguments:
60
+ model_name_or_path: Optional[str] = field(default="facebook/opt-125m")
61
+ model_class_name: Optional[str] = field(default=None, metadata={"help": "Used to init model class, format is XXXXForCausalLM. e.g. currently XXXX is chosen from LlavaLlama, LlavaMixtral, LlavaMistral, Llama"})
62
+
63
+ mm_tunable_parts: Optional[str] = field(
64
+ default=None, metadata={"help": 'Could be "mm_mlp_adapter", "mm_vision_resampler", "mm_vision_tower,mm_mlp_adapter,mm_language_model", "mm_vision_tower,mm_mlp_adapter,mm_language_model", "mm_mlp_adapter,mm_language_model"'}
65
+ )
66
+ # deciding which part of the multimodal model to tune, will overwrite other previous settings
67
+
68
+ version: Optional[str] = field(default="v0")
69
+ freeze_backbone: bool = field(default=False)
70
+ tune_mm_mlp_adapter: bool = field(default=False)
71
+ tune_mm_vision_resampler: bool = field(default=False)
72
+ vision_tower: Optional[str] = field(default=None)
73
+ vision_tower_pretrained: Optional[str] = field(default=None) # default to the last layer
74
+
75
+ unfreeze_mm_vision_tower: bool = field(default=False)
76
+ unfreeze_language_model: bool = field(default=False)
77
+ mm_vision_select_layer: Optional[int] = field(default=-1) # default to the last layer
78
+ pretrain_mm_mlp_adapter: Optional[str] = field(default=None)
79
+ mm_projector_type: Optional[str] = field(default="linear")
80
+ mm_use_im_start_end: bool = field(default=False)
81
+ mm_use_im_patch_token: bool = field(default=True)
82
+ mm_patch_merge_type: Optional[str] = field(default="flat")
83
+ mm_vision_select_feature: Optional[str] = field(default="patch")
84
+ mm_resampler_type: Optional[str] = field(default=None)
85
+ mm_mask_drop_mode: str = field(default="fixed")
86
+ mm_mask_drop_skip_percentage: float = field(default=0.0)
87
+ mm_mask_drop_ratio: float = field(default=0.25)
88
+ mm_mask_drop_ratio_upper: Optional[float] = field(default=None)
89
+ mm_mask_drop_ratio_lower: Optional[float] = field(default=None)
90
+ mm_spatial_pool_stride: Optional[int] = field(default=None)
91
+ mm_spatial_pool_mode: str = field(default="bilinear")
92
+ mm_spatial_pool_out_channels: Optional[int] = field(default=None)
93
+ mm_perceiver_depth: Optional[int] = field(default=3)
94
+ mm_perceiver_latents: Optional[int] = field(default=32)
95
+ mm_perceiver_ff_mult: Optional[float] = field(default=4)
96
+ mm_perceiver_pretrained: Optional[str] = field(default=None)
97
+ mm_qformer_depth: Optional[int] = field(default=3)
98
+ mm_qformer_latents: Optional[int] = field(default=32)
99
+ mm_qformer_pretrained: Optional[str] = field(default=None)
100
+
101
+ rope_scaling_factor: Optional[float] = field(default=None)
102
+ rope_scaling_type: Optional[str] = field(default=None)
103
+
104
+ s2: Optional[bool] = field(default=False)
105
+ s2_scales: Optional[str] = field(default="336,672,1008")
106
+
107
+ use_pos_skipping: Optional[bool] = field(default=False)
108
+ pos_skipping_range: Optional[int] = field(default=4096)
109
+
110
+
111
+ mm_newline_position: Optional[str] = field(default="grid")
112
+ delay_load: Optional[bool] = field(default=True)
113
+ add_faster_video: Optional[bool] = field(default=False)
114
+ faster_token_stride: Optional[int] = field(default=10)
115
+
116
+
117
+
118
+ @dataclass
119
+ class DataArguments:
120
+ data_path: str = field(default=None, metadata={"help": "Path to the training data, in llava's instruction.json format. Supporting multiple json files via /path/to/{a,b,c}.json"})
121
+ lazy_preprocess: bool = False
122
+ is_multimodal: bool = False
123
+ early_mix_text: bool = False
124
+ image_folder: Optional[str] = field(default=None)
125
+ image_aspect_ratio: str = "square"
126
+ image_grid_pinpoints: Optional[str] = field(default=None)
127
+ image_crop_resolution: Optional[int] = field(default=None)
128
+ image_split_resolution: Optional[int] = field(default=None)
129
+
130
+ video_folder: Optional[str] = field(default=None)
131
+ video_fps: Optional[int] = field(default=1)
132
+ frames_upbound: Optional[int] = field(default=0)
133
+ add_time_instruction: Optional[bool] = field(default=False)
134
+ force_sample: Optional[bool] = field(default=False)
135
+
136
+
137
+ @dataclass
138
+ class TrainingArguments(transformers.TrainingArguments):
139
+ cache_dir: Optional[str] = field(default=None)
140
+ optim: str = field(default="adamw_torch")
141
+ remove_unused_columns: bool = field(default=False)
142
+ freeze_mm_mlp_adapter: bool = field(default=False)
143
+ freeze_mm_vision_resampler: bool = field(default=False)
144
+ mpt_attn_impl: Optional[str] = field(default="triton")
145
+ model_max_length: int = field(
146
+ default=4096,
147
+ metadata={"help": "Maximum sequence length. Sequences will be right padded (and possibly truncated)."},
148
+ )
149
+ double_quant: bool = field(default=True, metadata={"help": "Compress the quantization statistics through double quantization."})
150
+ quant_type: str = field(default="nf4", metadata={"help": "Quantization data type to use. Should be one of `fp4` or `nf4`."})
151
+ bits: int = field(default=16, metadata={"help": "How many bits to use."})
152
+ lora_enable: bool = False
153
+ lora_r: int = 64
154
+ lora_alpha: int = 16
155
+ lora_dropout: float = 0.05
156
+ lora_weight_path: str = ""
157
+ lora_bias: str = "none"
158
+ mm_projector_lr: Optional[float] = None
159
+ mm_vision_tower_lr: Optional[float] = None
160
+ group_by_varlen: bool = field(default=False)
161
+ group_by_modality_length: bool = field(default=False)
162
+ group_by_modality_length_auto: bool = field(default=False)
163
+ auto_find_batch_size: bool = field(default=False)
164
+ gradient_checkpointing: bool = field(default=True)
165
+ verbose_logging: bool = field(default=False)
166
+ attn_implementation: str = field(default="flash_attention_2", metadata={"help": "Use transformers attention implementation."})
167
+ trainer_mode: str = field(default="regular", metadata={"help": "Mode of training (`regular`, `zo`)."})
168
+ zo_eps: float = field(default=1e-3, metadata={"help": "MeZO hyperparameter epsilon."})
169
+ zo_num_directions: int = field(default=1, metadata={"help": "Number of directions for MeZO."})
170
+
171
+
172
+ # @dataclass
173
+ # class EvaluationArguments:
174
+ # eval_num_processes: int = field(default=1)
175
+ # task_names: str = field(default=None)
176
+ # model: str = field(default="llava")
177
+ # model_args: Optional[str] = field(default=None)
178
+ # num_fewshot: Optional[int] = field(default=None)
179
+ # batch_size: int = field(default=1)
180
+ # device: Optional[str] = field(default=None)
181
+ # limit: Optional[int] = field(default=None)
182
+ # check_integrity: Optional[bool] = field(default=False)
183
+ # show_task_to_terminal: Optional[bool] = field(default=False)
184
+ # log_samples: Optional[bool] = field(default=True)
185
+ # gen_kwargs: Optional[str] = field(default="")
186
+ # log_samples_suffix: Optional[str] = field(default="")
187
+ # output_path: Optional[str] = field(default="./logs/")
188
+
189
+
190
+ def maybe_zero_3(param, ignore_status=False, name=None):
191
+ from deepspeed import zero
192
+ from deepspeed.runtime.zero.partition_parameters import ZeroParamStatus
193
+
194
+ if hasattr(param, "ds_id"):
195
+ if param.ds_status == ZeroParamStatus.NOT_AVAILABLE:
196
+ if not ignore_status:
197
+ logging.warning(f"{name}: param.ds_status != ZeroParamStatus.NOT_AVAILABLE: {param.ds_status}")
198
+ with zero.GatheredParameters([param]):
199
+ param = param.data.detach().cpu().clone()
200
+ else:
201
+ param = param.detach().cpu().clone()
202
+ return param
203
+
204
+
205
+ # Borrowed from peft.utils.get_peft_model_state_dict
206
+ def get_peft_state_maybe_zero_3(named_params, bias):
207
+ if bias == "none":
208
+ to_return = {k: t for k, t in named_params if "lora_" in k}
209
+ elif bias == "all":
210
+ to_return = {k: t for k, t in named_params if "lora_" in k or "bias" in k}
211
+ elif bias == "lora_only":
212
+ to_return = {}
213
+ maybe_lora_bias = {}
214
+ lora_bias_names = set()
215
+ for k, t in named_params:
216
+ if "lora_" in k:
217
+ to_return[k] = t
218
+ bias_name = k.split("lora_")[0] + "bias"
219
+ lora_bias_names.add(bias_name)
220
+ elif "bias" in k:
221
+ maybe_lora_bias[k] = t
222
+ for k, t in maybe_lora_bias:
223
+ if bias_name in lora_bias_names:
224
+ to_return[bias_name] = t
225
+ else:
226
+ raise NotImplementedError
227
+ to_return = {k: maybe_zero_3(v, ignore_status=True) for k, v in to_return.items()}
228
+ return to_return
229
+
230
+
231
+ def get_peft_state_non_lora_maybe_zero_3(named_params, require_grad_only=True):
232
+ to_return = {k: t for k, t in named_params if "lora_" not in k}
233
+ if require_grad_only:
234
+ to_return = {k: t for k, t in to_return.items() if t.requires_grad}
235
+ to_return = {k: maybe_zero_3(v, ignore_status=True).cpu() for k, v in to_return.items()}
236
+ return to_return
237
+
238
+
239
+ def get_mm_adapter_state_maybe_zero_3(named_params, keys_to_match):
240
+ to_return = {k: t for k, t in named_params if any(key_match in k for key_match in keys_to_match)}
241
+ to_return = {k: maybe_zero_3(v, ignore_status=True).cpu() for k, v in to_return.items()}
242
+ return to_return
243
+
244
+
245
+ def find_all_linear_names(model):
246
+ cls = torch.nn.Linear
247
+ lora_module_names = set()
248
+ multimodal_keywords = ["mm_projector", "vision_tower", "vision_resampler"]
249
+ for name, module in model.named_modules():
250
+ if any(mm_keyword in name for mm_keyword in multimodal_keywords):
251
+ continue
252
+ if isinstance(module, cls):
253
+ names = name.split(".")
254
+ lora_module_names.add(names[0] if len(names) == 1 else names[-1])
255
+
256
+ if "lm_head" in lora_module_names: # needed for 16-bit
257
+ lora_module_names.remove("lm_head")
258
+ return list(lora_module_names)
259
+
260
+
261
+ def safe_save_model_for_hf_trainer(trainer: transformers.Trainer, output_dir: str):
262
+ """Collects the state dict and dump to disk."""
263
+ if hasattr(trainer.args, "tune_mm_mlp_adapter") and trainer.args.tune_mm_mlp_adapter:
264
+ check_only_save_mm_adapter_tunnable = True
265
+ # only has mm_mlp_adapter and mm_vision_resampler in the tuneable parts
266
+ elif hasattr(trainer.args, "mm_tunable_parts") and (len(trainer.args.mm_tunable_parts.split(",")) == 1 and ("mm_mlp_adapter" in trainer.args.mm_tunable_parts or "mm_vision_resampler" in trainer.args.mm_tunable_parts)):
267
+ check_only_save_mm_adapter_tunnable = True
268
+ else:
269
+ check_only_save_mm_adapter_tunnable = False
270
+
271
+ trainer.accelerator.wait_for_everyone()
272
+ torch.cuda.synchronize()
273
+ rank0_print(f"Only save projectors: {check_only_save_mm_adapter_tunnable}")
274
+ if check_only_save_mm_adapter_tunnable:
275
+ # Only save Adapter
276
+ keys_to_match = ["mm_projector", "vision_resampler"]
277
+ if getattr(trainer.args, "use_im_start_end", False):
278
+ keys_to_match.extend(["embed_tokens", "embed_in"])
279
+
280
+ weight_to_save = get_mm_adapter_state_maybe_zero_3(trainer.model.named_parameters(), keys_to_match)
281
+ trainer.model.config.save_pretrained(output_dir)
282
+
283
+ current_folder = output_dir.split("/")[-1]
284
+ parent_folder = os.path.dirname(output_dir)
285
+ if trainer.args.local_rank == 0 or trainer.args.local_rank == -1:
286
+ if current_folder.startswith("checkpoint-"):
287
+ mm_projector_folder = os.path.join(parent_folder, "mm_projector")
288
+ os.makedirs(mm_projector_folder, exist_ok=True)
289
+ torch.save(weight_to_save, os.path.join(mm_projector_folder, f"{current_folder}.bin"))
290
+ else:
291
+ torch.save(weight_to_save, os.path.join(output_dir, f"mm_projector.bin"))
292
+ return
293
+
294
+ if trainer.deepspeed:
295
+ trainer.save_model(output_dir)
296
+ return
297
+
298
+ state_dict = trainer.model.state_dict()
299
+ if trainer.args.should_save:
300
+ cpu_state_dict = {key: value.cpu() for key, value in state_dict.items()}
301
+ del state_dict
302
+ trainer._save(output_dir, state_dict=cpu_state_dict) # noqa
303
+
304
+
305
+ def smart_tokenizer_and_embedding_resize(
306
+ special_tokens_dict: Dict,
307
+ tokenizer: transformers.PreTrainedTokenizer,
308
+ model: transformers.PreTrainedModel,
309
+ ):
310
+ """Resize tokenizer and embedding.
311
+
312
+ Note: This is the unoptimized version that may make your embedding size not be divisible by 64.
313
+ """
314
+ num_new_tokens = tokenizer.add_special_tokens(special_tokens_dict)
315
+ model.resize_token_embeddings(len(tokenizer))
316
+
317
+ if num_new_tokens > 0:
318
+ input_embeddings = model.get_input_embeddings().weight.data
319
+ output_embeddings = model.get_output_embeddings().weight.data
320
+
321
+ input_embeddings_avg = input_embeddings[:-num_new_tokens].mean(dim=0, keepdim=True)
322
+ output_embeddings_avg = output_embeddings[:-num_new_tokens].mean(dim=0, keepdim=True)
323
+
324
+ input_embeddings[-num_new_tokens:] = input_embeddings_avg
325
+ output_embeddings[-num_new_tokens:] = output_embeddings_avg
326
+
327
+
328
+ def _tokenize_fn(strings: Sequence[str], tokenizer: transformers.PreTrainedTokenizer) -> Dict:
329
+ """Tokenize a list of strings."""
330
+ tokenized_list = [
331
+ tokenizer(
332
+ text,
333
+ return_tensors="pt",
334
+ padding="longest",
335
+ max_length=tokenizer.model_max_length,
336
+ truncation=True,
337
+ )
338
+ for text in strings
339
+ ]
340
+ input_ids = labels = [tokenized.input_ids[0] for tokenized in tokenized_list]
341
+ input_ids_lens = labels_lens = [tokenized.input_ids.ne(tokenizer.pad_token_id).sum().item() for tokenized in tokenized_list]
342
+ return dict(
343
+ input_ids=input_ids,
344
+ labels=labels,
345
+ input_ids_lens=input_ids_lens,
346
+ labels_lens=labels_lens,
347
+ )
348
+
349
+
350
+ def _mask_targets(target, tokenized_lens, speakers):
351
+ # cur_idx = 0
352
+ cur_idx = tokenized_lens[0]
353
+ tokenized_lens = tokenized_lens[1:]
354
+ target[:cur_idx] = IGNORE_INDEX
355
+ for tokenized_len, speaker in zip(tokenized_lens, speakers):
356
+ if speaker == "human":
357
+ target[cur_idx + 2 : cur_idx + tokenized_len] = IGNORE_INDEX
358
+ cur_idx += tokenized_len
359
+
360
+
361
+ def _add_speaker_and_signal(header, source, get_conversation=True):
362
+ """Add speaker and start/end signal on each round."""
363
+ BEGIN_SIGNAL = "### "
364
+ END_SIGNAL = "\n"
365
+ conversation = header
366
+ for sentence in source:
367
+ from_str = sentence["from"]
368
+ if from_str.lower() == "human":
369
+ from_str = conversation_lib.default_conversation.roles[0]
370
+ elif from_str.lower() == "gpt":
371
+ from_str = conversation_lib.default_conversation.roles[1]
372
+ else:
373
+ from_str = "unknown"
374
+ sentence["value"] = BEGIN_SIGNAL + from_str + ": " + sentence["value"] + END_SIGNAL
375
+ if get_conversation:
376
+ conversation += sentence["value"]
377
+ conversation += BEGIN_SIGNAL
378
+ return conversation
379
+
380
+
381
+ def preprocess_multimodal(sources: Sequence[str], data_args: DataArguments) -> Dict:
382
+ is_multimodal = data_args.is_multimodal
383
+ if not is_multimodal:
384
+ return sources
385
+
386
+ for source in sources:
387
+ for sentence in source:
388
+ # TODO maybe this should be changed for interleaved data?
389
+ # if DEFAULT_IMAGE_TOKEN in sentence["value"] and not sentence["value"].startswith(DEFAULT_IMAGE_TOKEN):
390
+ # only check for num_im=1
391
+ num_im = len(re.findall(DEFAULT_IMAGE_TOKEN, sentence["value"]))
392
+ if num_im == 1 and DEFAULT_IMAGE_TOKEN in sentence["value"] and not sentence["value"].startswith(DEFAULT_IMAGE_TOKEN):
393
+ sentence["value"] = sentence["value"].replace(DEFAULT_IMAGE_TOKEN, "").strip()
394
+ sentence["value"] = DEFAULT_IMAGE_TOKEN + "\n" + sentence["value"]
395
+ sentence["value"] = sentence["value"].strip()
396
+ if "mmtag" in conversation_lib.default_conversation.version:
397
+ sentence["value"] = sentence["value"].replace(DEFAULT_IMAGE_TOKEN, "<Image>" + DEFAULT_IMAGE_TOKEN + "</Image>")
398
+ replace_token = DEFAULT_IMAGE_TOKEN
399
+ if data_args.mm_use_im_start_end:
400
+ replace_token = DEFAULT_IM_START_TOKEN + replace_token + DEFAULT_IM_END_TOKEN
401
+ sentence["value"] = sentence["value"].replace(DEFAULT_IMAGE_TOKEN, replace_token)
402
+
403
+ # For videoInstruct-100k noisy_data. TODO: Ask Yuanhan to clean the data instead of leaving the noise code here.
404
+ sentence["value"] = sentence["value"].replace("QA_GT_caption_based_noisy", "")
405
+
406
+ return sources
407
+
408
+
409
+ def preprocess_llama_2(sources, tokenizer: transformers.PreTrainedTokenizer, has_image: bool = False) -> Dict:
410
+ conv = conversation_lib.default_conversation.copy()
411
+ roles = {"human": conv.roles[0], "gpt": conv.roles[1]}
412
+
413
+ # Apply prompt templates
414
+ conversations = []
415
+ for i, source in enumerate(sources):
416
+ if roles[source[0]["from"]] != conv.roles[0]:
417
+ # Skip the first one if it is not from human
418
+ source = source[1:]
419
+
420
+ conv.messages = []
421
+ for j, sentence in enumerate(source):
422
+ role = roles[sentence["from"]]
423
+ assert role == conv.roles[j % 2], f"{i}"
424
+ conv.append_message(role, sentence["value"])
425
+ conversations.append(conv.get_prompt())
426
+
427
+ # Tokenize conversations
428
+
429
+ if has_image:
430
+ input_ids = torch.stack([tokenizer_image_token(prompt, tokenizer, return_tensors="pt") for prompt in conversations], dim=0)
431
+ else:
432
+ input_ids = tokenizer(
433
+ conversations,
434
+ return_tensors="pt",
435
+ padding="longest",
436
+ max_length=tokenizer.model_max_length,
437
+ truncation=True,
438
+ ).input_ids
439
+
440
+ targets = input_ids.clone()
441
+
442
+ assert conv.sep_style == conversation_lib.SeparatorStyle.LLAMA_2
443
+
444
+ # Mask targets
445
+ sep = "[/INST] "
446
+ for conversation, target in zip(conversations, targets):
447
+ total_len = int(target.ne(tokenizer.pad_token_id).sum())
448
+
449
+ rounds = conversation.split(conv.sep2)
450
+ cur_len = 1
451
+ target[:cur_len] = IGNORE_INDEX
452
+ for i, rou in enumerate(rounds):
453
+ if rou == "":
454
+ break
455
+
456
+ parts = rou.split(sep)
457
+ if len(parts) != 2:
458
+ break
459
+ parts[0] += sep
460
+
461
+ if has_image:
462
+ round_len = len(tokenizer_image_token(rou, tokenizer))
463
+ instruction_len = len(tokenizer_image_token(parts[0], tokenizer)) - 2
464
+ else:
465
+ round_len = len(tokenizer(rou).input_ids)
466
+ instruction_len = len(tokenizer(parts[0]).input_ids) - 2
467
+
468
+ target[cur_len : cur_len + instruction_len] = IGNORE_INDEX
469
+
470
+ cur_len += round_len
471
+ target[cur_len:] = IGNORE_INDEX
472
+
473
+ if cur_len < tokenizer.model_max_length:
474
+ if cur_len != total_len:
475
+ target[:] = IGNORE_INDEX
476
+ print(f"WARNING: tokenization mismatch: {cur_len} vs. {total_len}." f" (ignored)")
477
+
478
+ return dict(
479
+ input_ids=input_ids,
480
+ labels=targets,
481
+ )
482
+
483
+
484
+ def preprocess_gemma(sources: List[List[Dict[str, str]]], tokenizer: transformers.PreTrainedTokenizer, has_image: bool = False) -> Dict:
485
+ conv: conversation_lib.Conversation = conversation_lib.default_conversation.copy()
486
+ roles: Dict[str, str] = {"human": conv.roles[0], "gpt": conv.roles[1]}
487
+
488
+ # Apply prompt templates
489
+ conversations: List[str] = []
490
+ for i, source in enumerate(sources):
491
+ if roles[source[0]["from"]] != conv.roles[0]:
492
+ # Skip the first one if it is not from human
493
+ source: List[Dict[str, str]] = source[1:]
494
+
495
+ conv.messages = []
496
+ for j, sentence in enumerate(source):
497
+ role: str = roles[sentence["from"]]
498
+ assert role == conv.roles[j % 2], f"{i}"
499
+ conv.append_message(role, sentence["value"])
500
+ conversations.append(conv.get_prompt())
501
+
502
+ # Tokenize conversations
503
+ if has_image:
504
+ input_ids: torch.Tensor = torch.stack([tokenizer_image_token(prompt, tokenizer, return_tensors="pt") for prompt in conversations], dim=0)
505
+ else:
506
+ input_ids: torch.Tensor = tokenizer(
507
+ conversations,
508
+ return_tensors="pt",
509
+ padding="longest",
510
+ max_length=tokenizer.model_max_length,
511
+ truncation=True,
512
+ ).input_ids
513
+
514
+ targets: torch.Tensor = input_ids.clone()
515
+ assert conv.sep_style == conversation_lib.SeparatorStyle.GEMMA
516
+
517
+ # Mask target
518
+ sep: str = conv.sep + conv.roles[1]
519
+ for conversation, target in zip(conversations, targets):
520
+ total_len: int = int(target.ne(tokenizer.pad_token_id).sum())
521
+
522
+ rounds: List[str] = conversation.split(conv.sep)
523
+ re_rounds = []
524
+ for conv_idx in range(0, len(rounds), 2):
525
+ re_rounds.append(conv.sep.join(rounds[conv_idx : conv_idx + 2]))
526
+
527
+ cur_len = 1 # Ignore <bos>
528
+ target[:cur_len] = IGNORE_INDEX
529
+ for i, rou in enumerate(re_rounds):
530
+ if rou == "":
531
+ break
532
+
533
+ parts = rou.split(sep)
534
+ if len(parts) != 2:
535
+ break
536
+ parts[0] += sep # Re-append sep because split on this
537
+ # Now "".join(parts)==rou
538
+
539
+ if has_image:
540
+ round_len = len(tokenizer_image_token(rou, tokenizer)) - 1 # Ignore <bos>
541
+ instruction_len = len(tokenizer_image_token(parts[0], tokenizer)) - 1 # Ignore <bos>
542
+ else:
543
+ round_len = len(tokenizer(rou).input_ids) - 1 # Ignore <bos>
544
+ instruction_len = len(tokenizer(parts[0]).input_ids) - 1 # Ignore <bos>
545
+
546
+ round_len += 2 # sep: <end_of_turn>\n takes 2 tokens
547
+ target[cur_len : cur_len + instruction_len] = IGNORE_INDEX
548
+ cur_len += round_len
549
+
550
+ target[cur_len:] = IGNORE_INDEX
551
+
552
+ if cur_len < tokenizer.model_max_length:
553
+ if cur_len != total_len:
554
+ target[:] = IGNORE_INDEX
555
+ print(f"warning: tokenization mismatch: {cur_len} vs. {total_len}." f" (ignored)")
556
+
557
+ return dict(
558
+ input_ids=input_ids,
559
+ labels=targets,
560
+ )
561
+
562
+
563
+ def preprocess_qwen(sources, tokenizer: transformers.PreTrainedTokenizer, has_image: bool = False, max_len=2048, system_message: str = "You are a helpful assistant.") -> Dict:
564
+ # roles = {"human": "<|im_start|>user", "gpt": "<|im_start|>assistant"}
565
+ roles = {"human": "user", "gpt": "assistant"}
566
+
567
+ # Add image tokens to tokenizer as a special tokens
568
+ # Use a deepcopy of tokenizer so that we don't modify on the tokenizer
569
+ tokenizer = copy.deepcopy(tokenizer)
570
+ # When there is actually an image, we add the image tokens as a special token
571
+ if has_image:
572
+ tokenizer.add_tokens(["<image>"], special_tokens=True)
573
+
574
+ image_token_index = tokenizer.convert_tokens_to_ids("<image>")
575
+ im_start, im_end = tokenizer.additional_special_tokens_ids
576
+ # unmask_tokens = ["<|im_start|>", "<|im_start|>", "\n"]
577
+ unmask_tokens_idx = [198, im_start, im_end]
578
+ nl_tokens = tokenizer("\n").input_ids
579
+
580
+ # Reset Qwen chat templates so that it won't include system message every time we apply
581
+ chat_template = "{% for message in messages %}{{'<|im_start|>' + message['role'] + '\n' + message['content'] + '<|im_end|>' + '\n'}}{% endfor %}{% if add_generation_prompt %}{{ '<|im_start|>assistant\n' }}{% endif %}"
582
+ tokenizer.chat_template = chat_template
583
+
584
+ # _system = tokenizer("system").input_ids + nl_tokens
585
+ # _user = tokenizer("user").input_ids + nl_tokens
586
+ # _assistant = tokenizer("assistant").input_ids + nl_tokens
587
+
588
+ # Apply prompt templates
589
+ input_ids, targets = [], []
590
+ for i, source in enumerate(sources):
591
+ if roles[source[0]["from"]] != roles["human"]:
592
+ source = source[1:]
593
+
594
+ input_id, target = [], []
595
+
596
+ # New version, use apply chat template
597
+ # Build system message for each sentence
598
+ input_id += tokenizer.apply_chat_template([{"role" : "system", "content" : system_message}])
599
+ target += [IGNORE_INDEX] * len(input_id)
600
+
601
+ for conv in source:
602
+ # Make sure llava data can load
603
+ try:
604
+ role = conv["role"]
605
+ content = conv["content"]
606
+ except:
607
+ role = conv["from"]
608
+ content = conv["value"]
609
+
610
+ role = roles.get(role, role)
611
+
612
+ conv = [{"role" : role, "content" : content}]
613
+ encode_id = tokenizer.apply_chat_template(conv)
614
+ input_id += encode_id
615
+ if role in ["user", "system"]:
616
+ target += [IGNORE_INDEX] * len(encode_id)
617
+ else:
618
+ target += encode_id
619
+
620
+
621
+
622
+ assert len(input_id) == len(target), f"{len(input_id)} != {len(target)}"
623
+ for idx, encode_id in enumerate(input_id):
624
+ if encode_id in unmask_tokens_idx:
625
+ target[idx] = encode_id
626
+ if encode_id == image_token_index:
627
+ input_id[idx] = IMAGE_TOKEN_INDEX
628
+ input_ids.append(input_id)
629
+ targets.append(target)
630
+ input_ids = torch.tensor(input_ids, dtype=torch.long)
631
+ targets = torch.tensor(targets, dtype=torch.long)
632
+
633
+ return dict(
634
+ input_ids=input_ids, # tensor(bs x seq_len)
635
+ labels=targets, # tensor(bs x seq_len)
636
+ )
637
+
638
+
639
+ def preprocess_llama3(
640
+ sources,
641
+ tokenizer: transformers.PreTrainedTokenizer,
642
+ has_image: bool = False,
643
+ max_len=2048,
644
+ system_message: str = "You are a helpful language and vision assistant. You are able to understand the visual content that the user provides, and assist the user with a variety of tasks using natural language.",
645
+ ) -> Dict:
646
+ # roles = {"human": "<|start_header_id|>user<|end_header_id|>", "gpt": "<|start_header_id|>assistant<|end_header_id|>"}
647
+ roles = {"human": "user", "gpt": "assistant"}
648
+
649
+ # Add image tokens to tokenizer as a special tokens
650
+ # Use a deepcopy of tokenizer so that we don't modify on the tokenizer
651
+ tokenizer = copy.deepcopy(tokenizer)
652
+ # When there is actually an image, we add the image tokens as a special token
653
+ if has_image:
654
+ tokenizer.add_tokens(["<image>"], special_tokens=True)
655
+ image_token_index = tokenizer.convert_tokens_to_ids("<image>")
656
+ bos_token_id = tokenizer.convert_tokens_to_ids("<|begin_of_text|>")
657
+ start_header_id = tokenizer.convert_tokens_to_ids("<|start_header_id|>")
658
+ end_header_id = tokenizer.convert_tokens_to_ids("<|end_header_id|>")
659
+ eot_id = tokenizer.convert_tokens_to_ids("<|eot_id|>")
660
+
661
+ unmask_tokens = ["<|begin_of_text|>", "<|start_header_id|>", "<|end_header_id|>", "<|eot_id|>", "\n\n"]
662
+ unmask_tokens_idx = [tokenizer.convert_tokens_to_ids(tok) for tok in unmask_tokens]
663
+
664
+ # After update, calling tokenizer of llama3 will
665
+ # auto add bos id for the tokens. ヽ(`⌒´)ノ
666
+ def safe_tokenizer_llama3(text):
667
+ input_ids = tokenizer(text).input_ids
668
+ if input_ids[0] == bos_token_id:
669
+ input_ids = input_ids[1:]
670
+ return input_ids
671
+
672
+ nl_tokens = tokenizer.convert_tokens_to_ids("\n\n")
673
+ # Apply prompt templates
674
+ input_ids, targets = [], []
675
+ for i, source in enumerate(sources):
676
+ if roles[source[0]["from"]] != roles["human"]:
677
+ source = source[1:]
678
+
679
+ input_id, target = [], []
680
+
681
+ # New version, use apply chat template
682
+ # Build system message for each sentence
683
+ input_id += tokenizer.apply_chat_template([{"role" : "system", "content" : system_message}])
684
+ target += [IGNORE_INDEX] * len(input_id)
685
+
686
+ for conv in source:
687
+ # Make sure llava data can load
688
+ try:
689
+ role = conv["role"]
690
+ content = conv["content"]
691
+ except:
692
+ role = conv["from"]
693
+ content = conv["value"]
694
+
695
+ role = roles.get(role, role)
696
+
697
+ conv = [{"role" : role, "content" : content}]
698
+ # First is bos token we don't need here
699
+ encode_id = tokenizer.apply_chat_template(conv)[1:]
700
+ input_id += encode_id
701
+ if role in ["user", "system"]:
702
+ target += [IGNORE_INDEX] * len(encode_id)
703
+ else:
704
+ target += encode_id
705
+
706
+
707
+
708
+ assert len(input_id) == len(target), f"{len(input_id)} != {len(target)}"
709
+ for idx, encode_id in enumerate(input_id):
710
+ if encode_id in unmask_tokens_idx:
711
+ target[idx] = encode_id
712
+ if encode_id == image_token_index:
713
+ input_id[idx] = IMAGE_TOKEN_INDEX
714
+ input_ids.append(input_id)
715
+ targets.append(target)
716
+ input_ids = torch.tensor(input_ids, dtype=torch.long)
717
+ targets = torch.tensor(targets, dtype=torch.long)
718
+
719
+ return dict(
720
+ input_ids=input_ids, # tensor(bs x seq_len)
721
+ labels=targets, # tensor(bs x seq_len)
722
+ )
723
+
724
+
725
+ def preprocess_v1(sources, tokenizer: transformers.PreTrainedTokenizer, has_image: bool = False) -> Dict:
726
+ conv = conversation_lib.default_conversation.copy()
727
+ roles = {"human": conv.roles[0], "gpt": conv.roles[1]}
728
+
729
+ # Apply prompt templates
730
+ conversations = []
731
+ for i, source in enumerate(sources):
732
+ if roles[source[0]["from"]] != conv.roles[0]:
733
+ # Skip the first one if it is not from human
734
+ source = source[1:]
735
+
736
+ conv.messages = []
737
+ for j, sentence in enumerate(source):
738
+ role = roles[sentence["from"]]
739
+ assert role == conv.roles[j % 2], f"{i}"
740
+ conv.append_message(role, sentence["value"])
741
+ conversations.append(conv.get_prompt())
742
+
743
+ # Tokenize conversations
744
+
745
+ if has_image:
746
+ input_ids = torch.stack([tokenizer_image_token(prompt, tokenizer, return_tensors="pt") for prompt in conversations], dim=0)
747
+ else:
748
+ input_ids = tokenizer(
749
+ conversations,
750
+ return_tensors="pt",
751
+ padding="longest",
752
+ max_length=tokenizer.model_max_length,
753
+ truncation=True,
754
+ ).input_ids
755
+
756
+ targets = input_ids.clone()
757
+
758
+ assert conv.sep_style == conversation_lib.SeparatorStyle.TWO
759
+
760
+ # Mask targets
761
+ sep = conv.sep + conv.roles[1] + ": "
762
+ for conversation, target in zip(conversations, targets):
763
+ total_len = int(target.ne(tokenizer.pad_token_id).sum())
764
+
765
+ rounds = conversation.split(conv.sep2)
766
+ cur_len = 1
767
+ target[:cur_len] = IGNORE_INDEX
768
+ for i, rou in enumerate(rounds):
769
+ if rou == "":
770
+ break
771
+
772
+ parts = rou.split(sep)
773
+ if len(parts) != 2:
774
+ break
775
+ parts[0] += sep
776
+
777
+ if has_image:
778
+ round_len = len(tokenizer_image_token(rou, tokenizer))
779
+ instruction_len = len(tokenizer_image_token(parts[0], tokenizer)) - 2
780
+ else:
781
+ round_len = len(tokenizer(rou).input_ids)
782
+ instruction_len = len(tokenizer(parts[0]).input_ids) - 2
783
+
784
+ if i != 0 and not tokenizer.legacy and IS_TOKENIZER_GREATER_THAN_0_14:
785
+ round_len -= 1
786
+ instruction_len -= 1
787
+
788
+ target[cur_len : cur_len + instruction_len] = IGNORE_INDEX
789
+
790
+ cur_len += round_len
791
+ target[cur_len:] = IGNORE_INDEX
792
+
793
+ if cur_len < tokenizer.model_max_length:
794
+ if cur_len != total_len:
795
+ target[:] = IGNORE_INDEX
796
+ print(f"WARNING: tokenization mismatch: {cur_len} vs. {total_len}." f" (ignored)")
797
+
798
+ return dict(
799
+ input_ids=input_ids,
800
+ labels=targets,
801
+ )
802
+
803
+
804
+ def preprocess_mpt(sources, tokenizer: transformers.PreTrainedTokenizer, has_image: bool = False) -> Dict:
805
+ conv = conversation_lib.default_conversation.copy()
806
+ roles = {"human": conv.roles[0], "gpt": conv.roles[1]}
807
+
808
+ # Apply prompt templates
809
+ conversations = []
810
+ for i, source in enumerate(sources):
811
+ if roles[source[0]["from"]] != conv.roles[0]:
812
+ # Skip the first one if it is not from human
813
+ source = source[1:]
814
+
815
+ conv.messages = []
816
+ for j, sentence in enumerate(source):
817
+ role = roles[sentence["from"]]
818
+ assert role == conv.roles[j % 2], f"{i}"
819
+ conv.append_message(role, sentence["value"])
820
+ conversations.append(conv.get_prompt())
821
+
822
+ # Tokenize conversations
823
+
824
+ if has_image:
825
+ input_ids = torch.stack([tokenizer_image_token(prompt, tokenizer, return_tensors="pt") for prompt in conversations], dim=0)
826
+ else:
827
+ input_ids = tokenizer(
828
+ conversations,
829
+ return_tensors="pt",
830
+ padding="longest",
831
+ max_length=tokenizer.model_max_length,
832
+ truncation=True,
833
+ ).input_ids
834
+
835
+ targets = input_ids.clone()
836
+ assert conv.sep_style == conversation_lib.SeparatorStyle.MPT
837
+
838
+ # Mask targets
839
+ sep = conv.sep + conv.roles[1]
840
+ for conversation, target in zip(conversations, targets):
841
+ total_len = int(target.ne(tokenizer.pad_token_id).sum())
842
+
843
+ rounds = conversation.split(conv.sep)
844
+ re_rounds = [conv.sep.join(rounds[:3])] # system + user + gpt
845
+ for conv_idx in range(3, len(rounds), 2):
846
+ re_rounds.append(conv.sep.join(rounds[conv_idx : conv_idx + 2])) # user + gpt
847
+ cur_len = 1
848
+ target[:cur_len] = IGNORE_INDEX
849
+ for i, rou in enumerate(re_rounds):
850
+ if rou == "":
851
+ break
852
+
853
+ parts = rou.split(sep)
854
+ if len(parts) != 2:
855
+ break
856
+ parts[0] += sep
857
+
858
+ if has_image:
859
+ round_len = len(tokenizer_image_token(rou, tokenizer))
860
+ instruction_len = len(tokenizer_image_token(parts[0], tokenizer)) - 1
861
+ else:
862
+ round_len = len(tokenizer(rou).input_ids)
863
+ instruction_len = len(tokenizer(parts[0]).input_ids) - 1
864
+
865
+ if i != 0 and getattr(tokenizer, "legacy", False) and IS_TOKENIZER_GREATER_THAN_0_14:
866
+ round_len += 1
867
+ instruction_len += 1
868
+
869
+ target[cur_len : cur_len + instruction_len] = IGNORE_INDEX
870
+
871
+ cur_len += round_len
872
+ target[cur_len:] = IGNORE_INDEX
873
+
874
+ if cur_len < tokenizer.model_max_length:
875
+ if cur_len != total_len:
876
+ target[:] = IGNORE_INDEX
877
+ print(f"WARNING: tokenization mismatch: {cur_len} vs. {total_len}." f"(#turns={len(re_rounds)} ignored)")
878
+
879
+ return dict(
880
+ input_ids=input_ids,
881
+ labels=targets,
882
+ )
883
+
884
+
885
+ def preprocess_plain(
886
+ sources: Sequence[str],
887
+ tokenizer: transformers.PreTrainedTokenizer,
888
+ ) -> Dict:
889
+ # add end signal and concatenate together
890
+ conversations = []
891
+ for source in sources:
892
+ assert len(source) == 2
893
+ assert DEFAULT_IMAGE_TOKEN in source[0]["value"]
894
+ source[0]["value"] = DEFAULT_IMAGE_TOKEN
895
+ conversation = source[0]["value"] + source[1]["value"] + conversation_lib.default_conversation.sep
896
+ conversations.append(conversation)
897
+ # tokenize conversations
898
+ input_ids = [tokenizer_image_token(prompt, tokenizer, return_tensors="pt") for prompt in conversations]
899
+ targets = copy.deepcopy(input_ids)
900
+ for target, source in zip(targets, sources):
901
+ tokenized_len = len(tokenizer_image_token(source[0]["value"], tokenizer))
902
+ target[:tokenized_len] = IGNORE_INDEX
903
+
904
+ return dict(input_ids=input_ids, labels=targets)
905
+
906
+
907
+ def preprocess(sources: Sequence[str], tokenizer: transformers.PreTrainedTokenizer, has_image: bool = False) -> Dict:
908
+ """
909
+ Given a list of sources, each is a conversation list. This transform:
910
+ 1. Add signal '### ' at the beginning each sentence, with end signal '\n';
911
+ 2. Concatenate conversations together;
912
+ 3. Tokenize the concatenated conversation;
913
+ 4. Make a deepcopy as the target. Mask human words with IGNORE_INDEX.
914
+ """
915
+ if conversation_lib.default_conversation.sep_style == conversation_lib.SeparatorStyle.PLAIN:
916
+ return preprocess_plain(sources, tokenizer)
917
+ if conversation_lib.default_conversation.sep_style == conversation_lib.SeparatorStyle.LLAMA_2:
918
+ return preprocess_llama_2(sources, tokenizer, has_image=has_image)
919
+ if conversation_lib.default_conversation.version.startswith("v1"):
920
+ return preprocess_v1(sources, tokenizer, has_image=has_image)
921
+ if conversation_lib.default_conversation.version == "mpt":
922
+ return preprocess_mpt(sources, tokenizer, has_image=has_image)
923
+ if conversation_lib.default_conversation.version == "qwen":
924
+ return preprocess_qwen(sources, tokenizer, has_image=has_image)
925
+ if conversation_lib.default_conversation.version == "gemma":
926
+ return preprocess_gemma(sources, tokenizer, has_image=has_image)
927
+ if conversation_lib.default_conversation.version == "llama_v3":
928
+ return preprocess_llama3(sources, tokenizer, has_image=has_image)
929
+ # add end signal and concatenate together
930
+ conversations = []
931
+ for source in sources:
932
+ header = f"{conversation_lib.default_conversation.system}\n\n"
933
+ conversation = _add_speaker_and_signal(header, source)
934
+ conversations.append(conversation)
935
+
936
+ # tokenize conversations
937
+ def get_tokenize_len(prompts):
938
+ return [len(tokenizer_image_token(prompt, tokenizer)) for prompt in prompts]
939
+
940
+ if has_image:
941
+ input_ids = [tokenizer_image_token(prompt, tokenizer, return_tensors="pt") for prompt in conversations]
942
+ else:
943
+ conversations_tokenized = _tokenize_fn(conversations, tokenizer)
944
+ input_ids = conversations_tokenized["input_ids"]
945
+
946
+ targets = copy.deepcopy(input_ids)
947
+ for target, source in zip(targets, sources):
948
+ if has_image:
949
+ tokenized_lens = get_tokenize_len([header] + [s["value"] for s in source])
950
+ else:
951
+ tokenized_lens = _tokenize_fn([header] + [s["value"] for s in source], tokenizer)["input_ids_lens"]
952
+ speakers = [sentence["from"] for sentence in source]
953
+ _mask_targets(target, tokenized_lens, speakers)
954
+
955
+ return dict(input_ids=input_ids, labels=targets)
956
+
957
+
958
+ class LazySupervisedDataset(Dataset):
959
+ def __init__(self, data_path: str, tokenizer: transformers.PreTrainedTokenizer, data_args: DataArguments):
960
+ super(LazySupervisedDataset, self).__init__()
961
+ self.tokenizer = tokenizer
962
+ self.list_data_dict = []
963
+
964
+ # Handle multiple JSON files specified in the data_path
965
+ if "{" in data_path and "}" in data_path:
966
+ base_path, file_pattern = re.match(r"^(.*)\{(.*)\}\.json$", data_path).groups()
967
+ file_names = file_pattern.split(",")
968
+ rank0_print(f"Loading {file_names} from {base_path}")
969
+ data_args.dataset_paths = []
970
+ for file_name in file_names:
971
+ data_args.dataset_paths.append(f"{base_path}{file_name}.json")
972
+ full_path = f"{base_path}{file_name}.json"
973
+ rank0_print(f"Loading {full_path}")
974
+ with open(full_path, "r") as file:
975
+ cur_data_dict = json.load(file)
976
+ rank0_print(f"Loaded {len(cur_data_dict)} samples from {full_path}")
977
+ self.list_data_dict.extend(cur_data_dict)
978
+ elif data_path.endswith(".yaml"):
979
+ with open(data_path, "r") as file:
980
+ yaml_data = yaml.safe_load(file)
981
+ datasets = yaml_data.get("datasets")
982
+ # file should be in the format of:
983
+ # datasets:
984
+ # - json_path: xxxx1.json
985
+ # sampling_strategy: first:1000
986
+ # - json_path: xxxx2.json
987
+ # sampling_strategy: end:3000
988
+ # - json_path: xxxx3.json
989
+ # sampling_strategy: random:999
990
+ data_args.dataset_paths = [dataset.get("json_path") for dataset in datasets]
991
+ for dataset in datasets:
992
+ json_path = dataset.get("json_path")
993
+ sampling_strategy = dataset.get("sampling_strategy", "all")
994
+ sampling_number = None
995
+
996
+ rank0_print(f"Loading {json_path} with {sampling_strategy} sampling strategy")
997
+
998
+ if json_path.endswith(".jsonl"):
999
+ cur_data_dict = []
1000
+ with open(json_path, "r") as json_file:
1001
+ for line in json_file:
1002
+ cur_data_dict.append(json.loads(line.strip()))
1003
+ elif json_path.endswith(".json"):
1004
+ with open(json_path, "r") as json_file:
1005
+ cur_data_dict = json.load(json_file)
1006
+ else:
1007
+ raise ValueError(f"Unsupported file type: {json_path}")
1008
+
1009
+ if ":" in sampling_strategy:
1010
+ sampling_strategy, sampling_number = sampling_strategy.split(":")
1011
+ if "%" in sampling_number:
1012
+ sampling_number = math.ceil(int(sampling_number.split("%")[0]) * len(cur_data_dict) / 100)
1013
+ else:
1014
+ sampling_number = int(sampling_number)
1015
+
1016
+ # Apply the sampling strategy
1017
+ if sampling_strategy == "first" and sampling_number is not None:
1018
+ cur_data_dict = cur_data_dict[:sampling_number]
1019
+ elif sampling_strategy == "end" and sampling_number is not None:
1020
+ cur_data_dict = cur_data_dict[-sampling_number:]
1021
+ elif sampling_strategy == "random" and sampling_number is not None:
1022
+ random.shuffle(cur_data_dict)
1023
+ cur_data_dict = cur_data_dict[:sampling_number]
1024
+
1025
+ rank0_print(f"Loaded {len(cur_data_dict)} samples from {json_path}")
1026
+ self.list_data_dict.extend(cur_data_dict)
1027
+ else:
1028
+ data_args.dataset_paths = [data_path]
1029
+ rank0_print(f"Loading {data_path}")
1030
+ with open(data_path, "r") as file:
1031
+ cur_data_dict = json.load(file)
1032
+ rank0_print(f"Loaded {len(cur_data_dict)} samples from {data_path}")
1033
+ self.list_data_dict.extend(cur_data_dict)
1034
+
1035
+ rank0_print(f"Loaded {len(self.list_data_dict)} samples from {data_path}")
1036
+ rank0_print("Formatting inputs...Skip in lazy mode")
1037
+ self.tokenizer = tokenizer
1038
+ self.data_args = data_args
1039
+
1040
+ def __len__(self):
1041
+ return len(self.list_data_dict)
1042
+
1043
+ @property
1044
+ def lengths(self):
1045
+ length_list = []
1046
+ for sample in self.list_data_dict:
1047
+ img_tokens = 128 if "image" in sample else 0
1048
+ length_list.append(sum(len(conv["value"].split()) for conv in sample["conversations"]) + img_tokens)
1049
+ return length_list
1050
+
1051
+ @property
1052
+ def modality_lengths(self):
1053
+ length_list = []
1054
+ for sample in self.list_data_dict:
1055
+ cur_len = sum(len(conv["value"].split()) for conv in sample["conversations"])
1056
+ assert cur_len > 0, f"Conversation length is 0 for {sample}"
1057
+ if "image" in sample or "video" in sample or self.data_args.early_mix_text:
1058
+ length_list.append(cur_len)
1059
+ else:
1060
+ length_list.append(-cur_len)
1061
+ return length_list
1062
+
1063
+ def process_image(self, image_file, overwrite_image_aspect_ratio=None):
1064
+ image_folder = self.data_args.image_folder
1065
+ processor = self.data_args.image_processor
1066
+ # print(f"\n\nInspecting the image path, folder = {image_folder}, image={image_file}\n\n")
1067
+ try:
1068
+ image = Image.open(os.path.join(image_folder, image_file)).convert("RGB")
1069
+ except Exception as exn:
1070
+ print(f"Failed to open image {image_file}. Exception:", exn)
1071
+ raise exn
1072
+
1073
+ image_size = image.size
1074
+ image_aspect_ratio = self.data_args.image_aspect_ratio
1075
+ if overwrite_image_aspect_ratio is not None:
1076
+ image_aspect_ratio = overwrite_image_aspect_ratio
1077
+ if image_aspect_ratio == "highres":
1078
+ image = process_highres_image(image, self.data_args.image_processor, self.data_args.image_grid_pinpoints)
1079
+ elif image_aspect_ratio == "anyres" or "anyres_max" in image_aspect_ratio:
1080
+ image = process_anyres_image(image, self.data_args.image_processor, self.data_args.image_grid_pinpoints)
1081
+ elif image_aspect_ratio == "crop_split":
1082
+ image = process_highres_image_crop_split(image, self.data_args)
1083
+ elif image_aspect_ratio == "pad":
1084
+
1085
+ def expand2square(pil_img, background_color):
1086
+ width, height = pil_img.size
1087
+ if width == height:
1088
+ return pil_img
1089
+ elif width > height:
1090
+ result = Image.new(pil_img.mode, (width, width), background_color)
1091
+ result.paste(pil_img, (0, (width - height) // 2))
1092
+ return result
1093
+ else:
1094
+ result = Image.new(pil_img.mode, (height, height), background_color)
1095
+ result.paste(pil_img, ((height - width) // 2, 0))
1096
+ return result
1097
+
1098
+ image = expand2square(image, tuple(int(x * 255) for x in processor.image_mean))
1099
+ image = processor.preprocess(image, return_tensors="pt")["pixel_values"][0]
1100
+ else:
1101
+ image = processor.preprocess(image, return_tensors="pt")["pixel_values"][0]
1102
+ return image, image_size, "image"
1103
+
1104
+ def __getitem__(self, i) -> Dict[str, torch.Tensor]:
1105
+ # TODO: define number of retries somewhere else
1106
+ num_base_retries = 3
1107
+ num_final_retries = 300
1108
+
1109
+ # try the current sample first
1110
+ for attempt_idx in range(num_base_retries):
1111
+ try:
1112
+ sample = self._get_item(i)
1113
+ return sample
1114
+ except Exception as e:
1115
+ # sleep 1s in case it is a cloud disk issue
1116
+ print(f"[Try #{attempt_idx}] Failed to fetch sample {i}. Exception:", e)
1117
+ time.sleep(1)
1118
+
1119
+ # try other samples, in case it is file corruption issue
1120
+ for attempt_idx in range(num_base_retries):
1121
+ try:
1122
+ next_index = min(i + 1, len(self.list_data_dict) - 1)
1123
+ # sample_idx = random.choice(range(len(self)))
1124
+ sample = self._get_item(next_index)
1125
+ return sample
1126
+ except Exception as e:
1127
+ # no need to sleep
1128
+ print(f"[Try other #{attempt_idx}] Failed to fetch sample {next_index}. Exception:", e)
1129
+ pass
1130
+
1131
+ try:
1132
+ sample = self._get_item(i)
1133
+ return sample
1134
+ except Exception as e:
1135
+ raise e
1136
+
1137
+ def _get_item(self, i) -> Dict[str, torch.Tensor]:
1138
+ sources = self.list_data_dict[i]
1139
+ if isinstance(i, int):
1140
+ sources = [sources]
1141
+ assert len(sources) == 1, "Don't know why it is wrapped to a list" # FIXME
1142
+
1143
+ if "image" in sources[0]:
1144
+ image_file = self.list_data_dict[i]["image"]
1145
+ if type(image_file) is list:
1146
+ image = [self.process_image(f) for f in image_file]
1147
+ # Handling multi images
1148
+ # overwrite to process with simple pad
1149
+ if len(image_file) > 1:
1150
+ image = [self.process_image(f, "pad") for f in image_file]
1151
+ image = [[im[0], im[1], "image"] for im in image]
1152
+ else:
1153
+ image = [self.process_image(image_file)]
1154
+ sources = preprocess_multimodal(copy.deepcopy([e["conversations"] for e in sources]), self.data_args)
1155
+
1156
+ elif "video" in sources[0]:
1157
+ video_file = self.list_data_dict[i]["video"]
1158
+ video_folder = self.data_args.video_folder
1159
+ video_file = os.path.join(video_folder, video_file)
1160
+ suffix = video_file.split(".")[-1]
1161
+ if not os.path.exists(video_file):
1162
+ print("File {} not exist!".format(video_file))
1163
+
1164
+ try:
1165
+ if "shareVideoGPTV" in video_file:
1166
+ frame_files = [os.path.join(video_file, f) for f in os.listdir(video_file) if os.path.isfile(os.path.join(video_file, f))]
1167
+ frame_files.sort() # Ensure the frames are sorted if they are named sequentially
1168
+
1169
+ # TODO: Hard CODE: Determine the indices for uniformly sampling 10 frames
1170
+ if self.data_args.force_sample:
1171
+ num_frames_to_sample = self.data_args.frames_upbound
1172
+ else:
1173
+ num_frames_to_sample = 10
1174
+
1175
+ avg_fps = 2
1176
+
1177
+ total_frames = len(frame_files)
1178
+ sampled_indices = np.linspace(0, total_frames - 1, num_frames_to_sample, dtype=int)
1179
+
1180
+
1181
+ frame_time = [i/2 for i in sampled_indices]
1182
+ frame_time = ",".join([f"{i:.2f}s" for i in frame_time])
1183
+
1184
+ video_time = total_frames / avg_fps
1185
+
1186
+ # Read and store the sampled frames
1187
+ video = []
1188
+ for idx in sampled_indices:
1189
+ frame_path = frame_files[idx]
1190
+ try:
1191
+ with Image.open(frame_path) as img:
1192
+ frame = img.convert("RGB")
1193
+ video.append(frame)
1194
+ except IOError:
1195
+ print(f"Failed to read frame at path: {frame_path}")
1196
+ else:
1197
+ video, video_time, frame_time, num_frames_to_sample = process_video_with_decord(video_file, self.data_args)
1198
+
1199
+ processor = self.data_args.image_processor
1200
+ image = processor.preprocess(video, return_tensors="pt")["pixel_values"]
1201
+ if self.data_args.add_time_instruction:
1202
+ time_instruciton = f"The video lasts for {video_time:.2f} seconds, and {num_frames_to_sample} frames are uniformly sampled from it. These frames are located at {frame_time}.Please answer the following questions related to this video."
1203
+ sources[0]["conversations"][0]["value"] = f'{DEFAULT_IMAGE_TOKEN}\n{time_instruciton}\n{sources[0]["conversations"][0]["value"].replace(DEFAULT_IMAGE_TOKEN, "")}'
1204
+ image = [(image, video[0].size, "video")]
1205
+ sources = preprocess_multimodal(copy.deepcopy([e["conversations"] for e in sources]), self.data_args)
1206
+ # print(sources)
1207
+ except Exception as e:
1208
+ print(f"Error: {e}")
1209
+ print(f"Failed to read video file: {video_file}")
1210
+ return self._get_item(i + 1)
1211
+ else:
1212
+ sources = copy.deepcopy([e["conversations"] for e in sources])
1213
+
1214
+ has_image = ("image" in self.list_data_dict[i]) or ("video" in self.list_data_dict[i])
1215
+ data_dict = preprocess(sources, self.tokenizer, has_image=has_image)
1216
+
1217
+ if "prompt" in data_dict:
1218
+ prompt = data_dict["prompt"]
1219
+ else:
1220
+ prompt = None
1221
+
1222
+ if isinstance(i, int):
1223
+ data_dict = dict(input_ids=data_dict["input_ids"][0], labels=data_dict["labels"][0])
1224
+
1225
+ # image exist in the data
1226
+ if "image" in self.list_data_dict[i]:
1227
+ data_dict["image"] = image
1228
+ elif "video" in self.list_data_dict[i]:
1229
+ data_dict["image"] = image
1230
+ elif self.data_args.is_multimodal:
1231
+ # image does not exist in the data, but the model is multimodal
1232
+ crop_size = self.data_args.image_processor.crop_size
1233
+ data_dict["image"] = [
1234
+ (torch.zeros(1, 3, crop_size["height"], crop_size["width"]), (crop_size["width"], crop_size["height"]), "text"),
1235
+ ]
1236
+ # prompt exist in the data
1237
+ if prompt is not None:
1238
+ data_dict["prompt"] = prompt
1239
+
1240
+ data_dict["id"] = self.list_data_dict[i].get("id", i)
1241
+
1242
+ return data_dict
1243
+
1244
+
1245
+ @dataclass
1246
+ class DataCollatorForSupervisedDataset(object):
1247
+ """Collate examples for supervised fine-tuning."""
1248
+
1249
+ tokenizer: transformers.PreTrainedTokenizer
1250
+
1251
+ def pad_sequence(self, input_ids, batch_first, padding_value):
1252
+ if self.tokenizer.padding_side == "left":
1253
+ input_ids = [torch.flip(_input_ids, [0]) for _input_ids in input_ids]
1254
+ input_ids = torch.nn.utils.rnn.pad_sequence(input_ids, batch_first=batch_first, padding_value=padding_value)
1255
+ if self.tokenizer.padding_side == "left":
1256
+ input_ids = torch.flip(input_ids, [1])
1257
+ return input_ids
1258
+
1259
+ def __call__(self, instances: Sequence[Dict]) -> Dict[str, torch.Tensor]:
1260
+ input_ids, labels = tuple([instance[key] for instance in instances] for key in ("input_ids", "labels"))
1261
+ # input_ids, labels, ids = tuple([instance[key] for instance in instances] for key in ("input_ids", "labels", "id"))
1262
+ input_ids = [_input_ids[: self.tokenizer.model_max_length] for _input_ids in input_ids]
1263
+ labels = [_labels[: self.tokenizer.model_max_length] for _labels in labels]
1264
+ if self.tokenizer.pad_token_id is None:
1265
+ # self.tokenizer.pad_token_id = self.tokenizer.eos_token_id # FIXME: this could only be triggered for llama3 model.
1266
+ self.tokenizer.pad_token_id = 0 # This gets the best result. Don't know why.
1267
+ input_ids = self.pad_sequence(input_ids, batch_first=True, padding_value=self.tokenizer.pad_token_id)
1268
+ labels = self.pad_sequence(labels, batch_first=True, padding_value=IGNORE_INDEX)
1269
+ batch = dict(input_ids=input_ids, labels=labels.long() if labels.dtype == torch.int32 else labels, attention_mask=input_ids.ne(self.tokenizer.pad_token_id))
1270
+ # batch = dict(input_ids=input_ids, labels=labels, attention_mask=input_ids.ne(self.tokenizer.pad_token_id), ids=ids)
1271
+
1272
+ if "image" in instances[0]:
1273
+ images = [instance["image"] for instance in instances]
1274
+
1275
+ batch["image_sizes"] = [im[1] for im_list in images for im in im_list]
1276
+ batch["modalities"] = [im[2] for im_list in images for im in im_list]
1277
+ images = [im[0] for im_list in images for im in im_list]
1278
+
1279
+ # if all(x is not None and x.shape == images[0].shape for x in images):
1280
+ # Image: (N, P, C, H, W)
1281
+ # Video: (N, F, C, H, W)
1282
+ # batch["images"] = torch.stack(images)
1283
+ # else:
1284
+ batch["images"] = images
1285
+
1286
+ if "prompt" in instances[0]:
1287
+ batch["prompts"] = [instance["prompt"] for instance in instances]
1288
+
1289
+ return batch
1290
+
1291
+
1292
+ def make_supervised_data_module(tokenizer: transformers.PreTrainedTokenizer, data_args) -> Dict:
1293
+ """Make dataset and collator for supervised fine-tuning."""
1294
+ train_dataset = LazySupervisedDataset(tokenizer=tokenizer, data_path=data_args.data_path, data_args=data_args)
1295
+ data_collator = DataCollatorForSupervisedDataset(tokenizer=tokenizer)
1296
+ return dict(train_dataset=train_dataset, eval_dataset=None, data_collator=data_collator)
1297
+
1298
+
1299
+ def get_model(model_args, training_args, bnb_model_from_pretrained_args):
1300
+ assert training_args.attn_implementation
1301
+ if training_args.attn_implementation == "sdpa" and torch.__version__ < "2.1.2":
1302
+ raise ValueError("The 'sdpa' attention implementation requires torch version 2.1.2 or higher.")
1303
+
1304
+ customized_kwargs = dict()
1305
+ customized_kwargs.update(bnb_model_from_pretrained_args)
1306
+ cfg_pretrained = None
1307
+
1308
+ overwrite_config = {}
1309
+ if any(
1310
+ [
1311
+ model_args.rope_scaling_factor is not None,
1312
+ model_args.rope_scaling_type is not None,
1313
+ model_args.mm_spatial_pool_stride is not None,
1314
+ model_args.mm_spatial_pool_out_channels is not None,
1315
+ model_args.mm_spatial_pool_mode is not None,
1316
+ model_args.mm_resampler_type is not None,
1317
+ ]
1318
+ ):
1319
+ cfg_pretrained = AutoConfig.from_pretrained(model_args.model_name_or_path)
1320
+
1321
+ if model_args.use_pos_skipping is not None and model_args.pos_skipping_range is not None:
1322
+ overwrite_config["use_pos_skipping"] = model_args.use_pos_skipping
1323
+ overwrite_config["pos_skipping_range"] = model_args.pos_skipping_range
1324
+
1325
+ if model_args.rope_scaling_factor is not None and model_args.rope_scaling_type is not None:
1326
+ overwrite_config["rope_scaling"] = {
1327
+ "factor": model_args.rope_scaling_factor,
1328
+ "type": model_args.rope_scaling_type,
1329
+ }
1330
+ if training_args.model_max_length is None:
1331
+ training_args.model_max_length = cfg_pretrained.max_position_embeddings * model_args.rope_scaling_factor
1332
+ overwrite_config["max_sequence_length"] = training_args.model_max_length
1333
+ assert training_args.model_max_length == int(cfg_pretrained.max_position_embeddings * model_args.rope_scaling_factor), print(
1334
+ f"model_max_length: {training_args.model_max_length}, max_position_embeddings: {cfg_pretrained.max_position_embeddings}, rope_scaling_factor: {model_args.rope_scaling_factor}"
1335
+ )
1336
+ # overwrite_config["max_sequence_length"] = model_args.max_sequence_length
1337
+ # overwrite_config["tokenizer_model_max_length"] = model_args.tokenizer_model_max_length
1338
+
1339
+ if model_args.mm_spatial_pool_stride is not None and model_args.mm_spatial_pool_out_channels is not None and model_args.mm_spatial_pool_mode is not None and model_args.mm_resampler_type is not None:
1340
+ overwrite_config["mm_resampler_type"] = model_args.mm_resampler_type
1341
+ overwrite_config["mm_spatial_pool_stride"] = model_args.mm_spatial_pool_stride
1342
+ overwrite_config["mm_spatial_pool_out_channels"] = model_args.mm_spatial_pool_out_channels
1343
+ overwrite_config["mm_spatial_pool_mode"] = model_args.mm_spatial_pool_mode
1344
+
1345
+ if model_args.mm_spatial_pool_mode is not None:
1346
+ overwrite_config["mm_spatial_pool_mode"] = model_args.mm_spatial_pool_mode
1347
+
1348
+ if overwrite_config:
1349
+ assert cfg_pretrained is not None, "cfg_pretrained is None"
1350
+
1351
+ rank0_print(f"Overwriting config with {overwrite_config}")
1352
+ for k, v in overwrite_config.items():
1353
+ setattr(cfg_pretrained, k, v)
1354
+
1355
+ customized_kwargs["config"] = cfg_pretrained
1356
+
1357
+ if model_args.model_class_name is not None:
1358
+ actual_model_class_name = f"{model_args.model_class_name}ForCausalLM"
1359
+ model_class = getattr(transformers, actual_model_class_name)
1360
+ rank0_print(f"Using model class {model_class} from {model_args.model_class_name}")
1361
+ model = model_class.from_pretrained(
1362
+ model_args.model_name_or_path,
1363
+ cache_dir=training_args.cache_dir,
1364
+ attn_implementation=training_args.attn_implementation,
1365
+ torch_dtype=(torch.bfloat16 if training_args.bf16 else None),
1366
+ low_cpu_mem_usage=False,
1367
+ **customized_kwargs,
1368
+ )
1369
+ elif model_args.vision_tower is not None:
1370
+ if "mixtral" in model_args.model_name_or_path.lower():
1371
+ model = LlavaMixtralForCausalLM.from_pretrained(
1372
+ model_args.model_name_or_path,
1373
+ cache_dir=training_args.cache_dir,
1374
+ attn_implementation=training_args.attn_implementation,
1375
+ torch_dtype=(torch.bfloat16 if training_args.bf16 else None),
1376
+ low_cpu_mem_usage=False,
1377
+ **customized_kwargs,
1378
+ )
1379
+ from transformers.models.mixtral.modeling_mixtral import MixtralSparseMoeBlock
1380
+
1381
+ deepspeed.utils.set_z3_leaf_modules(model, [MixtralSparseMoeBlock])
1382
+ elif "mistral" in model_args.model_name_or_path.lower() or "zephyr" in model_args.model_name_or_path.lower():
1383
+ model = LlavaMistralForCausalLM.from_pretrained(
1384
+ model_args.model_name_or_path,
1385
+ cache_dir=training_args.cache_dir,
1386
+ attn_implementation=training_args.attn_implementation,
1387
+ torch_dtype=(torch.bfloat16 if training_args.bf16 else None),
1388
+ low_cpu_mem_usage=False,
1389
+ **customized_kwargs,
1390
+ )
1391
+ elif (
1392
+ "wizardlm-2" in model_args.model_name_or_path.lower()
1393
+ or "vicuna" in model_args.model_name_or_path.lower()
1394
+ or "llama" in model_args.model_name_or_path.lower()
1395
+ or "yi" in model_args.model_name_or_path.lower()
1396
+ or "nous-hermes" in model_args.model_name_or_path.lower()
1397
+ and "wizard-2" in model_args.model_name_or_path.lower()
1398
+ ):
1399
+ model = LlavaLlamaForCausalLM.from_pretrained(
1400
+ model_args.model_name_or_path,
1401
+ cache_dir=training_args.cache_dir,
1402
+ attn_implementation=training_args.attn_implementation,
1403
+ torch_dtype=(torch.bfloat16 if training_args.bf16 else None),
1404
+ low_cpu_mem_usage=False,
1405
+ **customized_kwargs,
1406
+ )
1407
+ elif "qwen" in model_args.model_name_or_path.lower():
1408
+ if "moe" in model_args.model_name_or_path.lower() or "A14B" in model_args.model_name_or_path:
1409
+ model = LlavaQwenMoeForCausalLM.from_pretrained(
1410
+ model_args.model_name_or_path,
1411
+ cache_dir=training_args.cache_dir,
1412
+ attn_implementation=training_args.attn_implementation,
1413
+ torch_dtype=(torch.bfloat16 if training_args.bf16 else None),
1414
+ low_cpu_mem_usage=False,
1415
+ **customized_kwargs,
1416
+ )
1417
+ from transformers.models.qwen2_moe.modeling_qwen2_moe import Qwen2MoeSparseMoeBlock
1418
+
1419
+ deepspeed.utils.set_z3_leaf_modules(model, [Qwen2MoeSparseMoeBlock])
1420
+ else:
1421
+ model = LlavaQwenForCausalLM.from_pretrained(
1422
+ model_args.model_name_or_path,
1423
+ cache_dir=training_args.cache_dir,
1424
+ attn_implementation=training_args.attn_implementation,
1425
+ torch_dtype=(torch.bfloat16 if training_args.bf16 else None),
1426
+ low_cpu_mem_usage=False,
1427
+ **customized_kwargs,
1428
+ )
1429
+ elif "gemma" in model_args.model_name_or_path.lower():
1430
+ model = LlavaGemmaForCausalLM.from_pretrained(
1431
+ model_args.model_name_or_path,
1432
+ cache_dir=training_args.cache_dir,
1433
+ attn_implementation=training_args.attn_implementation,
1434
+ torch_dtype=(torch.bfloat16 if training_args.bf16 else None),
1435
+ low_cpu_mem_usage=False,
1436
+ **customized_kwargs,
1437
+ )
1438
+ else:
1439
+ raise ValueError(f"Unknown model class {model_args}")
1440
+ else:
1441
+ model = transformers.LlamaForCausalLM.from_pretrained(
1442
+ model_args.model_name_or_path,
1443
+ cache_dir=training_args.cache_dir,
1444
+ attn_implementation=training_args.attn_implementation,
1445
+ torch_dtype=(torch.bfloat16 if training_args.bf16 else None),
1446
+ low_cpu_mem_usage=False,
1447
+ **customized_kwargs,
1448
+ )
1449
+ return model
1450
+
1451
+
1452
+ def train(attn_implementation=None):
1453
+ global local_rank
1454
+
1455
+ parser = transformers.HfArgumentParser((ModelArguments, DataArguments, TrainingArguments))
1456
+ model_args, data_args, training_args = parser.parse_args_into_dataclasses()
1457
+
1458
+ if training_args.verbose_logging:
1459
+ rank0_print(f"Inspecting experiment hyperparameters:\n")
1460
+ rank0_print(f"model_args = {vars(model_args)}\n\n")
1461
+ rank0_print(f"data_args = {vars(data_args)}\n\n")
1462
+ rank0_print(f"training_args = {vars(training_args)}\n\n")
1463
+ # rank0_print(f"evaluation_args = {vars(evaluation_args)}\n\n")
1464
+
1465
+ local_rank = training_args.local_rank
1466
+ compute_dtype = torch.float16 if training_args.fp16 else (torch.bfloat16 if training_args.bf16 else torch.float32)
1467
+
1468
+ bnb_model_from_pretrained_args = {}
1469
+ if training_args.bits in [4, 8]:
1470
+ from transformers import BitsAndBytesConfig
1471
+
1472
+ bnb_model_from_pretrained_args.update(
1473
+ dict(
1474
+ device_map={"": training_args.device},
1475
+ load_in_4bit=training_args.bits == 4,
1476
+ load_in_8bit=training_args.bits == 8,
1477
+ quantization_config=BitsAndBytesConfig(
1478
+ load_in_4bit=training_args.bits == 4,
1479
+ load_in_8bit=training_args.bits == 8,
1480
+ llm_int8_threshold=6.0,
1481
+ llm_int8_has_fp16_weight=False,
1482
+ bnb_4bit_compute_dtype=compute_dtype,
1483
+ bnb_4bit_use_double_quant=training_args.double_quant,
1484
+ bnb_4bit_quant_type=training_args.quant_type, # {'fp4', 'nf4'}
1485
+ ),
1486
+ )
1487
+ )
1488
+
1489
+ model = get_model(model_args, training_args, bnb_model_from_pretrained_args)
1490
+ model.config.use_cache = False
1491
+ if model_args.rope_scaling_factor is not None and model_args.rope_scaling_type is not None:
1492
+ model.config.rope_scaling = {
1493
+ "factor": model_args.rope_scaling_factor,
1494
+ "type": model_args.rope_scaling_type,
1495
+ }
1496
+
1497
+ if model_args.freeze_backbone:
1498
+ model.model.requires_grad_(False)
1499
+
1500
+ if training_args.bits in [4, 8]:
1501
+ from peft import prepare_model_for_kbit_training
1502
+
1503
+ model.config.torch_dtype = torch.float32 if training_args.fp16 else (torch.bfloat16 if training_args.bf16 else torch.float32)
1504
+ model = prepare_model_for_kbit_training(model, use_gradient_checkpointing=training_args.gradient_checkpointing)
1505
+
1506
+ if training_args.gradient_checkpointing:
1507
+ if hasattr(model, "enable_input_require_grads"):
1508
+ model.enable_input_require_grads()
1509
+ else:
1510
+
1511
+ def make_inputs_require_grad(module, input, output):
1512
+ output.requires_grad_(True)
1513
+
1514
+ model.get_input_embeddings().register_forward_hook(make_inputs_require_grad)
1515
+
1516
+ if training_args.lora_enable:
1517
+ from peft import LoraConfig, get_peft_model
1518
+
1519
+ lora_config = LoraConfig(
1520
+ r=training_args.lora_r,
1521
+ lora_alpha=training_args.lora_alpha,
1522
+ target_modules=find_all_linear_names(model),
1523
+ lora_dropout=training_args.lora_dropout,
1524
+ bias=training_args.lora_bias,
1525
+ task_type="CAUSAL_LM",
1526
+ )
1527
+ if training_args.bits == 16:
1528
+ if training_args.bf16:
1529
+ model.to(torch.bfloat16)
1530
+ if training_args.fp16:
1531
+ model.to(torch.float16)
1532
+ rank0_print("Adding LoRA adapters...")
1533
+ model = get_peft_model(model, lora_config)
1534
+
1535
+ if "mistral" in model_args.model_name_or_path.lower() or "mixtral" in model_args.model_name_or_path.lower() or "zephyr" in model_args.model_name_or_path.lower():
1536
+ tokenizer = transformers.AutoTokenizer.from_pretrained(model_args.model_name_or_path, cache_dir=training_args.cache_dir, model_max_length=training_args.model_max_length, padding_side="left")
1537
+ elif "qwen" in model_args.model_name_or_path.lower():
1538
+ tokenizer = transformers.AutoTokenizer.from_pretrained(model_args.model_name_or_path, cache_dir=training_args.cache_dir, model_max_length=training_args.model_max_length, padding_side="right")
1539
+ elif (
1540
+ "wizardlm-2" in model_args.model_name_or_path.lower()
1541
+ or "vicuna" in model_args.model_name_or_path.lower()
1542
+ or "llama" in model_args.model_name_or_path.lower()
1543
+ or "yi" in model_args.model_name_or_path.lower()
1544
+ or "nous-hermes" in model_args.model_name_or_path.lower()
1545
+ and "wizard-2" in model_args.model_name_or_path.lower()
1546
+ ):
1547
+ tokenizer = transformers.AutoTokenizer.from_pretrained(
1548
+ model_args.model_name_or_path,
1549
+ cache_dir=training_args.cache_dir,
1550
+ model_max_length=training_args.model_max_length,
1551
+ padding_side="right",
1552
+ use_fast=False,
1553
+ )
1554
+
1555
+ rank0_print(f"Prompt version: {model_args.version}")
1556
+ if model_args.version == "v0":
1557
+ if tokenizer.pad_token is None:
1558
+ smart_tokenizer_and_embedding_resize(
1559
+ special_tokens_dict=dict(pad_token="[PAD]"),
1560
+ tokenizer=tokenizer,
1561
+ model=model,
1562
+ )
1563
+ elif model_args.version == "v0.5":
1564
+ tokenizer.pad_token = tokenizer.unk_token
1565
+ else:
1566
+ if tokenizer.unk_token is not None:
1567
+ tokenizer.pad_token = tokenizer.unk_token
1568
+ if model_args.version in conversation_lib.conv_templates:
1569
+ conversation_lib.default_conversation = conversation_lib.conv_templates[model_args.version]
1570
+ else:
1571
+ conversation_lib.default_conversation = conversation_lib.conv_templates["vicuna_v1"]
1572
+
1573
+ if model_args.vision_tower is not None:
1574
+ model.get_model().initialize_vision_modules(model_args=model_args, fsdp=training_args.fsdp)
1575
+
1576
+ vision_tower = model.get_vision_tower()
1577
+ vision_tower.to(dtype=torch.bfloat16 if training_args.bf16 else torch.float16, device=training_args.device)
1578
+
1579
+ data_args.image_processor = vision_tower.image_processor
1580
+ data_args.is_multimodal = True
1581
+
1582
+ model.config.image_aspect_ratio = data_args.image_aspect_ratio
1583
+ if data_args.image_grid_pinpoints is not None:
1584
+ if isinstance(data_args.image_grid_pinpoints, str) and "x" in data_args.image_grid_pinpoints:
1585
+ try:
1586
+ patch_size = data_args.image_processor.size[0]
1587
+ except Exception as e:
1588
+ patch_size = data_args.image_processor.size["shortest_edge"]
1589
+
1590
+ assert patch_size in [224, 336, 384, 448, 512], "patch_size should be in [224, 336, 384, 448, 512]"
1591
+ # Use regex to extract the range from the input string
1592
+ matches = re.findall(r"\((\d+)x(\d+)\)", data_args.image_grid_pinpoints)
1593
+ range_start = tuple(map(int, matches[0]))
1594
+ range_end = tuple(map(int, matches[-1]))
1595
+ # Generate a matrix of tuples from (range_start[0], range_start[1]) to (range_end[0], range_end[1])
1596
+ grid_pinpoints = [(i, j) for i in range(range_start[0], range_end[0] + 1) for j in range(range_start[1], range_end[1] + 1)]
1597
+ # Multiply all elements by patch_size
1598
+ data_args.image_grid_pinpoints = [[dim * patch_size for dim in pair] for pair in grid_pinpoints]
1599
+ elif isinstance(data_args.image_grid_pinpoints, str):
1600
+ data_args.image_grid_pinpoints = ast.literal_eval(data_args.image_grid_pinpoints)
1601
+
1602
+ model.config.image_grid_pinpoints = data_args.image_grid_pinpoints
1603
+ model.config.image_crop_resolution = data_args.image_crop_resolution
1604
+ model.config.image_split_resolution = data_args.image_split_resolution
1605
+ model.config.tokenizer_padding_side = tokenizer.padding_side
1606
+ model.config.tokenizer_model_max_length = tokenizer.model_max_length
1607
+ model.config.mm_newline_position = model_args.mm_newline_position
1608
+ model.config.add_faster_video = model_args.add_faster_video
1609
+ model.config.faster_token_stride = model_args.faster_token_stride
1610
+ model.config.add_time_instruction = data_args.add_time_instruction
1611
+ model.config.force_sample = data_args.force_sample
1612
+ model.config.mm_spatial_pool_stride = model_args.mm_spatial_pool_stride
1613
+
1614
+ ### Deciding train which part of the model
1615
+ if model_args.mm_tunable_parts is None: # traditional way of deciding which part to train
1616
+ model.config.tune_mm_mlp_adapter = training_args.tune_mm_mlp_adapter = model_args.tune_mm_mlp_adapter
1617
+ model.config.tune_mm_vision_resampler = training_args.tune_mm_vision_resampler = model_args.tune_mm_vision_resampler
1618
+ if model_args.tune_mm_mlp_adapter or model_args.tune_mm_vision_resampler:
1619
+ model.requires_grad_(False)
1620
+ # Restore LoRA trainability after global freeze
1621
+ if training_args.lora_enable:
1622
+ for name, param in model.named_parameters():
1623
+ if "lora_" in name:
1624
+ param.requires_grad_(True)
1625
+ rank0_print("Restored LoRA parameters to trainable after global freeze (legacy branch).")
1626
+ if model_args.tune_mm_mlp_adapter:
1627
+ for p in model.get_model().mm_projector.parameters():
1628
+ p.requires_grad = True
1629
+ if model_args.tune_mm_vision_resampler:
1630
+ for p in model.get_model().vision_resampler.parameters():
1631
+ p.requires_grad = True
1632
+
1633
+ model.config.freeze_mm_mlp_adapter = training_args.freeze_mm_mlp_adapter
1634
+ if training_args.freeze_mm_mlp_adapter:
1635
+ for p in model.get_model().mm_projector.parameters():
1636
+ p.requires_grad = False
1637
+
1638
+ model.config.freeze_mm_vision_resampler = training_args.freeze_mm_vision_resampler
1639
+ if training_args.freeze_mm_vision_resampler:
1640
+ for p in model.get_model().vision_resampler.parameters():
1641
+ p.requires_grad = False
1642
+
1643
+ model.config.unfreeze_mm_vision_tower = model_args.unfreeze_mm_vision_tower
1644
+ if model_args.unfreeze_mm_vision_tower:
1645
+ vision_tower.requires_grad_(True)
1646
+ else:
1647
+ vision_tower.requires_grad_(False)
1648
+
1649
+ else:
1650
+ rank0_print(f"Using mm_tunable_parts: {model_args.mm_tunable_parts}")
1651
+ model.config.mm_tunable_parts = training_args.mm_tunable_parts = model_args.mm_tunable_parts
1652
+ # Set the entire model to not require gradients by default
1653
+ model.requires_grad_(False)
1654
+ vision_tower.requires_grad_(False)
1655
+ model.get_model().mm_projector.requires_grad_(False)
1656
+ model.get_model().vision_resampler.requires_grad_(False)
1657
+ # Parse the mm_tunable_parts to decide which parts to unfreeze
1658
+ tunable_parts = model_args.mm_tunable_parts.split(",")
1659
+ if "mm_mlp_adapter" in tunable_parts:
1660
+ for p in model.get_model().mm_projector.parameters():
1661
+ p.requires_grad = True
1662
+ if "mm_vision_resampler" in tunable_parts:
1663
+ for p in model.get_model().vision_resampler.parameters():
1664
+ p.requires_grad = True
1665
+ if "mm_vision_tower" in tunable_parts:
1666
+ for name, param in model.named_parameters():
1667
+ if "vision_tower" in name:
1668
+ param.requires_grad_(True)
1669
+ if "mm_language_model" in tunable_parts:
1670
+ if training_args.lora_enable:
1671
+ # LoRA mode: only unfreeze LoRA parameters, keep LLM backbone frozen
1672
+ rank0_print("LoRA enabled: unfreezing only LoRA parameters for LLM.")
1673
+ else:
1674
+ # Full finetune mode: unfreeze entire LLM backbone
1675
+ for name, param in model.named_parameters():
1676
+ if "vision_tower" not in name and "mm_projector" not in name and "vision_resampler" not in name:
1677
+ param.requires_grad_(True)
1678
+
1679
+ # Ensure LoRA parameters are always trainable when lora_enable is True,
1680
+ # regardless of which mm_tunable_parts are specified.
1681
+ # model.requires_grad_(False) above freezes everything including LoRA weights
1682
+ # injected by PEFT, so we must explicitly restore them here.
1683
+ if training_args.lora_enable:
1684
+ lora_param_count = 0
1685
+ for name, param in model.named_parameters():
1686
+ if "lora_" in name:
1687
+ param.requires_grad_(True)
1688
+ lora_param_count += 1
1689
+ rank0_print(f"Restored {lora_param_count} LoRA parameter tensors to trainable.")
1690
+ if "mm_language_model" not in tunable_parts:
1691
+ rank0_print(
1692
+ "WARNING: lora_enable is True but 'mm_language_model' is not in mm_tunable_parts. "
1693
+ "LoRA parameters will still be trained. If you do not intend to train the language "
1694
+ "model at all, consider setting --lora_enable False to avoid unnecessary overhead."
1695
+ )
1696
+
1697
+ total_params = sum(p.ds_numel if hasattr(p, "ds_numel") else p.numel() for p in model.parameters())
1698
+ trainable_params = sum(p.ds_numel if hasattr(p, "ds_numel") else p.numel() for p in model.parameters() if p.requires_grad)
1699
+ rank0_print(f"Total parameters: ~{total_params/1e6:.2f} MB)")
1700
+ rank0_print(f"Trainable parameters: ~{trainable_params/1e6:.2f} MB)")
1701
+ # Print per-group trainable parameter breakdown for verification
1702
+ trainable_groups = {"lora": 0, "mm_projector": 0, "vision_resampler": 0, "vision_tower": 0, "llm_base": 0}
1703
+ for name, p in model.named_parameters():
1704
+ if not p.requires_grad:
1705
+ continue
1706
+ n = p.ds_numel if hasattr(p, "ds_numel") else p.numel()
1707
+ if "lora_" in name:
1708
+ trainable_groups["lora"] += n
1709
+ elif "mm_projector" in name:
1710
+ trainable_groups["mm_projector"] += n
1711
+ elif "vision_resampler" in name:
1712
+ trainable_groups["vision_resampler"] += n
1713
+ elif "vision_tower" in name:
1714
+ trainable_groups["vision_tower"] += n
1715
+ else:
1716
+ trainable_groups["llm_base"] += n
1717
+ rank0_print("Trainable parameter groups: " + ", ".join(f"{k}={v:,}" for k, v in trainable_groups.items()))
1718
+ if training_args.bits in [4, 8]:
1719
+ model.get_model().mm_projector.to(dtype=compute_dtype, device=training_args.device)
1720
+
1721
+ model.config.mm_use_im_start_end = data_args.mm_use_im_start_end = model_args.mm_use_im_start_end
1722
+ model.config.mm_projector_lr = training_args.mm_projector_lr
1723
+ model.config.mm_vision_tower_lr = training_args.mm_vision_tower_lr
1724
+ training_args.use_im_start_end = model_args.mm_use_im_start_end
1725
+ model.config.mm_use_im_patch_token = model_args.mm_use_im_patch_token
1726
+ model.initialize_vision_tokenizer(model_args, tokenizer=tokenizer)
1727
+
1728
+ if training_args.bits in [4, 8]:
1729
+ from peft.tuners.lora import LoraLayer
1730
+
1731
+ for name, module in model.named_modules():
1732
+ if isinstance(module, LoraLayer):
1733
+ if training_args.bf16:
1734
+ module = module.to(torch.bfloat16)
1735
+ if "norm" in name:
1736
+ module = module.to(torch.float32)
1737
+ if "lm_head" in name or "embed_tokens" in name:
1738
+ if hasattr(module, "weight"):
1739
+ if training_args.bf16 and module.weight.dtype == torch.float32:
1740
+ module = module.to(torch.bfloat16)
1741
+
1742
+ data_module = make_supervised_data_module(tokenizer=tokenizer, data_args=data_args)
1743
+ trainer = LLaVATrainer(model=model, tokenizer=tokenizer, args=training_args, **data_module)
1744
+
1745
+ if list(pathlib.Path(training_args.output_dir).glob("checkpoint-*")):
1746
+ trainer.train(resume_from_checkpoint=True)
1747
+ else:
1748
+ trainer.train()
1749
+ trainer.save_state()
1750
+
1751
+ model.config.use_cache = True
1752
+
1753
+ if training_args.lora_enable:
1754
+ state_dict = get_peft_state_maybe_zero_3(model.named_parameters(), training_args.lora_bias)
1755
+ non_lora_state_dict = get_peft_state_non_lora_maybe_zero_3(model.named_parameters())
1756
+ if training_args.local_rank == 0 or training_args.local_rank == -1:
1757
+ if hasattr(model, "config"):
1758
+ model.config.save_pretrained(training_args.output_dir)
1759
+ if hasattr(model, "generation_config"):
1760
+ model.generation_config.save_pretrained(training_args.output_dir)
1761
+ model.save_pretrained(training_args.output_dir, state_dict=state_dict)
1762
+ torch.save(non_lora_state_dict, os.path.join(training_args.output_dir, "non_lora_trainables.bin"))
1763
+ else:
1764
+ safe_save_model_for_hf_trainer(trainer=trainer, output_dir=training_args.output_dir)
1765
+
1766
+ rank0_print(f"Model saved to {training_args.output_dir}")
1767
+
1768
+
1769
+ if __name__ == "__main__":
1770
+ train()
之前的代码版本/第一版-全部代码/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/llava/train/train_dpo.py ADDED
@@ -0,0 +1,1828 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Adopted from https://github.com/lm-sys/FastChat. Below is the original copyright:
2
+ # Adopted from tatsu-lab@stanford_alpaca. Below is the original copyright:
3
+ # Copyright 2023 Rohan Taori, Ishaan Gulrajani, Tianyi Zhang, Yann Dubois, Xuechen Li
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+
17
+ import os
18
+ import copy
19
+ import deepspeed
20
+ from dataclasses import dataclass, field
21
+ import json
22
+ import logging
23
+ import pathlib
24
+ from typing import Dict, Optional, Sequence, List
25
+ import ast
26
+
27
+ import yaml
28
+ import time
29
+ import random
30
+ import yaml
31
+ import math
32
+ import re
33
+ import torch
34
+
35
+ import transformers
36
+ import tokenizers
37
+
38
+ from llava.constants import IGNORE_INDEX, DEFAULT_IMAGE_TOKEN, DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN, IMAGE_TOKEN_INDEX
39
+ from torch.utils.data import Dataset
40
+ from llava.train.llava_trainer import LLaVADPOTrainer
41
+ from data_processing.utils import load_jsonl, load_json
42
+ from llava import conversation as conversation_lib
43
+ from llava.model import *
44
+ from llava.model.language_model.llava_qwen import LlavaQwenConfig
45
+ from llava.model.language_model.llava_llama import LlavaConfig
46
+ from llava.model.language_model.llava_mistral import LlavaMistralConfig
47
+ from llava.mm_utils import process_highres_image, process_anyres_image, process_highres_image_crop_split, tokenizer_image_token
48
+ from llava.utils import rank0_print
49
+ from transformers import AutoConfig
50
+ import pickle
51
+
52
+ from trl.trainer.utils import DPODataCollatorWithPadding
53
+ from PIL import Image, ImageFile
54
+ from decord import VideoReader, cpu
55
+
56
+ ImageFile.LOAD_TRUNCATED_IMAGES = True
57
+ from packaging import version
58
+ from typing import Any
59
+
60
+ local_rank = None
61
+ import numpy as np
62
+
63
+ IS_TOKENIZER_GREATER_THAN_0_14 = version.parse(tokenizers.__version__) >= version.parse("0.14")
64
+
65
+
66
+ @dataclass
67
+ class ModelArguments:
68
+ model_name_or_path: Optional[str] = field(default="facebook/opt-125m")
69
+ model_class_name: Optional[str] = field(default=None, metadata={"help": "Used to init model class, format is XXXXForCausalLM. e.g. currently XXXX is chosen from LlavaLlama, LlavaMixtral, LlavaMistral, Llama"})
70
+
71
+ mm_tunable_parts: Optional[str] = field(
72
+ default=None, metadata={"help": 'Could be "mm_mlp_adapter", "mm_vision_resampler", "mm_vision_tower,mm_mlp_adapter,mm_language_model", "mm_vision_tower,mm_mlp_adapter,mm_language_model", "mm_mlp_adapter,mm_language_model"'}
73
+ )
74
+ # deciding which part of the multimodal model to tune, will overwrite other previous settings
75
+
76
+ version: Optional[str] = field(default="v0")
77
+ freeze_backbone: bool = field(default=False)
78
+ tune_mm_mlp_adapter: bool = field(default=False)
79
+ tune_mm_vision_resampler: bool = field(default=False)
80
+ vision_tower: Optional[str] = field(default=None)
81
+ vision_tower_pretrained: Optional[str] = field(default=None) # default to the last layer
82
+
83
+ unfreeze_mm_vision_tower: bool = field(default=False)
84
+ unfreeze_language_model: bool = field(default=False)
85
+ mm_vision_select_layer: Optional[int] = field(default=-1) # default to the last layer
86
+ pretrain_mm_mlp_adapter: Optional[str] = field(default=None)
87
+ mm_projector_type: Optional[str] = field(default="linear")
88
+ mm_use_im_start_end: bool = field(default=False)
89
+ mm_use_im_patch_token: bool = field(default=True)
90
+ mm_patch_merge_type: Optional[str] = field(default="flat")
91
+ mm_vision_select_feature: Optional[str] = field(default="patch")
92
+ mm_resampler_type: Optional[str] = field(default=None)
93
+ mm_mask_drop_mode: str = field(default="fixed")
94
+ mm_mask_drop_skip_percentage: float = field(default=0.0)
95
+ mm_mask_drop_ratio: float = field(default=0.25)
96
+ mm_mask_drop_ratio_upper: Optional[float] = field(default=None)
97
+ mm_mask_drop_ratio_lower: Optional[float] = field(default=None)
98
+ mm_spatial_pool_stride: Optional[int] = field(default=None)
99
+ mm_spatial_pool_mode: str = field(default="average")
100
+ mm_spatial_pool_out_channels: Optional[int] = field(default=None)
101
+ mm_perceiver_depth: Optional[int] = field(default=3)
102
+ mm_perceiver_latents: Optional[int] = field(default=32)
103
+ mm_perceiver_ff_mult: Optional[float] = field(default=4)
104
+ mm_perceiver_pretrained: Optional[str] = field(default=None)
105
+ mm_qformer_depth: Optional[int] = field(default=3)
106
+ mm_qformer_latents: Optional[int] = field(default=32)
107
+ mm_qformer_pretrained: Optional[str] = field(default=None)
108
+
109
+ rope_scaling_factor: Optional[float] = field(default=None)
110
+ rope_scaling_type: Optional[str] = field(default=None)
111
+
112
+ s2: Optional[bool] = field(default=False)
113
+ s2_scales: Optional[str] = field(default="336,672,1008")
114
+
115
+
116
+ @dataclass
117
+ class DataArguments:
118
+ data_path: str = field(default=None, metadata={"help": "Path to the training data, in llava's instruction.json format. Supporting multiple json files via /path/to/{a,b,c}.json"})
119
+ lazy_preprocess: bool = False
120
+ is_multimodal: bool = False
121
+ image_folder: Optional[str] = field(default=None)
122
+ video_folder: Optional[str] = field(default=None)
123
+ video_fps: Optional[int] = field(default=1)
124
+ image_aspect_ratio: str = "square"
125
+ image_grid_pinpoints: Optional[str] = field(default=None)
126
+ image_crop_resolution: int = 384
127
+ image_split_resolution: int = 384
128
+ input_prompt: Optional[str] = field(default=None)
129
+ refine_prompt: Optional[bool] = field(default=False)
130
+ frames_upbound: Optional[int] = field(default=0)
131
+ num_sample: Optional[int] = field(default=None)
132
+
133
+
134
+ @dataclass
135
+ class TrainingArguments(transformers.TrainingArguments):
136
+ cache_dir: Optional[str] = field(default=None)
137
+ optim: str = field(default="adamw_torch")
138
+ remove_unused_columns: bool = field(default=False)
139
+ freeze_mm_mlp_adapter: bool = field(default=False)
140
+ freeze_mm_vision_resampler: bool = field(default=False)
141
+ mpt_attn_impl: Optional[str] = field(default="triton")
142
+ model_max_length: int = field(
143
+ default=4096,
144
+ metadata={"help": "Maximum sequence length. Sequences will be right padded (and possibly truncated)."},
145
+ )
146
+ double_quant: bool = field(default=True, metadata={"help": "Compress the quantization statistics through double quantization."})
147
+ quant_type: str = field(default="nf4", metadata={"help": "Quantization data type to use. Should be one of `fp4` or `nf4`."})
148
+ bits: int = field(default=16, metadata={"help": "How many bits to use."})
149
+ lora_enable: bool = False
150
+ lora_r: int = 64
151
+ lora_alpha: int = 16
152
+ lora_dropout: float = 0.05
153
+ lora_weight_path: str = ""
154
+ lora_bias: str = "none"
155
+ mm_projector_lr: Optional[float] = None
156
+ mm_vision_tower_lr: Optional[float] = None
157
+ group_by_varlen: bool = field(default=False)
158
+ group_by_modality_length: bool = field(default=False)
159
+ group_by_modality_length_auto: bool = field(default=False)
160
+ auto_find_batch_size: bool = field(default=False)
161
+ gradient_checkpointing: bool = field(default=True)
162
+ verbose_logging: bool = field(default=False)
163
+ attn_implementation: str = field(default="flash_attention_2", metadata={"help": "Use transformers attention implementation."})
164
+ dpo_alpha: float = field(default=1.0)
165
+ beta: float = field(default=0.1)
166
+ gamma: float = field(default=1.0)
167
+ generate_during_eval: bool = field(default=False)
168
+ precompute_ref_log_probs: bool = field(default=False)
169
+
170
+
171
+ def maybe_zero_3(param, ignore_status=False, name=None):
172
+ from deepspeed import zero
173
+ from deepspeed.runtime.zero.partition_parameters import ZeroParamStatus
174
+
175
+ if hasattr(param, "ds_id"):
176
+ if param.ds_status == ZeroParamStatus.NOT_AVAILABLE:
177
+ if not ignore_status:
178
+ logging.warning(f"{name}: param.ds_status != ZeroParamStatus.NOT_AVAILABLE: {param.ds_status}")
179
+ with zero.GatheredParameters([param]):
180
+ param = param.data.detach().cpu().clone()
181
+ else:
182
+ param = param.detach().cpu().clone()
183
+ return param
184
+
185
+
186
+ # Borrowed from peft.utils.get_peft_model_state_dict
187
+ def get_peft_state_maybe_zero_3(named_params, bias):
188
+ if bias == "none":
189
+ to_return = {k: t for k, t in named_params if "lora_" in k}
190
+ elif bias == "all":
191
+ to_return = {k: t for k, t in named_params if "lora_" in k or "bias" in k}
192
+ elif bias == "lora_only":
193
+ to_return = {}
194
+ maybe_lora_bias = {}
195
+ lora_bias_names = set()
196
+ for k, t in named_params:
197
+ if "lora_" in k:
198
+ to_return[k] = t
199
+ bias_name = k.split("lora_")[0] + "bias"
200
+ lora_bias_names.add(bias_name)
201
+ elif "bias" in k:
202
+ maybe_lora_bias[k] = t
203
+ for k, t in maybe_lora_bias:
204
+ if bias_name in lora_bias_names:
205
+ to_return[bias_name] = t
206
+ else:
207
+ raise NotImplementedError
208
+ to_return = {k: maybe_zero_3(v, ignore_status=True) for k, v in to_return.items()}
209
+ return to_return
210
+
211
+
212
+ def get_peft_state_non_lora_maybe_zero_3(named_params, require_grad_only=True):
213
+ to_return = {k: t for k, t in named_params if "lora_" not in k}
214
+ if require_grad_only:
215
+ to_return = {k: t for k, t in to_return.items() if t.requires_grad}
216
+ to_return = {k: maybe_zero_3(v, ignore_status=True).cpu() for k, v in to_return.items()}
217
+ return to_return
218
+
219
+
220
+ def get_mm_adapter_state_maybe_zero_3(named_params, keys_to_match):
221
+ to_return = {k: t for k, t in named_params if any(key_match in k for key_match in keys_to_match)}
222
+ to_return = {k: maybe_zero_3(v, ignore_status=True).cpu() for k, v in to_return.items()}
223
+ return to_return
224
+
225
+
226
+ def find_all_linear_names(model):
227
+ cls = torch.nn.Linear
228
+ lora_module_names = set()
229
+ multimodal_keywords = ["mm_projector", "vision_tower", "vision_resampler"]
230
+ for name, module in model.named_modules():
231
+ if any(mm_keyword in name for mm_keyword in multimodal_keywords):
232
+ continue
233
+ if isinstance(module, cls):
234
+ names = name.split(".")
235
+ lora_module_names.add(names[0] if len(names) == 1 else names[-1])
236
+
237
+ if "lm_head" in lora_module_names: # needed for 16-bit
238
+ lora_module_names.remove("lm_head")
239
+ return list(lora_module_names)
240
+
241
+
242
+ def safe_save_model_for_hf_trainer(trainer: transformers.Trainer, output_dir: str):
243
+ """Collects the state dict and dump to disk."""
244
+ if hasattr(trainer.args, "tune_mm_mlp_adapter") and trainer.args.tune_mm_mlp_adapter:
245
+ check_only_save_mm_adapter_tunnable = True
246
+ # only has mm_mlp_adapter and mm_vision_resampler in the tuneable parts
247
+ elif hasattr(trainer.args, "mm_tunable_parts") and (len(trainer.args.mm_tunable_parts.split(",")) == 1 and ("mm_mlp_adapter" in trainer.args.mm_tunable_parts or "mm_vision_resampler" in trainer.args.mm_tunable_parts)):
248
+ check_only_save_mm_adapter_tunnable = True
249
+ else:
250
+ check_only_save_mm_adapter_tunnable = False
251
+
252
+ trainer.accelerator.wait_for_everyone()
253
+ torch.cuda.synchronize()
254
+ rank0_print(f"Only save projectors: {check_only_save_mm_adapter_tunnable}")
255
+ if check_only_save_mm_adapter_tunnable:
256
+ # Only save Adapter
257
+ keys_to_match = ["mm_projector", "vision_resampler"]
258
+ if getattr(trainer.args, "use_im_start_end", False):
259
+ keys_to_match.extend(["embed_tokens", "embed_in"])
260
+
261
+ weight_to_save = get_mm_adapter_state_maybe_zero_3(trainer.model.named_parameters(), keys_to_match)
262
+ trainer.model.config.save_pretrained(output_dir)
263
+
264
+ current_folder = output_dir.split("/")[-1]
265
+ parent_folder = os.path.dirname(output_dir)
266
+ if trainer.args.local_rank == 0 or trainer.args.local_rank == -1:
267
+ if current_folder.startswith("checkpoint-"):
268
+ mm_projector_folder = os.path.join(parent_folder, "mm_projector")
269
+ os.makedirs(mm_projector_folder, exist_ok=True)
270
+ torch.save(weight_to_save, os.path.join(mm_projector_folder, f"{current_folder}.bin"))
271
+ else:
272
+ torch.save(weight_to_save, os.path.join(output_dir, f"mm_projector.bin"))
273
+ return
274
+
275
+ if trainer.deepspeed:
276
+ trainer.save_model(output_dir)
277
+ return
278
+
279
+ state_dict = trainer.model.state_dict()
280
+ if trainer.args.should_save:
281
+ cpu_state_dict = {key: value.cpu() for key, value in state_dict.items()}
282
+ del state_dict
283
+ trainer._save(output_dir, state_dict=cpu_state_dict) # noqa
284
+
285
+
286
+ def smart_tokenizer_and_embedding_resize(
287
+ special_tokens_dict: Dict,
288
+ tokenizer: transformers.PreTrainedTokenizer,
289
+ model: transformers.PreTrainedModel,
290
+ ):
291
+ """Resize tokenizer and embedding.
292
+
293
+ Note: This is the unoptimized version that may make your embedding size not be divisible by 64.
294
+ """
295
+ num_new_tokens = tokenizer.add_special_tokens(special_tokens_dict)
296
+ model.resize_token_embeddings(len(tokenizer))
297
+
298
+ if num_new_tokens > 0:
299
+ input_embeddings = model.get_input_embeddings().weight.data
300
+ output_embeddings = model.get_output_embeddings().weight.data
301
+
302
+ input_embeddings_avg = input_embeddings[:-num_new_tokens].mean(dim=0, keepdim=True)
303
+ output_embeddings_avg = output_embeddings[:-num_new_tokens].mean(dim=0, keepdim=True)
304
+
305
+ input_embeddings[-num_new_tokens:] = input_embeddings_avg
306
+ output_embeddings[-num_new_tokens:] = output_embeddings_avg
307
+
308
+
309
+ def _tokenize_fn(strings: Sequence[str], tokenizer: transformers.PreTrainedTokenizer) -> Dict:
310
+ """Tokenize a list of strings."""
311
+ tokenized_list = [
312
+ tokenizer(
313
+ text,
314
+ return_tensors="pt",
315
+ padding="longest",
316
+ max_length=tokenizer.model_max_length,
317
+ truncation=True,
318
+ )
319
+ for text in strings
320
+ ]
321
+ input_ids = labels = [tokenized.input_ids[0] for tokenized in tokenized_list]
322
+ input_ids_lens = labels_lens = [tokenized.input_ids.ne(tokenizer.pad_token_id).sum().item() for tokenized in tokenized_list]
323
+ return dict(
324
+ input_ids=input_ids,
325
+ labels=labels,
326
+ input_ids_lens=input_ids_lens,
327
+ labels_lens=labels_lens,
328
+ )
329
+
330
+
331
+ def _mask_targets(target, tokenized_lens, speakers):
332
+ # cur_idx = 0
333
+ cur_idx = tokenized_lens[0]
334
+ tokenized_lens = tokenized_lens[1:]
335
+ target[:cur_idx] = IGNORE_INDEX
336
+ for tokenized_len, speaker in zip(tokenized_lens, speakers):
337
+ if speaker == "human":
338
+ target[cur_idx + 2 : cur_idx + tokenized_len] = IGNORE_INDEX
339
+ cur_idx += tokenized_len
340
+
341
+
342
+ def _add_speaker_and_signal(header, source, get_conversation=True):
343
+ """Add speaker and start/end signal on each round."""
344
+ BEGIN_SIGNAL = "### "
345
+ END_SIGNAL = "\n"
346
+ conversation = header
347
+ for sentence in source:
348
+ from_str = sentence["from"]
349
+ if from_str.lower() == "human":
350
+ from_str = conversation_lib.default_conversation.roles[0]
351
+ elif from_str.lower() == "gpt":
352
+ from_str = conversation_lib.default_conversation.roles[1]
353
+ else:
354
+ from_str = "unknown"
355
+ sentence["value"] = BEGIN_SIGNAL + from_str + ": " + sentence["value"] + END_SIGNAL
356
+ if get_conversation:
357
+ conversation += sentence["value"]
358
+ conversation += BEGIN_SIGNAL
359
+ return conversation
360
+
361
+
362
+ def preprocess_multimodal(sources: Sequence[str], data_args: DataArguments) -> Dict:
363
+ is_multimodal = data_args.is_multimodal
364
+ if not is_multimodal:
365
+ return sources
366
+
367
+ for source in sources:
368
+ for sentence in source:
369
+ if DEFAULT_IMAGE_TOKEN in sentence["value"] and not sentence["value"].startswith(DEFAULT_IMAGE_TOKEN):
370
+ sentence["value"] = sentence["value"].replace(DEFAULT_IMAGE_TOKEN, "").strip()
371
+ sentence["value"] = DEFAULT_IMAGE_TOKEN + "\n" + sentence["value"]
372
+ sentence["value"] = sentence["value"].strip()
373
+ if "mmtag" in conversation_lib.default_conversation.version:
374
+ sentence["value"] = sentence["value"].replace(DEFAULT_IMAGE_TOKEN, "<Image>" + DEFAULT_IMAGE_TOKEN + "</Image>")
375
+ replace_token = DEFAULT_IMAGE_TOKEN
376
+ if data_args.mm_use_im_start_end:
377
+ replace_token = DEFAULT_IM_START_TOKEN + replace_token + DEFAULT_IM_END_TOKEN
378
+ sentence["value"] = sentence["value"].replace(DEFAULT_IMAGE_TOKEN, replace_token)
379
+
380
+ return sources
381
+
382
+
383
+ def preprocess_multimodal_movie(sources: Sequence[str], data_args: DataArguments, video_inputs: str) -> Dict:
384
+ is_multimodal = data_args.is_multimodal
385
+ if not is_multimodal:
386
+ return sources
387
+
388
+ for source in sources:
389
+ for sentence in source:
390
+ if DEFAULT_IMAGE_TOKEN in sentence["value"]:
391
+ prompt = sentence["value"].replace(DEFAULT_IMAGE_TOKEN, "").strip()
392
+ replace_token = video_inputs
393
+ if data_args.mm_use_im_start_end:
394
+ replace_token = DEFAULT_IM_START_TOKEN + replace_token + DEFAULT_IM_END_TOKEN
395
+ sentence["value"] = sentence["value"].replace(DEFAULT_IMAGE_TOKEN, replace_token)
396
+
397
+ return sources, prompt
398
+
399
+
400
+ def preprocess_llama_2(sources, tokenizer: transformers.PreTrainedTokenizer, has_image: bool = False) -> Dict:
401
+ conv = conversation_lib.default_conversation.copy()
402
+ roles = {"human": conv.roles[0], "gpt": conv.roles[1]}
403
+
404
+ # Apply prompt templates
405
+ conversations = []
406
+ for i, source in enumerate(sources):
407
+ if roles[source[0]["from"]] != conv.roles[0]:
408
+ # Skip the first one if it is not from human
409
+ source = source[1:]
410
+
411
+ conv.messages = []
412
+ for j, sentence in enumerate(source):
413
+ role = roles[sentence["from"]]
414
+ assert role == conv.roles[j % 2], f"{i}"
415
+ conv.append_message(role, sentence["value"])
416
+ conversations.append(conv.get_prompt())
417
+
418
+ # Tokenize conversations
419
+
420
+ if has_image:
421
+ input_ids = torch.stack([tokenizer_image_token(prompt, tokenizer, return_tensors="pt") for prompt in conversations], dim=0)
422
+ else:
423
+ input_ids = tokenizer(
424
+ conversations,
425
+ return_tensors="pt",
426
+ padding="longest",
427
+ max_length=tokenizer.model_max_length,
428
+ truncation=True,
429
+ ).input_ids
430
+
431
+ targets = input_ids.clone()
432
+
433
+ assert conv.sep_style == conversation_lib.SeparatorStyle.LLAMA_2
434
+
435
+ # Mask targets
436
+ sep = "[/INST] "
437
+ for conversation, target in zip(conversations, targets):
438
+ total_len = int(target.ne(tokenizer.pad_token_id).sum())
439
+
440
+ rounds = conversation.split(conv.sep2)
441
+ cur_len = 1
442
+ target[:cur_len] = IGNORE_INDEX
443
+ for i, rou in enumerate(rounds):
444
+ if rou == "":
445
+ break
446
+
447
+ parts = rou.split(sep)
448
+ if len(parts) != 2:
449
+ break
450
+ parts[0] += sep
451
+
452
+ if has_image:
453
+ round_len = len(tokenizer_image_token(rou, tokenizer))
454
+ instruction_len = len(tokenizer_image_token(parts[0], tokenizer)) - 2
455
+ else:
456
+ round_len = len(tokenizer(rou).input_ids)
457
+ instruction_len = len(tokenizer(parts[0]).input_ids) - 2
458
+
459
+ target[cur_len : cur_len + instruction_len] = IGNORE_INDEX
460
+
461
+ cur_len += round_len
462
+ target[cur_len:] = IGNORE_INDEX
463
+
464
+ if cur_len < tokenizer.model_max_length:
465
+ if cur_len != total_len:
466
+ target[:] = IGNORE_INDEX
467
+ rank0_print(f"WARNING: tokenization mismatch: {cur_len} vs. {total_len}." f" (ignored)")
468
+
469
+ return dict(
470
+ input_ids=input_ids,
471
+ labels=targets,
472
+ )
473
+
474
+
475
+ def make_conv(prompt, answer):
476
+ return [
477
+ {
478
+ "from": "human",
479
+ "value": prompt,
480
+ },
481
+ {
482
+ "from": "gpt",
483
+ "value": answer,
484
+ },
485
+ ]
486
+
487
+
488
+ def preprocess_gemma(sources: List[List[Dict[str, str]]], tokenizer: transformers.PreTrainedTokenizer, has_image: bool = False) -> Dict:
489
+ conv: conversation_lib.Conversation = conversation_lib.default_conversation.copy()
490
+ roles: Dict[str, str] = {"human": conv.roles[0], "gpt": conv.roles[1]}
491
+
492
+ # Apply prompt templates
493
+ conversations: List[str] = []
494
+ for i, source in enumerate(sources):
495
+ if roles[source[0]["from"]] != conv.roles[0]:
496
+ # Skip the first one if it is not from human
497
+ source: List[Dict[str, str]] = source[1:]
498
+
499
+ conv.messages = []
500
+ for j, sentence in enumerate(source):
501
+ role: str = roles[sentence["from"]]
502
+ assert role == conv.roles[j % 2], f"{i}"
503
+ conv.append_message(role, sentence["value"])
504
+ conversations.append(conv.get_prompt())
505
+
506
+ # Tokenize conversations
507
+ if has_image:
508
+ input_ids: torch.Tensor = torch.stack([tokenizer_image_token(prompt, tokenizer, return_tensors="pt") for prompt in conversations], dim=0)
509
+ else:
510
+ input_ids: torch.Tensor = tokenizer(
511
+ conversations,
512
+ return_tensors="pt",
513
+ padding="longest",
514
+ max_length=tokenizer.model_max_length,
515
+ truncation=True,
516
+ ).input_ids
517
+
518
+ targets: torch.Tensor = input_ids.clone()
519
+ assert conv.sep_style == conversation_lib.SeparatorStyle.GEMMA
520
+
521
+ # Mask target
522
+ sep: str = conv.sep + conv.roles[1]
523
+ for conversation, target in zip(conversations, targets):
524
+ total_len: int = int(target.ne(tokenizer.pad_token_id).sum())
525
+
526
+ rounds: List[str] = conversation.split(conv.sep)
527
+ re_rounds = []
528
+ for conv_idx in range(0, len(rounds), 2):
529
+ re_rounds.append(conv.sep.join(rounds[conv_idx : conv_idx + 2]))
530
+
531
+ cur_len = 1 # Ignore <bos>
532
+ target[:cur_len] = IGNORE_INDEX
533
+ for i, rou in enumerate(re_rounds):
534
+ if rou == "":
535
+ break
536
+
537
+ parts = rou.split(sep)
538
+ if len(parts) != 2:
539
+ break
540
+ parts[0] += sep # Re-append sep because split on this
541
+ # Now "".join(parts)==rou
542
+
543
+ if has_image:
544
+ round_len = len(tokenizer_image_token(rou, tokenizer)) - 1 # Ignore <bos>
545
+ instruction_len = len(tokenizer_image_token(parts[0], tokenizer)) - 1 # Ignore <bos>
546
+ else:
547
+ round_len = len(tokenizer(rou).input_ids) - 1 # Ignore <bos>
548
+ instruction_len = len(tokenizer(parts[0]).input_ids) - 1 # Ignore <bos>
549
+
550
+ round_len += 2 # sep: <end_of_turn>\n takes 2 tokens
551
+ target[cur_len : cur_len + instruction_len] = IGNORE_INDEX
552
+ cur_len += round_len
553
+
554
+ target[cur_len:] = IGNORE_INDEX
555
+
556
+ if cur_len < tokenizer.model_max_length:
557
+ if cur_len != total_len:
558
+ target[:] = IGNORE_INDEX
559
+ rank0_print(f"WARNING: tokenization mismatch: {cur_len} vs. {total_len}." f" (ignored)")
560
+
561
+ return dict(
562
+ input_ids=input_ids,
563
+ labels=targets,
564
+ )
565
+
566
+
567
+ def preprocess_qwen(sources, tokenizer: transformers.PreTrainedTokenizer, has_image: bool = False, max_len=2048, system_message: str = "You are a helpful assistant.") -> Dict:
568
+ roles = {"human": "<|im_start|>user", "gpt": "<|im_start|>assistant"}
569
+
570
+ im_start, im_end = tokenizer.additional_special_tokens_ids
571
+ nl_tokens = tokenizer("\n").input_ids
572
+ _system = tokenizer("system").input_ids + nl_tokens
573
+ _user = tokenizer("user").input_ids + nl_tokens
574
+ _assistant = tokenizer("assistant").input_ids + nl_tokens
575
+
576
+ # Apply prompt templates
577
+ input_ids, targets = [], []
578
+ for i, source in enumerate(sources):
579
+ if roles[source[0]["from"]] != roles["human"]:
580
+ source = source[1:]
581
+
582
+ input_id, target = [], []
583
+ system = [im_start] + _system + tokenizer(system_message).input_ids + [im_end] + nl_tokens
584
+ input_id += system
585
+ target += [im_start] + [IGNORE_INDEX] * (len(system) - 3) + [im_end] + nl_tokens
586
+ assert len(input_id) == len(target)
587
+ for j, sentence in enumerate(source):
588
+ role = roles[sentence["from"]]
589
+ if has_image and "<image>" in sentence["value"]:
590
+ assert sentence["value"].startswith("<image>"), print(sentence["value"])
591
+
592
+ _input_id = tokenizer(role).input_ids + nl_tokens + [IMAGE_TOKEN_INDEX] + nl_tokens + tokenizer(sentence["value"][len("<image>") :]).input_ids + [im_end] + nl_tokens
593
+ else:
594
+ _input_id = tokenizer(role).input_ids + nl_tokens + tokenizer(sentence["value"]).input_ids + [im_end] + nl_tokens
595
+ input_id += _input_id
596
+ if role == "<|im_start|>user":
597
+ _target = [im_start] + [IGNORE_INDEX] * (len(_input_id) - 3) + [im_end] + nl_tokens
598
+ elif role == "<|im_start|>assistant":
599
+ _target = [im_start] + [IGNORE_INDEX] * len(tokenizer(role).input_ids) + _input_id[len(tokenizer(role).input_ids) + 1 : -2] + [im_end] + nl_tokens
600
+ else:
601
+ raise NotImplementedError
602
+ target += _target
603
+ assert len(input_id) == len(target)
604
+ # input_id += [tokenizer.pad_token_id] * (max_len - len(input_id))
605
+ # target += [IGNORE_INDEX] * (max_len - len(target))
606
+ input_ids.append(input_id)
607
+ targets.append(target)
608
+ input_ids = torch.tensor(input_ids, dtype=torch.long)
609
+ targets = torch.tensor(targets, dtype=torch.long)
610
+
611
+ return dict(
612
+ input_ids=input_ids, # tensor(bs x seq_len)
613
+ labels=targets, # tensor(bs x seq_len)
614
+ # attention_mask=input_ids.ne(tokenizer.pad_token_id), # tensor(bs x seq_len)
615
+ )
616
+
617
+
618
+ def preprocess_llama3(
619
+ sources,
620
+ tokenizer: transformers.PreTrainedTokenizer,
621
+ has_image: bool = False,
622
+ max_len=2048,
623
+ system_message: str = "You are a helpful language and vision assistant. You are able to understand the visual content that the user provides, and assist the user with a variety of tasks using natural language.",
624
+ ) -> Dict:
625
+ roles = {"human": "<|start_header_id|>user<|end_header_id|>", "gpt": "<|start_header_id|>assistant<|end_header_id|>"}
626
+
627
+ eot_id = tokenizer.convert_tokens_to_ids("<|eot_id|>")
628
+ nl_tokens = tokenizer("\n").input_ids
629
+
630
+ # Apply prompt templates
631
+ input_ids, targets = [], []
632
+ for i, source in enumerate(sources):
633
+ if roles[source[0]["from"]] != roles["human"]:
634
+ source = source[1:]
635
+
636
+ input_id, target = [], []
637
+ system = tokenizer("<|begin_of_text|>").input_ids + tokenizer("<|start_header_id|>system<|end_header_id|>").input_ids + nl_tokens * 2 + tokenizer(system_message).input_ids + [eot_id]
638
+ input_id += system
639
+ target += [IGNORE_INDEX] * len(system)
640
+ for j, sentence in enumerate(source):
641
+ role = roles[sentence["from"]]
642
+ if has_image and "<image>" in sentence["value"]:
643
+ assert sentence["value"].startswith("<image>"), print(sentence["value"])
644
+ _input_id = tokenizer(role).input_ids + nl_tokens * 2 + [IMAGE_TOKEN_INDEX] + tokenizer(sentence["value"][len("<image>") :]).input_ids + [eot_id]
645
+ else:
646
+ _input_id = tokenizer(role).input_ids + nl_tokens * 2 + tokenizer(sentence["value"]).input_ids + [eot_id]
647
+ input_id += _input_id
648
+ if role == "<|start_header_id|>user<|end_header_id|>":
649
+ _target = [IGNORE_INDEX] * len(_input_id)
650
+ elif role == "<|start_header_id|>assistant<|end_header_id|>":
651
+ _target = [IGNORE_INDEX] * (len(tokenizer(role).input_ids) + 2) + _input_id[len(tokenizer(role).input_ids) + 2 : -1] + [eot_id]
652
+ else:
653
+ raise NotImplementedError
654
+ target += _target
655
+ assert len(input_id) == len(target), f"{len(input_id)} != {len(target)}"
656
+ input_ids.append(input_id)
657
+ targets.append(target)
658
+ input_ids = torch.tensor(input_ids, dtype=torch.long)
659
+ targets = torch.tensor(targets, dtype=torch.long)
660
+
661
+ return dict(
662
+ input_ids=input_ids, # tensor(bs x seq_len)
663
+ labels=targets, # tensor(bs x seq_len)
664
+ )
665
+
666
+
667
+ def preprocess_v1(sources, tokenizer: transformers.PreTrainedTokenizer, has_image: bool = False) -> Dict:
668
+ conv = conversation_lib.default_conversation.copy()
669
+ roles = {"human": conv.roles[0], "gpt": conv.roles[1]}
670
+
671
+ # Apply prompt templates
672
+ conversations = []
673
+ for i, source in enumerate(sources):
674
+ if roles[source[0]["from"]] != conv.roles[0]:
675
+ # Skip the first one if it is not from human
676
+ source = source[1:]
677
+
678
+ conv.messages = []
679
+ for j, sentence in enumerate(source):
680
+ role = roles[sentence["from"]]
681
+ assert role == conv.roles[j % 2], f"{i}"
682
+ conv.append_message(role, sentence["value"])
683
+ conversations.append(conv.get_prompt())
684
+
685
+ # Tokenize conversations
686
+
687
+ if has_image:
688
+ input_ids = torch.stack([tokenizer_image_token(prompt, tokenizer, return_tensors="pt") for prompt in conversations], dim=0)
689
+ else:
690
+ input_ids = tokenizer(
691
+ conversations,
692
+ return_tensors="pt",
693
+ padding="longest",
694
+ max_length=tokenizer.model_max_length,
695
+ truncation=True,
696
+ ).input_ids
697
+
698
+ targets = input_ids.clone()
699
+
700
+ assert conv.sep_style == conversation_lib.SeparatorStyle.TWO
701
+
702
+ # Mask targets
703
+ sep = conv.sep + conv.roles[1] + ": "
704
+ for conversation, target in zip(conversations, targets):
705
+ total_len = int(target.ne(tokenizer.pad_token_id).sum())
706
+
707
+ rounds = conversation.split(conv.sep2)
708
+ cur_len = 1
709
+ target[:cur_len] = IGNORE_INDEX
710
+ for i, rou in enumerate(rounds):
711
+ if rou == "":
712
+ break
713
+
714
+ parts = rou.split(sep)
715
+ if len(parts) != 2:
716
+ break
717
+ parts[0] += sep
718
+
719
+ if has_image:
720
+ round_len = len(tokenizer_image_token(rou, tokenizer))
721
+ instruction_len = len(tokenizer_image_token(parts[0], tokenizer)) - 2
722
+ else:
723
+ round_len = len(tokenizer(rou).input_ids)
724
+ instruction_len = len(tokenizer(parts[0]).input_ids) - 2
725
+
726
+ if i != 0 and not tokenizer.legacy and IS_TOKENIZER_GREATER_THAN_0_14:
727
+ round_len -= 1
728
+ instruction_len -= 1
729
+
730
+ target[cur_len : cur_len + instruction_len] = IGNORE_INDEX
731
+
732
+ cur_len += round_len
733
+ target[cur_len:] = IGNORE_INDEX
734
+
735
+ if cur_len < tokenizer.model_max_length:
736
+ if cur_len != total_len:
737
+ target[:] = IGNORE_INDEX
738
+ print(f"WARNING: tokenization mismatch: {cur_len} vs. {total_len}." f" (ignored)")
739
+
740
+ return dict(
741
+ input_ids=input_ids,
742
+ labels=targets,
743
+ )
744
+
745
+
746
+ def preprocess_mpt(sources, tokenizer: transformers.PreTrainedTokenizer, has_image: bool = False) -> Dict:
747
+ conv = conversation_lib.default_conversation.copy()
748
+ roles = {"human": conv.roles[0], "gpt": conv.roles[1]}
749
+
750
+ # Apply prompt templates
751
+ conversations = []
752
+ for i, source in enumerate(sources):
753
+ if roles[source[0]["from"]] != conv.roles[0]:
754
+ # Skip the first one if it is not from human
755
+ source = source[1:]
756
+
757
+ conv.messages = []
758
+ for j, sentence in enumerate(source):
759
+ role = roles[sentence["from"]]
760
+ assert role == conv.roles[j % 2], f"{i}"
761
+ conv.append_message(role, sentence["value"])
762
+ conversations.append(conv.get_prompt())
763
+
764
+ # Tokenize conversations
765
+
766
+ if has_image:
767
+ input_ids = torch.stack([tokenizer_image_token(prompt, tokenizer, return_tensors="pt") for prompt in conversations], dim=0)
768
+ else:
769
+ input_ids = tokenizer(
770
+ conversations,
771
+ return_tensors="pt",
772
+ padding="longest",
773
+ max_length=tokenizer.model_max_length,
774
+ truncation=True,
775
+ ).input_ids
776
+
777
+ targets = input_ids.clone()
778
+ assert conv.sep_style == conversation_lib.SeparatorStyle.MPT
779
+
780
+ # Mask targets
781
+ sep = conv.sep + conv.roles[1]
782
+ for conversation, target in zip(conversations, targets):
783
+ total_len = int(target.ne(tokenizer.pad_token_id).sum())
784
+
785
+ rounds = conversation.split(conv.sep)
786
+ re_rounds = [conv.sep.join(rounds[:3])] # system + user + gpt
787
+ for conv_idx in range(3, len(rounds), 2):
788
+ re_rounds.append(conv.sep.join(rounds[conv_idx : conv_idx + 2])) # user + gpt
789
+ cur_len = 1
790
+ target[:cur_len] = IGNORE_INDEX
791
+ for i, rou in enumerate(re_rounds):
792
+ if rou == "":
793
+ break
794
+
795
+ parts = rou.split(sep)
796
+ if len(parts) != 2:
797
+ break
798
+ parts[0] += sep
799
+
800
+ if has_image:
801
+ round_len = len(tokenizer_image_token(rou, tokenizer))
802
+ instruction_len = len(tokenizer_image_token(parts[0], tokenizer)) - 1
803
+ else:
804
+ round_len = len(tokenizer(rou).input_ids)
805
+ instruction_len = len(tokenizer(parts[0]).input_ids) - 1
806
+
807
+ if i != 0 and getattr(tokenizer, "legacy", False) and IS_TOKENIZER_GREATER_THAN_0_14:
808
+ round_len += 1
809
+ instruction_len += 1
810
+
811
+ target[cur_len : cur_len + instruction_len] = IGNORE_INDEX
812
+
813
+ cur_len += round_len
814
+ target[cur_len:] = IGNORE_INDEX
815
+
816
+ if cur_len < tokenizer.model_max_length:
817
+ if cur_len != total_len:
818
+ target[:] = IGNORE_INDEX
819
+ print(f"WARNING: tokenization mismatch: {cur_len} vs. {total_len}." f"(#turns={len(re_rounds)} ignored)")
820
+
821
+ return dict(
822
+ input_ids=input_ids,
823
+ labels=targets,
824
+ )
825
+
826
+
827
+ def preprocess_plain(
828
+ sources: Sequence[str],
829
+ tokenizer: transformers.PreTrainedTokenizer,
830
+ ) -> Dict:
831
+ # add end signal and concatenate together
832
+ conversations = []
833
+ for source in sources:
834
+ assert len(source) == 2
835
+ assert DEFAULT_IMAGE_TOKEN in source[0]["value"]
836
+ source[0]["value"] = DEFAULT_IMAGE_TOKEN
837
+ conversation = source[0]["value"] + source[1]["value"] + conversation_lib.default_conversation.sep
838
+ conversations.append(conversation)
839
+ # tokenize conversations
840
+ input_ids = [tokenizer_image_token(prompt, tokenizer, return_tensors="pt") for prompt in conversations]
841
+ targets = copy.deepcopy(input_ids)
842
+ for target, source in zip(targets, sources):
843
+ tokenized_len = len(tokenizer_image_token(source[0]["value"], tokenizer))
844
+ target[:tokenized_len] = IGNORE_INDEX
845
+
846
+ return dict(input_ids=input_ids, labels=targets)
847
+
848
+
849
+ def preprocess(sources: Sequence[str], tokenizer: transformers.PreTrainedTokenizer, has_image: bool = False) -> Dict:
850
+ """
851
+ Given a list of sources, each is a conversation list. This transform:
852
+ 1. Add signal '### ' at the beginning each sentence, with end signal '\n';
853
+ 2. Concatenate conversations together;
854
+ 3. Tokenize the concatenated conversation;
855
+ 4. Make a deepcopy as the target. Mask human words with IGNORE_INDEX.
856
+ """
857
+ if conversation_lib.default_conversation.sep_style == conversation_lib.SeparatorStyle.PLAIN:
858
+ return preprocess_plain(sources, tokenizer)
859
+ if conversation_lib.default_conversation.sep_style == conversation_lib.SeparatorStyle.LLAMA_2:
860
+ return preprocess_llama_2(sources, tokenizer, has_image=has_image)
861
+ if conversation_lib.default_conversation.version.startswith("v1"):
862
+ return preprocess_v1(sources, tokenizer, has_image=has_image)
863
+ if conversation_lib.default_conversation.version == "mpt":
864
+ return preprocess_mpt(sources, tokenizer, has_image=has_image)
865
+ if conversation_lib.default_conversation.version == "qwen":
866
+ return preprocess_qwen(sources, tokenizer, has_image=has_image)
867
+ if conversation_lib.default_conversation.version == "gemma":
868
+ return preprocess_gemma(sources, tokenizer, has_image=has_image)
869
+ if conversation_lib.default_conversation.version == "llama_v3":
870
+ return preprocess_llama3(sources, tokenizer, has_image=has_image)
871
+ # add end signal and concatenate together
872
+ conversations = []
873
+ for source in sources:
874
+ header = f"{conversation_lib.default_conversation.system}\n\n"
875
+ conversation = _add_speaker_and_signal(header, source)
876
+ conversations.append(conversation)
877
+
878
+ # tokenize conversations
879
+ def get_tokenize_len(prompts):
880
+ return [len(tokenizer_image_token(prompt, tokenizer)) for prompt in prompts]
881
+
882
+ if has_image:
883
+ input_ids = [tokenizer_image_token(prompt, tokenizer, return_tensors="pt") for prompt in conversations]
884
+ else:
885
+ conversations_tokenized = _tokenize_fn(conversations, tokenizer)
886
+ input_ids = conversations_tokenized["input_ids"]
887
+
888
+ targets = copy.deepcopy(input_ids)
889
+ for target, source in zip(targets, sources):
890
+ if has_image:
891
+ tokenized_lens = get_tokenize_len([header] + [s["value"] for s in source])
892
+ else:
893
+ tokenized_lens = _tokenize_fn([header] + [s["value"] for s in source], tokenizer)["input_ids_lens"]
894
+ speakers = [sentence["from"] for sentence in source]
895
+ _mask_targets(target, tokenized_lens, speakers)
896
+
897
+ return dict(input_ids=input_ids, labels=targets)
898
+
899
+
900
+ def load_data(data_path):
901
+ if "jsonl" in data_path:
902
+ data_list = load_jsonl(data_path)
903
+ else:
904
+ data_list = load_json(data_path)
905
+ return data_list
906
+
907
+
908
+ class DPODataset(Dataset):
909
+ """Dataset for DPODataset fine-tuning."""
910
+
911
+ def __init__(self, data_path: str, tokenizer: transformers.PreTrainedTokenizer, data_args: DataArguments):
912
+ super(DPODataset, self).__init__()
913
+ # Handle multiple JSON files specified in the data_path
914
+ self.list_data_dict = []
915
+
916
+ if "{" in data_path and "}" in data_path:
917
+ base_path, file_pattern = re.match(r"^(.*)\{(.*)\}\.json$", data_path).groups()
918
+ file_names = file_pattern.split(",")
919
+ rank0_print(f"Loading {file_names} from {base_path}")
920
+ data_args.dataset_paths = []
921
+ for file_name in file_names:
922
+ data_args.dataset_paths.append(f"{base_path}{file_name}.json")
923
+ full_path = f"{base_path}{file_name}.json"
924
+ rank0_print(f"Loading {full_path}")
925
+ cur_data_dict = load_data(full_path)
926
+ rank0_print(f"Loaded {len(cur_data_dict)} samples from {full_path}")
927
+ self.list_data_dict.extend(cur_data_dict)
928
+ elif data_path.endswith(".yaml"):
929
+ with open(data_path, "r") as file:
930
+ yaml_data = yaml.safe_load(file)
931
+ datasets = yaml_data.get("datasets")
932
+ # file should be in the format of:
933
+ # datasets:
934
+ # - json_path: xxxx1.json
935
+ # sampling_strategy: first:1000
936
+ # - json_path: xxxx2.json
937
+ # sampling_strategy: end:3000
938
+ # - json_path: xxxx3.json
939
+ # sampling_strategy: random:999
940
+ data_args.dataset_paths = [dataset.get("json_path") for dataset in datasets]
941
+ for dataset in datasets:
942
+ json_path = dataset.get("json_path")
943
+ sampling_strategy = dataset.get("sampling_strategy", "all")
944
+ sampling_number = None
945
+
946
+ rank0_print(f"Loading {json_path} with {sampling_strategy} sampling strategy")
947
+ cur_data_dict = load_data(json_path)
948
+
949
+ if ":" in sampling_strategy:
950
+ sampling_strategy, sampling_number = sampling_strategy.split(":")
951
+ if "%" in sampling_number:
952
+ sampling_number = math.ceil(int(sampling_number.split("%")[0]) * len(cur_data_dict) / 100)
953
+ else:
954
+ sampling_number = int(sampling_number)
955
+
956
+ # Apply the sampling strategy
957
+ if sampling_strategy == "first" and sampling_number is not None:
958
+ cur_data_dict = cur_data_dict[:sampling_number]
959
+ elif sampling_strategy == "end" and sampling_number is not None:
960
+ cur_data_dict = cur_data_dict[-sampling_number:]
961
+ elif sampling_strategy == "random" and sampling_number is not None:
962
+ random.shuffle(cur_data_dict)
963
+ cur_data_dict = cur_data_dict[:sampling_number]
964
+
965
+ rank0_print(f"Loaded {len(cur_data_dict)} samples from {json_path}")
966
+ self.list_data_dict.extend(cur_data_dict)
967
+ else:
968
+ data_args.dataset_paths = [data_path]
969
+ rank0_print(f"Loading {data_path}")
970
+ cur_data_dict = load_data(data_path)
971
+ rank0_print(f"Loaded {len(cur_data_dict)} samples from {data_path}")
972
+ self.list_data_dict.extend(cur_data_dict)
973
+
974
+ rank0_print("Formatting inputs...Skip in lazy mode")
975
+ self.tokenizer = tokenizer
976
+ self.data_args = data_args
977
+
978
+ def __len__(self):
979
+ return len(self.list_data_dict)
980
+
981
+ @property
982
+ def lengths(self):
983
+ length_list = []
984
+ for sample in self.list_data_dict:
985
+ # Calculate the length of the prompt, answer, chosen, and rejected text
986
+ cur_len = len(sample["prompt"].split()) + len(sample["answer"].split()) + len(sample["chosen"].split()) + len(sample["rejected"].split())
987
+ # Add additional tokens if an image is present
988
+ img_tokens = 128 if "image" in sample else 0
989
+ length_list.append(cur_len + img_tokens)
990
+ return length_list
991
+
992
+ @property
993
+ def modality_lengths(self):
994
+ length_list = []
995
+ for sample in self.list_data_dict:
996
+ # Calculate the length of the prompt, answer, chosen, and rejected text
997
+ cur_len = len(sample["prompt"].split()) + len(sample["answer"].split()) + len(sample["chosen"].split()) + len(sample["rejected"].split())
998
+ # If the sample includes a video, the length is positive; otherwise, it is negative
999
+ cur_len = cur_len if ("video" in sample or "image" in sample) else -cur_len
1000
+ length_list.append(cur_len)
1001
+ return length_list
1002
+
1003
+ def process_image(self, image_file):
1004
+ image_folder = self.data_args.image_folder
1005
+ processor = self.data_args.image_processor
1006
+ # print(f"\n\nInspecting the image path, folder = {image_folder}, image={image_file}\n\n")
1007
+ try:
1008
+ image = Image.open(os.path.join(image_folder, image_file)).convert("RGB")
1009
+ except Exception as exn:
1010
+ print(f"Failed to open image {image_file}. Exception:", exn)
1011
+ raise exn
1012
+
1013
+ image_size = image.size
1014
+ if self.data_args.image_aspect_ratio == "highres":
1015
+ image = process_highres_image(image, self.data_args.image_processor, self.data_args.image_grid_pinpoints)
1016
+ elif self.data_args.image_aspect_ratio == "anyres" or "anyres" in self.data_args.image_aspect_ratio:
1017
+ image = process_anyres_image(image, self.data_args.image_processor, self.data_args.image_grid_pinpoints)
1018
+ elif self.data_args.image_aspect_ratio == "crop_split":
1019
+ image = process_highres_image_crop_split(image, self.data_args)
1020
+ elif self.data_args.image_aspect_ratio == "pad":
1021
+
1022
+ def expand2square(pil_img, background_color):
1023
+ width, height = pil_img.size
1024
+ if width == height:
1025
+ return pil_img
1026
+ elif width > height:
1027
+ result = Image.new(pil_img.mode, (width, width), background_color)
1028
+ result.paste(pil_img, (0, (width - height) // 2))
1029
+ return result
1030
+ else:
1031
+ result = Image.new(pil_img.mode, (height, height), background_color)
1032
+ result.paste(pil_img, ((height - width) // 2, 0))
1033
+ return result
1034
+
1035
+ image = expand2square(image, tuple(int(x * 255) for x in processor.image_mean))
1036
+ image = processor.preprocess(image, return_tensors="pt")["pixel_values"][0]
1037
+ else:
1038
+ image = processor.preprocess(image, return_tensors="pt")["pixel_values"][0]
1039
+ return image, image_size, "image"
1040
+
1041
+ def __getitem__(self, i) -> Dict[str, torch.Tensor]:
1042
+ # TODO: define number of retries somewhere else
1043
+ num_base_retries = 3
1044
+ num_final_retries = 300
1045
+
1046
+ # try the current sample first
1047
+ for attempt_idx in range(num_base_retries):
1048
+ try:
1049
+ sample = self._get_item(i)
1050
+ return sample
1051
+ except Exception as e:
1052
+ # sleep 1s in case it is a cloud disk issue
1053
+ print(f"[Try #{attempt_idx}] Failed to fetch sample {i}. Exception:", e)
1054
+ time.sleep(1)
1055
+
1056
+ # try other samples, in case it is file corruption issue
1057
+ for attempt_idx in range(num_base_retries):
1058
+ try:
1059
+ next_index = min(i + 1, len(self.list_data_dict) - 1)
1060
+ # sample_idx = random.choice(range(len(self)))
1061
+ sample = self._get_item(next_index)
1062
+ return sample
1063
+ except Exception as e:
1064
+ # no need to sleep
1065
+ print(f"[Try other #{attempt_idx}] Failed to fetch sample {next_index}. Exception:", e)
1066
+ pass
1067
+
1068
+ # still fail, most likely to be path issue or cloud disk issue, retry the same sample for longer
1069
+ # for attempt_idx in range(num_final_retries):
1070
+ # try:
1071
+ # sample = self._get_item(i)
1072
+ # return sample
1073
+ # except Exception as e:
1074
+ # # sleep 1s in case it is a cloud disk issue
1075
+ # print(f"[Final try #{attempt_idx}] Failed to fetch sample {i}. Exception:", e)
1076
+ # time.sleep(1)
1077
+
1078
+ # Finally raise exception on failing.
1079
+ assert False, "Failed to fetch sample."
1080
+
1081
+ def _get_item(self, i) -> Dict[str, torch.Tensor]:
1082
+ sources = self.list_data_dict[i]
1083
+ if isinstance(i, int):
1084
+ sources = [sources]
1085
+ assert len(sources) == 1, "Don't know why it is wrapped to a list" # FIXME
1086
+
1087
+ suffix = None
1088
+ if "image" in sources[0]:
1089
+ image_file = self.list_data_dict[i]["image"]
1090
+ if type(image_file) is list:
1091
+ image = [self.process_image(f) for f in image_file]
1092
+ else:
1093
+ image = [self.process_image(image_file)]
1094
+ # sources = preprocess_multimodal(copy.deepcopy([e["conversations"] for e in sources]), self.data_args)
1095
+
1096
+ elif "video" in sources[0]: # FIXME: This logic should be largely improved by Yuanhan. It's too messy now.
1097
+ video_file = self.list_data_dict[i]["video"]
1098
+ video_folder = self.data_args.video_folder
1099
+ video_file = os.path.join(video_folder, video_file)
1100
+ suffix = video_file.split(".")[-1]
1101
+ if not os.path.exists(video_file):
1102
+ print("File {} not exist!".format(video_file))
1103
+
1104
+ if suffix == "pkl":
1105
+ video_info = pickle.load(open(video_file, "rb"))
1106
+ image = torch.from_numpy(video_info["feats"][:, 1:])
1107
+ input_prompt = video_info["inputs"].replace("...", "")
1108
+ # replace the default image token with multiple tokens
1109
+ input_prompt = input_prompt.replace(DEFAULT_IMAGE_TOKEN, DEFAULT_IMAGE_TOKEN * self.data_args.video_token)
1110
+ sources, query_prompt = preprocess_multimodal_movie(copy.deepcopy([e["conversations"] for e in sources]), self.data_args, input_prompt)
1111
+ else: # using videoreader
1112
+ if "shareVideoGPTV" not in video_file and "liangke" not in video_file:
1113
+ vr = VideoReader(video_file, ctx=cpu(0))
1114
+ total_frame_num = len(vr)
1115
+ avg_fps = round(vr.get_avg_fps() / self.data_args.video_fps)
1116
+ frame_idx = [i for i in range(0, total_frame_num, avg_fps)]
1117
+ if self.data_args.frames_upbound > 0:
1118
+ if len(frame_idx) > self.data_args.frames_upbound:
1119
+ uniform_sampled_frames = np.linspace(0, total_frame_num - 1, self.data_args.frames_upbound, dtype=int)
1120
+ frame_idx = uniform_sampled_frames.tolist()
1121
+ video = vr.get_batch(frame_idx).asnumpy()
1122
+ video = np.array(video)
1123
+ else:
1124
+ if "liangke" in video_file:
1125
+ video_file = self.list_data_dict[i]["video"]
1126
+ frame_files = [os.path.join(video_file, f) for f in os.listdir(video_file) if os.path.isfile(os.path.join(video_file, f))]
1127
+ frame_files.sort() # Ensure the frames are sorted if they are named sequentially
1128
+
1129
+ # TODO: Hard CODE: Determine the indices for uniformly sampling 10 frames
1130
+ num_frames_to_sample = 10
1131
+
1132
+ total_frames = len(frame_files)
1133
+
1134
+ sampled_indices = np.linspace(0, total_frames - 1, num_frames_to_sample, dtype=int)
1135
+
1136
+ # Read and store the sampled frames
1137
+ video = []
1138
+ for idx in sampled_indices:
1139
+ frame_path = frame_files[idx]
1140
+ try:
1141
+ with Image.open(frame_path) as img:
1142
+ frame = img.convert("RGB")
1143
+ video.append(frame)
1144
+ except IOError:
1145
+ print(f"Failed to read frame at path: {frame_path}")
1146
+
1147
+ processor = self.data_args.image_processor
1148
+ image = processor.preprocess(video, return_tensors="pt")["pixel_values"]
1149
+ image = [(image, video[0].size, "video")]
1150
+ # sources = preprocess_multimodal(copy.deepcopy([e["conversations"] for e in sources]), self.data_args)
1151
+
1152
+ else:
1153
+ sources = copy.deepcopy([e["conversations"] for e in sources])
1154
+
1155
+ has_image = ("image" in self.list_data_dict[i]) or ("video" in self.list_data_dict[i])
1156
+ # data_dict = preprocess(sources, self.tokenizer, has_image=has_image)
1157
+ data_dict = copy.deepcopy(self.list_data_dict[i]) # inplace modification following
1158
+
1159
+ if "prompt" in data_dict:
1160
+ prompt = data_dict["prompt"]
1161
+ prompt = prompt.replace("<image>", "").strip()
1162
+ prompt = "<image>\n" + prompt
1163
+ data_dict["prompt"] = prompt
1164
+ else:
1165
+ prompt = None
1166
+
1167
+ if suffix == "pkl":
1168
+ prompt = [query_prompt]
1169
+
1170
+ # image exist in the data
1171
+ if "image" in self.list_data_dict[i]:
1172
+ data_dict["image"] = image
1173
+ elif "video" in self.list_data_dict[i]:
1174
+ data_dict["image"] = image
1175
+ elif self.data_args.is_multimodal:
1176
+ # image does not exist in the data, but the model is multimodal
1177
+ crop_size = self.data_args.image_processor.crop_size
1178
+ data_dict["image"] = [
1179
+ (torch.zeros(1, 3, crop_size["height"], crop_size["width"]), (crop_size["width"], crop_size["height"]), "text"),
1180
+ ]
1181
+ # prompt exist in the data
1182
+ data_dict["has_image"] = has_image
1183
+ return data_dict
1184
+
1185
+
1186
+ @dataclass
1187
+ class DPODataCollator(DPODataCollatorWithPadding):
1188
+ """Collate examples for DPO fine-tuning."""
1189
+
1190
+ # tokenizer: transformers.PreTrainedTokenizer
1191
+
1192
+ def collate(self, batch):
1193
+ # first, pad everything to the same length
1194
+ # input_ids, labels = tuple([instance[key] for instance in instances]
1195
+ # for key in ("input_ids", "labels"))
1196
+ # input_ids = torch.nn.utils.rnn.pad_sequence(
1197
+ # input_ids,
1198
+ # batch_first=True,
1199
+ # padding_value=self.tokenizer.pad_token_id)
1200
+ # labels = torch.nn.utils.rnn.pad_sequence(labels,
1201
+ # batch_first=True,
1202
+ # padding_value=IGNORE_INDEX)
1203
+ # input_ids = input_ids[:, :self.tokenizer.model_max_length]
1204
+ # labels = labels[:, :self.tokenizer.model_max_length]
1205
+ # batch = dict(
1206
+ # input_ids=input_ids,
1207
+ # labels=labels,
1208
+ # attention_mask=input_ids.ne(self.tokenizer.pad_token_id),
1209
+ # )
1210
+ padded_batch = {}
1211
+ for k in batch[0].keys():
1212
+ if k.endswith("_input_ids") or k.endswith("_attention_mask") or k.endswith("_labels"):
1213
+ # if "prompt" in k:
1214
+ # to_pad = [torch.LongTensor(ex[k][::-1]) for ex in batch]
1215
+ # else:
1216
+ to_pad = [torch.LongTensor(ex[k]) for ex in batch]
1217
+ if k.endswith("_input_ids"):
1218
+ padding_value = self.tokenizer.pad_token_id
1219
+ elif k.endswith("_labels"):
1220
+ padding_value = self.label_pad_token_id
1221
+ else:
1222
+ continue
1223
+ # elif k.endswith("_attention_mask"):
1224
+ # padding_value = self.padding_value
1225
+ # else:
1226
+ # raise ValueError(f"Unexpected key in batch '{k}'")
1227
+
1228
+ padded_batch[k] = torch.nn.utils.rnn.pad_sequence(to_pad, batch_first=True, padding_value=padding_value)
1229
+ # for the prompt, flip back so padding is on left side
1230
+ # if "prompt" in k:
1231
+ # padded_batch[k] = padded_batch[k].flip(dims=[1])
1232
+ else:
1233
+ padded_batch[k] = [ex[k] for ex in batch]
1234
+ for k in ["chosen_input_ids", "rejected_input_ids"]:
1235
+ attn_k = k.replace("input_ids", "attention_mask")
1236
+ padded_batch[attn_k] = padded_batch[k].ne(self.tokenizer.pad_token_id)
1237
+ return padded_batch
1238
+
1239
+ def tokenize_batch_element(self, prompt: str, chosen: str, rejected: str, has_image: bool = True) -> Dict:
1240
+ """Tokenize a single batch element.
1241
+
1242
+ At this stage, we don't convert to PyTorch tensors yet; we just handle the truncation
1243
+ in case the prompt + chosen or prompt + rejected responses is/are too long. First
1244
+ we truncate the prompt; if we're still too long, we truncate the chosen/rejected.
1245
+
1246
+ We also create the labels for the chosen/rejected responses, which are of length equal to
1247
+ the sum of the length of the prompt and the chosen/rejected response, with
1248
+ label_pad_token_id for the prompt tokens.
1249
+ """
1250
+ # import pdb; pdb.set_trace()
1251
+ batch = {}
1252
+
1253
+ chosen_sources = make_conv(prompt, chosen)
1254
+ rejected_sources = make_conv(prompt, rejected)
1255
+ chosen_data_dict = preprocess([chosen_sources], self.tokenizer, has_image=has_image)
1256
+ # chosen_data_dict['attention_mask'] = chosen_data_dict["input_ids"].ne(self.tokenizer.pad_token_id)
1257
+
1258
+ rejected_data_dict = preprocess([rejected_sources], self.tokenizer, has_image=has_image)
1259
+ # rejected_data_dict['attention_mask'] = rejected_data_dict["input_ids"].ne(self.tokenizer.pad_token_id)
1260
+
1261
+ chosen_data_dict = {k: v[0] for k, v in chosen_data_dict.items()}
1262
+ rejected_data_dict = {k: v[0] for k, v in rejected_data_dict.items()}
1263
+
1264
+ for k, toks in {
1265
+ "chosen": chosen_data_dict,
1266
+ "rejected": rejected_data_dict,
1267
+ }.items():
1268
+ for type_key, tokens in toks.items():
1269
+ if type_key == "token_type_ids":
1270
+ continue
1271
+ batch[f"{k}_{type_key}"] = tokens
1272
+ return batch
1273
+
1274
+ def __call__(self, features: List[Dict[str, Any]]) -> Dict[str, Any]:
1275
+
1276
+ tokenized_batch = []
1277
+ Xs, keys = [], []
1278
+ for feature in features:
1279
+ prompt = feature["prompt"]
1280
+ chosen = feature["chosen"]
1281
+ rejected = feature["rejected"]
1282
+ has_image = feature["has_image"]
1283
+ # Xs.append(feature[has_X])
1284
+ # keys.append(has_X)
1285
+
1286
+ batch_element = self.tokenize_batch_element(prompt, chosen, rejected, has_image=has_image)
1287
+ tokenized_batch.append(batch_element)
1288
+
1289
+ # return collated batch
1290
+ padded_batch = self.collate(tokenized_batch)
1291
+ # import pdb;pdb.set_trace()
1292
+ if "image" in features[0]:
1293
+ # instances[1]['image'][0][0].shape
1294
+ # torch.Size([5, 3, 224, 224])
1295
+ images = [instance["image"] for instance in features]
1296
+
1297
+ padded_batch["image_sizes"] = [im[1] for im_list in images for im in im_list]
1298
+ padded_batch["modalities"] = [im[2] for im_list in images for im in im_list]
1299
+ images = [im[0] for im_list in images for im in im_list]
1300
+ # import pdb;pdb.set_trace()
1301
+
1302
+ padded_batch["images"] = images
1303
+ # padded_batch["images"] =[padded_batch["modalities"], images]
1304
+
1305
+ return padded_batch
1306
+
1307
+
1308
+ def make_dpo_data_module(tokenizer: transformers.PreTrainedTokenizer, data_args) -> Dict:
1309
+ """Make dataset and collator for supervised fine-tuning."""
1310
+ train_dataset = DPODataset(tokenizer=tokenizer, data_path=data_args.data_path, data_args=data_args)
1311
+ return train_dataset
1312
+
1313
+
1314
+ def get_model(model_args, training_args, bnb_model_from_pretrained_args):
1315
+ assert training_args.attn_implementation
1316
+ if training_args.attn_implementation == "sdpa" and torch.__version__ < "2.1.2":
1317
+ raise ValueError("The 'sdpa' attention implementation requires torch version 2.1.2 or higher.")
1318
+
1319
+ ######################### Overwrite config #########################
1320
+ customized_kwargs = dict()
1321
+ customized_kwargs.update(bnb_model_from_pretrained_args)
1322
+ overwrite_config = {}
1323
+ cfg_pretrained = None
1324
+ if "qwen" in model_args.model_name_or_path.lower():
1325
+ cfg_pretrained = LlavaQwenConfig.from_pretrained(model_args.model_name_or_path)
1326
+ elif "mistral" in model_args.model_name_or_path.lower() or "zephyr" in model_args.model_name_or_path.lower():
1327
+ cfg_pretrained = LlavaMistralConfig.from_pretrained(model_args.model_name_or_path)
1328
+ elif (
1329
+ "wizardlm-2" in model_args.model_name_or_path.lower()
1330
+ or "vicuna" in model_args.model_name_or_path.lower()
1331
+ or "llama" in model_args.model_name_or_path.lower()
1332
+ or "yi" in model_args.model_name_or_path.lower()
1333
+ or "nous-hermes" in model_args.model_name_or_path.lower()
1334
+ and "wizard-2" in model_args.model_name_or_path.lower()
1335
+ ):
1336
+ cfg_pretrained = LlavaConfig.from_pretrained(model_args.model_name_or_path)
1337
+ else:
1338
+ cfg_pretrained = AutoConfig.from_pretrained(model_args.model_name_or_path)
1339
+
1340
+ if model_args.rope_scaling_factor is not None and model_args.rope_scaling_type is not None and cfg_pretrained is not None:
1341
+ overwrite_config["rope_scaling"] = {
1342
+ "factor": model_args.rope_scaling_factor,
1343
+ "type": model_args.rope_scaling_type,
1344
+ }
1345
+ if training_args.model_max_length is None:
1346
+ training_args.model_max_length = cfg_pretrained.max_position_embeddings * model_args.rope_scaling_factor
1347
+ overwrite_config["max_sequence_length"] = training_args.model_max_length
1348
+ assert training_args.model_max_length == int(cfg_pretrained.max_position_embeddings * model_args.rope_scaling_factor), print(
1349
+ f"model_max_length: {training_args.model_max_length}, max_position_embeddings: {cfg_pretrained.max_position_embeddings}, rope_scaling_factor: {model_args.rope_scaling_factor}"
1350
+ )
1351
+ # overwrite_config["max_sequence_length"] = model_args.max_sequence_length
1352
+ # overwrite_config["tokenizer_model_max_length"] = model_args.tokenizer_model_max_length
1353
+
1354
+ if model_args.mm_spatial_pool_stride is not None and model_args.mm_spatial_pool_out_channels is not None and model_args.mm_spatial_pool_mode is not None and model_args.mm_resampler_type is not None and cfg_pretrained is not None:
1355
+ overwrite_config["mm_resampler_type"] = model_args.mm_resampler_type
1356
+ overwrite_config["mm_spatial_pool_stride"] = model_args.mm_spatial_pool_stride
1357
+ overwrite_config["mm_spatial_pool_out_channels"] = model_args.mm_spatial_pool_out_channels
1358
+ overwrite_config["mm_spatial_pool_mode"] = model_args.mm_spatial_pool_mode
1359
+
1360
+ if overwrite_config:
1361
+ rank0_print(f"Overwriting config with {overwrite_config}")
1362
+ for k, v in overwrite_config.items():
1363
+ setattr(cfg_pretrained, k, v)
1364
+
1365
+ customized_kwargs["config"] = cfg_pretrained
1366
+
1367
+ ######################### Finish Overwrite ###########################
1368
+
1369
+ ref_model = None
1370
+ if model_args.model_class_name is not None:
1371
+ actual_model_class_name = f"{model_args.model_class_name}ForCausalLM"
1372
+ model_class = getattr(transformers, actual_model_class_name)
1373
+ rank0_print(f"Using model class {model_class} from {model_args.model_class_name}")
1374
+ model = model_class.from_pretrained(
1375
+ model_args.model_name_or_path,
1376
+ cache_dir=training_args.cache_dir,
1377
+ attn_implementation=training_args.attn_implementation,
1378
+ torch_dtype=(torch.bfloat16 if training_args.bf16 else None),
1379
+ low_cpu_mem_usage=False,
1380
+ **customized_kwargs,
1381
+ )
1382
+ elif model_args.vision_tower is not None:
1383
+ if "mixtral" in model_args.model_name_or_path.lower():
1384
+ model = LlavaMixtralForCausalLM.from_pretrained(
1385
+ model_args.model_name_or_path,
1386
+ cache_dir=training_args.cache_dir,
1387
+ attn_implementation=training_args.attn_implementation,
1388
+ torch_dtype=(torch.bfloat16 if training_args.bf16 else None),
1389
+ low_cpu_mem_usage=False,
1390
+ **customized_kwargs,
1391
+ )
1392
+ from transformers.models.mixtral.modeling_mixtral import MixtralSparseMoeBlock
1393
+
1394
+ deepspeed.utils.set_z3_leaf_modules(model, [MixtralSparseMoeBlock])
1395
+ elif "mistral" in model_args.model_name_or_path.lower() or "zephyr" in model_args.model_name_or_path.lower():
1396
+ model = LlavaMistralForCausalLM.from_pretrained(
1397
+ model_args.model_name_or_path,
1398
+ cache_dir=training_args.cache_dir,
1399
+ attn_implementation=training_args.attn_implementation,
1400
+ torch_dtype=(torch.bfloat16 if training_args.bf16 else None),
1401
+ low_cpu_mem_usage=False,
1402
+ **customized_kwargs,
1403
+ )
1404
+ elif (
1405
+ "wizardlm-2" in model_args.model_name_or_path.lower()
1406
+ or "vicuna" in model_args.model_name_or_path.lower()
1407
+ or "llama" in model_args.model_name_or_path.lower()
1408
+ or "yi" in model_args.model_name_or_path.lower()
1409
+ or "nous-hermes" in model_args.model_name_or_path.lower()
1410
+ and "wizard-2" in model_args.model_name_or_path.lower()
1411
+ ):
1412
+ model = LlavaLlamaForCausalLM.from_pretrained(
1413
+ model_args.model_name_or_path,
1414
+ cache_dir=training_args.cache_dir,
1415
+ attn_implementation=training_args.attn_implementation,
1416
+ torch_dtype=(torch.bfloat16 if training_args.bf16 else None),
1417
+ low_cpu_mem_usage=False,
1418
+ **customized_kwargs,
1419
+ )
1420
+
1421
+ if "zero3" in training_args.deepspeed:
1422
+ rank0_print("#### Initialize reference model #####")
1423
+ ref_model = LlavaLlamaForCausalLM.from_pretrained(
1424
+ model_args.model_name_or_path,
1425
+ cache_dir=training_args.cache_dir,
1426
+ attn_implementation=training_args.attn_implementation,
1427
+ torch_dtype=(torch.bfloat16 if training_args.bf16 else None),
1428
+ low_cpu_mem_usage=False,
1429
+ **customized_kwargs,
1430
+ )
1431
+
1432
+ elif "qwen" in model_args.model_name_or_path.lower() or "quyen" in model_args.model_name_or_path.lower():
1433
+ if "moe" in model_args.model_name_or_path.lower():
1434
+ model = LlavaQwenMoeForCausalLM.from_pretrained(
1435
+ model_args.model_name_or_path,
1436
+ cache_dir=training_args.cache_dir,
1437
+ attn_implementation=training_args.attn_implementation,
1438
+ torch_dtype=(torch.bfloat16 if training_args.bf16 else None),
1439
+ low_cpu_mem_usage=False,
1440
+ **customized_kwargs,
1441
+ )
1442
+ from transformers.models.qwen2_moe.modeling_qwen2_moe import Qwen2MoeSparseMoeBlock
1443
+
1444
+ deepspeed.utils.set_z3_leaf_modules(model, [Qwen2MoeSparseMoeBlock])
1445
+ else:
1446
+ model = LlavaQwenForCausalLM.from_pretrained(
1447
+ model_args.model_name_or_path,
1448
+ cache_dir=training_args.cache_dir,
1449
+ attn_implementation=training_args.attn_implementation,
1450
+ torch_dtype=(torch.bfloat16 if training_args.bf16 else None),
1451
+ low_cpu_mem_usage=False,
1452
+ **customized_kwargs,
1453
+ )
1454
+
1455
+ if "zero3" in training_args.deepspeed:
1456
+ rank0_print("#### Initialize reference model #####")
1457
+ ref_model = LlavaQwenForCausalLM.from_pretrained(
1458
+ model_args.model_name_or_path,
1459
+ cache_dir=training_args.cache_dir,
1460
+ attn_implementation=training_args.attn_implementation,
1461
+ torch_dtype=(torch.bfloat16 if training_args.bf16 else None),
1462
+ low_cpu_mem_usage=False,
1463
+ **customized_kwargs,
1464
+ )
1465
+
1466
+ elif "gemma" in model_args.model_name_or_path.lower():
1467
+ model = LlavaGemmaForCausalLM.from_pretrained(
1468
+ model_args.model_name_or_path,
1469
+ cache_dir=training_args.cache_dir,
1470
+ attn_implementation=training_args.attn_implementation,
1471
+ torch_dtype=(torch.bfloat16 if training_args.bf16 else None),
1472
+ low_cpu_mem_usage=False,
1473
+ **customized_kwargs,
1474
+ )
1475
+ else:
1476
+ raise ValueError(f"Unknown model class {model_args}")
1477
+ else:
1478
+ model = transformers.LlamaForCausalLM.from_pretrained(
1479
+ model_args.model_name_or_path, cache_dir=training_args.cache_dir, attn_implementation=training_args.attn_implementation, torch_dtype=(torch.bfloat16 if training_args.bf16 else None), **customized_kwargs
1480
+ )
1481
+ return model, ref_model
1482
+
1483
+
1484
+ def train(attn_implementation=None):
1485
+ global local_rank
1486
+
1487
+ parser = transformers.HfArgumentParser((ModelArguments, DataArguments, TrainingArguments))
1488
+ model_args, data_args, training_args = parser.parse_args_into_dataclasses()
1489
+
1490
+ if training_args.verbose_logging:
1491
+ rank0_print(f"Inspecting experiment hyperparameters:\n")
1492
+ rank0_print(f"model_args = {vars(model_args)}\n\n")
1493
+ rank0_print(f"data_args = {vars(data_args)}\n\n")
1494
+ rank0_print(f"training_args = {vars(training_args)}\n\n")
1495
+ # rank0_print(f"evaluation_args = {vars(evaluation_args)}\n\n")
1496
+
1497
+ local_rank = training_args.local_rank
1498
+ compute_dtype = torch.float16 if training_args.fp16 else (torch.bfloat16 if training_args.bf16 else torch.float32)
1499
+
1500
+ bnb_model_from_pretrained_args = {}
1501
+ if training_args.bits in [4, 8]:
1502
+ from transformers import BitsAndBytesConfig
1503
+
1504
+ bnb_model_from_pretrained_args.update(
1505
+ dict(
1506
+ device_map={"": training_args.device},
1507
+ load_in_4bit=training_args.bits == 4,
1508
+ load_in_8bit=training_args.bits == 8,
1509
+ quantization_config=BitsAndBytesConfig(
1510
+ load_in_4bit=training_args.bits == 4,
1511
+ load_in_8bit=training_args.bits == 8,
1512
+ llm_int8_threshold=6.0,
1513
+ llm_int8_has_fp16_weight=False,
1514
+ bnb_4bit_compute_dtype=compute_dtype,
1515
+ bnb_4bit_use_double_quant=training_args.double_quant,
1516
+ bnb_4bit_quant_type=training_args.quant_type, # {'fp4', 'nf4'}
1517
+ ),
1518
+ )
1519
+ )
1520
+
1521
+ model, ref_model = get_model(model_args, training_args, bnb_model_from_pretrained_args)
1522
+ model.config.use_cache = False
1523
+
1524
+ if model_args.freeze_backbone:
1525
+ model.model.requires_grad_(False)
1526
+
1527
+ if training_args.bits in [4, 8]:
1528
+ from peft import prepare_model_for_kbit_training
1529
+
1530
+ model.config.torch_dtype = torch.float32 if training_args.fp16 else (torch.bfloat16 if training_args.bf16 else torch.float32)
1531
+ model = prepare_model_for_kbit_training(model, use_gradient_checkpointing=training_args.gradient_checkpointing)
1532
+
1533
+ if training_args.gradient_checkpointing:
1534
+ if hasattr(model, "enable_input_require_grads"):
1535
+ model.enable_input_require_grads()
1536
+ if ref_model is not None:
1537
+ ref_model.enable_input_require_grads()
1538
+ else:
1539
+
1540
+ def make_inputs_require_grad(module, input, output):
1541
+ output.requires_grad_(True)
1542
+
1543
+ model.get_input_embeddings().register_forward_hook(make_inputs_require_grad)
1544
+
1545
+ if ref_model is not None:
1546
+ ref_model.get_input_embeddings().register_forward_hook(make_inputs_require_grad)
1547
+
1548
+ if training_args.lora_enable:
1549
+ from peft import LoraConfig, get_peft_model
1550
+
1551
+ lora_config = LoraConfig(
1552
+ r=training_args.lora_r,
1553
+ lora_alpha=training_args.lora_alpha,
1554
+ target_modules=find_all_linear_names(model),
1555
+ lora_dropout=training_args.lora_dropout,
1556
+ bias=training_args.lora_bias,
1557
+ task_type="CAUSAL_LM",
1558
+ )
1559
+ if training_args.bits == 16:
1560
+ if training_args.bf16:
1561
+ model.to(torch.bfloat16)
1562
+ if training_args.fp16:
1563
+ model.to(torch.float16)
1564
+ rank0_print("Adding LoRA adapters...")
1565
+ model = get_peft_model(model, lora_config)
1566
+
1567
+ if "mpt" in model_args.model_name_or_path:
1568
+ tokenizer = transformers.AutoTokenizer.from_pretrained(model_args.model_name_or_path, cache_dir=training_args.cache_dir, model_max_length=training_args.model_max_length, padding_side="right")
1569
+ elif "mistral" in model_args.model_name_or_path.lower() or "mixtral" in model_args.model_name_or_path.lower() or "zephyr" in model_args.model_name_or_path.lower():
1570
+ tokenizer = transformers.AutoTokenizer.from_pretrained(model_args.model_name_or_path, cache_dir=training_args.cache_dir, model_max_length=training_args.model_max_length, padding_side="left")
1571
+ elif "qwen" in model_args.model_name_or_path.lower():
1572
+ tokenizer = transformers.AutoTokenizer.from_pretrained(model_args.model_name_or_path, cache_dir=training_args.cache_dir, model_max_length=training_args.model_max_length, padding_side="right")
1573
+ else: # for all other models
1574
+ tokenizer = transformers.AutoTokenizer.from_pretrained(
1575
+ model_args.model_name_or_path,
1576
+ cache_dir=training_args.cache_dir,
1577
+ model_max_length=training_args.model_max_length,
1578
+ padding_side="right",
1579
+ use_fast=False,
1580
+ )
1581
+
1582
+ rank0_print(f"Prompt version: {model_args.version}")
1583
+ if model_args.version == "v0":
1584
+ if tokenizer.pad_token is None:
1585
+ smart_tokenizer_and_embedding_resize(
1586
+ special_tokens_dict=dict(pad_token="[PAD]"),
1587
+ tokenizer=tokenizer,
1588
+ model=model,
1589
+ )
1590
+ elif model_args.version == "v0.5":
1591
+ tokenizer.pad_token = tokenizer.unk_token
1592
+ else:
1593
+ if tokenizer.unk_token is not None:
1594
+ tokenizer.pad_token = tokenizer.unk_token
1595
+ if model_args.version in conversation_lib.conv_templates:
1596
+ conversation_lib.default_conversation = conversation_lib.conv_templates[model_args.version]
1597
+ else:
1598
+ conversation_lib.default_conversation = conversation_lib.conv_templates["vicuna_v1"]
1599
+
1600
+ if model_args.vision_tower is not None:
1601
+ model.get_model().initialize_vision_modules(model_args=model_args, fsdp=training_args.fsdp)
1602
+
1603
+ vision_tower = model.get_vision_tower()
1604
+ vision_tower.to(dtype=torch.bfloat16 if training_args.bf16 else torch.float16, device=training_args.device)
1605
+
1606
+ data_args.image_processor = vision_tower.image_processor
1607
+ data_args.is_multimodal = True
1608
+
1609
+ model.config.image_aspect_ratio = data_args.image_aspect_ratio
1610
+ if data_args.image_grid_pinpoints is not None:
1611
+ # for input like "(1x1)...(3x3)", convert to [(1, 1), (2, 1), (3, 1), (1, 2), (2, 2), (3, 2), (1, 3), (2, 3), (3, 3)]
1612
+ if "x" in data_args.image_grid_pinpoints and "..." in data_args.image_grid_pinpoints:
1613
+ vis_encoder_size = data_args.image_processor.size[0]
1614
+ matches = re.findall(r"\((\d+)x(\d+)\)", data_args.image_grid_pinpoints)
1615
+ range_start = tuple(map(int, matches[0]))
1616
+ range_end = tuple(map(int, matches[-1]))
1617
+ grid_pinpoints = [(i, j) for i in range(range_start[0], range_end[0] + 1) for j in range(range_start[1], range_end[1] + 1)]
1618
+ grid_pinpoints = [[dim * vis_encoder_size for dim in pair] for pair in grid_pinpoints]
1619
+ data_args.image_grid_pinpoints = grid_pinpoints
1620
+ elif "x" in data_args.image_grid_pinpoints:
1621
+ vis_encoder_size = data_args.image_processor.size[0]
1622
+ assert vis_encoder_size in [224, 336, 384, 448, 512], "vis_encoder_size should be in [224, 336, 384, 448, 512]"
1623
+ grid_pinpoints = data_args.image_grid_pinpoints.replace(" ", "").replace("x", ",")[1:-1].split("),(")
1624
+ data_args.image_grid_pinpoints = [[int(x) * vis_encoder_size for x in item.split(",")] for item in grid_pinpoints]
1625
+ else:
1626
+ data_args.image_grid_pinpoints = ast.literal_eval(data_args.image_grid_pinpoints) # for backward compatibility
1627
+ model.config.image_grid_pinpoints = data_args.image_grid_pinpoints
1628
+ model.config.image_crop_resolution = data_args.image_crop_resolution
1629
+ model.config.image_split_resolution = data_args.image_split_resolution
1630
+ model.config.tokenizer_padding_side = tokenizer.padding_side
1631
+ model.config.tokenizer_model_max_length = tokenizer.model_max_length
1632
+
1633
+ ### Deciding train which part of the model
1634
+ if model_args.mm_tunable_parts is None: # traditional way of deciding which part to train
1635
+ model.config.tune_mm_mlp_adapter = training_args.tune_mm_mlp_adapter = model_args.tune_mm_mlp_adapter
1636
+ model.config.tune_mm_vision_resampler = training_args.tune_mm_vision_resampler = model_args.tune_mm_vision_resampler
1637
+ if model_args.tune_mm_mlp_adapter or model_args.tune_mm_vision_resampler:
1638
+ model.requires_grad_(False)
1639
+ # Restore LoRA trainability after global freeze
1640
+ if training_args.lora_enable:
1641
+ for name, param in model.named_parameters():
1642
+ if "lora_" in name:
1643
+ param.requires_grad_(True)
1644
+ rank0_print("Restored LoRA parameters to trainable after global freeze (legacy branch).")
1645
+ if model_args.tune_mm_mlp_adapter:
1646
+ for p in model.get_model().mm_projector.parameters():
1647
+ p.requires_grad = True
1648
+ if model_args.tune_mm_vision_resampler:
1649
+ for p in model.get_model().vision_resampler.parameters():
1650
+ p.requires_grad = True
1651
+
1652
+ model.config.freeze_mm_mlp_adapter = training_args.freeze_mm_mlp_adapter
1653
+ if training_args.freeze_mm_mlp_adapter:
1654
+ for p in model.get_model().mm_projector.parameters():
1655
+ p.requires_grad = False
1656
+
1657
+ model.config.freeze_mm_vision_resampler = training_args.freeze_mm_vision_resampler
1658
+ if training_args.freeze_mm_vision_resampler:
1659
+ for p in model.get_model().vision_resampler.parameters():
1660
+ p.requires_grad = False
1661
+
1662
+ model.config.unfreeze_mm_vision_tower = model_args.unfreeze_mm_vision_tower
1663
+ if model_args.unfreeze_mm_vision_tower:
1664
+ vision_tower.requires_grad_(True)
1665
+ else:
1666
+ vision_tower.requires_grad_(False)
1667
+
1668
+ else:
1669
+ rank0_print(f"Using mm_tunable_parts: {model_args.mm_tunable_parts}")
1670
+ model.config.mm_tunable_parts = training_args.mm_tunable_parts = model_args.mm_tunable_parts
1671
+ # Set the entire model to not require gradients by default
1672
+ model.requires_grad_(False)
1673
+ vision_tower.requires_grad_(False)
1674
+ model.get_model().mm_projector.requires_grad_(False)
1675
+ model.get_model().vision_resampler.requires_grad_(False)
1676
+ # Parse the mm_tunable_parts to decide which parts to unfreeze
1677
+ tunable_parts = model_args.mm_tunable_parts.split(",")
1678
+ if "mm_mlp_adapter" in tunable_parts:
1679
+ for p in model.get_model().mm_projector.parameters():
1680
+ p.requires_grad = True
1681
+ if "mm_vision_resampler" in tunable_parts:
1682
+ for p in model.get_model().vision_resampler.parameters():
1683
+ p.requires_grad = True
1684
+ if "mm_vision_tower" in tunable_parts:
1685
+ for name, param in model.named_parameters():
1686
+ if "vision_tower" in name:
1687
+ param.requires_grad_(True)
1688
+ if "mm_language_model" in tunable_parts:
1689
+ if training_args.lora_enable:
1690
+ # LoRA mode: only unfreeze LoRA parameters, keep LLM backbone frozen
1691
+ rank0_print("LoRA enabled: unfreezing only LoRA parameters for LLM.")
1692
+ else:
1693
+ # Full finetune mode: unfreeze entire LLM backbone
1694
+ for name, param in model.named_parameters():
1695
+ if "vision_tower" not in name and "mm_projector" not in name and "vision_resampler" not in name:
1696
+ param.requires_grad_(True)
1697
+
1698
+ # Ensure LoRA parameters are always trainable when lora_enable is True,
1699
+ # regardless of which mm_tunable_parts are specified.
1700
+ # model.requires_grad_(False) above freezes everything including LoRA weights
1701
+ # injected by PEFT, so we must explicitly restore them here.
1702
+ if training_args.lora_enable:
1703
+ lora_param_count = 0
1704
+ for name, param in model.named_parameters():
1705
+ if "lora_" in name:
1706
+ param.requires_grad_(True)
1707
+ lora_param_count += 1
1708
+ rank0_print(f"Restored {lora_param_count} LoRA parameter tensors to trainable.")
1709
+ if "mm_language_model" not in tunable_parts:
1710
+ rank0_print(
1711
+ "WARNING: lora_enable is True but 'mm_language_model' is not in mm_tunable_parts. "
1712
+ "LoRA parameters will still be trained. If you do not intend to train the language "
1713
+ "model at all, consider setting --lora_enable False to avoid unnecessary overhead."
1714
+ )
1715
+
1716
+ total_params = sum(p.ds_numel if hasattr(p, "ds_numel") else p.numel() for p in model.parameters())
1717
+ trainable_params = sum(p.ds_numel if hasattr(p, "ds_numel") else p.numel() for p in model.parameters() if p.requires_grad)
1718
+ rank0_print(f"Total parameters: ~{total_params/1e6:.2f} MB)")
1719
+ rank0_print(f"Trainable parameters: ~{trainable_params/1e6:.2f} MB)")
1720
+ # Print per-group trainable parameter breakdown for verification
1721
+ trainable_groups = {"lora": 0, "mm_projector": 0, "vision_resampler": 0, "vision_tower": 0, "llm_base": 0}
1722
+ for name, p in model.named_parameters():
1723
+ if not p.requires_grad:
1724
+ continue
1725
+ n = p.ds_numel if hasattr(p, "ds_numel") else p.numel()
1726
+ if "lora_" in name:
1727
+ trainable_groups["lora"] += n
1728
+ elif "mm_projector" in name:
1729
+ trainable_groups["mm_projector"] += n
1730
+ elif "vision_resampler" in name:
1731
+ trainable_groups["vision_resampler"] += n
1732
+ elif "vision_tower" in name:
1733
+ trainable_groups["vision_tower"] += n
1734
+ else:
1735
+ trainable_groups["llm_base"] += n
1736
+ rank0_print("Trainable parameter groups: " + ", ".join(f"{k}={v:,}" for k, v in trainable_groups.items()))
1737
+ if training_args.bits in [4, 8]:
1738
+ model.get_model().mm_projector.to(dtype=compute_dtype, device=training_args.device)
1739
+
1740
+ model.config.mm_use_im_start_end = data_args.mm_use_im_start_end = model_args.mm_use_im_start_end
1741
+ model.config.mm_projector_lr = training_args.mm_projector_lr
1742
+ model.config.mm_vision_tower_lr = training_args.mm_vision_tower_lr
1743
+ training_args.use_im_start_end = model_args.mm_use_im_start_end
1744
+ model.config.mm_use_im_patch_token = model_args.mm_use_im_patch_token
1745
+ model.initialize_vision_tokenizer(model_args, tokenizer=tokenizer)
1746
+
1747
+ if ref_model is not None:
1748
+ ref_model.get_model().initialize_vision_modules(model_args=model_args, fsdp=training_args.fsdp)
1749
+ ref_vision_tower = ref_model.get_vision_tower()
1750
+ ref_vision_tower.to(dtype=torch.bfloat16 if training_args.bf16 else torch.float16, device=training_args.device)
1751
+ ref_model.config.image_aspect_ratio = data_args.image_aspect_ratio
1752
+ ref_model.config.image_grid_pinpoints = data_args.image_grid_pinpoints
1753
+ ref_model.config.image_crop_resolution = data_args.image_crop_resolution
1754
+ ref_model.config.image_split_resolution = data_args.image_split_resolution
1755
+ ref_model.config.tokenizer_padding_side = tokenizer.padding_side
1756
+ ref_model.config.tokenizer_model_max_length = tokenizer.model_max_length
1757
+ ref_model.config.mm_use_im_start_end = data_args.mm_use_im_start_end
1758
+ ref_model.config.mm_use_im_patch_token = model_args.mm_use_im_patch_token
1759
+ ref_model.initialize_vision_tokenizer(model_args, tokenizer=tokenizer)
1760
+ parameter_names = [n for n, _ in ref_model.named_parameters()]
1761
+ for param_name in parameter_names:
1762
+ param = ref_model.get_parameter(param_name)
1763
+ param.requires_grad = False
1764
+ ref_model.eval()
1765
+
1766
+ if training_args.bits in [4, 8]:
1767
+ from peft.tuners.lora import LoraLayer
1768
+
1769
+ for name, module in model.named_modules():
1770
+ if isinstance(module, LoraLayer):
1771
+ if training_args.bf16:
1772
+ module = module.to(torch.bfloat16)
1773
+ if "norm" in name:
1774
+ module = module.to(torch.float32)
1775
+ if "lm_head" in name or "embed_tokens" in name:
1776
+ if hasattr(module, "weight"):
1777
+ if training_args.bf16 and module.weight.dtype == torch.float32:
1778
+ module = module.to(torch.bfloat16)
1779
+
1780
+ train_dataset = make_dpo_data_module(tokenizer=tokenizer, data_args=data_args)
1781
+ data_collator = DPODataCollator(
1782
+ tokenizer,
1783
+ label_pad_token_id=IGNORE_INDEX,
1784
+ pad_token_id=tokenizer.pad_token_id,
1785
+ )
1786
+
1787
+ trainer = LLaVADPOTrainer(
1788
+ model,
1789
+ ref_model,
1790
+ args=training_args,
1791
+ dpo_alpha=training_args.dpo_alpha,
1792
+ beta=training_args.beta,
1793
+ gamma=training_args.gamma,
1794
+ train_dataset=train_dataset,
1795
+ eval_dataset=None,
1796
+ data_collator=data_collator,
1797
+ tokenizer=tokenizer,
1798
+ max_length=training_args.model_max_length,
1799
+ generate_during_eval=False, # training_args.generate_during_eval,
1800
+ precompute_ref_log_probs=training_args.precompute_ref_log_probs,
1801
+ )
1802
+
1803
+ if list(pathlib.Path(training_args.output_dir).glob("checkpoint-*")):
1804
+ trainer.train(resume_from_checkpoint=True)
1805
+ else:
1806
+ trainer.train()
1807
+ trainer.save_state()
1808
+
1809
+ model.config.use_cache = True
1810
+
1811
+ if training_args.lora_enable:
1812
+ state_dict = get_peft_state_maybe_zero_3(model.named_parameters(), training_args.lora_bias)
1813
+ non_lora_state_dict = get_peft_state_non_lora_maybe_zero_3(model.named_parameters())
1814
+ if training_args.local_rank == 0 or training_args.local_rank == -1:
1815
+ if hasattr(model, "config"):
1816
+ model.config.save_pretrained(training_args.output_dir)
1817
+ if hasattr(model, "generation_config"):
1818
+ model.generation_config.save_pretrained(training_args.output_dir)
1819
+ model.save_pretrained(training_args.output_dir, state_dict=state_dict)
1820
+ torch.save(non_lora_state_dict, os.path.join(training_args.output_dir, "non_lora_trainables.bin"))
1821
+ else:
1822
+ safe_save_model_for_hf_trainer(trainer=trainer, output_dir=training_args.output_dir)
1823
+
1824
+ rank0_print(f"Model saved to {training_args.output_dir}")
1825
+
1826
+
1827
+ if __name__ == "__main__":
1828
+ train()
之前的代码版本/第一版-全部代码/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/llava/train/train_mem.py ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ from llava.train.train import train
2
+
3
+ if __name__ == "__main__":
4
+ train()
之前的代码版本/第一版-全部代码/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/llava/utils.py ADDED
@@ -0,0 +1,198 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import datetime
2
+ import logging
3
+ import logging.handlers
4
+ import os
5
+ import sys
6
+ import numpy as np
7
+
8
+ import requests
9
+
10
+ from llava.constants import LOGDIR
11
+
12
+ server_error_msg = "**NETWORK ERROR DUE TO HIGH TRAFFIC. PLEASE REGENERATE OR REFRESH THIS PAGE.**"
13
+ moderation_msg = "I am sorry. Your input may violate our content moderation guidelines. Please avoid using harmful or offensive content."
14
+
15
+ handler = None
16
+
17
+ import torch.distributed as dist
18
+
19
+ try:
20
+ import av
21
+ from decord import VideoReader, cpu
22
+ except ImportError:
23
+ print("Please install pyav to use video processing functions.")
24
+
25
+ def process_video_with_decord(video_file, data_args):
26
+ vr = VideoReader(video_file, ctx=cpu(0), num_threads=1)
27
+ total_frame_num = len(vr)
28
+ video_time = total_frame_num / vr.get_avg_fps()
29
+ avg_fps = round(vr.get_avg_fps() / data_args.video_fps)
30
+ frame_idx = [i for i in range(0, total_frame_num, avg_fps)]
31
+ frame_time = [i/avg_fps for i in frame_idx]
32
+
33
+
34
+ if data_args.frames_upbound > 0:
35
+ if len(frame_idx) > data_args.frames_upbound or data_args.force_sample:
36
+ uniform_sampled_frames = np.linspace(0, total_frame_num - 1, data_args.frames_upbound, dtype=int)
37
+ frame_idx = uniform_sampled_frames.tolist()
38
+ frame_time = [i/vr.get_avg_fps() for i in frame_idx]
39
+
40
+ video = vr.get_batch(frame_idx).asnumpy()
41
+ frame_time = ",".join([f"{i:.2f}s" for i in frame_time])
42
+
43
+ num_frames_to_sample = num_frames = len(frame_idx)
44
+ # https://github.com/dmlc/decord/issues/208
45
+ vr.seek(0)
46
+ return video, video_time, frame_time, num_frames_to_sample
47
+
48
+ def process_video_with_pyav(video_file, data_args):
49
+ container = av.open(video_file)
50
+ # !!! This is the only difference. Using auto threading
51
+ container.streams.video[0].thread_type = "AUTO"
52
+
53
+ video_frames = []
54
+ for packet in container.demux():
55
+ if packet.stream.type == 'video':
56
+ for frame in packet.decode():
57
+ video_frames.append(frame)
58
+ total_frame_num = len(video_frames)
59
+ video_time = video_frames[-1].time
60
+ avg_fps = round(total_frame_num / video_time / data_args.video_fps)
61
+ frame_idx = [i for i in range(0, total_frame_num, avg_fps)]
62
+
63
+ if data_args.frames_upbound > 0:
64
+ if len(frame_idx) > data_args.frames_upbound:
65
+ uniform_sampled_frames = np.linspace(0, total_frame_num - 1, data_args.frames_upbound, dtype=int)
66
+ frame_idx = uniform_sampled_frames.tolist()
67
+
68
+
69
+ frames = [video_frames[i] for i in frame_idx]
70
+ return np.stack([x.to_ndarray(format="rgb24") for x in frames])
71
+
72
+
73
+ def rank0_print(*args):
74
+ if dist.is_initialized():
75
+ if dist.get_rank() == 0:
76
+ print(f"Rank {dist.get_rank()}: ", *args)
77
+ else:
78
+ print(*args)
79
+
80
+
81
+ def rank_print(*args):
82
+ if dist.is_initialized():
83
+ print(f"Rank {dist.get_rank()}: ", *args)
84
+ else:
85
+ print(*args)
86
+
87
+ def build_logger(logger_name, logger_filename):
88
+ global handler
89
+
90
+ formatter = logging.Formatter(
91
+ fmt="%(asctime)s | %(levelname)s | %(name)s | %(message)s",
92
+ datefmt="%Y-%m-%d %H:%M:%S",
93
+ )
94
+
95
+ # Set the format of root handlers
96
+ if not logging.getLogger().handlers:
97
+ logging.basicConfig(level=logging.INFO)
98
+ logging.getLogger().handlers[0].setFormatter(formatter)
99
+
100
+ # Redirect stdout and stderr to loggers
101
+ stdout_logger = logging.getLogger("stdout")
102
+ stdout_logger.setLevel(logging.INFO)
103
+ sl = StreamToLogger(stdout_logger, logging.INFO)
104
+ sys.stdout = sl
105
+
106
+ stderr_logger = logging.getLogger("stderr")
107
+ stderr_logger.setLevel(logging.ERROR)
108
+ sl = StreamToLogger(stderr_logger, logging.ERROR)
109
+ sys.stderr = sl
110
+
111
+ # Get logger
112
+ logger = logging.getLogger(logger_name)
113
+ logger.setLevel(logging.INFO)
114
+
115
+ # Add a file handler for all loggers
116
+ if handler is None:
117
+ os.makedirs(LOGDIR, exist_ok=True)
118
+ filename = os.path.join(LOGDIR, logger_filename)
119
+ handler = logging.handlers.TimedRotatingFileHandler(filename, when="D", utc=True)
120
+ handler.setFormatter(formatter)
121
+
122
+ for name, item in logging.root.manager.loggerDict.items():
123
+ if isinstance(item, logging.Logger):
124
+ item.addHandler(handler)
125
+
126
+ return logger
127
+
128
+
129
+ class StreamToLogger(object):
130
+ """
131
+ Fake file-like stream object that redirects writes to a logger instance.
132
+ """
133
+
134
+ def __init__(self, logger, log_level=logging.INFO):
135
+ self.terminal = sys.stdout
136
+ self.logger = logger
137
+ self.log_level = log_level
138
+ self.linebuf = ""
139
+
140
+ def __getattr__(self, attr):
141
+ return getattr(self.terminal, attr)
142
+
143
+ def write(self, buf):
144
+ temp_linebuf = self.linebuf + buf
145
+ self.linebuf = ""
146
+ for line in temp_linebuf.splitlines(True):
147
+ # From the io.TextIOWrapper docs:
148
+ # On output, if newline is None, any '\n' characters written
149
+ # are translated to the system default line separator.
150
+ # By default sys.stdout.write() expects '\n' newlines and then
151
+ # translates them so this is still cross platform.
152
+ if line[-1] == "\n":
153
+ self.logger.log(self.log_level, line.rstrip())
154
+ else:
155
+ self.linebuf += line
156
+
157
+ def flush(self):
158
+ if self.linebuf != "":
159
+ self.logger.log(self.log_level, self.linebuf.rstrip())
160
+ self.linebuf = ""
161
+
162
+
163
+ def disable_torch_init():
164
+ """
165
+ Disable the redundant torch default initialization to accelerate model creation.
166
+ """
167
+ import torch
168
+
169
+ setattr(torch.nn.Linear, "reset_parameters", lambda self: None)
170
+ setattr(torch.nn.LayerNorm, "reset_parameters", lambda self: None)
171
+
172
+
173
+ def violates_moderation(text):
174
+ """
175
+ Check whether the text violates OpenAI moderation API.
176
+ """
177
+ url = "https://api.openai.com/v1/moderations"
178
+ headers = {"Content-Type": "application/json", "Authorization": "Bearer " + os.environ["OPENAI_API_KEY"]}
179
+ text = text.replace("\n", "")
180
+ data = "{" + '"input": ' + f'"{text}"' + "}"
181
+ data = data.encode("utf-8")
182
+ try:
183
+ ret = requests.post(url, headers=headers, data=data, timeout=5)
184
+ flagged = ret.json()["results"][0]["flagged"]
185
+ except requests.exceptions.RequestException as e:
186
+ print(f"######################### Moderation Error: {e} #########################")
187
+ flagged = False
188
+ except KeyError as e:
189
+ print(f"######################### Moderation Error: {e} #########################")
190
+ flagged = False
191
+
192
+ return flagged
193
+
194
+
195
+ def pretty_print_semaphore(semaphore):
196
+ if semaphore is None:
197
+ return "None"
198
+ return f"Semaphore(value={semaphore._value}, locked={semaphore.locked()})"
之前的代码版本/第一版-全部代码/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/archived/convert_gqa_for_eval.py ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import json
3
+ import argparse
4
+
5
+ parser = argparse.ArgumentParser()
6
+ parser.add_argument("--src", type=str)
7
+ parser.add_argument("--dst", type=str)
8
+ args = parser.parse_args()
9
+
10
+ all_answers = []
11
+ for line_idx, line in enumerate(open(args.src)):
12
+ res = json.loads(line)
13
+ question_id = res["question_id"]
14
+ text = res["text"].rstrip(".").lower()
15
+ all_answers.append({"questionId": question_id, "prediction": text})
16
+
17
+ with open(args.dst, "w") as f:
18
+ json.dump(all_answers, f)
之前的代码版本/第一版-全部代码/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/archived/convert_mmvet_for_eval.py ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import json
3
+ import argparse
4
+
5
+ parser = argparse.ArgumentParser()
6
+ parser.add_argument("--src", type=str)
7
+ parser.add_argument("--dst", type=str)
8
+ args = parser.parse_args()
9
+
10
+ cur_result = {}
11
+
12
+ for line in open(args.src):
13
+ data = json.loads(line)
14
+ qid = data["question_id"]
15
+ cur_result[f"v1_{qid}"] = data["text"]
16
+
17
+ with open(args.dst, "w") as f:
18
+ json.dump(cur_result, f, indent=2)
之前的代码版本/第一版-全部代码/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/archived/convert_sqa_to_llava.py ADDED
@@ -0,0 +1,88 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import os
3
+ import fire
4
+ import re
5
+ from convert_sqa_to_llava_base_prompt import build_prompt_chatbot
6
+
7
+
8
+ def convert_to_llava(base_dir, split, prompt_format="QCM-LEA"):
9
+ split_indices = json.load(open(os.path.join(base_dir, "pid_splits.json")))[split]
10
+ problems = json.load(open(os.path.join(base_dir, "problems.json")))
11
+
12
+ split_problems = build_prompt_chatbot(problems, split_indices, prompt_format, use_caption=False, is_test=False)
13
+
14
+ target_format = []
15
+ for prob_id, (input, output) in split_problems.items():
16
+ if input.startswith("Question: "):
17
+ input = input.replace("Question: ", "")
18
+ if output.startswith("Answer: "):
19
+ output = output.replace("Answer: ", "")
20
+
21
+ raw_prob_data = problems[prob_id]
22
+ if raw_prob_data["image"] is None:
23
+ target_format.append(
24
+ {
25
+ "id": prob_id,
26
+ "conversations": [
27
+ {"from": "human", "value": f"{input}"},
28
+ {"from": "gpt", "value": f"{output}"},
29
+ ],
30
+ }
31
+ )
32
+
33
+ else:
34
+ target_format.append(
35
+ {
36
+ "id": prob_id,
37
+ "image": os.path.join(prob_id, raw_prob_data["image"]),
38
+ "conversations": [
39
+ {"from": "human", "value": f"{input}\n<image>"},
40
+ {"from": "gpt", "value": f"{output}"},
41
+ ],
42
+ }
43
+ )
44
+
45
+ print(f"Number of samples: {len(target_format)}")
46
+
47
+ with open(os.path.join(base_dir, f"llava_{split}_{prompt_format}.json"), "w") as f:
48
+ json.dump(target_format, f, indent=2)
49
+
50
+
51
+ def convert_to_jsonl(base_dir, split, prompt_format="QCM-LEPA"):
52
+ split_indices = json.load(open(os.path.join(base_dir, "pid_splits.json")))[split]
53
+ problems = json.load(open(os.path.join(base_dir, "problems.json")))
54
+
55
+ split_problems = build_prompt_chatbot(problems, split_indices, prompt_format, use_caption=False, is_test=False)
56
+
57
+ writer = open(os.path.join(base_dir, f"scienceqa_{split}_{prompt_format}.jsonl"), "w")
58
+ for prob_id, (input, output) in split_problems.items():
59
+ if input.startswith("Question: "):
60
+ input = input.replace("Question: ", "")
61
+ if output.startswith("Answer: "):
62
+ output = output.replace("Answer: ", "")
63
+
64
+ raw_prob_data = problems[prob_id]
65
+ if raw_prob_data["image"] is None:
66
+ data = {
67
+ "id": prob_id,
68
+ "instruction": f"{input}",
69
+ "output": f"{output}",
70
+ }
71
+
72
+ else:
73
+ data = {
74
+ "id": prob_id,
75
+ "image": os.path.join(prob_id, raw_prob_data["image"]),
76
+ "instruction": f"{input}\n<image>",
77
+ "output": f"{output}",
78
+ }
79
+ writer.write(json.dumps(data) + "\n")
80
+ writer.close()
81
+
82
+
83
+ def main(task, **kwargs):
84
+ globals()[task](**kwargs)
85
+
86
+
87
+ if __name__ == "__main__":
88
+ fire.Fire(main)
之前的代码版本/第一版-全部代码/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/archived/convert_sqa_to_llava_base_prompt.py ADDED
@@ -0,0 +1,298 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ def get_question_text(problem):
2
+ question = problem["question"]
3
+ return question
4
+
5
+
6
+ def get_context_text(problem, use_caption):
7
+ txt_context = problem["hint"]
8
+ img_context = problem["caption"] if use_caption else ""
9
+ context = " ".join([txt_context, img_context]).strip()
10
+ if context == "":
11
+ context = "N/A"
12
+ return context
13
+
14
+
15
+ def get_choice_text(probelm, options):
16
+ choices = probelm["choices"]
17
+ choice_list = []
18
+ for i, c in enumerate(choices):
19
+ choice_list.append("({}) {}".format(options[i], c))
20
+ choice_txt = " ".join(choice_list)
21
+ # print(choice_txt)
22
+ return choice_txt
23
+
24
+
25
+ def get_answer(problem, options):
26
+ return options[problem["answer"]]
27
+
28
+
29
+ def get_lecture_text(problem):
30
+ # \\n: GPT-3 can generate the lecture with more tokens.
31
+ lecture = problem["lecture"].replace("\n", "\\n")
32
+ return lecture
33
+
34
+
35
+ def get_solution_text(problem):
36
+ # \\n: GPT-3 can generate the solution with more tokens
37
+ solution = problem["solution"].replace("\n", "\\n")
38
+ return solution
39
+
40
+
41
+ def create_one_example_chatbot(format, question, context, choice, answer, lecture, solution, test_example=True):
42
+
43
+ input_format, output_format = format.split("-")
44
+
45
+ ## Inputs
46
+ if input_format == "CQM":
47
+ input = f"Context: {context}\nQuestion: {question}\nOptions: {choice}\n"
48
+ elif input_format == "QCM":
49
+ input = f"Question: {question}\nContext: {context}\nOptions: {choice}\n"
50
+ # upper bound experiment
51
+ elif input_format == "QCML":
52
+ input = f"Question: {question}\nContext: {context}\nOptions: {choice}\nBECAUSE: {lecture}\n"
53
+ elif input_format == "QCME":
54
+ input = f"Question: {question}\nContext: {context}\nOptions: {choice}\nBECAUSE: {solution}\n"
55
+ elif input_format == "QCMLE":
56
+ input = f"Question: {question}\nContext: {context}\nOptions: {choice}\nBECAUSE: {lecture} {solution}\n"
57
+
58
+ elif input_format == "QCLM":
59
+ input = f"Question: {question}\nContext: {context}\nBECAUSE: {lecture}\nOptions: {choice}\n"
60
+ elif input_format == "QCEM":
61
+ input = f"Question: {question}\nContext: {context}\nBECAUSE: {solution}\nOptions: {choice}\n"
62
+ elif input_format == "QCLEM":
63
+ input = f"Question: {question}\nContext: {context}\nBECAUSE: {lecture} {solution}\nOptions: {choice}\n"
64
+
65
+ # Outputs
66
+ if test_example:
67
+ output = "Answer:"
68
+ elif output_format == "A":
69
+ output = f"Answer: The answer is {answer}."
70
+
71
+ elif output_format == "AL":
72
+ output = f"Answer: The answer is {answer}. BECAUSE: {solution}"
73
+ elif output_format == "AE":
74
+ output = f"Answer: The answer is {answer}. BECAUSE: {lecture}"
75
+ elif output_format == "ALE":
76
+ output = f"Answer: The answer is {answer}. BECAUSE: {lecture} {solution}"
77
+ elif output_format == "AEL":
78
+ output = f"Answer: The answer is {answer}. BECAUSE: {solution} {lecture}"
79
+
80
+ elif output_format == "LA":
81
+ output = f"Answer: {lecture} The answer is {answer}."
82
+ elif output_format == "EA":
83
+ output = f"Answer: {solution} The answer is {answer}."
84
+ elif output_format == "LEA":
85
+ output = f"Answer: {lecture} {solution} The answer is {answer}."
86
+ elif output_format == "ELA":
87
+ output = f"Answer: {solution} {lecture} The answer is {answer}."
88
+ elif output_format == "LEPA":
89
+ output = ""
90
+ if len(lecture.strip()) > 0:
91
+ output += f"LECTURE: {lecture}\n"
92
+ if len(solution.strip()) > 0:
93
+ output += f"SOLUTION: {solution}\n"
94
+ output += "###\n"
95
+ output += f"ANSWER: {answer}."
96
+
97
+ input = input.replace(" ", " ").strip()
98
+ output = output.replace(" ", " ").strip()
99
+ if input.endswith("BECAUSE:"):
100
+ input = input.replace("BECAUSE:", "").strip()
101
+ if output.endswith("BECAUSE:"):
102
+ output = output.replace("BECAUSE:", "").strip()
103
+ return input, output
104
+
105
+
106
+ def create_one_example(format, question, context, choice, answer, lecture, solution, test_example=True):
107
+
108
+ input_format, output_format = format.split("-")
109
+
110
+ ## Inputs
111
+ if input_format == "CQM":
112
+ input = f"Context: {context}\nQuestion: {question}\nOptions: {choice}\n"
113
+ elif input_format == "QCM":
114
+ input = f"Question: {question}\nContext: {context}\nOptions: {choice}\n"
115
+ # upper bound experiment
116
+ elif input_format == "QCML":
117
+ input = f"Question: {question}\nContext: {context}\nOptions: {choice}\nBECAUSE: {lecture}\n"
118
+ elif input_format == "QCME":
119
+ input = f"Question: {question}\nContext: {context}\nOptions: {choice}\nBECAUSE: {solution}\n"
120
+ elif input_format == "QCMLE":
121
+ input = f"Question: {question}\nContext: {context}\nOptions: {choice}\nBECAUSE: {lecture} {solution}\n"
122
+
123
+ elif input_format == "QCLM":
124
+ input = f"Question: {question}\nContext: {context}\nBECAUSE: {lecture}\nOptions: {choice}\n"
125
+ elif input_format == "QCEM":
126
+ input = f"Question: {question}\nContext: {context}\nBECAUSE: {solution}\nOptions: {choice}\n"
127
+ elif input_format == "QCLEM":
128
+ input = f"Question: {question}\nContext: {context}\nBECAUSE: {lecture} {solution}\nOptions: {choice}\n"
129
+
130
+ # Outputs
131
+ if test_example:
132
+ output = "Answer:"
133
+ elif output_format == "A":
134
+ output = f"Answer: The answer is {answer}."
135
+
136
+ elif output_format == "AL":
137
+ output = f"Answer: The answer is {answer}. BECAUSE: {solution}"
138
+ elif output_format == "AE":
139
+ output = f"Answer: The answer is {answer}. BECAUSE: {lecture}"
140
+ elif output_format == "ALE":
141
+ output = f"Answer: The answer is {answer}. BECAUSE: {lecture} {solution}"
142
+ elif output_format == "AEL":
143
+ output = f"Answer: The answer is {answer}. BECAUSE: {solution} {lecture}"
144
+
145
+ elif output_format == "LA":
146
+ output = f"Answer: {lecture} The answer is {answer}."
147
+ elif output_format == "EA":
148
+ output = f"Answer: {solution} The answer is {answer}."
149
+ elif output_format == "LEA":
150
+ output = f"Answer: {lecture} {solution} The answer is {answer}."
151
+ elif output_format == "ELA":
152
+ output = f"Answer: {solution} {lecture} The answer is {answer}."
153
+
154
+ text = input + output
155
+ text = text.replace(" ", " ").strip()
156
+ if text.endswith("BECAUSE:"):
157
+ text = text.replace("BECAUSE:", "").strip()
158
+ return text
159
+
160
+
161
+ def create_one_example_gpt4(format, question, context, choice, answer, lecture, solution, test_example=True):
162
+
163
+ input_format, output_format = format.split("-")
164
+
165
+ ## Inputs
166
+ if input_format == "CQM":
167
+ input = f"Context: {context}\nQuestion: {question}\nOptions: {choice}\n"
168
+ elif input_format == "QCM":
169
+ input = f"Question: {question}\nContext: {context}\nOptions: {choice}\n"
170
+ # upper bound experiment
171
+ elif input_format == "QCML":
172
+ input = f"Question: {question}\nContext: {context}\nOptions: {choice}\nBECAUSE: {lecture}\n"
173
+ elif input_format == "QCME":
174
+ input = f"Question: {question}\nContext: {context}\nOptions: {choice}\nBECAUSE: {solution}\n"
175
+ elif input_format == "QCMLE":
176
+ input = f"Question: {question}\nContext: {context}\nOptions: {choice}\nBECAUSE: {lecture} {solution}\n"
177
+
178
+ elif input_format == "QCLM":
179
+ input = f"Question: {question}\nContext: {context}\nBECAUSE: {lecture}\nOptions: {choice}\n"
180
+ elif input_format == "QCEM":
181
+ input = f"Question: {question}\nContext: {context}\nBECAUSE: {solution}\nOptions: {choice}\n"
182
+ elif input_format == "QCLEM":
183
+ input = f"Question: {question}\nContext: {context}\nBECAUSE: {lecture} {solution}\nOptions: {choice}\n"
184
+
185
+ # Outputs
186
+ if test_example:
187
+ output = "Answer:"
188
+ elif output_format == "A":
189
+ output = f"Answer: The answer is {answer}."
190
+
191
+ elif output_format == "AL":
192
+ output = f"Answer: The answer is {answer}. BECAUSE: {solution}"
193
+ elif output_format == "AE":
194
+ output = f"Answer: The answer is {answer}. BECAUSE: {lecture}"
195
+ elif output_format == "ALE":
196
+ output = f"Answer: The answer is {answer}. BECAUSE: {lecture} {solution}"
197
+ elif output_format == "AEL":
198
+ output = f"Answer: The answer is {answer}. BECAUSE: {solution} {lecture}"
199
+
200
+ elif output_format == "LA":
201
+ output = f"Answer: {lecture} The answer is {answer}."
202
+ elif output_format == "EA":
203
+ output = f"Answer: {solution} The answer is {answer}."
204
+ elif output_format == "LEA":
205
+ output = f"Answer: {lecture} {solution} The answer is {answer}."
206
+ elif output_format == "ELA":
207
+ output = f"Answer: {solution} {lecture} The answer is {answer}."
208
+
209
+ input = input.replace(" ", " ").strip()
210
+ output = output.replace(" ", " ").strip()
211
+ if output.endswith("BECAUSE:"):
212
+ output = output.replace("BECAUSE:", "").strip()
213
+
214
+ user_prompt = {"role": "user", "content": f"Can you explain {input}?"}
215
+ assistant_prompt = {"role": "assistant", "content": f"{output}"}
216
+
217
+ return user_prompt, assistant_prompt
218
+
219
+
220
+ def build_prompt_chatbot(problems, shot_qids, prompt_format, use_caption=False, options=["A", "B", "C", "D", "E"], is_test=False):
221
+ examples = {}
222
+
223
+ for qid in shot_qids:
224
+ question = get_question_text(problems[qid])
225
+ context = get_context_text(problems[qid], use_caption)
226
+ choice = get_choice_text(problems[qid], options)
227
+ answer = get_answer(problems[qid], options)
228
+ lecture = get_lecture_text(problems[qid]).replace("\\n", "\n")
229
+ solution = get_solution_text(problems[qid]).replace("\\n", "\n")
230
+
231
+ train_example = create_one_example_chatbot(prompt_format, question, context, choice, answer, lecture, solution, test_example=is_test)
232
+ examples[qid] = train_example
233
+ return examples
234
+
235
+
236
+ def build_prompt(problems, shot_qids, test_qid, args):
237
+
238
+ examples = []
239
+
240
+ # n-shot training examples
241
+ for qid in shot_qids:
242
+ question = get_question_text(problems[qid])
243
+ context = get_context_text(problems[qid], args.use_caption)
244
+ choice = get_choice_text(problems[qid], args.options)
245
+ answer = get_answer(problems[qid], args.options)
246
+ lecture = get_lecture_text(problems[qid])
247
+ solution = get_solution_text(problems[qid])
248
+
249
+ train_example = create_one_example(args.prompt_format, question, context, choice, answer, lecture, solution, test_example=False)
250
+ examples.append(train_example)
251
+
252
+ # test example
253
+ question = get_question_text(problems[test_qid])
254
+ context = get_context_text(problems[test_qid], args.use_caption)
255
+ choice = get_choice_text(problems[test_qid], args.options)
256
+ answer = get_answer(problems[test_qid], args.options)
257
+ lecture = get_lecture_text(problems[test_qid])
258
+ solution = get_solution_text(problems[test_qid])
259
+
260
+ test_example = create_one_example(args.prompt_format, question, context, choice, answer, lecture, solution, test_example=True)
261
+ examples.append(test_example)
262
+
263
+ # create the prompt input
264
+ prompt_input = "\n\n".join(examples)
265
+
266
+ return prompt_input
267
+
268
+
269
+ def build_prompt_gpt4(problems, shot_qids, test_qid, args):
270
+
271
+ prompt_array = [{"role": "system", "content": "You are a helpful assistant."}]
272
+
273
+ # n-shot training examples
274
+ for qid in shot_qids:
275
+ question = get_question_text(problems[qid])
276
+ context = get_context_text(problems[qid], args.use_caption)
277
+ choice = get_choice_text(problems[qid], args.options)
278
+ answer = get_answer(problems[qid], args.options)
279
+ lecture = get_lecture_text(problems[qid])
280
+ solution = get_solution_text(problems[qid])
281
+
282
+ user_prompt, assistant_prompt = create_one_example_gpt4(args.prompt_format, question, context, choice, answer, lecture, solution, test_example=False)
283
+ prompt_array.append(user_prompt)
284
+ prompt_array.append(assistant_prompt)
285
+
286
+ # test example
287
+ question = get_question_text(problems[test_qid])
288
+ context = get_context_text(problems[test_qid], args.use_caption)
289
+ choice = get_choice_text(problems[test_qid], args.options)
290
+ answer = get_answer(problems[test_qid], args.options)
291
+ lecture = get_lecture_text(problems[test_qid])
292
+ solution = get_solution_text(problems[test_qid])
293
+
294
+ user_prompt, assistant_prompt = create_one_example_gpt4(args.prompt_format, question, context, choice, answer, lecture, solution, test_example=True)
295
+ prompt_array.append(user_prompt)
296
+ prompt_array.append(assistant_prompt)
297
+
298
+ return prompt_array
之前的代码版本/第一版-全部代码/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/archived/convert_vizwiz_for_submission.py ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import argparse
3
+ import json
4
+
5
+ from llava.eval.m4c_evaluator import EvalAIAnswerProcessor
6
+
7
+
8
+ def parse_args():
9
+ parser = argparse.ArgumentParser()
10
+ parser.add_argument("--annotation-file", type=str, required=True)
11
+ parser.add_argument("--result-file", type=str, required=True)
12
+ parser.add_argument("--result-upload-file", type=str, required=True)
13
+ return parser.parse_args()
14
+
15
+
16
+ if __name__ == "__main__":
17
+
18
+ args = parse_args()
19
+
20
+ os.makedirs(os.path.dirname(args.result_upload_file), exist_ok=True)
21
+
22
+ results = []
23
+ error_line = 0
24
+ for line_idx, line in enumerate(open(args.result_file)):
25
+ try:
26
+ results.append(json.loads(line))
27
+ except:
28
+ error_line += 1
29
+ results = {x["question_id"]: x["text"] for x in results}
30
+ test_split = [json.loads(line) for line in open(args.annotation_file)]
31
+ split_ids = set([x["question_id"] for x in test_split])
32
+
33
+ print(f"total results: {len(results)}, total split: {len(test_split)}, error_line: {error_line}")
34
+
35
+ all_answers = []
36
+
37
+ answer_processor = EvalAIAnswerProcessor()
38
+
39
+ for x in test_split:
40
+ # import pdb; pdb.set_trace()
41
+ assert x["question_id"] in results, print(x)
42
+ all_answers.append({"image": x["image"], "answer": answer_processor(results[x["question_id"]])})
43
+
44
+ with open(args.result_upload_file, "w") as f:
45
+ json.dump(all_answers, f)
之前的代码版本/第一版-全部代码/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/archived/convert_vqav2_for_submission.py ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import argparse
3
+ import json
4
+
5
+ from llava.eval.m4c_evaluator import EvalAIAnswerProcessor
6
+
7
+
8
+ def parse_args():
9
+ parser = argparse.ArgumentParser()
10
+ parser.add_argument("--dir", type=str, default="./playground/data/eval/vqav2")
11
+ parser.add_argument("--ckpt", type=str, required=True)
12
+ parser.add_argument("--split", type=str, required=True)
13
+ return parser.parse_args()
14
+
15
+
16
+ if __name__ == "__main__":
17
+
18
+ args = parse_args()
19
+
20
+ src = os.path.join(args.dir, "answers", args.split, args.ckpt, "merge.jsonl")
21
+ test_split = os.path.join(args.dir, "llava_vqav2_mscoco_test2015.jsonl")
22
+ dst = os.path.join(args.dir, "answers_upload", args.split, f"{args.ckpt}.json")
23
+ os.makedirs(os.path.dirname(dst), exist_ok=True)
24
+
25
+ results = []
26
+ error_line = 0
27
+ for line_idx, line in enumerate(open(src)):
28
+ try:
29
+ results.append(json.loads(line))
30
+ except:
31
+ error_line += 1
32
+
33
+ results = {x["question_id"]: x["text"] for x in results}
34
+ test_split = [json.loads(line) for line in open(test_split)]
35
+ split_ids = set([x["question_id"] for x in test_split])
36
+
37
+ print(f"total results: {len(results)}, total split: {len(test_split)}, error_line: {error_line}")
38
+
39
+ all_answers = []
40
+
41
+ answer_processor = EvalAIAnswerProcessor()
42
+
43
+ for x in test_split:
44
+ if x["question_id"] not in results:
45
+ all_answers.append({"question_id": x["question_id"], "answer": ""})
46
+ else:
47
+ all_answers.append({"question_id": x["question_id"], "answer": answer_processor(results[x["question_id"]])})
48
+
49
+ with open(dst, "w") as f:
50
+ json.dump(all_answers, open(dst, "w"))
之前的代码版本/第一版-全部代码/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/archived/data_info.py ADDED
@@ -0,0 +1,124 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import os
3
+ from PIL import Image
4
+ from tqdm import tqdm
5
+ import matplotlib.pyplot as plt
6
+ import numpy as np
7
+
8
+
9
+ def load_data(json_path):
10
+ with open(json_path, "r") as f:
11
+ return json.load(f)
12
+
13
+
14
+ def filter_data(data):
15
+ # filtered_data = [item for item in data if "image" in item and "text" in item["image"]]
16
+ filtered_data = [item for item in data if "image" in item]
17
+ return filtered_data
18
+
19
+
20
+ from multiprocessing import Pool
21
+ import functools
22
+
23
+
24
+ def calculate_image_dimension(item, images_folder):
25
+ image_path = os.path.join(images_folder, item["image"])
26
+ try:
27
+ with Image.open(image_path) as img:
28
+ width, height = img.size
29
+ return width, height
30
+ except Exception as e:
31
+ print(f"Error opening {image_path}: {e}")
32
+ return None, None
33
+
34
+
35
+ def calculate_image_dimensions_multiprocess(filtered_data, images_folder, num_processes=256):
36
+ with Pool(num_processes) as p:
37
+ dimensions = list(tqdm(p.imap(functools.partial(calculate_image_dimension, images_folder=images_folder), filtered_data), total=len(filtered_data), desc="Calculating image dimensions"))
38
+ widths, heights = zip(*[dim for dim in dimensions if dim[0] is not None])
39
+ return list(widths), list(heights)
40
+
41
+
42
+ def tokenize(text):
43
+ return text.split()
44
+
45
+
46
+ def calculate_tokenized_lengths(data):
47
+ lengths = []
48
+ for item in tqdm(data, desc="Tokenizing conversations"):
49
+ for conversation in item["conversations"]:
50
+ tokenized_value = tokenize(conversation["value"])
51
+ lengths.append(len(tokenized_value))
52
+ return lengths
53
+
54
+
55
+ import argparse
56
+
57
+
58
+ def main():
59
+ parser = argparse.ArgumentParser(description="Process data for LLaVA_Next project.")
60
+ parser.add_argument("--json_path", type=str, help="Path to the JSON file containing data.")
61
+ parser.add_argument("--images_folder", type=str, default="/mnt/bn/vl-research/data/llava_data", help="Path to the folder containing images.")
62
+ args = parser.parse_args()
63
+
64
+ llava_instruct_name = args.json_path.split("/")[-1].replace(".json", "")
65
+ json_path = args.json_path
66
+ llava_instruct_name = os.path.basename(json_path).replace(".json", "")
67
+ images_folder = args.images_folder
68
+
69
+ data = load_data(json_path)
70
+ filtered_data = filter_data(data)
71
+
72
+ if len(filtered_data) != 0:
73
+ print(f"Total data items: {len(data)}, Filtered data items: {len(filtered_data)}")
74
+ widths, heights = calculate_image_dimensions_multiprocess(filtered_data, images_folder)
75
+ max_width = max(widths)
76
+ max_height = max(heights)
77
+ print(f"Max width: {max_width}, Max height: {max_height}")
78
+
79
+ tokenized_lengths = calculate_tokenized_lengths(data)
80
+
81
+ fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(24, 12))
82
+
83
+ if len(filtered_data) != 0:
84
+ # Plot 2D histogram
85
+ if min(widths) == max(widths):
86
+ widths_bins = [min(widths), max(widths) + 1]
87
+ else:
88
+ widths_bins = np.arange(min(widths), max(widths) + 100, 100)
89
+
90
+ if min(heights) == max(heights):
91
+ heights_bins = [min(heights), max(heights) + 1]
92
+ else:
93
+ heights_bins = np.arange(min(heights), max(heights) + 100, 100)
94
+
95
+ h, xedges, yedges, image = ax1.hist2d(widths, heights, bins=[widths_bins, heights_bins], cmap=plt.cm.jet, density=True)
96
+ fig.colorbar(image, ax=ax1)
97
+ ax1.set_xlabel("Width")
98
+ ax1.set_ylabel("Height")
99
+ ax1.set_title(f"dist_{llava_instruct_name}_2d_w_h\nMax width: {max(widths)}, Max height: {max(heights)}", fontsize=10)
100
+
101
+ # Plot histogram
102
+ hist, bin_edges = np.histogram(tokenized_lengths, bins=np.arange(0, max(tokenized_lengths) + 10, 100))
103
+ bins = np.arange(0, max(tokenized_lengths) + 10, 100)
104
+ ax2.bar(bin_edges[:-1], hist, width=7, edgecolor="black", log=True)
105
+
106
+ # Display every nth label on the x-axis
107
+ n = 8 # Adjust this value to control the number of labels displayed
108
+ ticks = bins[::n]
109
+ tick_labels = [int(tick) for tick in ticks]
110
+ ax2.set_xticks(ticks)
111
+ ax2.set_xticklabels(tick_labels, rotation=90, fontsize=8)
112
+
113
+ ax2.set_xlim(min(bin_edges), max(bin_edges))
114
+ ax2.set_xlabel("Tokenized Length")
115
+ ax2.set_ylabel("Count (log scale)")
116
+ ax2.set_title(f"dist_{llava_instruct_name}_tokenized_length", fontsize=8)
117
+
118
+ plt.tight_layout()
119
+ plt.savefig(f"/mnt/bn/vl-research/workspace/boli01/projects/LLaVA_Next/notebooks/sft_data/dist_{llava_instruct_name}_combined.png")
120
+ print(f"Plots saved to /mnt/bn/vl-research/workspace/boli01/projects/LLaVA_Next/notebooks/sft_data/dist_{llava_instruct_name}_combined.png")
121
+
122
+
123
+ if __name__ == "__main__":
124
+ main()
之前的代码版本/第一版-全部代码/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/archived/dpo_data_info.py ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import re
3
+
4
+ json_path = "/mnt/bn/vl-research/workspace/boli01/projects/sft_data_workspace/vlfeedback_80k.jsonl"
5
+
6
+ with open(json_path, "r") as f:
7
+ data = f.readlines()
8
+
9
+ data = [json.loads(d) for d in data]
10
+
11
+
12
+ def convert_format(original_data, dimension="Visual Faithfulness"):
13
+ converted_data = []
14
+ for item in original_data:
15
+ # Assuming the best response is the one with the highest helpfulness rating
16
+ best_completion = max(item["completions"], key=lambda x: int(x["annotations"]["Helpfulness"]["Rating"]))
17
+ best_response = best_completion["response"]
18
+ best_model = best_completion["model"]
19
+
20
+ if "†source" in best_response:
21
+ print(best_response)
22
+ # Regex pattern to match the pattern 【digit†source】
23
+ pattern = r"【\d+†source】"
24
+ # Replace the matched patterns with an empty string
25
+ cleaned_text = re.sub(pattern, "", best_response)
26
+ best_response = cleaned_text
27
+ print(f"*****************************************")
28
+ print(best_response)
29
+
30
+ # Assuming the worst response is the one with the lowest helpfulness rating
31
+ worst_completion = min(item["completions"], key=lambda x: int(x["annotations"]["Helpfulness"]["Rating"]))
32
+ worst_response = worst_completion["response"]
33
+
34
+ if "†source" in worst_response:
35
+ print(worst_response)
36
+ # Regex pattern to match the pattern ��digit†source】
37
+ pattern = r"【\d+†source】"
38
+ # Replace the matched patterns with an empty string
39
+ cleaned_text = re.sub(pattern, "", worst_response)
40
+ worst_response = cleaned_text
41
+ print(f"*****************************************")
42
+ print(worst_response)
43
+
44
+ # Extract scores
45
+ best_score = int(best_completion["annotations"][dimension]["Rating"])
46
+ worst_score = int(worst_completion["annotations"][dimension]["Rating"])
47
+
48
+ # Construct the new format
49
+ new_item = {
50
+ "id": item["id"],
51
+ "prompt": item["prompt"],
52
+ "answer": "",
53
+ "image": f"silkie_dpo/{item['id']}.jpg", # Assuming the video ID is the last part of the original ID
54
+ "chosen": best_response,
55
+ "rejected": worst_response,
56
+ "chosen_score": best_score,
57
+ "rejected_score": worst_score,
58
+ }
59
+ converted_data.append(new_item)
60
+
61
+ return converted_data
62
+
63
+
64
+ for dimension in ["Visual Faithfulness", "Helpfulness", "Ethical Considerations"]:
65
+ converted_data = convert_format(data, dimension=dimension)
66
+ with open(f"/mnt/bn/vl-research/data/llava_instruct/dpo_data/silkie_dpo_data_{dimension.replace(' ', '_').lower()}_{len(converted_data)}.json", "w") as f:
67
+ json.dump(converted_data, f, indent=4)
之前的代码版本/第一版-全部代码/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/archived/entry_cmd.sh ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ python3 -m pip install --upgrade pip;
2
+
3
+ export http_proxy=http://sys-proxy-rd-relay.byted.org:8118;
4
+ export https_proxy=http://sys-proxy-rd-relay.byted.org:8118;
5
+
6
+ export HF_HOME=/mnt/bn/vl-research-boli01-cn/.cache/huggingface;
7
+ export HF_TOKEN="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";
8
+ export HF_HUB_ENABLE_HF_TRANSFER="1";
9
+
10
+ cd /mnt/bn/vl-research-boli01-cn/projects/zzz/lmms-eval;
11
+ pip install -e .;
12
+
13
+ cd /mnt/bn/vl-research-boli01-cn/projects/zzz/LLaVA_Next;
14
+ pip install -e .;
15
+
16
+ python3 -m pip install ninja;
17
+ python3 -m pip install flash-attn --no-build-isolation;
18
+
19
+ bash /mnt/bn/vl-research-boli01-cn/projects/zzz/LLaVA_Next/cn_scripts/vicuna/internal0.6m_finetune_llava1.6mix_7b_v0.2_unfreeze.sh
20
+
21
+
22
+ accelerate launch --num_processes 8 --main_process_port 12345 -m lmms_eval \
23
+ --model llava \
24
+ --model_args pretrained="/mnt/bn/vl-research-boli01-cn/projects/zzz/LLaVA_Next/internal_project_checkpoints/llavanext-lmsys_vicuna-7b-v1.5-clip-vit-large-patch14-336-mlp2x_gelu-pretrain_internal0.6m_vicuna_v1_finetune_llava1.6_datamix_unfreezeVIS_1e" \
25
+ --tasks ok_vqa,textcaps_val,mme_test,mmmu,cmmmu,coco2017_cap_val,vizwiz_vqa_val,ai2d,chartqa,pope \
26
+ --batch_size 1 \
27
+ --log_samples \
28
+ --log_samples_suffix debug \
29
+ --output_path ./logs/ \
30
+ --wandb_args 'project=llava-next-lmms-eval,job_type=eval';
之前的代码版本/第一版-全部代码/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/archived/finetune.sh ADDED
@@ -0,0 +1,95 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+
3
+ cd /mnt/bn/vl-research/workspace/boli01/zzzprojects/LLaVA
4
+
5
+ # Install yolk3k if not installed
6
+ if ! pip show yolk3k > /dev/null 2>&1; then
7
+ pip install yolk3k
8
+ fi
9
+
10
+ # Get the installed version of transformers
11
+ installed_version=$(pip show transformers | grep Version | cut -d ' ' -f 2)
12
+
13
+ # Get the latest version of transformers from PyPI
14
+ latest_version=$(yolk -V transformers | cut -d ' ' -f 2)
15
+
16
+ # Check if the installed version is not the latest
17
+ if [ "$installed_version" != "$latest_version" ]; then
18
+ pip install -U transformers
19
+ fi
20
+
21
+ # Get the installed version of deepspeed
22
+ installed_version=$(pip show deepspeed | grep Version | cut -d ' ' -f 2)
23
+
24
+ # Get the latest version of deepspeed from PyPI
25
+ latest_version=$(yolk -V deepspeed | cut -d ' ' -f 2)
26
+
27
+ # Check if the installed version is not the latest
28
+ # pip install deepspeed==0.12.2
29
+ if [ "$installed_version" != "$latest_version" ]; then
30
+ pip install deepspeed==0.12.2
31
+ fi
32
+
33
+ # Install flash-attn if not installed
34
+ if ! pip show flash-attn > /dev/null 2>&1; then
35
+ pip install flash-attn --no-build-isolation
36
+ fi
37
+
38
+ ################## VICUNA ##################
39
+ PROMPT_VERSION=v1
40
+ MODEL_VERSION="vicuna-7b-v1-5"
41
+ ################## VICUNA ##################
42
+
43
+
44
+ ################## project ##################
45
+ PROJECT_NAME="ds_llava-vicuna-7b-v1-5-mlp2x_gelu-pretrain_blip558k_plain"
46
+
47
+ ################## data ##################
48
+ DATA_NAME="mixtral_instruct_158K_V1"
49
+
50
+ # wandb configure
51
+ export WANDB_API_KEY="03fc62d68025c9498cf6493432551badd7d4f953"
52
+ wandb login $WANDB_API_KEY
53
+
54
+ export WANDB_NAME=$PROJECT_NAME--$MODEL_VERSION--$DATA_NAME
55
+
56
+ export WANDB_PROJECT=LLaVA_Mixtral
57
+
58
+ export WANDB_MODE=online
59
+
60
+ # wandb online
61
+
62
+ deepspeed --master_port 26000 \
63
+ llava/train/train_mem.py \
64
+ --deepspeed ./scripts/zero2.json \
65
+ --model_name_or_path ./checkpoints/$MODEL_VERSION \
66
+ --version $PROMPT_VERSION \
67
+ --data_path ./playground/data/$DATA_NAME.json \
68
+ --image_folder /mnt/bn/vl-research/workspace/boli01/data/playground/data/coco/train2017 \
69
+ --vision_tower openai/clip-vit-large-patch14 \
70
+ --pretrain_mm_mlp_adapter ./checkpoints/$PROJECT_NAME/mm_projector.bin \
71
+ --mm_vision_select_layer -2 \
72
+ --mm_projector_type mlp2x_gelu \
73
+ --mm_use_im_start_end False \
74
+ --mm_use_im_patch_token False \
75
+ --bf16 True \
76
+ --output_dir ./checkpoints/llava--$PROJECT_NAME--$MODEL_VERSION--$DATA_NAME--finetune \
77
+ --num_train_epochs 1 \
78
+ --per_device_train_batch_size 16 \
79
+ --per_device_eval_batch_size 4 \
80
+ --gradient_accumulation_steps 1 \
81
+ --evaluation_strategy "no" \
82
+ --save_strategy "steps" \
83
+ --save_steps 50000 \
84
+ --save_total_limit 1 \
85
+ --learning_rate 2e-5 \
86
+ --weight_decay 0. \
87
+ --warmup_ratio 0.03 \
88
+ --lr_scheduler_type "cosine" \
89
+ --logging_steps 1 \
90
+ --tf32 True \
91
+ --model_max_length 2048 \
92
+ --gradient_checkpointing True \
93
+ --dataloader_num_workers 16 \
94
+ --lazy_preprocess True \
95
+ --report_to wandb
之前的代码版本/第一版-全部代码/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/archived/finetune_1.5.sh ADDED
@@ -0,0 +1,99 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ dataset_name=$1
3
+
4
+ # Uncomment and set the following variables correspondingly to run this script:
5
+
6
+ cd /mnt/bn/vl-research/workspace/boli01/zzzprojects/LLaVA
7
+
8
+ # Install yolk3k if not installed
9
+ if ! pip show yolk3k > /dev/null 2>&1; then
10
+ pip install yolk3k
11
+ fi
12
+
13
+ # Get the installed version of transformers
14
+ installed_version=$(pip show transformers | grep Version | cut -d ' ' -f 2)
15
+
16
+ # Get the latest version of transformers from PyPI
17
+ latest_version=$(yolk -V transformers | cut -d ' ' -f 2)
18
+
19
+ # Check if the installed version is not the latest
20
+ if [ "$installed_version" != "$latest_version" ]; then
21
+ pip install -U transformers
22
+ fi
23
+
24
+ # Get the installed version of deepspeed
25
+ installed_version=$(pip show deepspeed | grep Version | cut -d ' ' -f 2)
26
+
27
+ # Get the latest version of deepspeed from PyPI
28
+ latest_version=$(yolk -V deepspeed | cut -d ' ' -f 2)
29
+
30
+ # Check if the installed version is not the latest
31
+ if [ "$installed_version" != "$latest_version" ]; then
32
+ pip install deepspeed==0.12.2
33
+ fi
34
+
35
+ # Install yolk3k if not installed
36
+ if ! pip show flash-attn > /dev/null 2>&1; then
37
+ pip install flash-attn --no-build-isolation
38
+ fi
39
+
40
+
41
+ ################## VICUNA ##################
42
+ PROMPT_VERSION=v1
43
+ MODEL_VERSION="vicuna-7b-v1-5"
44
+ ################## VICUNA ##################
45
+
46
+ ################## project ##################
47
+ PROJECT_NAME="ds_llava-vicuna-7b-v1-5-mlp2x_gelu-pretrain_blip558k_plain"
48
+
49
+ ################## data ##################
50
+ DATA_NAME=$dataset_name
51
+
52
+
53
+ # wandb configure
54
+ export WANDB_API_KEY="03fc62d68025c9498cf6493432551badd7d4f953"
55
+ wandb login $WANDB_API_KEY
56
+
57
+ export WANDB_NAME=$PROJECT_NAME--$MODEL_VERSION--$DATA_NAME
58
+
59
+ export WANDB_PROJECT=LLaVA_Mixtral
60
+
61
+ export WANDB_MODE=online
62
+
63
+ wandb online
64
+
65
+
66
+ deepspeed --master_port 26000 \
67
+ llava/train/train_mem.py \
68
+ --deepspeed ./scripts/zero2.json \
69
+ --model_name_or_path ./checkpoints/$MODEL_VERSION \
70
+ --version $PROMPT_VERSION \
71
+ --data_path ./playground/data/$DATA_NAME.json \
72
+ --image_folder /mnt/bn/vl-research/workspace/boli01/data/playground/data \
73
+ --vision_tower openai/clip-vit-large-patch14 \
74
+ --pretrain_mm_mlp_adapter ./checkpoints/$PROJECT_NAME/mm_projector.bin \
75
+ --mm_vision_select_layer -2 \
76
+ --mm_projector_type mlp2x_gelu \
77
+ --mm_use_im_start_end False \
78
+ --mm_use_im_patch_token False \
79
+ --bf16 True \
80
+ --output_dir ./checkpoints/llava--$PROJECT_NAME--$MODEL_VERSION--$DATA_NAME--finetune \
81
+ --num_train_epochs 1 \
82
+ --per_device_train_batch_size 16 \
83
+ --per_device_eval_batch_size 4 \
84
+ --gradient_accumulation_steps 1 \
85
+ --evaluation_strategy "no" \
86
+ --save_strategy "steps" \
87
+ --save_steps 50000 \
88
+ --save_total_limit 1 \
89
+ --learning_rate 2e-5 \
90
+ --weight_decay 0. \
91
+ --warmup_ratio 0.03 \
92
+ --lr_scheduler_type "cosine" \
93
+ --logging_steps 1 \
94
+ --tf32 True \
95
+ --model_max_length 2048 \
96
+ --gradient_checkpointing True \
97
+ --dataloader_num_workers 16 \
98
+ --lazy_preprocess True \
99
+ --report_to wandb
之前的代码版本/第一版-全部代码/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/archived/finetune_full_schedule.sh ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+
3
+ # Uncomment and set the following variables correspondingly to run this script:
4
+
5
+ ################## VICUNA ##################
6
+ # PROMPT_VERSION=v1
7
+ # MODEL_VERSION="vicuna-v1-3-7b"
8
+ ################## VICUNA ##################
9
+
10
+ ################## LLaMA-2 ##################
11
+ # PROMPT_VERSION="llava_llama_2"
12
+ # MODEL_VERSION="llama-2-7b-chat"
13
+ ################## LLaMA-2 ##################
14
+
15
+ deepspeed llava/train/train_mem.py \
16
+ --deepspeed ./scripts/zero2.json \
17
+ --model_name_or_path ./checkpoints/$MODEL_VERSION \
18
+ --version $PROMPT_VERSION \
19
+ --data_path ./playground/data/llava_instruct_158k.json \
20
+ --image_folder /path/to/coco/train2017 \
21
+ --vision_tower openai/clip-vit-large-patch14 \
22
+ --pretrain_mm_mlp_adapter ./checkpoints/llava-$MODEL_VERSION-pretrain/mm_projector.bin \
23
+ --mm_vision_select_layer -2 \
24
+ --mm_use_im_start_end False \
25
+ --mm_use_im_patch_token False \
26
+ --bf16 True \
27
+ --output_dir ./checkpoints/llava-$MODEL_VERSION-finetune \
28
+ --num_train_epochs 3 \
29
+ --per_device_train_batch_size 16 \
30
+ --per_device_eval_batch_size 4 \
31
+ --gradient_accumulation_steps 1 \
32
+ --evaluation_strategy "no" \
33
+ --save_strategy "steps" \
34
+ --save_steps 50000 \
35
+ --save_total_limit 1 \
36
+ --learning_rate 2e-5 \
37
+ --weight_decay 0. \
38
+ --warmup_ratio 0.03 \
39
+ --lr_scheduler_type "cosine" \
40
+ --logging_steps 1 \
41
+ --tf32 True \
42
+ --model_max_length 2048 \
43
+ --gradient_checkpointing True \
44
+ --dataloader_num_workers 16 \
45
+ --lazy_preprocess True \
46
+ --report_to wandb
之前的代码版本/第一版-全部代码/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/archived/finetune_lora.sh ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+
3
+ # Uncomment and set the following variables correspondingly to run this script:
4
+
5
+ ################## VICUNA ##################
6
+ # PROMPT_VERSION=v1
7
+ # MODEL_VERSION="vicuna-v1-3-7b"
8
+ ################## VICUNA ##################
9
+
10
+ ################## LLaMA-2 ##################
11
+ # PROMPT_VERSION="llava_llama_2"
12
+ # MODEL_VERSION="llama-2-7b-chat"
13
+ ################## LLaMA-2 ##################
14
+
15
+ deepspeed llava/train/train_mem.py \
16
+ --deepspeed ./scripts/zero2.json \
17
+ --lora_enable True \
18
+ --model_name_or_path ./checkpoints/$MODEL_VERSION \
19
+ --version $PROMPT_VERSION \
20
+ --data_path ./playground/data/llava_instruct_80k.json \
21
+ --image_folder /path/to/coco/train2017 \
22
+ --vision_tower openai/clip-vit-large-patch14 \
23
+ --pretrain_mm_mlp_adapter ./checkpoints/llava-$MODEL_VERSION-pretrain/mm_projector.bin \
24
+ --mm_vision_select_layer -2 \
25
+ --mm_use_im_start_end False \
26
+ --mm_use_im_patch_token False \
27
+ --bf16 True \
28
+ --output_dir ./checkpoints/llava-$MODEL_VERSION-finetune_lora \
29
+ --num_train_epochs 1 \
30
+ --per_device_train_batch_size 16 \
31
+ --per_device_eval_batch_size 4 \
32
+ --gradient_accumulation_steps 1 \
33
+ --evaluation_strategy "no" \
34
+ --save_strategy "steps" \
35
+ --save_steps 50000 \
36
+ --save_total_limit 1 \
37
+ --learning_rate 2e-5 \
38
+ --weight_decay 0. \
39
+ --warmup_ratio 0.03 \
40
+ --lr_scheduler_type "cosine" \
41
+ --logging_steps 1 \
42
+ --tf32 True \
43
+ --model_max_length 2048 \
44
+ --gradient_checkpointing True \
45
+ --lazy_preprocess True \
46
+ --dataloader_num_workers 16 \
47
+ --report_to wandb
之前的代码版本/第一版-全部代码/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/archived/finetune_mixtral.sh ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+
3
+ cd /mnt/bn/vl-research/workspace/boli01/zzzprojects/LLaVA
4
+
5
+ # Install yolk3k if not installed
6
+ if ! pip show yolk3k > /dev/null 2>&1; then
7
+ pip install yolk3k
8
+ fi
9
+
10
+ # Get the installed version of transformers
11
+ installed_version=$(pip show transformers | grep Version | cut -d ' ' -f 2)
12
+
13
+ # Get the latest version of transformers from PyPI
14
+ latest_version=$(yolk -V transformers | cut -d ' ' -f 2)
15
+
16
+ # Check if the installed version is not the latest
17
+ if [ "$installed_version" != "$latest_version" ]; then
18
+ pip install -U transformers
19
+ fi
20
+
21
+ # Get the installed version of deepspeed
22
+ installed_version=$(pip show deepspeed | grep Version | cut -d ' ' -f 2)
23
+
24
+ # Get the latest version of deepspeed from PyPI
25
+ latest_version=$(yolk -V deepspeed | cut -d ' ' -f 2)
26
+
27
+ # Check if the installed version is not the latest
28
+ if [ "$installed_version" != "$latest_version" ]; then
29
+ pip install deepspeed==0.12.2
30
+ fi
31
+
32
+ # Install yolk3k if not installed
33
+ if ! pip show flash-attn > /dev/null 2>&1; then
34
+ pip install flash-attn --no-build-isolation
35
+ fi
36
+
37
+
38
+ ################## MISTRAL ##################
39
+ PROMPT_VERSION=mistral_instruct
40
+ MODEL_VERSION="Mistral-7B-Instruct-v0.2"
41
+ ################## VICUNA ##################
42
+
43
+
44
+ ################## project ##################
45
+ PROJECT_NAME="ds_llava-Mistral-7B-Instruct-v0.2-mlp2x_gelu-pretrain_blip558k_plain"
46
+
47
+ ################## data ##################
48
+ DATA_NAME="mixtral_instruct_158K_V1"
49
+
50
+ # wandb configure
51
+ export WANDB_API_KEY="03fc62d68025c9498cf6493432551badd7d4f953"
52
+ wandb login $WANDB_API_KEY
53
+
54
+ export WANDB_NAME=$PROJECT_NAME--$MODEL_VERSION--$DATA_NAME
55
+
56
+ export WANDB_PROJECT=LLaVA_Mixtral
57
+
58
+ export WANDB_MODE=online
59
+
60
+ wandb online
61
+
62
+
63
+ deepspeed --master_port 26000 \
64
+ llava/train/train_mem.py \
65
+ --deepspeed ./scripts/zero2.json \
66
+ --model_name_or_path ./checkpoints/$MODEL_VERSION \
67
+ --version $PROMPT_VERSION \
68
+ --data_path ./playground/data/$DATA_NAME.json \
69
+ --image_folder /mnt/bn/vl-research/workspace/boli01/data/playground/data/coco/train2017 \
70
+ --vision_tower openai/clip-vit-large-patch14 \
71
+ --pretrain_mm_mlp_adapter ./checkpoints/$PROJECT_NAME/mm_projector.bin \
72
+ --mm_vision_select_layer -2 \
73
+ --mm_projector_type mlp2x_gelu \
74
+ --mm_use_im_start_end False \
75
+ --mm_use_im_patch_token False \
76
+ --bf16 True \
77
+ --output_dir ./checkpoints/llava--$PROJECT_NAME--$MODEL_VERSION--$DATA_NAME--finetune \
78
+ --num_train_epochs 1 \
79
+ --per_device_train_batch_size 16 \
80
+ --per_device_eval_batch_size 4 \
81
+ --gradient_accumulation_steps 1 \
82
+ --evaluation_strategy "no" \
83
+ --save_strategy "steps" \
84
+ --save_steps 50000 \
85
+ --save_total_limit 1 \
86
+ --learning_rate 2e-5 \
87
+ --weight_decay 0. \
88
+ --warmup_ratio 0.03 \
89
+ --lr_scheduler_type "cosine" \
90
+ --logging_steps 1 \
91
+ --tf32 True \
92
+ --model_max_length 2048 \
93
+ --gradient_checkpointing True \
94
+ --dataloader_num_workers 16 \
95
+ --lazy_preprocess True \
96
+ --report_to wandb
之前的代码版本/第一版-全部代码/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/archived/finetune_mixtral_1.5.sh ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ dataset_name=$1
3
+
4
+ cd /mnt/bn/vl-research/workspace/yhzhang/LLaVA
5
+
6
+ # Install yolk3k if not installed
7
+ if ! pip show yolk3k > /dev/null 2>&1; then
8
+ pip install yolk3k
9
+ fi
10
+
11
+ # Get the installed version of transformers
12
+ installed_version=$(pip show transformers | grep Version | cut -d ' ' -f 2)
13
+
14
+ # Get the latest version of transformers from PyPI
15
+ latest_version=$(yolk -V transformers | cut -d ' ' -f 2)
16
+
17
+ # Check if the installed version is not the latest
18
+ if [ "$installed_version" != "$latest_version" ]; then
19
+ pip install -U transformers
20
+ fi
21
+
22
+ # Get the installed version of deepspeed
23
+ installed_version=$(pip show deepspeed | grep Version | cut -d ' ' -f 2)
24
+
25
+ # Get the latest version of deepspeed from PyPI
26
+ # latest_version=$(yolk -V deepspeed | cut -d ' ' -f 2)
27
+
28
+ # Check if the installed version is not the latest
29
+ if [ "$installed_version" != "0.12.2" ]; then
30
+ pip install deepspeed==0.12.2
31
+ fi
32
+
33
+ # Install yolk3k if not installed
34
+ if ! pip show flash-attn > /dev/null 2>&1; then
35
+ pip install flash-attn --no-build-isolation
36
+ fi
37
+
38
+ ################## MISTRAL ##################
39
+ PROMPT_VERSION=mistral_instruct
40
+ MODEL_VERSION="Mistral-7B-Instruct-v0.2"
41
+ ################## MISTRAL ##################
42
+
43
+
44
+ ################## project ##################
45
+ PROJECT_NAME="ds_llava-Mistral-7B-Instruct-v0.2-mlp2x_gelu-pretrain_blip558k_plain"
46
+
47
+ ################## data ##################
48
+ DATA_NAME=$dataset_name
49
+
50
+
51
+ # wandb configure
52
+ export WANDB_API_KEY="03fc62d68025c9498cf6493432551badd7d4f953"
53
+ wandb login $WANDB_API_KEY
54
+
55
+ export WANDB_NAME=$PROJECT_NAME--$MODEL_VERSION--$DATA_NAME
56
+
57
+ export WANDB_PROJECT=LLaVA_Mixtral
58
+
59
+ export WANDB_MODE=online
60
+
61
+ wandb online
62
+
63
+ deepspeed --master_port 26000 \
64
+ llava/train/train_mem.py \
65
+ --deepspeed ./scripts/zero2.json \
66
+ --model_name_or_path ./checkpoints/$MODEL_VERSION \
67
+ --version $PROMPT_VERSION \
68
+ --data_path ./playground/data/$DATA_NAME.json \
69
+ --image_folder /mnt/bn/vl-research/workspace/boli01/data/playground/data \
70
+ --vision_tower openai/clip-vit-large-patch14 \
71
+ --pretrain_mm_mlp_adapter ./checkpoints/$PROJECT_NAME/mm_projector.bin \
72
+ --mm_vision_select_layer -2 \
73
+ --mm_projector_type mlp2x_gelu \
74
+ --mm_use_im_start_end False \
75
+ --mm_use_im_patch_token False \
76
+ --bf16 True \
77
+ --output_dir ./checkpoints/llava--$PROJECT_NAME--$MODEL_VERSION--$DATA_NAME--finetune \
78
+ --num_train_epochs 1 \
79
+ --per_device_train_batch_size 16 \
80
+ --per_device_eval_batch_size 4 \
81
+ --gradient_accumulation_steps 1 \
82
+ --evaluation_strategy "no" \
83
+ --save_strategy "steps" \
84
+ --save_steps 50000 \
85
+ --save_total_limit 1 \
86
+ --learning_rate 2e-5 \
87
+ --weight_decay 0. \
88
+ --warmup_ratio 0.03 \
89
+ --lr_scheduler_type "cosine" \
90
+ --logging_steps 1 \
91
+ --tf32 True \
92
+ --model_max_length 2048 \
93
+ --gradient_checkpointing True \
94
+ --dataloader_num_workers 16 \
95
+ --lazy_preprocess True
96
+ # --report_to wandb
之前的代码版本/第一版-全部代码/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/archived/finetune_mixtral_1.6_336px_anyres.sh ADDED
@@ -0,0 +1,100 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ dataset_name=$1
3
+
4
+ cd /mnt/bn/vl-research/workspace/boli01/projects/LLaVA_Next
5
+
6
+ # Install yolk3k if not installed
7
+ if ! pip show yolk3k > /dev/null 2>&1; then
8
+ pip install yolk3k
9
+ fi
10
+
11
+ pip install pydantic
12
+
13
+ # Get the installed version of transformers
14
+ installed_version=$(pip show transformers | grep Version | cut -d ' ' -f 2)
15
+
16
+ # Get the latest version of transformers from PyPI
17
+ latest_version=$(yolk -V transformers | cut -d ' ' -f 2)
18
+
19
+ # Check if the installed version is not the latest
20
+ if [ "$installed_version" != "4.36.2" ]; then
21
+ pip install transformers==4.36.2
22
+ fi
23
+
24
+ # Get the installed version of deepspeed
25
+ installed_version=$(pip show deepspeed | grep Version | cut -d ' ' -f 2)
26
+
27
+
28
+ # Check if the installed version is not the latest
29
+ if [ "$installed_version" != "0.12.2" ]; then
30
+ pip install deepspeed==0.12.2
31
+ fi
32
+
33
+ # Install flash-atten if not installed
34
+ if ! pip show flash-attn > /dev/null 2>&1; then
35
+ pip install flash-attn --no-build-isolation
36
+ fi
37
+
38
+ ################## MISTRAL ##################
39
+ PROMPT_VERSION=mistral_instruct
40
+ MODEL_VERSION="Mistral-7B-Instruct-v0.2"
41
+ ################## MISTRAL ##################
42
+
43
+
44
+ ################## project ##################
45
+ PROJECT_NAME="ds_llava-Mistral-7B-Instruct-v0.2-clip_large_336px-mlp2x_gelu-pretrain_blip558k_plain"
46
+
47
+ ################## data ##################
48
+ DATA_NAME=$dataset_name
49
+
50
+
51
+ # wandb configure
52
+ export WANDB_API_KEY=e464cc107357c7b38e87f239bc3eb2ce5fb73c7c
53
+ export WANDB_PROJECT=llava
54
+
55
+ export WANDB_NAME=$PROJECT_NAME--$DATA_NAME--336px--anyres--sft
56
+
57
+ export WANDB_MODE=online
58
+
59
+ wandb online
60
+
61
+ deepspeed --master_port 26000 \
62
+ llava/train/train_mem.py \
63
+ --deepspeed ./scripts/zero3.json \
64
+ --model_name_or_path /mnt/bn/vl-research/workspace/project/2023/LLaVA/checkpoints/$MODEL_VERSION \
65
+ --version $PROMPT_VERSION \
66
+ --data_path ./playground/data/$DATA_NAME.json \
67
+ --image_folder /mnt/bn/vl-research/workspace/boli01/data/playground/data \
68
+ --vision_tower openai/clip-vit-large-patch14-336 \
69
+ --pretrain_mm_mlp_adapter /mnt/bn/vl-research/workspace/project/2023/LLaVA/checkpoints/ds_llava-Mistral-7B-Instruct-v0.2-clip_large_336px-mlp2x_gelu-pretrain_blip558k_plain/mm_projector.bin \
70
+ --mm_projector_type mlp2x_gelu \
71
+ --mm_vision_select_layer -2 \
72
+ --mm_use_im_start_end False \
73
+ --mm_use_im_patch_token False \
74
+ --group_by_modality_length True \
75
+ --unfreeze_mm_vision_tower True \
76
+ --mm_vision_tower_lr 2e-6 \
77
+ --image_aspect_ratio anyres \
78
+ --image_grid_pinpoints "[(336, 672), (672, 336), (672, 672), (1008, 336), (336, 1008)]" \
79
+ --mm_patch_merge_type spatial_unpad \
80
+ --bf16 True \
81
+ --output_dir ./checkpoints/$PROJECT_NAME--$DATA_NAME--336px--anyres--sft \
82
+ --num_train_epochs 9 \
83
+ --per_device_train_batch_size 8 \
84
+ --per_device_eval_batch_size 4 \
85
+ --gradient_accumulation_steps 1 \
86
+ --evaluation_strategy "no" \
87
+ --save_strategy "epoch" \
88
+ --save_steps 1500 \
89
+ --learning_rate 5e-6 \
90
+ --weight_decay 0. \
91
+ --warmup_ratio 0.03 \
92
+ --lr_scheduler_type "cosine" \
93
+ --logging_steps 1 \
94
+ --tf32 True \
95
+ --model_max_length 4096 \
96
+ --gradient_checkpointing True \
97
+ --dataloader_num_workers 8 \
98
+ --lazy_preprocess True \
99
+ --report_to wandb
100
+
之前的代码版本/第一版-全部代码/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/archived/finetune_mixtral_1.6_336px_anyres_freeze_vision.sh ADDED
@@ -0,0 +1,97 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ dataset_name=$1
3
+
4
+ cd /mnt/bn/vl-research/workspace/yhzhang/LLaVA
5
+
6
+ # Install yolk3k if not installed
7
+ if ! pip show yolk3k > /dev/null 2>&1; then
8
+ pip install yolk3k
9
+ fi
10
+
11
+ pip install pydantic
12
+
13
+ # Get the installed version of transformers
14
+ installed_version=$(pip show transformers | grep Version | cut -d ' ' -f 2)
15
+
16
+ # Get the latest version of transformers from PyPI
17
+ latest_version=$(yolk -V transformers | cut -d ' ' -f 2)
18
+
19
+ # Check if the installed version is not the latest
20
+ if [ "$installed_version" != "4.36.2" ]; then
21
+ pip install transformers==4.36.2
22
+ fi
23
+
24
+ # Get the installed version of deepspeed
25
+ installed_version=$(pip show deepspeed | grep Version | cut -d ' ' -f 2)
26
+
27
+
28
+ # Check if the installed version is not the latest
29
+ if [ "$installed_version" != "0.12.2" ]; then
30
+ pip install deepspeed==0.12.2
31
+ fi
32
+
33
+ # Install flash-atten if not installed
34
+ if ! pip show flash-attn > /dev/null 2>&1; then
35
+ pip install flash-attn --no-build-isolation
36
+ fi
37
+
38
+ ################## MISTRAL ##################
39
+ PROMPT_VERSION=mistral_instruct
40
+ MODEL_VERSION="Mistral-7B-Instruct-v0.2"
41
+ ################## MISTRAL ##################
42
+
43
+
44
+ ################## project ##################
45
+ PROJECT_NAME="ds_llava-Mistral-7B-Instruct-v0.2-clip_large_336px-mlp2x_gelu-pretrain_blip558k_plain"
46
+
47
+ ################## data ##################
48
+ DATA_NAME=$dataset_name
49
+
50
+
51
+ # wandb configure
52
+ export WANDB_API_KEY=e464cc107357c7b38e87f239bc3eb2ce5fb73c7c
53
+ export WANDB_PROJECT=llava
54
+
55
+ export WANDB_NAME=$PROJECT_NAME--$DATA_NAME--336px--unfreeze--anyres--sft
56
+
57
+ export WANDB_MODE=online
58
+
59
+ wandb online
60
+
61
+ deepspeed --master_port 26000 \
62
+ llava/train/train_mem.py \
63
+ --deepspeed ./scripts/zero3.json \
64
+ --model_name_or_path ./checkpoints/$MODEL_VERSION \
65
+ --version $PROMPT_VERSION \
66
+ --data_path ./playground/data/$DATA_NAME.json \
67
+ --image_folder /mnt/bn/vl-research/workspace/boli01/data/playground/data \
68
+ --vision_tower openai/clip-vit-large-patch14-336 \
69
+ --pretrain_mm_mlp_adapter /mnt/bn/vl-research/workspace/project/2023/LLaVA/checkpoints/ds_llava-Mistral-7B-Instruct-v0.2-clip_large_336px-mlp2x_gelu-pretrain_blip558k_plain/mm_projector.bin \
70
+ --mm_vision_select_layer -2 \
71
+ --mm_projector_type mlp2x_gelu \
72
+ --mm_use_im_start_end False \
73
+ --mm_use_im_patch_token False \
74
+ --group_by_modality_length True \
75
+ --image_aspect_ratio anyres \
76
+ --image_grid_pinpoints "[(336, 672), (672, 336), (672, 672), (1008, 336), (336, 1008)]" \
77
+ --mm_patch_merge_type spatial_unpad \
78
+ --bf16 True \
79
+ --output_dir ./checkpoints/$PROJECT_NAME--$DATA_NAME--336px--anyres--unfreeze--sft \
80
+ --num_train_epochs 1 \
81
+ --per_device_train_batch_size 16 \
82
+ --per_device_eval_batch_size 4 \
83
+ --gradient_accumulation_steps 1 \
84
+ --evaluation_strategy "no" \
85
+ --save_strategy "steps" \
86
+ --save_steps 50000 \
87
+ --save_total_limit 1 \
88
+ --learning_rate 2e-5 \
89
+ --weight_decay 0. \
90
+ --warmup_ratio 0.03 \
91
+ --lr_scheduler_type "cosine" \
92
+ --logging_steps 1 \
93
+ --tf32 True \
94
+ --model_max_length 2048 \
95
+ --gradient_checkpointing True \
96
+ --dataloader_num_workers 16 \
97
+
之前的代码版本/第一版-全部代码/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/archived/finetune_mixtral_1.6_336px_anyres_lmms_eval.sh ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+
3
+ # set up wandb
4
+ export WANDB_API_KEY=a651c244635bc6f913ab654af3f0eebaecdc9381
5
+ export WANDB_ENTITY=llava-vl
6
+ export WANDB_PROJECT=llava-next
7
+ export PYTHONWARNINGS="ignore"
8
+
9
+ cd /mnt/bn/vl-research/workspace/boli01/projects/lmms-eval
10
+
11
+ pip install -e .
12
+
13
+ # set up llava dev env
14
+ cd /mnt/bn/vl-research/workspace/boli01/projects/LLaVA_Next
15
+
16
+ ################## MISTRAL ##################
17
+ PROMPT_VERSION=mistral_instruct
18
+ MODEL_VERSION="Mistral-7B-Instruct-v0.2"
19
+ ################## MISTRAL ##################
20
+
21
+ ################## project ##################
22
+ PROJECT_NAME="ds_llava-Mistral-7B-Instruct-v0.2-clip_large_336px-mlp2x_gelu-pretrain_blip558k_plain"
23
+
24
+ ################## data ##################
25
+ DATA_NAME='llava_caps20k_chartqa19k'
26
+
27
+ export WANDB_NAME=$PROJECT_NAME--$DATA_NAME--336px--anyres--sft
28
+ export WANDB_MODE=online
29
+
30
+ wandb online
31
+
32
+ CUDA_VISIBLE_DEVICES="0,1,2,3,4,5,6,7" deepspeed --master_port 26000 --include localhost:0,1,2,3,4,5,6,7 llava/train/train_mem.py \
33
+ --deepspeed ./scripts/zero3_offload.json \
34
+ --model_name_or_path mistralai/$MODEL_VERSION \
35
+ --version $PROMPT_VERSION \
36
+ --data_path ./playground/data/llava_instruct/$DATA_NAME.json \
37
+ --image_folder /mnt/bn/vl-research/data/llava \
38
+ --vision_tower openai/clip-vit-large-patch14-336 \
39
+ --mm_projector_type mlp2x_gelu \
40
+ --mm_vision_select_layer -2 \
41
+ --mm_use_im_start_end False \
42
+ --mm_use_im_patch_token False \
43
+ --group_by_modality_length True \
44
+ --unfreeze_mm_vision_tower True \
45
+ --mm_vision_tower_lr 2e-6 \
46
+ --image_aspect_ratio anyres \
47
+ --image_grid_pinpoints "[(336, 672), (672, 336), (672, 672), (1008, 336), (336, 1008)]" \
48
+ --mm_patch_merge_type spatial_unpad \
49
+ --bf16 True \
50
+ --output_dir ./checkpoints/$PROJECT_NAME--llava1.6--336px--anyres--sft \
51
+ --num_train_epochs 1 \
52
+ --per_device_train_batch_size 8 \
53
+ --per_device_eval_batch_size 4 \
54
+ --gradient_accumulation_steps 1 \
55
+ --evaluation_strategy "no" \
56
+ --save_strategy "steps" \
57
+ --save_steps 1500 \
58
+ --learning_rate 2e-5 \
59
+ --weight_decay 0. \
60
+ --warmup_ratio 0.03 \
61
+ --lr_scheduler_type "cosine" \
62
+ --logging_steps 1 \
63
+ --tf32 True \
64
+ --model_max_length 4096 \
65
+ --gradient_checkpointing True \
66
+ --dataloader_num_workers 32 \
67
+ --lazy_preprocess True \
68
+ --report_to wandb \
69
+ --run_name $WANDB_NAME
70
+ # starting here is the args for evaluation
71
+ --eval_num_processes 4 \
72
+ --task_names mme,docvqa_val \
73
+ --model_args pretrained=./checkpoints/$PROJECT_NAME--$DATA_NAME--336px--anyres--sft \
74
+ --limit 8 \
75
+ --batch_size 1 \
76
+ --log_samples \
77
+ --log_samples_suffix debug \
78
+ --output_path ./logs/
之前的代码版本/第一版-全部代码/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/archived/finetune_mixtral_copy.sh ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+
3
+ cd /mnt/bn/vl-research/workspace/boli01/zzzprojects/LLaVA
4
+
5
+ # Install yolk3k if not installed
6
+ if ! pip show yolk3k > /dev/null 2>&1; then
7
+ pip install yolk3k
8
+ fi
9
+
10
+ # Get the installed version of transformers
11
+ installed_version=$(pip show transformers | grep Version | cut -d ' ' -f 2)
12
+
13
+ # Get the latest version of transformers from PyPI
14
+ latest_version=$(yolk -V transformers | cut -d ' ' -f 2)
15
+
16
+ # Check if the installed version is not the latest
17
+ if [ "$installed_version" != "$latest_version" ]; then
18
+ pip install -U transformers
19
+ fi
20
+
21
+ # Get the installed version of deepspeed
22
+ installed_version=$(pip show deepspeed | grep Version | cut -d ' ' -f 2)
23
+
24
+ # Get the latest version of deepspeed from PyPI
25
+ latest_version=$(yolk -V deepspeed | cut -d ' ' -f 2)
26
+
27
+ # Check if the installed version is not the latest
28
+ if [ "$installed_version" != "$latest_version" ]; then
29
+ pip install deepspeed==0.12.2
30
+ fi
31
+
32
+ # Install yolk3k if not installed
33
+ if ! pip show flash-attn > /dev/null 2>&1; then
34
+ pip install flash-attn --no-build-isolation
35
+ fi
36
+
37
+
38
+ ################## MISTRAL ##################
39
+ PROMPT_VERSION=mistral_instruct
40
+ MODEL_VERSION="Mistral-7B-Instruct-v0.2"
41
+ ################## VICUNA ##################
42
+
43
+
44
+ ################## project ##################
45
+ PROJECT_NAME="ds_llava-Mistral-7B-Instruct-v0.2-mlp2x_gelu-pretrain_blip558k_plain"
46
+
47
+ ################## data ##################
48
+ DATA_NAME="llava_instruct_150k"
49
+
50
+ # wandb configure
51
+ export WANDB_API_KEY="03fc62d68025c9498cf6493432551badd7d4f953"
52
+ wandb login $WANDB_API_KEY
53
+
54
+ export WANDB_NAME=$PROJECT_NAME--$MODEL_VERSION--$DATA_NAME
55
+
56
+ export WANDB_PROJECT=LLaVA_Mixtral
57
+
58
+ export WANDB_MODE=online
59
+
60
+ wandb online
61
+
62
+
63
+ deepspeed --master_port 26000 \
64
+ llava/train/train_mem.py \
65
+ --deepspeed ./scripts/zero2.json \
66
+ --model_name_or_path ./checkpoints/$MODEL_VERSION \
67
+ --version $PROMPT_VERSION \
68
+ --data_path ./playground/data/$DATA_NAME.json \
69
+ --image_folder /mnt/bn/vl-research/workspace/boli01/data/playground/data/coco/train2017 \
70
+ --vision_tower openai/clip-vit-large-patch14 \
71
+ --pretrain_mm_mlp_adapter ./checkpoints/$PROJECT_NAME/mm_projector.bin \
72
+ --mm_vision_select_layer -2 \
73
+ --mm_projector_type mlp2x_gelu \
74
+ --mm_use_im_start_end False \
75
+ --mm_use_im_patch_token False \
76
+ --bf16 True \
77
+ --output_dir ./checkpoints/llava--$PROJECT_NAME--$MODEL_VERSION--$DATA_NAME--finetune \
78
+ --num_train_epochs 1 \
79
+ --per_device_train_batch_size 16 \
80
+ --per_device_eval_batch_size 4 \
81
+ --gradient_accumulation_steps 1 \
82
+ --evaluation_strategy "no" \
83
+ --save_strategy "steps" \
84
+ --save_steps 50000 \
85
+ --save_total_limit 1 \
86
+ --learning_rate 2e-5 \
87
+ --weight_decay 0. \
88
+ --warmup_ratio 0.03 \
89
+ --lr_scheduler_type "cosine" \
90
+ --logging_steps 1 \
91
+ --tf32 True \
92
+ --model_max_length 2048 \
93
+ --gradient_checkpointing True \
94
+ --dataloader_num_workers 16 \
95
+ --lazy_preprocess True \
96
+ --report_to wandb
之前的代码版本/第一版-全部代码/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/archived/finetune_qlora.sh ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+
3
+ # Uncomment and set the following variables correspondingly to run this script:
4
+
5
+ ################## VICUNA ##################
6
+ # PROMPT_VERSION=v1
7
+ # MODEL_VERSION="vicuna-v1-3-7b"
8
+ ################## VICUNA ##################
9
+
10
+ ################## LLaMA-2 ##################
11
+ # PROMPT_VERSION="llava_llama_2"
12
+ # MODEL_VERSION="llama-2-7b-chat"
13
+ ################## LLaMA-2 ##################
14
+
15
+ deepspeed llava/train/train_mem.py \
16
+ --deepspeed ./scripts/zero2.json \
17
+ --lora_enable True \
18
+ --bits 4 \
19
+ --model_name_or_path ./checkpoints/$MODEL_VERSION \
20
+ --version $PROMPT_VERSION \
21
+ --data_path ./playground/data/llava_instruct_80k.json \
22
+ --image_folder /path/to/coco/train2017 \
23
+ --vision_tower openai/clip-vit-large-patch14 \
24
+ --pretrain_mm_mlp_adapter ./checkpoints/llava-$MODEL_VERSION-pretrain/mm_projector.bin \
25
+ --mm_vision_select_layer -2 \
26
+ --mm_use_im_start_end False \
27
+ --mm_use_im_patch_token False \
28
+ --bf16 True \
29
+ --output_dir ./checkpoints/llava-$MODEL_VERSION-finetune_lora \
30
+ --num_train_epochs 1 \
31
+ --per_device_train_batch_size 16 \
32
+ --per_device_eval_batch_size 4 \
33
+ --gradient_accumulation_steps 1 \
34
+ --evaluation_strategy "no" \
35
+ --save_strategy "steps" \
36
+ --save_steps 50000 \
37
+ --save_total_limit 1 \
38
+ --learning_rate 2e-5 \
39
+ --weight_decay 0. \
40
+ --warmup_ratio 0.03 \
41
+ --lr_scheduler_type "cosine" \
42
+ --logging_steps 1 \
43
+ --tf32 True \
44
+ --model_max_length 2048 \
45
+ --gradient_checkpointing True \
46
+ --lazy_preprocess True \
47
+ --dataloader_num_workers 16 \
48
+ --report_to wandb
之前的代码版本/第一版-全部代码/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/archived/finetune_sqa.sh ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+
3
+ deepspeed llava/train/train_mem.py \
4
+ --deepspeed ./scripts/zero2.json \
5
+ --model_name_or_path lmsys/vicuna-13b-v1.3 \
6
+ --version $PROMPT_VERSION \
7
+ --data_path /Data/ScienceQA/data/scienceqa/llava_train_QCM-LEA.json \
8
+ --image_folder /Data/ScienceQA/data/scienceqa/images/train \
9
+ --vision_tower openai/clip-vit-large-patch14 \
10
+ --pretrain_mm_mlp_adapter ./checkpoints/huggingface/liuhaotian/llava-pretrain-vicuna-13b-v1.3/mm_projector.bin \
11
+ --mm_vision_select_layer -2 \
12
+ --mm_use_im_start_end False \
13
+ --mm_use_im_patch_token False \
14
+ --bf16 True \
15
+ --output_dir ./checkpoints/llava-vicuna-13b-v1.3-pretrain_lcs558k_plain-ScienceQA_QCM_LEA-12e \
16
+ --num_train_epochs 12 \
17
+ --per_device_train_batch_size 16 \
18
+ --per_device_eval_batch_size 4 \
19
+ --gradient_accumulation_steps 1 \
20
+ --evaluation_strategy "no" \
21
+ --save_strategy "steps" \
22
+ --save_steps 50000 \
23
+ --save_total_limit 1 \
24
+ --learning_rate 2e-5 \
25
+ --weight_decay 0. \
26
+ --warmup_ratio 0.03 \
27
+ --lr_scheduler_type "cosine" \
28
+ --logging_steps 1 \
29
+ --tf32 True \
30
+ --model_max_length 2048 \
31
+ --gradient_checkpointing True \
32
+ --dataloader_num_workers 16 \
33
+ --lazy_preprocess True \
34
+ --report_to wandb
之前的代码版本/第一版-全部代码/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/archived/merge_lora_weights.py ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ from llava.model.builder import load_pretrained_model
3
+ from llava.mm_utils import get_model_name_from_path
4
+
5
+
6
+ def merge_lora(args):
7
+ model_name = get_model_name_from_path(args.model_path)
8
+ tokenizer, model, image_processor, context_len = load_pretrained_model(args.model_path, args.model_base, model_name, device_map="cpu")
9
+
10
+ model.save_pretrained(args.save_model_path)
11
+ tokenizer.save_pretrained(args.save_model_path)
12
+
13
+
14
+ if __name__ == "__main__":
15
+ parser = argparse.ArgumentParser()
16
+ parser.add_argument("--model-path", type=str, required=True)
17
+ parser.add_argument("--model-base", type=str, required=True)
18
+ parser.add_argument("--save-model-path", type=str, required=True)
19
+
20
+ args = parser.parse_args()
21
+
22
+ merge_lora(args)
之前的代码版本/第一版-全部代码/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/archived/pretrain.sh ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+
3
+ # Uncomment and set the following variables correspondingly to run this script:
4
+
5
+ # MODEL_VERSION=vicuna-v1-3-7b
6
+ # MODEL_VERSION=llama-2-7b-chat
7
+
8
+ ########### DO NOT CHANGE ###########
9
+ ########### USE THIS FOR BOTH ###########
10
+ PROMPT_VERSION=plain
11
+ ########### DO NOT CHANGE ###########
12
+
13
+ deepspeed llava/train/train_mem.py \
14
+ --deepspeed ./scripts/zero2.json \
15
+ --model_name_or_path ./checkpoints/$MODEL_VERSION \
16
+ --version $PROMPT_VERSION \
17
+ --data_path /path/to/pretrain_data.json \
18
+ --image_folder /path/to/images \
19
+ --vision_tower openai/clip-vit-large-patch14 \
20
+ --tune_mm_mlp_adapter True \
21
+ --mm_vision_select_layer -2 \
22
+ --mm_use_im_start_end False \
23
+ --mm_use_im_patch_token False \
24
+ --bf16 True \
25
+ --output_dir ./checkpoints/llava-$MODEL_VERSION-pretrain \
26
+ --num_train_epochs 1 \
27
+ --per_device_train_batch_size 16 \
28
+ --per_device_eval_batch_size 4 \
29
+ --gradient_accumulation_steps 1 \
30
+ --evaluation_strategy "no" \
31
+ --save_strategy "steps" \
32
+ --save_steps 24000 \
33
+ --learning_rate 2e-3 \
34
+ --weight_decay 0. \
35
+ --warmup_ratio 0.03 \
36
+ --lr_scheduler_type "cosine" \
37
+ --logging_steps 1 \
38
+ --tf32 True \
39
+ --model_max_length 2048 \
40
+ --gradient_checkpointing True \
41
+ --dataloader_num_workers 16 \
42
+ --lazy_preprocess True \
43
+ --report_to wandb
之前的代码版本/第一版-全部代码/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/archived/quick_check.py ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import os
3
+ import argparse
4
+ from tqdm import tqdm
5
+ import yaml
6
+
7
+
8
+ def check_missing_images(json_path, images_folder):
9
+ data = json.load(open(json_path, "r"))
10
+ missing_data = []
11
+
12
+ for i, d in enumerate(tqdm(data)):
13
+ image = d["image"] if "image" in d else ""
14
+ if image != "":
15
+ path = os.path.join(images_folder, image)
16
+ if not os.path.exists(path):
17
+ print(f"Missing image: {path}")
18
+ missing_data.append(d)
19
+
20
+ return missing_data
21
+
22
+
23
+ def read_yaml_to_llava_data(yaml_path, images_folder):
24
+ print(f"Reading YAML file: {yaml_path}")
25
+ with open(yaml_path, "r") as f:
26
+ data = yaml.safe_load(f)
27
+
28
+ llava_json_paths = data["datasets"]
29
+ for item in llava_json_paths:
30
+ json_path = item["json_path"]
31
+ missing_data = check_missing_images(json_path, images_folder)
32
+ if len(missing_data) > 0:
33
+ print(f"Missing images in {json_path}:")
34
+ for d in missing_data:
35
+ print(d)
36
+
37
+
38
+ def direct_check_llava_data(json_path, images_folder):
39
+ missing_data = check_missing_images(json_path, images_folder)
40
+ if len(missing_data) > 0:
41
+ print(f"Missing images in {json_path}:")
42
+ for d in missing_data:
43
+ print(d)
44
+
45
+
46
+ if __name__ == "__main__":
47
+ parser = argparse.ArgumentParser(description="Check for missing images in dataset.")
48
+ parser.add_argument("--yaml_path", type=str, default="", help="Path to the YAML file containing the dataset.")
49
+ parser.add_argument("--json_path", type=str, default="", help="Path to the JSON file containing the dataset.")
50
+ parser.add_argument("--images_folder", type=str, default="/mnt/bn/vl-research/data/llava_data", help="Path to the folder containing the images.")
51
+
52
+ args = parser.parse_args()
53
+
54
+ if args.json_path != "":
55
+ direct_check_llava_data(args.json_path, args.images_folder)
56
+ elif args.yaml_path != "":
57
+ read_yaml_to_llava_data(args.yaml_path, args.images_folder)
之前的代码版本/第一版-全部代码/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/archived/sqa_eval_batch.sh ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+
3
+ CHUNKS=8
4
+ for IDX in {0..7}; do
5
+ CUDA_VISIBLE_DEVICES=$IDX python -m llava.eval.model_vqa_science \
6
+ --model-path liuhaotian/llava-lcs558k-scienceqa-vicuna-13b-v1.3 \
7
+ --question-file ~/haotian/datasets/ScienceQA/data/scienceqa/llava_test_QCM-LEA.json \
8
+ --image-folder ~/haotian/datasets/ScienceQA/data/scienceqa/images/test \
9
+ --answers-file ./test_llava-13b-chunk$CHUNKS_$IDX.jsonl \
10
+ --num-chunks $CHUNKS \
11
+ --chunk-idx $IDX \
12
+ --conv-mode llava_v1 &
13
+ done