Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- .gitattributes +64 -0
- hf_datas/llava_v1_5_mix665k.json +3 -0
- hf_models/clip-vit-large-patch14-336/pytorch_model.bin +3 -0
- hf_models/clip-vit-large-patch14-336/tf_model.h5 +3 -0
- hf_models/vicuna-7b-v1.5/pytorch_model-00001-of-00002.bin +3 -0
- hf_models/vicuna-7b-v1.5/pytorch_model-00002-of-00002.bin +3 -0
- llava/__pycache__/__init__.cpython-310.pyc +0 -0
- llava/__pycache__/constants.cpython-310.pyc +0 -0
- llava/__pycache__/conversation.cpython-310.pyc +0 -0
- llava/__pycache__/mm_utils.cpython-310.pyc +0 -0
- llava/__pycache__/utils.cpython-310.pyc +0 -0
- llava/eval/__pycache__/m4c_evaluator.cpython-310.pyc +0 -0
- llava/eval/__pycache__/model_vqa_loader.cpython-310.pyc +0 -0
- llava/eval/__pycache__/model_vqa_mmbench.cpython-310.pyc +0 -0
- llava/eval/__pycache__/model_vqa_science.cpython-310.pyc +0 -0
- llava/eval/eval_science_qa.py +114 -0
- llava/eval/m4c_evaluator.py +334 -0
- llava/eval/model_vqa_loader.py +158 -0
- llava/eval/model_vqa_mmbench.py +170 -0
- llava/eval/model_vqa_science.py +122 -0
- llava/train/__pycache__/llava_trainer.cpython-310.pyc +0 -0
- llava/train/__pycache__/train_compress.cpython-310.pyc +0 -0
- llava/train/llama_flash_attn_monkey_patch.py +115 -0
- llava/train/llama_xformers_attn_monkey_patch.py +129 -0
- llava/train/train_compress.py +1014 -0
- playground/data.z01 +3 -0
- playground/data.z02 +3 -0
- playground/data.z04 +3 -0
- playground/data.z05 +3 -0
- playground/data.z06 +3 -0
- playground/data.z07 +3 -0
- playground/data.z08 +3 -0
- playground/data.z09 +3 -0
- playground/data.z10 +3 -0
- playground/data.z11 +3 -0
- playground/data.z12 +3 -0
- playground/data.z14 +3 -0
- playground/data.z15 +3 -0
- playground/data.z16 +3 -0
- playground/data.z18 +3 -0
- playground/data.z19 +3 -0
- playground/data.z20 +3 -0
- playground/data.z21 +3 -0
- playground/data.z23 +3 -0
- playground/data.z24 +3 -0
- playground/data.z25 +3 -0
- playground/data.z26 +3 -0
- playground/data.z27 +3 -0
- playground/data.z28 +3 -0
- playground/data.z30 +3 -0
.gitattributes
CHANGED
@@ -57,3 +57,67 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
57 |
# Video files - compressed
|
58 |
*.mp4 filter=lfs diff=lfs merge=lfs -text
|
59 |
*.webm filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
57 |
# Video files - compressed
|
58 |
*.mp4 filter=lfs diff=lfs merge=lfs -text
|
59 |
*.webm filter=lfs diff=lfs merge=lfs -text
|
60 |
+
hf_datas/llava_v1_5_mix665k.json filter=lfs diff=lfs merge=lfs -text
|
61 |
+
playground/data.z52 filter=lfs diff=lfs merge=lfs -text
|
62 |
+
playground/data.z40 filter=lfs diff=lfs merge=lfs -text
|
63 |
+
playground/data.z05 filter=lfs diff=lfs merge=lfs -text
|
64 |
+
playground/data.z74 filter=lfs diff=lfs merge=lfs -text
|
65 |
+
playground/data.z01 filter=lfs diff=lfs merge=lfs -text
|
66 |
+
playground/data.z60 filter=lfs diff=lfs merge=lfs -text
|
67 |
+
playground/data.z65 filter=lfs diff=lfs merge=lfs -text
|
68 |
+
playground/data.z37 filter=lfs diff=lfs merge=lfs -text
|
69 |
+
playground/data.z62 filter=lfs diff=lfs merge=lfs -text
|
70 |
+
playground/data.z63 filter=lfs diff=lfs merge=lfs -text
|
71 |
+
playground/data.z21 filter=lfs diff=lfs merge=lfs -text
|
72 |
+
playground/data.z53 filter=lfs diff=lfs merge=lfs -text
|
73 |
+
playground/data.z41 filter=lfs diff=lfs merge=lfs -text
|
74 |
+
playground/data.z07 filter=lfs diff=lfs merge=lfs -text
|
75 |
+
playground/data.z35 filter=lfs diff=lfs merge=lfs -text
|
76 |
+
playground/data.z06 filter=lfs diff=lfs merge=lfs -text
|
77 |
+
playground/data.z50 filter=lfs diff=lfs merge=lfs -text
|
78 |
+
playground/data.z12 filter=lfs diff=lfs merge=lfs -text
|
79 |
+
playground/data.z15 filter=lfs diff=lfs merge=lfs -text
|
80 |
+
playground/data.z18 filter=lfs diff=lfs merge=lfs -text
|
81 |
+
playground/data.z23 filter=lfs diff=lfs merge=lfs -text
|
82 |
+
playground/data.z09 filter=lfs diff=lfs merge=lfs -text
|
83 |
+
playground/data.z11 filter=lfs diff=lfs merge=lfs -text
|
84 |
+
playground/data.z38 filter=lfs diff=lfs merge=lfs -text
|
85 |
+
playground/data.z33 filter=lfs diff=lfs merge=lfs -text
|
86 |
+
playground/data.z70 filter=lfs diff=lfs merge=lfs -text
|
87 |
+
playground/data.z02 filter=lfs diff=lfs merge=lfs -text
|
88 |
+
playground/data.z51 filter=lfs diff=lfs merge=lfs -text
|
89 |
+
playground/data.z73 filter=lfs diff=lfs merge=lfs -text
|
90 |
+
playground/data.z42 filter=lfs diff=lfs merge=lfs -text
|
91 |
+
playground/data.z30 filter=lfs diff=lfs merge=lfs -text
|
92 |
+
playground/data.z64 filter=lfs diff=lfs merge=lfs -text
|
93 |
+
playground/data.z46 filter=lfs diff=lfs merge=lfs -text
|
94 |
+
playground/data.z27 filter=lfs diff=lfs merge=lfs -text
|
95 |
+
playground/data.z19 filter=lfs diff=lfs merge=lfs -text
|
96 |
+
playground/data.z04 filter=lfs diff=lfs merge=lfs -text
|
97 |
+
playground/data.z28 filter=lfs diff=lfs merge=lfs -text
|
98 |
+
playground/data.z48 filter=lfs diff=lfs merge=lfs -text
|
99 |
+
playground/data.z16 filter=lfs diff=lfs merge=lfs -text
|
100 |
+
playground/data.z71 filter=lfs diff=lfs merge=lfs -text
|
101 |
+
playground/data.z24 filter=lfs diff=lfs merge=lfs -text
|
102 |
+
playground/data.z69 filter=lfs diff=lfs merge=lfs -text
|
103 |
+
playground/data.z61 filter=lfs diff=lfs merge=lfs -text
|
104 |
+
playground/data.z68 filter=lfs diff=lfs merge=lfs -text
|
105 |
+
playground/data.z14 filter=lfs diff=lfs merge=lfs -text
|
106 |
+
playground/data.z58 filter=lfs diff=lfs merge=lfs -text
|
107 |
+
playground/data.z75 filter=lfs diff=lfs merge=lfs -text
|
108 |
+
playground/data.z44 filter=lfs diff=lfs merge=lfs -text
|
109 |
+
playground/data.z49 filter=lfs diff=lfs merge=lfs -text
|
110 |
+
playground/data.z10 filter=lfs diff=lfs merge=lfs -text
|
111 |
+
playground/data.z43 filter=lfs diff=lfs merge=lfs -text
|
112 |
+
playground/data.z39 filter=lfs diff=lfs merge=lfs -text
|
113 |
+
playground/data.z26 filter=lfs diff=lfs merge=lfs -text
|
114 |
+
playground/data.z55 filter=lfs diff=lfs merge=lfs -text
|
115 |
+
playground/data.z36 filter=lfs diff=lfs merge=lfs -text
|
116 |
+
playground/data.z08 filter=lfs diff=lfs merge=lfs -text
|
117 |
+
playground/data.z20 filter=lfs diff=lfs merge=lfs -text
|
118 |
+
playground/data.z67 filter=lfs diff=lfs merge=lfs -text
|
119 |
+
playground/data.z25 filter=lfs diff=lfs merge=lfs -text
|
120 |
+
playground/data.z31 filter=lfs diff=lfs merge=lfs -text
|
121 |
+
playground/data.z45 filter=lfs diff=lfs merge=lfs -text
|
122 |
+
playground/data.z47 filter=lfs diff=lfs merge=lfs -text
|
123 |
+
playground/data.z57 filter=lfs diff=lfs merge=lfs -text
|
hf_datas/llava_v1_5_mix665k.json
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:ce959ce6e23073ee1cd1a8a2ef1c633768c10d4174327b8b2dc7113b91af6cf8
|
3 |
+
size 1029887963
|
hf_models/clip-vit-large-patch14-336/pytorch_model.bin
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:c6032c2e0caae3dc2d4fba35535fa6307dbb49df59c7e182b1bc4b3329b81801
|
3 |
+
size 1711974081
|
hf_models/clip-vit-large-patch14-336/tf_model.h5
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:d12828ca8f0f3c92194f277b7d893da7f2fb7824d0b99dedb305eb48eb46bb7f
|
3 |
+
size 1712454232
|
hf_models/vicuna-7b-v1.5/pytorch_model-00001-of-00002.bin
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:4133d2fcc5f31286881ea50806d95b721d016b533036a99dedce3f8fe88520e6
|
3 |
+
size 9976634558
|
hf_models/vicuna-7b-v1.5/pytorch_model-00002-of-00002.bin
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:d261d3c35e92d3070d1e61ed821ebfca812a847d2a880757d82728acf005c5ac
|
3 |
+
size 3500315539
|
llava/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (199 Bytes). View file
|
|
llava/__pycache__/constants.cpython-310.pyc
ADDED
Binary file (507 Bytes). View file
|
|
llava/__pycache__/conversation.cpython-310.pyc
ADDED
Binary file (12.1 kB). View file
|
|
llava/__pycache__/mm_utils.cpython-310.pyc
ADDED
Binary file (8.78 kB). View file
|
|
llava/__pycache__/utils.cpython-310.pyc
ADDED
Binary file (4.04 kB). View file
|
|
llava/eval/__pycache__/m4c_evaluator.cpython-310.pyc
ADDED
Binary file (10.1 kB). View file
|
|
llava/eval/__pycache__/model_vqa_loader.cpython-310.pyc
ADDED
Binary file (5.96 kB). View file
|
|
llava/eval/__pycache__/model_vqa_mmbench.cpython-310.pyc
ADDED
Binary file (5.45 kB). View file
|
|
llava/eval/__pycache__/model_vqa_science.cpython-310.pyc
ADDED
Binary file (4.25 kB). View file
|
|
llava/eval/eval_science_qa.py
ADDED
@@ -0,0 +1,114 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import argparse
|
2 |
+
import json
|
3 |
+
import os
|
4 |
+
import re
|
5 |
+
import random
|
6 |
+
|
7 |
+
|
8 |
+
def get_args():
|
9 |
+
parser = argparse.ArgumentParser()
|
10 |
+
parser.add_argument('--base-dir', type=str)
|
11 |
+
parser.add_argument('--result-file', type=str)
|
12 |
+
parser.add_argument('--output-file', type=str)
|
13 |
+
parser.add_argument('--output-result', type=str)
|
14 |
+
parser.add_argument('--split', type=str, default='test')
|
15 |
+
parser.add_argument('--options', type=list, default=["A", "B", "C", "D", "E"])
|
16 |
+
return parser.parse_args()
|
17 |
+
|
18 |
+
|
19 |
+
def convert_caps(results):
|
20 |
+
fakecaps = []
|
21 |
+
for result in results:
|
22 |
+
image_id = result['question_id']
|
23 |
+
caption = result['text']
|
24 |
+
fakecaps.append({"image_id": int(image_id), "caption": caption})
|
25 |
+
return fakecaps
|
26 |
+
|
27 |
+
|
28 |
+
def get_pred_idx(prediction, choices, options):
|
29 |
+
"""
|
30 |
+
Get the index (e.g. 2) from the prediction (e.g. 'C')
|
31 |
+
"""
|
32 |
+
if prediction in options[:len(choices)]:
|
33 |
+
return options.index(prediction)
|
34 |
+
else:
|
35 |
+
return -1
|
36 |
+
return random.choice(range(len(choices)))
|
37 |
+
|
38 |
+
|
39 |
+
if __name__ == "__main__":
|
40 |
+
args = get_args()
|
41 |
+
|
42 |
+
base_dir = args.base_dir
|
43 |
+
split_indices = json.load(open(os.path.join(base_dir, "pid_splits.json")))[args.split]
|
44 |
+
problems = json.load(open(os.path.join(base_dir, "problems.json")))
|
45 |
+
predictions = [json.loads(line) for line in open(args.result_file)]
|
46 |
+
predictions = {pred['question_id']: pred for pred in predictions}
|
47 |
+
split_problems = {idx: problems[idx] for idx in split_indices}
|
48 |
+
|
49 |
+
results = {'correct': [], 'incorrect': []}
|
50 |
+
sqa_results = {}
|
51 |
+
sqa_results['acc'] = None
|
52 |
+
sqa_results['correct'] = None
|
53 |
+
sqa_results['count'] = None
|
54 |
+
sqa_results['results'] = {}
|
55 |
+
sqa_results['outputs'] = {}
|
56 |
+
|
57 |
+
for prob_id, prob in split_problems.items():
|
58 |
+
if prob_id not in predictions:
|
59 |
+
pred = {'text': 'FAILED', 'prompt': 'Unknown'}
|
60 |
+
pred_text = 'FAILED'
|
61 |
+
else:
|
62 |
+
pred = predictions[prob_id]
|
63 |
+
pred_text = pred['text']
|
64 |
+
|
65 |
+
if pred_text in args.options:
|
66 |
+
answer = pred_text
|
67 |
+
elif len(pred_text) >= 3 and pred_text[0] in args.options and pred_text[1:3] == ". ":
|
68 |
+
answer = pred_text[0]
|
69 |
+
else:
|
70 |
+
pattern = re.compile(r'The answer is ([A-Z]).')
|
71 |
+
res = pattern.findall(pred_text)
|
72 |
+
if len(res) == 1:
|
73 |
+
answer = res[0] # 'A', 'B', ...
|
74 |
+
else:
|
75 |
+
answer = "FAILED"
|
76 |
+
|
77 |
+
pred_idx = get_pred_idx(answer, prob['choices'], args.options)
|
78 |
+
|
79 |
+
analysis = {
|
80 |
+
'question_id': prob_id,
|
81 |
+
'parsed_ans': answer,
|
82 |
+
'ground_truth': args.options[prob['answer']],
|
83 |
+
'question': pred['prompt'],
|
84 |
+
'pred': pred_text,
|
85 |
+
'is_multimodal': '<image>' in pred['prompt'],
|
86 |
+
}
|
87 |
+
|
88 |
+
sqa_results['results'][prob_id] = get_pred_idx(answer, prob['choices'], args.options)
|
89 |
+
sqa_results['outputs'][prob_id] = pred_text
|
90 |
+
|
91 |
+
if pred_idx == prob['answer']:
|
92 |
+
results['correct'].append(analysis)
|
93 |
+
else:
|
94 |
+
results['incorrect'].append(analysis)
|
95 |
+
|
96 |
+
correct = len(results['correct'])
|
97 |
+
total = len(results['correct']) + len(results['incorrect'])
|
98 |
+
|
99 |
+
###### IMG ######
|
100 |
+
multimodal_correct = len([x for x in results['correct'] if x['is_multimodal']])
|
101 |
+
multimodal_incorrect = len([x for x in results['incorrect'] if x['is_multimodal']])
|
102 |
+
multimodal_total = multimodal_correct + multimodal_incorrect
|
103 |
+
###### IMG ######
|
104 |
+
|
105 |
+
print(f'Total: {total}, Correct: {correct}, Accuracy: {correct / total * 100:.2f}%, IMG-Accuracy: {multimodal_correct / multimodal_total * 100:.2f}%')
|
106 |
+
|
107 |
+
sqa_results['acc'] = correct / total * 100
|
108 |
+
sqa_results['correct'] = correct
|
109 |
+
sqa_results['count'] = total
|
110 |
+
|
111 |
+
with open(args.output_file, 'w') as f:
|
112 |
+
json.dump(results, f, indent=2)
|
113 |
+
with open(args.output_result, 'w') as f:
|
114 |
+
json.dump(sqa_results, f, indent=2)
|
llava/eval/m4c_evaluator.py
ADDED
@@ -0,0 +1,334 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright (c) Facebook, Inc. and its affiliates.
|
2 |
+
import re
|
3 |
+
|
4 |
+
from tqdm import tqdm
|
5 |
+
|
6 |
+
|
7 |
+
class EvalAIAnswerProcessor:
|
8 |
+
"""
|
9 |
+
Processes an answer similar to Eval AI
|
10 |
+
copied from
|
11 |
+
https://github.com/facebookresearch/mmf/blob/c46b3b3391275b4181567db80943473a89ab98ab/pythia/tasks/processors.py#L897
|
12 |
+
"""
|
13 |
+
|
14 |
+
CONTRACTIONS = {
|
15 |
+
"aint": "ain't",
|
16 |
+
"arent": "aren't",
|
17 |
+
"cant": "can't",
|
18 |
+
"couldve": "could've",
|
19 |
+
"couldnt": "couldn't",
|
20 |
+
"couldn'tve": "couldn't've",
|
21 |
+
"couldnt've": "couldn't've",
|
22 |
+
"didnt": "didn't",
|
23 |
+
"doesnt": "doesn't",
|
24 |
+
"dont": "don't",
|
25 |
+
"hadnt": "hadn't",
|
26 |
+
"hadnt've": "hadn't've",
|
27 |
+
"hadn'tve": "hadn't've",
|
28 |
+
"hasnt": "hasn't",
|
29 |
+
"havent": "haven't",
|
30 |
+
"hed": "he'd",
|
31 |
+
"hed've": "he'd've",
|
32 |
+
"he'dve": "he'd've",
|
33 |
+
"hes": "he's",
|
34 |
+
"howd": "how'd",
|
35 |
+
"howll": "how'll",
|
36 |
+
"hows": "how's",
|
37 |
+
"Id've": "I'd've",
|
38 |
+
"I'dve": "I'd've",
|
39 |
+
"Im": "I'm",
|
40 |
+
"Ive": "I've",
|
41 |
+
"isnt": "isn't",
|
42 |
+
"itd": "it'd",
|
43 |
+
"itd've": "it'd've",
|
44 |
+
"it'dve": "it'd've",
|
45 |
+
"itll": "it'll",
|
46 |
+
"let's": "let's",
|
47 |
+
"maam": "ma'am",
|
48 |
+
"mightnt": "mightn't",
|
49 |
+
"mightnt've": "mightn't've",
|
50 |
+
"mightn'tve": "mightn't've",
|
51 |
+
"mightve": "might've",
|
52 |
+
"mustnt": "mustn't",
|
53 |
+
"mustve": "must've",
|
54 |
+
"neednt": "needn't",
|
55 |
+
"notve": "not've",
|
56 |
+
"oclock": "o'clock",
|
57 |
+
"oughtnt": "oughtn't",
|
58 |
+
"ow's'at": "'ow's'at",
|
59 |
+
"'ows'at": "'ow's'at",
|
60 |
+
"'ow'sat": "'ow's'at",
|
61 |
+
"shant": "shan't",
|
62 |
+
"shed've": "she'd've",
|
63 |
+
"she'dve": "she'd've",
|
64 |
+
"she's": "she's",
|
65 |
+
"shouldve": "should've",
|
66 |
+
"shouldnt": "shouldn't",
|
67 |
+
"shouldnt've": "shouldn't've",
|
68 |
+
"shouldn'tve": "shouldn't've",
|
69 |
+
"somebody'd": "somebodyd",
|
70 |
+
"somebodyd've": "somebody'd've",
|
71 |
+
"somebody'dve": "somebody'd've",
|
72 |
+
"somebodyll": "somebody'll",
|
73 |
+
"somebodys": "somebody's",
|
74 |
+
"someoned": "someone'd",
|
75 |
+
"someoned've": "someone'd've",
|
76 |
+
"someone'dve": "someone'd've",
|
77 |
+
"someonell": "someone'll",
|
78 |
+
"someones": "someone's",
|
79 |
+
"somethingd": "something'd",
|
80 |
+
"somethingd've": "something'd've",
|
81 |
+
"something'dve": "something'd've",
|
82 |
+
"somethingll": "something'll",
|
83 |
+
"thats": "that's",
|
84 |
+
"thered": "there'd",
|
85 |
+
"thered've": "there'd've",
|
86 |
+
"there'dve": "there'd've",
|
87 |
+
"therere": "there're",
|
88 |
+
"theres": "there's",
|
89 |
+
"theyd": "they'd",
|
90 |
+
"theyd've": "they'd've",
|
91 |
+
"they'dve": "they'd've",
|
92 |
+
"theyll": "they'll",
|
93 |
+
"theyre": "they're",
|
94 |
+
"theyve": "they've",
|
95 |
+
"twas": "'twas",
|
96 |
+
"wasnt": "wasn't",
|
97 |
+
"wed've": "we'd've",
|
98 |
+
"we'dve": "we'd've",
|
99 |
+
"weve": "we've",
|
100 |
+
"werent": "weren't",
|
101 |
+
"whatll": "what'll",
|
102 |
+
"whatre": "what're",
|
103 |
+
"whats": "what's",
|
104 |
+
"whatve": "what've",
|
105 |
+
"whens": "when's",
|
106 |
+
"whered": "where'd",
|
107 |
+
"wheres": "where's",
|
108 |
+
"whereve": "where've",
|
109 |
+
"whod": "who'd",
|
110 |
+
"whod've": "who'd've",
|
111 |
+
"who'dve": "who'd've",
|
112 |
+
"wholl": "who'll",
|
113 |
+
"whos": "who's",
|
114 |
+
"whove": "who've",
|
115 |
+
"whyll": "why'll",
|
116 |
+
"whyre": "why're",
|
117 |
+
"whys": "why's",
|
118 |
+
"wont": "won't",
|
119 |
+
"wouldve": "would've",
|
120 |
+
"wouldnt": "wouldn't",
|
121 |
+
"wouldnt've": "wouldn't've",
|
122 |
+
"wouldn'tve": "wouldn't've",
|
123 |
+
"yall": "y'all",
|
124 |
+
"yall'll": "y'all'll",
|
125 |
+
"y'allll": "y'all'll",
|
126 |
+
"yall'd've": "y'all'd've",
|
127 |
+
"y'alld've": "y'all'd've",
|
128 |
+
"y'all'dve": "y'all'd've",
|
129 |
+
"youd": "you'd",
|
130 |
+
"youd've": "you'd've",
|
131 |
+
"you'dve": "you'd've",
|
132 |
+
"youll": "you'll",
|
133 |
+
"youre": "you're",
|
134 |
+
"youve": "you've",
|
135 |
+
}
|
136 |
+
|
137 |
+
NUMBER_MAP = {
|
138 |
+
"none": "0",
|
139 |
+
"zero": "0",
|
140 |
+
"one": "1",
|
141 |
+
"two": "2",
|
142 |
+
"three": "3",
|
143 |
+
"four": "4",
|
144 |
+
"five": "5",
|
145 |
+
"six": "6",
|
146 |
+
"seven": "7",
|
147 |
+
"eight": "8",
|
148 |
+
"nine": "9",
|
149 |
+
"ten": "10",
|
150 |
+
}
|
151 |
+
ARTICLES = ["a", "an", "the"]
|
152 |
+
PERIOD_STRIP = re.compile(r"(?!<=\d)(\.)(?!\d)")
|
153 |
+
COMMA_STRIP = re.compile(r"(?<=\d)(\,)+(?=\d)")
|
154 |
+
PUNCTUATIONS = [
|
155 |
+
";",
|
156 |
+
r"/",
|
157 |
+
"[",
|
158 |
+
"]",
|
159 |
+
'"',
|
160 |
+
"{",
|
161 |
+
"}",
|
162 |
+
"(",
|
163 |
+
")",
|
164 |
+
"=",
|
165 |
+
"+",
|
166 |
+
"\\",
|
167 |
+
"_",
|
168 |
+
"-",
|
169 |
+
">",
|
170 |
+
"<",
|
171 |
+
"@",
|
172 |
+
"`",
|
173 |
+
",",
|
174 |
+
"?",
|
175 |
+
"!",
|
176 |
+
]
|
177 |
+
|
178 |
+
def __init__(self, *args, **kwargs):
|
179 |
+
pass
|
180 |
+
|
181 |
+
def word_tokenize(self, word):
|
182 |
+
word = word.lower()
|
183 |
+
word = word.replace(",", "").replace("?", "").replace("'s", " 's")
|
184 |
+
return word.strip()
|
185 |
+
|
186 |
+
def process_punctuation(self, in_text):
|
187 |
+
out_text = in_text
|
188 |
+
for p in self.PUNCTUATIONS:
|
189 |
+
if (p + " " in in_text or " " + p in in_text) or (
|
190 |
+
re.search(self.COMMA_STRIP, in_text) is not None
|
191 |
+
):
|
192 |
+
out_text = out_text.replace(p, "")
|
193 |
+
else:
|
194 |
+
out_text = out_text.replace(p, " ")
|
195 |
+
out_text = self.PERIOD_STRIP.sub("", out_text, re.UNICODE)
|
196 |
+
return out_text
|
197 |
+
|
198 |
+
def process_digit_article(self, in_text):
|
199 |
+
out_text = []
|
200 |
+
temp_text = in_text.lower().split()
|
201 |
+
for word in temp_text:
|
202 |
+
word = self.NUMBER_MAP.setdefault(word, word)
|
203 |
+
if word not in self.ARTICLES:
|
204 |
+
out_text.append(word)
|
205 |
+
else:
|
206 |
+
pass
|
207 |
+
for word_id, word in enumerate(out_text):
|
208 |
+
if word in self.CONTRACTIONS:
|
209 |
+
out_text[word_id] = self.CONTRACTIONS[word]
|
210 |
+
out_text = " ".join(out_text)
|
211 |
+
return out_text
|
212 |
+
|
213 |
+
def __call__(self, item):
|
214 |
+
item = self.word_tokenize(item)
|
215 |
+
item = item.replace("\n", " ").replace("\t", " ").strip()
|
216 |
+
item = self.process_punctuation(item)
|
217 |
+
item = self.process_digit_article(item)
|
218 |
+
return item
|
219 |
+
|
220 |
+
|
221 |
+
class TextVQAAccuracyEvaluator:
|
222 |
+
def __init__(self):
|
223 |
+
self.answer_processor = EvalAIAnswerProcessor()
|
224 |
+
|
225 |
+
def _compute_answer_scores(self, raw_answers):
|
226 |
+
"""
|
227 |
+
compute the accuracy (soft score) of human answers
|
228 |
+
"""
|
229 |
+
answers = [self.answer_processor(a) for a in raw_answers]
|
230 |
+
assert len(answers) == 10
|
231 |
+
gt_answers = list(enumerate(answers))
|
232 |
+
unique_answers = set(answers)
|
233 |
+
unique_answer_scores = {}
|
234 |
+
|
235 |
+
for unique_answer in unique_answers:
|
236 |
+
accs = []
|
237 |
+
for gt_answer in gt_answers:
|
238 |
+
other_answers = [item for item in gt_answers if item != gt_answer]
|
239 |
+
matching_answers = [
|
240 |
+
item for item in other_answers if item[1] == unique_answer
|
241 |
+
]
|
242 |
+
acc = min(1, float(len(matching_answers)) / 3)
|
243 |
+
accs.append(acc)
|
244 |
+
unique_answer_scores[unique_answer] = sum(accs) / len(accs)
|
245 |
+
|
246 |
+
return unique_answer_scores
|
247 |
+
|
248 |
+
def eval_pred_list(self, pred_list):
|
249 |
+
pred_scores = []
|
250 |
+
for entry in tqdm(pred_list):
|
251 |
+
pred_answer = self.answer_processor(entry["pred_answer"])
|
252 |
+
unique_answer_scores = self._compute_answer_scores(entry["gt_answers"])
|
253 |
+
score = unique_answer_scores.get(pred_answer, 0.0)
|
254 |
+
pred_scores.append(score)
|
255 |
+
|
256 |
+
accuracy = sum(pred_scores) / len(pred_scores)
|
257 |
+
return accuracy
|
258 |
+
|
259 |
+
|
260 |
+
class STVQAAccuracyEvaluator:
|
261 |
+
def __init__(self):
|
262 |
+
self.answer_processor = EvalAIAnswerProcessor()
|
263 |
+
|
264 |
+
def eval_pred_list(self, pred_list):
|
265 |
+
pred_scores = []
|
266 |
+
for entry in pred_list:
|
267 |
+
pred_answer = self.answer_processor(entry["pred_answer"])
|
268 |
+
gts = [self.answer_processor(a) for a in entry["gt_answers"]]
|
269 |
+
score = 1.0 if pred_answer in gts else 0.0
|
270 |
+
pred_scores.append(score)
|
271 |
+
|
272 |
+
accuracy = sum(pred_scores) / len(pred_scores)
|
273 |
+
return accuracy
|
274 |
+
|
275 |
+
|
276 |
+
class STVQAANLSEvaluator:
|
277 |
+
def __init__(self):
|
278 |
+
import editdistance # install with `pip install editdistance`
|
279 |
+
|
280 |
+
self.get_edit_distance = editdistance.eval
|
281 |
+
|
282 |
+
def get_anls(self, s1, s2):
|
283 |
+
s1 = s1.lower().strip()
|
284 |
+
s2 = s2.lower().strip()
|
285 |
+
iou = 1 - self.get_edit_distance(s1, s2) / max(len(s1), len(s2))
|
286 |
+
anls = iou if iou >= 0.5 else 0.0
|
287 |
+
return anls
|
288 |
+
|
289 |
+
def eval_pred_list(self, pred_list):
|
290 |
+
pred_scores = []
|
291 |
+
for entry in pred_list:
|
292 |
+
anls = max(
|
293 |
+
self.get_anls(entry["pred_answer"], gt) for gt in entry["gt_answers"]
|
294 |
+
)
|
295 |
+
pred_scores.append(anls)
|
296 |
+
|
297 |
+
accuracy = sum(pred_scores) / len(pred_scores)
|
298 |
+
return accuracy
|
299 |
+
|
300 |
+
|
301 |
+
class TextCapsBleu4Evaluator:
|
302 |
+
def __init__(self):
|
303 |
+
# The following script requires Java 1.8.0 and pycocotools installed.
|
304 |
+
# The pycocoevalcap can be installed with pip as
|
305 |
+
# pip install git+https://github.com/ronghanghu/coco-caption.git@python23
|
306 |
+
# Original pycocoevalcap code is at https://github.com/tylin/coco-caption
|
307 |
+
# but has no python3 support yet.
|
308 |
+
try:
|
309 |
+
from pycocoevalcap.bleu.bleu import Bleu
|
310 |
+
from pycocoevalcap.tokenizer.ptbtokenizer import PTBTokenizer
|
311 |
+
except ModuleNotFoundError:
|
312 |
+
print(
|
313 |
+
"Please install pycocoevalcap module using "
|
314 |
+
"pip install git+https://github.com/ronghanghu/coco-caption.git@python23" # noqa
|
315 |
+
)
|
316 |
+
raise
|
317 |
+
|
318 |
+
self.tokenizer = PTBTokenizer()
|
319 |
+
self.scorer = Bleu(4)
|
320 |
+
|
321 |
+
def eval_pred_list(self, pred_list):
|
322 |
+
# Create reference and hypotheses captions.
|
323 |
+
gts = {}
|
324 |
+
res = {}
|
325 |
+
for idx, entry in enumerate(pred_list):
|
326 |
+
gts[idx] = [{"caption": a} for a in entry["gt_answers"]]
|
327 |
+
res[idx] = [{"caption": entry["pred_answer"]}]
|
328 |
+
|
329 |
+
gts = self.tokenizer.tokenize(gts)
|
330 |
+
res = self.tokenizer.tokenize(res)
|
331 |
+
score, _ = self.scorer.compute_score(gts, res)
|
332 |
+
|
333 |
+
bleu4 = score[3] # score is (Bleu-1, Bleu-2, Bleu-3, Bleu-4)
|
334 |
+
return bleu4
|
llava/eval/model_vqa_loader.py
ADDED
@@ -0,0 +1,158 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import argparse
|
2 |
+
import torch
|
3 |
+
import os
|
4 |
+
import json
|
5 |
+
from tqdm import tqdm
|
6 |
+
import shortuuid
|
7 |
+
|
8 |
+
from llava.constants import IMAGE_TOKEN_INDEX, DEFAULT_IMAGE_TOKEN, DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN
|
9 |
+
from llava.conversation import conv_templates, SeparatorStyle
|
10 |
+
from llava import conversation as conversation_lib
|
11 |
+
from llava.model.builder import load_pretrained_model
|
12 |
+
from llava.utils import disable_torch_init
|
13 |
+
from llava.mm_utils import tokenizer_image_token, process_images, get_model_name_from_path
|
14 |
+
from torch.utils.data import Dataset, DataLoader
|
15 |
+
|
16 |
+
from PIL import Image
|
17 |
+
import math
|
18 |
+
|
19 |
+
|
20 |
+
def split_list(lst, n):
|
21 |
+
"""Split a list into n (roughly) equal-sized chunks"""
|
22 |
+
chunk_size = math.ceil(len(lst) / n) # integer division
|
23 |
+
return [lst[i:i+chunk_size] for i in range(0, len(lst), chunk_size)]
|
24 |
+
|
25 |
+
|
26 |
+
def get_chunk(lst, n, k):
|
27 |
+
chunks = split_list(lst, n)
|
28 |
+
return chunks[k]
|
29 |
+
|
30 |
+
|
31 |
+
# Custom dataset class
|
32 |
+
class CustomDataset(Dataset):
|
33 |
+
def __init__(self, questions, image_folder, tokenizer, image_processor, model_config, voco_num):
|
34 |
+
self.questions = questions
|
35 |
+
self.image_folder = image_folder
|
36 |
+
self.tokenizer = tokenizer
|
37 |
+
self.image_processor = image_processor
|
38 |
+
self.model_config = model_config
|
39 |
+
self.voco_num = voco_num
|
40 |
+
print("voco_num is ", voco_num)
|
41 |
+
|
42 |
+
def __getitem__(self, index):
|
43 |
+
line = self.questions[index]
|
44 |
+
image_file = line["image"]
|
45 |
+
qs = line["text"]
|
46 |
+
if self.model_config.mm_use_im_start_end:
|
47 |
+
qs = DEFAULT_IM_START_TOKEN + DEFAULT_IMAGE_TOKEN + DEFAULT_IM_END_TOKEN + '\n' + qs
|
48 |
+
else:
|
49 |
+
qs = DEFAULT_IMAGE_TOKEN + '\n' + qs
|
50 |
+
|
51 |
+
# conv = conv_templates[args.conv_mode].copy()
|
52 |
+
conv = conversation_lib.voco_default_conversation.copy()
|
53 |
+
conv.append_message(conv.roles[0], qs)
|
54 |
+
conv.append_message(conv.roles[1], None)
|
55 |
+
prompt = conv.get_prompt()
|
56 |
+
|
57 |
+
# print(prompt)
|
58 |
+
maybe_voco_str = "".join(
|
59 |
+
["<voco>" for _ in range(self.voco_num)]
|
60 |
+
)
|
61 |
+
prompt = f"<image>\n{maybe_voco_str}\n" + prompt.replace("\n", '').replace("<image>", '')
|
62 |
+
|
63 |
+
image = Image.open(os.path.join(self.image_folder, image_file)).convert('RGB')
|
64 |
+
image_tensor = process_images([image], self.image_processor, self.model_config)[0]
|
65 |
+
|
66 |
+
input_ids = tokenizer_image_token(prompt, self.tokenizer, IMAGE_TOKEN_INDEX, return_tensors='pt')
|
67 |
+
|
68 |
+
return input_ids, image_tensor, image.size
|
69 |
+
|
70 |
+
def __len__(self):
|
71 |
+
return len(self.questions)
|
72 |
+
|
73 |
+
|
74 |
+
def collate_fn(batch):
|
75 |
+
input_ids, image_tensors, image_sizes = zip(*batch)
|
76 |
+
input_ids = torch.stack(input_ids, dim=0)
|
77 |
+
image_tensors = torch.stack(image_tensors, dim=0)
|
78 |
+
return input_ids, image_tensors, image_sizes
|
79 |
+
|
80 |
+
|
81 |
+
# DataLoader
|
82 |
+
def create_data_loader(questions, image_folder, tokenizer, image_processor, model_config, voco_num, batch_size=1, num_workers=4):
|
83 |
+
assert batch_size == 1, "batch_size must be 1"
|
84 |
+
dataset = CustomDataset(questions, image_folder, tokenizer, image_processor, model_config, voco_num)
|
85 |
+
data_loader = DataLoader(dataset, batch_size=batch_size, num_workers=num_workers, shuffle=False, collate_fn=collate_fn)
|
86 |
+
return data_loader
|
87 |
+
|
88 |
+
|
89 |
+
def eval_model(args):
|
90 |
+
# Model
|
91 |
+
disable_torch_init()
|
92 |
+
model_path = os.path.expanduser(args.model_path)
|
93 |
+
model_name = get_model_name_from_path(model_path)
|
94 |
+
tokenizer, model, image_processor, context_len = load_pretrained_model(model_path, args.model_base, model_name, llava_model="initial")
|
95 |
+
|
96 |
+
print("*************", len(tokenizer))
|
97 |
+
|
98 |
+
questions = [json.loads(q) for q in open(os.path.expanduser(args.question_file), "r")]
|
99 |
+
questions = get_chunk(questions, args.num_chunks, args.chunk_idx)
|
100 |
+
answers_file = os.path.expanduser(args.answers_file)
|
101 |
+
os.makedirs(os.path.dirname(answers_file), exist_ok=True)
|
102 |
+
ans_file = open(answers_file, "w")
|
103 |
+
voco_num = args.voco_num
|
104 |
+
|
105 |
+
if 'plain' in model_name and 'finetune' not in model_name.lower() and 'mmtag' not in args.conv_mode:
|
106 |
+
args.conv_mode = args.conv_mode + '_mmtag'
|
107 |
+
print(f'It seems that this is a plain model, but it is not using a mmtag prompt, auto switching to {args.conv_mode}.')
|
108 |
+
|
109 |
+
data_loader = create_data_loader(questions, args.image_folder, tokenizer, image_processor, model.config, voco_num)
|
110 |
+
|
111 |
+
for (input_ids, image_tensor, image_sizes), line in tqdm(zip(data_loader, questions), total=len(questions)):
|
112 |
+
idx = line["question_id"]
|
113 |
+
cur_prompt = line["text"]
|
114 |
+
|
115 |
+
input_ids = input_ids.to(device='cuda', non_blocking=True)
|
116 |
+
|
117 |
+
with torch.inference_mode():
|
118 |
+
output_ids = model.generate(
|
119 |
+
input_ids,
|
120 |
+
images=image_tensor.to(dtype=torch.float16, device='cuda', non_blocking=True),
|
121 |
+
image_sizes=image_sizes,
|
122 |
+
do_sample=True if args.temperature > 0 else False,
|
123 |
+
temperature=args.temperature,
|
124 |
+
top_p=args.top_p,
|
125 |
+
num_beams=args.num_beams,
|
126 |
+
max_new_tokens=args.max_new_tokens,
|
127 |
+
use_cache=True)
|
128 |
+
|
129 |
+
outputs = tokenizer.batch_decode(output_ids, skip_special_tokens=True)[0].strip()
|
130 |
+
|
131 |
+
ans_id = shortuuid.uuid()
|
132 |
+
ans_file.write(json.dumps({"question_id": idx,
|
133 |
+
"prompt": cur_prompt,
|
134 |
+
"text": outputs,
|
135 |
+
"answer_id": ans_id,
|
136 |
+
"model_id": model_name,
|
137 |
+
"metadata": {}}) + "\n")
|
138 |
+
ans_file.flush()
|
139 |
+
ans_file.close()
|
140 |
+
|
141 |
+
if __name__ == "__main__":
|
142 |
+
parser = argparse.ArgumentParser()
|
143 |
+
parser.add_argument("--model-path", type=str, default="facebook/opt-350m")
|
144 |
+
parser.add_argument("--model-base", type=str, default=None)
|
145 |
+
parser.add_argument("--image-folder", type=str, default="")
|
146 |
+
parser.add_argument("--question-file", type=str, default="tables/question.jsonl")
|
147 |
+
parser.add_argument("--answers-file", type=str, default="answer.jsonl")
|
148 |
+
parser.add_argument("--conv-mode", type=str, default="llava_v1")
|
149 |
+
parser.add_argument("--num-chunks", type=int, default=1)
|
150 |
+
parser.add_argument("--chunk-idx", type=int, default=0)
|
151 |
+
parser.add_argument("--temperature", type=float, default=0.2)
|
152 |
+
parser.add_argument("--top_p", type=float, default=None)
|
153 |
+
parser.add_argument("--num_beams", type=int, default=1)
|
154 |
+
parser.add_argument("--max_new_tokens", type=int, default=128)
|
155 |
+
parser.add_argument("--voco_num", type=int, default=None)
|
156 |
+
args = parser.parse_args()
|
157 |
+
|
158 |
+
eval_model(args)
|
llava/eval/model_vqa_mmbench.py
ADDED
@@ -0,0 +1,170 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import argparse
|
2 |
+
import torch
|
3 |
+
import os
|
4 |
+
import json
|
5 |
+
import pandas as pd
|
6 |
+
from tqdm import tqdm
|
7 |
+
import shortuuid
|
8 |
+
|
9 |
+
from llava.constants import IMAGE_TOKEN_INDEX, DEFAULT_IMAGE_TOKEN, DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN
|
10 |
+
from llava.conversation import conv_templates, SeparatorStyle
|
11 |
+
from llava.model.builder import load_pretrained_model
|
12 |
+
from llava.utils import disable_torch_init
|
13 |
+
from llava.mm_utils import tokenizer_image_token, process_images, load_image_from_base64, get_model_name_from_path
|
14 |
+
|
15 |
+
from llava import conversation as conversation_lib
|
16 |
+
from PIL import Image
|
17 |
+
import math
|
18 |
+
|
19 |
+
|
20 |
+
all_options = ['A', 'B', 'C', 'D']
|
21 |
+
|
22 |
+
|
23 |
+
def split_list(lst, n):
|
24 |
+
"""Split a list into n (roughly) equal-sized chunks"""
|
25 |
+
chunk_size = math.ceil(len(lst) / n) # integer division
|
26 |
+
return [lst[i:i+chunk_size] for i in range(0, len(lst), chunk_size)]
|
27 |
+
|
28 |
+
|
29 |
+
def get_chunk(lst, n, k):
|
30 |
+
chunks = split_list(lst, n)
|
31 |
+
return chunks[k]
|
32 |
+
|
33 |
+
|
34 |
+
def is_none(value):
|
35 |
+
if value is None:
|
36 |
+
return True
|
37 |
+
if type(value) is float and math.isnan(value):
|
38 |
+
return True
|
39 |
+
if type(value) is str and value.lower() == 'nan':
|
40 |
+
return True
|
41 |
+
if type(value) is str and value.lower() == 'none':
|
42 |
+
return True
|
43 |
+
return False
|
44 |
+
|
45 |
+
def get_options(row, options):
|
46 |
+
parsed_options = []
|
47 |
+
for option in options:
|
48 |
+
option_value = row[option]
|
49 |
+
if is_none(option_value):
|
50 |
+
break
|
51 |
+
parsed_options.append(option_value)
|
52 |
+
return parsed_options
|
53 |
+
|
54 |
+
|
55 |
+
def eval_model(args):
|
56 |
+
# Model
|
57 |
+
disable_torch_init()
|
58 |
+
model_path = os.path.expanduser(args.model_path)
|
59 |
+
model_name = get_model_name_from_path(model_path)
|
60 |
+
tokenizer, model, image_processor, context_len = load_pretrained_model(model_path, args.model_base, model_name, llava_model="initial")
|
61 |
+
|
62 |
+
print("*************", len(tokenizer))
|
63 |
+
|
64 |
+
questions = pd.read_table(os.path.expanduser(args.question_file))
|
65 |
+
questions = get_chunk(questions, args.num_chunks, args.chunk_idx)
|
66 |
+
answers_file = os.path.expanduser(args.answers_file)
|
67 |
+
os.makedirs(os.path.dirname(answers_file), exist_ok=True)
|
68 |
+
ans_file = open(answers_file, "w")
|
69 |
+
|
70 |
+
if 'plain' in model_name and 'finetune' not in model_name.lower() and 'mmtag' not in args.conv_mode:
|
71 |
+
args.conv_mode = args.conv_mode + '_mmtag'
|
72 |
+
print(f'It seems that this is a plain model, but it is not using a mmtag prompt, auto switching to {args.conv_mode}.')
|
73 |
+
|
74 |
+
for index, row in tqdm(questions.iterrows(), total=len(questions)):
|
75 |
+
options = get_options(row, all_options)
|
76 |
+
cur_option_char = all_options[:len(options)]
|
77 |
+
|
78 |
+
if args.all_rounds:
|
79 |
+
num_rounds = len(options)
|
80 |
+
else:
|
81 |
+
num_rounds = 1
|
82 |
+
|
83 |
+
for round_idx in range(num_rounds):
|
84 |
+
idx = row['index']
|
85 |
+
question = row['question']
|
86 |
+
hint = row['hint']
|
87 |
+
image = load_image_from_base64(row['image'])
|
88 |
+
if not is_none(hint):
|
89 |
+
question = hint + '\n' + question
|
90 |
+
for option_char, option in zip(all_options[:len(options)], options):
|
91 |
+
question = question + '\n' + option_char + '. ' + option
|
92 |
+
qs = cur_prompt = question
|
93 |
+
if model.config.mm_use_im_start_end:
|
94 |
+
qs = DEFAULT_IM_START_TOKEN + DEFAULT_IMAGE_TOKEN + DEFAULT_IM_END_TOKEN + '\n' + qs
|
95 |
+
else:
|
96 |
+
qs = DEFAULT_IMAGE_TOKEN + '\n' + qs
|
97 |
+
|
98 |
+
if args.single_pred_prompt:
|
99 |
+
if args.lang == 'cn':
|
100 |
+
qs = qs + '\n' + "请直接回答选项字母。"
|
101 |
+
else:
|
102 |
+
qs = qs + '\n' + "Answer with the option's letter from the given choices directly."
|
103 |
+
|
104 |
+
# conv = conv_templates[args.conv_mode].copy()
|
105 |
+
conv = conversation_lib.voco_default_conversation.copy()
|
106 |
+
conv.append_message(conv.roles[0], qs)
|
107 |
+
conv.append_message(conv.roles[1], None)
|
108 |
+
prompt = conv.get_prompt()
|
109 |
+
|
110 |
+
maybe_voco_str = "".join(
|
111 |
+
["<voco>" for _ in range(args.voco_num)]
|
112 |
+
)
|
113 |
+
prompt = f"<image>\n{maybe_voco_str}\n" + prompt.replace("\n", '').replace("<image>", '')
|
114 |
+
|
115 |
+
input_ids = tokenizer_image_token(prompt, tokenizer, IMAGE_TOKEN_INDEX, return_tensors='pt').unsqueeze(0).cuda()
|
116 |
+
|
117 |
+
image_tensor = process_images([image], image_processor, model.config)[0]
|
118 |
+
|
119 |
+
with torch.inference_mode():
|
120 |
+
output_ids = model.generate(
|
121 |
+
input_ids,
|
122 |
+
images=image_tensor.unsqueeze(0).half().cuda(),
|
123 |
+
image_sizes=[image.size],
|
124 |
+
do_sample=True if args.temperature > 0 else False,
|
125 |
+
temperature=args.temperature,
|
126 |
+
top_p=args.top_p,
|
127 |
+
num_beams=args.num_beams,
|
128 |
+
# no_repeat_ngram_size=3,
|
129 |
+
max_new_tokens=1024,
|
130 |
+
use_cache=True)
|
131 |
+
|
132 |
+
outputs = tokenizer.batch_decode(output_ids, skip_special_tokens=True)[0].strip()
|
133 |
+
|
134 |
+
ans_id = shortuuid.uuid()
|
135 |
+
ans_file.write(json.dumps({"question_id": idx,
|
136 |
+
"round_id": round_idx,
|
137 |
+
"prompt": cur_prompt,
|
138 |
+
"text": outputs,
|
139 |
+
"options": options,
|
140 |
+
"option_char": cur_option_char,
|
141 |
+
"answer_id": ans_id,
|
142 |
+
"model_id": model_name,
|
143 |
+
"metadata": {}}) + "\n")
|
144 |
+
ans_file.flush()
|
145 |
+
|
146 |
+
# rotate options
|
147 |
+
options = options[1:] + options[:1]
|
148 |
+
cur_option_char = cur_option_char[1:] + cur_option_char[:1]
|
149 |
+
ans_file.close()
|
150 |
+
|
151 |
+
if __name__ == "__main__":
|
152 |
+
parser = argparse.ArgumentParser()
|
153 |
+
parser.add_argument("--model-path", type=str, default="facebook/opt-350m")
|
154 |
+
parser.add_argument("--model-base", type=str, default=None)
|
155 |
+
parser.add_argument("--image-folder", type=str, default="")
|
156 |
+
parser.add_argument("--question-file", type=str, default="tables/question.jsonl")
|
157 |
+
parser.add_argument("--answers-file", type=str, default="answer.jsonl")
|
158 |
+
parser.add_argument("--conv-mode", type=str, default="llava_v1")
|
159 |
+
parser.add_argument("--num-chunks", type=int, default=1)
|
160 |
+
parser.add_argument("--chunk-idx", type=int, default=0)
|
161 |
+
parser.add_argument("--temperature", type=float, default=0.2)
|
162 |
+
parser.add_argument("--top_p", type=float, default=None)
|
163 |
+
parser.add_argument("--num_beams", type=int, default=1)
|
164 |
+
parser.add_argument("--all-rounds", action="store_true")
|
165 |
+
parser.add_argument("--single-pred-prompt", action="store_true")
|
166 |
+
parser.add_argument("--lang", type=str, default="en")
|
167 |
+
parser.add_argument("--voco_num", type=int, default=None)
|
168 |
+
args = parser.parse_args()
|
169 |
+
|
170 |
+
eval_model(args)
|
llava/eval/model_vqa_science.py
ADDED
@@ -0,0 +1,122 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import argparse
|
2 |
+
import torch
|
3 |
+
import os
|
4 |
+
import json
|
5 |
+
from tqdm import tqdm
|
6 |
+
import shortuuid
|
7 |
+
|
8 |
+
from llava.constants import IMAGE_TOKEN_INDEX, DEFAULT_IMAGE_TOKEN, DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN
|
9 |
+
from llava.conversation import conv_templates, SeparatorStyle
|
10 |
+
from llava.model.builder import load_pretrained_model
|
11 |
+
from llava import conversation as conversation_lib
|
12 |
+
from llava.utils import disable_torch_init
|
13 |
+
from llava.mm_utils import tokenizer_image_token, process_images, get_model_name_from_path
|
14 |
+
|
15 |
+
from PIL import Image
|
16 |
+
import math
|
17 |
+
|
18 |
+
|
19 |
+
def split_list(lst, n):
|
20 |
+
"""Split a list into n (roughly) equal-sized chunks"""
|
21 |
+
chunk_size = math.ceil(len(lst) / n) # integer division
|
22 |
+
return [lst[i:i+chunk_size] for i in range(0, len(lst), chunk_size)]
|
23 |
+
|
24 |
+
|
25 |
+
def get_chunk(lst, n, k):
|
26 |
+
chunks = split_list(lst, n)
|
27 |
+
return chunks[k]
|
28 |
+
|
29 |
+
|
30 |
+
def eval_model(args):
|
31 |
+
# Model
|
32 |
+
disable_torch_init()
|
33 |
+
model_path = os.path.expanduser(args.model_path)
|
34 |
+
model_name = get_model_name_from_path(model_path)
|
35 |
+
tokenizer, model, image_processor, context_len = load_pretrained_model(model_path, args.model_base, model_name, llava_model="initial")
|
36 |
+
|
37 |
+
print("*************", len(tokenizer))
|
38 |
+
|
39 |
+
questions = json.load(open(os.path.expanduser(args.question_file), "r"))
|
40 |
+
questions = get_chunk(questions, args.num_chunks, args.chunk_idx)
|
41 |
+
answers_file = os.path.expanduser(args.answers_file)
|
42 |
+
os.makedirs(os.path.dirname(answers_file), exist_ok=True)
|
43 |
+
ans_file = open(answers_file, "w")
|
44 |
+
for i, line in enumerate(tqdm(questions)):
|
45 |
+
idx = line["id"]
|
46 |
+
question = line['conversations'][0]
|
47 |
+
qs = question['value'].replace('<image>', '').strip()
|
48 |
+
cur_prompt = qs
|
49 |
+
|
50 |
+
if 'image' in line:
|
51 |
+
image_file = line["image"]
|
52 |
+
image = Image.open(os.path.join(args.image_folder, image_file))
|
53 |
+
image_tensor = process_images([image], image_processor, model.config)[0]
|
54 |
+
images = image_tensor.unsqueeze(0).half().cuda()
|
55 |
+
image_sizes = [image.size]
|
56 |
+
if getattr(model.config, 'mm_use_im_start_end', False):
|
57 |
+
qs = DEFAULT_IM_START_TOKEN + DEFAULT_IMAGE_TOKEN + DEFAULT_IM_END_TOKEN + '\n' + qs
|
58 |
+
else:
|
59 |
+
qs = DEFAULT_IMAGE_TOKEN + '\n' + qs
|
60 |
+
cur_prompt = '<image>' + '\n' + cur_prompt
|
61 |
+
else:
|
62 |
+
continue
|
63 |
+
images = None
|
64 |
+
image_sizes = None
|
65 |
+
|
66 |
+
if args.single_pred_prompt:
|
67 |
+
qs = qs + '\n' + "Answer with the option's letter from the given choices directly."
|
68 |
+
cur_prompt = cur_prompt + '\n' + "Answer with the option's letter from the given choices directly."
|
69 |
+
|
70 |
+
# conv = conv_templates[args.conv_mode].copy()
|
71 |
+
conv = conversation_lib.voco_default_conversation.copy()
|
72 |
+
conv.append_message(conv.roles[0], qs)
|
73 |
+
conv.append_message(conv.roles[1], None)
|
74 |
+
prompt = conv.get_prompt()
|
75 |
+
|
76 |
+
maybe_voco_str = "".join(
|
77 |
+
["<voco>" for _ in range(args.voco_num)]
|
78 |
+
)
|
79 |
+
prompt = f"<image>\n{maybe_voco_str}\n" + prompt.replace("\n", '').replace("<image>", '')
|
80 |
+
|
81 |
+
input_ids = tokenizer_image_token(prompt, tokenizer, IMAGE_TOKEN_INDEX, return_tensors='pt').unsqueeze(0).cuda()
|
82 |
+
|
83 |
+
with torch.inference_mode():
|
84 |
+
output_ids = model.generate(
|
85 |
+
input_ids,
|
86 |
+
images=images,
|
87 |
+
image_sizes=image_sizes,
|
88 |
+
do_sample=True if args.temperature > 0 else False,
|
89 |
+
temperature=args.temperature,
|
90 |
+
max_new_tokens=1024,
|
91 |
+
use_cache=True,
|
92 |
+
)
|
93 |
+
|
94 |
+
outputs = tokenizer.batch_decode(output_ids, skip_special_tokens=True)[0].strip()
|
95 |
+
|
96 |
+
ans_id = shortuuid.uuid()
|
97 |
+
ans_file.write(json.dumps({"question_id": idx,
|
98 |
+
"prompt": cur_prompt,
|
99 |
+
"text": outputs,
|
100 |
+
"answer_id": ans_id,
|
101 |
+
"model_id": model_name,
|
102 |
+
"metadata": {}}) + "\n")
|
103 |
+
ans_file.flush()
|
104 |
+
ans_file.close()
|
105 |
+
|
106 |
+
if __name__ == "__main__":
|
107 |
+
parser = argparse.ArgumentParser()
|
108 |
+
parser.add_argument("--model-path", type=str, default="facebook/opt-350m")
|
109 |
+
parser.add_argument("--model-base", type=str, default=None)
|
110 |
+
parser.add_argument("--image-folder", type=str, default="")
|
111 |
+
parser.add_argument("--question-file", type=str, default="tables/question.json")
|
112 |
+
parser.add_argument("--answers-file", type=str, default="answer.jsonl")
|
113 |
+
parser.add_argument("--conv-mode", type=str, default="llava_v0")
|
114 |
+
parser.add_argument("--num-chunks", type=int, default=1)
|
115 |
+
parser.add_argument("--chunk-idx", type=int, default=0)
|
116 |
+
parser.add_argument("--temperature", type=float, default=0.2)
|
117 |
+
parser.add_argument("--answer-prompter", action="store_true")
|
118 |
+
parser.add_argument("--single-pred-prompt", action="store_true")
|
119 |
+
parser.add_argument("--voco_num", type=int, default=None)
|
120 |
+
args = parser.parse_args()
|
121 |
+
|
122 |
+
eval_model(args)
|
llava/train/__pycache__/llava_trainer.cpython-310.pyc
ADDED
Binary file (11.4 kB). View file
|
|
llava/train/__pycache__/train_compress.cpython-310.pyc
ADDED
Binary file (28.1 kB). View file
|
|
llava/train/llama_flash_attn_monkey_patch.py
ADDED
@@ -0,0 +1,115 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from typing import Optional, Tuple
|
2 |
+
import warnings
|
3 |
+
|
4 |
+
import torch
|
5 |
+
|
6 |
+
import transformers
|
7 |
+
from transformers.models.llama.modeling_llama import apply_rotary_pos_emb, repeat_kv
|
8 |
+
|
9 |
+
try:
|
10 |
+
from flash_attn.flash_attn_interface import flash_attn_unpadded_qkvpacked_func
|
11 |
+
except ImportError:
|
12 |
+
from flash_attn.flash_attn_interface import flash_attn_varlen_qkvpacked_func as flash_attn_unpadded_qkvpacked_func
|
13 |
+
from flash_attn.bert_padding import unpad_input, pad_input
|
14 |
+
|
15 |
+
|
16 |
+
def forward(
|
17 |
+
self,
|
18 |
+
hidden_states: torch.Tensor,
|
19 |
+
attention_mask: Optional[torch.Tensor] = None,
|
20 |
+
position_ids: Optional[torch.Tensor] = None,
|
21 |
+
past_key_value: Optional[Tuple[torch.Tensor]] = None,
|
22 |
+
output_attentions: bool = False,
|
23 |
+
use_cache: bool = False,
|
24 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
25 |
+
if output_attentions:
|
26 |
+
warnings.warn(
|
27 |
+
"Output attentions is not supported for patched `LlamaAttention`, returning `None` instead."
|
28 |
+
)
|
29 |
+
|
30 |
+
bsz, q_len, _ = hidden_states.size()
|
31 |
+
|
32 |
+
query_states = (
|
33 |
+
self.q_proj(hidden_states)
|
34 |
+
.view(bsz, q_len, self.num_heads, self.head_dim)
|
35 |
+
.transpose(1, 2)
|
36 |
+
)
|
37 |
+
key_states = (
|
38 |
+
self.k_proj(hidden_states)
|
39 |
+
.view(bsz, q_len, self.num_key_value_heads, self.head_dim)
|
40 |
+
.transpose(1, 2)
|
41 |
+
)
|
42 |
+
value_states = (
|
43 |
+
self.v_proj(hidden_states)
|
44 |
+
.view(bsz, q_len, self.num_key_value_heads, self.head_dim)
|
45 |
+
.transpose(1, 2)
|
46 |
+
) # shape: (b, num_heads, s, head_dim)
|
47 |
+
|
48 |
+
kv_seq_len = key_states.shape[-2]
|
49 |
+
if past_key_value is not None:
|
50 |
+
kv_seq_len += past_key_value[0].shape[-2]
|
51 |
+
|
52 |
+
cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
|
53 |
+
query_states, key_states = apply_rotary_pos_emb(
|
54 |
+
query_states, key_states, cos, sin, position_ids
|
55 |
+
)
|
56 |
+
|
57 |
+
if past_key_value is not None:
|
58 |
+
# reuse k, v
|
59 |
+
key_states = torch.cat([past_key_value[0], key_states], dim=2)
|
60 |
+
value_states = torch.cat([past_key_value[1], value_states], dim=2)
|
61 |
+
|
62 |
+
past_key_value = (key_states, value_states) if use_cache else None
|
63 |
+
|
64 |
+
# repeat k/v heads if n_kv_heads < n_heads
|
65 |
+
key_states = repeat_kv(key_states, self.num_key_value_groups)
|
66 |
+
value_states = repeat_kv(value_states, self.num_key_value_groups)
|
67 |
+
|
68 |
+
# Transform the data into the format required by flash attention
|
69 |
+
qkv = torch.stack([query_states, key_states, value_states], dim=2)
|
70 |
+
qkv = qkv.transpose(1, 3) # shape: [b, s, 3, num_heads, head_dim]
|
71 |
+
key_padding_mask = attention_mask
|
72 |
+
|
73 |
+
if key_padding_mask is None:
|
74 |
+
qkv = qkv.reshape(-1, 3, self.num_heads, self.head_dim)
|
75 |
+
cu_q_lens = torch.arange(
|
76 |
+
0, (bsz + 1) * q_len, step=q_len, dtype=torch.int32, device=qkv.device
|
77 |
+
)
|
78 |
+
max_s = q_len
|
79 |
+
output = flash_attn_unpadded_qkvpacked_func(
|
80 |
+
qkv, cu_q_lens, max_s, 0.0, softmax_scale=None, causal=True
|
81 |
+
)
|
82 |
+
output = output.view(bsz, q_len, -1)
|
83 |
+
else:
|
84 |
+
qkv = qkv.reshape(bsz, q_len, -1)
|
85 |
+
qkv, indices, cu_q_lens, max_s = unpad_input(qkv, key_padding_mask)
|
86 |
+
qkv = qkv.view(-1, 3, self.num_heads, self.head_dim)
|
87 |
+
output_unpad = flash_attn_unpadded_qkvpacked_func(
|
88 |
+
qkv, cu_q_lens, max_s, 0.0, softmax_scale=None, causal=True
|
89 |
+
)
|
90 |
+
output_unpad = output_unpad.reshape(-1, self.num_heads * self.head_dim)
|
91 |
+
output = pad_input(output_unpad, indices, bsz, q_len)
|
92 |
+
|
93 |
+
return self.o_proj(output), None, past_key_value
|
94 |
+
|
95 |
+
|
96 |
+
# Disable the transformation of the attention mask in LlamaModel as the flash attention
|
97 |
+
# requires the attention mask to be the same as the key_padding_mask
|
98 |
+
def _prepare_decoder_attention_mask(
|
99 |
+
self, attention_mask, input_shape, inputs_embeds, past_key_values_length
|
100 |
+
):
|
101 |
+
# [bsz, seq_len]
|
102 |
+
return attention_mask
|
103 |
+
|
104 |
+
|
105 |
+
def replace_llama_attn_with_flash_attn():
|
106 |
+
cuda_major, cuda_minor = torch.cuda.get_device_capability()
|
107 |
+
if cuda_major < 8:
|
108 |
+
warnings.warn(
|
109 |
+
"Flash attention is only supported on A100 or H100 GPU during training due to head dim > 64 backward."
|
110 |
+
"ref: https://github.com/HazyResearch/flash-attention/issues/190#issuecomment-1523359593"
|
111 |
+
)
|
112 |
+
transformers.models.llama.modeling_llama.LlamaModel._prepare_decoder_attention_mask = (
|
113 |
+
_prepare_decoder_attention_mask
|
114 |
+
)
|
115 |
+
transformers.models.llama.modeling_llama.LlamaAttention.forward = forward
|
llava/train/llama_xformers_attn_monkey_patch.py
ADDED
@@ -0,0 +1,129 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
Directly copied the code from https://raw.githubusercontent.com/oobabooga/text-generation-webui/main/modules/llama_attn_hijack.py and made some adjustments
|
3 |
+
"""
|
4 |
+
|
5 |
+
import logging
|
6 |
+
import math
|
7 |
+
from typing import Optional, Tuple
|
8 |
+
|
9 |
+
import torch
|
10 |
+
import transformers.models.llama.modeling_llama
|
11 |
+
from torch import nn
|
12 |
+
|
13 |
+
try:
|
14 |
+
import xformers.ops
|
15 |
+
except ImportError:
|
16 |
+
logging.error("xformers not found! Please install it before trying to use it.")
|
17 |
+
|
18 |
+
|
19 |
+
def replace_llama_attn_with_xformers_attn():
|
20 |
+
transformers.models.llama.modeling_llama.LlamaAttention.forward = xformers_forward
|
21 |
+
|
22 |
+
|
23 |
+
def xformers_forward(
|
24 |
+
self,
|
25 |
+
hidden_states: torch.Tensor,
|
26 |
+
attention_mask: Optional[torch.Tensor] = None,
|
27 |
+
position_ids: Optional[torch.LongTensor] = None,
|
28 |
+
past_key_value: Optional[Tuple[torch.Tensor]] = None,
|
29 |
+
output_attentions: bool = False,
|
30 |
+
use_cache: bool = False,
|
31 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
32 |
+
# pylint: disable=duplicate-code
|
33 |
+
bsz, q_len, _ = hidden_states.size()
|
34 |
+
|
35 |
+
query_states = (
|
36 |
+
self.q_proj(hidden_states)
|
37 |
+
.view(bsz, q_len, self.num_heads, self.head_dim)
|
38 |
+
.transpose(1, 2)
|
39 |
+
)
|
40 |
+
key_states = (
|
41 |
+
self.k_proj(hidden_states)
|
42 |
+
.view(bsz, q_len, self.num_heads, self.head_dim)
|
43 |
+
.transpose(1, 2)
|
44 |
+
)
|
45 |
+
value_states = (
|
46 |
+
self.v_proj(hidden_states)
|
47 |
+
.view(bsz, q_len, self.num_heads, self.head_dim)
|
48 |
+
.transpose(1, 2)
|
49 |
+
)
|
50 |
+
|
51 |
+
kv_seq_len = key_states.shape[-2]
|
52 |
+
if past_key_value is not None:
|
53 |
+
kv_seq_len += past_key_value[0].shape[-2]
|
54 |
+
cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
|
55 |
+
(
|
56 |
+
query_states,
|
57 |
+
key_states,
|
58 |
+
) = transformers.models.llama.modeling_llama.apply_rotary_pos_emb(
|
59 |
+
query_states, key_states, cos, sin, position_ids
|
60 |
+
)
|
61 |
+
# [bsz, nh, t, hd]
|
62 |
+
|
63 |
+
if past_key_value is not None:
|
64 |
+
# reuse k, v, self_attention
|
65 |
+
key_states = torch.cat([past_key_value[0], key_states], dim=2)
|
66 |
+
value_states = torch.cat([past_key_value[1], value_states], dim=2)
|
67 |
+
|
68 |
+
past_key_value = (key_states, value_states) if use_cache else None
|
69 |
+
|
70 |
+
# We only apply xformers optimizations if we don't need to output the whole attention matrix
|
71 |
+
if not output_attentions:
|
72 |
+
query_states = query_states.transpose(1, 2)
|
73 |
+
key_states = key_states.transpose(1, 2)
|
74 |
+
value_states = value_states.transpose(1, 2)
|
75 |
+
|
76 |
+
# This is a nasty hack. We know attention_mask in transformers is either LowerTriangular or all Zeros.
|
77 |
+
# We therefore check if one element in the upper triangular portion is zero. If it is, then the mask is all zeros.
|
78 |
+
if attention_mask is None or attention_mask[0, 0, 0, 1] == 0:
|
79 |
+
# input and output should be of form (bsz, q_len, num_heads, head_dim)
|
80 |
+
attn_output = xformers.ops.memory_efficient_attention(
|
81 |
+
query_states, key_states, value_states, attn_bias=None
|
82 |
+
)
|
83 |
+
else:
|
84 |
+
# input and output should be of form (bsz, q_len, num_heads, head_dim)
|
85 |
+
attn_output = xformers.ops.memory_efficient_attention(
|
86 |
+
query_states,
|
87 |
+
key_states,
|
88 |
+
value_states,
|
89 |
+
attn_bias=xformers.ops.LowerTriangularMask(),
|
90 |
+
)
|
91 |
+
attn_weights = None
|
92 |
+
else:
|
93 |
+
attn_weights = torch.matmul(
|
94 |
+
query_states, key_states.transpose(2, 3)
|
95 |
+
) / math.sqrt(self.head_dim)
|
96 |
+
|
97 |
+
if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
|
98 |
+
raise ValueError(
|
99 |
+
f"Attention weights should be of size {(bsz * self.num_heads, q_len, kv_seq_len)}, but is"
|
100 |
+
f" {attn_weights.size()}"
|
101 |
+
)
|
102 |
+
|
103 |
+
if attention_mask is not None:
|
104 |
+
if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
|
105 |
+
raise ValueError(
|
106 |
+
f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
|
107 |
+
)
|
108 |
+
attn_weights = attn_weights + attention_mask
|
109 |
+
attn_weights = torch.max(
|
110 |
+
attn_weights, torch.tensor(torch.finfo(attn_weights.dtype).min)
|
111 |
+
)
|
112 |
+
|
113 |
+
# upcast attention to fp32
|
114 |
+
attn_weights = nn.functional.softmax(
|
115 |
+
attn_weights, dim=-1, dtype=torch.float32
|
116 |
+
).to(query_states.dtype)
|
117 |
+
attn_output = torch.matmul(attn_weights, value_states)
|
118 |
+
|
119 |
+
if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
|
120 |
+
raise ValueError(
|
121 |
+
f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
|
122 |
+
f" {attn_output.size()}"
|
123 |
+
)
|
124 |
+
|
125 |
+
attn_output = attn_output.transpose(1, 2)
|
126 |
+
|
127 |
+
attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
|
128 |
+
attn_output = self.o_proj(attn_output)
|
129 |
+
return attn_output, attn_weights, past_key_value
|
llava/train/train_compress.py
ADDED
@@ -0,0 +1,1014 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Adopted from https://github.com/haotian-liu/LLaVA.
|
2 |
+
# Adopted from https://github.com/lm-sys/FastChat. Below is the original copyright:
|
3 |
+
# Adopted from tatsu-lab@stanford_alpaca. Below is the original copyright:
|
4 |
+
# Copyright 2023 Rohan Taori, Ishaan Gulrajani, Tianyi Zhang, Yann Dubois, Xuechen Li
|
5 |
+
#
|
6 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
7 |
+
# you may not use this file except in compliance with the License.
|
8 |
+
# You may obtain a copy of the License at
|
9 |
+
#
|
10 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
11 |
+
#
|
12 |
+
# Unless required by applicable law or agreed to in writing, software
|
13 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
14 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
15 |
+
# See the License for the specific language governing permissions and
|
16 |
+
# limitations under the License.
|
17 |
+
|
18 |
+
import os
|
19 |
+
import copy
|
20 |
+
from dataclasses import dataclass, field
|
21 |
+
import json
|
22 |
+
import logging
|
23 |
+
import pathlib
|
24 |
+
from typing import Dict, Optional, Sequence, List
|
25 |
+
|
26 |
+
import torch
|
27 |
+
|
28 |
+
import transformers
|
29 |
+
import tokenizers
|
30 |
+
|
31 |
+
from llava.constants import IGNORE_INDEX, IMAGE_TOKEN_INDEX, DEFAULT_IMAGE_TOKEN, DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN
|
32 |
+
from torch.utils.data import Dataset
|
33 |
+
from llava.train.llava_trainer import LLaVATrainer
|
34 |
+
|
35 |
+
from llava import conversation as conversation_lib
|
36 |
+
from llava.model import *
|
37 |
+
from llava.mm_utils import tokenizer_image_token
|
38 |
+
|
39 |
+
from PIL import Image
|
40 |
+
|
41 |
+
|
42 |
+
local_rank = None
|
43 |
+
|
44 |
+
|
45 |
+
def rank0_print(*args):
|
46 |
+
if local_rank == 0:
|
47 |
+
print(*args)
|
48 |
+
|
49 |
+
|
50 |
+
from packaging import version
|
51 |
+
IS_TOKENIZER_GREATER_THAN_0_14 = version.parse(tokenizers.__version__) >= version.parse('0.14')
|
52 |
+
|
53 |
+
|
54 |
+
@dataclass
|
55 |
+
class ModelArguments:
|
56 |
+
model_name_or_path: Optional[str] = field(default="facebook/opt-125m")
|
57 |
+
version: Optional[str] = field(default="v0")
|
58 |
+
freeze_backbone: bool = field(default=False)
|
59 |
+
tune_mm_mlp_adapter: bool = field(default=False)
|
60 |
+
vision_tower: Optional[str] = field(default=None)
|
61 |
+
mm_vision_select_layer: Optional[int] = field(default=-1) # default to the last layer
|
62 |
+
pretrain_mm_mlp_adapter: Optional[str] = field(default=None)
|
63 |
+
mm_projector_type: Optional[str] = field(default='linear')
|
64 |
+
mm_use_im_start_end: bool = field(default=False)
|
65 |
+
mm_use_im_patch_token: bool = field(default=True)
|
66 |
+
mm_patch_merge_type: Optional[str] = field(default='flat')
|
67 |
+
mm_vision_select_feature: Optional[str] = field(default="patch")
|
68 |
+
|
69 |
+
|
70 |
+
@dataclass
|
71 |
+
class DataArguments:
|
72 |
+
data_path: str = field(default=None,
|
73 |
+
metadata={"help": "Path to the training data."})
|
74 |
+
lazy_preprocess: bool = False
|
75 |
+
is_multimodal: bool = False
|
76 |
+
image_folder: Optional[str] = field(default=None)
|
77 |
+
image_aspect_ratio: str = 'square'
|
78 |
+
|
79 |
+
|
80 |
+
@dataclass
|
81 |
+
class TrainingArguments(transformers.TrainingArguments):
|
82 |
+
cache_dir: Optional[str] = field(default=None)
|
83 |
+
optim: str = field(default="adamw_torch")
|
84 |
+
remove_unused_columns: bool = field(default=False)
|
85 |
+
freeze_mm_mlp_adapter: bool = field(default=False)
|
86 |
+
mpt_attn_impl: Optional[str] = field(default="triton")
|
87 |
+
model_max_length: int = field(
|
88 |
+
default=512,
|
89 |
+
metadata={
|
90 |
+
"help":
|
91 |
+
"Maximum sequence length. Sequences will be right padded (and possibly truncated)."
|
92 |
+
},
|
93 |
+
)
|
94 |
+
double_quant: bool = field(
|
95 |
+
default=True,
|
96 |
+
metadata={"help": "Compress the quantization statistics through double quantization."}
|
97 |
+
)
|
98 |
+
quant_type: str = field(
|
99 |
+
default="nf4",
|
100 |
+
metadata={"help": "Quantization data type to use. Should be one of `fp4` or `nf4`."}
|
101 |
+
)
|
102 |
+
bits: int = field(
|
103 |
+
default=16,
|
104 |
+
metadata={"help": "How many bits to use."}
|
105 |
+
)
|
106 |
+
lora_enable: bool = False
|
107 |
+
lora_r: int = 64
|
108 |
+
lora_alpha: int = 16
|
109 |
+
lora_dropout: float = 0.05
|
110 |
+
lora_weight_path: str = ""
|
111 |
+
lora_bias: str = "none"
|
112 |
+
mm_projector_lr: Optional[float] = None
|
113 |
+
group_by_modality_length: bool = field(default=False)
|
114 |
+
|
115 |
+
|
116 |
+
def maybe_zero_3(param, ignore_status=False, name=None):
|
117 |
+
from deepspeed import zero
|
118 |
+
from deepspeed.runtime.zero.partition_parameters import ZeroParamStatus
|
119 |
+
if hasattr(param, "ds_id"):
|
120 |
+
if param.ds_status == ZeroParamStatus.NOT_AVAILABLE:
|
121 |
+
if not ignore_status:
|
122 |
+
logging.warning(f"{name}: param.ds_status != ZeroParamStatus.NOT_AVAILABLE: {param.ds_status}")
|
123 |
+
with zero.GatheredParameters([param]):
|
124 |
+
param = param.data.detach().cpu().clone()
|
125 |
+
else:
|
126 |
+
param = param.detach().cpu().clone()
|
127 |
+
return param
|
128 |
+
|
129 |
+
|
130 |
+
# Borrowed from peft.utils.get_peft_model_state_dict
|
131 |
+
def get_peft_state_maybe_zero_3(named_params, bias):
|
132 |
+
if bias == "none":
|
133 |
+
to_return = {k: t for k, t in named_params if "lora_" in k}
|
134 |
+
elif bias == "all":
|
135 |
+
to_return = {k: t for k, t in named_params if "lora_" in k or "bias" in k}
|
136 |
+
elif bias == "lora_only":
|
137 |
+
to_return = {}
|
138 |
+
maybe_lora_bias = {}
|
139 |
+
lora_bias_names = set()
|
140 |
+
for k, t in named_params:
|
141 |
+
if "lora_" in k:
|
142 |
+
to_return[k] = t
|
143 |
+
bias_name = k.split("lora_")[0] + "bias"
|
144 |
+
lora_bias_names.add(bias_name)
|
145 |
+
elif "bias" in k:
|
146 |
+
maybe_lora_bias[k] = t
|
147 |
+
for k, t in maybe_lora_bias:
|
148 |
+
if bias_name in lora_bias_names:
|
149 |
+
to_return[bias_name] = t
|
150 |
+
else:
|
151 |
+
raise NotImplementedError
|
152 |
+
to_return = {k: maybe_zero_3(v, ignore_status=True) for k, v in to_return.items()}
|
153 |
+
return to_return
|
154 |
+
|
155 |
+
|
156 |
+
def get_peft_state_non_lora_maybe_zero_3(named_params, require_grad_only=True):
|
157 |
+
to_return = {k: t for k, t in named_params if "lora_" not in k}
|
158 |
+
if require_grad_only:
|
159 |
+
to_return = {k: t for k, t in to_return.items() if t.requires_grad}
|
160 |
+
to_return = {k: maybe_zero_3(v, ignore_status=True).cpu() for k, v in to_return.items()}
|
161 |
+
return to_return
|
162 |
+
|
163 |
+
|
164 |
+
def get_mm_adapter_state_maybe_zero_3(named_params, keys_to_match):
|
165 |
+
to_return = {k: t for k, t in named_params if any(key_match in k for key_match in keys_to_match)}
|
166 |
+
to_return = {k: maybe_zero_3(v, ignore_status=True).cpu() for k, v in to_return.items()}
|
167 |
+
return to_return
|
168 |
+
|
169 |
+
|
170 |
+
def find_all_linear_names(model):
|
171 |
+
cls = torch.nn.Linear
|
172 |
+
lora_module_names = set()
|
173 |
+
multimodal_keywords = ['mm_projector', 'vision_tower', 'vision_resampler']
|
174 |
+
for name, module in model.named_modules():
|
175 |
+
if any(mm_keyword in name for mm_keyword in multimodal_keywords):
|
176 |
+
continue
|
177 |
+
if isinstance(module, cls):
|
178 |
+
names = name.split('.')
|
179 |
+
lora_module_names.add(names[0] if len(names) == 1 else names[-1])
|
180 |
+
|
181 |
+
if 'lm_head' in lora_module_names: # needed for 16-bit
|
182 |
+
lora_module_names.remove('lm_head')
|
183 |
+
return list(lora_module_names)
|
184 |
+
|
185 |
+
|
186 |
+
def safe_save_model_for_hf_trainer(trainer: transformers.Trainer,
|
187 |
+
output_dir: str):
|
188 |
+
"""Collects the state dict and dump to disk."""
|
189 |
+
|
190 |
+
if getattr(trainer.args, "tune_mm_mlp_adapter", False):
|
191 |
+
# Only save Adapter
|
192 |
+
keys_to_match = ['mm_projector']
|
193 |
+
if getattr(trainer.args, "use_im_start_end", False):
|
194 |
+
keys_to_match.extend(['embed_tokens', 'embed_in'])
|
195 |
+
|
196 |
+
weight_to_save = get_mm_adapter_state_maybe_zero_3(trainer.model.named_parameters(), keys_to_match)
|
197 |
+
trainer.model.config.save_pretrained(output_dir)
|
198 |
+
|
199 |
+
current_folder = output_dir.split('/')[-1]
|
200 |
+
parent_folder = os.path.dirname(output_dir)
|
201 |
+
if trainer.args.local_rank == 0 or trainer.args.local_rank == -1:
|
202 |
+
if current_folder.startswith('checkpoint-'):
|
203 |
+
mm_projector_folder = os.path.join(parent_folder, "mm_projector")
|
204 |
+
os.makedirs(mm_projector_folder, exist_ok=True)
|
205 |
+
torch.save(weight_to_save, os.path.join(mm_projector_folder, f'{current_folder}.bin'))
|
206 |
+
else:
|
207 |
+
torch.save(weight_to_save, os.path.join(output_dir, f'mm_projector.bin'))
|
208 |
+
return
|
209 |
+
|
210 |
+
if trainer.deepspeed:
|
211 |
+
torch.cuda.synchronize()
|
212 |
+
trainer.save_model(output_dir)
|
213 |
+
return
|
214 |
+
|
215 |
+
state_dict = trainer.model.state_dict()
|
216 |
+
if trainer.args.should_save:
|
217 |
+
cpu_state_dict = {
|
218 |
+
key: value.cpu()
|
219 |
+
for key, value in state_dict.items()
|
220 |
+
}
|
221 |
+
del state_dict
|
222 |
+
trainer._save(output_dir, state_dict=cpu_state_dict) # noqa
|
223 |
+
|
224 |
+
|
225 |
+
def smart_tokenizer_and_embedding_resize(
|
226 |
+
special_tokens_dict: Dict,
|
227 |
+
tokenizer: transformers.PreTrainedTokenizer,
|
228 |
+
model: transformers.PreTrainedModel,
|
229 |
+
):
|
230 |
+
"""Resize tokenizer and embedding.
|
231 |
+
|
232 |
+
Note: This is the unoptimized version that may make your embedding size not be divisible by 64.
|
233 |
+
"""
|
234 |
+
num_new_tokens = tokenizer.add_special_tokens(special_tokens_dict)
|
235 |
+
model.resize_token_embeddings(len(tokenizer))
|
236 |
+
|
237 |
+
if num_new_tokens > 0:
|
238 |
+
input_embeddings = model.get_input_embeddings().weight.data
|
239 |
+
output_embeddings = model.get_output_embeddings().weight.data
|
240 |
+
|
241 |
+
input_embeddings_avg = input_embeddings[:-num_new_tokens].mean(
|
242 |
+
dim=0, keepdim=True)
|
243 |
+
output_embeddings_avg = output_embeddings[:-num_new_tokens].mean(
|
244 |
+
dim=0, keepdim=True)
|
245 |
+
|
246 |
+
input_embeddings[-num_new_tokens:] = input_embeddings_avg
|
247 |
+
output_embeddings[-num_new_tokens:] = output_embeddings_avg
|
248 |
+
|
249 |
+
|
250 |
+
def _tokenize_fn(strings: Sequence[str],
|
251 |
+
tokenizer: transformers.PreTrainedTokenizer) -> Dict:
|
252 |
+
"""Tokenize a list of strings."""
|
253 |
+
tokenized_list = [
|
254 |
+
tokenizer(
|
255 |
+
text,
|
256 |
+
return_tensors="pt",
|
257 |
+
padding="longest",
|
258 |
+
max_length=tokenizer.model_max_length,
|
259 |
+
truncation=True,
|
260 |
+
) for text in strings
|
261 |
+
]
|
262 |
+
input_ids = labels = [
|
263 |
+
tokenized.input_ids[0] for tokenized in tokenized_list
|
264 |
+
]
|
265 |
+
input_ids_lens = labels_lens = [
|
266 |
+
tokenized.input_ids.ne(tokenizer.pad_token_id).sum().item()
|
267 |
+
for tokenized in tokenized_list
|
268 |
+
]
|
269 |
+
return dict(
|
270 |
+
input_ids=input_ids,
|
271 |
+
labels=labels,
|
272 |
+
input_ids_lens=input_ids_lens,
|
273 |
+
labels_lens=labels_lens,
|
274 |
+
)
|
275 |
+
|
276 |
+
|
277 |
+
def _mask_targets(target, tokenized_lens, speakers):
|
278 |
+
# cur_idx = 0
|
279 |
+
cur_idx = tokenized_lens[0]
|
280 |
+
tokenized_lens = tokenized_lens[1:]
|
281 |
+
target[:cur_idx] = IGNORE_INDEX
|
282 |
+
for tokenized_len, speaker in zip(tokenized_lens, speakers):
|
283 |
+
if speaker == "human":
|
284 |
+
target[cur_idx+2:cur_idx + tokenized_len] = IGNORE_INDEX
|
285 |
+
cur_idx += tokenized_len
|
286 |
+
|
287 |
+
|
288 |
+
def _add_speaker_and_signal(header, source, get_conversation=True):
|
289 |
+
"""Add speaker and start/end signal on each round."""
|
290 |
+
BEGIN_SIGNAL = "### "
|
291 |
+
END_SIGNAL = "\n"
|
292 |
+
conversation = header
|
293 |
+
for sentence in source:
|
294 |
+
from_str = sentence["from"]
|
295 |
+
if from_str.lower() == "human":
|
296 |
+
from_str = conversation_lib.default_conversation.roles[0]
|
297 |
+
elif from_str.lower() == "gpt":
|
298 |
+
from_str = conversation_lib.default_conversation.roles[1]
|
299 |
+
else:
|
300 |
+
from_str = 'unknown'
|
301 |
+
sentence["value"] = (BEGIN_SIGNAL + from_str + ": " +
|
302 |
+
sentence["value"] + END_SIGNAL)
|
303 |
+
if get_conversation:
|
304 |
+
conversation += sentence["value"]
|
305 |
+
conversation += BEGIN_SIGNAL
|
306 |
+
return conversation
|
307 |
+
|
308 |
+
|
309 |
+
def preprocess_multimodal(
|
310 |
+
sources: Sequence[str],
|
311 |
+
data_args: DataArguments
|
312 |
+
) -> Dict:
|
313 |
+
is_multimodal = data_args.is_multimodal
|
314 |
+
if not is_multimodal:
|
315 |
+
return sources
|
316 |
+
|
317 |
+
for source in sources:
|
318 |
+
for sentence in source:
|
319 |
+
if DEFAULT_IMAGE_TOKEN in sentence['value']:
|
320 |
+
sentence['value'] = sentence['value'].replace(DEFAULT_IMAGE_TOKEN, '').strip()
|
321 |
+
sentence['value'] = DEFAULT_IMAGE_TOKEN + '\n' + sentence['value']
|
322 |
+
sentence['value'] = sentence['value'].strip()
|
323 |
+
if "mmtag" in conversation_lib.default_conversation.version:
|
324 |
+
sentence['value'] = sentence['value'].replace(DEFAULT_IMAGE_TOKEN, '<Image>' + DEFAULT_IMAGE_TOKEN + '</Image>')
|
325 |
+
replace_token = DEFAULT_IMAGE_TOKEN
|
326 |
+
if data_args.mm_use_im_start_end:
|
327 |
+
replace_token = DEFAULT_IM_START_TOKEN + replace_token + DEFAULT_IM_END_TOKEN
|
328 |
+
sentence["value"] = sentence["value"].replace(DEFAULT_IMAGE_TOKEN, replace_token)
|
329 |
+
|
330 |
+
return sources
|
331 |
+
|
332 |
+
|
333 |
+
def preprocess_llama_2(
|
334 |
+
sources,
|
335 |
+
tokenizer: transformers.PreTrainedTokenizer,
|
336 |
+
has_image: bool = False
|
337 |
+
) -> Dict:
|
338 |
+
conv = conversation_lib.default_conversation.copy()
|
339 |
+
roles = {"human": conv.roles[0], "gpt": conv.roles[1]}
|
340 |
+
|
341 |
+
# Apply prompt templates
|
342 |
+
conversations = []
|
343 |
+
for i, source in enumerate(sources):
|
344 |
+
if roles[source[0]["from"]] != conv.roles[0]:
|
345 |
+
# Skip the first one if it is not from human
|
346 |
+
source = source[1:]
|
347 |
+
|
348 |
+
conv.messages = []
|
349 |
+
for j, sentence in enumerate(source):
|
350 |
+
role = roles[sentence["from"]]
|
351 |
+
assert role == conv.roles[j % 2], f"{i}"
|
352 |
+
conv.append_message(role, sentence["value"])
|
353 |
+
conversations.append(conv.get_prompt())
|
354 |
+
|
355 |
+
# Tokenize conversations
|
356 |
+
|
357 |
+
if has_image:
|
358 |
+
input_ids = torch.stack([tokenizer_image_token(prompt, tokenizer, return_tensors='pt') for prompt in conversations], dim=0)
|
359 |
+
else:
|
360 |
+
input_ids = tokenizer(
|
361 |
+
conversations,
|
362 |
+
return_tensors="pt",
|
363 |
+
padding="longest",
|
364 |
+
max_length=tokenizer.model_max_length,
|
365 |
+
truncation=True,
|
366 |
+
).input_ids
|
367 |
+
|
368 |
+
targets = input_ids.clone()
|
369 |
+
|
370 |
+
assert conv.sep_style == conversation_lib.SeparatorStyle.LLAMA_2
|
371 |
+
|
372 |
+
# Mask targets
|
373 |
+
sep = "[/INST] "
|
374 |
+
for conversation, target in zip(conversations, targets):
|
375 |
+
total_len = int(target.ne(tokenizer.pad_token_id).sum())
|
376 |
+
|
377 |
+
rounds = conversation.split(conv.sep2)
|
378 |
+
cur_len = 1
|
379 |
+
target[:cur_len] = IGNORE_INDEX
|
380 |
+
for i, rou in enumerate(rounds):
|
381 |
+
if rou == "":
|
382 |
+
break
|
383 |
+
|
384 |
+
parts = rou.split(sep)
|
385 |
+
if len(parts) != 2:
|
386 |
+
break
|
387 |
+
parts[0] += sep
|
388 |
+
|
389 |
+
if has_image:
|
390 |
+
round_len = len(tokenizer_image_token(rou, tokenizer))
|
391 |
+
instruction_len = len(tokenizer_image_token(parts[0], tokenizer)) - 2
|
392 |
+
else:
|
393 |
+
round_len = len(tokenizer(rou).input_ids)
|
394 |
+
instruction_len = len(tokenizer(parts[0]).input_ids) - 2
|
395 |
+
|
396 |
+
target[cur_len : cur_len + instruction_len] = IGNORE_INDEX
|
397 |
+
|
398 |
+
cur_len += round_len
|
399 |
+
target[cur_len:] = IGNORE_INDEX
|
400 |
+
|
401 |
+
if cur_len < tokenizer.model_max_length:
|
402 |
+
if cur_len != total_len:
|
403 |
+
target[:] = IGNORE_INDEX
|
404 |
+
print(
|
405 |
+
f"WARNING: tokenization mismatch: {cur_len} vs. {total_len}."
|
406 |
+
f" (ignored)"
|
407 |
+
)
|
408 |
+
|
409 |
+
return dict(
|
410 |
+
input_ids=input_ids,
|
411 |
+
labels=targets,
|
412 |
+
)
|
413 |
+
|
414 |
+
|
415 |
+
def preprocess_v1(
|
416 |
+
sources,
|
417 |
+
tokenizer: transformers.PreTrainedTokenizer,
|
418 |
+
has_image: bool = False
|
419 |
+
) -> Dict:
|
420 |
+
conv = conversation_lib.voco_default_conversation.copy()
|
421 |
+
roles = {"human": conv.roles[0], "gpt": conv.roles[1]}
|
422 |
+
|
423 |
+
# Apply prompt templates
|
424 |
+
conversations = []
|
425 |
+
for i, source in enumerate(sources):
|
426 |
+
if roles[source[0]["from"]] != conv.roles[0]:
|
427 |
+
# Skip the first one if it is not from human
|
428 |
+
source = source[1:]
|
429 |
+
|
430 |
+
conv.messages = []
|
431 |
+
for j, sentence in enumerate(source):
|
432 |
+
role = roles[sentence["from"]]
|
433 |
+
assert role == conv.roles[j % 2], f"{i}"
|
434 |
+
conv.append_message(role, sentence["value"])
|
435 |
+
conversations.append(conv.get_prompt())
|
436 |
+
# The assistant gives helpful, detailed, and polite answers to the user's questions.
|
437 |
+
# + <image> + USER: Q + ASSITENT: A + ...
|
438 |
+
|
439 |
+
# Tokenize conversations
|
440 |
+
# token num
|
441 |
+
if has_image:
|
442 |
+
maybe_voco_str = "".join(
|
443 |
+
["<voco>" for _ in range(2)]
|
444 |
+
)
|
445 |
+
# conversations = [f"<image>\n{maybe_voco_str}\n" + conversations[0].replace("<image>\n", '')]
|
446 |
+
conversations = [f"<image>\n{maybe_voco_str}\n" + conversations[0].replace("<image>", '').replace("\n", '')]
|
447 |
+
input_ids = torch.stack([tokenizer_image_token(prompt, tokenizer, return_tensors='pt') for prompt in conversations], dim=0)
|
448 |
+
else:
|
449 |
+
input_ids = tokenizer(
|
450 |
+
conversations,
|
451 |
+
return_tensors="pt",
|
452 |
+
padding="longest",
|
453 |
+
max_length=tokenizer.model_max_length,
|
454 |
+
truncation=True,
|
455 |
+
).input_ids
|
456 |
+
|
457 |
+
targets = input_ids.clone() # [1, len]
|
458 |
+
|
459 |
+
assert conv.sep_style == conversation_lib.SeparatorStyle.TWO
|
460 |
+
|
461 |
+
# Mask targets
|
462 |
+
sep = conv.sep + conv.roles[1] + ": "
|
463 |
+
for conversation, target in zip(conversations, targets):
|
464 |
+
total_len = int(target.ne(tokenizer.pad_token_id).sum())
|
465 |
+
|
466 |
+
rounds = conversation.split(conv.sep2)
|
467 |
+
cur_len = 1
|
468 |
+
target[:cur_len] = IGNORE_INDEX
|
469 |
+
for i, rou in enumerate(rounds):
|
470 |
+
if rou == "":
|
471 |
+
break
|
472 |
+
|
473 |
+
parts = rou.split(sep)
|
474 |
+
if len(parts) != 2:
|
475 |
+
break
|
476 |
+
parts[0] += sep
|
477 |
+
if has_image:
|
478 |
+
round_len = len(tokenizer_image_token(rou, tokenizer)) # 1 + tokenize(rou), 其中<image>这个token被特殊编码为200
|
479 |
+
instruction_len = len(tokenizer_image_token(parts[0], tokenizer)) - 2 # 问题token
|
480 |
+
else:
|
481 |
+
round_len = len(tokenizer(rou).input_ids)
|
482 |
+
instruction_len = len(tokenizer(parts[0]).input_ids) - 2
|
483 |
+
|
484 |
+
if i != 0 and not tokenizer.legacy and IS_TOKENIZER_GREATER_THAN_0_14:
|
485 |
+
round_len -= 1
|
486 |
+
instruction_len -= 1
|
487 |
+
|
488 |
+
target[cur_len : cur_len + instruction_len] = IGNORE_INDEX
|
489 |
+
|
490 |
+
cur_len += round_len
|
491 |
+
target[cur_len:] = IGNORE_INDEX
|
492 |
+
if cur_len < tokenizer.model_max_length:
|
493 |
+
if cur_len != total_len:
|
494 |
+
target[:] = IGNORE_INDEX
|
495 |
+
print(
|
496 |
+
f"WARNING: tokenization mismatch: {cur_len} vs. {total_len}."
|
497 |
+
f" (ignored)"
|
498 |
+
)
|
499 |
+
|
500 |
+
return dict(
|
501 |
+
input_ids=input_ids,
|
502 |
+
labels=targets,
|
503 |
+
)
|
504 |
+
|
505 |
+
|
506 |
+
def preprocess_mpt(
|
507 |
+
sources,
|
508 |
+
tokenizer: transformers.PreTrainedTokenizer,
|
509 |
+
has_image: bool = False
|
510 |
+
) -> Dict:
|
511 |
+
conv = conversation_lib.default_conversation.copy()
|
512 |
+
roles = {"human": conv.roles[0], "gpt": conv.roles[1]}
|
513 |
+
|
514 |
+
# Apply prompt templates
|
515 |
+
conversations = []
|
516 |
+
for i, source in enumerate(sources):
|
517 |
+
if roles[source[0]["from"]] != conv.roles[0]:
|
518 |
+
# Skip the first one if it is not from human
|
519 |
+
source = source[1:]
|
520 |
+
|
521 |
+
conv.messages = []
|
522 |
+
for j, sentence in enumerate(source):
|
523 |
+
role = roles[sentence["from"]]
|
524 |
+
assert role == conv.roles[j % 2], f"{i}"
|
525 |
+
conv.append_message(role, sentence["value"])
|
526 |
+
conversations.append(conv.get_prompt())
|
527 |
+
|
528 |
+
# Tokenize conversations
|
529 |
+
|
530 |
+
if has_image:
|
531 |
+
input_ids = torch.stack([tokenizer_image_token(prompt, tokenizer, return_tensors='pt') for prompt in conversations], dim=0)
|
532 |
+
else:
|
533 |
+
input_ids = tokenizer(
|
534 |
+
conversations,
|
535 |
+
return_tensors="pt",
|
536 |
+
padding="longest",
|
537 |
+
max_length=tokenizer.model_max_length,
|
538 |
+
truncation=True,
|
539 |
+
).input_ids
|
540 |
+
|
541 |
+
targets = input_ids.clone()
|
542 |
+
assert conv.sep_style == conversation_lib.SeparatorStyle.MPT
|
543 |
+
|
544 |
+
# Mask targets
|
545 |
+
sep = conv.sep + conv.roles[1]
|
546 |
+
for conversation, target in zip(conversations, targets):
|
547 |
+
total_len = int(target.ne(tokenizer.pad_token_id).sum())
|
548 |
+
|
549 |
+
rounds = conversation.split(conv.sep)
|
550 |
+
re_rounds = [conv.sep.join(rounds[:3])] # system + user + gpt
|
551 |
+
for conv_idx in range(3, len(rounds), 2):
|
552 |
+
re_rounds.append(conv.sep.join(rounds[conv_idx:conv_idx+2])) # user + gpt
|
553 |
+
cur_len = 0
|
554 |
+
target[:cur_len] = IGNORE_INDEX
|
555 |
+
for i, rou in enumerate(re_rounds):
|
556 |
+
if rou == "":
|
557 |
+
break
|
558 |
+
|
559 |
+
parts = rou.split(sep)
|
560 |
+
if len(parts) != 2:
|
561 |
+
break
|
562 |
+
parts[0] += sep
|
563 |
+
|
564 |
+
if has_image:
|
565 |
+
round_len = len(tokenizer_image_token(rou, tokenizer))
|
566 |
+
instruction_len = len(tokenizer_image_token(parts[0], tokenizer)) - 1
|
567 |
+
else:
|
568 |
+
round_len = len(tokenizer(rou).input_ids)
|
569 |
+
instruction_len = len(tokenizer(parts[0]).input_ids) - 1
|
570 |
+
|
571 |
+
if i != 0 and getattr(tokenizer, 'legacy', False) and IS_TOKENIZER_GREATER_THAN_0_14:
|
572 |
+
round_len += 1
|
573 |
+
instruction_len += 1
|
574 |
+
|
575 |
+
target[cur_len : cur_len + instruction_len] = IGNORE_INDEX
|
576 |
+
|
577 |
+
cur_len += round_len
|
578 |
+
target[cur_len:] = IGNORE_INDEX
|
579 |
+
|
580 |
+
if cur_len < tokenizer.model_max_length:
|
581 |
+
if cur_len != total_len:
|
582 |
+
target[:] = IGNORE_INDEX
|
583 |
+
print(
|
584 |
+
f"WARNING: tokenization mismatch: {cur_len} vs. {total_len}."
|
585 |
+
f" (ignored)"
|
586 |
+
)
|
587 |
+
|
588 |
+
return dict(
|
589 |
+
input_ids=input_ids,
|
590 |
+
labels=targets,
|
591 |
+
)
|
592 |
+
|
593 |
+
|
594 |
+
def preprocess_plain(
|
595 |
+
sources: Sequence[str],
|
596 |
+
tokenizer: transformers.PreTrainedTokenizer,
|
597 |
+
) -> Dict:
|
598 |
+
# add end signal and concatenate together
|
599 |
+
conversations = []
|
600 |
+
for source in sources:
|
601 |
+
assert len(source) == 2
|
602 |
+
assert DEFAULT_IMAGE_TOKEN in source[0]['value']
|
603 |
+
source[0]['value'] = DEFAULT_IMAGE_TOKEN
|
604 |
+
conversation = source[0]['value'] + source[1]['value'] + conversation_lib.default_conversation.sep
|
605 |
+
conversations.append(conversation)
|
606 |
+
# tokenize conversations
|
607 |
+
input_ids = [tokenizer_image_token(prompt, tokenizer, return_tensors='pt') for prompt in conversations]
|
608 |
+
targets = copy.deepcopy(input_ids)
|
609 |
+
for target, source in zip(targets, sources):
|
610 |
+
tokenized_len = len(tokenizer_image_token(source[0]['value'], tokenizer))
|
611 |
+
target[:tokenized_len] = IGNORE_INDEX
|
612 |
+
|
613 |
+
return dict(input_ids=input_ids, labels=targets)
|
614 |
+
|
615 |
+
|
616 |
+
def preprocess(
|
617 |
+
sources: Sequence[str],
|
618 |
+
tokenizer: transformers.PreTrainedTokenizer,
|
619 |
+
has_image: bool = False
|
620 |
+
) -> Dict:
|
621 |
+
"""
|
622 |
+
Given a list of sources, each is a conversation list. This transform:
|
623 |
+
1. Add signal '### ' at the beginning each sentence, with end signal '\n';
|
624 |
+
2. Concatenate conversations together;
|
625 |
+
3. Tokenize the concatenated conversation;
|
626 |
+
4. Make a deepcopy as the target. Mask human words with IGNORE_INDEX.
|
627 |
+
"""
|
628 |
+
if conversation_lib.default_conversation.sep_style == conversation_lib.SeparatorStyle.PLAIN:
|
629 |
+
return preprocess_plain(sources, tokenizer)
|
630 |
+
if conversation_lib.default_conversation.sep_style == conversation_lib.SeparatorStyle.LLAMA_2:
|
631 |
+
return preprocess_llama_2(sources, tokenizer, has_image=has_image)
|
632 |
+
if conversation_lib.default_conversation.version.startswith("v1"):
|
633 |
+
return preprocess_v1(sources, tokenizer, has_image=has_image)
|
634 |
+
if conversation_lib.default_conversation.version == "mpt":
|
635 |
+
return preprocess_mpt(sources, tokenizer, has_image=has_image)
|
636 |
+
# add end signal and concatenate together
|
637 |
+
conversations = []
|
638 |
+
for source in sources:
|
639 |
+
header = f"{conversation_lib.default_conversation.system}\n\n"
|
640 |
+
conversation = _add_speaker_and_signal(header, source)
|
641 |
+
conversations.append(conversation)
|
642 |
+
# tokenize conversations
|
643 |
+
def get_tokenize_len(prompts):
|
644 |
+
return [len(tokenizer_image_token(prompt, tokenizer)) for prompt in prompts]
|
645 |
+
|
646 |
+
if has_image:
|
647 |
+
input_ids = [tokenizer_image_token(prompt, tokenizer, return_tensors='pt') for prompt in conversations]
|
648 |
+
else:
|
649 |
+
conversations_tokenized = _tokenize_fn(conversations, tokenizer)
|
650 |
+
input_ids = conversations_tokenized["input_ids"]
|
651 |
+
|
652 |
+
targets = copy.deepcopy(input_ids)
|
653 |
+
for target, source in zip(targets, sources):
|
654 |
+
if has_image:
|
655 |
+
tokenized_lens = get_tokenize_len([header] + [s["value"] for s in source])
|
656 |
+
else:
|
657 |
+
tokenized_lens = _tokenize_fn([header] + [s["value"] for s in source], tokenizer)["input_ids_lens"]
|
658 |
+
speakers = [sentence["from"] for sentence in source]
|
659 |
+
_mask_targets(target, tokenized_lens, speakers)
|
660 |
+
|
661 |
+
return dict(input_ids=input_ids, labels=targets)
|
662 |
+
|
663 |
+
|
664 |
+
class LazySupervisedDataset(Dataset):
|
665 |
+
"""Dataset for supervised fine-tuning."""
|
666 |
+
|
667 |
+
def __init__(self, data_path: str,
|
668 |
+
tokenizer: transformers.PreTrainedTokenizer,
|
669 |
+
data_args: DataArguments,
|
670 |
+
voco_token):
|
671 |
+
super(LazySupervisedDataset, self).__init__()
|
672 |
+
list_data_dict = json.load(open(data_path, "r"))
|
673 |
+
|
674 |
+
rank0_print("Formatting inputs...Skip in lazy mode")
|
675 |
+
self.tokenizer = tokenizer
|
676 |
+
self.list_data_dict = list_data_dict
|
677 |
+
self.data_args = data_args
|
678 |
+
self.voco_token = voco_token
|
679 |
+
|
680 |
+
def __len__(self):
|
681 |
+
return len(self.list_data_dict)
|
682 |
+
|
683 |
+
@property
|
684 |
+
def lengths(self):
|
685 |
+
length_list = []
|
686 |
+
for sample in self.list_data_dict:
|
687 |
+
img_tokens = 128 if 'image' in sample else 0
|
688 |
+
length_list.append(sum(len(conv['value'].split()) for conv in sample['conversations']) + img_tokens)
|
689 |
+
return length_list
|
690 |
+
|
691 |
+
@property
|
692 |
+
def modality_lengths(self):
|
693 |
+
length_list = []
|
694 |
+
for sample in self.list_data_dict:
|
695 |
+
cur_len = sum(len(conv['value'].split()) for conv in sample['conversations'])
|
696 |
+
cur_len = cur_len if 'image' in sample else -cur_len
|
697 |
+
length_list.append(cur_len)
|
698 |
+
return length_list
|
699 |
+
|
700 |
+
def __getitem__(self, i) -> Dict[str, torch.Tensor]:
|
701 |
+
sources = self.list_data_dict[i]
|
702 |
+
if isinstance(i, int):
|
703 |
+
sources = [sources]
|
704 |
+
assert len(sources) == 1, "Don't know why it is wrapped to a list" # FIXME
|
705 |
+
if 'image' in sources[0]:
|
706 |
+
image_file = self.list_data_dict[i]['image']
|
707 |
+
image_folder = self.data_args.image_folder
|
708 |
+
processor = self.data_args.image_processor
|
709 |
+
# print(image_folder, image_file)
|
710 |
+
image = Image.open(os.path.join(image_folder, image_file)).convert('RGB')
|
711 |
+
if self.data_args.image_aspect_ratio == 'pad':
|
712 |
+
def expand2square(pil_img, background_color):
|
713 |
+
width, height = pil_img.size
|
714 |
+
if width == height:
|
715 |
+
return pil_img
|
716 |
+
elif width > height:
|
717 |
+
result = Image.new(pil_img.mode, (width, width), background_color)
|
718 |
+
result.paste(pil_img, (0, (width - height) // 2))
|
719 |
+
return result
|
720 |
+
else:
|
721 |
+
result = Image.new(pil_img.mode, (height, height), background_color)
|
722 |
+
result.paste(pil_img, ((height - width) // 2, 0))
|
723 |
+
return result
|
724 |
+
image = expand2square(image, tuple(int(x*255) for x in processor.image_mean))
|
725 |
+
image = processor.preprocess(image, return_tensors='pt')['pixel_values'][0] # [3, 336, 336]
|
726 |
+
else:
|
727 |
+
image = processor.preprocess(image, return_tensors='pt')['pixel_values'][0]
|
728 |
+
sources = preprocess_multimodal(
|
729 |
+
copy.deepcopy([e["conversations"] for e in sources]),
|
730 |
+
self.data_args)
|
731 |
+
else:
|
732 |
+
sources = copy.deepcopy([e["conversations"] for e in sources])
|
733 |
+
data_dict = preprocess(
|
734 |
+
sources,
|
735 |
+
self.tokenizer,
|
736 |
+
has_image=('image' in self.list_data_dict[i]))
|
737 |
+
if isinstance(i, int):
|
738 |
+
data_dict = dict(input_ids=data_dict["input_ids"][0],
|
739 |
+
labels=data_dict["labels"][0])
|
740 |
+
|
741 |
+
# image exist in the data
|
742 |
+
if 'image' in self.list_data_dict[i]:
|
743 |
+
data_dict['image'] = image
|
744 |
+
elif self.data_args.is_multimodal:
|
745 |
+
# image does not exist in the data, but the model is multimodal
|
746 |
+
crop_size = self.data_args.image_processor.crop_size
|
747 |
+
data_dict['image'] = torch.zeros(3, crop_size['height'], crop_size['width'])
|
748 |
+
return data_dict
|
749 |
+
|
750 |
+
@dataclass
|
751 |
+
class DataCollatorForSupervisedDataset(object):
|
752 |
+
"""Collate examples for supervised fine-tuning."""
|
753 |
+
|
754 |
+
tokenizer: transformers.PreTrainedTokenizer
|
755 |
+
|
756 |
+
def __call__(self, instances: Sequence[Dict]) -> Dict[str, torch.Tensor]:
|
757 |
+
input_ids, labels = tuple([instance[key] for instance in instances]
|
758 |
+
for key in ("input_ids", "labels"))
|
759 |
+
input_ids = torch.nn.utils.rnn.pad_sequence(
|
760 |
+
input_ids,
|
761 |
+
batch_first=True,
|
762 |
+
padding_value=self.tokenizer.pad_token_id)
|
763 |
+
labels = torch.nn.utils.rnn.pad_sequence(labels,
|
764 |
+
batch_first=True,
|
765 |
+
padding_value=IGNORE_INDEX)
|
766 |
+
input_ids = input_ids[:, :self.tokenizer.model_max_length]
|
767 |
+
labels = labels[:, :self.tokenizer.model_max_length]
|
768 |
+
batch = dict(
|
769 |
+
input_ids=input_ids,
|
770 |
+
labels=labels,
|
771 |
+
attention_mask=input_ids.ne(self.tokenizer.pad_token_id),
|
772 |
+
)
|
773 |
+
|
774 |
+
if 'image' in instances[0]:
|
775 |
+
images = [instance['image'] for instance in instances]
|
776 |
+
if all(x is not None and x.shape == images[0].shape for x in images):
|
777 |
+
batch['images'] = torch.stack(images)
|
778 |
+
else:
|
779 |
+
batch['images'] = images
|
780 |
+
|
781 |
+
return batch
|
782 |
+
|
783 |
+
|
784 |
+
def make_supervised_data_module(tokenizer: transformers.PreTrainedTokenizer,
|
785 |
+
data_args, voco_token) -> Dict:
|
786 |
+
"""Make dataset and collator for supervised fine-tuning."""
|
787 |
+
train_dataset = LazySupervisedDataset(tokenizer=tokenizer,
|
788 |
+
data_path=data_args.data_path,
|
789 |
+
data_args=data_args,
|
790 |
+
voco_token=voco_token)
|
791 |
+
data_collator = DataCollatorForSupervisedDataset(tokenizer=tokenizer)
|
792 |
+
return dict(train_dataset=train_dataset,
|
793 |
+
eval_dataset=None,
|
794 |
+
data_collator=data_collator)
|
795 |
+
|
796 |
+
|
797 |
+
def train(attn_implementation=None):
|
798 |
+
global local_rank
|
799 |
+
|
800 |
+
parser = transformers.HfArgumentParser(
|
801 |
+
(ModelArguments, DataArguments, TrainingArguments))
|
802 |
+
model_args, data_args, training_args = parser.parse_args_into_dataclasses()
|
803 |
+
local_rank = training_args.local_rank
|
804 |
+
compute_dtype = (torch.float16 if training_args.fp16 else (torch.bfloat16 if training_args.bf16 else torch.float32))
|
805 |
+
|
806 |
+
bnb_model_from_pretrained_args = {}
|
807 |
+
if training_args.bits in [4, 8]:
|
808 |
+
from transformers import BitsAndBytesConfig
|
809 |
+
bnb_model_from_pretrained_args.update(dict(
|
810 |
+
device_map={"": training_args.device},
|
811 |
+
load_in_4bit=training_args.bits == 4,
|
812 |
+
load_in_8bit=training_args.bits == 8,
|
813 |
+
quantization_config=BitsAndBytesConfig(
|
814 |
+
load_in_4bit=training_args.bits == 4,
|
815 |
+
load_in_8bit=training_args.bits == 8,
|
816 |
+
llm_int8_skip_modules=["mm_projector"],
|
817 |
+
llm_int8_threshold=6.0,
|
818 |
+
llm_int8_has_fp16_weight=False,
|
819 |
+
bnb_4bit_compute_dtype=compute_dtype,
|
820 |
+
bnb_4bit_use_double_quant=training_args.double_quant,
|
821 |
+
bnb_4bit_quant_type=training_args.quant_type # {'fp4', 'nf4'}
|
822 |
+
)
|
823 |
+
))
|
824 |
+
|
825 |
+
if model_args.vision_tower is not None:
|
826 |
+
if 'mpt' in model_args.model_name_or_path:
|
827 |
+
config = transformers.AutoConfig.from_pretrained(model_args.model_name_or_path, trust_remote_code=True)
|
828 |
+
config.attn_config['attn_impl'] = training_args.mpt_attn_impl
|
829 |
+
model = LlavaMptForCausalLM.from_pretrained(
|
830 |
+
model_args.model_name_or_path,
|
831 |
+
config=config,
|
832 |
+
cache_dir=training_args.cache_dir,
|
833 |
+
**bnb_model_from_pretrained_args
|
834 |
+
)
|
835 |
+
else:
|
836 |
+
print("use LlavaLlamaForCausalLM!!!")
|
837 |
+
model = LlavaLlamaForCausalLM.from_pretrained(
|
838 |
+
model_args.model_name_or_path,
|
839 |
+
cache_dir=training_args.cache_dir,
|
840 |
+
attn_implementation=attn_implementation,
|
841 |
+
torch_dtype=(torch.bfloat16 if training_args.bf16 else None),
|
842 |
+
**bnb_model_from_pretrained_args
|
843 |
+
)
|
844 |
+
else:
|
845 |
+
model = transformers.LlamaForCausalLM.from_pretrained(
|
846 |
+
model_args.model_name_or_path,
|
847 |
+
cache_dir=training_args.cache_dir,
|
848 |
+
attn_implementation=attn_implementation,
|
849 |
+
torch_dtype=(torch.bfloat16 if training_args.bf16 else None),
|
850 |
+
**bnb_model_from_pretrained_args
|
851 |
+
)
|
852 |
+
model.config.use_cache = False
|
853 |
+
|
854 |
+
if model_args.freeze_backbone:
|
855 |
+
model.model.requires_grad_(False)
|
856 |
+
|
857 |
+
if training_args.bits in [4, 8]:
|
858 |
+
from peft import prepare_model_for_kbit_training
|
859 |
+
model.config.torch_dtype=(torch.float32 if training_args.fp16 else (torch.bfloat16 if training_args.bf16 else torch.float32))
|
860 |
+
model = prepare_model_for_kbit_training(model, use_gradient_checkpointing=training_args.gradient_checkpointing)
|
861 |
+
|
862 |
+
if training_args.gradient_checkpointing:
|
863 |
+
if hasattr(model, "enable_input_require_grads"):
|
864 |
+
model.enable_input_require_grads()
|
865 |
+
else:
|
866 |
+
def make_inputs_require_grad(module, input, output):
|
867 |
+
output.requires_grad_(True)
|
868 |
+
model.get_input_embeddings().register_forward_hook(make_inputs_require_grad)
|
869 |
+
|
870 |
+
if training_args.lora_enable:
|
871 |
+
from peft import LoraConfig, get_peft_model
|
872 |
+
lora_config = LoraConfig(
|
873 |
+
r=training_args.lora_r,
|
874 |
+
lora_alpha=training_args.lora_alpha,
|
875 |
+
target_modules=find_all_linear_names(model),
|
876 |
+
lora_dropout=training_args.lora_dropout,
|
877 |
+
bias=training_args.lora_bias,
|
878 |
+
task_type="CAUSAL_LM",
|
879 |
+
)
|
880 |
+
if training_args.bits == 16:
|
881 |
+
if training_args.bf16:
|
882 |
+
model.to(torch.bfloat16)
|
883 |
+
if training_args.fp16:
|
884 |
+
model.to(torch.float16)
|
885 |
+
rank0_print("Adding LoRA adapters...")
|
886 |
+
model = get_peft_model(model, lora_config)
|
887 |
+
|
888 |
+
if 'mpt' in model_args.model_name_or_path:
|
889 |
+
tokenizer = transformers.AutoTokenizer.from_pretrained(
|
890 |
+
model_args.model_name_or_path,
|
891 |
+
cache_dir=training_args.cache_dir,
|
892 |
+
model_max_length=training_args.model_max_length,
|
893 |
+
padding_side="right"
|
894 |
+
)
|
895 |
+
else:
|
896 |
+
tokenizer = transformers.AutoTokenizer.from_pretrained(
|
897 |
+
model_args.model_name_or_path,
|
898 |
+
cache_dir=training_args.cache_dir,
|
899 |
+
model_max_length=training_args.model_max_length,
|
900 |
+
padding_side="left",
|
901 |
+
use_fast=False,
|
902 |
+
)
|
903 |
+
|
904 |
+
if model_args.version == "v0":
|
905 |
+
if tokenizer.pad_token is None:
|
906 |
+
smart_tokenizer_and_embedding_resize(
|
907 |
+
special_tokens_dict=dict(pad_token="[PAD]"),
|
908 |
+
tokenizer=tokenizer,
|
909 |
+
model=model,
|
910 |
+
)
|
911 |
+
elif model_args.version == "v0.5":
|
912 |
+
tokenizer.pad_token = tokenizer.unk_token
|
913 |
+
else:
|
914 |
+
tokenizer.pad_token = tokenizer.unk_token
|
915 |
+
if model_args.version in conversation_lib.conv_templates:
|
916 |
+
conversation_lib.default_conversation = conversation_lib.conv_templates[model_args.version]
|
917 |
+
else:
|
918 |
+
conversation_lib.default_conversation = conversation_lib.conv_templates["vicuna_v1"]
|
919 |
+
|
920 |
+
if len(tokenizer) == 32000 + 1:
|
921 |
+
assert (
|
922 |
+
model.model.embed_tokens.weight.shape[0]
|
923 |
+
== 32000 + 1
|
924 |
+
)
|
925 |
+
assert model.lm_head.weight.shape[0] == 32000 + 1
|
926 |
+
else:
|
927 |
+
print('add_voco_token 32001')
|
928 |
+
# Initialize voco token
|
929 |
+
tokenizer.add_special_tokens({"additional_special_tokens": ["<voco>"]})
|
930 |
+
model.resize_token_embeddings(len(tokenizer))
|
931 |
+
voco_token = tokenizer.additional_special_tokens_ids[-1]
|
932 |
+
|
933 |
+
if model_args.vision_tower is not None:
|
934 |
+
model.get_model().initialize_vision_modules(
|
935 |
+
model_args=model_args,
|
936 |
+
fsdp=training_args.fsdp
|
937 |
+
)
|
938 |
+
|
939 |
+
vision_tower = model.get_vision_tower()
|
940 |
+
vision_tower.to(dtype=torch.bfloat16 if training_args.bf16 else torch.float16, device=training_args.device)
|
941 |
+
|
942 |
+
data_args.image_processor = vision_tower.image_processor
|
943 |
+
data_args.is_multimodal = True
|
944 |
+
|
945 |
+
model.config.image_aspect_ratio = data_args.image_aspect_ratio
|
946 |
+
model.config.tokenizer_padding_side = tokenizer.padding_side
|
947 |
+
model.config.tokenizer_model_max_length = tokenizer.model_max_length
|
948 |
+
|
949 |
+
model.config.tune_mm_mlp_adapter = training_args.tune_mm_mlp_adapter = model_args.tune_mm_mlp_adapter
|
950 |
+
if model_args.tune_mm_mlp_adapter:
|
951 |
+
model.requires_grad_(False)
|
952 |
+
for p in model.get_model().mm_projector.parameters():
|
953 |
+
p.requires_grad = True
|
954 |
+
|
955 |
+
model.config.freeze_mm_mlp_adapter = training_args.freeze_mm_mlp_adapter
|
956 |
+
if training_args.freeze_mm_mlp_adapter:
|
957 |
+
for p in model.get_model().mm_projector.parameters():
|
958 |
+
p.requires_grad = False
|
959 |
+
|
960 |
+
if training_args.bits in [4, 8]:
|
961 |
+
model.get_model().mm_projector.to(dtype=compute_dtype, device=training_args.device)
|
962 |
+
|
963 |
+
model.config.mm_use_im_start_end = data_args.mm_use_im_start_end = model_args.mm_use_im_start_end
|
964 |
+
model.config.mm_projector_lr = training_args.mm_projector_lr
|
965 |
+
training_args.use_im_start_end = model_args.mm_use_im_start_end
|
966 |
+
model.config.mm_use_im_patch_token = model_args.mm_use_im_patch_token
|
967 |
+
model.initialize_vision_tokenizer(model_args, tokenizer=tokenizer)
|
968 |
+
|
969 |
+
if training_args.bits in [4, 8]:
|
970 |
+
from peft.tuners.lora import LoraLayer
|
971 |
+
for name, module in model.named_modules():
|
972 |
+
if isinstance(module, LoraLayer):
|
973 |
+
if training_args.bf16:
|
974 |
+
module = module.to(torch.bfloat16)
|
975 |
+
if 'norm' in name:
|
976 |
+
module = module.to(torch.float32)
|
977 |
+
if 'lm_head' in name or 'embed_tokens' in name:
|
978 |
+
if hasattr(module, 'weight'):
|
979 |
+
if training_args.bf16 and module.weight.dtype == torch.float32:
|
980 |
+
module = module.to(torch.bfloat16)
|
981 |
+
|
982 |
+
data_module = make_supervised_data_module(tokenizer=tokenizer,
|
983 |
+
data_args=data_args,
|
984 |
+
voco_token=voco_token)
|
985 |
+
trainer = LLaVATrainer(model=model,
|
986 |
+
tokenizer=tokenizer,
|
987 |
+
args=training_args,
|
988 |
+
**data_module)
|
989 |
+
if list(pathlib.Path(training_args.output_dir).glob("checkpoint-*")):
|
990 |
+
trainer.train(resume_from_checkpoint=True)
|
991 |
+
else:
|
992 |
+
trainer.train()
|
993 |
+
trainer.save_state()
|
994 |
+
|
995 |
+
model.config.use_cache = True
|
996 |
+
|
997 |
+
if training_args.lora_enable:
|
998 |
+
state_dict = get_peft_state_maybe_zero_3(
|
999 |
+
model.named_parameters(), training_args.lora_bias
|
1000 |
+
)
|
1001 |
+
non_lora_state_dict = get_peft_state_non_lora_maybe_zero_3(
|
1002 |
+
model.named_parameters()
|
1003 |
+
)
|
1004 |
+
if training_args.local_rank == 0 or training_args.local_rank == -1:
|
1005 |
+
model.config.save_pretrained(training_args.output_dir)
|
1006 |
+
model.save_pretrained(training_args.output_dir, state_dict=state_dict)
|
1007 |
+
torch.save(non_lora_state_dict, os.path.join(training_args.output_dir, 'non_lora_trainables.bin'))
|
1008 |
+
else:
|
1009 |
+
safe_save_model_for_hf_trainer(trainer=trainer,
|
1010 |
+
output_dir=training_args.output_dir)
|
1011 |
+
|
1012 |
+
|
1013 |
+
if __name__ == "__main__":
|
1014 |
+
train()
|
playground/data.z01
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:e1ceb2163b22aa3902a15ce2437f706aa40fc1db138a7c4b716ed142198467cb
|
3 |
+
size 2147483648
|
playground/data.z02
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:8e138f45d610b3d95a4fc0d80d58405dbc71ccde5aa40bd3f1cefd66732426cd
|
3 |
+
size 2147483648
|
playground/data.z04
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:8ed07a3fd033e030566485904b51dad83a7c7ba33f84b7f695234268e4bc88f3
|
3 |
+
size 2147483648
|
playground/data.z05
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:e05dd44b56489f31294ee72cd53584f8696989b28d004967e0f1a21346fcf0d8
|
3 |
+
size 2147483648
|
playground/data.z06
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:9d46ed522f29fd1f5c9005802169aadf02f79f33a47a1fc4d92f7ae164729a72
|
3 |
+
size 2147483648
|
playground/data.z07
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:5f497e6b0591cd77b9c98f347ddaa30033fc68d7c11d7285e438e4e15bac4030
|
3 |
+
size 2147483648
|
playground/data.z08
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:8b86e4ec1984deb85e4328a651d577864d52a2d26b671bf0e14c24e6b0c7355a
|
3 |
+
size 2147483648
|
playground/data.z09
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:73ebf3eaf895f6b2887fd31715476d5c002aa35fd7a639d827d3c62f849c5fb4
|
3 |
+
size 2147483648
|
playground/data.z10
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:b3021d11b512ecef45411d98c050f4624c08e9b8ae9c1f92080193fba6ae2893
|
3 |
+
size 2147483648
|
playground/data.z11
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:b9a561fe234189d270e848c9a20bb333b571d8d9be301478506098a696146748
|
3 |
+
size 2147483648
|
playground/data.z12
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:6b7fc0a9d324138c93d23e9625c05e93f848ebb10ab97f69adcd3a31df1edf9d
|
3 |
+
size 2147483648
|
playground/data.z14
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:a43c6a02297e630589bfdae80253abd36844e0a4bc10878f1605ac49111c14ce
|
3 |
+
size 2147483648
|
playground/data.z15
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:e2e6ba5d89dc588bbc9961b487e9dc9f7eb0179b7d8b349b4135f5a279741ec1
|
3 |
+
size 2147483648
|
playground/data.z16
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:688f74622bf5d37b662328ffe3ef7633832239e85e59dad53dd05755e6aae80f
|
3 |
+
size 2147483648
|
playground/data.z18
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:734c4ddaf5495e9d46a46f94f5e5c66ca5ce99726dbfb07f910343066d7a2a5e
|
3 |
+
size 2147483648
|
playground/data.z19
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:d4dab9b7cd28541bce4280501891d0f416dc5fae6c752f6cef953b319df3d2b5
|
3 |
+
size 2147483648
|
playground/data.z20
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:85e2c888eaae0ea32b2d7165df9396741f5de2e60538147b096ed8de1272761b
|
3 |
+
size 2147483648
|
playground/data.z21
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:b9d0a980e330cb5c3ba0b0b11c18e6f423e2e6e9a6dd471a3cc9a2964f07f49d
|
3 |
+
size 2147483648
|
playground/data.z23
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:2b73e57e422c0b13a245bffae386710156395896275be0f1a79f2d82f960cd9a
|
3 |
+
size 2147483648
|
playground/data.z24
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:78c020681da40773468f8acb64367b4a34434d387dd98e19d2bc92fb459547c7
|
3 |
+
size 2147483648
|
playground/data.z25
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:cf9201ad221bbea10b9ca674aa09749e9ac85c1aa38faef43ccb68635f6c2d00
|
3 |
+
size 2147483648
|
playground/data.z26
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:74f50f8cbad2263539c7abd33c238a7a5d3fee2925cacc14c939c5eab0abd345
|
3 |
+
size 2147483648
|
playground/data.z27
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:6e466a0f229e226b1f7375854e8828cf5f633c5c787e63affc75d56b965aaeda
|
3 |
+
size 2147483648
|
playground/data.z28
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:107c1a049083baad33211500368dbca8a309cceb28fe9c39d34203684b81cc53
|
3 |
+
size 2147483648
|
playground/data.z30
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:f114630e80b9f0f943340b98042f797f81b186d53e4ebb6e87f0a661a8bfaf15
|
3 |
+
size 2147483648
|