diff --git "a/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/datas/Radrestruct/test_qa_pairs/1415.json" "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/datas/Radrestruct/test_qa_pairs/1415.json" new file mode 100644 index 0000000000000000000000000000000000000000..8a5e486409fab84926b5de80dd82cc0f43220c73 --- /dev/null +++ "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/datas/Radrestruct/test_qa_pairs/1415.json" @@ -0,0 +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"}]] \ No newline at end of file diff --git "a/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/datas/Radrestruct/test_qa_pairs/1552.json" "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/datas/Radrestruct/test_qa_pairs/1552.json" new file mode 100644 index 0000000000000000000000000000000000000000..564fddf12baf3ee59c108924553b116dc311ed4f --- /dev/null +++ "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/datas/Radrestruct/test_qa_pairs/1552.json" @@ -0,0 +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"}]] \ No newline at end of file diff --git "a/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/datas/Radrestruct/test_qa_pairs/194.json" "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/datas/Radrestruct/test_qa_pairs/194.json" new file mode 100644 index 0000000000000000000000000000000000000000..1c04f220640e294f3d0270d08f2e1a12e4e99db2 --- /dev/null +++ "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/datas/Radrestruct/test_qa_pairs/194.json" @@ -0,0 +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"}]] \ No newline at end of file diff --git "a/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/datas/Radrestruct/test_qa_pairs/2555.json" "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/datas/Radrestruct/test_qa_pairs/2555.json" new file mode 100644 index 0000000000000000000000000000000000000000..1f59455f438ad37f258bd895e6b2e8262939f4e3 --- /dev/null +++ "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/datas/Radrestruct/test_qa_pairs/2555.json" @@ -0,0 +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"}]] \ No newline at end of file diff --git "a/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/datas/Radrestruct/test_qa_pairs/2861.json" "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/datas/Radrestruct/test_qa_pairs/2861.json" new file mode 100644 index 0000000000000000000000000000000000000000..8a5e486409fab84926b5de80dd82cc0f43220c73 --- /dev/null +++ "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/datas/Radrestruct/test_qa_pairs/2861.json" @@ -0,0 +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"}]] \ No newline at end of file diff --git "a/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/datas/Radrestruct/test_qa_pairs/3236.json" "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/datas/Radrestruct/test_qa_pairs/3236.json" new file mode 100644 index 0000000000000000000000000000000000000000..8a5e486409fab84926b5de80dd82cc0f43220c73 --- /dev/null +++ "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/datas/Radrestruct/test_qa_pairs/3236.json" @@ -0,0 +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"}]] \ No newline at end of file diff --git "a/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/datas/Radrestruct/test_qa_pairs/3465.json" "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/datas/Radrestruct/test_qa_pairs/3465.json" new file mode 100644 index 0000000000000000000000000000000000000000..8a5e486409fab84926b5de80dd82cc0f43220c73 --- /dev/null +++ "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/datas/Radrestruct/test_qa_pairs/3465.json" @@ -0,0 +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"}]] \ No newline at end of file diff --git "a/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/datas/Radrestruct/test_qa_pairs/3678.json" "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/datas/Radrestruct/test_qa_pairs/3678.json" new file mode 100644 index 0000000000000000000000000000000000000000..d7b1b449f47cba31d2bc5163d6ab70946832c194 --- /dev/null +++ "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/datas/Radrestruct/test_qa_pairs/3678.json" @@ -0,0 +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"}]] \ No newline at end of file diff --git "a/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/datas/Radrestruct/test_qa_pairs/3954.json" "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/datas/Radrestruct/test_qa_pairs/3954.json" new file mode 100644 index 0000000000000000000000000000000000000000..8a5e486409fab84926b5de80dd82cc0f43220c73 --- /dev/null +++ "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/datas/Radrestruct/test_qa_pairs/3954.json" @@ -0,0 +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"}]] \ No newline at end of file diff --git "a/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/llava/__init__.py" "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/llava/__init__.py" new file mode 100644 index 0000000000000000000000000000000000000000..4d1f016db1028101d45ba7d68cb3f0bcb558c2bb --- /dev/null +++ "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/llava/__init__.py" @@ -0,0 +1 @@ +from .model import LlavaLlamaForCausalLM diff --git "a/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/llava/constants.py" "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/llava/constants.py" new file mode 100644 index 0000000000000000000000000000000000000000..be8cf0204969a6c973f442b383d8e425d684e826 --- /dev/null +++ "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/llava/constants.py" @@ -0,0 +1,12 @@ +CONTROLLER_HEART_BEAT_EXPIRATION = 30 +WORKER_HEART_BEAT_INTERVAL = 15 + +LOGDIR = "." + +# Model Constants +IGNORE_INDEX = -100 +IMAGE_TOKEN_INDEX = -200 +DEFAULT_IMAGE_TOKEN = "" +DEFAULT_IMAGE_PATCH_TOKEN = "" +DEFAULT_IM_START_TOKEN = "" +DEFAULT_IM_END_TOKEN = "" diff --git "a/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/llava/conversation.py" "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/llava/conversation.py" new file mode 100644 index 0000000000000000000000000000000000000000..66ef6963253d30e314a78372869091bd0181021a --- /dev/null +++ "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/llava/conversation.py" @@ -0,0 +1,597 @@ +import dataclasses +from enum import auto, Enum +from typing import List, Any, Dict, Union, Tuple +import re +import base64 +from io import BytesIO +from PIL import Image +from transformers import AutoTokenizer + + +class SeparatorStyle(Enum): + """Different separator style.""" + + SINGLE = auto() + TWO = auto() + MPT = auto() + PLAIN = auto() + CHATML = auto() + LLAMA_2 = auto() + LLAMA_3 = auto() + QWEN = auto() + GEMMA = auto() + + +@dataclasses.dataclass +class Conversation: + """A class that keeps all conversation history.""" + + system: str + roles: List[str] + messages: List[List[str]] + offset: int + sep_style: SeparatorStyle = SeparatorStyle.SINGLE + sep: str = "###" + sep2: str = None + version: str = "Unknown" + + tokenizer_id: str = "" + tokenizer: Any = None + # Stop criteria (the default one is EOS token) + stop_str: Union[str, List[str]] = None + # Stops generation if meeting any token in this list + stop_token_ids: List[int] = None + + skip_next: bool = False + + def get_prompt(self): + messages = self.messages + if len(messages) > 0 and type(messages[0][1]) is tuple: + messages = self.messages.copy() + init_role, init_msg = messages[0].copy() + init_msg = init_msg[0] + if "mmtag" in self.version: + init_msg = init_msg.replace("", "").strip() + messages[0] = (init_role, init_msg) + messages.insert(0, (self.roles[0], "")) + messages.insert(1, (self.roles[1], "Received.")) + elif not init_msg.startswith(""): + init_msg = init_msg.replace("", "").strip() + messages[0] = (init_role, "\n" + init_msg) + else: + messages[0] = (init_role, init_msg) + + if self.sep_style == SeparatorStyle.SINGLE: + ret = self.system + self.sep + for role, message in messages: + if message: + if type(message) is tuple: + message, _, _ = message + ret += role + ": " + message + self.sep + else: + ret += role + ":" + + elif self.sep_style == SeparatorStyle.TWO: + seps = [self.sep, self.sep2] + ret = self.system + seps[0] + for i, (role, message) in enumerate(messages): + if message: + if type(message) is tuple: + message, _, _ = message + ret += role + ": " + message + seps[i % 2] + else: + ret += role + ":" + + elif self.sep_style == SeparatorStyle.CHATML: + ret = "" if self.system == "" else self.system + self.sep + "\n" + for role, message in messages: + if message: + if type(message) is tuple: + message, images, _ = message + message = "" * len(images) + message + ret += role + "\n" + message + self.sep + "\n" + else: + ret += role + "\n" + return ret + + elif self.sep_style == SeparatorStyle.LLAMA_3: + if self.tokenizer is None: + raise ValueError("Llama 3 tokenizer is not available. Make sure you have the necessary permissions.") + chat_template_messages = [{"role": "system", "content": self.system}] + for role, message in messages: + if message: + if type(message) is tuple: + message, images = message + message = "" * len(images) + message + chat_template_messages.append({"role": role, "content": message}) + + # print(chat_template_messages) + return self.tokenizer.apply_chat_template(chat_template_messages, tokenize=False, add_generation_prompt=True) + # ret = "" if self.system == "" else self.system + self.sep + "\n" + # for role, message in messages: + # if message: + # if type(message) is tuple: + # message, images = message + # message = "" * len(images) + message + # ret += role + "\n" + message + self.sep + "\n" + # else: + # ret += role + "\n" + # return ret + + elif self.sep_style == SeparatorStyle.MPT: + ret = self.system + self.sep + for role, message in messages: + if message: + if type(message) is tuple: + message, _, _ = message + ret += role + message + self.sep + else: + ret += role + + elif self.sep_style == SeparatorStyle.GEMMA: + ret = "" + for i, (role, message) in enumerate(messages): + assert role == self.roles[i % 2], "Conversation should alternate user/assistant/user/assistant/..." + if message: + if type(message) is tuple: + message, _, _ = message + ret += role + message + self.sep + else: + ret += role + + elif self.sep_style == SeparatorStyle.LLAMA_2: + wrap_sys = lambda msg: f"<>\n{msg}\n<>\n\n" if len(msg) > 0 else msg + wrap_inst = lambda msg: f"[INST] {msg} [/INST]" + ret = "" + + for i, (role, message) in enumerate(messages): + if i == 0: + assert message, "first message should not be none" + assert role == self.roles[0], "first message should come from user" + if message: + if type(message) is tuple: + message, _, _ = message + if i == 0: + message = wrap_sys(self.system) + message + if i % 2 == 0: + message = wrap_inst(message) + ret += self.sep + message + else: + ret += " " + message + " " + self.sep2 + else: + ret += "" + ret = ret.lstrip(self.sep) + + elif self.sep_style == SeparatorStyle.PLAIN: + seps = [self.sep, self.sep2] + ret = self.system + for i, (role, message) in enumerate(messages): + if message: + if type(message) is tuple: + message, _, _ = message + ret += message + seps[i % 2] + else: + ret += "" + else: + raise ValueError(f"Invalid style: {self.sep_style}") + + return ret + + def append_message(self, role, message): + self.messages.append([role, message]) + + def process_image(self, image, image_process_mode, return_pil=False, image_format="PNG"): + if image_process_mode == "Pad": + + def expand2square(pil_img, background_color=(122, 116, 104)): + width, height = pil_img.size + if width == height: + return pil_img + elif width > height: + result = Image.new(pil_img.mode, (width, width), background_color) + result.paste(pil_img, (0, (width - height) // 2)) + return result + else: + result = Image.new(pil_img.mode, (height, height), background_color) + result.paste(pil_img, ((height - width) // 2, 0)) + return result + + image = expand2square(image) + elif image_process_mode in ["Default", "Crop"]: + pass + elif image_process_mode == "Resize": + image = image.resize((336, 336)) + else: + raise ValueError(f"Invalid image_process_mode: {image_process_mode}") + + if type(image) is not Image.Image: + image = Image.open(image).convert("RGB") + + max_hw, min_hw = max(image.size), min(image.size) + aspect_ratio = max_hw / min_hw + max_len, min_len = 672, 448 + shortest_edge = int(min(max_len / aspect_ratio, min_len, min_hw)) + longest_edge = int(shortest_edge * aspect_ratio) + W, H = image.size + if H > W: + H, W = longest_edge, shortest_edge + else: + H, W = shortest_edge, longest_edge + image = image.resize((W, H)) + if return_pil: + return image + else: + buffered = BytesIO() + image.save(buffered, format=image_format) + img_b64_str = base64.b64encode(buffered.getvalue()).decode() + return img_b64_str + + def get_images(self, return_pil=False, return_path=False): + images = [] + for i, (role, msg) in enumerate(self.messages[self.offset :]): + if i % 2 == 0: + if type(msg) is tuple: + msg, image, image_process_mode = msg + if type(image) != list: + image = [image] + for img in image: + if not return_path and self.is_image_file(img): + img = self.process_image(img, image_process_mode, return_pil=return_pil) + else: + images.append(img) + return images + + def is_image_file(self, filename): + image_extensions = [".png", ".jpg", ".jpeg", ".gif", ".bmp", ".tiff", ".webp"] + return any(filename.lower().endswith(ext) for ext in image_extensions) + + def is_video_file(self, filename): + video_extensions = [".mp4", ".mov", ".avi", ".mkv", ".wmv", ".flv", ".mpeg", ".mpg"] + return any(filename.lower().endswith(ext) for ext in video_extensions) + + def to_gradio_chatbot(self): + ret = [] + for i, (role, msg) in enumerate(self.messages[self.offset :]): + if i % 2 == 0: + if type(msg) is tuple: + msg, image, image_process_mode = msg + if type(image) != list: + image = [image] + if len(image) == 1: + msg = "\n" + msg.replace("", "").strip() + else: + msg = re.sub(r"()\n(?=)", r"\1 ", msg) + + img_str_list = [] + for img in image: + if self.is_image_file(img): + img_b64_str = self.process_image(img, "Default", return_pil=False, image_format="JPEG") + img_str = f'' + img_str_list.append(img_str) + elif self.is_video_file(img): + ret.append(((img,), None)) + + msg = msg.strip() + img_place_holder = "" + for img_str in img_str_list: + img_place_holder += f"{img_str}\n\n" + + if len(img_str_list) > 0: + msg = f"{img_place_holder}\n\n{msg}" + + if len(msg) > 0: + ret.append([msg, None]) + else: + ret.append([msg, None]) + else: + ret[-1][-1] = msg + return ret + + def copy(self): + 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) + + def dict(self): + if len(self.get_images()) > 0: + return { + "system": self.system, + "roles": self.roles, + "messages": [[x, y[0] if type(y) is tuple else y] for x, y in self.messages], + "offset": self.offset, + "sep": self.sep, + "sep2": self.sep2, + } + return { + "system": self.system, + "roles": self.roles, + "messages": self.messages, + "offset": self.offset, + "sep": self.sep, + "sep2": self.sep2, + } + + +conv_vicuna_v0 = Conversation( + 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.", + roles=("Human", "Assistant"), + messages=[ + ["Human", "What are the key differences between renewable and non-renewable energy sources?"], + [ + "Assistant", + "Renewable energy sources are those that can be replenished naturally in a relatively " + "short amount of time, such as solar, wind, hydro, geothermal, and biomass. " + "Non-renewable energy sources, on the other hand, are finite and will eventually be " + "depleted, such as coal, oil, and natural gas. Here are some key differences between " + "renewable and non-renewable energy sources:\n" + "1. Availability: Renewable energy sources are virtually inexhaustible, while non-renewable " + "energy sources are finite and will eventually run out.\n" + "2. Environmental impact: Renewable energy sources have a much lower environmental impact " + "than non-renewable sources, which can lead to air and water pollution, greenhouse gas emissions, " + "and other negative effects.\n" + "3. Cost: Renewable energy sources can be more expensive to initially set up, but they typically " + "have lower operational costs than non-renewable sources.\n" + "4. Reliability: Renewable energy sources are often more reliable and can be used in more remote " + "locations than non-renewable sources.\n" + "5. Flexibility: Renewable energy sources are often more flexible and can be adapted to different " + "situations and needs, while non-renewable sources are more rigid and inflexible.\n" + "6. Sustainability: Renewable energy sources are more sustainable over the long term, while " + "non-renewable sources are not, and their depletion can lead to economic and social instability.\n", + ], + ], + offset=2, + sep_style=SeparatorStyle.SINGLE, + sep="###", +) + +conv_vicuna_v1 = Conversation( + 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.", + roles=("USER", "ASSISTANT"), + version="v1", + messages=[], + offset=0, + sep_style=SeparatorStyle.TWO, + sep=" ", + sep2="", +) + +conv_llama_2 = Conversation( + 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. + +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.""", + roles=("USER", "ASSISTANT"), + version="llama_v2", + messages=[], + offset=0, + sep_style=SeparatorStyle.LLAMA_2, + sep="", + sep2="", +) + +conv_llava_llama_2 = Conversation( + 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.", + roles=("USER", "ASSISTANT"), + version="llama_v2", + messages=[], + offset=0, + sep_style=SeparatorStyle.LLAMA_2, + sep="", + sep2="", +) + +def safe_load_tokenizer(tokenizer_id): + try: + return AutoTokenizer.from_pretrained(tokenizer_id) + except Exception: + return None + +conv_llava_llama_3 = Conversation( + 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.", + roles=("user", "assistant"), + version="llama_v3", + messages=[], + offset=0, + sep="<|eot_id|>", + sep_style=SeparatorStyle.LLAMA_3, + tokenizer_id="meta-llama/Meta-Llama-3-8B-Instruct", + tokenizer=safe_load_tokenizer("meta-llama/Meta-Llama-3-8B-Instruct"), + stop_token_ids=[128009], +) + +conv_mistral_instruct = Conversation( + system="", + roles=("USER", "ASSISTANT"), + version="llama_v2", + messages=[], + offset=0, + sep_style=SeparatorStyle.LLAMA_2, + sep="", + sep2="", +) + +conv_llava_llama_2_simple = Conversation( + system="Answer the questions about the visual content that the user provides.", + roles=("USER", "ASSISTANT"), + version="llama_v2", + messages=[], + offset=0, + sep_style=SeparatorStyle.LLAMA_2, + sep="", + sep2="", +) + +conv_llava_llama_2_mmtag = Conversation( + system="Answer the questions about the visual content that the user provides." "The visual content will be provided with the following format: visual content.", + roles=("USER", "ASSISTANT"), + version="llama_v2_mmtag", + messages=[], + offset=0, + sep_style=SeparatorStyle.LLAMA_2, + sep="", + sep2="", +) + +conv_mpt = Conversation( + system="""<|im_start|>system +A conversation between a user and an LLM-based AI assistant. The assistant gives helpful and honest answers.""", + roles=("<|im_start|>user\n", "<|im_start|>assistant\n"), + version="mpt", + messages=[], + offset=0, + sep_style=SeparatorStyle.MPT, + sep="<|im_end|>", +) + +conv_qwen = Conversation( + system="""<|im_start|>system +You are a helpful assistant.""", + roles=("<|im_start|>user", "<|im_start|>assistant"), + version="qwen", + messages=[], + offset=0, + sep_style=SeparatorStyle.CHATML, + sep="<|im_end|>", +) + +conv_qwen_2_5 = Conversation( + system="""<|im_start|>system +You are Qwen, created by Alibaba Cloud. You are a helpful assistant.""", + roles=("<|im_start|>user", "<|im_start|>assistant"), + version="qwen", + messages=[], + offset=0, + sep_style=SeparatorStyle.CHATML, + sep="<|im_end|>", +) + +conv_gemma_instruct = Conversation(system="", roles=("user\n", "model\n"), version="gemma", messages=[], offset=0, sep_style=SeparatorStyle.GEMMA, sep="\n") + +conv_llava_plain = Conversation( + system="", + roles=("", ""), + messages=[], + offset=0, + sep_style=SeparatorStyle.PLAIN, + sep="\n", +) + +conv_llava_v0 = Conversation( + 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.", + roles=("Human", "Assistant"), + messages=[], + offset=0, + sep_style=SeparatorStyle.SINGLE, + sep="###", +) + +conv_llava_v0_mmtag = Conversation( + system="A chat between a curious user and an artificial intelligence assistant. " + "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." + "The visual content will be provided with the following format: visual content.", + roles=("Human", "Assistant"), + messages=[], + offset=0, + sep_style=SeparatorStyle.SINGLE, + sep="###", + version="v0_mmtag", +) + +conv_llava_v1 = Conversation( + 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.", + roles=("USER", "ASSISTANT"), + version="v1", + messages=[], + offset=0, + sep_style=SeparatorStyle.TWO, + sep=" ", + sep2="", +) + +conv_llava_v1_mmtag = Conversation( + system="A chat between a curious user and an artificial intelligence assistant. " + "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." + "The visual content will be provided with the following format: visual content.", + roles=("USER", "ASSISTANT"), + messages=[], + offset=0, + sep_style=SeparatorStyle.TWO, + sep=" ", + sep2="", + version="v1_mmtag", +) + +conv_mistral_orca = Conversation( + system="""<|im_start|>system +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!""", + roles=("<|im_start|>user\n", "<|im_start|>assistant\n"), + version="mpt", + messages=[], + offset=0, + sep_style=SeparatorStyle.MPT, + sep="<|im_end|>", +) + +conv_mistral_zephyr = Conversation( + system="""<|system|> +You are a helpful AI assistant.""", + roles=("<|user|>\n", "<|assistant|>\n"), + version="mpt", + messages=[], + offset=0, + sep_style=SeparatorStyle.MPT, + sep="", +) + +conv_mistral_direct = Conversation( + system="""<|im_start|>system +Answer the questions.""", + roles=("<|im_start|>user\n", "<|im_start|>assistant\n"), + version="mpt", + messages=[], + offset=0, + sep_style=SeparatorStyle.MPT, + sep="<|im_end|>", +) + +conv_chatml_direct = Conversation( + system="""<|im_start|>system +Answer the questions.""", + roles=("<|im_start|>user\n", "<|im_start|>assistant\n"), + version="mpt", + messages=[], + offset=0, + sep_style=SeparatorStyle.MPT, + sep="<|im_end|>", +) + +default_conversation = conv_vicuna_v0 +conv_templates = { + "default": conv_vicuna_v0, + "v0": conv_vicuna_v0, + "v1": conv_vicuna_v1, + "vicuna_v1": conv_vicuna_v1, + "llama_2": conv_llama_2, + "mistral_instruct": conv_mistral_instruct, + "mistral_orca": conv_mistral_orca, + "mistral_zephyr": conv_mistral_zephyr, + "mistral_direct": conv_mistral_direct, + "plain": conv_llava_plain, + "v0_plain": conv_llava_plain, + "chatml_direct": conv_chatml_direct, + "llava_v0": conv_llava_v0, + "llava_v0_mmtag": conv_llava_v0_mmtag, + "llava_v1": conv_llava_v1, + "llava_v1_mmtag": conv_llava_v1_mmtag, + "llava_llama_2": conv_llava_llama_2, + "llava_llama_3": conv_llava_llama_3, + "llava_llama_2_simple": conv_llava_llama_2_simple, + "llava_llama_2_mmtag": conv_llava_llama_2_mmtag, + "llava_mistral_instruct": conv_mistral_instruct, + "mpt": conv_mpt, + "qwen_1_5": conv_qwen, + "qwen_2": conv_qwen, + "qwen_2_5": conv_qwen_2_5, + "gemma_instruct": conv_gemma_instruct, +} + + +if __name__ == "__main__": + print(default_conversation.get_prompt()) diff --git "a/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/llava/mm_utils.py" "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/llava/mm_utils.py" new file mode 100644 index 0000000000000000000000000000000000000000..62a3e50905a9c18799ade86af7d62c59eb029115 --- /dev/null +++ "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/llava/mm_utils.py" @@ -0,0 +1,395 @@ +from PIL import Image +from io import BytesIO +import base64 +import math +import ast +import re +import torch +from transformers import StoppingCriteria +from llava.constants import IMAGE_TOKEN_INDEX + + +def resize_and_center_crop(image, shortest_edge_length): + # Calculate new dimensions and resize + aspect_ratio = float(image.width) / float(image.height) + if aspect_ratio > 1: + new_width = int(shortest_edge_length * aspect_ratio) + new_height = shortest_edge_length + else: + new_width = shortest_edge_length + new_height = int(shortest_edge_length / aspect_ratio) + resized_image = image.resize((new_width, new_height), Image.ANTIALIAS) + + # Calculate the position and perform the center crop + left = (new_width - shortest_edge_length) / 2 + top = (new_height - shortest_edge_length) / 2 + right = (new_width + shortest_edge_length) / 2 + bottom = (new_height + shortest_edge_length) / 2 + cropped_image = resized_image.crop((left, top, right, bottom)) + + return cropped_image + + +def auto_pad_images(image, grid_params): + assert isinstance(image, Image.Image), "Input should be a Pillow Image" + assert len(grid_params) > 0, "Grid parameters should not be empty" + + # Step 1: Calculate and find the closest aspect ratio + input_width, input_height = image.size + input_aspect_ratio = input_width / input_height + candidate_resolutions = [(w / h, w, h) for w in grid_params for h in grid_params] + closest_aspect_ratio = min(candidate_resolutions, key=lambda x: abs(input_aspect_ratio - x[0])) + + candidate_resolutions = [(x[1], x[2]) for x in candidate_resolutions if abs(x[0] - closest_aspect_ratio[0]) < 1e-3] + + target_resolution = min(candidate_resolutions, key=lambda res: abs(max(input_width, input_height) / max(res) - 1)) + + resize_width, resize_height = target_resolution + if input_width > input_height: + resize_height = int(resize_width / input_aspect_ratio) + else: + resize_width = int(resize_height * input_aspect_ratio) + resized_image = image.resize((resize_width, resize_height), Image.ANTIALIAS) + + # Step 5: Pad the resized image if necessary to match the target resolution + pad_width = target_resolution[0] - resize_width + pad_height = target_resolution[1] - resize_height + padded_image = Image.new("RGB", target_resolution, color=(0, 0, 0)) + padded_image.paste(resized_image, (pad_width // 2, pad_height // 2)) + + return padded_image + + +def extract_patches(image, patch_size, overlap_ratio): + assert isinstance(image, Image.Image), "Input should be a Pillow Image" + assert patch_size > 0, "Patch size should be greater than 0" + assert 0 <= overlap_ratio < 1, "Overlap ratio should be between 0 and 1" + + W, H = image.size + patches = [] + + stride = int(patch_size * (1 - overlap_ratio)) + + num_patches_y = (H - patch_size) // stride + 1 + num_patches_x = (W - patch_size) // stride + 1 + + y_start = (H - (num_patches_y - 1) * stride - patch_size) // 2 + x_start = (W - (num_patches_x - 1) * stride - patch_size) // 2 + + for y in range(y_start, y_start + num_patches_y * stride, stride): + for x in range(x_start, x_start + num_patches_x * stride, stride): + patch = image.crop((x, y, x + patch_size, y + patch_size)) + patches.append(patch) + + return patches + + +def process_highres_image_crop_split(image, data_args, processor=None): + crop_resolution = data_args.image_crop_resolution + split_resolution = data_args.image_split_resolution + if processor is None: + processor = data_args.image_processor + image_crop = resize_and_center_crop(image, crop_resolution) + image_patches = extract_patches(image_crop, patch_size=split_resolution, overlap_ratio=0) + image_patches = [processor.preprocess(image_patch, return_tensors="pt")["pixel_values"][0] for image_patch in image_patches] + return torch.stack(image_patches, dim=0) + + +def process_highres_image(image, processor, grid_pinpoints): + grid_params = [int(x) for x in grid_pinpoints.split(",")] + width_height = max(image.size) + fit_grid_params = [x for x in grid_params if x >= width_height] + if len(fit_grid_params) == 0: + select_size = max(grid_params) + else: + select_size = min(fit_grid_params) + # FIXME: always select the 448 + select_size = max(grid_params) + image_padded = expand2square(image, tuple(int(x * 255) for x in processor.image_mean)) + + # FIXME: this seems to be a bug that it always resizes instead of padding + image_original_resize = image.resize((processor.size["shortest_edge"], processor.size["shortest_edge"])) + image_padded = image_padded.resize((select_size, select_size)) + image_patches = extract_patches(image_padded, patch_size=processor.size["shortest_edge"], overlap_ratio=0) + image_patches = [image_original_resize] + image_patches + image_patches = [processor.preprocess(image_patch, return_tensors="pt")["pixel_values"][0] for image_patch in image_patches] + return torch.stack(image_patches, dim=0) + + +def select_best_resolution(original_size, possible_resolutions): + """ + Selects the best resolution from a list of possible resolutions based on the original size. + + Args: + original_size (tuple): The original size of the image in the format (width, height). + possible_resolutions (list): A list of possible resolutions in the format [(width1, height1), (width2, height2), ...]. + + Returns: + tuple: The best fit resolution in the format (width, height). + """ + original_width, original_height = original_size + best_fit = None + max_effective_resolution = 0 + min_wasted_resolution = float("inf") + + for width, height in possible_resolutions: + # Calculate the downscaled size to keep the aspect ratio + scale = min(width / original_width, height / original_height) + downscaled_width, downscaled_height = int(original_width * scale), int(original_height * scale) + + # Calculate effective and wasted resolutions + effective_resolution = min(downscaled_width * downscaled_height, original_width * original_height) + wasted_resolution = (width * height) - effective_resolution + + if effective_resolution > max_effective_resolution or (effective_resolution == max_effective_resolution and wasted_resolution < min_wasted_resolution): + max_effective_resolution = effective_resolution + min_wasted_resolution = wasted_resolution + best_fit = (width, height) + + return best_fit + + +def resize_and_pad_image(image, target_resolution): + """ + Resize and pad an image to a target resolution while maintaining aspect ratio. + + Args: + image (PIL.Image.Image): The input image. + target_resolution (tuple): The target resolution (width, height) of the image. + + Returns: + PIL.Image.Image: The resized and padded image. + """ + original_width, original_height = image.size + target_width, target_height = target_resolution + + # Determine which dimension (width or height) to fill + scale_w = target_width / original_width + scale_h = target_height / original_height + + if scale_w < scale_h: + # Width will be filled completely + new_width = target_width + new_height = min(math.ceil(original_height * scale_w), target_height) + else: + # Height will be filled completely + new_height = target_height + new_width = min(math.ceil(original_width * scale_h), target_width) + + # Resize the image + resized_image = image.resize((new_width, new_height)) + + # Create a new image with the target size and paste the resized image onto it + new_image = Image.new("RGB", (target_width, target_height), (0, 0, 0)) + paste_x = (target_width - new_width) // 2 + paste_y = (target_height - new_height) // 2 + new_image.paste(resized_image, (paste_x, paste_y)) + + return new_image + + +def divide_to_patches(image, patch_size): + """ + Divides an image into patches of a specified size. + + Args: + image (PIL.Image.Image): The input image. + patch_size (int): The size of each patch. + + Returns: + list: A list of PIL.Image.Image objects representing the patches. + """ + patches = [] + width, height = image.size + for i in range(0, height, patch_size): + for j in range(0, width, patch_size): + box = (j, i, j + patch_size, i + patch_size) + patch = image.crop(box) + patches.append(patch) + + return patches + + +def get_anyres_image_grid_shape(image_size, grid_pinpoints, patch_size): + """ + Calculate the shape of the image patch grid after the preprocessing for images of any resolution. + + Args: + image_size (tuple): The size of the input image in the format (width, height). + grid_pinpoints (str): A string representation of a list of possible resolutions. + patch_size (int): The size of each image patch. + + Returns: + tuple: The shape of the image patch grid in the format (width, height). + """ + if isinstance(grid_pinpoints, str) and "x" in grid_pinpoints: + assert patch_size in [224, 336, 384, 448, 512], "patch_size should be in [224, 336, 384, 448, 512]" + # Use regex to extract the range from the input string + matches = re.findall(r"\((\d+)x(\d+)\)", grid_pinpoints) + range_start = tuple(map(int, matches[0])) + range_end = tuple(map(int, matches[-1])) + # Generate a matrix of tuples from (range_start[0], range_start[1]) to (range_end[0], range_end[1]) + 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)] + # Multiply all elements by patch_size + grid_pinpoints = [[dim * patch_size for dim in pair] for pair in grid_pinpoints] + if type(grid_pinpoints) is list: + possible_resolutions = grid_pinpoints + else: + possible_resolutions = ast.literal_eval(grid_pinpoints) + width, height = select_best_resolution(image_size, possible_resolutions) + return width // patch_size, height // patch_size + + +def process_anyres_image(image, processor, grid_pinpoints): + """ + Process an image with variable resolutions. + + Args: + image (PIL.Image.Image): The input image to be processed. + processor: The image processor object. + grid_pinpoints (str): A string representation of a list of possible resolutions. + + Returns: + torch.Tensor: A tensor containing the processed image patches. + """ + # Convert grid_pinpoints from string to list + if isinstance(grid_pinpoints, str) and "x" in grid_pinpoints: + try: + patch_size = processor.size[0] + except Exception as e: + patch_size = processor.size["shortest_edge"] + assert patch_size in [224, 336, 384, 448, 512], "patch_size should be in [224, 336, 384, 448, 512]" + # Use regex to extract the range from the input string + matches = re.findall(r"\((\d+)x(\d+)\)", grid_pinpoints) + range_start = tuple(map(int, matches[0])) + range_end = tuple(map(int, matches[-1])) + # Generate a matrix of tuples from (range_start[0], range_start[1]) to (range_end[0], range_end[1]) + 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)] + # Multiply all elements by patch_size + grid_pinpoints = [[dim * patch_size for dim in pair] for pair in grid_pinpoints] + + if type(grid_pinpoints) is list: + possible_resolutions = grid_pinpoints + else: + possible_resolutions = ast.literal_eval(grid_pinpoints) + best_resolution = select_best_resolution(image.size, possible_resolutions) + image_padded = resize_and_pad_image(image, best_resolution) + + patches = divide_to_patches(image_padded, processor.crop_size["height"]) + + # FIXME: this seems to be a bug that it resizes instead of pad. + # but to keep it consistent with previous, i will keep it as it is + # TODO: uncomment below to ablate with the padding + if isinstance(processor.size, dict): + shortest_edge = processor.size["shortest_edge"] + else: + shortest_edge = min(processor.size) + image_original_resize = image.resize((shortest_edge, shortest_edge)) + # image_padded_square = expand2square(image, tuple(int(x*255) for x in processor.image_mean)) + # image_original_resize = image_padded_square.resize((processor.size['shortest_edge'], processor.size['shortest_edge'])) + + image_patches = [image_original_resize] + patches + image_patches = [processor.preprocess(image_patch, return_tensors="pt")["pixel_values"][0] for image_patch in image_patches] + return torch.stack(image_patches, dim=0) + + +def load_image_from_base64(image): + return Image.open(BytesIO(base64.b64decode(image))) + + +def expand2square(pil_img, background_color): + width, height = pil_img.size + if width == height: + return pil_img + elif width > height: + result = Image.new(pil_img.mode, (width, width), background_color) + result.paste(pil_img, (0, (width - height) // 2)) + return result + else: + result = Image.new(pil_img.mode, (height, height), background_color) + result.paste(pil_img, ((height - width) // 2, 0)) + return result + + +def process_images(images, image_processor, model_cfg): + image_aspect_ratio = getattr(model_cfg, "image_aspect_ratio", None) + new_images = [] + if image_aspect_ratio == "highres": + for image in images: + image = process_highres_image(image, image_processor, model_cfg.image_grid_pinpoints) + new_images.append(image) + elif image_aspect_ratio == "anyres" or "anyres_max" in image_aspect_ratio: + for image in images: + image = process_anyres_image(image, image_processor, model_cfg.image_grid_pinpoints) + new_images.append(image) + elif image_aspect_ratio == "crop_split": + for image in images: + image = process_highres_image_crop_split(image, model_cfg, image_processor) + new_images.append(image) + elif image_aspect_ratio == "pad": + for image in images: + image = expand2square(image, tuple(int(x * 255) for x in image_processor.image_mean)) + image = image_processor.preprocess(image, return_tensors="pt")["pixel_values"][0] + new_images.append(image) + else: + return image_processor.preprocess(images, return_tensors="pt")["pixel_values"] + if all(x.shape == new_images[0].shape for x in new_images): + new_images = torch.stack(new_images, dim=0) + return new_images + + +def tokenizer_image_token(prompt, tokenizer, image_token_index=IMAGE_TOKEN_INDEX, return_tensors=None): + prompt_chunks = [tokenizer(chunk).input_ids for chunk in prompt.split("")] + + def insert_separator(X, sep): + return [ele for sublist in zip(X, [sep] * len(X)) for ele in sublist][:-1] + + input_ids = [] + offset = 0 + if len(prompt_chunks) > 0 and len(prompt_chunks[0]) > 0 and prompt_chunks[0][0] == tokenizer.bos_token_id: + offset = 1 + input_ids.append(prompt_chunks[0][0]) + + for x in insert_separator(prompt_chunks, [image_token_index] * (offset + 1)): + input_ids.extend(x[offset:]) + + if return_tensors is not None: + if return_tensors == "pt": + return torch.tensor(input_ids, dtype=torch.long) + raise ValueError(f"Unsupported tensor type: {return_tensors}") + return input_ids + + +def get_model_name_from_path(model_path): + model_path = model_path.strip("/") + model_paths = model_path.split("/") + if model_paths[-1].startswith("checkpoint-"): + return model_paths[-2] + "_" + model_paths[-1] + else: + return model_paths[-1] + + +class KeywordsStoppingCriteria(StoppingCriteria): + def __init__(self, keywords, tokenizer, input_ids): + self.keywords = keywords + self.keyword_ids = [] + for keyword in keywords: + cur_keyword_ids = tokenizer(keyword).input_ids + if len(cur_keyword_ids) > 1 and cur_keyword_ids[0] == tokenizer.bos_token_id: + cur_keyword_ids = cur_keyword_ids[1:] + self.keyword_ids.append(torch.tensor(cur_keyword_ids)) + self.tokenizer = tokenizer + self.start_len = input_ids.shape[1] + + def __call__(self, output_ids: torch.LongTensor, scores: torch.FloatTensor, **kwargs) -> bool: + assert output_ids.shape[0] == 1, "Only support batch size 1 (yet)" # TODO + offset = min(output_ids.shape[1] - self.start_len, 3) + self.keyword_ids = [keyword_id.to(output_ids.device) for keyword_id in self.keyword_ids] + for keyword_id in self.keyword_ids: + if output_ids[0, -keyword_id.shape[0] :] == keyword_id: + return True + outputs = self.tokenizer.batch_decode(output_ids[:, -offset:], skip_special_tokens=True)[0] + for keyword in self.keywords: + if keyword in outputs: + return True + return False diff --git "a/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/llava/model/__init__.py" "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/llava/model/__init__.py" new file mode 100644 index 0000000000000000000000000000000000000000..1abf0b3629098c96a54fb6942e87e9f44e0e217d --- /dev/null +++ "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/llava/model/__init__.py" @@ -0,0 +1,16 @@ +import os + +AVAILABLE_MODELS = { + "llava_llama": "LlavaLlamaForCausalLM, LlavaConfig", + "llava_qwen": "LlavaQwenForCausalLM, LlavaQwenConfig", + "llava_mistral": "LlavaMistralForCausalLM, LlavaMistralConfig", + "llava_mixtral": "LlavaMixtralForCausalLM, LlavaMixtralConfig", + # "llava_qwen_moe": "LlavaQwenMoeForCausalLM, LlavaQwenMoeConfig", + # Add other models as needed +} + +for model_name, model_classes in AVAILABLE_MODELS.items(): + try: + exec(f"from .language_model.{model_name} import {model_classes}") + except Exception as e: + print(f"Failed to import {model_name} from llava.language_model.{model_name}. Error: {e}") diff --git "a/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/llava/model/apply_delta.py" "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/llava/model/apply_delta.py" new file mode 100644 index 0000000000000000000000000000000000000000..c183ba19a4e91e9cb95155b542e7406ea5b287a0 --- /dev/null +++ "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/llava/model/apply_delta.py" @@ -0,0 +1,47 @@ +""" +Usage: +python3 -m fastchat.model.apply_delta --base ~/model_weights/llama-7b --target ~/model_weights/vicuna-7b --delta lmsys/vicuna-7b-delta +""" + +import argparse + +import torch +from tqdm import tqdm +from transformers import AutoTokenizer, AutoModelForCausalLM +from llava import LlavaLlamaForCausalLM + + +def apply_delta(base_model_path, target_model_path, delta_path): + print("Loading base model") + base = AutoModelForCausalLM.from_pretrained(base_model_path, torch_dtype=torch.float16, low_cpu_mem_usage=True) + + print("Loading delta") + delta = LlavaLlamaForCausalLM.from_pretrained(delta_path, torch_dtype=torch.float16, low_cpu_mem_usage=True) + delta_tokenizer = AutoTokenizer.from_pretrained(delta_path) + + print("Applying delta") + for name, param in tqdm(delta.state_dict().items(), desc="Applying delta"): + if name not in base.state_dict(): + assert name in ["model.mm_projector.weight", "model.mm_projector.bias"], f"{name} not in base model" + continue + if param.data.shape == base.state_dict()[name].shape: + param.data += base.state_dict()[name] + else: + assert name in ["model.embed_tokens.weight", "lm_head.weight"], f"{name} dimension mismatch: {param.data.shape} vs {base.state_dict()[name].shape}" + bparam = base.state_dict()[name] + param.data[: bparam.shape[0], : bparam.shape[1]] += bparam + + print("Saving target model") + delta.save_pretrained(target_model_path) + delta_tokenizer.save_pretrained(target_model_path) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--base-model-path", type=str, required=True) + parser.add_argument("--target-model-path", type=str, required=True) + parser.add_argument("--delta-path", type=str, required=True) + + args = parser.parse_args() + + apply_delta(args.base_model_path, args.target_model_path, args.delta_path) diff --git "a/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/llava/model/builder.py" "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/llava/model/builder.py" new file mode 100644 index 0000000000000000000000000000000000000000..704b960a6ff3d36c953f2f2b549e9367997928bf --- /dev/null +++ "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/llava/model/builder.py" @@ -0,0 +1,305 @@ +# Copyright 2023 Haotian Liu +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + + +import os +import warnings +import shutil + +from transformers import AutoTokenizer, AutoModelForCausalLM, AutoConfig, BitsAndBytesConfig +import torch +from llava.model import * +from llava.constants import DEFAULT_IMAGE_PATCH_TOKEN, DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN +from llava.utils import rank0_print + + +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): + kwargs["device_map"] = device_map + + if load_8bit: + kwargs["load_in_8bit"] = True + elif load_4bit: + kwargs["load_in_4bit"] = True + 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") + elif torch_dtype == "float16": + kwargs["torch_dtype"] = torch.float16 + elif torch_dtype == "bfloat16": + kwargs["torch_dtype"] = torch.bfloat16 + else: + import pdb;pdb.set_trace() + + if customized_config is not None: + kwargs["config"] = customized_config + + if "multimodal" in kwargs: + if kwargs["multimodal"] is True: + is_multimodal = True + kwargs.pop("multimodal") + else: + is_multimodal = False + + if "llava" in model_name.lower() or is_multimodal: + # Load LLaVA model + if "lora" in model_name.lower() and model_base is None: + warnings.warn( + "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." + ) + if "lora" in model_name.lower() and model_base is not None: + lora_cfg_pretrained = AutoConfig.from_pretrained(model_path) + tokenizer = AutoTokenizer.from_pretrained(model_base, use_fast=False) + rank0_print("Loading LLaVA from base model...") + if "mixtral" in model_name.lower(): + from llava.model.language_model.llava_mixtral import LlavaMixtralConfig + + lora_cfg_pretrained = LlavaMixtralConfig.from_pretrained(model_path) + tokenizer = AutoTokenizer.from_pretrained(model_base, use_fast=False) + model = LlavaMixtralForCausalLM.from_pretrained(model_base, low_cpu_mem_usage=True, config=lora_cfg_pretrained, attn_implementation=attn_implementation, **kwargs) + elif "mistral" in model_name.lower(): + from llava.model.language_model.llava_mistral import LlavaMistralConfig + + lora_cfg_pretrained = LlavaMistralConfig.from_pretrained(model_path) + tokenizer = AutoTokenizer.from_pretrained(model_base, use_fast=False) + model = LlavaMistralForCausalLM.from_pretrained(model_base, low_cpu_mem_usage=True, config=lora_cfg_pretrained, attn_implementation=attn_implementation, **kwargs) + elif "gemma" in model_name.lower(): + from llava.model.language_model.llava_gemma import LlavaGemmaConfig + + lora_cfg_pretrained = LlavaGemmaConfig.from_pretrained(model_path) + tokenizer = AutoTokenizer.from_pretrained(model_base, use_fast=False) + model = LlavaGemmaForCausalLM.from_pretrained(model_base, low_cpu_mem_usage=True, config=lora_cfg_pretrained, attn_implementation=attn_implementation, **kwargs) + else: + from llava.model.language_model.llava_llama import LlavaConfig + + lora_cfg_pretrained = LlavaConfig.from_pretrained(model_path) + tokenizer = AutoTokenizer.from_pretrained(model_base, use_fast=False) + model = LlavaLlamaForCausalLM.from_pretrained(model_base, low_cpu_mem_usage=True, config=lora_cfg_pretrained, attn_implementation=attn_implementation, **kwargs) + + token_num, tokem_dim = model.lm_head.out_features, model.lm_head.in_features + if model.lm_head.weight.shape[0] != token_num: + model.lm_head.weight = torch.nn.Parameter(torch.empty(token_num, tokem_dim, device=model.device, dtype=model.dtype)) + model.model.embed_tokens.weight = torch.nn.Parameter(torch.empty(token_num, tokem_dim, device=model.device, dtype=model.dtype)) + + rank0_print("Loading additional LLaVA weights...") + if os.path.exists(os.path.join(model_path, "non_lora_trainables.bin")): + non_lora_trainables = torch.load(os.path.join(model_path, "non_lora_trainables.bin"), map_location="cpu") + else: + # this is probably from HF Hub + from huggingface_hub import hf_hub_download + + def load_from_hf(repo_id, filename, subfolder=None): + cache_file = hf_hub_download(repo_id=repo_id, filename=filename, subfolder=subfolder) + return torch.load(cache_file, map_location="cpu") + + non_lora_trainables = load_from_hf(model_path, "non_lora_trainables.bin") + non_lora_trainables = {(k[11:] if k.startswith("base_model.") else k): v for k, v in non_lora_trainables.items()} + if any(k.startswith("model.model.") for k in non_lora_trainables): + non_lora_trainables = {(k[6:] if k.startswith("model.") else k): v for k, v in non_lora_trainables.items()} + model.load_state_dict(non_lora_trainables, strict=False) + + from peft import PeftModel + + rank0_print("Loading LoRA weights...") + model = PeftModel.from_pretrained(model, model_path) + rank0_print("Merging LoRA weights...") + model = model.merge_and_unload() + rank0_print("Model is loaded...") + elif model_base is not None: # this may be mm projector only, loading projector with preset language mdoel + rank0_print(f"Loading LLaVA from base model {model_base}...") + if "mixtral" in model_name.lower(): + tokenizer = AutoTokenizer.from_pretrained(model_base, use_fast=False) + cfg_pretrained = AutoConfig.from_pretrained(model_path) + model = LlavaMixtralForCausalLM.from_pretrained(model_base, low_cpu_mem_usage=True, config=cfg_pretrained, attn_implementation=attn_implementation, **kwargs) + elif "mistral" in model_name.lower() or "zephyr" in model_name.lower(): + tokenizer = AutoTokenizer.from_pretrained(model_base, use_fast=False) + cfg_pretrained = AutoConfig.from_pretrained(model_path) + model = LlavaMistralForCausalLM.from_pretrained(model_base, low_cpu_mem_usage=True, config=cfg_pretrained, attn_implementation=attn_implementation, **kwargs) + elif "gemma" in model_name.lower(): + tokenizer = AutoTokenizer.from_pretrained(model_base, use_fast=False) + cfg_pretrained = AutoConfig.from_pretrained(model_path) + model = LlavaGemmaForCausalLM.from_pretrained(model_base, low_cpu_mem_usage=True, config=cfg_pretrained, attn_implementation=attn_implementation, **kwargs) + elif ( + "wizardlm-2" in model_name.lower() + and "vicuna" in model_name.lower() + or "llama" in model_name.lower() + or "yi" in model_name.lower() + or "nous-hermes" in model_name.lower() + or "llava-v1.6-34b" in model_name.lower() + or "llava-v1.5" in model_name.lower() + ): + from llava.model.language_model.llava_llama import LlavaConfig + + tokenizer = AutoTokenizer.from_pretrained(model_path, use_fast=False) + if customized_config is None: + llava_cfg = LlavaConfig.from_pretrained(model_path) + if "v1.5" in model_name.lower(): + llava_cfg.delay_load = True # a workaround for correctly loading v1.5 models + else: + llava_cfg = customized_config + + tokenizer = AutoTokenizer.from_pretrained(model_base, use_fast=False) + llava_cfg = LlavaConfig.from_pretrained(model_path) + model = LlavaLlamaForCausalLM.from_pretrained(model_base, low_cpu_mem_usage=True, config=llava_cfg, **kwargs) + else: + raise ValueError(f"Model {model_name} not supported") + + mm_projector_weights = torch.load(os.path.join(model_path, "mm_projector.bin"), map_location="cpu") + mm_projector_weights = {k: v.to(torch.float16) for k, v in mm_projector_weights.items()} + model.load_state_dict(mm_projector_weights, strict=False) + else: + rank0_print(f"Loaded LLaVA model: {model_path}") + if "mixtral" in model_name.lower(): + from llava.model.language_model.llava_mixtral import LlavaMixtralConfig + + tokenizer = AutoTokenizer.from_pretrained(model_path, use_fast=False) + if customized_config is None: + llava_cfg = LlavaMixtralConfig.from_pretrained(model_path) + else: + llava_cfg = customized_config + + if overwrite_config is not None: + rank0_print(f"Overwriting config with {overwrite_config}") + for k, v in overwrite_config.items(): + setattr(llava_cfg, k, v) + + tokenizer = AutoTokenizer.from_pretrained(model_path) + model = LlavaMixtralForCausalLM.from_pretrained(model_path, low_cpu_mem_usage=True, attn_implementation=attn_implementation, config=llava_cfg, **kwargs) + + elif "mistral" in model_name.lower() or "zephyr" in model_name.lower(): + tokenizer = AutoTokenizer.from_pretrained(model_path) + model = LlavaMistralForCausalLM.from_pretrained(model_path, low_cpu_mem_usage=True, attn_implementation=attn_implementation, **kwargs) + elif ( + "wizardlm-2" in model_name.lower() + and "vicuna" in model_name.lower() + or "llama" in model_name.lower() + or "yi" in model_name.lower() + or "nous-hermes" in model_name.lower() + or "llava-v1.6-34b" in model_name.lower() + or "llava-v1.5" in model_name.lower() + ): + from llava.model.language_model.llava_llama import LlavaConfig + + tokenizer = AutoTokenizer.from_pretrained(model_path, use_fast=False) + if customized_config is None: + llava_cfg = LlavaConfig.from_pretrained(model_path) + if "v1.5" in model_name.lower(): + llava_cfg.delay_load = True # a workaround for correctly loading v1.5 models + else: + llava_cfg = customized_config + + if overwrite_config is not None: + rank0_print(f"Overwriting config with {overwrite_config}") + for k, v in overwrite_config.items(): + setattr(llava_cfg, k, v) + + model = LlavaLlamaForCausalLM.from_pretrained(model_path, low_cpu_mem_usage=True, attn_implementation=attn_implementation, config=llava_cfg, **kwargs) + + elif "qwen" in model_name.lower() or "quyen" in model_name.lower(): + tokenizer = AutoTokenizer.from_pretrained(model_path) + if "moe" in model_name.lower() or "A14B" in model_name.lower(): + from llava.model.language_model.llava_qwen_moe import LlavaQwenMoeConfig + if overwrite_config is not None: + llava_cfg = LlavaQwenMoeConfig.from_pretrained(model_path) + rank0_print(f"Overwriting config with {overwrite_config}") + for k, v in overwrite_config.items(): + setattr(llava_cfg, k, v) + model = LlavaQwenMoeForCausalLM.from_pretrained(model_path, low_cpu_mem_usage=True, attn_implementation=attn_implementation, config=llava_cfg, **kwargs) + else: + model = LlavaQwenMoeForCausalLM.from_pretrained(model_path, low_cpu_mem_usage=True, attn_implementation=attn_implementation, **kwargs) + + else: + from llava.model.language_model.llava_qwen import LlavaQwenConfig + if overwrite_config is not None: + llava_cfg = LlavaQwenConfig.from_pretrained(model_path) + rank0_print(f"Overwriting config with {overwrite_config}") + for k, v in overwrite_config.items(): + setattr(llava_cfg, k, v) + model = LlavaQwenForCausalLM.from_pretrained(model_path, low_cpu_mem_usage=True, attn_implementation=attn_implementation, config=llava_cfg, **kwargs) + else: + model = LlavaQwenForCausalLM.from_pretrained(model_path, low_cpu_mem_usage=True, attn_implementation=attn_implementation, **kwargs) + + elif "gemma" in model_name.lower(): + tokenizer = AutoTokenizer.from_pretrained(model_path, use_fast=False) + cfg_pretrained = AutoConfig.from_pretrained(model_path) + model = LlavaGemmaForCausalLM.from_pretrained(model_path, low_cpu_mem_usage=True, config=cfg_pretrained, attn_implementation=attn_implementation, **kwargs) + else: + try: + from llava.model.language_model.llava_llama import LlavaConfig + + tokenizer = AutoTokenizer.from_pretrained(model_path, use_fast=False) + if customized_config is None: + llava_cfg = LlavaConfig.from_pretrained(model_path) + if "v1.5" in model_path.lower(): + llava_cfg.delay_load = True # a workaround for correctly loading v1.5 models + else: + llava_cfg = customized_config + + if overwrite_config is not None: + rank0_print(f"Overwriting config with {overwrite_config}") + for k, v in overwrite_config.items(): + setattr(llava_cfg, k, v) + model = LlavaLlamaForCausalLM.from_pretrained(model_path, low_cpu_mem_usage=True, attn_implementation=attn_implementation, config=llava_cfg, **kwargs) + except: + raise ValueError(f"Model {model_name} not supported") + + else: + # Load language model + if model_base is not None: + # PEFT model + from peft import PeftModel + + tokenizer = AutoTokenizer.from_pretrained(model_base, use_fast=False) + model = AutoModelForCausalLM.from_pretrained(model_base, torch_dtype=torch.float16, low_cpu_mem_usage=True, device_map="auto") + print(f"Loading LoRA weights from {model_path}") + model = PeftModel.from_pretrained(model, model_path) + print(f"Merging weights") + model = model.merge_and_unload() + print("Convert to FP16...") + model.to(torch.float16) + else: + use_fast = False + if "mpt" in model_name.lower().replace("prompt", ""): + tokenizer = AutoTokenizer.from_pretrained(model_path, use_fast=True) + model = AutoModelForCausalLM.from_pretrained(model_path, low_cpu_mem_usage=True, trust_remote_code=True, **kwargs) + else: + tokenizer = AutoTokenizer.from_pretrained(model_path, use_fast=False) + model = AutoModelForCausalLM.from_pretrained(model_path, low_cpu_mem_usage=True, **kwargs) + + rank0_print(f"Model Class: {model.__class__.__name__}") + image_processor = None + + if "llava" in model_name.lower() or is_multimodal: + mm_use_im_start_end = getattr(model.config, "mm_use_im_start_end", False) + mm_use_im_patch_token = getattr(model.config, "mm_use_im_patch_token", True) + if mm_use_im_patch_token: + tokenizer.add_tokens([DEFAULT_IMAGE_PATCH_TOKEN], special_tokens=True) + if mm_use_im_start_end: + tokenizer.add_tokens([DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN], special_tokens=True) + model.resize_token_embeddings(len(tokenizer)) + + vision_tower = model.get_vision_tower() + if not vision_tower.is_loaded: + vision_tower.load_model(device_map=device_map) + if device_map != "auto": + vision_tower.to(device="cuda", dtype=torch.float16) + image_processor = vision_tower.image_processor + + if hasattr(model.config, "max_sequence_length"): + context_len = model.config.max_sequence_length + elif hasattr(model.config, "max_position_embeddings"): + context_len = model.config.max_position_embeddings + elif hasattr(model.config, "tokenizer_model_max_length"): + context_len = model.config.tokenizer_model_max_length + else: + context_len = 2048 + + return tokenizer, model, image_processor, context_len diff --git "a/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/llava/model/consolidate.py" "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/llava/model/consolidate.py" new file mode 100644 index 0000000000000000000000000000000000000000..f02e575f6b8e4388e1758776cadd62309147a1ad --- /dev/null +++ "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/llava/model/consolidate.py" @@ -0,0 +1,30 @@ +""" +Usage: +python3 -m llava.model.consolidate --src ~/model_weights/llava-7b --dst ~/model_weights/llava-7b_consolidate +""" + +import argparse + +import torch +from transformers import AutoTokenizer, AutoModelForCausalLM +from llava.model import * +from llava.model.utils import auto_upgrade + + +def consolidate_ckpt(src_path, dst_path): + print("Loading model") + auto_upgrade(src_path) + src_model = AutoModelForCausalLM.from_pretrained(src_path, torch_dtype=torch.float16, low_cpu_mem_usage=True) + src_tokenizer = AutoTokenizer.from_pretrained(src_path, use_fast=False) + src_model.save_pretrained(dst_path) + src_tokenizer.save_pretrained(dst_path) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--src", type=str, required=True) + parser.add_argument("--dst", type=str, required=True) + + args = parser.parse_args() + + consolidate_ckpt(args.src, args.dst) diff --git "a/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/llava/model/llava_arch.py" "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/llava/model/llava_arch.py" new file mode 100644 index 0000000000000000000000000000000000000000..ea98ae8501b0f52d8a1b61323bfc03f6bc3c2541 --- /dev/null +++ "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/llava/model/llava_arch.py" @@ -0,0 +1,597 @@ +# Copyright 2023 Haotian Liu +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + + +from abc import ABC, abstractmethod + +import math +import re +import time +import torch +import torch.nn as nn +from .multimodal_encoder.builder import build_vision_tower +from .multimodal_resampler.builder import build_vision_resampler +from .multimodal_projector.builder import build_vision_projector + +from llava.constants import IGNORE_INDEX, IMAGE_TOKEN_INDEX, DEFAULT_IMAGE_PATCH_TOKEN, DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN + +from llava.mm_utils import get_anyres_image_grid_shape +from llava.utils import rank0_print, rank_print +import random + + +class LlavaMetaModel: + + def __init__(self, config): + super(LlavaMetaModel, self).__init__(config) + + if hasattr(config, "mm_vision_tower"): + delay_load = getattr(config, "delay_load", False) + self.vision_tower = build_vision_tower(config, delay_load=delay_load) + self.vision_resampler = build_vision_resampler(config, vision_tower=self.vision_tower) + self.mm_projector = build_vision_projector(config, vision_cfg=self.vision_tower.config) + + if "unpad" in getattr(config, "mm_patch_merge_type", ""): + self.image_newline = nn.Parameter(torch.empty(config.hidden_size, dtype=self.dtype)) + + def get_vision_tower(self): + vision_tower = getattr(self, "vision_tower", None) + if type(vision_tower) is list: + vision_tower = vision_tower[0] + return vision_tower + + def initialize_vision_modules(self, model_args, fsdp=None): + vision_tower = model_args.vision_tower + mm_vision_select_layer = model_args.mm_vision_select_layer + mm_vision_select_feature = model_args.mm_vision_select_feature + pretrain_mm_mlp_adapter = model_args.pretrain_mm_mlp_adapter + mm_patch_merge_type = model_args.mm_patch_merge_type + + self.config.mm_vision_tower = vision_tower + self.config.vision_tower_pretrained = getattr(model_args, "vision_tower_pretrained", "") + + if self.get_vision_tower() is None: + vision_tower = build_vision_tower(model_args) + vision_resampler = build_vision_resampler(model_args, vision_tower=vision_tower) + for k, v in vision_resampler.config.items(): + setattr(self.config, k, v) + + if fsdp is not None and len(fsdp) > 0: + self.vision_tower = [vision_tower] + self.vision_resampler = [vision_resampler] + else: + self.vision_tower = vision_tower + self.vision_resampler = vision_resampler + else: + if fsdp is not None and len(fsdp) > 0: + vision_resampler = self.vision_resampler[0] + vision_tower = self.vision_tower[0] + else: + vision_resampler = self.vision_resampler + vision_tower = self.vision_tower + vision_tower.load_model() + + # In case it is frozen by LoRA + for p in self.vision_resampler.parameters(): + p.requires_grad = True + + self.config.use_mm_proj = True + self.config.mm_projector_type = getattr(model_args, "mm_projector_type", "linear") + self.config.mm_hidden_size = getattr(vision_resampler, "hidden_size", vision_tower.hidden_size) + self.config.mm_vision_select_layer = mm_vision_select_layer + self.config.mm_vision_select_feature = mm_vision_select_feature + self.config.mm_patch_merge_type = mm_patch_merge_type + + + if not hasattr(self.config, 'add_faster_video'): + if model_args.add_faster_video: + embed_std = 1 / torch.sqrt(torch.tensor(self.config.hidden_size, dtype=self.dtype)) + self.faster_token = nn.Parameter( + torch.randn(self.config.hidden_size, dtype=self.dtype) * embed_std + ) + + if getattr(self, "mm_projector", None) is None: + self.mm_projector = build_vision_projector(self.config, vision_cfg=vision_tower.config) + + if "unpad" in mm_patch_merge_type: + embed_std = 1 / torch.sqrt(torch.tensor(self.config.hidden_size, dtype=self.dtype)) + self.image_newline = nn.Parameter(torch.randn(self.config.hidden_size, dtype=self.dtype) * embed_std) + else: + # In case it is frozen by LoRA + for p in self.mm_projector.parameters(): + p.requires_grad = True + + if pretrain_mm_mlp_adapter is not None: + mm_projector_weights = torch.load(pretrain_mm_mlp_adapter, map_location="cpu") + + def get_w(weights, keyword): + return {k.split(keyword + ".")[1]: v for k, v in weights.items() if keyword in k} + + incompatible_keys = self.mm_projector.load_state_dict(get_w(mm_projector_weights, "mm_projector")) + rank0_print(f"Loaded mm projector weights from {pretrain_mm_mlp_adapter}. Incompatible keys: {incompatible_keys}") + incompatible_keys = self.vision_resampler.load_state_dict(get_w(mm_projector_weights, "vision_resampler"), strict=False) + rank0_print(f"Loaded vision resampler weights from {pretrain_mm_mlp_adapter}. Incompatible keys: {incompatible_keys}") + + +def unpad_image(tensor, original_size): + """ + Unpads a PyTorch tensor of a padded and resized image. + + Args: + tensor (torch.Tensor): The image tensor, assumed to be in CxHxW format. + original_size (tuple): The original size of the image (height, width). + + Returns: + torch.Tensor: The unpadded image tensor. + """ + original_width, original_height = original_size + current_height, current_width = tensor.shape[1:] + + # Compute aspect ratios + original_aspect_ratio = original_width / original_height + current_aspect_ratio = current_width / current_height + + # Determine padding size and direction + if original_aspect_ratio > current_aspect_ratio: + # Padding was added to the height + scale_factor = current_width / original_width + new_height = int(original_height * scale_factor) + padding = (current_height - new_height) // 2 + unpadded_tensor = tensor[:, padding : current_height - padding, :] + else: + # Padding was added to the width + scale_factor = current_height / original_height + new_width = int(original_width * scale_factor) + padding = (current_width - new_width) // 2 + unpadded_tensor = tensor[:, :, padding : current_width - padding] + + return unpadded_tensor + + +class LlavaMetaForCausalLM(ABC): + + @abstractmethod + def get_model(self): + pass + + def get_vision_tower(self): + return self.get_model().get_vision_tower() + + def get_2dPool(self, image_feature, stride=2): + height = width = self.get_vision_tower().num_patches_per_side + num_frames, num_tokens, num_dim = image_feature.shape + image_feature = image_feature.view(num_frames, height, width, -1) + image_feature = image_feature.permute(0, 3, 1, 2).contiguous() + # image_feature = nn.functional.max_pool2d(image_feature, self.config.mm_spatial_pool_stride) + if self.config.mm_spatial_pool_mode == "average": + image_feature = nn.functional.avg_pool2d(image_feature, stride) + elif self.config.mm_spatial_pool_mode == "max": + image_feature = nn.functional.max_pool2d(image_feature, stride) + elif self.config.mm_spatial_pool_mode == "bilinear": + height, width = image_feature.shape[2:] + scaled_shape = [math.ceil(height / stride), math.ceil(width / stride)] + image_feature = nn.functional.interpolate(image_feature, size=scaled_shape, mode='bilinear') + + else: + raise ValueError(f"Unexpected mm_spatial_pool_mode: {self.config.mm_spatial_pool_mode}") + image_feature = image_feature.permute(0, 2, 3, 1) + image_feature = image_feature.view(num_frames, -1, num_dim) + return image_feature + + def encode_images(self, images): + image_features = self.get_model().get_vision_tower()(images) + # image_features = self.get_model().vision_resampler(image_features, images=images) + image_features = self.get_model().mm_projector(image_features) + return image_features + + def encode_multimodals(self, videos_or_images, video_idx_in_batch, split_sizes=None): + videos_or_images_features = self.get_model().get_vision_tower()(videos_or_images) + per_videos_or_images_features = torch.split(videos_or_images_features, split_sizes, dim=0) # tuple, (dim_1, 576, 4096) + all_videos_or_images_features = [] + all_faster_video_features = [] + cur_mm_spatial_pool_stride = self.config.mm_spatial_pool_stride + + for idx, feat in enumerate(per_videos_or_images_features): + + feat = self.get_model().mm_projector(feat) + faster_video_feature = 0 + slower_img_feat = 0 + if idx in video_idx_in_batch and cur_mm_spatial_pool_stride > 1: + slower_img_feat = self.get_2dPool(feat,cur_mm_spatial_pool_stride) + if self.config.add_faster_video: + cur_mm_spatial_pool_stride = cur_mm_spatial_pool_stride * 2 + faster_video_feature = self.get_2dPool(feat,cur_mm_spatial_pool_stride) + if slower_img_feat is not 0: + all_videos_or_images_features.append(slower_img_feat) + else: + all_videos_or_images_features.append(feat) + all_faster_video_features.append(faster_video_feature) + return all_videos_or_images_features,all_faster_video_features + + def add_token_per_grid(self, image_feature): + resize_h = int(math.sqrt(image_feature.shape[1])) + num_frames = image_feature.shape[0] + feature_dim = image_feature.shape[-1] + + image_feature = image_feature.view(num_frames, 1, resize_h, resize_h, -1) + image_feature = image_feature.permute(4, 0, 2, 1, 3).contiguous() + image_feature = image_feature.flatten(1, 2).flatten(2, 3) + image_feature = torch.cat((image_feature, self.model.image_newline[:, None, None].expand(*image_feature.shape[:-1], 1).to(image_feature.device)), dim=-1) + if getattr(self.config, "add_faster_video", False): + # import pdb; pdb.set_trace() + # (3584, 832, 14) -> (3584, 64, 13, 14) + image_feature = image_feature.view(feature_dim, num_frames,resize_h, -1) + # (3584, 64, 13, 14) -> (64, 13, 14, 3584) + image_feature = image_feature.permute(1, 2, 3, 0).contiguous() + # (64, 13, 14, 3584) -> (64, 13*14, 3584) + image_feature = image_feature.flatten(1, 2) + # import pdb; pdb.set_trace() + return image_feature + # import pdb; pdb.set_trace() + image_feature = image_feature.flatten(1, 2).transpose(0, 1) + return image_feature + + def add_token_per_frame(self, image_feature): + image_feature = image_feature.permute(2, 0, 1).contiguous() + image_feature = torch.cat((image_feature, self.model.image_newline[:, None, None].expand(*image_feature.shape[:-1], 1).to(image_feature.device)), dim=-1) + image_feature = image_feature.permute(1, 2, 0).contiguous() + return image_feature + + def prepare_inputs_labels_for_multimodal(self, input_ids, position_ids, attention_mask, past_key_values, labels, images, modalities=["image"], image_sizes=None): + vision_tower = self.get_vision_tower() + # rank_print(modalities) + if vision_tower is None or images is None or input_ids.shape[1] == 1: + return input_ids, position_ids, attention_mask, past_key_values, None, labels + + if isinstance(modalities, str): + modalities = [modalities] + + # import pdb; pdb.set_trace() + if type(images) is list or images.ndim == 5: + if type(images) is list: + images = [x.unsqueeze(0) if x.ndim == 3 else x for x in images] + + video_idx_in_batch = [] + for _ in range(len(modalities)): + if modalities[_] == "video": + video_idx_in_batch.append(_) + + images_list = [] + for image in images: + if image.ndim == 4: + images_list.append(image) + else: + images_list.append(image.unsqueeze(0)) + + concat_images = torch.cat([image for image in images_list], dim=0) + split_sizes = [image.shape[0] for image in images_list] + encoded_image_features = self.encode_images(concat_images) + # image_features,all_faster_video_features = self.encode_multimodals(concat_images, video_idx_in_batch, split_sizes) + + # This is a list, each element is [num_images, patch * patch, dim] + # rank_print(f"Concat images : {concat_images.shape}") + encoded_image_features = torch.split(encoded_image_features, split_sizes) + image_features = [] + for idx, image_feat in enumerate(encoded_image_features): + if idx in video_idx_in_batch: + image_features.append(self.get_2dPool(image_feat)) + else: + image_features.append(image_feat) + # image_features = self.encode_multimodals(concat_images, video_idx_in_batch, split_sizes) + # rank_print(f"Encoded image feats : {[x.shape for x in image_features]}") + # image_features = torch.split(image_features, split_sizes, dim=0) + mm_patch_merge_type = getattr(self.config, "mm_patch_merge_type", "flat") + image_aspect_ratio = getattr(self.config, "image_aspect_ratio", "square") + mm_newline_position = getattr(self.config, "mm_newline_position", "one_token") + + if mm_patch_merge_type == "flat": + image_features = [x.flatten(0, 1) for x in image_features] + + elif mm_patch_merge_type.startswith("spatial"): + new_image_features = [] + for image_idx, image_feature in enumerate(image_features): + # FIXME: now assume the image is square, and split to 2x2 patches + # num_patches = h * w, where h = w = sqrt(num_patches) + # currently image_feature is a tensor of shape (4, num_patches, hidden_size) + # we want to first unflatten it to (2, 2, h, w, hidden_size) + # rank0_print("At least we are reaching here") + # import pdb; pdb.set_trace() + if image_idx in video_idx_in_batch: # video operations + # rank0_print("Video") + if mm_newline_position == "grid": + # Grid-wise + image_feature = self.add_token_per_grid(image_feature) + if getattr(self.config, "add_faster_video", False): + faster_video_feature = self.add_token_per_grid(all_faster_video_features[image_idx]) + # Add a token for each frame + concat_slow_fater_token = [] + # import pdb; pdb.set_trace() + for _ in range(image_feature.shape[0]): + if _ % self.config.faster_token_stride == 0: + concat_slow_fater_token.append(torch.cat((image_feature[_], self.model.faster_token[None].to(image_feature.device)), dim=0)) + else: + concat_slow_fater_token.append(torch.cat((faster_video_feature[_], self.model.faster_token[None].to(image_feature.device)), dim=0)) + # import pdb; pdb.set_trace() + image_feature = torch.cat(concat_slow_fater_token) + + # print("!!!!!!!!!!!!") + + new_image_features.append(image_feature) + elif mm_newline_position == "frame": + # Frame-wise + image_feature = self.add_token_per_frame(image_feature) + + new_image_features.append(image_feature.flatten(0, 1)) + + elif mm_newline_position == "one_token": + # one-token + image_feature = image_feature.flatten(0, 1) + if 'unpad' in mm_patch_merge_type: + image_feature = torch.cat(( + image_feature, + self.model.image_newline[None].to(image_feature.device) + ), dim=0) + new_image_features.append(image_feature) + elif mm_newline_position == "no_token": + new_image_features.append(image_feature.flatten(0, 1)) + else: + raise ValueError(f"Unexpected mm_newline_position: {mm_newline_position}") + elif image_feature.shape[0] > 1: # multi patches and multi images operations + # rank0_print("Single-images") + base_image_feature = image_feature[0] + image_feature = image_feature[1:] + height = width = self.get_vision_tower().num_patches_per_side + assert height * width == base_image_feature.shape[0] + + if "anyres_max" in image_aspect_ratio: + matched_anyres_max_num_patches = re.match(r"anyres_max_(\d+)", image_aspect_ratio) + if matched_anyres_max_num_patches: + max_num_patches = int(matched_anyres_max_num_patches.group(1)) + + if image_aspect_ratio == "anyres" or "anyres_max" in image_aspect_ratio: + if hasattr(self.get_vision_tower(), "image_size"): + vision_tower_image_size = self.get_vision_tower().image_size + else: + raise ValueError("vision_tower_image_size is not found in the vision tower.") + try: + num_patch_width, num_patch_height = get_anyres_image_grid_shape(image_sizes[image_idx], self.config.image_grid_pinpoints, vision_tower_image_size) + except Exception as e: + rank0_print(f"Error: {e}") + num_patch_width, num_patch_height = 2, 2 + image_feature = image_feature.view(num_patch_height, num_patch_width, height, width, -1) + else: + image_feature = image_feature.view(2, 2, height, width, -1) + + if "maxpool2x2" in mm_patch_merge_type: + image_feature = image_feature.permute(4, 0, 2, 1, 3).contiguous() + image_feature = image_feature.flatten(1, 2).flatten(2, 3) + image_feature = nn.functional.max_pool2d(image_feature, 2) + image_feature = image_feature.flatten(1, 2).transpose(0, 1) + elif "unpad" in mm_patch_merge_type and "anyres_max" in image_aspect_ratio and matched_anyres_max_num_patches: + unit = image_feature.shape[2] + image_feature = image_feature.permute(4, 0, 2, 1, 3).contiguous() + image_feature = image_feature.flatten(1, 2).flatten(2, 3) + image_feature = unpad_image(image_feature, image_sizes[image_idx]) + c, h, w = image_feature.shape + times = math.sqrt(h * w / (max_num_patches * unit**2)) + if times > 1.1: + image_feature = image_feature[None] + image_feature = nn.functional.interpolate(image_feature, [int(h // times), int(w // times)], mode="bilinear")[0] + image_feature = torch.cat((image_feature, self.model.image_newline[:, None, None].expand(*image_feature.shape[:-1], 1).to(image_feature.device)), dim=-1) + image_feature = image_feature.flatten(1, 2).transpose(0, 1) + elif "unpad" in mm_patch_merge_type: + image_feature = image_feature.permute(4, 0, 2, 1, 3).contiguous() + image_feature = image_feature.flatten(1, 2).flatten(2, 3) + image_feature = unpad_image(image_feature, image_sizes[image_idx]) + image_feature = torch.cat((image_feature, self.model.image_newline[:, None, None].expand(*image_feature.shape[:-1], 1).to(image_feature.device)), dim=-1) + image_feature = image_feature.flatten(1, 2).transpose(0, 1) + else: + image_feature = image_feature.permute(0, 2, 1, 3, 4).contiguous() + image_feature = image_feature.flatten(0, 3) + if "nobase" in mm_patch_merge_type: + pass + else: + image_feature = torch.cat((base_image_feature, image_feature), dim=0) + new_image_features.append(image_feature) + else: # single image operations + image_feature = image_feature[0] + if "unpad" in mm_patch_merge_type: + image_feature = torch.cat((image_feature, self.model.image_newline[None]), dim=0) + + new_image_features.append(image_feature) + image_features = new_image_features + else: + raise ValueError(f"Unexpected mm_patch_merge_type: {self.config.mm_patch_merge_type}") + else: + image_features = self.encode_images(images) + + # TODO: image start / end is not implemented here to support pretraining. + if getattr(self.config, "tune_mm_mlp_adapter", False) and getattr(self.config, "mm_use_im_start_end", False): + raise NotImplementedError + # rank_print(f"Total images : {len(image_features)}") + + # Let's just add dummy tensors if they do not exist, + # it is a headache to deal with None all the time. + # But it is not ideal, and if you have a better idea, + # please open an issue / submit a PR, thanks. + _labels = labels + _position_ids = position_ids + _attention_mask = attention_mask + if attention_mask is None: + attention_mask = torch.ones_like(input_ids, dtype=torch.bool) + else: + attention_mask = attention_mask.bool() + if position_ids is None: + position_ids = torch.arange(0, input_ids.shape[1], dtype=torch.long, device=input_ids.device) + if labels is None: + labels = torch.full_like(input_ids, IGNORE_INDEX) + + # remove the padding using attention_mask -- FIXME + _input_ids = input_ids + input_ids = [cur_input_ids[cur_attention_mask] for cur_input_ids, cur_attention_mask in zip(input_ids, attention_mask)] + labels = [cur_labels[cur_attention_mask] for cur_labels, cur_attention_mask in zip(labels, attention_mask)] + + new_input_embeds = [] + new_labels = [] + cur_image_idx = 0 + # rank_print("Inserting Images embedding") + for batch_idx, cur_input_ids in enumerate(input_ids): + num_images = (cur_input_ids == IMAGE_TOKEN_INDEX).sum() + # rank0_print(num_images) + if num_images == 0: + cur_image_features = image_features[cur_image_idx] + cur_input_embeds_1 = self.get_model().embed_tokens(cur_input_ids) + cur_input_embeds = torch.cat([cur_input_embeds_1, cur_image_features[0:0]], dim=0) + new_input_embeds.append(cur_input_embeds) + new_labels.append(labels[batch_idx]) + cur_image_idx += 1 + continue + + image_token_indices = [-1] + torch.where(cur_input_ids == IMAGE_TOKEN_INDEX)[0].tolist() + [cur_input_ids.shape[0]] + cur_input_ids_noim = [] + cur_labels = labels[batch_idx] + cur_labels_noim = [] + for i in range(len(image_token_indices) - 1): + cur_input_ids_noim.append(cur_input_ids[image_token_indices[i] + 1 : image_token_indices[i + 1]]) + cur_labels_noim.append(cur_labels[image_token_indices[i] + 1 : image_token_indices[i + 1]]) + split_sizes = [x.shape[0] for x in cur_labels_noim] + cur_input_embeds = self.get_model().embed_tokens(torch.cat(cur_input_ids_noim)) + cur_input_embeds_no_im = torch.split(cur_input_embeds, split_sizes, dim=0) + cur_new_input_embeds = [] + cur_new_labels = [] + + for i in range(num_images + 1): + cur_new_input_embeds.append(cur_input_embeds_no_im[i]) + cur_new_labels.append(cur_labels_noim[i]) + if i < num_images: + try: + cur_image_features = image_features[cur_image_idx] + except IndexError: + cur_image_features = image_features[cur_image_idx - 1] + cur_image_idx += 1 + cur_new_input_embeds.append(cur_image_features) + cur_new_labels.append(torch.full((cur_image_features.shape[0],), IGNORE_INDEX, device=cur_labels.device, dtype=cur_labels.dtype)) + + cur_new_input_embeds = [x.to(self.device) for x in cur_new_input_embeds] + + # import pdb; pdb.set_trace() + cur_new_input_embeds = torch.cat(cur_new_input_embeds) + cur_new_labels = torch.cat(cur_new_labels) + + new_input_embeds.append(cur_new_input_embeds) + new_labels.append(cur_new_labels) + + # Truncate sequences to max length as image embeddings can make the sequence longer + tokenizer_model_max_length = getattr(self.config, "tokenizer_model_max_length", None) + # rank_print("Finishing Inserting") + + new_input_embeds = [x[:tokenizer_model_max_length] for x, modality in zip(new_input_embeds, modalities)] + new_labels = [x[:tokenizer_model_max_length] for x, modality in zip(new_labels, modalities)] + # TODO: Hard code for control loss spike + # if tokenizer_model_max_length is not None: + # new_input_embeds = [x[:4096] if modality != "video" else x[:tokenizer_model_max_length] for x, modality in zip(new_input_embeds, modalities)] + # new_labels = [x[:4096] if modality != "video" else x[:tokenizer_model_max_length] for x, modality in zip(new_labels, modalities)] + + # Combine them + max_len = max(x.shape[0] for x in new_input_embeds) + batch_size = len(new_input_embeds) + + new_input_embeds_padded = [] + new_labels_padded = torch.full((batch_size, max_len), IGNORE_INDEX, dtype=new_labels[0].dtype, device=new_labels[0].device) + attention_mask = torch.zeros((batch_size, max_len), dtype=attention_mask.dtype, device=attention_mask.device) + position_ids = torch.zeros((batch_size, max_len), dtype=position_ids.dtype, device=position_ids.device) + # rank0_print("Prepare pos id") + + for i, (cur_new_embed, cur_new_labels) in enumerate(zip(new_input_embeds, new_labels)): + cur_len = cur_new_embed.shape[0] + if getattr(self.config, "tokenizer_padding_side", "right") == "left": + 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)) + if cur_len > 0: + new_labels_padded[i, -cur_len:] = cur_new_labels + attention_mask[i, -cur_len:] = True + position_ids[i, -cur_len:] = torch.arange(0, cur_len, dtype=position_ids.dtype, device=position_ids.device) + else: + 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)) + if cur_len > 0: + new_labels_padded[i, :cur_len] = cur_new_labels + attention_mask[i, :cur_len] = True + position_ids[i, :cur_len] = torch.arange(0, cur_len, dtype=position_ids.dtype, device=position_ids.device) + + new_input_embeds = torch.stack(new_input_embeds_padded, dim=0) + # rank0_print("tokenizer padding") + + if _labels is None: + new_labels = None + else: + new_labels = new_labels_padded + + if _attention_mask is None: + attention_mask = None + else: + attention_mask = attention_mask.to(dtype=_attention_mask.dtype) + + if _position_ids is None: + position_ids = None + if getattr(self.config, "use_pos_skipping", False) and self.training: + position_ids = torch.arange(new_input_embeds.size(1), device=new_input_embeds.device).unsqueeze(0).to(new_input_embeds.device) + split_position = random.randint(0, new_input_embeds.size(1)) + left_add = random.randint(0, self.config.pos_skipping_range) + right_add = random.randint(left_add, self.config.pos_skipping_range) + position_ids[:, :split_position] += left_add + position_ids[:, split_position:] += right_add + # import pdb; pdb.set_trace() + # rank0_print("Finish preparing") + return None, position_ids, attention_mask, past_key_values, new_input_embeds, new_labels + + def initialize_vision_tokenizer(self, model_args, tokenizer): + if model_args.mm_use_im_patch_token: + tokenizer.add_tokens([DEFAULT_IMAGE_PATCH_TOKEN], special_tokens=True) + self.resize_token_embeddings(len(tokenizer)) + + if model_args.mm_use_im_start_end: + num_new_tokens = tokenizer.add_tokens([DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN], special_tokens=True) + self.resize_token_embeddings(len(tokenizer)) + + if num_new_tokens > 0: + input_embeddings = self.get_input_embeddings().weight.data + output_embeddings = self.get_output_embeddings().weight.data + + input_embeddings_avg = input_embeddings[:-num_new_tokens].mean(dim=0, keepdim=True) + output_embeddings_avg = output_embeddings[:-num_new_tokens].mean(dim=0, keepdim=True) + + input_embeddings[-num_new_tokens:] = input_embeddings_avg + output_embeddings[-num_new_tokens:] = output_embeddings_avg + + if model_args.tune_mm_mlp_adapter: + for p in self.get_input_embeddings().parameters(): + p.requires_grad = True + for p in self.get_output_embeddings().parameters(): + p.requires_grad = False + + if model_args.pretrain_mm_mlp_adapter: + mm_projector_weights = torch.load(model_args.pretrain_mm_mlp_adapter, map_location="cpu") + embed_tokens_weight = mm_projector_weights["model.embed_tokens.weight"] + assert num_new_tokens == 2 + if input_embeddings.shape == embed_tokens_weight.shape: + input_embeddings[-num_new_tokens:] = embed_tokens_weight[-num_new_tokens:] + elif embed_tokens_weight.shape[0] == num_new_tokens: + input_embeddings[-num_new_tokens:] = embed_tokens_weight + else: + raise ValueError(f"Unexpected embed_tokens_weight shape. Pretrained: {embed_tokens_weight.shape}. Current: {input_embeddings.shape}. Numer of new tokens: {num_new_tokens}.") + elif model_args.mm_use_im_patch_token: + if model_args.tune_mm_mlp_adapter: + for p in self.get_input_embeddings().parameters(): + p.requires_grad = False + for p in self.get_output_embeddings().parameters(): + p.requires_grad = False diff --git "a/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/llava/train/llama_flash_attn_monkey_patch.py" "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/llava/train/llama_flash_attn_monkey_patch.py" new file mode 100644 index 0000000000000000000000000000000000000000..c88fe34266d5467cf49ba0ad4fbc5f5eeac5c029 --- /dev/null +++ "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/llava/train/llama_flash_attn_monkey_patch.py" @@ -0,0 +1,87 @@ +from typing import Optional, Tuple +import warnings + +import torch + +import transformers +from transformers.models.llama.modeling_llama import apply_rotary_pos_emb, repeat_kv + +try: + from flash_attn.flash_attn_interface import flash_attn_unpadded_qkvpacked_func +except ImportError: + from flash_attn.flash_attn_interface import flash_attn_varlen_qkvpacked_func as flash_attn_unpadded_qkvpacked_func +from flash_attn.bert_padding import unpad_input, pad_input + + +def forward( + self, + hidden_states: torch.Tensor, + attention_mask: Optional[torch.Tensor] = None, + position_ids: Optional[torch.Tensor] = None, + past_key_value: Optional[Tuple[torch.Tensor]] = None, + output_attentions: bool = False, + use_cache: bool = False, + padding_mask: Optional[torch.Tensor] = None, +) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]: + if output_attentions: + warnings.warn("Output attentions is not supported for patched `LlamaAttention`, returning `None` instead.") + + bsz, q_len, _ = hidden_states.size() + + query_states = self.q_proj(hidden_states).view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2) + key_states = self.k_proj(hidden_states).view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2) + 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) + + kv_seq_len = key_states.shape[-2] + if past_key_value is not None: + kv_seq_len += past_key_value[0].shape[-2] + + cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len) + query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids) + + if past_key_value is not None: + # reuse k, v + key_states = torch.cat([past_key_value[0], key_states], dim=2) + value_states = torch.cat([past_key_value[1], value_states], dim=2) + + past_key_value = (key_states, value_states) if use_cache else None + + # repeat k/v heads if n_kv_heads < n_heads + key_states = repeat_kv(key_states, self.num_key_value_groups) + value_states = repeat_kv(value_states, self.num_key_value_groups) + + # Transform the data into the format required by flash attention + qkv = torch.stack([query_states, key_states, value_states], dim=2) + qkv = qkv.transpose(1, 3) # shape: [b, s, 3, num_heads, head_dim] + key_padding_mask = attention_mask + + if key_padding_mask is None: + qkv = qkv.reshape(-1, 3, self.num_heads, self.head_dim) + cu_q_lens = torch.arange(0, (bsz + 1) * q_len, step=q_len, dtype=torch.int32, device=qkv.device) + max_s = q_len + output = flash_attn_unpadded_qkvpacked_func(qkv, cu_q_lens, max_s, 0.0, softmax_scale=None, causal=True) + output = output.view(bsz, q_len, -1) + else: + qkv = qkv.reshape(bsz, q_len, -1) + qkv, indices, cu_q_lens, max_s = unpad_input(qkv, key_padding_mask) + qkv = qkv.view(-1, 3, self.num_heads, self.head_dim) + output_unpad = flash_attn_unpadded_qkvpacked_func(qkv, cu_q_lens, max_s, 0.0, softmax_scale=None, causal=True) + output_unpad = output_unpad.reshape(-1, self.num_heads * self.head_dim) + output = pad_input(output_unpad, indices, bsz, q_len) + + return self.o_proj(output), None, past_key_value + + +# Disable the transformation of the attention mask in LlamaModel as the flash attention +# requires the attention mask to be the same as the key_padding_mask +def _prepare_decoder_attention_mask(self, attention_mask, input_shape, inputs_embeds, past_key_values_length): + # [bsz, seq_len] + return attention_mask + + +def replace_llama_attn_with_flash_attn(): + cuda_major, cuda_minor = torch.cuda.get_device_capability() + if cuda_major < 8: + 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") + transformers.models.llama.modeling_llama.LlamaModel._prepare_decoder_attention_mask = _prepare_decoder_attention_mask + transformers.models.llama.modeling_llama.LlamaAttention.forward = forward diff --git "a/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/llava/train/llava_trainer.py" "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/llava/train/llava_trainer.py" new file mode 100644 index 0000000000000000000000000000000000000000..35e06cf4be6dec0dbe0cd38a24a35a6442876f0c --- /dev/null +++ "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/llava/train/llava_trainer.py" @@ -0,0 +1,1305 @@ +import os +import torch +import torch.nn as nn +import datetime + +from accelerate import Accelerator +from accelerate.utils import InitProcessGroupKwargs, GradientAccumulationPlugin +from torch.utils.data import Dataset, Sampler, DataLoader + +from trl.trainer import DPOTrainer +from trl.trainer.utils import DPODataCollatorWithPadding + +from transformers import Trainer +from transformers.trainer import is_sagemaker_mp_enabled, get_parameter_names, has_length, ALL_LAYERNORM_LAYERS, logger, is_accelerate_available, is_datasets_available, GradientAccumulationPlugin +from transformers.trainer_utils import seed_worker +from transformers.trainer_pt_utils import get_length_grouped_indices as get_length_grouped_indices_hf +from transformers.trainer_pt_utils import AcceleratorConfig +from typing import List, Optional +from datetime import timedelta + +if is_accelerate_available(): + from accelerate import Accelerator, skip_first_batches, InitProcessGroupKwargs + +if is_datasets_available(): + import datasets + +from llava.utils import rank0_print + + +def maybe_zero_3(param, ignore_status=False, name=None): + from deepspeed import zero + from deepspeed.runtime.zero.partition_parameters import ZeroParamStatus + + if hasattr(param, "ds_id"): + if param.ds_status == ZeroParamStatus.NOT_AVAILABLE: + if not ignore_status: + print(name, "no ignore status") + with zero.GatheredParameters([param]): + param = param.data.detach().cpu().clone() + else: + param = param.detach().cpu().clone() + return param + + +def get_mm_adapter_state_maybe_zero_3(named_params, keys_to_match): + to_return = {k: t for k, t in named_params if any(key_match in k for key_match in keys_to_match)} + to_return = {k: maybe_zero_3(v, ignore_status=True, name=k).cpu() for k, v in to_return.items()} + return to_return + + +def should_only_save_mm_adapter(args) -> bool: + # LoRA runs need full PEFT checkpoint handling, even when adapters are also trainable. + if getattr(args, "lora_enable", False): + return False + + if getattr(args, "tune_mm_mlp_adapter", False): + return True + + mm_tunable_parts = getattr(args, "mm_tunable_parts", None) + if not mm_tunable_parts: + return False + + tunable_parts = [part.strip() for part in mm_tunable_parts.split(",") if part.strip()] + return len(tunable_parts) == 1 and tunable_parts[0] in {"mm_mlp_adapter", "mm_vision_resampler"} + + +def split_to_even_chunks(indices, lengths, num_chunks): + """ + Split a list of indices into `chunks` chunks of roughly equal lengths. + """ + + if len(indices) % num_chunks != 0: + return [indices[i::num_chunks] for i in range(num_chunks)] + + num_indices_per_chunk = len(indices) // num_chunks + + chunks = [[] for _ in range(num_chunks)] + chunks_lengths = [0 for _ in range(num_chunks)] + for index in indices: + shortest_chunk = chunks_lengths.index(min(chunks_lengths)) + chunks[shortest_chunk].append(index) + chunks_lengths[shortest_chunk] += lengths[index] + if len(chunks[shortest_chunk]) == num_indices_per_chunk: + chunks_lengths[shortest_chunk] = float("inf") + + return chunks + + +def get_variable_length_grouped_indices(lengths, batch_size, world_size, megabatch_mult=8, generator=None): + # We need to use torch for the random part as a distributed sampler will set the random seed for torch. + indices = torch.randperm(len(lengths), generator=generator) + sorted_indices = sorted(range(len(lengths)), key=lambda i: lengths[i], reverse=True) + megabatch_size = world_size * batch_size * megabatch_mult + megabatches = [sorted_indices[i : i + megabatch_size] for i in range(0, len(lengths), megabatch_size)] + megabatches = [sorted(megabatch, key=lambda i: indices[i], reverse=True) for megabatch in megabatches] + shuffled_indices = [i for megabatch in megabatches for i in megabatch] + world_batch_size = world_size * batch_size + batches = [shuffled_indices[i : i + world_batch_size] for i in range(0, len(lengths), world_batch_size)] + batch_indices = torch.randperm(len(batches), generator=generator) + batches = [batches[i] for i in batch_indices] + + return [i for batch in batches for i in batch] + + +def get_modality_length_grouped_indices(lengths, batch_size, world_size, generator=None): + """ + Return a list of indices so that each slice of `batch_size` consecutive indices correspond to elements of similar + lengths. To do this, the indices are: + + - randomly permuted + - grouped in mega-batches of size `mega_batch_mult * batch_size` + - reorder by length in each mega-batch + + The result is the concatenation of all mega-batches, with the batch of `batch_size` containing the element of + maximum length placed first, so that an OOM happens sooner rather than later. + """ + + # We need to use torch for the random part as a distributed sampler will set the random seed for torch. + assert all(l != 0 for l in lengths), "Should not have zero length." + if all(l > 0 for l in lengths) or all(l < 0 for l in lengths): + # all samples are in the same modality + return get_length_grouped_indices(lengths, batch_size, world_size, generator=generator) + mm_indices, mm_lengths = zip(*[(i, l) for i, l in enumerate(lengths) if l > 0]) + lang_indices, lang_lengths = zip(*[(i, -l) for i, l in enumerate(lengths) if l < 0]) + + mm_shuffle = [mm_indices[i] for i in get_length_grouped_indices(mm_lengths, batch_size, world_size, generator=None)] + lang_shuffle = [lang_indices[i] for i in get_length_grouped_indices(lang_lengths, batch_size, world_size, generator=None)] + megabatch_size = world_size * batch_size + mm_megabatches = [mm_shuffle[i : i + megabatch_size] for i in range(0, len(mm_shuffle), megabatch_size)] + lang_megabatches = [lang_shuffle[i : i + megabatch_size] for i in range(0, len(lang_shuffle), megabatch_size)] + + last_mm = mm_megabatches[-1] + last_lang = lang_megabatches[-1] + additional_batch = last_mm + last_lang + megabatches = mm_megabatches[:-1] + lang_megabatches[:-1] + megabatch_indices = torch.randperm(len(megabatches), generator=generator) + megabatches = [megabatches[i] for i in megabatch_indices] + + if len(additional_batch) > 0: + megabatches.append(sorted(additional_batch)) + + return [i for megabatch in megabatches for i in megabatch] + + +def get_length_grouped_indices(lengths, batch_size, world_size, generator=None, merge=True): + """ + Return a list of indices so that each slice of `batch_size` consecutive indices correspond to elements of similar + lengths. To do this, the indices are: + + - randomly permuted + - grouped in mega-batches of size `mega_batch_mult * batch_size` + - reorder by length in each mega-batch + + The result is the concatenation of all mega-batches, with the batch of `batch_size` containing the element of + maximum length placed first, so that an OOM happens sooner rather than later. + """ + + # We need to use torch for the random part as a distributed sampler will set the random seed for torch. + indices = torch.randperm(len(lengths), generator=generator) + megabatch_size = world_size * batch_size + megabatches = [indices[i : i + megabatch_size].tolist() for i in range(0, len(lengths), megabatch_size)] + megabatches = [sorted(megabatch, key=lambda i: lengths[i], reverse=True) for megabatch in megabatches] + megabatches = [split_to_even_chunks(megabatch, lengths, world_size) for megabatch in megabatches] + + return [i for megabatch in megabatches for batch in megabatch for i in batch] + + +def get_length_grouped_indices_auto_single(lengths, batch_size, world_size, generator=None): + indices = get_length_grouped_indices_hf(lengths, batch_size * world_size, generator=generator) + + megabatch_size = world_size * batch_size + megabatches = [indices[i : i + megabatch_size] for i in range(0, len(lengths), megabatch_size)] + megabatches = [sorted(megabatch, key=lambda i: lengths[i], reverse=True) for megabatch in megabatches] + megabatches = [split_to_even_chunks(megabatch, lengths, world_size) for megabatch in megabatches] + + # We need to use torch for the random part as a distributed sampler will set the random seed for torch. + batch_indices = torch.randperm(len(megabatches), generator=generator) + megabatches = [megabatches[i] for i in batch_indices] + + return [i for megabatch in megabatches for batch in megabatch for i in batch] + + +def get_modality_length_grouped_indices_auto(lengths, batch_size, world_size, generator=None): + # We need to use torch for the random part as a distributed sampler will set the random seed for torch. + assert all(l != 0 for l in lengths), "Should not have zero length." + if all(l > 0 for l in lengths) or all(l < 0 for l in lengths): + # all samples are in the same modality + return get_length_grouped_indices_auto_single(lengths, batch_size, world_size, generator=generator) + mm_indices, mm_lengths = zip(*[(i, l) for i, l in enumerate(lengths) if l > 0]) + lang_indices, lang_lengths = zip(*[(i, -l) for i, l in enumerate(lengths) if l < 0]) + + mm_shuffle = [mm_indices[i] for i in get_length_grouped_indices_auto_single(mm_lengths, batch_size, world_size, generator=None)] + lang_shuffle = [lang_indices[i] for i in get_length_grouped_indices_auto_single(lang_lengths, batch_size, world_size, generator=None)] + megabatch_size = world_size * batch_size + mm_megabatches = [mm_shuffle[i : i + megabatch_size] for i in range(0, len(mm_shuffle), megabatch_size)] + lang_megabatches = [lang_shuffle[i : i + megabatch_size] for i in range(0, len(lang_shuffle), megabatch_size)] + + last_mm = mm_megabatches[-1] + last_lang = lang_megabatches[-1] + additional_batch = last_mm + last_lang + megabatches = mm_megabatches[:-1] + lang_megabatches[:-1] + megabatch_indices = torch.randperm(len(megabatches), generator=generator) + megabatches = [megabatches[i] for i in megabatch_indices] + + # FIXME: Hard code to avoid last batch mixed with different modalities + # if len(additional_batch) > 0: + # megabatches.append(sorted(additional_batch)) + + return [i for megabatch in megabatches for i in megabatch] + + +class LengthGroupedSampler(Sampler): + r""" + Sampler that samples indices in a way that groups together features of the dataset of roughly the same length while + keeping a bit of randomness. + """ + + def __init__( + self, + batch_size: int, + world_size: int, + lengths: Optional[List[int]] = None, + generator=None, + variable_length: bool = False, + group_by_modality: bool = False, + group_by_modality_auto: bool = False, + ): + if lengths is None: + raise ValueError("Lengths must be provided.") + + self.batch_size = batch_size + self.world_size = world_size + self.lengths = lengths + self.generator = generator + self.variable_length = variable_length + self.group_by_modality = group_by_modality + self.group_by_modality_auto = group_by_modality_auto + + def __len__(self): + return len(self.lengths) + + def __iter__(self): + if self.variable_length: + assert not self.group_by_modality, "Variable length grouping is not supported with modality grouping." + indices = get_variable_length_grouped_indices(self.lengths, self.batch_size, self.world_size, generator=self.generator) + else: + if self.group_by_modality: + indices = get_modality_length_grouped_indices(self.lengths, self.batch_size, self.world_size, generator=self.generator) + elif self.group_by_modality_auto: + indices = get_modality_length_grouped_indices_auto(self.lengths, self.batch_size, self.world_size, generator=self.generator) + else: + indices = get_length_grouped_indices_auto_single(self.lengths, self.batch_size, self.world_size, generator=self.generator) + return iter(indices) + + +class LLaVATrainer(Trainer): + def __init__(self, **kwargs): + """ + Initialize the LLaVATrainer with MeZO support. + + Args: + trainer_mode (str): Mode of training (`regular`, `zo`). + zo_eps (float): MeZO hyperparameter epsilon. + zo_num_directions (int): Number of directions for zero-order optimization. + """ + super().__init__(**kwargs) + + args = self.args + + self.trainer_mode = getattr(args, "trainer_mode", "regular") + self.zo_eps = getattr(args, "zo_eps", 1e-3) + self.zo_num_directions = getattr(args, "zo_num_directions", 1) + + print(f"MeZOLLaVATrainer initialized with mode: {self.trainer_mode}") + self.projected_grad = None + self.zo_random_seed = None + + self.zo_direction_accumulator = [] + self.zo_accumulation_count = 0 + + self.batch_zo_seeds = None + + self.trainable_params = [(p[0], p[1]) for p in self.model.named_parameters() if p[1].requires_grad] + + print(f"Trainable parameters amount: {len(self.trainable_params)}") + + if not self.trainable_params: + raise ValueError("No trainable parameters found.") + + if self.trainer_mode == "zo": + for param in self.model.parameters(): + param.requires_grad = False # Ensure no accidental gradient computation + + self.mezo_update_history = [] + + ######################## + # MeZO-specific Methods + ######################## + + def zo_perturb_parameters(self, scaling_factor=1.0): + """ + Perturb the model parameters with a random vector z. + + Args: + scaling_factor (float): Scaling factor for the perturbation. + """ + torch.manual_seed(self.zo_random_seed) + for name, param in self.trainable_params: + z = torch.normal( + mean=0, std=1, size=param.data.size(), + device=param.device, dtype=param.dtype + ) + param.data += scaling_factor * z * self.zo_eps + + def zo_forward(self, model, inputs): + """ + Compute the loss. + + Args: + model (nn.Module): The model. + inputs (Dict): Batch of inputs. + + Returns: + torch.Tensor: The computed loss. + """ + model.eval() + with torch.inference_mode(): + inputs = self._prepare_inputs(inputs) + with self.compute_loss_context_manager(): + loss = self.compute_loss(model, inputs) + if self.args.n_gpu > 1: + loss = loss.mean() + return loss.detach() + + def zo_step(self, model, inputs): + """ + Estimate the gradient using MeZO by performing multiple directional forward passes. + + Args: + model (nn.Module): The model. + inputs (Dict): Batch of inputs. + + Returns: + torch.Tensor: The loss from the first forward pass. + """ + directions = [] + + if self.batch_zo_seeds is None: + self.batch_zo_seeds = [np.random.randint(1000000000) for _ in range(self.zo_num_directions)] + print(f"Sampled batch seeds: {self.batch_zo_seeds}") + + for seed in self.batch_zo_seeds: + self.zo_random_seed = seed + + self.zo_perturb_parameters(scaling_factor=1.0) + loss_plus = self.zo_forward(model, inputs) + + self.zo_perturb_parameters(scaling_factor=-2.0) + loss_minus = self.zo_forward(model, inputs) + print(f"Seed {seed} loss_plus: {loss_plus} loss_minus: {loss_minus}") + + self.zo_perturb_parameters(scaling_factor=1.0) + + grad_estimate = ((loss_plus - loss_minus) / (2 * self.zo_eps)).item() + + directions.append((seed, grad_estimate)) + + update_entry = { + "type": "zo_step", + "global_step": self.state.global_step, + "zo_eps": self.zo_eps, + "seed": seed, + } + + self.mezo_update_history.append(update_entry) + + self.zo_direction_accumulator.extend(directions) + self.zo_accumulation_count += 1 + + return loss_plus / (self.args.gradient_accumulation_steps * self.zo_num_directions) + + def zo_update(self, learning_rate): + """ + Update model parameters based on the estimated gradient. + + Args: + learning_rate (float): The learning rate used for the update. + """ + if len(self.zo_direction_accumulator) == 0: + print("No accumulated directions to update.") + return + + seed_group = {} + for seed, grad_estimate in self.zo_direction_accumulator: + if seed in seed_group: + seed_group[seed] += grad_estimate / (self.args.gradient_accumulation_steps * self.zo_num_directions) + else: + seed_group[seed] = grad_estimate / (self.args.gradient_accumulation_steps * self.zo_num_directions) + + for seed, grad_sum in seed_group.items(): + torch.manual_seed(seed) + + for name, param in self.trainable_params: + z = torch.normal( + mean=0, std=1, size=param.data.size(), + device=param.device, dtype=param.dtype + ) + if "bias" not in name and "layer_norm" not in name and "layernorm" not in name: + param.data -= learning_rate * (grad_sum * z + self.args.weight_decay * param.data) + else: + param.data -= learning_rate * grad_sum * z + + print( + f"Applied MeZO update with aggregated grad estimates " + f"from {len(self.zo_direction_accumulator)} directions " + f"(aggregated to {len(seed_group)} unique seeds)." + f"Seed group: {seed_group}") + + self.zo_direction_accumulator = [] + self.zo_accumulation_count = 0 + self.batch_zo_seeds = None + + update_entry = { + "type": "mezo_update", + "global_step": self.state.global_step, + "learning_rate": learning_rate, + "seed_group": seed_group + } + + self.mezo_update_history.append(update_entry) + + def _save_mezo_state(self, output_dir: str): + """ + Save the MeZO state checkpoint that includes the noise seeds and the accumulated grad estimates. + """ + mezo_state = { + "weight_decay": self.args.weight_decay, + "zo_eps": self.zo_eps, + "zo_num_directions": self.zo_num_directions, + "trainable_params_names": [name for name, _ in self.trainable_params], + "trainable_params_sizes": {name: param.size() for name, param in self.trainable_params}, + "update_history": self.mezo_update_history + } + mezo_checkpoint_path = os.path.join(output_dir, "mezo_state.pt") + torch.save(mezo_state, mezo_checkpoint_path) + print(f"MeZO checkpoint saved at {mezo_checkpoint_path}") + + def save_model(self, output_dir: Optional[str] = None, _internal_call: bool = False): + """ + Override the save_model method to also store the lightweight MeZO checkpoint. + """ + ret = super().save_model(output_dir, _internal_call) + + if self.trainer_mode == "zo": + output_dir = output_dir if output_dir is not None else self.args.output_dir + self._save_mezo_state(output_dir) + return ret + + ######################## + # MeZO-specific Methods + ######################## + + def create_accelerator_and_postprocess(self): + grad_acc_kwargs = {"num_steps": self.args.gradient_accumulation_steps} + grad_acc_kwargs["sync_with_dataloader"] = False + gradient_accumulation_plugin = GradientAccumulationPlugin(**grad_acc_kwargs) + + accelerator_kwargs = InitProcessGroupKwargs(timeout=timedelta(weeks=52)) + rank0_print("Setting NCCL timeout to INF to avoid running errors.") + + # create accelerator object + self.accelerator = Accelerator( + 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] + ) + # some Trainer classes need to use `gather` instead of `gather_for_metrics`, thus we store a flag + self.gather_function = self.accelerator.gather_for_metrics + + # deepspeed and accelerate flags covering both trainer args and accelerate launcher + self.is_deepspeed_enabled = getattr(self.accelerator.state, "deepspeed_plugin", None) is not None + self.is_fsdp_enabled = getattr(self.accelerator.state, "fsdp_plugin", None) is not None + + # post accelerator creation setup + if self.is_fsdp_enabled: + fsdp_plugin = self.accelerator.state.fsdp_plugin + fsdp_plugin.limit_all_gathers = self.args.fsdp_config.get("limit_all_gathers", fsdp_plugin.limit_all_gathers) + if is_accelerate_available("0.23.0"): + fsdp_plugin.activation_checkpointing = self.args.fsdp_config.get("activation_checkpointing", fsdp_plugin.activation_checkpointing) + if fsdp_plugin.activation_checkpointing and self.args.gradient_checkpointing: + 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.") + + if self.is_deepspeed_enabled and getattr(self.args, "hf_deepspeed_config", None) is None: + self.propagate_args_to_deepspeed() + + def _get_train_sampler(self) -> Optional[torch.utils.data.Sampler]: + if self.train_dataset is None or not has_length(self.train_dataset): + return None + + if self.args.group_by_length: + lengths = self.train_dataset.lengths + return LengthGroupedSampler( + # self.args.train_batch_size * self.args.gradient_accumulation_steps, # TODO: seems that we should not have gradient_accumulation_steps + self.args.train_batch_size, + # world_size=self.args.world_size, + world_size=self.args.world_size * self.args.gradient_accumulation_steps, # TODO: seems that this may work? + lengths=lengths, + ) + elif self.args.group_by_modality_length: + lengths = self.train_dataset.modality_lengths + return LengthGroupedSampler( + # self.args.train_batch_size * self.args.gradient_accumulation_steps, # TODO: seems that we should not have gradient_accumulation_steps + self.args.train_batch_size, + # world_size=self.args.world_size, + world_size=self.args.world_size * self.args.gradient_accumulation_steps, # TODO: seems that this may work? + lengths=lengths, + group_by_modality=True, + ) + elif self.args.group_by_modality_length_auto: + lengths = self.train_dataset.modality_lengths + return LengthGroupedSampler( + # self.args.train_batch_size * self.args.gradient_accumulation_steps, # TODO: seems that we should not have gradient_accumulation_steps + self.args.train_batch_size, + # world_size=self.args.world_size, + world_size=self.args.world_size * self.args.gradient_accumulation_steps, # TODO: seems that this may work? + lengths=lengths, + group_by_modality_auto=True, + ) + elif self.args.group_by_varlen: + lengths = self.train_dataset.lengths + return LengthGroupedSampler( + self.args.train_batch_size * self.args.gradient_accumulation_steps, + # self.args.train_batch_size, # TODO: seems that we should have gradient_accumulation_steps + # world_size=self.args.world_size, + world_size=self.args.world_size * self.args.gradient_accumulation_steps, # TODO: seems that this may work? + lengths=lengths, + variable_length=True, + ) + else: + return super()._get_train_sampler() + + def get_train_dataloader(self) -> DataLoader: + """ + Returns the training [`~torch.utils.data.DataLoader`]. + + Will use no sampler if `train_dataset` does not implement `__len__`, a random sampler (adapted to distributed + training if necessary) otherwise. + + Subclass and override this method if you want to inject some custom behavior. + """ + if self.train_dataset is None: + raise ValueError("Trainer: training requires a train_dataset.") + + train_dataset = self.train_dataset + data_collator = self.data_collator + if is_datasets_available() and isinstance(train_dataset, datasets.Dataset): + train_dataset = self._remove_unused_columns(train_dataset, description="training") + else: + data_collator = self._get_collator_with_removed_columns(data_collator, description="training") + + dataloader_params = { + "batch_size": self._train_batch_size, + "collate_fn": data_collator, + "num_workers": self.args.dataloader_num_workers, + "pin_memory": self.args.dataloader_pin_memory, + "persistent_workers": self.args.dataloader_persistent_workers, + } + + if not isinstance(train_dataset, torch.utils.data.IterableDataset): + dataloader_params["sampler"] = self._get_train_sampler() + dataloader_params["drop_last"] = self.args.dataloader_drop_last + dataloader_params["worker_init_fn"] = seed_worker + dataloader_params["prefetch_factor"] = self.args.dataloader_num_workers * 2 if self.args.dataloader_num_workers != 0 else None + + dataloader = self.accelerator.prepare(DataLoader(train_dataset, **dataloader_params)) + + return dataloader + + def create_optimizer(self): + """ + Setup the optimizer. + + We provide a reasonable default that works well. If you want to use something else, you can pass a tuple in the + Trainer's init through `optimizers`, or subclass and override this method in a subclass. + """ + if self.trainer_mode == "zo": + # Create a dummy optimizer with this dummy parameter. + # This optimizer will never really be stepped using backprop gradients. + # We use no optimizer for MeZO. All updates are done in the `zo` methods. + dummy_param = torch.nn.Parameter(torch.zeros(1, device=self.args.device)) + self.optimizer = torch.optim.AdamW([dummy_param], lr=self.args.learning_rate) + return self.optimizer + + if is_sagemaker_mp_enabled(): + return super().create_optimizer() + + opt_model = self.model + + if self.optimizer is None: + decay_parameters = get_parameter_names(opt_model, ALL_LAYERNORM_LAYERS) + decay_parameters = [name for name in decay_parameters if "bias" not in name] + lr_mapper = {} + if self.args.mm_projector_lr is not None: + lr_mapper["mm_projector"] = self.args.mm_projector_lr + if self.args.mm_vision_tower_lr is not None: + lr_mapper["vision_tower"] = self.args.mm_vision_tower_lr + if len(lr_mapper) > 0: + special_lr_parameters = [name for name, _ in opt_model.named_parameters() if any(module_keyword in name for module_keyword in lr_mapper)] + optimizer_grouped_parameters = [ + { + "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)], + "weight_decay": self.args.weight_decay, + }, + { + "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)], + "weight_decay": 0.0, + }, + ] + for module_keyword, lr in lr_mapper.items(): + module_parameters = [name for name, _ in opt_model.named_parameters() if module_keyword in name] + optimizer_grouped_parameters.extend( + [ + { + "params": [p for n, p in opt_model.named_parameters() if (n in decay_parameters and n in module_parameters and p.requires_grad)], + "weight_decay": self.args.weight_decay, + "lr": lr, + }, + { + "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)], + "weight_decay": 0.0, + "lr": lr, + }, + ] + ) + else: + optimizer_grouped_parameters = [ + { + "params": [p for n, p in opt_model.named_parameters() if (n in decay_parameters and p.requires_grad)], + "weight_decay": self.args.weight_decay, + }, + { + "params": [p for n, p in opt_model.named_parameters() if (n not in decay_parameters and p.requires_grad)], + "weight_decay": 0.0, + }, + ] + + optimizer_cls, optimizer_kwargs = Trainer.get_optimizer_cls_and_kwargs(self.args) + + self.optimizer = optimizer_cls(optimizer_grouped_parameters, **optimizer_kwargs) + if optimizer_cls.__name__ == "Adam8bit": + import bitsandbytes + + manager = bitsandbytes.optim.GlobalOptimManager.get_instance() + + skipped = 0 + for module in opt_model.modules(): + if isinstance(module, nn.Embedding): + skipped += sum({p.data_ptr(): p.numel() for p in module.parameters()}.values()) + logger.info(f"skipped {module}: {skipped/2**20}M params") + manager.register_module_override(module, "weight", {"optim_bits": 32}) + logger.debug(f"bitsandbytes: will optimize {module} in fp32") + logger.info(f"skipped: {skipped/2**20}M params") + + return self.optimizer + + def _save_checkpoint(self, model, trial, metrics=None): + if should_only_save_mm_adapter(self.args): + from transformers.trainer_utils import PREFIX_CHECKPOINT_DIR + + checkpoint_folder = f"{PREFIX_CHECKPOINT_DIR}-{self.state.global_step}" + + run_dir = self._get_output_dir(trial=trial) + output_dir = os.path.join(run_dir, checkpoint_folder) + + # Only save Adapter + keys_to_match = ["mm_projector", "vision_resampler"] + if getattr(self.args, "use_im_start_end", False): + keys_to_match.extend(["embed_tokens", "embed_in"]) + + weight_to_save = get_mm_adapter_state_maybe_zero_3(self.model.named_parameters(), keys_to_match) + + if self.args.local_rank == 0 or self.args.local_rank == -1: + self.model.config.save_pretrained(output_dir) + torch.save(weight_to_save, os.path.join(output_dir, f"mm_projector.bin")) + else: + super(LLaVATrainer, self)._save_checkpoint(model, trial, metrics) + + def _save(self, output_dir: Optional[str] = None, state_dict=None): + if should_only_save_mm_adapter(self.args): + pass + else: + super(LLaVATrainer, self)._save(output_dir, state_dict) + + def _inner_training_loop( + self, batch_size=None, args=None, resume_from_checkpoint=None, trial=None, ignore_keys_for_eval=None + ): + if args is None: + args = self.args + + # Start of existing training loop setup + self.accelerator.free_memory() + self._train_batch_size = batch_size + if self.args.auto_find_batch_size: + if self.state.train_batch_size != self._train_batch_size: + from accelerate.utils import release_memory + + (self.model_wrapped,) = release_memory(self.model_wrapped) + self.model_wrapped = self.model + + # Check for DeepSpeed *after* the initial pass and modify the config + if self.is_deepspeed_enabled: + # Temporarily unset `self.args.train_batch_size` + original_bs = self.args.per_device_train_batch_size + self.args.per_device_train_batch_size = self._train_batch_size // max(1, self.args.n_gpu) + self.propagate_args_to_deepspeed(True) + self.args.per_device_train_batch_size = original_bs + self.state.train_batch_size = self._train_batch_size + logger.debug(f"Currently training with a batch size of: {self._train_batch_size}") + # Data loader and number of training steps + train_dataloader = self.get_train_dataloader() + if self.is_fsdp_xla_v2_enabled: + train_dataloader = tpu_spmd_dataloader(train_dataloader) + + # Setting up training control variables: + # number of training epochs: num_train_epochs + # number of training steps per epoch: num_update_steps_per_epoch + # total number of training steps to execute: max_steps + total_train_batch_size = self._train_batch_size * args.gradient_accumulation_steps * args.world_size + + len_dataloader = None + num_train_tokens = None + if has_length(train_dataloader): + len_dataloader = len(train_dataloader) + num_update_steps_per_epoch = len_dataloader // args.gradient_accumulation_steps + num_update_steps_per_epoch = max(num_update_steps_per_epoch, 1) + num_examples = self.num_examples(train_dataloader) + if args.max_steps > 0: + max_steps = args.max_steps + num_train_epochs = args.max_steps // num_update_steps_per_epoch + int( + args.max_steps % num_update_steps_per_epoch > 0 + ) + # May be slightly incorrect if the last batch in the training dataloader has a smaller size but it's + # the best we can do. + num_train_samples = args.max_steps * total_train_batch_size + if args.include_tokens_per_second: + num_train_tokens = ( + self.num_tokens(train_dataloader, args.max_steps) * args.gradient_accumulation_steps + ) + else: + max_steps = math.ceil(args.num_train_epochs * num_update_steps_per_epoch) + num_train_epochs = math.ceil(args.num_train_epochs) + num_train_samples = self.num_examples(train_dataloader) * args.num_train_epochs + if args.include_tokens_per_second: + num_train_tokens = self.num_tokens(train_dataloader) * args.num_train_epochs + elif args.max_steps > 0: # Rely on max_steps when dataloader does not have a working size + max_steps = args.max_steps + # Setting a very large number of epochs so we go as many times as necessary over the iterator. + num_train_epochs = sys.maxsize + num_update_steps_per_epoch = max_steps + num_examples = total_train_batch_size * args.max_steps + num_train_samples = args.max_steps * total_train_batch_size + if args.include_tokens_per_second: + num_train_tokens = self.num_tokens(train_dataloader, args.max_steps) * args.gradient_accumulation_steps + else: + raise ValueError( + "args.max_steps must be set to a positive value if dataloader does not have a length, was" + f" {args.max_steps}" + ) + + if DebugOption.UNDERFLOW_OVERFLOW in self.args.debug: + if self.args.n_gpu > 1: + # nn.DataParallel(model) replicates the model, creating new variables and module + # references registered here no longer work on other gpus, breaking the module + raise ValueError( + "Currently --debug underflow_overflow is not supported under DP. Please use DDP" + " (torchrun or torch.distributed.launch (deprecated))." + ) + else: + debug_overflow = DebugUnderflowOverflow(self.model) # noqa + + delay_optimizer_creation = is_sagemaker_mp_enabled() or self.is_fsdp_xla_enabled or self.is_fsdp_enabled + + # We need to reset the scheduler, as its parameters may be different on subsequent calls + if self._created_lr_scheduler: + self.lr_scheduler = None + self._created_lr_scheduler = False + + if self.is_deepspeed_enabled: + ######################## + # Changed Code + ######################## + if self.trainer_mode == "zo": + # We need to set the optimizer to dummy optimizer for MeZO + self.optimizer = self.create_optimizer() + else: + self.optimizer, self.lr_scheduler = deepspeed_init(self, num_training_steps=max_steps) + ######################## + # Changed Code + ######################## + + if not delay_optimizer_creation: + self.create_optimizer_and_scheduler(num_training_steps=max_steps) + + self.state = TrainerState() + self.state.is_hyper_param_search = trial is not None + self.state.train_batch_size = self._train_batch_size + + # Compute absolute values for logging, eval, and save if given as ratio + if args.logging_steps is not None: + if args.logging_steps < 1: + self.state.logging_steps = math.ceil(max_steps * args.logging_steps) + else: + self.state.logging_steps = args.logging_steps + if args.eval_steps is not None: + if args.eval_steps < 1: + self.state.eval_steps = math.ceil(max_steps * args.eval_steps) + else: + self.state.eval_steps = args.eval_steps + if args.save_steps is not None: + if args.save_steps < 1: + self.state.save_steps = math.ceil(max_steps * args.save_steps) + else: + self.state.save_steps = args.save_steps + + # Activate gradient checkpointing if needed + if args.gradient_checkpointing: + if args.gradient_checkpointing_kwargs is None: + gradient_checkpointing_kwargs = {} + else: + gradient_checkpointing_kwargs = args.gradient_checkpointing_kwargs + + self.model.gradient_checkpointing_enable(gradient_checkpointing_kwargs=gradient_checkpointing_kwargs) + + model = self._wrap_model(self.model_wrapped) + + # as the model is wrapped, don't use `accelerator.prepare` + # this is for unhandled cases such as + # FSDP-XLA, SageMaker MP/DP, DataParallel, IPEX + use_accelerator_prepare = True if model is self.model else False + + if delay_optimizer_creation: + if use_accelerator_prepare: + self._fsdp_qlora_plugin_updates() + self.model = self.accelerator.prepare(self.model) + self.create_optimizer_and_scheduler(num_training_steps=max_steps) + + # prepare using `accelerator` prepare + if use_accelerator_prepare: + self.model.train() + if hasattr(self.lr_scheduler, "step"): + if self.use_apex: + model = self.accelerator.prepare(self.model) + else: + model, self.optimizer = self.accelerator.prepare(self.model, self.optimizer) + else: + # to handle cases wherein we pass "DummyScheduler" such as when it is specified in DeepSpeed config. + model, self.optimizer, self.lr_scheduler = self.accelerator.prepare( + self.model, self.optimizer, self.lr_scheduler + ) + + if self.is_fsdp_enabled: + self.model = self.model_wrapped = model + + # for the rest of this function `model` is the outside model, whether it was wrapped or not + if model is not self.model: + self.model_wrapped = model + + # backward compatibility + if self.is_deepspeed_enabled: + self.deepspeed = self.model_wrapped + + # ckpt loading + if resume_from_checkpoint is not None: + if self.is_deepspeed_enabled: + deepspeed_load_checkpoint( + self.model_wrapped, resume_from_checkpoint, load_module_strict=not _is_peft_model(self.model) + ) + elif is_sagemaker_mp_enabled() or self.is_fsdp_enabled: + self._load_from_checkpoint(resume_from_checkpoint, self.model_wrapped) + + # Check if saved optimizer or scheduler states exist + self._load_optimizer_and_scheduler(resume_from_checkpoint) + + # important: at this point: + # self.model is the Transformers Model + # self.model_wrapped is DDP(Transformers Model), Deepspeed(Transformers Model), + # FSDP(Transformers Model), Dynamo Optimized Module(Transformers Model) etc. + + # Train! + logger.info("***** Running training *****") + logger.info(f" Num examples = {num_examples:,}") + logger.info(f" Num Epochs = {num_train_epochs:,}") + logger.info(f" Instantaneous batch size per device = {self.args.per_device_train_batch_size:,}") + if self.args.per_device_train_batch_size != self._train_batch_size: + logger.info(f" Training with DataParallel so batch size has been adjusted to: {self._train_batch_size:,}") + logger.info(f" Total train batch size (w. parallel, distributed & accumulation) = {total_train_batch_size:,}") + logger.info(f" Gradient Accumulation steps = {args.gradient_accumulation_steps}") + logger.info(f" Total optimization steps = {max_steps:,}") + logger.info(f" Number of trainable parameters = {get_model_param_count(model, trainable_only=True):,}") + + self.state.epoch = 0 + start_time = time.time() + epochs_trained = 0 + steps_trained_in_current_epoch = 0 + steps_trained_progress_bar = None + + # Check if continuing training from a checkpoint + if resume_from_checkpoint is not None and os.path.isfile( + os.path.join(resume_from_checkpoint, TRAINER_STATE_NAME) + ): + self.state = TrainerState.load_from_json(os.path.join(resume_from_checkpoint, TRAINER_STATE_NAME)) + self.compare_trainer_and_checkpoint_args(self.args, self.state) + epochs_trained = self.state.global_step // num_update_steps_per_epoch + if not args.ignore_data_skip: + steps_trained_in_current_epoch = self.state.global_step % (num_update_steps_per_epoch) + steps_trained_in_current_epoch *= args.gradient_accumulation_steps + else: + steps_trained_in_current_epoch = 0 + + logger.info(" Continuing training from checkpoint, will skip to saved global_step") + logger.info(f" Continuing training from epoch {epochs_trained}") + logger.info(f" Continuing training from global step {self.state.global_step}") + if not args.ignore_data_skip: + logger.info( + f" Will skip the first {epochs_trained} epochs then the first" + f" {steps_trained_in_current_epoch} batches in the first epoch." + ) + + # Update the references + self.callback_handler.model = self.model + self.callback_handler.optimizer = self.optimizer + self.callback_handler.lr_scheduler = self.lr_scheduler + self.callback_handler.train_dataloader = train_dataloader + if self.hp_name is not None and self._trial is not None: + # use self._trial because the SigOpt/Optuna hpo only call `_hp_search_setup(trial)` instead of passing trial + # parameter to Train when using DDP. + self.state.trial_name = self.hp_name(self._trial) + if trial is not None: + assignments = trial.assignments if self.hp_search_backend == HPSearchBackend.SIGOPT else trial + self.state.trial_params = hp_params(assignments) + else: + self.state.trial_params = None + # This should be the same if the state has been saved but in case the training arguments changed, it's safer + # to set this after the load. + self.state.max_steps = max_steps + self.state.num_train_epochs = num_train_epochs + self.state.is_local_process_zero = self.is_local_process_zero() + self.state.is_world_process_zero = self.is_world_process_zero() + + # tr_loss is a tensor to avoid synchronization of TPUs through .item() + tr_loss = torch.tensor(0.0).to(args.device) + # _total_loss_scalar is updated everytime .item() has to be called on tr_loss and stores the sum of all losses + self._total_loss_scalar = 0.0 + self._globalstep_last_logged = self.state.global_step + model.zero_grad() + grad_norm: Optional[float] = None + + self.control = self.callback_handler.on_train_begin(args, self.state, self.control) + + # Skip the first epochs_trained epochs to get the random state of the dataloader at the right point. + if not args.ignore_data_skip: + for epoch in range(epochs_trained): + sampler = get_dataloader_sampler(train_dataloader) + sampler_kinds = [RandomSampler] + if version.parse(accelerate_version) > version.parse("0.23.0"): + sampler_kinds.append(SeedableRandomSampler) + is_random_sampler = isinstance(sampler, tuple(sampler_kinds)) + if not is_random_sampler: + # We just need to begin an iteration to create the randomization of the sampler. + for _ in train_dataloader: + break + else: + # Otherwise we need to call the whooooole sampler cause there is some random operation added + # AT THE VERY END! + sampler = sampler if sampler is not None else [] + _ = list(sampler) + + total_batched_samples = 0 + for epoch in range(epochs_trained, num_train_epochs): + epoch_iterator = train_dataloader + if hasattr(epoch_iterator, "set_epoch"): + epoch_iterator.set_epoch(epoch) + + # Reset the past mems state at the beginning of each epoch if necessary. + if args.past_index >= 0: + self._past = None + + steps_in_epoch = ( + len(epoch_iterator) + if len_dataloader is not None + else args.max_steps * args.gradient_accumulation_steps + ) + self.control = self.callback_handler.on_epoch_begin(args, self.state, self.control) + + if epoch == epochs_trained and resume_from_checkpoint is not None and steps_trained_in_current_epoch == 0: + self._load_rng_state(resume_from_checkpoint) + + rng_to_sync = False + steps_skipped = 0 + if steps_trained_in_current_epoch > 0: + epoch_iterator = skip_first_batches(epoch_iterator, steps_trained_in_current_epoch) + steps_skipped = steps_trained_in_current_epoch + steps_trained_in_current_epoch = 0 + rng_to_sync = True + + step = -1 + for step, inputs in enumerate(epoch_iterator): + total_batched_samples += 1 + + if self.args.include_num_input_tokens_seen: + main_input_name = getattr(self.model, "main_input_name", "input_ids") + if main_input_name not in inputs: + logger.warning( + "Tried to track the number of tokens seen, however the current model is " + "not configured properly to know what item is the input. To fix this, add " + "a `main_input_name` attribute to the model class you are using." + ) + else: + input_device = inputs[main_input_name].device + self.state.num_input_tokens_seen += torch.sum( + self.accelerator.gather( + torch.tensor(inputs[main_input_name].numel(), device=input_device, dtype=torch.int64) + ) + ).item() + if rng_to_sync: + self._load_rng_state(resume_from_checkpoint) + rng_to_sync = False + + # Skip past any already trained steps if resuming training + if steps_trained_in_current_epoch > 0: + steps_trained_in_current_epoch -= 1 + if steps_trained_progress_bar is not None: + steps_trained_progress_bar.update(1) + if steps_trained_in_current_epoch == 0: + self._load_rng_state(resume_from_checkpoint) + continue + elif steps_trained_progress_bar is not None: + steps_trained_progress_bar.close() + steps_trained_progress_bar = None + + if step % args.gradient_accumulation_steps == 0: + self.control = self.callback_handler.on_step_begin(args, self.state, self.control) + + ######################## + # MeZO Integration + ######################## + if self.trainer_mode == "zo": + # Perform MeZO step + tr_loss_step = self.zo_step(model, inputs) + else: + # Regular training step with gradient accumulation + with self.accelerator.accumulate(model): + tr_loss_step = self.training_step(model, inputs) + print(f"Step {step} loss: {tr_loss_step}") + + torch.cuda.empty_cache() # Releasing reserved memory seems not to work correctly, so do it manually + ######################## + # End of MeZO Integration + ######################## + + # Accumulate loss + if ( + args.logging_nan_inf_filter + and not is_torch_xla_available() + and (torch.isnan(tr_loss_step) or torch.isinf(tr_loss_step)) + ): + # if loss is nan or inf simply add the average of previous logged losses + tr_loss += tr_loss / (1 + self.state.global_step - self._globalstep_last_logged) + else: + if tr_loss.device != tr_loss_step.device: + raise ValueError( + f"Calculated loss must be on the original device: {tr_loss.device} but device in use is {tr_loss_step.device}" + ) + tr_loss += tr_loss_step + + self.current_flos += float(self.floating_point_ops(inputs)) + + is_last_step_and_steps_less_than_grad_acc = ( + steps_in_epoch <= args.gradient_accumulation_steps and (step + 1) == steps_in_epoch + ) + + if ( + total_batched_samples % args.gradient_accumulation_steps == 0 + or + # last step in epoch but step is always smaller than gradient_accumulation_steps + is_last_step_and_steps_less_than_grad_acc + ): + ######################## + # MeZO Integration + ######################## + if self.trainer_mode == "zo": + self.zo_update(learning_rate=self._get_learning_rate()) + self.lr_scheduler.step() + ######################## + # End of MeZO Integration + ######################## + else: + # the `or` condition of `is_last_step_and_steps_less_than_grad_acc` is not covered + # in accelerate. So, explicitly enable sync gradients to True in that case. + if is_last_step_and_steps_less_than_grad_acc: + self.accelerator.gradient_state._set_sync_gradients(True) + + # Gradient clipping + if args.max_grad_norm is not None and args.max_grad_norm > 0: + # deepspeed does its own clipping + + if is_sagemaker_mp_enabled() and args.fp16: + _grad_norm = self.optimizer.clip_master_grads(args.max_grad_norm) + elif self.use_apex: + # Revert to normal clipping otherwise, handling Apex or full precision + _grad_norm = nn.utils.clip_grad_norm_( + amp.master_params(self.optimizer), + args.max_grad_norm, + ) + else: + _grad_norm = self.accelerator.clip_grad_norm_( + model.parameters(), + args.max_grad_norm, + ) + + if ( + is_accelerate_available() + and self.accelerator.distributed_type == DistributedType.DEEPSPEED + ): + grad_norm = model.get_global_grad_norm() + # In some cases the grad norm may not return a float + if hasattr(grad_norm, "item"): + grad_norm = grad_norm.item() + else: + grad_norm = _grad_norm + + # Optimizer step + self.optimizer.step() + optimizer_was_run = not self.accelerator.optimizer_step_was_skipped + if optimizer_was_run: + # Delay optimizer scheduling until metrics are generated + if not isinstance(self.lr_scheduler, torch.optim.lr_scheduler.ReduceLROnPlateau): + self.lr_scheduler.step() + + model.zero_grad() + + self.state.global_step += 1 + self.state.epoch = epoch + (step + 1 + steps_skipped) / steps_in_epoch + self.control = self.callback_handler.on_step_end(args, self.state, self.control) + + self._maybe_log_save_evaluate(tr_loss, grad_norm, model, trial, epoch, ignore_keys_for_eval) + else: + self.control = self.callback_handler.on_substep_end(args, self.state, self.control) + + if self.control.should_epoch_stop or self.control.should_training_stop: + # PyTorch/XLA relies on the data loader to insert the mark_step for + # each step. Since we are breaking the loop early, we need to manually + # insert the mark_step here. + if is_torch_xla_available(): + xm.mark_step() + break + + if step < 0: + logger.warning( + "There seems to be not a single sample in your epoch_iterator, stopping training at step" + f" {self.state.global_step}! This is expected if you're using an IterableDataset and set" + f" num_steps ({max_steps}) higher than the number of available samples." + ) + self.control.should_training_stop = True + + self.control = self.callback_handler.on_epoch_end(args, self.state, self.control) + self._maybe_log_save_evaluate(tr_loss, grad_norm, model, trial, epoch, ignore_keys_for_eval) + + if DebugOption.TPU_METRICS_DEBUG in self.args.debug: + if is_torch_xla_available(): + # tpu-comment: Logging debug metrics for PyTorch/XLA (compile, execute times, ops, etc.) + xm.master_print(met.metrics_report()) + else: + logger.warning( + "You enabled PyTorch/XLA debug metrics but you don't have a TPU " + "configured. Check your training configuration if this is unexpected." + ) + if self.control.should_training_stop: + break + + if args.past_index and hasattr(self, "_past"): + # Clean the state at the end of training + delattr(self, "_past") + + logger.info("\n\nTraining completed. Do not forget to share your model on huggingface.co/models =)\n\n") + if args.load_best_model_at_end and self.state.best_model_checkpoint is not None: + # Wait for everyone to get here so we are sure the model has been saved by process 0. + if is_torch_xla_available(): + xm.rendezvous("load_best_model_at_end") + elif args.parallel_mode == ParallelMode.DISTRIBUTED: + dist.barrier() + elif is_sagemaker_mp_enabled(): + smp.barrier() + + self._load_best_model() + + # add remaining tr_loss + self._total_loss_scalar += tr_loss.item() + effective_global_step = max(self.state.global_step, 0.001) # Avoid ZeroDivisionError + train_loss = self._total_loss_scalar / effective_global_step + + metrics = speed_metrics( + "train", + start_time, + num_samples=num_train_samples, + num_steps=self.state.max_steps, + num_tokens=num_train_tokens, + ) + self.store_flos() + metrics["total_flos"] = self.state.total_flos + metrics["train_loss"] = train_loss + + self.is_in_train = False + + self._memory_tracker.stop_and_update_metrics(metrics) + + self.log(metrics) + + run_dir = self._get_output_dir(trial) + checkpoints_sorted = self._sorted_checkpoints(use_mtime=False, output_dir=run_dir) + + # Delete the last checkpoint when save_total_limit=1 if it's different from the best checkpoint and process allowed to save. + if self.args.should_save and self.state.best_model_checkpoint is not None and self.args.save_total_limit == 1: + for checkpoint in checkpoints_sorted: + if not os.path.samefile(checkpoint, self.state.best_model_checkpoint): + logger.info(f"Deleting older checkpoint [{checkpoint}] due to args.save_total_limit") + shutil.rmtree(checkpoint) + + self.control = self.callback_handler.on_train_end(args, self.state, self.control) + + # Wait for the checkpoint to be uploaded. + self._finish_current_push() + + # After training we make sure to retrieve back the original forward pass method + # for the embedding layer by removing the forward post hook. + if self.neftune_noise_alpha is not None: + self._deactivate_neftune(self.model) + + plot_graphs_based_on_log_history( + log_history=self.state.log_history, + output_dir=run_dir, + metrics=["train_loss"], + ) + + return TrainOutput(self.state.global_step, train_loss, metrics) + + +class LLaVADPOTrainer(DPOTrainer): + def _get_train_sampler(self) -> Optional[torch.utils.data.Sampler]: + if self.train_dataset is None or not has_length(self.train_dataset): + return None + + if self.args.group_by_modality_length: + lengths = self.train_dataset.modality_lengths + return LengthGroupedSampler( + # self.args.train_batch_size * self.args.gradient_accumulation_steps, # TODO: seems that we should not have gradient_accumulation_steps + self.args.train_batch_size, + world_size=self.args.world_size, + lengths=lengths, + group_by_modality=True, + ) + else: + return super()._get_train_sampler() + + def _save_checkpoint(self, model, trial, metrics=None): + if should_only_save_mm_adapter(self.args): + from transformers.trainer_utils import PREFIX_CHECKPOINT_DIR + + checkpoint_folder = f"{PREFIX_CHECKPOINT_DIR}-{self.state.global_step}" + + run_dir = self._get_output_dir(trial=trial) + output_dir = os.path.join(run_dir, checkpoint_folder) + + # Only save Adapter + keys_to_match = ["mm_projector", "vision_resampler"] + if getattr(self.args, "use_im_start_end", False): + keys_to_match.extend(["embed_tokens", "embed_in"]) + + weight_to_save = get_mm_adapter_state_maybe_zero_3(self.model.named_parameters(), keys_to_match) + + if self.args.local_rank == 0 or self.args.local_rank == -1: + self.model.config.save_pretrained(output_dir) + torch.save(weight_to_save, os.path.join(output_dir, f"mm_projector.bin")) + else: + # super(LLaVADPOTrainer, self)._save_checkpoint(model, trial, metrics) + # print(type(model)) + # from transformers.modeling_utils import unwrap_model + # print(type(unwrap_model(model))) + # print(unwrap_model(model).config) + if self.args.lora_enable: + from transformers.trainer_utils import PREFIX_CHECKPOINT_DIR + + checkpoint_folder = f"{PREFIX_CHECKPOINT_DIR}-{self.state.global_step}" + run_dir = self._get_output_dir(trial=trial) + output_dir = os.path.join(run_dir, checkpoint_folder) + from transformers.modeling_utils import unwrap_model + + unwrapped_model = unwrap_model(model) + self.save_my_lora_ckpt(output_dir, self.args, unwrapped_model) + else: + super(LLaVADPOTrainer, self)._save_checkpoint(model, trial, metrics) + + def _save(self, output_dir: Optional[str] = None, state_dict=None): + if should_only_save_mm_adapter(self.args): + pass + else: + super(LLaVADPOTrainer, self)._save(output_dir, state_dict) diff --git "a/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/llava/train/llava_trainer_eval.py" "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/llava/train/llava_trainer_eval.py" new file mode 100644 index 0000000000000000000000000000000000000000..e82225852569674e9eea2cb8912153fba76b33fe --- /dev/null +++ "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/llava/train/llava_trainer_eval.py" @@ -0,0 +1,76 @@ +import json +import subprocess + +from llava.train.llava_trainer import LLaVATrainer + + +class LLaVAEvalTrainer(LLaVATrainer): + def evaluate(self, evaluate_args): + cmd = f"accelerate launch --num_processes {evaluate_args.eval_num_processes} -m lmms_eval \ + --model {evaluate_args.model} \ + --model_args {evaluate_args.model_args} \ + --tasks {evaluate_args.task_names} \ + --batch_size {evaluate_args.batch_size} \ + --log_samples_suffix {evaluate_args.log_samples_suffix} \ + --output_path {evaluate_args.output_path}" + if evaluate_args.limit: + cmd += f" --limit {evaluate_args.limit}" + if evaluate_args.num_fewshot: + cmd += f" --num_fewshot {evaluate_args.num_fewshot}" + if evaluate_args.gen_kwargs != "": + cmd += f" --gen_kwargs {evaluate_args.gen_kwargs}" + if evaluate_args.log_samples: + cmd += f" --log_samples" + else: + assert False, "Please log samples so that the result can be parsed" + results = subprocess.run([cmd], shell=True, capture_output=True, text=True) + try: + result_file_index_start = results.stdout.index("Saved samples to ") + result_file_index_end = results.stdout.index(f".json") + result_file_index_start += len("Saved samples to ") + file = results.stdout[result_file_index_start:result_file_index_end] + except: + result_file_index_start = results.stderr.index("Saved samples to ") + result_file_index_end = results.stderr.index(f".json") + result_file_index_start += len("Saved samples to ") + file = results.stderr[result_file_index_start:result_file_index_end] + file = file.split("/")[:-1] + file = "/".join(file) + "/results.json" + with open(file, "r") as f: + lmms_eval_results = json.load(f) + result_dict = {} + tasks_list = evaluate_args.task_names.split(",") + for task in tasks_list: + task_results = lmms_eval_results["results"][task] + for k, v in task_results.items(): + if k != "alias" and "stderr" not in k: + metric = k.split(",")[0] + result_dict[f"{task}_{metric}"] = v + return result_dict + + """def evaluate(self, evaluate_args): + initialize_tasks() + tasks_list = evaluate_args.task_names.split(",") + result_dict = {} + results = evaluator.simple_evaluate( + model=evaluate_args.model, + model_args=evaluate_args.model_args, + tasks=tasks_list, + num_fewshot=evaluate_args.num_fewshot, + batch_size=evaluate_args.batch_size, + device=evaluate_args.device, + limit=evaluate_args.limit, + check_integrity=evaluate_args.check_integrity, + show_task_to_terminal=evaluate_args.show_task_to_terminal, + log_samples=evaluate_args.log_samples, + gen_kwargs=evaluate_args.gen_kwargs, + cli_args=evaluate_args, + ) + for task in tasks_list: + task_results = results["results"][task] + for k,v in task_results.items(): + if k != "alias" and "stderr" not in k: + metric = k.split(",")[0] + result_dict[f"{task}_{metric}"] = v + + return result_dict""" diff --git "a/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/llava/train/train.py" "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/llava/train/train.py" new file mode 100644 index 0000000000000000000000000000000000000000..4c524be966283257f35d3e8a0856c9270127f6b2 --- /dev/null +++ "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/llava/train/train.py" @@ -0,0 +1,1770 @@ +# Adopted from https://github.com/lm-sys/FastChat. Below is the original copyright: +# Adopted from tatsu-lab@stanford_alpaca. Below is the original copyright: +# Copyright 2023 Rohan Taori, Ishaan Gulrajani, Tianyi Zhang, Yann Dubois, Xuechen Li +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import ast +import os +import copy +from dataclasses import dataclass, field +import json +import logging +import pathlib +from typing import Dict, Optional, Sequence, List +from PIL import Image, ImageFile +from packaging import version +import numpy as np + +import time +import random +import yaml +import math +import re +import torch + +import transformers +import tokenizers +import deepspeed + +from transformers import AutoConfig +from torch.utils.data import Dataset +from llava.constants import IGNORE_INDEX, DEFAULT_IMAGE_TOKEN, DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN, IMAGE_TOKEN_INDEX +from llava.train.llava_trainer import LLaVATrainer + +from llava import conversation as conversation_lib +from llava.model import * +from llava.mm_utils import process_highres_image, process_anyres_image, process_highres_image_crop_split, tokenizer_image_token +from llava.utils import rank0_print, process_video_with_pyav, process_video_with_decord + +torch.multiprocessing.set_sharing_strategy("file_system") + +ImageFile.LOAD_TRUNCATED_IMAGES = True +local_rank = None + +IS_TOKENIZER_GREATER_THAN_0_14 = version.parse(tokenizers.__version__) >= version.parse("0.14") + + +@dataclass +class ModelArguments: + model_name_or_path: Optional[str] = field(default="facebook/opt-125m") + 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"}) + + mm_tunable_parts: Optional[str] = field( + 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"'} + ) + # deciding which part of the multimodal model to tune, will overwrite other previous settings + + version: Optional[str] = field(default="v0") + freeze_backbone: bool = field(default=False) + tune_mm_mlp_adapter: bool = field(default=False) + tune_mm_vision_resampler: bool = field(default=False) + vision_tower: Optional[str] = field(default=None) + vision_tower_pretrained: Optional[str] = field(default=None) # default to the last layer + + unfreeze_mm_vision_tower: bool = field(default=False) + unfreeze_language_model: bool = field(default=False) + mm_vision_select_layer: Optional[int] = field(default=-1) # default to the last layer + pretrain_mm_mlp_adapter: Optional[str] = field(default=None) + mm_projector_type: Optional[str] = field(default="linear") + mm_use_im_start_end: bool = field(default=False) + mm_use_im_patch_token: bool = field(default=True) + mm_patch_merge_type: Optional[str] = field(default="flat") + mm_vision_select_feature: Optional[str] = field(default="patch") + mm_resampler_type: Optional[str] = field(default=None) + mm_mask_drop_mode: str = field(default="fixed") + mm_mask_drop_skip_percentage: float = field(default=0.0) + mm_mask_drop_ratio: float = field(default=0.25) + mm_mask_drop_ratio_upper: Optional[float] = field(default=None) + mm_mask_drop_ratio_lower: Optional[float] = field(default=None) + mm_spatial_pool_stride: Optional[int] = field(default=None) + mm_spatial_pool_mode: str = field(default="bilinear") + mm_spatial_pool_out_channels: Optional[int] = field(default=None) + mm_perceiver_depth: Optional[int] = field(default=3) + mm_perceiver_latents: Optional[int] = field(default=32) + mm_perceiver_ff_mult: Optional[float] = field(default=4) + mm_perceiver_pretrained: Optional[str] = field(default=None) + mm_qformer_depth: Optional[int] = field(default=3) + mm_qformer_latents: Optional[int] = field(default=32) + mm_qformer_pretrained: Optional[str] = field(default=None) + + rope_scaling_factor: Optional[float] = field(default=None) + rope_scaling_type: Optional[str] = field(default=None) + + s2: Optional[bool] = field(default=False) + s2_scales: Optional[str] = field(default="336,672,1008") + + use_pos_skipping: Optional[bool] = field(default=False) + pos_skipping_range: Optional[int] = field(default=4096) + + + mm_newline_position: Optional[str] = field(default="grid") + delay_load: Optional[bool] = field(default=True) + add_faster_video: Optional[bool] = field(default=False) + faster_token_stride: Optional[int] = field(default=10) + + + +@dataclass +class DataArguments: + 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"}) + lazy_preprocess: bool = False + is_multimodal: bool = False + early_mix_text: bool = False + image_folder: Optional[str] = field(default=None) + image_aspect_ratio: str = "square" + image_grid_pinpoints: Optional[str] = field(default=None) + image_crop_resolution: Optional[int] = field(default=None) + image_split_resolution: Optional[int] = field(default=None) + + video_folder: Optional[str] = field(default=None) + video_fps: Optional[int] = field(default=1) + frames_upbound: Optional[int] = field(default=0) + add_time_instruction: Optional[bool] = field(default=False) + force_sample: Optional[bool] = field(default=False) + + +@dataclass +class TrainingArguments(transformers.TrainingArguments): + cache_dir: Optional[str] = field(default=None) + optim: str = field(default="adamw_torch") + remove_unused_columns: bool = field(default=False) + freeze_mm_mlp_adapter: bool = field(default=False) + freeze_mm_vision_resampler: bool = field(default=False) + mpt_attn_impl: Optional[str] = field(default="triton") + model_max_length: int = field( + default=4096, + metadata={"help": "Maximum sequence length. Sequences will be right padded (and possibly truncated)."}, + ) + double_quant: bool = field(default=True, metadata={"help": "Compress the quantization statistics through double quantization."}) + quant_type: str = field(default="nf4", metadata={"help": "Quantization data type to use. Should be one of `fp4` or `nf4`."}) + bits: int = field(default=16, metadata={"help": "How many bits to use."}) + lora_enable: bool = False + lora_r: int = 64 + lora_alpha: int = 16 + lora_dropout: float = 0.05 + lora_weight_path: str = "" + lora_bias: str = "none" + mm_projector_lr: Optional[float] = None + mm_vision_tower_lr: Optional[float] = None + group_by_varlen: bool = field(default=False) + group_by_modality_length: bool = field(default=False) + group_by_modality_length_auto: bool = field(default=False) + auto_find_batch_size: bool = field(default=False) + gradient_checkpointing: bool = field(default=True) + verbose_logging: bool = field(default=False) + attn_implementation: str = field(default="flash_attention_2", metadata={"help": "Use transformers attention implementation."}) + trainer_mode: str = field(default="regular", metadata={"help": "Mode of training (`regular`, `zo`)."}) + zo_eps: float = field(default=1e-3, metadata={"help": "MeZO hyperparameter epsilon."}) + zo_num_directions: int = field(default=1, metadata={"help": "Number of directions for MeZO."}) + + +# @dataclass +# class EvaluationArguments: +# eval_num_processes: int = field(default=1) +# task_names: str = field(default=None) +# model: str = field(default="llava") +# model_args: Optional[str] = field(default=None) +# num_fewshot: Optional[int] = field(default=None) +# batch_size: int = field(default=1) +# device: Optional[str] = field(default=None) +# limit: Optional[int] = field(default=None) +# check_integrity: Optional[bool] = field(default=False) +# show_task_to_terminal: Optional[bool] = field(default=False) +# log_samples: Optional[bool] = field(default=True) +# gen_kwargs: Optional[str] = field(default="") +# log_samples_suffix: Optional[str] = field(default="") +# output_path: Optional[str] = field(default="./logs/") + + +def maybe_zero_3(param, ignore_status=False, name=None): + from deepspeed import zero + from deepspeed.runtime.zero.partition_parameters import ZeroParamStatus + + if hasattr(param, "ds_id"): + if param.ds_status == ZeroParamStatus.NOT_AVAILABLE: + if not ignore_status: + logging.warning(f"{name}: param.ds_status != ZeroParamStatus.NOT_AVAILABLE: {param.ds_status}") + with zero.GatheredParameters([param]): + param = param.data.detach().cpu().clone() + else: + param = param.detach().cpu().clone() + return param + + +# Borrowed from peft.utils.get_peft_model_state_dict +def get_peft_state_maybe_zero_3(named_params, bias): + if bias == "none": + to_return = {k: t for k, t in named_params if "lora_" in k} + elif bias == "all": + to_return = {k: t for k, t in named_params if "lora_" in k or "bias" in k} + elif bias == "lora_only": + to_return = {} + maybe_lora_bias = {} + lora_bias_names = set() + for k, t in named_params: + if "lora_" in k: + to_return[k] = t + bias_name = k.split("lora_")[0] + "bias" + lora_bias_names.add(bias_name) + elif "bias" in k: + maybe_lora_bias[k] = t + for k, t in maybe_lora_bias: + if bias_name in lora_bias_names: + to_return[bias_name] = t + else: + raise NotImplementedError + to_return = {k: maybe_zero_3(v, ignore_status=True) for k, v in to_return.items()} + return to_return + + +def get_peft_state_non_lora_maybe_zero_3(named_params, require_grad_only=True): + to_return = {k: t for k, t in named_params if "lora_" not in k} + if require_grad_only: + to_return = {k: t for k, t in to_return.items() if t.requires_grad} + to_return = {k: maybe_zero_3(v, ignore_status=True).cpu() for k, v in to_return.items()} + return to_return + + +def get_mm_adapter_state_maybe_zero_3(named_params, keys_to_match): + to_return = {k: t for k, t in named_params if any(key_match in k for key_match in keys_to_match)} + to_return = {k: maybe_zero_3(v, ignore_status=True).cpu() for k, v in to_return.items()} + return to_return + + +def find_all_linear_names(model): + cls = torch.nn.Linear + lora_module_names = set() + multimodal_keywords = ["mm_projector", "vision_tower", "vision_resampler"] + for name, module in model.named_modules(): + if any(mm_keyword in name for mm_keyword in multimodal_keywords): + continue + if isinstance(module, cls): + names = name.split(".") + lora_module_names.add(names[0] if len(names) == 1 else names[-1]) + + if "lm_head" in lora_module_names: # needed for 16-bit + lora_module_names.remove("lm_head") + return list(lora_module_names) + + +def safe_save_model_for_hf_trainer(trainer: transformers.Trainer, output_dir: str): + """Collects the state dict and dump to disk.""" + if hasattr(trainer.args, "tune_mm_mlp_adapter") and trainer.args.tune_mm_mlp_adapter: + check_only_save_mm_adapter_tunnable = True + # only has mm_mlp_adapter and mm_vision_resampler in the tuneable parts + 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)): + check_only_save_mm_adapter_tunnable = True + else: + check_only_save_mm_adapter_tunnable = False + + trainer.accelerator.wait_for_everyone() + torch.cuda.synchronize() + rank0_print(f"Only save projectors: {check_only_save_mm_adapter_tunnable}") + if check_only_save_mm_adapter_tunnable: + # Only save Adapter + keys_to_match = ["mm_projector", "vision_resampler"] + if getattr(trainer.args, "use_im_start_end", False): + keys_to_match.extend(["embed_tokens", "embed_in"]) + + weight_to_save = get_mm_adapter_state_maybe_zero_3(trainer.model.named_parameters(), keys_to_match) + trainer.model.config.save_pretrained(output_dir) + + current_folder = output_dir.split("/")[-1] + parent_folder = os.path.dirname(output_dir) + if trainer.args.local_rank == 0 or trainer.args.local_rank == -1: + if current_folder.startswith("checkpoint-"): + mm_projector_folder = os.path.join(parent_folder, "mm_projector") + os.makedirs(mm_projector_folder, exist_ok=True) + torch.save(weight_to_save, os.path.join(mm_projector_folder, f"{current_folder}.bin")) + else: + torch.save(weight_to_save, os.path.join(output_dir, f"mm_projector.bin")) + return + + if trainer.deepspeed: + trainer.save_model(output_dir) + return + + state_dict = trainer.model.state_dict() + if trainer.args.should_save: + cpu_state_dict = {key: value.cpu() for key, value in state_dict.items()} + del state_dict + trainer._save(output_dir, state_dict=cpu_state_dict) # noqa + + +def smart_tokenizer_and_embedding_resize( + special_tokens_dict: Dict, + tokenizer: transformers.PreTrainedTokenizer, + model: transformers.PreTrainedModel, +): + """Resize tokenizer and embedding. + + Note: This is the unoptimized version that may make your embedding size not be divisible by 64. + """ + num_new_tokens = tokenizer.add_special_tokens(special_tokens_dict) + model.resize_token_embeddings(len(tokenizer)) + + if num_new_tokens > 0: + input_embeddings = model.get_input_embeddings().weight.data + output_embeddings = model.get_output_embeddings().weight.data + + input_embeddings_avg = input_embeddings[:-num_new_tokens].mean(dim=0, keepdim=True) + output_embeddings_avg = output_embeddings[:-num_new_tokens].mean(dim=0, keepdim=True) + + input_embeddings[-num_new_tokens:] = input_embeddings_avg + output_embeddings[-num_new_tokens:] = output_embeddings_avg + + +def _tokenize_fn(strings: Sequence[str], tokenizer: transformers.PreTrainedTokenizer) -> Dict: + """Tokenize a list of strings.""" + tokenized_list = [ + tokenizer( + text, + return_tensors="pt", + padding="longest", + max_length=tokenizer.model_max_length, + truncation=True, + ) + for text in strings + ] + input_ids = labels = [tokenized.input_ids[0] for tokenized in tokenized_list] + input_ids_lens = labels_lens = [tokenized.input_ids.ne(tokenizer.pad_token_id).sum().item() for tokenized in tokenized_list] + return dict( + input_ids=input_ids, + labels=labels, + input_ids_lens=input_ids_lens, + labels_lens=labels_lens, + ) + + +def _mask_targets(target, tokenized_lens, speakers): + # cur_idx = 0 + cur_idx = tokenized_lens[0] + tokenized_lens = tokenized_lens[1:] + target[:cur_idx] = IGNORE_INDEX + for tokenized_len, speaker in zip(tokenized_lens, speakers): + if speaker == "human": + target[cur_idx + 2 : cur_idx + tokenized_len] = IGNORE_INDEX + cur_idx += tokenized_len + + +def _add_speaker_and_signal(header, source, get_conversation=True): + """Add speaker and start/end signal on each round.""" + BEGIN_SIGNAL = "### " + END_SIGNAL = "\n" + conversation = header + for sentence in source: + from_str = sentence["from"] + if from_str.lower() == "human": + from_str = conversation_lib.default_conversation.roles[0] + elif from_str.lower() == "gpt": + from_str = conversation_lib.default_conversation.roles[1] + else: + from_str = "unknown" + sentence["value"] = BEGIN_SIGNAL + from_str + ": " + sentence["value"] + END_SIGNAL + if get_conversation: + conversation += sentence["value"] + conversation += BEGIN_SIGNAL + return conversation + + +def preprocess_multimodal(sources: Sequence[str], data_args: DataArguments) -> Dict: + is_multimodal = data_args.is_multimodal + if not is_multimodal: + return sources + + for source in sources: + for sentence in source: + # TODO maybe this should be changed for interleaved data? + # if DEFAULT_IMAGE_TOKEN in sentence["value"] and not sentence["value"].startswith(DEFAULT_IMAGE_TOKEN): + # only check for num_im=1 + num_im = len(re.findall(DEFAULT_IMAGE_TOKEN, sentence["value"])) + if num_im == 1 and DEFAULT_IMAGE_TOKEN in sentence["value"] and not sentence["value"].startswith(DEFAULT_IMAGE_TOKEN): + sentence["value"] = sentence["value"].replace(DEFAULT_IMAGE_TOKEN, "").strip() + sentence["value"] = DEFAULT_IMAGE_TOKEN + "\n" + sentence["value"] + sentence["value"] = sentence["value"].strip() + if "mmtag" in conversation_lib.default_conversation.version: + sentence["value"] = sentence["value"].replace(DEFAULT_IMAGE_TOKEN, "" + DEFAULT_IMAGE_TOKEN + "") + replace_token = DEFAULT_IMAGE_TOKEN + if data_args.mm_use_im_start_end: + replace_token = DEFAULT_IM_START_TOKEN + replace_token + DEFAULT_IM_END_TOKEN + sentence["value"] = sentence["value"].replace(DEFAULT_IMAGE_TOKEN, replace_token) + + # For videoInstruct-100k noisy_data. TODO: Ask Yuanhan to clean the data instead of leaving the noise code here. + sentence["value"] = sentence["value"].replace("QA_GT_caption_based_noisy", "") + + return sources + + +def preprocess_llama_2(sources, tokenizer: transformers.PreTrainedTokenizer, has_image: bool = False) -> Dict: + conv = conversation_lib.default_conversation.copy() + roles = {"human": conv.roles[0], "gpt": conv.roles[1]} + + # Apply prompt templates + conversations = [] + for i, source in enumerate(sources): + if roles[source[0]["from"]] != conv.roles[0]: + # Skip the first one if it is not from human + source = source[1:] + + conv.messages = [] + for j, sentence in enumerate(source): + role = roles[sentence["from"]] + assert role == conv.roles[j % 2], f"{i}" + conv.append_message(role, sentence["value"]) + conversations.append(conv.get_prompt()) + + # Tokenize conversations + + if has_image: + input_ids = torch.stack([tokenizer_image_token(prompt, tokenizer, return_tensors="pt") for prompt in conversations], dim=0) + else: + input_ids = tokenizer( + conversations, + return_tensors="pt", + padding="longest", + max_length=tokenizer.model_max_length, + truncation=True, + ).input_ids + + targets = input_ids.clone() + + assert conv.sep_style == conversation_lib.SeparatorStyle.LLAMA_2 + + # Mask targets + sep = "[/INST] " + for conversation, target in zip(conversations, targets): + total_len = int(target.ne(tokenizer.pad_token_id).sum()) + + rounds = conversation.split(conv.sep2) + cur_len = 1 + target[:cur_len] = IGNORE_INDEX + for i, rou in enumerate(rounds): + if rou == "": + break + + parts = rou.split(sep) + if len(parts) != 2: + break + parts[0] += sep + + if has_image: + round_len = len(tokenizer_image_token(rou, tokenizer)) + instruction_len = len(tokenizer_image_token(parts[0], tokenizer)) - 2 + else: + round_len = len(tokenizer(rou).input_ids) + instruction_len = len(tokenizer(parts[0]).input_ids) - 2 + + target[cur_len : cur_len + instruction_len] = IGNORE_INDEX + + cur_len += round_len + target[cur_len:] = IGNORE_INDEX + + if cur_len < tokenizer.model_max_length: + if cur_len != total_len: + target[:] = IGNORE_INDEX + print(f"WARNING: tokenization mismatch: {cur_len} vs. {total_len}." f" (ignored)") + + return dict( + input_ids=input_ids, + labels=targets, + ) + + +def preprocess_gemma(sources: List[List[Dict[str, str]]], tokenizer: transformers.PreTrainedTokenizer, has_image: bool = False) -> Dict: + conv: conversation_lib.Conversation = conversation_lib.default_conversation.copy() + roles: Dict[str, str] = {"human": conv.roles[0], "gpt": conv.roles[1]} + + # Apply prompt templates + conversations: List[str] = [] + for i, source in enumerate(sources): + if roles[source[0]["from"]] != conv.roles[0]: + # Skip the first one if it is not from human + source: List[Dict[str, str]] = source[1:] + + conv.messages = [] + for j, sentence in enumerate(source): + role: str = roles[sentence["from"]] + assert role == conv.roles[j % 2], f"{i}" + conv.append_message(role, sentence["value"]) + conversations.append(conv.get_prompt()) + + # Tokenize conversations + if has_image: + input_ids: torch.Tensor = torch.stack([tokenizer_image_token(prompt, tokenizer, return_tensors="pt") for prompt in conversations], dim=0) + else: + input_ids: torch.Tensor = tokenizer( + conversations, + return_tensors="pt", + padding="longest", + max_length=tokenizer.model_max_length, + truncation=True, + ).input_ids + + targets: torch.Tensor = input_ids.clone() + assert conv.sep_style == conversation_lib.SeparatorStyle.GEMMA + + # Mask target + sep: str = conv.sep + conv.roles[1] + for conversation, target in zip(conversations, targets): + total_len: int = int(target.ne(tokenizer.pad_token_id).sum()) + + rounds: List[str] = conversation.split(conv.sep) + re_rounds = [] + for conv_idx in range(0, len(rounds), 2): + re_rounds.append(conv.sep.join(rounds[conv_idx : conv_idx + 2])) + + cur_len = 1 # Ignore + target[:cur_len] = IGNORE_INDEX + for i, rou in enumerate(re_rounds): + if rou == "": + break + + parts = rou.split(sep) + if len(parts) != 2: + break + parts[0] += sep # Re-append sep because split on this + # Now "".join(parts)==rou + + if has_image: + round_len = len(tokenizer_image_token(rou, tokenizer)) - 1 # Ignore + instruction_len = len(tokenizer_image_token(parts[0], tokenizer)) - 1 # Ignore + else: + round_len = len(tokenizer(rou).input_ids) - 1 # Ignore + instruction_len = len(tokenizer(parts[0]).input_ids) - 1 # Ignore + + round_len += 2 # sep: \n takes 2 tokens + target[cur_len : cur_len + instruction_len] = IGNORE_INDEX + cur_len += round_len + + target[cur_len:] = IGNORE_INDEX + + if cur_len < tokenizer.model_max_length: + if cur_len != total_len: + target[:] = IGNORE_INDEX + print(f"warning: tokenization mismatch: {cur_len} vs. {total_len}." f" (ignored)") + + return dict( + input_ids=input_ids, + labels=targets, + ) + + +def preprocess_qwen(sources, tokenizer: transformers.PreTrainedTokenizer, has_image: bool = False, max_len=2048, system_message: str = "You are a helpful assistant.") -> Dict: + # roles = {"human": "<|im_start|>user", "gpt": "<|im_start|>assistant"} + roles = {"human": "user", "gpt": "assistant"} + + # Add image tokens to tokenizer as a special tokens + # Use a deepcopy of tokenizer so that we don't modify on the tokenizer + tokenizer = copy.deepcopy(tokenizer) + # When there is actually an image, we add the image tokens as a special token + if has_image: + tokenizer.add_tokens([""], special_tokens=True) + + image_token_index = tokenizer.convert_tokens_to_ids("") + im_start, im_end = tokenizer.additional_special_tokens_ids + # unmask_tokens = ["<|im_start|>", "<|im_start|>", "\n"] + unmask_tokens_idx = [198, im_start, im_end] + nl_tokens = tokenizer("\n").input_ids + + # Reset Qwen chat templates so that it won't include system message every time we apply + 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 %}" + tokenizer.chat_template = chat_template + + # _system = tokenizer("system").input_ids + nl_tokens + # _user = tokenizer("user").input_ids + nl_tokens + # _assistant = tokenizer("assistant").input_ids + nl_tokens + + # Apply prompt templates + input_ids, targets = [], [] + for i, source in enumerate(sources): + if roles[source[0]["from"]] != roles["human"]: + source = source[1:] + + input_id, target = [], [] + + # New version, use apply chat template + # Build system message for each sentence + input_id += tokenizer.apply_chat_template([{"role" : "system", "content" : system_message}]) + target += [IGNORE_INDEX] * len(input_id) + + for conv in source: + # Make sure llava data can load + try: + role = conv["role"] + content = conv["content"] + except: + role = conv["from"] + content = conv["value"] + + role = roles.get(role, role) + + conv = [{"role" : role, "content" : content}] + encode_id = tokenizer.apply_chat_template(conv) + input_id += encode_id + if role in ["user", "system"]: + target += [IGNORE_INDEX] * len(encode_id) + else: + target += encode_id + + + + assert len(input_id) == len(target), f"{len(input_id)} != {len(target)}" + for idx, encode_id in enumerate(input_id): + if encode_id in unmask_tokens_idx: + target[idx] = encode_id + if encode_id == image_token_index: + input_id[idx] = IMAGE_TOKEN_INDEX + input_ids.append(input_id) + targets.append(target) + input_ids = torch.tensor(input_ids, dtype=torch.long) + targets = torch.tensor(targets, dtype=torch.long) + + return dict( + input_ids=input_ids, # tensor(bs x seq_len) + labels=targets, # tensor(bs x seq_len) + ) + + +def preprocess_llama3( + sources, + tokenizer: transformers.PreTrainedTokenizer, + has_image: bool = False, + max_len=2048, + 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.", +) -> Dict: + # roles = {"human": "<|start_header_id|>user<|end_header_id|>", "gpt": "<|start_header_id|>assistant<|end_header_id|>"} + roles = {"human": "user", "gpt": "assistant"} + + # Add image tokens to tokenizer as a special tokens + # Use a deepcopy of tokenizer so that we don't modify on the tokenizer + tokenizer = copy.deepcopy(tokenizer) + # When there is actually an image, we add the image tokens as a special token + if has_image: + tokenizer.add_tokens([""], special_tokens=True) + image_token_index = tokenizer.convert_tokens_to_ids("") + bos_token_id = tokenizer.convert_tokens_to_ids("<|begin_of_text|>") + start_header_id = tokenizer.convert_tokens_to_ids("<|start_header_id|>") + end_header_id = tokenizer.convert_tokens_to_ids("<|end_header_id|>") + eot_id = tokenizer.convert_tokens_to_ids("<|eot_id|>") + + unmask_tokens = ["<|begin_of_text|>", "<|start_header_id|>", "<|end_header_id|>", "<|eot_id|>", "\n\n"] + unmask_tokens_idx = [tokenizer.convert_tokens_to_ids(tok) for tok in unmask_tokens] + + # After update, calling tokenizer of llama3 will + # auto add bos id for the tokens. ヽ(`⌒´)ノ + def safe_tokenizer_llama3(text): + input_ids = tokenizer(text).input_ids + if input_ids[0] == bos_token_id: + input_ids = input_ids[1:] + return input_ids + + nl_tokens = tokenizer.convert_tokens_to_ids("\n\n") + # Apply prompt templates + input_ids, targets = [], [] + for i, source in enumerate(sources): + if roles[source[0]["from"]] != roles["human"]: + source = source[1:] + + input_id, target = [], [] + + # New version, use apply chat template + # Build system message for each sentence + input_id += tokenizer.apply_chat_template([{"role" : "system", "content" : system_message}]) + target += [IGNORE_INDEX] * len(input_id) + + for conv in source: + # Make sure llava data can load + try: + role = conv["role"] + content = conv["content"] + except: + role = conv["from"] + content = conv["value"] + + role = roles.get(role, role) + + conv = [{"role" : role, "content" : content}] + # First is bos token we don't need here + encode_id = tokenizer.apply_chat_template(conv)[1:] + input_id += encode_id + if role in ["user", "system"]: + target += [IGNORE_INDEX] * len(encode_id) + else: + target += encode_id + + + + assert len(input_id) == len(target), f"{len(input_id)} != {len(target)}" + for idx, encode_id in enumerate(input_id): + if encode_id in unmask_tokens_idx: + target[idx] = encode_id + if encode_id == image_token_index: + input_id[idx] = IMAGE_TOKEN_INDEX + input_ids.append(input_id) + targets.append(target) + input_ids = torch.tensor(input_ids, dtype=torch.long) + targets = torch.tensor(targets, dtype=torch.long) + + return dict( + input_ids=input_ids, # tensor(bs x seq_len) + labels=targets, # tensor(bs x seq_len) + ) + + +def preprocess_v1(sources, tokenizer: transformers.PreTrainedTokenizer, has_image: bool = False) -> Dict: + conv = conversation_lib.default_conversation.copy() + roles = {"human": conv.roles[0], "gpt": conv.roles[1]} + + # Apply prompt templates + conversations = [] + for i, source in enumerate(sources): + if roles[source[0]["from"]] != conv.roles[0]: + # Skip the first one if it is not from human + source = source[1:] + + conv.messages = [] + for j, sentence in enumerate(source): + role = roles[sentence["from"]] + assert role == conv.roles[j % 2], f"{i}" + conv.append_message(role, sentence["value"]) + conversations.append(conv.get_prompt()) + + # Tokenize conversations + + if has_image: + input_ids = torch.stack([tokenizer_image_token(prompt, tokenizer, return_tensors="pt") for prompt in conversations], dim=0) + else: + input_ids = tokenizer( + conversations, + return_tensors="pt", + padding="longest", + max_length=tokenizer.model_max_length, + truncation=True, + ).input_ids + + targets = input_ids.clone() + + assert conv.sep_style == conversation_lib.SeparatorStyle.TWO + + # Mask targets + sep = conv.sep + conv.roles[1] + ": " + for conversation, target in zip(conversations, targets): + total_len = int(target.ne(tokenizer.pad_token_id).sum()) + + rounds = conversation.split(conv.sep2) + cur_len = 1 + target[:cur_len] = IGNORE_INDEX + for i, rou in enumerate(rounds): + if rou == "": + break + + parts = rou.split(sep) + if len(parts) != 2: + break + parts[0] += sep + + if has_image: + round_len = len(tokenizer_image_token(rou, tokenizer)) + instruction_len = len(tokenizer_image_token(parts[0], tokenizer)) - 2 + else: + round_len = len(tokenizer(rou).input_ids) + instruction_len = len(tokenizer(parts[0]).input_ids) - 2 + + if i != 0 and not tokenizer.legacy and IS_TOKENIZER_GREATER_THAN_0_14: + round_len -= 1 + instruction_len -= 1 + + target[cur_len : cur_len + instruction_len] = IGNORE_INDEX + + cur_len += round_len + target[cur_len:] = IGNORE_INDEX + + if cur_len < tokenizer.model_max_length: + if cur_len != total_len: + target[:] = IGNORE_INDEX + print(f"WARNING: tokenization mismatch: {cur_len} vs. {total_len}." f" (ignored)") + + return dict( + input_ids=input_ids, + labels=targets, + ) + + +def preprocess_mpt(sources, tokenizer: transformers.PreTrainedTokenizer, has_image: bool = False) -> Dict: + conv = conversation_lib.default_conversation.copy() + roles = {"human": conv.roles[0], "gpt": conv.roles[1]} + + # Apply prompt templates + conversations = [] + for i, source in enumerate(sources): + if roles[source[0]["from"]] != conv.roles[0]: + # Skip the first one if it is not from human + source = source[1:] + + conv.messages = [] + for j, sentence in enumerate(source): + role = roles[sentence["from"]] + assert role == conv.roles[j % 2], f"{i}" + conv.append_message(role, sentence["value"]) + conversations.append(conv.get_prompt()) + + # Tokenize conversations + + if has_image: + input_ids = torch.stack([tokenizer_image_token(prompt, tokenizer, return_tensors="pt") for prompt in conversations], dim=0) + else: + input_ids = tokenizer( + conversations, + return_tensors="pt", + padding="longest", + max_length=tokenizer.model_max_length, + truncation=True, + ).input_ids + + targets = input_ids.clone() + assert conv.sep_style == conversation_lib.SeparatorStyle.MPT + + # Mask targets + sep = conv.sep + conv.roles[1] + for conversation, target in zip(conversations, targets): + total_len = int(target.ne(tokenizer.pad_token_id).sum()) + + rounds = conversation.split(conv.sep) + re_rounds = [conv.sep.join(rounds[:3])] # system + user + gpt + for conv_idx in range(3, len(rounds), 2): + re_rounds.append(conv.sep.join(rounds[conv_idx : conv_idx + 2])) # user + gpt + cur_len = 1 + target[:cur_len] = IGNORE_INDEX + for i, rou in enumerate(re_rounds): + if rou == "": + break + + parts = rou.split(sep) + if len(parts) != 2: + break + parts[0] += sep + + if has_image: + round_len = len(tokenizer_image_token(rou, tokenizer)) + instruction_len = len(tokenizer_image_token(parts[0], tokenizer)) - 1 + else: + round_len = len(tokenizer(rou).input_ids) + instruction_len = len(tokenizer(parts[0]).input_ids) - 1 + + if i != 0 and getattr(tokenizer, "legacy", False) and IS_TOKENIZER_GREATER_THAN_0_14: + round_len += 1 + instruction_len += 1 + + target[cur_len : cur_len + instruction_len] = IGNORE_INDEX + + cur_len += round_len + target[cur_len:] = IGNORE_INDEX + + if cur_len < tokenizer.model_max_length: + if cur_len != total_len: + target[:] = IGNORE_INDEX + print(f"WARNING: tokenization mismatch: {cur_len} vs. {total_len}." f"(#turns={len(re_rounds)} ignored)") + + return dict( + input_ids=input_ids, + labels=targets, + ) + + +def preprocess_plain( + sources: Sequence[str], + tokenizer: transformers.PreTrainedTokenizer, +) -> Dict: + # add end signal and concatenate together + conversations = [] + for source in sources: + assert len(source) == 2 + assert DEFAULT_IMAGE_TOKEN in source[0]["value"] + source[0]["value"] = DEFAULT_IMAGE_TOKEN + conversation = source[0]["value"] + source[1]["value"] + conversation_lib.default_conversation.sep + conversations.append(conversation) + # tokenize conversations + input_ids = [tokenizer_image_token(prompt, tokenizer, return_tensors="pt") for prompt in conversations] + targets = copy.deepcopy(input_ids) + for target, source in zip(targets, sources): + tokenized_len = len(tokenizer_image_token(source[0]["value"], tokenizer)) + target[:tokenized_len] = IGNORE_INDEX + + return dict(input_ids=input_ids, labels=targets) + + +def preprocess(sources: Sequence[str], tokenizer: transformers.PreTrainedTokenizer, has_image: bool = False) -> Dict: + """ + Given a list of sources, each is a conversation list. This transform: + 1. Add signal '### ' at the beginning each sentence, with end signal '\n'; + 2. Concatenate conversations together; + 3. Tokenize the concatenated conversation; + 4. Make a deepcopy as the target. Mask human words with IGNORE_INDEX. + """ + if conversation_lib.default_conversation.sep_style == conversation_lib.SeparatorStyle.PLAIN: + return preprocess_plain(sources, tokenizer) + if conversation_lib.default_conversation.sep_style == conversation_lib.SeparatorStyle.LLAMA_2: + return preprocess_llama_2(sources, tokenizer, has_image=has_image) + if conversation_lib.default_conversation.version.startswith("v1"): + return preprocess_v1(sources, tokenizer, has_image=has_image) + if conversation_lib.default_conversation.version == "mpt": + return preprocess_mpt(sources, tokenizer, has_image=has_image) + if conversation_lib.default_conversation.version == "qwen": + return preprocess_qwen(sources, tokenizer, has_image=has_image) + if conversation_lib.default_conversation.version == "gemma": + return preprocess_gemma(sources, tokenizer, has_image=has_image) + if conversation_lib.default_conversation.version == "llama_v3": + return preprocess_llama3(sources, tokenizer, has_image=has_image) + # add end signal and concatenate together + conversations = [] + for source in sources: + header = f"{conversation_lib.default_conversation.system}\n\n" + conversation = _add_speaker_and_signal(header, source) + conversations.append(conversation) + + # tokenize conversations + def get_tokenize_len(prompts): + return [len(tokenizer_image_token(prompt, tokenizer)) for prompt in prompts] + + if has_image: + input_ids = [tokenizer_image_token(prompt, tokenizer, return_tensors="pt") for prompt in conversations] + else: + conversations_tokenized = _tokenize_fn(conversations, tokenizer) + input_ids = conversations_tokenized["input_ids"] + + targets = copy.deepcopy(input_ids) + for target, source in zip(targets, sources): + if has_image: + tokenized_lens = get_tokenize_len([header] + [s["value"] for s in source]) + else: + tokenized_lens = _tokenize_fn([header] + [s["value"] for s in source], tokenizer)["input_ids_lens"] + speakers = [sentence["from"] for sentence in source] + _mask_targets(target, tokenized_lens, speakers) + + return dict(input_ids=input_ids, labels=targets) + + +class LazySupervisedDataset(Dataset): + def __init__(self, data_path: str, tokenizer: transformers.PreTrainedTokenizer, data_args: DataArguments): + super(LazySupervisedDataset, self).__init__() + self.tokenizer = tokenizer + self.list_data_dict = [] + + # Handle multiple JSON files specified in the data_path + if "{" in data_path and "}" in data_path: + base_path, file_pattern = re.match(r"^(.*)\{(.*)\}\.json$", data_path).groups() + file_names = file_pattern.split(",") + rank0_print(f"Loading {file_names} from {base_path}") + data_args.dataset_paths = [] + for file_name in file_names: + data_args.dataset_paths.append(f"{base_path}{file_name}.json") + full_path = f"{base_path}{file_name}.json" + rank0_print(f"Loading {full_path}") + with open(full_path, "r") as file: + cur_data_dict = json.load(file) + rank0_print(f"Loaded {len(cur_data_dict)} samples from {full_path}") + self.list_data_dict.extend(cur_data_dict) + elif data_path.endswith(".yaml"): + with open(data_path, "r") as file: + yaml_data = yaml.safe_load(file) + datasets = yaml_data.get("datasets") + # file should be in the format of: + # datasets: + # - json_path: xxxx1.json + # sampling_strategy: first:1000 + # - json_path: xxxx2.json + # sampling_strategy: end:3000 + # - json_path: xxxx3.json + # sampling_strategy: random:999 + data_args.dataset_paths = [dataset.get("json_path") for dataset in datasets] + for dataset in datasets: + json_path = dataset.get("json_path") + sampling_strategy = dataset.get("sampling_strategy", "all") + sampling_number = None + + rank0_print(f"Loading {json_path} with {sampling_strategy} sampling strategy") + + if json_path.endswith(".jsonl"): + cur_data_dict = [] + with open(json_path, "r") as json_file: + for line in json_file: + cur_data_dict.append(json.loads(line.strip())) + elif json_path.endswith(".json"): + with open(json_path, "r") as json_file: + cur_data_dict = json.load(json_file) + else: + raise ValueError(f"Unsupported file type: {json_path}") + + if ":" in sampling_strategy: + sampling_strategy, sampling_number = sampling_strategy.split(":") + if "%" in sampling_number: + sampling_number = math.ceil(int(sampling_number.split("%")[0]) * len(cur_data_dict) / 100) + else: + sampling_number = int(sampling_number) + + # Apply the sampling strategy + if sampling_strategy == "first" and sampling_number is not None: + cur_data_dict = cur_data_dict[:sampling_number] + elif sampling_strategy == "end" and sampling_number is not None: + cur_data_dict = cur_data_dict[-sampling_number:] + elif sampling_strategy == "random" and sampling_number is not None: + random.shuffle(cur_data_dict) + cur_data_dict = cur_data_dict[:sampling_number] + + rank0_print(f"Loaded {len(cur_data_dict)} samples from {json_path}") + self.list_data_dict.extend(cur_data_dict) + else: + data_args.dataset_paths = [data_path] + rank0_print(f"Loading {data_path}") + with open(data_path, "r") as file: + cur_data_dict = json.load(file) + rank0_print(f"Loaded {len(cur_data_dict)} samples from {data_path}") + self.list_data_dict.extend(cur_data_dict) + + rank0_print(f"Loaded {len(self.list_data_dict)} samples from {data_path}") + rank0_print("Formatting inputs...Skip in lazy mode") + self.tokenizer = tokenizer + self.data_args = data_args + + def __len__(self): + return len(self.list_data_dict) + + @property + def lengths(self): + length_list = [] + for sample in self.list_data_dict: + img_tokens = 128 if "image" in sample else 0 + length_list.append(sum(len(conv["value"].split()) for conv in sample["conversations"]) + img_tokens) + return length_list + + @property + def modality_lengths(self): + length_list = [] + for sample in self.list_data_dict: + cur_len = sum(len(conv["value"].split()) for conv in sample["conversations"]) + assert cur_len > 0, f"Conversation length is 0 for {sample}" + if "image" in sample or "video" in sample or self.data_args.early_mix_text: + length_list.append(cur_len) + else: + length_list.append(-cur_len) + return length_list + + def process_image(self, image_file, overwrite_image_aspect_ratio=None): + image_folder = self.data_args.image_folder + processor = self.data_args.image_processor + # print(f"\n\nInspecting the image path, folder = {image_folder}, image={image_file}\n\n") + try: + image = Image.open(os.path.join(image_folder, image_file)).convert("RGB") + except Exception as exn: + print(f"Failed to open image {image_file}. Exception:", exn) + raise exn + + image_size = image.size + image_aspect_ratio = self.data_args.image_aspect_ratio + if overwrite_image_aspect_ratio is not None: + image_aspect_ratio = overwrite_image_aspect_ratio + if image_aspect_ratio == "highres": + image = process_highres_image(image, self.data_args.image_processor, self.data_args.image_grid_pinpoints) + elif image_aspect_ratio == "anyres" or "anyres_max" in image_aspect_ratio: + image = process_anyres_image(image, self.data_args.image_processor, self.data_args.image_grid_pinpoints) + elif image_aspect_ratio == "crop_split": + image = process_highres_image_crop_split(image, self.data_args) + elif image_aspect_ratio == "pad": + + def expand2square(pil_img, background_color): + width, height = pil_img.size + if width == height: + return pil_img + elif width > height: + result = Image.new(pil_img.mode, (width, width), background_color) + result.paste(pil_img, (0, (width - height) // 2)) + return result + else: + result = Image.new(pil_img.mode, (height, height), background_color) + result.paste(pil_img, ((height - width) // 2, 0)) + return result + + image = expand2square(image, tuple(int(x * 255) for x in processor.image_mean)) + image = processor.preprocess(image, return_tensors="pt")["pixel_values"][0] + else: + image = processor.preprocess(image, return_tensors="pt")["pixel_values"][0] + return image, image_size, "image" + + def __getitem__(self, i) -> Dict[str, torch.Tensor]: + # TODO: define number of retries somewhere else + num_base_retries = 3 + num_final_retries = 300 + + # try the current sample first + for attempt_idx in range(num_base_retries): + try: + sample = self._get_item(i) + return sample + except Exception as e: + # sleep 1s in case it is a cloud disk issue + print(f"[Try #{attempt_idx}] Failed to fetch sample {i}. Exception:", e) + time.sleep(1) + + # try other samples, in case it is file corruption issue + for attempt_idx in range(num_base_retries): + try: + next_index = min(i + 1, len(self.list_data_dict) - 1) + # sample_idx = random.choice(range(len(self))) + sample = self._get_item(next_index) + return sample + except Exception as e: + # no need to sleep + print(f"[Try other #{attempt_idx}] Failed to fetch sample {next_index}. Exception:", e) + pass + + try: + sample = self._get_item(i) + return sample + except Exception as e: + raise e + + def _get_item(self, i) -> Dict[str, torch.Tensor]: + sources = self.list_data_dict[i] + if isinstance(i, int): + sources = [sources] + assert len(sources) == 1, "Don't know why it is wrapped to a list" # FIXME + + if "image" in sources[0]: + image_file = self.list_data_dict[i]["image"] + if type(image_file) is list: + image = [self.process_image(f) for f in image_file] + # Handling multi images + # overwrite to process with simple pad + if len(image_file) > 1: + image = [self.process_image(f, "pad") for f in image_file] + image = [[im[0], im[1], "image"] for im in image] + else: + image = [self.process_image(image_file)] + sources = preprocess_multimodal(copy.deepcopy([e["conversations"] for e in sources]), self.data_args) + + elif "video" in sources[0]: + video_file = self.list_data_dict[i]["video"] + video_folder = self.data_args.video_folder + video_file = os.path.join(video_folder, video_file) + suffix = video_file.split(".")[-1] + if not os.path.exists(video_file): + print("File {} not exist!".format(video_file)) + + try: + if "shareVideoGPTV" in video_file: + 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))] + frame_files.sort() # Ensure the frames are sorted if they are named sequentially + + # TODO: Hard CODE: Determine the indices for uniformly sampling 10 frames + if self.data_args.force_sample: + num_frames_to_sample = self.data_args.frames_upbound + else: + num_frames_to_sample = 10 + + avg_fps = 2 + + total_frames = len(frame_files) + sampled_indices = np.linspace(0, total_frames - 1, num_frames_to_sample, dtype=int) + + + frame_time = [i/2 for i in sampled_indices] + frame_time = ",".join([f"{i:.2f}s" for i in frame_time]) + + video_time = total_frames / avg_fps + + # Read and store the sampled frames + video = [] + for idx in sampled_indices: + frame_path = frame_files[idx] + try: + with Image.open(frame_path) as img: + frame = img.convert("RGB") + video.append(frame) + except IOError: + print(f"Failed to read frame at path: {frame_path}") + else: + video, video_time, frame_time, num_frames_to_sample = process_video_with_decord(video_file, self.data_args) + + processor = self.data_args.image_processor + image = processor.preprocess(video, return_tensors="pt")["pixel_values"] + if self.data_args.add_time_instruction: + 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." + sources[0]["conversations"][0]["value"] = f'{DEFAULT_IMAGE_TOKEN}\n{time_instruciton}\n{sources[0]["conversations"][0]["value"].replace(DEFAULT_IMAGE_TOKEN, "")}' + image = [(image, video[0].size, "video")] + sources = preprocess_multimodal(copy.deepcopy([e["conversations"] for e in sources]), self.data_args) + # print(sources) + except Exception as e: + print(f"Error: {e}") + print(f"Failed to read video file: {video_file}") + return self._get_item(i + 1) + else: + sources = copy.deepcopy([e["conversations"] for e in sources]) + + has_image = ("image" in self.list_data_dict[i]) or ("video" in self.list_data_dict[i]) + data_dict = preprocess(sources, self.tokenizer, has_image=has_image) + + if "prompt" in data_dict: + prompt = data_dict["prompt"] + else: + prompt = None + + if isinstance(i, int): + data_dict = dict(input_ids=data_dict["input_ids"][0], labels=data_dict["labels"][0]) + + # image exist in the data + if "image" in self.list_data_dict[i]: + data_dict["image"] = image + elif "video" in self.list_data_dict[i]: + data_dict["image"] = image + elif self.data_args.is_multimodal: + # image does not exist in the data, but the model is multimodal + crop_size = self.data_args.image_processor.crop_size + data_dict["image"] = [ + (torch.zeros(1, 3, crop_size["height"], crop_size["width"]), (crop_size["width"], crop_size["height"]), "text"), + ] + # prompt exist in the data + if prompt is not None: + data_dict["prompt"] = prompt + + data_dict["id"] = self.list_data_dict[i].get("id", i) + + return data_dict + + +@dataclass +class DataCollatorForSupervisedDataset(object): + """Collate examples for supervised fine-tuning.""" + + tokenizer: transformers.PreTrainedTokenizer + + def pad_sequence(self, input_ids, batch_first, padding_value): + if self.tokenizer.padding_side == "left": + input_ids = [torch.flip(_input_ids, [0]) for _input_ids in input_ids] + input_ids = torch.nn.utils.rnn.pad_sequence(input_ids, batch_first=batch_first, padding_value=padding_value) + if self.tokenizer.padding_side == "left": + input_ids = torch.flip(input_ids, [1]) + return input_ids + + def __call__(self, instances: Sequence[Dict]) -> Dict[str, torch.Tensor]: + input_ids, labels = tuple([instance[key] for instance in instances] for key in ("input_ids", "labels")) + # input_ids, labels, ids = tuple([instance[key] for instance in instances] for key in ("input_ids", "labels", "id")) + input_ids = [_input_ids[: self.tokenizer.model_max_length] for _input_ids in input_ids] + labels = [_labels[: self.tokenizer.model_max_length] for _labels in labels] + if self.tokenizer.pad_token_id is None: + # self.tokenizer.pad_token_id = self.tokenizer.eos_token_id # FIXME: this could only be triggered for llama3 model. + self.tokenizer.pad_token_id = 0 # This gets the best result. Don't know why. + input_ids = self.pad_sequence(input_ids, batch_first=True, padding_value=self.tokenizer.pad_token_id) + labels = self.pad_sequence(labels, batch_first=True, padding_value=IGNORE_INDEX) + 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)) + # batch = dict(input_ids=input_ids, labels=labels, attention_mask=input_ids.ne(self.tokenizer.pad_token_id), ids=ids) + + if "image" in instances[0]: + images = [instance["image"] for instance in instances] + + batch["image_sizes"] = [im[1] for im_list in images for im in im_list] + batch["modalities"] = [im[2] for im_list in images for im in im_list] + images = [im[0] for im_list in images for im in im_list] + + # if all(x is not None and x.shape == images[0].shape for x in images): + # Image: (N, P, C, H, W) + # Video: (N, F, C, H, W) + # batch["images"] = torch.stack(images) + # else: + batch["images"] = images + + if "prompt" in instances[0]: + batch["prompts"] = [instance["prompt"] for instance in instances] + + return batch + + +def make_supervised_data_module(tokenizer: transformers.PreTrainedTokenizer, data_args) -> Dict: + """Make dataset and collator for supervised fine-tuning.""" + train_dataset = LazySupervisedDataset(tokenizer=tokenizer, data_path=data_args.data_path, data_args=data_args) + data_collator = DataCollatorForSupervisedDataset(tokenizer=tokenizer) + return dict(train_dataset=train_dataset, eval_dataset=None, data_collator=data_collator) + + +def get_model(model_args, training_args, bnb_model_from_pretrained_args): + assert training_args.attn_implementation + if training_args.attn_implementation == "sdpa" and torch.__version__ < "2.1.2": + raise ValueError("The 'sdpa' attention implementation requires torch version 2.1.2 or higher.") + + customized_kwargs = dict() + customized_kwargs.update(bnb_model_from_pretrained_args) + cfg_pretrained = None + + overwrite_config = {} + if any( + [ + model_args.rope_scaling_factor is not None, + model_args.rope_scaling_type is not None, + model_args.mm_spatial_pool_stride is not None, + model_args.mm_spatial_pool_out_channels is not None, + model_args.mm_spatial_pool_mode is not None, + model_args.mm_resampler_type is not None, + ] + ): + cfg_pretrained = AutoConfig.from_pretrained(model_args.model_name_or_path) + + if model_args.use_pos_skipping is not None and model_args.pos_skipping_range is not None: + overwrite_config["use_pos_skipping"] = model_args.use_pos_skipping + overwrite_config["pos_skipping_range"] = model_args.pos_skipping_range + + if model_args.rope_scaling_factor is not None and model_args.rope_scaling_type is not None: + overwrite_config["rope_scaling"] = { + "factor": model_args.rope_scaling_factor, + "type": model_args.rope_scaling_type, + } + if training_args.model_max_length is None: + training_args.model_max_length = cfg_pretrained.max_position_embeddings * model_args.rope_scaling_factor + overwrite_config["max_sequence_length"] = training_args.model_max_length + assert training_args.model_max_length == int(cfg_pretrained.max_position_embeddings * model_args.rope_scaling_factor), print( + 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}" + ) + # overwrite_config["max_sequence_length"] = model_args.max_sequence_length + # overwrite_config["tokenizer_model_max_length"] = model_args.tokenizer_model_max_length + + 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: + overwrite_config["mm_resampler_type"] = model_args.mm_resampler_type + overwrite_config["mm_spatial_pool_stride"] = model_args.mm_spatial_pool_stride + overwrite_config["mm_spatial_pool_out_channels"] = model_args.mm_spatial_pool_out_channels + overwrite_config["mm_spatial_pool_mode"] = model_args.mm_spatial_pool_mode + + if model_args.mm_spatial_pool_mode is not None: + overwrite_config["mm_spatial_pool_mode"] = model_args.mm_spatial_pool_mode + + if overwrite_config: + assert cfg_pretrained is not None, "cfg_pretrained is None" + + rank0_print(f"Overwriting config with {overwrite_config}") + for k, v in overwrite_config.items(): + setattr(cfg_pretrained, k, v) + + customized_kwargs["config"] = cfg_pretrained + + if model_args.model_class_name is not None: + actual_model_class_name = f"{model_args.model_class_name}ForCausalLM" + model_class = getattr(transformers, actual_model_class_name) + rank0_print(f"Using model class {model_class} from {model_args.model_class_name}") + model = model_class.from_pretrained( + 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), + low_cpu_mem_usage=False, + **customized_kwargs, + ) + elif model_args.vision_tower is not None: + if "mixtral" in model_args.model_name_or_path.lower(): + model = LlavaMixtralForCausalLM.from_pretrained( + 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), + low_cpu_mem_usage=False, + **customized_kwargs, + ) + from transformers.models.mixtral.modeling_mixtral import MixtralSparseMoeBlock + + deepspeed.utils.set_z3_leaf_modules(model, [MixtralSparseMoeBlock]) + elif "mistral" in model_args.model_name_or_path.lower() or "zephyr" in model_args.model_name_or_path.lower(): + model = LlavaMistralForCausalLM.from_pretrained( + 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), + low_cpu_mem_usage=False, + **customized_kwargs, + ) + elif ( + "wizardlm-2" in model_args.model_name_or_path.lower() + or "vicuna" in model_args.model_name_or_path.lower() + or "llama" in model_args.model_name_or_path.lower() + or "yi" in model_args.model_name_or_path.lower() + or "nous-hermes" in model_args.model_name_or_path.lower() + and "wizard-2" in model_args.model_name_or_path.lower() + ): + model = LlavaLlamaForCausalLM.from_pretrained( + 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), + low_cpu_mem_usage=False, + **customized_kwargs, + ) + elif "qwen" in model_args.model_name_or_path.lower(): + if "moe" in model_args.model_name_or_path.lower() or "A14B" in model_args.model_name_or_path: + model = LlavaQwenMoeForCausalLM.from_pretrained( + 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), + low_cpu_mem_usage=False, + **customized_kwargs, + ) + from transformers.models.qwen2_moe.modeling_qwen2_moe import Qwen2MoeSparseMoeBlock + + deepspeed.utils.set_z3_leaf_modules(model, [Qwen2MoeSparseMoeBlock]) + else: + model = LlavaQwenForCausalLM.from_pretrained( + 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), + low_cpu_mem_usage=False, + **customized_kwargs, + ) + elif "gemma" in model_args.model_name_or_path.lower(): + model = LlavaGemmaForCausalLM.from_pretrained( + 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), + low_cpu_mem_usage=False, + **customized_kwargs, + ) + else: + raise ValueError(f"Unknown model class {model_args}") + else: + model = transformers.LlamaForCausalLM.from_pretrained( + 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), + low_cpu_mem_usage=False, + **customized_kwargs, + ) + return model + + +def train(attn_implementation=None): + global local_rank + + parser = transformers.HfArgumentParser((ModelArguments, DataArguments, TrainingArguments)) + model_args, data_args, training_args = parser.parse_args_into_dataclasses() + + if training_args.verbose_logging: + rank0_print(f"Inspecting experiment hyperparameters:\n") + rank0_print(f"model_args = {vars(model_args)}\n\n") + rank0_print(f"data_args = {vars(data_args)}\n\n") + rank0_print(f"training_args = {vars(training_args)}\n\n") + # rank0_print(f"evaluation_args = {vars(evaluation_args)}\n\n") + + local_rank = training_args.local_rank + compute_dtype = torch.float16 if training_args.fp16 else (torch.bfloat16 if training_args.bf16 else torch.float32) + + bnb_model_from_pretrained_args = {} + if training_args.bits in [4, 8]: + from transformers import BitsAndBytesConfig + + bnb_model_from_pretrained_args.update( + dict( + device_map={"": training_args.device}, + load_in_4bit=training_args.bits == 4, + load_in_8bit=training_args.bits == 8, + quantization_config=BitsAndBytesConfig( + load_in_4bit=training_args.bits == 4, + load_in_8bit=training_args.bits == 8, + llm_int8_threshold=6.0, + llm_int8_has_fp16_weight=False, + bnb_4bit_compute_dtype=compute_dtype, + bnb_4bit_use_double_quant=training_args.double_quant, + bnb_4bit_quant_type=training_args.quant_type, # {'fp4', 'nf4'} + ), + ) + ) + + model = get_model(model_args, training_args, bnb_model_from_pretrained_args) + model.config.use_cache = False + if model_args.rope_scaling_factor is not None and model_args.rope_scaling_type is not None: + model.config.rope_scaling = { + "factor": model_args.rope_scaling_factor, + "type": model_args.rope_scaling_type, + } + + if model_args.freeze_backbone: + model.model.requires_grad_(False) + + if training_args.bits in [4, 8]: + from peft import prepare_model_for_kbit_training + + model.config.torch_dtype = torch.float32 if training_args.fp16 else (torch.bfloat16 if training_args.bf16 else torch.float32) + model = prepare_model_for_kbit_training(model, use_gradient_checkpointing=training_args.gradient_checkpointing) + + if training_args.gradient_checkpointing: + if hasattr(model, "enable_input_require_grads"): + model.enable_input_require_grads() + else: + + def make_inputs_require_grad(module, input, output): + output.requires_grad_(True) + + model.get_input_embeddings().register_forward_hook(make_inputs_require_grad) + + if training_args.lora_enable: + from peft import LoraConfig, get_peft_model + + lora_config = LoraConfig( + r=training_args.lora_r, + lora_alpha=training_args.lora_alpha, + target_modules=find_all_linear_names(model), + lora_dropout=training_args.lora_dropout, + bias=training_args.lora_bias, + task_type="CAUSAL_LM", + ) + if training_args.bits == 16: + if training_args.bf16: + model.to(torch.bfloat16) + if training_args.fp16: + model.to(torch.float16) + rank0_print("Adding LoRA adapters...") + model = get_peft_model(model, lora_config) + + 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(): + 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") + elif "qwen" in model_args.model_name_or_path.lower(): + 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") + elif ( + "wizardlm-2" in model_args.model_name_or_path.lower() + or "vicuna" in model_args.model_name_or_path.lower() + or "llama" in model_args.model_name_or_path.lower() + or "yi" in model_args.model_name_or_path.lower() + or "nous-hermes" in model_args.model_name_or_path.lower() + and "wizard-2" in model_args.model_name_or_path.lower() + ): + 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", + use_fast=False, + ) + + rank0_print(f"Prompt version: {model_args.version}") + if model_args.version == "v0": + if tokenizer.pad_token is None: + smart_tokenizer_and_embedding_resize( + special_tokens_dict=dict(pad_token="[PAD]"), + tokenizer=tokenizer, + model=model, + ) + elif model_args.version == "v0.5": + tokenizer.pad_token = tokenizer.unk_token + else: + if tokenizer.unk_token is not None: + tokenizer.pad_token = tokenizer.unk_token + if model_args.version in conversation_lib.conv_templates: + conversation_lib.default_conversation = conversation_lib.conv_templates[model_args.version] + else: + conversation_lib.default_conversation = conversation_lib.conv_templates["vicuna_v1"] + + if model_args.vision_tower is not None: + model.get_model().initialize_vision_modules(model_args=model_args, fsdp=training_args.fsdp) + + vision_tower = model.get_vision_tower() + vision_tower.to(dtype=torch.bfloat16 if training_args.bf16 else torch.float16, device=training_args.device) + + data_args.image_processor = vision_tower.image_processor + data_args.is_multimodal = True + + model.config.image_aspect_ratio = data_args.image_aspect_ratio + if data_args.image_grid_pinpoints is not None: + if isinstance(data_args.image_grid_pinpoints, str) and "x" in data_args.image_grid_pinpoints: + try: + patch_size = data_args.image_processor.size[0] + except Exception as e: + patch_size = data_args.image_processor.size["shortest_edge"] + + assert patch_size in [224, 336, 384, 448, 512], "patch_size should be in [224, 336, 384, 448, 512]" + # Use regex to extract the range from the input string + matches = re.findall(r"\((\d+)x(\d+)\)", data_args.image_grid_pinpoints) + range_start = tuple(map(int, matches[0])) + range_end = tuple(map(int, matches[-1])) + # Generate a matrix of tuples from (range_start[0], range_start[1]) to (range_end[0], range_end[1]) + 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)] + # Multiply all elements by patch_size + data_args.image_grid_pinpoints = [[dim * patch_size for dim in pair] for pair in grid_pinpoints] + elif isinstance(data_args.image_grid_pinpoints, str): + data_args.image_grid_pinpoints = ast.literal_eval(data_args.image_grid_pinpoints) + + model.config.image_grid_pinpoints = data_args.image_grid_pinpoints + model.config.image_crop_resolution = data_args.image_crop_resolution + model.config.image_split_resolution = data_args.image_split_resolution + model.config.tokenizer_padding_side = tokenizer.padding_side + model.config.tokenizer_model_max_length = tokenizer.model_max_length + model.config.mm_newline_position = model_args.mm_newline_position + model.config.add_faster_video = model_args.add_faster_video + model.config.faster_token_stride = model_args.faster_token_stride + model.config.add_time_instruction = data_args.add_time_instruction + model.config.force_sample = data_args.force_sample + model.config.mm_spatial_pool_stride = model_args.mm_spatial_pool_stride + + ### Deciding train which part of the model + if model_args.mm_tunable_parts is None: # traditional way of deciding which part to train + model.config.tune_mm_mlp_adapter = training_args.tune_mm_mlp_adapter = model_args.tune_mm_mlp_adapter + model.config.tune_mm_vision_resampler = training_args.tune_mm_vision_resampler = model_args.tune_mm_vision_resampler + if model_args.tune_mm_mlp_adapter or model_args.tune_mm_vision_resampler: + model.requires_grad_(False) + # Restore LoRA trainability after global freeze + if training_args.lora_enable: + for name, param in model.named_parameters(): + if "lora_" in name: + param.requires_grad_(True) + rank0_print("Restored LoRA parameters to trainable after global freeze (legacy branch).") + if model_args.tune_mm_mlp_adapter: + for p in model.get_model().mm_projector.parameters(): + p.requires_grad = True + if model_args.tune_mm_vision_resampler: + for p in model.get_model().vision_resampler.parameters(): + p.requires_grad = True + + model.config.freeze_mm_mlp_adapter = training_args.freeze_mm_mlp_adapter + if training_args.freeze_mm_mlp_adapter: + for p in model.get_model().mm_projector.parameters(): + p.requires_grad = False + + model.config.freeze_mm_vision_resampler = training_args.freeze_mm_vision_resampler + if training_args.freeze_mm_vision_resampler: + for p in model.get_model().vision_resampler.parameters(): + p.requires_grad = False + + model.config.unfreeze_mm_vision_tower = model_args.unfreeze_mm_vision_tower + if model_args.unfreeze_mm_vision_tower: + vision_tower.requires_grad_(True) + else: + vision_tower.requires_grad_(False) + + else: + rank0_print(f"Using mm_tunable_parts: {model_args.mm_tunable_parts}") + model.config.mm_tunable_parts = training_args.mm_tunable_parts = model_args.mm_tunable_parts + # Set the entire model to not require gradients by default + model.requires_grad_(False) + vision_tower.requires_grad_(False) + model.get_model().mm_projector.requires_grad_(False) + model.get_model().vision_resampler.requires_grad_(False) + # Parse the mm_tunable_parts to decide which parts to unfreeze + tunable_parts = model_args.mm_tunable_parts.split(",") + if "mm_mlp_adapter" in tunable_parts: + for p in model.get_model().mm_projector.parameters(): + p.requires_grad = True + if "mm_vision_resampler" in tunable_parts: + for p in model.get_model().vision_resampler.parameters(): + p.requires_grad = True + if "mm_vision_tower" in tunable_parts: + for name, param in model.named_parameters(): + if "vision_tower" in name: + param.requires_grad_(True) + if "mm_language_model" in tunable_parts: + if training_args.lora_enable: + # LoRA mode: only unfreeze LoRA parameters, keep LLM backbone frozen + rank0_print("LoRA enabled: unfreezing only LoRA parameters for LLM.") + else: + # Full finetune mode: unfreeze entire LLM backbone + for name, param in model.named_parameters(): + if "vision_tower" not in name and "mm_projector" not in name and "vision_resampler" not in name: + param.requires_grad_(True) + + # Ensure LoRA parameters are always trainable when lora_enable is True, + # regardless of which mm_tunable_parts are specified. + # model.requires_grad_(False) above freezes everything including LoRA weights + # injected by PEFT, so we must explicitly restore them here. + if training_args.lora_enable: + lora_param_count = 0 + for name, param in model.named_parameters(): + if "lora_" in name: + param.requires_grad_(True) + lora_param_count += 1 + rank0_print(f"Restored {lora_param_count} LoRA parameter tensors to trainable.") + if "mm_language_model" not in tunable_parts: + rank0_print( + "WARNING: lora_enable is True but 'mm_language_model' is not in mm_tunable_parts. " + "LoRA parameters will still be trained. If you do not intend to train the language " + "model at all, consider setting --lora_enable False to avoid unnecessary overhead." + ) + + total_params = sum(p.ds_numel if hasattr(p, "ds_numel") else p.numel() for p in model.parameters()) + trainable_params = sum(p.ds_numel if hasattr(p, "ds_numel") else p.numel() for p in model.parameters() if p.requires_grad) + rank0_print(f"Total parameters: ~{total_params/1e6:.2f} MB)") + rank0_print(f"Trainable parameters: ~{trainable_params/1e6:.2f} MB)") + # Print per-group trainable parameter breakdown for verification + trainable_groups = {"lora": 0, "mm_projector": 0, "vision_resampler": 0, "vision_tower": 0, "llm_base": 0} + for name, p in model.named_parameters(): + if not p.requires_grad: + continue + n = p.ds_numel if hasattr(p, "ds_numel") else p.numel() + if "lora_" in name: + trainable_groups["lora"] += n + elif "mm_projector" in name: + trainable_groups["mm_projector"] += n + elif "vision_resampler" in name: + trainable_groups["vision_resampler"] += n + elif "vision_tower" in name: + trainable_groups["vision_tower"] += n + else: + trainable_groups["llm_base"] += n + rank0_print("Trainable parameter groups: " + ", ".join(f"{k}={v:,}" for k, v in trainable_groups.items())) + if training_args.bits in [4, 8]: + model.get_model().mm_projector.to(dtype=compute_dtype, device=training_args.device) + + model.config.mm_use_im_start_end = data_args.mm_use_im_start_end = model_args.mm_use_im_start_end + model.config.mm_projector_lr = training_args.mm_projector_lr + model.config.mm_vision_tower_lr = training_args.mm_vision_tower_lr + training_args.use_im_start_end = model_args.mm_use_im_start_end + model.config.mm_use_im_patch_token = model_args.mm_use_im_patch_token + model.initialize_vision_tokenizer(model_args, tokenizer=tokenizer) + + if training_args.bits in [4, 8]: + from peft.tuners.lora import LoraLayer + + for name, module in model.named_modules(): + if isinstance(module, LoraLayer): + if training_args.bf16: + module = module.to(torch.bfloat16) + if "norm" in name: + module = module.to(torch.float32) + if "lm_head" in name or "embed_tokens" in name: + if hasattr(module, "weight"): + if training_args.bf16 and module.weight.dtype == torch.float32: + module = module.to(torch.bfloat16) + + data_module = make_supervised_data_module(tokenizer=tokenizer, data_args=data_args) + trainer = LLaVATrainer(model=model, tokenizer=tokenizer, args=training_args, **data_module) + + if list(pathlib.Path(training_args.output_dir).glob("checkpoint-*")): + trainer.train(resume_from_checkpoint=True) + else: + trainer.train() + trainer.save_state() + + model.config.use_cache = True + + if training_args.lora_enable: + state_dict = get_peft_state_maybe_zero_3(model.named_parameters(), training_args.lora_bias) + non_lora_state_dict = get_peft_state_non_lora_maybe_zero_3(model.named_parameters()) + if training_args.local_rank == 0 or training_args.local_rank == -1: + if hasattr(model, "config"): + model.config.save_pretrained(training_args.output_dir) + if hasattr(model, "generation_config"): + model.generation_config.save_pretrained(training_args.output_dir) + model.save_pretrained(training_args.output_dir, state_dict=state_dict) + torch.save(non_lora_state_dict, os.path.join(training_args.output_dir, "non_lora_trainables.bin")) + else: + safe_save_model_for_hf_trainer(trainer=trainer, output_dir=training_args.output_dir) + + rank0_print(f"Model saved to {training_args.output_dir}") + + +if __name__ == "__main__": + train() diff --git "a/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/llava/train/train_dpo.py" "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/llava/train/train_dpo.py" new file mode 100644 index 0000000000000000000000000000000000000000..daf9ad422de38af78ca71c31acbc0fbe19c3bbb3 --- /dev/null +++ "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/llava/train/train_dpo.py" @@ -0,0 +1,1828 @@ +# Adopted from https://github.com/lm-sys/FastChat. Below is the original copyright: +# Adopted from tatsu-lab@stanford_alpaca. Below is the original copyright: +# Copyright 2023 Rohan Taori, Ishaan Gulrajani, Tianyi Zhang, Yann Dubois, Xuechen Li +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import os +import copy +import deepspeed +from dataclasses import dataclass, field +import json +import logging +import pathlib +from typing import Dict, Optional, Sequence, List +import ast + +import yaml +import time +import random +import yaml +import math +import re +import torch + +import transformers +import tokenizers + +from llava.constants import IGNORE_INDEX, DEFAULT_IMAGE_TOKEN, DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN, IMAGE_TOKEN_INDEX +from torch.utils.data import Dataset +from llava.train.llava_trainer import LLaVADPOTrainer +from data_processing.utils import load_jsonl, load_json +from llava import conversation as conversation_lib +from llava.model import * +from llava.model.language_model.llava_qwen import LlavaQwenConfig +from llava.model.language_model.llava_llama import LlavaConfig +from llava.model.language_model.llava_mistral import LlavaMistralConfig +from llava.mm_utils import process_highres_image, process_anyres_image, process_highres_image_crop_split, tokenizer_image_token +from llava.utils import rank0_print +from transformers import AutoConfig +import pickle + +from trl.trainer.utils import DPODataCollatorWithPadding +from PIL import Image, ImageFile +from decord import VideoReader, cpu + +ImageFile.LOAD_TRUNCATED_IMAGES = True +from packaging import version +from typing import Any + +local_rank = None +import numpy as np + +IS_TOKENIZER_GREATER_THAN_0_14 = version.parse(tokenizers.__version__) >= version.parse("0.14") + + +@dataclass +class ModelArguments: + model_name_or_path: Optional[str] = field(default="facebook/opt-125m") + 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"}) + + mm_tunable_parts: Optional[str] = field( + 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"'} + ) + # deciding which part of the multimodal model to tune, will overwrite other previous settings + + version: Optional[str] = field(default="v0") + freeze_backbone: bool = field(default=False) + tune_mm_mlp_adapter: bool = field(default=False) + tune_mm_vision_resampler: bool = field(default=False) + vision_tower: Optional[str] = field(default=None) + vision_tower_pretrained: Optional[str] = field(default=None) # default to the last layer + + unfreeze_mm_vision_tower: bool = field(default=False) + unfreeze_language_model: bool = field(default=False) + mm_vision_select_layer: Optional[int] = field(default=-1) # default to the last layer + pretrain_mm_mlp_adapter: Optional[str] = field(default=None) + mm_projector_type: Optional[str] = field(default="linear") + mm_use_im_start_end: bool = field(default=False) + mm_use_im_patch_token: bool = field(default=True) + mm_patch_merge_type: Optional[str] = field(default="flat") + mm_vision_select_feature: Optional[str] = field(default="patch") + mm_resampler_type: Optional[str] = field(default=None) + mm_mask_drop_mode: str = field(default="fixed") + mm_mask_drop_skip_percentage: float = field(default=0.0) + mm_mask_drop_ratio: float = field(default=0.25) + mm_mask_drop_ratio_upper: Optional[float] = field(default=None) + mm_mask_drop_ratio_lower: Optional[float] = field(default=None) + mm_spatial_pool_stride: Optional[int] = field(default=None) + mm_spatial_pool_mode: str = field(default="average") + mm_spatial_pool_out_channels: Optional[int] = field(default=None) + mm_perceiver_depth: Optional[int] = field(default=3) + mm_perceiver_latents: Optional[int] = field(default=32) + mm_perceiver_ff_mult: Optional[float] = field(default=4) + mm_perceiver_pretrained: Optional[str] = field(default=None) + mm_qformer_depth: Optional[int] = field(default=3) + mm_qformer_latents: Optional[int] = field(default=32) + mm_qformer_pretrained: Optional[str] = field(default=None) + + rope_scaling_factor: Optional[float] = field(default=None) + rope_scaling_type: Optional[str] = field(default=None) + + s2: Optional[bool] = field(default=False) + s2_scales: Optional[str] = field(default="336,672,1008") + + +@dataclass +class DataArguments: + 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"}) + lazy_preprocess: bool = False + is_multimodal: bool = False + image_folder: Optional[str] = field(default=None) + video_folder: Optional[str] = field(default=None) + video_fps: Optional[int] = field(default=1) + image_aspect_ratio: str = "square" + image_grid_pinpoints: Optional[str] = field(default=None) + image_crop_resolution: int = 384 + image_split_resolution: int = 384 + input_prompt: Optional[str] = field(default=None) + refine_prompt: Optional[bool] = field(default=False) + frames_upbound: Optional[int] = field(default=0) + num_sample: Optional[int] = field(default=None) + + +@dataclass +class TrainingArguments(transformers.TrainingArguments): + cache_dir: Optional[str] = field(default=None) + optim: str = field(default="adamw_torch") + remove_unused_columns: bool = field(default=False) + freeze_mm_mlp_adapter: bool = field(default=False) + freeze_mm_vision_resampler: bool = field(default=False) + mpt_attn_impl: Optional[str] = field(default="triton") + model_max_length: int = field( + default=4096, + metadata={"help": "Maximum sequence length. Sequences will be right padded (and possibly truncated)."}, + ) + double_quant: bool = field(default=True, metadata={"help": "Compress the quantization statistics through double quantization."}) + quant_type: str = field(default="nf4", metadata={"help": "Quantization data type to use. Should be one of `fp4` or `nf4`."}) + bits: int = field(default=16, metadata={"help": "How many bits to use."}) + lora_enable: bool = False + lora_r: int = 64 + lora_alpha: int = 16 + lora_dropout: float = 0.05 + lora_weight_path: str = "" + lora_bias: str = "none" + mm_projector_lr: Optional[float] = None + mm_vision_tower_lr: Optional[float] = None + group_by_varlen: bool = field(default=False) + group_by_modality_length: bool = field(default=False) + group_by_modality_length_auto: bool = field(default=False) + auto_find_batch_size: bool = field(default=False) + gradient_checkpointing: bool = field(default=True) + verbose_logging: bool = field(default=False) + attn_implementation: str = field(default="flash_attention_2", metadata={"help": "Use transformers attention implementation."}) + dpo_alpha: float = field(default=1.0) + beta: float = field(default=0.1) + gamma: float = field(default=1.0) + generate_during_eval: bool = field(default=False) + precompute_ref_log_probs: bool = field(default=False) + + +def maybe_zero_3(param, ignore_status=False, name=None): + from deepspeed import zero + from deepspeed.runtime.zero.partition_parameters import ZeroParamStatus + + if hasattr(param, "ds_id"): + if param.ds_status == ZeroParamStatus.NOT_AVAILABLE: + if not ignore_status: + logging.warning(f"{name}: param.ds_status != ZeroParamStatus.NOT_AVAILABLE: {param.ds_status}") + with zero.GatheredParameters([param]): + param = param.data.detach().cpu().clone() + else: + param = param.detach().cpu().clone() + return param + + +# Borrowed from peft.utils.get_peft_model_state_dict +def get_peft_state_maybe_zero_3(named_params, bias): + if bias == "none": + to_return = {k: t for k, t in named_params if "lora_" in k} + elif bias == "all": + to_return = {k: t for k, t in named_params if "lora_" in k or "bias" in k} + elif bias == "lora_only": + to_return = {} + maybe_lora_bias = {} + lora_bias_names = set() + for k, t in named_params: + if "lora_" in k: + to_return[k] = t + bias_name = k.split("lora_")[0] + "bias" + lora_bias_names.add(bias_name) + elif "bias" in k: + maybe_lora_bias[k] = t + for k, t in maybe_lora_bias: + if bias_name in lora_bias_names: + to_return[bias_name] = t + else: + raise NotImplementedError + to_return = {k: maybe_zero_3(v, ignore_status=True) for k, v in to_return.items()} + return to_return + + +def get_peft_state_non_lora_maybe_zero_3(named_params, require_grad_only=True): + to_return = {k: t for k, t in named_params if "lora_" not in k} + if require_grad_only: + to_return = {k: t for k, t in to_return.items() if t.requires_grad} + to_return = {k: maybe_zero_3(v, ignore_status=True).cpu() for k, v in to_return.items()} + return to_return + + +def get_mm_adapter_state_maybe_zero_3(named_params, keys_to_match): + to_return = {k: t for k, t in named_params if any(key_match in k for key_match in keys_to_match)} + to_return = {k: maybe_zero_3(v, ignore_status=True).cpu() for k, v in to_return.items()} + return to_return + + +def find_all_linear_names(model): + cls = torch.nn.Linear + lora_module_names = set() + multimodal_keywords = ["mm_projector", "vision_tower", "vision_resampler"] + for name, module in model.named_modules(): + if any(mm_keyword in name for mm_keyword in multimodal_keywords): + continue + if isinstance(module, cls): + names = name.split(".") + lora_module_names.add(names[0] if len(names) == 1 else names[-1]) + + if "lm_head" in lora_module_names: # needed for 16-bit + lora_module_names.remove("lm_head") + return list(lora_module_names) + + +def safe_save_model_for_hf_trainer(trainer: transformers.Trainer, output_dir: str): + """Collects the state dict and dump to disk.""" + if hasattr(trainer.args, "tune_mm_mlp_adapter") and trainer.args.tune_mm_mlp_adapter: + check_only_save_mm_adapter_tunnable = True + # only has mm_mlp_adapter and mm_vision_resampler in the tuneable parts + 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)): + check_only_save_mm_adapter_tunnable = True + else: + check_only_save_mm_adapter_tunnable = False + + trainer.accelerator.wait_for_everyone() + torch.cuda.synchronize() + rank0_print(f"Only save projectors: {check_only_save_mm_adapter_tunnable}") + if check_only_save_mm_adapter_tunnable: + # Only save Adapter + keys_to_match = ["mm_projector", "vision_resampler"] + if getattr(trainer.args, "use_im_start_end", False): + keys_to_match.extend(["embed_tokens", "embed_in"]) + + weight_to_save = get_mm_adapter_state_maybe_zero_3(trainer.model.named_parameters(), keys_to_match) + trainer.model.config.save_pretrained(output_dir) + + current_folder = output_dir.split("/")[-1] + parent_folder = os.path.dirname(output_dir) + if trainer.args.local_rank == 0 or trainer.args.local_rank == -1: + if current_folder.startswith("checkpoint-"): + mm_projector_folder = os.path.join(parent_folder, "mm_projector") + os.makedirs(mm_projector_folder, exist_ok=True) + torch.save(weight_to_save, os.path.join(mm_projector_folder, f"{current_folder}.bin")) + else: + torch.save(weight_to_save, os.path.join(output_dir, f"mm_projector.bin")) + return + + if trainer.deepspeed: + trainer.save_model(output_dir) + return + + state_dict = trainer.model.state_dict() + if trainer.args.should_save: + cpu_state_dict = {key: value.cpu() for key, value in state_dict.items()} + del state_dict + trainer._save(output_dir, state_dict=cpu_state_dict) # noqa + + +def smart_tokenizer_and_embedding_resize( + special_tokens_dict: Dict, + tokenizer: transformers.PreTrainedTokenizer, + model: transformers.PreTrainedModel, +): + """Resize tokenizer and embedding. + + Note: This is the unoptimized version that may make your embedding size not be divisible by 64. + """ + num_new_tokens = tokenizer.add_special_tokens(special_tokens_dict) + model.resize_token_embeddings(len(tokenizer)) + + if num_new_tokens > 0: + input_embeddings = model.get_input_embeddings().weight.data + output_embeddings = model.get_output_embeddings().weight.data + + input_embeddings_avg = input_embeddings[:-num_new_tokens].mean(dim=0, keepdim=True) + output_embeddings_avg = output_embeddings[:-num_new_tokens].mean(dim=0, keepdim=True) + + input_embeddings[-num_new_tokens:] = input_embeddings_avg + output_embeddings[-num_new_tokens:] = output_embeddings_avg + + +def _tokenize_fn(strings: Sequence[str], tokenizer: transformers.PreTrainedTokenizer) -> Dict: + """Tokenize a list of strings.""" + tokenized_list = [ + tokenizer( + text, + return_tensors="pt", + padding="longest", + max_length=tokenizer.model_max_length, + truncation=True, + ) + for text in strings + ] + input_ids = labels = [tokenized.input_ids[0] for tokenized in tokenized_list] + input_ids_lens = labels_lens = [tokenized.input_ids.ne(tokenizer.pad_token_id).sum().item() for tokenized in tokenized_list] + return dict( + input_ids=input_ids, + labels=labels, + input_ids_lens=input_ids_lens, + labels_lens=labels_lens, + ) + + +def _mask_targets(target, tokenized_lens, speakers): + # cur_idx = 0 + cur_idx = tokenized_lens[0] + tokenized_lens = tokenized_lens[1:] + target[:cur_idx] = IGNORE_INDEX + for tokenized_len, speaker in zip(tokenized_lens, speakers): + if speaker == "human": + target[cur_idx + 2 : cur_idx + tokenized_len] = IGNORE_INDEX + cur_idx += tokenized_len + + +def _add_speaker_and_signal(header, source, get_conversation=True): + """Add speaker and start/end signal on each round.""" + BEGIN_SIGNAL = "### " + END_SIGNAL = "\n" + conversation = header + for sentence in source: + from_str = sentence["from"] + if from_str.lower() == "human": + from_str = conversation_lib.default_conversation.roles[0] + elif from_str.lower() == "gpt": + from_str = conversation_lib.default_conversation.roles[1] + else: + from_str = "unknown" + sentence["value"] = BEGIN_SIGNAL + from_str + ": " + sentence["value"] + END_SIGNAL + if get_conversation: + conversation += sentence["value"] + conversation += BEGIN_SIGNAL + return conversation + + +def preprocess_multimodal(sources: Sequence[str], data_args: DataArguments) -> Dict: + is_multimodal = data_args.is_multimodal + if not is_multimodal: + return sources + + for source in sources: + for sentence in source: + if DEFAULT_IMAGE_TOKEN in sentence["value"] and not sentence["value"].startswith(DEFAULT_IMAGE_TOKEN): + sentence["value"] = sentence["value"].replace(DEFAULT_IMAGE_TOKEN, "").strip() + sentence["value"] = DEFAULT_IMAGE_TOKEN + "\n" + sentence["value"] + sentence["value"] = sentence["value"].strip() + if "mmtag" in conversation_lib.default_conversation.version: + sentence["value"] = sentence["value"].replace(DEFAULT_IMAGE_TOKEN, "" + DEFAULT_IMAGE_TOKEN + "") + replace_token = DEFAULT_IMAGE_TOKEN + if data_args.mm_use_im_start_end: + replace_token = DEFAULT_IM_START_TOKEN + replace_token + DEFAULT_IM_END_TOKEN + sentence["value"] = sentence["value"].replace(DEFAULT_IMAGE_TOKEN, replace_token) + + return sources + + +def preprocess_multimodal_movie(sources: Sequence[str], data_args: DataArguments, video_inputs: str) -> Dict: + is_multimodal = data_args.is_multimodal + if not is_multimodal: + return sources + + for source in sources: + for sentence in source: + if DEFAULT_IMAGE_TOKEN in sentence["value"]: + prompt = sentence["value"].replace(DEFAULT_IMAGE_TOKEN, "").strip() + replace_token = video_inputs + if data_args.mm_use_im_start_end: + replace_token = DEFAULT_IM_START_TOKEN + replace_token + DEFAULT_IM_END_TOKEN + sentence["value"] = sentence["value"].replace(DEFAULT_IMAGE_TOKEN, replace_token) + + return sources, prompt + + +def preprocess_llama_2(sources, tokenizer: transformers.PreTrainedTokenizer, has_image: bool = False) -> Dict: + conv = conversation_lib.default_conversation.copy() + roles = {"human": conv.roles[0], "gpt": conv.roles[1]} + + # Apply prompt templates + conversations = [] + for i, source in enumerate(sources): + if roles[source[0]["from"]] != conv.roles[0]: + # Skip the first one if it is not from human + source = source[1:] + + conv.messages = [] + for j, sentence in enumerate(source): + role = roles[sentence["from"]] + assert role == conv.roles[j % 2], f"{i}" + conv.append_message(role, sentence["value"]) + conversations.append(conv.get_prompt()) + + # Tokenize conversations + + if has_image: + input_ids = torch.stack([tokenizer_image_token(prompt, tokenizer, return_tensors="pt") for prompt in conversations], dim=0) + else: + input_ids = tokenizer( + conversations, + return_tensors="pt", + padding="longest", + max_length=tokenizer.model_max_length, + truncation=True, + ).input_ids + + targets = input_ids.clone() + + assert conv.sep_style == conversation_lib.SeparatorStyle.LLAMA_2 + + # Mask targets + sep = "[/INST] " + for conversation, target in zip(conversations, targets): + total_len = int(target.ne(tokenizer.pad_token_id).sum()) + + rounds = conversation.split(conv.sep2) + cur_len = 1 + target[:cur_len] = IGNORE_INDEX + for i, rou in enumerate(rounds): + if rou == "": + break + + parts = rou.split(sep) + if len(parts) != 2: + break + parts[0] += sep + + if has_image: + round_len = len(tokenizer_image_token(rou, tokenizer)) + instruction_len = len(tokenizer_image_token(parts[0], tokenizer)) - 2 + else: + round_len = len(tokenizer(rou).input_ids) + instruction_len = len(tokenizer(parts[0]).input_ids) - 2 + + target[cur_len : cur_len + instruction_len] = IGNORE_INDEX + + cur_len += round_len + target[cur_len:] = IGNORE_INDEX + + if cur_len < tokenizer.model_max_length: + if cur_len != total_len: + target[:] = IGNORE_INDEX + rank0_print(f"WARNING: tokenization mismatch: {cur_len} vs. {total_len}." f" (ignored)") + + return dict( + input_ids=input_ids, + labels=targets, + ) + + +def make_conv(prompt, answer): + return [ + { + "from": "human", + "value": prompt, + }, + { + "from": "gpt", + "value": answer, + }, + ] + + +def preprocess_gemma(sources: List[List[Dict[str, str]]], tokenizer: transformers.PreTrainedTokenizer, has_image: bool = False) -> Dict: + conv: conversation_lib.Conversation = conversation_lib.default_conversation.copy() + roles: Dict[str, str] = {"human": conv.roles[0], "gpt": conv.roles[1]} + + # Apply prompt templates + conversations: List[str] = [] + for i, source in enumerate(sources): + if roles[source[0]["from"]] != conv.roles[0]: + # Skip the first one if it is not from human + source: List[Dict[str, str]] = source[1:] + + conv.messages = [] + for j, sentence in enumerate(source): + role: str = roles[sentence["from"]] + assert role == conv.roles[j % 2], f"{i}" + conv.append_message(role, sentence["value"]) + conversations.append(conv.get_prompt()) + + # Tokenize conversations + if has_image: + input_ids: torch.Tensor = torch.stack([tokenizer_image_token(prompt, tokenizer, return_tensors="pt") for prompt in conversations], dim=0) + else: + input_ids: torch.Tensor = tokenizer( + conversations, + return_tensors="pt", + padding="longest", + max_length=tokenizer.model_max_length, + truncation=True, + ).input_ids + + targets: torch.Tensor = input_ids.clone() + assert conv.sep_style == conversation_lib.SeparatorStyle.GEMMA + + # Mask target + sep: str = conv.sep + conv.roles[1] + for conversation, target in zip(conversations, targets): + total_len: int = int(target.ne(tokenizer.pad_token_id).sum()) + + rounds: List[str] = conversation.split(conv.sep) + re_rounds = [] + for conv_idx in range(0, len(rounds), 2): + re_rounds.append(conv.sep.join(rounds[conv_idx : conv_idx + 2])) + + cur_len = 1 # Ignore + target[:cur_len] = IGNORE_INDEX + for i, rou in enumerate(re_rounds): + if rou == "": + break + + parts = rou.split(sep) + if len(parts) != 2: + break + parts[0] += sep # Re-append sep because split on this + # Now "".join(parts)==rou + + if has_image: + round_len = len(tokenizer_image_token(rou, tokenizer)) - 1 # Ignore + instruction_len = len(tokenizer_image_token(parts[0], tokenizer)) - 1 # Ignore + else: + round_len = len(tokenizer(rou).input_ids) - 1 # Ignore + instruction_len = len(tokenizer(parts[0]).input_ids) - 1 # Ignore + + round_len += 2 # sep: \n takes 2 tokens + target[cur_len : cur_len + instruction_len] = IGNORE_INDEX + cur_len += round_len + + target[cur_len:] = IGNORE_INDEX + + if cur_len < tokenizer.model_max_length: + if cur_len != total_len: + target[:] = IGNORE_INDEX + rank0_print(f"WARNING: tokenization mismatch: {cur_len} vs. {total_len}." f" (ignored)") + + return dict( + input_ids=input_ids, + labels=targets, + ) + + +def preprocess_qwen(sources, tokenizer: transformers.PreTrainedTokenizer, has_image: bool = False, max_len=2048, system_message: str = "You are a helpful assistant.") -> Dict: + roles = {"human": "<|im_start|>user", "gpt": "<|im_start|>assistant"} + + im_start, im_end = tokenizer.additional_special_tokens_ids + nl_tokens = tokenizer("\n").input_ids + _system = tokenizer("system").input_ids + nl_tokens + _user = tokenizer("user").input_ids + nl_tokens + _assistant = tokenizer("assistant").input_ids + nl_tokens + + # Apply prompt templates + input_ids, targets = [], [] + for i, source in enumerate(sources): + if roles[source[0]["from"]] != roles["human"]: + source = source[1:] + + input_id, target = [], [] + system = [im_start] + _system + tokenizer(system_message).input_ids + [im_end] + nl_tokens + input_id += system + target += [im_start] + [IGNORE_INDEX] * (len(system) - 3) + [im_end] + nl_tokens + assert len(input_id) == len(target) + for j, sentence in enumerate(source): + role = roles[sentence["from"]] + if has_image and "" in sentence["value"]: + assert sentence["value"].startswith(""), print(sentence["value"]) + + _input_id = tokenizer(role).input_ids + nl_tokens + [IMAGE_TOKEN_INDEX] + nl_tokens + tokenizer(sentence["value"][len("") :]).input_ids + [im_end] + nl_tokens + else: + _input_id = tokenizer(role).input_ids + nl_tokens + tokenizer(sentence["value"]).input_ids + [im_end] + nl_tokens + input_id += _input_id + if role == "<|im_start|>user": + _target = [im_start] + [IGNORE_INDEX] * (len(_input_id) - 3) + [im_end] + nl_tokens + elif role == "<|im_start|>assistant": + _target = [im_start] + [IGNORE_INDEX] * len(tokenizer(role).input_ids) + _input_id[len(tokenizer(role).input_ids) + 1 : -2] + [im_end] + nl_tokens + else: + raise NotImplementedError + target += _target + assert len(input_id) == len(target) + # input_id += [tokenizer.pad_token_id] * (max_len - len(input_id)) + # target += [IGNORE_INDEX] * (max_len - len(target)) + input_ids.append(input_id) + targets.append(target) + input_ids = torch.tensor(input_ids, dtype=torch.long) + targets = torch.tensor(targets, dtype=torch.long) + + return dict( + input_ids=input_ids, # tensor(bs x seq_len) + labels=targets, # tensor(bs x seq_len) + # attention_mask=input_ids.ne(tokenizer.pad_token_id), # tensor(bs x seq_len) + ) + + +def preprocess_llama3( + sources, + tokenizer: transformers.PreTrainedTokenizer, + has_image: bool = False, + max_len=2048, + 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.", +) -> Dict: + roles = {"human": "<|start_header_id|>user<|end_header_id|>", "gpt": "<|start_header_id|>assistant<|end_header_id|>"} + + eot_id = tokenizer.convert_tokens_to_ids("<|eot_id|>") + nl_tokens = tokenizer("\n").input_ids + + # Apply prompt templates + input_ids, targets = [], [] + for i, source in enumerate(sources): + if roles[source[0]["from"]] != roles["human"]: + source = source[1:] + + input_id, target = [], [] + 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] + input_id += system + target += [IGNORE_INDEX] * len(system) + for j, sentence in enumerate(source): + role = roles[sentence["from"]] + if has_image and "" in sentence["value"]: + assert sentence["value"].startswith(""), print(sentence["value"]) + _input_id = tokenizer(role).input_ids + nl_tokens * 2 + [IMAGE_TOKEN_INDEX] + tokenizer(sentence["value"][len("") :]).input_ids + [eot_id] + else: + _input_id = tokenizer(role).input_ids + nl_tokens * 2 + tokenizer(sentence["value"]).input_ids + [eot_id] + input_id += _input_id + if role == "<|start_header_id|>user<|end_header_id|>": + _target = [IGNORE_INDEX] * len(_input_id) + elif role == "<|start_header_id|>assistant<|end_header_id|>": + _target = [IGNORE_INDEX] * (len(tokenizer(role).input_ids) + 2) + _input_id[len(tokenizer(role).input_ids) + 2 : -1] + [eot_id] + else: + raise NotImplementedError + target += _target + assert len(input_id) == len(target), f"{len(input_id)} != {len(target)}" + input_ids.append(input_id) + targets.append(target) + input_ids = torch.tensor(input_ids, dtype=torch.long) + targets = torch.tensor(targets, dtype=torch.long) + + return dict( + input_ids=input_ids, # tensor(bs x seq_len) + labels=targets, # tensor(bs x seq_len) + ) + + +def preprocess_v1(sources, tokenizer: transformers.PreTrainedTokenizer, has_image: bool = False) -> Dict: + conv = conversation_lib.default_conversation.copy() + roles = {"human": conv.roles[0], "gpt": conv.roles[1]} + + # Apply prompt templates + conversations = [] + for i, source in enumerate(sources): + if roles[source[0]["from"]] != conv.roles[0]: + # Skip the first one if it is not from human + source = source[1:] + + conv.messages = [] + for j, sentence in enumerate(source): + role = roles[sentence["from"]] + assert role == conv.roles[j % 2], f"{i}" + conv.append_message(role, sentence["value"]) + conversations.append(conv.get_prompt()) + + # Tokenize conversations + + if has_image: + input_ids = torch.stack([tokenizer_image_token(prompt, tokenizer, return_tensors="pt") for prompt in conversations], dim=0) + else: + input_ids = tokenizer( + conversations, + return_tensors="pt", + padding="longest", + max_length=tokenizer.model_max_length, + truncation=True, + ).input_ids + + targets = input_ids.clone() + + assert conv.sep_style == conversation_lib.SeparatorStyle.TWO + + # Mask targets + sep = conv.sep + conv.roles[1] + ": " + for conversation, target in zip(conversations, targets): + total_len = int(target.ne(tokenizer.pad_token_id).sum()) + + rounds = conversation.split(conv.sep2) + cur_len = 1 + target[:cur_len] = IGNORE_INDEX + for i, rou in enumerate(rounds): + if rou == "": + break + + parts = rou.split(sep) + if len(parts) != 2: + break + parts[0] += sep + + if has_image: + round_len = len(tokenizer_image_token(rou, tokenizer)) + instruction_len = len(tokenizer_image_token(parts[0], tokenizer)) - 2 + else: + round_len = len(tokenizer(rou).input_ids) + instruction_len = len(tokenizer(parts[0]).input_ids) - 2 + + if i != 0 and not tokenizer.legacy and IS_TOKENIZER_GREATER_THAN_0_14: + round_len -= 1 + instruction_len -= 1 + + target[cur_len : cur_len + instruction_len] = IGNORE_INDEX + + cur_len += round_len + target[cur_len:] = IGNORE_INDEX + + if cur_len < tokenizer.model_max_length: + if cur_len != total_len: + target[:] = IGNORE_INDEX + print(f"WARNING: tokenization mismatch: {cur_len} vs. {total_len}." f" (ignored)") + + return dict( + input_ids=input_ids, + labels=targets, + ) + + +def preprocess_mpt(sources, tokenizer: transformers.PreTrainedTokenizer, has_image: bool = False) -> Dict: + conv = conversation_lib.default_conversation.copy() + roles = {"human": conv.roles[0], "gpt": conv.roles[1]} + + # Apply prompt templates + conversations = [] + for i, source in enumerate(sources): + if roles[source[0]["from"]] != conv.roles[0]: + # Skip the first one if it is not from human + source = source[1:] + + conv.messages = [] + for j, sentence in enumerate(source): + role = roles[sentence["from"]] + assert role == conv.roles[j % 2], f"{i}" + conv.append_message(role, sentence["value"]) + conversations.append(conv.get_prompt()) + + # Tokenize conversations + + if has_image: + input_ids = torch.stack([tokenizer_image_token(prompt, tokenizer, return_tensors="pt") for prompt in conversations], dim=0) + else: + input_ids = tokenizer( + conversations, + return_tensors="pt", + padding="longest", + max_length=tokenizer.model_max_length, + truncation=True, + ).input_ids + + targets = input_ids.clone() + assert conv.sep_style == conversation_lib.SeparatorStyle.MPT + + # Mask targets + sep = conv.sep + conv.roles[1] + for conversation, target in zip(conversations, targets): + total_len = int(target.ne(tokenizer.pad_token_id).sum()) + + rounds = conversation.split(conv.sep) + re_rounds = [conv.sep.join(rounds[:3])] # system + user + gpt + for conv_idx in range(3, len(rounds), 2): + re_rounds.append(conv.sep.join(rounds[conv_idx : conv_idx + 2])) # user + gpt + cur_len = 1 + target[:cur_len] = IGNORE_INDEX + for i, rou in enumerate(re_rounds): + if rou == "": + break + + parts = rou.split(sep) + if len(parts) != 2: + break + parts[0] += sep + + if has_image: + round_len = len(tokenizer_image_token(rou, tokenizer)) + instruction_len = len(tokenizer_image_token(parts[0], tokenizer)) - 1 + else: + round_len = len(tokenizer(rou).input_ids) + instruction_len = len(tokenizer(parts[0]).input_ids) - 1 + + if i != 0 and getattr(tokenizer, "legacy", False) and IS_TOKENIZER_GREATER_THAN_0_14: + round_len += 1 + instruction_len += 1 + + target[cur_len : cur_len + instruction_len] = IGNORE_INDEX + + cur_len += round_len + target[cur_len:] = IGNORE_INDEX + + if cur_len < tokenizer.model_max_length: + if cur_len != total_len: + target[:] = IGNORE_INDEX + print(f"WARNING: tokenization mismatch: {cur_len} vs. {total_len}." f"(#turns={len(re_rounds)} ignored)") + + return dict( + input_ids=input_ids, + labels=targets, + ) + + +def preprocess_plain( + sources: Sequence[str], + tokenizer: transformers.PreTrainedTokenizer, +) -> Dict: + # add end signal and concatenate together + conversations = [] + for source in sources: + assert len(source) == 2 + assert DEFAULT_IMAGE_TOKEN in source[0]["value"] + source[0]["value"] = DEFAULT_IMAGE_TOKEN + conversation = source[0]["value"] + source[1]["value"] + conversation_lib.default_conversation.sep + conversations.append(conversation) + # tokenize conversations + input_ids = [tokenizer_image_token(prompt, tokenizer, return_tensors="pt") for prompt in conversations] + targets = copy.deepcopy(input_ids) + for target, source in zip(targets, sources): + tokenized_len = len(tokenizer_image_token(source[0]["value"], tokenizer)) + target[:tokenized_len] = IGNORE_INDEX + + return dict(input_ids=input_ids, labels=targets) + + +def preprocess(sources: Sequence[str], tokenizer: transformers.PreTrainedTokenizer, has_image: bool = False) -> Dict: + """ + Given a list of sources, each is a conversation list. This transform: + 1. Add signal '### ' at the beginning each sentence, with end signal '\n'; + 2. Concatenate conversations together; + 3. Tokenize the concatenated conversation; + 4. Make a deepcopy as the target. Mask human words with IGNORE_INDEX. + """ + if conversation_lib.default_conversation.sep_style == conversation_lib.SeparatorStyle.PLAIN: + return preprocess_plain(sources, tokenizer) + if conversation_lib.default_conversation.sep_style == conversation_lib.SeparatorStyle.LLAMA_2: + return preprocess_llama_2(sources, tokenizer, has_image=has_image) + if conversation_lib.default_conversation.version.startswith("v1"): + return preprocess_v1(sources, tokenizer, has_image=has_image) + if conversation_lib.default_conversation.version == "mpt": + return preprocess_mpt(sources, tokenizer, has_image=has_image) + if conversation_lib.default_conversation.version == "qwen": + return preprocess_qwen(sources, tokenizer, has_image=has_image) + if conversation_lib.default_conversation.version == "gemma": + return preprocess_gemma(sources, tokenizer, has_image=has_image) + if conversation_lib.default_conversation.version == "llama_v3": + return preprocess_llama3(sources, tokenizer, has_image=has_image) + # add end signal and concatenate together + conversations = [] + for source in sources: + header = f"{conversation_lib.default_conversation.system}\n\n" + conversation = _add_speaker_and_signal(header, source) + conversations.append(conversation) + + # tokenize conversations + def get_tokenize_len(prompts): + return [len(tokenizer_image_token(prompt, tokenizer)) for prompt in prompts] + + if has_image: + input_ids = [tokenizer_image_token(prompt, tokenizer, return_tensors="pt") for prompt in conversations] + else: + conversations_tokenized = _tokenize_fn(conversations, tokenizer) + input_ids = conversations_tokenized["input_ids"] + + targets = copy.deepcopy(input_ids) + for target, source in zip(targets, sources): + if has_image: + tokenized_lens = get_tokenize_len([header] + [s["value"] for s in source]) + else: + tokenized_lens = _tokenize_fn([header] + [s["value"] for s in source], tokenizer)["input_ids_lens"] + speakers = [sentence["from"] for sentence in source] + _mask_targets(target, tokenized_lens, speakers) + + return dict(input_ids=input_ids, labels=targets) + + +def load_data(data_path): + if "jsonl" in data_path: + data_list = load_jsonl(data_path) + else: + data_list = load_json(data_path) + return data_list + + +class DPODataset(Dataset): + """Dataset for DPODataset fine-tuning.""" + + def __init__(self, data_path: str, tokenizer: transformers.PreTrainedTokenizer, data_args: DataArguments): + super(DPODataset, self).__init__() + # Handle multiple JSON files specified in the data_path + self.list_data_dict = [] + + if "{" in data_path and "}" in data_path: + base_path, file_pattern = re.match(r"^(.*)\{(.*)\}\.json$", data_path).groups() + file_names = file_pattern.split(",") + rank0_print(f"Loading {file_names} from {base_path}") + data_args.dataset_paths = [] + for file_name in file_names: + data_args.dataset_paths.append(f"{base_path}{file_name}.json") + full_path = f"{base_path}{file_name}.json" + rank0_print(f"Loading {full_path}") + cur_data_dict = load_data(full_path) + rank0_print(f"Loaded {len(cur_data_dict)} samples from {full_path}") + self.list_data_dict.extend(cur_data_dict) + elif data_path.endswith(".yaml"): + with open(data_path, "r") as file: + yaml_data = yaml.safe_load(file) + datasets = yaml_data.get("datasets") + # file should be in the format of: + # datasets: + # - json_path: xxxx1.json + # sampling_strategy: first:1000 + # - json_path: xxxx2.json + # sampling_strategy: end:3000 + # - json_path: xxxx3.json + # sampling_strategy: random:999 + data_args.dataset_paths = [dataset.get("json_path") for dataset in datasets] + for dataset in datasets: + json_path = dataset.get("json_path") + sampling_strategy = dataset.get("sampling_strategy", "all") + sampling_number = None + + rank0_print(f"Loading {json_path} with {sampling_strategy} sampling strategy") + cur_data_dict = load_data(json_path) + + if ":" in sampling_strategy: + sampling_strategy, sampling_number = sampling_strategy.split(":") + if "%" in sampling_number: + sampling_number = math.ceil(int(sampling_number.split("%")[0]) * len(cur_data_dict) / 100) + else: + sampling_number = int(sampling_number) + + # Apply the sampling strategy + if sampling_strategy == "first" and sampling_number is not None: + cur_data_dict = cur_data_dict[:sampling_number] + elif sampling_strategy == "end" and sampling_number is not None: + cur_data_dict = cur_data_dict[-sampling_number:] + elif sampling_strategy == "random" and sampling_number is not None: + random.shuffle(cur_data_dict) + cur_data_dict = cur_data_dict[:sampling_number] + + rank0_print(f"Loaded {len(cur_data_dict)} samples from {json_path}") + self.list_data_dict.extend(cur_data_dict) + else: + data_args.dataset_paths = [data_path] + rank0_print(f"Loading {data_path}") + cur_data_dict = load_data(data_path) + rank0_print(f"Loaded {len(cur_data_dict)} samples from {data_path}") + self.list_data_dict.extend(cur_data_dict) + + rank0_print("Formatting inputs...Skip in lazy mode") + self.tokenizer = tokenizer + self.data_args = data_args + + def __len__(self): + return len(self.list_data_dict) + + @property + def lengths(self): + length_list = [] + for sample in self.list_data_dict: + # Calculate the length of the prompt, answer, chosen, and rejected text + cur_len = len(sample["prompt"].split()) + len(sample["answer"].split()) + len(sample["chosen"].split()) + len(sample["rejected"].split()) + # Add additional tokens if an image is present + img_tokens = 128 if "image" in sample else 0 + length_list.append(cur_len + img_tokens) + return length_list + + @property + def modality_lengths(self): + length_list = [] + for sample in self.list_data_dict: + # Calculate the length of the prompt, answer, chosen, and rejected text + cur_len = len(sample["prompt"].split()) + len(sample["answer"].split()) + len(sample["chosen"].split()) + len(sample["rejected"].split()) + # If the sample includes a video, the length is positive; otherwise, it is negative + cur_len = cur_len if ("video" in sample or "image" in sample) else -cur_len + length_list.append(cur_len) + return length_list + + def process_image(self, image_file): + image_folder = self.data_args.image_folder + processor = self.data_args.image_processor + # print(f"\n\nInspecting the image path, folder = {image_folder}, image={image_file}\n\n") + try: + image = Image.open(os.path.join(image_folder, image_file)).convert("RGB") + except Exception as exn: + print(f"Failed to open image {image_file}. Exception:", exn) + raise exn + + image_size = image.size + if self.data_args.image_aspect_ratio == "highres": + image = process_highres_image(image, self.data_args.image_processor, self.data_args.image_grid_pinpoints) + elif self.data_args.image_aspect_ratio == "anyres" or "anyres" in self.data_args.image_aspect_ratio: + image = process_anyres_image(image, self.data_args.image_processor, self.data_args.image_grid_pinpoints) + elif self.data_args.image_aspect_ratio == "crop_split": + image = process_highres_image_crop_split(image, self.data_args) + elif self.data_args.image_aspect_ratio == "pad": + + def expand2square(pil_img, background_color): + width, height = pil_img.size + if width == height: + return pil_img + elif width > height: + result = Image.new(pil_img.mode, (width, width), background_color) + result.paste(pil_img, (0, (width - height) // 2)) + return result + else: + result = Image.new(pil_img.mode, (height, height), background_color) + result.paste(pil_img, ((height - width) // 2, 0)) + return result + + image = expand2square(image, tuple(int(x * 255) for x in processor.image_mean)) + image = processor.preprocess(image, return_tensors="pt")["pixel_values"][0] + else: + image = processor.preprocess(image, return_tensors="pt")["pixel_values"][0] + return image, image_size, "image" + + def __getitem__(self, i) -> Dict[str, torch.Tensor]: + # TODO: define number of retries somewhere else + num_base_retries = 3 + num_final_retries = 300 + + # try the current sample first + for attempt_idx in range(num_base_retries): + try: + sample = self._get_item(i) + return sample + except Exception as e: + # sleep 1s in case it is a cloud disk issue + print(f"[Try #{attempt_idx}] Failed to fetch sample {i}. Exception:", e) + time.sleep(1) + + # try other samples, in case it is file corruption issue + for attempt_idx in range(num_base_retries): + try: + next_index = min(i + 1, len(self.list_data_dict) - 1) + # sample_idx = random.choice(range(len(self))) + sample = self._get_item(next_index) + return sample + except Exception as e: + # no need to sleep + print(f"[Try other #{attempt_idx}] Failed to fetch sample {next_index}. Exception:", e) + pass + + # still fail, most likely to be path issue or cloud disk issue, retry the same sample for longer + # for attempt_idx in range(num_final_retries): + # try: + # sample = self._get_item(i) + # return sample + # except Exception as e: + # # sleep 1s in case it is a cloud disk issue + # print(f"[Final try #{attempt_idx}] Failed to fetch sample {i}. Exception:", e) + # time.sleep(1) + + # Finally raise exception on failing. + assert False, "Failed to fetch sample." + + def _get_item(self, i) -> Dict[str, torch.Tensor]: + sources = self.list_data_dict[i] + if isinstance(i, int): + sources = [sources] + assert len(sources) == 1, "Don't know why it is wrapped to a list" # FIXME + + suffix = None + if "image" in sources[0]: + image_file = self.list_data_dict[i]["image"] + if type(image_file) is list: + image = [self.process_image(f) for f in image_file] + else: + image = [self.process_image(image_file)] + # sources = preprocess_multimodal(copy.deepcopy([e["conversations"] for e in sources]), self.data_args) + + elif "video" in sources[0]: # FIXME: This logic should be largely improved by Yuanhan. It's too messy now. + video_file = self.list_data_dict[i]["video"] + video_folder = self.data_args.video_folder + video_file = os.path.join(video_folder, video_file) + suffix = video_file.split(".")[-1] + if not os.path.exists(video_file): + print("File {} not exist!".format(video_file)) + + if suffix == "pkl": + video_info = pickle.load(open(video_file, "rb")) + image = torch.from_numpy(video_info["feats"][:, 1:]) + input_prompt = video_info["inputs"].replace("...", "") + # replace the default image token with multiple tokens + input_prompt = input_prompt.replace(DEFAULT_IMAGE_TOKEN, DEFAULT_IMAGE_TOKEN * self.data_args.video_token) + sources, query_prompt = preprocess_multimodal_movie(copy.deepcopy([e["conversations"] for e in sources]), self.data_args, input_prompt) + else: # using videoreader + if "shareVideoGPTV" not in video_file and "liangke" not in video_file: + vr = VideoReader(video_file, ctx=cpu(0)) + total_frame_num = len(vr) + avg_fps = round(vr.get_avg_fps() / self.data_args.video_fps) + frame_idx = [i for i in range(0, total_frame_num, avg_fps)] + if self.data_args.frames_upbound > 0: + if len(frame_idx) > self.data_args.frames_upbound: + uniform_sampled_frames = np.linspace(0, total_frame_num - 1, self.data_args.frames_upbound, dtype=int) + frame_idx = uniform_sampled_frames.tolist() + video = vr.get_batch(frame_idx).asnumpy() + video = np.array(video) + else: + if "liangke" in video_file: + video_file = self.list_data_dict[i]["video"] + 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))] + frame_files.sort() # Ensure the frames are sorted if they are named sequentially + + # TODO: Hard CODE: Determine the indices for uniformly sampling 10 frames + num_frames_to_sample = 10 + + total_frames = len(frame_files) + + sampled_indices = np.linspace(0, total_frames - 1, num_frames_to_sample, dtype=int) + + # Read and store the sampled frames + video = [] + for idx in sampled_indices: + frame_path = frame_files[idx] + try: + with Image.open(frame_path) as img: + frame = img.convert("RGB") + video.append(frame) + except IOError: + print(f"Failed to read frame at path: {frame_path}") + + processor = self.data_args.image_processor + image = processor.preprocess(video, return_tensors="pt")["pixel_values"] + image = [(image, video[0].size, "video")] + # sources = preprocess_multimodal(copy.deepcopy([e["conversations"] for e in sources]), self.data_args) + + else: + sources = copy.deepcopy([e["conversations"] for e in sources]) + + has_image = ("image" in self.list_data_dict[i]) or ("video" in self.list_data_dict[i]) + # data_dict = preprocess(sources, self.tokenizer, has_image=has_image) + data_dict = copy.deepcopy(self.list_data_dict[i]) # inplace modification following + + if "prompt" in data_dict: + prompt = data_dict["prompt"] + prompt = prompt.replace("", "").strip() + prompt = "\n" + prompt + data_dict["prompt"] = prompt + else: + prompt = None + + if suffix == "pkl": + prompt = [query_prompt] + + # image exist in the data + if "image" in self.list_data_dict[i]: + data_dict["image"] = image + elif "video" in self.list_data_dict[i]: + data_dict["image"] = image + elif self.data_args.is_multimodal: + # image does not exist in the data, but the model is multimodal + crop_size = self.data_args.image_processor.crop_size + data_dict["image"] = [ + (torch.zeros(1, 3, crop_size["height"], crop_size["width"]), (crop_size["width"], crop_size["height"]), "text"), + ] + # prompt exist in the data + data_dict["has_image"] = has_image + return data_dict + + +@dataclass +class DPODataCollator(DPODataCollatorWithPadding): + """Collate examples for DPO fine-tuning.""" + + # tokenizer: transformers.PreTrainedTokenizer + + def collate(self, batch): + # first, pad everything to the same length + # input_ids, labels = tuple([instance[key] for instance in instances] + # for key in ("input_ids", "labels")) + # input_ids = torch.nn.utils.rnn.pad_sequence( + # input_ids, + # batch_first=True, + # padding_value=self.tokenizer.pad_token_id) + # labels = torch.nn.utils.rnn.pad_sequence(labels, + # batch_first=True, + # padding_value=IGNORE_INDEX) + # input_ids = input_ids[:, :self.tokenizer.model_max_length] + # labels = labels[:, :self.tokenizer.model_max_length] + # batch = dict( + # input_ids=input_ids, + # labels=labels, + # attention_mask=input_ids.ne(self.tokenizer.pad_token_id), + # ) + padded_batch = {} + for k in batch[0].keys(): + if k.endswith("_input_ids") or k.endswith("_attention_mask") or k.endswith("_labels"): + # if "prompt" in k: + # to_pad = [torch.LongTensor(ex[k][::-1]) for ex in batch] + # else: + to_pad = [torch.LongTensor(ex[k]) for ex in batch] + if k.endswith("_input_ids"): + padding_value = self.tokenizer.pad_token_id + elif k.endswith("_labels"): + padding_value = self.label_pad_token_id + else: + continue + # elif k.endswith("_attention_mask"): + # padding_value = self.padding_value + # else: + # raise ValueError(f"Unexpected key in batch '{k}'") + + padded_batch[k] = torch.nn.utils.rnn.pad_sequence(to_pad, batch_first=True, padding_value=padding_value) + # for the prompt, flip back so padding is on left side + # if "prompt" in k: + # padded_batch[k] = padded_batch[k].flip(dims=[1]) + else: + padded_batch[k] = [ex[k] for ex in batch] + for k in ["chosen_input_ids", "rejected_input_ids"]: + attn_k = k.replace("input_ids", "attention_mask") + padded_batch[attn_k] = padded_batch[k].ne(self.tokenizer.pad_token_id) + return padded_batch + + def tokenize_batch_element(self, prompt: str, chosen: str, rejected: str, has_image: bool = True) -> Dict: + """Tokenize a single batch element. + + At this stage, we don't convert to PyTorch tensors yet; we just handle the truncation + in case the prompt + chosen or prompt + rejected responses is/are too long. First + we truncate the prompt; if we're still too long, we truncate the chosen/rejected. + + We also create the labels for the chosen/rejected responses, which are of length equal to + the sum of the length of the prompt and the chosen/rejected response, with + label_pad_token_id for the prompt tokens. + """ + # import pdb; pdb.set_trace() + batch = {} + + chosen_sources = make_conv(prompt, chosen) + rejected_sources = make_conv(prompt, rejected) + chosen_data_dict = preprocess([chosen_sources], self.tokenizer, has_image=has_image) + # chosen_data_dict['attention_mask'] = chosen_data_dict["input_ids"].ne(self.tokenizer.pad_token_id) + + rejected_data_dict = preprocess([rejected_sources], self.tokenizer, has_image=has_image) + # rejected_data_dict['attention_mask'] = rejected_data_dict["input_ids"].ne(self.tokenizer.pad_token_id) + + chosen_data_dict = {k: v[0] for k, v in chosen_data_dict.items()} + rejected_data_dict = {k: v[0] for k, v in rejected_data_dict.items()} + + for k, toks in { + "chosen": chosen_data_dict, + "rejected": rejected_data_dict, + }.items(): + for type_key, tokens in toks.items(): + if type_key == "token_type_ids": + continue + batch[f"{k}_{type_key}"] = tokens + return batch + + def __call__(self, features: List[Dict[str, Any]]) -> Dict[str, Any]: + + tokenized_batch = [] + Xs, keys = [], [] + for feature in features: + prompt = feature["prompt"] + chosen = feature["chosen"] + rejected = feature["rejected"] + has_image = feature["has_image"] + # Xs.append(feature[has_X]) + # keys.append(has_X) + + batch_element = self.tokenize_batch_element(prompt, chosen, rejected, has_image=has_image) + tokenized_batch.append(batch_element) + + # return collated batch + padded_batch = self.collate(tokenized_batch) + # import pdb;pdb.set_trace() + if "image" in features[0]: + # instances[1]['image'][0][0].shape + # torch.Size([5, 3, 224, 224]) + images = [instance["image"] for instance in features] + + padded_batch["image_sizes"] = [im[1] for im_list in images for im in im_list] + padded_batch["modalities"] = [im[2] for im_list in images for im in im_list] + images = [im[0] for im_list in images for im in im_list] + # import pdb;pdb.set_trace() + + padded_batch["images"] = images + # padded_batch["images"] =[padded_batch["modalities"], images] + + return padded_batch + + +def make_dpo_data_module(tokenizer: transformers.PreTrainedTokenizer, data_args) -> Dict: + """Make dataset and collator for supervised fine-tuning.""" + train_dataset = DPODataset(tokenizer=tokenizer, data_path=data_args.data_path, data_args=data_args) + return train_dataset + + +def get_model(model_args, training_args, bnb_model_from_pretrained_args): + assert training_args.attn_implementation + if training_args.attn_implementation == "sdpa" and torch.__version__ < "2.1.2": + raise ValueError("The 'sdpa' attention implementation requires torch version 2.1.2 or higher.") + + ######################### Overwrite config ######################### + customized_kwargs = dict() + customized_kwargs.update(bnb_model_from_pretrained_args) + overwrite_config = {} + cfg_pretrained = None + if "qwen" in model_args.model_name_or_path.lower(): + cfg_pretrained = LlavaQwenConfig.from_pretrained(model_args.model_name_or_path) + elif "mistral" in model_args.model_name_or_path.lower() or "zephyr" in model_args.model_name_or_path.lower(): + cfg_pretrained = LlavaMistralConfig.from_pretrained(model_args.model_name_or_path) + elif ( + "wizardlm-2" in model_args.model_name_or_path.lower() + or "vicuna" in model_args.model_name_or_path.lower() + or "llama" in model_args.model_name_or_path.lower() + or "yi" in model_args.model_name_or_path.lower() + or "nous-hermes" in model_args.model_name_or_path.lower() + and "wizard-2" in model_args.model_name_or_path.lower() + ): + cfg_pretrained = LlavaConfig.from_pretrained(model_args.model_name_or_path) + else: + cfg_pretrained = AutoConfig.from_pretrained(model_args.model_name_or_path) + + if model_args.rope_scaling_factor is not None and model_args.rope_scaling_type is not None and cfg_pretrained is not None: + overwrite_config["rope_scaling"] = { + "factor": model_args.rope_scaling_factor, + "type": model_args.rope_scaling_type, + } + if training_args.model_max_length is None: + training_args.model_max_length = cfg_pretrained.max_position_embeddings * model_args.rope_scaling_factor + overwrite_config["max_sequence_length"] = training_args.model_max_length + assert training_args.model_max_length == int(cfg_pretrained.max_position_embeddings * model_args.rope_scaling_factor), print( + 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}" + ) + # overwrite_config["max_sequence_length"] = model_args.max_sequence_length + # overwrite_config["tokenizer_model_max_length"] = model_args.tokenizer_model_max_length + + 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: + overwrite_config["mm_resampler_type"] = model_args.mm_resampler_type + overwrite_config["mm_spatial_pool_stride"] = model_args.mm_spatial_pool_stride + overwrite_config["mm_spatial_pool_out_channels"] = model_args.mm_spatial_pool_out_channels + overwrite_config["mm_spatial_pool_mode"] = model_args.mm_spatial_pool_mode + + if overwrite_config: + rank0_print(f"Overwriting config with {overwrite_config}") + for k, v in overwrite_config.items(): + setattr(cfg_pretrained, k, v) + + customized_kwargs["config"] = cfg_pretrained + + ######################### Finish Overwrite ########################### + + ref_model = None + if model_args.model_class_name is not None: + actual_model_class_name = f"{model_args.model_class_name}ForCausalLM" + model_class = getattr(transformers, actual_model_class_name) + rank0_print(f"Using model class {model_class} from {model_args.model_class_name}") + model = model_class.from_pretrained( + 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), + low_cpu_mem_usage=False, + **customized_kwargs, + ) + elif model_args.vision_tower is not None: + if "mixtral" in model_args.model_name_or_path.lower(): + model = LlavaMixtralForCausalLM.from_pretrained( + 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), + low_cpu_mem_usage=False, + **customized_kwargs, + ) + from transformers.models.mixtral.modeling_mixtral import MixtralSparseMoeBlock + + deepspeed.utils.set_z3_leaf_modules(model, [MixtralSparseMoeBlock]) + elif "mistral" in model_args.model_name_or_path.lower() or "zephyr" in model_args.model_name_or_path.lower(): + model = LlavaMistralForCausalLM.from_pretrained( + 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), + low_cpu_mem_usage=False, + **customized_kwargs, + ) + elif ( + "wizardlm-2" in model_args.model_name_or_path.lower() + or "vicuna" in model_args.model_name_or_path.lower() + or "llama" in model_args.model_name_or_path.lower() + or "yi" in model_args.model_name_or_path.lower() + or "nous-hermes" in model_args.model_name_or_path.lower() + and "wizard-2" in model_args.model_name_or_path.lower() + ): + model = LlavaLlamaForCausalLM.from_pretrained( + 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), + low_cpu_mem_usage=False, + **customized_kwargs, + ) + + if "zero3" in training_args.deepspeed: + rank0_print("#### Initialize reference model #####") + ref_model = LlavaLlamaForCausalLM.from_pretrained( + 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), + low_cpu_mem_usage=False, + **customized_kwargs, + ) + + elif "qwen" in model_args.model_name_or_path.lower() or "quyen" in model_args.model_name_or_path.lower(): + if "moe" in model_args.model_name_or_path.lower(): + model = LlavaQwenMoeForCausalLM.from_pretrained( + 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), + low_cpu_mem_usage=False, + **customized_kwargs, + ) + from transformers.models.qwen2_moe.modeling_qwen2_moe import Qwen2MoeSparseMoeBlock + + deepspeed.utils.set_z3_leaf_modules(model, [Qwen2MoeSparseMoeBlock]) + else: + model = LlavaQwenForCausalLM.from_pretrained( + 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), + low_cpu_mem_usage=False, + **customized_kwargs, + ) + + if "zero3" in training_args.deepspeed: + rank0_print("#### Initialize reference model #####") + ref_model = LlavaQwenForCausalLM.from_pretrained( + 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), + low_cpu_mem_usage=False, + **customized_kwargs, + ) + + elif "gemma" in model_args.model_name_or_path.lower(): + model = LlavaGemmaForCausalLM.from_pretrained( + 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), + low_cpu_mem_usage=False, + **customized_kwargs, + ) + else: + raise ValueError(f"Unknown model class {model_args}") + else: + model = transformers.LlamaForCausalLM.from_pretrained( + 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 + ) + return model, ref_model + + +def train(attn_implementation=None): + global local_rank + + parser = transformers.HfArgumentParser((ModelArguments, DataArguments, TrainingArguments)) + model_args, data_args, training_args = parser.parse_args_into_dataclasses() + + if training_args.verbose_logging: + rank0_print(f"Inspecting experiment hyperparameters:\n") + rank0_print(f"model_args = {vars(model_args)}\n\n") + rank0_print(f"data_args = {vars(data_args)}\n\n") + rank0_print(f"training_args = {vars(training_args)}\n\n") + # rank0_print(f"evaluation_args = {vars(evaluation_args)}\n\n") + + local_rank = training_args.local_rank + compute_dtype = torch.float16 if training_args.fp16 else (torch.bfloat16 if training_args.bf16 else torch.float32) + + bnb_model_from_pretrained_args = {} + if training_args.bits in [4, 8]: + from transformers import BitsAndBytesConfig + + bnb_model_from_pretrained_args.update( + dict( + device_map={"": training_args.device}, + load_in_4bit=training_args.bits == 4, + load_in_8bit=training_args.bits == 8, + quantization_config=BitsAndBytesConfig( + load_in_4bit=training_args.bits == 4, + load_in_8bit=training_args.bits == 8, + llm_int8_threshold=6.0, + llm_int8_has_fp16_weight=False, + bnb_4bit_compute_dtype=compute_dtype, + bnb_4bit_use_double_quant=training_args.double_quant, + bnb_4bit_quant_type=training_args.quant_type, # {'fp4', 'nf4'} + ), + ) + ) + + model, ref_model = get_model(model_args, training_args, bnb_model_from_pretrained_args) + model.config.use_cache = False + + if model_args.freeze_backbone: + model.model.requires_grad_(False) + + if training_args.bits in [4, 8]: + from peft import prepare_model_for_kbit_training + + model.config.torch_dtype = torch.float32 if training_args.fp16 else (torch.bfloat16 if training_args.bf16 else torch.float32) + model = prepare_model_for_kbit_training(model, use_gradient_checkpointing=training_args.gradient_checkpointing) + + if training_args.gradient_checkpointing: + if hasattr(model, "enable_input_require_grads"): + model.enable_input_require_grads() + if ref_model is not None: + ref_model.enable_input_require_grads() + else: + + def make_inputs_require_grad(module, input, output): + output.requires_grad_(True) + + model.get_input_embeddings().register_forward_hook(make_inputs_require_grad) + + if ref_model is not None: + ref_model.get_input_embeddings().register_forward_hook(make_inputs_require_grad) + + if training_args.lora_enable: + from peft import LoraConfig, get_peft_model + + lora_config = LoraConfig( + r=training_args.lora_r, + lora_alpha=training_args.lora_alpha, + target_modules=find_all_linear_names(model), + lora_dropout=training_args.lora_dropout, + bias=training_args.lora_bias, + task_type="CAUSAL_LM", + ) + if training_args.bits == 16: + if training_args.bf16: + model.to(torch.bfloat16) + if training_args.fp16: + model.to(torch.float16) + rank0_print("Adding LoRA adapters...") + model = get_peft_model(model, lora_config) + + if "mpt" in model_args.model_name_or_path: + 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") + 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(): + 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") + elif "qwen" in model_args.model_name_or_path.lower(): + 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") + else: # for all other models + 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", + use_fast=False, + ) + + rank0_print(f"Prompt version: {model_args.version}") + if model_args.version == "v0": + if tokenizer.pad_token is None: + smart_tokenizer_and_embedding_resize( + special_tokens_dict=dict(pad_token="[PAD]"), + tokenizer=tokenizer, + model=model, + ) + elif model_args.version == "v0.5": + tokenizer.pad_token = tokenizer.unk_token + else: + if tokenizer.unk_token is not None: + tokenizer.pad_token = tokenizer.unk_token + if model_args.version in conversation_lib.conv_templates: + conversation_lib.default_conversation = conversation_lib.conv_templates[model_args.version] + else: + conversation_lib.default_conversation = conversation_lib.conv_templates["vicuna_v1"] + + if model_args.vision_tower is not None: + model.get_model().initialize_vision_modules(model_args=model_args, fsdp=training_args.fsdp) + + vision_tower = model.get_vision_tower() + vision_tower.to(dtype=torch.bfloat16 if training_args.bf16 else torch.float16, device=training_args.device) + + data_args.image_processor = vision_tower.image_processor + data_args.is_multimodal = True + + model.config.image_aspect_ratio = data_args.image_aspect_ratio + if data_args.image_grid_pinpoints is not None: + # 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)] + if "x" in data_args.image_grid_pinpoints and "..." in data_args.image_grid_pinpoints: + vis_encoder_size = data_args.image_processor.size[0] + matches = re.findall(r"\((\d+)x(\d+)\)", data_args.image_grid_pinpoints) + range_start = tuple(map(int, matches[0])) + range_end = tuple(map(int, matches[-1])) + 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)] + grid_pinpoints = [[dim * vis_encoder_size for dim in pair] for pair in grid_pinpoints] + data_args.image_grid_pinpoints = grid_pinpoints + elif "x" in data_args.image_grid_pinpoints: + vis_encoder_size = data_args.image_processor.size[0] + assert vis_encoder_size in [224, 336, 384, 448, 512], "vis_encoder_size should be in [224, 336, 384, 448, 512]" + grid_pinpoints = data_args.image_grid_pinpoints.replace(" ", "").replace("x", ",")[1:-1].split("),(") + data_args.image_grid_pinpoints = [[int(x) * vis_encoder_size for x in item.split(",")] for item in grid_pinpoints] + else: + data_args.image_grid_pinpoints = ast.literal_eval(data_args.image_grid_pinpoints) # for backward compatibility + model.config.image_grid_pinpoints = data_args.image_grid_pinpoints + model.config.image_crop_resolution = data_args.image_crop_resolution + model.config.image_split_resolution = data_args.image_split_resolution + model.config.tokenizer_padding_side = tokenizer.padding_side + model.config.tokenizer_model_max_length = tokenizer.model_max_length + + ### Deciding train which part of the model + if model_args.mm_tunable_parts is None: # traditional way of deciding which part to train + model.config.tune_mm_mlp_adapter = training_args.tune_mm_mlp_adapter = model_args.tune_mm_mlp_adapter + model.config.tune_mm_vision_resampler = training_args.tune_mm_vision_resampler = model_args.tune_mm_vision_resampler + if model_args.tune_mm_mlp_adapter or model_args.tune_mm_vision_resampler: + model.requires_grad_(False) + # Restore LoRA trainability after global freeze + if training_args.lora_enable: + for name, param in model.named_parameters(): + if "lora_" in name: + param.requires_grad_(True) + rank0_print("Restored LoRA parameters to trainable after global freeze (legacy branch).") + if model_args.tune_mm_mlp_adapter: + for p in model.get_model().mm_projector.parameters(): + p.requires_grad = True + if model_args.tune_mm_vision_resampler: + for p in model.get_model().vision_resampler.parameters(): + p.requires_grad = True + + model.config.freeze_mm_mlp_adapter = training_args.freeze_mm_mlp_adapter + if training_args.freeze_mm_mlp_adapter: + for p in model.get_model().mm_projector.parameters(): + p.requires_grad = False + + model.config.freeze_mm_vision_resampler = training_args.freeze_mm_vision_resampler + if training_args.freeze_mm_vision_resampler: + for p in model.get_model().vision_resampler.parameters(): + p.requires_grad = False + + model.config.unfreeze_mm_vision_tower = model_args.unfreeze_mm_vision_tower + if model_args.unfreeze_mm_vision_tower: + vision_tower.requires_grad_(True) + else: + vision_tower.requires_grad_(False) + + else: + rank0_print(f"Using mm_tunable_parts: {model_args.mm_tunable_parts}") + model.config.mm_tunable_parts = training_args.mm_tunable_parts = model_args.mm_tunable_parts + # Set the entire model to not require gradients by default + model.requires_grad_(False) + vision_tower.requires_grad_(False) + model.get_model().mm_projector.requires_grad_(False) + model.get_model().vision_resampler.requires_grad_(False) + # Parse the mm_tunable_parts to decide which parts to unfreeze + tunable_parts = model_args.mm_tunable_parts.split(",") + if "mm_mlp_adapter" in tunable_parts: + for p in model.get_model().mm_projector.parameters(): + p.requires_grad = True + if "mm_vision_resampler" in tunable_parts: + for p in model.get_model().vision_resampler.parameters(): + p.requires_grad = True + if "mm_vision_tower" in tunable_parts: + for name, param in model.named_parameters(): + if "vision_tower" in name: + param.requires_grad_(True) + if "mm_language_model" in tunable_parts: + if training_args.lora_enable: + # LoRA mode: only unfreeze LoRA parameters, keep LLM backbone frozen + rank0_print("LoRA enabled: unfreezing only LoRA parameters for LLM.") + else: + # Full finetune mode: unfreeze entire LLM backbone + for name, param in model.named_parameters(): + if "vision_tower" not in name and "mm_projector" not in name and "vision_resampler" not in name: + param.requires_grad_(True) + + # Ensure LoRA parameters are always trainable when lora_enable is True, + # regardless of which mm_tunable_parts are specified. + # model.requires_grad_(False) above freezes everything including LoRA weights + # injected by PEFT, so we must explicitly restore them here. + if training_args.lora_enable: + lora_param_count = 0 + for name, param in model.named_parameters(): + if "lora_" in name: + param.requires_grad_(True) + lora_param_count += 1 + rank0_print(f"Restored {lora_param_count} LoRA parameter tensors to trainable.") + if "mm_language_model" not in tunable_parts: + rank0_print( + "WARNING: lora_enable is True but 'mm_language_model' is not in mm_tunable_parts. " + "LoRA parameters will still be trained. If you do not intend to train the language " + "model at all, consider setting --lora_enable False to avoid unnecessary overhead." + ) + + total_params = sum(p.ds_numel if hasattr(p, "ds_numel") else p.numel() for p in model.parameters()) + trainable_params = sum(p.ds_numel if hasattr(p, "ds_numel") else p.numel() for p in model.parameters() if p.requires_grad) + rank0_print(f"Total parameters: ~{total_params/1e6:.2f} MB)") + rank0_print(f"Trainable parameters: ~{trainable_params/1e6:.2f} MB)") + # Print per-group trainable parameter breakdown for verification + trainable_groups = {"lora": 0, "mm_projector": 0, "vision_resampler": 0, "vision_tower": 0, "llm_base": 0} + for name, p in model.named_parameters(): + if not p.requires_grad: + continue + n = p.ds_numel if hasattr(p, "ds_numel") else p.numel() + if "lora_" in name: + trainable_groups["lora"] += n + elif "mm_projector" in name: + trainable_groups["mm_projector"] += n + elif "vision_resampler" in name: + trainable_groups["vision_resampler"] += n + elif "vision_tower" in name: + trainable_groups["vision_tower"] += n + else: + trainable_groups["llm_base"] += n + rank0_print("Trainable parameter groups: " + ", ".join(f"{k}={v:,}" for k, v in trainable_groups.items())) + if training_args.bits in [4, 8]: + model.get_model().mm_projector.to(dtype=compute_dtype, device=training_args.device) + + model.config.mm_use_im_start_end = data_args.mm_use_im_start_end = model_args.mm_use_im_start_end + model.config.mm_projector_lr = training_args.mm_projector_lr + model.config.mm_vision_tower_lr = training_args.mm_vision_tower_lr + training_args.use_im_start_end = model_args.mm_use_im_start_end + model.config.mm_use_im_patch_token = model_args.mm_use_im_patch_token + model.initialize_vision_tokenizer(model_args, tokenizer=tokenizer) + + if ref_model is not None: + ref_model.get_model().initialize_vision_modules(model_args=model_args, fsdp=training_args.fsdp) + ref_vision_tower = ref_model.get_vision_tower() + ref_vision_tower.to(dtype=torch.bfloat16 if training_args.bf16 else torch.float16, device=training_args.device) + ref_model.config.image_aspect_ratio = data_args.image_aspect_ratio + ref_model.config.image_grid_pinpoints = data_args.image_grid_pinpoints + ref_model.config.image_crop_resolution = data_args.image_crop_resolution + ref_model.config.image_split_resolution = data_args.image_split_resolution + ref_model.config.tokenizer_padding_side = tokenizer.padding_side + ref_model.config.tokenizer_model_max_length = tokenizer.model_max_length + ref_model.config.mm_use_im_start_end = data_args.mm_use_im_start_end + ref_model.config.mm_use_im_patch_token = model_args.mm_use_im_patch_token + ref_model.initialize_vision_tokenizer(model_args, tokenizer=tokenizer) + parameter_names = [n for n, _ in ref_model.named_parameters()] + for param_name in parameter_names: + param = ref_model.get_parameter(param_name) + param.requires_grad = False + ref_model.eval() + + if training_args.bits in [4, 8]: + from peft.tuners.lora import LoraLayer + + for name, module in model.named_modules(): + if isinstance(module, LoraLayer): + if training_args.bf16: + module = module.to(torch.bfloat16) + if "norm" in name: + module = module.to(torch.float32) + if "lm_head" in name or "embed_tokens" in name: + if hasattr(module, "weight"): + if training_args.bf16 and module.weight.dtype == torch.float32: + module = module.to(torch.bfloat16) + + train_dataset = make_dpo_data_module(tokenizer=tokenizer, data_args=data_args) + data_collator = DPODataCollator( + tokenizer, + label_pad_token_id=IGNORE_INDEX, + pad_token_id=tokenizer.pad_token_id, + ) + + trainer = LLaVADPOTrainer( + model, + ref_model, + args=training_args, + dpo_alpha=training_args.dpo_alpha, + beta=training_args.beta, + gamma=training_args.gamma, + train_dataset=train_dataset, + eval_dataset=None, + data_collator=data_collator, + tokenizer=tokenizer, + max_length=training_args.model_max_length, + generate_during_eval=False, # training_args.generate_during_eval, + precompute_ref_log_probs=training_args.precompute_ref_log_probs, + ) + + if list(pathlib.Path(training_args.output_dir).glob("checkpoint-*")): + trainer.train(resume_from_checkpoint=True) + else: + trainer.train() + trainer.save_state() + + model.config.use_cache = True + + if training_args.lora_enable: + state_dict = get_peft_state_maybe_zero_3(model.named_parameters(), training_args.lora_bias) + non_lora_state_dict = get_peft_state_non_lora_maybe_zero_3(model.named_parameters()) + if training_args.local_rank == 0 or training_args.local_rank == -1: + if hasattr(model, "config"): + model.config.save_pretrained(training_args.output_dir) + if hasattr(model, "generation_config"): + model.generation_config.save_pretrained(training_args.output_dir) + model.save_pretrained(training_args.output_dir, state_dict=state_dict) + torch.save(non_lora_state_dict, os.path.join(training_args.output_dir, "non_lora_trainables.bin")) + else: + safe_save_model_for_hf_trainer(trainer=trainer, output_dir=training_args.output_dir) + + rank0_print(f"Model saved to {training_args.output_dir}") + + +if __name__ == "__main__": + train() diff --git "a/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/llava/train/train_mem.py" "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/llava/train/train_mem.py" new file mode 100644 index 0000000000000000000000000000000000000000..6135ca4134a25d22eb40d994499ba564b9673f34 --- /dev/null +++ "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/llava/train/train_mem.py" @@ -0,0 +1,4 @@ +from llava.train.train import train + +if __name__ == "__main__": + train() diff --git "a/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/llava/utils.py" "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/llava/utils.py" new file mode 100644 index 0000000000000000000000000000000000000000..1e004c33bc503d213df619dec948f39b4c13e53d --- /dev/null +++ "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/llava/utils.py" @@ -0,0 +1,198 @@ +import datetime +import logging +import logging.handlers +import os +import sys +import numpy as np + +import requests + +from llava.constants import LOGDIR + +server_error_msg = "**NETWORK ERROR DUE TO HIGH TRAFFIC. PLEASE REGENERATE OR REFRESH THIS PAGE.**" +moderation_msg = "I am sorry. Your input may violate our content moderation guidelines. Please avoid using harmful or offensive content." + +handler = None + +import torch.distributed as dist + +try: + import av + from decord import VideoReader, cpu +except ImportError: + print("Please install pyav to use video processing functions.") + +def process_video_with_decord(video_file, data_args): + vr = VideoReader(video_file, ctx=cpu(0), num_threads=1) + total_frame_num = len(vr) + video_time = total_frame_num / vr.get_avg_fps() + avg_fps = round(vr.get_avg_fps() / data_args.video_fps) + frame_idx = [i for i in range(0, total_frame_num, avg_fps)] + frame_time = [i/avg_fps for i in frame_idx] + + + if data_args.frames_upbound > 0: + if len(frame_idx) > data_args.frames_upbound or data_args.force_sample: + uniform_sampled_frames = np.linspace(0, total_frame_num - 1, data_args.frames_upbound, dtype=int) + frame_idx = uniform_sampled_frames.tolist() + frame_time = [i/vr.get_avg_fps() for i in frame_idx] + + video = vr.get_batch(frame_idx).asnumpy() + frame_time = ",".join([f"{i:.2f}s" for i in frame_time]) + + num_frames_to_sample = num_frames = len(frame_idx) + # https://github.com/dmlc/decord/issues/208 + vr.seek(0) + return video, video_time, frame_time, num_frames_to_sample + +def process_video_with_pyav(video_file, data_args): + container = av.open(video_file) + # !!! This is the only difference. Using auto threading + container.streams.video[0].thread_type = "AUTO" + + video_frames = [] + for packet in container.demux(): + if packet.stream.type == 'video': + for frame in packet.decode(): + video_frames.append(frame) + total_frame_num = len(video_frames) + video_time = video_frames[-1].time + avg_fps = round(total_frame_num / video_time / data_args.video_fps) + frame_idx = [i for i in range(0, total_frame_num, avg_fps)] + + if data_args.frames_upbound > 0: + if len(frame_idx) > data_args.frames_upbound: + uniform_sampled_frames = np.linspace(0, total_frame_num - 1, data_args.frames_upbound, dtype=int) + frame_idx = uniform_sampled_frames.tolist() + + + frames = [video_frames[i] for i in frame_idx] + return np.stack([x.to_ndarray(format="rgb24") for x in frames]) + + +def rank0_print(*args): + if dist.is_initialized(): + if dist.get_rank() == 0: + print(f"Rank {dist.get_rank()}: ", *args) + else: + print(*args) + + +def rank_print(*args): + if dist.is_initialized(): + print(f"Rank {dist.get_rank()}: ", *args) + else: + print(*args) + +def build_logger(logger_name, logger_filename): + global handler + + formatter = logging.Formatter( + fmt="%(asctime)s | %(levelname)s | %(name)s | %(message)s", + datefmt="%Y-%m-%d %H:%M:%S", + ) + + # Set the format of root handlers + if not logging.getLogger().handlers: + logging.basicConfig(level=logging.INFO) + logging.getLogger().handlers[0].setFormatter(formatter) + + # Redirect stdout and stderr to loggers + stdout_logger = logging.getLogger("stdout") + stdout_logger.setLevel(logging.INFO) + sl = StreamToLogger(stdout_logger, logging.INFO) + sys.stdout = sl + + stderr_logger = logging.getLogger("stderr") + stderr_logger.setLevel(logging.ERROR) + sl = StreamToLogger(stderr_logger, logging.ERROR) + sys.stderr = sl + + # Get logger + logger = logging.getLogger(logger_name) + logger.setLevel(logging.INFO) + + # Add a file handler for all loggers + if handler is None: + os.makedirs(LOGDIR, exist_ok=True) + filename = os.path.join(LOGDIR, logger_filename) + handler = logging.handlers.TimedRotatingFileHandler(filename, when="D", utc=True) + handler.setFormatter(formatter) + + for name, item in logging.root.manager.loggerDict.items(): + if isinstance(item, logging.Logger): + item.addHandler(handler) + + return logger + + +class StreamToLogger(object): + """ + Fake file-like stream object that redirects writes to a logger instance. + """ + + def __init__(self, logger, log_level=logging.INFO): + self.terminal = sys.stdout + self.logger = logger + self.log_level = log_level + self.linebuf = "" + + def __getattr__(self, attr): + return getattr(self.terminal, attr) + + def write(self, buf): + temp_linebuf = self.linebuf + buf + self.linebuf = "" + for line in temp_linebuf.splitlines(True): + # From the io.TextIOWrapper docs: + # On output, if newline is None, any '\n' characters written + # are translated to the system default line separator. + # By default sys.stdout.write() expects '\n' newlines and then + # translates them so this is still cross platform. + if line[-1] == "\n": + self.logger.log(self.log_level, line.rstrip()) + else: + self.linebuf += line + + def flush(self): + if self.linebuf != "": + self.logger.log(self.log_level, self.linebuf.rstrip()) + self.linebuf = "" + + +def disable_torch_init(): + """ + Disable the redundant torch default initialization to accelerate model creation. + """ + import torch + + setattr(torch.nn.Linear, "reset_parameters", lambda self: None) + setattr(torch.nn.LayerNorm, "reset_parameters", lambda self: None) + + +def violates_moderation(text): + """ + Check whether the text violates OpenAI moderation API. + """ + url = "https://api.openai.com/v1/moderations" + headers = {"Content-Type": "application/json", "Authorization": "Bearer " + os.environ["OPENAI_API_KEY"]} + text = text.replace("\n", "") + data = "{" + '"input": ' + f'"{text}"' + "}" + data = data.encode("utf-8") + try: + ret = requests.post(url, headers=headers, data=data, timeout=5) + flagged = ret.json()["results"][0]["flagged"] + except requests.exceptions.RequestException as e: + print(f"######################### Moderation Error: {e} #########################") + flagged = False + except KeyError as e: + print(f"######################### Moderation Error: {e} #########################") + flagged = False + + return flagged + + +def pretty_print_semaphore(semaphore): + if semaphore is None: + return "None" + return f"Semaphore(value={semaphore._value}, locked={semaphore.locked()})" diff --git "a/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/archived/convert_gqa_for_eval.py" "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/archived/convert_gqa_for_eval.py" new file mode 100644 index 0000000000000000000000000000000000000000..2842975e7592162d352ee2263f2e1b56302ea4e2 --- /dev/null +++ "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/archived/convert_gqa_for_eval.py" @@ -0,0 +1,18 @@ +import os +import json +import argparse + +parser = argparse.ArgumentParser() +parser.add_argument("--src", type=str) +parser.add_argument("--dst", type=str) +args = parser.parse_args() + +all_answers = [] +for line_idx, line in enumerate(open(args.src)): + res = json.loads(line) + question_id = res["question_id"] + text = res["text"].rstrip(".").lower() + all_answers.append({"questionId": question_id, "prediction": text}) + +with open(args.dst, "w") as f: + json.dump(all_answers, f) diff --git "a/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/archived/convert_mmvet_for_eval.py" "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/archived/convert_mmvet_for_eval.py" new file mode 100644 index 0000000000000000000000000000000000000000..80ff3152042b5ea805a379436856bfef6ee030b4 --- /dev/null +++ "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/archived/convert_mmvet_for_eval.py" @@ -0,0 +1,18 @@ +import os +import json +import argparse + +parser = argparse.ArgumentParser() +parser.add_argument("--src", type=str) +parser.add_argument("--dst", type=str) +args = parser.parse_args() + +cur_result = {} + +for line in open(args.src): + data = json.loads(line) + qid = data["question_id"] + cur_result[f"v1_{qid}"] = data["text"] + +with open(args.dst, "w") as f: + json.dump(cur_result, f, indent=2) diff --git "a/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/archived/convert_sqa_to_llava.py" "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/archived/convert_sqa_to_llava.py" new file mode 100644 index 0000000000000000000000000000000000000000..b0d242234b9777c64d6122c713be3c9d6d38c7a7 --- /dev/null +++ "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/archived/convert_sqa_to_llava.py" @@ -0,0 +1,88 @@ +import json +import os +import fire +import re +from convert_sqa_to_llava_base_prompt import build_prompt_chatbot + + +def convert_to_llava(base_dir, split, prompt_format="QCM-LEA"): + split_indices = json.load(open(os.path.join(base_dir, "pid_splits.json")))[split] + problems = json.load(open(os.path.join(base_dir, "problems.json"))) + + split_problems = build_prompt_chatbot(problems, split_indices, prompt_format, use_caption=False, is_test=False) + + target_format = [] + for prob_id, (input, output) in split_problems.items(): + if input.startswith("Question: "): + input = input.replace("Question: ", "") + if output.startswith("Answer: "): + output = output.replace("Answer: ", "") + + raw_prob_data = problems[prob_id] + if raw_prob_data["image"] is None: + target_format.append( + { + "id": prob_id, + "conversations": [ + {"from": "human", "value": f"{input}"}, + {"from": "gpt", "value": f"{output}"}, + ], + } + ) + + else: + target_format.append( + { + "id": prob_id, + "image": os.path.join(prob_id, raw_prob_data["image"]), + "conversations": [ + {"from": "human", "value": f"{input}\n"}, + {"from": "gpt", "value": f"{output}"}, + ], + } + ) + + print(f"Number of samples: {len(target_format)}") + + with open(os.path.join(base_dir, f"llava_{split}_{prompt_format}.json"), "w") as f: + json.dump(target_format, f, indent=2) + + +def convert_to_jsonl(base_dir, split, prompt_format="QCM-LEPA"): + split_indices = json.load(open(os.path.join(base_dir, "pid_splits.json")))[split] + problems = json.load(open(os.path.join(base_dir, "problems.json"))) + + split_problems = build_prompt_chatbot(problems, split_indices, prompt_format, use_caption=False, is_test=False) + + writer = open(os.path.join(base_dir, f"scienceqa_{split}_{prompt_format}.jsonl"), "w") + for prob_id, (input, output) in split_problems.items(): + if input.startswith("Question: "): + input = input.replace("Question: ", "") + if output.startswith("Answer: "): + output = output.replace("Answer: ", "") + + raw_prob_data = problems[prob_id] + if raw_prob_data["image"] is None: + data = { + "id": prob_id, + "instruction": f"{input}", + "output": f"{output}", + } + + else: + data = { + "id": prob_id, + "image": os.path.join(prob_id, raw_prob_data["image"]), + "instruction": f"{input}\n", + "output": f"{output}", + } + writer.write(json.dumps(data) + "\n") + writer.close() + + +def main(task, **kwargs): + globals()[task](**kwargs) + + +if __name__ == "__main__": + fire.Fire(main) diff --git "a/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/archived/convert_sqa_to_llava_base_prompt.py" "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/archived/convert_sqa_to_llava_base_prompt.py" new file mode 100644 index 0000000000000000000000000000000000000000..9a457dc4b9e6288d30c1cbd9df7d89b7e1474e75 --- /dev/null +++ "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/archived/convert_sqa_to_llava_base_prompt.py" @@ -0,0 +1,298 @@ +def get_question_text(problem): + question = problem["question"] + return question + + +def get_context_text(problem, use_caption): + txt_context = problem["hint"] + img_context = problem["caption"] if use_caption else "" + context = " ".join([txt_context, img_context]).strip() + if context == "": + context = "N/A" + return context + + +def get_choice_text(probelm, options): + choices = probelm["choices"] + choice_list = [] + for i, c in enumerate(choices): + choice_list.append("({}) {}".format(options[i], c)) + choice_txt = " ".join(choice_list) + # print(choice_txt) + return choice_txt + + +def get_answer(problem, options): + return options[problem["answer"]] + + +def get_lecture_text(problem): + # \\n: GPT-3 can generate the lecture with more tokens. + lecture = problem["lecture"].replace("\n", "\\n") + return lecture + + +def get_solution_text(problem): + # \\n: GPT-3 can generate the solution with more tokens + solution = problem["solution"].replace("\n", "\\n") + return solution + + +def create_one_example_chatbot(format, question, context, choice, answer, lecture, solution, test_example=True): + + input_format, output_format = format.split("-") + + ## Inputs + if input_format == "CQM": + input = f"Context: {context}\nQuestion: {question}\nOptions: {choice}\n" + elif input_format == "QCM": + input = f"Question: {question}\nContext: {context}\nOptions: {choice}\n" + # upper bound experiment + elif input_format == "QCML": + input = f"Question: {question}\nContext: {context}\nOptions: {choice}\nBECAUSE: {lecture}\n" + elif input_format == "QCME": + input = f"Question: {question}\nContext: {context}\nOptions: {choice}\nBECAUSE: {solution}\n" + elif input_format == "QCMLE": + input = f"Question: {question}\nContext: {context}\nOptions: {choice}\nBECAUSE: {lecture} {solution}\n" + + elif input_format == "QCLM": + input = f"Question: {question}\nContext: {context}\nBECAUSE: {lecture}\nOptions: {choice}\n" + elif input_format == "QCEM": + input = f"Question: {question}\nContext: {context}\nBECAUSE: {solution}\nOptions: {choice}\n" + elif input_format == "QCLEM": + input = f"Question: {question}\nContext: {context}\nBECAUSE: {lecture} {solution}\nOptions: {choice}\n" + + # Outputs + if test_example: + output = "Answer:" + elif output_format == "A": + output = f"Answer: The answer is {answer}." + + elif output_format == "AL": + output = f"Answer: The answer is {answer}. BECAUSE: {solution}" + elif output_format == "AE": + output = f"Answer: The answer is {answer}. BECAUSE: {lecture}" + elif output_format == "ALE": + output = f"Answer: The answer is {answer}. BECAUSE: {lecture} {solution}" + elif output_format == "AEL": + output = f"Answer: The answer is {answer}. BECAUSE: {solution} {lecture}" + + elif output_format == "LA": + output = f"Answer: {lecture} The answer is {answer}." + elif output_format == "EA": + output = f"Answer: {solution} The answer is {answer}." + elif output_format == "LEA": + output = f"Answer: {lecture} {solution} The answer is {answer}." + elif output_format == "ELA": + output = f"Answer: {solution} {lecture} The answer is {answer}." + elif output_format == "LEPA": + output = "" + if len(lecture.strip()) > 0: + output += f"LECTURE: {lecture}\n" + if len(solution.strip()) > 0: + output += f"SOLUTION: {solution}\n" + output += "###\n" + output += f"ANSWER: {answer}." + + input = input.replace(" ", " ").strip() + output = output.replace(" ", " ").strip() + if input.endswith("BECAUSE:"): + input = input.replace("BECAUSE:", "").strip() + if output.endswith("BECAUSE:"): + output = output.replace("BECAUSE:", "").strip() + return input, output + + +def create_one_example(format, question, context, choice, answer, lecture, solution, test_example=True): + + input_format, output_format = format.split("-") + + ## Inputs + if input_format == "CQM": + input = f"Context: {context}\nQuestion: {question}\nOptions: {choice}\n" + elif input_format == "QCM": + input = f"Question: {question}\nContext: {context}\nOptions: {choice}\n" + # upper bound experiment + elif input_format == "QCML": + input = f"Question: {question}\nContext: {context}\nOptions: {choice}\nBECAUSE: {lecture}\n" + elif input_format == "QCME": + input = f"Question: {question}\nContext: {context}\nOptions: {choice}\nBECAUSE: {solution}\n" + elif input_format == "QCMLE": + input = f"Question: {question}\nContext: {context}\nOptions: {choice}\nBECAUSE: {lecture} {solution}\n" + + elif input_format == "QCLM": + input = f"Question: {question}\nContext: {context}\nBECAUSE: {lecture}\nOptions: {choice}\n" + elif input_format == "QCEM": + input = f"Question: {question}\nContext: {context}\nBECAUSE: {solution}\nOptions: {choice}\n" + elif input_format == "QCLEM": + input = f"Question: {question}\nContext: {context}\nBECAUSE: {lecture} {solution}\nOptions: {choice}\n" + + # Outputs + if test_example: + output = "Answer:" + elif output_format == "A": + output = f"Answer: The answer is {answer}." + + elif output_format == "AL": + output = f"Answer: The answer is {answer}. BECAUSE: {solution}" + elif output_format == "AE": + output = f"Answer: The answer is {answer}. BECAUSE: {lecture}" + elif output_format == "ALE": + output = f"Answer: The answer is {answer}. BECAUSE: {lecture} {solution}" + elif output_format == "AEL": + output = f"Answer: The answer is {answer}. BECAUSE: {solution} {lecture}" + + elif output_format == "LA": + output = f"Answer: {lecture} The answer is {answer}." + elif output_format == "EA": + output = f"Answer: {solution} The answer is {answer}." + elif output_format == "LEA": + output = f"Answer: {lecture} {solution} The answer is {answer}." + elif output_format == "ELA": + output = f"Answer: {solution} {lecture} The answer is {answer}." + + text = input + output + text = text.replace(" ", " ").strip() + if text.endswith("BECAUSE:"): + text = text.replace("BECAUSE:", "").strip() + return text + + +def create_one_example_gpt4(format, question, context, choice, answer, lecture, solution, test_example=True): + + input_format, output_format = format.split("-") + + ## Inputs + if input_format == "CQM": + input = f"Context: {context}\nQuestion: {question}\nOptions: {choice}\n" + elif input_format == "QCM": + input = f"Question: {question}\nContext: {context}\nOptions: {choice}\n" + # upper bound experiment + elif input_format == "QCML": + input = f"Question: {question}\nContext: {context}\nOptions: {choice}\nBECAUSE: {lecture}\n" + elif input_format == "QCME": + input = f"Question: {question}\nContext: {context}\nOptions: {choice}\nBECAUSE: {solution}\n" + elif input_format == "QCMLE": + input = f"Question: {question}\nContext: {context}\nOptions: {choice}\nBECAUSE: {lecture} {solution}\n" + + elif input_format == "QCLM": + input = f"Question: {question}\nContext: {context}\nBECAUSE: {lecture}\nOptions: {choice}\n" + elif input_format == "QCEM": + input = f"Question: {question}\nContext: {context}\nBECAUSE: {solution}\nOptions: {choice}\n" + elif input_format == "QCLEM": + input = f"Question: {question}\nContext: {context}\nBECAUSE: {lecture} {solution}\nOptions: {choice}\n" + + # Outputs + if test_example: + output = "Answer:" + elif output_format == "A": + output = f"Answer: The answer is {answer}." + + elif output_format == "AL": + output = f"Answer: The answer is {answer}. BECAUSE: {solution}" + elif output_format == "AE": + output = f"Answer: The answer is {answer}. BECAUSE: {lecture}" + elif output_format == "ALE": + output = f"Answer: The answer is {answer}. BECAUSE: {lecture} {solution}" + elif output_format == "AEL": + output = f"Answer: The answer is {answer}. BECAUSE: {solution} {lecture}" + + elif output_format == "LA": + output = f"Answer: {lecture} The answer is {answer}." + elif output_format == "EA": + output = f"Answer: {solution} The answer is {answer}." + elif output_format == "LEA": + output = f"Answer: {lecture} {solution} The answer is {answer}." + elif output_format == "ELA": + output = f"Answer: {solution} {lecture} The answer is {answer}." + + input = input.replace(" ", " ").strip() + output = output.replace(" ", " ").strip() + if output.endswith("BECAUSE:"): + output = output.replace("BECAUSE:", "").strip() + + user_prompt = {"role": "user", "content": f"Can you explain {input}?"} + assistant_prompt = {"role": "assistant", "content": f"{output}"} + + return user_prompt, assistant_prompt + + +def build_prompt_chatbot(problems, shot_qids, prompt_format, use_caption=False, options=["A", "B", "C", "D", "E"], is_test=False): + examples = {} + + for qid in shot_qids: + question = get_question_text(problems[qid]) + context = get_context_text(problems[qid], use_caption) + choice = get_choice_text(problems[qid], options) + answer = get_answer(problems[qid], options) + lecture = get_lecture_text(problems[qid]).replace("\\n", "\n") + solution = get_solution_text(problems[qid]).replace("\\n", "\n") + + train_example = create_one_example_chatbot(prompt_format, question, context, choice, answer, lecture, solution, test_example=is_test) + examples[qid] = train_example + return examples + + +def build_prompt(problems, shot_qids, test_qid, args): + + examples = [] + + # n-shot training examples + for qid in shot_qids: + question = get_question_text(problems[qid]) + context = get_context_text(problems[qid], args.use_caption) + choice = get_choice_text(problems[qid], args.options) + answer = get_answer(problems[qid], args.options) + lecture = get_lecture_text(problems[qid]) + solution = get_solution_text(problems[qid]) + + train_example = create_one_example(args.prompt_format, question, context, choice, answer, lecture, solution, test_example=False) + examples.append(train_example) + + # test example + question = get_question_text(problems[test_qid]) + context = get_context_text(problems[test_qid], args.use_caption) + choice = get_choice_text(problems[test_qid], args.options) + answer = get_answer(problems[test_qid], args.options) + lecture = get_lecture_text(problems[test_qid]) + solution = get_solution_text(problems[test_qid]) + + test_example = create_one_example(args.prompt_format, question, context, choice, answer, lecture, solution, test_example=True) + examples.append(test_example) + + # create the prompt input + prompt_input = "\n\n".join(examples) + + return prompt_input + + +def build_prompt_gpt4(problems, shot_qids, test_qid, args): + + prompt_array = [{"role": "system", "content": "You are a helpful assistant."}] + + # n-shot training examples + for qid in shot_qids: + question = get_question_text(problems[qid]) + context = get_context_text(problems[qid], args.use_caption) + choice = get_choice_text(problems[qid], args.options) + answer = get_answer(problems[qid], args.options) + lecture = get_lecture_text(problems[qid]) + solution = get_solution_text(problems[qid]) + + user_prompt, assistant_prompt = create_one_example_gpt4(args.prompt_format, question, context, choice, answer, lecture, solution, test_example=False) + prompt_array.append(user_prompt) + prompt_array.append(assistant_prompt) + + # test example + question = get_question_text(problems[test_qid]) + context = get_context_text(problems[test_qid], args.use_caption) + choice = get_choice_text(problems[test_qid], args.options) + answer = get_answer(problems[test_qid], args.options) + lecture = get_lecture_text(problems[test_qid]) + solution = get_solution_text(problems[test_qid]) + + user_prompt, assistant_prompt = create_one_example_gpt4(args.prompt_format, question, context, choice, answer, lecture, solution, test_example=True) + prompt_array.append(user_prompt) + prompt_array.append(assistant_prompt) + + return prompt_array diff --git "a/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/archived/convert_vizwiz_for_submission.py" "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/archived/convert_vizwiz_for_submission.py" new file mode 100644 index 0000000000000000000000000000000000000000..80b8253981831333b713a9eb433ddf0f626535b5 --- /dev/null +++ "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/archived/convert_vizwiz_for_submission.py" @@ -0,0 +1,45 @@ +import os +import argparse +import json + +from llava.eval.m4c_evaluator import EvalAIAnswerProcessor + + +def parse_args(): + parser = argparse.ArgumentParser() + parser.add_argument("--annotation-file", type=str, required=True) + parser.add_argument("--result-file", type=str, required=True) + parser.add_argument("--result-upload-file", type=str, required=True) + return parser.parse_args() + + +if __name__ == "__main__": + + args = parse_args() + + os.makedirs(os.path.dirname(args.result_upload_file), exist_ok=True) + + results = [] + error_line = 0 + for line_idx, line in enumerate(open(args.result_file)): + try: + results.append(json.loads(line)) + except: + error_line += 1 + results = {x["question_id"]: x["text"] for x in results} + test_split = [json.loads(line) for line in open(args.annotation_file)] + split_ids = set([x["question_id"] for x in test_split]) + + print(f"total results: {len(results)}, total split: {len(test_split)}, error_line: {error_line}") + + all_answers = [] + + answer_processor = EvalAIAnswerProcessor() + + for x in test_split: + # import pdb; pdb.set_trace() + assert x["question_id"] in results, print(x) + all_answers.append({"image": x["image"], "answer": answer_processor(results[x["question_id"]])}) + + with open(args.result_upload_file, "w") as f: + json.dump(all_answers, f) diff --git "a/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/archived/convert_vqav2_for_submission.py" "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/archived/convert_vqav2_for_submission.py" new file mode 100644 index 0000000000000000000000000000000000000000..f0a8057954570c1e87463e01bf08dfce0f720ab7 --- /dev/null +++ "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/archived/convert_vqav2_for_submission.py" @@ -0,0 +1,50 @@ +import os +import argparse +import json + +from llava.eval.m4c_evaluator import EvalAIAnswerProcessor + + +def parse_args(): + parser = argparse.ArgumentParser() + parser.add_argument("--dir", type=str, default="./playground/data/eval/vqav2") + parser.add_argument("--ckpt", type=str, required=True) + parser.add_argument("--split", type=str, required=True) + return parser.parse_args() + + +if __name__ == "__main__": + + args = parse_args() + + src = os.path.join(args.dir, "answers", args.split, args.ckpt, "merge.jsonl") + test_split = os.path.join(args.dir, "llava_vqav2_mscoco_test2015.jsonl") + dst = os.path.join(args.dir, "answers_upload", args.split, f"{args.ckpt}.json") + os.makedirs(os.path.dirname(dst), exist_ok=True) + + results = [] + error_line = 0 + for line_idx, line in enumerate(open(src)): + try: + results.append(json.loads(line)) + except: + error_line += 1 + + results = {x["question_id"]: x["text"] for x in results} + test_split = [json.loads(line) for line in open(test_split)] + split_ids = set([x["question_id"] for x in test_split]) + + print(f"total results: {len(results)}, total split: {len(test_split)}, error_line: {error_line}") + + all_answers = [] + + answer_processor = EvalAIAnswerProcessor() + + for x in test_split: + if x["question_id"] not in results: + all_answers.append({"question_id": x["question_id"], "answer": ""}) + else: + all_answers.append({"question_id": x["question_id"], "answer": answer_processor(results[x["question_id"]])}) + + with open(dst, "w") as f: + json.dump(all_answers, open(dst, "w")) diff --git "a/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/archived/data_info.py" "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/archived/data_info.py" new file mode 100644 index 0000000000000000000000000000000000000000..d4aa7a5ba394c4615e705a233fa6a714fa1cf3f1 --- /dev/null +++ "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/archived/data_info.py" @@ -0,0 +1,124 @@ +import json +import os +from PIL import Image +from tqdm import tqdm +import matplotlib.pyplot as plt +import numpy as np + + +def load_data(json_path): + with open(json_path, "r") as f: + return json.load(f) + + +def filter_data(data): + # filtered_data = [item for item in data if "image" in item and "text" in item["image"]] + filtered_data = [item for item in data if "image" in item] + return filtered_data + + +from multiprocessing import Pool +import functools + + +def calculate_image_dimension(item, images_folder): + image_path = os.path.join(images_folder, item["image"]) + try: + with Image.open(image_path) as img: + width, height = img.size + return width, height + except Exception as e: + print(f"Error opening {image_path}: {e}") + return None, None + + +def calculate_image_dimensions_multiprocess(filtered_data, images_folder, num_processes=256): + with Pool(num_processes) as p: + dimensions = list(tqdm(p.imap(functools.partial(calculate_image_dimension, images_folder=images_folder), filtered_data), total=len(filtered_data), desc="Calculating image dimensions")) + widths, heights = zip(*[dim for dim in dimensions if dim[0] is not None]) + return list(widths), list(heights) + + +def tokenize(text): + return text.split() + + +def calculate_tokenized_lengths(data): + lengths = [] + for item in tqdm(data, desc="Tokenizing conversations"): + for conversation in item["conversations"]: + tokenized_value = tokenize(conversation["value"]) + lengths.append(len(tokenized_value)) + return lengths + + +import argparse + + +def main(): + parser = argparse.ArgumentParser(description="Process data for LLaVA_Next project.") + parser.add_argument("--json_path", type=str, help="Path to the JSON file containing data.") + parser.add_argument("--images_folder", type=str, default="/mnt/bn/vl-research/data/llava_data", help="Path to the folder containing images.") + args = parser.parse_args() + + llava_instruct_name = args.json_path.split("/")[-1].replace(".json", "") + json_path = args.json_path + llava_instruct_name = os.path.basename(json_path).replace(".json", "") + images_folder = args.images_folder + + data = load_data(json_path) + filtered_data = filter_data(data) + + if len(filtered_data) != 0: + print(f"Total data items: {len(data)}, Filtered data items: {len(filtered_data)}") + widths, heights = calculate_image_dimensions_multiprocess(filtered_data, images_folder) + max_width = max(widths) + max_height = max(heights) + print(f"Max width: {max_width}, Max height: {max_height}") + + tokenized_lengths = calculate_tokenized_lengths(data) + + fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(24, 12)) + + if len(filtered_data) != 0: + # Plot 2D histogram + if min(widths) == max(widths): + widths_bins = [min(widths), max(widths) + 1] + else: + widths_bins = np.arange(min(widths), max(widths) + 100, 100) + + if min(heights) == max(heights): + heights_bins = [min(heights), max(heights) + 1] + else: + heights_bins = np.arange(min(heights), max(heights) + 100, 100) + + h, xedges, yedges, image = ax1.hist2d(widths, heights, bins=[widths_bins, heights_bins], cmap=plt.cm.jet, density=True) + fig.colorbar(image, ax=ax1) + ax1.set_xlabel("Width") + ax1.set_ylabel("Height") + ax1.set_title(f"dist_{llava_instruct_name}_2d_w_h\nMax width: {max(widths)}, Max height: {max(heights)}", fontsize=10) + + # Plot histogram + hist, bin_edges = np.histogram(tokenized_lengths, bins=np.arange(0, max(tokenized_lengths) + 10, 100)) + bins = np.arange(0, max(tokenized_lengths) + 10, 100) + ax2.bar(bin_edges[:-1], hist, width=7, edgecolor="black", log=True) + + # Display every nth label on the x-axis + n = 8 # Adjust this value to control the number of labels displayed + ticks = bins[::n] + tick_labels = [int(tick) for tick in ticks] + ax2.set_xticks(ticks) + ax2.set_xticklabels(tick_labels, rotation=90, fontsize=8) + + ax2.set_xlim(min(bin_edges), max(bin_edges)) + ax2.set_xlabel("Tokenized Length") + ax2.set_ylabel("Count (log scale)") + ax2.set_title(f"dist_{llava_instruct_name}_tokenized_length", fontsize=8) + + plt.tight_layout() + plt.savefig(f"/mnt/bn/vl-research/workspace/boli01/projects/LLaVA_Next/notebooks/sft_data/dist_{llava_instruct_name}_combined.png") + print(f"Plots saved to /mnt/bn/vl-research/workspace/boli01/projects/LLaVA_Next/notebooks/sft_data/dist_{llava_instruct_name}_combined.png") + + +if __name__ == "__main__": + main() diff --git "a/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/archived/dpo_data_info.py" "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/archived/dpo_data_info.py" new file mode 100644 index 0000000000000000000000000000000000000000..ea60ec1927874a5318e0230382106144d690db88 --- /dev/null +++ "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/archived/dpo_data_info.py" @@ -0,0 +1,67 @@ +import json +import re + +json_path = "/mnt/bn/vl-research/workspace/boli01/projects/sft_data_workspace/vlfeedback_80k.jsonl" + +with open(json_path, "r") as f: + data = f.readlines() + +data = [json.loads(d) for d in data] + + +def convert_format(original_data, dimension="Visual Faithfulness"): + converted_data = [] + for item in original_data: + # Assuming the best response is the one with the highest helpfulness rating + best_completion = max(item["completions"], key=lambda x: int(x["annotations"]["Helpfulness"]["Rating"])) + best_response = best_completion["response"] + best_model = best_completion["model"] + + if "†source" in best_response: + print(best_response) + # Regex pattern to match the pattern 【digit†source】 + pattern = r"【\d+†source】" + # Replace the matched patterns with an empty string + cleaned_text = re.sub(pattern, "", best_response) + best_response = cleaned_text + print(f"*****************************************") + print(best_response) + + # Assuming the worst response is the one with the lowest helpfulness rating + worst_completion = min(item["completions"], key=lambda x: int(x["annotations"]["Helpfulness"]["Rating"])) + worst_response = worst_completion["response"] + + if "†source" in worst_response: + print(worst_response) + # Regex pattern to match the pattern ��digit†source】 + pattern = r"【\d+†source】" + # Replace the matched patterns with an empty string + cleaned_text = re.sub(pattern, "", worst_response) + worst_response = cleaned_text + print(f"*****************************************") + print(worst_response) + + # Extract scores + best_score = int(best_completion["annotations"][dimension]["Rating"]) + worst_score = int(worst_completion["annotations"][dimension]["Rating"]) + + # Construct the new format + new_item = { + "id": item["id"], + "prompt": item["prompt"], + "answer": "", + "image": f"silkie_dpo/{item['id']}.jpg", # Assuming the video ID is the last part of the original ID + "chosen": best_response, + "rejected": worst_response, + "chosen_score": best_score, + "rejected_score": worst_score, + } + converted_data.append(new_item) + + return converted_data + + +for dimension in ["Visual Faithfulness", "Helpfulness", "Ethical Considerations"]: + converted_data = convert_format(data, dimension=dimension) + 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: + json.dump(converted_data, f, indent=4) diff --git "a/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/archived/entry_cmd.sh" "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/archived/entry_cmd.sh" new file mode 100644 index 0000000000000000000000000000000000000000..6f1f41f245b80ff723ade1abfea96ff3c83d69ce --- /dev/null +++ "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/archived/entry_cmd.sh" @@ -0,0 +1,30 @@ +python3 -m pip install --upgrade pip; + +export http_proxy=http://sys-proxy-rd-relay.byted.org:8118; +export https_proxy=http://sys-proxy-rd-relay.byted.org:8118; + +export HF_HOME=/mnt/bn/vl-research-boli01-cn/.cache/huggingface; +export HF_TOKEN="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"; +export HF_HUB_ENABLE_HF_TRANSFER="1"; + +cd /mnt/bn/vl-research-boli01-cn/projects/zzz/lmms-eval; +pip install -e .; + +cd /mnt/bn/vl-research-boli01-cn/projects/zzz/LLaVA_Next; +pip install -e .; + +python3 -m pip install ninja; +python3 -m pip install flash-attn --no-build-isolation; + +bash /mnt/bn/vl-research-boli01-cn/projects/zzz/LLaVA_Next/cn_scripts/vicuna/internal0.6m_finetune_llava1.6mix_7b_v0.2_unfreeze.sh + + +accelerate launch --num_processes 8 --main_process_port 12345 -m lmms_eval \ + --model llava \ + --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" \ + --tasks ok_vqa,textcaps_val,mme_test,mmmu,cmmmu,coco2017_cap_val,vizwiz_vqa_val,ai2d,chartqa,pope \ + --batch_size 1 \ + --log_samples \ + --log_samples_suffix debug \ + --output_path ./logs/ \ + --wandb_args 'project=llava-next-lmms-eval,job_type=eval'; \ No newline at end of file diff --git "a/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/archived/finetune.sh" "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/archived/finetune.sh" new file mode 100644 index 0000000000000000000000000000000000000000..9d1503682b355ecab9cb55f57f24fa4c57e46581 --- /dev/null +++ "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/archived/finetune.sh" @@ -0,0 +1,95 @@ +#!/bin/bash + +cd /mnt/bn/vl-research/workspace/boli01/zzzprojects/LLaVA + +# Install yolk3k if not installed +if ! pip show yolk3k > /dev/null 2>&1; then + pip install yolk3k +fi + +# Get the installed version of transformers +installed_version=$(pip show transformers | grep Version | cut -d ' ' -f 2) + +# Get the latest version of transformers from PyPI +latest_version=$(yolk -V transformers | cut -d ' ' -f 2) + +# Check if the installed version is not the latest +if [ "$installed_version" != "$latest_version" ]; then + pip install -U transformers +fi + +# Get the installed version of deepspeed +installed_version=$(pip show deepspeed | grep Version | cut -d ' ' -f 2) + +# Get the latest version of deepspeed from PyPI +latest_version=$(yolk -V deepspeed | cut -d ' ' -f 2) + +# Check if the installed version is not the latest + # pip install deepspeed==0.12.2 +if [ "$installed_version" != "$latest_version" ]; then + pip install deepspeed==0.12.2 +fi + +# Install flash-attn if not installed +if ! pip show flash-attn > /dev/null 2>&1; then + pip install flash-attn --no-build-isolation +fi + +################## VICUNA ################## +PROMPT_VERSION=v1 +MODEL_VERSION="vicuna-7b-v1-5" +################## VICUNA ################## + + +################## project ################## +PROJECT_NAME="ds_llava-vicuna-7b-v1-5-mlp2x_gelu-pretrain_blip558k_plain" + +################## data ################## +DATA_NAME="mixtral_instruct_158K_V1" + +# wandb configure +export WANDB_API_KEY="03fc62d68025c9498cf6493432551badd7d4f953" +wandb login $WANDB_API_KEY + +export WANDB_NAME=$PROJECT_NAME--$MODEL_VERSION--$DATA_NAME + +export WANDB_PROJECT=LLaVA_Mixtral + +export WANDB_MODE=online + +# wandb online + +deepspeed --master_port 26000 \ + llava/train/train_mem.py \ + --deepspeed ./scripts/zero2.json \ + --model_name_or_path ./checkpoints/$MODEL_VERSION \ + --version $PROMPT_VERSION \ + --data_path ./playground/data/$DATA_NAME.json \ + --image_folder /mnt/bn/vl-research/workspace/boli01/data/playground/data/coco/train2017 \ + --vision_tower openai/clip-vit-large-patch14 \ + --pretrain_mm_mlp_adapter ./checkpoints/$PROJECT_NAME/mm_projector.bin \ + --mm_vision_select_layer -2 \ + --mm_projector_type mlp2x_gelu \ + --mm_use_im_start_end False \ + --mm_use_im_patch_token False \ + --bf16 True \ + --output_dir ./checkpoints/llava--$PROJECT_NAME--$MODEL_VERSION--$DATA_NAME--finetune \ + --num_train_epochs 1 \ + --per_device_train_batch_size 16 \ + --per_device_eval_batch_size 4 \ + --gradient_accumulation_steps 1 \ + --evaluation_strategy "no" \ + --save_strategy "steps" \ + --save_steps 50000 \ + --save_total_limit 1 \ + --learning_rate 2e-5 \ + --weight_decay 0. \ + --warmup_ratio 0.03 \ + --lr_scheduler_type "cosine" \ + --logging_steps 1 \ + --tf32 True \ + --model_max_length 2048 \ + --gradient_checkpointing True \ + --dataloader_num_workers 16 \ + --lazy_preprocess True \ + --report_to wandb diff --git "a/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/archived/finetune_1.5.sh" "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/archived/finetune_1.5.sh" new file mode 100644 index 0000000000000000000000000000000000000000..13cb818b7a01413d2a11dc8f4b8154ad688979b7 --- /dev/null +++ "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/archived/finetune_1.5.sh" @@ -0,0 +1,99 @@ +#!/bin/bash +dataset_name=$1 + +# Uncomment and set the following variables correspondingly to run this script: + +cd /mnt/bn/vl-research/workspace/boli01/zzzprojects/LLaVA + +# Install yolk3k if not installed +if ! pip show yolk3k > /dev/null 2>&1; then + pip install yolk3k +fi + +# Get the installed version of transformers +installed_version=$(pip show transformers | grep Version | cut -d ' ' -f 2) + +# Get the latest version of transformers from PyPI +latest_version=$(yolk -V transformers | cut -d ' ' -f 2) + +# Check if the installed version is not the latest +if [ "$installed_version" != "$latest_version" ]; then + pip install -U transformers +fi + +# Get the installed version of deepspeed +installed_version=$(pip show deepspeed | grep Version | cut -d ' ' -f 2) + +# Get the latest version of deepspeed from PyPI +latest_version=$(yolk -V deepspeed | cut -d ' ' -f 2) + +# Check if the installed version is not the latest +if [ "$installed_version" != "$latest_version" ]; then + pip install deepspeed==0.12.2 +fi + +# Install yolk3k if not installed +if ! pip show flash-attn > /dev/null 2>&1; then + pip install flash-attn --no-build-isolation +fi + + +################## VICUNA ################## +PROMPT_VERSION=v1 +MODEL_VERSION="vicuna-7b-v1-5" +################## VICUNA ################## + +################## project ################## +PROJECT_NAME="ds_llava-vicuna-7b-v1-5-mlp2x_gelu-pretrain_blip558k_plain" + +################## data ################## +DATA_NAME=$dataset_name + + +# wandb configure +export WANDB_API_KEY="03fc62d68025c9498cf6493432551badd7d4f953" +wandb login $WANDB_API_KEY + +export WANDB_NAME=$PROJECT_NAME--$MODEL_VERSION--$DATA_NAME + +export WANDB_PROJECT=LLaVA_Mixtral + +export WANDB_MODE=online + +wandb online + + +deepspeed --master_port 26000 \ + llava/train/train_mem.py \ + --deepspeed ./scripts/zero2.json \ + --model_name_or_path ./checkpoints/$MODEL_VERSION \ + --version $PROMPT_VERSION \ + --data_path ./playground/data/$DATA_NAME.json \ + --image_folder /mnt/bn/vl-research/workspace/boli01/data/playground/data \ + --vision_tower openai/clip-vit-large-patch14 \ + --pretrain_mm_mlp_adapter ./checkpoints/$PROJECT_NAME/mm_projector.bin \ + --mm_vision_select_layer -2 \ + --mm_projector_type mlp2x_gelu \ + --mm_use_im_start_end False \ + --mm_use_im_patch_token False \ + --bf16 True \ + --output_dir ./checkpoints/llava--$PROJECT_NAME--$MODEL_VERSION--$DATA_NAME--finetune \ + --num_train_epochs 1 \ + --per_device_train_batch_size 16 \ + --per_device_eval_batch_size 4 \ + --gradient_accumulation_steps 1 \ + --evaluation_strategy "no" \ + --save_strategy "steps" \ + --save_steps 50000 \ + --save_total_limit 1 \ + --learning_rate 2e-5 \ + --weight_decay 0. \ + --warmup_ratio 0.03 \ + --lr_scheduler_type "cosine" \ + --logging_steps 1 \ + --tf32 True \ + --model_max_length 2048 \ + --gradient_checkpointing True \ + --dataloader_num_workers 16 \ + --lazy_preprocess True \ + --report_to wandb diff --git "a/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/archived/finetune_full_schedule.sh" "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/archived/finetune_full_schedule.sh" new file mode 100644 index 0000000000000000000000000000000000000000..9769666db9424808a896d322016ae86a2bf32a19 --- /dev/null +++ "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/archived/finetune_full_schedule.sh" @@ -0,0 +1,46 @@ +#!/bin/bash + +# Uncomment and set the following variables correspondingly to run this script: + +################## VICUNA ################## +# PROMPT_VERSION=v1 +# MODEL_VERSION="vicuna-v1-3-7b" +################## VICUNA ################## + +################## LLaMA-2 ################## +# PROMPT_VERSION="llava_llama_2" +# MODEL_VERSION="llama-2-7b-chat" +################## LLaMA-2 ################## + +deepspeed llava/train/train_mem.py \ + --deepspeed ./scripts/zero2.json \ + --model_name_or_path ./checkpoints/$MODEL_VERSION \ + --version $PROMPT_VERSION \ + --data_path ./playground/data/llava_instruct_158k.json \ + --image_folder /path/to/coco/train2017 \ + --vision_tower openai/clip-vit-large-patch14 \ + --pretrain_mm_mlp_adapter ./checkpoints/llava-$MODEL_VERSION-pretrain/mm_projector.bin \ + --mm_vision_select_layer -2 \ + --mm_use_im_start_end False \ + --mm_use_im_patch_token False \ + --bf16 True \ + --output_dir ./checkpoints/llava-$MODEL_VERSION-finetune \ + --num_train_epochs 3 \ + --per_device_train_batch_size 16 \ + --per_device_eval_batch_size 4 \ + --gradient_accumulation_steps 1 \ + --evaluation_strategy "no" \ + --save_strategy "steps" \ + --save_steps 50000 \ + --save_total_limit 1 \ + --learning_rate 2e-5 \ + --weight_decay 0. \ + --warmup_ratio 0.03 \ + --lr_scheduler_type "cosine" \ + --logging_steps 1 \ + --tf32 True \ + --model_max_length 2048 \ + --gradient_checkpointing True \ + --dataloader_num_workers 16 \ + --lazy_preprocess True \ + --report_to wandb diff --git "a/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/archived/finetune_lora.sh" "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/archived/finetune_lora.sh" new file mode 100644 index 0000000000000000000000000000000000000000..5ff90c0247a5072eb174ca7fad08c45b8880b317 --- /dev/null +++ "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/archived/finetune_lora.sh" @@ -0,0 +1,47 @@ +#!/bin/bash + +# Uncomment and set the following variables correspondingly to run this script: + +################## VICUNA ################## +# PROMPT_VERSION=v1 +# MODEL_VERSION="vicuna-v1-3-7b" +################## VICUNA ################## + +################## LLaMA-2 ################## +# PROMPT_VERSION="llava_llama_2" +# MODEL_VERSION="llama-2-7b-chat" +################## LLaMA-2 ################## + +deepspeed llava/train/train_mem.py \ + --deepspeed ./scripts/zero2.json \ + --lora_enable True \ + --model_name_or_path ./checkpoints/$MODEL_VERSION \ + --version $PROMPT_VERSION \ + --data_path ./playground/data/llava_instruct_80k.json \ + --image_folder /path/to/coco/train2017 \ + --vision_tower openai/clip-vit-large-patch14 \ + --pretrain_mm_mlp_adapter ./checkpoints/llava-$MODEL_VERSION-pretrain/mm_projector.bin \ + --mm_vision_select_layer -2 \ + --mm_use_im_start_end False \ + --mm_use_im_patch_token False \ + --bf16 True \ + --output_dir ./checkpoints/llava-$MODEL_VERSION-finetune_lora \ + --num_train_epochs 1 \ + --per_device_train_batch_size 16 \ + --per_device_eval_batch_size 4 \ + --gradient_accumulation_steps 1 \ + --evaluation_strategy "no" \ + --save_strategy "steps" \ + --save_steps 50000 \ + --save_total_limit 1 \ + --learning_rate 2e-5 \ + --weight_decay 0. \ + --warmup_ratio 0.03 \ + --lr_scheduler_type "cosine" \ + --logging_steps 1 \ + --tf32 True \ + --model_max_length 2048 \ + --gradient_checkpointing True \ + --lazy_preprocess True \ + --dataloader_num_workers 16 \ + --report_to wandb diff --git "a/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/archived/finetune_mixtral.sh" "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/archived/finetune_mixtral.sh" new file mode 100644 index 0000000000000000000000000000000000000000..f7ca3836143715124f8724b1f92d64b04a9f1856 --- /dev/null +++ "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/archived/finetune_mixtral.sh" @@ -0,0 +1,96 @@ +#!/bin/bash + +cd /mnt/bn/vl-research/workspace/boli01/zzzprojects/LLaVA + +# Install yolk3k if not installed +if ! pip show yolk3k > /dev/null 2>&1; then + pip install yolk3k +fi + +# Get the installed version of transformers +installed_version=$(pip show transformers | grep Version | cut -d ' ' -f 2) + +# Get the latest version of transformers from PyPI +latest_version=$(yolk -V transformers | cut -d ' ' -f 2) + +# Check if the installed version is not the latest +if [ "$installed_version" != "$latest_version" ]; then + pip install -U transformers +fi + +# Get the installed version of deepspeed +installed_version=$(pip show deepspeed | grep Version | cut -d ' ' -f 2) + +# Get the latest version of deepspeed from PyPI +latest_version=$(yolk -V deepspeed | cut -d ' ' -f 2) + +# Check if the installed version is not the latest +if [ "$installed_version" != "$latest_version" ]; then + pip install deepspeed==0.12.2 +fi + +# Install yolk3k if not installed +if ! pip show flash-attn > /dev/null 2>&1; then + pip install flash-attn --no-build-isolation +fi + + +################## MISTRAL ################## +PROMPT_VERSION=mistral_instruct +MODEL_VERSION="Mistral-7B-Instruct-v0.2" +################## VICUNA ################## + + +################## project ################## +PROJECT_NAME="ds_llava-Mistral-7B-Instruct-v0.2-mlp2x_gelu-pretrain_blip558k_plain" + +################## data ################## +DATA_NAME="mixtral_instruct_158K_V1" + +# wandb configure +export WANDB_API_KEY="03fc62d68025c9498cf6493432551badd7d4f953" +wandb login $WANDB_API_KEY + +export WANDB_NAME=$PROJECT_NAME--$MODEL_VERSION--$DATA_NAME + +export WANDB_PROJECT=LLaVA_Mixtral + +export WANDB_MODE=online + +wandb online + + +deepspeed --master_port 26000 \ + llava/train/train_mem.py \ + --deepspeed ./scripts/zero2.json \ + --model_name_or_path ./checkpoints/$MODEL_VERSION \ + --version $PROMPT_VERSION \ + --data_path ./playground/data/$DATA_NAME.json \ + --image_folder /mnt/bn/vl-research/workspace/boli01/data/playground/data/coco/train2017 \ + --vision_tower openai/clip-vit-large-patch14 \ + --pretrain_mm_mlp_adapter ./checkpoints/$PROJECT_NAME/mm_projector.bin \ + --mm_vision_select_layer -2 \ + --mm_projector_type mlp2x_gelu \ + --mm_use_im_start_end False \ + --mm_use_im_patch_token False \ + --bf16 True \ + --output_dir ./checkpoints/llava--$PROJECT_NAME--$MODEL_VERSION--$DATA_NAME--finetune \ + --num_train_epochs 1 \ + --per_device_train_batch_size 16 \ + --per_device_eval_batch_size 4 \ + --gradient_accumulation_steps 1 \ + --evaluation_strategy "no" \ + --save_strategy "steps" \ + --save_steps 50000 \ + --save_total_limit 1 \ + --learning_rate 2e-5 \ + --weight_decay 0. \ + --warmup_ratio 0.03 \ + --lr_scheduler_type "cosine" \ + --logging_steps 1 \ + --tf32 True \ + --model_max_length 2048 \ + --gradient_checkpointing True \ + --dataloader_num_workers 16 \ + --lazy_preprocess True \ + --report_to wandb diff --git "a/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/archived/finetune_mixtral_1.5.sh" "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/archived/finetune_mixtral_1.5.sh" new file mode 100644 index 0000000000000000000000000000000000000000..71f4ed8aba11fca1ad18979498b8c7ca7d7d5fa6 --- /dev/null +++ "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/archived/finetune_mixtral_1.5.sh" @@ -0,0 +1,96 @@ +#!/bin/bash +dataset_name=$1 + +cd /mnt/bn/vl-research/workspace/yhzhang/LLaVA + +# Install yolk3k if not installed +if ! pip show yolk3k > /dev/null 2>&1; then + pip install yolk3k +fi + +# Get the installed version of transformers +installed_version=$(pip show transformers | grep Version | cut -d ' ' -f 2) + +# Get the latest version of transformers from PyPI +latest_version=$(yolk -V transformers | cut -d ' ' -f 2) + +# Check if the installed version is not the latest +if [ "$installed_version" != "$latest_version" ]; then + pip install -U transformers +fi + +# Get the installed version of deepspeed +installed_version=$(pip show deepspeed | grep Version | cut -d ' ' -f 2) + +# Get the latest version of deepspeed from PyPI +# latest_version=$(yolk -V deepspeed | cut -d ' ' -f 2) + +# Check if the installed version is not the latest +if [ "$installed_version" != "0.12.2" ]; then + pip install deepspeed==0.12.2 +fi + +# Install yolk3k if not installed +if ! pip show flash-attn > /dev/null 2>&1; then + pip install flash-attn --no-build-isolation +fi + +################## MISTRAL ################## +PROMPT_VERSION=mistral_instruct +MODEL_VERSION="Mistral-7B-Instruct-v0.2" +################## MISTRAL ################## + + +################## project ################## +PROJECT_NAME="ds_llava-Mistral-7B-Instruct-v0.2-mlp2x_gelu-pretrain_blip558k_plain" + +################## data ################## +DATA_NAME=$dataset_name + + +# wandb configure +export WANDB_API_KEY="03fc62d68025c9498cf6493432551badd7d4f953" +wandb login $WANDB_API_KEY + +export WANDB_NAME=$PROJECT_NAME--$MODEL_VERSION--$DATA_NAME + +export WANDB_PROJECT=LLaVA_Mixtral + +export WANDB_MODE=online + +wandb online + +deepspeed --master_port 26000 \ + llava/train/train_mem.py \ + --deepspeed ./scripts/zero2.json \ + --model_name_or_path ./checkpoints/$MODEL_VERSION \ + --version $PROMPT_VERSION \ + --data_path ./playground/data/$DATA_NAME.json \ + --image_folder /mnt/bn/vl-research/workspace/boli01/data/playground/data \ + --vision_tower openai/clip-vit-large-patch14 \ + --pretrain_mm_mlp_adapter ./checkpoints/$PROJECT_NAME/mm_projector.bin \ + --mm_vision_select_layer -2 \ + --mm_projector_type mlp2x_gelu \ + --mm_use_im_start_end False \ + --mm_use_im_patch_token False \ + --bf16 True \ + --output_dir ./checkpoints/llava--$PROJECT_NAME--$MODEL_VERSION--$DATA_NAME--finetune \ + --num_train_epochs 1 \ + --per_device_train_batch_size 16 \ + --per_device_eval_batch_size 4 \ + --gradient_accumulation_steps 1 \ + --evaluation_strategy "no" \ + --save_strategy "steps" \ + --save_steps 50000 \ + --save_total_limit 1 \ + --learning_rate 2e-5 \ + --weight_decay 0. \ + --warmup_ratio 0.03 \ + --lr_scheduler_type "cosine" \ + --logging_steps 1 \ + --tf32 True \ + --model_max_length 2048 \ + --gradient_checkpointing True \ + --dataloader_num_workers 16 \ + --lazy_preprocess True + # --report_to wandb diff --git "a/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/archived/finetune_mixtral_1.6_336px_anyres.sh" "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/archived/finetune_mixtral_1.6_336px_anyres.sh" new file mode 100644 index 0000000000000000000000000000000000000000..28b2e0b257044fbd1d222c9aebb033d8c63d489a --- /dev/null +++ "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/archived/finetune_mixtral_1.6_336px_anyres.sh" @@ -0,0 +1,100 @@ +#!/bin/bash +dataset_name=$1 + +cd /mnt/bn/vl-research/workspace/boli01/projects/LLaVA_Next + +# Install yolk3k if not installed +if ! pip show yolk3k > /dev/null 2>&1; then + pip install yolk3k +fi + +pip install pydantic + +# Get the installed version of transformers +installed_version=$(pip show transformers | grep Version | cut -d ' ' -f 2) + +# Get the latest version of transformers from PyPI +latest_version=$(yolk -V transformers | cut -d ' ' -f 2) + +# Check if the installed version is not the latest +if [ "$installed_version" != "4.36.2" ]; then + pip install transformers==4.36.2 +fi + +# Get the installed version of deepspeed +installed_version=$(pip show deepspeed | grep Version | cut -d ' ' -f 2) + + +# Check if the installed version is not the latest +if [ "$installed_version" != "0.12.2" ]; then + pip install deepspeed==0.12.2 +fi + +# Install flash-atten if not installed +if ! pip show flash-attn > /dev/null 2>&1; then + pip install flash-attn --no-build-isolation +fi + +################## MISTRAL ################## +PROMPT_VERSION=mistral_instruct +MODEL_VERSION="Mistral-7B-Instruct-v0.2" +################## MISTRAL ################## + + +################## project ################## +PROJECT_NAME="ds_llava-Mistral-7B-Instruct-v0.2-clip_large_336px-mlp2x_gelu-pretrain_blip558k_plain" + +################## data ################## +DATA_NAME=$dataset_name + + +# wandb configure +export WANDB_API_KEY=e464cc107357c7b38e87f239bc3eb2ce5fb73c7c +export WANDB_PROJECT=llava + +export WANDB_NAME=$PROJECT_NAME--$DATA_NAME--336px--anyres--sft + +export WANDB_MODE=online + +wandb online + +deepspeed --master_port 26000 \ + llava/train/train_mem.py \ + --deepspeed ./scripts/zero3.json \ + --model_name_or_path /mnt/bn/vl-research/workspace/project/2023/LLaVA/checkpoints/$MODEL_VERSION \ + --version $PROMPT_VERSION \ + --data_path ./playground/data/$DATA_NAME.json \ + --image_folder /mnt/bn/vl-research/workspace/boli01/data/playground/data \ + --vision_tower openai/clip-vit-large-patch14-336 \ + --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 \ + --mm_projector_type mlp2x_gelu \ + --mm_vision_select_layer -2 \ + --mm_use_im_start_end False \ + --mm_use_im_patch_token False \ + --group_by_modality_length True \ + --unfreeze_mm_vision_tower True \ + --mm_vision_tower_lr 2e-6 \ + --image_aspect_ratio anyres \ + --image_grid_pinpoints "[(336, 672), (672, 336), (672, 672), (1008, 336), (336, 1008)]" \ + --mm_patch_merge_type spatial_unpad \ + --bf16 True \ + --output_dir ./checkpoints/$PROJECT_NAME--$DATA_NAME--336px--anyres--sft \ + --num_train_epochs 9 \ + --per_device_train_batch_size 8 \ + --per_device_eval_batch_size 4 \ + --gradient_accumulation_steps 1 \ + --evaluation_strategy "no" \ + --save_strategy "epoch" \ + --save_steps 1500 \ + --learning_rate 5e-6 \ + --weight_decay 0. \ + --warmup_ratio 0.03 \ + --lr_scheduler_type "cosine" \ + --logging_steps 1 \ + --tf32 True \ + --model_max_length 4096 \ + --gradient_checkpointing True \ + --dataloader_num_workers 8 \ + --lazy_preprocess True \ + --report_to wandb + diff --git "a/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/archived/finetune_mixtral_1.6_336px_anyres_freeze_vision.sh" "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/archived/finetune_mixtral_1.6_336px_anyres_freeze_vision.sh" new file mode 100644 index 0000000000000000000000000000000000000000..e04f4871f4da95c4c442522c0aa3f5c3829ff78e --- /dev/null +++ "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/archived/finetune_mixtral_1.6_336px_anyres_freeze_vision.sh" @@ -0,0 +1,97 @@ +#!/bin/bash +dataset_name=$1 + +cd /mnt/bn/vl-research/workspace/yhzhang/LLaVA + +# Install yolk3k if not installed +if ! pip show yolk3k > /dev/null 2>&1; then + pip install yolk3k +fi + +pip install pydantic + +# Get the installed version of transformers +installed_version=$(pip show transformers | grep Version | cut -d ' ' -f 2) + +# Get the latest version of transformers from PyPI +latest_version=$(yolk -V transformers | cut -d ' ' -f 2) + +# Check if the installed version is not the latest +if [ "$installed_version" != "4.36.2" ]; then + pip install transformers==4.36.2 +fi + +# Get the installed version of deepspeed +installed_version=$(pip show deepspeed | grep Version | cut -d ' ' -f 2) + + +# Check if the installed version is not the latest +if [ "$installed_version" != "0.12.2" ]; then + pip install deepspeed==0.12.2 +fi + +# Install flash-atten if not installed +if ! pip show flash-attn > /dev/null 2>&1; then + pip install flash-attn --no-build-isolation +fi + +################## MISTRAL ################## +PROMPT_VERSION=mistral_instruct +MODEL_VERSION="Mistral-7B-Instruct-v0.2" +################## MISTRAL ################## + + +################## project ################## +PROJECT_NAME="ds_llava-Mistral-7B-Instruct-v0.2-clip_large_336px-mlp2x_gelu-pretrain_blip558k_plain" + +################## data ################## +DATA_NAME=$dataset_name + + +# wandb configure +export WANDB_API_KEY=e464cc107357c7b38e87f239bc3eb2ce5fb73c7c +export WANDB_PROJECT=llava + +export WANDB_NAME=$PROJECT_NAME--$DATA_NAME--336px--unfreeze--anyres--sft + +export WANDB_MODE=online + +wandb online + +deepspeed --master_port 26000 \ + llava/train/train_mem.py \ + --deepspeed ./scripts/zero3.json \ + --model_name_or_path ./checkpoints/$MODEL_VERSION \ + --version $PROMPT_VERSION \ + --data_path ./playground/data/$DATA_NAME.json \ + --image_folder /mnt/bn/vl-research/workspace/boli01/data/playground/data \ + --vision_tower openai/clip-vit-large-patch14-336 \ + --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 \ + --mm_vision_select_layer -2 \ + --mm_projector_type mlp2x_gelu \ + --mm_use_im_start_end False \ + --mm_use_im_patch_token False \ + --group_by_modality_length True \ + --image_aspect_ratio anyres \ + --image_grid_pinpoints "[(336, 672), (672, 336), (672, 672), (1008, 336), (336, 1008)]" \ + --mm_patch_merge_type spatial_unpad \ + --bf16 True \ + --output_dir ./checkpoints/$PROJECT_NAME--$DATA_NAME--336px--anyres--unfreeze--sft \ + --num_train_epochs 1 \ + --per_device_train_batch_size 16 \ + --per_device_eval_batch_size 4 \ + --gradient_accumulation_steps 1 \ + --evaluation_strategy "no" \ + --save_strategy "steps" \ + --save_steps 50000 \ + --save_total_limit 1 \ + --learning_rate 2e-5 \ + --weight_decay 0. \ + --warmup_ratio 0.03 \ + --lr_scheduler_type "cosine" \ + --logging_steps 1 \ + --tf32 True \ + --model_max_length 2048 \ + --gradient_checkpointing True \ + --dataloader_num_workers 16 \ + diff --git "a/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/archived/finetune_mixtral_1.6_336px_anyres_lmms_eval.sh" "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/archived/finetune_mixtral_1.6_336px_anyres_lmms_eval.sh" new file mode 100644 index 0000000000000000000000000000000000000000..c31fdc53fd807d866e49091c1735c4969ed2b5f7 --- /dev/null +++ "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/archived/finetune_mixtral_1.6_336px_anyres_lmms_eval.sh" @@ -0,0 +1,78 @@ +#!/bin/bash + +# set up wandb +export WANDB_API_KEY=a651c244635bc6f913ab654af3f0eebaecdc9381 +export WANDB_ENTITY=llava-vl +export WANDB_PROJECT=llava-next +export PYTHONWARNINGS="ignore" + +cd /mnt/bn/vl-research/workspace/boli01/projects/lmms-eval + +pip install -e . + +# set up llava dev env +cd /mnt/bn/vl-research/workspace/boli01/projects/LLaVA_Next + +################## MISTRAL ################## +PROMPT_VERSION=mistral_instruct +MODEL_VERSION="Mistral-7B-Instruct-v0.2" +################## MISTRAL ################## + +################## project ################## +PROJECT_NAME="ds_llava-Mistral-7B-Instruct-v0.2-clip_large_336px-mlp2x_gelu-pretrain_blip558k_plain" + +################## data ################## +DATA_NAME='llava_caps20k_chartqa19k' + +export WANDB_NAME=$PROJECT_NAME--$DATA_NAME--336px--anyres--sft +export WANDB_MODE=online + +wandb online + +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 \ + --deepspeed ./scripts/zero3_offload.json \ + --model_name_or_path mistralai/$MODEL_VERSION \ + --version $PROMPT_VERSION \ + --data_path ./playground/data/llava_instruct/$DATA_NAME.json \ + --image_folder /mnt/bn/vl-research/data/llava \ + --vision_tower openai/clip-vit-large-patch14-336 \ + --mm_projector_type mlp2x_gelu \ + --mm_vision_select_layer -2 \ + --mm_use_im_start_end False \ + --mm_use_im_patch_token False \ + --group_by_modality_length True \ + --unfreeze_mm_vision_tower True \ + --mm_vision_tower_lr 2e-6 \ + --image_aspect_ratio anyres \ + --image_grid_pinpoints "[(336, 672), (672, 336), (672, 672), (1008, 336), (336, 1008)]" \ + --mm_patch_merge_type spatial_unpad \ + --bf16 True \ + --output_dir ./checkpoints/$PROJECT_NAME--llava1.6--336px--anyres--sft \ + --num_train_epochs 1 \ + --per_device_train_batch_size 8 \ + --per_device_eval_batch_size 4 \ + --gradient_accumulation_steps 1 \ + --evaluation_strategy "no" \ + --save_strategy "steps" \ + --save_steps 1500 \ + --learning_rate 2e-5 \ + --weight_decay 0. \ + --warmup_ratio 0.03 \ + --lr_scheduler_type "cosine" \ + --logging_steps 1 \ + --tf32 True \ + --model_max_length 4096 \ + --gradient_checkpointing True \ + --dataloader_num_workers 32 \ + --lazy_preprocess True \ + --report_to wandb \ + --run_name $WANDB_NAME +# starting here is the args for evaluation + --eval_num_processes 4 \ + --task_names mme,docvqa_val \ + --model_args pretrained=./checkpoints/$PROJECT_NAME--$DATA_NAME--336px--anyres--sft \ + --limit 8 \ + --batch_size 1 \ + --log_samples \ + --log_samples_suffix debug \ + --output_path ./logs/ diff --git "a/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/archived/finetune_mixtral_copy.sh" "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/archived/finetune_mixtral_copy.sh" new file mode 100644 index 0000000000000000000000000000000000000000..23cab89db08ec4557659c4810410bfff438a23b6 --- /dev/null +++ "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/archived/finetune_mixtral_copy.sh" @@ -0,0 +1,96 @@ +#!/bin/bash + +cd /mnt/bn/vl-research/workspace/boli01/zzzprojects/LLaVA + +# Install yolk3k if not installed +if ! pip show yolk3k > /dev/null 2>&1; then + pip install yolk3k +fi + +# Get the installed version of transformers +installed_version=$(pip show transformers | grep Version | cut -d ' ' -f 2) + +# Get the latest version of transformers from PyPI +latest_version=$(yolk -V transformers | cut -d ' ' -f 2) + +# Check if the installed version is not the latest +if [ "$installed_version" != "$latest_version" ]; then + pip install -U transformers +fi + +# Get the installed version of deepspeed +installed_version=$(pip show deepspeed | grep Version | cut -d ' ' -f 2) + +# Get the latest version of deepspeed from PyPI +latest_version=$(yolk -V deepspeed | cut -d ' ' -f 2) + +# Check if the installed version is not the latest +if [ "$installed_version" != "$latest_version" ]; then + pip install deepspeed==0.12.2 +fi + +# Install yolk3k if not installed +if ! pip show flash-attn > /dev/null 2>&1; then + pip install flash-attn --no-build-isolation +fi + + +################## MISTRAL ################## +PROMPT_VERSION=mistral_instruct +MODEL_VERSION="Mistral-7B-Instruct-v0.2" +################## VICUNA ################## + + +################## project ################## +PROJECT_NAME="ds_llava-Mistral-7B-Instruct-v0.2-mlp2x_gelu-pretrain_blip558k_plain" + +################## data ################## +DATA_NAME="llava_instruct_150k" + +# wandb configure +export WANDB_API_KEY="03fc62d68025c9498cf6493432551badd7d4f953" +wandb login $WANDB_API_KEY + +export WANDB_NAME=$PROJECT_NAME--$MODEL_VERSION--$DATA_NAME + +export WANDB_PROJECT=LLaVA_Mixtral + +export WANDB_MODE=online + +wandb online + + +deepspeed --master_port 26000 \ + llava/train/train_mem.py \ + --deepspeed ./scripts/zero2.json \ + --model_name_or_path ./checkpoints/$MODEL_VERSION \ + --version $PROMPT_VERSION \ + --data_path ./playground/data/$DATA_NAME.json \ + --image_folder /mnt/bn/vl-research/workspace/boli01/data/playground/data/coco/train2017 \ + --vision_tower openai/clip-vit-large-patch14 \ + --pretrain_mm_mlp_adapter ./checkpoints/$PROJECT_NAME/mm_projector.bin \ + --mm_vision_select_layer -2 \ + --mm_projector_type mlp2x_gelu \ + --mm_use_im_start_end False \ + --mm_use_im_patch_token False \ + --bf16 True \ + --output_dir ./checkpoints/llava--$PROJECT_NAME--$MODEL_VERSION--$DATA_NAME--finetune \ + --num_train_epochs 1 \ + --per_device_train_batch_size 16 \ + --per_device_eval_batch_size 4 \ + --gradient_accumulation_steps 1 \ + --evaluation_strategy "no" \ + --save_strategy "steps" \ + --save_steps 50000 \ + --save_total_limit 1 \ + --learning_rate 2e-5 \ + --weight_decay 0. \ + --warmup_ratio 0.03 \ + --lr_scheduler_type "cosine" \ + --logging_steps 1 \ + --tf32 True \ + --model_max_length 2048 \ + --gradient_checkpointing True \ + --dataloader_num_workers 16 \ + --lazy_preprocess True \ + --report_to wandb diff --git "a/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/archived/finetune_qlora.sh" "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/archived/finetune_qlora.sh" new file mode 100644 index 0000000000000000000000000000000000000000..05be856288274653ecb14f48c667ff5ca8ce1464 --- /dev/null +++ "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/archived/finetune_qlora.sh" @@ -0,0 +1,48 @@ +#!/bin/bash + +# Uncomment and set the following variables correspondingly to run this script: + +################## VICUNA ################## +# PROMPT_VERSION=v1 +# MODEL_VERSION="vicuna-v1-3-7b" +################## VICUNA ################## + +################## LLaMA-2 ################## +# PROMPT_VERSION="llava_llama_2" +# MODEL_VERSION="llama-2-7b-chat" +################## LLaMA-2 ################## + +deepspeed llava/train/train_mem.py \ + --deepspeed ./scripts/zero2.json \ + --lora_enable True \ + --bits 4 \ + --model_name_or_path ./checkpoints/$MODEL_VERSION \ + --version $PROMPT_VERSION \ + --data_path ./playground/data/llava_instruct_80k.json \ + --image_folder /path/to/coco/train2017 \ + --vision_tower openai/clip-vit-large-patch14 \ + --pretrain_mm_mlp_adapter ./checkpoints/llava-$MODEL_VERSION-pretrain/mm_projector.bin \ + --mm_vision_select_layer -2 \ + --mm_use_im_start_end False \ + --mm_use_im_patch_token False \ + --bf16 True \ + --output_dir ./checkpoints/llava-$MODEL_VERSION-finetune_lora \ + --num_train_epochs 1 \ + --per_device_train_batch_size 16 \ + --per_device_eval_batch_size 4 \ + --gradient_accumulation_steps 1 \ + --evaluation_strategy "no" \ + --save_strategy "steps" \ + --save_steps 50000 \ + --save_total_limit 1 \ + --learning_rate 2e-5 \ + --weight_decay 0. \ + --warmup_ratio 0.03 \ + --lr_scheduler_type "cosine" \ + --logging_steps 1 \ + --tf32 True \ + --model_max_length 2048 \ + --gradient_checkpointing True \ + --lazy_preprocess True \ + --dataloader_num_workers 16 \ + --report_to wandb diff --git "a/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/archived/finetune_sqa.sh" "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/archived/finetune_sqa.sh" new file mode 100644 index 0000000000000000000000000000000000000000..ac1359ce9eeffb5e6aae8bdc44425b84e5e642aa --- /dev/null +++ "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/archived/finetune_sqa.sh" @@ -0,0 +1,34 @@ +#!/bin/bash + +deepspeed llava/train/train_mem.py \ + --deepspeed ./scripts/zero2.json \ + --model_name_or_path lmsys/vicuna-13b-v1.3 \ + --version $PROMPT_VERSION \ + --data_path /Data/ScienceQA/data/scienceqa/llava_train_QCM-LEA.json \ + --image_folder /Data/ScienceQA/data/scienceqa/images/train \ + --vision_tower openai/clip-vit-large-patch14 \ + --pretrain_mm_mlp_adapter ./checkpoints/huggingface/liuhaotian/llava-pretrain-vicuna-13b-v1.3/mm_projector.bin \ + --mm_vision_select_layer -2 \ + --mm_use_im_start_end False \ + --mm_use_im_patch_token False \ + --bf16 True \ + --output_dir ./checkpoints/llava-vicuna-13b-v1.3-pretrain_lcs558k_plain-ScienceQA_QCM_LEA-12e \ + --num_train_epochs 12 \ + --per_device_train_batch_size 16 \ + --per_device_eval_batch_size 4 \ + --gradient_accumulation_steps 1 \ + --evaluation_strategy "no" \ + --save_strategy "steps" \ + --save_steps 50000 \ + --save_total_limit 1 \ + --learning_rate 2e-5 \ + --weight_decay 0. \ + --warmup_ratio 0.03 \ + --lr_scheduler_type "cosine" \ + --logging_steps 1 \ + --tf32 True \ + --model_max_length 2048 \ + --gradient_checkpointing True \ + --dataloader_num_workers 16 \ + --lazy_preprocess True \ + --report_to wandb diff --git "a/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/archived/merge_lora_weights.py" "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/archived/merge_lora_weights.py" new file mode 100644 index 0000000000000000000000000000000000000000..90b4aa0f903a3b345556213ddf27595319263e06 --- /dev/null +++ "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/archived/merge_lora_weights.py" @@ -0,0 +1,22 @@ +import argparse +from llava.model.builder import load_pretrained_model +from llava.mm_utils import get_model_name_from_path + + +def merge_lora(args): + model_name = get_model_name_from_path(args.model_path) + tokenizer, model, image_processor, context_len = load_pretrained_model(args.model_path, args.model_base, model_name, device_map="cpu") + + model.save_pretrained(args.save_model_path) + tokenizer.save_pretrained(args.save_model_path) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--model-path", type=str, required=True) + parser.add_argument("--model-base", type=str, required=True) + parser.add_argument("--save-model-path", type=str, required=True) + + args = parser.parse_args() + + merge_lora(args) diff --git "a/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/archived/pretrain.sh" "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/archived/pretrain.sh" new file mode 100644 index 0000000000000000000000000000000000000000..f3cf7d94e59e55e6a4942e3917b1eadffe6c9a86 --- /dev/null +++ "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/archived/pretrain.sh" @@ -0,0 +1,43 @@ +#!/bin/bash + +# Uncomment and set the following variables correspondingly to run this script: + +# MODEL_VERSION=vicuna-v1-3-7b +# MODEL_VERSION=llama-2-7b-chat + +########### DO NOT CHANGE ########### +########### USE THIS FOR BOTH ########### +PROMPT_VERSION=plain +########### DO NOT CHANGE ########### + +deepspeed llava/train/train_mem.py \ + --deepspeed ./scripts/zero2.json \ + --model_name_or_path ./checkpoints/$MODEL_VERSION \ + --version $PROMPT_VERSION \ + --data_path /path/to/pretrain_data.json \ + --image_folder /path/to/images \ + --vision_tower openai/clip-vit-large-patch14 \ + --tune_mm_mlp_adapter True \ + --mm_vision_select_layer -2 \ + --mm_use_im_start_end False \ + --mm_use_im_patch_token False \ + --bf16 True \ + --output_dir ./checkpoints/llava-$MODEL_VERSION-pretrain \ + --num_train_epochs 1 \ + --per_device_train_batch_size 16 \ + --per_device_eval_batch_size 4 \ + --gradient_accumulation_steps 1 \ + --evaluation_strategy "no" \ + --save_strategy "steps" \ + --save_steps 24000 \ + --learning_rate 2e-3 \ + --weight_decay 0. \ + --warmup_ratio 0.03 \ + --lr_scheduler_type "cosine" \ + --logging_steps 1 \ + --tf32 True \ + --model_max_length 2048 \ + --gradient_checkpointing True \ + --dataloader_num_workers 16 \ + --lazy_preprocess True \ + --report_to wandb diff --git "a/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/archived/quick_check.py" "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/archived/quick_check.py" new file mode 100644 index 0000000000000000000000000000000000000000..ca7cff9de618e59cfdd84925a9f34c39cde38ff1 --- /dev/null +++ "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/archived/quick_check.py" @@ -0,0 +1,57 @@ +import json +import os +import argparse +from tqdm import tqdm +import yaml + + +def check_missing_images(json_path, images_folder): + data = json.load(open(json_path, "r")) + missing_data = [] + + for i, d in enumerate(tqdm(data)): + image = d["image"] if "image" in d else "" + if image != "": + path = os.path.join(images_folder, image) + if not os.path.exists(path): + print(f"Missing image: {path}") + missing_data.append(d) + + return missing_data + + +def read_yaml_to_llava_data(yaml_path, images_folder): + print(f"Reading YAML file: {yaml_path}") + with open(yaml_path, "r") as f: + data = yaml.safe_load(f) + + llava_json_paths = data["datasets"] + for item in llava_json_paths: + json_path = item["json_path"] + missing_data = check_missing_images(json_path, images_folder) + if len(missing_data) > 0: + print(f"Missing images in {json_path}:") + for d in missing_data: + print(d) + + +def direct_check_llava_data(json_path, images_folder): + missing_data = check_missing_images(json_path, images_folder) + if len(missing_data) > 0: + print(f"Missing images in {json_path}:") + for d in missing_data: + print(d) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description="Check for missing images in dataset.") + parser.add_argument("--yaml_path", type=str, default="", help="Path to the YAML file containing the dataset.") + parser.add_argument("--json_path", type=str, default="", help="Path to the JSON file containing the dataset.") + parser.add_argument("--images_folder", type=str, default="/mnt/bn/vl-research/data/llava_data", help="Path to the folder containing the images.") + + args = parser.parse_args() + + if args.json_path != "": + direct_check_llava_data(args.json_path, args.images_folder) + elif args.yaml_path != "": + read_yaml_to_llava_data(args.yaml_path, args.images_folder) diff --git "a/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/archived/sqa_eval_batch.sh" "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/archived/sqa_eval_batch.sh" new file mode 100644 index 0000000000000000000000000000000000000000..adbf46ef7a6e86181b5927002597ef786add5bde --- /dev/null +++ "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/archived/sqa_eval_batch.sh" @@ -0,0 +1,13 @@ +#!/bin/bash + +CHUNKS=8 +for IDX in {0..7}; do + CUDA_VISIBLE_DEVICES=$IDX python -m llava.eval.model_vqa_science \ + --model-path liuhaotian/llava-lcs558k-scienceqa-vicuna-13b-v1.3 \ + --question-file ~/haotian/datasets/ScienceQA/data/scienceqa/llava_test_QCM-LEA.json \ + --image-folder ~/haotian/datasets/ScienceQA/data/scienceqa/images/test \ + --answers-file ./test_llava-13b-chunk$CHUNKS_$IDX.jsonl \ + --num-chunks $CHUNKS \ + --chunk-idx $IDX \ + --conv-mode llava_v1 & +done diff --git "a/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/archived/sqa_eval_gather.sh" "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/archived/sqa_eval_gather.sh" new file mode 100644 index 0000000000000000000000000000000000000000..525bd43b850e9f6a923158abd23bca6f8d15650e --- /dev/null +++ "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/archived/sqa_eval_gather.sh" @@ -0,0 +1,18 @@ +#!/bin/bash + +CHUNKS=8 +output_file="test_llava-13b.jsonl" + +# Clear out the output file if it exists. +> "$output_file" + +# Loop through the indices and concatenate each file. +for idx in $(seq 0 $((CHUNKS-1))); do + cat "./test_llava-13b-chunk${idx}.jsonl" >> "$output_file" +done + +python llava/eval/eval_science_qa.py \ + --base-dir ~/haotian/datasets/ScienceQA/data/scienceqa \ + --result-file ./test_llava-13b.jsonl \ + --output-file ./test_llava-13b_output.json \ + --output-result ./test_llava-13b_result.json diff --git "a/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/interleave/eval_all.sh" "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/interleave/eval_all.sh" new file mode 100644 index 0000000000000000000000000000000000000000..ee04c6ab8323f1a00d1fc821670106a91d11b786 --- /dev/null +++ "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/interleave/eval_all.sh" @@ -0,0 +1,5 @@ + +# evaluate +./scripts/interleave/eval_interleave_3d.sh /path/to/ckpt /path/to/images multi_image_in_domain +./scripts/interleave/eval_interleave_3d.sh /path/to/ckpt /path/to/images multi_image_out_domain +./scripts/interleave/eval_interleave_3d.sh /path/to/ckpt /path/to/images multi_view_in_domain \ No newline at end of file diff --git "a/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/interleave/eval_interleave_3d.sh" "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/interleave/eval_interleave_3d.sh" new file mode 100644 index 0000000000000000000000000000000000000000..cea796cd72a57eedcca2b671b9f2cdd7572f47ab --- /dev/null +++ "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/interleave/eval_interleave_3d.sh" @@ -0,0 +1,28 @@ +alias python=python3 +CKPT_PATH=$1 +NAME=$(echo "$CKPT_PATH" | awk -F'/' '{print $NF}') +echo $NAME +##### set images path +DATA_PATH=$2 +EVAL_TYPE=$3 +JSON_PATH=$2/$3.json +############################### eval multi-image +RESULT_NAME="logs/${NAME}/${EVAL_TYPE}" +echo $RESULT_NAME + +mkdir -p logs/${NAME} + +file_path=${RESULT_NAME}/result.jsonl + +bash scripts/interleave/eval_multiprocess.sh \ +${CKPT_PATH} \ +${JSON_PATH} \ +${RESULT_NAME} \ +${DATA_PATH} \ +"" \ +8 0 + +python3 llava/eval/evaluate_interleave.py --result-dir ${RESULT_NAME} + + + diff --git "a/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/interleave/eval_multiprocess.sh" "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/interleave/eval_multiprocess.sh" new file mode 100644 index 0000000000000000000000000000000000000000..bab4f725e2873f363a5789ef69cd7cf19a116c92 --- /dev/null +++ "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/interleave/eval_multiprocess.sh" @@ -0,0 +1,54 @@ +#!/bin/bash + +# Check if three arguments are passed +if [ "$#" -ne 7 ]; then + echo "Usage: $0 " + exit 1 +fi + +# Assign the command line arguments to variables +model_path=$1 +question_path=$2 +base_answer_path=$3 +image_folder=$4 +extra_prompt=$5 +N=$6 +temperature=$7 + +# Loop over each chunk/process +for (( chunk_id=0; chunk_id "${base_answer_path}.jsonl" +for ((i=0; i> "${base_answer_path}/result.jsonl" +done +# remove the unmerged files +for (( chunk_id=0; chunk_id They are basically the same as the basic training scripts, but with some modifications, such as the data yaml. + +- `finetune_clip.sh`: This could be seen as the first image version LLaVA-NeXT (2024-01) training script, with `anyres` strategy and maximum 2x2 image grids. +- `finetune_siglip.sh`: Same but with `siglip` encoder, each grid becomes 729 tokens. +- `finetune_onevision.sh`: This is our latest training script, with `anyres_max_9` strategy and image grids weaving from 1x1 to 6x6, at most to 2304x2304 resolution. Inside the script, we also incorporate the multi-image and video data into training loop. the detail token strategy could be found in our paper. + +# About the LLaVA-OneVision Data + +We need to address the fact that our data has been collected and used in different projects/people. LLaVA-OneVision is our first attempt to integrate these datasets. For the data that has already been uploaded, we will refer you to the corresponding locations. We kindly ask everyone to gather the "fragments" and piece them together into a "diamond" in your own environment. + +Here we explain the some technical details on our data. + +- **pretrain data** - BLIP558K (same as previous llava 1.5 series) +- **mid stage data mixture** + ```yaml + datasets: + - json_path: /mnt/bn/vl-research/data/llava_instruct/blip558k_stage1.5_finetune_w_prompt.json + sampling_strategy: all + - json_path: /mnt/bn/vl-research/data/llava_instruct/coco118k_stage1.5_finetune_w_prompt.json + sampling_strategy: all + - json_path: /mnt/bn/vl-research/data/llava_instruct/cc3m_recap_data_prompt_v2.json + sampling_strategy: all + - json_path: /mnt/bn/vl-research/data/llava_instruct/ureader_tr_sft.json + sampling_strategy: all + - json_path: /mnt/bn/vl-research/data/llava_instruct/instruct_azure_dc_zh_92K.json + sampling_strategy: all + - json_path: /mnt/bn/vl-research/data/llava_instruct/allava/Evol-Instruct-GPT4-Turbo-143K.json + sampling_strategy: all + - json_path: /mnt/bn/vl-research/data/llava_instruct/synthdog_zh/synthdog_zh_100k.json + sampling_strategy: all + - json_path: /mnt/bn/vl-research/data/llava_instruct/synthdog_en/synthdog_en_100k.json + sampling_strategy: all + ``` + The first three datasets can be collected via the [LLaVA-Recap](https://huggingface.co/collections/lmms-lab/llava-next-6623288e2d61edba3ddbf5ff) series data. We did a slightly modification to make the data more compatible to other data with an added prompt behind `` at each question. You may download our dataset and process it in local environment. Each data we added the **same prompt** "\nPlease generate detailed descriptions of the given image.". Here's an example: + ```json + { + "id": "000000000009", + "image": "coco/train2017/000000000009.jpg", + "conversations": [ + { + "from": "human", + "value": "\nPlease generate detailed descriptions of the given image." + }, + { + "from": "gpt", + "value": "The image shows a meal served in a blue tray with compartments. In the top left compartment, there is a slice of bread with a spread that appears to be butter, accompanied by a few almonds and a slice of what looks like a baked potato or sweet potato. The top right compartment contains a variety of fruits, including what seems to be pineapple, orange slices, and possibly a piece of melon.\n\nIn the bottom left compartment, there is a piece of bread with a spread that could be butter or margarine, and a small portion of what might be a meatball or a similar type of meat covered in a sauce. The bottom right compartment contains a serving of broccoli, which appears to be steamed or lightly cooked.\n\nThe meal is presented in a way that suggests it is a balanced meal, with a variety of food groups represented carbohydrates (bread), protein (meatball), healthy fats (almonds and butter), and fruits and vegetables (broccoli and the fruit assortment). The image is a close-up photograph with a focus on the food, and the colors are vibrant, indicating freshness." + } + ] + } + ``` + + The rest files are being uploaded to [LLaVA-OneVision Mid-Stage Data](https://huggingface.co/datasets/lmms-lab/LLaVA-OneVision-Mid-Data), except from `instruct_azure_dc_zh_92K` since it's internal data due and have policy issue (sad but I could preview one example). The `instruct_azure_dc_zh_92K` images are from COCO and QAs are generated by GPT-4V service provided by AzureAI. We uses this data in early stage experiments wishing to add Chinese knowledge to our model, and just kept using it (yes, just legacy, no other specific reason). + ```json + { + "id": "000000051920", + "image": "azure_dc_zh_92K/000000051920.jpg", + "conversations": [ + { + "from": "human", + "value": "\n这幅画中的关键信息有哪些?" + }, + { + "from": "gpt", + "value": "这张图片展示了一位穿着深色(可能是黑色或深蓝色)毛衣的人坐在一张桌子前,正在用右手拿着一片披萨。披萨看起来有多种配料,包括绿色的菠菜和橙红色的番茄,放在一个银色的圆形披萨盘上。披萨盘上还剩下大约六片披萨。在背景中,可以看到一个穿着浅色衣服的人站在柜台后面,柜台上方有一个黑板菜单,上面用白色粉笔写着菜单项,但是字迹不清晰,无法阅读。整个场景看起来像是在一个披萨店内部,环境显得比较休闲。" + } + ], + "data_source": "azure_dc_zh_92K" + } + ``` + +- **single-image stage data mixture** + +We have placed our single-image stage data in [single-image-yaml](https://github.com/LLaVA-VL/LLaVA-NeXT/blob/main/scripts/train/single_image.yaml) for users to review. You can download each subset from [onevision-data](https://huggingface.co/datasets/lmms-lab/LLaVA-OneVision-Data). + +Inside the data yaml, the first indicates the previous llava-1.6/next 790K data, you can download them in [llava-next-data](https://huggingface.co/datasets/lmms-lab/LLaVA-NeXT-Data). + +Inside the yaml, the naming would be different with our paper figure due to writing consideration. For users who need to explore our dataset, you can check the [upload script](https://github.com/LLaVA-VL/LLaVA-NeXT/blob/0070d0ae4931c9b19d9cc57c38e16a87c270a61c/playground/upload_data.py#L175) to find the mapping from our local dataset to HF's version. + +- **onevision stage data mixture** + +Our onevision stage data is available in [onevision-yaml](https://github.com/LLaVA-VL/LLaVA-NeXT/blob/main/scripts/train/onevision.yaml). The single-image portion can be downloaded from the above Huggingface link for onevision data. Here's a breakdown of each part: + + - Around 800K higher-quality data re-sampled from the previous stage (yes, it's data replay!). + - Multi-image data is released in [M4-Instruct Data](https://huggingface.co/datasets/lmms-lab/M4-Instruct-Data). We combine the different subsets into two jsons (as they are mainly from DEMON and Mantis) in our training yaml, the jsons are: + - /mnt/bn/vl-research/data/llava_instruct/real_vision_flan/llava_ofa_DEMON-FULL_filtered_311085.json + - /mnt/bn/vl-research/data/llava_instruct/real_vision_flan/llava_ofa_mantis-instruct_reformatted.json + + - Video Data: We have released the video part along with [llava-video-data](https://huggingface.co/datasets/lmms-lab/LLaVA-Video-178K). Users can download the data, and we utilize the subset used in LLaVA-OneVision: + - We have included captions and open-ended questions in the `0_30_s_academic_v0_1` split, along with 240,000 open-ended QA items and 15,000 caption entries, as part of the video data in LLaVA-Hound for LLaVA-OneVision. + - 0_30_s_academic_v0_1 captions + - 0_30_s_academic_v0_1 open-ended QA + - LLaVA-Hound: Same as above. diff --git "a/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/train/direct_finetune_clip.sh" "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/train/direct_finetune_clip.sh" new file mode 100644 index 0000000000000000000000000000000000000000..ad246b413c4ae446056cc8a3c3c1c68d1f84ca31 --- /dev/null +++ "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/train/direct_finetune_clip.sh" @@ -0,0 +1,65 @@ +export OMP_NUM_THREADS=8 +export NCCL_IB_DISABLE=0 +export NCCL_IB_GID_INDEX=3 +export NCCL_SOCKET_IFNAME=eth0 +export NCCL_DEBUG=INFO + +LLM_VERSION="Qwen/Qwen2-7B-Instruct" +LLM_VERSION_CLEAN="${LLM_VERSION//\//_}" +VISION_MODEL_VERSION="openai/clip-vit-large-patch14-336" +VISION_MODEL_VERSION_CLEAN="${VISION_MODEL_VERSION//\//_}" + +############### Pretrain ################ + +PROMPT_VERSION="qwen_1_5" + +BASE_RUN_NAME="llavanext-${VISION_MODEL_VERSION_CLEAN}-${LLM_VERSION_CLEAN}-mlp2x_gelu-pretrain_blip558k_plain" +echo "BASE_RUN_NAME: ${BASE_RUN_NAME}" + +ACCELERATE_CPU_AFFINITY=1 torchrun --nproc_per_node="${NUM_GPUS}" --nnodes="${NNODES}" --node_rank="${RANK}" --master_addr="${ADDR}" --master_port="${PORT}" \ + llava/train/train_mem.py \ + --deepspeed scripts/zero3.json \ + --model_name_or_path ${LLM_VERSION} \ + --version ${PROMPT_VERSION} \ + --data_path=llava_1_6.json \ + --image_folder your_image_folder \ + --pretrain_mm_mlp_adapter="/checkpoints/projectors/${BASE_RUN_NAME}/mm_projector.bin" \ + --mm_tunable_parts="mm_vision_tower,mm_mlp_adapter,mm_language_model" \ + --mm_vision_tower_lr=2e-6 \ + --vision_tower ${VISION_MODEL_VERSION} \ + --mm_projector_type mlp2x_gelu \ + --mm_vision_select_layer -2 \ + --mm_use_im_start_end False \ + --mm_use_im_patch_token False \ + --group_by_modality_length True \ + --image_aspect_ratio anyres \ + --image_grid_pinpoints "[(336, 672), (672, 336), (672, 672), (1008, 336), (336, 1008)]" \ + --mm_patch_merge_type spatial_unpad \ + --bf16 True \ + --run_name $MID_RUN_NAME \ + --output_dir "/checkpoints/${MID_RUN_NAME}" \ + --num_train_epochs 1 \ + --per_device_train_batch_size 4 \ + --per_device_eval_batch_size 4 \ + --gradient_accumulation_steps 1 \ + --evaluation_strategy "no" \ + --save_strategy "steps" \ + --save_steps 3000 \ + --save_total_limit 1 \ + --learning_rate 1e-5 \ + --weight_decay 0. \ + --warmup_ratio 0.03 \ + --lr_scheduler_type "cosine" \ + --logging_steps 1 \ + --tf32 True \ + --model_max_length 32768 \ + --gradient_checkpointing True \ + --dataloader_num_workers 16 \ + --lazy_preprocess True \ + --report_to wandb \ + --torch_compile True \ + --torch_compile_backend "inductor" \ + --dataloader_drop_last True \ + --attn_implementation sdpa + +# You can delete the sdpa attn_implementation if you want to use flash attn diff --git "a/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/train/direct_finetune_siglip_a4.sh" "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/train/direct_finetune_siglip_a4.sh" new file mode 100644 index 0000000000000000000000000000000000000000..2a55cd914e2a5ed400689d11d756c5c2440f0ef6 --- /dev/null +++ "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/train/direct_finetune_siglip_a4.sh" @@ -0,0 +1,67 @@ +export OMP_NUM_THREADS=8 +export NCCL_IB_DISABLE=0 +export NCCL_IB_GID_INDEX=3 +export NCCL_SOCKET_IFNAME=eth0 +export NCCL_DEBUG=INFO + +LLM_VERSION="Qwen/Qwen2-7B-Instruct" +LLM_VERSION_CLEAN="${LLM_VERSION//\//_}" +VISION_MODEL_VERSION="google/siglip-so400m-patch14-384" +VISION_MODEL_VERSION_CLEAN="${VISION_MODEL_VERSION//\//_}" + +############### Pretrain ################ + +PROMPT_VERSION="qwen_1_5" + +BASE_RUN_NAME="llavanext-${VISION_MODEL_VERSION_CLEAN}-${LLM_VERSION_CLEAN}-mlp2x_gelu-pretrain_blip558k_plain" +echo "BASE_RUN_NAME: ${BASE_RUN_NAME}" + +CKPT_PATH=$LLM_VERSION # this could also be the previous stage checkpoint + +ACCELERATE_CPU_AFFINITY=1 torchrun --nproc_per_node="${NUM_GPUS}" --nnodes="${NNODES}" --node_rank="${RANK}" --master_addr="${ADDR}" --master_port="${PORT}" \ + llava/train/train_mem.py \ + --deepspeed scripts/zero3.json \ + --model_name_or_path ${CKPT_PATH} \ + --version ${PROMPT_VERSION} \ + --data_path=llava_1_6.json \ + --image_folder your_image_folder \ + --pretrain_mm_mlp_adapter="/checkpoints/projectors/${BASE_RUN_NAME}/mm_projector.bin" \ + --mm_tunable_parts="mm_vision_tower,mm_mlp_adapter,mm_language_model" \ + --mm_vision_tower_lr=2e-6 \ + --vision_tower ${VISION_MODEL_VERSION} \ + --mm_projector_type mlp2x_gelu \ + --mm_vision_select_layer -2 \ + --mm_use_im_start_end False \ + --mm_use_im_patch_token False \ + --group_by_modality_length True \ + --image_aspect_ratio anyres \ + --image_grid_pinpoints "[(384, 768), (768, 384), (768, 768), (1152, 384), (384, 1152)]" \ + --mm_patch_merge_type spatial_unpad \ + --bf16 True \ + --run_name $MID_RUN_NAME \ + --output_dir "/checkpoints/${MID_RUN_NAME}" \ + --num_train_epochs 1 \ + --per_device_train_batch_size 4 \ + --per_device_eval_batch_size 4 \ + --gradient_accumulation_steps 1 \ + --evaluation_strategy "no" \ + --save_strategy "steps" \ + --save_steps 3000 \ + --save_total_limit 1 \ + --learning_rate 1e-5 \ + --weight_decay 0. \ + --warmup_ratio 0.03 \ + --lr_scheduler_type "cosine" \ + --logging_steps 1 \ + --tf32 True \ + --model_max_length 32768 \ + --gradient_checkpointing True \ + --dataloader_num_workers 16 \ + --lazy_preprocess True \ + --report_to wandb \ + --torch_compile True \ + --torch_compile_backend "inductor" \ + --dataloader_drop_last True \ + --attn_implementation sdpa + +# You can delete the sdpa attn_implementation if you want to use flash attn diff --git "a/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/train/dpo.sh" "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/train/dpo.sh" new file mode 100644 index 0000000000000000000000000000000000000000..83bfe84121e56ed615f450305da39822b780b667 --- /dev/null +++ "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/train/dpo.sh" @@ -0,0 +1,64 @@ +export OMP_NUM_THREADS=8 +export NCCL_IB_DISABLE=0 +export NCCL_IB_GID_INDEX=3 +# export NCCL_IB_HCA=${ARNOLD_RDMA_DEVICE} +export NCCL_SOCKET_IFNAME=eth0 +export NCCL_DEBUG=INFO + +VISION_MODEL_VERSION="openai/clip-vit-large-patch14-336" +VISION_MODEL_VERSION_CLEAN="${VISION_MODEL_VERSION//\//_}" + +############### Pretrain ################ + +# Stage 2 +PROMPT_VERSION="qwen_1_5" + +#torchrun --nproc_per_node="${ARNOLD_WORKER_GPU}" --nnodes="${ARNOLD_WORKER_NUM}" --node_rank="${ARNOLD_ID}" --master_addr="${METIS_WORKER_0_HOST}" --master_port="${port_in_cmd}" \ +ACCELERATE_CPU_AFFINITY=1 torchrun --nproc_per_node="${ARNOLD_WORKER_GPU}" --nnodes="${ARNOLD_WORKER_NUM}" --node_rank="${ARNOLD_ID}" --master_addr="${METIS_WORKER_0_HOST}" --master_port="${port_in_cmd}" \ + llava/train/train_dpo.py \ + --deepspeed scripts/zero3.json \ + --model_name_or_path lmms-lab/LongVA-7B \ + --version $PROMPT_VERSION \ + --dpo_alpha 1.0 --beta 0.1 --gamma 0 \ + --data_path="/data/llava_video/shareVideoGPTV/dpo/sft_dpo_17k.jsonl" \ + --image_folder /data/llava_data \ + --video_folder /llava_video/shareVideoGPTV/frames/all_frames/ \ + --mm_tunable_parts="mm_vision_tower,mm_mlp_adapter,mm_language_model" \ + --vision_tower ${VISION_MODEL_VERSION} \ + --mm_projector_type mlp2x_gelu \ + --mm_vision_select_layer -2 \ + --mm_use_im_start_end False \ + --mm_use_im_patch_token False \ + --mm_spatial_pool_stride 2 \ + --mm_resampler_type "spatial_pool" \ + --mm_spatial_pool_out_channels 1024 \ + --group_by_modality_length True \ + --image_aspect_ratio anyres \ + --image_grid_pinpoints "[(336, 672), (672, 336), (672, 672), (1008, 336), (336, 1008)]" \ + --mm_patch_merge_type unires \ + --bf16 True \ + --run_name $MID_RUN_NAME \ + --output_dir "/checkpoints/${MID_RUN_NAME}" \ + --num_train_epochs 3 \ + --per_device_train_batch_size 1 \ + --per_device_eval_batch_size 4 \ + --gradient_accumulation_steps 16 \ + --evaluation_strategy "no" \ + --save_strategy "steps" \ + --save_steps 3000 \ + --save_total_limit 1 \ + --learning_rate 5e-7 \ + --weight_decay 0. \ + --warmup_ratio 0.1 \ + --lr_scheduler_type "linear" \ + --logging_steps 1 \ + --tf32 True \ + --model_max_length 32768 \ + --gradient_checkpointing True \ + --dataloader_num_workers 16 \ + --lazy_preprocess True \ + --report_to wandb \ + --torch_compile True \ + --torch_compile_backend "inductor" \ + --dataloader_drop_last True \ + --attn_implementation sdpa \ No newline at end of file diff --git "a/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/train/dpo_ov7b.sh" "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/train/dpo_ov7b.sh" new file mode 100644 index 0000000000000000000000000000000000000000..26748e4b1710ec41ab88eb455933a238a439faf5 --- /dev/null +++ "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/train/dpo_ov7b.sh" @@ -0,0 +1,69 @@ +export OMP_NUM_THREADS=8 +export NCCL_IB_DISABLE=0 +export NCCL_IB_GID_INDEX=3 +# export NCCL_IB_HCA=${ARNOLD_RDMA_DEVICE} +export NCCL_SOCKET_IFNAME=eth0 +export NCCL_DEBUG=INFO + +VISION_MODEL_VERSION="google/siglip-so400m-patch14-384" +VISION_MODEL_VERSION_CLEAN="${VISION_MODEL_VERSION//\//_}" + +# DPO Stage +PROMPT_VERSION="qwen_1_5" +SFT_MODEL="lmms-lab/llava-onevision-qwen2-7b-ov" +EPOCH=1 +beta=0.1 + +DPO_RUN_NAME="llava-onevision-qwen2-7b-ov_dpo-beta${beta}-epoch${EPOCH}" +DPO_CLEAN_NAME="${DPO_RUN_NAME##*/}" +OUTPUT_DIR="/${DPO_CLEAN_NAME}" +DATA_PATH="" + +echo $DPO_RUN_NAME + +ACCELERATE_CPU_AFFINITY=1 torchrun --nproc_per_node="${NUM_GPUS}" --nnodes="${NNODES}" --node_rank="${RANK}" --master_addr="${ADDR}" --master_port="${PORT}" \ + llava/train/train_dpo.py \ + --deepspeed scripts/zero3.json \ + --model_name_or_path=${SFT_MODEL} \ + --dpo_alpha=1.0 \ + --beta=${beta} \ + --gamma=0 \ + --version $PROMPT_VERSION \ + --data_path=$DATA_PATH \ + --image_folder "" \ + --mm_tunable_parts="mm_vision_tower,mm_mlp_adapter,mm_language_model" \ + --unfreeze_mm_vision_tower True \ + --vision_tower ${VISION_MODEL_VERSION} \ + --mm_projector_type mlp2x_gelu \ + --mm_vision_select_layer -2 \ + --mm_use_im_start_end False \ + --mm_use_im_patch_token False \ + --group_by_modality_length True \ + --image_aspect_ratio anyres_max_9 \ + --image_grid_pinpoints "(1x1),...,(6x6)" \ + --mm_patch_merge_type spatial_unpad \ + --bf16 True \ + --run_name $DPO_CLEAN_NAME \ + --output_dir $OUTPUT_DIR \ + --num_train_epochs $EPOCH \ + --per_device_train_batch_size 1 \ + --per_device_eval_batch_size 1 \ + --gradient_accumulation_steps 8 \ + --evaluation_strategy "no" \ + --save_strategy "steps" \ + --save_steps 1000 \ + --save_total_limit 1 \ + --learning_rate 5e-7 \ + --weight_decay 0. \ + --warmup_ratio 0.1 \ + --lr_scheduler_type "cosine" \ + --logging_steps 1 \ + --tf32 True \ + --model_max_length 32768 \ + --gradient_checkpointing True \ + --dataloader_num_workers 4 \ + --lazy_preprocess True \ + --report_to wandb \ + --dataloader_drop_last True + + diff --git "a/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/train/finetune_ov.sh" "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/train/finetune_ov.sh" new file mode 100644 index 0000000000000000000000000000000000000000..0a4526684481f3dec5cc987ac4c8e989c4d62994 --- /dev/null +++ "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/train/finetune_ov.sh" @@ -0,0 +1,75 @@ +export OMP_NUM_THREADS=8 +export NCCL_IB_DISABLE=0 +export NCCL_IB_GID_INDEX=3 +export NCCL_SOCKET_IFNAME=eth0 +export NCCL_DEBUG=INFO + +LLM_VERSION="Qwen/Qwen2-7B-Instruct" +# for 7b model we recommend bs=1, accum=2, 16 nodes, 128 gpus, lr=1e-5, warmup=0.03 +# for 72b model we recommend bs=1, accum=1, 32 nodes, 256 gpus, lr=1e-5, warmup=0.03 +LLM_VERSION_CLEAN="${LLM_VERSION//\//_}" +VISION_MODEL_VERSION="google/siglip-so400m-patch14-384" +VISION_MODEL_VERSION_CLEAN="${VISION_MODEL_VERSION//\//_}" + +############### Pretrain ################ + +BASE_RUN_NAME="llavanext-google_siglip-so400m-patch14-384-Qwen_Qwen2-7B-Instruct-mlp2x_gelu-pretrain_blip558k_plain" +echo "BASE_RUN_NAME: ${BASE_RUN_NAME}" + +############### Finetune ################ + +# Stage 2 +PROMPT_VERSION="qwen_1_5" +RUN_NAME="llava-onevision-${VISION_MODEL_VERSION_CLEAN}-${LLM_VERSION_CLEAN}-ov_stage_am9" +PREV_STAGE_CHECKPOINT="/mnt/bn/vl-research/checkpoints/onevision/llavanext-google_siglip-so400m-patch14-384-Qwen_Qwen2-7B-Instruct-mid_to_final_next_3m_am9_july14" # replace it with your last checkpoint training from single image collection +echo "PREV_STAGE_CHECKPOINT: ${PREV_STAGE_CHECKPOINT}" +echo "MID_RUN_NAME: ${RUN_NAME}" + +ACCELERATE_CPU_AFFINITY=1 torchrun --nproc_per_node="${NUM_GPUS}" --nnodes="${NNODES}" --node_rank="${RANK}" --master_addr="${ADDR}" --master_port="${PORT}" \ + llava/train/train_mem.py \ + --deepspeed scripts/zero3.json \ + --model_name_or_path $PREV_STAGE_CHECKPOINT \ + --version $PROMPT_VERSION \ + --data_path /mnt/bn/vl-research/workspace/boli01/projects/LLaVA_Next/scripts/i18n/scale_llms/next_ov_stage_july21.yaml \ + --image_folder /mnt/bn/vl-research/data/llava_data \ + --video_folder /mnt/bn/vl-research/data/llava_video \ + --mm_tunable_parts="mm_vision_tower,mm_mlp_adapter,mm_language_model" \ + --mm_vision_tower_lr=2e-6 \ + --vision_tower ${VISION_MODEL_VERSION} \ + --mm_projector_type mlp2x_gelu \ + --mm_vision_select_layer -2 \ + --mm_use_im_start_end False \ + --mm_use_im_patch_token False \ + --group_by_modality_length True \ + --image_aspect_ratio anyres_max_9 \ + --image_grid_pinpoints "(1x1),...,(6x6)" \ + --mm_patch_merge_type spatial_unpad \ + --bf16 True \ + --run_name $RUN_NAME \ + --output_dir /mnt/bn/vl-research/checkpoints/onevision/$RUN_NAME \ + --num_train_epochs 1 \ + --per_device_train_batch_size 1 \ + --per_device_eval_batch_size 4 \ + --gradient_accumulation_steps 2 \ + --evaluation_strategy "no" \ + --save_strategy "steps" \ + --save_steps 1000 \ + --save_total_limit 1 \ + --learning_rate 1e-5 \ + --weight_decay 0. \ + --warmup_ratio 0.03 \ + --lr_scheduler_type "cosine" \ + --logging_steps 1 \ + --tf32 True \ + --model_max_length 32768 \ + --gradient_checkpointing True \ + --dataloader_num_workers 4 \ + --lazy_preprocess True \ + --report_to wandb \ + --torch_compile True \ + --torch_compile_backend "inductor" \ + --dataloader_drop_last True \ + --frames_upbound 32 +exit 0; + +# You can delete the sdpa attn_implementation if you want to use flash attn diff --git "a/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/train/finetune_si.sh" "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/train/finetune_si.sh" new file mode 100644 index 0000000000000000000000000000000000000000..32768f30647be88c331532d17c08dcdca7c1c989 --- /dev/null +++ "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/train/finetune_si.sh" @@ -0,0 +1,73 @@ +export OMP_NUM_THREADS=8 +export NCCL_IB_DISABLE=0 +export NCCL_IB_GID_INDEX=3 +export NCCL_SOCKET_IFNAME=eth0 +export NCCL_DEBUG=INFO + +LLM_VERSION="Qwen/Qwen2-7B-Instruct" +# for 7b model we recommend bs=1, accum=2, 16 nodes, 128 gpus, lr=1e-5, warmup=0.03 +# for 72b model we recommend bs=1, accum=1, 32 nodes, 256 gpus, lr=1e-5, warmup=0.03 +LLM_VERSION_CLEAN="${LLM_VERSION//\//_}" +VISION_MODEL_VERSION="google/siglip-so400m-patch14-384" +VISION_MODEL_VERSION_CLEAN="${VISION_MODEL_VERSION//\//_}" + +############### Pretrain ################ + +BASE_RUN_NAME="llavanext-google_siglip-so400m-patch14-384-Qwen_Qwen2-7B-Instruct-mlp2x_gelu-pretrain_blip558k_plain" +echo "BASE_RUN_NAME: ${BASE_RUN_NAME}" + +############### Finetune ################ + +# Stage 2 +PROMPT_VERSION="qwen_1_5" +RUN_NAME="llava-onevision-${VISION_MODEL_VERSION_CLEAN}-${LLM_VERSION_CLEAN}-si_stage_am9" +PREV_STAGE_CHECKPOINT="/mnt/bn/vl-research/checkpoints/onevision/xxxxxxxxxxxxxxxx" # replace it with your last checkpoint training from mid stage +echo "PREV_STAGE_CHECKPOINT: ${PREV_STAGE_CHECKPOINT}" +echo "MID_RUN_NAME: ${RUN_NAME}" + +ACCELERATE_CPU_AFFINITY=1 torchrun --nproc_per_node="${NUM_GPUS}" --nnodes="${NNODES}" --node_rank="${RANK}" --master_addr="${ADDR}" --master_port="${PORT}" \ + llava/train/train_mem.py \ + --deepspeed scripts/zero3.json \ + --model_name_or_path $PREV_STAGE_CHECKPOINT \ + --version $PROMPT_VERSION \ + --data_path /mnt/bn/vl-research/workspace/boli01/projects/LLaVA_Next/scripts/i18n/scale_llms/next_3p2m_single_image.yaml \ + --image_folder /mnt/bn/vl-research/data/llava_data \ + --video_folder /mnt/bn/vl-research/data/llava_video \ + --mm_tunable_parts="mm_vision_tower,mm_mlp_adapter,mm_language_model" \ + --mm_vision_tower_lr=2e-6 \ + --vision_tower ${VISION_MODEL_VERSION} \ + --mm_projector_type mlp2x_gelu \ + --mm_vision_select_layer -2 \ + --mm_use_im_start_end False \ + --mm_use_im_patch_token False \ + --group_by_modality_length True \ + --image_aspect_ratio anyres_max_9 \ + --image_grid_pinpoints "(1x1),...,(6x6)" \ + --mm_patch_merge_type spatial_unpad \ + --bf16 True \ + --run_name $RUN_NAME \ + --output_dir /mnt/bn/vl-research/checkpoints/onevision/$RUN_NAME \ + --num_train_epochs 1 \ + --per_device_train_batch_size 1 \ + --per_device_eval_batch_size 4 \ + --gradient_accumulation_steps 2 \ + --evaluation_strategy "no" \ + --save_strategy "steps" \ + --save_steps 1000 \ + --save_total_limit 1 \ + --learning_rate 1e-5 \ + --weight_decay 0. \ + --warmup_ratio 0.03 \ + --lr_scheduler_type "cosine" \ + --logging_steps 1 \ + --tf32 True \ + --model_max_length 32768 \ + --gradient_checkpointing True \ + --dataloader_num_workers 4 \ + --lazy_preprocess True \ + --report_to wandb \ + --torch_compile True \ + --torch_compile_backend "inductor" \ + --dataloader_drop_last True \ + --frames_upbound 32 +exit 0; diff --git "a/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/train/mid_stage.yaml" "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/train/mid_stage.yaml" new file mode 100644 index 0000000000000000000000000000000000000000..566998719fdeb3837e097da88014db56f380fd66 --- /dev/null +++ "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/train/mid_stage.yaml" @@ -0,0 +1,17 @@ +datasets: + - json_path: /mnt/bn/vl-research/data/llava_instruct/blip558k_stage1.5_finetune_w_prompt.json # released in lmms-lab/LLaVA-ReCap-* + sampling_strategy: all + - json_path: /mnt/bn/vl-research/data/llava_instruct/coco118k_stage1.5_finetune_w_prompt.json # released in lmms-lab/LLaVA-ReCap-* + sampling_strategy: all + - json_path: /mnt/bn/vl-research/data/llava_instruct/cc3m_recap_data_prompt_v2.json # released in lmms-lab/LLaVA-ReCap-* + sampling_strategy: all + - json_path: /mnt/bn/vl-research/data/llava_instruct/ureader_tr_sft.json # released in lmms-lab/LLaVA-OneVision-Mid-Data + sampling_strategy: all + - json_path: /mnt/bn/vl-research/data/llava_instruct/instruct_azure_dc_zh_92K.json # not released, explained at https://github.com/LLaVA-VL/LLaVA-NeXT/tree/main/scripts/train + sampling_strategy: all + - json_path: /mnt/bn/vl-research/data/llava_instruct/Evol-Instruct-GPT4-Turbo-143K.json # released in lmms-lab/LLaVA-OneVision-Mid-Data + sampling_strategy: all + - json_path: /mnt/bn/vl-research/data/llava_instruct/synthdog_zh/synthdog_zh_100k.json # released in lmms-lab/LLaVA-OneVision-Mid-Data + sampling_strategy: all + - json_path: /mnt/bn/vl-research/data/llava_instruct/synthdog_en/synthdog_en_100k.json # released in lmms-lab/LLaVA-OneVision-Mid-Data + sampling_strategy: all \ No newline at end of file diff --git "a/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/train/onevision.yaml" "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/train/onevision.yaml" new file mode 100644 index 0000000000000000000000000000000000000000..117a5e8f97ebf64840a5bbd4b2edf2acf100a617 --- /dev/null +++ "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/train/onevision.yaml" @@ -0,0 +1,185 @@ +datasets: + - json_path: /mnt/bn/vl-research/data/llava_instruct/real_vision_flan/llava_next_fit_mix_filtered_text_wild_738590.json + sampling_strategy: "first:50%" + - json_path: /mnt/bn/vl-research/data/llava_instruct/real_vision_flan/llava_wild_4v_39k.json # not released + sampling_strategy: "first:10%" + - json_path: /mnt/bn/vl-research/data/llava_instruct/real_vision_flan/llava_wild_4v_12k.json # not released + sampling_strategy: "first:10%" + - json_path: /mnt/bn/vl-research/data/llava_instruct/real_vision_flan/mavis_math_metagen_87358.json + sampling_strategy: "first:10%" + - json_path: /mnt/bn/vl-research/data/llava_instruct/real_vision_flan/mavis_math_rule_geo_100000.json + sampling_strategy: "first:10%" + - json_path: /mnt/bn/vl-research/data/llava_instruct/real_vision_flan/cambrian_filtered_gpt4vo_sp_token_fltd_max10k_checked.json + sampling_strategy: "all" + - json_path: /mnt/bn/vl-research/data/llava_instruct/real_vision_flan/VisualWebInstruct_filtered_263589.json + sampling_strategy: "all" + - json_path: /mnt/bn/vl-research/data/llava_instruct/real_vision_flan/visual_chat_en_26048_gpt4o_coco_checked.json # not released + sampling_strategy: "all" + # - json_path: /mnt/bn/vl-research/data/llava_instruct/real_vision_flan/gpt4o_combinations_51316.json + # sampling_strategy: "all" + # - json_path: /mnt/bn/vl-research/data/llava_instruct/real_vision_flan/chrome_writting_train_8835.json + # sampling_strategy: "first:20%" + # - json_path: /mnt/bn/vl-research/data/llava_instruct/real_vision_flan/k12_printing_train_256646.json + # sampling_strategy: "first:1%" + # - json_path: /mnt/bn/vl-research/data/llava_instruct/real_vision_flan/iiit5k_annotations_2000.json + # sampling_strategy: "first:20%" + # - json_path: /mnt/bn/vl-research/data/llava_instruct/real_vision_flan/hme100k_train_clean_74502.json + # sampling_strategy: "first:10%" + # - json_path: /mnt/bn/vl-research/data/llava_instruct/real_vision_flan/sroie_data_33626.json + # sampling_strategy: "first:1%" + # - json_path: /mnt/bn/vl-research/data/llava_instruct/real_vision_flan/orand_car_a_train_2009.json + # sampling_strategy: "first:10%" + # - json_path: /mnt/bn/vl-research/data/llava_instruct/real_vision_flan/orand_car_b_train_3000.json + # sampling_strategy: "first:10%" + - json_path: /mnt/bn/vl-research/data/llava_instruct/real_vision_flan/llavar_gpt4_20k.json + sampling_strategy: "first:10%" + - json_path: /mnt/bn/vl-research/data/llava_instruct/real_vision_flan/ai2d_azuregpt_detailed_understanding_4874.json + sampling_strategy: "all" + - json_path: /mnt/bn/vl-research/data/llava_instruct/real_vision_flan/infographic_vqa_4404.json + sampling_strategy: "all" + - json_path: /mnt/bn/vl-research/data/llava_instruct/real_vision_flan/infographic_azuregpt4v_1992.json + sampling_strategy: "all" + - json_path: /mnt/bn/vl-research/data/llava_instruct/real_vision_flan/lrv_chart_1787.json + sampling_strategy: "all" + - json_path: /mnt/bn/vl-research/data/llava_instruct/real_vision_flan/lrv_normal_gpt4v_filtered_10500.json + sampling_strategy: "first:10%" + # - json_path: /mnt/bn/vl-research/data/llava_instruct/real_vision_flan/scienceqa_nona_context_19218.json + # sampling_strategy: "first:10%" + - json_path: /mnt/bn/vl-research/data/llava_instruct/real_vision_flan/allava_instruct_vflan4v_20000.json + sampling_strategy: "first:30%" + - json_path: /mnt/bn/vl-research/data/llava_instruct/real_vision_flan/allava_instruct_laion4v_50000.json + sampling_strategy: "first:30%" + - json_path: /mnt/bn/vl-research/data/llava_instruct/real_vision_flan/textocr_gpt4v_train_converted_25114.json + sampling_strategy: "first:10%" + - json_path: /mnt/bn/vl-research/data/llava_instruct/real_vision_flan/ai2d_train_internvl_single_12413.json + sampling_strategy: "first:10%" + - json_path: /mnt/bn/vl-research/data/llava_instruct/real_vision_flan/textcaps_train_21952.json + sampling_strategy: "first:10%" + - json_path: /mnt/bn/vl-research/data/llava_instruct/ureader_new/ureader_qa_sft.json + sampling_strategy: "first:10%" + - json_path: /mnt/bn/vl-research/data/llava_instruct/ureader_new/ureader_cap_sft.json + sampling_strategy: "first:10%" + - json_path: /mnt/bn/vl-research/data/llava_instruct/ureader_new/ureader_ie_sft.json + sampling_strategy: "first:10%" + - json_path: /mnt/bn/vl-research/data/llava_instruct/ureader_new/ureader_kg_sft.json + sampling_strategy: "first:10%" + - json_path: /mnt/bn/vl-research/data/llava_instruct/real_vision_flan/vision_flan_filtered_186070.json + sampling_strategy: "all" + - json_path: /mnt/bn/vl-research/data/llava_instruct/real_vision_flan/mathqa_29837.json + sampling_strategy: "all" + - json_path: /mnt/bn/vl-research/data/llava_instruct/real_vision_flan/geo3k_2101.json + sampling_strategy: "all" + - json_path: /mnt/bn/vl-research/data/llava_instruct/real_vision_flan/geo170k_qa_converted_67833.json + sampling_strategy: "first:10%" + - json_path: /mnt/bn/vl-research/data/llava_instruct/real_vision_flan/geo170k_align_converted_60252.json + sampling_strategy: "first:10%" + - json_path: /mnt/bn/vl-research/data/llava_instruct/real_vision_flan/sharegpt4o_dataset.jsonl + sampling_strategy: "all" + - json_path: /mnt/bn/vl-research/data/llava_instruct/real_vision_flan/sharegpt4v-coco-50k.json + sampling_strategy: "all" + - json_path: /mnt/bn/vl-research/data/llava_instruct/real_vision_flan/sharegpt4v-knowledge-2k.json + sampling_strategy: "all" + - json_path: /mnt/bn/vl-research/data/llava_instruct/real_vision_flan/sharegpt4v-llava-30k.json + sampling_strategy: "all" + - json_path: /mnt/bn/vl-research/data/llava_instruct/real_vision_flan/sharegpt4v-sam-20k.json + sampling_strategy: "all" + - json_path: /mnt/bn/vl-research/data/llava_instruct/real_vision_flan/MathV360K_CLEVR-Math_5290.json + sampling_strategy: "first:10%" + - json_path: /mnt/bn/vl-research/data/llava_instruct/real_vision_flan/MathV360K_FigureQA_17597.json + sampling_strategy: "first:10%" + - json_path: /mnt/bn/vl-research/data/llava_instruct/real_vision_flan/MathV360K_Geometry3K_9734.json + sampling_strategy: "first:10%" + - json_path: /mnt/bn/vl-research/data/llava_instruct/real_vision_flan/MathV360K_GeoQA+_17172.json + sampling_strategy: "first:10%" + - json_path: /mnt/bn/vl-research/data/llava_instruct/real_vision_flan/MathV360K_GEOS_508.json + sampling_strategy: "all" + - json_path: /mnt/bn/vl-research/data/llava_instruct/real_vision_flan/MathV360K_IconQA_22599.json + sampling_strategy: "first:5%" + - json_path: /mnt/bn/vl-research/data/llava_instruct/real_vision_flan/MathV360K_MapQA_5235.json + sampling_strategy: "first:10%" + - json_path: /mnt/bn/vl-research/data/llava_instruct/real_vision_flan/MathV360K_PlotQA_5485.json + sampling_strategy: "first:10%" + - json_path: /mnt/bn/vl-research/data/llava_instruct/real_vision_flan/MathV360K_PMC-VQA_35958.json + sampling_strategy: "first:1%" + - json_path: /mnt/bn/vl-research/data/llava_instruct/real_vision_flan/MathV360K_Super-CLEVR_8652.json + sampling_strategy: "first:10%" + - json_path: /mnt/bn/vl-research/data/llava_instruct/real_vision_flan/MathV360K_TabMWP_22462.json + sampling_strategy: "first:10%" + - json_path: /mnt/bn/vl-research/data/llava_instruct/real_vision_flan/MathV360K_TQA_10181.json + sampling_strategy: "first:10%" + - json_path: /mnt/bn/vl-research/data/llava_instruct/real_vision_flan/MathV360K_UniGeo_11959.json + sampling_strategy: "first:10%" + - json_path: /mnt/bn/vl-research/data/llava_instruct/real_vision_flan/MathV360K_VizWiz_6614.json + sampling_strategy: "first:10%" + - json_path: /mnt/bn/vl-research/data/llava_instruct/real_vision_flan/MathV360K_VQA-AS_5907.json + sampling_strategy: "first:10%" + - json_path: /mnt/bn/vl-research/data/llava_instruct/real_vision_flan/MathV360K_VQA-RAD_2130.json + sampling_strategy: "first:10%" + - json_path: /mnt/bn/vl-research/data/llava_instruct/real_vision_flan/magpie_pro_qwen2_72b_st_300000_sp_token_fltd_299992.json + sampling_strategy: "end:20%" + - json_path: /mnt/bn/vl-research/data/llava_instruct/real_vision_flan/magpie_pro_l3_80b_st_300000.json + sampling_strategy: "end:20%" + - json_path: /mnt/bn/vl-research/data/llava_instruct/real_vision_flan/magpie_pro_l3_80b_mt_300000_sp_token_fltd_299998.json + sampling_strategy: "end:20%" + - json_path: /mnt/bn/vl-research/data/llava_instruct/real_vision_flan/image_textualization_dataset_filtered.json + sampling_strategy: "first:20%" + - json_path: /mnt/bn/vl-research/data/llava_instruct/cauldron/ai2d_llava_format_2434.json + sampling_strategy: "all" + - json_path: /mnt/bn/vl-research/data/llava_instruct/cauldron/chart2text_26961.json + sampling_strategy: "first:10%" + - json_path: /mnt/bn/vl-research/data/llava_instruct/cauldron/chartqa_18265_llava_format.json + sampling_strategy: "first:10%" + - json_path: /mnt/bn/vl-research/data/llava_instruct/cauldron/diagram_image_to_text_300.json + sampling_strategy: "all" + - json_path: /mnt/bn/vl-research/data/llava_instruct/cauldron/hateful_memes_8500_llava_format.json + sampling_strategy: "first:10%" + - json_path: /mnt/bn/vl-research/data/llava_instruct/cauldron/hitab_2500_llava_format.json + sampling_strategy: "first:10%" + - json_path: /mnt/bn/vl-research/data/llava_instruct/cauldron/iam_5663.json + sampling_strategy: "first:10%" + - json_path: /mnt/bn/vl-research/data/llava_instruct/cauldron/infographic_vqa_2118_llava_format.json + sampling_strategy: "first:10%" + - json_path: /mnt/bn/vl-research/data/llava_instruct/cauldron/intergps_1280_llava_format.json + sampling_strategy: "first:10%" + - json_path: /mnt/bn/vl-research/data/llava_instruct/cauldron/mapqa_37417_llava_format.json + sampling_strategy: "first:10%" + - json_path: /mnt/bn/vl-research/data/llava_instruct/cauldron/rendered_text_10000.json + sampling_strategy: "first:10%" + - json_path: /mnt/bn/vl-research/data/llava_instruct/cauldron/robut_sqa_8514.json + sampling_strategy: "first:10%" + - json_path: /mnt/bn/vl-research/data/llava_instruct/cauldron/robut_wikisql_74989.json + sampling_strategy: "first:10%" + # - json_path: /mnt/bn/vl-research/data/llava_instruct/cauldron/robut_wtq_38246_llava_format_filtered_4000tokens_38236.json + # sampling_strategy: "first:10%" + - json_path: /mnt/bn/vl-research/data/llava_instruct/cauldron/screen2words_15730.json + sampling_strategy: "first:10%" + - json_path: /mnt/bn/vl-research/data/llava_instruct/cauldron/tabmwp_22722.json + sampling_strategy: "first:5%" + - json_path: /mnt/bn/vl-research/data/llava_instruct/cauldron/tallyqa_98680_llava_format.json + sampling_strategy: "first:5%" + - json_path: /mnt/bn/vl-research/data/llava_instruct/cauldron/st_vqa_17247_llava_format.json + sampling_strategy: "first:10%" + - json_path: /mnt/bn/vl-research/data/llava_instruct/cauldron/tqa_llava_format_27307.json + sampling_strategy: "first:5%" + - json_path: /mnt/bn/vl-research/data/llava_instruct/cauldron/visual7w_llava_format_14366.json + sampling_strategy: "first:10%" + - json_path: /mnt/bn/vl-research/data/llava_instruct/cauldron/visualmrc_3027.json + sampling_strategy: "first:10%" + - json_path: /mnt/bn/vl-research/data/llava_instruct/cauldron/vqarad_313_llava_format.json + sampling_strategy: "first:10%" + - json_path: /mnt/bn/vl-research/data/llava_instruct/cauldron/vsr_2157_llava_format.json + sampling_strategy: "first:10%" + - json_path: /mnt/bn/vl-research/data/llava_instruct/cauldron/vistext_9969.json + sampling_strategy: "first:10%" + - json_path: /mnt/bn/vl-research/data/llava_instruct/cauldron/websight_10000.json + sampling_strategy: "first:10%" + - json_path: /mnt/bn/vl-research/data/llava_instruct/real_vision_flan/llava_ofa_DEMON-FULL_filtered_311085.json # released in lmms-lab/M4-Instruct + sampling_strategy: all + - json_path: /mnt/bn/vl-research/data/llava_instruct/real_vision_flan/llava_ofa_mantis-instruct_reformatted.json # released in lmms-lab/M4-Instruct + sampling_strategy: all + - json_path: /mnt/bn/vl-research/data/llava_instruct/real_vision_flan/academic_source_30s_v1_all.json # will be released in next version of LLaVA-NeXT-Video + sampling_strategy: all + - json_path: /mnt/bn/vl-research/data/llava_instruct/real_vision_flan/0718_0_30_s_academic_mc_v0_1_all.json # will be released in next version of LLaVA-NeXT-Video + sampling_strategy: all + - json_path: /mnt/bn/vl-research/data/llava_instruct/real_vision_flan/sharegpt4video_255000.json # download from sharegpt4video + sampling_strategy: all diff --git "a/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/train/pretrain_clip.sh" "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/train/pretrain_clip.sh" new file mode 100644 index 0000000000000000000000000000000000000000..2eb5c27e686ba69a486bd78312b08802fbb7130e --- /dev/null +++ "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/train/pretrain_clip.sh" @@ -0,0 +1,55 @@ +export OMP_NUM_THREADS=8 +export NCCL_IB_DISABLE=0 +export NCCL_IB_GID_INDEX=3 +export NCCL_SOCKET_IFNAME=eth0 +export NCCL_DEBUG=INFO + +LLM_VERSION="Qwen/Qwen2-7B-Instruct" +LLM_VERSION_CLEAN="${LLM_VERSION//\//_}" +VISION_MODEL_VERSION="openai/clip-vit-large-patch14-336" +VISION_MODEL_VERSION_CLEAN="${VISION_MODEL_VERSION//\//_}" + +############### Pretrain ################ + +PROMPT_VERSION=plain + +BASE_RUN_NAME="llavanext-${VISION_MODEL_VERSION_CLEAN}-${LLM_VERSION_CLEAN}-mlp2x_gelu-pretrain_blip558k_plain" +echo "BASE_RUN_NAME: ${BASE_RUN_NAME}" + +ACCELERATE_CPU_AFFINITY=1 torchrun --nproc_per_node="${NUM_GPUS}" --nnodes="${NNODES}" --node_rank="${RANK}" --master_addr="${ADDR}" --master_port="${PORT}" \ + llava/train/train_mem.py \ + --deepspeed scripts/zero3.json \ + --model_name_or_path ${LLM_VERSION} \ + --version ${PROMPT_VERSION} \ + --data_path /blip_558k/blip_558k_plain.json \ + --image_folder /blip_558k/images \ + --vision_tower ${VISION_MODEL_VERSION} \ + --mm_tunable_parts="mm_mlp_adapter" \ + --mm_vision_select_layer -2 \ + --mm_projector_type mlp2x_gelu \ + --mm_use_im_start_end False \ + --mm_use_im_patch_token False \ + --bf16 True \ + --output_dir /checkpoints/projectors/${BASE_RUN_NAME} \ + --num_train_epochs 1 \ + --per_device_train_batch_size 16 \ + --per_device_eval_batch_size 4 \ + --gradient_accumulation_steps 1 \ + --evaluation_strategy "no" \ + --save_strategy "no" \ + --save_steps 50000 \ + --learning_rate 1e-3 \ + --weight_decay 0. \ + --warmup_ratio 0.03 \ + --lr_scheduler_type "cosine" \ + --logging_steps 1 \ + --tf32 True \ + --model_max_length 8192 \ + --gradient_checkpointing True \ + --dataloader_num_workers 16 \ + --lazy_preprocess True \ + --report_to wandb \ + --run_name $BASE_RUN_NAME \ + --attn_implementation sdpa + +# You can delete the sdpa attn_implementation if you want to use flash attn \ No newline at end of file diff --git "a/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/train/pretrain_siglip.sh" "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/train/pretrain_siglip.sh" new file mode 100644 index 0000000000000000000000000000000000000000..ef13793d1c499ae6aac27dfd66193b14a9e69d19 --- /dev/null +++ "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/train/pretrain_siglip.sh" @@ -0,0 +1,55 @@ +export OMP_NUM_THREADS=8 +export NCCL_IB_DISABLE=0 +export NCCL_IB_GID_INDEX=3 +export NCCL_SOCKET_IFNAME=eth0 +export NCCL_DEBUG=INFO + +LLM_VERSION="Qwen/Qwen2-7B-Instruct" +LLM_VERSION_CLEAN="${LLM_VERSION//\//_}" +VISION_MODEL_VERSION="google/siglip-so400m-patch14-384" +VISION_MODEL_VERSION_CLEAN="${VISION_MODEL_VERSION//\//_}" + +############### Pretrain ################ + +PROMPT_VERSION=plain + +BASE_RUN_NAME="llavanext-${VISION_MODEL_VERSION_CLEAN}-${LLM_VERSION_CLEAN}-mlp2x_gelu-pretrain_blip558k_plain" +echo "BASE_RUN_NAME: ${BASE_RUN_NAME}" + +ACCELERATE_CPU_AFFINITY=1 torchrun --nproc_per_node="${NUM_GPUS}" --nnodes="${NNODES}" --node_rank="${RANK}" --master_addr="${ADDR}" --master_port="${PORT}" \ + llava/train/train_mem.py \ + --deepspeed scripts/zero3.json \ + --model_name_or_path ${LLM_VERSION} \ + --version ${PROMPT_VERSION} \ + --data_path /blip_558k/blip_558k_plain.json \ + --image_folder /blip_558k/images \ + --vision_tower ${VISION_MODEL_VERSION} \ + --mm_tunable_parts="mm_mlp_adapter" \ + --mm_vision_select_layer -2 \ + --mm_projector_type mlp2x_gelu \ + --mm_use_im_start_end False \ + --mm_use_im_patch_token False \ + --bf16 True \ + --output_dir /checkpoints/projectors/${BASE_RUN_NAME} \ + --num_train_epochs 1 \ + --per_device_train_batch_size 16 \ + --per_device_eval_batch_size 4 \ + --gradient_accumulation_steps 1 \ + --evaluation_strategy "no" \ + --save_strategy "no" \ + --save_steps 50000 \ + --learning_rate 1e-3 \ + --weight_decay 0. \ + --warmup_ratio 0.03 \ + --lr_scheduler_type "cosine" \ + --logging_steps 1 \ + --tf32 True \ + --model_max_length 8192 \ + --gradient_checkpointing True \ + --dataloader_num_workers 16 \ + --lazy_preprocess True \ + --report_to wandb \ + --run_name $BASE_RUN_NAME \ + --attn_implementation sdpa + +# You can delete the sdpa attn_implementation if you want to use flash attn \ No newline at end of file diff --git "a/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/train/single_image.yaml" "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/train/single_image.yaml" new file mode 100644 index 0000000000000000000000000000000000000000..a21e3a159389add74737e53c23b851d8163972c3 --- /dev/null +++ "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/train/single_image.yaml" @@ -0,0 +1,187 @@ +datasets: + - json_path: /mnt/bn/vl-research/data/llava_instruct/real_vision_flan/llava_next_fit_mix_filtered_text_wild_738590.json # released in lmms-lab/LLaVA-NeXT-Data + sampling_strategy: "all" + - json_path: /mnt/bn/vl-research/data/llava_instruct/real_vision_flan/llava_wild_4v_39k.json # not released + sampling_strategy: "all" + - json_path: /mnt/bn/vl-research/data/llava_instruct/real_vision_flan/llava_wild_4v_12k.json # not released + sampling_strategy: "all" + - json_path: /mnt/bn/vl-research/data/llava_instruct/real_vision_flan/llavar_gpt4_20k.json + sampling_strategy: "all" + # - json_path: /mnt/bn/vl-research/data/llava_instruct/real_vision_flan/sroie_data_33626.json + # sampling_strategy: "first:10%" + # - json_path: /mnt/bn/vl-research/data/llava_instruct/real_vision_flan/orand_car_a_train_2009.json + # sampling_strategy: "all" + # - json_path: /mnt/bn/vl-research/data/llava_instruct/real_vision_flan/orand_car_b_train_3000.json + # sampling_strategy: "all" + - json_path: /mnt/bn/vl-research/data/llava_instruct/real_vision_flan/mavis_math_metagen_87358.json + sampling_strategy: "all" + - json_path: /mnt/bn/vl-research/data/llava_instruct/real_vision_flan/mavis_math_rule_geo_100000.json + sampling_strategy: "all" + - json_path: /mnt/bn/vl-research/data/llava_instruct/real_vision_flan/chrome_writting_train_8835.json + sampling_strategy: "all" + - json_path: /mnt/bn/vl-research/data/llava_instruct/real_vision_flan/k12_printing_train_256646.json + sampling_strategy: "first:1%" + - json_path: /mnt/bn/vl-research/data/llava_instruct/real_vision_flan/iiit5k_annotations_2000.json + sampling_strategy: "all" + - json_path: /mnt/bn/vl-research/data/llava_instruct/real_vision_flan/hme100k_train_clean_74502.json + sampling_strategy: "first:10%" + - json_path: /mnt/bn/vl-research/data/llava_instruct/real_vision_flan/ai2d_azuregpt_detailed_understanding_4874.json + sampling_strategy: "all" + - json_path: /mnt/bn/vl-research/data/llava_instruct/real_vision_flan/infographic_vqa_4404.json + sampling_strategy: "all" + - json_path: /mnt/bn/vl-research/data/llava_instruct/real_vision_flan/infographic_azuregpt4v_1992.json + sampling_strategy: "all" + - json_path: /mnt/bn/vl-research/data/llava_instruct/real_vision_flan/lrv_chart_1787.json + sampling_strategy: "all" + - json_path: /mnt/bn/vl-research/data/llava_instruct/real_vision_flan/lrv_normal_gpt4v_filtered_10500.json + sampling_strategy: "all" + - json_path: /mnt/bn/vl-research/data/llava_instruct/real_vision_flan/scienceqa_nona_context_19218.json + sampling_strategy: "first:5%" + - json_path: /mnt/bn/vl-research/data/llava_instruct/real_vision_flan/allava_instruct_vflan4v_20000.json + sampling_strategy: "all" + - json_path: /mnt/bn/vl-research/data/llava_instruct/real_vision_flan/allava_instruct_laion4v_50000.json + sampling_strategy: "all" + - json_path: /mnt/bn/vl-research/data/llava_instruct/real_vision_flan/textocr_gpt4v_train_converted_25114.json + sampling_strategy: "all" + - json_path: /mnt/bn/vl-research/data/llava_instruct/real_vision_flan/ai2d_train_internvl_single_12413.json + sampling_strategy: "all" + - json_path: /mnt/bn/vl-research/data/llava_instruct/real_vision_flan/textcaps_train_21952.json + sampling_strategy: "all" + - json_path: /mnt/bn/vl-research/data/llava_instruct/ureader_new/ureader_qa_sft.json + sampling_strategy: "all" + - json_path: /mnt/bn/vl-research/data/llava_instruct/ureader_new/ureader_cap_sft.json + sampling_strategy: "all" + - json_path: /mnt/bn/vl-research/data/llava_instruct/ureader_new/ureader_ie_sft.json + sampling_strategy: "all" + - json_path: /mnt/bn/vl-research/data/llava_instruct/ureader_new/ureader_kg_sft.json + sampling_strategy: "all" + - json_path: /mnt/bn/vl-research/data/llava_instruct/real_vision_flan/vision_flan_filtered_186070.json + sampling_strategy: "all" + - json_path: /mnt/bn/vl-research/data/llava_instruct/real_vision_flan/mathqa_29837.json + sampling_strategy: "all" + - json_path: /mnt/bn/vl-research/data/llava_instruct/real_vision_flan/geo3k_2101.json + sampling_strategy: "all" + - json_path: /mnt/bn/vl-research/data/llava_instruct/real_vision_flan/geo170k_qa_converted_67833.json + sampling_strategy: "all" + - json_path: /mnt/bn/vl-research/data/llava_instruct/real_vision_flan/geo170k_align_converted_60252.json + sampling_strategy: "all" + - json_path: /mnt/bn/vl-research/data/llava_instruct/real_vision_flan/sharegpt4v-coco-50k.json + sampling_strategy: "all" + - json_path: /mnt/bn/vl-research/data/llava_instruct/real_vision_flan/sharegpt4v-knowledge-2k.json + sampling_strategy: "all" + - json_path: /mnt/bn/vl-research/data/llava_instruct/real_vision_flan/sharegpt4v-llava-30k.json + sampling_strategy: "all" + - json_path: /mnt/bn/vl-research/data/llava_instruct/real_vision_flan/sharegpt4v-sam-20k.json + sampling_strategy: "all" + - json_path: /mnt/bn/vl-research/data/llava_instruct/real_vision_flan/MathV360K_CLEVR-Math_5290.json + sampling_strategy: "all" + - json_path: /mnt/bn/vl-research/data/llava_instruct/real_vision_flan/MathV360K_FigureQA_17597.json + sampling_strategy: "first:5%" + - json_path: /mnt/bn/vl-research/data/llava_instruct/real_vision_flan/MathV360K_Geometry3K_9734.json + sampling_strategy: "all" + - json_path: /mnt/bn/vl-research/data/llava_instruct/real_vision_flan/MathV360K_GeoQA+_17172.json + sampling_strategy: "all" + - json_path: /mnt/bn/vl-research/data/llava_instruct/real_vision_flan/MathV360K_GEOS_508.json + sampling_strategy: "all" + - json_path: /mnt/bn/vl-research/data/llava_instruct/real_vision_flan/MathV360K_IconQA_22599.json + sampling_strategy: "first:5%" + - json_path: /mnt/bn/vl-research/data/llava_instruct/real_vision_flan/MathV360K_MapQA_5235.json + sampling_strategy: "all" + - json_path: /mnt/bn/vl-research/data/llava_instruct/real_vision_flan/MathV360K_PMC-VQA_35958.json + sampling_strategy: "first:5%" + - json_path: /mnt/bn/vl-research/data/llava_instruct/real_vision_flan/MathV360K_Super-CLEVR_8652.json + sampling_strategy: "all" + - json_path: /mnt/bn/vl-research/data/llava_instruct/real_vision_flan/MathV360K_TabMWP_22462.json + sampling_strategy: "all" + - json_path: /mnt/bn/vl-research/data/llava_instruct/real_vision_flan/MathV360K_TQA_10181.json + sampling_strategy: "all" + - json_path: /mnt/bn/vl-research/data/llava_instruct/real_vision_flan/MathV360K_UniGeo_11959.json + sampling_strategy: "all" + - json_path: /mnt/bn/vl-research/data/llava_instruct/real_vision_flan/MathV360K_VizWiz_6614.json + sampling_strategy: "all" + - json_path: /mnt/bn/vl-research/data/llava_instruct/real_vision_flan/MathV360K_VQA-AS_5907.json + sampling_strategy: "all" + - json_path: /mnt/bn/vl-research/data/llava_instruct/real_vision_flan/MathV360K_VQA-RAD_2130.json + sampling_strategy: "all" + - json_path: /mnt/bn/vl-research/data/llava_instruct/real_vision_flan/Evol-Instruct-GPT4-Turbo-143000.json + sampling_strategy: "first:30%" + - json_path: /mnt/bn/vl-research/data/llava_instruct/real_vision_flan/magpie_pro_qwen2_72b_st_300000_sp_token_fltd_299992.json + sampling_strategy: "first:50%" + - json_path: /mnt/bn/vl-research/data/llava_instruct/real_vision_flan/magpie_pro_l3_80b_st_300000.json + sampling_strategy: "first:50%" + - json_path: /mnt/bn/vl-research/data/llava_instruct/real_vision_flan/magpie_pro_l3_80b_mt_300000_sp_token_fltd_299998.json + sampling_strategy: "first:50%" + - json_path: /mnt/bn/vl-research/data/llava_instruct/real_vision_flan/image_textualization_dataset_filtered.json + sampling_strategy: "all" + - json_path: /mnt/bn/vl-research/data/llava_instruct/real_vision_flan/cambrian_filtered_gpt4vo_sp_token_fltd_max10k.json + sampling_strategy: "all" + - json_path: /mnt/bn/vl-research/data/llava_instruct/real_vision_flan/sharegpt4o_dataset.jsonl + sampling_strategy: "all" + - json_path: /mnt/bn/vl-research/data/llava_instruct/cauldron/ai2d_llava_format_2434.json + sampling_strategy: "all" + - json_path: /mnt/bn/vl-research/data/llava_instruct/cauldron/aokvqa_16539_llava_format.json + sampling_strategy: "all" + - json_path: /mnt/bn/vl-research/data/llava_instruct/cauldron/chart2text_26961.json + sampling_strategy: "all" + - json_path: /mnt/bn/vl-research/data/llava_instruct/cauldron/chartqa_18265_llava_format.json + sampling_strategy: "all" + - json_path: /mnt/bn/vl-research/data/llava_instruct/cauldron/clevr_70000_llava_format.json + sampling_strategy: "first:1%" + - json_path: /mnt/bn/vl-research/data/llava_instruct/cauldron/diagram_image_to_text_300.json + sampling_strategy: "all" + - json_path: /mnt/bn/vl-research/data/llava_instruct/cauldron/dvqa_200000_llava_format.json + sampling_strategy: "first:1%" + - json_path: /mnt/bn/vl-research/data/llava_instruct/cauldron/figureqa_100000_llava_format.json + sampling_strategy: "first:1%" + - json_path: /mnt/bn/vl-research/data/llava_instruct/cauldron/geomverse_9303.json + sampling_strategy: "all" + - json_path: /mnt/bn/vl-research/data/llava_instruct/cauldron/hateful_memes_8500_llava_format.json + sampling_strategy: "all" + - json_path: /mnt/bn/vl-research/data/llava_instruct/cauldron/hitab_2500_llava_format.json + sampling_strategy: "all" + - json_path: /mnt/bn/vl-research/data/llava_instruct/cauldron/iam_5663.json + sampling_strategy: "all" + - json_path: /mnt/bn/vl-research/data/llava_instruct/cauldron/raven_42000.json + sampling_strategy: "first:5%" + - json_path: /mnt/bn/vl-research/data/llava_instruct/cauldron/iconqa_llava_format_27307.json + sampling_strategy: "first:5%" + - json_path: /mnt/bn/vl-research/data/llava_instruct/cauldron/infographic_vqa_2118_llava_format.json + sampling_strategy: "all" + - json_path: /mnt/bn/vl-research/data/llava_instruct/cauldron/intergps_1280_llava_format.json + sampling_strategy: "all" + - json_path: /mnt/bn/vl-research/data/llava_instruct/cauldron/mapqa_37417_llava_format.json + sampling_strategy: "all" + - json_path: /mnt/bn/vl-research/data/llava_instruct/cauldron/multihiertt_7619.json + sampling_strategy: "all" + - json_path: /mnt/bn/vl-research/data/llava_instruct/cauldron/rendered_text_10000.json + sampling_strategy: "all" + - json_path: /mnt/bn/vl-research/data/llava_instruct/cauldron/robut_sqa_8514.json + sampling_strategy: "all" + - json_path: /mnt/bn/vl-research/data/llava_instruct/cauldron/robut_wikisql_74989.json + sampling_strategy: "all" + - json_path: /mnt/bn/vl-research/data/llava_instruct/cauldron/robut_wtq_38246_llava_format.json + sampling_strategy: "all" + - json_path: /mnt/bn/vl-research/data/llava_instruct/cauldron/screen2words_15730.json + sampling_strategy: "all" + - json_path: /mnt/bn/vl-research/data/llava_instruct/cauldron/scienceqa_llava_format_4976.json + sampling_strategy: "all" + - json_path: /mnt/bn/vl-research/data/llava_instruct/cauldron/tabmwp_22722.json + sampling_strategy: "all" + - json_path: /mnt/bn/vl-research/data/llava_instruct/cauldron/tallyqa_98680_llava_format.json + sampling_strategy: "first:10%" + - json_path: /mnt/bn/vl-research/data/llava_instruct/cauldron/st_vqa_17247_llava_format.json + sampling_strategy: "all" + - json_path: /mnt/bn/vl-research/data/llava_instruct/cauldron/tqa_llava_format_27307.json + sampling_strategy: "first:5%" + - json_path: /mnt/bn/vl-research/data/llava_instruct/cauldron/visual7w_llava_format_14366.json + sampling_strategy: "all" + - json_path: /mnt/bn/vl-research/data/llava_instruct/cauldron/visualmrc_3027.json + sampling_strategy: "all" + - json_path: /mnt/bn/vl-research/data/llava_instruct/cauldron/vqarad_313_llava_format.json + sampling_strategy: "all" + - json_path: /mnt/bn/vl-research/data/llava_instruct/cauldron/vsr_2157_llava_format.json + sampling_strategy: "all" + - json_path: /mnt/bn/vl-research/data/llava_instruct/cauldron/vistext_9969.json + sampling_strategy: "all" + - json_path: /mnt/bn/vl-research/data/llava_instruct/cauldron/websight_10000.json + sampling_strategy: "all" diff --git "a/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/video/demo/video_demo.sh" "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/video/demo/video_demo.sh" new file mode 100644 index 0000000000000000000000000000000000000000..17f24c957617793ca7f8edad7d01d6dc55f4268d --- /dev/null +++ "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/video/demo/video_demo.sh" @@ -0,0 +1,43 @@ +#!/bin/bash +ROOT_DIR="/mnt/bn/vl-research/workspace/yhzhang/LLaVA-NeXT" + +if [ ! -e $ROOT_DIR ]; then + echo "The root dir does not exist. Exiting the script." + exit 1 +fi + +cd $ROOT_DIR + +export PYTHONWARNINGS=ignore +export TOKENIZERS_PARALLELISM=false + +CKPT=$1 +CONV_MODE=$2 +FRAMES=$3 +POOL_STRIDE=$4 +POOL_MODE=$5 +NEWLINE_POSITION=$6 +OVERWRITE=$7 +VIDEO_PATH=$8 + + +if [ "$OVERWRITE" = False ]; then + SAVE_DIR=$(basename $CKPT)_${CONV_MODE}_frames_${FRAMES}_stride_${POOL_STRIDE}_overwrite_${OVERWRITE} + +else + SAVE_DIR=$(basename $CKPT)_${CONV_MODE}_frames_${FRAMES}_stride_${POOL_STRIDE} +fi + +python3 playground/demo/video_demo.py \ + --model-path $CKPT \ + --video_path ${VIDEO_PATH} \ + --output_dir ./work_dirs/video_demo/$SAVE_DIR \ + --output_name pred \ + --chunk-idx $(($IDX - 1)) \ + --overwrite ${OVERWRITE} \ + --mm_spatial_pool_stride ${POOL_STRIDE:-4} \ + --for_get_frames_num $FRAMES \ + --conv-mode $CONV_MODE \ + --mm_spatial_pool_mode ${POOL_MODE:-average} \ + --mm_newline_position ${NEWLINE_POSITION:-grid} \ + --prompt "Please provide a detailed description of the video, focusing on the main subjects, their actions, the background scenes." \ No newline at end of file diff --git "a/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/video/eval/activitynet_eval.sh" "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/video/eval/activitynet_eval.sh" new file mode 100644 index 0000000000000000000000000000000000000000..6e16c5a5d53222695abdc9a44de0dd153fab8c37 --- /dev/null +++ "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/video/eval/activitynet_eval.sh" @@ -0,0 +1,96 @@ +#!/bin/bash +ROOT_DIR="root to LLaVA-NeXT-Video" + +if [ ! -e $ROOT_DIR ]; then + echo "The root dir does not exist. Exiting the script." + exit 1 +fi + +cd $ROOT_DIR + +export PYTHONWARNINGS=ignore +export TOKENIZERS_PARALLELISM=false +CUDA_VISIBLE_DEVICES='0,1,2,3,4,5,6,7' +gpu_list="${CUDA_VISIBLE_DEVICES}" +GPULIST=(${(s:,:)gpu_list}) + +CHUNKS=${#GPULIST[@]} +echo "Using $CHUNKS GPUs" + +CKPT=$1 +CONV_MODE=$2 +FRAMES=$3 +OVERWRITE=$4 +PREDEFINED_CONFIGURE=$5 +mm_spatial_pool_stride=$6 +MODEL_MAX_LENGTH=${7:-0} + +CKPT=$1 +CONV_MODE=$2 +FRAMES=$3 +POOL_STRIDE=$4 +OVERWRITE=$5 +CHUNKS=${6:-1} + +PATCHIFY=False + + +OPENAIKEY="INPUT YOUR OPENAI API" + + +if [ "$OVERWRITE" = False ]; then + SAVE_DIR=$(basename $CKPT)_${CONV_MODE}_frames_${FRAMES}_stride_${POOL_STRIDE}_overwrite_${OVERWRITE} + +else + SAVE_DIR=$(basename $CKPT)_${CONV_MODE}_frames_${FRAMES}_stride_${POOL_STRIDE} +fi + +echo $SAVE_DIR + +# for IDX in {1..$CHUNKS}; do +# GPU_ID=${GPULIST[$IDX]} # Note: Zsh arrays are 1-indexed by default + +# # GPU_FREE=0 +# # while [ $GPU_FREE -eq 0 ]; do +# # # Using nvidia-smi to get the memory usage of the GPU with ID $GPU_ID +# # # Parsing the output to extract the memory usage, and checking if it is "0" +# # MEM_USAGE=$(nvidia-smi --query-gpu=memory.used --format=csv,noheader,nounits -i $GPU_ID | tr -d '[:space:]') + +# # if [ "$MEM_USAGE" -eq 0 ]; then +# # GPU_FREE=1 +# # echo "GPU $GPU_ID is free." +# # else +# # echo "GPU $GPU_ID is in use. Memory used: ${MEM_USAGE}MiB. Checking again in 100 seconds..." +# # sleep 100 +# # fi +# # done + +# echo "Running on GPU $GPU_ID" +# CUDA_VISIBLE_DEVICES=$GPU_ID python3 llavavid/eval/model_activitynet_qa.py \ +# --model-path $CKPT \ +# --video_dir ./data/llava_video/ActivityNet-QA/all_test \ +# --gt_file_question ./data/llava_video/ActivityNet-QA/test_q.json \ +# --gt_file_answers ./data/llava_videoActivityNet-QA/test_a.json \ +# --output_dir ./work_dirs/eval_activitynet/$SAVE_DIR \ +# --output_name pred \ +# --num-chunks $CHUNKS \ +# --chunk-idx $(($IDX - 1)) \ +# --overwrite ${OVERWRITE} \ +# --patchify_video_feature ${PATCHIFY} \ +# --predefined_configure ${PREDEFINED_CONFIGURE} \ +# --mm_spatial_pool_stride ${mm_spatial_pool_stride:-4} \ +# --for_get_frames_num $FRAMES \ +# --model-max-length ${MODEL_MAX_LENGTH:-0} \ +# --conv-mode $CONV_MODE & + +# done + +# wait + +python3 llava/eval/eval_activitynet_qa.py \ + --pred_path ./work_dirs/eval_activitynet/$SAVE_DIR \ + --output_dir ./work_dirs/eval_activitynet/$SAVE_DIR/results \ + --output_json ./work_dirs/eval_activitynet/$SAVE_DIR/results.json \ + --num_chunks $CHUNKS \ + --api_key $OPENAIKEY \ + # --num_tasks 16 \ \ No newline at end of file diff --git "a/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/video/eval/video_chatgpt_benchmark_eval_shard.sh" "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/video/eval/video_chatgpt_benchmark_eval_shard.sh" new file mode 100644 index 0000000000000000000000000000000000000000..8b6518a2da0f3735714a90698175e9504734b7d8 --- /dev/null +++ "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/video/eval/video_chatgpt_benchmark_eval_shard.sh" @@ -0,0 +1,242 @@ +#!/bin/bash +ROOT_DIR="root to LLaVA-NeXT-Video" + +if [ ! -e $ROOT_DIR ]; then + echo "The root dir does not exist. Exiting the script." + exit 1 +fi + +cd $ROOT_DIR + +export python3WARNINGS=ignore +export TOKENIZERS_PARALLELISM=false +# CUDA_VISIBLE_DEVICES='0,1,2,3,4,5,6,7' +gpu_list="${CUDA_VISIBLE_DEVICES}" +GPULIST=(${(s:,:)gpu_list}) + +# CHUNKS=${#GPULIST[@]} +# echo "Using $CHUNKS GPUs" + +CKPT=$1 +CONV_MODE=$2 +FRAMES=$3 +POOL_STRIDE=$4 +OVERWRITE=$5 +CHUNKS=${6:-1} + +OPENAIKEY="INPUT YOUR OPENAI API" + +if [ "$OVERWRITE" = False ]; then + SAVE_DIR=$(basename $CKPT)_${CONV_MODE}_frames_${FRAMES}_stride_${POOL_STRIDE}_overwrite_${OVERWRITE} + +else + SAVE_DIR=$(basename $CKPT)_${CONV_MODE}_frames_${FRAMES}_stride_${POOL_STRIDE} +fi + +echo $SAVE_DIR + +# Assuming GPULIST is a bash array containing your GPUs +GPULIST=(0 1 2 3 4 5 6 7) + +# Get the number of GPUs +NUM_GPUS=${#GPULIST[@]} + +# Calculate GPUs per chunk +GPUS_PER_CHUNK=$((NUM_GPUS / CHUNKS)) + + +for IDX in $(seq 1 $CHUNKS); do + START=$(((IDX-1) * GPUS_PER_CHUNK)) + LENGTH=$GPUS_PER_CHUNK # Length for slicing, not the end index + + CHUNK_GPUS=(${GPULIST[@]:$START:$LENGTH}) + + # Convert the chunk GPUs array to a comma-separated string + CHUNK_GPUS_STR=$(IFS=,; echo "${CHUNK_GPUS[*]}") + + # ALL_GPUS_FREE=0 + # while [ $ALL_GPUS_FREE -eq 0 ]; do + # ALL_GPUS_FREE=1 # Assume all GPUs are free initially + + # for GPU_ID in $CHUNK_GPUS; do + # MEM_USAGE=$(nvidia-smi --query-gpu=memory.used --format=csv,noheader,nounits -i $GPU_ID | tr -d '[:space:]') + + # # Assuming a GPU is considered free if its memory usage is less than 100 MiB + # if [ "$MEM_USAGE" -ge 100 ]; then + # ALL_GPUS_FREE=0 + # echo "GPU $GPU_ID is in use. Memory used: ${MEM_USAGE}MiB." + # break # Exit the loop early as we found a GPU that is not free + # fi + # done + + # if [ $ALL_GPUS_FREE -eq 0 ]; then + # echo "Not all GPUs in chunk are free. Checking again in 100 seconds..." + # sleep 100 + # fi + # done + + echo "CUDA_VISIBLE_DEVICES=$CHUNK_GPUS_STR" + CUDA_VISIBLE_DEVICES=$CHUNK_GPUS_STR python3 llava/eval/model_video_chatgpt_general.py \ + --model-path $CKPT \ + --video_dir ./data/llava_video/video-chatgpt/evaluation/Test_Videos/ \ + --gt_file ./data/llava_video/video-chatgpt/evaluation/generic_qa.json \ + --output_dir ./work_dirs/eval_video_chatgpt/$SAVE_DIR \ + --output_name pred \ + --num-chunks $CHUNKS \ + --chunk-idx $(($IDX - 1)) \ + --overwrite ${OVERWRITE:-true} \ + --mm_spatial_pool_stride ${POOL_STRIDE:-4} \ + --for_get_frames_num $FRAMES \ + --conv-mode $CONV_MODE & +done + +wait + +python3 llava/eval/evaluate_benchmark_1_correctness.py \ + --pred_path ./work_dirs/eval_video_chatgpt/$SAVE_DIR \ + --output_dir ./work_dirs/eval_video_chatgpt/$SAVE_DIR/correctness_results \ + --output_json ./work_dirs/eval_video_chatgpt/$SAVE_DIR/correctness_results.json \ + --num_chunks $CHUNKS \ + --output_name pred \ + --num_tasks 16 \ + --api_key $OPENAIKEY \ + + +python3 llava/eval/evaluate_benchmark_2_detailed_orientation.py \ + --pred_path ./work_dirs/eval_video_chatgpt/$SAVE_DIR \ + --output_dir ./work_dirs/eval_video_chatgpt/$SAVE_DIR/detail_results \ + --output_json ./work_dirs/eval_video_chatgpt/$SAVE_DIR/detail_results.json \ + --num_chunks $CHUNKS \ + --output_name pred \ + --num_tasks 16 \ + --api_key $OPENAIKEY \ + + +python3 llava/eval/evaluate_benchmark_3_context.py \ + --pred_path ./work_dirs/eval_video_chatgpt/$SAVE_DIR \ + --output_dir ./work_dirs/eval_video_chatgpt/$SAVE_DIR/context_results \ + --output_json ./work_dirs/eval_video_chatgpt/$SAVE_DIR/context_results.json \ + --num_chunks $CHUNKS \ + --output_name pred \ + --num_tasks 16 \ + --api_key $OPENAIKEY \ + + + +for IDX in $(seq 1 $CHUNKS); do + START=$(((IDX-1) * GPUS_PER_CHUNK)) + LENGTH=$GPUS_PER_CHUNK # Length for slicing, not the end index + + CHUNK_GPUS=(${GPULIST[@]:$START:$LENGTH}) + + # Convert the chunk GPUs array to a comma-separated string + CHUNK_GPUS_STR=$(IFS=,; echo "${CHUNK_GPUS[*]}") + + # ALL_GPUS_FREE=0 + # while [ $ALL_GPUS_FREE -eq 0 ]; do + # ALL_GPUS_FREE=1 # Assume all GPUs are free initially + + # for GPU_ID in $CHUNK_GPUS; do + # MEM_USAGE=$(nvidia-smi --query-gpu=memory.used --format=csv,noheader,nounits -i $GPU_ID | tr -d '[:space:]') + + # # Assuming a GPU is considered free if its memory usage is less than 100 MiB + # if [ "$MEM_USAGE" -ge 100 ]; then + # ALL_GPUS_FREE=0 + # echo "GPU $GPU_ID is in use. Memory used: ${MEM_USAGE}MiB." + # break # Exit the loop early as we found a GPU that is not free + # fi + # done + + # if [ $ALL_GPUS_FREE -eq 0 ]; then + # echo "Not all GPUs in chunk are free. Checking again in 100 seconds..." + # sleep 100 + # fi + # done + + echo "CUDA_VISIBLE_DEVICES=$CHUNK_GPUS_STR" + CUDA_VISIBLE_DEVICES=$CHUNK_GPUS_STR python3 llava/eval/model_video_chatgpt_general.py \ + --model-path $CKPT \ + --video_dir ./data/llava_video/video-chatgpt/evaluation/Test_Videos/ \ + --gt_file ./data/llava_video/video-chatgpt/evaluation/temporal_qa.json \ + --output_dir ./work_dirs/eval_video_chatgpt/$SAVE_DIR \ + --output_name pred_temporal \ + --num-chunks $CHUNKS \ + --chunk-idx $(($IDX - 1)) \ + --for_get_frames_num $FRAMES \ + --overwrite ${OVERWRITE} \ + --mm_spatial_pool_stride ${POOL_STRIDE:-4} \ + --conv-mode $CONV_MODE & + +done + +wait + + +python3 llava/eval/evaluate_benchmark_4_temporal.py \ + --pred_path ./work_dirs/eval_video_chatgpt/$SAVE_DIR \ + --output_dir ./work_dirs/eval_video_chatgpt/$SAVE_DIR/temporal_results \ + --output_json ./work_dirs/eval_video_chatgpt/$SAVE_DIR/temporal_results.json \ + --num_chunks $CHUNKS \ + --output_name pred_temporal \ + --num_tasks 16 \ + --api_key $OPENAIKEY \ + + + +for IDX in $(seq 1 $CHUNKS); do + START=$(((IDX-1) * GPUS_PER_CHUNK)) + LENGTH=$GPUS_PER_CHUNK # Length for slicing, not the end index + + CHUNK_GPUS=(${GPULIST[@]:$START:$LENGTH}) + + # Convert the chunk GPUs array to a comma-separated string + CHUNK_GPUS_STR=$(IFS=,; echo "${CHUNK_GPUS[*]}") + + # ALL_GPUS_FREE=0 + # while [ $ALL_GPUS_FREE -eq 0 ]; do + # ALL_GPUS_FREE=1 # Assume all GPUs are free initially + + # for GPU_ID in $CHUNK_GPUS; do + # MEM_USAGE=$(nvidia-smi --query-gpu=memory.used --format=csv,noheader,nounits -i $GPU_ID | tr -d '[:space:]') + + # # Assuming a GPU is considered free if its memory usage is less than 100 MiB + # if [ "$MEM_USAGE" -ge 100 ]; then + # ALL_GPUS_FREE=0 + # echo "GPU $GPU_ID is in use. Memory used: ${MEM_USAGE}MiB." + # break # Exit the loop early as we found a GPU that is not free + # fi + # done + + # if [ $ALL_GPUS_FREE -eq 0 ]; then + # echo "Not all GPUs in chunk are free. Checking again in 100 seconds..." + # sleep 100 + # fi + # done + + echo "CUDA_VISIBLE_DEVICES=$CHUNK_GPUS_STR" + CUDA_VISIBLE_DEVICES=$CHUNK_GPUS_STR python3 llava/eval/model_video_chatgpt_consistency.py \ + --model-path $CKPT \ + --video_dir ./data/llava_video/video-chatgpt/evaluation/Test_Videos/ \ + --gt_file ./data/llava_video/video-chatgpt/evaluation/consistency_qa.json \ + --output_dir ./work_dirs/eval_video_chatgpt/$SAVE_DIR \ + --output_name pred_consistency \ + --num-chunks $CHUNKS \ + --chunk-idx $(($IDX - 1)) \ + --mm_spatial_pool_stride ${POOL_STRIDE:-4} \ + --for_get_frames_num $FRAMES \ + --overwrite ${OVERWRITE} \ + --conv-mode $CONV_MODE & +done + +wait + + +python3 llava/eval/evaluate_benchmark_5_consistency.py \ + --pred_path ./work_dirs/eval_video_chatgpt/$SAVE_DIR \ + --output_dir ./work_dirs/eval_video_chatgpt/$SAVE_DIR/consistency_results \ + --output_json ./work_dirs/eval_video_chatgpt/$SAVE_DIR/consistency_results.json \ + --num_chunks $CHUNKS \ + --output_name pred_consistency \ + --num_tasks 16 \ + --api_key $OPENAIKEY \ + diff --git "a/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/video/eval/video_description_from_t2v.sh" "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/video/eval/video_description_from_t2v.sh" new file mode 100644 index 0000000000000000000000000000000000000000..7b87c9408acc9cb33f74f2792055c4de565534d4 --- /dev/null +++ "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/video/eval/video_description_from_t2v.sh" @@ -0,0 +1,98 @@ +#!/bin/bash +ROOT_DIR="/mnt/bn/vl-research/workspace/yhzhang/llava-next-video" + +if [ ! -e $ROOT_DIR ]; then + echo "The root dir does not exist. Exiting the script." + exit 1 +fi + +cd $ROOT_DIR + +export PYTHONWARNINGS=ignore +export TOKENIZERS_PARALLELISM=false + +CKPT=$1 +CONV_MODE=$2 +FRAMES=$3 +POOL_STRIDE=$4 +OVERWRITE=$5 +CHUNKS=${6:-1} +DO_CENTER_CROP=${7:-False} + +echo "Using $CHUNKS GPUs" + +LOAD_8BIT=False + + +if [ "$OVERWRITE" = False ]; then + if [ "$MODEL_MAX_LENGTH" = 0 ]; then + SAVE_DIR=$(basename $CKPT)_${CONV_MODE}_frames_${FRAMES}_overwrite_${OVERWRITE} + else + SAVE_DIR=$(basename $CKPT)_${CONV_MODE}_frames_${FRAMES}_overwrite_${OVERWRITE} + fi +else + SAVE_DIR=$(basename $CKPT)_${CONV_MODE}_frames_${FRAMES}_stride_${POOL_STRIDE} +fi + +SAVE_DIR=${SAVE_DIR}_do_center_crop_${DO_CENTER_CROP} +# Assuming GPULIST is a bash array containing your GPUs +GPULIST=(0 1 2 3 4 5 6 7) +# GPULIST=(0) + +# Get the number of GPUs +NUM_GPUS=${#GPULIST[@]} + +# Calculate GPUs per chunk +GPUS_PER_CHUNK=$((NUM_GPUS / CHUNKS)) + + +for IDX in $(seq 1 $CHUNKS); do + START=$(((IDX-1) * GPUS_PER_CHUNK)) + LENGTH=$GPUS_PER_CHUNK # Length for slicing, not the end index + + CHUNK_GPUS=(${GPULIST[@]:$START:$LENGTH}) + + # Convert the chunk GPUs array to a comma-separated string + CHUNK_GPUS_STR=$(IFS=,; echo "${CHUNK_GPUS[*]}") + + # ALL_GPUS_FREE=0 + # while [ $ALL_GPUS_FREE -eq 0 ]; do + # ALL_GPUS_FREE=1 # Assume all GPUs are free initially + + # for GPU_ID in $CHUNK_GPUS; do + # MEM_USAGE=$(nvidia-smi --query-gpu=memory.used --format=csv,noheader,nounits -i $GPU_ID | tr -d '[:space:]') + + # # Assuming a GPU is considered free if its memory usage is less than 100 MiB + # if [ "$MEM_USAGE" -ge 100 ]; then + # ALL_GPUS_FREE=0 + # echo "GPU $GPU_ID is in use. Memory used: ${MEM_USAGE}MiB." + # break # Exit the loop early as we found a GPU that is not free + # fi + # done + + # if [ $ALL_GPUS_FREE -eq 0 ]; then + # echo "Not all GPUs in chunk are free. Checking again in 100 seconds..." + # sleep 100 + # fi + # done + + echo "CUDA_VISIBLE_DEVICES=$CHUNK_GPUS_STR" + CUDA_VISIBLE_DEVICES=$CHUNK_GPUS_STR python3 llava/eval/model_video_description_from_t2v.py \ + --model-path $CKPT \ + --gt_file /mnt/bn/vl-research-1t/tuyen/webvid_hdvg_movie_pond5_for_captioning_evaluation/webvid_hdvg_movie_pond5_for_captioning_evaluation.processed.csv \ + --output_dir ./work_dirs/eval_video_description_from_t2v/$SAVE_DIR \ + --output_name pred \ + --num-chunks $CHUNKS \ + --chunk-idx $(($IDX - 1)) \ + --overwrite ${OVERWRITE} \ + --mm_spatial_pool_stride ${POOL_STRIDE:-4} \ + --for_get_frames_num $FRAMES \ + --load_8bit $LOAD_8BIT \ + --do_center_crop $DO_CENTER_CROP \ + --conv-mode $CONV_MODE & +done + +wait + +cat ${ROOT_DIR}/work_dirs/eval_video_description_from_t2v/$SAVE_DIR/${CHUNKS}* > ${ROOT_DIR}/work_dirs/eval_video_description_from_t2v/$SAVE_DIR/pred.json + diff --git "a/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/video/eval/video_detail_description_eval_only.sh" "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/video/eval/video_detail_description_eval_only.sh" new file mode 100644 index 0000000000000000000000000000000000000000..b75021ffb477025506660aedd7ea092bdbb048ce --- /dev/null +++ "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/video/eval/video_detail_description_eval_only.sh" @@ -0,0 +1,24 @@ +#!/bin/bash +ROOT_DIR="root to LLaVA-NeXT-Video" + +if [ ! -e $ROOT_DIR ]; then + echo "The root dir does not exist. Exiting the script." + exit 1 +fi + +cd $ROOT_DIR + +export PYTHONWARNINGS=ignore +export TOKENIZERS_PARALLELISM=false + +OPENAIKEY="INPUT YOUR OPENAI API" + +SAVE_DIR=$1 + +python3 llava/eval/evaluate_benchmark_video_detail_description.py \ + --pred_path ./work_dirs/eval_video_detail_description/$SAVE_DIR/pred.json \ + --output_dir ./work_dirs/eval_video_detail_description/$SAVE_DIR/detail_results \ + --output_json ./work_dirs/eval_video_detail_description/$SAVE_DIR/detail_results.json \ + --num_chunks 1 \ + --num_tasks 16 \ + --api_key $OPENAIKEY \ \ No newline at end of file diff --git "a/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/video/eval/video_detail_description_eval_shard.sh" "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/video/eval/video_detail_description_eval_shard.sh" new file mode 100644 index 0000000000000000000000000000000000000000..3b9de5caebbf6e4633432330a349006fa190c646 --- /dev/null +++ "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/video/eval/video_detail_description_eval_shard.sh" @@ -0,0 +1,95 @@ +#!/bin/bash +ROOT_DIR="/mnt/bn/vl-research/workspace/yhzhang/llava-next-video" + +if [ ! -e $ROOT_DIR ]; then + echo "The root dir does not exist. Exiting the script." + exit 1 +fi + +cd $ROOT_DIR + +export PYTHONWARNINGS=ignore +export TOKENIZERS_PARALLELISM=false + +OPENAIKEY="INPUT YOUR OPENAI API" + +CKPT=$1 +CONV_MODE=$2 +FRAMES=$3 +POOL_STRIDE=$4 +OVERWRITE=$5 +CHUNKS=${6:-1} + +echo "Using $CHUNKS GPUs" + +if [ "$OVERWRITE" = False ]; then + SAVE_DIR=$(basename $CKPT)_${CONV_MODE}_frames_${FRAMES}_stride_${POOL_STRIDE}_overwrite_${OVERWRITE} + +else + SAVE_DIR=$(basename $CKPT)_${CONV_MODE}_frames_${FRAMES}_stride_${POOL_STRIDE} +fi + +# Assuming GPULIST is a bash array containing your GPUs +GPULIST=(0 1 2 3 4 5 6 7) + +# Get the number of GPUs +NUM_GPUS=${#GPULIST[@]} + +# Calculate GPUs per chunk +GPUS_PER_CHUNK=$((NUM_GPUS / CHUNKS)) + + +for IDX in $(seq 1 $CHUNKS); do + START=$(((IDX-1) * GPUS_PER_CHUNK)) + LENGTH=$GPUS_PER_CHUNK # Length for slicing, not the end index + + CHUNK_GPUS=(${GPULIST[@]:$START:$LENGTH}) + + # Convert the chunk GPUs array to a comma-separated string + CHUNK_GPUS_STR=$(IFS=,; echo "${CHUNK_GPUS[*]}") + + # ALL_GPUS_FREE=0 + # while [ $ALL_GPUS_FREE -eq 0 ]; do + # ALL_GPUS_FREE=1 # Assume all GPUs are free initially + + # for GPU_ID in $CHUNK_GPUS; do + # MEM_USAGE=$(nvidia-smi --query-gpu=memory.used --format=csv,noheader,nounits -i $GPU_ID | tr -d '[:space:]') + + # # Assuming a GPU is considered free if its memory usage is less than 100 MiB + # if [ "$MEM_USAGE" -ge 100 ]; then + # ALL_GPUS_FREE=0 + # echo "GPU $GPU_ID is in use. Memory used: ${MEM_USAGE}MiB." + # break # Exit the loop early as we found a GPU that is not free + # fi + # done + + # if [ $ALL_GPUS_FREE -eq 0 ]; then + # echo "Not all GPUs in chunk are free. Checking again in 100 seconds..." + # sleep 100 + # fi + # done + + echo "CUDA_VISIBLE_DEVICES=$CHUNK_GPUS_STR" + CUDA_VISIBLE_DEVICES=$CHUNK_GPUS_STR python3 llava/eval/model_video_detail_description.py \ + --model-path $CKPT \ + --video_dir ./data/llava_video/video-chatgpt/evaluation/Test_Videos/ \ + --output_dir ./work_dirs/eval_video_detail_description/$SAVE_DIR \ + --output_name pred \ + --num-chunks $CHUNKS \ + --chunk-idx $(($IDX - 1)) \ + --overwrite ${OVERWRITE} \ + --mm_spatial_pool_stride ${POOL_STRIDE:-4} \ + --for_get_frames_num $FRAMES \ + --conv-mode $CONV_MODE & +done + +wait + +python3 llava/eval/evaluate_benchmark_video_detail_description.py \ + --pred_path ./work_dirs/eval_video_detail_description/$SAVE_DIR \ + --output_dir ./work_dirs/eval_video_detail_description/$SAVE_DIR/detail_results \ + --output_json ./work_dirs/eval_video_detail_description/$SAVE_DIR/detail_results.json \ + --num_chunks $CHUNKS \ + --num_tasks 16 \ + --api_key $OPENAIKEY \ + diff --git "a/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/video/train/SO400M_Qwen2_72B_ov_to_video_am9.sh" "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/video/train/SO400M_Qwen2_72B_ov_to_video_am9.sh" new file mode 100644 index 0000000000000000000000000000000000000000..5e053ffb5e6c4210a6a16508aff62866f22047e2 --- /dev/null +++ "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/video/train/SO400M_Qwen2_72B_ov_to_video_am9.sh" @@ -0,0 +1,84 @@ +#!/bin/bash + +# Set up the data folder +IMAGE_FOLDER="XXX" +VIDEO_FOLDER="XXX" +DATA_YAML="XXX" # e.g exp.yaml + +############### Prepare Envs ################# +python3 -m pip install flash-attn --no-build-isolation +alias python=python3 +############### Show Envs #################### + +nvidia-smi + +################ Arnold Jobs ################ + +LLM_VERSION="Qwen/Qwen2-72B-Instruct" +LLM_VERSION_CLEAN="${LLM_VERSION//\//_}" +VISION_MODEL_VERSION="google/siglip-so400m-patch14-384" +VISION_MODEL_VERSION_CLEAN="${VISION_MODEL_VERSION//\//_}" + + +BASE_RUN_NAME="llavanext-google_siglip-so400m-patch14-384-Qwen_Qwen2-72B-Instruct-mlp2x_gelu-pretrain_blip558k_plain" +echo "BASE_RUN_NAME: ${BASE_RUN_NAME}" + +# Stage 2 +PROMPT_VERSION="qwen_1_5" +MID_RUN_NAME="llavanext-${VISION_MODEL_VERSION_CLEAN}-${LLM_VERSION_CLEAN}-ov_to_video_am9" +PREV_STAGE_CHECKPOINT="lmms-lab/llava-onevision-qwen2-72b-ov-si" +echo "PREV_STAGE_CHECKPOINT: ${PREV_STAGE_CHECKPOINT}" +echo "MID_RUN_NAME: ${MID_RUN_NAME}" + + +# ACCELERATE_CPU_AFFINITY=1 torchrun --nproc_per_node="${ARNOLD_WORKER_GPU}" --nnodes="${ARNOLD_WORKER_NUM}" --node_rank="${ARNOLD_ID}" --master_addr="${METIS_WORKER_0_HOST}" --master_port="${port_in_cmd}" \ +deepspeed --master_port 30000 \ + llava/train/train_mem.py \ + --deepspeed scripts/zero3.json \ + --model_name_or_path $PREV_STAGE_CHECKPOINT \ + --version $PROMPT_VERSION \ + --data_path $DATA_YAML \ + --image_folder $IMAGE_FOLDER \ + --video_folder $VIDEO_FOLDER \ + --mm_tunable_parts="mm_vision_tower,mm_mlp_adapter,mm_language_model" \ + --mm_vision_tower_lr=2e-6 \ + --vision_tower ${VISION_MODEL_VERSION} \ + --mm_projector_type mlp2x_gelu \ + --mm_vision_select_layer -2 \ + --mm_use_im_start_end False \ + --mm_use_im_patch_token False \ + --group_by_modality_length True \ + --image_aspect_ratio anyres_max_9 \ + --image_grid_pinpoints "(1x1),...,(6x6)" \ + --mm_patch_merge_type spatial_unpad \ + --bf16 True \ + --run_name $MID_RUN_NAME \ + --output_dir ./work_dirs/$MID_RUN_NAME \ + --num_train_epochs 1 \ + --per_device_train_batch_size 1 \ + --per_device_eval_batch_size 4 \ + --gradient_accumulation_steps 2 \ + --evaluation_strategy "no" \ + --save_strategy "steps" \ + --save_steps 500 \ + --save_total_limit 1 \ + --learning_rate 1e-5 \ + --weight_decay 0. \ + --warmup_ratio 0.03 \ + --lr_scheduler_type "cosine" \ + --logging_steps 1 \ + --tf32 True \ + --model_max_length 32768 \ + --gradient_checkpointing True \ + --dataloader_num_workers 2 \ + --lazy_preprocess True \ + --report_to wandb \ + --torch_compile True \ + --torch_compile_backend "inductor" \ + --dataloader_drop_last True \ + --frames_upbound 32 \ + --mm_newline_position grid \ + --add_time_instruction True \ + --force_sample True \ + --mm_spatial_pool_stride 2 +exit 0; \ No newline at end of file diff --git "a/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/video/train/SO400M_Qwen2_7B_ov_to_video_am9.sh" "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/video/train/SO400M_Qwen2_7B_ov_to_video_am9.sh" new file mode 100644 index 0000000000000000000000000000000000000000..14b915a0ce78a077954873b44524089325fb5706 --- /dev/null +++ "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/video/train/SO400M_Qwen2_7B_ov_to_video_am9.sh" @@ -0,0 +1,84 @@ +#!/bin/bash + +# Set up the data folder +IMAGE_FOLDER="XXX" +VIDEO_FOLDER="XXX" +DATA_YAML="XXX" # e.g exp.yaml + +############### Prepare Envs ################# +python3 -m pip install flash-attn --no-build-isolation +alias python=python3 +############### Show Envs #################### + +nvidia-smi + +################ Arnold Jobs ################ + +LLM_VERSION="Qwen/Qwen2-7B-Instruct" +LLM_VERSION_CLEAN="${LLM_VERSION//\//_}" +VISION_MODEL_VERSION="google/siglip-so400m-patch14-384" +VISION_MODEL_VERSION_CLEAN="${VISION_MODEL_VERSION//\//_}" +# + +BASE_RUN_NAME="llavanext-google_siglip-so400m-patch14-384-Qwen_Qwen2-7B-Instruct-mlp2x_gelu-pretrain_blip558k_plain" +echo "BASE_RUN_NAME: ${BASE_RUN_NAME}" + +# Stage 2 +PROMPT_VERSION="qwen_1_5" +MID_RUN_NAME="llavanext-${VISION_MODEL_VERSION_CLEAN}-${LLM_VERSION_CLEAN}-ov_to_video_am9" +PREV_STAGE_CHECKPOINT="lmms-lab/llava-onevision-qwen2-7b-ov-si" +echo "PREV_STAGE_CHECKPOINT: ${PREV_STAGE_CHECKPOINT}" +echo "MID_RUN_NAME: ${MID_RUN_NAME}" + + +# ACCELERATE_CPU_AFFINITY=1 torchrun --nproc_per_node="${ARNOLD_WORKER_GPU}" --nnodes="${ARNOLD_WORKER_NUM}" --node_rank="${ARNOLD_ID}" --master_addr="${METIS_WORKER_0_HOST}" --master_port="${port_in_cmd}" \ +deepspeed --master_port 30000 \ + llava/train/train_mem.py \ + --deepspeed scripts/zero3.json \ + --model_name_or_path $PREV_STAGE_CHECKPOINT \ + --version $PROMPT_VERSION \ + --data_path $DATA_YAML \ + --image_folder $IMAGE_FOLDER \ + --video_folder $VIDEO_FOLDER \ + --mm_tunable_parts="mm_vision_tower,mm_mlp_adapter,mm_language_model" \ + --mm_vision_tower_lr=2e-6 \ + --vision_tower ${VISION_MODEL_VERSION} \ + --mm_projector_type mlp2x_gelu \ + --mm_vision_select_layer -2 \ + --mm_use_im_start_end False \ + --mm_use_im_patch_token False \ + --group_by_modality_length True \ + --image_aspect_ratio anyres_max_9 \ + --image_grid_pinpoints "(1x1),...,(6x6)" \ + --mm_patch_merge_type spatial_unpad \ + --bf16 True \ + --run_name $MID_RUN_NAME \ + --output_dir ./work_dirs/$MID_RUN_NAME \ + --num_train_epochs 1 \ + --per_device_train_batch_size 1 \ + --per_device_eval_batch_size 4 \ + --gradient_accumulation_steps 2 \ + --evaluation_strategy "no" \ + --save_strategy "steps" \ + --save_steps 500 \ + --save_total_limit 1 \ + --learning_rate 1e-5 \ + --weight_decay 0. \ + --warmup_ratio 0.03 \ + --lr_scheduler_type "cosine" \ + --logging_steps 1 \ + --tf32 True \ + --model_max_length 32768 \ + --gradient_checkpointing True \ + --dataloader_num_workers 2 \ + --lazy_preprocess True \ + --report_to wandb \ + --torch_compile True \ + --torch_compile_backend "inductor" \ + --dataloader_drop_last True \ + --frames_upbound 64 \ + --mm_newline_position grid \ + --add_time_instruction True \ + --force_sample True \ + --mm_spatial_pool_stride 2 +exit 0; \ No newline at end of file diff --git "a/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/video/train/exp.yaml" "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/video/train/exp.yaml" new file mode 100644 index 0000000000000000000000000000000000000000..a0f5cb59cfbb1a9c1c6028d6ad938a025f72a236 --- /dev/null +++ "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\347\254\254\344\270\200\347\211\210-\345\205\250\351\203\250\344\273\243\347\240\201/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/scripts/video/train/exp.yaml" @@ -0,0 +1,263 @@ +datasets: + - json_path: /mnt/bn/vl-research/data/llava_instruct/real_vision_flan/llava_next_fit_mix_filtered_text_wild_738590.json + sampling_strategy: "first:50%" + # - json_path: /mnt/bn/vl-research/data/llava_instruct/real_vision_flan/llava_wild_4v_39k.json + # sampling_strategy: "first:10%" + # - json_path: /mnt/bn/vl-research/data/llava_instruct/real_vision_flan/llava_wild_4v_12k.json + # sampling_strategy: "first:10%" + - json_path: /mnt/bn/vl-research/data/llava_instruct/real_vision_flan/mavis_math_metagen_87358.json + sampling_strategy: "first:10%" + - json_path: /mnt/bn/vl-research/data/llava_instruct/real_vision_flan/mavis_math_rule_geo_100000.json + sampling_strategy: "first:10%" + - json_path: /mnt/bn/vl-research/data/llava_instruct/real_vision_flan/cambrian_filtered_gpt4vo_sp_token_fltd_max10k_checked.json + sampling_strategy: "all" + - json_path: /mnt/bn/vl-research/data/llava_instruct/real_vision_flan/VisualWebInstruct_filtered_263589.json + sampling_strategy: "all" + - json_path: /mnt/bn/vl-research/data/llava_instruct/real_vision_flan/visual_chat_en_26048_gpt4o_coco_checked.json + sampling_strategy: "all" + # - json_path: /mnt/bn/vl-research/data/llava_instruct/real_vision_flan/gpt4o_combinations_51316.json + # sampling_strategy: "all" + # - json_path: /mnt/bn/vl-research/data/llava_instruct/real_vision_flan/chrome_writting_train_8835.json + # sampling_strategy: "first:20%" + # - json_path: /mnt/bn/vl-research/data/llava_instruct/real_vision_flan/k12_printing_train_256646.json + # sampling_strategy: "first:1%" + # - json_path: /mnt/bn/vl-research/data/llava_instruct/real_vision_flan/iiit5k_annotations_2000.json + # sampling_strategy: "first:20%" + # - json_path: /mnt/bn/vl-research/data/llava_instruct/real_vision_flan/hme100k_train_clean_74502.json + # sampling_strategy: "first:10%" + # - json_path: /mnt/bn/vl-research/data/llava_instruct/real_vision_flan/sroie_data_33626.json + # sampling_strategy: "first:1%" + # - json_path: /mnt/bn/vl-research/data/llava_instruct/real_vision_flan/orand_car_a_train_2009.json + # sampling_strategy: "first:10%" + # - json_path: /mnt/bn/vl-research/data/llava_instruct/real_vision_flan/orand_car_b_train_3000.json + # sampling_strategy: "first:10%" + - json_path: /mnt/bn/vl-research/data/llava_instruct/real_vision_flan/llavar_gpt4_20k.json + sampling_strategy: "first:10%" + - json_path: /mnt/bn/vl-research/data/llava_instruct/real_vision_flan/ai2d_azuregpt_detailed_understanding_4874.json + sampling_strategy: "all" + - json_path: /mnt/bn/vl-research/data/llava_instruct/real_vision_flan/infographic_vqa_4404.json + sampling_strategy: "all" + - json_path: /mnt/bn/vl-research/data/llava_instruct/real_vision_flan/infographic_azuregpt4v_1992.json + sampling_strategy: "all" + - json_path: /mnt/bn/vl-research/data/llava_instruct/real_vision_flan/lrv_chart_1787.json + sampling_strategy: "all" + - json_path: /mnt/bn/vl-research/data/llava_instruct/real_vision_flan/lrv_normal_gpt4v_filtered_10500.json + sampling_strategy: "first:10%" + # - json_path: /mnt/bn/vl-research/data/llava_instruct/real_vision_flan/scienceqa_nona_context_19218.json + # sampling_strategy: "first:10%" + - json_path: /mnt/bn/vl-research/data/llava_instruct/real_vision_flan/allava_instruct_vflan4v_20000.json + sampling_strategy: "first:30%" + - json_path: /mnt/bn/vl-research/data/llava_instruct/real_vision_flan/allava_instruct_laion4v_50000.json + sampling_strategy: "first:30%" + - json_path: /mnt/bn/vl-research/data/llava_instruct/real_vision_flan/textocr_gpt4v_train_converted_25114.json + sampling_strategy: "first:10%" + - json_path: /mnt/bn/vl-research/data/llava_instruct/real_vision_flan/ai2d_train_internvl_single_12413.json + sampling_strategy: "first:10%" + - json_path: /mnt/bn/vl-research/data/llava_instruct/real_vision_flan/textcaps_train_21952.json + sampling_strategy: "first:10%" + - json_path: /mnt/bn/vl-research/data/llava_instruct/ureader_new/ureader_qa_sft.json + sampling_strategy: "first:10%" + - json_path: /mnt/bn/vl-research/data/llava_instruct/ureader_new/ureader_cap_sft.json + sampling_strategy: "first:10%" + - json_path: /mnt/bn/vl-research/data/llava_instruct/ureader_new/ureader_ie_sft.json + sampling_strategy: "first:10%" + - json_path: /mnt/bn/vl-research/data/llava_instruct/ureader_new/ureader_kg_sft.json + sampling_strategy: "first:10%" + - json_path: /mnt/bn/vl-research/data/llava_instruct/real_vision_flan/vision_flan_filtered_186070.json + sampling_strategy: "all" + - json_path: /mnt/bn/vl-research/data/llava_instruct/real_vision_flan/mathqa_29837.json + sampling_strategy: "all" + - json_path: /mnt/bn/vl-research/data/llava_instruct/real_vision_flan/geo3k_2101.json + sampling_strategy: "all" + - json_path: /mnt/bn/vl-research/data/llava_instruct/real_vision_flan/geo170k_qa_converted_67833.json + sampling_strategy: "first:10%" + - json_path: /mnt/bn/vl-research/data/llava_instruct/real_vision_flan/geo170k_align_converted_60252.json + sampling_strategy: "first:10%" + - json_path: /mnt/bn/vl-research/data/llava_instruct/real_vision_flan/sharegpt4o_dataset.jsonl + sampling_strategy: "all" + - json_path: /mnt/bn/vl-research/data/llava_instruct/real_vision_flan/sharegpt4v-coco-50k.json + sampling_strategy: "all" + - json_path: /mnt/bn/vl-research/data/llava_instruct/real_vision_flan/sharegpt4v-knowledge-2k.json + sampling_strategy: "all" + - json_path: /mnt/bn/vl-research/data/llava_instruct/real_vision_flan/sharegpt4v-llava-30k.json + sampling_strategy: "all" + - json_path: /mnt/bn/vl-research/data/llava_instruct/real_vision_flan/sharegpt4v-sam-20k.json + sampling_strategy: "all" + - json_path: /mnt/bn/vl-research/data/llava_instruct/real_vision_flan/MathV360K_CLEVR-Math_5290.json + sampling_strategy: "first:10%" + - json_path: /mnt/bn/vl-research/data/llava_instruct/real_vision_flan/MathV360K_FigureQA_17597.json + sampling_strategy: "first:10%" + - json_path: /mnt/bn/vl-research/data/llava_instruct/real_vision_flan/MathV360K_Geometry3K_9734.json + sampling_strategy: "first:10%" + - json_path: /mnt/bn/vl-research/data/llava_instruct/real_vision_flan/MathV360K_GeoQA+_17172.json + sampling_strategy: "first:10%" + - json_path: /mnt/bn/vl-research/data/llava_instruct/real_vision_flan/MathV360K_GEOS_508.json + sampling_strategy: "all" + - json_path: /mnt/bn/vl-research/data/llava_instruct/real_vision_flan/MathV360K_IconQA_22599.json + sampling_strategy: "first:5%" + - json_path: /mnt/bn/vl-research/data/llava_instruct/real_vision_flan/MathV360K_MapQA_5235.json + sampling_strategy: "first:10%" + - json_path: /mnt/bn/vl-research/data/llava_instruct/real_vision_flan/MathV360K_PlotQA_5485.json + sampling_strategy: "first:10%" + - json_path: /mnt/bn/vl-research/data/llava_instruct/real_vision_flan/MathV360K_PMC-VQA_35958.json + sampling_strategy: "first:1%" + - json_path: /mnt/bn/vl-research/data/llava_instruct/real_vision_flan/MathV360K_Super-CLEVR_8652.json + sampling_strategy: "first:10%" + - json_path: /mnt/bn/vl-research/data/llava_instruct/real_vision_flan/MathV360K_TabMWP_22462.json + sampling_strategy: "first:10%" + - json_path: /mnt/bn/vl-research/data/llava_instruct/real_vision_flan/MathV360K_TQA_10181.json + sampling_strategy: "first:10%" + - json_path: /mnt/bn/vl-research/data/llava_instruct/real_vision_flan/MathV360K_UniGeo_11959.json + sampling_strategy: "first:10%" + - json_path: /mnt/bn/vl-research/data/llava_instruct/real_vision_flan/MathV360K_VizWiz_6614.json + sampling_strategy: "first:10%" + - json_path: /mnt/bn/vl-research/data/llava_instruct/real_vision_flan/MathV360K_VQA-AS_5907.json + sampling_strategy: "first:10%" + - json_path: /mnt/bn/vl-research/data/llava_instruct/real_vision_flan/MathV360K_VQA-RAD_2130.json + sampling_strategy: "first:10%" + - json_path: /mnt/bn/vl-research/data/llava_instruct/real_vision_flan/magpie_pro_qwen2_72b_st_300000_sp_token_fltd_299992.json + sampling_strategy: "end:20%" + - json_path: /mnt/bn/vl-research/data/llava_instruct/real_vision_flan/magpie_pro_l3_80b_st_300000.json + sampling_strategy: "end:20%" + - json_path: /mnt/bn/vl-research/data/llava_instruct/real_vision_flan/magpie_pro_l3_80b_mt_300000_sp_token_fltd_299998.json + sampling_strategy: "end:20%" + - json_path: /mnt/bn/vl-research/data/llava_instruct/real_vision_flan/image_textualization_dataset_filtered.json + sampling_strategy: "first:20%" + - json_path: /mnt/bn/vl-research/data/llava_instruct/cauldron/ai2d_llava_format_2434.json + sampling_strategy: "all" + - json_path: /mnt/bn/vl-research/data/llava_instruct/cauldron/chart2text_26961.json + sampling_strategy: "first:10%" + - json_path: /mnt/bn/vl-research/data/llava_instruct/cauldron/chartqa_18265_llava_format.json + sampling_strategy: "first:10%" + - json_path: /mnt/bn/vl-research/data/llava_instruct/cauldron/diagram_image_to_text_300.json + sampling_strategy: "all" + - json_path: /mnt/bn/vl-research/data/llava_instruct/cauldron/hateful_memes_8500_llava_format.json + sampling_strategy: "first:10%" + - json_path: /mnt/bn/vl-research/data/llava_instruct/cauldron/hitab_2500_llava_format.json + sampling_strategy: "first:10%" + - json_path: /mnt/bn/vl-research/data/llava_instruct/cauldron/iam_5663.json + sampling_strategy: "first:10%" + - json_path: /mnt/bn/vl-research/data/llava_instruct/cauldron/infographic_vqa_2118_llava_format.json + sampling_strategy: "first:10%" + - json_path: /mnt/bn/vl-research/data/llava_instruct/cauldron/intergps_1280_llava_format.json + sampling_strategy: "first:10%" + - json_path: /mnt/bn/vl-research/data/llava_instruct/cauldron/mapqa_37417_llava_format.json + sampling_strategy: "first:10%" + - json_path: /mnt/bn/vl-research/data/llava_instruct/cauldron/rendered_text_10000.json + sampling_strategy: "first:10%" + - json_path: /mnt/bn/vl-research/data/llava_instruct/cauldron/robut_sqa_8514.json + sampling_strategy: "first:10%" + - json_path: /mnt/bn/vl-research/data/llava_instruct/cauldron/robut_wikisql_74989.json + sampling_strategy: "first:10%" + # - json_path: /mnt/bn/vl-research/data/llava_instruct/cauldron/robut_wtq_38246_llava_format_filtered_4000tokens_38236.json + # sampling_strategy: "first:10%" + - json_path: /mnt/bn/vl-research/data/llava_instruct/cauldron/screen2words_15730.json + sampling_strategy: "first:10%" + - json_path: /mnt/bn/vl-research/data/llava_instruct/cauldron/tabmwp_22722.json + sampling_strategy: "first:5%" + - json_path: /mnt/bn/vl-research/data/llava_instruct/cauldron/tallyqa_98680_llava_format.json + sampling_strategy: "first:5%" + - json_path: /mnt/bn/vl-research/data/llava_instruct/cauldron/st_vqa_17247_llava_format.json + sampling_strategy: "first:10%" + - json_path: /mnt/bn/vl-research/data/llava_instruct/cauldron/tqa_llava_format_27307.json + sampling_strategy: "first:5%" + - json_path: /mnt/bn/vl-research/data/llava_instruct/cauldron/visual7w_llava_format_14366.json + sampling_strategy: "first:10%" + - json_path: /mnt/bn/vl-research/data/llava_instruct/cauldron/visualmrc_3027.json + sampling_strategy: "first:10%" + - json_path: /mnt/bn/vl-research/data/llava_instruct/cauldron/vqarad_313_llava_format.json + sampling_strategy: "first:10%" + - json_path: /mnt/bn/vl-research/data/llava_instruct/cauldron/vsr_2157_llava_format.json + sampling_strategy: "first:10%" + - json_path: /mnt/bn/vl-research/data/llava_instruct/cauldron/vistext_9969.json + sampling_strategy: "first:10%" + - json_path: /mnt/bn/vl-research/data/llava_instruct/cauldron/websight_10000.json + sampling_strategy: "first:10%" + - json_path: /mnt/bn/vl-research/data/llava_instruct/real_vision_flan/llava_ofa_DEMON-FULL_filtered_311085.json + sampling_strategy: all + - json_path: /mnt/bn/vl-research/data/llava_instruct/real_vision_flan/llava_ofa_mantis-instruct_reformatted.json + sampling_strategy: all + # - json_path: /mnt/bn/vl-research/data/llava_instruct/real_vision_flan/academic_source_30s_v1_all.json + # sampling_strategy: all + # - json_path: /mnt/bn/vl-research/data/llava_instruct/real_vision_flan/0718_0_30_s_academic_mc_v0_1_all.json + # sampling_strategy: all + # - json_path: /mnt/bn/vl-research/data/llava_instruct/real_vision_flan/sharegpt4video_255000.json + # sampling_strategy: all + - json_path: /mnt/bn/tiktok-mm-3/aiic/users/wujinming/_training_data/jsons/tos/0_30_s_academic_v0_1_cap.json + sampling_strategy: "all" + - json_path: /mnt/bn/tiktok-mm-3/aiic/users/wujinming/_training_data/jsons/tos/0_30_s_youtube_v0_1_cap.json + sampling_strategy: "all" + - json_path: /mnt/bn/tiktok-mm-3/aiic/users/wujinming/_training_data/jsons/tos/30_60_s_academic_v0_1_cap.json + sampling_strategy: "all" + - json_path: /mnt/bn/tiktok-mm-3/aiic/users/wujinming/_training_data/jsons/tos/30_60_s_youtube_v0_1_cap.json + sampling_strategy: "all" + - json_path: /mnt/bn/tiktok-mm-3/aiic/users/wujinming/_training_data/jsons/tos/1_2_m_academic_v0_1_cap.json + sampling_strategy: "all" + - json_path: /mnt/bn/tiktok-mm-3/aiic/users/wujinming/_training_data/jsons/tos/1_2_m_youtube_v0_1_cap.json + sampling_strategy: "all" + - json_path: /mnt/bn/tiktok-mm-3/aiic/users/wujinming/_training_data/jsons/tos/0_30_s_academic_oe_v0_1_qa.json + sampling_strategy: "all" + - json_path: /mnt/bn/tiktok-mm-3/aiic/users/wujinming/_training_data/jsons/tos/0_30_s_academic_mc_v0_1_qa.json + sampling_strategy: "all" + - json_path: /mnt/bn/tiktok-mm-3/aiic/users/wujinming/_training_data/jsons/tos/0_30_s_youtube_oe_v0_1_qa.json + sampling_strategy: "all" + - json_path: /mnt/bn/tiktok-mm-3/aiic/users/wujinming/_training_data/jsons/tos/0_30_s_youtube_mc_v0_1_qa.json + sampling_strategy: "all" + - json_path: /mnt/bn/tiktok-mm-3/aiic/users/wujinming/_training_data/jsons/tos/0_30_s_activitynetqa_oe_qa.json + sampling_strategy: "all" + - json_path: /mnt/bn/tiktok-mm-3/aiic/users/wujinming/_training_data/jsons/tos/0_30_s_nextqa_oe_qa.json + sampling_strategy: "all" + - json_path: /mnt/bn/tiktok-mm-3/aiic/users/wujinming/_training_data/jsons/tos/0_30_s_nextqa_mc_qa.json + sampling_strategy: "all" + - json_path: /mnt/bn/tiktok-mm-3/aiic/users/wujinming/_training_data/jsons/tos/0_30_s_perceptiontest_mc_qa.json + sampling_strategy: "all" + - json_path: /mnt/bn/tiktok-mm-3/aiic/users/wujinming/_training_data/jsons/tos/30_60_s_academic_oe_v0_1_qa.json + sampling_strategy: "all" + - json_path: /mnt/bn/tiktok-mm-3/aiic/users/wujinming/_training_data/jsons/tos/30_60_s_academic_mc_v0_1_qa.json + sampling_strategy: "all" + - json_path: /mnt/bn/tiktok-mm-3/aiic/users/wujinming/_training_data/jsons/tos/30_60_s_youtube_oe_v0_1_qa.json + sampling_strategy: "all" + - json_path: /mnt/bn/tiktok-mm-3/aiic/users/wujinming/_training_data/jsons/tos/30_60_s_youtube_mc_v0_1_qa.json + sampling_strategy: "all" + - json_path: /mnt/bn/tiktok-mm-3/aiic/users/wujinming/_training_data/jsons/tos/30_60_s_activitynetqa_oe_qa.json + sampling_strategy: "all" + - json_path: /mnt/bn/tiktok-mm-3/aiic/users/wujinming/_training_data/jsons/tos/30_60_s_nextqa_oe_qa.json + sampling_strategy: "all" + - json_path: /mnt/bn/tiktok-mm-3/aiic/users/wujinming/_training_data/jsons/tos/30_60_s_nextqa_mc_qa.json + sampling_strategy: "all" + - json_path: /mnt/bn/tiktok-mm-3/aiic/users/wujinming/_training_data/jsons/tos/30_60_s_perceptiontest_mc_qa.json + sampling_strategy: "all" + - json_path: /mnt/bn/tiktok-mm-3/aiic/users/wujinming/_training_data/jsons/tos/1_2_m_academic_oe_v0_1_qa.json + sampling_strategy: "all" + - json_path: /mnt/bn/tiktok-mm-3/aiic/users/wujinming/_training_data/jsons/tos/1_2_m_academic_mc_v0_1_qa.json + sampling_strategy: "all" + - json_path: /mnt/bn/tiktok-mm-3/aiic/users/wujinming/_training_data/jsons/tos/1_2_m_youtube_oe_v0_1_qa.json + sampling_strategy: "all" + - json_path: /mnt/bn/tiktok-mm-3/aiic/users/wujinming/_training_data/jsons/tos/1_2_m_youtube_mc_v0_1_qa.json + sampling_strategy: "all" + - json_path: /mnt/bn/tiktok-mm-3/aiic/users/wujinming/_training_data/jsons/tos/1_2_m_activitynetqa_oe_qa.json + sampling_strategy: "all" + - json_path: /mnt/bn/tiktok-mm-3/aiic/users/wujinming/_training_data/jsons/tos/1_2_m_nextqa_oe_qa.json + sampling_strategy: "all" + - json_path: /mnt/bn/tiktok-mm-3/aiic/users/wujinming/_training_data/jsons/tos/1_2_m_nextqa_mc_qa.json + sampling_strategy: "all" + - json_path: /mnt/bn/tiktok-mm-3/aiic/users/wujinming/_training_data/jsons/tos/sharegptvideo_qa_255k.json + sampling_strategy: "all" + - json_path: /mnt/bn/tiktok-mm-3/aiic/users/wujinming/_training_data/jsons/tos/2_3_m_academic_v0_1_cap.json + sampling_strategy: "all" + - json_path: /mnt/bn/tiktok-mm-3/aiic/users/wujinming/_training_data/jsons/tos/2_3_m_youtube_v0_1_cap.json + sampling_strategy: "all" + - json_path: /mnt/bn/tiktok-mm-3/aiic/users/wujinming/_training_data/jsons/tos/2_3_m_academic_oe_v0_1_qa.json + sampling_strategy: "all" + - json_path: /mnt/bn/tiktok-mm-3/aiic/users/wujinming/_training_data/jsons/tos/2_3_m_academic_mc_v0_1_qa.json + sampling_strategy: "all" + - json_path: /mnt/bn/tiktok-mm-3/aiic/users/wujinming/_training_data/jsons/tos/2_3_m_youtube_oe_v0_1_qa.json + sampling_strategy: "all" + - json_path: /mnt/bn/tiktok-mm-3/aiic/users/wujinming/_training_data/jsons/tos/2_3_m_youtube_mc_v0_1_qa.json + sampling_strategy: "all" + - json_path: /mnt/bn/tiktok-mm-3/aiic/users/wujinming/_training_data/jsons/tos/2_3_m_nextqa_oe_qa.json + sampling_strategy: "all" + - json_path: /mnt/bn/tiktok-mm-3/aiic/users/wujinming/_training_data/jsons/tos/2_3_m_nextqa_mc_qa.json + sampling_strategy: "all" + - json_path: /mnt/bn/tiktok-mm-3/aiic/users/wujinming/_training_data/jsons/tos/2_3_m_activitynetqa_oe_qa.json + sampling_strategy: "all"