run_infer.py 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303
  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='$OH_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. 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 = 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 = runtime.run_action(action)
  131. assert obs.exit_code == 0
  132. # copy logic_inference.py to /workspace
  133. runtime.copy_to(os.path.join(CUR_EVAL_DIR, 'logic_inference.py'), '/workspace')
  134. # check if the file exists
  135. obs = runtime.run_action(CmdRunAction(command='ls /workspace'))
  136. assert obs.exit_code == 0
  137. assert 'logic_inference.py' in obs.content
  138. runtime.add_env_vars({'DATASET_NAME': metadata.dataset})
  139. action = CmdRunAction(command='mkdir -p /workspace/.cache_program')
  140. logger.info(action, extra={'msg_type': 'ACTION'})
  141. obs = runtime.run_action(action)
  142. assert obs.exit_code == 0
  143. action = IPythonRunCellAction(code='%pip install scitools-pyke')
  144. logger.info(action, extra={'msg_type': 'ACTION'})
  145. ipynb_obs = runtime.run_action(action)
  146. logger.info(ipynb_obs, extra={'msg_type': 'OBSERVATION'})
  147. logger.info(f"{'-' * 50} END Runtime Initialization Fn {'-' * 50}")
  148. # Prepare instruction
  149. with open(os.path.join(CUR_EVAL_DIR, 'instruction.txt'), 'r') as f:
  150. INSTRUCTION_TEMPLATE = f.read()
  151. def process_instance(
  152. instance: pd.Series,
  153. metadata: EvalMetadata,
  154. reset_logger: bool = True,
  155. ):
  156. config = get_config(metadata)
  157. # Setup the logger properly, so you can run multi-processing to parallelize the evaluation
  158. if reset_logger:
  159. log_dir = os.path.join(metadata.eval_output_dir, 'infer_logs')
  160. reset_logger_for_multiprocessing(logger, instance['instance_id'], log_dir)
  161. else:
  162. logger.info(f'Starting evaluation for instance {instance["instance_id"]}.')
  163. instance_logic_programs = instance['raw_logic_programs'][0].strip()
  164. instruction = (
  165. INSTRUCTION_TEMPLATE.replace('[[dataset_name]]', dataset_name)
  166. .replace('[[logic_programs]]', instance_logic_programs)
  167. .replace('[[logic_inference_path.py]]', '/workspace/logic_inference.py')
  168. )
  169. # NOTE: You can actually set slightly different instruction for different agents
  170. instruction += AGENT_CLS_TO_INST_SUFFIX[metadata.agent_class]
  171. runtime = create_runtime(config)
  172. initialize_runtime(runtime, instance)
  173. # Here's how you can run the agent (similar to the `main` function) and get the final task state
  174. state: State | None = asyncio.run(
  175. run_controller(
  176. config=config,
  177. initial_user_action=MessageAction(content=instruction),
  178. runtime=runtime,
  179. fake_user_response_fn=AGENT_CLS_TO_FAKE_USER_RESPONSE_FN.get(
  180. metadata.agent_class
  181. ),
  182. )
  183. )
  184. # ======= Attempt to evaluate the agent's edits =======
  185. # If you are working on simpler benchmark that only evaluates the final model output (e.g., in a MessageAction)
  186. # You can simply get the LAST `MessageAction` from the returned `state.history` and parse it for evaluation.
  187. if state is None:
  188. raise ValueError('State should not be None.')
  189. final_message = ''
  190. for event in state.history.get_events(reverse=True):
  191. if isinstance(event, AgentFinishAction):
  192. final_message = event.thought
  193. break
  194. elif isinstance(event, MessageAction):
  195. final_message = event.content
  196. break
  197. final_message = final_message.strip("'")
  198. logger.info(
  199. f'Predicted answer: {final_message}, Ground truth: {instance["answer"]}'
  200. )
  201. test_result = get_test_result(
  202. model_answer=final_message, ground_truth=instance['answer']
  203. )
  204. test_result['final_message'] = final_message
  205. metrics = state.metrics.get() if state.metrics else None
  206. # history is now available as a stream of events, rather than list of pairs of (Action, Observation)
  207. # for compatibility with the existing output format, we can remake the pairs here
  208. # remove when it becomes unnecessary
  209. histories = state.history.compatibility_for_eval_history_pairs()
  210. # Save the output
  211. output = EvalOutput(
  212. instance_id=instance['instance_id'],
  213. instruction=instruction,
  214. metadata=metadata,
  215. history=histories,
  216. metrics=metrics,
  217. error=state.last_error if state and state.last_error else None,
  218. test_result=test_result,
  219. )
  220. return output
  221. if __name__ == '__main__':
  222. parser = get_parser()
  223. parser.add_argument(
  224. '--dataset',
  225. type=str,
  226. help='the logic reasoning dataset to evaluate on {ProntoQA, ProofWriter}',
  227. default='ProofWriter',
  228. )
  229. parser.add_argument(
  230. '--data_split',
  231. type=str,
  232. help='data split to evaluate on {validation}', # right now we only support validation split
  233. default='validation',
  234. )
  235. args, _ = parser.parse_known_args()
  236. dataset_name = args.dataset
  237. data_split = args.data_split
  238. dataset = load_dataset(f'renma/{dataset_name}')
  239. dataset_df = dataset[data_split].to_pandas()
  240. dataset_df.rename(columns={'id': 'instance_id'}, inplace=True)
  241. llm_config = None
  242. if args.llm_config:
  243. llm_config = get_llm_config_arg(args.llm_config)
  244. if llm_config is None:
  245. raise ValueError(f'Could not find LLM config: --llm_config {args.llm_config}')
  246. metadata = make_metadata(
  247. llm_config,
  248. dataset_name,
  249. args.agent_cls,
  250. args.max_iterations,
  251. args.eval_note,
  252. args.eval_output_dir,
  253. )
  254. output_file = os.path.join(metadata.eval_output_dir, 'output.jsonl')
  255. instances = prepare_dataset(dataset_df, output_file, args.eval_n_limit)
  256. run_evaluation(
  257. instances, metadata, output_file, args.eval_num_workers, process_instance
  258. )