eval_infer.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377
  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. remote_runtime_api_url=os.environ.get('SANDBOX_REMOTE_RUNTIME_API_URL'),
  73. ),
  74. # do not mount workspace
  75. workspace_base=None,
  76. workspace_mount_path=None,
  77. )
  78. return config
  79. def process_instance(
  80. instance: pd.Series,
  81. metadata: EvalMetadata | None = None,
  82. reset_logger: bool = True,
  83. ) -> EvalOutput:
  84. # Setup the logger properly, so you can run multi-processing to parallelize the evaluation
  85. if reset_logger:
  86. global output_file
  87. log_dir = output_file.replace('.jsonl', '.logs')
  88. os.makedirs(log_dir, exist_ok=True)
  89. reset_logger_for_multiprocessing(logger, instance.instance_id, log_dir)
  90. else:
  91. logger.info(f'Starting evaluation for instance {instance.instance_id}.')
  92. config = get_config(instance)
  93. instance_id = instance.instance_id
  94. model_patch = instance['model_patch']
  95. test_spec: TestSpec = instance['test_spec']
  96. logger.info(f'Starting evaluation for instance {instance_id}.')
  97. if 'test_result' not in instance.keys():
  98. instance['test_result'] = {}
  99. instance['test_result']['report'] = {
  100. 'empty_generation': False,
  101. 'resolved': False,
  102. 'failed_apply_patch': False,
  103. 'error_eval': False,
  104. 'test_timeout': False,
  105. }
  106. if model_patch == '':
  107. instance['test_result']['report']['empty_generation'] = True
  108. return EvalOutput(
  109. instance_id=instance_id,
  110. test_result=instance['test_result'],
  111. )
  112. runtime = create_runtime(config)
  113. # Get patch and save it to /tmp/patch.diff
  114. with tempfile.TemporaryDirectory() as temp_dir:
  115. # Patch file
  116. patch_file_path = os.path.join(temp_dir, 'patch.diff')
  117. with open(patch_file_path, 'w') as f:
  118. f.write(model_patch)
  119. runtime.copy_to(patch_file_path, '/tmp')
  120. # Eval script
  121. eval_script_path = os.path.join(temp_dir, 'eval.sh')
  122. with open(eval_script_path, 'w') as f:
  123. f.write(test_spec.eval_script)
  124. runtime.copy_to(eval_script_path, '/tmp')
  125. # Set +x
  126. action = CmdRunAction(command='chmod +x /tmp/eval.sh')
  127. action.timeout = 600
  128. logger.info(action, extra={'msg_type': 'ACTION'})
  129. obs = runtime.run_action(action)
  130. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  131. assert obs.exit_code == 0
  132. # Apply patch
  133. exec_command = (
  134. 'cd /testbed && '
  135. "(git apply -v /tmp/patch.diff && echo 'APPLY_PATCH_PASS' || "
  136. "(echo 'Failed to apply patch with git apply, trying with patch command...' && "
  137. "(patch --batch --fuzz=5 -p1 -i /tmp/patch.diff && echo 'APPLY_PATCH_PASS' || "
  138. "echo 'APPLY_PATCH_FAIL')))"
  139. )
  140. action = CmdRunAction(command=exec_command, keep_prompt=False)
  141. action.timeout = 600
  142. obs = runtime.run_action(action)
  143. assert isinstance(obs, CmdOutputObservation)
  144. apply_patch_output = obs.content
  145. assert isinstance(apply_patch_output, str)
  146. instance['test_result']['apply_patch_output'] = apply_patch_output
  147. try:
  148. if 'APPLY_PATCH_FAIL' in apply_patch_output:
  149. logger.info(f'[{instance_id}] {APPLY_PATCH_FAIL}:\n{apply_patch_output}')
  150. instance['test_result']['report']['failed_apply_patch'] = True
  151. return EvalOutput(
  152. instance_id=instance_id,
  153. test_result=instance['test_result'],
  154. )
  155. elif 'APPLY_PATCH_PASS' in apply_patch_output:
  156. logger.info(f'[{instance_id}] {APPLY_PATCH_PASS}:\n{apply_patch_output}')
  157. # Run eval script in background and save output to log file
  158. log_file = '/tmp/eval_output.log'
  159. action = CmdRunAction(
  160. command=f'/tmp/eval.sh > {log_file} 2>&1 & echo $!', keep_prompt=False
  161. )
  162. action.timeout = 60 # Short timeout just to get the process ID
  163. obs = runtime.run_action(action)
  164. if isinstance(obs, CmdOutputObservation) and obs.exit_code == 0:
  165. pid = obs.content.split()[-1].strip()
  166. logger.info(
  167. f'[{instance_id}] Evaluation process started with PID: {pid}'
  168. )
  169. # Poll for completion
  170. start_time = time.time()
  171. timeout = 1800 # 30 minutes
  172. while True:
  173. seconds_elapsed = time.time() - start_time
  174. if seconds_elapsed > timeout:
  175. logger.info(
  176. f'[{instance_id}] Evaluation timed out after {timeout} seconds'
  177. )
  178. instance['test_result']['report']['test_timeout'] = True
  179. break
  180. check_action = CmdRunAction(
  181. command=f'ps -p {pid} > /dev/null; echo $?', keep_prompt=False
  182. )
  183. check_action.timeout = 60
  184. check_obs = runtime.run_action(check_action)
  185. if (
  186. isinstance(check_obs, CmdOutputObservation)
  187. and check_obs.content.split()[-1].strip() == '1'
  188. ):
  189. logger.info(
  190. f'[{instance_id}] Evaluation process completed after {seconds_elapsed} seconds'
  191. )
  192. break
  193. logger.info(
  194. f'[{instance_id}] [{seconds_elapsed:.0f}s] Evaluation still running, waiting...'
  195. )
  196. time.sleep(30) # Wait for 30 seconds before checking again
  197. # Read the log file
  198. cat_action = CmdRunAction(command=f'cat {log_file}', keep_prompt=False)
  199. cat_action.timeout = 300
  200. cat_obs = runtime.run_action(cat_action)
  201. # Grade answer
  202. if isinstance(cat_obs, CmdOutputObservation) and cat_obs.exit_code == 0:
  203. test_output = cat_obs.content
  204. assert isinstance(test_output, str)
  205. instance['test_result']['test_output'] = test_output
  206. # Get report from test output
  207. logger.info(f'[{instance_id}] Grading answer...')
  208. with tempfile.TemporaryDirectory() as temp_dir:
  209. # Create a directory structure that matches the expected format
  210. # NOTE: this is a hack to make the eval report format consistent
  211. # with the original SWE-Bench eval script
  212. log_dir = os.path.join(temp_dir, 'logs', instance_id)
  213. os.makedirs(log_dir, exist_ok=True)
  214. test_output_path = os.path.join(log_dir, 'test_output.txt')
  215. with open(test_output_path, 'w') as f:
  216. f.write(test_output)
  217. _report = get_eval_report(
  218. test_spec=test_spec,
  219. prediction={
  220. 'model_patch': model_patch,
  221. 'instance_id': instance_id,
  222. },
  223. log_path=test_output_path,
  224. include_tests_status=True,
  225. )
  226. report = _report[instance_id]
  227. logger.info(
  228. f"[{instance_id}] report: {report}\nResult for {instance_id}: resolved: {report['resolved']}"
  229. )
  230. instance['test_result']['report']['resolved'] = report[
  231. 'resolved'
  232. ]
  233. else:
  234. logger.info(f'[{instance_id}] Error when starting eval:\n{obs.content}')
  235. instance['test_result']['report']['error_eval'] = True
  236. return EvalOutput(
  237. instance_id=instance_id,
  238. test_result=instance['test_result'],
  239. )
  240. else:
  241. logger.info(
  242. f'[{instance_id}] Unexpected output when applying patch:\n{apply_patch_output}'
  243. )
  244. raise RuntimeError(
  245. instance_id,
  246. f'Unexpected output when applying patch:\n{apply_patch_output}',
  247. logger,
  248. )
  249. finally:
  250. runtime.close()
  251. if __name__ == '__main__':
  252. parser = get_parser()
  253. parser.add_argument(
  254. '--input-file',
  255. type=str,
  256. help='Path to input predictions file',
  257. required=True,
  258. )
  259. parser.add_argument(
  260. '--dataset',
  261. type=str,
  262. default='princeton-nlp/SWE-bench',
  263. help='data set to evaluate on, either full-test or lite-test',
  264. )
  265. parser.add_argument(
  266. '--split',
  267. type=str,
  268. default='test',
  269. help='split to evaluate on',
  270. )
  271. args, _ = parser.parse_known_args()
  272. # Load SWE-Bench dataset
  273. full_dataset: list[SWEbenchInstance] = load_swebench_dataset(
  274. args.dataset, args.split
  275. )
  276. instance_id_to_instance = {
  277. instance['instance_id']: instance for instance in full_dataset
  278. }
  279. logger.info(
  280. f'Loaded dataset {args.dataset} with split {args.split} to run inference on.'
  281. )
  282. # Load predictions
  283. assert args.input_file.endswith('.jsonl'), 'Input file must be a jsonl file.'
  284. predictions = pd.read_json(args.input_file, lines=True)
  285. assert (
  286. 'instance_id' in predictions.columns
  287. ), 'Input file must contain instance_id column.'
  288. if 'model_patch' not in predictions.columns and (
  289. 'test_result' in predictions.columns
  290. and 'model_patch' in predictions['test_result'].iloc[0]
  291. ):
  292. raise ValueError(
  293. 'Input file must contain model_patch column OR test_result column with model_patch field.'
  294. )
  295. assert len(predictions['instance_id'].unique()) == len(
  296. predictions
  297. ), 'instance_id column must be unique.'
  298. if 'model_patch' not in predictions.columns:
  299. predictions['model_patch'] = predictions['test_result'].apply(
  300. lambda x: x['git_patch']
  301. )
  302. assert {'instance_id', 'model_patch'}.issubset(
  303. set(predictions.columns)
  304. ), 'Input file must contain instance_id and model_patch columns.'
  305. # Process model_patch
  306. predictions['model_patch'] = predictions['model_patch'].apply(process_git_patch)
  307. # Merge predictions with dataset
  308. predictions['instance'] = predictions['instance_id'].apply(
  309. lambda x: instance_id_to_instance[x]
  310. )
  311. predictions['test_spec'] = predictions['instance'].apply(make_test_spec)
  312. # Prepare dataset
  313. output_file = args.input_file.replace('.jsonl', '.swebench_eval.jsonl')
  314. instances = prepare_dataset(predictions, output_file, args.eval_n_limit)
  315. run_evaluation(
  316. instances,
  317. metadata=None,
  318. output_file=output_file,
  319. num_workers=args.eval_num_workers,
  320. process_instance_func=process_instance,
  321. )
  322. # Load evaluated predictions & print number of resolved predictions
  323. evaluated_predictions = pd.read_json(output_file, lines=True)
  324. fields = ['resolved', 'failed_apply_patch', 'error_eval', 'empty_generation']
  325. def count_report_field(row, field):
  326. return row['test_result']['report'][field]
  327. for field in fields:
  328. count = evaluated_predictions.apply(
  329. count_report_field, args=(field,), axis=1
  330. ).sum()
  331. logger.info(
  332. f'# {field}: {count} / {len(evaluated_predictions)}. ({count / len(evaluated_predictions):.2%})'
  333. )