run_infer.py 9.3 KB

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