DingZhenDojoCat commited on
Commit
e76659b
·
verified ·
1 Parent(s): 5d1b6bb

Add files using upload-large-folder tool

Browse files
Files changed (50) hide show
  1. analyze_accuracy.ipynb +1015 -0
  2. evaluate_single.py +77 -0
  3. find_caption_errors.ipynb +0 -0
  4. gemini_key.json +13 -0
  5. generate_answer.py +324 -0
  6. qwen_caption_cot.py +190 -0
  7. sft_description.json +0 -0
  8. sft_description/1182.jpg +0 -0
  9. sft_description/1332.jpg +0 -0
  10. sft_description/1389.png +0 -0
  11. sft_description/1402.jpg +0 -0
  12. sft_description/1473.jpg +0 -0
  13. sft_description/1571.jpg +0 -0
  14. sft_description/167.jpg +0 -0
  15. sft_description/1739.jpg +0 -0
  16. sft_description/1797.jpg +0 -0
  17. sft_description/249.jpg +0 -0
  18. sft_description/2513.jpg +0 -0
  19. sft_description/2539.jpg +0 -0
  20. sft_description/2543.jpg +0 -0
  21. sft_description/2739.jpg +0 -0
  22. sft_description/2811.jpg +0 -0
  23. sft_description/3009.jpg +0 -0
  24. sft_description/3052.jpg +0 -0
  25. sft_description/307.jpg +0 -0
  26. sft_description/3123.jpg +0 -0
  27. sft_description/3191.jpg +0 -0
  28. sft_description/3218.jpg +0 -0
  29. sft_description/3239.jpg +0 -0
  30. sft_description/3327.jpg +0 -0
  31. sft_description/3341.jpg +0 -0
  32. sft_description/3395.jpg +0 -0
  33. sft_description/3500.jpg +0 -0
  34. sft_description/3725.jpg +0 -0
  35. sft_description/3737.jpg +0 -0
  36. sft_description/3960.jpg +0 -0
  37. sft_description/4058.jpg +0 -0
  38. sft_description/4144.jpg +0 -0
  39. sft_description/4200.jpg +0 -0
  40. sft_description/4384.jpg +0 -0
  41. sft_description/4433.jpg +0 -0
  42. sft_description/4484.png +0 -0
  43. sft_description/4608.jpg +0 -0
  44. sft_description/4788.jpg +0 -0
  45. sft_description/4843.png +0 -0
  46. sft_description/4936.jpg +0 -0
  47. sft_description/617.jpg +0 -0
  48. sft_description/742.jpg +0 -0
  49. sft_description/83.jpg +0 -0
  50. sft_description/869.jpg +0 -0
