run_infer.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368
  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 os
  17. import random
  18. import re
  19. from typing import Callable
  20. import pandas as pd
  21. from datasets import load_dataset
  22. from evaluation.utils.shared import (
  23. EvalMetadata,
  24. EvalOutput,
  25. compatibility_for_eval_history_pairs,
  26. make_metadata,
  27. prepare_dataset,
  28. reset_logger_for_multiprocessing,
  29. run_evaluation,
  30. )
  31. from openhands.controller.state.state import State
  32. from openhands.core.config import (
  33. AppConfig,
  34. SandboxConfig,
  35. get_llm_config_arg,
  36. get_parser,
  37. )
  38. from openhands.core.logger import openhands_logger as logger
  39. from openhands.core.main import create_runtime, run_controller
  40. from openhands.events.action import (
  41. Action,
  42. AgentFinishAction,
  43. MessageAction,
  44. )
  45. from openhands.events.observation import Observation
  46. from openhands.utils.async_utils import call_async_from_sync
  47. ACTION_FORMAT = """
  48. <<FINAL_ANSWER||
  49. <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).)
  50. ||FINAL_ANSWER>>
  51. """.strip()
  52. def get_config(
  53. metadata: EvalMetadata,
  54. ) -> AppConfig:
  55. config = AppConfig(
  56. default_agent=metadata.agent_class,
  57. run_as_openhands=False,
  58. runtime='eventstream',
  59. max_iterations=metadata.max_iterations,
  60. sandbox=SandboxConfig(
  61. base_container_image='python:3.12-bookworm',
  62. enable_auto_lint=True,
  63. use_host_network=False,
  64. ),
  65. # do not mount workspace
  66. workspace_base=None,
  67. workspace_mount_path=None,
  68. )
  69. config.set_llm_config(metadata.llm_config)
  70. return config
  71. def gpqa_codeact_user_response(
  72. state: State,
  73. encapsulate_solution: bool = False,
  74. try_parse: Callable[[Action], str] | None = None,
  75. ) -> str:
  76. msg = (
  77. 'Please continue working on the task on whatever approach you think is suitable.\n'
  78. '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'
  79. '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'
  80. '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'
  81. 'That is, when you have decided on the answer report in the following format:\n'
  82. f'{ACTION_FORMAT}\n'
  83. '<execute_bash> exit </execute_bash>\n'
  84. 'IMPORTANT: YOU SHOULD NEVER ASK FOR HUMAN HELP TO SOLVE THIS TASK.\n'
  85. )
  86. return msg
  87. AGENT_CLS_TO_FAKE_USER_RESPONSE_FN = {'CodeActAgent': gpqa_codeact_user_response}
  88. AGENT_CLS_TO_INST_SUFFIX = {
  89. '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'
  90. }
  91. def parse_final_answer(final_answer: str | None) -> str | None:
  92. """Parse the final answer from the final message generated by the agent
  93. to extract the final answer. The final answer is usually enclosed in the format:
  94. <<FINAL_ANSWER||
  95. <insert correct answer here>
  96. ||FINAL_ANSWER>>
  97. """
  98. # to do this first extract the part enclosed in the format <<FINAL_ANSWER|| ... ||FINAL_ANSWER>>
  99. pattern = re.compile(r'<<FINAL_ANSWER\|\|(.*?)\|\|FINAL_ANSWER>>', re.DOTALL)
  100. match = pattern.search(final_answer)
  101. # and then strip it, remove any leading/trailing spaces line breaks etc.
  102. answer = match.group(1).strip()
  103. # finally capitalize it
  104. answer = answer.upper()
  105. # and then return A, B, C, D depending on whether the answer A, B, C, D is found in the final answer
  106. for letter in ['A', 'B', 'C', 'D']:
  107. if letter in answer:
  108. return letter
  109. def compare_answers(model_output: str | None, ground_truth: str):
  110. """Compare the predicted answer with the ground truth answer"""
  111. try:
  112. # parse the final answer from model output
  113. predicted_answer = parse_final_answer(model_output)
  114. except Exception as e:
  115. # Log the exception
  116. logger.error(f'An error occurred: {e}\n defaulting to random guess ...')
  117. # choose a random answer if the model output is not in the correct format
  118. predicted_answer = random.choice(['A', 'B', 'C', 'D'])
  119. logger.info('#############################################')
  120. logger.info(f'Predicted answer: {predicted_answer}')
  121. logger.info(f'Ground truth answer: {ground_truth}')
  122. logger.info('#############################################')
  123. return predicted_answer == ground_truth
  124. def convert_instance_dict(instance):
  125. """Used for preprocessing the hf dataset into a format that can be used by the agent.
  126. Reads and extracts relevant information from the dataset instance.
  127. """
  128. out_instance_dict = {}
  129. out_instance_dict['question'] = instance['Question']
  130. correct_answer = instance['Correct Answer']
  131. out_instance_dict['choices'] = [
  132. correct_answer,
  133. instance['Incorrect Answer 1'],
  134. instance['Incorrect Answer 2'],
  135. instance['Incorrect Answer 3'],
  136. ]
  137. # Randomize the order of choices
  138. random.shuffle(out_instance_dict['choices'])
  139. # Find the index of the correct answer after shuffling and store it as a letter (A/B/C/D)
  140. correct_index = out_instance_dict['choices'].index(correct_answer)
  141. correct_letter = chr(
  142. 65 + correct_index
  143. ) # Convert index (0-3) to corresponding letter (A-D)
  144. out_instance_dict['correct_solution'] = correct_letter
  145. return out_instance_dict
  146. def process_instance(
  147. instance: pd.Series,
  148. metadata: EvalMetadata,
  149. reset_logger: bool = True,
  150. ):
  151. config = get_config(metadata)
  152. # Setup the logger properly, so you can run multi-processing to parallelize the evaluation
  153. if reset_logger:
  154. log_dir = os.path.join(metadata.eval_output_dir, 'infer_logs')
  155. reset_logger_for_multiprocessing(logger, instance['instance_id'], log_dir)
  156. else:
  157. logger.info(f'Starting evaluation for instance {instance["instance_id"]}.')
  158. # ======= Run the agent on the instance =======
  159. # Prepare instruction for the agent using suggested format in gpqa codebase
  160. instruction = f"""
  161. What is the correct answer to this question:\n
  162. {instance['question']}\n
  163. Choices:\n
  164. (A) {instance['choices'][0]}\n
  165. (B) {instance['choices'][1]}\n
  166. (C) {instance['choices'][2]}\n
  167. (D) {instance['choices'][3]}\n
  168. \n\n
  169. MOST IMPORTANT: Format your response as follows:
  170. {ACTION_FORMAT}
  171. Additional Instructions:
  172. - Do not try to solve the question in a single step. Break it down into smaller steps.
  173. - You should ONLY interact with the environment provided to you AND NEVER ASK FOR HUMAN HELP.
  174. - 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>.
  175. - 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.
  176. That is, when you have decided on the answer report in the following format:
  177. {ACTION_FORMAT}
  178. <execute_bash> exit </execute_bash>
  179. Again do not quit without reporting the answer first.
  180. Ok now its time to start solving the question. Good luck!
  181. """
  182. runtime = create_runtime(config)
  183. call_async_from_sync(runtime.connect)
  184. state: State | None = asyncio.run(
  185. run_controller(
  186. config=config,
  187. initial_user_action=MessageAction(content=instruction),
  188. runtime=runtime,
  189. fake_user_response_fn=AGENT_CLS_TO_FAKE_USER_RESPONSE_FN.get(
  190. metadata.agent_class
  191. ),
  192. )
  193. )
  194. assert state is not None, 'State should not be None.'
  195. # ======= Attempt to evaluate the agent's edits =======
  196. question_choices = {
  197. 'A': instance['choices'][0],
  198. 'B': instance['choices'][1],
  199. 'C': instance['choices'][2],
  200. 'D': instance['choices'][3],
  201. }
  202. # get the final message from the state history (default to empty if not found)
  203. found_answers = {
  204. 'A': False,
  205. 'B': False,
  206. 'C': False,
  207. 'D': False,
  208. }
  209. for event in reversed(state.history):
  210. if (
  211. isinstance(event, AgentFinishAction)
  212. and event.source != 'user'
  213. and '<<FINAL_ANSWER||' in event.thought
  214. ):
  215. final_message = event.thought
  216. break
  217. elif (
  218. isinstance(event, MessageAction)
  219. and event.source != 'user'
  220. and '<<FINAL_ANSWER||' in event.content
  221. ):
  222. final_message = event.content
  223. break
  224. elif isinstance(event, Observation):
  225. for option, option_text in question_choices.items():
  226. if option_text in event.content:
  227. found_answers[option] = True
  228. else:
  229. final_message = None
  230. found_options = [option for option, found in found_answers.items() if found]
  231. logger.info('#############################################')
  232. logger.info(f'Final message generated by the agent: {final_message}')
  233. logger.info('#############################################')
  234. # check if the model output matches the ground truth
  235. test_result = compare_answers(final_message, instance.correct_solution)
  236. if final_message is None and len(found_options) > 0:
  237. _selected = random.choice(found_options)
  238. # if the final message is None, then the agent did not report the answer in the correct format
  239. # so we randomly select one of the found options and compare it with the correct solution
  240. test_result = _selected == instance.correct_solution
  241. logger.info('#############################################')
  242. logger.info('Agent did not report the answer in the correct format.')
  243. logger.info(f'Found options: {found_options}')
  244. logger.info(f'Selected option: {_selected}')
  245. logger.info('#############################################')
  246. logger.info('#############################################')
  247. logger.info(f'Test result: {test_result}')
  248. logger.info('#############################################')
  249. # If you are working on some simpler benchmark that only evaluates the final model output (e.g., in a MessageAction)
  250. # You can simply get the LAST `MessageAction` from the returned `state.history` and parse it for evaluation.
  251. if state is None:
  252. raise ValueError('State should not be None.')
  253. metrics = state.metrics.get() if state.metrics else None
  254. # Save the output
  255. output = EvalOutput(
  256. instance_id=str(instance.instance_id),
  257. instruction=instruction,
  258. metadata=metadata,
  259. history=compatibility_for_eval_history_pairs(state.history),
  260. metrics=metrics,
  261. error=state.last_error if state and state.last_error else None,
  262. test_result={
  263. 'result': test_result,
  264. 'found_answers': found_answers,
  265. 'last_message': final_message,
  266. },
  267. )
  268. return output
  269. if __name__ == '__main__':
  270. parser = get_parser()
  271. # data split must be one of 'gpqa_main', 'gqpa_diamond', 'gpqa_experts', 'gpqa_extended'
  272. parser.add_argument(
  273. '--data-split',
  274. type=str,
  275. choices=['gpqa_main', 'gpqa_diamond', 'gpqa_experts', 'gpqa_extended'],
  276. default='gpqa_diamond',
  277. help='data split to evaluate, eg. gpqa_diamond',
  278. )
  279. args, _ = parser.parse_known_args()
  280. llm_config = None
  281. if args.llm_config:
  282. llm_config = get_llm_config_arg(args.llm_config)
  283. if llm_config is None:
  284. raise ValueError(f'Could not find LLM config: --llm_config {args.llm_config}')
  285. # NOTE: It is preferable to load datasets from huggingface datasets and perform post-processing
  286. # so we don't need to manage file uploading to OpenHands's repo
  287. dataset = load_dataset('Idavidrein/gpqa', args.data_split)
  288. gpqa_dataset = dataset['train']
  289. # preprocess the dataset
  290. gpqa_dataset = gpqa_dataset.map(convert_instance_dict)
  291. gpqa_dataset = gpqa_dataset.to_pandas()
  292. # Add a new column 'instance_id' with the index
  293. gpqa_dataset['instance_id'] = gpqa_dataset.index
  294. if args.agent_cls != 'CodeActAgent':
  295. raise ValueError(
  296. f'Agent class {args.agent_cls} not supported for GPQA evaluation.'
  297. )
  298. metadata = make_metadata(
  299. llm_config=llm_config,
  300. dataset_name=args.data_split,
  301. agent_class=args.agent_cls,
  302. max_iterations=args.max_iterations,
  303. eval_note=args.eval_note,
  304. eval_output_dir=args.eval_output_dir,
  305. data_split=args.data_split,
  306. )
  307. output_file = os.path.join(metadata.eval_output_dir, 'output.jsonl')
  308. prepared_dataset = prepare_dataset(gpqa_dataset, output_file, args.eval_n_limit)
  309. run_evaluation(
  310. dataset=prepared_dataset,
  311. metadata=metadata,
  312. output_file=output_file,
  313. num_workers=args.eval_num_workers,
  314. process_instance_func=process_instance,
  315. )