teowu commited on
Commit
b7f8528
·
verified ·
1 Parent(s): 28b4a4d

Upload micbench_xcomposer.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. micbench_xcomposer.py +71 -0
micbench_xcomposer.py ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from transformers import AutoTokenizer, AutoModelForCausalLM
3
+ ckpt_path = "internlm/internlm-xcomposer2-vl-7b"
4
+ tokenizer = AutoTokenizer.from_pretrained(ckpt_path, trust_remote_code=True)
5
+ # `torch_dtype=torch.float16` 可以令模型以 float16 精度加载,否则 transformers 会将模型加载为 float32,导致显存不足
6
+ model = AutoModelForCausalLM.from_pretrained(ckpt_path, torch_dtype=torch.float16, trust_remote_code=True, device_map={"":"cuda:1"})
7
+
8
+ model.max_length = 5120
9
+
10
+ image_folder = "/home/ps/Downloads/datasets/micbench/micbench_imgs/"
11
+ questions_file = "/home/ps/Downloads/datasets/micbench/micbench_{}.json"
12
+ answers_file = "/home/ps/Downloads/InternLM-XComposer/q-bench2-xcomposer2-micbench-{}.jsonl"
13
+
14
+ split = "test"
15
+
16
+ import json
17
+ from ast import literal_eval
18
+ from PIL import Image
19
+ import numpy as np
20
+ from tqdm import tqdm
21
+
22
+
23
+ with open(questions_file.format(split)) as f:
24
+ if questions_file.endswith("json"):
25
+ llvqa_data = json.load(f)
26
+ else:
27
+ llvqa_data = [literal_eval(line) for line in f.readlines()]
28
+ print(llvqa_data[0])
29
+
30
+ model = model.eval()
31
+
32
+ correct_ = np.zeros((3,4))
33
+ all_ = np.zeros((3,4))
34
+
35
+ correct= 0
36
+
37
+ pbar = tqdm(total=len(llvqa_data))
38
+
39
+ for i, llddata in enumerate(llvqa_data):
40
+ img_path_list = llddata["img_path"]
41
+ if len(img_path_list) > 3:
42
+ pbar.update(1)
43
+ continue
44
+ images = []
45
+ for img_path in img_path_list:
46
+ image = Image.open(image_folder+img_path).convert("RGB")
47
+ image = model.vis_processor(image)
48
+ images.append(image)
49
+ image = torch.stack(images)
50
+ options_prompt = ''
51
+ for choice, ans in zip(["A.", "B.", "C.", "D."], llddata["candidates"]):
52
+ options_prompt += f"{choice} {ans}\n"
53
+ if ans == llddata["correct_ans"]:
54
+ llddata["correct_choice"] = choice[0]
55
+ query = '<ImageHere> '*len(img_path_list) + 'Please answer this question by choosing the correct choice.'
56
+ query += "Context: N/A\nQuestion: " + llddata["question"] + '\nOptions: ' + options_prompt
57
+ print(img_path_list, query)
58
+ with torch.no_grad():
59
+ with torch.cuda.amp.autocast():
60
+ response, history = model.chat(tokenizer, query=query, image=image, history=[], do_sample=False, max_new_tokens=6)
61
+ outputs = response.replace("The answer is ", "")
62
+ if llddata["correct_choice"] in outputs:
63
+ correct += 1
64
+ #correct_[llddata["type"]][llddata["concern"]]+= 1
65
+ #all_[llddata["type"]][llddata["concern"]]+= 1
66
+
67
+ with open(answers_file.format(split), "a") as wf:
68
+ json.dump(llddata, wf)
69
+
70
+ pbar.update(1)
71
+ pbar.set_description("[Running Accuracy]: {:.4f},[Response]: {}, [Correct Ans]: {}, , [Prog]: {}".format(correct/(i+1), outputs, llddata.get("correct_choice", -1), i+1))