|
| 1 | +"""Docker-based evaluation harness for SWE-bench.""" |
| 2 | + |
| 3 | +import json |
| 4 | +import logging |
| 5 | +import os |
| 6 | +import subprocess |
| 7 | +import tempfile |
| 8 | +from pathlib import Path |
| 9 | +from typing import Dict, List, Optional |
| 10 | + |
| 11 | +logger = logging.getLogger(__name__) |
| 12 | + |
| 13 | +class SWEBenchEvaluator: |
| 14 | + """Evaluator for running SWE-bench in Docker containers.""" |
| 15 | + |
| 16 | + def __init__(self, max_workers: int = 4, working_dir: Optional[Path] = None): |
| 17 | + """Initialize evaluator. |
| 18 | +
|
| 19 | + Args: |
| 20 | + max_workers: Number of parallel workers |
| 21 | + working_dir: Working directory for evaluation files |
| 22 | + """ |
| 23 | + self.max_workers = max_workers |
| 24 | + self.working_dir = working_dir or Path(tempfile.mkdtemp(prefix='swebench_')) |
| 25 | + self.working_dir.mkdir(parents=True, exist_ok=True) |
| 26 | + |
| 27 | + def evaluate_instances( |
| 28 | + self, |
| 29 | + instances: List[Dict], |
| 30 | + run_id: Optional[str] = None |
| 31 | + ) -> Dict: |
| 32 | + """Evaluate benchmark instances. |
| 33 | +
|
| 34 | + Args: |
| 35 | + instances: List of benchmark instances to evaluate |
| 36 | + run_id: Optional identifier for this evaluation run |
| 37 | +
|
| 38 | + Returns: |
| 39 | + Dictionary containing evaluation results |
| 40 | + """ |
| 41 | + results = {} |
| 42 | + run_dir = self.working_dir / (run_id or 'default') |
| 43 | + run_dir.mkdir(parents=True, exist_ok=True) |
| 44 | + |
| 45 | + # Save predictions for batch evaluation |
| 46 | + predictions_dir = run_dir / 'predictions' |
| 47 | + predictions_dir.mkdir(parents=True, exist_ok=True) |
| 48 | + |
| 49 | + for instance in instances: |
| 50 | + try: |
| 51 | + # Save instance prediction |
| 52 | + instance_dir = predictions_dir / instance['instance_id'] |
| 53 | + instance_dir.mkdir(parents=True, exist_ok=True) |
| 54 | + with open(instance_dir / 'prediction.json', 'w') as f: |
| 55 | + json.dump(instance, f, indent=2) |
| 56 | + except Exception as e: |
| 57 | + logger.error(f"Error preparing {instance['instance_id']}: {e}") |
| 58 | + results[instance['instance_id']] = { |
| 59 | + 'status': 'error', |
| 60 | + 'error': f"Failed to prepare instance: {str(e)}" |
| 61 | + } |
| 62 | + |
| 63 | + # Run batch evaluation using SWE-bench harness |
| 64 | + try: |
| 65 | + result = self._run_docker_evaluation(predictions_dir, run_id) |
| 66 | + results.update(self._parse_evaluation_results(result)) |
| 67 | + except Exception as e: |
| 68 | + logger.error(f"Docker evaluation failed: {e}") |
| 69 | + for instance in instances: |
| 70 | + if instance['instance_id'] not in results: |
| 71 | + results[instance['instance_id']] = { |
| 72 | + 'status': 'error', |
| 73 | + 'error': f"Docker evaluation failed: {str(e)}" |
| 74 | + } |
| 75 | + |
| 76 | + return results |
| 77 | + |
| 78 | + def _run_docker_evaluation(self, predictions_dir: Path, run_id: str) -> str: |
| 79 | + """Run Docker-based evaluation using SWE-bench harness. |
| 80 | +
|
| 81 | + Args: |
| 82 | + predictions_dir: Directory containing instance predictions |
| 83 | + run_id: Identifier for this evaluation run |
| 84 | +
|
| 85 | + Returns: |
| 86 | + Raw evaluation output |
| 87 | + """ |
| 88 | + cmd = [ |
| 89 | + 'python', '-m', 'swebench.harness.run_evaluation', |
| 90 | + '--predictions_path', str(predictions_dir), |
| 91 | + '--max_workers', str(self.max_workers), |
| 92 | + '--run_id', run_id or 'default' |
| 93 | + ] |
| 94 | + |
| 95 | + try: |
| 96 | + result = subprocess.run( |
| 97 | + cmd, |
| 98 | + capture_output=True, |
| 99 | + text=True, |
| 100 | + check=True |
| 101 | + ) |
| 102 | + return result.stdout |
| 103 | + except subprocess.CalledProcessError as e: |
| 104 | + logger.error(f"Docker evaluation command failed: {e.output}") |
| 105 | + raise RuntimeError(f"Docker evaluation failed: {str(e)}") |
| 106 | + |
| 107 | + def _parse_evaluation_results(self, output: str) -> Dict: |
| 108 | + """Parse evaluation output to extract metrics. |
| 109 | +
|
| 110 | + Args: |
| 111 | + output: Raw evaluation output string |
| 112 | +
|
| 113 | + Returns: |
| 114 | + Dictionary containing parsed metrics per instance |
| 115 | + """ |
| 116 | + results = {} |
| 117 | + try: |
| 118 | + # Extract results from evaluation output |
| 119 | + # Format: instance_id: {metrics} |
| 120 | + for line in output.splitlines(): |
| 121 | + if ':' in line: |
| 122 | + instance_id, metrics_str = line.split(':', 1) |
| 123 | + instance_id = instance_id.strip() |
| 124 | + try: |
| 125 | + metrics = json.loads(metrics_str.strip()) |
| 126 | + results[instance_id] = { |
| 127 | + 'status': 'success', |
| 128 | + 'metrics': metrics |
| 129 | + } |
| 130 | + except json.JSONDecodeError: |
| 131 | + results[instance_id] = { |
| 132 | + 'status': 'error', |
| 133 | + 'error': f"Failed to parse metrics: {metrics_str}" |
| 134 | + } |
| 135 | + except Exception as e: |
| 136 | + logger.error(f"Failed to parse evaluation results: {e}") |
| 137 | + raise RuntimeError(f"Failed to parse evaluation results: {str(e)}") |
| 138 | + |
| 139 | + return results |
0 commit comments