VD10 commited on
Commit
42c4979
·
verified ·
1 Parent(s): 37896ae

Upload batch_run.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. batch_run.py +294 -0
batch_run.py ADDED
@@ -0,0 +1,294 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """PatchJudge batch evaluation runner.
3
+
4
+ Judges 150 patches (mix of test-passing and test-failing from 2 agents)
5
+ plus 50 known-bad patches, then runs full validation.
6
+ """
7
+
8
+ import json
9
+ import logging
10
+ import os
11
+ import sys
12
+ import time
13
+ import statistics
14
+ from pathlib import Path
15
+ from collections import defaultdict
16
+
17
+ logging.basicConfig(
18
+ level=logging.INFO,
19
+ format="%(asctime)s [%(levelname)s] %(message)s",
20
+ )
21
+ logger = logging.getLogger("patchjudge-batch")
22
+
23
+
24
+ def main():
25
+ from patchjudge.data_loader import SWEBenchLoader
26
+ from patchjudge.feature_extractor import FeatureExtractor, extract_features_batch
27
+ from patchjudge.judge import PatchJudge
28
+ from patchjudge.validation import (
29
+ KnownBadPatchGenerator, PatchJudgeValidator, run_full_validation,
30
+ )
31
+ from patchjudge.models import PatchExample
32
+
33
+ data_dir = Path("data")
34
+ data_dir.mkdir(exist_ok=True)
35
+
36
+ # =========================================================================
37
+ # Step 1: Load data
38
+ # =========================================================================
39
+ print("=" * 70)
40
+ print(" STEP 1: Loading Data")
41
+ print("=" * 70)
42
+
43
+ loader = SWEBenchLoader(cache_dir="data")
44
+ gold = loader.load_gold_data()
45
+ examples = loader.build_dataset(sources=["coderforge", "o1"])
46
+
47
+ passed_examples = [e for e in examples if e.test_passed]
48
+ failed_examples = [e for e in examples if not e.test_passed]
49
+
50
+ print(f"\nTotal examples: {len(examples)}")
51
+ print(f" Passed: {len(passed_examples)}")
52
+ print(f" Failed: {len(failed_examples)}")
53
+
54
+ # Select examples for judging: diverse mix
55
+ # Take 50 passed from CoderForge, 50 passed from O1, 30 failed from each
56
+ coderforge_passed = [e for e in passed_examples if e.agent_name == "CoderForge-Qwen3-32B"][:50]
57
+ o1_passed = [e for e in passed_examples if e.agent_name == "OpenHands-O1-reasoning-high"][:50]
58
+ coderforge_failed = [e for e in failed_examples if e.agent_name == "CoderForge-Qwen3-32B"][:30]
59
+ o1_failed = [e for e in failed_examples if e.agent_name == "OpenHands-O1-reasoning-high"][:30]
60
+
61
+ judge_examples = coderforge_passed + o1_passed + coderforge_failed + o1_failed
62
+ print(f"\nSelected {len(judge_examples)} examples for judging:")
63
+ print(f" CoderForge passed: {len(coderforge_passed)}")
64
+ print(f" O1 passed: {len(o1_passed)}")
65
+ print(f" CoderForge failed: {len(coderforge_failed)}")
66
+ print(f" O1 failed: {len(o1_failed)}")
67
+
68
+ # =========================================================================
69
+ # Step 2: Extract features
70
+ # =========================================================================
71
+ print("\n" + "=" * 70)
72
+ print(" STEP 2: Feature Extraction")
73
+ print("=" * 70)
74
+
75
+ feat_results = extract_features_batch(judge_examples, show_progress=True)
76
+ features_list = [f for _, f in feat_results]
77
+
78
+ # Feature stats
79
+ bool_features = [
80
+ 'has_error_handling', 'has_edge_case_handling', 'has_todos',
81
+ 'has_hardcoded_values', 'has_debug_statements',
82
+ ]
83
+ for feat_name in bool_features:
84
+ count = sum(1 for f in features_list if getattr(f, feat_name))
85
+ print(f" {feat_name:>30}: {count}/{len(features_list)} ({count/len(features_list):.1%})")
86
+
87
+ # =========================================================================
88
+ # Step 3: LLM Judging
89
+ # =========================================================================
90
+ print("\n" + "=" * 70)
91
+ print(" STEP 3: LLM Judge Evaluation")
92
+ print("=" * 70)
93
+
94
+ model_id = "Qwen/Qwen2.5-Coder-32B-Instruct"
95
+ print(f"\nModel: {model_id}")
96
+
97
+ judge = PatchJudge(
98
+ model_id=model_id,
99
+ temperature=0.1,
100
+ max_tokens=2000,
101
+ max_retries=3,
102
+ )
103
+
104
+ start_time = time.time()
105
+ results = []
106
+
107
+ for i, (ex, feat) in enumerate(zip(judge_examples, features_list)):
108
+ print(f"\n [{i+1}/{len(judge_examples)}] {ex.instance_id} ({ex.agent_name})")
109
+ print(f" Test: {'PASS' if ex.test_passed else 'FAIL'}, "
110
+ f"Files: {feat.num_files_changed}, "
111
+ f"Lines: +{feat.num_lines_added}/-{feat.num_lines_removed}")
112
+
113
+ try:
114
+ result = judge.judge(ex, feat)
115
+ results.append(result)
116
+
117
+ print(f" MergeScore: {result.merge_score:.1f}/100")
118
+ for dim in ["correctness", "completeness", "code_quality",
119
+ "non_regression_risk", "merge_readiness"]:
120
+ score = result.dimension_scores.get(dim, {}).get("score", "?")
121
+ print(f" {dim}: {score}/10")
122
+
123
+ except Exception as e:
124
+ logger.error(f" ERROR: {e}")
125
+ from patchjudge.models import JudgeResult
126
+ results.append(JudgeResult(
127
+ merge_score=0.0,
128
+ dimension_scores={
129
+ dim: {"score": 0, "reasoning": f"Error: {str(e)}", "flags": ["ERROR"]}
130
+ for dim in judge.DIMENSIONS
131
+ },
132
+ raw_output=f"ERROR: {str(e)}",
133
+ model_used=model_id,
134
+ ))
135
+
136
+ # Rate limiting
137
+ time.sleep(0.3)
138
+
139
+ # Periodic save
140
+ if (i + 1) % 10 == 0:
141
+ _save_results(data_dir, judge_examples[:i+1], results)
142
+ elapsed = time.time() - start_time
143
+ rate = (i + 1) / elapsed * 60
144
+ remaining = (len(judge_examples) - i - 1) / (rate / 60)
145
+ print(f"\n --- Progress: {i+1}/{len(judge_examples)} | "
146
+ f"{rate:.1f}/min | ETA: {remaining:.0f}s ---")
147
+
148
+ elapsed = time.time() - start_time
149
+ print(f"\n\nJudging complete: {len(results)} patches in {elapsed:.0f}s "
150
+ f"({elapsed/len(results):.1f}s avg)")
151
+
152
+ # Final save
153
+ _save_results(data_dir, judge_examples, results)
154
+
155
+ # =========================================================================
156
+ # Step 4: Known-Bad Patches
157
+ # =========================================================================
158
+ print("\n" + "=" * 70)
159
+ print(" STEP 4: Known-Bad Patch Detection")
160
+ print("=" * 70)
161
+
162
+ gold_list = list(gold.values())[:30]
163
+ bad_patches = KnownBadPatchGenerator.generate_all(gold_list)
164
+
165
+ # Judge subset of known-bad patches (up to 50)
166
+ bad_to_judge = bad_patches[:50]
167
+ print(f"\nJudging {len(bad_to_judge)} known-bad patches...")
168
+
169
+ bad_features = [FeatureExtractor().extract(bp) for bp in bad_to_judge]
170
+ bad_results = []
171
+
172
+ for i, (bp, bf) in enumerate(zip(bad_to_judge, bad_features)):
173
+ print(f" [{i+1}/{len(bad_to_judge)}] {bp.agent_name}: {bp.instance_id}")
174
+ try:
175
+ result = judge.judge(bp, bf)
176
+ bad_results.append(result)
177
+ print(f" MergeScore: {result.merge_score:.1f}/100")
178
+ except Exception as e:
179
+ logger.error(f" ERROR: {e}")
180
+ from patchjudge.models import JudgeResult
181
+ bad_results.append(JudgeResult(
182
+ merge_score=0.0,
183
+ dimension_scores={
184
+ dim: {"score": 0, "reasoning": f"Error: {str(e)}", "flags": ["ERROR"]}
185
+ for dim in judge.DIMENSIONS
186
+ },
187
+ model_used=model_id,
188
+ ))
189
+ time.sleep(0.3)
190
+
191
+ known_bad_pairs = list(zip(bad_to_judge, bad_results))
192
+
193
+ # Save known-bad results
194
+ with open(data_dir / "known_bad_results.jsonl", 'w') as f:
195
+ for bp, br in known_bad_pairs:
196
+ f.write(json.dumps({
197
+ "instance_id": bp.instance_id,
198
+ "agent_name": bp.agent_name,
199
+ "merge_score": br.merge_score,
200
+ "dimension_scores": br.dimension_scores,
201
+ }) + "\n")
202
+
203
+ # =========================================================================
204
+ # Step 5: Full Validation
205
+ # =========================================================================
206
+ print("\n" + "=" * 70)
207
+ print(" STEP 5: Validation Report")
208
+ print("=" * 70)
209
+
210
+ validator = PatchJudgeValidator()
211
+ vr = validator.validate(judge_examples, results, known_bad_pairs)
212
+ report = validator.print_report(vr, judge_examples, results)
213
+
214
+ print(report)
215
+
216
+ # Save validation
217
+ with open(data_dir / "validation_results.json", 'w') as f:
218
+ json.dump(vr.to_dict(), f, indent=2)
219
+
220
+ with open(data_dir / "validation_report.txt", 'w') as f:
221
+ f.write(report)
222
+
223
+ # =========================================================================
224
+ # Step 6: Summary statistics
225
+ # =========================================================================
226
+ print("\n" + "=" * 70)
227
+ print(" FINAL SUMMARY")
228
+ print("=" * 70)
229
+
230
+ scores = [r.merge_score for r in results]
231
+ passed_scores = [r.merge_score for ex, r in zip(judge_examples, results) if ex.test_passed]
232
+ failed_scores = [r.merge_score for ex, r in zip(judge_examples, results) if not ex.test_passed]
233
+
234
+ print(f"\nAll patches ({len(scores)}):")
235
+ print(f" Mean MergeScore: {statistics.mean(scores):.1f}")
236
+ print(f" Median: {statistics.median(scores):.1f}")
237
+ print(f" Std: {statistics.stdev(scores):.1f}")
238
+
239
+ if passed_scores:
240
+ print(f"\nTest-passing patches ({len(passed_scores)}):")
241
+ print(f" Mean: {statistics.mean(passed_scores):.1f}")
242
+ print(f" Below 50: {sum(1 for s in passed_scores if s < 50)}/{len(passed_scores)} "
243
+ f"({sum(1 for s in passed_scores if s < 50)/len(passed_scores):.1%})")
244
+
245
+ if failed_scores:
246
+ print(f"\nTest-failing patches ({len(failed_scores)}):")
247
+ print(f" Mean: {statistics.mean(failed_scores):.1f}")
248
+ print(f" Below 50: {sum(1 for s in failed_scores if s < 50)}/{len(failed_scores)} "
249
+ f"({sum(1 for s in failed_scores if s < 50)/len(failed_scores):.1%})")
250
+
251
+ # Per-agent comparison
252
+ print(f"\nPer-agent scores:")
253
+ agent_scores = defaultdict(list)
254
+ for ex, r in zip(judge_examples, results):
255
+ agent_scores[ex.agent_name].append(r.merge_score)
256
+ for agent, scores_a in sorted(agent_scores.items()):
257
+ print(f" {agent}: mean={statistics.mean(scores_a):.1f}, "
258
+ f"median={statistics.median(scores_a):.1f}")
259
+
260
+ # Known-bad summary
261
+ if bad_results:
262
+ bad_scores = [r.merge_score for r in bad_results]
263
+ print(f"\nKnown-bad patches ({len(bad_scores)}):")
264
+ print(f" Mean: {statistics.mean(bad_scores):.1f}")
265
+ print(f" Below 50: {sum(1 for s in bad_scores if s < 50)}/{len(bad_scores)} "
266
+ f"({sum(1 for s in bad_scores if s < 50)/len(bad_scores):.1%})")
267
+
268
+ bad_agent_scores = defaultdict(list)
269
+ for bp, br in known_bad_pairs:
270
+ bad_agent_scores[bp.agent_name].append(br.merge_score)
271
+ for agent, scores_b in sorted(bad_agent_scores.items()):
272
+ print(f" {agent}: mean={statistics.mean(scores_b):.1f}")
273
+
274
+ print("\n✅ PatchJudge batch evaluation complete!")
275
+ print(f" Results saved to: {data_dir}/")
276
+
277
+
278
+ def _save_results(data_dir, examples, results):
279
+ """Save intermediate results."""
280
+ path = data_dir / "judge_results.jsonl"
281
+ with open(path, 'w') as f:
282
+ for ex, r in zip(examples, results):
283
+ f.write(json.dumps({
284
+ "instance_id": ex.instance_id,
285
+ "agent_name": ex.agent_name,
286
+ "test_passed": ex.test_passed,
287
+ "merge_score": r.merge_score,
288
+ "dimension_scores": r.dimension_scores,
289
+ "model_used": r.model_used,
290
+ }) + "\n")
291
+
292
+
293
+ if __name__ == "__main__":
294
+ main()