run_infer.py 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291
  1. import asyncio
  2. import functools
  3. import os
  4. from typing import Any
  5. import pandas as pd
  6. from datasets import load_dataset
  7. from evaluation.mint.datatypes import TaskState
  8. from evaluation.mint.env import SimplifiedEnv
  9. from evaluation.mint.prompts import ToolPromptTemplate
  10. from evaluation.mint.tasks import Task
  11. from evaluation.utils.shared import (
  12. EvalMetadata,
  13. EvalOutput,
  14. make_metadata,
  15. prepare_dataset,
  16. reset_logger_for_multiprocessing,
  17. run_evaluation,
  18. )
  19. from openhands.controller.state.state import State
  20. from openhands.core.config import (
  21. AppConfig,
  22. SandboxConfig,
  23. get_llm_config_arg,
  24. get_parser,
  25. )
  26. from openhands.core.logger import openhands_logger as logger
  27. from openhands.core.main import create_runtime, run_controller
  28. from openhands.events.action import (
  29. CmdRunAction,
  30. MessageAction,
  31. )
  32. from openhands.events.observation import CmdOutputObservation
  33. from openhands.runtime.runtime import Runtime
  34. def codeact_user_response_mint(state: State, task: Task, task_config: dict[str, int]):
  35. logger.info(f'Gold reference: {task.reference}')
  36. logger.info(f'Task config: {task_config}')
  37. env = SimplifiedEnv(
  38. agent_state=state,
  39. task=task,
  40. task_config=task_config,
  41. )
  42. last_action = state.history.get_last_action()
  43. result_state: TaskState = env.step(last_action.message or '')
  44. state.extra_data['task_state'] = result_state
  45. if not result_state.latest_output:
  46. # Task is finished
  47. msg = '/exit'
  48. else:
  49. msg = result_state.latest_output['content']
  50. logger.info('User response:' + msg)
  51. return msg
  52. AGENT_CLS_TO_FAKE_USER_RESPONSE_FN = {
  53. 'CodeActAgent': codeact_user_response_mint,
  54. }
  55. AGENT_CLS_TO_INST_SUFFIX = {
  56. 'CodeActAgent': '\nIMPORTANT: When your answer is confirmed by the user to be correct, you can exit using the following command: <execute_bash> exit </execute_bash>.\n'
  57. }
  58. with open(os.path.join(os.path.dirname(__file__), 'requirements.txt'), 'r') as f:
  59. MINT_DEPENDENCIES = f.read().splitlines()
  60. def load_incontext_example(task_name: str, with_tool: bool = True):
  61. assert with_tool, 'NOT with_tool is not supported yet'
  62. subset = {
  63. 'gsm8k': 'reasoning',
  64. 'math': 'reasoning',
  65. 'mmlu': 'reasoning',
  66. 'theoremqa': 'reasoning',
  67. 'mbpp': 'mbpp',
  68. 'humaneval': 'humaneval',
  69. }[task_name]
  70. with open(
  71. os.path.join(
  72. os.path.dirname(__file__),
  73. 'tasks',
  74. 'in_context_examples',
  75. subset,
  76. 'with_tool.txt',
  77. ),
  78. 'r',
  79. ) as f:
  80. return f.read()
  81. def get_config(
  82. metadata: EvalMetadata,
  83. ) -> AppConfig:
  84. config = AppConfig(
  85. default_agent=metadata.agent_class,
  86. run_as_openhands=False,
  87. runtime='eventstream',
  88. max_iterations=metadata.max_iterations,
  89. sandbox=SandboxConfig(
  90. base_container_image='xingyaoww/od-eval-mint:v1.0',
  91. enable_auto_lint=True,
  92. use_host_network=False,
  93. runtime_extra_deps=f'$OH_INTERPRETER_PATH -m pip install {" ".join(MINT_DEPENDENCIES)}',
  94. ),
  95. # do not mount workspace
  96. workspace_base=None,
  97. workspace_mount_path=None,
  98. )
  99. config.set_llm_config(metadata.llm_config)
  100. return config
  101. def initialize_runtime(runtime: Runtime):
  102. """Initialize the runtime for the agent.
  103. This function is called before the runtime is used to run the agent.
  104. """
  105. logger.info(f"{'-' * 50} BEGIN Runtime Initialization Fn {'-' * 50}")
  106. obs: CmdOutputObservation
  107. # Set instance id
  108. action = CmdRunAction(command='mkdir -p /workspace')
  109. logger.info(action, extra={'msg_type': 'ACTION'})
  110. obs = runtime.run_action(action)
  111. assert obs.exit_code == 0
  112. action = CmdRunAction(command='cd /workspace')
  113. logger.info(action, extra={'msg_type': 'ACTION'})
  114. obs = runtime.run_action(action)
  115. assert obs.exit_code == 0
  116. logger.info(f"{'-' * 50} END Runtime Initialization Fn {'-' * 50}")
  117. def process_instance(
  118. instance: Any,
  119. metadata: EvalMetadata,
  120. reset_logger: bool = True,
  121. ):
  122. config = get_config(metadata)
  123. # Setup the logger properly, so you can run multi-processing to parallelize the evaluation
  124. if reset_logger:
  125. log_dir = os.path.join(metadata.eval_output_dir, 'infer_logs')
  126. reset_logger_for_multiprocessing(logger, instance.instance_id, log_dir)
  127. else:
  128. logger.info(f'Starting evaluation for instance {instance.instance_id}.')
  129. # Prepare instruction
  130. assert metadata.details is not None
  131. instruction = ToolPromptTemplate(use_tool=True)(
  132. max_total_steps=metadata.max_iterations,
  133. max_propose_solution=metadata.details['max_propose_solution'],
  134. in_context_example=instance.in_context_example,
  135. task_prompt='Task:\n' + instance.prompt,
  136. )
  137. instruction += 'IMPORTANT: You should ONLY interact with the environment provided to you or provide the concise RESULT inside <solution> tag AND NEVER ASK FOR HUMAN HELP.\n'
  138. # NOTE: You can actually set slightly different instruction for different agents
  139. instruction += AGENT_CLS_TO_INST_SUFFIX[metadata.agent_class]
  140. # Here's how you can run the agent (similar to the `main` function) and get the final task state
  141. fake_user_response_fn = functools.partial(
  142. AGENT_CLS_TO_FAKE_USER_RESPONSE_FN[metadata.agent_class],
  143. task=instance,
  144. task_config={
  145. 'max_iterations': metadata.max_iterations,
  146. 'max_propose_solution': metadata.details['max_propose_solution'],
  147. },
  148. )
  149. runtime = create_runtime(config)
  150. initialize_runtime(runtime)
  151. state: State | None = asyncio.run(
  152. run_controller(
  153. config=config,
  154. initial_user_action=MessageAction(content=instruction),
  155. runtime=runtime,
  156. fake_user_response_fn=fake_user_response_fn,
  157. )
  158. )
  159. if state is None:
  160. raise ValueError('State should not be None.')
  161. task_state = None
  162. if 'task_state' in state.extra_data:
  163. task_state = state.extra_data['task_state']
  164. logger.info('Task state: ' + str(task_state.to_dict()))
  165. metrics = state.metrics.get() if state.metrics else None
  166. # history is now available as a stream of events, rather than list of pairs of (Action, Observation)
  167. # for compatibility with the existing output format, we can remake the pairs here
  168. # remove when it becomes unnecessary
  169. histories = state.history.compatibility_for_eval_history_pairs()
  170. # Save the output
  171. output = EvalOutput(
  172. instance_id=instance.instance_id,
  173. instance=instance.to_dict(),
  174. instruction=instruction,
  175. metadata=metadata,
  176. history=histories,
  177. metrics=metrics,
  178. error=state.last_error if state and state.last_error else None,
  179. test_result={
  180. 'success': task_state.success if task_state else False,
  181. },
  182. )
  183. return output
  184. if __name__ == '__main__':
  185. parser = get_parser()
  186. SUBSETS = [
  187. # Eurus subset: https://arxiv.org/abs/2404.02078
  188. 'math',
  189. # 'gsm8k',
  190. 'mmlu',
  191. 'theoremqa',
  192. 'mbpp',
  193. 'humaneval',
  194. ]
  195. parser.add_argument(
  196. '--subset',
  197. default='all',
  198. choices=SUBSETS + ['all'],
  199. type=str,
  200. help='subset of the dataset to be used',
  201. )
  202. parser.add_argument(
  203. '--max-propose-solution',
  204. default=2,
  205. type=int,
  206. help='maximum number of times the agent can propose a solution',
  207. )
  208. args, _ = parser.parse_known_args()
  209. # NOTE: It is preferable to load datasets from huggingface datasets and perform post-processing
  210. # so we don't need to manage file uploading to OpenHands's repo
  211. if args.subset == 'all':
  212. subsets = SUBSETS
  213. else:
  214. subsets = [args.subset]
  215. dataset_dfs = []
  216. for subset in subsets:
  217. in_context_example = load_incontext_example(subset)
  218. _cur_dataset = load_dataset(
  219. 'ryanhoangt/xingyaoww-mint-bench', name=subset, split='test'
  220. )
  221. logger.info(f'Loaded MINT - {subset} subset')
  222. _df = _cur_dataset.to_pandas().rename(columns={'id': 'instance_id'})
  223. _df['instance_id'] = _df['instance_id'].apply(lambda x: f'{subset}/{x}') # noqa
  224. _df['in_context_example'] = in_context_example
  225. dataset_dfs.append(_df)
  226. logger.info(f'Loaded {len(_df)} instances for subset: {subset}')
  227. dataset_df = pd.concat(dataset_dfs)
  228. logger.info(f'Loaded {len(dataset_df)} instances for subset: {subsets}')
  229. llm_config = None
  230. if args.llm_config:
  231. llm_config = get_llm_config_arg(args.llm_config)
  232. if llm_config is None:
  233. raise ValueError(f'Could not find LLM config: --llm_config {args.llm_config}')
  234. metadata = make_metadata(
  235. llm_config,
  236. f'MINT-{args.subset}',
  237. args.agent_cls,
  238. args.max_iterations,
  239. args.eval_note,
  240. args.eval_output_dir,
  241. details={'max_propose_solution': args.max_propose_solution},
  242. )
  243. output_file = os.path.join(metadata.eval_output_dir, 'output.jsonl')
  244. instances = prepare_dataset(dataset_df, output_file, args.eval_n_limit)
  245. run_evaluation(
  246. instances, metadata, output_file, args.eval_num_workers, process_instance
  247. )