run_infer.py 10.0 KB

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