run_infer.py 9.1 KB

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