run_infer.py 9.3 KB

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