narcolepticchicken commited on
Commit
ee396fa
Β·
verified Β·
1 Parent(s): f654d83

Upload training/router_integration_benchmark.py with huggingface_hub

Browse files
training/router_integration_benchmark.py ADDED
@@ -0,0 +1,237 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Standalone integration: Replace heuristic router with trained XGBoost router.
4
+
5
+ This script:
6
+ 1. Generates 2K eval traces (same as standalone_eval_v2.py)
7
+ 2. Runs the full benchmark with the TRAINED router replacing _route_learned()
8
+ 3. Compares: heuristic, trained, and oracle routers
9
+ """
10
+
11
+ import json, os, sys, random, uuid, pickle
12
+ import numpy as np
13
+ from datetime import datetime, timedelta
14
+ from dataclasses import dataclass, field
15
+ from enum import Enum
16
+ from collections import defaultdict
17
+ from typing import Dict, List, Optional, Any
18
+
19
+ # ─── Load trained models ─────────────────────────────────────────────
20
+ print("="*80)
21
+ print("ACO TRAINED ROUTER - INTEGRATION BENCHMARK")
22
+ print("="*80)
23
+
24
+ import xgboost as xgb
25
+
26
+ MODEL_DIR = "/app/router_models"
27
+ feat_keys = json.load(open(f"{MODEL_DIR}/feat_keys.json"))
28
+ tier_config = json.load(open(f"{MODEL_DIR}/tier_config.json"))
29
+ TIER_COST = {int(k):v for k,v in tier_config["tier_cost"].items()}
30
+ TIER_STR = {int(k):v for k,v in tier_config["tier_str"].items()}
31
+ TASK_FLOOR = tier_config["task_floor"]
32
+
33
+ print(f"\n[1] Loading trained router models...")
34
+ tier_clfs = {}
35
+ for tier in range(1, 6):
36
+ clf = xgb.XGBClassifier()
37
+ clf.load_model(f"{MODEL_DIR}/tier_{tier}_success.json")
38
+ tier_clfs[tier] = clf
39
+ print(f" Loaded tier_{tier}_success.json")
40
+
41
+ # ─── Feature extraction (must match training) ────────────────────────
42
+ TASK_TYPES = ["quick_answer","coding","research","document_drafting",
43
+ "legal_regulated","tool_heavy","retrieval_heavy",
44
+ "long_horizon","unknown_ambiguous"]
45
+ TT2IDX = {t:i for i,t in enumerate(TASK_TYPES)}
46
+
47
+ CODE_KW = ["python","javascript","code","function","bug","debug","refactor",
48
+ "implement","test","compile","runtime","class","module","async","thread"]
49
+ LEGAL_KW = ["contract","legal","compliance","gdpr","privacy","policy","regulatory","liability"]
50
+ RESEARCH_KW = ["research","find sources","literature","investigate","compare","analyze","survey"]
51
+ TOOL_KW = ["search","fetch","retrieve","query","api","database","scrape","aggregate"]
52
+ LONG_KW = ["plan","project","roadmap","orchestrate","multi-step","migrate","pipeline","deploy"]
53
+ MATH_KW = ["calculate","compute","solve","equation","formula","optimize","probability"]
54
+
55
+ def extract_features(request, task_type, difficulty=3):
56
+ r = request.lower()
57
+ f = {"req_len": len(request), "num_words": len(request.split()),
58
+ "has_code": int(any(k in r for k in CODE_KW)),
59
+ "n_code": sum(1 for k in CODE_KW if k in r),
60
+ "has_legal": int(any(k in r for k in LEGAL_KW)),
61
+ "n_legal": sum(1 for k in LEGAL_KW if k in r),
62
+ "has_research": int(any(k in r for k in RESEARCH_KW)),
63
+ "n_research": sum(1 for k in RESEARCH_KW if k in r),
64
+ "has_tool": int(any(k in r for k in TOOL_KW)),
65
+ "n_tool": sum(1 for k in TOOL_KW if k in r),
66
+ "has_long": int(any(k in r for k in LONG_KW)),
67
+ "has_math": int(any(k in r for k in MATH_KW)),
68
+ "tt_idx": TT2IDX.get(task_type, 8), "difficulty": difficulty}
69
+ for tt in TASK_TYPES:
70
+ f[f"tt_{tt}"] = int(task_type == tt)
71
+ return f
72
+
73
+ def f2v(feats):
74
+ return np.array([float(feats.get(k, 0.0)) for k in feat_keys], dtype=np.float32)
75
+
76
+ # ─── Routing Functions ────────────────────────────────────────────────
77
+ def route_trained(request, task_type, difficulty):
78
+ """Trained router: per-tier P(success) + safety floor + asymmetric cost."""
79
+ feats = extract_features(request, task_type, difficulty)
80
+ x = f2v(feats).reshape(1, -1)
81
+ floor = TASK_FLOOR.get(task_type, 2)
82
+
83
+ best_tier = floor; best_score = float("inf")
84
+ for tier in range(floor, 6):
85
+ p_success = tier_clfs[tier].predict_proba(x)[0, 1]
86
+ p_fail = 1.0 - p_success
87
+ cost_norm = TIER_COST[tier] / TIER_COST[5]
88
+ score = p_fail * 5.0 + cost_norm * 1.0 # asymmetric: 5x underkill penalty
89
+ if score < best_score:
90
+ best_score = score; best_tier = tier
91
+ return best_tier
92
+
93
+ def route_heuristic(task_type, difficulty):
94
+ """Original heuristic router: difficulty + 1."""
95
+ return min(difficulty + 1, 5)
96
+
97
+ def route_frontier():
98
+ return 4
99
+
100
+ def route_cascade_trained(request, task_type, difficulty):
101
+ """Cascade: start at floor, escalate if P(success) < threshold."""
102
+ feats = extract_features(request, task_type, difficulty)
103
+ x = f2v(feats).reshape(1, -1)
104
+ floor = TASK_FLOOR.get(task_type, 2)
105
+
106
+ for tier in range(floor, 6):
107
+ p_success = tier_clfs[tier].predict_proba(x)[0, 1]
108
+ if p_success >= 0.65:
109
+ return tier
110
+ return 4 # fallback to frontier
111
+
112
+ # ─── Generate Evaluation Traces ────────────────────────────────────────
113
+ print("\n[2] Generating 2K evaluation traces (different seed from training)...")
114
+
115
+ class TaskType(Enum):
116
+ QUICK_ANSWER="quick_answer"; CODING="coding"; RESEARCH="research"
117
+ DOCUMENT_DRAFTING="document_drafting"; LEGAL_REGULATED="legal_regulated"
118
+ TOOL_HEAVY="tool_heavy"; RETRIEVAL_HEAVY="retrieval_heavy"
119
+ LONG_HORIZON="long_horizon"; UNKNOWN_AMBIGUOUS="unknown_ambiguous"
120
+
121
+ TASK_TEMPLATES_EVAL = {
122
+ "quick_answer":["What is the capital of France?","Explain quantum computing briefly.","What is 237*452?"],
123
+ "coding":["Write a Python function to reverse a linked list.","Fix the bug in this React component.",
124
+ "Implement LRU cache in Go.","Debug segfault in C++ thread pool."],
125
+ "research":["Research latest transformer advances.","Find sources comparing LoRA and full FT.",
126
+ "Investigate data center climate impact."],
127
+ "document_drafting":["Draft project proposal for ML pipeline.","Write email to team about deployment."],
128
+ "legal_regulated":["Review this contract for liability clauses.","Check GDPR compliance for data pipeline.",
129
+ "Draft privacy policy section."],
130
+ "tool_heavy":["Search open issues and create summary.","Fetch API docs and generate client code."],
131
+ "retrieval_heavy":["Answer based on 50-page document.","Find all payment processing mentions."],
132
+ "long_horizon":["Plan 3-month roadmap.","Orchestrate multi-region deployment."],
133
+ "unknown_ambiguous":["Help me with this thing.","I need something about the server."],
134
+ }
135
+
136
+ def tsp(tier, diff):
137
+ s = {1:0.35,2:0.55,3:0.80,4:0.93,5:0.97}[tier]
138
+ return s ** (diff * 0.6)
139
+
140
+ eval_rng = random.Random(999) # DIFFERENT seed for eval
141
+ eval_traces = []
142
+ for i in range(2000):
143
+ tt = eval_rng.choice(list(TASK_TEMPLATES_EVAL.keys()))
144
+ diff = {"quick_answer":1,"document_drafting":2,"tool_heavy":2,"retrieval_heavy":2,
145
+ "research":3,"coding":3,"unknown_ambiguous":3,"long_horizon":4,"legal_regulated":5}[tt]
146
+ tier_out = {t: eval_rng.random() < tsp(t, diff) for t in range(1,6)}
147
+ opt = 5
148
+ for t in range(1,6):
149
+ if tier_out[t]: opt = t; break
150
+ req = eval_rng.choice(TASK_TEMPLATES_EVAL[tt])
151
+ eval_traces.append({"tt":tt,"diff":diff,"opt":opt,"tier_out":tier_out,"req":req})
152
+
153
+ print(f" Generated {len(eval_traces)} eval traces")
154
+
155
+ # ─── Evaluate All Routers ─────────────────────────────────────────────
156
+ print("\n[3] Evaluating all routers on 2K traces...")
157
+
158
+ def eval_router(name, route_fn):
159
+ succ = 0; cost = 0.0; unsafe = 0; fd = 0
160
+ td = defaultdict(int)
161
+ for t in eval_traces:
162
+ pred = route_fn(t)
163
+ td[pred] += 1
164
+ if t["tier_out"].get(pred, False):
165
+ succ += 1
166
+ elif pred < t["opt"]:
167
+ unsafe += 1
168
+ else:
169
+ fd += 1
170
+ cost += TIER_COST[pred]
171
+ n = len(eval_traces)
172
+ return {"success":succ/n, "avg_cost":cost/n, "unsafe_rate":unsafe/n,
173
+ "false_done":fd/n, "tier_dist":dict(td)}
174
+
175
+ routers = {
176
+ "always_frontier": lambda t: 4,
177
+ "always_cheap": lambda t: 1,
178
+ "heuristic_diff+1": lambda t: min(t["diff"]+1, 5),
179
+ "heuristic_floor": lambda t: TASK_FLOOR.get(t["tt"], 2),
180
+ "trained_asymmetric": lambda t: route_trained(t["req"], t["tt"], t["diff"]),
181
+ "trained_cascade_t0.65": lambda t: route_cascade_trained(t["req"], t["tt"], t["diff"]),
182
+ "oracle": lambda t: t["opt"],
183
+ }
184
+
185
+ results = {}
186
+ for name, fn in routers.items():
187
+ results[name] = eval_router(name, fn)
188
+ r = results[name]
189
+ fc = results["always_frontier"]["avg_cost"]
190
+ cr = (1 - r["avg_cost"]/fc)*100
191
+ print(f" {name:<25} success={r['success']:.3f} cost={r['avg_cost']:.4f} costRed={cr:.1f}% unsafe={r['unsafe_rate']:.3f}")
192
+
193
+ # ─── Per-Task-Type Breakdown ──────────────────────────────────────────
194
+ print("\n\n[4] Per-task-type breakdown (trained vs heuristic vs frontier)...")
195
+ for tt in sorted(set(t["tt"] for t in eval_traces)):
196
+ tt_traces = [t for t in eval_traces if t["tt"] == tt]
197
+ n_tt = len(tt_traces)
198
+ if n_tt == 0: continue
199
+
200
+ for rname, rfn in [("frontier", lambda t:4),
201
+ ("heuristic", lambda t:min(t["diff"]+1,5)),
202
+ ("trained", lambda t:route_trained(t["req"],t["tt"],t["diff"]))]:
203
+ succ = sum(1 for t in tt_traces if t["tier_out"].get(rfn(t), False))
204
+ cost = sum(TIER_COST[rfn(t)] for t in tt_traces)
205
+ sr = succ/n_tt; ac = cost/n_tt
206
+ if rname == "frontier":
207
+ print(f"\n {tt} (n={n_tt}):")
208
+ print(f" {rname:<12} success={sr:.3f} cost={ac:.4f}")
209
+
210
+ # ─── Final Comparison ─────────────────────────────────────────────────
211
+ print(f"\n\n{'='*80}")
212
+ print("FINAL INTEGRATION BENCHMARK")
213
+ print(f"{'='*80}")
214
+ print(f"\n{'Router':<25} {'Success':>10} {'AvgCost':>10} {'CostRed':>10} {'Unsafe':>10} {'F-DONE':>10}")
215
+ print("-"*75)
216
+ fc = results["always_frontier"]["avg_cost"]
217
+ for name, r in sorted(results.items(), key=lambda x: (-x[1]["success"], x[1]["avg_cost"])):
218
+ cr = (1 - r["avg_cost"]/fc)*100
219
+ print(f"{name:<25} {r['success']:>10.3f} {r['avg_cost']:>10.4f} {cr:>9.1f}% {r['unsafe_rate']:>10.3f} {r['false_done']:>10.3f}")
220
+
221
+ # Quality/cost frontier
222
+ print("\nPARETO FRONTIER:")
223
+ pareto = []
224
+ for name, r in results.items():
225
+ if name == "always_cheap": continue
226
+ dominated = False
227
+ for name2, r2 in results.items():
228
+ if name == name2: continue
229
+ if r2["success"] >= r["success"] and r2["avg_cost"] <= r["avg_cost"]:
230
+ if r2["success"] > r["success"] or r2["avg_cost"] < r["avg_cost"]:
231
+ dominated = True; break
232
+ if not dominated:
233
+ pareto.append((name, r))
234
+ cr = (1 - r["avg_cost"]/fc)*100
235
+ print(f" {name:<25} success={r['success']:.3f} cost={r['avg_cost']:.4f} costRed={cr:.1f}%")
236
+
237
+ print(f"\n\nDONE!")