eval_infer.py 15 KB

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