analyze_accuracy.ipynb ADDED
@@ -0,0 +1,1015 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "execution_count": 8,
6
+ "id": "89f2b537",
7
+ "metadata": {},
8
+ "outputs": [],
9
+ "source": [
10
+ "import re\n",
11
+ "from typing import Dict, List, Optional\n",
12
+ "from mathruler.grader import extract_boxed_content, grade_answer\n"
13
+ ]
14
+ },
15
+ {
16
+ "cell_type": "code",
17
+ "execution_count": 9,
18
+ "id": "8590ec56",
19
+ "metadata": {},
20
+ "outputs": [],
21
+ "source": [
22
+ "import json\n",
23
+ "from pathlib import Path\n",
24
+ "from typing import List, Dict, Union\n",
25
+ "from typing import Dict, List, Any\n",
26
+ "import re\n",
27
+ "from typing import List\n",
28
+ "\n",
29
+ "def read_json(path: Union[str, Path]) -> List[Dict]:\n",
30
+ " \"\"\"\n",
31
+ " Read a JSON file and return its contents as a list of dicts.\n",
32
+ "\n",
33
+ " Parameters\n",
34
+ " ----------\n",
35
+ " path : str or Path\n",
36
+ " Path to a JSON file whose root is a JSON array.\n",
37
+ "\n",
38
+ " Returns\n",
39
+ " -------\n",
40
+ " List[Dict]\n",
41
+ " Each element of the top-level JSON array, parsed into a Python dict.\n",
42
+ "\n",
43
+ " Raises\n",
44
+ " ------\n",
45
+ " ValueError\n",
46
+ " If the JSON root is not a list.\n",
47
+ " json.JSONDecodeError\n",
48
+ " If the file is not valid JSON.\n",
49
+ " \"\"\"\n",
50
+ " path = Path(path).expanduser()\n",
51
+ "\n",
52
+ " with path.open(\"r\", encoding=\"utf-8\") as f:\n",
53
+ " data = json.load(f)\n",
54
+ "\n",
55
+ " if not isinstance(data, list):\n",
56
+ " raise ValueError(f\"{path} does not contain a JSON array at the top level.\")\n",
57
+ "\n",
58
+ " # (Optional) sanity-check that every item is a dict\n",
59
+ " if not all(isinstance(item, dict) for item in data):\n",
60
+ " raise ValueError(\"Not every element in the JSON array is an object.\")\n",
61
+ "\n",
62
+ " return data\n",
63
+ "\n",
64
+ "\n",
65
+ "def extract_description(predict: str) -> Optional[str]:\n",
66
+ " \"\"\"\n",
67
+ " Extracts the content of the <answer>…</answer> block from `predict`.\n",
68
+ " Returns the inner text (with leading/trailing whitespace stripped),\n",
69
+ " or None if no <answer> tag is found.\n",
70
+ " \"\"\"\n",
71
+ " match = re.search(r\"<description>([\\s\\S]*?)</description>\", predict, re.DOTALL)\n",
72
+ " if not match:\n",
73
+ " return None\n",
74
+ " return match.group(1).strip()\n",
75
+ "\n",
76
+ "\n",
77
+ "def accuracy_reward(predict: str, ground_truth: str) -> float:\n",
78
+ " answer = extract_boxed_content(predict)\n",
79
+ " # answer = extract_answer(predict)\n",
80
+ " return 1.0 if grade_answer(answer, ground_truth) else 0.0"
81
+ ]
82
+ },
83
+ {
84
+ "cell_type": "code",
85
+ "execution_count": 10,
86
+ "id": "9fb984e7",
87
+ "metadata": {},
88
+ "outputs": [],
89
+ "source": [
90
+ "def load_json_dir(root: str | Path, *, verbose: bool = True) -> Dict[str, List[Any]]:\n",
91
+ " \"\"\"\n",
92
+ " Traverse *root* recursively and return {file_stem: parsed_json_data}.\n",
93
+ "\n",
94
+ " • Files that are empty or contain invalid JSON are skipped with a warning.\n",
95
+ " Set verbose=False to silence the warnings.\n",
96
+ " \"\"\"\n",
97
+ " root = Path(root).expanduser().resolve()\n",
98
+ " out: Dict[str, List[Any]] = {}\n",
99
+ "\n",
100
+ " for path in root.rglob(\"*.json\"):\n",
101
+ " try:\n",
102
+ " with path.open(\"r\", encoding=\"utf-8\") as f:\n",
103
+ " data = json.load(f)\n",
104
+ " out[path.stem] = data\n",
105
+ " except json.JSONDecodeError as err:\n",
106
+ " if verbose:\n",
107
+ " print(f\"[skip] {path} – invalid JSON ({err})\")\n",
108
+ " except Exception as err:\n",
109
+ " if verbose:\n",
110
+ " print(f\"[skip] {path} – {err}\")\n",
111
+ "\n",
112
+ " return out"
113
+ ]
114
+ },
115
+ {
116
+ "cell_type": "code",
117
+ "execution_count": 4,
118
+ "id": "c8e29fcb",
119
+ "metadata": {},
120
+ "outputs": [],
121
+ "source": [
122
+ "# folder_dir = './gemini-flash'\n",
123
+ "folder_dir = './gemini-pro'\n",
124
+ "# folder_dir = './gemini-pro-pro'"
125
+ ]
126
+ },
127
+ {
128
+ "cell_type": "code",
129
+ "execution_count": 5,
130
+ "id": "fad0547b",
131
+ "metadata": {},
132
+ "outputs": [
133
+ {
134
+ "data": {
135
+ "text/plain": [
136
+ "dict_keys(['realWorldQA', 'clevr_count_70k', 'mmmu-pro', 'mathvision', 'mmstar', 'mmmu-pro-vision', 'mm-vet', 'mmmu_pro_10options', 'mathvista', 'visnumbench'])"
137
+ ]
138
+ },
139
+ "execution_count": 5,
140
+ "metadata": {},
141
+ "output_type": "execute_result"
142
+ }
143
+ ],
144
+ "source": [
145
+ "datas = load_json_dir(folder_dir)\n",
146
+ "\n",
147
+ "datas.keys()"
148
+ ]
149
+ },
150
+ {
151
+ "cell_type": "code",
152
+ "execution_count": 6,
153
+ "id": "e74dd8dd",
154
+ "metadata": {},
155
+ "outputs": [
156
+ {
157
+ "name": "stdout",
158
+ "output_type": "stream",
159
+ "text": [
160
+ "realWorldQA: 0.6862745098039216\n",
161
+ "clevr_count_70k: 0.7108571428571429\n",
162
+ "mmmu-pro: 0.6105527638190955\n",
163
+ "mathvision: 0.36875\n",
164
+ "mmstar: 0.6633333333333333\n",
165
+ "mmmu-pro-vision: 0.5256410256410257\n",
166
+ "mm-vet: 0.3302752293577982\n",
167
+ "mmmu_pro_10options: 0.49243379571248425\n",
168
+ "mathvista: 0.554\n",
169
+ "visnumbench: 0.28835978835978837\n"
170
+ ]
171
+ }
172
+ ],
173
+ "source": [
174
+ "indices = {}\n",
175
+ "\n",
176
+ "for file, answers in datas.items():\n",
177
+ " indices[file]=[]\n",
178
+ " acc = 0\n",
179
+ " for index, ele in enumerate(answers):\n",
180
+ " solution = ele['solution']\n",
181
+ " prediction = ele['predictions'][0]\n",
182
+ " accuracy = accuracy_reward(prediction, solution)\n",
183
+ " acc += accuracy\n",
184
+ " \n",
185
+ " if accuracy == 1:\n",
186
+ " indices[file].append(index)\n",
187
+ " \n",
188
+ " print(f'{file}: {acc/len(answers)}')"
189
+ ]
190
+ },
191
+ {
192
+ "cell_type": "code",
193
+ "execution_count": 7,
194
+ "id": "99761358",
195
+ "metadata": {},
196
+ "outputs": [
197
+ {
198
+ "ename": "KeyError",
199
+ "evalue": "'MLLM_rlvr_train'",
200
+ "output_type": "error",
201
+ "traceback": [
202
+ "\u001b[31m---------------------------------------------------------------------------\u001b[39m",
203
+ "\u001b[31mKeyError\u001b[39m Traceback (most recent call last)",
204
+ "\u001b[36mCell\u001b[39m\u001b[36m \u001b[39m\u001b[32mIn[7]\u001b[39m\u001b[32m, line 1\u001b[39m\n\u001b[32m----> \u001b[39m\u001b[32m1\u001b[39m \u001b[38;5;28mlen\u001b[39m(\u001b[43mdatas\u001b[49m\u001b[43m[\u001b[49m\u001b[33;43m'\u001b[39;49m\u001b[33;43mMLLM_rlvr_train\u001b[39;49m\u001b[33;43m'\u001b[39;49m\u001b[43m]\u001b[49m)\n",
205
+ "\u001b[31mKeyError\u001b[39m: 'MLLM_rlvr_train'"
206
+ ]
207
+ }
208
+ ],
209
+ "source": [
210
+ "len(datas['MLLM_rlvr_train'])"
211
+ ]
212
+ },
213
+ {
214
+ "cell_type": "code",
215
+ "execution_count": 8,
216
+ "id": "cb380a0c",
217
+ "metadata": {},
218
+ "outputs": [
219
+ {
220
+ "data": {
221
+ "text/plain": [
222
+ "dict_keys(['realWorldQA', 'MLLM_hotpot_train', 'mmmu-pro', 'mmstar', 'mm-vet', 'mathvista'])"
223
+ ]
224
+ },
225
+ "execution_count": 8,
226
+ "metadata": {},
227
+ "output_type": "execute_result"
228
+ }
229
+ ],
230
+ "source": [
231
+ "indices.keys()"
232
+ ]
233
+ },
234
+ {
235
+ "cell_type": "code",
236
+ "execution_count": null,
237
+ "id": "9367bc67",
238
+ "metadata": {},
239
+ "outputs": [],
240
+ "source": [
241
+ "realWorldQA: 0.6972477064220184\n",
242
+ "mmmu-pro: 0.5646606914212549\n",
243
+ "mmstar: 0.6061433447098976\n",
244
+ "mm-vet: 0.6018518518518519\n",
245
+ "mathvista: 0.5822401614530777"
246
+ ]
247
+ },
248
+ {
249
+ "cell_type": "code",
250
+ "execution_count": null,
251
+ "id": "08286602",
252
+ "metadata": {},
253
+ "outputs": [],
254
+ "source": []
255
+ },
256
+ {
257
+ "cell_type": "code",
258
+ "execution_count": null,
259
+ "id": "d033bd06",
260
+ "metadata": {},
261
+ "outputs": [],
262
+ "source": []
263
+ },
264
+ {
265
+ "cell_type": "code",
266
+ "execution_count": null,
267
+ "id": "8f7a73e5",
268
+ "metadata": {},
269
+ "outputs": [],
270
+ "source": []
271
+ },
272
+ {
273
+ "cell_type": "markdown",
274
+ "id": "84f260ed",
275
+ "metadata": {},
276
+ "source": [
277
+ "# Construct indices to merge datasets"
278
+ ]
279
+ },
280
+ {
281
+ "cell_type": "code",
282
+ "execution_count": 8,
283
+ "id": "6c771d63",
284
+ "metadata": {},
285
+ "outputs": [],
286
+ "source": [
287
+ "description_folder_dir = './gpt_o1_outputs'\n",
288
+ "description_outputs = load_json_dir(description_folder_dir)"
289
+ ]
290
+ },
291
+ {
292
+ "cell_type": "code",
293
+ "execution_count": 9,
294
+ "id": "d8e03bf5",
295
+ "metadata": {},
296
+ "outputs": [
297
+ {
298
+ "name": "stdout",
299
+ "output_type": "stream",
300
+ "text": [
301
+ "891\n",
302
+ "2694\n"
303
+ ]
304
+ }
305
+ ],
306
+ "source": [
307
+ "file = 'mathvision'\n",
308
+ "print(len(description_outputs[file]))\n",
309
+ "print(len(datas[file]))"
310
+ ]
311
+ },
312
+ {
313
+ "cell_type": "code",
314
+ "execution_count": 11,
315
+ "id": "6a814cba",
316
+ "metadata": {},
317
+ "outputs": [],
318
+ "source": [
319
+ "# idx = 1200\n",
320
+ "# print(description_outputs[file][idx])\n",
321
+ "# print('-'*10)\n",
322
+ "# print(datas[file][idx])"
323
+ ]
324
+ },
325
+ {
326
+ "cell_type": "code",
327
+ "execution_count": 12,
328
+ "id": "7c08cff1",
329
+ "metadata": {},
330
+ "outputs": [
331
+ {
332
+ "data": {
333
+ "text/plain": [
334
+ "{'index': 0,\n",
335
+ " 'problem': 'Are there any states with a number of reporters between 376-385? Options:\\nA. No\\nB. Yes',\n",
336
+ " 'solution': 'B',\n",
337
+ " 'predictions': ['<think> The task is to determine if there are any states with a number of reporters between 376-385. The map shows states in two different colors corresponding to two ranges of reporters: 373-375 and 376-385. I need to identify states in the color representing the range 376-385.\\n\\nThe legend indicates two colors:\\n- A lighter color for the range 373-375.\\n- A darker color for the range 376-385.\\n\\nI will look at the map to identify states shaded with the darker color. The states shaded in the darker color are:\\n- California\\n- North Dakota\\n- South Dakota\\n- Iowa\\n- Missouri\\n- Illinois\\n- Kentucky\\n- West Virginia\\n- New Jersey\\n- Massachusetts\\n\\nThese states are not in the lighter color range, hence they must have a number of reporters between 376-385. Therefore, there are indeed states with a number of reporters in the range 376-385.\\n\\nThe correct option is B. Yes, because there are several states shaded in the darker color that indicates the range 376-385. </think> \\\\boxed{B}']}"
338
+ ]
339
+ },
340
+ "execution_count": 12,
341
+ "metadata": {},
342
+ "output_type": "execute_result"
343
+ }
344
+ ],
345
+ "source": [
346
+ "datas['MLLM_hotpot_train'][0]"
347
+ ]
348
+ },
349
+ {
350
+ "cell_type": "code",
351
+ "execution_count": 11,
352
+ "id": "c3e8619a",
353
+ "metadata": {},
354
+ "outputs": [
355
+ {
356
+ "name": "stdout",
357
+ "output_type": "stream",
358
+ "text": [
359
+ "MLLM_hotpot_train: 0.2949054259284827; dataset len: 14486\n",
360
+ "mathverse: 0.18071065989847715; dataset len: 3940\n"
361
+ ]
362
+ }
363
+ ],
364
+ "source": [
365
+ "indices = {}\n",
366
+ "\n",
367
+ "for file, answers in datas.items():\n",
368
+ " # try:\n",
369
+ " indices[file]=[]\n",
370
+ " # description_data = description_outputs[file]\n",
371
+ " acc = 0\n",
372
+ " for i, ele in enumerate(answers):\n",
373
+ " solution = ele['solution']\n",
374
+ " prediction = ele['predictions'][0]\n",
375
+ " datas_index = ele['index']\n",
376
+ " \n",
377
+ " # print(description)\n",
378
+ " # break\n",
379
+ " accuracy = accuracy_reward(prediction, solution)\n",
380
+ " # acc += accuracy\n",
381
+ " \n",
382
+ " if accuracy == 1:\n",
383
+ " # if description is not None:\n",
384
+ " indices[file].append(datas_index)\n",
385
+ " acc += accuracy\n",
386
+ " \n",
387
+ " print(f'{file}: {acc/len(answers)}; dataset len: {len(answers)}')\n",
388
+ " # except Exception as e:\n",
389
+ " # print(f\"Exception caught: {e} for file: {file}\")"
390
+ ]
391
+ },
392
+ {
393
+ "cell_type": "code",
394
+ "execution_count": 12,
395
+ "id": "ca869a96",
396
+ "metadata": {},
397
+ "outputs": [
398
+ {
399
+ "name": "stdout",
400
+ "output_type": "stream",
401
+ "text": [
402
+ "Exception caught: name 'description_outputs' is not defined for file: MLLM_hotpot_train\n",
403
+ "Exception caught: name 'description_outputs' is not defined for file: mathverse\n"
404
+ ]
405
+ }
406
+ ],
407
+ "source": [
408
+ "indices = {}\n",
409
+ "texts = {}\n",
410
+ "for file, answers in datas.items():\n",
411
+ " try:\n",
412
+ " indices[file]=[]\n",
413
+ " texts[file] = []\n",
414
+ " description_data = description_outputs[file]\n",
415
+ " # ---------- 1) make a hash‑map: index -> description item ----------\n",
416
+ " desc_by_idx = {item[\"index\"]: item for item in description_data}\n",
417
+ " \n",
418
+ " acc = 0\n",
419
+ " for i, ele in enumerate(answers):\n",
420
+ " solution = ele['solution']\n",
421
+ " prediction = ele['predictions'][0]\n",
422
+ " data_idx = ele[\"index\"] # the index in the answers item\n",
423
+ " \n",
424
+ " try:\n",
425
+ " desc_item = desc_by_idx.get(data_idx)\n",
426
+ " extracted_description = extract_description(desc_item['predictions'][0])\n",
427
+ " except:\n",
428
+ " extracted_description = None\n",
429
+ "\n",
430
+ " # print(description)\n",
431
+ " # break\n",
432
+ " accuracy = accuracy_reward(prediction, solution)\n",
433
+ " # acc += accuracy \n",
434
+ " \n",
435
+ " # print('data: ', description_data)\n",
436
+ " # print('-'*10)\n",
437
+ " # print('data1: ', ele)\n",
438
+ " # break\n",
439
+ " \n",
440
+ " \n",
441
+ " if accuracy == 1:\n",
442
+ " if extracted_description is not None:\n",
443
+ " indices[file].append(data_idx)\n",
444
+ " curr_text = '<description>\\n' + extracted_description + '/n</description>' + prediction\n",
445
+ " texts[file].append(curr_text) \n",
446
+ " \n",
447
+ " acc += accuracy\n",
448
+ " \n",
449
+ " print(f'{file}: {acc/len(answers)}; dataset len: {len(answers)}')\n",
450
+ " except Exception as e:\n",
451
+ " print(f\"Exception caught: {e} for file: {file}\")"
452
+ ]
453
+ },
454
+ {
455
+ "cell_type": "code",
456
+ "execution_count": 15,
457
+ "id": "2d3594e0",
458
+ "metadata": {},
459
+ "outputs": [],
460
+ "source": [
461
+ "indices_by_dataset = indices"
462
+ ]
463
+ },
464
+ {
465
+ "cell_type": "code",
466
+ "execution_count": 16,
467
+ "id": "4b0a1872",
468
+ "metadata": {},
469
+ "outputs": [
470
+ {
471
+ "name": "stdout",
472
+ "output_type": "stream",
473
+ "text": [
474
+ "K: realWorldQA; V len: 514\n",
475
+ "K: MLLM_hotpot_train; V len: 0\n",
476
+ "K: mmmu-pro; V len: 389\n",
477
+ "K: mathvision; V len: 328\n",
478
+ "K: mmstar; V len: 512\n",
479
+ "K: mm-vet; V len: 65\n",
480
+ "K: mathvista; V len: 457\n"
481
+ ]
482
+ },
483
+ {
484
+ "data": {
485
+ "text/plain": [
486
+ "2265"
487
+ ]
488
+ },
489
+ "execution_count": 16,
490
+ "metadata": {},
491
+ "output_type": "execute_result"
492
+ }
493
+ ],
494
+ "source": [
495
+ "total = 0\n",
496
+ "for k, v in indices_by_dataset.items():\n",
497
+ " print(f'K: {k}; V len: {len(v)}')\n",
498
+ " total += len(v)\n",
499
+ " \n",
500
+ "total"
501
+ ]
502
+ },
503
+ {
504
+ "cell_type": "markdown",
505
+ "id": "4dba6e3c",
506
+ "metadata": {},
507
+ "source": [
508
+ "### Add it for MLLM hotpot train"
509
+ ]
510
+ },
511
+ {
512
+ "cell_type": "code",
513
+ "execution_count": 13,
514
+ "id": "5d453890",
515
+ "metadata": {},
516
+ "outputs": [
517
+ {
518
+ "name": "stdout",
519
+ "output_type": "stream",
520
+ "text": [
521
+ "[skip] /apdcephfs_cq11/share_1603164/user/zongxia/workspace/C-gemini-answers/gemini-flash/clevr_count_70k.json – invalid JSON (Expecting value: line 1 column 1 (char 0))\n",
522
+ "14486\n",
523
+ "MLLM_hotpot_train: 0.2949054259284827; dataset len: 14486\n",
524
+ "3940\n",
525
+ "mathverse: 0.18071065989847715; dataset len: 3940\n"
526
+ ]
527
+ },
528
+ {
529
+ "data": {
530
+ "text/plain": [
531
+ "4272"
532
+ ]
533
+ },
534
+ "execution_count": 13,
535
+ "metadata": {},
536
+ "output_type": "execute_result"
537
+ }
538
+ ],
539
+ "source": [
540
+ "indices = {}\n",
541
+ "\n",
542
+ "hotpot_description_folder_dir = './gemini-flash'\n",
543
+ "hotpot_description_outs = load_json_dir(hotpot_description_folder_dir)\n",
544
+ "\n",
545
+ "for file, answers in hotpot_description_outs.items():\n",
546
+ " try:\n",
547
+ " print(len(answers))\n",
548
+ " indices[file]=[]\n",
549
+ " texts[file] = []\n",
550
+ " acc = 0\n",
551
+ " for i, ele in enumerate(answers):\n",
552
+ " solution = ele['solution']\n",
553
+ " prediction = ele['predictions'][0]\n",
554
+ " datas_index = ele['index']\n",
555
+ " \n",
556
+ " # print(description)\n",
557
+ " # break\n",
558
+ " accuracy = accuracy_reward(prediction, solution)\n",
559
+ " # acc += accuracy\n",
560
+ " \n",
561
+ " if accuracy == 1:\n",
562
+ " indices[file].append(datas_index)\n",
563
+ " texts[file].append(prediction)\n",
564
+ " acc += accuracy\n",
565
+ " \n",
566
+ " print(f'{file}: {acc/len(answers)}; dataset len: {len(answers)}')\n",
567
+ " except Exception as e:\n",
568
+ " print(f\"Exception caught: {e} for file: {file}\")\n",
569
+ "\n",
570
+ "len(indices['MLLM_hotpot_train'])"
571
+ ]
572
+ },
573
+ {
574
+ "cell_type": "code",
575
+ "execution_count": 14,
576
+ "id": "8f4fe74e",
577
+ "metadata": {},
578
+ "outputs": [
579
+ {
580
+ "name": "stdout",
581
+ "output_type": "stream",
582
+ "text": [
583
+ "len(idxs) = 14486 min = 0 max = 14485\n",
584
+ "missing count : 0\n",
585
+ "first 20 gaps : []\n"
586
+ ]
587
+ }
588
+ ],
589
+ "source": [
590
+ "idxs = [ele['index'] for ele in hotpot_description_outs['MLLM_hotpot_train']]\n",
591
+ "\n",
592
+ "\n",
593
+ "print(\"len(idxs) =\", len(idxs), \" min =\", min(idxs), \" max =\", max(idxs))\n",
594
+ "# → len(idxs) == 6105, min == 0 (maybe), max == 6463\n",
595
+ "\n",
596
+ "# 2) find every number that *should* be there but isn’t\n",
597
+ "expected = set(range(min(idxs), max(idxs) + 1)) # full consecutive range\n",
598
+ "missing = sorted(expected - set(idxs))\n",
599
+ "\n",
600
+ "print(\"missing count :\", len(missing))\n",
601
+ "print(\"first 20 gaps :\", missing[:20])"
602
+ ]
603
+ },
604
+ {
605
+ "cell_type": "code",
606
+ "execution_count": 15,
607
+ "id": "411dcfc7",
608
+ "metadata": {},
609
+ "outputs": [],
610
+ "source": [
611
+ "indices_by_dataset = indices"
612
+ ]
613
+ },
614
+ {
615
+ "cell_type": "code",
616
+ "execution_count": 16,
617
+ "id": "ce4cea20",
618
+ "metadata": {},
619
+ "outputs": [
620
+ {
621
+ "name": "stdout",
622
+ "output_type": "stream",
623
+ "text": [
624
+ "dict_keys(['MLLM_hotpot_train', 'mathverse'])\n",
625
+ "dict_keys(['MLLM_hotpot_train', 'mathverse'])\n"
626
+ ]
627
+ }
628
+ ],
629
+ "source": [
630
+ "print(indices_by_dataset.keys())\n",
631
+ "print(texts.keys())"
632
+ ]
633
+ },
634
+ {
635
+ "cell_type": "code",
636
+ "execution_count": 17,
637
+ "id": "2a3ea275",
638
+ "metadata": {},
639
+ "outputs": [
640
+ {
641
+ "data": {
642
+ "text/plain": [
643
+ "4272"
644
+ ]
645
+ },
646
+ "execution_count": 17,
647
+ "metadata": {},
648
+ "output_type": "execute_result"
649
+ }
650
+ ],
651
+ "source": [
652
+ "len(indices_by_dataset['MLLM_hotpot_train'])"
653
+ ]
654
+ },
655
+ {
656
+ "cell_type": "code",
657
+ "execution_count": 18,
658
+ "id": "08197397",
659
+ "metadata": {},
660
+ "outputs": [
661
+ {
662
+ "data": {
663
+ "text/plain": [
664
+ "[14471, 14473, 14474, 14476, 14477, 14478, 14480, 14481, 14484, 14485]"
665
+ ]
666
+ },
667
+ "execution_count": 18,
668
+ "metadata": {},
669
+ "output_type": "execute_result"
670
+ }
671
+ ],
672
+ "source": [
673
+ "indices_by_dataset['MLLM_hotpot_train'][-10:]"
674
+ ]
675
+ },
676
+ {
677
+ "cell_type": "code",
678
+ "execution_count": 19,
679
+ "id": "bd2b91ff",
680
+ "metadata": {},
681
+ "outputs": [
682
+ {
683
+ "name": "stderr",
684
+ "output_type": "stream",
685
+ "text": [
686
+ "/usr/local/lib/python3.11/site-packages/tqdm/auto.py:21: TqdmWarning: IProgress not found. Please update jupyter and ipywidgets. See https://ipywidgets.readthedocs.io/en/stable/user_install.html\n",
687
+ " from .autonotebook import tqdm as notebook_tqdm\n"
688
+ ]
689
+ },
690
+ {
691
+ "name": "stdout",
692
+ "output_type": "stream",
693
+ "text": [
694
+ "filename: zli12321/MLLM_hotpot_train\n"
695
+ ]
696
+ },
697
+ {
698
+ "name": "stderr",
699
+ "output_type": "stream",
700
+ "text": [
701
+ "Flattening the indices: 100%|██████████| 4272/4272 [00:03<00:00, 1282.44 examples/s]\n"
702
+ ]
703
+ },
704
+ {
705
+ "name": "stdout",
706
+ "output_type": "stream",
707
+ "text": [
708
+ "filename: zli12321/mathverse\n"
709
+ ]
710
+ },
711
+ {
712
+ "name": "stderr",
713
+ "output_type": "stream",
714
+ "text": [
715
+ "Generating test split: 3940 examples [00:00, 13229.68 examples/s]\n",
716
+ "Flattening the indices: 100%|██████████| 712/712 [00:00<00:00, 48814.82 examples/s]"
717
+ ]
718
+ },
719
+ {
720
+ "name": "stdout",
721
+ "output_type": "stream",
722
+ "text": [
723
+ "Dataset({\n",
724
+ " features: ['problem', 'answer', 'images', 'outputs'],\n",
725
+ " num_rows: 4984\n",
726
+ "})\n"
727
+ ]
728
+ },
729
+ {
730
+ "name": "stderr",
731
+ "output_type": "stream",
732
+ "text": [
733
+ "\n"
734
+ ]
735
+ }
736
+ ],
737
+ "source": [
738
+ "from datasets import load_dataset, concatenate_datasets\n",
739
+ "\n",
740
+ "BASE_REPO = \"zli12321/\" # prefix for every dataset id\n",
741
+ "kept_splits = []\n",
742
+ "\n",
743
+ "for short_name, keep in indices_by_dataset.items():\n",
744
+ " try:\n",
745
+ " if not keep: # nothing to keep → skip\n",
746
+ " continue\n",
747
+ "\n",
748
+ " # -----------------------------------------------------------------\n",
749
+ " # 1) ensure `keep` and its matching texts are sorted *together*\n",
750
+ " # -----------------------------------------------------------------\n",
751
+ " idxs = keep\n",
752
+ " outs = texts[short_name]\n",
753
+ "\n",
754
+ " # idxs and outs were built in parallel, so they are aligned.\n",
755
+ " # If you want the rows in ascending order, sort both lists together:\n",
756
+ " order = sorted(range(len(idxs)), key=idxs.__getitem__)\n",
757
+ " idxs = [idxs[i] for i in order] # sorted indices\n",
758
+ " outs = [outs[i] for i in order] # matching outputs\n",
759
+ "\n",
760
+ " # -----------------------------------------------------------------\n",
761
+ " # 2) load, slice, and keep only the three original columns\n",
762
+ " # -----------------------------------------------------------------\n",
763
+ " full_name = f\"{BASE_REPO}{short_name}\"\n",
764
+ " \n",
765
+ " print(f'filename: {full_name}')\n",
766
+ " split = \"train\" if \"MLLM_hotpot_train\" in short_name else \"test\"\n",
767
+ "\n",
768
+ " ds = load_dataset(full_name, split=split, trust_remote_code=True)\n",
769
+ " ds = ds.select(idxs) # keep only those rows\n",
770
+ " \n",
771
+ " # print(f'filename: {full_name}; len: {len(ds)}')\n",
772
+ "\n",
773
+ " cols_to_keep = {\"problem\", \"images\", \"answer\"}\n",
774
+ " ds = ds.remove_columns([c for c in ds.column_names if c not in cols_to_keep])\n",
775
+ "\n",
776
+ " # -----------------------------------------------------------------\n",
777
+ " # 3) add the new column\n",
778
+ " # -----------------------------------------------------------------\n",
779
+ " ds = ds.add_column(\"outputs\", outs) # len(outs) == len(ds)\n",
780
+ "\n",
781
+ " kept_splits.append(ds)\n",
782
+ " except Exception as e:\n",
783
+ " print(f\"dataset len: {len(ds)}\")\n",
784
+ " print(f'{short_name} Failed: {e}')\n",
785
+ "\n",
786
+ "# ---------------------------------------------------------------------\n",
787
+ "# 4) concatenate everything into one big dataset\n",
788
+ "# ---------------------------------------------------------------------\n",
789
+ "combined = concatenate_datasets(kept_splits)\n",
790
+ "\n",
791
+ "print(combined) # verify\n",
792
+ "# combined.save_to_disk(\"combined.arrow\") # or .to_parquet(...)\n",
793
+ "\n"
794
+ ]
795
+ },
796
+ {
797
+ "cell_type": "code",
798
+ "execution_count": 29,
799
+ "id": "cb8bfe20",
800
+ "metadata": {},
801
+ "outputs": [
802
+ {
803
+ "name": "stderr",
804
+ "output_type": "stream",
805
+ "text": [
806
+ "Creating parquet from Arrow format: 100%|██████████| 39/39 [00:17<00:00, 2.18ba/s]\n"
807
+ ]
808
+ },
809
+ {
810
+ "data": {
811
+ "text/plain": [
812
+ "909006342"
813
+ ]
814
+ },
815
+ "execution_count": 29,
816
+ "metadata": {},
817
+ "output_type": "execute_result"
818
+ }
819
+ ],
820
+ "source": [
821
+ "combined.to_parquet(\"./hf_upload_train/train.parquet\")"
822
+ ]
823
+ },
824
+ {
825
+ "cell_type": "code",
826
+ "execution_count": 20,
827
+ "id": "5b7aed77",
828
+ "metadata": {},
829
+ "outputs": [],
830
+ "source": [
831
+ "def save_any_image(img_obj, out_base: Path) -> Path:\n",
832
+ " \"\"\"\n",
833
+ " Save *img_obj* (str | dict | PIL.Image) to disk.\n",
834
+ " Returns the *Path* actually written (possibly .png if alpha).\n",
835
+ " \"\"\"\n",
836
+ " import io, shutil\n",
837
+ " from PIL import Image\n",
838
+ "\n",
839
+ " # 1) resolve a PIL.Image ---------------------------------------------------\n",
840
+ " if isinstance(img_obj, str): # already a path\n",
841
+ " pil = Image.open(img_obj)\n",
842
+ "\n",
843
+ " elif isinstance(img_obj, dict): # HF Image feature\n",
844
+ " if img_obj.get(\"path\"):\n",
845
+ " pil = Image.open(img_obj[\"path\"])\n",
846
+ " else:\n",
847
+ " pil = Image.open(io.BytesIO(img_obj[\"bytes\"]))\n",
848
+ "\n",
849
+ " else: # PIL.Image.Image\n",
850
+ " pil = img_obj\n",
851
+ "\n",
852
+ " # 2) choose format & filename ---------------------------------------------\n",
853
+ " suffix = \".jpg\"\n",
854
+ " img_mode = pil.mode\n",
855
+ "\n",
856
+ " if img_mode in (\"RGBA\", \"LA\", \"P\"):\n",
857
+ " # keep alpha by switching to PNG (or call .convert(\"RGB\") to stay JPEG)\n",
858
+ " suffix = \".png\"\n",
859
+ "\n",
860
+ " out_path = out_base.with_suffix(suffix)\n",
861
+ "\n",
862
+ " # 3) convert if you insist on JPG without alpha\n",
863
+ " if suffix == \".jpg\" and img_mode != \"RGB\":\n",
864
+ " pil = pil.convert(\"RGB\")\n",
865
+ "\n",
866
+ " # 4) write -----------------------------------------------------------------\n",
867
+ " pil.save(out_path)\n",
868
+ " return out_path\n"
869
+ ]
870
+ },
871
+ {
872
+ "cell_type": "code",
873
+ "execution_count": 21,
874
+ "id": "358edaa6",
875
+ "metadata": {},
876
+ "outputs": [
877
+ {
878
+ "name": "stderr",
879
+ "output_type": "stream",
880
+ "text": [
881
+ "writing images: 100%|██████████| 4984/4984 [14:38<00:00, 5.67it/s]\n"
882
+ ]
883
+ },
884
+ {
885
+ "name": "stdout",
886
+ "output_type": "stream",
887
+ "text": [
888
+ "✅ Done: 4984 items saved.\n"
889
+ ]
890
+ }
891
+ ],
892
+ "source": [
893
+ "import os, io, json, shutil\n",
894
+ "from pathlib import Path\n",
895
+ "from PIL import Image\n",
896
+ "from tqdm import tqdm # optional progress bar\n",
897
+ "\n",
898
+ "# ------------------------------------------------------------------ #\n",
899
+ "# directory setup\n",
900
+ "# ------------------------------------------------------------------ #\n",
901
+ "OUT_DIR = Path(\"sft_description\")\n",
902
+ "OUT_DIR.mkdir(exist_ok=True) # creates folder if missing\n",
903
+ "\n",
904
+ "json_records = []\n",
905
+ "\n",
906
+ "# ------------------------------------------------------------------ #\n",
907
+ "# main loop\n",
908
+ "# ------------------------------------------------------------------ #\n",
909
+ "for idx, row in enumerate(tqdm(combined, desc=\"writing images\")):\n",
910
+ " img_path = save_any_image(row[\"images\"], OUT_DIR / str(idx))\n",
911
+ " json_records.append({\n",
912
+ " \"messages\": [\n",
913
+ " {\"content\": row[\"problem\"], \"role\": \"user\"},\n",
914
+ " {\"content\": row[\"outputs\"], \"role\": \"assistant\"}\n",
915
+ " ],\n",
916
+ " \"images\": [str(img_path)]\n",
917
+ " })\n",
918
+ "\n",
919
+ "# ------------------------------------------------------------------ #\n",
920
+ "# write the JSONL / JSON\n",
921
+ "# ------------------------------------------------------------------ #\n",
922
+ "with open(\"sft_description.json\", \"w\", encoding=\"utf-8\") as f:\n",
923
+ " json.dump(json_records, f, ensure_ascii=False, indent=2)\n",
924
+ "\n",
925
+ "print(f\"✅ Done: {len(json_records)} items saved.\")"
926
+ ]
927
+ },
928
+ {
929
+ "cell_type": "markdown",
930
+ "id": "d4e56b70",
931
+ "metadata": {},
932
+ "source": []
933
+ },
934
+ {
935
+ "cell_type": "markdown",
936
+ "id": "adc502bc",
937
+ "metadata": {},
938
+ "source": [
939
+ "### Now process the data for Hotpot Train"
940
+ ]
941
+ },
942
+ {
943
+ "cell_type": "code",
944
+ "execution_count": null,
945
+ "id": "e84f2aa2",
946
+ "metadata": {},
947
+ "outputs": [],
948
+ "source": []
949
+ },
950
+ {
951
+ "cell_type": "code",
952
+ "execution_count": 1,
953
+ "id": "54356d4e",
954
+ "metadata": {},
955
+ "outputs": [],
956
+ "source": [
957
+ "import pandas as pd\n",
958
+ "from openai import OpenAI\n",
959
+ "from concurrent.futures import ThreadPoolExecutor, as_completed\n",
960
+ "from time import sleep\n",
961
+ "from typing import List, Dict, Any, Optional\n",
962
+ "from openai import OpenAI\n",
963
+ "from __future__ import annotations\n",
964
+ "import json\n",
965
+ "from pathlib import Path\n",
966
+ "from typing import Any, Dict, Iterable, List, Union"
967
+ ]
968
+ },
969
+ {
970
+ "cell_type": "code",
971
+ "execution_count": 4,
972
+ "id": "5caaaa06",
973
+ "metadata": {},
974
+ "outputs": [
975
+ {
976
+ "data": {
977
+ "text/plain": [
978
+ "{'index': 0,\n",
979
+ " 'problem': 'Are there any states with a number of reporters between 376-385? Options:\\nA. No\\nB. Yes',\n",
980
+ " 'solution': 'B',\n",
981
+ " 'predictions': ['<description>The image is a map of the United States, with each state colored according to the number of reporters in that state. The title of the map is \"The Number of reporters in the USA\". There is a legend in the bottom right corner. States colored in a light beige color have between 373-375 reporters. States colored in a dark purple color have between 376-385 reporters. Several states are colored dark purple, including Washington, Montana, North Dakota, South Dakota, Iowa, Missouri, Louisiana, Utah, Nevada, California, Virginia, Maryland, and New Hampshire. Alaska and Hawaii are also shown. </description>\\n<think>The question asks if there are any states with a number of reporters between 376-385. The legend indicates that states with 376-385 reporters are colored dark purple. The map shows several states colored dark purple. Therefore, the answer is yes. </think>\\n\\\\boxed{Yes}']}"
982
+ ]
983
+ },
984
+ "execution_count": 4,
985
+ "metadata": {},
986
+ "output_type": "execute_result"
987
+ }
988
+ ],
989
+ "source": [
990
+ "data[0]"
991
+ ]
992
+ }
993
+ ],
994
+ "metadata": {
995
+ "kernelspec": {
996
+ "display_name": "Python 3",
997
+ "language": "python",
998
+ "name": "python3"
999
+ },
1000
+ "language_info": {
1001
+ "codemirror_mode": {
1002
+ "name": "ipython",
1003
+ "version": 3
1004
+ },
1005
+ "file_extension": ".py",
1006
+ "mimetype": "text/x-python",
1007
+ "name": "python",
1008
+ "nbconvert_exporter": "python",
1009
+ "pygments_lexer": "ipython3",
1010
+ "version": "3.11.6"
1011
+ }
1012
+ },
1013
+ "nbformat": 4,
1014
+ "nbformat_minor": 5
1015
+ }
evaluate_single.py ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from utils.gemini_eval import *
2
+ from mathruler.grader import extract_boxed_content
3
+ import json
4
+ from typing import List, Dict, Union, Any
5
+ from pathlib import Path
6
+ from tqdm import tqdm
7
+ import logging
8
+ logging.getLogger().setLevel(logging.ERROR)
9
+ import json
10
+ from pathlib import Path
11
+ from tqdm import tqdm
12
+ import concurrent.futures
13
+ from datasets import load_dataset
14
+
15
+
16
+ def dump_json(
17
+ data: List[Dict[str, Any]],
18
+ path: Union[str, Path],
19
+ *,
20
+ indent: int | None = 2,
21
+ ensure_ascii: bool = False
22
+ ) -> None:
23
+ """
24
+ Save `data` (a list of dictionaries) to `path` in JSON format.
25
+
26
+ Parameters
27
+ ----------
28
+ data : list[dict]
29
+ The objects you want to serialize.
30
+ path : str | pathlib.Path
31
+ Where to write the JSON file. Parent directories are created if needed.
32
+ indent : int | None, default=2
33
+ How many spaces to use for pretty-printing. Set to `None` for a single-line file.
34
+ ensure_ascii : bool, default=False
35
+ If False, non-ASCII characters are written as UTF-8; if True, they're escaped.
36
+
37
+ Raises
38
+ ------
39
+ TypeError
40
+ If `data` contains objects that `json` cannot serialize.
41
+ OSError
42
+ If the file cannot be created or written.
43
+ """
44
+ path = Path(path)
45
+ path.parent.mkdir(parents=True, exist_ok=True)
46
+
47
+ with path.open("w", encoding="utf-8") as f:
48
+ json.dump(data, f, indent=indent, ensure_ascii=ensure_ascii)
49
+ f.write("\n") # final newline (POSIX style)
50
+
51
+
52
+
53
+
54
+ ONLY_FILE = './gemini-pro/visnumbench.json'
55
+ output_file = './eval_out/gemini-pro/visnumbench.json'
56
+
57
+
58
+ ONLY_FILE = Path(ONLY_FILE)
59
+ with ONLY_FILE.open("r", encoding="utf-8") as f:
60
+ data = json.load(f)
61
+
62
+ outputs = []
63
+
64
+ for ele in tqdm(data):
65
+ problem = ele['problem'].replace('<image>', '')
66
+ reference = ele['solution']
67
+ candidate = extract_boxed_content(ele['predictions'][0])
68
+
69
+ judgment = generate(problem, reference, candidate)
70
+ # print(judgment)
71
+ ele['judgment'] = judgment
72
+ outputs.append(ele)
73
+
74
+
75
+
76
+
77
+ dump_json(outputs, output_file)
find_caption_errors.ipynb ADDED
The diff for this file is too large to render. See raw diff
 
