narcolepticchicken commited on
Commit
71a9c04
·
verified ·
1 Parent(s): 52d908d

Upload jobs/run_ablations_detailed_v2.py

Browse files
Files changed (1) hide show
  1. jobs/run_ablations_detailed_v2.py +446 -0
jobs/run_ablations_detailed_v2.py ADDED
@@ -0,0 +1,446 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Self-contained ablation runner with meaningful variation — V2.
3
+ Fixes: Added _score_qa, _score_debate, transfer() to inline classes.
4
+ """
5
+ import json
6
+ import random
7
+ import time
8
+ from dataclasses import dataclass, field
9
+ from enum import Enum
10
+ from pathlib import Path
11
+ from typing import Any, Dict, List, Optional
12
+
13
+ import numpy as np
14
+
15
+
16
+ # --- CORE ---
17
+
18
+ @dataclass
19
+ class OracleResult:
20
+ raw_score: float; cost_adjusted_score: float; confidence: float
21
+ evidence: Dict[str, Any]; reason: str
22
+ failure_tags: List[str] = field(default_factory=list)
23
+ reward_value: float = 0.0
24
+
25
+
26
+ class ImpactOracle:
27
+ def __init__(self, compute_penalty_rate=0.0001, calibration_weight=0.2,
28
+ abstention_bonus=1.0, hallucination_penalty=2.0,
29
+ confident_wrong_penalty=3.0, gaming_penalty=2.0):
30
+ self.compute_penalty_rate = compute_penalty_rate
31
+ self.calibration_weight = calibration_weight
32
+ self.abstention_bonus = abstention_bonus
33
+ self.hallucination_penalty = hallucination_penalty
34
+ self.confident_wrong_penalty = confident_wrong_penalty
35
+ self.gaming_penalty = gaming_penalty
36
+
37
+ def score(self, mode, action, context, result, agent_id=""):
38
+ if mode == "code":
39
+ return self._score_code(action, context, result, agent_id)
40
+ elif mode == "retrieval_qa":
41
+ return self._score_qa(action, context, result, agent_id)
42
+ elif mode == "debate":
43
+ return self._score_debate(action, context, result, agent_id)
44
+ return OracleResult(0.0, 0.0, 0.0, {}, f"unknown mode {mode}", ["unknown_mode"])
45
+
46
+ def _score_code(self, action, context, result, agent_id):
47
+ correctness = result.get("correctness", 0.0)
48
+ compute_cost = result.get("compute_cost", 0.0)
49
+ hidden_pass = result.get("hidden_tests_pass", correctness)
50
+ public_pass = result.get("public_pass", correctness)
51
+ tags = []
52
+ if public_pass and not hidden_pass:
53
+ tags.append("gaming_hidden_tests")
54
+ raw = correctness * 1.0 - compute_cost * self.compute_penalty_rate
55
+ if "gaming_hidden_tests" in tags:
56
+ raw -= self.gaming_penalty
57
+ cost_adj = raw - compute_cost * self.compute_penalty_rate
58
+ return OracleResult(raw, cost_adj, result.get("confidence", correctness),
59
+ {"correctness": correctness}, f"corr={correctness:.2f}, cost={compute_cost}", tags, cost_adj)
60
+
61
+ def _score_qa(self, action, context, result, agent_id):
62
+ gold = context.get("gold_answer", "")
63
+ answer = result.get("answer", "")
64
+ confidence = result.get("confidence", 0.5)
65
+ compute_cost = result.get("compute_cost", 0.0)
66
+ abstained = action.get("abstained", False)
67
+ if abstained:
68
+ correct_abstention = context.get("is_unanswerable", False)
69
+ raw = self.abstention_bonus if correct_abstention else -self.abstention_bonus
70
+ tags = ["correct_abstention" if correct_abstention else "wrong_abstention"]
71
+ return OracleResult(raw, raw - compute_cost * self.compute_penalty_rate, confidence, {}, f"abstain correct={correct_abstention}", tags, raw)
72
+ correctness = self._fuzzy_match(answer, gold)
73
+ evidence = result.get("evidence", {})
74
+ entailment = evidence.get("entailment_score", 0.0)
75
+ contradiction = evidence.get("contradiction_score", 0.0)
76
+ hallucination = contradiction > 0.5
77
+ confident_wrong = confidence > 0.8 and correctness < 0.5
78
+ tags = []
79
+ if hallucination: tags.append("hallucination")
80
+ if confident_wrong: tags.append("confident_wrong")
81
+ if compute_cost > 2000: tags.append("excessive_compute")
82
+ if compute_cost > 500 and correctness < 0.5: tags.append("compute_waste")
83
+ raw = (correctness * 1.0 + entailment * 0.5 -
84
+ (self.hallucination_penalty if hallucination else 0.0) -
85
+ (self.confident_wrong_penalty if confident_wrong else 0.0) -
86
+ compute_cost * self.compute_penalty_rate)
87
+ brier = (confidence - correctness) ** 2
88
+ raw += (1 - brier) * self.calibration_weight
89
+ cost_adj = raw - compute_cost * self.compute_penalty_rate
90
+ if compute_cost > 100 and raw < 0.5:
91
+ cost_adj -= self.gaming_penalty * 0.5
92
+ return OracleResult(raw, cost_adj, confidence, evidence, f"corr={correctness:.2f}, conf={confidence:.2f}", tags, cost_adj)
93
+
94
+ def _score_debate(self, action, context, result, agent_id):
95
+ decision_quality = result.get("decision_quality", 0.0)
96
+ marginal = result.get("marginal_contribution", 0.0)
97
+ tokens = result.get("tokens", 0)
98
+ compute_cost = result.get("compute_cost", tokens)
99
+ spam = result.get("spam", False)
100
+ collusion = result.get("collusion", False)
101
+ tags = []
102
+ if spam: tags.append("spam")
103
+ if collusion: tags.append("collusion")
104
+ if tokens > 5000: tags.append("verbose_waste")
105
+ raw = (decision_quality * 1.0 + marginal * 0.5 +
106
+ (1.0 / max(tokens, 1)) * 0.5 - compute_cost * self.compute_penalty_rate)
107
+ if spam: raw -= self.gaming_penalty
108
+ if collusion: raw -= self.gaming_penalty * 2
109
+ cost_adj = raw - compute_cost * self.compute_penalty_rate
110
+ return OracleResult(raw, cost_adj, result.get("confidence", 0.5),
111
+ {"marginal": marginal}, f"dq={decision_quality:.2f}, tokens={tokens}", tags, cost_adj)
112
+
113
+ def _fuzzy_match(self, a, b):
114
+ if not a or not b: return 0.0
115
+ a, b = a.strip().lower(), b.strip().lower()
116
+ return 1.0 if a == b else 0.5 if (a in b or b in a) else 0.0
117
+
118
+
119
+ @dataclass
120
+ class LedgerEntry:
121
+ agent_id: str; task_id: str; action_id: str; earned_credit: float; spent_credit: float
122
+ decayed_credit: float; remaining_credit: float; reason: str; oracle_score: float
123
+ compute_cost: float; timestamp: float; capability_scope: str = "global"
124
+
125
+
126
+ class CreditLedger:
127
+ def __init__(self, decay_lambda=0.05):
128
+ self.entries = []; self.balances = {}; self.decay_lambda = decay_lambda
129
+
130
+ def earn(self, agent_id, task_id, action_id, amount, oracle_score, compute_cost, reason, capability_scope="global"):
131
+ now = time.time()
132
+ self._apply_decay(agent_id, now, capability_scope)
133
+ current = self._get(agent_id, capability_scope)
134
+ new_bal = current + amount
135
+ self.entries.append(LedgerEntry(agent_id, task_id, action_id, amount, 0.0, 0.0, new_bal, reason, oracle_score, compute_cost, now, capability_scope))
136
+ self._set(agent_id, capability_scope, new_bal)
137
+
138
+ def spend(self, agent_id, task_id, action_id, amount, capability_scope="global", reason="spend"):
139
+ now = time.time()
140
+ self._apply_decay(agent_id, now, capability_scope)
141
+ current = self._get(agent_id, capability_scope)
142
+ if current < amount: return False
143
+ new_bal = current - amount
144
+ self.entries.append(LedgerEntry(agent_id, task_id, action_id, 0.0, amount, 0.0, new_bal, reason, 0.0, 0.0, now, capability_scope))
145
+ self._set(agent_id, capability_scope, new_bal)
146
+ return True
147
+
148
+ def transfer(self, from_agent, to_agent, amount, capability_scope="global"):
149
+ return False # non-transferable
150
+
151
+ def balance(self, agent_id, capability_scope="global"):
152
+ now = time.time()
153
+ self._apply_decay(agent_id, now, capability_scope)
154
+ return self._get(agent_id, capability_scope)
155
+
156
+ def _get(self, agent_id, cap): return self.balances.get(agent_id, {}).get(cap, 0.0)
157
+ def _set(self, agent_id, cap, val):
158
+ if agent_id not in self.balances: self.balances[agent_id] = {}
159
+ self.balances[agent_id][cap] = val
160
+ def _apply_decay(self, agent_id, now, cap):
161
+ current = self._get(agent_id, cap)
162
+ if current <= 0: return
163
+ decayed = current * (1 - self.decay_lambda)
164
+ if decayed < current:
165
+ self.entries.append(LedgerEntry(agent_id, "decay", "decay", 0.0, 0.0, current - decayed, decayed, "credit_decay", 0.0, 0.0, now, cap))
166
+ self._set(agent_id, cap, decayed)
167
+
168
+ def detect_collusion(self, window=10):
169
+ recent = self.entries[-window:]
170
+ agents = set(e.agent_id for e in recent)
171
+ if len(agents) < 2: return None
172
+ return {"suspicious_agents": list(agents), "count": len(recent)}
173
+
174
+
175
+ class Decision(Enum):
176
+ ALLOW = "allow"; DENY = "deny"; REQUIRE_APPROVAL = "require_approval"
177
+ DOWNGRADE = "downgrade"; ESCALATE = "escalate"; ASK_JUSTIFICATION = "ask_justification"
178
+
179
+
180
+ @dataclass
181
+ class ResourceDecision:
182
+ decision: Decision; reason: str; capability: str; downgrade_to: Optional[str] = None
183
+
184
+
185
+ class ResourceBroker:
186
+ RESOURCE_RISK = {"model_call": "medium", "retrieval_call": "low", "verifier_call": "medium",
187
+ "debate_turn": "low", "file_write": "high", "shell_execute": "high",
188
+ "memory_write": "medium", "human_escalation": "high", "larger_model": "medium"}
189
+ DEFAULT_THRESHOLDS = {"low": 0.5, "medium": 2.0, "high": 5.0}
190
+
191
+ def __init__(self, thresholds=None, urgency_boost=0.5):
192
+ self.thresholds = thresholds or self.DEFAULT_THRESHOLDS.copy()
193
+ self.urgency_boost = urgency_boost
194
+ self.denial_history = {}
195
+
196
+ def request(self, capability, agent_id, credit_balance, task_state=None, risk_score=0.0, gaming_flags=None):
197
+ task_state = task_state or {}; gaming_flags = gaming_flags or []
198
+ risk_class = self.RESOURCE_RISK.get(capability, "medium")
199
+ threshold = self.thresholds.get(risk_class, 2.0)
200
+ urgency = task_state.get("urgency", 0.0)
201
+ adjusted = max(0.1, threshold - urgency * self.urgency_boost)
202
+ if gaming_flags: return ResourceDecision(Decision.DENY, f"Gaming: {gaming_flags}", capability)
203
+ if risk_class == "high" and risk_score > 0.7: return ResourceDecision(Decision.REQUIRE_APPROVAL, f"High risk {risk_score:.2f}", capability)
204
+ if credit_balance >= adjusted: return ResourceDecision(Decision.ALLOW, f"Balance {credit_balance:.2f} >= {adjusted:.2f}", capability)
205
+ if credit_balance >= adjusted * 0.5:
206
+ if risk_class == "medium": return ResourceDecision(Decision.DOWNGRADE, f"Downgrading from {capability}", capability, "retrieval_call")
207
+ return ResourceDecision(Decision.ASK_JUSTIFICATION, f"Justification required", capability)
208
+ denials = self.denial_history.get(agent_id, 0)
209
+ if denials > 3: return ResourceDecision(Decision.ESCALATE, f"Denied {denials} times", capability)
210
+ self.denial_history[agent_id] = denials + 1
211
+ return ResourceDecision(Decision.DENY, f"Balance {credit_balance:.2f} < {adjusted:.2f}", capability)
212
+
213
+
214
+ # --- CODE BENCHMARK WITH THRESHOLD-DEPENDENT SELECTION ---
215
+
216
+ @dataclass
217
+ class CodeProblem:
218
+ task_id: str; difficulty: float; hidden_test_difficulty: float
219
+
220
+
221
+ class SimCodeAgent:
222
+ def __init__(self, agent_id, pass_easy, pass_hard, hidden_falloff, cost):
223
+ self.agent_id = agent_id
224
+ self.pass_easy = pass_easy
225
+ self.pass_hard = pass_hard
226
+ self.hidden_falloff = hidden_falloff
227
+ self.cost = cost
228
+ self.attempts = 0
229
+
230
+ def solve(self, problem):
231
+ self.attempts += 1
232
+ base = self.pass_easy * (1 - problem.difficulty) + self.pass_hard * problem.difficulty
233
+ public = random.random() < base
234
+ hidden_acc = max(0.0, base - self.hidden_falloff * problem.hidden_test_difficulty)
235
+ hidden = random.random() < hidden_acc
236
+ return {"public_pass": public, "hidden_pass": hidden, "compute_cost": self.cost}
237
+
238
+
239
+ def gen_problems(n, seed):
240
+ random.seed(seed); np.random.seed(seed)
241
+ return [CodeProblem(f"task_{i}", random.random(), random.random()) for i in range(n)]
242
+
243
+
244
+ def run_code_occ(problems, agents, oracle, ledger, broker, max_attempts=3):
245
+ total = 0; results = []
246
+ for a in agents:
247
+ q = (a.pass_easy + a.pass_hard) / 2
248
+ ledger.earn(a.agent_id, "seed", "seed", q * 20, 0.0, 0.0, "initial", "model_call")
249
+
250
+ for p in problems:
251
+ solved = False; cost = 0; used = []
252
+ ranked = sorted(agents, key=lambda a: a.cost / max(0.1, (a.pass_easy + a.pass_hard) / 2))
253
+ for agent in ranked:
254
+ if solved or len(used) >= max_attempts: break
255
+ balance = ledger.balance(agent.agent_id, "model_call")
256
+ dec = broker.request("model_call", agent.agent_id, balance,
257
+ task_state={"urgency": 0.3 if not solved else 0.0, "attempts": len(used)})
258
+ if dec.decision == Decision.DENY:
259
+ used.append(f"{agent.agent_id}_DENIED")
260
+ continue
261
+ r = agent.solve(p); cost += r["compute_cost"]; total += r["compute_cost"]; used.append(agent.agent_id)
262
+ solved = r["public_pass"]; hidden = r["hidden_pass"]
263
+ ora = oracle.score("code", {"attempt": len([u for u in used if not u.endswith("_DENIED")])}, {},
264
+ {"correctness": 1.0 if solved else 0.0, "pass_at_k": 1.0 if hidden else 0.0,
265
+ "compute_cost": cost, "public_pass": solved, "hidden_tests_pass": hidden},
266
+ agent_id=agent.agent_id)
267
+ if ora.raw_score > 0:
268
+ ledger.earn(agent.agent_id, p.task_id, "solve", ora.raw_score * 5, ora.raw_score, cost, "pass", "model_call")
269
+ else:
270
+ ledger.spend(agent.agent_id, p.task_id, "solve", 1.0, "model_call", "fail")
271
+ if hidden: break
272
+ results.append({"solved": solved, "cost": cost, "agents": used})
273
+ acc = sum(1 for r in results if r["solved"]) / len(results)
274
+ return {"accuracy": acc, "total_compute": total, "mean_compute": total / len(problems),
275
+ "mean_agents": sum(len(r["agents"]) for r in results) / len(results),
276
+ "denied_count": sum(1 for r in results for u in r["agents"] if u.endswith("_DENIED"))}
277
+
278
+
279
+ def run_qa_occ(dataset, oracle, ledger, broker, agent_acc=0.85):
280
+ total_compute = 0; correct = 0; attempted = 0
281
+ ledger.earn("qa_agent", "seed", "seed", 20, 0.0, 0.0, "initial", "retrieval_call")
282
+ for item in dataset:
283
+ balance = ledger.balance("qa_agent", "retrieval_call")
284
+ dec = broker.request("retrieval_call", "qa_agent", balance, task_state={"urgency": 0.5})
285
+ if dec.decision == Decision.DENY:
286
+ continue
287
+ tokens = 200 if dec.decision == Decision.ALLOW else 100
288
+ total_compute += tokens; attempted += 1
289
+ should_answer = item["type"] != "unanswerable"
290
+ ans = item["answer"] if (should_answer and random.random() < agent_acc) else None
291
+ conf = 0.9 if ans else 0.3
292
+ ora = oracle.score("retrieval_qa", {"abstained": ans is None}, item,
293
+ {"answer": ans, "confidence": conf, "evidence": {}, "compute_cost": tokens}, "qa_agent")
294
+ if ora.raw_score > 0:
295
+ ledger.earn("qa_agent", item["id"], "ans", ora.raw_score * 3, ora.raw_score, tokens, "correct", "retrieval_call")
296
+ correct += 1
297
+ else:
298
+ ledger.spend("qa_agent", item["id"], "ans", 0.5, "retrieval_call", "wrong")
299
+ return {"accuracy": correct / len(dataset), "attempted": attempted, "correct": correct,
300
+ "total_compute": total_compute, "mean_compute": total_compute / len(dataset)}
301
+
302
+
303
+ def create_qa_dataset(seed=42, n=50):
304
+ random.seed(seed)
305
+ evidence_pool = ["alpha", "beta", "gamma", "delta"]
306
+ return [{"id": f"q_{i}", "question": f"Q{i}", "type": random.choice(["answerable", "unanswerable", "misleading", "incomplete", "conflicting"]),
307
+ "answer": random.choice(["paris", "42", "yes", "no", "tokyo"]), "evidence": random.sample(evidence_pool, k=random.randint(1, 3)),
308
+ "gold_answer": random.choice(["paris", "42", "yes", "no", "tokyo"]), "is_unanswerable": False} for i in range(n)]
309
+
310
+
311
+ def run_debate_occ(n_debates, n_agents, agent_configs, oracle, ledger, broker, seed=42):
312
+ random.seed(seed); correct = 0; total_compute = 0; consensus = 0
313
+ for _ in range(n_debates):
314
+ truth = random.choice(["A", "B", "C"])
315
+ agents = []
316
+ for cfg in agent_configs:
317
+ acc = cfg["acc"] if cfg["honest"] else random.random() * 0.4
318
+ agents.append({"honest": cfg["honest"], "acc": acc, "id": cfg["id"], "tokens": cfg.get("tokens", 200)})
319
+ votes = []
320
+ for a in agents:
321
+ balance = ledger.balance(a["id"], "debate_turn")
322
+ dec = broker.request("debate_turn", a["id"], balance)
323
+ if dec.decision == Decision.DENY: continue
324
+ total_compute += a["tokens"]
325
+ vote = truth if (a["honest"] and random.random() < a["acc"]) else random.choice(["A", "B", "C"])
326
+ votes.append((a["id"], vote, a["honest"], a["acc"]))
327
+ ledger.spend(a["id"], "debate", "turn", 1.0, "debate_turn", "participate")
328
+ if not votes: continue
329
+ honest_votes = [v for _, v, h, _ in votes if h]
330
+ final = max(set([v for _, v, _, _ in votes]), key=lambda x: sum(1 for _, v, _, _ in votes if v == x))
331
+ if final == truth: correct += 1
332
+ if len(set(v for _, v, _, _ in votes)) == 1: consensus += 1
333
+ n = n_debates
334
+ return {"accuracy": correct / n, "consensus_reached": consensus / n, "total_compute": total_compute, "mean_compute": total_compute / n}
335
+
336
+
337
+ # --- ABLATIONS ---
338
+
339
+ ABLATIONS = [
340
+ ("default", "Full OCC", 0.02, 2.0, 0.0001, True, {}),
341
+ ("no_decay", "No credit decay", 0.0, 2.0, 0.0001, True, {}),
342
+ ("fast_decay", "Aggressive decay", 0.1, 2.0, 0.0001, True, {}),
343
+ ("no_gaming_penalty", "No gaming penalties", 0.02, 0.0, 0.0001, True, {}),
344
+ ("high_gaming_penalty", "Severe gaming penalties", 0.02, 5.0, 0.0001, True, {}),
345
+ ("lenient_broker", "Lenient broker (thresholds x0.5)", 0.02, 2.0, 0.0001, True, {"low": 0.25, "medium": 1.0, "high": 2.5}),
346
+ ("strict_broker", "Strict broker (thresholds x2.0)", 0.02, 2.0, 0.0001, True, {"low": 1.0, "medium": 4.0, "high": 10.0}),
347
+ ("high_compute_cost", "High compute penalty (x10)", 0.02, 2.0, 0.001, True, {}),
348
+ ("low_compute_cost", "Low compute penalty (x0.1)", 0.02, 2.0, 0.00001, True, {}),
349
+ ("anti_gaming_off", "Anti-gaming disabled", 0.02, 2.0, 0.0001, False, {}),
350
+ ]
351
+
352
+
353
+ def run_all():
354
+ print("=" * 60)
355
+ print("OCC ABLATION RUNNER (DETAILED V2)")
356
+ print("=" * 60)
357
+ seed = 42; n_problems = 200; n_qa = 100; n_debates = 50
358
+ results = {"ablations": {}, "anti_gaming": {}}
359
+
360
+ for name, desc, decay, game_pen, comp_pen, anti_on, broker_thresh in ABLATIONS:
361
+ print(f"\n--- ABLATION: {name} ---")
362
+ oracle = ImpactOracle(compute_penalty_rate=comp_pen, gaming_penalty=game_pen if anti_on else 0.0)
363
+ ledger = CreditLedger(decay_lambda=decay)
364
+ broker = ResourceBroker(thresholds=broker_thresh if broker_thresh else None)
365
+
366
+ problems = gen_problems(n_problems, seed)
367
+ cheap = SimCodeAgent("cheap", 0.65, 0.15, 0.20, 60)
368
+ medium = SimCodeAgent("medium", 0.85, 0.35, 0.15, 150)
369
+ expensive = SimCodeAgent("expensive", 0.95, 0.65, 0.10, 350)
370
+ code_res = run_code_occ(problems, [cheap, medium, expensive], oracle, ledger, broker, max_attempts=3)
371
+ print(f" Code: acc={code_res['accuracy']:.3f}, compute={code_res['total_compute']:.0f}, denied={code_res['denied_count']}")
372
+
373
+ qa_data = create_qa_dataset(seed=seed, n=n_qa)
374
+ qa_res = run_qa_occ(qa_data, oracle, ledger, broker, agent_acc=0.85)
375
+ print(f" QA: acc={qa_res['accuracy']:.3f} ({qa_res['correct']}/{qa_res['attempted']}), compute={qa_res['total_compute']:.0f}")
376
+
377
+ ledger2 = CreditLedger(decay_lambda=decay)
378
+ broker2 = ResourceBroker(thresholds=broker_thresh if broker_thresh else None)
379
+ for i in range(3):
380
+ ledger2.earn(f"f{i}", "seed", "seed", 5, 0, 0, "initial", "debate_turn")
381
+ debate_res = run_debate_occ(n_debates, 3,
382
+ [{"id": f"f{i}", "honest": True, "acc": 0.9, "tokens": 200} for i in range(3)],
383
+ oracle, ledger2, broker2, seed=seed)
384
+ print(f" Debate: acc={debate_res['accuracy']:.3f}, compute={debate_res['total_compute']:.0f}")
385
+
386
+ results["ablations"][name] = {"description": desc, "code": code_res, "qa": qa_res, "debate": debate_res}
387
+
388
+ # Anti-gaming
389
+ print("\n--- ANTI-GAMING TESTS ---")
390
+ oracle = ImpactOracle(gaming_penalty=2.0)
391
+ normal_res = []; gamer_res = []
392
+ for _ in range(50):
393
+ public = random.random() < 0.9
394
+ hidden = random.random() < 0.5
395
+ ora_normal = oracle.score("code", {}, {}, {"correctness": 1.0 if public else 0.0, "pass_at_k": 1.0 if hidden else 0.0, "compute_cost": 150, "public_pass": public, "hidden_tests_pass": hidden})
396
+ normal_res.append(ora_normal.raw_score)
397
+ ora_gamer = oracle.score("code", {}, {}, {"correctness": 1.0, "pass_at_k": 0.0, "compute_cost": 100, "public_pass": True, "hidden_tests_pass": False})
398
+ gamer_res.append(ora_gamer.raw_score)
399
+ results["anti_gaming"]["hidden_test_gaming"] = {
400
+ "normal_mean_raw": sum(normal_res) / len(normal_res),
401
+ "gamer_mean_raw": sum(gamer_res) / len(gamer_res),
402
+ "gamer_penalized_rate": sum(1 for r in gamer_res if r < 0) / len(gamer_res),
403
+ }
404
+ print(f" Hidden-test: normal={results['anti_gaming']['hidden_test_gaming']['normal_mean_raw']:.2f}, gamer={results['anti_gaming']['hidden_test_gaming']['gamer_mean_raw']:.2f}")
405
+
406
+ ledger = CreditLedger()
407
+ ledger.earn("alice", "seed", "seed", 10, 0, 0, "initial")
408
+ ok = ledger.transfer("alice", "bob", 5.0)
409
+ results["anti_gaming"]["collusion"] = {"transfer_allowed": ok, "alice_balance": ledger.balance("alice"), "blocked": not ok}
410
+ print(f" Collusion: transfer_allowed={ok}, blocked={not ok}")
411
+
412
+ oracle = ImpactOracle()
413
+ abstention_rewards = []
414
+ for _ in range(10):
415
+ res = oracle.score("retrieval_qa", {"abstained": True}, {"is_unanswerable": False, "gold_answer": "yes"},
416
+ {"answer": None, "confidence": 0.9, "evidence": {}, "compute_cost": 50})
417
+ abstention_rewards.append(res.reward_value)
418
+ results["anti_gaming"]["abstention"] = {"mean_reward": sum(abstention_rewards) / len(abstention_rewards), "negative": sum(abstention_rewards) < 0}
419
+ print(f" Abstention: mean_reward={results['anti_gaming']['abstention']['mean_reward']:.2f}")
420
+
421
+ oracle = ImpactOracle()
422
+ spam_res = oracle.score("retrieval_qa", {}, {"gold_answer": "paris"},
423
+ {"answer": "london", "confidence": 0.1, "evidence": {}, "compute_cost": 5000})
424
+ results["anti_gaming"]["spam"] = {"reward": spam_res.reward_value, "tags": spam_res.failure_tags}
425
+ print(f" Spam: reward={spam_res.reward_value:.2f}, tags={spam_res.failure_tags}")
426
+
427
+ # Save
428
+ out = Path("/app/occ/reports")
429
+ out.mkdir(parents=True, exist_ok=True)
430
+ with open(out / "ablations_detailed_v2.json", "w") as f:
431
+ json.dump(results, f, indent=2, default=str)
432
+
433
+ print("\n" + "=" * 60)
434
+ print("ABLATION SUMMARY")
435
+ print("=" * 60)
436
+ print(f"{'Name':<22} {'Code Acc':>9} {'Code Comp':>10} {'Denied':>8} {'QA Acc':>9} {'QA Comp':>10} {'Deb Acc':>9} {'Deb Comp':>10}")
437
+ for name, data in results["ablations"].items():
438
+ print(f"{name:<22} {data['code']['accuracy']:>9.3f} {data['code']['total_compute']:>10.0f} "
439
+ f"{data['code']['denied_count']:>8} {data['qa']['accuracy']:>9.3f} {data['qa']['total_compute']:>10.0f} "
440
+ f"{data['debate']['accuracy']:>9.3f} {data['debate']['total_compute']:>10.0f}")
441
+ print(f"\nSaved to {out / 'ablations_detailed_v2.json'}")
442
+ return results
443
+
444
+
445
+ if __name__ == "__main__":
446
+ run_all()