run_infer.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391
  1. """
  2. Implements evaluation of agents on HumanEvalFix from the HumanEvalPack benchmark introduced in
  3. "OctoPack: Instruction Tuning Code Large Language Models" (https://arxiv.org/abs/2308.07124).
  4. Please see https://github.com/bigcode-project/bigcode-evaluation-harness/blob/main/bigcode_eval/tasks/humanevalpack.py
  5. for the reference implementation used in the paper.
  6. TODOs:
  7. - Potentially support other HumanEvalPack datasets (Explain & Synthesize)
  8. - Support other languages (currently only Python)
  9. """
  10. import asyncio
  11. import json
  12. import logging
  13. import multiprocessing as mp
  14. import os
  15. import pathlib
  16. import subprocess
  17. import time
  18. from concurrent.futures import ProcessPoolExecutor
  19. import pandas as pd
  20. from datasets import load_dataset
  21. from evaluate import load
  22. from tqdm import tqdm
  23. from opendevin.controller.state.state import State
  24. from opendevin.core.config import args, config, get_llm_config_arg
  25. from opendevin.core.logger import get_console_handler
  26. from opendevin.core.logger import opendevin_logger as logger
  27. from opendevin.core.main import main
  28. from opendevin.events.action import MessageAction
  29. from opendevin.events.serialization.event import event_to_dict
  30. IMPORT_HELPER = {
  31. 'python': [
  32. 'import math',
  33. 'import re',
  34. 'import sys',
  35. 'import copy',
  36. 'import datetime',
  37. 'import itertools',
  38. 'import collections',
  39. 'import heapq',
  40. 'import statistics',
  41. 'import functools',
  42. 'import hashlib',
  43. 'import numpy',
  44. 'import numpy as np',
  45. 'import string',
  46. 'from typing import *',
  47. 'from collections import *',
  48. ],
  49. }
  50. LANGUAGE_TO_TIMEOUT = {
  51. 'python': 10,
  52. }
  53. LANGUAGE_TO_NUM_WORKERS = {
  54. 'python': 4,
  55. }
  56. def cleanup():
  57. logger.info('Cleaning up child processes...')
  58. for process in mp.active_children():
  59. logger.info(f'Terminating child process: {process.name}')
  60. process.terminate()
  61. process.join()
  62. def codeact_user_response(state: State) -> str:
  63. msg = (
  64. 'Please continue working on the task on whatever approach you think is suitable.\n'
  65. 'If you think you have modified the code in a way that fixes the issue, please run the following command: <execute_bash> exit </execute_bash>.\n'
  66. 'IMPORTANT: YOU SHOULD NEVER ASK FOR HUMAN HELP OR USE THE INTERNET TO SOLVE THIS TASK.\n'
  67. )
  68. if state.history:
  69. user_msgs = [
  70. action
  71. for action, _ in state.history
  72. if isinstance(action, MessageAction) and action.source == 'user'
  73. ]
  74. if len(user_msgs) >= 2:
  75. # let the agent know that it can give up when it has tried 3 times
  76. return (
  77. msg
  78. + 'If you want to give up, run: <execute_bash> exit </execute_bash>.\n'
  79. )
  80. return msg
  81. def monologue_user_response(state: State) -> str:
  82. raise NotImplementedError('MonologueAgent should never ask for user responses.')
  83. AGENT_CLS_TO_FAKE_USER_RESPONSE_FN = {
  84. 'CodeActAgent': codeact_user_response,
  85. 'MonologueAgent': monologue_user_response,
  86. }
  87. AGENT_CLS_TO_INST_SUFFIX = {
  88. 'CodeActAgent': 'When you think you have fixed the issue through code changes, please run the following command: <execute_bash> exit </execute_bash>.\n'
  89. }
  90. def get_test_result(instance, path, language='python', timeout=10):
  91. # Evaluation reference: https://github.com/bigcode-project/bigcode-evaluation-harness/blob/84b96da31b7f840b55c5733325346176140cdb6b/bigcode_eval/tasks/humanevalpack.py#L347
  92. test_result = {'result': {}, 'metadata': {}}
  93. code_metric = load('Muennighoff/code_eval_octopack')
  94. timeout = LANGUAGE_TO_TIMEOUT[language]
  95. num_workers = LANGUAGE_TO_NUM_WORKERS[language]
  96. python_imports = '\n'.join(IMPORT_HELPER[language])
  97. # Load function from path
  98. with open(path, 'r') as f:
  99. function = f.read()
  100. function = [[python_imports + '\n' + function.strip()]]
  101. results, logs = code_metric.compute(
  102. references=[instance.test],
  103. predictions=function,
  104. language=language,
  105. timeout=timeout,
  106. num_workers=num_workers,
  107. )
  108. test_result['result'] = results
  109. test_result['metadata'] = {
  110. 'logs': logs,
  111. 'timeout': timeout,
  112. 'num_workers': num_workers,
  113. }
  114. return test_result
  115. def process_instance(
  116. instance, agent_class, metadata, skip_workspace_mount, reset_logger: bool = True
  117. ):
  118. old_workspace_mount_path = config.workspace_mount_path
  119. old_workspace_base = config.workspace_base
  120. try:
  121. workspace_mount_path = os.path.join(
  122. config.workspace_mount_path, '_eval_workspace'
  123. )
  124. # create process-specific workspace dir
  125. # if `not skip_workspace_mount` - we will create a workspace directory for EACH process
  126. # so that different agent don't interfere with each other.
  127. if not skip_workspace_mount:
  128. workspace_mount_path = os.path.join(workspace_mount_path, str(os.getpid()))
  129. pathlib.Path(workspace_mount_path).mkdir(parents=True, exist_ok=True)
  130. # reset workspace to config
  131. config.workspace_base = workspace_mount_path
  132. config.workspace_mount_path = workspace_mount_path
  133. # Setup the logger properly, so you can run multi-processing to parallelize the evaluation
  134. if reset_logger:
  135. # Set up logger
  136. log_file = os.path.join(
  137. eval_output_dir,
  138. 'logs',
  139. f'instance_{instance.task_id.replace("/", "__")}.log',
  140. )
  141. # Remove all existing handlers from logger
  142. for handler in logger.handlers[:]:
  143. logger.removeHandler(handler)
  144. # add back the console handler to print ONE line
  145. logger.addHandler(get_console_handler())
  146. logger.info(
  147. f'Starting evaluation for instance {instance.task_id}.\nLOG: tail -f {log_file}'
  148. )
  149. # Remove all existing handlers from logger
  150. for handler in logger.handlers[:]:
  151. logger.removeHandler(handler)
  152. file_handler = logging.FileHandler(log_file)
  153. file_handler.setFormatter(
  154. logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
  155. )
  156. logger.addHandler(file_handler)
  157. if not skip_workspace_mount:
  158. logger.info(f'Process-specific workspace mounted at {workspace_mount_path}')
  159. # Create file with HumanEvalFix problem
  160. # Prompt reference: https://github.com/bigcode-project/bigcode-evaluation-harness/blob/84b96da31b7f840b55c5733325346176140cdb6b/bigcode_eval/tasks/humanevalpack.py#L509
  161. problem_statement = (
  162. instance.declaration + instance.buggy_solution + '\n' + instance.test
  163. )
  164. path = os.path.join(
  165. workspace_mount_path, f'{instance.task_id.replace("/", "__")}.py'
  166. )
  167. with open(path, 'w') as f:
  168. f.write(problem_statement)
  169. # Prepare instruction
  170. instruction = (
  171. f'Please fix the function in {instance.task_id.replace("/", "__")}.py such that all test cases pass.\n'
  172. 'Environment has been set up for you to start working. You may assume all necessary tools are installed.\n\n'
  173. '# Problem Statement\n'
  174. f'{problem_statement}\n\n'
  175. )
  176. instruction += (
  177. 'IMPORTANT: You should ONLY interact with the environment provided to you AND NEVER ASK FOR HUMAN HELP.\n'
  178. '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'
  179. 'You SHOULD INCLUDE PROPER INDENTATION in your edit commands.\n'
  180. )
  181. # NOTE: You can actually set slightly different instruction for different agents
  182. instruction += AGENT_CLS_TO_INST_SUFFIX.get(agent_class, '')
  183. # Here's how you can run the agent (similar to the `main` function) and get the final task state
  184. state: State = asyncio.run(
  185. main(
  186. instruction,
  187. fake_user_response_fn=AGENT_CLS_TO_FAKE_USER_RESPONSE_FN.get(
  188. agent_class
  189. ),
  190. )
  191. )
  192. # ======= Attempt to evaluate the agent's edits =======
  193. test_result = get_test_result(instance, path)
  194. # If you are working on some simpler benchmark that only evaluates the final model output (e.g., in a MessageAction)
  195. # You can simply get the LAST `MessageAction` from the returned `state.history` and parse it for evaluation.
  196. if state is None:
  197. raise ValueError('State should not be None.')
  198. metrics = state.metrics.get() if state.metrics else None
  199. # Save the output
  200. output = {
  201. 'task_id': instance.task_id,
  202. 'instruction': instruction,
  203. 'metadata': metadata,
  204. 'history': [
  205. (event_to_dict(action), event_to_dict(obs))
  206. for action, obs in state.history
  207. ],
  208. 'metrics': metrics,
  209. 'error': state.error if state and state.error else None,
  210. 'test_result': test_result,
  211. }
  212. except Exception:
  213. logger.error('Process instance failed')
  214. raise
  215. finally:
  216. config.workspace_mount_path = old_workspace_mount_path
  217. config.workspace_base = old_workspace_base
  218. return output
  219. if __name__ == '__main__':
  220. # NOTE: It is preferable to load datasets from huggingface datasets and perform post-processing
  221. # so we don't need to manage file uploading to OpenDevin's repo
  222. dataset = load_dataset(
  223. 'bigcode/humanevalpack', 'python'
  224. ) # TODO: Support other languages
  225. hefix_tests = dataset['test'].to_pandas()
  226. # Check https://github.com/OpenDevin/OpenDevin/blob/main/evaluation/humanevalfix/README.md#configure-opendevin-and-your-llm
  227. # for details of how to set `llm_config`
  228. if args.llm_config:
  229. specified_llm_config = get_llm_config_arg(args.llm_config)
  230. if specified_llm_config:
  231. config.llm = specified_llm_config
  232. logger.info(f'Config for evaluation: {config}')
  233. # TEST METADATA
  234. agent_class = args.agent_cls
  235. assert (
  236. agent_class in AGENT_CLS_TO_FAKE_USER_RESPONSE_FN
  237. ), f'Unsupported agent class: {agent_class}'
  238. model_name = config.llm.model.split('/')[-1]
  239. max_iterations = args.max_iterations
  240. eval_note = ''
  241. if args.eval_note is not None:
  242. eval_note += '_N_' + args.eval_note
  243. eval_output_dir = os.path.join(
  244. args.eval_output_dir,
  245. 'humanevalfix',
  246. agent_class,
  247. model_name + '_maxiter_' + str(max_iterations) + eval_note,
  248. )
  249. pathlib.Path(eval_output_dir).mkdir(parents=True, exist_ok=True)
  250. pathlib.Path(os.path.join(eval_output_dir, 'logs')).mkdir(
  251. parents=True, exist_ok=True
  252. )
  253. logger.info(f'Using evaluation output directory: {eval_output_dir}')
  254. metadata = {
  255. 'agent_class': agent_class,
  256. 'model_name': model_name,
  257. 'max_iterations': max_iterations,
  258. 'eval_output_dir': eval_output_dir,
  259. 'start_time': time.strftime('%Y-%m-%d %H:%M:%S'),
  260. # get the commit id of current repo for reproducibility
  261. 'git_commit': subprocess.check_output(['git', 'rev-parse', 'HEAD'])
  262. .decode('utf-8')
  263. .strip(),
  264. }
  265. logger.info(f'Metadata: {metadata}')
  266. with open(os.path.join(eval_output_dir, 'metadata.json'), 'w') as f:
  267. json.dump(metadata, f)
  268. # LIMIT EVALUATION
  269. eval_n_limit = args.eval_n_limit
  270. if eval_n_limit:
  271. hefix_tests = hefix_tests.head(eval_n_limit)
  272. logger.info(f'Limiting evaluation to first {eval_n_limit} instances.')
  273. # OUTPUT FILE
  274. output_file = os.path.join(eval_output_dir, 'output.jsonl')
  275. logger.info(f'Writing evaluation output to {output_file}')
  276. finished_instance_ids = set()
  277. if os.path.exists(output_file):
  278. with open(output_file, 'r') as f:
  279. for line in f:
  280. data = json.loads(line)
  281. finished_instance_ids.add(data['task_id'])
  282. logger.warning(
  283. f'Output file {output_file} already exists. Loaded {len(finished_instance_ids)} finished instances.'
  284. )
  285. output_fp = open(output_file, 'a')
  286. logger.info(
  287. f'Evaluation started with Agent {agent_class}, model {model_name}, max iterations {max_iterations}.'
  288. )
  289. # =============================================
  290. # filter out finished instances
  291. new_hefix_tests = []
  292. for idx, instance in hefix_tests.iterrows():
  293. if instance.task_id in finished_instance_ids:
  294. logger.info(
  295. f'Skipping instance {instance.task_id} as it is already finished.'
  296. )
  297. continue
  298. new_hefix_tests.append(instance)
  299. hefix_tests = pd.DataFrame(new_hefix_tests)
  300. logger.info(
  301. f'Finished instances: {len(finished_instance_ids)}, Remaining instances: {len(hefix_tests)}'
  302. )
  303. # =============================================
  304. pbar = tqdm(total=len(hefix_tests))
  305. # This function tracks the progress AND write the output to a JSONL file
  306. def update_progress(future):
  307. pbar.update(1)
  308. output = future.result()
  309. pbar.set_description(f'Instance {output["task_id"]}')
  310. pbar.set_postfix_str(f'Test Result: {output["test_result"]["result"]}')
  311. logger.info(
  312. f'Finished evaluation for instance {output["task_id"]}: {output["test_result"]["result"]}'
  313. )
  314. output_fp.write(json.dumps(output) + '\n')
  315. output_fp.flush()
  316. # This sets the multi-processing
  317. num_workers = args.eval_num_workers
  318. logger.info(f'Using {num_workers} workers for evaluation.')
  319. try:
  320. with ProcessPoolExecutor(num_workers) as executor:
  321. futures = []
  322. # This is how we perform multi-processing
  323. for row_idx, instance in hefix_tests.iterrows():
  324. future = executor.submit(
  325. process_instance,
  326. instance,
  327. agent_class,
  328. metadata,
  329. skip_workspace_mount=False,
  330. reset_logger=bool(num_workers > 1),
  331. )
  332. future.add_done_callback(update_progress)
  333. futures.append(future)
  334. # Wait for all futures to complete
  335. for future in futures:
  336. future.result()
  337. except KeyboardInterrupt:
  338. print('KeyboardInterrupt received. Cleaning up...')
  339. cleanup()
  340. output_fp.close()
  341. logger.info('Evaluation finished.')