run_infer.py 14 KB

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