run_infer.py 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310
  1. import asyncio
  2. import os
  3. import pandas as pd
  4. from datasets import load_dataset
  5. from evaluation.utils.shared import (
  6. EvalMetadata,
  7. EvalOutput,
  8. codeact_user_response,
  9. make_metadata,
  10. prepare_dataset,
  11. reset_logger_for_multiprocessing,
  12. run_evaluation,
  13. )
  14. from openhands.controller.state.state import State
  15. from openhands.core.config import (
  16. AppConfig,
  17. SandboxConfig,
  18. get_llm_config_arg,
  19. get_parser,
  20. )
  21. from openhands.core.logger import openhands_logger as logger
  22. from openhands.core.main import create_runtime, run_controller
  23. from openhands.events.action import (
  24. AgentFinishAction,
  25. CmdRunAction,
  26. IPythonRunCellAction,
  27. MessageAction,
  28. )
  29. from openhands.events.observation import CmdOutputObservation
  30. from openhands.runtime.runtime import Runtime
  31. AGENT_CLS_TO_FAKE_USER_RESPONSE_FN = {
  32. 'CodeActAgent': codeact_user_response,
  33. }
  34. AGENT_CLS_TO_INST_SUFFIX = {
  35. 'CodeActAgent': 'When you think you have solved the question, please first send your answer to user through message and then exit.\n'
  36. }
  37. def get_config(
  38. metadata: EvalMetadata,
  39. ) -> AppConfig:
  40. config = AppConfig(
  41. default_agent=metadata.agent_class,
  42. run_as_openhands=False,
  43. runtime='eventstream',
  44. max_iterations=metadata.max_iterations,
  45. sandbox=SandboxConfig(
  46. base_container_image='xingyaoww/od-eval-logic-reasoning:v1.0',
  47. enable_auto_lint=True,
  48. use_host_network=False,
  49. runtime_extra_deps='$OD_INTERPRETER_PATH -m pip install scitools-pyke',
  50. ),
  51. # do not mount workspace
  52. workspace_base=None,
  53. workspace_mount_path=None,
  54. )
  55. config.set_llm_config(metadata.llm_config)
  56. return config
  57. def get_choice(answer_str):
  58. choices = [
  59. 'A',
  60. 'B',
  61. 'C',
  62. 'D',
  63. 'E',
  64. 'F',
  65. 'G',
  66. 'H',
  67. 'A)',
  68. 'B)',
  69. 'C)',
  70. 'D)',
  71. 'E)',
  72. 'F)',
  73. 'G)',
  74. 'H)',
  75. 'A.',
  76. 'B.',
  77. 'C.',
  78. 'D.',
  79. 'E.',
  80. 'F.',
  81. 'G.',
  82. 'H.',
  83. ]
  84. for c in choices:
  85. if answer_str.startswith(c):
  86. return c.replace(')', '')
  87. if answer_str.startswith(':'):
  88. return answer_str.replace(':', '').replace('.', '').strip()
  89. return None
  90. def get_test_result(
  91. model_answer: str,
  92. ground_truth: str,
  93. ) -> dict[str, bool]:
  94. gold_answer = ground_truth.replace('(', '').replace(')', '').strip()
  95. answer_str = model_answer if model_answer is not None else ''
  96. prediction = get_choice(answer_str)
  97. indicators = [
  98. 'the correct option is',
  99. 'the correct answer is',
  100. 'The correct answer is',
  101. 'The correct option is',
  102. 'the answer is',
  103. ]
  104. if prediction is None:
  105. for indicator in indicators:
  106. if answer_str.find(indicator) >= 0:
  107. answer_str = answer_str.split(indicator)[1].strip()
  108. prediction = get_choice(answer_str)
  109. break
  110. isTrue = prediction == gold_answer
  111. test_result = {'result': isTrue}
  112. return test_result
  113. CUR_EVAL_DIR = os.path.dirname(__file__)
  114. async def initialize_runtime(
  115. runtime: Runtime,
  116. instance: pd.Series, # this argument is not required
  117. ):
  118. """Initialize the runtime for the agent.
  119. This function is called before the runtime is used to run the agent.
  120. """
  121. logger.info(f"{'-' * 50} BEGIN Runtime Initialization Fn {'-' * 50}")
  122. obs: CmdOutputObservation
  123. # Set instance id
  124. action = CmdRunAction(command='mkdir -p /workspace')
  125. logger.info(action, extra={'msg_type': 'ACTION'})
  126. obs = await runtime.run_action(action)
  127. assert obs.exit_code == 0
  128. action = CmdRunAction(command='cd /workspace')
  129. logger.info(action, extra={'msg_type': 'ACTION'})
  130. obs = await runtime.run_action(action)
  131. assert obs.exit_code == 0
  132. # copy logic_inference.py to /workspace
  133. await runtime.copy_to(
  134. os.path.join(CUR_EVAL_DIR, 'logic_inference.py'), '/workspace'
  135. )
  136. # check if the file exists
  137. obs = await runtime.run_action(CmdRunAction(command='ls /workspace'))
  138. assert obs.exit_code == 0
  139. assert 'logic_inference.py' in obs.content
  140. await runtime.add_env_vars({'DATASET_NAME': metadata.dataset})
  141. action = CmdRunAction(command='mkdir -p /workspace/.cache_program')
  142. logger.info(action, extra={'msg_type': 'ACTION'})
  143. obs = await runtime.run_action(action)
  144. assert obs.exit_code == 0
  145. action = IPythonRunCellAction(code='%pip install scitools-pyke')
  146. logger.info(action, extra={'msg_type': 'ACTION'})
  147. ipynb_obs = await runtime.run_action(action)
  148. logger.info(ipynb_obs, extra={'msg_type': 'OBSERVATION'})
  149. logger.info(f"{'-' * 50} END Runtime Initialization Fn {'-' * 50}")
  150. # Prepare instruction
  151. with open(os.path.join(CUR_EVAL_DIR, 'instruction.txt'), 'r') as f:
  152. INSTRUCTION_TEMPLATE = f.read()
  153. async def process_instance(
  154. instance: pd.Series,
  155. metadata: EvalMetadata,
  156. reset_logger: bool = True,
  157. ):
  158. config = get_config(metadata)
  159. # Setup the logger properly, so you can run multi-processing to parallelize the evaluation
  160. if reset_logger:
  161. log_dir = os.path.join(metadata.eval_output_dir, 'infer_logs')
  162. reset_logger_for_multiprocessing(logger, instance['instance_id'], log_dir)
  163. else:
  164. logger.info(f'Starting evaluation for instance {instance["instance_id"]}.')
  165. instance_logic_programs = instance['raw_logic_programs'][0].strip()
  166. instruction = (
  167. INSTRUCTION_TEMPLATE.replace('[[dataset_name]]', dataset_name)
  168. .replace('[[logic_programs]]', instance_logic_programs)
  169. .replace('[[logic_inference_path.py]]', '/workspace/logic_inference.py')
  170. )
  171. # NOTE: You can actually set slightly different instruction for different agents
  172. instruction += AGENT_CLS_TO_INST_SUFFIX[metadata.agent_class]
  173. # use a session id for concurrent evaluation
  174. sid = instance['instance_id']
  175. runtime = await create_runtime(config, sid=sid)
  176. await initialize_runtime(runtime, instance)
  177. # Here's how you can run the agent (similar to the `main` function) and get the final task state
  178. state: State | None = asyncio.run(
  179. run_controller(
  180. config=config,
  181. task_str=instruction,
  182. runtime=runtime,
  183. fake_user_response_fn=AGENT_CLS_TO_FAKE_USER_RESPONSE_FN.get(
  184. metadata.agent_class
  185. ),
  186. )
  187. )
  188. # ======= Attempt to evaluate the agent's edits =======
  189. # If you are working on simpler benchmark that only evaluates the final model output (e.g., in a MessageAction)
  190. # You can simply get the LAST `MessageAction` from the returned `state.history` and parse it for evaluation.
  191. if state is None:
  192. raise ValueError('State should not be None.')
  193. final_message = ''
  194. for event in state.history.get_events(reverse=True):
  195. if isinstance(event, AgentFinishAction):
  196. final_message = event.thought
  197. break
  198. elif isinstance(event, MessageAction):
  199. final_message = event.content
  200. break
  201. final_message = final_message.strip("'")
  202. logger.info(
  203. f'Predicted answer: {final_message}, Ground truth: {instance["answer"]}'
  204. )
  205. test_result = get_test_result(
  206. model_answer=final_message, ground_truth=instance['answer']
  207. )
  208. test_result['final_message'] = final_message
  209. metrics = state.metrics.get() if state.metrics else None
  210. # history is now available as a stream of events, rather than list of pairs of (Action, Observation)
  211. # for compatibility with the existing output format, we can remake the pairs here
  212. # remove when it becomes unnecessary
  213. histories = state.history.compatibility_for_eval_history_pairs()
  214. # Save the output
  215. output = EvalOutput(
  216. instance_id=instance['instance_id'],
  217. instruction=instruction,
  218. metadata=metadata,
  219. history=histories,
  220. metrics=metrics,
  221. error=state.last_error if state and state.last_error else None,
  222. test_result=test_result,
  223. )
  224. return output
  225. if __name__ == '__main__':
  226. parser = get_parser()
  227. parser.add_argument(
  228. '--dataset',
  229. type=str,
  230. help='the logic reasoning dataset to evaluate on {ProntoQA, ProofWriter}',
  231. default='ProofWriter',
  232. )
  233. parser.add_argument(
  234. '--data_split',
  235. type=str,
  236. help='data split to evaluate on {validation}', # right now we only support validation split
  237. default='validation',
  238. )
  239. args, _ = parser.parse_known_args()
  240. dataset_name = args.dataset
  241. data_split = args.data_split
  242. dataset = load_dataset(f'renma/{dataset_name}')
  243. dataset_df = dataset[data_split].to_pandas()
  244. dataset_df.rename(columns={'id': 'instance_id'}, inplace=True)
  245. llm_config = None
  246. if args.llm_config:
  247. llm_config = get_llm_config_arg(args.llm_config)
  248. if llm_config is None:
  249. raise ValueError(f'Could not find LLM config: --llm_config {args.llm_config}')
  250. metadata = make_metadata(
  251. llm_config,
  252. dataset_name,
  253. args.agent_cls,
  254. args.max_iterations,
  255. args.eval_note,
  256. args.eval_output_dir,
  257. )
  258. output_file = os.path.join(metadata.eval_output_dir, 'output.jsonl')
  259. instances = prepare_dataset(dataset_df, output_file, args.eval_n_limit)
  260. asyncio.run(
  261. run_evaluation(
  262. instances, metadata, output_file, args.eval_num_workers, process_instance
  263. )
  264. )