| 1 | """ |
| 2 | A script to drive end-to-end experiment workflow. |
| 3 | """ |
| 4 | |
| 5 | import argparse |
| 6 | import configparser |
| 7 | import contextlib |
| 8 | import json |
| 9 | import os |
| 10 | import shutil |
| 11 | import subprocess |
| 12 | from datetime import datetime |
| 13 | from glob import glob |
| 14 | from os.path import dirname as pdirname |
| 15 | from os.path import join as pjoin |
| 16 | from pathlib import Path |
| 17 | from statistics import mean |
| 18 | |
| 19 | ## globals |
| 20 | # whether to force delete existing data directories |
| 21 | force_delete: bool = False |
| 22 | # whether running combined experiment of lite, devin, and swe-25 |
| 23 | running_combined: bool = False |
| 24 | |
| 25 | |
| 26 | # figure out some path to conda executable |
| 27 | conda_bin_path = os.getenv("CONDA_EXE") |
| 28 | conda_bin_dir = pdirname(conda_bin_path) |
| 29 | activate_path = pjoin(conda_bin_dir, "activate") |
| 30 | deactivate_path = pjoin(conda_bin_dir, "deactivate") |
| 31 | |
| 32 | |
| 33 | @contextlib.contextmanager |
| 34 | def cd(newdir): |
| 35 | """ |
| 36 | Context manager for changing the current working directory |
| 37 | :param newdir: path to the new directory |
| 38 | :return: None |
| 39 | """ |
| 40 | prevdir = os.getcwd() |
| 41 | os.chdir(os.path.expanduser(newdir)) |
| 42 | try: |
| 43 | yield |
| 44 | finally: |
| 45 | os.chdir(prevdir) |
| 46 | |
| 47 | |
| 48 | def create_fresh_dir(dir_name: str): |
| 49 | """ |
| 50 | A helper method to create a fresh directory. |
| 51 | """ |
| 52 | if (not force_delete) and os.path.exists(dir_name) and os.listdir(dir_name): |
| 53 | print( |
| 54 | f"{dir_name} is not empty. Please clear it or use -f option to force delete it." |
| 55 | ) |
| 56 | exit(1) |
| 57 | |
| 58 | if os.path.exists(dir_name): |
| 59 | shutil.rmtree(dir_name) |
| 60 | |
| 61 | os.makedirs(dir_name) |
| 62 | |
| 63 | |
| 64 | def run_string_cmd_in_conda( |
| 65 | command: str, env_name: str, **kwargs |
| 66 | ) -> subprocess.CompletedProcess: |
| 67 | """ |
| 68 | Run a complete command in a given conda environment, where the command is a string. |
| 69 | |
| 70 | This is useful when the command to be run contains &&, etc. |
| 71 | |
| 72 | NOTE: use `conda activate` instead of `conda run` in this verison, so that we can |
| 73 | run commands that contain `&&`, etc. |
| 74 | NOTE: can find a similar version of this function in app/utils.py |
| 75 | """ |
| 76 | conda_bin_path = os.getenv("CONDA_EXE") # for calling conda |
| 77 | conda_root_dir = pdirname(pdirname(conda_bin_path)) |
| 78 | conda_script_path = pjoin(conda_root_dir, "etc", "profile.d", "conda.sh") |
| 79 | conda_cmd = f"source {conda_script_path} ; conda activate {env_name} ; {command} ; conda deactivate" |
| 80 | cp = subprocess.run(conda_cmd, shell=True, **kwargs) |
| 81 | return cp |
| 82 | |
| 83 | |
| 84 | def create_expr_dir( |
| 85 | overall_expr_dir: str, expr_id: str, selected_tasks_file: str |
| 86 | ) -> tuple[str, str]: |
| 87 | """ |
| 88 | Create experiment dir, and copy the selected tasks file inside. |
| 89 | |
| 90 | Returns: |
| 91 | - The new path of selected tasks file. |
| 92 | - The experiment output dir |
| 93 | """ |
| 94 | expr_dir = pjoin(overall_expr_dir, expr_id) |
| 95 | create_fresh_dir(expr_dir) |
| 96 | # os.makedirs(expr_dir, exist_ok=True) |
| 97 | shutil.copy(selected_tasks_file, expr_dir) |
| 98 | # figure out the name |
| 99 | base_name = os.path.basename(selected_tasks_file) |
| 100 | new_path = pjoin(expr_dir, base_name) |
| 101 | return new_path, expr_dir |
| 102 | |
| 103 | |
| 104 | def run_agent( |
| 105 | root_dir: str, |
| 106 | setup_result_dir: str, |
| 107 | expr_dir: str, |
| 108 | task_list_file_path: str, |
| 109 | model: str, |
| 110 | temperature: float, |
| 111 | enbale_sbfl: bool, |
| 112 | enable_layered: bool, |
| 113 | enable_validation: bool, |
| 114 | enable_angelic: bool, |
| 115 | enable_perfect_angelic: bool, |
| 116 | print_more: bool, |
| 117 | conv_round_limit: int, |
| 118 | num_processes: int, |
| 119 | ): |
| 120 | """ |
| 121 | Run the agent to perform the experiment. |
| 122 | Returns: |
| 123 | - The input file for SWE-bench. |
| 124 | """ |
| 125 | setup_map_json = pjoin(setup_result_dir, "setup_map.json") |
| 126 | tasks_map_json = pjoin(setup_result_dir, "tasks_map.json") |
| 127 | if not os.path.exists(setup_map_json): |
| 128 | raise FileNotFoundError(f"setup_map.json not found in {setup_result_dir}") |
| 129 | if not os.path.exists(tasks_map_json): |
| 130 | raise FileNotFoundError(f"task_map.json not found in {setup_result_dir}") |
| 131 | |
| 132 | added_env = {"PYTHONPATH": root_dir} |
| 133 | modified_env = {**os.environ, **added_env} |
| 134 | |
| 135 | cmd = "python app/main.py " |
| 136 | cmd += f"--setup-map {setup_map_json} " |
| 137 | cmd += f"--tasks-map {tasks_map_json} " |
| 138 | cmd += f"--output-dir {expr_dir} " |
| 139 | cmd += f"--task-list-file {task_list_file_path} " |
| 140 | cmd += f"--model {model} " |
| 141 | cmd += f"--model-temperature {temperature} " |
| 142 | cmd += f"--conv-round-limit {conv_round_limit} " |
| 143 | cmd += f"--num-processes {num_processes} " |
| 144 | if enbale_sbfl: |
| 145 | cmd += "--enable-sbfl " |
| 146 | if enable_layered: |
| 147 | cmd += "--enable-layered " |
| 148 | if enable_validation: |
| 149 | cmd += "--enable-validation " |
| 150 | if enable_angelic: |
| 151 | cmd += "--enable-angelic " |
| 152 | if enable_perfect_angelic: |
| 153 | cmd += "--enable-perfect-angelic " |
| 154 | if not print_more: |
| 155 | cmd += "--no-print " |
| 156 | |
| 157 | print(f"Running agent workflow with cmd: {cmd}") |
| 158 | with cd(root_dir): |
| 159 | _ = run_string_cmd_in_conda(cmd, "auto-code-rover", env=modified_env) |
| 160 | |
| 161 | print("Done with running agent workflow.") |
| 162 | swe_input_file = pjoin(expr_dir, "predictions_for_swebench.json") |
| 163 | return swe_input_file |
| 164 | |
| 165 | |
| 166 | def run_swe_bench_eval( |
| 167 | expr_id: str, swe_bench_dir: str, swe_input_file: str, eval_log_dir: str |
| 168 | ): |
| 169 | """ |
| 170 | Run SWE-bench evaluation. |
| 171 | Returns: |
| 172 | - The created log directory containing evaluation results. |
| 173 | """ |
| 174 | expr_eval_log_dir = pjoin(eval_log_dir, expr_id) |
| 175 | create_fresh_dir(expr_eval_log_dir) |
| 176 | temp_eval_test_bed_dir = pjoin(swe_bench_dir, "temp_eval_testbed", expr_id) |
| 177 | create_fresh_dir(temp_eval_test_bed_dir) |
| 178 | all_tasks_json = pjoin(swe_bench_dir, "data", "swe-bench.json") |
| 179 | |
| 180 | cmd = "python harness/run_evaluation.py " |
| 181 | cmd += f"--swe_bench_tasks {all_tasks_json} " |
| 182 | cmd += f"--predictions_path {swe_input_file} " |
| 183 | cmd += f"--log_dir {expr_eval_log_dir} " |
| 184 | cmd += f"--testbed {temp_eval_test_bed_dir} " |
| 185 | cmd += "--verbose " |
| 186 | |
| 187 | print(f"Running SWE-bench evaluation with cmd: {cmd}") |
| 188 | with cd(swe_bench_dir): |
| 189 | _ = run_string_cmd_in_conda(cmd, "swe-bench") |
| 190 | |
| 191 | print("Done with running SWE-bench evaluation.") |
| 192 | return expr_eval_log_dir |
| 193 | |
| 194 | |
| 195 | def create_separate_reports(expr_dir: str, combined_report_path: str): |
| 196 | script_dir = pdirname(os.path.realpath(__file__)) |
| 197 | root_dir = pdirname(script_dir) |
| 198 | devin_task_file = pjoin(root_dir, "processed_data_devin", "tasks.txt") |
| 199 | lite_task_file = pjoin(root_dir, "processed_data_lite", "test", "tasks.txt") |
| 200 | swe25_task_file = pjoin(root_dir, "processed_data_swe_25", "tasks.txt") |
| 201 | |
| 202 | def read_tasks_from_file(file): |
| 203 | with open(file) as f: |
| 204 | tasks = f.read().splitlines() |
| 205 | tasks = [t.strip().strip("\n") for t in tasks] |
| 206 | tasks = [t for t in tasks if t] |
| 207 | return tasks |
| 208 | |
| 209 | devin_tasks = read_tasks_from_file(devin_task_file) |
| 210 | lite_tasks = read_tasks_from_file(lite_task_file) |
| 211 | swe25_tasks = read_tasks_from_file(swe25_task_file) |
| 212 | |
| 213 | with open(combined_report_path) as f: |
| 214 | combined_report = json.load(f) |
| 215 | |
| 216 | combined_fixed = combined_report["resolved"] |
| 217 | |
| 218 | devin_fixed = [t for t in combined_fixed if t in devin_tasks] |
| 219 | lite_fixed = [t for t in combined_fixed if t in lite_tasks] |
| 220 | swe25_fixed = [t for t in combined_fixed if t in swe25_tasks] |
| 221 | |
| 222 | def write_separate_report(resolved_tasks, all_tasks, report_path): |
| 223 | report = dict() |
| 224 | report["resolved"] = resolved_tasks |
| 225 | report["total_num_tasks"] = len(all_tasks) |
| 226 | report["num_resolved"] = len(resolved_tasks) |
| 227 | # calculate in percentage, round to 4 decimal places |
| 228 | resolve_rate = round(100 * len(resolved_tasks) / len(all_tasks), 4) |
| 229 | report["resolve_rate"] = f"{resolve_rate} %" |
| 230 | with open(report_path, "w") as f: |
| 231 | json.dump(report, f, indent=4) |
| 232 | |
| 233 | write_separate_report( |
| 234 | devin_fixed, devin_tasks, pjoin(expr_dir, "final_report_devin_subset.json") |
| 235 | ) |
| 236 | write_separate_report( |
| 237 | lite_fixed, lite_tasks, pjoin(expr_dir, "final_report_lite_subset.json") |
| 238 | ) |
| 239 | write_separate_report( |
| 240 | swe25_fixed, swe25_tasks, pjoin(expr_dir, "final_report_swe_25_subset.json") |
| 241 | ) |
| 242 | |
| 243 | |
| 244 | def generate_report( |
| 245 | expr_dir: str, |
| 246 | swe_bench_dir: str, |
| 247 | swe_input_file: str, |
| 248 | expr_eval_log_dir: str, |
| 249 | model: str, |
| 250 | ): |
| 251 | """ |
| 252 | Generate a report for the experiment. |
| 253 | Returns: |
| 254 | - Path to the final report json file. |
| 255 | """ |
| 256 | all_tasks_json = pjoin(swe_bench_dir, "data", "swe-bench.json") |
| 257 | |
| 258 | final_report_path = pjoin(expr_dir, "final_report.json") |
| 259 | |
| 260 | cmd = "python metrics/report.py " |
| 261 | cmd += f"--task_file {all_tasks_json} " |
| 262 | cmd += f"--predictions {swe_input_file} " |
| 263 | cmd += f"--logs {expr_eval_log_dir} " |
| 264 | cmd += f"--model {model} " |
| 265 | cmd += f"--out {final_report_path} " |
| 266 | |
| 267 | print(f"Generating final report with cmd: {cmd}") |
| 268 | with cd(swe_bench_dir): |
| 269 | _ = run_string_cmd_in_conda(cmd, "swe-bench") |
| 270 | |
| 271 | print("Done with generating final report.") |
| 272 | return final_report_path |
| 273 | |
| 274 | |
| 275 | def generate_stats(expr_dir: str, eval_start_epoch: float, eval_end_epoch: float): |
| 276 | cost_files = glob(pjoin(expr_dir, "**", "*__*", "cost.json")) |
| 277 | cost_data = [json.loads(Path(file).read_text()) for file in cost_files] |
| 278 | |
| 279 | stats = {} |
| 280 | stats["num_tasks"] = len(cost_data) |
| 281 | |
| 282 | stats["model"] = cost_data[0]["model"] |
| 283 | stats["commit"] = cost_data[0]["commit"] |
| 284 | stats["input_cost_per_token"] = cost_data[0]["input_cost_per_token"] |
| 285 | stats["output_cost_per_token"] = cost_data[0]["output_cost_per_token"] |
| 286 | |
| 287 | total_cost = sum(x["total_cost"] for x in cost_data) |
| 288 | stats["total_cost"] = total_cost |
| 289 | stats["avg_cost"] = total_cost / len(cost_data) |
| 290 | |
| 291 | avg_input_tokens = mean(x["total_input_tokens"] for x in cost_data) |
| 292 | avg_output_tokens = mean(x["total_output_tokens"] for x in cost_data) |
| 293 | stats["avg_tokens"] = round(avg_input_tokens + avg_output_tokens, 1) |
| 294 | stats["avg_input_tokens"] = round(avg_input_tokens, 1) |
| 295 | stats["avg_output_tokens"] = round(avg_output_tokens, 1) |
| 296 | |
| 297 | inference_start_epoch = min(x["start_epoch"] for x in cost_data) |
| 298 | inference_end_epoch = max(x["end_epoch"] for x in cost_data) |
| 299 | inference_elapsed = inference_end_epoch - inference_start_epoch |
| 300 | stats["inference_start_epoch"] = inference_start_epoch |
| 301 | stats["inference_end_epoch"] = inference_end_epoch |
| 302 | stats["inference_elapsed_mins"] = round(inference_elapsed / 60, 2) |
| 303 | stats["inference_avg_elapsed_secs_parallel"] = round( |
| 304 | inference_elapsed / len(cost_data), 1 |
| 305 | ) |
| 306 | stats["inference_avg_elapsed_secs_serial"] = round( |
| 307 | mean(x["elapsed_seconds"] for x in cost_data), 1 |
| 308 | ) |
| 309 | |
| 310 | stats["eval_start_epoch"] = eval_start_epoch |
| 311 | stats["eval_end_epoch"] = eval_end_epoch |
| 312 | eval_elapsed = eval_end_epoch - eval_start_epoch |
| 313 | stats["eval_elapsed_mins"] = round(eval_elapsed / 60, 2) |
| 314 | stats["eval_avg_elapsed_secs"] = round(eval_elapsed / len(cost_data), 1) |
| 315 | |
| 316 | stats["total_elapsed_mins"] = round((inference_elapsed + eval_elapsed) / 60, 2) |
| 317 | |
| 318 | with open(pjoin(expr_dir, "stats.json"), "w") as f: |
| 319 | json.dump(stats, f, indent=4) |
| 320 | |
| 321 | |
| 322 | def main(): |
| 323 | global force_delete, running_combined |
| 324 | parser = argparse.ArgumentParser() |
| 325 | parser.add_argument("conf_file", help="Configuration file") |
| 326 | parser.add_argument( |
| 327 | "--eval-only", |
| 328 | action="store_true", |
| 329 | default=False, |
| 330 | help="Only do SWE-bench evaluation", |
| 331 | ) |
| 332 | parser.add_argument( |
| 333 | "-f", |
| 334 | "--force-delete", |
| 335 | action="store_true", |
| 336 | default=False, |
| 337 | help="Force delete existing data in experiment dir (if any)", |
| 338 | ) |
| 339 | parser.add_argument( |
| 340 | "-c", |
| 341 | "--combined", |
| 342 | action="store_true", |
| 343 | default=False, |
| 344 | help="Run combined Lite, Devin, SWE-25 experiment. Will generate seperate report file for each subset.", |
| 345 | ) |
| 346 | args = parser.parse_args() |
| 347 | |
| 348 | conf_file = args.conf_file |
| 349 | force_delete = args.force_delete |
| 350 | running_combined = args.combined |
| 351 | |
| 352 | # (1) Read configuration file |
| 353 | if not os.path.exists(conf_file): |
| 354 | raise FileNotFoundError(f"Configuration file {conf_file} not found") |
| 355 | config = configparser.ConfigParser() |
| 356 | |
| 357 | # TODO: use a single conf file for all experiments and use different sections |
| 358 | # for individual experiments |
| 359 | default_section = "DEFAULT" |
| 360 | with open(conf_file) as f: |
| 361 | config.read_string(f"[{default_section}]\n" + f.read()) |
| 362 | |
| 363 | config_dict = config["DEFAULT"] |
| 364 | expr_id = config_dict["id"] |
| 365 | overall_expr_dir = config_dict["experiment_dir"] |
| 366 | swe_bench_dir = config_dict["swe_bench_dir"] |
| 367 | setup_result_dir = config_dict["setup_result_dir"] |
| 368 | eval_log_dir = config_dict["eval_log_dir"] |
| 369 | |
| 370 | model = config_dict["model"] |
| 371 | temperature = float(config_dict["temperature"]) |
| 372 | selected_tasks_file = config_dict["selected_tasks_file"] |
| 373 | enable_sbfl = config.getboolean("DEFAULT", "enable_sbfl", fallback=False) |
| 374 | enable_layered = config.getboolean("DEFAULT", "enable_layered", fallback=False) |
| 375 | enable_validation = config.getboolean( |
| 376 | "DEFAULT", "enable_validation", fallback=False |
| 377 | ) |
| 378 | enable_angelic = config.getboolean("DEFAULT", "enable_angelic", fallback=False) |
| 379 | enable_perfect_angelic = config.getboolean( |
| 380 | "DEFAULT", "enable_perfect_angelic", fallback=False |
| 381 | ) |
| 382 | conv_round_limit = config.getint("DEFAULT", "conv_round_limit", fallback=15) |
| 383 | |
| 384 | # with_sbfl = config.getboolean("DEFAULT", "with_sbfl", fallback=False) |
| 385 | print_more = config.getboolean("DEFAULT", "print", fallback=False) |
| 386 | num_processes = int(config_dict["num_processes"]) |
| 387 | |
| 388 | expr_dir = pjoin(overall_expr_dir, expr_id) |
| 389 | task_list_file_path = pjoin(expr_dir, os.path.basename(selected_tasks_file)) |
| 390 | if not args.eval_only: |
| 391 | create_fresh_dir(expr_dir) |
| 392 | shutil.copy(selected_tasks_file, expr_dir) |
| 393 | |
| 394 | script_dir = pdirname(os.path.realpath(__file__)) |
| 395 | root_dir = pdirname(script_dir) # root of this repo |
| 396 | |
| 397 | if args.eval_only: |
| 398 | swe_input_file = pjoin(expr_dir, "predictions_for_swebench.json") |
| 399 | else: |
| 400 | swe_input_file = run_agent( |
| 401 | root_dir, |
| 402 | setup_result_dir, |
| 403 | expr_dir, |
| 404 | task_list_file_path, |
| 405 | model, |
| 406 | temperature, |
| 407 | enable_sbfl, |
| 408 | enable_layered, |
| 409 | enable_validation, |
| 410 | enable_angelic, |
| 411 | enable_perfect_angelic, |
| 412 | print_more, |
| 413 | conv_round_limit, |
| 414 | num_processes, |
| 415 | ) |
| 416 | |
| 417 | eval_start_time = datetime.now() |
| 418 | expr_eval_log_dir = run_swe_bench_eval( |
| 419 | expr_id, swe_bench_dir, swe_input_file, eval_log_dir |
| 420 | ) |
| 421 | eval_end_time = datetime.now() |
| 422 | |
| 423 | final_report_path = generate_report( |
| 424 | expr_dir, swe_bench_dir, swe_input_file, expr_eval_log_dir, model |
| 425 | ) |
| 426 | |
| 427 | generate_stats(expr_dir, eval_start_time.timestamp(), eval_end_time.timestamp()) |
| 428 | |
| 429 | print(f"Experiment {expr_id} done. Final report is at {final_report_path}.") |
| 430 | |
| 431 | if running_combined: |
| 432 | create_separate_reports(expr_dir, final_report_path) |
| 433 | print("Created separate reports for each subset.") |
| 434 | |
| 435 | |
| 436 | if __name__ == "__main__": |
| 437 | main() |