narcolepticchicken commited on
Commit
b40184a
·
verified ·
1 Parent(s): 427ee84

Upload benchmarks/benchmark_code.py

Browse files
Files changed (1) hide show
  1. benchmarks/benchmark_code.py +408 -0
benchmarks/benchmark_code.py ADDED
@@ -0,0 +1,408 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Benchmark 1: Code Compute Allocation
3
+
4
+ Compares:
5
+ A. baseline fixed compute
6
+ B. verifier-guided retries
7
+ C. OCC credit/resource allocation
8
+ D. OCC + oracle-aware allocation
9
+
10
+ Uses HumanEval / EvalPlus-style evaluation with simulated agents.
11
+ """
12
+
13
+ import json
14
+ import random
15
+ import time
16
+ from collections import defaultdict
17
+ from pathlib import Path
18
+ from typing import Any, Dict, List, Optional, Tuple
19
+
20
+ import numpy as np
21
+ from datasets import load_dataset
22
+
23
+ import sys
24
+ sys.path.insert(0, str(Path(__file__).parent.parent))
25
+ from oracle.oracle import ImpactOracle, OracleResult
26
+ from ledger.ledger import CreditLedger, LedgerEntry
27
+ from broker.broker import ResourceBroker, Decision
28
+ from rl.reward import RewardHook, OfflineComparator
29
+
30
+
31
+ class SimulatedCodeAgent:
32
+ """
33
+ Simulates a code generation agent with variable quality.
34
+ Quality parameter controls probability of generating a correct solution.
35
+ """
36
+
37
+ def __init__(
38
+ self,
39
+ agent_id: str,
40
+ quality: float = 0.3,
41
+ cost_per_attempt: float = 100.0,
42
+ verbose_padding_prob: float = 0.0,
43
+ gaming_mode: bool = False,
44
+ ):
45
+ self.agent_id = agent_id
46
+ self.quality = quality
47
+ self.cost_per_attempt = cost_per_attempt
48
+ self.verbose_padding_prob = verbose_padding_prob
49
+ self.gaming_mode = gaming_mode
50
+ self.attempts_made = 0
51
+ self.tokens_used = 0
52
+
53
+ def generate(self, problem: Dict, oracle: ImpactOracle, context: Dict) -> Dict:
54
+ """Generate a code attempt. Returns result dict for oracle scoring."""
55
+ self.attempts_made += 1
56
+ tokens = self.cost_per_attempt
57
+ if random.random() < self.verbose_padding_prob:
58
+ tokens *= 3.0 # verbose but low-value
59
+
60
+ self.tokens_used += tokens
61
+
62
+ # Simulate correctness
63
+ passed = random.random() < self.quality
64
+ hidden_passed = passed
65
+ if self.gaming_mode:
66
+ # Gaming: passes public tests but fails hidden tests sometimes
67
+ hidden_passed = random.random() < (self.quality * 0.5)
68
+
69
+ return {
70
+ "passed": passed,
71
+ "hidden_passed": hidden_passed,
72
+ "compute_cost": tokens,
73
+ "k": 1,
74
+ "passes": 1 if hidden_passed else 0,
75
+ "tokens_used": tokens,
76
+ }
77
+
78
+
79
+ class CodeBenchmark:
80
+ """
81
+ Run code compute allocation benchmark with multiple strategies.
82
+ """
83
+
84
+ def __init__(
85
+ self,
86
+ dataset_name: str = "openai/openai_humaneval",
87
+ split: str = "test",
88
+ max_problems: int = 50,
89
+ seed: int = 42,
90
+ ):
91
+ self.dataset_name = dataset_name
92
+ self.split = split
93
+ self.max_problems = max_problems
94
+ self.seed = seed
95
+ self.problems: List[Dict] = []
96
+ self.oracle = ImpactOracle(compute_budget=1e5)
97
+ self.ledger = CreditLedger(decay_lambda=0.05)
98
+ self.broker = ResourceBroker()
99
+
100
+ def load_data(self):
101
+ ds = load_dataset(self.dataset_name, split=self.split)
102
+ self.problems = [
103
+ {
104
+ "task_id": row["task_id"],
105
+ "prompt": row["prompt"],
106
+ "canonical_solution": row.get("canonical_solution", ""),
107
+ "entry_point": row["entry_point"],
108
+ "test": row.get("test", ""),
109
+ }
110
+ for row in ds.select(range(min(self.max_problems, len(ds))))
111
+ ]
112
+
113
+ def run_baseline_fixed(
114
+ self,
115
+ agents: List[SimulatedCodeAgent],
116
+ fixed_attempts: int = 3,
117
+ ) -> Dict:
118
+ """Baseline: each agent gets fixed number of attempts per problem."""
119
+ random.seed(self.seed)
120
+ np.random.seed(self.seed)
121
+
122
+ results = []
123
+ total_compute = 0.0
124
+
125
+ for problem in self.problems:
126
+ best_score = 0.0
127
+ best_hidden = False
128
+ attempts = 0
129
+
130
+ for agent in agents:
131
+ for _ in range(fixed_attempts):
132
+ result = agent.generate(problem, self.oracle, {})
133
+ oracle_res = self.oracle.score(
134
+ mode="code",
135
+ action={},
136
+ context={"previous_passed": best_hidden},
137
+ result=result,
138
+ agent_id=agent.agent_id,
139
+ )
140
+ best_score = max(best_score, oracle_res.raw_score)
141
+ best_hidden = best_hidden or result["hidden_passed"]
142
+ attempts += 1
143
+ total_compute += result["compute_cost"]
144
+
145
+ results.append({
146
+ "task_id": problem["task_id"],
147
+ "pass": best_hidden,
148
+ "raw_score": best_score,
149
+ "attempts": attempts,
150
+ })
151
+
152
+ return self._summarize(results, total_compute, "baseline_fixed")
153
+
154
+ def run_verifier_retries(
155
+ self,
156
+ agents: List[SimulatedCodeAgent],
157
+ max_attempts: int = 5,
158
+ verifier_budget: int = 2,
159
+ ) -> Dict:
160
+ """Verifier-guided: retry only if verifier (public test) says fail."""
161
+ random.seed(self.seed)
162
+ np.random.seed(self.seed)
163
+
164
+ results = []
165
+ total_compute = 0.0
166
+
167
+ for problem in self.problems:
168
+ best_score = 0.0
169
+ best_hidden = False
170
+ attempts = 0
171
+ verifier_calls = 0
172
+
173
+ for agent in agents:
174
+ for _ in range(max_attempts):
175
+ result = agent.generate(problem, self.oracle, {})
176
+ attempts += 1
177
+ total_compute += result["compute_cost"]
178
+
179
+ # Verifier: check public test pass
180
+ verifier_calls += 1
181
+ if result["passed"]:
182
+ # Only run hidden test if public passed
183
+ oracle_res = self.oracle.score(
184
+ mode="code",
185
+ action={},
186
+ context={"previous_passed": best_hidden},
187
+ result=result,
188
+ agent_id=agent.agent_id,
189
+ )
190
+ best_score = max(best_score, oracle_res.raw_score)
191
+ best_hidden = best_hidden or result["hidden_passed"]
192
+ break # stop retrying this agent
193
+
194
+ results.append({
195
+ "task_id": problem["task_id"],
196
+ "pass": best_hidden,
197
+ "raw_score": best_score,
198
+ "attempts": attempts,
199
+ "verifier_calls": verifier_calls,
200
+ })
201
+
202
+ return self._summarize(results, total_compute, "verifier_retries")
203
+
204
+ def run_occ_allocation(
205
+ self,
206
+ agents: List[SimulatedCodeAgent],
207
+ max_attempts: int = 5,
208
+ credit_threshold: float = 2.0,
209
+ ) -> Dict:
210
+ """OCC: allocate attempts based on agent credits and learned success rate.
211
+
212
+ Key differences from baseline:
213
+ - Track per-agent success rate across problems
214
+ - Prioritize high success-rate, low-cost agents
215
+ - Early stop on hidden pass
216
+ - Broker limits repeated attempts when marginal value is low
217
+ - Stop after any agent succeeds (no redundant expensive attempts)
218
+ """
219
+ random.seed(self.seed)
220
+ np.random.seed(self.seed)
221
+
222
+ results = []
223
+ total_compute = 0.0
224
+ ledger = CreditLedger(decay_lambda=0.05)
225
+ broker = ResourceBroker()
226
+
227
+ # Track per-agent historical success rate
228
+ agent_success: Dict[str, List[bool]] = {a.agent_id: [] for a in agents}
229
+
230
+ for problem in self.problems:
231
+ best_score = 0.0
232
+ best_hidden = False
233
+ attempts = 0
234
+
235
+ # Seed each agent with a small initial credit to allow at least one trial attempt
236
+ for agent in agents:
237
+ ledger.earn(
238
+ agent_id=agent.agent_id,
239
+ task_id=problem["task_id"],
240
+ action_id="seed",
241
+ amount=3.0,
242
+ oracle_score=0.0,
243
+ compute_cost=0.0,
244
+ reason="initial_trial_credit",
245
+ )
246
+
247
+ # Rank agents by estimated value = success_rate / cost
248
+ def agent_value(a):
249
+ history = agent_success.get(a.agent_id, [])
250
+ rate = sum(history) / max(1, len(history)) if history else 0.3
251
+ return rate / max(1.0, a.cost_per_attempt)
252
+
253
+ ranked_agents = sorted(agents, key=agent_value, reverse=True)
254
+
255
+ # Try ranked agents, escalate if they fail
256
+ for agent in ranked_agents:
257
+ # Check broker permission
258
+ balance = ledger.balance(agent.agent_id, "general", "global")
259
+ dec = broker.request(
260
+ "model_call_small",
261
+ agent.agent_id,
262
+ balance,
263
+ task_state={"progress": best_score, "urgency": 0.5},
264
+ )
265
+
266
+ if dec.decision == Decision.DENY:
267
+ continue
268
+
269
+ for attempt_idx in range(max_attempts):
270
+ result = agent.generate(problem, self.oracle, {})
271
+ attempts += 1
272
+ total_compute += result["compute_cost"]
273
+
274
+ oracle_res = self.oracle.score(
275
+ mode="code",
276
+ action={"tokens_used": result["tokens_used"]},
277
+ context={"previous_passed": best_hidden},
278
+ result=result,
279
+ agent_id=agent.agent_id,
280
+ )
281
+
282
+ # Earn credits for hidden pass
283
+ if oracle_res.raw_score >= 0.5:
284
+ ledger.earn(
285
+ agent_id=agent.agent_id,
286
+ task_id=problem["task_id"],
287
+ action_id=f"attempt_{attempt_idx}",
288
+ amount=oracle_res.reward_value * 5.0,
289
+ oracle_score=oracle_res.raw_score,
290
+ compute_cost=result["compute_cost"],
291
+ reason=oracle_res.reason,
292
+ )
293
+
294
+ best_score = max(best_score, oracle_res.raw_score)
295
+ best_hidden = best_hidden or result["hidden_passed"]
296
+ agent_success[agent.agent_id].append(result["hidden_passed"])
297
+
298
+ # Stop if we got a good solution
299
+ if result["hidden_passed"]:
300
+ break
301
+
302
+ # OCC-specific: after one failure, check if this agent's historical
303
+ # success rate is very low — if so, skip to next agent
304
+ history = agent_success[agent.agent_id]
305
+ if len(history) >= 3:
306
+ recent_rate = sum(history[-3:]) / 3.0
307
+ if recent_rate < 0.15 and attempt_idx >= 1:
308
+ break
309
+
310
+ # Check if broker allows another attempt
311
+ balance = ledger.balance(agent.agent_id, "general", "global")
312
+ dec = broker.request(
313
+ "model_call_small",
314
+ agent.agent_id,
315
+ balance,
316
+ task_state={"progress": best_score, "urgency": 0.5},
317
+ )
318
+ if dec.decision == Decision.DENY:
319
+ break
320
+
321
+ # If we already solved, skip remaining agents (crucial compute saving)
322
+ if best_hidden:
323
+ break
324
+
325
+ results.append({
326
+ "task_id": problem["task_id"],
327
+ "pass": best_hidden,
328
+ "raw_score": best_score,
329
+ "attempts": attempts,
330
+ })
331
+
332
+ return self._summarize(results, total_compute, "occ_allocation")
333
+
334
+ def _summarize(self, results: List[Dict], total_compute: float, label: str) -> Dict:
335
+ n = len(results)
336
+ passes = sum(1 for r in results if r["pass"])
337
+ total_attempts = sum(r["attempts"] for r in results)
338
+ mean_score = np.mean([r["raw_score"] for r in results])
339
+
340
+ return {
341
+ "label": label,
342
+ "n_problems": n,
343
+ "pass@1": passes / n if n else 0.0,
344
+ "mean_raw_score": float(mean_score),
345
+ "total_attempts": total_attempts,
346
+ "mean_attempts_per_problem": total_attempts / n if n else 0.0,
347
+ "total_compute": float(total_compute),
348
+ "compute_per_problem": float(total_compute / n) if n else 0.0,
349
+ "results": results,
350
+ }
351
+
352
+ def run_all(
353
+ self,
354
+ agents: Optional[List[SimulatedCodeAgent]] = None,
355
+ ) -> Dict[str, Dict]:
356
+ if not self.problems:
357
+ self.load_data()
358
+
359
+ if agents is None:
360
+ # Varied quality and cost to show compute allocation tradeoffs
361
+ agents = [
362
+ SimulatedCodeAgent("agent_A", quality=0.30, cost_per_attempt=80),
363
+ SimulatedCodeAgent("agent_B", quality=0.22, cost_per_attempt=60),
364
+ SimulatedCodeAgent("agent_C", quality=0.40, cost_per_attempt=120),
365
+ ]
366
+
367
+ return {
368
+ "baseline_fixed": self.run_baseline_fixed(agents, fixed_attempts=3),
369
+ "verifier_retries": self.run_verifier_retries(agents, max_attempts=5),
370
+ "occ_allocation": self.run_occ_allocation(agents, max_attempts=5),
371
+ }
372
+
373
+
374
+ def main():
375
+ bench = CodeBenchmark(max_problems=50, seed=42)
376
+ bench.load_data()
377
+ results = bench.run_all()
378
+
379
+ print("=" * 60)
380
+ print("CODE COMPUTE ALLOCATION BENCHMARK")
381
+ print("=" * 60)
382
+ for label, res in results.items():
383
+ print(f"\n{label}")
384
+ print(f" pass@1: {res['pass@1']:.3f}")
385
+ print(f" mean attempts/problem: {res['mean_attempts_per_problem']:.2f}")
386
+ print(f" total compute: {res['total_compute']:.0f}")
387
+ print(f" compute/problem: {res['compute_per_problem']:.0f}")
388
+
389
+ # Compute savings at iso-accuracy
390
+ baseline_pass = results["baseline_fixed"]["pass@1"]
391
+ baseline_compute = results["baseline_fixed"]["total_compute"]
392
+
393
+ for label in ["verifier_retries", "occ_allocation"]:
394
+ r = results[label]
395
+ if r["pass@1"] >= baseline_pass:
396
+ savings = 1.0 - (r["total_compute"] / baseline_compute)
397
+ print(f"\n {label}: {savings*100:.1f}% compute saved at >= baseline pass@1")
398
+ else:
399
+ print(f"\n {label}: accuracy below baseline ({r['pass@1']:.3f} < {baseline_pass:.3f})")
400
+
401
+ Path("/app/occ/reports").mkdir(parents=True, exist_ok=True)
402
+ with open("/app/occ/reports/benchmark_code_results.json", "w") as f:
403
+ json.dump(results, f, indent=2, default=str)
404
+ print("\nSaved to reports/benchmark_code_results.json")
405
+
406
+
407
+ if __name__ == "__main__":
408
+ main()