run_infer.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388
  1. """Overview:
  2. This code implements the evaluation of agents on the GPQA Benchmark with Open Book setting.
  3. - 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.
  4. - Even experts in the corresponding domains achieve only 65% accuracy.
  5. - State-of-the-art AI systems achieve only 39% accuracy on this challenging dataset.
  6. 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.
  7. Further references:
  8. - https://arxiv.org/pdf/2311.12022
  9. - https://paperswithcode.com/dataset/gpqa
  10. - https://github.com/idavidrein/gpqa
  11. TODOs:
  12. - Add evaluation on other Agent classes
  13. - Batch inference and evaluation of agents on the GPQA Benchmark.
  14. """
  15. import asyncio
  16. import logging
  17. import os
  18. import pathlib
  19. import random
  20. import re
  21. from typing import Callable
  22. import pandas as pd
  23. from datasets import load_dataset
  24. from evaluation.utils.shared import (
  25. EvalMetadata,
  26. codeact_user_response,
  27. make_metadata,
  28. prepare_dataset,
  29. run_evaluation,
  30. )
  31. from opendevin.controller.agent import Agent
  32. from opendevin.controller.state.state import State
  33. from opendevin.core.config import get_llm_config_arg, get_parser, load_app_config
  34. from opendevin.core.logger import get_console_handler
  35. from opendevin.core.logger import opendevin_logger as logger
  36. from opendevin.core.main import run_agent_controller
  37. from opendevin.events.action import Action, AgentFinishAction, MessageAction
  38. from opendevin.events.observation import Observation
  39. from opendevin.llm.llm import LLM
  40. config = load_app_config()
  41. ACTION_FORMAT = """
  42. <<FINAL_ANSWER||
  43. <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).)
  44. ||FINAL_ANSWER>>
  45. """.strip()
  46. def gpqa_codeact_user_response(
  47. state: State,
  48. encapsulate_solution: bool = False,
  49. try_parse: Callable[[Action], str] | None = None,
  50. ) -> str:
  51. msg = (
  52. 'Please continue working on the task on whatever approach you think is suitable.\n'
  53. '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'
  54. 'If you have finished reporting the answer in the expected format, (and only once that is done), please run the following command to submit: <execute_bash> exit </execute_bash>.\n'
  55. 'Again you are being told a million times to first report the answer in the requested format (see again below for reference) before exiting. DO NOT EXIT WITHOUT REPORTING THE ANSWER FIRST.\n'
  56. 'That is, when you have decided on the answer report in the following format:\n'
  57. f'{ACTION_FORMAT}\n'
  58. '<execute_bash> exit </execute_bash>\n'
  59. 'IMPORTANT: YOU SHOULD NEVER ASK FOR HUMAN HELP TO SOLVE THIS TASK.\n'
  60. )
  61. return msg
  62. AGENT_CLS_TO_FAKE_USER_RESPONSE_FN = {'CodeActAgent': codeact_user_response}
  63. AGENT_CLS_TO_INST_SUFFIX = {
  64. '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'
  65. }
  66. def parse_final_answer(final_answer: str | None) -> str | None:
  67. """Parse the final answer from the final message generated by the agent
  68. to extract the final answer. The final answer is usually enclosed in the format:
  69. <<FINAL_ANSWER||
  70. <insert correct answer here>
  71. ||FINAL_ANSWER>>
  72. """
  73. # to do this first extract the part enclosed in the format <<FINAL_ANSWER|| ... ||FINAL_ANSWER>>
  74. pattern = re.compile(r'<<FINAL_ANSWER\|\|(.*?)\|\|FINAL_ANSWER>>', re.DOTALL)
  75. match = pattern.search(final_answer)
  76. # and then strip it, remove any leading/trailing spaces line breaks etc.
  77. answer = match.group(1).strip()
  78. # finally capitalize it
  79. answer = answer.upper()
  80. # and then return A, B, C, D depending on whether the answer A, B, C, D is found in the final answer
  81. for letter in ['A', 'B', 'C', 'D']:
  82. if letter in answer:
  83. return letter
  84. def compare_answers(model_output: str | None, ground_truth: str):
  85. """Compare the predicted answer with the ground truth answer"""
  86. try:
  87. # parse the final answer from model output
  88. predicted_answer = parse_final_answer(model_output)
  89. except Exception as e:
  90. # Log the exception
  91. logger.error(f'An error occurred: {e}\n defaulting to random guess ...')
  92. # choose a random answer if the model output is not in the correct format
  93. predicted_answer = random.choice(['A', 'B', 'C', 'D'])
  94. logger.info('#############################################')
  95. logger.info(f'Predicted answer: {predicted_answer}')
  96. logger.info(f'Ground truth answer: {ground_truth}')
  97. logger.info('#############################################')
  98. return predicted_answer == ground_truth
  99. def convert_instance_dict(instance):
  100. """Used for preprocessing the hf dataset into a format that can be used by the agent.
  101. Reads and extracts relevant information from the dataset instance.
  102. """
  103. out_instance_dict = {}
  104. out_instance_dict['question'] = instance['Question']
  105. correct_answer = instance['Correct Answer']
  106. out_instance_dict['choices'] = [
  107. correct_answer,
  108. instance['Incorrect Answer 1'],
  109. instance['Incorrect Answer 2'],
  110. instance['Incorrect Answer 3'],
  111. ]
  112. # Randomize the order of choices
  113. random.shuffle(out_instance_dict['choices'])
  114. # Find the index of the correct answer after shuffling and store it as a letter (A/B/C/D)
  115. correct_index = out_instance_dict['choices'].index(correct_answer)
  116. correct_letter = chr(
  117. 65 + correct_index
  118. ) # Convert index (0-3) to corresponding letter (A-D)
  119. out_instance_dict['correct_solution'] = correct_letter
  120. return out_instance_dict
  121. def process_instance(
  122. instance: pd.Series,
  123. metadata: EvalMetadata,
  124. reset_logger: bool = True,
  125. ):
  126. # Create the agent
  127. agent = Agent.get_cls(metadata.agent_class)(llm=LLM(config=metadata.llm_config))
  128. old_workspace_mount_path = config.workspace_mount_path
  129. old_workspace_base = config.workspace_base
  130. try:
  131. workspace_mount_path = os.path.join(
  132. config.workspace_mount_path, '_eval_workspace'
  133. )
  134. # create process-specific workspace dir
  135. workspace_mount_path = os.path.join(workspace_mount_path, str(os.getpid()))
  136. pathlib.Path(workspace_mount_path).mkdir(parents=True, exist_ok=True)
  137. # reset workspace to config
  138. config.workspace_base = workspace_mount_path
  139. config.workspace_mount_path = workspace_mount_path
  140. # Setup the logger properly, so you can run multi-processing to parallelize the evaluation
  141. if reset_logger:
  142. # Set up logger
  143. log_file = os.path.join(
  144. metadata.eval_output_dir, 'logs', f'instance_{instance.instance_id}.log'
  145. )
  146. # Remove all existing handlers from logger
  147. for handler in logger.handlers[:]:
  148. logger.removeHandler(handler)
  149. # add back the console handler to print ONE line
  150. logger.addHandler(get_console_handler())
  151. logger.info(
  152. f'Starting evaluation for instance {instance.instance_id}.\nHint: run "tail -f {log_file}" to see live logs in a separate shell'
  153. )
  154. # Remove all existing handlers from logger
  155. for handler in logger.handlers[:]:
  156. logger.removeHandler(handler)
  157. file_handler = logging.FileHandler(log_file)
  158. file_handler.setFormatter(
  159. logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
  160. )
  161. logger.addHandler(file_handler)
  162. else:
  163. logger.info(f'Starting evaluation for instance {instance.instance_id}.')
  164. logger.info(f'Process-specific workspace mounted at {workspace_mount_path}')
  165. # ======= Run the agent on the instance =======
  166. # Prepare instruction for the agent using suggested format in gpqa codebase
  167. instruction = f"""
  168. What is the correct answer to this question:\n
  169. {instance['question']}\n
  170. Choices:\n
  171. (A) {instance['choices'][0]}\n
  172. (B) {instance['choices'][1]}\n
  173. (C) {instance['choices'][2]}\n
  174. (D) {instance['choices'][3]}\n
  175. \n\n
  176. MOST IMPORTANT: Format your response as follows:
  177. {ACTION_FORMAT}
  178. Additional Instructions:
  179. - Do not try to solve the question in a single step. Break it down into smaller steps.
  180. - You should ONLY interact with the environment provided to you AND NEVER ASK FOR HUMAN HELP.
  181. - SUPER IMPORTANT: When you have reported the answer to the user in the requested format, (and only once that is done) in the next turn, please run the following command: <execute_bash> exit </execute_bash>.
  182. - Again you are being told a million times to first report the answer in the requested format (see again below for reference) before exiting. DO NOT EXIT WITHOUT REPORTING THE ANSWER FIRST.
  183. That is, when you have decided on the answer report in the following format:
  184. {ACTION_FORMAT}
  185. <execute_bash> exit </execute_bash>
  186. Again do not quit without reporting the answer first.
  187. Ok now its time to start solving the question. Good luck!
  188. """
  189. # Here's how you can run the agent (similar to the `main` function) and get the final task state
  190. state: State | None = asyncio.run(
  191. run_agent_controller(
  192. agent,
  193. instruction,
  194. max_iterations=metadata.max_iterations,
  195. max_budget_per_task=config.max_budget_per_task,
  196. fake_user_response_fn=AGENT_CLS_TO_FAKE_USER_RESPONSE_FN.get(
  197. agent.__class__.__name__
  198. ),
  199. sid=f'gptq_{str(instance.instance_id)}',
  200. )
  201. )
  202. assert state is not None, 'State should not be None.'
  203. # ======= Attempt to evaluate the agent's edits =======
  204. question_choices = {
  205. 'A': instance['choices'][0],
  206. 'B': instance['choices'][1],
  207. 'C': instance['choices'][2],
  208. 'D': instance['choices'][3],
  209. }
  210. # get the final message from the state history (default to empty if not found)
  211. found_answers = {
  212. 'A': False,
  213. 'B': False,
  214. 'C': False,
  215. 'D': False,
  216. }
  217. for event in state.history.get_events(reverse=True):
  218. if (
  219. isinstance(event, AgentFinishAction)
  220. and event.source != 'user'
  221. and '<<FINAL_ANSWER||' in event.thought
  222. ):
  223. final_message = event.thought
  224. break
  225. elif (
  226. isinstance(event, MessageAction)
  227. and event.source != 'user'
  228. and '<<FINAL_ANSWER||' in event.content
  229. ):
  230. final_message = event.content
  231. break
  232. elif isinstance(event, Observation):
  233. for option, option_text in question_choices.items():
  234. if option_text in event.content:
  235. found_answers[option] = True
  236. else:
  237. final_message = None
  238. found_options = [option for option, found in found_answers.items() if found]
  239. logger.info('#############################################')
  240. logger.info(f'Final message generated by the agent: {final_message}')
  241. logger.info('#############################################')
  242. # check if the model output matches the ground truth
  243. test_result = compare_answers(final_message, instance.correct_solution)
  244. if final_message is None and len(found_options) > 0:
  245. _selected = random.choice(found_options)
  246. # if the final message is None, then the agent did not report the answer in the correct format
  247. # so we randomly select one of the found options and compare it with the correct solution
  248. test_result = _selected == instance.correct_solution
  249. logger.info('#############################################')
  250. logger.info('Agent did not report the answer in the correct format.')
  251. logger.info(f'Found options: {found_options}')
  252. logger.info(f'Selected option: {_selected}')
  253. logger.info('#############################################')
  254. logger.info('#############################################')
  255. logger.info(f'Test result: {test_result}')
  256. logger.info('#############################################')
  257. # If you are working on some simpler benchmark that only evaluates the final model output (e.g., in a MessageAction)
  258. # You can simply get the LAST `MessageAction` from the returned `state.history` and parse it for evaluation.
  259. if state is None:
  260. raise ValueError('State should not be None.')
  261. metrics = state.metrics.get() if state.metrics else None
  262. # Save the output
  263. output = {
  264. 'task_id': instance.task_id,
  265. 'instance_id': instance.instance_id,
  266. 'instruction': instruction,
  267. 'metadata': metadata.model_dump(),
  268. 'history': state.history.compatibility_for_eval_history_pairs(),
  269. 'metrics': metrics,
  270. 'error': state.last_error if state and state.last_error else None,
  271. 'test_result': {
  272. 'result': test_result,
  273. 'found_answers': found_answers,
  274. 'last_message': final_message,
  275. },
  276. }
  277. except Exception:
  278. logger.error('Process instance failed')
  279. raise
  280. finally:
  281. config.workspace_mount_path = old_workspace_mount_path
  282. config.workspace_base = old_workspace_base
  283. return output
  284. if __name__ == '__main__':
  285. parser = get_parser()
  286. # data split must be one of 'gpqa_main', 'gqpa_diamond', 'gpqa_experts', 'gpqa_extended'
  287. parser.add_argument(
  288. '--data-split',
  289. type=str,
  290. choices=['gpqa_main', 'gpqa_diamond', 'gpqa_experts', 'gpqa_extended'],
  291. default='gpqa_diamond',
  292. help='data split to evaluate, eg. gpqa_diamond',
  293. )
  294. args, _ = parser.parse_known_args()
  295. llm_config = get_llm_config_arg(args.llm_config) if args.llm_config else config.llm
  296. logger.info(f'Config for evaluation: {config}')
  297. # NOTE: It is preferable to load datasets from huggingface datasets and perform post-processing
  298. # so we don't need to manage file uploading to OpenDevin's repo
  299. dataset = load_dataset('Idavidrein/gpqa', args.data_split)
  300. gpqa_dataset = dataset['train']
  301. # preprocess the dataset
  302. gpqa_dataset = gpqa_dataset.map(convert_instance_dict)
  303. gpqa_dataset = gpqa_dataset.to_pandas()
  304. # Add a new column 'instance_id' with the index
  305. gpqa_dataset['instance_id'] = gpqa_dataset.index
  306. gpqa_dataset['task_id'] = gpqa_dataset.index
  307. # gpqa_dataset = dataset['train'].to_pandas().sort_values(by='id').reset_index(drop=True)
  308. if args.agent_cls != 'CodeActAgent':
  309. raise ValueError(
  310. f'Agent class {args.agent_cls} not supported for GPQA evaluation.'
  311. )
  312. metadata = make_metadata(
  313. llm_config=llm_config,
  314. dataset_name=args.data_split,
  315. agent_class=args.agent_cls,
  316. max_iterations=args.max_iterations,
  317. eval_note=args.eval_note,
  318. eval_output_dir=args.eval_output_dir,
  319. data_split=args.data_split,
  320. )
  321. output_file = os.path.join(metadata.eval_output_dir, 'output.jsonl')
  322. prepared_dataset = prepare_dataset(
  323. gpqa_dataset, output_file, args.eval_n_limit, 'task_id'
  324. )
  325. run_evaluation(
  326. dataset=prepared_dataset,
  327. metadata=metadata,
  328. output_file=output_file,
  329. num_workers=args.eval_num_workers,
  330. process_instance_func=process_instance,
  331. id_column='task_id',
  332. )