gemini_key.json ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "type": "service_account",
3
+ "project_id": "tencent-gemini-omd01",
4
+ "private_key_id": "c2eab17392a5b8ceb2d389b439573ad26a33700e",
5
+ "private_key": "-----BEGIN PRIVATE KEY-----\nMIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCpxIaQ1HXmZT4a\nIiyi8EZxAFuPq8dog4+6cDs7HBmXXkqn7oUMWbEneLlCdC7TAAckRCqljIpjQiRE\nC6bqtSCjc5GEOOCknKMBfcwu/I4Pc5Tmhi8eu4alDocJgtnRMnzZwHy/Ama/FJ5d\nKnR24DubKJQUf9mCfvxgJj9xNw7c57EMJ2X/o7BjecHOiKZX1fN5J97yviE+wIm/\nxubkYyMuEM+HLhQWo6fI7SV1/qe3i94OGnYmSnLD6G7IN0kjoZj3n88+JGJpxJKp\nQ3Lv/gRQPjGhOylYNqsvulirKdeKoXWhMmV9Z71FjshMMedWoAnH7ijdh4SJALgY\nD1h9QbYpAgMBAAECggEAB9TMJ6fYAndJd0Impfjd1FOhuvhqcUdJsjOAKqNgCNat\ngfP4849lon5T/sfw6wSAJSuh01OEL2el2EpjT5toXzHdv2gyRgBVwqQExGbGai8O\nP4NmxAz+0o601aWmxPAxHd2zw3SUZxxyi7YBe68Eq40ie5REOoaqFLNe+irXMYMe\nkpellvArBamyYjjGYhDK4CRcHIotc3ZdfcJR5wqjViUnGS1onhdBSMxovpYnXNj9\nHK+pVlaKzvJQ5ovnr7Ic9XgDHdo23s/1zk8/Hh0wLEGzOzz1L+bMdMeZ8JR8CVQ2\nZ2+DM7LILpm3yUDX/LtteCTPAjG1prNv1jrXYExyEwKBgQDo2DeEMlV3zw0BqGQy\nHsMnJngWY6Z9tVCnLC5fEAEV9uDbKkt8OIenCwrZlsnO1XeFyig4UqgOuQfHQT0v\nE0FtoYfnjYzY0pogXzW1jC/flvSMLxz+KzI35zlRNOlSTTVafy4EsNN0kayTgHzO\nI8Xh0VBYkddypGxG/WwiF9adSwKBgQC6pn1drkbmTMDcjT2CnipxWsgmTr1fD8vo\nRIypaq+AU89ULYjdUaMTv2uHpE5wVQe+va2QhCUJ6pNwkV3c2KjTQ0TOXjaTJJSn\nFAJ4MLtVneBcz2eJHIGP5fJIjQmGgwWU8h+0LShQUdVUmGUR8763jzpClZvJxIkM\nmot6qgYV2wKBgEuOLaWV96ni4+OP0sN4u/auQvVw7IuKFFvKuFlchh2seJZliQ0M\nAuivapvklCOrnRcq3BY6rBHq9J0xjDsEUozSh5kZk4SgAidS/cilbrts7nm2p//J\n4IfHXg/9zWBJcXCmKDaZcmQ3CPrsDJOPhBycoSe8W171/7Shcz804Q01AoGAYKrV\nhu05vxDFWfS0hK+R379apaxmG5O80YCfMScV2eqOGFS065raUOH0uP15umfvaPQn\nrg8id65LyiMfb7+uQCw4uIDG1xI9AwMz/DeQ7lij2K16O+LNn09CWhzhcA7vlyKH\nFPPGS0L2r6d1wQRyI/NEAzQkySzGpgZsco0YNb0CgYEAjETeHxD/itWyHOg6y49c\nw74Yiwk1eFMg7C3lNXd5j8tRk1+2QDhcSMJo6QdRomzyDL9DIxCWUJblVi6hJof/\nE4PH07JBaRAEnWMHjJpBzXriQ5VhWU0MRwpaHOZ2ZAoOkkiqKZIhwryBvfoZa07Q\noArMcZ4xuOoFhE9pOE6g5nE=\n-----END PRIVATE KEY-----\n",
6
+ "client_email": "[email protected]",
7
+ "client_id": "104935904768461518534",
8
+ "auth_uri": "https://accounts.google.com/o/oauth2/auth",
9
+ "token_uri": "https://oauth2.googleapis.com/token",
10
+ "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
11
+ "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/ailab01%40tencent-gemini-omd01.iam.gserviceaccount.com",
12
+ "universe_domain": "googleapis.com"
13
+ }
generate_answer.py ADDED
@@ -0,0 +1,324 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json, os
2
+ from pathlib import Path
3
+ from typing import List
4
+ from datasets import load_dataset
5
+ from PIL import Image
6
+ from tqdm import tqdm
7
+ import concurrent.futures as cf
8
+ import os
9
+ from openai import AzureOpenAI
10
+ from typing import Set, List, Dict, Any
11
+ import time
12
+ import pandas as pd
13
+ from tqdm import tqdm
14
+ import io
15
+ import base64
16
+ import imghdr
17
+ from io import BytesIO
18
+ from mimetypes import guess_type
19
+ import base64
20
+ import time
21
+ from datasets import load_dataset, Features, Sequence, Value, Image as HFImage, ClassLabel
22
+ from PIL import Image
23
+ # from azure.core.exceptions import AzureError
24
+ import concurrent.futures as cf
25
+ import os
26
+ from typing import List
27
+ import os
28
+ from io import BytesIO
29
+
30
+ import vertexai
31
+ from vertexai import generative_models
32
+ from vertexai.generative_models import GenerativeModel, Part
33
+ from datasets import load_dataset
34
+ from PIL import Image as PILImage
35
+
36
+
37
+ # 0) Point at your service account
38
+ os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = './gemini_key.json'
39
+
40
+ # 1) Your generation & safety configs (unchanged)
41
+ generation_config = {
42
+ "max_output_tokens": 2048,
43
+ "temperature": 0.4,
44
+ "top_p": 0.4,
45
+ "top_k": 32,
46
+ }
47
+ safety_settings = {
48
+ generative_models.HarmCategory.HARM_CATEGORY_HATE_SPEECH:
49
+ generative_models.HarmBlockThreshold.BLOCK_MEDIUM_AND_ABOVE,
50
+ generative_models.HarmCategory.HARM_CATEGORY_DANGEROUS_CONTENT:
51
+ generative_models.HarmBlockThreshold.BLOCK_MEDIUM_AND_ABOVE,
52
+ generative_models.HarmCategory.HARM_CATEGORY_SEXUALLY_EXPLICIT:
53
+ generative_models.HarmBlockThreshold.BLOCK_MEDIUM_AND_ABOVE,
54
+ generative_models.HarmCategory.HARM_CATEGORY_HARASSMENT:
55
+ generative_models.HarmBlockThreshold.BLOCK_MEDIUM_AND_ABOVE,
56
+ }
57
+
58
+
59
+ TIMEOUT_CODES = {408, 504, 524}
60
+
61
+
62
+ DATASETS = [
63
+ # "zli12321/realWorldQA",
64
+ # "zli12321/mmmu-pro",
65
+ # "zli12321/mathvista",
66
+ # "zli12321/mm-vet",
67
+ # "zli12321/mmstar",
68
+ # "zli12321/mathvision",
69
+ # "zli12321/MLLM_hotpot_train",
70
+ "zli12321/MLLM_test"
71
+ # "BUAADreamer/clevr_count_70k",
72
+ # "zli12321/mathverse"
73
+ # "zli12321/MLLM_rlvr_train"
74
+ # "zli12321/mmmu-pro-vision",
75
+ # "zli12321/visnumbench",
76
+ # "zli12321/mmmu_pro_10options"
77
+ ]
78
+
79
+ # ---------------------------------------------------------------------
80
+ # 1) CONFIG – adjust as you like
81
+ # ---------------------------------------------------------------------
82
+ # DATA_OUT = "./gpt_outputs/realworldQA.json"
83
+ N_GEN = 1 # ⇐ how many completions per prompt
84
+ retry_delay = 10
85
+
86
+ # QUESTION_TEMPLATE = (
87
+ # "You are tasked with analyzing an image to generate a detailed description to help you answer the question. First analyze the image and produce a self-contained description—detailed enough that can lead to the correct answer. Wrap the entire description in <description> </description> tags.\n Next, engage in an internal dialogue and include self-reflection or verification in your reasoning process. Provide your detailed, step-by-step reasoning based on the image description information and image, and enclose this part within <think> </think> tags.\n Finally, provide a single word or phrase answer to the question in \\boxed{}.\nThe output format should be: <description> image description here </description> <think> reasoning process here </think> \\boxed{FINAL ANSWER here}. Please only include the single letter choice as your answer for multiple choice questions."
88
+ # "Question: {Question}\n"
89
+ # )
90
+
91
+
92
+ QUESTION_TEMPLATE = (
93
+ "You are tasked with analyzing an image and answer a question. First engage in an internal dialogue and include self-reflection or verification in your reasoning process. Provide your detailed, step-by-step reasoning based on the image description information and image, and enclose this part within <think> </think> tags.\n Finally, provide a single word or phrase answer to the question in \\boxed{}.\nThe output format should be: <think> reasoning process here </think> \\boxed{FINAL ANSWER here}."
94
+ "Question: {Question}\n"
95
+ )
96
+
97
+
98
+ # QUESTION_TEMPLATE = (
99
+ # "You are tasked with analyzing an image to generate a detailed description to help you answer the question. Analyze the image and produce a self-contained description—detailed enough that can lead to the correct answer. Wrap the entire description in <description> </description> tags. Then provide a single word or phrase answer to the question in \\boxed{}. The output format should be: <description> image description here </description> \\boxed{FINAL ANSWER here}."
100
+ # "Question: {Question}\n"
101
+ # )
102
+
103
+ def is_timeout(err):
104
+ """Return True if the error (or its cause) is a network timeout."""
105
+ return isinstance(err, TimeoutError) or isinstance(
106
+ getattr(err, "__cause__", None), TimeoutError
107
+ )
108
+
109
+
110
+ vertexai.init(project="tencent-gemini-omd01", location="us-central1")
111
+
112
+ '''Below is for rlvr'''
113
+ # model = GenerativeModel("gemini-2.0-flash")
114
+
115
+ '''Below is for counting'''
116
+ # model = GenerativeModel("gemini-2.0-flash-lite")
117
+
118
+
119
+ '''Below is for Gemini pro pro Accuracy'''
120
+ model = GenerativeModel("gemini-2.5-pro")
121
+ # 3) Load CLEVR‑count 70k and pull the first example’s images list
122
+
123
+
124
+ def generate(pil_img, query):
125
+ # 1) Ensure RGB & re‑encode as PNG in‑memory
126
+ buf = BytesIO()
127
+ pil_img.convert("RGB").save(buf, format="PNG")
128
+ png_bytes = buf.getvalue()
129
+
130
+ # 2) Wrap in a Part
131
+ image_part = Part.from_data(
132
+ data=png_bytes,
133
+ mime_type="image/png"
134
+ )
135
+ for i in range(2):
136
+ # 3) Generate
137
+ try:
138
+ responses = model.generate_content(
139
+ contents=[image_part, query],
140
+ generation_config=generation_config,
141
+ safety_settings=safety_settings,
142
+ stream=True,
143
+ )
144
+
145
+ # 4) Collect and return
146
+ full = ""
147
+ for chunk in responses:
148
+ full += chunk.text
149
+ except Exception as e:
150
+ full = "No Text"
151
+ print(f'Failed generating: {e}')
152
+ time.sleep(5)
153
+
154
+
155
+ return full
156
+
157
+
158
+
159
+ # ---------------------------------------------------------------------
160
+ # 2) YOUR MODEL / API CALL – plug in here
161
+ # ---------------------------------------------------------------------
162
+ def generate_answer(image, messages) -> str:
163
+ """
164
+ Replace the body of this function with whatever you use to talk to
165
+ your model (e.g. OpenAI, Ollama, local HF pipeline, etc.).
166
+ Must return a *single* string completion.
167
+ """
168
+ # raise NotImplementedError(
169
+ # "Implement generate_answer(img, prompt_text) to call your model."
170
+ # )
171
+ # return azure_gpt4(messages)
172
+ return generate(image, messages)
173
+
174
+
175
+
176
+ # ---------------------------------------------------------------------
177
+ # 3) DATASET & UTILS
178
+ # ---------------------------------------------------------------------
179
+
180
+ def build_prompt(item) -> str:
181
+ """Fill QUESTION_TEMPLATE with the current question."""
182
+ return QUESTION_TEMPLATE.replace("{Question}", item["problem"])
183
+
184
+ def to_rgb(img: Image.Image) -> Image.Image:
185
+ return img if img.mode == "RGB" else img.convert("RGB")
186
+
187
+ def _load_partial(out_path: Path) -> List[Dict[str, Any]]:
188
+ if not out_path.exists():
189
+ return []
190
+ try:
191
+ with out_path.open("r", encoding="utf-8") as f:
192
+ return json.load(f)
193
+ except Exception as err:
194
+ print(f"[warn] {out_path} could not be read ({err}) – ignoring.")
195
+ return []
196
+
197
+
198
+ def run_dataset(dataset_id: str, n_gen: int = 1) -> None:
199
+ """Run the generation loop for one dataset, resuming if output exists."""
200
+ print(f"\n=== Processing {dataset_id} ===")
201
+
202
+ # ---- prepare output path ----------------------------------------
203
+ slug = dataset_id.split("/")[-1]
204
+ # DATA_OUT = Path(f"./gemini-flash/{slug}.json")
205
+ # DATA_OUT = Path(f"./gemini-pro/{slug}.json")
206
+ # DATA_OUT = Path(f"./gemini-pro-pro/{slug}.json")
207
+ DATA_OUT = Path(f"./gemini-cot/{slug}.json")
208
+
209
+
210
+ DATA_OUT.parent.mkdir(parents=True, exist_ok=True)
211
+
212
+ # ---- load existing results (if any) -----------------------------
213
+ results: List[Dict[str, Any]] = _load_partial(DATA_OUT)
214
+ done_idx: Set[int] = {rec["index"] for rec in results}
215
+ print(f"[{slug}] found {len(done_idx)} previously processed items")
216
+
217
+
218
+ # ---- load split -------------------------------------------------
219
+ # if 'count' in dataset_id or 'hotpot' in dataset_id:
220
+ # ds = load_dataset(dataset_id, split="train", trust_remote_code=True)
221
+ # else:
222
+ # ds = load_dataset(dataset_id, split="test", trust_remote_code=True)
223
+
224
+ if 'count' in dataset_id or 'hotpot' in dataset_id:
225
+ ds = load_dataset(dataset_id, split="train")
226
+ else:
227
+ try:
228
+ ds = load_dataset(dataset_id, split="train")
229
+ except:
230
+ ds = load_dataset(dataset_id, split="test", trust_remote_code=True)
231
+
232
+
233
+ # ---- decode images once ----------------------------------------
234
+ df = ds.to_pandas()
235
+ try:
236
+ df["pil_images"] = df["images"].apply(
237
+ lambda lst: [Image.open(io.BytesIO(d["bytes"])).convert("RGB") for d in lst]
238
+ )
239
+ images = [imgs[0] for imgs in df["pil_images"]]
240
+ except Exception:
241
+ df["pil_images"] = df["images"].apply(
242
+ lambda d: Image.open(io.BytesIO(d["bytes"])).convert("RGB")
243
+ )
244
+ images = list(df["pil_images"])
245
+
246
+ # ---- main generation loop --------------------------------------
247
+ with cf.ThreadPoolExecutor(max_workers=n_gen) as pool: # <-- here
248
+ for idx, item in enumerate(
249
+ tqdm(ds, desc=f"generating · {slug}",
250
+ initial=len(done_idx), total=len(ds))
251
+ ):
252
+ if idx in done_idx:
253
+ continue
254
+
255
+ prompt_txt = build_prompt(item)
256
+ # image_url = pil_image_to_data_url(images[idx])
257
+ # messages = [{"instruction": prompt_txt, "image": image_url}]
258
+
259
+ # launch `n_gen` concurrent calls
260
+ futures = [pool.submit(generate_answer, images[idx], prompt_txt)
261
+ for _ in range(n_gen)] # <-- here
262
+ answers = [f.result() for f in futures if f.result()]
263
+
264
+ if answers:
265
+ results.append(
266
+ dict(
267
+ index = idx,
268
+ problem = item["problem"],
269
+ solution = item["answer"],
270
+ predictions = answers,
271
+ )
272
+ )
273
+ DATA_OUT.write_text(json.dumps(results, indent=2, ensure_ascii=False))
274
+ print(f"✅ {slug}: finished {len(results)} samples → {DATA_OUT}")
275
+
276
+
277
+ # --------------------------- 2. run_all -------------------------------
278
+ def run_all(
279
+ datasets: list, # list[str] *or* list[tuple[str,int]]
280
+ default_n_gen: int = 1,
281
+ max_workers: int | None = None,
282
+ ) -> None:
283
+ """
284
+ Launch `run_dataset` for every entry in *datasets*.
285
+
286
+ `datasets` may contain:
287
+ • "foo/bar" -> uses default_n_gen
288
+ • ("foo/bar", 8) -> uses 8 for that file
289
+ """
290
+ if max_workers is None:
291
+ max_workers = min(len(datasets), 32)
292
+
293
+ print(f"\nLaunching {len(datasets)} dataset jobs "
294
+ f"({max_workers} workers)…\n")
295
+
296
+ with cf.ThreadPoolExecutor(max_workers=max_workers) as pool:
297
+ fut_to_name = {}
298
+ for entry in datasets:
299
+ if isinstance(entry, tuple):
300
+ ds_id, n_gen = entry
301
+ else:
302
+ ds_id, n_gen = entry, default_n_gen
303
+ fut = pool.submit(run_dataset, ds_id, n_gen)
304
+ fut_to_name[fut] = ds_id
305
+
306
+ for fut in cf.as_completed(fut_to_name):
307
+ name = fut_to_name[fut]
308
+ try:
309
+ fut.result()
310
+ except Exception as exc:
311
+ print(f"❌ {name} failed: {exc!r}")
312
+ else:
313
+ print(f"✅ {name} done")
314
+
315
+ # ---------------------------------------------------------------------
316
+ # ENTRY-POINT
317
+ # ---------------------------------------------------------------------
318
+ if __name__ == "__main__":
319
+ run_all(DATASETS, max_workers=min(len(DATASETS), os.cpu_count() * 2))
320
+
321
+
322
+
323
+ '''Below is code for gemini inference'''
324
+
qwen_caption_cot.py ADDED
@@ -0,0 +1,190 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+ import pandas as pd
3
+ from openai import OpenAI
4
+ from concurrent.futures import ThreadPoolExecutor, as_completed
5
+ from time import sleep
6
+ from typing import List, Dict, Any, Optional
7
+ from openai import OpenAI
8
+ import json
9
+ from pathlib import Path
10
+ from typing import Any, Dict, Iterable, List, Union
11
+ import re
12
+ import datetime
13
+ from typing import Dict, List, Optional
14
+ from mathruler.grader import extract_boxed_content, grade_answer
15
+ import math
16
+ from tqdm.auto import tqdm
17
+
18
+
19
+ def extract_description(predict: str) -> Optional[str]:
20
+ """
21
+ Extracts the content of the <answer>…</answer> block from `predict`.
22
+ Returns the inner text (with leading/trailing whitespace stripped),
23
+ or None if no <answer> tag is found.
24
+ """
25
+ match = re.search(r"<description>([\s\S]*?)</description>", predict, re.DOTALL)
26
+ if not match:
27
+ return predict
28
+ return match.group(1).strip()
29
+
30
+ # curl http://29.81.228.243:8081 /v1/models
31
+ client = OpenAI(
32
+ base_url="http://29.81.244.54:8081/v1", # your vLLM server
33
+ api_key="ANYKEY", # if you set --api-key when launching
34
+ )
35
+
36
+
37
+ def chat_once(messages):
38
+ resp = client.chat.completions.create(
39
+ model="Qwen2.5-VL-72B-Instruct",
40
+ messages=messages
41
+ )
42
+ return resp.choices[0].message.content
43
+
44
+
45
+ def chat_batch(
46
+ client,
47
+ all_message_batches: List[List[Dict[str, str]]],
48
+ *,
49
+ model: str = "Qwen2.5-VL-72B-Instruct",
50
+ max_workers: int = 8,
51
+ retries: int = 2,
52
+ backoff: float = 0.5,
53
+ timeout: Optional[float] = None,
54
+ ) -> List[str]:
55
+ """
56
+ Send many chat requests in parallel and return replies as a list of strings,
57
+ preserving the order of `all_message_batches`.
58
+ """
59
+
60
+ def _chat_once_with_retry(messages: List[Dict[str, str]]) -> str:
61
+ last_err: Optional[BaseException] = None
62
+ for attempt in range(retries + 1):
63
+ try:
64
+ resp = client.chat.completions.create(
65
+ model=model,
66
+ messages=messages,
67
+ timeout=timeout,
68
+ )
69
+ # Different SDKs expose content slightly differently; handle common cases.
70
+ choice = resp.choices[0]
71
+ if hasattr(choice, "message") and getattr(choice.message, "content", None) is not None:
72
+ return choice.message.content
73
+ if hasattr(choice, "text") and choice.text is not None:
74
+ return choice.text
75
+ # Fallback to stringifying the choice if structure is unexpected.
76
+ return str(choice)
77
+ except Exception as e:
78
+ last_err = e
79
+ if attempt < retries:
80
+ sleep(backoff * (2 ** attempt))
81
+ return f"Error: {last_err!r}"
82
+
83
+ results: List[Optional[str]] = [None] * len(all_message_batches)
84
+ with ThreadPoolExecutor(max_workers=max_workers) as executor:
85
+ future_to_idx = {
86
+ executor.submit(_chat_once_with_retry, batch): i
87
+ for i, batch in enumerate(all_message_batches)
88
+ }
89
+ for fut in as_completed(future_to_idx):
90
+ i = future_to_idx[fut]
91
+ results[i] = fut.result()
92
+
93
+ # mypy-friendly cast: no Nones remain at this point
94
+ return [r if r is not None else "Error: Unknown failure" for r in results]
95
+
96
+
97
+
98
+ def load_json_list(path: Union[str, Path], encoding: str = "utf-8") -> List[Dict[str, Any]]:
99
+ """
100
+ Load a JSON file whose top-level structure is a list of dicts.
101
+
102
+ Raises:
103
+ FileNotFoundError, json.JSONDecodeError, TypeError
104
+ """
105
+ p = Path(path)
106
+ with p.open("r", encoding=encoding) as f:
107
+ data = json.load(f)
108
+
109
+ if not isinstance(data, list):
110
+ raise TypeError(f"Expected top-level JSON to be a list, got {type(data).__name__}")
111
+
112
+ for i, item in enumerate(data):
113
+ if not isinstance(item, dict):
114
+ raise TypeError(f"Item at index {i} is {type(item).__name__}, expected dict")
115
+
116
+ return data
117
+
118
+ # Prepare a list of different message‐lists you want to send:
119
+ all_message_batches = [
120
+ [
121
+ {"role": "system", "content": "You are a helpful assistant."},
122
+ {"role": "user", "content": "Hello, how are you?"}
123
+ ],
124
+ [
125
+ {"role": "system", "content": "You are a helpful assistant."},
126
+ {"role": "user", "content": "Tell me a joke."}
127
+ ],
128
+ [
129
+ {"role": "system", "content": "You are a helpful assistant."},
130
+ {"role": "user", "content": "Tell me a joke."}
131
+ ],
132
+ [
133
+ {"role": "system", "content": "You are a helpful assistant."},
134
+ {"role": "user", "content": "Tell me a joke."}
135
+ ],
136
+ # …more batches…
137
+ ]
138
+
139
+
140
+ res = chat_batch(client, all_message_batches)
141
+
142
+ prompt_template = '''Text description: {Description}\nQuestion: {Question}\nYou are provided a text description of a problem and a question. Determine the answer to the question based on the text description. First provide an internal step-by-step reasoning within <think> </think> tags, then provide a single word or phrase answer in \\boxed{}.'''
143
+ MODEL = "Qwen2.5-VL-72B-Instruct"
144
+ BATCH_SIZE = 16
145
+ filename = "MLLM_rlvr_train"
146
+ out_file = f'./caption_out/{filename}.json'
147
+ data = load_json_list(f'./gemini-flash/{filename}.json')
148
+
149
+
150
+ def to_messages(example: Dict[str, Any]) -> List[Dict[str, str]]:
151
+ """Use the single string inside `predictions` as the user input."""
152
+ preds = example.get("predictions")
153
+ question = example.get("problem")
154
+
155
+ if isinstance(preds, list) and preds:
156
+ first = preds[0]
157
+ text = first if isinstance(first, str) else json.dumps(first, ensure_ascii=False)
158
+ description = extract_description(text)
159
+ input_question = prompt_template.replace('{Description}', description).replace('{Question}', question)
160
+ else:
161
+ input_question = 'None'
162
+
163
+ return [
164
+ {"role": "system", "content": "You are a helpful assistant."},
165
+ {"role": "user", "content": input_question},
166
+ ]
167
+
168
+
169
+ # Ensure output dir exists and start fresh
170
+ Path(out_file).parent.mkdir(parents=True, exist_ok=True)
171
+ with open(out_file, "w", encoding="utf-8"):
172
+ pass
173
+
174
+ total = len(data)
175
+ num_batches = math.ceil(total / BATCH_SIZE)
176
+
177
+ for start in tqdm(range(0, total, BATCH_SIZE),
178
+ total=num_batches, desc="Batches", unit="batch"):
179
+ chunk = data[start : start + BATCH_SIZE]
180
+ batch_messages = [to_messages(ex) for ex in chunk]
181
+
182
+ replies = chat_batch(client, batch_messages, model=MODEL,
183
+ max_workers=8, retries=2, backoff=0.5, timeout=None)
184
+
185
+ print(replies[0])
186
+ with open(out_file, "a", encoding="utf-8") as f:
187
+ for ex, reply in zip(chunk, replies):
188
+ record = {**ex, "model": MODEL, "model_caption_response": reply}
189
+ f.write(json.dumps(record, ensure_ascii=False) + "\n")
190
+ f.flush()
sft_description.json ADDED
The diff for this file is too large to render. See raw diff
 
