eval_infer.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376
  1. import os
  2. import tempfile
  3. import time
  4. import pandas as pd
  5. from swebench.harness.grading import get_eval_report
  6. from swebench.harness.run_evaluation import (
  7. APPLY_PATCH_FAIL,
  8. APPLY_PATCH_PASS,
  9. )
  10. from swebench.harness.test_spec import SWEbenchInstance, TestSpec, make_test_spec
  11. from swebench.harness.utils import load_swebench_dataset
  12. from evaluation.swe_bench.run_infer import get_instance_docker_image
  13. from evaluation.utils.shared import (
  14. EvalMetadata,
  15. EvalOutput,
  16. prepare_dataset,
  17. reset_logger_for_multiprocessing,
  18. run_evaluation,
  19. )
  20. from openhands.core.config import (
  21. AppConfig,
  22. SandboxConfig,
  23. get_parser,
  24. )
  25. from openhands.core.logger import openhands_logger as logger
  26. from openhands.core.main import create_runtime
  27. from openhands.events.action import CmdRunAction
  28. from openhands.events.observation import CmdOutputObservation
  29. # TODO: migrate all swe-bench docker to ghcr.io/openhands
  30. DOCKER_IMAGE_PREFIX = os.environ.get('EVAL_DOCKER_IMAGE_PREFIX', 'docker.io/xingyaoww/')
  31. logger.info(f'Using docker image prefix: {DOCKER_IMAGE_PREFIX}')
  32. def process_git_patch(patch):
  33. if not isinstance(patch, str):
  34. return ''
  35. if not patch.strip():
  36. # skip empty patches
  37. return ''
  38. patch = patch.replace('\r\n', '\n')
  39. # There might be some weird characters at the beginning of the patch
  40. # due to some OpenHands inference command outputs
  41. # FOR EXAMPLE:
  42. # git diff --no-color --cached 895f28f9cbed817c00ab68770433170d83132d90
  43. # 0
  44. # diff --git a/django/db/models/sql/.backup.query.py b/django/db/models/sql/.backup.query.py
  45. # new file mode 100644
  46. # index 0000000000..fc13db5948
  47. # We "find" the first line that starts with "diff" and then we remove lines before it
  48. lines = patch.split('\n')
  49. for i, line in enumerate(lines):
  50. if line.startswith('diff --git'):
  51. patch = '\n'.join(lines[i:])
  52. break
  53. patch = patch.rstrip() + '\n' # Make sure the last line ends with a newline
  54. return patch
  55. def get_config(instance: pd.Series) -> AppConfig:
  56. # We use a different instance image for the each instance of swe-bench eval
  57. base_container_image = get_instance_docker_image(instance['instance_id'])
  58. logger.info(
  59. f'Using instance container image: {base_container_image}. '
  60. f'Please make sure this image exists. '
  61. f'Submit an issue on https://github.com/All-Hands-AI/OpenHands if you run into any issues.'
  62. )
  63. config = AppConfig(
  64. run_as_openhands=False,
  65. runtime=os.environ.get('RUNTIME', 'eventstream'),
  66. sandbox=SandboxConfig(
  67. base_container_image=base_container_image,
  68. use_host_network=False,
  69. # large enough timeout, since some testcases take very long to run
  70. timeout=1800,
  71. api_key=os.environ.get('ALLHANDS_API_KEY', None),
  72. ),
  73. # do not mount workspace
  74. workspace_base=None,
  75. workspace_mount_path=None,
  76. )
  77. return config
  78. def process_instance(
  79. instance: pd.Series,
  80. metadata: EvalMetadata | None = None,
  81. reset_logger: bool = True,
  82. ) -> EvalOutput:
  83. # Setup the logger properly, so you can run multi-processing to parallelize the evaluation
  84. if reset_logger:
  85. global output_file
  86. log_dir = output_file.replace('.jsonl', '.logs')
  87. os.makedirs(log_dir, exist_ok=True)
  88. reset_logger_for_multiprocessing(logger, instance.instance_id, log_dir)
  89. else:
  90. logger.info(f'Starting evaluation for instance {instance.instance_id}.')
  91. config = get_config(instance)
  92. instance_id = instance.instance_id
  93. model_patch = instance['model_patch']
  94. test_spec: TestSpec = instance['test_spec']
  95. logger.info(f'Starting evaluation for instance {instance_id}.')
  96. if 'test_result' not in instance.keys():
  97. instance['test_result'] = {}
  98. instance['test_result']['report'] = {
  99. 'empty_generation': False,
  100. 'resolved': False,
  101. 'failed_apply_patch': False,
  102. 'error_eval': False,
  103. 'test_timeout': False,
  104. }
  105. if model_patch == '':
  106. instance['test_result']['report']['empty_generation'] = True
  107. return EvalOutput(
  108. instance_id=instance_id,
  109. test_result=instance['test_result'],
  110. )
  111. runtime = create_runtime(config, sid=instance_id)
  112. # Get patch and save it to /tmp/patch.diff
  113. with tempfile.TemporaryDirectory() as temp_dir:
  114. # Patch file
  115. patch_file_path = os.path.join(temp_dir, 'patch.diff')
  116. with open(patch_file_path, 'w') as f:
  117. f.write(model_patch)
  118. runtime.copy_to(patch_file_path, '/tmp')
  119. # Eval script
  120. eval_script_path = os.path.join(temp_dir, 'eval.sh')
  121. with open(eval_script_path, 'w') as f:
  122. f.write(test_spec.eval_script)
  123. runtime.copy_to(eval_script_path, '/tmp')
  124. # Set +x
  125. action = CmdRunAction(command='chmod +x /tmp/eval.sh')
  126. action.timeout = 600
  127. logger.info(action, extra={'msg_type': 'ACTION'})
  128. obs = runtime.run_action(action)
  129. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  130. assert obs.exit_code == 0
  131. # Apply patch
  132. exec_command = (
  133. 'cd /testbed && '
  134. "(git apply -v /tmp/patch.diff && echo 'APPLY_PATCH_PASS' || "
  135. "(echo 'Failed to apply patch with git apply, trying with patch command...' && "
  136. "(patch --batch --fuzz=5 -p1 -i /tmp/patch.diff && echo 'APPLY_PATCH_PASS' || "
  137. "echo 'APPLY_PATCH_FAIL')))"
  138. )
  139. action = CmdRunAction(command=exec_command, keep_prompt=False)
  140. action.timeout = 600
  141. obs = runtime.run_action(action)
  142. assert isinstance(obs, CmdOutputObservation)
  143. apply_patch_output = obs.content
  144. assert isinstance(apply_patch_output, str)
  145. instance['test_result']['apply_patch_output'] = apply_patch_output
  146. try:
  147. if 'APPLY_PATCH_FAIL' in apply_patch_output:
  148. logger.info(f'[{instance_id}] {APPLY_PATCH_FAIL}:\n{apply_patch_output}')
  149. instance['test_result']['report']['failed_apply_patch'] = True
  150. return EvalOutput(
  151. instance_id=instance_id,
  152. test_result=instance['test_result'],
  153. )
  154. elif 'APPLY_PATCH_PASS' in apply_patch_output:
  155. logger.info(f'[{instance_id}] {APPLY_PATCH_PASS}:\n{apply_patch_output}')
  156. # Run eval script in background and save output to log file
  157. log_file = '/tmp/eval_output.log'
  158. action = CmdRunAction(
  159. command=f'/tmp/eval.sh > {log_file} 2>&1 & echo $!', keep_prompt=False
  160. )
  161. action.timeout = 60 # Short timeout just to get the process ID
  162. obs = runtime.run_action(action)
  163. if isinstance(obs, CmdOutputObservation) and obs.exit_code == 0:
  164. pid = obs.content.split()[-1].strip()
  165. logger.info(
  166. f'[{instance_id}] Evaluation process started with PID: {pid}'
  167. )
  168. # Poll for completion
  169. start_time = time.time()
  170. timeout = 1800 # 30 minutes
  171. while True:
  172. seconds_elapsed = time.time() - start_time
  173. if seconds_elapsed > timeout:
  174. logger.info(
  175. f'[{instance_id}] Evaluation timed out after {timeout} seconds'
  176. )
  177. instance['test_result']['report']['test_timeout'] = True
  178. break
  179. check_action = CmdRunAction(
  180. command=f'ps -p {pid} > /dev/null; echo $?', keep_prompt=False
  181. )
  182. check_action.timeout = 60
  183. check_obs = runtime.run_action(check_action)
  184. if (
  185. isinstance(check_obs, CmdOutputObservation)
  186. and check_obs.content.split()[-1].strip() == '1'
  187. ):
  188. logger.info(
  189. f'[{instance_id}] Evaluation process completed after {seconds_elapsed} seconds'
  190. )
  191. break
  192. logger.info(
  193. f'[{instance_id}] [{seconds_elapsed:.0f}s] Evaluation still running, waiting...'
  194. )
  195. time.sleep(30) # Wait for 30 seconds before checking again
  196. # Read the log file
  197. cat_action = CmdRunAction(command=f'cat {log_file}', keep_prompt=False)
  198. cat_action.timeout = 300
  199. cat_obs = runtime.run_action(cat_action)
  200. # Grade answer
  201. if isinstance(cat_obs, CmdOutputObservation) and cat_obs.exit_code == 0:
  202. test_output = cat_obs.content
  203. assert isinstance(test_output, str)
  204. instance['test_result']['test_output'] = test_output
  205. # Get report from test output
  206. logger.info(f'[{instance_id}] Grading answer...')
  207. with tempfile.TemporaryDirectory() as temp_dir:
  208. # Create a directory structure that matches the expected format
  209. # NOTE: this is a hack to make the eval report format consistent
  210. # with the original SWE-Bench eval script
  211. log_dir = os.path.join(temp_dir, 'logs', instance_id)
  212. os.makedirs(log_dir, exist_ok=True)
  213. test_output_path = os.path.join(log_dir, 'test_output.txt')
  214. with open(test_output_path, 'w') as f:
  215. f.write(test_output)
  216. _report = get_eval_report(
  217. test_spec=test_spec,
  218. prediction={
  219. 'model_patch': model_patch,
  220. 'instance_id': instance_id,
  221. },
  222. log_path=test_output_path,
  223. include_tests_status=True,
  224. )
  225. report = _report[instance_id]
  226. logger.info(
  227. f"[{instance_id}] report: {report}\nResult for {instance_id}: resolved: {report['resolved']}"
  228. )
  229. instance['test_result']['report']['resolved'] = report[
  230. 'resolved'
  231. ]
  232. else:
  233. logger.info(f'[{instance_id}] Error when starting eval:\n{obs.content}')
  234. instance['test_result']['report']['error_eval'] = True
  235. return EvalOutput(
  236. instance_id=instance_id,
  237. test_result=instance['test_result'],
  238. )
  239. else:
  240. logger.info(
  241. f'[{instance_id}] Unexpected output when applying patch:\n{apply_patch_output}'
  242. )
  243. raise RuntimeError(
  244. instance_id,
  245. f'Unexpected output when applying patch:\n{apply_patch_output}',
  246. logger,
  247. )
  248. finally:
  249. runtime.close()
  250. if __name__ == '__main__':
  251. parser = get_parser()
  252. parser.add_argument(
  253. '--input-file',
  254. type=str,
  255. help='Path to input predictions file',
  256. required=True,
  257. )
  258. parser.add_argument(
  259. '--dataset',
  260. type=str,
  261. default='princeton-nlp/SWE-bench',
  262. help='data set to evaluate on, either full-test or lite-test',
  263. )
  264. parser.add_argument(
  265. '--split',
  266. type=str,
  267. default='test',
  268. help='split to evaluate on',
  269. )
  270. args, _ = parser.parse_known_args()
  271. # Load SWE-Bench dataset
  272. full_dataset: list[SWEbenchInstance] = load_swebench_dataset(
  273. args.dataset, args.split
  274. )
  275. instance_id_to_instance = {
  276. instance['instance_id']: instance for instance in full_dataset
  277. }
  278. logger.info(
  279. f'Loaded dataset {args.dataset} with split {args.split} to run inference on.'
  280. )
  281. # Load predictions
  282. assert args.input_file.endswith('.jsonl'), 'Input file must be a jsonl file.'
  283. predictions = pd.read_json(args.input_file, lines=True)
  284. assert (
  285. 'instance_id' in predictions.columns
  286. ), 'Input file must contain instance_id column.'
  287. if 'model_patch' not in predictions.columns and (
  288. 'test_result' in predictions.columns
  289. and 'model_patch' in predictions['test_result'].iloc[0]
  290. ):
  291. raise ValueError(
  292. 'Input file must contain model_patch column OR test_result column with model_patch field.'
  293. )
  294. assert len(predictions['instance_id'].unique()) == len(
  295. predictions
  296. ), 'instance_id column must be unique.'
  297. if 'model_patch' not in predictions.columns:
  298. predictions['model_patch'] = predictions['test_result'].apply(
  299. lambda x: x['git_patch']
  300. )
  301. assert {'instance_id', 'model_patch'}.issubset(
  302. set(predictions.columns)
  303. ), 'Input file must contain instance_id and model_patch columns.'
  304. # Process model_patch
  305. predictions['model_patch'] = predictions['model_patch'].apply(process_git_patch)
  306. # Merge predictions with dataset
  307. predictions['instance'] = predictions['instance_id'].apply(
  308. lambda x: instance_id_to_instance[x]
  309. )
  310. predictions['test_spec'] = predictions['instance'].apply(make_test_spec)
  311. # Prepare dataset
  312. output_file = args.input_file.replace('.jsonl', '.swebench_eval.jsonl')
  313. instances = prepare_dataset(predictions, output_file, args.eval_n_limit)
  314. run_evaluation(
  315. instances,
  316. metadata=None,
  317. output_file=output_file,
  318. num_workers=args.eval_num_workers,
  319. process_instance_func=process_instance,
  320. )
  321. # Load evaluated predictions & print number of resolved predictions
  322. evaluated_predictions = pd.read_json(output_file, lines=True)
  323. fields = ['resolved', 'failed_apply_patch', 'error_eval', 'empty_generation']
  324. def count_report_field(row, field):
  325. return row['test_result']['report'][field]
  326. for field in fields:
  327. count = evaluated_predictions.apply(
  328. count_report_field, args=(field,), axis=1
  329. ).sum()
  330. logger.info(
  331. f'# {field}: {count} / {len(evaluated_predictions)}. ({count / len(evaluated_predictions):.2%})'
  332. )