Jamari commited on
Commit
b89b366
·
verified ·
1 Parent(s): 410680e

current file used to run the benchmark (returns a json you pass to assess.py)

Browse files
Files changed (1) hide show
  1. run.py +143 -0
run.py ADDED
@@ -0,0 +1,143 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers import AutoModelForCausalLM, AutoProcessor, GenerationConfig
2
+ from PIL import Image
3
+ import requests
4
+ import torch
5
+ import json
6
+ import re
7
+ import os
8
+ from torch.nn.utils.rnn import pad_sequence
9
+ from datasets import load_dataset
10
+ import re
11
+
12
+
13
+ dataset = load_dataset('moondream/analog-clock-benchmark', split='test', streaming=True)
14
+
15
+
16
+ result_location = './molmo-answers.json'
17
+ model_path = 'moondream/Molmo-72B-0924'
18
+ processor = AutoProcessor.from_pretrained(
19
+ model_path,
20
+ trust_remote_code=True,
21
+ torch_dtype='auto',
22
+ device_map='auto'
23
+ )
24
+
25
+ model = AutoModelForCausalLM.from_pretrained(
26
+ model_path,
27
+ trust_remote_code=True,
28
+ torch_dtype='auto',
29
+ device_map='auto'
30
+ )
31
+
32
+ def extract_points_and_text(input_string):
33
+ # match the points attributes with single or double quotes
34
+ points_pattern = r'(?:x|y)(\d*)=["\']?([\d.]+)["\']?'
35
+
36
+ matches = re.findall(points_pattern, input_string)
37
+
38
+ # Group matches by their index (or empty string if no index)
39
+ point_dict = {}
40
+ for index, value in matches:
41
+ point_dict.setdefault(index, []).append(float(value))
42
+
43
+ # Convert matches to the desired format
44
+ points = [point for point in point_dict.values() if len(point) == 2]
45
+
46
+ text_pattern = r'<(?:point|points)[^>]*>(.*?)</(?:point|points)>'
47
+ text_match = re.search(text_pattern, input_string)
48
+ text = text_match.group(1) if text_match else ""
49
+
50
+ cleaned_string = re.sub(text_pattern, text, input_string)
51
+
52
+ # Find all integers in the cleaned string
53
+ answers = [int(num) for num in re.findall(r'\b\d+\b', cleaned_string)]
54
+
55
+ result = {
56
+ "points": points,
57
+ "cleaned_string": cleaned_string,
58
+ "answers": answers
59
+ }
60
+
61
+ return result
62
+
63
+ def do_inference(image, text):
64
+ inputs = processor.process(
65
+ images=[image],
66
+ text=text
67
+ )
68
+
69
+ # move inputs to the correct device and make a batch of size 1
70
+ inputs = {k: v.to(model.device).unsqueeze(0) for k, v in inputs.items()}
71
+
72
+ # generate output; maximum 200 new tokens; stop generation when <|endoftext|> is generated
73
+ inputs["images"] = inputs["images"].to(torch.float16)
74
+ output = model.generate_from_batch(
75
+ inputs,
76
+ GenerationConfig(max_new_tokens=200, stop_strings="<|endoftext|>", attention_type='flash'),
77
+ tokenizer=processor.tokenizer
78
+ )
79
+
80
+ # only get generated tokens; decode them to text
81
+ generated_tokens = output[0,inputs['input_ids'].size(1):]
82
+ generated_text = processor.tokenizer.decode(generated_tokens, skip_special_tokens=True)
83
+
84
+ return generated_text
85
+
86
+ # cleaned_obj = extract_points_and_text(generated_text)
87
+
88
+ # return cleaned_obj
89
+
90
+
91
+
92
+ # create results file if it doesn't exist
93
+ if not os.path.exists(result_location):
94
+ os.makedirs(os.path.dirname(result_location), exist_ok=True)
95
+ with open(result_location, 'w') as file:
96
+ json.dump([], file)
97
+
98
+ def has_one_clock(image):
99
+ molmo_res_text = do_inference(image, 'How many clocks are in this image?')
100
+ print('Clock count -> ', molmo_res_text)
101
+
102
+ if molmo_res_text.strip().endswith("1.") and molmo_res_text.strip().startswith(" Counting the"):
103
+ return True
104
+ else:
105
+ return False
106
+
107
+
108
+ def get_time(image):
109
+ return do_inference(image, '''Look at this image with a readable clock and do the following:
110
+ 1. Report the hour hand location
111
+ 2. Report the minute hand location
112
+ 3. Report the time based on these locations''')
113
+
114
+
115
+
116
+
117
+
118
+ # Create progress bar
119
+ datapoint_index = 0
120
+ for datapoint in dataset:
121
+ molmo_time_string = get_time(datapoint['image'])
122
+ print(molmo_time_string)
123
+ print('\n\n\n\n\n')
124
+
125
+ #skip if the string is empty or function returned false (molmo could not tell the time)
126
+
127
+ # Check if molmo_time_string contains exactly one time formatted as HH:MM
128
+ time_pattern = r'\b\d{1,2}:\d{2}\b'
129
+ times_found = re.findall(time_pattern, molmo_time_string)
130
+
131
+ if len(times_found) == 1 and times_found[0] != "10:10":
132
+ obj_to_save = {
133
+ 'datapoint_index': datapoint_index,
134
+ 'correct_answer': molmo_time_string,
135
+ 'reported_times': times_found,
136
+ 'llm_string': molmo_time_string
137
+ }
138
+ with open(result_location, 'r+') as file:
139
+ data = json.load(file)
140
+ data.append(obj_to_save)
141
+ file.seek(0)
142
+ json.dump(data, file, indent=4)
143
+ file.truncate()