run_infer.py 9.1 KB

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