run_infer.py 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305
  1. """Implements evaluation of agents on HumanEvalFix from the HumanEvalPack benchmark introduced in
  2. "OctoPack: Instruction Tuning Code Large Language Models" (https://arxiv.org/abs/2308.07124).
  3. Please see https://github.com/bigcode-project/bigcode-evaluation-harness/blob/main/bigcode_eval/tasks/humanevalpack.py
  4. for the reference implementation used in the paper.
  5. TODOs:
  6. - Potentially support other HumanEvalPack datasets (Explain & Synthesize)
  7. - Support other languages (currently only Python)
  8. """
  9. import asyncio
  10. import os
  11. import tempfile
  12. from typing import Any
  13. import pandas as pd
  14. from datasets import load_dataset
  15. from evaluate import load
  16. from evaluation.utils.shared import (
  17. EvalMetadata,
  18. EvalOutput,
  19. codeact_user_response,
  20. make_metadata,
  21. prepare_dataset,
  22. reset_logger_for_multiprocessing,
  23. run_evaluation,
  24. )
  25. from openhands.controller.state.state import State
  26. from openhands.core.config import (
  27. AppConfig,
  28. SandboxConfig,
  29. get_llm_config_arg,
  30. parse_arguments,
  31. )
  32. from openhands.core.logger import openhands_logger as logger
  33. from openhands.core.main import create_runtime, run_controller
  34. from openhands.events.action import CmdRunAction
  35. from openhands.events.observation import CmdOutputObservation
  36. from openhands.runtime.runtime import Runtime
  37. IMPORT_HELPER = {
  38. 'python': [
  39. 'import math',
  40. 'import re',
  41. 'import sys',
  42. 'import copy',
  43. 'import datetime',
  44. 'import itertools',
  45. 'import collections',
  46. 'import heapq',
  47. 'import statistics',
  48. 'import functools',
  49. 'import hashlib',
  50. 'import numpy',
  51. 'import numpy as np',
  52. 'import string',
  53. 'from typing import *',
  54. 'from collections import *',
  55. ],
  56. }
  57. LANGUAGE_TO_TIMEOUT = {
  58. 'python': 10,
  59. }
  60. LANGUAGE_TO_NUM_WORKERS = {
  61. 'python': 4,
  62. }
  63. AGENT_CLS_TO_FAKE_USER_RESPONSE_FN = {
  64. 'CodeActAgent': codeact_user_response,
  65. }
  66. AGENT_CLS_TO_INST_SUFFIX = {
  67. 'CodeActAgent': 'When you think you have fixed the issue through code changes, please run the following command: <execute_bash> exit </execute_bash>.\n'
  68. }
  69. def get_config(
  70. metadata: EvalMetadata,
  71. ) -> AppConfig:
  72. config = AppConfig(
  73. default_agent=metadata.agent_class,
  74. run_as_openhands=False,
  75. runtime='eventstream',
  76. max_iterations=metadata.max_iterations,
  77. sandbox=SandboxConfig(
  78. base_container_image='python:3.11-bookworm',
  79. enable_auto_lint=True,
  80. use_host_network=False,
  81. ),
  82. # do not mount workspace
  83. workspace_base=None,
  84. workspace_mount_path=None,
  85. )
  86. config.set_llm_config(metadata.llm_config)
  87. return config
  88. def _get_instance_id(instance: pd.Series) -> str:
  89. return instance.task_id.replace('/', '__')
  90. async def initialize_runtime(
  91. runtime: Runtime,
  92. instance: pd.Series, # this argument is not required
  93. ):
  94. """Initialize the runtime for the agent.
  95. This function is called before the runtime is used to run the agent.
  96. """
  97. logger.info(f"{'-' * 50} BEGIN Runtime Initialization Fn {'-' * 50}")
  98. obs: CmdOutputObservation
  99. action = CmdRunAction(command='mkdir -p /workspace')
  100. logger.info(action, extra={'msg_type': 'ACTION'})
  101. obs = await runtime.run_action(action)
  102. assert obs.exit_code == 0
  103. action = CmdRunAction(command='cd /workspace')
  104. logger.info(action, extra={'msg_type': 'ACTION'})
  105. obs = await runtime.run_action(action)
  106. assert obs.exit_code == 0
  107. problem_statement = (
  108. instance.declaration + instance.buggy_solution + '\n' + instance.test
  109. )
  110. filename = f'{_get_instance_id(instance)}.py'
  111. with tempfile.TemporaryDirectory() as tmpdir:
  112. host_script_path = os.path.join(tmpdir, filename)
  113. with open(host_script_path, 'w') as f:
  114. f.write(problem_statement)
  115. await runtime.copy_to(
  116. host_script_path,
  117. '/workspace',
  118. )
  119. # check file exists
  120. action = CmdRunAction(command=f'ls /workspace/{_get_instance_id(instance)}.py')
  121. obs = await runtime.run_action(action)
  122. assert obs.exit_code == 0
  123. logger.info(f"{'-' * 50} END Runtime Initialization Fn {'-' * 50}")
  124. async def complete_runtime(
  125. runtime: Runtime,
  126. instance: pd.Series, # this argument is not required, but it is used to get the workspace_dir_name
  127. ) -> dict[str, Any]:
  128. """Complete the runtime for the agent.
  129. This function is called before the runtime is used to run the agent.
  130. If you need to do something in the sandbox to get the correctness metric after
  131. the agent has run, modify this function.
  132. """
  133. logger.info(f"{'-' * 50} BEGIN Runtime Completion Fn {'-' * 50}")
  134. obs: CmdOutputObservation
  135. # default value
  136. language = 'python'
  137. timeout = 10
  138. test_result = {'result': {}, 'metadata': {}}
  139. code_metric = load('Muennighoff/code_eval_octopack')
  140. timeout = LANGUAGE_TO_TIMEOUT[language]
  141. num_workers = LANGUAGE_TO_NUM_WORKERS[language]
  142. python_imports = '\n'.join(IMPORT_HELPER[language])
  143. action = CmdRunAction(
  144. command=f'cat /workspace/{_get_instance_id(instance)}.py', keep_prompt=False
  145. )
  146. obs = await runtime.run_action(action)
  147. assert obs.exit_code == 0
  148. function = obs.content.replace('\r\n', '\n')
  149. logger.info(f'Function: {function}')
  150. function = [[python_imports + '\n' + function]]
  151. results, logs = code_metric.compute(
  152. references=[instance.test],
  153. predictions=function,
  154. language=language,
  155. timeout=timeout,
  156. num_workers=num_workers,
  157. )
  158. test_result['result'] = results
  159. test_result['metadata'] = {
  160. 'logs': logs,
  161. 'timeout': timeout,
  162. 'num_workers': num_workers,
  163. }
  164. logger.info(f"{'-' * 50} END Runtime Completion Fn {'-' * 50}")
  165. return test_result
  166. async def process_instance(
  167. instance: pd.Series,
  168. metadata: EvalMetadata,
  169. reset_logger: bool = True,
  170. ) -> EvalOutput:
  171. config = get_config(metadata)
  172. # use a session id for concurrent evaluation
  173. sid = _get_instance_id(instance)
  174. # Setup the logger properly, so you can run multi-processing to parallelize the evaluation
  175. if reset_logger:
  176. log_dir = os.path.join(metadata.eval_output_dir, 'infer_logs')
  177. reset_logger_for_multiprocessing(logger, instance.task_id, log_dir)
  178. else:
  179. logger.info(f'Starting evaluation for instance {instance.task_id}.')
  180. # Create file with HumanEvalFix problem
  181. # Prompt reference: https://github.com/bigcode-project/bigcode-evaluation-harness/blob/84b96da31b7f840b55c5733325346176140cdb6b/bigcode_eval/tasks/humanevalpack.py#L509
  182. problem_statement = (
  183. instance.declaration + instance.buggy_solution + '\n' + instance.test
  184. )
  185. # Prepare instruction
  186. instruction = (
  187. f'Please fix the function in {sid}.py such that all test cases pass.\n'
  188. 'Environment has been set up for you to start working. You may assume all necessary tools are installed.\n\n'
  189. '# Problem Statement\n'
  190. f'{problem_statement}\n\n'
  191. )
  192. instruction += (
  193. 'IMPORTANT: You should ONLY interact with the environment provided to you AND NEVER ASK FOR HUMAN HELP.\n'
  194. 'You should NOT modify any existing test case files. If needed, you can add new test cases in a NEW file to reproduce the issue.\n'
  195. 'You SHOULD INCLUDE PROPER INDENTATION in your edit commands.\n'
  196. )
  197. # NOTE: You can actually set slightly different instruction for different agents
  198. instruction += AGENT_CLS_TO_INST_SUFFIX[metadata.agent_class]
  199. # Here's how you can run the agent (similar to the `main` function) and get the final task state
  200. runtime = await create_runtime(config, sid=sid)
  201. await initialize_runtime(runtime, instance)
  202. state: State | None = await run_controller(
  203. config=config,
  204. task_str=instruction,
  205. runtime=runtime,
  206. fake_user_response_fn=AGENT_CLS_TO_FAKE_USER_RESPONSE_FN.get(
  207. metadata.agent_class
  208. ),
  209. )
  210. if state is None:
  211. raise ValueError('State should not be None.')
  212. metrics = state.metrics.get() if state.metrics else None
  213. test_result = await complete_runtime(runtime, instance)
  214. # history is now available as a stream of events, rather than list of pairs of (Action, Observation)
  215. # for compatibility with the existing output format, we can remake the pairs here
  216. # remove when it becomes unnecessary
  217. histories = state.history.compatibility_for_eval_history_pairs()
  218. # Save the output
  219. output = EvalOutput(
  220. instance_id=instance.task_id,
  221. instruction=instruction,
  222. metadata=metadata,
  223. history=histories,
  224. metrics=metrics,
  225. error=state.last_error if state and state.last_error else None,
  226. test_result=test_result,
  227. )
  228. return output
  229. if __name__ == '__main__':
  230. args = parse_arguments()
  231. # NOTE: It is preferable to load datasets from huggingface datasets and perform post-processing
  232. # so we don't need to manage file uploading to OpenHands's repo
  233. dataset = load_dataset(
  234. 'bigcode/humanevalpack', 'python'
  235. ) # TODO: Support other languages
  236. hefix_tests = dataset['test'].to_pandas()
  237. hefix_tests.rename(columns={'task_id': 'instance_id'}, inplace=True)
  238. llm_config = None
  239. if args.llm_config:
  240. llm_config = get_llm_config_arg(args.llm_config)
  241. if llm_config is None:
  242. raise ValueError(f'Could not find LLM config: --llm_config {args.llm_config}')
  243. metadata = make_metadata(
  244. llm_config,
  245. 'humanevalfix-python',
  246. args.agent_cls,
  247. args.max_iterations,
  248. args.eval_note,
  249. args.eval_output_dir,
  250. )
  251. output_file = os.path.join(metadata.eval_output_dir, 'output.jsonl')
  252. instances = prepare_dataset(hefix_tests, output_file, args.eval_n_limit)
  253. asyncio.run(
  254. run_evaluation(
  255. instances,
  256. metadata,
  257. output_file,
  258. args.eval_num_workers,
  259. process_instance,
  260. )
  261. )