sft_description/1182.jpg ADDED
sft_description/1332.jpg ADDED
sft_description/1389.png ADDED
sft_description/1402.jpg ADDED
sft_description/1473.jpg ADDED
sft_description/1571.jpg ADDED
sft_description/167.jpg ADDED
sft_description/1739.jpg ADDED
sft_description/1797.jpg ADDED
sft_description/249.jpg ADDED
sft_description/2513.jpg ADDED
sft_description/2539.jpg ADDED
sft_description/2543.jpg ADDED
sft_description/2739.jpg ADDED
sft_description/2811.jpg ADDED
sft_description/3009.jpg ADDED
sft_description/3052.jpg ADDED
sft_description/307.jpg ADDED
sft_description/3123.jpg ADDED
sft_description/3191.jpg ADDED
sft_description/3218.jpg ADDED
sft_description/3239.jpg ADDED
sft_description/3327.jpg ADDED
sft_description/3341.jpg ADDED
sft_description/3395.jpg ADDED
sft_description/3500.jpg ADDED
sft_description/3725.jpg ADDED
sft_description/3737.jpg ADDED
sft_description/3960.jpg ADDED
sft_description/4058.jpg ADDED
sft_description/4144.jpg ADDED
sft_description/4200.jpg ADDED
sft_description/4384.jpg ADDED
sft_description/4433.jpg ADDED
sft_description/4484.png ADDED
sft_description/4608.jpg ADDED
sft_description/4788.jpg ADDED
sft_description/4843.png ADDED
sft_description/4936.jpg ADDED
sft_description/617.jpg ADDED
sft_description/742.jpg ADDED
sft_description/83.jpg ADDED
sft_description/869.jpg ADDED