run_infer.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468
  1. """
  2. Overview:
  3. This code implements the evaluation of agents on the GPQA Benchmark with Open Book setting.
  4. - The benchmark consists of 448 high-quality and extremely difficult multiple-choice questions in the domains of biology, physics, and chemistry. The questions are intentionally designed to be "Google-proof," meaning that even highly skilled non-expert validators achieve only 34% accuracy despite unrestricted access to the web.
  5. - Even experts in the corresponding domains achieve only 65% accuracy.
  6. - State-of-the-art AI systems achieve only 39% accuracy on this challenging dataset.
  7. Accurate solving of above graduate level questions would require both tool use (e.g., python for calculations) and web-search for finding related facts as information required for the questions might not be part of the LLM knowledge / training data.
  8. Further references:
  9. - https://arxiv.org/pdf/2311.12022
  10. - https://paperswithcode.com/dataset/gpqa
  11. - https://github.com/idavidrein/gpqa
  12. TODOs:
  13. - Add evaluation on other Agent classes (e.g., MonologueAgent)
  14. - Batch inference and evaluation of agents on the GPQA Benchmark.
  15. """
  16. import asyncio
  17. import json
  18. import logging
  19. import multiprocessing as mp
  20. import os
  21. import pathlib
  22. import random
  23. import re
  24. import subprocess
  25. import time
  26. from concurrent.futures import ProcessPoolExecutor
  27. import pandas as pd
  28. from datasets import load_dataset
  29. from tqdm import tqdm
  30. from opendevin.controller.state.state import State
  31. from opendevin.core.config import config, get_llm_config_arg, get_parser
  32. from opendevin.core.logger import get_console_handler
  33. from opendevin.core.logger import opendevin_logger as logger
  34. from opendevin.core.main import main
  35. from opendevin.events.action import MessageAction
  36. from opendevin.events.serialization.event import event_to_dict
  37. def cleanup():
  38. logger.info('Cleaning up child processes...')
  39. for process in mp.active_children():
  40. logger.info(f'Terminating child process: {process.name}')
  41. process.terminate()
  42. process.join()
  43. def codeact_user_response(state: State) -> str:
  44. msg = (
  45. 'Please continue working on the task on whatever approach you think is suitable.\n'
  46. 'Feel free to use all tools for calculations and solving the problem, and web-search for finding relevant facts during the process if needed\n'
  47. 'If you think you have reliably finished solving the problem, first generate a message reporting the final concise answer to the user. Once that is done, please run the following command: <execute_bash> exit </execute_bash>.\n'
  48. 'IMPORTANT: YOU SHOULD NEVER ASK FOR HUMAN HELP TO SOLVE THIS TASK.\n'
  49. )
  50. if state.history:
  51. user_msgs = [
  52. action
  53. for action, _ in state.history
  54. if isinstance(action, MessageAction) and action.source == 'user'
  55. ]
  56. if len(user_msgs) >= 2:
  57. # let the agent know that it can give up when it has tried 3 times
  58. return (
  59. msg
  60. + 'If you want to give up, just generate a final answer message to the user and in the next turn --> run: <execute_bash> exit </execute_bash>.\n'
  61. )
  62. return msg
  63. def monologue_user_response(state: State) -> str:
  64. raise NotImplementedError('MonologueAgent should never ask for user responses.')
  65. AGENT_CLS_TO_FAKE_USER_RESPONSE_FN = {
  66. 'CodeActAgent': codeact_user_response,
  67. 'MonologueAgent': monologue_user_response,
  68. }
  69. AGENT_CLS_TO_INST_SUFFIX = {
  70. 'CodeActAgent': '\n\n SUPER IMPORTANT: When you think you have solved the question, first report it back to the user in the requested format. Only once that is done, in the next turn, please run the following command: <execute_bash> exit </execute_bash>.\n'
  71. }
  72. def parse_final_answer(final_answer: str) -> str:
  73. """
  74. Parse the final answer from the final message generated by the agent
  75. to extract the final answer. The final answer is usually enclosed in the format:
  76. <<FINAL_ANSWER||
  77. <insert correct answer here>
  78. ||FINAL_ANSWER>>
  79. """
  80. pattern = re.compile(r'<<FINAL_ANSWER\|\|(.*?)\|\|FINAL_ANSWER>>', re.DOTALL)
  81. match = pattern.search(final_answer)
  82. if match:
  83. return match.group(1).strip()
  84. else:
  85. return 'No final answer found in the provided string.'
  86. def compare_answers(predicted_answer, ground_truth):
  87. """
  88. Compare the predicted answer with the ground truth answer
  89. """
  90. return predicted_answer == ground_truth
  91. def get_test_result(model_output, ground_truth):
  92. """
  93. Implements the evaluation logic for GPQA
  94. Checks if the output of a given instance is correct (as per the ground truth)
  95. """
  96. # parse the final answer from model output
  97. predicted_answer = parse_final_answer(model_output)
  98. # check if the model output matches the ground truth
  99. result = compare_answers(predicted_answer, ground_truth)
  100. return result
  101. def convert_instance_dict(instance):
  102. """
  103. Used for preprocessing the hf dataset into a format that can be used by the agent.
  104. Reads and extracts relevant information from the dataset instance.
  105. """
  106. out_instance_dict = {}
  107. out_instance_dict['question'] = instance['Question']
  108. correct_answer = instance['Correct Answer']
  109. out_instance_dict['choices'] = [
  110. correct_answer,
  111. instance['Incorrect Answer 1'],
  112. instance['Incorrect Answer 2'],
  113. instance['Incorrect Answer 3'],
  114. ]
  115. # Randomize the order of choices
  116. random.shuffle(out_instance_dict['choices'])
  117. # Find the index of the correct answer after shuffling and store it as a letter (A/B/C/D)
  118. correct_index = out_instance_dict['choices'].index(correct_answer)
  119. correct_letter = chr(
  120. 65 + correct_index
  121. ) # Convert index (0-3) to corresponding letter (A-D)
  122. out_instance_dict['correct_solution'] = correct_letter
  123. return out_instance_dict
  124. def process_instance(
  125. instance: dict,
  126. agent_class: str,
  127. metadata: dict,
  128. skip_workspace_mount: bool,
  129. eval_output_dir: str,
  130. reset_logger: bool = True,
  131. ):
  132. """
  133. Process a single instance from the dataset
  134. """
  135. old_workspace_mount_path = config.workspace_mount_path
  136. old_workspace_base = config.workspace_base
  137. try:
  138. workspace_mount_path = os.path.join(
  139. config.workspace_mount_path, '_eval_workspace'
  140. )
  141. # create process-specific workspace dir
  142. # if `not skip_workspace_mount` - we will create a workspace directory for EACH process
  143. # so that different agent don't interfere with each other.
  144. skip_workspace_mount = False
  145. if not skip_workspace_mount:
  146. workspace_mount_path = os.path.join(workspace_mount_path, str(os.getpid()))
  147. pathlib.Path(workspace_mount_path).mkdir(parents=True, exist_ok=True)
  148. # reset workspace to config
  149. config.workspace_base = workspace_mount_path
  150. config.workspace_mount_path = workspace_mount_path
  151. # workspace_mount_path = os.path.join(config.workspace_mount_path, '_eval_workspace')
  152. # workspace_mount_path = os.path.abspath(workspace_mount_path)
  153. # # create process-specific workspace dir
  154. # # if `not skip_workspace_mount` - we will create a workspace directory for EACH process
  155. # # so that different agent don't interfere with each other.
  156. # if not skip_workspace_mount:
  157. # workspace_mount_path = os.path.join(workspace_mount_path, str(os.getpid()))
  158. # pathlib.Path(workspace_mount_path).mkdir(parents=True, exist_ok=True)
  159. # Setup the logger properly, so you can run multi-processing to parallelize the evaluation
  160. if reset_logger:
  161. # Set up logger
  162. log_file = os.path.join(
  163. eval_output_dir, 'logs', f'instance_{instance.instance_id}.log'
  164. )
  165. # Remove all existing handlers from logger
  166. for handler in logger.handlers[:]:
  167. logger.removeHandler(handler)
  168. # add back the console handler to print ONE line
  169. logger.addHandler(get_console_handler())
  170. logger.info(
  171. f'Starting evaluation for instance {instance.instance_id}.\nHint: run "tail -f {log_file}" to see live logs in a separate shell'
  172. )
  173. # Remove all existing handlers from logger
  174. for handler in logger.handlers[:]:
  175. logger.removeHandler(handler)
  176. file_handler = logging.FileHandler(log_file)
  177. file_handler.setFormatter(
  178. logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
  179. )
  180. logger.addHandler(file_handler)
  181. else:
  182. logger.info(f'Starting evaluation for instance {instance.instance_id}.')
  183. if not skip_workspace_mount:
  184. logger.info(f'Process-specific workspace mounted at {workspace_mount_path}')
  185. # ======= Run the agent on the instance =======
  186. # Prepare instruction for the agent using suggested format in gpqa codebase
  187. instruction = f"""
  188. What is the correct answer to this question:\n
  189. {instance['question']}\n
  190. Choices:\n
  191. (A) {instance['choices'][0]}\n
  192. (B) {instance['choices'][1]}\n
  193. (C) {instance['choices'][2]}\n
  194. (D) {instance['choices'][3]}\n
  195. \n\n
  196. MOST IMPORTANT: Format your response as follows:
  197. <<FINAL_ANSWER||
  198. <insert correct answer here, must be one of A, B, C, D> (Please dont use any additional characters. Just the letter of the correct answer (A/B/C/D).)
  199. ||FINAL_ANSWER>>
  200. Additional Instructions:
  201. - You should ONLY interact with the environment provided to you AND NEVER ASK FOR HUMAN HELP.
  202. """
  203. # NOTE: You can actually set slightly different instruction for different agents
  204. instruction += AGENT_CLS_TO_INST_SUFFIX.get(agent_class, '')
  205. # Here's how you can run the agent (similar to the `main` function) and get the final task state
  206. state: State = asyncio.run(
  207. main(
  208. instruction,
  209. fake_user_response_fn=AGENT_CLS_TO_FAKE_USER_RESPONSE_FN.get(
  210. agent_class
  211. ),
  212. )
  213. )
  214. # ======= Attempt to evaluate the agent's edits =======
  215. # get the final message from the state history (default to None if not found)
  216. final_message = next(
  217. (
  218. act.content
  219. for act in reversed(state.history)
  220. if isinstance(act, MessageAction)
  221. ),
  222. None,
  223. )
  224. logger.info(f'Final message generated by the agent: {final_message}')
  225. test_result = get_test_result(final_message, instance.correct_solution)
  226. # If you are working on some simpler benchmark that only evaluates the final model output (e.g., in a MessageAction)
  227. # You can simply get the LAST `MessageAction` from the returned `state.history` and parse it for evaluation.
  228. if state is None:
  229. raise ValueError('State should not be None.')
  230. metrics = state.metrics.get() if state.metrics else None
  231. # Save the output
  232. output = {
  233. 'task_id': instance.task_id,
  234. 'instance_id': instance.instance_id,
  235. 'instruction': instruction,
  236. 'metadata': metadata,
  237. 'history': [
  238. (event_to_dict(action), event_to_dict(obs))
  239. for action, obs in state.history
  240. ],
  241. 'metrics': metrics,
  242. 'error': state.error if state and state.error else None,
  243. 'test_result': test_result,
  244. }
  245. except Exception:
  246. logger.error('Process instance failed')
  247. raise
  248. finally:
  249. config.workspace_mount_path = old_workspace_mount_path
  250. config.workspace_base = old_workspace_base
  251. return output
  252. if __name__ == '__main__':
  253. parser = get_parser()
  254. # data split must be one of 'gpqa_main', 'gqpa_diamond', 'gpqa_experts', 'gpqa_extended'
  255. parser.add_argument(
  256. '--data-split',
  257. type=str,
  258. choices=['gpqa_main', 'gpqa_diamond', 'gpqa_experts', 'gpqa_extended'],
  259. default='gpqa_diamond',
  260. help='data split to evaluate, eg. gpqa_diamond',
  261. )
  262. args, _ = parser.parse_known_args()
  263. # NOTE: It is preferable to load datasets from huggingface datasets and perform post-processing
  264. # so we don't need to manage file uploading to OpenDevin's repo
  265. dataset = load_dataset('Idavidrein/gpqa', args.data_split)
  266. gpqa_dataset = dataset['train']
  267. # preprocess the dataset
  268. gpqa_dataset = gpqa_dataset.map(convert_instance_dict)
  269. gpqa_dataset = gpqa_dataset.to_pandas()
  270. # Add a new column 'instance_id' with the index
  271. gpqa_dataset['instance_id'] = gpqa_dataset.index
  272. gpqa_dataset['task_id'] = gpqa_dataset.index
  273. # gpqa_dataset = dataset['train'].to_pandas().sort_values(by='id').reset_index(drop=True)
  274. # Check https://github.com/OpenDevin/OpenDevin/blob/main/evaluation/swe_bench/README.md#configure-opendevin-and-your-llm
  275. # for details of how to set `llm_config`
  276. if args.llm_config:
  277. specified_llm_config = get_llm_config_arg(args.llm_config)
  278. if specified_llm_config:
  279. config.llm = specified_llm_config
  280. logger.info(f'Config for evaluation: {config}')
  281. # TEST METADATA
  282. agent_class = args.agent_cls
  283. assert (
  284. agent_class in AGENT_CLS_TO_FAKE_USER_RESPONSE_FN
  285. ), f'Unsupported agent class: {agent_class}'
  286. model_name = config.llm.model.split('/')[-1]
  287. max_iterations = args.max_iterations
  288. eval_note = ''
  289. if args.eval_note is not None:
  290. eval_note += '_N_' + args.eval_note
  291. eval_output_dir = os.path.join(
  292. args.eval_output_dir,
  293. 'gpqa',
  294. agent_class,
  295. model_name + '_maxiter_' + str(max_iterations) + eval_note,
  296. )
  297. pathlib.Path(eval_output_dir).mkdir(parents=True, exist_ok=True)
  298. pathlib.Path(os.path.join(eval_output_dir, 'logs')).mkdir(
  299. parents=True, exist_ok=True
  300. )
  301. logger.info(f'Using evaluation output directory: {eval_output_dir}')
  302. metadata = {
  303. 'agent_class': agent_class,
  304. 'model_name': model_name,
  305. 'max_iterations': max_iterations,
  306. 'eval_output_dir': eval_output_dir,
  307. 'start_time': time.strftime('%Y-%m-%d %H:%M:%S'),
  308. # get the commit id of current repo for reproduciblity
  309. 'git_commit': subprocess.check_output(['git', 'rev-parse', 'HEAD'])
  310. .decode('utf-8')
  311. .strip(),
  312. }
  313. logger.info(f'Metadata: {metadata}')
  314. with open(os.path.join(eval_output_dir, 'metadata.json'), 'w') as f:
  315. json.dump(metadata, f)
  316. # LIMIT EVALUATION
  317. eval_n_limit = args.eval_n_limit # NOTE: This is useful for debugging and testing using a smaller subset of the dataset
  318. if eval_n_limit:
  319. # start_index = 20
  320. # gpqa_dataset = gpqa_dataset.iloc[start_index:]
  321. gpqa_dataset = gpqa_dataset.head(eval_n_limit)
  322. logger.info(f'Limiting evaluation to first {eval_n_limit} instances.')
  323. logger.info('#############################################')
  324. logger.info(f'{eval_n_limit} instances will be evaluated.')
  325. logger.info('#############################################')
  326. # OUTPUT FILE
  327. output_file = os.path.join(eval_output_dir, 'output.jsonl')
  328. logger.info(f'Writing evaluation output to {output_file}')
  329. finished_instance_ids = set()
  330. if os.path.exists(output_file):
  331. with open(output_file, 'r') as f:
  332. for line in f:
  333. data = json.loads(line)
  334. finished_instance_ids.add(data['instance_id'])
  335. logger.warning(
  336. f'Output file {output_file} already exists. Loaded {len(finished_instance_ids)} finished instances.'
  337. )
  338. output_fp = open(output_file, 'a')
  339. logger.info(
  340. f'Evaluation started with Agent {agent_class}, model {model_name}, max iterations {max_iterations}.'
  341. )
  342. # =============================================
  343. # filter out finished instances
  344. new_gpqa_dataset = []
  345. for idx, instance in gpqa_dataset.iterrows():
  346. # instance = convert_instance_dict(instance) # preprocessing
  347. if instance.instance_id in finished_instance_ids:
  348. logger.info(
  349. f'Skipping instance {instance.instance_id} as it is already finished.'
  350. )
  351. continue
  352. new_gpqa_dataset.append(instance)
  353. gpqa_dataset = pd.DataFrame(new_gpqa_dataset)
  354. logger.info(
  355. f'Finished instances: {len(finished_instance_ids)}, Remaining instances: {len(gpqa_dataset)}'
  356. )
  357. # =============================================
  358. pbar = tqdm(total=len(gpqa_dataset))
  359. # This function tracks the progress AND write the output to a JSONL file
  360. def update_progress(future):
  361. pbar.update(1)
  362. output = future.result()
  363. pbar.set_description(f'Instance {output["instance_id"]}')
  364. pbar.set_postfix_str(f'Test Result: {output["test_result"]["result"]}')
  365. logger.info(
  366. f'Finished evaluation for instance {output["instance_id"]}: {output["test_result"]["result"]}'
  367. )
  368. output_fp.write(json.dumps(output) + '\n')
  369. output_fp.flush()
  370. # This sets the multi-processing
  371. num_workers = args.eval_num_workers
  372. logger.info(f'Using {num_workers} workers for evaluation.')
  373. # This is SWE-Bench specific - CodeActAgent doesn't require mounted workspace to work
  374. skip_workspace_mount = agent_class == 'CodeActAgent'
  375. logger.info(f'Skipping workspace mount: {skip_workspace_mount}')
  376. try:
  377. with ProcessPoolExecutor(num_workers) as executor:
  378. futures = []
  379. # This is how we perform multi-processing
  380. for row_idx, instance in gpqa_dataset.iterrows():
  381. future = executor.submit(
  382. process_instance,
  383. instance,
  384. agent_class,
  385. metadata,
  386. skip_workspace_mount,
  387. eval_output_dir,
  388. reset_logger=bool(num_workers > 1),
  389. )
  390. future.add_done_callback(update_progress)
  391. futures.append(future)
  392. # Wait for all futures to complete
  393. for future in futures:
  394. future.result()
  395. except KeyboardInterrupt:
  396. print('KeyboardInterrupt received. Cleaning up...')
  397. cleanup()
  398. output_fp.close()
  399. logger.info('Evaluation finished.')